gerege-cli 0.26.6 → 0.26.8

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 (247) hide show
  1. package/bundled/gerege-video/SKILL.md +22 -0
  2. package/bundled/gerege-video/scripts/video.js +137 -0
  3. package/chunks/{MaxSizedBox-QCIXIS4P.js → MaxSizedBox-LUINLOQW.js} +1 -1
  4. package/chunks/{StandaloneSessionPicker-BAFAIRT7.js → StandaloneSessionPicker-B7N4QO5D.js} +1 -1
  5. package/chunks/{acp-subagent-executor-TPVXURLW.js → acp-subagent-executor-J6H6FKUT.js} +1 -1
  6. package/chunks/{acpAgent-67UN66PB.js → acpAgent-XG6SM2VU.js} +3 -3
  7. package/chunks/{advisor-SAXMI4QZ.js → advisor-SZVPQNPA.js} +1 -1
  8. package/chunks/{agent-KV7BXY6C.js → agent-N7QF7BJS.js} +1 -1
  9. package/chunks/{agent-headless-FQX3JGG6.js → agent-headless-GLP5GUEX.js} +1 -1
  10. package/chunks/{agent-host-client-L5EHC4AC.js → agent-host-client-H4VOB3M6.js} +1 -1
  11. package/chunks/{agent-host-connections-EDBMCVQF.js → agent-host-connections-E4C3OC4M.js} +1 -1
  12. package/chunks/{anthropicContentGenerator-V7TX2NXP.js → anthropicContentGenerator-5VTWQLT5.js} +1 -1
  13. package/chunks/{autofix-pr-WP34NYHL.js → autofix-pr-HDYQDJS4.js} +1 -1
  14. package/chunks/{batch-XFVQ4BLM.js → batch-3CRVN5VJ.js} +1 -1
  15. package/chunks/{bridge-AE7AFEXB.js → bridge-NZ6WVBLQ.js} +1 -1
  16. package/chunks/{channel-settings-store-X63P5OVT.js → channel-settings-store-Z7I2JI6M.js} +1 -1
  17. package/chunks/{chunk-BCI62WSL.js → chunk-236DHGNH.js} +1 -1
  18. package/chunks/{chunk-JRTOPEM3.js → chunk-2M3ND5WN.js} +1 -1
  19. package/chunks/{chunk-LBLLWAKK.js → chunk-36A6EXHB.js} +1 -1
  20. package/chunks/{chunk-H3IR3GIE.js → chunk-3ANIQTDT.js} +1 -1
  21. package/chunks/{chunk-GSPGIGO5.js → chunk-3QTR2HAE.js} +3 -3
  22. package/chunks/{chunk-32XHDDIA.js → chunk-3TTHYXT3.js} +1 -1
  23. package/chunks/{chunk-MTDBCIDA.js → chunk-4CE4GMDL.js} +1 -1
  24. package/chunks/{chunk-T2YTHAJW.js → chunk-4FVT657Y.js} +1 -1
  25. package/chunks/{chunk-CGDFZEER.js → chunk-4HSISRRA.js} +1 -1
  26. package/chunks/{chunk-7453BHJO.js → chunk-4SZUJ5RT.js} +1 -1
  27. package/chunks/{chunk-B37YY4XU.js → chunk-57D2OB3I.js} +1 -1
  28. package/chunks/{chunk-WGFX3EL3.js → chunk-5FGBLIXB.js} +1 -1
  29. package/chunks/{chunk-I6PUY2T3.js → chunk-5HX2QGVR.js} +1 -1
  30. package/chunks/{chunk-BPFFRPWE.js → chunk-5ZNXAWOG.js} +6 -6
  31. package/chunks/{chunk-BHIDG6VZ.js → chunk-6CKX56LJ.js} +1 -1
  32. package/chunks/{chunk-GRAECADD.js → chunk-6NIQFWXP.js} +1 -1
  33. package/chunks/{chunk-ELDZ4MNL.js → chunk-6PC6MZHL.js} +1 -1
  34. package/chunks/{chunk-FEP6W4NJ.js → chunk-6VQKGKMJ.js} +1 -1
  35. package/chunks/{chunk-GBSRWT7J.js → chunk-6ZEMLEK2.js} +1 -1
  36. package/chunks/{chunk-4NDJKNN6.js → chunk-72VY2PJA.js} +1 -1
  37. package/chunks/{chunk-BAUMVH4Q.js → chunk-75I3NYBD.js} +1 -1
  38. package/chunks/{chunk-YH2XRWRF.js → chunk-76L7ZDEK.js} +1 -1
  39. package/chunks/{chunk-2JGTWRZJ.js → chunk-7XQ5D34E.js} +6 -6
  40. package/chunks/{chunk-DA6LOBSB.js → chunk-AYX75VXG.js} +1 -1
  41. package/chunks/{chunk-G6DALGGS.js → chunk-BBDFEMCF.js} +1 -1
  42. package/chunks/{chunk-VD2GSW64.js → chunk-BOTX7S66.js} +1 -1
  43. package/chunks/{chunk-M6KB5RVD.js → chunk-CY2QKKZA.js} +1 -1
  44. package/chunks/{chunk-HTAUIJB4.js → chunk-D5JWQUID.js} +1 -1
  45. package/chunks/{chunk-P3JEEDQZ.js → chunk-DMIPB7RZ.js} +1 -1
  46. package/chunks/{chunk-CF6SZJNP.js → chunk-DSKA3P2C.js} +1 -1
  47. package/chunks/{chunk-LTE4N6L3.js → chunk-DVC65H4X.js} +1 -1
  48. package/chunks/{chunk-W5Z4BWWA.js → chunk-DVJSDCMX.js} +1 -1
  49. package/chunks/{chunk-65ME4BOH.js → chunk-E6CPFQX2.js} +1 -1
  50. package/chunks/{chunk-JEDL4IKF.js → chunk-EIFBGEXJ.js} +1 -1
  51. package/chunks/{chunk-AYVCT5FF.js → chunk-EQOHDAYU.js} +1 -1
  52. package/chunks/{chunk-2TAJ5STJ.js → chunk-EZPM4DLR.js} +1 -1
  53. package/chunks/{chunk-JWNKPINR.js → chunk-F6U6T7QD.js} +1 -1
  54. package/chunks/{chunk-ET5M5WFN.js → chunk-FCGFBUHS.js} +1 -1
  55. package/chunks/{chunk-OU7CEG7Q.js → chunk-G2LTZU67.js} +1 -1
  56. package/chunks/{chunk-2N3NBTYJ.js → chunk-GMJSEK4V.js} +1 -1
  57. package/chunks/{chunk-NA4ZF2FE.js → chunk-HJMUBVXZ.js} +2 -2
  58. package/chunks/{chunk-AFO5ER23.js → chunk-HQZTAA2U.js} +1 -1
  59. package/chunks/{chunk-OK7LBM5G.js → chunk-I63TIQOI.js} +1 -1
  60. package/chunks/{chunk-OJ4K62S2.js → chunk-I65LBJN7.js} +1 -1
  61. package/chunks/{chunk-GHIFIXNX.js → chunk-IBDOC27R.js} +1 -1
  62. package/chunks/{chunk-2LWJGXTW.js → chunk-IKF2HWEV.js} +1 -1
  63. package/chunks/{chunk-AEZYXPFS.js → chunk-K6NS2HXT.js} +1 -1
  64. package/chunks/{chunk-T5DKF33F.js → chunk-KTRNYPQP.js} +1 -1
  65. package/chunks/{chunk-SKGJ26HQ.js → chunk-L3ANU5JZ.js} +1 -1
  66. package/chunks/{chunk-U3Q72OGV.js → chunk-LKPMADUO.js} +1 -1
  67. package/chunks/{chunk-MYV7GY3H.js → chunk-M56Y2B6N.js} +1 -1
  68. package/chunks/{chunk-34HC2AXI.js → chunk-N5KRBAK5.js} +2 -2
  69. package/chunks/{chunk-EXIFPXMB.js → chunk-NA2WJPOU.js} +1 -1
  70. package/chunks/{chunk-7RNOS7R4.js → chunk-NGOWLXYK.js} +1 -1
  71. package/chunks/{chunk-IZ5MWA6E.js → chunk-NL7P73ZP.js} +1 -1
  72. package/chunks/{chunk-FYBJGRX7.js → chunk-NS3QR7D3.js} +1 -1
  73. package/chunks/{chunk-XISR37DQ.js → chunk-O5JCCBMQ.js} +1 -1
  74. package/chunks/{chunk-FKL3V5BO.js → chunk-OOKFFZHF.js} +1 -1
  75. package/chunks/{chunk-VRKYBH5G.js → chunk-OTYPLLMT.js} +5 -5
  76. package/chunks/{chunk-W66WWTOP.js → chunk-P7NHWX27.js} +1 -1
  77. package/chunks/{chunk-AEKEZRIU.js → chunk-PC5QZUKR.js} +1 -1
  78. package/chunks/{chunk-NEKPQLFY.js → chunk-PS7MQL57.js} +2 -2
  79. package/chunks/{chunk-TB4AUC2L.js → chunk-PXWHOFAA.js} +1 -1
  80. package/chunks/{chunk-OOJ2AQT3.js → chunk-Q65LVCDR.js} +1 -1
  81. package/chunks/{chunk-EFIRES46.js → chunk-QDUDLELH.js} +1 -1
  82. package/chunks/{chunk-KZNYALFU.js → chunk-QF22ILPV.js} +1 -1
  83. package/chunks/{chunk-MGATL4OA.js → chunk-QW7MAG2E.js} +1 -1
  84. package/chunks/{chunk-KJGRCIVY.js → chunk-RXK6XD6F.js} +1 -1
  85. package/chunks/{chunk-W2RQIZ6B.js → chunk-SVDFCWS7.js} +1 -1
  86. package/chunks/{chunk-P62S5JGM.js → chunk-TKP3GAUI.js} +1 -1
  87. package/chunks/{chunk-BQZF3UKI.js → chunk-TUS74LFI.js} +1 -1
  88. package/chunks/{chunk-JH3V5SPA.js → chunk-U7YGHPSL.js} +1 -1
  89. package/chunks/{chunk-NONBHCXP.js → chunk-UB37RBSK.js} +1 -1
  90. package/chunks/{chunk-T53VMDXH.js → chunk-UK5SIRH4.js} +1 -1
  91. package/chunks/{chunk-3W32X2DH.js → chunk-UTTSBCFR.js} +1 -1
  92. package/chunks/{chunk-RSLTOIG5.js → chunk-UYV4ZVXY.js} +2 -2
  93. package/chunks/{chunk-FKZ46GKL.js → chunk-VC3JJL7E.js} +1 -1
  94. package/chunks/{chunk-SP6CQ3MO.js → chunk-VKWVIWLK.js} +1 -1
  95. package/chunks/{chunk-N7PWZBXV.js → chunk-VUI6STKU.js} +1 -1
  96. package/chunks/{chunk-5EXL4TKQ.js → chunk-W3YXE55M.js} +1 -1
  97. package/chunks/{chunk-NVOI6UDQ.js → chunk-WAIPC47V.js} +1 -1
  98. package/chunks/{chunk-QDCUR3JB.js → chunk-WMJ6UHDP.js} +1 -1
  99. package/chunks/{chunk-CBE6ZIHU.js → chunk-WZU2ECUD.js} +1 -1
  100. package/chunks/{chunk-ZENMAISJ.js → chunk-XAGIZY2Y.js} +1 -1
  101. package/chunks/{chunk-RXN7DUMP.js → chunk-XGZYVULJ.js} +2 -2
  102. package/chunks/{chunk-HOG66S6K.js → chunk-XJIHDVPX.js} +1 -1
  103. package/chunks/{chunk-UKLXKJKL.js → chunk-XVDIHFRH.js} +1 -1
  104. package/chunks/{chunk-76FSYQTG.js → chunk-YMEW4TTT.js} +1 -1
  105. package/chunks/{chunk-EYPLBTMI.js → chunk-Z32URWBG.js} +1 -1
  106. package/chunks/{chunk-CUP2TNJK.js → chunk-Z6HRXHJP.js} +1 -1
  107. package/chunks/{chunk-MPVQDYPH.js → chunk-ZO4F6ZWR.js} +1 -1
  108. package/chunks/{codex-subagent-executor-OLMGVPVS.js → codex-subagent-executor-DDKYNU42.js} +1 -1
  109. package/chunks/{config-utils-OWY5G5Y2.js → config-utils-S7Z2ZZ2E.js} +1 -1
  110. package/chunks/{contextCommand-IXFUZH65.js → contextCommand-7F4PGV2A.js} +1 -1
  111. package/chunks/{core-runtime-O4LC4NY3.js → core-runtime-LBH3U7ZF.js} +1 -1
  112. package/chunks/{create-sub-session-6F7C3TMT.js → create-sub-session-56DS2T6L.js} +1 -1
  113. package/chunks/{cron-create-2422NBSJ.js → cron-create-PBP3C46Q.js} +1 -1
  114. package/chunks/{daemon-git-worktree-guard-EWPQA6NO.js → daemon-git-worktree-guard-WJS6FBDA.js} +1 -1
  115. package/chunks/{daemon-status-provider-FAHOXNFW.js → daemon-status-provider-UPPAEHJ6.js} +1 -1
  116. package/chunks/{daemon-trust-policy-L3DM6AI5.js → daemon-trust-policy-4Z5HSNUX.js} +1 -1
  117. package/chunks/{daemon-trust-policy-monitor-HNPY5KJ4.js → daemon-trust-policy-monitor-WFWDOYX3.js} +1 -1
  118. package/chunks/{deferred-core-runtime-JF42NQJK.js → deferred-core-runtime-MJYNEA4N.js} +1 -1
  119. package/chunks/{edit-E5LEI2LL.js → edit-U7TGKKK3.js} +1 -1
  120. package/chunks/{enterPlanMode-3COTUV5V.js → enterPlanMode-27HC5AXN.js} +1 -1
  121. package/chunks/{environment-XBBIB3VA.js → environment-PHWY6C4P.js} +1 -1
  122. package/chunks/{errors-LNMQ7TUK.js → errors-F2EYYFI3.js} +1 -1
  123. package/chunks/{execution-tool-QDDKJD2K.js → execution-tool-O4KJ5SMM.js} +1 -1
  124. package/chunks/{execution-worker-TXGZRZXE.js → execution-worker-AMFXZ7JD.js} +1 -1
  125. package/chunks/{exitPlanMode-Z7QEMWPE.js → exitPlanMode-LDYL43PB.js} +1 -1
  126. package/chunks/{fast-path-M6K2RACY.js → fast-path-HTODEVOR.js} +1 -1
  127. package/chunks/{glob-N2QT4U7U.js → glob-NKQJJZND.js} +1 -1
  128. package/chunks/{goal-tools-CUSQD3DG.js → goal-tools-47I455VV.js} +1 -1
  129. package/chunks/{handleAutoUpdate-QF2YQHF6.js → handleAutoUpdate-MJKTDJUO.js} +1 -1
  130. package/chunks/{i18n-AGOA6MUI.js → i18n-TCOB4TC5.js} +1 -1
  131. package/chunks/{initializer-FRKYDUSX.js → initializer-NLYOGZZS.js} +1 -1
  132. package/chunks/{installationInfo-OKA4WXAS.js → installationInfo-TF2RSJOG.js} +1 -1
  133. package/chunks/{interactive-mod-session-MWYN5IFK.js → interactive-mod-session-5F7R3KSA.js} +1 -1
  134. package/chunks/{list-DE7VUIR2.js → list-U2AEVLFP.js} +1 -1
  135. package/chunks/{llm-N3JGJHYC.js → llm-EV2QTQBU.js} +4 -4
  136. package/chunks/{llm-content-generator-VMUBA7OJ.js → llm-content-generator-ZXUSPPG2.js} +1 -1
  137. package/chunks/{loadedSettingsAdapter-5C36OZ7N.js → loadedSettingsAdapter-TLRI22X7.js} +1 -1
  138. package/chunks/{local-BE624O3A.js → local-ZTSBSKWV.js} +1 -1
  139. package/chunks/{local-execution-environment-OPGM7Y6L.js → local-execution-environment-F263PSIM.js} +1 -1
  140. package/chunks/{loggingContentGenerator-2MHAI6JR.js → loggingContentGenerator-2XHSIJQD.js} +1 -1
  141. package/chunks/{loop-wakeup-BDLATBXH.js → loop-wakeup-5ET3JHUT.js} +1 -1
  142. package/chunks/{manage-memory-BBCEIIWB.js → manage-memory-MJEQ47H2.js} +1 -1
  143. package/chunks/{managed-execution-engine-SRFALTCX.js → managed-execution-engine-ODPR5OEH.js} +1 -1
  144. package/chunks/{managed-local-serve-ICNAS3E6.js → managed-local-serve-S5R4Z5OL.js} +1 -1
  145. package/chunks/managed-npm-update-BUI5APGY.js +8 -0
  146. package/chunks/{managed-runtime-attestation-worker-ZRDWKXCI.js → managed-runtime-attestation-worker-BQP4E7LQ.js} +1 -1
  147. package/chunks/{managed-runtime-bootstrap-6NTGZXQL.js → managed-runtime-bootstrap-SRBDFSKK.js} +1 -1
  148. package/chunks/{managed-runtime-session-worker-RKQBBFR6.js → managed-runtime-session-worker-UI23BTYJ.js} +1 -1
  149. package/chunks/{managed-runtime-ssh-worker-FCGV6FSW.js → managed-runtime-ssh-worker-HU4CIJRK.js} +1 -1
  150. package/chunks/{managed-session-authority-C7IW6TJX.js → managed-session-authority-XSSTLAEY.js} +1 -1
  151. package/chunks/{mcp-VC4CJPE5.js → mcp-WLHDOKP7.js} +1 -1
  152. package/chunks/{memory-S6OJA3ZD.js → memory-OUUHPSDD.js} +1 -1
  153. package/chunks/{model-call-collection-MJZWRQSU.js → model-call-collection-4A2EB76B.js} +1 -1
  154. package/chunks/{model-configuration-SKU6L3QI.js → model-configuration-4CGUFKEP.js} +1 -1
  155. package/chunks/{modelConfigUtils-TJCB6NXT.js → modelConfigUtils-HUEERWBA.js} +1 -1
  156. package/chunks/{monitor-M3PNLCYP.js → monitor-FXL5UNMP.js} +1 -1
  157. package/chunks/{nonInteractiveCli-MR7JLAWU.js → nonInteractiveCli-W7M2O43W.js} +1 -1
  158. package/chunks/{nonInteractiveToolExecutor-YKA6JMTY.js → nonInteractiveToolExecutor-EMLI363Q.js} +1 -1
  159. package/chunks/{notebook-edit-ENTFB5D7.js → notebook-edit-R5RSLSSH.js} +1 -1
  160. package/chunks/{omni-6YBX4R6K.js → omni-DNZGITTE.js} +1 -1
  161. package/chunks/{openaiContentGenerator-XRXX33FY.js → openaiContentGenerator-PKOPYMHR.js} +1 -1
  162. package/chunks/{openaiResponsesContentGenerator-L6ONEHMR.js → openaiResponsesContentGenerator-MHH2MF3V.js} +1 -1
  163. package/chunks/{pidfile-XR4JF2Z6.js → pidfile-5ZNJWMKG.js} +1 -1
  164. package/chunks/{processUtils-GQYNJRBJ.js → processUtils-JIHQDASW.js} +1 -1
  165. package/chunks/{prompt-terminal-ledger-7BM7YDLG.js → prompt-terminal-ledger-L3LZ5SLR.js} +1 -1
  166. package/chunks/{qwenContentGenerator-QSA32XEL.js → qwenContentGenerator-QCZL7HJJ.js} +1 -1
  167. package/chunks/{reactive-degrade-TFNBAAPZ.js → reactive-degrade-YUXOUQG4.js} +1 -1
  168. package/chunks/{read-file-VD7OFO2E.js → read-file-FBNU3AVX.js} +1 -1
  169. package/chunks/{resumeHistoryUtils-2B4KPI7G.js → resumeHistoryUtils-5FPRTI4A.js} +1 -1
  170. package/chunks/{review-C365WGCW.js → review-NLFYSNM3.js} +1 -1
  171. package/chunks/{ripGrep-D7WPMBXR.js → ripGrep-JUAPC5LD.js} +1 -1
  172. package/chunks/{run-qwen-serve-NZWQHWQA.js → run-qwen-serve-JP64UQ3Y.js} +1 -1
  173. package/chunks/{runtime-J6SPBSCS.js → runtime-D2QUYM6U.js} +1 -1
  174. package/chunks/{sandboxConfig-QS2XBPZG.js → sandboxConfig-7VZJQV6H.js} +1 -1
  175. package/chunks/{scheduled-tasks-YNNIOOPM.js → scheduled-tasks-PC6EH75E.js} +1 -1
  176. package/chunks/{scheduler-KCMSPHON.js → scheduler-RUV2FNDR.js} +1 -1
  177. package/chunks/{search-memory-EUBJ7IAV.js → search-memory-YJTJ7BRU.js} +1 -1
  178. package/chunks/{send-message-CWWZUPSK.js → send-message-EEEFFTHX.js} +1 -1
  179. package/chunks/{serve-4CB4BWJ5.js → serve-KMIZDYON.js} +1 -1
  180. package/chunks/{server-JNANUIGC.js → server-DUPK3V7B.js} +3 -3
  181. package/chunks/{session-3LQLXPUA.js → session-CW5YMFMP.js} +1 -1
  182. package/chunks/{session-attachments-root-BWIVWFHJ.js → session-attachments-root-5H5GFHLI.js} +1 -1
  183. package/chunks/{session-execution-engine-selector-5OLRX57L.js → session-execution-engine-selector-MVXM2HZW.js} +1 -1
  184. package/chunks/{session-pr-refresh-RLF3EXS3.js → session-pr-refresh-4UPONX4L.js} +1 -1
  185. package/chunks/{sessionService-U7ACD2HP.js → sessionService-GGCYISSL.js} +1 -1
  186. package/chunks/{settings-FTGWYTUH.js → settings-AASJCESS.js} +1 -1
  187. package/chunks/{shell-E4RENYQC.js → shell-V4WWLW3Q.js} +1 -1
  188. package/chunks/{skill-OLNPHRWB.js → skill-NDEBB7VX.js} +1 -1
  189. package/chunks/{skill-settings-R2BV2GEK.js → skill-settings-YAI3GYU5.js} +1 -1
  190. package/chunks/{spawnChannel-LOPAR5T2.js → spawnChannel-6JKVJAXZ.js} +1 -1
  191. package/chunks/{standalone-update-IGDX2RGN.js → standalone-update-NJP5OCKJ.js} +1 -1
  192. package/chunks/{start-opentui-ui-33QLBNRC.js → start-opentui-ui-M4B4SXRM.js} +1 -1
  193. package/chunks/{startInteractiveUI-RQKHD7MM.js → startInteractiveUI-O4JUDEAU.js} +1 -1
  194. package/chunks/{team-create-HAVKHNU5.js → team-create-NLJ7QBLD.js} +1 -1
  195. package/chunks/{team-plan-approval-7MCQX67C.js → team-plan-approval-XKYPVWNG.js} +1 -1
  196. package/chunks/{terminal-image-renderer-XT5JVEO6.js → terminal-image-renderer-47TD747D.js} +1 -1
  197. package/chunks/{theme-manager-DR5EYGLT.js → theme-manager-AANEBPLJ.js} +1 -1
  198. package/chunks/{tool-call-LZHZ5RVH.js → tool-call-ETH3LS7Y.js} +1 -1
  199. package/chunks/{tool-result-media-XCXCF4YC.js → tool-result-media-EFOEPAF2.js} +1 -1
  200. package/chunks/{tool-search-K6S3ON7M.js → tool-search-J3CF5PRN.js} +1 -1
  201. package/chunks/{total-session-admission-LGSS2VWS.js → total-session-admission-3DC52PLQ.js} +1 -1
  202. package/chunks/{trustedFolders-IIR2UZRL.js → trustedFolders-4KPWZZKB.js} +1 -1
  203. package/chunks/{update-relaunch-WVIFX5CN.js → update-relaunch-A67BS7QS.js} +1 -1
  204. package/chunks/{updateCheck-CMEWLLZJ.js → updateCheck-X623JRSY.js} +1 -1
  205. package/chunks/{upload-config-TCCFCNCD.js → upload-config-X2CR3F26.js} +1 -1
  206. package/chunks/{useAutoAcceptIndicator-5RTTH3OW.js → useAutoAcceptIndicator-INIOQGJH.js} +1 -1
  207. package/chunks/{validateNonInterActiveAuth-AO336KDX.js → validateNonInterActiveAuth-XJ2U5CLB.js} +1 -1
  208. package/chunks/{version-JYWKKMNP.js → version-MFHRMM7W.js} +1 -1
  209. package/chunks/{web-fetch-HWTAWXFM.js → web-fetch-3GEJ62DH.js} +1 -1
  210. package/chunks/{web-search-HAI5LW3G.js → web-search-WJZO3Q3A.js} +1 -1
  211. package/chunks/{workflow-BZ2YFGF6.js → workflow-ML7ITCMH.js} +1 -1
  212. package/chunks/{workflow-ancestor-trust-26TFXFPO.js → workflow-ancestor-trust-M3VFMS73.js} +1 -1
  213. package/chunks/{workspace-agents-DLI4JQJZ.js → workspace-agents-YFZMV7EF.js} +1 -1
  214. package/chunks/{workspace-providers-status-64C7DJZU.js → workspace-providers-status-3COKLBCI.js} +1 -1
  215. package/chunks/{workspace-recovery-worker-IFRT3KKP.js → workspace-recovery-worker-QURA3WFZ.js} +1 -1
  216. package/chunks/{workspace-registration-store-MYKJM2SK.js → workspace-registration-store-F3AGIOBW.js} +1 -1
  217. package/chunks/{workspace-registry-GZJRONAY.js → workspace-registry-QUBL3RW6.js} +1 -1
  218. package/chunks/{workspace-runtime-coordinator-44KW6HSN.js → workspace-runtime-coordinator-22TSDHXX.js} +1 -1
  219. package/chunks/{workspace-service-YHTSZYYD.js → workspace-service-UUENTHNO.js} +1 -1
  220. package/chunks/{workspace-skills-status-NEB62X24.js → workspace-skills-status-NNQQBBCJ.js} +1 -1
  221. package/chunks/{workspace-trust-reconciler-HZLOOZWM.js → workspace-trust-reconciler-3CMMNCGG.js} +1 -1
  222. package/chunks/{write-file-HD5LHXGL.js → write-file-DEAFIK4C.js} +1 -1
  223. package/chunks/{zoom-image-W4BMRC5T.js → zoom-image-YYO22PQG.js} +1 -1
  224. package/cli-entry.js +2 -3
  225. package/cli.js +2 -2
  226. package/execution-worker.js +1 -1
  227. package/export-transcript-document.js +1 -1
  228. package/gerege.mjs +11 -0
  229. package/package.json +2 -12
  230. package/chunks/managed-npm-update-CTL6LH5Z.js +0 -8
  231. package/opentui-assets/@opentui/core/assets/javascript/highlights.scm +0 -205
  232. package/opentui-assets/@opentui/core/assets/javascript/tree-sitter-javascript.wasm +0 -0
  233. package/opentui-assets/@opentui/core/assets/markdown/highlights.scm +0 -150
  234. package/opentui-assets/@opentui/core/assets/markdown/injections.scm +0 -27
  235. package/opentui-assets/@opentui/core/assets/markdown/tree-sitter-markdown.wasm +0 -0
  236. package/opentui-assets/@opentui/core/assets/markdown_inline/highlights.scm +0 -115
  237. package/opentui-assets/@opentui/core/assets/markdown_inline/tree-sitter-markdown_inline.wasm +0 -0
  238. package/opentui-assets/@opentui/core/assets/typescript/highlights.scm +0 -604
  239. package/opentui-assets/@opentui/core/assets/typescript/tree-sitter-typescript.wasm +0 -0
  240. package/opentui-assets/@opentui/core/assets/zig/highlights.scm +0 -284
  241. package/opentui-assets/@opentui/core/assets/zig/tree-sitter-zig.wasm +0 -0
  242. package/opentui-assets/@opentui/core/parser.worker.js +0 -4566
  243. package/opentui-assets/@opentui/core-darwin-arm64/libopentui.dylib +0 -0
  244. package/opentui-assets/@opentui/core-darwin-x64/libopentui.dylib +0 -0
  245. package/opentui-assets/@opentui/core-linux-arm64/libopentui.so +0 -0
  246. package/opentui-assets/@opentui/core-linux-x64/libopentui.so +0 -0
  247. package/opentui-assets/web-tree-sitter/tree-sitter.wasm +0 -0
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{registerMcpHotReload,registerModelProvidersHotReload}from"./chunk-N7PWZBXV.js";import{startEarlyStartupPrefetches}from"./chunk-RSLTOIG5.js";import{ExtensionRefreshState}from"./chunk-254YDSL2.js";import{validateAuthMethod}from"./chunk-BQZF3UKI.js";import{isAcpStartupProfilerEnabled,markAcpStartup,recordAcpConfigStartupEvent}from"./chunk-XRVEZKVE.js";import{appEvents,buildDisabledSkillNamesProvider,buildEnabledSkillNamesProvider,isDebugMode,isInteractiveInvocation,loadCliConfig,parseArguments}from"./chunk-VRKYBH5G.js";import"./chunk-VURTGFJP.js";import{sanitizeTerminalText}from"./chunk-64CA3W6G.js";import"./chunk-S34YI2NO.js";import"./chunk-76FSYQTG.js";import"./chunk-OX4QMNUW.js";import"./chunk-HOG66S6K.js";import"./chunk-SZBGWRES.js";import"./chunk-R4VUFIDQ.js";import"./chunk-XIFNBULA.js";import"./chunk-34HC2AXI.js";import{getHeadlessYoloSafetyWarning}from"./chunk-Z57KDB5F.js";import"./chunk-6BSQDDUG.js";import"./chunk-R7TNFTT4.js";import"./chunk-DHYCGKLG.js";import"./chunk-G2SXDY2E.js";import"./chunk-XKSB7VTV.js";import{getInstallationInfo,selectNpmBunHandoff}from"./chunk-26MNTKT2.js";import"./chunk-2HLVSWM6.js";import"./chunk-AVCBF5WL.js";import{isValidSessionId}from"./chunk-LGFF5PJA.js";import"./chunk-BWQ5AIEA.js";import"./chunk-WDR5XP3Y.js";import"./chunk-WBDNGVHU.js";import"./chunk-2QYDBHYZ.js";import"./chunk-BZAH4DTS.js";import"./chunk-SKGJ26HQ.js";import"./chunk-3SHHYK7S.js";import"./chunk-BYVINSWZ.js";import"./chunk-L5UULTGF.js";import"./chunk-AVJJ62OC.js";import"./chunk-VNV7VKZL.js";import"./chunk-KOJ7WZ63.js";import"./chunk-O6ZQAVRG.js";import"./chunk-3KZHPZVZ.js";import"./chunk-CFTFKWPW.js";import{EXTERNAL_TOOL_GUARD_PROVIDER_ATTACHED_VALUE,EXTERNAL_TOOL_GUARD_REQUIRED_VALUE,EXTERNAL_TOOL_GUARD_TOKEN_ENV,PRIVATE_EXTERNAL_TOOL_GUARD_ENV,PRIVATE_EXTERNAL_TOOL_GUARD_PROVIDER_ENV}from"./chunk-NIEO2TBE.js";import"./chunk-SPYNWVDZ.js";import"./chunk-E4UMXDOZ.js";import"./chunk-MMQY4FJL.js";import"./chunk-NY56CL2X.js";import"./chunk-TL6RUTMP.js";import"./chunk-W7V6J2VV.js";import"./chunk-B6ZRS462.js";import"./chunk-AZ3CKMCT.js";import"./chunk-TDDRZUJO.js";import"./chunk-Q6U4ODPJ.js";import"./chunk-LTE4N6L3.js";import"./chunk-GT4TCQ3R.js";import"./chunk-BAUMVH4Q.js";import"./chunk-AEZYXPFS.js";import"./chunk-D2NY7HVY.js";import"./chunk-ZENMAISJ.js";import{CUSTOM_SANDBOX_IMAGE_ENV_VAR,HOST_UPDATE_RELAUNCH_ENV_VAR,RELAUNCH_EXIT_CODE,SKIP_UPDATE_CHECK_ENV_VAR,UPDATE_COMPLETE_EXIT_CODE,UPDATE_ON_EXIT_MESSAGE,UPDATE_RELAUNCH_EXIT_CODE,getRelaunchExecArgv,superviseInProcess}from"./chunk-M6KB5RVD.js";import"./chunk-QO46QMCC.js";import{loadSandboxConfig}from"./chunk-WWRXBAW4.js";import"./chunk-A27RJEWD.js";import"./chunk-QN7NYEE3.js";import"./chunk-WSOEJTOC.js";import"./chunk-P62S5JGM.js";import"./chunk-ELDZ4MNL.js";import{createMinimalSettings,getFlattenedSchema,getOperatorTrustSettings,getSettingsWarnings,getUserSettingsDir,initializeLlmOutputLanguage,loadSettings}from"./chunk-2TAJ5STJ.js";import"./chunk-UWCF7JIF.js";import"./chunk-NONBHCXP.js";import"./chunk-LMUSSYJH.js";import{initializeI18n,resolveLanguageSetting}from"./chunk-NO7VTKRL.js";import"./chunk-U7HZUZKP.js";import{SETTINGS_DIRECTORY_NAME,getRelaunchEnvProvenance,hasLoadedEnvironmentValues,preResolveHomeEnvOverrides}from"./chunk-MPVQDYPH.js";import"./chunk-PKK2D2W4.js";import{ENV_CORRUPTED_PATH,ENV_WAS_RECOVERED,QWEN_CODE_DESKTOP_ENV,QWEN_CODE_SERVE_ENV,processBootLoaderEnv,scrubAndReportInheritedLoaderEnv}from"./chunk-N3AQAZ7D.js";import{RELAUNCH_SUPERVISED_ENV}from"./chunk-E5T4R2PM.js";import{BWRAP_MIGRATION_MESSAGE,stripUtf8Bom,validateExecutionSandboxSelection}from"./chunk-DOLUT3XC.js";import"./chunk-PTHIQ7ZN.js";import{createLocalWorkflowAncestorTrustProvider}from"./chunk-MTDBCIDA.js";import"./chunk-EIPLDYEY.js";import"./chunk-IDXJIDME.js";import"./chunk-OU7CEG7Q.js";import"./chunk-QS2ZMQIS.js";import{PRIVATE_CONVERSATIONS_RUNTIME_ENABLE,PRIVATE_CONVERSATIONS_RUNTIME_ENV}from"./chunk-S7IKHQ6I.js";import"./chunk-SEQAVABL.js";import"./chunk-GBSRWT7J.js";import"./chunk-O4EDHV64.js";import"./chunk-PAD5GPDY.js";import"./chunk-MD3ZEOBX.js";import"./chunk-SSYS5YN5.js";import"./chunk-X5QSFJVS.js";import{clearWorktreeSessionDurable,getSessionRuntimeLiveness,readWorktreeSession,writeWorktreeSession}from"./chunk-OMDTFGTX.js";import"./chunk-32XHDDIA.js";import"./chunk-46VUDNCL.js";import"./chunk-MKH3EH7O.js";import"./chunk-FKZ46GKL.js";import{claimInterruptedWorkflowRuns,snapshotArgsUnavailable}from"./chunk-SP6CQ3MO.js";import"./chunk-HW6SU6MX.js";import"./chunk-ZHHFNZ5J.js";import"./chunk-AKWYMQKU.js";import"./chunk-MZUOREFD.js";import"./chunk-CF6SZJNP.js";import"./chunk-7XZVMIY5.js";import"./chunk-CGDFZEER.js";import"./chunk-ZZJXFLVM.js";import"./chunk-RKDS7A4H.js";import"./chunk-KZNYALFU.js";import"./chunk-IV3HAIUN.js";import"./chunk-XFMPZINJ.js";import"./chunk-DECUAM3U.js";import"./chunk-QX7W2HY7.js";import"./chunk-HN5UYLPU.js";import"./chunk-PGRN3GZY.js";import"./chunk-HTW7PYHK.js";import"./chunk-AMGUAA4G.js";import"./chunk-YFTVFH2A.js";import"./chunk-ZBHL2CXR.js";import"./chunk-NIOS3B3V.js";import{MODEL_CATALOG_REFRESH_ENV,SessionService,buildResumeCall,closeFileWatcher,computeInitialTurnFromHistory,hasUninlinableResumeArgs,persistSessionUsage,prepareFileWatchersForProcessExit,setStartupEventSink,watch}from"./chunk-2JGTWRZJ.js";import"./chunk-R2EHHA2C.js";import"./chunk-YK7NDQKM.js";import"./chunk-ZLZF2ZDD.js";import"./chunk-OMSVOFTC.js";import"./chunk-PHIPLV2I.js";import"./chunk-ZOTKZI2P.js";import"./chunk-A6G5TAIF.js";import"./chunk-YVBHCSZD.js";import"./chunk-FIXDX63I.js";import"./chunk-T7CHK6C2.js";import"./chunk-PT7NZBDY.js";import"./chunk-TWP72VRH.js";import"./chunk-UYEWRLGD.js";import"./chunk-QVPT37XZ.js";import"./chunk-YVD4O5ZB.js";import"./chunk-T6W33SET.js";import"./chunk-WK2IBT6D.js";import{canUseRipgrep}from"./chunk-QZV4PFQK.js";import{GitWorktreeService,WorktreeMarkerCommittedError,WorktreeSessionMarkerOwnerChangedError,createWorktreeSessionMarker,ensureWorktreeSessionMarkerExcluded,readWorktreeSessionMarker,replaceWorktreeSessionMarker,worktreeBranchForSlug}from"./chunk-ILECDNJX.js";import"./chunk-QXQGUM3Y.js";import"./chunk-UQ7IROJH.js";import"./chunk-SZCBUCNH.js";import"./chunk-BEKROCWN.js";import"./chunk-5SUFJTQQ.js";import"./chunk-BYU42MLK.js";import"./chunk-JWQXU3SR.js";import"./chunk-5LZ2DPLH.js";import"./chunk-XQJOZDV7.js";import"./chunk-CV2UAEZA.js";import"./chunk-FUBDS3AV.js";import"./chunk-HW6AWS7W.js";import"./chunk-KLC3OD2M.js";import"./chunk-Q5IZXKUJ.js";import"./chunk-G5PYYZMM.js";import"./chunk-BG67XABA.js";import"./chunk-OBOU4ZZM.js";import{QWEN_CODE_SIMPLE_ENV_VAR,isBareMode}from"./chunk-D7XCQWP2.js";import"./chunk-AE5OMKRY.js";import"./chunk-OBV7RNHV.js";import"./chunk-7CQMWEMY.js";import"./chunk-GOZYWU4B.js";import"./chunk-OUC3WICA.js";import"./chunk-JZK2WGXA.js";import"./chunk-MPHSE7M4.js";import"./chunk-S2ZKZXHX.js";import"./chunk-7UK4WJWS.js";import"./chunk-4GP3PH7Z.js";import"./chunk-4QQKOW5M.js";import"./chunk-OV3EBH6J.js";import"./chunk-EBMCWXGZ.js";import"./chunk-XZTE4YTN.js";import"./chunk-LSASUDF2.js";import"./chunk-2V5EKGDK.js";import"./chunk-MOKVM4PT.js";import"./chunk-YIW3H46P.js";import"./chunk-EOMRLUNZ.js";import"./chunk-4ZRCV3JY.js";import"./chunk-TL6MLBXR.js";import"./chunk-NMY3PYNO.js";import"./chunk-YGLM5XPP.js";import"./chunk-WGNF7FPC.js";import{resolveBundleDir}from"./chunk-4NPYOXJO.js";import"./chunk-MWGB5RCF.js";import"./chunk-SCD5TUBG.js";import"./chunk-NTRFETZB.js";import{require_shell_quote}from"./chunk-TL3SF2GA.js";import"./chunk-LMJPU2JM.js";import"./chunk-VFB6Q74I.js";import"./chunk-4JNHUZ7M.js";import"./chunk-SW54YEPK.js";import"./chunk-ZCRL73DT.js";import"./chunk-A6LT3FIJ.js";import"./chunk-S6RXVOY6.js";import"./chunk-YZFNBUKG.js";import"./chunk-AGEDDL7Z.js";import"./chunk-2NJJHZ52.js";import"./chunk-BN4FIQ77.js";import"./chunk-X64RXJQQ.js";import"./chunk-HETUGUHE.js";import"./chunk-ET2Z7ZGF.js";import"./chunk-XFPYXD2P.js";import"./chunk-3YWXKSOI.js";import"./chunk-5CWTKFI4.js";import"./chunk-C4MVD5OI.js";import"./chunk-Z2W7S4O4.js";import"./chunk-476F6QIM.js";import"./chunk-4R67LXKL.js";import"./chunk-FQRF6B65.js";import{logUserPrompt,uiTelemetryService}from"./chunk-ZWPSBU7K.js";import"./chunk-UQFTXKEB.js";import"./chunk-HDGTWJ24.js";import"./chunk-W5NWIGKO.js";import"./chunk-KVA6DHHF.js";import"./chunk-PWOQASXT.js";import"./chunk-K7JCVESI.js";import"./chunk-Y6HHV4LC.js";import"./chunk-RP57XAJ2.js";import"./chunk-Z6AR5XE5.js";import"./chunk-7DOOXUDG.js";import"./chunk-77V43YOE.js";import"./chunk-7U7CWMP7.js";import{PRIVATE_ACP_CAPABILITY_ENV}from"./chunk-EFTJIDS3.js";import"./chunk-4DIWAQ5G.js";import"./chunk-Q6UAOTP3.js";import"./chunk-AFO5ER23.js";import{MODEL_CATALOG_ENV,MODEL_CATALOG_URL_ENV}from"./chunk-GOR7FFVE.js";import"./chunk-4ZBZL23U.js";import"./chunk-BMHYEQTI.js";import"./chunk-ZZZAYAJW.js";import"./chunk-XMANRGPK.js";import"./chunk-3XVPZY7X.js";import"./chunk-KQX4H2D3.js";import"./chunk-URNNJMIC.js";import"./chunk-GU22I6TY.js";import"./chunk-YEYW7PPR.js";import{handleUncaughtException,isExpectedPtyRaceError}from"./chunk-SJCE6UFF.js";import{clearInheritedPeerMessagingEnv}from"./chunk-NPAX2UFU.js";import{finalizeStartupProfile,isStartupProfilerEnabled,profileCheckpoint,recordStartupEvent,setInteractiveMode}from"./chunk-H4XFFVZ2.js";import"./chunk-X7QN6R6K.js";import"./chunk-EO57EBMH.js";import{cleanupCheckpoints,registerCleanup,runExitCleanup}from"./chunk-AYVCT5FF.js";import{writeStderrLine,writeStderrLineSafe}from"./chunk-M4ECEHLX.js";import{stripAnsiAndControl}from"./chunk-DBRQGEEI.js";import"./chunk-B3ZFUGTC.js";import"./chunk-IRINPFG7.js";import"./chunk-6GTPLW7K.js";import"./chunk-NGVRCUYD.js";import"./chunk-5DTFN37U.js";import"./chunk-2YUBAWQ6.js";import"./chunk-O5EKX7LG.js";import"./chunk-TM6ZCBR7.js";import"./chunk-SVAPAMMG.js";import"./chunk-3KUHQGOS.js";import"./chunk-I6S7NGX3.js";import"./chunk-SBZFGYYS.js";import{createDebugLogger,isDebugLogFileEnabled,isDebugLoggingDegraded}from"./chunk-JAUJI56S.js";import"./chunk-I4H7NUVP.js";import{Storage}from"./chunk-EPODBRBP.js";import{isSubpath}from"./chunk-OKN3Z5C5.js";import{FatalSandboxError,getErrorMessage}from"./chunk-XYB7GC5U.js";import"./chunk-2UOMCYQG.js";import"./chunk-I7L2TX4M.js";import"./chunk-MK3OONRA.js";import"./chunk-COGTQ5KZ.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import dns from"node:dns";import fs7 from"node:fs";import os3 from"node:os";import path8 from"node:path";import v8 from"node:v8";init_esbuild_shims();import*as fs from"node:fs";import*as path from"node:path";var debugLogger=createDebugLogger("SETTINGS_WATCHER");function collectChangedKeys(before,after,prefix=""){const changed=[];const keys=new Set([...Object.keys(before),...Object.keys(after)]);for(const key of keys){const keyPath=prefix?`${prefix}.${key}`:key;const beforeValue=before[key];const afterValue=after[key];if(isPlainObject(beforeValue)&&isPlainObject(afterValue)){changed.push(...collectChangedKeys(beforeValue,afterValue,keyPath))}else if(JSON.stringify(beforeValue)!==JSON.stringify(afterValue)){changed.push(keyPath)}}return changed}__name(collectChangedKeys,"collectChangedKeys");function isPlainObject(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isPlainObject,"isPlainObject");function isRestartRequiredKey(changedPath){const flattened=getFlattenedSchema();const parts=changedPath.split(".");for(let i=parts.length;i>0;i--){const candidate=parts.slice(0,i).join(".");const definition=flattened[candidate];if(definition)return definition.requiresRestart===true}return false}__name(isRestartRequiredKey,"isRestartRequiredKey");var SettingsWatcher=class _SettingsWatcher{static{__name(this,"SettingsWatcher")}settings;watchers=new Map;watchStage=new Map;watchGeneration=new Map;changeListeners=new Set;refreshTimer=null;pendingScopeChanges=new Set;processing=false;started=false;static DEBOUNCE_MS=300;static LISTENER_TIMEOUT_MS=3e4;constructor(settings){this.settings=settings}startWatching(){if(this.started)return;this.started=true;for(const{scope,settingsPath}of this.getScopePaths()){if(!settingsPath)continue;const dir=path.dirname(settingsPath);if(fs.existsSync(dir)){this.watchTargetDir(scope,settingsPath)}else{this.watchParentForDir(scope,settingsPath)}}}watchTargetDir(scope,settingsPath){const dir=path.dirname(settingsPath);const targetBasename=path.basename(settingsPath);const gen=this.bumpGeneration(scope);try{const watcher=watch(dir,{ignoreInitial:true,depth:0,ignored:__name((filePath,stats)=>{if(stats&&!stats.isFile()&&!stats.isDirectory())return true;return false},"ignored")}).on("all",(event,changedPath)=>{if(this.watchGeneration.get(scope)!==gen)return;if(event==="unlinkDir"&&changedPath===dir){void this.demoteScope(scope,settingsPath);return}if(path.basename(changedPath)!==targetBasename)return;this.scheduleRefresh(scope)}).on("error",error=>{debugLogger.warn(`Settings watcher error for ${dir}:`,error)});this.watchers.set(scope,watcher);this.watchStage.set(scope,"target")}catch(error){debugLogger.warn(`Failed to start settings watcher for ${scope} (${dir}):`,error)}}watchParentForDir(scope,settingsPath){const dir=path.dirname(settingsPath);const parentDir=path.dirname(dir);const dirBasename=path.basename(dir);const gen=this.bumpGeneration(scope);try{const watcher=watch(parentDir,{ignoreInitial:true,depth:0,ignored:__name(filePath=>filePath!==parentDir&&path.basename(filePath)!==dirBasename,"ignored")}).on("all",(_event,changedPath)=>{if(this.watchGeneration.get(scope)!==gen)return;if(path.basename(changedPath)!==dirBasename)return;void this.promoteScope(scope,settingsPath)}).on("error",error=>{debugLogger.warn(`Settings bootstrap watcher error for ${parentDir}:`,error)});this.watchers.set(scope,watcher);this.watchStage.set(scope,"bootstrap")}catch(error){debugLogger.warn(`Failed to start settings bootstrap watcher for ${scope} (${parentDir}):`,error);return}if(fs.existsSync(dir)){void this.promoteScope(scope,settingsPath)}}async promoteScope(scope,settingsPath){if(this.watchStage.get(scope)!=="bootstrap")return;await this.replaceWatcher(scope);if(!this.started)return;this.watchTargetDir(scope,settingsPath);this.scheduleRefresh(scope)}async demoteScope(scope,settingsPath){if(this.watchStage.get(scope)!=="target")return;await this.replaceWatcher(scope);if(!this.started)return;this.watchParentForDir(scope,settingsPath);this.scheduleRefresh(scope)}async replaceWatcher(scope){this.bumpGeneration(scope);const watcher=this.watchers.get(scope);this.watchers.delete(scope);this.watchStage.delete(scope);if(watcher){try{await closeFileWatcher(watcher)}catch(err){debugLogger.warn("Settings watcher close error:",err)}}}bumpGeneration(scope){const next=(this.watchGeneration.get(scope)??0)+1;this.watchGeneration.set(scope,next);return next}stopWatching(){if(!this.started)return;this.started=false;for(const[,watcher]of this.watchers){closeFileWatcher(watcher).catch(err=>{debugLogger.warn("Settings watcher close error:",err)})}this.watchers.clear();this.watchStage.clear();for(const scope of this.watchGeneration.keys()){this.bumpGeneration(scope)}if(this.refreshTimer){clearTimeout(this.refreshTimer);this.refreshTimer=null}this.pendingScopeChanges.clear()}addChangeListener(listener){this.changeListeners.add(listener);return()=>{this.changeListeners.delete(listener)}}getScopePaths(){const paths=[{scope:"User",settingsPath:this.settings.user.path}];if(this.settings.workspaceSettingsActive){paths.push({scope:"Workspace",settingsPath:this.settings.workspace.path})}return paths}scheduleRefresh(scope){this.pendingScopeChanges.add(scope);if(this.refreshTimer)clearTimeout(this.refreshTimer);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null;void this.drainPendingChanges().catch(err=>{debugLogger.warn("Settings watcher refresh error:",err)})},_SettingsWatcher.DEBOUNCE_MS)}async drainPendingChanges(){if(this.processing)return;this.processing=true;try{while(this.pendingScopeChanges.size>0){const scopes=new Set(this.pendingScopeChanges);this.pendingScopeChanges.clear();await this.handleChange(scopes)}}finally{this.processing=false}}async handleChange(changedScopes){const events=[];for(const scope of changedScopes){const file=this.settings.forScope(scope);const before=structuredClone(file.settings??{});const existedBefore=file.rawJson!==void 0;this.settings.reloadScopeFromDisk(scope);const after=file.settings??{};const existsNow=file.rawJson!==void 0;const changedKeys=collectChangedKeys(before,after);if(changedKeys.length===0){continue}const hasHotReloadableChange=changedKeys.some(key=>!isRestartRequiredKey(key));if(!hasHotReloadableChange){continue}events.push({scope,path:file.path,changeType:!existedBefore&&existsNow?"created":existedBefore&&!existsNow?"deleted":"modified"})}if(events.length>0){await this.notifyListeners(events)}}async notifyListeners(events){const TIMEOUT_MS=_SettingsWatcher.LISTENER_TIMEOUT_MS;const withTimeout=__name(p=>{let timerId;const timeoutPromise=new Promise((_,reject)=>{timerId=setTimeout(()=>reject(new Error(`settings change listener timeout after ${TIMEOUT_MS}ms`)),TIMEOUT_MS);if(typeof timerId==="object"&&timerId!==null&&"unref"in timerId){timerId.unref()}});return Promise.race([p,timeoutPromise]).finally(()=>{if(timerId!==void 0)clearTimeout(timerId)})},"withTimeout");const results=await Promise.allSettled(Array.from(this.changeListeners).map(listener=>withTimeout(Promise.resolve().then(()=>listener(events)))));for(const result of results){if(result.status==="rejected"){debugLogger.warn("Settings change listener error:",result.reason)}}}};init_esbuild_shims();import*as fs2 from"node:fs";import*as path2 from"node:path";var debugLogger2=createDebugLogger("LSP_CONFIG_WATCHER");var LspConfigWatcher=class _LspConfigWatcher{constructor(workspaceRoot){this.workspaceRoot=workspaceRoot;this.configPath=path2.join(workspaceRoot,".lsp.json");this.lastSnapshot=this.readSnapshot()}static{__name(this,"LspConfigWatcher")}watcher;listener;refreshTimer=null;activeDrain;processing=false;pending=false;started=false;lastSnapshot;configPath;static DEBOUNCE_MS=300;static LISTENER_TIMEOUT_MS=3e4;startWatching(listener){if(this.started)return;debugLogger2.info(`Starting LSP config watcher for ${this.configPath}`);try{const watcher=watch(this.workspaceRoot,{ignoreInitial:true,depth:0}).on("all",(_event,changedPath)=>{if(path2.basename(changedPath)!==".lsp.json")return;this.scheduleRefresh()}).on("error",error=>{debugLogger2.warn(`LSP config watcher error for ${this.workspaceRoot}:`,error)});this.watcher=watcher;this.listener=listener;this.started=true}catch(error){this.watcher=void 0;this.listener=void 0;this.started=false;debugLogger2.warn(`Failed to start LSP config watcher for ${this.workspaceRoot}:`,error)}}async stopWatching(){if(!this.started)return;this.started=false;debugLogger2.info(`Stopping LSP config watcher for ${this.configPath}`);if(this.refreshTimer){clearTimeout(this.refreshTimer);this.refreshTimer=null}this.pending=false;await this.activeDrain;this.listener=void 0;try{await closeFileWatcher(this.watcher)}catch(error){debugLogger2.warn("LSP config watcher close error:",error)}this.watcher=void 0}scheduleRefresh(){if(!this.started)return;this.pending=true;if(this.refreshTimer)clearTimeout(this.refreshTimer);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null;if(this.processing)return;const activeDrain=this.drainPendingChange().catch(error=>{debugLogger2.warn("LSP config watcher refresh error:",error)});this.activeDrain=activeDrain;void activeDrain.finally(()=>{if(this.activeDrain===activeDrain){this.activeDrain=void 0}})},_LspConfigWatcher.DEBOUNCE_MS);if(typeof this.refreshTimer==="object"&&this.refreshTimer!==null&&"unref"in this.refreshTimer){this.refreshTimer.unref()}}async drainPendingChange(){if(this.processing)return;this.processing=true;try{while(this.pending){this.pending=false;await this.handleChange()}}finally{this.processing=false}}async handleChange(){const before=this.lastSnapshot;const after=this.readSnapshot();if(after.exists&&after.canonical===void 0){debugLogger2.warn(`Invalid .lsp.json; keeping existing LSP runtime state.`);const notified2=await this.notifyListener({path:this.configPath,changeType:"invalid",error:after.error??"Invalid JSON in .lsp.json; existing LSP runtime state is unchanged."});if(notified2){this.lastSnapshot=after}return}const changed=before.exists!==after.exists||before.canonical!==after.canonical;if(!changed){this.lastSnapshot=after;return}const event={path:this.configPath,changeType:!before.exists&&after.exists?"created":before.exists&&!after.exists?"deleted":"modified"};debugLogger2.info(`LSP config changed: ${event.changeType} ${event.path}`);const notified=await this.notifyListener(event);if(notified){this.lastSnapshot=after}}readSnapshot(){let raw;try{raw=fs2.readFileSync(this.configPath,"utf-8")}catch(error){if(error.code==="ENOENT"){return{exists:false}}debugLogger2.warn("Failed to read .lsp.json:",error);return{exists:true,error:"Failed to read .lsp.json; existing LSP runtime state is unchanged."}}try{const parsed=JSON.parse(stripUtf8Bom(raw));return{exists:true,canonical:canonicalize(parsed)}}catch(error){debugLogger2.warn("Failed to parse .lsp.json:",error);return{exists:true,error:"Invalid JSON in .lsp.json; existing LSP runtime state is unchanged."}}}async notifyListener(event){if(!this.listener)return true;const TIMEOUT_MS=_LspConfigWatcher.LISTENER_TIMEOUT_MS;let timerId;const timeoutPromise=new Promise((_,reject)=>{timerId=setTimeout(()=>reject(new Error(`LSP config change listener timeout after ${TIMEOUT_MS}ms`)),TIMEOUT_MS);if(typeof timerId==="object"&&timerId!==null&&"unref"in timerId){timerId.unref()}});const listenerPromise=Promise.resolve().then(()=>this.listener?.(event));try{await Promise.race([listenerPromise,timeoutPromise]);return true}catch(error){debugLogger2.warn("LSP config change listener error:",error);return false}finally{if(timerId!==void 0)clearTimeout(timerId);void listenerPromise.catch(()=>void 0)}}};function canonicalize(value){return JSON.stringify(sortJsonValue(value))}__name(canonicalize,"canonicalize");function sortJsonValue(value){if(Array.isArray(value)){return value.map(sortJsonValue)}if(value&&typeof value==="object"){const sorted=Object.create(null);for(const key of Object.keys(value).sort()){sorted[key]=sortJsonValue(value[key])}return sorted}return value}__name(sortJsonValue,"sortJsonValue");init_esbuild_shims();import*as fs3 from"node:fs";import*as path3 from"node:path";var debugLogger3=createDebugLogger("EXTENSION_FILE_WATCHER");var TOP_LEVEL_FILES=new Set(["extension-enablement.json"]);var EXTENSION_FILES=new Set(["qwen-extension.json",".qwen-extension-install.json"]);var AUTO_REFRESH_DIRS=new Set(["commands","skills","agents","workflows"]);var STALE_DIRS=new Set(["hooks"]);var ExtensionFileWatcher=class{constructor(config,extensionsDir=Storage.getUserExtensionsDir(),refreshState=new ExtensionRefreshState,storeStatePath){this.config=config;this.extensionsDir=extensionsDir;this.refreshState=refreshState;this.storeStatePath=storeStatePath??path3.join(path3.dirname(this.extensionsDir),"extension-store","state.json");this.observedStoreGeneration=this.readStoreGeneration()}static{__name(this,"ExtensionFileWatcher")}watcher;bootstrapWatcher;mutationListenerDisposer;mutationSuppressionEnds=new Map;staleFiles=new Set;watching=false;watchGeneration=0;storeStatePath;generationPoller;observedStoreGeneration;startWatching(){this.stopWatching();this.watching=true;const generation=++this.watchGeneration;this.subscribeExtensionManagerMutations();this.staleFiles=this.getStaleFiles();const roots=this.getWatchRoots();if(roots.length>0){this.watcher=watch(roots,{ignoreInitial:true,followSymlinks:false,awaitWriteFinish:{stabilityThreshold:200,pollInterval:50},ignored:__name(filePath=>this.isIgnored(filePath),"ignored")}).on("all",(event,changedPath)=>{if(generation!==this.watchGeneration)return;const resolvedPath=path3.resolve(changedPath);const action=this.getRefreshAction(event,resolvedPath);let marked=false;if(action==="auto"){marked=this.refreshState.markExtensionContentChanged("extension content files changed")}else if(action==="stale"){marked=this.refreshState.markExtensionsChanged("extension files changed")}debugLogger3.debug("Extension file event classified",{event,path:resolvedPath,action,marked})}).on("error",error=>{debugLogger3.warn("Extension file watcher error:",error)})}if(!fs3.existsSync(this.extensionsDir)){this.watchExtensionsParent()}this.startGenerationPolling()}stopWatching(){const watcher=this.watcher;const bootstrapWatcher=this.bootstrapWatcher;this.watcher=void 0;this.bootstrapWatcher=void 0;this.watching=false;this.watchGeneration++;if(this.generationPoller)clearInterval(this.generationPoller);this.generationPoller=void 0;this.mutationListenerDisposer?.();this.mutationListenerDisposer=void 0;this.endPendingMutationSuppressions();closeFileWatcher(watcher).catch(error=>{debugLogger3.warn("Extension file watcher close error:",error)});closeFileWatcher(bootstrapWatcher).catch(error=>{debugLogger3.warn("Extension bootstrap watcher close error:",error)})}restartWatching(){this.startWatching()}getWatchRoots(){const roots=new Set;if(fs3.existsSync(this.extensionsDir)){roots.add(this.extensionsDir)}roots.add(this.storeStatePath);for(const extension of this.config.getActiveExtensions()){if(extension.installMetadata?.type==="link"){const rawSource=extension.installMetadata.source;const source=rawSource?path3.resolve(rawSource):void 0;if(source&&fs3.existsSync(source)){roots.add(source)}}}return[...roots]}getStaleFiles(){const files=new Set;for(const extension of this.config.getActiveExtensions()){for(const filePath of extension.contextFiles){files.add(path3.resolve(filePath))}const configured=extension.config.contextFileName;const names=configured===void 0?["QWEN.md"]:Array.isArray(configured)?configured:[configured];for(const name of names){files.add(path3.resolve(extension.path,name))}this.addManifestFileReference(files,extension.path,extension.config.hooks);this.addManifestFileReference(files,extension.path,extension.config.lspServers)}return files}addManifestFileReference(files,extensionPath,value){if(typeof value!=="string")return;files.add(path3.isAbsolute(value)?path3.resolve(value):path3.resolve(extensionPath,value))}watchExtensionsParent(){this.closeBootstrapWatcher();const parentDir=path3.dirname(this.extensionsDir);const dirBasename=path3.basename(this.extensionsDir);const generation=this.watchGeneration;this.bootstrapWatcher=watch(parentDir,{ignoreInitial:true,followSymlinks:false,depth:0,ignored:__name(filePath=>filePath!==parentDir&&path3.basename(filePath)!==dirBasename,"ignored")}).on("all",(_event,changedPath)=>{if(generation!==this.watchGeneration)return;if(path3.basename(changedPath)!==dirBasename)return;if(!fs3.existsSync(this.extensionsDir))return;this.refreshState.markExtensionsChanged("extension directory created");queueMicrotask(()=>{if(this.watching){this.restartWatching()}})}).on("error",error=>{debugLogger3.warn("Extension bootstrap watcher error:",error)})}getRefreshAction(event,changedPath){if(changedPath===path3.resolve(this.storeStatePath)){const generation=this.readStoreGeneration();if(generation!==void 0){this.markStoreGenerationChanged(generation,true)}else{this.refreshState.markExtensionsChanged("extension store generation changed")}return false}if(this.staleFiles.has(changedPath)){return"stale"}if(changedPath===path3.resolve(this.extensionsDir)){if(event==="unlinkDir"){this.watchExtensionsParent();return"stale"}return false}if(isSubpath(this.extensionsDir,changedPath)){return this.getUserExtensionRefreshAction(event,changedPath)}return this.getLinkedExtensionRefreshAction(changedPath)}getUserExtensionRefreshAction(event,changedPath){const relative2=path3.relative(this.extensionsDir,changedPath);const parts=relative2.split(path3.sep).filter(Boolean);if(parts.length===1){if(TOP_LEVEL_FILES.has(parts[0]))return"stale";if(event==="addDir"||event==="unlinkDir")return"stale";return false}if(!fs3.existsSync(path3.join(this.extensionsDir,parts[0],"qwen-extension.json"))){return"stale"}const runtimePath=parts.slice(1);return this.getRuntimePathRefreshAction(runtimePath)}getLinkedExtensionRefreshAction(changedPath){for(const extension of this.config.getActiveExtensions()){if(extension.installMetadata?.type!=="link")continue;const rawSource=extension.installMetadata.source;const source=rawSource?path3.resolve(rawSource):void 0;if(!source||!isSubpath(source,changedPath))continue;const relative2=path3.relative(source,changedPath);const parts=relative2.split(path3.sep).filter(Boolean);return parts.length===0?"stale":this.getRuntimePathRefreshAction(parts)}return false}getRuntimePathRefreshAction(parts){if(EXTENSION_FILES.has(parts[0])||STALE_DIRS.has(parts[0])){return"stale"}if(AUTO_REFRESH_DIRS.has(parts[0])){return"auto"}return false}isIgnored(filePath){const normalized=filePath.replace(/\\/g,"/");const searchablePath=`/${normalized}/`;if(searchablePath.includes("/node_modules/")||searchablePath.includes("/.git/")){return true}const basename4=normalized.split("/").pop()??"";return basename4===".DS_Store"||basename4.endsWith("~")||basename4.endsWith(".swp")||basename4.endsWith(".tmp")}subscribeExtensionManagerMutations(){const manager=this.config.getExtensionManager();this.mutationListenerDisposer=manager.addMutationListener(event=>{if(event.phase==="start"){this.mutationSuppressionEnds.set(event.id,this.refreshState.beginSuppression(()=>this.restartAfterMutation()));return}const endSuppression=this.mutationSuppressionEnds.get(event.id);if(!endSuppression){return}this.mutationSuppressionEnds.delete(event.id);endSuppression()})}endPendingMutationSuppressions(){const endSuppressions=[...this.mutationSuppressionEnds.values()];this.mutationSuppressionEnds.clear();for(const endSuppression of endSuppressions){endSuppression()}}restartAfterMutation(){if(this.watching){this.restartWatching()}}closeBootstrapWatcher(){const bootstrapWatcher=this.bootstrapWatcher;this.bootstrapWatcher=void 0;closeFileWatcher(bootstrapWatcher).catch(error=>{debugLogger3.warn("Extension bootstrap watcher close error:",error)})}startGenerationPolling(){if(this.generationPoller)clearInterval(this.generationPoller);this.pollStoreGeneration();this.generationPoller=setInterval(()=>this.pollStoreGeneration(),3e4);this.generationPoller.unref?.()}pollStoreGeneration(){const generation=this.readStoreGeneration();if(generation===void 0)return;this.markStoreGenerationChanged(generation)}markStoreGenerationChanged(generation,force=false){const previous=this.observedStoreGeneration;if(previous===void 0){this.observedStoreGeneration=generation;return}if(!force&&previous===generation)return;if(this.refreshState.isSuppressed())return;const marked=this.refreshState.markExtensionsChanged("extension store generation changed");if(marked||this.refreshState.needsExtensionRefresh()){this.observedStoreGeneration=generation}}readStoreGeneration(){try{const parsed=JSON.parse(fs3.readFileSync(this.storeStatePath,"utf8"));return typeof parsed.generation==="number"?parsed.generation:void 0}catch{return void 0}}};init_esbuild_shims();import*as path4 from"node:path";var debugLogger4=createDebugLogger("WORKTREE_STARTUP");var WorktreeOwnershipConflictError=class extends Error{constructor(ownerSessionId,reason="active"){const safeOwner=stripAnsiAndControl(ownerSessionId.replace(/[\p{Cf}\s]+/gu," "));super(reason==="active"?`Worktree is owned by active session ${safeOwner}`:`Worktree ownership cannot be verified for session ${safeOwner}`);this.ownerSessionId=ownerSessionId;this.name="WorktreeOwnershipConflictError"}static{__name(this,"WorktreeOwnershipConflictError")}};var DETACHED_HEAD="HEAD";async function setupStartupWorktree(rawInput,options){if(rawInput===void 0)return null;const trimmed=rawInput.trim();const launchCwd=process.cwd();const probe=new GitWorktreeService(launchCwd);const gitCheck=await probe.checkGitAvailable();if(!gitCheck.available){return{ok:false,error:`--worktree: ${gitCheck.error??"git is not available on PATH."}`}}if(/[\\/]\.qwen[\\/]worktrees[\\/]/.test(launchCwd)){return{ok:false,error:`--worktree: cannot start a new worktree from inside another worktree (cwd: ${launchCwd}). Run from the main checkout.`}}const rawRepoRoot=await probe.getRepoTopLevel();if(rawRepoRoot===null){return{ok:false,error:`--worktree: ${launchCwd} is not a git repository. Run \`git init\` first or relaunch from inside one.`}}const repoRoot=path4.resolve(rawRepoRoot);const service=repoRoot===launchCwd?probe:new GitWorktreeService(repoRoot);const prNumber=GitWorktreeService.parsePRReference(trimmed);const isPullRequest=prNumber!==null;let slug;if(prNumber!==null){slug=`pr-${prNumber}`}else if(trimmed.length===0){slug=GitWorktreeService.generateAutoSlug()}else{const validation=GitWorktreeService.validateUserWorktreeSlug(trimmed,{allowPrBackedShape:true});if(validation){return{ok:false,error:`--worktree: ${validation}`}}slug=trimmed}const[originalBranchRaw,originalHeadCommit]=await Promise.all([service.getCurrentBranch().catch(()=>void 0),service.getCurrentCommitHash().catch(()=>"")]);const originalBranch=originalBranchRaw&&originalBranchRaw!==DETACHED_HEAD?originalBranchRaw:void 0;const expectedWorktreePath=service.getUserWorktreePath(slug);const expectedBranch=worktreeBranchForSlug(slug);let registered=null;try{registered=await service.getRegisteredWorktreeBranch(expectedWorktreePath)}catch{registered=null}if(registered===null&&!isPullRequest){const reserved=GitWorktreeService.validateUserWorktreeSlug(slug);if(reserved){return{ok:false,error:`--worktree: ${reserved} Use \`--worktree=#${slug.slice("pr-".length)}\` to create the worktree for that PR.`}}}if(registered!==null){if(registered.branch!==expectedBranch){return{ok:false,error:`--worktree: ${expectedWorktreePath} is already a git worktree, but its branch is ${registered.branch} (expected ${expectedBranch}). Refusing to re-attach. Resolve the conflict manually (e.g. \`git worktree remove ${expectedWorktreePath}\`).`}}const worktreePath2=path4.resolve(expectedWorktreePath);try{process.chdir(worktreePath2)}catch(error){return{ok:false,error:`--worktree: failed to chdir into ${worktreePath2} (${error instanceof Error?error.message:String(error)}).`}}debugLogger4.debug(`setupStartupWorktree: re-attached to existing worktree at ${worktreePath2} (branch=${registered.branch})`);return{ok:true,context:{worktreePath:worktreePath2,slug,branch:registered.branch,repoRoot,originalBranch:originalBranch??DETACHED_HEAD,originalHeadCommit:registered.headCommit,isPullRequest,wasReattached:true}}}let pullRequestHeadSha=null;if(prNumber!==null){const fetchRes=await service.fetchPullRequestRef(prNumber);if(!fetchRes.success){return{ok:false,error:`--worktree: ${fetchRes.error}`}}pullRequestHeadSha=await service.resolveRef("FETCH_HEAD");if(pullRequestHeadSha===null){return{ok:false,error:`--worktree: fetched PR #${prNumber} but FETCH_HEAD did not resolve to a commit SHA. Refusing to proceed (the worktree would otherwise branch off an unknown commit).`}}}const baseRef=isPullRequest?pullRequestHeadSha:originalBranch;const result=await service.createUserWorktree(slug,baseRef,{symlinkDirectories:options?.symlinkDirectories,prBacked:isPullRequest});if(!result.success||!result.worktree){return{ok:false,error:`--worktree: ${result.error??"failed to create worktree."}`}}const worktreePath=path4.resolve(result.worktree.path);try{process.chdir(worktreePath)}catch(error){return{ok:false,error:`--worktree: created worktree at ${worktreePath} but failed to chdir into it (${error instanceof Error?error.message:String(error)}). Run \`cd ${worktreePath}\` manually.`}}return{ok:true,context:{worktreePath,slug,branch:result.worktree.branch,repoRoot,originalBranch:originalBranch??DETACHED_HEAD,originalHeadCommit:isPullRequest?pullRequestHeadSha:originalHeadCommit,isPullRequest,wasReattached:false}}}__name(setupStartupWorktree,"setupStartupWorktree");async function persistStartupWorktreeSidecar(config,context){const sessionId=config.getSessionId();const sidecarPath=config.getSessionService().getWorktreeSessionPath(sessionId);let overrodeResumedWorktree=false;let overriddenSlug;let previous=null;try{previous=await readWorktreeSession(sidecarPath)}catch(error){debugLogger4.warn(`persistStartupWorktreeSidecar: failed to read existing sidecar at ${sidecarPath} \u2014 treating as "no previous worktree" and proceeding: ${error}`);previous=null}if(previous&&previous.slug!==context.slug){overrodeResumedWorktree=true;overriddenSlug=previous.slug}let observedOwner=null;try{if(!context.wasReattached){await createWorktreeSessionMarker(context.worktreePath,sessionId)}else{observedOwner=await readWorktreeSessionMarker(context.worktreePath);if(observedOwner===null){await createWorktreeSessionMarker(context.worktreePath,sessionId)}else if(observedOwner===sessionId){await ensureWorktreeSessionMarkerExcluded(context.worktreePath)}else{const ownerLiveness=await getSessionRuntimeLiveness(observedOwner,[context.repoRoot,context.worktreePath]).catch(error=>{debugLogger4.warn(`persistStartupWorktreeSidecar: failed to check owner runtime ${observedOwner}: ${error}`);return"unknown"});if(ownerLiveness==="active"){throw new WorktreeOwnershipConflictError(observedOwner)}if(ownerLiveness==="unknown"){debugLogger4.warn(`persistStartupWorktreeSidecar: cannot verify marker owner ${observedOwner} at ${path4.join(context.worktreePath,".qwen-session")}; preserving ownership`);if(previous&&previous.slug!==context.slug){await clearWorktreeSessionDurable(sidecarPath).catch(error=>debugLogger4.warn(`persistStartupWorktreeSidecar: failed to clear the stale sidecar at ${sidecarPath}: ${error}`))}return{overrodeResumedWorktree:false,sidecarPath}}else{await replaceWorktreeSessionMarker(context.worktreePath,observedOwner,sessionId)}}}}catch(error){if(error instanceof WorktreeOwnershipConflictError)throw error;if(error instanceof WorktreeSessionMarkerOwnerChangedError){throw new WorktreeOwnershipConflictError(observedOwner??"(unknown)")}if(error instanceof WorktreeMarkerCommittedError){if(error.committedOwner!==sessionId||await readWorktreeSessionMarker(context.worktreePath)!==sessionId){throw error}}else{let markerAlreadyOwned=false;if(error.code==="EEXIST"){const currentOwner=await readWorktreeSessionMarker(context.worktreePath);if(currentOwner!==null&&currentOwner!==sessionId){throw new WorktreeOwnershipConflictError(currentOwner)}markerAlreadyOwned=currentOwner===sessionId}if(context.wasReattached&&!markerAlreadyOwned)throw error;debugLogger4.warn(`persistStartupWorktreeSidecar: marker update failed; persisting the sidecar without changing ownership: ${error}`)}}await writeWorktreeSession(sidecarPath,{slug:context.slug,worktreePath:context.worktreePath,worktreeBranch:context.branch,originalCwd:context.repoRoot,originalBranch:context.originalBranch,originalHeadCommit:context.originalHeadCommit});return{overrodeResumedWorktree,overriddenSlug,sidecarPath}}__name(persistStartupWorktreeSidecar,"persistStartupWorktreeSidecar");function buildStartupWorktreeNotice(context,override){const verb=context.wasReattached?"Re-attached to worktree":"Active worktree";const base=`[Startup] ${verb}: "${context.slug}" at ${context.worktreePath} (branch: ${context.branch}). Continue using this path for all file operations.`;if(override?.overrodeResumedWorktree&&override.overriddenSlug){return`${base}
3
+ import{registerMcpHotReload,registerModelProvidersHotReload}from"./chunk-VUI6STKU.js";import{startEarlyStartupPrefetches}from"./chunk-UYV4ZVXY.js";import{ExtensionRefreshState}from"./chunk-254YDSL2.js";import{validateAuthMethod}from"./chunk-TUS74LFI.js";import{isAcpStartupProfilerEnabled,markAcpStartup,recordAcpConfigStartupEvent}from"./chunk-XRVEZKVE.js";import{appEvents,buildDisabledSkillNamesProvider,buildEnabledSkillNamesProvider,isDebugMode,isInteractiveInvocation,loadCliConfig,parseArguments}from"./chunk-OTYPLLMT.js";import"./chunk-VURTGFJP.js";import{sanitizeTerminalText}from"./chunk-64CA3W6G.js";import"./chunk-S34YI2NO.js";import"./chunk-YMEW4TTT.js";import"./chunk-OX4QMNUW.js";import"./chunk-XJIHDVPX.js";import"./chunk-SZBGWRES.js";import"./chunk-R4VUFIDQ.js";import"./chunk-XIFNBULA.js";import"./chunk-N5KRBAK5.js";import{getHeadlessYoloSafetyWarning}from"./chunk-Z57KDB5F.js";import"./chunk-6BSQDDUG.js";import"./chunk-R7TNFTT4.js";import"./chunk-DHYCGKLG.js";import"./chunk-G2SXDY2E.js";import"./chunk-XKSB7VTV.js";import{getInstallationInfo,selectNpmBunHandoff}from"./chunk-26MNTKT2.js";import"./chunk-2HLVSWM6.js";import"./chunk-AVCBF5WL.js";import{isValidSessionId}from"./chunk-LGFF5PJA.js";import"./chunk-BWQ5AIEA.js";import"./chunk-WDR5XP3Y.js";import"./chunk-WBDNGVHU.js";import"./chunk-2QYDBHYZ.js";import"./chunk-BZAH4DTS.js";import"./chunk-L3ANU5JZ.js";import"./chunk-3SHHYK7S.js";import"./chunk-BYVINSWZ.js";import"./chunk-L5UULTGF.js";import"./chunk-AVJJ62OC.js";import"./chunk-VNV7VKZL.js";import"./chunk-KOJ7WZ63.js";import"./chunk-O6ZQAVRG.js";import"./chunk-3KZHPZVZ.js";import"./chunk-CFTFKWPW.js";import{EXTERNAL_TOOL_GUARD_PROVIDER_ATTACHED_VALUE,EXTERNAL_TOOL_GUARD_REQUIRED_VALUE,EXTERNAL_TOOL_GUARD_TOKEN_ENV,PRIVATE_EXTERNAL_TOOL_GUARD_ENV,PRIVATE_EXTERNAL_TOOL_GUARD_PROVIDER_ENV}from"./chunk-NIEO2TBE.js";import"./chunk-SPYNWVDZ.js";import"./chunk-E4UMXDOZ.js";import"./chunk-MMQY4FJL.js";import"./chunk-NY56CL2X.js";import"./chunk-TL6RUTMP.js";import"./chunk-W7V6J2VV.js";import"./chunk-B6ZRS462.js";import"./chunk-AZ3CKMCT.js";import"./chunk-TDDRZUJO.js";import"./chunk-Q6U4ODPJ.js";import"./chunk-DVC65H4X.js";import"./chunk-GT4TCQ3R.js";import"./chunk-75I3NYBD.js";import"./chunk-K6NS2HXT.js";import"./chunk-D2NY7HVY.js";import"./chunk-XAGIZY2Y.js";import{CUSTOM_SANDBOX_IMAGE_ENV_VAR,HOST_UPDATE_RELAUNCH_ENV_VAR,RELAUNCH_EXIT_CODE,SKIP_UPDATE_CHECK_ENV_VAR,UPDATE_COMPLETE_EXIT_CODE,UPDATE_ON_EXIT_MESSAGE,UPDATE_RELAUNCH_EXIT_CODE,getRelaunchExecArgv,superviseInProcess}from"./chunk-CY2QKKZA.js";import"./chunk-QO46QMCC.js";import{loadSandboxConfig}from"./chunk-WWRXBAW4.js";import"./chunk-A27RJEWD.js";import"./chunk-QN7NYEE3.js";import"./chunk-WSOEJTOC.js";import"./chunk-TKP3GAUI.js";import"./chunk-6PC6MZHL.js";import{createMinimalSettings,getFlattenedSchema,getOperatorTrustSettings,getSettingsWarnings,getUserSettingsDir,initializeLlmOutputLanguage,loadSettings}from"./chunk-EZPM4DLR.js";import"./chunk-UWCF7JIF.js";import"./chunk-UB37RBSK.js";import"./chunk-LMUSSYJH.js";import{initializeI18n,resolveLanguageSetting}from"./chunk-NO7VTKRL.js";import"./chunk-U7HZUZKP.js";import{SETTINGS_DIRECTORY_NAME,getRelaunchEnvProvenance,hasLoadedEnvironmentValues,preResolveHomeEnvOverrides}from"./chunk-ZO4F6ZWR.js";import"./chunk-PKK2D2W4.js";import{ENV_CORRUPTED_PATH,ENV_WAS_RECOVERED,QWEN_CODE_DESKTOP_ENV,QWEN_CODE_SERVE_ENV,processBootLoaderEnv,scrubAndReportInheritedLoaderEnv}from"./chunk-N3AQAZ7D.js";import{RELAUNCH_SUPERVISED_ENV}from"./chunk-E5T4R2PM.js";import{BWRAP_MIGRATION_MESSAGE,stripUtf8Bom,validateExecutionSandboxSelection}from"./chunk-DOLUT3XC.js";import"./chunk-PTHIQ7ZN.js";import{createLocalWorkflowAncestorTrustProvider}from"./chunk-4CE4GMDL.js";import"./chunk-EIPLDYEY.js";import"./chunk-IDXJIDME.js";import"./chunk-G2LTZU67.js";import"./chunk-QS2ZMQIS.js";import{PRIVATE_CONVERSATIONS_RUNTIME_ENABLE,PRIVATE_CONVERSATIONS_RUNTIME_ENV}from"./chunk-S7IKHQ6I.js";import"./chunk-SEQAVABL.js";import"./chunk-6ZEMLEK2.js";import"./chunk-O4EDHV64.js";import"./chunk-PAD5GPDY.js";import"./chunk-MD3ZEOBX.js";import"./chunk-SSYS5YN5.js";import"./chunk-X5QSFJVS.js";import{clearWorktreeSessionDurable,getSessionRuntimeLiveness,readWorktreeSession,writeWorktreeSession}from"./chunk-OMDTFGTX.js";import"./chunk-3TTHYXT3.js";import"./chunk-46VUDNCL.js";import"./chunk-MKH3EH7O.js";import"./chunk-VC3JJL7E.js";import{claimInterruptedWorkflowRuns,snapshotArgsUnavailable}from"./chunk-VKWVIWLK.js";import"./chunk-HW6SU6MX.js";import"./chunk-ZHHFNZ5J.js";import"./chunk-AKWYMQKU.js";import"./chunk-MZUOREFD.js";import"./chunk-DSKA3P2C.js";import"./chunk-7XZVMIY5.js";import"./chunk-4HSISRRA.js";import"./chunk-ZZJXFLVM.js";import"./chunk-RKDS7A4H.js";import"./chunk-QF22ILPV.js";import"./chunk-IV3HAIUN.js";import"./chunk-XFMPZINJ.js";import"./chunk-DECUAM3U.js";import"./chunk-QX7W2HY7.js";import"./chunk-HN5UYLPU.js";import"./chunk-PGRN3GZY.js";import"./chunk-HTW7PYHK.js";import"./chunk-AMGUAA4G.js";import"./chunk-YFTVFH2A.js";import"./chunk-ZBHL2CXR.js";import"./chunk-NIOS3B3V.js";import{MODEL_CATALOG_REFRESH_ENV,SessionService,buildResumeCall,closeFileWatcher,computeInitialTurnFromHistory,hasUninlinableResumeArgs,persistSessionUsage,prepareFileWatchersForProcessExit,setStartupEventSink,watch}from"./chunk-7XQ5D34E.js";import"./chunk-R2EHHA2C.js";import"./chunk-YK7NDQKM.js";import"./chunk-ZLZF2ZDD.js";import"./chunk-OMSVOFTC.js";import"./chunk-PHIPLV2I.js";import"./chunk-ZOTKZI2P.js";import"./chunk-A6G5TAIF.js";import"./chunk-YVBHCSZD.js";import"./chunk-FIXDX63I.js";import"./chunk-T7CHK6C2.js";import"./chunk-PT7NZBDY.js";import"./chunk-TWP72VRH.js";import"./chunk-UYEWRLGD.js";import"./chunk-QVPT37XZ.js";import"./chunk-YVD4O5ZB.js";import"./chunk-T6W33SET.js";import"./chunk-WK2IBT6D.js";import{canUseRipgrep}from"./chunk-QZV4PFQK.js";import{GitWorktreeService,WorktreeMarkerCommittedError,WorktreeSessionMarkerOwnerChangedError,createWorktreeSessionMarker,ensureWorktreeSessionMarkerExcluded,readWorktreeSessionMarker,replaceWorktreeSessionMarker,worktreeBranchForSlug}from"./chunk-ILECDNJX.js";import"./chunk-QXQGUM3Y.js";import"./chunk-UQ7IROJH.js";import"./chunk-SZCBUCNH.js";import"./chunk-BEKROCWN.js";import"./chunk-5SUFJTQQ.js";import"./chunk-BYU42MLK.js";import"./chunk-JWQXU3SR.js";import"./chunk-5LZ2DPLH.js";import"./chunk-XQJOZDV7.js";import"./chunk-CV2UAEZA.js";import"./chunk-FUBDS3AV.js";import"./chunk-HW6AWS7W.js";import"./chunk-KLC3OD2M.js";import"./chunk-Q5IZXKUJ.js";import"./chunk-G5PYYZMM.js";import"./chunk-BG67XABA.js";import"./chunk-OBOU4ZZM.js";import{QWEN_CODE_SIMPLE_ENV_VAR,isBareMode}from"./chunk-D7XCQWP2.js";import"./chunk-AE5OMKRY.js";import"./chunk-OBV7RNHV.js";import"./chunk-7CQMWEMY.js";import"./chunk-GOZYWU4B.js";import"./chunk-OUC3WICA.js";import"./chunk-JZK2WGXA.js";import"./chunk-MPHSE7M4.js";import"./chunk-S2ZKZXHX.js";import"./chunk-7UK4WJWS.js";import"./chunk-4GP3PH7Z.js";import"./chunk-4QQKOW5M.js";import"./chunk-OV3EBH6J.js";import"./chunk-EBMCWXGZ.js";import"./chunk-XZTE4YTN.js";import"./chunk-LSASUDF2.js";import"./chunk-2V5EKGDK.js";import"./chunk-MOKVM4PT.js";import"./chunk-YIW3H46P.js";import"./chunk-EOMRLUNZ.js";import"./chunk-4ZRCV3JY.js";import"./chunk-TL6MLBXR.js";import"./chunk-NMY3PYNO.js";import"./chunk-YGLM5XPP.js";import"./chunk-WGNF7FPC.js";import{resolveBundleDir}from"./chunk-4NPYOXJO.js";import"./chunk-MWGB5RCF.js";import"./chunk-SCD5TUBG.js";import"./chunk-NTRFETZB.js";import{require_shell_quote}from"./chunk-TL3SF2GA.js";import"./chunk-LMJPU2JM.js";import"./chunk-VFB6Q74I.js";import"./chunk-4JNHUZ7M.js";import"./chunk-SW54YEPK.js";import"./chunk-ZCRL73DT.js";import"./chunk-A6LT3FIJ.js";import"./chunk-S6RXVOY6.js";import"./chunk-YZFNBUKG.js";import"./chunk-AGEDDL7Z.js";import"./chunk-2NJJHZ52.js";import"./chunk-BN4FIQ77.js";import"./chunk-X64RXJQQ.js";import"./chunk-HETUGUHE.js";import"./chunk-ET2Z7ZGF.js";import"./chunk-XFPYXD2P.js";import"./chunk-3YWXKSOI.js";import"./chunk-5CWTKFI4.js";import"./chunk-C4MVD5OI.js";import"./chunk-Z2W7S4O4.js";import"./chunk-476F6QIM.js";import"./chunk-4R67LXKL.js";import"./chunk-FQRF6B65.js";import{logUserPrompt,uiTelemetryService}from"./chunk-ZWPSBU7K.js";import"./chunk-UQFTXKEB.js";import"./chunk-HDGTWJ24.js";import"./chunk-W5NWIGKO.js";import"./chunk-KVA6DHHF.js";import"./chunk-PWOQASXT.js";import"./chunk-K7JCVESI.js";import"./chunk-Y6HHV4LC.js";import"./chunk-RP57XAJ2.js";import"./chunk-Z6AR5XE5.js";import"./chunk-7DOOXUDG.js";import"./chunk-77V43YOE.js";import"./chunk-7U7CWMP7.js";import{PRIVATE_ACP_CAPABILITY_ENV}from"./chunk-EFTJIDS3.js";import"./chunk-4DIWAQ5G.js";import"./chunk-Q6UAOTP3.js";import"./chunk-HQZTAA2U.js";import{MODEL_CATALOG_ENV,MODEL_CATALOG_URL_ENV}from"./chunk-GOR7FFVE.js";import"./chunk-4ZBZL23U.js";import"./chunk-BMHYEQTI.js";import"./chunk-ZZZAYAJW.js";import"./chunk-XMANRGPK.js";import"./chunk-3XVPZY7X.js";import"./chunk-KQX4H2D3.js";import"./chunk-URNNJMIC.js";import"./chunk-GU22I6TY.js";import"./chunk-YEYW7PPR.js";import{handleUncaughtException,isExpectedPtyRaceError}from"./chunk-SJCE6UFF.js";import{clearInheritedPeerMessagingEnv}from"./chunk-NPAX2UFU.js";import{finalizeStartupProfile,isStartupProfilerEnabled,profileCheckpoint,recordStartupEvent,setInteractiveMode}from"./chunk-H4XFFVZ2.js";import"./chunk-X7QN6R6K.js";import"./chunk-EO57EBMH.js";import{cleanupCheckpoints,registerCleanup,runExitCleanup}from"./chunk-EQOHDAYU.js";import{writeStderrLine,writeStderrLineSafe}from"./chunk-M4ECEHLX.js";import{stripAnsiAndControl}from"./chunk-DBRQGEEI.js";import"./chunk-B3ZFUGTC.js";import"./chunk-IRINPFG7.js";import"./chunk-6GTPLW7K.js";import"./chunk-NGVRCUYD.js";import"./chunk-5DTFN37U.js";import"./chunk-2YUBAWQ6.js";import"./chunk-O5EKX7LG.js";import"./chunk-TM6ZCBR7.js";import"./chunk-SVAPAMMG.js";import"./chunk-3KUHQGOS.js";import"./chunk-I6S7NGX3.js";import"./chunk-SBZFGYYS.js";import{createDebugLogger,isDebugLogFileEnabled,isDebugLoggingDegraded}from"./chunk-JAUJI56S.js";import"./chunk-I4H7NUVP.js";import{Storage}from"./chunk-EPODBRBP.js";import{isSubpath}from"./chunk-OKN3Z5C5.js";import{FatalSandboxError,getErrorMessage}from"./chunk-XYB7GC5U.js";import"./chunk-2UOMCYQG.js";import"./chunk-I7L2TX4M.js";import"./chunk-MK3OONRA.js";import"./chunk-COGTQ5KZ.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import dns from"node:dns";import fs7 from"node:fs";import os3 from"node:os";import path8 from"node:path";import v8 from"node:v8";init_esbuild_shims();import*as fs from"node:fs";import*as path from"node:path";var debugLogger=createDebugLogger("SETTINGS_WATCHER");function collectChangedKeys(before,after,prefix=""){const changed=[];const keys=new Set([...Object.keys(before),...Object.keys(after)]);for(const key of keys){const keyPath=prefix?`${prefix}.${key}`:key;const beforeValue=before[key];const afterValue=after[key];if(isPlainObject(beforeValue)&&isPlainObject(afterValue)){changed.push(...collectChangedKeys(beforeValue,afterValue,keyPath))}else if(JSON.stringify(beforeValue)!==JSON.stringify(afterValue)){changed.push(keyPath)}}return changed}__name(collectChangedKeys,"collectChangedKeys");function isPlainObject(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isPlainObject,"isPlainObject");function isRestartRequiredKey(changedPath){const flattened=getFlattenedSchema();const parts=changedPath.split(".");for(let i=parts.length;i>0;i--){const candidate=parts.slice(0,i).join(".");const definition=flattened[candidate];if(definition)return definition.requiresRestart===true}return false}__name(isRestartRequiredKey,"isRestartRequiredKey");var SettingsWatcher=class _SettingsWatcher{static{__name(this,"SettingsWatcher")}settings;watchers=new Map;watchStage=new Map;watchGeneration=new Map;changeListeners=new Set;refreshTimer=null;pendingScopeChanges=new Set;processing=false;started=false;static DEBOUNCE_MS=300;static LISTENER_TIMEOUT_MS=3e4;constructor(settings){this.settings=settings}startWatching(){if(this.started)return;this.started=true;for(const{scope,settingsPath}of this.getScopePaths()){if(!settingsPath)continue;const dir=path.dirname(settingsPath);if(fs.existsSync(dir)){this.watchTargetDir(scope,settingsPath)}else{this.watchParentForDir(scope,settingsPath)}}}watchTargetDir(scope,settingsPath){const dir=path.dirname(settingsPath);const targetBasename=path.basename(settingsPath);const gen=this.bumpGeneration(scope);try{const watcher=watch(dir,{ignoreInitial:true,depth:0,ignored:__name((filePath,stats)=>{if(stats&&!stats.isFile()&&!stats.isDirectory())return true;return false},"ignored")}).on("all",(event,changedPath)=>{if(this.watchGeneration.get(scope)!==gen)return;if(event==="unlinkDir"&&changedPath===dir){void this.demoteScope(scope,settingsPath);return}if(path.basename(changedPath)!==targetBasename)return;this.scheduleRefresh(scope)}).on("error",error=>{debugLogger.warn(`Settings watcher error for ${dir}:`,error)});this.watchers.set(scope,watcher);this.watchStage.set(scope,"target")}catch(error){debugLogger.warn(`Failed to start settings watcher for ${scope} (${dir}):`,error)}}watchParentForDir(scope,settingsPath){const dir=path.dirname(settingsPath);const parentDir=path.dirname(dir);const dirBasename=path.basename(dir);const gen=this.bumpGeneration(scope);try{const watcher=watch(parentDir,{ignoreInitial:true,depth:0,ignored:__name(filePath=>filePath!==parentDir&&path.basename(filePath)!==dirBasename,"ignored")}).on("all",(_event,changedPath)=>{if(this.watchGeneration.get(scope)!==gen)return;if(path.basename(changedPath)!==dirBasename)return;void this.promoteScope(scope,settingsPath)}).on("error",error=>{debugLogger.warn(`Settings bootstrap watcher error for ${parentDir}:`,error)});this.watchers.set(scope,watcher);this.watchStage.set(scope,"bootstrap")}catch(error){debugLogger.warn(`Failed to start settings bootstrap watcher for ${scope} (${parentDir}):`,error);return}if(fs.existsSync(dir)){void this.promoteScope(scope,settingsPath)}}async promoteScope(scope,settingsPath){if(this.watchStage.get(scope)!=="bootstrap")return;await this.replaceWatcher(scope);if(!this.started)return;this.watchTargetDir(scope,settingsPath);this.scheduleRefresh(scope)}async demoteScope(scope,settingsPath){if(this.watchStage.get(scope)!=="target")return;await this.replaceWatcher(scope);if(!this.started)return;this.watchParentForDir(scope,settingsPath);this.scheduleRefresh(scope)}async replaceWatcher(scope){this.bumpGeneration(scope);const watcher=this.watchers.get(scope);this.watchers.delete(scope);this.watchStage.delete(scope);if(watcher){try{await closeFileWatcher(watcher)}catch(err){debugLogger.warn("Settings watcher close error:",err)}}}bumpGeneration(scope){const next=(this.watchGeneration.get(scope)??0)+1;this.watchGeneration.set(scope,next);return next}stopWatching(){if(!this.started)return;this.started=false;for(const[,watcher]of this.watchers){closeFileWatcher(watcher).catch(err=>{debugLogger.warn("Settings watcher close error:",err)})}this.watchers.clear();this.watchStage.clear();for(const scope of this.watchGeneration.keys()){this.bumpGeneration(scope)}if(this.refreshTimer){clearTimeout(this.refreshTimer);this.refreshTimer=null}this.pendingScopeChanges.clear()}addChangeListener(listener){this.changeListeners.add(listener);return()=>{this.changeListeners.delete(listener)}}getScopePaths(){const paths=[{scope:"User",settingsPath:this.settings.user.path}];if(this.settings.workspaceSettingsActive){paths.push({scope:"Workspace",settingsPath:this.settings.workspace.path})}return paths}scheduleRefresh(scope){this.pendingScopeChanges.add(scope);if(this.refreshTimer)clearTimeout(this.refreshTimer);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null;void this.drainPendingChanges().catch(err=>{debugLogger.warn("Settings watcher refresh error:",err)})},_SettingsWatcher.DEBOUNCE_MS)}async drainPendingChanges(){if(this.processing)return;this.processing=true;try{while(this.pendingScopeChanges.size>0){const scopes=new Set(this.pendingScopeChanges);this.pendingScopeChanges.clear();await this.handleChange(scopes)}}finally{this.processing=false}}async handleChange(changedScopes){const events=[];for(const scope of changedScopes){const file=this.settings.forScope(scope);const before=structuredClone(file.settings??{});const existedBefore=file.rawJson!==void 0;this.settings.reloadScopeFromDisk(scope);const after=file.settings??{};const existsNow=file.rawJson!==void 0;const changedKeys=collectChangedKeys(before,after);if(changedKeys.length===0){continue}const hasHotReloadableChange=changedKeys.some(key=>!isRestartRequiredKey(key));if(!hasHotReloadableChange){continue}events.push({scope,path:file.path,changeType:!existedBefore&&existsNow?"created":existedBefore&&!existsNow?"deleted":"modified"})}if(events.length>0){await this.notifyListeners(events)}}async notifyListeners(events){const TIMEOUT_MS=_SettingsWatcher.LISTENER_TIMEOUT_MS;const withTimeout=__name(p=>{let timerId;const timeoutPromise=new Promise((_,reject)=>{timerId=setTimeout(()=>reject(new Error(`settings change listener timeout after ${TIMEOUT_MS}ms`)),TIMEOUT_MS);if(typeof timerId==="object"&&timerId!==null&&"unref"in timerId){timerId.unref()}});return Promise.race([p,timeoutPromise]).finally(()=>{if(timerId!==void 0)clearTimeout(timerId)})},"withTimeout");const results=await Promise.allSettled(Array.from(this.changeListeners).map(listener=>withTimeout(Promise.resolve().then(()=>listener(events)))));for(const result of results){if(result.status==="rejected"){debugLogger.warn("Settings change listener error:",result.reason)}}}};init_esbuild_shims();import*as fs2 from"node:fs";import*as path2 from"node:path";var debugLogger2=createDebugLogger("LSP_CONFIG_WATCHER");var LspConfigWatcher=class _LspConfigWatcher{constructor(workspaceRoot){this.workspaceRoot=workspaceRoot;this.configPath=path2.join(workspaceRoot,".lsp.json");this.lastSnapshot=this.readSnapshot()}static{__name(this,"LspConfigWatcher")}watcher;listener;refreshTimer=null;activeDrain;processing=false;pending=false;started=false;lastSnapshot;configPath;static DEBOUNCE_MS=300;static LISTENER_TIMEOUT_MS=3e4;startWatching(listener){if(this.started)return;debugLogger2.info(`Starting LSP config watcher for ${this.configPath}`);try{const watcher=watch(this.workspaceRoot,{ignoreInitial:true,depth:0}).on("all",(_event,changedPath)=>{if(path2.basename(changedPath)!==".lsp.json")return;this.scheduleRefresh()}).on("error",error=>{debugLogger2.warn(`LSP config watcher error for ${this.workspaceRoot}:`,error)});this.watcher=watcher;this.listener=listener;this.started=true}catch(error){this.watcher=void 0;this.listener=void 0;this.started=false;debugLogger2.warn(`Failed to start LSP config watcher for ${this.workspaceRoot}:`,error)}}async stopWatching(){if(!this.started)return;this.started=false;debugLogger2.info(`Stopping LSP config watcher for ${this.configPath}`);if(this.refreshTimer){clearTimeout(this.refreshTimer);this.refreshTimer=null}this.pending=false;await this.activeDrain;this.listener=void 0;try{await closeFileWatcher(this.watcher)}catch(error){debugLogger2.warn("LSP config watcher close error:",error)}this.watcher=void 0}scheduleRefresh(){if(!this.started)return;this.pending=true;if(this.refreshTimer)clearTimeout(this.refreshTimer);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null;if(this.processing)return;const activeDrain=this.drainPendingChange().catch(error=>{debugLogger2.warn("LSP config watcher refresh error:",error)});this.activeDrain=activeDrain;void activeDrain.finally(()=>{if(this.activeDrain===activeDrain){this.activeDrain=void 0}})},_LspConfigWatcher.DEBOUNCE_MS);if(typeof this.refreshTimer==="object"&&this.refreshTimer!==null&&"unref"in this.refreshTimer){this.refreshTimer.unref()}}async drainPendingChange(){if(this.processing)return;this.processing=true;try{while(this.pending){this.pending=false;await this.handleChange()}}finally{this.processing=false}}async handleChange(){const before=this.lastSnapshot;const after=this.readSnapshot();if(after.exists&&after.canonical===void 0){debugLogger2.warn(`Invalid .lsp.json; keeping existing LSP runtime state.`);const notified2=await this.notifyListener({path:this.configPath,changeType:"invalid",error:after.error??"Invalid JSON in .lsp.json; existing LSP runtime state is unchanged."});if(notified2){this.lastSnapshot=after}return}const changed=before.exists!==after.exists||before.canonical!==after.canonical;if(!changed){this.lastSnapshot=after;return}const event={path:this.configPath,changeType:!before.exists&&after.exists?"created":before.exists&&!after.exists?"deleted":"modified"};debugLogger2.info(`LSP config changed: ${event.changeType} ${event.path}`);const notified=await this.notifyListener(event);if(notified){this.lastSnapshot=after}}readSnapshot(){let raw;try{raw=fs2.readFileSync(this.configPath,"utf-8")}catch(error){if(error.code==="ENOENT"){return{exists:false}}debugLogger2.warn("Failed to read .lsp.json:",error);return{exists:true,error:"Failed to read .lsp.json; existing LSP runtime state is unchanged."}}try{const parsed=JSON.parse(stripUtf8Bom(raw));return{exists:true,canonical:canonicalize(parsed)}}catch(error){debugLogger2.warn("Failed to parse .lsp.json:",error);return{exists:true,error:"Invalid JSON in .lsp.json; existing LSP runtime state is unchanged."}}}async notifyListener(event){if(!this.listener)return true;const TIMEOUT_MS=_LspConfigWatcher.LISTENER_TIMEOUT_MS;let timerId;const timeoutPromise=new Promise((_,reject)=>{timerId=setTimeout(()=>reject(new Error(`LSP config change listener timeout after ${TIMEOUT_MS}ms`)),TIMEOUT_MS);if(typeof timerId==="object"&&timerId!==null&&"unref"in timerId){timerId.unref()}});const listenerPromise=Promise.resolve().then(()=>this.listener?.(event));try{await Promise.race([listenerPromise,timeoutPromise]);return true}catch(error){debugLogger2.warn("LSP config change listener error:",error);return false}finally{if(timerId!==void 0)clearTimeout(timerId);void listenerPromise.catch(()=>void 0)}}};function canonicalize(value){return JSON.stringify(sortJsonValue(value))}__name(canonicalize,"canonicalize");function sortJsonValue(value){if(Array.isArray(value)){return value.map(sortJsonValue)}if(value&&typeof value==="object"){const sorted=Object.create(null);for(const key of Object.keys(value).sort()){sorted[key]=sortJsonValue(value[key])}return sorted}return value}__name(sortJsonValue,"sortJsonValue");init_esbuild_shims();import*as fs3 from"node:fs";import*as path3 from"node:path";var debugLogger3=createDebugLogger("EXTENSION_FILE_WATCHER");var TOP_LEVEL_FILES=new Set(["extension-enablement.json"]);var EXTENSION_FILES=new Set(["qwen-extension.json",".qwen-extension-install.json"]);var AUTO_REFRESH_DIRS=new Set(["commands","skills","agents","workflows"]);var STALE_DIRS=new Set(["hooks"]);var ExtensionFileWatcher=class{constructor(config,extensionsDir=Storage.getUserExtensionsDir(),refreshState=new ExtensionRefreshState,storeStatePath){this.config=config;this.extensionsDir=extensionsDir;this.refreshState=refreshState;this.storeStatePath=storeStatePath??path3.join(path3.dirname(this.extensionsDir),"extension-store","state.json");this.observedStoreGeneration=this.readStoreGeneration()}static{__name(this,"ExtensionFileWatcher")}watcher;bootstrapWatcher;mutationListenerDisposer;mutationSuppressionEnds=new Map;staleFiles=new Set;watching=false;watchGeneration=0;storeStatePath;generationPoller;observedStoreGeneration;startWatching(){this.stopWatching();this.watching=true;const generation=++this.watchGeneration;this.subscribeExtensionManagerMutations();this.staleFiles=this.getStaleFiles();const roots=this.getWatchRoots();if(roots.length>0){this.watcher=watch(roots,{ignoreInitial:true,followSymlinks:false,awaitWriteFinish:{stabilityThreshold:200,pollInterval:50},ignored:__name(filePath=>this.isIgnored(filePath),"ignored")}).on("all",(event,changedPath)=>{if(generation!==this.watchGeneration)return;const resolvedPath=path3.resolve(changedPath);const action=this.getRefreshAction(event,resolvedPath);let marked=false;if(action==="auto"){marked=this.refreshState.markExtensionContentChanged("extension content files changed")}else if(action==="stale"){marked=this.refreshState.markExtensionsChanged("extension files changed")}debugLogger3.debug("Extension file event classified",{event,path:resolvedPath,action,marked})}).on("error",error=>{debugLogger3.warn("Extension file watcher error:",error)})}if(!fs3.existsSync(this.extensionsDir)){this.watchExtensionsParent()}this.startGenerationPolling()}stopWatching(){const watcher=this.watcher;const bootstrapWatcher=this.bootstrapWatcher;this.watcher=void 0;this.bootstrapWatcher=void 0;this.watching=false;this.watchGeneration++;if(this.generationPoller)clearInterval(this.generationPoller);this.generationPoller=void 0;this.mutationListenerDisposer?.();this.mutationListenerDisposer=void 0;this.endPendingMutationSuppressions();closeFileWatcher(watcher).catch(error=>{debugLogger3.warn("Extension file watcher close error:",error)});closeFileWatcher(bootstrapWatcher).catch(error=>{debugLogger3.warn("Extension bootstrap watcher close error:",error)})}restartWatching(){this.startWatching()}getWatchRoots(){const roots=new Set;if(fs3.existsSync(this.extensionsDir)){roots.add(this.extensionsDir)}roots.add(this.storeStatePath);for(const extension of this.config.getActiveExtensions()){if(extension.installMetadata?.type==="link"){const rawSource=extension.installMetadata.source;const source=rawSource?path3.resolve(rawSource):void 0;if(source&&fs3.existsSync(source)){roots.add(source)}}}return[...roots]}getStaleFiles(){const files=new Set;for(const extension of this.config.getActiveExtensions()){for(const filePath of extension.contextFiles){files.add(path3.resolve(filePath))}const configured=extension.config.contextFileName;const names=configured===void 0?["QWEN.md"]:Array.isArray(configured)?configured:[configured];for(const name of names){files.add(path3.resolve(extension.path,name))}this.addManifestFileReference(files,extension.path,extension.config.hooks);this.addManifestFileReference(files,extension.path,extension.config.lspServers)}return files}addManifestFileReference(files,extensionPath,value){if(typeof value!=="string")return;files.add(path3.isAbsolute(value)?path3.resolve(value):path3.resolve(extensionPath,value))}watchExtensionsParent(){this.closeBootstrapWatcher();const parentDir=path3.dirname(this.extensionsDir);const dirBasename=path3.basename(this.extensionsDir);const generation=this.watchGeneration;this.bootstrapWatcher=watch(parentDir,{ignoreInitial:true,followSymlinks:false,depth:0,ignored:__name(filePath=>filePath!==parentDir&&path3.basename(filePath)!==dirBasename,"ignored")}).on("all",(_event,changedPath)=>{if(generation!==this.watchGeneration)return;if(path3.basename(changedPath)!==dirBasename)return;if(!fs3.existsSync(this.extensionsDir))return;this.refreshState.markExtensionsChanged("extension directory created");queueMicrotask(()=>{if(this.watching){this.restartWatching()}})}).on("error",error=>{debugLogger3.warn("Extension bootstrap watcher error:",error)})}getRefreshAction(event,changedPath){if(changedPath===path3.resolve(this.storeStatePath)){const generation=this.readStoreGeneration();if(generation!==void 0){this.markStoreGenerationChanged(generation,true)}else{this.refreshState.markExtensionsChanged("extension store generation changed")}return false}if(this.staleFiles.has(changedPath)){return"stale"}if(changedPath===path3.resolve(this.extensionsDir)){if(event==="unlinkDir"){this.watchExtensionsParent();return"stale"}return false}if(isSubpath(this.extensionsDir,changedPath)){return this.getUserExtensionRefreshAction(event,changedPath)}return this.getLinkedExtensionRefreshAction(changedPath)}getUserExtensionRefreshAction(event,changedPath){const relative2=path3.relative(this.extensionsDir,changedPath);const parts=relative2.split(path3.sep).filter(Boolean);if(parts.length===1){if(TOP_LEVEL_FILES.has(parts[0]))return"stale";if(event==="addDir"||event==="unlinkDir")return"stale";return false}if(!fs3.existsSync(path3.join(this.extensionsDir,parts[0],"qwen-extension.json"))){return"stale"}const runtimePath=parts.slice(1);return this.getRuntimePathRefreshAction(runtimePath)}getLinkedExtensionRefreshAction(changedPath){for(const extension of this.config.getActiveExtensions()){if(extension.installMetadata?.type!=="link")continue;const rawSource=extension.installMetadata.source;const source=rawSource?path3.resolve(rawSource):void 0;if(!source||!isSubpath(source,changedPath))continue;const relative2=path3.relative(source,changedPath);const parts=relative2.split(path3.sep).filter(Boolean);return parts.length===0?"stale":this.getRuntimePathRefreshAction(parts)}return false}getRuntimePathRefreshAction(parts){if(EXTENSION_FILES.has(parts[0])||STALE_DIRS.has(parts[0])){return"stale"}if(AUTO_REFRESH_DIRS.has(parts[0])){return"auto"}return false}isIgnored(filePath){const normalized=filePath.replace(/\\/g,"/");const searchablePath=`/${normalized}/`;if(searchablePath.includes("/node_modules/")||searchablePath.includes("/.git/")){return true}const basename4=normalized.split("/").pop()??"";return basename4===".DS_Store"||basename4.endsWith("~")||basename4.endsWith(".swp")||basename4.endsWith(".tmp")}subscribeExtensionManagerMutations(){const manager=this.config.getExtensionManager();this.mutationListenerDisposer=manager.addMutationListener(event=>{if(event.phase==="start"){this.mutationSuppressionEnds.set(event.id,this.refreshState.beginSuppression(()=>this.restartAfterMutation()));return}const endSuppression=this.mutationSuppressionEnds.get(event.id);if(!endSuppression){return}this.mutationSuppressionEnds.delete(event.id);endSuppression()})}endPendingMutationSuppressions(){const endSuppressions=[...this.mutationSuppressionEnds.values()];this.mutationSuppressionEnds.clear();for(const endSuppression of endSuppressions){endSuppression()}}restartAfterMutation(){if(this.watching){this.restartWatching()}}closeBootstrapWatcher(){const bootstrapWatcher=this.bootstrapWatcher;this.bootstrapWatcher=void 0;closeFileWatcher(bootstrapWatcher).catch(error=>{debugLogger3.warn("Extension bootstrap watcher close error:",error)})}startGenerationPolling(){if(this.generationPoller)clearInterval(this.generationPoller);this.pollStoreGeneration();this.generationPoller=setInterval(()=>this.pollStoreGeneration(),3e4);this.generationPoller.unref?.()}pollStoreGeneration(){const generation=this.readStoreGeneration();if(generation===void 0)return;this.markStoreGenerationChanged(generation)}markStoreGenerationChanged(generation,force=false){const previous=this.observedStoreGeneration;if(previous===void 0){this.observedStoreGeneration=generation;return}if(!force&&previous===generation)return;if(this.refreshState.isSuppressed())return;const marked=this.refreshState.markExtensionsChanged("extension store generation changed");if(marked||this.refreshState.needsExtensionRefresh()){this.observedStoreGeneration=generation}}readStoreGeneration(){try{const parsed=JSON.parse(fs3.readFileSync(this.storeStatePath,"utf8"));return typeof parsed.generation==="number"?parsed.generation:void 0}catch{return void 0}}};init_esbuild_shims();import*as path4 from"node:path";var debugLogger4=createDebugLogger("WORKTREE_STARTUP");var WorktreeOwnershipConflictError=class extends Error{constructor(ownerSessionId,reason="active"){const safeOwner=stripAnsiAndControl(ownerSessionId.replace(/[\p{Cf}\s]+/gu," "));super(reason==="active"?`Worktree is owned by active session ${safeOwner}`:`Worktree ownership cannot be verified for session ${safeOwner}`);this.ownerSessionId=ownerSessionId;this.name="WorktreeOwnershipConflictError"}static{__name(this,"WorktreeOwnershipConflictError")}};var DETACHED_HEAD="HEAD";async function setupStartupWorktree(rawInput,options){if(rawInput===void 0)return null;const trimmed=rawInput.trim();const launchCwd=process.cwd();const probe=new GitWorktreeService(launchCwd);const gitCheck=await probe.checkGitAvailable();if(!gitCheck.available){return{ok:false,error:`--worktree: ${gitCheck.error??"git is not available on PATH."}`}}if(/[\\/]\.qwen[\\/]worktrees[\\/]/.test(launchCwd)){return{ok:false,error:`--worktree: cannot start a new worktree from inside another worktree (cwd: ${launchCwd}). Run from the main checkout.`}}const rawRepoRoot=await probe.getRepoTopLevel();if(rawRepoRoot===null){return{ok:false,error:`--worktree: ${launchCwd} is not a git repository. Run \`git init\` first or relaunch from inside one.`}}const repoRoot=path4.resolve(rawRepoRoot);const service=repoRoot===launchCwd?probe:new GitWorktreeService(repoRoot);const prNumber=GitWorktreeService.parsePRReference(trimmed);const isPullRequest=prNumber!==null;let slug;if(prNumber!==null){slug=`pr-${prNumber}`}else if(trimmed.length===0){slug=GitWorktreeService.generateAutoSlug()}else{const validation=GitWorktreeService.validateUserWorktreeSlug(trimmed,{allowPrBackedShape:true});if(validation){return{ok:false,error:`--worktree: ${validation}`}}slug=trimmed}const[originalBranchRaw,originalHeadCommit]=await Promise.all([service.getCurrentBranch().catch(()=>void 0),service.getCurrentCommitHash().catch(()=>"")]);const originalBranch=originalBranchRaw&&originalBranchRaw!==DETACHED_HEAD?originalBranchRaw:void 0;const expectedWorktreePath=service.getUserWorktreePath(slug);const expectedBranch=worktreeBranchForSlug(slug);let registered=null;try{registered=await service.getRegisteredWorktreeBranch(expectedWorktreePath)}catch{registered=null}if(registered===null&&!isPullRequest){const reserved=GitWorktreeService.validateUserWorktreeSlug(slug);if(reserved){return{ok:false,error:`--worktree: ${reserved} Use \`--worktree=#${slug.slice("pr-".length)}\` to create the worktree for that PR.`}}}if(registered!==null){if(registered.branch!==expectedBranch){return{ok:false,error:`--worktree: ${expectedWorktreePath} is already a git worktree, but its branch is ${registered.branch} (expected ${expectedBranch}). Refusing to re-attach. Resolve the conflict manually (e.g. \`git worktree remove ${expectedWorktreePath}\`).`}}const worktreePath2=path4.resolve(expectedWorktreePath);try{process.chdir(worktreePath2)}catch(error){return{ok:false,error:`--worktree: failed to chdir into ${worktreePath2} (${error instanceof Error?error.message:String(error)}).`}}debugLogger4.debug(`setupStartupWorktree: re-attached to existing worktree at ${worktreePath2} (branch=${registered.branch})`);return{ok:true,context:{worktreePath:worktreePath2,slug,branch:registered.branch,repoRoot,originalBranch:originalBranch??DETACHED_HEAD,originalHeadCommit:registered.headCommit,isPullRequest,wasReattached:true}}}let pullRequestHeadSha=null;if(prNumber!==null){const fetchRes=await service.fetchPullRequestRef(prNumber);if(!fetchRes.success){return{ok:false,error:`--worktree: ${fetchRes.error}`}}pullRequestHeadSha=await service.resolveRef("FETCH_HEAD");if(pullRequestHeadSha===null){return{ok:false,error:`--worktree: fetched PR #${prNumber} but FETCH_HEAD did not resolve to a commit SHA. Refusing to proceed (the worktree would otherwise branch off an unknown commit).`}}}const baseRef=isPullRequest?pullRequestHeadSha:originalBranch;const result=await service.createUserWorktree(slug,baseRef,{symlinkDirectories:options?.symlinkDirectories,prBacked:isPullRequest});if(!result.success||!result.worktree){return{ok:false,error:`--worktree: ${result.error??"failed to create worktree."}`}}const worktreePath=path4.resolve(result.worktree.path);try{process.chdir(worktreePath)}catch(error){return{ok:false,error:`--worktree: created worktree at ${worktreePath} but failed to chdir into it (${error instanceof Error?error.message:String(error)}). Run \`cd ${worktreePath}\` manually.`}}return{ok:true,context:{worktreePath,slug,branch:result.worktree.branch,repoRoot,originalBranch:originalBranch??DETACHED_HEAD,originalHeadCommit:isPullRequest?pullRequestHeadSha:originalHeadCommit,isPullRequest,wasReattached:false}}}__name(setupStartupWorktree,"setupStartupWorktree");async function persistStartupWorktreeSidecar(config,context){const sessionId=config.getSessionId();const sidecarPath=config.getSessionService().getWorktreeSessionPath(sessionId);let overrodeResumedWorktree=false;let overriddenSlug;let previous=null;try{previous=await readWorktreeSession(sidecarPath)}catch(error){debugLogger4.warn(`persistStartupWorktreeSidecar: failed to read existing sidecar at ${sidecarPath} \u2014 treating as "no previous worktree" and proceeding: ${error}`);previous=null}if(previous&&previous.slug!==context.slug){overrodeResumedWorktree=true;overriddenSlug=previous.slug}let observedOwner=null;try{if(!context.wasReattached){await createWorktreeSessionMarker(context.worktreePath,sessionId)}else{observedOwner=await readWorktreeSessionMarker(context.worktreePath);if(observedOwner===null){await createWorktreeSessionMarker(context.worktreePath,sessionId)}else if(observedOwner===sessionId){await ensureWorktreeSessionMarkerExcluded(context.worktreePath)}else{const ownerLiveness=await getSessionRuntimeLiveness(observedOwner,[context.repoRoot,context.worktreePath]).catch(error=>{debugLogger4.warn(`persistStartupWorktreeSidecar: failed to check owner runtime ${observedOwner}: ${error}`);return"unknown"});if(ownerLiveness==="active"){throw new WorktreeOwnershipConflictError(observedOwner)}if(ownerLiveness==="unknown"){debugLogger4.warn(`persistStartupWorktreeSidecar: cannot verify marker owner ${observedOwner} at ${path4.join(context.worktreePath,".qwen-session")}; preserving ownership`);if(previous&&previous.slug!==context.slug){await clearWorktreeSessionDurable(sidecarPath).catch(error=>debugLogger4.warn(`persistStartupWorktreeSidecar: failed to clear the stale sidecar at ${sidecarPath}: ${error}`))}return{overrodeResumedWorktree:false,sidecarPath}}else{await replaceWorktreeSessionMarker(context.worktreePath,observedOwner,sessionId)}}}}catch(error){if(error instanceof WorktreeOwnershipConflictError)throw error;if(error instanceof WorktreeSessionMarkerOwnerChangedError){throw new WorktreeOwnershipConflictError(observedOwner??"(unknown)")}if(error instanceof WorktreeMarkerCommittedError){if(error.committedOwner!==sessionId||await readWorktreeSessionMarker(context.worktreePath)!==sessionId){throw error}}else{let markerAlreadyOwned=false;if(error.code==="EEXIST"){const currentOwner=await readWorktreeSessionMarker(context.worktreePath);if(currentOwner!==null&&currentOwner!==sessionId){throw new WorktreeOwnershipConflictError(currentOwner)}markerAlreadyOwned=currentOwner===sessionId}if(context.wasReattached&&!markerAlreadyOwned)throw error;debugLogger4.warn(`persistStartupWorktreeSidecar: marker update failed; persisting the sidecar without changing ownership: ${error}`)}}await writeWorktreeSession(sidecarPath,{slug:context.slug,worktreePath:context.worktreePath,worktreeBranch:context.branch,originalCwd:context.repoRoot,originalBranch:context.originalBranch,originalHeadCommit:context.originalHeadCommit});return{overrodeResumedWorktree,overriddenSlug,sidecarPath}}__name(persistStartupWorktreeSidecar,"persistStartupWorktreeSidecar");function buildStartupWorktreeNotice(context,override){const verb=context.wasReattached?"Re-attached to worktree":"Active worktree";const base=`[Startup] ${verb}: "${context.slug}" at ${context.worktreePath} (branch: ${context.branch}). Continue using this path for all file operations.`;if(override?.overrodeResumedWorktree&&override.overriddenSlug){return`${base}
4
4
  Note: --worktree overrode the resumed session's previous worktree "${override.overriddenSlug}". That worktree directory was left intact; re-attach with \`qwen --worktree ${override.overriddenSlug}\` if needed.`}return base}__name(buildStartupWorktreeNotice,"buildStartupWorktreeNotice");init_esbuild_shims();function takeUtf8Prefix(value,maxBytes){let bytes=0;let end=0;for(const char of value){const charBytes=Buffer.byteLength(char,"utf8");if(bytes+charBytes>maxBytes){break}bytes+=charBytes;end+=char.length}return value.slice(0,end)}__name(takeUtf8Prefix,"takeUtf8Prefix");async function readStdin(){const MAX_STDIN_SIZE=8*1024*1024;return new Promise((resolve3,reject)=>{let data="";let totalSize=0;let settled=false;process.stdin.setEncoding("utf8");const pipedInputShouldBeAvailableInMs=500;let pipedInputTimerId=setTimeout(()=>{onEnd()},pipedInputShouldBeAvailableInMs);const onReadable=__name(()=>{let chunk;while((chunk=process.stdin.read())!==null){if(pipedInputTimerId){clearTimeout(pipedInputTimerId);pipedInputTimerId=null}const chunkSize=Buffer.byteLength(chunk,"utf8");if(totalSize+chunkSize>MAX_STDIN_SIZE){const remainingSize=MAX_STDIN_SIZE-totalSize;const prefix=takeUtf8Prefix(chunk,remainingSize);data+=prefix;totalSize+=Buffer.byteLength(prefix,"utf8");writeStderrLine(`Warning: stdin input truncated to ${MAX_STDIN_SIZE} bytes.`);finish();process.stdin.destroy();return}data+=chunk;totalSize+=chunkSize}},"onReadable");const finish=__name(()=>{if(settled)return;settled=true;cleanup();resolve3(data)},"finish");const onEnd=__name(()=>{finish()},"onEnd");const onError=__name(err=>{if(settled)return;settled=true;cleanup();reject(err)},"onError");const cleanup=__name(()=>{if(pipedInputTimerId){clearTimeout(pipedInputTimerId);pipedInputTimerId=null}process.stdin.removeListener("readable",onReadable);process.stdin.removeListener("end",onEnd);process.stdin.removeListener("error",onError)},"cleanup");process.stdin.on("readable",onReadable);process.stdin.on("end",onEnd);process.stdin.on("error",onError)})}__name(readStdin,"readStdin");init_esbuild_shims();import{spawn}from"node:child_process";import{isatty}from"node:tty";var debugLogger5=createDebugLogger("RELAUNCH");var ORPHAN_GRACE_MS=12e4;async function relaunchOnExitCode(runner,options){while(true){try{const exitCode=await runner();if(exitCode===UPDATE_RELAUNCH_EXIT_CODE&&options?.onUpdateRelaunch){const updatedExitCode=await options.onUpdateRelaunch(true);process.exit(updatedExitCode)}if(exitCode!==RELAUNCH_EXIT_CODE){process.exit(exitCode)}}catch(error){process.stdin.resume();writeStderrLine("Fatal error: Failed to relaunch the CLI process.");writeStderrLine(error instanceof Error?error.message:String(error));process.exit(1)}}}__name(relaunchOnExitCode,"relaunchOnExitCode");function exitWhenSupervisorExits(graceMs=ORPHAN_GRACE_MS){const supervision=process.env[RELAUNCH_SUPERVISED_ENV];if(supervision!=="1"&&supervision!=="terminal"){return}delete process.env[RELAUNCH_SUPERVISED_ENV];if(typeof process.send!=="function"){return}const onTerminal=isatty(0);if(onTerminal&&supervision!=="terminal"){return}const exit=__name(()=>void runExitCleanup().finally(()=>process.exit(129)),"exit");if(!process.connected||!process.channel){debugLogger5.debug("Supervisor gone before startup; exiting.");exit();return}process.once("disconnect",()=>{if(onTerminal){debugLogger5.debug("Terminal supervisor gone; exiting.");exit();return}debugLogger5.debug("Supervisor gone; exiting after the grace period.");setTimeout(exit,graceMs).unref()});process.channel.unref()}__name(exitWhenSupervisorExits,"exitWhenSupervisorExits");async function relaunchAppInChildProcess(additionalNodeArgs,additionalScriptArgs,options){if(process.env["QWEN_CODE_NO_RELAUNCH"]){return}const script=process.argv[1];const scriptArgs=process.argv.slice(2);const command=options?.interpreter?.command??process.execPath;const nodeArgs=[...options?.interpreter?.runtime==="bun"?["--expose-gc"]:[...getRelaunchExecArgv(),...additionalNodeArgs],script,...additionalScriptArgs,...scriptArgs];const createChildEnv=__name(()=>{const env={...process.env,...options?.childEnv,QWEN_CODE_NO_RELAUNCH:"true"};delete env[RELAUNCH_SUPERVISED_ENV];if(env["QWEN_CODE_SCRUB_ELECTRON_RUN_AS_NODE"]==="1"){env["ELECTRON_RUN_AS_NODE"]="1"}return env},"createChildEnv");if(options?.replaceProcess&&!options.interpreter&&typeof process.execve==="function"&&!["win32","os400"].includes(process.platform)){if(additionalNodeArgs.length===0&&additionalScriptArgs.length===0&&!options?.environmentChangedSinceBoot){process.env["QWEN_CODE_NO_RELAUNCH"]="true";return}try{return process.execve(process.execPath,[process.execPath,...nodeArgs],createChildEnv())}catch(error){writeStderrLine(`Process replacement failed, using a supervised relaunch instead: ${error instanceof Error?error.message:String(error)}`)}}const runner=__name(()=>{let updateOnExitRequested=false;const terminalHandoff=options?.interpreter?.runtime==="bun"&&isatty(0);const newEnv={...createChildEnv(),[RELAUNCH_SUPERVISED_ENV]:terminalHandoff?"terminal":"1"};process.stdin.pause();const child=spawn(command,nodeArgs,{stdio:["inherit","inherit","inherit","ipc"],env:newEnv});const keepSupervisor=__name(()=>{},"keepSupervisor");if(terminalHandoff)process.on("SIGINT",keepSupervisor);const removeSignalHandler=__name(()=>{if(terminalHandoff)process.removeListener("SIGINT",keepSupervisor)},"removeSignalHandler");child.on("message",message=>{if(typeof message==="object"&&message!==null&&"type"in message&&message.type===UPDATE_ON_EXIT_MESSAGE){updateOnExitRequested=true}});try{options?.afterSpawn?.()}catch(err){removeSignalHandler();child.kill();throw err}return new Promise((resolve3,reject)=>{child.on("error",error=>{removeSignalHandler();reject(error)});child.on("close",code=>{removeSignalHandler();process.stdin.resume();const exitCode=code??1;if(exitCode===0&&updateOnExitRequested&&options?.onUpdateRelaunch){updateOnExitRequested=false;void Promise.resolve(options.onUpdateRelaunch(false)).then(updatedExitCode=>resolve3(updatedExitCode),reject);return}resolve3(exitCode)})})},"runner");await relaunchOnExitCode(runner,options)}__name(relaunchAppInChildProcess,"relaunchAppInChildProcess");init_esbuild_shims();var import_shell_quote=__toESM(require_shell_quote(),1);import{exec,execSync,spawn as spawn2}from"node:child_process";import os2 from"node:os";import path6 from"node:path";import fs4 from"node:fs";import{promisify}from"node:util";import{randomBytes}from"node:crypto";init_esbuild_shims();function parseSandboxImageName(image){const imageWithoutDigest=image.split("@")[0]??image;const lastSlash=imageWithoutDigest.lastIndexOf("/");const lastColon=imageWithoutDigest.lastIndexOf(":");const hasTag=lastColon>lastSlash;const fullName=hasTag?imageWithoutDigest.slice(0,lastColon):imageWithoutDigest;const tag=hasTag?imageWithoutDigest.slice(lastColon+1):void 0;const name=fullName.split("/").at(-1)||"unknown-image";return tag?`${name}-${tag}`:name}__name(parseSandboxImageName,"parseSandboxImageName");init_esbuild_shims();import path5 from"node:path";function isContainerPathWithinWorkdir(containerWorkdir,containerPath){const normalize=__name(value=>{const normalized=path5.posix.normalize(value.replace(/\\/g,"/")).replace(/\/+$/,"").toLowerCase();return normalized||"/"},"normalize");const normalizedWorkdir=normalize(containerWorkdir);const normalizedPath=normalize(containerPath);if(normalizedWorkdir==="/"){return normalizedPath.startsWith("/")}return normalizedPath===normalizedWorkdir||normalizedPath.startsWith(`${normalizedWorkdir}/`)}__name(isContainerPathWithinWorkdir,"isContainerPathWithinWorkdir");init_esbuild_shims();import os from"node:os";function parseSandboxMountSpec(rawMount,platform=os.platform()){const mount=rawMount.trim();const mountSeparator=platform==="win32"&&/^[A-Za-z]:[\\/]/.test(mount)?mount.indexOf(":",2):mount.indexOf(":");const from=mountSeparator===-1?mount:mount.slice(0,mountSeparator);const rest=mountSeparator===-1?"":mount.slice(mountSeparator+1);const[toPart,optsPart]=rest.split(":");return{from,to:toPart||from,opts:optsPart||"ro"}}__name(parseSandboxMountSpec,"parseSandboxMountSpec");var execAsync=promisify(exec);function getContainerPath(hostPath){if(os2.platform()!=="win32"){return hostPath}const withForwardSlashes=hostPath.replace(/\\/g,"/");const match=withForwardSlashes.match(/^([A-Z]):\/(.*)/i);if(match){return`/${match[1].toLowerCase()}/${match[2]}`}return hostPath}__name(getContainerPath,"getContainerPath");function ensureDirectoryAndGetRealPath(dir){if(!fs4.existsSync(dir)){fs4.mkdirSync(dir,{recursive:true})}return fs4.realpathSync(dir)}__name(ensureDirectoryAndGetRealPath,"ensureDirectoryAndGetRealPath");var LOCAL_DEV_SANDBOX_IMAGE_NAME="qwen-code-sandbox";var SANDBOX_NETWORK_NAME="qwen-code-sandbox";var SANDBOX_PROXY_NAME="qwen-code-sandbox-proxy";var BUILTIN_SEATBELT_PROFILES=["permissive-open","permissive-closed","permissive-proxied","restrictive-open","restrictive-closed","restrictive-proxied"];function getSandboxPassthroughEnvArgs(env=process.env){return["QWEN_DEBUG_LOG_FILE","QWEN_CODE_LEGACY_MCP_BLOCKING",MODEL_CATALOG_ENV,MODEL_CATALOG_REFRESH_ENV,MODEL_CATALOG_URL_ENV,SKIP_UPDATE_CHECK_ENV_VAR,CUSTOM_SANDBOX_IMAGE_ENV_VAR,HOST_UPDATE_RELAUNCH_ENV_VAR,QWEN_CODE_SERVE_ENV,QWEN_CODE_DESKTOP_ENV,"QWEN_CODE_ENABLE_WORKFLOWS","QWEN_CODE_DISABLE_WORKFLOWS"].flatMap(envVar=>env[envVar]===void 0?[]:["--env",`${envVar}=${env[envVar]}`])}__name(getSandboxPassthroughEnvArgs,"getSandboxPassthroughEnvArgs");function resolveSeatbeltProfileFile(profile,importMetaUrl=import.meta.url){if(!BUILTIN_SEATBELT_PROFILES.includes(profile)){return path6.join(SETTINGS_DIRECTORY_NAME,`sandbox-macos-${profile}.sb`)}return path6.join(resolveBundleDir(importMetaUrl),`sandbox-macos-${profile}.sb`)}__name(resolveSeatbeltProfileFile,"resolveSeatbeltProfileFile");async function shouldUseCurrentUserInSandbox(){const envVar=process.env["SANDBOX_SET_UID_GID"]?.toLowerCase().trim();if(envVar==="1"||envVar==="true"){return true}if(envVar==="0"||envVar==="false"){return false}if(os2.platform()==="linux"){const debugEnv=[process.env["DEBUG"],process.env["DEBUG_MODE"]].some(v=>v==="true"||v==="1");if(debugEnv){writeStderrLine("INFO: Using current user UID/GID in Linux sandbox. Set SANDBOX_SET_UID_GID=false to disable.")}return true}return false}__name(shouldUseCurrentUserInSandbox,"shouldUseCurrentUserInSandbox");function ports(){return(process.env["SANDBOX_PORTS"]??"").split(",").filter(p=>p.trim()).map(p=>p.trim())}__name(ports,"ports");function entrypoint(workdir,cliArgs){const isWindows=os2.platform()==="win32";const containerWorkdir=getContainerPath(workdir);const shellCmds=[];const pathSeparator=isWindows?";":":";let pathSuffix="";if(process.env["PATH"]){const paths=process.env["PATH"].split(pathSeparator);for(const p of paths){const containerPath=getContainerPath(p);if(isContainerPathWithinWorkdir(containerWorkdir,containerPath)){pathSuffix+=`:${containerPath}`}}}if(pathSuffix){shellCmds.push(`export PATH="$PATH${pathSuffix}";`)}let pythonPathSuffix="";if(process.env["PYTHONPATH"]){const paths=process.env["PYTHONPATH"].split(pathSeparator);for(const p of paths){const containerPath=getContainerPath(p);if(isContainerPathWithinWorkdir(containerWorkdir,containerPath)){pythonPathSuffix+=`:${containerPath}`}}}if(pythonPathSuffix){shellCmds.push(`export PYTHONPATH="$PYTHONPATH${pythonPathSuffix}";`)}const projectSandboxBashrc=path6.join(SETTINGS_DIRECTORY_NAME,"sandbox.bashrc");if(fs4.existsSync(projectSandboxBashrc)){shellCmds.push(`source ${getContainerPath(projectSandboxBashrc)};`)}ports().forEach(p=>shellCmds.push(`socat TCP4-LISTEN:${p},bind=$(hostname -i),fork,reuseaddr TCP4:127.0.0.1:${p} 2> /dev/null &`));const quotedCliArgs=cliArgs.slice(2).map(arg=>(0,import_shell_quote.quote)([arg]));const cliCmd=false?process.env["DEBUG"]?"npm run debug --":"npm rebuild && npm run start --":process.env["DEBUG"]?`node --inspect-brk=0.0.0.0:${process.env["DEBUG_PORT"]||"9229"} $(which qwen)`:"qwen";const args=[...shellCmds,cliCmd,...quotedCliArgs];return["bash","-c",args.join(" ")]}__name(entrypoint,"entrypoint");async function start_sandbox(config,nodeArgs=[],cliConfig,cliArgs=[],childEnv){if(config.command==="bwrap")throw new FatalSandboxError(BWRAP_MIGRATION_MESSAGE);if(config.command==="sandbox-exec"){if(process.env["BUILD_SANDBOX"]){throw new FatalSandboxError("Cannot BUILD_SANDBOX when using macOS Seatbelt")}const profile=process.env["SEATBELT_PROFILE"]??="permissive-open";const profileFile=resolveSeatbeltProfileFile(profile);if(!fs4.existsSync(profileFile)){throw new FatalSandboxError(`Missing macos seatbelt profile file '${profileFile}'`)}writeStderrLine(`using macos seatbelt (profile: ${profile}) ...`);const nodeOptions=[...process.env["DEBUG"]?["--inspect-brk"]:[],...nodeArgs].join(" ");const qwenDir=Storage.getGlobalQwenDir();const runtimeDir=Storage.getRuntimeBaseDir();fs4.mkdirSync(qwenDir,{recursive:true});fs4.mkdirSync(runtimeDir,{recursive:true});const args2=["-D",`TARGET_DIR=${fs4.realpathSync(process.cwd())}`,"-D",`TMP_DIR=${fs4.realpathSync(os2.tmpdir())}`,"-D",`HOME_DIR=${fs4.realpathSync(os2.homedir())}`,"-D",`CACHE_DIR=${fs4.realpathSync(execSync(`getconf DARWIN_USER_CACHE_DIR`).toString().trim())}`,"-D",`QWEN_DIR=${fs4.realpathSync(qwenDir)}`,"-D",`RUNTIME_DIR=${fs4.realpathSync(runtimeDir)}`];const MAX_INCLUDE_DIRS=5;const targetDir=fs4.realpathSync(cliConfig?.getTargetDir()||"");const includedDirs=[];if(cliConfig){const workspaceContext=cliConfig.getWorkspaceContext();const directories=workspaceContext.getDirectories();for(const dir of directories){const realDir=fs4.realpathSync(dir);if(realDir!==targetDir){includedDirs.push(realDir)}}}for(let i=0;i<MAX_INCLUDE_DIRS;i++){let dirPath="/dev/null";if(i<includedDirs.length){dirPath=includedDirs[i]}args2.push("-D",`INCLUDE_DIR_${i}=${dirPath}`)}const finalArgv=cliArgs;args2.push("-f",profileFile,"sh","-c",[...process.env["QWEN_CODE_SCRUB_ELECTRON_RUN_AS_NODE"]==="1"?["ELECTRON_RUN_AS_NODE=1"]:[],`SANDBOX=sandbox-exec`,`NODE_OPTIONS="${nodeOptions}"`,...finalArgv.map(arg=>(0,import_shell_quote.quote)([arg]))].join(" "));const proxyCommand2=process.env["QWEN_SANDBOX_PROXY_COMMAND"];let proxyProcess2=void 0;let sandboxProcess2=void 0;const sandboxEnv={...process.env};if(proxyCommand2){const proxy=process.env["HTTPS_PROXY"]||process.env["https_proxy"]||process.env["HTTP_PROXY"]||process.env["http_proxy"]||"http://localhost:8877";sandboxEnv["HTTPS_PROXY"]=proxy;sandboxEnv["https_proxy"]=proxy;sandboxEnv["HTTP_PROXY"]=proxy;sandboxEnv["http_proxy"]=proxy;const noProxy=process.env["NO_PROXY"]||process.env["no_proxy"];if(noProxy){sandboxEnv["NO_PROXY"]=noProxy;sandboxEnv["no_proxy"]=noProxy}proxyProcess2=spawn2("bash",["-c",proxyCommand2],{stdio:["ignore","pipe","pipe"],detached:true});const stopProxy=__name(()=>{writeStderrLine("stopping proxy ...");if(proxyProcess2?.pid){process.kill(-proxyProcess2.pid,"SIGTERM")}},"stopProxy");process.on("exit",stopProxy);process.on("SIGINT",stopProxy);process.on("SIGTERM",stopProxy);proxyProcess2.stderr?.on("data",data=>{writeStderrLine(data.toString())});proxyProcess2.on("close",(code,signal)=>{if(sandboxProcess2?.pid){process.kill(-sandboxProcess2.pid,"SIGTERM")}throw new FatalSandboxError(`Proxy command '${proxyCommand2}' exited with code ${code}, signal ${signal}`)});writeStderrLine("waiting for proxy to start ...");await execAsync(`until timeout 0.25 curl -s http://localhost:8877; do sleep 0.25; done`)}process.stdin.pause();sandboxProcess2=spawn2(config.command,args2,{stdio:"inherit",...childEnv?{env:{...process.env,...childEnv}}:{}});return new Promise((resolve3,reject)=>{sandboxProcess2?.on("error",reject);sandboxProcess2?.on("close",code=>{process.stdin.resume();resolve3(code??1)})})}writeStderrLine(`hopping into sandbox (command: ${config.command}) ...`);const gcPath=fs4.realpathSync(process.argv[1]);const projectSandboxDockerfile=path6.join(SETTINGS_DIRECTORY_NAME,"sandbox.Dockerfile");const isCustomProjectSandbox=fs4.existsSync(projectSandboxDockerfile);const image=config.image;if(!image){throw new FatalSandboxError(`Sandbox command '${config.command}' requires an image`)}const workdir=path6.resolve(process.cwd());const containerWorkdir=getContainerPath(workdir);if(process.env["BUILD_SANDBOX"]){if(!gcPath.includes("qwen-code/packages/")){throw new FatalSandboxError("Cannot build sandbox using installed Qwen Code binary; run `npm link ./packages/cli` under QwenCode-cli repo to switch to linked binary.")}else{writeStderrLine("building sandbox ...");const gcRoot=gcPath.split("/packages/")[0];let buildArgs="";const projectSandboxDockerfile2=path6.join(SETTINGS_DIRECTORY_NAME,"sandbox.Dockerfile");if(isCustomProjectSandbox){writeStderrLine(`using ${projectSandboxDockerfile2} for sandbox`);buildArgs+=`-f ${path6.resolve(projectSandboxDockerfile2)} -i ${image}`}execSync(`cd ${gcRoot} && node scripts/build_sandbox.js -s ${buildArgs}`,{stdio:"inherit",env:{...process.env,QWEN_SANDBOX:config.command}})}}if(!await ensureSandboxImageIsPresent(config.command,image)){const remedy=image===LOCAL_DEV_SANDBOX_IMAGE_NAME?"Try running `npm run build:all` or `npm run build:sandbox` under the qwen-code repo to build it locally, or check the image name and your network connection.":"Please check the image name, your network connection, or notify qwen-code-dev@service.alibaba.com if the issue persists.";throw new FatalSandboxError(`Sandbox image '${image}' is missing or could not be pulled. ${remedy}`)}const args=["run","-i","--rm","--init","--workdir",containerWorkdir];if(process.env["SANDBOX_FLAGS"]){const flags=(0,import_shell_quote.parse)(process.env["SANDBOX_FLAGS"],process.env).filter(f=>typeof f==="string");args.push(...flags)}if(process.stdin.isTTY){args.push("-t")}args.push("--add-host","host.docker.internal:host-gateway");args.push("--volume",`${workdir}:${containerWorkdir}`);const userSettingsDirOnHost=getUserSettingsDir();const runtimeBaseDirOnHost=Storage.getRuntimeBaseDir();const userSettingsDirRealPath=ensureDirectoryAndGetRealPath(userSettingsDirOnHost);const runtimeBaseDirRealPath=ensureDirectoryAndGetRealPath(runtimeBaseDirOnHost);const userSettingsDirInSandbox=getContainerPath(`/home/node/${SETTINGS_DIRECTORY_NAME}`);const userSettingsDirContainerPath=getContainerPath(userSettingsDirRealPath);const runtimeBaseDirContainerPath=getContainerPath(runtimeBaseDirRealPath);const runtimeCoveredByUserSettings=isSubpath(userSettingsDirRealPath,runtimeBaseDirRealPath);const userSettingsCoveredByRuntime=isSubpath(runtimeBaseDirRealPath,userSettingsDirRealPath);const runtimeSameAsUserSettings=runtimeCoveredByUserSettings&&userSettingsCoveredByRuntime;args.push("--volume",`${userSettingsDirRealPath}:${userSettingsDirInSandbox}`);if((!userSettingsCoveredByRuntime||runtimeSameAsUserSettings)&&userSettingsDirInSandbox!==userSettingsDirContainerPath){args.push("--volume",`${userSettingsDirRealPath}:${userSettingsDirContainerPath}`)}args.push("--env",`QWEN_HOME=${userSettingsDirContainerPath}`);if(!runtimeCoveredByUserSettings){args.push("--volume",`${runtimeBaseDirRealPath}:${runtimeBaseDirContainerPath}`)}if(!runtimeSameAsUserSettings){args.push("--env",`QWEN_RUNTIME_DIR=${runtimeBaseDirContainerPath}`)}args.push("--volume",`${os2.tmpdir()}:${getContainerPath(os2.tmpdir())}`);const gcloudConfigDir=path6.join(os2.homedir(),".config","gcloud");if(fs4.existsSync(gcloudConfigDir)){args.push("--volume",`${gcloudConfigDir}:${getContainerPath(gcloudConfigDir)}:ro`)}if(process.env["GOOGLE_APPLICATION_CREDENTIALS"]){const adcFile=process.env["GOOGLE_APPLICATION_CREDENTIALS"];if(fs4.existsSync(adcFile)){args.push("--volume",`${adcFile}:${getContainerPath(adcFile)}:ro`);args.push("--env",`GOOGLE_APPLICATION_CREDENTIALS=${getContainerPath(adcFile)}`)}}if(process.env["SANDBOX_MOUNTS"]){for(let mount of process.env["SANDBOX_MOUNTS"].split(",")){if(mount.trim()){const{from,to,opts}=parseSandboxMountSpec(mount);mount=`${from}:${to}:${opts}`;if(!path6.isAbsolute(from)){throw new FatalSandboxError(`Path '${from}' listed in SANDBOX_MOUNTS must be absolute`)}if(!fs4.existsSync(from)){throw new FatalSandboxError(`Missing mount path '${from}' listed in SANDBOX_MOUNTS`)}writeStderrLine(`SANDBOX_MOUNTS: ${from} -> ${to} (${opts})`);args.push("--volume",mount)}}}ports().forEach(p=>args.push("--publish",`${p}:${p}`));if(process.env["DEBUG"]){const debugPort=process.env["DEBUG_PORT"]||"9229";args.push(`--publish`,`${debugPort}:${debugPort}`)}const proxyCommand=process.env["QWEN_SANDBOX_PROXY_COMMAND"];if(proxyCommand){let proxy=process.env["HTTPS_PROXY"]||process.env["https_proxy"]||process.env["HTTP_PROXY"]||process.env["http_proxy"]||"http://localhost:8877";proxy=proxy.replace("localhost",SANDBOX_PROXY_NAME);if(proxy){args.push("--env",`HTTPS_PROXY=${proxy}`);args.push("--env",`https_proxy=${proxy}`);args.push("--env",`HTTP_PROXY=${proxy}`);args.push("--env",`http_proxy=${proxy}`)}const noProxy=process.env["NO_PROXY"]||process.env["no_proxy"];if(noProxy){args.push("--env",`NO_PROXY=${noProxy}`);args.push("--env",`no_proxy=${noProxy}`)}if(proxy){execSync(`${config.command} network inspect ${SANDBOX_NETWORK_NAME} || ${config.command} network create --internal ${SANDBOX_NETWORK_NAME}`);args.push("--network",SANDBOX_NETWORK_NAME);if(proxyCommand){execSync(`${config.command} network inspect ${SANDBOX_PROXY_NAME} || ${config.command} network create ${SANDBOX_PROXY_NAME}`)}}}const imageName=parseSandboxImageName(image);const isIntegrationTest=process.env["QWEN_CODE_INTEGRATION_TEST"]==="true";let containerName;if(isIntegrationTest){containerName=`qwen-code-integration-test-${randomBytes(4).toString("hex")}`;writeStderrLine(`ContainerName: ${containerName}`)}else{containerName=`${imageName}-${randomBytes(4).toString("hex")}`;writeStderrLine(`ContainerName (regular): ${containerName}`)}args.push("--name",containerName);if(containerName.length<=64){args.push("--hostname",containerName)}if(process.env["QWEN_CODE_TEST_VAR"]){args.push("--env",`QWEN_CODE_TEST_VAR=${process.env["QWEN_CODE_TEST_VAR"]}`)}args.push(...getSandboxPassthroughEnvArgs());if(process.env["QWEN_CODE_MCP_APPROVALS_PATH"]){args.push("--env",`QWEN_CODE_MCP_APPROVALS_PATH=${getContainerPath(process.env["QWEN_CODE_MCP_APPROVALS_PATH"])}`)}if(process.env["QWEN_CODE_WARNINGS_FILE"]){args.push("--env",`QWEN_CODE_WARNINGS_FILE=${getContainerPath(process.env["QWEN_CODE_WARNINGS_FILE"])}`)}if(process.env["GEMINI_API_KEY"]){args.push("--env",`GEMINI_API_KEY=${process.env["GEMINI_API_KEY"]}`)}if(process.env["GOOGLE_API_KEY"]){args.push("--env",`GOOGLE_API_KEY=${process.env["GOOGLE_API_KEY"]}`)}if(process.env["OPENAI_API_KEY"]){args.push("--env",`OPENAI_API_KEY=${process.env["OPENAI_API_KEY"]}`)}if(process.env["OPENAI_BASE_URL"]){args.push("--env",`OPENAI_BASE_URL=${process.env["OPENAI_BASE_URL"]}`)}if(process.env["OPENAI_MODEL"]){args.push("--env",`OPENAI_MODEL=${process.env["OPENAI_MODEL"]}`)}if(process.env["GOOGLE_GENAI_USE_VERTEXAI"]){args.push("--env",`GOOGLE_GENAI_USE_VERTEXAI=${process.env["GOOGLE_GENAI_USE_VERTEXAI"]}`)}if(process.env["GOOGLE_GENAI_USE_GCA"]){args.push("--env",`GOOGLE_GENAI_USE_GCA=${process.env["GOOGLE_GENAI_USE_GCA"]}`)}if(process.env["GOOGLE_CLOUD_PROJECT"]){args.push("--env",`GOOGLE_CLOUD_PROJECT=${process.env["GOOGLE_CLOUD_PROJECT"]}`)}if(process.env["GOOGLE_CLOUD_LOCATION"]){args.push("--env",`GOOGLE_CLOUD_LOCATION=${process.env["GOOGLE_CLOUD_LOCATION"]}`)}if(process.env["GEMINI_MODEL"]){args.push("--env",`GEMINI_MODEL=${process.env["GEMINI_MODEL"]}`)}if(process.env["TERM"]){args.push("--env",`TERM=${process.env["TERM"]}`)}if(process.env["COLORTERM"]){args.push("--env",`COLORTERM=${process.env["COLORTERM"]}`)}for(const envVar of["QWEN_CODE_IDE_SERVER_PORT","QWEN_CODE_IDE_WORKSPACE_PATH","TERM_PROGRAM"]){if(process.env[envVar]){args.push("--env",`${envVar}=${process.env[envVar]}`)}}const virtualEnv=process.env["VIRTUAL_ENV"];if(virtualEnv&&isContainerPathWithinWorkdir(getContainerPath(workdir),getContainerPath(virtualEnv))){const sandboxVenvPath=path6.resolve(SETTINGS_DIRECTORY_NAME,"sandbox.venv");if(!fs4.existsSync(sandboxVenvPath)){fs4.mkdirSync(sandboxVenvPath,{recursive:true})}args.push("--volume",`${sandboxVenvPath}:${getContainerPath(virtualEnv)}`);args.push("--env",`VIRTUAL_ENV=${getContainerPath(virtualEnv)}`)}if(process.env["SANDBOX_ENV"]){for(let env of process.env["SANDBOX_ENV"].split(",")){if(env=env.trim()){if(env.includes("=")){writeStderrLine(`SANDBOX_ENV: ${env}`);args.push("--env",env)}else{throw new FatalSandboxError("SANDBOX_ENV must be a comma-separated list of key=value pairs")}}}}for(const name of Object.keys(childEnv??{})){args.push("--env",name)}const existingNodeOptions=process.env["NODE_OPTIONS"]||"";const allNodeOptions=[...existingNodeOptions?[existingNodeOptions]:[],...nodeArgs].join(" ");if(allNodeOptions.length>0){args.push("--env",`NODE_OPTIONS="${allNodeOptions}"`)}args.push("--env",`SANDBOX=${containerName}`);if(config.command==="podman"){const emptyAuthFilePath=path6.join(os2.tmpdir(),"empty_auth.json");fs4.writeFileSync(emptyAuthFilePath,"{}","utf-8");args.push("--authfile",emptyAuthFilePath)}let userFlag="";const finalEntrypoint=entrypoint(workdir,cliArgs);const useCurrentUser=await shouldUseCurrentUserInSandbox();if(useCurrentUser){args.push("--user","root");const uid=execSync("id -u").toString().trim();const gid=execSync("id -g").toString().trim();const username="qwen";const homeDir=getContainerPath(os2.homedir());const setupUserCommands=[`groupadd -f -g ${gid} ${username}`,`id -u ${username} &>/dev/null || useradd -o -u ${uid} -g ${gid} -d ${homeDir} -s /bin/bash ${username}`].join(" && ");const originalCommand=finalEntrypoint[2];const escapedOriginalCommand=originalCommand.replace(/'/g,"'\\''");const suCommand=`su -p ${username} -c '${escapedOriginalCommand}'`;finalEntrypoint[2]=`${setupUserCommands} && ${suCommand}`;userFlag=`--user ${uid}:${gid}`;args.push("--env",`HOME=${os2.homedir()}`)}else if(isIntegrationTest){args.push("--user","root");userFlag="--user root"}args.push(image);args.push(...finalEntrypoint);let proxyProcess=void 0;let sandboxProcess=void 0;if(proxyCommand){const proxyContainerCommand=`${config.command} run --rm --init ${userFlag} --name ${SANDBOX_PROXY_NAME} --network ${SANDBOX_PROXY_NAME} -p 8877:8877 -v ${process.cwd()}:${workdir} --workdir ${workdir} ${image} ${proxyCommand}`;const isWindows=os2.platform()==="win32";const proxyShell=isWindows?"cmd.exe":"bash";const proxyShellArgs=isWindows?["/c",proxyContainerCommand]:["-c",proxyContainerCommand];proxyProcess=spawn2(proxyShell,proxyShellArgs,{stdio:["ignore","pipe","pipe"],detached:true});const stopProxy=__name(()=>{writeStderrLine("stopping proxy container ...");execSync(`${config.command} rm -f ${SANDBOX_PROXY_NAME}`)},"stopProxy");process.on("exit",stopProxy);process.on("SIGINT",stopProxy);process.on("SIGTERM",stopProxy);proxyProcess.stderr?.on("data",data=>{writeStderrLine(data.toString().trim())});proxyProcess.on("close",(code,signal)=>{if(sandboxProcess?.pid){process.kill(-sandboxProcess.pid,"SIGTERM")}throw new FatalSandboxError(`Proxy container command '${proxyContainerCommand}' exited with code ${code}, signal ${signal}`)});writeStderrLine("waiting for proxy to start ...");await execAsync(`until timeout 0.25 curl -s http://localhost:8877; do sleep 0.25; done`);await execAsync(`${config.command} network connect ${SANDBOX_NETWORK_NAME} ${SANDBOX_PROXY_NAME}`)}process.stdin.pause();sandboxProcess=spawn2(config.command,args,{stdio:"inherit",...childEnv?{env:{...process.env,...childEnv}}:{}});return new Promise((resolve3,reject)=>{sandboxProcess.on("error",err=>{writeStderrLine(`Sandbox process error: ${err}`);reject(err)});sandboxProcess?.on("close",(code,signal)=>{process.stdin.resume();if(code!==0&&code!==null){writeStderrLine(`Sandbox process exited with code: ${code}, signal: ${signal}`)}resolve3(code??1)})})}__name(start_sandbox,"start_sandbox");async function imageExists(sandbox,image){return new Promise(resolve3=>{const args=["image","inspect","--format","{{.Id}}",image];const checkProcess=spawn2(sandbox,args);let stdoutData="";if(checkProcess.stdout){checkProcess.stdout.on("data",data=>{stdoutData+=data.toString()})}checkProcess.on("error",err=>{writeStderrLine(`Failed to start '${sandbox}' command for image check: ${err.message}`);resolve3(false)});checkProcess.on("close",()=>{resolve3(stdoutData.trim()!=="")})})}__name(imageExists,"imageExists");async function pullImage(sandbox,image){writeStderrLine(`Attempting to pull image ${image} using ${sandbox}...`);return new Promise(resolve3=>{const args=["pull",image];const pullProcess=spawn2(sandbox,args,{stdio:"pipe"});let stderrData="";const onStdoutData=__name(data=>{writeStderrLine(data.toString().trim())},"onStdoutData");const onStderrData=__name(data=>{stderrData+=data.toString();writeStderrLine(data.toString().trim())},"onStderrData");const onError=__name(err=>{writeStderrLine(`Failed to start '${sandbox} pull ${image}' command: ${err.message}`);cleanup();resolve3(false)},"onError");const onClose=__name(code=>{if(code===0){writeStderrLine(`Successfully pulled image ${image}.`);cleanup();resolve3(true)}else{writeStderrLine(`Failed to pull image ${image}. '${sandbox} pull ${image}' exited with code ${code}.`);if(stderrData.trim()){}cleanup();resolve3(false)}},"onClose");const cleanup=__name(()=>{if(pullProcess.stdout){pullProcess.stdout.removeListener("data",onStdoutData)}if(pullProcess.stderr){pullProcess.stderr.removeListener("data",onStderrData)}pullProcess.removeListener("error",onError);pullProcess.removeListener("close",onClose);if(pullProcess.connected){pullProcess.disconnect()}},"cleanup");if(pullProcess.stdout){pullProcess.stdout.on("data",onStdoutData)}if(pullProcess.stderr){pullProcess.stderr.on("data",onStderrData)}pullProcess.on("error",onError);pullProcess.on("close",onClose)})}__name(pullImage,"pullImage");async function ensureSandboxImageIsPresent(sandbox,image){writeStderrLine(`Checking for sandbox image: ${image}`);if(await imageExists(sandbox,image)){writeStderrLine(`Sandbox image ${image} found locally.`);return true}writeStderrLine(`Sandbox image ${image} not found locally.`);if(image===LOCAL_DEV_SANDBOX_IMAGE_NAME){return false}if(await pullImage(sandbox,image)){if(await imageExists(sandbox,image)){writeStderrLine(`Sandbox image ${image} is now available after pulling.`);return true}else{writeStderrLine(`Sandbox image ${image} still not found after a pull attempt. This might indicate an issue with the image name or registry, or the pull command reported success but failed to make the image available.`);return false}}writeStderrLine(`Failed to obtain sandbox image ${image} after check and pull attempt.`);return false}__name(ensureSandboxImageIsPresent,"ensureSandboxImageIsPresent");init_esbuild_shims();import fs5 from"node:fs/promises";async function getStartupWarnings(){const warningsFilePath=process.env["QWEN_CODE_WARNINGS_FILE"];if(!warningsFilePath)return[];try{await fs5.access(warningsFilePath);const warningsContent=await fs5.readFile(warningsFilePath,"utf-8");const warnings=warningsContent.split("\n").filter(line=>line.trim()!=="");try{await fs5.unlink(warningsFilePath)}catch{warnings.push("Warning: Could not delete temporary warnings file.")}return warnings}catch(err){if(err instanceof Error&&"code"in err&&err.code==="ENOENT"){return[]}return[`Error checking/reading warnings file: ${getErrorMessage(err)}`]}}__name(getStartupWarnings,"getStartupWarnings");init_esbuild_shims();import fs6 from"node:fs/promises";import path7 from"node:path";var rootDirectoryCheck={id:"root-directory",check:__name(async options=>{try{const workspaceRealPath=await fs6.realpath(options.workspaceRoot);const errorMessage="Warning: You are running Qwen Code in the root directory. Your entire folder structure will be used for context. It is strongly recommended to run in a project-specific directory.";if(path7.dirname(workspaceRealPath)===workspaceRealPath){return errorMessage}return null}catch(_err){return"Could not verify the current directory due to a file system error."}},"check")};var ripgrepAvailabilityCheck={id:"ripgrep-availability",check:__name(async options=>{if(!options.useRipgrep){return null}try{const isAvailable=await canUseRipgrep(options.useBuiltinRipgrep);if(!isAvailable){return"Ripgrep not available: Please install ripgrep globally to enable faster file content search. Falling back to built-in grep."}return null}catch(error){return`Ripgrep not available: ${error instanceof Error?error.message:"Unknown error"}. Falling back to built-in grep.`}},"check")};var WARNING_CHECKS=[rootDirectoryCheck,ripgrepAvailabilityCheck];async function getUserStartupWarnings(options){const results=await Promise.all(WARNING_CHECKS.map(check=>check.check(options)));return results.filter(msg=>msg!==null)}__name(getUserStartupWarnings,"getUserStartupWarnings");init_esbuild_shims();var MAX_LISTED_RUNS=3;function formatInterruptedWorkflowRunsNotice(runs,options={}){if(runs.length===0)return void 0;const lines=[runs.length===1?"A workflow run was interrupted when the Qwen Code process running it exited:":`${runs.length} workflow runs were interrupted when the Qwen Code process running them exited:`];for(const{snapshot,resumeName,hasJournal}of runs.slice(0,MAX_LISTED_RUNS)){const name=stripAnsiAndControl(snapshot.meta?.name??snapshot.workflowName??"");const agents=snapshot.agentsDispatched>0?` \xB7 ${snapshot.agentsCompleted}/${snapshot.agentsDispatched} agents finished`:"";lines.push(` ${snapshot.runId}${name?` \xB7 ${name}`:""}${agents}`);const target={runId:snapshot.runId,scriptPath:snapshot.scriptPath,args:snapshot.args,resumeName,nameOnly:options.nameOnly===true};const call=hasJournal?buildResumeCall(target):null;if(call){const argsNote=snapshotArgsUnavailable(snapshot)||hasUninlinableResumeArgs(target)?" (pass its original args too)":"";lines.push(` resume: ${call}${argsNote}`)}}if(runs.length>MAX_LISTED_RUNS){lines.push(` \u2026and ${runs.length-MAX_LISTED_RUNS} more.`)}lines.push("Run /workflows to see them.");return lines.join("\n")}__name(formatInterruptedWorkflowRunsNotice,"formatInterruptedWorkflowRunsNotice");async function getInterruptedWorkflowRunsNotice(config){try{const runs=await claimInterruptedWorkflowRuns(config);return formatInterruptedWorkflowRunsNotice(runs,{nameOnly:config.isWorkflowNameOnly?.()===true})}catch{return void 0}}__name(getInterruptedWorkflowRunsNotice,"getInterruptedWorkflowRunsNotice");init_esbuild_shims();var SUPPRESSED_WARNINGS=[/MaxListenersExceededWarning.*AbortSignal/];function isSuppressed(warning){const text=`${warning.name}: ${warning.message}`;return SUPPRESSED_WARNINGS.some(re=>re.test(text))}__name(isSuppressed,"isSuppressed");function isDebugMode2(){if(false)return true;const truthy=__name(v=>!!v&&v!=="0"&&v.toLowerCase()!=="false","truthy");return truthy(process.env["DEBUG"])||truthy(process.env["QWEN_DEBUG"])}__name(isDebugMode2,"isDebugMode");var installedHandler=null;function initializeWarningHandler(){if(installedHandler)return;const priorListeners=[...process.listeners("warning")];installedHandler=__name(warning=>{if(!isDebugMode2()&&isSuppressed(warning))return;for(const fn of priorListeners){try{fn(warning)}catch{}}},"installedHandler");process.removeAllListeners("warning");process.on("warning",installedHandler)}__name(initializeWarningHandler,"initializeWarningHandler");var debugLogger6=createDebugLogger("STARTUP");function clearCorruptionEnvVars(){delete process.env[ENV_CORRUPTED_PATH];delete process.env[ENV_WAS_RECOVERED]}__name(clearCorruptionEnvVars,"clearCorruptionEnvVars");function validateDnsResolutionOrder(order){const defaultValue="ipv4first";if(order===void 0){return defaultValue}if(order==="ipv4first"||order==="verbatim"){return order}writeStderrLine(`Invalid value for dnsResolutionOrder in settings: "${order}". Using default "${defaultValue}".`);return defaultValue}__name(validateDnsResolutionOrder,"validateDnsResolutionOrder");function getNodeMemoryArgs(isDebugMode3){if("bun"in process.versions){return[]}const totalMemoryMB=os3.totalmem()/(1024*1024);const heapStats=v8.getHeapStatistics();const currentMaxOldSpaceSizeMb=Math.floor(heapStats.heap_size_limit/1024/1024);const targetMaxOldSpaceSizeInMB=Math.floor(totalMemoryMB*.5);if(isDebugMode3){writeStderrLine(`Current heap size ${currentMaxOldSpaceSizeMb.toFixed(2)} MB`)}if(process.env["QWEN_CODE_NO_RELAUNCH"]){return[]}if(targetMaxOldSpaceSizeInMB>currentMaxOldSpaceSizeMb){if(isDebugMode3){writeStderrLine(`Need to relaunch with more memory: ${targetMaxOldSpaceSizeInMB.toFixed(2)} MB`)}return[`--max-old-space-size=${targetMaxOldSpaceSizeInMB}`]}return[]}__name(getNodeMemoryArgs,"getNodeMemoryArgs");var uncaughtExceptionHandler;function setupUncaughtExceptionHandler(config){process.removeListener("uncaughtException",handleUncaughtException);if(uncaughtExceptionHandler){process.removeListener("uncaughtException",uncaughtExceptionHandler)}uncaughtExceptionHandler=__name(rawError=>{if(isExpectedPtyRaceError(rawError)){return}const error=rawError instanceof Error?rawError:new Error(String(rawError));const timestamp=new Date().toISOString();const line=`${timestamp} [ERROR] [STARTUP] [UNCAUGHT_EXCEPTION] ${error.message}
5
5
  ${error.stack??""}
6
6
  `;let logged=false;let logPath;try{logPath=Storage.getDebugLogPath(config.getSessionId());fs7.mkdirSync(path8.dirname(logPath),{recursive:true});fs7.appendFileSync(logPath,line,"utf8");logged=true}catch{}if(process.stdout.isTTY){try{process.stdout.write("\x1B[?1049l");process.stdout.write("\x1B[?25h")}catch{}}writeStderrLineSafe(`
@@ -13,11 +13,11 @@ CRITICAL: Unhandled Promise Rejection!
13
13
  =========================================
14
14
  Reason: ${reason}${reason instanceof Error&&reason.stack?`
15
15
  Stack trace:
16
- ${reason.stack}`:""}`;debugLogger6.error(errorMessage);appEvents.emit("log-error",errorMessage);if(!unhandledRejectionOccurred){unhandledRejectionOccurred=true;appEvents.emit("open-debug-console")}})}__name(setupUnhandledRejectionHandler,"setupUnhandledRejectionHandler");function getSignalExitCode(signal){if(signal==="SIGINT")return 130;if(signal==="SIGHUP")return 129;return 143}__name(getSignalExitCode,"getSignalExitCode");var SIGINT_EXIT_CONFIRM_WINDOW_MS=1e3;var SIGINT_RERAISE_IGNORE_MS=50;function installInteractiveSignalHandlers(wasRaw){let cleanupStarted=false;let lastSigintAt=0;const swallowSignalDuringCleanup=__name(()=>{},"swallowSignalDuringCleanup");const beginExit=__name(signal=>{if(process.stdin.isTTY){process.stdin.setRawMode(wasRaw)}if(cleanupStarted){return}cleanupStarted=true;process.on("SIGINT",swallowSignalDuringCleanup);void runExitCleanup().catch(error=>{debugLogger6.error(`Error during ${signal} cleanup:`,error)}).finally(()=>{process.exit(getSignalExitCode(signal))})},"beginExit");const handleSigterm=__name(()=>{beginExit("SIGTERM")},"handleSigterm");const handleSighup=__name(()=>{beginExit("SIGHUP")},"handleSighup");const handleSigint=__name(()=>{if(cleanupStarted){return}const now=Date.now();const sincePrevious=now-lastSigintAt;if(sincePrevious<=SIGINT_RERAISE_IGNORE_MS){return}if(sincePrevious<=SIGINT_EXIT_CONFIRM_WINDOW_MS){beginExit("SIGINT");return}lastSigintAt=now;writeStderrLine("Press Ctrl+C again to exit.")},"handleSigint");process.on("SIGTERM",handleSigterm);process.on("SIGINT",handleSigint);process.on("SIGHUP",handleSighup);return()=>{process.removeListener("SIGTERM",handleSigterm);process.removeListener("SIGINT",handleSigint);process.removeListener("SIGHUP",handleSighup)}}__name(installInteractiveSignalHandlers,"installInteractiveSignalHandlers");async function main(){profileCheckpoint("main_entry");clearInheritedPeerMessagingEnv();exitWhenSupervisorExits();const acpStartupProfilerEnabled=isAcpStartupProfilerEnabled();const startupProfilerEnabled=isStartupProfilerEnabled();if(startupProfilerEnabled||acpStartupProfilerEnabled){setStartupEventSink((name,attrs)=>{if(startupProfilerEnabled)recordStartupEvent(name,attrs);if(acpStartupProfilerEnabled)recordAcpConfigStartupEvent(name)})}setupUnhandledRejectionHandler();initializeWarningHandler();const privateAcpParentCapability=process.env[PRIVATE_ACP_CAPABILITY_ENV];delete process.env[PRIVATE_ACP_CAPABILITY_ENV];const conversationsRuntimeMarkerSeen=process.env[PRIVATE_CONVERSATIONS_RUNTIME_ENV]===PRIVATE_CONVERSATIONS_RUNTIME_ENABLE;delete process.env[PRIVATE_CONVERSATIONS_RUNTIME_ENV];const privateExternalToolGuard=process.env[PRIVATE_EXTERNAL_TOOL_GUARD_ENV]===EXTERNAL_TOOL_GUARD_REQUIRED_VALUE?EXTERNAL_TOOL_GUARD_REQUIRED_VALUE:void 0;delete process.env[PRIVATE_EXTERNAL_TOOL_GUARD_ENV];const privateExternalToolGuardProvider=process.env[PRIVATE_EXTERNAL_TOOL_GUARD_PROVIDER_ENV]===EXTERNAL_TOOL_GUARD_PROVIDER_ATTACHED_VALUE?EXTERNAL_TOOL_GUARD_PROVIDER_ATTACHED_VALUE:void 0;delete process.env[PRIVATE_EXTERNAL_TOOL_GUARD_PROVIDER_ENV];if(process.argv.includes("--bare")){process.env[QWEN_CODE_SIMPLE_ENV_VAR]="1"}preResolveHomeEnvOverrides();markAcpStartup("argsParseStart");let argv=await parseArguments();delete process.env[EXTERNAL_TOOL_GUARD_TOKEN_ENV];markAcpStartup("argsParseEnd");profileCheckpoint("after_parse_arguments");const isAcpMode=argv.acp||argv.experimentalAcp;const conversationsRuntimeProvenance=isAcpMode&&privateAcpParentCapability!==void 0&&conversationsRuntimeMarkerSeen;if(argv.acpExecutionEngine!==void 0&&(argv.acpExecutionEngine!=="managed"||!isAcpMode||privateAcpParentCapability===void 0||conversationsRuntimeProvenance)){throw new Error("--acp-execution-engine is reserved for hosts spawned by qwen serve.")}const privateAcpChildEnv=isAcpMode&&privateAcpParentCapability!==void 0?{[PRIVATE_ACP_CAPABILITY_ENV]:privateAcpParentCapability,...conversationsRuntimeProvenance?{[PRIVATE_CONVERSATIONS_RUNTIME_ENV]:PRIVATE_CONVERSATIONS_RUNTIME_ENABLE}:{},...privateExternalToolGuard?{[PRIVATE_EXTERNAL_TOOL_GUARD_ENV]:privateExternalToolGuard,...privateExternalToolGuardProvider?{[PRIVATE_EXTERNAL_TOOL_GUARD_PROVIDER_ENV]:privateExternalToolGuardProvider}:{}}:{}}:void 0;if((argv.acp||argv.experimentalAcp)&&process.env["QWEN_CODE_SCRUB_ELECTRON_RUN_AS_NODE"]==="1"){delete process.env["ELECTRON_RUN_AS_NODE"];if(process.env["QWEN_CODE_NO_RELAUNCH"]||process.env["SANDBOX"]){delete process.env["QWEN_CODE_SCRUB_ELECTRON_RUN_AS_NODE"]}}if(isBareMode(argv.bare)){process.env[QWEN_CODE_SIMPLE_ENV_VAR]="1"}markAcpStartup("settingsLoadStart");const settings=isBareMode(argv.bare)?createMinimalSettings():loadSettings();markAcpStartup("settingsLoadEnd");const executionSandboxSettings=validateExecutionSandboxSelection(settings.merged,argv);if(executionSandboxSettings&&(argv.acp||argv.experimentalAcp||argv.worktree!==void 0||argv.experimentalLsp||argv.mcpConfig||argv.extensions?.length)){throw new Error("tools.executionSandbox does not yet support ACP, worktree management, LSP, MCP or extensions.")}delete process.env[PRIVATE_CONVERSATIONS_RUNTIME_ENV];if(settings.corruptedPath){process.env[ENV_CORRUPTED_PATH]=settings.corruptedPath;process.env[ENV_WAS_RECOVERED]=settings.wasRecovered?"1":"0"}if(!executionSandboxSettings)await cleanupCheckpoints();profileCheckpoint("after_load_settings");const settingsWarnings=getSettingsWarnings(settings);for(const warning of settingsWarnings){writeStderrLine(warning)}if(settings.corruptedPath){writeStderrLine("Warning: Workspace settings had invalid JSON. A copy of the corrupted file has been saved at: "+settings.corruptedPath)}if(argv.listExtensions){await initializeI18n(resolveLanguageSetting(settings.merged.general?.language));const{handleList:handleListExtensions}=await import("./list-DE7VUIR2.js");await handleListExtensions();process.exit(0)}if(argv.promptInteractive&&!process.stdin.isTTY){writeStderrLine("Error: The --prompt-interactive flag cannot be used when input is piped from stdin.");process.exit(1)}const isDebugMode3=isDebugMode(argv);dns.setDefaultResultOrder(validateDnsResolutionOrder(settings.merged.advanced?.dnsResolutionOrder));const{themeManager,AUTO_THEME_NAME}=await import("./theme-manager-DR5EYGLT.js");themeManager.loadCustomThemes(settings.merged.ui?.customThemes);const configuredTheme=settings.merged.ui?.theme;if(configuredTheme&&configuredTheme!==AUTO_THEME_NAME){if(!themeManager.setActiveTheme(configuredTheme)){writeStderrLine(`Warning: Theme "${configuredTheme}" not found.`)}}else if(process.stdout.isTTY&&!(!argv.promptInteractive&&(argv.outputFormat==="json"||argv.outputFormat==="stream-json")&&!!(argv.query||argv.prompt))){themeManager.setActiveTheme(AUTO_THEME_NAME)}if(!process.env["SANDBOX"]){const memoryArgs=settings.merged.advanced?.autoConfigureMemory?getNodeMemoryArgs(isDebugMode3):[];const updateProjectRoot=process.cwd();const onUpdateRelaunch=__name(async relaunchOnFailure=>{await initializeI18n(resolveLanguageSetting(settings.merged.general?.language));const{updateBeforeRelaunch}=await import("./update-relaunch-WVIFX5CN.js");const shouldRelaunch=await updateBeforeRelaunch(settings,updateProjectRoot,relaunchOnFailure);return shouldRelaunch?UPDATE_COMPLETE_EXIT_CODE:0},"onUpdateRelaunch");const sandboxConfig=await loadSandboxConfig(settings.merged,argv);const npmBunHandoff=selectNpmBunHandoff({interactive:isInteractiveInvocation(argv)&&Boolean(process.stdout.isTTY),screenReader:argv.screenReader??settings.merged.ui?.accessibility?.screenReader??false,protocolMode:Boolean(isAcpMode||argv.inputFormat==="stream-json"||(argv.inputFile??settings.merged.dualOutput?.inputFile)||argv.jsonFd!==void 0),sandbox:Boolean(sandboxConfig)});const customSandboxImage=argv.sandboxImage??process.env["QWEN_SANDBOX_IMAGE"]??settings.merged.tools?.sandboxImage;const containerSandbox=sandboxConfig?.command==="docker"||sandboxConfig?.command==="podman"?sandboxConfig:void 0;if(containerSandbox?.image&&customSandboxImage){process.env[CUSTOM_SANDBOX_IMAGE_ENV_VAR]=containerSandbox.image}else if(containerSandbox){const hostInstallationInfo=getInstallationInfo(updateProjectRoot,true);process.env[HOST_UPDATE_RELAUNCH_ENV_VAR]=String(Boolean(hostInstallationInfo.updateCommand||hostInstallationInfo.isStandalone&&hostInstallationInfo.standaloneDir))}if(sandboxConfig){const partialConfig=await loadCliConfig(settings.merged,argv,void 0,[],{systemHooks:settings.getSystemHooks(),userHooks:settings.getUserHooks(),projectHooks:settings.getProjectHooks()},buildDisabledSkillNamesProvider(settings),void 0,void 0,void 0,privateAcpParentCapability===void 0?{workflowAncestorTrustProvider:createLocalWorkflowAncestorTrustProvider(getOperatorTrustSettings(settings))}:void 0,buildEnabledSkillNamesProvider(settings));if(!settings.merged.security?.auth?.useExternal){try{const authType=partialConfig.getModelsConfig().getCurrentAuthType();if(authType){const err=validateAuthMethod(authType,partialConfig);if(err){throw new Error(err)}await partialConfig.refreshAuth(authType)}}catch(err){writeStderrLine(`Error authenticating: ${err}`);process.exit(1)}}const inputFormat=argv.inputFormat;const isAcpMode2=argv.acp||argv.experimentalAcp;let stdinData="";if(!process.stdin.isTTY&&inputFormat!=="stream-json"&&!isAcpMode2){stdinData=await readStdin()}const injectStdinIntoArgs=__name((args,stdinData2)=>{const finalArgs=[...args];if(stdinData2){const promptIndex=finalArgs.findIndex(arg=>arg==="--prompt"||arg==="-p");if(promptIndex>-1&&finalArgs.length>promptIndex+1){finalArgs[promptIndex+1]=`${stdinData2}
16
+ ${reason.stack}`:""}`;debugLogger6.error(errorMessage);appEvents.emit("log-error",errorMessage);if(!unhandledRejectionOccurred){unhandledRejectionOccurred=true;appEvents.emit("open-debug-console")}})}__name(setupUnhandledRejectionHandler,"setupUnhandledRejectionHandler");function getSignalExitCode(signal){if(signal==="SIGINT")return 130;if(signal==="SIGHUP")return 129;return 143}__name(getSignalExitCode,"getSignalExitCode");var SIGINT_EXIT_CONFIRM_WINDOW_MS=1e3;var SIGINT_RERAISE_IGNORE_MS=50;function installInteractiveSignalHandlers(wasRaw){let cleanupStarted=false;let lastSigintAt=0;const swallowSignalDuringCleanup=__name(()=>{},"swallowSignalDuringCleanup");const beginExit=__name(signal=>{if(process.stdin.isTTY){process.stdin.setRawMode(wasRaw)}if(cleanupStarted){return}cleanupStarted=true;process.on("SIGINT",swallowSignalDuringCleanup);void runExitCleanup().catch(error=>{debugLogger6.error(`Error during ${signal} cleanup:`,error)}).finally(()=>{process.exit(getSignalExitCode(signal))})},"beginExit");const handleSigterm=__name(()=>{beginExit("SIGTERM")},"handleSigterm");const handleSighup=__name(()=>{beginExit("SIGHUP")},"handleSighup");const handleSigint=__name(()=>{if(cleanupStarted){return}const now=Date.now();const sincePrevious=now-lastSigintAt;if(sincePrevious<=SIGINT_RERAISE_IGNORE_MS){return}if(sincePrevious<=SIGINT_EXIT_CONFIRM_WINDOW_MS){beginExit("SIGINT");return}lastSigintAt=now;writeStderrLine("Press Ctrl+C again to exit.")},"handleSigint");process.on("SIGTERM",handleSigterm);process.on("SIGINT",handleSigint);process.on("SIGHUP",handleSighup);return()=>{process.removeListener("SIGTERM",handleSigterm);process.removeListener("SIGINT",handleSigint);process.removeListener("SIGHUP",handleSighup)}}__name(installInteractiveSignalHandlers,"installInteractiveSignalHandlers");async function main(){profileCheckpoint("main_entry");clearInheritedPeerMessagingEnv();exitWhenSupervisorExits();const acpStartupProfilerEnabled=isAcpStartupProfilerEnabled();const startupProfilerEnabled=isStartupProfilerEnabled();if(startupProfilerEnabled||acpStartupProfilerEnabled){setStartupEventSink((name,attrs)=>{if(startupProfilerEnabled)recordStartupEvent(name,attrs);if(acpStartupProfilerEnabled)recordAcpConfigStartupEvent(name)})}setupUnhandledRejectionHandler();initializeWarningHandler();const privateAcpParentCapability=process.env[PRIVATE_ACP_CAPABILITY_ENV];delete process.env[PRIVATE_ACP_CAPABILITY_ENV];const conversationsRuntimeMarkerSeen=process.env[PRIVATE_CONVERSATIONS_RUNTIME_ENV]===PRIVATE_CONVERSATIONS_RUNTIME_ENABLE;delete process.env[PRIVATE_CONVERSATIONS_RUNTIME_ENV];const privateExternalToolGuard=process.env[PRIVATE_EXTERNAL_TOOL_GUARD_ENV]===EXTERNAL_TOOL_GUARD_REQUIRED_VALUE?EXTERNAL_TOOL_GUARD_REQUIRED_VALUE:void 0;delete process.env[PRIVATE_EXTERNAL_TOOL_GUARD_ENV];const privateExternalToolGuardProvider=process.env[PRIVATE_EXTERNAL_TOOL_GUARD_PROVIDER_ENV]===EXTERNAL_TOOL_GUARD_PROVIDER_ATTACHED_VALUE?EXTERNAL_TOOL_GUARD_PROVIDER_ATTACHED_VALUE:void 0;delete process.env[PRIVATE_EXTERNAL_TOOL_GUARD_PROVIDER_ENV];if(process.argv.includes("--bare")){process.env[QWEN_CODE_SIMPLE_ENV_VAR]="1"}preResolveHomeEnvOverrides();markAcpStartup("argsParseStart");let argv=await parseArguments();delete process.env[EXTERNAL_TOOL_GUARD_TOKEN_ENV];markAcpStartup("argsParseEnd");profileCheckpoint("after_parse_arguments");const isAcpMode=argv.acp||argv.experimentalAcp;const conversationsRuntimeProvenance=isAcpMode&&privateAcpParentCapability!==void 0&&conversationsRuntimeMarkerSeen;if(argv.acpExecutionEngine!==void 0&&(argv.acpExecutionEngine!=="managed"||!isAcpMode||privateAcpParentCapability===void 0||conversationsRuntimeProvenance)){throw new Error("--acp-execution-engine is reserved for hosts spawned by qwen serve.")}const privateAcpChildEnv=isAcpMode&&privateAcpParentCapability!==void 0?{[PRIVATE_ACP_CAPABILITY_ENV]:privateAcpParentCapability,...conversationsRuntimeProvenance?{[PRIVATE_CONVERSATIONS_RUNTIME_ENV]:PRIVATE_CONVERSATIONS_RUNTIME_ENABLE}:{},...privateExternalToolGuard?{[PRIVATE_EXTERNAL_TOOL_GUARD_ENV]:privateExternalToolGuard,...privateExternalToolGuardProvider?{[PRIVATE_EXTERNAL_TOOL_GUARD_PROVIDER_ENV]:privateExternalToolGuardProvider}:{}}:{}}:void 0;if((argv.acp||argv.experimentalAcp)&&process.env["QWEN_CODE_SCRUB_ELECTRON_RUN_AS_NODE"]==="1"){delete process.env["ELECTRON_RUN_AS_NODE"];if(process.env["QWEN_CODE_NO_RELAUNCH"]||process.env["SANDBOX"]){delete process.env["QWEN_CODE_SCRUB_ELECTRON_RUN_AS_NODE"]}}if(isBareMode(argv.bare)){process.env[QWEN_CODE_SIMPLE_ENV_VAR]="1"}markAcpStartup("settingsLoadStart");const settings=isBareMode(argv.bare)?createMinimalSettings():loadSettings();markAcpStartup("settingsLoadEnd");const executionSandboxSettings=validateExecutionSandboxSelection(settings.merged,argv);if(executionSandboxSettings&&(argv.acp||argv.experimentalAcp||argv.worktree!==void 0||argv.experimentalLsp||argv.mcpConfig||argv.extensions?.length)){throw new Error("tools.executionSandbox does not yet support ACP, worktree management, LSP, MCP or extensions.")}delete process.env[PRIVATE_CONVERSATIONS_RUNTIME_ENV];if(settings.corruptedPath){process.env[ENV_CORRUPTED_PATH]=settings.corruptedPath;process.env[ENV_WAS_RECOVERED]=settings.wasRecovered?"1":"0"}if(!executionSandboxSettings)await cleanupCheckpoints();profileCheckpoint("after_load_settings");const settingsWarnings=getSettingsWarnings(settings);for(const warning of settingsWarnings){writeStderrLine(warning)}if(settings.corruptedPath){writeStderrLine("Warning: Workspace settings had invalid JSON. A copy of the corrupted file has been saved at: "+settings.corruptedPath)}if(argv.listExtensions){await initializeI18n(resolveLanguageSetting(settings.merged.general?.language));const{handleList:handleListExtensions}=await import("./list-U2AEVLFP.js");await handleListExtensions();process.exit(0)}if(argv.promptInteractive&&!process.stdin.isTTY){writeStderrLine("Error: The --prompt-interactive flag cannot be used when input is piped from stdin.");process.exit(1)}const isDebugMode3=isDebugMode(argv);dns.setDefaultResultOrder(validateDnsResolutionOrder(settings.merged.advanced?.dnsResolutionOrder));const{themeManager,AUTO_THEME_NAME}=await import("./theme-manager-AANEBPLJ.js");themeManager.loadCustomThemes(settings.merged.ui?.customThemes);const configuredTheme=settings.merged.ui?.theme;if(configuredTheme&&configuredTheme!==AUTO_THEME_NAME){if(!themeManager.setActiveTheme(configuredTheme)){writeStderrLine(`Warning: Theme "${configuredTheme}" not found.`)}}else if(process.stdout.isTTY&&!(!argv.promptInteractive&&(argv.outputFormat==="json"||argv.outputFormat==="stream-json")&&!!(argv.query||argv.prompt))){themeManager.setActiveTheme(AUTO_THEME_NAME)}if(!process.env["SANDBOX"]){const memoryArgs=settings.merged.advanced?.autoConfigureMemory?getNodeMemoryArgs(isDebugMode3):[];const updateProjectRoot=process.cwd();const onUpdateRelaunch=__name(async relaunchOnFailure=>{await initializeI18n(resolveLanguageSetting(settings.merged.general?.language));const{updateBeforeRelaunch}=await import("./update-relaunch-A67BS7QS.js");const shouldRelaunch=await updateBeforeRelaunch(settings,updateProjectRoot,relaunchOnFailure);return shouldRelaunch?UPDATE_COMPLETE_EXIT_CODE:0},"onUpdateRelaunch");const sandboxConfig=await loadSandboxConfig(settings.merged,argv);const npmBunHandoff=selectNpmBunHandoff({interactive:isInteractiveInvocation(argv)&&Boolean(process.stdout.isTTY),screenReader:argv.screenReader??settings.merged.ui?.accessibility?.screenReader??false,protocolMode:Boolean(isAcpMode||argv.inputFormat==="stream-json"||(argv.inputFile??settings.merged.dualOutput?.inputFile)||argv.jsonFd!==void 0),sandbox:Boolean(sandboxConfig)});const customSandboxImage=argv.sandboxImage??process.env["QWEN_SANDBOX_IMAGE"]??settings.merged.tools?.sandboxImage;const containerSandbox=sandboxConfig?.command==="docker"||sandboxConfig?.command==="podman"?sandboxConfig:void 0;if(containerSandbox?.image&&customSandboxImage){process.env[CUSTOM_SANDBOX_IMAGE_ENV_VAR]=containerSandbox.image}else if(containerSandbox){const hostInstallationInfo=getInstallationInfo(updateProjectRoot,true);process.env[HOST_UPDATE_RELAUNCH_ENV_VAR]=String(Boolean(hostInstallationInfo.updateCommand||hostInstallationInfo.isStandalone&&hostInstallationInfo.standaloneDir))}if(sandboxConfig){const partialConfig=await loadCliConfig(settings.merged,argv,void 0,[],{systemHooks:settings.getSystemHooks(),userHooks:settings.getUserHooks(),projectHooks:settings.getProjectHooks()},buildDisabledSkillNamesProvider(settings),void 0,void 0,void 0,privateAcpParentCapability===void 0?{workflowAncestorTrustProvider:createLocalWorkflowAncestorTrustProvider(getOperatorTrustSettings(settings))}:void 0,buildEnabledSkillNamesProvider(settings));if(!settings.merged.security?.auth?.useExternal){try{const authType=partialConfig.getModelsConfig().getCurrentAuthType();if(authType){const err=validateAuthMethod(authType,partialConfig);if(err){throw new Error(err)}await partialConfig.refreshAuth(authType)}}catch(err){writeStderrLine(`Error authenticating: ${err}`);process.exit(1)}}const inputFormat=argv.inputFormat;const isAcpMode2=argv.acp||argv.experimentalAcp;let stdinData="";if(!process.stdin.isTTY&&inputFormat!=="stream-json"&&!isAcpMode2){stdinData=await readStdin()}const injectStdinIntoArgs=__name((args,stdinData2)=>{const finalArgs=[...args];if(stdinData2){const promptIndex=finalArgs.findIndex(arg=>arg==="--prompt"||arg==="-p");if(promptIndex>-1&&finalArgs.length>promptIndex+1){finalArgs[promptIndex+1]=`${stdinData2}
17
17
 
18
- ${finalArgs[promptIndex+1]}`}else{finalArgs.push("--prompt",stdinData2)}}return finalArgs},"injectStdinIntoArgs");const injectSandboxSessionIdIntoArgs=__name((args,sessionId2)=>{const separatorIndex=args.indexOf("--");const cliArgs=separatorIndex<0?args:args.slice(0,separatorIndex);const hasArg=__name(names=>cliArgs.some(arg=>names.some(name=>arg===name||arg.startsWith(`${name}=`))),"hasArg");if(hasArg(["--session-id","--sandbox-session-id"])||hasArg(["--continue","-c"])||hasArg(["--resume","-r"])){return args}const sessionArgs=["--sandbox-session-id",sessionId2];if(separatorIndex<0){return[...args,...sessionArgs]}return[...cliArgs,...sessionArgs,...args.slice(separatorIndex)]},"injectSandboxSessionIdIntoArgs");const sessionId=partialConfig.getSessionId();const sandboxArgs=sessionId?injectSandboxSessionIdIntoArgs(injectStdinIntoArgs(process.argv,stdinData),sessionId):injectStdinIntoArgs(process.argv,stdinData);delete process.env[PRIVATE_CONVERSATIONS_RUNTIME_ENV];await relaunchOnExitCode(()=>start_sandbox(sandboxConfig,memoryArgs,partialConfig,sandboxArgs,privateAcpChildEnv),{onUpdateRelaunch});process.exit(0)}else if(!npmBunHandoff&&memoryArgs.length===0&&!hasLoadedEnvironmentValues()&&!isAcpMode&&argv.inputFormat!=="stream-json"&&!(argv.inputFile??settings.merged.dualOutput?.inputFile)&&argv.jsonFd===void 0&&typeof process.execve==="function"&&!["win32","os400"].includes(process.platform)){superviseInProcess(onUpdateRelaunch)}else{await relaunchAppInChildProcess(memoryArgs,[],{interpreter:npmBunHandoff?.interpreter,afterSpawn:clearCorruptionEnvVars,childEnv:{...privateAcpChildEnv,...getRelaunchEnvProvenance(),...npmBunHandoff?.childEnv},environmentChangedSinceBoot:hasLoadedEnvironmentValues(),onUpdateRelaunch,replaceProcess:!isAcpMode&&argv.inputFormat!=="stream-json"&&!argv.promptInteractive&&!(argv.inputFile??settings.merged.dualOutput?.inputFile)&&argv.jsonFd===void 0&&Boolean(argv.prompt)})}}if(isAcpMode&&process.env[QWEN_CODE_SERVE_ENV]==="1"){scrubAndReportInheritedLoaderEnv(process.env,"qwen","ACP child",processBootLoaderEnv)}if(argv.worktree!==void 0){const launchCwdForPaths=process.cwd();const looksLikeInlineJson=__name(v=>{const t=v.trim();return t.startsWith("{")||t.startsWith("[")},"looksLikeInlineJson");const resolveIfPath=__name(v=>{if(typeof v!=="string"||v.length===0)return v;if(looksLikeInlineJson(v))return v;return path8.resolve(launchCwdForPaths,v)},"resolveIfPath");argv.mcpConfig=resolveIfPath(argv.mcpConfig);argv.openaiLoggingDir=resolveIfPath(argv.openaiLoggingDir);argv.jsonFile=resolveIfPath(argv.jsonFile);argv.inputFile=resolveIfPath(argv.inputFile);argv.telemetryOutfile=resolveIfPath(argv.telemetryOutfile);if(Array.isArray(argv.includeDirectories)){argv.includeDirectories=argv.includeDirectories.map(d=>typeof d==="string"&&d.length>0?path8.resolve(launchCwdForPaths,d):d)}if(typeof argv.jsonSchema==="string"){const trimmedSchema=argv.jsonSchema.trim();if(trimmedSchema.startsWith("@")){const rel=trimmedSchema.slice(1);if(rel.length>0&&!path8.isAbsolute(rel)){argv.jsonSchema="@"+path8.resolve(launchCwdForPaths,rel)}}}}let startupWorktreeContext=null;if(argv.worktree!==void 0&&(argv.acp||argv.experimentalAcp)){writeStderrLine("--worktree cannot be combined with --acp / --experimental-acp. Pass the worktree path as the cwd of the ACP loadSession / newSession request instead.");process.exit(1)}{const startupRes=await setupStartupWorktree(argv.worktree,{symlinkDirectories:settings.merged.worktree?.symlinkDirectories});if(startupRes!==null){if(!startupRes.ok){writeStderrLine(startupRes.error);process.exit(1)}startupWorktreeContext=startupRes.context}}if(argv.resume!==void 0){Storage.setRuntimeBaseDir(settings.merged.advanced?.runtimeOutputDir,process.cwd());let resolvedSessionId;if(argv.resume===""){const{showResumeSessionPicker}=await import("./StandaloneSessionPicker-BAFAIRT7.js");resolvedSessionId=await showResumeSessionPicker()}else if(!isValidSessionId(argv.resume)){const sessionService=new SessionService(process.cwd());const matches=await sessionService.findSessionsByTitle(argv.resume);if(matches.length===1){resolvedSessionId=matches[0].sessionId}else if(matches.length>1){writeStderrLine(`Multiple sessions found with title "${argv.resume}". Please select one:`);const{showResumeSessionPicker}=await import("./StandaloneSessionPicker-BAFAIRT7.js");resolvedSessionId=await showResumeSessionPicker(process.cwd(),matches)}}if(resolvedSessionId!==void 0){argv={...argv,resume:resolvedSessionId}}else if(argv.resume===""||!isValidSessionId(argv.resume)){if(argv.resume!==""){writeStderrLine(`No saved session found with title "${argv.resume}".`);process.exit(1)}else{process.exit(0)}}}profileCheckpoint("after_sandbox_check");if(!isBareMode(argv.bare)){initializeLlmOutputLanguage(settings.merged.general?.outputLanguage)}{const settingsWatcher=isBareMode(argv.bare)?void 0:new SettingsWatcher(settings);settingsWatcher?.startWatching();markAcpStartup("configConstructionStart");const config=await loadCliConfig(settings.merged,argv.acp||argv.experimentalAcp?{...argv,chatRecording:false}:argv,process.cwd(),argv.extensions,{systemHooks:settings.getSystemHooks(),userHooks:settings.getUserHooks(),projectHooks:settings.getProjectHooks()},buildDisabledSkillNamesProvider(settings),void 0,settingsWatcher,void 0,privateAcpParentCapability===void 0?{workflowAncestorTrustProvider:createLocalWorkflowAncestorTrustProvider(getOperatorTrustSettings(settings))}:void 0,buildEnabledSkillNamesProvider(settings));markAcpStartup("configConstructionEnd");profileCheckpoint("after_load_cli_config");if(config.isInteractive()&&!config.getExperimentalZedIntegration()){const{assertFullIcuAvailable}=await import("./icu-check-ZRFBB545.js");assertFullIcuAvailable()}const nonInteractiveHousekeeping=!config.isInteractive()||config.getExperimentalZedIntegration()?await import("./scheduler-KCMSPHON.js"):void 0;if(nonInteractiveHousekeeping){registerCleanup(()=>nonInteractiveHousekeeping.stopNonInteractiveOpenAILogHousekeeping())}if(settingsWatcher&&!config.getShellExecutionSandbox?.()){registerCleanup(settingsWatcher.addChangeListener(()=>{config.setWorkflowKeywordTriggerEnabled(settings.merged.ui?.disableWorkflowKeywordTrigger!==true)}));const disposeMcpHotReload=registerMcpHotReload(settingsWatcher,settings,config,config.getTopTierMcpServers());registerCleanup(disposeMcpHotReload);const disposeModelProvidersHotReload=registerModelProvidersHotReload(settingsWatcher,settings,config);registerCleanup(disposeModelProvidersHotReload)}registerLspHotReload(config,registerCleanup);const extensionRefreshState=new ExtensionRefreshState;const extensionFileWatcher=isBareMode(argv.bare)||config.isSafeMode()||config.getShellExecutionSandbox?.()?void 0:new ExtensionFileWatcher(config,void 0,extensionRefreshState);extensionFileWatcher?.startWatching();if(extensionFileWatcher){const restartExtensionWatcher=__name(()=>extensionFileWatcher.restartWatching(),"restartExtensionWatcher");extensionRefreshState.on("extensions-reloaded",restartExtensionWatcher);registerCleanup(()=>{extensionRefreshState.off("extensions-reloaded",restartExtensionWatcher);extensionFileWatcher.stopWatching()})}if(startupWorktreeContext){config.setPendingStartupWorktreeNotice(buildStartupWorktreeNotice(startupWorktreeContext));try{const startupWorktreePersist=await persistStartupWorktreeSidecar(config,startupWorktreeContext);if(startupWorktreePersist.overrodeResumedWorktree){writeStderrLine(`--worktree overrode the resumed session's previous worktree "${startupWorktreePersist.overriddenSlug??"(unknown)"}". That worktree directory was left intact on disk.`)}config.setPendingStartupWorktreeNotice(buildStartupWorktreeNotice(startupWorktreeContext,startupWorktreePersist))}catch(error){if(error instanceof WorktreeOwnershipConflictError)throw error;debugLogger6.warn(`--worktree sidecar persist failed (non-fatal, notice preserved): ${error instanceof Error?error.message:String(error)}`)}}registerCleanup(()=>{try{const metrics=uiTelemetryService.getMetrics();const hasActivity=Object.values(metrics.models).some(m=>m.api.totalRequests>0);if(!hasActivity)return;persistSessionUsage({sessionId:config.getSessionId(),startTime:uiTelemetryService.getSessionStartTime(),endTime:new Date,project:config.getProjectRoot(),metrics})}catch{}});registerCleanup(()=>config.shutdownExecutionEnvironments(),{first:true});registerCleanup(()=>config.shutdown());setupUncaughtExceptionHandler(config);startEarlyStartupPrefetches(config);const wasRaw=process.stdin.isRaw;let kittyProtocolDetectionComplete;let themeAutoDetectionComplete;if(config.isInteractive()){registerCleanup(installInteractiveSignalHandlers(wasRaw))}if(config.isInteractive()&&!wasRaw&&process.stdin.isTTY){const{startEarlyInputCapture,stopAndGetCapturedInput}=await import("./earlyInputCapture-25433Q5Q.js");const{detectAndEnableKittyProtocol}=await import("./kittyProtocolDetector-QP3H46YU.js");process.stdin.setRawMode(true);startEarlyInputCapture();registerCleanup(()=>stopAndGetCapturedInput());kittyProtocolDetectionComplete=detectAndEnableKittyProtocol();if(!configuredTheme||configuredTheme===AUTO_THEME_NAME){themeAutoDetectionComplete=themeManager.resolveAutoThemeAsync().catch(err=>{debugLogger6.warn("Async theme auto-detection failed:",err)})}}if(config.isInteractive()){const{setMaxSizedBoxDebugging}=await import("./MaxSizedBox-QCIXIS4P.js");setMaxSizedBoxDebugging(isDebugMode3)}const inputFormat=process.stdin.isTTY?"text":typeof config.getInputFormat==="function"?config.getInputFormat():"text";const{initializeApp}=await import("./initializer-FRKYDUSX.js");let input=config.getQuestion();const hasRemoteInput=Boolean(config.getInputFile?.());const deferIdeConnection=config.isInteractive()&&!config.getExperimentalZedIntegration()&&!input&&!hasRemoteInput;markAcpStartup("appInitializationStart");const initializationResult=await initializeApp(config,settings,{deferIdeConnection});markAcpStartup("appInitializationEnd");profileCheckpoint("after_initialize_app");if(config.getExperimentalZedIntegration()){markAcpStartup("acpImportStart");const{runAcpAgent}=await import("./acpAgent-67UN66PB.js");markAcpStartup("acpImportEnd");const managedRuntimeEnvironment=argv.acpExecutionEngine==="managed"?(await import("./managed-runtime-session-worker-RKQBBFR6.js")).createManagedRuntimeEnvironment:void 0;try{await runAcpAgent(config,settings,argv,{privateParentCapability:isAcpMode?privateAcpParentCapability:void 0,conversationsRuntimeProvenance,executionEngine:argv.acpExecutionEngine,managedRuntimeEnvironment,externalToolGuardRequired:isAcpMode&&privateAcpParentCapability!==void 0&&privateExternalToolGuard===EXTERNAL_TOOL_GUARD_REQUIRED_VALUE,externalToolGuardProviderAttached:isAcpMode&&privateAcpParentCapability!==void 0&&privateExternalToolGuardProvider===EXTERNAL_TOOL_GUARD_PROVIDER_ATTACHED_VALUE})}finally{prepareFileWatchersForProcessExit();await runExitCleanup()}process.exit(0)}const startupWarnings=[...new Set([...config.isSafeMode()?["\u26A0 SAFE MODE \u2014 all customizations disabled (hooks, extensions, skills, MCP servers, QWEN.md). Restart without --safe-mode to resume normal operation."]:[],...await getStartupWarnings(),...await getUserStartupWarnings({workspaceRoot:process.cwd(),useRipgrep:settings.merged.tools?.useRipgrep??true,useBuiltinRipgrep:settings.merged.tools?.useBuiltinRipgrep??true}),...getSettingsWarnings(settings),...config.getWarnings(),...config.getModelsConfig().getCurrentAuthType()==="qwen-oauth"?["Qwen OAuth free tier was discontinued on 2026-04-15. Run /auth to switch to Coding Plan or another provider."]:[]])];const emittedStartupWarnings=new Set(startupWarnings);for(const warning of startupWarnings){writeStderrLine(warning)}profileCheckpoint("before_render");if(config.isInteractive()){const interruptedWorkflowsNotice=await getInterruptedWorkflowRunsNotice(config);if(interruptedWorkflowsNotice){startupWarnings.push(interruptedWorkflowsNotice)}if(config.getJsonSchema?.()){writeStderrLine("Error: --json-schema is a headless-only flag. Provide a one-shot prompt via -p / --prompt or pipe one in via stdin.");await runExitCleanup();process.exit(1)}setInteractiveMode(true);await kittyProtocolDetectionComplete;await themeAutoDetectionComplete;if(settings.merged.experimental?.mods){const{createInteractiveModSession}=await import("./interactive-mod-session-MWYN5IFK.js");createInteractiveModSession(config,settings)}const{selectTuiRenderer,TUI_RENDERER_STRICT_ENV_VAR}=await import("./renderer-selection-YDH3JZ4J.js");const selection=selectTuiRenderer(void 0,void 0,process.env,config.getScreenReader());if(selection.renderer==="opentui"){try{const{startOpenTuiUI}=await import("./start-opentui-ui-33QLBNRC.js");const started=await startOpenTuiUI(config,settings,startupWarnings,process.cwd(),initializationResult,{postRenderConnectIde:deferIdeConnection,extensionRefreshState});if(started){clearCorruptionEnvVars();return}if(selection.strict){throw new Error(`OpenTUI failed to start and ${TUI_RENDERER_STRICT_ENV_VAR} forbids the ink fallback`)}}catch(err){if(selection.strict){throw err}debugLogger6.error("OpenTUI boot failed; falling back to ink:",err);writeStderrLine(`Warning: OpenTUI failed to start \u2014 ${err instanceof Error?err.message:String(err)} (falling back to ink)`)}}else{debugLogger6.debug(`TUI renderer: ${selection.reason}`)}const{startInteractiveUI}=await import("./startInteractiveUI-RQKHD7MM.js");await startInteractiveUI(config,settings,startupWarnings,process.cwd(),initializationResult,{postRenderConnectIde:deferIdeConnection,extensionRefreshState});clearCorruptionEnvVars();return}clearCorruptionEnvVars();if(config.getDebugMode()){writeStderrLine("Debug mode enabled");if(isDebugLogFileEnabled()){writeStderrLine(`Logging to: ${Storage.getDebugLogPath(config.getSessionId())}`)}else{writeStderrLine("Debug log file disabled by QWEN_DEBUG_LOG_FILE")}if(isDebugLoggingDegraded()){writeStderrLine("Warning: Debug logging is degraded (write failures occurred)")}}if(!config.isInteractive()){const yoloWarning=getHeadlessYoloSafetyWarning(config);if(yoloWarning)writeStderrLine(yoloWarning)}if(inputFormat!=="stream-json"){profileCheckpoint("config_initialize_start");await config.initialize();for(const warning of config.getWarnings()){if(emittedStartupWarnings.has(warning))continue;emittedStartupWarnings.add(warning);writeStderrLine(warning)}profileCheckpoint("config_initialize_end");await config.waitForMcpReady();const failedMcpServers=typeof config.getFailedMcpServerNames==="function"?config.getFailedMcpServerNames():[];if(failedMcpServers.length>0){writeStderrLine(`Warning: MCP server(s) failed to start: ${failedMcpServers.join(", ")}. Continuing with built-in tools and any servers that did connect. Re-run with QWEN_CODE_DEBUG=1 to see per-server reasons.`)}finalizeStartupProfile(config.getSessionId())}if(inputFormat!=="stream-json"&&!process.stdin.isTTY){const stdinData=await readStdin();if(stdinData){input=`${stdinData}
18
+ ${finalArgs[promptIndex+1]}`}else{finalArgs.push("--prompt",stdinData2)}}return finalArgs},"injectStdinIntoArgs");const injectSandboxSessionIdIntoArgs=__name((args,sessionId2)=>{const separatorIndex=args.indexOf("--");const cliArgs=separatorIndex<0?args:args.slice(0,separatorIndex);const hasArg=__name(names=>cliArgs.some(arg=>names.some(name=>arg===name||arg.startsWith(`${name}=`))),"hasArg");if(hasArg(["--session-id","--sandbox-session-id"])||hasArg(["--continue","-c"])||hasArg(["--resume","-r"])){return args}const sessionArgs=["--sandbox-session-id",sessionId2];if(separatorIndex<0){return[...args,...sessionArgs]}return[...cliArgs,...sessionArgs,...args.slice(separatorIndex)]},"injectSandboxSessionIdIntoArgs");const sessionId=partialConfig.getSessionId();const sandboxArgs=sessionId?injectSandboxSessionIdIntoArgs(injectStdinIntoArgs(process.argv,stdinData),sessionId):injectStdinIntoArgs(process.argv,stdinData);delete process.env[PRIVATE_CONVERSATIONS_RUNTIME_ENV];await relaunchOnExitCode(()=>start_sandbox(sandboxConfig,memoryArgs,partialConfig,sandboxArgs,privateAcpChildEnv),{onUpdateRelaunch});process.exit(0)}else if(!npmBunHandoff&&memoryArgs.length===0&&!hasLoadedEnvironmentValues()&&!isAcpMode&&argv.inputFormat!=="stream-json"&&!(argv.inputFile??settings.merged.dualOutput?.inputFile)&&argv.jsonFd===void 0&&typeof process.execve==="function"&&!["win32","os400"].includes(process.platform)){superviseInProcess(onUpdateRelaunch)}else{await relaunchAppInChildProcess(memoryArgs,[],{interpreter:npmBunHandoff?.interpreter,afterSpawn:clearCorruptionEnvVars,childEnv:{...privateAcpChildEnv,...getRelaunchEnvProvenance(),...npmBunHandoff?.childEnv},environmentChangedSinceBoot:hasLoadedEnvironmentValues(),onUpdateRelaunch,replaceProcess:!isAcpMode&&argv.inputFormat!=="stream-json"&&!argv.promptInteractive&&!(argv.inputFile??settings.merged.dualOutput?.inputFile)&&argv.jsonFd===void 0&&Boolean(argv.prompt)})}}if(isAcpMode&&process.env[QWEN_CODE_SERVE_ENV]==="1"){scrubAndReportInheritedLoaderEnv(process.env,"qwen","ACP child",processBootLoaderEnv)}if(argv.worktree!==void 0){const launchCwdForPaths=process.cwd();const looksLikeInlineJson=__name(v=>{const t=v.trim();return t.startsWith("{")||t.startsWith("[")},"looksLikeInlineJson");const resolveIfPath=__name(v=>{if(typeof v!=="string"||v.length===0)return v;if(looksLikeInlineJson(v))return v;return path8.resolve(launchCwdForPaths,v)},"resolveIfPath");argv.mcpConfig=resolveIfPath(argv.mcpConfig);argv.openaiLoggingDir=resolveIfPath(argv.openaiLoggingDir);argv.jsonFile=resolveIfPath(argv.jsonFile);argv.inputFile=resolveIfPath(argv.inputFile);argv.telemetryOutfile=resolveIfPath(argv.telemetryOutfile);if(Array.isArray(argv.includeDirectories)){argv.includeDirectories=argv.includeDirectories.map(d=>typeof d==="string"&&d.length>0?path8.resolve(launchCwdForPaths,d):d)}if(typeof argv.jsonSchema==="string"){const trimmedSchema=argv.jsonSchema.trim();if(trimmedSchema.startsWith("@")){const rel=trimmedSchema.slice(1);if(rel.length>0&&!path8.isAbsolute(rel)){argv.jsonSchema="@"+path8.resolve(launchCwdForPaths,rel)}}}}let startupWorktreeContext=null;if(argv.worktree!==void 0&&(argv.acp||argv.experimentalAcp)){writeStderrLine("--worktree cannot be combined with --acp / --experimental-acp. Pass the worktree path as the cwd of the ACP loadSession / newSession request instead.");process.exit(1)}{const startupRes=await setupStartupWorktree(argv.worktree,{symlinkDirectories:settings.merged.worktree?.symlinkDirectories});if(startupRes!==null){if(!startupRes.ok){writeStderrLine(startupRes.error);process.exit(1)}startupWorktreeContext=startupRes.context}}if(argv.resume!==void 0){Storage.setRuntimeBaseDir(settings.merged.advanced?.runtimeOutputDir,process.cwd());let resolvedSessionId;if(argv.resume===""){const{showResumeSessionPicker}=await import("./StandaloneSessionPicker-B7N4QO5D.js");resolvedSessionId=await showResumeSessionPicker()}else if(!isValidSessionId(argv.resume)){const sessionService=new SessionService(process.cwd());const matches=await sessionService.findSessionsByTitle(argv.resume);if(matches.length===1){resolvedSessionId=matches[0].sessionId}else if(matches.length>1){writeStderrLine(`Multiple sessions found with title "${argv.resume}". Please select one:`);const{showResumeSessionPicker}=await import("./StandaloneSessionPicker-B7N4QO5D.js");resolvedSessionId=await showResumeSessionPicker(process.cwd(),matches)}}if(resolvedSessionId!==void 0){argv={...argv,resume:resolvedSessionId}}else if(argv.resume===""||!isValidSessionId(argv.resume)){if(argv.resume!==""){writeStderrLine(`No saved session found with title "${argv.resume}".`);process.exit(1)}else{process.exit(0)}}}profileCheckpoint("after_sandbox_check");if(!isBareMode(argv.bare)){initializeLlmOutputLanguage(settings.merged.general?.outputLanguage)}{const settingsWatcher=isBareMode(argv.bare)?void 0:new SettingsWatcher(settings);settingsWatcher?.startWatching();markAcpStartup("configConstructionStart");const config=await loadCliConfig(settings.merged,argv.acp||argv.experimentalAcp?{...argv,chatRecording:false}:argv,process.cwd(),argv.extensions,{systemHooks:settings.getSystemHooks(),userHooks:settings.getUserHooks(),projectHooks:settings.getProjectHooks()},buildDisabledSkillNamesProvider(settings),void 0,settingsWatcher,void 0,privateAcpParentCapability===void 0?{workflowAncestorTrustProvider:createLocalWorkflowAncestorTrustProvider(getOperatorTrustSettings(settings))}:void 0,buildEnabledSkillNamesProvider(settings));markAcpStartup("configConstructionEnd");profileCheckpoint("after_load_cli_config");if(config.isInteractive()&&!config.getExperimentalZedIntegration()){const{assertFullIcuAvailable}=await import("./icu-check-ZRFBB545.js");assertFullIcuAvailable()}const nonInteractiveHousekeeping=!config.isInteractive()||config.getExperimentalZedIntegration()?await import("./scheduler-RUV2FNDR.js"):void 0;if(nonInteractiveHousekeeping){registerCleanup(()=>nonInteractiveHousekeeping.stopNonInteractiveOpenAILogHousekeeping())}if(settingsWatcher&&!config.getShellExecutionSandbox?.()){registerCleanup(settingsWatcher.addChangeListener(()=>{config.setWorkflowKeywordTriggerEnabled(settings.merged.ui?.disableWorkflowKeywordTrigger!==true)}));const disposeMcpHotReload=registerMcpHotReload(settingsWatcher,settings,config,config.getTopTierMcpServers());registerCleanup(disposeMcpHotReload);const disposeModelProvidersHotReload=registerModelProvidersHotReload(settingsWatcher,settings,config);registerCleanup(disposeModelProvidersHotReload)}registerLspHotReload(config,registerCleanup);const extensionRefreshState=new ExtensionRefreshState;const extensionFileWatcher=isBareMode(argv.bare)||config.isSafeMode()||config.getShellExecutionSandbox?.()?void 0:new ExtensionFileWatcher(config,void 0,extensionRefreshState);extensionFileWatcher?.startWatching();if(extensionFileWatcher){const restartExtensionWatcher=__name(()=>extensionFileWatcher.restartWatching(),"restartExtensionWatcher");extensionRefreshState.on("extensions-reloaded",restartExtensionWatcher);registerCleanup(()=>{extensionRefreshState.off("extensions-reloaded",restartExtensionWatcher);extensionFileWatcher.stopWatching()})}if(startupWorktreeContext){config.setPendingStartupWorktreeNotice(buildStartupWorktreeNotice(startupWorktreeContext));try{const startupWorktreePersist=await persistStartupWorktreeSidecar(config,startupWorktreeContext);if(startupWorktreePersist.overrodeResumedWorktree){writeStderrLine(`--worktree overrode the resumed session's previous worktree "${startupWorktreePersist.overriddenSlug??"(unknown)"}". That worktree directory was left intact on disk.`)}config.setPendingStartupWorktreeNotice(buildStartupWorktreeNotice(startupWorktreeContext,startupWorktreePersist))}catch(error){if(error instanceof WorktreeOwnershipConflictError)throw error;debugLogger6.warn(`--worktree sidecar persist failed (non-fatal, notice preserved): ${error instanceof Error?error.message:String(error)}`)}}registerCleanup(()=>{try{const metrics=uiTelemetryService.getMetrics();const hasActivity=Object.values(metrics.models).some(m=>m.api.totalRequests>0);if(!hasActivity)return;persistSessionUsage({sessionId:config.getSessionId(),startTime:uiTelemetryService.getSessionStartTime(),endTime:new Date,project:config.getProjectRoot(),metrics})}catch{}});registerCleanup(()=>config.shutdownExecutionEnvironments(),{first:true});registerCleanup(()=>config.shutdown());setupUncaughtExceptionHandler(config);startEarlyStartupPrefetches(config);const wasRaw=process.stdin.isRaw;let kittyProtocolDetectionComplete;let themeAutoDetectionComplete;if(config.isInteractive()){registerCleanup(installInteractiveSignalHandlers(wasRaw))}if(config.isInteractive()&&!wasRaw&&process.stdin.isTTY){const{startEarlyInputCapture,stopAndGetCapturedInput}=await import("./earlyInputCapture-25433Q5Q.js");const{detectAndEnableKittyProtocol}=await import("./kittyProtocolDetector-QP3H46YU.js");process.stdin.setRawMode(true);startEarlyInputCapture();registerCleanup(()=>stopAndGetCapturedInput());kittyProtocolDetectionComplete=detectAndEnableKittyProtocol();if(!configuredTheme||configuredTheme===AUTO_THEME_NAME){themeAutoDetectionComplete=themeManager.resolveAutoThemeAsync().catch(err=>{debugLogger6.warn("Async theme auto-detection failed:",err)})}}if(config.isInteractive()){const{setMaxSizedBoxDebugging}=await import("./MaxSizedBox-LUINLOQW.js");setMaxSizedBoxDebugging(isDebugMode3)}const inputFormat=process.stdin.isTTY?"text":typeof config.getInputFormat==="function"?config.getInputFormat():"text";const{initializeApp}=await import("./initializer-NLYOGZZS.js");let input=config.getQuestion();const hasRemoteInput=Boolean(config.getInputFile?.());const deferIdeConnection=config.isInteractive()&&!config.getExperimentalZedIntegration()&&!input&&!hasRemoteInput;markAcpStartup("appInitializationStart");const initializationResult=await initializeApp(config,settings,{deferIdeConnection});markAcpStartup("appInitializationEnd");profileCheckpoint("after_initialize_app");if(config.getExperimentalZedIntegration()){markAcpStartup("acpImportStart");const{runAcpAgent}=await import("./acpAgent-XG6SM2VU.js");markAcpStartup("acpImportEnd");const managedRuntimeEnvironment=argv.acpExecutionEngine==="managed"?(await import("./managed-runtime-session-worker-UI23BTYJ.js")).createManagedRuntimeEnvironment:void 0;try{await runAcpAgent(config,settings,argv,{privateParentCapability:isAcpMode?privateAcpParentCapability:void 0,conversationsRuntimeProvenance,executionEngine:argv.acpExecutionEngine,managedRuntimeEnvironment,externalToolGuardRequired:isAcpMode&&privateAcpParentCapability!==void 0&&privateExternalToolGuard===EXTERNAL_TOOL_GUARD_REQUIRED_VALUE,externalToolGuardProviderAttached:isAcpMode&&privateAcpParentCapability!==void 0&&privateExternalToolGuardProvider===EXTERNAL_TOOL_GUARD_PROVIDER_ATTACHED_VALUE})}finally{prepareFileWatchersForProcessExit();await runExitCleanup()}process.exit(0)}const startupWarnings=[...new Set([...config.isSafeMode()?["\u26A0 SAFE MODE \u2014 all customizations disabled (hooks, extensions, skills, MCP servers, QWEN.md). Restart without --safe-mode to resume normal operation."]:[],...await getStartupWarnings(),...await getUserStartupWarnings({workspaceRoot:process.cwd(),useRipgrep:settings.merged.tools?.useRipgrep??true,useBuiltinRipgrep:settings.merged.tools?.useBuiltinRipgrep??true}),...getSettingsWarnings(settings),...config.getWarnings(),...config.getModelsConfig().getCurrentAuthType()==="qwen-oauth"?["Qwen OAuth free tier was discontinued on 2026-04-15. Run /auth to switch to Coding Plan or another provider."]:[]])];const emittedStartupWarnings=new Set(startupWarnings);for(const warning of startupWarnings){writeStderrLine(warning)}profileCheckpoint("before_render");if(config.isInteractive()){const interruptedWorkflowsNotice=await getInterruptedWorkflowRunsNotice(config);if(interruptedWorkflowsNotice){startupWarnings.push(interruptedWorkflowsNotice)}if(config.getJsonSchema?.()){writeStderrLine("Error: --json-schema is a headless-only flag. Provide a one-shot prompt via -p / --prompt or pipe one in via stdin.");await runExitCleanup();process.exit(1)}setInteractiveMode(true);await kittyProtocolDetectionComplete;await themeAutoDetectionComplete;if(settings.merged.experimental?.mods){const{createInteractiveModSession}=await import("./interactive-mod-session-5F7R3KSA.js");createInteractiveModSession(config,settings)}const{selectTuiRenderer,TUI_RENDERER_STRICT_ENV_VAR}=await import("./renderer-selection-YDH3JZ4J.js");const selection=selectTuiRenderer(void 0,void 0,process.env,config.getScreenReader());if(selection.renderer==="opentui"){try{const{startOpenTuiUI}=await import("./start-opentui-ui-M4B4SXRM.js");const started=await startOpenTuiUI(config,settings,startupWarnings,process.cwd(),initializationResult,{postRenderConnectIde:deferIdeConnection,extensionRefreshState});if(started){clearCorruptionEnvVars();return}if(selection.strict){throw new Error(`OpenTUI failed to start and ${TUI_RENDERER_STRICT_ENV_VAR} forbids the ink fallback`)}}catch(err){if(selection.strict){throw err}debugLogger6.error("OpenTUI boot failed; falling back to ink:",err);writeStderrLine(`Warning: OpenTUI failed to start \u2014 ${err instanceof Error?err.message:String(err)} (falling back to ink)`)}}else{debugLogger6.debug(`TUI renderer: ${selection.reason}`)}const{startInteractiveUI}=await import("./startInteractiveUI-O4JUDEAU.js");await startInteractiveUI(config,settings,startupWarnings,process.cwd(),initializationResult,{postRenderConnectIde:deferIdeConnection,extensionRefreshState});clearCorruptionEnvVars();return}clearCorruptionEnvVars();if(config.getDebugMode()){writeStderrLine("Debug mode enabled");if(isDebugLogFileEnabled()){writeStderrLine(`Logging to: ${Storage.getDebugLogPath(config.getSessionId())}`)}else{writeStderrLine("Debug log file disabled by QWEN_DEBUG_LOG_FILE")}if(isDebugLoggingDegraded()){writeStderrLine("Warning: Debug logging is degraded (write failures occurred)")}}if(!config.isInteractive()){const yoloWarning=getHeadlessYoloSafetyWarning(config);if(yoloWarning)writeStderrLine(yoloWarning)}if(inputFormat!=="stream-json"){profileCheckpoint("config_initialize_start");await config.initialize();for(const warning of config.getWarnings()){if(emittedStartupWarnings.has(warning))continue;emittedStartupWarnings.add(warning);writeStderrLine(warning)}profileCheckpoint("config_initialize_end");await config.waitForMcpReady();const failedMcpServers=typeof config.getFailedMcpServerNames==="function"?config.getFailedMcpServerNames():[];if(failedMcpServers.length>0){writeStderrLine(`Warning: MCP server(s) failed to start: ${failedMcpServers.join(", ")}. Continuing with built-in tools and any servers that did connect. Re-run with QWEN_CODE_DEBUG=1 to see per-server reasons.`)}finalizeStartupProfile(config.getSessionId())}if(inputFormat!=="stream-json"&&!process.stdin.isTTY){const stdinData=await readStdin();if(stdinData){input=`${stdinData}
19
19
 
20
- ${input}`}}const{validateNonInteractiveAuth}=await import("./validateNonInterActiveAuth-AO336KDX.js");const nonInteractiveConfig=await validateNonInteractiveAuth(settings.merged.security?.auth?.useExternal,config,settings);const prompt_id=createNonInteractivePromptId(config.getSessionId(),config.getResumedSessionData?.()?.conversation.messages);if(inputFormat==="stream-json"){const trimmedInput=(input??"").trim();const{runNonInteractiveStreamJson}=await import("./session-3LQLXPUA.js");nonInteractiveHousekeeping?.startNonInteractiveOpenAILogHousekeeping(nonInteractiveConfig,settings);try{await runNonInteractiveStreamJson(nonInteractiveConfig,trimmedInput.length>0?trimmedInput:"",settings)}finally{await runExitCleanup()}process.exit(process.exitCode??0)}if(!input){writeStderrLine(`No input provided via stdin. Input can be provided by piping data into gemini or using the --prompt option.`);process.exit(1)}logUserPrompt(config,{"event.name":"user_prompt","event.timestamp":new Date().toISOString(),prompt:input,prompt_id,auth_type:config.getContentGeneratorConfig()?.authType,prompt_length:input.length});debugLogger6.debug(`Session ID: ${config.getSessionId()}`);const{runNonInteractive}=await import("./nonInteractiveCli-MR7JLAWU.js");nonInteractiveHousekeeping?.startNonInteractiveOpenAILogHousekeeping(nonInteractiveConfig,settings);let exitCode;try{exitCode=await runNonInteractive(nonInteractiveConfig,settings,input,prompt_id)}finally{await runExitCleanup()}process.exit(exitCode)}}__name(main,"main");function createNonInteractivePromptId(sessionId,resumedRecords){const lastTurn=resumedRecords?.length?computeInitialTurnFromHistory(resumedRecords,sessionId):-1;return`${sessionId}########${lastTurn+1}`}__name(createNonInteractivePromptId,"createNonInteractivePromptId");function registerLspHotReload(config,registerCleanup2){const lspClient=config.getLspClient?.();const runtimeConfig=config;const reinitializeLsp=runtimeConfig.reinitializeLsp;if(config.isLspEnabled?.()!==true||!lspClient?.reinitialize||!reinitializeLsp){return}const lspConfigWatcher=new LspConfigWatcher(config.getProjectRoot());debugLogger6.info(`Registering LSP config hot reload watcher for ${config.getProjectRoot()}`);lspConfigWatcher.startWatching(async event=>{if(event.changeType==="invalid"){debugLogger6.warn(`Invalid LSP config file ${event.path}: ${event.error}`);appEvents.emit("log-error",event.error);return}debugLogger6.info(`Reloading LSP server settings: changeType=${event.changeType}, path=${event.path}`);let errorReported=false;try{const result=await reinitializeLsp();if(result){const failedServers=getRuntimeReloadFailedNames(result.reconcile);debugLogger6.info(`Reloaded LSP server settings: added=${formatRuntimeReloadNames(result.reconcile.added)}, removed=${formatRuntimeReloadNames(result.reconcile.removed)}, restarted=${formatRuntimeReloadNames(result.reconcile.restarted)}, unchanged=${formatRuntimeReloadNames(result.reconcile.unchanged)}, failed=${formatRuntimeReloadNames(failedServers)}, skipped=${formatRuntimeReloadNames(result.skipped.map(server=>server.name))}`);if(failedServers.length>0){appEvents.emit("lsp-status-changed");const changedServers=[...result.reconcile.added,...result.reconcile.removed,...result.reconcile.restarted];const message=`LSP reload partially completed: changed=${formatRuntimeReloadNames(changedServers)}, failed=${formatRuntimeReloadNames(failedServers)}. Run with --debug for details.`;appEvents.emit("log-error",message);errorReported=true;throw new Error(message)}}else{debugLogger6.info("Skipped LSP server settings reload because LSP is disabled or no client is available")}appEvents.emit("lsp-status-changed")}catch(error){debugLogger6.warn("Failed to reload LSP server settings:",error);if(!errorReported){const message=error instanceof Error?`Failed to reload LSP server settings: ${error.message}. Some LSP servers may have been partially updated. Run with --debug for details.`:"Failed to reload LSP server settings; some LSP servers may have been partially updated. Run with --debug for details.";appEvents.emit("log-error",message)}throw error}});registerCleanup2(()=>lspConfigWatcher.stopWatching())}__name(registerLspHotReload,"registerLspHotReload");function formatRuntimeReloadNames(names){return names.length===0?"<none>":names.join(",")}__name(formatRuntimeReloadNames,"formatRuntimeReloadNames");function getRuntimeReloadFailedNames(reconcile){return reconcile.failed??[]}__name(getRuntimeReloadFailedNames,"getRuntimeReloadFailedNames");export{createNonInteractivePromptId,main,registerLspHotReload,setupUncaughtExceptionHandler,setupUnhandledRejectionHandler,validateDnsResolutionOrder};
20
+ ${input}`}}const{validateNonInteractiveAuth}=await import("./validateNonInterActiveAuth-XJ2U5CLB.js");const nonInteractiveConfig=await validateNonInteractiveAuth(settings.merged.security?.auth?.useExternal,config,settings);const prompt_id=createNonInteractivePromptId(config.getSessionId(),config.getResumedSessionData?.()?.conversation.messages);if(inputFormat==="stream-json"){const trimmedInput=(input??"").trim();const{runNonInteractiveStreamJson}=await import("./session-CW5YMFMP.js");nonInteractiveHousekeeping?.startNonInteractiveOpenAILogHousekeeping(nonInteractiveConfig,settings);try{await runNonInteractiveStreamJson(nonInteractiveConfig,trimmedInput.length>0?trimmedInput:"",settings)}finally{await runExitCleanup()}process.exit(process.exitCode??0)}if(!input){writeStderrLine(`No input provided via stdin. Input can be provided by piping data into gemini or using the --prompt option.`);process.exit(1)}logUserPrompt(config,{"event.name":"user_prompt","event.timestamp":new Date().toISOString(),prompt:input,prompt_id,auth_type:config.getContentGeneratorConfig()?.authType,prompt_length:input.length});debugLogger6.debug(`Session ID: ${config.getSessionId()}`);const{runNonInteractive}=await import("./nonInteractiveCli-W7M2O43W.js");nonInteractiveHousekeeping?.startNonInteractiveOpenAILogHousekeeping(nonInteractiveConfig,settings);let exitCode;try{exitCode=await runNonInteractive(nonInteractiveConfig,settings,input,prompt_id)}finally{await runExitCleanup()}process.exit(exitCode)}}__name(main,"main");function createNonInteractivePromptId(sessionId,resumedRecords){const lastTurn=resumedRecords?.length?computeInitialTurnFromHistory(resumedRecords,sessionId):-1;return`${sessionId}########${lastTurn+1}`}__name(createNonInteractivePromptId,"createNonInteractivePromptId");function registerLspHotReload(config,registerCleanup2){const lspClient=config.getLspClient?.();const runtimeConfig=config;const reinitializeLsp=runtimeConfig.reinitializeLsp;if(config.isLspEnabled?.()!==true||!lspClient?.reinitialize||!reinitializeLsp){return}const lspConfigWatcher=new LspConfigWatcher(config.getProjectRoot());debugLogger6.info(`Registering LSP config hot reload watcher for ${config.getProjectRoot()}`);lspConfigWatcher.startWatching(async event=>{if(event.changeType==="invalid"){debugLogger6.warn(`Invalid LSP config file ${event.path}: ${event.error}`);appEvents.emit("log-error",event.error);return}debugLogger6.info(`Reloading LSP server settings: changeType=${event.changeType}, path=${event.path}`);let errorReported=false;try{const result=await reinitializeLsp();if(result){const failedServers=getRuntimeReloadFailedNames(result.reconcile);debugLogger6.info(`Reloaded LSP server settings: added=${formatRuntimeReloadNames(result.reconcile.added)}, removed=${formatRuntimeReloadNames(result.reconcile.removed)}, restarted=${formatRuntimeReloadNames(result.reconcile.restarted)}, unchanged=${formatRuntimeReloadNames(result.reconcile.unchanged)}, failed=${formatRuntimeReloadNames(failedServers)}, skipped=${formatRuntimeReloadNames(result.skipped.map(server=>server.name))}`);if(failedServers.length>0){appEvents.emit("lsp-status-changed");const changedServers=[...result.reconcile.added,...result.reconcile.removed,...result.reconcile.restarted];const message=`LSP reload partially completed: changed=${formatRuntimeReloadNames(changedServers)}, failed=${formatRuntimeReloadNames(failedServers)}. Run with --debug for details.`;appEvents.emit("log-error",message);errorReported=true;throw new Error(message)}}else{debugLogger6.info("Skipped LSP server settings reload because LSP is disabled or no client is available")}appEvents.emit("lsp-status-changed")}catch(error){debugLogger6.warn("Failed to reload LSP server settings:",error);if(!errorReported){const message=error instanceof Error?`Failed to reload LSP server settings: ${error.message}. Some LSP servers may have been partially updated. Run with --debug for details.`:"Failed to reload LSP server settings; some LSP servers may have been partially updated. Run with --debug for details.";appEvents.emit("log-error",message)}throw error}});registerCleanup2(()=>lspConfigWatcher.stopWatching())}__name(registerLspHotReload,"registerLspHotReload");function formatRuntimeReloadNames(names){return names.length===0?"<none>":names.join(",")}__name(formatRuntimeReloadNames,"formatRuntimeReloadNames");function getRuntimeReloadFailedNames(reconcile){return reconcile.failed??[]}__name(getRuntimeReloadFailedNames,"getRuntimeReloadFailedNames");export{createNonInteractivePromptId,main,registerLspHotReload,setupUncaughtExceptionHandler,setupUnhandledRejectionHandler,validateDnsResolutionOrder};
21
21
  /**
22
22
  * @license
23
23
  * Copyright 2025 Qwen
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{reportLlmChunk,reportLlmRequest,reportLlmResponse}from"./chunk-YTKRKP2I.js";import"./chunk-S6RXVOY6.js";import{isResponsesReasoningSignature}from"./chunk-HETUGUHE.js";import{buildSessionIdHeaders,expandDynamicHeaders,getEffectiveReasoning,hasDynamicPlaceholder,resolveReasoningForModel,warnIfDynamicHeadersDisabled}from"./chunk-ET2Z7ZGF.js";import{InstallationManager}from"./chunk-77V43YOE.js";import"./chunk-AFO5ER23.js";import"./chunk-GOR7FFVE.js";import"./chunk-4ZBZL23U.js";import"./chunk-BMHYEQTI.js";import"./chunk-ZZZAYAJW.js";import{GoogleGenAI}from"./chunk-QKX6AI4W.js";import"./chunk-GU22I6TY.js";import"./chunk-YEYW7PPR.js";import"./chunk-U6C6ONIN.js";import"./chunk-GLXNCFWC.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import"./chunk-I4H7NUVP.js";import"./chunk-EPODBRBP.js";import"./chunk-OKN3Z5C5.js";import"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();var debugLogger=createDebugLogger("GEMINI");function observeLlmStream(stream,telemetryAttempt){const iterator=stream[Symbol.asyncIterator]();return{async next(){const result=await iterator.next();if(!result.done)reportLlmChunk(telemetryAttempt,result.value);return result},async return(value){if(iterator.return)return iterator.return(value);return{done:true,value}},async throw(error){if(iterator.throw)return iterator.throw(error);await iterator.return?.();throw error},[Symbol.asyncIterator](){return this}}}__name(observeLlmStream,"observeLlmStream");var LlmContentGenerator=class{static{__name(this,"LlmContentGenerator")}googleGenAI;clientBaseUrl;contentGeneratorConfig;cliConfig;effortClampWarned=false;constructor(options,contentGeneratorConfig,cliConfig){const allCustomHeaders=contentGeneratorConfig?.customHeaders;if(cliConfig)warnIfDynamicHeadersDisabled(allCustomHeaders,cliConfig);const staticEntries=Object.entries(allCustomHeaders??{}).filter(([,value])=>typeof value!=="string"||!hasDynamicPlaceholder(value));const customHeaders=staticEntries.length>0?Object.fromEntries(staticEntries):void 0;const finalOptions=customHeaders?(()=>{const baseHttpOptions=options.httpOptions;const baseHeaders=baseHttpOptions?.headers??{};return{...options,httpOptions:{...baseHttpOptions??{},headers:{...baseHeaders,...customHeaders}}}})():options;this.googleGenAI=new GoogleGenAI(finalOptions);this.clientBaseUrl=finalOptions.httpOptions?.baseUrl;this.contentGeneratorConfig=contentGeneratorConfig;this.cliConfig=cliConfig}buildHttpOptions(httpOptions){if(!this.cliConfig)return httpOptions;const dynamicHeaders=expandDynamicHeaders(this.contentGeneratorConfig?.customHeaders,this.cliConfig);const destination=httpOptions?.baseUrl??this.clientBaseUrl;const sessionHeaders=destination?buildSessionIdHeaders(this.cliConfig,destination):{};if(Object.keys(sessionHeaders).length===0&&Object.keys(dynamicHeaders).length===0){return httpOptions}return{...httpOptions,headers:{...httpOptions?.headers,...dynamicHeaders,...sessionHeaders}}}buildGenerateContentConfig(request){const configSamplingParams=this.contentGeneratorConfig?.samplingParams;const requestConfig=request.config||{};const httpOptions=this.buildHttpOptions(requestConfig.httpOptions);const getParameterValue=__name((configValue,requestKey,defaultValue)=>{const requestValue=requestConfig[requestKey];if(configValue!==void 0)return configValue;if(requestValue!==void 0)return requestValue;return defaultValue},"getParameterValue");return{...requestConfig,...httpOptions?{httpOptions}:{},temperature:getParameterValue(configSamplingParams?.temperature,"temperature",1),topP:getParameterValue(configSamplingParams?.top_p,"topP",.95),topK:getParameterValue(configSamplingParams?.top_k,"topK",64),maxOutputTokens:configSamplingParams?.max_tokens!==void 0&&requestConfig.maxOutputTokens!==void 0?Math.min(configSamplingParams.max_tokens,requestConfig.maxOutputTokens):configSamplingParams?.max_tokens??requestConfig.maxOutputTokens,presencePenalty:getParameterValue(configSamplingParams?.presence_penalty,"presencePenalty"),frequencyPenalty:getParameterValue(configSamplingParams?.frequency_penalty,"frequencyPenalty"),thinkingConfig:getParameterValue(this.buildThinkingConfig(request.model,requestConfig.thinkingConfig),"thinkingConfig",{includeThoughts:true,thinkingLevel:"THINKING_LEVEL_UNSPECIFIED"})}}buildThinkingConfig(model,requestThinking){const generation=this.contentGeneratorConfig;const resolved=generation&&this.cliConfig?resolveReasoningForModel(this.cliConfig,generation,model):void 0;if(resolved&&requestThinking?.includeThoughts===false)return requestThinking;const reasoning=generation?getEffectiveReasoning(generation,resolved):void 0;if(reasoning===false){return{includeThoughts:false}}if(reasoning){let thinkingLevel;switch(reasoning.effort){case"low":thinkingLevel="LOW";break;case"medium":thinkingLevel="MEDIUM";break;case"high":thinkingLevel="HIGH";break;case"xhigh":case"max":if(!this.effortClampWarned){debugLogger.warn(`reasoning.effort='${reasoning.effort}' is not supported by Gemini; clamping to 'HIGH'.`);this.effortClampWarned=true}thinkingLevel="HIGH";break;case void 0:thinkingLevel="THINKING_LEVEL_UNSPECIFIED";break;default:{const _exhaustive=reasoning.effort;void _exhaustive;thinkingLevel="THINKING_LEVEL_UNSPECIFIED";break}}return{includeThoughts:true,thinkingLevel}}return void 0}async generateContent(request,_userPromptId){const finalRequest={...request,contents:this.stripUnsupportedFields(request.contents),config:this.buildGenerateContentConfig(request)};const telemetryAttempt=reportLlmRequest(finalRequest);const response=await this.googleGenAI.models.generateContent(finalRequest);reportLlmResponse(telemetryAttempt,response);return response}async generateContentStream(request,_userPromptId){const finalRequest={...request,contents:this.stripUnsupportedFields(request.contents),config:this.buildGenerateContentConfig(request)};const telemetryAttempt=reportLlmRequest(finalRequest);const stream=await this.googleGenAI.models.generateContentStream(finalRequest);return observeLlmStream(stream,telemetryAttempt)}stripUnsupportedFields(contents){if(!contents)return contents;if(typeof contents==="string")return contents;if(Array.isArray(contents)){return contents.map(content=>this.stripContentFields(content))}return this.stripContentFields(contents)}stripContentFields(content){if(typeof content==="string"){return content}if(!("role"in content)&&!("parts"in content)){return this.stripPartFields(content)}const contentObj=content;if(!contentObj.parts)return contentObj;return{...contentObj,parts:contentObj.parts.map(part=>this.stripPartFields(part))}}stripPartFields(part){if(typeof part==="string"){return part}const result={...part};delete result.partMetadata;if(result.inlineData){const{displayName:_,...inlineDataWithoutDisplayName}=result.inlineData;result.inlineData=inlineDataWithoutDisplayName}if(result.fileData){const{displayName:_,...fileDataWithoutDisplayName}=result.fileData;result.fileData=fileDataWithoutDisplayName}if(isResponsesReasoningSignature(result.thoughtSignature)){delete result.thoughtSignature}if(result.functionResponse?.parts){const processedParts=result.functionResponse.parts.map(p=>{const converted=this.convertUnsupportedMediaToText(p);return this.stripPartFields(converted)});result.functionResponse={...result.functionResponse,parts:processedParts}}return result}convertUnsupportedMediaToText(part){if(typeof part==="string")return part;const inlineMimeType=part.inlineData?.mimeType||"";const fileMimeType=part.fileData?.mimeType||"";if(inlineMimeType.startsWith("audio/")||inlineMimeType.startsWith("video/")){const displayName=part.inlineData?.displayName;const displayNameText=displayName?` (${displayName})`:"";return{text:`Unsupported media type for Gemini: ${inlineMimeType}${displayNameText}.`}}if(fileMimeType.startsWith("audio/")||fileMimeType.startsWith("video/")){const displayName=part.fileData?.displayName;const displayNameText=displayName?` (${displayName})`:"";return{text:`Unsupported media type for Gemini: ${fileMimeType}${displayNameText}.`}}return part}async embedContent(request){const httpOptions=this.buildHttpOptions(request.config?.httpOptions);return this.googleGenAI.models.embedContent({...request,...httpOptions?{config:{...request.config,httpOptions}}:{}})}};function createLlmContentGenerator(config,gcConfig){const version="0.26.6";const userAgent=config.userAgent||`QwenCode/${version} (${process.platform}; ${process.arch})`;const baseHeaders={"User-Agent":userAgent};let headers={...baseHeaders};if(gcConfig?.getUsageStatisticsEnabled()){const installationManager=new InstallationManager;const installationId=installationManager.getInstallationId();headers={...headers,"x-gemini-api-privileged-user-id":`${installationId}`}}const httpOptions=config.baseUrl?{headers,baseUrl:config.baseUrl}:{headers};const llmContentGenerator=new LlmContentGenerator({apiKey:config.apiKey===""?void 0:config.apiKey,vertexai:config.vertexai??(config.authType==="vertex-ai"?true:void 0),httpOptions},config,gcConfig);return llmContentGenerator}__name(createLlmContentGenerator,"createLlmContentGenerator");export{LlmContentGenerator,createLlmContentGenerator};
3
+ import{reportLlmChunk,reportLlmRequest,reportLlmResponse}from"./chunk-YTKRKP2I.js";import"./chunk-S6RXVOY6.js";import{isResponsesReasoningSignature}from"./chunk-HETUGUHE.js";import{buildSessionIdHeaders,expandDynamicHeaders,getEffectiveReasoning,hasDynamicPlaceholder,resolveReasoningForModel,warnIfDynamicHeadersDisabled}from"./chunk-ET2Z7ZGF.js";import{InstallationManager}from"./chunk-77V43YOE.js";import"./chunk-HQZTAA2U.js";import"./chunk-GOR7FFVE.js";import"./chunk-4ZBZL23U.js";import"./chunk-BMHYEQTI.js";import"./chunk-ZZZAYAJW.js";import{GoogleGenAI}from"./chunk-QKX6AI4W.js";import"./chunk-GU22I6TY.js";import"./chunk-YEYW7PPR.js";import"./chunk-U6C6ONIN.js";import"./chunk-GLXNCFWC.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import"./chunk-I4H7NUVP.js";import"./chunk-EPODBRBP.js";import"./chunk-OKN3Z5C5.js";import"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();var debugLogger=createDebugLogger("GEMINI");function observeLlmStream(stream,telemetryAttempt){const iterator=stream[Symbol.asyncIterator]();return{async next(){const result=await iterator.next();if(!result.done)reportLlmChunk(telemetryAttempt,result.value);return result},async return(value){if(iterator.return)return iterator.return(value);return{done:true,value}},async throw(error){if(iterator.throw)return iterator.throw(error);await iterator.return?.();throw error},[Symbol.asyncIterator](){return this}}}__name(observeLlmStream,"observeLlmStream");var LlmContentGenerator=class{static{__name(this,"LlmContentGenerator")}googleGenAI;clientBaseUrl;contentGeneratorConfig;cliConfig;effortClampWarned=false;constructor(options,contentGeneratorConfig,cliConfig){const allCustomHeaders=contentGeneratorConfig?.customHeaders;if(cliConfig)warnIfDynamicHeadersDisabled(allCustomHeaders,cliConfig);const staticEntries=Object.entries(allCustomHeaders??{}).filter(([,value])=>typeof value!=="string"||!hasDynamicPlaceholder(value));const customHeaders=staticEntries.length>0?Object.fromEntries(staticEntries):void 0;const finalOptions=customHeaders?(()=>{const baseHttpOptions=options.httpOptions;const baseHeaders=baseHttpOptions?.headers??{};return{...options,httpOptions:{...baseHttpOptions??{},headers:{...baseHeaders,...customHeaders}}}})():options;this.googleGenAI=new GoogleGenAI(finalOptions);this.clientBaseUrl=finalOptions.httpOptions?.baseUrl;this.contentGeneratorConfig=contentGeneratorConfig;this.cliConfig=cliConfig}buildHttpOptions(httpOptions){if(!this.cliConfig)return httpOptions;const dynamicHeaders=expandDynamicHeaders(this.contentGeneratorConfig?.customHeaders,this.cliConfig);const destination=httpOptions?.baseUrl??this.clientBaseUrl;const sessionHeaders=destination?buildSessionIdHeaders(this.cliConfig,destination):{};if(Object.keys(sessionHeaders).length===0&&Object.keys(dynamicHeaders).length===0){return httpOptions}return{...httpOptions,headers:{...httpOptions?.headers,...dynamicHeaders,...sessionHeaders}}}buildGenerateContentConfig(request){const configSamplingParams=this.contentGeneratorConfig?.samplingParams;const requestConfig=request.config||{};const httpOptions=this.buildHttpOptions(requestConfig.httpOptions);const getParameterValue=__name((configValue,requestKey,defaultValue)=>{const requestValue=requestConfig[requestKey];if(configValue!==void 0)return configValue;if(requestValue!==void 0)return requestValue;return defaultValue},"getParameterValue");return{...requestConfig,...httpOptions?{httpOptions}:{},temperature:getParameterValue(configSamplingParams?.temperature,"temperature",1),topP:getParameterValue(configSamplingParams?.top_p,"topP",.95),topK:getParameterValue(configSamplingParams?.top_k,"topK",64),maxOutputTokens:configSamplingParams?.max_tokens!==void 0&&requestConfig.maxOutputTokens!==void 0?Math.min(configSamplingParams.max_tokens,requestConfig.maxOutputTokens):configSamplingParams?.max_tokens??requestConfig.maxOutputTokens,presencePenalty:getParameterValue(configSamplingParams?.presence_penalty,"presencePenalty"),frequencyPenalty:getParameterValue(configSamplingParams?.frequency_penalty,"frequencyPenalty"),thinkingConfig:getParameterValue(this.buildThinkingConfig(request.model,requestConfig.thinkingConfig),"thinkingConfig",{includeThoughts:true,thinkingLevel:"THINKING_LEVEL_UNSPECIFIED"})}}buildThinkingConfig(model,requestThinking){const generation=this.contentGeneratorConfig;const resolved=generation&&this.cliConfig?resolveReasoningForModel(this.cliConfig,generation,model):void 0;if(resolved&&requestThinking?.includeThoughts===false)return requestThinking;const reasoning=generation?getEffectiveReasoning(generation,resolved):void 0;if(reasoning===false){return{includeThoughts:false}}if(reasoning){let thinkingLevel;switch(reasoning.effort){case"low":thinkingLevel="LOW";break;case"medium":thinkingLevel="MEDIUM";break;case"high":thinkingLevel="HIGH";break;case"xhigh":case"max":if(!this.effortClampWarned){debugLogger.warn(`reasoning.effort='${reasoning.effort}' is not supported by Gemini; clamping to 'HIGH'.`);this.effortClampWarned=true}thinkingLevel="HIGH";break;case void 0:thinkingLevel="THINKING_LEVEL_UNSPECIFIED";break;default:{const _exhaustive=reasoning.effort;void _exhaustive;thinkingLevel="THINKING_LEVEL_UNSPECIFIED";break}}return{includeThoughts:true,thinkingLevel}}return void 0}async generateContent(request,_userPromptId){const finalRequest={...request,contents:this.stripUnsupportedFields(request.contents),config:this.buildGenerateContentConfig(request)};const telemetryAttempt=reportLlmRequest(finalRequest);const response=await this.googleGenAI.models.generateContent(finalRequest);reportLlmResponse(telemetryAttempt,response);return response}async generateContentStream(request,_userPromptId){const finalRequest={...request,contents:this.stripUnsupportedFields(request.contents),config:this.buildGenerateContentConfig(request)};const telemetryAttempt=reportLlmRequest(finalRequest);const stream=await this.googleGenAI.models.generateContentStream(finalRequest);return observeLlmStream(stream,telemetryAttempt)}stripUnsupportedFields(contents){if(!contents)return contents;if(typeof contents==="string")return contents;if(Array.isArray(contents)){return contents.map(content=>this.stripContentFields(content))}return this.stripContentFields(contents)}stripContentFields(content){if(typeof content==="string"){return content}if(!("role"in content)&&!("parts"in content)){return this.stripPartFields(content)}const contentObj=content;if(!contentObj.parts)return contentObj;return{...contentObj,parts:contentObj.parts.map(part=>this.stripPartFields(part))}}stripPartFields(part){if(typeof part==="string"){return part}const result={...part};delete result.partMetadata;if(result.inlineData){const{displayName:_,...inlineDataWithoutDisplayName}=result.inlineData;result.inlineData=inlineDataWithoutDisplayName}if(result.fileData){const{displayName:_,...fileDataWithoutDisplayName}=result.fileData;result.fileData=fileDataWithoutDisplayName}if(isResponsesReasoningSignature(result.thoughtSignature)){delete result.thoughtSignature}if(result.functionResponse?.parts){const processedParts=result.functionResponse.parts.map(p=>{const converted=this.convertUnsupportedMediaToText(p);return this.stripPartFields(converted)});result.functionResponse={...result.functionResponse,parts:processedParts}}return result}convertUnsupportedMediaToText(part){if(typeof part==="string")return part;const inlineMimeType=part.inlineData?.mimeType||"";const fileMimeType=part.fileData?.mimeType||"";if(inlineMimeType.startsWith("audio/")||inlineMimeType.startsWith("video/")){const displayName=part.inlineData?.displayName;const displayNameText=displayName?` (${displayName})`:"";return{text:`Unsupported media type for Gemini: ${inlineMimeType}${displayNameText}.`}}if(fileMimeType.startsWith("audio/")||fileMimeType.startsWith("video/")){const displayName=part.fileData?.displayName;const displayNameText=displayName?` (${displayName})`:"";return{text:`Unsupported media type for Gemini: ${fileMimeType}${displayNameText}.`}}return part}async embedContent(request){const httpOptions=this.buildHttpOptions(request.config?.httpOptions);return this.googleGenAI.models.embedContent({...request,...httpOptions?{config:{...request.config,httpOptions}}:{}})}};function createLlmContentGenerator(config,gcConfig){const version="0.26.8";const userAgent=config.userAgent||`QwenCode/${version} (${process.platform}; ${process.arch})`;const baseHeaders={"User-Agent":userAgent};let headers={...baseHeaders};if(gcConfig?.getUsageStatisticsEnabled()){const installationManager=new InstallationManager;const installationId=installationManager.getInstallationId();headers={...headers,"x-gemini-api-privileged-user-id":`${installationId}`}}const httpOptions=config.baseUrl?{headers,baseUrl:config.baseUrl}:{headers};const llmContentGenerator=new LlmContentGenerator({apiKey:config.apiKey===""?void 0:config.apiKey,vertexai:config.vertexai??(config.authType==="vertex-ai"?true:void 0),httpOptions},config,gcConfig);return llmContentGenerator}__name(createLlmContentGenerator,"createLlmContentGenerator");export{LlmContentGenerator,createLlmContentGenerator};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Google LLC
@@ -1,3 +1,3 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{createLoadedSettingsAdapter,findRawModelProviderEntries,getRawModelProviders}from"./chunk-G6DALGGS.js";import"./chunk-2TAJ5STJ.js";import"./chunk-UWCF7JIF.js";import"./chunk-NONBHCXP.js";import"./chunk-LMUSSYJH.js";import"./chunk-NO7VTKRL.js";import"./chunk-U7HZUZKP.js";import"./chunk-MPVQDYPH.js";import"./chunk-PKK2D2W4.js";import"./chunk-N3AQAZ7D.js";import"./chunk-E5T4R2PM.js";import"./chunk-DOLUT3XC.js";import"./chunk-PTHIQ7ZN.js";import"./chunk-MTDBCIDA.js";import"./chunk-EIPLDYEY.js";import"./chunk-IDXJIDME.js";import"./chunk-OU7CEG7Q.js";import"./chunk-QS2ZMQIS.js";import"./chunk-S7IKHQ6I.js";import"./chunk-PAD5GPDY.js";import"./chunk-MD3ZEOBX.js";import"./chunk-SSYS5YN5.js";import"./chunk-X5QSFJVS.js";import"./chunk-OMDTFGTX.js";import"./chunk-32XHDDIA.js";import"./chunk-46VUDNCL.js";import"./chunk-MKH3EH7O.js";import"./chunk-FKZ46GKL.js";import"./chunk-SP6CQ3MO.js";import"./chunk-HW6SU6MX.js";import"./chunk-ZHHFNZ5J.js";import"./chunk-AKWYMQKU.js";import"./chunk-MZUOREFD.js";import"./chunk-CF6SZJNP.js";import"./chunk-7XZVMIY5.js";import"./chunk-CGDFZEER.js";import"./chunk-ZZJXFLVM.js";import"./chunk-RKDS7A4H.js";import"./chunk-KZNYALFU.js";import"./chunk-IV3HAIUN.js";import"./chunk-XFMPZINJ.js";import"./chunk-DECUAM3U.js";import"./chunk-QX7W2HY7.js";import"./chunk-HN5UYLPU.js";import"./chunk-PGRN3GZY.js";import"./chunk-HTW7PYHK.js";import"./chunk-AMGUAA4G.js";import"./chunk-YFTVFH2A.js";import"./chunk-ZBHL2CXR.js";import"./chunk-NIOS3B3V.js";import"./chunk-2JGTWRZJ.js";import"./chunk-R2EHHA2C.js";import"./chunk-YK7NDQKM.js";import"./chunk-ZLZF2ZDD.js";import"./chunk-OMSVOFTC.js";import"./chunk-PHIPLV2I.js";import"./chunk-ZOTKZI2P.js";import"./chunk-A6G5TAIF.js";import"./chunk-YVBHCSZD.js";import"./chunk-FIXDX63I.js";import"./chunk-T7CHK6C2.js";import"./chunk-PT7NZBDY.js";import"./chunk-TWP72VRH.js";import"./chunk-UYEWRLGD.js";import"./chunk-QVPT37XZ.js";import"./chunk-YVD4O5ZB.js";import"./chunk-T6W33SET.js";import"./chunk-WK2IBT6D.js";import"./chunk-QZV4PFQK.js";import"./chunk-ILECDNJX.js";import"./chunk-QXQGUM3Y.js";import"./chunk-UQ7IROJH.js";import"./chunk-SZCBUCNH.js";import"./chunk-BEKROCWN.js";import"./chunk-5SUFJTQQ.js";import"./chunk-BYU42MLK.js";import"./chunk-JWQXU3SR.js";import"./chunk-5LZ2DPLH.js";import"./chunk-XQJOZDV7.js";import"./chunk-CV2UAEZA.js";import"./chunk-FUBDS3AV.js";import"./chunk-HW6AWS7W.js";import"./chunk-KLC3OD2M.js";import"./chunk-Q5IZXKUJ.js";import"./chunk-G5PYYZMM.js";import"./chunk-BG67XABA.js";import"./chunk-OBOU4ZZM.js";import"./chunk-D7XCQWP2.js";import"./chunk-AE5OMKRY.js";import"./chunk-OBV7RNHV.js";import"./chunk-7CQMWEMY.js";import"./chunk-GOZYWU4B.js";import"./chunk-OUC3WICA.js";import"./chunk-JZK2WGXA.js";import"./chunk-MPHSE7M4.js";import"./chunk-S2ZKZXHX.js";import"./chunk-7UK4WJWS.js";import"./chunk-4GP3PH7Z.js";import"./chunk-4QQKOW5M.js";import"./chunk-OV3EBH6J.js";import"./chunk-EBMCWXGZ.js";import"./chunk-XZTE4YTN.js";import"./chunk-LSASUDF2.js";import"./chunk-2V5EKGDK.js";import"./chunk-MOKVM4PT.js";import"./chunk-YIW3H46P.js";import"./chunk-EOMRLUNZ.js";import"./chunk-4ZRCV3JY.js";import"./chunk-TL6MLBXR.js";import"./chunk-NMY3PYNO.js";import"./chunk-YGLM5XPP.js";import"./chunk-WGNF7FPC.js";import"./chunk-4NPYOXJO.js";import"./chunk-MWGB5RCF.js";import"./chunk-SCD5TUBG.js";import"./chunk-NTRFETZB.js";import"./chunk-TL3SF2GA.js";import"./chunk-LMJPU2JM.js";import"./chunk-VFB6Q74I.js";import"./chunk-4JNHUZ7M.js";import"./chunk-SW54YEPK.js";import"./chunk-ZCRL73DT.js";import"./chunk-A6LT3FIJ.js";import"./chunk-S6RXVOY6.js";import"./chunk-YZFNBUKG.js";import"./chunk-AGEDDL7Z.js";import"./chunk-2NJJHZ52.js";import"./chunk-BN4FIQ77.js";import"./chunk-X64RXJQQ.js";import"./chunk-HETUGUHE.js";import"./chunk-ET2Z7ZGF.js";import"./chunk-XFPYXD2P.js";import"./chunk-3YWXKSOI.js";import"./chunk-5CWTKFI4.js";import"./chunk-C4MVD5OI.js";import"./chunk-Z2W7S4O4.js";import"./chunk-476F6QIM.js";import"./chunk-4R67LXKL.js";import"./chunk-FQRF6B65.js";import"./chunk-ZWPSBU7K.js";import"./chunk-UQFTXKEB.js";import"./chunk-HDGTWJ24.js";import"./chunk-W5NWIGKO.js";import"./chunk-KVA6DHHF.js";import"./chunk-PWOQASXT.js";import"./chunk-K7JCVESI.js";import"./chunk-Y6HHV4LC.js";import"./chunk-RP57XAJ2.js";import"./chunk-Z6AR5XE5.js";import"./chunk-7DOOXUDG.js";import"./chunk-77V43YOE.js";import"./chunk-7U7CWMP7.js";import"./chunk-EFTJIDS3.js";import"./chunk-4DIWAQ5G.js";import"./chunk-Q6UAOTP3.js";import"./chunk-AFO5ER23.js";import"./chunk-GOR7FFVE.js";import"./chunk-4ZBZL23U.js";import"./chunk-BMHYEQTI.js";import"./chunk-ZZZAYAJW.js";import"./chunk-XMANRGPK.js";import"./chunk-3XVPZY7X.js";import"./chunk-KQX4H2D3.js";import"./chunk-URNNJMIC.js";import"./chunk-GU22I6TY.js";import"./chunk-YEYW7PPR.js";import"./chunk-M4ECEHLX.js";import"./chunk-DBRQGEEI.js";import"./chunk-B3ZFUGTC.js";import"./chunk-IRINPFG7.js";import"./chunk-6GTPLW7K.js";import"./chunk-NGVRCUYD.js";import"./chunk-5DTFN37U.js";import"./chunk-2YUBAWQ6.js";import"./chunk-O5EKX7LG.js";import"./chunk-TM6ZCBR7.js";import"./chunk-SVAPAMMG.js";import"./chunk-3KUHQGOS.js";import"./chunk-I6S7NGX3.js";import"./chunk-SBZFGYYS.js";import"./chunk-JAUJI56S.js";import"./chunk-I4H7NUVP.js";import"./chunk-EPODBRBP.js";import"./chunk-OKN3Z5C5.js";import"./chunk-XYB7GC5U.js";import"./chunk-2UOMCYQG.js";import"./chunk-I7L2TX4M.js";import"./chunk-MK3OONRA.js";import"./chunk-COGTQ5KZ.js";import"./chunk-VKDAXTCZ.js";import"./chunk-KBWJGX7I.js";export{createLoadedSettingsAdapter,findRawModelProviderEntries,getRawModelProviders};
3
+ import{createLoadedSettingsAdapter,findRawModelProviderEntries,getRawModelProviders}from"./chunk-BBDFEMCF.js";import"./chunk-EZPM4DLR.js";import"./chunk-UWCF7JIF.js";import"./chunk-UB37RBSK.js";import"./chunk-LMUSSYJH.js";import"./chunk-NO7VTKRL.js";import"./chunk-U7HZUZKP.js";import"./chunk-ZO4F6ZWR.js";import"./chunk-PKK2D2W4.js";import"./chunk-N3AQAZ7D.js";import"./chunk-E5T4R2PM.js";import"./chunk-DOLUT3XC.js";import"./chunk-PTHIQ7ZN.js";import"./chunk-4CE4GMDL.js";import"./chunk-EIPLDYEY.js";import"./chunk-IDXJIDME.js";import"./chunk-G2LTZU67.js";import"./chunk-QS2ZMQIS.js";import"./chunk-S7IKHQ6I.js";import"./chunk-PAD5GPDY.js";import"./chunk-MD3ZEOBX.js";import"./chunk-SSYS5YN5.js";import"./chunk-X5QSFJVS.js";import"./chunk-OMDTFGTX.js";import"./chunk-3TTHYXT3.js";import"./chunk-46VUDNCL.js";import"./chunk-MKH3EH7O.js";import"./chunk-VC3JJL7E.js";import"./chunk-VKWVIWLK.js";import"./chunk-HW6SU6MX.js";import"./chunk-ZHHFNZ5J.js";import"./chunk-AKWYMQKU.js";import"./chunk-MZUOREFD.js";import"./chunk-DSKA3P2C.js";import"./chunk-7XZVMIY5.js";import"./chunk-4HSISRRA.js";import"./chunk-ZZJXFLVM.js";import"./chunk-RKDS7A4H.js";import"./chunk-QF22ILPV.js";import"./chunk-IV3HAIUN.js";import"./chunk-XFMPZINJ.js";import"./chunk-DECUAM3U.js";import"./chunk-QX7W2HY7.js";import"./chunk-HN5UYLPU.js";import"./chunk-PGRN3GZY.js";import"./chunk-HTW7PYHK.js";import"./chunk-AMGUAA4G.js";import"./chunk-YFTVFH2A.js";import"./chunk-ZBHL2CXR.js";import"./chunk-NIOS3B3V.js";import"./chunk-7XQ5D34E.js";import"./chunk-R2EHHA2C.js";import"./chunk-YK7NDQKM.js";import"./chunk-ZLZF2ZDD.js";import"./chunk-OMSVOFTC.js";import"./chunk-PHIPLV2I.js";import"./chunk-ZOTKZI2P.js";import"./chunk-A6G5TAIF.js";import"./chunk-YVBHCSZD.js";import"./chunk-FIXDX63I.js";import"./chunk-T7CHK6C2.js";import"./chunk-PT7NZBDY.js";import"./chunk-TWP72VRH.js";import"./chunk-UYEWRLGD.js";import"./chunk-QVPT37XZ.js";import"./chunk-YVD4O5ZB.js";import"./chunk-T6W33SET.js";import"./chunk-WK2IBT6D.js";import"./chunk-QZV4PFQK.js";import"./chunk-ILECDNJX.js";import"./chunk-QXQGUM3Y.js";import"./chunk-UQ7IROJH.js";import"./chunk-SZCBUCNH.js";import"./chunk-BEKROCWN.js";import"./chunk-5SUFJTQQ.js";import"./chunk-BYU42MLK.js";import"./chunk-JWQXU3SR.js";import"./chunk-5LZ2DPLH.js";import"./chunk-XQJOZDV7.js";import"./chunk-CV2UAEZA.js";import"./chunk-FUBDS3AV.js";import"./chunk-HW6AWS7W.js";import"./chunk-KLC3OD2M.js";import"./chunk-Q5IZXKUJ.js";import"./chunk-G5PYYZMM.js";import"./chunk-BG67XABA.js";import"./chunk-OBOU4ZZM.js";import"./chunk-D7XCQWP2.js";import"./chunk-AE5OMKRY.js";import"./chunk-OBV7RNHV.js";import"./chunk-7CQMWEMY.js";import"./chunk-GOZYWU4B.js";import"./chunk-OUC3WICA.js";import"./chunk-JZK2WGXA.js";import"./chunk-MPHSE7M4.js";import"./chunk-S2ZKZXHX.js";import"./chunk-7UK4WJWS.js";import"./chunk-4GP3PH7Z.js";import"./chunk-4QQKOW5M.js";import"./chunk-OV3EBH6J.js";import"./chunk-EBMCWXGZ.js";import"./chunk-XZTE4YTN.js";import"./chunk-LSASUDF2.js";import"./chunk-2V5EKGDK.js";import"./chunk-MOKVM4PT.js";import"./chunk-YIW3H46P.js";import"./chunk-EOMRLUNZ.js";import"./chunk-4ZRCV3JY.js";import"./chunk-TL6MLBXR.js";import"./chunk-NMY3PYNO.js";import"./chunk-YGLM5XPP.js";import"./chunk-WGNF7FPC.js";import"./chunk-4NPYOXJO.js";import"./chunk-MWGB5RCF.js";import"./chunk-SCD5TUBG.js";import"./chunk-NTRFETZB.js";import"./chunk-TL3SF2GA.js";import"./chunk-LMJPU2JM.js";import"./chunk-VFB6Q74I.js";import"./chunk-4JNHUZ7M.js";import"./chunk-SW54YEPK.js";import"./chunk-ZCRL73DT.js";import"./chunk-A6LT3FIJ.js";import"./chunk-S6RXVOY6.js";import"./chunk-YZFNBUKG.js";import"./chunk-AGEDDL7Z.js";import"./chunk-2NJJHZ52.js";import"./chunk-BN4FIQ77.js";import"./chunk-X64RXJQQ.js";import"./chunk-HETUGUHE.js";import"./chunk-ET2Z7ZGF.js";import"./chunk-XFPYXD2P.js";import"./chunk-3YWXKSOI.js";import"./chunk-5CWTKFI4.js";import"./chunk-C4MVD5OI.js";import"./chunk-Z2W7S4O4.js";import"./chunk-476F6QIM.js";import"./chunk-4R67LXKL.js";import"./chunk-FQRF6B65.js";import"./chunk-ZWPSBU7K.js";import"./chunk-UQFTXKEB.js";import"./chunk-HDGTWJ24.js";import"./chunk-W5NWIGKO.js";import"./chunk-KVA6DHHF.js";import"./chunk-PWOQASXT.js";import"./chunk-K7JCVESI.js";import"./chunk-Y6HHV4LC.js";import"./chunk-RP57XAJ2.js";import"./chunk-Z6AR5XE5.js";import"./chunk-7DOOXUDG.js";import"./chunk-77V43YOE.js";import"./chunk-7U7CWMP7.js";import"./chunk-EFTJIDS3.js";import"./chunk-4DIWAQ5G.js";import"./chunk-Q6UAOTP3.js";import"./chunk-HQZTAA2U.js";import"./chunk-GOR7FFVE.js";import"./chunk-4ZBZL23U.js";import"./chunk-BMHYEQTI.js";import"./chunk-ZZZAYAJW.js";import"./chunk-XMANRGPK.js";import"./chunk-3XVPZY7X.js";import"./chunk-KQX4H2D3.js";import"./chunk-URNNJMIC.js";import"./chunk-GU22I6TY.js";import"./chunk-YEYW7PPR.js";import"./chunk-M4ECEHLX.js";import"./chunk-DBRQGEEI.js";import"./chunk-B3ZFUGTC.js";import"./chunk-IRINPFG7.js";import"./chunk-6GTPLW7K.js";import"./chunk-NGVRCUYD.js";import"./chunk-5DTFN37U.js";import"./chunk-2YUBAWQ6.js";import"./chunk-O5EKX7LG.js";import"./chunk-TM6ZCBR7.js";import"./chunk-SVAPAMMG.js";import"./chunk-3KUHQGOS.js";import"./chunk-I6S7NGX3.js";import"./chunk-SBZFGYYS.js";import"./chunk-JAUJI56S.js";import"./chunk-I4H7NUVP.js";import"./chunk-EPODBRBP.js";import"./chunk-OKN3Z5C5.js";import"./chunk-XYB7GC5U.js";import"./chunk-2UOMCYQG.js";import"./chunk-I7L2TX4M.js";import"./chunk-MK3OONRA.js";import"./chunk-COGTQ5KZ.js";import"./chunk-VKDAXTCZ.js";import"./chunk-KBWJGX7I.js";export{createLoadedSettingsAdapter,findRawModelProviderEntries,getRawModelProviders};