@hostclubeos/miraos 0.0.6-beta → 0.0.8-beta
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/chunks/{MaxSizedBox-CBUPHLMW.js → MaxSizedBox-YR2SA5XW.js} +1 -1
- package/chunks/{StandaloneSessionPicker-EXZJQKTK.js → StandaloneSessionPicker-VEXSGLU4.js} +1 -1
- package/chunks/{acp-subagent-executor-BMIXP52W.js → acp-subagent-executor-ATOLWCVC.js} +1 -1
- package/chunks/{acpAgent-OGBFWA5R.js → acpAgent-DN46FTZ2.js} +3 -3
- package/chunks/{advisor-5RUG3VFZ.js → advisor-6MI5JQGC.js} +1 -1
- package/chunks/{agent-SGQ7AEZI.js → agent-6HPQ4XCT.js} +1 -1
- package/chunks/{agent-headless-ZGCZ2DA7.js → agent-headless-KXAJBOPG.js} +1 -1
- package/chunks/{agent-host-client-HY5GPSHM.js → agent-host-client-NOZRE2ZR.js} +1 -1
- package/chunks/{agent-host-connections-KGTBS37X.js → agent-host-connections-6FOSHEWD.js} +1 -1
- package/chunks/{autofix-pr-E62FC67X.js → autofix-pr-IMJA2KZF.js} +1 -1
- package/chunks/{batch-OUC6FGCQ.js → batch-L5VJ4XGP.js} +1 -1
- package/chunks/{bridge-FLEIBB5V.js → bridge-CCRTJSIM.js} +1 -1
- package/chunks/{channel-settings-store-QG6HREVH.js → channel-settings-store-SB7BP6XT.js} +1 -1
- package/chunks/{chunk-GPI53DWB.js → chunk-2DPE27WB.js} +1 -1
- package/chunks/{chunk-JJDF5FHA.js → chunk-32DLSPV5.js} +1 -1
- package/chunks/{chunk-2PB6TEZU.js → chunk-3NA5O4QO.js} +1 -1
- package/chunks/{chunk-RBA3TP7L.js → chunk-3VKLOQ2P.js} +1 -1
- package/chunks/{chunk-3KFLO5W3.js → chunk-4C5BOFDC.js} +1 -1
- package/chunks/{chunk-TFITRCIC.js → chunk-4RRQ7CPF.js} +1 -1
- package/chunks/{chunk-YN6WXB6B.js → chunk-5AJKMBPM.js} +1 -1
- package/chunks/{chunk-SCHCTQCG.js → chunk-5BWVS5D3.js} +1 -1
- package/chunks/{chunk-Y3BCVTFB.js → chunk-5SX4UPMN.js} +1 -1
- package/chunks/{chunk-FK5L2WVV.js → chunk-5YULNQF3.js} +1 -1
- package/chunks/{chunk-T3A53XMM.js → chunk-66N3SLXJ.js} +1 -1
- package/chunks/{chunk-4WYKHP7Q.js → chunk-6AAVML2M.js} +1 -1
- package/chunks/{chunk-HHSHBOT7.js → chunk-6STDVRH5.js} +2 -2
- package/chunks/{chunk-TI7J4HX2.js → chunk-6TNX3S5H.js} +2 -2
- package/chunks/{chunk-ZOWMHZWO.js → chunk-77GGGTWS.js} +1 -1
- package/chunks/{chunk-KNW2OD46.js → chunk-7DJYSBNJ.js} +1 -1
- package/chunks/{chunk-MYS5NQXO.js → chunk-7EEWU6XO.js} +1 -1
- package/chunks/{chunk-VJUTDS6C.js → chunk-7GU7HKIT.js} +1 -1
- package/chunks/{chunk-UWMLSAQY.js → chunk-7HO5DQ6V.js} +1 -1
- package/chunks/{chunk-SHKSVOTG.js → chunk-7L4MR4QM.js} +1 -1
- package/chunks/{chunk-RWFOQXPU.js → chunk-7Q6RNE77.js} +1 -1
- package/chunks/{chunk-FC7SJIAS.js → chunk-AHV4IMUX.js} +1 -1
- package/chunks/{chunk-2QYFSBJY.js → chunk-ARILWFTZ.js} +1 -1
- package/chunks/{chunk-7JT2V4AW.js → chunk-BWFZEDYG.js} +1 -1
- package/chunks/chunk-BWLMXGA2.js +13 -0
- package/chunks/{chunk-ORVQPZMQ.js → chunk-C3ZJUOTJ.js} +1 -1
- package/chunks/{chunk-WJLHLFIR.js → chunk-CEVKKM22.js} +1 -1
- package/chunks/{chunk-K7KY7FIB.js → chunk-CJLKKIUW.js} +1 -1
- package/chunks/{chunk-HASJX2YS.js → chunk-CLLQQMTU.js} +1 -1
- package/chunks/{chunk-7F5IYTVE.js → chunk-CNGBG3X5.js} +1 -1
- package/chunks/{chunk-RNPVWQ3V.js → chunk-CNZS2RPX.js} +1 -1
- package/chunks/{chunk-WC72OWF2.js → chunk-D4WMUCSK.js} +2 -2
- package/chunks/{chunk-W2ZVZ6LS.js → chunk-DNCXESHL.js} +1 -1
- package/chunks/{chunk-HSN5QUS7.js → chunk-DNXQKR5E.js} +1 -1
- package/chunks/{chunk-H65ZVST6.js → chunk-DTNW2CM3.js} +1 -1
- package/chunks/{chunk-BB2C4HKQ.js → chunk-DTRSC73M.js} +3 -3
- package/chunks/{chunk-2VW4HXVF.js → chunk-E743PFSX.js} +1 -1
- package/chunks/{chunk-P5543CFV.js → chunk-EHM4KL2U.js} +1 -1
- package/chunks/{chunk-PQOQONLN.js → chunk-FC5IAX56.js} +1 -1
- package/chunks/{chunk-3MBYQYPC.js → chunk-G3COGFSZ.js} +1 -1
- package/chunks/{chunk-5JKJSIIP.js → chunk-G4OSEVOV.js} +2 -2
- package/chunks/{chunk-SOCXRMZM.js → chunk-G7D42XGP.js} +2 -2
- package/chunks/{chunk-IF3SWUYT.js → chunk-GBEQD55S.js} +1 -1
- package/chunks/{chunk-EW3EVEYN.js → chunk-GM6YF6IS.js} +1 -1
- package/chunks/{chunk-UOYXBAN7.js → chunk-GS4FZF6I.js} +1 -1
- package/chunks/{chunk-2ZWVSKPK.js → chunk-HCCONFJY.js} +1 -1
- package/chunks/{chunk-GY4ID3EB.js → chunk-HCKF74X7.js} +1 -1
- package/chunks/{chunk-6RDYPRV6.js → chunk-IJH5HZTB.js} +1 -1
- package/chunks/{chunk-3GA3NTAV.js → chunk-IJIQDCNJ.js} +5 -5
- package/chunks/{chunk-TLZM3DMY.js → chunk-IK5TB2CB.js} +1 -1
- package/chunks/{chunk-RGVXNWZA.js → chunk-IWIGJDPL.js} +1 -1
- package/chunks/{chunk-VBJV7T47.js → chunk-JCWNB45W.js} +1 -1
- package/chunks/{chunk-GTQULDIL.js → chunk-JHGMLUAL.js} +1 -1
- package/chunks/{chunk-23543L6E.js → chunk-JRIVHFCG.js} +1 -1
- package/chunks/{chunk-34YXJ3CX.js → chunk-JT5EN5MI.js} +1 -1
- package/chunks/{chunk-JDHMSERR.js → chunk-K2PGOAJP.js} +1 -1
- package/chunks/{chunk-O6Z3KO6R.js → chunk-K3RWL2YH.js} +1 -1
- package/chunks/{chunk-7W5DOBKY.js → chunk-KZZ5ZQHX.js} +1 -1
- package/chunks/{chunk-HMID4D72.js → chunk-LRXYXGMT.js} +1 -1
- package/chunks/{chunk-YVN32EUM.js → chunk-LTXZHHNK.js} +1 -1
- package/chunks/{chunk-TU5QHOJC.js → chunk-M3IQE5G4.js} +1 -1
- package/chunks/{chunk-RRMTSVGU.js → chunk-MCHMWRNO.js} +1 -1
- package/chunks/{chunk-SHLTP6ZB.js → chunk-MCY3IS2E.js} +1 -1
- package/chunks/{chunk-VGPV5AVJ.js → chunk-MOXZO5PM.js} +1 -1
- package/chunks/{chunk-TWJ4XBED.js → chunk-MV7LX23I.js} +1 -1
- package/chunks/{chunk-66DZADDA.js → chunk-MXFS555I.js} +1 -1
- package/chunks/{chunk-USR2Y7B3.js → chunk-NNYAXFFN.js} +1 -1
- package/chunks/{chunk-NGH27AWP.js → chunk-NUDHRTIM.js} +1 -1
- package/chunks/{chunk-JRPR5IME.js → chunk-NYGJ53Y7.js} +1 -1
- package/chunks/chunk-OHOG4HSN.js +31 -0
- package/chunks/{chunk-JQOLNQQN.js → chunk-OPFBBIAQ.js} +1 -1
- package/chunks/{chunk-KYK53GFP.js → chunk-OXG4BLFF.js} +1 -1
- package/chunks/{chunk-GLQWA4W2.js → chunk-PGKVSOWW.js} +1 -1
- package/chunks/{chunk-PFKTTUGS.js → chunk-POMEWCFJ.js} +6 -6
- package/chunks/{chunk-YVORE4W4.js → chunk-Q4NEZZ6L.js} +1 -1
- package/chunks/{chunk-Z4JY3HGO.js → chunk-QCSGHQ2P.js} +1 -1
- package/chunks/{chunk-VF2UWWI2.js → chunk-QWNTORRT.js} +1 -1
- package/chunks/{chunk-3GJ56V2J.js → chunk-QZNCYZ7H.js} +1 -1
- package/chunks/{chunk-T5PDEAU5.js → chunk-S5NTCBEI.js} +1 -1
- package/chunks/{chunk-AIAYQAPA.js → chunk-SK5C26Y6.js} +1 -1
- package/chunks/{chunk-ATVRF62A.js → chunk-SMO4PEHK.js} +1 -1
- package/chunks/{chunk-AE6E2YKY.js → chunk-SPCIIUIG.js} +1 -1
- package/chunks/{chunk-CUY6CVSL.js → chunk-SVNSF5ZH.js} +1 -1
- package/chunks/{chunk-K7VOBDFT.js → chunk-UC455ZS7.js} +1 -1
- package/chunks/{chunk-J773THNP.js → chunk-UZAFPEVN.js} +1 -1
- package/chunks/{chunk-PVHBBTAU.js → chunk-V3ASW57P.js} +1 -1
- package/chunks/{chunk-4MGTY3CJ.js → chunk-VAFRD2H4.js} +1 -1
- package/chunks/{chunk-F2XELUO3.js → chunk-VOCM2M4K.js} +1 -1
- package/chunks/{chunk-W6IOHGWW.js → chunk-VOIC5ZW2.js} +1 -1
- package/chunks/{chunk-V5Z6OEKJ.js → chunk-W4M6JXZB.js} +1 -1
- package/chunks/{chunk-4KIFAVR2.js → chunk-WJXADORN.js} +1 -1
- package/chunks/{chunk-P42MFWO2.js → chunk-WN6Z3J27.js} +1 -1
- package/chunks/{chunk-FS67DOZQ.js → chunk-WOMJLK3E.js} +1 -1
- package/chunks/{chunk-NVD63O5H.js → chunk-WSXRO2YB.js} +1 -1
- package/chunks/{chunk-IC2WDA6V.js → chunk-WUZ53TKN.js} +1 -1
- package/chunks/{chunk-724YPZRX.js → chunk-WW43VZ6O.js} +1 -1
- package/chunks/{chunk-PFECH6U6.js → chunk-WZAUO3LV.js} +1 -1
- package/chunks/{chunk-EF3HUB7S.js → chunk-XGPGIMZK.js} +1 -1
- package/chunks/{chunk-PGKFDR73.js → chunk-XJKDC7OE.js} +1 -1
- package/chunks/{chunk-HZ4L4MDM.js → chunk-XNP5JXCS.js} +1 -1
- package/chunks/{chunk-4346FNTB.js → chunk-YELFN6AG.js} +1 -1
- package/chunks/{chunk-WZTO3EYG.js → chunk-YFXKRGHT.js} +1 -1
- package/chunks/{chunk-E6LRCLLE.js → chunk-YOBM4ZFW.js} +2 -2
- package/chunks/{chunk-7VP4KALB.js → chunk-ZJOVJLIH.js} +1 -1
- package/chunks/{chunk-KK6SQPYG.js → chunk-ZQZK267X.js} +1 -1
- package/chunks/{codex-subagent-executor-UCDGQFTR.js → codex-subagent-executor-TPO62HU5.js} +1 -1
- package/chunks/{config-utils-Z6F4DVLG.js → config-utils-6GWIYBUK.js} +1 -1
- package/chunks/{contextCommand-HMVZT56Y.js → contextCommand-WWVGDTOL.js} +1 -1
- package/chunks/{core-runtime-AV7CJXOL.js → core-runtime-ASQR33TV.js} +1 -1
- package/chunks/{create-sub-session-NNKVHZKT.js → create-sub-session-XY2FXSPE.js} +1 -1
- package/chunks/{cron-create-HWZDFVPA.js → cron-create-HY3TLNV2.js} +1 -1
- package/chunks/{daemon-git-worktree-guard-Q3C45X7T.js → daemon-git-worktree-guard-ILW3NJJC.js} +1 -1
- package/chunks/{daemon-status-provider-FCQ4YYAY.js → daemon-status-provider-JVOGEKWY.js} +1 -1
- package/chunks/{daemon-trust-policy-6D4KJANB.js → daemon-trust-policy-XXRBG4JE.js} +1 -1
- package/chunks/{daemon-trust-policy-monitor-BZ46W4IA.js → daemon-trust-policy-monitor-UL73ADOZ.js} +1 -1
- package/chunks/{deferred-core-runtime-YC5XIWEI.js → deferred-core-runtime-PT747R7S.js} +1 -1
- package/chunks/{edit-LOWDEKPX.js → edit-4PJ3NPFA.js} +1 -1
- package/chunks/{enterPlanMode-NGSATDRH.js → enterPlanMode-KQ62QN7S.js} +1 -1
- package/chunks/{environment-CVIB5DW4.js → environment-H4HADXGA.js} +1 -1
- package/chunks/{errors-USKSVZFO.js → errors-OSD4ZZGR.js} +1 -1
- package/chunks/{execution-tool-QSJLRU5N.js → execution-tool-PHHGLKWC.js} +1 -1
- package/chunks/{execution-worker-TQEIC4AJ.js → execution-worker-MH3CV66T.js} +1 -1
- package/chunks/{exitPlanMode-AW2HOTIK.js → exitPlanMode-OU5YP4XN.js} +1 -1
- package/chunks/{fast-path-ZBD7IYQM.js → fast-path-WKOMHBWN.js} +1 -1
- package/chunks/{glob-7U6FQSWZ.js → glob-FYCOEQPM.js} +1 -1
- package/chunks/{goal-tools-5ZB6GPCJ.js → goal-tools-T27GSDNM.js} +1 -1
- package/chunks/{handleAutoUpdate-MLUFTWFP.js → handleAutoUpdate-XXCPJLKO.js} +1 -1
- package/chunks/{i18n-QAPQLOC3.js → i18n-3B2PRJM2.js} +1 -1
- package/chunks/{initializer-B27IZ7K4.js → initializer-HSFVDRTR.js} +1 -1
- package/chunks/{installationInfo-SAMHABWV.js → installationInfo-SJJ2DYZ6.js} +1 -1
- package/chunks/{interactive-mod-session-7LQ5CYUR.js → interactive-mod-session-BWY2JRSQ.js} +1 -1
- package/chunks/{list-TDMJQDQO.js → list-TGCI3MBM.js} +1 -1
- package/chunks/{llm-DQNQEAFW.js → llm-FYR73GKD.js} +4 -4
- package/chunks/{loadedSettingsAdapter-ZQK5KMEW.js → loadedSettingsAdapter-DUDCINQL.js} +1 -1
- package/chunks/{local-ZRC4XZCJ.js → local-7PEOBJKE.js} +1 -1
- package/chunks/{local-execution-environment-WJVCE26F.js → local-execution-environment-Q4OOA7BL.js} +1 -1
- package/chunks/{loggingContentGenerator-ALSG42YA.js → loggingContentGenerator-VVESQOIQ.js} +1 -1
- package/chunks/{loop-wakeup-LFU4LDJM.js → loop-wakeup-M2XLAAKZ.js} +1 -1
- package/chunks/{manage-memory-FBL6CHX2.js → manage-memory-FRVWHM2C.js} +1 -1
- package/chunks/{managed-execution-engine-FX7FDAWW.js → managed-execution-engine-AVIM6AQU.js} +1 -1
- package/chunks/{managed-local-serve-B2KOLPB5.js → managed-local-serve-GIXHGFIU.js} +1 -1
- package/chunks/{managed-npm-update-2MKV7UOI.js → managed-npm-update-3QSXGSHW.js} +1 -1
- package/chunks/{managed-runtime-attestation-worker-DBAHM5MN.js → managed-runtime-attestation-worker-ML4TCRAW.js} +1 -1
- package/chunks/{managed-runtime-bootstrap-MREL5UC2.js → managed-runtime-bootstrap-JWJFGLBM.js} +1 -1
- package/chunks/{managed-runtime-session-worker-YN4KML7A.js → managed-runtime-session-worker-4ISKROGZ.js} +1 -1
- package/chunks/{managed-runtime-ssh-worker-GUKAZFAJ.js → managed-runtime-ssh-worker-C44V2CPM.js} +1 -1
- package/chunks/{managed-session-authority-MFEINLXC.js → managed-session-authority-UJ3FSKMD.js} +1 -1
- package/chunks/{mcp-TS5PX5FY.js → mcp-BWCLHHZ6.js} +1 -1
- package/chunks/{memory-ZYPCFYPF.js → memory-5XQ2JVNS.js} +1 -1
- package/chunks/{model-call-collection-TNBMD3YL.js → model-call-collection-DXK2SIDR.js} +1 -1
- package/chunks/{model-configuration-6KTQQTMO.js → model-configuration-6OLZS4C3.js} +1 -1
- package/chunks/{modelConfigUtils-LCZZ3EQU.js → modelConfigUtils-5S5PC2RR.js} +1 -1
- package/chunks/{monitor-KCCNIKLE.js → monitor-6GKCWWUI.js} +1 -1
- package/chunks/{nonInteractiveCli-JG6PKBAD.js → nonInteractiveCli-ROHAB2H7.js} +1 -1
- package/chunks/{nonInteractiveToolExecutor-R5CTTWKD.js → nonInteractiveToolExecutor-OWCCSC5Y.js} +1 -1
- package/chunks/{notebook-edit-KIWE2XOA.js → notebook-edit-WNRQ3QJZ.js} +1 -1
- package/chunks/{omni-IFTMWBMU.js → omni-DJ5RGNKA.js} +1 -1
- package/chunks/{openaiContentGenerator-XP3VPU6C.js → openaiContentGenerator-237NVB63.js} +1 -1
- package/chunks/{openaiResponsesContentGenerator-ZJ6C22EA.js → openaiResponsesContentGenerator-J33TCZKQ.js} +1 -1
- package/chunks/{pidfile-42P24JIA.js → pidfile-F7IYTFLX.js} +1 -1
- package/chunks/{processUtils-I2XOO5U2.js → processUtils-C6CSXITS.js} +1 -1
- package/chunks/{prompt-terminal-ledger-7EW46VQ4.js → prompt-terminal-ledger-ZGYWPFJF.js} +1 -1
- package/chunks/{reactive-degrade-O4JO7MOX.js → reactive-degrade-QKXPZQ3W.js} +1 -1
- package/chunks/{read-file-VGC4O7F2.js → read-file-GSNUMHRE.js} +1 -1
- package/chunks/{resumeHistoryUtils-QMVIHQRW.js → resumeHistoryUtils-4GUCHQGU.js} +1 -1
- package/chunks/{review-N3VFZQMI.js → review-M2QGZFIO.js} +1 -1
- package/chunks/{ripGrep-JY4PZABK.js → ripGrep-X4JTJZC6.js} +1 -1
- package/chunks/{run-qwen-serve-4MZRQFXK.js → run-qwen-serve-4WW37RL2.js} +1 -1
- package/chunks/{runtime-OL7B72CH.js → runtime-EFHJ6REE.js} +1 -1
- package/chunks/{sandboxConfig-EJTMWZHD.js → sandboxConfig-5XMIRDS4.js} +1 -1
- package/chunks/{scheduled-tasks-XQSZWZXG.js → scheduled-tasks-ZCYM5YQJ.js} +1 -1
- package/chunks/{scheduler-3TIRZEVB.js → scheduler-5UAKCD5Z.js} +1 -1
- package/chunks/{search-memory-P5KOTUVV.js → search-memory-KKPYK33Q.js} +1 -1
- package/chunks/{send-message-KFSKFXLX.js → send-message-KOZRSWXO.js} +1 -1
- package/chunks/{serve-EQN6QAXF.js → serve-5HSHEBMT.js} +1 -1
- package/chunks/{server-CCEHAI25.js → server-MC6KHP3G.js} +3 -3
- package/chunks/{session-HNUJSV5A.js → session-Z5HFG4IQ.js} +1 -1
- package/chunks/{session-attachments-root-O3YQ7HWD.js → session-attachments-root-K2E5ETD4.js} +1 -1
- package/chunks/{session-execution-engine-selector-LZBHS3UO.js → session-execution-engine-selector-NZA6CAJB.js} +1 -1
- package/chunks/{session-pr-refresh-L5Z5WCXS.js → session-pr-refresh-OYJ56U3L.js} +1 -1
- package/chunks/{sessionService-MMPZUN5X.js → sessionService-BC56MX3G.js} +1 -1
- package/chunks/{settings-7PYHXPN4.js → settings-OHB77GXH.js} +1 -1
- package/chunks/{shell-E6QLKRVU.js → shell-VKSH7JVL.js} +1 -1
- package/chunks/{skill-55IZUUM5.js → skill-HQ4C2C3X.js} +1 -1
- package/chunks/{skill-settings-A2M5BPH7.js → skill-settings-6WPQFE3V.js} +1 -1
- package/chunks/{spawnChannel-KWU26CB7.js → spawnChannel-MXKVLS24.js} +1 -1
- package/chunks/{standalone-update-32WYZ3BJ.js → standalone-update-NZP3OAZZ.js} +1 -1
- package/chunks/{start-opentui-ui-6MCAEWAW.js → start-opentui-ui-25YQQD3O.js} +1 -1
- package/chunks/{startInteractiveUI-657JWOTK.js → startInteractiveUI-DWQJNIIV.js} +2 -2
- package/chunks/{team-create-ARICYIQB.js → team-create-RSD7IADX.js} +1 -1
- package/chunks/{team-plan-approval-JPRE6Q3R.js → team-plan-approval-XAOKZ6BR.js} +1 -1
- package/chunks/{terminal-image-renderer-HVIZ2VNE.js → terminal-image-renderer-P5AGEOYS.js} +1 -1
- package/chunks/{theme-manager-UEPLIBUP.js → theme-manager-YBKJYPVQ.js} +1 -1
- package/chunks/{tool-call-EFJKXI3Z.js → tool-call-HJCSPR6N.js} +1 -1
- package/chunks/{tool-result-media-LMIYNXSD.js → tool-result-media-SPWVV3OS.js} +1 -1
- package/chunks/{tool-search-D7HQTRQG.js → tool-search-YWCOODLL.js} +1 -1
- package/chunks/{total-session-admission-67QMR44O.js → total-session-admission-HKACVEI2.js} +1 -1
- package/chunks/{trustedFolders-HARYVS3F.js → trustedFolders-BXLZULWO.js} +1 -1
- package/chunks/{update-relaunch-NVNPOK5J.js → update-relaunch-CBJVLG6S.js} +1 -1
- package/chunks/{updateCheck-7NMXUCTN.js → updateCheck-2J6RY3L3.js} +1 -1
- package/chunks/{upload-config-W2SICJ32.js → upload-config-EN5XYA3V.js} +1 -1
- package/chunks/{useAutoAcceptIndicator-ELMIP4TJ.js → useAutoAcceptIndicator-LF7VIUER.js} +1 -1
- package/chunks/{validateNonInterActiveAuth-CP5WFNAE.js → validateNonInterActiveAuth-63TR5JOG.js} +1 -1
- package/chunks/{version-SIM74L5K.js → version-F22SKNME.js} +1 -1
- package/chunks/{web-fetch-537RS6IX.js → web-fetch-ULH7TOLR.js} +1 -1
- package/chunks/{web-search-O27MYFSW.js → web-search-C3ORWAWR.js} +1 -1
- package/chunks/{workflow-6QF4RMYM.js → workflow-4ATPGZ5N.js} +1 -1
- package/chunks/{workflow-ancestor-trust-CABLU3VV.js → workflow-ancestor-trust-AJ27EBZD.js} +1 -1
- package/chunks/{workspace-agents-5WP3PY7W.js → workspace-agents-VLAJGYJF.js} +1 -1
- package/chunks/{workspace-providers-status-7G2EJJEO.js → workspace-providers-status-TFAXNJ6L.js} +1 -1
- package/chunks/{workspace-recovery-worker-ICCIDEWU.js → workspace-recovery-worker-GKYYJPXV.js} +1 -1
- package/chunks/{workspace-registration-store-WHXMNQQQ.js → workspace-registration-store-ANR3STGQ.js} +1 -1
- package/chunks/{workspace-registry-NXBODLYH.js → workspace-registry-OVHNLVBM.js} +1 -1
- package/chunks/{workspace-runtime-coordinator-CJXS273B.js → workspace-runtime-coordinator-IEN2G7JP.js} +1 -1
- package/chunks/{workspace-service-HUDE2RXN.js → workspace-service-NISFZTBE.js} +1 -1
- package/chunks/{workspace-skills-status-FJC6U62F.js → workspace-skills-status-QRF5ZXMT.js} +1 -1
- package/chunks/{workspace-trust-reconciler-ZIQ3A5ZB.js → workspace-trust-reconciler-X3XMX2GJ.js} +1 -1
- package/chunks/{write-file-652YGG7I.js → write-file-SF42KZAH.js} +1 -1
- package/chunks/{zoom-image-YEH4O74G.js → zoom-image-4UMB6G3P.js} +1 -1
- package/cli.js +2 -2
- package/execution-worker.js +1 -1
- package/package.json +2 -2
- package/chunks/chunk-56PVVXUG.js +0 -8
- package/chunks/chunk-AJ75BPTA.js +0 -31
|
@@ -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{ENGINE_NODE,MOD_END_TIMEOUT_MS,MOD_MAX_BYTES,ModBudget,adjustRenderTree,assertModDepth,invalidRenderText,record,validModelResult,validateRenderTree,validateResult}from"./chunk-XWYUQMLN.js";import{stableJson}from"./chunk-FIXDX63I.js";import{external_exports}from"./chunk-KZSUHQLD.js";import{openNoFollow}from"./chunk-PSKT6KWO.js";import{isZombie,readLocalBootId,readPidNamespaceId,readProcStartToken}from"./chunk-JB3XRNK7.js";import{buildModelIdContext,resolveModelId}from"./chunk-QTJPOTU5.js";import{resolveBundleDir}from"./chunk-4NPYOXJO.js";import{isQuotaExhaustedError,isQwenQuotaExceededError}from"./chunk-3MG44MZK.js";import{runOutsideAgentContext}from"./chunk-KP77CL5U.js";import{isInternalPromptId,uiTelemetryService}from"./chunk-MJEL7DIE.js";import{Mutex,Semaphore}from"./chunk-JEV36CS7.js";import{renameWithRetry}from"./chunk-2GF3E5MI.js";import{hasExplicitOutputLimit,tokenLimit}from"./chunk-EV2CXPMN.js";import{EVENT_API_RESPONSE}from"./chunk-JJAEIBSV.js";import{getGenAiUsageProvenance,outputTokenCount}from"./chunk-4DIWAQ5G.js";import{require_semver}from"./chunk-73G3MZQR.js";import{registerCleanup}from"./chunk-PFECH6U6.js";import{stripAnsiAndControl}from"./chunk-DBRQGEEI.js";import{ToolNames}from"./chunk-SBZFGYYS.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{getErrorStatus,isNodeError}from"./chunk-E7MYPQGV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();import{randomUUID as randomUUID2}from"node:crypto";import path4 from"node:path";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(external_exports.string(),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,queuePrompt,completeModel,store){this.log=log;this.facts=facts;this.resolveTool=resolveTool;this.surface=surface;this.abortTurn=abortTurn;this.renderHost=renderHost;this.queuePrompt=queuePrompt;this.completeModel=completeModel;this.store=store;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();root.models.get(id)?.abort();this.storeCalls.get(id)?.controller.abort()}}else if(reply.type==="model-complete")this.answerModel(reply,root);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==="prompt-queue")this.answerPromptQueue(reply,root.id);else if(reply.type==="store"){const remainingMs=reply.deadline-performance.now();if(remainingMs<=0)return;const controller=new AbortController;const signals=[root.storeAbort.signal,controller.signal];if(Number.isFinite(remainingMs))signals.push(AbortSignal.timeout(Math.ceil(remainingMs)));const task=this.answerStore(reply,root.id,AbortSignal.any(signals));this.storeCalls.set(reply.id,{controller,task});void task.finally(()=>this.storeCalls.delete(reply.id))}else if(reply.type==="invalidate"){if(reply.event!=="ui.render"||this.failure)return;if(this.early)this.early.add(reply.plugin);else if(Object.values(this.renders).some(names=>names.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&&!root.models.has(reply.operation))return;root.revision=reply.revision;root.idle=reply.operation===root.native&&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;storeCalls=new Map;storeReadSlots=new Semaphore(4);failure;pending;commands=[];tools=false;turns={start:false,complete:[]};prompts=[];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,prompts=false,queuePrompt,completeModel,store){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,queuePrompt,completeModel,store);try{const result=await runtime.request({type:"load",plugins,cwd,surface,version,sites:render?.sites??[],prompts,submits:queuePrompt!==void 0,models:completeModel!==void 0,stores:store!==void 0},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;const promptSubmit=record(result)?result["promptSubmit"]:void 0;if(!record(result)||typeof result["tools"]!=="boolean"||typeof result["turnStart"]!=="boolean"||!names(promptSubmit)||!names(turnComplete)||!record(renders)||Object.entries(renders).some(([site,plugins2])=>!(render?.sites??[]).includes(site)||!names(plugins2)))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.prompts=promptSubmit;runtime.renders=renders;const early=runtime.early;runtime.early=void 0;for(const plugin of early)if(Object.values(runtime.renders).some(plugins2=>plugins2.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 promptHooks(){return this.prompts}renderHooksFor(site){return this.renders[site]??[]}async render(input,signal){const answer=await this.request({type:"render",input},signal);let settled=answer;if(input.component==="AssistantMessage")settled=record(answer)?answer["tree"]:void 0;const hooks=this.renderHooksFor(input.component);const owner=hooks.length===1?hooks[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}}if(input.component==="AssistantMessage"){if(!record(settled)||settled["type"]!=="engine"||settled["ref"]!==0){note(`ui.render (${input.component}) answered a tree; this host draws only a rewrite of the row's props, so the row was left as it was`);return{tree:ENGINE_NODE,notes,props:input.props}}const props=record(answer)?answer["props"]:void 0;const text=record(props)?props["text"]:void 0;if(!record(props)||typeof text!=="string"||text!==input.props.text&&invalidRenderText(text)!==void 0||props["isFirstOfReply"]!==input.props.isFirstOfReply)return{tree:ENGINE_NODE,notes,props:input.props};return{tree:ENGINE_NODE,notes,props:{...input.props,text}}}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-E6QLKRVU.js")).ShellTool;break;case ToolNames.EDIT:builtin=await this.resolveTool(name2)instanceof(await import("./edit-LOWDEKPX.js")).EditTool;break;case ToolNames.WRITE_FILE:builtin=await this.resolveTool(name2)instanceof(await import("./write-file-652YGG7I.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 submitPrompt(input,signal){const result=await this.request({type:"prompt-submit",input},signal);if(record(result)&&(typeof result["drop"]==="string"?Object.keys(result).length===2&&typeof result["byHook"]==="boolean":typeof result["text"]==="string"&&Object.keys(result).every(key=>key==="text"||key==="context")&&(result["context"]===void 0||Array.isArray(result["context"])&&result["context"].every(item=>typeof item==="string"))))return result;throw new Error("Invalid Mod prompt.submit result.")}async completeTurn(input,signal){const result=await this.request({type:"turn-complete",input},signal);validateResult("turn.complete",result);return result.text}answerModel(reply,root){if(Atomics.load(this.cancelled,0)!==0||Atomics.load(reply.cancellation,0)!==0)return;const remainingMs=reply.deadline-performance.now();if(remainingMs<=0)return;const controller=new AbortController;const signal=Number.isFinite(remainingMs)?AbortSignal.any([controller.signal,AbortSignal.timeout(Math.ceil(remainingMs))]):controller.signal;root.models.set(reply.id,controller);const answer=__name(async()=>{try{if(!this.completeModel)throw new Error("this host runs no Mod model calls");const result=await this.completeModel(reply.input,signal);if(!validModelResult(result))throw new Error("the host answered with an invalid model result");return{type:"model-result",id:reply.id,result}}catch(caught){const error=(caught instanceof Error?caught.message:String(caught)).slice(0,4e3);return{type:"model-result",id:reply.id,error}}},"answer");void answer().then(request=>{root.models.delete(reply.id);if(this.root!==root)return;if(!signal.aborted){try{this.post(request,root.id)}catch(caught){this.post({type:"model-result",id:reply.id,error:caught instanceof Error?caught.message:String(caught)},root.id)}}root.refresh()})}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)}answerPromptQueue(reply,root){let refused;try{refused=this.queuePrompt?this.queuePrompt(reply.prompt):"this host does not run prompts a Mod submits"}catch(caught){refused=(caught instanceof Error?caught.message:String(caught)).slice(0,4e3)}this.post({type:"prompt-queue-result",id:reply.id,refused},root)}async answerStore(reply,root,signal){const{operation}=reply;let value;let error;try{signal.throwIfAborted();const store=this.store;if(!store)throw new Error("This host keeps no Mod store.");if(operation.method==="store.get"||operation.method==="store.keys"){value=await this.storeReadSlots.runExclusive(()=>{signal.throwIfAborted();return operation.method==="store.get"?store.get(operation.plugin,operation.key):store.keys(operation.plugin)})}else if(operation.method==="store.set")await store.set(operation.plugin,operation.key,operation.value,signal);else await store.delete(operation.plugin,operation.key,signal)}catch(caught){error=(caught instanceof Error?caught.message:String(caught)).slice(0,4e3)}if(signal.aborted)return;try{this.post({type:"store-result",id:reply.id,value,error},root)}catch(caught){this.post({type:"store-result",id:reply.id,error:(caught instanceof Error?caught.message:String(caught)).slice(0,4e3)},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),...[...this.storeCalls.values()].map(({task})=>task)])}fail(error){this.failure??=error;this.tool?.controller.abort();this.root?.storeAbort.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,models:new Map,storeAbort:new AbortController,refresh:__name(()=>{if(aborted||this.root!==root)return;const lending=root.idle!==void 0&&(request.type==="tool"&&root.idle===root.native&&!this.tool?.checks.size||root.models.has(root.idle))&&!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")};root.storeAbort.signal.addEventListener("abort",()=>this.storeReadSlots.cancel(),{once:true});this.root=root;const onAbort=__name(()=>{aborted=true;Atomics.store(this.cancelled,0,1);this.tool?.controller.abort();for(const model of root.models.values())model.abort();root.storeAbort.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;root.storeAbort.abort();for(const model of root.models.values())model.abort();root.models.clear();if(timer)clearTimeout(timer);if(cancelTimer)clearTimeout(cancelTimer);signal.removeEventListener("abort",onAbort);this.pending=void 0}}};init_esbuild_shims();import{createHash,createHmac,randomUUID}from"node:crypto";import{closeSync,constants,openSync,readFileSync,statfsSync,statSync}from"node:fs";import*as fs2 from"node:fs/promises";import{hostname}from"node:os";import*as path3 from"node:path";import{setTimeout as delay}from"node:timers/promises";var MOD_STORE_MAX_BYTES=4*1024*1024;var MAX_KEY_LIST_BYTES=MOD_MAX_BYTES-64;var LOCK_WAIT_MS=8e3;var PROC_SUPER_MAGIC=40864;var BOOT_ID_PATH="/proc/sys/kernel/random/boot_id";var lockHost=hostname();var pidNamespace=readPidNamespaceId();var bootId=process.platform==="linux"?readLocalBootId():null;var startPrefix=pidNamespace===null?null:readStartPrefix();var lockScope=scopeForBoot(bootId);var machineScope=bootId!==null&&pidNamespace!==null&&hasKernelBootId(bootId)?readMachineScope():null;var fileLocks=new Map;function scopeForBoot(id){return createHash("sha256").update(JSON.stringify([lockHost,pidNamespace,id])).digest("hex").slice(0,16)}__name(scopeForBoot,"scopeForBoot");function hasKernelBootId(expected){try{const fd=openSync(BOOT_ID_PATH,constants.O_RDONLY|constants.O_NONBLOCK);try{return statfsSync(`/proc/self/fd/${fd}`).type===PROC_SUPER_MAGIC&&readFileSync(fd,"utf8").trim()===expected}finally{closeSync(fd)}}catch{return false}}__name(hasKernelBootId,"hasKernelBootId");function readMachineScope(){try{const id=readFileSync("/etc/machine-id","utf8").trim();if(!/^[a-f0-9]{32}$/i.test(id)||/^0+$/.test(id))return null;return createHmac("sha256","Qwen-Code/ModStore/lock-host").update(Buffer.from(id,"hex")).digest("hex").slice(0,32)}catch{return null}}__name(readMachineScope,"readMachineScope");function hasLocalProcPids(){if(pidNamespace===null)return false;try{const status=readFileSync("/proc/self/status","utf8");return/^NStgid:[ \t]+(\d+)[ \t]*$/m.exec(status)?.[1]===String(process.pid)}catch{return false}}__name(hasLocalProcPids,"hasLocalProcPids");function readStartPrefix(){try{return`${statSync("/proc/self/ns/time").ino}~`}catch{return null}}__name(readStartPrefix,"readStartPrefix");function processStart(pid){if(startPrefix===null)return"-";const token=readProcStartToken(pid);return token===null?"-":`${startPrefix}${Buffer.from(token).toString("base64url")}`}__name(processStart,"processStart");function deadOwner(owner){const identity=/^(?<scope>[a-f0-9]{16})\.(?<pid>[1-9]\d{0,9})\.(?<start>(?:\d+~)?[\w-]+)\.[a-f0-9-]{36}(?:(?<kernel>\.k)?\.(?<machine>[a-f0-9]{32})\.(?<boot>[a-f0-9-]+))?$/.exec(owner)?.groups;if(!identity)return false;const{scope,pid:rawPid,start:recordedStart,kernel,machine,boot}=identity;if(scope!==lockScope){return kernel!==void 0&&machineScope!==null&&machine===machineScope&&boot!==void 0&&boot!==bootId&&scope===scopeForBoot(boot)}if(process.platform==="linux"&&(pidNamespace===null||bootId===null))return false;const pid=Number(rawPid);if(pid>2147483647)return false;try{process.kill(pid,0)}catch(error){return isNodeError(error)&&error.code==="ESRCH"}if(!hasLocalProcPids())return false;if(isZombie(pid))return true;if(startPrefix===null||!recordedStart.startsWith(startPrefix))return false;const start=processStart(pid);return start!=="-"&&recordedStart!==start}__name(deadOwner,"deadOwner");async function removeLock(lock,owner){if(owner)await fs2.rm(path3.join(lock,owner),{recursive:true,force:true});try{await fs2.rmdir(lock)}catch(error){if(!isNodeError(error)||!["ENOENT","ENOTEMPTY","EEXIST"].includes(error.code??""))throw error}}__name(removeLock,"removeLock");async function acquireLock(lock,signal){signal?.throwIfAborted();const nonce=randomUUID();const staging=`${lock}.${nonce}`;const recovery=machineScope&&bootId?`.k.${machineScope}.${bootId}`:"";const start=hasLocalProcPids()?processStart(process.pid):"-";const owner=`${lockScope}.${process.pid}.${start}.${nonce}${recovery}`;await fs2.mkdir(staging,{mode:448});let acquired=false;try{await fs2.mkdir(path3.join(staging,owner));const deadline=performance.now()+LOCK_WAIT_MS;do{signal?.throwIfAborted();try{await fs2.rename(staging,lock);acquired=true;return path3.join(lock,owner)}catch(error){if(!isNodeError(error)||!["ENOTEMPTY","EEXIST","EPERM","EACCES"].includes(error.code??""))throw error;const owners=await fs2.lstat(lock).then(stat=>{if(!stat.isDirectory())throw error;return fs2.readdir(lock)}).catch(cause=>{if(isNodeError(cause)&&cause.code==="ENOENT")return[];throw cause});if(owners.length===0)await removeLock(lock);else if(owners.length===1&&deadOwner(owners[0]))await removeLock(lock,owners[0])}await delay(50,void 0,{signal})}while(performance.now()<deadline);throw new Error(`Mod store: timed out waiting for ${lock}.`)}finally{if(!acquired)await fs2.rm(staging,{recursive:true,force:true}).catch(()=>{})}}__name(acquireLock,"acquireLock");function acquireLocalLock(mutex,signal){if(!signal)return mutex.acquire();signal.throwIfAborted();return new Promise((resolve,reject)=>{const abort=__name(()=>reject(signal.reason),"abort");signal.addEventListener("abort",abort,{once:true});void mutex.acquire().then(release=>{signal.removeEventListener("abort",abort);if(signal.aborted)release();else resolve(release)},error=>{signal.removeEventListener("abort",abort);reject(error)})})}__name(acquireLocalLock,"acquireLocalLock");var ModStore=class{constructor(dir){this.dir=dir}static{__name(this,"ModStore")}async get(plugin,key){return(await this.read(this.file(plugin))).get(key)}async keys(plugin){return[...(await this.read(this.file(plugin))).keys()]}async set(plugin,key,value,signal){await this.change(plugin,signal,entries=>{if(!entries.has(key)&&Buffer.byteLength(JSON.stringify([...entries.keys(),key]))>MAX_KEY_LIST_BYTES)throw new Error(`Mod store: the key list would be over ${MAX_KEY_LIST_BYTES} bytes of JSON.`);entries.set(key,value);return true})}async delete(plugin,key,signal){await this.change(plugin,signal,entries=>entries.delete(key))}file(plugin){const name2=plugin.toLowerCase();if(!/^[a-z0-9_.-]+$/.test(name2)||/^\.+$/.test(name2))throw new Error(`Mod store: no store for the plugin name "${plugin}".`);const stem=name2.length>128?`~${createHash("sha256").update(name2).digest("hex")}`:name2;return path3.join(this.dir,`${stem}.json`)}async read(file){let text;try{const handle=await openNoFollow(file,{nonBlocking:true}).catch(error=>{if(isNodeError(error)&&error.code==="ELOOP")return openNoFollow(file,{nonBlocking:true});throw error});try{if(!(await handle.stat()).isFile())throw new Error("The store is not a regular file.");text=await handle.readFile("utf8")}finally{await handle.close()}}catch(error){if(isNodeError(error)&&error.code==="ENOENT")return new Map;throw new Error(`Mod store: cannot read ${file}: ${error instanceof Error?error.message:String(error)}`)}let parsed;try{parsed=JSON.parse(text)}catch{parsed=void 0}const stored=parsed;if(!stored||stored.version!==1||!Array.isArray(stored.entries)||!stored.entries.every(entry=>Array.isArray(entry)&&entry.length===2&&typeof entry[0]==="string"))throw new Error(`Mod store: ${file} is not a store this version reads; it is left unchanged.`);return new Map(stored.entries)}async change(plugin,signal,apply){const file=this.file(plugin);let mutex=fileLocks.get(file);if(!mutex)fileLocks.set(file,mutex=new Mutex);const release=await acquireLocalLock(mutex,signal);try{signal?.throwIfAborted();await fs2.mkdir(this.dir,{recursive:true,mode:448});const lock=`${file}.lock`;const owner=await acquireLock(lock,signal);try{signal?.throwIfAborted();const entries=await this.read(file);if(!apply(entries))return;const stored={version:1,entries:[...entries]};const text=JSON.stringify(stored);if(Buffer.byteLength(text)>MOD_STORE_MAX_BYTES)throw new Error(`Mod store: the store would be over ${MOD_STORE_MAX_BYTES} bytes of JSON.`);const temporary=path3.join(owner,"store.json");await fs2.writeFile(temporary,text,{flag:"wx",mode:384,flush:true});await renameWithRetry(temporary,file,3,50)}finally{await removeLock(lock,path3.basename(owner))}}finally{release()}}};init_esbuild_shims();init_esbuild_shims();function classifyApiError(error){const status=error.status;const message=error.message?.toLowerCase()??"";if(status===429||message.includes("rate limit")){return"rate_limit"}if(status===401||message.includes("unauthorized")){return"authentication_failed"}if(status===402||status===403||message.includes("billing")||message.includes("quota")){return"billing_error"}if(status===400||message.includes("invalid")){return"invalid_request"}if(status!==void 0&&status>=500){return"server_error"}if(message.includes("max_tokens")||message.includes("token limit")){return"max_output_tokens"}return"unknown"}__name(classifyApiError,"classifyApiError");var MOD_MODEL_DEFAULT_MAX_TOKENS=1024;var ALIASES=new Map([["haiku","fast"],["sonnet","inherit"],["opus","inherit"]]);var NO_USAGE={input_tokens:0,output_tokens:0,cache_read_input_tokens:0,cache_creation_input_tokens:0};function resolveModModel(config,name2){const modelName=name2.trim();const wanted=ALIASES.get(modelName)??modelName;const target=wanted==="fast"?config.getFastModel?.({requirePinnedEndpoint:true})??"inherit":wanted;const context=buildModelIdContext(config);const[modelSelector,endpoint,extra]=target.split("\0");if(!modelSelector?.trim()||endpoint===""||extra!==void 0){throw new Error(`invalid model endpoint selector ${JSON.stringify(name2)}`)}const resolved=resolveModelId(modelSelector,context);if(!resolved)throw new Error(`model ${JSON.stringify(name2)} is not available`);const isSession=resolved.modelId===context.currentModel&&(!resolved.authType||resolved.authType===context.currentAuthType)&&(endpoint===void 0||endpoint===config.getContentGeneratorConfig()?.baseUrl);const configured=config.getAllConfiguredModels(resolved.authType?[resolved.authType]:void 0).some(model=>model.id===resolved.modelId&&(endpoint===void 0||model.baseUrl===endpoint)&&!model.voiceOnly&&!model.imageOnly&&!model.visionOnly);if(!isSession&&!configured)throw new Error(`model ${JSON.stringify(name2)} is not configured`);const selector=resolved.authType?`${resolved.authType}:${resolved.modelId}`:resolved.modelId;return{selector:endpoint===void 0?selector:`${selector}\0${endpoint}`,modelId:resolved.modelId,...resolved.authType&&{authType:resolved.authType}}}__name(resolveModModel,"resolveModModel");function tokenCount(value){return typeof value==="number"&&Number.isFinite(value)&&value>=0?Math.floor(value):0}__name(tokenCount,"tokenCount");function modModelUsage(metadata,authType){if(!metadata)return{...NO_USAGE};const prompt=tokenCount(metadata.promptTokenCount);const read=tokenCount(metadata.cachedContentTokenCount);const written=tokenCount(getGenAiUsageProvenance(metadata)?.cacheCreationInputTokens);return{input_tokens:Math.max(0,prompt-read-written),output_tokens:outputTokenCount({input:prompt,output:tokenCount(metadata.candidatesTokenCount),thoughts:tokenCount(metadata.thoughtsTokenCount),total:tokenCount(metadata.totalTokenCount)},authType),cache_read_input_tokens:read,cache_creation_input_tokens:written}}__name(modModelUsage,"modModelUsage");function apiErrorKind(error,status){const message=error instanceof Error?error.message:String(error);if(status===529||/overloaded/i.test(message))return"overloaded";if(status===404||/model[^.]*not (found|exist)/i.test(message))return"model_not_found";if(isQuotaExhaustedError(error)||isQwenQuotaExceededError(error))return"billing_error";const kind=classifyApiError({message,status});return kind==="loop_detected"?"unknown":kind}__name(apiErrorKind,"apiErrorKind");async function completeModModel(config,input,signal){if(signal.aborted)return{isAnswered:false,reason:"aborted",usage:{...NO_USAGE}};const model=resolveModModel(config,input.model);const maxTokens=input.maxTokens??MOD_MODEL_DEFAULT_MAX_TOKENS;if(input.maxTokens!==void 0&&hasExplicitOutputLimit(model.modelId)&&maxTokens>tokenLimit(model.modelId,"output"))throw new Error(`maxTokens ${maxTokens} is over ${model.modelId}'s output limit of ${tokenLimit(model.modelId,"output")}`);const abortSignal=input.timeoutMs===void 0?signal:AbortSignal.any([signal,AbortSignal.timeout(input.timeoutMs)]);let onAbort;try{const request=Promise.resolve().then(()=>config.getBaseLlmClient().generateText({contents:[{role:"user",parts:[{text:input.prompt}]}],model:model.selector,...typeof input.system==="string"&&input.system&&{systemInstruction:input.system},abortSignal,promptId:"side-query:mod-model-complete",config:{maxOutputTokens:Math.min(maxTokens,hasExplicitOutputLimit(model.modelId)?tokenLimit(model.modelId,"output"):maxTokens),thinkingConfig:{includeThoughts:input.effort!==void 0}},isolatedRequest:true}));const cancelled=new Promise((_,reject)=>{onAbort=__name(()=>reject(abortSignal.reason),"onAbort");abortSignal.addEventListener("abort",onAbort,{once:true})});const result=await Promise.race([request,cancelled]);const usage=modModelUsage(result.usage,model.authType??config.getContentGeneratorConfig()?.authType);if(!result.text)return{isAnswered:false,reason:"empty-reply",usage};const text=projectJsonStringToByteBudget(result.text,MOD_MAX_BYTES/2,"\n[... truncated for Mods ...]\n");return{isAnswered:true,text,usage}}catch(error){if(abortSignal.aborted)return{isAnswered:false,reason:"aborted",usage:{...NO_USAGE}};const providerError=error instanceof Error?error.cause??error:error;let cause=providerError;let status=getErrorStatus(cause);for(let depth=0;depth<4&&status===void 0&&cause instanceof Error&&cause.cause!==void 0;depth++){cause=cause.cause;status=getErrorStatus(cause)}const providerStatus=status??getErrorStatus(error);return{isAnswered:false,reason:"api-error",status:providerStatus??null,error:apiErrorKind(status===void 0?providerError:cause,providerStatus),usage:{...NO_USAGE}}}finally{if(onAbort)abortSignal.removeEventListener("abort",onAbort)}}__name(completeModModel,"completeModModel");init_esbuild_shims();var KEPT_ROWS=1e3;var rowId=__name(input=>`${input.component}\0${input.requestId}`,"rowId");var rowKey=__name(input=>stableJson({...input,viewport:void 0}),"rowKey");var ModRows=class{constructor(schedule,render){this.schedule=schedule;this.render=render}static{__name(this,"ModRows")}rows=new Map;queue=[];running=false;watch(input,listener){const id=rowId(input);const key=rowKey(input);let row=this.rows.get(id);if(row){this.rows.delete(id);row.input=input;row.key=key}else row={input,key,queued:false,listeners:new Set};this.rows.set(id,row);row.listeners.add(listener);if(this.due(row))this.enqueue(id,row);this.prune();return()=>{row.listeners.delete(listener);if(!this.running)this.prune()}}get(input){const row=this.rows.get(rowId(input));return row?.answer&&row.answerKey===rowKey(input)?row.answer:void 0}invalidate(component){for(const[id,row]of this.rows){if(row.input.component!==component)continue;row.stale=true;if(row.listeners.size)this.enqueue(id,row)}}clear(){const rows=[...this.rows.values()];this.rows.clear();this.queue.length=0;for(const row of rows)if(row.answer)for(const listener of row.listeners)listener()}enqueue(id,row){if(row.queued)return;row.queued=true;this.queue.push(id);this.pump()}pump(){if(this.running)return;let id;let row;while((id=this.queue.shift())!==void 0){const next=this.rows.get(id);if(!next)continue;next.queued=false;if(next.listeners.size&&this.due(next)){row=next;break}}this.prune();if(!row||id===void 0)return;const ready=row;const readyId=id;this.running=true;this.schedule(async()=>{try{if(this.rows.get(readyId)!==ready||!ready.listeners.size)return;const{input,key}=ready;ready.stale=false;let answer;try{answer=await this.render(input)}catch{answer=void 0}if(this.rows.get(readyId)===ready){const changed=ready.answer!==answer;ready.answer=answer;ready.answerKey=key;if(this.due(ready)&&ready.listeners.size)this.enqueue(readyId,ready);if(changed)for(const listener of ready.listeners)listener()}}finally{this.running=false;this.pump()}})}due(row){return row.stale===true||row.answerKey!==row.key}prune(){if(this.rows.size<=KEPT_ROWS)return;for(const[id,row]of this.rows){if(this.rows.size<=KEPT_ROWS)break;if(!row.listeners.size&&!row.queued)this.rows.delete(id)}}};var logger=createDebugLogger("MODS");var MOD_PROMPT_TURN_LIMIT=8;var RENDER_SETTLE_MS=150;var RENDER_LIVE_MS=34;var RENDER_STEADY_MS=100;var RENDER_SLOW_MS=1e3;var ROW_RENDER_TIMEOUT_MS=3e4;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;submitted=[];modTurns=0;stopped=false;taken=new WeakMap;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};sessionListeners=new Set;rows=new ModRows(task=>{this.toolQueue=this.toolQueue.then(task).catch(error=>logger.debug(`Mod ui.render: ${String(error)}`))},input=>this.renderRow(input));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(plugin=>this.invalidateRenders(plugin),"invalidate")}:void 0,this.terminal?this.terminal.prompts?.()===true:true,this.terminal&&this.terminal.runsPrompts?.()!==true?void 0:prompt=>this.queuePrompt(prompt),(input,modelSignal)=>completeModModel(this.config,input,this.sessionId===this.config.getSessionId()?modelSignal:AbortSignal.abort()),new ModStore(path4.join(Storage.getGlobalQwenDir(),"mods","store")));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;this.requestRender();this.refreshRows()}}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;this.refreshRows()}return}this.invalidateTools();const task=this.toolQueue.then(async()=>{if(current===this.sessionId||this.closing)return;await this.end(reason);this.sessionId=current;this.rows.clear();for(const listener of this.sessionListeners)listener();this.submitted.length=0;this.modTurns=0;this.stopped=false;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?.renderHooksFor("AbovePrompt").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 hooks=runtime.renderHooksFor("AbovePrompt");const owner=hooks.length===1?hooks[0]:"hooks";band.state="running";band.startedAt=Date.now();const signal=AbortSignal.any([this.lifetime.signal,this.toolGeneration.signal]);const isCurrent=__name(()=>!signal.aborted&&this.sessionId===this.config.getSessionId(),"isCurrent");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,signal);for(const note of notes)logger.debug(note);if(isCurrent())this.terminal?.draw?.(tree,owner)}catch(error){logger.debug(`Mod ui.render: ${String(error)}`);if(isCurrent())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()}}get rowSession(){return this.sessionId}subscribeSession=__name(listener=>{this.sessionListeners.add(listener);return()=>this.sessionListeners.delete(listener)},"subscribeSession");watchRow(sessionId,input,listener){if(this.closing||sessionId!==this.sessionId||!this.sites.includes(input.component)||!this.runtime?.renderHooksFor(input.component).length||Buffer.byteLength(JSON.stringify(input))>MOD_MAX_BYTES/2)return void 0;return this.rows.watch(input,listener)}rowProps(sessionId,input){return sessionId===this.sessionId?this.rows.get(input):void 0}refreshRows(){for(const site of this.sites)if(site!=="AbovePrompt")this.rows.invalidate(site)}invalidateRenders(plugin){const runtime=this.runtime;if(!runtime)return;for(const site of this.sites){if(!runtime.renderHooksFor(site).includes(plugin))continue;if(site==="AbovePrompt")this.requestRender();else this.rows.invalidate(site)}}async renderRow(input){const runtime=this.runtime;const generation=this.toolGeneration.signal;if(!runtime||this.closing||generation.aborted||this.sessionId!==this.config.getSessionId()||!this.allowed()||!this.active())return void 0;const signal=AbortSignal.any([this.lifetime.signal,generation,AbortSignal.timeout(ROW_RENDER_TIMEOUT_MS)]);try{const{props,notes}=await runtime.render(input,signal);signal.throwIfAborted();for(const note of notes)logger.debug(note);return!props||stableJson(props)===stableJson(input.props)?void 0:props}finally{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}}queuePrompt(prompt){if(this.closing||this.sessionId!==this.config.getSessionId())return"the session is ending";const refused=this.stopped?"the person stopped a turn and has not sent a prompt since":this.modTurns+this.submitted.length>=MOD_PROMPT_TURN_LIMIT?`the Mods have started ${MOD_PROMPT_TURN_LIMIT} turns since the last prompt from the person`:void 0;if(refused){this.pendingLogs.push({text:`$.prompt.submit refused: ${refused}`,to:"transcript",plugin:prompt.plugin,sessionId:this.sessionId});this.flushLogs();return refused}this.submitted.push({...prompt,sessionId:this.sessionId});this.terminal?.promptQueued?.();return void 0}takeSubmittedPrompt(){const sessionId=this.config.getSessionId();let next=this.submitted.shift();while(next&&next.sessionId!==sessionId)next=this.submitted.shift();if(!next||this.closing)return void 0;this.modTurns++;const{sessionId:queuedFor,...prompt}=next;this.taken.set(prompt,queuedFor);return prompt}returnSubmittedPrompt(prompt){const sessionId=this.taken.get(prompt);this.taken.delete(prompt);if(sessionId===void 0||this.closing||this.stopped||sessionId!==this.config.getSessionId())return;this.modTurns=Math.max(0,this.modTurns-1);this.submitted.unshift({...prompt,sessionId})}get hasSubmittedPrompts(){const sessionId=this.config.getSessionId();return!this.closing&&this.submitted.some(prompt=>prompt.sessionId===sessionId)}notePersonPrompt(){this.modTurns=0;this.stopped=false}discardSubmittedPrompts(){this.submitted.length=0}stopSubmittedPrompts(){this.discardSubmittedPrompts();this.stopped=true}get hearsPrompts(){return!this.closing&&(this.runtime?.promptHooks.length??0)>0}async submitPrompt(text,signal){const plugins=this.runtime?.promptHooks??[];if(!plugins.length||this.closing)return{text};const input={text,wait:false,origin:{kind:this.terminal?"composer":"sdk"}};if(fitTurnText(text).truncated){this.pendingLogs.push({text:"prompt.submit hook skipped: the prompt is too long for a Mod payload",to:"transcript",plugin:plugins.join("+"),sessionId:this.sessionId});this.flushLogs();return{text}}const sessionId=this.sessionId;const task=this.toolQueue.then(async()=>{signal.throwIfAborted();if(this.closing||sessionId!==this.config.getSessionId()||!this.allowed()||!this.active())return{text};try{return await this.runtime.submitPrompt(input,AbortSignal.any([signal,this.lifetime.signal]))}catch(error){signal.throwIfAborted();logger.debug(`Mod prompt.submit: ${String(error)}`);return{text}}finally{this.flushLogs()}});this.toolQueue=task.catch(()=>{});const result=await task;if(!("drop"in result)){if(!result.text.trim()&&text.trim())return{drop:"Prompt dropped by a hook: it left the prompt empty"};return result}if(!result.byHook)return{drop:`Prompt not submitted: ${result.drop}`};const reason=(this.terminal?sanitizeTerminalLine:stripAnsiAndControl)(result.drop.replace(/\r?\n/g," ").trim());if(cpLen(reason)>4096)logger.debug(`${plugins.join("+")}: prompt.submit hook: a drop of ${cpLen(reason)} characters, kept up to its first 4096`);return{drop:`Prompt dropped by a hook: ${cpLen(reason)>4096?`${cpSlice(reason,0,4096)}\u2026`:reason}`}}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:randomUUID2(),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{ENGINE_NODE,MOD_END_TIMEOUT_MS,MOD_MAX_BYTES,ModBudget,adjustRenderTree,assertModDepth,invalidRenderText,record,validModelResult,validateRenderTree,validateResult}from"./chunk-XWYUQMLN.js";import{stableJson}from"./chunk-FIXDX63I.js";import{external_exports}from"./chunk-KZSUHQLD.js";import{openNoFollow}from"./chunk-PSKT6KWO.js";import{isZombie,readLocalBootId,readPidNamespaceId,readProcStartToken}from"./chunk-JB3XRNK7.js";import{buildModelIdContext,resolveModelId}from"./chunk-QTJPOTU5.js";import{resolveBundleDir}from"./chunk-4NPYOXJO.js";import{isQuotaExhaustedError,isQwenQuotaExceededError}from"./chunk-3MG44MZK.js";import{runOutsideAgentContext}from"./chunk-KP77CL5U.js";import{isInternalPromptId,uiTelemetryService}from"./chunk-MJEL7DIE.js";import{Mutex,Semaphore}from"./chunk-JEV36CS7.js";import{renameWithRetry}from"./chunk-2GF3E5MI.js";import{hasExplicitOutputLimit,tokenLimit}from"./chunk-EV2CXPMN.js";import{EVENT_API_RESPONSE}from"./chunk-JJAEIBSV.js";import{getGenAiUsageProvenance,outputTokenCount}from"./chunk-4DIWAQ5G.js";import{require_semver}from"./chunk-73G3MZQR.js";import{registerCleanup}from"./chunk-WZAUO3LV.js";import{stripAnsiAndControl}from"./chunk-DBRQGEEI.js";import{ToolNames}from"./chunk-SBZFGYYS.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{getErrorStatus,isNodeError}from"./chunk-E7MYPQGV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();import{randomUUID as randomUUID2}from"node:crypto";import path4 from"node:path";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(external_exports.string(),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,queuePrompt,completeModel,store){this.log=log;this.facts=facts;this.resolveTool=resolveTool;this.surface=surface;this.abortTurn=abortTurn;this.renderHost=renderHost;this.queuePrompt=queuePrompt;this.completeModel=completeModel;this.store=store;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();root.models.get(id)?.abort();this.storeCalls.get(id)?.controller.abort()}}else if(reply.type==="model-complete")this.answerModel(reply,root);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==="prompt-queue")this.answerPromptQueue(reply,root.id);else if(reply.type==="store"){const remainingMs=reply.deadline-performance.now();if(remainingMs<=0)return;const controller=new AbortController;const signals=[root.storeAbort.signal,controller.signal];if(Number.isFinite(remainingMs))signals.push(AbortSignal.timeout(Math.ceil(remainingMs)));const task=this.answerStore(reply,root.id,AbortSignal.any(signals));this.storeCalls.set(reply.id,{controller,task});void task.finally(()=>this.storeCalls.delete(reply.id))}else if(reply.type==="invalidate"){if(reply.event!=="ui.render"||this.failure)return;if(this.early)this.early.add(reply.plugin);else if(Object.values(this.renders).some(names=>names.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&&!root.models.has(reply.operation))return;root.revision=reply.revision;root.idle=reply.operation===root.native&&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;storeCalls=new Map;storeReadSlots=new Semaphore(4);failure;pending;commands=[];tools=false;turns={start:false,complete:[]};prompts=[];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,prompts=false,queuePrompt,completeModel,store){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,queuePrompt,completeModel,store);try{const result=await runtime.request({type:"load",plugins,cwd,surface,version,sites:render?.sites??[],prompts,submits:queuePrompt!==void 0,models:completeModel!==void 0,stores:store!==void 0},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;const promptSubmit=record(result)?result["promptSubmit"]:void 0;if(!record(result)||typeof result["tools"]!=="boolean"||typeof result["turnStart"]!=="boolean"||!names(promptSubmit)||!names(turnComplete)||!record(renders)||Object.entries(renders).some(([site,plugins2])=>!(render?.sites??[]).includes(site)||!names(plugins2)))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.prompts=promptSubmit;runtime.renders=renders;const early=runtime.early;runtime.early=void 0;for(const plugin of early)if(Object.values(runtime.renders).some(plugins2=>plugins2.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 promptHooks(){return this.prompts}renderHooksFor(site){return this.renders[site]??[]}async render(input,signal){const answer=await this.request({type:"render",input},signal);let settled=answer;if(input.component==="AssistantMessage")settled=record(answer)?answer["tree"]:void 0;const hooks=this.renderHooksFor(input.component);const owner=hooks.length===1?hooks[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}}if(input.component==="AssistantMessage"){if(!record(settled)||settled["type"]!=="engine"||settled["ref"]!==0){note(`ui.render (${input.component}) answered a tree; this host draws only a rewrite of the row's props, so the row was left as it was`);return{tree:ENGINE_NODE,notes,props:input.props}}const props=record(answer)?answer["props"]:void 0;const text=record(props)?props["text"]:void 0;if(!record(props)||typeof text!=="string"||text!==input.props.text&&invalidRenderText(text)!==void 0||props["isFirstOfReply"]!==input.props.isFirstOfReply)return{tree:ENGINE_NODE,notes,props:input.props};return{tree:ENGINE_NODE,notes,props:{...input.props,text}}}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-VKSH7JVL.js")).ShellTool;break;case ToolNames.EDIT:builtin=await this.resolveTool(name2)instanceof(await import("./edit-4PJ3NPFA.js")).EditTool;break;case ToolNames.WRITE_FILE:builtin=await this.resolveTool(name2)instanceof(await import("./write-file-SF42KZAH.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 submitPrompt(input,signal){const result=await this.request({type:"prompt-submit",input},signal);if(record(result)&&(typeof result["drop"]==="string"?Object.keys(result).length===2&&typeof result["byHook"]==="boolean":typeof result["text"]==="string"&&Object.keys(result).every(key=>key==="text"||key==="context")&&(result["context"]===void 0||Array.isArray(result["context"])&&result["context"].every(item=>typeof item==="string"))))return result;throw new Error("Invalid Mod prompt.submit result.")}async completeTurn(input,signal){const result=await this.request({type:"turn-complete",input},signal);validateResult("turn.complete",result);return result.text}answerModel(reply,root){if(Atomics.load(this.cancelled,0)!==0||Atomics.load(reply.cancellation,0)!==0)return;const remainingMs=reply.deadline-performance.now();if(remainingMs<=0)return;const controller=new AbortController;const signal=Number.isFinite(remainingMs)?AbortSignal.any([controller.signal,AbortSignal.timeout(Math.ceil(remainingMs))]):controller.signal;root.models.set(reply.id,controller);const answer=__name(async()=>{try{if(!this.completeModel)throw new Error("this host runs no Mod model calls");const result=await this.completeModel(reply.input,signal);if(!validModelResult(result))throw new Error("the host answered with an invalid model result");return{type:"model-result",id:reply.id,result}}catch(caught){const error=(caught instanceof Error?caught.message:String(caught)).slice(0,4e3);return{type:"model-result",id:reply.id,error}}},"answer");void answer().then(request=>{root.models.delete(reply.id);if(this.root!==root)return;if(!signal.aborted){try{this.post(request,root.id)}catch(caught){this.post({type:"model-result",id:reply.id,error:caught instanceof Error?caught.message:String(caught)},root.id)}}root.refresh()})}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)}answerPromptQueue(reply,root){let refused;try{refused=this.queuePrompt?this.queuePrompt(reply.prompt):"this host does not run prompts a Mod submits"}catch(caught){refused=(caught instanceof Error?caught.message:String(caught)).slice(0,4e3)}this.post({type:"prompt-queue-result",id:reply.id,refused},root)}async answerStore(reply,root,signal){const{operation}=reply;let value;let error;try{signal.throwIfAborted();const store=this.store;if(!store)throw new Error("This host keeps no Mod store.");if(operation.method==="store.get"||operation.method==="store.keys"){value=await this.storeReadSlots.runExclusive(()=>{signal.throwIfAborted();return operation.method==="store.get"?store.get(operation.plugin,operation.key):store.keys(operation.plugin)})}else if(operation.method==="store.set")await store.set(operation.plugin,operation.key,operation.value,signal);else await store.delete(operation.plugin,operation.key,signal)}catch(caught){error=(caught instanceof Error?caught.message:String(caught)).slice(0,4e3)}if(signal.aborted)return;try{this.post({type:"store-result",id:reply.id,value,error},root)}catch(caught){this.post({type:"store-result",id:reply.id,error:(caught instanceof Error?caught.message:String(caught)).slice(0,4e3)},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),...[...this.storeCalls.values()].map(({task})=>task)])}fail(error){this.failure??=error;this.tool?.controller.abort();this.root?.storeAbort.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,models:new Map,storeAbort:new AbortController,refresh:__name(()=>{if(aborted||this.root!==root)return;const lending=root.idle!==void 0&&(request.type==="tool"&&root.idle===root.native&&!this.tool?.checks.size||root.models.has(root.idle))&&!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")};root.storeAbort.signal.addEventListener("abort",()=>this.storeReadSlots.cancel(),{once:true});this.root=root;const onAbort=__name(()=>{aborted=true;Atomics.store(this.cancelled,0,1);this.tool?.controller.abort();for(const model of root.models.values())model.abort();root.storeAbort.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;root.storeAbort.abort();for(const model of root.models.values())model.abort();root.models.clear();if(timer)clearTimeout(timer);if(cancelTimer)clearTimeout(cancelTimer);signal.removeEventListener("abort",onAbort);this.pending=void 0}}};init_esbuild_shims();import{createHash,createHmac,randomUUID}from"node:crypto";import{closeSync,constants,openSync,readFileSync,statfsSync,statSync}from"node:fs";import*as fs2 from"node:fs/promises";import{hostname}from"node:os";import*as path3 from"node:path";import{setTimeout as delay}from"node:timers/promises";var MOD_STORE_MAX_BYTES=4*1024*1024;var MAX_KEY_LIST_BYTES=MOD_MAX_BYTES-64;var LOCK_WAIT_MS=8e3;var PROC_SUPER_MAGIC=40864;var BOOT_ID_PATH="/proc/sys/kernel/random/boot_id";var lockHost=hostname();var pidNamespace=readPidNamespaceId();var bootId=process.platform==="linux"?readLocalBootId():null;var startPrefix=pidNamespace===null?null:readStartPrefix();var lockScope=scopeForBoot(bootId);var machineScope=bootId!==null&&pidNamespace!==null&&hasKernelBootId(bootId)?readMachineScope():null;var fileLocks=new Map;function scopeForBoot(id){return createHash("sha256").update(JSON.stringify([lockHost,pidNamespace,id])).digest("hex").slice(0,16)}__name(scopeForBoot,"scopeForBoot");function hasKernelBootId(expected){try{const fd=openSync(BOOT_ID_PATH,constants.O_RDONLY|constants.O_NONBLOCK);try{return statfsSync(`/proc/self/fd/${fd}`).type===PROC_SUPER_MAGIC&&readFileSync(fd,"utf8").trim()===expected}finally{closeSync(fd)}}catch{return false}}__name(hasKernelBootId,"hasKernelBootId");function readMachineScope(){try{const id=readFileSync("/etc/machine-id","utf8").trim();if(!/^[a-f0-9]{32}$/i.test(id)||/^0+$/.test(id))return null;return createHmac("sha256","Qwen-Code/ModStore/lock-host").update(Buffer.from(id,"hex")).digest("hex").slice(0,32)}catch{return null}}__name(readMachineScope,"readMachineScope");function hasLocalProcPids(){if(pidNamespace===null)return false;try{const status=readFileSync("/proc/self/status","utf8");return/^NStgid:[ \t]+(\d+)[ \t]*$/m.exec(status)?.[1]===String(process.pid)}catch{return false}}__name(hasLocalProcPids,"hasLocalProcPids");function readStartPrefix(){try{return`${statSync("/proc/self/ns/time").ino}~`}catch{return null}}__name(readStartPrefix,"readStartPrefix");function processStart(pid){if(startPrefix===null)return"-";const token=readProcStartToken(pid);return token===null?"-":`${startPrefix}${Buffer.from(token).toString("base64url")}`}__name(processStart,"processStart");function deadOwner(owner){const identity=/^(?<scope>[a-f0-9]{16})\.(?<pid>[1-9]\d{0,9})\.(?<start>(?:\d+~)?[\w-]+)\.[a-f0-9-]{36}(?:(?<kernel>\.k)?\.(?<machine>[a-f0-9]{32})\.(?<boot>[a-f0-9-]+))?$/.exec(owner)?.groups;if(!identity)return false;const{scope,pid:rawPid,start:recordedStart,kernel,machine,boot}=identity;if(scope!==lockScope){return kernel!==void 0&&machineScope!==null&&machine===machineScope&&boot!==void 0&&boot!==bootId&&scope===scopeForBoot(boot)}if(process.platform==="linux"&&(pidNamespace===null||bootId===null))return false;const pid=Number(rawPid);if(pid>2147483647)return false;try{process.kill(pid,0)}catch(error){return isNodeError(error)&&error.code==="ESRCH"}if(!hasLocalProcPids())return false;if(isZombie(pid))return true;if(startPrefix===null||!recordedStart.startsWith(startPrefix))return false;const start=processStart(pid);return start!=="-"&&recordedStart!==start}__name(deadOwner,"deadOwner");async function removeLock(lock,owner){if(owner)await fs2.rm(path3.join(lock,owner),{recursive:true,force:true});try{await fs2.rmdir(lock)}catch(error){if(!isNodeError(error)||!["ENOENT","ENOTEMPTY","EEXIST"].includes(error.code??""))throw error}}__name(removeLock,"removeLock");async function acquireLock(lock,signal){signal?.throwIfAborted();const nonce=randomUUID();const staging=`${lock}.${nonce}`;const recovery=machineScope&&bootId?`.k.${machineScope}.${bootId}`:"";const start=hasLocalProcPids()?processStart(process.pid):"-";const owner=`${lockScope}.${process.pid}.${start}.${nonce}${recovery}`;await fs2.mkdir(staging,{mode:448});let acquired=false;try{await fs2.mkdir(path3.join(staging,owner));const deadline=performance.now()+LOCK_WAIT_MS;do{signal?.throwIfAborted();try{await fs2.rename(staging,lock);acquired=true;return path3.join(lock,owner)}catch(error){if(!isNodeError(error)||!["ENOTEMPTY","EEXIST","EPERM","EACCES"].includes(error.code??""))throw error;const owners=await fs2.lstat(lock).then(stat=>{if(!stat.isDirectory())throw error;return fs2.readdir(lock)}).catch(cause=>{if(isNodeError(cause)&&cause.code==="ENOENT")return[];throw cause});if(owners.length===0)await removeLock(lock);else if(owners.length===1&&deadOwner(owners[0]))await removeLock(lock,owners[0])}await delay(50,void 0,{signal})}while(performance.now()<deadline);throw new Error(`Mod store: timed out waiting for ${lock}.`)}finally{if(!acquired)await fs2.rm(staging,{recursive:true,force:true}).catch(()=>{})}}__name(acquireLock,"acquireLock");function acquireLocalLock(mutex,signal){if(!signal)return mutex.acquire();signal.throwIfAborted();return new Promise((resolve,reject)=>{const abort=__name(()=>reject(signal.reason),"abort");signal.addEventListener("abort",abort,{once:true});void mutex.acquire().then(release=>{signal.removeEventListener("abort",abort);if(signal.aborted)release();else resolve(release)},error=>{signal.removeEventListener("abort",abort);reject(error)})})}__name(acquireLocalLock,"acquireLocalLock");var ModStore=class{constructor(dir){this.dir=dir}static{__name(this,"ModStore")}async get(plugin,key){return(await this.read(this.file(plugin))).get(key)}async keys(plugin){return[...(await this.read(this.file(plugin))).keys()]}async set(plugin,key,value,signal){await this.change(plugin,signal,entries=>{if(!entries.has(key)&&Buffer.byteLength(JSON.stringify([...entries.keys(),key]))>MAX_KEY_LIST_BYTES)throw new Error(`Mod store: the key list would be over ${MAX_KEY_LIST_BYTES} bytes of JSON.`);entries.set(key,value);return true})}async delete(plugin,key,signal){await this.change(plugin,signal,entries=>entries.delete(key))}file(plugin){const name2=plugin.toLowerCase();if(!/^[a-z0-9_.-]+$/.test(name2)||/^\.+$/.test(name2))throw new Error(`Mod store: no store for the plugin name "${plugin}".`);const stem=name2.length>128?`~${createHash("sha256").update(name2).digest("hex")}`:name2;return path3.join(this.dir,`${stem}.json`)}async read(file){let text;try{const handle=await openNoFollow(file,{nonBlocking:true}).catch(error=>{if(isNodeError(error)&&error.code==="ELOOP")return openNoFollow(file,{nonBlocking:true});throw error});try{if(!(await handle.stat()).isFile())throw new Error("The store is not a regular file.");text=await handle.readFile("utf8")}finally{await handle.close()}}catch(error){if(isNodeError(error)&&error.code==="ENOENT")return new Map;throw new Error(`Mod store: cannot read ${file}: ${error instanceof Error?error.message:String(error)}`)}let parsed;try{parsed=JSON.parse(text)}catch{parsed=void 0}const stored=parsed;if(!stored||stored.version!==1||!Array.isArray(stored.entries)||!stored.entries.every(entry=>Array.isArray(entry)&&entry.length===2&&typeof entry[0]==="string"))throw new Error(`Mod store: ${file} is not a store this version reads; it is left unchanged.`);return new Map(stored.entries)}async change(plugin,signal,apply){const file=this.file(plugin);let mutex=fileLocks.get(file);if(!mutex)fileLocks.set(file,mutex=new Mutex);const release=await acquireLocalLock(mutex,signal);try{signal?.throwIfAborted();await fs2.mkdir(this.dir,{recursive:true,mode:448});const lock=`${file}.lock`;const owner=await acquireLock(lock,signal);try{signal?.throwIfAborted();const entries=await this.read(file);if(!apply(entries))return;const stored={version:1,entries:[...entries]};const text=JSON.stringify(stored);if(Buffer.byteLength(text)>MOD_STORE_MAX_BYTES)throw new Error(`Mod store: the store would be over ${MOD_STORE_MAX_BYTES} bytes of JSON.`);const temporary=path3.join(owner,"store.json");await fs2.writeFile(temporary,text,{flag:"wx",mode:384,flush:true});await renameWithRetry(temporary,file,3,50)}finally{await removeLock(lock,path3.basename(owner))}}finally{release()}}};init_esbuild_shims();init_esbuild_shims();function classifyApiError(error){const status=error.status;const message=error.message?.toLowerCase()??"";if(status===429||message.includes("rate limit")){return"rate_limit"}if(status===401||message.includes("unauthorized")){return"authentication_failed"}if(status===402||status===403||message.includes("billing")||message.includes("quota")){return"billing_error"}if(status===400||message.includes("invalid")){return"invalid_request"}if(status!==void 0&&status>=500){return"server_error"}if(message.includes("max_tokens")||message.includes("token limit")){return"max_output_tokens"}return"unknown"}__name(classifyApiError,"classifyApiError");var MOD_MODEL_DEFAULT_MAX_TOKENS=1024;var ALIASES=new Map([["haiku","fast"],["sonnet","inherit"],["opus","inherit"]]);var NO_USAGE={input_tokens:0,output_tokens:0,cache_read_input_tokens:0,cache_creation_input_tokens:0};function resolveModModel(config,name2){const modelName=name2.trim();const wanted=ALIASES.get(modelName)??modelName;const target=wanted==="fast"?config.getFastModel?.({requirePinnedEndpoint:true})??"inherit":wanted;const context=buildModelIdContext(config);const[modelSelector,endpoint,extra]=target.split("\0");if(!modelSelector?.trim()||endpoint===""||extra!==void 0){throw new Error(`invalid model endpoint selector ${JSON.stringify(name2)}`)}const resolved=resolveModelId(modelSelector,context);if(!resolved)throw new Error(`model ${JSON.stringify(name2)} is not available`);const isSession=resolved.modelId===context.currentModel&&(!resolved.authType||resolved.authType===context.currentAuthType)&&(endpoint===void 0||endpoint===config.getContentGeneratorConfig()?.baseUrl);const configured=config.getAllConfiguredModels(resolved.authType?[resolved.authType]:void 0).some(model=>model.id===resolved.modelId&&(endpoint===void 0||model.baseUrl===endpoint)&&!model.voiceOnly&&!model.imageOnly&&!model.visionOnly);if(!isSession&&!configured)throw new Error(`model ${JSON.stringify(name2)} is not configured`);const selector=resolved.authType?`${resolved.authType}:${resolved.modelId}`:resolved.modelId;return{selector:endpoint===void 0?selector:`${selector}\0${endpoint}`,modelId:resolved.modelId,...resolved.authType&&{authType:resolved.authType}}}__name(resolveModModel,"resolveModModel");function tokenCount(value){return typeof value==="number"&&Number.isFinite(value)&&value>=0?Math.floor(value):0}__name(tokenCount,"tokenCount");function modModelUsage(metadata,authType){if(!metadata)return{...NO_USAGE};const prompt=tokenCount(metadata.promptTokenCount);const read=tokenCount(metadata.cachedContentTokenCount);const written=tokenCount(getGenAiUsageProvenance(metadata)?.cacheCreationInputTokens);return{input_tokens:Math.max(0,prompt-read-written),output_tokens:outputTokenCount({input:prompt,output:tokenCount(metadata.candidatesTokenCount),thoughts:tokenCount(metadata.thoughtsTokenCount),total:tokenCount(metadata.totalTokenCount)},authType),cache_read_input_tokens:read,cache_creation_input_tokens:written}}__name(modModelUsage,"modModelUsage");function apiErrorKind(error,status){const message=error instanceof Error?error.message:String(error);if(status===529||/overloaded/i.test(message))return"overloaded";if(status===404||/model[^.]*not (found|exist)/i.test(message))return"model_not_found";if(isQuotaExhaustedError(error)||isQwenQuotaExceededError(error))return"billing_error";const kind=classifyApiError({message,status});return kind==="loop_detected"?"unknown":kind}__name(apiErrorKind,"apiErrorKind");async function completeModModel(config,input,signal){if(signal.aborted)return{isAnswered:false,reason:"aborted",usage:{...NO_USAGE}};const model=resolveModModel(config,input.model);const maxTokens=input.maxTokens??MOD_MODEL_DEFAULT_MAX_TOKENS;if(input.maxTokens!==void 0&&hasExplicitOutputLimit(model.modelId)&&maxTokens>tokenLimit(model.modelId,"output"))throw new Error(`maxTokens ${maxTokens} is over ${model.modelId}'s output limit of ${tokenLimit(model.modelId,"output")}`);const abortSignal=input.timeoutMs===void 0?signal:AbortSignal.any([signal,AbortSignal.timeout(input.timeoutMs)]);let onAbort;try{const request=Promise.resolve().then(()=>config.getBaseLlmClient().generateText({contents:[{role:"user",parts:[{text:input.prompt}]}],model:model.selector,...typeof input.system==="string"&&input.system&&{systemInstruction:input.system},abortSignal,promptId:"side-query:mod-model-complete",config:{maxOutputTokens:Math.min(maxTokens,hasExplicitOutputLimit(model.modelId)?tokenLimit(model.modelId,"output"):maxTokens),thinkingConfig:{includeThoughts:input.effort!==void 0}},isolatedRequest:true}));const cancelled=new Promise((_,reject)=>{onAbort=__name(()=>reject(abortSignal.reason),"onAbort");abortSignal.addEventListener("abort",onAbort,{once:true})});const result=await Promise.race([request,cancelled]);const usage=modModelUsage(result.usage,model.authType??config.getContentGeneratorConfig()?.authType);if(!result.text)return{isAnswered:false,reason:"empty-reply",usage};const text=projectJsonStringToByteBudget(result.text,MOD_MAX_BYTES/2,"\n[... truncated for Mods ...]\n");return{isAnswered:true,text,usage}}catch(error){if(abortSignal.aborted)return{isAnswered:false,reason:"aborted",usage:{...NO_USAGE}};const providerError=error instanceof Error?error.cause??error:error;let cause=providerError;let status=getErrorStatus(cause);for(let depth=0;depth<4&&status===void 0&&cause instanceof Error&&cause.cause!==void 0;depth++){cause=cause.cause;status=getErrorStatus(cause)}const providerStatus=status??getErrorStatus(error);return{isAnswered:false,reason:"api-error",status:providerStatus??null,error:apiErrorKind(status===void 0?providerError:cause,providerStatus),usage:{...NO_USAGE}}}finally{if(onAbort)abortSignal.removeEventListener("abort",onAbort)}}__name(completeModModel,"completeModModel");init_esbuild_shims();var KEPT_ROWS=1e3;var rowId=__name(input=>`${input.component}\0${input.requestId}`,"rowId");var rowKey=__name(input=>stableJson({...input,viewport:void 0}),"rowKey");var ModRows=class{constructor(schedule,render){this.schedule=schedule;this.render=render}static{__name(this,"ModRows")}rows=new Map;queue=[];running=false;watch(input,listener){const id=rowId(input);const key=rowKey(input);let row=this.rows.get(id);if(row){this.rows.delete(id);row.input=input;row.key=key}else row={input,key,queued:false,listeners:new Set};this.rows.set(id,row);row.listeners.add(listener);if(this.due(row))this.enqueue(id,row);this.prune();return()=>{row.listeners.delete(listener);if(!this.running)this.prune()}}get(input){const row=this.rows.get(rowId(input));return row?.answer&&row.answerKey===rowKey(input)?row.answer:void 0}invalidate(component){for(const[id,row]of this.rows){if(row.input.component!==component)continue;row.stale=true;if(row.listeners.size)this.enqueue(id,row)}}clear(){const rows=[...this.rows.values()];this.rows.clear();this.queue.length=0;for(const row of rows)if(row.answer)for(const listener of row.listeners)listener()}enqueue(id,row){if(row.queued)return;row.queued=true;this.queue.push(id);this.pump()}pump(){if(this.running)return;let id;let row;while((id=this.queue.shift())!==void 0){const next=this.rows.get(id);if(!next)continue;next.queued=false;if(next.listeners.size&&this.due(next)){row=next;break}}this.prune();if(!row||id===void 0)return;const ready=row;const readyId=id;this.running=true;this.schedule(async()=>{try{if(this.rows.get(readyId)!==ready||!ready.listeners.size)return;const{input,key}=ready;ready.stale=false;let answer;try{answer=await this.render(input)}catch{answer=void 0}if(this.rows.get(readyId)===ready){const changed=ready.answer!==answer;ready.answer=answer;ready.answerKey=key;if(this.due(ready)&&ready.listeners.size)this.enqueue(readyId,ready);if(changed)for(const listener of ready.listeners)listener()}}finally{this.running=false;this.pump()}})}due(row){return row.stale===true||row.answerKey!==row.key}prune(){if(this.rows.size<=KEPT_ROWS)return;for(const[id,row]of this.rows){if(this.rows.size<=KEPT_ROWS)break;if(!row.listeners.size&&!row.queued)this.rows.delete(id)}}};var logger=createDebugLogger("MODS");var MOD_PROMPT_TURN_LIMIT=8;var RENDER_SETTLE_MS=150;var RENDER_LIVE_MS=34;var RENDER_STEADY_MS=100;var RENDER_SLOW_MS=1e3;var ROW_RENDER_TIMEOUT_MS=3e4;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;submitted=[];modTurns=0;stopped=false;taken=new WeakMap;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};sessionListeners=new Set;rows=new ModRows(task=>{this.toolQueue=this.toolQueue.then(task).catch(error=>logger.debug(`Mod ui.render: ${String(error)}`))},input=>this.renderRow(input));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(plugin=>this.invalidateRenders(plugin),"invalidate")}:void 0,this.terminal?this.terminal.prompts?.()===true:true,this.terminal&&this.terminal.runsPrompts?.()!==true?void 0:prompt=>this.queuePrompt(prompt),(input,modelSignal)=>completeModModel(this.config,input,this.sessionId===this.config.getSessionId()?modelSignal:AbortSignal.abort()),new ModStore(path4.join(Storage.getGlobalQwenDir(),"mods","store")));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;this.requestRender();this.refreshRows()}}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;this.refreshRows()}return}this.invalidateTools();const task=this.toolQueue.then(async()=>{if(current===this.sessionId||this.closing)return;await this.end(reason);this.sessionId=current;this.rows.clear();for(const listener of this.sessionListeners)listener();this.submitted.length=0;this.modTurns=0;this.stopped=false;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?.renderHooksFor("AbovePrompt").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 hooks=runtime.renderHooksFor("AbovePrompt");const owner=hooks.length===1?hooks[0]:"hooks";band.state="running";band.startedAt=Date.now();const signal=AbortSignal.any([this.lifetime.signal,this.toolGeneration.signal]);const isCurrent=__name(()=>!signal.aborted&&this.sessionId===this.config.getSessionId(),"isCurrent");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,signal);for(const note of notes)logger.debug(note);if(isCurrent())this.terminal?.draw?.(tree,owner)}catch(error){logger.debug(`Mod ui.render: ${String(error)}`);if(isCurrent())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()}}get rowSession(){return this.sessionId}subscribeSession=__name(listener=>{this.sessionListeners.add(listener);return()=>this.sessionListeners.delete(listener)},"subscribeSession");watchRow(sessionId,input,listener){if(this.closing||sessionId!==this.sessionId||!this.sites.includes(input.component)||!this.runtime?.renderHooksFor(input.component).length||Buffer.byteLength(JSON.stringify(input))>MOD_MAX_BYTES/2)return void 0;return this.rows.watch(input,listener)}rowProps(sessionId,input){return sessionId===this.sessionId?this.rows.get(input):void 0}refreshRows(){for(const site of this.sites)if(site!=="AbovePrompt")this.rows.invalidate(site)}invalidateRenders(plugin){const runtime=this.runtime;if(!runtime)return;for(const site of this.sites){if(!runtime.renderHooksFor(site).includes(plugin))continue;if(site==="AbovePrompt")this.requestRender();else this.rows.invalidate(site)}}async renderRow(input){const runtime=this.runtime;const generation=this.toolGeneration.signal;if(!runtime||this.closing||generation.aborted||this.sessionId!==this.config.getSessionId()||!this.allowed()||!this.active())return void 0;const signal=AbortSignal.any([this.lifetime.signal,generation,AbortSignal.timeout(ROW_RENDER_TIMEOUT_MS)]);try{const{props,notes}=await runtime.render(input,signal);signal.throwIfAborted();for(const note of notes)logger.debug(note);return!props||stableJson(props)===stableJson(input.props)?void 0:props}finally{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}}queuePrompt(prompt){if(this.closing||this.sessionId!==this.config.getSessionId())return"the session is ending";const refused=this.stopped?"the person stopped a turn and has not sent a prompt since":this.modTurns+this.submitted.length>=MOD_PROMPT_TURN_LIMIT?`the Mods have started ${MOD_PROMPT_TURN_LIMIT} turns since the last prompt from the person`:void 0;if(refused){this.pendingLogs.push({text:`$.prompt.submit refused: ${refused}`,to:"transcript",plugin:prompt.plugin,sessionId:this.sessionId});this.flushLogs();return refused}this.submitted.push({...prompt,sessionId:this.sessionId});this.terminal?.promptQueued?.();return void 0}takeSubmittedPrompt(){const sessionId=this.config.getSessionId();let next=this.submitted.shift();while(next&&next.sessionId!==sessionId)next=this.submitted.shift();if(!next||this.closing)return void 0;this.modTurns++;const{sessionId:queuedFor,...prompt}=next;this.taken.set(prompt,queuedFor);return prompt}returnSubmittedPrompt(prompt){const sessionId=this.taken.get(prompt);this.taken.delete(prompt);if(sessionId===void 0||this.closing||this.stopped||sessionId!==this.config.getSessionId())return;this.modTurns=Math.max(0,this.modTurns-1);this.submitted.unshift({...prompt,sessionId})}get hasSubmittedPrompts(){const sessionId=this.config.getSessionId();return!this.closing&&this.submitted.some(prompt=>prompt.sessionId===sessionId)}notePersonPrompt(){this.modTurns=0;this.stopped=false}discardSubmittedPrompts(){this.submitted.length=0}stopSubmittedPrompts(){this.discardSubmittedPrompts();this.stopped=true}get hearsPrompts(){return!this.closing&&(this.runtime?.promptHooks.length??0)>0}async submitPrompt(text,signal){const plugins=this.runtime?.promptHooks??[];if(!plugins.length||this.closing)return{text};const input={text,wait:false,origin:{kind:this.terminal?"composer":"sdk"}};if(fitTurnText(text).truncated){this.pendingLogs.push({text:"prompt.submit hook skipped: the prompt is too long for a Mod payload",to:"transcript",plugin:plugins.join("+"),sessionId:this.sessionId});this.flushLogs();return{text}}const sessionId=this.sessionId;const task=this.toolQueue.then(async()=>{signal.throwIfAborted();if(this.closing||sessionId!==this.config.getSessionId()||!this.allowed()||!this.active())return{text};try{return await this.runtime.submitPrompt(input,AbortSignal.any([signal,this.lifetime.signal]))}catch(error){signal.throwIfAborted();logger.debug(`Mod prompt.submit: ${String(error)}`);return{text}}finally{this.flushLogs()}});this.toolQueue=task.catch(()=>{});const result=await task;if(!("drop"in result)){if(!result.text.trim()&&text.trim())return{drop:"Prompt dropped by a hook: it left the prompt empty"};return result}if(!result.byHook)return{drop:`Prompt not submitted: ${result.drop}`};const reason=(this.terminal?sanitizeTerminalLine:stripAnsiAndControl)(result.drop.replace(/\r?\n/g," ").trim());if(cpLen(reason)>4096)logger.debug(`${plugins.join("+")}: prompt.submit hook: a drop of ${cpLen(reason)} characters, kept up to its first 4096`);return{drop:`Prompt dropped by a hook: ${cpLen(reason)>4096?`${cpSlice(reason,0,4096)}\u2026`:reason}`}}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:randomUUID2(),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 addTurnUsage(usage,metadata,authType){if(!metadata)return usage;const added=modModelUsage(metadata,authType);return{input_tokens:(usage?.input_tokens??0)+added.input_tokens,output_tokens:(usage?.output_tokens??0)+added.output_tokens,cache_read_input_tokens:(usage?.cache_read_input_tokens??0)+added.cache_read_input_tokens,cache_creation_input_tokens:(usage?.cache_creation_input_tokens??0)+added.cache_creation_input_tokens}}__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;var MODS_FAILED_TO_INITIALIZE="Mods failed to initialize. Fix the Mod configuration and restart. /help and /quit remain available.";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"),prompts:__name(()=>this.prompts,"prompts"),runsPrompts:__name(()=>this.runsPrompts,"runsPrompts"),promptQueued:__name(()=>{for(const listener of this.promptListeners)listener()},"promptQueued"),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;started=false;startupFailed=false;closing;listener;logs=[];presentation={isFullscreen:false,columns:80};sites=[];prompts=false;runsPrompts=false;promptListeners=new Set;band;revision=0;bandListeners=new Set;unregisterCleanup;initialize(sites=[],{prompts=false,runsPrompts=false}={}){if(!this.initialization){this.sites=sites;this.prompts=prompts;this.runsPrompts=runsPrompts}this.initialization??=this.session.initialize(this.lifetime.signal).then(()=>{this.session.flushLogs();this.started=true;this.resolveStartup()},error=>{this.started=true;this.startupFailed=true;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}get starting(){return!this.closing&&!this.started}get failed(){return!this.closing&&this.startupFailed}failStartup(error){if(this.initialization)return;this.initialization=this.startup;this.started=true;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)}watchRow(sessionId,input,listener){return this.closing||!this.started||this.startupFailed?void 0:this.session.watchRow(sessionId,input,listener)}get rowSession(){return this.session.rowSession}subscribeSession=__name(listener=>this.session.subscribeSession(listener),"subscribeSession");rowProps(sessionId,input){return this.closing?void 0:this.session.rowProps(sessionId,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)}get hearsPrompts(){return!this.closing&&this.session.hearsPrompts}submitPrompt(text,signal){return this.closing?Promise.resolve({text}):this.session.submitPrompt(text,signal)}subscribePrompts=__name(listener=>{this.promptListeners.add(listener);return()=>this.promptListeners.delete(listener)},"subscribePrompts");get hasSubmittedPrompts(){return!this.closing&&this.session.hasSubmittedPrompts}takeSubmittedPrompt(){return this.closing?void 0:this.session.takeSubmittedPrompt()}returnSubmittedPrompt(prompt){if(!this.closing)this.session.returnSubmittedPrompt(prompt)}notePersonPrompt(){this.session.notePersonPrompt()}stopSubmittedPrompts(){this.session.stopSubmittedPrompts()}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();this.promptListeners.clear();if(sessions.get(this.config)===this)sessions.delete(this.config)}})();return this.closing}};export{classifyApiError,ModSession,MODS_FAILED_TO_INITIALIZE,isModRecoveryCommand,createInteractiveModSession,getInteractiveModSession,InteractiveModSession};
|
|
6
6
|
/**
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{LEASE_PREFIX,REVIEW_TMP_DIR,inertPath,reviewBranch,reviewTrustStateDir}from"./chunk-
|
|
3
|
+
import{LEASE_PREFIX,REVIEW_TMP_DIR,inertPath,reviewBranch,reviewTrustStateDir}from"./chunk-MCHMWRNO.js";import{writeStderrLineSafe}from"./chunk-M4ECEHLX.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{execFileSync}from"node:child_process";import{randomBytes}from"node:crypto";import{existsSync,lstatSync,mkdirSync,readFileSync,readdirSync,renameSync,rmdirSync,rmSync,writeFileSync}from"node:fs";import{basename,dirname,isAbsolute,join,relative,resolve}from"node:path";var GIT_TIMEOUT_MS=12e4;var debugLogger=createDebugLogger("REVIEW_WORKTREE_LEASE");function gitOptions(timeout){return{stdio:"ignore",timeout,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}}__name(gitOptions,"gitOptions");function validTarget(target){return/^pr-\d+$/.test(target)}__name(validTarget,"validTarget");function isReviewLeaseFile(fileName){if(!fileName.startsWith(LEASE_PREFIX)||!fileName.endsWith(".json")){return false}const target=fileName.slice(LEASE_PREFIX.length,fileName.length-".json".length);return validTarget(target)}__name(isReviewLeaseFile,"isReviewLeaseFile");function leaseDirectory(repositoryRoot){return reviewTrustStateDir(repositoryRoot)}__name(leaseDirectory,"leaseDirectory");function legacyLeasePath(repositoryRoot,target){return join(repositoryRoot,REVIEW_TMP_DIR,`${LEASE_PREFIX}${target}.json`)}__name(legacyLeasePath,"legacyLeasePath");function leasePath(repositoryRoot,target){return join(leaseDirectory(repositoryRoot),`${LEASE_PREFIX}${target}.json`)}__name(leasePath,"leasePath");function clearReviewWorktreeLease(repositoryRoot,target){if(!validTarget(target))return;const root=resolve(repositoryRoot);rmSync(leasePath(root,target),{force:true});reclaimBaseTreeTrust(root,target);const legacy=legacyLeasePath(root,target);try{rmSync(legacy,{force:true,recursive:true})}catch(error){writeStderrLineSafe(`warning: could not remove the pre-move review lease at ${legacy} (${error.code??error}); the trusted lease for ${target} is released, but a build from before the lease move will keep seeing this one until it is deleted by hand.`)}}__name(clearReviewWorktreeLease,"clearReviewWorktreeLease");function clearReviewWorktreeLeaseIfOwned(repositoryRoot,target,owner){const lease=readReviewWorktreeLease(repositoryRoot,target);if(!lease||lease.sessionId!==owner.sessionId||lease.promptId!==owner.promptId){return}clearReviewWorktreeLease(repositoryRoot,target)}__name(clearReviewWorktreeLeaseIfOwned,"clearReviewWorktreeLeaseIfOwned");function mintIdentity(){return Math.floor(Date.now()/1e3)*2**20+randomBytes(3).readUIntBE(0,3)%2**20}__name(mintIdentity,"mintIdentity");function recordReviewWorktreeLeaseMergeBase(repositoryRoot,target,mergeBaseSha,sessionId,options={}){if(!validTarget(target)||!mergeBaseSha)return;const stale=options.stale===true;const root=resolve(repositoryRoot);const path=leasePath(root,target);const existing=readLease(path);if(!existing)return;if(sessionId!==void 0&&existing.sessionId!==sessionId)return;if(existing.mergeBaseSha===mergeBaseSha&&existing.mergeBaseStale===true===stale){return}const previous=existing.mergeBaseSha??existing.priorMergeBaseSha;const next={...existing,mergeBaseSha,mergeBaseStale:stale,priorMergeBaseSha:mergeBaseSha,priorMergeBaseStale:stale,priorMergeBaseCurrent:true,identity:previous===void 0||previous===mergeBaseSha?existing.identity??mintIdentity():mintIdentity()};try{atomicWriteLease(path,`${JSON.stringify(next,null,2)}
|
|
4
4
|
`)}catch(error){debugLogger.debug(`Failed to record the merge base in ${path}:`,error)}}__name(recordReviewWorktreeLeaseMergeBase,"recordReviewWorktreeLeaseMergeBase");function atomicWriteLease(path,data){const tmp=`${path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;try{writeFileSync(tmp,data,{encoding:"utf8",flag:"wx"});renameSync(tmp,path)}catch(error){try{rmSync(tmp,{force:true})}catch{}throw error}}__name(atomicWriteLease,"atomicWriteLease");function reclaimBaseTreeTrust(root,target){const dir=join(leaseDirectory(root),"base-tree",target);let entries;try{entries=readdirSync(dir)}catch(error){if(error.code!=="ENOENT"){debugLogger.debug(`Failed to reclaim base-tree trust state for ${target}:`,error)}return}for(const name of entries){if(name.endsWith(".lock"))continue;try{rmSync(join(dir,name),{recursive:true,force:true})}catch(error){debugLogger.debug(`Failed to reclaim base-tree trust state ${name} for ${target}:`,error)}}try{rmdirSync(dir)}catch{}}__name(reclaimBaseTreeTrust,"reclaimBaseTreeTrust");function restoreReviewWorktreeLeaseMergeBase(repositoryRoot,target,sessionId){if(!validTarget(target)||!sessionId)return;const path=leasePath(resolve(repositoryRoot),target);const existing=readLease(path);if(!existing||existing.sessionId!==sessionId)return;if(existing.mergeBaseSha!==void 0)return;if(existing.priorMergeBaseResumable!==true)return;const next={...existing,mergeBaseSha:existing.priorMergeBaseSha,mergeBaseStale:existing.priorMergeBaseStale===true,priorMergeBaseCurrent:true};try{atomicWriteLease(path,`${JSON.stringify(next,null,2)}
|
|
5
5
|
`)}catch(error){debugLogger.debug(`Failed to restore the merge base in ${path}:`,error)}}__name(restoreReviewWorktreeLeaseMergeBase,"restoreReviewWorktreeLeaseMergeBase");function createReviewWorktreeLease(params){if(!params.sessionId||!params.promptId||!validTarget(params.target)){return}const repositoryRoot=resolve(params.repositoryRoot);const path=leasePath(repositoryRoot,params.target);const leaseFor=__name((identity,prior)=>{const lease={sessionId:params.sessionId,promptId:params.promptId,target:params.target,repositoryRoot,worktreePath:resolve(repositoryRoot,params.worktreePath),branch:params.branch,identity,...prior===void 0?{}:{priorMergeBaseSha:prior.sha,priorMergeBaseStale:prior.stale,priorMergeBaseResumable:prior.resumable}};return`${JSON.stringify(lease,null,2)}
|
|
6
6
|
`},"leaseFor");let data=leaseFor(mintIdentity());mkdirSync(leaseDirectory(repositoryRoot),{recursive:true,mode:448});const legacy=legacyLeasePath(repositoryRoot,params.target);try{writeFileSync(path,data,{encoding:"utf8",flag:"wx"})}catch(error){if(error.code!=="EEXIST")throw error;const existing=readLease(path);if(existing&&existing.sessionId!==params.sessionId){throw new Error(`review worktree lease for ${params.target} is held by another session (session ${existing.sessionId}) at ${path}; it was acquired between the gate read and the lease write \u2014 retry`)}if(existing){data=leaseFor(typeof existing.identity==="number"&&Number.isFinite(existing.identity)?existing.identity:mintIdentity(),existing.mergeBaseSha!==void 0?{sha:existing.mergeBaseSha,stale:existing.mergeBaseStale===true,resumable:existing.priorMergeBaseCurrent===true}:existing.priorMergeBaseSha!==void 0?{sha:existing.priorMergeBaseSha,stale:existing.priorMergeBaseStale===true,resumable:existing.priorMergeBaseCurrent===true}:void 0)}atomicWriteLease(path,data)}mirrorLeaseAtLegacyPath(legacy,data,params.sessionId,params.target)}__name(createReviewWorktreeLease,"createReviewWorktreeLease");function mirrorLeaseAtLegacyPath(legacy,data,sessionId,target){try{mkdirSync(dirname(legacy),{recursive:true});writeFileSync(legacy,data,{encoding:"utf8",flag:"wx"});return}catch(error){if(error.code!=="EEXIST"){warnMirrorSkipped(legacy,error);return}}const displaced=readLease(legacy);const tmp=`${legacy}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;try{writeFileSync(tmp,data,{encoding:"utf8",flag:"wx"});renameSync(tmp,legacy)}catch(error){try{rmSync(tmp,{force:true})}catch{}warnMirrorSkipped(legacy,error);return}if(displaced&&displaced.sessionId!==sessionId){writeStderrLineSafe(`warning: replaced the pre-move review lease for ${target} at ${legacy} (recorded session ${inertSessionId(displaced.sessionId)}) \u2014 if a pre-move build is still reviewing ${target} on this machine, its worktree is no longer protected; otherwise this was residue or a plant, and it is gone.`)}}__name(mirrorLeaseAtLegacyPath,"mirrorLeaseAtLegacyPath");function inertSessionId(id){const inert=inertPath(id);return inert.length>120?`${inert.slice(0,120)}\u2026`:inert}__name(inertSessionId,"inertSessionId");function warnMirrorSkipped(legacy,error){writeStderrLineSafe(`warning: could not mirror the review worktree lease to the pre-move path ${legacy} (${error.code??error}); the acquisition stands on the new-path lease, but builds from before the lease move will not see this lock.`)}__name(warnMirrorSkipped,"warnMirrorSkipped");function readLease(path){try{if(!lstatSync(path).isFile()){rmSync(path,{force:true,recursive:true});return null}}catch(error){if(error.code!=="ENOENT"){debugLogger.debug(`Failed to inspect review lease ${path}:`,error)}return null}try{const value=JSON.parse(readFileSync(path,"utf8"));if(typeof value.sessionId!=="string"||typeof value.promptId!=="string"||typeof value.target!=="string"||typeof value.repositoryRoot!=="string"||typeof value.worktreePath!=="string"||typeof value.branch!=="string"||value.identity!==void 0&&(typeof value.identity!=="number"||!Number.isFinite(value.identity))||value.mergeBaseSha!==void 0&&typeof value.mergeBaseSha!=="string"||value.priorMergeBaseSha!==void 0&&typeof value.priorMergeBaseSha!=="string"||value.mergeBaseStale!==void 0&&typeof value.mergeBaseStale!=="boolean"||value.priorMergeBaseStale!==void 0&&typeof value.priorMergeBaseStale!=="boolean"||value.priorMergeBaseCurrent!==void 0&&typeof value.priorMergeBaseCurrent!=="boolean"||value.priorMergeBaseResumable!==void 0&&typeof value.priorMergeBaseResumable!=="boolean"){return null}return value}catch(error){debugLogger.debug(`Failed to read review lease ${path}:`,error);return null}}__name(readLease,"readLease");function readReviewWorktreeLease(repositoryRoot,target){return readReviewWorktreeLeaseAt(repositoryRoot,target)?.lease??null}__name(readReviewWorktreeLease,"readReviewWorktreeLease");function readReviewWorktreeLeaseAt(repositoryRoot,target){if(!validTarget(target))return null;const root=resolve(repositoryRoot);const current=leasePath(root,target);const lease=readLease(current);return lease?{lease,path:current}:null}__name(readReviewWorktreeLeaseAt,"readReviewWorktreeLeaseAt");function reviewLeaseHeldByAnotherSession(lease){if(!lease)return false;const sessionId=process.env["QWEN_CODE_SESSION_ID"]?.trim();return!sessionId||lease.sessionId!==sessionId}__name(reviewLeaseHeldByAnotherSession,"reviewLeaseHeldByAnotherSession");function sameLease(a,b){return b!==null&&a.sessionId===b.sessionId&&a.promptId===b.promptId&&a.target===b.target&&a.repositoryRoot===b.repositoryRoot&&a.worktreePath===b.worktreePath&&a.branch===b.branch}__name(sameLease,"sameLease");function removeLeaseWorktree(lease,gitTimeout){const prMatch=/^pr-(\d+)$/.exec(lease.target);if(!prMatch||lease.branch!==reviewBranch(prMatch[1])){debugLogger.debug(`Rejected invalid review lease ${lease.target}`);return false}const repositoryRoot=resolve(lease.repositoryRoot);const worktreePath=resolve(lease.worktreePath);const reviewTmpRoot=resolve(repositoryRoot,REVIEW_TMP_DIR);const worktreeRelative=relative(reviewTmpRoot,worktreePath);if(worktreeRelative===""||worktreeRelative.startsWith("..")||isAbsolute(worktreeRelative)){debugLogger.debug(`Rejected review lease outside ${REVIEW_TMP_DIR}: ${worktreePath}`);return false}try{execFileSync("git",["-C",repositoryRoot,"worktree","remove",worktreePath,"--force"],gitOptions(gitTimeout))}catch(error){debugLogger.debug(`Git failed to remove review worktree ${lease.target}:`,error);try{rmSync(worktreePath,{recursive:true,force:true});execFileSync("git",["-C",repositoryRoot,"worktree","prune"],gitOptions(gitTimeout))}catch(fallbackError){debugLogger.debug(`Fallback failed to remove review worktree ${lease.target}:`,fallbackError);return false}}let branchExists=true;try{execFileSync("git",["-C",repositoryRoot,"show-ref","--verify","--quiet",`refs/heads/${lease.branch}`],gitOptions(gitTimeout))}catch(error){if(error.status!==1){debugLogger.debug(`Failed to inspect review branch ${lease.branch}:`,error);return false}branchExists=false}if(branchExists){try{execFileSync("git",["-C",repositoryRoot,"branch","-D",lease.branch],gitOptions(gitTimeout))}catch(error){debugLogger.debug(`Failed to delete review branch ${lease.branch}:`,error);return false}}return!existsSync(worktreePath)}__name(removeLeaseWorktree,"removeLeaseWorktree");function cleanupReviewWorktreeLeases(params){try{const repositoryRoot=resolve(params.repositoryRoot);const newLeaseDirectory=leaseDirectory(repositoryRoot);if(!existsSync(newLeaseDirectory))return;let entries;try{entries=readdirSync(newLeaseDirectory)}catch(error){debugLogger.debug(`Failed to list ${newLeaseDirectory} for lease cleanup:`,error);return}for(const entry of entries){if(!isReviewLeaseFile(entry))continue;const path=join(newLeaseDirectory,basename(entry));const lease=readLease(path);if(!lease||lease.sessionId!==params.sessionId||lease.promptId!==params.promptId||resolve(lease.repositoryRoot)!==repositoryRoot){continue}if(!removeLeaseWorktree(lease,params.gitTimeout??GIT_TIMEOUT_MS)){continue}rmSync(path,{force:true});reclaimBaseTreeTrust(repositoryRoot,lease.target);const twin=join(repositoryRoot,REVIEW_TMP_DIR,basename(entry));try{if(sameLease(lease,readLease(twin))){rmSync(twin,{force:true})}}catch(error){debugLogger.debug(`Failed to remove legacy lease twin ${twin}:`,error)}}}catch(error){debugLogger.debug("Failed to clean up review worktree leases:",error)}}__name(cleanupReviewWorktreeLeases,"cleanupReviewWorktreeLeases");export{isReviewLeaseFile,clearReviewWorktreeLease,clearReviewWorktreeLeaseIfOwned,recordReviewWorktreeLeaseMergeBase,restoreReviewWorktreeLeaseMergeBase,createReviewWorktreeLease,readReviewWorktreeLease,readReviewWorktreeLeaseAt,reviewLeaseHeldByAnotherSession,cleanupReviewWorktreeLeases};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{wrapForMultiplexer}from"./chunk-
|
|
3
|
+
import{wrapForMultiplexer}from"./chunk-G3COGFSZ.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var KITTY_CTRL_C="[99;5u";var KITTY_KEYCODE_ENTER=13;var KITTY_KEYCODE_NUMPAD_ENTER=57414;var KITTY_KEYCODE_TAB=9;var KITTY_KEYCODE_BACKSPACE=127;var KITTY_MODIFIER_BASE=1;var KITTY_MODIFIER_EVENT_TYPES_OFFSET=128;var MODIFIER_SHIFT_BIT=1;var MODIFIER_ALT_BIT=2;var MODIFIER_CTRL_BIT=4;var MODIFIER_SUPER_BIT=8;var CTRL_EXIT_PROMPT_DURATION_MS=1e3;var VSCODE_SHIFT_ENTER_SEQUENCE="\\\r\n";var BACKSLASH_ENTER_DETECTION_WINDOW_MS=5;var MAX_KITTY_SEQUENCE_LENGTH=32;var CHAR_CODE_ESC=27;init_esbuild_shims();import*as fs from"node:fs/promises";import{constants as fsConstants}from"node:fs";import{execSync,spawn}from"node:child_process";import*as path from"node:path";import{randomUUID}from"node:crypto";init_esbuild_shims();var ESC="\x1B";var BEL="\x07";var ST=ESC+"\\";var OSC_PREFIX=ESC+"]";var SEP=";";var OSC={ITERM2:9,KITTY:99,GHOSTTY:777,PROGRAM_STATUS:7501};function detectTerminal(){const termProgram=process.env["TERM_PROGRAM"];switch(termProgram){case"iTerm.app":return"iTerm.app";case"kitty":return"kitty";case"ghostty":return"ghostty";case"Apple_Terminal":return"Apple_Terminal";default:break}if(process.env["TERM"]==="xterm-ghostty"){return"ghostty"}if(process.env["TERM"]?.includes("kitty")){return"kitty"}if(process.env["KITTY_WINDOW_ID"])return"kitty";return"unknown"}__name(detectTerminal,"detectTerminal");function sanitizeOscPayload(text){return text.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\x80-\x9f]/g,"")}__name(sanitizeOscPayload,"sanitizeOscPayload");function osc(...parts){const isKitty=detectTerminal()==="kitty";const inScreen=!!process.env["STY"];const terminator=isKitty&&!inScreen?ST:BEL;const sanitized=parts.map(p=>typeof p==="string"?sanitizeOscPayload(p):p);return`${OSC_PREFIX}${sanitized.join(SEP)}${terminator}`}__name(osc,"osc");function encodeKittyPayload(text){return Buffer.from(text,"utf8").toString("base64")}__name(encodeKittyPayload,"encodeKittyPayload");function oscITerm2Notify(title,message){const displayString=title?`${title}:
|
|
4
4
|
${message}`:message;return osc(OSC.ITERM2,`
|
|
5
5
|
|
|
6
6
|
${displayString}`)}__name(oscITerm2Notify,"oscITerm2Notify");function oscKittyNotify(title,message,id){return[osc(OSC.KITTY,`i=${id}:d=0:p=title:e=1`,encodeKittyPayload(title)),osc(OSC.KITTY,`i=${id}:p=body:e=1`,encodeKittyPayload(message)),osc(OSC.KITTY,`i=${id}:d=1:a=focus`,"")]}__name(oscKittyNotify,"oscKittyNotify");function oscGhosttyNotify(title,message){return osc(OSC.GHOSTTY,"notify",title,message)}__name(oscGhosttyNotify,"oscGhosttyNotify");var PROGRAM_STATUS_APP="qwen-code";var PROGRAM_STATUS_MAX_MSG_BYTES=2048;function encodeProgramStatusMsg(msg){let text=msg.replace(/[\x00-\x1f\x7f\x80-\x9f\u2028\u2029]/g," ").trim();while(Buffer.byteLength(text,"utf8")>PROGRAM_STATUS_MAX_MSG_BYTES){text=Array.from(text).slice(0,-16).join("")}return Buffer.from(text,"utf8").toString("base64")}__name(encodeProgramStatusMsg,"encodeProgramStatusMsg");function oscProgramStatus(status){const pairs=[`state=${status.state}`];if(status.state==="blocked"&&status.kind){pairs.push(`kind=${status.kind}`)}pairs.push(`app=${PROGRAM_STATUS_APP}`);if(status.msg){const encoded=encodeProgramStatusMsg(status.msg);if(encoded)pairs.push(`msg=${encoded}`)}return`${OSC_PREFIX}${OSC.PROGRAM_STATUS}${SEP}${pairs.join(":")}${ST}`}__name(oscProgramStatus,"oscProgramStatus");function oscProgramStatusClear(){return`${OSC_PREFIX}${OSC.PROGRAM_STATUS}${SEP}state=clear${ST}`}__name(oscProgramStatusClear,"oscProgramStatusClear");function generateKittyId(){return Math.floor(Math.random()*2**31)}__name(generateKittyId,"generateKittyId");init_esbuild_shims();import{fileURLToPath}from"node:url";function isUncPath(candidate){return/^[\\/]{2}[^\\/]/.test(candidate)}__name(isUncPath,"isUncPath");function isFileUri(text){return/^file:/i.test(text)}__name(isFileUri,"isFileUri");function fileUriToLocalPath(uri){let url;try{url=new URL(uri)}catch{return null}if(url.protocol!=="file:"||url.host!==""){return null}try{const localPath=fileURLToPath(url);return isUncPath(localPath)?null:localPath}catch{return null}}__name(fileUriToLocalPath,"fileUriToLocalPath");var debugLogger=createDebugLogger("CLIPBOARD_UTILS");var PROCESS_TIMEOUT_MS=5e3;var MAX_CLIPBOARD_TEXT_BYTES=16*1024*1024;function writeOsc52(text){try{const MAX_OSC52_BYTES=75e3;if(Buffer.byteLength(text,"utf-8")>MAX_OSC52_BYTES){debugLogger.warn(`writeOsc52: text too large (${Buffer.byteLength(text,"utf-8")} bytes), skipping`);return false}const base64=Buffer.from(text,"utf-8").toString("base64");const sequence=wrapForMultiplexer(`\x1B]52;c;${base64}\x07`);const stream=process.stderr.isTTY?process.stderr:process.stdout.isTTY?process.stdout:null;if(!stream){debugLogger.warn("OSC 52 clipboard requires a TTY; stdout/stderr not connected to terminal");return false}stream.write(sequence,err=>{if(err)debugLogger.warn("writeOsc52: async write failed:",err)});return true}catch(e){debugLogger.warn("writeOsc52 failed:",e);return false}}__name(writeOsc52,"writeOsc52");var linuxClipboardTool;var cachedWlPasteTypes=null;var clipboardModulePromise=null;async function getClipboardModule(){if(!clipboardModulePromise){const modName="@teddyzhu/clipboard";clipboardModulePromise=import(modName).catch(()=>{debugLogger.error("Failed to load @teddyzhu/clipboard native module. Clipboard image features will be unavailable.");return null})}return clipboardModulePromise}__name(getClipboardModule,"getClipboardModule");function isWaylandSession(){return process.env["XDG_SESSION_TYPE"]?.toLowerCase()==="wayland"||Boolean(process.env["WAYLAND_DISPLAY"])}__name(isWaylandSession,"isWaylandSession");function getLinuxClipboardTool(){if(linuxClipboardTool!==void 0)return linuxClipboardTool;const sessionType=process.env["XDG_SESSION_TYPE"];const display=process.env["DISPLAY"];let toolName=null;if(isWaylandSession()){toolName="wl-paste"}else if(sessionType==="x11"||display){toolName="xclip"}else{linuxClipboardTool=null;return null}try{execSync("command -v "+toolName,{stdio:"ignore"});linuxClipboardTool=toolName;return toolName}catch{debugLogger.warn(`${toolName} not found`);linuxClipboardTool=null;return null}}__name(getLinuxClipboardTool,"getLinuxClipboardTool");async function saveFromCommand(command,args,destination){let fd;try{fd=await fs.open(destination,fsConstants.O_WRONLY|fsConstants.O_CREAT|fsConstants.O_EXCL)}catch{return false}return new Promise(resolve=>{const child=spawn(command,args,{stdio:["ignore","pipe","pipe"]});const fileStream=fd.createWriteStream();let stderr="";let resolved=false;const safeResolve=__name(value=>{if(!resolved){resolved=true;try{if(!child.killed)child.kill()}catch{}try{fileStream.destroy()}catch{}resolve(value)}},"safeResolve");const timer=setTimeout(()=>{debugLogger.debug(`${command} timed out after ${PROCESS_TIMEOUT_MS}ms`);safeResolve(false)},PROCESS_TIMEOUT_MS);child.stderr.on("data",data=>{stderr+=data.toString()});child.stdout.pipe(fileStream);child.stdout.on("error",err=>{debugLogger.debug(`stdout error for ${command}:`,err);clearTimeout(timer);safeResolve(false)});child.on("error",err=>{debugLogger.debug(`Failed to spawn ${command}:`,err);clearTimeout(timer);safeResolve(false)});fileStream.on("error",err=>{debugLogger.debug(`File stream error for ${destination}:`,err);clearTimeout(timer);safeResolve(false)});child.on("close",code=>{clearTimeout(timer);if(resolved)return;if(code!==0){debugLogger.debug(`${command} exited with code ${code}. Args: ${args.join(" ")}`);if(stderr)debugLogger.debug(`${command} stderr: ${stderr.trim()}`);safeResolve(false);return}const checkFile=__name(()=>{fs.stat(destination).then(stats=>{safeResolve(stats.size>0)}).catch(()=>{safeResolve(false)})},"checkFile");if(fileStream.writableFinished){checkFile()}else{fileStream.on("finish",checkFile);fileStream.on("close",()=>{if(!resolved)checkFile()})}})})}__name(saveFromCommand,"saveFromCommand");var EMPTY_CLIPBOARD_STDERR_MARKERS=["target TARGETS not available","no owner for the","Nothing is copied","No selection"];function isEmptyClipboardError(stderr){return EMPTY_CLIPBOARD_STDERR_MARKERS.some(marker=>stderr.includes(marker))}__name(isEmptyClipboardError,"isEmptyClipboardError");var CLIPBOARD_IMAGE_TYPES=new Set(["image/png","image/bmp"]);async function checkClipboardForImage(command,args,onUnavailable){if(command==="wl-paste"&&args.length===1&&args[0]==="--list-types"){const types=await getWlPasteImageTypes(onUnavailable);return types.length>0}return new Promise(resolve=>{try{const child=spawn(command,args,{stdio:["ignore","pipe","pipe"]});let stdout="";let stderr="";let settled=false;const timer=setTimeout(()=>{if(settled)return;settled=true;try{child.kill()}catch{}debugLogger.debug(`${command} timed out after ${PROCESS_TIMEOUT_MS}ms`);onUnavailable?.();resolve(false)},PROCESS_TIMEOUT_MS);child.stdout.on("data",data=>{stdout+=data.toString()});child.stderr.on("data",data=>{stderr+=data.toString()});child.on("close",code=>{clearTimeout(timer);if(settled)return;settled=true;if(code!==0){debugLogger.debug(`${command} exited with code ${code}. Args: ${args.join(" ")}`);if(stderr){debugLogger.debug(`${command} stderr: ${stderr.trim()}`)}if(isEmptyClipboardError(stderr)){resolve(false);return}onUnavailable?.();resolve(false);return}resolve(stdout.split("\n").map(line=>line.trim()).some(line=>CLIPBOARD_IMAGE_TYPES.has(line)))});child.on("error",err=>{clearTimeout(timer);if(settled)return;settled=true;debugLogger.debug(`Failed to spawn ${command}:`,err);onUnavailable?.();resolve(false)})}catch{onUnavailable?.();resolve(false)}})}__name(checkClipboardForImage,"checkClipboardForImage");async function clipboardHasImage(onUnavailable){cachedWlPasteTypes=null;if(process.platform==="linux"){try{const tool=getLinuxClipboardTool();if(tool==="wl-paste"){return checkClipboardForImage("wl-paste",["--list-types"],onUnavailable)}if(tool==="xclip"){return checkClipboardForImage("xclip",["-selection","clipboard","-t","TARGETS","-o"],onUnavailable)}onUnavailable?.()}catch(error){debugLogger.error("Error checking clipboard for image:",error)}return false}try{const mod=await getClipboardModule();if(!mod){onUnavailable?.();return false}const clipboard=new mod.ClipboardManager;return clipboard.hasFormat("image")}catch(error){debugLogger.error("Error checking clipboard for image:",error);onUnavailable?.();return false}}__name(clipboardHasImage,"clipboardHasImage");var PLAIN_TEXT_TYPES=new Set(["text/plain","utf8_string","string","text"]);var PLAIN_TIER_ORDER=["text/plain","utf8_string","string","text"];var BOOKKEEPING_TYPES=new Set(["targets","multiple","save_targets","delete","incr","timestamp","version"]);function baseTypeName(name){return name.trim().toLowerCase().split(";")[0].trim()}__name(baseTypeName,"baseTypeName");function classifyClipboardType(name){const base=baseTypeName(name);if(BOOKKEEPING_TYPES.has(base)){return null}if(PLAIN_TEXT_TYPES.has(base)){return"plain"}return base.startsWith("text/")?"other":null}__name(classifyClipboardType,"classifyClipboardType");function clipboardReadArgs(tool,type){return tool==="wl-paste"?["--no-newline","--type",type]:["-selection","clipboard","-t",type,"-o"]}__name(clipboardReadArgs,"clipboardReadArgs");var READ_DISCARDED_FOR_SIZE=Symbol("readDiscardedForSize");async function readStdout(command,args,latin1Fallback=false){return new Promise(resolve=>{let child;try{child=spawn(command,args,{stdio:["ignore","pipe","pipe"]})}catch(error){debugLogger.debug(`Failed to spawn ${command} ${args.join(" ")}:`,error);resolve("");return}const chunks=[];let received=0;let settled=false;const timer=setTimeout(()=>{if(settled)return;settled=true;try{child.kill()}catch{}debugLogger.debug(`${command} ${args.join(" ")} timed out after ${PROCESS_TIMEOUT_MS}ms`);resolve("")},PROCESS_TIMEOUT_MS);const done=__name(value=>{if(settled)return;settled=true;clearTimeout(timer);resolve(value)},"done");child.stdout.on("data",data=>{if(settled)return;received+=data.length;if(received>MAX_CLIPBOARD_TEXT_BYTES){try{child.kill()}catch{}debugLogger.debug(`${command} ${args.join(" ")} exceeded ${MAX_CLIPBOARD_TEXT_BYTES} bytes; discarding the read`);done(READ_DISCARDED_FOR_SIZE);return}chunks.push(data)});child.on("error",err=>{debugLogger.debug(`Failed to spawn ${command} ${args.join(" ")}:`,err);done("")});child.on("close",code=>{if(code===0){const bytes=Buffer.concat(chunks);let text;try{text=new TextDecoder("utf-8",{fatal:true}).decode(bytes)}catch{text=latin1Fallback?bytes.toString("latin1"):bytes.toString("utf8")}done(text)}else{debugLogger.debug(`${command} ${args.join(" ")} exited with code ${code}`);done("")}})})}__name(readStdout,"readStdout");async function listWlPasteTypes(onUnavailable){if(cachedWlPasteTypes!==null){return cachedWlPasteTypes}return new Promise(resolve=>{let child;try{child=spawn("wl-paste",["--list-types"],{stdio:["ignore","pipe","pipe"]})}catch(error){debugLogger.error("Failed to spawn wl-paste --list-types:",error);onUnavailable?.();resolve([]);return}let stdout="";let stderr="";let settled=false;const timer=setTimeout(()=>{if(settled)return;settled=true;try{child.kill()}catch{}debugLogger.debug(`wl-paste --list-types timed out after ${PROCESS_TIMEOUT_MS}ms`);onUnavailable?.();resolve([])},PROCESS_TIMEOUT_MS);child.stdout.on("data",data=>{stdout+=data.toString()});child.stderr.on("data",data=>{stderr+=data.toString()});child.on("close",code=>{clearTimeout(timer);if(settled)return;settled=true;if(code!==0){debugLogger.debug(`wl-paste --list-types exited with code ${code}`);if(stderr){debugLogger.debug(`wl-paste stderr: ${stderr.trim()}`)}if(!isEmptyClipboardError(stderr)){onUnavailable?.()}resolve([]);return}const types=stdout.trim().split("\n").map(type=>type.trim()).filter(Boolean);cachedWlPasteTypes=types;resolve(types)});child.on("error",err=>{clearTimeout(timer);if(settled)return;settled=true;debugLogger.debug("Failed to spawn wl-paste --list-types:",err);onUnavailable?.();resolve([])})})}__name(listWlPasteTypes,"listWlPasteTypes");async function getWlPasteImageTypes(onUnavailable){const types=await listWlPasteTypes(onUnavailable);return types.filter(type=>CLIPBOARD_IMAGE_TYPES.has(type))}__name(getWlPasteImageTypes,"getWlPasteImageTypes");async function listClipboardTypes(tool){const names=tool==="wl-paste"?await listWlPasteTypes():await readStdout(tool,["-selection","clipboard","-t","TARGETS","-o"]).then(targets=>typeof targets==="string"?targets.split(/\s+/):[]);const types=[];for(const name of names){const tier=classifyClipboardType(name);if(tier){types.push({raw:name,tier})}}return types}__name(listClipboardTypes,"listClipboardTypes");async function readClipboardText(){if(process.platform!=="linux"){return null}const tool=getLinuxClipboardTool();if(!tool){return null}const offers=await listClipboardTypes(tool);for(const tier of["plain","other"]){const tierOffers=offers.filter(offer=>offer.tier===tier);if(tier==="plain"){tierOffers.sort((a,b)=>PLAIN_TIER_ORDER.indexOf(baseTypeName(a.raw))-PLAIN_TIER_ORDER.indexOf(baseTypeName(b.raw)))}for(const type of tierOffers){const base=baseTypeName(type.raw);const result=await readStdout(tool,clipboardReadArgs(tool,type.raw),base==="string"||base==="text");if(result===READ_DISCARDED_FOR_SIZE){return null}if(result===""){continue}const text=result.replace(/\r\n/g,"\n").replace(/\r/g,"\n").replace(/\n+$/,"");const isUriList=base==="text/uri-list";const converted=isUriList?uriListToPaths(text):text;if(converted===""){if(isUriList){continue}return null}return converted.trim()?converted:null}}return null}__name(readClipboardText,"readClipboardText");function uriListToPaths(text){return text.split("\n").filter(line=>!line.startsWith("#")).map(line=>isFileUri(line)?fileUriToLocalPath(line)??line:line).join("\n")}__name(uriListToPaths,"uriListToPaths");async function saveFileWithWlPaste(tempFilePath){const imageTypes=await getWlPasteImageTypes();if(imageTypes.includes("image/png")){const success=await saveFromCommand("wl-paste",["--no-newline","--type","image/png"],tempFilePath);if(success)return tempFilePath;try{await fs.unlink(tempFilePath)}catch{}}if(imageTypes.includes("image/bmp")){const bmpPath=tempFilePath.replace(/\.png$/,".bmp");const bmpSuccess=await saveFromCommand("wl-paste",["--no-newline","--type","image/bmp"],bmpPath);if(bmpSuccess){try{await new Promise((resolve,reject)=>{const child=spawn("python3",["-c","import sys; from PIL import Image; Image.open(sys.argv[1]).save(sys.argv[2])",bmpPath,tempFilePath],{stdio:["ignore","ignore","pipe"]});let stderr="";child.stderr.on("data",d=>{stderr+=d.toString()});const timer=setTimeout(()=>{try{child.kill()}catch{}reject(new Error("python3 timed out"))},PROCESS_TIMEOUT_MS);child.on("close",code=>{clearTimeout(timer);if(code===0)resolve();else reject(new Error(`python3 exited with code ${code}${stderr?": "+stderr.trim():""}`))});child.on("error",err=>{clearTimeout(timer);reject(err)})});try{await fs.unlink(bmpPath)}catch{}return tempFilePath}catch(err){debugLogger.warn("BMP-to-PNG conversion failed (install python3-pil for BMP support):",err);try{await fs.unlink(bmpPath)}catch{}try{await fs.unlink(tempFilePath)}catch{}return false}}try{await fs.unlink(bmpPath)}catch{}}return false}__name(saveFileWithWlPaste,"saveFileWithWlPaste");async function saveFileWithXclip(tempFilePath){const success=await saveFromCommand("xclip",["-selection","clipboard","-t","image/png","-o"],tempFilePath);if(success)return true;try{await fs.unlink(tempFilePath)}catch{}return false}__name(saveFileWithXclip,"saveFileWithXclip");async function saveClipboardImage(targetDir){try{const baseDir=targetDir||process.cwd();const tempDir=path.join(baseDir,"clipboard");await fs.mkdir(tempDir,{recursive:true});const timestamp=new Date().getTime();if(process.platform==="linux"){const pngPath=path.join(tempDir,`clipboard-${timestamp}-${randomUUID()}.png`);const tool=getLinuxClipboardTool();if(tool==="wl-paste"){const savedPath=await saveFileWithWlPaste(pngPath);if(savedPath){try{const stats=await fs.stat(savedPath);if(stats.size>0)return savedPath;await fs.unlink(savedPath)}catch{}}return null}if(tool==="xclip"){if(await saveFileWithXclip(pngPath))return pngPath;return null}return null}const mod=await getClipboardModule();if(!mod)return null;const clipboard=new mod.ClipboardManager;if(!clipboard.hasFormat("image")){return null}const tempFilePath=path.join(tempDir,`clipboard-${timestamp}-${randomUUID()}.png`);const imageData=clipboard.getImageData();const buffer=imageData.data;if(!buffer){return null}await fs.writeFile(tempFilePath,buffer);return tempFilePath}catch(error){debugLogger.error("Error saving clipboard image:",error);return null}}__name(saveClipboardImage,"saveClipboardImage");async function cleanupOldClipboardImages(targetDir){try{const baseDir=targetDir||process.cwd();const tempDir=path.join(baseDir,"clipboard");const files=await fs.readdir(tempDir);const MAX_IMAGES=100;const CLEANUP_COUNT=50;const imageFiles=[];for(const file of files){if(file.startsWith("clipboard-")&&(file.endsWith(".png")||file.endsWith(".jpg")||file.endsWith(".webp")||file.endsWith(".heic")||file.endsWith(".heif")||file.endsWith(".tiff")||file.endsWith(".gif")||file.endsWith(".bmp"))){const filePath=path.join(tempDir,file);const stats=await fs.stat(filePath);imageFiles.push({name:file,path:filePath,atime:stats.atimeMs})}}if(imageFiles.length>MAX_IMAGES){imageFiles.sort((a,b)=>a.atime-b.atime);const removeCount=Math.min(CLEANUP_COUNT,imageFiles.length-MAX_IMAGES+CLEANUP_COUNT);const filesToRemove=imageFiles.slice(0,removeCount);for(const file of filesToRemove){await fs.unlink(file.path)}}}catch{}}__name(cleanupOldClipboardImages,"cleanupOldClipboardImages");export{KITTY_CTRL_C,KITTY_KEYCODE_ENTER,KITTY_KEYCODE_NUMPAD_ENTER,KITTY_KEYCODE_TAB,KITTY_KEYCODE_BACKSPACE,KITTY_MODIFIER_BASE,KITTY_MODIFIER_EVENT_TYPES_OFFSET,MODIFIER_SHIFT_BIT,MODIFIER_ALT_BIT,MODIFIER_CTRL_BIT,MODIFIER_SUPER_BIT,CTRL_EXIT_PROMPT_DURATION_MS,VSCODE_SHIFT_ENTER_SEQUENCE,BACKSLASH_ENTER_DETECTION_WINDOW_MS,MAX_KITTY_SEQUENCE_LENGTH,CHAR_CODE_ESC,BEL,OSC_PREFIX,detectTerminal,oscITerm2Notify,oscKittyNotify,oscGhosttyNotify,oscProgramStatus,oscProgramStatusClear,generateKittyId,isUncPath,isFileUri,fileUriToLocalPath,writeOsc52,isWaylandSession,clipboardHasImage,readClipboardText,saveClipboardImage,cleanupOldClipboardImages};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{useKeypress}from"./chunk-
|
|
3
|
+
import{useKeypress}from"./chunk-CNZS2RPX.js";import{require_react}from"./chunk-5QKDV4CD.js";import{t}from"./chunk-5YULNQF3.js";import{APPROVAL_MODES}from"./chunk-JZK2WGXA.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_react=__toESM(require_react(),1);var AUTO_MODE_FIRST_TIME_MESSAGE_KEY="auto_mode.entry_notice";var AUTO_MODE_FIRST_TIME_MESSAGE_FALLBACK="Auto mode enabled.\n An LLM classifier evaluates each tool call \u2014 safe actions auto-approve,\n risky ones are blocked. Exit: Shift+Tab or /approval-mode default.";var getAutoModeFirstTimeMessage=__name(()=>{const message=t(AUTO_MODE_FIRST_TIME_MESSAGE_KEY);return message===AUTO_MODE_FIRST_TIME_MESSAGE_KEY?AUTO_MODE_FIRST_TIME_MESSAGE_FALLBACK:message},"getAutoModeFirstTimeMessage");function useAutoAcceptIndicator({config,settings,addItem,onApprovalModeChange,shouldBlockTab,disabled}){const currentConfigValue=config.getApprovalMode();const[showAutoAcceptIndicator,setShowAutoAcceptIndicator]=(0,import_react.useState)(currentConfigValue);(0,import_react.useEffect)(()=>{setShowAutoAcceptIndicator(currentConfigValue)},[currentConfigValue]);(0,import_react.useEffect)(()=>{if(currentConfigValue==="auto"){emitAutoModeEntryNotices({config,settings,addItem})}},[]);useKeypress(key=>{const isShiftTab=key.shift&&key.name==="tab"&&!key.ctrl;const isWindowsTab=process.platform==="win32"&&key.name==="tab"&&!key.ctrl&&!key.meta;if(isShiftTab||isWindowsTab){if(isWindowsTab&&shouldBlockTab?.()){return}const currentMode=config.getApprovalMode();const currentIndex=APPROVAL_MODES.indexOf(currentMode);const nextIndex=currentIndex===-1?0:(currentIndex+1)%APPROVAL_MODES.length;const nextApprovalMode=APPROVAL_MODES[nextIndex];try{config.setApprovalMode(nextApprovalMode);setShowAutoAcceptIndicator(nextApprovalMode);if(nextApprovalMode==="auto"&¤tMode!=="auto"){emitAutoModeEntryNotices({config,settings,addItem})}onApprovalModeChange?.(nextApprovalMode)}catch(e){addItem?.({type:"info",text:e.message},Date.now())}}},{isActive:!disabled});return showAutoAcceptIndicator}__name(useAutoAcceptIndicator,"useAutoAcceptIndicator");function emitAutoModeEntryNotices(opts){const{config,settings,addItem}=opts;if(!addItem)return;const now=Date.now();const acknowledged=settings?.merged.ui?.autoModeAcknowledged===true;if(!acknowledged){addItem({type:"info",text:getAutoModeFirstTimeMessage()},now);if(settings){try{settings.setValue("User","ui.autoModeAcknowledged",true)}catch{}}}const pm=config.getPermissionManager?.();const stripped=pm?.getStrippedDangerousRules?.();if(stripped&&(stripped.persistent.length>0||stripped.session.length>0)){const lines=["\u2139 Auto mode temporarily disabled these allow rules"," (they would bypass the classifier):",...stripped.persistent.map(r=>` - ${r.raw} (from user settings)`),...stripped.session.map(r=>` - ${r.raw} (session)`)," These will be restored when leaving auto mode."];addItem({type:"info",text:lines.join("\n")},now+1)}}__name(emitAutoModeEntryNotices,"emitAutoModeEntryNotices");export{useAutoAcceptIndicator,emitAutoModeEntryNotices};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2025 Google LLC
|