gerege-cli 0.26.6 → 0.26.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bundled/gerege-video/SKILL.md +22 -0
- package/bundled/gerege-video/scripts/video.js +137 -0
- package/chunks/{MaxSizedBox-QCIXIS4P.js → MaxSizedBox-LUINLOQW.js} +1 -1
- package/chunks/{StandaloneSessionPicker-BAFAIRT7.js → StandaloneSessionPicker-B7N4QO5D.js} +1 -1
- package/chunks/{acp-subagent-executor-TPVXURLW.js → acp-subagent-executor-J6H6FKUT.js} +1 -1
- package/chunks/{acpAgent-67UN66PB.js → acpAgent-XG6SM2VU.js} +3 -3
- package/chunks/{advisor-SAXMI4QZ.js → advisor-SZVPQNPA.js} +1 -1
- package/chunks/{agent-KV7BXY6C.js → agent-N7QF7BJS.js} +1 -1
- package/chunks/{agent-headless-FQX3JGG6.js → agent-headless-GLP5GUEX.js} +1 -1
- package/chunks/{agent-host-client-L5EHC4AC.js → agent-host-client-H4VOB3M6.js} +1 -1
- package/chunks/{agent-host-connections-EDBMCVQF.js → agent-host-connections-E4C3OC4M.js} +1 -1
- package/chunks/{anthropicContentGenerator-V7TX2NXP.js → anthropicContentGenerator-5VTWQLT5.js} +1 -1
- package/chunks/{autofix-pr-WP34NYHL.js → autofix-pr-HDYQDJS4.js} +1 -1
- package/chunks/{batch-XFVQ4BLM.js → batch-3CRVN5VJ.js} +1 -1
- package/chunks/{bridge-AE7AFEXB.js → bridge-NZ6WVBLQ.js} +1 -1
- package/chunks/{channel-settings-store-X63P5OVT.js → channel-settings-store-Z7I2JI6M.js} +1 -1
- package/chunks/{chunk-BCI62WSL.js → chunk-236DHGNH.js} +1 -1
- package/chunks/{chunk-JRTOPEM3.js → chunk-2M3ND5WN.js} +1 -1
- package/chunks/{chunk-LBLLWAKK.js → chunk-36A6EXHB.js} +1 -1
- package/chunks/{chunk-H3IR3GIE.js → chunk-3ANIQTDT.js} +1 -1
- package/chunks/{chunk-GSPGIGO5.js → chunk-3QTR2HAE.js} +3 -3
- package/chunks/{chunk-32XHDDIA.js → chunk-3TTHYXT3.js} +1 -1
- package/chunks/{chunk-MTDBCIDA.js → chunk-4CE4GMDL.js} +1 -1
- package/chunks/{chunk-T2YTHAJW.js → chunk-4FVT657Y.js} +1 -1
- package/chunks/{chunk-CGDFZEER.js → chunk-4HSISRRA.js} +1 -1
- package/chunks/{chunk-7453BHJO.js → chunk-4SZUJ5RT.js} +1 -1
- package/chunks/{chunk-B37YY4XU.js → chunk-57D2OB3I.js} +1 -1
- package/chunks/{chunk-WGFX3EL3.js → chunk-5FGBLIXB.js} +1 -1
- package/chunks/{chunk-I6PUY2T3.js → chunk-5HX2QGVR.js} +1 -1
- package/chunks/{chunk-BPFFRPWE.js → chunk-5ZNXAWOG.js} +6 -6
- package/chunks/{chunk-BHIDG6VZ.js → chunk-6CKX56LJ.js} +1 -1
- package/chunks/{chunk-GRAECADD.js → chunk-6NIQFWXP.js} +1 -1
- package/chunks/{chunk-ELDZ4MNL.js → chunk-6PC6MZHL.js} +1 -1
- package/chunks/{chunk-FEP6W4NJ.js → chunk-6VQKGKMJ.js} +1 -1
- package/chunks/{chunk-GBSRWT7J.js → chunk-6ZEMLEK2.js} +1 -1
- package/chunks/{chunk-4NDJKNN6.js → chunk-72VY2PJA.js} +1 -1
- package/chunks/{chunk-BAUMVH4Q.js → chunk-75I3NYBD.js} +1 -1
- package/chunks/{chunk-YH2XRWRF.js → chunk-76L7ZDEK.js} +1 -1
- package/chunks/{chunk-2JGTWRZJ.js → chunk-7XQ5D34E.js} +6 -6
- package/chunks/{chunk-DA6LOBSB.js → chunk-AYX75VXG.js} +1 -1
- package/chunks/{chunk-G6DALGGS.js → chunk-BBDFEMCF.js} +1 -1
- package/chunks/{chunk-VD2GSW64.js → chunk-BOTX7S66.js} +1 -1
- package/chunks/{chunk-M6KB5RVD.js → chunk-CY2QKKZA.js} +1 -1
- package/chunks/{chunk-HTAUIJB4.js → chunk-D5JWQUID.js} +1 -1
- package/chunks/{chunk-P3JEEDQZ.js → chunk-DMIPB7RZ.js} +1 -1
- package/chunks/{chunk-CF6SZJNP.js → chunk-DSKA3P2C.js} +1 -1
- package/chunks/{chunk-LTE4N6L3.js → chunk-DVC65H4X.js} +1 -1
- package/chunks/{chunk-W5Z4BWWA.js → chunk-DVJSDCMX.js} +1 -1
- package/chunks/{chunk-65ME4BOH.js → chunk-E6CPFQX2.js} +1 -1
- package/chunks/{chunk-JEDL4IKF.js → chunk-EIFBGEXJ.js} +1 -1
- package/chunks/{chunk-AYVCT5FF.js → chunk-EQOHDAYU.js} +1 -1
- package/chunks/{chunk-2TAJ5STJ.js → chunk-EZPM4DLR.js} +1 -1
- package/chunks/{chunk-JWNKPINR.js → chunk-F6U6T7QD.js} +1 -1
- package/chunks/{chunk-ET5M5WFN.js → chunk-FCGFBUHS.js} +1 -1
- package/chunks/{chunk-OU7CEG7Q.js → chunk-G2LTZU67.js} +1 -1
- package/chunks/{chunk-2N3NBTYJ.js → chunk-GMJSEK4V.js} +1 -1
- package/chunks/{chunk-NA4ZF2FE.js → chunk-HJMUBVXZ.js} +2 -2
- package/chunks/{chunk-AFO5ER23.js → chunk-HQZTAA2U.js} +1 -1
- package/chunks/{chunk-OK7LBM5G.js → chunk-I63TIQOI.js} +1 -1
- package/chunks/{chunk-OJ4K62S2.js → chunk-I65LBJN7.js} +1 -1
- package/chunks/{chunk-GHIFIXNX.js → chunk-IBDOC27R.js} +1 -1
- package/chunks/{chunk-2LWJGXTW.js → chunk-IKF2HWEV.js} +1 -1
- package/chunks/{chunk-AEZYXPFS.js → chunk-K6NS2HXT.js} +1 -1
- package/chunks/{chunk-T5DKF33F.js → chunk-KTRNYPQP.js} +1 -1
- package/chunks/{chunk-SKGJ26HQ.js → chunk-L3ANU5JZ.js} +1 -1
- package/chunks/{chunk-U3Q72OGV.js → chunk-LKPMADUO.js} +1 -1
- package/chunks/{chunk-MYV7GY3H.js → chunk-M56Y2B6N.js} +1 -1
- package/chunks/{chunk-34HC2AXI.js → chunk-N5KRBAK5.js} +2 -2
- package/chunks/{chunk-EXIFPXMB.js → chunk-NA2WJPOU.js} +1 -1
- package/chunks/{chunk-7RNOS7R4.js → chunk-NGOWLXYK.js} +1 -1
- package/chunks/{chunk-IZ5MWA6E.js → chunk-NL7P73ZP.js} +1 -1
- package/chunks/{chunk-FYBJGRX7.js → chunk-NS3QR7D3.js} +1 -1
- package/chunks/{chunk-XISR37DQ.js → chunk-O5JCCBMQ.js} +1 -1
- package/chunks/{chunk-FKL3V5BO.js → chunk-OOKFFZHF.js} +1 -1
- package/chunks/{chunk-VRKYBH5G.js → chunk-OTYPLLMT.js} +5 -5
- package/chunks/{chunk-W66WWTOP.js → chunk-P7NHWX27.js} +1 -1
- package/chunks/{chunk-AEKEZRIU.js → chunk-PC5QZUKR.js} +1 -1
- package/chunks/{chunk-NEKPQLFY.js → chunk-PS7MQL57.js} +2 -2
- package/chunks/{chunk-TB4AUC2L.js → chunk-PXWHOFAA.js} +1 -1
- package/chunks/{chunk-OOJ2AQT3.js → chunk-Q65LVCDR.js} +1 -1
- package/chunks/{chunk-EFIRES46.js → chunk-QDUDLELH.js} +1 -1
- package/chunks/{chunk-KZNYALFU.js → chunk-QF22ILPV.js} +1 -1
- package/chunks/{chunk-MGATL4OA.js → chunk-QW7MAG2E.js} +1 -1
- package/chunks/{chunk-KJGRCIVY.js → chunk-RXK6XD6F.js} +1 -1
- package/chunks/{chunk-W2RQIZ6B.js → chunk-SVDFCWS7.js} +1 -1
- package/chunks/{chunk-P62S5JGM.js → chunk-TKP3GAUI.js} +1 -1
- package/chunks/{chunk-BQZF3UKI.js → chunk-TUS74LFI.js} +1 -1
- package/chunks/{chunk-JH3V5SPA.js → chunk-U7YGHPSL.js} +1 -1
- package/chunks/{chunk-NONBHCXP.js → chunk-UB37RBSK.js} +1 -1
- package/chunks/{chunk-T53VMDXH.js → chunk-UK5SIRH4.js} +1 -1
- package/chunks/{chunk-3W32X2DH.js → chunk-UTTSBCFR.js} +1 -1
- package/chunks/{chunk-RSLTOIG5.js → chunk-UYV4ZVXY.js} +2 -2
- package/chunks/{chunk-FKZ46GKL.js → chunk-VC3JJL7E.js} +1 -1
- package/chunks/{chunk-SP6CQ3MO.js → chunk-VKWVIWLK.js} +1 -1
- package/chunks/{chunk-N7PWZBXV.js → chunk-VUI6STKU.js} +1 -1
- package/chunks/{chunk-5EXL4TKQ.js → chunk-W3YXE55M.js} +1 -1
- package/chunks/{chunk-NVOI6UDQ.js → chunk-WAIPC47V.js} +1 -1
- package/chunks/{chunk-QDCUR3JB.js → chunk-WMJ6UHDP.js} +1 -1
- package/chunks/{chunk-CBE6ZIHU.js → chunk-WZU2ECUD.js} +1 -1
- package/chunks/{chunk-ZENMAISJ.js → chunk-XAGIZY2Y.js} +1 -1
- package/chunks/{chunk-RXN7DUMP.js → chunk-XGZYVULJ.js} +2 -2
- package/chunks/{chunk-HOG66S6K.js → chunk-XJIHDVPX.js} +1 -1
- package/chunks/{chunk-UKLXKJKL.js → chunk-XVDIHFRH.js} +1 -1
- package/chunks/{chunk-76FSYQTG.js → chunk-YMEW4TTT.js} +1 -1
- package/chunks/{chunk-EYPLBTMI.js → chunk-Z32URWBG.js} +1 -1
- package/chunks/{chunk-CUP2TNJK.js → chunk-Z6HRXHJP.js} +1 -1
- package/chunks/{chunk-MPVQDYPH.js → chunk-ZO4F6ZWR.js} +1 -1
- package/chunks/{codex-subagent-executor-OLMGVPVS.js → codex-subagent-executor-DDKYNU42.js} +1 -1
- package/chunks/{config-utils-OWY5G5Y2.js → config-utils-S7Z2ZZ2E.js} +1 -1
- package/chunks/{contextCommand-IXFUZH65.js → contextCommand-7F4PGV2A.js} +1 -1
- package/chunks/{core-runtime-O4LC4NY3.js → core-runtime-LBH3U7ZF.js} +1 -1
- package/chunks/{create-sub-session-6F7C3TMT.js → create-sub-session-56DS2T6L.js} +1 -1
- package/chunks/{cron-create-2422NBSJ.js → cron-create-PBP3C46Q.js} +1 -1
- package/chunks/{daemon-git-worktree-guard-EWPQA6NO.js → daemon-git-worktree-guard-WJS6FBDA.js} +1 -1
- package/chunks/{daemon-status-provider-FAHOXNFW.js → daemon-status-provider-UPPAEHJ6.js} +1 -1
- package/chunks/{daemon-trust-policy-L3DM6AI5.js → daemon-trust-policy-4Z5HSNUX.js} +1 -1
- package/chunks/{daemon-trust-policy-monitor-HNPY5KJ4.js → daemon-trust-policy-monitor-WFWDOYX3.js} +1 -1
- package/chunks/{deferred-core-runtime-JF42NQJK.js → deferred-core-runtime-MJYNEA4N.js} +1 -1
- package/chunks/{edit-E5LEI2LL.js → edit-U7TGKKK3.js} +1 -1
- package/chunks/{enterPlanMode-3COTUV5V.js → enterPlanMode-27HC5AXN.js} +1 -1
- package/chunks/{environment-XBBIB3VA.js → environment-PHWY6C4P.js} +1 -1
- package/chunks/{errors-LNMQ7TUK.js → errors-F2EYYFI3.js} +1 -1
- package/chunks/{execution-tool-QDDKJD2K.js → execution-tool-O4KJ5SMM.js} +1 -1
- package/chunks/{execution-worker-TXGZRZXE.js → execution-worker-AMFXZ7JD.js} +1 -1
- package/chunks/{exitPlanMode-Z7QEMWPE.js → exitPlanMode-LDYL43PB.js} +1 -1
- package/chunks/{fast-path-M6K2RACY.js → fast-path-HTODEVOR.js} +1 -1
- package/chunks/{glob-N2QT4U7U.js → glob-NKQJJZND.js} +1 -1
- package/chunks/{goal-tools-CUSQD3DG.js → goal-tools-47I455VV.js} +1 -1
- package/chunks/{handleAutoUpdate-QF2YQHF6.js → handleAutoUpdate-MJKTDJUO.js} +1 -1
- package/chunks/{i18n-AGOA6MUI.js → i18n-TCOB4TC5.js} +1 -1
- package/chunks/{initializer-FRKYDUSX.js → initializer-NLYOGZZS.js} +1 -1
- package/chunks/{installationInfo-OKA4WXAS.js → installationInfo-TF2RSJOG.js} +1 -1
- package/chunks/{interactive-mod-session-MWYN5IFK.js → interactive-mod-session-5F7R3KSA.js} +1 -1
- package/chunks/{list-DE7VUIR2.js → list-U2AEVLFP.js} +1 -1
- package/chunks/{llm-N3JGJHYC.js → llm-EV2QTQBU.js} +4 -4
- package/chunks/{llm-content-generator-VMUBA7OJ.js → llm-content-generator-ZXUSPPG2.js} +1 -1
- package/chunks/{loadedSettingsAdapter-5C36OZ7N.js → loadedSettingsAdapter-TLRI22X7.js} +1 -1
- package/chunks/{local-BE624O3A.js → local-ZTSBSKWV.js} +1 -1
- package/chunks/{local-execution-environment-OPGM7Y6L.js → local-execution-environment-F263PSIM.js} +1 -1
- package/chunks/{loggingContentGenerator-2MHAI6JR.js → loggingContentGenerator-2XHSIJQD.js} +1 -1
- package/chunks/{loop-wakeup-BDLATBXH.js → loop-wakeup-5ET3JHUT.js} +1 -1
- package/chunks/{manage-memory-BBCEIIWB.js → manage-memory-MJEQ47H2.js} +1 -1
- package/chunks/{managed-execution-engine-SRFALTCX.js → managed-execution-engine-ODPR5OEH.js} +1 -1
- package/chunks/{managed-local-serve-ICNAS3E6.js → managed-local-serve-S5R4Z5OL.js} +1 -1
- package/chunks/managed-npm-update-BUI5APGY.js +8 -0
- package/chunks/{managed-runtime-attestation-worker-ZRDWKXCI.js → managed-runtime-attestation-worker-BQP4E7LQ.js} +1 -1
- package/chunks/{managed-runtime-bootstrap-6NTGZXQL.js → managed-runtime-bootstrap-SRBDFSKK.js} +1 -1
- package/chunks/{managed-runtime-session-worker-RKQBBFR6.js → managed-runtime-session-worker-UI23BTYJ.js} +1 -1
- package/chunks/{managed-runtime-ssh-worker-FCGV6FSW.js → managed-runtime-ssh-worker-HU4CIJRK.js} +1 -1
- package/chunks/{managed-session-authority-C7IW6TJX.js → managed-session-authority-XSSTLAEY.js} +1 -1
- package/chunks/{mcp-VC4CJPE5.js → mcp-WLHDOKP7.js} +1 -1
- package/chunks/{memory-S6OJA3ZD.js → memory-OUUHPSDD.js} +1 -1
- package/chunks/{model-call-collection-MJZWRQSU.js → model-call-collection-4A2EB76B.js} +1 -1
- package/chunks/{model-configuration-SKU6L3QI.js → model-configuration-4CGUFKEP.js} +1 -1
- package/chunks/{modelConfigUtils-TJCB6NXT.js → modelConfigUtils-HUEERWBA.js} +1 -1
- package/chunks/{monitor-M3PNLCYP.js → monitor-FXL5UNMP.js} +1 -1
- package/chunks/{nonInteractiveCli-MR7JLAWU.js → nonInteractiveCli-W7M2O43W.js} +1 -1
- package/chunks/{nonInteractiveToolExecutor-YKA6JMTY.js → nonInteractiveToolExecutor-EMLI363Q.js} +1 -1
- package/chunks/{notebook-edit-ENTFB5D7.js → notebook-edit-R5RSLSSH.js} +1 -1
- package/chunks/{omni-6YBX4R6K.js → omni-DNZGITTE.js} +1 -1
- package/chunks/{openaiContentGenerator-XRXX33FY.js → openaiContentGenerator-PKOPYMHR.js} +1 -1
- package/chunks/{openaiResponsesContentGenerator-L6ONEHMR.js → openaiResponsesContentGenerator-MHH2MF3V.js} +1 -1
- package/chunks/{pidfile-XR4JF2Z6.js → pidfile-5ZNJWMKG.js} +1 -1
- package/chunks/{processUtils-GQYNJRBJ.js → processUtils-JIHQDASW.js} +1 -1
- package/chunks/{prompt-terminal-ledger-7BM7YDLG.js → prompt-terminal-ledger-L3LZ5SLR.js} +1 -1
- package/chunks/{qwenContentGenerator-QSA32XEL.js → qwenContentGenerator-QCZL7HJJ.js} +1 -1
- package/chunks/{reactive-degrade-TFNBAAPZ.js → reactive-degrade-YUXOUQG4.js} +1 -1
- package/chunks/{read-file-VD7OFO2E.js → read-file-FBNU3AVX.js} +1 -1
- package/chunks/{resumeHistoryUtils-2B4KPI7G.js → resumeHistoryUtils-5FPRTI4A.js} +1 -1
- package/chunks/{review-C365WGCW.js → review-NLFYSNM3.js} +1 -1
- package/chunks/{ripGrep-D7WPMBXR.js → ripGrep-JUAPC5LD.js} +1 -1
- package/chunks/{run-qwen-serve-NZWQHWQA.js → run-qwen-serve-JP64UQ3Y.js} +1 -1
- package/chunks/{runtime-J6SPBSCS.js → runtime-D2QUYM6U.js} +1 -1
- package/chunks/{sandboxConfig-QS2XBPZG.js → sandboxConfig-7VZJQV6H.js} +1 -1
- package/chunks/{scheduled-tasks-YNNIOOPM.js → scheduled-tasks-PC6EH75E.js} +1 -1
- package/chunks/{scheduler-KCMSPHON.js → scheduler-RUV2FNDR.js} +1 -1
- package/chunks/{search-memory-EUBJ7IAV.js → search-memory-YJTJ7BRU.js} +1 -1
- package/chunks/{send-message-CWWZUPSK.js → send-message-EEEFFTHX.js} +1 -1
- package/chunks/{serve-4CB4BWJ5.js → serve-KMIZDYON.js} +1 -1
- package/chunks/{server-JNANUIGC.js → server-DUPK3V7B.js} +3 -3
- package/chunks/{session-3LQLXPUA.js → session-CW5YMFMP.js} +1 -1
- package/chunks/{session-attachments-root-BWIVWFHJ.js → session-attachments-root-5H5GFHLI.js} +1 -1
- package/chunks/{session-execution-engine-selector-5OLRX57L.js → session-execution-engine-selector-MVXM2HZW.js} +1 -1
- package/chunks/{session-pr-refresh-RLF3EXS3.js → session-pr-refresh-4UPONX4L.js} +1 -1
- package/chunks/{sessionService-U7ACD2HP.js → sessionService-GGCYISSL.js} +1 -1
- package/chunks/{settings-FTGWYTUH.js → settings-AASJCESS.js} +1 -1
- package/chunks/{shell-E4RENYQC.js → shell-V4WWLW3Q.js} +1 -1
- package/chunks/{skill-OLNPHRWB.js → skill-NDEBB7VX.js} +1 -1
- package/chunks/{skill-settings-R2BV2GEK.js → skill-settings-YAI3GYU5.js} +1 -1
- package/chunks/{spawnChannel-LOPAR5T2.js → spawnChannel-6JKVJAXZ.js} +1 -1
- package/chunks/{standalone-update-IGDX2RGN.js → standalone-update-NJP5OCKJ.js} +1 -1
- package/chunks/{start-opentui-ui-33QLBNRC.js → start-opentui-ui-M4B4SXRM.js} +1 -1
- package/chunks/{startInteractiveUI-RQKHD7MM.js → startInteractiveUI-O4JUDEAU.js} +1 -1
- package/chunks/{team-create-HAVKHNU5.js → team-create-NLJ7QBLD.js} +1 -1
- package/chunks/{team-plan-approval-7MCQX67C.js → team-plan-approval-XKYPVWNG.js} +1 -1
- package/chunks/{terminal-image-renderer-XT5JVEO6.js → terminal-image-renderer-47TD747D.js} +1 -1
- package/chunks/{theme-manager-DR5EYGLT.js → theme-manager-AANEBPLJ.js} +1 -1
- package/chunks/{tool-call-LZHZ5RVH.js → tool-call-ETH3LS7Y.js} +1 -1
- package/chunks/{tool-result-media-XCXCF4YC.js → tool-result-media-EFOEPAF2.js} +1 -1
- package/chunks/{tool-search-K6S3ON7M.js → tool-search-J3CF5PRN.js} +1 -1
- package/chunks/{total-session-admission-LGSS2VWS.js → total-session-admission-3DC52PLQ.js} +1 -1
- package/chunks/{trustedFolders-IIR2UZRL.js → trustedFolders-4KPWZZKB.js} +1 -1
- package/chunks/{update-relaunch-WVIFX5CN.js → update-relaunch-A67BS7QS.js} +1 -1
- package/chunks/{updateCheck-CMEWLLZJ.js → updateCheck-X623JRSY.js} +1 -1
- package/chunks/{upload-config-TCCFCNCD.js → upload-config-X2CR3F26.js} +1 -1
- package/chunks/{useAutoAcceptIndicator-5RTTH3OW.js → useAutoAcceptIndicator-INIOQGJH.js} +1 -1
- package/chunks/{validateNonInterActiveAuth-AO336KDX.js → validateNonInterActiveAuth-XJ2U5CLB.js} +1 -1
- package/chunks/{version-JYWKKMNP.js → version-MFHRMM7W.js} +1 -1
- package/chunks/{web-fetch-HWTAWXFM.js → web-fetch-3GEJ62DH.js} +1 -1
- package/chunks/{web-search-HAI5LW3G.js → web-search-WJZO3Q3A.js} +1 -1
- package/chunks/{workflow-BZ2YFGF6.js → workflow-ML7ITCMH.js} +1 -1
- package/chunks/{workflow-ancestor-trust-26TFXFPO.js → workflow-ancestor-trust-M3VFMS73.js} +1 -1
- package/chunks/{workspace-agents-DLI4JQJZ.js → workspace-agents-YFZMV7EF.js} +1 -1
- package/chunks/{workspace-providers-status-64C7DJZU.js → workspace-providers-status-3COKLBCI.js} +1 -1
- package/chunks/{workspace-recovery-worker-IFRT3KKP.js → workspace-recovery-worker-QURA3WFZ.js} +1 -1
- package/chunks/{workspace-registration-store-MYKJM2SK.js → workspace-registration-store-F3AGIOBW.js} +1 -1
- package/chunks/{workspace-registry-GZJRONAY.js → workspace-registry-QUBL3RW6.js} +1 -1
- package/chunks/{workspace-runtime-coordinator-44KW6HSN.js → workspace-runtime-coordinator-22TSDHXX.js} +1 -1
- package/chunks/{workspace-service-YHTSZYYD.js → workspace-service-UUENTHNO.js} +1 -1
- package/chunks/{workspace-skills-status-NEB62X24.js → workspace-skills-status-NNQQBBCJ.js} +1 -1
- package/chunks/{workspace-trust-reconciler-HZLOOZWM.js → workspace-trust-reconciler-3CMMNCGG.js} +1 -1
- package/chunks/{write-file-HD5LHXGL.js → write-file-DEAFIK4C.js} +1 -1
- package/chunks/{zoom-image-W4BMRC5T.js → zoom-image-YYO22PQG.js} +1 -1
- package/cli-entry.js +2 -3
- package/cli.js +2 -2
- package/execution-worker.js +1 -1
- package/export-transcript-document.js +1 -1
- package/gerege.mjs +11 -0
- package/package.json +2 -12
- package/chunks/managed-npm-update-CTL6LH5Z.js +0 -8
- package/opentui-assets/@opentui/core/assets/javascript/highlights.scm +0 -205
- package/opentui-assets/@opentui/core/assets/javascript/tree-sitter-javascript.wasm +0 -0
- package/opentui-assets/@opentui/core/assets/markdown/highlights.scm +0 -150
- package/opentui-assets/@opentui/core/assets/markdown/injections.scm +0 -27
- package/opentui-assets/@opentui/core/assets/markdown/tree-sitter-markdown.wasm +0 -0
- package/opentui-assets/@opentui/core/assets/markdown_inline/highlights.scm +0 -115
- package/opentui-assets/@opentui/core/assets/markdown_inline/tree-sitter-markdown_inline.wasm +0 -0
- package/opentui-assets/@opentui/core/assets/typescript/highlights.scm +0 -604
- package/opentui-assets/@opentui/core/assets/typescript/tree-sitter-typescript.wasm +0 -0
- package/opentui-assets/@opentui/core/assets/zig/highlights.scm +0 -284
- package/opentui-assets/@opentui/core/assets/zig/tree-sitter-zig.wasm +0 -0
- package/opentui-assets/@opentui/core/parser.worker.js +0 -4566
- package/opentui-assets/@opentui/core-darwin-arm64/libopentui.dylib +0 -0
- package/opentui-assets/@opentui/core-darwin-x64/libopentui.dylib +0 -0
- package/opentui-assets/@opentui/core-linux-arm64/libopentui.so +0 -0
- package/opentui-assets/@opentui/core-linux-x64/libopentui.so +0 -0
- package/opentui-assets/web-tree-sitter/tree-sitter.wasm +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{MAX_WORKSPACE_PATH_LENGTH,canonicalizeWorkspace}from"./chunk-L5UULTGF.js";import{getGlobalQwenDirLite}from"./chunk-PTHIQ7ZN.js";import{isWithinRoot}from"./chunk-IDXJIDME.js";import{isUnverifiableIdentityError,openNoFollow}from"./chunk-QXQGUM3Y.js";import{require_proper_lockfile}from"./chunk-YIW3H46P.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import{createHash}from"node:crypto";import*as fs from"node:fs/promises";import*as os from"node:os";import*as path from"node:path";init_esbuild_shims();var MAX_REGISTERED_WORKSPACES=256;var MAX_CONFIGURED_REGISTERED_WORKSPACES=256;var QWEN_SERVE_MAX_WORKSPACES_ENV="QWEN_SERVE_MAX_WORKSPACES";function resolveMaxRegisteredWorkspaces(configured,env){const raw=env[QWEN_SERVE_MAX_WORKSPACES_ENV];const value=configured??(raw===void 0?MAX_REGISTERED_WORKSPACES:/^\d+$/.test(raw.trim())?Number(raw.trim()):Number.NaN);if(!Number.isSafeInteger(value)||value<1||value>MAX_CONFIGURED_REGISTERED_WORKSPACES){const source=configured===void 0?`${QWEN_SERVE_MAX_WORKSPACES_ENV}=${JSON.stringify(raw)}`:`maxRegisteredWorkspaces option ${String(configured)}`;throw new TypeError(`Invalid ${source}: must be an integer from 1 to ${MAX_CONFIGURED_REGISTERED_WORKSPACES}.`)}return value}__name(resolveMaxRegisteredWorkspaces,"resolveMaxRegisteredWorkspaces");var DuplicateWorkspaceInputError=class extends Error{static{__name(this,"DuplicateWorkspaceInputError")}constructor(workspace){super(`Duplicate --workspace value resolves to ${JSON.stringify(workspace)}. Pass distinct --workspace values.`);this.name="DuplicateWorkspaceInputError"}};var NestedWorkspaceInputError=class extends Error{static{__name(this,"NestedWorkspaceInputError")}constructor(parent,child){super(`Nested --workspace values are not supported yet: ${JSON.stringify(child)} is inside ${JSON.stringify(parent)}. Pass non-nested --workspace values.`);this.name="NestedWorkspaceInputError"}};var MissingWorkspaceInputError=class extends Error{static{__name(this,"MissingWorkspaceInputError")}constructor(){super("--workspace requires a value.");this.name="MissingWorkspaceInputError"}};function normalizeWorkspaceInputs(workspace){if(Array.isArray(workspace)){if(workspace.length===0){throw new MissingWorkspaceInputError}return workspace.map(value=>String(value))}if(workspace===void 0)return[process.cwd()];return[String(workspace)]}__name(normalizeWorkspaceInputs,"normalizeWorkspaceInputs");function isNestedWorkspace(parent,child){return parent!==child&&isWithinRoot(child,parent)}__name(isNestedWorkspace,"isNestedWorkspace");function rejectDuplicateOrNestedWorkspaceInputs(workspaces){if(workspaces.length<=1)return;let canonicalWorkspaces;try{canonicalWorkspaces=workspaces.map(workspace=>canonicalizeWorkspace(workspace))}catch{return}const seen=new Set;for(const workspace of canonicalWorkspaces){if(seen.has(workspace)){throw new DuplicateWorkspaceInputError(workspace)}seen.add(workspace)}for(let i=0;i<canonicalWorkspaces.length;i++){for(let j=i+1;j<canonicalWorkspaces.length;j++){const first=canonicalWorkspaces[i];const second=canonicalWorkspaces[j];if(isNestedWorkspace(first,second)){throw new NestedWorkspaceInputError(first,second)}if(isNestedWorkspace(second,first)){throw new NestedWorkspaceInputError(second,first)}}}}__name(rejectDuplicateOrNestedWorkspaceInputs,"rejectDuplicateOrNestedWorkspaceInputs");function resolveWorkspaceInputs(workspace){const workspaces=normalizeWorkspaceInputs(workspace);rejectDuplicateOrNestedWorkspaceInputs(workspaces);return workspaces}__name(resolveWorkspaceInputs,"resolveWorkspaceInputs");var SCHEMA_VERSION=1;var MAX_SECONDARY_WORKSPACES=MAX_CONFIGURED_REGISTERED_WORKSPACES-1;var MAX_STORE_BYTES=8*1024*1024;var MAX_WORKSPACE_DISPLAY_NAME_LENGTH=256;var LOCK_OPTIONS={realpath:false,stale:1e4,update:2e3,retries:{retries:120,minTimeout:10,maxTimeout:100,factor:1.2,randomize:true}};var WorkspaceDisplayNameValidationError=class extends Error{static{__name(this,"WorkspaceDisplayNameValidationError")}constructor(message){super(message);this.name="WorkspaceDisplayNameValidationError"}};function containsDisplayNameControlCharacter(value){for(const character of value){const codePoint=character.codePointAt(0);if(codePoint<=31||codePoint===127)return true}return false}__name(containsDisplayNameControlCharacter,"containsDisplayNameControlCharacter");function normalizeWorkspaceDisplayName(value){if(typeof value!=="string"){throw new WorkspaceDisplayNameValidationError("Workspace display name must be a string")}const trimmed=value.trim();if(trimmed.length>MAX_WORKSPACE_DISPLAY_NAME_LENGTH){throw new WorkspaceDisplayNameValidationError(`Workspace display name exceeds ${MAX_WORKSPACE_DISPLAY_NAME_LENGTH} characters`)}if(containsDisplayNameControlCharacter(trimmed)){throw new WorkspaceDisplayNameValidationError("Workspace display name contains control characters")}return trimmed.length===0?void 0:trimmed}__name(normalizeWorkspaceDisplayName,"normalizeWorkspaceDisplayName");var WorkspaceRegistrationStoreError=class extends Error{static{__name(this,"WorkspaceRegistrationStoreError")}constructor(message){super(message);this.name="WorkspaceRegistrationStoreError"}};var WorkspaceRegistrationStoreLimitError=class extends WorkspaceRegistrationStoreError{static{__name(this,"WorkspaceRegistrationStoreLimitError")}};var WorkspaceRegistrationStoreTooLargeError=class extends WorkspaceRegistrationStoreError{static{__name(this,"WorkspaceRegistrationStoreTooLargeError")}};var WorkspaceRegistrationStoreCommittedError=class extends WorkspaceRegistrationStoreError{static{__name(this,"WorkspaceRegistrationStoreCommittedError")}};function normalizedScopePath(primaryWorkspace){return os.platform()==="win32"?primaryWorkspace.toLowerCase():primaryWorkspace}__name(normalizedScopePath,"normalizedScopePath");function workspaceRegistrationScopeHash(primaryWorkspace){return createHash("sha256").update(normalizedScopePath(primaryWorkspace)).digest("hex")}__name(workspaceRegistrationScopeHash,"workspaceRegistrationScopeHash");function workspaceRegistrationId(workspace){return createHash("sha256").update(workspace).digest("hex").slice(0,16)}__name(workspaceRegistrationId,"workspaceRegistrationId");function getWorkspaceRegistrationStorePath(primaryWorkspace,qwenHome=getGlobalQwenDirLite()){return path.join(qwenHome,"daemon","workspaces",`${workspaceRegistrationScopeHash(primaryWorkspace)}.json`)}__name(getWorkspaceRegistrationStorePath,"getWorkspaceRegistrationStorePath");function emptySnapshot(primaryWorkspace){return{schemaVersion:SCHEMA_VERSION,primaryWorkspace,workspaces:[]}}__name(emptySnapshot,"emptySnapshot");function validateWorkspacePath(value,label){if(typeof value!=="string"||!path.isAbsolute(value)){throw new WorkspaceRegistrationStoreError(`${label} must be an absolute path`)}if(value.includes("\0")||value.length>MAX_WORKSPACE_PATH_LENGTH){throw new WorkspaceRegistrationStoreError(`${label} is invalid`)}return value}__name(validateWorkspacePath,"validateWorkspacePath");function validateStoredDisplayName(value,label){let displayName;try{displayName=normalizeWorkspaceDisplayName(value)}catch(err){throw new WorkspaceRegistrationStoreError(`${label} is invalid: ${err instanceof Error?err.message:String(err)}`)}if(displayName===void 0){throw new WorkspaceRegistrationStoreError(`${label} must not be empty`)}return displayName}__name(validateStoredDisplayName,"validateStoredDisplayName");function setSnapshotDisplayName(snapshot,registrationId,displayName){if(displayName===void 0){if(!snapshot.displayNames||!Object.hasOwn(snapshot.displayNames,registrationId)){return false}delete snapshot.displayNames[registrationId];if(Object.keys(snapshot.displayNames).length===0){delete snapshot.displayNames}return true}if(snapshot.displayNames?.[registrationId]===displayName)return false;snapshot.displayNames??={};snapshot.displayNames[registrationId]=displayName;return true}__name(setSnapshotDisplayName,"setSnapshotDisplayName");function parseSnapshot(raw,primaryWorkspace){let value;try{value=JSON.parse(raw)}catch{throw new WorkspaceRegistrationStoreError("Workspace registration store contains malformed JSON")}if(typeof value!=="object"||value===null||Array.isArray(value)){throw new WorkspaceRegistrationStoreError("Workspace registration store root must be an object")}const record=value;if(record["schemaVersion"]!==SCHEMA_VERSION){throw new WorkspaceRegistrationStoreError(`Unsupported workspace registration schema ${String(record["schemaVersion"])}`)}const storedPrimary=validateWorkspacePath(record["primaryWorkspace"],"primaryWorkspace");if(normalizedScopePath(storedPrimary)!==normalizedScopePath(primaryWorkspace)){throw new WorkspaceRegistrationStoreError("Workspace registration store primary does not match this daemon")}if(!Array.isArray(record["workspaces"])){throw new WorkspaceRegistrationStoreError("Workspace registration store workspaces must be an array")}if(record["workspaces"].length>MAX_SECONDARY_WORKSPACES){throw new WorkspaceRegistrationStoreError(`Workspace registration store exceeds ${MAX_SECONDARY_WORKSPACES} entries`)}const seen=new Set;const workspaces=record["workspaces"].map((entry,index)=>{const workspace=validateWorkspacePath(entry,`workspaces[${index}]`);const normalizedWorkspace=normalizedScopePath(workspace);if(normalizedWorkspace===normalizedScopePath(primaryWorkspace)){throw new WorkspaceRegistrationStoreError("Primary workspace cannot be stored as a secondary registration")}if(seen.has(normalizedWorkspace)){throw new WorkspaceRegistrationStoreError("Workspace registration store contains duplicate paths")}seen.add(normalizedWorkspace);return workspace});const rawDisplayNames=record["displayNames"];let displayNames;if(rawDisplayNames!==void 0){if(typeof rawDisplayNames!=="object"||rawDisplayNames===null||Array.isArray(rawDisplayNames)){throw new WorkspaceRegistrationStoreError("Workspace registration store displayNames must be an object")}const registrationIds=new Set(workspaces.map(workspaceRegistrationId));for(const[registrationId,value2]of Object.entries(rawDisplayNames)){if(!registrationIds.has(registrationId)){throw new WorkspaceRegistrationStoreError(`Workspace registration store displayNames contains unknown registration id ${JSON.stringify(registrationId)}`)}displayNames??={};displayNames[registrationId]=validateStoredDisplayName(value2,`displayNames[${JSON.stringify(registrationId)}]`)}}return{schemaVersion:SCHEMA_VERSION,primaryWorkspace,workspaces,...displayNames?{displayNames}:{}}}__name(parseSnapshot,"parseSnapshot");var updateChains=new Map;async function withInProcessLock(filePath,work){const previous=updateChains.get(filePath)??Promise.resolve();const next=previous.then(work,work);const settled=next.catch(()=>void 0).finally(()=>{if(updateChains.get(filePath)===settled)updateChains.delete(filePath)});updateChains.set(filePath,settled);return next}__name(withInProcessLock,"withInProcessLock");function compromisedLockError(){return new WorkspaceRegistrationStoreError("Workspace registration store lock was compromised")}__name(compromisedLockError,"compromisedLockError");async function acquireFileLock(filePath){await fs.mkdir(path.dirname(filePath),{recursive:true,mode:448});let compromised=false;const release=await import_proper_lockfile.default.lock(filePath,{...LOCK_OPTIONS,onCompromised:__name(()=>{compromised=true},"onCompromised")});return{assertOwned:__name(()=>{if(compromised)throw compromisedLockError()},"assertOwned"),release:__name(async()=>{try{await release()}catch(err){if(!compromised)throw err}if(compromised)throw compromisedLockError()},"release")}}__name(acquireFileLock,"acquireFileLock");var WorkspaceRegistrationStore=class{constructor(primaryWorkspace,qwenHome){this.primaryWorkspace=primaryWorkspace;validateWorkspacePath(primaryWorkspace,"primaryWorkspace");this.filePath=getWorkspaceRegistrationStorePath(primaryWorkspace,qwenHome)}static{__name(this,"WorkspaceRegistrationStore")}filePath;async read(){try{const entry=await fs.lstat(this.filePath);if(entry.isSymbolicLink()||!entry.isFile()){throw new WorkspaceRegistrationStoreError("Workspace registration store must be a regular file")}}catch(err){if(err.code==="ENOENT"){return emptySnapshot(this.primaryWorkspace)}throw err}let file;try{file=await openNoFollow(this.filePath)}catch(err){if(err.code==="ENOENT"){return emptySnapshot(this.primaryWorkspace)}if(isUnverifiableIdentityError(err)){throw new WorkspaceRegistrationStoreError("Workspace registration store identity could not be verified")}if(err.code==="ELOOP"){throw new WorkspaceRegistrationStoreError("Workspace registration store must be a regular file")}throw err}try{const stat=await file.stat();if(!stat.isFile()){throw new WorkspaceRegistrationStoreError("Workspace registration store must be a regular file")}if(stat.size>MAX_STORE_BYTES){throw new WorkspaceRegistrationStoreTooLargeError(`Workspace registration store exceeds ${MAX_STORE_BYTES} bytes`)}let buffer=Buffer.alloc(Math.max(1,Math.min(stat.size+1,MAX_STORE_BYTES+1)));let totalBytesRead=0;for(;;){if(totalBytesRead===buffer.length){if(totalBytesRead>MAX_STORE_BYTES)break;const grown=Buffer.alloc(Math.min(MAX_STORE_BYTES+1,Math.max(buffer.length*2,totalBytesRead+1)));buffer.copy(grown,0,0,totalBytesRead);buffer=grown}const{bytesRead}=await file.read(buffer,totalBytesRead,buffer.length-totalBytesRead,totalBytesRead);if(bytesRead===0)break;totalBytesRead+=bytesRead}if(totalBytesRead>MAX_STORE_BYTES){throw new WorkspaceRegistrationStoreTooLargeError(`Workspace registration store exceeds ${MAX_STORE_BYTES} bytes`)}return parseSnapshot(buffer.toString("utf8",0,totalBytesRead),this.primaryWorkspace)}finally{await file.close()}}async add(workspace,displayName,maxRegisteredWorkspaces=MAX_REGISTERED_WORKSPACES){const maxSecondaries=resolveMaxRegisteredWorkspaces(maxRegisteredWorkspaces,{})-1;validateWorkspacePath(workspace,"workspace");const normalizedDisplayName=displayName===void 0?void 0:normalizeWorkspaceDisplayName(displayName);if(normalizedScopePath(workspace)===normalizedScopePath(this.primaryWorkspace)){throw new WorkspaceRegistrationStoreError("Primary workspace cannot be stored as a secondary registration")}return this.update(snapshot=>{const normalizedWorkspace=normalizedScopePath(workspace);if(snapshot.workspaces.some(stored=>normalizedScopePath(stored)===normalizedWorkspace)){return false}if(snapshot.workspaces.length>=maxSecondaries){throw new WorkspaceRegistrationStoreLimitError(`Workspace registration store limit of ${maxSecondaries} reached`)}snapshot.workspaces.push(workspace);if(normalizedDisplayName!==void 0){snapshot.displayNames??={};snapshot.displayNames[workspaceRegistrationId(workspace)]=normalizedDisplayName}return true})}async removeById(id){return await this.removeByIds([id])>0}async setDisplayNameByIds(ids,displayName){const normalizedDisplayName=displayName===void 0?void 0:normalizeWorkspaceDisplayName(displayName);const requested=new Set(ids);if(requested.size===0)return 0;let matched=0;await this.update(snapshot=>{let changed=false;for(const workspace of snapshot.workspaces){const registrationId=workspaceRegistrationId(workspace);if(!requested.has(registrationId))continue;matched++;changed=setSnapshotDisplayName(snapshot,registrationId,normalizedDisplayName)||changed}return changed});return matched}async removeByIds(ids){const requested=new Set(ids);if(requested.size===0)return 0;let removed=0;await this.update(snapshot=>{const removedIds=new Set;const retained=snapshot.workspaces.filter(workspace=>{const registrationId=workspaceRegistrationId(workspace);if(!requested.has(registrationId))return true;removed++;removedIds.add(registrationId);return false});if(removed===0)return false;snapshot.workspaces.splice(0,snapshot.workspaces.length,...retained);for(const registrationId of removedIds){setSnapshotDisplayName(snapshot,registrationId,void 0)}return true});return removed}async update(mutate){const{atomicWriteFile}=await import("./deferred-core-runtime-JF42NQJK.js");return withInProcessLock(this.filePath,async()=>{const lock=await acquireFileLock(this.filePath);let committed=false;let changed=false;let workError;try{const snapshot=await this.read();lock.assertOwned();changed=mutate(snapshot);if(changed){const serialized=`${JSON.stringify(snapshot,null,2)}
|
|
3
|
+
import{MAX_WORKSPACE_PATH_LENGTH,canonicalizeWorkspace}from"./chunk-L5UULTGF.js";import{getGlobalQwenDirLite}from"./chunk-PTHIQ7ZN.js";import{isWithinRoot}from"./chunk-IDXJIDME.js";import{isUnverifiableIdentityError,openNoFollow}from"./chunk-QXQGUM3Y.js";import{require_proper_lockfile}from"./chunk-YIW3H46P.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import{createHash}from"node:crypto";import*as fs from"node:fs/promises";import*as os from"node:os";import*as path from"node:path";init_esbuild_shims();var MAX_REGISTERED_WORKSPACES=256;var MAX_CONFIGURED_REGISTERED_WORKSPACES=256;var QWEN_SERVE_MAX_WORKSPACES_ENV="QWEN_SERVE_MAX_WORKSPACES";function resolveMaxRegisteredWorkspaces(configured,env){const raw=env[QWEN_SERVE_MAX_WORKSPACES_ENV];const value=configured??(raw===void 0?MAX_REGISTERED_WORKSPACES:/^\d+$/.test(raw.trim())?Number(raw.trim()):Number.NaN);if(!Number.isSafeInteger(value)||value<1||value>MAX_CONFIGURED_REGISTERED_WORKSPACES){const source=configured===void 0?`${QWEN_SERVE_MAX_WORKSPACES_ENV}=${JSON.stringify(raw)}`:`maxRegisteredWorkspaces option ${String(configured)}`;throw new TypeError(`Invalid ${source}: must be an integer from 1 to ${MAX_CONFIGURED_REGISTERED_WORKSPACES}.`)}return value}__name(resolveMaxRegisteredWorkspaces,"resolveMaxRegisteredWorkspaces");var DuplicateWorkspaceInputError=class extends Error{static{__name(this,"DuplicateWorkspaceInputError")}constructor(workspace){super(`Duplicate --workspace value resolves to ${JSON.stringify(workspace)}. Pass distinct --workspace values.`);this.name="DuplicateWorkspaceInputError"}};var NestedWorkspaceInputError=class extends Error{static{__name(this,"NestedWorkspaceInputError")}constructor(parent,child){super(`Nested --workspace values are not supported yet: ${JSON.stringify(child)} is inside ${JSON.stringify(parent)}. Pass non-nested --workspace values.`);this.name="NestedWorkspaceInputError"}};var MissingWorkspaceInputError=class extends Error{static{__name(this,"MissingWorkspaceInputError")}constructor(){super("--workspace requires a value.");this.name="MissingWorkspaceInputError"}};function normalizeWorkspaceInputs(workspace){if(Array.isArray(workspace)){if(workspace.length===0){throw new MissingWorkspaceInputError}return workspace.map(value=>String(value))}if(workspace===void 0)return[process.cwd()];return[String(workspace)]}__name(normalizeWorkspaceInputs,"normalizeWorkspaceInputs");function isNestedWorkspace(parent,child){return parent!==child&&isWithinRoot(child,parent)}__name(isNestedWorkspace,"isNestedWorkspace");function rejectDuplicateOrNestedWorkspaceInputs(workspaces){if(workspaces.length<=1)return;let canonicalWorkspaces;try{canonicalWorkspaces=workspaces.map(workspace=>canonicalizeWorkspace(workspace))}catch{return}const seen=new Set;for(const workspace of canonicalWorkspaces){if(seen.has(workspace)){throw new DuplicateWorkspaceInputError(workspace)}seen.add(workspace)}for(let i=0;i<canonicalWorkspaces.length;i++){for(let j=i+1;j<canonicalWorkspaces.length;j++){const first=canonicalWorkspaces[i];const second=canonicalWorkspaces[j];if(isNestedWorkspace(first,second)){throw new NestedWorkspaceInputError(first,second)}if(isNestedWorkspace(second,first)){throw new NestedWorkspaceInputError(second,first)}}}}__name(rejectDuplicateOrNestedWorkspaceInputs,"rejectDuplicateOrNestedWorkspaceInputs");function resolveWorkspaceInputs(workspace){const workspaces=normalizeWorkspaceInputs(workspace);rejectDuplicateOrNestedWorkspaceInputs(workspaces);return workspaces}__name(resolveWorkspaceInputs,"resolveWorkspaceInputs");var SCHEMA_VERSION=1;var MAX_SECONDARY_WORKSPACES=MAX_CONFIGURED_REGISTERED_WORKSPACES-1;var MAX_STORE_BYTES=8*1024*1024;var MAX_WORKSPACE_DISPLAY_NAME_LENGTH=256;var LOCK_OPTIONS={realpath:false,stale:1e4,update:2e3,retries:{retries:120,minTimeout:10,maxTimeout:100,factor:1.2,randomize:true}};var WorkspaceDisplayNameValidationError=class extends Error{static{__name(this,"WorkspaceDisplayNameValidationError")}constructor(message){super(message);this.name="WorkspaceDisplayNameValidationError"}};function containsDisplayNameControlCharacter(value){for(const character of value){const codePoint=character.codePointAt(0);if(codePoint<=31||codePoint===127)return true}return false}__name(containsDisplayNameControlCharacter,"containsDisplayNameControlCharacter");function normalizeWorkspaceDisplayName(value){if(typeof value!=="string"){throw new WorkspaceDisplayNameValidationError("Workspace display name must be a string")}const trimmed=value.trim();if(trimmed.length>MAX_WORKSPACE_DISPLAY_NAME_LENGTH){throw new WorkspaceDisplayNameValidationError(`Workspace display name exceeds ${MAX_WORKSPACE_DISPLAY_NAME_LENGTH} characters`)}if(containsDisplayNameControlCharacter(trimmed)){throw new WorkspaceDisplayNameValidationError("Workspace display name contains control characters")}return trimmed.length===0?void 0:trimmed}__name(normalizeWorkspaceDisplayName,"normalizeWorkspaceDisplayName");var WorkspaceRegistrationStoreError=class extends Error{static{__name(this,"WorkspaceRegistrationStoreError")}constructor(message){super(message);this.name="WorkspaceRegistrationStoreError"}};var WorkspaceRegistrationStoreLimitError=class extends WorkspaceRegistrationStoreError{static{__name(this,"WorkspaceRegistrationStoreLimitError")}};var WorkspaceRegistrationStoreTooLargeError=class extends WorkspaceRegistrationStoreError{static{__name(this,"WorkspaceRegistrationStoreTooLargeError")}};var WorkspaceRegistrationStoreCommittedError=class extends WorkspaceRegistrationStoreError{static{__name(this,"WorkspaceRegistrationStoreCommittedError")}};function normalizedScopePath(primaryWorkspace){return os.platform()==="win32"?primaryWorkspace.toLowerCase():primaryWorkspace}__name(normalizedScopePath,"normalizedScopePath");function workspaceRegistrationScopeHash(primaryWorkspace){return createHash("sha256").update(normalizedScopePath(primaryWorkspace)).digest("hex")}__name(workspaceRegistrationScopeHash,"workspaceRegistrationScopeHash");function workspaceRegistrationId(workspace){return createHash("sha256").update(workspace).digest("hex").slice(0,16)}__name(workspaceRegistrationId,"workspaceRegistrationId");function getWorkspaceRegistrationStorePath(primaryWorkspace,qwenHome=getGlobalQwenDirLite()){return path.join(qwenHome,"daemon","workspaces",`${workspaceRegistrationScopeHash(primaryWorkspace)}.json`)}__name(getWorkspaceRegistrationStorePath,"getWorkspaceRegistrationStorePath");function emptySnapshot(primaryWorkspace){return{schemaVersion:SCHEMA_VERSION,primaryWorkspace,workspaces:[]}}__name(emptySnapshot,"emptySnapshot");function validateWorkspacePath(value,label){if(typeof value!=="string"||!path.isAbsolute(value)){throw new WorkspaceRegistrationStoreError(`${label} must be an absolute path`)}if(value.includes("\0")||value.length>MAX_WORKSPACE_PATH_LENGTH){throw new WorkspaceRegistrationStoreError(`${label} is invalid`)}return value}__name(validateWorkspacePath,"validateWorkspacePath");function validateStoredDisplayName(value,label){let displayName;try{displayName=normalizeWorkspaceDisplayName(value)}catch(err){throw new WorkspaceRegistrationStoreError(`${label} is invalid: ${err instanceof Error?err.message:String(err)}`)}if(displayName===void 0){throw new WorkspaceRegistrationStoreError(`${label} must not be empty`)}return displayName}__name(validateStoredDisplayName,"validateStoredDisplayName");function setSnapshotDisplayName(snapshot,registrationId,displayName){if(displayName===void 0){if(!snapshot.displayNames||!Object.hasOwn(snapshot.displayNames,registrationId)){return false}delete snapshot.displayNames[registrationId];if(Object.keys(snapshot.displayNames).length===0){delete snapshot.displayNames}return true}if(snapshot.displayNames?.[registrationId]===displayName)return false;snapshot.displayNames??={};snapshot.displayNames[registrationId]=displayName;return true}__name(setSnapshotDisplayName,"setSnapshotDisplayName");function parseSnapshot(raw,primaryWorkspace){let value;try{value=JSON.parse(raw)}catch{throw new WorkspaceRegistrationStoreError("Workspace registration store contains malformed JSON")}if(typeof value!=="object"||value===null||Array.isArray(value)){throw new WorkspaceRegistrationStoreError("Workspace registration store root must be an object")}const record=value;if(record["schemaVersion"]!==SCHEMA_VERSION){throw new WorkspaceRegistrationStoreError(`Unsupported workspace registration schema ${String(record["schemaVersion"])}`)}const storedPrimary=validateWorkspacePath(record["primaryWorkspace"],"primaryWorkspace");if(normalizedScopePath(storedPrimary)!==normalizedScopePath(primaryWorkspace)){throw new WorkspaceRegistrationStoreError("Workspace registration store primary does not match this daemon")}if(!Array.isArray(record["workspaces"])){throw new WorkspaceRegistrationStoreError("Workspace registration store workspaces must be an array")}if(record["workspaces"].length>MAX_SECONDARY_WORKSPACES){throw new WorkspaceRegistrationStoreError(`Workspace registration store exceeds ${MAX_SECONDARY_WORKSPACES} entries`)}const seen=new Set;const workspaces=record["workspaces"].map((entry,index)=>{const workspace=validateWorkspacePath(entry,`workspaces[${index}]`);const normalizedWorkspace=normalizedScopePath(workspace);if(normalizedWorkspace===normalizedScopePath(primaryWorkspace)){throw new WorkspaceRegistrationStoreError("Primary workspace cannot be stored as a secondary registration")}if(seen.has(normalizedWorkspace)){throw new WorkspaceRegistrationStoreError("Workspace registration store contains duplicate paths")}seen.add(normalizedWorkspace);return workspace});const rawDisplayNames=record["displayNames"];let displayNames;if(rawDisplayNames!==void 0){if(typeof rawDisplayNames!=="object"||rawDisplayNames===null||Array.isArray(rawDisplayNames)){throw new WorkspaceRegistrationStoreError("Workspace registration store displayNames must be an object")}const registrationIds=new Set(workspaces.map(workspaceRegistrationId));for(const[registrationId,value2]of Object.entries(rawDisplayNames)){if(!registrationIds.has(registrationId)){throw new WorkspaceRegistrationStoreError(`Workspace registration store displayNames contains unknown registration id ${JSON.stringify(registrationId)}`)}displayNames??={};displayNames[registrationId]=validateStoredDisplayName(value2,`displayNames[${JSON.stringify(registrationId)}]`)}}return{schemaVersion:SCHEMA_VERSION,primaryWorkspace,workspaces,...displayNames?{displayNames}:{}}}__name(parseSnapshot,"parseSnapshot");var updateChains=new Map;async function withInProcessLock(filePath,work){const previous=updateChains.get(filePath)??Promise.resolve();const next=previous.then(work,work);const settled=next.catch(()=>void 0).finally(()=>{if(updateChains.get(filePath)===settled)updateChains.delete(filePath)});updateChains.set(filePath,settled);return next}__name(withInProcessLock,"withInProcessLock");function compromisedLockError(){return new WorkspaceRegistrationStoreError("Workspace registration store lock was compromised")}__name(compromisedLockError,"compromisedLockError");async function acquireFileLock(filePath){await fs.mkdir(path.dirname(filePath),{recursive:true,mode:448});let compromised=false;const release=await import_proper_lockfile.default.lock(filePath,{...LOCK_OPTIONS,onCompromised:__name(()=>{compromised=true},"onCompromised")});return{assertOwned:__name(()=>{if(compromised)throw compromisedLockError()},"assertOwned"),release:__name(async()=>{try{await release()}catch(err){if(!compromised)throw err}if(compromised)throw compromisedLockError()},"release")}}__name(acquireFileLock,"acquireFileLock");var WorkspaceRegistrationStore=class{constructor(primaryWorkspace,qwenHome){this.primaryWorkspace=primaryWorkspace;validateWorkspacePath(primaryWorkspace,"primaryWorkspace");this.filePath=getWorkspaceRegistrationStorePath(primaryWorkspace,qwenHome)}static{__name(this,"WorkspaceRegistrationStore")}filePath;async read(){try{const entry=await fs.lstat(this.filePath);if(entry.isSymbolicLink()||!entry.isFile()){throw new WorkspaceRegistrationStoreError("Workspace registration store must be a regular file")}}catch(err){if(err.code==="ENOENT"){return emptySnapshot(this.primaryWorkspace)}throw err}let file;try{file=await openNoFollow(this.filePath)}catch(err){if(err.code==="ENOENT"){return emptySnapshot(this.primaryWorkspace)}if(isUnverifiableIdentityError(err)){throw new WorkspaceRegistrationStoreError("Workspace registration store identity could not be verified")}if(err.code==="ELOOP"){throw new WorkspaceRegistrationStoreError("Workspace registration store must be a regular file")}throw err}try{const stat=await file.stat();if(!stat.isFile()){throw new WorkspaceRegistrationStoreError("Workspace registration store must be a regular file")}if(stat.size>MAX_STORE_BYTES){throw new WorkspaceRegistrationStoreTooLargeError(`Workspace registration store exceeds ${MAX_STORE_BYTES} bytes`)}let buffer=Buffer.alloc(Math.max(1,Math.min(stat.size+1,MAX_STORE_BYTES+1)));let totalBytesRead=0;for(;;){if(totalBytesRead===buffer.length){if(totalBytesRead>MAX_STORE_BYTES)break;const grown=Buffer.alloc(Math.min(MAX_STORE_BYTES+1,Math.max(buffer.length*2,totalBytesRead+1)));buffer.copy(grown,0,0,totalBytesRead);buffer=grown}const{bytesRead}=await file.read(buffer,totalBytesRead,buffer.length-totalBytesRead,totalBytesRead);if(bytesRead===0)break;totalBytesRead+=bytesRead}if(totalBytesRead>MAX_STORE_BYTES){throw new WorkspaceRegistrationStoreTooLargeError(`Workspace registration store exceeds ${MAX_STORE_BYTES} bytes`)}return parseSnapshot(buffer.toString("utf8",0,totalBytesRead),this.primaryWorkspace)}finally{await file.close()}}async add(workspace,displayName,maxRegisteredWorkspaces=MAX_REGISTERED_WORKSPACES){const maxSecondaries=resolveMaxRegisteredWorkspaces(maxRegisteredWorkspaces,{})-1;validateWorkspacePath(workspace,"workspace");const normalizedDisplayName=displayName===void 0?void 0:normalizeWorkspaceDisplayName(displayName);if(normalizedScopePath(workspace)===normalizedScopePath(this.primaryWorkspace)){throw new WorkspaceRegistrationStoreError("Primary workspace cannot be stored as a secondary registration")}return this.update(snapshot=>{const normalizedWorkspace=normalizedScopePath(workspace);if(snapshot.workspaces.some(stored=>normalizedScopePath(stored)===normalizedWorkspace)){return false}if(snapshot.workspaces.length>=maxSecondaries){throw new WorkspaceRegistrationStoreLimitError(`Workspace registration store limit of ${maxSecondaries} reached`)}snapshot.workspaces.push(workspace);if(normalizedDisplayName!==void 0){snapshot.displayNames??={};snapshot.displayNames[workspaceRegistrationId(workspace)]=normalizedDisplayName}return true})}async removeById(id){return await this.removeByIds([id])>0}async setDisplayNameByIds(ids,displayName){const normalizedDisplayName=displayName===void 0?void 0:normalizeWorkspaceDisplayName(displayName);const requested=new Set(ids);if(requested.size===0)return 0;let matched=0;await this.update(snapshot=>{let changed=false;for(const workspace of snapshot.workspaces){const registrationId=workspaceRegistrationId(workspace);if(!requested.has(registrationId))continue;matched++;changed=setSnapshotDisplayName(snapshot,registrationId,normalizedDisplayName)||changed}return changed});return matched}async removeByIds(ids){const requested=new Set(ids);if(requested.size===0)return 0;let removed=0;await this.update(snapshot=>{const removedIds=new Set;const retained=snapshot.workspaces.filter(workspace=>{const registrationId=workspaceRegistrationId(workspace);if(!requested.has(registrationId))return true;removed++;removedIds.add(registrationId);return false});if(removed===0)return false;snapshot.workspaces.splice(0,snapshot.workspaces.length,...retained);for(const registrationId of removedIds){setSnapshotDisplayName(snapshot,registrationId,void 0)}return true});return removed}async update(mutate){const{atomicWriteFile}=await import("./deferred-core-runtime-MJYNEA4N.js");return withInProcessLock(this.filePath,async()=>{const lock=await acquireFileLock(this.filePath);let committed=false;let changed=false;let workError;try{const snapshot=await this.read();lock.assertOwned();changed=mutate(snapshot);if(changed){const serialized=`${JSON.stringify(snapshot,null,2)}
|
|
4
4
|
`;if(Buffer.byteLength(serialized,"utf8")>MAX_STORE_BYTES){throw new WorkspaceRegistrationStoreTooLargeError(`Workspace registration store exceeds ${MAX_STORE_BYTES} bytes`)}lock.assertOwned();await atomicWriteFile(this.filePath,serialized,{mode:384,forceMode:true,noFollow:true});committed=true}}catch(err){workError=err}let releaseError;try{await lock.release()}catch(err){releaseError=committed?new WorkspaceRegistrationStoreCommittedError(`Workspace registration update committed but lock release failed: ${err instanceof Error?err.message:String(err)}`):err}if(workError instanceof Error&&releaseError!==void 0&&workError.cause===void 0){workError.cause=releaseError}if(workError!==void 0)throw workError;if(releaseError!==void 0)throw releaseError;return changed})}};export{MAX_REGISTERED_WORKSPACES,resolveMaxRegisteredWorkspaces,resolveWorkspaceInputs,MAX_WORKSPACE_DISPLAY_NAME_LENGTH,WorkspaceDisplayNameValidationError,normalizeWorkspaceDisplayName,WorkspaceRegistrationStoreError,WorkspaceRegistrationStoreLimitError,WorkspaceRegistrationStoreTooLargeError,WorkspaceRegistrationStoreCommittedError,workspaceRegistrationScopeHash,workspaceRegistrationId,getWorkspaceRegistrationStorePath,WorkspaceRegistrationStore};
|
|
5
5
|
/**
|
|
6
6
|
* @license
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{collectInlineImages,extractInlineContentRuns}from"./chunk-VRNYIKVL.js";import{formatHistoryGapNotice,indexGapsByChild}from"./chunk-2DU2WMTL.js";import{t}from"./chunk-NO7VTKRL.js";import{isGoalCheckpointBookkeepingRecord}from"./chunk-OU7CEG7Q.js";import{GoalPersistenceUnavailableError,computeInitialTurnFromHistory,getRecordRewindId,getToolResponseDisplayText}from"./chunk-2JGTWRZJ.js";import{projectUserTranscriptForDisplay}from"./chunk-SZCBUCNH.js";import{parseGoalStateRecordPayloadV2}from"./chunk-HW6AWS7W.js";import{ToolDisplayNames}from"./chunk-SBZFGYYS.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as path from"node:path";init_esbuild_shims();init_esbuild_shims();var EstimatedArtWidth=59;var BoxBorderWidth=1;var BOX_PADDING_X=1;var UI_WIDTH=EstimatedArtWidth+BOX_PADDING_X*2+BoxBorderWidth*2;var SHELL_COMMAND_NAME="Shell Command";var SHELL_NAME="Shell";var TOOL_STATUS={SUCCESS:"\u2713",PENDING:"o",EXECUTING:"\u22B7",CONFIRMING:"?",CANCELED:"-",ERROR:"x"};var _VS15="\uFE0E";var ICON={DIAMOND:`\u25C6${_VS15}`,CIRCLE_FILLED:`\u25CF${_VS15}`,TRIANGLE:`\u25B3${_VS15}`,CIRCLE_EMPTY:`\u25CB${_VS15}`,BULLSEYE:`\u25CE${_VS15}`,REFERENCE:`\u203B${_VS15}`,THEREFORE:`\u2234${_VS15}`,BECAUSE:`\u2235${_VS15}`,STAR:`\u2605${_VS15}`,SPARKLE:`\u2733${_VS15}`,RADIO_FILLED:`\u25C9${_VS15}`,CIRCLE_LEFT_HALF:`\u25D0${_VS15}`,CHECK:`\u2713${_VS15}`,CROSS:`\u2716${_VS15}`};var SPINNER_FRAMES=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];var SPINNER_INTERVAL_MS=80;var WAITING_SPINNER_FRAME="\u280F";var TOOL_NAME_TO_CATEGORY={[ToolDisplayNames.READ_FILE]:"read",[ToolDisplayNames.EDIT]:"edit",[ToolDisplayNames.WRITE_FILE]:"write",[ToolDisplayNames.NOTEBOOK_EDIT]:"edit",[ToolDisplayNames.GREP]:"search",[ToolDisplayNames.GLOB]:"search",[ToolDisplayNames.LS]:"list",[ToolDisplayNames.SHELL]:"command",[SHELL_COMMAND_NAME]:"command",[ToolDisplayNames.AGENT]:"agent",[ToolDisplayNames.WORKFLOW]:"agent",[ToolDisplayNames.SEND_MESSAGE]:"agent","Read File":"read","Read File(s)":"read","Read Directory":"list",SearchFiles:"search",FindFiles:"search",ReadFolder:"list",Task:"agent",TodoWrite:"other"};var CATEGORY_TEMPLATES={read:{past:{one:"Read {{count}} file",many:"Read {{count}} files"},active:{one:"Reading {{count}} file",many:"Reading {{count}} files"},pastVerb:"Read",activeVerb:"Reading"},edit:{past:{one:"Edited {{count}} file",many:"Edited {{count}} files"},active:{one:"Editing {{count}} file",many:"Editing {{count}} files"},pastVerb:"Edited",activeVerb:"Editing"},write:{past:{one:"Wrote {{count}} file",many:"Wrote {{count}} files"},active:{one:"Writing {{count}} file",many:"Writing {{count}} files"},pastVerb:"Wrote",activeVerb:"Writing"},search:{past:{one:"Searched {{count}} pattern",many:"Searched {{count}} patterns"},active:{one:"Searching {{count}} pattern",many:"Searching {{count}} patterns"},pastVerb:"Searched",activeVerb:"Searching"},list:{past:{one:"Listed {{count}} directory",many:"Listed {{count}} directories"},active:{one:"Listing {{count}} directory",many:"Listing {{count}} directories"},pastVerb:"Listed",activeVerb:"Listing"},command:{past:{one:"Ran {{count}} command",many:"Ran {{count}} commands"},active:{one:"Running {{count}} command",many:"Running {{count}} commands"},pastVerb:"Ran",activeVerb:"Running"},agent:{past:{one:"Ran {{count}} agent",many:"Ran {{count}} agents"},active:{one:"Running {{count}} agent",many:"Running {{count}} agents"},pastVerb:"Ran",activeVerb:"Running"},other:{past:{one:"Used {{count}} tool",many:"Used {{count}} tools"},active:{one:"Using {{count}} tool",many:"Using {{count}} tools"},pastVerb:"Used",activeVerb:"Using"}};var CATEGORY_ORDER=["search","read","list","command","edit","write","agent","other"];var COLLAPSIBLE_CATEGORIES=new Set(["read","search","list"]);function getToolCategory(toolName){return TOOL_NAME_TO_CATEGORY[toolName]??"other"}__name(getToolCategory,"getToolCategory");function isCollapsibleTool(toolName){return COLLAPSIBLE_CATEGORIES.has(getToolCategory(toolName))}__name(isCollapsibleTool,"isCollapsibleTool");function safeDescription(raw){if(!raw)return void 0;const stripped=raw.replace(/\x1b\][^\x07]*\x07|\x1b[()][A-Z0-9]|\x1b\[[0-9;]*[a-zA-Z]|\x1b./g,"");const cleaned=stripped.replace(/[\x00-\x1f\x7f]/g," ").trim();if(cleaned.startsWith("{")||cleaned.startsWith("[")){try{const parsed=JSON.parse(cleaned);if(typeof parsed==="object"&&parsed!==null)return void 0}catch{}}return cleaned||void 0}__name(safeDescription,"safeDescription");function categoryShowsDescriptionsInline(toolCalls,category){const sameCategory=toolCalls.filter(tc=>getToolCategory(tc.name)===category);if(sameCategory.length>DESCRIPTION_INLINE_LIMIT)return false;return sameCategory.every(tc=>safeDescription(tc.description)!==void 0)}__name(categoryShowsDescriptionsInline,"categoryShowsDescriptionsInline");function getActiveToolHint(toolCalls){if(toolCalls.length<2)return void 0;const statuses=["Confirming","Executing","Pending"];for(const status of statuses){for(let index=toolCalls.length-1;index>=0;index--){const tool=toolCalls[index];if(tool.status===status){const category=getToolCategory(tool.name);const hasCategoryPeers=toolCalls.some((candidate,candidateIndex)=>candidateIndex!==index&&getToolCategory(candidate.name)===category);if(!hasCategoryPeers)return void 0;if(categoryShowsDescriptionsInline(toolCalls,category))return void 0;return safeDescription(tool.description)}}}return void 0}__name(getActiveToolHint,"getActiveToolHint");var DESCRIPTION_INLINE_LIMIT=3;var DESCRIPTION_PREVIEW_COUNT=2;function buildToolSummary(toolCalls,isActive){if(toolCalls.length===0)return"";const toolsByCategory=new Map;for(const tool of toolCalls){const cat=getToolCategory(tool.name);const arr=toolsByCategory.get(cat)??[];arr.push(tool);toolsByCategory.set(cat,arr)}const parts=[];for(const cat of CATEGORY_ORDER){const tools=toolsByCategory.get(cat);if(!tools||tools.length===0)continue;const template=CATEGORY_TEMPLATES[cat];const verb=isActive?template.activeVerb:template.pastVerb;let part;if(tools.length===1){const safeDesc=safeDescription(tools[0].description);if(safeDesc!==void 0){part=`${verb} ${safeDesc}`}else{part=t(isActive?template.active.one:template.past.one,{count:"1"})}}else if(tools.length<=DESCRIPTION_INLINE_LIMIT){const descriptions=tools.map(tc=>safeDescription(tc.description)).filter(d=>d!==void 0);if(descriptions.length===tools.length){part=`${verb} ${descriptions.join(", ")}`}else{const forms=isActive?template.active:template.past;part=t(forms.many,{count:String(tools.length)})}}else{const previewDescs=tools.slice(0,DESCRIPTION_PREVIEW_COUNT).map(tc=>safeDescription(tc.description)).filter(d=>d!==void 0);if(previewDescs.length===DESCRIPTION_PREVIEW_COUNT){const remaining=tools.length-DESCRIPTION_PREVIEW_COUNT;const morePhrase=t("... and {{count}} more",{count:String(remaining)});part=`${verb} ${previewDescs.join(", ")}, ${morePhrase}`}else{const forms=isActive?template.active:template.past;part=t(forms.many,{count:String(tools.length)})}}if(parts.length>0){part=part.charAt(0).toLowerCase()+part.slice(1)}parts.push(part)}return parts.join(", ")}__name(buildToolSummary,"buildToolSummary");function isSubagentToolEntry(tool){const rd=tool.resultDisplay;return typeof rd==="object"&&rd!==null&&"type"in rd&&rd.type==="task_execution"}__name(isSubagentToolEntry,"isSubagentToolEntry");init_esbuild_shims();var SUPERSEDED_FINDINGS_MESSAGE="(findings replaced by a later report_findings call)";function isFindingsListDisplay(value){return typeof value==="object"&&value!==null&&"type"in value&&value.type==="findings_list"}__name(isFindingsListDisplay,"isFindingsListDisplay");function coalesceFindingsHistoryItems(items){let lastItem=-1;let lastTool=-1;for(let i=items.length-1;i>=0&&lastItem===-1;i-=1){const item=items[i];if(item.type!=="tool_group")continue;for(let j=item.tools.length-1;j>=0;j-=1){if(isFindingsListDisplay(item.tools[j].resultDisplay)){lastItem=i;lastTool=j;break}}}if(lastItem===-1)return items;let changed=false;const next=items.map((item,i)=>{if(item.type!=="tool_group")return item;let toolsChanged=false;const tools=item.tools.map((tool,j)=>{if(i===lastItem&&j===lastTool)return tool;if(!isFindingsListDisplay(tool.resultDisplay))return tool;toolsChanged=true;return{...tool,resultDisplay:SUPERSEDED_FINDINGS_MESSAGE,supersededFindingsDisplay:tool.supersededFindingsDisplay??tool.resultDisplay}});if(!toolsChanged)return item;changed=true;return{...item,tools}});return changed?next:items}__name(coalesceFindingsHistoryItems,"coalesceFindingsHistoryItems");function recoalesceFindingsHistoryItems(items){let restored=false;const next=items.map(item=>{if(item.type!=="tool_group")return item;let toolsChanged=false;const tools=item.tools.map(tool=>{if(tool.resultDisplay!==SUPERSEDED_FINDINGS_MESSAGE||!tool.supersededFindingsDisplay){return tool}toolsChanged=true;return{...tool,resultDisplay:tool.supersededFindingsDisplay,supersededFindingsDisplay:void 0}});if(!toolsChanged)return item;restored=true;return{...item,tools}});return coalesceFindingsHistoryItems(restored?next:items)}__name(recoalesceFindingsHistoryItems,"recoalesceFindingsHistoryItems");init_esbuild_shims();function shouldDisplayGoalStateCause(cause){switch(cause){case"turn_finished":case"checkpoint":case"verifier_accept":return false;case"verifier_reject":case"create":case"replace":case"edit":case"pause":case"resume":case"complete":case"blocked":case"usage_limited":case"clear":case"migrated":return true;default:{const exhaustive=cause;return exhaustive}}}__name(shouldDisplayGoalStateCause,"shouldDisplayGoalStateCause");async function waitForGoalRuntime(config,options={}){const awaitReady=__name(async()=>{try{await config.getGoalRuntimeReady()}catch(error){if(!(error instanceof GoalPersistenceUnavailableError))throw error}},"awaitReady");const{timeoutMs}=options;if(timeoutMs==null||timeoutMs<=0){await awaitReady();return true}let timer;const timeout=new Promise(resolve=>{timer=setTimeout(()=>resolve("timeout"),timeoutMs);timer.unref?.()});try{const winner=await Promise.race([awaitReady(),timeout]);return winner!=="timeout"}finally{if(timer)clearTimeout(timer)}}__name(waitForGoalRuntime,"waitForGoalRuntime");function extractTextFromParts(parts){if(!parts)return"";const textParts=[];for(const part of parts){if("text"in part&&part.text){if(!("thought"in part&&part.thought)){textParts.push(part.text)}}}return textParts.join("\n")}__name(extractTextFromParts,"extractTextFromParts");function extractThoughtTextFromParts(parts){if(!parts)return"";const thoughtParts=[];for(const part of parts){if("text"in part&&part.text&&"thought"in part&&part.thought){thoughtParts.push(part.text)}}return thoughtParts.join("\n")}__name(extractThoughtTextFromParts,"extractThoughtTextFromParts");function extractFunctionCalls(parts){if(!parts)return[];const calls=[];for(const part of parts){if("functionCall"in part&&part.functionCall){const fc=part.functionCall;calls.push({id:fc.id||`call-${calls.length}`,name:fc.name||"unknown",args:fc.args||{}})}}return calls}__name(extractFunctionCalls,"extractFunctionCalls");function getTool(config,name){if(!config)return void 0;const toolRegistry=config.getToolRegistry();return toolRegistry.getTool(name)}__name(getTool,"getTool");function formatToolDescription(tool,args){try{const invocation=tool.build(args);return invocation.getDescription()}catch{if(typeof args["description"]==="string"){return args["description"]}return""}}__name(formatToolDescription,"formatToolDescription");function restoreHistoryItem(raw){if(!raw||typeof raw!=="object"){return}const clone={...raw};if("timestamp"in clone){const ts=clone["timestamp"];if(typeof ts==="string"||typeof ts==="number"){clone["timestamp"]=new Date(ts)}}if(typeof clone["type"]!=="string"){return}return clone}__name(restoreHistoryItem,"restoreHistoryItem");function createHistoryGapItem(gap){return{type:"info",text:formatHistoryGapNotice(gap)}}__name(createHistoryGapItem,"createHistoryGapItem");function convertToHistoryItems(conversation,config,historyGaps){const items=[];const gapByChildUuid=indexGapsByChild(historyGaps);const pendingAtCommands=[];let atCommandCounter=0;let lastGoalStateSnapshot;let lastGoalStateCause;const pendingToolCalls=new Map;let currentToolGroup=[];const buildAtCommandDisplays=__name(payload=>{if(payload.status==="error"){atCommandCounter+=1;const filesLabel=payload.filesRead?.length?payload.filesRead.join(", "):"files";return[{callId:`at-command-${atCommandCounter}`,name:"Read File(s)",description:"Error attempting to read files",status:"Error",resultDisplay:payload.message||`Error reading files (${filesLabel})`,confirmationDetails:void 0}]}if(!payload.filesRead?.length){atCommandCounter+=1;return[{callId:`at-command-${atCommandCounter}`,name:"Read File",description:"Read File(s)",status:"Success",resultDisplay:void 0,confirmationDetails:void 0}]}return payload.filesRead.map(filePath=>{atCommandCounter+=1;const isDir=filePath.endsWith("/");return{callId:`at-command-${atCommandCounter}`,name:isDir?"Read Directory":"Read File",description:isDir?`Read directory ${path.basename(filePath)}`:`Read file ${path.basename(filePath)}`,status:"Success",resultDisplay:void 0,confirmationDetails:void 0}})},"buildAtCommandDisplays");for(const record of conversation.messages){const promptId=typeof record.promptId==="string"&&record.promptId.length>0?record.promptId:void 0;const rewindId=promptId?void 0:getRecordRewindId(record);const gap=gapByChildUuid.get(record.uuid);if(gap){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}pendingAtCommands.length=0;lastGoalStateSnapshot=void 0;lastGoalStateCause=void 0;items.push(createHistoryGapItem(gap))}if(record.type==="system"){if(record.subtype==="goal_state"){const payload=parseGoalStateRecordPayloadV2(record.systemPayload);if(payload){const bookkeepingOnly=isGoalCheckpointBookkeepingRecord({cause:payload.cause,previousCause:lastGoalStateCause,previous:lastGoalStateSnapshot,next:payload.snapshot});lastGoalStateCause=payload.cause;lastGoalStateSnapshot=payload.snapshot;if(shouldDisplayGoalStateCause(payload.cause)&&!bookkeepingOnly){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}items.push({type:"goal_state",snapshot:payload.snapshot,cause:payload.cause})}}continue}if(record.subtype==="slash_command"){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}const payload=record.systemPayload;if(!payload)continue;if(payload.phase==="invocation"&&payload.rawCommand&&!payload.hiddenInvocation){const sentToModel=typeof payload.sentToModel==="boolean"?payload.sentToModel:void 0;items.push({type:"user",text:payload.rawCommand,...promptId?{promptId}:{},...sentToModel===void 0?{}:{sentToModel}})}if(payload.phase==="result"){const outputs=payload.outputHistoryItems??[];for(const raw of outputs){const restored=restoreHistoryItem(raw);if(restored){items.push(restored)}}}}if(record.subtype==="at_command"){const payload=record.systemPayload;if(!payload)continue;pendingAtCommands.push(payload)}if(record.subtype==="rewind"){items.push({type:"info",text:"Conversation rewound."})}continue}switch(record.type){case"user":{if(record.subtype==="goal_runtime")break;if(record.subtype==="notification"||record.subtype==="cron"){const payload2=record.systemPayload;const fallback=record.subtype==="cron"?"Cron job fired":"Background agent completed";const text2=payload2?.displayText||extractTextFromParts(record.message?.parts)||fallback;items.push({type:"notification",text:text2});break}if(record.subtype==="agent_mention"||record.subtype==="agent_message"){const payload2=record.systemPayload;const text2=payload2?.displayText;if(text2){if(record.subtype==="agent_mention"&&!payload2?.author){items.push({type:"user",text:text2,sentToModel:false})}else{const name=payload2?.author?.name??record.agentName;items.push({type:"notification",text:name?`${name}: ${text2}`:text2})}}break}if(record.subtype==="mid_turn_user_message"){const payload2=record.systemPayload;const hasAttachmentReferences2=Array.isArray(payload2?.attachmentReferences)&&payload2.attachmentReferences.length>0;const text2=payload2?.displayText||(hasAttachmentReferences2?"[User message with attachments]":extractTextFromParts(record.message?.parts));if(text2){items.push({type:"user",text:text2,sentToModel:false})}break}if(pendingAtCommands.length>0){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}const payload2=pendingAtCommands.shift();const projection2=projectUserTranscriptForDisplay(record);const text2=payload2.userText||(projection2.displayText??extractTextFromParts(projection2.parts));if(text2){items.push({type:"user",text:text2,...promptId?{promptId}:{},...rewindId?{rewindId}:{}})}const toolDisplays=buildAtCommandDisplays(payload2);if(toolDisplays.length>0){items.push({type:"tool_group",tools:toolDisplays})}break}if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}const projection=projectUserTranscriptForDisplay(record);const payload=record.systemPayload;const hasAttachmentReferences=Array.isArray(payload?.attachmentReferences)&&payload.attachmentReferences.length>0;const text=projection.displayText||(hasAttachmentReferences?"[User message with attachments]":extractTextFromParts(projection.parts));if(text){items.push({type:"user",text,...promptId?{promptId}:{},...rewindId?{rewindId}:{}})}break}case"assistant":{const parts=record.message?.parts;const thoughtText=!config?extractThoughtTextFromParts(parts):"";const displayRuns=extractInlineContentRuns(parts,"\n");const functionCalls=extractFunctionCalls(parts);if(thoughtText){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}items.push({type:"gemini_thought",text:thoughtText})}if(displayRuns.length>0){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}for(const[index,run]of displayRuns.entries()){const type=index===0?"gemini":"gemini_content";const timestamp=index===0?{timestamp:new Date(record.timestamp).getTime()}:{};if(run.kind==="text"){items.push({type,text:run.text,...timestamp})}else if(run.kind==="image"){items.push({type,text:"",images:[run.image],...timestamp})}else{items.push({type,text:"",omittedImageCount:run.count,...timestamp})}}}for(const fc of functionCalls){const tool=getTool(config,fc.name);pendingToolCalls.set(fc.id,{name:fc.name,args:fc.args});currentToolGroup.push({callId:fc.id,name:tool?.displayName||fc.name,description:tool?formatToolDescription(tool,fc.args):"",args:fc.args,resultDisplay:void 0,status:"Error",confirmationDetails:void 0})}break}case"tool_result":{if(record.toolCallResult){const callId=record.toolCallResult.callId;const toolCall=currentToolGroup.find(t2=>t2.callId===callId);if(toolCall){const responseParts=record.toolCallResult.responseParts??record.message?.parts;const rawDisplay=record.toolCallResult.resultDisplay;toolCall.resultDisplay=rawDisplay;if(record.toolCallResult.visionBridgeNotice!==void 0){toolCall.visionBridgeNotice=record.toolCallResult.visionBridgeNotice}const rawStatus=record.toolCallResult["status"];toolCall.status=rawStatus==="error"?"Error":rawStatus==="cancelled"?"Canceled":"Success";const{images,omittedImageCount}=collectInlineImages(responseParts);if(images.length>0){toolCall.images=images}if(omittedImageCount>0){toolCall.omittedImageCount=omittedImageCount}if(toolCall.status==="Success"&&isCollapsibleTool(toolCall.name)){toolCall.detailedDisplay=getToolResponseDisplayText(responseParts)}}pendingToolCalls.delete(callId||"")}break}default:break}}if(pendingAtCommands.length>0){for(const payload of pendingAtCommands){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}const text=payload.userText;if(text){items.push({type:"user",text})}const toolDisplays=buildAtCommandDisplays(payload);if(toolDisplays.length>0){items.push({type:"tool_group",tools:toolDisplays})}}}if(currentToolGroup.length>0){items.push({type:"tool_group",tools:currentToolGroup})}return coalesceFindingsHistoryItems(items)}__name(convertToHistoryItems,"convertToHistoryItems");function buildResumedHistoryItems(sessionData,config,baseTimestamp=Date.now()){const items=[];let idCounter=1;const getNextId=__name(()=>baseTimestamp+idCounter++,"getNextId");const historyItems=convertToHistoryItems(sessionData.conversation,config,sessionData.historyGaps);for(const item of historyItems){items.push({...item,id:getNextId()})}return items}__name(buildResumedHistoryItems,"buildResumedHistoryItems");function applyResumeDisplayPolicy(items){return items.map(item=>({...item,display:{...item.display,suppressOnRestore:true}}))}__name(applyResumeDisplayPolicy,"applyResumeDisplayPolicy");function createHistoryCollapseSummaryItem(messageCount){const n=String(messageCount);return{type:"info",text:t("History collapsed: {{n}} messages hidden. Use /history expand-now to show.",{n}),display:{kind:"collapse-summary"}}}__name(createHistoryCollapseSummaryItem,"createHistoryCollapseSummaryItem");function stripSuppressOnRestore(item){if(!item.display?.suppressOnRestore)return item;const{suppressOnRestore:_,...rest}=item.display;return{...item,display:Object.keys(rest).length>0?rest:void 0}}__name(stripSuppressOnRestore,"stripSuppressOnRestore");function computeResumedPromptCountSeed(records,sessionId){const userTurnCount=records.filter(m=>m.type==="user"&&m.subtype!=="mid_turn_user_message"&&m.subtype!=="realtime_message").length;if(records.length===0){return 0}return Math.max(userTurnCount,computeInitialTurnFromHistory(records,sessionId)+1)}__name(computeResumedPromptCountSeed,"computeResumedPromptCountSeed");function expandCollapsedHistory(items){return items.filter(item=>item.display?.kind!=="collapse-summary").map(stripSuppressOnRestore)}__name(expandCollapsedHistory,"expandCollapsedHistory");function applyCollapsePolicyAndSummary(rawItems,collapseOnResume,collapsePreviewCount=0){if(!collapseOnResume)return rawItems;if(collapsePreviewCount===-1)return rawItems;let boundary=rawItems.length;if(collapsePreviewCount>0){let userTurnCount=0;for(let i=rawItems.length-1;i>=0;i--){const item=rawItems[i];if(item.type==="user"&&item.sentToModel!==false){userTurnCount++;if(userTurnCount===collapsePreviewCount){boundary=i;break}}}if(userTurnCount<collapsePreviewCount){boundary=0}}const hiddenItems=applyResumeDisplayPolicy(rawItems.slice(0,boundary));const visibleItems=rawItems.slice(boundary);const uiHistoryItems=[...hiddenItems,...visibleItems];if(boundary>0){const nextId=rawItems[rawItems.length-1].id+1;return[...uiHistoryItems,{id:nextId,...createHistoryCollapseSummaryItem(boundary)}]}return uiHistoryItems}__name(applyCollapsePolicyAndSummary,"applyCollapsePolicyAndSummary");export{SHELL_COMMAND_NAME,SHELL_NAME,TOOL_STATUS,ICON,SPINNER_FRAMES,SPINNER_INTERVAL_MS,WAITING_SPINNER_FRAME,isCollapsibleTool,getActiveToolHint,buildToolSummary,isSubagentToolEntry,isFindingsListDisplay,coalesceFindingsHistoryItems,recoalesceFindingsHistoryItems,shouldDisplayGoalStateCause,waitForGoalRuntime,buildResumedHistoryItems,stripSuppressOnRestore,computeResumedPromptCountSeed,expandCollapsedHistory,applyCollapsePolicyAndSummary};
|
|
3
|
+
import{collectInlineImages,extractInlineContentRuns}from"./chunk-VRNYIKVL.js";import{formatHistoryGapNotice,indexGapsByChild}from"./chunk-2DU2WMTL.js";import{t}from"./chunk-NO7VTKRL.js";import{isGoalCheckpointBookkeepingRecord}from"./chunk-G2LTZU67.js";import{GoalPersistenceUnavailableError,computeInitialTurnFromHistory,getRecordRewindId,getToolResponseDisplayText}from"./chunk-7XQ5D34E.js";import{projectUserTranscriptForDisplay}from"./chunk-SZCBUCNH.js";import{parseGoalStateRecordPayloadV2}from"./chunk-HW6AWS7W.js";import{ToolDisplayNames}from"./chunk-SBZFGYYS.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as path from"node:path";init_esbuild_shims();init_esbuild_shims();var EstimatedArtWidth=59;var BoxBorderWidth=1;var BOX_PADDING_X=1;var UI_WIDTH=EstimatedArtWidth+BOX_PADDING_X*2+BoxBorderWidth*2;var SHELL_COMMAND_NAME="Shell Command";var SHELL_NAME="Shell";var TOOL_STATUS={SUCCESS:"\u2713",PENDING:"o",EXECUTING:"\u22B7",CONFIRMING:"?",CANCELED:"-",ERROR:"x"};var _VS15="\uFE0E";var ICON={DIAMOND:`\u25C6${_VS15}`,CIRCLE_FILLED:`\u25CF${_VS15}`,TRIANGLE:`\u25B3${_VS15}`,CIRCLE_EMPTY:`\u25CB${_VS15}`,BULLSEYE:`\u25CE${_VS15}`,REFERENCE:`\u203B${_VS15}`,THEREFORE:`\u2234${_VS15}`,BECAUSE:`\u2235${_VS15}`,STAR:`\u2605${_VS15}`,SPARKLE:`\u2733${_VS15}`,RADIO_FILLED:`\u25C9${_VS15}`,CIRCLE_LEFT_HALF:`\u25D0${_VS15}`,CHECK:`\u2713${_VS15}`,CROSS:`\u2716${_VS15}`};var SPINNER_FRAMES=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];var SPINNER_INTERVAL_MS=80;var WAITING_SPINNER_FRAME="\u280F";var TOOL_NAME_TO_CATEGORY={[ToolDisplayNames.READ_FILE]:"read",[ToolDisplayNames.EDIT]:"edit",[ToolDisplayNames.WRITE_FILE]:"write",[ToolDisplayNames.NOTEBOOK_EDIT]:"edit",[ToolDisplayNames.GREP]:"search",[ToolDisplayNames.GLOB]:"search",[ToolDisplayNames.LS]:"list",[ToolDisplayNames.SHELL]:"command",[SHELL_COMMAND_NAME]:"command",[ToolDisplayNames.AGENT]:"agent",[ToolDisplayNames.WORKFLOW]:"agent",[ToolDisplayNames.SEND_MESSAGE]:"agent","Read File":"read","Read File(s)":"read","Read Directory":"list",SearchFiles:"search",FindFiles:"search",ReadFolder:"list",Task:"agent",TodoWrite:"other"};var CATEGORY_TEMPLATES={read:{past:{one:"Read {{count}} file",many:"Read {{count}} files"},active:{one:"Reading {{count}} file",many:"Reading {{count}} files"},pastVerb:"Read",activeVerb:"Reading"},edit:{past:{one:"Edited {{count}} file",many:"Edited {{count}} files"},active:{one:"Editing {{count}} file",many:"Editing {{count}} files"},pastVerb:"Edited",activeVerb:"Editing"},write:{past:{one:"Wrote {{count}} file",many:"Wrote {{count}} files"},active:{one:"Writing {{count}} file",many:"Writing {{count}} files"},pastVerb:"Wrote",activeVerb:"Writing"},search:{past:{one:"Searched {{count}} pattern",many:"Searched {{count}} patterns"},active:{one:"Searching {{count}} pattern",many:"Searching {{count}} patterns"},pastVerb:"Searched",activeVerb:"Searching"},list:{past:{one:"Listed {{count}} directory",many:"Listed {{count}} directories"},active:{one:"Listing {{count}} directory",many:"Listing {{count}} directories"},pastVerb:"Listed",activeVerb:"Listing"},command:{past:{one:"Ran {{count}} command",many:"Ran {{count}} commands"},active:{one:"Running {{count}} command",many:"Running {{count}} commands"},pastVerb:"Ran",activeVerb:"Running"},agent:{past:{one:"Ran {{count}} agent",many:"Ran {{count}} agents"},active:{one:"Running {{count}} agent",many:"Running {{count}} agents"},pastVerb:"Ran",activeVerb:"Running"},other:{past:{one:"Used {{count}} tool",many:"Used {{count}} tools"},active:{one:"Using {{count}} tool",many:"Using {{count}} tools"},pastVerb:"Used",activeVerb:"Using"}};var CATEGORY_ORDER=["search","read","list","command","edit","write","agent","other"];var COLLAPSIBLE_CATEGORIES=new Set(["read","search","list"]);function getToolCategory(toolName){return TOOL_NAME_TO_CATEGORY[toolName]??"other"}__name(getToolCategory,"getToolCategory");function isCollapsibleTool(toolName){return COLLAPSIBLE_CATEGORIES.has(getToolCategory(toolName))}__name(isCollapsibleTool,"isCollapsibleTool");function safeDescription(raw){if(!raw)return void 0;const stripped=raw.replace(/\x1b\][^\x07]*\x07|\x1b[()][A-Z0-9]|\x1b\[[0-9;]*[a-zA-Z]|\x1b./g,"");const cleaned=stripped.replace(/[\x00-\x1f\x7f]/g," ").trim();if(cleaned.startsWith("{")||cleaned.startsWith("[")){try{const parsed=JSON.parse(cleaned);if(typeof parsed==="object"&&parsed!==null)return void 0}catch{}}return cleaned||void 0}__name(safeDescription,"safeDescription");function categoryShowsDescriptionsInline(toolCalls,category){const sameCategory=toolCalls.filter(tc=>getToolCategory(tc.name)===category);if(sameCategory.length>DESCRIPTION_INLINE_LIMIT)return false;return sameCategory.every(tc=>safeDescription(tc.description)!==void 0)}__name(categoryShowsDescriptionsInline,"categoryShowsDescriptionsInline");function getActiveToolHint(toolCalls){if(toolCalls.length<2)return void 0;const statuses=["Confirming","Executing","Pending"];for(const status of statuses){for(let index=toolCalls.length-1;index>=0;index--){const tool=toolCalls[index];if(tool.status===status){const category=getToolCategory(tool.name);const hasCategoryPeers=toolCalls.some((candidate,candidateIndex)=>candidateIndex!==index&&getToolCategory(candidate.name)===category);if(!hasCategoryPeers)return void 0;if(categoryShowsDescriptionsInline(toolCalls,category))return void 0;return safeDescription(tool.description)}}}return void 0}__name(getActiveToolHint,"getActiveToolHint");var DESCRIPTION_INLINE_LIMIT=3;var DESCRIPTION_PREVIEW_COUNT=2;function buildToolSummary(toolCalls,isActive){if(toolCalls.length===0)return"";const toolsByCategory=new Map;for(const tool of toolCalls){const cat=getToolCategory(tool.name);const arr=toolsByCategory.get(cat)??[];arr.push(tool);toolsByCategory.set(cat,arr)}const parts=[];for(const cat of CATEGORY_ORDER){const tools=toolsByCategory.get(cat);if(!tools||tools.length===0)continue;const template=CATEGORY_TEMPLATES[cat];const verb=isActive?template.activeVerb:template.pastVerb;let part;if(tools.length===1){const safeDesc=safeDescription(tools[0].description);if(safeDesc!==void 0){part=`${verb} ${safeDesc}`}else{part=t(isActive?template.active.one:template.past.one,{count:"1"})}}else if(tools.length<=DESCRIPTION_INLINE_LIMIT){const descriptions=tools.map(tc=>safeDescription(tc.description)).filter(d=>d!==void 0);if(descriptions.length===tools.length){part=`${verb} ${descriptions.join(", ")}`}else{const forms=isActive?template.active:template.past;part=t(forms.many,{count:String(tools.length)})}}else{const previewDescs=tools.slice(0,DESCRIPTION_PREVIEW_COUNT).map(tc=>safeDescription(tc.description)).filter(d=>d!==void 0);if(previewDescs.length===DESCRIPTION_PREVIEW_COUNT){const remaining=tools.length-DESCRIPTION_PREVIEW_COUNT;const morePhrase=t("... and {{count}} more",{count:String(remaining)});part=`${verb} ${previewDescs.join(", ")}, ${morePhrase}`}else{const forms=isActive?template.active:template.past;part=t(forms.many,{count:String(tools.length)})}}if(parts.length>0){part=part.charAt(0).toLowerCase()+part.slice(1)}parts.push(part)}return parts.join(", ")}__name(buildToolSummary,"buildToolSummary");function isSubagentToolEntry(tool){const rd=tool.resultDisplay;return typeof rd==="object"&&rd!==null&&"type"in rd&&rd.type==="task_execution"}__name(isSubagentToolEntry,"isSubagentToolEntry");init_esbuild_shims();var SUPERSEDED_FINDINGS_MESSAGE="(findings replaced by a later report_findings call)";function isFindingsListDisplay(value){return typeof value==="object"&&value!==null&&"type"in value&&value.type==="findings_list"}__name(isFindingsListDisplay,"isFindingsListDisplay");function coalesceFindingsHistoryItems(items){let lastItem=-1;let lastTool=-1;for(let i=items.length-1;i>=0&&lastItem===-1;i-=1){const item=items[i];if(item.type!=="tool_group")continue;for(let j=item.tools.length-1;j>=0;j-=1){if(isFindingsListDisplay(item.tools[j].resultDisplay)){lastItem=i;lastTool=j;break}}}if(lastItem===-1)return items;let changed=false;const next=items.map((item,i)=>{if(item.type!=="tool_group")return item;let toolsChanged=false;const tools=item.tools.map((tool,j)=>{if(i===lastItem&&j===lastTool)return tool;if(!isFindingsListDisplay(tool.resultDisplay))return tool;toolsChanged=true;return{...tool,resultDisplay:SUPERSEDED_FINDINGS_MESSAGE,supersededFindingsDisplay:tool.supersededFindingsDisplay??tool.resultDisplay}});if(!toolsChanged)return item;changed=true;return{...item,tools}});return changed?next:items}__name(coalesceFindingsHistoryItems,"coalesceFindingsHistoryItems");function recoalesceFindingsHistoryItems(items){let restored=false;const next=items.map(item=>{if(item.type!=="tool_group")return item;let toolsChanged=false;const tools=item.tools.map(tool=>{if(tool.resultDisplay!==SUPERSEDED_FINDINGS_MESSAGE||!tool.supersededFindingsDisplay){return tool}toolsChanged=true;return{...tool,resultDisplay:tool.supersededFindingsDisplay,supersededFindingsDisplay:void 0}});if(!toolsChanged)return item;restored=true;return{...item,tools}});return coalesceFindingsHistoryItems(restored?next:items)}__name(recoalesceFindingsHistoryItems,"recoalesceFindingsHistoryItems");init_esbuild_shims();function shouldDisplayGoalStateCause(cause){switch(cause){case"turn_finished":case"checkpoint":case"verifier_accept":return false;case"verifier_reject":case"create":case"replace":case"edit":case"pause":case"resume":case"complete":case"blocked":case"usage_limited":case"clear":case"migrated":return true;default:{const exhaustive=cause;return exhaustive}}}__name(shouldDisplayGoalStateCause,"shouldDisplayGoalStateCause");async function waitForGoalRuntime(config,options={}){const awaitReady=__name(async()=>{try{await config.getGoalRuntimeReady()}catch(error){if(!(error instanceof GoalPersistenceUnavailableError))throw error}},"awaitReady");const{timeoutMs}=options;if(timeoutMs==null||timeoutMs<=0){await awaitReady();return true}let timer;const timeout=new Promise(resolve=>{timer=setTimeout(()=>resolve("timeout"),timeoutMs);timer.unref?.()});try{const winner=await Promise.race([awaitReady(),timeout]);return winner!=="timeout"}finally{if(timer)clearTimeout(timer)}}__name(waitForGoalRuntime,"waitForGoalRuntime");function extractTextFromParts(parts){if(!parts)return"";const textParts=[];for(const part of parts){if("text"in part&&part.text){if(!("thought"in part&&part.thought)){textParts.push(part.text)}}}return textParts.join("\n")}__name(extractTextFromParts,"extractTextFromParts");function extractThoughtTextFromParts(parts){if(!parts)return"";const thoughtParts=[];for(const part of parts){if("text"in part&&part.text&&"thought"in part&&part.thought){thoughtParts.push(part.text)}}return thoughtParts.join("\n")}__name(extractThoughtTextFromParts,"extractThoughtTextFromParts");function extractFunctionCalls(parts){if(!parts)return[];const calls=[];for(const part of parts){if("functionCall"in part&&part.functionCall){const fc=part.functionCall;calls.push({id:fc.id||`call-${calls.length}`,name:fc.name||"unknown",args:fc.args||{}})}}return calls}__name(extractFunctionCalls,"extractFunctionCalls");function getTool(config,name){if(!config)return void 0;const toolRegistry=config.getToolRegistry();return toolRegistry.getTool(name)}__name(getTool,"getTool");function formatToolDescription(tool,args){try{const invocation=tool.build(args);return invocation.getDescription()}catch{if(typeof args["description"]==="string"){return args["description"]}return""}}__name(formatToolDescription,"formatToolDescription");function restoreHistoryItem(raw){if(!raw||typeof raw!=="object"){return}const clone={...raw};if("timestamp"in clone){const ts=clone["timestamp"];if(typeof ts==="string"||typeof ts==="number"){clone["timestamp"]=new Date(ts)}}if(typeof clone["type"]!=="string"){return}return clone}__name(restoreHistoryItem,"restoreHistoryItem");function createHistoryGapItem(gap){return{type:"info",text:formatHistoryGapNotice(gap)}}__name(createHistoryGapItem,"createHistoryGapItem");function convertToHistoryItems(conversation,config,historyGaps){const items=[];const gapByChildUuid=indexGapsByChild(historyGaps);const pendingAtCommands=[];let atCommandCounter=0;let lastGoalStateSnapshot;let lastGoalStateCause;const pendingToolCalls=new Map;let currentToolGroup=[];const buildAtCommandDisplays=__name(payload=>{if(payload.status==="error"){atCommandCounter+=1;const filesLabel=payload.filesRead?.length?payload.filesRead.join(", "):"files";return[{callId:`at-command-${atCommandCounter}`,name:"Read File(s)",description:"Error attempting to read files",status:"Error",resultDisplay:payload.message||`Error reading files (${filesLabel})`,confirmationDetails:void 0}]}if(!payload.filesRead?.length){atCommandCounter+=1;return[{callId:`at-command-${atCommandCounter}`,name:"Read File",description:"Read File(s)",status:"Success",resultDisplay:void 0,confirmationDetails:void 0}]}return payload.filesRead.map(filePath=>{atCommandCounter+=1;const isDir=filePath.endsWith("/");return{callId:`at-command-${atCommandCounter}`,name:isDir?"Read Directory":"Read File",description:isDir?`Read directory ${path.basename(filePath)}`:`Read file ${path.basename(filePath)}`,status:"Success",resultDisplay:void 0,confirmationDetails:void 0}})},"buildAtCommandDisplays");for(const record of conversation.messages){const promptId=typeof record.promptId==="string"&&record.promptId.length>0?record.promptId:void 0;const rewindId=promptId?void 0:getRecordRewindId(record);const gap=gapByChildUuid.get(record.uuid);if(gap){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}pendingAtCommands.length=0;lastGoalStateSnapshot=void 0;lastGoalStateCause=void 0;items.push(createHistoryGapItem(gap))}if(record.type==="system"){if(record.subtype==="goal_state"){const payload=parseGoalStateRecordPayloadV2(record.systemPayload);if(payload){const bookkeepingOnly=isGoalCheckpointBookkeepingRecord({cause:payload.cause,previousCause:lastGoalStateCause,previous:lastGoalStateSnapshot,next:payload.snapshot});lastGoalStateCause=payload.cause;lastGoalStateSnapshot=payload.snapshot;if(shouldDisplayGoalStateCause(payload.cause)&&!bookkeepingOnly){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}items.push({type:"goal_state",snapshot:payload.snapshot,cause:payload.cause})}}continue}if(record.subtype==="slash_command"){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}const payload=record.systemPayload;if(!payload)continue;if(payload.phase==="invocation"&&payload.rawCommand&&!payload.hiddenInvocation){const sentToModel=typeof payload.sentToModel==="boolean"?payload.sentToModel:void 0;items.push({type:"user",text:payload.rawCommand,...promptId?{promptId}:{},...sentToModel===void 0?{}:{sentToModel}})}if(payload.phase==="result"){const outputs=payload.outputHistoryItems??[];for(const raw of outputs){const restored=restoreHistoryItem(raw);if(restored){items.push(restored)}}}}if(record.subtype==="at_command"){const payload=record.systemPayload;if(!payload)continue;pendingAtCommands.push(payload)}if(record.subtype==="rewind"){items.push({type:"info",text:"Conversation rewound."})}continue}switch(record.type){case"user":{if(record.subtype==="goal_runtime")break;if(record.subtype==="notification"||record.subtype==="cron"){const payload2=record.systemPayload;const fallback=record.subtype==="cron"?"Cron job fired":"Background agent completed";const text2=payload2?.displayText||extractTextFromParts(record.message?.parts)||fallback;items.push({type:"notification",text:text2});break}if(record.subtype==="agent_mention"||record.subtype==="agent_message"){const payload2=record.systemPayload;const text2=payload2?.displayText;if(text2){if(record.subtype==="agent_mention"&&!payload2?.author){items.push({type:"user",text:text2,sentToModel:false})}else{const name=payload2?.author?.name??record.agentName;items.push({type:"notification",text:name?`${name}: ${text2}`:text2})}}break}if(record.subtype==="mid_turn_user_message"){const payload2=record.systemPayload;const hasAttachmentReferences2=Array.isArray(payload2?.attachmentReferences)&&payload2.attachmentReferences.length>0;const text2=payload2?.displayText||(hasAttachmentReferences2?"[User message with attachments]":extractTextFromParts(record.message?.parts));if(text2){items.push({type:"user",text:text2,sentToModel:false})}break}if(pendingAtCommands.length>0){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}const payload2=pendingAtCommands.shift();const projection2=projectUserTranscriptForDisplay(record);const text2=payload2.userText||(projection2.displayText??extractTextFromParts(projection2.parts));if(text2){items.push({type:"user",text:text2,...promptId?{promptId}:{},...rewindId?{rewindId}:{}})}const toolDisplays=buildAtCommandDisplays(payload2);if(toolDisplays.length>0){items.push({type:"tool_group",tools:toolDisplays})}break}if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}const projection=projectUserTranscriptForDisplay(record);const payload=record.systemPayload;const hasAttachmentReferences=Array.isArray(payload?.attachmentReferences)&&payload.attachmentReferences.length>0;const text=projection.displayText||(hasAttachmentReferences?"[User message with attachments]":extractTextFromParts(projection.parts));if(text){items.push({type:"user",text,...promptId?{promptId}:{},...rewindId?{rewindId}:{}})}break}case"assistant":{const parts=record.message?.parts;const thoughtText=!config?extractThoughtTextFromParts(parts):"";const displayRuns=extractInlineContentRuns(parts,"\n");const functionCalls=extractFunctionCalls(parts);if(thoughtText){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}items.push({type:"gemini_thought",text:thoughtText})}if(displayRuns.length>0){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}for(const[index,run]of displayRuns.entries()){const type=index===0?"gemini":"gemini_content";const timestamp=index===0?{timestamp:new Date(record.timestamp).getTime()}:{};if(run.kind==="text"){items.push({type,text:run.text,...timestamp})}else if(run.kind==="image"){items.push({type,text:"",images:[run.image],...timestamp})}else{items.push({type,text:"",omittedImageCount:run.count,...timestamp})}}}for(const fc of functionCalls){const tool=getTool(config,fc.name);pendingToolCalls.set(fc.id,{name:fc.name,args:fc.args});currentToolGroup.push({callId:fc.id,name:tool?.displayName||fc.name,description:tool?formatToolDescription(tool,fc.args):"",args:fc.args,resultDisplay:void 0,status:"Error",confirmationDetails:void 0})}break}case"tool_result":{if(record.toolCallResult){const callId=record.toolCallResult.callId;const toolCall=currentToolGroup.find(t2=>t2.callId===callId);if(toolCall){const responseParts=record.toolCallResult.responseParts??record.message?.parts;const rawDisplay=record.toolCallResult.resultDisplay;toolCall.resultDisplay=rawDisplay;if(record.toolCallResult.visionBridgeNotice!==void 0){toolCall.visionBridgeNotice=record.toolCallResult.visionBridgeNotice}const rawStatus=record.toolCallResult["status"];toolCall.status=rawStatus==="error"?"Error":rawStatus==="cancelled"?"Canceled":"Success";const{images,omittedImageCount}=collectInlineImages(responseParts);if(images.length>0){toolCall.images=images}if(omittedImageCount>0){toolCall.omittedImageCount=omittedImageCount}if(toolCall.status==="Success"&&isCollapsibleTool(toolCall.name)){toolCall.detailedDisplay=getToolResponseDisplayText(responseParts)}}pendingToolCalls.delete(callId||"")}break}default:break}}if(pendingAtCommands.length>0){for(const payload of pendingAtCommands){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}const text=payload.userText;if(text){items.push({type:"user",text})}const toolDisplays=buildAtCommandDisplays(payload);if(toolDisplays.length>0){items.push({type:"tool_group",tools:toolDisplays})}}}if(currentToolGroup.length>0){items.push({type:"tool_group",tools:currentToolGroup})}return coalesceFindingsHistoryItems(items)}__name(convertToHistoryItems,"convertToHistoryItems");function buildResumedHistoryItems(sessionData,config,baseTimestamp=Date.now()){const items=[];let idCounter=1;const getNextId=__name(()=>baseTimestamp+idCounter++,"getNextId");const historyItems=convertToHistoryItems(sessionData.conversation,config,sessionData.historyGaps);for(const item of historyItems){items.push({...item,id:getNextId()})}return items}__name(buildResumedHistoryItems,"buildResumedHistoryItems");function applyResumeDisplayPolicy(items){return items.map(item=>({...item,display:{...item.display,suppressOnRestore:true}}))}__name(applyResumeDisplayPolicy,"applyResumeDisplayPolicy");function createHistoryCollapseSummaryItem(messageCount){const n=String(messageCount);return{type:"info",text:t("History collapsed: {{n}} messages hidden. Use /history expand-now to show.",{n}),display:{kind:"collapse-summary"}}}__name(createHistoryCollapseSummaryItem,"createHistoryCollapseSummaryItem");function stripSuppressOnRestore(item){if(!item.display?.suppressOnRestore)return item;const{suppressOnRestore:_,...rest}=item.display;return{...item,display:Object.keys(rest).length>0?rest:void 0}}__name(stripSuppressOnRestore,"stripSuppressOnRestore");function computeResumedPromptCountSeed(records,sessionId){const userTurnCount=records.filter(m=>m.type==="user"&&m.subtype!=="mid_turn_user_message"&&m.subtype!=="realtime_message").length;if(records.length===0){return 0}return Math.max(userTurnCount,computeInitialTurnFromHistory(records,sessionId)+1)}__name(computeResumedPromptCountSeed,"computeResumedPromptCountSeed");function expandCollapsedHistory(items){return items.filter(item=>item.display?.kind!=="collapse-summary").map(stripSuppressOnRestore)}__name(expandCollapsedHistory,"expandCollapsedHistory");function applyCollapsePolicyAndSummary(rawItems,collapseOnResume,collapsePreviewCount=0){if(!collapseOnResume)return rawItems;if(collapsePreviewCount===-1)return rawItems;let boundary=rawItems.length;if(collapsePreviewCount>0){let userTurnCount=0;for(let i=rawItems.length-1;i>=0;i--){const item=rawItems[i];if(item.type==="user"&&item.sentToModel!==false){userTurnCount++;if(userTurnCount===collapsePreviewCount){boundary=i;break}}}if(userTurnCount<collapsePreviewCount){boundary=0}}const hiddenItems=applyResumeDisplayPolicy(rawItems.slice(0,boundary));const visibleItems=rawItems.slice(boundary);const uiHistoryItems=[...hiddenItems,...visibleItems];if(boundary>0){const nextId=rawItems[rawItems.length-1].id+1;return[...uiHistoryItems,{id:nextId,...createHistoryCollapseSummaryItem(boundary)}]}return uiHistoryItems}__name(applyCollapsePolicyAndSummary,"applyCollapsePolicyAndSummary");export{SHELL_COMMAND_NAME,SHELL_NAME,TOOL_STATUS,ICON,SPINNER_FRAMES,SPINNER_INTERVAL_MS,WAITING_SPINNER_FRAME,isCollapsibleTool,getActiveToolHint,buildToolSummary,isSubagentToolEntry,isFindingsListDisplay,coalesceFindingsHistoryItems,recoalesceFindingsHistoryItems,shouldDisplayGoalStateCause,waitForGoalRuntime,buildResumedHistoryItems,stripSuppressOnRestore,computeResumedPromptCountSeed,expandCollapsedHistory,applyCollapsePolicyAndSummary};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2025 Google LLC
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{EXTENSION_CONTEXT_BUDGET,buildExtensionMentionContext,buildExtensionRef,getSanitizedExtensionDisplayName,matchExtensionByRef,parseExtensionRef,sanitizeDisplayText}from"./chunk-3W32X2DH.js";import{t}from"./chunk-NO7VTKRL.js";import{SessionReferenceService,readManyFiles}from"./chunk-OU7CEG7Q.js";import{emptyMcpResourceText,formatMcpResourceContents,summarizeMcpResource}from"./chunk-46VUDNCL.js";import{SessionService}from"./chunk-2JGTWRZJ.js";import{shouldRunVisionBridge}from"./chunk-ZWPSBU7K.js";import{Storage}from"./chunk-EPODBRBP.js";import{isSubpath,unescapePath,unescapeShellSpecials}from"./chunk-OKN3Z5C5.js";import{getErrorMessage,isNodeError}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs/promises";import*as path from"node:path";init_esbuild_shims();function matchMcpServerPrefix(input,serverNames){let serverName=null;for(const name of serverNames){if(input.startsWith(`${name}:`)&&(serverName===null||name.length>serverName.length)){serverName=name}}if(serverName===null)return null;return{serverName,rest:input.slice(serverName.length+1)}}__name(matchMcpServerPrefix,"matchMcpServerPrefix");function buildMcpResourceRef(serverName,uri){return`${serverName}:${uri}`}__name(buildMcpResourceRef,"buildMcpResourceRef");init_esbuild_shims();init_esbuild_shims();var MAX_SUGGESTIONS_TO_SHOW=8;var MAX_SUGGESTION_LABEL_WIDTH=150;function prepareSuggestionLabel(label,matchedIndex,userInput,isExpanded=false){const hasMatch=matchedIndex!==void 0&&matchedIndex>=0&&matchedIndex<label.length&&userInput.length>0;if(!hasMatch){return{before:!isExpanded&&label.length>MAX_SUGGESTION_LABEL_WIDTH?label.slice(0,MAX_SUGGESTION_LABEL_WIDTH)+"...":label,match:"",after:""}}const matchLength=userInput.length;let before="";let match="";let after="";if(isExpanded||label.length<=MAX_SUGGESTION_LABEL_WIDTH){before=label.slice(0,matchedIndex);match=label.slice(matchedIndex,matchedIndex+matchLength);after=label.slice(matchedIndex+matchLength)}else if(matchLength>=MAX_SUGGESTION_LABEL_WIDTH){match=label.slice(matchedIndex,matchedIndex+MAX_SUGGESTION_LABEL_WIDTH-1)+"..."}else{const contextSpace=MAX_SUGGESTION_LABEL_WIDTH-matchLength;const beforeSpace=Math.floor(contextSpace/2);const afterSpace=Math.ceil(contextSpace/2);let start=matchedIndex-beforeSpace;let end=matchedIndex+matchLength+afterSpace;if(start<0){end+=-start;start=0}if(end>label.length){start-=end-label.length;end=label.length}start=Math.max(0,start);const finalMatchIndex=matchedIndex-start;const slicedLabel=label.slice(start,end);before=slicedLabel.slice(0,finalMatchIndex);match=slicedLabel.slice(finalMatchIndex,finalMatchIndex+matchLength);after=slicedLabel.slice(finalMatchIndex+matchLength);if(start>0){before=before.length>=3?"..."+before.slice(3):"..."}if(end<label.length){after=after.length>=3?after.slice(0,-3)+"...":"..."}}return{before,match,after}}__name(prepareSuggestionLabel,"prepareSuggestionLabel");function normalizeDescription(description){return description.replace(/\s+/g," ").trim()}__name(normalizeDescription,"normalizeDescription");function getExtensionSuggestions(config,pattern){if(!config)return[];if(config.isTrustedFolder?.()===false)return[];const extensions=config.getActiveExtensions?.()??[];if(extensions.length===0)return[];const query=pattern.toLowerCase();return extensions.map(ext=>({ext,safeLabel:sanitizeDisplayText(ext.displayName||ext.name)||ext.name})).filter(({safeLabel,ext})=>{const label=safeLabel.toLowerCase();const name=ext.name.toLowerCase();return label.includes(query)||name.includes(query)}).sort((a,b)=>{const aName=a.safeLabel.toLowerCase();const bName=b.safeLabel.toLowerCase();const aPrefix=aName.startsWith(query)?0:1;const bPrefix=bName.startsWith(query)?0:1;if(aPrefix!==bPrefix)return aPrefix-bPrefix;return aName.localeCompare(bName)}).slice(0,MAX_SUGGESTIONS_TO_SHOW).map(({ext,safeLabel})=>({label:safeLabel,value:buildExtensionRef(ext.name),description:ext.config.description?sanitizeDisplayText(ext.config.description)??void 0:void 0,sourceBadge:t("Extension"),isDirectory:false,category:"extension"}))}__name(getExtensionSuggestions,"getExtensionSuggestions");init_esbuild_shims();var SESSION_MENTION_PREFIX="session:";var UUID_RE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function isSessionId(value){return UUID_RE.test(value.trim())}__name(isSessionId,"isSessionId");function parseSessionRef(pathName){if(!pathName.startsWith(SESSION_MENTION_PREFIX))return null;const rawRemainder=pathName.slice(SESSION_MENTION_PREFIX.length).trim();const remainder=process.platform==="win32"?unescapeShellSpecials(rawRemainder):rawRemainder;if(remainder.length===0)return null;return isSessionId(remainder)?{id:remainder}:{title:remainder}}__name(parseSessionRef,"parseSessionRef");function buildSessionRef(idOrTitle){return`${SESSION_MENTION_PREFIX}${idOrTitle}`}__name(buildSessionRef,"buildSessionRef");init_esbuild_shims();var MCP_SERVER_REF_PREFIX="mcp:";function parseMcpServerRef(pathName){if(!pathName.startsWith(MCP_SERVER_REF_PREFIX))return null;const name=pathName.slice(MCP_SERVER_REF_PREFIX.length);if(!name)return null;return{name}}__name(parseMcpServerRef,"parseMcpServerRef");function buildMcpServerRef(serverName){return`${MCP_SERVER_REF_PREFIX}${serverName}`}__name(buildMcpServerRef,"buildMcpServerRef");function matchMcpServerByRef(name,servers){const lower=name.toLowerCase();const matchedName=Object.keys(servers).find(serverName=>serverName.toLowerCase()===lower);if(!matchedName)return void 0;return{serverName:matchedName,server:servers[matchedName]}}__name(matchMcpServerByRef,"matchMcpServerByRef");function buildMcpServerContextText(config,serverName){const lines=[`--- MCP Server: ${serverName} ---`,`The user explicitly mentioned this MCP server. Prefer using tools and resources from this server when relevant for this turn. This is advisory context, not a hard restriction.`];const prompts=config.getPromptRegistry?.()?.getPromptsByServer(serverName)??[];const resources=config.getResourceRegistry?.()?.getResourcesByServer(serverName)??[];const details=[];if(resources.length>0){details.push(`- Resources: ${resources.length}`)}if(prompts.length>0){details.push(`- Prompts: ${prompts.length}`)}if(details.length>0){lines.push("Available capabilities from this MCP server:");lines.push(...details)}lines.push(`--- End MCP Server: ${serverName} ---`);return lines.join("\n")}__name(buildMcpServerContextText,"buildMcpServerContextText");function parseAllAtCommands(query){const parts=[];let currentIndex=0;while(currentIndex<query.length){let atIndex=-1;let nextSearchIndex=currentIndex;while(nextSearchIndex<query.length){if(query[nextSearchIndex]==="@"&&(nextSearchIndex===0||query[nextSearchIndex-1]!=="\\")){atIndex=nextSearchIndex;break}nextSearchIndex++}if(atIndex===-1){if(currentIndex<query.length){parts.push({type:"text",content:query.substring(currentIndex)})}break}if(atIndex>currentIndex){parts.push({type:"text",content:query.substring(currentIndex,atIndex)})}const isUrlRef=/^https?:\/\//i.test(query.slice(atIndex+1));const NON_URL_CHAR=/[^A-Za-z0-9\-._~:/?#[\]@!$&'()*+,;=%]/;let pathEndIndex=atIndex+1;let inEscape=false;while(pathEndIndex<query.length){const char=query[pathEndIndex];if(inEscape){inEscape=false}else if(char==="\\"){inEscape=true}else if(isUrlRef){if(NON_URL_CHAR.test(char))break}else if(/[,\s;!?()[\]{}]/.test(char)){break}else if(char==="."){const nextChar=pathEndIndex+1<query.length?query[pathEndIndex+1]:"";if(nextChar===""||/\s/.test(nextChar)){break}}pathEndIndex++}let rawAtPath=query.substring(atIndex,pathEndIndex);if(isUrlRef){const trimmed=rawAtPath.replace(/[.,;:!?]+$/,"");pathEndIndex=atIndex+trimmed.length;rawAtPath=trimmed}const atPath=unescapePath(rawAtPath);parts.push({type:"atPath",content:atPath});currentIndex=pathEndIndex}return parts.filter(part=>!(part.type==="text"&&part.content.trim()===""))}__name(parseAllAtCommands,"parseAllAtCommands");function extractAtPathCommands(query){return parseAllAtCommands(query).flatMap(part=>part.type==="atPath"&&part.content!=="@"?[part.content.substring(1)]:[])}__name(extractAtPathCommands,"extractAtPathCommands");function parseMcpResourceRef(pathName,mcpServerNames){const match=matchMcpServerPrefix(pathName,mcpServerNames);if(!match||!match.rest)return null;return{serverName:match.serverName,uri:match.rest}}__name(parseMcpResourceRef,"parseMcpResourceRef");async function resolveAtCommandQuery({query,config,onDebugMessage,messageId:userMessageTimestamp,signal}){const commandParts=parseAllAtCommands(query);const atPathCommandParts=commandParts.filter(part=>part.type==="atPath");if(atPathCommandParts.length===0){return{processedQuery:[{text:query}],shouldProceed:true}}const fileDiscovery=config.getFileService();const respectFileIgnore=config.getFileFilteringOptions();const configuredProjectTempDir=Storage.getGlobalTempDir();const projectTempDir=await fs.realpath(configuredProjectTempDir).catch(()=>path.resolve(configuredProjectTempDir));const pathSpecsToRead=[];const atPathToResolvedSpecMap=new Map;const contentLabelsForDisplay=[];const displayPaths=new Map;const displayPathsByCanonicalPath=new Map;const ignoredByReason={git:[],qwen:[],both:[]};const getIgnoreReason=__name(candidate=>{const gitIgnored=respectFileIgnore.respectGitIgnore&&fileDiscovery.shouldIgnoreFile(candidate,{respectGitIgnore:true,respectQwenIgnore:false});const qwenIgnored=respectFileIgnore.respectQwenIgnore&&fileDiscovery.shouldIgnoreFile(candidate,{respectGitIgnore:false,respectQwenIgnore:true});return gitIgnored&&qwenIgnored?"both":gitIgnored?"git":qwenIgnored?"qwen":void 0},"getIgnoreReason");const mcpServerNames=new Set(Object.keys(config.getMcpServers()||{}));const mcpResourceRefs=[];const mcpServerMentions=[];const activeExtensions=config.getActiveExtensions?.()??[];const extensionMentions=[];const sessionMentions=[];const urlMediaRefs=[];const rememberedMediaRefs=[];for(const atPathPart of atPathCommandParts){const originalAtPath=atPathPart.content;if(originalAtPath==="@"){onDebugMessage("Lone @ detected, will be treated as text in the modified query.");continue}const pathName=originalAtPath.substring(1);if(/^https?:\/\//i.test(pathName)&&config.isOmniEnabled?.()){const omni=await import("./omni-6YBX4R6K.js");if(omni.isOmniDeliveryActive(config)&&omni.parseHttpUrlRef(pathName)){if(!urlMediaRefs.some(r=>r.url===pathName)){urlMediaRefs.push({originalAtPath,url:pathName})}atPathToResolvedSpecMap.set(originalAtPath,pathName);continue}}const extRef=parseExtensionRef(pathName);if(extRef){const extension=matchExtensionByRef(extRef.name,activeExtensions);if(extension){if(!extensionMentions.some(m=>m.extension.name===extension.name)){extensionMentions.push({originalAtPath,extension})}atPathToResolvedSpecMap.set(originalAtPath,pathName);continue}onDebugMessage(`Extension "${extRef.name}" not found among active extensions. Available: ${activeExtensions.map(e=>e.name).join(", ")||"(none)"}`);continue}const sessionRef=parseSessionRef(pathName);if(sessionRef){if(!sessionMentions.some(m=>(m.ref.id??m.ref.title)===(sessionRef.id??sessionRef.title))){sessionMentions.push({originalAtPath,ref:sessionRef})}atPathToResolvedSpecMap.set(originalAtPath,buildSessionRef(sessionRef.id??sessionRef.title));continue}const resourceRef=parseMcpResourceRef(pathName,mcpServerNames);if(resourceRef){mcpResourceRefs.push({originalAtPath,...resourceRef});atPathToResolvedSpecMap.set(originalAtPath,pathName);continue}const mcpServerRef=parseMcpServerRef(pathName);if(mcpServerRef){const matched=matchMcpServerByRef(mcpServerRef.name,config.getMcpServers()||{});if(matched){if(!mcpServerMentions.some(m=>m.serverName===matched.serverName)){mcpServerMentions.push({originalAtPath,serverName:matched.serverName})}atPathToResolvedSpecMap.set(originalAtPath,buildMcpServerRef(matched.serverName));continue}onDebugMessage(`MCP server "${mcpServerRef.name}" not found among configured MCP servers. Available: ${Object.keys(config.getMcpServers()||{}).join(", ")||"(none)"}`);continue}const workspaceContext=config.getWorkspaceContext();const absolutePathName=path.isAbsolute(pathName)?pathName:path.resolve(workspaceContext.getDirectories()[0]||"",pathName);if(!isSubpath(configuredProjectTempDir,absolutePathName)&&!isSubpath(projectTempDir,absolutePathName)&&!workspaceContext.isPathWithinWorkspace(pathName)){onDebugMessage(`Path ${pathName} is not in the workspace and will be skipped.`);continue}const ignoredReason=getIgnoreReason(pathName);if(ignoredReason){const reason=ignoredReason;ignoredByReason[reason].push(pathName);const reasonText=reason==="both"?"ignored by both git and qwen":reason==="git"?"git-ignored":"qwen-ignored";onDebugMessage(`Path ${pathName} is ${reasonText} and will be skipped.`);continue}let resolvedSuccessfully=false;let sawNotFound=false;let deferredIgnoreReason;for(const dir of config.getWorkspaceContext().getDirectories()){try{const absolutePath=path.resolve(dir,pathName);const canonicalPath=await fs.realpath(absolutePath);const stats=await fs.stat(canonicalPath);if(!isSubpath(configuredProjectTempDir,canonicalPath)&&!isSubpath(projectTempDir,canonicalPath)&&!workspaceContext.isPathWithinWorkspace(canonicalPath)){onDebugMessage(`Path ${pathName} is not in the workspace and will be skipped.`);continue}const canonicalIgnoreReason=getIgnoreReason(canonicalPath);if(canonicalIgnoreReason){deferredIgnoreReason=canonicalIgnoreReason;const reasonText=canonicalIgnoreReason==="both"?"ignored by both git and qwen":canonicalIgnoreReason==="git"?"git-ignored":"qwen-ignored";onDebugMessage(`Path ${pathName} is ${reasonText} and will be skipped.`);continue}if(stats.isDirectory()){onDebugMessage(`Path ${pathName} resolved to directory.`)}else{onDebugMessage(`Path ${pathName} resolved to file: ${absolutePath}`)}pathSpecsToRead.push(canonicalPath);atPathToResolvedSpecMap.set(originalAtPath,pathName);contentLabelsForDisplay.push(pathName);displayPaths.set(canonicalPath,pathName);const canonicalDisplays=displayPathsByCanonicalPath.get(canonicalPath)??new Set;canonicalDisplays.add(pathName);displayPathsByCanonicalPath.set(canonicalPath,canonicalDisplays);resolvedSuccessfully=true}catch(error){if(isNodeError(error)&&error.code==="ENOENT"){sawNotFound=true;continue}else{onDebugMessage(`Error stating path ${pathName}: ${getErrorMessage(error)}. Path ${pathName} will be skipped.`)}}if(resolvedSuccessfully){break}}if(!resolvedSuccessfully&&sawNotFound){let reanchored=false;if(config.isOmniEnabled?.()){const{reanchorRememberedMedia}=await import("./omni-6YBX4R6K.js");for(const dir of config.getWorkspaceContext().getDirectories()){const anchor=await reanchorRememberedMedia(config,path.resolve(dir,pathName));if(!anchor)continue;rememberedMediaRefs.push({originalAtPath,pathName,annotation:anchor.annotation});atPathToResolvedSpecMap.set(originalAtPath,pathName);onDebugMessage(`Path ${pathName} is gone but remembered; re-anchored as ${anchor.resourceId} (bytes unavailable).`);reanchored=true;break}}if(!reanchored){onDebugMessage(`Path ${pathName} not found. Path ${pathName} will be skipped.`)}}if(!resolvedSuccessfully&&deferredIgnoreReason){ignoredByReason[deferredIgnoreReason].push(pathName)}}const buildInitialQueryText=__name(()=>{let text="";for(let i=0;i<commandParts.length;i++){const part=commandParts[i];if(part.type==="text"){text+=part.content}else{const resolvedSpec=atPathToResolvedSpecMap.get(part.content);if(i>0&&text.length>0&&!text.endsWith(" ")){const prevPart=commandParts[i-1];if(prevPart.type==="text"||prevPart.type==="atPath"){text+=" "}}if(resolvedSpec){text+=`@${resolvedSpec}`}else{if(i>0&&text.length>0&&!text.endsWith(" ")&&!part.content.startsWith(" ")){text+=" "}text+=part.content}}}return text.trim()},"buildInitialQueryText");let initialQueryText=buildInitialQueryText();const totalIgnored=ignoredByReason["git"].length+ignoredByReason["qwen"].length+ignoredByReason["both"].length;if(totalIgnored>0){const messages=[];if(ignoredByReason["git"].length){messages.push(`Git-ignored: ${ignoredByReason["git"].join(", ")}`)}if(ignoredByReason["qwen"].length){messages.push(`Qwen-ignored: ${ignoredByReason["qwen"].join(", ")}`)}if(ignoredByReason["both"].length){messages.push(`Ignored by both: ${ignoredByReason["both"].join(", ")}`)}const message=`Ignored ${totalIgnored} files:
|
|
4
|
-
${messages.join("\n")}`;onDebugMessage(message)}const resourceReads=await Promise.allSettled(mcpResourceRefs.map(ref=>config.getToolRegistry().readMcpResource(ref.serverName,ref.uri,{signal})));const urlMediaParts=[];const urlMediaDisplays=[];const urlMediaLabels=[];if(urlMediaRefs.length>0){const core=await import("./omni-6YBX4R6K.js");for(let i=0;i<urlMediaRefs.length;i++){const ref=urlMediaRefs[i];const callId=`client-url-media-${userMessageTimestamp}-${i}`;const hostLabel=(()=>{try{return new URL(ref.url).hostname}catch{return"invalid-url"}})();let tempPartPath;try{const store=new core.OmniObjectStore(config.storage.getQwenDir());const downloadsDir=path.join(store.getOmniRootDir(),"downloads");const downloaded=await core.downloadMediaUrl({url:ref.url,downloadsDir,maxBytes:core.effectiveMaxDownloadFileBytes(config),signal});tempPartPath=downloaded.partPath;const urlBase=path.basename(new URL(ref.url).pathname)||hostLabel;const modalities=config.getContentGeneratorConfig?.()?.modalities??{};const sniffedModality=await core.sniffFileModality(downloaded.partPath);if(sniffedModality&&!modalities[sniffedModality]){urlMediaDisplays.push({callId,name:"Fetch Media URL",description:`Download ${ref.url}`,status:"Error",resultDisplay:`Skipped ${urlBase}: the active model does not accept ${sniffedModality} input.`,confirmationDetails:void 0});continue}const delivery=await core.processMediaForOmniDelivery(downloaded.partPath,config,{signal,displayName:urlBase,sourceUrl:ref.url});const transcriptParts=core.buildTranscriptParts(urlBase,delivery.transcripts);const additionalParts=core.buildAdditionalMediaParts(urlBase,delivery.additionalMedia);const handleParts=delivery.resourceId?[{text:core.formatResourceHandleText(urlBase,delivery.resourceId)}]:[];if(delivery.omission){urlMediaParts.push(...handleParts);urlMediaParts.push({text:core.formatOmissionText(urlBase,delivery.omission.reason)});urlMediaParts.push(...additionalParts);urlMediaParts.push(...transcriptParts);urlMediaLabels.push(ref.url);urlMediaDisplays.push({callId,name:"Fetch Media URL",description:`Downloaded ${ref.url}`,status:"Success",resultDisplay:`Media omitted by the omni transport guard: ${urlBase}`,confirmationDetails:void 0});continue}if(!delivery.fileUri&&transcriptParts.length>0){urlMediaParts.push(...handleParts);if(delivery.disclosure){urlMediaParts.push({text:core.formatDisclosureText(urlBase,delivery.disclosure)})}urlMediaParts.push(...additionalParts);urlMediaParts.push(...transcriptParts);urlMediaLabels.push(ref.url);urlMediaDisplays.push({callId,name:"Fetch Media URL",description:`Downloaded ${ref.url}`,status:"Success",resultDisplay:`Localized ${urlBase} and delivered as transcript (omni policy).`,confirmationDetails:void 0});continue}urlMediaParts.push(...handleParts);if(delivery.disclosure){urlMediaParts.push({text:core.formatDisclosureText(urlBase,delivery.disclosure)})}urlMediaParts.push({fileData:{fileUri:delivery.fileUri,mimeType:delivery.mimeType,displayName:urlBase}});urlMediaParts.push(...additionalParts);urlMediaParts.push(...transcriptParts);urlMediaLabels.push(ref.url);urlMediaDisplays.push({callId,name:"Fetch Media URL",description:`Downloaded ${ref.url}`,status:"Success",resultDisplay:`Localized ${urlBase} (${delivery.recognized.modality}, ${(delivery.recognized.sizeBytes/1024/1024).toFixed(1)}MB) and delivered via omni upload${delivery.degraded?" (degraded by media policy)":""}.`,confirmationDetails:void 0})}catch(error){if(signal.aborted){if(tempPartPath){await fs.rm(tempPartPath,{force:true}).catch(()=>{})}return{processedQuery:null,shouldProceed:false,toolDisplays:[...urlMediaDisplays],filesRead:urlMediaLabels}}const reason=getErrorMessage(error);onDebugMessage(`Failed to localize media URL ${ref.url}: ${reason}`);urlMediaDisplays.push({callId,name:"Fetch Media URL",description:`Download ${ref.url}`,status:"Error",resultDisplay:`Failed to fetch media from ${hostLabel}: ${reason}`,confirmationDetails:void 0})}finally{if(tempPartPath){await fs.rm(tempPartPath,{force:true}).catch(()=>{})}}}}const resourceParts=[];const resourceDisplays=[];const resourceLabels=[];for(let i=0;i<mcpResourceRefs.length;i++){const ref=mcpResourceRefs[i];const label=`${ref.serverName}:${ref.uri}`;const callId=`client-mcp-resource-${userMessageTimestamp}-${i}`;const outcome=resourceReads[i];if(outcome.status==="rejected"){onDebugMessage(`Failed to read MCP resource ${label}: ${getErrorMessage(outcome.reason)}`);resourceDisplays.push({callId,name:"Read MCP Resource",description:`Read resource ${label}`,status:"Error",resultDisplay:`Failed to read resource ${label}: ${getErrorMessage(outcome.reason)}`,confirmationDetails:void 0});continue}const formatted=formatMcpResourceContents(outcome.value,label);if(formatted.parts.length>0){resourceParts.push(...formatted.parts)}else{resourceParts.push({text:emptyMcpResourceText(formatted,label)})}resourceLabels.push(label);resourceDisplays.push({callId,name:"Read MCP Resource",description:`Read resource ${label}`,status:"Success",resultDisplay:summarizeMcpResource(formatted),confirmationDetails:void 0})}if(pathSpecsToRead.length===0&&mcpResourceRefs.length===0&&mcpServerMentions.length===0&&extensionMentions.length===0&&sessionMentions.length===0&&urlMediaRefs.length===0){onDebugMessage("No valid file paths found in @ commands to read.");if(initialQueryText==="@"&&query.trim()==="@"){return{processedQuery:[{text:query}],shouldProceed:true}}else if(!initialQueryText&&query){return{processedQuery:[{text:query}],shouldProceed:true}}return{processedQuery:[{text:initialQueryText||query}],shouldProceed:true}}let extensionContextBudgetRemaining=EXTENSION_CONTEXT_BUDGET;const scopedMentionEntries=[];for(let i=0;i<extensionMentions.length;i++){const{originalAtPath,extension}=extensionMentions[i];const displayName=getSanitizedExtensionDisplayName(extension);const callId=`client-extension-${userMessageTimestamp}-${i}`;const context=await buildExtensionMentionContext(extension,{remainingBudget:extensionContextBudgetRemaining,signal,onDebugMessage});extensionContextBudgetRemaining=context.remainingBudget;scopedMentionEntries.push({originalAtPath,part:{text:context.text},label:buildExtensionRef(extension.name),display:{callId,name:"Activate Extension",description:`Activated extension ${displayName}`,status:"Success",resultDisplay:void 0,confirmationDetails:void 0}})}for(let i=0;i<mcpServerMentions.length;i++){const{originalAtPath,serverName}=mcpServerMentions[i];scopedMentionEntries.push({originalAtPath,part:{text:buildMcpServerContextText(config,serverName)},label:buildMcpServerRef(serverName),display:{callId:`client-mcp-server-${userMessageTimestamp}-${i}`,name:"Activate MCP Server",description:`Activated MCP server ${serverName}`,status:"Success",resultDisplay:void 0,confirmationDetails:void 0}})}const resolvedSessionIds=new Set;for(let i=0;i<sessionMentions.length;i++){const{originalAtPath,ref}=sessionMentions[i];const callId=`client-session-${userMessageTimestamp}-${i}`;let sessionId=ref.id;if(!sessionId&&ref.title){let matches=[];try{matches=await new SessionService(config.getProjectRoot()).findSessionsByTitle(ref.title)}catch(error){const reason=`Could not look up sessions matching "@${originalAtPath.substring(1)}" (${getErrorMessage(error)}); try a session id instead.`;onDebugMessage(reason);scopedMentionEntries.push({originalAtPath,part:{text:""},label:buildSessionRef(ref.title??originalAtPath),display:{callId,name:"Referenced Session",description:`Reference session "${ref.title??""}"`,status:"Error",resultDisplay:reason,confirmationDetails:void 0}});continue}if(matches.length===1){sessionId=matches[0].sessionId}else{const reason=matches.length===0?`No session matches "@${originalAtPath.substring(1)}".`:`"@${originalAtPath.substring(1)}" is ambiguous (${matches.length} matches); use the picker or a session id.`;onDebugMessage(reason);scopedMentionEntries.push({originalAtPath,part:{text:""},label:buildSessionRef(ref.title),display:{callId,name:"Referenced Session",description:`Reference session "${ref.title}"`,status:"Error",resultDisplay:reason,confirmationDetails:void 0}});continue}}if(!sessionId){const reason=`Session reference "@${originalAtPath.substring(1)}" could not be resolved.`;onDebugMessage(reason);scopedMentionEntries.push({originalAtPath,part:{text:""},label:buildSessionRef(ref.title??ref.id??originalAtPath),display:{callId,name:"Referenced Session",description:`Reference session "${ref.title??ref.id??""}"`,status:"Error",resultDisplay:reason,confirmationDetails:void 0}});continue}if(resolvedSessionIds.has(sessionId)){onDebugMessage(`Session reference "@${originalAtPath.substring(1)}" resolves to session ${sessionId}, which was already referenced; skipping duplicate.`);continue}resolvedSessionIds.add(sessionId);let resolved;try{resolved=await new SessionReferenceService(config.getProjectRoot()).resolve(sessionId,ref.title?{title:ref.title}:{})}catch(error){const reason=`Failed to load session "${sessionId}" (${getErrorMessage(error)}); the transcript may be corrupted or unreadable.`;onDebugMessage(reason);scopedMentionEntries.push({originalAtPath,part:{text:""},label:buildSessionRef(sessionId),display:{callId,name:"Referenced Session",description:`Reference session ${sessionId}`,status:"Error",resultDisplay:reason,confirmationDetails:void 0}});continue}if("notFound"in resolved){const reason=`Session "${sessionId}" not found in this project.`;onDebugMessage(reason);scopedMentionEntries.push({originalAtPath,part:{text:""},label:buildSessionRef(sessionId),display:{callId,name:"Referenced Session",description:`Reference session ${sessionId}`,status:"Error",resultDisplay:reason,confirmationDetails:void 0}});continue}scopedMentionEntries.push({originalAtPath,part:{text:resolved.text},label:buildSessionRef(sessionId),display:{callId,name:"Referenced Session",description:`Referenced session "${resolved.meta.title}"${resolved.truncated?" (truncated)":""}`,status:"Success",resultDisplay:void 0,confirmationDetails:void 0}})}const scopedMentionOrder=new Map(atPathCommandParts.map((part,index)=>[part.content,index]));scopedMentionEntries.sort((a,b)=>(scopedMentionOrder.get(a.originalAtPath)??Number.MAX_SAFE_INTEGER)-(scopedMentionOrder.get(b.originalAtPath)??Number.MAX_SAFE_INTEGER));const scopedMentionParts=scopedMentionEntries.map(entry=>entry.part);const scopedMentionLabels=scopedMentionEntries.map(entry=>entry.label);const scopedMentionDisplays=scopedMentionEntries.map(entry=>entry.display);const fileParts=[];let fileDisplays=[];const revalidatedPathSpecs=[];const revalidatedDisplayPaths=new Map;const validatedPathIdentities=new Map;const pruneSkippedPath=__name(approvedPath=>{const displayPath=displayPaths.get(approvedPath);const displayLabels=displayPathsByCanonicalPath.get(approvedPath)??new Set(displayPath?[displayPath]:[]);for(const[originalAtPath,resolvedSpec]of atPathToResolvedSpecMap){if(resolvedSpec===approvedPath||displayLabels.has(resolvedSpec)){atPathToResolvedSpecMap.delete(originalAtPath)}}for(let index=contentLabelsForDisplay.length-1;index>=0;index--){const label=contentLabelsForDisplay[index];if(label===approvedPath||displayLabels.has(label)){contentLabelsForDisplay.splice(index,1)}}},"pruneSkippedPath");for(const approvedPath of pathSpecsToRead){try{const currentPath=await fs.realpath(approvedPath);const stats=await fs.stat(currentPath);if(currentPath===approvedPath&&(stats.isFile()||stats.isDirectory())&&(isSubpath(configuredProjectTempDir,currentPath)||isSubpath(projectTempDir,currentPath)||config.getWorkspaceContext().isPathWithinWorkspace(currentPath))&&getIgnoreReason(currentPath)===void 0){revalidatedPathSpecs.push(currentPath);const displayPath=displayPaths.get(approvedPath);if(displayPath)revalidatedDisplayPaths.set(currentPath,displayPath);validatedPathIdentities.set(currentPath,{dev:stats.dev,ino:stats.ino})}else{pruneSkippedPath(approvedPath);onDebugMessage(`Path ${approvedPath} failed revalidation and will be skipped.`)}}catch{pruneSkippedPath(approvedPath);onDebugMessage(`Path ${approvedPath} changed before it could be read and will be skipped.`)}}initialQueryText=buildInitialQueryText();if(revalidatedPathSpecs.length>0){try{const result=await readManyFiles(config,{paths:revalidatedPathSpecs,signal,preserveUnsupportedImageForBridge:shouldRunVisionBridge(config),validatedPathIdentities,displayPaths:revalidatedDisplayPaths});const parts=Array.isArray(result.contentParts)?result.contentParts:[result.contentParts];fileDisplays=result.files.map((file,index)=>({callId:`client-read-${userMessageTimestamp}-${index}`,name:file.isDirectory?"Read Directory":"Read File",description:`@${path.basename(file.filePath)}`,status:file.error?"Error":"Success",resultDisplay:file.error?`Failed to read ${path.basename(file.filePath)}: ${file.error}`:void 0,confirmationDetails:void 0}));if(parts.length>0&&!result.error){for(const part of parts){fileParts.push(typeof part==="string"?{text:part}:part)}}else{onDebugMessage("readManyFiles returned no content or empty content.")}}catch(error){const errorToolCallDisplay={callId:`client-read-${userMessageTimestamp}`,name:"Read File(s)",description:"Error attempting to read files",status:"Error",resultDisplay:`Error reading files (${contentLabelsForDisplay.join(", ")}): ${getErrorMessage(error)}`,confirmationDetails:void 0};const errorMessage=typeof errorToolCallDisplay.resultDisplay==="string"?errorToolCallDisplay.resultDisplay:void 0;const labelsOnError=[...scopedMentionLabels,...contentLabelsForDisplay,...resourceLabels,...urlMediaLabels];return{processedQuery:null,shouldProceed:false,toolDisplays:[...scopedMentionDisplays,...resourceDisplays,...urlMediaDisplays,errorToolCallDisplay],filesRead:labelsOnError,recording:{filesRead:labelsOnError,status:"error",message:errorMessage}}}}const rememberedMediaParts=rememberedMediaRefs.flatMap(ref=>[{text:ref.annotation},{text:`\u3010\u5A92\u4F53\u7F3A\u5931\u3011${ref.pathName}\uFF1A\u6587\u4EF6\u5DF2\u4E0D\u5728\u78C1\u76D8\u4E0A\uFF0C\u65E0\u6CD5\u6295\u9012\u753B\u9762/\u97F3\u9891\u3002\u5176\u5904\u7406\u8BB0\u5FC6\u4ECD\u53EF\u7528\u2014\u2014\u7528\u4E0A\u9762\u7684\u53E5\u67C4\u8C03\u7528 omni_recall_media_memory \u53D6\u56DE\u3002`}]);const processedQueryParts=[{text:initialQueryText},...scopedMentionParts,...fileParts,...resourceParts,...urlMediaParts,...rememberedMediaParts];const allLabels=[...scopedMentionLabels,...contentLabelsForDisplay,...resourceLabels,...urlMediaLabels,...rememberedMediaRefs.map(ref=>`${ref.pathName} (\u8BB0\u5FC6)`)];return{processedQuery:processedQueryParts,shouldProceed:true,toolDisplays:[...scopedMentionDisplays,...fileDisplays,...resourceDisplays,...urlMediaDisplays],filesRead:allLabels,recording:{filesRead:allLabels,status:"success"}}}__name(resolveAtCommandQuery,"resolveAtCommandQuery");async function handleAtCommand(params){const result=await resolveAtCommandQuery(params);if(result.recording){const chatRecorder=params.config.getChatRecordingService?.();chatRecorder?.recordAtCommand({filesRead:result.recording.filesRead,status:result.recording.status,...result.recording.message?{message:result.recording.message}:{},userText:params.query})}if(params.addItem&&result.toolDisplays&&result.toolDisplays.length>0){const toolGroupItem={type:"tool_group",tools:result.toolDisplays};params.addItem(toolGroupItem,params.messageId)}return{processedQuery:result.processedQuery,shouldProceed:result.shouldProceed,toolDisplays:result.toolDisplays,filesRead:result.filesRead}}__name(handleAtCommand,"handleAtCommand");export{matchMcpServerPrefix,buildMcpResourceRef,MAX_SUGGESTIONS_TO_SHOW,MAX_SUGGESTION_LABEL_WIDTH,prepareSuggestionLabel,normalizeDescription,getExtensionSuggestions,SESSION_MENTION_PREFIX,buildSessionRef,parseMcpServerRef,buildMcpServerRef,matchMcpServerByRef,buildMcpServerContextText,extractAtPathCommands,resolveAtCommandQuery,handleAtCommand};
|
|
3
|
+
import{EXTENSION_CONTEXT_BUDGET,buildExtensionMentionContext,buildExtensionRef,getSanitizedExtensionDisplayName,matchExtensionByRef,parseExtensionRef,sanitizeDisplayText}from"./chunk-UTTSBCFR.js";import{t}from"./chunk-NO7VTKRL.js";import{SessionReferenceService,readManyFiles}from"./chunk-G2LTZU67.js";import{emptyMcpResourceText,formatMcpResourceContents,summarizeMcpResource}from"./chunk-46VUDNCL.js";import{SessionService}from"./chunk-7XQ5D34E.js";import{shouldRunVisionBridge}from"./chunk-ZWPSBU7K.js";import{Storage}from"./chunk-EPODBRBP.js";import{isSubpath,unescapePath,unescapeShellSpecials}from"./chunk-OKN3Z5C5.js";import{getErrorMessage,isNodeError}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs/promises";import*as path from"node:path";init_esbuild_shims();function matchMcpServerPrefix(input,serverNames){let serverName=null;for(const name of serverNames){if(input.startsWith(`${name}:`)&&(serverName===null||name.length>serverName.length)){serverName=name}}if(serverName===null)return null;return{serverName,rest:input.slice(serverName.length+1)}}__name(matchMcpServerPrefix,"matchMcpServerPrefix");function buildMcpResourceRef(serverName,uri){return`${serverName}:${uri}`}__name(buildMcpResourceRef,"buildMcpResourceRef");init_esbuild_shims();init_esbuild_shims();var MAX_SUGGESTIONS_TO_SHOW=8;var MAX_SUGGESTION_LABEL_WIDTH=150;function prepareSuggestionLabel(label,matchedIndex,userInput,isExpanded=false){const hasMatch=matchedIndex!==void 0&&matchedIndex>=0&&matchedIndex<label.length&&userInput.length>0;if(!hasMatch){return{before:!isExpanded&&label.length>MAX_SUGGESTION_LABEL_WIDTH?label.slice(0,MAX_SUGGESTION_LABEL_WIDTH)+"...":label,match:"",after:""}}const matchLength=userInput.length;let before="";let match="";let after="";if(isExpanded||label.length<=MAX_SUGGESTION_LABEL_WIDTH){before=label.slice(0,matchedIndex);match=label.slice(matchedIndex,matchedIndex+matchLength);after=label.slice(matchedIndex+matchLength)}else if(matchLength>=MAX_SUGGESTION_LABEL_WIDTH){match=label.slice(matchedIndex,matchedIndex+MAX_SUGGESTION_LABEL_WIDTH-1)+"..."}else{const contextSpace=MAX_SUGGESTION_LABEL_WIDTH-matchLength;const beforeSpace=Math.floor(contextSpace/2);const afterSpace=Math.ceil(contextSpace/2);let start=matchedIndex-beforeSpace;let end=matchedIndex+matchLength+afterSpace;if(start<0){end+=-start;start=0}if(end>label.length){start-=end-label.length;end=label.length}start=Math.max(0,start);const finalMatchIndex=matchedIndex-start;const slicedLabel=label.slice(start,end);before=slicedLabel.slice(0,finalMatchIndex);match=slicedLabel.slice(finalMatchIndex,finalMatchIndex+matchLength);after=slicedLabel.slice(finalMatchIndex+matchLength);if(start>0){before=before.length>=3?"..."+before.slice(3):"..."}if(end<label.length){after=after.length>=3?after.slice(0,-3)+"...":"..."}}return{before,match,after}}__name(prepareSuggestionLabel,"prepareSuggestionLabel");function normalizeDescription(description){return description.replace(/\s+/g," ").trim()}__name(normalizeDescription,"normalizeDescription");function getExtensionSuggestions(config,pattern){if(!config)return[];if(config.isTrustedFolder?.()===false)return[];const extensions=config.getActiveExtensions?.()??[];if(extensions.length===0)return[];const query=pattern.toLowerCase();return extensions.map(ext=>({ext,safeLabel:sanitizeDisplayText(ext.displayName||ext.name)||ext.name})).filter(({safeLabel,ext})=>{const label=safeLabel.toLowerCase();const name=ext.name.toLowerCase();return label.includes(query)||name.includes(query)}).sort((a,b)=>{const aName=a.safeLabel.toLowerCase();const bName=b.safeLabel.toLowerCase();const aPrefix=aName.startsWith(query)?0:1;const bPrefix=bName.startsWith(query)?0:1;if(aPrefix!==bPrefix)return aPrefix-bPrefix;return aName.localeCompare(bName)}).slice(0,MAX_SUGGESTIONS_TO_SHOW).map(({ext,safeLabel})=>({label:safeLabel,value:buildExtensionRef(ext.name),description:ext.config.description?sanitizeDisplayText(ext.config.description)??void 0:void 0,sourceBadge:t("Extension"),isDirectory:false,category:"extension"}))}__name(getExtensionSuggestions,"getExtensionSuggestions");init_esbuild_shims();var SESSION_MENTION_PREFIX="session:";var UUID_RE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function isSessionId(value){return UUID_RE.test(value.trim())}__name(isSessionId,"isSessionId");function parseSessionRef(pathName){if(!pathName.startsWith(SESSION_MENTION_PREFIX))return null;const rawRemainder=pathName.slice(SESSION_MENTION_PREFIX.length).trim();const remainder=process.platform==="win32"?unescapeShellSpecials(rawRemainder):rawRemainder;if(remainder.length===0)return null;return isSessionId(remainder)?{id:remainder}:{title:remainder}}__name(parseSessionRef,"parseSessionRef");function buildSessionRef(idOrTitle){return`${SESSION_MENTION_PREFIX}${idOrTitle}`}__name(buildSessionRef,"buildSessionRef");init_esbuild_shims();var MCP_SERVER_REF_PREFIX="mcp:";function parseMcpServerRef(pathName){if(!pathName.startsWith(MCP_SERVER_REF_PREFIX))return null;const name=pathName.slice(MCP_SERVER_REF_PREFIX.length);if(!name)return null;return{name}}__name(parseMcpServerRef,"parseMcpServerRef");function buildMcpServerRef(serverName){return`${MCP_SERVER_REF_PREFIX}${serverName}`}__name(buildMcpServerRef,"buildMcpServerRef");function matchMcpServerByRef(name,servers){const lower=name.toLowerCase();const matchedName=Object.keys(servers).find(serverName=>serverName.toLowerCase()===lower);if(!matchedName)return void 0;return{serverName:matchedName,server:servers[matchedName]}}__name(matchMcpServerByRef,"matchMcpServerByRef");function buildMcpServerContextText(config,serverName){const lines=[`--- MCP Server: ${serverName} ---`,`The user explicitly mentioned this MCP server. Prefer using tools and resources from this server when relevant for this turn. This is advisory context, not a hard restriction.`];const prompts=config.getPromptRegistry?.()?.getPromptsByServer(serverName)??[];const resources=config.getResourceRegistry?.()?.getResourcesByServer(serverName)??[];const details=[];if(resources.length>0){details.push(`- Resources: ${resources.length}`)}if(prompts.length>0){details.push(`- Prompts: ${prompts.length}`)}if(details.length>0){lines.push("Available capabilities from this MCP server:");lines.push(...details)}lines.push(`--- End MCP Server: ${serverName} ---`);return lines.join("\n")}__name(buildMcpServerContextText,"buildMcpServerContextText");function parseAllAtCommands(query){const parts=[];let currentIndex=0;while(currentIndex<query.length){let atIndex=-1;let nextSearchIndex=currentIndex;while(nextSearchIndex<query.length){if(query[nextSearchIndex]==="@"&&(nextSearchIndex===0||query[nextSearchIndex-1]!=="\\")){atIndex=nextSearchIndex;break}nextSearchIndex++}if(atIndex===-1){if(currentIndex<query.length){parts.push({type:"text",content:query.substring(currentIndex)})}break}if(atIndex>currentIndex){parts.push({type:"text",content:query.substring(currentIndex,atIndex)})}const isUrlRef=/^https?:\/\//i.test(query.slice(atIndex+1));const NON_URL_CHAR=/[^A-Za-z0-9\-._~:/?#[\]@!$&'()*+,;=%]/;let pathEndIndex=atIndex+1;let inEscape=false;while(pathEndIndex<query.length){const char=query[pathEndIndex];if(inEscape){inEscape=false}else if(char==="\\"){inEscape=true}else if(isUrlRef){if(NON_URL_CHAR.test(char))break}else if(/[,\s;!?()[\]{}]/.test(char)){break}else if(char==="."){const nextChar=pathEndIndex+1<query.length?query[pathEndIndex+1]:"";if(nextChar===""||/\s/.test(nextChar)){break}}pathEndIndex++}let rawAtPath=query.substring(atIndex,pathEndIndex);if(isUrlRef){const trimmed=rawAtPath.replace(/[.,;:!?]+$/,"");pathEndIndex=atIndex+trimmed.length;rawAtPath=trimmed}const atPath=unescapePath(rawAtPath);parts.push({type:"atPath",content:atPath});currentIndex=pathEndIndex}return parts.filter(part=>!(part.type==="text"&&part.content.trim()===""))}__name(parseAllAtCommands,"parseAllAtCommands");function extractAtPathCommands(query){return parseAllAtCommands(query).flatMap(part=>part.type==="atPath"&&part.content!=="@"?[part.content.substring(1)]:[])}__name(extractAtPathCommands,"extractAtPathCommands");function parseMcpResourceRef(pathName,mcpServerNames){const match=matchMcpServerPrefix(pathName,mcpServerNames);if(!match||!match.rest)return null;return{serverName:match.serverName,uri:match.rest}}__name(parseMcpResourceRef,"parseMcpResourceRef");async function resolveAtCommandQuery({query,config,onDebugMessage,messageId:userMessageTimestamp,signal}){const commandParts=parseAllAtCommands(query);const atPathCommandParts=commandParts.filter(part=>part.type==="atPath");if(atPathCommandParts.length===0){return{processedQuery:[{text:query}],shouldProceed:true}}const fileDiscovery=config.getFileService();const respectFileIgnore=config.getFileFilteringOptions();const configuredProjectTempDir=Storage.getGlobalTempDir();const projectTempDir=await fs.realpath(configuredProjectTempDir).catch(()=>path.resolve(configuredProjectTempDir));const pathSpecsToRead=[];const atPathToResolvedSpecMap=new Map;const contentLabelsForDisplay=[];const displayPaths=new Map;const displayPathsByCanonicalPath=new Map;const ignoredByReason={git:[],qwen:[],both:[]};const getIgnoreReason=__name(candidate=>{const gitIgnored=respectFileIgnore.respectGitIgnore&&fileDiscovery.shouldIgnoreFile(candidate,{respectGitIgnore:true,respectQwenIgnore:false});const qwenIgnored=respectFileIgnore.respectQwenIgnore&&fileDiscovery.shouldIgnoreFile(candidate,{respectGitIgnore:false,respectQwenIgnore:true});return gitIgnored&&qwenIgnored?"both":gitIgnored?"git":qwenIgnored?"qwen":void 0},"getIgnoreReason");const mcpServerNames=new Set(Object.keys(config.getMcpServers()||{}));const mcpResourceRefs=[];const mcpServerMentions=[];const activeExtensions=config.getActiveExtensions?.()??[];const extensionMentions=[];const sessionMentions=[];const urlMediaRefs=[];const rememberedMediaRefs=[];for(const atPathPart of atPathCommandParts){const originalAtPath=atPathPart.content;if(originalAtPath==="@"){onDebugMessage("Lone @ detected, will be treated as text in the modified query.");continue}const pathName=originalAtPath.substring(1);if(/^https?:\/\//i.test(pathName)&&config.isOmniEnabled?.()){const omni=await import("./omni-DNZGITTE.js");if(omni.isOmniDeliveryActive(config)&&omni.parseHttpUrlRef(pathName)){if(!urlMediaRefs.some(r=>r.url===pathName)){urlMediaRefs.push({originalAtPath,url:pathName})}atPathToResolvedSpecMap.set(originalAtPath,pathName);continue}}const extRef=parseExtensionRef(pathName);if(extRef){const extension=matchExtensionByRef(extRef.name,activeExtensions);if(extension){if(!extensionMentions.some(m=>m.extension.name===extension.name)){extensionMentions.push({originalAtPath,extension})}atPathToResolvedSpecMap.set(originalAtPath,pathName);continue}onDebugMessage(`Extension "${extRef.name}" not found among active extensions. Available: ${activeExtensions.map(e=>e.name).join(", ")||"(none)"}`);continue}const sessionRef=parseSessionRef(pathName);if(sessionRef){if(!sessionMentions.some(m=>(m.ref.id??m.ref.title)===(sessionRef.id??sessionRef.title))){sessionMentions.push({originalAtPath,ref:sessionRef})}atPathToResolvedSpecMap.set(originalAtPath,buildSessionRef(sessionRef.id??sessionRef.title));continue}const resourceRef=parseMcpResourceRef(pathName,mcpServerNames);if(resourceRef){mcpResourceRefs.push({originalAtPath,...resourceRef});atPathToResolvedSpecMap.set(originalAtPath,pathName);continue}const mcpServerRef=parseMcpServerRef(pathName);if(mcpServerRef){const matched=matchMcpServerByRef(mcpServerRef.name,config.getMcpServers()||{});if(matched){if(!mcpServerMentions.some(m=>m.serverName===matched.serverName)){mcpServerMentions.push({originalAtPath,serverName:matched.serverName})}atPathToResolvedSpecMap.set(originalAtPath,buildMcpServerRef(matched.serverName));continue}onDebugMessage(`MCP server "${mcpServerRef.name}" not found among configured MCP servers. Available: ${Object.keys(config.getMcpServers()||{}).join(", ")||"(none)"}`);continue}const workspaceContext=config.getWorkspaceContext();const absolutePathName=path.isAbsolute(pathName)?pathName:path.resolve(workspaceContext.getDirectories()[0]||"",pathName);if(!isSubpath(configuredProjectTempDir,absolutePathName)&&!isSubpath(projectTempDir,absolutePathName)&&!workspaceContext.isPathWithinWorkspace(pathName)){onDebugMessage(`Path ${pathName} is not in the workspace and will be skipped.`);continue}const ignoredReason=getIgnoreReason(pathName);if(ignoredReason){const reason=ignoredReason;ignoredByReason[reason].push(pathName);const reasonText=reason==="both"?"ignored by both git and qwen":reason==="git"?"git-ignored":"qwen-ignored";onDebugMessage(`Path ${pathName} is ${reasonText} and will be skipped.`);continue}let resolvedSuccessfully=false;let sawNotFound=false;let deferredIgnoreReason;for(const dir of config.getWorkspaceContext().getDirectories()){try{const absolutePath=path.resolve(dir,pathName);const canonicalPath=await fs.realpath(absolutePath);const stats=await fs.stat(canonicalPath);if(!isSubpath(configuredProjectTempDir,canonicalPath)&&!isSubpath(projectTempDir,canonicalPath)&&!workspaceContext.isPathWithinWorkspace(canonicalPath)){onDebugMessage(`Path ${pathName} is not in the workspace and will be skipped.`);continue}const canonicalIgnoreReason=getIgnoreReason(canonicalPath);if(canonicalIgnoreReason){deferredIgnoreReason=canonicalIgnoreReason;const reasonText=canonicalIgnoreReason==="both"?"ignored by both git and qwen":canonicalIgnoreReason==="git"?"git-ignored":"qwen-ignored";onDebugMessage(`Path ${pathName} is ${reasonText} and will be skipped.`);continue}if(stats.isDirectory()){onDebugMessage(`Path ${pathName} resolved to directory.`)}else{onDebugMessage(`Path ${pathName} resolved to file: ${absolutePath}`)}pathSpecsToRead.push(canonicalPath);atPathToResolvedSpecMap.set(originalAtPath,pathName);contentLabelsForDisplay.push(pathName);displayPaths.set(canonicalPath,pathName);const canonicalDisplays=displayPathsByCanonicalPath.get(canonicalPath)??new Set;canonicalDisplays.add(pathName);displayPathsByCanonicalPath.set(canonicalPath,canonicalDisplays);resolvedSuccessfully=true}catch(error){if(isNodeError(error)&&error.code==="ENOENT"){sawNotFound=true;continue}else{onDebugMessage(`Error stating path ${pathName}: ${getErrorMessage(error)}. Path ${pathName} will be skipped.`)}}if(resolvedSuccessfully){break}}if(!resolvedSuccessfully&&sawNotFound){let reanchored=false;if(config.isOmniEnabled?.()){const{reanchorRememberedMedia}=await import("./omni-DNZGITTE.js");for(const dir of config.getWorkspaceContext().getDirectories()){const anchor=await reanchorRememberedMedia(config,path.resolve(dir,pathName));if(!anchor)continue;rememberedMediaRefs.push({originalAtPath,pathName,annotation:anchor.annotation});atPathToResolvedSpecMap.set(originalAtPath,pathName);onDebugMessage(`Path ${pathName} is gone but remembered; re-anchored as ${anchor.resourceId} (bytes unavailable).`);reanchored=true;break}}if(!reanchored){onDebugMessage(`Path ${pathName} not found. Path ${pathName} will be skipped.`)}}if(!resolvedSuccessfully&&deferredIgnoreReason){ignoredByReason[deferredIgnoreReason].push(pathName)}}const buildInitialQueryText=__name(()=>{let text="";for(let i=0;i<commandParts.length;i++){const part=commandParts[i];if(part.type==="text"){text+=part.content}else{const resolvedSpec=atPathToResolvedSpecMap.get(part.content);if(i>0&&text.length>0&&!text.endsWith(" ")){const prevPart=commandParts[i-1];if(prevPart.type==="text"||prevPart.type==="atPath"){text+=" "}}if(resolvedSpec){text+=`@${resolvedSpec}`}else{if(i>0&&text.length>0&&!text.endsWith(" ")&&!part.content.startsWith(" ")){text+=" "}text+=part.content}}}return text.trim()},"buildInitialQueryText");let initialQueryText=buildInitialQueryText();const totalIgnored=ignoredByReason["git"].length+ignoredByReason["qwen"].length+ignoredByReason["both"].length;if(totalIgnored>0){const messages=[];if(ignoredByReason["git"].length){messages.push(`Git-ignored: ${ignoredByReason["git"].join(", ")}`)}if(ignoredByReason["qwen"].length){messages.push(`Qwen-ignored: ${ignoredByReason["qwen"].join(", ")}`)}if(ignoredByReason["both"].length){messages.push(`Ignored by both: ${ignoredByReason["both"].join(", ")}`)}const message=`Ignored ${totalIgnored} files:
|
|
4
|
+
${messages.join("\n")}`;onDebugMessage(message)}const resourceReads=await Promise.allSettled(mcpResourceRefs.map(ref=>config.getToolRegistry().readMcpResource(ref.serverName,ref.uri,{signal})));const urlMediaParts=[];const urlMediaDisplays=[];const urlMediaLabels=[];if(urlMediaRefs.length>0){const core=await import("./omni-DNZGITTE.js");for(let i=0;i<urlMediaRefs.length;i++){const ref=urlMediaRefs[i];const callId=`client-url-media-${userMessageTimestamp}-${i}`;const hostLabel=(()=>{try{return new URL(ref.url).hostname}catch{return"invalid-url"}})();let tempPartPath;try{const store=new core.OmniObjectStore(config.storage.getQwenDir());const downloadsDir=path.join(store.getOmniRootDir(),"downloads");const downloaded=await core.downloadMediaUrl({url:ref.url,downloadsDir,maxBytes:core.effectiveMaxDownloadFileBytes(config),signal});tempPartPath=downloaded.partPath;const urlBase=path.basename(new URL(ref.url).pathname)||hostLabel;const modalities=config.getContentGeneratorConfig?.()?.modalities??{};const sniffedModality=await core.sniffFileModality(downloaded.partPath);if(sniffedModality&&!modalities[sniffedModality]){urlMediaDisplays.push({callId,name:"Fetch Media URL",description:`Download ${ref.url}`,status:"Error",resultDisplay:`Skipped ${urlBase}: the active model does not accept ${sniffedModality} input.`,confirmationDetails:void 0});continue}const delivery=await core.processMediaForOmniDelivery(downloaded.partPath,config,{signal,displayName:urlBase,sourceUrl:ref.url});const transcriptParts=core.buildTranscriptParts(urlBase,delivery.transcripts);const additionalParts=core.buildAdditionalMediaParts(urlBase,delivery.additionalMedia);const handleParts=delivery.resourceId?[{text:core.formatResourceHandleText(urlBase,delivery.resourceId)}]:[];if(delivery.omission){urlMediaParts.push(...handleParts);urlMediaParts.push({text:core.formatOmissionText(urlBase,delivery.omission.reason)});urlMediaParts.push(...additionalParts);urlMediaParts.push(...transcriptParts);urlMediaLabels.push(ref.url);urlMediaDisplays.push({callId,name:"Fetch Media URL",description:`Downloaded ${ref.url}`,status:"Success",resultDisplay:`Media omitted by the omni transport guard: ${urlBase}`,confirmationDetails:void 0});continue}if(!delivery.fileUri&&transcriptParts.length>0){urlMediaParts.push(...handleParts);if(delivery.disclosure){urlMediaParts.push({text:core.formatDisclosureText(urlBase,delivery.disclosure)})}urlMediaParts.push(...additionalParts);urlMediaParts.push(...transcriptParts);urlMediaLabels.push(ref.url);urlMediaDisplays.push({callId,name:"Fetch Media URL",description:`Downloaded ${ref.url}`,status:"Success",resultDisplay:`Localized ${urlBase} and delivered as transcript (omni policy).`,confirmationDetails:void 0});continue}urlMediaParts.push(...handleParts);if(delivery.disclosure){urlMediaParts.push({text:core.formatDisclosureText(urlBase,delivery.disclosure)})}urlMediaParts.push({fileData:{fileUri:delivery.fileUri,mimeType:delivery.mimeType,displayName:urlBase}});urlMediaParts.push(...additionalParts);urlMediaParts.push(...transcriptParts);urlMediaLabels.push(ref.url);urlMediaDisplays.push({callId,name:"Fetch Media URL",description:`Downloaded ${ref.url}`,status:"Success",resultDisplay:`Localized ${urlBase} (${delivery.recognized.modality}, ${(delivery.recognized.sizeBytes/1024/1024).toFixed(1)}MB) and delivered via omni upload${delivery.degraded?" (degraded by media policy)":""}.`,confirmationDetails:void 0})}catch(error){if(signal.aborted){if(tempPartPath){await fs.rm(tempPartPath,{force:true}).catch(()=>{})}return{processedQuery:null,shouldProceed:false,toolDisplays:[...urlMediaDisplays],filesRead:urlMediaLabels}}const reason=getErrorMessage(error);onDebugMessage(`Failed to localize media URL ${ref.url}: ${reason}`);urlMediaDisplays.push({callId,name:"Fetch Media URL",description:`Download ${ref.url}`,status:"Error",resultDisplay:`Failed to fetch media from ${hostLabel}: ${reason}`,confirmationDetails:void 0})}finally{if(tempPartPath){await fs.rm(tempPartPath,{force:true}).catch(()=>{})}}}}const resourceParts=[];const resourceDisplays=[];const resourceLabels=[];for(let i=0;i<mcpResourceRefs.length;i++){const ref=mcpResourceRefs[i];const label=`${ref.serverName}:${ref.uri}`;const callId=`client-mcp-resource-${userMessageTimestamp}-${i}`;const outcome=resourceReads[i];if(outcome.status==="rejected"){onDebugMessage(`Failed to read MCP resource ${label}: ${getErrorMessage(outcome.reason)}`);resourceDisplays.push({callId,name:"Read MCP Resource",description:`Read resource ${label}`,status:"Error",resultDisplay:`Failed to read resource ${label}: ${getErrorMessage(outcome.reason)}`,confirmationDetails:void 0});continue}const formatted=formatMcpResourceContents(outcome.value,label);if(formatted.parts.length>0){resourceParts.push(...formatted.parts)}else{resourceParts.push({text:emptyMcpResourceText(formatted,label)})}resourceLabels.push(label);resourceDisplays.push({callId,name:"Read MCP Resource",description:`Read resource ${label}`,status:"Success",resultDisplay:summarizeMcpResource(formatted),confirmationDetails:void 0})}if(pathSpecsToRead.length===0&&mcpResourceRefs.length===0&&mcpServerMentions.length===0&&extensionMentions.length===0&&sessionMentions.length===0&&urlMediaRefs.length===0){onDebugMessage("No valid file paths found in @ commands to read.");if(initialQueryText==="@"&&query.trim()==="@"){return{processedQuery:[{text:query}],shouldProceed:true}}else if(!initialQueryText&&query){return{processedQuery:[{text:query}],shouldProceed:true}}return{processedQuery:[{text:initialQueryText||query}],shouldProceed:true}}let extensionContextBudgetRemaining=EXTENSION_CONTEXT_BUDGET;const scopedMentionEntries=[];for(let i=0;i<extensionMentions.length;i++){const{originalAtPath,extension}=extensionMentions[i];const displayName=getSanitizedExtensionDisplayName(extension);const callId=`client-extension-${userMessageTimestamp}-${i}`;const context=await buildExtensionMentionContext(extension,{remainingBudget:extensionContextBudgetRemaining,signal,onDebugMessage});extensionContextBudgetRemaining=context.remainingBudget;scopedMentionEntries.push({originalAtPath,part:{text:context.text},label:buildExtensionRef(extension.name),display:{callId,name:"Activate Extension",description:`Activated extension ${displayName}`,status:"Success",resultDisplay:void 0,confirmationDetails:void 0}})}for(let i=0;i<mcpServerMentions.length;i++){const{originalAtPath,serverName}=mcpServerMentions[i];scopedMentionEntries.push({originalAtPath,part:{text:buildMcpServerContextText(config,serverName)},label:buildMcpServerRef(serverName),display:{callId:`client-mcp-server-${userMessageTimestamp}-${i}`,name:"Activate MCP Server",description:`Activated MCP server ${serverName}`,status:"Success",resultDisplay:void 0,confirmationDetails:void 0}})}const resolvedSessionIds=new Set;for(let i=0;i<sessionMentions.length;i++){const{originalAtPath,ref}=sessionMentions[i];const callId=`client-session-${userMessageTimestamp}-${i}`;let sessionId=ref.id;if(!sessionId&&ref.title){let matches=[];try{matches=await new SessionService(config.getProjectRoot()).findSessionsByTitle(ref.title)}catch(error){const reason=`Could not look up sessions matching "@${originalAtPath.substring(1)}" (${getErrorMessage(error)}); try a session id instead.`;onDebugMessage(reason);scopedMentionEntries.push({originalAtPath,part:{text:""},label:buildSessionRef(ref.title??originalAtPath),display:{callId,name:"Referenced Session",description:`Reference session "${ref.title??""}"`,status:"Error",resultDisplay:reason,confirmationDetails:void 0}});continue}if(matches.length===1){sessionId=matches[0].sessionId}else{const reason=matches.length===0?`No session matches "@${originalAtPath.substring(1)}".`:`"@${originalAtPath.substring(1)}" is ambiguous (${matches.length} matches); use the picker or a session id.`;onDebugMessage(reason);scopedMentionEntries.push({originalAtPath,part:{text:""},label:buildSessionRef(ref.title),display:{callId,name:"Referenced Session",description:`Reference session "${ref.title}"`,status:"Error",resultDisplay:reason,confirmationDetails:void 0}});continue}}if(!sessionId){const reason=`Session reference "@${originalAtPath.substring(1)}" could not be resolved.`;onDebugMessage(reason);scopedMentionEntries.push({originalAtPath,part:{text:""},label:buildSessionRef(ref.title??ref.id??originalAtPath),display:{callId,name:"Referenced Session",description:`Reference session "${ref.title??ref.id??""}"`,status:"Error",resultDisplay:reason,confirmationDetails:void 0}});continue}if(resolvedSessionIds.has(sessionId)){onDebugMessage(`Session reference "@${originalAtPath.substring(1)}" resolves to session ${sessionId}, which was already referenced; skipping duplicate.`);continue}resolvedSessionIds.add(sessionId);let resolved;try{resolved=await new SessionReferenceService(config.getProjectRoot()).resolve(sessionId,ref.title?{title:ref.title}:{})}catch(error){const reason=`Failed to load session "${sessionId}" (${getErrorMessage(error)}); the transcript may be corrupted or unreadable.`;onDebugMessage(reason);scopedMentionEntries.push({originalAtPath,part:{text:""},label:buildSessionRef(sessionId),display:{callId,name:"Referenced Session",description:`Reference session ${sessionId}`,status:"Error",resultDisplay:reason,confirmationDetails:void 0}});continue}if("notFound"in resolved){const reason=`Session "${sessionId}" not found in this project.`;onDebugMessage(reason);scopedMentionEntries.push({originalAtPath,part:{text:""},label:buildSessionRef(sessionId),display:{callId,name:"Referenced Session",description:`Reference session ${sessionId}`,status:"Error",resultDisplay:reason,confirmationDetails:void 0}});continue}scopedMentionEntries.push({originalAtPath,part:{text:resolved.text},label:buildSessionRef(sessionId),display:{callId,name:"Referenced Session",description:`Referenced session "${resolved.meta.title}"${resolved.truncated?" (truncated)":""}`,status:"Success",resultDisplay:void 0,confirmationDetails:void 0}})}const scopedMentionOrder=new Map(atPathCommandParts.map((part,index)=>[part.content,index]));scopedMentionEntries.sort((a,b)=>(scopedMentionOrder.get(a.originalAtPath)??Number.MAX_SAFE_INTEGER)-(scopedMentionOrder.get(b.originalAtPath)??Number.MAX_SAFE_INTEGER));const scopedMentionParts=scopedMentionEntries.map(entry=>entry.part);const scopedMentionLabels=scopedMentionEntries.map(entry=>entry.label);const scopedMentionDisplays=scopedMentionEntries.map(entry=>entry.display);const fileParts=[];let fileDisplays=[];const revalidatedPathSpecs=[];const revalidatedDisplayPaths=new Map;const validatedPathIdentities=new Map;const pruneSkippedPath=__name(approvedPath=>{const displayPath=displayPaths.get(approvedPath);const displayLabels=displayPathsByCanonicalPath.get(approvedPath)??new Set(displayPath?[displayPath]:[]);for(const[originalAtPath,resolvedSpec]of atPathToResolvedSpecMap){if(resolvedSpec===approvedPath||displayLabels.has(resolvedSpec)){atPathToResolvedSpecMap.delete(originalAtPath)}}for(let index=contentLabelsForDisplay.length-1;index>=0;index--){const label=contentLabelsForDisplay[index];if(label===approvedPath||displayLabels.has(label)){contentLabelsForDisplay.splice(index,1)}}},"pruneSkippedPath");for(const approvedPath of pathSpecsToRead){try{const currentPath=await fs.realpath(approvedPath);const stats=await fs.stat(currentPath);if(currentPath===approvedPath&&(stats.isFile()||stats.isDirectory())&&(isSubpath(configuredProjectTempDir,currentPath)||isSubpath(projectTempDir,currentPath)||config.getWorkspaceContext().isPathWithinWorkspace(currentPath))&&getIgnoreReason(currentPath)===void 0){revalidatedPathSpecs.push(currentPath);const displayPath=displayPaths.get(approvedPath);if(displayPath)revalidatedDisplayPaths.set(currentPath,displayPath);validatedPathIdentities.set(currentPath,{dev:stats.dev,ino:stats.ino})}else{pruneSkippedPath(approvedPath);onDebugMessage(`Path ${approvedPath} failed revalidation and will be skipped.`)}}catch{pruneSkippedPath(approvedPath);onDebugMessage(`Path ${approvedPath} changed before it could be read and will be skipped.`)}}initialQueryText=buildInitialQueryText();if(revalidatedPathSpecs.length>0){try{const result=await readManyFiles(config,{paths:revalidatedPathSpecs,signal,preserveUnsupportedImageForBridge:shouldRunVisionBridge(config),validatedPathIdentities,displayPaths:revalidatedDisplayPaths});const parts=Array.isArray(result.contentParts)?result.contentParts:[result.contentParts];fileDisplays=result.files.map((file,index)=>({callId:`client-read-${userMessageTimestamp}-${index}`,name:file.isDirectory?"Read Directory":"Read File",description:`@${path.basename(file.filePath)}`,status:file.error?"Error":"Success",resultDisplay:file.error?`Failed to read ${path.basename(file.filePath)}: ${file.error}`:void 0,confirmationDetails:void 0}));if(parts.length>0&&!result.error){for(const part of parts){fileParts.push(typeof part==="string"?{text:part}:part)}}else{onDebugMessage("readManyFiles returned no content or empty content.")}}catch(error){const errorToolCallDisplay={callId:`client-read-${userMessageTimestamp}`,name:"Read File(s)",description:"Error attempting to read files",status:"Error",resultDisplay:`Error reading files (${contentLabelsForDisplay.join(", ")}): ${getErrorMessage(error)}`,confirmationDetails:void 0};const errorMessage=typeof errorToolCallDisplay.resultDisplay==="string"?errorToolCallDisplay.resultDisplay:void 0;const labelsOnError=[...scopedMentionLabels,...contentLabelsForDisplay,...resourceLabels,...urlMediaLabels];return{processedQuery:null,shouldProceed:false,toolDisplays:[...scopedMentionDisplays,...resourceDisplays,...urlMediaDisplays,errorToolCallDisplay],filesRead:labelsOnError,recording:{filesRead:labelsOnError,status:"error",message:errorMessage}}}}const rememberedMediaParts=rememberedMediaRefs.flatMap(ref=>[{text:ref.annotation},{text:`\u3010\u5A92\u4F53\u7F3A\u5931\u3011${ref.pathName}\uFF1A\u6587\u4EF6\u5DF2\u4E0D\u5728\u78C1\u76D8\u4E0A\uFF0C\u65E0\u6CD5\u6295\u9012\u753B\u9762/\u97F3\u9891\u3002\u5176\u5904\u7406\u8BB0\u5FC6\u4ECD\u53EF\u7528\u2014\u2014\u7528\u4E0A\u9762\u7684\u53E5\u67C4\u8C03\u7528 omni_recall_media_memory \u53D6\u56DE\u3002`}]);const processedQueryParts=[{text:initialQueryText},...scopedMentionParts,...fileParts,...resourceParts,...urlMediaParts,...rememberedMediaParts];const allLabels=[...scopedMentionLabels,...contentLabelsForDisplay,...resourceLabels,...urlMediaLabels,...rememberedMediaRefs.map(ref=>`${ref.pathName} (\u8BB0\u5FC6)`)];return{processedQuery:processedQueryParts,shouldProceed:true,toolDisplays:[...scopedMentionDisplays,...fileDisplays,...resourceDisplays,...urlMediaDisplays],filesRead:allLabels,recording:{filesRead:allLabels,status:"success"}}}__name(resolveAtCommandQuery,"resolveAtCommandQuery");async function handleAtCommand(params){const result=await resolveAtCommandQuery(params);if(result.recording){const chatRecorder=params.config.getChatRecordingService?.();chatRecorder?.recordAtCommand({filesRead:result.recording.filesRead,status:result.recording.status,...result.recording.message?{message:result.recording.message}:{},userText:params.query})}if(params.addItem&&result.toolDisplays&&result.toolDisplays.length>0){const toolGroupItem={type:"tool_group",tools:result.toolDisplays};params.addItem(toolGroupItem,params.messageId)}return{processedQuery:result.processedQuery,shouldProceed:result.shouldProceed,toolDisplays:result.toolDisplays,filesRead:result.filesRead}}__name(handleAtCommand,"handleAtCommand");export{matchMcpServerPrefix,buildMcpResourceRef,MAX_SUGGESTIONS_TO_SHOW,MAX_SUGGESTION_LABEL_WIDTH,prepareSuggestionLabel,normalizeDescription,getExtensionSuggestions,SESSION_MENTION_PREFIX,buildSessionRef,parseMcpServerRef,buildMcpServerRef,matchMcpServerByRef,buildMcpServerContextText,extractAtPathCommands,resolveAtCommandQuery,handleAtCommand};
|
|
5
5
|
/**
|
|
6
6
|
* @license
|
|
7
7
|
* Copyright 2025 Google LLC
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{createWorkspaceRuntimeSessionService}from"./chunk-JWNKPINR.js";import{parseCallerSuppliedSessionId}from"./chunk-LGFF5PJA.js";import{isInternalWorkspaceRuntime}from"./chunk-M5KJJE2X.js";import{canonicalizeWorkspace}from"./chunk-L5UULTGF.js";import{isWithinRoot}from"./chunk-IDXJIDME.js";import{WORKTREE_SESSION_FILE,gitEnv}from"./chunk-ILECDNJX.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs";import*as fsPromises from"node:fs/promises";import path from"node:path";import{execFile}from"node:child_process";import{promisify}from"node:util";var execFileAsync=promisify(execFile);function isGitProbeInfrastructureError(error){const failure=error;return failure.killed===true||typeof failure.code==="string"&&["ENOENT","EACCES","EAGAIN","ENOMEM","ETIMEDOUT"].includes(failure.code)}__name(isGitProbeInfrastructureError,"isGitProbeInfrastructureError");async function isGitInfrastructureFault(error,cwd){if(!isGitProbeInfrastructureError(error))return false;const code=error.code;if(code!=="ENOENT"&&code!=="EACCES")return true;try{await fsPromises.access(cwd,fs.constants.X_OK);return true}catch{return false}}__name(isGitInfrastructureFault,"isGitInfrastructureFault");function resolveWorkspaceEntryFromParam(registry,req,res,paramName="workspace"){const selector=req.params[paramName]??"";const entry=resolveWorkspaceEntryBySelector(registry,selector);if(entry)return entry;if(!isPortableAbsolutePath(selector)){res.status(400).json({error:`\`:${paramName}\` must decode to a workspace id or absolute path`,code:"workspace_mismatch"});return null}sendWorkspaceMismatch(res,registry);return null}__name(resolveWorkspaceEntryFromParam,"resolveWorkspaceEntryFromParam");function resolveWorkspaceEntryBySelector(registry,selector){const byId=registry.getEntryByWorkspaceId(selector);if(byId)return byId;if(!isPortableAbsolutePath(selector))return void 0;const exact=registry.getEntryByWorkspaceCwd(selector);if(exact)return exact;if(path.isAbsolute(selector)&&!isUncPath(selector)){try{const canonicalSelector=canonicalizeWorkspace(selector);const canonicalMatch=registry.getEntryByWorkspaceCwd(canonicalSelector);if(canonicalMatch)return canonicalMatch;for(const candidate of registry.listEntries()){if(canonicalizeWorkspace(candidate.workspaceCwd)===canonicalSelector){return candidate}}}catch{}}const normalizedSelector=normalizePortableAbsolutePath(selector);return registry.listEntries().find(candidate=>normalizePortableAbsolutePath(candidate.workspaceCwd)===normalizedSelector)}__name(resolveWorkspaceEntryBySelector,"resolveWorkspaceEntryBySelector");function isPortableAbsolutePath(value){return path.isAbsolute(value)||/^[A-Za-z]:[\\/]/.test(value)||/^\\\\[^\\]+\\[^\\]+/.test(value)}__name(isPortableAbsolutePath,"isPortableAbsolutePath");function isUncPath(value){return/^\\\\[^\\]+\\[^\\]+/.test(value)}__name(isUncPath,"isUncPath");function normalizePortableAbsolutePath(value){if(/^[A-Za-z]:[\\/]/.test(value)||/^\\\\[^\\]+\\[^\\]+/.test(value)){return path.win32.normalize(value).toLowerCase()}return path.resolve(value)}__name(normalizePortableAbsolutePath,"normalizePortableAbsolutePath");function resolveRegisteredWorkspaceRuntimeByPathSelector(registry,selector){const exact=registry.getByWorkspaceCwd(selector);if(exact)return exact;if(path.isAbsolute(selector)&&!isUncPath(selector)){try{const canonicalSelector=canonicalizeWorkspace(selector);const canonicalMatch=registry.getByWorkspaceCwd(canonicalSelector);if(canonicalMatch)return canonicalMatch;for(const runtime of registry.list()){if(canonicalizeWorkspace(runtime.workspaceCwd)===canonicalSelector){return runtime}}}catch{}}const normalizedSelector=normalizePortableAbsolutePath(selector);return registry.list().find(runtime=>normalizePortableAbsolutePath(runtime.workspaceCwd)===normalizedSelector)}__name(resolveRegisteredWorkspaceRuntimeByPathSelector,"resolveRegisteredWorkspaceRuntimeByPathSelector");function resolveManagedWorkspaceRuntimeByPathSelector(registry,selector){const exact=registry.getManagedByWorkspaceCwd(selector);if(exact&&!isInternalWorkspaceRuntime(exact))return exact;if(path.isAbsolute(selector)&&!isUncPath(selector)){try{const canonicalSelector=canonicalizeWorkspace(selector);const canonicalMatch=registry.getManagedByWorkspaceCwd(canonicalSelector);if(canonicalMatch&&!isInternalWorkspaceRuntime(canonicalMatch)){return canonicalMatch}for(const runtime of registry.listManaged()){if(isInternalWorkspaceRuntime(runtime))continue;if(canonicalizeWorkspace(runtime.workspaceCwd)===canonicalSelector){return runtime}}}catch{}}const normalizedSelector=normalizePortableAbsolutePath(selector);return registry.listManaged().find(runtime=>!isInternalWorkspaceRuntime(runtime)&&normalizePortableAbsolutePath(runtime.workspaceCwd)===normalizedSelector)}__name(resolveManagedWorkspaceRuntimeByPathSelector,"resolveManagedWorkspaceRuntimeByPathSelector");function resolveWorkspaceRuntimeFromParam(registry,req,res,paramName="workspace"){const entry=resolveWorkspaceEntryFromParam(registry,req,res,paramName);if(!entry)return null;const runtime=entry.state==="active"?entry.current?.runtime:void 0;if(!runtime){sendWorkspaceRuntimeUnavailable(res,entry);return null}return runtime}__name(resolveWorkspaceRuntimeFromParam,"resolveWorkspaceRuntimeFromParam");function resolveTrustedRuntime(registry,req,res,paramName="workspace"){const runtime=resolveWorkspaceRuntimeFromParam(registry,req,res,paramName);if(!runtime)return null;return requireTrustedWorkspaceRuntime(runtime,res)?runtime:null}__name(resolveTrustedRuntime,"resolveTrustedRuntime");function resolveWorkspaceRuntimeWithLiveCompatibilityFromParam(registry,req,res,paramName="workspace"){if(typeof registry.getManagedEntryByWorkspaceId!=="function"||typeof registry.getManagedEntryByWorkspaceCwd!=="function"){return resolveWorkspaceRuntimeFromParam(registry,req,res,paramName)}const selector=req.params[paramName]??"";let entry=registry.getManagedEntryByWorkspaceId(selector);if(!entry&&isPortableAbsolutePath(selector)){entry=registry.getManagedEntryByWorkspaceCwd(selector)}if(!entry?.internal){return resolveWorkspaceRuntimeFromParam(registry,req,res,paramName)}const runtime=entry.state==="active"?entry.current?.runtime:void 0;if(!runtime){sendConversationRuntimeUnavailable(res);return null}return runtime}__name(resolveWorkspaceRuntimeWithLiveCompatibilityFromParam,"resolveWorkspaceRuntimeWithLiveCompatibilityFromParam");function sendConversationRuntimeUnavailable(res){res.set("Retry-After","1");res.status(503).json({error:"The Conversations runtime is temporarily unavailable.",code:"conversation_runtime_unavailable",retryable:true})}__name(sendConversationRuntimeUnavailable,"sendConversationRuntimeUnavailable");function sendWorkspaceRuntimeUnavailable(res,entry){res.set("Retry-After","1");res.status(503).json({error:"Workspace runtime is not active.",code:"workspace_runtime_unavailable",...entry?{workspaceCwd:entry.workspaceCwd,workspaceId:entry.workspaceId}:{}})}__name(sendWorkspaceRuntimeUnavailable,"sendWorkspaceRuntimeUnavailable");var MAX_BATCH_WORKSPACES=20;var MAX_SELECTOR_CHARS=4096;var MAX_MEMBER_BYTES=512*1024;function failedBatchMember(workspace,entry,status,code,message){return{workspace,...entry?{workspaceId:entry.workspaceId,cwd:entry.workspaceCwd}:{},error:{code,message,status}}}__name(failedBatchMember,"failedBatchMember");function captureWorkspaceEntryCurrency(registry,entry){const generation=entry.current;return{generation,isCurrent:__name(()=>registry.getEntryByWorkspaceId(entry.workspaceId)===entry&&entry.state==="active"&&entry.current?.generationId===generation?.generationId&&generation!==void 0&&!generation.guard.closed,"isCurrent")}}__name(captureWorkspaceEntryCurrency,"captureWorkspaceEntryCurrency");function isGenerationClosedError(error){return Boolean(error&&typeof error==="object"&&"code"in error&&error.code==="workspace_generation_closed")}__name(isGenerationClosedError,"isGenerationClosedError");function sendGenerationClosedError(res,error){if(!isGenerationClosedError(error))return false;sendWorkspaceRuntimeUnavailable(res);return true}__name(sendGenerationClosedError,"sendGenerationClosedError");function resolveManagedWorkspaceRuntimeFromParam(registry,req,res,paramName="workspace"){const selector=req.params[paramName]??"";const byId=registry.getManagedByWorkspaceId(selector);if(byId&&!isInternalWorkspaceRuntime(byId))return byId;if(!isPortableAbsolutePath(selector)){res.status(400).json({error:`\`:${paramName}\` must decode to a workspace id or absolute path`,code:"workspace_mismatch"});return null}const runtime=resolveManagedWorkspaceRuntimeByPathSelector(registry,selector);if(!runtime){res.status(400).json({error:"Workspace mismatch: the requested workspace is not registered with this daemon.",code:"workspace_mismatch"});return null}return runtime}__name(resolveManagedWorkspaceRuntimeFromParam,"resolveManagedWorkspaceRuntimeFromParam");function requireTrustedWorkspaceRuntime(runtime,res){if(runtime.trusted)return true;sendUntrustedWorkspaceResponse(res);return false}__name(requireTrustedWorkspaceRuntime,"requireTrustedWorkspaceRuntime");function sendUntrustedWorkspaceResponse(res,extra){res.status(403).json({error:"Workspace is not trusted.",code:"untrusted_workspace",...extra})}__name(sendUntrustedWorkspaceResponse,"sendUntrustedWorkspaceResponse");function getWorkspaceRouteContext(req){return req.workspaceRouteContext}__name(getWorkspaceRouteContext,"getWorkspaceRouteContext");function setWorkspaceRouteContext(req,context){req.workspaceRouteContext=context}__name(setWorkspaceRouteContext,"setWorkspaceRouteContext");function sendWorkspaceMismatch(res,registry){res.status(400).json({error:"Workspace mismatch: the requested workspace is not registered with this daemon.",code:"workspace_mismatch",workspaceCount:registry.listEntries().length})}__name(sendWorkspaceMismatch,"sendWorkspaceMismatch");function resolveContainedCwd(req,workspaceCwd){const rawCwd=req.query["cwd"];if(typeof rawCwd!=="string"||rawCwd.length===0){return workspaceCwd}try{const resolved=fs.realpathSync(path.resolve(rawCwd));const root=fs.realpathSync(workspaceCwd);if(isWithinRoot(resolved,root)){return resolved}}catch{}return workspaceCwd}__name(resolveContainedCwd,"resolveContainedCwd");function resolveContainedCwdOrFail(req,workspaceCwd){const rawCwd=req.query["cwd"];if(rawCwd===void 0){return workspaceCwd}if(typeof rawCwd!=="string"||rawCwd.length===0){return null}try{const resolved=fs.realpathSync(path.resolve(rawCwd));const root=fs.realpathSync(workspaceCwd);if(isWithinRoot(resolved,root)){return resolved}}catch{}return null}__name(resolveContainedCwdOrFail,"resolveContainedCwdOrFail");async function resolveGitCommonDir(cwd){let stdout;try{({stdout}=await execFileAsync("git",["rev-parse","--git-common-dir"],{cwd,encoding:"utf8",timeout:3e4,env:gitEnv()}))}catch(error){if(await isGitInfrastructureFault(error,cwd))throw error;return null}return fsPromises.realpath(path.resolve(cwd,stdout.trim())).catch(()=>null)}__name(resolveGitCommonDir,"resolveGitCommonDir");async function resolveAbsoluteGitDir(cwd){let stdout;try{({stdout}=await execFileAsync("git",["rev-parse","--absolute-git-dir"],{cwd,encoding:"utf8",timeout:3e4,env:gitEnv()}))}catch(error){if(await isGitInfrastructureFault(error,cwd))throw error;return null}return fsPromises.realpath(stdout.trim()).catch(()=>null)}__name(resolveAbsoluteGitDir,"resolveAbsoluteGitDir");async function readBoundedRegularFile(filePath,maxBytes,options){const pathStat=await fsPromises.lstat(filePath);if(!pathStat.isFile()||!options?.allowHardLinks&&pathStat.nlink!==1||pathStat.size>maxBytes){return null}const handle=await fsPromises.open(filePath,fs.constants.O_RDONLY|(fs.constants.O_NOFOLLOW??0));try{const openedStat=await handle.stat();if(!openedStat.isFile()||!options?.allowHardLinks&&openedStat.nlink!==1||openedStat.dev!==pathStat.dev||openedStat.ino!==pathStat.ino||openedStat.size>maxBytes){return null}const buffer=Buffer.alloc(maxBytes+1);let bytesRead=0;while(bytesRead<buffer.length){const chunk=await handle.read(buffer,bytesRead,buffer.length-bytesRead,bytesRead);if(chunk.bytesRead===0)break;bytesRead+=chunk.bytesRead}if(bytesRead>maxBytes)return null;const finalStat=await fsPromises.lstat(filePath);if(!finalStat.isFile()||!options?.allowHardLinks&&finalStat.nlink!==1||finalStat.dev!==openedStat.dev||finalStat.ino!==openedStat.ino){return null}return buffer.subarray(0,bytesRead).toString("utf8")}finally{await handle.close()}}__name(readBoundedRegularFile,"readBoundedRegularFile");async function markerIsOwnedBy(markerPath,sessionId){try{return(await readBoundedRegularFile(markerPath,256))?.trim()===sessionId}catch{return false}}__name(markerIsOwnedBy,"markerIsOwnedBy");async function isLinkedWorktreeOrUnknown(cwd){let stdout;try{({stdout}=await execFileAsync("git",["rev-parse","--git-common-dir","--absolute-git-dir"],{cwd,encoding:"utf8",timeout:3e4,env:gitEnv()}))}catch(error){if(await isGitInfrastructureFault(error,cwd))throw error;const stderr=error.stderr;return!(typeof stderr==="string"&&/not a git repository/i.test(stderr))}const[common,absolute]=stdout.trim().split("\n");if(!common||!absolute)return true;try{const[commonDir,gitDir]=await Promise.all([fsPromises.realpath(path.resolve(cwd,common)),fsPromises.realpath(absolute)]);return commonDir!==gitDir}catch{return true}}__name(isLinkedWorktreeOrUnknown,"isLinkedWorktreeOrUnknown");async function resolveSessionManagedGitCwd(req,runtime){const rawCwd=req.query["cwd"];if(rawCwd===void 0)return runtime.workspaceCwd;if(typeof rawCwd!=="string"||rawCwd.length===0)return null;let requested;let workspace;try{requested=await fsPromises.realpath(path.resolve(rawCwd));workspace=await fsPromises.realpath(runtime.workspaceCwd)}catch{return null}let stdout;try{({stdout}=await execFileAsync("git",["rev-parse","--show-toplevel"],{cwd:workspace,encoding:"utf8",timeout:3e4,env:gitEnv()}))}catch(error){if(isGitProbeInfrastructureError(error))throw error;const stderr=error.stderr;if(typeof stderr==="string"&&/not a git repository/i.test(stderr)&&isWithinRoot(requested,workspace)&&!await isLinkedWorktreeOrUnknown(requested)){return requested}return null}const repoTop=await fsPromises.realpath(stdout.trim()).catch(()=>null);if(repoTop===null)return null;if(requested===workspace)return requested;const managedRoot=path.join(repoTop,".qwen","worktrees");if(isWithinRoot(requested,workspace)&&!isWithinRoot(requested,managedRoot)){if(!await isLinkedWorktreeOrUnknown(requested)){return requested}const[workspaceGitDir,requestedGitDir]=await Promise.all([resolveAbsoluteGitDir(workspace),resolveAbsoluteGitDir(requested)]);if(workspaceGitDir!==null&&requestedGitDir===workspaceGitDir){return requested}}if(!isWithinRoot(requested,managedRoot))return null;const[workspaceCommonDir,requestedCommonDir]=await Promise.all([resolveGitCommonDir(workspace),resolveGitCommonDir(requested)]);if(workspaceCommonDir===null||requestedCommonDir===null||requestedCommonDir!==workspaceCommonDir){return null}try{let rawSessionId=req.query["sessionId"];if(rawSessionId===void 0){const[slug]=path.relative(managedRoot,requested).split(path.sep);if(!slug)return null;rawSessionId=(await readBoundedRegularFile(path.join(managedRoot,slug,WORKTREE_SESSION_FILE),256))?.trim()}const parsedSessionId=parseCallerSuppliedSessionId(rawSessionId);if(parsedSessionId.kind!=="valid")return null;const sessionId=parsedSessionId.sessionId;let snapshot;try{snapshot=runtime.bridge.getSessionExecutionSnapshot(sessionId)}catch{return null}if(await fsPromises.realpath(snapshot.workspaceCwd)!==workspace||!snapshot.worktree){return null}const worktreeRoot=await fsPromises.realpath(snapshot.worktree.path);if(path.dirname(worktreeRoot)!==managedRoot||!isWithinRoot(requested,worktreeRoot)){return null}const sidecarPath=createWorkspaceRuntimeSessionService(runtime).getWorktreeSessionPath(sessionId);const sidecarRaw=await readBoundedRegularFile(sidecarPath,64*1024,{allowHardLinks:true});if(sidecarRaw===null)return null;let sidecar;try{sidecar=JSON.parse(sidecarRaw)}catch{return null}if(!sidecar||typeof sidecar!=="object"||Array.isArray(sidecar)||typeof sidecar["worktreePath"]!=="string"||await fsPromises.realpath(sidecar.worktreePath)!==worktreeRoot){return null}const markerPath=path.join(worktreeRoot,WORKTREE_SESSION_FILE);if(!await markerIsOwnedBy(markerPath,sessionId)){return null}const requestedGitDir=await resolveAbsoluteGitDir(requested);if(requestedGitDir===null)return null;const metadataRoot=await fsPromises.realpath(path.join(workspaceCommonDir,"worktrees"));if(path.dirname(requestedGitDir)!==metadataRoot)return null;const backpointer=await readBoundedRegularFile(path.join(requestedGitDir,"gitdir"),4096);if(backpointer===null)return null;const actualGitFile=await fsPromises.realpath(path.resolve(requestedGitDir,backpointer.trim()));const expectedGitFile=await fsPromises.realpath(path.join(worktreeRoot,".git"));if(actualGitFile!==expectedGitFile)return null;return requested}catch(error){const code=error.code;if(code==="ENOENT"||code==="EACCES"||code==="EPERM"||code==="ELOOP"||code==="ENOTDIR"){return null}throw error}}__name(resolveSessionManagedGitCwd,"resolveSessionManagedGitCwd");async function resolveSessionManagedGitCwdForRoute(req,res,runtime,route,sendBridgeError){let cwd;try{cwd=await resolveSessionManagedGitCwd(req,runtime);runtime.generationGuard?.assertOpen()}catch(error){sendBridgeError(res,error,{route});return void 0}if(cwd===null){res.status(400).json({error:"invalid_cwd",message:"The supplied cwd is invalid or outside the workspace"});return void 0}return cwd}__name(resolveSessionManagedGitCwdForRoute,"resolveSessionManagedGitCwdForRoute");export{resolveWorkspaceEntryFromParam,resolveWorkspaceEntryBySelector,isPortableAbsolutePath,resolveRegisteredWorkspaceRuntimeByPathSelector,resolveManagedWorkspaceRuntimeByPathSelector,resolveWorkspaceRuntimeFromParam,resolveTrustedRuntime,resolveWorkspaceRuntimeWithLiveCompatibilityFromParam,sendConversationRuntimeUnavailable,sendWorkspaceRuntimeUnavailable,MAX_BATCH_WORKSPACES,MAX_SELECTOR_CHARS,MAX_MEMBER_BYTES,failedBatchMember,captureWorkspaceEntryCurrency,isGenerationClosedError,sendGenerationClosedError,resolveManagedWorkspaceRuntimeFromParam,requireTrustedWorkspaceRuntime,sendUntrustedWorkspaceResponse,getWorkspaceRouteContext,setWorkspaceRouteContext,resolveContainedCwd,resolveContainedCwdOrFail,resolveSessionManagedGitCwdForRoute};
|
|
3
|
+
import{createWorkspaceRuntimeSessionService}from"./chunk-F6U6T7QD.js";import{parseCallerSuppliedSessionId}from"./chunk-LGFF5PJA.js";import{isInternalWorkspaceRuntime}from"./chunk-M5KJJE2X.js";import{canonicalizeWorkspace}from"./chunk-L5UULTGF.js";import{isWithinRoot}from"./chunk-IDXJIDME.js";import{WORKTREE_SESSION_FILE,gitEnv}from"./chunk-ILECDNJX.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs";import*as fsPromises from"node:fs/promises";import path from"node:path";import{execFile}from"node:child_process";import{promisify}from"node:util";var execFileAsync=promisify(execFile);function isGitProbeInfrastructureError(error){const failure=error;return failure.killed===true||typeof failure.code==="string"&&["ENOENT","EACCES","EAGAIN","ENOMEM","ETIMEDOUT"].includes(failure.code)}__name(isGitProbeInfrastructureError,"isGitProbeInfrastructureError");async function isGitInfrastructureFault(error,cwd){if(!isGitProbeInfrastructureError(error))return false;const code=error.code;if(code!=="ENOENT"&&code!=="EACCES")return true;try{await fsPromises.access(cwd,fs.constants.X_OK);return true}catch{return false}}__name(isGitInfrastructureFault,"isGitInfrastructureFault");function resolveWorkspaceEntryFromParam(registry,req,res,paramName="workspace"){const selector=req.params[paramName]??"";const entry=resolveWorkspaceEntryBySelector(registry,selector);if(entry)return entry;if(!isPortableAbsolutePath(selector)){res.status(400).json({error:`\`:${paramName}\` must decode to a workspace id or absolute path`,code:"workspace_mismatch"});return null}sendWorkspaceMismatch(res,registry);return null}__name(resolveWorkspaceEntryFromParam,"resolveWorkspaceEntryFromParam");function resolveWorkspaceEntryBySelector(registry,selector){const byId=registry.getEntryByWorkspaceId(selector);if(byId)return byId;if(!isPortableAbsolutePath(selector))return void 0;const exact=registry.getEntryByWorkspaceCwd(selector);if(exact)return exact;if(path.isAbsolute(selector)&&!isUncPath(selector)){try{const canonicalSelector=canonicalizeWorkspace(selector);const canonicalMatch=registry.getEntryByWorkspaceCwd(canonicalSelector);if(canonicalMatch)return canonicalMatch;for(const candidate of registry.listEntries()){if(canonicalizeWorkspace(candidate.workspaceCwd)===canonicalSelector){return candidate}}}catch{}}const normalizedSelector=normalizePortableAbsolutePath(selector);return registry.listEntries().find(candidate=>normalizePortableAbsolutePath(candidate.workspaceCwd)===normalizedSelector)}__name(resolveWorkspaceEntryBySelector,"resolveWorkspaceEntryBySelector");function isPortableAbsolutePath(value){return path.isAbsolute(value)||/^[A-Za-z]:[\\/]/.test(value)||/^\\\\[^\\]+\\[^\\]+/.test(value)}__name(isPortableAbsolutePath,"isPortableAbsolutePath");function isUncPath(value){return/^\\\\[^\\]+\\[^\\]+/.test(value)}__name(isUncPath,"isUncPath");function normalizePortableAbsolutePath(value){if(/^[A-Za-z]:[\\/]/.test(value)||/^\\\\[^\\]+\\[^\\]+/.test(value)){return path.win32.normalize(value).toLowerCase()}return path.resolve(value)}__name(normalizePortableAbsolutePath,"normalizePortableAbsolutePath");function resolveRegisteredWorkspaceRuntimeByPathSelector(registry,selector){const exact=registry.getByWorkspaceCwd(selector);if(exact)return exact;if(path.isAbsolute(selector)&&!isUncPath(selector)){try{const canonicalSelector=canonicalizeWorkspace(selector);const canonicalMatch=registry.getByWorkspaceCwd(canonicalSelector);if(canonicalMatch)return canonicalMatch;for(const runtime of registry.list()){if(canonicalizeWorkspace(runtime.workspaceCwd)===canonicalSelector){return runtime}}}catch{}}const normalizedSelector=normalizePortableAbsolutePath(selector);return registry.list().find(runtime=>normalizePortableAbsolutePath(runtime.workspaceCwd)===normalizedSelector)}__name(resolveRegisteredWorkspaceRuntimeByPathSelector,"resolveRegisteredWorkspaceRuntimeByPathSelector");function resolveManagedWorkspaceRuntimeByPathSelector(registry,selector){const exact=registry.getManagedByWorkspaceCwd(selector);if(exact&&!isInternalWorkspaceRuntime(exact))return exact;if(path.isAbsolute(selector)&&!isUncPath(selector)){try{const canonicalSelector=canonicalizeWorkspace(selector);const canonicalMatch=registry.getManagedByWorkspaceCwd(canonicalSelector);if(canonicalMatch&&!isInternalWorkspaceRuntime(canonicalMatch)){return canonicalMatch}for(const runtime of registry.listManaged()){if(isInternalWorkspaceRuntime(runtime))continue;if(canonicalizeWorkspace(runtime.workspaceCwd)===canonicalSelector){return runtime}}}catch{}}const normalizedSelector=normalizePortableAbsolutePath(selector);return registry.listManaged().find(runtime=>!isInternalWorkspaceRuntime(runtime)&&normalizePortableAbsolutePath(runtime.workspaceCwd)===normalizedSelector)}__name(resolveManagedWorkspaceRuntimeByPathSelector,"resolveManagedWorkspaceRuntimeByPathSelector");function resolveWorkspaceRuntimeFromParam(registry,req,res,paramName="workspace"){const entry=resolveWorkspaceEntryFromParam(registry,req,res,paramName);if(!entry)return null;const runtime=entry.state==="active"?entry.current?.runtime:void 0;if(!runtime){sendWorkspaceRuntimeUnavailable(res,entry);return null}return runtime}__name(resolveWorkspaceRuntimeFromParam,"resolveWorkspaceRuntimeFromParam");function resolveTrustedRuntime(registry,req,res,paramName="workspace"){const runtime=resolveWorkspaceRuntimeFromParam(registry,req,res,paramName);if(!runtime)return null;return requireTrustedWorkspaceRuntime(runtime,res)?runtime:null}__name(resolveTrustedRuntime,"resolveTrustedRuntime");function resolveWorkspaceRuntimeWithLiveCompatibilityFromParam(registry,req,res,paramName="workspace"){if(typeof registry.getManagedEntryByWorkspaceId!=="function"||typeof registry.getManagedEntryByWorkspaceCwd!=="function"){return resolveWorkspaceRuntimeFromParam(registry,req,res,paramName)}const selector=req.params[paramName]??"";let entry=registry.getManagedEntryByWorkspaceId(selector);if(!entry&&isPortableAbsolutePath(selector)){entry=registry.getManagedEntryByWorkspaceCwd(selector)}if(!entry?.internal){return resolveWorkspaceRuntimeFromParam(registry,req,res,paramName)}const runtime=entry.state==="active"?entry.current?.runtime:void 0;if(!runtime){sendConversationRuntimeUnavailable(res);return null}return runtime}__name(resolveWorkspaceRuntimeWithLiveCompatibilityFromParam,"resolveWorkspaceRuntimeWithLiveCompatibilityFromParam");function sendConversationRuntimeUnavailable(res){res.set("Retry-After","1");res.status(503).json({error:"The Conversations runtime is temporarily unavailable.",code:"conversation_runtime_unavailable",retryable:true})}__name(sendConversationRuntimeUnavailable,"sendConversationRuntimeUnavailable");function sendWorkspaceRuntimeUnavailable(res,entry){res.set("Retry-After","1");res.status(503).json({error:"Workspace runtime is not active.",code:"workspace_runtime_unavailable",...entry?{workspaceCwd:entry.workspaceCwd,workspaceId:entry.workspaceId}:{}})}__name(sendWorkspaceRuntimeUnavailable,"sendWorkspaceRuntimeUnavailable");var MAX_BATCH_WORKSPACES=20;var MAX_SELECTOR_CHARS=4096;var MAX_MEMBER_BYTES=512*1024;function failedBatchMember(workspace,entry,status,code,message){return{workspace,...entry?{workspaceId:entry.workspaceId,cwd:entry.workspaceCwd}:{},error:{code,message,status}}}__name(failedBatchMember,"failedBatchMember");function captureWorkspaceEntryCurrency(registry,entry){const generation=entry.current;return{generation,isCurrent:__name(()=>registry.getEntryByWorkspaceId(entry.workspaceId)===entry&&entry.state==="active"&&entry.current?.generationId===generation?.generationId&&generation!==void 0&&!generation.guard.closed,"isCurrent")}}__name(captureWorkspaceEntryCurrency,"captureWorkspaceEntryCurrency");function isGenerationClosedError(error){return Boolean(error&&typeof error==="object"&&"code"in error&&error.code==="workspace_generation_closed")}__name(isGenerationClosedError,"isGenerationClosedError");function sendGenerationClosedError(res,error){if(!isGenerationClosedError(error))return false;sendWorkspaceRuntimeUnavailable(res);return true}__name(sendGenerationClosedError,"sendGenerationClosedError");function resolveManagedWorkspaceRuntimeFromParam(registry,req,res,paramName="workspace"){const selector=req.params[paramName]??"";const byId=registry.getManagedByWorkspaceId(selector);if(byId&&!isInternalWorkspaceRuntime(byId))return byId;if(!isPortableAbsolutePath(selector)){res.status(400).json({error:`\`:${paramName}\` must decode to a workspace id or absolute path`,code:"workspace_mismatch"});return null}const runtime=resolveManagedWorkspaceRuntimeByPathSelector(registry,selector);if(!runtime){res.status(400).json({error:"Workspace mismatch: the requested workspace is not registered with this daemon.",code:"workspace_mismatch"});return null}return runtime}__name(resolveManagedWorkspaceRuntimeFromParam,"resolveManagedWorkspaceRuntimeFromParam");function requireTrustedWorkspaceRuntime(runtime,res){if(runtime.trusted)return true;sendUntrustedWorkspaceResponse(res);return false}__name(requireTrustedWorkspaceRuntime,"requireTrustedWorkspaceRuntime");function sendUntrustedWorkspaceResponse(res,extra){res.status(403).json({error:"Workspace is not trusted.",code:"untrusted_workspace",...extra})}__name(sendUntrustedWorkspaceResponse,"sendUntrustedWorkspaceResponse");function getWorkspaceRouteContext(req){return req.workspaceRouteContext}__name(getWorkspaceRouteContext,"getWorkspaceRouteContext");function setWorkspaceRouteContext(req,context){req.workspaceRouteContext=context}__name(setWorkspaceRouteContext,"setWorkspaceRouteContext");function sendWorkspaceMismatch(res,registry){res.status(400).json({error:"Workspace mismatch: the requested workspace is not registered with this daemon.",code:"workspace_mismatch",workspaceCount:registry.listEntries().length})}__name(sendWorkspaceMismatch,"sendWorkspaceMismatch");function resolveContainedCwd(req,workspaceCwd){const rawCwd=req.query["cwd"];if(typeof rawCwd!=="string"||rawCwd.length===0){return workspaceCwd}try{const resolved=fs.realpathSync(path.resolve(rawCwd));const root=fs.realpathSync(workspaceCwd);if(isWithinRoot(resolved,root)){return resolved}}catch{}return workspaceCwd}__name(resolveContainedCwd,"resolveContainedCwd");function resolveContainedCwdOrFail(req,workspaceCwd){const rawCwd=req.query["cwd"];if(rawCwd===void 0){return workspaceCwd}if(typeof rawCwd!=="string"||rawCwd.length===0){return null}try{const resolved=fs.realpathSync(path.resolve(rawCwd));const root=fs.realpathSync(workspaceCwd);if(isWithinRoot(resolved,root)){return resolved}}catch{}return null}__name(resolveContainedCwdOrFail,"resolveContainedCwdOrFail");async function resolveGitCommonDir(cwd){let stdout;try{({stdout}=await execFileAsync("git",["rev-parse","--git-common-dir"],{cwd,encoding:"utf8",timeout:3e4,env:gitEnv()}))}catch(error){if(await isGitInfrastructureFault(error,cwd))throw error;return null}return fsPromises.realpath(path.resolve(cwd,stdout.trim())).catch(()=>null)}__name(resolveGitCommonDir,"resolveGitCommonDir");async function resolveAbsoluteGitDir(cwd){let stdout;try{({stdout}=await execFileAsync("git",["rev-parse","--absolute-git-dir"],{cwd,encoding:"utf8",timeout:3e4,env:gitEnv()}))}catch(error){if(await isGitInfrastructureFault(error,cwd))throw error;return null}return fsPromises.realpath(stdout.trim()).catch(()=>null)}__name(resolveAbsoluteGitDir,"resolveAbsoluteGitDir");async function readBoundedRegularFile(filePath,maxBytes,options){const pathStat=await fsPromises.lstat(filePath);if(!pathStat.isFile()||!options?.allowHardLinks&&pathStat.nlink!==1||pathStat.size>maxBytes){return null}const handle=await fsPromises.open(filePath,fs.constants.O_RDONLY|(fs.constants.O_NOFOLLOW??0));try{const openedStat=await handle.stat();if(!openedStat.isFile()||!options?.allowHardLinks&&openedStat.nlink!==1||openedStat.dev!==pathStat.dev||openedStat.ino!==pathStat.ino||openedStat.size>maxBytes){return null}const buffer=Buffer.alloc(maxBytes+1);let bytesRead=0;while(bytesRead<buffer.length){const chunk=await handle.read(buffer,bytesRead,buffer.length-bytesRead,bytesRead);if(chunk.bytesRead===0)break;bytesRead+=chunk.bytesRead}if(bytesRead>maxBytes)return null;const finalStat=await fsPromises.lstat(filePath);if(!finalStat.isFile()||!options?.allowHardLinks&&finalStat.nlink!==1||finalStat.dev!==openedStat.dev||finalStat.ino!==openedStat.ino){return null}return buffer.subarray(0,bytesRead).toString("utf8")}finally{await handle.close()}}__name(readBoundedRegularFile,"readBoundedRegularFile");async function markerIsOwnedBy(markerPath,sessionId){try{return(await readBoundedRegularFile(markerPath,256))?.trim()===sessionId}catch{return false}}__name(markerIsOwnedBy,"markerIsOwnedBy");async function isLinkedWorktreeOrUnknown(cwd){let stdout;try{({stdout}=await execFileAsync("git",["rev-parse","--git-common-dir","--absolute-git-dir"],{cwd,encoding:"utf8",timeout:3e4,env:gitEnv()}))}catch(error){if(await isGitInfrastructureFault(error,cwd))throw error;const stderr=error.stderr;return!(typeof stderr==="string"&&/not a git repository/i.test(stderr))}const[common,absolute]=stdout.trim().split("\n");if(!common||!absolute)return true;try{const[commonDir,gitDir]=await Promise.all([fsPromises.realpath(path.resolve(cwd,common)),fsPromises.realpath(absolute)]);return commonDir!==gitDir}catch{return true}}__name(isLinkedWorktreeOrUnknown,"isLinkedWorktreeOrUnknown");async function resolveSessionManagedGitCwd(req,runtime){const rawCwd=req.query["cwd"];if(rawCwd===void 0)return runtime.workspaceCwd;if(typeof rawCwd!=="string"||rawCwd.length===0)return null;let requested;let workspace;try{requested=await fsPromises.realpath(path.resolve(rawCwd));workspace=await fsPromises.realpath(runtime.workspaceCwd)}catch{return null}let stdout;try{({stdout}=await execFileAsync("git",["rev-parse","--show-toplevel"],{cwd:workspace,encoding:"utf8",timeout:3e4,env:gitEnv()}))}catch(error){if(isGitProbeInfrastructureError(error))throw error;const stderr=error.stderr;if(typeof stderr==="string"&&/not a git repository/i.test(stderr)&&isWithinRoot(requested,workspace)&&!await isLinkedWorktreeOrUnknown(requested)){return requested}return null}const repoTop=await fsPromises.realpath(stdout.trim()).catch(()=>null);if(repoTop===null)return null;if(requested===workspace)return requested;const managedRoot=path.join(repoTop,".qwen","worktrees");if(isWithinRoot(requested,workspace)&&!isWithinRoot(requested,managedRoot)){if(!await isLinkedWorktreeOrUnknown(requested)){return requested}const[workspaceGitDir,requestedGitDir]=await Promise.all([resolveAbsoluteGitDir(workspace),resolveAbsoluteGitDir(requested)]);if(workspaceGitDir!==null&&requestedGitDir===workspaceGitDir){return requested}}if(!isWithinRoot(requested,managedRoot))return null;const[workspaceCommonDir,requestedCommonDir]=await Promise.all([resolveGitCommonDir(workspace),resolveGitCommonDir(requested)]);if(workspaceCommonDir===null||requestedCommonDir===null||requestedCommonDir!==workspaceCommonDir){return null}try{let rawSessionId=req.query["sessionId"];if(rawSessionId===void 0){const[slug]=path.relative(managedRoot,requested).split(path.sep);if(!slug)return null;rawSessionId=(await readBoundedRegularFile(path.join(managedRoot,slug,WORKTREE_SESSION_FILE),256))?.trim()}const parsedSessionId=parseCallerSuppliedSessionId(rawSessionId);if(parsedSessionId.kind!=="valid")return null;const sessionId=parsedSessionId.sessionId;let snapshot;try{snapshot=runtime.bridge.getSessionExecutionSnapshot(sessionId)}catch{return null}if(await fsPromises.realpath(snapshot.workspaceCwd)!==workspace||!snapshot.worktree){return null}const worktreeRoot=await fsPromises.realpath(snapshot.worktree.path);if(path.dirname(worktreeRoot)!==managedRoot||!isWithinRoot(requested,worktreeRoot)){return null}const sidecarPath=createWorkspaceRuntimeSessionService(runtime).getWorktreeSessionPath(sessionId);const sidecarRaw=await readBoundedRegularFile(sidecarPath,64*1024,{allowHardLinks:true});if(sidecarRaw===null)return null;let sidecar;try{sidecar=JSON.parse(sidecarRaw)}catch{return null}if(!sidecar||typeof sidecar!=="object"||Array.isArray(sidecar)||typeof sidecar["worktreePath"]!=="string"||await fsPromises.realpath(sidecar.worktreePath)!==worktreeRoot){return null}const markerPath=path.join(worktreeRoot,WORKTREE_SESSION_FILE);if(!await markerIsOwnedBy(markerPath,sessionId)){return null}const requestedGitDir=await resolveAbsoluteGitDir(requested);if(requestedGitDir===null)return null;const metadataRoot=await fsPromises.realpath(path.join(workspaceCommonDir,"worktrees"));if(path.dirname(requestedGitDir)!==metadataRoot)return null;const backpointer=await readBoundedRegularFile(path.join(requestedGitDir,"gitdir"),4096);if(backpointer===null)return null;const actualGitFile=await fsPromises.realpath(path.resolve(requestedGitDir,backpointer.trim()));const expectedGitFile=await fsPromises.realpath(path.join(worktreeRoot,".git"));if(actualGitFile!==expectedGitFile)return null;return requested}catch(error){const code=error.code;if(code==="ENOENT"||code==="EACCES"||code==="EPERM"||code==="ELOOP"||code==="ENOTDIR"){return null}throw error}}__name(resolveSessionManagedGitCwd,"resolveSessionManagedGitCwd");async function resolveSessionManagedGitCwdForRoute(req,res,runtime,route,sendBridgeError){let cwd;try{cwd=await resolveSessionManagedGitCwd(req,runtime);runtime.generationGuard?.assertOpen()}catch(error){sendBridgeError(res,error,{route});return void 0}if(cwd===null){res.status(400).json({error:"invalid_cwd",message:"The supplied cwd is invalid or outside the workspace"});return void 0}return cwd}__name(resolveSessionManagedGitCwdForRoute,"resolveSessionManagedGitCwdForRoute");export{resolveWorkspaceEntryFromParam,resolveWorkspaceEntryBySelector,isPortableAbsolutePath,resolveRegisteredWorkspaceRuntimeByPathSelector,resolveManagedWorkspaceRuntimeByPathSelector,resolveWorkspaceRuntimeFromParam,resolveTrustedRuntime,resolveWorkspaceRuntimeWithLiveCompatibilityFromParam,sendConversationRuntimeUnavailable,sendWorkspaceRuntimeUnavailable,MAX_BATCH_WORKSPACES,MAX_SELECTOR_CHARS,MAX_MEMBER_BYTES,failedBatchMember,captureWorkspaceEntryCurrency,isGenerationClosedError,sendGenerationClosedError,resolveManagedWorkspaceRuntimeFromParam,requireTrustedWorkspaceRuntime,sendUntrustedWorkspaceResponse,getWorkspaceRouteContext,setWorkspaceRouteContext,resolveContainedCwd,resolveContainedCwdOrFail,resolveSessionManagedGitCwdForRoute};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2026 Qwen Team
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{LEASE_PREFIX,REVIEW_TMP_DIR,inertPath,reviewBranch,reviewTrustStateDir}from"./chunk-
|
|
3
|
+
import{LEASE_PREFIX,REVIEW_TMP_DIR,inertPath,reviewBranch,reviewTrustStateDir}from"./chunk-UK5SIRH4.js";import{writeStderrLineSafe}from"./chunk-M4ECEHLX.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{execFileSync}from"node:child_process";import{randomBytes}from"node:crypto";import{existsSync,lstatSync,mkdirSync,readFileSync,readdirSync,renameSync,rmdirSync,rmSync,writeFileSync}from"node:fs";import{basename,dirname,isAbsolute,join,relative,resolve}from"node:path";var GIT_TIMEOUT_MS=12e4;var debugLogger=createDebugLogger("REVIEW_WORKTREE_LEASE");function gitOptions(timeout){return{stdio:"ignore",timeout,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}}__name(gitOptions,"gitOptions");function validTarget(target){return/^pr-\d+$/.test(target)}__name(validTarget,"validTarget");function isReviewLeaseFile(fileName){if(!fileName.startsWith(LEASE_PREFIX)||!fileName.endsWith(".json")){return false}const target=fileName.slice(LEASE_PREFIX.length,fileName.length-".json".length);return validTarget(target)}__name(isReviewLeaseFile,"isReviewLeaseFile");function leaseDirectory(repositoryRoot){return reviewTrustStateDir(repositoryRoot)}__name(leaseDirectory,"leaseDirectory");function legacyLeasePath(repositoryRoot,target){return join(repositoryRoot,REVIEW_TMP_DIR,`${LEASE_PREFIX}${target}.json`)}__name(legacyLeasePath,"legacyLeasePath");function leasePath(repositoryRoot,target){return join(leaseDirectory(repositoryRoot),`${LEASE_PREFIX}${target}.json`)}__name(leasePath,"leasePath");function clearReviewWorktreeLease(repositoryRoot,target){if(!validTarget(target))return;const root=resolve(repositoryRoot);rmSync(leasePath(root,target),{force:true});reclaimBaseTreeTrust(root,target);const legacy=legacyLeasePath(root,target);try{rmSync(legacy,{force:true,recursive:true})}catch(error){writeStderrLineSafe(`warning: could not remove the pre-move review lease at ${legacy} (${error.code??error}); the trusted lease for ${target} is released, but a build from before the lease move will keep seeing this one until it is deleted by hand.`)}}__name(clearReviewWorktreeLease,"clearReviewWorktreeLease");function clearReviewWorktreeLeaseIfOwned(repositoryRoot,target,owner){const lease=readReviewWorktreeLease(repositoryRoot,target);if(!lease||lease.sessionId!==owner.sessionId||lease.promptId!==owner.promptId){return}clearReviewWorktreeLease(repositoryRoot,target)}__name(clearReviewWorktreeLeaseIfOwned,"clearReviewWorktreeLeaseIfOwned");function mintIdentity(){return Math.floor(Date.now()/1e3)*2**20+randomBytes(3).readUIntBE(0,3)%2**20}__name(mintIdentity,"mintIdentity");function recordReviewWorktreeLeaseMergeBase(repositoryRoot,target,mergeBaseSha,sessionId,options={}){if(!validTarget(target)||!mergeBaseSha)return;const stale=options.stale===true;const root=resolve(repositoryRoot);const path=leasePath(root,target);const existing=readLease(path);if(!existing)return;if(sessionId!==void 0&&existing.sessionId!==sessionId)return;if(existing.mergeBaseSha===mergeBaseSha&&existing.mergeBaseStale===true===stale){return}const previous=existing.mergeBaseSha??existing.priorMergeBaseSha;const next={...existing,mergeBaseSha,mergeBaseStale:stale,priorMergeBaseSha:mergeBaseSha,priorMergeBaseStale:stale,priorMergeBaseCurrent:true,identity:previous===void 0||previous===mergeBaseSha?existing.identity??mintIdentity():mintIdentity()};try{atomicWriteLease(path,`${JSON.stringify(next,null,2)}
|
|
4
4
|
`)}catch(error){debugLogger.debug(`Failed to record the merge base in ${path}:`,error)}}__name(recordReviewWorktreeLeaseMergeBase,"recordReviewWorktreeLeaseMergeBase");function atomicWriteLease(path,data){const tmp=`${path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;try{writeFileSync(tmp,data,{encoding:"utf8",flag:"wx"});renameSync(tmp,path)}catch(error){try{rmSync(tmp,{force:true})}catch{}throw error}}__name(atomicWriteLease,"atomicWriteLease");function reclaimBaseTreeTrust(root,target){const dir=join(leaseDirectory(root),"base-tree",target);let entries;try{entries=readdirSync(dir)}catch(error){if(error.code!=="ENOENT"){debugLogger.debug(`Failed to reclaim base-tree trust state for ${target}:`,error)}return}for(const name of entries){if(name.endsWith(".lock"))continue;try{rmSync(join(dir,name),{recursive:true,force:true})}catch(error){debugLogger.debug(`Failed to reclaim base-tree trust state ${name} for ${target}:`,error)}}try{rmdirSync(dir)}catch{}}__name(reclaimBaseTreeTrust,"reclaimBaseTreeTrust");function restoreReviewWorktreeLeaseMergeBase(repositoryRoot,target,sessionId){if(!validTarget(target)||!sessionId)return;const path=leasePath(resolve(repositoryRoot),target);const existing=readLease(path);if(!existing||existing.sessionId!==sessionId)return;if(existing.mergeBaseSha!==void 0)return;if(existing.priorMergeBaseResumable!==true)return;const next={...existing,mergeBaseSha:existing.priorMergeBaseSha,mergeBaseStale:existing.priorMergeBaseStale===true,priorMergeBaseCurrent:true};try{atomicWriteLease(path,`${JSON.stringify(next,null,2)}
|
|
5
5
|
`)}catch(error){debugLogger.debug(`Failed to restore the merge base in ${path}:`,error)}}__name(restoreReviewWorktreeLeaseMergeBase,"restoreReviewWorktreeLeaseMergeBase");function createReviewWorktreeLease(params){if(!params.sessionId||!params.promptId||!validTarget(params.target)){return}const repositoryRoot=resolve(params.repositoryRoot);const path=leasePath(repositoryRoot,params.target);const leaseFor=__name((identity,prior)=>{const lease={sessionId:params.sessionId,promptId:params.promptId,target:params.target,repositoryRoot,worktreePath:resolve(repositoryRoot,params.worktreePath),branch:params.branch,identity,...prior===void 0?{}:{priorMergeBaseSha:prior.sha,priorMergeBaseStale:prior.stale,priorMergeBaseResumable:prior.resumable}};return`${JSON.stringify(lease,null,2)}
|
|
6
6
|
`},"leaseFor");let data=leaseFor(mintIdentity());mkdirSync(leaseDirectory(repositoryRoot),{recursive:true,mode:448});const legacy=legacyLeasePath(repositoryRoot,params.target);try{writeFileSync(path,data,{encoding:"utf8",flag:"wx"})}catch(error){if(error.code!=="EEXIST")throw error;const existing=readLease(path);if(existing&&existing.sessionId!==params.sessionId){throw new Error(`review worktree lease for ${params.target} is held by another session (session ${existing.sessionId}) at ${path}; it was acquired between the gate read and the lease write \u2014 retry`)}if(existing){data=leaseFor(typeof existing.identity==="number"&&Number.isFinite(existing.identity)?existing.identity:mintIdentity(),existing.mergeBaseSha!==void 0?{sha:existing.mergeBaseSha,stale:existing.mergeBaseStale===true,resumable:existing.priorMergeBaseCurrent===true}:existing.priorMergeBaseSha!==void 0?{sha:existing.priorMergeBaseSha,stale:existing.priorMergeBaseStale===true,resumable:existing.priorMergeBaseCurrent===true}:void 0)}atomicWriteLease(path,data)}mirrorLeaseAtLegacyPath(legacy,data,params.sessionId,params.target)}__name(createReviewWorktreeLease,"createReviewWorktreeLease");function mirrorLeaseAtLegacyPath(legacy,data,sessionId,target){try{mkdirSync(dirname(legacy),{recursive:true});writeFileSync(legacy,data,{encoding:"utf8",flag:"wx"});return}catch(error){if(error.code!=="EEXIST"){warnMirrorSkipped(legacy,error);return}}const displaced=readLease(legacy);const tmp=`${legacy}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;try{writeFileSync(tmp,data,{encoding:"utf8",flag:"wx"});renameSync(tmp,legacy)}catch(error){try{rmSync(tmp,{force:true})}catch{}warnMirrorSkipped(legacy,error);return}if(displaced&&displaced.sessionId!==sessionId){writeStderrLineSafe(`warning: replaced the pre-move review lease for ${target} at ${legacy} (recorded session ${inertSessionId(displaced.sessionId)}) \u2014 if a pre-move build is still reviewing ${target} on this machine, its worktree is no longer protected; otherwise this was residue or a plant, and it is gone.`)}}__name(mirrorLeaseAtLegacyPath,"mirrorLeaseAtLegacyPath");function inertSessionId(id){const inert=inertPath(id);return inert.length>120?`${inert.slice(0,120)}\u2026`:inert}__name(inertSessionId,"inertSessionId");function warnMirrorSkipped(legacy,error){writeStderrLineSafe(`warning: could not mirror the review worktree lease to the pre-move path ${legacy} (${error.code??error}); the acquisition stands on the new-path lease, but builds from before the lease move will not see this lock.`)}__name(warnMirrorSkipped,"warnMirrorSkipped");function readLease(path){try{if(!lstatSync(path).isFile()){rmSync(path,{force:true,recursive:true});return null}}catch(error){if(error.code!=="ENOENT"){debugLogger.debug(`Failed to inspect review lease ${path}:`,error)}return null}try{const value=JSON.parse(readFileSync(path,"utf8"));if(typeof value.sessionId!=="string"||typeof value.promptId!=="string"||typeof value.target!=="string"||typeof value.repositoryRoot!=="string"||typeof value.worktreePath!=="string"||typeof value.branch!=="string"||value.identity!==void 0&&(typeof value.identity!=="number"||!Number.isFinite(value.identity))||value.mergeBaseSha!==void 0&&typeof value.mergeBaseSha!=="string"||value.priorMergeBaseSha!==void 0&&typeof value.priorMergeBaseSha!=="string"||value.mergeBaseStale!==void 0&&typeof value.mergeBaseStale!=="boolean"||value.priorMergeBaseStale!==void 0&&typeof value.priorMergeBaseStale!=="boolean"||value.priorMergeBaseCurrent!==void 0&&typeof value.priorMergeBaseCurrent!=="boolean"||value.priorMergeBaseResumable!==void 0&&typeof value.priorMergeBaseResumable!=="boolean"){return null}return value}catch(error){debugLogger.debug(`Failed to read review lease ${path}:`,error);return null}}__name(readLease,"readLease");function readReviewWorktreeLease(repositoryRoot,target){return readReviewWorktreeLeaseAt(repositoryRoot,target)?.lease??null}__name(readReviewWorktreeLease,"readReviewWorktreeLease");function readReviewWorktreeLeaseAt(repositoryRoot,target){if(!validTarget(target))return null;const root=resolve(repositoryRoot);const current=leasePath(root,target);const lease=readLease(current);return lease?{lease,path:current}:null}__name(readReviewWorktreeLeaseAt,"readReviewWorktreeLeaseAt");function reviewLeaseHeldByAnotherSession(lease){if(!lease)return false;const sessionId=process.env["QWEN_CODE_SESSION_ID"]?.trim();return!sessionId||lease.sessionId!==sessionId}__name(reviewLeaseHeldByAnotherSession,"reviewLeaseHeldByAnotherSession");function sameLease(a,b){return b!==null&&a.sessionId===b.sessionId&&a.promptId===b.promptId&&a.target===b.target&&a.repositoryRoot===b.repositoryRoot&&a.worktreePath===b.worktreePath&&a.branch===b.branch}__name(sameLease,"sameLease");function removeLeaseWorktree(lease,gitTimeout){const prMatch=/^pr-(\d+)$/.exec(lease.target);if(!prMatch||lease.branch!==reviewBranch(prMatch[1])){debugLogger.debug(`Rejected invalid review lease ${lease.target}`);return false}const repositoryRoot=resolve(lease.repositoryRoot);const worktreePath=resolve(lease.worktreePath);const reviewTmpRoot=resolve(repositoryRoot,REVIEW_TMP_DIR);const worktreeRelative=relative(reviewTmpRoot,worktreePath);if(worktreeRelative===""||worktreeRelative.startsWith("..")||isAbsolute(worktreeRelative)){debugLogger.debug(`Rejected review lease outside ${REVIEW_TMP_DIR}: ${worktreePath}`);return false}try{execFileSync("git",["-C",repositoryRoot,"worktree","remove",worktreePath,"--force"],gitOptions(gitTimeout))}catch(error){debugLogger.debug(`Git failed to remove review worktree ${lease.target}:`,error);try{rmSync(worktreePath,{recursive:true,force:true});execFileSync("git",["-C",repositoryRoot,"worktree","prune"],gitOptions(gitTimeout))}catch(fallbackError){debugLogger.debug(`Fallback failed to remove review worktree ${lease.target}:`,fallbackError);return false}}let branchExists=true;try{execFileSync("git",["-C",repositoryRoot,"show-ref","--verify","--quiet",`refs/heads/${lease.branch}`],gitOptions(gitTimeout))}catch(error){if(error.status!==1){debugLogger.debug(`Failed to inspect review branch ${lease.branch}:`,error);return false}branchExists=false}if(branchExists){try{execFileSync("git",["-C",repositoryRoot,"branch","-D",lease.branch],gitOptions(gitTimeout))}catch(error){debugLogger.debug(`Failed to delete review branch ${lease.branch}:`,error);return false}}return!existsSync(worktreePath)}__name(removeLeaseWorktree,"removeLeaseWorktree");function cleanupReviewWorktreeLeases(params){try{const repositoryRoot=resolve(params.repositoryRoot);const newLeaseDirectory=leaseDirectory(repositoryRoot);if(!existsSync(newLeaseDirectory))return;let entries;try{entries=readdirSync(newLeaseDirectory)}catch(error){debugLogger.debug(`Failed to list ${newLeaseDirectory} for lease cleanup:`,error);return}for(const entry of entries){if(!isReviewLeaseFile(entry))continue;const path=join(newLeaseDirectory,basename(entry));const lease=readLease(path);if(!lease||lease.sessionId!==params.sessionId||lease.promptId!==params.promptId||resolve(lease.repositoryRoot)!==repositoryRoot){continue}if(!removeLeaseWorktree(lease,params.gitTimeout??GIT_TIMEOUT_MS)){continue}rmSync(path,{force:true});reclaimBaseTreeTrust(repositoryRoot,lease.target);const twin=join(repositoryRoot,REVIEW_TMP_DIR,basename(entry));try{if(sameLease(lease,readLease(twin))){rmSync(twin,{force:true})}}catch(error){debugLogger.debug(`Failed to remove legacy lease twin ${twin}:`,error)}}}catch(error){debugLogger.debug("Failed to clean up review worktree leases:",error)}}__name(cleanupReviewWorktreeLeases,"cleanupReviewWorktreeLeases");export{isReviewLeaseFile,clearReviewWorktreeLease,clearReviewWorktreeLeaseIfOwned,recordReviewWorktreeLeaseMergeBase,restoreReviewWorktreeLeaseMergeBase,createReviewWorktreeLease,readReviewWorktreeLease,readReviewWorktreeLeaseAt,reviewLeaseHeldByAnotherSession,cleanupReviewWorktreeLeases};
|