gerege-cli 0.26.5 → 0.26.6
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-QCIXIS4P.js} +1 -1
- package/chunks/{StandaloneSessionPicker-UNORCVYY.js → StandaloneSessionPicker-BAFAIRT7.js} +1 -1
- package/chunks/{acp-subagent-executor-623ZUTJT.js → acp-subagent-executor-TPVXURLW.js} +1 -1
- package/chunks/{acpAgent-MTTDTK2C.js → acpAgent-67UN66PB.js} +3 -3
- package/chunks/{advisor-ANUGICJ5.js → advisor-SAXMI4QZ.js} +1 -1
- package/chunks/{agent-GNCQDICJ.js → agent-KV7BXY6C.js} +1 -1
- package/chunks/{agent-headless-OPUXAXQM.js → agent-headless-FQX3JGG6.js} +1 -1
- package/chunks/{agent-host-client-K6GRPTFD.js → agent-host-client-L5EHC4AC.js} +1 -1
- package/chunks/{agent-host-connections-MF3YBZU2.js → agent-host-connections-EDBMCVQF.js} +1 -1
- package/chunks/{anthropicContentGenerator-OK4PFE5Y.js → anthropicContentGenerator-V7TX2NXP.js} +1 -1
- package/chunks/{autofix-pr-MABTGEHZ.js → autofix-pr-WP34NYHL.js} +1 -1
- package/chunks/{batch-V2NJT3M5.js → batch-XFVQ4BLM.js} +1 -1
- package/chunks/{bridge-BJQ627CX.js → bridge-AE7AFEXB.js} +1 -1
- package/chunks/{channel-settings-store-4JMCI4UR.js → channel-settings-store-X63P5OVT.js} +1 -1
- package/chunks/{chunk-ZN57TOVA.js → chunk-2DU2WMTL.js} +1 -1
- package/chunks/{chunk-Z5XENA4A.js → chunk-2JGTWRZJ.js} +8 -7
- package/chunks/{chunk-MTW3A3KT.js → chunk-2LWJGXTW.js} +1 -1
- package/chunks/{chunk-OCBJCZC2.js → chunk-2N3NBTYJ.js} +1 -1
- package/chunks/{chunk-WI4UMN3Q.js → chunk-2TAJ5STJ.js} +1 -1
- package/chunks/{chunk-EIILQ6KT.js → chunk-32XHDDIA.js} +1 -1
- package/chunks/{chunk-FNXO5KWB.js → chunk-34HC2AXI.js} +2 -2
- package/chunks/{chunk-2X3UF2CF.js → chunk-3W32X2DH.js} +1 -1
- package/chunks/{chunk-CKZRJP4F.js → chunk-4ME3BUJK.js} +1 -1
- package/chunks/{chunk-NVSKOSFG.js → chunk-4NDJKNN6.js} +1 -1
- package/chunks/{chunk-BRPJ5EHA.js → chunk-5EXL4TKQ.js} +1 -1
- package/chunks/{chunk-3XBJYUWP.js → chunk-65ME4BOH.js} +1 -1
- package/chunks/{chunk-TQTIEK2W.js → chunk-7453BHJO.js} +1 -1
- package/chunks/{chunk-HSYBIGMS.js → chunk-76FSYQTG.js} +1 -1
- package/chunks/{chunk-FNB3DPQZ.js → chunk-7RNOS7R4.js} +1 -1
- package/chunks/{chunk-H57IX45A.js → chunk-AEKEZRIU.js} +1 -1
- package/chunks/{chunk-CXGGC4NO.js → chunk-AEZYXPFS.js} +1 -1
- package/chunks/{chunk-NGOIJH7K.js → chunk-AFO5ER23.js} +1 -1
- package/chunks/{chunk-UY2ET2AL.js → chunk-AYVCT5FF.js} +1 -1
- package/chunks/{chunk-QOYRDEXR.js → chunk-B37YY4XU.js} +1 -1
- package/chunks/{chunk-IDUGQMTP.js → chunk-BAUMVH4Q.js} +1 -1
- package/chunks/{chunk-CAPG7UVH.js → chunk-BCI62WSL.js} +1 -1
- package/chunks/{chunk-USJFJZ23.js → chunk-BGELKSQ4.js} +1 -1
- package/chunks/{chunk-6X73W4TL.js → chunk-BHIDG6VZ.js} +1 -1
- package/chunks/{chunk-26ISBUM7.js → chunk-BPFFRPWE.js} +6 -6
- package/chunks/{chunk-YGHM5CDT.js → chunk-BQZF3UKI.js} +1 -1
- package/chunks/{chunk-3NQESE5K.js → chunk-CBE6ZIHU.js} +1 -1
- package/chunks/{chunk-DEMXCA3K.js → chunk-CF6SZJNP.js} +1 -1
- package/chunks/{chunk-2VCDJ6UF.js → chunk-CGDFZEER.js} +1 -1
- package/chunks/{chunk-3WQPUP5U.js → chunk-CUP2TNJK.js} +1 -1
- package/chunks/{chunk-2IGE2K5V.js → chunk-DA6LOBSB.js} +1 -1
- package/chunks/{chunk-HFV6CQWE.js → chunk-EFIRES46.js} +1 -1
- package/chunks/{chunk-E5YRAQXM.js → chunk-EKRUF347.js} +1 -1
- package/chunks/{chunk-KN27BFXM.js → chunk-ELDZ4MNL.js} +1 -1
- package/chunks/{chunk-ADTFKUH2.js → chunk-ET5M5WFN.js} +1 -1
- package/chunks/{chunk-IBYFSHBB.js → chunk-EXIFPXMB.js} +1 -1
- package/chunks/{chunk-IA4K4PGK.js → chunk-EYPLBTMI.js} +1 -1
- package/chunks/{chunk-DTTC4ZKY.js → chunk-FEP6W4NJ.js} +1 -1
- package/chunks/{chunk-FHBGTZ4K.js → chunk-FKL3V5BO.js} +1 -1
- package/chunks/{chunk-Q5E5SOY2.js → chunk-FKZ46GKL.js} +1 -1
- package/chunks/{chunk-OPYGNTZP.js → chunk-FYBJGRX7.js} +1 -1
- package/chunks/{chunk-FPZPCZFS.js → chunk-G6DALGGS.js} +1 -1
- package/chunks/{chunk-3Y6LSWEW.js → chunk-GBSRWT7J.js} +1 -1
- package/chunks/{chunk-SMYBY353.js → chunk-GHIFIXNX.js} +1 -1
- package/chunks/{chunk-DE53B2R7.js → chunk-GRAECADD.js} +1 -1
- package/chunks/{chunk-UJYOILZR.js → chunk-GSPGIGO5.js} +3 -3
- package/chunks/{chunk-5UZT4SXG.js → chunk-H3IR3GIE.js} +1 -1
- package/chunks/{chunk-ADZI3OFT.js → chunk-HOG66S6K.js} +1 -1
- package/chunks/{chunk-WB34KMOT.js → chunk-HTAUIJB4.js} +1 -1
- package/chunks/{chunk-MPAR4JBP.js → chunk-I6PUY2T3.js} +1 -1
- package/chunks/{chunk-5ZQWQ3RK.js → chunk-IZ5MWA6E.js} +1 -1
- package/chunks/{chunk-7IERHQ63.js → chunk-JEDL4IKF.js} +1 -1
- package/chunks/{chunk-RVJJFDF3.js → chunk-JH3V5SPA.js} +1 -1
- package/chunks/{chunk-SELRSZFK.js → chunk-JRTOPEM3.js} +1 -1
- package/chunks/{chunk-SQQORHMS.js → chunk-JWNKPINR.js} +1 -1
- package/chunks/{chunk-55RVKT4O.js → chunk-KJGRCIVY.js} +1 -1
- package/chunks/{chunk-GSOBASYW.js → chunk-KZNYALFU.js} +1 -1
- package/chunks/{chunk-FDUXQAGW.js → chunk-LBLLWAKK.js} +1 -1
- package/chunks/{chunk-ZSVSRF4C.js → chunk-LT3J74BZ.js} +1 -1
- package/chunks/{chunk-AMTFJVDD.js → chunk-LTE4N6L3.js} +1 -1
- package/chunks/{chunk-F26LTWDZ.js → chunk-M6KB5RVD.js} +1 -1
- package/chunks/{chunk-2PY7R7GG.js → chunk-MGATL4OA.js} +1 -1
- package/chunks/{chunk-KGJ47CI5.js → chunk-MPVQDYPH.js} +1 -1
- package/chunks/{chunk-BBOJUFMW.js → chunk-MTDBCIDA.js} +1 -1
- package/chunks/{chunk-ZYTG6R7S.js → chunk-MYV7GY3H.js} +1 -1
- package/chunks/{chunk-4GC5HJZO.js → chunk-N7PWZBXV.js} +1 -1
- package/chunks/{chunk-2NOMOJWE.js → chunk-NA4ZF2FE.js} +2 -2
- package/chunks/{chunk-7MTBINFX.js → chunk-NEKPQLFY.js} +2 -2
- package/chunks/{chunk-ABJGFEES.js → chunk-NO7VTKRL.js} +1 -1
- package/chunks/{chunk-OHXQYU6S.js → chunk-NONBHCXP.js} +1 -1
- package/chunks/{chunk-ZOBX6C7E.js → chunk-NVOI6UDQ.js} +1 -1
- package/chunks/{chunk-YLAI26PX.js → chunk-OJ4K62S2.js} +1 -1
- package/chunks/{chunk-CCOUFBOY.js → chunk-OK7LBM5G.js} +1 -1
- package/chunks/{chunk-POA4NX4N.js → chunk-OOJ2AQT3.js} +1 -1
- package/chunks/{chunk-5WLKN3GD.js → chunk-OU7CEG7Q.js} +1 -1
- package/chunks/{chunk-4TYTJQWR.js → chunk-P3JEEDQZ.js} +1 -1
- package/chunks/{chunk-AQWHCRKY.js → chunk-P62S5JGM.js} +1 -1
- package/chunks/{chunk-B6D3KTUK.js → chunk-QDCUR3JB.js} +1 -1
- package/chunks/{chunk-XFLLE2J3.js → chunk-RSLTOIG5.js} +2 -2
- package/chunks/{chunk-ISGF3BVD.js → chunk-RXN7DUMP.js} +2 -2
- package/chunks/{chunk-PN62SUYK.js → chunk-SKGJ26HQ.js} +1 -1
- package/chunks/{chunk-62NLMVVT.js → chunk-SP6CQ3MO.js} +1 -1
- package/chunks/{chunk-4EQWJTJR.js → chunk-T2YTHAJW.js} +1 -1
- package/chunks/{chunk-NO26JN24.js → chunk-T53VMDXH.js} +1 -1
- package/chunks/{chunk-X4BFEDWU.js → chunk-T5DKF33F.js} +1 -1
- package/chunks/{chunk-KKBOCRPF.js → chunk-TB4AUC2L.js} +1 -1
- package/chunks/{chunk-Q6QS5JTK.js → chunk-U3Q72OGV.js} +1 -1
- package/chunks/{chunk-FLJLUMQF.js → chunk-UKLXKJKL.js} +1 -1
- package/chunks/{chunk-IH2PFVWO.js → chunk-VD2GSW64.js} +1 -1
- package/chunks/{chunk-VDRE7U3P.js → chunk-VRKYBH5G.js} +5 -5
- package/chunks/{chunk-MOPJNP5I.js → chunk-W2RQIZ6B.js} +1 -1
- package/chunks/{chunk-2LLPGSUK.js → chunk-W5Z4BWWA.js} +1 -1
- package/chunks/{chunk-CNFA5UUM.js → chunk-W66WWTOP.js} +1 -1
- package/chunks/{chunk-C56YJIEI.js → chunk-WGFX3EL3.js} +1 -1
- package/chunks/{chunk-6NI33TVK.js → chunk-X2TY7VTY.js} +1 -1
- package/chunks/{chunk-FIM7MM25.js → chunk-XISR37DQ.js} +1 -1
- package/chunks/{chunk-KDYUZBZC.js → chunk-YH2XRWRF.js} +1 -1
- package/chunks/{chunk-UBXLQ6TP.js → chunk-ZENMAISJ.js} +1 -1
- package/chunks/{codex-subagent-executor-EK3A2WBH.js → codex-subagent-executor-OLMGVPVS.js} +1 -1
- package/chunks/{config-utils-DLOK7OLM.js → config-utils-OWY5G5Y2.js} +1 -1
- package/chunks/{contextCommand-AVCUCHQC.js → contextCommand-IXFUZH65.js} +1 -1
- package/chunks/{core-runtime-QSS4ZTG6.js → core-runtime-O4LC4NY3.js} +1 -1
- package/chunks/{create-sub-session-PNF7QDKC.js → create-sub-session-6F7C3TMT.js} +1 -1
- package/chunks/{cron-create-C6JOFIU4.js → cron-create-2422NBSJ.js} +1 -1
- package/chunks/{daemon-git-worktree-guard-5XZAZ7D2.js → daemon-git-worktree-guard-EWPQA6NO.js} +1 -1
- package/chunks/{daemon-status-provider-MRNELSNJ.js → daemon-status-provider-FAHOXNFW.js} +1 -1
- package/chunks/{daemon-trust-policy-26CMW3WY.js → daemon-trust-policy-L3DM6AI5.js} +1 -1
- package/chunks/{daemon-trust-policy-monitor-3DWO6NQY.js → daemon-trust-policy-monitor-HNPY5KJ4.js} +1 -1
- package/chunks/{deferred-core-runtime-DEC3N46T.js → deferred-core-runtime-JF42NQJK.js} +1 -1
- package/chunks/{edit-3HMQPCHN.js → edit-E5LEI2LL.js} +1 -1
- package/chunks/{enterPlanMode-QHJF4JXZ.js → enterPlanMode-3COTUV5V.js} +1 -1
- package/chunks/{environment-NGIBJWOT.js → environment-XBBIB3VA.js} +1 -1
- package/chunks/{errors-MSTGCVGJ.js → errors-LNMQ7TUK.js} +1 -1
- package/chunks/{execution-tool-VR4TGOI4.js → execution-tool-QDDKJD2K.js} +1 -1
- package/chunks/{execution-worker-EJH7HIE2.js → execution-worker-TXGZRZXE.js} +1 -1
- package/chunks/{exitPlanMode-P25OHQJ6.js → exitPlanMode-Z7QEMWPE.js} +1 -1
- package/chunks/{fast-path-II433ZDP.js → fast-path-M6K2RACY.js} +1 -1
- package/chunks/{glob-4Q6DCT3F.js → glob-N2QT4U7U.js} +1 -1
- package/chunks/{goal-tools-FFMAJW6V.js → goal-tools-CUSQD3DG.js} +1 -1
- package/chunks/{handleAutoUpdate-QNM26NZK.js → handleAutoUpdate-QF2YQHF6.js} +1 -1
- package/chunks/{i18n-L5URVOBB.js → i18n-AGOA6MUI.js} +1 -1
- package/chunks/{initializer-NQ2NECYP.js → initializer-FRKYDUSX.js} +1 -1
- package/chunks/{installationInfo-BCTXASUM.js → installationInfo-OKA4WXAS.js} +1 -1
- package/chunks/{interactive-mod-session-PPTBI37E.js → interactive-mod-session-MWYN5IFK.js} +1 -1
- package/chunks/{list-7TE5TUZJ.js → list-DE7VUIR2.js} +1 -1
- package/chunks/{llm-BWWKUBBZ.js → llm-N3JGJHYC.js} +4 -4
- package/chunks/{llm-content-generator-QOTGPBYC.js → llm-content-generator-VMUBA7OJ.js} +1 -1
- package/chunks/{loadedSettingsAdapter-THAGI5M2.js → loadedSettingsAdapter-5C36OZ7N.js} +1 -1
- package/chunks/{local-7BTAGV4J.js → local-BE624O3A.js} +1 -1
- package/chunks/{local-execution-environment-S3OR4KSC.js → local-execution-environment-OPGM7Y6L.js} +1 -1
- package/chunks/{loggingContentGenerator-AXJ5E5RS.js → loggingContentGenerator-2MHAI6JR.js} +1 -1
- package/chunks/{loop-wakeup-AJTLMLRX.js → loop-wakeup-BDLATBXH.js} +1 -1
- package/chunks/{manage-memory-JHTUVMDJ.js → manage-memory-BBCEIIWB.js} +1 -1
- package/chunks/{managed-execution-engine-U6GNJ4U4.js → managed-execution-engine-SRFALTCX.js} +1 -1
- package/chunks/{managed-local-serve-P4ZXVRBU.js → managed-local-serve-ICNAS3E6.js} +1 -1
- package/chunks/{managed-npm-update-UDUILNR5.js → managed-npm-update-CTL6LH5Z.js} +1 -1
- package/chunks/{managed-runtime-attestation-worker-P34ZBNRG.js → managed-runtime-attestation-worker-ZRDWKXCI.js} +1 -1
- package/chunks/{managed-runtime-bootstrap-CLMYNPH5.js → managed-runtime-bootstrap-6NTGZXQL.js} +1 -1
- package/chunks/{managed-runtime-session-worker-7H7AZJBV.js → managed-runtime-session-worker-RKQBBFR6.js} +1 -1
- package/chunks/{managed-runtime-ssh-worker-5KEMC7FD.js → managed-runtime-ssh-worker-FCGV6FSW.js} +1 -1
- package/chunks/{managed-session-authority-CFUZ45HT.js → managed-session-authority-C7IW6TJX.js} +1 -1
- package/chunks/{mcp-YMG4RVMC.js → mcp-VC4CJPE5.js} +1 -1
- package/chunks/{memory-7STURUXK.js → memory-S6OJA3ZD.js} +1 -1
- package/chunks/mn-JMS6SWTO.js +8 -0
- package/chunks/{model-call-collection-WBWTO3EG.js → model-call-collection-MJZWRQSU.js} +1 -1
- package/chunks/{model-configuration-6KCZZSZD.js → model-configuration-SKU6L3QI.js} +1 -1
- package/chunks/{modelConfigUtils-Z2EKFSPN.js → modelConfigUtils-TJCB6NXT.js} +1 -1
- package/chunks/{monitor-U5E33JO6.js → monitor-M3PNLCYP.js} +1 -1
- package/chunks/{nonInteractiveCli-BVCL5I5R.js → nonInteractiveCli-MR7JLAWU.js} +1 -1
- package/chunks/{nonInteractiveToolExecutor-B4EUOMYF.js → nonInteractiveToolExecutor-YKA6JMTY.js} +1 -1
- package/chunks/{notebook-edit-MXKD5J2C.js → notebook-edit-ENTFB5D7.js} +1 -1
- package/chunks/{omni-I5YECZBW.js → omni-6YBX4R6K.js} +1 -1
- package/chunks/{openaiContentGenerator-Q5SINFJJ.js → openaiContentGenerator-XRXX33FY.js} +1 -1
- package/chunks/{openaiResponsesContentGenerator-R3XCZLZY.js → openaiResponsesContentGenerator-L6ONEHMR.js} +1 -1
- package/chunks/{pidfile-UOGUNUTK.js → pidfile-XR4JF2Z6.js} +1 -1
- package/chunks/{processUtils-QGQGZHBA.js → processUtils-GQYNJRBJ.js} +1 -1
- package/chunks/{prompt-terminal-ledger-L57JMVSR.js → prompt-terminal-ledger-7BM7YDLG.js} +1 -1
- package/chunks/{qwenContentGenerator-UKZ237LC.js → qwenContentGenerator-QSA32XEL.js} +1 -1
- package/chunks/{reactive-degrade-3OM3HWVA.js → reactive-degrade-TFNBAAPZ.js} +1 -1
- package/chunks/{read-file-63ZLWMOW.js → read-file-VD7OFO2E.js} +1 -1
- package/chunks/{resumeHistoryUtils-R5YQS4YQ.js → resumeHistoryUtils-2B4KPI7G.js} +1 -1
- package/chunks/{review-AT6OWVDO.js → review-C365WGCW.js} +1 -1
- package/chunks/{ripGrep-7KBZGTPV.js → ripGrep-D7WPMBXR.js} +1 -1
- package/chunks/{run-qwen-serve-CLBG7W6F.js → run-qwen-serve-NZWQHWQA.js} +1 -1
- package/chunks/{runtime-R3QIGB7U.js → runtime-J6SPBSCS.js} +1 -1
- package/chunks/{sandboxConfig-PM3ZRQYV.js → sandboxConfig-QS2XBPZG.js} +1 -1
- package/chunks/{scheduled-tasks-PUMNN5XV.js → scheduled-tasks-YNNIOOPM.js} +1 -1
- package/chunks/{scheduler-KTPM226B.js → scheduler-KCMSPHON.js} +1 -1
- package/chunks/{search-memory-7I5MGDNV.js → search-memory-EUBJ7IAV.js} +1 -1
- package/chunks/{send-message-J526AEBI.js → send-message-CWWZUPSK.js} +1 -1
- package/chunks/{serve-KLTMPK4W.js → serve-4CB4BWJ5.js} +1 -1
- package/chunks/{server-VLRNY6KG.js → server-JNANUIGC.js} +3 -3
- package/chunks/{session-2EB57NXY.js → session-3LQLXPUA.js} +1 -1
- package/chunks/{session-attachments-root-I7TESMWL.js → session-attachments-root-BWIVWFHJ.js} +1 -1
- package/chunks/{session-execution-engine-selector-5FAMSPSO.js → session-execution-engine-selector-5OLRX57L.js} +1 -1
- package/chunks/{session-pr-refresh-JCPVQPNJ.js → session-pr-refresh-RLF3EXS3.js} +1 -1
- package/chunks/{sessionService-YRW2IFPR.js → sessionService-U7ACD2HP.js} +1 -1
- package/chunks/{settings-KO2Q47JP.js → settings-FTGWYTUH.js} +1 -1
- package/chunks/{shell-OLZVNTQZ.js → shell-E4RENYQC.js} +1 -1
- package/chunks/{skill-XW2AQS7M.js → skill-OLNPHRWB.js} +1 -1
- package/chunks/{skill-settings-TKAVQ4XP.js → skill-settings-R2BV2GEK.js} +1 -1
- package/chunks/{spawnChannel-MBGCTK2J.js → spawnChannel-LOPAR5T2.js} +1 -1
- package/chunks/{standalone-update-A3YLLIAN.js → standalone-update-IGDX2RGN.js} +1 -1
- package/chunks/{start-opentui-ui-G5ROAR4V.js → start-opentui-ui-33QLBNRC.js} +1 -1
- package/chunks/{startInteractiveUI-PZQR4U53.js → startInteractiveUI-RQKHD7MM.js} +1 -1
- package/chunks/{team-create-S5ZY2UMF.js → team-create-HAVKHNU5.js} +1 -1
- package/chunks/{team-plan-approval-KX6RXEST.js → team-plan-approval-7MCQX67C.js} +1 -1
- package/chunks/{terminal-image-renderer-SCJREXE6.js → terminal-image-renderer-XT5JVEO6.js} +1 -1
- package/chunks/{theme-manager-DZSM4EBR.js → theme-manager-DR5EYGLT.js} +1 -1
- package/chunks/{tool-call-UK56SWCT.js → tool-call-LZHZ5RVH.js} +1 -1
- package/chunks/{tool-result-media-JLLSLGFL.js → tool-result-media-XCXCF4YC.js} +1 -1
- package/chunks/{tool-search-OWPFLVV5.js → tool-search-K6S3ON7M.js} +1 -1
- package/chunks/{total-session-admission-NQU4ACKH.js → total-session-admission-LGSS2VWS.js} +1 -1
- package/chunks/{trustedFolders-N7GXFYSF.js → trustedFolders-IIR2UZRL.js} +1 -1
- package/chunks/{update-relaunch-5SPXXHM2.js → update-relaunch-WVIFX5CN.js} +1 -1
- package/chunks/{updateCheck-VXUIX2XG.js → updateCheck-CMEWLLZJ.js} +1 -1
- package/chunks/{upload-config-OWLL4SRQ.js → upload-config-TCCFCNCD.js} +1 -1
- package/chunks/{useAutoAcceptIndicator-OUYRR56F.js → useAutoAcceptIndicator-5RTTH3OW.js} +1 -1
- package/chunks/{validateNonInterActiveAuth-PSVJO5HK.js → validateNonInterActiveAuth-AO336KDX.js} +1 -1
- package/chunks/{version-C26S7UAW.js → version-JYWKKMNP.js} +1 -1
- package/chunks/{web-fetch-AYOYV7R4.js → web-fetch-HWTAWXFM.js} +1 -1
- package/chunks/{web-search-DAREKD3Z.js → web-search-HAI5LW3G.js} +1 -1
- package/chunks/{workflow-WBGPKVO6.js → workflow-BZ2YFGF6.js} +1 -1
- package/chunks/{workflow-ancestor-trust-GEEB53TB.js → workflow-ancestor-trust-26TFXFPO.js} +1 -1
- package/chunks/{workspace-agents-IMAQME4W.js → workspace-agents-DLI4JQJZ.js} +1 -1
- package/chunks/{workspace-providers-status-VALHVEU2.js → workspace-providers-status-64C7DJZU.js} +1 -1
- package/chunks/{workspace-recovery-worker-AIAVRDGU.js → workspace-recovery-worker-IFRT3KKP.js} +1 -1
- package/chunks/{workspace-registration-store-FXEGZG3L.js → workspace-registration-store-MYKJM2SK.js} +1 -1
- package/chunks/{workspace-registry-GYFFHWCD.js → workspace-registry-GZJRONAY.js} +1 -1
- package/chunks/{workspace-runtime-coordinator-VZ462TLU.js → workspace-runtime-coordinator-44KW6HSN.js} +1 -1
- package/chunks/{workspace-service-5DIZM4IZ.js → workspace-service-YHTSZYYD.js} +1 -1
- package/chunks/{workspace-skills-status-DOOBVL5N.js → workspace-skills-status-NEB62X24.js} +1 -1
- package/chunks/{workspace-trust-reconciler-LOICVUVW.js → workspace-trust-reconciler-HZLOOZWM.js} +1 -1
- package/chunks/{write-file-EJNMAHQD.js → write-file-HD5LHXGL.js} +1 -1
- package/chunks/{zoom-image-S3OARMYP.js → zoom-image-W4BMRC5T.js} +1 -1
- package/cli.js +2 -2
- package/execution-worker.js +1 -1
- package/export-transcript-document.js +1 -1
- package/gerege.mjs +53 -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{ExtensionRefreshState}from"./chunk-254YDSL2.js";import{getInteractiveModSession}from"./chunk-5UZT4SXG.js";import{contextCommand}from"./chunk-2X3UF2CF.js";import{billableOutputTokens,calculateCost,commandRestrictionNames,computeSessionStats,diffCommand,extensionOwnerLabel,filterCommandsForMode,findInlineMathExpressions,formatCompressionTokenCount,formatDuration,formatTokenCount,getCompressionFailureStatusText,getSystemInfoFields,skillOriginLabel}from"./chunk-ADTFKUH2.js";import{VSCODE_SHIFT_ENTER_SEQUENCE,isWaylandSession,writeOsc52}from"./chunk-HR4TFOG6.js";import{isKittyProtocolEnabled}from"./chunk-HKA2IEQ6.js";import{themeManager}from"./chunk-W3YCOEIP.js";import{validateAuthMethod}from"./chunk-YGHM5CDT.js";import{clearSkillArgs,skillArgsNote,skillArgsPath,staleArgsWarning,writeSkillArgs}from"./chunk-TD6VSPYX.js";import{GITHUB_WORKFLOW_PATHS,INSIGHT_CSS,INSIGHT_JS,collectSessionData,extractInjections,generateExportFilename,normalizeSessionData,setupGithub,toHtml,toJson,toJsonl,toMarkdown}from"./chunk-26ISBUM7.js";import{checkAdvisorModelAvailability,isAdvisorModelEligible,resolveHookSettingsForConfig}from"./chunk-VDRE7U3P.js";import{stripUnsafeCharacters,toCodePoints,truncateToWidth}from"./chunk-64CA3W6G.js";import{MarkdownCommandDefSchema,parseMarkdownCommand}from"./chunk-XXUK6YLA.js";import{formatUnsupportedVoiceModelMessage,getVoiceSettingsScope,isSelectableVoiceModel,isVoiceEnabled,readVoiceMode,readVoiceModel}from"./chunk-E5YRAQXM.js";import{rollbackStandaloneUpdate}from"./chunk-4TYTJQWR.js";import{getInstallationInfo}from"./chunk-26MNTKT2.js";import{getExtendedSystemInfo,getGitVersion,getNpmVersion}from"./chunk-2LLPGSUK.js";import{getReasoningEffortsForConfig}from"./chunk-4XF4ZGJG.js";import{formatAuxModelSelectorForDisplay}from"./chunk-L42NTHIT.js";import{isValidSessionId}from"./chunk-LGFF5PJA.js";import{SERVE_CONTROL_EXT_METHODS,SERVE_STATUS_EXT_METHODS}from"./chunk-LUDNUVSA.js";import{ACP_ROUTE_ID_PREFIX,isInlineModelOverrideAllowed,parseAcpModelOption,resolveAcpFastModelSelector}from"./chunk-GT4TCQ3R.js";import{getErrorMessage as getErrorMessage2}from"./chunk-UBXLQ6TP.js";import{OUTPUT_LANGUAGE_AUTO,getAllSettingKeys,getDefaultValue,getFlattenedSchema,getNestedProperty,getPersistScopeForModelSelection,getSettingDefinition,isAutoLanguage,nextBooleanSettingValue,resolveOutputLanguageOrPreserveAuto,validateSettingValue,writeOutputLanguageAndRegisterPath}from"./chunk-WI4UMN3Q.js";import{getCurrentLanguage,setLanguageAsync,t}from"./chunk-ABJGFEES.js";import{SUPPORTED_LANGUAGES,getSupportedLanguageIds,resolveSupportedLanguage}from"./chunk-U7HZUZKP.js";import{require_strip_json_comments,stripUtf8Bom}from"./chunk-DOLUT3XC.js";import{isFolderTrustEnabled,loadTrustedFolders}from"./chunk-BBOJUFMW.js";import{BTW_MAX_INPUT_LENGTH,Logger,analyzeToolResultRetention,buildBtwCacheSafeParams,buildBtwPrompt,buildLearnSkillPrompt,buildLearnVideoSkillRequest,describePeerInboxFailure,encodeInsightErrorMessage,encodeInsightProgressMessage,encodeInsightReadyMessage,findOutputStyle,generateSessionRecap,getIdeInstaller,getLastPeerInboxFailure,getMCPServerPrompts,isWsl,listPeerControllers,loadOutputStyleCatalog,parseLearnVideoInput,readPathFromWorkspace,removePeerController}from"./chunk-5WLKN3GD.js";import{canonicalizeMsgId,describeHoldCause}from"./chunk-MKH3EH7O.js";import{buildBareRememberPrompt,buildManagedRememberPrompt}from"./chunk-Q5E5SOY2.js";import{MAX_WORKFLOW_RESULT_PREVIEW_CHARS,buildWorkflowResultPreview,listWorkflowSnapshots,readWorkflowSnapshot}from"./chunk-62NLMVVT.js";import{toCanonicalWorkspaceArtifactPath}from"./chunk-MZUOREFD.js";import{executeModTool,modToolRequest}from"./chunk-2VCDJ6UF.js";import{resolveOpenAILogDir}from"./chunk-QX7W2HY7.js";import{ArenaManager,ConditionalRulesRegistry,CoreToolScheduler,EXTENSIONS_CONFIG_FILENAME,ExtensionManager,GoalPersistenceUnavailableError,IdeClient,MAX_FAILURE_LINE_CHARS,QWEN_CODE_COMPANION_EXTENSION_NAME,REPORTED_FAILURE_KEYS,SESSION_TITLE_MAX_LENGTH,SessionService,appendAutoMemoryContext,appendToLastTextPart,buildBackgroundEntryLabel,buildFailureLines,collectMemoryDiagnostics,executeRuntimeShell,flatMapTextParts,getExtensionDescription,getExtensionDisplayName,getLastApiHistoryPromptId,getToolCallFingerprint,hookEventSupportsMatcher,ideContextStore,isActiveWorkflowStatus,isCompressionFailureStatus,isExtensionCommittedWithWarningsError,isSuccessStatus,isTerminalStatus,isTerminalWorkflowStatus,isWorkflowRunId,listSavedWorkflows,loadServerHierarchicalMemory,normalizeClaudeMcpServer,parseInstallSource,partToString,persistSessionUsage,reportedFailureLines,require_toml,runForkedAgent,sanitizeWorkflowText,truncateWorkflowText,tryGenerateSessionTitle,withoutAutoMemorySnapshots}from"./chunk-Z5XENA4A.js";import{shellResultText}from"./chunk-T7CHK6C2.js";import{external_exports}from"./chunk-TWP72VRH.js";import{canUseRipgrep}from"./chunk-QZV4PFQK.js";import{isInternalCodeModeToolResult,projectUserTranscriptForDisplay}from"./chunk-SZCBUCNH.js";import{resolveModelId}from"./chunk-BEKROCWN.js";import{normalizeSkillPriority}from"./chunk-5SUFJTQQ.js";import{flattenPeerLabel}from"./chunk-BYU42MLK.js";import{getAutoSkillCuratorStatus,recordAutoSkillUsage,restoreArchivedAutoSkill,runAutoSkillCurator,setAutoSkillPinned}from"./chunk-XQJOZDV7.js";import{GOAL_PAUSE_REASON_COMMAND,emptyGoalSnapshot}from"./chunk-HW6AWS7W.js";import{glob}from"./chunk-OBOU4ZZM.js";import{APPROVAL_MODES}from"./chunk-JZK2WGXA.js";import{isMediaPolicyToolHiddenFromModel}from"./chunk-S2ZKZXHX.js";import{BUILT_IN_OUTPUT_STYLES,getArenaSystemReminder,getInsightPrompt,getPlanModeSystemReminder,getProjectSummaryPrompt,isSystemMdActive,resolveMainSessionOutputStyle}from"./chunk-OV3EBH6J.js";import{isSignalTermination}from"./chunk-NMY3PYNO.js";import{checkArgumentSafety,checkCommandPermissions,escapeShellArg,getShellConfiguration}from"./chunk-SCD5TUBG.js";import{escapeJsonTagCharacters,formatMemoryUsage}from"./chunk-NTRFETZB.js";import{captureHookExecutionOwner,runWithHookExecutionOwner}from"./chunk-YZFNBUKG.js";import{buildRuntimeSnapshotId,findProviderByCredentials,isImageGenerationCapable,stripRuntimeSnapshotPrefix}from"./chunk-ET2Z7ZGF.js";import{openBrowserSecurely}from"./chunk-3YWXKSOI.js";import{COMBINED_PASS_TOLERANCE_FACTOR,IdeConnectionEvent,formatTokenUsageSummaryAsCsv,formatTokenUsageSummaryAsJson,getMCPServerStatus,isImageCapable,logIdeConnection,queryTokenUsage,recordSkillInvocation,uiTelemetryService}from"./chunk-ZWPSBU7K.js";import{read}from"./chunk-UQFTXKEB.js";import{getAutoMemoryRoot}from"./chunk-KVA6DHHF.js";import{runSideQuery}from"./chunk-K7JCVESI.js";import{getCurrentMemoryFilename}from"./chunk-Y6HHV4LC.js";import{resolveSlimmingConfig}from"./chunk-Q6UAOTP3.js";import{REASONING_EFFORT_TIERS,applyReasoningEffort,normalizeReasoningEffort}from"./chunk-GOR7FFVE.js";import{AuthType}from"./chunk-ZZZAYAJW.js";import{redactUrlCredentials}from"./chunk-3XVPZY7X.js";import{isCpuProfileRecording,startCpuProfile,stopCpuProfile}from"./chunk-DE53B2R7.js";import{FORK_SUBAGENT_TYPE,getApiHistoryPromptId,markApiHistoryPrompt,stripStartupContext}from"./chunk-B3ZFUGTC.js";import{applySkillSideEffects,buildSkillLlmContent}from"./chunk-IRINPFG7.js";import{HookEventName,sanitizeUserPromptExpansionAdditionalContext}from"./chunk-6GTPLW7K.js";import{isShellProgressData}from"./chunk-O5EKX7LG.js";import{ToolDisplayNamesMigration,ToolNames,canonicalToolName}from"./chunk-SBZFGYYS.js";import{createDebugLogger,updateSymlink}from"./chunk-JAUJI56S.js";import{Storage}from"./chunk-EPODBRBP.js";import{expandHomeDir,isSubpath,resolvePath}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();import{isDeepStrictEqual}from"node:util";function isCrossSessionMessagingEnabled(settings){const value=settings?.agents?.crossSessionMessaging;return value===void 0||value===true}__name(isCrossSessionMessagingEnabled,"isCrossSessionMessagingEnabled");function crossSessionMessagingSuppression(config){if(config?.isSafeMode?.()===true)return"safe-mode";if(config?.getBareMode?.()===true)return"bare";return void 0}__name(crossSessionMessagingSuppression,"crossSessionMessagingSuppression");function isCrossSessionMessagingActive(settings,config){return isCrossSessionMessagingEnabled(settings)&&crossSessionMessagingSuppression(config)===void 0}__name(isCrossSessionMessagingActive,"isCrossSessionMessagingActive");function switchIn(file){return file?.settings.agents?.crossSessionMessaging}__name(switchIn,"switchIn");function workspaceCounts(settings){return settings.isTrusted===true&&settings.workspaceSettingsActive===true}__name(workspaceCounts,"workspaceCounts");function isCrossSessionMessagingOptedIn(settings){if(switchIn(settings.user)===true)return true;return workspaceCounts(settings)&&switchIn(settings.workspace)===true}__name(isCrossSessionMessagingOptedIn,"isCrossSessionMessagingOptedIn");function crossSessionMessagingOffScope(settings){if(isCrossSessionMessagingEnabled(settings.merged))return void 0;const merged=settings.merged.agents?.crossSessionMessaging;if(switchIn(settings.system)!==void 0)return"system";if(isDeepStrictEqual(switchIn(settings.user),merged))return"user";if(isDeepStrictEqual(switchIn(settings.systemDefaults),merged)){return"system-defaults"}if(workspaceCounts(settings)&&isDeepStrictEqual(switchIn(settings.workspace),merged)){return"workspace"}return void 0}__name(crossSessionMessagingOffScope,"crossSessionMessagingOffScope");init_esbuild_shims();import{spawn}from"node:child_process";init_esbuild_shims();var MAX_STACKED_SKILLS=5;var isStackedSkillCompletableCommand=__name(command=>command.kind==="skill"&&command.userInvocable!==false&&!command.hidden,"isStackedSkillCompletableCommand");var isValidStackedSkillPrefix=__name((prefix,commands)=>{const trimmed=prefix.trim();if(!trimmed)return false;const tokens=trimmed.split(/\s+/);if(tokens.length>=MAX_STACKED_SKILLS)return false;return tokens.every(token=>{if(!token.startsWith("/"))return false;const command=findCommandByName(token.slice(1),commands);return command!==void 0&&isStackedSkillCompletableCommand(command)})},"isValidStackedSkillPrefix");var parseSlashCommand=__name((query,commands)=>{const trimmed=query.trim();const commandText=trimmed.substring(1).trim();const parts=commandText.split(/\s+/);const commandPath=parts.filter(p=>p);let currentCommands=commands;let commandToExecute;let pathIndex=0;const canonicalPath=[];let argsStart=0;for(const part of commandPath){let foundCommand=currentCommands.find(cmd=>cmd.name===part);if(!foundCommand){foundCommand=currentCommands.find(cmd=>cmd.altNames?.includes(part))}if(foundCommand){commandToExecute=foundCommand;canonicalPath.push(foundCommand.name);pathIndex++;const partIndex=commandText.indexOf(part,argsStart);argsStart=partIndex+part.length;if(foundCommand.subCommands){currentCommands=foundCommand.subCommands}else{break}}else{break}}const args=commandToExecute?commandText.slice(argsStart).trim():parts.slice(pathIndex).join(" ");return{commandToExecute,args,canonicalPath}},"parseSlashCommand");var parseStackedSlashCommands=__name((query,commands)=>{const trimmed=query.trim();if(!trimmed.startsWith("/")){return{skills:[],remainingText:trimmed,exceededMax:false}}const commandText=trimmed.substring(1);const skills=[];let pos=0;let restPos=0;let exceededMax=false;while(pos<commandText.length){while(pos<commandText.length&&/\s/.test(commandText[pos]))pos++;if(pos>=commandText.length){restPos=pos;break}const tokenStart=pos;while(pos<commandText.length&&!/\s/.test(commandText[pos]))pos++;const token=commandText.slice(tokenStart,pos);if(skills.length===0){if(token.startsWith("/"))break;const cmd2=findCommandByName(token,commands);if(!cmd2||cmd2.kind!=="skill")break;skills.push(cmd2);restPos=pos;continue}if(!token.startsWith("/"))break;const name=token.substring(1);if(!name)break;const cmd=findCommandByName(name,commands);if(!cmd||cmd.kind!=="skill")break;if(skills.length>=MAX_STACKED_SKILLS){exceededMax=true;break}skills.push(cmd);restPos=pos}if(skills.length<2){return{skills:[],remainingText:trimmed,exceededMax:false}}const afterSkills=commandText.slice(restPos).trim();return{skills,remainingText:afterSkills,exceededMax}},"parseStackedSlashCommands");function findCommandByName(name,commands){return commands.find(cmd=>cmd.name===name)??commands.find(cmd=>cmd.altNames?.includes(name))}__name(findCommandByName,"findCommandByName");var CONTEXT_FILES_ANNOUNCEMENT_PREFIX="Read context files:";function isContextFilesAnnouncement(item){return item.type==="info"&&typeof item.text==="string"&&item.text.startsWith(CONTEXT_FILES_ANNOUNCEMENT_PREFIX)}__name(isContextFilesAnnouncement,"isContextFilesAnnouncement");var CodePage={UTF8:65001,GBK:936,BIG5:950,LATIN1:1252};var isAtCommand=__name(query=>query.startsWith("@")||/\s@/.test(query),"isAtCommand");var SLASH_PATH_SEPARATOR_RE=/[/\\]/;var SLASH_COMMANDS_SKIP_RECORDING=new Set(["quit","exit","clear","reset","new","resume","delete","branch","btw","history"]);var getSlashCommandFirstToken=__name(query=>query.slice(1).trimStart().split(/\s+/u)[0]??"","getSlashCommandFirstToken");var hasSlashCommandPathSeparator=__name(query=>SLASH_PATH_SEPARATOR_RE.test(getSlashCommandFirstToken(query)),"hasSlashCommandPathSeparator");var isSlashCommand=__name(query=>{if(!query.startsWith("/")){return false}if(query.startsWith("//")){return false}if(query.startsWith("/*")){return false}if(hasSlashCommandPathSeparator(query)){return false}return true},"isSlashCommand");var BTW_COMMAND_RE=/^[/?]btw(?:\s|$)/;var isBtwCommand=__name(query=>{const trimmed=query.trim();return trimmed.length>0&&BTW_COMMAND_RE.test(trimmed)},"isBtwCommand");function consumesContextAnnouncementLatch(trimmedPrompt,options){if(trimmedPrompt.length===0){return false}if(/^\/btw(?:\s|$)/.test(trimmedPrompt)){return false}if(isSlashCommand(trimmedPrompt)){return parseSlashCommand(trimmedPrompt,options.slashCommands).commandToExecute?.modelInvocable===true}if(options.shellModeActive){return false}return true}__name(consumesContextAnnouncementLatch,"consumesContextAnnouncementLatch");var debugLogger=createDebugLogger("COMMAND_UTILS");var formatCommandFailure=__name((error,command)=>error instanceof Error&&error.code==="ENOENT"?`${command} not found`:error instanceof Error?error.message:String(error),"formatCommandFailure");var copyToClipboard=__name(async text=>{let wlCopyError;const run=__name((cmd,args,options)=>new Promise((resolve4,reject)=>{const child=options?spawn(cmd,args,options):spawn(cmd,args);let stderr="";if(child.stderr){child.stderr.on("data",chunk=>stderr+=chunk.toString())}child.on("error",reject);child.on("close",code=>{if(code===0)return resolve4();const errorMsg=stderr.trim();reject(new Error(`'${cmd}' exited with code ${code}${errorMsg?`: ${errorMsg}`:""}`))});if(child.stdin){child.stdin.on("error",reject);child.stdin.write(text);child.stdin.end()}else{reject(new Error("Child process has no stdin stream to write to."))}}),"run");const linuxOptions={stdio:["pipe","inherit","pipe"]};switch(process.platform){case"win32":return run("cmd",["/c",`chcp ${CodePage.UTF8} >nul && clip`]);case"darwin":return run("pbcopy",[]);case"linux":if(isWaylandSession()){try{await run("wl-copy",["-t","text/plain"],{stdio:["pipe","inherit","ignore"]});return}catch(error){wlCopyError=error;debugLogger.debug("wl-copy failed; falling back to other clipboard methods:",error)}}try{await run("xclip",["-selection","clipboard"],linuxOptions)}catch(primaryError){try{await run("xsel",["--clipboard","--input"],linuxOptions)}catch(fallbackError){const xclipNotFound=primaryError instanceof Error&&primaryError.code==="ENOENT";const xselNotFound=fallbackError instanceof Error&&fallbackError.code==="ENOENT";const wlCopyFailure=wlCopyError===void 0?"":`wl-copy failed ("${formatCommandFailure(wlCopyError,"wl-copy")}"); `;if(xclipNotFound&&xselNotFound){if(!writeOsc52(text)){throw new Error(`Clipboard unavailable: ${wlCopyFailure}xclip/xsel not found and OSC 52 requires a TTY. Try running inside a terminal emulator.`)}return}const primaryMsg=formatCommandFailure(primaryError,"xclip");const fallbackMsg=formatCommandFailure(fallbackError,"xsel");if(writeOsc52(text))return;throw new Error(`Clipboard unavailable: ${wlCopyFailure}xclip/xsel failed ("${primaryMsg}", "${fallbackMsg}") and OSC 52 requires a TTY. Try running inside a terminal emulator.`)}}return;default:throw new Error(`Unsupported platform: ${process.platform}`)}},"copyToClipboard");var getUrlOpenCommand=__name(()=>{let openCmd;switch(process.platform){case"darwin":openCmd="open";break;case"win32":openCmd="start";break;case"linux":openCmd="xdg-open";break;default:openCmd="xdg-open";debugLogger.warn(`Unknown platform: ${process.platform}. Attempting to open URLs with: ${openCmd}.`);break}return openCmd},"getUrlOpenCommand");function isMidInputCompletableCommand(cmd){return cmd.modelInvocable===true&&!cmd.hidden}__name(isMidInputCompletableCommand,"isMidInputCompletableCommand");function findMidInputSlashCommand(input,cursorOffset){const codePoints=toCodePoints(input);const beforeCursor=codePoints.slice(0,cursorOffset).join("");const match=beforeCursor.match(/\s\/([a-zA-Z0-9_:-]*)$/);if(!match)return null;const partialCommand=match[1];const slashPos=cursorOffset-1-partialCommand.length;const textAfterSlash=codePoints.slice(slashPos+1).join("");const commandMatch=textAfterSlash.match(/^[a-zA-Z0-9_:-]*/);const fullCommand=commandMatch?commandMatch[0]:"";if(cursorOffset!==slashPos+1+fullCommand.length)return null;return{token:"/"+fullCommand,startPos:slashPos,partialCommand}}__name(findMidInputSlashCommand,"findMidInputSlashCommand");function getBestSlashCommandMatch(partialCommand,commands,recentCommands){if(!partialCommand)return null;const query=partialCommand.toLowerCase();const matches=commands.filter(cmd=>{if(!isMidInputCompletableCommand(cmd))return false;const name=cmd.name.toLowerCase();return name.startsWith(query)&&(name!==query||!!cmd.argumentHint)}).sort((left,right)=>{const leftRecent=recentCommands?.get(left.name);const rightRecent=recentCommands?.get(right.name);const recentOrder=(rightRecent?.usedAt??0)-(leftRecent?.usedAt??0);return(right.completionPriority??0)-(left.completionPriority??0)||recentOrder||left.name.localeCompare(right.name)});const best=matches[0];if(!best)return null;return{suffix:best.name.slice(partialCommand.length),fullCommand:best.name,command:best,argumentHint:best.argumentHint}}__name(getBestSlashCommandMatch,"getBestSlashCommandMatch");var SLASH_TOKEN_RE=/(?:^|(?<=\s))\/([a-zA-Z][a-zA-Z0-9:_-]*)/g;function findSlashCommandTokens(text,commands){if(!text)return[];const commandMapEntries=[];for(const cmd of commands){commandMapEntries.push([cmd.name.toLowerCase(),cmd]);for(const altName of cmd.altNames??[]){commandMapEntries.push([altName.toLowerCase(),cmd])}}const commandMap=new Map(commandMapEntries);const tokens=[];let match;SLASH_TOKEN_RE.lastIndex=0;while((match=SLASH_TOKEN_RE.exec(text))!==null){const fullMatch=match[0];const commandName=match[1];const start=match.index;const end=start+fullMatch.length;const precedingChar=start>0?text[start-1]:null;const isLineStart=start===0||precedingChar==="\n";const cmd=commandMap.get(commandName.toLowerCase());let valid=false;if(cmd){if(isLineStart){valid=cmd.userInvocable!==false&&!cmd.hidden}else{const prefix=text.slice(0,start);valid=cmd.modelInvocable===true||isStackedSkillCompletableCommand(cmd)&&isValidStackedSkillPrefix(prefix,commands)}}tokens.push({start,end,commandName,valid})}return tokens}__name(findSlashCommandTokens,"findSlashCommandTokens");init_esbuild_shims();var debugLogger2=createDebugLogger("SESSION_MODEL");var AUTH_TYPES=new Set(Object.values(AuthType));function isAuthType(value){return AUTH_TYPES.has(value)}__name(isAuthType,"isAuthType");function registryHonoredBaseUrl(config,authType,modelId,baseUrl){if(typeof baseUrl!=="string"||!baseUrl){return void 0}return config.getResolvedModelConfig?.(authType,modelId,baseUrl)?baseUrl:void 0}__name(registryHonoredBaseUrl,"registryHonoredBaseUrl");async function recordDaemonSessionModel(config,payload){const recording=config.getChatRecordingService?.();if(!recording?.recordSessionModel)return;try{await recording.recordSessionModel(payload)}catch(error){debugLogger2.debug("recordSessionModel failed",error)}}__name(recordDaemonSessionModel,"recordDaemonSessionModel");async function recordDaemonSessionModelFromConfig(config){const modelId=config.getModel()?.trim();const authType=config.getAuthType();if(!modelId||!authType)return;const snapshot=config.getActiveRuntimeModelSnapshot?.();const registryBaseUrl=snapshot?void 0:config.getCurrentModelRegistryBaseUrl?.();await recordDaemonSessionModel(config,{modelId,authType,...typeof registryBaseUrl==="string"?{baseUrl:registryBaseUrl}:{},...snapshot?{isRuntime:true}:{}})}__name(recordDaemonSessionModelFromConfig,"recordDaemonSessionModelFromConfig");function hasMatchingRuntimeSnapshot(config,authType,modelId){const snapshot=config.getActiveRuntimeModelSnapshot?.();return snapshot?.authType===authType&&snapshot.modelId===modelId}__name(hasMatchingRuntimeSnapshot,"hasMatchingRuntimeSnapshot");function liveAuthType(config){return config.getAuthType()??config.getModelsConfig?.()?.getCurrentAuthType?.()}__name(liveAuthType,"liveAuthType");function runtimeSnapshotIdentity(snapshot){if(!snapshot)return void 0;if(typeof snapshot.id==="string"&&snapshot.id){return snapshot.id}if(snapshot.authType&&snapshot.modelId){return buildRuntimeSnapshotId(snapshot.authType,snapshot.modelId)}return void 0}__name(runtimeSnapshotIdentity,"runtimeSnapshotIdentity");function recordedRouteMatches(recorded,currentRegistryBaseUrl){if(!recorded||recorded.isRuntime)return true;const targetBaseUrl=recorded.baseUrl;if(targetBaseUrl===void 0){return currentRegistryBaseUrl===null||currentRegistryBaseUrl===void 0}if(targetBaseUrl===""){return currentRegistryBaseUrl===null||currentRegistryBaseUrl===void 0||currentRegistryBaseUrl===""}return currentRegistryBaseUrl===targetBaseUrl}__name(recordedRouteMatches,"recordedRouteMatches");async function applyRestoredSessionModel(config,projection){const recorded=projection?.runtime.recording.sessionModel;const fallbackModel=projection?.runtime.recording.lastAssistantModel;const recordedAuth=recorded?.authType?.trim();const authType=(recordedAuth&&isAuthType(recordedAuth)?recordedAuth:liveAuthType(config))?.trim();const modelId=recorded?.modelId||fallbackModel;if(!modelId?.trim()||!authType||!isAuthType(authType))return;const currentModel=stripRuntimeSnapshotPrefix(config.getModel()??"");const currentAuth=liveAuthType(config);const targetModel=stripRuntimeSnapshotPrefix(modelId.trim());const targetBaseUrl=recorded?.isRuntime?void 0:registryHonoredBaseUrl(config,authType,targetModel,recorded?.baseUrl);const recordedRoute=recorded?{...recorded,...targetBaseUrl?{baseUrl:targetBaseUrl}:{baseUrl:void 0}}:void 0;const currentRegistryBaseUrl=config.getCurrentModelRegistryBaseUrl?.();const baseUrlMatches=recordedRouteMatches(recordedRoute,currentRegistryBaseUrl);const currentRuntimeMatches=hasMatchingRuntimeSnapshot(config,authType,targetModel);if(currentModel===targetModel&¤tAuth===authType&&baseUrlMatches&&!(recorded&&!recorded.isRuntime&¤tRuntimeMatches)){return}const useRuntimeSnapshot=Boolean(recorded?.isRuntime)&&hasMatchingRuntimeSnapshot(config,authType,targetModel);const switchModelId=useRuntimeSnapshot?buildRuntimeSnapshotId(authType,targetModel):targetModel;const requireCachedCredentials=authType==="qwen-oauth"&¤tAuth!==authType;const switchOptions=targetBaseUrl||requireCachedCredentials?{...targetBaseUrl?{baseUrl:targetBaseUrl}:{},...requireCachedCredentials?{requireCachedCredentials:true}:{}}:void 0;try{await config.switchModel(authType,switchModelId,switchOptions)}catch(error){debugLogger2.warn(`restore session model failed (${targetModel}/${authType}): ${error instanceof Error?error.message:String(error)}`)}}__name(applyRestoredSessionModel,"applyRestoredSessionModel");async function restoreSessionModelThenAuthenticate(config,projection,authenticate){const originalAuth=liveAuthType(config);const originalModel=config.getModel();const originalBaseUrl=config.getCurrentModelRegistryBaseUrl?.();const originalRuntimeSnapshot=config.getActiveRuntimeModelSnapshot?.();await applyRestoredSessionModel(config,projection);try{await authenticate()}catch(error){if(liveAuthType(config)===originalAuth&&config.getModel()===originalModel&&(config.getCurrentModelRegistryBaseUrl?.()??void 0)===(originalBaseUrl??void 0)&&runtimeSnapshotIdentity(config.getActiveRuntimeModelSnapshot?.())===runtimeSnapshotIdentity(originalRuntimeSnapshot)){throw error}debugLogger2.warn("restored session model made authentication fail; retrying with settings model");if(!originalAuth||!originalModel){throw error}const rollbackModelId=originalRuntimeSnapshot?.authType===originalAuth&&originalRuntimeSnapshot.modelId===stripRuntimeSnapshotPrefix(originalModel)?buildRuntimeSnapshotId(originalAuth,stripRuntimeSnapshotPrefix(originalModel)):originalModel;try{await config.switchModel(originalAuth,rollbackModelId,typeof originalBaseUrl==="string"?{baseUrl:originalBaseUrl}:void 0)}catch{throw error}await authenticate()}}__name(restoreSessionModelThenAuthenticate,"restoreSessionModelThenAuthenticate");init_esbuild_shims();var SSH_SLASH_COMMAND_POLICY={allowSessionReset:false,allowWorkspaceSettingsWrite:false,persistModelSelection:false,blockedBuiltinCommandNames:[]};var sshCommands=new Set(["help","model","effort","compress","context"]);function isSshSessionCommandAllowed(command){return command.kind==="built-in"&&sshCommands.has(command.name)}__name(isSshSessionCommandAllowed,"isSshSessionCommandAllowed");var unsupportedSessionMethods=new Set([SERVE_STATUS_EXT_METHODS.sessionMessageGroups,SERVE_CONTROL_EXT_METHODS.sessionCd,SERVE_CONTROL_EXT_METHODS.sessionBranch,SERVE_CONTROL_EXT_METHODS.sessionSideTask,SERVE_CONTROL_EXT_METHODS.sessionForkAgent,SERVE_CONTROL_EXT_METHODS.sessionBtw,SERVE_CONTROL_EXT_METHODS.sessionArtifactsPersist,SERVE_CONTROL_EXT_METHODS.sessionMessagesDelete,SERVE_CONTROL_EXT_METHODS.sessionRewind,SERVE_CONTROL_EXT_METHODS.sessionWorkflowTaskAction,SERVE_CONTROL_EXT_METHODS.sessionMcpRuntimeAdd,SERVE_CONTROL_EXT_METHODS.sessionMcpRuntimeRemove,SERVE_CONTROL_EXT_METHODS.sessionLanguage,SERVE_CONTROL_EXT_METHODS.sessionManagedConversationBindingCommit,SERVE_CONTROL_EXT_METHODS.sessionManagedConversationBindingRelease,"rewindSession"]);function isSshWorkspaceExtMethodAllowed(method){return!(method.startsWith("qwen/control/workspace/")||method.startsWith("qwen/skills/")||method.startsWith("qwen/session/sources/")||method.startsWith("qwen/settings/")&&method!=="qwen/settings/getCore"||unsupportedSessionMethods.has(method))}__name(isSshWorkspaceExtMethodAllowed,"isSshWorkspaceExtMethodAllowed");init_esbuild_shims();init_esbuild_shims();var debugLogger3=createDebugLogger("CLI_COMMANDS");function commandOrigin(command){const owner=command.extensionName?`extension "${command.extensionName}"`:command.kind;return`${owner} command "${command.name}"`}__name(commandOrigin,"commandOrigin");var CommandService=class _CommandService{constructor(commands){this.commands=commands}static{__name(this,"CommandService")}static async create(loaders,signal,disabledNames){const results=await Promise.allSettled(loaders.map(loader=>loader.loadCommands(signal)));const allCommands=[];for(const result of results){if(result.status==="fulfilled"){allCommands.push(...result.value)}else{debugLogger3.debug("A command loader failed:",result.reason)}}const commandMap=new Map;for(const cmd of allCommands){let finalName=cmd.name;if(cmd.extensionName&&commandMap.has(cmd.name)){let renamedName=`${cmd.extensionName}.${cmd.name}`;let suffix=1;while(commandMap.has(renamedName)){renamedName=`${cmd.extensionName}.${cmd.name}${suffix}`;suffix++}finalName=renamedName}const shadowed=commandMap.get(finalName);if(shadowed){debugLogger3.warn(`Slash command "/${finalName}" from ${commandOrigin(shadowed)} is replaced by ${commandOrigin(cmd)}`)}commandMap.set(finalName,{...cmd,name:finalName})}if(disabledNames&&disabledNames.size>0){const normalizedDisabled=new Set;for(const entry of disabledNames){const trimmed=entry.trim();if(trimmed)normalizedDisabled.add(trimmed.toLowerCase())}if(normalizedDisabled.size>0){for(const[name,cmd]of Array.from(commandMap.entries())){if(commandRestrictionNames(cmd).some(candidate=>normalizedDisabled.has(candidate))){commandMap.delete(name)}}}}const finalCommands=Object.freeze(Array.from(commandMap.values()));return new _CommandService(finalCommands)}getCommands(){return this.commands}getCommandsForMode(mode){return Object.freeze(filterCommandsForMode(this.commands.filter(cmd=>!cmd.hidden&&cmd.userInvocable!==false),mode))}getModelInvocableCommands(){return this.commands.filter(cmd=>!cmd.hidden&&cmd.modelInvocable===true)}};init_esbuild_shims();init_esbuild_shims();init_esbuild_shims();import fs from"node:fs/promises";import path from"node:path";var debugLogger4=createDebugLogger("SESSION_PATHS");var OPENAI_LOG_SCAN_LIMIT=100;async function collectSessionPathInfo(context){const config=context.services.config;const sessionId=config?.getSessionId()||context.session.stats.sessionId||"unknown";const contentGeneratorConfig=config?.getContentGeneratorConfig();const workingDir=config?.getWorkingDir()||process.cwd();const openAILogDir=resolveOpenAILogDir(contentGeneratorConfig?.openAILoggingDir,workingDir);const openAILoggingEnabled=contentGeneratorConfig?.enableOpenAILogging===true;const latestOpenAILog=openAILoggingEnabled&&sessionId!=="unknown"?await findLatestOpenAILogForSession(openAILogDir,sessionId):void 0;const transcriptPath=config?.getTranscriptPath()||"";const debugLogPath=config?.getDebugMode()&&sessionId!=="unknown"?Storage.getDebugLogPath(sessionId):"";const planFilePath=config?.getPlanFilePath()||(sessionId==="unknown"?"":Storage.getPlanFilePath(sessionId));const planFileExists=planFilePath?await pathExists(planFilePath):false;const sections=[{title:"Session files",entries:[{label:"Session ID",value:sessionId},...transcriptPath?[{label:"Transcript",value:transcriptPath}]:[],...debugLogPath?[{label:"Debug log",value:debugLogPath}]:[],...planFileExists?[{label:"Plan file",value:planFilePath}]:[]]}];if(openAILoggingEnabled){sections.push({title:"OpenAI logs",entries:[{label:"Directory",value:openAILogDir},{label:"Latest for session",value:latestOpenAILog??"none yet"}]})}return{sections}}__name(collectSessionPathInfo,"collectSessionPathInfo");function formatSessionPathInfo(info){const lines=[];for(const[index,section]of info.sections.entries()){if(index>0){lines.push("")}lines.push(`${section.title}:`);for(const entry of section.entries){lines.push(` ${entry.label}: ${entry.value}`)}}return lines.join("\n")}__name(formatSessionPathInfo,"formatSessionPathInfo");async function findLatestOpenAILogForSession(logDir,sessionId){const files=await listLogFiles(logDir,name=>/^openai-.*\.json$/.test(name));for(const file of files){try{const raw=await fs.readFile(file,"utf-8");const parsed=JSON.parse(raw);if(hasContextSessionId(parsed,sessionId)){return file}}catch(error){if(error instanceof SyntaxError||error.code==="ENOENT"){continue}debugLogger4.warn("Error reading OpenAI log file",file,error)}}return void 0}__name(findLatestOpenAILogForSession,"findLatestOpenAILogForSession");async function listLogFiles(dir,predicate){try{const entries=await fs.readdir(dir,{withFileTypes:true});const files=[];for(const entry of entries){if(!entry.isFile()||!predicate(entry.name)){continue}insertRecentFile(files,path.join(dir,entry.name))}return files}catch(error){if(error.code!=="ENOENT"){debugLogger4.warn("Unable to list OpenAI log directory",dir,error)}return[]}}__name(listLogFiles,"listLogFiles");function insertRecentFile(files,file){const insertAt=files.findIndex(existing=>file>existing);if(insertAt===-1){if(files.length<OPENAI_LOG_SCAN_LIMIT){files.push(file)}return}files.splice(insertAt,0,file);if(files.length>OPENAI_LOG_SCAN_LIMIT){files.pop()}}__name(insertRecentFile,"insertRecentFile");async function pathExists(filePath){try{await fs.access(filePath);return true}catch{return false}}__name(pathExists,"pathExists");function hasContextSessionId(value,sessionId){if(!value||typeof value!=="object"){return false}const context=value.context;if(!context||typeof context!=="object"){return false}const ctx=context;return ctx.sessionId===sessionId||ctx.promptId===sessionId}__name(hasContextSessionId,"hasContextSessionId");var aboutCommand={name:"status",altNames:["about"],get description(){return t("show version info")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],canRunDuringStreaming:true,action:__name(async context=>{const systemInfo=await getExtendedSystemInfo(context);if(context.executionMode!=="interactive"){const lines=[`Qwen Code v${systemInfo.cliVersion}`,`Model: ${systemInfo.modelVersion}`,`Fast Model: ${systemInfo.fastModel??"not set"}`,`Auth: ${systemInfo.selectedAuthType}`,`Platform: ${systemInfo.osPlatform} ${systemInfo.osArch} (${systemInfo.osRelease})`,`Node.js: ${systemInfo.nodeVersion}`,`Session: ${systemInfo.sessionId}`,...systemInfo.gitCommit?[`Git commit: ${systemInfo.gitCommit}`]:[],...systemInfo.ideClient?[`IDE: ${systemInfo.ideClient}`]:[],...systemInfo.lspStatus?[`LSP: ${systemInfo.lspStatus}`]:[]];return{type:"message",messageType:"info",content:lines.join("\n")}}const aboutItem={type:"about",systemInfo};context.ui.addItem(aboutItem,Date.now());return},"action"),subCommands:[{name:"paths",get description(){return t("show paths for current session files and logs")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],canRunDuringStreaming:true,action:__name(async context=>{const info=await collectSessionPathInfo(context);const content=formatSessionPathInfo(info);return{type:"message",messageType:"info",content}},"action")}]};init_esbuild_shims();var ADVISOR_SCHEMA={type:"object",additionalProperties:false,properties:{verdict:{type:"string",minLength:1},risks:{type:"string",minLength:1},missingEvidence:{type:"string",minLength:1},recommendation:{type:"string",minLength:1}},required:["verdict","risks","missingEvidence","recommendation"]};function buildAdvisorPrompt(focus){return["<system-reminder>","You are acting as an ADVISOR \u2014 an independent senior reviewer giving a second opinion on the conversation so far. The transcript above may be truncated to the most recent turns; treat what is shown as the evidence available to you.","","CRITICAL CONSTRAINTS:","- You have NO tools. Base every claim strictly on evidence present in the transcript; never claim to have verified something you could not observe.","- Do not perform the task or write the implementation. Review only.","- Be direct about problems: flawed assumptions, premature conclusions, unverified claims, risky next steps.","- The main conversation is NOT interrupted; your review is shown to the user only.","","Return exactly one JSON object with these string fields and no markdown fence, preamble, extra key, or commentary:","- verdict: one short paragraph stating whether the current approach or conclusion is sound.",'- risks: concrete risks or flawed assumptions, each citing transcript evidence. Write "None found" if none.',"- missingEvidence: claims asserted but not verified in the visible transcript (earlier verification may exist outside the shown window).","- recommendation: the single most valuable next action.","</system-reminder>","",focus||"Review the conversation above."].join("\n")}__name(buildAdvisorPrompt,"buildAdvisorPrompt");function formatAdvisorReview(value){const fields=["verdict","risks","missingEvidence","recommendation"];if(!value||Object.keys(value).length!==fields.length||fields.some(field=>{const fieldValue=value[field];return typeof fieldValue!=="string"||fieldValue.trim().length===0})){throw new Error("Advisor returned invalid structured output.")}const review=value;return["## Verdict",review.verdict.trim(),"## Risks",review.risks.trim(),"## Missing evidence",review.missingEvidence.trim(),"## Recommendation",review.recommendation.trim()].join("\n\n")}__name(formatAdvisorReview,"formatAdvisorReview");function parseJsonObjectText(text){const value=text?.trim();if(!value)return void 0;const firstStructuredChar=value.search(/[[{]/);if(firstStructuredChar!==-1&&value[firstStructuredChar]==="["){return void 0}const first=value.indexOf("{");const last=value.lastIndexOf("}");if(first===-1||last<=first)return void 0;try{const parsed=JSON.parse(value.slice(first,last+1));return parsed&&typeof parsed==="object"&&!Array.isArray(parsed)?parsed:void 0}catch{return void 0}}__name(parseJsonObjectText,"parseJsonObjectText");function formatAdvisorError(error){return t("Advisor review failed: {{error}}",{error:error instanceof Error?error.message:String(error||"Unknown error")})}__name(formatAdvisorError,"formatAdvisorError");function unavailableModelMessage(modelName,availableModelIds){const configured=availableModelIds.length>0?t("Configured models: {{models}}.",{models:availableModelIds.join(", ")}):t("No models are configured.");return[`Advisor model '${modelName}' is not configured.`,configured,"Configure models in settings.modelProviders, or run /advisor without arguments to choose a model."].join("\n")}__name(unavailableModelMessage,"unavailableModelMessage");async function setAdvisorModel(context,model){if(context.executionPolicy?.persistModelSelection===false){return{type:"message",messageType:"error",content:t("This model selection is not available in this session.")}}const{config,settings}=context.services;if(!config){return{type:"message",messageType:"error",content:t("Advisor configuration is unavailable.")}}if(model){const availability=checkAdvisorModelAvailability(config,model);if(!availability.available){return{type:"message",messageType:"error",content:unavailableModelMessage(model,availability.availableModelIds)}}}const applied=await config.setAdvisorModel(model);if(applied===false){return{type:"message",messageType:"error",content:t("Advisor configuration is unavailable.")}}settings.setValue("User","advisorModel",model??"");return{type:"message",messageType:"info",content:model?t("Advisor set to {{model}}",{model}):t("Advisor disabled")}}__name(setAdvisorModel,"setAdvisorModel");async function askAdvisor(context,focus,abortSignal){const{config}=context.services;if(!config)throw new Error(t("Config not loaded."));const cacheSafeParams=buildBtwCacheSafeParams(config);if(!cacheSafeParams||config.getLlmClient().getHistoryForForkWindow().length===0){throw new Error(t("No conversation context available for /advisor"))}const advisorModel=config.getAdvisorModel();const result=await runForkedAgent({config,userMessage:buildAdvisorPrompt(focus),cacheSafeParams,jsonSchema:ADVISOR_SCHEMA,...advisorModel?{model:advisorModel}:{},abortSignal,disableModelFallbacks:true});return{text:formatAdvisorReview(result.jsonResult??parseJsonObjectText(result.text)),model:result.model}}__name(askAdvisor,"askAdvisor");var advisorCommand={name:"advisor",get description(){return t("Configure the Advisor model")},argumentHint:"[<model-id>|off|review [focus]]",kind:"built-in",supportedModes:["interactive","non_interactive","acp"],completion:__name(async(context,partialArg)=>{const prefix=partialArg.trim();const fixed=[{value:"off",description:t("Disable Advisor")},{value:"review",description:t("Get a second opinion on the current conversation from a reviewer model")}].filter(({value})=>value.startsWith(prefix));if(!context.services.config||prefix.startsWith("review "))return fixed;return[...fixed,...context.services.config.getAllConfiguredModels().filter(model=>isAdvisorModelEligible(model)).map(model=>model.id).filter(id=>id.startsWith(prefix))]},"completion"),action:__name(async(context,args)=>{const value=context.invocation?.args?.trim()||args.trim();const[subcommand="",...rest]=value.split(/\s+/);const isReview=subcommand==="review";if(!isReview){if(!value){if(context.executionMode!=="interactive"){return{type:"message",messageType:"info",content:[`Advisor: ${context.services.config?.getAdvisorModel()?.split("\0")[0]??"off"}`,`Session calls: ${context.services.config?.getAdvisorUseCount()??0} / ${context.services.config?.getAdvisorMaxUses()||"unlimited"}`,"Each consultation sends the conversation to the selected provider and consumes additional tokens.","Use /advisor <model-id> or /advisor off."].join("\n")}}return{type:"dialog",dialog:"advisor-model"}}return setAdvisorModel(context,value.toLowerCase()==="off"?void 0:value)}const focus=rest.join(" ").trim();if(focus.length>BTW_MAX_INPUT_LENGTH){return{type:"message",messageType:"error",content:t("Focus too long (max {{max}} chars)",{max:String(BTW_MAX_INPUT_LENGTH)})}}const{config}=context.services;const{ui}=context;if(!config){return{type:"message",messageType:"error",content:t("Config not loaded.")}}if(!config.getModel()){return{type:"message",messageType:"error",content:t("No model configured.")}}const abortSignal=context.abortSignal??new AbortController().signal;const executionMode=context.executionMode??"interactive";if(executionMode!=="interactive"){try{const review=await askAdvisor(context,focus,abortSignal);return{type:"message",messageType:"info",content:review.text}}catch(error){return{type:"message",messageType:"error",content:formatAdvisorError(error)}}}const turnInFlight=!ui.isIdleRef.current||ui.pendingItem!==null;if(turnInFlight){return{type:"message",messageType:"error",content:t("Another operation is in progress, wait for it to complete before running /advisor")}}try{ui.setPendingItem({type:"info",text:t("Consulting advisor...")});const review=await askAdvisor(context,focus,abortSignal);if(abortSignal.aborted)return;ui.addItem({type:"advisor",text:review.text,model:review.model},Date.now())}catch(error){if(abortSignal.aborted)return;ui.addItem({type:"error",text:formatAdvisorError(error)},Date.now())}finally{if(!abortSignal.aborted)ui.setPendingItem(null)}},"action")};init_esbuild_shims();function statusLabel(entry){switch(entry.kind){case"agent":{const status=entry.status;switch(status){case"completed":return"completed";case"failed":return`failed: ${entry.error??"unknown error"}`;case"cancelled":return"cancelled";case"paused":return entry.resumeBlockedReason?`paused (resume blocked): ${entry.resumeBlockedReason}`:"paused";case"running":return"running";default:{const _exhaustive=status;throw new Error(`statusLabel(agent): unknown status: ${JSON.stringify(_exhaustive)}`)}}}case"shell":{const status=entry.status;switch(status){case"completed":return`completed (exit ${entry.exitCode??"?"})`;case"failed":return`failed: ${entry.error??"unknown error"}`;case"cancelled":return"cancelled";case"running":return"running";default:{const _exhaustive=status;throw new Error(`statusLabel(shell): unknown status: ${JSON.stringify(_exhaustive)}`)}}}case"monitor":{const events=`${entry.eventCount} event${entry.eventCount===1?"":"s"}`;const status=entry.status;switch(status){case"completed":return entry.error?`completed (${entry.error}, ${events})`:`completed (exit ${entry.exitCode??"?"}, ${events})`;case"failed":return`failed: ${entry.error??"unknown error"} (${events})`;case"cancelled":return`cancelled (${events})`;case"running":return`running (${events})`;default:{const _exhaustive=status;throw new Error(`statusLabel(monitor): unknown status: ${JSON.stringify(_exhaustive)}`)}}}default:{const _exhaustive=entry;throw new Error(`statusLabel: unknown TaskEntry kind: ${JSON.stringify(_exhaustive)}`)}}}__name(statusLabel,"statusLabel");function taskLabel(entry){switch(entry.kind){case"agent":return buildBackgroundEntryLabel(entry);case"shell":return entry.command;case"monitor":return entry.description;default:{const _exhaustive=entry;throw new Error(`taskLabel: unknown TaskEntry kind: ${JSON.stringify(_exhaustive)}`)}}}__name(taskLabel,"taskLabel");function taskId(entry){switch(entry.kind){case"agent":return entry.agentId;case"shell":return entry.shellId;case"monitor":return entry.monitorId;default:{const _exhaustive=entry;throw new Error(`taskId: unknown TaskEntry kind: ${JSON.stringify(_exhaustive)}`)}}}__name(taskId,"taskId");function taskOutputPath(entry){switch(entry.kind){case"agent":case"shell":return entry.outputFile;case"monitor":return void 0;default:{const _exhaustive=entry;throw new Error(`taskOutputPath: unknown TaskEntry kind: ${JSON.stringify(_exhaustive)}`)}}}__name(taskOutputPath,"taskOutputPath");var tasksCommand={name:"tasks",get description(){return t("List background tasks (text dump \u2014 interactive dialog opens via the footer pill)")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],canRunDuringStreaming:true,action:__name(async context=>{const{config}=context.services;if(!config){return{type:"message",messageType:"error",content:"Config not available."}}const agentEntries=[...config.getBackgroundTaskRegistry().getAll()];const shellEntries=[...config.getBackgroundShellRegistry().getAll()];const monitorEntries=[...config.getMonitorRegistry().getAll()];const entries=[...agentEntries,...shellEntries,...monitorEntries].sort((a,b)=>a.startTime-b.startTime);if(entries.length===0){return{type:"message",messageType:"info",content:"No background tasks."}}const now=Date.now();const lines=[];if(context.executionMode==="interactive"){lines.push(t("Tip: focus the Background tasks pill in the footer (use \u2193 from an empty composer) and press Enter for the interactive dialog with detail view + live updates."),"")}lines.push(`Background tasks (${entries.length} total)`,"");for(const entry of entries){const endTime=entry.endTime??now;const runtime=formatDuration(endTime-entry.startTime,{hideTrailingZeros:true});const pidPart=(entry.kind==="shell"||entry.kind==="monitor")&&entry.pid!==void 0?` pid=${entry.pid}`:"";lines.push(`[${taskId(entry)}] ${statusLabel(entry)} ${runtime}${pidPart} ${taskLabel(entry)}`);const outputPath=taskOutputPath(entry);if(outputPath){lines.push(` output: ${outputPath}`)}}return{type:"message",messageType:"info",content:stripUnsafeCharacters(lines.join("\n"))}},"action")};init_esbuild_shims();function snapshotToTask(s){return{id:s.runId,kind:"workflow",runId:s.runId,...s.parentSessionId?{parentSessionId:s.parentSessionId}:{},...s.toolUseId?{toolUseId:s.toolUseId}:{},...s.sourceRef?{sourceRef:{...s.sourceRef}}:{},...s.workflowCalls?{workflowCalls:s.workflowCalls.map(call=>({...call}))}:{},...s.workflowCallsTruncated?{workflowCallsTruncated:true}:{},...s.workflowName?{workflowName:s.workflowName}:{},description:s.meta?.name??s.runId,meta:s.meta,status:s.status,currentPhase:null,currentPhaseVisitId:null,phases:s.phases??[],phaseVisits:s.phaseVisits??[],dispatches:s.dispatches??[],sourceRunId:s.sourceRunId,startMode:s.startMode,agentsDispatched:s.agentsDispatched??0,agentsCompleted:s.agentsCompleted??0,recentLogs:s.recentLogs??[],events:s.events??[],tokensSpent:s.tokensSpent??0,tokenBudgetTotal:s.tokenBudgetTotal??null,perPhaseTokens:new Map(s.perPhaseTokens??[]),pendingApprovals:[],script:s.script??"",scriptPath:s.scriptPath,result:s.result,error:s.error,startTime:s.startTime,endTime:s.endTime,outputFile:"",outputOffset:0,notified:true,abortController:new AbortController}}__name(snapshotToTask,"snapshotToTask");function rowLine(entry,now){const endTime=entry.endTime??now;const runtime=formatDuration(endTime-entry.startTime,{hideTrailingZeros:true});const label=entry.meta?.name??entry.runId;const phase=entry.currentPhase?` \xB7 ${entry.currentPhase}`:"";const counts=entry.agentsDispatched>0?` \xB7 ${entry.agentsCompleted}/${entry.agentsDispatched} agents`:"";const phaseCount=entry.phases.length>0?` \xB7 ${entry.phases.length} ${entry.phases.length===1?"phase":"phases"}`:"";const budgetChip=entry.tokensSpent>0||entry.tokenBudgetTotal!==null?entry.tokenBudgetTotal!==null?` \xB7 ${formatTokenCount(entry.tokensSpent)}/${formatTokenCount(entry.tokenBudgetTotal)}t`:` \xB7 ${formatTokenCount(entry.tokensSpent)}t`:"";const errorTail=entry.status==="failed"&&entry.error?` \u2014 ${entry.error.slice(0,80)}`:"";return` ${entry.runId.padEnd(20)} ${entry.status.padEnd(10)} ${runtime.padStart(8)} ${label}${phase}${counts}${phaseCount}${budgetChip}${errorTail}`}__name(rowLine,"rowLine");var MAX_DETAIL_ERROR_CHARS=4096;function isHollow(value){if(typeof value!=="object"||value===null)return false;return Object.values(value).every(isHollow)}__name(isHollow,"isHollow");function withoutHollowFailures(result){if(typeof result!=="object"||result===null||Array.isArray(result)){return result}const kept={...result};for(const key of REPORTED_FAILURE_KEYS){try{if(isHollow(kept[key]))delete kept[key]}catch{}}return kept}__name(withoutHollowFailures,"withoutHollowFailures");function mayHaveLostDetail(result){return typeof result==="object"&&result!==null||typeof result==="string"&&result.startsWith("(non-JSON-serializable ")}__name(mayHaveLostDetail,"mayHaveLostDetail");function resultPreviewFor(entry,source){if(entry.status!=="completed")return{legacy:false};if(!source){return{preview:buildWorkflowResultPreview(entry.result),legacy:false}}const{snapshot}=source;if(snapshot.resultPreview){return{preview:snapshot.resultPreview,legacy:false}}if(!Object.hasOwn(snapshot,"result"))return{legacy:true};const{result}=snapshot;return{preview:{...buildWorkflowResultPreview(result),reportedFailures:reportedFailureLines(withoutHollowFailures(result))},legacy:mayHaveLostDetail(result)}}__name(resultPreviewFor,"resultPreviewFor");function indent(text,prefix){return text.split("\n").map(line=>prefix+line).join("\n")}__name(indent,"indent");async function confirmedSnapshotFile(config,runId){if(!isWorkflowRunId(runId)||!config.storage)return void 0;return await readWorkflowSnapshot(config,runId)?config.storage.getWorkflowRunSnapshotPath(runId):void 0}__name(confirmedSnapshotFile,"confirmedSnapshotFile");function detailLines(entry,now,source){const lines=[];const endTime=entry.endTime??now;const runtime=formatDuration(endTime-entry.startTime,{hideTrailingZeros:true});lines.push(`Workflow ${entry.runId}`);if(entry.meta?.name){lines.push(` name : ${entry.meta.name}`)}if(entry.meta?.description){lines.push(` description : ${entry.meta.description}`)}if(entry.meta?.whenToUse){lines.push(` whenToUse : ${entry.meta.whenToUse}`)}lines.push(` status : ${entry.status}`);lines.push(` runtime : ${runtime}`);if(entry.currentPhase){lines.push(` currentPhase: ${entry.currentPhase}`)}lines.push(` agents : ${entry.agentsCompleted}/${entry.agentsDispatched}`);lines.push(` tokens : ${formatTokenCount(entry.tokensSpent)}`);lines.push(` cap : ${entry.tokenBudgetTotal!==null?formatTokenCount(entry.tokenBudgetTotal):"(no cap)"}`);if(entry.error){const error=truncateWorkflowText(sanitizeWorkflowText(entry.error),MAX_DETAIL_ERROR_CHARS);lines.push(` error : ${error.split("\n").join("\n ")}`)}if(source?.file){lines.push(` snapshotFile: ${source.file}`)}if(entry.phases.length>0){lines.push("");lines.push(` Phases (${entry.phases.length})`);for(const phase of entry.phases){const phaseTokens=entry.perPhaseTokens.get(phase)??0;const chip=phaseTokens>0?` \xB7 ${formatTokenCount(phaseTokens)}t`:"";lines.push(` \xB7 ${phase}${chip}`)}const prePhaseTokens=entry.perPhaseTokens.get(null)??0;if(prePhaseTokens>0){lines.push(` \xB7 (no phase) \xB7 ${formatTokenCount(prePhaseTokens)}t`)}}if(entry.recentLogs.length>0){lines.push("");lines.push(` Logs (last ${entry.recentLogs.length})`);for(const line of entry.recentLogs){lines.push(` ${line}`)}}if(source&&source.snapshot.dispatches===void 0){lines.push(""," Failed agents: not recorded in this snapshot")}else{const failures=buildFailureLines(entry);if(failures.length>0){const count=entry.dispatches.filter(d=>d.status==="failed").length;lines.push("",` Failed agents (${count})`);for(const line of failures)lines.push(indent(line," "))}}const{preview:preview2,legacy}=resultPreviewFor(entry,source);const reported=(preview2?.reportedFailures??[]).map(line=>truncateWorkflowText(sanitizeWorkflowText(line),MAX_FAILURE_LINE_CHARS));if(reported.length>0){lines.push(""," Reported failures");for(const line of reported)lines.push(indent(line," "))}if(entry.status==="completed"){lines.push(""," Result");if(!preview2){lines.push(" (this snapshot did not record a result)")}else{const sanitized=sanitizeWorkflowText(preview2.text);const text=truncateWorkflowText(sanitized,MAX_WORKFLOW_RESULT_PREVIEW_CHARS);lines.push(indent(text," "));if(preview2.truncated||text!==sanitized){lines.push(` (preview truncated to ${MAX_WORKFLOW_RESULT_PREVIEW_CHARS} characters)`)}}if(legacy){lines.push(" (older snapshot: result details such as Error, Map, and Set values may be incomplete)")}}return lines}__name(detailLines,"detailLines");var workflowsCommand={name:"workflows",get description(){return t("List workflow runs or cooperatively pause/resume a live run")},get argumentHint(){return t("[mode [status|on|off] | runId | p <runId>]")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],subCommands:[{name:"mode",description:"Show or change this session\u2019s Workflow guidance mode",kind:"built-in",supportedModes:["interactive","non_interactive","acp"],canRunDuringStreaming:true,action:__name(async(context,args)=>{const config=context.services.config;if(!config?.isWorkflowModeSupported()){return{type:"message",messageType:"error",content:"Workflow mode is unavailable for this session owner."}}const value=args.trim()||"status";if(!["status","on","off"].includes(value)){return{type:"message",messageType:"error",content:"Usage: /workflows mode [status|on|off]"}}try{const state=value==="status"?config.getWorkflowMode():await config.setWorkflowMode(value==="on");return{type:"message",messageType:"info",content:`Workflow mode: ${state.requested?"on":"off"}${state.requested&&!state.effective?" (unavailable)":""}${state.reason?` \u2014 ${state.reason}`:""}`}}catch(error){return{type:"message",messageType:"error",content:error instanceof Error?error.message:String(error)}}},"action")}],action:__name(async(context,args)=>{const{config}=context.services;if(!config){return{type:"message",messageType:"error",content:"Config not available."}}if(!config.isWorkflowsEnabled()){return{type:"message",messageType:"error",content:"Workflows are disabled. Use /workflows mode status or off to manage the saved mode."}}const registry=config.getWorkflowRunRegistry();const allEntries=registry.list();const trimmedArgs=(args??"").trim();const tokens=trimmedArgs.split(/\s+/);if(tokens[0]==="p"){if(context.executionMode!=="interactive"){return{type:"message",messageType:"error",content:"Workflow pause controls are available only in the interactive TUI."}}if(tokens.length!==2||!tokens[1]){return{type:"message",messageType:"error",content:"Usage: /workflows p <runId>"}}const runId=tokens[1];let target=registry.get(runId);let fromSnapshot=false;if(!target){const snapshot=(await listWorkflowSnapshots(config)).find(s=>s.runId===runId);if(snapshot){target=snapshotToTask(snapshot);fromSnapshot=true}}if(!target){return{type:"message",messageType:"error",content:`Unknown live workflow runId: ${runId}`}}if(isTerminalWorkflowStatus(target.status)){return{type:"message",messageType:"error",content:`Workflow ${runId} is ${target.status} and cannot be paused or resumed.`}}if(!fromSnapshot&&!target.isBackgrounded){return{type:"message",messageType:"error",content:"Foreground workflow runs cannot be paused or resumed; only background runs support cooperative pause."}}if(target.status==="pausing"){return{type:"message",messageType:"warning",content:`Workflow ${runId} is still pausing; wait until it reaches paused before resuming.`}}if(target.status==="running"){return registry.pause(runId)?{type:"message",messageType:"info",content:`Cooperative pause requested for workflow ${runId}.`}:{type:"message",messageType:"error",content:`Workflow ${runId} could not be paused because its state changed.`}}if(target.status==="paused"){return registry.resume(runId)?{type:"message",messageType:"info",content:`Resume requested for workflow ${runId}.`}:{type:"message",messageType:"error",content:`Workflow ${runId} could not be resumed because its state changed.`}}return{type:"message",messageType:"error",content:`Workflow ${runId} is ${target.status} and cannot be paused or resumed.`}}if(trimmedArgs.length>0){let target=registry.get(trimmedArgs);let source;if(!target){const snapshot=(await listWorkflowSnapshots(config)).find(s=>s.runId===trimmedArgs);if(snapshot){target=snapshotToTask(snapshot);source={snapshot,file:await confirmedSnapshotFile(config,snapshot.runId)}}}if(!target){return{type:"message",messageType:"error",content:`Unknown workflow runId: ${trimmedArgs}`}}return{type:"message",messageType:"info",content:detailLines(target,Date.now(),source).join("\n")}}const snapshots=await listWorkflowSnapshots(config);const liveRunIds=new Set(allEntries.map(e=>e.runId));const snapshotTasks=snapshots.filter(s=>!liveRunIds.has(s.runId)).map(snapshotToTask);if(allEntries.length===0&&snapshotTasks.length===0){return{type:"message",messageType:"info",content:"No workflow runs recorded yet."}}const now=Date.now();const active=allEntries.filter(e=>isActiveWorkflowStatus(e.status)).sort((a,b)=>a.startTime-b.startTime);const terminal=[...allEntries.filter(e=>!isActiveWorkflowStatus(e.status)),...snapshotTasks].sort((a,b)=>(b.endTime??0)-(a.endTime??0));const lines=[];if(context.executionMode==="interactive"){lines.push(t("Tip: use `/workflows p <runId>` or Background tasks + p to cooperatively pause/resume; use `/workflows <runId>` for details."),"")}lines.push(`Workflow runs (${active.length+terminal.length} total \xB7 ${active.length} active)`,"");if(active.length>0){lines.push("Active");for(const entry of active)lines.push(rowLine(entry,now));lines.push("")}if(terminal.length>0){lines.push("Recent");for(const entry of terminal)lines.push(rowLine(entry,now))}return{type:"message",messageType:"info",content:lines.join("\n")}},"action")};init_esbuild_shims();var agentsCommand={name:"agents",get description(){return t("Manage subagents for specialized task delegation.")},kind:"built-in",supportedModes:["interactive"],subCommands:[{name:"manage",get description(){return t("Manage existing subagents (view, edit, delete).")},kind:"built-in",supportedModes:["interactive"],action:__name(()=>({type:"dialog",dialog:"subagent_list"}),"action")},{name:"create",get description(){return t("Create a new subagent with guided setup.")},kind:"built-in",supportedModes:["interactive"],action:__name(()=>({type:"dialog",dialog:"subagent_create"}),"action")}]};init_esbuild_shims();function parseArenaArgs(args){const modelsMatch=args.match(/--models\s+(\S+)/);let models=[];let task=args;if(modelsMatch){const modelStrings=modelsMatch[1].split(",").filter(Boolean);models=modelStrings.map(str=>{const colonIndex=str.indexOf(":");if(colonIndex>0){return{authType:str.substring(0,colonIndex),modelId:str.substring(colonIndex+1)}}return{modelId:str}});task=task.replace(/--models\s+\S+/,"").trim()}task=task.replace(/^["']|["']$/g,"").trim();return{models,task}}__name(parseArenaArgs,"parseArenaArgs");var debugLogger5=createDebugLogger("ARENA_COMMAND");function buildArenaExecutionInput(parsed,config){if(!parsed.task){return{type:"message",messageType:"error",content:[t("Usage: /arena start --models model1,model2 <task>"),"",t("Options:")," --models [authType:]model1,[authType:]model2",` ${t("Models to compete (required, at least 2)")}`,` ${t("Format: authType:modelId or just modelId")}`,"",t("Examples:"),' /arena start --models openai:gpt-4o,anthropic:claude-3 "implement sorting"',' /arena start --models qwen-coder-plus,kimi-for-coding "fix the bug"'].join("\n")}}if(parsed.models.length<2){return{type:"message",messageType:"error",content:[t("Arena requires at least 2 models. Use --models model1,model2 to specify."),t("Format: [authType:]modelId (e.g., openai:gpt-4o or just gpt-4o)")].join("\n")}}const contentGeneratorConfig=config.getContentGeneratorConfig();const defaultAuthType=contentGeneratorConfig?.authType??"openai";const modelsConfig=config.getModelsConfig();const models=[];for(const parsedModel of parsed.models){const authType=parsedModel.authType??defaultAuthType;const registryModels=modelsConfig.getAvailableModelsForAuthType(authType);const resolved=registryModels.find(m=>m.id===parsedModel.modelId);if(resolved?.imageOnly){return{type:"message",messageType:"error",content:t("Image-only model '{{model}}' cannot be used in an Arena session.",{model:parsedModel.modelId})}}models.push({modelId:parsedModel.modelId,authType,displayName:resolved?.label??parsedModel.modelId})}return{task:parsed.task,models,approvalMode:config.getApprovalMode()}}__name(buildArenaExecutionInput,"buildArenaExecutionInput");function recordArenaItem(config,item){try{const chatRecorder=config.getChatRecordingService();if(!chatRecorder)return;chatRecorder.recordSlashCommand({phase:"result",rawCommand:"/arena",outputHistoryItems:[{...item}]})}catch{debugLogger5.error("Failed to record arena history item")}}__name(recordArenaItem,"recordArenaItem");function executeArenaCommand(config,ui,input){let chatHistory;try{const fullHistory=config.getLlmClient().getChat().getHistoryShallow();chatHistory=stripStartupContext(fullHistory)}catch{debugLogger5.debug("Could not retrieve chat history for arena agents")}const manager=new ArenaManager(config);const emitter=manager.getEventEmitter();const detachListeners=[];const agentLabels=new Map;const addArenaMessage=__name((type,text)=>{ui.addItem({type,text},Date.now())},"addArenaMessage");const addAndRecordArenaMessage=__name((type,text)=>{const item={type,text};ui.addItem(item,Date.now());recordArenaItem(config,item)},"addAndRecordArenaMessage");const handleSessionStart=__name(event=>{const modelList=event.models.map((model,index)=>` ${index+1}. ${model.modelId}`).join("\n");addArenaMessage("info",t('Arena started with {{count}} agents on task: "{{task}}"\nModels:\n{{modelList}}',{count:String(event.models.length),task:event.task,modelList}))},"handleSessionStart");const handleAgentStart=__name(event=>{agentLabels.set(event.agentId,event.model.modelId);debugLogger5.debug(`Arena agent started: ${event.model.modelId} (${event.agentId})`)},"handleAgentStart");const handleSessionUpdate=__name(event=>{const attachHintPrefix="To view agent panes, run: ";if(event.message.startsWith(attachHintPrefix)){const command=event.message.slice(attachHintPrefix.length).trim();addAndRecordArenaMessage("info",t("Arena panes are running in tmux. Attach with: `{{command}}`",{command}));return}if(event.type==="success"){addAndRecordArenaMessage("success",event.message)}else if(event.type==="info"){addAndRecordArenaMessage("info",event.message)}else{addAndRecordArenaMessage("warning",event.message)}},"handleSessionUpdate");const handleAgentError=__name(event=>{const label=agentLabels.get(event.agentId)||event.agentId;addAndRecordArenaMessage("error",t("[{{label}}] failed: {{error}}",{label,error:event.error}))},"handleAgentError");const buildAgentCardData=__name(result=>({label:result.model.modelId,status:result.status,durationMs:result.stats.durationMs,totalTokens:result.stats.totalTokens,inputTokens:result.stats.inputTokens,outputTokens:result.stats.outputTokens,toolCalls:result.stats.toolCalls,successfulToolCalls:result.stats.successfulToolCalls,failedToolCalls:result.stats.failedToolCalls,rounds:result.stats.rounds,error:result.error,diff:result.diff,diffSummary:result.diffSummary,modifiedFiles:result.modifiedFiles,approachSummary:result.approachSummary}),"buildAgentCardData");const handleAgentComplete=__name(event=>{if(!isTerminalStatus(event.result.status)){return}const agent=buildAgentCardData(event.result);const item={type:"arena_agent_complete",agent};ui.addItem(item,Date.now());recordArenaItem(config,item)},"handleAgentComplete");const handleSessionError=__name(event=>{addAndRecordArenaMessage("error",`${event.error}`)},"handleSessionError");const handleSessionComplete=__name(event=>{const item={type:"arena_session_complete",sessionStatus:event.result.status,task:event.result.task,totalDurationMs:event.result.totalDurationMs??0,agents:event.result.agents.map(buildAgentCardData)};ui.addItem(item,Date.now());recordArenaItem(config,item)},"handleSessionComplete");emitter.on("session_start",handleSessionStart);detachListeners.push(()=>emitter.off("session_start",handleSessionStart));emitter.on("agent_start",handleAgentStart);detachListeners.push(()=>emitter.off("agent_start",handleAgentStart));emitter.on("session_update",handleSessionUpdate);detachListeners.push(()=>emitter.off("session_update",handleSessionUpdate));emitter.on("agent_error",handleAgentError);detachListeners.push(()=>emitter.off("agent_error",handleAgentError));emitter.on("agent_complete",handleAgentComplete);detachListeners.push(()=>emitter.off("agent_complete",handleAgentComplete));emitter.on("session_error",handleSessionError);detachListeners.push(()=>emitter.off("session_error",handleSessionError));emitter.on("session_complete",handleSessionComplete);detachListeners.push(()=>emitter.off("session_complete",handleSessionComplete));config.setArenaManager(manager);const cols=process.stdout.columns||120;const rows=Math.max((process.stdout.rows||40)-2,1);const lifecycle=manager.start({task:input.task,models:input.models,cols,rows,approvalMode:input.approvalMode,chatHistory}).then(()=>{debugLogger5.debug("Arena agents settled")},error=>{const message2=error instanceof Error?error.message:String(error);addAndRecordArenaMessage("error",`${message2}`);debugLogger5.error("Arena session failed:",error);config.setArenaManager(null);for(const detach of detachListeners){detach()}});manager.setLifecyclePromise(lifecycle)}__name(executeArenaCommand,"executeArenaCommand");var arenaCommand={name:"arena",get description(){return t("Manage Arena sessions")},kind:"built-in",subCommands:[{name:"start",get description(){return t("Start an Arena session with multiple models competing on the same task")},kind:"built-in",action:__name(async(context,args)=>{if(context.services.config?.getShellExecutionSandbox?.()){return{type:"message",messageType:"error",content:"Arena is unavailable in tool sandbox."}}const executionMode=context.executionMode??"interactive";if(executionMode!=="interactive"){return{type:"message",messageType:"error",content:t("Arena is not supported in non-interactive mode. Use interactive mode to start an Arena session.")}}const{services,ui}=context;const{config}=services;if(!config){return{type:"message",messageType:"error",content:t("Configuration not available.")}}const existingManager=config.getArenaManager();if(existingManager){return{type:"message",messageType:"error",content:t("An Arena session exists. Use /arena stop or /arena select to end it before starting a new one.")}}const parsed=parseArenaArgs(args);if(parsed.models.length===0){return{type:"dialog",dialog:"arena_start"}}const executionInput=buildArenaExecutionInput(parsed,config);if("type"in executionInput){return executionInput}executeArenaCommand(config,ui,executionInput)},"action")},{name:"stop",get description(){return t("Stop the current Arena session")},kind:"built-in",action:__name(async context=>{if(context.services.config?.getShellExecutionSandbox?.()){return{type:"message",messageType:"error",content:"Arena is unavailable in tool sandbox."}}const executionMode=context.executionMode??"interactive";if(executionMode!=="interactive"){return{type:"message",messageType:"error",content:t("Arena is not supported in non-interactive mode. Use interactive mode to stop an Arena session.")}}const{config}=context.services;if(!config){return{type:"message",messageType:"error",content:t("Configuration not available.")}}const manager=config.getArenaManager();if(!manager){return{type:"message",messageType:"error",content:t("No running Arena session found.")}}return{type:"dialog",dialog:"arena_stop"}},"action")},{name:"status",get description(){return t("Show the current Arena session status")},kind:"built-in",action:__name(async context=>{if(context.services.config?.getShellExecutionSandbox?.()){return{type:"message",messageType:"error",content:"Arena is unavailable in tool sandbox."}}const executionMode=context.executionMode??"interactive";if(executionMode!=="interactive"){return{type:"message",messageType:"error",content:t("Arena is not supported in non-interactive mode.")}}const{config}=context.services;if(!config){return{type:"message",messageType:"error",content:t("Configuration not available.")}}const manager=config.getArenaManager();if(!manager){return{type:"message",messageType:"error",content:t("No Arena session found. Start one with /arena start.")}}return{type:"dialog",dialog:"arena_status"}},"action")},{name:"select",altNames:["choose"],get description(){return t("Select a model result and merge its diff into the current workspace")},kind:"built-in",action:__name(async(context,args)=>{if(context.services.config?.getShellExecutionSandbox?.()){return{type:"message",messageType:"error",content:"Arena is unavailable in tool sandbox."}}const executionMode=context.executionMode??"interactive";if(executionMode!=="interactive"){return{type:"message",messageType:"error",content:t("Arena is not supported in non-interactive mode.")}}const{config}=context.services;if(!config){return{type:"message",messageType:"error",content:t("Configuration not available.")}}const manager=config.getArenaManager();if(!manager){return{type:"message",messageType:"error",content:t("No Arena session found. Start one with /arena start.")}}const sessionStatus=manager.getSessionStatus();if(sessionStatus==="running"||sessionStatus==="initializing"){return{type:"message",messageType:"error",content:t("Arena session is still running. Wait for it to complete or use /arena stop first.")}}const trimmedArgs=args.trim();if(trimmedArgs==="--discard"){if(!context.overwriteConfirmed){return{type:"confirm_action",prompt:t("Discard all Arena results and clean up worktrees?"),originalInvocation:{raw:context.invocation?.raw||"/arena select --discard"}}}await config.cleanupArenaRuntime(true);return{type:"message",messageType:"info",content:t("Arena results discarded. All worktrees cleaned up.")}}const agents=manager.getAgentStates();const hasSuccessful=agents.some(a=>isSuccessStatus(a.status));if(!hasSuccessful){return{type:"message",messageType:"error",content:[t("No successful agent results to select from. All agents failed or were cancelled."),t("Use /arena stop to end the session.")].join("\n")}}if(trimmedArgs){const matchingAgent=agents.find(a=>isSuccessStatus(a.status)&&a.model.modelId.toLowerCase()===trimmedArgs.toLowerCase());if(!matchingAgent){return{type:"message",messageType:"error",content:t('No idle agent found matching "{{name}}".',{name:trimmedArgs})}}const label=matchingAgent.model.modelId;const result=await manager.applyAgentResult(matchingAgent.agentId);if(!result.success){return{type:"message",messageType:"error",content:t("Failed to apply changes from {{label}}: {{error}}",{label,error:result.error??"Unknown error"})}}await config.cleanupArenaRuntime(true);return{type:"message",messageType:"info",content:t("Applied changes from {{label}} to workspace. Arena session complete.",{label})}}return{type:"dialog",dialog:"arena_select"}},"action")}]};init_esbuild_shims();init_esbuild_shims();function formatApprovalModeName(mode){switch(mode){case"plan":return t("plan mode");case"default":return t("Ask permissions");case"auto-edit":return t("auto-accept edits");case"auto":return t("Auto mode");case"yolo":return t("YOLO mode");default:return mode}}__name(formatApprovalModeName,"formatApprovalModeName");function formatApprovalModeDescription(mode){switch(mode){case"plan":return t("Analyze only, do not modify files or execute commands");case"default":return t("Require approval for file edits or shell commands");case"auto-edit":return t("Automatically approve file edits");case"auto":return t("Use classifier to automatically approve safe tool calls");case"yolo":return t("Automatically approve all tools");default:return mode}}__name(formatApprovalModeDescription,"formatApprovalModeDescription");function parseApprovalModeArg(arg){const trimmed=arg.trim().toLowerCase();if(!trimmed){return void 0}return APPROVAL_MODES.find(mode=>mode.toLowerCase()===trimmed)}__name(parseApprovalModeArg,"parseApprovalModeArg");var approvalModeCommand={name:"approval-mode",get description(){return t("View or change the approval mode for tool usage")},argumentHint:"<mode>",kind:"built-in",supportedModes:["interactive"],action:__name(async(context,args)=>{const mode=parseApprovalModeArg(args);if(!args.trim()){return{type:"dialog",dialog:"approval-mode"}}if(!mode){return{type:"message",messageType:"error",content:t('Invalid approval mode "{{arg}}". Valid modes: {{modes}}',{arg:args.trim(),modes:APPROVAL_MODES.join(", ")})}}const{config,settings}=context.services;let priorMode;if(config){try{priorMode=config.getApprovalMode()}catch(e){return{type:"message",messageType:"error",content:e.message}}}const autoModeNotices=mode==="auto"&&priorMode!=="auto"&&config?await import("./useAutoAcceptIndicator-OUYRR56F.js"):void 0;if(config){try{config.setApprovalMode(mode)}catch(e){return{type:"message",messageType:"error",content:e.message}}}if(autoModeNotices&&config){autoModeNotices.emitAutoModeEntryNotices({config,settings,addItem:context.ui.addItem})}return{type:"message",messageType:"info",content:t('Approval mode set to "{{mode}}"',{mode:formatApprovalModeName(mode)})}},"action")};init_esbuild_shims();var authCommand={name:"auth",altNames:["connect","login"],get description(){return t("Connect an LLM provider")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],action:__name((context,_args)=>{const executionMode=context.executionMode??"interactive";if(executionMode!=="interactive"){return{type:"message",messageType:"info",content:t("Authentication configuration is only available in interactive mode. To configure authentication, run Qwen Code interactively and use /auth, or set environment variables: OPENAI_API_KEY, OPENAI_BASE_URL, OPENAI_MODEL.")}}return{type:"dialog",dialog:"auth"}},"action")};init_esbuild_shims();var branchCommand={name:"branch",kind:"built-in",get description(){return t("Fork the current conversation into a new session")},action:__name(async(context,args)=>{const{config}=context.services;if(!config){return{type:"message",messageType:"error",content:t("Config is not available.")}}if(context.ui.isIdleRef?.current===false){return{type:"message",messageType:"error",content:t("Cannot branch while a response or tool call is in progress. Wait for it to finish or resolve the pending tool call.")}}const sessionService=config.getSessionService();const currentId=config.getSessionId();const hasRecords=await sessionService.sessionExists(currentId);if(!hasRecords){return{type:"message",messageType:"error",content:t("No conversation to branch.")}}const name=args.trim().replace(/[\r\n]+/g," ");return name?{type:"dialog",dialog:"branch",name}:{type:"dialog",dialog:"branch"}},"action")};init_esbuild_shims();function shortId(msgId){return msgId.replace(/-/g,"").slice(0,6)}__name(shortId,"shortId");function displayHandle(entry,held){const own=canonicalizeMsgId(entry.frame.msgId);let length=Math.min(shortId(entry.frame.msgId).length,own.length);const collides=__name(len=>held.some(other=>other!==entry&&canonicalizeMsgId(other.frame.msgId).startsWith(own.slice(0,len))),"collides");while(length<own.length&&collides(length)){length+=1}return own.slice(0,length)}__name(displayHandle,"displayHandle");function preview(text,max=100){const oneLine=flattenPeerLabel(text).replace(/\s+/g," ").trim();return oneLine.length>max?`${oneLine.slice(0,max-1)}\u2026`:oneLine}__name(preview,"preview");function describeRemaining(entry,expiryMs){if(expiryMs===null)return"";const wallAge=Date.now()-entry.heldAt;const age=entry.monotonicAt===void 0?wallAge:Math.max(wallAge,performance.now()-entry.monotonicAt);const remaining=expiryMs-age;if(remaining<=0)return", expiring now";const minutes=Math.ceil(remaining/6e4);return remaining<6e4?", less than a minute left":`, ${minutes} minute${minutes===1?"":"s"} left`}__name(describeRemaining,"describeRemaining");function formatHeldList(held,expiryFor=()=>null){if(held.length===0)return"No messages from other sessions are waiting.";const lines=held.map(entry=>{const peerLabel=entry.controller?flattenPeerLabel(entry.controller.label):flattenPeerLabel(entry.frame.fromName??entry.frame.from??(entry.selfSent?"this session":"unknown session"));const origin=entry.controller?"[controller]":entry.selfSent?"[own process]":"[peer]";const who=`${origin} ${peerLabel}`;const handle=flattenPeerLabel(displayHandle(entry,held));return` ${handle} ${who}
|
|
3
|
+
import{ExtensionRefreshState}from"./chunk-254YDSL2.js";import{getInteractiveModSession}from"./chunk-H3IR3GIE.js";import{contextCommand}from"./chunk-3W32X2DH.js";import{billableOutputTokens,calculateCost,commandRestrictionNames,computeSessionStats,diffCommand,extensionOwnerLabel,filterCommandsForMode,findInlineMathExpressions,formatCompressionTokenCount,formatDuration,formatTokenCount,getCompressionFailureStatusText,getSystemInfoFields,skillOriginLabel}from"./chunk-ET5M5WFN.js";import{VSCODE_SHIFT_ENTER_SEQUENCE,isWaylandSession,writeOsc52}from"./chunk-HR4TFOG6.js";import{isKittyProtocolEnabled}from"./chunk-HKA2IEQ6.js";import{themeManager}from"./chunk-W3YCOEIP.js";import{validateAuthMethod}from"./chunk-BQZF3UKI.js";import{clearSkillArgs,skillArgsNote,skillArgsPath,staleArgsWarning,writeSkillArgs}from"./chunk-TD6VSPYX.js";import{GITHUB_WORKFLOW_PATHS,INSIGHT_CSS,INSIGHT_JS,collectSessionData,extractInjections,generateExportFilename,normalizeSessionData,setupGithub,toHtml,toJson,toJsonl,toMarkdown}from"./chunk-BPFFRPWE.js";import{checkAdvisorModelAvailability,isAdvisorModelEligible,resolveHookSettingsForConfig}from"./chunk-VRKYBH5G.js";import{stripUnsafeCharacters,toCodePoints,truncateToWidth}from"./chunk-64CA3W6G.js";import{MarkdownCommandDefSchema,parseMarkdownCommand}from"./chunk-XXUK6YLA.js";import{formatUnsupportedVoiceModelMessage,getVoiceSettingsScope,isSelectableVoiceModel,isVoiceEnabled,readVoiceMode,readVoiceModel}from"./chunk-EKRUF347.js";import{rollbackStandaloneUpdate}from"./chunk-P3JEEDQZ.js";import{getInstallationInfo}from"./chunk-26MNTKT2.js";import{getExtendedSystemInfo,getGitVersion,getNpmVersion}from"./chunk-W5Z4BWWA.js";import{getReasoningEffortsForConfig}from"./chunk-4XF4ZGJG.js";import{formatAuxModelSelectorForDisplay}from"./chunk-L42NTHIT.js";import{isValidSessionId}from"./chunk-LGFF5PJA.js";import{SERVE_CONTROL_EXT_METHODS,SERVE_STATUS_EXT_METHODS}from"./chunk-LUDNUVSA.js";import{ACP_ROUTE_ID_PREFIX,isInlineModelOverrideAllowed,parseAcpModelOption,resolveAcpFastModelSelector}from"./chunk-GT4TCQ3R.js";import{getErrorMessage as getErrorMessage2}from"./chunk-ZENMAISJ.js";import{OUTPUT_LANGUAGE_AUTO,getAllSettingKeys,getDefaultValue,getFlattenedSchema,getNestedProperty,getPersistScopeForModelSelection,getSettingDefinition,isAutoLanguage,nextBooleanSettingValue,resolveOutputLanguageOrPreserveAuto,validateSettingValue,writeOutputLanguageAndRegisterPath}from"./chunk-2TAJ5STJ.js";import{getCurrentLanguage,setLanguageAsync,t}from"./chunk-NO7VTKRL.js";import{SUPPORTED_LANGUAGES,getSupportedLanguageIds,resolveSupportedLanguage}from"./chunk-U7HZUZKP.js";import{require_strip_json_comments,stripUtf8Bom}from"./chunk-DOLUT3XC.js";import{isFolderTrustEnabled,loadTrustedFolders}from"./chunk-MTDBCIDA.js";import{BTW_MAX_INPUT_LENGTH,Logger,analyzeToolResultRetention,buildBtwCacheSafeParams,buildBtwPrompt,buildLearnSkillPrompt,buildLearnVideoSkillRequest,describePeerInboxFailure,encodeInsightErrorMessage,encodeInsightProgressMessage,encodeInsightReadyMessage,findOutputStyle,generateSessionRecap,getIdeInstaller,getLastPeerInboxFailure,getMCPServerPrompts,isWsl,listPeerControllers,loadOutputStyleCatalog,parseLearnVideoInput,readPathFromWorkspace,removePeerController}from"./chunk-OU7CEG7Q.js";import{canonicalizeMsgId,describeHoldCause}from"./chunk-MKH3EH7O.js";import{buildBareRememberPrompt,buildManagedRememberPrompt}from"./chunk-FKZ46GKL.js";import{MAX_WORKFLOW_RESULT_PREVIEW_CHARS,buildWorkflowResultPreview,listWorkflowSnapshots,readWorkflowSnapshot}from"./chunk-SP6CQ3MO.js";import{toCanonicalWorkspaceArtifactPath}from"./chunk-MZUOREFD.js";import{executeModTool,modToolRequest}from"./chunk-CGDFZEER.js";import{resolveOpenAILogDir}from"./chunk-QX7W2HY7.js";import{ArenaManager,ConditionalRulesRegistry,CoreToolScheduler,EXTENSIONS_CONFIG_FILENAME,ExtensionManager,GoalPersistenceUnavailableError,IdeClient,MAX_FAILURE_LINE_CHARS,QWEN_CODE_COMPANION_EXTENSION_NAME,REPORTED_FAILURE_KEYS,SESSION_TITLE_MAX_LENGTH,SessionService,appendAutoMemoryContext,appendToLastTextPart,buildBackgroundEntryLabel,buildFailureLines,collectMemoryDiagnostics,executeRuntimeShell,flatMapTextParts,getExtensionDescription,getExtensionDisplayName,getLastApiHistoryPromptId,getToolCallFingerprint,hookEventSupportsMatcher,ideContextStore,isActiveWorkflowStatus,isCompressionFailureStatus,isExtensionCommittedWithWarningsError,isSuccessStatus,isTerminalStatus,isTerminalWorkflowStatus,isWorkflowRunId,listSavedWorkflows,loadServerHierarchicalMemory,normalizeClaudeMcpServer,parseInstallSource,partToString,persistSessionUsage,reportedFailureLines,require_toml,runForkedAgent,sanitizeWorkflowText,truncateWorkflowText,tryGenerateSessionTitle,withoutAutoMemorySnapshots}from"./chunk-2JGTWRZJ.js";import{shellResultText}from"./chunk-T7CHK6C2.js";import{external_exports}from"./chunk-TWP72VRH.js";import{canUseRipgrep}from"./chunk-QZV4PFQK.js";import{isInternalCodeModeToolResult,projectUserTranscriptForDisplay}from"./chunk-SZCBUCNH.js";import{resolveModelId}from"./chunk-BEKROCWN.js";import{normalizeSkillPriority}from"./chunk-5SUFJTQQ.js";import{flattenPeerLabel}from"./chunk-BYU42MLK.js";import{getAutoSkillCuratorStatus,recordAutoSkillUsage,restoreArchivedAutoSkill,runAutoSkillCurator,setAutoSkillPinned}from"./chunk-XQJOZDV7.js";import{GOAL_PAUSE_REASON_COMMAND,emptyGoalSnapshot}from"./chunk-HW6AWS7W.js";import{glob}from"./chunk-OBOU4ZZM.js";import{APPROVAL_MODES}from"./chunk-JZK2WGXA.js";import{isMediaPolicyToolHiddenFromModel}from"./chunk-S2ZKZXHX.js";import{BUILT_IN_OUTPUT_STYLES,getArenaSystemReminder,getInsightPrompt,getPlanModeSystemReminder,getProjectSummaryPrompt,isSystemMdActive,resolveMainSessionOutputStyle}from"./chunk-OV3EBH6J.js";import{isSignalTermination}from"./chunk-NMY3PYNO.js";import{checkArgumentSafety,checkCommandPermissions,escapeShellArg,getShellConfiguration}from"./chunk-SCD5TUBG.js";import{escapeJsonTagCharacters,formatMemoryUsage}from"./chunk-NTRFETZB.js";import{captureHookExecutionOwner,runWithHookExecutionOwner}from"./chunk-YZFNBUKG.js";import{buildRuntimeSnapshotId,findProviderByCredentials,isImageGenerationCapable,stripRuntimeSnapshotPrefix}from"./chunk-ET2Z7ZGF.js";import{openBrowserSecurely}from"./chunk-3YWXKSOI.js";import{COMBINED_PASS_TOLERANCE_FACTOR,IdeConnectionEvent,formatTokenUsageSummaryAsCsv,formatTokenUsageSummaryAsJson,getMCPServerStatus,isImageCapable,logIdeConnection,queryTokenUsage,recordSkillInvocation,uiTelemetryService}from"./chunk-ZWPSBU7K.js";import{read}from"./chunk-UQFTXKEB.js";import{getAutoMemoryRoot}from"./chunk-KVA6DHHF.js";import{runSideQuery}from"./chunk-K7JCVESI.js";import{getCurrentMemoryFilename}from"./chunk-Y6HHV4LC.js";import{resolveSlimmingConfig}from"./chunk-Q6UAOTP3.js";import{REASONING_EFFORT_TIERS,applyReasoningEffort,normalizeReasoningEffort}from"./chunk-GOR7FFVE.js";import{AuthType}from"./chunk-ZZZAYAJW.js";import{redactUrlCredentials}from"./chunk-3XVPZY7X.js";import{isCpuProfileRecording,startCpuProfile,stopCpuProfile}from"./chunk-GRAECADD.js";import{FORK_SUBAGENT_TYPE,getApiHistoryPromptId,markApiHistoryPrompt,stripStartupContext}from"./chunk-B3ZFUGTC.js";import{applySkillSideEffects,buildSkillLlmContent}from"./chunk-IRINPFG7.js";import{HookEventName,sanitizeUserPromptExpansionAdditionalContext}from"./chunk-6GTPLW7K.js";import{isShellProgressData}from"./chunk-O5EKX7LG.js";import{ToolDisplayNamesMigration,ToolNames,canonicalToolName}from"./chunk-SBZFGYYS.js";import{createDebugLogger,updateSymlink}from"./chunk-JAUJI56S.js";import{Storage}from"./chunk-EPODBRBP.js";import{expandHomeDir,isSubpath,resolvePath}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();import{isDeepStrictEqual}from"node:util";function isCrossSessionMessagingEnabled(settings){const value=settings?.agents?.crossSessionMessaging;return value===void 0||value===true}__name(isCrossSessionMessagingEnabled,"isCrossSessionMessagingEnabled");function crossSessionMessagingSuppression(config){if(config?.isSafeMode?.()===true)return"safe-mode";if(config?.getBareMode?.()===true)return"bare";return void 0}__name(crossSessionMessagingSuppression,"crossSessionMessagingSuppression");function isCrossSessionMessagingActive(settings,config){return isCrossSessionMessagingEnabled(settings)&&crossSessionMessagingSuppression(config)===void 0}__name(isCrossSessionMessagingActive,"isCrossSessionMessagingActive");function switchIn(file){return file?.settings.agents?.crossSessionMessaging}__name(switchIn,"switchIn");function workspaceCounts(settings){return settings.isTrusted===true&&settings.workspaceSettingsActive===true}__name(workspaceCounts,"workspaceCounts");function isCrossSessionMessagingOptedIn(settings){if(switchIn(settings.user)===true)return true;return workspaceCounts(settings)&&switchIn(settings.workspace)===true}__name(isCrossSessionMessagingOptedIn,"isCrossSessionMessagingOptedIn");function crossSessionMessagingOffScope(settings){if(isCrossSessionMessagingEnabled(settings.merged))return void 0;const merged=settings.merged.agents?.crossSessionMessaging;if(switchIn(settings.system)!==void 0)return"system";if(isDeepStrictEqual(switchIn(settings.user),merged))return"user";if(isDeepStrictEqual(switchIn(settings.systemDefaults),merged)){return"system-defaults"}if(workspaceCounts(settings)&&isDeepStrictEqual(switchIn(settings.workspace),merged)){return"workspace"}return void 0}__name(crossSessionMessagingOffScope,"crossSessionMessagingOffScope");init_esbuild_shims();import{spawn}from"node:child_process";init_esbuild_shims();var MAX_STACKED_SKILLS=5;var isStackedSkillCompletableCommand=__name(command=>command.kind==="skill"&&command.userInvocable!==false&&!command.hidden,"isStackedSkillCompletableCommand");var isValidStackedSkillPrefix=__name((prefix,commands)=>{const trimmed=prefix.trim();if(!trimmed)return false;const tokens=trimmed.split(/\s+/);if(tokens.length>=MAX_STACKED_SKILLS)return false;return tokens.every(token=>{if(!token.startsWith("/"))return false;const command=findCommandByName(token.slice(1),commands);return command!==void 0&&isStackedSkillCompletableCommand(command)})},"isValidStackedSkillPrefix");var parseSlashCommand=__name((query,commands)=>{const trimmed=query.trim();const commandText=trimmed.substring(1).trim();const parts=commandText.split(/\s+/);const commandPath=parts.filter(p=>p);let currentCommands=commands;let commandToExecute;let pathIndex=0;const canonicalPath=[];let argsStart=0;for(const part of commandPath){let foundCommand=currentCommands.find(cmd=>cmd.name===part);if(!foundCommand){foundCommand=currentCommands.find(cmd=>cmd.altNames?.includes(part))}if(foundCommand){commandToExecute=foundCommand;canonicalPath.push(foundCommand.name);pathIndex++;const partIndex=commandText.indexOf(part,argsStart);argsStart=partIndex+part.length;if(foundCommand.subCommands){currentCommands=foundCommand.subCommands}else{break}}else{break}}const args=commandToExecute?commandText.slice(argsStart).trim():parts.slice(pathIndex).join(" ");return{commandToExecute,args,canonicalPath}},"parseSlashCommand");var parseStackedSlashCommands=__name((query,commands)=>{const trimmed=query.trim();if(!trimmed.startsWith("/")){return{skills:[],remainingText:trimmed,exceededMax:false}}const commandText=trimmed.substring(1);const skills=[];let pos=0;let restPos=0;let exceededMax=false;while(pos<commandText.length){while(pos<commandText.length&&/\s/.test(commandText[pos]))pos++;if(pos>=commandText.length){restPos=pos;break}const tokenStart=pos;while(pos<commandText.length&&!/\s/.test(commandText[pos]))pos++;const token=commandText.slice(tokenStart,pos);if(skills.length===0){if(token.startsWith("/"))break;const cmd2=findCommandByName(token,commands);if(!cmd2||cmd2.kind!=="skill")break;skills.push(cmd2);restPos=pos;continue}if(!token.startsWith("/"))break;const name=token.substring(1);if(!name)break;const cmd=findCommandByName(name,commands);if(!cmd||cmd.kind!=="skill")break;if(skills.length>=MAX_STACKED_SKILLS){exceededMax=true;break}skills.push(cmd);restPos=pos}if(skills.length<2){return{skills:[],remainingText:trimmed,exceededMax:false}}const afterSkills=commandText.slice(restPos).trim();return{skills,remainingText:afterSkills,exceededMax}},"parseStackedSlashCommands");function findCommandByName(name,commands){return commands.find(cmd=>cmd.name===name)??commands.find(cmd=>cmd.altNames?.includes(name))}__name(findCommandByName,"findCommandByName");var CONTEXT_FILES_ANNOUNCEMENT_PREFIX="Read context files:";function isContextFilesAnnouncement(item){return item.type==="info"&&typeof item.text==="string"&&item.text.startsWith(CONTEXT_FILES_ANNOUNCEMENT_PREFIX)}__name(isContextFilesAnnouncement,"isContextFilesAnnouncement");var CodePage={UTF8:65001,GBK:936,BIG5:950,LATIN1:1252};var isAtCommand=__name(query=>query.startsWith("@")||/\s@/.test(query),"isAtCommand");var SLASH_PATH_SEPARATOR_RE=/[/\\]/;var SLASH_COMMANDS_SKIP_RECORDING=new Set(["quit","exit","clear","reset","new","resume","delete","branch","btw","history"]);var getSlashCommandFirstToken=__name(query=>query.slice(1).trimStart().split(/\s+/u)[0]??"","getSlashCommandFirstToken");var hasSlashCommandPathSeparator=__name(query=>SLASH_PATH_SEPARATOR_RE.test(getSlashCommandFirstToken(query)),"hasSlashCommandPathSeparator");var isSlashCommand=__name(query=>{if(!query.startsWith("/")){return false}if(query.startsWith("//")){return false}if(query.startsWith("/*")){return false}if(hasSlashCommandPathSeparator(query)){return false}return true},"isSlashCommand");var BTW_COMMAND_RE=/^[/?]btw(?:\s|$)/;var isBtwCommand=__name(query=>{const trimmed=query.trim();return trimmed.length>0&&BTW_COMMAND_RE.test(trimmed)},"isBtwCommand");function consumesContextAnnouncementLatch(trimmedPrompt,options){if(trimmedPrompt.length===0){return false}if(/^\/btw(?:\s|$)/.test(trimmedPrompt)){return false}if(isSlashCommand(trimmedPrompt)){return parseSlashCommand(trimmedPrompt,options.slashCommands).commandToExecute?.modelInvocable===true}if(options.shellModeActive){return false}return true}__name(consumesContextAnnouncementLatch,"consumesContextAnnouncementLatch");var debugLogger=createDebugLogger("COMMAND_UTILS");var formatCommandFailure=__name((error,command)=>error instanceof Error&&error.code==="ENOENT"?`${command} not found`:error instanceof Error?error.message:String(error),"formatCommandFailure");var copyToClipboard=__name(async text=>{let wlCopyError;const run=__name((cmd,args,options)=>new Promise((resolve4,reject)=>{const child=options?spawn(cmd,args,options):spawn(cmd,args);let stderr="";if(child.stderr){child.stderr.on("data",chunk=>stderr+=chunk.toString())}child.on("error",reject);child.on("close",code=>{if(code===0)return resolve4();const errorMsg=stderr.trim();reject(new Error(`'${cmd}' exited with code ${code}${errorMsg?`: ${errorMsg}`:""}`))});if(child.stdin){child.stdin.on("error",reject);child.stdin.write(text);child.stdin.end()}else{reject(new Error("Child process has no stdin stream to write to."))}}),"run");const linuxOptions={stdio:["pipe","inherit","pipe"]};switch(process.platform){case"win32":return run("cmd",["/c",`chcp ${CodePage.UTF8} >nul && clip`]);case"darwin":return run("pbcopy",[]);case"linux":if(isWaylandSession()){try{await run("wl-copy",["-t","text/plain"],{stdio:["pipe","inherit","ignore"]});return}catch(error){wlCopyError=error;debugLogger.debug("wl-copy failed; falling back to other clipboard methods:",error)}}try{await run("xclip",["-selection","clipboard"],linuxOptions)}catch(primaryError){try{await run("xsel",["--clipboard","--input"],linuxOptions)}catch(fallbackError){const xclipNotFound=primaryError instanceof Error&&primaryError.code==="ENOENT";const xselNotFound=fallbackError instanceof Error&&fallbackError.code==="ENOENT";const wlCopyFailure=wlCopyError===void 0?"":`wl-copy failed ("${formatCommandFailure(wlCopyError,"wl-copy")}"); `;if(xclipNotFound&&xselNotFound){if(!writeOsc52(text)){throw new Error(`Clipboard unavailable: ${wlCopyFailure}xclip/xsel not found and OSC 52 requires a TTY. Try running inside a terminal emulator.`)}return}const primaryMsg=formatCommandFailure(primaryError,"xclip");const fallbackMsg=formatCommandFailure(fallbackError,"xsel");if(writeOsc52(text))return;throw new Error(`Clipboard unavailable: ${wlCopyFailure}xclip/xsel failed ("${primaryMsg}", "${fallbackMsg}") and OSC 52 requires a TTY. Try running inside a terminal emulator.`)}}return;default:throw new Error(`Unsupported platform: ${process.platform}`)}},"copyToClipboard");var getUrlOpenCommand=__name(()=>{let openCmd;switch(process.platform){case"darwin":openCmd="open";break;case"win32":openCmd="start";break;case"linux":openCmd="xdg-open";break;default:openCmd="xdg-open";debugLogger.warn(`Unknown platform: ${process.platform}. Attempting to open URLs with: ${openCmd}.`);break}return openCmd},"getUrlOpenCommand");function isMidInputCompletableCommand(cmd){return cmd.modelInvocable===true&&!cmd.hidden}__name(isMidInputCompletableCommand,"isMidInputCompletableCommand");function findMidInputSlashCommand(input,cursorOffset){const codePoints=toCodePoints(input);const beforeCursor=codePoints.slice(0,cursorOffset).join("");const match=beforeCursor.match(/\s\/([a-zA-Z0-9_:-]*)$/);if(!match)return null;const partialCommand=match[1];const slashPos=cursorOffset-1-partialCommand.length;const textAfterSlash=codePoints.slice(slashPos+1).join("");const commandMatch=textAfterSlash.match(/^[a-zA-Z0-9_:-]*/);const fullCommand=commandMatch?commandMatch[0]:"";if(cursorOffset!==slashPos+1+fullCommand.length)return null;return{token:"/"+fullCommand,startPos:slashPos,partialCommand}}__name(findMidInputSlashCommand,"findMidInputSlashCommand");function getBestSlashCommandMatch(partialCommand,commands,recentCommands){if(!partialCommand)return null;const query=partialCommand.toLowerCase();const matches=commands.filter(cmd=>{if(!isMidInputCompletableCommand(cmd))return false;const name=cmd.name.toLowerCase();return name.startsWith(query)&&(name!==query||!!cmd.argumentHint)}).sort((left,right)=>{const leftRecent=recentCommands?.get(left.name);const rightRecent=recentCommands?.get(right.name);const recentOrder=(rightRecent?.usedAt??0)-(leftRecent?.usedAt??0);return(right.completionPriority??0)-(left.completionPriority??0)||recentOrder||left.name.localeCompare(right.name)});const best=matches[0];if(!best)return null;return{suffix:best.name.slice(partialCommand.length),fullCommand:best.name,command:best,argumentHint:best.argumentHint}}__name(getBestSlashCommandMatch,"getBestSlashCommandMatch");var SLASH_TOKEN_RE=/(?:^|(?<=\s))\/([a-zA-Z][a-zA-Z0-9:_-]*)/g;function findSlashCommandTokens(text,commands){if(!text)return[];const commandMapEntries=[];for(const cmd of commands){commandMapEntries.push([cmd.name.toLowerCase(),cmd]);for(const altName of cmd.altNames??[]){commandMapEntries.push([altName.toLowerCase(),cmd])}}const commandMap=new Map(commandMapEntries);const tokens=[];let match;SLASH_TOKEN_RE.lastIndex=0;while((match=SLASH_TOKEN_RE.exec(text))!==null){const fullMatch=match[0];const commandName=match[1];const start=match.index;const end=start+fullMatch.length;const precedingChar=start>0?text[start-1]:null;const isLineStart=start===0||precedingChar==="\n";const cmd=commandMap.get(commandName.toLowerCase());let valid=false;if(cmd){if(isLineStart){valid=cmd.userInvocable!==false&&!cmd.hidden}else{const prefix=text.slice(0,start);valid=cmd.modelInvocable===true||isStackedSkillCompletableCommand(cmd)&&isValidStackedSkillPrefix(prefix,commands)}}tokens.push({start,end,commandName,valid})}return tokens}__name(findSlashCommandTokens,"findSlashCommandTokens");init_esbuild_shims();var debugLogger2=createDebugLogger("SESSION_MODEL");var AUTH_TYPES=new Set(Object.values(AuthType));function isAuthType(value){return AUTH_TYPES.has(value)}__name(isAuthType,"isAuthType");function registryHonoredBaseUrl(config,authType,modelId,baseUrl){if(typeof baseUrl!=="string"||!baseUrl){return void 0}return config.getResolvedModelConfig?.(authType,modelId,baseUrl)?baseUrl:void 0}__name(registryHonoredBaseUrl,"registryHonoredBaseUrl");async function recordDaemonSessionModel(config,payload){const recording=config.getChatRecordingService?.();if(!recording?.recordSessionModel)return;try{await recording.recordSessionModel(payload)}catch(error){debugLogger2.debug("recordSessionModel failed",error)}}__name(recordDaemonSessionModel,"recordDaemonSessionModel");async function recordDaemonSessionModelFromConfig(config){const modelId=config.getModel()?.trim();const authType=config.getAuthType();if(!modelId||!authType)return;const snapshot=config.getActiveRuntimeModelSnapshot?.();const registryBaseUrl=snapshot?void 0:config.getCurrentModelRegistryBaseUrl?.();await recordDaemonSessionModel(config,{modelId,authType,...typeof registryBaseUrl==="string"?{baseUrl:registryBaseUrl}:{},...snapshot?{isRuntime:true}:{}})}__name(recordDaemonSessionModelFromConfig,"recordDaemonSessionModelFromConfig");function hasMatchingRuntimeSnapshot(config,authType,modelId){const snapshot=config.getActiveRuntimeModelSnapshot?.();return snapshot?.authType===authType&&snapshot.modelId===modelId}__name(hasMatchingRuntimeSnapshot,"hasMatchingRuntimeSnapshot");function liveAuthType(config){return config.getAuthType()??config.getModelsConfig?.()?.getCurrentAuthType?.()}__name(liveAuthType,"liveAuthType");function runtimeSnapshotIdentity(snapshot){if(!snapshot)return void 0;if(typeof snapshot.id==="string"&&snapshot.id){return snapshot.id}if(snapshot.authType&&snapshot.modelId){return buildRuntimeSnapshotId(snapshot.authType,snapshot.modelId)}return void 0}__name(runtimeSnapshotIdentity,"runtimeSnapshotIdentity");function recordedRouteMatches(recorded,currentRegistryBaseUrl){if(!recorded||recorded.isRuntime)return true;const targetBaseUrl=recorded.baseUrl;if(targetBaseUrl===void 0){return currentRegistryBaseUrl===null||currentRegistryBaseUrl===void 0}if(targetBaseUrl===""){return currentRegistryBaseUrl===null||currentRegistryBaseUrl===void 0||currentRegistryBaseUrl===""}return currentRegistryBaseUrl===targetBaseUrl}__name(recordedRouteMatches,"recordedRouteMatches");async function applyRestoredSessionModel(config,projection){const recorded=projection?.runtime.recording.sessionModel;const fallbackModel=projection?.runtime.recording.lastAssistantModel;const recordedAuth=recorded?.authType?.trim();const authType=(recordedAuth&&isAuthType(recordedAuth)?recordedAuth:liveAuthType(config))?.trim();const modelId=recorded?.modelId||fallbackModel;if(!modelId?.trim()||!authType||!isAuthType(authType))return;const currentModel=stripRuntimeSnapshotPrefix(config.getModel()??"");const currentAuth=liveAuthType(config);const targetModel=stripRuntimeSnapshotPrefix(modelId.trim());const targetBaseUrl=recorded?.isRuntime?void 0:registryHonoredBaseUrl(config,authType,targetModel,recorded?.baseUrl);const recordedRoute=recorded?{...recorded,...targetBaseUrl?{baseUrl:targetBaseUrl}:{baseUrl:void 0}}:void 0;const currentRegistryBaseUrl=config.getCurrentModelRegistryBaseUrl?.();const baseUrlMatches=recordedRouteMatches(recordedRoute,currentRegistryBaseUrl);const currentRuntimeMatches=hasMatchingRuntimeSnapshot(config,authType,targetModel);if(currentModel===targetModel&¤tAuth===authType&&baseUrlMatches&&!(recorded&&!recorded.isRuntime&¤tRuntimeMatches)){return}const useRuntimeSnapshot=Boolean(recorded?.isRuntime)&&hasMatchingRuntimeSnapshot(config,authType,targetModel);const switchModelId=useRuntimeSnapshot?buildRuntimeSnapshotId(authType,targetModel):targetModel;const requireCachedCredentials=authType==="qwen-oauth"&¤tAuth!==authType;const switchOptions=targetBaseUrl||requireCachedCredentials?{...targetBaseUrl?{baseUrl:targetBaseUrl}:{},...requireCachedCredentials?{requireCachedCredentials:true}:{}}:void 0;try{await config.switchModel(authType,switchModelId,switchOptions)}catch(error){debugLogger2.warn(`restore session model failed (${targetModel}/${authType}): ${error instanceof Error?error.message:String(error)}`)}}__name(applyRestoredSessionModel,"applyRestoredSessionModel");async function restoreSessionModelThenAuthenticate(config,projection,authenticate){const originalAuth=liveAuthType(config);const originalModel=config.getModel();const originalBaseUrl=config.getCurrentModelRegistryBaseUrl?.();const originalRuntimeSnapshot=config.getActiveRuntimeModelSnapshot?.();await applyRestoredSessionModel(config,projection);try{await authenticate()}catch(error){if(liveAuthType(config)===originalAuth&&config.getModel()===originalModel&&(config.getCurrentModelRegistryBaseUrl?.()??void 0)===(originalBaseUrl??void 0)&&runtimeSnapshotIdentity(config.getActiveRuntimeModelSnapshot?.())===runtimeSnapshotIdentity(originalRuntimeSnapshot)){throw error}debugLogger2.warn("restored session model made authentication fail; retrying with settings model");if(!originalAuth||!originalModel){throw error}const rollbackModelId=originalRuntimeSnapshot?.authType===originalAuth&&originalRuntimeSnapshot.modelId===stripRuntimeSnapshotPrefix(originalModel)?buildRuntimeSnapshotId(originalAuth,stripRuntimeSnapshotPrefix(originalModel)):originalModel;try{await config.switchModel(originalAuth,rollbackModelId,typeof originalBaseUrl==="string"?{baseUrl:originalBaseUrl}:void 0)}catch{throw error}await authenticate()}}__name(restoreSessionModelThenAuthenticate,"restoreSessionModelThenAuthenticate");init_esbuild_shims();var SSH_SLASH_COMMAND_POLICY={allowSessionReset:false,allowWorkspaceSettingsWrite:false,persistModelSelection:false,blockedBuiltinCommandNames:[]};var sshCommands=new Set(["help","model","effort","compress","context"]);function isSshSessionCommandAllowed(command){return command.kind==="built-in"&&sshCommands.has(command.name)}__name(isSshSessionCommandAllowed,"isSshSessionCommandAllowed");var unsupportedSessionMethods=new Set([SERVE_STATUS_EXT_METHODS.sessionMessageGroups,SERVE_CONTROL_EXT_METHODS.sessionCd,SERVE_CONTROL_EXT_METHODS.sessionBranch,SERVE_CONTROL_EXT_METHODS.sessionSideTask,SERVE_CONTROL_EXT_METHODS.sessionForkAgent,SERVE_CONTROL_EXT_METHODS.sessionBtw,SERVE_CONTROL_EXT_METHODS.sessionArtifactsPersist,SERVE_CONTROL_EXT_METHODS.sessionMessagesDelete,SERVE_CONTROL_EXT_METHODS.sessionRewind,SERVE_CONTROL_EXT_METHODS.sessionWorkflowTaskAction,SERVE_CONTROL_EXT_METHODS.sessionMcpRuntimeAdd,SERVE_CONTROL_EXT_METHODS.sessionMcpRuntimeRemove,SERVE_CONTROL_EXT_METHODS.sessionLanguage,SERVE_CONTROL_EXT_METHODS.sessionManagedConversationBindingCommit,SERVE_CONTROL_EXT_METHODS.sessionManagedConversationBindingRelease,"rewindSession"]);function isSshWorkspaceExtMethodAllowed(method){return!(method.startsWith("qwen/control/workspace/")||method.startsWith("qwen/skills/")||method.startsWith("qwen/session/sources/")||method.startsWith("qwen/settings/")&&method!=="qwen/settings/getCore"||unsupportedSessionMethods.has(method))}__name(isSshWorkspaceExtMethodAllowed,"isSshWorkspaceExtMethodAllowed");init_esbuild_shims();init_esbuild_shims();var debugLogger3=createDebugLogger("CLI_COMMANDS");function commandOrigin(command){const owner=command.extensionName?`extension "${command.extensionName}"`:command.kind;return`${owner} command "${command.name}"`}__name(commandOrigin,"commandOrigin");var CommandService=class _CommandService{constructor(commands){this.commands=commands}static{__name(this,"CommandService")}static async create(loaders,signal,disabledNames){const results=await Promise.allSettled(loaders.map(loader=>loader.loadCommands(signal)));const allCommands=[];for(const result of results){if(result.status==="fulfilled"){allCommands.push(...result.value)}else{debugLogger3.debug("A command loader failed:",result.reason)}}const commandMap=new Map;for(const cmd of allCommands){let finalName=cmd.name;if(cmd.extensionName&&commandMap.has(cmd.name)){let renamedName=`${cmd.extensionName}.${cmd.name}`;let suffix=1;while(commandMap.has(renamedName)){renamedName=`${cmd.extensionName}.${cmd.name}${suffix}`;suffix++}finalName=renamedName}const shadowed=commandMap.get(finalName);if(shadowed){debugLogger3.warn(`Slash command "/${finalName}" from ${commandOrigin(shadowed)} is replaced by ${commandOrigin(cmd)}`)}commandMap.set(finalName,{...cmd,name:finalName})}if(disabledNames&&disabledNames.size>0){const normalizedDisabled=new Set;for(const entry of disabledNames){const trimmed=entry.trim();if(trimmed)normalizedDisabled.add(trimmed.toLowerCase())}if(normalizedDisabled.size>0){for(const[name,cmd]of Array.from(commandMap.entries())){if(commandRestrictionNames(cmd).some(candidate=>normalizedDisabled.has(candidate))){commandMap.delete(name)}}}}const finalCommands=Object.freeze(Array.from(commandMap.values()));return new _CommandService(finalCommands)}getCommands(){return this.commands}getCommandsForMode(mode){return Object.freeze(filterCommandsForMode(this.commands.filter(cmd=>!cmd.hidden&&cmd.userInvocable!==false),mode))}getModelInvocableCommands(){return this.commands.filter(cmd=>!cmd.hidden&&cmd.modelInvocable===true)}};init_esbuild_shims();init_esbuild_shims();init_esbuild_shims();import fs from"node:fs/promises";import path from"node:path";var debugLogger4=createDebugLogger("SESSION_PATHS");var OPENAI_LOG_SCAN_LIMIT=100;async function collectSessionPathInfo(context){const config=context.services.config;const sessionId=config?.getSessionId()||context.session.stats.sessionId||"unknown";const contentGeneratorConfig=config?.getContentGeneratorConfig();const workingDir=config?.getWorkingDir()||process.cwd();const openAILogDir=resolveOpenAILogDir(contentGeneratorConfig?.openAILoggingDir,workingDir);const openAILoggingEnabled=contentGeneratorConfig?.enableOpenAILogging===true;const latestOpenAILog=openAILoggingEnabled&&sessionId!=="unknown"?await findLatestOpenAILogForSession(openAILogDir,sessionId):void 0;const transcriptPath=config?.getTranscriptPath()||"";const debugLogPath=config?.getDebugMode()&&sessionId!=="unknown"?Storage.getDebugLogPath(sessionId):"";const planFilePath=config?.getPlanFilePath()||(sessionId==="unknown"?"":Storage.getPlanFilePath(sessionId));const planFileExists=planFilePath?await pathExists(planFilePath):false;const sections=[{title:"Session files",entries:[{label:"Session ID",value:sessionId},...transcriptPath?[{label:"Transcript",value:transcriptPath}]:[],...debugLogPath?[{label:"Debug log",value:debugLogPath}]:[],...planFileExists?[{label:"Plan file",value:planFilePath}]:[]]}];if(openAILoggingEnabled){sections.push({title:"OpenAI logs",entries:[{label:"Directory",value:openAILogDir},{label:"Latest for session",value:latestOpenAILog??"none yet"}]})}return{sections}}__name(collectSessionPathInfo,"collectSessionPathInfo");function formatSessionPathInfo(info){const lines=[];for(const[index,section]of info.sections.entries()){if(index>0){lines.push("")}lines.push(`${section.title}:`);for(const entry of section.entries){lines.push(` ${entry.label}: ${entry.value}`)}}return lines.join("\n")}__name(formatSessionPathInfo,"formatSessionPathInfo");async function findLatestOpenAILogForSession(logDir,sessionId){const files=await listLogFiles(logDir,name=>/^openai-.*\.json$/.test(name));for(const file of files){try{const raw=await fs.readFile(file,"utf-8");const parsed=JSON.parse(raw);if(hasContextSessionId(parsed,sessionId)){return file}}catch(error){if(error instanceof SyntaxError||error.code==="ENOENT"){continue}debugLogger4.warn("Error reading OpenAI log file",file,error)}}return void 0}__name(findLatestOpenAILogForSession,"findLatestOpenAILogForSession");async function listLogFiles(dir,predicate){try{const entries=await fs.readdir(dir,{withFileTypes:true});const files=[];for(const entry of entries){if(!entry.isFile()||!predicate(entry.name)){continue}insertRecentFile(files,path.join(dir,entry.name))}return files}catch(error){if(error.code!=="ENOENT"){debugLogger4.warn("Unable to list OpenAI log directory",dir,error)}return[]}}__name(listLogFiles,"listLogFiles");function insertRecentFile(files,file){const insertAt=files.findIndex(existing=>file>existing);if(insertAt===-1){if(files.length<OPENAI_LOG_SCAN_LIMIT){files.push(file)}return}files.splice(insertAt,0,file);if(files.length>OPENAI_LOG_SCAN_LIMIT){files.pop()}}__name(insertRecentFile,"insertRecentFile");async function pathExists(filePath){try{await fs.access(filePath);return true}catch{return false}}__name(pathExists,"pathExists");function hasContextSessionId(value,sessionId){if(!value||typeof value!=="object"){return false}const context=value.context;if(!context||typeof context!=="object"){return false}const ctx=context;return ctx.sessionId===sessionId||ctx.promptId===sessionId}__name(hasContextSessionId,"hasContextSessionId");var aboutCommand={name:"status",altNames:["about"],get description(){return t("show version info")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],canRunDuringStreaming:true,action:__name(async context=>{const systemInfo=await getExtendedSystemInfo(context);if(context.executionMode!=="interactive"){const lines=[`Qwen Code v${systemInfo.cliVersion}`,`Model: ${systemInfo.modelVersion}`,`Fast Model: ${systemInfo.fastModel??"not set"}`,`Auth: ${systemInfo.selectedAuthType}`,`Platform: ${systemInfo.osPlatform} ${systemInfo.osArch} (${systemInfo.osRelease})`,`Node.js: ${systemInfo.nodeVersion}`,`Session: ${systemInfo.sessionId}`,...systemInfo.gitCommit?[`Git commit: ${systemInfo.gitCommit}`]:[],...systemInfo.ideClient?[`IDE: ${systemInfo.ideClient}`]:[],...systemInfo.lspStatus?[`LSP: ${systemInfo.lspStatus}`]:[]];return{type:"message",messageType:"info",content:lines.join("\n")}}const aboutItem={type:"about",systemInfo};context.ui.addItem(aboutItem,Date.now());return},"action"),subCommands:[{name:"paths",get description(){return t("show paths for current session files and logs")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],canRunDuringStreaming:true,action:__name(async context=>{const info=await collectSessionPathInfo(context);const content=formatSessionPathInfo(info);return{type:"message",messageType:"info",content}},"action")}]};init_esbuild_shims();var ADVISOR_SCHEMA={type:"object",additionalProperties:false,properties:{verdict:{type:"string",minLength:1},risks:{type:"string",minLength:1},missingEvidence:{type:"string",minLength:1},recommendation:{type:"string",minLength:1}},required:["verdict","risks","missingEvidence","recommendation"]};function buildAdvisorPrompt(focus){return["<system-reminder>","You are acting as an ADVISOR \u2014 an independent senior reviewer giving a second opinion on the conversation so far. The transcript above may be truncated to the most recent turns; treat what is shown as the evidence available to you.","","CRITICAL CONSTRAINTS:","- You have NO tools. Base every claim strictly on evidence present in the transcript; never claim to have verified something you could not observe.","- Do not perform the task or write the implementation. Review only.","- Be direct about problems: flawed assumptions, premature conclusions, unverified claims, risky next steps.","- The main conversation is NOT interrupted; your review is shown to the user only.","","Return exactly one JSON object with these string fields and no markdown fence, preamble, extra key, or commentary:","- verdict: one short paragraph stating whether the current approach or conclusion is sound.",'- risks: concrete risks or flawed assumptions, each citing transcript evidence. Write "None found" if none.',"- missingEvidence: claims asserted but not verified in the visible transcript (earlier verification may exist outside the shown window).","- recommendation: the single most valuable next action.","</system-reminder>","",focus||"Review the conversation above."].join("\n")}__name(buildAdvisorPrompt,"buildAdvisorPrompt");function formatAdvisorReview(value){const fields=["verdict","risks","missingEvidence","recommendation"];if(!value||Object.keys(value).length!==fields.length||fields.some(field=>{const fieldValue=value[field];return typeof fieldValue!=="string"||fieldValue.trim().length===0})){throw new Error("Advisor returned invalid structured output.")}const review=value;return["## Verdict",review.verdict.trim(),"## Risks",review.risks.trim(),"## Missing evidence",review.missingEvidence.trim(),"## Recommendation",review.recommendation.trim()].join("\n\n")}__name(formatAdvisorReview,"formatAdvisorReview");function parseJsonObjectText(text){const value=text?.trim();if(!value)return void 0;const firstStructuredChar=value.search(/[[{]/);if(firstStructuredChar!==-1&&value[firstStructuredChar]==="["){return void 0}const first=value.indexOf("{");const last=value.lastIndexOf("}");if(first===-1||last<=first)return void 0;try{const parsed=JSON.parse(value.slice(first,last+1));return parsed&&typeof parsed==="object"&&!Array.isArray(parsed)?parsed:void 0}catch{return void 0}}__name(parseJsonObjectText,"parseJsonObjectText");function formatAdvisorError(error){return t("Advisor review failed: {{error}}",{error:error instanceof Error?error.message:String(error||"Unknown error")})}__name(formatAdvisorError,"formatAdvisorError");function unavailableModelMessage(modelName,availableModelIds){const configured=availableModelIds.length>0?t("Configured models: {{models}}.",{models:availableModelIds.join(", ")}):t("No models are configured.");return[`Advisor model '${modelName}' is not configured.`,configured,"Configure models in settings.modelProviders, or run /advisor without arguments to choose a model."].join("\n")}__name(unavailableModelMessage,"unavailableModelMessage");async function setAdvisorModel(context,model){if(context.executionPolicy?.persistModelSelection===false){return{type:"message",messageType:"error",content:t("This model selection is not available in this session.")}}const{config,settings}=context.services;if(!config){return{type:"message",messageType:"error",content:t("Advisor configuration is unavailable.")}}if(model){const availability=checkAdvisorModelAvailability(config,model);if(!availability.available){return{type:"message",messageType:"error",content:unavailableModelMessage(model,availability.availableModelIds)}}}const applied=await config.setAdvisorModel(model);if(applied===false){return{type:"message",messageType:"error",content:t("Advisor configuration is unavailable.")}}settings.setValue("User","advisorModel",model??"");return{type:"message",messageType:"info",content:model?t("Advisor set to {{model}}",{model}):t("Advisor disabled")}}__name(setAdvisorModel,"setAdvisorModel");async function askAdvisor(context,focus,abortSignal){const{config}=context.services;if(!config)throw new Error(t("Config not loaded."));const cacheSafeParams=buildBtwCacheSafeParams(config);if(!cacheSafeParams||config.getLlmClient().getHistoryForForkWindow().length===0){throw new Error(t("No conversation context available for /advisor"))}const advisorModel=config.getAdvisorModel();const result=await runForkedAgent({config,userMessage:buildAdvisorPrompt(focus),cacheSafeParams,jsonSchema:ADVISOR_SCHEMA,...advisorModel?{model:advisorModel}:{},abortSignal,disableModelFallbacks:true});return{text:formatAdvisorReview(result.jsonResult??parseJsonObjectText(result.text)),model:result.model}}__name(askAdvisor,"askAdvisor");var advisorCommand={name:"advisor",get description(){return t("Configure the Advisor model")},argumentHint:"[<model-id>|off|review [focus]]",kind:"built-in",supportedModes:["interactive","non_interactive","acp"],completion:__name(async(context,partialArg)=>{const prefix=partialArg.trim();const fixed=[{value:"off",description:t("Disable Advisor")},{value:"review",description:t("Get a second opinion on the current conversation from a reviewer model")}].filter(({value})=>value.startsWith(prefix));if(!context.services.config||prefix.startsWith("review "))return fixed;return[...fixed,...context.services.config.getAllConfiguredModels().filter(model=>isAdvisorModelEligible(model)).map(model=>model.id).filter(id=>id.startsWith(prefix))]},"completion"),action:__name(async(context,args)=>{const value=context.invocation?.args?.trim()||args.trim();const[subcommand="",...rest]=value.split(/\s+/);const isReview=subcommand==="review";if(!isReview){if(!value){if(context.executionMode!=="interactive"){return{type:"message",messageType:"info",content:[`Advisor: ${context.services.config?.getAdvisorModel()?.split("\0")[0]??"off"}`,`Session calls: ${context.services.config?.getAdvisorUseCount()??0} / ${context.services.config?.getAdvisorMaxUses()||"unlimited"}`,"Each consultation sends the conversation to the selected provider and consumes additional tokens.","Use /advisor <model-id> or /advisor off."].join("\n")}}return{type:"dialog",dialog:"advisor-model"}}return setAdvisorModel(context,value.toLowerCase()==="off"?void 0:value)}const focus=rest.join(" ").trim();if(focus.length>BTW_MAX_INPUT_LENGTH){return{type:"message",messageType:"error",content:t("Focus too long (max {{max}} chars)",{max:String(BTW_MAX_INPUT_LENGTH)})}}const{config}=context.services;const{ui}=context;if(!config){return{type:"message",messageType:"error",content:t("Config not loaded.")}}if(!config.getModel()){return{type:"message",messageType:"error",content:t("No model configured.")}}const abortSignal=context.abortSignal??new AbortController().signal;const executionMode=context.executionMode??"interactive";if(executionMode!=="interactive"){try{const review=await askAdvisor(context,focus,abortSignal);return{type:"message",messageType:"info",content:review.text}}catch(error){return{type:"message",messageType:"error",content:formatAdvisorError(error)}}}const turnInFlight=!ui.isIdleRef.current||ui.pendingItem!==null;if(turnInFlight){return{type:"message",messageType:"error",content:t("Another operation is in progress, wait for it to complete before running /advisor")}}try{ui.setPendingItem({type:"info",text:t("Consulting advisor...")});const review=await askAdvisor(context,focus,abortSignal);if(abortSignal.aborted)return;ui.addItem({type:"advisor",text:review.text,model:review.model},Date.now())}catch(error){if(abortSignal.aborted)return;ui.addItem({type:"error",text:formatAdvisorError(error)},Date.now())}finally{if(!abortSignal.aborted)ui.setPendingItem(null)}},"action")};init_esbuild_shims();function statusLabel(entry){switch(entry.kind){case"agent":{const status=entry.status;switch(status){case"completed":return"completed";case"failed":return`failed: ${entry.error??"unknown error"}`;case"cancelled":return"cancelled";case"paused":return entry.resumeBlockedReason?`paused (resume blocked): ${entry.resumeBlockedReason}`:"paused";case"running":return"running";default:{const _exhaustive=status;throw new Error(`statusLabel(agent): unknown status: ${JSON.stringify(_exhaustive)}`)}}}case"shell":{const status=entry.status;switch(status){case"completed":return`completed (exit ${entry.exitCode??"?"})`;case"failed":return`failed: ${entry.error??"unknown error"}`;case"cancelled":return"cancelled";case"running":return"running";default:{const _exhaustive=status;throw new Error(`statusLabel(shell): unknown status: ${JSON.stringify(_exhaustive)}`)}}}case"monitor":{const events=`${entry.eventCount} event${entry.eventCount===1?"":"s"}`;const status=entry.status;switch(status){case"completed":return entry.error?`completed (${entry.error}, ${events})`:`completed (exit ${entry.exitCode??"?"}, ${events})`;case"failed":return`failed: ${entry.error??"unknown error"} (${events})`;case"cancelled":return`cancelled (${events})`;case"running":return`running (${events})`;default:{const _exhaustive=status;throw new Error(`statusLabel(monitor): unknown status: ${JSON.stringify(_exhaustive)}`)}}}default:{const _exhaustive=entry;throw new Error(`statusLabel: unknown TaskEntry kind: ${JSON.stringify(_exhaustive)}`)}}}__name(statusLabel,"statusLabel");function taskLabel(entry){switch(entry.kind){case"agent":return buildBackgroundEntryLabel(entry);case"shell":return entry.command;case"monitor":return entry.description;default:{const _exhaustive=entry;throw new Error(`taskLabel: unknown TaskEntry kind: ${JSON.stringify(_exhaustive)}`)}}}__name(taskLabel,"taskLabel");function taskId(entry){switch(entry.kind){case"agent":return entry.agentId;case"shell":return entry.shellId;case"monitor":return entry.monitorId;default:{const _exhaustive=entry;throw new Error(`taskId: unknown TaskEntry kind: ${JSON.stringify(_exhaustive)}`)}}}__name(taskId,"taskId");function taskOutputPath(entry){switch(entry.kind){case"agent":case"shell":return entry.outputFile;case"monitor":return void 0;default:{const _exhaustive=entry;throw new Error(`taskOutputPath: unknown TaskEntry kind: ${JSON.stringify(_exhaustive)}`)}}}__name(taskOutputPath,"taskOutputPath");var tasksCommand={name:"tasks",get description(){return t("List background tasks (text dump \u2014 interactive dialog opens via the footer pill)")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],canRunDuringStreaming:true,action:__name(async context=>{const{config}=context.services;if(!config){return{type:"message",messageType:"error",content:"Config not available."}}const agentEntries=[...config.getBackgroundTaskRegistry().getAll()];const shellEntries=[...config.getBackgroundShellRegistry().getAll()];const monitorEntries=[...config.getMonitorRegistry().getAll()];const entries=[...agentEntries,...shellEntries,...monitorEntries].sort((a,b)=>a.startTime-b.startTime);if(entries.length===0){return{type:"message",messageType:"info",content:"No background tasks."}}const now=Date.now();const lines=[];if(context.executionMode==="interactive"){lines.push(t("Tip: focus the Background tasks pill in the footer (use \u2193 from an empty composer) and press Enter for the interactive dialog with detail view + live updates."),"")}lines.push(`Background tasks (${entries.length} total)`,"");for(const entry of entries){const endTime=entry.endTime??now;const runtime=formatDuration(endTime-entry.startTime,{hideTrailingZeros:true});const pidPart=(entry.kind==="shell"||entry.kind==="monitor")&&entry.pid!==void 0?` pid=${entry.pid}`:"";lines.push(`[${taskId(entry)}] ${statusLabel(entry)} ${runtime}${pidPart} ${taskLabel(entry)}`);const outputPath=taskOutputPath(entry);if(outputPath){lines.push(` output: ${outputPath}`)}}return{type:"message",messageType:"info",content:stripUnsafeCharacters(lines.join("\n"))}},"action")};init_esbuild_shims();function snapshotToTask(s){return{id:s.runId,kind:"workflow",runId:s.runId,...s.parentSessionId?{parentSessionId:s.parentSessionId}:{},...s.toolUseId?{toolUseId:s.toolUseId}:{},...s.sourceRef?{sourceRef:{...s.sourceRef}}:{},...s.workflowCalls?{workflowCalls:s.workflowCalls.map(call=>({...call}))}:{},...s.workflowCallsTruncated?{workflowCallsTruncated:true}:{},...s.workflowName?{workflowName:s.workflowName}:{},description:s.meta?.name??s.runId,meta:s.meta,status:s.status,currentPhase:null,currentPhaseVisitId:null,phases:s.phases??[],phaseVisits:s.phaseVisits??[],dispatches:s.dispatches??[],sourceRunId:s.sourceRunId,startMode:s.startMode,agentsDispatched:s.agentsDispatched??0,agentsCompleted:s.agentsCompleted??0,recentLogs:s.recentLogs??[],events:s.events??[],tokensSpent:s.tokensSpent??0,tokenBudgetTotal:s.tokenBudgetTotal??null,perPhaseTokens:new Map(s.perPhaseTokens??[]),pendingApprovals:[],script:s.script??"",scriptPath:s.scriptPath,result:s.result,error:s.error,startTime:s.startTime,endTime:s.endTime,outputFile:"",outputOffset:0,notified:true,abortController:new AbortController}}__name(snapshotToTask,"snapshotToTask");function rowLine(entry,now){const endTime=entry.endTime??now;const runtime=formatDuration(endTime-entry.startTime,{hideTrailingZeros:true});const label=entry.meta?.name??entry.runId;const phase=entry.currentPhase?` \xB7 ${entry.currentPhase}`:"";const counts=entry.agentsDispatched>0?` \xB7 ${entry.agentsCompleted}/${entry.agentsDispatched} agents`:"";const phaseCount=entry.phases.length>0?` \xB7 ${entry.phases.length} ${entry.phases.length===1?"phase":"phases"}`:"";const budgetChip=entry.tokensSpent>0||entry.tokenBudgetTotal!==null?entry.tokenBudgetTotal!==null?` \xB7 ${formatTokenCount(entry.tokensSpent)}/${formatTokenCount(entry.tokenBudgetTotal)}t`:` \xB7 ${formatTokenCount(entry.tokensSpent)}t`:"";const errorTail=entry.status==="failed"&&entry.error?` \u2014 ${entry.error.slice(0,80)}`:"";return` ${entry.runId.padEnd(20)} ${entry.status.padEnd(10)} ${runtime.padStart(8)} ${label}${phase}${counts}${phaseCount}${budgetChip}${errorTail}`}__name(rowLine,"rowLine");var MAX_DETAIL_ERROR_CHARS=4096;function isHollow(value){if(typeof value!=="object"||value===null)return false;return Object.values(value).every(isHollow)}__name(isHollow,"isHollow");function withoutHollowFailures(result){if(typeof result!=="object"||result===null||Array.isArray(result)){return result}const kept={...result};for(const key of REPORTED_FAILURE_KEYS){try{if(isHollow(kept[key]))delete kept[key]}catch{}}return kept}__name(withoutHollowFailures,"withoutHollowFailures");function mayHaveLostDetail(result){return typeof result==="object"&&result!==null||typeof result==="string"&&result.startsWith("(non-JSON-serializable ")}__name(mayHaveLostDetail,"mayHaveLostDetail");function resultPreviewFor(entry,source){if(entry.status!=="completed")return{legacy:false};if(!source){return{preview:buildWorkflowResultPreview(entry.result),legacy:false}}const{snapshot}=source;if(snapshot.resultPreview){return{preview:snapshot.resultPreview,legacy:false}}if(!Object.hasOwn(snapshot,"result"))return{legacy:true};const{result}=snapshot;return{preview:{...buildWorkflowResultPreview(result),reportedFailures:reportedFailureLines(withoutHollowFailures(result))},legacy:mayHaveLostDetail(result)}}__name(resultPreviewFor,"resultPreviewFor");function indent(text,prefix){return text.split("\n").map(line=>prefix+line).join("\n")}__name(indent,"indent");async function confirmedSnapshotFile(config,runId){if(!isWorkflowRunId(runId)||!config.storage)return void 0;return await readWorkflowSnapshot(config,runId)?config.storage.getWorkflowRunSnapshotPath(runId):void 0}__name(confirmedSnapshotFile,"confirmedSnapshotFile");function detailLines(entry,now,source){const lines=[];const endTime=entry.endTime??now;const runtime=formatDuration(endTime-entry.startTime,{hideTrailingZeros:true});lines.push(`Workflow ${entry.runId}`);if(entry.meta?.name){lines.push(` name : ${entry.meta.name}`)}if(entry.meta?.description){lines.push(` description : ${entry.meta.description}`)}if(entry.meta?.whenToUse){lines.push(` whenToUse : ${entry.meta.whenToUse}`)}lines.push(` status : ${entry.status}`);lines.push(` runtime : ${runtime}`);if(entry.currentPhase){lines.push(` currentPhase: ${entry.currentPhase}`)}lines.push(` agents : ${entry.agentsCompleted}/${entry.agentsDispatched}`);lines.push(` tokens : ${formatTokenCount(entry.tokensSpent)}`);lines.push(` cap : ${entry.tokenBudgetTotal!==null?formatTokenCount(entry.tokenBudgetTotal):"(no cap)"}`);if(entry.error){const error=truncateWorkflowText(sanitizeWorkflowText(entry.error),MAX_DETAIL_ERROR_CHARS);lines.push(` error : ${error.split("\n").join("\n ")}`)}if(source?.file){lines.push(` snapshotFile: ${source.file}`)}if(entry.phases.length>0){lines.push("");lines.push(` Phases (${entry.phases.length})`);for(const phase of entry.phases){const phaseTokens=entry.perPhaseTokens.get(phase)??0;const chip=phaseTokens>0?` \xB7 ${formatTokenCount(phaseTokens)}t`:"";lines.push(` \xB7 ${phase}${chip}`)}const prePhaseTokens=entry.perPhaseTokens.get(null)??0;if(prePhaseTokens>0){lines.push(` \xB7 (no phase) \xB7 ${formatTokenCount(prePhaseTokens)}t`)}}if(entry.recentLogs.length>0){lines.push("");lines.push(` Logs (last ${entry.recentLogs.length})`);for(const line of entry.recentLogs){lines.push(` ${line}`)}}if(source&&source.snapshot.dispatches===void 0){lines.push(""," Failed agents: not recorded in this snapshot")}else{const failures=buildFailureLines(entry);if(failures.length>0){const count=entry.dispatches.filter(d=>d.status==="failed").length;lines.push("",` Failed agents (${count})`);for(const line of failures)lines.push(indent(line," "))}}const{preview:preview2,legacy}=resultPreviewFor(entry,source);const reported=(preview2?.reportedFailures??[]).map(line=>truncateWorkflowText(sanitizeWorkflowText(line),MAX_FAILURE_LINE_CHARS));if(reported.length>0){lines.push(""," Reported failures");for(const line of reported)lines.push(indent(line," "))}if(entry.status==="completed"){lines.push(""," Result");if(!preview2){lines.push(" (this snapshot did not record a result)")}else{const sanitized=sanitizeWorkflowText(preview2.text);const text=truncateWorkflowText(sanitized,MAX_WORKFLOW_RESULT_PREVIEW_CHARS);lines.push(indent(text," "));if(preview2.truncated||text!==sanitized){lines.push(` (preview truncated to ${MAX_WORKFLOW_RESULT_PREVIEW_CHARS} characters)`)}}if(legacy){lines.push(" (older snapshot: result details such as Error, Map, and Set values may be incomplete)")}}return lines}__name(detailLines,"detailLines");var workflowsCommand={name:"workflows",get description(){return t("List workflow runs or cooperatively pause/resume a live run")},get argumentHint(){return t("[mode [status|on|off] | runId | p <runId>]")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],subCommands:[{name:"mode",description:"Show or change this session\u2019s Workflow guidance mode",kind:"built-in",supportedModes:["interactive","non_interactive","acp"],canRunDuringStreaming:true,action:__name(async(context,args)=>{const config=context.services.config;if(!config?.isWorkflowModeSupported()){return{type:"message",messageType:"error",content:"Workflow mode is unavailable for this session owner."}}const value=args.trim()||"status";if(!["status","on","off"].includes(value)){return{type:"message",messageType:"error",content:"Usage: /workflows mode [status|on|off]"}}try{const state=value==="status"?config.getWorkflowMode():await config.setWorkflowMode(value==="on");return{type:"message",messageType:"info",content:`Workflow mode: ${state.requested?"on":"off"}${state.requested&&!state.effective?" (unavailable)":""}${state.reason?` \u2014 ${state.reason}`:""}`}}catch(error){return{type:"message",messageType:"error",content:error instanceof Error?error.message:String(error)}}},"action")}],action:__name(async(context,args)=>{const{config}=context.services;if(!config){return{type:"message",messageType:"error",content:"Config not available."}}if(!config.isWorkflowsEnabled()){return{type:"message",messageType:"error",content:"Workflows are disabled. Use /workflows mode status or off to manage the saved mode."}}const registry=config.getWorkflowRunRegistry();const allEntries=registry.list();const trimmedArgs=(args??"").trim();const tokens=trimmedArgs.split(/\s+/);if(tokens[0]==="p"){if(context.executionMode!=="interactive"){return{type:"message",messageType:"error",content:"Workflow pause controls are available only in the interactive TUI."}}if(tokens.length!==2||!tokens[1]){return{type:"message",messageType:"error",content:"Usage: /workflows p <runId>"}}const runId=tokens[1];let target=registry.get(runId);let fromSnapshot=false;if(!target){const snapshot=(await listWorkflowSnapshots(config)).find(s=>s.runId===runId);if(snapshot){target=snapshotToTask(snapshot);fromSnapshot=true}}if(!target){return{type:"message",messageType:"error",content:`Unknown live workflow runId: ${runId}`}}if(isTerminalWorkflowStatus(target.status)){return{type:"message",messageType:"error",content:`Workflow ${runId} is ${target.status} and cannot be paused or resumed.`}}if(!fromSnapshot&&!target.isBackgrounded){return{type:"message",messageType:"error",content:"Foreground workflow runs cannot be paused or resumed; only background runs support cooperative pause."}}if(target.status==="pausing"){return{type:"message",messageType:"warning",content:`Workflow ${runId} is still pausing; wait until it reaches paused before resuming.`}}if(target.status==="running"){return registry.pause(runId)?{type:"message",messageType:"info",content:`Cooperative pause requested for workflow ${runId}.`}:{type:"message",messageType:"error",content:`Workflow ${runId} could not be paused because its state changed.`}}if(target.status==="paused"){return registry.resume(runId)?{type:"message",messageType:"info",content:`Resume requested for workflow ${runId}.`}:{type:"message",messageType:"error",content:`Workflow ${runId} could not be resumed because its state changed.`}}return{type:"message",messageType:"error",content:`Workflow ${runId} is ${target.status} and cannot be paused or resumed.`}}if(trimmedArgs.length>0){let target=registry.get(trimmedArgs);let source;if(!target){const snapshot=(await listWorkflowSnapshots(config)).find(s=>s.runId===trimmedArgs);if(snapshot){target=snapshotToTask(snapshot);source={snapshot,file:await confirmedSnapshotFile(config,snapshot.runId)}}}if(!target){return{type:"message",messageType:"error",content:`Unknown workflow runId: ${trimmedArgs}`}}return{type:"message",messageType:"info",content:detailLines(target,Date.now(),source).join("\n")}}const snapshots=await listWorkflowSnapshots(config);const liveRunIds=new Set(allEntries.map(e=>e.runId));const snapshotTasks=snapshots.filter(s=>!liveRunIds.has(s.runId)).map(snapshotToTask);if(allEntries.length===0&&snapshotTasks.length===0){return{type:"message",messageType:"info",content:"No workflow runs recorded yet."}}const now=Date.now();const active=allEntries.filter(e=>isActiveWorkflowStatus(e.status)).sort((a,b)=>a.startTime-b.startTime);const terminal=[...allEntries.filter(e=>!isActiveWorkflowStatus(e.status)),...snapshotTasks].sort((a,b)=>(b.endTime??0)-(a.endTime??0));const lines=[];if(context.executionMode==="interactive"){lines.push(t("Tip: use `/workflows p <runId>` or Background tasks + p to cooperatively pause/resume; use `/workflows <runId>` for details."),"")}lines.push(`Workflow runs (${active.length+terminal.length} total \xB7 ${active.length} active)`,"");if(active.length>0){lines.push("Active");for(const entry of active)lines.push(rowLine(entry,now));lines.push("")}if(terminal.length>0){lines.push("Recent");for(const entry of terminal)lines.push(rowLine(entry,now))}return{type:"message",messageType:"info",content:lines.join("\n")}},"action")};init_esbuild_shims();var agentsCommand={name:"agents",get description(){return t("Manage subagents for specialized task delegation.")},kind:"built-in",supportedModes:["interactive"],subCommands:[{name:"manage",get description(){return t("Manage existing subagents (view, edit, delete).")},kind:"built-in",supportedModes:["interactive"],action:__name(()=>({type:"dialog",dialog:"subagent_list"}),"action")},{name:"create",get description(){return t("Create a new subagent with guided setup.")},kind:"built-in",supportedModes:["interactive"],action:__name(()=>({type:"dialog",dialog:"subagent_create"}),"action")}]};init_esbuild_shims();function parseArenaArgs(args){const modelsMatch=args.match(/--models\s+(\S+)/);let models=[];let task=args;if(modelsMatch){const modelStrings=modelsMatch[1].split(",").filter(Boolean);models=modelStrings.map(str=>{const colonIndex=str.indexOf(":");if(colonIndex>0){return{authType:str.substring(0,colonIndex),modelId:str.substring(colonIndex+1)}}return{modelId:str}});task=task.replace(/--models\s+\S+/,"").trim()}task=task.replace(/^["']|["']$/g,"").trim();return{models,task}}__name(parseArenaArgs,"parseArenaArgs");var debugLogger5=createDebugLogger("ARENA_COMMAND");function buildArenaExecutionInput(parsed,config){if(!parsed.task){return{type:"message",messageType:"error",content:[t("Usage: /arena start --models model1,model2 <task>"),"",t("Options:")," --models [authType:]model1,[authType:]model2",` ${t("Models to compete (required, at least 2)")}`,` ${t("Format: authType:modelId or just modelId")}`,"",t("Examples:"),' /arena start --models openai:gpt-4o,anthropic:claude-3 "implement sorting"',' /arena start --models qwen-coder-plus,kimi-for-coding "fix the bug"'].join("\n")}}if(parsed.models.length<2){return{type:"message",messageType:"error",content:[t("Arena requires at least 2 models. Use --models model1,model2 to specify."),t("Format: [authType:]modelId (e.g., openai:gpt-4o or just gpt-4o)")].join("\n")}}const contentGeneratorConfig=config.getContentGeneratorConfig();const defaultAuthType=contentGeneratorConfig?.authType??"openai";const modelsConfig=config.getModelsConfig();const models=[];for(const parsedModel of parsed.models){const authType=parsedModel.authType??defaultAuthType;const registryModels=modelsConfig.getAvailableModelsForAuthType(authType);const resolved=registryModels.find(m=>m.id===parsedModel.modelId);if(resolved?.imageOnly){return{type:"message",messageType:"error",content:t("Image-only model '{{model}}' cannot be used in an Arena session.",{model:parsedModel.modelId})}}models.push({modelId:parsedModel.modelId,authType,displayName:resolved?.label??parsedModel.modelId})}return{task:parsed.task,models,approvalMode:config.getApprovalMode()}}__name(buildArenaExecutionInput,"buildArenaExecutionInput");function recordArenaItem(config,item){try{const chatRecorder=config.getChatRecordingService();if(!chatRecorder)return;chatRecorder.recordSlashCommand({phase:"result",rawCommand:"/arena",outputHistoryItems:[{...item}]})}catch{debugLogger5.error("Failed to record arena history item")}}__name(recordArenaItem,"recordArenaItem");function executeArenaCommand(config,ui,input){let chatHistory;try{const fullHistory=config.getLlmClient().getChat().getHistoryShallow();chatHistory=stripStartupContext(fullHistory)}catch{debugLogger5.debug("Could not retrieve chat history for arena agents")}const manager=new ArenaManager(config);const emitter=manager.getEventEmitter();const detachListeners=[];const agentLabels=new Map;const addArenaMessage=__name((type,text)=>{ui.addItem({type,text},Date.now())},"addArenaMessage");const addAndRecordArenaMessage=__name((type,text)=>{const item={type,text};ui.addItem(item,Date.now());recordArenaItem(config,item)},"addAndRecordArenaMessage");const handleSessionStart=__name(event=>{const modelList=event.models.map((model,index)=>` ${index+1}. ${model.modelId}`).join("\n");addArenaMessage("info",t('Arena started with {{count}} agents on task: "{{task}}"\nModels:\n{{modelList}}',{count:String(event.models.length),task:event.task,modelList}))},"handleSessionStart");const handleAgentStart=__name(event=>{agentLabels.set(event.agentId,event.model.modelId);debugLogger5.debug(`Arena agent started: ${event.model.modelId} (${event.agentId})`)},"handleAgentStart");const handleSessionUpdate=__name(event=>{const attachHintPrefix="To view agent panes, run: ";if(event.message.startsWith(attachHintPrefix)){const command=event.message.slice(attachHintPrefix.length).trim();addAndRecordArenaMessage("info",t("Arena panes are running in tmux. Attach with: `{{command}}`",{command}));return}if(event.type==="success"){addAndRecordArenaMessage("success",event.message)}else if(event.type==="info"){addAndRecordArenaMessage("info",event.message)}else{addAndRecordArenaMessage("warning",event.message)}},"handleSessionUpdate");const handleAgentError=__name(event=>{const label=agentLabels.get(event.agentId)||event.agentId;addAndRecordArenaMessage("error",t("[{{label}}] failed: {{error}}",{label,error:event.error}))},"handleAgentError");const buildAgentCardData=__name(result=>({label:result.model.modelId,status:result.status,durationMs:result.stats.durationMs,totalTokens:result.stats.totalTokens,inputTokens:result.stats.inputTokens,outputTokens:result.stats.outputTokens,toolCalls:result.stats.toolCalls,successfulToolCalls:result.stats.successfulToolCalls,failedToolCalls:result.stats.failedToolCalls,rounds:result.stats.rounds,error:result.error,diff:result.diff,diffSummary:result.diffSummary,modifiedFiles:result.modifiedFiles,approachSummary:result.approachSummary}),"buildAgentCardData");const handleAgentComplete=__name(event=>{if(!isTerminalStatus(event.result.status)){return}const agent=buildAgentCardData(event.result);const item={type:"arena_agent_complete",agent};ui.addItem(item,Date.now());recordArenaItem(config,item)},"handleAgentComplete");const handleSessionError=__name(event=>{addAndRecordArenaMessage("error",`${event.error}`)},"handleSessionError");const handleSessionComplete=__name(event=>{const item={type:"arena_session_complete",sessionStatus:event.result.status,task:event.result.task,totalDurationMs:event.result.totalDurationMs??0,agents:event.result.agents.map(buildAgentCardData)};ui.addItem(item,Date.now());recordArenaItem(config,item)},"handleSessionComplete");emitter.on("session_start",handleSessionStart);detachListeners.push(()=>emitter.off("session_start",handleSessionStart));emitter.on("agent_start",handleAgentStart);detachListeners.push(()=>emitter.off("agent_start",handleAgentStart));emitter.on("session_update",handleSessionUpdate);detachListeners.push(()=>emitter.off("session_update",handleSessionUpdate));emitter.on("agent_error",handleAgentError);detachListeners.push(()=>emitter.off("agent_error",handleAgentError));emitter.on("agent_complete",handleAgentComplete);detachListeners.push(()=>emitter.off("agent_complete",handleAgentComplete));emitter.on("session_error",handleSessionError);detachListeners.push(()=>emitter.off("session_error",handleSessionError));emitter.on("session_complete",handleSessionComplete);detachListeners.push(()=>emitter.off("session_complete",handleSessionComplete));config.setArenaManager(manager);const cols=process.stdout.columns||120;const rows=Math.max((process.stdout.rows||40)-2,1);const lifecycle=manager.start({task:input.task,models:input.models,cols,rows,approvalMode:input.approvalMode,chatHistory}).then(()=>{debugLogger5.debug("Arena agents settled")},error=>{const message2=error instanceof Error?error.message:String(error);addAndRecordArenaMessage("error",`${message2}`);debugLogger5.error("Arena session failed:",error);config.setArenaManager(null);for(const detach of detachListeners){detach()}});manager.setLifecyclePromise(lifecycle)}__name(executeArenaCommand,"executeArenaCommand");var arenaCommand={name:"arena",get description(){return t("Manage Arena sessions")},kind:"built-in",subCommands:[{name:"start",get description(){return t("Start an Arena session with multiple models competing on the same task")},kind:"built-in",action:__name(async(context,args)=>{if(context.services.config?.getShellExecutionSandbox?.()){return{type:"message",messageType:"error",content:"Arena is unavailable in tool sandbox."}}const executionMode=context.executionMode??"interactive";if(executionMode!=="interactive"){return{type:"message",messageType:"error",content:t("Arena is not supported in non-interactive mode. Use interactive mode to start an Arena session.")}}const{services,ui}=context;const{config}=services;if(!config){return{type:"message",messageType:"error",content:t("Configuration not available.")}}const existingManager=config.getArenaManager();if(existingManager){return{type:"message",messageType:"error",content:t("An Arena session exists. Use /arena stop or /arena select to end it before starting a new one.")}}const parsed=parseArenaArgs(args);if(parsed.models.length===0){return{type:"dialog",dialog:"arena_start"}}const executionInput=buildArenaExecutionInput(parsed,config);if("type"in executionInput){return executionInput}executeArenaCommand(config,ui,executionInput)},"action")},{name:"stop",get description(){return t("Stop the current Arena session")},kind:"built-in",action:__name(async context=>{if(context.services.config?.getShellExecutionSandbox?.()){return{type:"message",messageType:"error",content:"Arena is unavailable in tool sandbox."}}const executionMode=context.executionMode??"interactive";if(executionMode!=="interactive"){return{type:"message",messageType:"error",content:t("Arena is not supported in non-interactive mode. Use interactive mode to stop an Arena session.")}}const{config}=context.services;if(!config){return{type:"message",messageType:"error",content:t("Configuration not available.")}}const manager=config.getArenaManager();if(!manager){return{type:"message",messageType:"error",content:t("No running Arena session found.")}}return{type:"dialog",dialog:"arena_stop"}},"action")},{name:"status",get description(){return t("Show the current Arena session status")},kind:"built-in",action:__name(async context=>{if(context.services.config?.getShellExecutionSandbox?.()){return{type:"message",messageType:"error",content:"Arena is unavailable in tool sandbox."}}const executionMode=context.executionMode??"interactive";if(executionMode!=="interactive"){return{type:"message",messageType:"error",content:t("Arena is not supported in non-interactive mode.")}}const{config}=context.services;if(!config){return{type:"message",messageType:"error",content:t("Configuration not available.")}}const manager=config.getArenaManager();if(!manager){return{type:"message",messageType:"error",content:t("No Arena session found. Start one with /arena start.")}}return{type:"dialog",dialog:"arena_status"}},"action")},{name:"select",altNames:["choose"],get description(){return t("Select a model result and merge its diff into the current workspace")},kind:"built-in",action:__name(async(context,args)=>{if(context.services.config?.getShellExecutionSandbox?.()){return{type:"message",messageType:"error",content:"Arena is unavailable in tool sandbox."}}const executionMode=context.executionMode??"interactive";if(executionMode!=="interactive"){return{type:"message",messageType:"error",content:t("Arena is not supported in non-interactive mode.")}}const{config}=context.services;if(!config){return{type:"message",messageType:"error",content:t("Configuration not available.")}}const manager=config.getArenaManager();if(!manager){return{type:"message",messageType:"error",content:t("No Arena session found. Start one with /arena start.")}}const sessionStatus=manager.getSessionStatus();if(sessionStatus==="running"||sessionStatus==="initializing"){return{type:"message",messageType:"error",content:t("Arena session is still running. Wait for it to complete or use /arena stop first.")}}const trimmedArgs=args.trim();if(trimmedArgs==="--discard"){if(!context.overwriteConfirmed){return{type:"confirm_action",prompt:t("Discard all Arena results and clean up worktrees?"),originalInvocation:{raw:context.invocation?.raw||"/arena select --discard"}}}await config.cleanupArenaRuntime(true);return{type:"message",messageType:"info",content:t("Arena results discarded. All worktrees cleaned up.")}}const agents=manager.getAgentStates();const hasSuccessful=agents.some(a=>isSuccessStatus(a.status));if(!hasSuccessful){return{type:"message",messageType:"error",content:[t("No successful agent results to select from. All agents failed or were cancelled."),t("Use /arena stop to end the session.")].join("\n")}}if(trimmedArgs){const matchingAgent=agents.find(a=>isSuccessStatus(a.status)&&a.model.modelId.toLowerCase()===trimmedArgs.toLowerCase());if(!matchingAgent){return{type:"message",messageType:"error",content:t('No idle agent found matching "{{name}}".',{name:trimmedArgs})}}const label=matchingAgent.model.modelId;const result=await manager.applyAgentResult(matchingAgent.agentId);if(!result.success){return{type:"message",messageType:"error",content:t("Failed to apply changes from {{label}}: {{error}}",{label,error:result.error??"Unknown error"})}}await config.cleanupArenaRuntime(true);return{type:"message",messageType:"info",content:t("Applied changes from {{label}} to workspace. Arena session complete.",{label})}}return{type:"dialog",dialog:"arena_select"}},"action")}]};init_esbuild_shims();init_esbuild_shims();function formatApprovalModeName(mode){switch(mode){case"plan":return t("plan mode");case"default":return t("Ask permissions");case"auto-edit":return t("auto-accept edits");case"auto":return t("Auto mode");case"yolo":return t("YOLO mode");default:return mode}}__name(formatApprovalModeName,"formatApprovalModeName");function formatApprovalModeDescription(mode){switch(mode){case"plan":return t("Analyze only, do not modify files or execute commands");case"default":return t("Require approval for file edits or shell commands");case"auto-edit":return t("Automatically approve file edits");case"auto":return t("Use classifier to automatically approve safe tool calls");case"yolo":return t("Automatically approve all tools");default:return mode}}__name(formatApprovalModeDescription,"formatApprovalModeDescription");function parseApprovalModeArg(arg){const trimmed=arg.trim().toLowerCase();if(!trimmed){return void 0}return APPROVAL_MODES.find(mode=>mode.toLowerCase()===trimmed)}__name(parseApprovalModeArg,"parseApprovalModeArg");var approvalModeCommand={name:"approval-mode",get description(){return t("View or change the approval mode for tool usage")},argumentHint:"<mode>",kind:"built-in",supportedModes:["interactive"],action:__name(async(context,args)=>{const mode=parseApprovalModeArg(args);if(!args.trim()){return{type:"dialog",dialog:"approval-mode"}}if(!mode){return{type:"message",messageType:"error",content:t('Invalid approval mode "{{arg}}". Valid modes: {{modes}}',{arg:args.trim(),modes:APPROVAL_MODES.join(", ")})}}const{config,settings}=context.services;let priorMode;if(config){try{priorMode=config.getApprovalMode()}catch(e){return{type:"message",messageType:"error",content:e.message}}}const autoModeNotices=mode==="auto"&&priorMode!=="auto"&&config?await import("./useAutoAcceptIndicator-5RTTH3OW.js"):void 0;if(config){try{config.setApprovalMode(mode)}catch(e){return{type:"message",messageType:"error",content:e.message}}}if(autoModeNotices&&config){autoModeNotices.emitAutoModeEntryNotices({config,settings,addItem:context.ui.addItem})}return{type:"message",messageType:"info",content:t('Approval mode set to "{{mode}}"',{mode:formatApprovalModeName(mode)})}},"action")};init_esbuild_shims();var authCommand={name:"auth",altNames:["connect","login"],get description(){return t("Connect an LLM provider")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],action:__name((context,_args)=>{const executionMode=context.executionMode??"interactive";if(executionMode!=="interactive"){return{type:"message",messageType:"info",content:t("Authentication configuration is only available in interactive mode. To configure authentication, run Qwen Code interactively and use /auth, or set environment variables: OPENAI_API_KEY, OPENAI_BASE_URL, OPENAI_MODEL.")}}return{type:"dialog",dialog:"auth"}},"action")};init_esbuild_shims();var branchCommand={name:"branch",kind:"built-in",get description(){return t("Fork the current conversation into a new session")},action:__name(async(context,args)=>{const{config}=context.services;if(!config){return{type:"message",messageType:"error",content:t("Config is not available.")}}if(context.ui.isIdleRef?.current===false){return{type:"message",messageType:"error",content:t("Cannot branch while a response or tool call is in progress. Wait for it to finish or resolve the pending tool call.")}}const sessionService=config.getSessionService();const currentId=config.getSessionId();const hasRecords=await sessionService.sessionExists(currentId);if(!hasRecords){return{type:"message",messageType:"error",content:t("No conversation to branch.")}}const name=args.trim().replace(/[\r\n]+/g," ");return name?{type:"dialog",dialog:"branch",name}:{type:"dialog",dialog:"branch"}},"action")};init_esbuild_shims();function shortId(msgId){return msgId.replace(/-/g,"").slice(0,6)}__name(shortId,"shortId");function displayHandle(entry,held){const own=canonicalizeMsgId(entry.frame.msgId);let length=Math.min(shortId(entry.frame.msgId).length,own.length);const collides=__name(len=>held.some(other=>other!==entry&&canonicalizeMsgId(other.frame.msgId).startsWith(own.slice(0,len))),"collides");while(length<own.length&&collides(length)){length+=1}return own.slice(0,length)}__name(displayHandle,"displayHandle");function preview(text,max=100){const oneLine=flattenPeerLabel(text).replace(/\s+/g," ").trim();return oneLine.length>max?`${oneLine.slice(0,max-1)}\u2026`:oneLine}__name(preview,"preview");function describeRemaining(entry,expiryMs){if(expiryMs===null)return"";const wallAge=Date.now()-entry.heldAt;const age=entry.monotonicAt===void 0?wallAge:Math.max(wallAge,performance.now()-entry.monotonicAt);const remaining=expiryMs-age;if(remaining<=0)return", expiring now";const minutes=Math.ceil(remaining/6e4);return remaining<6e4?", less than a minute left":`, ${minutes} minute${minutes===1?"":"s"} left`}__name(describeRemaining,"describeRemaining");function formatHeldList(held,expiryFor=()=>null){if(held.length===0)return"No messages from other sessions are waiting.";const lines=held.map(entry=>{const peerLabel=entry.controller?flattenPeerLabel(entry.controller.label):flattenPeerLabel(entry.frame.fromName??entry.frame.from??(entry.selfSent?"this session":"unknown session"));const origin=entry.controller?"[controller]":entry.selfSent?"[own process]":"[peer]";const who=`${origin} ${peerLabel}`;const handle=flattenPeerLabel(displayHandle(entry,held));return` ${handle} ${who}
|
|
4
4
|
${preview(entry.frame.message.content)}
|
|
5
5
|
held because ${describeHoldCause(entry.cause,entry.policyScope)}`+describeRemaining(entry,expiryFor(entry))});return[`${held.length} message${held.length===1?"":"s"} waiting for your review:`,...lines,"","Release with /peers accept <id|all>, or drop with /peers deny <id|all>."].join("\n")}__name(formatHeldList,"formatHeldList");function resolveHeld(held,token){const needle=token.toLowerCase();const exact=held.filter(entry=>canonicalizeMsgId(entry.frame.msgId)===needle);if(exact.length===1)return{kind:"one",msgId:exact[0].frame.msgId};const matches=held.filter(entry=>canonicalizeMsgId(entry.frame.msgId).startsWith(needle)||entry.frame.msgId.toLowerCase().startsWith(needle));if(matches.length===0)return{kind:"none"};if(matches.length>1)return{kind:"ambiguous"};return{kind:"one",msgId:matches[0].frame.msgId}}__name(resolveHeld,"resolveHeld");async function listControllers(){try{return await listPeerControllers()}catch(error){return{error:error instanceof Error?error.message:String(error)}}}__name(listControllers,"listControllers");function formatControllerList(controllers){if(!Array.isArray(controllers)){return`Could not read the trusted controllers: ${controllers.error}`}if(controllers.length===0){return`No trusted controllers. Without an explicit "accept" setting, a message that asserts no review class is held for your review, except one from a process this session started, which is always accepted. A sender's own review-class claim is not authenticated; set agents.crossSessionInbound to "hold" to review every inbound message.
|
|
6
6
|
Add one with: qwen sessions controllers add --label <name>`}const lines=controllers.map(record=>` ${record.id} ${flattenPeerLabel(record.label)} added ${formatCreated(record.createdAt)}`);return[`${controllers.length} trusted controller${controllers.length===1?"":"s"}. Messages presenting one of these tokens are delivered without per-message review unless crossSessionInbound is "hold" or "refuse". A process this session started is always accepted; other senders' review-class claims are not authenticated, so set crossSessionInbound to "hold" to review every inbound message:`,...lines,"","Revoke with /peers revoke <id>."].join("\n")}__name(formatControllerList,"formatControllerList");function formatCreated(createdAt){const date=new Date(createdAt);return Number.isNaN(date.getTime())?"unknown":date.toISOString().replace("T"," ").slice(0,16)}__name(formatCreated,"formatCreated");var peersCommand={name:"peers",kind:"built-in",get description(){return t("Review messages held from other Qwen Code sessions (accept | deny), and manage trusted controllers (controllers | revoke)")},action:__name(async(context,args)=>{const[verb,...rest]=args.trim().split(/\s+/).filter(Boolean);if(verb==="controllers"){return{type:"message",messageType:"info",content:formatControllerList(await listControllers())}}if(verb==="revoke"){const id=rest[0];if(id===void 0){return{type:"message",messageType:"error",content:"Which controller? Use /peers revoke <id> \u2014 /peers controllers lists the ids."}}let removed;try{removed=await removePeerController(id)}catch(error){return{type:"message",messageType:"error",content:`Could not revoke that controller: ${error instanceof Error?error.message:String(error)}`}}if(!removed){return{type:"message",messageType:"error",content:`No controller has the id "${flattenPeerLabel(id)}". Run /peers controllers to see them.`}}const forgotten=context.services.peerMessaging?.forgetController(removed.id)??0;const backlog=forgotten===0?"No held messages in this session used that grant.":`${forgotten} held message${forgotten===1?"":"s"} from it ${forgotten===1?"remains":"remain"} parked for review as ${forgotten===1?"an ordinary peer message":"ordinary peer messages"}.`;return{type:"message",messageType:"info",content:`Revoked the controller "${flattenPeerLabel(removed.label)}" (${removed.id}). Running sessions revalidate active connections, and new connections can no longer use its token. ${backlog}`}}const peerMessaging=context.services.peerMessaging;if(!peerMessaging){const settings=context.services.settings;const runtime=context.services.config;if(!isCrossSessionMessagingActive(settings?.merged,runtime)){const suppression=crossSessionMessagingSuppression(runtime);const offScope=settings?crossSessionMessagingOffScope(settings):void 0;const off=describeMessagingOff(offScope);let content;if(!suppression){content=off}else if(isCrossSessionMessagingEnabled(settings?.merged)){content=describeMessagingSuppressed(suppression)}else{content=`${off} ${describeSuppressionAlso(suppression)}`}return{type:"message",messageType:"info",content}}const failure=getLastPeerInboxFailure();if(failure?.cause==="unsupported_platform"){return{type:"message",messageType:"info",content:"Cross-session messaging is not available on this platform, so this session has no inbox and other sessions cannot reach it."}}return{type:"message",messageType:"error",content:failure?`Cross-session messaging is on, but this session has no inbox \u2014 it failed to bind its socket: ${describePeerInboxFailure(failure)}`:"Cross-session messaging is on, but this session has no inbox: it failed to register in the session registry, or the inbox is still starting. Re-run with DEBUG=1 to see the registration error."}}const held=peerMessaging.getHeld();if(verb===void 0||verb==="list"){peerMessaging.recordHeldListing(held);return{type:"message",messageType:"info",content:formatHeldList(held,entry=>peerMessaging.getHeldExpiryMs(entry.frame.toSessionId))}}if(verb!=="accept"&&verb!=="deny"){return{type:"message",messageType:"error",content:`Unknown subcommand "${verb}". Use /peers, /peers accept <id|all>, /peers deny <id|all>, /peers controllers, or /peers revoke <id>.`}}const decision=verb==="accept"?"approve":"deny";const target=rest[0];if(target===void 0){return{type:"message",messageType:"error",content:`Which message? Use /peers ${verb} <id|all> \u2014 /peers lists the ids.`}}if(peerMessaging.heldSetChangedSinceListing()){return{type:"message",messageType:"error",content:"The waiting list changed since you listed it \u2014 run /peers again to review what is waiting now."}}if(held.length===0){return{type:"message",messageType:"info",content:"No messages from other sessions are waiting."}}if(target.toLowerCase()==="all"){const ids=held.map(entry=>entry.frame.msgId);let count=0;let failed=0;let gone=0;for(const msgId of ids){const outcome2=peerMessaging.decide(msgId,decision);if(outcome2==="done")count+=1;else if(outcome2==="failed")failed+=1;else if(outcome2==="gone")gone+=1}peerMessaging.recordHeldListing(peerMessaging.getHeld());return{type:"message",messageType:"info",content:`${verb==="accept"?"Released":"Dropped"} ${count} message${count===1?"":"s"}.`+(failed>0?` ${failed} could not be delivered and ${failed===1?"is":"are"} still waiting \u2014 try again once the session catches up.`:"")+(gone>0?` ${gone} had already expired or been decided \u2014 run /peers to see what is waiting now.`:"")}}const resolved=resolveHeld(held,target);if(resolved.kind==="none"){return{type:"message",messageType:"error",content:`No held message matches "${target}". Run /peers to see what is waiting.`}}if(resolved.kind==="ambiguous"){return{type:"message",messageType:"error",content:`"${target}" matches more than one held message. Use more characters of the id.`}}const outcome=peerMessaging.decide(resolved.msgId,decision);peerMessaging.recordHeldListing(peerMessaging.getHeld());if(outcome==="gone"){return{type:"message",messageType:"info",content:"That message is no longer waiting \u2014 it may have expired or already been decided."}}if(outcome==="failed"){return{type:"message",messageType:"error",content:"The session could not take the message just now \u2014 its input queue is full, or it could not confirm it still holds the session. It is still waiting; try again in a moment."}}return{type:"message",messageType:"info",content:verb==="accept"?"Released to this session. It will be picked up on the next turn.":"Dropped. The sending session has been told."}},"action")};function describeMessagingOff(scope){switch(scope){case"workspace":return`Cross-session messaging is off: this repository's .qwen/settings.json turns "agents.crossSessionMessaging" off. A workspace may only make that setting stricter, so your user settings cannot turn it back on here. Remove the entry from that file, then restart.`;case"system":return'Cross-session messaging is off: system settings set "agents.crossSessionMessaging", and system settings override every other scope. Whoever manages them can remove the entry.';case"system-defaults":return'Cross-session messaging is off: the system defaults turn "agents.crossSessionMessaging" off. Set it to true in your user settings, then restart.';case"user":return'Cross-session messaging is off: your user settings turn "agents.crossSessionMessaging" off (only true, or leaving it unset, turns it on). Remove that entry, then restart.';default:return'Cross-session messaging is off because of the "agents.crossSessionMessaging" setting (only true, or leaving it unset, turns it on). Remove that entry, then restart.'}}__name(describeMessagingOff,"describeMessagingOff");var SUPPRESSION_PROSE={"safe-mode":{mode:"safe mode",channels:"--safe-mode, or QWEN_CODE_SAFE_MODE",effect:"which closes the surfaces other processes can reach"},bare:{mode:"bare mode",channels:"--bare, or QWEN_CODE_SIMPLE",effect:"which skips implicit startup work"}};function describeMessagingSuppressed(suppression){const{mode,channels,effect}=SUPPRESSION_PROSE[suppression];return`Cross-session messaging is off: this session runs in ${mode} (${channels}), ${effect}. The "agents.crossSessionMessaging" setting cannot turn it back on; restart without ${mode}.`}__name(describeMessagingSuppressed,"describeMessagingSuppressed");function describeSuppressionAlso(suppression){const{mode,channels,effect}=SUPPRESSION_PROSE[suppression];return`This session also runs in ${mode} (${channels}), ${effect}, so fixing the setting alone will not bring messaging back: restart without ${mode} as well.`}__name(describeSuppressionAlso,"describeSuppressionAlso");init_esbuild_shims();function formatBtwError(error){return t("Failed to answer btw question: {{error}}",{error:error instanceof Error?error.message:String(error||"Unknown error")})}__name(formatBtwError,"formatBtwError");function getBtwCacheSafeParams(context){const{config}=context.services;if(config){return buildBtwCacheSafeParams(config)}return null}__name(getBtwCacheSafeParams,"getBtwCacheSafeParams");async function askBtw(context,question,abortSignal){const{config}=context.services;if(!config)throw new Error("Config not loaded");const cacheSafeParams=getBtwCacheSafeParams(context);if(!cacheSafeParams)throw new Error(t("No conversation context available for /btw"));const result=await runForkedAgent({config,userMessage:buildBtwPrompt(question),cacheSafeParams,abortSignal});return result.text||t("No response received.")}__name(askBtw,"askBtw");var btwCommand={name:"btw",get description(){return t("Ask a quick side question without affecting the main conversation")},kind:"built-in",supportedModes:["interactive","acp"],action:__name(async(context,args)=>{const question=args.trim();if(!question){return{type:"message",messageType:"error",content:t("Please provide a question. Usage: /btw <your question>")}}if(question.length>BTW_MAX_INPUT_LENGTH){return{type:"message",messageType:"error",content:t("Question too long (max {{max}} chars)",{max:String(BTW_MAX_INPUT_LENGTH)})}}const{config}=context.services;const{ui}=context;if(!config){return{type:"message",messageType:"error",content:t("Config not loaded.")}}const model=config.getModel();if(!model){return{type:"message",messageType:"error",content:t("No model configured.")}}const executionMode=context.executionMode??"interactive";if(executionMode!=="interactive"){try{const answer=await askBtw(context,question,context.abortSignal??new AbortController().signal);return{type:"message",messageType:"info",content:answer}}catch(error){return{type:"message",messageType:"error",content:formatBtwError(error)}}}ui.cancelBtw();const btwAbortController=new AbortController;const btwSignal=btwAbortController.signal;ui.btwAbortControllerRef.current=btwAbortController;const pendingItem={type:"btw",btw:{question,answer:"",isPending:true}};ui.setBtwItem(pendingItem);void askBtw(context,question,btwSignal).then(answer=>{if(btwSignal.aborted)return;ui.btwAbortControllerRef.current=null;const completedItem={type:"btw",btw:{question,answer,isPending:false}};ui.setBtwItem(completedItem)}).catch(error=>{if(btwSignal.aborted)return;ui.btwAbortControllerRef.current=null;ui.setBtwItem(null);ui.addItem({type:"error",text:formatBtwError(error)},Date.now())})},"action")};init_esbuild_shims();var bugCommand={name:"bug",get description(){return t("submit a bug report")},kind:"built-in",argumentHint:"<description>",supportedModes:["interactive","non_interactive","acp"],canRunDuringStreaming:true,action:__name(async(context,args)=>{const bugDescription=(args||"").trim();const systemInfo=await getExtendedSystemInfo(context);const fields=getSystemInfoFields(systemInfo);const info=fields.map(field=>`${field.label}: ${field.value}`).join("\n");let bugReportUrl="https://github.com/QwenLM/qwen-code/issues/new?template=bug_report.yml&title={title}&info={info}";const bugCommandSettings=context.services.config?.getBugCommand();if(bugCommandSettings?.urlTemplate){bugReportUrl=bugCommandSettings.urlTemplate}bugReportUrl=bugReportUrl.replace("{title}",encodeURIComponent(bugDescription)).replace("{info}",encodeURIComponent(`
|
|
@@ -63,7 +63,7 @@ ${formatHeapSnapshotErrorMessage(error)}`}finally{if(executionMode==="interactiv
|
|
|
63
63
|
${formatToolResultRetention(toolResultRetention)}`:"")}}catch(error){if(context.abortSignal?.aborted){return}return{type:"message",messageType:"error",content:`${t("Failed to collect memory diagnostics")}: ${formatErrorMessage2(error)}`}}}__name(memoryDoctorAction,"memoryDoctorAction");function formatCpuMicroseconds(micros){return`${(micros/1e6).toFixed(2)}s`}__name(formatCpuMicroseconds,"formatCpuMicroseconds");function formatHeapSpaces(spaces){if(!spaces||spaces.length===0){return void 0}const top=[...spaces].sort((a,b)=>b.used-a.used).slice(0,4);const lines=top.map(space=>` - ${space.name}: used ${formatMemoryUsage(space.used)} / size ${formatMemoryUsage(space.size)}`);if(spaces.length>top.length){lines.push(` - \u2026 ${spaces.length-top.length} more`)}return lines.join("\n")}__name(formatHeapSpaces,"formatHeapSpaces");function formatSmapsRollup(smapsRollup){if(!smapsRollup){return t("unavailable")}const rssLine=smapsRollup.split(/\r?\n/).map(line=>line.trim().replace(/\s+/g," ")).find(line=>line.startsWith("Rss:"));if(rssLine){return rssLine}const preview2=smapsRollup.slice(0,80).trim().replace(/\s+/g," ");return`${t("parse error")}: ${preview2}`}__name(formatSmapsRollup,"formatSmapsRollup");function formatCoreDiagnostics(diagnostics){const risks=diagnostics.analysis.risks.length>0?diagnostics.analysis.risks.map(risk=>` - ${risk.type}: ${risk.message}`).join("\n"):` ${t("none")}`;const lines=[t("Memory Diagnostics"),`timestamp: ${diagnostics.timestamp}`,`uptimeSeconds: ${diagnostics.uptimeSeconds.toFixed(1)}`,`heapUsed: ${formatMemoryUsage(diagnostics.memoryUsage.heapUsed)}`,`heapTotal: ${formatMemoryUsage(diagnostics.memoryUsage.heapTotal)}`,`rss: ${formatMemoryUsage(diagnostics.memoryUsage.rss)}`,`external: ${formatMemoryUsage(diagnostics.memoryUsage.external)}`,`arrayBuffers: ${formatMemoryUsage(diagnostics.memoryUsage.arrayBuffers)}`,`v8HeapLimit: ${formatMemoryUsage(diagnostics.v8HeapStats.heapSizeLimit)}`,`v8MallocedMemory: ${formatMemoryUsage(diagnostics.v8HeapStats.mallocedMemory)}`,`v8PeakMallocedMemory: ${formatMemoryUsage(diagnostics.v8HeapStats.peakMallocedMemory)}`,`detachedContexts: ${diagnostics.v8HeapStats.detachedContexts}`,`nativeContexts: ${diagnostics.v8HeapStats.nativeContexts}`,`maxRSS: ${formatMemoryUsage(diagnostics.resourceUsage.maxRSS)}`,`userCPUTime: ${formatCpuMicroseconds(diagnostics.resourceUsage.userCPUTime)}`,`systemCPUTime: ${formatCpuMicroseconds(diagnostics.resourceUsage.systemCPUTime)}`,`activeHandles: ${diagnostics.activeHandles}`,`activeRequests: ${diagnostics.activeRequests}`,`openFileDescriptors: ${diagnostics.openFileDescriptors??t("unavailable")}`,`smapsRollup: ${formatSmapsRollup(diagnostics.smapsRollup)}`];const heapSpaces=formatHeapSpaces(diagnostics.v8HeapSpaces);if(heapSpaces){lines.push("v8HeapSpaces:",heapSpaces)}lines.push("risks:",risks,`recommendation: ${diagnostics.analysis.recommendation}`);return lines.join("\n")}__name(formatCoreDiagnostics,"formatCoreDiagnostics");function collectToolResultRetention(context){try{const config=context.services.config;const history=config?.getLlmClient()?.getHistoryShallow();if(!history){return null}const resolveToolBudgetChars=__name(name=>config?.getToolRegistry?.()?.getTool(canonicalToolName(name))?.maxOutputChars,"resolveToolBudgetChars");const displayNameBudgets=new Map;for(const tool of config?.getToolRegistry?.()?.getAllTools()??[]){if(tool.displayName){displayNameBudgets.set(tool.displayName,tool.maxOutputChars)}}const stats=analyzeToolResultRetention(history,{resolveToolBudgetChars,thresholdChars:config?.getTruncateToolOutputThreshold?.(),imageTokenEstimate:resolveSlimmingConfig(config?.getChatCompression?.()).imageTokenEstimate});const threshold=config?.getTruncateToolOutputThreshold?.()??stats.oversizedThresholdChars;let largeOutputsInUIHistory=0;for(const item of context.ui.history??[]){if(item.type!=="tool_group"){continue}for(const tool of item.tools){const displayText=shellResultText(tool.resultDisplay);if(displayText===void 0){continue}const migratedName=ToolDisplayNamesMigration[tool.name]??tool.name;const budget=displayNameBudgets.get(tool.name)??displayNameBudgets.get(migratedName)??resolveToolBudgetChars(tool.name)??threshold;if(Number.isFinite(budget)&&displayText.length>budget*COMBINED_PASS_TOLERANCE_FACTOR){largeOutputsInUIHistory+=1}}}return{...stats,largeOutputsInUIHistory,presentInCompressionInput:stats.oversizedResultCount>0}}catch(error){debugLogger7.warn(`Tool result retention diagnostics unavailable: ${formatErrorMessage2(error)}`);return null}}__name(collectToolResultRetention,"collectToolResultRetention");function formatToolResultRetention(stats){const lines=["Tool result retention",` Tool results in history: ${stats.toolResultCount}`,` Total retained: ${stats.totalChars} chars`,` Largest result: ${stats.largestResultChars} chars`,` Oversized results (above tool budget): ${stats.oversizedResultCount}`,` Oversized also rendered in UI history: ${stats.largeOutputsInUIHistory} item(s)`,` Oversized also in compression input: ${stats.presentInCompressionInput?"yes (shared by reference, no extra copy)":"no"}`];if(stats.oversizedResultCount>0){lines.push(" Hint: oversized tool results stay in context and tax every later turn; /compress can reclaim space.")}return lines.join("\n")}__name(formatToolResultRetention,"formatToolResultRetention");var CPU_PROFILE_USAGE_HINT="/doctor cpu-profile [--duration <seconds>]";var DEFAULT_CPU_PROFILE_DURATION_SEC=30;var MAX_CPU_PROFILE_DURATION_SEC=300;function parseCpuProfileDuration(raw){if(!raw||!/^\d+$/.test(raw)){return NaN}return Number(raw)}__name(parseCpuProfileDuration,"parseCpuProfileDuration");async function cpuProfileDoctorAction(context,args=""){const executionMode=context.executionMode??"interactive";const abortSignal=context.abortSignal;if(abortSignal?.aborted)return;const tokens=args.trim().split(/\s+/).filter(Boolean);let durationSec=DEFAULT_CPU_PROFILE_DURATION_SEC;const durationIdx=tokens.indexOf("--duration");if(durationIdx!==-1){const rawVal=tokens[durationIdx+1];const val=parseCpuProfileDuration(rawVal);if(!Number.isFinite(val)||val<1||val>MAX_CPU_PROFILE_DURATION_SEC){const errorMsg=`${t("Duration must be between 1 and {max} seconds",{max:String(MAX_CPU_PROFILE_DURATION_SEC)})}. ${t("Usage")}: ${CPU_PROFILE_USAGE_HINT}`;if(executionMode==="interactive"){context.ui.addItem({type:"error",text:errorMsg},Date.now());return}return{type:"message",messageType:"error",content:errorMsg}}durationSec=val}const knownTokens=new Set(["--duration"]);const unknown=tokens.filter((token,idx)=>{if(knownTokens.has(token))return false;if(idx>0&&tokens[idx-1]==="--duration")return false;return true});if(unknown.length>0){const errorMsg=`${t("Unknown argument(s)")}: ${unknown.join(", ")}. ${t("Usage")}: ${CPU_PROFILE_USAGE_HINT}`;if(executionMode==="interactive"){context.ui.addItem({type:"error",text:errorMsg},Date.now());return}return{type:"message",messageType:"error",content:errorMsg}}if(isCpuProfileRecording()){const errorMsg=process.platform==="win32"?t("CPU profiling is already in progress. Wait for it to complete."):t("CPU profiling is already in progress. Send SIGUSR1 or wait for it to complete.");if(executionMode==="interactive"){context.ui.addItem({type:"error",text:errorMsg},Date.now());return}return{type:"message",messageType:"error",content:errorMsg}}const startResult=await startCpuProfile();if(!startResult.ok){if(executionMode==="interactive"){context.ui.addItem({type:"error",text:startResult.error},Date.now());return}return{type:"message",messageType:"error",content:startResult.error}}if(abortSignal?.aborted){const abortResult=await stopCpuProfile();if(abortResult.ok){const msg=t("CPU profile aborted early. Profile saved: {path}",{path:abortResult.filePath});if(executionMode==="interactive"){context.ui.addItem({type:"info",text:msg},Date.now())}}else{const msg=`${t("CPU profile aborted but failed to stop cleanly")}: ${abortResult.error}`;if(executionMode==="interactive"){context.ui.addItem({type:"error",text:msg},Date.now())}}return}if(executionMode==="interactive"){context.ui.setPendingItem({type:"info",text:t("Recording CPU profile for {duration}s...",{duration:String(durationSec)})})}await new Promise(resolve4=>{const timer=setTimeout(resolve4,durationSec*1e3);if(abortSignal){abortSignal.addEventListener("abort",()=>{clearTimeout(timer);resolve4()},{once:true})}});if(executionMode==="interactive"){context.ui.setPendingItem(null)}const stopResult=await stopCpuProfile();if(!stopResult.ok){const alreadyStopped=stopResult.error.includes("not recording");if(alreadyStopped){const infoMsg=process.platform==="win32"?t("CPU profile was stopped externally. Check ~/.qwen/cpu-profiles/ for the output."):t("CPU profile was stopped externally (e.g., via SIGUSR1). Check ~/.qwen/cpu-profiles/ for the output.");if(executionMode==="interactive"){context.ui.addItem({type:"info",text:infoMsg},Date.now());return}return{type:"message",messageType:"info",content:infoMsg}}if(executionMode==="interactive"){context.ui.addItem({type:"error",text:stopResult.error},Date.now());return}return{type:"message",messageType:"error",content:stopResult.error}}const successMsg=`${t("CPU profile written:")} ${stopResult.filePath}
|
|
64
64
|
${t("Open in Chrome DevTools \u2192 Performance tab \u2192 Load profile")}`;if(executionMode==="interactive"){context.ui.addItem({type:"info",text:successMsg},Date.now());return}return{type:"message",messageType:"info",content:successMsg}}__name(cpuProfileDoctorAction,"cpuProfileDoctorAction");function rollbackDoctorAction(context){const installInfo=getInstallationInfo(process.cwd(),false);if(!installInfo.isStandalone||!installInfo.standaloneDir){const msg2=t("Rollback is only available for standalone installations.");if(context.executionMode==="interactive"){context.ui.addItem({type:"info",text:msg2},Date.now());return}return{type:"message",messageType:"info",content:msg2}}if(process.platform==="win32"){const winMsg=t("Rollback on Windows requires manual intervention. Rename qwen-code.old to qwen-code in your installation directory.");if(context.executionMode==="interactive"){context.ui.addItem({type:"info",text:winMsg},Date.now());return}return{type:"message",messageType:"info",content:winMsg}}const result=rollbackStandaloneUpdate(installInfo.standaloneDir);let msg;let messageType;if(result.ok){msg=t("Rollback successful. Restart your terminal to use the previous version.");messageType="info"}else{msg=`${t("Rollback failed:")} ${result.detail}`;messageType="error"}if(context.executionMode==="interactive"){context.ui.addItem({type:messageType,text:msg},Date.now());return}return{type:"message",messageType,content:msg}}__name(rollbackDoctorAction,"rollbackDoctorAction");init_esbuild_shims();var editorCommand={name:"editor",get description(){return t("set external editor preference")},kind:"built-in",supportedModes:["interactive"],canRunDuringStreaming:true,action:__name(()=>({type:"dialog",dialog:"editor"}),"action")};init_esbuild_shims();init_esbuild_shims();function formatEffortChangeMessage(config,tier){if(config.getReasoningEffort()!==tier){const override2=config.getReasoningEffortOverride?.();if(override2){return t("Reasoning effort set to {{tier}}, but thinking is currently disabled; after thinking is re-enabled, {{source}}.{{field}} will still have higher priority.",{tier,source:override2.source,field:override2.field})}return t("Reasoning effort set to {{tier}}, but thinking is currently disabled \u2014 it will take effect when thinking is re-enabled.",{tier})}const override=config.getReasoningEffortOverride?.();if(override){return t("Reasoning effort: {{tier}} requested, but {{source}}.{{field}} has higher priority for the active DashScope Qwen model; that configured value will remain effective.",{tier,source:override.source,field:override.field})}return t("Reasoning effort: {{tier}} (requested; the effective tier depends on the active provider/model).",{tier})}__name(formatEffortChangeMessage,"formatEffortChangeMessage");var TIER_LIST=REASONING_EFFORT_TIERS.join(", ");var effortCommand={name:"effort",get description(){return t("Set how hard reasoning-capable models think ({{tiers}}); mapped and clamped per provider.",{tiers:TIER_LIST})},argumentHint:"[low|medium|high|xhigh|max]",kind:"built-in",supportedModes:["interactive","non_interactive","acp"],action:__name(async(context,actionArgs)=>{const{services}=context;const{config,settings}=services;if(!config){return{type:"message",messageType:"error",content:t("Configuration not available.")}}const args=context.invocation?.args?.trim()||actionArgs.trim();const availableTiers=getReasoningEffortsForConfig(config);if(availableTiers.length===0){return{type:"message",messageType:"info",content:t("The current model does not expose reasoning effort tiers.")}}const availableTierList=availableTiers.join(", ");if(!args){if(context.executionMode==="interactive"){return{type:"dialog",dialog:"effort"}}const current=config.getReasoningEffort();return{type:"message",messageType:"info",content:current&&availableTiers.includes(current)?t('Current reasoning effort: {{current}}\nAvailable: {{tiers}}\nUse "/effort <tier>" to change it.',{current,tiers:availableTierList}):t('Reasoning effort: not set (using the model/provider default).\nAvailable: {{tiers}}\nUse "/effort <tier>" to set it.',{tiers:availableTierList})}}const tier=normalizeReasoningEffort(args);if(!tier||!availableTiers.includes(tier)){return{type:"message",messageType:"error",content:t('Unknown reasoning effort "{{value}}". Choose one of: {{tiers}}.',{value:args,tiers:availableTierList})}}if(!settings){return{type:"message",messageType:"error",content:t("Settings service not available.")}}applyReasoningEffort(config,tier);if(context.executionPolicy?.persistModelSelection!==false){settings.setValue(getPersistScopeForModelSelection(settings),"model.reasoningEffort",tier)}return{type:"message",messageType:"info",content:formatEffortChangeMessage(config,tier)}},"action")};init_esbuild_shims();import*as fs5 from"node:fs/promises";import path5 from"node:path";var EXPORT_DIR_OUT_OF_CWD="Export directory must be within the project working directory.";var debugLogger8=createDebugLogger("EXPORT_COMMAND");function formatExportTargetContext(target){return`target: "${target.outputDir}", cwd: "${target.resolvedCwd}"`}__name(formatExportTargetContext,"formatExportTargetContext");function formatMissingCwdError(resolvedCwd){return`Cannot resolve any existing ancestor within cwd: ${resolvedCwd}. This usually means the project working directory has been deleted or is on an unmounted filesystem.`}__name(formatMissingCwdError,"formatMissingCwdError");function resolveExportTarget(cwd,args,extension){const filename=generateExportFilename(extension);const outputDirArg=args.trim();const resolvedCwd=path5.resolve(cwd);const outputDir=outputDirArg?path5.resolve(resolvedCwd,outputDirArg):resolvedCwd;const filepath=path5.join(outputDir,filename);const isDefaultOutputDir=outputDir===resolvedCwd;const isInsideCwd=isSubpath(resolvedCwd,outputDir);const outputDirKind=outputDirArg&&!isDefaultOutputDir?"custom":"default";return{filepath,outputDir,displayPath:isDefaultOutputDir?filename:path5.join(outputDirArg,filename),resolvedCwd,outputDirKind,isInsideCwd}}__name(resolveExportTarget,"resolveExportTarget");async function validateExportTargetWithinCwd(target){debugLogger8.debug("Validating export target realpath:",formatExportTargetContext(target));let realCwd;let realOutputDir;try{[realCwd,realOutputDir]=await Promise.all([fs5.realpath(target.resolvedCwd),fs5.realpath(target.outputDir)])}catch(error){if(error.code==="ENOENT"){debugLogger8.debug("Export target realpath validation failed: missing path",formatExportTargetContext(target));return{type:"message",messageType:"error",content:`Export target directory is not accessible (path does not exist; ${formatExportTargetContext(target)}).`}}throw error}if(!isSubpath(realCwd,realOutputDir)){debugLogger8.debug("Export target realpath escaped cwd:",{realCwd,realOutputDir,target});return{type:"message",messageType:"error",content:`${EXPORT_DIR_OUT_OF_CWD} (target path resolves outside cwd via symlink; ${formatExportTargetContext(target)})`}}return void 0}__name(validateExportTargetWithinCwd,"validateExportTargetWithinCwd");async function realpathNearestExisting(outputDir,resolvedCwd){let currentPath=outputDir;debugLogger8.debug("Resolving nearest existing export parent:",{outputDir,resolvedCwd});while(isSubpath(resolvedCwd,currentPath)){try{const realCurrentPath=await fs5.realpath(currentPath);debugLogger8.debug("Resolved nearest existing export parent:",{currentPath,realCurrentPath});return realCurrentPath}catch(error){if(error.code!=="ENOENT"){debugLogger8.debug("Failed to resolve existing export parent:",error);throw error}const parentPath=path5.dirname(currentPath);if(parentPath===currentPath){break}currentPath=parentPath}}throw new Error(formatMissingCwdError(resolvedCwd))}__name(realpathNearestExisting,"realpathNearestExisting");async function validateExistingExportParentWithinCwd(target){debugLogger8.debug("Validating existing export parent realpath:",formatExportTargetContext(target));let realCwd;try{realCwd=await fs5.realpath(target.resolvedCwd)}catch(error){if(error.code==="ENOENT"){throw new Error(formatMissingCwdError(target.resolvedCwd))}throw error}const realExistingParent=await realpathNearestExisting(target.outputDir,target.resolvedCwd);if(!isSubpath(realCwd,realExistingParent)){debugLogger8.debug("Existing export parent escaped cwd:",{realCwd,realExistingParent,target});return{type:"message",messageType:"error",content:`${EXPORT_DIR_OUT_OF_CWD} (parent path resolves outside cwd via symlink; ${formatExportTargetContext(target)})`}}return void 0}__name(validateExistingExportParentWithinCwd,"validateExistingExportParentWithinCwd");async function exportSessionAction(context,args,exportFormat){const{services}=context;const{config}=services;if(!config){return{type:"message",messageType:"error",content:"Configuration not available."}}const cwd=config.getWorkingDir()||config.getProjectRoot();if(!cwd){return{type:"message",messageType:"error",content:"Could not determine current working directory."}}const target=resolveExportTarget(cwd,args,exportFormat.extension);const targetFilepath=target.filepath;debugLogger8.debug("Resolved export target:",{format:exportFormat.displayName,cwd,outputDirArg:args.trim(),outputDir:target.outputDir,outputDirKind:target.outputDirKind,filepath:target.filepath});if(!target.isInsideCwd){debugLogger8.debug("Export target rejected before realpath validation:",formatExportTargetContext(target));return{type:"message",messageType:"error",content:`${EXPORT_DIR_OUT_OF_CWD} (target path is outside cwd; ${formatExportTargetContext(target)})`}}try{const initialValidationError=target.outputDirKind==="custom"?await validateExistingExportParentWithinCwd(target):await validateExportTargetWithinCwd(target);if(initialValidationError){return initialValidationError}debugLogger8.debug("Export target validation passed:",{format:exportFormat.displayName,outputDir:target.outputDir,outputDirKind:target.outputDirKind});const sessionService=new SessionService(cwd);const sessionId=config.getSessionId();debugLogger8.debug("Loading session for export:",{sessionId,cwd});const sessionData=await sessionService.loadSession(sessionId);if(!sessionData){debugLogger8.debug("No active session found for export:",{sessionId,cwd});return{type:"message",messageType:"error",content:"No active session found to export."}}const{conversation}=sessionData;const exportData=await collectSessionData(conversation,config);const normalizedData=normalizeSessionData(exportData,conversation.messages,config);const content=exportFormat.format(normalizedData,conversation.messages);if(target.outputDirKind==="custom"){try{debugLogger8.debug("Creating export directory:",{outputDir:target.outputDir});await fs5.mkdir(target.outputDir,{recursive:true,mode:448})}catch(error){debugLogger8.debug("Failed to create export directory:",error);return{type:"message",messageType:"error",content:`Failed to create export directory "${target.outputDir}": ${error instanceof Error?error.message:String(error)}`}}}try{const writeValidationError=await validateExportTargetWithinCwd(target);if(writeValidationError){return writeValidationError}}catch(error){debugLogger8.debug("Export path validation failed before write:",error);return{type:"message",messageType:"error",content:`Export path validation failed: ${error instanceof Error?error.message:String(error)} (${exportFormat.displayName} target: "${targetFilepath}")`}}try{debugLogger8.debug("Writing export file:",{format:exportFormat.displayName,filepath:target.filepath});await fs5.writeFile(target.filepath,content,{encoding:"utf-8",mode:384});await fs5.chmod(target.filepath,384).catch(error=>{debugLogger8.debug("Failed to tighten export file permissions:",error)})}catch(error){debugLogger8.debug("Failed to write export file:",error);return{type:"message",messageType:"error",content:`Failed to export session: ${error instanceof Error?error.message:String(error)} (${exportFormat.displayName} target: "${targetFilepath}")`}}debugLogger8.debug("Session export completed:",{format:exportFormat.displayName,filepath:target.filepath});const workspacePath=context.executionMode==="acp"?toCanonicalWorkspaceArtifactPath(target.filepath,config.getTargetDir()):null;const artifacts=workspacePath?[{kind:exportFormat.extension==="html"?"html":"file",storage:"workspace",title:path5.basename(target.filepath),workspacePath,mimeType:exportFormat.mimeType,sizeBytes:Buffer.byteLength(content,"utf-8")}]:[];return{type:"message",messageType:"info",content:`Session exported to ${exportFormat.displayName}: ${target.displayPath}`,...artifacts.length>0?{artifacts}:{}}}catch(error){debugLogger8.debug("Session export failed:",{format:exportFormat.displayName,target,error});return{type:"message",messageType:"error",content:`Failed to export session: ${error instanceof Error?error.message:String(error)} (${exportFormat.displayName})`}}}__name(exportSessionAction,"exportSessionAction");async function exportMarkdownAction(context,args){return exportSessionAction(context,args,{extension:"md",displayName:"markdown",mimeType:"text/markdown; charset=utf-8",format:toMarkdown})}__name(exportMarkdownAction,"exportMarkdownAction");async function exportHtmlAction(context,args){return exportSessionAction(context,args,{extension:"html",displayName:"HTML",mimeType:"text/html; charset=utf-8",format:toHtml})}__name(exportHtmlAction,"exportHtmlAction");async function exportJsonAction(context,args){return exportSessionAction(context,args,{extension:"json",displayName:"JSON",mimeType:"application/json; charset=utf-8",format:toJson})}__name(exportJsonAction,"exportJsonAction");async function exportJsonlAction(context,args){return exportSessionAction(context,args,{extension:"jsonl",displayName:"JSONL",mimeType:"application/jsonl; charset=utf-8",format:toJsonl})}__name(exportJsonlAction,"exportJsonlAction");var exportCommand={name:"export",get description(){return t("Export current session message history to a file")},argumentHint:"[md|html|json|jsonl] [path]",kind:"built-in",supportedModes:["interactive","non_interactive","acp"],action:exportHtmlAction,subCommands:[{name:"html",get description(){return t("Export session to HTML format")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],action:exportHtmlAction},{name:"md",get description(){return t("Export session to markdown format")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],action:exportMarkdownAction},{name:"json",get description(){return t("Export session to JSON format")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],action:exportJsonAction},{name:"jsonl",get description(){return t("Export session to JSONL format (one message per line)")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],action:exportJsonlAction}]};init_esbuild_shims();var debugLogger9=createDebugLogger("FORK_COMMAND");function deriveForkDescription(directive){const oneLine=directive.replace(/\s+/g," ").trim();return oneLine.length>60?`${oneLine.slice(0,57)}\u2026`:oneLine}__name(deriveForkDescription,"deriveForkDescription");function hasFailedDisplayStatus(display){return display!==null&&typeof display==="object"&&"status"in display&&display.status==="failed"}__name(hasFailedDisplayStatus,"hasFailedDisplayStatus");var forkCommand={name:"fork",kind:"built-in",supportedModes:["interactive"],argumentHint:"<directive>",get description(){return t("Spawn a background agent that inherits the full conversation")},action:__name(async(context,args)=>{const directive=args.trim();if(!directive){return{type:"message",messageType:"error",content:t("Please provide a directive. Usage: /fork <directive>")}}const{config}=context.services;const{ui}=context;if(!config){return{type:"message",messageType:"error",content:t("Config is not available.")}}if(ui.isIdleRef?.current===false){return{type:"message",messageType:"error",content:t("Cannot fork while a response or tool call is in progress. Wait for it to finish or resolve the pending tool call.")}}if(!config.getModel()){return{type:"message",messageType:"error",content:t("No model configured.")}}let hasHistory=false;try{hasHistory=(config.getLlmClient().getHistoryShallow()??[]).length>0}catch(error){debugLogger9.debug("Failed to read history before /fork:",error);hasHistory=false}if(!hasHistory){return{type:"message",messageType:"error",content:t("Cannot fork before the first conversation turn.")}}const agentTool=config.getToolRegistry().getTool(ToolNames.AGENT);if(!agentTool){return{type:"message",messageType:"error",content:t("The agent tool is unavailable; cannot fork.")}}const params={description:deriveForkDescription(directive),prompt:directive,subagent_type:FORK_SUBAGENT_TYPE,run_in_background:true};let result;try{result=await agentTool.build(params).execute(new AbortController().signal)}catch(error){return{type:"message",messageType:"error",content:t("Failed to launch fork: {{error}}",{error:error instanceof Error?error.message:String(error)})}}const display=result?.returnDisplay;if(hasFailedDisplayStatus(display)){const reason=typeof result.llmContent==="string"&&result.llmContent.trim()?result.llmContent.trim():t("the background agent could not be started.");return{type:"message",messageType:"error",content:t("Failed to launch fork: {{error}}",{error:reason})}}try{config.getLlmClient().addHistory({role:"user",parts:[{text:t("User launched a background fork via /fork: {{directive}}",{directive})}]})}catch(error){debugLogger9.debug("Failed to record fork event in history:",error)}return{type:"message",messageType:"info",content:t("Forked into a background agent. It inherits this conversation and runs without blocking \u2014 track it in the background tasks panel; it reports back when done.")}},"action")};init_esbuild_shims();var debugLogger10=createDebugLogger("EXTENSIONS_COMMAND");var EXTENSION_EXPLORE_URL={Gemini:"https://geminicli.com/extensions/",ClaudeCode:"https://claudemarketplaces.com/"};async function exploreAction(context,args){const mode=context.executionMode??"interactive";if(mode!=="interactive"){return{type:"message",messageType:"error",content:t("/extensions explore is only available in interactive mode.")}}const source=args.trim();const extensionsUrl=source?EXTENSION_EXPLORE_URL[source]:"";if(!extensionsUrl){context.ui.addItem({type:"error",text:t("Unknown extensions source: {{source}}.",{source})},Date.now());return}if(false){context.ui.addItem({type:"info",text:t("Would open extensions page in your browser: {{url}} (skipped in test environment)",{url:extensionsUrl})},Date.now())}else if(process.env["SANDBOX"]&&process.env["SANDBOX"]!=="sandbox-exec"){context.ui.addItem({type:"info",text:t("View available extensions at {{url}}",{url:extensionsUrl})},Date.now())}else{context.ui.addItem({type:"info",text:t("Opening extensions page in your browser: {{url}}",{url:extensionsUrl})},Date.now());try{await openBrowserSecurely(extensionsUrl)}catch(_error){context.ui.addItem({type:"error",text:t("Failed to open browser. Check out the extensions gallery at {{url}}",{url:extensionsUrl})},Date.now())}}return void 0}__name(exploreAction,"exploreAction");async function listAction(context,args){const mode=context.executionMode??"interactive";if(mode!=="interactive"){return listTextAction(context,args)}return{type:"dialog",dialog:"extensions_manage"}}__name(listAction,"listAction");async function listTextAction(context,_args){const config=context.services.config;if(!config){return{type:"message",messageType:"error",content:t("Config not loaded.")}}let extensions;try{extensions=config.getExtensions()}catch(error){return{type:"message",messageType:"error",content:t("Failed to read extensions: {{error}}",{error:error instanceof Error?error.message:String(error)})}}if(extensions.length===0){return{type:"message",messageType:"info",content:t("No extensions installed.")}}const active=extensions.filter(e=>e.isActive);let output=t("**Installed Extensions ({{total}} total, {{active}} active)**",{total:String(extensions.length),active:String(active.length)})+"\n\n";const locale=getCurrentLanguage();for(const ext of extensions){const status=ext.isActive?"\u2713":"\u2717";const displayLabel=getExtensionDisplayName(ext,locale);const description=getExtensionDescription(ext,locale);const caps=[];const mcpCount=ext.mcpServers?Object.keys(ext.mcpServers).length:0;if(mcpCount>0){caps.push(t("{{count}} MCP servers",{count:String(mcpCount)}))}if(ext.skills&&ext.skills.length>0){caps.push(t("{{count}} skills",{count:String(ext.skills.length)}))}if(ext.commands&&ext.commands.length>0){caps.push(t("{{count}} commands",{count:String(ext.commands.length)}))}const capsStr=caps.length>0?` [${caps.join(", ")}]`:"";output+=`- [${status}] **${displayLabel}**${capsStr}
|
|
65
65
|
`;if(description){const maxLen=80;const truncated=description.length>maxLen?description.slice(0,maxLen-1)+"\u2026":description;output+=` ${truncated}
|
|
66
|
-
`}}return{type:"message",messageType:"info",content:output}}__name(listTextAction,"listTextAction");async function installAction(context,args){const mode=context.executionMode??"interactive";if(mode!=="interactive"){return{type:"message",messageType:"error",content:t("/extensions install is only available in interactive mode.")}}const extensionManager=context.services.config?.getExtensionManager();if(!(extensionManager instanceof ExtensionManager)){debugLogger10.error(`Cannot ${context.invocation?.name} extensions in this environment`);return}const source=args.trim();if(!source){context.ui.addItem({type:"error",text:t("Usage: /extensions install <source>")},Date.now());return}try{const installMetadata=await parseInstallSource(source);const redactedSource=redactUrlCredentials(source);context.ui.addItem({type:"info",text:t('Installing extension from "{{source}}"...',{source:redactedSource})},Date.now());const extension=await extensionManager.installExtension(installMetadata);context.ui.addItem({type:"info",text:t('Extension "{{name}}" installed successfully.',{name:extension.name})},Date.now());context.ui.reloadCommands()}catch(error){if(isExtensionCommittedWithWarningsError(error)){context.ui.addItem({type:"warning",text:t("Extension was installed but could not be reloaded: {{error}}",{error:redactUrlCredentials(getErrorMessage2(error))})},Date.now());context.ui.reloadCommands();return}context.ui.addItem({type:"error",text:t('Failed to install extension from "{{source}}": {{error}}',{source:redactUrlCredentials(source),error:redactUrlCredentials(getErrorMessage2(error))})},Date.now());return}return void 0}__name(installAction,"installAction");async function completeExtensionsExplore(context,partialArg){const suggestions=Object.keys(EXTENSION_EXPLORE_URL).filter(name=>name.startsWith(partialArg));return suggestions}__name(completeExtensionsExplore,"completeExtensionsExplore");var exploreExtensionsCommand={name:"explore",get description(){return t("Open extensions page in your browser")},kind:"built-in",supportedModes:["interactive"],action:exploreAction,completion:completeExtensionsExplore};var manageExtensionsCommand={name:"manage",get description(){return t("Manage installed extensions")},kind:"built-in",supportedModes:["interactive"],action:listAction};var listExtensionsCommand={name:"list",get description(){return t("List installed extensions")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],action:listTextAction};var installCommand={name:"install",get description(){return t("Install an extension from a git repo or local path")},kind:"built-in",supportedModes:["interactive"],action:installAction};var extensionsCommand={name:"extensions",get description(){return t("Manage extensions")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],subCommands:[listExtensionsCommand,manageExtensionsCommand,installCommand,exploreExtensionsCommand],action:__name(async(context,args)=>{const executionMode=context.executionMode??"interactive";if(executionMode==="interactive"){return manageExtensionsCommand.action(context,args)}return listTextAction(context,args)},"action")};init_esbuild_shims();var CLEAR_KEYWORDS=new Set(["clear","stop","off","reset","none","cancel"]);function parseGoalCommand(args){let input=args.trim();if(/^\/goal(?:\s|$)/i.test(input)){input=input.slice("/goal".length).trim()}if(!input)return{kind:"status"};const[head="",...tail]=input.split(/\s+/);const keyword=head.toLowerCase();const objective=tail.join(" ").trim();if(keyword==="set"){return objective?{kind:"set",objective}:{kind:"error",message:"`/goal set` requires an objective."}}if(keyword==="edit"){return objective?{kind:"edit",objective}:{kind:"error",message:"`/goal edit` requires an objective."}}if(tail.length===0){if(keyword==="pause")return{kind:"pause"};if(keyword==="resume")return{kind:"resume"};if(CLEAR_KEYWORDS.has(keyword))return{kind:"clear"}}return{kind:"set",objective:input}}__name(parseGoalCommand,"parseGoalCommand");function errorMessage(content){return{type:"message",messageType:"error",content}}__name(errorMessage,"errorMessage");function goalControl(operation,response,cause){return{type:"goal_control",operation,response,...cause?{cause}:{}}}__name(goalControl,"goalControl");var goalCommand={name:"goal",get description(){return t("Set or control a session goal")},argumentHint:"[<objective> | set <objective> | edit <objective> | pause | resume | clear]",kind:"built-in",supportedModes:["interactive","non_interactive","acp"],action:__name(async(context,args)=>{const{config}=context.services;if(!config)return errorMessage("Configuration is not available.");const operation=parseGoalCommand(args);if(operation.kind==="error")return errorMessage(operation.message);const requiresTrustedFolder=operation.kind==="set"||operation.kind==="edit"||operation.kind==="resume";if(requiresTrustedFolder&&!config.isTrustedFolder()){return errorMessage("/goal is only available in trusted workspaces. Trust this folder via `/trust` and try again.")}let runtime;try{runtime=await config.getGoalRuntimeReady()}catch(error){if(error instanceof GoalPersistenceUnavailableError&&(operation.kind==="status"||operation.kind==="clear")&&config.getChatRecordingService()===void 0){return goalControl(operation,{snapshot:emptyGoalSnapshot()})}return errorMessage(error instanceof Error?error.message:String(error))}try{const snapshot=runtime.getSnapshot();if(operation.kind==="status"){return goalControl(operation,{snapshot})}const current=snapshot.goal;if(operation.kind==="set"){const request2=current?{action:"replace",objective:operation.objective,expectedGoalId:current.goalId,expectedRevision:current.revision}:{action:"create",objective:operation.objective};return goalControl(operation,await runtime.dispatch(request2),request2.action)}if(!current){if(operation.kind==="clear"){return goalControl(operation,{snapshot})}return errorMessage(`Cannot ${operation.kind}: no Goal is active.`)}const version={expectedGoalId:current.goalId,expectedRevision:current.revision};const request=operation.kind==="edit"?{action:"edit",objective:operation.objective,...version}:operation.kind==="pause"?{action:"pause",...version,reason:GOAL_PAUSE_REASON_COMMAND}:{action:operation.kind,...version};return goalControl(operation,await runtime.dispatch(request),request.action)}catch(error){return errorMessage(error instanceof Error?error.message:String(error))}},"action")};init_esbuild_shims();var helpCommand={name:"help",altNames:["?"],kind:"built-in",supportedModes:["interactive"],canRunDuringStreaming:true,get description(){return t("for help on Qwen Code")},action:__name(async()=>({type:"dialog",dialog:"help"}),"action")};init_esbuild_shims();var collapseOnResumeCommand={name:"collapse-on-resume",get description(){return t("Set history to collapse by default when resuming a session")},kind:"built-in",supportedModes:["interactive"],action:__name(context=>{const{settings}=context.services;settings.setValue("User","ui.history.collapseOnResume",true);return{type:"message",messageType:"info",content:t("History will be collapsed by default for future resumed sessions.")}},"action")};var expandOnResumeCommand={name:"expand-on-resume",get description(){return t("Set history to expand by default when resuming a session")},kind:"built-in",supportedModes:["interactive"],action:__name(context=>{const{settings}=context.services;settings.setValue("User","ui.history.collapseOnResume",false);return{type:"message",messageType:"info",content:t("History will be expanded by default for future resumed sessions.")}},"action")};var expandNowCommand={name:"expand-now",get description(){return t("Expand the currently collapsed history transcript")},kind:"built-in",supportedModes:["interactive"],action:__name(async context=>{const{history,loadHistory,refreshStatic}=context.ui;const hasSuppressed=history.some(item=>item.display?.suppressOnRestore);if(!hasSuppressed){return{type:"message",messageType:"info",content:t("History is already expanded in this session.")}}const{expandCollapsedHistory}=await import("./resumeHistoryUtils-R5YQS4YQ.js");const updated=expandCollapsedHistory(history);loadHistory(updated,"expand");refreshStatic()},"action")};var historyCommand={name:"history",get description(){return t("Control history display preferences and visibility")},argumentHint:"collapse-on-resume|expand-on-resume|expand-now",kind:"built-in",supportedModes:["interactive"],subCommands:[collapseOnResumeCommand,expandOnResumeCommand,expandNowCommand],action:__name(async()=>({type:"message",messageType:"error",content:t("Usage: /history collapse-on-resume|expand-on-resume|expand-now")}),"action")};init_esbuild_shims();init_esbuild_shims();function getHookExitCodes(eventName){const exitCodesMap={["Stop"]:[{code:0,description:t("stdout/stderr not shown")},{code:2,description:t("show stderr to model and continue conversation")},{code:"Other",description:t("show stderr to user only")}],["PreToolUse"]:[{code:0,description:t("stdout/stderr not shown")},{code:2,description:t("show stderr to model and block tool call")},{code:"Other",description:t("show stderr to user only but continue with tool call")}],["PostToolUse"]:[{code:0,description:t("stdout shown in transcript mode (ctrl+o)")},{code:2,description:t("show stderr to model immediately")},{code:"Other",description:t("show stderr to user only")}],["PostToolUseFailure"]:[{code:0,description:t("stdout shown in transcript mode (ctrl+o)")},{code:2,description:t("show stderr to model immediately")},{code:"Other",description:t("show stderr to user only")}],["PostToolBatch"]:[{code:0,description:t("stdout shown in transcript mode (ctrl+o)")},{code:2,description:t("show stderr to model immediately")},{code:"Other",description:t("show stderr to user only")}],["MessageDisplay"]:[{code:0,description:t("fire-and-forget; exit status is ignored")},{code:"Other",description:t("fire-and-forget; exit status is ignored")}],["Notification"]:[{code:0,description:t("stdout/stderr not shown")},{code:"Other",description:t("show stderr to user only")}],["InstructionsLoaded"]:[{code:0,description:t("stdout/stderr not shown")},{code:"Other",description:t("show stderr to user only")}],["UserPromptSubmit"]:[{code:0,description:t("stdout shown to Qwen")},{code:2,description:t("block processing, erase original prompt, and show stderr to user only")},{code:"Other",description:t("show stderr to user only")}],["UserPromptExpansion"]:[{code:0,description:t("stdout shown to Qwen")},{code:2,description:t("block expanded prompt submission and show stderr to user only")},{code:"Other",description:t("show stderr to user only")}],["SessionStart"]:[{code:0,description:t("stdout shown to Qwen")},{code:"Other",description:t("show stderr to user only (blocking errors ignored)")}],["SessionEnd"]:[{code:0,description:t("command completes successfully")},{code:"Other",description:t("show stderr to user only")}],["SessionDelete"]:[{code:0,description:t("fire-and-forget; exit status is ignored")},{code:"Other",description:t("fire-and-forget; exit status is ignored")}],["SubagentStart"]:[{code:0,description:t("stdout shown to subagent")},{code:"Other",description:t("show stderr to user only (blocking errors ignored)")}],["SubagentStop"]:[{code:0,description:t("stdout/stderr not shown")},{code:2,description:t("show stderr to subagent and continue having it run")},{code:"Other",description:t("show stderr to user only")}],["PreCompact"]:[{code:0,description:t("stdout appended as custom compact instructions")},{code:2,description:t("block compaction")},{code:"Other",description:t("show stderr to user only but continue with compaction")}],["PostCompact"]:[{code:0,description:t("stdout/stderr not shown")},{code:"Other",description:t("show stderr to user only")}],["StopFailure"]:[{code:0,description:t("fire-and-forget; exit status is ignored")},{code:"Other",description:t("fire-and-forget; exit status is ignored")}],["PermissionRequest"]:[{code:0,description:t("use hook decision if provided")},{code:"Other",description:t("show stderr to user only")}],["PermissionDenied"]:[{code:0,description:t("stdout/stderr not shown")},{code:"Other",description:t("show stderr to user only")}],["TodoCreated"]:[{code:0,description:t("allow todo creation")},{code:2,description:t("block todo creation and show reason to model")},{code:"Other",description:t("show stderr to user only")}],["TodoCompleted"]:[{code:0,description:t("allow todo completion")},{code:2,description:t("block todo completion and show reason to model")},{code:"Other",description:t("show stderr to user only")}]};return exitCodesMap[eventName]||[]}__name(getHookExitCodes,"getHookExitCodes");function getHookShortDescription(eventName){const descriptions={["PreToolUse"]:t("Before tool execution"),["PostToolUse"]:t("After tool execution"),["PostToolUseFailure"]:t("After tool execution fails"),["PostToolBatch"]:t("After all tool calls in a batch resolve"),["Notification"]:t("When notifications are sent"),["InstructionsLoaded"]:t("When instruction files are loaded"),["UserPromptSubmit"]:t("When the user submits a prompt"),["UserPromptExpansion"]:t("When a slash command expands into a prompt"),["SessionStart"]:t("When a new session is started"),["MessageDisplay"]:t("Repeatedly, as the assistant reply streams"),["Stop"]:t("Right before Qwen Code concludes its response"),["SubagentStart"]:t("When a subagent (Agent tool call) is started"),["SubagentStop"]:t("Right before a subagent concludes its response"),["PreCompact"]:t("Before conversation compaction"),["PostCompact"]:t("After conversation compaction"),["StopFailure"]:t("When the turn ends due to an API error (fires instead of Stop)"),["SessionEnd"]:t("When a session is ending"),["SessionDelete"]:t("After an explicitly selected session is deleted"),["PermissionRequest"]:t("When a permission dialog is displayed"),["PermissionDenied"]:t("When AUTO-mode classification denies a tool call"),["TodoCreated"]:t("When a new todo item is created"),["TodoCompleted"]:t("When a todo item is marked as completed")};return descriptions[eventName]||""}__name(getHookShortDescription,"getHookShortDescription");function getHookDescription(eventName){const descriptions={["Stop"]:"",["PreToolUse"]:t("Input to command is JSON of tool call arguments."),["PostToolUse"]:t('Input to command is JSON with fields "inputs" (tool call arguments) and "response" (tool call response).'),["PostToolUseFailure"]:t("Input to command is JSON with tool_name, tool_input, tool_use_id, error, error_type, is_interrupt, and is_timeout."),["PostToolBatch"]:t("Input to command is JSON with tool_calls, an array of resolved tool calls containing tool_name, tool_input, tool_use_id, and tool_response."),["Notification"]:t("Input to command is JSON with notification message and type."),["InstructionsLoaded"]:t("Input to command is JSON with file_path, memory_type, load_reason, and optional trigger_file_path and parent_file_path."),["UserPromptSubmit"]:t('Input to command is JSON with "prompt" (the current model-bound prompt) and optional "submitted_prompt" (the text projection captured at a supported submission boundary).'),["UserPromptExpansion"]:t("Input to command is JSON with command_name, command_args, and expanded prompt text."),["SessionStart"]:t("Input to command is JSON with session start source."),["MessageDisplay"]:t("Input to command is JSON with message_id, displayed_text (cumulative text streamed so far), and is_final. Fire-and-forget: output and exit status are ignored."),["SessionEnd"]:t("Input to command is JSON with session end reason."),["SessionDelete"]:t("Input to command is JSON with deleted_session_id. It runs after an explicitly selected session is deleted; output and failures are ignored."),["SubagentStart"]:t("Input to command is JSON with agent_id and agent_type."),["SubagentStop"]:t("Input to command is JSON with agent_id, agent_type, and agent_transcript_path."),["PreCompact"]:t("Input to command is JSON with compaction details."),["PostCompact"]:t("Input to command is JSON with trigger (manual/auto) and compact_summary. Output is ignored for control purposes."),["StopFailure"]:t("Input to command is JSON with error (rate_limit, authentication_failed, billing_error, invalid_request, server_error, max_output_tokens, unknown) and optional error_details. Fire-and-forget: output and exit status are ignored."),["PermissionRequest"]:t("Input to command is JSON with tool_name, tool_input, and tool_use_id. Output JSON with hookSpecificOutput containing decision to allow or deny."),["PermissionDenied"]:t("Input to command is JSON with tool_name, tool_input, tool_use_id, and reason."),["TodoCreated"]:t("Input to command is JSON with todo_id, todo_content, todo_status, all_todos, and phase. In validation, output JSON with decision (allow/block/deny) and reason. In postWrite, block/deny is ignored."),["TodoCompleted"]:t("Input to command is JSON with todo_id, todo_content, previous_status, all_todos, and phase. In validation, output JSON with decision (allow/block/deny) and reason. In postWrite, block/deny is ignored.")};return descriptions[eventName]||""}__name(getHookDescription,"getHookDescription");function getTranslatedSourceDisplayMap(){return{["project"]:t("Local Settings"),["user"]:t("User Settings"),["system"]:t("System Settings"),["extensions"]:t("Extensions"),["session"]:t("Session (temporary)")}}__name(getTranslatedSourceDisplayMap,"getTranslatedSourceDisplayMap");var DISPLAY_HOOK_EVENTS=Object.values(HookEventName);function supportsMatchers(eventName){return hookEventSupportsMatcher(eventName)}__name(supportsMatchers,"supportsMatchers");function createEmptyHookEventInfo(eventName){return{event:eventName,shortDescription:getHookShortDescription(eventName),description:getHookDescription(eventName),exitCodes:getHookExitCodes(eventName),matcherGroups:[]}}__name(createEmptyHookEventInfo,"createEmptyHookEventInfo");init_esbuild_shims();function normalizeMatcher(matcher){const trimmed=matcher?.trim();return trimmed?trimmed:"*"}__name(normalizeMatcher,"normalizeMatcher");function addConfigToMatcherGroup(hookInfo,matcher,sequential,configInfo,groupByMatcher=true){const normalizedMatcher=groupByMatcher?normalizeMatcher(matcher):"*";const normalizedSequential=sequential??false;const normalizedConfig={...configInfo,matcher:normalizedMatcher,sequential:normalizedSequential};let group=hookInfo.matcherGroups.find(candidate=>candidate.matcher===normalizedMatcher);if(!group){group={matcher:normalizedMatcher,sequential:normalizedSequential,configs:[]};hookInfo.matcherGroups.push(group)}else if(normalizedSequential){group.sequential=true}group.configs.push(normalizedConfig)}__name(addConfigToMatcherGroup,"addConfigToMatcherGroup");function getAllConfigs(hookInfo){return hookInfo.matcherGroups.flatMap(group=>group.configs)}__name(getAllConfigs,"getAllConfigs");var debugLogger11=createDebugLogger("HOOKS_COMMAND");async function reloadHooksFromSettings(config,settings){const hookSystem=config.getHookSystem();if(!hookSystem){return}if(!settings.reloadScopesFromDiskAtomically(["User","Workspace"])){throw new Error("Settings could not be read; the previous hooks are still active.")}const systemScopes=["System","SystemDefaults"];const systemReloaded=settings.reloadScopesFromDiskAtomically(systemScopes);config.setHooksFromSettings(resolveHookSettingsForConfig(settings.merged.hooks,{systemHooks:settings.getSystemHooks(),userHooks:settings.getUserHooks(),projectHooks:settings.getProjectHooks()},config.getBareMode()||config.isSafeMode(),config.getTopTierMcpServers()?.["external-context"]));await hookSystem.reload();if(!systemReloaded){const paths=systemScopes.map(scope=>settings.forScope(scope).path).join(", ");throw new Error(`System settings could not be read (${paths}); hooks from them are unchanged, and other hook edits were applied.`)}}__name(reloadHooksFromSettings,"reloadHooksFromSettings");function formatHookSource(source){switch(source){case"project":return t("Project");case"user":return t("User");case"system":return t("System");case"extensions":return t("Extension");case"session":return t("Session (temporary)");default:return source}}__name(formatHookSource,"formatHookSource");var listCommand={name:"list",get description(){return t("List all configured hooks")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],action:__name(async(context,_args)=>{const{config}=context.services;if(!config){return{type:"message",messageType:"error",content:t("Config not loaded.")}}const hookSystem=config.getHookSystem();if(!hookSystem){return{type:"message",messageType:"info",content:t("Hooks are not enabled. Enable hooks in settings to use this feature.")}}const registry=hookSystem.getRegistry();const configHooks=registry.getAllHooks();const sessionId=config.getSessionId();const sessionHooksManager=hookSystem.getSessionHooksManager();const sessionHooks=sessionId?sessionHooksManager.getAllSessionHooks(sessionId):[];const totalHooks=configHooks.length+sessionHooks.length;if(totalHooks===0){return{type:"message",messageType:"info",content:t("No hooks configured. Add hooks in your settings.json file or invoke a skill with hooks.")}}const hooksByEvent=new Map;const addHook=__name((eventName,matcher,hook)=>{const matcherKey=supportsMatchers(eventName)?matcher:"*";let matcherMap=hooksByEvent.get(eventName);if(!matcherMap){matcherMap=new Map;hooksByEvent.set(eventName,matcherMap)}let bucket=matcherMap.get(matcherKey);if(!bucket){bucket=[];matcherMap.set(matcherKey,bucket)}bucket.push(hook)},"addHook");const extractName=__name(config2=>config2.name||(config2.type==="command"?config2.command:void 0)||(config2.type==="http"?config2.url:void 0)||"unnamed","extractName");for(const hook of configHooks){const configHook=hook;const config2=configHook.config;addHook(configHook.eventName,normalizeMatcher(configHook.matcher),{name:extractName(config2),source:formatHookSource(configHook.source)})}for(const hook of sessionHooks){const sessionHook=hook;const config2=sessionHook.config;addHook(sessionHook.eventName,normalizeMatcher(sessionHook.matcher),{name:extractName(config2),source:formatHookSource("session")})}let output=`**Configured Hooks (${totalHooks} total)**
|
|
66
|
+
`}}return{type:"message",messageType:"info",content:output}}__name(listTextAction,"listTextAction");async function installAction(context,args){const mode=context.executionMode??"interactive";if(mode!=="interactive"){return{type:"message",messageType:"error",content:t("/extensions install is only available in interactive mode.")}}const extensionManager=context.services.config?.getExtensionManager();if(!(extensionManager instanceof ExtensionManager)){debugLogger10.error(`Cannot ${context.invocation?.name} extensions in this environment`);return}const source=args.trim();if(!source){context.ui.addItem({type:"error",text:t("Usage: /extensions install <source>")},Date.now());return}try{const installMetadata=await parseInstallSource(source);const redactedSource=redactUrlCredentials(source);context.ui.addItem({type:"info",text:t('Installing extension from "{{source}}"...',{source:redactedSource})},Date.now());const extension=await extensionManager.installExtension(installMetadata);context.ui.addItem({type:"info",text:t('Extension "{{name}}" installed successfully.',{name:extension.name})},Date.now());context.ui.reloadCommands()}catch(error){if(isExtensionCommittedWithWarningsError(error)){context.ui.addItem({type:"warning",text:t("Extension was installed but could not be reloaded: {{error}}",{error:redactUrlCredentials(getErrorMessage2(error))})},Date.now());context.ui.reloadCommands();return}context.ui.addItem({type:"error",text:t('Failed to install extension from "{{source}}": {{error}}',{source:redactUrlCredentials(source),error:redactUrlCredentials(getErrorMessage2(error))})},Date.now());return}return void 0}__name(installAction,"installAction");async function completeExtensionsExplore(context,partialArg){const suggestions=Object.keys(EXTENSION_EXPLORE_URL).filter(name=>name.startsWith(partialArg));return suggestions}__name(completeExtensionsExplore,"completeExtensionsExplore");var exploreExtensionsCommand={name:"explore",get description(){return t("Open extensions page in your browser")},kind:"built-in",supportedModes:["interactive"],action:exploreAction,completion:completeExtensionsExplore};var manageExtensionsCommand={name:"manage",get description(){return t("Manage installed extensions")},kind:"built-in",supportedModes:["interactive"],action:listAction};var listExtensionsCommand={name:"list",get description(){return t("List installed extensions")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],action:listTextAction};var installCommand={name:"install",get description(){return t("Install an extension from a git repo or local path")},kind:"built-in",supportedModes:["interactive"],action:installAction};var extensionsCommand={name:"extensions",get description(){return t("Manage extensions")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],subCommands:[listExtensionsCommand,manageExtensionsCommand,installCommand,exploreExtensionsCommand],action:__name(async(context,args)=>{const executionMode=context.executionMode??"interactive";if(executionMode==="interactive"){return manageExtensionsCommand.action(context,args)}return listTextAction(context,args)},"action")};init_esbuild_shims();var CLEAR_KEYWORDS=new Set(["clear","stop","off","reset","none","cancel"]);function parseGoalCommand(args){let input=args.trim();if(/^\/goal(?:\s|$)/i.test(input)){input=input.slice("/goal".length).trim()}if(!input)return{kind:"status"};const[head="",...tail]=input.split(/\s+/);const keyword=head.toLowerCase();const objective=tail.join(" ").trim();if(keyword==="set"){return objective?{kind:"set",objective}:{kind:"error",message:"`/goal set` requires an objective."}}if(keyword==="edit"){return objective?{kind:"edit",objective}:{kind:"error",message:"`/goal edit` requires an objective."}}if(tail.length===0){if(keyword==="pause")return{kind:"pause"};if(keyword==="resume")return{kind:"resume"};if(CLEAR_KEYWORDS.has(keyword))return{kind:"clear"}}return{kind:"set",objective:input}}__name(parseGoalCommand,"parseGoalCommand");function errorMessage(content){return{type:"message",messageType:"error",content}}__name(errorMessage,"errorMessage");function goalControl(operation,response,cause){return{type:"goal_control",operation,response,...cause?{cause}:{}}}__name(goalControl,"goalControl");var goalCommand={name:"goal",get description(){return t("Set or control a session goal")},argumentHint:"[<objective> | set <objective> | edit <objective> | pause | resume | clear]",kind:"built-in",supportedModes:["interactive","non_interactive","acp"],action:__name(async(context,args)=>{const{config}=context.services;if(!config)return errorMessage("Configuration is not available.");const operation=parseGoalCommand(args);if(operation.kind==="error")return errorMessage(operation.message);const requiresTrustedFolder=operation.kind==="set"||operation.kind==="edit"||operation.kind==="resume";if(requiresTrustedFolder&&!config.isTrustedFolder()){return errorMessage("/goal is only available in trusted workspaces. Trust this folder via `/trust` and try again.")}let runtime;try{runtime=await config.getGoalRuntimeReady()}catch(error){if(error instanceof GoalPersistenceUnavailableError&&(operation.kind==="status"||operation.kind==="clear")&&config.getChatRecordingService()===void 0){return goalControl(operation,{snapshot:emptyGoalSnapshot()})}return errorMessage(error instanceof Error?error.message:String(error))}try{const snapshot=runtime.getSnapshot();if(operation.kind==="status"){return goalControl(operation,{snapshot})}const current=snapshot.goal;if(operation.kind==="set"){const request2=current?{action:"replace",objective:operation.objective,expectedGoalId:current.goalId,expectedRevision:current.revision}:{action:"create",objective:operation.objective};return goalControl(operation,await runtime.dispatch(request2),request2.action)}if(!current){if(operation.kind==="clear"){return goalControl(operation,{snapshot})}return errorMessage(`Cannot ${operation.kind}: no Goal is active.`)}const version={expectedGoalId:current.goalId,expectedRevision:current.revision};const request=operation.kind==="edit"?{action:"edit",objective:operation.objective,...version}:operation.kind==="pause"?{action:"pause",...version,reason:GOAL_PAUSE_REASON_COMMAND}:{action:operation.kind,...version};return goalControl(operation,await runtime.dispatch(request),request.action)}catch(error){return errorMessage(error instanceof Error?error.message:String(error))}},"action")};init_esbuild_shims();var helpCommand={name:"help",altNames:["?"],kind:"built-in",supportedModes:["interactive"],canRunDuringStreaming:true,get description(){return t("for help on Qwen Code")},action:__name(async()=>({type:"dialog",dialog:"help"}),"action")};init_esbuild_shims();var collapseOnResumeCommand={name:"collapse-on-resume",get description(){return t("Set history to collapse by default when resuming a session")},kind:"built-in",supportedModes:["interactive"],action:__name(context=>{const{settings}=context.services;settings.setValue("User","ui.history.collapseOnResume",true);return{type:"message",messageType:"info",content:t("History will be collapsed by default for future resumed sessions.")}},"action")};var expandOnResumeCommand={name:"expand-on-resume",get description(){return t("Set history to expand by default when resuming a session")},kind:"built-in",supportedModes:["interactive"],action:__name(context=>{const{settings}=context.services;settings.setValue("User","ui.history.collapseOnResume",false);return{type:"message",messageType:"info",content:t("History will be expanded by default for future resumed sessions.")}},"action")};var expandNowCommand={name:"expand-now",get description(){return t("Expand the currently collapsed history transcript")},kind:"built-in",supportedModes:["interactive"],action:__name(async context=>{const{history,loadHistory,refreshStatic}=context.ui;const hasSuppressed=history.some(item=>item.display?.suppressOnRestore);if(!hasSuppressed){return{type:"message",messageType:"info",content:t("History is already expanded in this session.")}}const{expandCollapsedHistory}=await import("./resumeHistoryUtils-2B4KPI7G.js");const updated=expandCollapsedHistory(history);loadHistory(updated,"expand");refreshStatic()},"action")};var historyCommand={name:"history",get description(){return t("Control history display preferences and visibility")},argumentHint:"collapse-on-resume|expand-on-resume|expand-now",kind:"built-in",supportedModes:["interactive"],subCommands:[collapseOnResumeCommand,expandOnResumeCommand,expandNowCommand],action:__name(async()=>({type:"message",messageType:"error",content:t("Usage: /history collapse-on-resume|expand-on-resume|expand-now")}),"action")};init_esbuild_shims();init_esbuild_shims();function getHookExitCodes(eventName){const exitCodesMap={["Stop"]:[{code:0,description:t("stdout/stderr not shown")},{code:2,description:t("show stderr to model and continue conversation")},{code:"Other",description:t("show stderr to user only")}],["PreToolUse"]:[{code:0,description:t("stdout/stderr not shown")},{code:2,description:t("show stderr to model and block tool call")},{code:"Other",description:t("show stderr to user only but continue with tool call")}],["PostToolUse"]:[{code:0,description:t("stdout shown in transcript mode (ctrl+o)")},{code:2,description:t("show stderr to model immediately")},{code:"Other",description:t("show stderr to user only")}],["PostToolUseFailure"]:[{code:0,description:t("stdout shown in transcript mode (ctrl+o)")},{code:2,description:t("show stderr to model immediately")},{code:"Other",description:t("show stderr to user only")}],["PostToolBatch"]:[{code:0,description:t("stdout shown in transcript mode (ctrl+o)")},{code:2,description:t("show stderr to model immediately")},{code:"Other",description:t("show stderr to user only")}],["MessageDisplay"]:[{code:0,description:t("fire-and-forget; exit status is ignored")},{code:"Other",description:t("fire-and-forget; exit status is ignored")}],["Notification"]:[{code:0,description:t("stdout/stderr not shown")},{code:"Other",description:t("show stderr to user only")}],["InstructionsLoaded"]:[{code:0,description:t("stdout/stderr not shown")},{code:"Other",description:t("show stderr to user only")}],["UserPromptSubmit"]:[{code:0,description:t("stdout shown to Qwen")},{code:2,description:t("block processing, erase original prompt, and show stderr to user only")},{code:"Other",description:t("show stderr to user only")}],["UserPromptExpansion"]:[{code:0,description:t("stdout shown to Qwen")},{code:2,description:t("block expanded prompt submission and show stderr to user only")},{code:"Other",description:t("show stderr to user only")}],["SessionStart"]:[{code:0,description:t("stdout shown to Qwen")},{code:"Other",description:t("show stderr to user only (blocking errors ignored)")}],["SessionEnd"]:[{code:0,description:t("command completes successfully")},{code:"Other",description:t("show stderr to user only")}],["SessionDelete"]:[{code:0,description:t("fire-and-forget; exit status is ignored")},{code:"Other",description:t("fire-and-forget; exit status is ignored")}],["SubagentStart"]:[{code:0,description:t("stdout shown to subagent")},{code:"Other",description:t("show stderr to user only (blocking errors ignored)")}],["SubagentStop"]:[{code:0,description:t("stdout/stderr not shown")},{code:2,description:t("show stderr to subagent and continue having it run")},{code:"Other",description:t("show stderr to user only")}],["PreCompact"]:[{code:0,description:t("stdout appended as custom compact instructions")},{code:2,description:t("block compaction")},{code:"Other",description:t("show stderr to user only but continue with compaction")}],["PostCompact"]:[{code:0,description:t("stdout/stderr not shown")},{code:"Other",description:t("show stderr to user only")}],["StopFailure"]:[{code:0,description:t("fire-and-forget; exit status is ignored")},{code:"Other",description:t("fire-and-forget; exit status is ignored")}],["PermissionRequest"]:[{code:0,description:t("use hook decision if provided")},{code:"Other",description:t("show stderr to user only")}],["PermissionDenied"]:[{code:0,description:t("stdout/stderr not shown")},{code:"Other",description:t("show stderr to user only")}],["TodoCreated"]:[{code:0,description:t("allow todo creation")},{code:2,description:t("block todo creation and show reason to model")},{code:"Other",description:t("show stderr to user only")}],["TodoCompleted"]:[{code:0,description:t("allow todo completion")},{code:2,description:t("block todo completion and show reason to model")},{code:"Other",description:t("show stderr to user only")}]};return exitCodesMap[eventName]||[]}__name(getHookExitCodes,"getHookExitCodes");function getHookShortDescription(eventName){const descriptions={["PreToolUse"]:t("Before tool execution"),["PostToolUse"]:t("After tool execution"),["PostToolUseFailure"]:t("After tool execution fails"),["PostToolBatch"]:t("After all tool calls in a batch resolve"),["Notification"]:t("When notifications are sent"),["InstructionsLoaded"]:t("When instruction files are loaded"),["UserPromptSubmit"]:t("When the user submits a prompt"),["UserPromptExpansion"]:t("When a slash command expands into a prompt"),["SessionStart"]:t("When a new session is started"),["MessageDisplay"]:t("Repeatedly, as the assistant reply streams"),["Stop"]:t("Right before Qwen Code concludes its response"),["SubagentStart"]:t("When a subagent (Agent tool call) is started"),["SubagentStop"]:t("Right before a subagent concludes its response"),["PreCompact"]:t("Before conversation compaction"),["PostCompact"]:t("After conversation compaction"),["StopFailure"]:t("When the turn ends due to an API error (fires instead of Stop)"),["SessionEnd"]:t("When a session is ending"),["SessionDelete"]:t("After an explicitly selected session is deleted"),["PermissionRequest"]:t("When a permission dialog is displayed"),["PermissionDenied"]:t("When AUTO-mode classification denies a tool call"),["TodoCreated"]:t("When a new todo item is created"),["TodoCompleted"]:t("When a todo item is marked as completed")};return descriptions[eventName]||""}__name(getHookShortDescription,"getHookShortDescription");function getHookDescription(eventName){const descriptions={["Stop"]:"",["PreToolUse"]:t("Input to command is JSON of tool call arguments."),["PostToolUse"]:t('Input to command is JSON with fields "inputs" (tool call arguments) and "response" (tool call response).'),["PostToolUseFailure"]:t("Input to command is JSON with tool_name, tool_input, tool_use_id, error, error_type, is_interrupt, and is_timeout."),["PostToolBatch"]:t("Input to command is JSON with tool_calls, an array of resolved tool calls containing tool_name, tool_input, tool_use_id, and tool_response."),["Notification"]:t("Input to command is JSON with notification message and type."),["InstructionsLoaded"]:t("Input to command is JSON with file_path, memory_type, load_reason, and optional trigger_file_path and parent_file_path."),["UserPromptSubmit"]:t('Input to command is JSON with "prompt" (the current model-bound prompt) and optional "submitted_prompt" (the text projection captured at a supported submission boundary).'),["UserPromptExpansion"]:t("Input to command is JSON with command_name, command_args, and expanded prompt text."),["SessionStart"]:t("Input to command is JSON with session start source."),["MessageDisplay"]:t("Input to command is JSON with message_id, displayed_text (cumulative text streamed so far), and is_final. Fire-and-forget: output and exit status are ignored."),["SessionEnd"]:t("Input to command is JSON with session end reason."),["SessionDelete"]:t("Input to command is JSON with deleted_session_id. It runs after an explicitly selected session is deleted; output and failures are ignored."),["SubagentStart"]:t("Input to command is JSON with agent_id and agent_type."),["SubagentStop"]:t("Input to command is JSON with agent_id, agent_type, and agent_transcript_path."),["PreCompact"]:t("Input to command is JSON with compaction details."),["PostCompact"]:t("Input to command is JSON with trigger (manual/auto) and compact_summary. Output is ignored for control purposes."),["StopFailure"]:t("Input to command is JSON with error (rate_limit, authentication_failed, billing_error, invalid_request, server_error, max_output_tokens, unknown) and optional error_details. Fire-and-forget: output and exit status are ignored."),["PermissionRequest"]:t("Input to command is JSON with tool_name, tool_input, and tool_use_id. Output JSON with hookSpecificOutput containing decision to allow or deny."),["PermissionDenied"]:t("Input to command is JSON with tool_name, tool_input, tool_use_id, and reason."),["TodoCreated"]:t("Input to command is JSON with todo_id, todo_content, todo_status, all_todos, and phase. In validation, output JSON with decision (allow/block/deny) and reason. In postWrite, block/deny is ignored."),["TodoCompleted"]:t("Input to command is JSON with todo_id, todo_content, previous_status, all_todos, and phase. In validation, output JSON with decision (allow/block/deny) and reason. In postWrite, block/deny is ignored.")};return descriptions[eventName]||""}__name(getHookDescription,"getHookDescription");function getTranslatedSourceDisplayMap(){return{["project"]:t("Local Settings"),["user"]:t("User Settings"),["system"]:t("System Settings"),["extensions"]:t("Extensions"),["session"]:t("Session (temporary)")}}__name(getTranslatedSourceDisplayMap,"getTranslatedSourceDisplayMap");var DISPLAY_HOOK_EVENTS=Object.values(HookEventName);function supportsMatchers(eventName){return hookEventSupportsMatcher(eventName)}__name(supportsMatchers,"supportsMatchers");function createEmptyHookEventInfo(eventName){return{event:eventName,shortDescription:getHookShortDescription(eventName),description:getHookDescription(eventName),exitCodes:getHookExitCodes(eventName),matcherGroups:[]}}__name(createEmptyHookEventInfo,"createEmptyHookEventInfo");init_esbuild_shims();function normalizeMatcher(matcher){const trimmed=matcher?.trim();return trimmed?trimmed:"*"}__name(normalizeMatcher,"normalizeMatcher");function addConfigToMatcherGroup(hookInfo,matcher,sequential,configInfo,groupByMatcher=true){const normalizedMatcher=groupByMatcher?normalizeMatcher(matcher):"*";const normalizedSequential=sequential??false;const normalizedConfig={...configInfo,matcher:normalizedMatcher,sequential:normalizedSequential};let group=hookInfo.matcherGroups.find(candidate=>candidate.matcher===normalizedMatcher);if(!group){group={matcher:normalizedMatcher,sequential:normalizedSequential,configs:[]};hookInfo.matcherGroups.push(group)}else if(normalizedSequential){group.sequential=true}group.configs.push(normalizedConfig)}__name(addConfigToMatcherGroup,"addConfigToMatcherGroup");function getAllConfigs(hookInfo){return hookInfo.matcherGroups.flatMap(group=>group.configs)}__name(getAllConfigs,"getAllConfigs");var debugLogger11=createDebugLogger("HOOKS_COMMAND");async function reloadHooksFromSettings(config,settings){const hookSystem=config.getHookSystem();if(!hookSystem){return}if(!settings.reloadScopesFromDiskAtomically(["User","Workspace"])){throw new Error("Settings could not be read; the previous hooks are still active.")}const systemScopes=["System","SystemDefaults"];const systemReloaded=settings.reloadScopesFromDiskAtomically(systemScopes);config.setHooksFromSettings(resolveHookSettingsForConfig(settings.merged.hooks,{systemHooks:settings.getSystemHooks(),userHooks:settings.getUserHooks(),projectHooks:settings.getProjectHooks()},config.getBareMode()||config.isSafeMode(),config.getTopTierMcpServers()?.["external-context"]));await hookSystem.reload();if(!systemReloaded){const paths=systemScopes.map(scope=>settings.forScope(scope).path).join(", ");throw new Error(`System settings could not be read (${paths}); hooks from them are unchanged, and other hook edits were applied.`)}}__name(reloadHooksFromSettings,"reloadHooksFromSettings");function formatHookSource(source){switch(source){case"project":return t("Project");case"user":return t("User");case"system":return t("System");case"extensions":return t("Extension");case"session":return t("Session (temporary)");default:return source}}__name(formatHookSource,"formatHookSource");var listCommand={name:"list",get description(){return t("List all configured hooks")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],action:__name(async(context,_args)=>{const{config}=context.services;if(!config){return{type:"message",messageType:"error",content:t("Config not loaded.")}}const hookSystem=config.getHookSystem();if(!hookSystem){return{type:"message",messageType:"info",content:t("Hooks are not enabled. Enable hooks in settings to use this feature.")}}const registry=hookSystem.getRegistry();const configHooks=registry.getAllHooks();const sessionId=config.getSessionId();const sessionHooksManager=hookSystem.getSessionHooksManager();const sessionHooks=sessionId?sessionHooksManager.getAllSessionHooks(sessionId):[];const totalHooks=configHooks.length+sessionHooks.length;if(totalHooks===0){return{type:"message",messageType:"info",content:t("No hooks configured. Add hooks in your settings.json file or invoke a skill with hooks.")}}const hooksByEvent=new Map;const addHook=__name((eventName,matcher,hook)=>{const matcherKey=supportsMatchers(eventName)?matcher:"*";let matcherMap=hooksByEvent.get(eventName);if(!matcherMap){matcherMap=new Map;hooksByEvent.set(eventName,matcherMap)}let bucket=matcherMap.get(matcherKey);if(!bucket){bucket=[];matcherMap.set(matcherKey,bucket)}bucket.push(hook)},"addHook");const extractName=__name(config2=>config2.name||(config2.type==="command"?config2.command:void 0)||(config2.type==="http"?config2.url:void 0)||"unnamed","extractName");for(const hook of configHooks){const configHook=hook;const config2=configHook.config;addHook(configHook.eventName,normalizeMatcher(configHook.matcher),{name:extractName(config2),source:formatHookSource(configHook.source)})}for(const hook of sessionHooks){const sessionHook=hook;const config2=sessionHook.config;addHook(sessionHook.eventName,normalizeMatcher(sessionHook.matcher),{name:extractName(config2),source:formatHookSource("session")})}let output=`**Configured Hooks (${totalHooks} total)**
|
|
67
67
|
|
|
68
68
|
`;for(const[eventName,matcherMap]of hooksByEvent){output+=`### ${eventName}
|
|
69
69
|
|
|
@@ -188,7 +188,7 @@ None captured`}async scanChatFiles(baseDir){const allChatFiles=[];try{const proj
|
|
|
188
188
|
</body>
|
|
189
189
|
</html>`;return html}};var StaticInsightGenerator=class{static{__name(this,"StaticInsightGenerator")}dataProcessor;templateRenderer;constructor(config){this.dataProcessor=new DataProcessor(config);this.templateRenderer=new TemplateRenderer}async ensureOutputDirectory(){const outputDir=path15.join(Storage.getRuntimeBaseDir(),"insights");await fs12.mkdir(outputDir,{recursive:true});return outputDir}async generateOutputPath(outputDir){const now=new Date;const date=dayKey(now);const time=now.toTimeString().slice(0,8).replace(/:/g,"");let outputPath=path15.join(outputDir,`insight-${date}.html`);try{await fs12.access(outputPath);outputPath=path15.join(outputDir,`insight-${date}-${time}.html`)}catch{}return outputPath}async updateInsightSymlink(outputDir,targetPath){const latestPath=path15.join(outputDir,"insight.html");await updateSymlink(latestPath,targetPath)}async generateStaticInsight(baseDir,onProgress){const outputDir=await this.ensureOutputDirectory();const facetsDir=path15.join(outputDir,"facets");await fs12.mkdir(facetsDir,{recursive:true});const insights=await this.dataProcessor.generateInsights(baseDir,facetsDir,onProgress);const html=await this.templateRenderer.renderInsightHTML(insights);const outputPath=await this.generateOutputPath(outputDir);await fs12.writeFile(outputPath,html,"utf-8");await this.updateInsightSymlink(outputDir,outputPath);return outputPath}};var logger3=createDebugLogger("DataProcessor");var insightCommand={name:"insight",get description(){return t("generate personalized programming insights from your chat history")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],action:__name(async context=>{try{context.ui.setDebugMessage(t("Generating insights..."));const projectsDir=join7(Storage.getRuntimeBaseDir(),"projects");if(!context.services.config){if(context.executionMode!=="interactive"){return{type:"message",messageType:"error",content:"Config service is not available."}}throw new Error("Config service is not available")}const insightGenerator=new StaticInsightGenerator(context.services.config);if(context.executionMode==="non_interactive"){try{const outputPath2=await insightGenerator.generateStaticInsight(projectsDir,()=>{});return{type:"message",messageType:"info",content:t("Insight report generated at: {{path}}",{path:outputPath2})}}catch(error){return{type:"message",messageType:"error",content:t("Failed to generate insights: {{error}}",{error:error.message})}}}if(context.executionMode==="acp"){const pendingMessages=[];let isComplete=false;let resume=null;const flushResume=__name(()=>{const resolve4=resume;if(!resolve4){return}resume=null;resolve4()},"flushResume");const pushMessage=__name(message2=>{pendingMessages.push(message2);flushResume()},"pushMessage");const streamMessages=__name(async function*(){while(!isComplete||pendingMessages.length>0){if(pendingMessages.length===0){await new Promise(resolve4=>{resume=resolve4})}while(pendingMessages.length>0){const message2=pendingMessages.shift();if(message2){yield message2}}}},"streamMessages");void(async()=>{try{pushMessage({messageType:"info",content:t("This may take a couple minutes. Sit tight!")});pushMessage({messageType:"info",content:encodeInsightProgressMessage(t("Starting insight generation..."),0)});const outputPath2=await insightGenerator.generateStaticInsight(projectsDir,(stage,progress,detail)=>{pushMessage({messageType:"info",content:encodeInsightProgressMessage(stage,progress,detail)})});pushMessage({messageType:"info",content:encodeInsightReadyMessage(outputPath2)})}catch(error){const errorText=error.message;pushMessage({messageType:"info",content:encodeInsightErrorMessage(errorText)});pushMessage({messageType:"error",content:t("Failed to generate insights: {{error}}",{error:errorText})});logger3.error("Insight generation error:",error)}finally{isComplete=true;flushResume()}})();return{type:"stream_messages",messages:streamMessages()}}const updateProgress=__name((stage,progress,detail)=>{const progressItem={type:"insight_progress",progress:{stage,progress,detail}};context.ui.setPendingItem(progressItem)},"updateProgress");context.ui.addItem({type:"info",text:t("This may take a couple minutes. Sit tight!")},Date.now());updateProgress(t("Starting insight generation..."),0);const outputPath=await insightGenerator.generateStaticInsight(projectsDir,updateProgress);context.ui.setPendingItem(null);context.ui.addItem({type:"info",text:t("Insight report generated successfully!")},Date.now());context.ui.addItem({type:"info",text:t("Insights generated at: {{path}}. If the browser does not open automatically, open this file manually.",{path:outputPath})},Date.now());try{await openBrowserSecurely(pathToFileURL(outputPath).href,{allowFile:true,allowedFilePaths:[outputPath]})}catch(browserError){logger3.error("Failed to open browser automatically:",browserError)}context.ui.setDebugMessage(t("Insights ready."));return}catch(error){context.ui.setPendingItem(null);if(context.executionMode!=="interactive"){return{type:"message",messageType:"error",content:`Failed to generate insights: ${error.message}`}}context.ui.addItem({type:"error",text:t("Failed to generate insights: {{error}}",{error:error.message})},Date.now());logger3.error("Insight generation error:",error);return}},"action")};init_esbuild_shims();var learnCommand={name:"learn",get description(){return t("Create a reusable skill from a knowledge source (file, URL, conversation, or text).")},kind:"built-in",supportedModes:["interactive","acp"],argumentHint:"<path|URL|text> [focus]",action:__name(async(context,args)=>{const rawInput=args.trim();if(!rawInput){return{type:"message",messageType:"error",content:t("Usage: /learn <path|URL|text> [focus]\nExamples:\n /learn https://docs.example.com/api\n /learn ~/projects/acme-sdk\n /learn Our deploy process: ssh to prod, run migrate, restart")}}const config=context.services.config;if(!config){return{type:"message",messageType:"error",content:t("Config not loaded.")}}const projectRoot=config.getProjectRoot();const video=parseLearnVideoInput(rawInput);if(video){if(video.kind==="youtube"){return{type:"message",messageType:"error",content:t("YouTube page URLs cannot be sent as native video input. Download the video into your workspace and pass the local video file path to /learn.")}}const authType=config.getContentGeneratorConfig()?.authType;const supportsVideoTransport=authType==="openai"||authType==="qwen-oauth";if(config.getEffectiveInputModalities().video!==true||!supportsVideoTransport){return{type:"message",messageType:"error",content:t("The current model or provider does not support native video input for /learn. Switch to a video-capable model on an OpenAI-compatible provider and try again.")}}let localVideoPart;if(video.kind==="local"){let parts;try{parts=await readPathFromWorkspace(expandHomeDir(video.source),config)}catch{return{type:"submit_prompt",content:await buildLearnSkillPrompt(rawInput,projectRoot)}}localVideoPart=parts.find(part=>typeof part!=="string"&&part.inlineData?.mimeType?.startsWith("video/")===true);if(!localVideoPart){const inlineParts=parts.filter(part=>typeof part!=="string"&&part.inlineData!=null);if(inlineParts.length===1&&inlineParts[0].inlineData){inlineParts[0].inlineData.mimeType=video.mimeType;localVideoPart=inlineParts[0]}}if(!localVideoPart){const errorDetail=parts.filter(p=>typeof p==="string").join(" ");return{type:"message",messageType:"error",content:errorDetail?`${t("The local video could not be attached for /learn.")} ${errorDetail}`:t("The local video could not be attached for /learn.")}}}return{type:"submit_prompt",content:await buildLearnVideoSkillRequest(video,projectRoot,localVideoPart)}}return{type:"submit_prompt",content:await buildLearnSkillPrompt(rawInput,projectRoot)}},"action")};init_esbuild_shims();var statuslineCommand={name:"statusline",get description(){return t("Set up Qwen Code's status line UI")},kind:"built-in",supportedModes:["interactive"],action:__name((_context,args)=>{const prompt=args.trim();if(!prompt){return{type:"dialog",dialog:"statusline"}}return{type:"submit_prompt",content:[{text:`Use the Agent tool with subagent_type: "statusline-setup" and this prompt:
|
|
190
190
|
|
|
191
|
-
${prompt}`}]}},"action")};init_esbuild_shims();function emitMessage(context,messageType,content){if(context.executionMode!=="interactive"){return{type:"message",messageType,content}}context.ui.addItem({type:messageType==="error"?"error":"info",text:content},Date.now())}__name(emitMessage,"emitMessage");var lspCommand={name:"lsp",get description(){return t("Show LSP server status. Usage: /lsp [status]")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],canRunDuringStreaming:true,action:__name(async(context,_args)=>{const config=context.services.config;if(!config){return emitMessage(context,"error",t("Config not available."))}if(!config.isLspEnabled()){return emitMessage(context,"info",t("LSP is not enabled. Start Qwen Code with `--experimental-lsp` to enable LSP support."))}const client=config.getLspClient();if(!client){return emitMessage(context,"info",t("LSP is enabled but no client is connected. Check debug logs under `${QWEN_RUNTIME_DIR:-~/.qwen}/debug/` or see the LSP troubleshooting docs."))}if(!client.getServerStatus){return emitMessage(context,"info",t("LSP is enabled, but server status is unavailable."))}const servers=client.getServerStatus();if(servers.length===0){return emitMessage(context,"info",t("No LSP servers configured. Add a `.lsp.json` file to your project root. See `/help` for details."))}const lines=["**LSP Server Status**",""];lines.push("| Server | Command | Languages | Status |");lines.push("|--------|---------|-----------|--------|");for(const server of servers){const cmd=server.command??"(n/a)";const langs=server.languages.join(", ")||"(auto)";const statusText=server.error?`${server.status} - ${server.error}`:server.status;lines.push(`| ${server.name} | \`${cmd}\` | ${langs} | ${statusText} |`)}return emitMessage(context,"info",lines.join("\n"))},"action")};init_esbuild_shims();var updateCommand={name:"update",get description(){return t("Check for Qwen Code updates and install if available")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],action:__name(async context=>{const[{checkForUpdatesDetailed,describeUpdateCheckFailure},{CUSTOM_SANDBOX_IMAGE_ENV_VAR,HOST_UPDATE_RELAUNCH_ENV_VAR,relaunchForUpdate},{performStandaloneUpdate},installationInfo]=await Promise.all([import("./updateCheck-
|
|
191
|
+
${prompt}`}]}},"action")};init_esbuild_shims();function emitMessage(context,messageType,content){if(context.executionMode!=="interactive"){return{type:"message",messageType,content}}context.ui.addItem({type:messageType==="error"?"error":"info",text:content},Date.now())}__name(emitMessage,"emitMessage");var lspCommand={name:"lsp",get description(){return t("Show LSP server status. Usage: /lsp [status]")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],canRunDuringStreaming:true,action:__name(async(context,_args)=>{const config=context.services.config;if(!config){return emitMessage(context,"error",t("Config not available."))}if(!config.isLspEnabled()){return emitMessage(context,"info",t("LSP is not enabled. Start Qwen Code with `--experimental-lsp` to enable LSP support."))}const client=config.getLspClient();if(!client){return emitMessage(context,"info",t("LSP is enabled but no client is connected. Check debug logs under `${QWEN_RUNTIME_DIR:-~/.qwen}/debug/` or see the LSP troubleshooting docs."))}if(!client.getServerStatus){return emitMessage(context,"info",t("LSP is enabled, but server status is unavailable."))}const servers=client.getServerStatus();if(servers.length===0){return emitMessage(context,"info",t("No LSP servers configured. Add a `.lsp.json` file to your project root. See `/help` for details."))}const lines=["**LSP Server Status**",""];lines.push("| Server | Command | Languages | Status |");lines.push("|--------|---------|-----------|--------|");for(const server of servers){const cmd=server.command??"(n/a)";const langs=server.languages.join(", ")||"(auto)";const statusText=server.error?`${server.status} - ${server.error}`:server.status;lines.push(`| ${server.name} | \`${cmd}\` | ${langs} | ${statusText} |`)}return emitMessage(context,"info",lines.join("\n"))},"action")};init_esbuild_shims();var updateCommand={name:"update",get description(){return t("Check for Qwen Code updates and install if available")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],action:__name(async context=>{const[{checkForUpdatesDetailed,describeUpdateCheckFailure},{CUSTOM_SANDBOX_IMAGE_ENV_VAR,HOST_UPDATE_RELAUNCH_ENV_VAR,relaunchForUpdate},{performStandaloneUpdate},installationInfo]=await Promise.all([import("./updateCheck-CMEWLLZJ.js"),import("./processUtils-GQYNJRBJ.js"),import("./standalone-update-IGDX2RGN.js"),import("./installationInfo-OKA4WXAS.js")]);const{formatUpdateInstructions,getInstallationInfo:getInstallationInfo2}=installationInfo;const settings=context.services.settings;const projectRoot=context.services.config?.getProjectRoot();const updateCheck=await checkForUpdatesDetailed();if(updateCheck.status==="up-to-date"){const msg=t("Qwen Code {{version}} is up to date!",{version:updateCheck.currentVersion});return{type:"message",messageType:"info",content:msg}}if(updateCheck.status==="error"){return{type:"message",messageType:"error",content:t("Failed to check for updates ({{reason}}). Please check your network or registry configuration.",{reason:describeUpdateCheckFailure(updateCheck.error)})}}if(updateCheck.status==="skipped"){return{type:"message",messageType:"error",content:t("Unable to check for updates: {{reason}}",{reason:updateCheck.reason})}}const info=updateCheck.info;const isAutoUpdateEnabled=settings.merged.general?.enableAutoUpdate!==false;const installInfo=getInstallationInfo2(projectRoot||process.cwd(),isAutoUpdateEnabled);const manualInstructions=__name(()=>{const lines=[info.message,...formatUpdateInstructions(installInfo,info.update.latest).map(line=>t(line))];return{type:"message",messageType:"info",content:lines.join("\n")}},"manualInstructions");if(context.executionMode==="interactive"&&projectRoot){const customSandboxImage=process.env[CUSTOM_SANDBOX_IMAGE_ENV_VAR];if(customSandboxImage){return{type:"message",messageType:"info",content:`${info.message}
|
|
192
192
|
${t("This session uses the custom sandbox image {{image}}. Update that image and restart Qwen Code.",{image:customSandboxImage})}`}}const hostUpdateRelaunch=process.env[HOST_UPDATE_RELAUNCH_ENV_VAR];if(hostUpdateRelaunch==="true"&&isAutoUpdateEnabled){await relaunchForUpdate();return}if(hostUpdateRelaunch!==void 0){return{type:"message",messageType:"info",content:`${info.message}
|
|
193
193
|
${t("Update Qwen Code on the host, then restart the sandbox.")}`}}const canAutoUpdate=installInfo.updateCommand||installInfo.isStandalone&&installInfo.standaloneDir;if(isAutoUpdateEnabled&&canAutoUpdate){await relaunchForUpdate();return}return manualInstructions()}if(isAutoUpdateEnabled&&installInfo.isStandalone&&installInfo.standaloneDir){try{const result=await performStandaloneUpdate(installInfo.standaloneDir,info.update.latest);const message2=result==="done"?t("Update successful! The new version will be used on your next run."):t("Update downloaded. It will be applied after you exit this session.");return{type:"message",messageType:"info",content:`${info.message}
|
|
194
194
|
${t("Downloading update...")}
|