gerege-cli 0.26.7 → 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-LSNOJEKM.js → MaxSizedBox-LUINLOQW.js} +1 -1
- package/chunks/{StandaloneSessionPicker-KSYGPMEV.js → StandaloneSessionPicker-B7N4QO5D.js} +1 -1
- package/chunks/{acp-subagent-executor-NSW2MFUI.js → acp-subagent-executor-J6H6FKUT.js} +1 -1
- package/chunks/{acpAgent-3DTOHTDM.js → acpAgent-XG6SM2VU.js} +3 -3
- package/chunks/{advisor-7JGQPS7X.js → advisor-SZVPQNPA.js} +1 -1
- package/chunks/{agent-PNKQJGDO.js → agent-N7QF7BJS.js} +1 -1
- package/chunks/{agent-headless-7D33X7QQ.js → agent-headless-GLP5GUEX.js} +1 -1
- package/chunks/{agent-host-client-3R2MAUVE.js → agent-host-client-H4VOB3M6.js} +1 -1
- package/chunks/{agent-host-connections-2D7DECAE.js → agent-host-connections-E4C3OC4M.js} +1 -1
- package/chunks/{anthropicContentGenerator-MGTJJGEQ.js → anthropicContentGenerator-5VTWQLT5.js} +1 -1
- package/chunks/{autofix-pr-OIHHZSPQ.js → autofix-pr-HDYQDJS4.js} +1 -1
- package/chunks/{batch-6UDAMPAA.js → batch-3CRVN5VJ.js} +1 -1
- package/chunks/{bridge-QXVXPNJ6.js → bridge-NZ6WVBLQ.js} +1 -1
- package/chunks/{channel-settings-store-P4W4R5SJ.js → channel-settings-store-Z7I2JI6M.js} +1 -1
- package/chunks/{chunk-HVP4UF2Q.js → chunk-236DHGNH.js} +1 -1
- package/chunks/{chunk-GA35LMSX.js → chunk-2M3ND5WN.js} +1 -1
- package/chunks/{chunk-IZXHCHJD.js → chunk-36A6EXHB.js} +1 -1
- package/chunks/{chunk-QHYSRPQR.js → chunk-3ANIQTDT.js} +1 -1
- package/chunks/{chunk-WK666FGZ.js → chunk-3QTR2HAE.js} +3 -3
- package/chunks/{chunk-3EZ5GCUT.js → chunk-3TTHYXT3.js} +1 -1
- package/chunks/{chunk-YWK3E4WJ.js → chunk-4CE4GMDL.js} +1 -1
- package/chunks/{chunk-VUNHJ74J.js → chunk-4FVT657Y.js} +1 -1
- package/chunks/{chunk-BY46PCWY.js → chunk-4HSISRRA.js} +1 -1
- package/chunks/{chunk-2LMSDH6P.js → chunk-4SZUJ5RT.js} +1 -1
- package/chunks/{chunk-53IB4U4E.js → chunk-57D2OB3I.js} +1 -1
- package/chunks/{chunk-QTKPC24L.js → chunk-5FGBLIXB.js} +1 -1
- package/chunks/{chunk-5TWAP4OG.js → chunk-5HX2QGVR.js} +1 -1
- package/chunks/{chunk-K7GN4CMV.js → chunk-5ZNXAWOG.js} +6 -6
- package/chunks/{chunk-QTVSPQZQ.js → chunk-6CKX56LJ.js} +1 -1
- package/chunks/{chunk-4W27Z3OL.js → chunk-6NIQFWXP.js} +1 -1
- package/chunks/{chunk-6YFNUVJR.js → chunk-6PC6MZHL.js} +1 -1
- package/chunks/{chunk-DQQN2HOP.js → chunk-6VQKGKMJ.js} +1 -1
- package/chunks/{chunk-MXZXQUVP.js → chunk-6ZEMLEK2.js} +1 -1
- package/chunks/{chunk-RT6J7PV4.js → chunk-72VY2PJA.js} +1 -1
- package/chunks/{chunk-EEPNACXJ.js → chunk-75I3NYBD.js} +1 -1
- package/chunks/{chunk-ATTJQLQV.js → chunk-76L7ZDEK.js} +1 -1
- package/chunks/{chunk-T3CQ72HC.js → chunk-7XQ5D34E.js} +6 -6
- package/chunks/{chunk-4AKTP4MM.js → chunk-AYX75VXG.js} +1 -1
- package/chunks/{chunk-MDCA4I63.js → chunk-BBDFEMCF.js} +1 -1
- package/chunks/{chunk-N4ZQC5HB.js → chunk-BOTX7S66.js} +1 -1
- package/chunks/{chunk-UVMLWDRU.js → chunk-CY2QKKZA.js} +1 -1
- package/chunks/{chunk-W2CV36HT.js → chunk-D5JWQUID.js} +1 -1
- package/chunks/{chunk-WEPC42YR.js → chunk-DMIPB7RZ.js} +1 -1
- package/chunks/{chunk-BVV7UXES.js → chunk-DSKA3P2C.js} +1 -1
- package/chunks/{chunk-SAVYMUU3.js → chunk-DVC65H4X.js} +1 -1
- package/chunks/{chunk-MS2XCBPP.js → chunk-DVJSDCMX.js} +1 -1
- package/chunks/{chunk-4QOVM2LL.js → chunk-E6CPFQX2.js} +1 -1
- package/chunks/{chunk-LYFRGP42.js → chunk-EIFBGEXJ.js} +1 -1
- package/chunks/{chunk-3ICJI5KW.js → chunk-EQOHDAYU.js} +1 -1
- package/chunks/{chunk-Q5RRVBTY.js → chunk-EZPM4DLR.js} +1 -1
- package/chunks/{chunk-ISQMHOCC.js → chunk-F6U6T7QD.js} +1 -1
- package/chunks/{chunk-WCI33URB.js → chunk-FCGFBUHS.js} +1 -1
- package/chunks/{chunk-CK3OKTTL.js → chunk-G2LTZU67.js} +1 -1
- package/chunks/{chunk-WSI4G7XC.js → chunk-GMJSEK4V.js} +1 -1
- package/chunks/{chunk-QONPET6Y.js → chunk-HJMUBVXZ.js} +2 -2
- package/chunks/{chunk-H5EXNXGW.js → chunk-HQZTAA2U.js} +1 -1
- package/chunks/{chunk-5R2JIZID.js → chunk-I63TIQOI.js} +1 -1
- package/chunks/{chunk-IY7M5HKF.js → chunk-I65LBJN7.js} +1 -1
- package/chunks/{chunk-H34KVVI4.js → chunk-IBDOC27R.js} +1 -1
- package/chunks/{chunk-N6EFYQ7M.js → chunk-IKF2HWEV.js} +1 -1
- package/chunks/{chunk-CDKBM72V.js → chunk-K6NS2HXT.js} +1 -1
- package/chunks/{chunk-BIPPD7W6.js → chunk-KTRNYPQP.js} +1 -1
- package/chunks/{chunk-DTX2OVQW.js → chunk-L3ANU5JZ.js} +1 -1
- package/chunks/{chunk-WXK7Z45R.js → chunk-LKPMADUO.js} +1 -1
- package/chunks/{chunk-4VR4DUUD.js → chunk-M56Y2B6N.js} +1 -1
- package/chunks/{chunk-YY4GWNTU.js → chunk-N5KRBAK5.js} +2 -2
- package/chunks/{chunk-DVUKYOCJ.js → chunk-NA2WJPOU.js} +1 -1
- package/chunks/{chunk-O3TUZQP4.js → chunk-NGOWLXYK.js} +1 -1
- package/chunks/{chunk-F7622ZRQ.js → chunk-NL7P73ZP.js} +1 -1
- package/chunks/{chunk-U5YOAOU3.js → chunk-NS3QR7D3.js} +1 -1
- package/chunks/{chunk-FTF2NFLB.js → chunk-O5JCCBMQ.js} +1 -1
- package/chunks/{chunk-DEJ47KJE.js → chunk-OOKFFZHF.js} +1 -1
- package/chunks/{chunk-4A663FE6.js → chunk-OTYPLLMT.js} +5 -5
- package/chunks/{chunk-NPAENNRO.js → chunk-P7NHWX27.js} +1 -1
- package/chunks/{chunk-HXTYFGSQ.js → chunk-PC5QZUKR.js} +1 -1
- package/chunks/{chunk-RULGA7WE.js → chunk-PS7MQL57.js} +2 -2
- package/chunks/{chunk-FKUDVIME.js → chunk-PXWHOFAA.js} +1 -1
- package/chunks/{chunk-6WV5RKYB.js → chunk-Q65LVCDR.js} +1 -1
- package/chunks/{chunk-ULLW2AYD.js → chunk-QDUDLELH.js} +1 -1
- package/chunks/{chunk-PMBI46K4.js → chunk-QF22ILPV.js} +1 -1
- package/chunks/{chunk-LY4XTBL4.js → chunk-QW7MAG2E.js} +1 -1
- package/chunks/{chunk-IIHUDJX7.js → chunk-RXK6XD6F.js} +1 -1
- package/chunks/{chunk-QSPXKBUX.js → chunk-SVDFCWS7.js} +1 -1
- package/chunks/{chunk-NHPKD7LY.js → chunk-TKP3GAUI.js} +1 -1
- package/chunks/{chunk-WF7Q3ZSQ.js → chunk-TUS74LFI.js} +1 -1
- package/chunks/{chunk-OZFZBGZG.js → chunk-U7YGHPSL.js} +1 -1
- package/chunks/{chunk-G4MWPXNY.js → chunk-UB37RBSK.js} +1 -1
- package/chunks/{chunk-4LC4INFI.js → chunk-UK5SIRH4.js} +1 -1
- package/chunks/{chunk-7HFFTOAD.js → chunk-UTTSBCFR.js} +1 -1
- package/chunks/{chunk-IQMKQKKD.js → chunk-UYV4ZVXY.js} +2 -2
- package/chunks/{chunk-E3KWSRJN.js → chunk-VC3JJL7E.js} +1 -1
- package/chunks/{chunk-FRVXSKL4.js → chunk-VKWVIWLK.js} +1 -1
- package/chunks/{chunk-L7LO3YRT.js → chunk-VUI6STKU.js} +1 -1
- package/chunks/{chunk-VK7LOUOJ.js → chunk-W3YXE55M.js} +1 -1
- package/chunks/{chunk-JHC22BZH.js → chunk-WAIPC47V.js} +1 -1
- package/chunks/{chunk-P2MZZMCS.js → chunk-WMJ6UHDP.js} +1 -1
- package/chunks/{chunk-6JAXAFX7.js → chunk-WZU2ECUD.js} +1 -1
- package/chunks/{chunk-HJLRKM3W.js → chunk-XAGIZY2Y.js} +1 -1
- package/chunks/{chunk-2J2BQ3PL.js → chunk-XGZYVULJ.js} +2 -2
- package/chunks/{chunk-QVHDM6N7.js → chunk-XJIHDVPX.js} +1 -1
- package/chunks/{chunk-ZFOEVHWG.js → chunk-XVDIHFRH.js} +1 -1
- package/chunks/{chunk-F5SLLEJY.js → chunk-YMEW4TTT.js} +1 -1
- package/chunks/{chunk-NYBYDW6R.js → chunk-Z32URWBG.js} +1 -1
- package/chunks/{chunk-WMLYHZZX.js → chunk-Z6HRXHJP.js} +1 -1
- package/chunks/{chunk-UM5KBBYP.js → chunk-ZO4F6ZWR.js} +1 -1
- package/chunks/{codex-subagent-executor-GPTKVP7H.js → codex-subagent-executor-DDKYNU42.js} +1 -1
- package/chunks/{config-utils-6B5FHBSF.js → config-utils-S7Z2ZZ2E.js} +1 -1
- package/chunks/{contextCommand-FGRDE3GA.js → contextCommand-7F4PGV2A.js} +1 -1
- package/chunks/{core-runtime-OFEHSKDB.js → core-runtime-LBH3U7ZF.js} +1 -1
- package/chunks/{create-sub-session-D2KEWVHQ.js → create-sub-session-56DS2T6L.js} +1 -1
- package/chunks/{cron-create-RFGGKTL7.js → cron-create-PBP3C46Q.js} +1 -1
- package/chunks/{daemon-git-worktree-guard-AV752IOZ.js → daemon-git-worktree-guard-WJS6FBDA.js} +1 -1
- package/chunks/{daemon-status-provider-GHQBRDMC.js → daemon-status-provider-UPPAEHJ6.js} +1 -1
- package/chunks/{daemon-trust-policy-24ENJNTQ.js → daemon-trust-policy-4Z5HSNUX.js} +1 -1
- package/chunks/{daemon-trust-policy-monitor-NMSQAGWV.js → daemon-trust-policy-monitor-WFWDOYX3.js} +1 -1
- package/chunks/{deferred-core-runtime-5BAMFFOI.js → deferred-core-runtime-MJYNEA4N.js} +1 -1
- package/chunks/{edit-XCECLEH3.js → edit-U7TGKKK3.js} +1 -1
- package/chunks/{enterPlanMode-SEN2PMRM.js → enterPlanMode-27HC5AXN.js} +1 -1
- package/chunks/{environment-CCPQJYKS.js → environment-PHWY6C4P.js} +1 -1
- package/chunks/{errors-Y6HHUTGK.js → errors-F2EYYFI3.js} +1 -1
- package/chunks/{execution-tool-HADWGMIG.js → execution-tool-O4KJ5SMM.js} +1 -1
- package/chunks/{execution-worker-GZS7WOQL.js → execution-worker-AMFXZ7JD.js} +1 -1
- package/chunks/{exitPlanMode-76B5HDLT.js → exitPlanMode-LDYL43PB.js} +1 -1
- package/chunks/{fast-path-OEV7LQYV.js → fast-path-HTODEVOR.js} +1 -1
- package/chunks/{glob-NLWCQRMS.js → glob-NKQJJZND.js} +1 -1
- package/chunks/{goal-tools-43XV33BT.js → goal-tools-47I455VV.js} +1 -1
- package/chunks/{handleAutoUpdate-JDQWGSSP.js → handleAutoUpdate-MJKTDJUO.js} +1 -1
- package/chunks/{i18n-JW6BVEGF.js → i18n-TCOB4TC5.js} +1 -1
- package/chunks/{initializer-UT6JLZ3O.js → initializer-NLYOGZZS.js} +1 -1
- package/chunks/{installationInfo-LKWDV3S2.js → installationInfo-TF2RSJOG.js} +1 -1
- package/chunks/{interactive-mod-session-2KWKYVPC.js → interactive-mod-session-5F7R3KSA.js} +1 -1
- package/chunks/{list-BKINK3S2.js → list-U2AEVLFP.js} +1 -1
- package/chunks/{llm-3RWXAVM2.js → llm-EV2QTQBU.js} +4 -4
- package/chunks/{llm-content-generator-MDRBSH73.js → llm-content-generator-ZXUSPPG2.js} +1 -1
- package/chunks/{loadedSettingsAdapter-WWJUKWUN.js → loadedSettingsAdapter-TLRI22X7.js} +1 -1
- package/chunks/{local-TT4FLCTR.js → local-ZTSBSKWV.js} +1 -1
- package/chunks/{local-execution-environment-OBA6VWYL.js → local-execution-environment-F263PSIM.js} +1 -1
- package/chunks/{loggingContentGenerator-CK7IKYQH.js → loggingContentGenerator-2XHSIJQD.js} +1 -1
- package/chunks/{loop-wakeup-4MSRX3DY.js → loop-wakeup-5ET3JHUT.js} +1 -1
- package/chunks/{manage-memory-PX5PZJKZ.js → manage-memory-MJEQ47H2.js} +1 -1
- package/chunks/{managed-execution-engine-WMAUR3ZK.js → managed-execution-engine-ODPR5OEH.js} +1 -1
- package/chunks/{managed-local-serve-X7REHGB4.js → managed-local-serve-S5R4Z5OL.js} +1 -1
- package/chunks/managed-npm-update-BUI5APGY.js +8 -0
- package/chunks/{managed-runtime-attestation-worker-F4AT53M5.js → managed-runtime-attestation-worker-BQP4E7LQ.js} +1 -1
- package/chunks/{managed-runtime-bootstrap-3BP5JRJX.js → managed-runtime-bootstrap-SRBDFSKK.js} +1 -1
- package/chunks/{managed-runtime-session-worker-2PO7J5UK.js → managed-runtime-session-worker-UI23BTYJ.js} +1 -1
- package/chunks/{managed-runtime-ssh-worker-4N7EMRSV.js → managed-runtime-ssh-worker-HU4CIJRK.js} +1 -1
- package/chunks/{managed-session-authority-MYOYTUM2.js → managed-session-authority-XSSTLAEY.js} +1 -1
- package/chunks/{mcp-5OTEMZ7P.js → mcp-WLHDOKP7.js} +1 -1
- package/chunks/{memory-TNW7RSAV.js → memory-OUUHPSDD.js} +1 -1
- package/chunks/{model-call-collection-KNTWFZQS.js → model-call-collection-4A2EB76B.js} +1 -1
- package/chunks/{model-configuration-U5C5P5UQ.js → model-configuration-4CGUFKEP.js} +1 -1
- package/chunks/{modelConfigUtils-R4KFI2WK.js → modelConfigUtils-HUEERWBA.js} +1 -1
- package/chunks/{monitor-RD2PFK42.js → monitor-FXL5UNMP.js} +1 -1
- package/chunks/{nonInteractiveCli-QQ72HZSH.js → nonInteractiveCli-W7M2O43W.js} +1 -1
- package/chunks/{nonInteractiveToolExecutor-QPQYR6IS.js → nonInteractiveToolExecutor-EMLI363Q.js} +1 -1
- package/chunks/{notebook-edit-YLRN3UZT.js → notebook-edit-R5RSLSSH.js} +1 -1
- package/chunks/{omni-CUJ52EW5.js → omni-DNZGITTE.js} +1 -1
- package/chunks/{openaiContentGenerator-6B5MAU54.js → openaiContentGenerator-PKOPYMHR.js} +1 -1
- package/chunks/{openaiResponsesContentGenerator-I245I3R7.js → openaiResponsesContentGenerator-MHH2MF3V.js} +1 -1
- package/chunks/{pidfile-P2HIGAUA.js → pidfile-5ZNJWMKG.js} +1 -1
- package/chunks/{processUtils-JSKN5UGS.js → processUtils-JIHQDASW.js} +1 -1
- package/chunks/{prompt-terminal-ledger-F5TSXVGU.js → prompt-terminal-ledger-L3LZ5SLR.js} +1 -1
- package/chunks/{qwenContentGenerator-IEDZONWG.js → qwenContentGenerator-QCZL7HJJ.js} +1 -1
- package/chunks/{reactive-degrade-FYZBJCF6.js → reactive-degrade-YUXOUQG4.js} +1 -1
- package/chunks/{read-file-VNZNSD6X.js → read-file-FBNU3AVX.js} +1 -1
- package/chunks/{resumeHistoryUtils-IDPE6N2N.js → resumeHistoryUtils-5FPRTI4A.js} +1 -1
- package/chunks/{review-TBJRZWTD.js → review-NLFYSNM3.js} +1 -1
- package/chunks/{ripGrep-4W5B5FOE.js → ripGrep-JUAPC5LD.js} +1 -1
- package/chunks/{run-qwen-serve-44X262G5.js → run-qwen-serve-JP64UQ3Y.js} +1 -1
- package/chunks/{runtime-6H6LKD73.js → runtime-D2QUYM6U.js} +1 -1
- package/chunks/{sandboxConfig-SQXDRGVN.js → sandboxConfig-7VZJQV6H.js} +1 -1
- package/chunks/{scheduled-tasks-62IZKHJG.js → scheduled-tasks-PC6EH75E.js} +1 -1
- package/chunks/{scheduler-QUCXJYRL.js → scheduler-RUV2FNDR.js} +1 -1
- package/chunks/{search-memory-TC2Z34QN.js → search-memory-YJTJ7BRU.js} +1 -1
- package/chunks/{send-message-TFZX7KI7.js → send-message-EEEFFTHX.js} +1 -1
- package/chunks/{serve-WSICDFGG.js → serve-KMIZDYON.js} +1 -1
- package/chunks/{server-GYYVTNGY.js → server-DUPK3V7B.js} +3 -3
- package/chunks/{session-KF3O23ZJ.js → session-CW5YMFMP.js} +1 -1
- package/chunks/{session-attachments-root-7HFUSONH.js → session-attachments-root-5H5GFHLI.js} +1 -1
- package/chunks/{session-execution-engine-selector-NVILT6BR.js → session-execution-engine-selector-MVXM2HZW.js} +1 -1
- package/chunks/{session-pr-refresh-3KDFTDEV.js → session-pr-refresh-4UPONX4L.js} +1 -1
- package/chunks/{sessionService-XRTFLPDW.js → sessionService-GGCYISSL.js} +1 -1
- package/chunks/{settings-QPPK6WXE.js → settings-AASJCESS.js} +1 -1
- package/chunks/{shell-WYQDZWL7.js → shell-V4WWLW3Q.js} +1 -1
- package/chunks/{skill-FYPT6AU7.js → skill-NDEBB7VX.js} +1 -1
- package/chunks/{skill-settings-OGFI5KZF.js → skill-settings-YAI3GYU5.js} +1 -1
- package/chunks/{spawnChannel-ANOOVPG7.js → spawnChannel-6JKVJAXZ.js} +1 -1
- package/chunks/{standalone-update-45WTDY4E.js → standalone-update-NJP5OCKJ.js} +1 -1
- package/chunks/{start-opentui-ui-TL5WK33V.js → start-opentui-ui-M4B4SXRM.js} +1 -1
- package/chunks/{startInteractiveUI-N2IREVBM.js → startInteractiveUI-O4JUDEAU.js} +1 -1
- package/chunks/{team-create-R77PRZ5U.js → team-create-NLJ7QBLD.js} +1 -1
- package/chunks/{team-plan-approval-6DCRKB5I.js → team-plan-approval-XKYPVWNG.js} +1 -1
- package/chunks/{terminal-image-renderer-TB7EX2WW.js → terminal-image-renderer-47TD747D.js} +1 -1
- package/chunks/{theme-manager-RQDXJGVR.js → theme-manager-AANEBPLJ.js} +1 -1
- package/chunks/{tool-call-LVB4NCDT.js → tool-call-ETH3LS7Y.js} +1 -1
- package/chunks/{tool-result-media-LRBB2KS6.js → tool-result-media-EFOEPAF2.js} +1 -1
- package/chunks/{tool-search-OG73QAQZ.js → tool-search-J3CF5PRN.js} +1 -1
- package/chunks/{total-session-admission-A4CUF6AD.js → total-session-admission-3DC52PLQ.js} +1 -1
- package/chunks/{trustedFolders-LSGOYTU2.js → trustedFolders-4KPWZZKB.js} +1 -1
- package/chunks/{update-relaunch-OGC6BZO7.js → update-relaunch-A67BS7QS.js} +1 -1
- package/chunks/{updateCheck-7J3GXTER.js → updateCheck-X623JRSY.js} +1 -1
- package/chunks/{upload-config-ML5XEJIF.js → upload-config-X2CR3F26.js} +1 -1
- package/chunks/{useAutoAcceptIndicator-6DH6GQ2X.js → useAutoAcceptIndicator-INIOQGJH.js} +1 -1
- package/chunks/{validateNonInterActiveAuth-KJDAGZCM.js → validateNonInterActiveAuth-XJ2U5CLB.js} +1 -1
- package/chunks/{version-7JN2YXL2.js → version-MFHRMM7W.js} +1 -1
- package/chunks/{web-fetch-42ZR4FEZ.js → web-fetch-3GEJ62DH.js} +1 -1
- package/chunks/{web-search-74NLPMZJ.js → web-search-WJZO3Q3A.js} +1 -1
- package/chunks/{workflow-WNPHX42I.js → workflow-ML7ITCMH.js} +1 -1
- package/chunks/{workflow-ancestor-trust-HGF6G7LQ.js → workflow-ancestor-trust-M3VFMS73.js} +1 -1
- package/chunks/{workspace-agents-3YFBFAK3.js → workspace-agents-YFZMV7EF.js} +1 -1
- package/chunks/{workspace-providers-status-EPJI6KRV.js → workspace-providers-status-3COKLBCI.js} +1 -1
- package/chunks/{workspace-recovery-worker-T3FK5YOD.js → workspace-recovery-worker-QURA3WFZ.js} +1 -1
- package/chunks/{workspace-registration-store-VEXYBDMA.js → workspace-registration-store-F3AGIOBW.js} +1 -1
- package/chunks/{workspace-registry-NRZYTP2X.js → workspace-registry-QUBL3RW6.js} +1 -1
- package/chunks/{workspace-runtime-coordinator-USNSTP2V.js → workspace-runtime-coordinator-22TSDHXX.js} +1 -1
- package/chunks/{workspace-service-USATWO56.js → workspace-service-UUENTHNO.js} +1 -1
- package/chunks/{workspace-skills-status-M5JTSFDL.js → workspace-skills-status-NNQQBBCJ.js} +1 -1
- package/chunks/{workspace-trust-reconciler-ZUZ2O5WC.js → workspace-trust-reconciler-3CMMNCGG.js} +1 -1
- package/chunks/{write-file-UMJVKE4S.js → write-file-DEAFIK4C.js} +1 -1
- package/chunks/{zoom-image-76XYHQ3Z.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/package.json +2 -12
- package/chunks/managed-npm-update-6HUVAJH7.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{msSinceLastInteraction}from"./chunk-UGLQO5K7.js";import{isValidSessionId}from"./chunk-LGFF5PJA.js";import{DEFAULT_OPENAI_LOG_RETENTION_DAYS}from"./chunk-G4MWPXNY.js";import{resolveOpenAILogDir}from"./chunk-QX7W2HY7.js";import{FILE_HISTORY_DIR,getSubagentsRootDir}from"./chunk-T3CQ72HC.js";import{createDebugLogger,sessionIdContext}from"./chunk-JAUJI56S.js";import{Storage}from"./chunk-EPODBRBP.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{stat as stat3}from"node:fs/promises";import{createHash}from"node:crypto";import{join as join2}from"node:path";init_esbuild_shims();import{opendir,readdir,stat,rm,rmdir,unlink}from"node:fs/promises";import{join}from"node:path";var DEBUG_LOG_FILE_SUFFIX=".txt";var debugLogger=createDebugLogger("HOUSEKEEPING");var MS_PER_DAY=24*60*60*1e3;var MS_PER_HOUR=60*60*1e3;var MIN_DATE_MS=-864e13;var SWEEP_CONCURRENCY=20;function getCutoffDate(cleanupPeriodDays){const periodMs=cleanupPeriodDays>0?cleanupPeriodDays*MS_PER_DAY:MS_PER_HOUR;return new Date(Math.max(Date.now()-periodMs,MIN_DATE_MS))}__name(getCutoffDate,"getCutoffDate");async function sweepOldSessionDirs(root,opts){const result={removed:0,errors:0};const excludes=opts.excludeSessionIds??new Set;let entries;try{entries=await readdir(root,{withFileTypes:true})}catch(e){if(isENOENT(e))return result;debugLogger.error("readdir failed",e);return result}const sessionDirs=entries.filter(e=>e.isDirectory()&&!excludes.has(e.name)).map(e=>join(root,e.name));for(let i=0;i<sessionDirs.length;i+=SWEEP_CONCURRENCY){const batch=sessionDirs.slice(i,i+SWEEP_CONCURRENCY);await Promise.all(batch.map(async dir=>{try{const s=await stat(dir);if(s.mtime<opts.cutoffDate){await rm(dir,{recursive:true,force:true});result.removed++}}catch(err){result.errors++;debugLogger.error(`failed to sweep ${dir}`,err)}}))}if(opts.removeEmptyRoot!==false){await rmdir(root).catch(()=>{})}return result}__name(sweepOldSessionDirs,"sweepOldSessionDirs");async function cleanupOldFileHistoryBackups(opts){return sweepOldSessionDirs(join(Storage.getGlobalQwenDir(),FILE_HISTORY_DIR),opts)}__name(cleanupOldFileHistoryBackups,"cleanupOldFileHistoryBackups");async function cleanupOldSubagentTranscripts(opts){return sweepOldSessionDirs(opts.subagentsRoot,{...opts,removeEmptyRoot:false})}__name(cleanupOldSubagentTranscripts,"cleanupOldSubagentTranscripts");var OPENAI_LOG_FILE_PATTERN=/^openai-(\d{4}-\d{2}-\d{2})T\d{2}-\d{2}-\d{2}\.\d{3}Z-[a-f0-9]{8}(?:-[a-zA-Z0-9._](?:[a-zA-Z0-9._-]*[a-zA-Z0-9._])?)?\.json$/;async function cleanupOldOpenAILogs(opts){const result={removed:0,errors:0,completed:true};if(opts.signal?.aborted){result.completed=false;return result}let dir;try{dir=await opendir(opts.logDir)}catch(e){if(isENOENT(e))return result;debugLogger.error("opendir failed",e);throw e}const cutoffDay=opts.cutoffDate.toISOString().slice(0,10);let batch=[];for await(const entry of dir){if(opts.signal?.aborted){result.completed=false;break}const filenameDate=entry.isFile()?OPENAI_LOG_FILE_PATTERN.exec(entry.name)?.[1]:void 0;if(!filenameDate)continue;const filePath=join(opts.logDir,entry.name);batch.push((async()=>{try{let shouldRemove;if(filenameDate!==cutoffDay){shouldRemove=filenameDate<cutoffDay}else{const s=await stat(filePath);shouldRemove=s.mtime<opts.cutoffDate}if(shouldRemove){await unlink(filePath);result.removed++}}catch(err){if(isENOENT(err))return;result.errors++;debugLogger.error(`failed to sweep ${filePath}`,err)}})());if(batch.length===SWEEP_CONCURRENCY){await Promise.all(batch);batch=[]}}await Promise.all(batch);return result}__name(cleanupOldOpenAILogs,"cleanupOldOpenAILogs");function isENOENT(e){return e?.code==="ENOENT"}__name(isENOENT,"isENOENT");async function cleanupOldDebugLogs(opts){const result={removed:0,errors:0};const root=Storage.getGlobalDebugDir();const excludes=opts.excludeSessionIds??new Set;let entries;try{entries=await readdir(root,{withFileTypes:true})}catch(e){if(isENOENT(e))return result;debugLogger.error("readdir failed",e);return result}const logFiles=entries.flatMap(entry=>{if(!entry.isFile()||!entry.name.endsWith(DEBUG_LOG_FILE_SUFFIX)){return[]}const sessionId=entry.name.slice(0,-DEBUG_LOG_FILE_SUFFIX.length);if(!opts.isValidSessionId(sessionId)||excludes.has(sessionId)){return[]}return[join(root,entry.name)]});for(let i=0;i<logFiles.length;i+=SWEEP_CONCURRENCY){const batch=logFiles.slice(i,i+SWEEP_CONCURRENCY);await Promise.all(batch.map(async filePath=>{try{const s=await stat(filePath);if(s.mtime<opts.cutoffDate){await unlink(filePath);result.removed++}}catch(err){if(isENOENT(err))return;result.errors++;debugLogger.error(`failed to sweep ${filePath}`,err)}}))}return result}__name(cleanupOldDebugLogs,"cleanupOldDebugLogs");init_esbuild_shims();import{mkdir,open,stat as stat2,unlink as unlink2,writeFile}from"node:fs/promises";import{dirname}from"node:path";var debugLogger2=createDebugLogger("HOUSEKEEPING");var ONE_DAY_MS=24*60*60*1e3;var STALE_LOCK_MS=60*60*1e3;async function runThrottledOnce(opts,task){const minIntervalMs=opts.minIntervalMs??ONE_DAY_MS;const staleLockMs=opts.staleLockMs??STALE_LOCK_MS;await mkdir(dirname(opts.lockPath),{mode:448}).catch(()=>{});const firstFreshForMs=await markerFreshForMs(opts.markerPath,minIntervalMs,opts.name);if(firstFreshForMs!==void 0){return{status:"fresh",retryAfterMs:firstFreshForMs}}let acquired=await tryAcquire(opts.lockPath);if(!acquired){try{const s=await stat2(opts.lockPath);if(Date.now()-s.mtimeMs>staleLockMs){await unlink2(opts.lockPath).catch(()=>{});acquired=await tryAcquire(opts.lockPath)}}catch{acquired=await tryAcquire(opts.lockPath)}if(!acquired){debugLogger2.debug(`${opts.name}: skipping, lock held`);return{status:"locked"}}}try{const secondFreshForMs=await markerFreshForMs(opts.markerPath,minIntervalMs,opts.name);if(secondFreshForMs!==void 0){return{status:"fresh",retryAfterMs:secondFreshForMs}}let taskCompleted=false;try{taskCompleted=await task()!==false}finally{if(taskCompleted){try{await writeFile(opts.markerPath,new Date().toISOString())}catch(err){debugLogger2.debug(`${opts.name}: marker write failed (cleanup succeeded)`,err)}}}return{status:taskCompleted?"completed":"incomplete"}}finally{await unlink2(opts.lockPath).catch(()=>{debugLogger2.debug(`${opts.name}: lock unlink failed (harmless)`)})}}__name(runThrottledOnce,"runThrottledOnce");async function markerFreshForMs(markerPath,minIntervalMs,name){try{const s=await stat2(markerPath);const age=Date.now()-s.mtimeMs;if(age<minIntervalMs){debugLogger2.debug(`${name}: skipping, ran ${age}ms ago`);return minIntervalMs-age}}catch{}return void 0}__name(markerFreshForMs,"markerFreshForMs");async function tryAcquire(lockPath){try{const fh=await open(lockPath,"wx");await fh.close();return true}catch(e){if(e?.code==="EEXIST"){return false}throw e}}__name(tryAcquire,"tryAcquire");var debugLogger3=createDebugLogger("HOUSEKEEPING");var STARTUP_DELAY_MS=10*60*1e3;var RECURRING_INTERVAL_MS=24*60*60*1e3;var RECENT_INTERACTION_MS=60*1e3;var CATCHUP_THRESHOLD_MS=7*24*60*60*1e3;var STARTUP_DELAY_CATCHUP_MS=60*1e3;var NON_INTERACTIVE_LOCK_RETRY_MS=60*1e3;var NON_INTERACTIVE_FAILURE_RETRY_MS=10*60*1e3;var NON_INTERACTIVE_STOP_GRACE_MS=250;var FILE_HISTORY_MARKER=".file-history-cleanup";var SUBAGENT_MARKER=".subagent-cleanup";var OPENAI_LOGS_MARKER=".openai-logs-cleanup";var DEBUG_LOGS_MARKER=".debug-logs-cleanup";var PSEUDO_DEBUG_SESSION_STEMS=new Set(["transcript-replay","workspace-mcp-discovery"]);var started=false;var nonInteractiveJobs=new Map;var nonInteractiveQueue=[];var activeNonInteractiveJob;var activeNonInteractiveAbortController;var nonInteractiveWorker;var nonInteractiveStopping=false;var nonInteractiveStopPromise;function startBackgroundHousekeeping(config,settings){if(started)return;started=true;void scheduleFirstPass(config,settings).catch(err=>{started=false;debugLogger3.error("scheduleFirstPass failed; chain will retry on next start",err)})}__name(startBackgroundHousekeeping,"startBackgroundHousekeeping");async function scheduleFirstPass(config,settings){const delay=await getFirstPassDelay(config,settings);debugLogger3.debug(`first pass in ${delay/1e3}s`);setTimeout(()=>scheduleNextPass(config,settings),delay).unref()}__name(scheduleFirstPass,"scheduleFirstPass");async function getFirstPassDelay(config,settings){const qwenDir=Storage.getGlobalQwenDir();const markerPaths=[join2(qwenDir,FILE_HISTORY_MARKER),getDebugLogsMarkerPath(qwenDir,Storage.getGlobalDebugDir())];const openaiTarget=getOpenAILogCleanupTarget(config,settings);if(openaiTarget){markerPaths.push(getOpenAILogsMarkerPath(qwenDir,openaiTarget.logDir))}const catchUpStates=await Promise.all(markerPaths.map(needsCatchUp));return catchUpStates.some(Boolean)?STARTUP_DELAY_CATCHUP_MS:STARTUP_DELAY_MS}__name(getFirstPassDelay,"getFirstPassDelay");async function needsCatchUp(markerPath){try{const s=await stat3(markerPath);return Date.now()-s.mtimeMs>CATCHUP_THRESHOLD_MS}catch{return true}}__name(needsCatchUp,"needsCatchUp");function getSubagentMarkerPath(qwenDir,projectDir){const projectKey=createHash("sha256").update(projectDir).digest("hex").slice(0,16);return join2(qwenDir,`${SUBAGENT_MARKER}-${projectKey}`)}__name(getSubagentMarkerPath,"getSubagentMarkerPath");function getOpenAILogsMarkerPath(qwenDir,logDir){const logDirKey=createHash("sha256").update(logDir).digest("hex").slice(0,16);return join2(qwenDir,`${OPENAI_LOGS_MARKER}-${logDirKey}`)}__name(getOpenAILogsMarkerPath,"getOpenAILogsMarkerPath");function getDebugLogsMarkerPath(qwenDir,debugDir){const debugDirKey=createHash("sha256").update(debugDir).digest("hex").slice(0,16);return join2(qwenDir,`${DEBUG_LOGS_MARKER}-${debugDirKey}`)}__name(getDebugLogsMarkerPath,"getDebugLogsMarkerPath");function getOpenAILogCleanupTarget(config,settings){try{const customLogDir=config.getContentGeneratorConfig?.()?.openAILoggingDir??config.getModelsConfig?.()?.getGenerationConfig?.().openAILoggingDir??settings.merged.model?.openAILoggingDir;const systemRetention=settings.system?.settings.model?.openAILogRetentionDays;const workspaceRetention=settings.isTrusted?settings.workspace?.settings.model?.openAILogRetentionDays:void 0;if(customLogDir&&workspaceRetention!==void 0&&systemRetention===void 0){debugLogger3.error("workspace-scoped openAILogRetentionDays is unsafe with a custom openAILoggingDir; skipping cleanup");return void 0}const retentionDays=customLogDir?systemRetention??settings.user?.settings.model?.openAILogRetentionDays??settings.systemDefaults?.settings.model?.openAILogRetentionDays??DEFAULT_OPENAI_LOG_RETENTION_DAYS:settings.merged.model?.openAILogRetentionDays??DEFAULT_OPENAI_LOG_RETENTION_DAYS;return{logDir:resolveOpenAILogDir(customLogDir,config.getWorkingDir()),retentionDays}}catch(err){debugLogger3.error("failed to resolve OpenAI log cleanup target; skipping",err);return void 0}}__name(getOpenAILogCleanupTarget,"getOpenAILogCleanupTarget");function startNonInteractiveOpenAILogHousekeeping(config,settings){if(nonInteractiveStopping)return;sessionIdContext.exit(()=>{try{const target=getOpenAILogCleanupTarget(config,settings);if(!target||nonInteractiveJobs.has(target.logDir))return;const markerPath=getOpenAILogsMarkerPath(Storage.getGlobalQwenDir(),target.logDir);const job={target,markerPath,queued:false};nonInteractiveJobs.set(target.logDir,job);enqueueNonInteractiveJob(job)}catch(err){debugLogger3.error("failed to start non-interactive OpenAI log cleanup; skipping",err)}})}__name(startNonInteractiveOpenAILogHousekeeping,"startNonInteractiveOpenAILogHousekeeping");function stopNonInteractiveOpenAILogHousekeeping(){if(nonInteractiveStopPromise)return nonInteractiveStopPromise;nonInteractiveStopping=true;for(const job of nonInteractiveJobs.values()){if(job.timer){clearTimeout(job.timer);job.timer=void 0}job.queued=false}nonInteractiveQueue.length=0;activeNonInteractiveAbortController?.abort();nonInteractiveStopPromise=waitForNonInteractiveWorkerToStop();return nonInteractiveStopPromise}__name(stopNonInteractiveOpenAILogHousekeeping,"stopNonInteractiveOpenAILogHousekeeping");function enqueueNonInteractiveJob(job){if(nonInteractiveStopping||job.queued||activeNonInteractiveJob===job){return}job.queued=true;nonInteractiveQueue.push(job);startNonInteractiveWorker()}__name(enqueueNonInteractiveJob,"enqueueNonInteractiveJob");function startNonInteractiveWorker(){if(nonInteractiveWorker||nonInteractiveStopping)return;nonInteractiveWorker=drainNonInteractiveQueue().catch(err=>{debugLogger3.error("non-interactive OpenAI log worker failed",err)}).finally(()=>{nonInteractiveWorker=void 0;if(nonInteractiveQueue.length>0&&!nonInteractiveStopping){startNonInteractiveWorker()}})}__name(startNonInteractiveWorker,"startNonInteractiveWorker");async function drainNonInteractiveQueue(){while(!nonInteractiveStopping){const job=nonInteractiveQueue.shift();if(!job)return;job.queued=false;activeNonInteractiveJob=job;const abortController=new AbortController;activeNonInteractiveAbortController=abortController;try{const result=await runOpenAILogCleanup(job.target,job.markerPath,abortController.signal);if(nonInteractiveStopping)continue;switch(result.status){case"completed":scheduleNonInteractiveJob(job,RECURRING_INTERVAL_MS);break;case"fresh":scheduleNonInteractiveJob(job,Math.min(RECURRING_INTERVAL_MS,Math.max(NON_INTERACTIVE_LOCK_RETRY_MS,result.retryAfterMs)));break;case"locked":scheduleNonInteractiveJob(job,NON_INTERACTIVE_LOCK_RETRY_MS);break;case"incomplete":break;default:break}}catch(err){debugLogger3.error(`non-interactive OpenAI log cleanup failed for ${job.target.logDir}`,err);if(!nonInteractiveStopping){scheduleNonInteractiveJob(job,NON_INTERACTIVE_FAILURE_RETRY_MS)}}finally{activeNonInteractiveJob=void 0;activeNonInteractiveAbortController=void 0}}}__name(drainNonInteractiveQueue,"drainNonInteractiveQueue");async function runOpenAILogCleanup(target,markerPath,signal){return runThrottledOnce({name:"openai-logs-cleanup",markerPath,lockPath:markerPath+".lock"},async()=>{const r=await cleanupOldOpenAILogs({logDir:target.logDir,cutoffDate:getCutoffDate(target.retentionDays),signal});debugLogger3.debug(`openai-logs: removed=${r.removed} errors=${r.errors} completed=${r.completed}`);return r.completed?void 0:false})}__name(runOpenAILogCleanup,"runOpenAILogCleanup");function scheduleNonInteractiveJob(job,delayMs){if(nonInteractiveStopping)return;job.timer=setTimeout(()=>{job.timer=void 0;enqueueNonInteractiveJob(job)},delayMs);job.timer.unref()}__name(scheduleNonInteractiveJob,"scheduleNonInteractiveJob");async function waitForNonInteractiveWorkerToStop(){const worker=nonInteractiveWorker;if(!worker){nonInteractiveJobs.clear();return}let timeout;try{await Promise.race([worker,new Promise(resolve=>{timeout=setTimeout(resolve,NON_INTERACTIVE_STOP_GRACE_MS)})])}finally{if(timeout)clearTimeout(timeout);nonInteractiveJobs.clear()}}__name(waitForNonInteractiveWorkerToStop,"waitForNonInteractiveWorkerToStop");async function runPass(config,settings){if(msSinceLastInteraction()<RECENT_INTERACTION_MS){debugLogger3.debug("user active, deferring 10 min");setTimeout(()=>scheduleNextPass(config,settings),STARTUP_DELAY_MS).unref();return}try{await runHousekeeping(config,settings)}catch(err){debugLogger3.error("housekeeping pass failed; will retry next cycle",err)}setTimeout(()=>scheduleNextPass(config,settings),RECURRING_INTERVAL_MS).unref()}__name(runPass,"runPass");function scheduleNextPass(config,settings){void runPass(config,settings).catch(err=>{debugLogger3.error("runPass rejected unexpectedly",err)})}__name(scheduleNextPass,"scheduleNextPass");async function runHousekeeping(config,settings){const days=settings.merged.general?.cleanupPeriodDays??30;const cutoff=getCutoffDate(days);const currentSessionId=config.getSessionId();const qwenDir=Storage.getGlobalQwenDir();await runThrottledOnce({name:"file-history-cleanup",markerPath:join2(qwenDir,FILE_HISTORY_MARKER),lockPath:join2(qwenDir,FILE_HISTORY_MARKER+".lock")},async()=>{const r=await cleanupOldFileHistoryBackups({cutoffDate:cutoff,excludeSessionIds:new Set([currentSessionId])});debugLogger3.debug(`file-history: removed=${r.removed} errors=${r.errors}`)});const debugLogsMarkerPath=getDebugLogsMarkerPath(qwenDir,Storage.getGlobalDebugDir());await runThrottledOnce({name:"debug-logs-cleanup",markerPath:debugLogsMarkerPath,lockPath:debugLogsMarkerPath+".lock"},async()=>{const r=await cleanupOldDebugLogs({cutoffDate:cutoff,excludeSessionIds:new Set([currentSessionId]),isValidSessionId:__name(v=>isValidSessionId(v)||PSEUDO_DEBUG_SESSION_STEMS.has(v),"isValidSessionId")});debugLogger3.debug(`debug-logs: removed=${r.removed} errors=${r.errors}`)});const projectDir=config.storage?.getProjectDir?.();if(projectDir){const markerPath=getSubagentMarkerPath(qwenDir,projectDir);await runThrottledOnce({name:"subagent-cleanup",markerPath,lockPath:markerPath+".lock"},async()=>{const r=await cleanupOldSubagentTranscripts({cutoffDate:cutoff,excludeSessionIds:new Set([currentSessionId]),subagentsRoot:getSubagentsRootDir(projectDir)});debugLogger3.debug(`subagents: removed=${r.removed} errors=${r.errors}`)})}const openaiTarget=getOpenAILogCleanupTarget(config,settings);if(openaiTarget){await runOpenAILogCleanup(openaiTarget,getOpenAILogsMarkerPath(qwenDir,openaiTarget.logDir))}}__name(runHousekeeping,"runHousekeeping");function _resetForTesting(){started=false}__name(_resetForTesting,"_resetForTesting");async function _resetNonInteractiveForTesting(){nonInteractiveStopping=true;for(const job of nonInteractiveJobs.values()){if(job.timer)clearTimeout(job.timer)}nonInteractiveQueue.length=0;activeNonInteractiveAbortController?.abort();await nonInteractiveWorker;nonInteractiveJobs.clear();activeNonInteractiveJob=void 0;activeNonInteractiveAbortController=void 0;nonInteractiveWorker=void 0;nonInteractiveStopping=false;nonInteractiveStopPromise=void 0}__name(_resetNonInteractiveForTesting,"_resetNonInteractiveForTesting");var _needsCatchUpForTesting=needsCatchUp;var _getFirstPassDelayForTesting=getFirstPassDelay;var _runHousekeepingForTesting=runHousekeeping;var _runPassForTesting=runPass;var _FILE_HISTORY_MARKER_FOR_TESTING=FILE_HISTORY_MARKER;var _getDebugLogsMarkerPathForTesting=getDebugLogsMarkerPath;var _getSubagentMarkerPathForTesting=getSubagentMarkerPath;var _getOpenAILogsMarkerPathForTesting=getOpenAILogsMarkerPath;export{startBackgroundHousekeeping,startNonInteractiveOpenAILogHousekeeping,stopNonInteractiveOpenAILogHousekeeping,_resetForTesting,_resetNonInteractiveForTesting,_needsCatchUpForTesting,_getFirstPassDelayForTesting,_runHousekeepingForTesting,_runPassForTesting,_FILE_HISTORY_MARKER_FOR_TESTING,_getDebugLogsMarkerPathForTesting,_getSubagentMarkerPathForTesting,_getOpenAILogsMarkerPathForTesting};
|
|
3
|
+
import{msSinceLastInteraction}from"./chunk-UGLQO5K7.js";import{isValidSessionId}from"./chunk-LGFF5PJA.js";import{DEFAULT_OPENAI_LOG_RETENTION_DAYS}from"./chunk-UB37RBSK.js";import{resolveOpenAILogDir}from"./chunk-QX7W2HY7.js";import{FILE_HISTORY_DIR,getSubagentsRootDir}from"./chunk-7XQ5D34E.js";import{createDebugLogger,sessionIdContext}from"./chunk-JAUJI56S.js";import{Storage}from"./chunk-EPODBRBP.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{stat as stat3}from"node:fs/promises";import{createHash}from"node:crypto";import{join as join2}from"node:path";init_esbuild_shims();import{opendir,readdir,stat,rm,rmdir,unlink}from"node:fs/promises";import{join}from"node:path";var DEBUG_LOG_FILE_SUFFIX=".txt";var debugLogger=createDebugLogger("HOUSEKEEPING");var MS_PER_DAY=24*60*60*1e3;var MS_PER_HOUR=60*60*1e3;var MIN_DATE_MS=-864e13;var SWEEP_CONCURRENCY=20;function getCutoffDate(cleanupPeriodDays){const periodMs=cleanupPeriodDays>0?cleanupPeriodDays*MS_PER_DAY:MS_PER_HOUR;return new Date(Math.max(Date.now()-periodMs,MIN_DATE_MS))}__name(getCutoffDate,"getCutoffDate");async function sweepOldSessionDirs(root,opts){const result={removed:0,errors:0};const excludes=opts.excludeSessionIds??new Set;let entries;try{entries=await readdir(root,{withFileTypes:true})}catch(e){if(isENOENT(e))return result;debugLogger.error("readdir failed",e);return result}const sessionDirs=entries.filter(e=>e.isDirectory()&&!excludes.has(e.name)).map(e=>join(root,e.name));for(let i=0;i<sessionDirs.length;i+=SWEEP_CONCURRENCY){const batch=sessionDirs.slice(i,i+SWEEP_CONCURRENCY);await Promise.all(batch.map(async dir=>{try{const s=await stat(dir);if(s.mtime<opts.cutoffDate){await rm(dir,{recursive:true,force:true});result.removed++}}catch(err){result.errors++;debugLogger.error(`failed to sweep ${dir}`,err)}}))}if(opts.removeEmptyRoot!==false){await rmdir(root).catch(()=>{})}return result}__name(sweepOldSessionDirs,"sweepOldSessionDirs");async function cleanupOldFileHistoryBackups(opts){return sweepOldSessionDirs(join(Storage.getGlobalQwenDir(),FILE_HISTORY_DIR),opts)}__name(cleanupOldFileHistoryBackups,"cleanupOldFileHistoryBackups");async function cleanupOldSubagentTranscripts(opts){return sweepOldSessionDirs(opts.subagentsRoot,{...opts,removeEmptyRoot:false})}__name(cleanupOldSubagentTranscripts,"cleanupOldSubagentTranscripts");var OPENAI_LOG_FILE_PATTERN=/^openai-(\d{4}-\d{2}-\d{2})T\d{2}-\d{2}-\d{2}\.\d{3}Z-[a-f0-9]{8}(?:-[a-zA-Z0-9._](?:[a-zA-Z0-9._-]*[a-zA-Z0-9._])?)?\.json$/;async function cleanupOldOpenAILogs(opts){const result={removed:0,errors:0,completed:true};if(opts.signal?.aborted){result.completed=false;return result}let dir;try{dir=await opendir(opts.logDir)}catch(e){if(isENOENT(e))return result;debugLogger.error("opendir failed",e);throw e}const cutoffDay=opts.cutoffDate.toISOString().slice(0,10);let batch=[];for await(const entry of dir){if(opts.signal?.aborted){result.completed=false;break}const filenameDate=entry.isFile()?OPENAI_LOG_FILE_PATTERN.exec(entry.name)?.[1]:void 0;if(!filenameDate)continue;const filePath=join(opts.logDir,entry.name);batch.push((async()=>{try{let shouldRemove;if(filenameDate!==cutoffDay){shouldRemove=filenameDate<cutoffDay}else{const s=await stat(filePath);shouldRemove=s.mtime<opts.cutoffDate}if(shouldRemove){await unlink(filePath);result.removed++}}catch(err){if(isENOENT(err))return;result.errors++;debugLogger.error(`failed to sweep ${filePath}`,err)}})());if(batch.length===SWEEP_CONCURRENCY){await Promise.all(batch);batch=[]}}await Promise.all(batch);return result}__name(cleanupOldOpenAILogs,"cleanupOldOpenAILogs");function isENOENT(e){return e?.code==="ENOENT"}__name(isENOENT,"isENOENT");async function cleanupOldDebugLogs(opts){const result={removed:0,errors:0};const root=Storage.getGlobalDebugDir();const excludes=opts.excludeSessionIds??new Set;let entries;try{entries=await readdir(root,{withFileTypes:true})}catch(e){if(isENOENT(e))return result;debugLogger.error("readdir failed",e);return result}const logFiles=entries.flatMap(entry=>{if(!entry.isFile()||!entry.name.endsWith(DEBUG_LOG_FILE_SUFFIX)){return[]}const sessionId=entry.name.slice(0,-DEBUG_LOG_FILE_SUFFIX.length);if(!opts.isValidSessionId(sessionId)||excludes.has(sessionId)){return[]}return[join(root,entry.name)]});for(let i=0;i<logFiles.length;i+=SWEEP_CONCURRENCY){const batch=logFiles.slice(i,i+SWEEP_CONCURRENCY);await Promise.all(batch.map(async filePath=>{try{const s=await stat(filePath);if(s.mtime<opts.cutoffDate){await unlink(filePath);result.removed++}}catch(err){if(isENOENT(err))return;result.errors++;debugLogger.error(`failed to sweep ${filePath}`,err)}}))}return result}__name(cleanupOldDebugLogs,"cleanupOldDebugLogs");init_esbuild_shims();import{mkdir,open,stat as stat2,unlink as unlink2,writeFile}from"node:fs/promises";import{dirname}from"node:path";var debugLogger2=createDebugLogger("HOUSEKEEPING");var ONE_DAY_MS=24*60*60*1e3;var STALE_LOCK_MS=60*60*1e3;async function runThrottledOnce(opts,task){const minIntervalMs=opts.minIntervalMs??ONE_DAY_MS;const staleLockMs=opts.staleLockMs??STALE_LOCK_MS;await mkdir(dirname(opts.lockPath),{mode:448}).catch(()=>{});const firstFreshForMs=await markerFreshForMs(opts.markerPath,minIntervalMs,opts.name);if(firstFreshForMs!==void 0){return{status:"fresh",retryAfterMs:firstFreshForMs}}let acquired=await tryAcquire(opts.lockPath);if(!acquired){try{const s=await stat2(opts.lockPath);if(Date.now()-s.mtimeMs>staleLockMs){await unlink2(opts.lockPath).catch(()=>{});acquired=await tryAcquire(opts.lockPath)}}catch{acquired=await tryAcquire(opts.lockPath)}if(!acquired){debugLogger2.debug(`${opts.name}: skipping, lock held`);return{status:"locked"}}}try{const secondFreshForMs=await markerFreshForMs(opts.markerPath,minIntervalMs,opts.name);if(secondFreshForMs!==void 0){return{status:"fresh",retryAfterMs:secondFreshForMs}}let taskCompleted=false;try{taskCompleted=await task()!==false}finally{if(taskCompleted){try{await writeFile(opts.markerPath,new Date().toISOString())}catch(err){debugLogger2.debug(`${opts.name}: marker write failed (cleanup succeeded)`,err)}}}return{status:taskCompleted?"completed":"incomplete"}}finally{await unlink2(opts.lockPath).catch(()=>{debugLogger2.debug(`${opts.name}: lock unlink failed (harmless)`)})}}__name(runThrottledOnce,"runThrottledOnce");async function markerFreshForMs(markerPath,minIntervalMs,name){try{const s=await stat2(markerPath);const age=Date.now()-s.mtimeMs;if(age<minIntervalMs){debugLogger2.debug(`${name}: skipping, ran ${age}ms ago`);return minIntervalMs-age}}catch{}return void 0}__name(markerFreshForMs,"markerFreshForMs");async function tryAcquire(lockPath){try{const fh=await open(lockPath,"wx");await fh.close();return true}catch(e){if(e?.code==="EEXIST"){return false}throw e}}__name(tryAcquire,"tryAcquire");var debugLogger3=createDebugLogger("HOUSEKEEPING");var STARTUP_DELAY_MS=10*60*1e3;var RECURRING_INTERVAL_MS=24*60*60*1e3;var RECENT_INTERACTION_MS=60*1e3;var CATCHUP_THRESHOLD_MS=7*24*60*60*1e3;var STARTUP_DELAY_CATCHUP_MS=60*1e3;var NON_INTERACTIVE_LOCK_RETRY_MS=60*1e3;var NON_INTERACTIVE_FAILURE_RETRY_MS=10*60*1e3;var NON_INTERACTIVE_STOP_GRACE_MS=250;var FILE_HISTORY_MARKER=".file-history-cleanup";var SUBAGENT_MARKER=".subagent-cleanup";var OPENAI_LOGS_MARKER=".openai-logs-cleanup";var DEBUG_LOGS_MARKER=".debug-logs-cleanup";var PSEUDO_DEBUG_SESSION_STEMS=new Set(["transcript-replay","workspace-mcp-discovery"]);var started=false;var nonInteractiveJobs=new Map;var nonInteractiveQueue=[];var activeNonInteractiveJob;var activeNonInteractiveAbortController;var nonInteractiveWorker;var nonInteractiveStopping=false;var nonInteractiveStopPromise;function startBackgroundHousekeeping(config,settings){if(started)return;started=true;void scheduleFirstPass(config,settings).catch(err=>{started=false;debugLogger3.error("scheduleFirstPass failed; chain will retry on next start",err)})}__name(startBackgroundHousekeeping,"startBackgroundHousekeeping");async function scheduleFirstPass(config,settings){const delay=await getFirstPassDelay(config,settings);debugLogger3.debug(`first pass in ${delay/1e3}s`);setTimeout(()=>scheduleNextPass(config,settings),delay).unref()}__name(scheduleFirstPass,"scheduleFirstPass");async function getFirstPassDelay(config,settings){const qwenDir=Storage.getGlobalQwenDir();const markerPaths=[join2(qwenDir,FILE_HISTORY_MARKER),getDebugLogsMarkerPath(qwenDir,Storage.getGlobalDebugDir())];const openaiTarget=getOpenAILogCleanupTarget(config,settings);if(openaiTarget){markerPaths.push(getOpenAILogsMarkerPath(qwenDir,openaiTarget.logDir))}const catchUpStates=await Promise.all(markerPaths.map(needsCatchUp));return catchUpStates.some(Boolean)?STARTUP_DELAY_CATCHUP_MS:STARTUP_DELAY_MS}__name(getFirstPassDelay,"getFirstPassDelay");async function needsCatchUp(markerPath){try{const s=await stat3(markerPath);return Date.now()-s.mtimeMs>CATCHUP_THRESHOLD_MS}catch{return true}}__name(needsCatchUp,"needsCatchUp");function getSubagentMarkerPath(qwenDir,projectDir){const projectKey=createHash("sha256").update(projectDir).digest("hex").slice(0,16);return join2(qwenDir,`${SUBAGENT_MARKER}-${projectKey}`)}__name(getSubagentMarkerPath,"getSubagentMarkerPath");function getOpenAILogsMarkerPath(qwenDir,logDir){const logDirKey=createHash("sha256").update(logDir).digest("hex").slice(0,16);return join2(qwenDir,`${OPENAI_LOGS_MARKER}-${logDirKey}`)}__name(getOpenAILogsMarkerPath,"getOpenAILogsMarkerPath");function getDebugLogsMarkerPath(qwenDir,debugDir){const debugDirKey=createHash("sha256").update(debugDir).digest("hex").slice(0,16);return join2(qwenDir,`${DEBUG_LOGS_MARKER}-${debugDirKey}`)}__name(getDebugLogsMarkerPath,"getDebugLogsMarkerPath");function getOpenAILogCleanupTarget(config,settings){try{const customLogDir=config.getContentGeneratorConfig?.()?.openAILoggingDir??config.getModelsConfig?.()?.getGenerationConfig?.().openAILoggingDir??settings.merged.model?.openAILoggingDir;const systemRetention=settings.system?.settings.model?.openAILogRetentionDays;const workspaceRetention=settings.isTrusted?settings.workspace?.settings.model?.openAILogRetentionDays:void 0;if(customLogDir&&workspaceRetention!==void 0&&systemRetention===void 0){debugLogger3.error("workspace-scoped openAILogRetentionDays is unsafe with a custom openAILoggingDir; skipping cleanup");return void 0}const retentionDays=customLogDir?systemRetention??settings.user?.settings.model?.openAILogRetentionDays??settings.systemDefaults?.settings.model?.openAILogRetentionDays??DEFAULT_OPENAI_LOG_RETENTION_DAYS:settings.merged.model?.openAILogRetentionDays??DEFAULT_OPENAI_LOG_RETENTION_DAYS;return{logDir:resolveOpenAILogDir(customLogDir,config.getWorkingDir()),retentionDays}}catch(err){debugLogger3.error("failed to resolve OpenAI log cleanup target; skipping",err);return void 0}}__name(getOpenAILogCleanupTarget,"getOpenAILogCleanupTarget");function startNonInteractiveOpenAILogHousekeeping(config,settings){if(nonInteractiveStopping)return;sessionIdContext.exit(()=>{try{const target=getOpenAILogCleanupTarget(config,settings);if(!target||nonInteractiveJobs.has(target.logDir))return;const markerPath=getOpenAILogsMarkerPath(Storage.getGlobalQwenDir(),target.logDir);const job={target,markerPath,queued:false};nonInteractiveJobs.set(target.logDir,job);enqueueNonInteractiveJob(job)}catch(err){debugLogger3.error("failed to start non-interactive OpenAI log cleanup; skipping",err)}})}__name(startNonInteractiveOpenAILogHousekeeping,"startNonInteractiveOpenAILogHousekeeping");function stopNonInteractiveOpenAILogHousekeeping(){if(nonInteractiveStopPromise)return nonInteractiveStopPromise;nonInteractiveStopping=true;for(const job of nonInteractiveJobs.values()){if(job.timer){clearTimeout(job.timer);job.timer=void 0}job.queued=false}nonInteractiveQueue.length=0;activeNonInteractiveAbortController?.abort();nonInteractiveStopPromise=waitForNonInteractiveWorkerToStop();return nonInteractiveStopPromise}__name(stopNonInteractiveOpenAILogHousekeeping,"stopNonInteractiveOpenAILogHousekeeping");function enqueueNonInteractiveJob(job){if(nonInteractiveStopping||job.queued||activeNonInteractiveJob===job){return}job.queued=true;nonInteractiveQueue.push(job);startNonInteractiveWorker()}__name(enqueueNonInteractiveJob,"enqueueNonInteractiveJob");function startNonInteractiveWorker(){if(nonInteractiveWorker||nonInteractiveStopping)return;nonInteractiveWorker=drainNonInteractiveQueue().catch(err=>{debugLogger3.error("non-interactive OpenAI log worker failed",err)}).finally(()=>{nonInteractiveWorker=void 0;if(nonInteractiveQueue.length>0&&!nonInteractiveStopping){startNonInteractiveWorker()}})}__name(startNonInteractiveWorker,"startNonInteractiveWorker");async function drainNonInteractiveQueue(){while(!nonInteractiveStopping){const job=nonInteractiveQueue.shift();if(!job)return;job.queued=false;activeNonInteractiveJob=job;const abortController=new AbortController;activeNonInteractiveAbortController=abortController;try{const result=await runOpenAILogCleanup(job.target,job.markerPath,abortController.signal);if(nonInteractiveStopping)continue;switch(result.status){case"completed":scheduleNonInteractiveJob(job,RECURRING_INTERVAL_MS);break;case"fresh":scheduleNonInteractiveJob(job,Math.min(RECURRING_INTERVAL_MS,Math.max(NON_INTERACTIVE_LOCK_RETRY_MS,result.retryAfterMs)));break;case"locked":scheduleNonInteractiveJob(job,NON_INTERACTIVE_LOCK_RETRY_MS);break;case"incomplete":break;default:break}}catch(err){debugLogger3.error(`non-interactive OpenAI log cleanup failed for ${job.target.logDir}`,err);if(!nonInteractiveStopping){scheduleNonInteractiveJob(job,NON_INTERACTIVE_FAILURE_RETRY_MS)}}finally{activeNonInteractiveJob=void 0;activeNonInteractiveAbortController=void 0}}}__name(drainNonInteractiveQueue,"drainNonInteractiveQueue");async function runOpenAILogCleanup(target,markerPath,signal){return runThrottledOnce({name:"openai-logs-cleanup",markerPath,lockPath:markerPath+".lock"},async()=>{const r=await cleanupOldOpenAILogs({logDir:target.logDir,cutoffDate:getCutoffDate(target.retentionDays),signal});debugLogger3.debug(`openai-logs: removed=${r.removed} errors=${r.errors} completed=${r.completed}`);return r.completed?void 0:false})}__name(runOpenAILogCleanup,"runOpenAILogCleanup");function scheduleNonInteractiveJob(job,delayMs){if(nonInteractiveStopping)return;job.timer=setTimeout(()=>{job.timer=void 0;enqueueNonInteractiveJob(job)},delayMs);job.timer.unref()}__name(scheduleNonInteractiveJob,"scheduleNonInteractiveJob");async function waitForNonInteractiveWorkerToStop(){const worker=nonInteractiveWorker;if(!worker){nonInteractiveJobs.clear();return}let timeout;try{await Promise.race([worker,new Promise(resolve=>{timeout=setTimeout(resolve,NON_INTERACTIVE_STOP_GRACE_MS)})])}finally{if(timeout)clearTimeout(timeout);nonInteractiveJobs.clear()}}__name(waitForNonInteractiveWorkerToStop,"waitForNonInteractiveWorkerToStop");async function runPass(config,settings){if(msSinceLastInteraction()<RECENT_INTERACTION_MS){debugLogger3.debug("user active, deferring 10 min");setTimeout(()=>scheduleNextPass(config,settings),STARTUP_DELAY_MS).unref();return}try{await runHousekeeping(config,settings)}catch(err){debugLogger3.error("housekeeping pass failed; will retry next cycle",err)}setTimeout(()=>scheduleNextPass(config,settings),RECURRING_INTERVAL_MS).unref()}__name(runPass,"runPass");function scheduleNextPass(config,settings){void runPass(config,settings).catch(err=>{debugLogger3.error("runPass rejected unexpectedly",err)})}__name(scheduleNextPass,"scheduleNextPass");async function runHousekeeping(config,settings){const days=settings.merged.general?.cleanupPeriodDays??30;const cutoff=getCutoffDate(days);const currentSessionId=config.getSessionId();const qwenDir=Storage.getGlobalQwenDir();await runThrottledOnce({name:"file-history-cleanup",markerPath:join2(qwenDir,FILE_HISTORY_MARKER),lockPath:join2(qwenDir,FILE_HISTORY_MARKER+".lock")},async()=>{const r=await cleanupOldFileHistoryBackups({cutoffDate:cutoff,excludeSessionIds:new Set([currentSessionId])});debugLogger3.debug(`file-history: removed=${r.removed} errors=${r.errors}`)});const debugLogsMarkerPath=getDebugLogsMarkerPath(qwenDir,Storage.getGlobalDebugDir());await runThrottledOnce({name:"debug-logs-cleanup",markerPath:debugLogsMarkerPath,lockPath:debugLogsMarkerPath+".lock"},async()=>{const r=await cleanupOldDebugLogs({cutoffDate:cutoff,excludeSessionIds:new Set([currentSessionId]),isValidSessionId:__name(v=>isValidSessionId(v)||PSEUDO_DEBUG_SESSION_STEMS.has(v),"isValidSessionId")});debugLogger3.debug(`debug-logs: removed=${r.removed} errors=${r.errors}`)});const projectDir=config.storage?.getProjectDir?.();if(projectDir){const markerPath=getSubagentMarkerPath(qwenDir,projectDir);await runThrottledOnce({name:"subagent-cleanup",markerPath,lockPath:markerPath+".lock"},async()=>{const r=await cleanupOldSubagentTranscripts({cutoffDate:cutoff,excludeSessionIds:new Set([currentSessionId]),subagentsRoot:getSubagentsRootDir(projectDir)});debugLogger3.debug(`subagents: removed=${r.removed} errors=${r.errors}`)})}const openaiTarget=getOpenAILogCleanupTarget(config,settings);if(openaiTarget){await runOpenAILogCleanup(openaiTarget,getOpenAILogsMarkerPath(qwenDir,openaiTarget.logDir))}}__name(runHousekeeping,"runHousekeeping");function _resetForTesting(){started=false}__name(_resetForTesting,"_resetForTesting");async function _resetNonInteractiveForTesting(){nonInteractiveStopping=true;for(const job of nonInteractiveJobs.values()){if(job.timer)clearTimeout(job.timer)}nonInteractiveQueue.length=0;activeNonInteractiveAbortController?.abort();await nonInteractiveWorker;nonInteractiveJobs.clear();activeNonInteractiveJob=void 0;activeNonInteractiveAbortController=void 0;nonInteractiveWorker=void 0;nonInteractiveStopping=false;nonInteractiveStopPromise=void 0}__name(_resetNonInteractiveForTesting,"_resetNonInteractiveForTesting");var _needsCatchUpForTesting=needsCatchUp;var _getFirstPassDelayForTesting=getFirstPassDelay;var _runHousekeepingForTesting=runHousekeeping;var _runPassForTesting=runPass;var _FILE_HISTORY_MARKER_FOR_TESTING=FILE_HISTORY_MARKER;var _getDebugLogsMarkerPathForTesting=getDebugLogsMarkerPath;var _getSubagentMarkerPathForTesting=getSubagentMarkerPath;var _getOpenAILogsMarkerPathForTesting=getOpenAILogsMarkerPath;export{startBackgroundHousekeeping,startNonInteractiveOpenAILogHousekeeping,stopNonInteractiveOpenAILogHousekeeping,_resetForTesting,_resetNonInteractiveForTesting,_needsCatchUpForTesting,_getFirstPassDelayForTesting,_runHousekeepingForTesting,_runPassForTesting,_FILE_HISTORY_MARKER_FOR_TESTING,_getDebugLogsMarkerPathForTesting,_getSubagentMarkerPathForTesting,_getOpenAILogsMarkerPathForTesting};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2025 Google LLC
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{mapSkillConfigToStatus}from"./chunk-BJ5KZREO.js";import{resolveSkillSettings}from"./chunk-AVCBF5WL.js";import{STATUS_SCHEMA_VERSION}from"./chunk-LUDNUVSA.js";import{loadSettings}from"./chunk-
|
|
3
|
+
import{mapSkillConfigToStatus}from"./chunk-BJ5KZREO.js";import{resolveSkillSettings}from"./chunk-AVCBF5WL.js";import{STATUS_SCHEMA_VERSION}from"./chunk-LUDNUVSA.js";import{loadSettings}from"./chunk-EZPM4DLR.js";import{resolveLanguage,resolveLanguageSetting}from"./chunk-NO7VTKRL.js";import{ExtensionManager,ExtensionStore,SkillManager,getExtensionDisplayName,isSafeModeEnv}from"./chunk-7XQ5D34E.js";import{authoredSkillName,qualifySkillName}from"./chunk-CV2UAEZA.js";import{writeStderrLine}from"./chunk-M4ECEHLX.js";import{Storage}from"./chunk-EPODBRBP.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";var VALID_SKILL_LEVELS=new Set(["project","user","extension","bundled"]);function createWorkspaceSkillsStatusProvider(options={}){const managers=new Map;const epochs=new Map;const inFlight=new Map;const provider=__name((workspaceCwd=>{const pending=inFlight.get(workspaceCwd);if(pending)return pending;const epoch=epochs.get(workspaceCwd)??0;const promise=buildWorkspaceSkillsStatus(workspaceCwd,managers,options.workspaceTrusted??true,options.includeUntrustedSkills??false,()=>(epochs.get(workspaceCwd)??0)===epoch).finally(()=>{if(inFlight.get(workspaceCwd)===promise){inFlight.delete(workspaceCwd)}});inFlight.set(workspaceCwd,promise);return promise}),"provider");provider.invalidate=workspaceCwd=>{epochs.set(workspaceCwd,(epochs.get(workspaceCwd)??0)+1);managers.delete(workspaceCwd);inFlight.delete(workspaceCwd)};provider.snapshot=async workspaceCwd=>{if(options.workspaceTrusted===false)throw new Error("Skills snapshots require a trusted Workspace.");const freshManagers=new Map;const status=await buildWorkspaceSkillsStatus(workspaceCwd,freshManagers,true,false);const manager=freshManagers.get(workspaceCwd)?.skillManager;if(!status.initialized||status.errors?.length||!manager||manager.hasDiscoveryErrors())throw new Error("The enabled Skills could not be completely discovered.");const configured=new Map(manager.getCachedSkills().map(skill=>[skill.name,skill]));const skills=status.skills.filter(skill=>skill.status==="ok").map(entry=>{const skill=configured.get(entry.name);if(!skill)throw new Error("An enabled Skill is missing its instructions.");return{name:entry.name,description:entry.description,body:skill.body,...entry.modelInvocable?{}:{model_invocable:false},...entry.userInvocable===false?{user_invocable:false}:{}}});if(skills.length>256||skills.some(skill=>Buffer.byteLength(skill.body,"utf8")>512*1024)||Buffer.byteLength(JSON.stringify(skills),"utf8")>2*1024*1024)throw new Error("Enabled Skills exceed the 256-item, 512-KiB/body or 2-MiB catalog limit.");return{workspaceCwd,skills}};return provider}__name(createWorkspaceSkillsStatusProvider,"createWorkspaceSkillsStatusProvider");async function buildWorkspaceSkillsStatus(workspaceCwd,managers,workspaceTrusted,includeUntrustedSkills,canInstall){try{const settings=loadSettings(workspaceCwd,{consumeCorruptionEnvVars:false,skipLoadEnvironment:true,skipWorkspaceSettings:!workspaceTrusted,workspaceTrusted});const rawLanguage=settings.merged.general?.language;const locale=resolveLanguage(resolveLanguageSetting(typeof rawLanguage==="string"?rawLanguage:void 0));let cached=managers.get(workspaceCwd);if(!cached){const rawLevels=!workspaceTrusted||isSafeModeEnv()?void 0:settings.merged.skills?.disabledLevels;const disabledLevels=new Set(Array.isArray(rawLevels)?rawLevels.filter(v=>typeof v==="string"&&VALID_SKILL_LEVELS.has(v)):[]);const safeMode=!workspaceTrusted&&!includeUntrustedSkills||isSafeModeEnv();let extensionManager2;const extensionSkillStates2=new Map;if(workspaceTrusted&&!safeMode){const directory=Storage.getUserExtensionsDir();const entry=await fs.lstat(directory).catch(error=>{if(error.code==="ENOENT")return void 0;throw error});if(entry){await fs.readdir(directory);const extensionStore=new ExtensionStore;extensionManager2=new ExtensionManager({extensionStore,workspaceDir:workspaceCwd,isWorkspaceTrusted:workspaceTrusted,locale});const snapshot=await extensionManager2.refreshCacheWithSnapshot();for(const extension of extensionManager2.getLoadedExtensions()){const states=new Map;for(const skill of extension.skills??[]){const name=skill.name.trim().toLowerCase();const defaults=extension.config.skillStates;const defaultEnabled=defaults&&Object.hasOwn(defaults,name)?defaults[name]:true;states.set(name,extensionStore.getSkillWorkspaceOverride(snapshot,extension.id,workspaceCwd,name)??defaultEnabled)}extensionSkillStates2.set(extension,states)}}}const shim={isSafeMode:__name(()=>safeMode,"isSafeMode"),getBareMode:__name(()=>false,"getBareMode"),getProjectRoot:__name(()=>workspaceCwd,"getProjectRoot"),getActiveExtensions:__name(()=>extensionManager2?.getLoadedExtensions().filter(e=>e.isActive)??[],"getActiveExtensions"),getDisabledSkillLevels:__name(()=>disabledLevels,"getDisabledSkillLevels")};const skillManager2=new SkillManager(shim);if(!safeMode){for(const level of["project","user"]){if(disabledLevels.has(level))continue;for(const directory of skillManager2.getSkillsBaseDirs(level)){try{await fs.readdir(directory)}catch(error){if(error.code!=="ENOENT"){throw error}}}}}cached={skillManager:skillManager2,extensionManager:extensionManager2,extensionSkillStates:extensionSkillStates2};if(!canInstall||canInstall())managers.set(workspaceCwd,cached)}const{disablements,enabledNames}=resolveSkillSettings(settings);const{skillManager,extensionManager,extensionSkillStates}=cached;const extensions=extensionManager?.getLoadedExtensions()??[];const skills=await skillManager.listSkills();const statuses=skills.map(skill=>{const extension=skill.level==="extension"?extensions.find(e=>e.name===skill.extensionName):void 0;const enabled=extension?extensionSkillStates.get(extension)?.get(authoredSkillName(skill).trim().toLowerCase()):void 0;const localizedSkill=extension?.displayName!==void 0?{...skill,extensionDisplayName:getExtensionDisplayName(extension,locale)}:skill;return mapSkillConfigToStatus(localizedSkill,disablements,{enabled:enabledNames.has(skill.name.trim().toLowerCase())||enabled!==false})});for(const extension of extensions){if(extension.isActive)continue;const seenNames=new Set;for(const skill of extension.skills??[]){if(seenNames.has(skill.name))continue;seenNames.add(skill.name);statuses.push(mapSkillConfigToStatus({...skill,name:qualifySkillName(extension.name,skill.name),authoredName:skill.name,level:"extension",extensionName:extension.name,extensionDisplayName:extension.displayName===void 0?void 0:getExtensionDisplayName(extension,locale)},disablements,{disabled:true}))}}return{v:STATUS_SCHEMA_VERSION,workspaceCwd,initialized:true,skills:statuses.sort((a,b)=>a.name.localeCompare(b.name))}}catch(error){const message=error instanceof Error?error.message:String(error);writeStderrLine(`qwen serve: daemon-local skills enumeration failed for ${workspaceCwd}: ${message}`);return{v:STATUS_SCHEMA_VERSION,workspaceCwd,initialized:false,skills:[],errors:[{kind:"skills",status:"error",error:message}]}}}__name(buildWorkspaceSkillsStatus,"buildWorkspaceSkillsStatus");export{createWorkspaceSkillsStatusProvider};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2025 Qwen Team
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{projectJsonStringToByteBudget}from"./chunk-WQUA4G2X.js";import{flushOutput}from"./chunk-VURTGFJP.js";import{cpLen,cpSlice,sanitizeTerminalLine,sanitizeTerminalText,stripUnsafeCharacters}from"./chunk-64CA3W6G.js";import{require_semver}from"./chunk-YZUKMJW7.js";import{ENGINE_NODE,MOD_END_TIMEOUT_MS,MOD_MAX_BYTES,ModBudget,adjustRenderTree,assertModDepth,record,validateRenderTree,validateResult}from"./chunk-ZZJXFLVM.js";import{stableJson}from"./chunk-FIXDX63I.js";import{external_exports}from"./chunk-TWP72VRH.js";import{openNoFollow}from"./chunk-QXQGUM3Y.js";import{resolveBundleDir}from"./chunk-4NPYOXJO.js";import{runOutsideAgentContext}from"./chunk-YZFNBUKG.js";import{isInternalPromptId,uiTelemetryService}from"./chunk-ZWPSBU7K.js";import{getGenAiUsageProvenance,outputTokenCount}from"./chunk-4DIWAQ5G.js";import{EVENT_API_RESPONSE}from"./chunk-3XVPZY7X.js";import{registerCleanup}from"./chunk-3ICJI5KW.js";import{stripAnsiAndControl}from"./chunk-DBRQGEEI.js";import{ToolNames}from"./chunk-SBZFGYYS.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();import{randomUUID}from"node:crypto";init_esbuild_shims();import{promises as fs}from"node:fs";import path from"node:path";init_esbuild_shims();var import_semver=__toESM(require_semver(),1);var name=external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/);var dependency=external_exports.union([external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*(?:@[a-zA-Z0-9][a-zA-Z0-9._-]*)?$/),external_exports.object({name,marketplace:name.optional(),version:external_exports.string().optional()}).strict()]);function parseModDependencies(value){const parsed=external_exports.array(dependency).safeParse(value===void 0?[]:value);if(!parsed.success)throw new Error("Invalid Mod dependencies declaration.");return parsed.data.map(item=>{if(typeof item==="string"){const[name2,marketplace]=item.split("@");return{name:name2,marketplace}}if(item.version!==void 0&&!(0,import_semver.validRange)(item.version)){throw new Error(`Invalid Mod dependency version range for ${item.name}.`)}return item})}__name(parseModDependencies,"parseModDependencies");function resolveModDependency(plugins,plugin,dependency2){const marketplace=dependency2.marketplace??plugin.marketplace;const local=plugins.filter(item=>item.name===dependency2.name&&!item.marketplace);const matches=local.length?local:plugins.filter(item=>item.name===dependency2.name&&item.marketplace===marketplace);if(matches.length!==1){throw new Error(`Mod ${plugin.name}: dependency ${dependency2.name} must identify one installed, enabled plugin.`)}const target=matches[0];if(target.marketplace&&dependency2.version&&!(0,import_semver.satisfies)(target.version,dependency2.version)){throw new Error(`Mod ${plugin.name}: dependency ${dependency2.name} has an incompatible installed version.`)}return target}__name(resolveModDependency,"resolveModDependency");function orderModPlugins(plugins){const edges=plugins.map(()=>new Set);const incoming=plugins.map(()=>0);for(const[index,plugin]of plugins.entries()){for(const dependency2 of plugin.dependencies){const targetIndex=plugins.indexOf(resolveModDependency(plugins,plugin,dependency2));if(!edges[index].has(targetIndex)){edges[index].add(targetIndex);incoming[targetIndex]++}}}const ordered=[];const remaining=new Set(plugins.map((_,index)=>index));while(remaining.size){const next=[...remaining].find(index=>incoming[index]===0);if(next===void 0)throw new Error("Mod dependency cycle: activation refused.");remaining.delete(next);ordered.push(plugins[next]);for(const target of edges[next])incoming[target]--}return ordered}__name(orderModPlugins,"orderModPlugins");function isContainedFile(root,file){const relative=path.relative(root,file);return Boolean(relative)&&!path.isAbsolute(relative)&&relative!==".."&&!relative.startsWith(`..${path.sep}`)}__name(isContainedFile,"isContainedFile");async function readModFile(root,file){if(!isContainedFile(root,file)){throw new Error("Mod file must stay inside the installed extension.")}let current=root;for(const part of path.relative(root,file).split(path.sep)){current=path.join(current,part);const stat=await fs.lstat(current);if(stat.isSymbolicLink()){throw new Error("Mod files cannot be symbolic links.")}if(current===file&&!stat.isFile()){throw Object.assign(new Error("Mod input must be a regular file."),{code:stat.isDirectory()?"EISDIR":void 0})}}const entry=await fs.realpath(file);if(!isContainedFile(root,entry)){throw new Error("Mod file must stay inside the installed extension.")}const handle=await openNoFollow(entry);try{const stat=await handle.stat();if(!stat.isFile()||stat.size>MOD_MAX_BYTES){throw new Error("Mod file exceeds the 256 KiB regular-file limit.")}const buffer=Buffer.alloc(MOD_MAX_BYTES+1);const{bytesRead}=await handle.read(buffer,0,buffer.length,0);if(bytesRead>MOD_MAX_BYTES)throw new Error("Mod file is too large.");return{entry,source:buffer.subarray(0,bytesRead).toString("utf8")}}finally{await handle.close()}}__name(readModFile,"readModFile");async function readManifest(root,relative){try{if(path.isAbsolute(relative)){throw new Error("Mod manifest path must be relative to the extension.")}const value=JSON.parse((await readModFile(root,path.resolve(root,relative))).source);if(!value||typeof value!=="object"||Array.isArray(value)){throw new Error("Mod manifest must be a JSON object.")}return value}catch(error){if(error.code==="ENOENT")return void 0;throw error}}__name(readManifest,"readManifest");async function loadModSource(extensionPath){const root=await fs.realpath(extensionPath);const qwen=await readManifest(root,"qwen-extension.json");if(typeof qwen?.["hooks"]==="string"&&(path.isAbsolute(qwen["hooks"])||!isContainedFile(root,path.resolve(root,qwen["hooks"])))){return void 0}const claude=await readManifest(root,".claude-plugin/plugin.json");const hooksPath=typeof qwen?.["hooks"]==="string"?qwen["hooks"]:typeof claude?.["hooks"]==="string"?claude["hooks"]:"hooks/hooks.json";if(path.isAbsolute(hooksPath)||!isContainedFile(root,path.resolve(root,hooksPath))){return void 0}const hooks=await readManifest(root,hooksPath);if(!hooks||!Object.hasOwn(hooks,"modules"))return void 0;const modules=hooks["modules"];if(!Array.isArray(modules)||modules.length!==1||typeof modules[0]!=="string"||path.isAbsolute(modules[0])||!/\.(?:[cm]?js|[cm]?ts|[jt]sx)$/.test(modules[0])){throw new Error("Mods require one relative JavaScript, TypeScript or JSX module.")}const manifest={...claude,...qwen};const entry=path.resolve(root,path.dirname(hooksPath),modules[0]);return{root,...await readModFile(root,entry),userConfig:manifest["userConfig"],dependencies:parseModDependencies(manifest["dependencies"])}}__name(loadModSource,"loadModSource");async function loadModDependencies(extensionPath){const root=await fs.realpath(extensionPath);const qwen=await readManifest(root,"qwen-extension.json");const claude=await readManifest(root,".claude-plugin/plugin.json");return parseModDependencies({...claude,...qwen}["dependencies"])}__name(loadModDependencies,"loadModDependencies");init_esbuild_shims();var option=external_exports.union([external_exports.string(),external_exports.number().finite(),external_exports.boolean(),external_exports.array(external_exports.string())]);var field=external_exports.object({type:external_exports.enum(["string","number","boolean","directory","file"]),title:external_exports.string(),description:external_exports.string(),required:external_exports.boolean().optional(),default:option.optional(),multiple:external_exports.boolean().optional(),sensitive:external_exports.boolean().optional(),min:external_exports.number().finite().optional(),max:external_exports.number().finite().optional(),options:external_exports.array(external_exports.string().min(1).max(64)).nonempty().optional()}).strict().refine(value=>{if(!value.options)return true;return value.type==="string"&&!value.multiple&&!value.sensitive&&value.options.every(item=>item.trim()===item&&!/[\p{Cc}\p{Cf}]/u.test(item))&&new Set(value.options.map(item=>item.toLowerCase())).size===value.options.length&&(value.default===void 0?value.required===true:value.options.includes(value.default))});var schema=external_exports.record(external_exports.string().regex(/^[A-Za-z_]\w*$/),field);var storedOptions=external_exports.record(option);function*pluginConfigurations(scopes,name2,marketplace){const keys=marketplace?[`${name2}@${marketplace}`]:[name2,`${name2}@inline`];for(const scope of scopes){if(scope===void 0)continue;if(!scope||typeof scope!=="object"||Array.isArray(scope)){throw new Error("Invalid Mod pluginConfigs settings.")}for(const key of keys){if(!Object.hasOwn(scope,key))continue;const config=scope[key];if(!config||typeof config!=="object"||Array.isArray(config)){throw new Error("Invalid Mod pluginConfigs entry.")}yield config}}}__name(pluginConfigurations,"pluginConfigurations");function resolveModChoice(scopes,name2,marketplace,key,choices){let choice=choices[0];for(const config of pluginConfigurations(scopes,name2,marketplace)){const value=config[key];if(value===void 0)continue;if(!choices.includes(value))throw new Error(`Invalid Mod ${key}: expected ${choices.join(" or ")}.`);choice=value}return choice}__name(resolveModChoice,"resolveModChoice");function resolveModToolDialect(scopes,name2,marketplace){return resolveModChoice(scopes,name2,marketplace,"toolDialect",["native","claude"])}__name(resolveModToolDialect,"resolveModToolDialect");function resolveModUnsupportedEvents(scopes,name2,marketplace){return resolveModChoice(scopes,name2,marketplace,"unsupportedEvents",["skip","reject"])}__name(resolveModUnsupportedEvents,"resolveModUnsupportedEvents");function resolveModOptions(declaration,scopes,name2,marketplace){const parsed=schema.safeParse(declaration===void 0?{}:declaration);if(!parsed.success)throw new Error("Invalid Mod userConfig declaration.");const fields=Object.entries(parsed.data);if(!fields.length)return{};if(fields.some(([,value])=>value.sensitive)){throw new Error("Sensitive Mod userConfig is not supported yet.")}let stored={};for(const config of pluginConfigurations(scopes,name2,marketplace)){const options=config["options"];if(options===void 0)continue;const values=storedOptions.safeParse(options);if(!values.success)throw new Error(`Invalid Mod configured option: ${String(values.error.issues[0]?.path[0]??"").slice(0,64)}.`);stored={...stored,...values.data}}const result=Object.fromEntries(fields.filter(([,config])=>config.default!==void 0||!config.required).map(([key,config])=>[key,config.default??""]));for(const[key,value]of Object.entries(stored)){const choices=Object.hasOwn(parsed.data,key)?parsed.data[key].options:void 0;if(!choices||choices.includes(value))Object.defineProperty(result,key,{value,enumerable:true,writable:true,configurable:true})}for(const[key,config]of fields){const value=Object.hasOwn(result,key)?result[key]:void 0;if(value===void 0||value===""){if(config.required)throw new Error(`Missing required Mod option: ${key}.`)}else{const valid=config.type==="number"?typeof value==="number"&&(config.min===void 0||value>=config.min)&&(config.max===void 0||value<=config.max):config.type==="boolean"?typeof value==="boolean":typeof value==="string"||config.type==="string"&&config.multiple&&Array.isArray(value);if(!valid)throw new Error(`Invalid Mod option: ${key}.`)}}if(Buffer.byteLength(JSON.stringify(result))>MOD_MAX_BYTES){throw new Error("Mod options exceed the 256 KiB limit.")}return result}__name(resolveModOptions,"resolveModOptions");init_esbuild_shims();import{Worker}from"node:worker_threads";import{existsSync}from"node:fs";import path2 from"node:path";import{createRequire}from"node:module";import{pathToFileURL}from"node:url";function workerEntry(){if(import.meta.url.endsWith(".ts")){return new URL(`data:text/javascript,${encodeURIComponent(`import { register } from ${JSON.stringify(pathToFileURL(createRequire(import.meta.url).resolve("tsx/esm/api")).href)}; register(); await import(${JSON.stringify(new URL("./mod-worker.ts",import.meta.url).href)});`)}`)}const sibling=new URL("./mod-worker.js",import.meta.url);return existsSync(sibling)?sibling:path2.join(resolveBundleDir(import.meta.url),"mod-worker.js")}__name(workerEntry,"workerEntry");var ModRuntime=class _ModRuntime{constructor(log,facts,resolveTool,surface=null,abortTurn,renderHost){this.log=log;this.facts=facts;this.resolveTool=resolveTool;this.surface=surface;this.abortTurn=abortTurn;this.renderHost=renderHost;this.worker=new Worker(workerEntry(),{stdout:true,stderr:true,workerData:this.cancelled.buffer});this.worker.stdout?.resume();this.worker.stderr?.resume();this.worker.on("message",reply=>{const root=this.root;if(!root||reply.root!==root.id)return;if(reply.type==="host-call")this.executeHost(reply);else if(reply.type==="host-cancel"){for(const id of reply.ids)this.tool?.operations.get(id)?.controller.abort()}else if(reply.type==="check-result")this.tool?.checks.get(reply.id)?.(reply);else if(reply.type==="turn-abort")this.answerTurnAbort(reply,root.id);else if(reply.type==="invalidate"){if(reply.event!=="ui.render"||this.failure)return;if(this.early)this.early.add(reply.plugin);else if(this.renders.includes(reply.plugin))this.renderHost?.invalidate(reply.plugin)}else if(reply.type==="activity"){if(reply.phase!==root.phase||reply.revision<=root.revision||reply.operation!==void 0&&reply.operation!==root.native)return;root.revision=reply.revision;root.idle=this.tool?.checks.size?void 0:reply.operation;root.refresh()}else if(reply.type==="log"){if(this.failure)return;try{this.log({text:reply.text,to:reply.to},reply.plugin)}catch(error){this.fail(error instanceof Error?error:new Error(String(error)));void this.worker.terminate()}}else this.pending?.(reply)});this.worker.on("error",error=>this.fail(error));this.worker.on("exit",code=>this.fail(new Error(`Mod worker exited (${code}).`)))}static{__name(this,"ModRuntime")}worker;failure;pending;commands=[];tools=false;turns={start:false,complete:[]};renders=[];early=new Set;noted=new Set;sequence=0;root;tool;cancelled=new Int32Array(new SharedArrayBuffer(4));static async create(source,cwd,log,signal,options={}){return _ModRuntime.createGroup([{id:"mod",name:"mod",source,options}],cwd,log,signal)}static async createGroup(plugins,cwd,log,signal,resolveTool,surface=null,version="unknown",facts,abortTurn,render){if(plugins.length>32||new Set(plugins.map(p=>p.id)).size!==plugins.length)throw new Error("Invalid Mod plugin group.");const startedAt=Date.now();const runtime=new _ModRuntime(log,facts??(()=>({id:"",cwd,root:cwd,model:"",turns:0,usage:{startedAt,context:{tokens:0,window:0},rateLimits:[]}})),plugins.some(plugin=>plugin.toolDialect==="claude")?resolveTool:void 0,surface,abortTurn,render);try{const result=await runtime.request({type:"load",plugins,cwd,surface,version,sites:render?.sites??[]},signal,6e4);const names=__name(value=>Array.isArray(value)&&value.every(name2=>plugins.some(plugin=>plugin.name===name2)),"names");const turnComplete=record(result)?result["turnComplete"]:void 0;const renders=record(result)?result["render"]:void 0;if(!record(result)||typeof result["tools"]!=="boolean"||typeof result["turnStart"]!=="boolean"||!names(turnComplete)||!names(renders))throw new Error("Invalid Mod declarations.");const commands=result["commands"];if(!Array.isArray(commands)||commands.length>64||commands.some(command=>!command||!plugins.some(plugin=>plugin.id===command.plugin)||typeof command.name!=="string"||!/^[a-zA-Z0-9_-]{1,64}$/.test(command.name)||typeof command.description!=="string"||command.argumentHint!==void 0&&typeof command.argumentHint!=="string"))throw new Error("Invalid Mod command declarations.");runtime.commands=commands;runtime.tools=result["tools"];runtime.turns={start:result["turnStart"],complete:turnComplete};runtime.renders=renders;const early=runtime.early;runtime.early=void 0;for(const plugin of early)if(renders.includes(plugin))render?.invalidate(plugin);return runtime}catch(error){await runtime.dispose();throw error}}getCommands(plugin="mod"){return this.commands.filter(command=>command.plugin===plugin).map(({plugin:_plugin,...command})=>command)}get hasToolHooks(){return this.tools}get turnHooks(){return this.turns}get renderHooks(){return this.renders}async render(input,signal){const settled=await this.request({type:"render",input},signal);const owner=this.renders.length===1?this.renders[0]:"hooks";const notes=[];const note=__name((line,key=line)=>{if(this.noted.has(key))return;this.noted.add(key);notes.push(`${owner}: ${line}`)},"note");try{validateRenderTree(settled)}catch(error){note(`ui.render (${input.component}) refused: ${error instanceof Error?error.message:String(error)}; nothing was drawn`);return{tree:ENGINE_NODE,notes}}const adjusted=adjustRenderTree(settled,input.component);for(const{key,text}of adjusted.notes)note(text,`${input.component}\0${key}`);return{tree:adjusted.tree,notes}}async builtinTool(name2){if(!this.resolveTool)return void 0;let builtin=false;switch(name2){case ToolNames.SHELL:builtin=await this.resolveTool(name2)instanceof(await import("./shell-WYQDZWL7.js")).ShellTool;break;case ToolNames.EDIT:builtin=await this.resolveTool(name2)instanceof(await import("./edit-XCECLEH3.js")).EditTool;break;case ToolNames.WRITE_FILE:builtin=await this.resolveTool(name2)instanceof(await import("./write-file-UMJVKE4S.js")).WriteFileTool;break;default:return void 0}return builtin?name2:void 0}async runTool(input,next,signal){if(this.tool||this.pending)throw new Error("A Mod dispatch is already running.");const owner={next,controller:new AbortController,operations:new Map,checks:new Map,tail:Promise.resolve()};this.tool=owner;try{const builtinTool=await this.builtinTool(input.tool);const result=await this.request({type:"tool",input,builtinTool},AbortSignal.any([signal,owner.controller.signal]));validateResult("tool.call",result);return result}finally{owner.controller.abort();await Promise.allSettled([...owner.operations.values()].map(operation=>operation.task));this.tool=void 0}}executeHost(reply){const owner=this.tool;const root=this.root;if(!owner||!root||owner.operations.size>=32||owner.operations.has(reply.id)){this.fail(new Error("Invalid Mod host operation."));return}const controller=new AbortController;const signal=AbortSignal.any([owner.controller.signal,controller.signal]);const task=owner.tail.then(async()=>{signal.throwIfAborted();root.native=reply.id;root.phase++;root.idle=void 0;root.refresh();this.post({type:"native",id:reply.id},root.id);const result=await owner.next(reply.input,signal,async(input,verdict,checkSignal)=>{const active=AbortSignal.any([signal,checkSignal]);active.throwIfAborted();const id=++this.sequence;let abort=__name(()=>{},"abort");try{return await new Promise((resolve,reject)=>{abort=__name(()=>reject(new Error("Mod permission check cancelled.")),"abort");owner.checks.set(id,response=>{if(response.error!==void 0)reject(new Error(response.error));else{try{validateResult("tool.check",response.result);resolve({...response.result,ceiling:input.ceiling})}catch(error){reject(error)}}});root.idle=void 0;root.phase++;root.refresh();active.addEventListener("abort",abort,{once:true});this.post({type:"tool-check",id,operation:reply.id,input,verdict},root.id)})}finally{active.removeEventListener("abort",abort);owner.checks.delete(id);root.refresh()}});root.native=void 0;root.phase++;root.idle=void 0;root.refresh();signal.throwIfAborted();this.post({type:"host-result",id:reply.id,result},root.id)}).catch(error=>{root.native=void 0;root.phase++;root.idle=void 0;root.refresh();if(!this.failure)this.post({type:"host-result",id:reply.id,error:String(error).slice(0,4e3)},root.id)}).finally(()=>{owner.operations.delete(reply.id)});owner.operations.set(reply.id,{controller,task});owner.tail=task}post(request,root){if(this.root?.id!==root)return;const json=JSON.stringify(request);if(Buffer.byteLength(json)>MOD_MAX_BYTES+8192)throw new Error("Mod host message is too large.");assertModDepth(json,"Mod host message");this.worker.postMessage({...request,root,phase:this.root.phase})}async runCommand(command,args,signal,presentation){if(!this.commands.some(item=>item.name===command))throw new Error("Unknown Mod command.");const result=await this.request({type:"command",command,args,...this.surface==="terminal"&&presentation?{presentation}:{}},signal);if(!result||typeof result!=="object"||Array.isArray(result)||Object.keys(result).some(key=>key!=="text")||"text"in result&&typeof result.text!=="string"){throw new Error("Invalid Mod command result.")}return"text"in result?result.text:""}async startTurn(input,signal){validateResult("turn.start",await this.request({type:"turn-start",input},signal))}async completeTurn(input,signal){const result=await this.request({type:"turn-complete",input},signal);validateResult("turn.complete",result);return result.text}answerTurnAbort(reply,root){let error;try{if(!this.abortTurn)throw new Error(`$.turn.abort: no turn is running (asked for ${reply.turnId})`);this.abortTurn(reply.turnId)}catch(caught){error=(caught instanceof Error?caught.message:String(caught)).slice(0,4e3)}this.post({type:"turn-abort-result",id:reply.id,error},root)}async end(sessionId,reason,signal){await this.request({type:"end",sessionId,reason},signal,MOD_END_TIMEOUT_MS)}async dispose(){this.fail(new Error("Mod runtime is closed."));await this.worker.terminate();await Promise.allSettled([...this.tool?.operations.values()??[]].map(operation=>operation.task))}fail(error){this.failure??=error;this.tool?.controller.abort();this.pending?.({type:"error",message:this.failure.message})}async request(request,signal,timeoutMs=6e4){signal.throwIfAborted();if(this.failure)throw this.failure;if(this.pending)throw new Error("A Mod dispatch is already running.");const message={...request,facts:this.facts()};const json=JSON.stringify(message);if(Buffer.byteLength(json)>(request.type==="load"?32:1)*MOD_MAX_BYTES+8192)throw new Error("Mod request is too large.");assertModDepth(json,"Mod request");let timer;let cancelTimer;let aborted=false;const budget=new ModBudget(timeoutMs+250);const stop=__name(()=>{this.fail(new Error(aborted?"Mod dispatch cancelled.":"Mod dispatch timed out."));void this.worker.terminate()},"stop");const root={id:++this.sequence,revision:0,phase:0,refresh:__name(()=>{if(aborted||this.root!==root)return;const lending=request.type==="tool"&&root.native!==void 0&&root.idle===root.native&&!this.tool?.checks.size&&!budget.expired;if(lending!==budget.lending){if(lending)budget.pause();else budget.resume()}if(timer)clearTimeout(timer);if(!budget.lending)timer=setTimeout(stop,budget.remainingMs)},"refresh")};this.root=root;const onAbort=__name(()=>{aborted=true;Atomics.store(this.cancelled,0,1);this.tool?.controller.abort();if(timer)clearTimeout(timer);cancelTimer=setTimeout(stop,250)},"onAbort");Atomics.store(this.cancelled,0,0);try{return await new Promise((resolve,reject)=>{this.pending=reply=>{if(this.failure)reject(this.failure);else if(aborted)reject(new Error("Mod dispatch cancelled."));else if(reply.type==="error")reject(new Error(reply.message));else if(reply.type==="result"){try{if(Buffer.byteLength(reply.json)>MOD_MAX_BYTES)throw new Error("Mod reply is too large.");resolve(JSON.parse(reply.json))}catch(error){reject(error)}}};signal.addEventListener("abort",onAbort,{once:true});root.refresh();this.worker.postMessage({...message,root:root.id,phase:root.phase})})}finally{this.root=void 0;if(timer)clearTimeout(timer);if(cancelTimer)clearTimeout(cancelTimer);signal.removeEventListener("abort",onAbort);this.pending=void 0}}};var logger=createDebugLogger("MODS");var RENDER_SETTLE_MS=150;var RENDER_LIVE_MS=34;var RENDER_STEADY_MS=100;var RENDER_SLOW_MS=1e3;var ModSession=class _ModSession{constructor(config,output,optionScopes=[]){this.config=config;this.output=output;this.optionScopes=optionScopes;this.sessionId=config.getSessionId();uiTelemetryService.on("update",this.observe);this.unregisterCleanup=registerCleanup(()=>{this.unregisterCleanup=()=>{};return this.close().then(()=>this.flushOutput())},{first:Boolean(this.terminal)})}static{__name(this,"ModSession")}mods=[];runtime;toolQueue=Promise.resolve();lifetime=new AbortController;endLifetime=new AbortController;initialization;closing;logsReady=false;pendingLogs=[];notes=[];activeCommand;commandSignal;toolSignal;sessionId;adoptedAt=Date.now();startedAt;recorder;context={tokens:0,window:0};turn;observe=__name(update=>runOutsideAgentContext(()=>{if(this.config.getSessionId()!==this.sessionId)return;this.recorder=this.config.getChatRecordingService();this.context={tokens:uiTelemetryService.getLastPromptTokenCount(),window:this.config.getContentGeneratorConfig()?.contextWindowSize||0};const event=update?.event;if(!this.turn||event?.["event.name"]!==EVENT_API_RESPONSE)return;const response=event;if(response.subagent_name===void 0&&!isInternalPromptId(response.prompt_id)&&(this.turn.promptId===void 0||response.prompt_id===this.turn.promptId))this.turn.model=response.model}),"observe");toolGeneration=new AbortController;sites=[];band={state:"idle",again:false,startedAt:-Infinity,steadyUntil:0};unregisterCleanup;static create(config,settings,output){return settings.merged.experimental?.mods?new _ModSession(config,output,[settings.systemDefaults.settings.pluginConfigs,settings.user.settings.pluginConfigs,settings.system.settings.pluginConfigs]):void 0}get terminal(){return"surface"in this.output?this.output:void 0}allowed(){return this.config.isInteractive()===Boolean(this.terminal)&&!this.config.getExperimentalZedIntegration()&&this.config.isTrustedFolder()&&!this.config.getDisableAllHooks()&&!this.config.getBareMode()&&!this.config.isSafeMode()&&!this.config.getExecutionEnvironment()&&!this.config.getExecutionEnvironmentFactory()&&!this.config.getHookSystem()?.isManaged()&&!this.config.getSandbox()&&!this.config.isSessionAgentSession()}async initialize(signal){if(this.closing)throw new Error("Mod session is closed.");if(!this.allowed()){if(this.mods.length){await this.close();throw new Error("Mods are no longer permitted in this session.")}return}this.initialization??=this.load(AbortSignal.any([signal,this.lifetime.signal]));await this.initialization}async load(signal){const sites=this.sites=this.terminal?.sites?.()??[];try{const candidates=[];for(const extension of this.config.getExtensions().filter(item=>item.isActive&&item.format!=="agent-plugins-v1")){signal.throwIfAborted();try{const source=await loadModSource(extension.path);const marketplace=extension.installMetadata?.marketplaceConfig?.name;candidates.push({extension,name:extension.name,version:extension.version,marketplace,source,dependencies:source?.dependencies??[],toolDialect:source?resolveModToolDialect(this.optionScopes,extension.name,marketplace):void 0,unsupportedEvents:source?resolveModUnsupportedEvents(this.optionScopes,extension.name,marketplace):void 0,options:source?resolveModOptions(source.userConfig,this.optionScopes,extension.name,marketplace):{}})}catch(error){throw new Error(`Mod ${extension.name}: ${error instanceof Error?error.message:String(error)}`)}}const pending=candidates.filter(item=>item.source);const reachable=new Set;while(pending.length){signal.throwIfAborted();const plugin=pending.shift();if(reachable.has(plugin))continue;reachable.add(plugin);if(!plugin.source){try{plugin.dependencies=await loadModDependencies(plugin.extension.path)}catch(error){throw new Error(`Mod dependency ${plugin.name}: ${error instanceof Error?error.message:String(error)}`)}}for(const dependency2 of plugin.dependencies){pending.push(resolveModDependency(candidates,plugin,dependency2))}}const selected=candidates.filter(item=>reachable.has(item));orderModPlugins(selected);const mods=selected.filter(item=>item.source).map(plugin=>({...plugin,dependencies:plugin.dependencies.filter(dependency2=>resolveModDependency(selected,plugin,dependency2).source)}));const ordered=orderModPlugins(mods);if(ordered.length){this.runtime=await ModRuntime.createGroup(ordered.map(({extension,source,options,toolDialect,unsupportedEvents})=>({id:extension.id,name:extension.name,source:{root:source.root,entry:source.entry,source:source.source},options,toolDialect,unsupportedEvents})),this.config.getTargetDir(),(entry,plugin)=>{if(this.commandSignal?.aborted||this.toolSignal?.aborted)return;this.pendingLogs.push({...entry,plugin,sessionId:this.sessionId});if(this.logsReady)this.flushLogs()},signal,name2=>this.config.getToolRegistry().ensureTool(name2),this.terminal?.surface??null,this.config.getCliVersion()||"unknown",()=>this.facts(),turnId=>this.abortTurn(turnId),sites.length?{sites,invalidate:__name(()=>this.requestRender(),"invalidate")}:void 0);this.mods.push(...ordered.map(({extension})=>({id:extension.id,name:extension.name})));this.requestRender()}}catch(error){await this.runtime?.dispose();this.mods.length=0;throw error}}async loadCommands(signal){await this.initialize(signal);return this.mods.flatMap(mod=>this.runtime.getCommands(mod.id).map(command=>({name:command.name,description:this.terminal?sanitizeTerminalLine(command.description):command.description,kind:"file",source:"plugin-command",extensionName:this.terminal?sanitizeTerminalLine(mod.name):mod.name,supportedModes:[this.terminal?"interactive":"non_interactive"],argumentHint:this.terminal&&command.argumentHint!==void 0?sanitizeTerminalLine(command.argumentHint):command.argumentHint,modelInvocable:false,action:__name(async(context,args)=>{const active=AbortSignal.any([context.abortSignal??(this.terminal?this.lifetime.signal:signal),this.lifetime.signal]);const task=this.toolQueue.then(async()=>{active.throwIfAborted();if(!this.allowed()||!this.active()||this.closing){await this.runtime.dispose();throw new Error(`Mod ${mod.name} is disabled or its middleware chain changed.`)}if(this.sessionId!==this.config.getSessionId())throw new Error("The Mod command belongs to a previous session.");const controller=new AbortController;this.activeCommand=controller;const commandSignal=AbortSignal.any([active,controller.signal]);this.commandSignal=commandSignal;try{const content=await this.runtime.runCommand(command.name,args,commandSignal,this.terminal?.presentation());commandSignal.throwIfAborted();return{type:"message",messageType:"info",content:this.terminal?sanitizeTerminalText(stripUnsafeCharacters(content)):content}}finally{this.flushLogs();this.activeCommand=void 0;this.commandSignal=void 0}});this.toolQueue=task.catch(()=>{});return task},"action")})))}invalidateTools(){this.toolGeneration.abort();this.pendingLogs.length=0;this.activeCommand?.abort()}async restoreTools(){await this.toolQueue;if(!this.closing&&this.sessionId===this.config.getSessionId()){this.toolGeneration=new AbortController}}captureToolSignal(){return this.toolGeneration.signal}async syncSession(reason){const current=this.config.getSessionId();if(current===this.sessionId){if(this.toolGeneration.signal.aborted)this.toolGeneration=new AbortController;return}this.invalidateTools();const task=this.toolQueue.then(async()=>{if(current===this.sessionId||this.closing)return;await this.end(reason);this.sessionId=current;this.adoptedAt=Date.now();this.startedAt=void 0;this.recorder=void 0;this.context={tokens:0,window:0};this.capture();this.toolGeneration=new AbortController;this.requestRender()});this.toolQueue=task.catch(()=>{});await task}get hasToolHooks(){return this.runtime?.hasToolHooks===true}setRenderInput(input){const band=this.band;const key=[input.viewport?.columns,input.viewport?.isFullscreen,stableJson(input.props)].join("\0");band.input=input;if(key===band.key)return;const size=`${input.viewport?.columns}\0${input.props.maxRows}`;const resized=band.size!==void 0&&size!==band.size;band.key=key;band.size=size;if(resized){clearTimeout(band.settle);band.settle=setTimeout(()=>{band.settle=void 0;this.requestRender()},RENDER_SETTLE_MS)}else this.requestRender()}requestRender(){const band=this.band;if(this.closing||!band.input||!this.sites.includes(band.input.component)||band.settle||band.wait||!this.runtime?.renderHooks.length||band.state==="waiting")return;if(band.state==="running"){band.again=true;return}const now=Date.now();const gap=(now<band.steadyUntil?RENDER_STEADY_MS:RENDER_LIVE_MS)-(now-band.startedAt);if(gap>0){band.wait=setTimeout(()=>{band.wait=void 0;this.requestRender()},gap);return}band.state="waiting";this.toolQueue=this.toolQueue.then(()=>this.render()).catch(error=>logger.debug(`Mod ui.render: ${String(error)}`))}async render(){const band=this.band;const runtime=this.runtime;const owner=runtime.renderHooks.length===1?runtime.renderHooks[0]:"hooks";band.state="running";band.startedAt=Date.now();try{if(this.closing||this.sessionId!==this.config.getSessionId())return;if(!this.allowed()||!this.active()){this.terminal?.draw?.(ENGINE_NODE,owner);return}const{tree,notes}=await runtime.render(band.input,this.lifetime.signal);for(const note of notes)logger.debug(note);if(!this.closing)this.terminal?.draw?.(tree,owner)}catch(error){logger.debug(`Mod ui.render: ${String(error)}`);if(!this.closing)this.terminal?.draw?.(ENGINE_NODE,owner)}finally{if(Date.now()-band.startedAt>RENDER_LIVE_MS)band.steadyUntil=Date.now()+RENDER_SLOW_MS;band.state="idle";if(band.again){band.again=false;this.requestRender()}this.flushLogs()}}toolCall(onRepeat){if(!this.hasToolHooks)return void 0;return(input,next,signal)=>{const generation=this.toolGeneration;const sessionId=this.sessionId;const active=AbortSignal.any([signal,this.lifetime.signal,generation.signal]);const assertAllowed=__name(()=>{active.throwIfAborted();if(generation!==this.toolGeneration||sessionId!==this.config.getSessionId()||!this.allowed()||!this.active()||this.closing)throw new Error("Mod tool middleware is disabled or its chain changed.")},"assertAllowed");const task=this.toolQueue.then(async()=>{assertAllowed();let attempts=0;this.toolSignal=active;try{return await this.runtime.runTool(input,async(changed,hostSignal,check)=>{assertAllowed();if(attempts++)onRepeat();active.throwIfAborted();return next(changed,hostSignal,async(question,verdict,checkSignal)=>{assertAllowed();const result=await check(question,verdict,checkSignal);assertAllowed();checkSignal.throwIfAborted();return result})},active)}finally{if(this.toolSignal===active)this.toolSignal=void 0}});this.toolQueue=task.catch(()=>{});return task}}startTurn(text,signal,abort,promptId){const hooks=this.runtime?.turnHooks;if(!hooks||!hooks.start&&!hooks.complete.length||this.closing)return void 0;const turn={id:randomUUID(),sessionId:this.sessionId,startedAt:Date.now(),abort,aborting:false,streaming:"",answer:"",failed:false,...promptId!==void 0&&{promptId}};this.turn=turn;if(hooks.start){const fitted=fitTurnText(text);const input={text:fitted.text,turnId:turn.id,...fitted.truncated&&{isTextTruncated:true}};void this.queueTurnEvent(turn,lifetime=>this.runtime.startTurn(input,AbortSignal.any([lifetime,signal])))}let ending;return{id:turn.id,saw:__name(event=>this.see(turn,event),"saw"),complete:__name(reason=>ending??=this.completeTurn(turn,reason),"complete")}}see(turn,event){if(turn.ended||!this.runtime?.turnHooks.complete.length)return;switch(event.type){case"content":turn.streaming+=event.value;break;case"finished":turn.answer=turn.streaming;turn.streaming="";turn.usage=addTurnUsage(turn.usage,event.value.usageMetadata,this.config.getContentGeneratorConfig()?.authType);break;case"retry":if(!event.isContinuation)turn.streaming="";else if(!turn.streaming)turn.streaming=turn.answer;break;case"model_fallback":turn.streaming="";break;case"error":case"loop_detected":case"max_session_turns":case"session_token_limit_exceeded":turn.failed=true;break;default:break}}completeTurn(turn,ending){if(turn.ended)return turn.ended;if(this.turn===turn)this.turn=void 0;const plugins=this.runtime?.turnHooks.complete??[];if(!plugins.length)return Promise.resolve();const reason=turn.aborting||ending==="aborted"?"aborted":ending==="error"||turn.failed?"error":"answer";const answer=fitTurnText((turn.streaming||turn.answer).trim());const input={answer:answer.text,durationMs:Date.now()-turn.startedAt,isAborted:reason==="aborted",turnId:turn.id,reason,...turn.usage?{usage:{...turn.usage,model:turn.model??runOutsideAgentContext(()=>this.config.getModel())}}:{},...answer.truncated&&{isAnswerTruncated:true}};const run=__name(async signal=>{const text=await this.runtime.completeTurn(input,signal);if(text===input.answer||!text.trim())return;const note={text:cpLen(text)>4096?`${cpSlice(text,0,4096)}\u2026`:text,to:"transcript",plugin:plugins.join("+"),sessionId:turn.sessionId,isTurnNote:true};if(!this.terminal&&this.config.getOutputFormat()==="text")this.notes.push(`[Mod ${note.plugin}] ${stripAnsiAndControl(note.text)}`);else this.pendingLogs.push(note)},"run");return turn.ended=this.queueTurnEvent(turn,run,true)}queueTurnEvent(turn,run,isEnd=false){const task=this.toolQueue.then(async()=>{if(this.closing&&!isEnd||turn.sessionId!==this.sessionId||!this.allowed()||!this.active())return;try{await run(isEnd?this.endLifetime.signal:this.lifetime.signal)}finally{this.flushLogs()}}).catch(error=>logger.debug(`Mod turn event: ${String(error)}`));this.toolQueue=task;return task}abortTurn(turnId){const turn=this.turn;if(!turn)throw new Error(`$.turn.abort: no turn is running (asked for ${turnId})`);if(turn.id!==turnId)throw new Error(`$.turn.abort: ${turnId} is not the running turn (${turn.id}); a hook ends the turn turn.start told it about`);if(turn.aborting)throw new Error(`$.turn.abort: ${turnId} is already ending`);turn.aborting=true;let cancelled=false;try{cancelled=turn.abort()}finally{turn.aborting=cancelled}if(!cancelled)throw new Error(`$.turn.abort: ${turnId} is already ending`);logger.debug(`$.turn.abort: cancelled turn ${turnId}`)}flushLogs(){this.logsReady=true;for(const entry of this.pendingLogs.splice(0)){logger.debug(`[${entry.plugin}] ${entry.text}`);if(entry.to==="debug")continue;const text=this.terminal?sanitizeTerminalText(stripUnsafeCharacters(entry.text)):stripAnsiAndControl(entry.text);if("surface"in this.output){const{isTurnNote,...log}=entry;this.output.log({...log,text:isTurnNote?text:cpSlice(text,0,2e3)},entry.plugin,entry.sessionId)}else if(this.config.getOutputFormat()==="text"){process.stderr.write(`[Mod ${entry.plugin}] ${text}
|
|
3
|
+
import{projectJsonStringToByteBudget}from"./chunk-WQUA4G2X.js";import{flushOutput}from"./chunk-VURTGFJP.js";import{cpLen,cpSlice,sanitizeTerminalLine,sanitizeTerminalText,stripUnsafeCharacters}from"./chunk-64CA3W6G.js";import{require_semver}from"./chunk-YZUKMJW7.js";import{ENGINE_NODE,MOD_END_TIMEOUT_MS,MOD_MAX_BYTES,ModBudget,adjustRenderTree,assertModDepth,record,validateRenderTree,validateResult}from"./chunk-ZZJXFLVM.js";import{stableJson}from"./chunk-FIXDX63I.js";import{external_exports}from"./chunk-TWP72VRH.js";import{openNoFollow}from"./chunk-QXQGUM3Y.js";import{resolveBundleDir}from"./chunk-4NPYOXJO.js";import{runOutsideAgentContext}from"./chunk-YZFNBUKG.js";import{isInternalPromptId,uiTelemetryService}from"./chunk-ZWPSBU7K.js";import{getGenAiUsageProvenance,outputTokenCount}from"./chunk-4DIWAQ5G.js";import{EVENT_API_RESPONSE}from"./chunk-3XVPZY7X.js";import{registerCleanup}from"./chunk-EQOHDAYU.js";import{stripAnsiAndControl}from"./chunk-DBRQGEEI.js";import{ToolNames}from"./chunk-SBZFGYYS.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();import{randomUUID}from"node:crypto";init_esbuild_shims();import{promises as fs}from"node:fs";import path from"node:path";init_esbuild_shims();var import_semver=__toESM(require_semver(),1);var name=external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/);var dependency=external_exports.union([external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*(?:@[a-zA-Z0-9][a-zA-Z0-9._-]*)?$/),external_exports.object({name,marketplace:name.optional(),version:external_exports.string().optional()}).strict()]);function parseModDependencies(value){const parsed=external_exports.array(dependency).safeParse(value===void 0?[]:value);if(!parsed.success)throw new Error("Invalid Mod dependencies declaration.");return parsed.data.map(item=>{if(typeof item==="string"){const[name2,marketplace]=item.split("@");return{name:name2,marketplace}}if(item.version!==void 0&&!(0,import_semver.validRange)(item.version)){throw new Error(`Invalid Mod dependency version range for ${item.name}.`)}return item})}__name(parseModDependencies,"parseModDependencies");function resolveModDependency(plugins,plugin,dependency2){const marketplace=dependency2.marketplace??plugin.marketplace;const local=plugins.filter(item=>item.name===dependency2.name&&!item.marketplace);const matches=local.length?local:plugins.filter(item=>item.name===dependency2.name&&item.marketplace===marketplace);if(matches.length!==1){throw new Error(`Mod ${plugin.name}: dependency ${dependency2.name} must identify one installed, enabled plugin.`)}const target=matches[0];if(target.marketplace&&dependency2.version&&!(0,import_semver.satisfies)(target.version,dependency2.version)){throw new Error(`Mod ${plugin.name}: dependency ${dependency2.name} has an incompatible installed version.`)}return target}__name(resolveModDependency,"resolveModDependency");function orderModPlugins(plugins){const edges=plugins.map(()=>new Set);const incoming=plugins.map(()=>0);for(const[index,plugin]of plugins.entries()){for(const dependency2 of plugin.dependencies){const targetIndex=plugins.indexOf(resolveModDependency(plugins,plugin,dependency2));if(!edges[index].has(targetIndex)){edges[index].add(targetIndex);incoming[targetIndex]++}}}const ordered=[];const remaining=new Set(plugins.map((_,index)=>index));while(remaining.size){const next=[...remaining].find(index=>incoming[index]===0);if(next===void 0)throw new Error("Mod dependency cycle: activation refused.");remaining.delete(next);ordered.push(plugins[next]);for(const target of edges[next])incoming[target]--}return ordered}__name(orderModPlugins,"orderModPlugins");function isContainedFile(root,file){const relative=path.relative(root,file);return Boolean(relative)&&!path.isAbsolute(relative)&&relative!==".."&&!relative.startsWith(`..${path.sep}`)}__name(isContainedFile,"isContainedFile");async function readModFile(root,file){if(!isContainedFile(root,file)){throw new Error("Mod file must stay inside the installed extension.")}let current=root;for(const part of path.relative(root,file).split(path.sep)){current=path.join(current,part);const stat=await fs.lstat(current);if(stat.isSymbolicLink()){throw new Error("Mod files cannot be symbolic links.")}if(current===file&&!stat.isFile()){throw Object.assign(new Error("Mod input must be a regular file."),{code:stat.isDirectory()?"EISDIR":void 0})}}const entry=await fs.realpath(file);if(!isContainedFile(root,entry)){throw new Error("Mod file must stay inside the installed extension.")}const handle=await openNoFollow(entry);try{const stat=await handle.stat();if(!stat.isFile()||stat.size>MOD_MAX_BYTES){throw new Error("Mod file exceeds the 256 KiB regular-file limit.")}const buffer=Buffer.alloc(MOD_MAX_BYTES+1);const{bytesRead}=await handle.read(buffer,0,buffer.length,0);if(bytesRead>MOD_MAX_BYTES)throw new Error("Mod file is too large.");return{entry,source:buffer.subarray(0,bytesRead).toString("utf8")}}finally{await handle.close()}}__name(readModFile,"readModFile");async function readManifest(root,relative){try{if(path.isAbsolute(relative)){throw new Error("Mod manifest path must be relative to the extension.")}const value=JSON.parse((await readModFile(root,path.resolve(root,relative))).source);if(!value||typeof value!=="object"||Array.isArray(value)){throw new Error("Mod manifest must be a JSON object.")}return value}catch(error){if(error.code==="ENOENT")return void 0;throw error}}__name(readManifest,"readManifest");async function loadModSource(extensionPath){const root=await fs.realpath(extensionPath);const qwen=await readManifest(root,"qwen-extension.json");if(typeof qwen?.["hooks"]==="string"&&(path.isAbsolute(qwen["hooks"])||!isContainedFile(root,path.resolve(root,qwen["hooks"])))){return void 0}const claude=await readManifest(root,".claude-plugin/plugin.json");const hooksPath=typeof qwen?.["hooks"]==="string"?qwen["hooks"]:typeof claude?.["hooks"]==="string"?claude["hooks"]:"hooks/hooks.json";if(path.isAbsolute(hooksPath)||!isContainedFile(root,path.resolve(root,hooksPath))){return void 0}const hooks=await readManifest(root,hooksPath);if(!hooks||!Object.hasOwn(hooks,"modules"))return void 0;const modules=hooks["modules"];if(!Array.isArray(modules)||modules.length!==1||typeof modules[0]!=="string"||path.isAbsolute(modules[0])||!/\.(?:[cm]?js|[cm]?ts|[jt]sx)$/.test(modules[0])){throw new Error("Mods require one relative JavaScript, TypeScript or JSX module.")}const manifest={...claude,...qwen};const entry=path.resolve(root,path.dirname(hooksPath),modules[0]);return{root,...await readModFile(root,entry),userConfig:manifest["userConfig"],dependencies:parseModDependencies(manifest["dependencies"])}}__name(loadModSource,"loadModSource");async function loadModDependencies(extensionPath){const root=await fs.realpath(extensionPath);const qwen=await readManifest(root,"qwen-extension.json");const claude=await readManifest(root,".claude-plugin/plugin.json");return parseModDependencies({...claude,...qwen}["dependencies"])}__name(loadModDependencies,"loadModDependencies");init_esbuild_shims();var option=external_exports.union([external_exports.string(),external_exports.number().finite(),external_exports.boolean(),external_exports.array(external_exports.string())]);var field=external_exports.object({type:external_exports.enum(["string","number","boolean","directory","file"]),title:external_exports.string(),description:external_exports.string(),required:external_exports.boolean().optional(),default:option.optional(),multiple:external_exports.boolean().optional(),sensitive:external_exports.boolean().optional(),min:external_exports.number().finite().optional(),max:external_exports.number().finite().optional(),options:external_exports.array(external_exports.string().min(1).max(64)).nonempty().optional()}).strict().refine(value=>{if(!value.options)return true;return value.type==="string"&&!value.multiple&&!value.sensitive&&value.options.every(item=>item.trim()===item&&!/[\p{Cc}\p{Cf}]/u.test(item))&&new Set(value.options.map(item=>item.toLowerCase())).size===value.options.length&&(value.default===void 0?value.required===true:value.options.includes(value.default))});var schema=external_exports.record(external_exports.string().regex(/^[A-Za-z_]\w*$/),field);var storedOptions=external_exports.record(option);function*pluginConfigurations(scopes,name2,marketplace){const keys=marketplace?[`${name2}@${marketplace}`]:[name2,`${name2}@inline`];for(const scope of scopes){if(scope===void 0)continue;if(!scope||typeof scope!=="object"||Array.isArray(scope)){throw new Error("Invalid Mod pluginConfigs settings.")}for(const key of keys){if(!Object.hasOwn(scope,key))continue;const config=scope[key];if(!config||typeof config!=="object"||Array.isArray(config)){throw new Error("Invalid Mod pluginConfigs entry.")}yield config}}}__name(pluginConfigurations,"pluginConfigurations");function resolveModChoice(scopes,name2,marketplace,key,choices){let choice=choices[0];for(const config of pluginConfigurations(scopes,name2,marketplace)){const value=config[key];if(value===void 0)continue;if(!choices.includes(value))throw new Error(`Invalid Mod ${key}: expected ${choices.join(" or ")}.`);choice=value}return choice}__name(resolveModChoice,"resolveModChoice");function resolveModToolDialect(scopes,name2,marketplace){return resolveModChoice(scopes,name2,marketplace,"toolDialect",["native","claude"])}__name(resolveModToolDialect,"resolveModToolDialect");function resolveModUnsupportedEvents(scopes,name2,marketplace){return resolveModChoice(scopes,name2,marketplace,"unsupportedEvents",["skip","reject"])}__name(resolveModUnsupportedEvents,"resolveModUnsupportedEvents");function resolveModOptions(declaration,scopes,name2,marketplace){const parsed=schema.safeParse(declaration===void 0?{}:declaration);if(!parsed.success)throw new Error("Invalid Mod userConfig declaration.");const fields=Object.entries(parsed.data);if(!fields.length)return{};if(fields.some(([,value])=>value.sensitive)){throw new Error("Sensitive Mod userConfig is not supported yet.")}let stored={};for(const config of pluginConfigurations(scopes,name2,marketplace)){const options=config["options"];if(options===void 0)continue;const values=storedOptions.safeParse(options);if(!values.success)throw new Error(`Invalid Mod configured option: ${String(values.error.issues[0]?.path[0]??"").slice(0,64)}.`);stored={...stored,...values.data}}const result=Object.fromEntries(fields.filter(([,config])=>config.default!==void 0||!config.required).map(([key,config])=>[key,config.default??""]));for(const[key,value]of Object.entries(stored)){const choices=Object.hasOwn(parsed.data,key)?parsed.data[key].options:void 0;if(!choices||choices.includes(value))Object.defineProperty(result,key,{value,enumerable:true,writable:true,configurable:true})}for(const[key,config]of fields){const value=Object.hasOwn(result,key)?result[key]:void 0;if(value===void 0||value===""){if(config.required)throw new Error(`Missing required Mod option: ${key}.`)}else{const valid=config.type==="number"?typeof value==="number"&&(config.min===void 0||value>=config.min)&&(config.max===void 0||value<=config.max):config.type==="boolean"?typeof value==="boolean":typeof value==="string"||config.type==="string"&&config.multiple&&Array.isArray(value);if(!valid)throw new Error(`Invalid Mod option: ${key}.`)}}if(Buffer.byteLength(JSON.stringify(result))>MOD_MAX_BYTES){throw new Error("Mod options exceed the 256 KiB limit.")}return result}__name(resolveModOptions,"resolveModOptions");init_esbuild_shims();import{Worker}from"node:worker_threads";import{existsSync}from"node:fs";import path2 from"node:path";import{createRequire}from"node:module";import{pathToFileURL}from"node:url";function workerEntry(){if(import.meta.url.endsWith(".ts")){return new URL(`data:text/javascript,${encodeURIComponent(`import { register } from ${JSON.stringify(pathToFileURL(createRequire(import.meta.url).resolve("tsx/esm/api")).href)}; register(); await import(${JSON.stringify(new URL("./mod-worker.ts",import.meta.url).href)});`)}`)}const sibling=new URL("./mod-worker.js",import.meta.url);return existsSync(sibling)?sibling:path2.join(resolveBundleDir(import.meta.url),"mod-worker.js")}__name(workerEntry,"workerEntry");var ModRuntime=class _ModRuntime{constructor(log,facts,resolveTool,surface=null,abortTurn,renderHost){this.log=log;this.facts=facts;this.resolveTool=resolveTool;this.surface=surface;this.abortTurn=abortTurn;this.renderHost=renderHost;this.worker=new Worker(workerEntry(),{stdout:true,stderr:true,workerData:this.cancelled.buffer});this.worker.stdout?.resume();this.worker.stderr?.resume();this.worker.on("message",reply=>{const root=this.root;if(!root||reply.root!==root.id)return;if(reply.type==="host-call")this.executeHost(reply);else if(reply.type==="host-cancel"){for(const id of reply.ids)this.tool?.operations.get(id)?.controller.abort()}else if(reply.type==="check-result")this.tool?.checks.get(reply.id)?.(reply);else if(reply.type==="turn-abort")this.answerTurnAbort(reply,root.id);else if(reply.type==="invalidate"){if(reply.event!=="ui.render"||this.failure)return;if(this.early)this.early.add(reply.plugin);else if(this.renders.includes(reply.plugin))this.renderHost?.invalidate(reply.plugin)}else if(reply.type==="activity"){if(reply.phase!==root.phase||reply.revision<=root.revision||reply.operation!==void 0&&reply.operation!==root.native)return;root.revision=reply.revision;root.idle=this.tool?.checks.size?void 0:reply.operation;root.refresh()}else if(reply.type==="log"){if(this.failure)return;try{this.log({text:reply.text,to:reply.to},reply.plugin)}catch(error){this.fail(error instanceof Error?error:new Error(String(error)));void this.worker.terminate()}}else this.pending?.(reply)});this.worker.on("error",error=>this.fail(error));this.worker.on("exit",code=>this.fail(new Error(`Mod worker exited (${code}).`)))}static{__name(this,"ModRuntime")}worker;failure;pending;commands=[];tools=false;turns={start:false,complete:[]};renders=[];early=new Set;noted=new Set;sequence=0;root;tool;cancelled=new Int32Array(new SharedArrayBuffer(4));static async create(source,cwd,log,signal,options={}){return _ModRuntime.createGroup([{id:"mod",name:"mod",source,options}],cwd,log,signal)}static async createGroup(plugins,cwd,log,signal,resolveTool,surface=null,version="unknown",facts,abortTurn,render){if(plugins.length>32||new Set(plugins.map(p=>p.id)).size!==plugins.length)throw new Error("Invalid Mod plugin group.");const startedAt=Date.now();const runtime=new _ModRuntime(log,facts??(()=>({id:"",cwd,root:cwd,model:"",turns:0,usage:{startedAt,context:{tokens:0,window:0},rateLimits:[]}})),plugins.some(plugin=>plugin.toolDialect==="claude")?resolveTool:void 0,surface,abortTurn,render);try{const result=await runtime.request({type:"load",plugins,cwd,surface,version,sites:render?.sites??[]},signal,6e4);const names=__name(value=>Array.isArray(value)&&value.every(name2=>plugins.some(plugin=>plugin.name===name2)),"names");const turnComplete=record(result)?result["turnComplete"]:void 0;const renders=record(result)?result["render"]:void 0;if(!record(result)||typeof result["tools"]!=="boolean"||typeof result["turnStart"]!=="boolean"||!names(turnComplete)||!names(renders))throw new Error("Invalid Mod declarations.");const commands=result["commands"];if(!Array.isArray(commands)||commands.length>64||commands.some(command=>!command||!plugins.some(plugin=>plugin.id===command.plugin)||typeof command.name!=="string"||!/^[a-zA-Z0-9_-]{1,64}$/.test(command.name)||typeof command.description!=="string"||command.argumentHint!==void 0&&typeof command.argumentHint!=="string"))throw new Error("Invalid Mod command declarations.");runtime.commands=commands;runtime.tools=result["tools"];runtime.turns={start:result["turnStart"],complete:turnComplete};runtime.renders=renders;const early=runtime.early;runtime.early=void 0;for(const plugin of early)if(renders.includes(plugin))render?.invalidate(plugin);return runtime}catch(error){await runtime.dispose();throw error}}getCommands(plugin="mod"){return this.commands.filter(command=>command.plugin===plugin).map(({plugin:_plugin,...command})=>command)}get hasToolHooks(){return this.tools}get turnHooks(){return this.turns}get renderHooks(){return this.renders}async render(input,signal){const settled=await this.request({type:"render",input},signal);const owner=this.renders.length===1?this.renders[0]:"hooks";const notes=[];const note=__name((line,key=line)=>{if(this.noted.has(key))return;this.noted.add(key);notes.push(`${owner}: ${line}`)},"note");try{validateRenderTree(settled)}catch(error){note(`ui.render (${input.component}) refused: ${error instanceof Error?error.message:String(error)}; nothing was drawn`);return{tree:ENGINE_NODE,notes}}const adjusted=adjustRenderTree(settled,input.component);for(const{key,text}of adjusted.notes)note(text,`${input.component}\0${key}`);return{tree:adjusted.tree,notes}}async builtinTool(name2){if(!this.resolveTool)return void 0;let builtin=false;switch(name2){case ToolNames.SHELL:builtin=await this.resolveTool(name2)instanceof(await import("./shell-V4WWLW3Q.js")).ShellTool;break;case ToolNames.EDIT:builtin=await this.resolveTool(name2)instanceof(await import("./edit-U7TGKKK3.js")).EditTool;break;case ToolNames.WRITE_FILE:builtin=await this.resolveTool(name2)instanceof(await import("./write-file-DEAFIK4C.js")).WriteFileTool;break;default:return void 0}return builtin?name2:void 0}async runTool(input,next,signal){if(this.tool||this.pending)throw new Error("A Mod dispatch is already running.");const owner={next,controller:new AbortController,operations:new Map,checks:new Map,tail:Promise.resolve()};this.tool=owner;try{const builtinTool=await this.builtinTool(input.tool);const result=await this.request({type:"tool",input,builtinTool},AbortSignal.any([signal,owner.controller.signal]));validateResult("tool.call",result);return result}finally{owner.controller.abort();await Promise.allSettled([...owner.operations.values()].map(operation=>operation.task));this.tool=void 0}}executeHost(reply){const owner=this.tool;const root=this.root;if(!owner||!root||owner.operations.size>=32||owner.operations.has(reply.id)){this.fail(new Error("Invalid Mod host operation."));return}const controller=new AbortController;const signal=AbortSignal.any([owner.controller.signal,controller.signal]);const task=owner.tail.then(async()=>{signal.throwIfAborted();root.native=reply.id;root.phase++;root.idle=void 0;root.refresh();this.post({type:"native",id:reply.id},root.id);const result=await owner.next(reply.input,signal,async(input,verdict,checkSignal)=>{const active=AbortSignal.any([signal,checkSignal]);active.throwIfAborted();const id=++this.sequence;let abort=__name(()=>{},"abort");try{return await new Promise((resolve,reject)=>{abort=__name(()=>reject(new Error("Mod permission check cancelled.")),"abort");owner.checks.set(id,response=>{if(response.error!==void 0)reject(new Error(response.error));else{try{validateResult("tool.check",response.result);resolve({...response.result,ceiling:input.ceiling})}catch(error){reject(error)}}});root.idle=void 0;root.phase++;root.refresh();active.addEventListener("abort",abort,{once:true});this.post({type:"tool-check",id,operation:reply.id,input,verdict},root.id)})}finally{active.removeEventListener("abort",abort);owner.checks.delete(id);root.refresh()}});root.native=void 0;root.phase++;root.idle=void 0;root.refresh();signal.throwIfAborted();this.post({type:"host-result",id:reply.id,result},root.id)}).catch(error=>{root.native=void 0;root.phase++;root.idle=void 0;root.refresh();if(!this.failure)this.post({type:"host-result",id:reply.id,error:String(error).slice(0,4e3)},root.id)}).finally(()=>{owner.operations.delete(reply.id)});owner.operations.set(reply.id,{controller,task});owner.tail=task}post(request,root){if(this.root?.id!==root)return;const json=JSON.stringify(request);if(Buffer.byteLength(json)>MOD_MAX_BYTES+8192)throw new Error("Mod host message is too large.");assertModDepth(json,"Mod host message");this.worker.postMessage({...request,root,phase:this.root.phase})}async runCommand(command,args,signal,presentation){if(!this.commands.some(item=>item.name===command))throw new Error("Unknown Mod command.");const result=await this.request({type:"command",command,args,...this.surface==="terminal"&&presentation?{presentation}:{}},signal);if(!result||typeof result!=="object"||Array.isArray(result)||Object.keys(result).some(key=>key!=="text")||"text"in result&&typeof result.text!=="string"){throw new Error("Invalid Mod command result.")}return"text"in result?result.text:""}async startTurn(input,signal){validateResult("turn.start",await this.request({type:"turn-start",input},signal))}async completeTurn(input,signal){const result=await this.request({type:"turn-complete",input},signal);validateResult("turn.complete",result);return result.text}answerTurnAbort(reply,root){let error;try{if(!this.abortTurn)throw new Error(`$.turn.abort: no turn is running (asked for ${reply.turnId})`);this.abortTurn(reply.turnId)}catch(caught){error=(caught instanceof Error?caught.message:String(caught)).slice(0,4e3)}this.post({type:"turn-abort-result",id:reply.id,error},root)}async end(sessionId,reason,signal){await this.request({type:"end",sessionId,reason},signal,MOD_END_TIMEOUT_MS)}async dispose(){this.fail(new Error("Mod runtime is closed."));await this.worker.terminate();await Promise.allSettled([...this.tool?.operations.values()??[]].map(operation=>operation.task))}fail(error){this.failure??=error;this.tool?.controller.abort();this.pending?.({type:"error",message:this.failure.message})}async request(request,signal,timeoutMs=6e4){signal.throwIfAborted();if(this.failure)throw this.failure;if(this.pending)throw new Error("A Mod dispatch is already running.");const message={...request,facts:this.facts()};const json=JSON.stringify(message);if(Buffer.byteLength(json)>(request.type==="load"?32:1)*MOD_MAX_BYTES+8192)throw new Error("Mod request is too large.");assertModDepth(json,"Mod request");let timer;let cancelTimer;let aborted=false;const budget=new ModBudget(timeoutMs+250);const stop=__name(()=>{this.fail(new Error(aborted?"Mod dispatch cancelled.":"Mod dispatch timed out."));void this.worker.terminate()},"stop");const root={id:++this.sequence,revision:0,phase:0,refresh:__name(()=>{if(aborted||this.root!==root)return;const lending=request.type==="tool"&&root.native!==void 0&&root.idle===root.native&&!this.tool?.checks.size&&!budget.expired;if(lending!==budget.lending){if(lending)budget.pause();else budget.resume()}if(timer)clearTimeout(timer);if(!budget.lending)timer=setTimeout(stop,budget.remainingMs)},"refresh")};this.root=root;const onAbort=__name(()=>{aborted=true;Atomics.store(this.cancelled,0,1);this.tool?.controller.abort();if(timer)clearTimeout(timer);cancelTimer=setTimeout(stop,250)},"onAbort");Atomics.store(this.cancelled,0,0);try{return await new Promise((resolve,reject)=>{this.pending=reply=>{if(this.failure)reject(this.failure);else if(aborted)reject(new Error("Mod dispatch cancelled."));else if(reply.type==="error")reject(new Error(reply.message));else if(reply.type==="result"){try{if(Buffer.byteLength(reply.json)>MOD_MAX_BYTES)throw new Error("Mod reply is too large.");resolve(JSON.parse(reply.json))}catch(error){reject(error)}}};signal.addEventListener("abort",onAbort,{once:true});root.refresh();this.worker.postMessage({...message,root:root.id,phase:root.phase})})}finally{this.root=void 0;if(timer)clearTimeout(timer);if(cancelTimer)clearTimeout(cancelTimer);signal.removeEventListener("abort",onAbort);this.pending=void 0}}};var logger=createDebugLogger("MODS");var RENDER_SETTLE_MS=150;var RENDER_LIVE_MS=34;var RENDER_STEADY_MS=100;var RENDER_SLOW_MS=1e3;var ModSession=class _ModSession{constructor(config,output,optionScopes=[]){this.config=config;this.output=output;this.optionScopes=optionScopes;this.sessionId=config.getSessionId();uiTelemetryService.on("update",this.observe);this.unregisterCleanup=registerCleanup(()=>{this.unregisterCleanup=()=>{};return this.close().then(()=>this.flushOutput())},{first:Boolean(this.terminal)})}static{__name(this,"ModSession")}mods=[];runtime;toolQueue=Promise.resolve();lifetime=new AbortController;endLifetime=new AbortController;initialization;closing;logsReady=false;pendingLogs=[];notes=[];activeCommand;commandSignal;toolSignal;sessionId;adoptedAt=Date.now();startedAt;recorder;context={tokens:0,window:0};turn;observe=__name(update=>runOutsideAgentContext(()=>{if(this.config.getSessionId()!==this.sessionId)return;this.recorder=this.config.getChatRecordingService();this.context={tokens:uiTelemetryService.getLastPromptTokenCount(),window:this.config.getContentGeneratorConfig()?.contextWindowSize||0};const event=update?.event;if(!this.turn||event?.["event.name"]!==EVENT_API_RESPONSE)return;const response=event;if(response.subagent_name===void 0&&!isInternalPromptId(response.prompt_id)&&(this.turn.promptId===void 0||response.prompt_id===this.turn.promptId))this.turn.model=response.model}),"observe");toolGeneration=new AbortController;sites=[];band={state:"idle",again:false,startedAt:-Infinity,steadyUntil:0};unregisterCleanup;static create(config,settings,output){return settings.merged.experimental?.mods?new _ModSession(config,output,[settings.systemDefaults.settings.pluginConfigs,settings.user.settings.pluginConfigs,settings.system.settings.pluginConfigs]):void 0}get terminal(){return"surface"in this.output?this.output:void 0}allowed(){return this.config.isInteractive()===Boolean(this.terminal)&&!this.config.getExperimentalZedIntegration()&&this.config.isTrustedFolder()&&!this.config.getDisableAllHooks()&&!this.config.getBareMode()&&!this.config.isSafeMode()&&!this.config.getExecutionEnvironment()&&!this.config.getExecutionEnvironmentFactory()&&!this.config.getHookSystem()?.isManaged()&&!this.config.getSandbox()&&!this.config.isSessionAgentSession()}async initialize(signal){if(this.closing)throw new Error("Mod session is closed.");if(!this.allowed()){if(this.mods.length){await this.close();throw new Error("Mods are no longer permitted in this session.")}return}this.initialization??=this.load(AbortSignal.any([signal,this.lifetime.signal]));await this.initialization}async load(signal){const sites=this.sites=this.terminal?.sites?.()??[];try{const candidates=[];for(const extension of this.config.getExtensions().filter(item=>item.isActive&&item.format!=="agent-plugins-v1")){signal.throwIfAborted();try{const source=await loadModSource(extension.path);const marketplace=extension.installMetadata?.marketplaceConfig?.name;candidates.push({extension,name:extension.name,version:extension.version,marketplace,source,dependencies:source?.dependencies??[],toolDialect:source?resolveModToolDialect(this.optionScopes,extension.name,marketplace):void 0,unsupportedEvents:source?resolveModUnsupportedEvents(this.optionScopes,extension.name,marketplace):void 0,options:source?resolveModOptions(source.userConfig,this.optionScopes,extension.name,marketplace):{}})}catch(error){throw new Error(`Mod ${extension.name}: ${error instanceof Error?error.message:String(error)}`)}}const pending=candidates.filter(item=>item.source);const reachable=new Set;while(pending.length){signal.throwIfAborted();const plugin=pending.shift();if(reachable.has(plugin))continue;reachable.add(plugin);if(!plugin.source){try{plugin.dependencies=await loadModDependencies(plugin.extension.path)}catch(error){throw new Error(`Mod dependency ${plugin.name}: ${error instanceof Error?error.message:String(error)}`)}}for(const dependency2 of plugin.dependencies){pending.push(resolveModDependency(candidates,plugin,dependency2))}}const selected=candidates.filter(item=>reachable.has(item));orderModPlugins(selected);const mods=selected.filter(item=>item.source).map(plugin=>({...plugin,dependencies:plugin.dependencies.filter(dependency2=>resolveModDependency(selected,plugin,dependency2).source)}));const ordered=orderModPlugins(mods);if(ordered.length){this.runtime=await ModRuntime.createGroup(ordered.map(({extension,source,options,toolDialect,unsupportedEvents})=>({id:extension.id,name:extension.name,source:{root:source.root,entry:source.entry,source:source.source},options,toolDialect,unsupportedEvents})),this.config.getTargetDir(),(entry,plugin)=>{if(this.commandSignal?.aborted||this.toolSignal?.aborted)return;this.pendingLogs.push({...entry,plugin,sessionId:this.sessionId});if(this.logsReady)this.flushLogs()},signal,name2=>this.config.getToolRegistry().ensureTool(name2),this.terminal?.surface??null,this.config.getCliVersion()||"unknown",()=>this.facts(),turnId=>this.abortTurn(turnId),sites.length?{sites,invalidate:__name(()=>this.requestRender(),"invalidate")}:void 0);this.mods.push(...ordered.map(({extension})=>({id:extension.id,name:extension.name})));this.requestRender()}}catch(error){await this.runtime?.dispose();this.mods.length=0;throw error}}async loadCommands(signal){await this.initialize(signal);return this.mods.flatMap(mod=>this.runtime.getCommands(mod.id).map(command=>({name:command.name,description:this.terminal?sanitizeTerminalLine(command.description):command.description,kind:"file",source:"plugin-command",extensionName:this.terminal?sanitizeTerminalLine(mod.name):mod.name,supportedModes:[this.terminal?"interactive":"non_interactive"],argumentHint:this.terminal&&command.argumentHint!==void 0?sanitizeTerminalLine(command.argumentHint):command.argumentHint,modelInvocable:false,action:__name(async(context,args)=>{const active=AbortSignal.any([context.abortSignal??(this.terminal?this.lifetime.signal:signal),this.lifetime.signal]);const task=this.toolQueue.then(async()=>{active.throwIfAborted();if(!this.allowed()||!this.active()||this.closing){await this.runtime.dispose();throw new Error(`Mod ${mod.name} is disabled or its middleware chain changed.`)}if(this.sessionId!==this.config.getSessionId())throw new Error("The Mod command belongs to a previous session.");const controller=new AbortController;this.activeCommand=controller;const commandSignal=AbortSignal.any([active,controller.signal]);this.commandSignal=commandSignal;try{const content=await this.runtime.runCommand(command.name,args,commandSignal,this.terminal?.presentation());commandSignal.throwIfAborted();return{type:"message",messageType:"info",content:this.terminal?sanitizeTerminalText(stripUnsafeCharacters(content)):content}}finally{this.flushLogs();this.activeCommand=void 0;this.commandSignal=void 0}});this.toolQueue=task.catch(()=>{});return task},"action")})))}invalidateTools(){this.toolGeneration.abort();this.pendingLogs.length=0;this.activeCommand?.abort()}async restoreTools(){await this.toolQueue;if(!this.closing&&this.sessionId===this.config.getSessionId()){this.toolGeneration=new AbortController}}captureToolSignal(){return this.toolGeneration.signal}async syncSession(reason){const current=this.config.getSessionId();if(current===this.sessionId){if(this.toolGeneration.signal.aborted)this.toolGeneration=new AbortController;return}this.invalidateTools();const task=this.toolQueue.then(async()=>{if(current===this.sessionId||this.closing)return;await this.end(reason);this.sessionId=current;this.adoptedAt=Date.now();this.startedAt=void 0;this.recorder=void 0;this.context={tokens:0,window:0};this.capture();this.toolGeneration=new AbortController;this.requestRender()});this.toolQueue=task.catch(()=>{});await task}get hasToolHooks(){return this.runtime?.hasToolHooks===true}setRenderInput(input){const band=this.band;const key=[input.viewport?.columns,input.viewport?.isFullscreen,stableJson(input.props)].join("\0");band.input=input;if(key===band.key)return;const size=`${input.viewport?.columns}\0${input.props.maxRows}`;const resized=band.size!==void 0&&size!==band.size;band.key=key;band.size=size;if(resized){clearTimeout(band.settle);band.settle=setTimeout(()=>{band.settle=void 0;this.requestRender()},RENDER_SETTLE_MS)}else this.requestRender()}requestRender(){const band=this.band;if(this.closing||!band.input||!this.sites.includes(band.input.component)||band.settle||band.wait||!this.runtime?.renderHooks.length||band.state==="waiting")return;if(band.state==="running"){band.again=true;return}const now=Date.now();const gap=(now<band.steadyUntil?RENDER_STEADY_MS:RENDER_LIVE_MS)-(now-band.startedAt);if(gap>0){band.wait=setTimeout(()=>{band.wait=void 0;this.requestRender()},gap);return}band.state="waiting";this.toolQueue=this.toolQueue.then(()=>this.render()).catch(error=>logger.debug(`Mod ui.render: ${String(error)}`))}async render(){const band=this.band;const runtime=this.runtime;const owner=runtime.renderHooks.length===1?runtime.renderHooks[0]:"hooks";band.state="running";band.startedAt=Date.now();try{if(this.closing||this.sessionId!==this.config.getSessionId())return;if(!this.allowed()||!this.active()){this.terminal?.draw?.(ENGINE_NODE,owner);return}const{tree,notes}=await runtime.render(band.input,this.lifetime.signal);for(const note of notes)logger.debug(note);if(!this.closing)this.terminal?.draw?.(tree,owner)}catch(error){logger.debug(`Mod ui.render: ${String(error)}`);if(!this.closing)this.terminal?.draw?.(ENGINE_NODE,owner)}finally{if(Date.now()-band.startedAt>RENDER_LIVE_MS)band.steadyUntil=Date.now()+RENDER_SLOW_MS;band.state="idle";if(band.again){band.again=false;this.requestRender()}this.flushLogs()}}toolCall(onRepeat){if(!this.hasToolHooks)return void 0;return(input,next,signal)=>{const generation=this.toolGeneration;const sessionId=this.sessionId;const active=AbortSignal.any([signal,this.lifetime.signal,generation.signal]);const assertAllowed=__name(()=>{active.throwIfAborted();if(generation!==this.toolGeneration||sessionId!==this.config.getSessionId()||!this.allowed()||!this.active()||this.closing)throw new Error("Mod tool middleware is disabled or its chain changed.")},"assertAllowed");const task=this.toolQueue.then(async()=>{assertAllowed();let attempts=0;this.toolSignal=active;try{return await this.runtime.runTool(input,async(changed,hostSignal,check)=>{assertAllowed();if(attempts++)onRepeat();active.throwIfAborted();return next(changed,hostSignal,async(question,verdict,checkSignal)=>{assertAllowed();const result=await check(question,verdict,checkSignal);assertAllowed();checkSignal.throwIfAborted();return result})},active)}finally{if(this.toolSignal===active)this.toolSignal=void 0}});this.toolQueue=task.catch(()=>{});return task}}startTurn(text,signal,abort,promptId){const hooks=this.runtime?.turnHooks;if(!hooks||!hooks.start&&!hooks.complete.length||this.closing)return void 0;const turn={id:randomUUID(),sessionId:this.sessionId,startedAt:Date.now(),abort,aborting:false,streaming:"",answer:"",failed:false,...promptId!==void 0&&{promptId}};this.turn=turn;if(hooks.start){const fitted=fitTurnText(text);const input={text:fitted.text,turnId:turn.id,...fitted.truncated&&{isTextTruncated:true}};void this.queueTurnEvent(turn,lifetime=>this.runtime.startTurn(input,AbortSignal.any([lifetime,signal])))}let ending;return{id:turn.id,saw:__name(event=>this.see(turn,event),"saw"),complete:__name(reason=>ending??=this.completeTurn(turn,reason),"complete")}}see(turn,event){if(turn.ended||!this.runtime?.turnHooks.complete.length)return;switch(event.type){case"content":turn.streaming+=event.value;break;case"finished":turn.answer=turn.streaming;turn.streaming="";turn.usage=addTurnUsage(turn.usage,event.value.usageMetadata,this.config.getContentGeneratorConfig()?.authType);break;case"retry":if(!event.isContinuation)turn.streaming="";else if(!turn.streaming)turn.streaming=turn.answer;break;case"model_fallback":turn.streaming="";break;case"error":case"loop_detected":case"max_session_turns":case"session_token_limit_exceeded":turn.failed=true;break;default:break}}completeTurn(turn,ending){if(turn.ended)return turn.ended;if(this.turn===turn)this.turn=void 0;const plugins=this.runtime?.turnHooks.complete??[];if(!plugins.length)return Promise.resolve();const reason=turn.aborting||ending==="aborted"?"aborted":ending==="error"||turn.failed?"error":"answer";const answer=fitTurnText((turn.streaming||turn.answer).trim());const input={answer:answer.text,durationMs:Date.now()-turn.startedAt,isAborted:reason==="aborted",turnId:turn.id,reason,...turn.usage?{usage:{...turn.usage,model:turn.model??runOutsideAgentContext(()=>this.config.getModel())}}:{},...answer.truncated&&{isAnswerTruncated:true}};const run=__name(async signal=>{const text=await this.runtime.completeTurn(input,signal);if(text===input.answer||!text.trim())return;const note={text:cpLen(text)>4096?`${cpSlice(text,0,4096)}\u2026`:text,to:"transcript",plugin:plugins.join("+"),sessionId:turn.sessionId,isTurnNote:true};if(!this.terminal&&this.config.getOutputFormat()==="text")this.notes.push(`[Mod ${note.plugin}] ${stripAnsiAndControl(note.text)}`);else this.pendingLogs.push(note)},"run");return turn.ended=this.queueTurnEvent(turn,run,true)}queueTurnEvent(turn,run,isEnd=false){const task=this.toolQueue.then(async()=>{if(this.closing&&!isEnd||turn.sessionId!==this.sessionId||!this.allowed()||!this.active())return;try{await run(isEnd?this.endLifetime.signal:this.lifetime.signal)}finally{this.flushLogs()}}).catch(error=>logger.debug(`Mod turn event: ${String(error)}`));this.toolQueue=task;return task}abortTurn(turnId){const turn=this.turn;if(!turn)throw new Error(`$.turn.abort: no turn is running (asked for ${turnId})`);if(turn.id!==turnId)throw new Error(`$.turn.abort: ${turnId} is not the running turn (${turn.id}); a hook ends the turn turn.start told it about`);if(turn.aborting)throw new Error(`$.turn.abort: ${turnId} is already ending`);turn.aborting=true;let cancelled=false;try{cancelled=turn.abort()}finally{turn.aborting=cancelled}if(!cancelled)throw new Error(`$.turn.abort: ${turnId} is already ending`);logger.debug(`$.turn.abort: cancelled turn ${turnId}`)}flushLogs(){this.logsReady=true;for(const entry of this.pendingLogs.splice(0)){logger.debug(`[${entry.plugin}] ${entry.text}`);if(entry.to==="debug")continue;const text=this.terminal?sanitizeTerminalText(stripUnsafeCharacters(entry.text)):stripAnsiAndControl(entry.text);if("surface"in this.output){const{isTurnNote,...log}=entry;this.output.log({...log,text:isTurnNote?text:cpSlice(text,0,2e3)},entry.plugin,entry.sessionId)}else if(this.config.getOutputFormat()==="text"){process.stderr.write(`[Mod ${entry.plugin}] ${text}
|
|
4
4
|
`)}else{this.output.emitSystemMessage("ui_log",{plugin:entry.plugin,text})}}}async flushOutput(){if(this.notes.length&&!this.terminal)await flushOutput(process.stdout,AbortSignal.timeout(1500));for(const note of this.notes.splice(0))process.stderr.write(`${note}
|
|
5
5
|
`);await this.flushStreams()}async flushStreams(){if(this.terminal)return;const signal=AbortSignal.timeout(1500);await Promise.allSettled([flushOutput(process.stdout,signal),flushOutput(process.stderr,signal)])}capture(){this.observe();if(this.startedAt!==void 0)return this.startedAt;const resumed=this.config.getResumedSessionData()?.conversation;const first=resumed?.sessionId===this.sessionId?Date.parse(resumed.startTime):NaN;return this.startedAt=Number.isFinite(first)?first:this.adoptedAt}facts(){return runOutsideAgentContext(()=>this.readFacts())}readFacts(){const startedAt=this.capture();const{tokens,window}=this.context;return{id:this.sessionId,cwd:this.config.getTargetDir(),root:this.config.getProjectRoot(),model:this.config.getModel(),turns:this.recorder?.getUserTurnCount()??0,usage:{startedAt,context:{tokens,window,...window>0?{percent:Math.min(100,Math.round(tokens/window*100))}:{}},rateLimits:[]}}}active(){const extensions=this.config.getExtensions();return this.mods.every(mod=>extensions.some(extension=>extension.id===mod.id&&extension.isActive))}async end(reason){if(!this.allowed()||!this.active())return;try{await this.runtime?.end(this.sessionId,reason,AbortSignal.timeout(MOD_END_TIMEOUT_MS))}catch(error){logger.warn(`Mod session.end: ${String(error)}`)}}close(){this.closing??=(async()=>{this.unregisterCleanup();uiTelemetryService.off("update",this.observe);clearTimeout(this.band.settle);clearTimeout(this.band.wait);if(this.turn)void this.completeTurn(this.turn,"aborted");const endBudget=setTimeout(()=>this.endLifetime.abort(),MOD_END_TIMEOUT_MS);this.lifetime.abort();this.invalidateTools();await this.initialization?.catch(()=>{});try{await this.toolQueue;clearTimeout(endBudget);await this.end("other")}finally{clearTimeout(endBudget);this.endLifetime.abort();this.lifetime.abort();await this.runtime?.dispose();await this.flushStreams()}})();return this.closing}};function tokenCount(value){return typeof value==="number"&&Number.isFinite(value)&&value>=0?Math.floor(value):0}__name(tokenCount,"tokenCount");function addTurnUsage(usage,metadata,authType){if(!metadata)return usage;const prompt=tokenCount(metadata.promptTokenCount);const read=tokenCount(metadata.cachedContentTokenCount);const written=tokenCount(getGenAiUsageProvenance(metadata)?.cacheCreationInputTokens);const output=outputTokenCount({input:prompt,output:tokenCount(metadata.candidatesTokenCount),thoughts:tokenCount(metadata.thoughtsTokenCount),total:tokenCount(metadata.totalTokenCount)},authType);return{input_tokens:(usage?.input_tokens??0)+Math.max(0,prompt-read-written),output_tokens:(usage?.output_tokens??0)+output,cache_read_input_tokens:(usage?.cache_read_input_tokens??0)+read,cache_creation_input_tokens:(usage?.cache_creation_input_tokens??0)+written}}__name(addTurnUsage,"addTurnUsage");function fitTurnText(text){const fitted=projectJsonStringToByteBudget(text,MOD_MAX_BYTES/2,"\n[... truncated for Mods ...]\n");return{text:fitted,truncated:fitted!==text}}__name(fitTurnText,"fitTurnText");var sessions=new WeakMap;function isModRecoveryCommand(command){return command?.kind==="built-in"&&(command.name==="help"||command.name==="quit")}__name(isModRecoveryCommand,"isModRecoveryCommand");function createInteractiveModSession(config,settings){if(!settings.merged.experimental?.mods||!config.isInteractive())return;let session=sessions.get(config);if(!session){session=new InteractiveModSession(config,settings);sessions.set(config,session)}return session}__name(createInteractiveModSession,"createInteractiveModSession");function getInteractiveModSession(config){return config?sessions.get(config):void 0}__name(getInteractiveModSession,"getInteractiveModSession");var InteractiveModSession=class{constructor(config,settings){this.config=config;this.startup.catch(()=>{});this.session=ModSession.create(config,settings,{surface:"terminal",presentation:__name(()=>this.presentation,"presentation"),sites:__name(()=>this.sites,"sites"),draw:__name((tree,owner)=>{const band=tree.type==="engine"?void 0:{tree,owner,revision:++this.revision};if(!band&&!this.band)return;this.band=band;for(const listener of this.bandListeners)listener()},"draw"),log:__name((entry,plugin,sessionId)=>this.emit(`[Mod ${sanitizeTerminalLine(plugin)}] ${entry.text}`,sessionId),"log")});this.unregisterCleanup=registerCleanup(()=>{this.unregisterCleanup=()=>{};return this.close()})}static{__name(this,"InteractiveModSession")}session;lifetime=new AbortController;resolveStartup;rejectStartup;startup=new Promise((resolve,reject)=>{this.resolveStartup=resolve;this.rejectStartup=reject});initialization;closing;listener;logs=[];presentation={isFullscreen:false,columns:80};sites=[];band;revision=0;bandListeners=new Set;unregisterCleanup;initialize(sites=[]){if(!this.initialization)this.sites=sites;this.initialization??=this.session.initialize(this.lifetime.signal).then(()=>{this.session.flushLogs();this.resolveStartup()},error=>{this.emit(`Mods failed to initialize: ${sanitizeTerminalLine(String(error)).slice(0,2e3)}`,this.config.getSessionId());this.rejectStartup(error);throw error});return this.initialization}get ready(){return this.startup}failStartup(error){if(this.initialization)return;this.initialization=this.startup;this.rejectStartup(error)}async loadCommands(signal){await this.startup;signal.throwIfAborted();return this.session.loadCommands(this.lifetime.signal)}setPresentation(presentation){this.presentation={...presentation}}setRenderInput(input){if(!this.closing)this.session.setRenderInput(input)}subscribeBand=__name(listener=>{this.bandListeners.add(listener);return()=>this.bandListeners.delete(listener)},"subscribeBand");getBand=__name(()=>this.band,"getBand");subscribe(listener){this.listener=listener;for(const entry of this.logs.splice(0))this.emit(entry.text,entry.sessionId);return()=>{if(this.listener===listener)this.listener=void 0}}emit(text,sessionId){if(this.closing||sessionId!==this.config.getSessionId())return;if(this.listener)this.listener(text);else{if(this.logs.length===100)this.logs.shift();this.logs.push({text,sessionId})}}captureToolSignal(){return AbortSignal.any([this.lifetime.signal,this.session.captureToolSignal()])}restoreTools(){return this.session.restoreTools()}invalidateTools(){this.session.invalidateTools()}toolCall(){return this.session.toolCall(()=>{})}syncSession(reason){return this.session.syncSession(reason)}startTurn(text,signal,abort,promptId){return this.closing?void 0:this.session.startTurn(text,signal,abort,promptId)}close(){this.closing??=(async()=>{this.unregisterCleanup();this.lifetime.abort();this.rejectStartup(new Error("Interactive Mod session is closed."));try{await this.session.close()}finally{this.listener=void 0;this.logs.length=0;this.band=void 0;for(const listener of this.bandListeners)listener();if(sessions.get(this.config)===this)sessions.delete(this.config)}})();return this.closing}};export{ModSession,isModRecoveryCommand,createInteractiveModSession,getInteractiveModSession,InteractiveModSession};
|
|
6
6
|
/**
|