@hostclubeos/miraos 0.0.8-beta → 0.0.9-beta
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.
- package/chunks/{MaxSizedBox-YR2SA5XW.js → MaxSizedBox-6CGCRBRO.js} +1 -1
- package/chunks/{StandaloneSessionPicker-VEXSGLU4.js → StandaloneSessionPicker-7VQOS4TU.js} +1 -1
- package/chunks/{acp-subagent-executor-ATOLWCVC.js → acp-subagent-executor-BFQRCU7R.js} +1 -1
- package/chunks/{acpAgent-DN46FTZ2.js → acpAgent-PCXQRPNU.js} +3 -3
- package/chunks/{advisor-6MI5JQGC.js → advisor-WDZ5N5ZP.js} +1 -1
- package/chunks/{agent-6HPQ4XCT.js → agent-I7Q3IPSS.js} +1 -1
- package/chunks/{agent-headless-KXAJBOPG.js → agent-headless-6LOYWI5T.js} +1 -1
- package/chunks/{agent-host-client-NOZRE2ZR.js → agent-host-client-PZZKCNQF.js} +1 -1
- package/chunks/{agent-host-connections-6FOSHEWD.js → agent-host-connections-TWWSRTKJ.js} +1 -1
- package/chunks/{autofix-pr-IMJA2KZF.js → autofix-pr-RQPGPQ4D.js} +1 -1
- package/chunks/{batch-L5VJ4XGP.js → batch-UJD5TSBN.js} +1 -1
- package/chunks/{bridge-CCRTJSIM.js → bridge-4TYLRPXZ.js} +1 -1
- package/chunks/{channel-settings-store-SB7BP6XT.js → channel-settings-store-RENJMOQ5.js} +1 -1
- package/chunks/{chunk-UC455ZS7.js → chunk-24PHAWM3.js} +1 -1
- package/chunks/{chunk-CNGBG3X5.js → chunk-26JPBN6V.js} +1 -1
- package/chunks/{chunk-W4M6JXZB.js → chunk-2MQH3J4U.js} +1 -1
- package/chunks/{chunk-GS4FZF6I.js → chunk-2RXOWQSQ.js} +1 -1
- package/chunks/{chunk-LRXYXGMT.js → chunk-323HUW2T.js} +1 -1
- package/chunks/{chunk-7DJYSBNJ.js → chunk-3BHXE7CB.js} +1 -1
- package/chunks/{chunk-7Q6RNE77.js → chunk-3GYAEXAA.js} +1 -1
- package/chunks/{chunk-VOIC5ZW2.js → chunk-3YBZW4HP.js} +1 -1
- package/chunks/{chunk-JRIVHFCG.js → chunk-4RJ2RRGZ.js} +1 -1
- package/chunks/{chunk-3NA5O4QO.js → chunk-5DIW4X4P.js} +1 -1
- package/chunks/{chunk-YELFN6AG.js → chunk-5GB6JNJX.js} +1 -1
- package/chunks/{chunk-6TNX3S5H.js → chunk-5HSNCG73.js} +2 -2
- package/chunks/{chunk-FC5IAX56.js → chunk-6HDMM7TJ.js} +1 -1
- package/chunks/{chunk-CJLKKIUW.js → chunk-6STNGEYC.js} +1 -1
- package/chunks/{chunk-ZJOVJLIH.js → chunk-7EFWNFJJ.js} +1 -1
- package/chunks/{chunk-SMO4PEHK.js → chunk-7EWIKIJI.js} +1 -1
- package/chunks/{chunk-S5NTCBEI.js → chunk-7TB6VG72.js} +1 -1
- package/chunks/{chunk-6AAVML2M.js → chunk-7TLL4JLR.js} +1 -1
- package/chunks/{chunk-IWIGJDPL.js → chunk-AOMXZNMX.js} +1 -1
- package/chunks/{chunk-5YULNQF3.js → chunk-AUM57JI2.js} +1 -1
- package/chunks/{chunk-ZQZK267X.js → chunk-AW5UCOZO.js} +1 -1
- package/chunks/{chunk-D4WMUCSK.js → chunk-C6HVNDQT.js} +2 -2
- package/chunks/{chunk-2DPE27WB.js → chunk-CC6E5CQV.js} +1 -1
- package/chunks/{chunk-SK5C26Y6.js → chunk-CLKUQP27.js} +1 -1
- package/chunks/{chunk-ARILWFTZ.js → chunk-DFMQQM4M.js} +1 -1
- package/chunks/{chunk-IJIQDCNJ.js → chunk-DP7LJTG2.js} +5 -5
- package/chunks/{chunk-7EEWU6XO.js → chunk-DQT5VL7G.js} +1 -1
- package/chunks/{chunk-AHV4IMUX.js → chunk-E4QOAV5O.js} +1 -1
- package/chunks/{chunk-G3COGFSZ.js → chunk-E4REGDEZ.js} +1 -1
- package/chunks/{chunk-MOXZO5PM.js → chunk-EAG7VZJJ.js} +1 -1
- package/chunks/{chunk-GQ24VFGQ.js → chunk-EFO6J22W.js} +1 -1
- package/chunks/{chunk-IJH5HZTB.js → chunk-EMR4QK2F.js} +1 -1
- package/chunks/{chunk-YFXKRGHT.js → chunk-EYECE2PH.js} +1 -1
- package/chunks/{chunk-7HO5DQ6V.js → chunk-EZDXHUHB.js} +1 -1
- package/chunks/{chunk-66N3SLXJ.js → chunk-FJFTKA4H.js} +1 -1
- package/chunks/{chunk-DNCXESHL.js → chunk-FSLDNLNU.js} +1 -1
- package/chunks/{chunk-K3RWL2YH.js → chunk-FSRXTX3N.js} +1 -1
- package/chunks/{chunk-4RRQ7CPF.js → chunk-FWSXFRIQ.js} +1 -1
- package/chunks/{chunk-M3IQE5G4.js → chunk-G4ATLMDH.js} +1 -1
- package/chunks/{chunk-WUZ53TKN.js → chunk-GAS3HKRX.js} +1 -1
- package/chunks/{chunk-LTXZHHNK.js → chunk-GFFL2LR2.js} +1 -1
- package/chunks/{chunk-IK5TB2CB.js → chunk-GYFIY7TD.js} +1 -1
- package/chunks/{chunk-XJKDC7OE.js → chunk-GYXRI4P5.js} +1 -1
- package/chunks/{chunk-4C5BOFDC.js → chunk-H3U7DXIU.js} +1 -1
- package/chunks/{chunk-5AJKMBPM.js → chunk-HEDVPRMD.js} +1 -1
- package/chunks/{chunk-32DLSPV5.js → chunk-HI3644FQ.js} +1 -1
- package/chunks/{chunk-CLLQQMTU.js → chunk-HTHYLMBO.js} +1 -1
- package/chunks/{chunk-VAFRD2H4.js → chunk-IW7RPDV2.js} +1 -1
- package/chunks/{chunk-5BWVS5D3.js → chunk-IXQI4K6O.js} +1 -1
- package/chunks/{chunk-BWLMXGA2.js → chunk-IYH3IZL4.js} +1 -1
- package/chunks/{chunk-XGPGIMZK.js → chunk-J52J35K4.js} +1 -1
- package/chunks/{chunk-BWFZEDYG.js → chunk-J7L5IHLG.js} +1 -1
- package/chunks/{chunk-6STDVRH5.js → chunk-JHS5B4N7.js} +2 -2
- package/chunks/{chunk-EHM4KL2U.js → chunk-JRSO5ZGU.js} +1 -1
- package/chunks/{chunk-NYGJ53Y7.js → chunk-JS6VAGRQ.js} +1 -1
- package/chunks/{chunk-QCSGHQ2P.js → chunk-KAFPULGU.js} +1 -1
- package/chunks/{chunk-CNZS2RPX.js → chunk-LDP47G5M.js} +1 -1
- package/chunks/{chunk-GM6YF6IS.js → chunk-LMZZWPKA.js} +1 -1
- package/chunks/{chunk-5SX4UPMN.js → chunk-LNCELICB.js} +1 -1
- package/chunks/{chunk-K2PGOAJP.js → chunk-LY2DRNTZ.js} +1 -1
- package/chunks/{chunk-KZZ5ZQHX.js → chunk-MMGGGYSJ.js} +1 -1
- package/chunks/{chunk-SVNSF5ZH.js → chunk-MTBU2ZIM.js} +1 -1
- package/chunks/{chunk-MV7LX23I.js → chunk-N27KICJQ.js} +1 -1
- package/chunks/{chunk-OPFBBIAQ.js → chunk-NHYFTK4O.js} +1 -1
- package/chunks/{chunk-NUDHRTIM.js → chunk-NRDHXSEE.js} +1 -1
- package/chunks/{chunk-QZNCYZ7H.js → chunk-NV5VVTYQ.js} +1 -1
- package/chunks/{chunk-7GU7HKIT.js → chunk-OEDMFKZL.js} +1 -1
- package/chunks/{chunk-V3ASW57P.js → chunk-OQAVMR6K.js} +1 -1
- package/chunks/{chunk-GBEQD55S.js → chunk-OY3Y6EMV.js} +1 -1
- package/chunks/{chunk-G7D42XGP.js → chunk-OZL4ZMGQ.js} +2 -2
- package/chunks/{chunk-PGKVSOWW.js → chunk-PKSPKVFH.js} +1 -1
- package/chunks/{chunk-OXG4BLFF.js → chunk-PNFKCYZT.js} +1 -1
- package/chunks/{chunk-JT5EN5MI.js → chunk-PTWHFVGG.js} +2 -2
- package/chunks/{chunk-3VKLOQ2P.js → chunk-QJ6ZTZFC.js} +1 -1
- package/chunks/{chunk-WZAUO3LV.js → chunk-QRGWB7IX.js} +1 -1
- package/chunks/{chunk-JCWNB45W.js → chunk-QRP2GXQD.js} +1 -1
- package/chunks/{chunk-CEVKKM22.js → chunk-RES5ET63.js} +1 -1
- package/chunks/{chunk-HCKF74X7.js → chunk-ROSJCTWB.js} +1 -1
- package/chunks/{chunk-WJXADORN.js → chunk-RR3NFNWL.js} +1 -1
- package/chunks/{chunk-HCCONFJY.js → chunk-RYQDRFLW.js} +1 -1
- package/chunks/{chunk-WSXRO2YB.js → chunk-S7CWSAUQ.js} +1 -1
- package/chunks/{chunk-MXFS555I.js → chunk-SAJKF4WS.js} +1 -1
- package/chunks/chunk-SINRWOVD.js +36 -0
- package/chunks/{chunk-DNXQKR5E.js → chunk-SJNQ6I23.js} +1 -1
- package/chunks/{chunk-DTRSC73M.js → chunk-T2GM4S4G.js} +3 -3
- package/chunks/{chunk-C3ZJUOTJ.js → chunk-TCQJO42E.js} +1 -1
- package/chunks/{chunk-G4OSEVOV.js → chunk-TIIDF23U.js} +2 -2
- package/chunks/{chunk-NNYAXFFN.js → chunk-TKH5R7RZ.js} +1 -1
- package/chunks/{chunk-JHGMLUAL.js → chunk-TSRTZD3X.js} +1 -1
- package/chunks/{chunk-GXNGLDUN.js → chunk-UXSXKLRH.js} +1 -1
- package/chunks/{chunk-MCY3IS2E.js → chunk-UYI5AMPI.js} +1 -1
- package/chunks/{chunk-7L4MR4QM.js → chunk-VO6SPDH4.js} +1 -1
- package/chunks/{chunk-SPCIIUIG.js → chunk-VRIHYTDI.js} +1 -1
- package/chunks/{chunk-Q4NEZZ6L.js → chunk-VT47A26Q.js} +1 -1
- package/chunks/{chunk-E743PFSX.js → chunk-VZOZUCZX.js} +1 -1
- package/chunks/{chunk-WW43VZ6O.js → chunk-WLEGTKGA.js} +1 -1
- package/chunks/{chunk-77GGGTWS.js → chunk-XHCJN4A2.js} +1 -1
- package/chunks/{chunk-UZAFPEVN.js → chunk-XTRZ5PHG.js} +1 -1
- package/chunks/{chunk-DTNW2CM3.js → chunk-Y4GZOZWD.js} +1 -1
- package/chunks/{chunk-YOBM4ZFW.js → chunk-YUCAGV52.js} +2 -2
- package/chunks/{chunk-WOMJLK3E.js → chunk-YWQM4TSO.js} +1 -1
- package/chunks/{chunk-WN6Z3J27.js → chunk-YYTOHY4V.js} +1 -1
- package/chunks/{chunk-VOCM2M4K.js → chunk-Z25W2S5N.js} +1 -1
- package/chunks/{chunk-QWNTORRT.js → chunk-Z6GECBAJ.js} +1 -1
- package/chunks/{chunk-XNP5JXCS.js → chunk-ZJU4B4WX.js} +1 -1
- package/chunks/{chunk-MCHMWRNO.js → chunk-ZSHDQPAO.js} +1 -1
- package/chunks/{chunk-POMEWCFJ.js → chunk-ZUWLTGSR.js} +6 -6
- package/chunks/{codex-subagent-executor-TPO62HU5.js → codex-subagent-executor-2V4NB7IR.js} +1 -1
- package/chunks/{config-utils-6GWIYBUK.js → config-utils-5B2LYCON.js} +1 -1
- package/chunks/{contextCommand-WWVGDTOL.js → contextCommand-UPQGRXWK.js} +1 -1
- package/chunks/{core-runtime-ASQR33TV.js → core-runtime-DPMH2BXK.js} +1 -1
- package/chunks/{create-sub-session-XY2FXSPE.js → create-sub-session-EJVB3FE5.js} +1 -1
- package/chunks/{cron-create-HY3TLNV2.js → cron-create-V2A7PMQC.js} +1 -1
- package/chunks/{daemon-git-worktree-guard-ILW3NJJC.js → daemon-git-worktree-guard-YEIMR2X7.js} +1 -1
- package/chunks/{daemon-status-provider-JVOGEKWY.js → daemon-status-provider-6BRB5TG3.js} +1 -1
- package/chunks/{daemon-trust-policy-XXRBG4JE.js → daemon-trust-policy-BEXVFO4M.js} +1 -1
- package/chunks/{daemon-trust-policy-monitor-UL73ADOZ.js → daemon-trust-policy-monitor-BVS6LXBX.js} +1 -1
- package/chunks/{deferred-core-runtime-PT747R7S.js → deferred-core-runtime-NTKFHL5J.js} +1 -1
- package/chunks/{edit-4PJ3NPFA.js → edit-LRG3TMHP.js} +1 -1
- package/chunks/{enterPlanMode-KQ62QN7S.js → enterPlanMode-KOUSHJHR.js} +1 -1
- package/chunks/{environment-H4HADXGA.js → environment-54CM3OXE.js} +1 -1
- package/chunks/{errors-OSD4ZZGR.js → errors-D6XR3NH4.js} +1 -1
- package/chunks/{execution-tool-PHHGLKWC.js → execution-tool-7RZ2JLEK.js} +1 -1
- package/chunks/{execution-worker-MH3CV66T.js → execution-worker-LXQ7WAFG.js} +1 -1
- package/chunks/{exitPlanMode-OU5YP4XN.js → exitPlanMode-4FGFA2QC.js} +1 -1
- package/chunks/{fast-path-WKOMHBWN.js → fast-path-4B7OKPYK.js} +1 -1
- package/chunks/{glob-FYCOEQPM.js → glob-N2D7SY23.js} +1 -1
- package/chunks/{goal-tools-T27GSDNM.js → goal-tools-7RNSDRFO.js} +1 -1
- package/chunks/{handleAutoUpdate-XXCPJLKO.js → handleAutoUpdate-PKKJQAKG.js} +1 -1
- package/chunks/{i18n-3B2PRJM2.js → i18n-F3OAHCLJ.js} +1 -1
- package/chunks/{initializer-HSFVDRTR.js → initializer-OL3DDWR7.js} +1 -1
- package/chunks/{installationInfo-SJJ2DYZ6.js → installationInfo-D2L743RV.js} +1 -1
- package/chunks/{interactive-mod-session-BWY2JRSQ.js → interactive-mod-session-2GXRCQKR.js} +1 -1
- package/chunks/{list-TGCI3MBM.js → list-PU7ZXBY5.js} +1 -1
- package/chunks/{llm-FYR73GKD.js → llm-V42HGUVH.js} +4 -4
- package/chunks/{loadedSettingsAdapter-DUDCINQL.js → loadedSettingsAdapter-KAEVWWRX.js} +1 -1
- package/chunks/{local-7PEOBJKE.js → local-KM5F5RAB.js} +1 -1
- package/chunks/{local-execution-environment-Q4OOA7BL.js → local-execution-environment-OEO2KW3M.js} +1 -1
- package/chunks/{loggingContentGenerator-VVESQOIQ.js → loggingContentGenerator-DQLXSDZR.js} +1 -1
- package/chunks/{loop-wakeup-M2XLAAKZ.js → loop-wakeup-CJICM24Y.js} +1 -1
- package/chunks/{manage-memory-FRVWHM2C.js → manage-memory-7CV6LF4C.js} +1 -1
- package/chunks/{managed-execution-engine-AVIM6AQU.js → managed-execution-engine-JEAIQ7L4.js} +1 -1
- package/chunks/{managed-local-serve-GIXHGFIU.js → managed-local-serve-KA37YWRW.js} +1 -1
- package/chunks/{managed-npm-update-3QSXGSHW.js → managed-npm-update-TSUUH3NN.js} +1 -1
- package/chunks/{managed-runtime-attestation-worker-ML4TCRAW.js → managed-runtime-attestation-worker-PUZ2ECM5.js} +1 -1
- package/chunks/{managed-runtime-bootstrap-JWJFGLBM.js → managed-runtime-bootstrap-SERIRKPD.js} +1 -1
- package/chunks/{managed-runtime-session-worker-4ISKROGZ.js → managed-runtime-session-worker-UOXK63YX.js} +1 -1
- package/chunks/{managed-runtime-ssh-worker-C44V2CPM.js → managed-runtime-ssh-worker-VKZYIX6R.js} +1 -1
- package/chunks/{managed-session-authority-UJ3FSKMD.js → managed-session-authority-5FYS3G3M.js} +1 -1
- package/chunks/{mcp-BWCLHHZ6.js → mcp-TRPV3K74.js} +1 -1
- package/chunks/{memory-5XQ2JVNS.js → memory-5CMNRPM2.js} +1 -1
- package/chunks/{model-call-collection-DXK2SIDR.js → model-call-collection-S4JKVFUO.js} +1 -1
- package/chunks/{model-configuration-6OLZS4C3.js → model-configuration-NEIDLKWQ.js} +1 -1
- package/chunks/{modelConfigUtils-5S5PC2RR.js → modelConfigUtils-LZLQOZKJ.js} +1 -1
- package/chunks/{monitor-6GKCWWUI.js → monitor-5MNKK5AO.js} +1 -1
- package/chunks/{nonInteractiveCli-ROHAB2H7.js → nonInteractiveCli-DDTGU2ER.js} +1 -1
- package/chunks/{nonInteractiveToolExecutor-OWCCSC5Y.js → nonInteractiveToolExecutor-N7PCYCKO.js} +1 -1
- package/chunks/{notebook-edit-WNRQ3QJZ.js → notebook-edit-7HIBTFFW.js} +1 -1
- package/chunks/{omni-DJ5RGNKA.js → omni-MX7BMOL5.js} +1 -1
- package/chunks/{openaiContentGenerator-237NVB63.js → openaiContentGenerator-NOIIZNRX.js} +1 -1
- package/chunks/{openaiResponsesContentGenerator-J33TCZKQ.js → openaiResponsesContentGenerator-5JJ6G7RS.js} +1 -1
- package/chunks/{pidfile-F7IYTFLX.js → pidfile-OHAGZOTV.js} +1 -1
- package/chunks/{processUtils-C6CSXITS.js → processUtils-TCDNCYVB.js} +1 -1
- package/chunks/{prompt-terminal-ledger-ZGYWPFJF.js → prompt-terminal-ledger-4ZUOCMOS.js} +1 -1
- package/chunks/{reactive-degrade-QKXPZQ3W.js → reactive-degrade-C7CGUJNP.js} +1 -1
- package/chunks/{read-file-GSNUMHRE.js → read-file-L4ZF6VDG.js} +1 -1
- package/chunks/{resumeHistoryUtils-4GUCHQGU.js → resumeHistoryUtils-WK3I4OIL.js} +1 -1
- package/chunks/{review-M2QGZFIO.js → review-F6JGI2LP.js} +1 -1
- package/chunks/{ripGrep-X4JTJZC6.js → ripGrep-L6M2GPCM.js} +1 -1
- package/chunks/{run-qwen-serve-4WW37RL2.js → run-qwen-serve-D5HB55SC.js} +1 -1
- package/chunks/{runtime-EFHJ6REE.js → runtime-CH3RAOQL.js} +1 -1
- package/chunks/{sandboxConfig-5XMIRDS4.js → sandboxConfig-EADWCO37.js} +1 -1
- package/chunks/{scheduled-tasks-ZCYM5YQJ.js → scheduled-tasks-PBKD4BHY.js} +1 -1
- package/chunks/{scheduler-5UAKCD5Z.js → scheduler-U5K3523K.js} +1 -1
- package/chunks/{search-memory-KKPYK33Q.js → search-memory-Y2IPKBDP.js} +1 -1
- package/chunks/{send-message-KOZRSWXO.js → send-message-JJQG2S6D.js} +1 -1
- package/chunks/{serve-5HSHEBMT.js → serve-2ZYS47MO.js} +1 -1
- package/chunks/{server-MC6KHP3G.js → server-5GMO4IHU.js} +3 -3
- package/chunks/{session-Z5HFG4IQ.js → session-LLOOVSHK.js} +1 -1
- package/chunks/{session-attachments-root-K2E5ETD4.js → session-attachments-root-XCLXH2XO.js} +1 -1
- package/chunks/{session-execution-engine-selector-NZA6CAJB.js → session-execution-engine-selector-5QPWJZSF.js} +1 -1
- package/chunks/{session-pr-refresh-OYJ56U3L.js → session-pr-refresh-MDBOAN3R.js} +1 -1
- package/chunks/{sessionService-BC56MX3G.js → sessionService-VKAHCTCC.js} +1 -1
- package/chunks/{settings-OHB77GXH.js → settings-ULEB2IYZ.js} +1 -1
- package/chunks/{shell-VKSH7JVL.js → shell-RBEKIYKU.js} +1 -1
- package/chunks/{skill-HQ4C2C3X.js → skill-GEVOEFMZ.js} +1 -1
- package/chunks/{skill-settings-6WPQFE3V.js → skill-settings-4IMGLYJW.js} +1 -1
- package/chunks/{spawnChannel-MXKVLS24.js → spawnChannel-B7L5PWQ6.js} +1 -1
- package/chunks/{standalone-update-NZP3OAZZ.js → standalone-update-SYQM6NOC.js} +1 -1
- package/chunks/{start-opentui-ui-25YQQD3O.js → start-opentui-ui-N427PLF4.js} +2 -2
- package/chunks/{startInteractiveUI-DWQJNIIV.js → startInteractiveUI-AS6GZKJJ.js} +1 -1
- package/chunks/{team-create-RSD7IADX.js → team-create-MN6FHUHU.js} +1 -1
- package/chunks/{team-plan-approval-XAOKZ6BR.js → team-plan-approval-OUYBIT7H.js} +1 -1
- package/chunks/{terminal-image-renderer-P5AGEOYS.js → terminal-image-renderer-MXZDUEOS.js} +1 -1
- package/chunks/{theme-manager-YBKJYPVQ.js → theme-manager-QOYSKWFK.js} +1 -1
- package/chunks/{tool-call-HJCSPR6N.js → tool-call-Q5NLEQFD.js} +1 -1
- package/chunks/{tool-result-media-SPWVV3OS.js → tool-result-media-NZJZTOBQ.js} +1 -1
- package/chunks/{tool-search-YWCOODLL.js → tool-search-D6Y45RNQ.js} +1 -1
- package/chunks/{total-session-admission-HKACVEI2.js → total-session-admission-36W7MDHP.js} +1 -1
- package/chunks/{trustedFolders-BXLZULWO.js → trustedFolders-XW5VH6HK.js} +1 -1
- package/chunks/{update-relaunch-CBJVLG6S.js → update-relaunch-KQPR2HAP.js} +1 -1
- package/chunks/{updateCheck-2J6RY3L3.js → updateCheck-SRW67WAX.js} +1 -1
- package/chunks/{upload-config-EN5XYA3V.js → upload-config-BTJNYMRX.js} +1 -1
- package/chunks/{useAutoAcceptIndicator-LF7VIUER.js → useAutoAcceptIndicator-N3RRUBSL.js} +1 -1
- package/chunks/{validateNonInterActiveAuth-63TR5JOG.js → validateNonInterActiveAuth-SWNH4FY4.js} +1 -1
- package/chunks/{version-F22SKNME.js → version-6R6LSGXO.js} +1 -1
- package/chunks/{web-fetch-ULH7TOLR.js → web-fetch-Y7LBAU3R.js} +1 -1
- package/chunks/{web-search-C3ORWAWR.js → web-search-IB4NYYUH.js} +1 -1
- package/chunks/{workflow-4ATPGZ5N.js → workflow-TR4YIPJO.js} +1 -1
- package/chunks/{workflow-ancestor-trust-AJ27EBZD.js → workflow-ancestor-trust-AHDUBOR7.js} +1 -1
- package/chunks/{workspace-agents-VLAJGYJF.js → workspace-agents-MY2NFL6A.js} +1 -1
- package/chunks/{workspace-providers-status-TFAXNJ6L.js → workspace-providers-status-DNCCKFVE.js} +1 -1
- package/chunks/{workspace-recovery-worker-GKYYJPXV.js → workspace-recovery-worker-22VK4T4R.js} +1 -1
- package/chunks/{workspace-registration-store-ANR3STGQ.js → workspace-registration-store-64TGRRGC.js} +1 -1
- package/chunks/{workspace-registry-OVHNLVBM.js → workspace-registry-E6LFL5GL.js} +1 -1
- package/chunks/{workspace-runtime-coordinator-IEN2G7JP.js → workspace-runtime-coordinator-UHJHBIQT.js} +1 -1
- package/chunks/{workspace-service-NISFZTBE.js → workspace-service-OVEYIQOC.js} +1 -1
- package/chunks/{workspace-skills-status-QRF5ZXMT.js → workspace-skills-status-3NKXA5SK.js} +1 -1
- package/chunks/{workspace-trust-reconciler-X3XMX2GJ.js → workspace-trust-reconciler-JF7YHR52.js} +1 -1
- package/chunks/{write-file-SF42KZAH.js → write-file-FSTHYKKZ.js} +1 -1
- package/chunks/{zoom-image-4UMB6G3P.js → zoom-image-JP3EUDXE.js} +1 -1
- package/cli.js +2 -2
- package/execution-worker.js +1 -1
- package/package.json +2 -2
- package/chunks/chunk-OHOG4HSN.js +0 -31
|
@@ -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,isWithinRoot}from"./chunk-IDXJIDME.js";import{ideContextStore}from"./chunk-POMEWCFJ.js";import{require_proper_lockfile}from"./chunk-YIW3H46P.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{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,isWithinRoot}from"./chunk-IDXJIDME.js";import{ideContextStore}from"./chunk-ZUWLTGSR.js";import{require_proper_lockfile}from"./chunk-YIW3H46P.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{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 hasTrustRuleBelowRoot(trustConfig,location,root){if(root===void 0||arePathsEquivalent(location,root))return false;const folders=loadTrustedFoldersWithOverrides(trustConfig);const rule=resolveTrustRule(buildTrustPrecedenceRules(folders.rules),getPathComparisonVariants(location));if(!rule)return false;const rootVariants=getPathComparisonVariants(root);return[...rule.variants].some(ruleVariant=>[...rootVariants].some(rootVariant=>ruleVariant!==rootVariant&&isWithinRoot(ruleVariant,rootVariant)))}__name(hasTrustRuleBelowRoot,"hasTrustRuleBelowRoot");function getTrustFileDecisionBelowIdeRoot(settings,location,root,trustConfig){if(!isFolderTrustEnabled(settings)||!hasTrustRuleBelowRoot(trustConfig,location,root)){return void 0}return loadTrustedFoldersWithOverrides(trustConfig).isPathTrusted(location)}__name(getTrustFileDecisionBelowIdeRoot,"getTrustFileDecisionBelowIdeRoot");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.getWorkspaceTrustScope(workspaceCwd);if(ideTrust!==void 0&&!hasTrustRuleBelowRoot(trustConfig,workspaceCwd,ideTrust.root)){return{v:1,workspaceCwd,folderTrustEnabled:true,effective:{state:ideTrust.isTrusted?"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}}if(workspacePath===void 0){const ideTrust=ideContextStore.get()?.workspaceState?.isTrusted;if(ideTrust!==void 0){const fileTrust=getTrustFileDecisionBelowIdeRoot(settings,process.cwd(),ideContextStore.getWorkspaceTrustScope(process.cwd())?.root,trustConfig);return fileTrust===void 0?{isTrusted:ideTrust,source:"ide"}:{isTrusted:fileTrust,source:"file"}}}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,getTrustFileDecisionBelowIdeRoot,getWorkspaceTrustStatus,isWorkspaceTrusted};
|
|
5
5
|
/**
|
|
6
6
|
* @license
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{OUTPUT_LANGUAGE_TABLE}from"./chunk-
|
|
3
|
+
import{OUTPUT_LANGUAGE_TABLE}from"./chunk-ZUWLTGSR.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var STRICT_PARITY_CODES=new Set(["zh","zh-TW"]);var SUPPORTED_LANGUAGES=OUTPUT_LANGUAGE_TABLE.map(entry=>({...entry,...STRICT_PARITY_CODES.has(entry.code)?{strictParity:true}:{}}));function normalizeLanguageCandidate(input){return input.trim().replace(/_/g,"-").toLowerCase()}__name(normalizeLanguageCandidate,"normalizeLanguageCandidate");function matchesLocaleToken(candidate,token){return candidate===token||candidate.startsWith(`${token}-`)||candidate.startsWith(`${token}.`)||candidate.startsWith(`${token}@`)}__name(matchesLocaleToken,"matchesLocaleToken");function getMatchedLocaleTokenLength(candidate,language){const code=language.code.toLowerCase();const id=language.id.toLowerCase();if(matchesLocaleToken(candidate,id)){return id.length}if(matchesLocaleToken(candidate,code)){return code.length}return void 0}__name(getMatchedLocaleTokenLength,"getMatchedLocaleTokenLength");function resolveSupportedLanguage(input){const normalized=normalizeLanguageCandidate(input);if(!normalized){return void 0}let bestMatch;for(const language of SUPPORTED_LANGUAGES){if(normalized===language.fullName.toLowerCase()||language.nativeName&&normalized===language.nativeName.toLowerCase()){return language.code}const tokenLength=getMatchedLocaleTokenLength(normalized,language);if(tokenLength!==void 0&&(!bestMatch||tokenLength>bestMatch.tokenLength)){bestMatch={code:language.code,tokenLength}}}return bestMatch?.code}__name(resolveSupportedLanguage,"resolveSupportedLanguage");function getLanguageNameFromLocale(locale){const resolved=resolveSupportedLanguage(locale);const lang=resolved?SUPPORTED_LANGUAGES.find(language=>language.code===resolved):void 0;return lang?.fullName||"English"}__name(getLanguageNameFromLocale,"getLanguageNameFromLocale");function getLanguageSettingsOptions(){return[{value:"auto",label:"Auto (detect from system)"},...SUPPORTED_LANGUAGES.map(l=>({value:l.code,label:l.nativeName?`${l.nativeName} (${l.fullName})`:`${l.fullName} (${l.id})`}))]}__name(getLanguageSettingsOptions,"getLanguageSettingsOptions");function getSupportedLanguageIds(separator="|"){return SUPPORTED_LANGUAGES.map(l=>l.id).join(separator)}__name(getSupportedLanguageIds,"getSupportedLanguageIds");export{SUPPORTED_LANGUAGES,resolveSupportedLanguage,getLanguageNameFromLocale,getLanguageSettingsOptions,getSupportedLanguageIds};
|
|
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{normalizeWorkspaceRelativePath}from"./chunk-YJ6APXNB.js";import{MAX_SNAPSHOTS,ManagedToolProtocolError,managedToolDigest}from"./chunk-POMEWCFJ.js";import{MANAGED_SESSION_LIMITS,assertManagedSessionDurableRef,assertManagedSessionKey,assertManagedSessionSequence,assertManagedSessionStableId}from"./chunk-HMCTSPVJ.js";import{getMemoryBaseDir}from"./chunk-CQGP2BAW.js";import{normalizeQwenCustomIgnoreFileNames}from"./chunk-LWVCLDHV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as path from"node:path";var MANAGED_TOOL_FILE_HISTORY_MAX_BYTES=8*1024*1024;function captureManagedToolExecutionContext(config){const filtering=config.getFileFilteringOptions();return{workspaceDirectories:[...config.getWorkspaceContext().getDirectories()],memoryBaseDir:getMemoryBaseDir(),lsToolEnabled:config.isLsToolEnabled(),grepOptions:{useRipgrep:config.getUseRipgrep(),useBuiltinRipgrep:config.getUseBuiltinRipgrep()},outputLimits:{chars:encodeOutputLimit(config.getTruncateToolOutputThreshold()),lines:encodeOutputLimit(config.getTruncateToolOutputLines()),charsExplicit:config.isTruncateToolOutputThresholdExplicit()},fileFilteringOptions:{respectGitIgnore:filtering.respectGitIgnore,respectQwenIgnore:filtering.respectQwenIgnore,customIgnoreFiles:normalizeQwenCustomIgnoreFileNames(filtering.customIgnoreFiles)}}}__name(captureManagedToolExecutionContext,"captureManagedToolExecutionContext");function record(value,keys){if(!value||typeof value!=="object"||Array.isArray(value))throw new ManagedToolProtocolError;const result=value;if(keys&&Object.keys(result).some(key=>!keys.includes(key)))throw new ManagedToolProtocolError;return result}__name(record,"record");function text(value,limit){if(typeof value!=="string"||!value.length||value.length>limit||value.includes("\0"))throw new ManagedToolProtocolError;return value}__name(text,"text");function uuid(value){const result=text(value,256);if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(result))throw new ManagedToolProtocolError;return result}__name(uuid,"uuid");function integer(value){if(typeof value!=="number"||!Number.isSafeInteger(value)||value<0)throw new ManagedToolProtocolError;return value}__name(integer,"integer");function timestamp(value){const result=text(value,32);const date=new Date(result);if(!Number.isFinite(date.getTime())||date.toISOString()!==result)throw new ManagedToolProtocolError;return result}__name(timestamp,"timestamp");function parseManagedToolFileHistoryPromptId(value){return text(value,128)}__name(parseManagedToolFileHistoryPromptId,"parseManagedToolFileHistoryPromptId");function snapshots(value){if(!Array.isArray(value)||value.length>MAX_SNAPSHOTS)throw new ManagedToolProtocolError;const prompts=new Set;return value.map(item=>{const snapshot=record(item,["promptId","timestamp","trackedFileBackups"]);const promptId=parseManagedToolFileHistoryPromptId(snapshot["promptId"]);if(prompts.has(promptId))throw new ManagedToolProtocolError;prompts.add(promptId);return{promptId,timestamp:timestamp(snapshot["timestamp"]),trackedFileBackups:Object.fromEntries(Object.entries(record(snapshot["trackedFileBackups"])).map(([filePath,value2])=>{text(filePath,4096);if(filePath.split(/[/\\]/).includes(".."))throw new ManagedToolProtocolError;const backup=record(value2,["backupFileName","version","backupTime","failed"]);const backupFileName=backup["backupFileName"]===null?null:text(backup["backupFileName"],256);if(backupFileName!==null&&(backupFileName==="."||backupFileName===".."||/[/\\]/.test(backupFileName)))throw new ManagedToolProtocolError;if("failed"in backup&&typeof backup["failed"]!=="boolean")throw new ManagedToolProtocolError;return[filePath,{backupFileName,version:integer(backup["version"]),backupTime:timestamp(backup["backupTime"]),..."failed"in backup?{failed:backup["failed"]}:{}}]}))}})}__name(snapshots,"snapshots");function absolutePath(value){const result=text(value,4096);if(!path.isAbsolute(result)||path.normalize(result)!==result)throw new ManagedToolProtocolError;return result}__name(absolutePath,"absolutePath");function encodeOutputLimit(value){return value===Number.POSITIVE_INFINITY?null:value}__name(encodeOutputLimit,"encodeOutputLimit");function outputLimit(value){if(value===null)return null;if(typeof value!=="number"||!Number.isFinite(value)||value<=0)throw new ManagedToolProtocolError;return value}__name(outputLimit,"outputLimit");function grepOptions(value){const input=record(value,["useRipgrep","useBuiltinRipgrep"]);if(typeof input["useRipgrep"]!=="boolean"||typeof input["useBuiltinRipgrep"]!=="boolean")throw new ManagedToolProtocolError;return{useRipgrep:input["useRipgrep"],useBuiltinRipgrep:input["useBuiltinRipgrep"]}}__name(grepOptions,"grepOptions");function outputLimits(value){const input=record(value,["chars","lines","charsExplicit"]);if(typeof input["charsExplicit"]!=="boolean")throw new ManagedToolProtocolError;return{chars:outputLimit(input["chars"]),lines:outputLimit(input["lines"]),charsExplicit:input["charsExplicit"]}}__name(outputLimits,"outputLimits");function executionContext(value){const input=record(value,["workspaceDirectories","memoryBaseDir","fileFilteringOptions","lsToolEnabled","grepOptions","outputLimits"]);const filtering=record(input["fileFilteringOptions"],["respectGitIgnore","respectQwenIgnore","customIgnoreFiles"]);if(!Array.isArray(input["workspaceDirectories"])||!Array.isArray(filtering["customIgnoreFiles"])||typeof filtering["respectGitIgnore"]!=="boolean"||typeof filtering["respectQwenIgnore"]!=="boolean"||typeof input["lsToolEnabled"]!=="boolean")throw new ManagedToolProtocolError;const directories=input["workspaceDirectories"].map(absolutePath);if(new Set(directories).size!==directories.length)throw new ManagedToolProtocolError;const customIgnoreFiles=filtering["customIgnoreFiles"].map(value2=>text(value2,4096));if(JSON.stringify(normalizeQwenCustomIgnoreFileNames(customIgnoreFiles))!==JSON.stringify(customIgnoreFiles))throw new ManagedToolProtocolError;return{workspaceDirectories:directories,memoryBaseDir:absolutePath(input["memoryBaseDir"]),lsToolEnabled:input["lsToolEnabled"],..."grepOptions"in input?{grepOptions:grepOptions(input["grepOptions"])}:{},..."outputLimits"in input?{outputLimits:outputLimits(input["outputLimits"])}:{},fileFilteringOptions:{respectGitIgnore:filtering["respectGitIgnore"],respectQwenIgnore:filtering["respectQwenIgnore"],customIgnoreFiles}}}__name(executionContext,"executionContext");function parseManagedToolFileHistoryBinding(value){managedToolDigest(value,MANAGED_TOOL_FILE_HISTORY_MAX_BYTES);const input=record(value,["ownerSessionId","ownerRuntimeSessionId","executionCwd","executionContext","snapshots"]);const executionCwd=text(input["executionCwd"],4096);if(!path.isAbsolute(executionCwd)||path.normalize(executionCwd)!==executionCwd)throw new ManagedToolProtocolError;return{ownerSessionId:uuid(input["ownerSessionId"]),ownerRuntimeSessionId:uuid(input["ownerRuntimeSessionId"]),executionCwd,..."executionContext"in input?{executionContext:executionContext(input["executionContext"])}:{},snapshots:snapshots(input["snapshots"])}}__name(parseManagedToolFileHistoryBinding,"parseManagedToolFileHistoryBinding");function parseManagedToolFileHistoryState(value){managedToolDigest(value,MANAGED_TOOL_FILE_HISTORY_MAX_BYTES);const input=record(value,["ownerSessionId","revision","snapshots"]);return{ownerSessionId:uuid(input["ownerSessionId"]),revision:integer(input["revision"]),snapshots:snapshots(input["snapshots"])}}__name(parseManagedToolFileHistoryState,"parseManagedToolFileHistoryState");init_esbuild_shims();function historyPath(value){if(typeof value!=="string"||value==="."||normalizeWorkspaceRelativePath(value)!==value)throw new Error("Invalid Hosted file history path.");return value}__name(historyPath,"historyPath");function parseHostedFileHistoryState(value,owner){if(!value||typeof value!=="object"||Array.isArray(value))throw new Error("Invalid Hosted file history state.");const state=value;if(Object.keys(state).sort().join(",")!=="files,ownerSessionId,snapshots"||state["ownerSessionId"]!==owner)throw new Error("Hosted file history owner conflicts.");const{snapshots:snapshots2}=parseManagedToolFileHistoryState({ownerSessionId:owner,revision:0,snapshots:state["snapshots"]});const paths=new Set(snapshots2.flatMap(s=>Object.keys(s.trackedFileBackups).map(historyPath)));const files=state["files"];if(!files||typeof files!=="object"||Array.isArray(files)||Object.keys(files).length!==paths.size)throw new Error("Hosted file history files conflict.");for(const[file,expected]of Object.entries(files)){if(!paths.has(historyPath(file)))throw new Error("Hosted file history file is untracked.");if(expected!==null&&(typeof expected!=="object"||Array.isArray(expected)||Object.keys(expected).sort().join(",")!=="digest,mode"||!/^sha256:[a-f0-9]{64}$/.test(expected.digest)||!Number.isSafeInteger(expected.mode)||expected.mode<0||expected.mode>4095))throw new Error("Invalid Hosted file history file state.")}return structuredClone({ownerSessionId:owner,snapshots:snapshots2,files})}__name(parseHostedFileHistoryState,"parseHostedFileHistoryState");var HOSTED_UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;function parseHostedFileHistoryRecord(value,owner){const record2=value;if(!record2||typeof record2!=="object"||Array.isArray(record2)||record2.schemaVersion!==1||!(record2.pendingTurn===null||typeof record2.pendingTurn==="string")||record2.pendingMessageId!==void 0&&(typeof record2.pendingMessageId!=="string"||!record2.pendingTurn)||!(record2.pendingUndo===null||typeof record2.pendingUndo?.requestId==="string"&&typeof record2.pendingUndo.promptId==="string"))throw new Error("Invalid Hosted file history record.");const state=parseHostedFileHistoryState(record2.state,owner);const undoReceipts=record2.undoReceipts===void 0?[]:record2.undoReceipts;if(!Array.isArray(undoReceipts))throw new Error("Invalid Hosted file history undo receipts: expected an array.");const requests=new Set;const prompts=new Set(state.snapshots.map(snapshot=>snapshot.promptId));for(const[index,receipt]of undoReceipts.entries()){const invalid=__name(reason=>{throw new Error(`Invalid Hosted file history undo receipt ${index}: ${reason}.`)},"invalid");if(!receipt||typeof receipt!=="object"||Array.isArray(receipt)||Object.keys(receipt).sort().join(",")!=="conflict,filesChanged,promptId,requestId")invalid("expected exactly requestId, promptId, filesChanged and conflict");if(typeof receipt.requestId!=="string"||!HOSTED_UUID.test(receipt.requestId))invalid("requestId must be a lowercase UUID v1-v5");if(typeof receipt.promptId!=="string"||!HOSTED_UUID.test(receipt.promptId))invalid("promptId must be a lowercase UUID v1-v5");if(!prompts.has(receipt.promptId))invalid("promptId is not a retained snapshot");if(requests.has(receipt.requestId))invalid("requestId is duplicated");if(typeof receipt.conflict!=="boolean")invalid("conflict must be a boolean");if(!Array.isArray(receipt.filesChanged))invalid("filesChanged must be an array");if(receipt.filesChanged.some(file=>typeof file!=="string"||!Object.hasOwn(state.files,file)))invalid("filesChanged must contain only tracked paths");if(new Set(receipt.filesChanged).size!==receipt.filesChanged.length)invalid("filesChanged contains duplicate paths");if(receipt.conflict&&receipt.filesChanged.length!==0)invalid("conflict must have no changed paths");if(record2.pendingUndo?.requestId===receipt.requestId&&record2.pendingUndo.promptId!==receipt.promptId)invalid("promptId does not match pendingUndo");requests.add(receipt.requestId)}return{schemaVersion:1,state,pendingTurn:record2.pendingTurn,...record2.pendingMessageId!==void 0?{pendingMessageId:record2.pendingMessageId}:{},pendingUndo:record2.pendingUndo,undoReceipts}}__name(parseHostedFileHistoryRecord,"parseHostedFileHistoryRecord");init_esbuild_shims();import{createHash,randomBytes}from"node:crypto";var TOOL_PUBLICATION_PROTOCOL="managed-tool-publication/1";var TOOL_PUBLICATION_LIMITS=Object.freeze({maxBodyBytes:64*1024,maxCaptureBytes:2**41,producerBytes:2*1024*1024+64*1024+2*256*1024,admissionBytes:2*1024*1024});var BINDING_KEYS=["publication","publicationId","sessionKey","turnId","executionCallId","modelCallId","runtimeBindingId","reference","bindingGeneration","captureId","revision","captureScope","capturePolicy","argsRef","requestDigest","writerId","writerGeneration","activationId","activationEpoch","intentSequence","checkpointRef"];function requireValue(condition){if(!condition)throw new Error("Invalid managed tool publication.")}__name(requireValue,"requireValue");function closed(value,keys){requireValue(value!==null&&typeof value==="object");requireValue(Object.getPrototypeOf(value)===Object.prototype||Object.getPrototypeOf(value)===null);const present=Object.keys(value);requireValue(present.length===keys.length&&present.every(key=>keys.includes(key)));return Object.fromEntries(present.map(key=>[key,value[key]]))}__name(closed,"closed");function id(value){return assertManagedSessionStableId(value,"publication id")}__name(id,"id");function token(value){const text2=id(value);requireValue(/^[a-z0-9_-]{1,128}$/.test(text2));return text2}__name(token,"token");function count(value,max=Number.MAX_SAFE_INTEGER-1){const result=assertManagedSessionSequence(value,"publication count");requireValue(result>0&&result<=max);return result}__name(count,"count");function wireDigest(value){requireValue(typeof value==="string"&&/^sha256:[0-9a-f]{64}$/.test(value));return value}__name(wireDigest,"wireDigest");function ref(value,kind){const result=assertManagedSessionDurableRef(value,"publication ref");requireValue(result.kind===kind&&result.schemaVersion===1&&result.byteLength>0&&result.byteLength<=(kind==="managed-checkpoint"?MANAGED_SESSION_LIMITS.maxEventBytes:TOOL_PUBLICATION_LIMITS.maxBodyBytes));return Object.freeze(result)}__name(ref,"ref");function bounded(value){requireValue(Buffer.byteLength(JSON.stringify(value))<=TOOL_PUBLICATION_LIMITS.maxBodyBytes);return Object.freeze(value)}__name(bounded,"bounded");function parseToolPublicationBinding(value){const r=closed(value,BINDING_KEYS);requireValue(r["publication"]===TOOL_PUBLICATION_PROTOCOL&&r["revision"]===1&&r["captureScope"]==="process_pipes"&&r["capturePolicy"]==="complete_required");const generation=id(r["bindingGeneration"]);requireValue(/^[1-9][0-9]{0,18}$/.test(generation)&&BigInt(generation)<=9223372036854775807n);const reference=closed(r["reference"],["sessionId","promptId","callId","argsDigest"]);return bounded({publication:TOOL_PUBLICATION_PROTOCOL,publicationId:token(r["publicationId"]),sessionKey:Object.freeze(assertManagedSessionKey(r["sessionKey"])),turnId:id(r["turnId"]),executionCallId:id(r["executionCallId"]),modelCallId:id(r["modelCallId"]),runtimeBindingId:id(r["runtimeBindingId"]),reference:Object.freeze({sessionId:id(reference["sessionId"]),promptId:id(reference["promptId"]),callId:id(reference["callId"]),argsDigest:wireDigest(reference["argsDigest"])}),bindingGeneration:generation,captureId:token(r["captureId"]),revision:1,captureScope:"process_pipes",capturePolicy:"complete_required",argsRef:ref(r["argsRef"],"managed-tool-input"),requestDigest:wireDigest(r["requestDigest"]),writerId:id(r["writerId"]),writerGeneration:count(r["writerGeneration"]),activationId:id(r["activationId"]),activationEpoch:count(r["activationEpoch"]),intentSequence:count(r["intentSequence"]),checkpointRef:ref(r["checkpointRef"],"managed-checkpoint")})}__name(parseToolPublicationBinding,"parseToolPublicationBinding");function toolPublicationManifestIdentity(binding){const b=parseToolPublicationBinding(binding);return{tenantId:b.sessionKey.tenantId,sessionId:b.sessionKey.sessionId,turnId:b.turnId,executionCallId:b.executionCallId,callId:b.reference.callId,invocationDigest:b.reference.argsDigest,bindingGeneration:b.bindingGeneration,captureId:b.captureId,revision:b.revision}}__name(toolPublicationManifestIdentity,"toolPublicationManifestIdentity");function createToolPublicationToken(){return randomBytes(32).toString("base64url")}__name(createToolPublicationToken,"createToolPublicationToken");export{MANAGED_TOOL_FILE_HISTORY_MAX_BYTES,captureManagedToolExecutionContext,parseManagedToolFileHistoryPromptId,parseManagedToolFileHistoryBinding,parseManagedToolFileHistoryState,historyPath,parseHostedFileHistoryState,HOSTED_UUID,parseHostedFileHistoryRecord,parseToolPublicationBinding,toolPublicationManifestIdentity,createToolPublicationToken};
|
|
3
|
+
import{normalizeWorkspaceRelativePath}from"./chunk-YJ6APXNB.js";import{MAX_SNAPSHOTS,ManagedToolProtocolError,managedToolDigest}from"./chunk-ZUWLTGSR.js";import{MANAGED_SESSION_LIMITS,assertManagedSessionDurableRef,assertManagedSessionKey,assertManagedSessionSequence,assertManagedSessionStableId}from"./chunk-HMCTSPVJ.js";import{getMemoryBaseDir}from"./chunk-CQGP2BAW.js";import{normalizeQwenCustomIgnoreFileNames}from"./chunk-LWVCLDHV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as path from"node:path";var MANAGED_TOOL_FILE_HISTORY_MAX_BYTES=8*1024*1024;function captureManagedToolExecutionContext(config){const filtering=config.getFileFilteringOptions();return{workspaceDirectories:[...config.getWorkspaceContext().getDirectories()],memoryBaseDir:getMemoryBaseDir(),lsToolEnabled:config.isLsToolEnabled(),grepOptions:{useRipgrep:config.getUseRipgrep(),useBuiltinRipgrep:config.getUseBuiltinRipgrep()},outputLimits:{chars:encodeOutputLimit(config.getTruncateToolOutputThreshold()),lines:encodeOutputLimit(config.getTruncateToolOutputLines()),charsExplicit:config.isTruncateToolOutputThresholdExplicit()},fileFilteringOptions:{respectGitIgnore:filtering.respectGitIgnore,respectQwenIgnore:filtering.respectQwenIgnore,customIgnoreFiles:normalizeQwenCustomIgnoreFileNames(filtering.customIgnoreFiles)}}}__name(captureManagedToolExecutionContext,"captureManagedToolExecutionContext");function record(value,keys){if(!value||typeof value!=="object"||Array.isArray(value))throw new ManagedToolProtocolError;const result=value;if(keys&&Object.keys(result).some(key=>!keys.includes(key)))throw new ManagedToolProtocolError;return result}__name(record,"record");function text(value,limit){if(typeof value!=="string"||!value.length||value.length>limit||value.includes("\0"))throw new ManagedToolProtocolError;return value}__name(text,"text");function uuid(value){const result=text(value,256);if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(result))throw new ManagedToolProtocolError;return result}__name(uuid,"uuid");function integer(value){if(typeof value!=="number"||!Number.isSafeInteger(value)||value<0)throw new ManagedToolProtocolError;return value}__name(integer,"integer");function timestamp(value){const result=text(value,32);const date=new Date(result);if(!Number.isFinite(date.getTime())||date.toISOString()!==result)throw new ManagedToolProtocolError;return result}__name(timestamp,"timestamp");function parseManagedToolFileHistoryPromptId(value){return text(value,128)}__name(parseManagedToolFileHistoryPromptId,"parseManagedToolFileHistoryPromptId");function snapshots(value){if(!Array.isArray(value)||value.length>MAX_SNAPSHOTS)throw new ManagedToolProtocolError;const prompts=new Set;return value.map(item=>{const snapshot=record(item,["promptId","timestamp","trackedFileBackups"]);const promptId=parseManagedToolFileHistoryPromptId(snapshot["promptId"]);if(prompts.has(promptId))throw new ManagedToolProtocolError;prompts.add(promptId);return{promptId,timestamp:timestamp(snapshot["timestamp"]),trackedFileBackups:Object.fromEntries(Object.entries(record(snapshot["trackedFileBackups"])).map(([filePath,value2])=>{text(filePath,4096);if(filePath.split(/[/\\]/).includes(".."))throw new ManagedToolProtocolError;const backup=record(value2,["backupFileName","version","backupTime","failed"]);const backupFileName=backup["backupFileName"]===null?null:text(backup["backupFileName"],256);if(backupFileName!==null&&(backupFileName==="."||backupFileName===".."||/[/\\]/.test(backupFileName)))throw new ManagedToolProtocolError;if("failed"in backup&&typeof backup["failed"]!=="boolean")throw new ManagedToolProtocolError;return[filePath,{backupFileName,version:integer(backup["version"]),backupTime:timestamp(backup["backupTime"]),..."failed"in backup?{failed:backup["failed"]}:{}}]}))}})}__name(snapshots,"snapshots");function absolutePath(value){const result=text(value,4096);if(!path.isAbsolute(result)||path.normalize(result)!==result)throw new ManagedToolProtocolError;return result}__name(absolutePath,"absolutePath");function encodeOutputLimit(value){return value===Number.POSITIVE_INFINITY?null:value}__name(encodeOutputLimit,"encodeOutputLimit");function outputLimit(value){if(value===null)return null;if(typeof value!=="number"||!Number.isFinite(value)||value<=0)throw new ManagedToolProtocolError;return value}__name(outputLimit,"outputLimit");function grepOptions(value){const input=record(value,["useRipgrep","useBuiltinRipgrep"]);if(typeof input["useRipgrep"]!=="boolean"||typeof input["useBuiltinRipgrep"]!=="boolean")throw new ManagedToolProtocolError;return{useRipgrep:input["useRipgrep"],useBuiltinRipgrep:input["useBuiltinRipgrep"]}}__name(grepOptions,"grepOptions");function outputLimits(value){const input=record(value,["chars","lines","charsExplicit"]);if(typeof input["charsExplicit"]!=="boolean")throw new ManagedToolProtocolError;return{chars:outputLimit(input["chars"]),lines:outputLimit(input["lines"]),charsExplicit:input["charsExplicit"]}}__name(outputLimits,"outputLimits");function executionContext(value){const input=record(value,["workspaceDirectories","memoryBaseDir","fileFilteringOptions","lsToolEnabled","grepOptions","outputLimits"]);const filtering=record(input["fileFilteringOptions"],["respectGitIgnore","respectQwenIgnore","customIgnoreFiles"]);if(!Array.isArray(input["workspaceDirectories"])||!Array.isArray(filtering["customIgnoreFiles"])||typeof filtering["respectGitIgnore"]!=="boolean"||typeof filtering["respectQwenIgnore"]!=="boolean"||typeof input["lsToolEnabled"]!=="boolean")throw new ManagedToolProtocolError;const directories=input["workspaceDirectories"].map(absolutePath);if(new Set(directories).size!==directories.length)throw new ManagedToolProtocolError;const customIgnoreFiles=filtering["customIgnoreFiles"].map(value2=>text(value2,4096));if(JSON.stringify(normalizeQwenCustomIgnoreFileNames(customIgnoreFiles))!==JSON.stringify(customIgnoreFiles))throw new ManagedToolProtocolError;return{workspaceDirectories:directories,memoryBaseDir:absolutePath(input["memoryBaseDir"]),lsToolEnabled:input["lsToolEnabled"],..."grepOptions"in input?{grepOptions:grepOptions(input["grepOptions"])}:{},..."outputLimits"in input?{outputLimits:outputLimits(input["outputLimits"])}:{},fileFilteringOptions:{respectGitIgnore:filtering["respectGitIgnore"],respectQwenIgnore:filtering["respectQwenIgnore"],customIgnoreFiles}}}__name(executionContext,"executionContext");function parseManagedToolFileHistoryBinding(value){managedToolDigest(value,MANAGED_TOOL_FILE_HISTORY_MAX_BYTES);const input=record(value,["ownerSessionId","ownerRuntimeSessionId","executionCwd","executionContext","snapshots"]);const executionCwd=text(input["executionCwd"],4096);if(!path.isAbsolute(executionCwd)||path.normalize(executionCwd)!==executionCwd)throw new ManagedToolProtocolError;return{ownerSessionId:uuid(input["ownerSessionId"]),ownerRuntimeSessionId:uuid(input["ownerRuntimeSessionId"]),executionCwd,..."executionContext"in input?{executionContext:executionContext(input["executionContext"])}:{},snapshots:snapshots(input["snapshots"])}}__name(parseManagedToolFileHistoryBinding,"parseManagedToolFileHistoryBinding");function parseManagedToolFileHistoryState(value){managedToolDigest(value,MANAGED_TOOL_FILE_HISTORY_MAX_BYTES);const input=record(value,["ownerSessionId","revision","snapshots"]);return{ownerSessionId:uuid(input["ownerSessionId"]),revision:integer(input["revision"]),snapshots:snapshots(input["snapshots"])}}__name(parseManagedToolFileHistoryState,"parseManagedToolFileHistoryState");init_esbuild_shims();function historyPath(value){if(typeof value!=="string"||value==="."||normalizeWorkspaceRelativePath(value)!==value)throw new Error("Invalid Hosted file history path.");return value}__name(historyPath,"historyPath");function parseHostedFileHistoryState(value,owner){if(!value||typeof value!=="object"||Array.isArray(value))throw new Error("Invalid Hosted file history state.");const state=value;if(Object.keys(state).sort().join(",")!=="files,ownerSessionId,snapshots"||state["ownerSessionId"]!==owner)throw new Error("Hosted file history owner conflicts.");const{snapshots:snapshots2}=parseManagedToolFileHistoryState({ownerSessionId:owner,revision:0,snapshots:state["snapshots"]});const paths=new Set(snapshots2.flatMap(s=>Object.keys(s.trackedFileBackups).map(historyPath)));const files=state["files"];if(!files||typeof files!=="object"||Array.isArray(files)||Object.keys(files).length!==paths.size)throw new Error("Hosted file history files conflict.");for(const[file,expected]of Object.entries(files)){if(!paths.has(historyPath(file)))throw new Error("Hosted file history file is untracked.");if(expected!==null&&(typeof expected!=="object"||Array.isArray(expected)||Object.keys(expected).sort().join(",")!=="digest,mode"||!/^sha256:[a-f0-9]{64}$/.test(expected.digest)||!Number.isSafeInteger(expected.mode)||expected.mode<0||expected.mode>4095))throw new Error("Invalid Hosted file history file state.")}return structuredClone({ownerSessionId:owner,snapshots:snapshots2,files})}__name(parseHostedFileHistoryState,"parseHostedFileHistoryState");var HOSTED_UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;function parseHostedFileHistoryRecord(value,owner){const record2=value;if(!record2||typeof record2!=="object"||Array.isArray(record2)||record2.schemaVersion!==1||!(record2.pendingTurn===null||typeof record2.pendingTurn==="string")||record2.pendingMessageId!==void 0&&(typeof record2.pendingMessageId!=="string"||!record2.pendingTurn)||!(record2.pendingUndo===null||typeof record2.pendingUndo?.requestId==="string"&&typeof record2.pendingUndo.promptId==="string"))throw new Error("Invalid Hosted file history record.");const state=parseHostedFileHistoryState(record2.state,owner);const undoReceipts=record2.undoReceipts===void 0?[]:record2.undoReceipts;if(!Array.isArray(undoReceipts))throw new Error("Invalid Hosted file history undo receipts: expected an array.");const requests=new Set;const prompts=new Set(state.snapshots.map(snapshot=>snapshot.promptId));for(const[index,receipt]of undoReceipts.entries()){const invalid=__name(reason=>{throw new Error(`Invalid Hosted file history undo receipt ${index}: ${reason}.`)},"invalid");if(!receipt||typeof receipt!=="object"||Array.isArray(receipt)||Object.keys(receipt).sort().join(",")!=="conflict,filesChanged,promptId,requestId")invalid("expected exactly requestId, promptId, filesChanged and conflict");if(typeof receipt.requestId!=="string"||!HOSTED_UUID.test(receipt.requestId))invalid("requestId must be a lowercase UUID v1-v5");if(typeof receipt.promptId!=="string"||!HOSTED_UUID.test(receipt.promptId))invalid("promptId must be a lowercase UUID v1-v5");if(!prompts.has(receipt.promptId))invalid("promptId is not a retained snapshot");if(requests.has(receipt.requestId))invalid("requestId is duplicated");if(typeof receipt.conflict!=="boolean")invalid("conflict must be a boolean");if(!Array.isArray(receipt.filesChanged))invalid("filesChanged must be an array");if(receipt.filesChanged.some(file=>typeof file!=="string"||!Object.hasOwn(state.files,file)))invalid("filesChanged must contain only tracked paths");if(new Set(receipt.filesChanged).size!==receipt.filesChanged.length)invalid("filesChanged contains duplicate paths");if(receipt.conflict&&receipt.filesChanged.length!==0)invalid("conflict must have no changed paths");if(record2.pendingUndo?.requestId===receipt.requestId&&record2.pendingUndo.promptId!==receipt.promptId)invalid("promptId does not match pendingUndo");requests.add(receipt.requestId)}return{schemaVersion:1,state,pendingTurn:record2.pendingTurn,...record2.pendingMessageId!==void 0?{pendingMessageId:record2.pendingMessageId}:{},pendingUndo:record2.pendingUndo,undoReceipts}}__name(parseHostedFileHistoryRecord,"parseHostedFileHistoryRecord");init_esbuild_shims();import{createHash,randomBytes}from"node:crypto";var TOOL_PUBLICATION_PROTOCOL="managed-tool-publication/1";var TOOL_PUBLICATION_LIMITS=Object.freeze({maxBodyBytes:64*1024,maxCaptureBytes:2**41,producerBytes:2*1024*1024+64*1024+2*256*1024,admissionBytes:2*1024*1024});var BINDING_KEYS=["publication","publicationId","sessionKey","turnId","executionCallId","modelCallId","runtimeBindingId","reference","bindingGeneration","captureId","revision","captureScope","capturePolicy","argsRef","requestDigest","writerId","writerGeneration","activationId","activationEpoch","intentSequence","checkpointRef"];function requireValue(condition){if(!condition)throw new Error("Invalid managed tool publication.")}__name(requireValue,"requireValue");function closed(value,keys){requireValue(value!==null&&typeof value==="object");requireValue(Object.getPrototypeOf(value)===Object.prototype||Object.getPrototypeOf(value)===null);const present=Object.keys(value);requireValue(present.length===keys.length&&present.every(key=>keys.includes(key)));return Object.fromEntries(present.map(key=>[key,value[key]]))}__name(closed,"closed");function id(value){return assertManagedSessionStableId(value,"publication id")}__name(id,"id");function token(value){const text2=id(value);requireValue(/^[a-z0-9_-]{1,128}$/.test(text2));return text2}__name(token,"token");function count(value,max=Number.MAX_SAFE_INTEGER-1){const result=assertManagedSessionSequence(value,"publication count");requireValue(result>0&&result<=max);return result}__name(count,"count");function wireDigest(value){requireValue(typeof value==="string"&&/^sha256:[0-9a-f]{64}$/.test(value));return value}__name(wireDigest,"wireDigest");function ref(value,kind){const result=assertManagedSessionDurableRef(value,"publication ref");requireValue(result.kind===kind&&result.schemaVersion===1&&result.byteLength>0&&result.byteLength<=(kind==="managed-checkpoint"?MANAGED_SESSION_LIMITS.maxEventBytes:TOOL_PUBLICATION_LIMITS.maxBodyBytes));return Object.freeze(result)}__name(ref,"ref");function bounded(value){requireValue(Buffer.byteLength(JSON.stringify(value))<=TOOL_PUBLICATION_LIMITS.maxBodyBytes);return Object.freeze(value)}__name(bounded,"bounded");function parseToolPublicationBinding(value){const r=closed(value,BINDING_KEYS);requireValue(r["publication"]===TOOL_PUBLICATION_PROTOCOL&&r["revision"]===1&&r["captureScope"]==="process_pipes"&&r["capturePolicy"]==="complete_required");const generation=id(r["bindingGeneration"]);requireValue(/^[1-9][0-9]{0,18}$/.test(generation)&&BigInt(generation)<=9223372036854775807n);const reference=closed(r["reference"],["sessionId","promptId","callId","argsDigest"]);return bounded({publication:TOOL_PUBLICATION_PROTOCOL,publicationId:token(r["publicationId"]),sessionKey:Object.freeze(assertManagedSessionKey(r["sessionKey"])),turnId:id(r["turnId"]),executionCallId:id(r["executionCallId"]),modelCallId:id(r["modelCallId"]),runtimeBindingId:id(r["runtimeBindingId"]),reference:Object.freeze({sessionId:id(reference["sessionId"]),promptId:id(reference["promptId"]),callId:id(reference["callId"]),argsDigest:wireDigest(reference["argsDigest"])}),bindingGeneration:generation,captureId:token(r["captureId"]),revision:1,captureScope:"process_pipes",capturePolicy:"complete_required",argsRef:ref(r["argsRef"],"managed-tool-input"),requestDigest:wireDigest(r["requestDigest"]),writerId:id(r["writerId"]),writerGeneration:count(r["writerGeneration"]),activationId:id(r["activationId"]),activationEpoch:count(r["activationEpoch"]),intentSequence:count(r["intentSequence"]),checkpointRef:ref(r["checkpointRef"],"managed-checkpoint")})}__name(parseToolPublicationBinding,"parseToolPublicationBinding");function toolPublicationManifestIdentity(binding){const b=parseToolPublicationBinding(binding);return{tenantId:b.sessionKey.tenantId,sessionId:b.sessionKey.sessionId,turnId:b.turnId,executionCallId:b.executionCallId,callId:b.reference.callId,invocationDigest:b.reference.argsDigest,bindingGeneration:b.bindingGeneration,captureId:b.captureId,revision:b.revision}}__name(toolPublicationManifestIdentity,"toolPublicationManifestIdentity");function createToolPublicationToken(){return randomBytes(32).toString("base64url")}__name(createToolPublicationToken,"createToolPublicationToken");export{MANAGED_TOOL_FILE_HISTORY_MAX_BYTES,captureManagedToolExecutionContext,parseManagedToolFileHistoryPromptId,parseManagedToolFileHistoryBinding,parseManagedToolFileHistoryState,historyPath,parseHostedFileHistoryState,HOSTED_UUID,parseHostedFileHistoryRecord,parseToolPublicationBinding,toolPublicationManifestIdentity,createToolPublicationToken};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2026 Qwen Team
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{DEFAULT_DASHSCOPE_BASE_URL,DEFAULT_MAX_RETRIES,QWENCLOUD_MAAS_HOSTS,applyDeepSeekReasoningEffort,buildSessionAwareFetch,filterIsolatedModelOverrides,getBuiltinDeepSeekReasoning,getDashscopeProxyBaseUrl,getEffectiveReasoning,isDeepSeekEstablishedHost,isOpenRouterHostname,resolveReasoningDeclaration,resolveReasoningForModel,resolveRequestTimeout,withDashScopeSourceConfig,withoutDashScopeSourceConfig}from"./chunk-OHOG4HSN.js";import{REASONING_EFFORT_TIERS,clampReasoningEffort,defaultOutputCeiling,getGptReasoningCapabilities,hasExplicitOutputLimit,isQwenFamilyWireModel,isReasoningEffortPlaceholder,isTieredEffortWireModel,parsePositiveIntegerEnvValue,tokenLimit}from"./chunk-EV2CXPMN.js";import{buildRuntimeFetchOptions}from"./chunk-E5XJBLSO.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{OpenAI}from"./chunk-2UOMCYQG.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var debugLogger=createDebugLogger("DefaultOpenAICompatibleProvider");var OPENAI_COMPATIBLE_EFFORTS=["low","medium","high","xhigh"];function isQwen3Model(model){return model.toLowerCase().includes("qwen3")}__name(isQwen3Model,"isQwen3Model");function mirrorReasoningContentToReasoning(message){if(message.role!=="assistant"){return message}const assistant=message;if(typeof assistant.reasoning_content!=="string"||assistant.reasoning_content.length===0||typeof assistant.reasoning==="string"){return message}return{...assistant,reasoning:assistant.reasoning_content}}__name(mirrorReasoningContentToReasoning,"mirrorReasoningContentToReasoning");var DefaultOpenAICompatibleProvider=class{static{__name(this,"DefaultOpenAICompatibleProvider")}contentGeneratorConfig;cliConfig;effortClampWarned=false;constructor(contentGeneratorConfig,cliConfig){this.cliConfig=cliConfig;this.contentGeneratorConfig=contentGeneratorConfig}buildHeaders(){const version=this.cliConfig.getCliVersion()||"unknown";const userAgent=`QwenCode/${version} (${process.platform}; ${process.arch})`;const{customHeaders}=this.contentGeneratorConfig;const defaultHeaders={"User-Agent":userAgent};return customHeaders?{...defaultHeaders,...customHeaders}:defaultHeaders}buildClient(){const{apiKey,baseUrl,maxRetries=DEFAULT_MAX_RETRIES}=this.contentGeneratorConfig;const timeout=resolveRequestTimeout(this.contentGeneratorConfig.timeout);const defaultHeaders=this.buildHeaders();const runtimeOptions=buildRuntimeFetchOptions("openai",this.cliConfig.getProxy());return new OpenAI({apiKey,baseURL:baseUrl,...this.contentGeneratorConfig.isolatedRoute&&{organization:null,project:null},timeout,maxRetries,defaultHeaders,...runtimeOptions||{},fetch:buildSessionAwareFetch(runtimeOptions?.fetch,this.cliConfig,this.contentGeneratorConfig.customHeaders)})}supportedReasoningEffortsFor(model){const configured=this.getReasoningCapabilities(model);if(!configured?.profile&&!getGptReasoningCapabilities(model))return OPENAI_COMPATIBLE_EFFORTS;if(configured&&!configured.toggleOnly)return configured.efforts;return getGptReasoningCapabilities(model)?.efforts??OPENAI_COMPATIBLE_EFFORTS}getReasoningCapabilities(model){return resolveReasoningForModel(this.cliConfig,this.contentGeneratorConfig,model)}clampConfiguredReasoningEffort(request){if(this.contentGeneratorConfig.samplingParams?.["reasoning"]!==void 0||this.getReasoningCapabilities(request.model)?.profile){return request}const loose=request;const reasoning=loose["reasoning"];const effort=reasoning?.effort;if(typeof effort!=="string"||!REASONING_EFFORT_TIERS.includes(effort)){return request}const clamped=clampReasoningEffort(effort,this.supportedReasoningEffortsFor(loose["model"]??this.contentGeneratorConfig.model));if(clamped===effort){return request}if(!this.effortClampWarned){debugLogger.warn(`reasoning.effort='${effort}' is not accepted by this OpenAI-compatible endpoint; using '${clamped}'.`);this.effortClampWarned=true}return{...loose,reasoning:{...reasoning,effort:clamped}}}buildRequest(request,_userPromptId){const extraBody=filterIsolatedModelOverrides(this.contentGeneratorConfig.extra_body);const requestWithTokenLimits=this.clampConfiguredReasoningEffort(this.applyOutputTokenLimit(request));const profile=this.getReasoningCapabilities(request.model)?.profile;const messages=!profile&&isQwen3Model(request.model)||profile==="qwen-chat-template"?requestWithTokenLimits.messages.map(mirrorReasoningContentToReasoning):requestWithTokenLimits.messages;const result={...requestWithTokenLimits,messages,...extraBody?extraBody:{}};this.flattenGptReasoningEffort(result);return this.flattenDeepSeekReasoningEffort(result)}flattenDeepSeekReasoningEffort(body){const model=body.model;const resolved=this.getReasoningCapabilities(model);if(!getBuiltinDeepSeekReasoning({...this.contentGeneratorConfig,model})||!resolved||resolved.toggleOnly||resolved.profile!==void 0&&resolved.profile!=="deepseek-openai")return body;if(!isDeepSeekEstablishedHost(this.contentGeneratorConfig.baseUrl,model)&&resolveReasoningDeclaration(this.cliConfig,this.contentGeneratorConfig,model)!==void 0)return body;const reasoning=getEffectiveReasoning({...this.contentGeneratorConfig,model},resolved);const result=applyDeepSeekReasoningEffort(body,this.contentGeneratorConfig.baseUrl,(reasoning||void 0)?.effort);const loose=result;if(resolved.canDisable!==false&&(loose["reasoning_effort"]==="none"||(resolved.disableField==="thinking"?loose["thinking"]?.type==="disabled":loose["enable_thinking"]===false))){if(resolved.disableField==="thinking"){loose["thinking"]={type:"disabled"};delete loose["reasoning_effort"]}else if(resolved.disableField==="enable_thinking"){loose["enable_thinking"]=false;delete loose["reasoning_effort"]}}return result}flattenGptReasoningEffort(body){if(this.getReasoningCapabilities(body["model"])?.profile||!getGptReasoningCapabilities(body["model"])||isOpenRouterHostname(this.contentGeneratorConfig)||this.contentGeneratorConfig.samplingParams?.["reasoning"]!==void 0||this.contentGeneratorConfig.extra_body?.["reasoning"]!==void 0)return;const reasoning=body["reasoning"];if(typeof reasoning?.effort!=="string"||!reasoning.effort)return;if(isReasoningEffortPlaceholder(body["reasoning_effort"])){body["reasoning_effort"]=reasoning.effort}const{effort:_drop,...rest}=reasoning;if(Object.keys(rest).length>0)body["reasoning"]=rest;else delete body["reasoning"]}getDefaultGenerationConfig(){return{}}getResponseParsingOptions(model){return{contentOnlyThinkingTagLeaks:true,...model&&isQwen3Model(model)?{taggedThinkingTagsAfterReasoning:true}:{}}}applyOutputTokenLimit(request){if(this.contentGeneratorConfig.samplingParams!==void 0){return request}const userMaxTokens=request.max_tokens;const modelLimit=tokenLimit(request.model,"output");const isKnownModel=hasExplicitOutputLimit(request.model);let effectiveMaxTokens;if(userMaxTokens!==void 0&&userMaxTokens!==null){if(isKnownModel){effectiveMaxTokens=Math.min(userMaxTokens,modelLimit)}else{effectiveMaxTokens=userMaxTokens}}else{const envMaxTokens=parsePositiveIntegerEnvValue(process.env["QWEN_CODE_MAX_OUTPUT_TOKENS"]);if(envMaxTokens!==void 0){effectiveMaxTokens=isKnownModel?Math.min(envMaxTokens,modelLimit):envMaxTokens}else{effectiveMaxTokens=defaultOutputCeiling(request.model)}}return{...request,max_tokens:effectiveMaxTokens}}};init_esbuild_shims();var debugLogger2=createDebugLogger("DashScopeOpenAICompatibleProvider");var DASHSCOPE_TIERED_EFFORTS=["low","medium","high","xhigh"];var DASHSCOPE_OUTPUT_TOKEN_CAPS=new Map([["minimax-m2.5",32768]]);function selectDashScopeThinkingKnob(model,extraBody,samplingParams,reasoningEffort,tieredModel=isTieredEffortWireModel(model)){if(!tieredModel){return void 0}const selectFromLayer=__name((source,layer)=>{if(layer?.["enable_thinking"]===false){return{source,field:"enable_thinking",value:false}}return selectValueFromLayer(source,layer)??selectOnSwitch(source,layer)},"selectFromLayer");const selectValueFromLayer=__name((source,layer)=>{if(layer?.["reasoning_effort"]!=null){return{source,field:"reasoning_effort",value:layer["reasoning_effort"]}}if(layer?.["thinking_budget"]!=null){return{source,field:"thinking_budget",value:layer["thinking_budget"]}}return void 0},"selectValueFromLayer");const selectOnSwitch=__name((source,layer)=>{if(layer?.["enable_thinking"]===true){return{source,field:"enable_thinking",value:true}}return void 0},"selectOnSwitch");const reasoningSelection=reasoningEffort!==void 0?{source:"reasoning",field:"reasoning_effort",value:reasoningEffort}:void 0;const extraBodySelection=selectFromLayer("extra_body",extraBody);if(extraBodySelection?.field==="enable_thinking"&&extraBodySelection.value===true){return selectValueFromLayer("samplingParams",samplingParams)??reasoningSelection??extraBodySelection}if(extraBodySelection){return extraBodySelection}const samplingSelection=selectFromLayer("samplingParams",samplingParams);return samplingSelection?.field==="enable_thinking"&&samplingSelection.value===true?reasoningSelection??samplingSelection:samplingSelection??reasoningSelection}__name(selectDashScopeThinkingKnob,"selectDashScopeThinkingKnob");function withoutNullishThinkingKnobs(layer){if(!layer){return void 0}const hasNullishEnableThinking="enable_thinking"in layer&&layer["enable_thinking"]==null;const hasNullishEffort="reasoning_effort"in layer&&layer["reasoning_effort"]==null;const hasNullishBudget="thinking_budget"in layer&&layer["thinking_budget"]==null;if(!hasNullishEnableThinking&&!hasNullishEffort&&!hasNullishBudget){return layer}const sanitized={...layer};if(hasNullishEnableThinking){delete sanitized["enable_thinking"]}if(hasNullishEffort){delete sanitized["reasoning_effort"]}if(hasNullishBudget){delete sanitized["thinking_budget"]}return sanitized}__name(withoutNullishThinkingKnobs,"withoutNullishThinkingKnobs");var DASHSCOPE_REGIONAL_HOSTS=["dashscope.aliyuncs.com","dashscope-intl.aliyuncs.com","dashscope-us.aliyuncs.com"];var DashScopeOpenAICompatibleProvider=class _DashScopeOpenAICompatibleProvider extends DefaultOpenAICompatibleProvider{static{__name(this,"DashScopeOpenAICompatibleProvider")}constructor(contentGeneratorConfig,cliConfig){super(contentGeneratorConfig,cliConfig)}static isDashScopeProvider(contentGeneratorConfig){const{baseUrl}=contentGeneratorConfig;if(!baseUrl)return true;const normalizedBaseUrl=baseUrl.endsWith("/")?baseUrl.slice(0,-1):baseUrl;let hostname=null;try{hostname=new URL(normalizedBaseUrl).hostname.toLowerCase()}catch{hostname=null}const isDashscopeOrigin=hostname!==null&&DASHSCOPE_REGIONAL_HOSTS.some(host=>hostname===host||hostname.endsWith("."+host));const isMaasOrigin=hostname!==null&&hostname.endsWith(".maas.aliyuncs.com");const isQwenCloudOrigin=hostname!==null&&QWENCLOUD_MAAS_HOSTS.some(host=>hostname===host||hostname.endsWith("."+host));const isInternalOrigin=hostname!==null&&(hostname.endsWith(".alibaba-inc.com")||hostname.endsWith(".aliyun-inc.com"));const isAliCloudApiOrigin=hostname!==null&&hostname.endsWith(".alicloudapi.com");const proxyBaseUrl=getDashscopeProxyBaseUrl();const normalizedProxyUrl=proxyBaseUrl?.endsWith("/")?proxyBaseUrl.slice(0,-1):proxyBaseUrl;const isProxyMatch=Boolean(normalizedProxyUrl&&normalizedBaseUrl.toLowerCase()===normalizedProxyUrl.toLowerCase());if(normalizedProxyUrl&&!isDashscopeOrigin&&!isMaasOrigin&&!isQwenCloudOrigin&&!isInternalOrigin&&!isAliCloudApiOrigin&&!isProxyMatch){debugLogger2.debug(`DASHSCOPE_PROXY_BASE_URL is configured but the request baseUrl does not match. DashScope headers/cache control will be skipped.`)}if(isInternalOrigin){debugLogger2.debug(`DashScope provider activated via internal origin: ${hostname}`)}if(isAliCloudApiOrigin){debugLogger2.debug(`DashScope provider activated via alicloudapi origin: ${hostname}`)}return isDashscopeOrigin||isMaasOrigin||isQwenCloudOrigin||isInternalOrigin||isAliCloudApiOrigin||isProxyMatch}buildHeaders(){const version=this.cliConfig.getCliVersion()||"unknown";const userAgent=`QwenCode/${version} (${process.platform}; ${process.arch})`;const{authType,customHeaders}=this.contentGeneratorConfig;const defaultHeaders={"User-Agent":userAgent,"X-DashScope-CacheControl":"enable","X-DashScope-UserAgent":userAgent,"X-DashScope-AuthType":authType};if(this.cliConfig.isOmniEnabled?.()){defaultHeaders["X-DashScope-OssResourceResolve"]="enable"}return withDashScopeSourceConfig(customHeaders?{...defaultHeaders,...customHeaders}:defaultHeaders,this.contentGeneratorConfig.baseUrl,this.cliConfig.getChannel?.())}buildClient(){const{apiKey,baseUrl=DEFAULT_DASHSCOPE_BASE_URL,maxRetries=DEFAULT_MAX_RETRIES}=this.contentGeneratorConfig;const timeout=resolveRequestTimeout(this.contentGeneratorConfig.timeout);const defaultHeaders=this.buildHeaders();const runtimeOptions=buildRuntimeFetchOptions("openai",this.cliConfig.getProxy());return new OpenAI({apiKey,baseURL:baseUrl,...this.contentGeneratorConfig.isolatedRoute&&{organization:null,project:null},timeout,maxRetries,defaultHeaders,...runtimeOptions||{},fetch:buildSessionAwareFetch(runtimeOptions?.fetch,this.cliConfig,withoutDashScopeSourceConfig(this.contentGeneratorConfig.customHeaders))})}buildRequest(request,userPromptId,reattachBlockCount=0){let messages=request.messages;const tools=request.tools;const flattenPlainTextForGlm=this.isGlmModel(request.model)&&!this.hasFunctionCallingContext(request);if(flattenPlainTextForGlm){messages=this.flattenTextContent(messages)}else if(this.shouldEnableCacheControl()){messages=this.addDashScopeCacheControl(request,request.stream?"all":"system_only",reattachBlockCount)}const requestWithTokenLimits=this.applyOutputTokenLimit(request);const isTieredQwenModel=this.isTieredEffortModel(request.model);const configuredExtraBody=filterIsolatedModelOverrides(this.contentGeneratorConfig.extra_body);const extraBody=isTieredQwenModel?withoutNullishThinkingKnobs(configuredExtraBody):configuredExtraBody;const qwenEffortConfig=this.buildQwenEffortConfig(request.model);const rawRequestParams=requestWithTokenLimits;const requestParams=isTieredQwenModel?withoutNullishThinkingKnobs(rawRequestParams):rawRequestParams;if("reasoning_effort"in requestParams&&"reasoning_effort"in qwenEffortConfig){qwenEffortConfig["reasoning_effort"]=requestParams["reasoning_effort"]}const hasQwenEffortConfig=Object.keys(qwenEffortConfig).length>0;const selectedThinkingKnob=isTieredQwenModel?selectDashScopeThinkingKnob(this.resolveWireModel(request.model),extraBody,requestParams,qwenEffortConfig["reasoning_effort"],isTieredQwenModel):void 0;if(this.isVisionModel(request.model)){const dashscopeExtras2={vl_high_resolution_images:true,preserve_thinking:true,...qwenEffortConfig};const visionResult={...requestParams,messages,...tools?{tools}:{},...this.buildRequestMetadata(request.model,userPromptId),...dashscopeExtras2};if(hasQwenEffortConfig&&"reasoning"in visionResult){delete visionResult["reasoning"]}return this.mergeExtraBodyAndResolveKnobs(hasQwenEffortConfig?visionResult:this.clampConfiguredReasoningEffort(visionResult),extraBody,request.model,selectedThinkingKnob)}const dashscopeExtras={preserve_thinking:true,...qwenEffortConfig};const result={...requestParams,messages,...tools?{tools}:{},...this.buildRequestMetadata(request.model,userPromptId),...dashscopeExtras};if(hasQwenEffortConfig&&"reasoning"in result){delete result["reasoning"]}return this.mergeExtraBodyAndResolveKnobs(hasQwenEffortConfig?result:this.clampConfiguredReasoningEffort(result),extraBody,request.model,selectedThinkingKnob)}mergeExtraBodyAndResolveKnobs(result,extraBody,model,selectedThinkingKnob){const merged={...result,...extraBody?extraBody:{}};this.capHostedOutputTokens(merged,model);const reasoningEffort=merged["reasoning_effort"];const dropped=new Set;if(selectedThinkingKnob?.field==="thinking_budget"){if(reasoningEffort!==void 0){dropped.add("reasoning_effort")}if(merged["enable_thinking"]===false){dropped.add("enable_thinking")}}if(selectedThinkingKnob?.field==="reasoning_effort"&&merged["thinking_budget"]!==void 0){dropped.add("thinking_budget")}for(const key of dropped){delete merged[key]}for(const key of this.dropConflictingThinkingKnobs(model,merged,selectedThinkingKnob)){dropped.add(key)}this.warnConflictingKnobDrop(model,reasoningEffort,[...dropped]);this.flattenGptReasoningEffort(merged);return this.flattenDeepSeekReasoningEffort(merged)}getConfiguredReasoning(model){return this.getReasoningCapabilities(model)}isTieredEffortModel(model){const configured=this.getConfiguredReasoning(model);if(configured?.profile)return configured.profile==="dashscope-effort";return isTieredEffortWireModel(model??this.contentGeneratorConfig.model,configured)}resolveWireModel(model){return(model??this.contentGeneratorConfig.model??"").toLowerCase()}buildQwenEffortConfig(model){const configured=this.getConfiguredReasoning(model);if(configured?.profile)return{};const reasoning=getEffectiveReasoning(this.contentGeneratorConfig,configured);if(!reasoning||reasoning.effort===void 0){return{}}const wireModel=this.resolveWireModel(model);if(this.isTieredEffortModel(model)){const configured2=this.getConfiguredReasoning(model);if(configured2&&!configured2.toggleOnly){return configured2.efforts.includes(reasoning.effort)?{reasoning_effort:reasoning.effort}:{}}return{reasoning_effort:this.clampTieredEffort(reasoning.effort)}}if(isQwenFamilyWireModel(wireModel)){return{enable_thinking:true}}return{}}capHostedOutputTokens(merged,model){const cap=DASHSCOPE_OUTPUT_TOKEN_CAPS.get(this.resolveWireModel(model));const maxTokens=merged["max_tokens"];if(cap!==void 0&&typeof maxTokens==="number"&&maxTokens>cap){merged["max_tokens"]=cap}}clampTieredEffort(effort){const clamped=clampReasoningEffort(effort,DASHSCOPE_TIERED_EFFORTS);if(clamped!==effort&&!this.effortClampWarned){debugLogger2.warn(`reasoning.effort='${effort}' is not accepted by the DashScope tiered-effort family; using '${clamped}'.`);this.effortClampWarned=true}return clamped}dropConflictingThinkingKnobs(model,merged,selectedThinkingKnob){const wireModel=this.resolveWireModel(model);if(!isQwenFamilyWireModel(wireModel)){return[]}const isTieredEffortModel=this.isTieredEffortModel(model);if(isTieredEffortModel&&selectedThinkingKnob?.field==="enable_thinking"&&selectedThinkingKnob.value===false){merged["reasoning_effort"]="none";const dropped=["enable_thinking"];if(merged["thinking_budget"]!==void 0){dropped.push("thinking_budget")}for(const key of dropped){delete merged[key]}return dropped}const effort=merged["reasoning_effort"];if(typeof effort!=="string"){return[]}if(isTieredEffortModel&&effort==="none"){if(merged["thinking_budget"]===void 0){return[]}delete merged["thinking_budget"];return["thinking_budget"]}if(isTieredEffortModel){if(selectedThinkingKnob?.field==="reasoning_effort"&&"enable_thinking"in merged){delete merged["enable_thinking"];return["enable_thinking"]}return[]}if(merged["thinking_budget"]===void 0){return[]}delete merged["reasoning_effort"];return["reasoning_effort"]}warnConflictingKnobDrop(model,reasoningEffort,dropped){if(dropped.length===0){return}if(!this.conflictingKnobDropWarned){this.conflictingKnobDropWarned=true;debugLogger2.warn("DashScope: dropped conflicting thinking knobs",{model:this.resolveWireModel(model),reasoningEffort,dropped})}}conflictingKnobDropWarned=false;buildRequestMetadata(model,userPromptId){if(!this.shouldSendRequestMetadata(model)){return{}}return this.buildMetadata(userPromptId)||{}}shouldSendRequestMetadata(model){const configured=this.contentGeneratorConfig.enableRequestMetadata;if(typeof configured==="boolean"){return configured}return isQwenFamilyWireModel(this.resolveWireModel(model))}buildMetadata(userPromptId){const channel=this.cliConfig.getChannel?.();return{metadata:{sessionId:this.cliConfig.getSessionId?.(),promptId:userPromptId,...channel?{channel}:{}}}}getDefaultGenerationConfig(){return{}}addDashScopeCacheControl(request,cacheControl,reattachBlockCount=0){const messages=request.messages;const systemIndex=messages.findIndex(msg=>msg.role==="system");const lastIndex=messages.length-1;const stableBlock=reattachBlockCount>0&&lastIndex>=0?this.lastStableBlock(messages,reattachBlockCount):{messageIndex:lastIndex,excludeTail:0};const updatedMessages=messages.length===0?messages:messages.map((message,index)=>{const isConversationAnchor=stableBlock?.messageIndex===index&&cacheControl==="all";const shouldAddCacheControl=Boolean(index===systemIndex&&systemIndex!==-1||isConversationAnchor);if(!shouldAddCacheControl||!("content"in message)||message.content===null||message.content===void 0){return message}return{...message,content:this.addCacheControlToContent(message.content,isConversationAnchor&&stableBlock?stableBlock.excludeTail:0)}});return updatedMessages}lastStableBlock(messages,reattachBlockCount){let remaining=reattachBlockCount;for(let index=messages.length-1;index>=0;index--){const content=messages[index].content;const blockCount=typeof content==="string"?content.length>0?1:0:Array.isArray(content)?content.length:0;if(blockCount===0)continue;if(blockCount>remaining){if(remaining>0){remaining=0;continue}return{messageIndex:index,excludeTail:remaining}}remaining-=blockCount}return void 0}addCacheControlToContent(content,excludeTail=0){const contentArray=this.normalizeContentToArray(content);return this.addCacheControlToContentArray(contentArray,excludeTail)}normalizeContentToArray(content){if(typeof content==="string"){return[{type:"text",text:content}]}return[...content]}addCacheControlToContentArray(contentArray,excludeTail=0){if(contentArray.length===0){return contentArray}let targetIndex=contentArray.length-1-excludeTail;if(targetIndex<0){return contentArray}if(excludeTail>0){while(targetIndex>0&&contentArray[targetIndex].type!=="text"){targetIndex-=1}}const lastItem=contentArray[targetIndex];contentArray[targetIndex]={...lastItem,cache_control:{type:"ephemeral"}};return contentArray}isGlmModel(model){return!!model&&model.toLowerCase().startsWith("glm-")}hasFunctionCallingContext(request){if(request.tools&&request.tools.length>0){return true}return request.messages.some(message=>{if(message.role==="tool"){return true}if(message.role==="assistant"){const toolCalls=message.tool_calls;return Array.isArray(toolCalls)&&toolCalls.length>0}return false})}flattenTextContent(messages){return messages.map(message=>{if(!("content"in message)||!Array.isArray(message.content)){return message}const parts=message.content;if(parts.length===0){return message}const isTextOnly=parts.every(part=>part&&part.type==="text");if(!isTextOnly){return message}const text=parts.map(part=>part.text??"").join("\n\n");return{...message,content:text}})}static VISION_MODEL_EXACT_MATCHES=new Set(["coder-model"]);static VISION_MODEL_PREFIX_PATTERNS=["qwen-vl","qwen3-vl-plus","qwen3.5-plus","qwen3.6-plus","qwen3.7-plus"];isVisionModel(model){if(!model){return false}const normalized=model.toLowerCase();if(_DashScopeOpenAICompatibleProvider.VISION_MODEL_EXACT_MATCHES.has(normalized)){return true}for(const prefix of _DashScopeOpenAICompatibleProvider.VISION_MODEL_PREFIX_PATTERNS){if(normalized.startsWith(prefix)){return true}}return false}shouldEnableCacheControl(){const config=this.contentGeneratorConfig.isolatedRoute?this.contentGeneratorConfig:this.cliConfig.getContentGeneratorConfig();return config?.enableCacheControl!==false}};export{DefaultOpenAICompatibleProvider,selectDashScopeThinkingKnob,DASHSCOPE_REGIONAL_HOSTS,DashScopeOpenAICompatibleProvider};
|
|
3
|
+
import{DEFAULT_DASHSCOPE_BASE_URL,DEFAULT_MAX_RETRIES,QWENCLOUD_MAAS_HOSTS,applyDeepSeekReasoningEffort,buildSessionAwareFetch,filterIsolatedModelOverrides,getBuiltinDeepSeekReasoning,getDashscopeProxyBaseUrl,getEffectiveReasoning,isDeepSeekEstablishedHost,isOpenRouterHostname,resolveReasoningDeclaration,resolveReasoningForModel,resolveRequestTimeout,withDashScopeSourceConfig,withoutDashScopeSourceConfig}from"./chunk-SINRWOVD.js";import{REASONING_EFFORT_TIERS,clampReasoningEffort,defaultOutputCeiling,getGptReasoningCapabilities,hasExplicitOutputLimit,isQwenFamilyWireModel,isReasoningEffortPlaceholder,isTieredEffortWireModel,parsePositiveIntegerEnvValue,tokenLimit}from"./chunk-EV2CXPMN.js";import{buildRuntimeFetchOptions}from"./chunk-E5XJBLSO.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{OpenAI}from"./chunk-2UOMCYQG.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var debugLogger=createDebugLogger("DefaultOpenAICompatibleProvider");var OPENAI_COMPATIBLE_EFFORTS=["low","medium","high","xhigh"];function isQwen3Model(model){return model.toLowerCase().includes("qwen3")}__name(isQwen3Model,"isQwen3Model");function mirrorReasoningContentToReasoning(message){if(message.role!=="assistant"){return message}const assistant=message;if(typeof assistant.reasoning_content!=="string"||assistant.reasoning_content.length===0||typeof assistant.reasoning==="string"){return message}return{...assistant,reasoning:assistant.reasoning_content}}__name(mirrorReasoningContentToReasoning,"mirrorReasoningContentToReasoning");var DefaultOpenAICompatibleProvider=class{static{__name(this,"DefaultOpenAICompatibleProvider")}contentGeneratorConfig;cliConfig;effortClampWarned=false;constructor(contentGeneratorConfig,cliConfig){this.cliConfig=cliConfig;this.contentGeneratorConfig=contentGeneratorConfig}buildHeaders(){const version=this.cliConfig.getCliVersion()||"unknown";const userAgent=`QwenCode/${version} (${process.platform}; ${process.arch})`;const{customHeaders}=this.contentGeneratorConfig;const defaultHeaders={"User-Agent":userAgent};return customHeaders?{...defaultHeaders,...customHeaders}:defaultHeaders}buildClient(){const{apiKey,baseUrl,maxRetries=DEFAULT_MAX_RETRIES}=this.contentGeneratorConfig;const timeout=resolveRequestTimeout(this.contentGeneratorConfig.timeout);const defaultHeaders=this.buildHeaders();const runtimeOptions=buildRuntimeFetchOptions("openai",this.cliConfig.getProxy());return new OpenAI({apiKey,baseURL:baseUrl,...this.contentGeneratorConfig.isolatedRoute&&{organization:null,project:null},timeout,maxRetries,defaultHeaders,...runtimeOptions||{},fetch:buildSessionAwareFetch(runtimeOptions?.fetch,this.cliConfig,this.contentGeneratorConfig.customHeaders)})}supportedReasoningEffortsFor(model){const configured=this.getReasoningCapabilities(model);if(!configured?.profile&&!getGptReasoningCapabilities(model))return OPENAI_COMPATIBLE_EFFORTS;if(configured&&!configured.toggleOnly)return configured.efforts;return getGptReasoningCapabilities(model)?.efforts??OPENAI_COMPATIBLE_EFFORTS}getReasoningCapabilities(model){return resolveReasoningForModel(this.cliConfig,this.contentGeneratorConfig,model)}clampConfiguredReasoningEffort(request){if(this.contentGeneratorConfig.samplingParams?.["reasoning"]!==void 0||this.getReasoningCapabilities(request.model)?.profile){return request}const loose=request;const reasoning=loose["reasoning"];const effort=reasoning?.effort;if(typeof effort!=="string"||!REASONING_EFFORT_TIERS.includes(effort)){return request}const clamped=clampReasoningEffort(effort,this.supportedReasoningEffortsFor(loose["model"]??this.contentGeneratorConfig.model));if(clamped===effort){return request}if(!this.effortClampWarned){debugLogger.warn(`reasoning.effort='${effort}' is not accepted by this OpenAI-compatible endpoint; using '${clamped}'.`);this.effortClampWarned=true}return{...loose,reasoning:{...reasoning,effort:clamped}}}buildRequest(request,_userPromptId){const extraBody=filterIsolatedModelOverrides(this.contentGeneratorConfig.extra_body);const requestWithTokenLimits=this.clampConfiguredReasoningEffort(this.applyOutputTokenLimit(request));const profile=this.getReasoningCapabilities(request.model)?.profile;const messages=!profile&&isQwen3Model(request.model)||profile==="qwen-chat-template"?requestWithTokenLimits.messages.map(mirrorReasoningContentToReasoning):requestWithTokenLimits.messages;const result={...requestWithTokenLimits,messages,...extraBody?extraBody:{}};this.flattenGptReasoningEffort(result);return this.flattenDeepSeekReasoningEffort(result)}flattenDeepSeekReasoningEffort(body){const model=body.model;const resolved=this.getReasoningCapabilities(model);if(!getBuiltinDeepSeekReasoning({...this.contentGeneratorConfig,model})||!resolved||resolved.toggleOnly||resolved.profile!==void 0&&resolved.profile!=="deepseek-openai")return body;if(!isDeepSeekEstablishedHost(this.contentGeneratorConfig.baseUrl,model)&&resolveReasoningDeclaration(this.cliConfig,this.contentGeneratorConfig,model)!==void 0)return body;const reasoning=getEffectiveReasoning({...this.contentGeneratorConfig,model},resolved);const result=applyDeepSeekReasoningEffort(body,this.contentGeneratorConfig.baseUrl,(reasoning||void 0)?.effort);const loose=result;if(resolved.canDisable!==false&&(loose["reasoning_effort"]==="none"||(resolved.disableField==="thinking"?loose["thinking"]?.type==="disabled":loose["enable_thinking"]===false))){if(resolved.disableField==="thinking"){loose["thinking"]={type:"disabled"};delete loose["reasoning_effort"]}else if(resolved.disableField==="enable_thinking"){loose["enable_thinking"]=false;delete loose["reasoning_effort"]}}return result}flattenGptReasoningEffort(body){if(this.getReasoningCapabilities(body["model"])?.profile||!getGptReasoningCapabilities(body["model"])||isOpenRouterHostname(this.contentGeneratorConfig)||this.contentGeneratorConfig.samplingParams?.["reasoning"]!==void 0||this.contentGeneratorConfig.extra_body?.["reasoning"]!==void 0)return;const reasoning=body["reasoning"];if(typeof reasoning?.effort!=="string"||!reasoning.effort)return;if(isReasoningEffortPlaceholder(body["reasoning_effort"])){body["reasoning_effort"]=reasoning.effort}const{effort:_drop,...rest}=reasoning;if(Object.keys(rest).length>0)body["reasoning"]=rest;else delete body["reasoning"]}getDefaultGenerationConfig(){return{}}getResponseParsingOptions(model){return{contentOnlyThinkingTagLeaks:true,...model&&isQwen3Model(model)?{taggedThinkingTagsAfterReasoning:true}:{}}}applyOutputTokenLimit(request){if(this.contentGeneratorConfig.samplingParams!==void 0){return request}const userMaxTokens=request.max_tokens;const modelLimit=tokenLimit(request.model,"output");const isKnownModel=hasExplicitOutputLimit(request.model);let effectiveMaxTokens;if(userMaxTokens!==void 0&&userMaxTokens!==null){if(isKnownModel){effectiveMaxTokens=Math.min(userMaxTokens,modelLimit)}else{effectiveMaxTokens=userMaxTokens}}else{const envMaxTokens=parsePositiveIntegerEnvValue(process.env["QWEN_CODE_MAX_OUTPUT_TOKENS"]);if(envMaxTokens!==void 0){effectiveMaxTokens=isKnownModel?Math.min(envMaxTokens,modelLimit):envMaxTokens}else{effectiveMaxTokens=defaultOutputCeiling(request.model)}}return{...request,max_tokens:effectiveMaxTokens}}};init_esbuild_shims();var debugLogger2=createDebugLogger("DashScopeOpenAICompatibleProvider");var DASHSCOPE_TIERED_EFFORTS=["low","medium","high","xhigh"];var DASHSCOPE_OUTPUT_TOKEN_CAPS=new Map([["minimax-m2.5",32768]]);function selectDashScopeThinkingKnob(model,extraBody,samplingParams,reasoningEffort,tieredModel=isTieredEffortWireModel(model)){if(!tieredModel){return void 0}const selectFromLayer=__name((source,layer)=>{if(layer?.["enable_thinking"]===false){return{source,field:"enable_thinking",value:false}}return selectValueFromLayer(source,layer)??selectOnSwitch(source,layer)},"selectFromLayer");const selectValueFromLayer=__name((source,layer)=>{if(layer?.["reasoning_effort"]!=null){return{source,field:"reasoning_effort",value:layer["reasoning_effort"]}}if(layer?.["thinking_budget"]!=null){return{source,field:"thinking_budget",value:layer["thinking_budget"]}}return void 0},"selectValueFromLayer");const selectOnSwitch=__name((source,layer)=>{if(layer?.["enable_thinking"]===true){return{source,field:"enable_thinking",value:true}}return void 0},"selectOnSwitch");const reasoningSelection=reasoningEffort!==void 0?{source:"reasoning",field:"reasoning_effort",value:reasoningEffort}:void 0;const extraBodySelection=selectFromLayer("extra_body",extraBody);if(extraBodySelection?.field==="enable_thinking"&&extraBodySelection.value===true){return selectValueFromLayer("samplingParams",samplingParams)??reasoningSelection??extraBodySelection}if(extraBodySelection){return extraBodySelection}const samplingSelection=selectFromLayer("samplingParams",samplingParams);return samplingSelection?.field==="enable_thinking"&&samplingSelection.value===true?reasoningSelection??samplingSelection:samplingSelection??reasoningSelection}__name(selectDashScopeThinkingKnob,"selectDashScopeThinkingKnob");function withoutNullishThinkingKnobs(layer){if(!layer){return void 0}const hasNullishEnableThinking="enable_thinking"in layer&&layer["enable_thinking"]==null;const hasNullishEffort="reasoning_effort"in layer&&layer["reasoning_effort"]==null;const hasNullishBudget="thinking_budget"in layer&&layer["thinking_budget"]==null;if(!hasNullishEnableThinking&&!hasNullishEffort&&!hasNullishBudget){return layer}const sanitized={...layer};if(hasNullishEnableThinking){delete sanitized["enable_thinking"]}if(hasNullishEffort){delete sanitized["reasoning_effort"]}if(hasNullishBudget){delete sanitized["thinking_budget"]}return sanitized}__name(withoutNullishThinkingKnobs,"withoutNullishThinkingKnobs");var DASHSCOPE_REGIONAL_HOSTS=["dashscope.aliyuncs.com","dashscope-intl.aliyuncs.com","dashscope-us.aliyuncs.com"];var DashScopeOpenAICompatibleProvider=class _DashScopeOpenAICompatibleProvider extends DefaultOpenAICompatibleProvider{static{__name(this,"DashScopeOpenAICompatibleProvider")}constructor(contentGeneratorConfig,cliConfig){super(contentGeneratorConfig,cliConfig)}static isDashScopeProvider(contentGeneratorConfig){const{baseUrl}=contentGeneratorConfig;if(!baseUrl)return true;const normalizedBaseUrl=baseUrl.endsWith("/")?baseUrl.slice(0,-1):baseUrl;let hostname=null;try{hostname=new URL(normalizedBaseUrl).hostname.toLowerCase()}catch{hostname=null}const isDashscopeOrigin=hostname!==null&&DASHSCOPE_REGIONAL_HOSTS.some(host=>hostname===host||hostname.endsWith("."+host));const isMaasOrigin=hostname!==null&&hostname.endsWith(".maas.aliyuncs.com");const isQwenCloudOrigin=hostname!==null&&QWENCLOUD_MAAS_HOSTS.some(host=>hostname===host||hostname.endsWith("."+host));const isInternalOrigin=hostname!==null&&(hostname.endsWith(".alibaba-inc.com")||hostname.endsWith(".aliyun-inc.com"));const isAliCloudApiOrigin=hostname!==null&&hostname.endsWith(".alicloudapi.com");const proxyBaseUrl=getDashscopeProxyBaseUrl();const normalizedProxyUrl=proxyBaseUrl?.endsWith("/")?proxyBaseUrl.slice(0,-1):proxyBaseUrl;const isProxyMatch=Boolean(normalizedProxyUrl&&normalizedBaseUrl.toLowerCase()===normalizedProxyUrl.toLowerCase());if(normalizedProxyUrl&&!isDashscopeOrigin&&!isMaasOrigin&&!isQwenCloudOrigin&&!isInternalOrigin&&!isAliCloudApiOrigin&&!isProxyMatch){debugLogger2.debug(`DASHSCOPE_PROXY_BASE_URL is configured but the request baseUrl does not match. DashScope headers/cache control will be skipped.`)}if(isInternalOrigin){debugLogger2.debug(`DashScope provider activated via internal origin: ${hostname}`)}if(isAliCloudApiOrigin){debugLogger2.debug(`DashScope provider activated via alicloudapi origin: ${hostname}`)}return isDashscopeOrigin||isMaasOrigin||isQwenCloudOrigin||isInternalOrigin||isAliCloudApiOrigin||isProxyMatch}buildHeaders(){const version=this.cliConfig.getCliVersion()||"unknown";const userAgent=`QwenCode/${version} (${process.platform}; ${process.arch})`;const{authType,customHeaders}=this.contentGeneratorConfig;const defaultHeaders={"User-Agent":userAgent,"X-DashScope-CacheControl":"enable","X-DashScope-UserAgent":userAgent,"X-DashScope-AuthType":authType};if(this.cliConfig.isOmniEnabled?.()){defaultHeaders["X-DashScope-OssResourceResolve"]="enable"}return withDashScopeSourceConfig(customHeaders?{...defaultHeaders,...customHeaders}:defaultHeaders,this.contentGeneratorConfig.baseUrl,this.cliConfig.getChannel?.())}buildClient(){const{apiKey,baseUrl=DEFAULT_DASHSCOPE_BASE_URL,maxRetries=DEFAULT_MAX_RETRIES}=this.contentGeneratorConfig;const timeout=resolveRequestTimeout(this.contentGeneratorConfig.timeout);const defaultHeaders=this.buildHeaders();const runtimeOptions=buildRuntimeFetchOptions("openai",this.cliConfig.getProxy());return new OpenAI({apiKey,baseURL:baseUrl,...this.contentGeneratorConfig.isolatedRoute&&{organization:null,project:null},timeout,maxRetries,defaultHeaders,...runtimeOptions||{},fetch:buildSessionAwareFetch(runtimeOptions?.fetch,this.cliConfig,withoutDashScopeSourceConfig(this.contentGeneratorConfig.customHeaders))})}buildRequest(request,userPromptId,reattachBlockCount=0){let messages=request.messages;const tools=request.tools;const flattenPlainTextForGlm=this.isGlmModel(request.model)&&!this.hasFunctionCallingContext(request);if(flattenPlainTextForGlm){messages=this.flattenTextContent(messages)}else if(this.shouldEnableCacheControl()){messages=this.addDashScopeCacheControl(request,request.stream?"all":"system_only",reattachBlockCount)}const requestWithTokenLimits=this.applyOutputTokenLimit(request);const isTieredQwenModel=this.isTieredEffortModel(request.model);const configuredExtraBody=filterIsolatedModelOverrides(this.contentGeneratorConfig.extra_body);const extraBody=isTieredQwenModel?withoutNullishThinkingKnobs(configuredExtraBody):configuredExtraBody;const qwenEffortConfig=this.buildQwenEffortConfig(request.model);const rawRequestParams=requestWithTokenLimits;const requestParams=isTieredQwenModel?withoutNullishThinkingKnobs(rawRequestParams):rawRequestParams;if("reasoning_effort"in requestParams&&"reasoning_effort"in qwenEffortConfig){qwenEffortConfig["reasoning_effort"]=requestParams["reasoning_effort"]}const hasQwenEffortConfig=Object.keys(qwenEffortConfig).length>0;const selectedThinkingKnob=isTieredQwenModel?selectDashScopeThinkingKnob(this.resolveWireModel(request.model),extraBody,requestParams,qwenEffortConfig["reasoning_effort"],isTieredQwenModel):void 0;if(this.isVisionModel(request.model)){const dashscopeExtras2={vl_high_resolution_images:true,preserve_thinking:true,...qwenEffortConfig};const visionResult={...requestParams,messages,...tools?{tools}:{},...this.buildRequestMetadata(request.model,userPromptId),...dashscopeExtras2};if(hasQwenEffortConfig&&"reasoning"in visionResult){delete visionResult["reasoning"]}return this.mergeExtraBodyAndResolveKnobs(hasQwenEffortConfig?visionResult:this.clampConfiguredReasoningEffort(visionResult),extraBody,request.model,selectedThinkingKnob)}const dashscopeExtras={preserve_thinking:true,...qwenEffortConfig};const result={...requestParams,messages,...tools?{tools}:{},...this.buildRequestMetadata(request.model,userPromptId),...dashscopeExtras};if(hasQwenEffortConfig&&"reasoning"in result){delete result["reasoning"]}return this.mergeExtraBodyAndResolveKnobs(hasQwenEffortConfig?result:this.clampConfiguredReasoningEffort(result),extraBody,request.model,selectedThinkingKnob)}mergeExtraBodyAndResolveKnobs(result,extraBody,model,selectedThinkingKnob){const merged={...result,...extraBody?extraBody:{}};this.capHostedOutputTokens(merged,model);const reasoningEffort=merged["reasoning_effort"];const dropped=new Set;if(selectedThinkingKnob?.field==="thinking_budget"){if(reasoningEffort!==void 0){dropped.add("reasoning_effort")}if(merged["enable_thinking"]===false){dropped.add("enable_thinking")}}if(selectedThinkingKnob?.field==="reasoning_effort"&&merged["thinking_budget"]!==void 0){dropped.add("thinking_budget")}for(const key of dropped){delete merged[key]}for(const key of this.dropConflictingThinkingKnobs(model,merged,selectedThinkingKnob)){dropped.add(key)}this.warnConflictingKnobDrop(model,reasoningEffort,[...dropped]);this.flattenGptReasoningEffort(merged);return this.flattenDeepSeekReasoningEffort(merged)}getConfiguredReasoning(model){return this.getReasoningCapabilities(model)}isTieredEffortModel(model){const configured=this.getConfiguredReasoning(model);if(configured?.profile)return configured.profile==="dashscope-effort";return isTieredEffortWireModel(model??this.contentGeneratorConfig.model,configured)}resolveWireModel(model){return(model??this.contentGeneratorConfig.model??"").toLowerCase()}buildQwenEffortConfig(model){const configured=this.getConfiguredReasoning(model);if(configured?.profile)return{};const reasoning=getEffectiveReasoning(this.contentGeneratorConfig,configured);if(!reasoning||reasoning.effort===void 0){return{}}const wireModel=this.resolveWireModel(model);if(this.isTieredEffortModel(model)){const configured2=this.getConfiguredReasoning(model);if(configured2&&!configured2.toggleOnly){return configured2.efforts.includes(reasoning.effort)?{reasoning_effort:reasoning.effort}:{}}return{reasoning_effort:this.clampTieredEffort(reasoning.effort)}}if(isQwenFamilyWireModel(wireModel)){return{enable_thinking:true}}return{}}capHostedOutputTokens(merged,model){const cap=DASHSCOPE_OUTPUT_TOKEN_CAPS.get(this.resolveWireModel(model));const maxTokens=merged["max_tokens"];if(cap!==void 0&&typeof maxTokens==="number"&&maxTokens>cap){merged["max_tokens"]=cap}}clampTieredEffort(effort){const clamped=clampReasoningEffort(effort,DASHSCOPE_TIERED_EFFORTS);if(clamped!==effort&&!this.effortClampWarned){debugLogger2.warn(`reasoning.effort='${effort}' is not accepted by the DashScope tiered-effort family; using '${clamped}'.`);this.effortClampWarned=true}return clamped}dropConflictingThinkingKnobs(model,merged,selectedThinkingKnob){const wireModel=this.resolveWireModel(model);if(!isQwenFamilyWireModel(wireModel)){return[]}const isTieredEffortModel=this.isTieredEffortModel(model);if(isTieredEffortModel&&selectedThinkingKnob?.field==="enable_thinking"&&selectedThinkingKnob.value===false){merged["reasoning_effort"]="none";const dropped=["enable_thinking"];if(merged["thinking_budget"]!==void 0){dropped.push("thinking_budget")}for(const key of dropped){delete merged[key]}return dropped}const effort=merged["reasoning_effort"];if(typeof effort!=="string"){return[]}if(isTieredEffortModel&&effort==="none"){if(merged["thinking_budget"]===void 0){return[]}delete merged["thinking_budget"];return["thinking_budget"]}if(isTieredEffortModel){if(selectedThinkingKnob?.field==="reasoning_effort"&&"enable_thinking"in merged){delete merged["enable_thinking"];return["enable_thinking"]}return[]}if(merged["thinking_budget"]===void 0){return[]}delete merged["reasoning_effort"];return["reasoning_effort"]}warnConflictingKnobDrop(model,reasoningEffort,dropped){if(dropped.length===0){return}if(!this.conflictingKnobDropWarned){this.conflictingKnobDropWarned=true;debugLogger2.warn("DashScope: dropped conflicting thinking knobs",{model:this.resolveWireModel(model),reasoningEffort,dropped})}}conflictingKnobDropWarned=false;buildRequestMetadata(model,userPromptId){if(!this.shouldSendRequestMetadata(model)){return{}}return this.buildMetadata(userPromptId)||{}}shouldSendRequestMetadata(model){const configured=this.contentGeneratorConfig.enableRequestMetadata;if(typeof configured==="boolean"){return configured}return isQwenFamilyWireModel(this.resolveWireModel(model))}buildMetadata(userPromptId){const channel=this.cliConfig.getChannel?.();return{metadata:{sessionId:this.cliConfig.getSessionId?.(),promptId:userPromptId,...channel?{channel}:{}}}}getDefaultGenerationConfig(){return{}}addDashScopeCacheControl(request,cacheControl,reattachBlockCount=0){const messages=request.messages;const systemIndex=messages.findIndex(msg=>msg.role==="system");const lastIndex=messages.length-1;const stableBlock=reattachBlockCount>0&&lastIndex>=0?this.lastStableBlock(messages,reattachBlockCount):{messageIndex:lastIndex,excludeTail:0};const updatedMessages=messages.length===0?messages:messages.map((message,index)=>{const isConversationAnchor=stableBlock?.messageIndex===index&&cacheControl==="all";const shouldAddCacheControl=Boolean(index===systemIndex&&systemIndex!==-1||isConversationAnchor);if(!shouldAddCacheControl||!("content"in message)||message.content===null||message.content===void 0){return message}return{...message,content:this.addCacheControlToContent(message.content,isConversationAnchor&&stableBlock?stableBlock.excludeTail:0)}});return updatedMessages}lastStableBlock(messages,reattachBlockCount){let remaining=reattachBlockCount;for(let index=messages.length-1;index>=0;index--){const content=messages[index].content;const blockCount=typeof content==="string"?content.length>0?1:0:Array.isArray(content)?content.length:0;if(blockCount===0)continue;if(blockCount>remaining){if(remaining>0){remaining=0;continue}return{messageIndex:index,excludeTail:remaining}}remaining-=blockCount}return void 0}addCacheControlToContent(content,excludeTail=0){const contentArray=this.normalizeContentToArray(content);return this.addCacheControlToContentArray(contentArray,excludeTail)}normalizeContentToArray(content){if(typeof content==="string"){return[{type:"text",text:content}]}return[...content]}addCacheControlToContentArray(contentArray,excludeTail=0){if(contentArray.length===0){return contentArray}let targetIndex=contentArray.length-1-excludeTail;if(targetIndex<0){return contentArray}if(excludeTail>0){while(targetIndex>0&&contentArray[targetIndex].type!=="text"){targetIndex-=1}}const lastItem=contentArray[targetIndex];contentArray[targetIndex]={...lastItem,cache_control:{type:"ephemeral"}};return contentArray}isGlmModel(model){return!!model&&model.toLowerCase().startsWith("glm-")}hasFunctionCallingContext(request){if(request.tools&&request.tools.length>0){return true}return request.messages.some(message=>{if(message.role==="tool"){return true}if(message.role==="assistant"){const toolCalls=message.tool_calls;return Array.isArray(toolCalls)&&toolCalls.length>0}return false})}flattenTextContent(messages){return messages.map(message=>{if(!("content"in message)||!Array.isArray(message.content)){return message}const parts=message.content;if(parts.length===0){return message}const isTextOnly=parts.every(part=>part&&part.type==="text");if(!isTextOnly){return message}const text=parts.map(part=>part.text??"").join("\n\n");return{...message,content:text}})}static VISION_MODEL_EXACT_MATCHES=new Set(["coder-model"]);static VISION_MODEL_PREFIX_PATTERNS=["qwen-vl","qwen3-vl-plus","qwen3.5-plus","qwen3.6-plus","qwen3.7-plus"];isVisionModel(model){if(!model){return false}const normalized=model.toLowerCase();if(_DashScopeOpenAICompatibleProvider.VISION_MODEL_EXACT_MATCHES.has(normalized)){return true}for(const prefix of _DashScopeOpenAICompatibleProvider.VISION_MODEL_PREFIX_PATTERNS){if(normalized.startsWith(prefix)){return true}}return false}shouldEnableCacheControl(){const config=this.contentGeneratorConfig.isolatedRoute?this.contentGeneratorConfig:this.cliConfig.getContentGeneratorConfig();return config?.enableCacheControl!==false}};export{DefaultOpenAICompatibleProvider,selectDashScopeThinkingKnob,DASHSCOPE_REGIONAL_HOSTS,DashScopeOpenAICompatibleProvider};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{getInstallationInfo,getNpmCliPath,getNpmNodePath}from"./chunk-GOZ5FAUV.js";import{t}from"./chunk-5YULNQF3.js";import{getPackageJson}from"./chunk-6KMPLONS.js";import{isBunRuntime}from"./chunk-WGNF7FPC.js";import{require_semver}from"./chunk-73G3MZQR.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_semver=__toESM(require_semver(),1);import{execFile}from"node:child_process";import{promisify}from"node:util";init_esbuild_shims();import*as fs from"node:fs";import*as os from"node:os";import*as path from"node:path";function npmrcValue(raw){const value=raw.trim();if(value.startsWith('"')&&value.endsWith('"')){try{const parsed=JSON.parse(value);if(typeof parsed==="string")return parsed}catch{return value}}if(value.startsWith("'")&&value.endsWith("'"))return value.slice(1,-1);return value.replace(/\\([\\;#])|[;#].*$/g,(_match,escaped)=>escaped??"").trim()}__name(npmrcValue,"npmrcValue");function expandEnv(value){return value.replace(/(\\*)\$\{([^}]+)\}/g,(match,escapes,name)=>{if(escapes.length%2)return match.slice(1);return escapes+(process.env[name]??`\${${name}}`)})}__name(expandEnv,"expandEnv");function readNpmrc(filename){let content;try{content=fs.readFileSync(filename,"utf8")}catch(error){if(error.code==="ENOENT")return new Map;throw new Error("Unable to read npm registry configuration")}const config=new Map;let inSection=false;for(const line of content.split(/\r?\n/)){if(/^\s*\[/.test(line))inSection=true;if(inSection||/^\s*[;#]/.test(line))continue;const match=line.match(/^\s*([^=]+?)\s*=(.*)$/);if(!match)continue;config.set(expandEnv(npmrcValue(match[1])),expandEnv(npmrcValue(match[2])))}return config}__name(readNpmrc,"readNpmrc");function getGlobalNpmRegistryConfig(packageName){const env=new Map;for(const[key,value]of Object.entries(process.env)){if(!/^npm_config_/i.test(key)||!value)continue;const suffix=key.slice("npm_config_".length);const name=suffix.startsWith("//")?suffix:suffix.toLowerCase().replace(/(?!^)_/g,"-");env.set(expandEnv(name),expandEnv(value.trim()))}const home=os.homedir();const configPath=__name(value=>{if(/^~(?=\/|$)/.test(value)){if(!path.isAbsolute(home)){throw new Error("Cannot resolve npm configuration without an absolute home directory")}value=value.replace(/^~/,home)}return path.resolve(value)},"configPath");const builtin=readNpmrc(path.join(path.dirname(process.execPath),...process.platform==="win32"?["node_modules","npm","npmrc"]:["..","lib","node_modules","npm","npmrc"]));const userConfig=env.get("userconfig")??builtin.get("userconfig")??(path.isAbsolute(home)?path.join(home,".npmrc"):void 0);const user=userConfig?readNpmrc(configPath(userConfig)):new Map;let defaultPrefix=path.dirname(process.execPath);if(process.platform!=="win32"){defaultPrefix=path.dirname(defaultPrefix);if(process.env["DESTDIR"]){defaultPrefix=path.join(process.env["DESTDIR"],defaultPrefix)}}if(process.env["PREFIX"])defaultPrefix=process.env["PREFIX"];const prefix=env.get("prefix")??user.get("prefix")??builtin.get("prefix")??defaultPrefix;const global=readNpmrc(configPath(env.get("globalconfig")??user.get("globalconfig")??builtin.get("globalconfig")??path.join(prefix,"etc","npmrc")));const config=new Map([...builtin,...global,...user,...env]);const scope=packageName.startsWith("@")?packageName.split("/")[0]:void 0;let registry;try{registry=new URL(scope&&config.get(`${scope}:registry`)||config.get("registry")||"https://registry.npmjs.org/")}catch{throw new Error("Invalid npm registry configuration")}if(!["https:","http:"].includes(registry.protocol)||registry.username||registry.password){throw new Error("Invalid npm registry configuration")}if(!registry.pathname.endsWith("/"))registry.pathname+="/";registry.search="";registry.hash="";let authPath=registry.pathname;for(;;){const key=`//${registry.host}${authPath}:`;const token=config.get(`${key}_authToken`);const auth=config.get(`${key}_auth`);const username=config.get(`${key}username`);const password=config.get(`${key}_password`);let authorization;if(token)authorization=`Bearer ${token}`;else if(auth)authorization=`Basic ${auth}`;else if(username&&password){const decodedPassword=Buffer.from(password,"base64").toString("utf8");authorization=`Basic ${Buffer.from(`${username}:${decodedPassword}`).toString("base64")}`}if(authorization){try{new Headers({Authorization:authorization})}catch{throw new Error("Invalid npm registry authentication configuration")}return{registry,authorization}}if(authPath==="")break;authPath=authPath.replace(/([^/]+|\/)$/,"")}return{registry}}__name(getGlobalNpmRegistryConfig,"getGlobalNpmRegistryConfig");var debugLogger=createDebugLogger("UPDATE_CHECK");var FETCH_TIMEOUT_MS=5e3;var UpdateCheckTimeoutError=class extends Error{static{__name(this,"UpdateCheckTimeoutError")}distTag;constructor(timeoutMs,distTag){const suffix=distTag?` for ${distTag}`:"";super(`update check timed out after ${timeoutMs}ms${suffix}`);this.name="UpdateCheckTimeoutError";this.distTag=distTag}};var NETWORK_ERROR_CODES=["ENOTFOUND","ECONNREFUSED","EAI_AGAIN","ETIMEDOUT","ENETUNREACH"];function classifyUpdateCheckError(error){if(error instanceof UpdateCheckTimeoutError)return"timeout";if(error instanceof Error){if(error.name==="TimeoutError")return"timeout";if("killed"in error&&error.killed===true&&"signal"in error&&error.signal==="SIGTERM"){return"timeout"}const errors=[error];if(error.cause instanceof Error)errors.push(error.cause);const matchesCode=__name(code=>errors.some(error2=>error2.code===code||error2.message.includes(code)),"matchesCode");if(NETWORK_ERROR_CODES.some(matchesCode))return"offline"}return"registry"}__name(classifyUpdateCheckError,"classifyUpdateCheckError");function describeUpdateCheckFailure(error,timeoutMs=FETCH_TIMEOUT_MS){switch(classifyUpdateCheckError(error)){case"timeout":return t("registry did not respond within {{seconds}}s",{seconds:String(Math.round(timeoutMs/1e3))});case"offline":return t("registry unreachable");default:return t("registry error")}}__name(describeUpdateCheckFailure,"describeUpdateCheckFailure");async function fetchInfoWithTimeout(notifier,timeoutMs,distTag){let timer;try{return await Promise.race([Promise.resolve(notifier.fetchInfo()),new Promise((_,reject)=>{timer=setTimeout(()=>reject(new UpdateCheckTimeoutError(timeoutMs,distTag)),timeoutMs)})])}finally{if(timer!==void 0)clearTimeout(timer)}}__name(fetchInfoWithTimeout,"fetchInfoWithTimeout");var execFileAsync=promisify(execFile);async function runGlobalNpm(args,run=execFileAsync,platform=process.platform,nodePath=getNpmNodePath(),resolveNpmCliPath=getNpmCliPath){const{stdout}=await run(nodePath,[resolveNpmCliPath(nodePath,platform),...args],{encoding:"utf8",timeout:FETCH_TIMEOUT_MS});return String(stdout).trim()}__name(runGlobalNpm,"runGlobalNpm");async function fetchGlobalNpmUpdateInfo(packageName,currentVersion,distTag,run=execFileAsync){if(isBunRuntime()&&getInstallationInfo("",false).isStandalone){const{registry,authorization}=getGlobalNpmRegistryConfig(packageName);let url=new URL(`-/package/${encodeURIComponent(packageName)}/dist-tags`,registry);const signal=AbortSignal.timeout(FETCH_TIMEOUT_MS);let auth=authorization;let response;for(let redirects=0;;redirects++){response=await fetch(url,{signal,headers:auth?{Authorization:auth}:void 0,redirect:"manual"});if(![301,302,303,307,308].includes(response.status))break;const location=response.headers.get("location");await response.body?.cancel();if(!location||redirects===5){throw new Error("Invalid npm registry redirect")}let next;try{next=new URL(location,url)}catch{throw new Error("Invalid npm registry redirect")}if(!["https:","http:"].includes(next.protocol)||next.username||next.password){throw new Error("Invalid npm registry redirect")}if(next.origin!==url.origin)auth=void 0;url=next}if(!response.ok)throw new Error(`Registry returned HTTP ${response.status}`);const tags=await response.json();if(typeof tags!=="object"||tags===null||Array.isArray(tags)){throw new Error("Invalid registry dist-tags response")}const latest2=Reflect.get(tags,distTag);if(latest2!==void 0&&typeof latest2!=="string"){throw new Error(`Invalid registry ${distTag} version response`)}return{latest:latest2??currentVersion,current:currentVersion,type:"latest",name:packageName}}const output=await runGlobalNpm(["view",packageName,`dist-tags.${distTag}`,"--json","--global"],run);if(output===""){return{latest:currentVersion,current:currentVersion,type:"latest",name:packageName}}const parsed=JSON.parse(output);const latest=typeof parsed==="string"?parsed:Array.isArray(parsed)&&parsed.length===1&&typeof parsed[0]==="string"?parsed[0]:void 0;if(latest===void 0){throw new Error(`Invalid npm ${distTag} version response`)}return{latest,current:currentVersion,type:"latest",name:packageName}}__name(fetchGlobalNpmUpdateInfo,"fetchGlobalNpmUpdateInfo");function getBestAvailableUpdate(nightly,stable){if(!nightly)return stable||null;if(!stable)return nightly||null;const nightlyVer=nightly.latest;const stableVer=stable.latest;if(import_semver.default.coerce(stableVer)?.version===import_semver.default.coerce(nightlyVer)?.version){return nightly}return import_semver.default.gt(stableVer,nightlyVer)?stable:nightly}__name(getBestAvailableUpdate,"getBestAvailableUpdate");async function checkForUpdatesDetailed(fetchGlobalNpm=fetchGlobalNpmUpdateInfo){let currentVersion;try{if(process.env["DEV"]==="true"){return{status:"skipped",reason:"development mode"}}const packageJson=await getPackageJson();if(!packageJson||!packageJson.name||!packageJson.version){return{status:"skipped",reason:"package metadata unavailable"}}const{name,version}=packageJson;currentVersion=version;const isNightly=version.includes("nightly");const createNotifier=__name(distTag=>({fetchInfo:__name(()=>fetchGlobalNpm(name,version,distTag),"fetchInfo")}),"createNotifier");if(isNightly){const[nightlyUpdateInfo,latestUpdateInfo]=await Promise.all([fetchInfoWithTimeout(createNotifier("nightly"),FETCH_TIMEOUT_MS,"nightly"),fetchInfoWithTimeout(createNotifier("latest"),FETCH_TIMEOUT_MS,"latest")]);debugLogger.debug(`fetchInfo returned nightly=${JSON.stringify(nightlyUpdateInfo)} latest=${JSON.stringify(latestUpdateInfo)} for current=${version}`);const bestUpdate=getBestAvailableUpdate(nightlyUpdateInfo,latestUpdateInfo);if(bestUpdate&&import_semver.default.gt(bestUpdate.latest,version)){return{status:"update",info:{message:t("A new version of MiraOS is available! {{current}} \u2192 {{latest}}",{current:version,latest:bestUpdate.latest}),update:{...bestUpdate,current:version}}}}}else{const updateInfo=await fetchInfoWithTimeout(createNotifier("latest"),FETCH_TIMEOUT_MS,"latest");debugLogger.debug(`fetchInfo returned ${JSON.stringify(updateInfo)} for current=${version}`);if(updateInfo&&import_semver.default.gt(updateInfo.latest,version)){return{status:"update",info:{message:t("Qwen Code update available! {{current}} \u2192 {{latest}}",{current:version,latest:updateInfo.latest}),update:{...updateInfo,current:version}}}}}return{status:"up-to-date",currentVersion:version}}catch(e){const error=e instanceof Error?e:new Error(String(e));debugLogger.warn("Failed to check for updates: "+error);return{status:"error",error,currentVersion}}}__name(checkForUpdatesDetailed,"checkForUpdatesDetailed");async function checkForUpdates(fetchGlobalNpm=fetchGlobalNpmUpdateInfo){const result=await checkForUpdatesDetailed(fetchGlobalNpm);return result.status==="update"?result.info:null}__name(checkForUpdates,"checkForUpdates");export{FETCH_TIMEOUT_MS,UpdateCheckTimeoutError,classifyUpdateCheckError,describeUpdateCheckFailure,runGlobalNpm,fetchGlobalNpmUpdateInfo,checkForUpdatesDetailed,checkForUpdates};
|
|
3
|
+
import{getInstallationInfo,getNpmCliPath,getNpmNodePath}from"./chunk-GOZ5FAUV.js";import{t}from"./chunk-AUM57JI2.js";import{getPackageJson}from"./chunk-6KMPLONS.js";import{isBunRuntime}from"./chunk-WGNF7FPC.js";import{require_semver}from"./chunk-73G3MZQR.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_semver=__toESM(require_semver(),1);import{execFile}from"node:child_process";import{promisify}from"node:util";init_esbuild_shims();import*as fs from"node:fs";import*as os from"node:os";import*as path from"node:path";function npmrcValue(raw){const value=raw.trim();if(value.startsWith('"')&&value.endsWith('"')){try{const parsed=JSON.parse(value);if(typeof parsed==="string")return parsed}catch{return value}}if(value.startsWith("'")&&value.endsWith("'"))return value.slice(1,-1);return value.replace(/\\([\\;#])|[;#].*$/g,(_match,escaped)=>escaped??"").trim()}__name(npmrcValue,"npmrcValue");function expandEnv(value){return value.replace(/(\\*)\$\{([^}]+)\}/g,(match,escapes,name)=>{if(escapes.length%2)return match.slice(1);return escapes+(process.env[name]??`\${${name}}`)})}__name(expandEnv,"expandEnv");function readNpmrc(filename){let content;try{content=fs.readFileSync(filename,"utf8")}catch(error){if(error.code==="ENOENT")return new Map;throw new Error("Unable to read npm registry configuration")}const config=new Map;let inSection=false;for(const line of content.split(/\r?\n/)){if(/^\s*\[/.test(line))inSection=true;if(inSection||/^\s*[;#]/.test(line))continue;const match=line.match(/^\s*([^=]+?)\s*=(.*)$/);if(!match)continue;config.set(expandEnv(npmrcValue(match[1])),expandEnv(npmrcValue(match[2])))}return config}__name(readNpmrc,"readNpmrc");function getGlobalNpmRegistryConfig(packageName){const env=new Map;for(const[key,value]of Object.entries(process.env)){if(!/^npm_config_/i.test(key)||!value)continue;const suffix=key.slice("npm_config_".length);const name=suffix.startsWith("//")?suffix:suffix.toLowerCase().replace(/(?!^)_/g,"-");env.set(expandEnv(name),expandEnv(value.trim()))}const home=os.homedir();const configPath=__name(value=>{if(/^~(?=\/|$)/.test(value)){if(!path.isAbsolute(home)){throw new Error("Cannot resolve npm configuration without an absolute home directory")}value=value.replace(/^~/,home)}return path.resolve(value)},"configPath");const builtin=readNpmrc(path.join(path.dirname(process.execPath),...process.platform==="win32"?["node_modules","npm","npmrc"]:["..","lib","node_modules","npm","npmrc"]));const userConfig=env.get("userconfig")??builtin.get("userconfig")??(path.isAbsolute(home)?path.join(home,".npmrc"):void 0);const user=userConfig?readNpmrc(configPath(userConfig)):new Map;let defaultPrefix=path.dirname(process.execPath);if(process.platform!=="win32"){defaultPrefix=path.dirname(defaultPrefix);if(process.env["DESTDIR"]){defaultPrefix=path.join(process.env["DESTDIR"],defaultPrefix)}}if(process.env["PREFIX"])defaultPrefix=process.env["PREFIX"];const prefix=env.get("prefix")??user.get("prefix")??builtin.get("prefix")??defaultPrefix;const global=readNpmrc(configPath(env.get("globalconfig")??user.get("globalconfig")??builtin.get("globalconfig")??path.join(prefix,"etc","npmrc")));const config=new Map([...builtin,...global,...user,...env]);const scope=packageName.startsWith("@")?packageName.split("/")[0]:void 0;let registry;try{registry=new URL(scope&&config.get(`${scope}:registry`)||config.get("registry")||"https://registry.npmjs.org/")}catch{throw new Error("Invalid npm registry configuration")}if(!["https:","http:"].includes(registry.protocol)||registry.username||registry.password){throw new Error("Invalid npm registry configuration")}if(!registry.pathname.endsWith("/"))registry.pathname+="/";registry.search="";registry.hash="";let authPath=registry.pathname;for(;;){const key=`//${registry.host}${authPath}:`;const token=config.get(`${key}_authToken`);const auth=config.get(`${key}_auth`);const username=config.get(`${key}username`);const password=config.get(`${key}_password`);let authorization;if(token)authorization=`Bearer ${token}`;else if(auth)authorization=`Basic ${auth}`;else if(username&&password){const decodedPassword=Buffer.from(password,"base64").toString("utf8");authorization=`Basic ${Buffer.from(`${username}:${decodedPassword}`).toString("base64")}`}if(authorization){try{new Headers({Authorization:authorization})}catch{throw new Error("Invalid npm registry authentication configuration")}return{registry,authorization}}if(authPath==="")break;authPath=authPath.replace(/([^/]+|\/)$/,"")}return{registry}}__name(getGlobalNpmRegistryConfig,"getGlobalNpmRegistryConfig");var debugLogger=createDebugLogger("UPDATE_CHECK");var FETCH_TIMEOUT_MS=5e3;var UpdateCheckTimeoutError=class extends Error{static{__name(this,"UpdateCheckTimeoutError")}distTag;constructor(timeoutMs,distTag){const suffix=distTag?` for ${distTag}`:"";super(`update check timed out after ${timeoutMs}ms${suffix}`);this.name="UpdateCheckTimeoutError";this.distTag=distTag}};var NETWORK_ERROR_CODES=["ENOTFOUND","ECONNREFUSED","EAI_AGAIN","ETIMEDOUT","ENETUNREACH"];function classifyUpdateCheckError(error){if(error instanceof UpdateCheckTimeoutError)return"timeout";if(error instanceof Error){if(error.name==="TimeoutError")return"timeout";if("killed"in error&&error.killed===true&&"signal"in error&&error.signal==="SIGTERM"){return"timeout"}const errors=[error];if(error.cause instanceof Error)errors.push(error.cause);const matchesCode=__name(code=>errors.some(error2=>error2.code===code||error2.message.includes(code)),"matchesCode");if(NETWORK_ERROR_CODES.some(matchesCode))return"offline"}return"registry"}__name(classifyUpdateCheckError,"classifyUpdateCheckError");function describeUpdateCheckFailure(error,timeoutMs=FETCH_TIMEOUT_MS){switch(classifyUpdateCheckError(error)){case"timeout":return t("registry did not respond within {{seconds}}s",{seconds:String(Math.round(timeoutMs/1e3))});case"offline":return t("registry unreachable");default:return t("registry error")}}__name(describeUpdateCheckFailure,"describeUpdateCheckFailure");async function fetchInfoWithTimeout(notifier,timeoutMs,distTag){let timer;try{return await Promise.race([Promise.resolve(notifier.fetchInfo()),new Promise((_,reject)=>{timer=setTimeout(()=>reject(new UpdateCheckTimeoutError(timeoutMs,distTag)),timeoutMs)})])}finally{if(timer!==void 0)clearTimeout(timer)}}__name(fetchInfoWithTimeout,"fetchInfoWithTimeout");var execFileAsync=promisify(execFile);async function runGlobalNpm(args,run=execFileAsync,platform=process.platform,nodePath=getNpmNodePath(),resolveNpmCliPath=getNpmCliPath){const{stdout}=await run(nodePath,[resolveNpmCliPath(nodePath,platform),...args],{encoding:"utf8",timeout:FETCH_TIMEOUT_MS});return String(stdout).trim()}__name(runGlobalNpm,"runGlobalNpm");async function fetchGlobalNpmUpdateInfo(packageName,currentVersion,distTag,run=execFileAsync){if(isBunRuntime()&&getInstallationInfo("",false).isStandalone){const{registry,authorization}=getGlobalNpmRegistryConfig(packageName);let url=new URL(`-/package/${encodeURIComponent(packageName)}/dist-tags`,registry);const signal=AbortSignal.timeout(FETCH_TIMEOUT_MS);let auth=authorization;let response;for(let redirects=0;;redirects++){response=await fetch(url,{signal,headers:auth?{Authorization:auth}:void 0,redirect:"manual"});if(![301,302,303,307,308].includes(response.status))break;const location=response.headers.get("location");await response.body?.cancel();if(!location||redirects===5){throw new Error("Invalid npm registry redirect")}let next;try{next=new URL(location,url)}catch{throw new Error("Invalid npm registry redirect")}if(!["https:","http:"].includes(next.protocol)||next.username||next.password){throw new Error("Invalid npm registry redirect")}if(next.origin!==url.origin)auth=void 0;url=next}if(!response.ok)throw new Error(`Registry returned HTTP ${response.status}`);const tags=await response.json();if(typeof tags!=="object"||tags===null||Array.isArray(tags)){throw new Error("Invalid registry dist-tags response")}const latest2=Reflect.get(tags,distTag);if(latest2!==void 0&&typeof latest2!=="string"){throw new Error(`Invalid registry ${distTag} version response`)}return{latest:latest2??currentVersion,current:currentVersion,type:"latest",name:packageName}}const output=await runGlobalNpm(["view",packageName,`dist-tags.${distTag}`,"--json","--global"],run);if(output===""){return{latest:currentVersion,current:currentVersion,type:"latest",name:packageName}}const parsed=JSON.parse(output);const latest=typeof parsed==="string"?parsed:Array.isArray(parsed)&&parsed.length===1&&typeof parsed[0]==="string"?parsed[0]:void 0;if(latest===void 0){throw new Error(`Invalid npm ${distTag} version response`)}return{latest,current:currentVersion,type:"latest",name:packageName}}__name(fetchGlobalNpmUpdateInfo,"fetchGlobalNpmUpdateInfo");function getBestAvailableUpdate(nightly,stable){if(!nightly)return stable||null;if(!stable)return nightly||null;const nightlyVer=nightly.latest;const stableVer=stable.latest;if(import_semver.default.coerce(stableVer)?.version===import_semver.default.coerce(nightlyVer)?.version){return nightly}return import_semver.default.gt(stableVer,nightlyVer)?stable:nightly}__name(getBestAvailableUpdate,"getBestAvailableUpdate");async function checkForUpdatesDetailed(fetchGlobalNpm=fetchGlobalNpmUpdateInfo){let currentVersion;try{if(process.env["DEV"]==="true"){return{status:"skipped",reason:"development mode"}}const packageJson=await getPackageJson();if(!packageJson||!packageJson.name||!packageJson.version){return{status:"skipped",reason:"package metadata unavailable"}}const{name,version}=packageJson;currentVersion=version;const isNightly=version.includes("nightly");const createNotifier=__name(distTag=>({fetchInfo:__name(()=>fetchGlobalNpm(name,version,distTag),"fetchInfo")}),"createNotifier");if(isNightly){const[nightlyUpdateInfo,latestUpdateInfo]=await Promise.all([fetchInfoWithTimeout(createNotifier("nightly"),FETCH_TIMEOUT_MS,"nightly"),fetchInfoWithTimeout(createNotifier("latest"),FETCH_TIMEOUT_MS,"latest")]);debugLogger.debug(`fetchInfo returned nightly=${JSON.stringify(nightlyUpdateInfo)} latest=${JSON.stringify(latestUpdateInfo)} for current=${version}`);const bestUpdate=getBestAvailableUpdate(nightlyUpdateInfo,latestUpdateInfo);if(bestUpdate&&import_semver.default.gt(bestUpdate.latest,version)){return{status:"update",info:{message:t("A new version of MiraOS is available! {{current}} \u2192 {{latest}}",{current:version,latest:bestUpdate.latest}),update:{...bestUpdate,current:version}}}}}else{const updateInfo=await fetchInfoWithTimeout(createNotifier("latest"),FETCH_TIMEOUT_MS,"latest");debugLogger.debug(`fetchInfo returned ${JSON.stringify(updateInfo)} for current=${version}`);if(updateInfo&&import_semver.default.gt(updateInfo.latest,version)){return{status:"update",info:{message:t("Qwen Code update available! {{current}} \u2192 {{latest}}",{current:version,latest:updateInfo.latest}),update:{...updateInfo,current:version}}}}}return{status:"up-to-date",currentVersion:version}}catch(e){const error=e instanceof Error?e:new Error(String(e));debugLogger.warn("Failed to check for updates: "+error);return{status:"error",error,currentVersion}}}__name(checkForUpdatesDetailed,"checkForUpdatesDetailed");async function checkForUpdates(fetchGlobalNpm=fetchGlobalNpmUpdateInfo){const result=await checkForUpdatesDetailed(fetchGlobalNpm);return result.status==="update"?result.info:null}__name(checkForUpdates,"checkForUpdates");export{FETCH_TIMEOUT_MS,UpdateCheckTimeoutError,classifyUpdateCheckError,describeUpdateCheckFailure,runGlobalNpm,fetchGlobalNpmUpdateInfo,checkForUpdatesDetailed,checkForUpdates};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2026 Alibaba Inc.
|