@qwen-code/qwen-code 0.27.2-preview.0 → 0.27.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (302) hide show
  1. package/chunks/{MaxSizedBox-XGJBXFET.js → MaxSizedBox-QRQEXRXW.js} +1 -1
  2. package/chunks/{StandaloneSessionPicker-BNFJWFLQ.js → StandaloneSessionPicker-X274Q6BX.js} +1 -1
  3. package/chunks/{acp-subagent-executor-P5FBYPD5.js → acp-subagent-executor-YIFQD4LJ.js} +1 -1
  4. package/chunks/{acpAgent-J6G57ZCE.js → acpAgent-NW4XNW7P.js} +3 -3
  5. package/chunks/{advisor-3O63GFOM.js → advisor-W7KCVPBR.js} +1 -1
  6. package/chunks/{agent-ALZEISY2.js → agent-FGDWPNXW.js} +1 -1
  7. package/chunks/{agent-headless-XAKKB6OT.js → agent-headless-7KA3VVAB.js} +1 -1
  8. package/chunks/{agent-host-client-DIV2XAL5.js → agent-host-client-YZJLSOLB.js} +1 -1
  9. package/chunks/{agent-host-connections-ZQUMCO2F.js → agent-host-connections-5JGDPG3L.js} +1 -1
  10. package/chunks/{anthropicContentGenerator-ZE7TAQPO.js → anthropicContentGenerator-QUXJVJ3I.js} +1 -1
  11. package/chunks/{autofix-pr-RZ4PWQ46.js → autofix-pr-UDRPJC7L.js} +1 -1
  12. package/chunks/{batch-AIMBHUMX.js → batch-GCEHGR5P.js} +1 -1
  13. package/chunks/{bridge-A3RRGPEI.js → bridge-JY2JXNVV.js} +1 -1
  14. package/chunks/{channel-settings-store-P3KM5GTN.js → channel-settings-store-EX6ZU6R3.js} +1 -1
  15. package/chunks/{chunk-P22U5UQR.js → chunk-27MJJU2I.js} +1 -1
  16. package/chunks/{chunk-RYRMDOIX.js → chunk-2LDABIAY.js} +3 -3
  17. package/chunks/{chunk-MYPEVUKI.js → chunk-2QZDPMIH.js} +1 -1
  18. package/chunks/{chunk-TW2REHPX.js → chunk-2SGTJMSU.js} +1 -1
  19. package/chunks/{chunk-NCW3NPS5.js → chunk-3BHXPXCC.js} +1 -1
  20. package/chunks/{chunk-XUB4JKSR.js → chunk-3NR3JBMA.js} +6 -6
  21. package/chunks/{chunk-NRJOUWP4.js → chunk-3QCFMVI6.js} +1 -1
  22. package/chunks/{chunk-EGMV4S6D.js → chunk-3YOERSU5.js} +1 -1
  23. package/chunks/{chunk-WXKD4L4A.js → chunk-4NIUXYUF.js} +1 -1
  24. package/chunks/{chunk-YHC27L5W.js → chunk-5FS5OQHO.js} +1 -1
  25. package/chunks/{chunk-L76RFQKW.js → chunk-5MGG2BGT.js} +1 -1
  26. package/chunks/{chunk-HHDQ5JAA.js → chunk-66LFVQJP.js} +1 -1
  27. package/chunks/{chunk-RJPELYUW.js → chunk-6KU7LHBT.js} +1 -1
  28. package/chunks/{chunk-SKU5J7Q7.js → chunk-6O7CARPF.js} +1 -1
  29. package/chunks/{chunk-CPOFE42B.js → chunk-6Z3TBTUS.js} +1 -1
  30. package/chunks/{chunk-HRRQHZQE.js → chunk-73TSS7KS.js} +1 -1
  31. package/chunks/{chunk-BSGONILH.js → chunk-776L3HAN.js} +1 -1
  32. package/chunks/{chunk-MZNZYCAC.js → chunk-7BL2OTHX.js} +1 -1
  33. package/chunks/{chunk-5DPLJQUC.js → chunk-7GYFDPEP.js} +1 -1
  34. package/chunks/{chunk-OD44AOSX.js → chunk-7KGCNYE4.js} +1 -1
  35. package/chunks/{chunk-4JLLFT6S.js → chunk-7SX547WS.js} +1 -1
  36. package/chunks/{chunk-5Q6POUDM.js → chunk-7VIES3RW.js} +1 -1
  37. package/chunks/{chunk-NMK72ZA4.js → chunk-ABEBQNYK.js} +1 -1
  38. package/chunks/{chunk-QZ5JBF3E.js → chunk-AD7JBW6R.js} +2 -2
  39. package/chunks/{chunk-E6XRNALG.js → chunk-AEX3XSTE.js} +1 -1
  40. package/chunks/{chunk-B7CYUTAO.js → chunk-AKDODQCI.js} +1 -1
  41. package/chunks/{chunk-EEARSY3D.js → chunk-B3I5LFFK.js} +1 -1
  42. package/chunks/{chunk-YSGVX6LT.js → chunk-B5Y56PDI.js} +1 -1
  43. package/chunks/{chunk-MEFN5DY3.js → chunk-BEBKKJP3.js} +1 -1
  44. package/chunks/{chunk-GYCGVZ32.js → chunk-BFPP7X4E.js} +1 -1
  45. package/chunks/{chunk-GNWPYWGQ.js → chunk-BY5GX6DQ.js} +1 -1
  46. package/chunks/{chunk-6W5ZZSQF.js → chunk-CUX3C6QV.js} +1 -1
  47. package/chunks/{chunk-HXYHIEMH.js → chunk-CXPRHT3E.js} +1 -1
  48. package/chunks/{chunk-53CWA7N2.js → chunk-D5H5GARR.js} +1 -1
  49. package/chunks/{chunk-DV67DRNT.js → chunk-DLY7QJ5Y.js} +1 -1
  50. package/chunks/{chunk-SFDOJ2FF.js → chunk-DN4QKOFL.js} +1 -1
  51. package/chunks/{chunk-VOAIDOUV.js → chunk-DP4YE24V.js} +1 -1
  52. package/chunks/{chunk-D2X6A5FH.js → chunk-DQLI7HH7.js} +1 -1
  53. package/chunks/{chunk-ET7ADS4X.js → chunk-DS2FKATN.js} +1 -1
  54. package/chunks/{chunk-FRSSRLIO.js → chunk-E6EW43WZ.js} +1 -1
  55. package/chunks/{chunk-F4AWT5LV.js → chunk-EEBFFC76.js} +1 -1
  56. package/chunks/{chunk-B7PJ5TNK.js → chunk-EGKUF5NS.js} +2 -2
  57. package/chunks/{chunk-B2YLVSQE.js → chunk-ERMAKXS3.js} +2 -2
  58. package/chunks/{chunk-PEZZTKPM.js → chunk-FB73O3E5.js} +1 -1
  59. package/chunks/{chunk-36DBNBTF.js → chunk-FEIUMWFA.js} +1 -1
  60. package/chunks/{chunk-YE3LA3U4.js → chunk-FWJKQA2H.js} +1 -1
  61. package/chunks/{chunk-VDNPMX5W.js → chunk-FZQJOSHD.js} +1 -1
  62. package/chunks/{chunk-YYSMMFK7.js → chunk-GNI5J2ON.js} +1 -1
  63. package/chunks/{chunk-6OCKLRQC.js → chunk-H3VGRICV.js} +1 -1
  64. package/chunks/{chunk-OSLFWRV2.js → chunk-HRTWLOGK.js} +1 -1
  65. package/chunks/{chunk-XZYQKCTU.js → chunk-IGIZ6AZE.js} +1 -1
  66. package/chunks/{chunk-RIBVEHUG.js → chunk-IHB7CDQ2.js} +1 -1
  67. package/chunks/{chunk-LO6OFMFC.js → chunk-IHEGGZBE.js} +1 -1
  68. package/chunks/{chunk-N5S6SIRO.js → chunk-IMTHBYJP.js} +1 -1
  69. package/chunks/{chunk-I5F24CVP.js → chunk-IP3K5SRR.js} +1 -1
  70. package/chunks/{chunk-2FYWJVGW.js → chunk-ISA4MFNT.js} +1 -1
  71. package/chunks/{chunk-GV3E2RHX.js → chunk-JGF3ND5D.js} +1 -1
  72. package/chunks/{chunk-ASQ7BSJ4.js → chunk-JJ4UPR4A.js} +1 -1
  73. package/chunks/{chunk-HOCNE2LO.js → chunk-JTUWFGEB.js} +1 -1
  74. package/chunks/{chunk-FDQFJFO5.js → chunk-KAN5KUJD.js} +1 -1
  75. package/chunks/{chunk-K7GCWWTI.js → chunk-KU4F6SSJ.js} +2 -2
  76. package/chunks/{chunk-QDQQFQB4.js → chunk-LBAINHIN.js} +1 -1
  77. package/chunks/{chunk-BAPIZCC7.js → chunk-LTJLPYFS.js} +1 -1
  78. package/chunks/{chunk-ZOUMCSDW.js → chunk-MSNPEQ2I.js} +1 -1
  79. package/chunks/{chunk-MPDGSR2S.js → chunk-N3YWQWSR.js} +5 -5
  80. package/chunks/{chunk-VEVQB4CI.js → chunk-NDTPBVER.js} +1 -1
  81. package/chunks/{chunk-L4WG2XDS.js → chunk-NJ77L3GS.js} +1 -1
  82. package/chunks/{chunk-U2DX235N.js → chunk-NL62UQDW.js} +1 -1
  83. package/chunks/{chunk-QASJXL5B.js → chunk-NYXR2655.js} +1 -1
  84. package/chunks/{chunk-5SPQ5V35.js → chunk-OEPXWKZL.js} +1 -1
  85. package/chunks/{chunk-EOR7AP7Z.js → chunk-OIKWJN7E.js} +1 -1
  86. package/chunks/{chunk-BT7V3O75.js → chunk-OIQKVWR7.js} +1 -1
  87. package/chunks/{chunk-ESXBBANA.js → chunk-OPBSEVFC.js} +1 -1
  88. package/chunks/{chunk-NW3H676V.js → chunk-P5RBFVMP.js} +1 -1
  89. package/chunks/{chunk-F7KVMGGZ.js → chunk-QD4KNY2J.js} +1 -1
  90. package/chunks/{chunk-2ZE6CAZV.js → chunk-RSLBGXPB.js} +1 -1
  91. package/chunks/{chunk-3R7NEEW7.js → chunk-S542WTV7.js} +1 -1
  92. package/chunks/{chunk-KXAZ2Z5M.js → chunk-SEK234IM.js} +1 -1
  93. package/chunks/{chunk-5DPXLL3H.js → chunk-TM6IVXAM.js} +1 -1
  94. package/chunks/{chunk-KMJLEAS3.js → chunk-TPTV6HPU.js} +1 -1
  95. package/chunks/{chunk-DCUBMMWG.js → chunk-TQ6FKWSC.js} +1 -1
  96. package/chunks/{chunk-JK2S74SA.js → chunk-TUBHG6EI.js} +1 -1
  97. package/chunks/{chunk-FMZ5U7J5.js → chunk-UBPC3F32.js} +1 -1
  98. package/chunks/{chunk-XB7DJWOJ.js → chunk-UG5B4UOQ.js} +6 -6
  99. package/chunks/{chunk-36S57YYW.js → chunk-UGWTN5IK.js} +1 -1
  100. package/chunks/{chunk-SK2DTYBZ.js → chunk-URMRX2MG.js} +1 -1
  101. package/chunks/{chunk-VB4DB57C.js → chunk-UY6J5CHF.js} +1 -1
  102. package/chunks/{chunk-STQ3TEZW.js → chunk-VSTQT667.js} +2 -2
  103. package/chunks/{chunk-SGUUOXLH.js → chunk-WDO33SWR.js} +1 -1
  104. package/chunks/{chunk-IVXR5JO2.js → chunk-WFJHBU7B.js} +1 -1
  105. package/chunks/{chunk-BINJRUHZ.js → chunk-XSRHGC5R.js} +1 -1
  106. package/chunks/{chunk-HN7EGFIP.js → chunk-XVF3FMTM.js} +1 -1
  107. package/chunks/{chunk-C5X6K67T.js → chunk-XYRNYCRQ.js} +1 -1
  108. package/chunks/{chunk-HZOPWFFL.js → chunk-YAMLF3SM.js} +1 -1
  109. package/chunks/{chunk-CMW64XU2.js → chunk-ZEZCRRQC.js} +1 -1
  110. package/chunks/{chunk-J5W6P7QD.js → chunk-ZF56DRDP.js} +1 -1
  111. package/chunks/{chunk-LHIEE3A2.js → chunk-ZSPOFXP3.js} +1 -1
  112. package/chunks/{chunk-Q6CXEN4H.js → chunk-ZZXAOGUV.js} +1 -1
  113. package/chunks/{codex-subagent-executor-HB3MUCY4.js → codex-subagent-executor-7RAVQBYA.js} +1 -1
  114. package/chunks/{config-utils-F7OF5UR2.js → config-utils-JFD4RJK3.js} +1 -1
  115. package/chunks/{contextCommand-Y3KO2FY6.js → contextCommand-U6CD3CW7.js} +1 -1
  116. package/chunks/{core-runtime-D7DAA5NY.js → core-runtime-ORCZRJ4O.js} +1 -1
  117. package/chunks/{create-sub-session-2HTWYAP4.js → create-sub-session-57WMU2AE.js} +1 -1
  118. package/chunks/{cron-create-Y5I6E2X4.js → cron-create-V466MOUE.js} +1 -1
  119. package/chunks/{daemon-git-worktree-guard-UOBMXOUC.js → daemon-git-worktree-guard-ATD77XOF.js} +1 -1
  120. package/chunks/{daemon-status-provider-L2225KDS.js → daemon-status-provider-5FVRNMAZ.js} +1 -1
  121. package/chunks/{daemon-trust-policy-5D52N5GL.js → daemon-trust-policy-6YRQV4ZM.js} +1 -1
  122. package/chunks/{daemon-trust-policy-monitor-RUE25K7A.js → daemon-trust-policy-monitor-QRUOWZQP.js} +1 -1
  123. package/chunks/{deferred-core-runtime-6BO5DI5B.js → deferred-core-runtime-TXIXMDDH.js} +1 -1
  124. package/chunks/{edit-B6DKSK3O.js → edit-FNXBINJ3.js} +1 -1
  125. package/chunks/{enterPlanMode-WVJ3XC3P.js → enterPlanMode-YMLAOTTS.js} +1 -1
  126. package/chunks/{environment-7WMACN3E.js → environment-RFNJLRF7.js} +1 -1
  127. package/chunks/{errors-BN73QF2O.js → errors-NHGSZ2BV.js} +1 -1
  128. package/chunks/{execution-tool-IGDH3MQT.js → execution-tool-L2BF6ZKP.js} +1 -1
  129. package/chunks/{execution-worker-WWP3JZGV.js → execution-worker-F5B2BI2W.js} +1 -1
  130. package/chunks/{exitPlanMode-7WHKOTS7.js → exitPlanMode-ZZVBF5V4.js} +1 -1
  131. package/chunks/{fast-path-B37HGFQO.js → fast-path-TOJYOAD3.js} +1 -1
  132. package/chunks/{glob-ZRXU5G5X.js → glob-SYPMYU4V.js} +1 -1
  133. package/chunks/{goal-tools-DQ5IZXCM.js → goal-tools-NOXNXZFR.js} +1 -1
  134. package/chunks/{handleAutoUpdate-FD7QAG2R.js → handleAutoUpdate-RS6Y2IWS.js} +1 -1
  135. package/chunks/{i18n-TI3ZCEHR.js → i18n-WWZD25J5.js} +1 -1
  136. package/chunks/{initializer-SB7P3LRU.js → initializer-YGR4YXAM.js} +1 -1
  137. package/chunks/{installationInfo-B337C7R4.js → installationInfo-EPURVILN.js} +1 -1
  138. package/chunks/{interactive-mod-session-OWRMETPP.js → interactive-mod-session-2VSTTHPA.js} +1 -1
  139. package/chunks/{list-2QKQIEOB.js → list-6JAKVRMZ.js} +1 -1
  140. package/chunks/{llm-GQ76E4DL.js → llm-V272EOVL.js} +4 -4
  141. package/chunks/{llm-content-generator-2A23HFLD.js → llm-content-generator-EXMC3NYS.js} +1 -1
  142. package/chunks/{loadedSettingsAdapter-RGQOA5BG.js → loadedSettingsAdapter-T6W2CKFA.js} +1 -1
  143. package/chunks/{local-OEBLERSJ.js → local-NUBKA3T2.js} +1 -1
  144. package/chunks/{local-execution-environment-FT5J4SUH.js → local-execution-environment-WO62QDKJ.js} +1 -1
  145. package/chunks/{loggingContentGenerator-WC23RZYM.js → loggingContentGenerator-KHRN6S3S.js} +1 -1
  146. package/chunks/{loop-wakeup-GIIIDUNG.js → loop-wakeup-TTAZMOYH.js} +1 -1
  147. package/chunks/{manage-memory-E2OAR2RV.js → manage-memory-BKA7QM4N.js} +1 -1
  148. package/chunks/{managed-execution-engine-CYYNVVP5.js → managed-execution-engine-32BLALNC.js} +1 -1
  149. package/chunks/{managed-local-serve-TUVNNY7K.js → managed-local-serve-UTJFLZI6.js} +1 -1
  150. package/chunks/{managed-npm-update-IDRZ32UK.js → managed-npm-update-XPIRAQ47.js} +1 -1
  151. package/chunks/{managed-runtime-attestation-worker-HON7TGY2.js → managed-runtime-attestation-worker-DDU4HUGS.js} +1 -1
  152. package/chunks/{managed-runtime-bootstrap-OMLX5CTV.js → managed-runtime-bootstrap-7TTCLDQJ.js} +1 -1
  153. package/chunks/{managed-runtime-session-worker-J3P7WMDW.js → managed-runtime-session-worker-WBYLRXU3.js} +1 -1
  154. package/chunks/{managed-runtime-ssh-worker-LPFPOBTL.js → managed-runtime-ssh-worker-X2U2OK2E.js} +1 -1
  155. package/chunks/{managed-session-authority-I5OHOM7N.js → managed-session-authority-U76OGS6U.js} +1 -1
  156. package/chunks/{mcp-CGDIDRDI.js → mcp-UROGTJ3U.js} +1 -1
  157. package/chunks/{memory-VKXOH5UM.js → memory-M4OF6FV7.js} +1 -1
  158. package/chunks/{model-call-collection-ZTYFDFBB.js → model-call-collection-TW6Q7SXP.js} +1 -1
  159. package/chunks/{model-configuration-EXLM4SD3.js → model-configuration-4PJUBAYR.js} +1 -1
  160. package/chunks/{modelConfigUtils-XDMB6XPY.js → modelConfigUtils-ARMBTDAK.js} +1 -1
  161. package/chunks/{monitor-LKKCC6MQ.js → monitor-URMSEGAJ.js} +1 -1
  162. package/chunks/{nonInteractiveCli-J3Z3IZIF.js → nonInteractiveCli-YHOC5KZF.js} +1 -1
  163. package/chunks/{nonInteractiveToolExecutor-UQTMGYN2.js → nonInteractiveToolExecutor-DM5IGBP7.js} +1 -1
  164. package/chunks/{notebook-edit-JFD2KDI6.js → notebook-edit-3YSG73BK.js} +1 -1
  165. package/chunks/{omni-CI5JTMPR.js → omni-J6YYWKII.js} +1 -1
  166. package/chunks/{openaiContentGenerator-YZOV2TQX.js → openaiContentGenerator-UIFSPMTE.js} +1 -1
  167. package/chunks/{openaiResponsesContentGenerator-AHL7V6TE.js → openaiResponsesContentGenerator-U6Q536RZ.js} +1 -1
  168. package/chunks/{pidfile-ULOUTG67.js → pidfile-WCZE5ONH.js} +1 -1
  169. package/chunks/{processUtils-XX62FVFO.js → processUtils-3CDEN2GV.js} +1 -1
  170. package/chunks/{prompt-terminal-ledger-L6CWXBAW.js → prompt-terminal-ledger-VAQC6TC3.js} +1 -1
  171. package/chunks/{qwenContentGenerator-ZDXJW7EM.js → qwenContentGenerator-RWBGMON6.js} +1 -1
  172. package/chunks/{reactive-degrade-4OJ7XKSJ.js → reactive-degrade-GOTSVZKO.js} +1 -1
  173. package/chunks/{read-file-H6I32UZS.js → read-file-WNNTTHL5.js} +1 -1
  174. package/chunks/{resumeHistoryUtils-CTRMXPKQ.js → resumeHistoryUtils-UAGV4TC3.js} +1 -1
  175. package/chunks/{review-7SV2M7EL.js → review-JETUJT7N.js} +1 -1
  176. package/chunks/{ripGrep-Y2TGCQH5.js → ripGrep-OJNMOYPD.js} +1 -1
  177. package/chunks/{run-qwen-serve-6SWKYY6I.js → run-qwen-serve-BVNSBOLL.js} +1 -1
  178. package/chunks/{runtime-ITZIIC6D.js → runtime-CERVMTEG.js} +1 -1
  179. package/chunks/{sandboxConfig-FF2YF3RY.js → sandboxConfig-ZHW3GTMH.js} +1 -1
  180. package/chunks/{scheduled-tasks-WWPWNM3Y.js → scheduled-tasks-AAB5OESY.js} +1 -1
  181. package/chunks/{scheduler-ELSUH4GZ.js → scheduler-4ZZA357S.js} +1 -1
  182. package/chunks/{search-memory-465ZSHKG.js → search-memory-USJ3D7WQ.js} +1 -1
  183. package/chunks/{send-message-M5JFT3VH.js → send-message-QE2YZZ6M.js} +1 -1
  184. package/chunks/{serve-VTR7PTK2.js → serve-SX2PK3OZ.js} +1 -1
  185. package/chunks/{server-5NHPPEPR.js → server-OGTIIX65.js} +3 -3
  186. package/chunks/{session-HZLRQKEB.js → session-DXORIQDK.js} +1 -1
  187. package/chunks/{session-attachments-root-LS5Q4OT3.js → session-attachments-root-VHH2OZF6.js} +1 -1
  188. package/chunks/{session-execution-engine-selector-GS4LJPUU.js → session-execution-engine-selector-5WKZ6WXX.js} +1 -1
  189. package/chunks/{session-pr-refresh-FKYCCTWD.js → session-pr-refresh-MHXNT44I.js} +1 -1
  190. package/chunks/{sessionService-XUBKN4CM.js → sessionService-QDDGXOB7.js} +1 -1
  191. package/chunks/{settings-BFTTGWJN.js → settings-W3ALYJZM.js} +1 -1
  192. package/chunks/{shell-YEUMIQVE.js → shell-YROF2KXZ.js} +1 -1
  193. package/chunks/{skill-2MJ7S5SK.js → skill-CBEQAUIQ.js} +1 -1
  194. package/chunks/{skill-settings-DP7A2GMB.js → skill-settings-YRN4SHJO.js} +1 -1
  195. package/chunks/{spawnChannel-3IZ7S6U7.js → spawnChannel-M7Q6URLT.js} +1 -1
  196. package/chunks/{standalone-update-NAI3OI3P.js → standalone-update-WIRHMWE6.js} +1 -1
  197. package/chunks/{start-opentui-ui-D6ETKJSG.js → start-opentui-ui-OLHWNKCY.js} +1 -1
  198. package/chunks/{startInteractiveUI-FR5ZT72L.js → startInteractiveUI-KCHCIQWO.js} +1 -1
  199. package/chunks/{subscription-content-generator-JHU5YG2L.js → subscription-content-generator-YQLQKG6S.js} +1 -1
  200. package/chunks/{team-create-ZW3NXJ2M.js → team-create-I432CHIX.js} +1 -1
  201. package/chunks/{team-plan-approval-GPFOKUEV.js → team-plan-approval-APMPMLXS.js} +1 -1
  202. package/chunks/{terminal-image-renderer-WTEEKRMJ.js → terminal-image-renderer-3BNICGAX.js} +1 -1
  203. package/chunks/{theme-manager-STF74SF2.js → theme-manager-6KY7Q4ZR.js} +1 -1
  204. package/chunks/{tool-call-TVX5UHRJ.js → tool-call-QGOVXOVJ.js} +1 -1
  205. package/chunks/{tool-result-media-QALAETZ4.js → tool-result-media-LRSYJOND.js} +1 -1
  206. package/chunks/{tool-search-ZGJEYTBI.js → tool-search-HXP25AWV.js} +1 -1
  207. package/chunks/{total-session-admission-BOYLCRYA.js → total-session-admission-ISTRHUQ7.js} +1 -1
  208. package/chunks/{trustedFolders-65OZWLQO.js → trustedFolders-5BXMWMYB.js} +1 -1
  209. package/chunks/{update-relaunch-4LJ3SY6L.js → update-relaunch-NYGYYLSC.js} +1 -1
  210. package/chunks/{updateCheck-2QOAKEIH.js → updateCheck-UBLS3LUD.js} +1 -1
  211. package/chunks/{upload-config-5N7UDWC6.js → upload-config-Y372LVXX.js} +1 -1
  212. package/chunks/{useAutoAcceptIndicator-V37CGGMF.js → useAutoAcceptIndicator-RXZJRU74.js} +1 -1
  213. package/chunks/{validateNonInterActiveAuth-6ZTVWZ6W.js → validateNonInterActiveAuth-2GJ4ICJ3.js} +1 -1
  214. package/chunks/{version-EO3VIRH6.js → version-XRSNVEB2.js} +1 -1
  215. package/chunks/{web-fetch-B6LNZ2YK.js → web-fetch-B4VFVGWW.js} +1 -1
  216. package/chunks/{web-search-VIPZWUJX.js → web-search-3DSQWMAV.js} +1 -1
  217. package/chunks/{workflow-W5QEAOGN.js → workflow-RCCH5FPV.js} +1 -1
  218. package/chunks/{workflow-ancestor-trust-VE7B4RD2.js → workflow-ancestor-trust-N3QYH3OL.js} +1 -1
  219. package/chunks/{workspace-agents-D32D3K5S.js → workspace-agents-KEV4VBZD.js} +1 -1
  220. package/chunks/{workspace-providers-status-BOH7RJPV.js → workspace-providers-status-HW4VI4T7.js} +1 -1
  221. package/chunks/{workspace-recovery-worker-53GJWYJ5.js → workspace-recovery-worker-C3SSJ64A.js} +1 -1
  222. package/chunks/{workspace-registration-store-BMX2NT45.js → workspace-registration-store-K7VEBHIU.js} +1 -1
  223. package/chunks/{workspace-registry-SS2NKLEL.js → workspace-registry-C5ZPYT4P.js} +1 -1
  224. package/chunks/{workspace-runtime-coordinator-7ZKVLJDC.js → workspace-runtime-coordinator-ALWOLW3N.js} +1 -1
  225. package/chunks/{workspace-service-GIUD3D25.js → workspace-service-TNZJAC7M.js} +1 -1
  226. package/chunks/{workspace-skills-status-36A76TDX.js → workspace-skills-status-TI763F5M.js} +1 -1
  227. package/chunks/{workspace-trust-reconciler-VKKSY2AR.js → workspace-trust-reconciler-6UQ7HSUG.js} +1 -1
  228. package/chunks/{write-file-43JOGU55.js → write-file-2XXEHBZR.js} +1 -1
  229. package/chunks/{zoom-image-USUXATDM.js → zoom-image-P3E3V6PQ.js} +1 -1
  230. package/cli.js +2 -2
  231. package/execution-worker.js +1 -1
  232. package/export-transcript-document.js +1 -1
  233. package/package.json +3 -3
  234. package/web-shell/assets/{PierreFilePreview-Dx075_VT.js → PierreFilePreview-DtTOu9VE.js} +1 -1
  235. package/web-shell/assets/{SpreadsheetPreview-l2R-Y1o6.js → SpreadsheetPreview-C21imJIX.js} +1 -1
  236. package/web-shell/assets/{WorkspaceFileBrowser-CGi_eR1a.js → WorkspaceFileBrowser-DIWHfhtl.js} +1 -1
  237. package/web-shell/assets/{abnfDiagram-VCTEODGH-DZPHyWbH.js → abnfDiagram-VCTEODGH-qffA9juk.js} +1 -1
  238. package/web-shell/assets/{agents-route-Bp0Yjhm4.js → agents-route-4f6fKJaY.js} +1 -1
  239. package/web-shell/assets/{arc-BAS_Ct0z.js → arc-BOZg4dn0.js} +1 -1
  240. package/web-shell/assets/{architectureDiagram-5GKGNRK7-C5a7ooE1.js → architectureDiagram-5GKGNRK7-BOYWC6dJ.js} +1 -1
  241. package/web-shell/assets/{blockDiagram-NRAW4CY4-D-Wzzi9Z.js → blockDiagram-NRAW4CY4-CiN_IMJ7.js} +1 -1
  242. package/web-shell/assets/{c4Diagram-UCG6FXSJ-BiYnmYkI.js → c4Diagram-UCG6FXSJ-WYLA0JW0.js} +1 -1
  243. package/web-shell/assets/channel-DtcoR96T.js +1 -0
  244. package/web-shell/assets/{chunk-2Q5K7J3B-DHi3a_yf.js → chunk-2Q5K7J3B-BZUPB745.js} +1 -1
  245. package/web-shell/assets/{chunk-5VM5RSS4-DKgiHWPM.js → chunk-5VM5RSS4-BHfjsu8x.js} +1 -1
  246. package/web-shell/assets/{chunk-F27PBJKO-qvFMzdl_.js → chunk-F27PBJKO-DHtQsOyA.js} +1 -1
  247. package/web-shell/assets/{chunk-G27WJ6UU-C9Apl4Df.js → chunk-G27WJ6UU-DvEX_QHY.js} +1 -1
  248. package/web-shell/assets/{chunk-JWPE2WC7-ManrSgDL.js → chunk-JWPE2WC7-CwQJmw1a.js} +1 -1
  249. package/web-shell/assets/{chunk-LCL6LL3I-DNZqkjQu.js → chunk-LCL6LL3I-Cv7bRuRV.js} +1 -1
  250. package/web-shell/assets/{chunk-POPQ4Y6H-CxineRE8.js → chunk-POPQ4Y6H-zGw4PzDB.js} +1 -1
  251. package/web-shell/assets/{chunk-SVP7TREG-BzmCQ6Bh.js → chunk-SVP7TREG-DZMGVnJg.js} +1 -1
  252. package/web-shell/assets/{chunk-XXDRQBXY-Dm6Ascgd.js → chunk-XXDRQBXY-Dg5_qrTq.js} +1 -1
  253. package/web-shell/assets/classDiagram-DTDB5LWJ-CBq-DXYQ.js +1 -0
  254. package/web-shell/assets/classDiagram-v2-JRS7N3AN-CBq-DXYQ.js +1 -0
  255. package/web-shell/assets/{cose-bilkent-JH36ORCC-Cs-vIewG.js → cose-bilkent-JH36ORCC-D07aXZdD.js} +1 -1
  256. package/web-shell/assets/{cynefin-OW5HDTMX-CrxyzLrG.js → cynefin-OW5HDTMX-B4txjD0l.js} +1 -1
  257. package/web-shell/assets/{cynefinDiagram-5FMLGOSQ-Bf7RdtX4.js → cynefinDiagram-5FMLGOSQ-zFtLauJ6.js} +1 -1
  258. package/web-shell/assets/{dagre-3AP2YEHR-jN7qDhRR.js → dagre-3AP2YEHR-CKZj9zbB.js} +1 -1
  259. package/web-shell/assets/{diagram-S7CK7UJ4-KcNQ38Ue.js → diagram-S7CK7UJ4-DIsLTku6.js} +1 -1
  260. package/web-shell/assets/{diagram-UQ7AKVKN-9VmCS0SV.js → diagram-UQ7AKVKN-60CC00CO.js} +1 -1
  261. package/web-shell/assets/{diagram-VSXAHHWV-D-MA8NCD.js → diagram-VSXAHHWV-BCfHqY7L.js} +1 -1
  262. package/web-shell/assets/{diagram-VX7I27RA-323tLIBS.js → diagram-VX7I27RA-BbTOx9qC.js} +1 -1
  263. package/web-shell/assets/{diagram-Z3DM3KII-C547h61H.js → diagram-Z3DM3KII-DLjgnodz.js} +1 -1
  264. package/web-shell/assets/{docx-preview-DHO0seXT.js → docx-preview-CfGqg6IJ.js} +1 -1
  265. package/web-shell/assets/{ebnfDiagram-PWID7BFC-DfB8wLF5.js → ebnfDiagram-PWID7BFC-Cf1IQbGo.js} +1 -1
  266. package/web-shell/assets/{erDiagram-SSCWMZ5O-tzqYkCjp.js → erDiagram-SSCWMZ5O-BTVNpu1y.js} +1 -1
  267. package/web-shell/assets/{flowDiagram-A5DVABFB-Dsw6uHjD.js → flowDiagram-A5DVABFB-BC404IkJ.js} +1 -1
  268. package/web-shell/assets/{ganttDiagram-EL5Y4UJY-D1SaF3O0.js → ganttDiagram-EL5Y4UJY-BHP58V1Y.js} +1 -1
  269. package/web-shell/assets/{gitGraphDiagram-WWUBYQGX-D0EzECMT.js → gitGraphDiagram-WWUBYQGX-s1PkjMd4.js} +1 -1
  270. package/web-shell/assets/{index-ob2Iut7D.js → index-DZnv4pXI.js} +6 -6
  271. package/web-shell/assets/{index-C-YHF5xI.js → index-YpdTDWts.js} +1 -1
  272. package/web-shell/assets/{infoDiagram-RXCK75RN-6NnYMmcC.js → infoDiagram-RXCK75RN-DDaQbbGu.js} +1 -1
  273. package/web-shell/assets/{ishikawaDiagram-5VMMS53U-BnxsfuuS.js → ishikawaDiagram-5VMMS53U-FpQWCzWS.js} +1 -1
  274. package/web-shell/assets/{journeyDiagram-EYS64GPL-DduswigY.js → journeyDiagram-EYS64GPL-CC5YG1zk.js} +1 -1
  275. package/web-shell/assets/{kanban-definition-3QL26DDD-D0trNRAQ.js → kanban-definition-3QL26DDD-CsitCmSH.js} +1 -1
  276. package/web-shell/assets/{layout-nP-pCdd_.js → layout-DR8LNzXS.js} +1 -1
  277. package/web-shell/assets/{linear-DCw4lqG9.js → linear-Dt61H2xY.js} +1 -1
  278. package/web-shell/assets/{mermaid.core-DYjTp4Sk.js → mermaid.core-C3SdL30W.js} +6 -6
  279. package/web-shell/assets/{mindmap-definition-FBJOCRG2-BK9iSa2V.js → mindmap-definition-FBJOCRG2-BjxTLs9R.js} +1 -1
  280. package/web-shell/assets/{pegDiagram-XKGWAZYB-Dg0TQ1Ty.js → pegDiagram-XKGWAZYB-eBurSwq6.js} +1 -1
  281. package/web-shell/assets/{pieDiagram-E7YTZNPT-DKeqeVkg.js → pieDiagram-E7YTZNPT-BFWkbtZz.js} +1 -1
  282. package/web-shell/assets/{quadrantDiagram-AXDQQJYC-C4zBeQXd.js → quadrantDiagram-AXDQQJYC-SThzXP6T.js} +1 -1
  283. package/web-shell/assets/{railroadDiagram-O6MQD6OU-jDnAGU3z.js → railroadDiagram-O6MQD6OU-D73YId-T.js} +1 -1
  284. package/web-shell/assets/{requirementDiagram-EFPCY7ZU-D0sIdHq4.js → requirementDiagram-EFPCY7ZU-YecInWjM.js} +1 -1
  285. package/web-shell/assets/{sankeyDiagram-P5KCCOFB-BFz_QzXx.js → sankeyDiagram-P5KCCOFB-D4Gl35cC.js} +1 -1
  286. package/web-shell/assets/{sequenceDiagram-WJ2MYXX4-DhDmjiCT.js → sequenceDiagram-WJ2MYXX4-C1JdJSRH.js} +1 -1
  287. package/web-shell/assets/{sizeCapture-X5ZJPWSS-D8Ov3K_0.js → sizeCapture-X5ZJPWSS-D3mHX34v.js} +1 -1
  288. package/web-shell/assets/{stateDiagram-HBIQ2CUA-Bb4f1ILo.js → stateDiagram-HBIQ2CUA-BR05d7ll.js} +1 -1
  289. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-BBhqVmOU.js +1 -0
  290. package/web-shell/assets/{swimlanes-XN3QIQJK-CQyilPoS.js → swimlanes-XN3QIQJK-CENq9EQ7.js} +1 -1
  291. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-DI8ON7to.js +8 -0
  292. package/web-shell/assets/{timeline-definition-24CTP7MA-B_CntdLT.js → timeline-definition-24CTP7MA-DFhKdLgc.js} +1 -1
  293. package/web-shell/assets/{vennDiagram-4TSXK5OY-BbuHkADM.js → vennDiagram-4TSXK5OY-C-p5h-ue.js} +1 -1
  294. package/web-shell/assets/{wardleyDiagram-VM6X3IG4-0mNKcB-T.js → wardleyDiagram-VM6X3IG4-BCWSjHZH.js} +1 -1
  295. package/web-shell/assets/{xychartDiagram-S5SC5T6Z-BL-rMOQs.js → xychartDiagram-S5SC5T6Z-DBvE_Y0y.js} +1 -1
  296. package/web-shell/index.html +1 -1
  297. package/web-shell/sw.js +1 -1
  298. package/web-shell/assets/channel-B31dxYCL.js +0 -1
  299. package/web-shell/assets/classDiagram-DTDB5LWJ-CxU_Ty2M.js +0 -1
  300. package/web-shell/assets/classDiagram-v2-JRS7N3AN-CxU_Ty2M.js +0 -1
  301. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-xbht8Czs.js +0 -1
  302. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-Dz34bASJ.js +0 -8
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{getGitVersion,getNpmVersion}from"./chunk-4JLLFT6S.js";import{buildEnvStatusFromEnv,snapshotProcessEnv}from"./chunk-EXVVGGII.js";import{mapDomainErrorToErrorKind}from"./chunk-YCAEGUZI.js";import{canUseRipgrep}from"./chunk-MYPKMC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{promises as fs}from"node:fs";var REQUIRED_NODE_MAJOR=22;function createDaemonStatusProvider(options={}){const readEnv=__name(()=>options.env??snapshotProcessEnv(),"readEnv");return{async getEnvStatus(boundWorkspace,acpChannelLive){return buildEnvStatusFromEnv(boundWorkspace,acpChannelLive,readEnv())},async getDaemonPreflightCells(boundWorkspace){return buildDaemonPreflightCells(boundWorkspace,readEnv())}}}__name(createDaemonStatusProvider,"createDaemonStatusProvider");async function buildDaemonPreflightCells(boundWorkspace,env){const nodeVersionCell=__name(()=>{try{const nodeVersion=process.versions.node;const major=Number.parseInt(nodeVersion.split(".")[0]??"0",10);if(Number.isFinite(major)&&major>=REQUIRED_NODE_MAJOR){return{kind:"node_version",status:"ok",locality:"daemon",detail:{version:nodeVersion,required:`>=${REQUIRED_NODE_MAJOR}`}}}return{kind:"node_version",status:"error",errorKind:"missing_binary",error:`Node ${nodeVersion} is below the required >=${REQUIRED_NODE_MAJOR}.`,hint:`Upgrade Node to v${REQUIRED_NODE_MAJOR} or newer.`,locality:"daemon",detail:{version:nodeVersion,required:`>=${REQUIRED_NODE_MAJOR}`}}}catch(err){return{kind:"node_version",status:"error",error:err instanceof Error?err.message:String(err),locality:"daemon"}}},"nodeVersionCell");const cliEntryCell=__name(()=>{const cliEntry=env["QWEN_CLI_ENTRY"]||process.argv[1]||"";if(cliEntry){return{kind:"cli_entry",status:"ok",locality:"daemon",detail:{path:cliEntry,source:env["QWEN_CLI_ENTRY"]?"QWEN_CLI_ENTRY":"process.argv[1]"}}}return{kind:"cli_entry",status:"error",errorKind:"missing_binary",error:"Cannot determine CLI entry path for spawning the ACP child.",hint:"Set QWEN_CLI_ENTRY to the absolute path of the qwen entry script.",locality:"daemon"}},"cliEntryCell");const workspaceDirCell=__name(async()=>{try{const stat=await fs.stat(boundWorkspace);if(stat.isDirectory()){return{kind:"workspace_dir",status:"ok",locality:"daemon",detail:{path:boundWorkspace}}}return{kind:"workspace_dir",status:"error",errorKind:"missing_file",error:`Bound workspace path is not a directory: ${boundWorkspace}`,locality:"daemon",detail:{path:boundWorkspace}}}catch(err){const errorKind=mapDomainErrorToErrorKind(err);return{kind:"workspace_dir",status:"error",error:err instanceof Error?err.message:String(err),...errorKind?{errorKind}:{},locality:"daemon",detail:{path:boundWorkspace}}}},"workspaceDirCell");const slots=[{kind:"node_version",run:nodeVersionCell},{kind:"cli_entry",run:cliEntryCell},{kind:"workspace_dir",run:workspaceDirCell},{kind:"ripgrep",run:__name(()=>safeCheck("ripgrep",async()=>{const ok=await canUseRipgrep(true);return ok?{status:"ok"}:{status:"warning",hint:"Install ripgrep for faster grep tool execution."}}),"run")},{kind:"git",run:__name(()=>safeCheck("git",async()=>{const v=await getGitVersion();return v&&v!=="unknown"?{status:"ok",detail:{version:v}}:{status:"warning",hint:"git not found on PATH."}}),"run")},{kind:"npm",run:__name(()=>safeCheck("npm",async()=>{const v=await getNpmVersion();return v&&v!=="unknown"?{status:"ok",detail:{version:v}}:{status:"warning",hint:"npm not found on PATH."}}),"run")}];const settled=await Promise.allSettled(slots.map(s=>Promise.resolve().then(s.run)));return settled.map((result,i)=>{if(result.status==="fulfilled")return result.value;const err=result.reason;const errorKind=mapDomainErrorToErrorKind(err);return{kind:slots[i].kind,status:"error",locality:"daemon",error:err instanceof Error?err.message:String(err),...errorKind?{errorKind}:{}}})}__name(buildDaemonPreflightCells,"buildDaemonPreflightCells");async function safeCheck(kind,body){try{const r=await body();return{kind,status:r.status,locality:"daemon",...r.detail?{detail:r.detail}:{},...r.hint?{hint:r.hint}:{}}}catch(err){const errorKind=mapDomainErrorToErrorKind(err);return{kind,status:"error",error:err instanceof Error?err.message:String(err),locality:"daemon",...errorKind?{errorKind}:{}}}}__name(safeCheck,"safeCheck");export{createDaemonStatusProvider};
3
+ import{getGitVersion,getNpmVersion}from"./chunk-7SX547WS.js";import{buildEnvStatusFromEnv,snapshotProcessEnv}from"./chunk-EXVVGGII.js";import{mapDomainErrorToErrorKind}from"./chunk-YCAEGUZI.js";import{canUseRipgrep}from"./chunk-MYPKMC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{promises as fs}from"node:fs";var REQUIRED_NODE_MAJOR=22;function createDaemonStatusProvider(options={}){const readEnv=__name(()=>options.env??snapshotProcessEnv(),"readEnv");return{async getEnvStatus(boundWorkspace,acpChannelLive){return buildEnvStatusFromEnv(boundWorkspace,acpChannelLive,readEnv())},async getDaemonPreflightCells(boundWorkspace){return buildDaemonPreflightCells(boundWorkspace,readEnv())}}}__name(createDaemonStatusProvider,"createDaemonStatusProvider");async function buildDaemonPreflightCells(boundWorkspace,env){const nodeVersionCell=__name(()=>{try{const nodeVersion=process.versions.node;const major=Number.parseInt(nodeVersion.split(".")[0]??"0",10);if(Number.isFinite(major)&&major>=REQUIRED_NODE_MAJOR){return{kind:"node_version",status:"ok",locality:"daemon",detail:{version:nodeVersion,required:`>=${REQUIRED_NODE_MAJOR}`}}}return{kind:"node_version",status:"error",errorKind:"missing_binary",error:`Node ${nodeVersion} is below the required >=${REQUIRED_NODE_MAJOR}.`,hint:`Upgrade Node to v${REQUIRED_NODE_MAJOR} or newer.`,locality:"daemon",detail:{version:nodeVersion,required:`>=${REQUIRED_NODE_MAJOR}`}}}catch(err){return{kind:"node_version",status:"error",error:err instanceof Error?err.message:String(err),locality:"daemon"}}},"nodeVersionCell");const cliEntryCell=__name(()=>{const cliEntry=env["QWEN_CLI_ENTRY"]||process.argv[1]||"";if(cliEntry){return{kind:"cli_entry",status:"ok",locality:"daemon",detail:{path:cliEntry,source:env["QWEN_CLI_ENTRY"]?"QWEN_CLI_ENTRY":"process.argv[1]"}}}return{kind:"cli_entry",status:"error",errorKind:"missing_binary",error:"Cannot determine CLI entry path for spawning the ACP child.",hint:"Set QWEN_CLI_ENTRY to the absolute path of the qwen entry script.",locality:"daemon"}},"cliEntryCell");const workspaceDirCell=__name(async()=>{try{const stat=await fs.stat(boundWorkspace);if(stat.isDirectory()){return{kind:"workspace_dir",status:"ok",locality:"daemon",detail:{path:boundWorkspace}}}return{kind:"workspace_dir",status:"error",errorKind:"missing_file",error:`Bound workspace path is not a directory: ${boundWorkspace}`,locality:"daemon",detail:{path:boundWorkspace}}}catch(err){const errorKind=mapDomainErrorToErrorKind(err);return{kind:"workspace_dir",status:"error",error:err instanceof Error?err.message:String(err),...errorKind?{errorKind}:{},locality:"daemon",detail:{path:boundWorkspace}}}},"workspaceDirCell");const slots=[{kind:"node_version",run:nodeVersionCell},{kind:"cli_entry",run:cliEntryCell},{kind:"workspace_dir",run:workspaceDirCell},{kind:"ripgrep",run:__name(()=>safeCheck("ripgrep",async()=>{const ok=await canUseRipgrep(true);return ok?{status:"ok"}:{status:"warning",hint:"Install ripgrep for faster grep tool execution."}}),"run")},{kind:"git",run:__name(()=>safeCheck("git",async()=>{const v=await getGitVersion();return v&&v!=="unknown"?{status:"ok",detail:{version:v}}:{status:"warning",hint:"git not found on PATH."}}),"run")},{kind:"npm",run:__name(()=>safeCheck("npm",async()=>{const v=await getNpmVersion();return v&&v!=="unknown"?{status:"ok",detail:{version:v}}:{status:"warning",hint:"npm not found on PATH."}}),"run")}];const settled=await Promise.allSettled(slots.map(s=>Promise.resolve().then(s.run)));return settled.map((result,i)=>{if(result.status==="fulfilled")return result.value;const err=result.reason;const errorKind=mapDomainErrorToErrorKind(err);return{kind:slots[i].kind,status:"error",locality:"daemon",error:err instanceof Error?err.message:String(err),...errorKind?{errorKind}:{}}})}__name(buildDaemonPreflightCells,"buildDaemonPreflightCells");async function safeCheck(kind,body){try{const r=await body();return{kind,status:r.status,locality:"daemon",...r.detail?{detail:r.detail}:{},...r.hint?{hint:r.hint}:{}}}catch(err){const errorKind=mapDomainErrorToErrorKind(err);return{kind,status:"error",error:err instanceof Error?err.message:String(err),locality:"daemon",...errorKind?{errorKind}:{}}}}__name(safeCheck,"safeCheck");export{createDaemonStatusProvider};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Qwen Team
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{MOD_MAX_BYTES,MOD_MAX_DEPTH,MOD_TOOL_RESERVED,jsonDepth,record,validateInput}from"./chunk-XWYUQMLN.js";import{CoreToolScheduler}from"./chunk-XUB4JKSR.js";import{ToolNames,canonicalToolName,resolveRegisteredToolName}from"./chunk-SBZFGYYS.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();import{isDeepStrictEqual}from"node:util";async function modToolRequest(config,request){const name=canonicalToolName(request.name);if(request.goalContext||name===ToolNames.STRUCTURED_OUTPUT||name===ToolNames.TOOL_SEARCH||name===ToolNames.SEARCH_MEMORY||request.executionOrigin?.kind==="fixed_policy")return void 0;if(name!==ToolNames.TOOL_CALL)return config.getToolRegistry().getTool(name)||config.getToolRegistry().getAllToolNames().includes(name)?{...request,name}:void 0;const targetName=request.args["name"];let args=request.args["arguments"];if(typeof args==="string"){try{args=JSON.parse(args)}catch{return void 0}}if(typeof targetName!=="string"||!record(args))return void 0;const registry=config.getToolRegistry();const resolved=resolveRegisteredToolName(canonicalToolName(targetName),registry.getAllToolNames());if(typeof resolved!=="string"||resolved===ToolNames.TOOL_CALL||resolved===ToolNames.TOOL_SEARCH||resolved===ToolNames.SEARCH_MEMORY)return void 0;let target;try{target=await registry.ensureTool(resolved)}catch{return void 0}if(!target||!registry.isDeferredAndHidden(target.name)||target.name===ToolNames.STRUCTURED_OUTPUT)return void 0;return{...request,name:target.name,args}}__name(modToolRequest,"modToolRequest");async function executeModTool(request,execution,middleware,execute,signal){const shadowed=Object.fromEntries(MOD_TOOL_RESERVED.filter(key=>Object.hasOwn(execution.args,key)).map(key=>[key,execution.args[key]]));const input={...execution.args,tool:execution.name,tool_use_id:request.callId};for(const key of MOD_TOOL_RESERVED)delete input[key];input.tool=execution.name;input.tool_use_id=request.callId;if(Object.keys(shadowed).length)input["$shadowed"]=shadowed;const refs=new Map;let latest;let executed;let attempts=0;let answer;try{answer=await middleware(input,async(changed,active,check)=>{active.throwIfAborted();validateInput("tool.call",changed,input);if(++attempts>64)throw new Error("Mod tool execution limit exceeded.");const args={...changed};for(const key of MOD_TOOL_RESERVED)delete args[key];Object.assign(args,shadowed);const nativeRequest=canonicalToolName(request.name)===ToolNames.TOOL_CALL?{...request,args:{...request.args,arguments:structuredClone(args)}}:{...request,args:structuredClone(args)};const completed=await execute(nativeRequest,active,check);latest=completed;if(completed.response.executionStatus==="success"||completed.response.executionStatus==="error"&&executed?.response.executionStatus!=="success")executed=completed;const response2=completed.response;let result2=response2.responseParts.find(part=>part.functionResponse)?.functionResponse?.response??{};let json=JSON.stringify(result2);if(Buffer.byteLength(json)>MOD_MAX_BYTES/2||jsonDepth(json)>MOD_MAX_DEPTH/2){result2={output:"[Native tool result exceeds the Mod payload limit; return this reference unchanged to retain it.]"};json=JSON.stringify(result2)}const value={ref:attempts,result:JSON.parse(json),text:(record(result2)&&typeof result2["output"]==="string"?result2["output"]:json).slice(0,16e3),...response2.error?{isError:true}:{}};refs.set(attempts,{completed,value});return value},signal)}catch(error2){answer={deny:`Mod tool dispatch failed: ${String(error2)}`}}const referenced=!("deny"in answer)&&answer.ref!==void 0?refs.get(answer.ref):void 0;const selected=referenced?.completed??latest;const native=selected?.response;if(latest?.response.error&&(latest.response.executionStatus==="not_started"||latest.response.executionStatus==="cancelled")){if(!executed)return{response:latest.response,completed:latest};const message2=`An earlier Mod tool attempt ran. A later attempt failed: ${latest.response.error.message}`;return{completed:executed,response:{...latest.response,executionStatus:executed.response.executionStatus,error:new Error(message2),resultDisplay:message2,contentLength:message2.length,responseParts:[{functionResponse:{id:request.callId,name:request.name,response:{error:message2}}}]}}}if(referenced&&!("deny"in answer)&&isDeepStrictEqual(answer.result,referenced.value.result)){return{response:{...referenced.completed.response,executionStatus:executed?.response.executionStatus??referenced.completed.response.executionStatus},completed:executed??referenced.completed}}const message="deny"in answer?`${executed?"The tool ran; a Mod withheld its result. ":"Tool denied by Mod. "}${answer.deny}`:void 0;const result="deny"in answer?{error:message}:record(answer.result)&&Object.entries(answer.result).every(([key,value])=>(key==="output"||key==="error")&&typeof value==="string")?answer.result:{output:typeof answer.result==="string"?answer.result:JSON.stringify(answer.result)};const text=JSON.stringify(result);const error=message?new Error(message):native?.error??(!("deny"in answer)&&answer.isError?new Error("Mod returned an error result."):void 0);const response={...native,callId:request.callId,responseParts:[{functionResponse:{id:request.callId,name:request.name,response:result}}],resultDisplay:text,contentLength:text.length,executionStatus:executed?.response.executionStatus??native?.executionStatus??"not_started",error,errorType:native?.errorType??(error?"execution_denied":void 0)};return{response,completed:executed??selected}}__name(executeModTool,"executeModTool");async function executeToolCall(config,toolCallRequest,abortSignal,options={}){const execution=options.modToolCall&&await modToolRequest(config,toolCallRequest);if(execution&&options.modToolCall){const{response,completed}=await executeModTool(toolCallRequest,execution,options.modToolCall,async(request,signal,check)=>{let completed2;await executeToolCall(config,request,signal,{...options,modToolCall:void 0,modToolCheck:check,recordToolResult:false,onAllToolCallsComplete:__name(async calls=>{completed2=calls[0]},"onAllToolCallsComplete")});if(!completed2)throw new Error("Mod native tool did not complete.");return completed2},abortSignal);if(completed)await options.onAllToolCallsComplete?.([{...completed,response}]);if(options.recordToolResult!==false)config.getChatRecordingService()?.recordToolResult(response.responseParts,{...response,status:completed?.status??(response.error?"error":"success")});return response}return new Promise((resolve,reject)=>{new CoreToolScheduler({config,modToolCheck:options.modToolCheck,chatRecordingService:options.recordToolResult===false?void 0:config.getChatRecordingService(),outputUpdateHandler:options.outputUpdateHandler,onAllToolCallsComplete:__name(async completedToolCalls=>{if(options.onAllToolCallsComplete){await options.onAllToolCallsComplete(completedToolCalls)}resolve(completedToolCalls[0].response)},"onAllToolCallsComplete"),onToolCallsUpdate:options.onToolCallsUpdate,onToolResultFullTurnModel:options.onToolResultFullTurnModel,getPreferredEditor:__name(()=>void 0,"getPreferredEditor"),onEditorClose:__name(()=>{},"onEditorClose")}).schedule(toolCallRequest,abortSignal,options.runtimeView).catch(reject)})}__name(executeToolCall,"executeToolCall");export{modToolRequest,executeModTool,executeToolCall};
3
+ import{MOD_MAX_BYTES,MOD_MAX_DEPTH,MOD_TOOL_RESERVED,jsonDepth,record,validateInput}from"./chunk-XWYUQMLN.js";import{CoreToolScheduler}from"./chunk-3NR3JBMA.js";import{ToolNames,canonicalToolName,resolveRegisteredToolName}from"./chunk-SBZFGYYS.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();import{isDeepStrictEqual}from"node:util";async function modToolRequest(config,request){const name=canonicalToolName(request.name);if(request.goalContext||name===ToolNames.STRUCTURED_OUTPUT||name===ToolNames.TOOL_SEARCH||name===ToolNames.SEARCH_MEMORY||request.executionOrigin?.kind==="fixed_policy")return void 0;if(name!==ToolNames.TOOL_CALL)return config.getToolRegistry().getTool(name)||config.getToolRegistry().getAllToolNames().includes(name)?{...request,name}:void 0;const targetName=request.args["name"];let args=request.args["arguments"];if(typeof args==="string"){try{args=JSON.parse(args)}catch{return void 0}}if(typeof targetName!=="string"||!record(args))return void 0;const registry=config.getToolRegistry();const resolved=resolveRegisteredToolName(canonicalToolName(targetName),registry.getAllToolNames());if(typeof resolved!=="string"||resolved===ToolNames.TOOL_CALL||resolved===ToolNames.TOOL_SEARCH||resolved===ToolNames.SEARCH_MEMORY)return void 0;let target;try{target=await registry.ensureTool(resolved)}catch{return void 0}if(!target||!registry.isDeferredAndHidden(target.name)||target.name===ToolNames.STRUCTURED_OUTPUT)return void 0;return{...request,name:target.name,args}}__name(modToolRequest,"modToolRequest");async function executeModTool(request,execution,middleware,execute,signal){const shadowed=Object.fromEntries(MOD_TOOL_RESERVED.filter(key=>Object.hasOwn(execution.args,key)).map(key=>[key,execution.args[key]]));const input={...execution.args,tool:execution.name,tool_use_id:request.callId};for(const key of MOD_TOOL_RESERVED)delete input[key];input.tool=execution.name;input.tool_use_id=request.callId;if(Object.keys(shadowed).length)input["$shadowed"]=shadowed;const refs=new Map;let latest;let executed;let attempts=0;let answer;try{answer=await middleware(input,async(changed,active,check)=>{active.throwIfAborted();validateInput("tool.call",changed,input);if(++attempts>64)throw new Error("Mod tool execution limit exceeded.");const args={...changed};for(const key of MOD_TOOL_RESERVED)delete args[key];Object.assign(args,shadowed);const nativeRequest=canonicalToolName(request.name)===ToolNames.TOOL_CALL?{...request,args:{...request.args,arguments:structuredClone(args)}}:{...request,args:structuredClone(args)};const completed=await execute(nativeRequest,active,check);latest=completed;if(completed.response.executionStatus==="success"||completed.response.executionStatus==="error"&&executed?.response.executionStatus!=="success")executed=completed;const response2=completed.response;let result2=response2.responseParts.find(part=>part.functionResponse)?.functionResponse?.response??{};let json=JSON.stringify(result2);if(Buffer.byteLength(json)>MOD_MAX_BYTES/2||jsonDepth(json)>MOD_MAX_DEPTH/2){result2={output:"[Native tool result exceeds the Mod payload limit; return this reference unchanged to retain it.]"};json=JSON.stringify(result2)}const value={ref:attempts,result:JSON.parse(json),text:(record(result2)&&typeof result2["output"]==="string"?result2["output"]:json).slice(0,16e3),...response2.error?{isError:true}:{}};refs.set(attempts,{completed,value});return value},signal)}catch(error2){answer={deny:`Mod tool dispatch failed: ${String(error2)}`}}const referenced=!("deny"in answer)&&answer.ref!==void 0?refs.get(answer.ref):void 0;const selected=referenced?.completed??latest;const native=selected?.response;if(latest?.response.error&&(latest.response.executionStatus==="not_started"||latest.response.executionStatus==="cancelled")){if(!executed)return{response:latest.response,completed:latest};const message2=`An earlier Mod tool attempt ran. A later attempt failed: ${latest.response.error.message}`;return{completed:executed,response:{...latest.response,executionStatus:executed.response.executionStatus,error:new Error(message2),resultDisplay:message2,contentLength:message2.length,responseParts:[{functionResponse:{id:request.callId,name:request.name,response:{error:message2}}}]}}}if(referenced&&!("deny"in answer)&&isDeepStrictEqual(answer.result,referenced.value.result)){return{response:{...referenced.completed.response,executionStatus:executed?.response.executionStatus??referenced.completed.response.executionStatus},completed:executed??referenced.completed}}const message="deny"in answer?`${executed?"The tool ran; a Mod withheld its result. ":"Tool denied by Mod. "}${answer.deny}`:void 0;const result="deny"in answer?{error:message}:record(answer.result)&&Object.entries(answer.result).every(([key,value])=>(key==="output"||key==="error")&&typeof value==="string")?answer.result:{output:typeof answer.result==="string"?answer.result:JSON.stringify(answer.result)};const text=JSON.stringify(result);const error=message?new Error(message):native?.error??(!("deny"in answer)&&answer.isError?new Error("Mod returned an error result."):void 0);const response={...native,callId:request.callId,responseParts:[{functionResponse:{id:request.callId,name:request.name,response:result}}],resultDisplay:text,contentLength:text.length,executionStatus:executed?.response.executionStatus??native?.executionStatus??"not_started",error,errorType:native?.errorType??(error?"execution_denied":void 0)};return{response,completed:executed??selected}}__name(executeModTool,"executeModTool");async function executeToolCall(config,toolCallRequest,abortSignal,options={}){const execution=options.modToolCall&&await modToolRequest(config,toolCallRequest);if(execution&&options.modToolCall){const{response,completed}=await executeModTool(toolCallRequest,execution,options.modToolCall,async(request,signal,check)=>{let completed2;await executeToolCall(config,request,signal,{...options,modToolCall:void 0,modToolCheck:check,recordToolResult:false,onAllToolCallsComplete:__name(async calls=>{completed2=calls[0]},"onAllToolCallsComplete")});if(!completed2)throw new Error("Mod native tool did not complete.");return completed2},abortSignal);if(completed)await options.onAllToolCallsComplete?.([{...completed,response}]);if(options.recordToolResult!==false)config.getChatRecordingService()?.recordToolResult(response.responseParts,{...response,status:completed?.status??(response.error?"error":"success")});return response}return new Promise((resolve,reject)=>{new CoreToolScheduler({config,modToolCheck:options.modToolCheck,chatRecordingService:options.recordToolResult===false?void 0:config.getChatRecordingService(),outputUpdateHandler:options.outputUpdateHandler,onAllToolCallsComplete:__name(async completedToolCalls=>{if(options.onAllToolCallsComplete){await options.onAllToolCallsComplete(completedToolCalls)}resolve(completedToolCalls[0].response)},"onAllToolCallsComplete"),onToolCallsUpdate:options.onToolCallsUpdate,onToolResultFullTurnModel:options.onToolResultFullTurnModel,getPreferredEditor:__name(()=>void 0,"getPreferredEditor"),onEditorClose:__name(()=>{},"onEditorClose")}).schedule(toolCallRequest,abortSignal,options.runtimeView).catch(reject)})}__name(executeToolCall,"executeToolCall");export{modToolRequest,executeModTool,executeToolCall};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2026 Qwen Team
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{cancelTask,checkReadiness,cleanTask,collectTask,listTasks,retryTask,runPlan}from"./chunk-FMDNFKEK.js";import{loadUndici}from"./chunk-XKSB7VTV.js";import{loadSettings}from"./chunk-E6XRNALG.js";import{collectProviderModelsForProtocol,getAuthTypeFromEnv,resolveCliGenerationConfig}from"./chunk-53CWA7N2.js";import{normalizeProxyUrl}from"./chunk-XUB4JKSR.js";import{isTlsVerificationDisabled}from"./chunk-E5XJBLSO.js";import{ignoreBrokenPipe,writeStderrLine,writeStdoutLine}from"./chunk-M4ECEHLX.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();async function resolveProxy(cliProxy,settingsProxy){const proxyUrl=resolveProxyUrl(cliProxy,settingsProxy);if(proxyUrl){const{EnvHttpProxyAgent,setGlobalDispatcher}=await loadUndici();setGlobalDispatcher(new EnvHttpProxyAgent({httpProxy:proxyUrl,httpsProxy:proxyUrl}))}return proxyUrl}__name(resolveProxy,"resolveProxy");function resolveProxyUrl(cliProxy,settingsProxy){return normalizeProxyUrl(cliProxy||settingsProxy||process.env["HTTPS_PROXY"]||process.env["https_proxy"]||process.env["HTTP_PROXY"]||process.env["http_proxy"])}__name(resolveProxyUrl,"resolveProxyUrl");var DEFAULT_BASE_URL="https://dashscope.aliyuncs.com/compatible-mode/v1";function resolveEndpoint(env=process.env,options={}){let settings=options.settings??loadSettings().merged;const batch=settings.batch;if(batch?.model||batch?.authType||batch?.baseUrl){if(!batch.model?.trim()){throw new Error("Set batch.model to a modelProviders model ID.")}if(batch.authType&&batch.authType!=="openai"){throw new Error('batch.authType must be "openai" for DashScope Batch.')}const matches=collectProviderModelsForProtocol(settings.modelProviders,settings.providerProtocol,"openai").filter(provider2=>provider2.id===batch.model&&(!batch.baseUrl||provider2.baseUrl===batch.baseUrl));if(matches.length!==1){throw new Error("batch.model must match exactly one chat-completions modelProviders entry; use batch.baseUrl to disambiguate duplicate IDs.")}const provider=matches[0];if(!provider.baseUrl||!provider.envKey||!env[provider.envKey]){throw new Error("The Batch provider needs baseUrl and an envKey with a non-empty value in settings.env or the environment.")}settings={...settings,model:{name:provider.id,baseUrl:provider.baseUrl},modelProviders:{openai:[provider]},security:{auth:{selectedType:"openai"}}};env={[provider.envKey]:env[provider.envKey]}}const selectedAuthType=settings.security?.auth?.selectedType??getAuthTypeFromEnv(env);if(selectedAuthType!=="openai"){throw new Error(`qwen batch needs an API key (auth type "openai") for a DashScope endpoint; current auth type is "${selectedAuthType??"none"}".`)}const{apiKey,baseUrl,model,warnings,authType,generationConfig}=resolveCliGenerationConfig({argv:{},settings,selectedAuthType,env});if(authType!=="openai"){throw new Error(`qwen batch needs a model on the OpenAI-compatible chat-completions wire; "${model||"the configured model"}" resolves to auth type "${authType??"none"}".`)}if(!apiKey){throw new Error("No API key found: set OPENAI_API_KEY or security.auth.apiKey.")}const warn=options.warn??(message=>writeStderrLine(`warning: ${message}`));for(const warning of warnings??[]){warn(warning)}return{apiKey,baseUrl:(baseUrl||DEFAULT_BASE_URL).replace(/\/+$/,""),model,generationConfig}}__name(resolveEndpoint,"resolveEndpoint");async function prepareEndpoint(env=process.env,cliOptions={}){if(cliOptions.insecure)process.env["QWEN_TLS_INSECURE"]="1";if(isTlsVerificationDisabled()&&process.env["NODE_TLS_REJECT_UNAUTHORIZED"]!=="0"){process.env["NODE_TLS_REJECT_UNAUTHORIZED"]="0";writeStderrLine("WARNING: TLS certificate verification is disabled (--insecure / QWEN_TLS_INSECURE); connections made by this command are vulnerable to man-in-the-middle attacks.")}await resolveProxy(cliOptions.proxy,loadSettings().merged.proxy);return resolveEndpoint(env)}__name(prepareEndpoint,"prepareEndpoint");var cliOptionsOf=__name(argv=>({proxy:argv["proxy"],insecure:argv["insecure"]}),"cliOptionsOf");async function run(fn){try{await fn()}catch(error){writeStderrLine(error instanceof Error?error.message:String(error));process.exitCode=1}await Promise.all([process.stdout,process.stderr].map(stream=>new Promise(resolve=>stream.write("",()=>resolve()))))}__name(run,"run");var LOCK_WAIT_MS=15e3;var workflowDeps=__name(ep=>({ep,cwd:process.cwd(),env:process.env,out:writeStdoutLine,err:writeStderrLine,lockWaitMs:LOCK_WAIT_MS}),"workflowDeps");var runWorkflowCommand={command:"run <plan>",describe:"Run an agent-prepared batch plan: assemble requests, submit, record the task",builder:__name(yargs=>yargs.positional("plan",{describe:"Plan JSON (usually written by the /batch-api skill): shared rules + source/target items",type:"string",demandOption:true}).option("dry-run",{describe:"Assemble and show items, frozen settings and the estimate without uploading; prints a snapshot digest",type:"boolean",default:false}).option("expect",{describe:"Submit only if the batch still matches this snapshot digest from --dry-run",type:"string"}).check(argv=>argv["dry-run"]&&argv["expect"]!==void 0?"--dry-run and --expect cannot be combined":true),"builder"),handler:__name(argv=>run(async()=>{await runPlan(workflowDeps(await prepareEndpoint(process.env,cliOptionsOf(argv))),argv["plan"],{dryRun:argv["dry-run"],expect:argv["expect"]})}),"handler")};var collectWorkflowCommand={command:"collect <task-id>",describe:"Collect a workflow task: reconcile, download, validate, and deliver results",builder:__name(yargs=>yargs.positional("task-id",{describe:"Task id printed by `qwen batch run`",type:"string",demandOption:true}).option("wait",{describe:"Poll (over HTTP, holding no lock) until the batch settles, then collect",type:"boolean",default:false}).option("timeout",{describe:"Seconds to wait with --wait before giving up (default: none)",type:"number"}).check(argv=>argv["timeout"]===void 0||Number.isFinite(argv["timeout"])&&argv["timeout"]>0?true:"--timeout must be a positive number of seconds"),"builder"),handler:__name(argv=>run(async()=>{await collectTask(workflowDeps(await prepareEndpoint(process.env,cliOptionsOf(argv))),argv["task-id"],{wait:argv["wait"],timeoutSeconds:argv["timeout"]})}),"handler")};var retryWorkflowCommand={command:"retry <task-id>",describe:"Resubmit only the failed items of a workflow task",builder:__name(yargs=>yargs.positional("task-id",{describe:"Task id",type:"string",demandOption:true}).option("max-output-tokens",{describe:"Output limit for the new attempt; required to resend items that were truncated",type:"number"}).check(argv=>argv["max-output-tokens"]===void 0||Number.isInteger(argv["max-output-tokens"])&&argv["max-output-tokens"]>0?true:"--max-output-tokens must be a positive integer"),"builder"),handler:__name(argv=>run(async()=>{await retryTask(workflowDeps(await prepareEndpoint(process.env,cliOptionsOf(argv))),argv["task-id"],{maxOutputTokens:argv["max-output-tokens"]})}),"handler")};var cleanWorkflowCommand={command:"clean <task-id>",describe:"Delete a workflow task's local record (cancels nothing; refuses while a batch may be running)",builder:__name(yargs=>yargs.positional("task-id",{describe:"Task id",type:"string",demandOption:true}).option("force",{describe:"Delete even if a batch may still be running or uncollected (it is not cancelled)",type:"boolean",default:false}),"builder"),handler:__name(argv=>run(async()=>{await cleanTask({env:process.env,out:writeStdoutLine,err:writeStderrLine,lockWaitMs:LOCK_WAIT_MS},argv["task-id"],{force:argv["force"]})}),"handler")};var checkWorkflowCommand={command:"check",describe:"Verify credentials and the Batch route, and show the settings a run would freeze (no billed request)",builder:__name(yargs=>yargs,"builder"),handler:__name(argv=>run(async()=>{await checkReadiness(workflowDeps(await prepareEndpoint(process.env,cliOptionsOf(argv))))}),"handler")};var cancelWorkflowCommand={command:"cancel <task-id>",describe:"Cancel a workflow task's active batch (already-completed requests are still billed)",builder:__name(yargs=>yargs.positional("task-id",{describe:"Task id",type:"string",demandOption:true}),"builder"),handler:__name(argv=>run(async()=>{await cancelTask(workflowDeps(await prepareEndpoint(process.env,cliOptionsOf(argv))),argv["task-id"])}),"handler")};var listWorkflowCommand={command:"list",describe:"List all recorded workflow tasks with their project",builder:__name(yargs=>yargs,"builder"),handler:__name(()=>run(async()=>{ignoreBrokenPipe();await listTasks({env:process.env,out:writeStdoutLine,err:writeStderrLine})}),"handler")};var batchCommand={command:"batch",describe:"Run many independent requests through the DashScope Batch API",builder:__name(yargs=>yargs.command(runWorkflowCommand).command(collectWorkflowCommand).command(retryWorkflowCommand).command(cancelWorkflowCommand).command(listWorkflowCommand).command(checkWorkflowCommand).command(cleanWorkflowCommand).demandCommand(1,"You need at least one command before continuing.").version(false),"builder"),handler:__name(()=>{},"handler")};export{resolveProxy,resolveProxyUrl,resolveEndpoint,prepareEndpoint,listWorkflowCommand,batchCommand};
3
+ import{cancelTask,checkReadiness,cleanTask,collectTask,listTasks,retryTask,runPlan}from"./chunk-FMDNFKEK.js";import{loadUndici}from"./chunk-XKSB7VTV.js";import{loadSettings}from"./chunk-AEX3XSTE.js";import{collectProviderModelsForProtocol,getAuthTypeFromEnv,resolveCliGenerationConfig}from"./chunk-D5H5GARR.js";import{normalizeProxyUrl}from"./chunk-3NR3JBMA.js";import{isTlsVerificationDisabled}from"./chunk-E5XJBLSO.js";import{ignoreBrokenPipe,writeStderrLine,writeStdoutLine}from"./chunk-M4ECEHLX.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();async function resolveProxy(cliProxy,settingsProxy){const proxyUrl=resolveProxyUrl(cliProxy,settingsProxy);if(proxyUrl){const{EnvHttpProxyAgent,setGlobalDispatcher}=await loadUndici();setGlobalDispatcher(new EnvHttpProxyAgent({httpProxy:proxyUrl,httpsProxy:proxyUrl}))}return proxyUrl}__name(resolveProxy,"resolveProxy");function resolveProxyUrl(cliProxy,settingsProxy){return normalizeProxyUrl(cliProxy||settingsProxy||process.env["HTTPS_PROXY"]||process.env["https_proxy"]||process.env["HTTP_PROXY"]||process.env["http_proxy"])}__name(resolveProxyUrl,"resolveProxyUrl");var DEFAULT_BASE_URL="https://dashscope.aliyuncs.com/compatible-mode/v1";function resolveEndpoint(env=process.env,options={}){let settings=options.settings??loadSettings().merged;const batch=settings.batch;if(batch?.model||batch?.authType||batch?.baseUrl){if(!batch.model?.trim()){throw new Error("Set batch.model to a modelProviders model ID.")}if(batch.authType&&batch.authType!=="openai"){throw new Error('batch.authType must be "openai" for DashScope Batch.')}const matches=collectProviderModelsForProtocol(settings.modelProviders,settings.providerProtocol,"openai").filter(provider2=>provider2.id===batch.model&&(!batch.baseUrl||provider2.baseUrl===batch.baseUrl));if(matches.length!==1){throw new Error("batch.model must match exactly one chat-completions modelProviders entry; use batch.baseUrl to disambiguate duplicate IDs.")}const provider=matches[0];if(!provider.baseUrl||!provider.envKey||!env[provider.envKey]){throw new Error("The Batch provider needs baseUrl and an envKey with a non-empty value in settings.env or the environment.")}settings={...settings,model:{name:provider.id,baseUrl:provider.baseUrl},modelProviders:{openai:[provider]},security:{auth:{selectedType:"openai"}}};env={[provider.envKey]:env[provider.envKey]}}const selectedAuthType=settings.security?.auth?.selectedType??getAuthTypeFromEnv(env);if(selectedAuthType!=="openai"){throw new Error(`qwen batch needs an API key (auth type "openai") for a DashScope endpoint; current auth type is "${selectedAuthType??"none"}".`)}const{apiKey,baseUrl,model,warnings,authType,generationConfig}=resolveCliGenerationConfig({argv:{},settings,selectedAuthType,env});if(authType!=="openai"){throw new Error(`qwen batch needs a model on the OpenAI-compatible chat-completions wire; "${model||"the configured model"}" resolves to auth type "${authType??"none"}".`)}if(!apiKey){throw new Error("No API key found: set OPENAI_API_KEY or security.auth.apiKey.")}const warn=options.warn??(message=>writeStderrLine(`warning: ${message}`));for(const warning of warnings??[]){warn(warning)}return{apiKey,baseUrl:(baseUrl||DEFAULT_BASE_URL).replace(/\/+$/,""),model,generationConfig}}__name(resolveEndpoint,"resolveEndpoint");async function prepareEndpoint(env=process.env,cliOptions={}){if(cliOptions.insecure)process.env["QWEN_TLS_INSECURE"]="1";if(isTlsVerificationDisabled()&&process.env["NODE_TLS_REJECT_UNAUTHORIZED"]!=="0"){process.env["NODE_TLS_REJECT_UNAUTHORIZED"]="0";writeStderrLine("WARNING: TLS certificate verification is disabled (--insecure / QWEN_TLS_INSECURE); connections made by this command are vulnerable to man-in-the-middle attacks.")}await resolveProxy(cliOptions.proxy,loadSettings().merged.proxy);return resolveEndpoint(env)}__name(prepareEndpoint,"prepareEndpoint");var cliOptionsOf=__name(argv=>({proxy:argv["proxy"],insecure:argv["insecure"]}),"cliOptionsOf");async function run(fn){try{await fn()}catch(error){writeStderrLine(error instanceof Error?error.message:String(error));process.exitCode=1}await Promise.all([process.stdout,process.stderr].map(stream=>new Promise(resolve=>stream.write("",()=>resolve()))))}__name(run,"run");var LOCK_WAIT_MS=15e3;var workflowDeps=__name(ep=>({ep,cwd:process.cwd(),env:process.env,out:writeStdoutLine,err:writeStderrLine,lockWaitMs:LOCK_WAIT_MS}),"workflowDeps");var runWorkflowCommand={command:"run <plan>",describe:"Run an agent-prepared batch plan: assemble requests, submit, record the task",builder:__name(yargs=>yargs.positional("plan",{describe:"Plan JSON (usually written by the /batch-api skill): shared rules + source/target items",type:"string",demandOption:true}).option("dry-run",{describe:"Assemble and show items, frozen settings and the estimate without uploading; prints a snapshot digest",type:"boolean",default:false}).option("expect",{describe:"Submit only if the batch still matches this snapshot digest from --dry-run",type:"string"}).check(argv=>argv["dry-run"]&&argv["expect"]!==void 0?"--dry-run and --expect cannot be combined":true),"builder"),handler:__name(argv=>run(async()=>{await runPlan(workflowDeps(await prepareEndpoint(process.env,cliOptionsOf(argv))),argv["plan"],{dryRun:argv["dry-run"],expect:argv["expect"]})}),"handler")};var collectWorkflowCommand={command:"collect <task-id>",describe:"Collect a workflow task: reconcile, download, validate, and deliver results",builder:__name(yargs=>yargs.positional("task-id",{describe:"Task id printed by `qwen batch run`",type:"string",demandOption:true}).option("wait",{describe:"Poll (over HTTP, holding no lock) until the batch settles, then collect",type:"boolean",default:false}).option("timeout",{describe:"Seconds to wait with --wait before giving up (default: none)",type:"number"}).check(argv=>argv["timeout"]===void 0||Number.isFinite(argv["timeout"])&&argv["timeout"]>0?true:"--timeout must be a positive number of seconds"),"builder"),handler:__name(argv=>run(async()=>{await collectTask(workflowDeps(await prepareEndpoint(process.env,cliOptionsOf(argv))),argv["task-id"],{wait:argv["wait"],timeoutSeconds:argv["timeout"]})}),"handler")};var retryWorkflowCommand={command:"retry <task-id>",describe:"Resubmit only the failed items of a workflow task",builder:__name(yargs=>yargs.positional("task-id",{describe:"Task id",type:"string",demandOption:true}).option("max-output-tokens",{describe:"Output limit for the new attempt; required to resend items that were truncated",type:"number"}).check(argv=>argv["max-output-tokens"]===void 0||Number.isInteger(argv["max-output-tokens"])&&argv["max-output-tokens"]>0?true:"--max-output-tokens must be a positive integer"),"builder"),handler:__name(argv=>run(async()=>{await retryTask(workflowDeps(await prepareEndpoint(process.env,cliOptionsOf(argv))),argv["task-id"],{maxOutputTokens:argv["max-output-tokens"]})}),"handler")};var cleanWorkflowCommand={command:"clean <task-id>",describe:"Delete a workflow task's local record (cancels nothing; refuses while a batch may be running)",builder:__name(yargs=>yargs.positional("task-id",{describe:"Task id",type:"string",demandOption:true}).option("force",{describe:"Delete even if a batch may still be running or uncollected (it is not cancelled)",type:"boolean",default:false}),"builder"),handler:__name(argv=>run(async()=>{await cleanTask({env:process.env,out:writeStdoutLine,err:writeStderrLine,lockWaitMs:LOCK_WAIT_MS},argv["task-id"],{force:argv["force"]})}),"handler")};var checkWorkflowCommand={command:"check",describe:"Verify credentials and the Batch route, and show the settings a run would freeze (no billed request)",builder:__name(yargs=>yargs,"builder"),handler:__name(argv=>run(async()=>{await checkReadiness(workflowDeps(await prepareEndpoint(process.env,cliOptionsOf(argv))))}),"handler")};var cancelWorkflowCommand={command:"cancel <task-id>",describe:"Cancel a workflow task's active batch (already-completed requests are still billed)",builder:__name(yargs=>yargs.positional("task-id",{describe:"Task id",type:"string",demandOption:true}),"builder"),handler:__name(argv=>run(async()=>{await cancelTask(workflowDeps(await prepareEndpoint(process.env,cliOptionsOf(argv))),argv["task-id"])}),"handler")};var listWorkflowCommand={command:"list",describe:"List all recorded workflow tasks with their project",builder:__name(yargs=>yargs,"builder"),handler:__name(()=>run(async()=>{ignoreBrokenPipe();await listTasks({env:process.env,out:writeStdoutLine,err:writeStderrLine})}),"handler")};var batchCommand={command:"batch",describe:"Run many independent requests through the DashScope Batch API",builder:__name(yargs=>yargs.command(runWorkflowCommand).command(collectWorkflowCommand).command(retryWorkflowCommand).command(cancelWorkflowCommand).command(listWorkflowCommand).command(checkWorkflowCommand).command(cleanWorkflowCommand).demandCommand(1,"You need at least one command before continuing.").version(false),"builder"),handler:__name(()=>{},"handler")};export{resolveProxy,resolveProxyUrl,resolveEndpoint,prepareEndpoint,listWorkflowCommand,batchCommand};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Qwen Team
@@ -1,10 +1,10 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{appEvents}from"./chunk-MPDGSR2S.js";import{loadUndici}from"./chunk-XKSB7VTV.js";import{CUSTOM_SANDBOX_IMAGE_ENV_VAR,HOST_UPDATE_RELAUNCH_ENV_VAR,SKIP_UPDATE_CHECK_ENV_VAR,requestUpdateOnExit}from"./chunk-QDQQFQB4.js";import{IdeClient}from"./chunk-XUB4JKSR.js";import{getAllProviderBaseUrls}from"./chunk-N3AKLLXG.js";import{detectRuntime,getOrCreateSharedDispatcher,preloadRuntimeFetchModule,redactProxyCredentials}from"./chunk-E5XJBLSO.js";import{initializeTelemetry}from"./chunk-UFRESHR3.js";import{recordStartupEvent}from"./chunk-H4XFFVZ2.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();var debugLogger=createDebugLogger("PRECONNECT");var preconnectFired=false;var preconnectInFlight;var DEFAULT_BASE_URLS={openai:"https://api.openai.com","qwen-oauth":"https://coding.dashscope.aliyuncs.com",anthropic:"https://api.anthropic.com",dashscope:"https://dashscope.aliyuncs.com"};var ALL_DEFAULT_URLS=[...Object.values(DEFAULT_BASE_URLS),...getAllProviderBaseUrls()];function shouldSkipPreconnect(){if(process.env["NODE_EXTRA_CA_CERTS"]){debugLogger.debug("Skipping preconnect: custom CA certificate configured");return true}return false}__name(shouldSkipPreconnect,"shouldSkipPreconnect");function isInSandboxMode(){return process.env["SANDBOX"]!==void 0}__name(isInSandboxMode,"isInSandboxMode");function isDefaultBaseUrl(baseUrl){const normalizedInput=baseUrl.toLowerCase().replace(/^https?:\/\//,"").replace(/\/+$/,"");return ALL_DEFAULT_URLS.some(defaultUrl=>{const normalizedDefault=defaultUrl.toLowerCase().replace(/^https?:\/\//,"").replace(/\/+$/,"");return normalizedInput===normalizedDefault||normalizedInput.startsWith(normalizedDefault+"/")})}__name(isDefaultBaseUrl,"isDefaultBaseUrl");function getPreconnectTargetUrl(authType,resolvedBaseUrl){if(resolvedBaseUrl&&/^https?:\/\//i.test(resolvedBaseUrl)){if(isDefaultBaseUrl(resolvedBaseUrl)){return resolvedBaseUrl}debugLogger.debug("Skipping preconnect: resolved baseUrl is not a default URL");return void 0}if(authType&&DEFAULT_BASE_URLS[authType]){return DEFAULT_BASE_URLS[authType]}return void 0}__name(getPreconnectTargetUrl,"getPreconnectTargetUrl");function preconnectApi(authType,options={}){if(preconnectFired){return}if(process.env["QWEN_CODE_DISABLE_PRECONNECT"]==="1"){debugLogger.debug("Preconnect disabled by environment variable");preconnectFired=true;return}if(isInSandboxMode()){debugLogger.debug("Skipping preconnect: sandbox mode detected");preconnectFired=true;return}if(shouldSkipPreconnect()){preconnectFired=true;return}if(detectRuntime()!=="node"){debugLogger.debug("Skipping preconnect: unsupported runtime");preconnectFired=true;return}if(!options.proxy){debugLogger.debug("Skipping preconnect dispatcher: no proxy configured");return}const proxy=options.proxy;const targetUrl=getPreconnectTargetUrl(authType,options.resolvedBaseUrl);if(!targetUrl){debugLogger.debug("No target URL for preconnect");return}preconnectFired=true;debugLogger.debug(`Preconnecting to: ${targetUrl}`);preconnectInFlight=(async()=>{await preloadRuntimeFetchModule();const dispatcher=getOrCreateSharedDispatcher(proxy);const{fetch:undiciFetch}=await loadUndici();await undiciFetch(targetUrl,{method:"HEAD",signal:AbortSignal.timeout(5e3),headers:{"User-Agent":"QwenCode-Preconnect/1.0"},dispatcher});debugLogger.debug("Preconnect completed")})().catch(error=>{const redactedError=redactProxyCredentials(String(error));debugLogger.debug(`Preconnect failed (ignored): ${redactedError}`)})}__name(preconnectApi,"preconnectApi");var debugLogger2=createDebugLogger("STARTUP_PREFETCH");var DEFERRED_IDE_CONNECT_TIMEOUT_MS=15e3;var earlyStarted=new WeakSet;var postRenderStarted=new WeakSet;function withTimeout(promise,name,timeoutMs,onTimeout=()=>{}){let timeoutId;let timedOut=false;const runTimeoutCleanup=__name(()=>{void Promise.resolve().then(onTimeout).catch(err=>{debugLogger2.debug(`${name} timeout cleanup failed:`,err)})},"runTimeoutCleanup");const timeout=new Promise((_,reject)=>{timeoutId=setTimeout(()=>{timedOut=true;runTimeoutCleanup();reject(new Error(`${name} timed out after ${timeoutMs}ms`))},timeoutMs);timeoutId.unref?.()});void promise.then(()=>{if(timedOut){runTimeoutCleanup()}},err=>{if(timedOut){debugLogger2.debug(`${name} underlying error after timeout:`,err)}});return Promise.race([promise,timeout]).finally(()=>{if(timeoutId){clearTimeout(timeoutId)}})}__name(withTimeout,"withTimeout");function runDeferredTask(name,task){recordStartupEvent("startup_prefetch_started",{name});void Promise.resolve().then(task).then(()=>{recordStartupEvent("startup_prefetch_completed",{name})}).catch(err=>{recordStartupEvent("startup_prefetch_failed",{name});debugLogger2.warn(`${name} failed:`,err)})}__name(runDeferredTask,"runDeferredTask");async function disconnectIdeAfterDeferredTimeout(){const ideClient=await IdeClient.getInstance();await ideClient.disconnect()}__name(disconnectIdeAfterDeferredTimeout,"disconnectIdeAfterDeferredTimeout");function startEarlyStartupPrefetches(config){if(earlyStarted.has(config))return;earlyStarted.add(config);try{const modelsConfig=config.getModelsConfig();const authType=modelsConfig.getCurrentAuthType();const resolvedBaseUrl=modelsConfig.getGenerationConfig().baseUrl;const proxy=config.getProxy();preconnectApi(authType,{resolvedBaseUrl,proxy})}catch(error){debugLogger2.debug(`Preconnect skipped due to error getting authType: ${error}`)}}__name(startEarlyStartupPrefetches,"startEarlyStartupPrefetches");var UPDATE_CHECK_DELAY_MS=3e3;function startPostRenderPrefetches(config,settings,options={}){if(postRenderStarted.has(config))return;postRenderStarted.add(config);if(settings.merged.general?.enableAutoUpdate!==false&&process.env[SKIP_UPDATE_CHECK_ENV_VAR]!=="true"&&!process.env[CUSTOM_SANDBOX_IMAGE_ENV_VAR]){runDeferredTask("update_check",async()=>{await new Promise(resolve=>{setTimeout(resolve,UPDATE_CHECK_DELAY_MS).unref?.()});const[{checkForUpdatesDetailed,describeUpdateCheckFailure},{handleAutoUpdate},{getInstallationInfo},{updateEventEmitter},{t}]=await Promise.all([import("./updateCheck-2QOAKEIH.js"),import("./handleAutoUpdate-FD7QAG2R.js"),import("./installationInfo-B337C7R4.js"),import("./updateEventEmitter-HCGBOCP2.js"),import("./i18n-TI3ZCEHR.js")]);const updateCheckSkippedMessage=__name(error=>t("Update check skipped ({{reason}}) \u2014 run /update to retry.",{reason:describeUpdateCheckFailure(error)}),"updateCheckSkippedMessage");try{const result=await checkForUpdatesDetailed();if(result.status==="update"){const projectRoot=config.getProjectRoot();const hostUpdateRelaunch=process.env[HOST_UPDATE_RELAUNCH_ENV_VAR];if(hostUpdateRelaunch==="true"){updateEventEmitter.emit("update-info",{message:`${result.info.message}
3
+ import{appEvents}from"./chunk-N3YWQWSR.js";import{loadUndici}from"./chunk-XKSB7VTV.js";import{CUSTOM_SANDBOX_IMAGE_ENV_VAR,HOST_UPDATE_RELAUNCH_ENV_VAR,SKIP_UPDATE_CHECK_ENV_VAR,requestUpdateOnExit}from"./chunk-LBAINHIN.js";import{IdeClient}from"./chunk-3NR3JBMA.js";import{getAllProviderBaseUrls}from"./chunk-N3AKLLXG.js";import{detectRuntime,getOrCreateSharedDispatcher,preloadRuntimeFetchModule,redactProxyCredentials}from"./chunk-E5XJBLSO.js";import{initializeTelemetry}from"./chunk-UFRESHR3.js";import{recordStartupEvent}from"./chunk-H4XFFVZ2.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();var debugLogger=createDebugLogger("PRECONNECT");var preconnectFired=false;var preconnectInFlight;var DEFAULT_BASE_URLS={openai:"https://api.openai.com","qwen-oauth":"https://coding.dashscope.aliyuncs.com",anthropic:"https://api.anthropic.com",dashscope:"https://dashscope.aliyuncs.com"};var ALL_DEFAULT_URLS=[...Object.values(DEFAULT_BASE_URLS),...getAllProviderBaseUrls()];function shouldSkipPreconnect(){if(process.env["NODE_EXTRA_CA_CERTS"]){debugLogger.debug("Skipping preconnect: custom CA certificate configured");return true}return false}__name(shouldSkipPreconnect,"shouldSkipPreconnect");function isInSandboxMode(){return process.env["SANDBOX"]!==void 0}__name(isInSandboxMode,"isInSandboxMode");function isDefaultBaseUrl(baseUrl){const normalizedInput=baseUrl.toLowerCase().replace(/^https?:\/\//,"").replace(/\/+$/,"");return ALL_DEFAULT_URLS.some(defaultUrl=>{const normalizedDefault=defaultUrl.toLowerCase().replace(/^https?:\/\//,"").replace(/\/+$/,"");return normalizedInput===normalizedDefault||normalizedInput.startsWith(normalizedDefault+"/")})}__name(isDefaultBaseUrl,"isDefaultBaseUrl");function getPreconnectTargetUrl(authType,resolvedBaseUrl){if(resolvedBaseUrl&&/^https?:\/\//i.test(resolvedBaseUrl)){if(isDefaultBaseUrl(resolvedBaseUrl)){return resolvedBaseUrl}debugLogger.debug("Skipping preconnect: resolved baseUrl is not a default URL");return void 0}if(authType&&DEFAULT_BASE_URLS[authType]){return DEFAULT_BASE_URLS[authType]}return void 0}__name(getPreconnectTargetUrl,"getPreconnectTargetUrl");function preconnectApi(authType,options={}){if(preconnectFired){return}if(process.env["QWEN_CODE_DISABLE_PRECONNECT"]==="1"){debugLogger.debug("Preconnect disabled by environment variable");preconnectFired=true;return}if(isInSandboxMode()){debugLogger.debug("Skipping preconnect: sandbox mode detected");preconnectFired=true;return}if(shouldSkipPreconnect()){preconnectFired=true;return}if(detectRuntime()!=="node"){debugLogger.debug("Skipping preconnect: unsupported runtime");preconnectFired=true;return}if(!options.proxy){debugLogger.debug("Skipping preconnect dispatcher: no proxy configured");return}const proxy=options.proxy;const targetUrl=getPreconnectTargetUrl(authType,options.resolvedBaseUrl);if(!targetUrl){debugLogger.debug("No target URL for preconnect");return}preconnectFired=true;debugLogger.debug(`Preconnecting to: ${targetUrl}`);preconnectInFlight=(async()=>{await preloadRuntimeFetchModule();const dispatcher=getOrCreateSharedDispatcher(proxy);const{fetch:undiciFetch}=await loadUndici();await undiciFetch(targetUrl,{method:"HEAD",signal:AbortSignal.timeout(5e3),headers:{"User-Agent":"QwenCode-Preconnect/1.0"},dispatcher});debugLogger.debug("Preconnect completed")})().catch(error=>{const redactedError=redactProxyCredentials(String(error));debugLogger.debug(`Preconnect failed (ignored): ${redactedError}`)})}__name(preconnectApi,"preconnectApi");var debugLogger2=createDebugLogger("STARTUP_PREFETCH");var DEFERRED_IDE_CONNECT_TIMEOUT_MS=15e3;var earlyStarted=new WeakSet;var postRenderStarted=new WeakSet;function withTimeout(promise,name,timeoutMs,onTimeout=()=>{}){let timeoutId;let timedOut=false;const runTimeoutCleanup=__name(()=>{void Promise.resolve().then(onTimeout).catch(err=>{debugLogger2.debug(`${name} timeout cleanup failed:`,err)})},"runTimeoutCleanup");const timeout=new Promise((_,reject)=>{timeoutId=setTimeout(()=>{timedOut=true;runTimeoutCleanup();reject(new Error(`${name} timed out after ${timeoutMs}ms`))},timeoutMs);timeoutId.unref?.()});void promise.then(()=>{if(timedOut){runTimeoutCleanup()}},err=>{if(timedOut){debugLogger2.debug(`${name} underlying error after timeout:`,err)}});return Promise.race([promise,timeout]).finally(()=>{if(timeoutId){clearTimeout(timeoutId)}})}__name(withTimeout,"withTimeout");function runDeferredTask(name,task){recordStartupEvent("startup_prefetch_started",{name});void Promise.resolve().then(task).then(()=>{recordStartupEvent("startup_prefetch_completed",{name})}).catch(err=>{recordStartupEvent("startup_prefetch_failed",{name});debugLogger2.warn(`${name} failed:`,err)})}__name(runDeferredTask,"runDeferredTask");async function disconnectIdeAfterDeferredTimeout(){const ideClient=await IdeClient.getInstance();await ideClient.disconnect()}__name(disconnectIdeAfterDeferredTimeout,"disconnectIdeAfterDeferredTimeout");function startEarlyStartupPrefetches(config){if(earlyStarted.has(config))return;earlyStarted.add(config);try{const modelsConfig=config.getModelsConfig();const authType=modelsConfig.getCurrentAuthType();const resolvedBaseUrl=modelsConfig.getGenerationConfig().baseUrl;const proxy=config.getProxy();preconnectApi(authType,{resolvedBaseUrl,proxy})}catch(error){debugLogger2.debug(`Preconnect skipped due to error getting authType: ${error}`)}}__name(startEarlyStartupPrefetches,"startEarlyStartupPrefetches");var UPDATE_CHECK_DELAY_MS=3e3;function startPostRenderPrefetches(config,settings,options={}){if(postRenderStarted.has(config))return;postRenderStarted.add(config);if(settings.merged.general?.enableAutoUpdate!==false&&process.env[SKIP_UPDATE_CHECK_ENV_VAR]!=="true"&&!process.env[CUSTOM_SANDBOX_IMAGE_ENV_VAR]){runDeferredTask("update_check",async()=>{await new Promise(resolve=>{setTimeout(resolve,UPDATE_CHECK_DELAY_MS).unref?.()});const[{checkForUpdatesDetailed,describeUpdateCheckFailure},{handleAutoUpdate},{getInstallationInfo},{updateEventEmitter},{t}]=await Promise.all([import("./updateCheck-UBLS3LUD.js"),import("./handleAutoUpdate-RS6Y2IWS.js"),import("./installationInfo-EPURVILN.js"),import("./updateEventEmitter-HCGBOCP2.js"),import("./i18n-WWZD25J5.js")]);const updateCheckSkippedMessage=__name(error=>t("Update check skipped ({{reason}}) \u2014 run /update to retry.",{reason:describeUpdateCheckFailure(error)}),"updateCheckSkippedMessage");try{const result=await checkForUpdatesDetailed();if(result.status==="update"){const projectRoot=config.getProjectRoot();const hostUpdateRelaunch=process.env[HOST_UPDATE_RELAUNCH_ENV_VAR];if(hostUpdateRelaunch==="true"){updateEventEmitter.emit("update-info",{message:`${result.info.message}
4
4
  ${t("Run /update to install the update on the host.")}`});return}if(hostUpdateRelaunch==="false"){updateEventEmitter.emit("update-info",{message:`${result.info.message}
5
5
  ${t("Update Qwen Code on the host, then restart the sandbox.")}`});return}const installationInfo=getInstallationInfo(projectRoot,true);if(installationInfo.packageManager==="npm"){void handleAutoUpdate(result.info,settings,projectRoot);return}if(installationInfo.updateCommand||installationInfo.isStandalone&&installationInfo.standaloneDir){if(requestUpdateOnExit()){updateEventEmitter.emit("update-info",{message:`${result.info.message}
6
6
  ${t("The update will be installed after you exit this session.")}`})}else{updateEventEmitter.emit("update-info",{message:`${result.info.message}
7
- ${t("Run /update to install the update.")}`})}}else{void handleAutoUpdate(result.info,settings,projectRoot)}}else if(result.status==="error"){updateEventEmitter.emit("update-failed",{message:updateCheckSkippedMessage(result.error),severity:"warning"})}}catch(error){updateEventEmitter.emit("update-failed",{message:updateCheckSkippedMessage(error),severity:"warning"});throw error}})}if(options.connectIde&&config.getIdeMode()){runDeferredTask("ide_connect",async()=>{appEvents.emit("startup-ide-connection-status-changed",{state:"connecting"});try{const{connectIdeForStartup}=await import("./initializer-SB7P3LRU.js");await withTimeout(connectIdeForStartup(config),"ide_connect",DEFERRED_IDE_CONNECT_TIMEOUT_MS,disconnectIdeAfterDeferredTimeout);appEvents.emit("startup-ide-connection-status-changed",{state:"connected"})}catch(err){appEvents.emit("startup-ide-connection-status-changed",{state:"failed",message:err instanceof Error?err.message:String(err)});throw err}})}if(options.initializeTelemetry){runDeferredTask("telemetry_init",()=>initializeTelemetry(config))}if(config.isInteractive()&&settings.merged.general?.batchAutoCollect!==false){runDeferredTask("batch_auto_collect",async()=>{const[{startBatchAutoCollect},{resolveEndpoint},{updateEventEmitter}]=await Promise.all([import("./batch-auto-collect-SXF3W75V.js"),import("./batch-AIMBHUMX.js"),import("./updateEventEmitter-HCGBOCP2.js")]);startBatchAutoCollect({projectRoot:config.getWorkingDir(),notify:__name(message=>updateEventEmitter.emit("update-info",{message}),"notify"),resolveEndpoint:__name(()=>resolveEndpoint(process.env,{settings:settings.merged,warn:__name(message=>debugLogger2.debug(message),"warn")}),"resolveEndpoint"),log:__name(message=>debugLogger2.debug(message),"log")})})}if(config.isInteractive()){runDeferredTask("background_housekeeping",async()=>{const{startBackgroundHousekeeping}=await import("./scheduler-ELSUH4GZ.js");startBackgroundHousekeeping(config,settings)})}}__name(startPostRenderPrefetches,"startPostRenderPrefetches");export{startEarlyStartupPrefetches,startPostRenderPrefetches};
7
+ ${t("Run /update to install the update.")}`})}}else{void handleAutoUpdate(result.info,settings,projectRoot)}}else if(result.status==="error"){updateEventEmitter.emit("update-failed",{message:updateCheckSkippedMessage(result.error),severity:"warning"})}}catch(error){updateEventEmitter.emit("update-failed",{message:updateCheckSkippedMessage(error),severity:"warning"});throw error}})}if(options.connectIde&&config.getIdeMode()){runDeferredTask("ide_connect",async()=>{appEvents.emit("startup-ide-connection-status-changed",{state:"connecting"});try{const{connectIdeForStartup}=await import("./initializer-YGR4YXAM.js");await withTimeout(connectIdeForStartup(config),"ide_connect",DEFERRED_IDE_CONNECT_TIMEOUT_MS,disconnectIdeAfterDeferredTimeout);appEvents.emit("startup-ide-connection-status-changed",{state:"connected"})}catch(err){appEvents.emit("startup-ide-connection-status-changed",{state:"failed",message:err instanceof Error?err.message:String(err)});throw err}})}if(options.initializeTelemetry){runDeferredTask("telemetry_init",()=>initializeTelemetry(config))}if(config.isInteractive()&&settings.merged.general?.batchAutoCollect!==false){runDeferredTask("batch_auto_collect",async()=>{const[{startBatchAutoCollect},{resolveEndpoint},{updateEventEmitter}]=await Promise.all([import("./batch-auto-collect-SXF3W75V.js"),import("./batch-GCEHGR5P.js"),import("./updateEventEmitter-HCGBOCP2.js")]);startBatchAutoCollect({projectRoot:config.getWorkingDir(),notify:__name(message=>updateEventEmitter.emit("update-info",{message}),"notify"),resolveEndpoint:__name(()=>resolveEndpoint(process.env,{settings:settings.merged,warn:__name(message=>debugLogger2.debug(message),"warn")}),"resolveEndpoint"),log:__name(message=>debugLogger2.debug(message),"log")})})}if(config.isInteractive()){runDeferredTask("background_housekeeping",async()=>{const{startBackgroundHousekeeping}=await import("./scheduler-4ZZA357S.js");startBackgroundHousekeeping(config,settings)})}}__name(startPostRenderPrefetches,"startPostRenderPrefetches");export{startEarlyStartupPrefetches,startPostRenderPrefetches};
8
8
  /**
9
9
  * @license
10
10
  * Copyright 2026 Qwen Team
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{buildTrustPrecedenceRules,resolveTrustDecision,resolveTrustRule}from"./chunk-EIPLDYEY.js";import{arePathsEquivalent,getPathComparisonVariants}from"./chunk-IDXJIDME.js";import{ideContextStore}from"./chunk-XUB4JKSR.js";import{atomicWriteFileSync}from"./chunk-2GF3E5MI.js";import{writeStderrLine}from"./chunk-M4ECEHLX.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{FatalConfigError,getErrorMessage}from"./chunk-E7MYPQGV.js";import{require_proper_lockfile}from"./chunk-YIW3H46P.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import*as fs4 from"node:fs";import*as path3 from"node:path";init_esbuild_shims();import*as fs2 from"node:fs";import{isDeepStrictEqual}from"node:util";init_esbuild_shims();init_esbuild_shims();init_esbuild_shims();function createScanner(text,ignoreTrivia=false){const len=text.length;let pos=0,value="",tokenOffset=0,token=16,lineNumber=0,lineStartOffset=0,tokenLineStartOffset=0,prevTokenLineStartOffset=0,scanError=0;function scanHexDigits(count,exact){let digits=0;let value2=0;while(digits<count||!exact){let ch=text.charCodeAt(pos);if(ch>=48&&ch<=57){value2=value2*16+ch-48}else if(ch>=65&&ch<=70){value2=value2*16+ch-65+10}else if(ch>=97&&ch<=102){value2=value2*16+ch-97+10}else{break}pos++;digits++}if(digits<count){value2=-1}return value2}__name(scanHexDigits,"scanHexDigits");function setPosition(newPosition){pos=newPosition;value="";tokenOffset=0;token=16;scanError=0}__name(setPosition,"setPosition");function scanNumber(){let start=pos;if(text.charCodeAt(pos)===48){pos++}else{pos++;while(pos<text.length&&isDigit(text.charCodeAt(pos))){pos++}}if(pos<text.length&&text.charCodeAt(pos)===46){pos++;if(pos<text.length&&isDigit(text.charCodeAt(pos))){pos++;while(pos<text.length&&isDigit(text.charCodeAt(pos))){pos++}}else{scanError=3;return text.substring(start,pos)}}let end=pos;if(pos<text.length&&(text.charCodeAt(pos)===69||text.charCodeAt(pos)===101)){pos++;if(pos<text.length&&text.charCodeAt(pos)===43||text.charCodeAt(pos)===45){pos++}if(pos<text.length&&isDigit(text.charCodeAt(pos))){pos++;while(pos<text.length&&isDigit(text.charCodeAt(pos))){pos++}end=pos}else{scanError=3}}return text.substring(start,end)}__name(scanNumber,"scanNumber");function scanString(){let result="",start=pos;while(true){if(pos>=len){result+=text.substring(start,pos);scanError=2;break}const ch=text.charCodeAt(pos);if(ch===34){result+=text.substring(start,pos);pos++;break}if(ch===92){result+=text.substring(start,pos);pos++;if(pos>=len){scanError=2;break}const ch2=text.charCodeAt(pos++);switch(ch2){case 34:result+='"';break;case 92:result+="\\";break;case 47:result+="/";break;case 98:result+="\b";break;case 102:result+="\f";break;case 110:result+="\n";break;case 114:result+="\r";break;case 116:result+=" ";break;case 117:const ch3=scanHexDigits(4,true);if(ch3>=0){result+=String.fromCharCode(ch3)}else{scanError=4}break;default:scanError=5}start=pos;continue}if(ch>=0&&ch<=31){if(isLineBreak(ch)){result+=text.substring(start,pos);scanError=2;break}else{scanError=6}}pos++}return result}__name(scanString,"scanString");function scanNext(){value="";scanError=0;tokenOffset=pos;lineStartOffset=lineNumber;prevTokenLineStartOffset=tokenLineStartOffset;if(pos>=len){tokenOffset=len;return token=17}let code=text.charCodeAt(pos);if(isWhiteSpace(code)){do{pos++;value+=String.fromCharCode(code);code=text.charCodeAt(pos)}while(isWhiteSpace(code));return token=15}if(isLineBreak(code)){pos++;value+=String.fromCharCode(code);if(code===13&&text.charCodeAt(pos)===10){pos++;value+="\n"}lineNumber++;tokenLineStartOffset=pos;return token=14}switch(code){case 123:pos++;return token=1;case 125:pos++;return token=2;case 91:pos++;return token=3;case 93:pos++;return token=4;case 58:pos++;return token=6;case 44:pos++;return token=5;case 34:pos++;value=scanString();return token=10;case 47:const start=pos-1;if(text.charCodeAt(pos+1)===47){pos+=2;while(pos<len){if(isLineBreak(text.charCodeAt(pos))){break}pos++}value=text.substring(start,pos);return token=12}if(text.charCodeAt(pos+1)===42){pos+=2;const safeLength=len-1;let commentClosed=false;while(pos<safeLength){const ch=text.charCodeAt(pos);if(ch===42&&text.charCodeAt(pos+1)===47){pos+=2;commentClosed=true;break}pos++;if(isLineBreak(ch)){if(ch===13&&text.charCodeAt(pos)===10){pos++}lineNumber++;tokenLineStartOffset=pos}}if(!commentClosed){pos++;scanError=1}value=text.substring(start,pos);return token=13}value+=String.fromCharCode(code);pos++;return token=16;case 45:value+=String.fromCharCode(code);pos++;if(pos===len||!isDigit(text.charCodeAt(pos))){return token=16}case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:value+=scanNumber();return token=11;default:while(pos<len&&isUnknownContentCharacter(code)){pos++;code=text.charCodeAt(pos)}if(tokenOffset!==pos){value=text.substring(tokenOffset,pos);switch(value){case"true":return token=8;case"false":return token=9;case"null":return token=7}return token=16}value+=String.fromCharCode(code);pos++;return token=16}}__name(scanNext,"scanNext");function isUnknownContentCharacter(code){if(isWhiteSpace(code)||isLineBreak(code)){return false}switch(code){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return false}return true}__name(isUnknownContentCharacter,"isUnknownContentCharacter");function scanNextNonTrivia(){let result;do{result=scanNext()}while(result>=12&&result<=15);return result}__name(scanNextNonTrivia,"scanNextNonTrivia");return{setPosition,getPosition:__name(()=>pos,"getPosition"),scan:ignoreTrivia?scanNextNonTrivia:scanNext,getToken:__name(()=>token,"getToken"),getTokenValue:__name(()=>value,"getTokenValue"),getTokenOffset:__name(()=>tokenOffset,"getTokenOffset"),getTokenLength:__name(()=>pos-tokenOffset,"getTokenLength"),getTokenStartLine:__name(()=>lineStartOffset,"getTokenStartLine"),getTokenStartCharacter:__name(()=>tokenOffset-prevTokenLineStartOffset,"getTokenStartCharacter"),getTokenError:__name(()=>scanError,"getTokenError")}}__name(createScanner,"createScanner");function isWhiteSpace(ch){return ch===32||ch===9}__name(isWhiteSpace,"isWhiteSpace");function isLineBreak(ch){return ch===10||ch===13}__name(isLineBreak,"isLineBreak");function isDigit(ch){return ch>=48&&ch<=57}__name(isDigit,"isDigit");var CharacterCodes;(function(CharacterCodes2){CharacterCodes2[CharacterCodes2["lineFeed"]=10]="lineFeed";CharacterCodes2[CharacterCodes2["carriageReturn"]=13]="carriageReturn";CharacterCodes2[CharacterCodes2["space"]=32]="space";CharacterCodes2[CharacterCodes2["_0"]=48]="_0";CharacterCodes2[CharacterCodes2["_1"]=49]="_1";CharacterCodes2[CharacterCodes2["_2"]=50]="_2";CharacterCodes2[CharacterCodes2["_3"]=51]="_3";CharacterCodes2[CharacterCodes2["_4"]=52]="_4";CharacterCodes2[CharacterCodes2["_5"]=53]="_5";CharacterCodes2[CharacterCodes2["_6"]=54]="_6";CharacterCodes2[CharacterCodes2["_7"]=55]="_7";CharacterCodes2[CharacterCodes2["_8"]=56]="_8";CharacterCodes2[CharacterCodes2["_9"]=57]="_9";CharacterCodes2[CharacterCodes2["a"]=97]="a";CharacterCodes2[CharacterCodes2["b"]=98]="b";CharacterCodes2[CharacterCodes2["c"]=99]="c";CharacterCodes2[CharacterCodes2["d"]=100]="d";CharacterCodes2[CharacterCodes2["e"]=101]="e";CharacterCodes2[CharacterCodes2["f"]=102]="f";CharacterCodes2[CharacterCodes2["g"]=103]="g";CharacterCodes2[CharacterCodes2["h"]=104]="h";CharacterCodes2[CharacterCodes2["i"]=105]="i";CharacterCodes2[CharacterCodes2["j"]=106]="j";CharacterCodes2[CharacterCodes2["k"]=107]="k";CharacterCodes2[CharacterCodes2["l"]=108]="l";CharacterCodes2[CharacterCodes2["m"]=109]="m";CharacterCodes2[CharacterCodes2["n"]=110]="n";CharacterCodes2[CharacterCodes2["o"]=111]="o";CharacterCodes2[CharacterCodes2["p"]=112]="p";CharacterCodes2[CharacterCodes2["q"]=113]="q";CharacterCodes2[CharacterCodes2["r"]=114]="r";CharacterCodes2[CharacterCodes2["s"]=115]="s";CharacterCodes2[CharacterCodes2["t"]=116]="t";CharacterCodes2[CharacterCodes2["u"]=117]="u";CharacterCodes2[CharacterCodes2["v"]=118]="v";CharacterCodes2[CharacterCodes2["w"]=119]="w";CharacterCodes2[CharacterCodes2["x"]=120]="x";CharacterCodes2[CharacterCodes2["y"]=121]="y";CharacterCodes2[CharacterCodes2["z"]=122]="z";CharacterCodes2[CharacterCodes2["A"]=65]="A";CharacterCodes2[CharacterCodes2["B"]=66]="B";CharacterCodes2[CharacterCodes2["C"]=67]="C";CharacterCodes2[CharacterCodes2["D"]=68]="D";CharacterCodes2[CharacterCodes2["E"]=69]="E";CharacterCodes2[CharacterCodes2["F"]=70]="F";CharacterCodes2[CharacterCodes2["G"]=71]="G";CharacterCodes2[CharacterCodes2["H"]=72]="H";CharacterCodes2[CharacterCodes2["I"]=73]="I";CharacterCodes2[CharacterCodes2["J"]=74]="J";CharacterCodes2[CharacterCodes2["K"]=75]="K";CharacterCodes2[CharacterCodes2["L"]=76]="L";CharacterCodes2[CharacterCodes2["M"]=77]="M";CharacterCodes2[CharacterCodes2["N"]=78]="N";CharacterCodes2[CharacterCodes2["O"]=79]="O";CharacterCodes2[CharacterCodes2["P"]=80]="P";CharacterCodes2[CharacterCodes2["Q"]=81]="Q";CharacterCodes2[CharacterCodes2["R"]=82]="R";CharacterCodes2[CharacterCodes2["S"]=83]="S";CharacterCodes2[CharacterCodes2["T"]=84]="T";CharacterCodes2[CharacterCodes2["U"]=85]="U";CharacterCodes2[CharacterCodes2["V"]=86]="V";CharacterCodes2[CharacterCodes2["W"]=87]="W";CharacterCodes2[CharacterCodes2["X"]=88]="X";CharacterCodes2[CharacterCodes2["Y"]=89]="Y";CharacterCodes2[CharacterCodes2["Z"]=90]="Z";CharacterCodes2[CharacterCodes2["asterisk"]=42]="asterisk";CharacterCodes2[CharacterCodes2["backslash"]=92]="backslash";CharacterCodes2[CharacterCodes2["closeBrace"]=125]="closeBrace";CharacterCodes2[CharacterCodes2["closeBracket"]=93]="closeBracket";CharacterCodes2[CharacterCodes2["colon"]=58]="colon";CharacterCodes2[CharacterCodes2["comma"]=44]="comma";CharacterCodes2[CharacterCodes2["dot"]=46]="dot";CharacterCodes2[CharacterCodes2["doubleQuote"]=34]="doubleQuote";CharacterCodes2[CharacterCodes2["minus"]=45]="minus";CharacterCodes2[CharacterCodes2["openBrace"]=123]="openBrace";CharacterCodes2[CharacterCodes2["openBracket"]=91]="openBracket";CharacterCodes2[CharacterCodes2["plus"]=43]="plus";CharacterCodes2[CharacterCodes2["slash"]=47]="slash";CharacterCodes2[CharacterCodes2["formFeed"]=12]="formFeed";CharacterCodes2[CharacterCodes2["tab"]=9]="tab"})(CharacterCodes||(CharacterCodes={}));init_esbuild_shims();var cachedSpaces=new Array(20).fill(0).map((_,index)=>{return" ".repeat(index)});var maxCachedValues=200;var cachedBreakLinesWithSpaces={" ":{"\n":new Array(maxCachedValues).fill(0).map((_,index)=>{return"\n"+" ".repeat(index)}),"\r":new Array(maxCachedValues).fill(0).map((_,index)=>{return"\r"+" ".repeat(index)}),"\r\n":new Array(maxCachedValues).fill(0).map((_,index)=>{return"\r\n"+" ".repeat(index)})}," ":{"\n":new Array(maxCachedValues).fill(0).map((_,index)=>{return"\n"+" ".repeat(index)}),"\r":new Array(maxCachedValues).fill(0).map((_,index)=>{return"\r"+" ".repeat(index)}),"\r\n":new Array(maxCachedValues).fill(0).map((_,index)=>{return"\r\n"+" ".repeat(index)})}};var supportedEols=["\n","\r","\r\n"];function format(documentText,range,options){let initialIndentLevel;let formatText;let formatTextStart;let rangeStart;let rangeEnd;if(range){rangeStart=range.offset;rangeEnd=rangeStart+range.length;formatTextStart=rangeStart;while(formatTextStart>0&&!isEOL(documentText,formatTextStart-1)){formatTextStart--}let endOffset=rangeEnd;while(endOffset<documentText.length&&!isEOL(documentText,endOffset)){endOffset++}formatText=documentText.substring(formatTextStart,endOffset);initialIndentLevel=computeIndentLevel(formatText,options)}else{formatText=documentText;initialIndentLevel=0;formatTextStart=0;rangeStart=0;rangeEnd=documentText.length}const eol=getEOL(options,documentText);const eolFastPathSupported=supportedEols.includes(eol);let numberLineBreaks=0;let indentLevel=0;let indentValue;if(options.insertSpaces){indentValue=cachedSpaces[options.tabSize||4]??repeat(cachedSpaces[1],options.tabSize||4)}else{indentValue=" "}const indentType=indentValue===" "?" ":" ";let scanner=createScanner(formatText,false);let hasError=false;function newLinesAndIndent(){if(numberLineBreaks>1){return repeat(eol,numberLineBreaks)+repeat(indentValue,initialIndentLevel+indentLevel)}const amountOfSpaces=indentValue.length*(initialIndentLevel+indentLevel);if(!eolFastPathSupported||amountOfSpaces>cachedBreakLinesWithSpaces[indentType][eol].length){return eol+repeat(indentValue,initialIndentLevel+indentLevel)}if(amountOfSpaces<=0){return eol}return cachedBreakLinesWithSpaces[indentType][eol][amountOfSpaces]}__name(newLinesAndIndent,"newLinesAndIndent");function scanNext(){let token=scanner.scan();numberLineBreaks=0;while(token===15||token===14){if(token===14&&options.keepLines){numberLineBreaks+=1}else if(token===14){numberLineBreaks=1}token=scanner.scan()}hasError=token===16||scanner.getTokenError()!==0;return token}__name(scanNext,"scanNext");const editOperations=[];function addEdit(text,startOffset,endOffset){if(!hasError&&(!range||startOffset<rangeEnd&&endOffset>rangeStart)&&documentText.substring(startOffset,endOffset)!==text){editOperations.push({offset:startOffset,length:endOffset-startOffset,content:text})}}__name(addEdit,"addEdit");let firstToken=scanNext();if(options.keepLines&&numberLineBreaks>0){addEdit(repeat(eol,numberLineBreaks),0,0)}if(firstToken!==17){let firstTokenStart=scanner.getTokenOffset()+formatTextStart;let initialIndent=indentValue.length*initialIndentLevel<20&&options.insertSpaces?cachedSpaces[indentValue.length*initialIndentLevel]:repeat(indentValue,initialIndentLevel);addEdit(initialIndent,formatTextStart,firstTokenStart)}while(firstToken!==17){let firstTokenEnd=scanner.getTokenOffset()+scanner.getTokenLength()+formatTextStart;let secondToken=scanNext();let replaceContent="";let needsLineBreak=false;while(numberLineBreaks===0&&(secondToken===12||secondToken===13)){let commentTokenStart=scanner.getTokenOffset()+formatTextStart;addEdit(cachedSpaces[1],firstTokenEnd,commentTokenStart);firstTokenEnd=scanner.getTokenOffset()+scanner.getTokenLength()+formatTextStart;needsLineBreak=secondToken===12;replaceContent=needsLineBreak?newLinesAndIndent():"";secondToken=scanNext()}if(secondToken===2){if(firstToken!==1){indentLevel--};if(options.keepLines&&numberLineBreaks>0||!options.keepLines&&firstToken!==1){replaceContent=newLinesAndIndent()}else if(options.keepLines){replaceContent=cachedSpaces[1]}}else if(secondToken===4){if(firstToken!==3){indentLevel--};if(options.keepLines&&numberLineBreaks>0||!options.keepLines&&firstToken!==3){replaceContent=newLinesAndIndent()}else if(options.keepLines){replaceContent=cachedSpaces[1]}}else{switch(firstToken){case 3:case 1:indentLevel++;if(options.keepLines&&numberLineBreaks>0||!options.keepLines){replaceContent=newLinesAndIndent()}else{replaceContent=cachedSpaces[1]}break;case 5:if(options.keepLines&&numberLineBreaks>0||!options.keepLines){replaceContent=newLinesAndIndent()}else{replaceContent=cachedSpaces[1]}break;case 12:replaceContent=newLinesAndIndent();break;case 13:if(numberLineBreaks>0){replaceContent=newLinesAndIndent()}else if(!needsLineBreak){replaceContent=cachedSpaces[1]}break;case 6:if(options.keepLines&&numberLineBreaks>0){replaceContent=newLinesAndIndent()}else if(!needsLineBreak){replaceContent=cachedSpaces[1]}break;case 10:if(options.keepLines&&numberLineBreaks>0){replaceContent=newLinesAndIndent()}else if(secondToken===6&&!needsLineBreak){replaceContent=""}break;case 7:case 8:case 9:case 11:case 2:case 4:if(options.keepLines&&numberLineBreaks>0){replaceContent=newLinesAndIndent()}else{if((secondToken===12||secondToken===13)&&!needsLineBreak){replaceContent=cachedSpaces[1]}else if(secondToken!==5&&secondToken!==17){hasError=true}}break;case 16:hasError=true;break}if(numberLineBreaks>0&&(secondToken===12||secondToken===13)){replaceContent=newLinesAndIndent()}}if(secondToken===17){if(options.keepLines&&numberLineBreaks>0){replaceContent=newLinesAndIndent()}else{replaceContent=options.insertFinalNewline?eol:""}}const secondTokenStart=scanner.getTokenOffset()+formatTextStart;addEdit(replaceContent,firstTokenEnd,secondTokenStart);firstToken=secondToken}return editOperations}__name(format,"format");function repeat(s,count){let result="";for(let i=0;i<count;i++){result+=s}return result}__name(repeat,"repeat");function computeIndentLevel(content,options){let i=0;let nChars=0;const tabSize=options.tabSize||4;while(i<content.length){let ch=content.charAt(i);if(ch===cachedSpaces[1]){nChars++}else if(ch===" "){nChars+=tabSize}else{break}i++}return Math.floor(nChars/tabSize)}__name(computeIndentLevel,"computeIndentLevel");function getEOL(options,text){for(let i=0;i<text.length;i++){const ch=text.charAt(i);if(ch==="\r"){if(i+1<text.length&&text.charAt(i+1)==="\n"){return"\r\n"}return"\r"}else if(ch==="\n"){return"\n"}}return options&&options.eol||"\n"}__name(getEOL,"getEOL");function isEOL(text,offset){return"\r\n".indexOf(text.charAt(offset))!==-1}__name(isEOL,"isEOL");init_esbuild_shims();init_esbuild_shims();var ParseOptions;(function(ParseOptions2){ParseOptions2.DEFAULT={allowTrailingComma:false}})(ParseOptions||(ParseOptions={}));function parseTree(text,errors=[],options=ParseOptions.DEFAULT){let currentParent={type:"array",offset:-1,length:-1,children:[],parent:void 0};function ensurePropertyComplete(endOffset){if(currentParent.type==="property"){currentParent.length=endOffset-currentParent.offset;currentParent=currentParent.parent}}__name(ensurePropertyComplete,"ensurePropertyComplete");function onValue(valueNode){currentParent.children.push(valueNode);return valueNode}__name(onValue,"onValue");const visitor={onObjectBegin:__name(offset=>{currentParent=onValue({type:"object",offset,length:-1,parent:currentParent,children:[]})},"onObjectBegin"),onObjectProperty:__name((name,offset,length)=>{currentParent=onValue({type:"property",offset,length:-1,parent:currentParent,children:[]});currentParent.children.push({type:"string",value:name,offset,length,parent:currentParent})},"onObjectProperty"),onObjectEnd:__name((offset,length)=>{ensurePropertyComplete(offset+length);currentParent.length=offset+length-currentParent.offset;currentParent=currentParent.parent;ensurePropertyComplete(offset+length)},"onObjectEnd"),onArrayBegin:__name((offset,length)=>{currentParent=onValue({type:"array",offset,length:-1,parent:currentParent,children:[]})},"onArrayBegin"),onArrayEnd:__name((offset,length)=>{currentParent.length=offset+length-currentParent.offset;currentParent=currentParent.parent;ensurePropertyComplete(offset+length)},"onArrayEnd"),onLiteralValue:__name((value,offset,length)=>{onValue({type:getNodeType(value),offset,length,parent:currentParent,value});ensurePropertyComplete(offset+length)},"onLiteralValue"),onSeparator:__name((sep,offset,length)=>{if(currentParent.type==="property"){if(sep===":"){currentParent.colonOffset=offset}else if(sep===","){ensurePropertyComplete(offset)}}},"onSeparator"),onError:__name((error,offset,length)=>{errors.push({error,offset,length})},"onError")};visit(text,visitor,options);const result=currentParent.children[0];if(result){delete result.parent}return result}__name(parseTree,"parseTree");function findNodeAtLocation(root,path4){if(!root){return void 0}let node=root;for(let segment of path4){if(typeof segment==="string"){if(node.type!=="object"||!Array.isArray(node.children)){return void 0}let found=false;for(const propertyNode of node.children){if(Array.isArray(propertyNode.children)&&propertyNode.children[0].value===segment&&propertyNode.children.length===2){node=propertyNode.children[1];found=true;break}}if(!found){return void 0}}else{const index=segment;if(node.type!=="array"||index<0||!Array.isArray(node.children)||index>=node.children.length){return void 0}node=node.children[index]}}return node}__name(findNodeAtLocation,"findNodeAtLocation");function getNodeValue(node){switch(node.type){case"array":return node.children.map(getNodeValue);case"object":const obj=Object.create(null);for(let prop of node.children){const valueNode=prop.children[1];if(valueNode){obj[prop.children[0].value]=getNodeValue(valueNode)}}return obj;case"null":case"string":case"number":case"boolean":return node.value;default:return void 0}}__name(getNodeValue,"getNodeValue");function visit(text,visitor,options=ParseOptions.DEFAULT){const _scanner=createScanner(text,false);const _jsonPath=[];let suppressedCallbacks=0;function toNoArgVisit(visitFunction){return visitFunction?()=>suppressedCallbacks===0&&visitFunction(_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter()):()=>true}__name(toNoArgVisit,"toNoArgVisit");function toOneArgVisit(visitFunction){return visitFunction?arg=>suppressedCallbacks===0&&visitFunction(arg,_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter()):()=>true}__name(toOneArgVisit,"toOneArgVisit");function toOneArgVisitWithPath(visitFunction){return visitFunction?arg=>suppressedCallbacks===0&&visitFunction(arg,_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter(),()=>_jsonPath.slice()):()=>true}__name(toOneArgVisitWithPath,"toOneArgVisitWithPath");function toBeginVisit(visitFunction){return visitFunction?()=>{if(suppressedCallbacks>0){suppressedCallbacks++}else{let cbReturn=visitFunction(_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter(),()=>_jsonPath.slice());if(cbReturn===false){suppressedCallbacks=1}}}:()=>true}__name(toBeginVisit,"toBeginVisit");function toEndVisit(visitFunction){return visitFunction?()=>{if(suppressedCallbacks>0){suppressedCallbacks--}if(suppressedCallbacks===0){visitFunction(_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter())}}:()=>true}__name(toEndVisit,"toEndVisit");const onObjectBegin=toBeginVisit(visitor.onObjectBegin),onObjectProperty=toOneArgVisitWithPath(visitor.onObjectProperty),onObjectEnd=toEndVisit(visitor.onObjectEnd),onArrayBegin=toBeginVisit(visitor.onArrayBegin),onArrayEnd=toEndVisit(visitor.onArrayEnd),onLiteralValue=toOneArgVisitWithPath(visitor.onLiteralValue),onSeparator=toOneArgVisit(visitor.onSeparator),onComment=toNoArgVisit(visitor.onComment),onError=toOneArgVisit(visitor.onError);const disallowComments=options&&options.disallowComments;const allowTrailingComma=options&&options.allowTrailingComma;function scanNext(){while(true){const token=_scanner.scan();switch(_scanner.getTokenError()){case 4:handleError(14);break;case 5:handleError(15);break;case 3:handleError(13);break;case 1:if(!disallowComments){handleError(11)}break;case 2:handleError(12);break;case 6:handleError(16);break}switch(token){case 12:case 13:if(disallowComments){handleError(10)}else{onComment()}break;case 16:handleError(1);break;case 15:case 14:break;default:return token}}}__name(scanNext,"scanNext");function handleError(error,skipUntilAfter=[],skipUntil=[]){onError(error);if(skipUntilAfter.length+skipUntil.length>0){let token=_scanner.getToken();while(token!==17){if(skipUntilAfter.indexOf(token)!==-1){scanNext();break}else if(skipUntil.indexOf(token)!==-1){break}token=scanNext()}}}__name(handleError,"handleError");function parseString(isValue){const value=_scanner.getTokenValue();if(isValue){onLiteralValue(value)}else{onObjectProperty(value);_jsonPath.push(value)}scanNext();return true}__name(parseString,"parseString");function parseLiteral(){switch(_scanner.getToken()){case 11:const tokenValue=_scanner.getTokenValue();let value=Number(tokenValue);if(isNaN(value)){handleError(2);value=0}onLiteralValue(value);break;case 7:onLiteralValue(null);break;case 8:onLiteralValue(true);break;case 9:onLiteralValue(false);break;default:return false}scanNext();return true}__name(parseLiteral,"parseLiteral");function parseProperty(){if(_scanner.getToken()!==10){handleError(3,[],[2,5]);return false}parseString(false);if(_scanner.getToken()===6){onSeparator(":");scanNext();if(!parseValue()){handleError(4,[],[2,5])}}else{handleError(5,[],[2,5])}_jsonPath.pop();return true}__name(parseProperty,"parseProperty");function parseObject(){onObjectBegin();scanNext();let needsComma=false;while(_scanner.getToken()!==2&&_scanner.getToken()!==17){if(_scanner.getToken()===5){if(!needsComma){handleError(4,[],[])}onSeparator(",");scanNext();if(_scanner.getToken()===2&&allowTrailingComma){break}}else if(needsComma){handleError(6,[],[])}if(!parseProperty()){handleError(4,[],[2,5])}needsComma=true}onObjectEnd();if(_scanner.getToken()!==2){handleError(7,[2],[])}else{scanNext()}return true}__name(parseObject,"parseObject");function parseArray(){onArrayBegin();scanNext();let isFirstElement=true;let needsComma=false;while(_scanner.getToken()!==4&&_scanner.getToken()!==17){if(_scanner.getToken()===5){if(!needsComma){handleError(4,[],[])}onSeparator(",");scanNext();if(_scanner.getToken()===4&&allowTrailingComma){break}}else if(needsComma){handleError(6,[],[])}if(isFirstElement){_jsonPath.push(0);isFirstElement=false}else{_jsonPath[_jsonPath.length-1]++}if(!parseValue()){handleError(4,[],[4,5])}needsComma=true}onArrayEnd();if(!isFirstElement){_jsonPath.pop()}if(_scanner.getToken()!==4){handleError(8,[4],[])}else{scanNext()}return true}__name(parseArray,"parseArray");function parseValue(){switch(_scanner.getToken()){case 3:return parseArray();case 1:return parseObject();case 10:return parseString(true);default:return parseLiteral()}}__name(parseValue,"parseValue");scanNext();if(_scanner.getToken()===17){if(options.allowEmptyContent){return true}handleError(4,[],[]);return false}if(!parseValue()){handleError(4,[],[]);return false}if(_scanner.getToken()!==17){handleError(9,[],[])}return true}__name(visit,"visit");function getNodeType(value){switch(typeof value){case"boolean":return"boolean";case"number":return"number";case"string":return"string";case"object":{if(!value){return"null"}else if(Array.isArray(value)){return"array"}return"object"}default:return"null"}}__name(getNodeType,"getNodeType");function setProperty(text,originalPath,value,options){const path4=originalPath.slice();const errors=[];const root=parseTree(text,errors);let parent=void 0;let lastSegment=void 0;while(path4.length>0){lastSegment=path4.pop();parent=findNodeAtLocation(root,path4);if(parent===void 0&&value!==void 0){if(typeof lastSegment==="string"){value={[lastSegment]:value}}else{value=[value]}}else{break}}if(!parent){if(value===void 0){throw new Error("Can not delete in empty document")}return withFormatting(text,{offset:root?root.offset:0,length:root?root.length:0,content:JSON.stringify(value)},options)}else if(parent.type==="object"&&typeof lastSegment==="string"&&Array.isArray(parent.children)){const existing=findNodeAtLocation(parent,[lastSegment]);if(existing!==void 0){if(value===void 0){if(!existing.parent){throw new Error("Malformed AST")}const propertyIndex=parent.children.indexOf(existing.parent);let removeBegin;let removeEnd=existing.parent.offset+existing.parent.length;if(propertyIndex>0){let previous=parent.children[propertyIndex-1];removeBegin=previous.offset+previous.length}else{removeBegin=parent.offset+1;if(parent.children.length>1){let next=parent.children[1];removeEnd=next.offset}}return withFormatting(text,{offset:removeBegin,length:removeEnd-removeBegin,content:""},options)}else{return withFormatting(text,{offset:existing.offset,length:existing.length,content:JSON.stringify(value)},options)}}else{if(value===void 0){return[]}const newProperty=`${JSON.stringify(lastSegment)}: ${JSON.stringify(value)}`;const index=options.getInsertionIndex?options.getInsertionIndex(parent.children.map(p=>p.children[0].value)):parent.children.length;let edit;if(index>0){let previous=parent.children[index-1];edit={offset:previous.offset+previous.length,length:0,content:","+newProperty}}else if(parent.children.length===0){edit={offset:parent.offset+1,length:0,content:newProperty}}else{edit={offset:parent.offset+1,length:0,content:newProperty+","}}return withFormatting(text,edit,options)}}else if(parent.type==="array"&&typeof lastSegment==="number"&&Array.isArray(parent.children)){const insertIndex=lastSegment;if(insertIndex===-1){const newProperty=`${JSON.stringify(value)}`;let edit;if(parent.children.length===0){edit={offset:parent.offset+1,length:0,content:newProperty}}else{const previous=parent.children[parent.children.length-1];edit={offset:previous.offset+previous.length,length:0,content:","+newProperty}}return withFormatting(text,edit,options)}else if(value===void 0&&parent.children.length>=0){const removalIndex=lastSegment;const toRemove=parent.children[removalIndex];let edit;if(parent.children.length===1){edit={offset:parent.offset+1,length:parent.length-2,content:""}}else if(parent.children.length-1===removalIndex){let previous=parent.children[removalIndex-1];let offset=previous.offset+previous.length;let parentEndOffset=parent.offset+parent.length;edit={offset,length:parentEndOffset-2-offset,content:""}}else{edit={offset:toRemove.offset,length:parent.children[removalIndex+1].offset-toRemove.offset,content:""}}return withFormatting(text,edit,options)}else if(value!==void 0){let edit;const newProperty=`${JSON.stringify(value)}`;if(!options.isArrayInsertion&&parent.children.length>lastSegment){const toModify=parent.children[lastSegment];edit={offset:toModify.offset,length:toModify.length,content:newProperty}}else if(parent.children.length===0||lastSegment===0){edit={offset:parent.offset+1,length:0,content:parent.children.length===0?newProperty:newProperty+","}}else{const index=lastSegment>parent.children.length?parent.children.length:lastSegment;const previous=parent.children[index-1];edit={offset:previous.offset+previous.length,length:0,content:","+newProperty}}return withFormatting(text,edit,options)}else{throw new Error(`Can not ${value===void 0?"remove":options.isArrayInsertion?"insert":"modify"} Array index ${insertIndex} as length is not sufficient`)}}else{throw new Error(`Can not add ${typeof lastSegment!=="number"?"index":"property"} to parent of type ${parent.type}`)}}__name(setProperty,"setProperty");function withFormatting(text,edit,options){if(!options.formattingOptions){return[edit]}let newText=applyEdit(text,edit);let begin=edit.offset;let end=edit.offset+edit.content.length;if(edit.length===0||edit.content.length===0){while(begin>0&&!isEOL(newText,begin-1)){begin--}while(end<newText.length&&!isEOL(newText,end)){end++}}const edits=format(newText,{offset:begin,length:end-begin},{...options.formattingOptions,keepLines:false});for(let i=edits.length-1;i>=0;i--){const edit2=edits[i];newText=applyEdit(newText,edit2);begin=Math.min(begin,edit2.offset);end=Math.max(end,edit2.offset+edit2.length);end+=edit2.content.length-edit2.length}const editLength=text.length-(newText.length-end)-begin;return[{offset:begin,length:editLength,content:newText.substring(begin,end)}]}__name(withFormatting,"withFormatting");function applyEdit(text,edit){return text.substring(0,edit.offset)+edit.content+text.substring(edit.offset+edit.length)}__name(applyEdit,"applyEdit");var ScanError;(function(ScanError2){ScanError2[ScanError2["None"]=0]="None";ScanError2[ScanError2["UnexpectedEndOfComment"]=1]="UnexpectedEndOfComment";ScanError2[ScanError2["UnexpectedEndOfString"]=2]="UnexpectedEndOfString";ScanError2[ScanError2["UnexpectedEndOfNumber"]=3]="UnexpectedEndOfNumber";ScanError2[ScanError2["InvalidUnicode"]=4]="InvalidUnicode";ScanError2[ScanError2["InvalidEscapeCharacter"]=5]="InvalidEscapeCharacter";ScanError2[ScanError2["InvalidCharacter"]=6]="InvalidCharacter"})(ScanError||(ScanError={}));var SyntaxKind;(function(SyntaxKind2){SyntaxKind2[SyntaxKind2["OpenBraceToken"]=1]="OpenBraceToken";SyntaxKind2[SyntaxKind2["CloseBraceToken"]=2]="CloseBraceToken";SyntaxKind2[SyntaxKind2["OpenBracketToken"]=3]="OpenBracketToken";SyntaxKind2[SyntaxKind2["CloseBracketToken"]=4]="CloseBracketToken";SyntaxKind2[SyntaxKind2["CommaToken"]=5]="CommaToken";SyntaxKind2[SyntaxKind2["ColonToken"]=6]="ColonToken";SyntaxKind2[SyntaxKind2["NullKeyword"]=7]="NullKeyword";SyntaxKind2[SyntaxKind2["TrueKeyword"]=8]="TrueKeyword";SyntaxKind2[SyntaxKind2["FalseKeyword"]=9]="FalseKeyword";SyntaxKind2[SyntaxKind2["StringLiteral"]=10]="StringLiteral";SyntaxKind2[SyntaxKind2["NumericLiteral"]=11]="NumericLiteral";SyntaxKind2[SyntaxKind2["LineCommentTrivia"]=12]="LineCommentTrivia";SyntaxKind2[SyntaxKind2["BlockCommentTrivia"]=13]="BlockCommentTrivia";SyntaxKind2[SyntaxKind2["LineBreakTrivia"]=14]="LineBreakTrivia";SyntaxKind2[SyntaxKind2["Trivia"]=15]="Trivia";SyntaxKind2[SyntaxKind2["Unknown"]=16]="Unknown";SyntaxKind2[SyntaxKind2["EOF"]=17]="EOF"})(SyntaxKind||(SyntaxKind={}));var parseTree2=parseTree;var findNodeAtLocation2=findNodeAtLocation;var getNodeValue2=getNodeValue;var ParseErrorCode;(function(ParseErrorCode2){ParseErrorCode2[ParseErrorCode2["InvalidSymbol"]=1]="InvalidSymbol";ParseErrorCode2[ParseErrorCode2["InvalidNumberFormat"]=2]="InvalidNumberFormat";ParseErrorCode2[ParseErrorCode2["PropertyNameExpected"]=3]="PropertyNameExpected";ParseErrorCode2[ParseErrorCode2["ValueExpected"]=4]="ValueExpected";ParseErrorCode2[ParseErrorCode2["ColonExpected"]=5]="ColonExpected";ParseErrorCode2[ParseErrorCode2["CommaExpected"]=6]="CommaExpected";ParseErrorCode2[ParseErrorCode2["CloseBraceExpected"]=7]="CloseBraceExpected";ParseErrorCode2[ParseErrorCode2["CloseBracketExpected"]=8]="CloseBracketExpected";ParseErrorCode2[ParseErrorCode2["EndOfFileExpected"]=9]="EndOfFileExpected";ParseErrorCode2[ParseErrorCode2["InvalidCommentToken"]=10]="InvalidCommentToken";ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfComment"]=11]="UnexpectedEndOfComment";ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfString"]=12]="UnexpectedEndOfString";ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfNumber"]=13]="UnexpectedEndOfNumber";ParseErrorCode2[ParseErrorCode2["InvalidUnicode"]=14]="InvalidUnicode";ParseErrorCode2[ParseErrorCode2["InvalidEscapeCharacter"]=15]="InvalidEscapeCharacter";ParseErrorCode2[ParseErrorCode2["InvalidCharacter"]=16]="InvalidCharacter"})(ParseErrorCode||(ParseErrorCode={}));function printParseErrorCode(code){switch(code){case 1:return"InvalidSymbol";case 2:return"InvalidNumberFormat";case 3:return"PropertyNameExpected";case 4:return"ValueExpected";case 5:return"ColonExpected";case 6:return"CommaExpected";case 7:return"CloseBraceExpected";case 8:return"CloseBracketExpected";case 9:return"EndOfFileExpected";case 10:return"InvalidCommentToken";case 11:return"UnexpectedEndOfComment";case 12:return"UnexpectedEndOfString";case 13:return"UnexpectedEndOfNumber";case 14:return"InvalidUnicode";case 15:return"InvalidEscapeCharacter";case 16:return"InvalidCharacter"}return"<unknown ParseErrorCode>"}__name(printParseErrorCode,"printParseErrorCode");function modify(text,path4,value,options){return setProperty(text,path4,value,options)}__name(modify,"modify");function applyEdits(text,edits){let sortedEdits=edits.slice(0).sort((a,b)=>{const diff=a.offset-b.offset;if(diff===0){return a.length-b.length}return diff});let lastModifiedOffset=text.length;for(let i=sortedEdits.length-1;i>=0;i--){let e=sortedEdits[i];if(e.offset+e.length<=lastModifiedOffset){text=applyEdit(text,e)}else{throw new Error("Overlapping edit")}lastModifiedOffset=e.offset}return text}__name(applyEdits,"applyEdits");init_esbuild_shims();import*as fs from"node:fs";import path from"node:path";function writeWithBackupSync(targetPath,content,options={}){const{backupSuffix=".orig",encoding="utf-8"}=options;const existing=fs.existsSync(targetPath)?fs.statSync(targetPath):void 0;if(existing?.isDirectory()){throw new Error(`Cannot write to '${targetPath}' because it is a directory`)}const workingDirectory=fs.mkdtempSync(`${targetPath}.write-`);const basename=path.basename(targetPath);const tempPath=path.join(workingDirectory,`${basename}.tmp`);const backupPath=path.join(workingDirectory,`${basename}${backupSuffix}`);let backupCreated=false;try{const mode=existing&&fs.lstatSync(targetPath,{throwIfNoEntry:false})?.isFile()?existing.mode&511:void 0;fs.writeFileSync(tempPath,content,{encoding,flag:"wx",flush:true,mode});if(mode!==void 0){try{fs.chmodSync(tempPath,mode)}catch(error){const code=error instanceof Error&&"code"in error?error.code:void 0;if(code!=="ENOSYS"&&code!=="ENOTSUP"&&code!=="EPERM"||(fs.statSync(tempPath).mode&511&~mode)!==0){throw error}}}if(fs.existsSync(targetPath)){try{fs.copyFileSync(targetPath,backupPath,fs.constants.COPYFILE_EXCL);backupCreated=true}catch(backupError){throw new Error(`Failed to backup existing file: ${backupError instanceof Error?backupError.message:String(backupError)}`)}}fs.renameSync(tempPath,targetPath)}catch(error){const recoveryRetained=backupCreated&&!sameContents(backupPath,targetPath);try{if(recoveryRetained){fs.unlinkSync(tempPath)}else{fs.rmSync(workingDirectory,{recursive:true,force:true})}}catch{}if(recoveryRetained){throw new Error(`Failed to write file: ${error instanceof Error?error.message:String(error)}. Recovery copy retained at '${backupPath}'; inspect the current target before restoring it.`)}throw error}try{fs.rmSync(workingDirectory,{recursive:true,force:true})}catch{}}__name(writeWithBackupSync,"writeWithBackupSync");function sameContents(first,second){try{return fs.readFileSync(first).equals(fs.readFileSync(second))}catch{return false}}__name(sameContents,"sameContents");var PARSE_OPTIONS={allowTrailingComma:true};function updateSettingsFilePreservingFormat(filePath,updates,sync=false,replacePath=[]){if(!fs2.existsSync(filePath)){const content=JSON.stringify(updates,null,2);writeWithBackupSync(filePath,content);return true}const originalContent=fs2.readFileSync(filePath,"utf-8");try{parseJsoncObject(originalContent)}catch(_error){writeStderrLine("Error parsing settings file.");writeStderrLine(`Settings file may be corrupted: ${_error instanceof Error?_error.message:String(_error)}`);return false}let updatedContent;try{updatedContent=updateJsoncContent(originalContent,updates,sync,replacePath)}catch(validationError){writeStderrLine("Error: Refusing to write settings file \u2014 the result would not be valid JSON.");writeStderrLine(validationError instanceof Error?validationError.message:String(validationError));return false}writeWithBackupSync(filePath,updatedContent);return true}__name(updateSettingsFilePreservingFormat,"updateSettingsFilePreservingFormat");function parseJsoncObject(content){const errors=[];const root=parseTree2(stripBom(content),errors,PARSE_OPTIONS);if(errors.length>0){const error=errors[0];throw new Error(`${printParseErrorCode(error.error)} at offset ${error.offset}`)}if(root?.type!=="object"){throw new Error("JSONC document root is not a JSON object.")}return JSON.parse(JSON.stringify(getNodeValue2(root)))}__name(parseJsoncObject,"parseJsoncObject");function updateJsoncContent(content,updates,sync=false,replacePath=[]){const bom=content.startsWith("\uFEFF")?"\uFEFF":"";const editableContent=stripBom(content);const parsed=parseJsoncObject(editableContent);const targetWithUndefined=applyUpdates(structuredClone(parsed),updates,sync,replacePath);const target=JSON.parse(JSON.stringify(targetWithUndefined));const options={formattingOptions:detectFormattingOptions(editableContent)};let updated=normalizeDuplicateProperties(editableContent,options);const current=parseJsoncObject(updated);for(const operation of collectOperations(current,target)){if(operation.value===void 0){updated=removeTrailingInlineComment(updated,operation.path)}updated=applyEdits(updated,modify(updated,operation.path,operation.value,options))}const reparsed=parseJsoncObject(updated);if(!isDeepStrictEqual(reparsed,target)){throw new Error("Edited JSONC does not match the intended settings.")}return bom+updated}__name(updateJsoncContent,"updateJsoncContent");function applyUpdates(current,updates,sync=false,replacePath=[],currentPath=[]){const result=current;if(sync){const keysToRemove=Object.keys(result).filter(key=>!Object.hasOwn(updates,key));for(const key of keysToRemove){delete result[key]}}for(const key of Object.getOwnPropertyNames(updates)){if(key==="__proto__"||key==="constructor"||key==="prototype"){continue}const value=updates[key];const nextPath=[...currentPath,key];const valueIsObject=typeof value==="object"&&value!==null&&!Array.isArray(value)&&Object.keys(value).length>0;if(pathsEqual(nextPath,replacePath)){result[key]=valueIsObject?applyUpdates({},value):value;continue}if(valueIsObject&&(typeof result[key]!=="object"||result[key]===null||Array.isArray(result[key]))){result[key]=applyUpdates({},value,sync,replacePath,nextPath)}else if(valueIsObject&&typeof result[key]==="object"&&result[key]!==null&&!Array.isArray(result[key])){result[key]=applyUpdates(result[key],value,sync,replacePath,nextPath)}else{result[key]=value}}return result}__name(applyUpdates,"applyUpdates");function stripBom(content){return content.startsWith("\uFEFF")?content.slice(1):content}__name(stripBom,"stripBom");function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord,"isRecord");function detectFormattingOptions(content){const root=parseTree2(content,[],PARSE_OPTIONS);const firstKey=root?.children?.[0]?.children?.[0];const lineStart=firstKey===void 0?-1:content.lastIndexOf("\n",firstKey.offset-1);const candidate=firstKey===void 0?void 0:content.slice(lineStart+1,firstKey.offset);const indentation=candidate!==void 0&&/^[ \t]*$/.test(candidate)?candidate:" ";return{eol:content.includes("\r\n")?"\r\n":"\n",insertSpaces:!indentation.startsWith(" "),tabSize:indentation.startsWith(" ")?1:indentation.length,insertFinalNewline:content.endsWith("\n")}}__name(detectFormattingOptions,"detectFormattingOptions");function collectOperations(current,target,path4=[],operations=[]){for(const key of Object.keys(current)){if(!Object.hasOwn(target,key)){operations.push({path:[...path4,key],value:void 0})}}for(const key of Object.keys(target)){const nextPath=[...path4,key];if(!Object.hasOwn(current,key)){operations.push({path:nextPath,value:target[key]})}else if(isRecord(current[key])&&isRecord(target[key])){collectOperations(current[key],target[key],nextPath,operations)}else if(!isDeepStrictEqual(current[key],target[key])){operations.push({path:nextPath,value:target[key]})}}return operations}__name(collectOperations,"collectOperations");function findDuplicateProperty(node,path4=[]){if(node.type!=="object"||node.children===void 0){return void 0}const properties=new Map;for(const property of node.children){const keyNode=property.children?.[0];const key=keyNode?.value;if(typeof key!=="string"||keyNode===void 0){continue}const previous=properties.get(key);if(previous!==void 0){return{objectPath:[...path4],keyNode:previous,propertyNames:new Set(properties.keys())}}properties.set(key,keyNode)}for(const property of node.children){const key=property.children?.[0]?.value;const valueNode=property.children?.[1];if(typeof key!=="string"||valueNode===void 0){continue}const duplicate=findDuplicateProperty(valueNode,[...path4,key]);if(duplicate!==void 0){return duplicate}}return void 0}__name(findDuplicateProperty,"findDuplicateProperty");function normalizeDuplicateProperties(content,options){let normalized=content;let duplicateIndex=0;while(true){const root=parseTree2(normalized,[],PARSE_OPTIONS);if(root===void 0){return normalized}const duplicate=findDuplicateProperty(root);if(duplicate===void 0){return normalized}let temporaryKey;do{temporaryKey=`__qwen_duplicate_${duplicateIndex}`;duplicateIndex+=1}while(duplicate.propertyNames.has(temporaryKey));let renamed=normalized.slice(0,duplicate.keyNode.offset)+JSON.stringify(temporaryKey)+normalized.slice(duplicate.keyNode.offset+duplicate.keyNode.length);renamed=removeTrailingInlineComment(renamed,[...duplicate.objectPath,temporaryKey]);normalized=applyEdits(renamed,modify(renamed,[...duplicate.objectPath,temporaryKey],void 0,options))}}__name(normalizeDuplicateProperties,"normalizeDuplicateProperties");function removeTrailingInlineComment(content,path4){const root=parseTree2(content,[],PARSE_OPTIONS);if(root===void 0){return content}const node=findNodeAtLocation2(root,[...path4]);if(node===void 0){return content}const tail=content.slice(node.offset+node.length);const match=tail.match(/^[ \t]*(?:,[ \t]*)?(\/\/[^\r\n]*|\/\*[\s\S]*?\*\/)/);const comment=match?.[1];if(comment===void 0||match===null){return content}const commentOffset=node.offset+node.length+match[0].indexOf(comment);return content.slice(0,commentOffset)+content.slice(commentOffset+comment.length)}__name(removeTrailingInlineComment,"removeTrailingInlineComment");function pathsEqual(left,right){return left.length===right.length&&left.every((segment,index)=>segment===right[index])}__name(pathsEqual,"pathsEqual");init_esbuild_shims();import*as fs3 from"node:fs";import*as path2 from"node:path";function isWorkflowAncestorDirectorySafe(directory){if(process.platform==="win32")return true;for(const location of[directory,path2.join(directory,".qwen"),path2.join(directory,".qwen","workflows")]){try{if((fs3.statSync(location).mode&2)!==0)return false}catch(error){const code=error.code;if(location===directory)return false;if(code==="ENOENT"||code==="ENOTDIR")break;return false}}return true}__name(isWorkflowAncestorDirectorySafe,"isWorkflowAncestorDirectorySafe");var debugLogger=createDebugLogger("TRUSTED_FOLDERS");var TRUSTED_FOLDERS_FILENAME="trustedFolders.json";function getTrustedFoldersPath(){if(process.env["QWEN_CODE_TRUSTED_FOLDERS_PATH"]){return process.env["QWEN_CODE_TRUSTED_FOLDERS_PATH"]}return path3.join(Storage.getGlobalQwenDir(),TRUSTED_FOLDERS_FILENAME)}__name(getTrustedFoldersPath,"getTrustedFoldersPath");var TrustLevel=(TrustLevel2=>{TrustLevel2["TRUST_FOLDER"]="TRUST_FOLDER";TrustLevel2["TRUST_PARENT"]="TRUST_PARENT";TrustLevel2["DO_NOT_TRUST"]="DO_NOT_TRUST";return TrustLevel2})(TrustLevel||{});var trustedFoldersChangeListeners=new Set;function onTrustedFoldersChanged(listener){trustedFoldersChangeListeners.add(listener);return()=>trustedFoldersChangeListeners.delete(listener)}__name(onTrustedFoldersChanged,"onTrustedFoldersChanged");function notifyTrustedFoldersChanged(){for(const listener of trustedFoldersChangeListeners)listener()}__name(notifyTrustedFoldersChanged,"notifyTrustedFoldersChanged");var LoadedTrustedFolders=class{constructor(user,errors){this.user=user;this.errors=errors}static{__name(this,"LoadedTrustedFolders")}get rules(){return Object.entries(this.user.config).map(([path4,trustLevel])=>({path:path4,trustLevel}))}isPathTrusted(location){return resolveTrustDecision(buildTrustPrecedenceRules(this.rules),getPathComparisonVariants(location))}setValue(path4,trustLevel,preserveExistingTrust=false){const committedConfig=writeTrustedFolders(this.user.path,diskConfig=>{const existing=diskConfig[path4];if(preserveExistingTrust&&(existing==="TRUST_FOLDER"||existing==="TRUST_PARENT")){return diskConfig}return{...diskConfig,[path4]:trustLevel}});this.user.config=committedConfig;notifyTrustedFoldersChanged()}};var loadedTrustedFolders;function resetTrustedFoldersForTesting(){loadedTrustedFolders=void 0}__name(resetTrustedFoldersForTesting,"resetTrustedFoldersForTesting");function loadTrustedFolders(){loadedTrustedFolders??=readTrustedFoldersFile(false);return loadedTrustedFolders}__name(loadTrustedFolders,"loadTrustedFolders");function loadTrustedFoldersFresh(){return readTrustedFoldersFile(true)}__name(loadTrustedFoldersFresh,"loadTrustedFoldersFresh");function readTrustedFoldersFile(validateRules){const errors=[];let userConfig={};const userPath=getTrustedFoldersPath();try{if(fs4.existsSync(userPath)){const content=fs4.readFileSync(userPath,"utf-8");const parsed=parseJsoncObject(content);if(validateRules)assertTrustedFoldersConfig(parsed);userConfig=parsed}}catch(error){errors.push({message:error instanceof Error&&error.message==="JSONC document root is not a JSON object."?"Trusted folders file is not a valid JSON object.":getErrorMessage(error),path:userPath})}return new LoadedTrustedFolders({path:userPath,config:userConfig},errors)}__name(readTrustedFoldersFile,"readTrustedFoldersFile");function createLocalWorkflowAncestorTrustProvider(settings){return async(ancestorDirs,canonicalTargetDir)=>{if(!isFolderTrustEnabled(settings)){return ancestorDirs.map(isWorkflowAncestorDirectorySafe)}if(ideContextStore.get()?.workspaceState?.isTrusted===false){return ancestorDirs.map(()=>false)}const folders=loadTrustedFoldersFresh();if(folders.errors.length>0){debugLogger.warn("Workflow ancestor trust denied: invalid trusted folders snapshot:",folders.errors.map(error=>`${error.path}: ${error.message}`).join("; "));return ancestorDirs.map(()=>false)}if(folders.isPathTrusted(canonicalTargetDir)!==true){return ancestorDirs.map(()=>false)}return ancestorDirs.map(directory=>folders.isPathTrusted(directory)===true)}}__name(createLocalWorkflowAncestorTrustProvider,"createLocalWorkflowAncestorTrustProvider");function saveTrustedFolders(trustedFoldersFile){writeTrustedFolders(trustedFoldersFile.path,()=>({...trustedFoldersFile.config}))}__name(saveTrustedFolders,"saveTrustedFolders");function assertTrustedFoldersConfig(config){for(const[rulePath,trustLevel]of Object.entries(config)){if(!Object.values(TrustLevel).includes(trustLevel)){throw new FatalConfigError(`Invalid trusted folder rule for ${JSON.stringify(rulePath)}.`)}}}__name(assertTrustedFoldersConfig,"assertTrustedFoldersConfig");function writeTrustedFolders(filePath,update){const dirPath=path3.dirname(filePath);if(!fs4.existsSync(dirPath)){fs4.mkdirSync(dirPath,{recursive:true})}const release=import_proper_lockfile.default.lockSync(filePath,{realpath:false,stale:1e4,onCompromised:__name(err=>{debugLogger.warn("trusted folders lock compromised:",err)},"onCompromised")});try{let originalContent="{}";if(fs4.existsSync(filePath)){const stat=fs4.lstatSync(filePath);if(stat.isSymbolicLink()||!stat.isFile()){throw new FatalConfigError("Trusted folders path must be a regular file.")}originalContent=fs4.readFileSync(filePath,"utf-8")}let parsed;try{parsed=parseJsoncObject(originalContent)}catch(error){if(error instanceof Error&&error.message==="JSONC document root is not a JSON object."){throw new FatalConfigError("Trusted folders file is not a valid JSON object.")}throw error}const diskConfig=Object.fromEntries(Object.entries(parsed));assertTrustedFoldersConfig(diskConfig);const nextConfig=update({...diskConfig});assertTrustedFoldersConfig(nextConfig);const content=updateJsoncContent(originalContent,nextConfig,true);atomicWriteFileSync(filePath,content,{encoding:"utf-8",mode:384,forceMode:true,noFollow:true});return nextConfig}finally{try{release()}catch{}}}__name(writeTrustedFolders,"writeTrustedFolders");function isFolderTrustEnabled(settings){const folderTrustSetting=settings.security?.folderTrust?.enabled??false;return folderTrustSetting}__name(isFolderTrustEnabled,"isFolderTrustEnabled");function getExplicitTrustLevel(trustConfig,workspaceCwd){const winner=resolveTrustRule(buildTrustPrecedenceRules(Object.entries(trustConfig).map(([rulePath,trustLevel])=>({path:rulePath,trustLevel}))),getPathComparisonVariants(workspaceCwd));return winner?.payload??null}__name(getExplicitTrustLevel,"getExplicitTrustLevel");function loadTrustedFoldersWithOverrides(trustConfig){const folders=loadTrustedFolders();if(folders.errors.length>0){const errorMessages=folders.errors.map(error=>`Error in ${error.path}: ${error.message}`);throw new FatalConfigError(`${errorMessages.join("\n")}
3
+ import{buildTrustPrecedenceRules,resolveTrustDecision,resolveTrustRule}from"./chunk-EIPLDYEY.js";import{arePathsEquivalent,getPathComparisonVariants}from"./chunk-IDXJIDME.js";import{ideContextStore}from"./chunk-3NR3JBMA.js";import{atomicWriteFileSync}from"./chunk-2GF3E5MI.js";import{writeStderrLine}from"./chunk-M4ECEHLX.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{FatalConfigError,getErrorMessage}from"./chunk-E7MYPQGV.js";import{require_proper_lockfile}from"./chunk-YIW3H46P.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import*as fs4 from"node:fs";import*as path3 from"node:path";init_esbuild_shims();import*as fs2 from"node:fs";import{isDeepStrictEqual}from"node:util";init_esbuild_shims();init_esbuild_shims();init_esbuild_shims();function createScanner(text,ignoreTrivia=false){const len=text.length;let pos=0,value="",tokenOffset=0,token=16,lineNumber=0,lineStartOffset=0,tokenLineStartOffset=0,prevTokenLineStartOffset=0,scanError=0;function scanHexDigits(count,exact){let digits=0;let value2=0;while(digits<count||!exact){let ch=text.charCodeAt(pos);if(ch>=48&&ch<=57){value2=value2*16+ch-48}else if(ch>=65&&ch<=70){value2=value2*16+ch-65+10}else if(ch>=97&&ch<=102){value2=value2*16+ch-97+10}else{break}pos++;digits++}if(digits<count){value2=-1}return value2}__name(scanHexDigits,"scanHexDigits");function setPosition(newPosition){pos=newPosition;value="";tokenOffset=0;token=16;scanError=0}__name(setPosition,"setPosition");function scanNumber(){let start=pos;if(text.charCodeAt(pos)===48){pos++}else{pos++;while(pos<text.length&&isDigit(text.charCodeAt(pos))){pos++}}if(pos<text.length&&text.charCodeAt(pos)===46){pos++;if(pos<text.length&&isDigit(text.charCodeAt(pos))){pos++;while(pos<text.length&&isDigit(text.charCodeAt(pos))){pos++}}else{scanError=3;return text.substring(start,pos)}}let end=pos;if(pos<text.length&&(text.charCodeAt(pos)===69||text.charCodeAt(pos)===101)){pos++;if(pos<text.length&&text.charCodeAt(pos)===43||text.charCodeAt(pos)===45){pos++}if(pos<text.length&&isDigit(text.charCodeAt(pos))){pos++;while(pos<text.length&&isDigit(text.charCodeAt(pos))){pos++}end=pos}else{scanError=3}}return text.substring(start,end)}__name(scanNumber,"scanNumber");function scanString(){let result="",start=pos;while(true){if(pos>=len){result+=text.substring(start,pos);scanError=2;break}const ch=text.charCodeAt(pos);if(ch===34){result+=text.substring(start,pos);pos++;break}if(ch===92){result+=text.substring(start,pos);pos++;if(pos>=len){scanError=2;break}const ch2=text.charCodeAt(pos++);switch(ch2){case 34:result+='"';break;case 92:result+="\\";break;case 47:result+="/";break;case 98:result+="\b";break;case 102:result+="\f";break;case 110:result+="\n";break;case 114:result+="\r";break;case 116:result+=" ";break;case 117:const ch3=scanHexDigits(4,true);if(ch3>=0){result+=String.fromCharCode(ch3)}else{scanError=4}break;default:scanError=5}start=pos;continue}if(ch>=0&&ch<=31){if(isLineBreak(ch)){result+=text.substring(start,pos);scanError=2;break}else{scanError=6}}pos++}return result}__name(scanString,"scanString");function scanNext(){value="";scanError=0;tokenOffset=pos;lineStartOffset=lineNumber;prevTokenLineStartOffset=tokenLineStartOffset;if(pos>=len){tokenOffset=len;return token=17}let code=text.charCodeAt(pos);if(isWhiteSpace(code)){do{pos++;value+=String.fromCharCode(code);code=text.charCodeAt(pos)}while(isWhiteSpace(code));return token=15}if(isLineBreak(code)){pos++;value+=String.fromCharCode(code);if(code===13&&text.charCodeAt(pos)===10){pos++;value+="\n"}lineNumber++;tokenLineStartOffset=pos;return token=14}switch(code){case 123:pos++;return token=1;case 125:pos++;return token=2;case 91:pos++;return token=3;case 93:pos++;return token=4;case 58:pos++;return token=6;case 44:pos++;return token=5;case 34:pos++;value=scanString();return token=10;case 47:const start=pos-1;if(text.charCodeAt(pos+1)===47){pos+=2;while(pos<len){if(isLineBreak(text.charCodeAt(pos))){break}pos++}value=text.substring(start,pos);return token=12}if(text.charCodeAt(pos+1)===42){pos+=2;const safeLength=len-1;let commentClosed=false;while(pos<safeLength){const ch=text.charCodeAt(pos);if(ch===42&&text.charCodeAt(pos+1)===47){pos+=2;commentClosed=true;break}pos++;if(isLineBreak(ch)){if(ch===13&&text.charCodeAt(pos)===10){pos++}lineNumber++;tokenLineStartOffset=pos}}if(!commentClosed){pos++;scanError=1}value=text.substring(start,pos);return token=13}value+=String.fromCharCode(code);pos++;return token=16;case 45:value+=String.fromCharCode(code);pos++;if(pos===len||!isDigit(text.charCodeAt(pos))){return token=16}case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:value+=scanNumber();return token=11;default:while(pos<len&&isUnknownContentCharacter(code)){pos++;code=text.charCodeAt(pos)}if(tokenOffset!==pos){value=text.substring(tokenOffset,pos);switch(value){case"true":return token=8;case"false":return token=9;case"null":return token=7}return token=16}value+=String.fromCharCode(code);pos++;return token=16}}__name(scanNext,"scanNext");function isUnknownContentCharacter(code){if(isWhiteSpace(code)||isLineBreak(code)){return false}switch(code){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return false}return true}__name(isUnknownContentCharacter,"isUnknownContentCharacter");function scanNextNonTrivia(){let result;do{result=scanNext()}while(result>=12&&result<=15);return result}__name(scanNextNonTrivia,"scanNextNonTrivia");return{setPosition,getPosition:__name(()=>pos,"getPosition"),scan:ignoreTrivia?scanNextNonTrivia:scanNext,getToken:__name(()=>token,"getToken"),getTokenValue:__name(()=>value,"getTokenValue"),getTokenOffset:__name(()=>tokenOffset,"getTokenOffset"),getTokenLength:__name(()=>pos-tokenOffset,"getTokenLength"),getTokenStartLine:__name(()=>lineStartOffset,"getTokenStartLine"),getTokenStartCharacter:__name(()=>tokenOffset-prevTokenLineStartOffset,"getTokenStartCharacter"),getTokenError:__name(()=>scanError,"getTokenError")}}__name(createScanner,"createScanner");function isWhiteSpace(ch){return ch===32||ch===9}__name(isWhiteSpace,"isWhiteSpace");function isLineBreak(ch){return ch===10||ch===13}__name(isLineBreak,"isLineBreak");function isDigit(ch){return ch>=48&&ch<=57}__name(isDigit,"isDigit");var CharacterCodes;(function(CharacterCodes2){CharacterCodes2[CharacterCodes2["lineFeed"]=10]="lineFeed";CharacterCodes2[CharacterCodes2["carriageReturn"]=13]="carriageReturn";CharacterCodes2[CharacterCodes2["space"]=32]="space";CharacterCodes2[CharacterCodes2["_0"]=48]="_0";CharacterCodes2[CharacterCodes2["_1"]=49]="_1";CharacterCodes2[CharacterCodes2["_2"]=50]="_2";CharacterCodes2[CharacterCodes2["_3"]=51]="_3";CharacterCodes2[CharacterCodes2["_4"]=52]="_4";CharacterCodes2[CharacterCodes2["_5"]=53]="_5";CharacterCodes2[CharacterCodes2["_6"]=54]="_6";CharacterCodes2[CharacterCodes2["_7"]=55]="_7";CharacterCodes2[CharacterCodes2["_8"]=56]="_8";CharacterCodes2[CharacterCodes2["_9"]=57]="_9";CharacterCodes2[CharacterCodes2["a"]=97]="a";CharacterCodes2[CharacterCodes2["b"]=98]="b";CharacterCodes2[CharacterCodes2["c"]=99]="c";CharacterCodes2[CharacterCodes2["d"]=100]="d";CharacterCodes2[CharacterCodes2["e"]=101]="e";CharacterCodes2[CharacterCodes2["f"]=102]="f";CharacterCodes2[CharacterCodes2["g"]=103]="g";CharacterCodes2[CharacterCodes2["h"]=104]="h";CharacterCodes2[CharacterCodes2["i"]=105]="i";CharacterCodes2[CharacterCodes2["j"]=106]="j";CharacterCodes2[CharacterCodes2["k"]=107]="k";CharacterCodes2[CharacterCodes2["l"]=108]="l";CharacterCodes2[CharacterCodes2["m"]=109]="m";CharacterCodes2[CharacterCodes2["n"]=110]="n";CharacterCodes2[CharacterCodes2["o"]=111]="o";CharacterCodes2[CharacterCodes2["p"]=112]="p";CharacterCodes2[CharacterCodes2["q"]=113]="q";CharacterCodes2[CharacterCodes2["r"]=114]="r";CharacterCodes2[CharacterCodes2["s"]=115]="s";CharacterCodes2[CharacterCodes2["t"]=116]="t";CharacterCodes2[CharacterCodes2["u"]=117]="u";CharacterCodes2[CharacterCodes2["v"]=118]="v";CharacterCodes2[CharacterCodes2["w"]=119]="w";CharacterCodes2[CharacterCodes2["x"]=120]="x";CharacterCodes2[CharacterCodes2["y"]=121]="y";CharacterCodes2[CharacterCodes2["z"]=122]="z";CharacterCodes2[CharacterCodes2["A"]=65]="A";CharacterCodes2[CharacterCodes2["B"]=66]="B";CharacterCodes2[CharacterCodes2["C"]=67]="C";CharacterCodes2[CharacterCodes2["D"]=68]="D";CharacterCodes2[CharacterCodes2["E"]=69]="E";CharacterCodes2[CharacterCodes2["F"]=70]="F";CharacterCodes2[CharacterCodes2["G"]=71]="G";CharacterCodes2[CharacterCodes2["H"]=72]="H";CharacterCodes2[CharacterCodes2["I"]=73]="I";CharacterCodes2[CharacterCodes2["J"]=74]="J";CharacterCodes2[CharacterCodes2["K"]=75]="K";CharacterCodes2[CharacterCodes2["L"]=76]="L";CharacterCodes2[CharacterCodes2["M"]=77]="M";CharacterCodes2[CharacterCodes2["N"]=78]="N";CharacterCodes2[CharacterCodes2["O"]=79]="O";CharacterCodes2[CharacterCodes2["P"]=80]="P";CharacterCodes2[CharacterCodes2["Q"]=81]="Q";CharacterCodes2[CharacterCodes2["R"]=82]="R";CharacterCodes2[CharacterCodes2["S"]=83]="S";CharacterCodes2[CharacterCodes2["T"]=84]="T";CharacterCodes2[CharacterCodes2["U"]=85]="U";CharacterCodes2[CharacterCodes2["V"]=86]="V";CharacterCodes2[CharacterCodes2["W"]=87]="W";CharacterCodes2[CharacterCodes2["X"]=88]="X";CharacterCodes2[CharacterCodes2["Y"]=89]="Y";CharacterCodes2[CharacterCodes2["Z"]=90]="Z";CharacterCodes2[CharacterCodes2["asterisk"]=42]="asterisk";CharacterCodes2[CharacterCodes2["backslash"]=92]="backslash";CharacterCodes2[CharacterCodes2["closeBrace"]=125]="closeBrace";CharacterCodes2[CharacterCodes2["closeBracket"]=93]="closeBracket";CharacterCodes2[CharacterCodes2["colon"]=58]="colon";CharacterCodes2[CharacterCodes2["comma"]=44]="comma";CharacterCodes2[CharacterCodes2["dot"]=46]="dot";CharacterCodes2[CharacterCodes2["doubleQuote"]=34]="doubleQuote";CharacterCodes2[CharacterCodes2["minus"]=45]="minus";CharacterCodes2[CharacterCodes2["openBrace"]=123]="openBrace";CharacterCodes2[CharacterCodes2["openBracket"]=91]="openBracket";CharacterCodes2[CharacterCodes2["plus"]=43]="plus";CharacterCodes2[CharacterCodes2["slash"]=47]="slash";CharacterCodes2[CharacterCodes2["formFeed"]=12]="formFeed";CharacterCodes2[CharacterCodes2["tab"]=9]="tab"})(CharacterCodes||(CharacterCodes={}));init_esbuild_shims();var cachedSpaces=new Array(20).fill(0).map((_,index)=>{return" ".repeat(index)});var maxCachedValues=200;var cachedBreakLinesWithSpaces={" ":{"\n":new Array(maxCachedValues).fill(0).map((_,index)=>{return"\n"+" ".repeat(index)}),"\r":new Array(maxCachedValues).fill(0).map((_,index)=>{return"\r"+" ".repeat(index)}),"\r\n":new Array(maxCachedValues).fill(0).map((_,index)=>{return"\r\n"+" ".repeat(index)})}," ":{"\n":new Array(maxCachedValues).fill(0).map((_,index)=>{return"\n"+" ".repeat(index)}),"\r":new Array(maxCachedValues).fill(0).map((_,index)=>{return"\r"+" ".repeat(index)}),"\r\n":new Array(maxCachedValues).fill(0).map((_,index)=>{return"\r\n"+" ".repeat(index)})}};var supportedEols=["\n","\r","\r\n"];function format(documentText,range,options){let initialIndentLevel;let formatText;let formatTextStart;let rangeStart;let rangeEnd;if(range){rangeStart=range.offset;rangeEnd=rangeStart+range.length;formatTextStart=rangeStart;while(formatTextStart>0&&!isEOL(documentText,formatTextStart-1)){formatTextStart--}let endOffset=rangeEnd;while(endOffset<documentText.length&&!isEOL(documentText,endOffset)){endOffset++}formatText=documentText.substring(formatTextStart,endOffset);initialIndentLevel=computeIndentLevel(formatText,options)}else{formatText=documentText;initialIndentLevel=0;formatTextStart=0;rangeStart=0;rangeEnd=documentText.length}const eol=getEOL(options,documentText);const eolFastPathSupported=supportedEols.includes(eol);let numberLineBreaks=0;let indentLevel=0;let indentValue;if(options.insertSpaces){indentValue=cachedSpaces[options.tabSize||4]??repeat(cachedSpaces[1],options.tabSize||4)}else{indentValue=" "}const indentType=indentValue===" "?" ":" ";let scanner=createScanner(formatText,false);let hasError=false;function newLinesAndIndent(){if(numberLineBreaks>1){return repeat(eol,numberLineBreaks)+repeat(indentValue,initialIndentLevel+indentLevel)}const amountOfSpaces=indentValue.length*(initialIndentLevel+indentLevel);if(!eolFastPathSupported||amountOfSpaces>cachedBreakLinesWithSpaces[indentType][eol].length){return eol+repeat(indentValue,initialIndentLevel+indentLevel)}if(amountOfSpaces<=0){return eol}return cachedBreakLinesWithSpaces[indentType][eol][amountOfSpaces]}__name(newLinesAndIndent,"newLinesAndIndent");function scanNext(){let token=scanner.scan();numberLineBreaks=0;while(token===15||token===14){if(token===14&&options.keepLines){numberLineBreaks+=1}else if(token===14){numberLineBreaks=1}token=scanner.scan()}hasError=token===16||scanner.getTokenError()!==0;return token}__name(scanNext,"scanNext");const editOperations=[];function addEdit(text,startOffset,endOffset){if(!hasError&&(!range||startOffset<rangeEnd&&endOffset>rangeStart)&&documentText.substring(startOffset,endOffset)!==text){editOperations.push({offset:startOffset,length:endOffset-startOffset,content:text})}}__name(addEdit,"addEdit");let firstToken=scanNext();if(options.keepLines&&numberLineBreaks>0){addEdit(repeat(eol,numberLineBreaks),0,0)}if(firstToken!==17){let firstTokenStart=scanner.getTokenOffset()+formatTextStart;let initialIndent=indentValue.length*initialIndentLevel<20&&options.insertSpaces?cachedSpaces[indentValue.length*initialIndentLevel]:repeat(indentValue,initialIndentLevel);addEdit(initialIndent,formatTextStart,firstTokenStart)}while(firstToken!==17){let firstTokenEnd=scanner.getTokenOffset()+scanner.getTokenLength()+formatTextStart;let secondToken=scanNext();let replaceContent="";let needsLineBreak=false;while(numberLineBreaks===0&&(secondToken===12||secondToken===13)){let commentTokenStart=scanner.getTokenOffset()+formatTextStart;addEdit(cachedSpaces[1],firstTokenEnd,commentTokenStart);firstTokenEnd=scanner.getTokenOffset()+scanner.getTokenLength()+formatTextStart;needsLineBreak=secondToken===12;replaceContent=needsLineBreak?newLinesAndIndent():"";secondToken=scanNext()}if(secondToken===2){if(firstToken!==1){indentLevel--};if(options.keepLines&&numberLineBreaks>0||!options.keepLines&&firstToken!==1){replaceContent=newLinesAndIndent()}else if(options.keepLines){replaceContent=cachedSpaces[1]}}else if(secondToken===4){if(firstToken!==3){indentLevel--};if(options.keepLines&&numberLineBreaks>0||!options.keepLines&&firstToken!==3){replaceContent=newLinesAndIndent()}else if(options.keepLines){replaceContent=cachedSpaces[1]}}else{switch(firstToken){case 3:case 1:indentLevel++;if(options.keepLines&&numberLineBreaks>0||!options.keepLines){replaceContent=newLinesAndIndent()}else{replaceContent=cachedSpaces[1]}break;case 5:if(options.keepLines&&numberLineBreaks>0||!options.keepLines){replaceContent=newLinesAndIndent()}else{replaceContent=cachedSpaces[1]}break;case 12:replaceContent=newLinesAndIndent();break;case 13:if(numberLineBreaks>0){replaceContent=newLinesAndIndent()}else if(!needsLineBreak){replaceContent=cachedSpaces[1]}break;case 6:if(options.keepLines&&numberLineBreaks>0){replaceContent=newLinesAndIndent()}else if(!needsLineBreak){replaceContent=cachedSpaces[1]}break;case 10:if(options.keepLines&&numberLineBreaks>0){replaceContent=newLinesAndIndent()}else if(secondToken===6&&!needsLineBreak){replaceContent=""}break;case 7:case 8:case 9:case 11:case 2:case 4:if(options.keepLines&&numberLineBreaks>0){replaceContent=newLinesAndIndent()}else{if((secondToken===12||secondToken===13)&&!needsLineBreak){replaceContent=cachedSpaces[1]}else if(secondToken!==5&&secondToken!==17){hasError=true}}break;case 16:hasError=true;break}if(numberLineBreaks>0&&(secondToken===12||secondToken===13)){replaceContent=newLinesAndIndent()}}if(secondToken===17){if(options.keepLines&&numberLineBreaks>0){replaceContent=newLinesAndIndent()}else{replaceContent=options.insertFinalNewline?eol:""}}const secondTokenStart=scanner.getTokenOffset()+formatTextStart;addEdit(replaceContent,firstTokenEnd,secondTokenStart);firstToken=secondToken}return editOperations}__name(format,"format");function repeat(s,count){let result="";for(let i=0;i<count;i++){result+=s}return result}__name(repeat,"repeat");function computeIndentLevel(content,options){let i=0;let nChars=0;const tabSize=options.tabSize||4;while(i<content.length){let ch=content.charAt(i);if(ch===cachedSpaces[1]){nChars++}else if(ch===" "){nChars+=tabSize}else{break}i++}return Math.floor(nChars/tabSize)}__name(computeIndentLevel,"computeIndentLevel");function getEOL(options,text){for(let i=0;i<text.length;i++){const ch=text.charAt(i);if(ch==="\r"){if(i+1<text.length&&text.charAt(i+1)==="\n"){return"\r\n"}return"\r"}else if(ch==="\n"){return"\n"}}return options&&options.eol||"\n"}__name(getEOL,"getEOL");function isEOL(text,offset){return"\r\n".indexOf(text.charAt(offset))!==-1}__name(isEOL,"isEOL");init_esbuild_shims();init_esbuild_shims();var ParseOptions;(function(ParseOptions2){ParseOptions2.DEFAULT={allowTrailingComma:false}})(ParseOptions||(ParseOptions={}));function parseTree(text,errors=[],options=ParseOptions.DEFAULT){let currentParent={type:"array",offset:-1,length:-1,children:[],parent:void 0};function ensurePropertyComplete(endOffset){if(currentParent.type==="property"){currentParent.length=endOffset-currentParent.offset;currentParent=currentParent.parent}}__name(ensurePropertyComplete,"ensurePropertyComplete");function onValue(valueNode){currentParent.children.push(valueNode);return valueNode}__name(onValue,"onValue");const visitor={onObjectBegin:__name(offset=>{currentParent=onValue({type:"object",offset,length:-1,parent:currentParent,children:[]})},"onObjectBegin"),onObjectProperty:__name((name,offset,length)=>{currentParent=onValue({type:"property",offset,length:-1,parent:currentParent,children:[]});currentParent.children.push({type:"string",value:name,offset,length,parent:currentParent})},"onObjectProperty"),onObjectEnd:__name((offset,length)=>{ensurePropertyComplete(offset+length);currentParent.length=offset+length-currentParent.offset;currentParent=currentParent.parent;ensurePropertyComplete(offset+length)},"onObjectEnd"),onArrayBegin:__name((offset,length)=>{currentParent=onValue({type:"array",offset,length:-1,parent:currentParent,children:[]})},"onArrayBegin"),onArrayEnd:__name((offset,length)=>{currentParent.length=offset+length-currentParent.offset;currentParent=currentParent.parent;ensurePropertyComplete(offset+length)},"onArrayEnd"),onLiteralValue:__name((value,offset,length)=>{onValue({type:getNodeType(value),offset,length,parent:currentParent,value});ensurePropertyComplete(offset+length)},"onLiteralValue"),onSeparator:__name((sep,offset,length)=>{if(currentParent.type==="property"){if(sep===":"){currentParent.colonOffset=offset}else if(sep===","){ensurePropertyComplete(offset)}}},"onSeparator"),onError:__name((error,offset,length)=>{errors.push({error,offset,length})},"onError")};visit(text,visitor,options);const result=currentParent.children[0];if(result){delete result.parent}return result}__name(parseTree,"parseTree");function findNodeAtLocation(root,path4){if(!root){return void 0}let node=root;for(let segment of path4){if(typeof segment==="string"){if(node.type!=="object"||!Array.isArray(node.children)){return void 0}let found=false;for(const propertyNode of node.children){if(Array.isArray(propertyNode.children)&&propertyNode.children[0].value===segment&&propertyNode.children.length===2){node=propertyNode.children[1];found=true;break}}if(!found){return void 0}}else{const index=segment;if(node.type!=="array"||index<0||!Array.isArray(node.children)||index>=node.children.length){return void 0}node=node.children[index]}}return node}__name(findNodeAtLocation,"findNodeAtLocation");function getNodeValue(node){switch(node.type){case"array":return node.children.map(getNodeValue);case"object":const obj=Object.create(null);for(let prop of node.children){const valueNode=prop.children[1];if(valueNode){obj[prop.children[0].value]=getNodeValue(valueNode)}}return obj;case"null":case"string":case"number":case"boolean":return node.value;default:return void 0}}__name(getNodeValue,"getNodeValue");function visit(text,visitor,options=ParseOptions.DEFAULT){const _scanner=createScanner(text,false);const _jsonPath=[];let suppressedCallbacks=0;function toNoArgVisit(visitFunction){return visitFunction?()=>suppressedCallbacks===0&&visitFunction(_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter()):()=>true}__name(toNoArgVisit,"toNoArgVisit");function toOneArgVisit(visitFunction){return visitFunction?arg=>suppressedCallbacks===0&&visitFunction(arg,_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter()):()=>true}__name(toOneArgVisit,"toOneArgVisit");function toOneArgVisitWithPath(visitFunction){return visitFunction?arg=>suppressedCallbacks===0&&visitFunction(arg,_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter(),()=>_jsonPath.slice()):()=>true}__name(toOneArgVisitWithPath,"toOneArgVisitWithPath");function toBeginVisit(visitFunction){return visitFunction?()=>{if(suppressedCallbacks>0){suppressedCallbacks++}else{let cbReturn=visitFunction(_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter(),()=>_jsonPath.slice());if(cbReturn===false){suppressedCallbacks=1}}}:()=>true}__name(toBeginVisit,"toBeginVisit");function toEndVisit(visitFunction){return visitFunction?()=>{if(suppressedCallbacks>0){suppressedCallbacks--}if(suppressedCallbacks===0){visitFunction(_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter())}}:()=>true}__name(toEndVisit,"toEndVisit");const onObjectBegin=toBeginVisit(visitor.onObjectBegin),onObjectProperty=toOneArgVisitWithPath(visitor.onObjectProperty),onObjectEnd=toEndVisit(visitor.onObjectEnd),onArrayBegin=toBeginVisit(visitor.onArrayBegin),onArrayEnd=toEndVisit(visitor.onArrayEnd),onLiteralValue=toOneArgVisitWithPath(visitor.onLiteralValue),onSeparator=toOneArgVisit(visitor.onSeparator),onComment=toNoArgVisit(visitor.onComment),onError=toOneArgVisit(visitor.onError);const disallowComments=options&&options.disallowComments;const allowTrailingComma=options&&options.allowTrailingComma;function scanNext(){while(true){const token=_scanner.scan();switch(_scanner.getTokenError()){case 4:handleError(14);break;case 5:handleError(15);break;case 3:handleError(13);break;case 1:if(!disallowComments){handleError(11)}break;case 2:handleError(12);break;case 6:handleError(16);break}switch(token){case 12:case 13:if(disallowComments){handleError(10)}else{onComment()}break;case 16:handleError(1);break;case 15:case 14:break;default:return token}}}__name(scanNext,"scanNext");function handleError(error,skipUntilAfter=[],skipUntil=[]){onError(error);if(skipUntilAfter.length+skipUntil.length>0){let token=_scanner.getToken();while(token!==17){if(skipUntilAfter.indexOf(token)!==-1){scanNext();break}else if(skipUntil.indexOf(token)!==-1){break}token=scanNext()}}}__name(handleError,"handleError");function parseString(isValue){const value=_scanner.getTokenValue();if(isValue){onLiteralValue(value)}else{onObjectProperty(value);_jsonPath.push(value)}scanNext();return true}__name(parseString,"parseString");function parseLiteral(){switch(_scanner.getToken()){case 11:const tokenValue=_scanner.getTokenValue();let value=Number(tokenValue);if(isNaN(value)){handleError(2);value=0}onLiteralValue(value);break;case 7:onLiteralValue(null);break;case 8:onLiteralValue(true);break;case 9:onLiteralValue(false);break;default:return false}scanNext();return true}__name(parseLiteral,"parseLiteral");function parseProperty(){if(_scanner.getToken()!==10){handleError(3,[],[2,5]);return false}parseString(false);if(_scanner.getToken()===6){onSeparator(":");scanNext();if(!parseValue()){handleError(4,[],[2,5])}}else{handleError(5,[],[2,5])}_jsonPath.pop();return true}__name(parseProperty,"parseProperty");function parseObject(){onObjectBegin();scanNext();let needsComma=false;while(_scanner.getToken()!==2&&_scanner.getToken()!==17){if(_scanner.getToken()===5){if(!needsComma){handleError(4,[],[])}onSeparator(",");scanNext();if(_scanner.getToken()===2&&allowTrailingComma){break}}else if(needsComma){handleError(6,[],[])}if(!parseProperty()){handleError(4,[],[2,5])}needsComma=true}onObjectEnd();if(_scanner.getToken()!==2){handleError(7,[2],[])}else{scanNext()}return true}__name(parseObject,"parseObject");function parseArray(){onArrayBegin();scanNext();let isFirstElement=true;let needsComma=false;while(_scanner.getToken()!==4&&_scanner.getToken()!==17){if(_scanner.getToken()===5){if(!needsComma){handleError(4,[],[])}onSeparator(",");scanNext();if(_scanner.getToken()===4&&allowTrailingComma){break}}else if(needsComma){handleError(6,[],[])}if(isFirstElement){_jsonPath.push(0);isFirstElement=false}else{_jsonPath[_jsonPath.length-1]++}if(!parseValue()){handleError(4,[],[4,5])}needsComma=true}onArrayEnd();if(!isFirstElement){_jsonPath.pop()}if(_scanner.getToken()!==4){handleError(8,[4],[])}else{scanNext()}return true}__name(parseArray,"parseArray");function parseValue(){switch(_scanner.getToken()){case 3:return parseArray();case 1:return parseObject();case 10:return parseString(true);default:return parseLiteral()}}__name(parseValue,"parseValue");scanNext();if(_scanner.getToken()===17){if(options.allowEmptyContent){return true}handleError(4,[],[]);return false}if(!parseValue()){handleError(4,[],[]);return false}if(_scanner.getToken()!==17){handleError(9,[],[])}return true}__name(visit,"visit");function getNodeType(value){switch(typeof value){case"boolean":return"boolean";case"number":return"number";case"string":return"string";case"object":{if(!value){return"null"}else if(Array.isArray(value)){return"array"}return"object"}default:return"null"}}__name(getNodeType,"getNodeType");function setProperty(text,originalPath,value,options){const path4=originalPath.slice();const errors=[];const root=parseTree(text,errors);let parent=void 0;let lastSegment=void 0;while(path4.length>0){lastSegment=path4.pop();parent=findNodeAtLocation(root,path4);if(parent===void 0&&value!==void 0){if(typeof lastSegment==="string"){value={[lastSegment]:value}}else{value=[value]}}else{break}}if(!parent){if(value===void 0){throw new Error("Can not delete in empty document")}return withFormatting(text,{offset:root?root.offset:0,length:root?root.length:0,content:JSON.stringify(value)},options)}else if(parent.type==="object"&&typeof lastSegment==="string"&&Array.isArray(parent.children)){const existing=findNodeAtLocation(parent,[lastSegment]);if(existing!==void 0){if(value===void 0){if(!existing.parent){throw new Error("Malformed AST")}const propertyIndex=parent.children.indexOf(existing.parent);let removeBegin;let removeEnd=existing.parent.offset+existing.parent.length;if(propertyIndex>0){let previous=parent.children[propertyIndex-1];removeBegin=previous.offset+previous.length}else{removeBegin=parent.offset+1;if(parent.children.length>1){let next=parent.children[1];removeEnd=next.offset}}return withFormatting(text,{offset:removeBegin,length:removeEnd-removeBegin,content:""},options)}else{return withFormatting(text,{offset:existing.offset,length:existing.length,content:JSON.stringify(value)},options)}}else{if(value===void 0){return[]}const newProperty=`${JSON.stringify(lastSegment)}: ${JSON.stringify(value)}`;const index=options.getInsertionIndex?options.getInsertionIndex(parent.children.map(p=>p.children[0].value)):parent.children.length;let edit;if(index>0){let previous=parent.children[index-1];edit={offset:previous.offset+previous.length,length:0,content:","+newProperty}}else if(parent.children.length===0){edit={offset:parent.offset+1,length:0,content:newProperty}}else{edit={offset:parent.offset+1,length:0,content:newProperty+","}}return withFormatting(text,edit,options)}}else if(parent.type==="array"&&typeof lastSegment==="number"&&Array.isArray(parent.children)){const insertIndex=lastSegment;if(insertIndex===-1){const newProperty=`${JSON.stringify(value)}`;let edit;if(parent.children.length===0){edit={offset:parent.offset+1,length:0,content:newProperty}}else{const previous=parent.children[parent.children.length-1];edit={offset:previous.offset+previous.length,length:0,content:","+newProperty}}return withFormatting(text,edit,options)}else if(value===void 0&&parent.children.length>=0){const removalIndex=lastSegment;const toRemove=parent.children[removalIndex];let edit;if(parent.children.length===1){edit={offset:parent.offset+1,length:parent.length-2,content:""}}else if(parent.children.length-1===removalIndex){let previous=parent.children[removalIndex-1];let offset=previous.offset+previous.length;let parentEndOffset=parent.offset+parent.length;edit={offset,length:parentEndOffset-2-offset,content:""}}else{edit={offset:toRemove.offset,length:parent.children[removalIndex+1].offset-toRemove.offset,content:""}}return withFormatting(text,edit,options)}else if(value!==void 0){let edit;const newProperty=`${JSON.stringify(value)}`;if(!options.isArrayInsertion&&parent.children.length>lastSegment){const toModify=parent.children[lastSegment];edit={offset:toModify.offset,length:toModify.length,content:newProperty}}else if(parent.children.length===0||lastSegment===0){edit={offset:parent.offset+1,length:0,content:parent.children.length===0?newProperty:newProperty+","}}else{const index=lastSegment>parent.children.length?parent.children.length:lastSegment;const previous=parent.children[index-1];edit={offset:previous.offset+previous.length,length:0,content:","+newProperty}}return withFormatting(text,edit,options)}else{throw new Error(`Can not ${value===void 0?"remove":options.isArrayInsertion?"insert":"modify"} Array index ${insertIndex} as length is not sufficient`)}}else{throw new Error(`Can not add ${typeof lastSegment!=="number"?"index":"property"} to parent of type ${parent.type}`)}}__name(setProperty,"setProperty");function withFormatting(text,edit,options){if(!options.formattingOptions){return[edit]}let newText=applyEdit(text,edit);let begin=edit.offset;let end=edit.offset+edit.content.length;if(edit.length===0||edit.content.length===0){while(begin>0&&!isEOL(newText,begin-1)){begin--}while(end<newText.length&&!isEOL(newText,end)){end++}}const edits=format(newText,{offset:begin,length:end-begin},{...options.formattingOptions,keepLines:false});for(let i=edits.length-1;i>=0;i--){const edit2=edits[i];newText=applyEdit(newText,edit2);begin=Math.min(begin,edit2.offset);end=Math.max(end,edit2.offset+edit2.length);end+=edit2.content.length-edit2.length}const editLength=text.length-(newText.length-end)-begin;return[{offset:begin,length:editLength,content:newText.substring(begin,end)}]}__name(withFormatting,"withFormatting");function applyEdit(text,edit){return text.substring(0,edit.offset)+edit.content+text.substring(edit.offset+edit.length)}__name(applyEdit,"applyEdit");var ScanError;(function(ScanError2){ScanError2[ScanError2["None"]=0]="None";ScanError2[ScanError2["UnexpectedEndOfComment"]=1]="UnexpectedEndOfComment";ScanError2[ScanError2["UnexpectedEndOfString"]=2]="UnexpectedEndOfString";ScanError2[ScanError2["UnexpectedEndOfNumber"]=3]="UnexpectedEndOfNumber";ScanError2[ScanError2["InvalidUnicode"]=4]="InvalidUnicode";ScanError2[ScanError2["InvalidEscapeCharacter"]=5]="InvalidEscapeCharacter";ScanError2[ScanError2["InvalidCharacter"]=6]="InvalidCharacter"})(ScanError||(ScanError={}));var SyntaxKind;(function(SyntaxKind2){SyntaxKind2[SyntaxKind2["OpenBraceToken"]=1]="OpenBraceToken";SyntaxKind2[SyntaxKind2["CloseBraceToken"]=2]="CloseBraceToken";SyntaxKind2[SyntaxKind2["OpenBracketToken"]=3]="OpenBracketToken";SyntaxKind2[SyntaxKind2["CloseBracketToken"]=4]="CloseBracketToken";SyntaxKind2[SyntaxKind2["CommaToken"]=5]="CommaToken";SyntaxKind2[SyntaxKind2["ColonToken"]=6]="ColonToken";SyntaxKind2[SyntaxKind2["NullKeyword"]=7]="NullKeyword";SyntaxKind2[SyntaxKind2["TrueKeyword"]=8]="TrueKeyword";SyntaxKind2[SyntaxKind2["FalseKeyword"]=9]="FalseKeyword";SyntaxKind2[SyntaxKind2["StringLiteral"]=10]="StringLiteral";SyntaxKind2[SyntaxKind2["NumericLiteral"]=11]="NumericLiteral";SyntaxKind2[SyntaxKind2["LineCommentTrivia"]=12]="LineCommentTrivia";SyntaxKind2[SyntaxKind2["BlockCommentTrivia"]=13]="BlockCommentTrivia";SyntaxKind2[SyntaxKind2["LineBreakTrivia"]=14]="LineBreakTrivia";SyntaxKind2[SyntaxKind2["Trivia"]=15]="Trivia";SyntaxKind2[SyntaxKind2["Unknown"]=16]="Unknown";SyntaxKind2[SyntaxKind2["EOF"]=17]="EOF"})(SyntaxKind||(SyntaxKind={}));var parseTree2=parseTree;var findNodeAtLocation2=findNodeAtLocation;var getNodeValue2=getNodeValue;var ParseErrorCode;(function(ParseErrorCode2){ParseErrorCode2[ParseErrorCode2["InvalidSymbol"]=1]="InvalidSymbol";ParseErrorCode2[ParseErrorCode2["InvalidNumberFormat"]=2]="InvalidNumberFormat";ParseErrorCode2[ParseErrorCode2["PropertyNameExpected"]=3]="PropertyNameExpected";ParseErrorCode2[ParseErrorCode2["ValueExpected"]=4]="ValueExpected";ParseErrorCode2[ParseErrorCode2["ColonExpected"]=5]="ColonExpected";ParseErrorCode2[ParseErrorCode2["CommaExpected"]=6]="CommaExpected";ParseErrorCode2[ParseErrorCode2["CloseBraceExpected"]=7]="CloseBraceExpected";ParseErrorCode2[ParseErrorCode2["CloseBracketExpected"]=8]="CloseBracketExpected";ParseErrorCode2[ParseErrorCode2["EndOfFileExpected"]=9]="EndOfFileExpected";ParseErrorCode2[ParseErrorCode2["InvalidCommentToken"]=10]="InvalidCommentToken";ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfComment"]=11]="UnexpectedEndOfComment";ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfString"]=12]="UnexpectedEndOfString";ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfNumber"]=13]="UnexpectedEndOfNumber";ParseErrorCode2[ParseErrorCode2["InvalidUnicode"]=14]="InvalidUnicode";ParseErrorCode2[ParseErrorCode2["InvalidEscapeCharacter"]=15]="InvalidEscapeCharacter";ParseErrorCode2[ParseErrorCode2["InvalidCharacter"]=16]="InvalidCharacter"})(ParseErrorCode||(ParseErrorCode={}));function printParseErrorCode(code){switch(code){case 1:return"InvalidSymbol";case 2:return"InvalidNumberFormat";case 3:return"PropertyNameExpected";case 4:return"ValueExpected";case 5:return"ColonExpected";case 6:return"CommaExpected";case 7:return"CloseBraceExpected";case 8:return"CloseBracketExpected";case 9:return"EndOfFileExpected";case 10:return"InvalidCommentToken";case 11:return"UnexpectedEndOfComment";case 12:return"UnexpectedEndOfString";case 13:return"UnexpectedEndOfNumber";case 14:return"InvalidUnicode";case 15:return"InvalidEscapeCharacter";case 16:return"InvalidCharacter"}return"<unknown ParseErrorCode>"}__name(printParseErrorCode,"printParseErrorCode");function modify(text,path4,value,options){return setProperty(text,path4,value,options)}__name(modify,"modify");function applyEdits(text,edits){let sortedEdits=edits.slice(0).sort((a,b)=>{const diff=a.offset-b.offset;if(diff===0){return a.length-b.length}return diff});let lastModifiedOffset=text.length;for(let i=sortedEdits.length-1;i>=0;i--){let e=sortedEdits[i];if(e.offset+e.length<=lastModifiedOffset){text=applyEdit(text,e)}else{throw new Error("Overlapping edit")}lastModifiedOffset=e.offset}return text}__name(applyEdits,"applyEdits");init_esbuild_shims();import*as fs from"node:fs";import path from"node:path";function writeWithBackupSync(targetPath,content,options={}){const{backupSuffix=".orig",encoding="utf-8"}=options;const existing=fs.existsSync(targetPath)?fs.statSync(targetPath):void 0;if(existing?.isDirectory()){throw new Error(`Cannot write to '${targetPath}' because it is a directory`)}const workingDirectory=fs.mkdtempSync(`${targetPath}.write-`);const basename=path.basename(targetPath);const tempPath=path.join(workingDirectory,`${basename}.tmp`);const backupPath=path.join(workingDirectory,`${basename}${backupSuffix}`);let backupCreated=false;try{const mode=existing&&fs.lstatSync(targetPath,{throwIfNoEntry:false})?.isFile()?existing.mode&511:void 0;fs.writeFileSync(tempPath,content,{encoding,flag:"wx",flush:true,mode});if(mode!==void 0){try{fs.chmodSync(tempPath,mode)}catch(error){const code=error instanceof Error&&"code"in error?error.code:void 0;if(code!=="ENOSYS"&&code!=="ENOTSUP"&&code!=="EPERM"||(fs.statSync(tempPath).mode&511&~mode)!==0){throw error}}}if(fs.existsSync(targetPath)){try{fs.copyFileSync(targetPath,backupPath,fs.constants.COPYFILE_EXCL);backupCreated=true}catch(backupError){throw new Error(`Failed to backup existing file: ${backupError instanceof Error?backupError.message:String(backupError)}`)}}fs.renameSync(tempPath,targetPath)}catch(error){const recoveryRetained=backupCreated&&!sameContents(backupPath,targetPath);try{if(recoveryRetained){fs.unlinkSync(tempPath)}else{fs.rmSync(workingDirectory,{recursive:true,force:true})}}catch{}if(recoveryRetained){throw new Error(`Failed to write file: ${error instanceof Error?error.message:String(error)}. Recovery copy retained at '${backupPath}'; inspect the current target before restoring it.`)}throw error}try{fs.rmSync(workingDirectory,{recursive:true,force:true})}catch{}}__name(writeWithBackupSync,"writeWithBackupSync");function sameContents(first,second){try{return fs.readFileSync(first).equals(fs.readFileSync(second))}catch{return false}}__name(sameContents,"sameContents");var PARSE_OPTIONS={allowTrailingComma:true};function updateSettingsFilePreservingFormat(filePath,updates,sync=false,replacePath=[]){if(!fs2.existsSync(filePath)){const content=JSON.stringify(updates,null,2);writeWithBackupSync(filePath,content);return true}const originalContent=fs2.readFileSync(filePath,"utf-8");try{parseJsoncObject(originalContent)}catch(_error){writeStderrLine("Error parsing settings file.");writeStderrLine(`Settings file may be corrupted: ${_error instanceof Error?_error.message:String(_error)}`);return false}let updatedContent;try{updatedContent=updateJsoncContent(originalContent,updates,sync,replacePath)}catch(validationError){writeStderrLine("Error: Refusing to write settings file \u2014 the result would not be valid JSON.");writeStderrLine(validationError instanceof Error?validationError.message:String(validationError));return false}writeWithBackupSync(filePath,updatedContent);return true}__name(updateSettingsFilePreservingFormat,"updateSettingsFilePreservingFormat");function parseJsoncObject(content){const errors=[];const root=parseTree2(stripBom(content),errors,PARSE_OPTIONS);if(errors.length>0){const error=errors[0];throw new Error(`${printParseErrorCode(error.error)} at offset ${error.offset}`)}if(root?.type!=="object"){throw new Error("JSONC document root is not a JSON object.")}return JSON.parse(JSON.stringify(getNodeValue2(root)))}__name(parseJsoncObject,"parseJsoncObject");function updateJsoncContent(content,updates,sync=false,replacePath=[]){const bom=content.startsWith("\uFEFF")?"\uFEFF":"";const editableContent=stripBom(content);const parsed=parseJsoncObject(editableContent);const targetWithUndefined=applyUpdates(structuredClone(parsed),updates,sync,replacePath);const target=JSON.parse(JSON.stringify(targetWithUndefined));const options={formattingOptions:detectFormattingOptions(editableContent)};let updated=normalizeDuplicateProperties(editableContent,options);const current=parseJsoncObject(updated);for(const operation of collectOperations(current,target)){if(operation.value===void 0){updated=removeTrailingInlineComment(updated,operation.path)}updated=applyEdits(updated,modify(updated,operation.path,operation.value,options))}const reparsed=parseJsoncObject(updated);if(!isDeepStrictEqual(reparsed,target)){throw new Error("Edited JSONC does not match the intended settings.")}return bom+updated}__name(updateJsoncContent,"updateJsoncContent");function applyUpdates(current,updates,sync=false,replacePath=[],currentPath=[]){const result=current;if(sync){const keysToRemove=Object.keys(result).filter(key=>!Object.hasOwn(updates,key));for(const key of keysToRemove){delete result[key]}}for(const key of Object.getOwnPropertyNames(updates)){if(key==="__proto__"||key==="constructor"||key==="prototype"){continue}const value=updates[key];const nextPath=[...currentPath,key];const valueIsObject=typeof value==="object"&&value!==null&&!Array.isArray(value)&&Object.keys(value).length>0;if(pathsEqual(nextPath,replacePath)){result[key]=valueIsObject?applyUpdates({},value):value;continue}if(valueIsObject&&(typeof result[key]!=="object"||result[key]===null||Array.isArray(result[key]))){result[key]=applyUpdates({},value,sync,replacePath,nextPath)}else if(valueIsObject&&typeof result[key]==="object"&&result[key]!==null&&!Array.isArray(result[key])){result[key]=applyUpdates(result[key],value,sync,replacePath,nextPath)}else{result[key]=value}}return result}__name(applyUpdates,"applyUpdates");function stripBom(content){return content.startsWith("\uFEFF")?content.slice(1):content}__name(stripBom,"stripBom");function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord,"isRecord");function detectFormattingOptions(content){const root=parseTree2(content,[],PARSE_OPTIONS);const firstKey=root?.children?.[0]?.children?.[0];const lineStart=firstKey===void 0?-1:content.lastIndexOf("\n",firstKey.offset-1);const candidate=firstKey===void 0?void 0:content.slice(lineStart+1,firstKey.offset);const indentation=candidate!==void 0&&/^[ \t]*$/.test(candidate)?candidate:" ";return{eol:content.includes("\r\n")?"\r\n":"\n",insertSpaces:!indentation.startsWith(" "),tabSize:indentation.startsWith(" ")?1:indentation.length,insertFinalNewline:content.endsWith("\n")}}__name(detectFormattingOptions,"detectFormattingOptions");function collectOperations(current,target,path4=[],operations=[]){for(const key of Object.keys(current)){if(!Object.hasOwn(target,key)){operations.push({path:[...path4,key],value:void 0})}}for(const key of Object.keys(target)){const nextPath=[...path4,key];if(!Object.hasOwn(current,key)){operations.push({path:nextPath,value:target[key]})}else if(isRecord(current[key])&&isRecord(target[key])){collectOperations(current[key],target[key],nextPath,operations)}else if(!isDeepStrictEqual(current[key],target[key])){operations.push({path:nextPath,value:target[key]})}}return operations}__name(collectOperations,"collectOperations");function findDuplicateProperty(node,path4=[]){if(node.type!=="object"||node.children===void 0){return void 0}const properties=new Map;for(const property of node.children){const keyNode=property.children?.[0];const key=keyNode?.value;if(typeof key!=="string"||keyNode===void 0){continue}const previous=properties.get(key);if(previous!==void 0){return{objectPath:[...path4],keyNode:previous,propertyNames:new Set(properties.keys())}}properties.set(key,keyNode)}for(const property of node.children){const key=property.children?.[0]?.value;const valueNode=property.children?.[1];if(typeof key!=="string"||valueNode===void 0){continue}const duplicate=findDuplicateProperty(valueNode,[...path4,key]);if(duplicate!==void 0){return duplicate}}return void 0}__name(findDuplicateProperty,"findDuplicateProperty");function normalizeDuplicateProperties(content,options){let normalized=content;let duplicateIndex=0;while(true){const root=parseTree2(normalized,[],PARSE_OPTIONS);if(root===void 0){return normalized}const duplicate=findDuplicateProperty(root);if(duplicate===void 0){return normalized}let temporaryKey;do{temporaryKey=`__qwen_duplicate_${duplicateIndex}`;duplicateIndex+=1}while(duplicate.propertyNames.has(temporaryKey));let renamed=normalized.slice(0,duplicate.keyNode.offset)+JSON.stringify(temporaryKey)+normalized.slice(duplicate.keyNode.offset+duplicate.keyNode.length);renamed=removeTrailingInlineComment(renamed,[...duplicate.objectPath,temporaryKey]);normalized=applyEdits(renamed,modify(renamed,[...duplicate.objectPath,temporaryKey],void 0,options))}}__name(normalizeDuplicateProperties,"normalizeDuplicateProperties");function removeTrailingInlineComment(content,path4){const root=parseTree2(content,[],PARSE_OPTIONS);if(root===void 0){return content}const node=findNodeAtLocation2(root,[...path4]);if(node===void 0){return content}const tail=content.slice(node.offset+node.length);const match=tail.match(/^[ \t]*(?:,[ \t]*)?(\/\/[^\r\n]*|\/\*[\s\S]*?\*\/)/);const comment=match?.[1];if(comment===void 0||match===null){return content}const commentOffset=node.offset+node.length+match[0].indexOf(comment);return content.slice(0,commentOffset)+content.slice(commentOffset+comment.length)}__name(removeTrailingInlineComment,"removeTrailingInlineComment");function pathsEqual(left,right){return left.length===right.length&&left.every((segment,index)=>segment===right[index])}__name(pathsEqual,"pathsEqual");init_esbuild_shims();import*as fs3 from"node:fs";import*as path2 from"node:path";function isWorkflowAncestorDirectorySafe(directory){if(process.platform==="win32")return true;for(const location of[directory,path2.join(directory,".qwen"),path2.join(directory,".qwen","workflows")]){try{if((fs3.statSync(location).mode&2)!==0)return false}catch(error){const code=error.code;if(location===directory)return false;if(code==="ENOENT"||code==="ENOTDIR")break;return false}}return true}__name(isWorkflowAncestorDirectorySafe,"isWorkflowAncestorDirectorySafe");var debugLogger=createDebugLogger("TRUSTED_FOLDERS");var TRUSTED_FOLDERS_FILENAME="trustedFolders.json";function getTrustedFoldersPath(){if(process.env["QWEN_CODE_TRUSTED_FOLDERS_PATH"]){return process.env["QWEN_CODE_TRUSTED_FOLDERS_PATH"]}return path3.join(Storage.getGlobalQwenDir(),TRUSTED_FOLDERS_FILENAME)}__name(getTrustedFoldersPath,"getTrustedFoldersPath");var TrustLevel=(TrustLevel2=>{TrustLevel2["TRUST_FOLDER"]="TRUST_FOLDER";TrustLevel2["TRUST_PARENT"]="TRUST_PARENT";TrustLevel2["DO_NOT_TRUST"]="DO_NOT_TRUST";return TrustLevel2})(TrustLevel||{});var trustedFoldersChangeListeners=new Set;function onTrustedFoldersChanged(listener){trustedFoldersChangeListeners.add(listener);return()=>trustedFoldersChangeListeners.delete(listener)}__name(onTrustedFoldersChanged,"onTrustedFoldersChanged");function notifyTrustedFoldersChanged(){for(const listener of trustedFoldersChangeListeners)listener()}__name(notifyTrustedFoldersChanged,"notifyTrustedFoldersChanged");var LoadedTrustedFolders=class{constructor(user,errors){this.user=user;this.errors=errors}static{__name(this,"LoadedTrustedFolders")}get rules(){return Object.entries(this.user.config).map(([path4,trustLevel])=>({path:path4,trustLevel}))}isPathTrusted(location){return resolveTrustDecision(buildTrustPrecedenceRules(this.rules),getPathComparisonVariants(location))}setValue(path4,trustLevel,preserveExistingTrust=false){const committedConfig=writeTrustedFolders(this.user.path,diskConfig=>{const existing=diskConfig[path4];if(preserveExistingTrust&&(existing==="TRUST_FOLDER"||existing==="TRUST_PARENT")){return diskConfig}return{...diskConfig,[path4]:trustLevel}});this.user.config=committedConfig;notifyTrustedFoldersChanged()}};var loadedTrustedFolders;function resetTrustedFoldersForTesting(){loadedTrustedFolders=void 0}__name(resetTrustedFoldersForTesting,"resetTrustedFoldersForTesting");function loadTrustedFolders(){loadedTrustedFolders??=readTrustedFoldersFile(false);return loadedTrustedFolders}__name(loadTrustedFolders,"loadTrustedFolders");function loadTrustedFoldersFresh(){return readTrustedFoldersFile(true)}__name(loadTrustedFoldersFresh,"loadTrustedFoldersFresh");function readTrustedFoldersFile(validateRules){const errors=[];let userConfig={};const userPath=getTrustedFoldersPath();try{if(fs4.existsSync(userPath)){const content=fs4.readFileSync(userPath,"utf-8");const parsed=parseJsoncObject(content);if(validateRules)assertTrustedFoldersConfig(parsed);userConfig=parsed}}catch(error){errors.push({message:error instanceof Error&&error.message==="JSONC document root is not a JSON object."?"Trusted folders file is not a valid JSON object.":getErrorMessage(error),path:userPath})}return new LoadedTrustedFolders({path:userPath,config:userConfig},errors)}__name(readTrustedFoldersFile,"readTrustedFoldersFile");function createLocalWorkflowAncestorTrustProvider(settings){return async(ancestorDirs,canonicalTargetDir)=>{if(!isFolderTrustEnabled(settings)){return ancestorDirs.map(isWorkflowAncestorDirectorySafe)}if(ideContextStore.get()?.workspaceState?.isTrusted===false){return ancestorDirs.map(()=>false)}const folders=loadTrustedFoldersFresh();if(folders.errors.length>0){debugLogger.warn("Workflow ancestor trust denied: invalid trusted folders snapshot:",folders.errors.map(error=>`${error.path}: ${error.message}`).join("; "));return ancestorDirs.map(()=>false)}if(folders.isPathTrusted(canonicalTargetDir)!==true){return ancestorDirs.map(()=>false)}return ancestorDirs.map(directory=>folders.isPathTrusted(directory)===true)}}__name(createLocalWorkflowAncestorTrustProvider,"createLocalWorkflowAncestorTrustProvider");function saveTrustedFolders(trustedFoldersFile){writeTrustedFolders(trustedFoldersFile.path,()=>({...trustedFoldersFile.config}))}__name(saveTrustedFolders,"saveTrustedFolders");function assertTrustedFoldersConfig(config){for(const[rulePath,trustLevel]of Object.entries(config)){if(!Object.values(TrustLevel).includes(trustLevel)){throw new FatalConfigError(`Invalid trusted folder rule for ${JSON.stringify(rulePath)}.`)}}}__name(assertTrustedFoldersConfig,"assertTrustedFoldersConfig");function writeTrustedFolders(filePath,update){const dirPath=path3.dirname(filePath);if(!fs4.existsSync(dirPath)){fs4.mkdirSync(dirPath,{recursive:true})}const release=import_proper_lockfile.default.lockSync(filePath,{realpath:false,stale:1e4,onCompromised:__name(err=>{debugLogger.warn("trusted folders lock compromised:",err)},"onCompromised")});try{let originalContent="{}";if(fs4.existsSync(filePath)){const stat=fs4.lstatSync(filePath);if(stat.isSymbolicLink()||!stat.isFile()){throw new FatalConfigError("Trusted folders path must be a regular file.")}originalContent=fs4.readFileSync(filePath,"utf-8")}let parsed;try{parsed=parseJsoncObject(originalContent)}catch(error){if(error instanceof Error&&error.message==="JSONC document root is not a JSON object."){throw new FatalConfigError("Trusted folders file is not a valid JSON object.")}throw error}const diskConfig=Object.fromEntries(Object.entries(parsed));assertTrustedFoldersConfig(diskConfig);const nextConfig=update({...diskConfig});assertTrustedFoldersConfig(nextConfig);const content=updateJsoncContent(originalContent,nextConfig,true);atomicWriteFileSync(filePath,content,{encoding:"utf-8",mode:384,forceMode:true,noFollow:true});return nextConfig}finally{try{release()}catch{}}}__name(writeTrustedFolders,"writeTrustedFolders");function isFolderTrustEnabled(settings){const folderTrustSetting=settings.security?.folderTrust?.enabled??false;return folderTrustSetting}__name(isFolderTrustEnabled,"isFolderTrustEnabled");function getExplicitTrustLevel(trustConfig,workspaceCwd){const winner=resolveTrustRule(buildTrustPrecedenceRules(Object.entries(trustConfig).map(([rulePath,trustLevel])=>({path:rulePath,trustLevel}))),getPathComparisonVariants(workspaceCwd));return winner?.payload??null}__name(getExplicitTrustLevel,"getExplicitTrustLevel");function loadTrustedFoldersWithOverrides(trustConfig){const folders=loadTrustedFolders();if(folders.errors.length>0){const errorMessages=folders.errors.map(error=>`Error in ${error.path}: ${error.message}`);throw new FatalConfigError(`${errorMessages.join("\n")}
4
4
  Please fix the configuration file and try again.`)}if(trustConfig){return new LoadedTrustedFolders({...folders.user,config:trustConfig},folders.errors)}return folders}__name(loadTrustedFoldersWithOverrides,"loadTrustedFoldersWithOverrides");function trustStatusToResult(status){if(status.effective.source==="disabled"){return{isTrusted:true,source:void 0}}return{isTrusted:status.effective.state==="trusted"?true:status.effective.state==="untrusted"?false:void 0,source:status.effective.source==="file"||status.effective.source==="ide"?status.effective.source:void 0}}__name(trustStatusToResult,"trustStatusToResult");function getWorkspaceTrustStatus(settings,workspaceCwd,trustConfig){if(!isFolderTrustEnabled(settings)){return{v:1,workspaceCwd,folderTrustEnabled:false,effective:{state:"trusted",source:"disabled"},explicitTrustLevel:null,requiresDaemonRestartForChanges:true}}const ideTrust=ideContextStore.get()?.workspaceState?.isTrusted;if(ideTrust!==void 0&&arePathsEquivalent(workspaceCwd,process.cwd())){return{v:1,workspaceCwd,folderTrustEnabled:true,effective:{state:ideTrust?"trusted":"untrusted",source:"ide"},explicitTrustLevel:null,requiresDaemonRestartForChanges:true}}const folders=loadTrustedFoldersWithOverrides(trustConfig);const isTrusted=folders.isPathTrusted(workspaceCwd);const state=isTrusted===true?"trusted":isTrusted===false?"untrusted":"unknown";return{v:1,workspaceCwd,folderTrustEnabled:true,effective:{state,source:isTrusted===void 0?"none":"file"},explicitTrustLevel:getExplicitTrustLevel(folders.user.config,workspaceCwd),requiresDaemonRestartForChanges:true}}__name(getWorkspaceTrustStatus,"getWorkspaceTrustStatus");function isWorkspaceTrusted(settings,trustConfig,workspacePath){if(!isFolderTrustEnabled(settings)){return{isTrusted:true,source:void 0}}const ideTrust=ideContextStore.get()?.workspaceState?.isTrusted;if(ideTrust!==void 0&&(workspacePath===void 0||arePathsEquivalent(workspacePath,process.cwd()))){return{isTrusted:ideTrust,source:"ide"}}return trustStatusToResult(getWorkspaceTrustStatus(settings,workspacePath??process.cwd(),trustConfig))}__name(isWorkspaceTrusted,"isWorkspaceTrusted");export{writeWithBackupSync,updateSettingsFilePreservingFormat,parseJsoncObject,isWorkflowAncestorDirectorySafe,TRUSTED_FOLDERS_FILENAME,getTrustedFoldersPath,TrustLevel,onTrustedFoldersChanged,LoadedTrustedFolders,resetTrustedFoldersForTesting,loadTrustedFolders,loadTrustedFoldersFresh,createLocalWorkflowAncestorTrustProvider,saveTrustedFolders,isFolderTrustEnabled,getExplicitTrustLevel,getWorkspaceTrustStatus,isWorkspaceTrusted};
5
5
  /**
6
6
  * @license