gerege-cli 0.26.5 → 0.26.7
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/README.md +8 -8
- package/chunks/{MaxSizedBox-VMVLMS4X.js → MaxSizedBox-LSNOJEKM.js} +1 -1
- package/chunks/{StandaloneSessionPicker-UNORCVYY.js → StandaloneSessionPicker-KSYGPMEV.js} +1 -1
- package/chunks/{acp-subagent-executor-623ZUTJT.js → acp-subagent-executor-NSW2MFUI.js} +1 -1
- package/chunks/{acpAgent-MTTDTK2C.js → acpAgent-3DTOHTDM.js} +3 -3
- package/chunks/{advisor-ANUGICJ5.js → advisor-7JGQPS7X.js} +1 -1
- package/chunks/{agent-GNCQDICJ.js → agent-PNKQJGDO.js} +1 -1
- package/chunks/{agent-headless-OPUXAXQM.js → agent-headless-7D33X7QQ.js} +1 -1
- package/chunks/{agent-host-client-K6GRPTFD.js → agent-host-client-3R2MAUVE.js} +1 -1
- package/chunks/{agent-host-connections-MF3YBZU2.js → agent-host-connections-2D7DECAE.js} +1 -1
- package/chunks/{anthropicContentGenerator-OK4PFE5Y.js → anthropicContentGenerator-MGTJJGEQ.js} +1 -1
- package/chunks/{autofix-pr-MABTGEHZ.js → autofix-pr-OIHHZSPQ.js} +1 -1
- package/chunks/{batch-V2NJT3M5.js → batch-6UDAMPAA.js} +1 -1
- package/chunks/{bridge-BJQ627CX.js → bridge-QXVXPNJ6.js} +1 -1
- package/chunks/{channel-settings-store-4JMCI4UR.js → channel-settings-store-P4W4R5SJ.js} +1 -1
- package/chunks/{chunk-ZN57TOVA.js → chunk-2DU2WMTL.js} +1 -1
- package/chunks/{chunk-ISGF3BVD.js → chunk-2J2BQ3PL.js} +2 -2
- package/chunks/{chunk-TQTIEK2W.js → chunk-2LMSDH6P.js} +1 -1
- package/chunks/{chunk-EIILQ6KT.js → chunk-3EZ5GCUT.js} +1 -1
- package/chunks/{chunk-UY2ET2AL.js → chunk-3ICJI5KW.js} +1 -1
- package/chunks/{chunk-VDRE7U3P.js → chunk-4A663FE6.js} +5 -5
- package/chunks/{chunk-2IGE2K5V.js → chunk-4AKTP4MM.js} +1 -1
- package/chunks/{chunk-NO26JN24.js → chunk-4LC4INFI.js} +1 -1
- package/chunks/{chunk-CKZRJP4F.js → chunk-4ME3BUJK.js} +1 -1
- package/chunks/{chunk-3XBJYUWP.js → chunk-4QOVM2LL.js} +1 -1
- package/chunks/{chunk-ZYTG6R7S.js → chunk-4VR4DUUD.js} +1 -1
- package/chunks/{chunk-DE53B2R7.js → chunk-4W27Z3OL.js} +1 -1
- package/chunks/{chunk-QOYRDEXR.js → chunk-53IB4U4E.js} +1 -1
- package/chunks/{chunk-CCOUFBOY.js → chunk-5R2JIZID.js} +1 -1
- package/chunks/{chunk-MPAR4JBP.js → chunk-5TWAP4OG.js} +1 -1
- package/chunks/{chunk-3NQESE5K.js → chunk-6JAXAFX7.js} +1 -1
- package/chunks/{chunk-POA4NX4N.js → chunk-6WV5RKYB.js} +1 -1
- package/chunks/{chunk-KN27BFXM.js → chunk-6YFNUVJR.js} +1 -1
- package/chunks/{chunk-2X3UF2CF.js → chunk-7HFFTOAD.js} +1 -1
- package/chunks/{chunk-KDYUZBZC.js → chunk-ATTJQLQV.js} +1 -1
- package/chunks/{chunk-USJFJZ23.js → chunk-BGELKSQ4.js} +1 -1
- package/chunks/{chunk-X4BFEDWU.js → chunk-BIPPD7W6.js} +1 -1
- package/chunks/{chunk-DEMXCA3K.js → chunk-BVV7UXES.js} +1 -1
- package/chunks/{chunk-2VCDJ6UF.js → chunk-BY46PCWY.js} +1 -1
- package/chunks/{chunk-CXGGC4NO.js → chunk-CDKBM72V.js} +1 -1
- package/chunks/{chunk-5WLKN3GD.js → chunk-CK3OKTTL.js} +1 -1
- package/chunks/{chunk-FHBGTZ4K.js → chunk-DEJ47KJE.js} +1 -1
- package/chunks/{chunk-DTTC4ZKY.js → chunk-DQQN2HOP.js} +1 -1
- package/chunks/{chunk-PN62SUYK.js → chunk-DTX2OVQW.js} +1 -1
- package/chunks/{chunk-IBYFSHBB.js → chunk-DVUKYOCJ.js} +1 -1
- package/chunks/{chunk-Q5E5SOY2.js → chunk-E3KWSRJN.js} +1 -1
- package/chunks/{chunk-IDUGQMTP.js → chunk-EEPNACXJ.js} +1 -1
- package/chunks/{chunk-E5YRAQXM.js → chunk-EKRUF347.js} +1 -1
- package/chunks/{chunk-HSYBIGMS.js → chunk-F5SLLEJY.js} +1 -1
- package/chunks/{chunk-5ZQWQ3RK.js → chunk-F7622ZRQ.js} +1 -1
- package/chunks/{chunk-KKBOCRPF.js → chunk-FKUDVIME.js} +1 -1
- package/chunks/{chunk-62NLMVVT.js → chunk-FRVXSKL4.js} +1 -1
- package/chunks/{chunk-FIM7MM25.js → chunk-FTF2NFLB.js} +1 -1
- package/chunks/{chunk-OHXQYU6S.js → chunk-G4MWPXNY.js} +1 -1
- package/chunks/{chunk-SELRSZFK.js → chunk-GA35LMSX.js} +1 -1
- package/chunks/{chunk-SMYBY353.js → chunk-H34KVVI4.js} +1 -1
- package/chunks/{chunk-NGOIJH7K.js → chunk-H5EXNXGW.js} +1 -1
- package/chunks/{chunk-UBXLQ6TP.js → chunk-HJLRKM3W.js} +1 -1
- package/chunks/{chunk-CAPG7UVH.js → chunk-HVP4UF2Q.js} +1 -1
- package/chunks/{chunk-H57IX45A.js → chunk-HXTYFGSQ.js} +1 -1
- package/chunks/{chunk-55RVKT4O.js → chunk-IIHUDJX7.js} +1 -1
- package/chunks/{chunk-XFLLE2J3.js → chunk-IQMKQKKD.js} +2 -2
- package/chunks/{chunk-SQQORHMS.js → chunk-ISQMHOCC.js} +1 -1
- package/chunks/{chunk-YLAI26PX.js → chunk-IY7M5HKF.js} +1 -1
- package/chunks/{chunk-FDUXQAGW.js → chunk-IZXHCHJD.js} +1 -1
- package/chunks/{chunk-ZOBX6C7E.js → chunk-JHC22BZH.js} +1 -1
- package/chunks/{chunk-26ISBUM7.js → chunk-K7GN4CMV.js} +6 -6
- package/chunks/{chunk-4GC5HJZO.js → chunk-L7LO3YRT.js} +1 -1
- package/chunks/{chunk-ZSVSRF4C.js → chunk-LT3J74BZ.js} +1 -1
- package/chunks/{chunk-2PY7R7GG.js → chunk-LY4XTBL4.js} +1 -1
- package/chunks/{chunk-7IERHQ63.js → chunk-LYFRGP42.js} +1 -1
- package/chunks/{chunk-FPZPCZFS.js → chunk-MDCA4I63.js} +1 -1
- package/chunks/{chunk-2LLPGSUK.js → chunk-MS2XCBPP.js} +1 -1
- package/chunks/{chunk-3Y6LSWEW.js → chunk-MXZXQUVP.js} +1 -1
- package/chunks/{chunk-IH2PFVWO.js → chunk-N4ZQC5HB.js} +1 -1
- package/chunks/{chunk-MTW3A3KT.js → chunk-N6EFYQ7M.js} +1 -1
- package/chunks/{chunk-AQWHCRKY.js → chunk-NHPKD7LY.js} +1 -1
- package/chunks/{chunk-ABJGFEES.js → chunk-NO7VTKRL.js} +1 -1
- package/chunks/{chunk-CNFA5UUM.js → chunk-NPAENNRO.js} +1 -1
- package/chunks/{chunk-IA4K4PGK.js → chunk-NYBYDW6R.js} +1 -1
- package/chunks/{chunk-FNB3DPQZ.js → chunk-O3TUZQP4.js} +1 -1
- package/chunks/{chunk-RVJJFDF3.js → chunk-OZFZBGZG.js} +1 -1
- package/chunks/{chunk-B6D3KTUK.js → chunk-P2MZZMCS.js} +1 -1
- package/chunks/{chunk-GSOBASYW.js → chunk-PMBI46K4.js} +1 -1
- package/chunks/{chunk-WI4UMN3Q.js → chunk-Q5RRVBTY.js} +1 -1
- package/chunks/{chunk-5UZT4SXG.js → chunk-QHYSRPQR.js} +1 -1
- package/chunks/{chunk-2NOMOJWE.js → chunk-QONPET6Y.js} +2 -2
- package/chunks/{chunk-MOPJNP5I.js → chunk-QSPXKBUX.js} +1 -1
- package/chunks/{chunk-C56YJIEI.js → chunk-QTKPC24L.js} +1 -1
- package/chunks/{chunk-6X73W4TL.js → chunk-QTVSPQZQ.js} +1 -1
- package/chunks/{chunk-ADZI3OFT.js → chunk-QVHDM6N7.js} +1 -1
- package/chunks/{chunk-NVSKOSFG.js → chunk-RT6J7PV4.js} +1 -1
- package/chunks/{chunk-7MTBINFX.js → chunk-RULGA7WE.js} +2 -2
- package/chunks/{chunk-AMTFJVDD.js → chunk-SAVYMUU3.js} +1 -1
- package/chunks/{chunk-Z5XENA4A.js → chunk-T3CQ72HC.js} +8 -7
- package/chunks/{chunk-OPYGNTZP.js → chunk-U5YOAOU3.js} +1 -1
- package/chunks/{chunk-HFV6CQWE.js → chunk-ULLW2AYD.js} +1 -1
- package/chunks/{chunk-KGJ47CI5.js → chunk-UM5KBBYP.js} +1 -1
- package/chunks/{chunk-F26LTWDZ.js → chunk-UVMLWDRU.js} +1 -1
- package/chunks/{chunk-BRPJ5EHA.js → chunk-VK7LOUOJ.js} +1 -1
- package/chunks/{chunk-4EQWJTJR.js → chunk-VUNHJ74J.js} +1 -1
- package/chunks/{chunk-WB34KMOT.js → chunk-W2CV36HT.js} +1 -1
- package/chunks/{chunk-ADTFKUH2.js → chunk-WCI33URB.js} +1 -1
- package/chunks/{chunk-4TYTJQWR.js → chunk-WEPC42YR.js} +1 -1
- package/chunks/{chunk-YGHM5CDT.js → chunk-WF7Q3ZSQ.js} +1 -1
- package/chunks/{chunk-UJYOILZR.js → chunk-WK666FGZ.js} +3 -3
- package/chunks/{chunk-3WQPUP5U.js → chunk-WMLYHZZX.js} +1 -1
- package/chunks/{chunk-OCBJCZC2.js → chunk-WSI4G7XC.js} +1 -1
- package/chunks/{chunk-Q6QS5JTK.js → chunk-WXK7Z45R.js} +1 -1
- package/chunks/{chunk-6NI33TVK.js → chunk-X2TY7VTY.js} +1 -1
- package/chunks/{chunk-BBOJUFMW.js → chunk-YWK3E4WJ.js} +1 -1
- package/chunks/{chunk-FNXO5KWB.js → chunk-YY4GWNTU.js} +2 -2
- package/chunks/{chunk-FLJLUMQF.js → chunk-ZFOEVHWG.js} +1 -1
- package/chunks/{codex-subagent-executor-EK3A2WBH.js → codex-subagent-executor-GPTKVP7H.js} +1 -1
- package/chunks/{config-utils-DLOK7OLM.js → config-utils-6B5FHBSF.js} +1 -1
- package/chunks/{contextCommand-AVCUCHQC.js → contextCommand-FGRDE3GA.js} +1 -1
- package/chunks/{core-runtime-QSS4ZTG6.js → core-runtime-OFEHSKDB.js} +1 -1
- package/chunks/{create-sub-session-PNF7QDKC.js → create-sub-session-D2KEWVHQ.js} +1 -1
- package/chunks/{cron-create-C6JOFIU4.js → cron-create-RFGGKTL7.js} +1 -1
- package/chunks/{daemon-git-worktree-guard-5XZAZ7D2.js → daemon-git-worktree-guard-AV752IOZ.js} +1 -1
- package/chunks/{daemon-status-provider-MRNELSNJ.js → daemon-status-provider-GHQBRDMC.js} +1 -1
- package/chunks/{daemon-trust-policy-26CMW3WY.js → daemon-trust-policy-24ENJNTQ.js} +1 -1
- package/chunks/{daemon-trust-policy-monitor-3DWO6NQY.js → daemon-trust-policy-monitor-NMSQAGWV.js} +1 -1
- package/chunks/{deferred-core-runtime-DEC3N46T.js → deferred-core-runtime-5BAMFFOI.js} +1 -1
- package/chunks/{edit-3HMQPCHN.js → edit-XCECLEH3.js} +1 -1
- package/chunks/{enterPlanMode-QHJF4JXZ.js → enterPlanMode-SEN2PMRM.js} +1 -1
- package/chunks/{environment-NGIBJWOT.js → environment-CCPQJYKS.js} +1 -1
- package/chunks/{errors-MSTGCVGJ.js → errors-Y6HHUTGK.js} +1 -1
- package/chunks/{execution-tool-VR4TGOI4.js → execution-tool-HADWGMIG.js} +1 -1
- package/chunks/{execution-worker-EJH7HIE2.js → execution-worker-GZS7WOQL.js} +1 -1
- package/chunks/{exitPlanMode-P25OHQJ6.js → exitPlanMode-76B5HDLT.js} +1 -1
- package/chunks/{fast-path-II433ZDP.js → fast-path-OEV7LQYV.js} +1 -1
- package/chunks/{glob-4Q6DCT3F.js → glob-NLWCQRMS.js} +1 -1
- package/chunks/{goal-tools-FFMAJW6V.js → goal-tools-43XV33BT.js} +1 -1
- package/chunks/{handleAutoUpdate-QNM26NZK.js → handleAutoUpdate-JDQWGSSP.js} +1 -1
- package/chunks/{i18n-L5URVOBB.js → i18n-JW6BVEGF.js} +1 -1
- package/chunks/{initializer-NQ2NECYP.js → initializer-UT6JLZ3O.js} +1 -1
- package/chunks/{installationInfo-BCTXASUM.js → installationInfo-LKWDV3S2.js} +1 -1
- package/chunks/{interactive-mod-session-PPTBI37E.js → interactive-mod-session-2KWKYVPC.js} +1 -1
- package/chunks/{list-7TE5TUZJ.js → list-BKINK3S2.js} +1 -1
- package/chunks/{llm-BWWKUBBZ.js → llm-3RWXAVM2.js} +4 -4
- package/chunks/{llm-content-generator-QOTGPBYC.js → llm-content-generator-MDRBSH73.js} +1 -1
- package/chunks/{loadedSettingsAdapter-THAGI5M2.js → loadedSettingsAdapter-WWJUKWUN.js} +1 -1
- package/chunks/{local-7BTAGV4J.js → local-TT4FLCTR.js} +1 -1
- package/chunks/{local-execution-environment-S3OR4KSC.js → local-execution-environment-OBA6VWYL.js} +1 -1
- package/chunks/{loggingContentGenerator-AXJ5E5RS.js → loggingContentGenerator-CK7IKYQH.js} +1 -1
- package/chunks/{loop-wakeup-AJTLMLRX.js → loop-wakeup-4MSRX3DY.js} +1 -1
- package/chunks/{manage-memory-JHTUVMDJ.js → manage-memory-PX5PZJKZ.js} +1 -1
- package/chunks/{managed-execution-engine-U6GNJ4U4.js → managed-execution-engine-WMAUR3ZK.js} +1 -1
- package/chunks/{managed-local-serve-P4ZXVRBU.js → managed-local-serve-X7REHGB4.js} +1 -1
- package/chunks/{managed-npm-update-UDUILNR5.js → managed-npm-update-6HUVAJH7.js} +1 -1
- package/chunks/{managed-runtime-attestation-worker-P34ZBNRG.js → managed-runtime-attestation-worker-F4AT53M5.js} +1 -1
- package/chunks/{managed-runtime-bootstrap-CLMYNPH5.js → managed-runtime-bootstrap-3BP5JRJX.js} +1 -1
- package/chunks/{managed-runtime-session-worker-7H7AZJBV.js → managed-runtime-session-worker-2PO7J5UK.js} +1 -1
- package/chunks/{managed-runtime-ssh-worker-5KEMC7FD.js → managed-runtime-ssh-worker-4N7EMRSV.js} +1 -1
- package/chunks/{managed-session-authority-CFUZ45HT.js → managed-session-authority-MYOYTUM2.js} +1 -1
- package/chunks/{mcp-YMG4RVMC.js → mcp-5OTEMZ7P.js} +1 -1
- package/chunks/{memory-7STURUXK.js → memory-TNW7RSAV.js} +1 -1
- package/chunks/mn-JMS6SWTO.js +8 -0
- package/chunks/{model-call-collection-WBWTO3EG.js → model-call-collection-KNTWFZQS.js} +1 -1
- package/chunks/{model-configuration-6KCZZSZD.js → model-configuration-U5C5P5UQ.js} +1 -1
- package/chunks/{modelConfigUtils-Z2EKFSPN.js → modelConfigUtils-R4KFI2WK.js} +1 -1
- package/chunks/{monitor-U5E33JO6.js → monitor-RD2PFK42.js} +1 -1
- package/chunks/{nonInteractiveCli-BVCL5I5R.js → nonInteractiveCli-QQ72HZSH.js} +1 -1
- package/chunks/{nonInteractiveToolExecutor-B4EUOMYF.js → nonInteractiveToolExecutor-QPQYR6IS.js} +1 -1
- package/chunks/{notebook-edit-MXKD5J2C.js → notebook-edit-YLRN3UZT.js} +1 -1
- package/chunks/{omni-I5YECZBW.js → omni-CUJ52EW5.js} +1 -1
- package/chunks/{openaiContentGenerator-Q5SINFJJ.js → openaiContentGenerator-6B5MAU54.js} +1 -1
- package/chunks/{openaiResponsesContentGenerator-R3XCZLZY.js → openaiResponsesContentGenerator-I245I3R7.js} +1 -1
- package/chunks/{pidfile-UOGUNUTK.js → pidfile-P2HIGAUA.js} +1 -1
- package/chunks/{processUtils-QGQGZHBA.js → processUtils-JSKN5UGS.js} +1 -1
- package/chunks/{prompt-terminal-ledger-L57JMVSR.js → prompt-terminal-ledger-F5TSXVGU.js} +1 -1
- package/chunks/{qwenContentGenerator-UKZ237LC.js → qwenContentGenerator-IEDZONWG.js} +1 -1
- package/chunks/{reactive-degrade-3OM3HWVA.js → reactive-degrade-FYZBJCF6.js} +1 -1
- package/chunks/{read-file-63ZLWMOW.js → read-file-VNZNSD6X.js} +1 -1
- package/chunks/{resumeHistoryUtils-R5YQS4YQ.js → resumeHistoryUtils-IDPE6N2N.js} +1 -1
- package/chunks/{review-AT6OWVDO.js → review-TBJRZWTD.js} +1 -1
- package/chunks/{ripGrep-7KBZGTPV.js → ripGrep-4W5B5FOE.js} +1 -1
- package/chunks/{run-qwen-serve-CLBG7W6F.js → run-qwen-serve-44X262G5.js} +1 -1
- package/chunks/{runtime-R3QIGB7U.js → runtime-6H6LKD73.js} +1 -1
- package/chunks/{sandboxConfig-PM3ZRQYV.js → sandboxConfig-SQXDRGVN.js} +1 -1
- package/chunks/{scheduled-tasks-PUMNN5XV.js → scheduled-tasks-62IZKHJG.js} +1 -1
- package/chunks/{scheduler-KTPM226B.js → scheduler-QUCXJYRL.js} +1 -1
- package/chunks/{search-memory-7I5MGDNV.js → search-memory-TC2Z34QN.js} +1 -1
- package/chunks/{send-message-J526AEBI.js → send-message-TFZX7KI7.js} +1 -1
- package/chunks/{serve-KLTMPK4W.js → serve-WSICDFGG.js} +1 -1
- package/chunks/{server-VLRNY6KG.js → server-GYYVTNGY.js} +3 -3
- package/chunks/{session-2EB57NXY.js → session-KF3O23ZJ.js} +1 -1
- package/chunks/{session-attachments-root-I7TESMWL.js → session-attachments-root-7HFUSONH.js} +1 -1
- package/chunks/{session-execution-engine-selector-5FAMSPSO.js → session-execution-engine-selector-NVILT6BR.js} +1 -1
- package/chunks/{session-pr-refresh-JCPVQPNJ.js → session-pr-refresh-3KDFTDEV.js} +1 -1
- package/chunks/{sessionService-YRW2IFPR.js → sessionService-XRTFLPDW.js} +1 -1
- package/chunks/{settings-KO2Q47JP.js → settings-QPPK6WXE.js} +1 -1
- package/chunks/{shell-OLZVNTQZ.js → shell-WYQDZWL7.js} +1 -1
- package/chunks/{skill-XW2AQS7M.js → skill-FYPT6AU7.js} +1 -1
- package/chunks/{skill-settings-TKAVQ4XP.js → skill-settings-OGFI5KZF.js} +1 -1
- package/chunks/{spawnChannel-MBGCTK2J.js → spawnChannel-ANOOVPG7.js} +1 -1
- package/chunks/{standalone-update-A3YLLIAN.js → standalone-update-45WTDY4E.js} +1 -1
- package/chunks/{start-opentui-ui-G5ROAR4V.js → start-opentui-ui-TL5WK33V.js} +1 -1
- package/chunks/{startInteractiveUI-PZQR4U53.js → startInteractiveUI-N2IREVBM.js} +1 -1
- package/chunks/{team-create-S5ZY2UMF.js → team-create-R77PRZ5U.js} +1 -1
- package/chunks/{team-plan-approval-KX6RXEST.js → team-plan-approval-6DCRKB5I.js} +1 -1
- package/chunks/{terminal-image-renderer-SCJREXE6.js → terminal-image-renderer-TB7EX2WW.js} +1 -1
- package/chunks/{theme-manager-DZSM4EBR.js → theme-manager-RQDXJGVR.js} +1 -1
- package/chunks/{tool-call-UK56SWCT.js → tool-call-LVB4NCDT.js} +1 -1
- package/chunks/{tool-result-media-JLLSLGFL.js → tool-result-media-LRBB2KS6.js} +1 -1
- package/chunks/{tool-search-OWPFLVV5.js → tool-search-OG73QAQZ.js} +1 -1
- package/chunks/{total-session-admission-NQU4ACKH.js → total-session-admission-A4CUF6AD.js} +1 -1
- package/chunks/{trustedFolders-N7GXFYSF.js → trustedFolders-LSGOYTU2.js} +1 -1
- package/chunks/{update-relaunch-5SPXXHM2.js → update-relaunch-OGC6BZO7.js} +1 -1
- package/chunks/{updateCheck-VXUIX2XG.js → updateCheck-7J3GXTER.js} +1 -1
- package/chunks/{upload-config-OWLL4SRQ.js → upload-config-ML5XEJIF.js} +1 -1
- package/chunks/{useAutoAcceptIndicator-OUYRR56F.js → useAutoAcceptIndicator-6DH6GQ2X.js} +1 -1
- package/chunks/{validateNonInterActiveAuth-PSVJO5HK.js → validateNonInterActiveAuth-KJDAGZCM.js} +1 -1
- package/chunks/{version-C26S7UAW.js → version-7JN2YXL2.js} +1 -1
- package/chunks/{web-fetch-AYOYV7R4.js → web-fetch-42ZR4FEZ.js} +1 -1
- package/chunks/{web-search-DAREKD3Z.js → web-search-74NLPMZJ.js} +1 -1
- package/chunks/{workflow-WBGPKVO6.js → workflow-WNPHX42I.js} +1 -1
- package/chunks/{workflow-ancestor-trust-GEEB53TB.js → workflow-ancestor-trust-HGF6G7LQ.js} +1 -1
- package/chunks/{workspace-agents-IMAQME4W.js → workspace-agents-3YFBFAK3.js} +1 -1
- package/chunks/{workspace-providers-status-VALHVEU2.js → workspace-providers-status-EPJI6KRV.js} +1 -1
- package/chunks/{workspace-recovery-worker-AIAVRDGU.js → workspace-recovery-worker-T3FK5YOD.js} +1 -1
- package/chunks/{workspace-registration-store-FXEGZG3L.js → workspace-registration-store-VEXYBDMA.js} +1 -1
- package/chunks/{workspace-registry-GYFFHWCD.js → workspace-registry-NRZYTP2X.js} +1 -1
- package/chunks/{workspace-runtime-coordinator-VZ462TLU.js → workspace-runtime-coordinator-USNSTP2V.js} +1 -1
- package/chunks/{workspace-service-5DIZM4IZ.js → workspace-service-USATWO56.js} +1 -1
- package/chunks/{workspace-skills-status-DOOBVL5N.js → workspace-skills-status-M5JTSFDL.js} +1 -1
- package/chunks/{workspace-trust-reconciler-LOICVUVW.js → workspace-trust-reconciler-ZUZ2O5WC.js} +1 -1
- package/chunks/{write-file-EJNMAHQD.js → write-file-UMJVKE4S.js} +1 -1
- package/chunks/{zoom-image-S3OARMYP.js → zoom-image-76XYHQ3Z.js} +1 -1
- package/cli.js +2 -2
- package/execution-worker.js +1 -1
- package/export-transcript-document.js +1 -1
- package/gerege.mjs +64 -15
- package/locales/mn.js +2702 -3774
- package/package.json +3 -3
- package/chunks/mn-YH2OTBWJ.js +0 -8
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{AUTO_THEME_NAME,themeManager}from"./chunk-W3YCOEIP.js";import{initializeI18n,resolveLanguageSetting,t}from"./chunk-
|
|
3
|
+
import{AUTO_THEME_NAME,themeManager}from"./chunk-W3YCOEIP.js";import{initializeI18n,resolveLanguageSetting,t}from"./chunk-NO7VTKRL.js";import{IdeClient}from"./chunk-T3CQ72HC.js";import{AuthEvent,IdeConnectionEvent,logAuth,logIdeConnection}from"./chunk-ZWPSBU7K.js";import{getErrorMessage}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();async function performInitialAuth(config,authType){if(!authType){return null}try{await config.refreshAuth(authType,true);const authEvent=new AuthEvent(authType,"auto","success");logAuth(config,authEvent)}catch(e){const errorMessage=`Failed to login. Message: ${getErrorMessage(e)}`;const authEvent=new AuthEvent(authType,"auto","error",errorMessage);logAuth(config,authEvent);return errorMessage}return null}__name(performInitialAuth,"performInitialAuth");init_esbuild_shims();function validateTheme(settings){const effectiveTheme=settings.merged.ui?.theme;if(effectiveTheme&&effectiveTheme!==AUTO_THEME_NAME&&!themeManager.findThemeByName(effectiveTheme)){return t('Theme "{{themeName}}" not found.',{themeName:effectiveTheme})}return null}__name(validateTheme,"validateTheme");async function connectIdeForStartup(config){if(!config.getIdeMode())return;const ideClient=await IdeClient.getInstance();await ideClient.connect();logIdeConnection(config,new IdeConnectionEvent("start"))}__name(connectIdeForStartup,"connectIdeForStartup");async function initializeApp(config,settings,options={}){await initializeI18n(resolveLanguageSetting(settings.merged.general?.language));const authType=config.getModelsConfig().getCurrentAuthType();const authError=await performInitialAuth(config,authType);const themeError=validateTheme(settings);const shouldOpenAuthDialog=!config.getModelsConfig().wasAuthTypeExplicitlyProvided()||!!authError;if(!options.deferIdeConnection){await connectIdeForStartup(config)}return{authError,themeError,shouldOpenAuthDialog,memoryFileCount:config.getMemoryFileCount()}}__name(initializeApp,"initializeApp");export{connectIdeForStartup,initializeApp};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2025 Google LLC
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{HOSTNAME_RE,isOwnerRepo,normalizeGhHostForUrl}from"./chunk-UPWFKIG7.js";import{GIT_TIMEOUT_MS,git,gitOpt,gitProbe,gitRaw,redirectedAncestor,refExists,releaseWorktree,repoRoot,sanitizedGitEnv}from"./chunk-
|
|
3
|
+
import{HOSTNAME_RE,isOwnerRepo,normalizeGhHostForUrl}from"./chunk-UPWFKIG7.js";import{GIT_TIMEOUT_MS,git,gitOpt,gitProbe,gitRaw,redirectedAncestor,refExists,releaseWorktree,repoRoot,sanitizedGitEnv}from"./chunk-4LC4INFI.js";import{normalizeSegment}from"./chunk-CTMNGGOU.js";import{isWithinRoot}from"./chunk-IDXJIDME.js";import{atomicWriteFileSync}from"./chunk-BMHYEQTI.js";import{writeStdoutLine}from"./chunk-M4ECEHLX.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{lstatSync as lstatSync2,readFileSync as readFileSync2,renameSync as renameSync2,rmSync as rmSync2}from"node:fs";import{dirname as dirname2,join as join2}from"node:path";init_esbuild_shims();import{createHash,randomUUID}from"node:crypto";import{homedir}from"node:os";import{closeSync,constants,existsSync,fstatSync,linkSync,lstatSync,mkdirSync,openSync,readFileSync,readlinkSync,realpathSync,renameSync,rmSync,statSync,unlinkSync,writeFileSync}from"node:fs";import{basename,dirname,isAbsolute,join,resolve}from"node:path";var REPLY_MARKER="<!-- qwen-autofix-pr:v1 -->";var WATCH_INTERVALS=[1,2,5,10,15,30,60];var MAX_NEEDS_HUMAN=20;var MAX_INSTRUCTIONS_CHARS=2e3;function rerunFloors(state){return[...state.rerunChecks??[],...(state.heldChecks??[]).map(entry=>entry.replace(/^\d+:/,""))]}__name(rerunFloors,"rerunFloors");var MAX_PUSHES=10;var MAX_CHECK_FIX_PUSHES=3;var MAX_FAILING_CHECKS=100;function withKnownHead(state,head){if(state.pushedShas.includes(head)||!state.failingChecks?.length){return{...state,lastKnownHeadSha:head}}const lastPush=state.pushedShas.at(-1);return{...state,lastKnownHeadSha:head,failingChecks:state.failingChecks.map(record=>({identity:record.identity,check:record.check,head:record.head,pushes:0,...lastPush===void 0?{}:{lastPush}}))}}__name(withKnownHead,"withKnownHead");function checkAttemptKey(check,headSha,attempt){return`${check}@${headSha}@${attempt}`}__name(checkAttemptKey,"checkAttemptKey");function watchRoot(){if(process.env["QWEN_CODE_SERVE"]==="1"){return git("rev-parse","--show-toplevel")}return repoRoot()}__name(watchRoot,"watchRoot");function parseWorktreePaths(nulOutput){const paths=[];for(const field of nulOutput.split("\0")){if(field.startsWith("worktree ")){paths.push(field.slice("worktree ".length))}}return paths}__name(parseWorktreePaths,"parseWorktreePaths");function cloneWorktreeRoots(){const z=gitOpt("worktree","list","--porcelain","-z");if(z!==null)return parseWorktreePaths(z);return[repoRoot()]}__name(cloneWorktreeRoots,"cloneWorktreeRoots");function findWatchRoot(prNumber){assertPositiveInteger(prNumber,"PR number");let found=null;for(const root of vouchedScanRoots(cloneWorktreeRoots())){const paths=autofixPrPaths(root,prNumber);let hasState;try{hasState=isRegularFile(paths.statePath)}catch{continue}if(!hasState)continue;if(found===null||!existsSync(autofixPrPaths(found,prNumber).worktreePath)&&existsSync(paths.worktreePath)){found=root}}return found}__name(findWatchRoot,"findWatchRoot");function resolveWatchRoot(prNumber){return findWatchRoot(prNumber)??watchRoot()}__name(resolveWatchRoot,"resolveWatchRoot");function anchorStoreRoot(){return process.env["QWEN_AUTOFIX_ANCHOR_DIR"]??join(homedir(),".qwen","autofix-anchors")}__name(anchorStoreRoot,"anchorStoreRoot");function anchorPath(repository,prNumber,cloneRoot){assertPositiveInteger(prNumber,"PR number");const slug=[normalizeGhHostForUrl(repository.host).replace(/:/g,"@"),normalizeSegment(repository.owner),normalizeSegment(repository.repo)].join("+").replace(/[^a-z0-9._@+-]/g,"_");const cloneKey=createHash("sha256").update(resolve(cloneRoot)).digest("hex").slice(0,16);return join(anchorStoreRoot(),slug,`${cloneKey}-pr-${prNumber}.json`)}__name(anchorPath,"anchorPath");function writeAnchor(repository,prNumber,trustRoot){const path=anchorPath(repository,prNumber,trustRoot);mkdirSync(dirname(path),{recursive:true});const anchor={trustRoot,...repository};atomicWriteFileSync(path,`${JSON.stringify(anchor,null,2)}
|
|
4
4
|
`,NO_FOLLOW)}__name(writeAnchor,"writeAnchor");function readAnchor(repository,prNumber){const path=anchorPath(repository,prNumber,repoRoot());if(!isRegularFile(path))return null;try{const parsed=JSON.parse(readRegularFile(path)??"null");if(parsed&&typeof parsed.trustRoot==="string"&&typeof parsed.host==="string"&&typeof parsed.owner==="string"&&typeof parsed.repo==="string"){return parsed}return null}catch{return null}}__name(readAnchor,"readAnchor");function trustAnchor(state){const anchor=readAnchor(state,state.prNumber);if(!anchor){throw new Error(`PR #${state.prNumber} has no confirmed trust anchor; re-run \`qwen autofix-pr prepare ${state.prNumber}\` (or resume it) to confirm the clone before its worktree can be validated`)}return anchor.trustRoot}__name(trustAnchor,"trustAnchor");function vouchedScanRoots(roots){if(roots.length===0)return[];const main=roots[0];const notNested=roots.filter(r=>!roots.some(other=>other!==r&&isWithinRoot(r,join(other,".qwen","tmp"))));let genuineCommon;let genuineWorktrees;try{const dotGit=join(main,".git");genuineCommon=realpathSync(existsSync(dotGit)?dotGit:main);genuineWorktrees=realpathSync(join(genuineCommon,"worktrees"))}catch{return notNested.slice(0,1)}return notNested.filter(r=>r===main||vouchesForClone(r,genuineCommon,genuineWorktrees))}__name(vouchedScanRoots,"vouchedScanRoots");function vouchesForClone(root,genuineCommon,genuineWorktrees){const dotGit=join(root,".git");let st;try{st=lstatSync(dotGit)}catch{return false}if(st.isDirectory()){try{return realpathSync(dotGit)===genuineCommon}catch{return false}}if(!st.isFile())return false;let text;try{text=readFileSync(dotGit,"utf8")}catch{return false}if(!text.startsWith("gitdir: "))return false;const pointer=text.slice("gitdir: ".length).replace(/[\r\n]+$/,"");let entry;try{entry=realpathSync(isAbsolute(pointer)?pointer:join(root,pointer))}catch{return false}if(dirname(entry)!==genuineWorktrees)return false;let back;try{back=readFileSync(join(entry,"gitdir"),"utf8").replace(/[\r\n]+$/,"")}catch{return false}try{return realpathSync(isAbsolute(back)?back:join(entry,back))===realpathSync(dotGit)}catch{return false}}__name(vouchesForClone,"vouchesForClone");function assertPositiveInteger(value,what){if(!Number.isInteger(value)||value<1){throw new TypeError(`${what} must be a positive integer, got ${value}`)}}__name(assertPositiveInteger,"assertPositiveInteger");function statePaths(root,state){const paths=autofixPrPaths(root,state.prNumber);return state.inPlace?{...paths,worktreePath:state.worktreePath,branch:state.branch}:paths}__name(statePaths,"statePaths");function autofixPrPaths(root,prNumber){assertPositiveInteger(prNumber,"PR number");const tmp=join(root,".qwen","tmp");return{worktreePath:join(tmp,`autofix-pr-${prNumber}`),statePath:join(tmp,`autofix-pr-${prNumber}-state.json`),gatePath:join(tmp,`autofix-pr-${prNumber}-gate.json`),checkedPath:join(tmp,`autofix-pr-${prNumber}-gate.checked`),snapshotPath:join(tmp,`autofix-pr-${prNumber}-snapshot.json`),repliesPath:join(tmp,`autofix-pr-${prNumber}-replies.json`),lockPath:join(tmp,`autofix-pr-${prNumber}.lock`),instructionsPath:join(tmp,`autofix-pr-${prNumber}-instructions.txt`),fixPath:join(tmp,`autofix-pr-${prNumber}-fix.json`),branch:`qwen-autofix/pr-${prNumber}`,headRef:`refs/qwen-autofix/pr-${prNumber}/head`}}__name(autofixPrPaths,"autofixPrPaths");function isRegularFile(path){return lstatSync(path,{throwIfNoEntry:false})?.isFile()===true}__name(isRegularFile,"isRegularFile");function readRegularFile(path){let fd;try{fd=openSync(path,constants.O_RDONLY|(constants.O_NOFOLLOW??0)|(constants.O_NONBLOCK??0))}catch(err){if(err.code==="ENOENT")return null;throw err}try{if(!fstatSync(fd).isFile()){throw new Error(`${path} is not a regular file`)}return readFileSync(fd,"utf8")}finally{closeSync(fd)}}__name(readRegularFile,"readRegularFile");function readGateCursor(gatePath){if(lstatSync(gatePath,{throwIfNoEntry:false})===void 0){return null}if(!isRegularFile(gatePath)){throw new Error(`${gatePath} is not a regular file`)}const text=readRegularFile(gatePath);if(text===null)return null;const parsed=JSON.parse(text);if(parsed.version!==1){throw new Error(`unsupported autofix-pr gate cursor version in ${gatePath}: ${String(parsed.version)}`)}return{...parsed,reportedTruncated:parsed.reportedTruncated??[]}}__name(readGateCursor,"readGateCursor");function writeGateCursor(gatePath,cursor){atomicWriteFileSync(gatePath,`${JSON.stringify(cursor,null,2)}
|
|
5
5
|
`,{noFollow:true})}__name(writeGateCursor,"writeGateCursor");function sameRepository(a,b){return normalizeGhHostForUrl(a.host)===normalizeGhHostForUrl(b.host)&&normalizeSegment(a.owner)===normalizeSegment(b.owner)&&normalizeSegment(a.repo)===normalizeSegment(b.repo)}__name(sameRepository,"sameRepository");var SHA_RE=/^[0-9a-f]{40,64}$/;function isBranchName(name){return!(name===""||name==="@"||name.startsWith("-")||name.endsWith("/")||name.endsWith(".")||[...name].some(char=>char.charCodeAt(0)<=32||char==="\x7F")||/[~^:?*[\\]/.test(name)||name.includes("..")||name.includes("@{")||name.includes("//")||name.split("/").some(part=>part.startsWith(".")||part.endsWith(".lock")))}__name(isBranchName,"isBranchName");var SHELL_SPECIAL=/[;&|$`<>()'"{}!#]/;function isCommandSafeName(name){return!SHELL_SPECIAL.test(name)}__name(isCommandSafeName,"isCommandSafeName");function stringList(value){return Array.isArray(value)?value.filter(item=>typeof item==="string"):[]}__name(stringList,"stringList");var isStringList=__name(value=>Array.isArray(value)&&value.every(item=>typeof item==="string"),"isStringList");var isRunList=__name(value=>Array.isArray(value)&&value.every(item=>Number.isInteger(item)),"isRunList");function isPendingPost(value){const post=value;return typeof post==="object"&&post!==null&&(post.where==="summary"||Number.isInteger(post.where))&&isStringList(post.handled)&&typeof post.bodyHash==="string"&&typeof post.sha==="string"&&(post.needsHuman===void 0||isStringList(post.needsHuman))}__name(isPendingPost,"isPendingPost");function stateDefect(state){const word=__name(value=>typeof value==="string"&&value!==""&&!value.startsWith("-"),"word");if(!word(state.remote)||!isBranchName(state.remote)||!isCommandSafeName(state.remote)){return"remote"}if(!word(state.pushTarget))return"pushTarget";if(!word(state.headRefName)||!isBranchName(state.headRefName)){return"headRefName"}if(!word(state.baseRefName)||!isBranchName(state.baseRefName)||!isCommandSafeName(state.baseRefName)){return"baseRefName"}if(!isOwnerRepo(`${state.owner}/${state.repo}`))return"owner/repo";if(typeof state.host!=="string"||!HOSTNAME_RE.test(state.host)){return"host"}if(!Number.isInteger(state.prNumber)||state.prNumber<1){return"prNumber"}if(typeof state.lastKnownHeadSha!=="string"||!SHA_RE.test(state.lastKnownHeadSha)){return"lastKnownHeadSha"}if(!Array.isArray(state.pushedShas)||!state.pushedShas.every(sha=>typeof sha==="string"&&SHA_RE.test(sha))){return"pushedShas"}if(!isStringList(state.handledCommentIds))return"handledCommentIds";if(!isStringList(state.postedCommentIds))return"postedCommentIds";if(state.handledChecks!==void 0&&!isStringList(state.handledChecks)){return"handledChecks"}if(state.rerunChecks!==void 0&&!isStringList(state.rerunChecks)){return"rerunChecks"}if(state.deferredRuns!==void 0&&!isRunList(state.deferredRuns)){return"deferredRuns"}if(state.heldChecks!==void 0&&!isStringList(state.heldChecks)){return"heldChecks"}if(state.pendingPosts!==void 0&&!(Array.isArray(state.pendingPosts)&&state.pendingPosts.every(isPendingPost))){return"pendingPosts"}if(state.pushCount!==void 0&&!(Number.isInteger(state.pushCount)&&state.pushCount>=0)){return"pushCount"}if(state.watch!==void 0&&!isWatchOptions(state.watch)){return"watch"}if(state.needsHuman!==void 0&&!(Array.isArray(state.needsHuman)&&state.needsHuman.every(isNeedsHumanItem))){return"needsHuman"}if(state.reportedNeedsHuman!==void 0&&!(typeof state.reportedNeedsHuman==="object"&&state.reportedNeedsHuman!==null&&typeof state.reportedNeedsHuman.sha==="string"&&SHA_RE.test(state.reportedNeedsHuman.sha)&&isStringList(state.reportedNeedsHuman.texts))){return"reportedNeedsHuman"}if(state.preparedAt!==void 0&&typeof state.preparedAt!=="string"){return"preparedAt"}if(state.ended!==void 0&&!(typeof state.ended==="object"&&state.ended!==null&&typeof state.ended.at==="string"&&typeof state.ended.reason==="string")){return"ended"}if(state.failingChecks!==void 0&&!(Array.isArray(state.failingChecks)&&state.failingChecks.every(isFailingCheck))){return"failingChecks"}return null}__name(stateDefect,"stateDefect");function isFailingCheck(value){const check=value;return typeof check==="object"&&check!==null&&typeof check.identity==="string"&&typeof check.check==="string"&&typeof check.head==="string"&&Number.isInteger(check.pushes)&&check.pushes>=0&&SHA_RE.test(check.head)&&(check.lastPush===void 0||SHA_RE.test(check.lastPush))&&(check.unanswered===void 0||Array.isArray(check.unanswered)&&check.unanswered.every(entry=>typeof entry==="object"&&entry!==null&&typeof entry.sha==="string"&&SHA_RE.test(entry.sha)&&Number.isInteger(entry.pushes)&&entry.pushes>=0))}__name(isFailingCheck,"isFailingCheck");function isWatchOptions(value){const watch=value;return typeof watch==="object"&&watch!==null&&WATCH_INTERVALS.includes(watch.every)&&typeof watch.reply==="boolean"&&typeof watch.instructions==="string"&&watch.instructions.length<=MAX_INSTRUCTIONS_CHARS&&!/[\p{Cc}\p{Cf}\u2028\u2029]/u.test(watch.instructions)&&(watch.task===void 0||/^[0-9a-f]{12}$/.test(watch.task))}__name(isWatchOptions,"isWatchOptions");function isNeedsHumanItem(value){const item=value;return typeof item==="object"&&item!==null&&typeof item.sha==="string"&&typeof item.at==="string"&&typeof item.text==="string"}__name(isNeedsHumanItem,"isNeedsHumanItem");function readState(statePath){const entry=lstatSync(statePath,{throwIfNoEntry:false});if(entry===void 0)return null;if(!entry.isFile()){throw new Error(`${statePath} is not a regular file; \`qwen autofix-pr cleanup <pr> --force\` discards it.`)}let text;try{text=readRegularFile(statePath)}catch{throw new Error(`${statePath} is not a regular file; \`qwen autofix-pr cleanup <pr> --force\` discards it.`)}if(text===null)return null;const parsed=JSON.parse(text);if(parsed.version!==1){throw new Error(`unsupported autofix-pr state version in ${statePath}: ${String(parsed.version)}`)}const defect=stateDefect(parsed);if(defect){throw new Error(`${statePath} has an invalid ${defect}; run \`qwen autofix-pr cleanup ${String(parsed.prNumber)} --force\` and prepare the watch again.`)}const{watch,ended,needsHuman,reportedNeedsHuman,failingChecks}=parsed;return{...parsed,...watch?{watch:{every:watch.every,reply:watch.reply,instructions:watch.instructions,...watch.task!==void 0?{task:watch.task}:{}}}:{},...ended?{ended:{at:ended.at,reason:ended.reason}}:{},...needsHuman?{needsHuman:needsHuman.map(({sha,at,text:text2})=>({sha,at,text:text2}))}:{},...reportedNeedsHuman?{reportedNeedsHuman:{sha:reportedNeedsHuman.sha,texts:[...reportedNeedsHuman.texts]}}:{},...failingChecks?{failingChecks:failingChecks.map(({identity,check,head,pushes,lastPush,unanswered})=>({identity,check,head,pushes,...lastPush===void 0?{}:{lastPush},...unanswered===void 0?{}:{unanswered:unanswered.map(({sha,pushes:pushes2})=>({sha,pushes:pushes2}))}}))}:{}}}__name(readState,"readState");var NO_FOLLOW={noFollow:true};function writeState(statePath,state){atomicWriteFileSync(statePath,`${JSON.stringify(state,null,2)}
|
|
6
6
|
`,NO_FOLLOW)}__name(writeState,"writeState");function historyPath(paths,repository){const slug=[normalizeGhHostForUrl(repository.host).replace(/:/g,"@"),normalizeSegment(repository.owner),normalizeSegment(repository.repo)].join("+").replace(/[^a-z0-9._@+-]/g,"_");return join(dirname(paths.statePath),`${historyPrefix(paths)}${slug}.history.json`)}__name(historyPath,"historyPath");function historyPrefix(paths){return basename(paths.statePath).replace(/-state\.json$/,"-history-")}__name(historyPrefix,"historyPrefix");function readHistory(path){if(lstatSync(path,{throwIfNoEntry:false})===void 0)return null;if(!isRegularFile(path))throw new Error(`${path} is not a regular file`);const parsed=JSON.parse(readFileSync(path,"utf8"));if(parsed.version!==1){throw new Error(`unsupported autofix-pr history version in ${path}: ${String(parsed.version)}`)}return{...parsed,handledCommentIds:stringList(parsed.handledCommentIds),postedCommentIds:stringList(parsed.postedCommentIds),handledChecks:stringList(parsed.handledChecks),rerunChecks:stringList(parsed.rerunChecks),handledConflictSha:typeof parsed.handledConflictSha==="string"&&SHA_RE.test(parsed.handledConflictSha)?parsed.handledConflictSha:null,pendingPosts:Array.isArray(parsed.pendingPosts)?parsed.pendingPosts.filter(isPendingPost):[],deferredRuns:Array.isArray(parsed.deferredRuns)?parsed.deferredRuns.filter(run=>Number.isInteger(run)):[],heldChecks:stringList(parsed.heldChecks)}}__name(readHistory,"readHistory");function keepHistory(paths,state){const path=historyPath(paths,state);let earlier=null;try{earlier=readHistory(path)}catch{}if(earlier&&!sameRepository(earlier,state))earlier=null;const union=__name((a,b)=>[...new Set([...stringList(a),...stringList(b)])],"union");const history={version:1,host:state.host,owner:state.owner,repo:state.repo,prNumber:state.prNumber,handledCommentIds:union(earlier?.handledCommentIds,state.handledCommentIds),postedCommentIds:union(earlier?.postedCommentIds,state.postedCommentIds),handledChecks:union(earlier?.handledChecks,state.handledChecks),rerunChecks:union(earlier?.rerunChecks,state.rerunChecks),handledConflictSha:state.handledConflictSha??earlier?.handledConflictSha??null,pendingPosts:state.pendingPosts??earlier?.pendingPosts??[],deferredRuns:state.deferredRuns??earlier?.deferredRuns??[],heldChecks:state.heldChecks??earlier?.heldChecks??[]};const entry=lstatSync(path,{throwIfNoEntry:false});if(entry&&!entry.isFile()&&!entry.isSymbolicLink()){rmSync(path,{recursive:true,force:true})}atomicWriteFileSync(path,`${JSON.stringify(history,null,2)}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{captureEnvironmentBeforeLoad,publishPendingCompileCache,resetEnvironmentSnapshotForTesting}from"./chunk-PKK2D2W4.js";import{DEFAULT_EXCLUDED_ENV_VARS,HOME_ENV_BOOTSTRAP_KEYS,PROJECT_ENV_HARDCODED_EXCLUSIONS,VERIFY_PR_COORDINATE_ENV,isHardcodedProjectEnvExclusion,isLoaderEnvKey,isPrivateProvenanceEnvKey,reportRejectedLoaderKeys,resetLoaderKeyRejectionReportingForTesting}from"./chunk-N3AQAZ7D.js";import{PRIVATE_RELAUNCH_ENV_PROVENANCE}from"./chunk-E5T4R2PM.js";import{isWorkspaceTrusted}from"./chunk-BBOJUFMW.js";import{require_main}from"./chunk-ZOTKZI2P.js";import{writeStderrLineSafe}from"./chunk-M4ECEHLX.js";import{Storage}from"./chunk-EPODBRBP.js";import{QWEN_DIR}from"./chunk-OKN3Z5C5.js";import{getErrorMessage}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var dotenv=__toESM(require_main(),1);import*as fs from"node:fs";import*as path from"node:path";import*as os from"node:os";var SETTINGS_DIRECTORY_NAME=QWEN_DIR;var RELOAD_EXCLUDED_KEYS=new Set([...PROJECT_ENV_HARDCODED_EXCLUSIONS,"LD_LIBRARY_PATH","DYLD_LIBRARY_PATH","ENV","PATH","HOME"]);var RELOAD_EXCLUDED_KEYS_CASEFOLDED=new Set([...RELOAD_EXCLUDED_KEYS].map(key=>key.toLowerCase()));function isReloadExcludedKey(key){return RELOAD_EXCLUDED_KEYS_CASEFOLDED.has(key.toLowerCase())||isHardcodedProjectEnvExclusion(key)}__name(isReloadExcludedKey,"isReloadExcludedKey");var dotEnvSourcedKeys=new Set;var settingsEnvSourcedKeys=new Set;var inheritedDotEnvKeys=new Set;var inheritedSettingsEnvKeys=new Set;var inheritedProvenance=process.env[PRIVATE_RELAUNCH_ENV_PROVENANCE];delete process.env[PRIVATE_RELAUNCH_ENV_PROVENANCE];if(inheritedProvenance){const sources=JSON.parse(inheritedProvenance);if(!sources||typeof sources!=="object"||!("dotEnv"in sources)||!("settingsEnv"in sources)||!Array.isArray(sources.dotEnv)||!Array.isArray(sources.settingsEnv)||!sources.dotEnv.every(key=>typeof key==="string")||!sources.settingsEnv.every(key=>typeof key==="string")){throw new Error("Invalid inherited environment provenance.")}for(const key of sources.dotEnv)inheritedDotEnvKeys.add(key);for(const key of sources.settingsEnv)inheritedSettingsEnvKeys.add(key);Object.assign(process.env,getRelaunchEnvProvenance())}var DOCUMENTED_MODEL_ENV_KEYS=["OPENAI_API_KEY","OPENAI_BASE_URL","OPENAI_MODEL","QWEN_MODEL","ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","ANTHROPIC_MODEL","GEMINI_API_KEY","GEMINI_MODEL","GOOGLE_API_KEY","GOOGLE_MODEL"];var requestTimeEnvKeys=new Set;function rememberRequestTimeEnvKeys(settings){requestTimeEnvKeys.clear();for(const key of DOCUMENTED_MODEL_ENV_KEYS)requestTimeEnvKeys.add(key);for(const models of Object.values(settings.modelProviders??{})){if(!Array.isArray(models))continue;for(const model of models){const envKey=model?.envKey;if(typeof envKey==="string"&&envKey&&!isHardcodedProjectEnvExclusion(envKey)&&!isLoaderEnvKey(envKey)){requestTimeEnvKeys.add(envKey)}}}}__name(rememberRequestTimeEnvKeys,"rememberRequestTimeEnvKeys");function hasLoadedEnvironmentValues(){for(const keys of[dotEnvSourcedKeys,settingsEnvSourcedKeys]){for(const key of keys){if(!requestTimeEnvKeys.has(key))return true}}return false}__name(hasLoadedEnvironmentValues,"hasLoadedEnvironmentValues");function getRelaunchEnvProvenance(){return{[PRIVATE_RELAUNCH_ENV_PROVENANCE]:JSON.stringify({dotEnv:[...new Set([...inheritedDotEnvKeys,...dotEnvSourcedKeys])],settingsEnv:[...new Set([...inheritedSettingsEnvKeys,...settingsEnvSourcedKeys])]})}}__name(getRelaunchEnvProvenance,"getRelaunchEnvProvenance");var lastReloadSnapshot=new Map;var lastReloadSnapshotSeeded=false;function getUserLevelEnvPaths(){const homeDir=os.homedir();const globalQwenDir=Storage.getGlobalQwenDir();const paths=new Set([path.normalize(path.join(homeDir,".env")),path.normalize(path.join(globalQwenDir,".env"))]);const legacyQwenEnv=path.normalize(path.join(homeDir,QWEN_DIR,".env"));paths.add(legacyQwenEnv);return paths}__name(getUserLevelEnvPaths,"getUserLevelEnvPaths");var homeEnvBootstrapped=false;function preResolveHomeEnvOverrides(){if(homeEnvBootstrapped){return}homeEnvBootstrapped=true;if(HOME_ENV_BOOTSTRAP_KEYS.every(key=>process.env[key])){return}const initialQwenHome=process.env["QWEN_HOME"];const initialQwenDir=Storage.getGlobalQwenDir();const candidates=[path.join(initialQwenDir,".env")];if(!initialQwenHome){candidates.push(path.join(path.dirname(initialQwenDir),".env"))}for(const candidate of candidates){readHomeEnvInto(candidate)}const discoveredQwenHome=process.env["QWEN_HOME"];if(discoveredQwenHome&&discoveredQwenHome!==initialQwenHome){const discoveredDir=Storage.getGlobalQwenDir();if(discoveredDir!==initialQwenDir){readHomeEnvInto(path.join(discoveredDir,".env"))}}}__name(preResolveHomeEnvOverrides,"preResolveHomeEnvOverrides");function readHomeEnvInto(file){if(!fs.existsSync(file)){return}try{const parsed=dotenv.parse(fs.readFileSync(file,"utf-8"));for(const key of HOME_ENV_BOOTSTRAP_KEYS){if(parsed[key]&&!Object.hasOwn(process.env,key)){process.env[key]=parsed[key]}}}catch(_e){}}__name(readHomeEnvInto,"readHomeEnvInto");function resetHomeEnvBootstrapForTesting(){homeEnvBootstrapped=false}__name(resetHomeEnvBootstrapForTesting,"resetHomeEnvBootstrapForTesting");function resetEnvironmentTrackingForTesting(){resetLoaderKeyRejectionReportingForTesting();resetEnvironmentSnapshotForTesting();dotEnvSourcedKeys.clear();settingsEnvSourcedKeys.clear();inheritedDotEnvKeys.clear();inheritedSettingsEnvKeys.clear();requestTimeEnvKeys.clear();delete process.env[PRIVATE_RELAUNCH_ENV_PROVENANCE];lastReloadSnapshot.clear();lastReloadSnapshotSeeded=false}__name(resetEnvironmentTrackingForTesting,"resetEnvironmentTrackingForTesting");function isFileSourcedEnvKey(key){const sources=[dotEnvSourcedKeys,settingsEnvSourcedKeys,inheritedDotEnvKeys,inheritedSettingsEnvKeys];if(sources.some(keys=>keys.has(key))){return true}if(process.platform!=="win32")return false;const lower=key.toLowerCase();for(const keys of sources){for(const tracked of keys){if(tracked.toLowerCase()===lower)return true}}return false}__name(isFileSourcedEnvKey,"isFileSourcedEnvKey");function getHomeEnvFallbackVars(onReadError){const globalQwenDir=Storage.getGlobalQwenDir();const candidates=[path.join(globalQwenDir,".env")];if(!process.env["QWEN_HOME"]){candidates.push(path.join(path.dirname(globalQwenDir),".env"))}const result={};for(const candidate of candidates){if(!fs.existsSync(candidate)){continue}try{const parsed=dotenv.parse(fs.readFileSync(candidate,"utf-8"));for(const key in parsed){if(Object.hasOwn(parsed,key)&&!Object.hasOwn(process.env,key)){result[key]??=parsed[key]}}}catch(e){onReadError?.(`Failed to read home .env candidate ${candidate}: ${getErrorMessage(e)}`)}}return result}__name(getHomeEnvFallbackVars,"getHomeEnvFallbackVars");function findEnvFiles(settings,startDir,userLevelPaths=getUserLevelEnvPaths(),workspaceTrusted){const homeDir=os.homedir();let realStartDir=path.resolve(startDir);try{realStartDir=fs.realpathSync(realStartDir)}catch{}const globalQwenDir=Storage.getGlobalQwenDir();const legacyQwenDir=path.normalize(path.join(homeDir,QWEN_DIR));const hasCustomConfigDir=path.normalize(globalQwenDir)!==legacyQwenDir;const found=[];const seen=new Set;const workspaceIsTrusted=workspaceTrusted??isWorkspaceTrusted(settings,void 0,realStartDir).isTrusted===true;const canUseEnvFile=__name(filePath=>{const normalized=path.normalize(filePath);if(userLevelPaths.has(normalized))return true;if(!workspaceIsTrusted)return false;const dirPath=path.dirname(normalized);const workspaceDir=path.basename(dirPath)===SETTINGS_DIRECTORY_NAME?path.dirname(dirPath):dirPath;if(workspaceDir===realStartDir)return true;return isWorkspaceTrusted(settings,void 0,workspaceDir).isTrusted!==false},"canUseEnvFile");const pushCandidate=__name(filePath=>{const normalized=path.normalize(filePath);if(!seen.has(normalized)&&fs.existsSync(filePath)&&canUseEnvFile(filePath)){seen.add(normalized);found.push(filePath);return true}return false},"pushCandidate");const pushHomeCandidates=__name(()=>{const candidates=[path.join(globalQwenDir,".env")];if(hasCustomConfigDir){candidates.push(path.join(legacyQwenDir,".env"))}candidates.push(path.join(homeDir,".env"));for(const candidate of candidates){pushCandidate(candidate)}},"pushHomeCandidates");if(path.resolve(startDir)===path.resolve(homeDir)){pushHomeCandidates();return found}let currentDir=realStartDir;let visitedHomeDir=false;while(true){if(currentDir===homeDir){visitedHomeDir=true;pushHomeCandidates();return found}else{const geminiEnvPath=path.join(currentDir,QWEN_DIR,".env");if(pushCandidate(geminiEnvPath)){pushHomeCandidates();return found}const envPath=path.join(currentDir,".env");if(pushCandidate(envPath)){pushHomeCandidates();return found}}const parentDir=path.dirname(currentDir);if(parentDir===currentDir||!parentDir){if(!visitedHomeDir){pushHomeCandidates()}return found}currentDir=parentDir}}__name(findEnvFiles,"findEnvFiles");function setUpCloudShellEnvironment(envFilePath){if(envFilePath&&fs.existsSync(envFilePath)){const envFileContent=fs.readFileSync(envFilePath);const parsedEnv=dotenv.parse(envFileContent);if(parsedEnv["GOOGLE_CLOUD_PROJECT"]){process.env["GOOGLE_CLOUD_PROJECT"]=parsedEnv["GOOGLE_CLOUD_PROJECT"]}else{process.env["GOOGLE_CLOUD_PROJECT"]="cloudshell-gca"}}else{process.env["GOOGLE_CLOUD_PROJECT"]="cloudshell-gca"}}__name(setUpCloudShellEnvironment,"setUpCloudShellEnvironment");function setUpCloudShellEnvironmentInEnv(env,envFiles){for(const envFile of envFiles){if(envFile.parsedEnv["GOOGLE_CLOUD_PROJECT"]){env["GOOGLE_CLOUD_PROJECT"]=envFile.parsedEnv["GOOGLE_CLOUD_PROJECT"];return}}env["GOOGLE_CLOUD_PROJECT"]="cloudshell-gca"}__name(setUpCloudShellEnvironmentInEnv,"setUpCloudShellEnvironmentInEnv");function parseEnvFiles(envFilePaths,userLevelPaths){const files=[];const readFailures=[];for(const envFilePath of envFilePaths){try{const envFileContent=fs.readFileSync(envFilePath,"utf-8");const parsedEnv=dotenv.parse(envFileContent);const normalizedEnvFilePath=path.normalize(envFilePath);const isHomeScopedEnvFile=userLevelPaths.has(normalizedEnvFilePath);const isQwenScopedEnvFile=isHomeScopedEnvFile||path.basename(path.dirname(normalizedEnvFilePath))===QWEN_DIR;files.push({path:envFilePath,parsedEnv,isHomeScopedEnvFile,isQwenScopedEnvFile})}catch(err){readFailures.push({path:envFilePath,error:getErrorMessage(err)})}}return{files,readFailed:readFailures.length>0,readFailures}}__name(parseEnvFiles,"parseEnvFiles");function canApplyParsedEnvKey(envFile,key,excludedVars,options={}){if(!Object.hasOwn(envFile.parsedEnv,key))return false;if(isLoaderEnvKey(key))return false;if(isPrivateProvenanceEnvKey(key))return false;if(options.reload&&isReloadExcludedKey(key))return false;if(!envFile.isHomeScopedEnvFile&&isHardcodedProjectEnvExclusion(key)){return false}return envFile.isQwenScopedEnvFile||!excludedVars.includes(key)}__name(canApplyParsedEnvKey,"canApplyParsedEnvKey");function isEffectivelyUnset(env,key){const existingValue=env[key];return!Object.hasOwn(env,key)||existingValue===""}__name(isEffectivelyUnset,"isEffectivelyUnset");function setRuntimeEnvIfUnset(env,key,value){if(isEffectivelyUnset(env,key)){env[key]=value}}__name(setRuntimeEnvIfUnset,"setRuntimeEnvIfUnset");function reportRejectedSettingsEnv(env,startDir){const source=`settings.env (${startDir})`;reportRejectedLoaderKeys(source,Object.keys(env));if(Object.entries(env).some(([key,value])=>key.toUpperCase()==="QWEN_AGENT_EXECUTION_BACKEND"&&typeof value==="string"&&value.trim()!=="")){writeStderrLineSafe(`qwen: ${source} cannot set QWEN_AGENT_EXECUTION_BACKEND; ignored. Export it in the launch environment instead.`)}for(const[setting,key]of Object.entries(VERIFY_PR_COORDINATE_ENV)){const entry=Object.entries(env).find(([candidate,value])=>candidate.toUpperCase()===key&&typeof value==="string"&&value.trim()!=="");if(!entry)continue;writeStderrLineSafe(`qwen: ${source} cannot set ${entry[0]}; ignored. Set verifyPr.${setting} at user scope in settings.json, or export it in the launch environment.`)}}__name(reportRejectedSettingsEnv,"reportRejectedSettingsEnv");function buildRuntimeEnvironment(settings,startDir=process.cwd(),baseEnv=process.env,workspaceTrusted){const userLevelPaths=getUserLevelEnvPaths();const envFilePaths=findEnvFiles(settings,startDir,userLevelPaths,workspaceTrusted);const parsedEnvFiles=parseEnvFiles(envFilePaths,userLevelPaths);const effectiveEnv={...baseEnv};if(baseEnv["CLOUD_SHELL"]==="true"){setUpCloudShellEnvironmentInEnv(effectiveEnv,parsedEnvFiles.files)}for(const envFile of parsedEnvFiles.files){const excludedVars=settings?.advanced?.excludedEnvVars||DEFAULT_EXCLUDED_ENV_VARS;for(const key in envFile.parsedEnv){if(!canApplyParsedEnvKey(envFile,key,excludedVars,{reload:true})){continue}setRuntimeEnvIfUnset(effectiveEnv,key,envFile.parsedEnv[key])}reportRejectedLoaderKeys(`.env file ${envFile.path}`,Object.keys(envFile.parsedEnv))}if(settings.env){const excludedVars=settings?.advanced?.excludedEnvVars||DEFAULT_EXCLUDED_ENV_VARS;for(const[key,value]of Object.entries(settings.env)){if(isLoaderEnvKey(key))continue;if(isReloadExcludedKey(key))continue;if(isHardcodedProjectEnvExclusion(key))continue;if(excludedVars.includes(key))continue;if(typeof value!=="string")continue;setRuntimeEnvIfUnset(effectiveEnv,key,value)}reportRejectedSettingsEnv(settings.env,startDir)}const overlayKeys=Object.keys(effectiveEnv).filter(key=>effectiveEnv[key]!==baseEnv[key]).sort();return{effectiveEnv:Object.freeze({...effectiveEnv}),overlayKeys:Object.freeze(overlayKeys),envFilePaths:Object.freeze([...envFilePaths]),envFileReadFailed:parsedEnvFiles.readFailed,envFileReadFailures:Object.freeze([...parsedEnvFiles.readFailures])}}__name(buildRuntimeEnvironment,"buildRuntimeEnvironment");function loadEnvironment(settings,startDir=process.cwd()){captureEnvironmentBeforeLoad();rememberRequestTimeEnvKeys(settings);const userLevelPaths=getUserLevelEnvPaths();const envFilePaths=findEnvFiles(settings,startDir,userLevelPaths);const parsedEnvFiles=parseEnvFiles(envFilePaths,userLevelPaths);if(process.env["CLOUD_SHELL"]==="true"){setUpCloudShellEnvironmentInEnv(process.env,parsedEnvFiles.files)}for(const envFile of parsedEnvFiles.files){const excludedVars=settings?.advanced?.excludedEnvVars||DEFAULT_EXCLUDED_ENV_VARS;for(const key in envFile.parsedEnv){if(!canApplyParsedEnvKey(envFile,key,excludedVars))continue;const existingValue=process.env[key];const isEffectivelyUnset2=!Object.hasOwn(process.env,key)||existingValue==="";if(isEffectivelyUnset2){process.env[key]=envFile.parsedEnv[key];dotEnvSourcedKeys.add(key)}if(!lastReloadSnapshotSeeded&&!lastReloadSnapshot.has(key)){lastReloadSnapshot.set(key,envFile.parsedEnv[key])}}reportRejectedLoaderKeys(`.env file ${envFile.path}`,Object.keys(envFile.parsedEnv))}if(settings.env){for(const[key,value]of Object.entries(settings.env)){if(isLoaderEnvKey(key)){continue}if(isReloadExcludedKey(key)){continue}if(isHardcodedProjectEnvExclusion(key)){continue}const existingValue=process.env[key];const isEffectivelyUnset2=!Object.hasOwn(process.env,key)||existingValue==="";if(isEffectivelyUnset2&&typeof value==="string"){process.env[key]=value;settingsEnvSourcedKeys.add(key)}if(!lastReloadSnapshotSeeded&&typeof value==="string"&&!lastReloadSnapshot.has(key)){lastReloadSnapshot.set(key,value)}}reportRejectedSettingsEnv(settings.env,startDir)}lastReloadSnapshotSeeded=true;Object.assign(process.env,getRelaunchEnvProvenance());publishPendingCompileCache()}__name(loadEnvironment,"loadEnvironment");function reloadEnvironment(settings,workspaceCwd,workspaceTrusted,options={}){const userLevelPaths=getUserLevelEnvPaths();const envFilePaths=findEnvFiles(settings,workspaceCwd,userLevelPaths,workspaceTrusted);const parsedEnvFiles=parseEnvFiles(envFilePaths,userLevelPaths);if(parsedEnvFiles.readFailed&&options.failClosedOnEnvFileReadError){return{updatedKeys:[],removedKeys:[],envFileReadFailed:true}}if(process.env["CLOUD_SHELL"]==="true"){setUpCloudShellEnvironmentInEnv(process.env,parsedEnvFiles.files)}const dotEnvReadFailed=parsedEnvFiles.readFailed;const newDotEnvKeys=new Map;const newSettingsEnvKeys=new Map;for(const envFile of parsedEnvFiles.files){const excludedVars=settings?.advanced?.excludedEnvVars||DEFAULT_EXCLUDED_ENV_VARS;for(const key in envFile.parsedEnv){if(!canApplyParsedEnvKey(envFile,key,excludedVars,{reload:true})){continue}if(!newDotEnvKeys.has(key)){newDotEnvKeys.set(key,envFile.parsedEnv[key])}}reportRejectedLoaderKeys(`.env file ${envFile.path}`,Object.keys(envFile.parsedEnv))}if(settings.env){for(const[key,value]of Object.entries(settings.env)){if(isLoaderEnvKey(key))continue;if(isReloadExcludedKey(key))continue;if(isHardcodedProjectEnvExclusion(key))continue;if(typeof value!=="string")continue;const dotEnvValue=newDotEnvKeys.get(key);if(dotEnvValue!==void 0&&dotEnvValue!=="")continue;if(dotEnvReadFailed&&lastReloadSnapshot.has(key))continue;newSettingsEnvKeys.set(key,value)}reportRejectedSettingsEnv(settings.env,workspaceCwd)}const allNewKeys=new Set([...newDotEnvKeys.keys(),...newSettingsEnvKeys.keys()]);const updatedKeys=[];const removedKeys=[];if(!dotEnvReadFailed){const previouslyKnown=new Set([...lastReloadSnapshot.keys(),...dotEnvSourcedKeys,...settingsEnvSourcedKeys]);for(const key of previouslyKnown){if(!allNewKeys.has(key)&&!isReloadExcludedKey(key)){delete process.env[key];inheritedDotEnvKeys.delete(key);inheritedSettingsEnvKeys.delete(key);removedKeys.push(key)}}}for(const[key,value]of newDotEnvKeys){if(value===""&&newSettingsEnvKeys.has(key))continue;if(process.env[key]!==value){updatedKeys.push(key)}process.env[key]=value}for(const[key,value]of newSettingsEnvKeys){if(process.env[key]!==value){updatedKeys.push(key)}process.env[key]=value}if(!dotEnvReadFailed){for(const sources of[dotEnvSourcedKeys,settingsEnvSourcedKeys]){for(const key of sources){if(!isReloadExcludedKey(key))sources.delete(key)}}lastReloadSnapshot.clear();for(const[key,value]of newDotEnvKeys){lastReloadSnapshot.set(key,value)}for(const[key,value]of newSettingsEnvKeys){lastReloadSnapshot.set(key,value)}}for(const key of newDotEnvKeys.keys()){dotEnvSourcedKeys.add(key)}for(const key of newSettingsEnvKeys.keys()){settingsEnvSourcedKeys.add(key)}Object.assign(process.env,getRelaunchEnvProvenance());return{updatedKeys,removedKeys,...dotEnvReadFailed?{envFileReadFailed:true}:{}}}__name(reloadEnvironment,"reloadEnvironment");export{SETTINGS_DIRECTORY_NAME,hasLoadedEnvironmentValues,getRelaunchEnvProvenance,preResolveHomeEnvOverrides,resetHomeEnvBootstrapForTesting,resetEnvironmentTrackingForTesting,isFileSourcedEnvKey,getHomeEnvFallbackVars,findEnvFiles,setUpCloudShellEnvironment,buildRuntimeEnvironment,loadEnvironment,reloadEnvironment};
|
|
3
|
+
import{captureEnvironmentBeforeLoad,publishPendingCompileCache,resetEnvironmentSnapshotForTesting}from"./chunk-PKK2D2W4.js";import{DEFAULT_EXCLUDED_ENV_VARS,HOME_ENV_BOOTSTRAP_KEYS,PROJECT_ENV_HARDCODED_EXCLUSIONS,VERIFY_PR_COORDINATE_ENV,isHardcodedProjectEnvExclusion,isLoaderEnvKey,isPrivateProvenanceEnvKey,reportRejectedLoaderKeys,resetLoaderKeyRejectionReportingForTesting}from"./chunk-N3AQAZ7D.js";import{PRIVATE_RELAUNCH_ENV_PROVENANCE}from"./chunk-E5T4R2PM.js";import{isWorkspaceTrusted}from"./chunk-YWK3E4WJ.js";import{require_main}from"./chunk-ZOTKZI2P.js";import{writeStderrLineSafe}from"./chunk-M4ECEHLX.js";import{Storage}from"./chunk-EPODBRBP.js";import{QWEN_DIR}from"./chunk-OKN3Z5C5.js";import{getErrorMessage}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var dotenv=__toESM(require_main(),1);import*as fs from"node:fs";import*as path from"node:path";import*as os from"node:os";var SETTINGS_DIRECTORY_NAME=QWEN_DIR;var RELOAD_EXCLUDED_KEYS=new Set([...PROJECT_ENV_HARDCODED_EXCLUSIONS,"LD_LIBRARY_PATH","DYLD_LIBRARY_PATH","ENV","PATH","HOME"]);var RELOAD_EXCLUDED_KEYS_CASEFOLDED=new Set([...RELOAD_EXCLUDED_KEYS].map(key=>key.toLowerCase()));function isReloadExcludedKey(key){return RELOAD_EXCLUDED_KEYS_CASEFOLDED.has(key.toLowerCase())||isHardcodedProjectEnvExclusion(key)}__name(isReloadExcludedKey,"isReloadExcludedKey");var dotEnvSourcedKeys=new Set;var settingsEnvSourcedKeys=new Set;var inheritedDotEnvKeys=new Set;var inheritedSettingsEnvKeys=new Set;var inheritedProvenance=process.env[PRIVATE_RELAUNCH_ENV_PROVENANCE];delete process.env[PRIVATE_RELAUNCH_ENV_PROVENANCE];if(inheritedProvenance){const sources=JSON.parse(inheritedProvenance);if(!sources||typeof sources!=="object"||!("dotEnv"in sources)||!("settingsEnv"in sources)||!Array.isArray(sources.dotEnv)||!Array.isArray(sources.settingsEnv)||!sources.dotEnv.every(key=>typeof key==="string")||!sources.settingsEnv.every(key=>typeof key==="string")){throw new Error("Invalid inherited environment provenance.")}for(const key of sources.dotEnv)inheritedDotEnvKeys.add(key);for(const key of sources.settingsEnv)inheritedSettingsEnvKeys.add(key);Object.assign(process.env,getRelaunchEnvProvenance())}var DOCUMENTED_MODEL_ENV_KEYS=["OPENAI_API_KEY","OPENAI_BASE_URL","OPENAI_MODEL","QWEN_MODEL","ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","ANTHROPIC_MODEL","GEMINI_API_KEY","GEMINI_MODEL","GOOGLE_API_KEY","GOOGLE_MODEL"];var requestTimeEnvKeys=new Set;function rememberRequestTimeEnvKeys(settings){requestTimeEnvKeys.clear();for(const key of DOCUMENTED_MODEL_ENV_KEYS)requestTimeEnvKeys.add(key);for(const models of Object.values(settings.modelProviders??{})){if(!Array.isArray(models))continue;for(const model of models){const envKey=model?.envKey;if(typeof envKey==="string"&&envKey&&!isHardcodedProjectEnvExclusion(envKey)&&!isLoaderEnvKey(envKey)){requestTimeEnvKeys.add(envKey)}}}}__name(rememberRequestTimeEnvKeys,"rememberRequestTimeEnvKeys");function hasLoadedEnvironmentValues(){for(const keys of[dotEnvSourcedKeys,settingsEnvSourcedKeys]){for(const key of keys){if(!requestTimeEnvKeys.has(key))return true}}return false}__name(hasLoadedEnvironmentValues,"hasLoadedEnvironmentValues");function getRelaunchEnvProvenance(){return{[PRIVATE_RELAUNCH_ENV_PROVENANCE]:JSON.stringify({dotEnv:[...new Set([...inheritedDotEnvKeys,...dotEnvSourcedKeys])],settingsEnv:[...new Set([...inheritedSettingsEnvKeys,...settingsEnvSourcedKeys])]})}}__name(getRelaunchEnvProvenance,"getRelaunchEnvProvenance");var lastReloadSnapshot=new Map;var lastReloadSnapshotSeeded=false;function getUserLevelEnvPaths(){const homeDir=os.homedir();const globalQwenDir=Storage.getGlobalQwenDir();const paths=new Set([path.normalize(path.join(homeDir,".env")),path.normalize(path.join(globalQwenDir,".env"))]);const legacyQwenEnv=path.normalize(path.join(homeDir,QWEN_DIR,".env"));paths.add(legacyQwenEnv);return paths}__name(getUserLevelEnvPaths,"getUserLevelEnvPaths");var homeEnvBootstrapped=false;function preResolveHomeEnvOverrides(){if(homeEnvBootstrapped){return}homeEnvBootstrapped=true;if(HOME_ENV_BOOTSTRAP_KEYS.every(key=>process.env[key])){return}const initialQwenHome=process.env["QWEN_HOME"];const initialQwenDir=Storage.getGlobalQwenDir();const candidates=[path.join(initialQwenDir,".env")];if(!initialQwenHome){candidates.push(path.join(path.dirname(initialQwenDir),".env"))}for(const candidate of candidates){readHomeEnvInto(candidate)}const discoveredQwenHome=process.env["QWEN_HOME"];if(discoveredQwenHome&&discoveredQwenHome!==initialQwenHome){const discoveredDir=Storage.getGlobalQwenDir();if(discoveredDir!==initialQwenDir){readHomeEnvInto(path.join(discoveredDir,".env"))}}}__name(preResolveHomeEnvOverrides,"preResolveHomeEnvOverrides");function readHomeEnvInto(file){if(!fs.existsSync(file)){return}try{const parsed=dotenv.parse(fs.readFileSync(file,"utf-8"));for(const key of HOME_ENV_BOOTSTRAP_KEYS){if(parsed[key]&&!Object.hasOwn(process.env,key)){process.env[key]=parsed[key]}}}catch(_e){}}__name(readHomeEnvInto,"readHomeEnvInto");function resetHomeEnvBootstrapForTesting(){homeEnvBootstrapped=false}__name(resetHomeEnvBootstrapForTesting,"resetHomeEnvBootstrapForTesting");function resetEnvironmentTrackingForTesting(){resetLoaderKeyRejectionReportingForTesting();resetEnvironmentSnapshotForTesting();dotEnvSourcedKeys.clear();settingsEnvSourcedKeys.clear();inheritedDotEnvKeys.clear();inheritedSettingsEnvKeys.clear();requestTimeEnvKeys.clear();delete process.env[PRIVATE_RELAUNCH_ENV_PROVENANCE];lastReloadSnapshot.clear();lastReloadSnapshotSeeded=false}__name(resetEnvironmentTrackingForTesting,"resetEnvironmentTrackingForTesting");function isFileSourcedEnvKey(key){const sources=[dotEnvSourcedKeys,settingsEnvSourcedKeys,inheritedDotEnvKeys,inheritedSettingsEnvKeys];if(sources.some(keys=>keys.has(key))){return true}if(process.platform!=="win32")return false;const lower=key.toLowerCase();for(const keys of sources){for(const tracked of keys){if(tracked.toLowerCase()===lower)return true}}return false}__name(isFileSourcedEnvKey,"isFileSourcedEnvKey");function getHomeEnvFallbackVars(onReadError){const globalQwenDir=Storage.getGlobalQwenDir();const candidates=[path.join(globalQwenDir,".env")];if(!process.env["QWEN_HOME"]){candidates.push(path.join(path.dirname(globalQwenDir),".env"))}const result={};for(const candidate of candidates){if(!fs.existsSync(candidate)){continue}try{const parsed=dotenv.parse(fs.readFileSync(candidate,"utf-8"));for(const key in parsed){if(Object.hasOwn(parsed,key)&&!Object.hasOwn(process.env,key)){result[key]??=parsed[key]}}}catch(e){onReadError?.(`Failed to read home .env candidate ${candidate}: ${getErrorMessage(e)}`)}}return result}__name(getHomeEnvFallbackVars,"getHomeEnvFallbackVars");function findEnvFiles(settings,startDir,userLevelPaths=getUserLevelEnvPaths(),workspaceTrusted){const homeDir=os.homedir();let realStartDir=path.resolve(startDir);try{realStartDir=fs.realpathSync(realStartDir)}catch{}const globalQwenDir=Storage.getGlobalQwenDir();const legacyQwenDir=path.normalize(path.join(homeDir,QWEN_DIR));const hasCustomConfigDir=path.normalize(globalQwenDir)!==legacyQwenDir;const found=[];const seen=new Set;const workspaceIsTrusted=workspaceTrusted??isWorkspaceTrusted(settings,void 0,realStartDir).isTrusted===true;const canUseEnvFile=__name(filePath=>{const normalized=path.normalize(filePath);if(userLevelPaths.has(normalized))return true;if(!workspaceIsTrusted)return false;const dirPath=path.dirname(normalized);const workspaceDir=path.basename(dirPath)===SETTINGS_DIRECTORY_NAME?path.dirname(dirPath):dirPath;if(workspaceDir===realStartDir)return true;return isWorkspaceTrusted(settings,void 0,workspaceDir).isTrusted!==false},"canUseEnvFile");const pushCandidate=__name(filePath=>{const normalized=path.normalize(filePath);if(!seen.has(normalized)&&fs.existsSync(filePath)&&canUseEnvFile(filePath)){seen.add(normalized);found.push(filePath);return true}return false},"pushCandidate");const pushHomeCandidates=__name(()=>{const candidates=[path.join(globalQwenDir,".env")];if(hasCustomConfigDir){candidates.push(path.join(legacyQwenDir,".env"))}candidates.push(path.join(homeDir,".env"));for(const candidate of candidates){pushCandidate(candidate)}},"pushHomeCandidates");if(path.resolve(startDir)===path.resolve(homeDir)){pushHomeCandidates();return found}let currentDir=realStartDir;let visitedHomeDir=false;while(true){if(currentDir===homeDir){visitedHomeDir=true;pushHomeCandidates();return found}else{const geminiEnvPath=path.join(currentDir,QWEN_DIR,".env");if(pushCandidate(geminiEnvPath)){pushHomeCandidates();return found}const envPath=path.join(currentDir,".env");if(pushCandidate(envPath)){pushHomeCandidates();return found}}const parentDir=path.dirname(currentDir);if(parentDir===currentDir||!parentDir){if(!visitedHomeDir){pushHomeCandidates()}return found}currentDir=parentDir}}__name(findEnvFiles,"findEnvFiles");function setUpCloudShellEnvironment(envFilePath){if(envFilePath&&fs.existsSync(envFilePath)){const envFileContent=fs.readFileSync(envFilePath);const parsedEnv=dotenv.parse(envFileContent);if(parsedEnv["GOOGLE_CLOUD_PROJECT"]){process.env["GOOGLE_CLOUD_PROJECT"]=parsedEnv["GOOGLE_CLOUD_PROJECT"]}else{process.env["GOOGLE_CLOUD_PROJECT"]="cloudshell-gca"}}else{process.env["GOOGLE_CLOUD_PROJECT"]="cloudshell-gca"}}__name(setUpCloudShellEnvironment,"setUpCloudShellEnvironment");function setUpCloudShellEnvironmentInEnv(env,envFiles){for(const envFile of envFiles){if(envFile.parsedEnv["GOOGLE_CLOUD_PROJECT"]){env["GOOGLE_CLOUD_PROJECT"]=envFile.parsedEnv["GOOGLE_CLOUD_PROJECT"];return}}env["GOOGLE_CLOUD_PROJECT"]="cloudshell-gca"}__name(setUpCloudShellEnvironmentInEnv,"setUpCloudShellEnvironmentInEnv");function parseEnvFiles(envFilePaths,userLevelPaths){const files=[];const readFailures=[];for(const envFilePath of envFilePaths){try{const envFileContent=fs.readFileSync(envFilePath,"utf-8");const parsedEnv=dotenv.parse(envFileContent);const normalizedEnvFilePath=path.normalize(envFilePath);const isHomeScopedEnvFile=userLevelPaths.has(normalizedEnvFilePath);const isQwenScopedEnvFile=isHomeScopedEnvFile||path.basename(path.dirname(normalizedEnvFilePath))===QWEN_DIR;files.push({path:envFilePath,parsedEnv,isHomeScopedEnvFile,isQwenScopedEnvFile})}catch(err){readFailures.push({path:envFilePath,error:getErrorMessage(err)})}}return{files,readFailed:readFailures.length>0,readFailures}}__name(parseEnvFiles,"parseEnvFiles");function canApplyParsedEnvKey(envFile,key,excludedVars,options={}){if(!Object.hasOwn(envFile.parsedEnv,key))return false;if(isLoaderEnvKey(key))return false;if(isPrivateProvenanceEnvKey(key))return false;if(options.reload&&isReloadExcludedKey(key))return false;if(!envFile.isHomeScopedEnvFile&&isHardcodedProjectEnvExclusion(key)){return false}return envFile.isQwenScopedEnvFile||!excludedVars.includes(key)}__name(canApplyParsedEnvKey,"canApplyParsedEnvKey");function isEffectivelyUnset(env,key){const existingValue=env[key];return!Object.hasOwn(env,key)||existingValue===""}__name(isEffectivelyUnset,"isEffectivelyUnset");function setRuntimeEnvIfUnset(env,key,value){if(isEffectivelyUnset(env,key)){env[key]=value}}__name(setRuntimeEnvIfUnset,"setRuntimeEnvIfUnset");function reportRejectedSettingsEnv(env,startDir){const source=`settings.env (${startDir})`;reportRejectedLoaderKeys(source,Object.keys(env));if(Object.entries(env).some(([key,value])=>key.toUpperCase()==="QWEN_AGENT_EXECUTION_BACKEND"&&typeof value==="string"&&value.trim()!=="")){writeStderrLineSafe(`qwen: ${source} cannot set QWEN_AGENT_EXECUTION_BACKEND; ignored. Export it in the launch environment instead.`)}for(const[setting,key]of Object.entries(VERIFY_PR_COORDINATE_ENV)){const entry=Object.entries(env).find(([candidate,value])=>candidate.toUpperCase()===key&&typeof value==="string"&&value.trim()!=="");if(!entry)continue;writeStderrLineSafe(`qwen: ${source} cannot set ${entry[0]}; ignored. Set verifyPr.${setting} at user scope in settings.json, or export it in the launch environment.`)}}__name(reportRejectedSettingsEnv,"reportRejectedSettingsEnv");function buildRuntimeEnvironment(settings,startDir=process.cwd(),baseEnv=process.env,workspaceTrusted){const userLevelPaths=getUserLevelEnvPaths();const envFilePaths=findEnvFiles(settings,startDir,userLevelPaths,workspaceTrusted);const parsedEnvFiles=parseEnvFiles(envFilePaths,userLevelPaths);const effectiveEnv={...baseEnv};if(baseEnv["CLOUD_SHELL"]==="true"){setUpCloudShellEnvironmentInEnv(effectiveEnv,parsedEnvFiles.files)}for(const envFile of parsedEnvFiles.files){const excludedVars=settings?.advanced?.excludedEnvVars||DEFAULT_EXCLUDED_ENV_VARS;for(const key in envFile.parsedEnv){if(!canApplyParsedEnvKey(envFile,key,excludedVars,{reload:true})){continue}setRuntimeEnvIfUnset(effectiveEnv,key,envFile.parsedEnv[key])}reportRejectedLoaderKeys(`.env file ${envFile.path}`,Object.keys(envFile.parsedEnv))}if(settings.env){const excludedVars=settings?.advanced?.excludedEnvVars||DEFAULT_EXCLUDED_ENV_VARS;for(const[key,value]of Object.entries(settings.env)){if(isLoaderEnvKey(key))continue;if(isReloadExcludedKey(key))continue;if(isHardcodedProjectEnvExclusion(key))continue;if(excludedVars.includes(key))continue;if(typeof value!=="string")continue;setRuntimeEnvIfUnset(effectiveEnv,key,value)}reportRejectedSettingsEnv(settings.env,startDir)}const overlayKeys=Object.keys(effectiveEnv).filter(key=>effectiveEnv[key]!==baseEnv[key]).sort();return{effectiveEnv:Object.freeze({...effectiveEnv}),overlayKeys:Object.freeze(overlayKeys),envFilePaths:Object.freeze([...envFilePaths]),envFileReadFailed:parsedEnvFiles.readFailed,envFileReadFailures:Object.freeze([...parsedEnvFiles.readFailures])}}__name(buildRuntimeEnvironment,"buildRuntimeEnvironment");function loadEnvironment(settings,startDir=process.cwd()){captureEnvironmentBeforeLoad();rememberRequestTimeEnvKeys(settings);const userLevelPaths=getUserLevelEnvPaths();const envFilePaths=findEnvFiles(settings,startDir,userLevelPaths);const parsedEnvFiles=parseEnvFiles(envFilePaths,userLevelPaths);if(process.env["CLOUD_SHELL"]==="true"){setUpCloudShellEnvironmentInEnv(process.env,parsedEnvFiles.files)}for(const envFile of parsedEnvFiles.files){const excludedVars=settings?.advanced?.excludedEnvVars||DEFAULT_EXCLUDED_ENV_VARS;for(const key in envFile.parsedEnv){if(!canApplyParsedEnvKey(envFile,key,excludedVars))continue;const existingValue=process.env[key];const isEffectivelyUnset2=!Object.hasOwn(process.env,key)||existingValue==="";if(isEffectivelyUnset2){process.env[key]=envFile.parsedEnv[key];dotEnvSourcedKeys.add(key)}if(!lastReloadSnapshotSeeded&&!lastReloadSnapshot.has(key)){lastReloadSnapshot.set(key,envFile.parsedEnv[key])}}reportRejectedLoaderKeys(`.env file ${envFile.path}`,Object.keys(envFile.parsedEnv))}if(settings.env){for(const[key,value]of Object.entries(settings.env)){if(isLoaderEnvKey(key)){continue}if(isReloadExcludedKey(key)){continue}if(isHardcodedProjectEnvExclusion(key)){continue}const existingValue=process.env[key];const isEffectivelyUnset2=!Object.hasOwn(process.env,key)||existingValue==="";if(isEffectivelyUnset2&&typeof value==="string"){process.env[key]=value;settingsEnvSourcedKeys.add(key)}if(!lastReloadSnapshotSeeded&&typeof value==="string"&&!lastReloadSnapshot.has(key)){lastReloadSnapshot.set(key,value)}}reportRejectedSettingsEnv(settings.env,startDir)}lastReloadSnapshotSeeded=true;Object.assign(process.env,getRelaunchEnvProvenance());publishPendingCompileCache()}__name(loadEnvironment,"loadEnvironment");function reloadEnvironment(settings,workspaceCwd,workspaceTrusted,options={}){const userLevelPaths=getUserLevelEnvPaths();const envFilePaths=findEnvFiles(settings,workspaceCwd,userLevelPaths,workspaceTrusted);const parsedEnvFiles=parseEnvFiles(envFilePaths,userLevelPaths);if(parsedEnvFiles.readFailed&&options.failClosedOnEnvFileReadError){return{updatedKeys:[],removedKeys:[],envFileReadFailed:true}}if(process.env["CLOUD_SHELL"]==="true"){setUpCloudShellEnvironmentInEnv(process.env,parsedEnvFiles.files)}const dotEnvReadFailed=parsedEnvFiles.readFailed;const newDotEnvKeys=new Map;const newSettingsEnvKeys=new Map;for(const envFile of parsedEnvFiles.files){const excludedVars=settings?.advanced?.excludedEnvVars||DEFAULT_EXCLUDED_ENV_VARS;for(const key in envFile.parsedEnv){if(!canApplyParsedEnvKey(envFile,key,excludedVars,{reload:true})){continue}if(!newDotEnvKeys.has(key)){newDotEnvKeys.set(key,envFile.parsedEnv[key])}}reportRejectedLoaderKeys(`.env file ${envFile.path}`,Object.keys(envFile.parsedEnv))}if(settings.env){for(const[key,value]of Object.entries(settings.env)){if(isLoaderEnvKey(key))continue;if(isReloadExcludedKey(key))continue;if(isHardcodedProjectEnvExclusion(key))continue;if(typeof value!=="string")continue;const dotEnvValue=newDotEnvKeys.get(key);if(dotEnvValue!==void 0&&dotEnvValue!=="")continue;if(dotEnvReadFailed&&lastReloadSnapshot.has(key))continue;newSettingsEnvKeys.set(key,value)}reportRejectedSettingsEnv(settings.env,workspaceCwd)}const allNewKeys=new Set([...newDotEnvKeys.keys(),...newSettingsEnvKeys.keys()]);const updatedKeys=[];const removedKeys=[];if(!dotEnvReadFailed){const previouslyKnown=new Set([...lastReloadSnapshot.keys(),...dotEnvSourcedKeys,...settingsEnvSourcedKeys]);for(const key of previouslyKnown){if(!allNewKeys.has(key)&&!isReloadExcludedKey(key)){delete process.env[key];inheritedDotEnvKeys.delete(key);inheritedSettingsEnvKeys.delete(key);removedKeys.push(key)}}}for(const[key,value]of newDotEnvKeys){if(value===""&&newSettingsEnvKeys.has(key))continue;if(process.env[key]!==value){updatedKeys.push(key)}process.env[key]=value}for(const[key,value]of newSettingsEnvKeys){if(process.env[key]!==value){updatedKeys.push(key)}process.env[key]=value}if(!dotEnvReadFailed){for(const sources of[dotEnvSourcedKeys,settingsEnvSourcedKeys]){for(const key of sources){if(!isReloadExcludedKey(key))sources.delete(key)}}lastReloadSnapshot.clear();for(const[key,value]of newDotEnvKeys){lastReloadSnapshot.set(key,value)}for(const[key,value]of newSettingsEnvKeys){lastReloadSnapshot.set(key,value)}}for(const key of newDotEnvKeys.keys()){dotEnvSourcedKeys.add(key)}for(const key of newSettingsEnvKeys.keys()){settingsEnvSourcedKeys.add(key)}Object.assign(process.env,getRelaunchEnvProvenance());return{updatedKeys,removedKeys,...dotEnvReadFailed?{envFileReadFailed:true}:{}}}__name(reloadEnvironment,"reloadEnvironment");export{SETTINGS_DIRECTORY_NAME,hasLoadedEnvironmentValues,getRelaunchEnvProvenance,preResolveHomeEnvOverrides,resetHomeEnvBootstrapForTesting,resetEnvironmentTrackingForTesting,isFileSourcedEnvKey,getHomeEnvFallbackVars,findEnvFiles,setUpCloudShellEnvironment,buildRuntimeEnvironment,loadEnvironment,reloadEnvironment};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2025 Qwen Team
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{runExitCleanup}from"./chunk-
|
|
3
|
+
import{runExitCleanup}from"./chunk-3ICJI5KW.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var RELAUNCH_EXIT_CODE=42;var UPDATE_RELAUNCH_EXIT_CODE=43;var UPDATE_COMPLETE_EXIT_CODE=44;var SKIP_UPDATE_CHECK_ENV_VAR="QWEN_CODE_SKIP_UPDATE_CHECK_ONCE";var CUSTOM_SANDBOX_IMAGE_ENV_VAR="QWEN_CODE_CUSTOM_SANDBOX_IMAGE";var HOST_UPDATE_RELAUNCH_ENV_VAR="QWEN_CODE_HOST_UPDATE_RELAUNCH";var UPDATE_ON_EXIT_MESSAGE="qwen-code:update-on-exit";var inProcessUpdateRelaunch;var supervisedInProcess=false;var updateOnExitRequested=false;var updatingOnExit=false;function superviseInProcess(onUpdateRelaunch){supervisedInProcess=true;inProcessUpdateRelaunch=onUpdateRelaunch}__name(superviseInProcess,"superviseInProcess");function getRelaunchExecArgv(){const needsExposeGc=typeof globalThis.gc==="function"&&!process.execArgv.includes("--expose-gc");return needsExposeGc?[...process.execArgv,"--expose-gc"]:[...process.execArgv]}__name(getRelaunchExecArgv,"getRelaunchExecArgv");async function relaunchApp(){await runExitCleanup();const proc=process;if(supervisedInProcess&&proc.execve){proc.execve(process.execPath,[process.execPath,...getRelaunchExecArgv(),...process.argv.slice(1)])}process.exit(RELAUNCH_EXIT_CODE)}__name(relaunchApp,"relaunchApp");async function exitCleanly(code){if(updatingOnExit)return new Promise(()=>{});if(code===0&&updateOnExitRequested&&inProcessUpdateRelaunch){updateOnExitRequested=false;updatingOnExit=true;try{code=await inProcessUpdateRelaunch(false)}catch{code=1}}process.exit(code)}__name(exitCleanly,"exitCleanly");async function relaunchForUpdate(){await runExitCleanup();if(inProcessUpdateRelaunch){process.exit(await inProcessUpdateRelaunch(true))}process.exit(UPDATE_RELAUNCH_EXIT_CODE)}__name(relaunchForUpdate,"relaunchForUpdate");function requestUpdateOnExit(){if(inProcessUpdateRelaunch){updateOnExitRequested=true;return true}if(!process.send)return false;try{process.send({type:UPDATE_ON_EXIT_MESSAGE});return true}catch{return false}}__name(requestUpdateOnExit,"requestUpdateOnExit");export{RELAUNCH_EXIT_CODE,UPDATE_RELAUNCH_EXIT_CODE,UPDATE_COMPLETE_EXIT_CODE,SKIP_UPDATE_CHECK_ENV_VAR,CUSTOM_SANDBOX_IMAGE_ENV_VAR,HOST_UPDATE_RELAUNCH_ENV_VAR,UPDATE_ON_EXIT_MESSAGE,superviseInProcess,getRelaunchExecArgv,relaunchApp,exitCleanly,relaunchForUpdate,requestUpdateOnExit};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2025 Google LLC
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{SessionOrganizationService}from"./chunk-
|
|
3
|
+
import{SessionOrganizationService}from"./chunk-T3CQ72HC.js";import{writeStderrLine}from"./chunk-M4ECEHLX.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();function createSessionOrganizationService(workspaceCwd){return new SessionOrganizationService(workspaceCwd,message=>{writeStderrLine(`qwen serve: session-org: ${message}`)})}__name(createSessionOrganizationService,"createSessionOrganizationService");export{createSessionOrganizationService};
|
|
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{SessionService,TURN_INTERRUPTION_HISTORY_TAIL_COUNT,buildSessionHistoryFromConversation,detectTurnInterruption,effectiveHistoryEnd}from"./chunk-
|
|
3
|
+
import{SessionService,TURN_INTERRUPTION_HISTORY_TAIL_COUNT,buildSessionHistoryFromConversation,detectTurnInterruption,effectiveHistoryEnd}from"./chunk-T3CQ72HC.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{closeSync as closeSync2,openSync as openSync2,readSync as readSync2,statSync as statSync2}from"node:fs";init_esbuild_shims();import{appendFileSync,closeSync,mkdirSync,openSync,readFileSync,readSync,statSync}from"node:fs";import*as path from"node:path";function isPromptLedgerTerminalRecord(record){return"terminal"in record}__name(isPromptLedgerTerminalRecord,"isPromptLedgerTerminalRecord");function appendPromptLedgerRecord(filePath,record){mkdirSync(path.dirname(filePath),{recursive:true});sealTornTailSync(filePath);appendFileSync(filePath,`${JSON.stringify(record)}
|
|
4
4
|
`,{encoding:"utf8",mode:384})}__name(appendPromptLedgerRecord,"appendPromptLedgerRecord");function sealTornTailSync(filePath){let stats;try{stats=statSync(filePath)}catch(error){if(error.code==="ENOENT")return;throw error}if(stats.size===0)return;const fd=openSync(filePath,"r");try{const lastByte=Buffer.alloc(1);const bytesRead=readSync(fd,lastByte,0,1,stats.size-1);if(bytesRead===1&&lastByte[0]!==10){appendFileSync(filePath,"\n","utf8")}}finally{closeSync(fd)}}__name(sealTornTailSync,"sealTornTailSync");function coercePromptLedgerRecord(value){if(typeof value!=="object"||value===null)return void 0;const record=value;const promptId=record["promptId"];const at=record["at"];if(record["v"]!==1||typeof promptId!=="string")return void 0;if(typeof at!=="number"||!Number.isFinite(at))return void 0;if(record["state"]==="in_flight"){const tailUuid=record["tailUuid"];return{v:1,promptId,state:"in_flight",...typeof tailUuid==="string"&&tailUuid.length>0?{tailUuid}:{},at}}const terminal=record["terminal"];if(terminal!=="completed"&&terminal!=="cancelled"&&terminal!=="error"&&terminal!=="interrupted"){return void 0}const code=record["code"];const stopReason=record["stopReason"];return{v:1,promptId,terminal,...typeof code==="string"?{code}:{},...typeof stopReason==="string"?{stopReason}:{},at}}__name(coercePromptLedgerRecord,"coercePromptLedgerRecord");function readPromptLedgerRecords(filePath,options){let contents;let dropFirstLine=false;try{const tailBytes=options?.tailBytes;if(tailBytes===void 0){contents=readFileSync(filePath,"utf8")}else{const size=statSync(filePath).size;if(size<=tailBytes){contents=readFileSync(filePath,"utf8")}else{const fd=openSync(filePath,"r");try{const buffer=Buffer.alloc(tailBytes);const bytesRead=readSync(fd,buffer,0,tailBytes,size-tailBytes);contents=buffer.subarray(0,bytesRead).toString("utf8");dropFirstLine=true}finally{closeSync(fd)}}}}catch(error){if(error.code==="ENOENT")return[];throw error}const records=[];const lines=contents.split("\n");for(let i=dropFirstLine?1:0;i<lines.length;i++){const line=lines[i];if(line===void 0||line.length===0)continue;let parsed;try{parsed=JSON.parse(line)}catch{continue}const record=coercePromptLedgerRecord(parsed);if(record!==void 0)records.push(record)}return records}__name(readPromptLedgerRecords,"readPromptLedgerRecords");function danglingInFlightPromptIds(records){const latest=new Map;for(const record of records){latest.set(record.promptId,record)}const dangling=[];for(const[promptId,record]of latest){if(!isPromptLedgerTerminalRecord(record))dangling.push(promptId)}return dangling}__name(danglingInFlightPromptIds,"danglingInFlightPromptIds");var PROMPT_TERMINALS_RESPONSE_LIMIT=64;function recentPromptTerminalRecords(records){const terminals=records.filter(isPromptLedgerTerminalRecord);return terminals.length<=PROMPT_TERMINALS_RESPONSE_LIMIT?terminals:terminals.slice(-PROMPT_TERMINALS_RESPONSE_LIMIT)}__name(recentPromptTerminalRecords,"recentPromptTerminalRecords");function createPromptLedgerSink(workspaceCwd,sessionRuntimeBaseDir){const sessionService=new SessionService(workspaceCwd,{runtimeBaseDir:sessionRuntimeBaseDir});return{appendSync(sessionId,record){appendPromptLedgerRecord(sessionService.getPromptLedgerPath(sessionId),record)},transcriptTailUuid(sessionId){return readTranscriptTailUuid(sessionService.getSessionTranscriptPath(sessionId))}}}__name(createPromptLedgerSink,"createPromptLedgerSink");var TRANSCRIPT_TAIL_BYTES=64*1024;function readTranscriptTailUuid(transcriptPath){let contents;try{const size=statSync2(transcriptPath).size;if(size===0)return void 0;const windowBytes=Math.min(size,TRANSCRIPT_TAIL_BYTES);const buffer=Buffer.alloc(windowBytes);const fd=openSync2(transcriptPath,"r");try{readSync2(fd,buffer,0,windowBytes,size-windowBytes)}finally{closeSync2(fd)}contents=buffer.toString("utf8")}catch{return void 0}const lines=contents.split("\n");for(let i=lines.length-1;i>=0;i--){const line=lines[i];if(line===void 0||line.length===0)continue;try{const uuid=JSON.parse(line).uuid;return typeof uuid==="string"&&uuid.length>0?uuid:void 0}catch{return void 0}}return void 0}__name(readTranscriptTailUuid,"readTranscriptTailUuid");async function reconcileDanglingPromptTerminals(sessionService,sessionId){const ledgerPath=sessionService.getPromptLedgerPath(sessionId);let records;try{records=readPromptLedgerRecords(ledgerPath)}catch{return}const snapshotLength=records.length;const dangling=danglingInFlightPromptIds(records);if(dangling.length===0)return;if(dangling.length>1)return;const target=dangling[0];if(target===void 0)return;const settledPromptIds=new Set(records.filter(isPromptLedgerTerminalRecord).map(r=>r.promptId));let targetAdmission;for(const record2 of records){if(!isPromptLedgerTerminalRecord(record2)&&!settledPromptIds.has(record2.promptId)){targetAdmission=record2}}if(targetAdmission===void 0||targetAdmission.promptId!==target){return}let resumed;try{resumed=await sessionService.loadSession(sessionId)}catch{return}if(resumed===void 0)return;const messages=resumed.conversation.messages;const admissionMarker=targetAdmission.tailUuid;let markerIndex=-1;if(admissionMarker!==void 0){markerIndex=messages.findIndex(record2=>record2.uuid===admissionMarker);let wroteAfterMarker=false;for(let i=markerIndex+1;i<messages.length;i++){const record2=messages[i];if(record2===void 0||record2.type==="system")continue;if(!record2.message||record2.subtype==="realtime_message")continue;wroteAfterMarker=true;break}if(markerIndex<0||!wroteAfterMarker)return}let lastVisibleWriteMs=NaN;let lastVisibleNonSystem;let compressedAfterAdmission=false;let localCommandCompleted=false;const admissionAt=targetAdmission.at;const isAfterAdmission=__name((idx,writeMs)=>admissionMarker!==void 0?idx>markerIndex:Number.isFinite(writeMs)&&writeMs>=admissionAt,"isAfterAdmission");for(let idx=0;idx<messages.length;idx++){const record2=messages[idx];const writeMs=Date.parse(record2.timestamp);if(record2.type==="system"){if(isCompressionResetRecord(record2)){if(isAfterAdmission(idx,writeMs))compressedAfterAdmission=true}else if(!localCommandCompleted&&isAfterAdmission(idx,writeMs)&&isLocalSlashCommandResult(record2,lastVisibleNonSystem)){localCommandCompleted=true}continue}if(!record2.message||record2.subtype==="realtime_message")continue;if(record2.provenance==="system")continue;if(record2.subtype==="agent_mention"||record2.subtype==="agent_message"){continue}if(Number.isFinite(writeMs))lastVisibleWriteMs=writeMs;lastVisibleNonSystem=record2}let lastOtherTerminalAt=0;for(const record2 of records){if(isPromptLedgerTerminalRecord(record2)&&record2.promptId!==target){if(record2.code==="prompt_deadline_exceeded")return;lastOtherTerminalAt=Math.max(lastOtherTerminalAt,record2.at)}}if(compressedAfterAdmission||!Number.isFinite(lastVisibleWriteMs)||lastVisibleWriteMs<=targetAdmission.at||lastVisibleWriteMs<=lastOtherTerminalAt){return}const{apiHistory,completedToolCallIds}=buildSessionHistoryFromConversation(resumed.conversation);const classifiableEnd=effectiveHistoryEnd(apiHistory);const historyTail=apiHistory.slice(Math.max(0,classifiableEnd-TURN_INTERRUPTION_HISTORY_TAIL_COUNT),classifiableEnd);const verdict=detectTurnInterruption(historyTail,completedToolCallIds);const interrupted=verdict.kind!=="none"||tailHoldsAnyFunctionCall(historyTail);const lastVisibleNonSystemType=lastVisibleNonSystem?.type;if(!interrupted&&lastVisibleNonSystemType!=="assistant"&&lastVisibleNonSystemType!=="tool_result"&&!localCommandCompleted){return}let refetch;try{refetch=readPromptLedgerRecords(ledgerPath)}catch{return}if(refetch.length!==snapshotLength)return;const record=interrupted?{v:1,promptId:target,terminal:"interrupted",code:"daemon_lost",at:Date.now()}:{v:1,promptId:target,terminal:"completed",stopReason:"reconstructed_from_transcript",at:Date.now()};try{appendPromptLedgerRecord(ledgerPath,record)}catch{}}__name(reconcileDanglingPromptTerminals,"reconcileDanglingPromptTerminals");function isCompressionResetRecord(record){if(record.type!=="system"||record.subtype!=="chat_compression"){return false}return Boolean(record.systemPayload?.compressedHistory)}__name(isCompressionResetRecord,"isCompressionResetRecord");function isLocalSlashCommandResult(record,previous){if(record.subtype!=="slash_command")return false;const payload=record.systemPayload;const items=payload?.outputHistoryItems;const parts=previous?.message?.parts;const first=parts?.[0];return payload?.phase==="result"&&payload.sentToModel!==true&&Array.isArray(items)&&items.length>0&&items.every(item=>item["type"]==="assistant")&&previous?.type==="user"&&previous.subtype===void 0&&previous.message?.role==="user"&&parts?.length===1&&first!==void 0&&typeof first.text==="string"&&Object.keys(first).length===1&&first.text===payload.rawCommand}__name(isLocalSlashCommandResult,"isLocalSlashCommandResult");function tailHoldsAnyFunctionCall(history){const last=history[history.length-1];if(last?.role!=="model")return false;return(last.parts??[]).some(part=>part.functionCall!==void 0)}__name(tailHoldsAnyFunctionCall,"tailHoldsAnyFunctionCall");var RECENT_TERMINALS_TAIL_BYTES=256*1024;function readRecentPromptTerminals(sessionService,sessionId){try{const terminals=recentPromptTerminalRecords(readPromptLedgerRecords(sessionService.getPromptLedgerPath(sessionId),{tailBytes:RECENT_TERMINALS_TAIL_BYTES}));return terminals.length>0?terminals:void 0}catch{return void 0}}__name(readRecentPromptTerminals,"readRecentPromptTerminals");function withPromptTerminals(session,terminals){if(terminals===void 0||terminals.length===0)return session;return{...session,promptTerminals:[...terminals]}}__name(withPromptTerminals,"withPromptTerminals");export{createPromptLedgerSink,readTranscriptTailUuid,reconcileDanglingPromptTerminals,readRecentPromptTerminals,withPromptTerminals};
|
|
5
5
|
/**
|
|
6
6
|
* @license
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{captureRuntimeFileVersion,writeRuntimeFile}from"./chunk-Q6QS5JTK.js";import{checkTeamMemorySecrets,checkWorkspaceTeamMemorySecrets}from"./chunk-UJP2MPBI.js";import{buildWorkspaceArtifactCandidate,formatRecordArtifactReminder}from"./chunk-AKWYMQKU.js";import{CommitAttributionService,FileEncoding,checkPriorRead,createPatchSmart,detectLineEnding,getDiffStat,needsUtf8Bom}from"./chunk-Z5XENA4A.js";import{backgroundFixHolding}from"./chunk-YVD4O5ZB.js";import{getCurrentAgentId}from"./chunk-YZFNBUKG.js";import{FileOperationEvent,getLanguageFromFilePath,logFileOperation}from"./chunk-ZWPSBU7K.js";import{isAnyAutoMemPath,isTeamAutoMemPath}from"./chunk-KVA6DHHF.js";import{fileExists,getSpecificMimeType}from"./chunk-Y6HHV4LC.js";import{BaseDeclarativeTool,BaseToolInvocation,StructuredToolError}from"./chunk-O5EKX7LG.js";import{ToolDisplayNames,ToolNames}from"./chunk-SBZFGYYS.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{makeRelative,shortenPath,unescapePath}from"./chunk-OKN3Z5C5.js";import{getErrorMessage,isNodeError}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import fs from"node:fs";import path from"node:path";var debugLogger=createDebugLogger("WRITE_FILE");var WriteFileToolInvocation=class extends BaseToolInvocation{constructor(config,params){super(params);this.config=config}static{__name(this,"WriteFileToolInvocation")}toolLocations(){return[{path:this.params.file_path}]}getDescription(){const relativePath=makeRelative(this.params.file_path,this.config.getTargetDir());return`Writing to ${shortenPath(relativePath)}`}requiresUserInteraction(){return backgroundFixHolding(this.params.file_path,getCurrentAgentId())!==void 0}async getDefaultPermission(){if(this.config.getFileSystemService().textFileIo)return"ask";const projectRoot=this.config.getProjectRoot();const filePath=path.resolve(this.params.file_path);if(isTeamAutoMemPath(filePath,projectRoot)){return"ask"}if(isAnyAutoMemPath(filePath,projectRoot)){return"allow"}return"ask"}async getConfirmationDetails(_abortSignal){let originalContent="";let observation;try{observation=await this.config.getFileSystemService().textFileIo?.inspect(this.params.file_path,_abortSignal)}catch(error){if(isNodeError(error)&&error.code==="EISDIR")throw new StructuredToolError(`Path is a directory, not a file: ${this.params.file_path}`,"target_is_directory");throw error}let fileExists2=observation?observation.kind==="file":await fileExists(this.params.file_path);if(!this.config.getFileReadCacheDisabled()){const decision=await checkPriorRead(this.config.getFileReadCache(),this.params.file_path,"overwriting");if(!decision.ok){throw new StructuredToolError(decision.rawMessage,decision.type)}}if(fileExists2){try{const{content}=observation?.kind==="file"?observation.response:await this.config.getFileSystemService().readTextFile({path:this.params.file_path});originalContent=content}catch(err){if(isNodeError(err)&&err.code==="ENOENT"){fileExists2=false}else{throw new Error(`Error reading existing file for confirmation: ${getErrorMessage(err)}`)}}}if(fileExists2&&!this.config.getFileReadCacheDisabled()){const postDecision=await checkPriorRead(this.config.getFileReadCache(),this.params.file_path,"overwriting",{expectExisting:true});if(!postDecision.ok){debugLogger.warn("post-read TOCTOU rejection (confirmation)",{path:this.params.file_path,reason:postDecision.type});throw new StructuredToolError(postDecision.rawMessage,postDecision.type)}}const relativePath=makeRelative(this.params.file_path,this.config.getTargetDir());const fileName=path.basename(this.params.file_path);const fileDiff=createPatchSmart(fileName,originalContent,this.params.content,"Current","Proposed");const confirmationDetails={type:"edit",title:`Confirm Write: ${shortenPath(relativePath)}`,fileName,filePath:this.params.file_path,fileDiff,originalContent,newContent:this.params.content,onConfirm:__name(async outcome=>{if(outcome==="proceed_always"){this.config.setApprovalMode("auto-edit")}},"onConfirm")};return confirmationDetails}async execute(abortSignal){const io=this.config.getFileSystemService().textFileIo;if(!io)return this.executeObserved(abortSignal);try{return await io.withMutation(this.params.file_path,abortSignal,mutation=>this.executeObserved(abortSignal,mutation))}catch(error){if(abortSignal.aborted)throw error;return this.writeFailure(error)}}async executeObserved(abortSignal,mutation){const{file_path,content,ai_proposed_content,modified_by_user}=this.params;let sandboxFileVersion;try{sandboxFileVersion=captureRuntimeFileVersion(this.config,file_path)}catch(error){const message=`${file_path}: ${getErrorMessage(error)}`;return{llmContent:message,returnDisplay:message,error:{message,type:isNodeError(error)&&error.code==="EISDIR"?"target_is_directory":"file_write_failure"}}}let fileExists2=mutation?mutation.original.kind==="file":await fileExists(file_path);let originalContent="";let useBOM=false;let detectedEncoding;let detectedLineEnding;const dirName=path.dirname(file_path);const teamMemoryError=(this.config.getFileSystemService().textFileIo?checkWorkspaceTeamMemorySecrets:checkTeamMemorySecrets)(file_path,content,this.config.getProjectRoot());if(teamMemoryError){return{llmContent:`[ERROR: ${teamMemoryError}]`,returnDisplay:teamMemoryError,error:{message:teamMemoryError,type:"invalid_tool_params"}}}if(!this.config.getFileReadCacheDisabled()){const decision=await checkPriorRead(this.config.getFileReadCache(),file_path,"overwriting");if(!decision.ok){return{llmContent:decision.rawMessage,returnDisplay:`Error: ${decision.displayMessage}`,error:{message:decision.rawMessage,type:decision.type}}}}if(fileExists2){try{const fileInfo=mutation?.original.kind==="file"?mutation.original.response:await this.config.getFileSystemService().readTextFile({path:file_path});if(fileInfo._meta?.bom!==void 0){useBOM=fileInfo._meta.bom}else{useBOM=fileInfo.content.length>0&&fileInfo.content.codePointAt(0)===65279}detectedEncoding=fileInfo._meta?.encoding||"utf-8";detectedLineEnding=detectLineEnding(fileInfo.content);originalContent=fileInfo.content;fileExists2=true}catch(err){if(isNodeError(err)&&err.code==="ENOENT"){fileExists2=false}else{const error={message:getErrorMessage(err),code:isNodeError(err)?err.code:void 0};const errorMsg=error.code?`Error checking existing file '${file_path}': ${error.message} (${error.code})`:`Error checking existing file: ${error.message}`;return{llmContent:errorMsg,returnDisplay:errorMsg,error:{message:errorMsg,type:"file_write_failure"}}}}}if(fileExists2&&!this.config.getFileReadCacheDisabled()){const postDecision=await checkPriorRead(this.config.getFileReadCache(),file_path,"overwriting",{expectExisting:true});if(!postDecision.ok){debugLogger.warn("post-read TOCTOU rejection (execute)",{path:file_path,reason:postDecision.type});return{llmContent:postDecision.rawMessage,returnDisplay:`Error: ${postDecision.displayMessage}`,error:{message:postDecision.rawMessage,type:postDecision.type}}}}if(!fileExists2){const userEncoding=this.config.getDefaultFileEncoding();if(userEncoding===FileEncoding.UTF8_BOM){useBOM=true}else if(userEncoding===void 0){useBOM=needsUtf8Bom(file_path)}detectedEncoding=void 0}try{await this.config.getFileHistoryService().trackEdit(file_path)}catch{}if(!this.config.getFileReadCacheDisabled()){const writeDecision=await checkPriorRead(this.config.getFileReadCache(),file_path,"overwriting",{expectExisting:fileExists2});if(!writeDecision.ok){debugLogger.warn("pre-write TOCTOU rejection",{path:file_path,reason:writeDecision.type});return{llmContent:writeDecision.rawMessage,returnDisplay:`Error: ${writeDecision.displayMessage}`,error:{message:writeDecision.rawMessage,type:writeDecision.type}}}}if(!mutation&&!fileExists2&&!this.config.getShellExecutionSandbox?.()){fs.mkdirSync(dirName,{recursive:true})}try{const writeParams={path:file_path,content,toolWriteOrigin:"write_file",_meta:{bom:useBOM,encoding:detectedEncoding,lineEnding:detectedLineEnding}};const committedStats=mutation?await mutation.write(writeParams):(await writeRuntimeFile(this.config,writeParams,sandboxFileVersion,abortSignal),void 0);if(!mutation&&!modified_by_user){CommitAttributionService.getInstance().recordEdit(file_path,fileExists2?originalContent:null,content)}let postWriteSizeBytes;try{if(mutation&&!committedStats)throw new Error("Scoped file write returned no committed stats.");const postWriteStats=mutation?committedStats:fs.statSync(file_path);postWriteSizeBytes=postWriteStats.size;this.config.getFileReadCache().recordWrite(file_path,postWriteStats)}catch(error){if(mutation)throw error}const fileName=path.basename(file_path);const currentContentForDiff=originalContent;const fileDiff=createPatchSmart(fileName,currentContentForDiff,content,"Original","Written");const originallyProposedContent=ai_proposed_content||content;const diffStat=getDiffStat(fileName,currentContentForDiff,originallyProposedContent,content);const llmSuccessMessageParts=[!fileExists2?`Successfully created and wrote to new file: ${file_path}.`:`Successfully overwrote file: ${file_path}.`];if(modified_by_user){llmSuccessMessageParts.push(`User modified the \`content\` to be: ${content}`)}const artifact=buildWorkspaceArtifactCandidate(this.config,file_path,{recordAsArtifact:this.params.record_as_artifact,sizeBytes:postWriteSizeBytes});if(artifact&&!artifact.updateOnly){llmSuccessMessageParts.push(formatRecordArtifactReminder(artifact.workspacePath))}const mimetype=getSpecificMimeType(file_path);const programmingLanguage=getLanguageFromFilePath(file_path);const extension=path.extname(file_path);const operation=!fileExists2?"create":"update";const lineCount=content.split("\n").length;logFileOperation(this.config,new FileOperationEvent(WriteFileTool.Name,operation,lineCount,mimetype,extension,programmingLanguage));const displayResult={fileDiff,fileName,filePath:file_path,originalContent,newContent:content,diffStat};return{llmContent:llmSuccessMessageParts.join(" "),returnDisplay:displayResult,...artifact?{artifacts:[artifact]}:{}}}catch(error){return this.writeFailure(error)}}writeFailure(error){const file_path=this.params.file_path;let errorMsg;let errorType="file_write_failure";if(isNodeError(error)){errorMsg=`Error writing to file '${file_path}': ${error.message} (${error.code})`;if(error.code==="ESTALE"&&this.config.getShellExecutionSandbox?.()){errorType="file_changed_since_read"}else if(error.code==="EACCES"){errorMsg=`Permission denied writing to file: ${file_path} (${error.code})`;errorType="permission_denied"}else if(error.code==="ENOSPC"){errorMsg=`No space left on device: ${file_path} (${error.code})`;errorType="no_space_left"}else if(error.code==="EISDIR"){errorMsg=`Target is a directory, not a file: ${file_path} (${error.code})`;errorType="target_is_directory"}if(this.config.getDebugMode()&&error.stack){debugLogger.debug("Write file error stack:",error.stack)}}else{errorMsg=`Error writing to file: ${getErrorMessage(error)}`}return{llmContent:errorMsg,returnDisplay:errorMsg,error:{message:errorMsg,type:errorType}}}};var WRITE_FILE_ARTIFACT_DESCRIPTION="Artifact-like files such as HTML, PDF, images, notebooks, office documents, CSV, Markdown, JSON, SQL, and Python files are automatically registered as session artifacts. Set record_as_artifact=false for intermediates, such as HTML written only to print a PDF: that does not create an artifact, but one the session already has for the path is still refreshed. Files under .qwen/tmp/ are not registered. Delete intermediates when done.";var WriteFileTool=class _WriteFileTool extends BaseDeclarativeTool{constructor(config){super(_WriteFileTool.Name,ToolDisplayNames.WRITE_FILE,`Writes content to a specified file in the local filesystem. A request to create or generate a file does not establish that the target path is new. Unless the target's absence or current text contents have already been established in this session, you MUST use the ${ToolNames.READ_FILE} tool first; if the file does not exist, then create it. With prior-read enforcement enabled, blind overwrites are rejected. The file_path argument MUST be an absolute path. Always construct it by combining the project root with the file's relative path (e.g. project root '/path/to/project/' + relative 'foo/bar.txt' = '/path/to/project/foo/bar.txt'). If the user provides a relative path, resolve it against the project root first.
|
|
3
|
+
import{captureRuntimeFileVersion,writeRuntimeFile}from"./chunk-WXK7Z45R.js";import{checkTeamMemorySecrets,checkWorkspaceTeamMemorySecrets}from"./chunk-UJP2MPBI.js";import{buildWorkspaceArtifactCandidate,formatRecordArtifactReminder}from"./chunk-AKWYMQKU.js";import{CommitAttributionService,FileEncoding,checkPriorRead,createPatchSmart,detectLineEnding,getDiffStat,needsUtf8Bom}from"./chunk-T3CQ72HC.js";import{backgroundFixHolding}from"./chunk-YVD4O5ZB.js";import{getCurrentAgentId}from"./chunk-YZFNBUKG.js";import{FileOperationEvent,getLanguageFromFilePath,logFileOperation}from"./chunk-ZWPSBU7K.js";import{isAnyAutoMemPath,isTeamAutoMemPath}from"./chunk-KVA6DHHF.js";import{fileExists,getSpecificMimeType}from"./chunk-Y6HHV4LC.js";import{BaseDeclarativeTool,BaseToolInvocation,StructuredToolError}from"./chunk-O5EKX7LG.js";import{ToolDisplayNames,ToolNames}from"./chunk-SBZFGYYS.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{makeRelative,shortenPath,unescapePath}from"./chunk-OKN3Z5C5.js";import{getErrorMessage,isNodeError}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import fs from"node:fs";import path from"node:path";var debugLogger=createDebugLogger("WRITE_FILE");var WriteFileToolInvocation=class extends BaseToolInvocation{constructor(config,params){super(params);this.config=config}static{__name(this,"WriteFileToolInvocation")}toolLocations(){return[{path:this.params.file_path}]}getDescription(){const relativePath=makeRelative(this.params.file_path,this.config.getTargetDir());return`Writing to ${shortenPath(relativePath)}`}requiresUserInteraction(){return backgroundFixHolding(this.params.file_path,getCurrentAgentId())!==void 0}async getDefaultPermission(){if(this.config.getFileSystemService().textFileIo)return"ask";const projectRoot=this.config.getProjectRoot();const filePath=path.resolve(this.params.file_path);if(isTeamAutoMemPath(filePath,projectRoot)){return"ask"}if(isAnyAutoMemPath(filePath,projectRoot)){return"allow"}return"ask"}async getConfirmationDetails(_abortSignal){let originalContent="";let observation;try{observation=await this.config.getFileSystemService().textFileIo?.inspect(this.params.file_path,_abortSignal)}catch(error){if(isNodeError(error)&&error.code==="EISDIR")throw new StructuredToolError(`Path is a directory, not a file: ${this.params.file_path}`,"target_is_directory");throw error}let fileExists2=observation?observation.kind==="file":await fileExists(this.params.file_path);if(!this.config.getFileReadCacheDisabled()){const decision=await checkPriorRead(this.config.getFileReadCache(),this.params.file_path,"overwriting");if(!decision.ok){throw new StructuredToolError(decision.rawMessage,decision.type)}}if(fileExists2){try{const{content}=observation?.kind==="file"?observation.response:await this.config.getFileSystemService().readTextFile({path:this.params.file_path});originalContent=content}catch(err){if(isNodeError(err)&&err.code==="ENOENT"){fileExists2=false}else{throw new Error(`Error reading existing file for confirmation: ${getErrorMessage(err)}`)}}}if(fileExists2&&!this.config.getFileReadCacheDisabled()){const postDecision=await checkPriorRead(this.config.getFileReadCache(),this.params.file_path,"overwriting",{expectExisting:true});if(!postDecision.ok){debugLogger.warn("post-read TOCTOU rejection (confirmation)",{path:this.params.file_path,reason:postDecision.type});throw new StructuredToolError(postDecision.rawMessage,postDecision.type)}}const relativePath=makeRelative(this.params.file_path,this.config.getTargetDir());const fileName=path.basename(this.params.file_path);const fileDiff=createPatchSmart(fileName,originalContent,this.params.content,"Current","Proposed");const confirmationDetails={type:"edit",title:`Confirm Write: ${shortenPath(relativePath)}`,fileName,filePath:this.params.file_path,fileDiff,originalContent,newContent:this.params.content,onConfirm:__name(async outcome=>{if(outcome==="proceed_always"){this.config.setApprovalMode("auto-edit")}},"onConfirm")};return confirmationDetails}async execute(abortSignal){const io=this.config.getFileSystemService().textFileIo;if(!io)return this.executeObserved(abortSignal);try{return await io.withMutation(this.params.file_path,abortSignal,mutation=>this.executeObserved(abortSignal,mutation))}catch(error){if(abortSignal.aborted)throw error;return this.writeFailure(error)}}async executeObserved(abortSignal,mutation){const{file_path,content,ai_proposed_content,modified_by_user}=this.params;let sandboxFileVersion;try{sandboxFileVersion=captureRuntimeFileVersion(this.config,file_path)}catch(error){const message=`${file_path}: ${getErrorMessage(error)}`;return{llmContent:message,returnDisplay:message,error:{message,type:isNodeError(error)&&error.code==="EISDIR"?"target_is_directory":"file_write_failure"}}}let fileExists2=mutation?mutation.original.kind==="file":await fileExists(file_path);let originalContent="";let useBOM=false;let detectedEncoding;let detectedLineEnding;const dirName=path.dirname(file_path);const teamMemoryError=(this.config.getFileSystemService().textFileIo?checkWorkspaceTeamMemorySecrets:checkTeamMemorySecrets)(file_path,content,this.config.getProjectRoot());if(teamMemoryError){return{llmContent:`[ERROR: ${teamMemoryError}]`,returnDisplay:teamMemoryError,error:{message:teamMemoryError,type:"invalid_tool_params"}}}if(!this.config.getFileReadCacheDisabled()){const decision=await checkPriorRead(this.config.getFileReadCache(),file_path,"overwriting");if(!decision.ok){return{llmContent:decision.rawMessage,returnDisplay:`Error: ${decision.displayMessage}`,error:{message:decision.rawMessage,type:decision.type}}}}if(fileExists2){try{const fileInfo=mutation?.original.kind==="file"?mutation.original.response:await this.config.getFileSystemService().readTextFile({path:file_path});if(fileInfo._meta?.bom!==void 0){useBOM=fileInfo._meta.bom}else{useBOM=fileInfo.content.length>0&&fileInfo.content.codePointAt(0)===65279}detectedEncoding=fileInfo._meta?.encoding||"utf-8";detectedLineEnding=detectLineEnding(fileInfo.content);originalContent=fileInfo.content;fileExists2=true}catch(err){if(isNodeError(err)&&err.code==="ENOENT"){fileExists2=false}else{const error={message:getErrorMessage(err),code:isNodeError(err)?err.code:void 0};const errorMsg=error.code?`Error checking existing file '${file_path}': ${error.message} (${error.code})`:`Error checking existing file: ${error.message}`;return{llmContent:errorMsg,returnDisplay:errorMsg,error:{message:errorMsg,type:"file_write_failure"}}}}}if(fileExists2&&!this.config.getFileReadCacheDisabled()){const postDecision=await checkPriorRead(this.config.getFileReadCache(),file_path,"overwriting",{expectExisting:true});if(!postDecision.ok){debugLogger.warn("post-read TOCTOU rejection (execute)",{path:file_path,reason:postDecision.type});return{llmContent:postDecision.rawMessage,returnDisplay:`Error: ${postDecision.displayMessage}`,error:{message:postDecision.rawMessage,type:postDecision.type}}}}if(!fileExists2){const userEncoding=this.config.getDefaultFileEncoding();if(userEncoding===FileEncoding.UTF8_BOM){useBOM=true}else if(userEncoding===void 0){useBOM=needsUtf8Bom(file_path)}detectedEncoding=void 0}try{await this.config.getFileHistoryService().trackEdit(file_path)}catch{}if(!this.config.getFileReadCacheDisabled()){const writeDecision=await checkPriorRead(this.config.getFileReadCache(),file_path,"overwriting",{expectExisting:fileExists2});if(!writeDecision.ok){debugLogger.warn("pre-write TOCTOU rejection",{path:file_path,reason:writeDecision.type});return{llmContent:writeDecision.rawMessage,returnDisplay:`Error: ${writeDecision.displayMessage}`,error:{message:writeDecision.rawMessage,type:writeDecision.type}}}}if(!mutation&&!fileExists2&&!this.config.getShellExecutionSandbox?.()){fs.mkdirSync(dirName,{recursive:true})}try{const writeParams={path:file_path,content,toolWriteOrigin:"write_file",_meta:{bom:useBOM,encoding:detectedEncoding,lineEnding:detectedLineEnding}};const committedStats=mutation?await mutation.write(writeParams):(await writeRuntimeFile(this.config,writeParams,sandboxFileVersion,abortSignal),void 0);if(!mutation&&!modified_by_user){CommitAttributionService.getInstance().recordEdit(file_path,fileExists2?originalContent:null,content)}let postWriteSizeBytes;try{if(mutation&&!committedStats)throw new Error("Scoped file write returned no committed stats.");const postWriteStats=mutation?committedStats:fs.statSync(file_path);postWriteSizeBytes=postWriteStats.size;this.config.getFileReadCache().recordWrite(file_path,postWriteStats)}catch(error){if(mutation)throw error}const fileName=path.basename(file_path);const currentContentForDiff=originalContent;const fileDiff=createPatchSmart(fileName,currentContentForDiff,content,"Original","Written");const originallyProposedContent=ai_proposed_content||content;const diffStat=getDiffStat(fileName,currentContentForDiff,originallyProposedContent,content);const llmSuccessMessageParts=[!fileExists2?`Successfully created and wrote to new file: ${file_path}.`:`Successfully overwrote file: ${file_path}.`];if(modified_by_user){llmSuccessMessageParts.push(`User modified the \`content\` to be: ${content}`)}const artifact=buildWorkspaceArtifactCandidate(this.config,file_path,{recordAsArtifact:this.params.record_as_artifact,sizeBytes:postWriteSizeBytes});if(artifact&&!artifact.updateOnly){llmSuccessMessageParts.push(formatRecordArtifactReminder(artifact.workspacePath))}const mimetype=getSpecificMimeType(file_path);const programmingLanguage=getLanguageFromFilePath(file_path);const extension=path.extname(file_path);const operation=!fileExists2?"create":"update";const lineCount=content.split("\n").length;logFileOperation(this.config,new FileOperationEvent(WriteFileTool.Name,operation,lineCount,mimetype,extension,programmingLanguage));const displayResult={fileDiff,fileName,filePath:file_path,originalContent,newContent:content,diffStat};return{llmContent:llmSuccessMessageParts.join(" "),returnDisplay:displayResult,...artifact?{artifacts:[artifact]}:{}}}catch(error){return this.writeFailure(error)}}writeFailure(error){const file_path=this.params.file_path;let errorMsg;let errorType="file_write_failure";if(isNodeError(error)){errorMsg=`Error writing to file '${file_path}': ${error.message} (${error.code})`;if(error.code==="ESTALE"&&this.config.getShellExecutionSandbox?.()){errorType="file_changed_since_read"}else if(error.code==="EACCES"){errorMsg=`Permission denied writing to file: ${file_path} (${error.code})`;errorType="permission_denied"}else if(error.code==="ENOSPC"){errorMsg=`No space left on device: ${file_path} (${error.code})`;errorType="no_space_left"}else if(error.code==="EISDIR"){errorMsg=`Target is a directory, not a file: ${file_path} (${error.code})`;errorType="target_is_directory"}if(this.config.getDebugMode()&&error.stack){debugLogger.debug("Write file error stack:",error.stack)}}else{errorMsg=`Error writing to file: ${getErrorMessage(error)}`}return{llmContent:errorMsg,returnDisplay:errorMsg,error:{message:errorMsg,type:errorType}}}};var WRITE_FILE_ARTIFACT_DESCRIPTION="Artifact-like files such as HTML, PDF, images, notebooks, office documents, CSV, Markdown, JSON, SQL, and Python files are automatically registered as session artifacts. Set record_as_artifact=false for intermediates, such as HTML written only to print a PDF: that does not create an artifact, but one the session already has for the path is still refreshed. Files under .qwen/tmp/ are not registered. Delete intermediates when done.";var WriteFileTool=class _WriteFileTool extends BaseDeclarativeTool{constructor(config){super(_WriteFileTool.Name,ToolDisplayNames.WRITE_FILE,`Writes content to a specified file in the local filesystem. A request to create or generate a file does not establish that the target path is new. Unless the target's absence or current text contents have already been established in this session, you MUST use the ${ToolNames.READ_FILE} tool first; if the file does not exist, then create it. With prior-read enforcement enabled, blind overwrites are rejected. The file_path argument MUST be an absolute path. Always construct it by combining the project root with the file's relative path (e.g. project root '/path/to/project/' + relative 'foo/bar.txt' = '/path/to/project/foo/bar.txt'). If the user provides a relative path, resolve it against the project root first.
|
|
4
4
|
|
|
5
5
|
${WRITE_FILE_ARTIFACT_DESCRIPTION}
|
|
6
6
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{sanitizeFilenameForDisplay,truncateToWidth}from"./chunk-64CA3W6G.js";import{t}from"./chunk-ABJGFEES.js";import{isCompressionFailureStatus}from"./chunk-Z5XENA4A.js";import{fetchGitDiff}from"./chunk-ILECDNJX.js";import{skillRestrictionNames}from"./chunk-CV2UAEZA.js";import{findProviderByCredentials,resolveMetadataKey}from"./chunk-ET2Z7ZGF.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var formatRelativeTime=__name(timestamp=>{const now=Date.now();const diffMs=now-timestamp;const seconds=Math.floor(diffMs/1e3);const minutes=Math.floor(seconds/60);const hours=Math.floor(minutes/60);const days=Math.floor(hours/24);const weeks=Math.floor(days/7);const months=Math.floor(days/30);if(months>0){return months===1?"1 month ago":`${months} months ago`}if(weeks>0){return weeks===1?"1 week ago":`${weeks} weeks ago`}if(days>0){return days===1?"1 day ago":`${days} days ago`}if(hours>0){return hours===1?"1 hour ago":`${hours} hours ago`}if(minutes>0){return minutes===1?"1 minute ago":`${minutes} minutes ago`}return"just now"},"formatRelativeTime");var formatClockTime=__name(timestamp=>`[${new Date(timestamp).toLocaleTimeString("en-US",{hour12:false,hour:"2-digit",minute:"2-digit",second:"2-digit"})}]`,"formatClockTime");var formatTokenCount=__name(count=>{if(count<1e3){return`${count}`}if(count<1e4){return`${(count/1e3).toFixed(1)}k`}return`${Math.floor(count/1e3)}k`},"formatTokenCount");var formatPercentageUsed=__name(percentage=>{if(percentage>1){return">100"}return(percentage*100).toFixed(1)},"formatPercentageUsed");var contextUsageLabel=__name(terminalWidth=>terminalWidth<100?t("% used"):t("% context used"),"contextUsageLabel");var formatDuration=__name((milliseconds,options)=>{if(milliseconds<=0){return"0s"}if(milliseconds<1e3){return`${Math.round(milliseconds)}ms`}const totalSeconds=milliseconds/1e3;if(totalSeconds<60){const formatted=totalSeconds.toFixed(1);if(parseFloat(formatted)>=60){return"1m"}if(options?.hideTrailingZeros&&formatted.endsWith(".0")){return`${formatted.slice(0,-2)}s`}return`${formatted}s`}const hours=Math.floor(totalSeconds/3600);const minutes=Math.floor(totalSeconds%3600/60);const seconds=Math.floor(totalSeconds%60);const parts=[];if(hours>0){parts.push(`${hours}h`)}if(minutes>0){parts.push(`${minutes}m`)}if(seconds>0){parts.push(`${seconds}s`)}if(parts.length===0){if(hours>0)return`${hours}h`;if(minutes>0)return`${minutes}m`;return`${seconds}s`}return parts.join(" ")},"formatDuration");init_esbuild_shims();var formatCompressionTokenCount=__name((count,isEstimated)=>isEstimated?`~${count}`:String(count),"formatCompressionTokenCount");function getCompressionStatusText({isPending,originalTokenCount,newTokenCount,compressionStatus,originalTokenCountIsEstimated,newTokenCountIsEstimated}){if(isPending){return t("Compressing chat history")}const originalTokens=originalTokenCount??0;const newTokens=newTokenCount??0;switch(compressionStatus){case 1:return t("Chat history compressed from {{originalTokens}} to {{newTokens}} tokens.",{originalTokens:formatCompressionTokenCount(originalTokens,originalTokenCountIsEstimated),newTokens:formatCompressionTokenCount(newTokens,newTokenCountIsEstimated)});case 2:if(originalTokens<5e4){return t("Compression was not beneficial for this history size.")}return t("Chat history compression did not reduce size. This may indicate issues with the compression prompt.");case 3:return t("Could not compress chat history due to a token counting error.");case 4:return t("Could not compress chat history because the compression summary was empty.");case 6:return t("Could not compress chat history because the compression summary was truncated.");case 7:return t("Could not compress chat history due to an API error.");case 5:return"Nothing to compress.";default:return""}}__name(getCompressionStatusText,"getCompressionStatusText");function getCompressionFailureStatusText(options){if(!isCompressionFailureStatus(options.compressionStatus)){return t("Failed to compress chat history.")}return getCompressionStatusText({...options,isPending:false})||t("Failed to compress chat history.")}__name(getCompressionFailureStatusText,"getCompressionFailureStatusText");init_esbuild_shims();function getSystemInfoFields(info){const fields=[];addField(fields,t("Qwen Code"),formatCliVersion(info));addField(fields,t("Runtime"),formatRuntime(info));addField(fields,t("IDE Client"),info.ideClient);addField(fields,"LSP",info.lspStatus??"");addField(fields,t("OS"),formatOs(info));addField(fields,t("Auth"),formatAuth(info));addField(fields,t("Base URL"),formatBaseUrl(info));addField(fields,t("Model"),info.modelVersion);addField(fields,t("Fast Model"),info.fastModel||info.modelVersion);addField(fields,t("Session ID"),info.sessionId);addField(fields,t("Sandbox"),info.sandboxEnv);addField(fields,t("Proxy"),formatProxy(info.proxy));addField(fields,t("Memory Usage"),info.memoryUsage);return fields}__name(getSystemInfoFields,"getSystemInfoFields");function addField(fields,label,value){if(value){fields.push({label,value})}}__name(addField,"addField");function formatCliVersion(info){if(!info.cliVersion){return""}if(!info.gitCommit){return info.cliVersion}return`${info.cliVersion} (${info.gitCommit})`}__name(formatCliVersion,"formatCliVersion");function formatRuntime(info){if(!info.nodeVersion&&!info.npmVersion){return""}const node=info.nodeVersion?`Node.js ${info.nodeVersion}`:"";const npm=info.npmVersion?`npm ${info.npmVersion}`:"";return joinParts([node,npm]," / ")}__name(formatRuntime,"formatRuntime");function formatOs(info){return joinParts([info.osPlatform,info.osArch,formatOsRelease(info.osRelease)]," ").trim()}__name(formatOs,"formatOs");function formatOsRelease(release){if(!release){return""}return`(${release})`}__name(formatOsRelease,"formatOsRelease");function formatAuth(info){if(!info.selectedAuthType){return""}const managedProvider=findProviderByCredentials(info.baseUrl,info.apiKeyEnvKey);if(managedProvider&&resolveMetadataKey(managedProvider)){return t(managedProvider.label)}if(info.selectedAuthType.startsWith("oauth")||info.selectedAuthType==="qwen-oauth"){return"Qwen OAuth"}return`API Key - ${info.selectedAuthType}`}__name(formatAuth,"formatAuth");function formatBaseUrl(info){if(!info.selectedAuthType||!info.baseUrl){return""}if(info.selectedAuthType.startsWith("oauth")||info.selectedAuthType==="qwen-oauth"){return""}return info.baseUrl}__name(formatBaseUrl,"formatBaseUrl");function formatProxy(proxy){if(!proxy){return"no proxy"}return redactProxy(proxy)}__name(formatProxy,"formatProxy");function redactProxy(proxy){try{const url=new URL(proxy);if(url.username||url.password){url.username=url.username?"***":"";url.password=url.password?"***":""}return url.toString()}catch{return proxy.replace(/\/\/[^/]*@/,"//***@")}}__name(redactProxy,"redactProxy");function joinParts(parts,separator){return parts.filter(part=>part).join(separator)}__name(joinParts,"joinParts");init_esbuild_shims();function calculateErrorRate(metrics){if(metrics.api.totalRequests===0){return 0}return metrics.api.totalErrors/metrics.api.totalRequests*100}__name(calculateErrorRate,"calculateErrorRate");function calculateAverageLatency(metrics){if(metrics.api.totalRequests===0){return 0}return metrics.api.totalLatencyMs/metrics.api.totalRequests}__name(calculateAverageLatency,"calculateAverageLatency");function calculateCacheHitRate(metrics){if(metrics.tokens.prompt===0){return 0}return metrics.tokens.cached/metrics.tokens.prompt*100}__name(calculateCacheHitRate,"calculateCacheHitRate");var computeSessionStats=__name(metrics=>{const{models,tools,files}=metrics;const totalApiTime=Object.values(models).reduce((acc,model)=>acc+model.api.totalLatencyMs,0);const totalToolTime=tools.totalDurationMs;const agentActiveTime=totalApiTime+totalToolTime;const apiTimePercent=agentActiveTime>0?totalApiTime/agentActiveTime*100:0;const toolTimePercent=agentActiveTime>0?totalToolTime/agentActiveTime*100:0;const totalCachedTokens=Object.values(models).reduce((acc,model)=>acc+model.tokens.cached,0);const totalPromptTokens=Object.values(models).reduce((acc,model)=>acc+model.tokens.prompt,0);const cacheEfficiency=totalPromptTokens>0?totalCachedTokens/totalPromptTokens*100:0;const totalDecisions=tools.totalDecisions.accept+tools.totalDecisions.reject+tools.totalDecisions.modify;const successRate=tools.totalCalls>0?tools.totalSuccess/tools.totalCalls*100:0;const agreementRate=totalDecisions>0?tools.totalDecisions.accept/totalDecisions*100:0;return{totalApiTime,totalToolTime,agentActiveTime,apiTimePercent,toolTimePercent,cacheEfficiency,totalDecisions,successRate,agreementRate,totalCachedTokens,totalPromptTokens,totalLinesAdded:files.totalLinesAdded,totalLinesRemoved:files.totalLinesRemoved}},"computeSessionStats");init_esbuild_shims();function calculateCost(args){const{inputTokens,outputTokens,pricing}=args;if(!pricing)return null;if(pricing.inputPerMillionTokens==null&&pricing.outputPerMillionTokens==null){return null}if(inputTokens<=0&&outputTokens<=0){return null}const inputCost=pricing.inputPerMillionTokens!=null?inputTokens/1e6*pricing.inputPerMillionTokens:0;const outputCost=pricing.outputPerMillionTokens!=null?outputTokens/1e6*pricing.outputPerMillionTokens:0;return inputCost+outputCost}__name(calculateCost,"calculateCost");function billableOutputTokens(tokens){const{prompt,candidates,thoughts,total}=tokens;const derived=total-prompt;if(derived>=candidates&&derived<=candidates+thoughts){return derived}return candidates+thoughts}__name(billableOutputTokens,"billableOutputTokens");init_esbuild_shims();function commandRestrictionNames(cmd){const names=cmd.skillDetail?skillRestrictionNames(cmd.skillDetail):[cmd.name.trim().toLowerCase()];return[...names,...cmd.workflowName?[cmd.workflowName.trim().toLowerCase()]:[],...(cmd.altNames??[]).map(name=>name.trim().toLowerCase())]}__name(commandRestrictionNames,"commandRestrictionNames");function getEffectiveSupportedModes(cmd){if(cmd.supportedModes!==void 0){return cmd.supportedModes}switch(cmd.kind){case"built-in":return["interactive"];case"file":case"skill":case"mcp-prompt":return["interactive","non_interactive","acp"];default:return["interactive"]}}__name(getEffectiveSupportedModes,"getEffectiveSupportedModes");function filterCommandsForMode(commands,mode){return commands.filter(cmd=>getEffectiveSupportedModes(cmd).includes(mode))}__name(filterCommandsForMode,"filterCommandsForMode");init_esbuild_shims();function extensionOwnerLabel(owner){return`${t("Extension:")} ${owner.displayName||owner.name||"unknown"}`}__name(extensionOwnerLabel,"extensionOwnerLabel");var MAX_EXTENSION_OWNER_LABEL_WIDTH=35;function getCommandSourceBadge(command){switch(command.source){case"bundled-skill":return"[Skill]";case"skill-dir-command":if(command.sourceDetail==="user"){return"[User]"}if(command.sourceDetail==="project"){return"[Project]"}return"[Custom]";case"plugin-command":if(command.sourceDetail!=="extension"){return"[Plugin]"}return command.sourceLabel?`[${truncateToWidth(command.sourceLabel,MAX_EXTENSION_OWNER_LABEL_WIDTH)}]`:"[Extension]";case"mcp-prompt":return"[MCP]";case"workflow-command":return command.sourceDetail==="extension"&&command.sourceLabel?`[${truncateToWidth(command.sourceLabel,MAX_EXTENSION_OWNER_LABEL_WIDTH)}]`:null;case"builtin-command":default:return null}}__name(getCommandSourceBadge,"getCommandSourceBadge");function getCommandSourceGroup(command){switch(command.source){case"builtin-command":return{key:"built-in",title:"Built-in Commands",order:0};case"bundled-skill":return{key:"bundled-skill",title:"Bundled Skills",order:1};case"skill-dir-command":return{key:"custom",title:"Custom Commands",order:2};case"plugin-command":return{key:"plugin",title:"Plugin Commands",order:3};case"mcp-prompt":return{key:"mcp",title:"MCP Commands",order:4};default:return{key:"other",title:"Other Commands",order:5}}}__name(getCommandSourceGroup,"getCommandSourceGroup");function formatSupportedModes(command){const modes=getEffectiveSupportedModes(command);const hasInteractive=modes.includes("interactive");const hasNonInteractive=modes.includes("non_interactive");const hasAcp=modes.includes("acp");if(hasInteractive&&hasNonInteractive&&hasAcp){return"[all]"}if(!hasInteractive&&hasNonInteractive&&hasAcp){return"[headless]"}if(hasInteractive&&!hasNonInteractive&&!hasAcp){return"[interactive]"}return modes.map(mode=>{switch(mode){case"interactive":return"[i]";case"non_interactive":return"[ni]";case"acp":return"[acp]";default:return`[${mode}]`}}).join(" ")}__name(formatSupportedModes,"formatSupportedModes");function getCommandDisplayName(command,options={}){const prefix=options.prefix??"";const baseLabel=`${prefix}${command.name}`;if(options.matchedAlias){return`${baseLabel} (alias: ${options.matchedAlias})`}if(options.includeAliases===false){return baseLabel}const altNames=command.altNames?.filter(Boolean);if(!altNames||altNames.length===0){return baseLabel}return`${baseLabel} (${altNames.join(", ")})`}__name(getCommandDisplayName,"getCommandDisplayName");function getCommandSubcommandNames(command){return command.subCommands?.filter(subCommand=>!subCommand.hidden).map(subCommand=>subCommand.name)??[]}__name(getCommandSubcommandNames,"getCommandSubcommandNames");init_esbuild_shims();function levelLabel(level){switch(level){case"project":return t("Project");case"user":return t("User");case"extension":return t("Extension");case"bundled":return t("Bundled");default:{const _exhaustive=level;return _exhaustive}}}__name(levelLabel,"levelLabel");function skillOriginLabel(skill){if(skill.level==="extension"){return`(${extensionOwnerLabel({name:skill.extensionName,displayName:skill.extensionDisplayName})})`}return`(${levelLabel(skill.level)})`}__name(skillOriginLabel,"skillOriginLabel");init_esbuild_shims();async function diffAction(context){const{config}=context.services;if(!config){return{type:"message",messageType:"error",content:t("Configuration not available.")}}if(config.getShellExecutionSandbox?.()){return{type:"message",messageType:"error",content:"Diff preview unavailable in tool sandbox. Run git diff through the Shell tool."}}if(context.executionMode==="interactive"){return{type:"dialog",dialog:"diff"}}const cwd=config.getWorkingDir()||config.getProjectRoot();if(!cwd){return{type:"message",messageType:"error",content:t("Could not determine current working directory.")}}let result;try{result=await fetchGitDiff(cwd)}catch(error){return{type:"message",messageType:"error",content:`${t("Failed to compute git diff stats")}: ${error instanceof Error?error.message:String(error)}`}}if(!result){return{type:"message",messageType:"info",content:t("No diff available. Either this is not a git repository, HEAD is missing, or a merge/rebase/cherry-pick/revert is in progress.")}}if(result.stats.filesCount===0){return{type:"message",messageType:"info",content:t("Clean working tree \u2014 no changes against HEAD.")}}const model=buildDiffRenderModel(result);return{type:"message",messageType:"info",content:renderDiffModelText(model)}}__name(diffAction,"diffAction");function buildDiffRenderModel(result){const rows=[];for(const[filename,s]of result.perFileStats){rows.push(toRow(filename,s))}const hiddenCount=Math.max(0,result.stats.filesCount-rows.length);return{filesCount:result.stats.filesCount,linesAdded:result.stats.linesAdded,linesRemoved:result.stats.linesRemoved,rows,hiddenCount}}__name(buildDiffRenderModel,"buildDiffRenderModel");function toRow(filename,s){if(s.isBinary){return{filename,oldPath:s.oldPath,isBinary:true,isUntracked:Boolean(s.isUntracked),isDeleted:Boolean(s.isDeleted),truncated:false}}return{filename,oldPath:s.oldPath,added:s.added,removed:s.isUntracked?0:s.removed,isBinary:false,isUntracked:Boolean(s.isUntracked),isDeleted:Boolean(s.isDeleted),truncated:Boolean(s.truncated)}}__name(toRow,"toRow");function computeDiffColumnWidths(rows){let maxAdded=0;let maxRemoved=0;for(const r of rows){if(r.isBinary)continue;if((r.added??0)>maxAdded)maxAdded=r.added??0;if((r.removed??0)>maxRemoved)maxRemoved=r.removed??0}const addWidth=String(maxAdded).length;const remWidth=String(maxRemoved).length;const statColumnWidth=1+addWidth+1+1+remWidth;return{addWidth,remWidth,statColumnWidth}}__name(computeDiffColumnWidths,"computeDiffColumnWidths");function renderDiffModelText(model){const{filesCount,linesAdded,linesRemoved,rows,hiddenCount}=model;const header=filesCount===1?t("{{count}} file changed, +{{added}} / -{{removed}}",{count:String(filesCount),added:String(linesAdded),removed:String(linesRemoved)}):t("{{count}} files changed, +{{added}} / -{{removed}}",{count:String(filesCount),added:String(linesAdded),removed:String(linesRemoved)});const lines=formatRowsText(rows);const capNote=hiddenCount>0&&rows.length>0?`
|
|
3
|
+
import{sanitizeFilenameForDisplay,truncateToWidth}from"./chunk-64CA3W6G.js";import{t}from"./chunk-NO7VTKRL.js";import{isCompressionFailureStatus}from"./chunk-T3CQ72HC.js";import{fetchGitDiff}from"./chunk-ILECDNJX.js";import{skillRestrictionNames}from"./chunk-CV2UAEZA.js";import{findProviderByCredentials,resolveMetadataKey}from"./chunk-ET2Z7ZGF.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var formatRelativeTime=__name(timestamp=>{const now=Date.now();const diffMs=now-timestamp;const seconds=Math.floor(diffMs/1e3);const minutes=Math.floor(seconds/60);const hours=Math.floor(minutes/60);const days=Math.floor(hours/24);const weeks=Math.floor(days/7);const months=Math.floor(days/30);if(months>0){return months===1?"1 month ago":`${months} months ago`}if(weeks>0){return weeks===1?"1 week ago":`${weeks} weeks ago`}if(days>0){return days===1?"1 day ago":`${days} days ago`}if(hours>0){return hours===1?"1 hour ago":`${hours} hours ago`}if(minutes>0){return minutes===1?"1 minute ago":`${minutes} minutes ago`}return"just now"},"formatRelativeTime");var formatClockTime=__name(timestamp=>`[${new Date(timestamp).toLocaleTimeString("en-US",{hour12:false,hour:"2-digit",minute:"2-digit",second:"2-digit"})}]`,"formatClockTime");var formatTokenCount=__name(count=>{if(count<1e3){return`${count}`}if(count<1e4){return`${(count/1e3).toFixed(1)}k`}return`${Math.floor(count/1e3)}k`},"formatTokenCount");var formatPercentageUsed=__name(percentage=>{if(percentage>1){return">100"}return(percentage*100).toFixed(1)},"formatPercentageUsed");var contextUsageLabel=__name(terminalWidth=>terminalWidth<100?t("% used"):t("% context used"),"contextUsageLabel");var formatDuration=__name((milliseconds,options)=>{if(milliseconds<=0){return"0s"}if(milliseconds<1e3){return`${Math.round(milliseconds)}ms`}const totalSeconds=milliseconds/1e3;if(totalSeconds<60){const formatted=totalSeconds.toFixed(1);if(parseFloat(formatted)>=60){return"1m"}if(options?.hideTrailingZeros&&formatted.endsWith(".0")){return`${formatted.slice(0,-2)}s`}return`${formatted}s`}const hours=Math.floor(totalSeconds/3600);const minutes=Math.floor(totalSeconds%3600/60);const seconds=Math.floor(totalSeconds%60);const parts=[];if(hours>0){parts.push(`${hours}h`)}if(minutes>0){parts.push(`${minutes}m`)}if(seconds>0){parts.push(`${seconds}s`)}if(parts.length===0){if(hours>0)return`${hours}h`;if(minutes>0)return`${minutes}m`;return`${seconds}s`}return parts.join(" ")},"formatDuration");init_esbuild_shims();var formatCompressionTokenCount=__name((count,isEstimated)=>isEstimated?`~${count}`:String(count),"formatCompressionTokenCount");function getCompressionStatusText({isPending,originalTokenCount,newTokenCount,compressionStatus,originalTokenCountIsEstimated,newTokenCountIsEstimated}){if(isPending){return t("Compressing chat history")}const originalTokens=originalTokenCount??0;const newTokens=newTokenCount??0;switch(compressionStatus){case 1:return t("Chat history compressed from {{originalTokens}} to {{newTokens}} tokens.",{originalTokens:formatCompressionTokenCount(originalTokens,originalTokenCountIsEstimated),newTokens:formatCompressionTokenCount(newTokens,newTokenCountIsEstimated)});case 2:if(originalTokens<5e4){return t("Compression was not beneficial for this history size.")}return t("Chat history compression did not reduce size. This may indicate issues with the compression prompt.");case 3:return t("Could not compress chat history due to a token counting error.");case 4:return t("Could not compress chat history because the compression summary was empty.");case 6:return t("Could not compress chat history because the compression summary was truncated.");case 7:return t("Could not compress chat history due to an API error.");case 5:return"Nothing to compress.";default:return""}}__name(getCompressionStatusText,"getCompressionStatusText");function getCompressionFailureStatusText(options){if(!isCompressionFailureStatus(options.compressionStatus)){return t("Failed to compress chat history.")}return getCompressionStatusText({...options,isPending:false})||t("Failed to compress chat history.")}__name(getCompressionFailureStatusText,"getCompressionFailureStatusText");init_esbuild_shims();function getSystemInfoFields(info){const fields=[];addField(fields,t("Qwen Code"),formatCliVersion(info));addField(fields,t("Runtime"),formatRuntime(info));addField(fields,t("IDE Client"),info.ideClient);addField(fields,"LSP",info.lspStatus??"");addField(fields,t("OS"),formatOs(info));addField(fields,t("Auth"),formatAuth(info));addField(fields,t("Base URL"),formatBaseUrl(info));addField(fields,t("Model"),info.modelVersion);addField(fields,t("Fast Model"),info.fastModel||info.modelVersion);addField(fields,t("Session ID"),info.sessionId);addField(fields,t("Sandbox"),info.sandboxEnv);addField(fields,t("Proxy"),formatProxy(info.proxy));addField(fields,t("Memory Usage"),info.memoryUsage);return fields}__name(getSystemInfoFields,"getSystemInfoFields");function addField(fields,label,value){if(value){fields.push({label,value})}}__name(addField,"addField");function formatCliVersion(info){if(!info.cliVersion){return""}if(!info.gitCommit){return info.cliVersion}return`${info.cliVersion} (${info.gitCommit})`}__name(formatCliVersion,"formatCliVersion");function formatRuntime(info){if(!info.nodeVersion&&!info.npmVersion){return""}const node=info.nodeVersion?`Node.js ${info.nodeVersion}`:"";const npm=info.npmVersion?`npm ${info.npmVersion}`:"";return joinParts([node,npm]," / ")}__name(formatRuntime,"formatRuntime");function formatOs(info){return joinParts([info.osPlatform,info.osArch,formatOsRelease(info.osRelease)]," ").trim()}__name(formatOs,"formatOs");function formatOsRelease(release){if(!release){return""}return`(${release})`}__name(formatOsRelease,"formatOsRelease");function formatAuth(info){if(!info.selectedAuthType){return""}const managedProvider=findProviderByCredentials(info.baseUrl,info.apiKeyEnvKey);if(managedProvider&&resolveMetadataKey(managedProvider)){return t(managedProvider.label)}if(info.selectedAuthType.startsWith("oauth")||info.selectedAuthType==="qwen-oauth"){return"Qwen OAuth"}return`API Key - ${info.selectedAuthType}`}__name(formatAuth,"formatAuth");function formatBaseUrl(info){if(!info.selectedAuthType||!info.baseUrl){return""}if(info.selectedAuthType.startsWith("oauth")||info.selectedAuthType==="qwen-oauth"){return""}return info.baseUrl}__name(formatBaseUrl,"formatBaseUrl");function formatProxy(proxy){if(!proxy){return"no proxy"}return redactProxy(proxy)}__name(formatProxy,"formatProxy");function redactProxy(proxy){try{const url=new URL(proxy);if(url.username||url.password){url.username=url.username?"***":"";url.password=url.password?"***":""}return url.toString()}catch{return proxy.replace(/\/\/[^/]*@/,"//***@")}}__name(redactProxy,"redactProxy");function joinParts(parts,separator){return parts.filter(part=>part).join(separator)}__name(joinParts,"joinParts");init_esbuild_shims();function calculateErrorRate(metrics){if(metrics.api.totalRequests===0){return 0}return metrics.api.totalErrors/metrics.api.totalRequests*100}__name(calculateErrorRate,"calculateErrorRate");function calculateAverageLatency(metrics){if(metrics.api.totalRequests===0){return 0}return metrics.api.totalLatencyMs/metrics.api.totalRequests}__name(calculateAverageLatency,"calculateAverageLatency");function calculateCacheHitRate(metrics){if(metrics.tokens.prompt===0){return 0}return metrics.tokens.cached/metrics.tokens.prompt*100}__name(calculateCacheHitRate,"calculateCacheHitRate");var computeSessionStats=__name(metrics=>{const{models,tools,files}=metrics;const totalApiTime=Object.values(models).reduce((acc,model)=>acc+model.api.totalLatencyMs,0);const totalToolTime=tools.totalDurationMs;const agentActiveTime=totalApiTime+totalToolTime;const apiTimePercent=agentActiveTime>0?totalApiTime/agentActiveTime*100:0;const toolTimePercent=agentActiveTime>0?totalToolTime/agentActiveTime*100:0;const totalCachedTokens=Object.values(models).reduce((acc,model)=>acc+model.tokens.cached,0);const totalPromptTokens=Object.values(models).reduce((acc,model)=>acc+model.tokens.prompt,0);const cacheEfficiency=totalPromptTokens>0?totalCachedTokens/totalPromptTokens*100:0;const totalDecisions=tools.totalDecisions.accept+tools.totalDecisions.reject+tools.totalDecisions.modify;const successRate=tools.totalCalls>0?tools.totalSuccess/tools.totalCalls*100:0;const agreementRate=totalDecisions>0?tools.totalDecisions.accept/totalDecisions*100:0;return{totalApiTime,totalToolTime,agentActiveTime,apiTimePercent,toolTimePercent,cacheEfficiency,totalDecisions,successRate,agreementRate,totalCachedTokens,totalPromptTokens,totalLinesAdded:files.totalLinesAdded,totalLinesRemoved:files.totalLinesRemoved}},"computeSessionStats");init_esbuild_shims();function calculateCost(args){const{inputTokens,outputTokens,pricing}=args;if(!pricing)return null;if(pricing.inputPerMillionTokens==null&&pricing.outputPerMillionTokens==null){return null}if(inputTokens<=0&&outputTokens<=0){return null}const inputCost=pricing.inputPerMillionTokens!=null?inputTokens/1e6*pricing.inputPerMillionTokens:0;const outputCost=pricing.outputPerMillionTokens!=null?outputTokens/1e6*pricing.outputPerMillionTokens:0;return inputCost+outputCost}__name(calculateCost,"calculateCost");function billableOutputTokens(tokens){const{prompt,candidates,thoughts,total}=tokens;const derived=total-prompt;if(derived>=candidates&&derived<=candidates+thoughts){return derived}return candidates+thoughts}__name(billableOutputTokens,"billableOutputTokens");init_esbuild_shims();function commandRestrictionNames(cmd){const names=cmd.skillDetail?skillRestrictionNames(cmd.skillDetail):[cmd.name.trim().toLowerCase()];return[...names,...cmd.workflowName?[cmd.workflowName.trim().toLowerCase()]:[],...(cmd.altNames??[]).map(name=>name.trim().toLowerCase())]}__name(commandRestrictionNames,"commandRestrictionNames");function getEffectiveSupportedModes(cmd){if(cmd.supportedModes!==void 0){return cmd.supportedModes}switch(cmd.kind){case"built-in":return["interactive"];case"file":case"skill":case"mcp-prompt":return["interactive","non_interactive","acp"];default:return["interactive"]}}__name(getEffectiveSupportedModes,"getEffectiveSupportedModes");function filterCommandsForMode(commands,mode){return commands.filter(cmd=>getEffectiveSupportedModes(cmd).includes(mode))}__name(filterCommandsForMode,"filterCommandsForMode");init_esbuild_shims();function extensionOwnerLabel(owner){return`${t("Extension:")} ${owner.displayName||owner.name||"unknown"}`}__name(extensionOwnerLabel,"extensionOwnerLabel");var MAX_EXTENSION_OWNER_LABEL_WIDTH=35;function getCommandSourceBadge(command){switch(command.source){case"bundled-skill":return"[Skill]";case"skill-dir-command":if(command.sourceDetail==="user"){return"[User]"}if(command.sourceDetail==="project"){return"[Project]"}return"[Custom]";case"plugin-command":if(command.sourceDetail!=="extension"){return"[Plugin]"}return command.sourceLabel?`[${truncateToWidth(command.sourceLabel,MAX_EXTENSION_OWNER_LABEL_WIDTH)}]`:"[Extension]";case"mcp-prompt":return"[MCP]";case"workflow-command":return command.sourceDetail==="extension"&&command.sourceLabel?`[${truncateToWidth(command.sourceLabel,MAX_EXTENSION_OWNER_LABEL_WIDTH)}]`:null;case"builtin-command":default:return null}}__name(getCommandSourceBadge,"getCommandSourceBadge");function getCommandSourceGroup(command){switch(command.source){case"builtin-command":return{key:"built-in",title:"Built-in Commands",order:0};case"bundled-skill":return{key:"bundled-skill",title:"Bundled Skills",order:1};case"skill-dir-command":return{key:"custom",title:"Custom Commands",order:2};case"plugin-command":return{key:"plugin",title:"Plugin Commands",order:3};case"mcp-prompt":return{key:"mcp",title:"MCP Commands",order:4};default:return{key:"other",title:"Other Commands",order:5}}}__name(getCommandSourceGroup,"getCommandSourceGroup");function formatSupportedModes(command){const modes=getEffectiveSupportedModes(command);const hasInteractive=modes.includes("interactive");const hasNonInteractive=modes.includes("non_interactive");const hasAcp=modes.includes("acp");if(hasInteractive&&hasNonInteractive&&hasAcp){return"[all]"}if(!hasInteractive&&hasNonInteractive&&hasAcp){return"[headless]"}if(hasInteractive&&!hasNonInteractive&&!hasAcp){return"[interactive]"}return modes.map(mode=>{switch(mode){case"interactive":return"[i]";case"non_interactive":return"[ni]";case"acp":return"[acp]";default:return`[${mode}]`}}).join(" ")}__name(formatSupportedModes,"formatSupportedModes");function getCommandDisplayName(command,options={}){const prefix=options.prefix??"";const baseLabel=`${prefix}${command.name}`;if(options.matchedAlias){return`${baseLabel} (alias: ${options.matchedAlias})`}if(options.includeAliases===false){return baseLabel}const altNames=command.altNames?.filter(Boolean);if(!altNames||altNames.length===0){return baseLabel}return`${baseLabel} (${altNames.join(", ")})`}__name(getCommandDisplayName,"getCommandDisplayName");function getCommandSubcommandNames(command){return command.subCommands?.filter(subCommand=>!subCommand.hidden).map(subCommand=>subCommand.name)??[]}__name(getCommandSubcommandNames,"getCommandSubcommandNames");init_esbuild_shims();function levelLabel(level){switch(level){case"project":return t("Project");case"user":return t("User");case"extension":return t("Extension");case"bundled":return t("Bundled");default:{const _exhaustive=level;return _exhaustive}}}__name(levelLabel,"levelLabel");function skillOriginLabel(skill){if(skill.level==="extension"){return`(${extensionOwnerLabel({name:skill.extensionName,displayName:skill.extensionDisplayName})})`}return`(${levelLabel(skill.level)})`}__name(skillOriginLabel,"skillOriginLabel");init_esbuild_shims();async function diffAction(context){const{config}=context.services;if(!config){return{type:"message",messageType:"error",content:t("Configuration not available.")}}if(config.getShellExecutionSandbox?.()){return{type:"message",messageType:"error",content:"Diff preview unavailable in tool sandbox. Run git diff through the Shell tool."}}if(context.executionMode==="interactive"){return{type:"dialog",dialog:"diff"}}const cwd=config.getWorkingDir()||config.getProjectRoot();if(!cwd){return{type:"message",messageType:"error",content:t("Could not determine current working directory.")}}let result;try{result=await fetchGitDiff(cwd)}catch(error){return{type:"message",messageType:"error",content:`${t("Failed to compute git diff stats")}: ${error instanceof Error?error.message:String(error)}`}}if(!result){return{type:"message",messageType:"info",content:t("No diff available. Either this is not a git repository, HEAD is missing, or a merge/rebase/cherry-pick/revert is in progress.")}}if(result.stats.filesCount===0){return{type:"message",messageType:"info",content:t("Clean working tree \u2014 no changes against HEAD.")}}const model=buildDiffRenderModel(result);return{type:"message",messageType:"info",content:renderDiffModelText(model)}}__name(diffAction,"diffAction");function buildDiffRenderModel(result){const rows=[];for(const[filename,s]of result.perFileStats){rows.push(toRow(filename,s))}const hiddenCount=Math.max(0,result.stats.filesCount-rows.length);return{filesCount:result.stats.filesCount,linesAdded:result.stats.linesAdded,linesRemoved:result.stats.linesRemoved,rows,hiddenCount}}__name(buildDiffRenderModel,"buildDiffRenderModel");function toRow(filename,s){if(s.isBinary){return{filename,oldPath:s.oldPath,isBinary:true,isUntracked:Boolean(s.isUntracked),isDeleted:Boolean(s.isDeleted),truncated:false}}return{filename,oldPath:s.oldPath,added:s.added,removed:s.isUntracked?0:s.removed,isBinary:false,isUntracked:Boolean(s.isUntracked),isDeleted:Boolean(s.isDeleted),truncated:Boolean(s.truncated)}}__name(toRow,"toRow");function computeDiffColumnWidths(rows){let maxAdded=0;let maxRemoved=0;for(const r of rows){if(r.isBinary)continue;if((r.added??0)>maxAdded)maxAdded=r.added??0;if((r.removed??0)>maxRemoved)maxRemoved=r.removed??0}const addWidth=String(maxAdded).length;const remWidth=String(maxRemoved).length;const statColumnWidth=1+addWidth+1+1+remWidth;return{addWidth,remWidth,statColumnWidth}}__name(computeDiffColumnWidths,"computeDiffColumnWidths");function renderDiffModelText(model){const{filesCount,linesAdded,linesRemoved,rows,hiddenCount}=model;const header=filesCount===1?t("{{count}} file changed, +{{added}} / -{{removed}}",{count:String(filesCount),added:String(linesAdded),removed:String(linesRemoved)}):t("{{count}} files changed, +{{added}} / -{{removed}}",{count:String(filesCount),added:String(linesAdded),removed:String(linesRemoved)});const lines=formatRowsText(rows);const capNote=hiddenCount>0&&rows.length>0?`
|
|
4
4
|
${t("\u2026and {{hidden}} more (showing first {{shown}})",{hidden:String(hiddenCount),shown:String(rows.length)})}`:"";return lines.length>0?`${header}
|
|
5
5
|
${lines.join("\n")}${capNote}`:header}__name(renderDiffModelText,"renderDiffModelText");function formatRowsText(rows){if(rows.length===0)return[];const{addWidth,remWidth,statColumnWidth}=computeDiffColumnWidths(rows);const out=[];for(const r of rows){const safeName=sanitizeFilenameForDisplay(r.filename);const displayName=r.oldPath?`${sanitizeFilenameForDisplay(r.oldPath)} \u2192 ${safeName}`:safeName;if(r.isBinary){const suffix2=r.isUntracked?` ${t("(binary, new)")}`:r.isDeleted?` ${t("(binary, deleted)")}`:` ${t("(binary)")}`;out.push(` ${padMarker("~",statColumnWidth)} ${displayName}${suffix2}`);continue}const added=`+${String(r.added??0).padStart(addWidth)}`;const removed=`-${String(r.removed??0).padStart(remWidth)}`;let suffix="";if(r.isUntracked){suffix=r.truncated?` ${t("(new, partial)")}`:` ${t("(new)")}`}else if(r.isDeleted){suffix=` ${t("(deleted)")}`}out.push(` ${added} ${removed} ${displayName}${suffix}`)}return out}__name(formatRowsText,"formatRowsText");function padMarker(marker,width){if(marker.length>=width)return marker;return`${marker}${" ".repeat(width-marker.length)}`}__name(padMarker,"padMarker");var diffCommand={name:"diff",get description(){return t("Show working-tree change stats versus HEAD")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],action:diffAction};init_esbuild_shims();var INLINE_MATH_MAX_CHARS=1024;var INLINE_CODE_SPAN_PATTERN_SOURCE=String.raw`(?<!\`)(?<inlineCodeFence>\`+)(?!\`).+?(?<!\`)\k<inlineCodeFence>(?!\`)`;var INLINE_CODE_SPAN_RE=new RegExp(INLINE_CODE_SPAN_PATTERN_SOURCE,"g");function isEscapedAt(text,index){let slashCount=0;for(let cursor=index-1;cursor>=0&&text[cursor]==="\\";cursor-=1){slashCount+=1}return slashCount%2===1}__name(isEscapedAt,"isEscapedAt");function isUnescapedDollarAt(text,index){return text[index]==="$"&&!isEscapedAt(text,index)}__name(isUnescapedDollarAt,"isUnescapedDollarAt");function unescapeMarkdownDollars(text){return text.replace(/(\\+)\$/g,(_match,slashes)=>`${"\\".repeat(Math.floor(slashes.length/2))}$`)}__name(unescapeMarkdownDollars,"unescapeMarkdownDollars");function unescapeMarkdownBeforeMath(text){return unescapeMarkdownDollars(`${text}$`).slice(0,-1)}__name(unescapeMarkdownBeforeMath,"unescapeMarkdownBeforeMath");function readInlineMathSpan(text,index){if(!isUnescapedDollarAt(text,index)){return null}const previous=text[index-1]??"";const next=text[index+1]??"";if(/\w/.test(previous)||isUnescapedDollarAt(text,index-1)||!next||/[\s\d$]/.test(next)){return null}let closingIndex=index+1;while(closingIndex<text.length&&text[closingIndex]!=="\n"&&closingIndex-index-1<=INLINE_MATH_MAX_CHARS&&!isUnescapedDollarAt(text,closingIndex)){closingIndex+=1}if(!isUnescapedDollarAt(text,closingIndex)){return null}const content=text.slice(index+1,closingIndex);const following=text[closingIndex+1]??"";if(content.length>INLINE_MATH_MAX_CHARS||/\s$/.test(content)||/[\w$]/.test(following)){return null}return{content,index,raw:text.slice(index,closingIndex+1)}}__name(readInlineMathSpan,"readInlineMathSpan");function findNextInlineMath(text,fromIndex=0){for(let index=fromIndex;index<text.length;index+=1){const span=readInlineMathSpan(text,index);if(span){return span}}return null}__name(findNextInlineMath,"findNextInlineMath");function*mergeInlineMathMatches(text,markupRegex,enableInlineMath=true){markupRegex.lastIndex=0;const markupMatches=text.matchAll(markupRegex);let nextMarkup=markupMatches.next();let nextMath=enableInlineMath?findNextInlineMath(text):null;let cursor=0;while(!nextMarkup.done||nextMath){while(!nextMarkup.done&&(nextMarkup.value.index??0)<cursor){nextMarkup=markupMatches.next()}if(nextMath&&nextMath.index<cursor){nextMath=findNextInlineMath(text,cursor)}const markupIndex=nextMarkup.done?Number.POSITIVE_INFINITY:nextMarkup.value.index??0;const mathIndex=nextMath?.index??Number.POSITIVE_INFINITY;if(!nextMarkup.done&&markupIndex<=mathIndex){const match=nextMarkup.value;yield{kind:"markup",match};cursor=markupIndex+match[0].length;nextMarkup=markupMatches.next()}else if(nextMath){yield{kind:"math",span:nextMath};cursor=mathIndex+nextMath.raw.length;nextMath=findNextInlineMath(text,cursor)}}}__name(mergeInlineMathMatches,"mergeInlineMathMatches");function findInlineMathExpressions(text){const expressions=[];for(const token of mergeInlineMathMatches(text,INLINE_CODE_SPAN_RE)){if(token.kind==="math"){expressions.push(token.span.content)}}return expressions}__name(findInlineMathExpressions,"findInlineMathExpressions");function readInlineMathSpanAt(text,index){return readInlineMathSpan(text,index)?.raw??null}__name(readInlineMathSpanAt,"readInlineMathSpanAt");export{formatRelativeTime,formatClockTime,formatTokenCount,formatPercentageUsed,contextUsageLabel,formatDuration,INLINE_CODE_SPAN_PATTERN_SOURCE,unescapeMarkdownDollars,unescapeMarkdownBeforeMath,mergeInlineMathMatches,findInlineMathExpressions,readInlineMathSpanAt,formatCompressionTokenCount,getCompressionStatusText,getCompressionFailureStatusText,getSystemInfoFields,redactProxy,calculateErrorRate,calculateAverageLatency,calculateCacheHitRate,computeSessionStats,calculateCost,billableOutputTokens,commandRestrictionNames,getEffectiveSupportedModes,filterCommandsForMode,extensionOwnerLabel,MAX_EXTENSION_OWNER_LABEL_WIDTH,getCommandSourceBadge,getCommandSourceGroup,formatSupportedModes,getCommandDisplayName,getCommandSubcommandNames,levelLabel,skillOriginLabel,computeDiffColumnWidths,diffCommand};
|
|
6
6
|
/**
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{loadUndici}from"./chunk-XKSB7VTV.js";import{updateEventEmitter}from"./chunk-VDUNIK4I.js";import{require_semver}from"./chunk-YZUKMJW7.js";import{hasStandaloneArchiveLayout,standaloneRuntimePaths}from"./chunk-26MNTKT2.js";import{t}from"./chunk-ABJGFEES.js";import{So}from"./chunk-Z5XENA4A.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{createHash}from"node:crypto";import*as fs from"node:fs";import*as os from"node:os";import*as path from"node:path";import{Readable,Transform}from"node:stream";import{spawn,execFile}from"node:child_process";import{pipeline}from"node:stream/promises";var import_semver=__toESM(require_semver(),1);init_esbuild_shims();import{createPublicKey,verify}from"node:crypto";var RELEASE_PUBLIC_KEY_DER_B64="MCowBQYDK2VwAyEAr9WRFLDauibZQKCe1oKfuFZn6zRMaEkD5+KVqN6mKM4=";function verifySignature(sha256sumsContent,signatureBase64){const key=createPublicKey({key:Buffer.from(RELEASE_PUBLIC_KEY_DER_B64,"base64"),format:"der",type:"spki"});const signature=Buffer.from(signatureBase64,"base64");if(signature.length!==64){throw new Error(`Invalid signature length: expected 64 bytes, got ${signature.length}`)}const valid=verify(null,Buffer.from(sha256sumsContent),key,signature);if(!valid){throw new Error("SHA256SUMS signature verification failed \u2014 possible tampering detected")}}__name(verifySignature,"verifySignature");var debugLogger=createDebugLogger("STANDALONE_UPDATE");var OSS_BASE="https://qwen-code-assets.oss-cn-hangzhou.aliyuncs.com/releases/qwen-code";var GITHUB_BASE="https://github.com/QwenLM/qwen-code/releases/download";var FETCH_TIMEOUT_MS=3e4;var ARCHIVE_TIMEOUT_MS=3e5;var VALID_TARGETS=new Set(["darwin-arm64","darwin-x64","linux-arm64","linux-x64","win-x64"]);var SEMVER_RE=/^v?\d+\.\d+\.\d+(-[\w.]+)?$/;function isConcreteVersion(version){return SEMVER_RE.test(version)&&import_semver.default.valid(version)!==null}__name(isConcreteVersion,"isConcreteVersion");function normalizeVersion(version){if(!isConcreteVersion(version)){throw new Error(`Invalid version format: ${version}`)}return version.startsWith("v")?version:`v${version}`}__name(normalizeVersion,"normalizeVersion");function validateTarget(target){if(!VALID_TARGETS.has(target)){throw new Error(`Unknown target: ${target}`)}}__name(validateTarget,"validateTarget");function archiveFilename(target,runtime){const ext=target.startsWith("win")?"zip":"tar.gz";const suffix=runtime==="bun"?"-opentui-preview":"";return`qwen-code-${target}${suffix}.${ext}`}__name(archiveFilename,"archiveFilename");function escapePS(s){return s.replace(/'/g,"''")}__name(escapePS,"escapePS");function resolveUpdateBaseUrl(){const value=process.env["QWEN_UPDATE_BASE_URL"]?.trim();if(!value)return void 0;const invalidUrl=__name(()=>new Error("QWEN_UPDATE_BASE_URL must be an absolute HTTPS URL without credentials, query parameters, or a fragment."),"invalidUrl");let url;try{url=new URL(value)}catch{throw invalidUrl()}if(!/^https:\/\//i.test(value)||url.username||url.password||/[?#\s]/.test(value)){throw invalidUrl()}return url.href.replace(/\/+$/,"")}__name(resolveUpdateBaseUrl,"resolveUpdateBaseUrl");async function tryFetch(url,timeoutMs=FETCH_TIMEOUT_MS){try{const{fetch}=await loadUndici();const res=await fetch(url,{signal:AbortSignal.timeout(timeoutMs)});if(res.ok)return{response:res};await res.body?.cancel().catch(()=>{});return{error:new Error(`HTTP ${res.status} ${res.statusText}`)}}catch(err){const error=err instanceof Error?err:new Error(String(err));debugLogger.debug(`Fetch failed for ${url}: ${error.message}`);return{error}}}__name(tryFetch,"tryFetch");async function downloadWithFallback(versionPath,filename,timeoutMs=FETCH_TIMEOUT_MS,baseUrl){if(baseUrl){const result=await tryFetch(`${baseUrl}/${versionPath}/${filename}`,timeoutMs);if(result.response)return result.response;throw new Error(`Failed to download ${filename} from QWEN_UPDATE_BASE_URL: ${result.error.message}`)}const ossUrl=`${OSS_BASE}/${versionPath}/${filename}`;const ossResult=await tryFetch(ossUrl,timeoutMs);if(ossResult.response)return ossResult.response;const ghUrl=`${GITHUB_BASE}/${versionPath}/${filename}`;const ghResult=await tryFetch(ghUrl,timeoutMs);if(ghResult.response)return ghResult.response;throw new Error(`Failed to download ${filename}: OSS (${ossResult.error?.message??"unknown"}), GitHub (${ghResult.error?.message??"unknown"})`)}__name(downloadWithFallback,"downloadWithFallback");async function verifyChecksum(actualHash,filename,versionPath,baseUrl){const response=await downloadWithFallback(versionPath,"SHA256SUMS",FETCH_TIMEOUT_MS,baseUrl);const text=await response.text();const requireSig=process.env["QWEN_REQUIRE_SIGNATURE"]==="1";let sigResponse;try{sigResponse=await downloadWithFallback(versionPath,"SHA256SUMS.sig",FETCH_TIMEOUT_MS,baseUrl)}catch(err){debugLogger.debug("SHA256SUMS.sig not available:",err)}if(sigResponse){const sigContent=await sigResponse.text();verifySignature(text,sigContent.trim());debugLogger.info("SHA256SUMS signature verified.")}else if(requireSig){throw new Error("SHA256SUMS.sig not found and QWEN_REQUIRE_SIGNATURE=1 is set")}else{debugLogger.warn("SHA256SUMS.sig not available \u2014 update integrity relies on SHA256 checksum only. Set QWEN_REQUIRE_SIGNATURE=1 to enforce signature verification.")}const expectedLine=text.split("\n").find(line=>{const parts=line.trim().split(/\s+/);if(parts.length<2)return false;const name=parts[parts.length-1].replace(/^\*/,"");return name===filename});if(!expectedLine){throw new Error(`No checksum found for ${filename} in SHA256SUMS`)}const expectedHash=expectedLine.trim().split(/\s+/)[0];if(actualHash!==expectedHash){throw new Error(`Checksum mismatch: expected ${expectedHash}, got ${actualHash}`)}}__name(verifyChecksum,"verifyChecksum");var MAX_DOWNLOAD_BYTES=512*1024*1024;async function downloadToFile(versionPath,filename,destPath,baseUrl){const response=await downloadWithFallback(versionPath,filename,ARCHIVE_TIMEOUT_MS,baseUrl);const body=response.body;if(!body)throw new Error("Empty response body");const contentLength=response.headers.get("content-length");if(contentLength&&parseInt(contentLength,10)>MAX_DOWNLOAD_BYTES){await body.cancel().catch(()=>{});throw new Error(`Download too large: ${contentLength} bytes exceeds ${MAX_DOWNLOAD_BYTES} limit`)}const hash=createHash("sha256");let bytesWritten=0;const dest=fs.createWriteStream(destPath);const sizeGuard=new Transform({transform(chunk,_encoding,callback){bytesWritten+=chunk.length;if(bytesWritten>MAX_DOWNLOAD_BYTES){callback(new Error(`Download exceeded ${MAX_DOWNLOAD_BYTES} byte limit`))}else{hash.update(chunk);callback(null,chunk)}}});await pipeline(Readable.fromWeb(body),sizeGuard,dest);return hash.digest("hex")}__name(downloadToFile,"downloadToFile");function isPathInside(base,candidate){const rel=path.relative(base,candidate);return rel===""||!!rel&&rel!==".."&&!rel.startsWith(`..${path.sep}`)&&!path.isAbsolute(rel)}__name(isPathInside,"isPathInside");function normalizeTarEntryPath(entryPath){const parts=entryPath.split(/[\\/]+/).filter(part=>part&&part!==".");if(parts.length===0||parts.includes("..")){return null}return parts.join("/")}__name(normalizeTarEntryPath,"normalizeTarEntryPath");function isSafeTarLinkTarget(entryPath,linkPath,resolvedDest){if(path.posix.isAbsolute(linkPath)||path.win32.isAbsolute(linkPath)){return false}const normalizedEntryPath=normalizeTarEntryPath(entryPath);if(!normalizedEntryPath){return false}const archiveRoot=normalizedEntryPath.split("/")[0];const linkTarget=path.resolve(resolvedDest,path.posix.dirname(normalizedEntryPath),linkPath);return isPathInside(path.join(resolvedDest,archiveRoot),linkTarget)}__name(isSafeTarLinkTarget,"isSafeTarLinkTarget");function getTarEntryType(entry){if("type"in entry)return entry.type;if("isFile"in entry&&entry.isFile())return"File";if("isDirectory"in entry&&entry.isDirectory())return"Directory";if("isSymbolicLink"in entry&&entry.isSymbolicLink()){return"SymbolicLink"}return void 0}__name(getTarEntryType,"getTarEntryType");function isSafeTarEntry(entryPath,entry,resolvedDest){if(!isSafeTarEntryPath(entryPath))return false;const entryType=getTarEntryType(entry);const linkPath="linkpath"in entry?entry.linkpath:void 0;if(entryType!=="File"&&entryType!=="Directory"&&entryType!=="SymbolicLink"){return false}if(entryType==="SymbolicLink"){if(linkPath===void 0)return false;return isSafeTarLinkTarget(entryPath,String(linkPath),resolvedDest)}return true}__name(isSafeTarEntry,"isSafeTarEntry");function isAlreadyExistsError(err){return typeof err==="object"&&err!==null&&"code"in err&&err.code==="EEXIST"}__name(isAlreadyExistsError,"isAlreadyExistsError");function validateExtractedPaths(resolvedDest,options={}){const entries=fs.readdirSync(resolvedDest,{recursive:true,withFileTypes:true});for(const entry of entries){if(options.symlinksOnly&&!entry.isSymbolicLink()){continue}const fullPath=path.join(String(entry.parentPath||entry.path),entry.name);let resolved;try{resolved=fs.realpathSync(fullPath)}catch(err){fs.rmSync(resolvedDest,{recursive:true,force:true});const detail=err instanceof Error?err.message:String(err);throw new Error(`Invalid archive entry: ${entry.name} could not be resolved (${detail})`)}if(!isPathInside(resolvedDest,resolved)){fs.rmSync(resolvedDest,{recursive:true,force:true});throw new Error(`Path traversal detected in archive: ${entry.name} resolves to ${resolved}`)}}}__name(validateExtractedPaths,"validateExtractedPaths");function isSafeTarEntryPath(entryPath){if(entryPath.length===0)return false;if(path.posix.isAbsolute(entryPath)||path.win32.isAbsolute(entryPath)){return false}return normalizeTarEntryPath(entryPath)!==null}__name(isSafeTarEntryPath,"isSafeTarEntryPath");async function extractArchive(archivePath,destDir,target){fs.mkdirSync(destDir,{recursive:true});if(target.startsWith("win")){await new Promise((resolve2,reject)=>{const ps=spawn("powershell.exe",["-NoProfile","-Command",`Expand-Archive -Path '${escapePS(archivePath)}' -DestinationPath '${escapePS(destDir)}' -Force`],{stdio:"ignore"});ps.on("close",code=>code===0?resolve2():reject(new Error(`Expand-Archive exited with code ${code}`)));ps.on("error",reject)});const resolvedDest=fs.realpathSync(destDir);validateExtractedPaths(resolvedDest)}else{const resolvedDest=fs.realpathSync(destDir);await So({file:archivePath,cwd:destDir,preservePaths:false,filter:__name((p,entry)=>isSafeTarEntry(p,entry,resolvedDest),"filter")});validateExtractedPaths(fs.realpathSync(destDir),{symlinksOnly:true})}}__name(extractArchive,"extractArchive");function spawnAndCapture(command,args,timeoutMs,cwd){const env={...process.env};for(const key of Object.keys(env)){if(/^(NODE_OPTIONS|BUN_OPTIONS|CLI_VERSION|QWEN_CODE_RELAUNCH_ARGS)$/i.test(key))delete env[key]}return new Promise((resolve2,reject)=>{let settled=false;const child=execFile(command,args,{env,cwd,timeout:timeoutMs,killSignal:"SIGKILL",maxBuffer:64*1024},(err,out,stderr)=>{if(settled)return;settled=true;if(err&&("killed"in err&&err.killed||"signal"in err&&err.signal)){reject(new Error("Smoke test timed out"));return}if(err){const exitCode="code"in err&&typeof err.code==="number"?err.code:1;resolve2({exitCode,stdout:out||"",stderr:stderr||""});return}resolve2({exitCode:0,stdout:out||"",stderr:stderr||""})});child.on("error",()=>{if(settled)return;settled=true;reject(new Error("Smoke test failed: unable to start new binary"))})})}__name(spawnAndCapture,"spawnAndCapture");async function smokeTest(newInstallDir,target,runtime,expectedVersion){const resolvedInstallDir=path.resolve(newInstallDir);const interpreter=target.startsWith("win")?path.join(resolvedInstallDir,runtime,`${runtime}.exe`):path.join(resolvedInstallDir,runtime,"bin",runtime);const cliBin=path.join(resolvedInstallDir,"lib","cli.js");if(!fs.existsSync(interpreter)){throw new Error(`Smoke test failed: ${runtime} binary not found at ${interpreter}`)}if(!fs.existsSync(cliBin)){throw new Error(`Smoke test failed: CLI entry not found at ${cliBin}`)}const cwd=fs.mkdtempSync(path.join(os.tmpdir(),"qwen-code-smoke-"));try{const identity=await spawnAndCapture(interpreter,["-e",'console.log(JSON.stringify({runtime:process.versions.bun?"bun":"node",platform:process.platform,arch:process.arch}))'],1e4,cwd);let actual;try{actual=JSON.parse(identity.stdout)}catch{throw new Error("Smoke test failed: invalid interpreter identity")}const[platform2,arch2]=target.split("-");if(identity.exitCode!==0||!actual||typeof actual!=="object"||Array.isArray(actual)||Reflect.get(actual,"runtime")!==runtime||Reflect.get(actual,"platform")!==(platform2==="win"?"win32":platform2)||Reflect.get(actual,"arch")!==arch2){throw new Error("Smoke test failed: interpreter identity does not match the expected runtime and target")}const{exitCode,stdout}=await spawnAndCapture(interpreter,[cliBin,"--version"],1e4,cwd);if(exitCode!==0){throw new Error(`Smoke test failed: new binary exited with code ${exitCode}`)}const version=stdout.trim();if(!SEMVER_RE.test(version)){throw new Error("Smoke test failed: unexpected version output")}let versionMatches;try{versionMatches=import_semver.default.eq(version,expectedVersion)}catch{versionMatches=false}if(!versionMatches){throw new Error("Smoke test failed: CLI version does not match the expected version")}const launcher=await spawnAndCapture(interpreter,[path.join(resolvedInstallDir,"lib","cli-entry.js"),"--help"],1e4,cwd);if(launcher.exitCode!==0){throw new Error("Smoke test failed: launcher could not load CLI")}debugLogger.info(`Smoke test passed: ${version}`)}finally{try{fs.rmSync(cwd,{recursive:true,force:true})}catch{debugLogger.warn("Could not remove the smoke test temporary directory")}}}__name(smokeTest,"smokeTest");function pendingSwapError(standaloneDir){return new Error(`A previous update left a pending swap at ${standaloneDir}.new. If no qwen-update.bat process is running, remove the pending swap and .qwen-update.lock, then try again.`)}__name(pendingSwapError,"pendingSwapError");function deferredMarkerError(standaloneDir){return new Error(`A previous update left a deferred-swap marker at ${standaloneDir}.deferred. If no qwen-update.bat process is running, remove the marker, the pending swap at ${standaloneDir}.new, and .qwen-update.lock, then try again.`)}__name(deferredMarkerError,"deferredMarkerError");var PENDING_SWAP_STALE_MS=15*60*1e3;function checkDeferredSwap(standaloneDir){const deferredMarker=`${standaloneDir}.deferred`;let swapProvenDead=false;if(fs.existsSync(deferredMarker)){let marker;try{marker=fs.readFileSync(deferredMarker,"utf-8").trim()}catch{throw deferredMarkerError(standaloneDir)}const batPid=parseInt(marker,10);if(!Number.isSafeInteger(batPid)||batPid<=0||batPid>2147483647){throw deferredMarkerError(standaloneDir)}if(!isProcessProvablyGone(batPid)){let markerStale=false;try{markerStale=Date.now()-fs.statSync(deferredMarker).mtimeMs>PENDING_SWAP_STALE_MS}catch{}if(markerStale){throw new Error(`A previous update left a deferred-swap marker at ${standaloneDir}.deferred. If a qwen-update.bat process is still running, end it first; then remove the marker, the pending swap at ${standaloneDir}.new, and .qwen-update.lock, and try again.`)}throw new Error("A previous update is still being applied. Please wait a moment and try again.")}swapProvenDead=true;try{fs.unlinkSync(deferredMarker)}catch{}}const pendingDir=`${standaloneDir}.new`;if(fs.existsSync(pendingDir)){if(!swapProvenDead){let stale=false;try{stale=Date.now()-fs.statSync(pendingDir).mtimeMs>PENDING_SWAP_STALE_MS}catch{}if(!stale){throw pendingSwapError(standaloneDir)}}try{fs.rmSync(pendingDir,{recursive:true,force:true})}catch(err){const reason=err instanceof Error?err.message:String(err);throw new Error(`A previous update left a pending swap at ${pendingDir} that could not be removed (${reason}). Remove it and .qwen-update.lock, then try again.`)}}}__name(checkDeferredSwap,"checkDeferredSwap");function acquireLock(lockPath,standaloneDir){try{fs.writeFileSync(lockPath,String(process.pid),{flag:"wx"});if(standaloneDir){checkDeferredSwap(standaloneDir)}return true}catch(fastPathErr){if(fastPathErr instanceof Error&&(fastPathErr.message.startsWith("A previous update")||fastPathErr.message.includes("pending swap"))){try{fs.unlinkSync(lockPath)}catch{}throw fastPathErr}let pidStr;try{pidStr=fs.readFileSync(lockPath,"utf-8").trim()}catch{return false}const pid=parseInt(pidStr,10);if(!Number.isNaN(pid)&&isProcessAlive(pid)){return false}if(standaloneDir){checkDeferredSwap(standaloneDir)}try{fs.unlinkSync(lockPath);fs.writeFileSync(lockPath,String(process.pid),{flag:"wx"});return true}catch{return false}}}__name(acquireLock,"acquireLock");function releaseLock(lockPath){try{fs.unlinkSync(lockPath)}catch{}}__name(releaseLock,"releaseLock");function cleanupEmptyStandaloneDir(standaloneDir){const manifestPath=path.join(standaloneDir,"manifest.json");if(fs.existsSync(standaloneDir)&&!fs.existsSync(manifestPath)){fs.rmSync(standaloneDir,{recursive:true,force:true})}}__name(cleanupEmptyStandaloneDir,"cleanupEmptyStandaloneDir");var UNSAFE_SHELL_CHARS=/[\0\n\r]/;var UNSAFE_CMD_CHARS=/[&|<>^%!"`\n\r]/;function assertSafeForSingleQuotedShellPath(p,context){if(UNSAFE_SHELL_CHARS.test(p)){throw new Error(`${context} contains characters unsafe for shell embedding: ${p}`)}}__name(assertSafeForSingleQuotedShellPath,"assertSafeForSingleQuotedShellPath");function shellQuoteForSh(p){return`'${p.replace(/'/g,"'\\''")}'`}__name(shellQuoteForSh,"shellQuoteForSh");function shellQuoteForFish(p){return shellQuoteForSh(p)}__name(shellQuoteForFish,"shellQuoteForFish");function isProcessAlive(pid){try{process.kill(pid,0);return true}catch{return false}}__name(isProcessAlive,"isProcessAlive");function isProcessProvablyGone(pid){try{process.kill(pid,0);return false}catch(err){return err.code==="ESRCH"}}__name(isProcessProvablyGone,"isProcessProvablyGone");function atomicReplace(standaloneDir,newDir,lockPath){const oldDir=`${standaloneDir}.old`;const pendingDir=`${standaloneDir}.new`;if(fs.existsSync(oldDir)){fs.rmSync(oldDir,{recursive:true,force:true})}if(os.platform()==="win32"){if(UNSAFE_CMD_CHARS.test(standaloneDir)||UNSAFE_CMD_CHARS.test(oldDir)||UNSAFE_CMD_CHARS.test(pendingDir)){throw new Error("Installation path contains characters unsafe for deferred update script")}if(fs.existsSync(pendingDir)){fs.rmSync(pendingDir,{recursive:true,force:true})}fs.renameSync(newDir,pendingDir);const lockFile=lockPath;const deferredMarker=`${standaloneDir}.deferred`;const logFile=path.join(path.dirname(standaloneDir),"qwen-update.log");const script=["@echo off","set /a TRIES=0",":wait","set /a TRIES+=1","if %TRIES% GTR 30 goto proceed",`tasklist /FI "PID eq ${process.pid}" 2>nul | find "${process.pid}" >nul && (timeout /t 1 >nul & goto wait)`,...process.env["QWEN_CODE_LAUNCHER_PID"]?.match(/^\d+$/)?["set /a LAUNCHER_TRIES=0",":wait_launcher","set /a LAUNCHER_TRIES+=1","if %LAUNCHER_TRIES% GTR 30 goto proceed",`tasklist /FI "PID eq ${process.env["QWEN_CODE_LAUNCHER_PID"]}" 2>nul | find "${process.env["QWEN_CODE_LAUNCHER_PID"]}" >nul && (timeout /t 1 >nul & goto wait_launcher)`]:[],":proceed",`echo [%DATE% %TIME%] starting swap >> "${logFile}"`,`move /Y "${standaloneDir}" "${oldDir}"`,"if errorlevel 1 goto move1_failed",`move /Y "${pendingDir}" "${standaloneDir}"`,"if errorlevel 1 goto move2_failed",`echo [%DATE% %TIME%] swap completed >> "${logFile}"`,"goto cleanup",":move1_failed",`echo [%DATE% %TIME%] ERROR: failed to rename install to .old (errorlevel %errorlevel%) >> "${logFile}"`,"goto cleanup",":move2_failed",`echo [%DATE% %TIME%] ERROR: failed to promote .new; rolling back >> "${logFile}"`,`move /Y "${oldDir}" "${standaloneDir}"`,"if errorlevel 1 (",` echo [%DATE% %TIME%] CRITICAL: rollback also failed; manual recovery: move "${oldDir}" "${standaloneDir}" >> "${logFile}"`,") else (",` echo [%DATE% %TIME%] rollback succeeded >> "${logFile}"`,")",":cleanup",`del /F /Q "${deferredMarker}" 2>nul`,`del /F /Q "${lockFile}" 2>nul`,`del "%~f0"`].join("\r\n");const scriptPath=path.join(path.dirname(standaloneDir),"qwen-update.bat");fs.writeFileSync(scriptPath,script);const child=spawn("cmd.exe",["/c",scriptPath],{detached:true,stdio:"ignore",windowsHide:true});child.on("error",err=>{debugLogger.warn("Deferred bat script failed to spawn:",err)});child.unref();if(!child.pid){throw new Error("Failed to spawn deferred update script. Update was not applied.")}fs.writeFileSync(deferredMarker,String(child.pid));return"deferred"}else{fs.renameSync(standaloneDir,oldDir);try{fs.renameSync(newDir,standaloneDir)}catch(promoteErr){try{fs.renameSync(oldDir,standaloneDir)}catch(rollbackErr){const detail=`Standalone update failed AND rollback failed.
|
|
3
|
+
import{loadUndici}from"./chunk-XKSB7VTV.js";import{updateEventEmitter}from"./chunk-VDUNIK4I.js";import{require_semver}from"./chunk-YZUKMJW7.js";import{hasStandaloneArchiveLayout,standaloneRuntimePaths}from"./chunk-26MNTKT2.js";import{t}from"./chunk-NO7VTKRL.js";import{So}from"./chunk-T3CQ72HC.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{createHash}from"node:crypto";import*as fs from"node:fs";import*as os from"node:os";import*as path from"node:path";import{Readable,Transform}from"node:stream";import{spawn,execFile}from"node:child_process";import{pipeline}from"node:stream/promises";var import_semver=__toESM(require_semver(),1);init_esbuild_shims();import{createPublicKey,verify}from"node:crypto";var RELEASE_PUBLIC_KEY_DER_B64="MCowBQYDK2VwAyEAr9WRFLDauibZQKCe1oKfuFZn6zRMaEkD5+KVqN6mKM4=";function verifySignature(sha256sumsContent,signatureBase64){const key=createPublicKey({key:Buffer.from(RELEASE_PUBLIC_KEY_DER_B64,"base64"),format:"der",type:"spki"});const signature=Buffer.from(signatureBase64,"base64");if(signature.length!==64){throw new Error(`Invalid signature length: expected 64 bytes, got ${signature.length}`)}const valid=verify(null,Buffer.from(sha256sumsContent),key,signature);if(!valid){throw new Error("SHA256SUMS signature verification failed \u2014 possible tampering detected")}}__name(verifySignature,"verifySignature");var debugLogger=createDebugLogger("STANDALONE_UPDATE");var OSS_BASE="https://qwen-code-assets.oss-cn-hangzhou.aliyuncs.com/releases/qwen-code";var GITHUB_BASE="https://github.com/QwenLM/qwen-code/releases/download";var FETCH_TIMEOUT_MS=3e4;var ARCHIVE_TIMEOUT_MS=3e5;var VALID_TARGETS=new Set(["darwin-arm64","darwin-x64","linux-arm64","linux-x64","win-x64"]);var SEMVER_RE=/^v?\d+\.\d+\.\d+(-[\w.]+)?$/;function isConcreteVersion(version){return SEMVER_RE.test(version)&&import_semver.default.valid(version)!==null}__name(isConcreteVersion,"isConcreteVersion");function normalizeVersion(version){if(!isConcreteVersion(version)){throw new Error(`Invalid version format: ${version}`)}return version.startsWith("v")?version:`v${version}`}__name(normalizeVersion,"normalizeVersion");function validateTarget(target){if(!VALID_TARGETS.has(target)){throw new Error(`Unknown target: ${target}`)}}__name(validateTarget,"validateTarget");function archiveFilename(target,runtime){const ext=target.startsWith("win")?"zip":"tar.gz";const suffix=runtime==="bun"?"-opentui-preview":"";return`qwen-code-${target}${suffix}.${ext}`}__name(archiveFilename,"archiveFilename");function escapePS(s){return s.replace(/'/g,"''")}__name(escapePS,"escapePS");function resolveUpdateBaseUrl(){const value=process.env["QWEN_UPDATE_BASE_URL"]?.trim();if(!value)return void 0;const invalidUrl=__name(()=>new Error("QWEN_UPDATE_BASE_URL must be an absolute HTTPS URL without credentials, query parameters, or a fragment."),"invalidUrl");let url;try{url=new URL(value)}catch{throw invalidUrl()}if(!/^https:\/\//i.test(value)||url.username||url.password||/[?#\s]/.test(value)){throw invalidUrl()}return url.href.replace(/\/+$/,"")}__name(resolveUpdateBaseUrl,"resolveUpdateBaseUrl");async function tryFetch(url,timeoutMs=FETCH_TIMEOUT_MS){try{const{fetch}=await loadUndici();const res=await fetch(url,{signal:AbortSignal.timeout(timeoutMs)});if(res.ok)return{response:res};await res.body?.cancel().catch(()=>{});return{error:new Error(`HTTP ${res.status} ${res.statusText}`)}}catch(err){const error=err instanceof Error?err:new Error(String(err));debugLogger.debug(`Fetch failed for ${url}: ${error.message}`);return{error}}}__name(tryFetch,"tryFetch");async function downloadWithFallback(versionPath,filename,timeoutMs=FETCH_TIMEOUT_MS,baseUrl){if(baseUrl){const result=await tryFetch(`${baseUrl}/${versionPath}/${filename}`,timeoutMs);if(result.response)return result.response;throw new Error(`Failed to download ${filename} from QWEN_UPDATE_BASE_URL: ${result.error.message}`)}const ossUrl=`${OSS_BASE}/${versionPath}/${filename}`;const ossResult=await tryFetch(ossUrl,timeoutMs);if(ossResult.response)return ossResult.response;const ghUrl=`${GITHUB_BASE}/${versionPath}/${filename}`;const ghResult=await tryFetch(ghUrl,timeoutMs);if(ghResult.response)return ghResult.response;throw new Error(`Failed to download ${filename}: OSS (${ossResult.error?.message??"unknown"}), GitHub (${ghResult.error?.message??"unknown"})`)}__name(downloadWithFallback,"downloadWithFallback");async function verifyChecksum(actualHash,filename,versionPath,baseUrl){const response=await downloadWithFallback(versionPath,"SHA256SUMS",FETCH_TIMEOUT_MS,baseUrl);const text=await response.text();const requireSig=process.env["QWEN_REQUIRE_SIGNATURE"]==="1";let sigResponse;try{sigResponse=await downloadWithFallback(versionPath,"SHA256SUMS.sig",FETCH_TIMEOUT_MS,baseUrl)}catch(err){debugLogger.debug("SHA256SUMS.sig not available:",err)}if(sigResponse){const sigContent=await sigResponse.text();verifySignature(text,sigContent.trim());debugLogger.info("SHA256SUMS signature verified.")}else if(requireSig){throw new Error("SHA256SUMS.sig not found and QWEN_REQUIRE_SIGNATURE=1 is set")}else{debugLogger.warn("SHA256SUMS.sig not available \u2014 update integrity relies on SHA256 checksum only. Set QWEN_REQUIRE_SIGNATURE=1 to enforce signature verification.")}const expectedLine=text.split("\n").find(line=>{const parts=line.trim().split(/\s+/);if(parts.length<2)return false;const name=parts[parts.length-1].replace(/^\*/,"");return name===filename});if(!expectedLine){throw new Error(`No checksum found for ${filename} in SHA256SUMS`)}const expectedHash=expectedLine.trim().split(/\s+/)[0];if(actualHash!==expectedHash){throw new Error(`Checksum mismatch: expected ${expectedHash}, got ${actualHash}`)}}__name(verifyChecksum,"verifyChecksum");var MAX_DOWNLOAD_BYTES=512*1024*1024;async function downloadToFile(versionPath,filename,destPath,baseUrl){const response=await downloadWithFallback(versionPath,filename,ARCHIVE_TIMEOUT_MS,baseUrl);const body=response.body;if(!body)throw new Error("Empty response body");const contentLength=response.headers.get("content-length");if(contentLength&&parseInt(contentLength,10)>MAX_DOWNLOAD_BYTES){await body.cancel().catch(()=>{});throw new Error(`Download too large: ${contentLength} bytes exceeds ${MAX_DOWNLOAD_BYTES} limit`)}const hash=createHash("sha256");let bytesWritten=0;const dest=fs.createWriteStream(destPath);const sizeGuard=new Transform({transform(chunk,_encoding,callback){bytesWritten+=chunk.length;if(bytesWritten>MAX_DOWNLOAD_BYTES){callback(new Error(`Download exceeded ${MAX_DOWNLOAD_BYTES} byte limit`))}else{hash.update(chunk);callback(null,chunk)}}});await pipeline(Readable.fromWeb(body),sizeGuard,dest);return hash.digest("hex")}__name(downloadToFile,"downloadToFile");function isPathInside(base,candidate){const rel=path.relative(base,candidate);return rel===""||!!rel&&rel!==".."&&!rel.startsWith(`..${path.sep}`)&&!path.isAbsolute(rel)}__name(isPathInside,"isPathInside");function normalizeTarEntryPath(entryPath){const parts=entryPath.split(/[\\/]+/).filter(part=>part&&part!==".");if(parts.length===0||parts.includes("..")){return null}return parts.join("/")}__name(normalizeTarEntryPath,"normalizeTarEntryPath");function isSafeTarLinkTarget(entryPath,linkPath,resolvedDest){if(path.posix.isAbsolute(linkPath)||path.win32.isAbsolute(linkPath)){return false}const normalizedEntryPath=normalizeTarEntryPath(entryPath);if(!normalizedEntryPath){return false}const archiveRoot=normalizedEntryPath.split("/")[0];const linkTarget=path.resolve(resolvedDest,path.posix.dirname(normalizedEntryPath),linkPath);return isPathInside(path.join(resolvedDest,archiveRoot),linkTarget)}__name(isSafeTarLinkTarget,"isSafeTarLinkTarget");function getTarEntryType(entry){if("type"in entry)return entry.type;if("isFile"in entry&&entry.isFile())return"File";if("isDirectory"in entry&&entry.isDirectory())return"Directory";if("isSymbolicLink"in entry&&entry.isSymbolicLink()){return"SymbolicLink"}return void 0}__name(getTarEntryType,"getTarEntryType");function isSafeTarEntry(entryPath,entry,resolvedDest){if(!isSafeTarEntryPath(entryPath))return false;const entryType=getTarEntryType(entry);const linkPath="linkpath"in entry?entry.linkpath:void 0;if(entryType!=="File"&&entryType!=="Directory"&&entryType!=="SymbolicLink"){return false}if(entryType==="SymbolicLink"){if(linkPath===void 0)return false;return isSafeTarLinkTarget(entryPath,String(linkPath),resolvedDest)}return true}__name(isSafeTarEntry,"isSafeTarEntry");function isAlreadyExistsError(err){return typeof err==="object"&&err!==null&&"code"in err&&err.code==="EEXIST"}__name(isAlreadyExistsError,"isAlreadyExistsError");function validateExtractedPaths(resolvedDest,options={}){const entries=fs.readdirSync(resolvedDest,{recursive:true,withFileTypes:true});for(const entry of entries){if(options.symlinksOnly&&!entry.isSymbolicLink()){continue}const fullPath=path.join(String(entry.parentPath||entry.path),entry.name);let resolved;try{resolved=fs.realpathSync(fullPath)}catch(err){fs.rmSync(resolvedDest,{recursive:true,force:true});const detail=err instanceof Error?err.message:String(err);throw new Error(`Invalid archive entry: ${entry.name} could not be resolved (${detail})`)}if(!isPathInside(resolvedDest,resolved)){fs.rmSync(resolvedDest,{recursive:true,force:true});throw new Error(`Path traversal detected in archive: ${entry.name} resolves to ${resolved}`)}}}__name(validateExtractedPaths,"validateExtractedPaths");function isSafeTarEntryPath(entryPath){if(entryPath.length===0)return false;if(path.posix.isAbsolute(entryPath)||path.win32.isAbsolute(entryPath)){return false}return normalizeTarEntryPath(entryPath)!==null}__name(isSafeTarEntryPath,"isSafeTarEntryPath");async function extractArchive(archivePath,destDir,target){fs.mkdirSync(destDir,{recursive:true});if(target.startsWith("win")){await new Promise((resolve2,reject)=>{const ps=spawn("powershell.exe",["-NoProfile","-Command",`Expand-Archive -Path '${escapePS(archivePath)}' -DestinationPath '${escapePS(destDir)}' -Force`],{stdio:"ignore"});ps.on("close",code=>code===0?resolve2():reject(new Error(`Expand-Archive exited with code ${code}`)));ps.on("error",reject)});const resolvedDest=fs.realpathSync(destDir);validateExtractedPaths(resolvedDest)}else{const resolvedDest=fs.realpathSync(destDir);await So({file:archivePath,cwd:destDir,preservePaths:false,filter:__name((p,entry)=>isSafeTarEntry(p,entry,resolvedDest),"filter")});validateExtractedPaths(fs.realpathSync(destDir),{symlinksOnly:true})}}__name(extractArchive,"extractArchive");function spawnAndCapture(command,args,timeoutMs,cwd){const env={...process.env};for(const key of Object.keys(env)){if(/^(NODE_OPTIONS|BUN_OPTIONS|CLI_VERSION|QWEN_CODE_RELAUNCH_ARGS)$/i.test(key))delete env[key]}return new Promise((resolve2,reject)=>{let settled=false;const child=execFile(command,args,{env,cwd,timeout:timeoutMs,killSignal:"SIGKILL",maxBuffer:64*1024},(err,out,stderr)=>{if(settled)return;settled=true;if(err&&("killed"in err&&err.killed||"signal"in err&&err.signal)){reject(new Error("Smoke test timed out"));return}if(err){const exitCode="code"in err&&typeof err.code==="number"?err.code:1;resolve2({exitCode,stdout:out||"",stderr:stderr||""});return}resolve2({exitCode:0,stdout:out||"",stderr:stderr||""})});child.on("error",()=>{if(settled)return;settled=true;reject(new Error("Smoke test failed: unable to start new binary"))})})}__name(spawnAndCapture,"spawnAndCapture");async function smokeTest(newInstallDir,target,runtime,expectedVersion){const resolvedInstallDir=path.resolve(newInstallDir);const interpreter=target.startsWith("win")?path.join(resolvedInstallDir,runtime,`${runtime}.exe`):path.join(resolvedInstallDir,runtime,"bin",runtime);const cliBin=path.join(resolvedInstallDir,"lib","cli.js");if(!fs.existsSync(interpreter)){throw new Error(`Smoke test failed: ${runtime} binary not found at ${interpreter}`)}if(!fs.existsSync(cliBin)){throw new Error(`Smoke test failed: CLI entry not found at ${cliBin}`)}const cwd=fs.mkdtempSync(path.join(os.tmpdir(),"qwen-code-smoke-"));try{const identity=await spawnAndCapture(interpreter,["-e",'console.log(JSON.stringify({runtime:process.versions.bun?"bun":"node",platform:process.platform,arch:process.arch}))'],1e4,cwd);let actual;try{actual=JSON.parse(identity.stdout)}catch{throw new Error("Smoke test failed: invalid interpreter identity")}const[platform2,arch2]=target.split("-");if(identity.exitCode!==0||!actual||typeof actual!=="object"||Array.isArray(actual)||Reflect.get(actual,"runtime")!==runtime||Reflect.get(actual,"platform")!==(platform2==="win"?"win32":platform2)||Reflect.get(actual,"arch")!==arch2){throw new Error("Smoke test failed: interpreter identity does not match the expected runtime and target")}const{exitCode,stdout}=await spawnAndCapture(interpreter,[cliBin,"--version"],1e4,cwd);if(exitCode!==0){throw new Error(`Smoke test failed: new binary exited with code ${exitCode}`)}const version=stdout.trim();if(!SEMVER_RE.test(version)){throw new Error("Smoke test failed: unexpected version output")}let versionMatches;try{versionMatches=import_semver.default.eq(version,expectedVersion)}catch{versionMatches=false}if(!versionMatches){throw new Error("Smoke test failed: CLI version does not match the expected version")}const launcher=await spawnAndCapture(interpreter,[path.join(resolvedInstallDir,"lib","cli-entry.js"),"--help"],1e4,cwd);if(launcher.exitCode!==0){throw new Error("Smoke test failed: launcher could not load CLI")}debugLogger.info(`Smoke test passed: ${version}`)}finally{try{fs.rmSync(cwd,{recursive:true,force:true})}catch{debugLogger.warn("Could not remove the smoke test temporary directory")}}}__name(smokeTest,"smokeTest");function pendingSwapError(standaloneDir){return new Error(`A previous update left a pending swap at ${standaloneDir}.new. If no qwen-update.bat process is running, remove the pending swap and .qwen-update.lock, then try again.`)}__name(pendingSwapError,"pendingSwapError");function deferredMarkerError(standaloneDir){return new Error(`A previous update left a deferred-swap marker at ${standaloneDir}.deferred. If no qwen-update.bat process is running, remove the marker, the pending swap at ${standaloneDir}.new, and .qwen-update.lock, then try again.`)}__name(deferredMarkerError,"deferredMarkerError");var PENDING_SWAP_STALE_MS=15*60*1e3;function checkDeferredSwap(standaloneDir){const deferredMarker=`${standaloneDir}.deferred`;let swapProvenDead=false;if(fs.existsSync(deferredMarker)){let marker;try{marker=fs.readFileSync(deferredMarker,"utf-8").trim()}catch{throw deferredMarkerError(standaloneDir)}const batPid=parseInt(marker,10);if(!Number.isSafeInteger(batPid)||batPid<=0||batPid>2147483647){throw deferredMarkerError(standaloneDir)}if(!isProcessProvablyGone(batPid)){let markerStale=false;try{markerStale=Date.now()-fs.statSync(deferredMarker).mtimeMs>PENDING_SWAP_STALE_MS}catch{}if(markerStale){throw new Error(`A previous update left a deferred-swap marker at ${standaloneDir}.deferred. If a qwen-update.bat process is still running, end it first; then remove the marker, the pending swap at ${standaloneDir}.new, and .qwen-update.lock, and try again.`)}throw new Error("A previous update is still being applied. Please wait a moment and try again.")}swapProvenDead=true;try{fs.unlinkSync(deferredMarker)}catch{}}const pendingDir=`${standaloneDir}.new`;if(fs.existsSync(pendingDir)){if(!swapProvenDead){let stale=false;try{stale=Date.now()-fs.statSync(pendingDir).mtimeMs>PENDING_SWAP_STALE_MS}catch{}if(!stale){throw pendingSwapError(standaloneDir)}}try{fs.rmSync(pendingDir,{recursive:true,force:true})}catch(err){const reason=err instanceof Error?err.message:String(err);throw new Error(`A previous update left a pending swap at ${pendingDir} that could not be removed (${reason}). Remove it and .qwen-update.lock, then try again.`)}}}__name(checkDeferredSwap,"checkDeferredSwap");function acquireLock(lockPath,standaloneDir){try{fs.writeFileSync(lockPath,String(process.pid),{flag:"wx"});if(standaloneDir){checkDeferredSwap(standaloneDir)}return true}catch(fastPathErr){if(fastPathErr instanceof Error&&(fastPathErr.message.startsWith("A previous update")||fastPathErr.message.includes("pending swap"))){try{fs.unlinkSync(lockPath)}catch{}throw fastPathErr}let pidStr;try{pidStr=fs.readFileSync(lockPath,"utf-8").trim()}catch{return false}const pid=parseInt(pidStr,10);if(!Number.isNaN(pid)&&isProcessAlive(pid)){return false}if(standaloneDir){checkDeferredSwap(standaloneDir)}try{fs.unlinkSync(lockPath);fs.writeFileSync(lockPath,String(process.pid),{flag:"wx"});return true}catch{return false}}}__name(acquireLock,"acquireLock");function releaseLock(lockPath){try{fs.unlinkSync(lockPath)}catch{}}__name(releaseLock,"releaseLock");function cleanupEmptyStandaloneDir(standaloneDir){const manifestPath=path.join(standaloneDir,"manifest.json");if(fs.existsSync(standaloneDir)&&!fs.existsSync(manifestPath)){fs.rmSync(standaloneDir,{recursive:true,force:true})}}__name(cleanupEmptyStandaloneDir,"cleanupEmptyStandaloneDir");var UNSAFE_SHELL_CHARS=/[\0\n\r]/;var UNSAFE_CMD_CHARS=/[&|<>^%!"`\n\r]/;function assertSafeForSingleQuotedShellPath(p,context){if(UNSAFE_SHELL_CHARS.test(p)){throw new Error(`${context} contains characters unsafe for shell embedding: ${p}`)}}__name(assertSafeForSingleQuotedShellPath,"assertSafeForSingleQuotedShellPath");function shellQuoteForSh(p){return`'${p.replace(/'/g,"'\\''")}'`}__name(shellQuoteForSh,"shellQuoteForSh");function shellQuoteForFish(p){return shellQuoteForSh(p)}__name(shellQuoteForFish,"shellQuoteForFish");function isProcessAlive(pid){try{process.kill(pid,0);return true}catch{return false}}__name(isProcessAlive,"isProcessAlive");function isProcessProvablyGone(pid){try{process.kill(pid,0);return false}catch(err){return err.code==="ESRCH"}}__name(isProcessProvablyGone,"isProcessProvablyGone");function atomicReplace(standaloneDir,newDir,lockPath){const oldDir=`${standaloneDir}.old`;const pendingDir=`${standaloneDir}.new`;if(fs.existsSync(oldDir)){fs.rmSync(oldDir,{recursive:true,force:true})}if(os.platform()==="win32"){if(UNSAFE_CMD_CHARS.test(standaloneDir)||UNSAFE_CMD_CHARS.test(oldDir)||UNSAFE_CMD_CHARS.test(pendingDir)){throw new Error("Installation path contains characters unsafe for deferred update script")}if(fs.existsSync(pendingDir)){fs.rmSync(pendingDir,{recursive:true,force:true})}fs.renameSync(newDir,pendingDir);const lockFile=lockPath;const deferredMarker=`${standaloneDir}.deferred`;const logFile=path.join(path.dirname(standaloneDir),"qwen-update.log");const script=["@echo off","set /a TRIES=0",":wait","set /a TRIES+=1","if %TRIES% GTR 30 goto proceed",`tasklist /FI "PID eq ${process.pid}" 2>nul | find "${process.pid}" >nul && (timeout /t 1 >nul & goto wait)`,...process.env["QWEN_CODE_LAUNCHER_PID"]?.match(/^\d+$/)?["set /a LAUNCHER_TRIES=0",":wait_launcher","set /a LAUNCHER_TRIES+=1","if %LAUNCHER_TRIES% GTR 30 goto proceed",`tasklist /FI "PID eq ${process.env["QWEN_CODE_LAUNCHER_PID"]}" 2>nul | find "${process.env["QWEN_CODE_LAUNCHER_PID"]}" >nul && (timeout /t 1 >nul & goto wait_launcher)`]:[],":proceed",`echo [%DATE% %TIME%] starting swap >> "${logFile}"`,`move /Y "${standaloneDir}" "${oldDir}"`,"if errorlevel 1 goto move1_failed",`move /Y "${pendingDir}" "${standaloneDir}"`,"if errorlevel 1 goto move2_failed",`echo [%DATE% %TIME%] swap completed >> "${logFile}"`,"goto cleanup",":move1_failed",`echo [%DATE% %TIME%] ERROR: failed to rename install to .old (errorlevel %errorlevel%) >> "${logFile}"`,"goto cleanup",":move2_failed",`echo [%DATE% %TIME%] ERROR: failed to promote .new; rolling back >> "${logFile}"`,`move /Y "${oldDir}" "${standaloneDir}"`,"if errorlevel 1 (",` echo [%DATE% %TIME%] CRITICAL: rollback also failed; manual recovery: move "${oldDir}" "${standaloneDir}" >> "${logFile}"`,") else (",` echo [%DATE% %TIME%] rollback succeeded >> "${logFile}"`,")",":cleanup",`del /F /Q "${deferredMarker}" 2>nul`,`del /F /Q "${lockFile}" 2>nul`,`del "%~f0"`].join("\r\n");const scriptPath=path.join(path.dirname(standaloneDir),"qwen-update.bat");fs.writeFileSync(scriptPath,script);const child=spawn("cmd.exe",["/c",scriptPath],{detached:true,stdio:"ignore",windowsHide:true});child.on("error",err=>{debugLogger.warn("Deferred bat script failed to spawn:",err)});child.unref();if(!child.pid){throw new Error("Failed to spawn deferred update script. Update was not applied.")}fs.writeFileSync(deferredMarker,String(child.pid));return"deferred"}else{fs.renameSync(standaloneDir,oldDir);try{fs.renameSync(newDir,standaloneDir)}catch(promoteErr){try{fs.renameSync(oldDir,standaloneDir)}catch(rollbackErr){const detail=`Standalone update failed AND rollback failed.
|
|
4
4
|
Original error: ${promoteErr.message}
|
|
5
5
|
Rollback error: ${rollbackErr.message}
|
|
6
6
|
Manual recovery: mv "${oldDir}" "${standaloneDir}"`;throw new Error(detail)}throw promoteErr}return"done"}}__name(atomicReplace,"atomicReplace");function ensureBinWrapper(standaloneDir,target,runtime="node"){const binDir=path.join(path.dirname(standaloneDir),"..","bin");const artifacts={wrapperCreated:false};const{launcher,interpreter,entryPoint}=standaloneRuntimePaths(standaloneDir,target,runtime);const hasLauncher=fs.existsSync(launcher);try{fs.mkdirSync(binDir,{recursive:true});if(target.startsWith("win")){if(UNSAFE_CMD_CHARS.test(standaloneDir)){throw new Error("standaloneDir contains characters unsafe for cmd.exe wrapper")}const wrapperPath=path.join(binDir,"qwen.cmd");artifacts.wrapperPath=wrapperPath;const content=hasLauncher?`@echo off\r
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{collectProviderModelsForProtocol}from"./chunk-
|
|
3
|
+
import{collectProviderModelsForProtocol}from"./chunk-SAVYMUU3.js";import{loadSettings}from"./chunk-Q5RRVBTY.js";import{t}from"./chunk-NO7VTKRL.js";import{loadEnvironment}from"./chunk-UM5KBBYP.js";import{resolveModelSelectionAuthType}from"./chunk-ET2Z7ZGF.js";import{VERTEX_ADC_HINT,hasVertexProjectConfigured}from"./chunk-H5EXNXGW.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var DEFAULT_ENV_KEYS={["openai"]:"OPENAI_API_KEY",["openai-responses"]:"OPENAI_API_KEY",["anthropic"]:"ANTHROPIC_API_KEY",["gemini"]:"GEMINI_API_KEY",["vertex-ai"]:"GOOGLE_API_KEY"};function findModelConfig(modelProviders,providerProtocol,authType,modelId,baseUrl){if(!modelProviders||!modelId){return void 0}const models=collectProviderModelsForProtocol(modelProviders,providerProtocol,authType);if(models.length===0){return void 0}if(baseUrl){return models.find(m=>m.id===modelId&&m.baseUrl===baseUrl)??models.find(m=>m.id===modelId)}return models.find(m=>m.id===modelId)}__name(findModelConfig,"findModelConfig");function resolveSelectedModel(settings,config){const modelsConfig=config?.getModelsConfig();if(modelsConfig){return{modelId:modelsConfig.getModel(),baseUrl:modelsConfig.getGenerationConfig()?.baseUrl}}return{modelId:settings.model?.name,baseUrl:settings.model?.baseUrl}}__name(resolveSelectedModel,"resolveSelectedModel");function hasEnvValue(settings,envKey){if(!envKey){return false}if(process.env[envKey]){return true}const settingsEnv=settings.env;const settingsEnvValue=settingsEnv?.[envKey];return typeof settingsEnvValue==="string"&&settingsEnvValue.trim().length>0}__name(hasEnvValue,"hasEnvValue");function hasApiKeyForAuth(authType,settings,config){const modelProviders=settings.modelProviders;const{modelId,baseUrl}=resolveSelectedModel(settings,config);const modelAuthType=!config&&(authType==="openai"||authType==="openai-responses")?resolveModelSelectionAuthType(authType,modelId,modelProviders,settings.providerProtocol,baseUrl):authType;const modelConfig=findModelConfig(modelProviders,settings.providerProtocol,modelAuthType,modelId,baseUrl);const resolvedApiKey=config?.getModelsConfig().getGenerationConfig()?.apiKey;if(resolvedApiKey){return{hasKey:true,checkedEnvKey:modelConfig?.envKey??DEFAULT_ENV_KEYS[authType],isExplicitEnvKey:!!modelConfig?.envKey}}if(modelConfig?.envKey){const hasKey=hasEnvValue(settings,modelConfig.envKey);return{hasKey,checkedEnvKey:modelConfig.envKey,isExplicitEnvKey:true}}const defaultEnvKey=DEFAULT_ENV_KEYS[authType];if(defaultEnvKey){const hasKey=hasEnvValue(settings,defaultEnvKey);if(hasKey){return{hasKey,checkedEnvKey:defaultEnvKey,isExplicitEnvKey:false}}}if(settings.security?.auth?.apiKey){return{hasKey:true,checkedEnvKey:defaultEnvKey||void 0,isExplicitEnvKey:false}}return{hasKey:false,checkedEnvKey:defaultEnvKey,isExplicitEnvKey:false}}__name(hasApiKeyForAuth,"hasApiKeyForAuth");function isVertexAdcEligible(settings,config){const{modelId,baseUrl}=resolveSelectedModel(settings,config);const modelConfig=findModelConfig(settings.modelProviders,settings.providerProtocol,"vertex-ai",modelId,baseUrl);return!modelConfig?.envKey}__name(isVertexAdcEligible,"isVertexAdcEligible");function hasVertexProject(settings){const settingsEnv=settings.env;return hasVertexProjectConfigured(key=>{const fromProcess=process.env[key];if(fromProcess!==void 0){return fromProcess}const fromSettings=settingsEnv?.[key];return typeof fromSettings==="string"?fromSettings:void 0})}__name(hasVertexProject,"hasVertexProject");function getApiKeyError(authMethod,settings,config){const{hasKey,checkedEnvKey,isExplicitEnvKey}=hasApiKeyForAuth(authMethod,settings,config);if(hasKey){return null}const envKeyHint=checkedEnvKey||DEFAULT_ENV_KEYS[authMethod];if(isExplicitEnvKey){return t("{{envKeyHint}} environment variable not found. Please set it in your .env file or environment variables.",{envKeyHint})}return t("{{envKeyHint}} environment variable not found (or set settings.security.auth.apiKey). Please set it in your .env file or environment variables.",{envKeyHint})}__name(getApiKeyError,"getApiKeyError");function validateAuthMethod(authMethod,config){const settings=loadSettings(process.cwd(),false);loadEnvironment(settings.merged);if(authMethod==="openai"||authMethod==="openai-responses"){const{hasKey,checkedEnvKey,isExplicitEnvKey}=hasApiKeyForAuth(authMethod,settings.merged,config);if(!hasKey){const envKeyHint=checkedEnvKey?`'${checkedEnvKey}'`:"'OPENAI_API_KEY'";if(isExplicitEnvKey){return t("Missing API key for OpenAI-compatible auth. Set the {{envKeyHint}} environment variable.",{envKeyHint})}return t("Missing API key for OpenAI-compatible auth. Set settings.security.auth.apiKey, or set the {{envKeyHint}} environment variable.",{envKeyHint})}return null}if(authMethod==="qwen-oauth"){return t("Qwen OAuth free tier was discontinued on 2026-04-15. Run /auth to switch to Coding Plan, OpenRouter, Fireworks AI, or another provider.")}if(authMethod==="anthropic"){const apiKeyError=getApiKeyError(authMethod,settings.merged,config);if(apiKeyError){return apiKeyError}const modelProviders=settings.merged.modelProviders;const{modelId,baseUrl}=resolveSelectedModel(settings.merged,config);const modelConfig=findModelConfig(modelProviders,settings.merged.providerProtocol,authMethod,modelId,baseUrl);if(modelConfig&&!modelConfig.baseUrl){return t("Anthropic provider missing required baseUrl in modelProviders[].baseUrl.")}if(!modelConfig&&!process.env["ANTHROPIC_BASE_URL"]){return t("ANTHROPIC_BASE_URL environment variable not found.")}return null}if(authMethod==="gemini"){const apiKeyError=getApiKeyError(authMethod,settings.merged,config);if(apiKeyError){return apiKeyError}return null}if(authMethod==="vertex-ai"){const adcEligible=isVertexAdcEligible(settings.merged,config);if(!adcEligible||!hasVertexProject(settings.merged)){const apiKeyError=getApiKeyError(authMethod,settings.merged,config);if(apiKeyError){return adcEligible?apiKeyError+VERTEX_ADC_HINT:apiKeyError}}process.env["GOOGLE_GENAI_USE_VERTEXAI"]="true";return null}return t("Invalid auth method selected.")}__name(validateAuthMethod,"validateAuthMethod");export{validateAuthMethod};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2025 Qwen Team
|