@hostclubeos/miraos 0.0.8-beta → 0.0.9-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-YR2SA5XW.js → MaxSizedBox-6CGCRBRO.js} +1 -1
- package/chunks/{StandaloneSessionPicker-VEXSGLU4.js → StandaloneSessionPicker-7VQOS4TU.js} +1 -1
- package/chunks/{acp-subagent-executor-ATOLWCVC.js → acp-subagent-executor-BFQRCU7R.js} +1 -1
- package/chunks/{acpAgent-DN46FTZ2.js → acpAgent-PCXQRPNU.js} +3 -3
- package/chunks/{advisor-6MI5JQGC.js → advisor-WDZ5N5ZP.js} +1 -1
- package/chunks/{agent-6HPQ4XCT.js → agent-I7Q3IPSS.js} +1 -1
- package/chunks/{agent-headless-KXAJBOPG.js → agent-headless-6LOYWI5T.js} +1 -1
- package/chunks/{agent-host-client-NOZRE2ZR.js → agent-host-client-PZZKCNQF.js} +1 -1
- package/chunks/{agent-host-connections-6FOSHEWD.js → agent-host-connections-TWWSRTKJ.js} +1 -1
- package/chunks/{autofix-pr-IMJA2KZF.js → autofix-pr-RQPGPQ4D.js} +1 -1
- package/chunks/{batch-L5VJ4XGP.js → batch-UJD5TSBN.js} +1 -1
- package/chunks/{bridge-CCRTJSIM.js → bridge-4TYLRPXZ.js} +1 -1
- package/chunks/{channel-settings-store-SB7BP6XT.js → channel-settings-store-RENJMOQ5.js} +1 -1
- package/chunks/{chunk-UC455ZS7.js → chunk-24PHAWM3.js} +1 -1
- package/chunks/{chunk-CNGBG3X5.js → chunk-26JPBN6V.js} +1 -1
- package/chunks/{chunk-W4M6JXZB.js → chunk-2MQH3J4U.js} +1 -1
- package/chunks/{chunk-GS4FZF6I.js → chunk-2RXOWQSQ.js} +1 -1
- package/chunks/{chunk-LRXYXGMT.js → chunk-323HUW2T.js} +1 -1
- package/chunks/{chunk-7DJYSBNJ.js → chunk-3BHXE7CB.js} +1 -1
- package/chunks/{chunk-7Q6RNE77.js → chunk-3GYAEXAA.js} +1 -1
- package/chunks/{chunk-VOIC5ZW2.js → chunk-3YBZW4HP.js} +1 -1
- package/chunks/{chunk-JRIVHFCG.js → chunk-4RJ2RRGZ.js} +1 -1
- package/chunks/{chunk-3NA5O4QO.js → chunk-5DIW4X4P.js} +1 -1
- package/chunks/{chunk-YELFN6AG.js → chunk-5GB6JNJX.js} +1 -1
- package/chunks/{chunk-6TNX3S5H.js → chunk-5HSNCG73.js} +2 -2
- package/chunks/{chunk-FC5IAX56.js → chunk-6HDMM7TJ.js} +1 -1
- package/chunks/{chunk-CJLKKIUW.js → chunk-6STNGEYC.js} +1 -1
- package/chunks/{chunk-ZJOVJLIH.js → chunk-7EFWNFJJ.js} +1 -1
- package/chunks/{chunk-SMO4PEHK.js → chunk-7EWIKIJI.js} +1 -1
- package/chunks/{chunk-S5NTCBEI.js → chunk-7TB6VG72.js} +1 -1
- package/chunks/{chunk-6AAVML2M.js → chunk-7TLL4JLR.js} +1 -1
- package/chunks/{chunk-IWIGJDPL.js → chunk-AOMXZNMX.js} +1 -1
- package/chunks/{chunk-5YULNQF3.js → chunk-AUM57JI2.js} +1 -1
- package/chunks/{chunk-ZQZK267X.js → chunk-AW5UCOZO.js} +1 -1
- package/chunks/{chunk-D4WMUCSK.js → chunk-C6HVNDQT.js} +2 -2
- package/chunks/{chunk-2DPE27WB.js → chunk-CC6E5CQV.js} +1 -1
- package/chunks/{chunk-SK5C26Y6.js → chunk-CLKUQP27.js} +1 -1
- package/chunks/{chunk-ARILWFTZ.js → chunk-DFMQQM4M.js} +1 -1
- package/chunks/{chunk-IJIQDCNJ.js → chunk-DP7LJTG2.js} +5 -5
- package/chunks/{chunk-7EEWU6XO.js → chunk-DQT5VL7G.js} +1 -1
- package/chunks/{chunk-AHV4IMUX.js → chunk-E4QOAV5O.js} +1 -1
- package/chunks/{chunk-G3COGFSZ.js → chunk-E4REGDEZ.js} +1 -1
- package/chunks/{chunk-MOXZO5PM.js → chunk-EAG7VZJJ.js} +1 -1
- package/chunks/{chunk-GQ24VFGQ.js → chunk-EFO6J22W.js} +1 -1
- package/chunks/{chunk-IJH5HZTB.js → chunk-EMR4QK2F.js} +1 -1
- package/chunks/{chunk-YFXKRGHT.js → chunk-EYECE2PH.js} +1 -1
- package/chunks/{chunk-7HO5DQ6V.js → chunk-EZDXHUHB.js} +1 -1
- package/chunks/{chunk-66N3SLXJ.js → chunk-FJFTKA4H.js} +1 -1
- package/chunks/{chunk-DNCXESHL.js → chunk-FSLDNLNU.js} +1 -1
- package/chunks/{chunk-K3RWL2YH.js → chunk-FSRXTX3N.js} +1 -1
- package/chunks/{chunk-4RRQ7CPF.js → chunk-FWSXFRIQ.js} +1 -1
- package/chunks/{chunk-M3IQE5G4.js → chunk-G4ATLMDH.js} +1 -1
- package/chunks/{chunk-WUZ53TKN.js → chunk-GAS3HKRX.js} +1 -1
- package/chunks/{chunk-LTXZHHNK.js → chunk-GFFL2LR2.js} +1 -1
- package/chunks/{chunk-IK5TB2CB.js → chunk-GYFIY7TD.js} +1 -1
- package/chunks/{chunk-XJKDC7OE.js → chunk-GYXRI4P5.js} +1 -1
- package/chunks/{chunk-4C5BOFDC.js → chunk-H3U7DXIU.js} +1 -1
- package/chunks/{chunk-5AJKMBPM.js → chunk-HEDVPRMD.js} +1 -1
- package/chunks/{chunk-32DLSPV5.js → chunk-HI3644FQ.js} +1 -1
- package/chunks/{chunk-CLLQQMTU.js → chunk-HTHYLMBO.js} +1 -1
- package/chunks/{chunk-VAFRD2H4.js → chunk-IW7RPDV2.js} +1 -1
- package/chunks/{chunk-5BWVS5D3.js → chunk-IXQI4K6O.js} +1 -1
- package/chunks/{chunk-BWLMXGA2.js → chunk-IYH3IZL4.js} +1 -1
- package/chunks/{chunk-XGPGIMZK.js → chunk-J52J35K4.js} +1 -1
- package/chunks/{chunk-BWFZEDYG.js → chunk-J7L5IHLG.js} +1 -1
- package/chunks/{chunk-6STDVRH5.js → chunk-JHS5B4N7.js} +2 -2
- package/chunks/{chunk-EHM4KL2U.js → chunk-JRSO5ZGU.js} +1 -1
- package/chunks/{chunk-NYGJ53Y7.js → chunk-JS6VAGRQ.js} +1 -1
- package/chunks/{chunk-QCSGHQ2P.js → chunk-KAFPULGU.js} +1 -1
- package/chunks/{chunk-CNZS2RPX.js → chunk-LDP47G5M.js} +1 -1
- package/chunks/{chunk-GM6YF6IS.js → chunk-LMZZWPKA.js} +1 -1
- package/chunks/{chunk-5SX4UPMN.js → chunk-LNCELICB.js} +1 -1
- package/chunks/{chunk-K2PGOAJP.js → chunk-LY2DRNTZ.js} +1 -1
- package/chunks/{chunk-KZZ5ZQHX.js → chunk-MMGGGYSJ.js} +1 -1
- package/chunks/{chunk-SVNSF5ZH.js → chunk-MTBU2ZIM.js} +1 -1
- package/chunks/{chunk-MV7LX23I.js → chunk-N27KICJQ.js} +1 -1
- package/chunks/{chunk-OPFBBIAQ.js → chunk-NHYFTK4O.js} +1 -1
- package/chunks/{chunk-NUDHRTIM.js → chunk-NRDHXSEE.js} +1 -1
- package/chunks/{chunk-QZNCYZ7H.js → chunk-NV5VVTYQ.js} +1 -1
- package/chunks/{chunk-7GU7HKIT.js → chunk-OEDMFKZL.js} +1 -1
- package/chunks/{chunk-V3ASW57P.js → chunk-OQAVMR6K.js} +1 -1
- package/chunks/{chunk-GBEQD55S.js → chunk-OY3Y6EMV.js} +1 -1
- package/chunks/{chunk-G7D42XGP.js → chunk-OZL4ZMGQ.js} +2 -2
- package/chunks/{chunk-PGKVSOWW.js → chunk-PKSPKVFH.js} +1 -1
- package/chunks/{chunk-OXG4BLFF.js → chunk-PNFKCYZT.js} +1 -1
- package/chunks/{chunk-JT5EN5MI.js → chunk-PTWHFVGG.js} +2 -2
- package/chunks/{chunk-3VKLOQ2P.js → chunk-QJ6ZTZFC.js} +1 -1
- package/chunks/{chunk-WZAUO3LV.js → chunk-QRGWB7IX.js} +1 -1
- package/chunks/{chunk-JCWNB45W.js → chunk-QRP2GXQD.js} +1 -1
- package/chunks/{chunk-CEVKKM22.js → chunk-RES5ET63.js} +1 -1
- package/chunks/{chunk-HCKF74X7.js → chunk-ROSJCTWB.js} +1 -1
- package/chunks/{chunk-WJXADORN.js → chunk-RR3NFNWL.js} +1 -1
- package/chunks/{chunk-HCCONFJY.js → chunk-RYQDRFLW.js} +1 -1
- package/chunks/{chunk-WSXRO2YB.js → chunk-S7CWSAUQ.js} +1 -1
- package/chunks/{chunk-MXFS555I.js → chunk-SAJKF4WS.js} +1 -1
- package/chunks/chunk-SINRWOVD.js +36 -0
- package/chunks/{chunk-DNXQKR5E.js → chunk-SJNQ6I23.js} +1 -1
- package/chunks/{chunk-DTRSC73M.js → chunk-T2GM4S4G.js} +3 -3
- package/chunks/{chunk-C3ZJUOTJ.js → chunk-TCQJO42E.js} +1 -1
- package/chunks/{chunk-G4OSEVOV.js → chunk-TIIDF23U.js} +2 -2
- package/chunks/{chunk-NNYAXFFN.js → chunk-TKH5R7RZ.js} +1 -1
- package/chunks/{chunk-JHGMLUAL.js → chunk-TSRTZD3X.js} +1 -1
- package/chunks/{chunk-GXNGLDUN.js → chunk-UXSXKLRH.js} +1 -1
- package/chunks/{chunk-MCY3IS2E.js → chunk-UYI5AMPI.js} +1 -1
- package/chunks/{chunk-7L4MR4QM.js → chunk-VO6SPDH4.js} +1 -1
- package/chunks/{chunk-SPCIIUIG.js → chunk-VRIHYTDI.js} +1 -1
- package/chunks/{chunk-Q4NEZZ6L.js → chunk-VT47A26Q.js} +1 -1
- package/chunks/{chunk-E743PFSX.js → chunk-VZOZUCZX.js} +1 -1
- package/chunks/{chunk-WW43VZ6O.js → chunk-WLEGTKGA.js} +1 -1
- package/chunks/{chunk-77GGGTWS.js → chunk-XHCJN4A2.js} +1 -1
- package/chunks/{chunk-UZAFPEVN.js → chunk-XTRZ5PHG.js} +1 -1
- package/chunks/{chunk-DTNW2CM3.js → chunk-Y4GZOZWD.js} +1 -1
- package/chunks/{chunk-YOBM4ZFW.js → chunk-YUCAGV52.js} +2 -2
- package/chunks/{chunk-WOMJLK3E.js → chunk-YWQM4TSO.js} +1 -1
- package/chunks/{chunk-WN6Z3J27.js → chunk-YYTOHY4V.js} +1 -1
- package/chunks/{chunk-VOCM2M4K.js → chunk-Z25W2S5N.js} +1 -1
- package/chunks/{chunk-QWNTORRT.js → chunk-Z6GECBAJ.js} +1 -1
- package/chunks/{chunk-XNP5JXCS.js → chunk-ZJU4B4WX.js} +1 -1
- package/chunks/{chunk-MCHMWRNO.js → chunk-ZSHDQPAO.js} +1 -1
- package/chunks/{chunk-POMEWCFJ.js → chunk-ZUWLTGSR.js} +6 -6
- package/chunks/{codex-subagent-executor-TPO62HU5.js → codex-subagent-executor-2V4NB7IR.js} +1 -1
- package/chunks/{config-utils-6GWIYBUK.js → config-utils-5B2LYCON.js} +1 -1
- package/chunks/{contextCommand-WWVGDTOL.js → contextCommand-UPQGRXWK.js} +1 -1
- package/chunks/{core-runtime-ASQR33TV.js → core-runtime-DPMH2BXK.js} +1 -1
- package/chunks/{create-sub-session-XY2FXSPE.js → create-sub-session-EJVB3FE5.js} +1 -1
- package/chunks/{cron-create-HY3TLNV2.js → cron-create-V2A7PMQC.js} +1 -1
- package/chunks/{daemon-git-worktree-guard-ILW3NJJC.js → daemon-git-worktree-guard-YEIMR2X7.js} +1 -1
- package/chunks/{daemon-status-provider-JVOGEKWY.js → daemon-status-provider-6BRB5TG3.js} +1 -1
- package/chunks/{daemon-trust-policy-XXRBG4JE.js → daemon-trust-policy-BEXVFO4M.js} +1 -1
- package/chunks/{daemon-trust-policy-monitor-UL73ADOZ.js → daemon-trust-policy-monitor-BVS6LXBX.js} +1 -1
- package/chunks/{deferred-core-runtime-PT747R7S.js → deferred-core-runtime-NTKFHL5J.js} +1 -1
- package/chunks/{edit-4PJ3NPFA.js → edit-LRG3TMHP.js} +1 -1
- package/chunks/{enterPlanMode-KQ62QN7S.js → enterPlanMode-KOUSHJHR.js} +1 -1
- package/chunks/{environment-H4HADXGA.js → environment-54CM3OXE.js} +1 -1
- package/chunks/{errors-OSD4ZZGR.js → errors-D6XR3NH4.js} +1 -1
- package/chunks/{execution-tool-PHHGLKWC.js → execution-tool-7RZ2JLEK.js} +1 -1
- package/chunks/{execution-worker-MH3CV66T.js → execution-worker-LXQ7WAFG.js} +1 -1
- package/chunks/{exitPlanMode-OU5YP4XN.js → exitPlanMode-4FGFA2QC.js} +1 -1
- package/chunks/{fast-path-WKOMHBWN.js → fast-path-4B7OKPYK.js} +1 -1
- package/chunks/{glob-FYCOEQPM.js → glob-N2D7SY23.js} +1 -1
- package/chunks/{goal-tools-T27GSDNM.js → goal-tools-7RNSDRFO.js} +1 -1
- package/chunks/{handleAutoUpdate-XXCPJLKO.js → handleAutoUpdate-PKKJQAKG.js} +1 -1
- package/chunks/{i18n-3B2PRJM2.js → i18n-F3OAHCLJ.js} +1 -1
- package/chunks/{initializer-HSFVDRTR.js → initializer-OL3DDWR7.js} +1 -1
- package/chunks/{installationInfo-SJJ2DYZ6.js → installationInfo-D2L743RV.js} +1 -1
- package/chunks/{interactive-mod-session-BWY2JRSQ.js → interactive-mod-session-2GXRCQKR.js} +1 -1
- package/chunks/{list-TGCI3MBM.js → list-PU7ZXBY5.js} +1 -1
- package/chunks/{llm-FYR73GKD.js → llm-V42HGUVH.js} +4 -4
- package/chunks/{loadedSettingsAdapter-DUDCINQL.js → loadedSettingsAdapter-KAEVWWRX.js} +1 -1
- package/chunks/{local-7PEOBJKE.js → local-KM5F5RAB.js} +1 -1
- package/chunks/{local-execution-environment-Q4OOA7BL.js → local-execution-environment-OEO2KW3M.js} +1 -1
- package/chunks/{loggingContentGenerator-VVESQOIQ.js → loggingContentGenerator-DQLXSDZR.js} +1 -1
- package/chunks/{loop-wakeup-M2XLAAKZ.js → loop-wakeup-CJICM24Y.js} +1 -1
- package/chunks/{manage-memory-FRVWHM2C.js → manage-memory-7CV6LF4C.js} +1 -1
- package/chunks/{managed-execution-engine-AVIM6AQU.js → managed-execution-engine-JEAIQ7L4.js} +1 -1
- package/chunks/{managed-local-serve-GIXHGFIU.js → managed-local-serve-KA37YWRW.js} +1 -1
- package/chunks/{managed-npm-update-3QSXGSHW.js → managed-npm-update-TSUUH3NN.js} +1 -1
- package/chunks/{managed-runtime-attestation-worker-ML4TCRAW.js → managed-runtime-attestation-worker-PUZ2ECM5.js} +1 -1
- package/chunks/{managed-runtime-bootstrap-JWJFGLBM.js → managed-runtime-bootstrap-SERIRKPD.js} +1 -1
- package/chunks/{managed-runtime-session-worker-4ISKROGZ.js → managed-runtime-session-worker-UOXK63YX.js} +1 -1
- package/chunks/{managed-runtime-ssh-worker-C44V2CPM.js → managed-runtime-ssh-worker-VKZYIX6R.js} +1 -1
- package/chunks/{managed-session-authority-UJ3FSKMD.js → managed-session-authority-5FYS3G3M.js} +1 -1
- package/chunks/{mcp-BWCLHHZ6.js → mcp-TRPV3K74.js} +1 -1
- package/chunks/{memory-5XQ2JVNS.js → memory-5CMNRPM2.js} +1 -1
- package/chunks/{model-call-collection-DXK2SIDR.js → model-call-collection-S4JKVFUO.js} +1 -1
- package/chunks/{model-configuration-6OLZS4C3.js → model-configuration-NEIDLKWQ.js} +1 -1
- package/chunks/{modelConfigUtils-5S5PC2RR.js → modelConfigUtils-LZLQOZKJ.js} +1 -1
- package/chunks/{monitor-6GKCWWUI.js → monitor-5MNKK5AO.js} +1 -1
- package/chunks/{nonInteractiveCli-ROHAB2H7.js → nonInteractiveCli-DDTGU2ER.js} +1 -1
- package/chunks/{nonInteractiveToolExecutor-OWCCSC5Y.js → nonInteractiveToolExecutor-N7PCYCKO.js} +1 -1
- package/chunks/{notebook-edit-WNRQ3QJZ.js → notebook-edit-7HIBTFFW.js} +1 -1
- package/chunks/{omni-DJ5RGNKA.js → omni-MX7BMOL5.js} +1 -1
- package/chunks/{openaiContentGenerator-237NVB63.js → openaiContentGenerator-NOIIZNRX.js} +1 -1
- package/chunks/{openaiResponsesContentGenerator-J33TCZKQ.js → openaiResponsesContentGenerator-5JJ6G7RS.js} +1 -1
- package/chunks/{pidfile-F7IYTFLX.js → pidfile-OHAGZOTV.js} +1 -1
- package/chunks/{processUtils-C6CSXITS.js → processUtils-TCDNCYVB.js} +1 -1
- package/chunks/{prompt-terminal-ledger-ZGYWPFJF.js → prompt-terminal-ledger-4ZUOCMOS.js} +1 -1
- package/chunks/{reactive-degrade-QKXPZQ3W.js → reactive-degrade-C7CGUJNP.js} +1 -1
- package/chunks/{read-file-GSNUMHRE.js → read-file-L4ZF6VDG.js} +1 -1
- package/chunks/{resumeHistoryUtils-4GUCHQGU.js → resumeHistoryUtils-WK3I4OIL.js} +1 -1
- package/chunks/{review-M2QGZFIO.js → review-F6JGI2LP.js} +1 -1
- package/chunks/{ripGrep-X4JTJZC6.js → ripGrep-L6M2GPCM.js} +1 -1
- package/chunks/{run-qwen-serve-4WW37RL2.js → run-qwen-serve-D5HB55SC.js} +1 -1
- package/chunks/{runtime-EFHJ6REE.js → runtime-CH3RAOQL.js} +1 -1
- package/chunks/{sandboxConfig-5XMIRDS4.js → sandboxConfig-EADWCO37.js} +1 -1
- package/chunks/{scheduled-tasks-ZCYM5YQJ.js → scheduled-tasks-PBKD4BHY.js} +1 -1
- package/chunks/{scheduler-5UAKCD5Z.js → scheduler-U5K3523K.js} +1 -1
- package/chunks/{search-memory-KKPYK33Q.js → search-memory-Y2IPKBDP.js} +1 -1
- package/chunks/{send-message-KOZRSWXO.js → send-message-JJQG2S6D.js} +1 -1
- package/chunks/{serve-5HSHEBMT.js → serve-2ZYS47MO.js} +1 -1
- package/chunks/{server-MC6KHP3G.js → server-5GMO4IHU.js} +3 -3
- package/chunks/{session-Z5HFG4IQ.js → session-LLOOVSHK.js} +1 -1
- package/chunks/{session-attachments-root-K2E5ETD4.js → session-attachments-root-XCLXH2XO.js} +1 -1
- package/chunks/{session-execution-engine-selector-NZA6CAJB.js → session-execution-engine-selector-5QPWJZSF.js} +1 -1
- package/chunks/{session-pr-refresh-OYJ56U3L.js → session-pr-refresh-MDBOAN3R.js} +1 -1
- package/chunks/{sessionService-BC56MX3G.js → sessionService-VKAHCTCC.js} +1 -1
- package/chunks/{settings-OHB77GXH.js → settings-ULEB2IYZ.js} +1 -1
- package/chunks/{shell-VKSH7JVL.js → shell-RBEKIYKU.js} +1 -1
- package/chunks/{skill-HQ4C2C3X.js → skill-GEVOEFMZ.js} +1 -1
- package/chunks/{skill-settings-6WPQFE3V.js → skill-settings-4IMGLYJW.js} +1 -1
- package/chunks/{spawnChannel-MXKVLS24.js → spawnChannel-B7L5PWQ6.js} +1 -1
- package/chunks/{standalone-update-NZP3OAZZ.js → standalone-update-SYQM6NOC.js} +1 -1
- package/chunks/{start-opentui-ui-25YQQD3O.js → start-opentui-ui-N427PLF4.js} +2 -2
- package/chunks/{startInteractiveUI-DWQJNIIV.js → startInteractiveUI-AS6GZKJJ.js} +1 -1
- package/chunks/{team-create-RSD7IADX.js → team-create-MN6FHUHU.js} +1 -1
- package/chunks/{team-plan-approval-XAOKZ6BR.js → team-plan-approval-OUYBIT7H.js} +1 -1
- package/chunks/{terminal-image-renderer-P5AGEOYS.js → terminal-image-renderer-MXZDUEOS.js} +1 -1
- package/chunks/{theme-manager-YBKJYPVQ.js → theme-manager-QOYSKWFK.js} +1 -1
- package/chunks/{tool-call-HJCSPR6N.js → tool-call-Q5NLEQFD.js} +1 -1
- package/chunks/{tool-result-media-SPWVV3OS.js → tool-result-media-NZJZTOBQ.js} +1 -1
- package/chunks/{tool-search-YWCOODLL.js → tool-search-D6Y45RNQ.js} +1 -1
- package/chunks/{total-session-admission-HKACVEI2.js → total-session-admission-36W7MDHP.js} +1 -1
- package/chunks/{trustedFolders-BXLZULWO.js → trustedFolders-XW5VH6HK.js} +1 -1
- package/chunks/{update-relaunch-CBJVLG6S.js → update-relaunch-KQPR2HAP.js} +1 -1
- package/chunks/{updateCheck-2J6RY3L3.js → updateCheck-SRW67WAX.js} +1 -1
- package/chunks/{upload-config-EN5XYA3V.js → upload-config-BTJNYMRX.js} +1 -1
- package/chunks/{useAutoAcceptIndicator-LF7VIUER.js → useAutoAcceptIndicator-N3RRUBSL.js} +1 -1
- package/chunks/{validateNonInterActiveAuth-63TR5JOG.js → validateNonInterActiveAuth-SWNH4FY4.js} +1 -1
- package/chunks/{version-F22SKNME.js → version-6R6LSGXO.js} +1 -1
- package/chunks/{web-fetch-ULH7TOLR.js → web-fetch-Y7LBAU3R.js} +1 -1
- package/chunks/{web-search-C3ORWAWR.js → web-search-IB4NYYUH.js} +1 -1
- package/chunks/{workflow-4ATPGZ5N.js → workflow-TR4YIPJO.js} +1 -1
- package/chunks/{workflow-ancestor-trust-AJ27EBZD.js → workflow-ancestor-trust-AHDUBOR7.js} +1 -1
- package/chunks/{workspace-agents-VLAJGYJF.js → workspace-agents-MY2NFL6A.js} +1 -1
- package/chunks/{workspace-providers-status-TFAXNJ6L.js → workspace-providers-status-DNCCKFVE.js} +1 -1
- package/chunks/{workspace-recovery-worker-GKYYJPXV.js → workspace-recovery-worker-22VK4T4R.js} +1 -1
- package/chunks/{workspace-registration-store-ANR3STGQ.js → workspace-registration-store-64TGRRGC.js} +1 -1
- package/chunks/{workspace-registry-OVHNLVBM.js → workspace-registry-E6LFL5GL.js} +1 -1
- package/chunks/{workspace-runtime-coordinator-IEN2G7JP.js → workspace-runtime-coordinator-UHJHBIQT.js} +1 -1
- package/chunks/{workspace-service-NISFZTBE.js → workspace-service-OVEYIQOC.js} +1 -1
- package/chunks/{workspace-skills-status-QRF5ZXMT.js → workspace-skills-status-3NKXA5SK.js} +1 -1
- package/chunks/{workspace-trust-reconciler-X3XMX2GJ.js → workspace-trust-reconciler-JF7YHR52.js} +1 -1
- package/chunks/{write-file-SF42KZAH.js → write-file-FSTHYKKZ.js} +1 -1
- package/chunks/{zoom-image-4UMB6G3P.js → zoom-image-JP3EUDXE.js} +1 -1
- package/cli.js +2 -2
- package/execution-worker.js +1 -1
- package/package.json +2 -2
- package/chunks/chunk-OHOG4HSN.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-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}
|
|
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-QRGWB7IX.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-RBEKIYKU.js")).ShellTool;break;case ToolNames.EDIT:builtin=await this.resolveTool(name2)instanceof(await import("./edit-LRG3TMHP.js")).EditTool;break;case ToolNames.WRITE_FILE:builtin=await this.resolveTool(name2)instanceof(await import("./write-file-FSTHYKKZ.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{getPackageJson}from"./chunk-6KMPLONS.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();async function getCliVersion(){const pkgJson=await getPackageJson();return"0.0.
|
|
3
|
+
import{getPackageJson}from"./chunk-6KMPLONS.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();async function getCliVersion(){const pkgJson=await getPackageJson();return"0.0.9-beta"}__name(getCliVersion,"getCliVersion");function formatVersionLabel(version){return/^\d/.test(version)?`v${version}`:version}__name(formatVersionLabel,"formatVersionLabel");export{getCliVersion,formatVersionLabel};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2025 Google LLC
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{checkTeamMemorySecrets}from"./chunk-VFFTE2PS.js";import{buildWorkspaceArtifactCandidate,formatRecordArtifactReminder}from"./chunk-54CHQYA3.js";import{CommitAttributionService,createPatchSmart,detectLineEnding,getDiffStat}from"./chunk-POMEWCFJ.js";import{backgroundFixHolding}from"./chunk-B5ZFH363.js";import{getCurrentAgentId}from"./chunk-KP77CL5U.js";import{FileOperationEvent,logFileOperation}from"./chunk-MJEL7DIE.js";import{findCellIndex,getCellDisplayId,getNotebookLanguage,getSpecificMimeType,hasStableCellIds,inferInsertedCellSourceArrayStyle,inferNotebookJsonFormat,isAmbiguousCellId,makeCellId,normalizeEditedCell,normalizeSource,parseNotebook,serializeNotebook,toNotebookSource}from"./chunk-6JHMYZNS.js";import{BaseDeclarativeTool,BaseToolInvocation,StructuredToolError}from"./chunk-D6CEQ2GY.js";import{ToolDisplayNames,ToolNames}from"./chunk-SBZFGYYS.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{makeRelative,shortenPath,unescapePath}from"./chunk-2ZK2FGZQ.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs";import*as path from"node:path";var debugLogger=createDebugLogger("NOTEBOOK_EDIT");function rejectNotebookPriorRead(notebookPath,reason,decision){debugLogger.debug("prior-read-rejected",{path:notebookPath,reason,type:decision.type,displayMessage:decision.displayMessage});return decision}__name(rejectNotebookPriorRead,"rejectNotebookPriorRead");var NotebookEditError=class extends Error{constructor(message,type){super(message);this.type=type;this.name="NotebookEditError"}static{__name(this,"NotebookEditError")}};function requireNotebookSource(source,mode){if(mode==="delete"){return""}if(typeof source!=="string"){throw new NotebookEditError(`new_source is required when edit_mode is "${mode}".`,"invalid_tool_params")}return source}__name(requireNotebookSource,"requireNotebookSource");function displayCellId(cell,index){return cell?getCellDisplayId(cell,index):`cell-${index}`}__name(displayCellId,"displayCellId");function resolveTargetIndex(notebook,cellId,mode){if(!cellId){if(mode==="insert"){return-1}throw new NotebookEditError("cell_id is required for replace and delete operations.","invalid_tool_params")}if(isAmbiguousCellId(notebook,cellId)){throw new NotebookEditError(`Cell ID "${cellId}" is ambiguous in the rendered notebook. Re-read the notebook and target a stable real cell ID before editing.`,"invalid_tool_params")}const index=findCellIndex(notebook,cellId);if(index===-1){throw new NotebookEditError(`Cell with ID "${cellId}" not found in notebook.`,"notebook_cell_not_found")}return index}__name(resolveTargetIndex,"resolveTargetIndex");function createNotebookCell(notebook,cellType,source,preferSourceArray){const cell={cell_type:cellType,metadata:{},source:toNotebookSource(source,preferSourceArray)};const id=makeCellId(notebook);if(id){cell.id=id}normalizeEditedCell(cell,cellType);return cell}__name(createNotebookCell,"createNotebookCell");function applyNotebookEdit(rawContent,params){let notebook;try{notebook=parseNotebook(rawContent)}catch(error){throw new NotebookEditError(error instanceof Error?error.message:String(error),"notebook_invalid_json")}const mode=params.edit_mode??"replace";const source=requireNotebookSource(params.new_source,mode);const originalHasStableCellIds=hasStableCellIds(notebook);const targetIndex=resolveTargetIndex(notebook,params.cell_id,mode);const language=getNotebookLanguage(notebook);const jsonFormat=inferNotebookJsonFormat(rawContent);const buildResult=__name((updatedNotebook,result)=>{const structuralEdit=mode==="insert"||mode==="delete";return{...result,updatedContent:serializeNotebook(updatedNotebook,jsonFormat),requiresReadAfterWrite:structuralEdit&&!(originalHasStableCellIds&&hasStableCellIds(updatedNotebook))}},"buildResult");switch(mode){case"insert":{const cellType=params.cell_type??"code";const insertAt=targetIndex===-1?0:targetIndex+1;const newCell=createNotebookCell(notebook,cellType,source,inferInsertedCellSourceArrayStyle(notebook,insertAt));notebook.cells.splice(insertAt,0,newCell);return buildResult(notebook,{editedCellId:displayCellId(newCell,insertAt),editedCellType:cellType,language,mode})}case"delete":{const[removed]=notebook.cells.splice(targetIndex,1);return buildResult(notebook,{editedCellId:displayCellId(removed,targetIndex),editedCellType:removed?.cell_type,language,mode})}case"replace":{const target=notebook.cells[targetIndex];if(!target){throw new NotebookEditError(`Cell index ${targetIndex} is out of range.`,"notebook_cell_not_found")}const finalType=params.cell_type??target.cell_type;target.source=toNotebookSource(source,Array.isArray(target.source));normalizeEditedCell(target,finalType);return buildResult(notebook,{editedCellId:displayCellId(target,targetIndex),editedCellType:finalType,language,mode})}default:throw new NotebookEditError(`Unsupported notebook edit mode: ${mode}`,"invalid_tool_params")}}__name(applyNotebookEdit,"applyNotebookEdit");function prepareModifiedNotebookContent(originalContent,modifiedContent,params){let notebook;let originalNotebook;try{notebook=parseNotebook(modifiedContent);originalNotebook=parseNotebook(originalContent)}catch(error){throw new NotebookEditError(error instanceof Error?error.message:String(error),"notebook_invalid_json")}return{updatedContent:modifiedContent,editedCellId:params.cell_id??"user-modified-notebook",editedCellType:void 0,language:getNotebookLanguage(notebook),mode:params.edit_mode??"replace",requiresReadAfterWrite:!hasStableCellIds(originalNotebook)||!hasStableCellIds(notebook)}}__name(prepareModifiedNotebookContent,"prepareModifiedNotebookContent");async function checkPriorNotebookRead(config,notebookPath,options={}){if(config.getFileReadCacheDisabled()){return{ok:true}}let stats;try{stats=await fs.promises.stat(notebookPath)}catch(error){const code=error?.code;if(code==="ENOENT"){if(options.expectExisting){return rejectNotebookPriorRead(notebookPath,"missing-after-read",{ok:false,type:"file_changed_since_read",rawMessage:`Notebook ${notebookPath} disappeared after it was read. Re-read it with the ${ToolNames.READ_FILE} tool before editing it.`,displayMessage:`notebook disappeared after last read; re-run ${ToolNames.READ_FILE} first.`})}return{ok:true}}return rejectNotebookPriorRead(notebookPath,"stat-failed",{ok:false,type:"prior_read_verification_failed",rawMessage:`Could not stat ${notebookPath} to verify prior notebook read (${code??"unknown error"}). Re-read it with the ${ToolNames.READ_FILE} tool before editing it.`,displayMessage:`cannot verify prior read of ${notebookPath}; re-run ${ToolNames.READ_FILE} before editing this notebook.`})}if(stats.isDirectory()){return rejectNotebookPriorRead(notebookPath,"target-is-directory",{ok:false,type:"target_is_directory",rawMessage:`${notebookPath} is a directory. The NotebookEdit tool only operates on .ipynb files.`,displayMessage:"path is a directory; cannot edit as a notebook."})}if(!stats.isFile()){return rejectNotebookPriorRead(notebookPath,"target-not-regular-file",{ok:false,type:"target_not_regular_file",rawMessage:`${notebookPath} is not a regular file. The NotebookEdit tool only operates on .ipynb files.`,displayMessage:"special file; cannot edit as a notebook."})}const status=config.getFileReadCache().check(stats);if(status.state==="fresh"&&status.entry.lastReadAt!==void 0&&status.entry.lastReadWasFull){return{ok:true}}if(status.state==="fresh"&&status.entry.lastReadAt!==void 0&&!status.entry.lastReadWasFull){return rejectNotebookPriorRead(notebookPath,"truncated-cache-entry",{ok:false,type:"edit_requires_prior_read",rawMessage:`Notebook ${notebookPath} is too large for cell-level editing because its rendered output was truncated when read. Reduce the notebook output size or split the notebook before editing cells.`,displayMessage:"notebook too large for cell-level editing."})}if(status.state==="stale"){return rejectNotebookPriorRead(notebookPath,"stale-cache-entry",{ok:false,type:"file_changed_since_read",rawMessage:`Notebook ${notebookPath} has been modified since you last read it. Re-read it with the ${ToolNames.READ_FILE} tool before editing it.`,displayMessage:`notebook changed since last read; re-run ${ToolNames.READ_FILE} first.`})}if(status.state==="unverifiable"){return rejectNotebookPriorRead(notebookPath,"unverifiable-cache-entry",{ok:false,type:"prior_read_verification_failed",rawMessage:`Notebook ${notebookPath} is on a filesystem that does not provide a verifiable inode identity (ino=0), so NotebookEdit cannot safely confirm a prior read. Use a different mechanism to edit this notebook.`,displayMessage:`cannot verify prior read of ${notebookPath}; use a different mechanism to edit it.`})}return rejectNotebookPriorRead(notebookPath,`cache-${status.state}`,{ok:false,type:"edit_requires_prior_read",rawMessage:`Notebook ${notebookPath} has not been fully read in this session. Use the ${ToolNames.READ_FILE} tool first, without offset or limit, before editing cells.`,displayMessage:`${ToolNames.READ_FILE} required before editing this notebook.`})}__name(checkPriorNotebookRead,"checkPriorNotebookRead");var NotebookEditInvocation=class extends BaseToolInvocation{constructor(config,params,modifyMetadata){super(params);this.config=config;this.modifyMetadata=modifyMetadata}static{__name(this,"NotebookEditInvocation")}toolLocations(){return[{path:this.params.notebook_path}]}getDescription(){const relativePath=makeRelative(this.params.notebook_path,this.config.getTargetDir());const mode=this.params.edit_mode??"replace";const cell=this.params.cell_id??"beginning";return`${mode} notebook cell ${cell} in ${shortenPath(relativePath)}`}async getDefaultPermission(){return"ask"}requiresUserInteraction(){return backgroundFixHolding(this.params.notebook_path,getCurrentAgentId())!==void 0}async getConfirmationDetails(abortSignal){const prepared=await this.prepareEdit(abortSignal);const fileName=path.basename(this.params.notebook_path);const fileDiff=createPatchSmart(fileName,prepared.originalContent,prepared.updatedContent,"Current","Proposed");const confirmationDetails={type:"edit",title:`Confirm Notebook Edit: ${shortenPath(makeRelative(this.params.notebook_path,this.config.getTargetDir()))}`,fileName,filePath:this.params.notebook_path,fileDiff,originalContent:prepared.originalContent,newContent:prepared.updatedContent,onConfirm:__name(async outcome=>{if(outcome==="proceed_always"){this.config.setApprovalMode("auto-edit")}},"onConfirm")};return confirmationDetails}async prepareEdit(abortSignal){const preDecision=await checkPriorNotebookRead(this.config,this.params.notebook_path);if(!preDecision.ok){throw new StructuredToolError(preDecision.rawMessage,preDecision.type)}let originalContent;let bom=false;let encoding;let lineEnding="lf";try{const fileInfo=await this.config.getFileSystemService().readTextFile({path:this.params.notebook_path});originalContent=fileInfo.content;bom=fileInfo._meta?.bom??false;encoding=fileInfo._meta?.encoding;lineEnding=fileInfo._meta?.lineEnding??detectLineEnding(fileInfo.content)}catch(error){if(abortSignal.aborted){throw error}const code=error?.code;if(code==="ENOENT"){throw new StructuredToolError(`Notebook file not found: ${this.params.notebook_path}`,"file_not_found")}throw new StructuredToolError(`Error reading notebook: ${error instanceof Error?error.message:String(error)}`,"read_content_failure")}const postDecision=await checkPriorNotebookRead(this.config,this.params.notebook_path,{expectExisting:true});if(!postDecision.ok){throw new StructuredToolError(postDecision.rawMessage,postDecision.type)}try{if(this.modifyMetadata?.modifiedNotebookContent!==void 0){return{...prepareModifiedNotebookContent(originalContent,this.modifyMetadata.modifiedNotebookContent,this.params),originalContent,bom,encoding,lineEnding}}return{...applyNotebookEdit(originalContent,this.params),originalContent,bom,encoding,lineEnding}}catch(error){if(error instanceof NotebookEditError){throw new StructuredToolError(error.message,error.type)}throw error}}async execute(signal){let prepared;try{prepared=await this.prepareEdit(signal)}catch(error){if(signal.aborted){throw error}const errorType=error instanceof StructuredToolError?error.errorType:"notebook_edit_failure";const message=error instanceof Error?error.message:String(error);return{llmContent:message,returnDisplay:`Error: ${message}`,error:{message,type:errorType}}}const teamMemoryError=checkTeamMemorySecrets(this.params.notebook_path,prepared.updatedContent,this.config.getProjectRoot());if(teamMemoryError){return{llmContent:`[ERROR: ${teamMemoryError}]`,returnDisplay:teamMemoryError,error:{message:teamMemoryError,type:"invalid_tool_params"}}}try{try{await this.config.getFileHistoryService().trackEdit(this.params.notebook_path)}catch{}const writeDecision=await checkPriorNotebookRead(this.config,this.params.notebook_path,{expectExisting:true});if(!writeDecision.ok){return{llmContent:writeDecision.rawMessage,returnDisplay:`Error: ${writeDecision.displayMessage}`,error:{message:writeDecision.rawMessage,type:writeDecision.type}}}await this.config.getFileSystemService().writeTextFile({path:this.params.notebook_path,content:prepared.updatedContent,toolWriteOrigin:"notebook_edit",_meta:{bom:prepared.bom,encoding:prepared.encoding,lineEnding:prepared.lineEnding}});if(!this.modifyMetadata?.modifiedByUser){CommitAttributionService.getInstance().recordEdit(this.params.notebook_path,prepared.originalContent,prepared.updatedContent)}let postWriteSizeBytes;try{const postWriteStats=fs.statSync(this.params.notebook_path);postWriteSizeBytes=postWriteStats.size;const cache=this.config.getFileReadCache();if(prepared.requiresReadAfterWrite){cache.invalidate(postWriteStats)}else{cache.recordWrite(this.params.notebook_path,postWriteStats,{cacheable:false})}}catch(error){debugLogger.warn(`[NotebookEdit] post-write cache update failed for ${this.params.notebook_path}: ${error instanceof Error?error.message:String(error)}`)}const fileName=path.basename(this.params.notebook_path);const fileDiff=createPatchSmart(fileName,prepared.originalContent,prepared.updatedContent,"Current","Proposed");const diffStat=getDiffStat(fileName,prepared.originalContent,this.modifyMetadata?.aiProposedContent??prepared.updatedContent,prepared.updatedContent);logFileOperation(this.config,new FileOperationEvent(NotebookEditTool.Name,"update",prepared.updatedContent.split("\n").length,getSpecificMimeType(this.params.notebook_path),".ipynb",prepared.language));const displayResult={fileDiff,fileName,filePath:this.params.notebook_path,originalContent:prepared.originalContent,newContent:prepared.updatedContent,diffStat};const artifact=buildWorkspaceArtifactCandidate(this.config,this.params.notebook_path,{recordAsArtifact:this.params.record_as_artifact,sizeBytes:postWriteSizeBytes});const reminder=artifact&&!artifact.updateOnly?` ${formatRecordArtifactReminder(artifact.workspacePath)}`:"";const llmContent=this.modifyMetadata?.modifiedNotebookContent!==void 0?`Notebook ${this.params.notebook_path} has been updated.${reminder} Notebook content was modified by the user before approval; the final saved notebook may differ from the original ${prepared.mode} cell ${prepared.editedCellId} proposal.`:`Notebook ${this.params.notebook_path} has been updated.${reminder} ${prepared.mode} cell ${prepared.editedCellId}.${prepared.mode==="delete"?"":`
|
|
3
|
+
import{checkTeamMemorySecrets}from"./chunk-VFFTE2PS.js";import{buildWorkspaceArtifactCandidate,formatRecordArtifactReminder}from"./chunk-54CHQYA3.js";import{CommitAttributionService,createPatchSmart,detectLineEnding,getDiffStat}from"./chunk-ZUWLTGSR.js";import{backgroundFixHolding}from"./chunk-B5ZFH363.js";import{getCurrentAgentId}from"./chunk-KP77CL5U.js";import{FileOperationEvent,logFileOperation}from"./chunk-MJEL7DIE.js";import{findCellIndex,getCellDisplayId,getNotebookLanguage,getSpecificMimeType,hasStableCellIds,inferInsertedCellSourceArrayStyle,inferNotebookJsonFormat,isAmbiguousCellId,makeCellId,normalizeEditedCell,normalizeSource,parseNotebook,serializeNotebook,toNotebookSource}from"./chunk-6JHMYZNS.js";import{BaseDeclarativeTool,BaseToolInvocation,StructuredToolError}from"./chunk-D6CEQ2GY.js";import{ToolDisplayNames,ToolNames}from"./chunk-SBZFGYYS.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{makeRelative,shortenPath,unescapePath}from"./chunk-2ZK2FGZQ.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs";import*as path from"node:path";var debugLogger=createDebugLogger("NOTEBOOK_EDIT");function rejectNotebookPriorRead(notebookPath,reason,decision){debugLogger.debug("prior-read-rejected",{path:notebookPath,reason,type:decision.type,displayMessage:decision.displayMessage});return decision}__name(rejectNotebookPriorRead,"rejectNotebookPriorRead");var NotebookEditError=class extends Error{constructor(message,type){super(message);this.type=type;this.name="NotebookEditError"}static{__name(this,"NotebookEditError")}};function requireNotebookSource(source,mode){if(mode==="delete"){return""}if(typeof source!=="string"){throw new NotebookEditError(`new_source is required when edit_mode is "${mode}".`,"invalid_tool_params")}return source}__name(requireNotebookSource,"requireNotebookSource");function displayCellId(cell,index){return cell?getCellDisplayId(cell,index):`cell-${index}`}__name(displayCellId,"displayCellId");function resolveTargetIndex(notebook,cellId,mode){if(!cellId){if(mode==="insert"){return-1}throw new NotebookEditError("cell_id is required for replace and delete operations.","invalid_tool_params")}if(isAmbiguousCellId(notebook,cellId)){throw new NotebookEditError(`Cell ID "${cellId}" is ambiguous in the rendered notebook. Re-read the notebook and target a stable real cell ID before editing.`,"invalid_tool_params")}const index=findCellIndex(notebook,cellId);if(index===-1){throw new NotebookEditError(`Cell with ID "${cellId}" not found in notebook.`,"notebook_cell_not_found")}return index}__name(resolveTargetIndex,"resolveTargetIndex");function createNotebookCell(notebook,cellType,source,preferSourceArray){const cell={cell_type:cellType,metadata:{},source:toNotebookSource(source,preferSourceArray)};const id=makeCellId(notebook);if(id){cell.id=id}normalizeEditedCell(cell,cellType);return cell}__name(createNotebookCell,"createNotebookCell");function applyNotebookEdit(rawContent,params){let notebook;try{notebook=parseNotebook(rawContent)}catch(error){throw new NotebookEditError(error instanceof Error?error.message:String(error),"notebook_invalid_json")}const mode=params.edit_mode??"replace";const source=requireNotebookSource(params.new_source,mode);const originalHasStableCellIds=hasStableCellIds(notebook);const targetIndex=resolveTargetIndex(notebook,params.cell_id,mode);const language=getNotebookLanguage(notebook);const jsonFormat=inferNotebookJsonFormat(rawContent);const buildResult=__name((updatedNotebook,result)=>{const structuralEdit=mode==="insert"||mode==="delete";return{...result,updatedContent:serializeNotebook(updatedNotebook,jsonFormat),requiresReadAfterWrite:structuralEdit&&!(originalHasStableCellIds&&hasStableCellIds(updatedNotebook))}},"buildResult");switch(mode){case"insert":{const cellType=params.cell_type??"code";const insertAt=targetIndex===-1?0:targetIndex+1;const newCell=createNotebookCell(notebook,cellType,source,inferInsertedCellSourceArrayStyle(notebook,insertAt));notebook.cells.splice(insertAt,0,newCell);return buildResult(notebook,{editedCellId:displayCellId(newCell,insertAt),editedCellType:cellType,language,mode})}case"delete":{const[removed]=notebook.cells.splice(targetIndex,1);return buildResult(notebook,{editedCellId:displayCellId(removed,targetIndex),editedCellType:removed?.cell_type,language,mode})}case"replace":{const target=notebook.cells[targetIndex];if(!target){throw new NotebookEditError(`Cell index ${targetIndex} is out of range.`,"notebook_cell_not_found")}const finalType=params.cell_type??target.cell_type;target.source=toNotebookSource(source,Array.isArray(target.source));normalizeEditedCell(target,finalType);return buildResult(notebook,{editedCellId:displayCellId(target,targetIndex),editedCellType:finalType,language,mode})}default:throw new NotebookEditError(`Unsupported notebook edit mode: ${mode}`,"invalid_tool_params")}}__name(applyNotebookEdit,"applyNotebookEdit");function prepareModifiedNotebookContent(originalContent,modifiedContent,params){let notebook;let originalNotebook;try{notebook=parseNotebook(modifiedContent);originalNotebook=parseNotebook(originalContent)}catch(error){throw new NotebookEditError(error instanceof Error?error.message:String(error),"notebook_invalid_json")}return{updatedContent:modifiedContent,editedCellId:params.cell_id??"user-modified-notebook",editedCellType:void 0,language:getNotebookLanguage(notebook),mode:params.edit_mode??"replace",requiresReadAfterWrite:!hasStableCellIds(originalNotebook)||!hasStableCellIds(notebook)}}__name(prepareModifiedNotebookContent,"prepareModifiedNotebookContent");async function checkPriorNotebookRead(config,notebookPath,options={}){if(config.getFileReadCacheDisabled()){return{ok:true}}let stats;try{stats=await fs.promises.stat(notebookPath)}catch(error){const code=error?.code;if(code==="ENOENT"){if(options.expectExisting){return rejectNotebookPriorRead(notebookPath,"missing-after-read",{ok:false,type:"file_changed_since_read",rawMessage:`Notebook ${notebookPath} disappeared after it was read. Re-read it with the ${ToolNames.READ_FILE} tool before editing it.`,displayMessage:`notebook disappeared after last read; re-run ${ToolNames.READ_FILE} first.`})}return{ok:true}}return rejectNotebookPriorRead(notebookPath,"stat-failed",{ok:false,type:"prior_read_verification_failed",rawMessage:`Could not stat ${notebookPath} to verify prior notebook read (${code??"unknown error"}). Re-read it with the ${ToolNames.READ_FILE} tool before editing it.`,displayMessage:`cannot verify prior read of ${notebookPath}; re-run ${ToolNames.READ_FILE} before editing this notebook.`})}if(stats.isDirectory()){return rejectNotebookPriorRead(notebookPath,"target-is-directory",{ok:false,type:"target_is_directory",rawMessage:`${notebookPath} is a directory. The NotebookEdit tool only operates on .ipynb files.`,displayMessage:"path is a directory; cannot edit as a notebook."})}if(!stats.isFile()){return rejectNotebookPriorRead(notebookPath,"target-not-regular-file",{ok:false,type:"target_not_regular_file",rawMessage:`${notebookPath} is not a regular file. The NotebookEdit tool only operates on .ipynb files.`,displayMessage:"special file; cannot edit as a notebook."})}const status=config.getFileReadCache().check(stats);if(status.state==="fresh"&&status.entry.lastReadAt!==void 0&&status.entry.lastReadWasFull){return{ok:true}}if(status.state==="fresh"&&status.entry.lastReadAt!==void 0&&!status.entry.lastReadWasFull){return rejectNotebookPriorRead(notebookPath,"truncated-cache-entry",{ok:false,type:"edit_requires_prior_read",rawMessage:`Notebook ${notebookPath} is too large for cell-level editing because its rendered output was truncated when read. Reduce the notebook output size or split the notebook before editing cells.`,displayMessage:"notebook too large for cell-level editing."})}if(status.state==="stale"){return rejectNotebookPriorRead(notebookPath,"stale-cache-entry",{ok:false,type:"file_changed_since_read",rawMessage:`Notebook ${notebookPath} has been modified since you last read it. Re-read it with the ${ToolNames.READ_FILE} tool before editing it.`,displayMessage:`notebook changed since last read; re-run ${ToolNames.READ_FILE} first.`})}if(status.state==="unverifiable"){return rejectNotebookPriorRead(notebookPath,"unverifiable-cache-entry",{ok:false,type:"prior_read_verification_failed",rawMessage:`Notebook ${notebookPath} is on a filesystem that does not provide a verifiable inode identity (ino=0), so NotebookEdit cannot safely confirm a prior read. Use a different mechanism to edit this notebook.`,displayMessage:`cannot verify prior read of ${notebookPath}; use a different mechanism to edit it.`})}return rejectNotebookPriorRead(notebookPath,`cache-${status.state}`,{ok:false,type:"edit_requires_prior_read",rawMessage:`Notebook ${notebookPath} has not been fully read in this session. Use the ${ToolNames.READ_FILE} tool first, without offset or limit, before editing cells.`,displayMessage:`${ToolNames.READ_FILE} required before editing this notebook.`})}__name(checkPriorNotebookRead,"checkPriorNotebookRead");var NotebookEditInvocation=class extends BaseToolInvocation{constructor(config,params,modifyMetadata){super(params);this.config=config;this.modifyMetadata=modifyMetadata}static{__name(this,"NotebookEditInvocation")}toolLocations(){return[{path:this.params.notebook_path}]}getDescription(){const relativePath=makeRelative(this.params.notebook_path,this.config.getTargetDir());const mode=this.params.edit_mode??"replace";const cell=this.params.cell_id??"beginning";return`${mode} notebook cell ${cell} in ${shortenPath(relativePath)}`}async getDefaultPermission(){return"ask"}requiresUserInteraction(){return backgroundFixHolding(this.params.notebook_path,getCurrentAgentId())!==void 0}async getConfirmationDetails(abortSignal){const prepared=await this.prepareEdit(abortSignal);const fileName=path.basename(this.params.notebook_path);const fileDiff=createPatchSmart(fileName,prepared.originalContent,prepared.updatedContent,"Current","Proposed");const confirmationDetails={type:"edit",title:`Confirm Notebook Edit: ${shortenPath(makeRelative(this.params.notebook_path,this.config.getTargetDir()))}`,fileName,filePath:this.params.notebook_path,fileDiff,originalContent:prepared.originalContent,newContent:prepared.updatedContent,onConfirm:__name(async outcome=>{if(outcome==="proceed_always"){this.config.setApprovalMode("auto-edit")}},"onConfirm")};return confirmationDetails}async prepareEdit(abortSignal){const preDecision=await checkPriorNotebookRead(this.config,this.params.notebook_path);if(!preDecision.ok){throw new StructuredToolError(preDecision.rawMessage,preDecision.type)}let originalContent;let bom=false;let encoding;let lineEnding="lf";try{const fileInfo=await this.config.getFileSystemService().readTextFile({path:this.params.notebook_path});originalContent=fileInfo.content;bom=fileInfo._meta?.bom??false;encoding=fileInfo._meta?.encoding;lineEnding=fileInfo._meta?.lineEnding??detectLineEnding(fileInfo.content)}catch(error){if(abortSignal.aborted){throw error}const code=error?.code;if(code==="ENOENT"){throw new StructuredToolError(`Notebook file not found: ${this.params.notebook_path}`,"file_not_found")}throw new StructuredToolError(`Error reading notebook: ${error instanceof Error?error.message:String(error)}`,"read_content_failure")}const postDecision=await checkPriorNotebookRead(this.config,this.params.notebook_path,{expectExisting:true});if(!postDecision.ok){throw new StructuredToolError(postDecision.rawMessage,postDecision.type)}try{if(this.modifyMetadata?.modifiedNotebookContent!==void 0){return{...prepareModifiedNotebookContent(originalContent,this.modifyMetadata.modifiedNotebookContent,this.params),originalContent,bom,encoding,lineEnding}}return{...applyNotebookEdit(originalContent,this.params),originalContent,bom,encoding,lineEnding}}catch(error){if(error instanceof NotebookEditError){throw new StructuredToolError(error.message,error.type)}throw error}}async execute(signal){let prepared;try{prepared=await this.prepareEdit(signal)}catch(error){if(signal.aborted){throw error}const errorType=error instanceof StructuredToolError?error.errorType:"notebook_edit_failure";const message=error instanceof Error?error.message:String(error);return{llmContent:message,returnDisplay:`Error: ${message}`,error:{message,type:errorType}}}const teamMemoryError=checkTeamMemorySecrets(this.params.notebook_path,prepared.updatedContent,this.config.getProjectRoot());if(teamMemoryError){return{llmContent:`[ERROR: ${teamMemoryError}]`,returnDisplay:teamMemoryError,error:{message:teamMemoryError,type:"invalid_tool_params"}}}try{try{await this.config.getFileHistoryService().trackEdit(this.params.notebook_path)}catch{}const writeDecision=await checkPriorNotebookRead(this.config,this.params.notebook_path,{expectExisting:true});if(!writeDecision.ok){return{llmContent:writeDecision.rawMessage,returnDisplay:`Error: ${writeDecision.displayMessage}`,error:{message:writeDecision.rawMessage,type:writeDecision.type}}}await this.config.getFileSystemService().writeTextFile({path:this.params.notebook_path,content:prepared.updatedContent,toolWriteOrigin:"notebook_edit",_meta:{bom:prepared.bom,encoding:prepared.encoding,lineEnding:prepared.lineEnding}});if(!this.modifyMetadata?.modifiedByUser){CommitAttributionService.getInstance().recordEdit(this.params.notebook_path,prepared.originalContent,prepared.updatedContent)}let postWriteSizeBytes;try{const postWriteStats=fs.statSync(this.params.notebook_path);postWriteSizeBytes=postWriteStats.size;const cache=this.config.getFileReadCache();if(prepared.requiresReadAfterWrite){cache.invalidate(postWriteStats)}else{cache.recordWrite(this.params.notebook_path,postWriteStats,{cacheable:false})}}catch(error){debugLogger.warn(`[NotebookEdit] post-write cache update failed for ${this.params.notebook_path}: ${error instanceof Error?error.message:String(error)}`)}const fileName=path.basename(this.params.notebook_path);const fileDiff=createPatchSmart(fileName,prepared.originalContent,prepared.updatedContent,"Current","Proposed");const diffStat=getDiffStat(fileName,prepared.originalContent,this.modifyMetadata?.aiProposedContent??prepared.updatedContent,prepared.updatedContent);logFileOperation(this.config,new FileOperationEvent(NotebookEditTool.Name,"update",prepared.updatedContent.split("\n").length,getSpecificMimeType(this.params.notebook_path),".ipynb",prepared.language));const displayResult={fileDiff,fileName,filePath:this.params.notebook_path,originalContent:prepared.originalContent,newContent:prepared.updatedContent,diffStat};const artifact=buildWorkspaceArtifactCandidate(this.config,this.params.notebook_path,{recordAsArtifact:this.params.record_as_artifact,sizeBytes:postWriteSizeBytes});const reminder=artifact&&!artifact.updateOnly?` ${formatRecordArtifactReminder(artifact.workspacePath)}`:"";const llmContent=this.modifyMetadata?.modifiedNotebookContent!==void 0?`Notebook ${this.params.notebook_path} has been updated.${reminder} Notebook content was modified by the user before approval; the final saved notebook may differ from the original ${prepared.mode} cell ${prepared.editedCellId} proposal.`:`Notebook ${this.params.notebook_path} has been updated.${reminder} ${prepared.mode} cell ${prepared.editedCellId}.${prepared.mode==="delete"?"":`
|
|
4
4
|
|
|
5
5
|
Updated source:
|
|
6
6
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{captureRuntimeFileVersion,writeRuntimeFile}from"./chunk-AHV4IMUX.js";import{checkTeamMemorySecrets,checkWorkspaceTeamMemorySecrets}from"./chunk-VFFTE2PS.js";import{buildWorkspaceArtifactCandidate,formatRecordArtifactReminder}from"./chunk-54CHQYA3.js";import{CommitAttributionService,FileEncoding,checkPriorRead,createPatchSmart,detectLineEnding,getDiffStat,needsUtf8Bom}from"./chunk-POMEWCFJ.js";import{backgroundFixHolding}from"./chunk-B5ZFH363.js";import{getCurrentAgentId}from"./chunk-KP77CL5U.js";import{FileOperationEvent,getLanguageFromFilePath,logFileOperation}from"./chunk-MJEL7DIE.js";import{isAnyAutoMemPath,isTeamAutoMemPath}from"./chunk-CQGP2BAW.js";import{fileExists,getSpecificMimeType}from"./chunk-6JHMYZNS.js";import{BaseDeclarativeTool,BaseToolInvocation,StructuredToolError}from"./chunk-D6CEQ2GY.js";import{ToolDisplayNames,ToolNames}from"./chunk-SBZFGYYS.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{makeRelative,shortenPath,unescapePath}from"./chunk-2ZK2FGZQ.js";import{getErrorMessage,isNodeError}from"./chunk-E7MYPQGV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import fs from"node:fs";import path from"node:path";var debugLogger=createDebugLogger("WRITE_FILE");var WriteFileToolInvocation=class extends BaseToolInvocation{constructor(config,params){super(params);this.config=config}static{__name(this,"WriteFileToolInvocation")}toolLocations(){return[{path:this.params.file_path}]}getDescription(){const relativePath=makeRelative(this.params.file_path,this.config.getTargetDir());return`Writing to ${shortenPath(relativePath)}`}requiresUserInteraction(){return backgroundFixHolding(this.params.file_path,getCurrentAgentId())!==void 0}async getDefaultPermission(){if(this.config.getFileSystemService().textFileIo)return"ask";const projectRoot=this.config.getProjectRoot();const filePath=path.resolve(this.params.file_path);if(isTeamAutoMemPath(filePath,projectRoot)){return"ask"}if(isAnyAutoMemPath(filePath,projectRoot)){return"allow"}return"ask"}async getConfirmationDetails(_abortSignal){let originalContent="";let observation;try{observation=await this.config.getFileSystemService().textFileIo?.inspect(this.params.file_path,_abortSignal)}catch(error){if(isNodeError(error)&&error.code==="EISDIR")throw new StructuredToolError(`Path is a directory, not a file: ${this.params.file_path}`,"target_is_directory");throw error}let fileExists2=observation?observation.kind==="file":await fileExists(this.params.file_path);if(!this.config.getFileReadCacheDisabled()){const decision=await checkPriorRead(this.config.getFileReadCache(),this.params.file_path,"overwriting");if(!decision.ok){throw new StructuredToolError(decision.rawMessage,decision.type)}}if(fileExists2){try{const{content}=observation?.kind==="file"?observation.response:await this.config.getFileSystemService().readTextFile({path:this.params.file_path});originalContent=content}catch(err){if(isNodeError(err)&&err.code==="ENOENT"){fileExists2=false}else{throw new Error(`Error reading existing file for confirmation: ${getErrorMessage(err)}`)}}}if(fileExists2&&!this.config.getFileReadCacheDisabled()){const postDecision=await checkPriorRead(this.config.getFileReadCache(),this.params.file_path,"overwriting",{expectExisting:true});if(!postDecision.ok){debugLogger.warn("post-read TOCTOU rejection (confirmation)",{path:this.params.file_path,reason:postDecision.type});throw new StructuredToolError(postDecision.rawMessage,postDecision.type)}}const relativePath=makeRelative(this.params.file_path,this.config.getTargetDir());const fileName=path.basename(this.params.file_path);const fileDiff=createPatchSmart(fileName,originalContent,this.params.content,"Current","Proposed");const confirmationDetails={type:"edit",title:`Confirm Write: ${shortenPath(relativePath)}`,fileName,filePath:this.params.file_path,fileDiff,originalContent,newContent:this.params.content,onConfirm:__name(async outcome=>{if(outcome==="proceed_always"){this.config.setApprovalMode("auto-edit")}},"onConfirm")};return confirmationDetails}async execute(abortSignal){const io=this.config.getFileSystemService().textFileIo;if(!io)return this.executeObserved(abortSignal);try{return await io.withMutation(this.params.file_path,abortSignal,mutation=>this.executeObserved(abortSignal,mutation))}catch(error){if(abortSignal.aborted)throw error;return this.writeFailure(error)}}async executeObserved(abortSignal,mutation){const{file_path,content,ai_proposed_content,modified_by_user}=this.params;let sandboxFileVersion;try{sandboxFileVersion=captureRuntimeFileVersion(this.config,file_path)}catch(error){const message=`${file_path}: ${getErrorMessage(error)}`;return{llmContent:message,returnDisplay:message,error:{message,type:isNodeError(error)&&error.code==="EISDIR"?"target_is_directory":"file_write_failure"}}}let fileExists2=mutation?mutation.original.kind==="file":await fileExists(file_path);let originalContent="";let useBOM=false;let detectedEncoding;let detectedLineEnding;const dirName=path.dirname(file_path);const teamMemoryError=(this.config.getFileSystemService().textFileIo?checkWorkspaceTeamMemorySecrets:checkTeamMemorySecrets)(file_path,content,this.config.getProjectRoot());if(teamMemoryError){return{llmContent:`[ERROR: ${teamMemoryError}]`,returnDisplay:teamMemoryError,error:{message:teamMemoryError,type:"invalid_tool_params"}}}if(!this.config.getFileReadCacheDisabled()){const decision=await checkPriorRead(this.config.getFileReadCache(),file_path,"overwriting");if(!decision.ok){return{llmContent:decision.rawMessage,returnDisplay:`Error: ${decision.displayMessage}`,error:{message:decision.rawMessage,type:decision.type}}}}if(fileExists2){try{const fileInfo=mutation?.original.kind==="file"?mutation.original.response:await this.config.getFileSystemService().readTextFile({path:file_path});if(fileInfo._meta?.bom!==void 0){useBOM=fileInfo._meta.bom}else{useBOM=fileInfo.content.length>0&&fileInfo.content.codePointAt(0)===65279}detectedEncoding=fileInfo._meta?.encoding||"utf-8";detectedLineEnding=detectLineEnding(fileInfo.content);originalContent=fileInfo.content;fileExists2=true}catch(err){if(isNodeError(err)&&err.code==="ENOENT"){fileExists2=false}else{const error={message:getErrorMessage(err),code:isNodeError(err)?err.code:void 0};const errorMsg=error.code?`Error checking existing file '${file_path}': ${error.message} (${error.code})`:`Error checking existing file: ${error.message}`;return{llmContent:errorMsg,returnDisplay:errorMsg,error:{message:errorMsg,type:"file_write_failure"}}}}}if(fileExists2&&!this.config.getFileReadCacheDisabled()){const postDecision=await checkPriorRead(this.config.getFileReadCache(),file_path,"overwriting",{expectExisting:true});if(!postDecision.ok){debugLogger.warn("post-read TOCTOU rejection (execute)",{path:file_path,reason:postDecision.type});return{llmContent:postDecision.rawMessage,returnDisplay:`Error: ${postDecision.displayMessage}`,error:{message:postDecision.rawMessage,type:postDecision.type}}}}if(!fileExists2){const userEncoding=this.config.getDefaultFileEncoding();if(userEncoding===FileEncoding.UTF8_BOM){useBOM=true}else if(userEncoding===void 0){useBOM=needsUtf8Bom(file_path)}detectedEncoding=void 0}try{await this.config.getFileHistoryService().trackEdit(file_path)}catch{}if(!this.config.getFileReadCacheDisabled()){const writeDecision=await checkPriorRead(this.config.getFileReadCache(),file_path,"overwriting",{expectExisting:fileExists2});if(!writeDecision.ok){debugLogger.warn("pre-write TOCTOU rejection",{path:file_path,reason:writeDecision.type});return{llmContent:writeDecision.rawMessage,returnDisplay:`Error: ${writeDecision.displayMessage}`,error:{message:writeDecision.rawMessage,type:writeDecision.type}}}}if(!mutation&&!fileExists2&&!this.config.getShellExecutionSandbox?.()){fs.mkdirSync(dirName,{recursive:true})}try{const writeParams={path:file_path,content,toolWriteOrigin:"write_file",_meta:{bom:useBOM,encoding:detectedEncoding,lineEnding:detectedLineEnding}};const committedStats=mutation?await mutation.write(writeParams):(await writeRuntimeFile(this.config,writeParams,sandboxFileVersion,abortSignal),void 0);if(!mutation&&!modified_by_user){CommitAttributionService.getInstance().recordEdit(file_path,fileExists2?originalContent:null,content)}let postWriteSizeBytes;try{if(mutation&&!committedStats)throw new Error("Scoped file write returned no committed stats.");const postWriteStats=mutation?committedStats:fs.statSync(file_path);postWriteSizeBytes=postWriteStats.size;this.config.getFileReadCache().recordWrite(file_path,postWriteStats)}catch(error){if(mutation)throw error}const fileName=path.basename(file_path);const currentContentForDiff=originalContent;const fileDiff=createPatchSmart(fileName,currentContentForDiff,content,"Original","Written");const originallyProposedContent=ai_proposed_content||content;const diffStat=getDiffStat(fileName,currentContentForDiff,originallyProposedContent,content);const llmSuccessMessageParts=[!fileExists2?`Successfully created and wrote to new file: ${file_path}.`:`Successfully overwrote file: ${file_path}.`];if(modified_by_user){llmSuccessMessageParts.push(`User modified the \`content\` to be: ${content}`)}const artifact=buildWorkspaceArtifactCandidate(this.config,file_path,{recordAsArtifact:this.params.record_as_artifact,sizeBytes:postWriteSizeBytes});if(artifact&&!artifact.updateOnly){llmSuccessMessageParts.push(formatRecordArtifactReminder(artifact.workspacePath))}const mimetype=getSpecificMimeType(file_path);const programmingLanguage=getLanguageFromFilePath(file_path);const extension=path.extname(file_path);const operation=!fileExists2?"create":"update";const lineCount=content.split("\n").length;logFileOperation(this.config,new FileOperationEvent(WriteFileTool.Name,operation,lineCount,mimetype,extension,programmingLanguage));const displayResult={fileDiff,fileName,filePath:file_path,originalContent,newContent:content,diffStat};return{llmContent:llmSuccessMessageParts.join(" "),returnDisplay:displayResult,...artifact?{artifacts:[artifact]}:{}}}catch(error){return this.writeFailure(error)}}writeFailure(error){const file_path=this.params.file_path;let errorMsg;let errorType="file_write_failure";if(isNodeError(error)){errorMsg=`Error writing to file '${file_path}': ${error.message} (${error.code})`;if(error.code==="ESTALE"&&this.config.getShellExecutionSandbox?.()){errorType="file_changed_since_read"}else if(error.code==="EACCES"){errorMsg=`Permission denied writing to file: ${file_path} (${error.code})`;errorType="permission_denied"}else if(error.code==="ENOSPC"){errorMsg=`No space left on device: ${file_path} (${error.code})`;errorType="no_space_left"}else if(error.code==="EISDIR"){errorMsg=`Target is a directory, not a file: ${file_path} (${error.code})`;errorType="target_is_directory"}if(this.config.getDebugMode()&&error.stack){debugLogger.debug("Write file error stack:",error.stack)}}else{errorMsg=`Error writing to file: ${getErrorMessage(error)}`}return{llmContent:errorMsg,returnDisplay:errorMsg,error:{message:errorMsg,type:errorType}}}};var WRITE_FILE_ARTIFACT_DESCRIPTION="Artifact-like files such as HTML, PDF, images, notebooks, office documents, CSV, Markdown, JSON, SQL, and Python files are automatically registered as session artifacts. Set record_as_artifact=false for intermediates, such as HTML written only to print a PDF: that does not create an artifact, but one the session already has for the path is still refreshed. Files under .qwen/tmp/ are not registered. Delete intermediates when done.";var WriteFileTool=class _WriteFileTool extends BaseDeclarativeTool{constructor(config){super(_WriteFileTool.Name,ToolDisplayNames.WRITE_FILE,`Writes content to a specified file in the local filesystem. A request to create or generate a file does not establish that the target path is new. Unless the target's absence or current text contents have already been established in this session, you MUST use the ${ToolNames.READ_FILE} tool first; if the file does not exist, then create it. With prior-read enforcement enabled, blind overwrites are rejected. The file_path argument MUST be an absolute path. Always construct it by combining the project root with the file's relative path (e.g. project root '/path/to/project/' + relative 'foo/bar.txt' = '/path/to/project/foo/bar.txt'). If the user provides a relative path, resolve it against the project root first.
|
|
3
|
+
import{captureRuntimeFileVersion,writeRuntimeFile}from"./chunk-E4QOAV5O.js";import{checkTeamMemorySecrets,checkWorkspaceTeamMemorySecrets}from"./chunk-VFFTE2PS.js";import{buildWorkspaceArtifactCandidate,formatRecordArtifactReminder}from"./chunk-54CHQYA3.js";import{CommitAttributionService,FileEncoding,checkPriorRead,createPatchSmart,detectLineEnding,getDiffStat,needsUtf8Bom}from"./chunk-ZUWLTGSR.js";import{backgroundFixHolding}from"./chunk-B5ZFH363.js";import{getCurrentAgentId}from"./chunk-KP77CL5U.js";import{FileOperationEvent,getLanguageFromFilePath,logFileOperation}from"./chunk-MJEL7DIE.js";import{isAnyAutoMemPath,isTeamAutoMemPath}from"./chunk-CQGP2BAW.js";import{fileExists,getSpecificMimeType}from"./chunk-6JHMYZNS.js";import{BaseDeclarativeTool,BaseToolInvocation,StructuredToolError}from"./chunk-D6CEQ2GY.js";import{ToolDisplayNames,ToolNames}from"./chunk-SBZFGYYS.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{makeRelative,shortenPath,unescapePath}from"./chunk-2ZK2FGZQ.js";import{getErrorMessage,isNodeError}from"./chunk-E7MYPQGV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import fs from"node:fs";import path from"node:path";var debugLogger=createDebugLogger("WRITE_FILE");var WriteFileToolInvocation=class extends BaseToolInvocation{constructor(config,params){super(params);this.config=config}static{__name(this,"WriteFileToolInvocation")}toolLocations(){return[{path:this.params.file_path}]}getDescription(){const relativePath=makeRelative(this.params.file_path,this.config.getTargetDir());return`Writing to ${shortenPath(relativePath)}`}requiresUserInteraction(){return backgroundFixHolding(this.params.file_path,getCurrentAgentId())!==void 0}async getDefaultPermission(){if(this.config.getFileSystemService().textFileIo)return"ask";const projectRoot=this.config.getProjectRoot();const filePath=path.resolve(this.params.file_path);if(isTeamAutoMemPath(filePath,projectRoot)){return"ask"}if(isAnyAutoMemPath(filePath,projectRoot)){return"allow"}return"ask"}async getConfirmationDetails(_abortSignal){let originalContent="";let observation;try{observation=await this.config.getFileSystemService().textFileIo?.inspect(this.params.file_path,_abortSignal)}catch(error){if(isNodeError(error)&&error.code==="EISDIR")throw new StructuredToolError(`Path is a directory, not a file: ${this.params.file_path}`,"target_is_directory");throw error}let fileExists2=observation?observation.kind==="file":await fileExists(this.params.file_path);if(!this.config.getFileReadCacheDisabled()){const decision=await checkPriorRead(this.config.getFileReadCache(),this.params.file_path,"overwriting");if(!decision.ok){throw new StructuredToolError(decision.rawMessage,decision.type)}}if(fileExists2){try{const{content}=observation?.kind==="file"?observation.response:await this.config.getFileSystemService().readTextFile({path:this.params.file_path});originalContent=content}catch(err){if(isNodeError(err)&&err.code==="ENOENT"){fileExists2=false}else{throw new Error(`Error reading existing file for confirmation: ${getErrorMessage(err)}`)}}}if(fileExists2&&!this.config.getFileReadCacheDisabled()){const postDecision=await checkPriorRead(this.config.getFileReadCache(),this.params.file_path,"overwriting",{expectExisting:true});if(!postDecision.ok){debugLogger.warn("post-read TOCTOU rejection (confirmation)",{path:this.params.file_path,reason:postDecision.type});throw new StructuredToolError(postDecision.rawMessage,postDecision.type)}}const relativePath=makeRelative(this.params.file_path,this.config.getTargetDir());const fileName=path.basename(this.params.file_path);const fileDiff=createPatchSmart(fileName,originalContent,this.params.content,"Current","Proposed");const confirmationDetails={type:"edit",title:`Confirm Write: ${shortenPath(relativePath)}`,fileName,filePath:this.params.file_path,fileDiff,originalContent,newContent:this.params.content,onConfirm:__name(async outcome=>{if(outcome==="proceed_always"){this.config.setApprovalMode("auto-edit")}},"onConfirm")};return confirmationDetails}async execute(abortSignal){const io=this.config.getFileSystemService().textFileIo;if(!io)return this.executeObserved(abortSignal);try{return await io.withMutation(this.params.file_path,abortSignal,mutation=>this.executeObserved(abortSignal,mutation))}catch(error){if(abortSignal.aborted)throw error;return this.writeFailure(error)}}async executeObserved(abortSignal,mutation){const{file_path,content,ai_proposed_content,modified_by_user}=this.params;let sandboxFileVersion;try{sandboxFileVersion=captureRuntimeFileVersion(this.config,file_path)}catch(error){const message=`${file_path}: ${getErrorMessage(error)}`;return{llmContent:message,returnDisplay:message,error:{message,type:isNodeError(error)&&error.code==="EISDIR"?"target_is_directory":"file_write_failure"}}}let fileExists2=mutation?mutation.original.kind==="file":await fileExists(file_path);let originalContent="";let useBOM=false;let detectedEncoding;let detectedLineEnding;const dirName=path.dirname(file_path);const teamMemoryError=(this.config.getFileSystemService().textFileIo?checkWorkspaceTeamMemorySecrets:checkTeamMemorySecrets)(file_path,content,this.config.getProjectRoot());if(teamMemoryError){return{llmContent:`[ERROR: ${teamMemoryError}]`,returnDisplay:teamMemoryError,error:{message:teamMemoryError,type:"invalid_tool_params"}}}if(!this.config.getFileReadCacheDisabled()){const decision=await checkPriorRead(this.config.getFileReadCache(),file_path,"overwriting");if(!decision.ok){return{llmContent:decision.rawMessage,returnDisplay:`Error: ${decision.displayMessage}`,error:{message:decision.rawMessage,type:decision.type}}}}if(fileExists2){try{const fileInfo=mutation?.original.kind==="file"?mutation.original.response:await this.config.getFileSystemService().readTextFile({path:file_path});if(fileInfo._meta?.bom!==void 0){useBOM=fileInfo._meta.bom}else{useBOM=fileInfo.content.length>0&&fileInfo.content.codePointAt(0)===65279}detectedEncoding=fileInfo._meta?.encoding||"utf-8";detectedLineEnding=detectLineEnding(fileInfo.content);originalContent=fileInfo.content;fileExists2=true}catch(err){if(isNodeError(err)&&err.code==="ENOENT"){fileExists2=false}else{const error={message:getErrorMessage(err),code:isNodeError(err)?err.code:void 0};const errorMsg=error.code?`Error checking existing file '${file_path}': ${error.message} (${error.code})`:`Error checking existing file: ${error.message}`;return{llmContent:errorMsg,returnDisplay:errorMsg,error:{message:errorMsg,type:"file_write_failure"}}}}}if(fileExists2&&!this.config.getFileReadCacheDisabled()){const postDecision=await checkPriorRead(this.config.getFileReadCache(),file_path,"overwriting",{expectExisting:true});if(!postDecision.ok){debugLogger.warn("post-read TOCTOU rejection (execute)",{path:file_path,reason:postDecision.type});return{llmContent:postDecision.rawMessage,returnDisplay:`Error: ${postDecision.displayMessage}`,error:{message:postDecision.rawMessage,type:postDecision.type}}}}if(!fileExists2){const userEncoding=this.config.getDefaultFileEncoding();if(userEncoding===FileEncoding.UTF8_BOM){useBOM=true}else if(userEncoding===void 0){useBOM=needsUtf8Bom(file_path)}detectedEncoding=void 0}try{await this.config.getFileHistoryService().trackEdit(file_path)}catch{}if(!this.config.getFileReadCacheDisabled()){const writeDecision=await checkPriorRead(this.config.getFileReadCache(),file_path,"overwriting",{expectExisting:fileExists2});if(!writeDecision.ok){debugLogger.warn("pre-write TOCTOU rejection",{path:file_path,reason:writeDecision.type});return{llmContent:writeDecision.rawMessage,returnDisplay:`Error: ${writeDecision.displayMessage}`,error:{message:writeDecision.rawMessage,type:writeDecision.type}}}}if(!mutation&&!fileExists2&&!this.config.getShellExecutionSandbox?.()){fs.mkdirSync(dirName,{recursive:true})}try{const writeParams={path:file_path,content,toolWriteOrigin:"write_file",_meta:{bom:useBOM,encoding:detectedEncoding,lineEnding:detectedLineEnding}};const committedStats=mutation?await mutation.write(writeParams):(await writeRuntimeFile(this.config,writeParams,sandboxFileVersion,abortSignal),void 0);if(!mutation&&!modified_by_user){CommitAttributionService.getInstance().recordEdit(file_path,fileExists2?originalContent:null,content)}let postWriteSizeBytes;try{if(mutation&&!committedStats)throw new Error("Scoped file write returned no committed stats.");const postWriteStats=mutation?committedStats:fs.statSync(file_path);postWriteSizeBytes=postWriteStats.size;this.config.getFileReadCache().recordWrite(file_path,postWriteStats)}catch(error){if(mutation)throw error}const fileName=path.basename(file_path);const currentContentForDiff=originalContent;const fileDiff=createPatchSmart(fileName,currentContentForDiff,content,"Original","Written");const originallyProposedContent=ai_proposed_content||content;const diffStat=getDiffStat(fileName,currentContentForDiff,originallyProposedContent,content);const llmSuccessMessageParts=[!fileExists2?`Successfully created and wrote to new file: ${file_path}.`:`Successfully overwrote file: ${file_path}.`];if(modified_by_user){llmSuccessMessageParts.push(`User modified the \`content\` to be: ${content}`)}const artifact=buildWorkspaceArtifactCandidate(this.config,file_path,{recordAsArtifact:this.params.record_as_artifact,sizeBytes:postWriteSizeBytes});if(artifact&&!artifact.updateOnly){llmSuccessMessageParts.push(formatRecordArtifactReminder(artifact.workspacePath))}const mimetype=getSpecificMimeType(file_path);const programmingLanguage=getLanguageFromFilePath(file_path);const extension=path.extname(file_path);const operation=!fileExists2?"create":"update";const lineCount=content.split("\n").length;logFileOperation(this.config,new FileOperationEvent(WriteFileTool.Name,operation,lineCount,mimetype,extension,programmingLanguage));const displayResult={fileDiff,fileName,filePath:file_path,originalContent,newContent:content,diffStat};return{llmContent:llmSuccessMessageParts.join(" "),returnDisplay:displayResult,...artifact?{artifacts:[artifact]}:{}}}catch(error){return this.writeFailure(error)}}writeFailure(error){const file_path=this.params.file_path;let errorMsg;let errorType="file_write_failure";if(isNodeError(error)){errorMsg=`Error writing to file '${file_path}': ${error.message} (${error.code})`;if(error.code==="ESTALE"&&this.config.getShellExecutionSandbox?.()){errorType="file_changed_since_read"}else if(error.code==="EACCES"){errorMsg=`Permission denied writing to file: ${file_path} (${error.code})`;errorType="permission_denied"}else if(error.code==="ENOSPC"){errorMsg=`No space left on device: ${file_path} (${error.code})`;errorType="no_space_left"}else if(error.code==="EISDIR"){errorMsg=`Target is a directory, not a file: ${file_path} (${error.code})`;errorType="target_is_directory"}if(this.config.getDebugMode()&&error.stack){debugLogger.debug("Write file error stack:",error.stack)}}else{errorMsg=`Error writing to file: ${getErrorMessage(error)}`}return{llmContent:errorMsg,returnDisplay:errorMsg,error:{message:errorMsg,type:errorType}}}};var WRITE_FILE_ARTIFACT_DESCRIPTION="Artifact-like files such as HTML, PDF, images, notebooks, office documents, CSV, Markdown, JSON, SQL, and Python files are automatically registered as session artifacts. Set record_as_artifact=false for intermediates, such as HTML written only to print a PDF: that does not create an artifact, but one the session already has for the path is still refreshed. Files under .qwen/tmp/ are not registered. Delete intermediates when done.";var WriteFileTool=class _WriteFileTool extends BaseDeclarativeTool{constructor(config){super(_WriteFileTool.Name,ToolDisplayNames.WRITE_FILE,`Writes content to a specified file in the local filesystem. A request to create or generate a file does not establish that the target path is new. Unless the target's absence or current text contents have already been established in this session, you MUST use the ${ToolNames.READ_FILE} tool first; if the file does not exist, then create it. With prior-read enforcement enabled, blind overwrites are rejected. The file_path argument MUST be an absolute path. Always construct it by combining the project root with the file's relative path (e.g. project root '/path/to/project/' + relative 'foo/bar.txt' = '/path/to/project/foo/bar.txt'). If the user provides a relative path, resolve it against the project root first.
|
|
4
4
|
|
|
5
5
|
${WRITE_FILE_ARTIFACT_DESCRIPTION}
|
|
6
6
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{MOD_MAX_BYTES,MOD_MAX_DEPTH,MOD_TOOL_RESERVED,jsonDepth,record,validateInput}from"./chunk-XWYUQMLN.js";import{CoreToolScheduler}from"./chunk-
|
|
3
|
+
import{MOD_MAX_BYTES,MOD_MAX_DEPTH,MOD_TOOL_RESERVED,jsonDepth,record,validateInput}from"./chunk-XWYUQMLN.js";import{CoreToolScheduler}from"./chunk-ZUWLTGSR.js";import{ToolNames,canonicalToolName,resolveRegisteredToolName}from"./chunk-SBZFGYYS.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();import{isDeepStrictEqual}from"node:util";async function modToolRequest(config,request){const name=canonicalToolName(request.name);if(request.goalContext||name===ToolNames.STRUCTURED_OUTPUT||name===ToolNames.TOOL_SEARCH||name===ToolNames.SEARCH_MEMORY||request.executionOrigin?.kind==="fixed_policy")return void 0;if(name!==ToolNames.TOOL_CALL)return config.getToolRegistry().getTool(name)||config.getToolRegistry().getAllToolNames().includes(name)?{...request,name}:void 0;const targetName=request.args["name"];let args=request.args["arguments"];if(typeof args==="string"){try{args=JSON.parse(args)}catch{return void 0}}if(typeof targetName!=="string"||!record(args))return void 0;const registry=config.getToolRegistry();const resolved=resolveRegisteredToolName(canonicalToolName(targetName),registry.getAllToolNames());if(typeof resolved!=="string"||resolved===ToolNames.TOOL_CALL||resolved===ToolNames.TOOL_SEARCH||resolved===ToolNames.SEARCH_MEMORY)return void 0;let target;try{target=await registry.ensureTool(resolved)}catch{return void 0}if(!target||!registry.isDeferredAndHidden(target.name)||target.name===ToolNames.STRUCTURED_OUTPUT)return void 0;return{...request,name:target.name,args}}__name(modToolRequest,"modToolRequest");async function executeModTool(request,execution,middleware,execute,signal){const shadowed=Object.fromEntries(MOD_TOOL_RESERVED.filter(key=>Object.hasOwn(execution.args,key)).map(key=>[key,execution.args[key]]));const input={...execution.args,tool:execution.name,tool_use_id:request.callId};for(const key of MOD_TOOL_RESERVED)delete input[key];input.tool=execution.name;input.tool_use_id=request.callId;if(Object.keys(shadowed).length)input["$shadowed"]=shadowed;const refs=new Map;let latest;let executed;let attempts=0;let answer;try{answer=await middleware(input,async(changed,active,check)=>{active.throwIfAborted();validateInput("tool.call",changed,input);if(++attempts>64)throw new Error("Mod tool execution limit exceeded.");const args={...changed};for(const key of MOD_TOOL_RESERVED)delete args[key];Object.assign(args,shadowed);const nativeRequest=canonicalToolName(request.name)===ToolNames.TOOL_CALL?{...request,args:{...request.args,arguments:structuredClone(args)}}:{...request,args:structuredClone(args)};const completed=await execute(nativeRequest,active,check);latest=completed;if(completed.response.executionStatus==="success"||completed.response.executionStatus==="error"&&executed?.response.executionStatus!=="success")executed=completed;const response2=completed.response;let result2=response2.responseParts.find(part=>part.functionResponse)?.functionResponse?.response??{};let json=JSON.stringify(result2);if(Buffer.byteLength(json)>MOD_MAX_BYTES/2||jsonDepth(json)>MOD_MAX_DEPTH/2){result2={output:"[Native tool result exceeds the Mod payload limit; return this reference unchanged to retain it.]"};json=JSON.stringify(result2)}const value={ref:attempts,result:JSON.parse(json),text:(record(result2)&&typeof result2["output"]==="string"?result2["output"]:json).slice(0,16e3),...response2.error?{isError:true}:{}};refs.set(attempts,{completed,value});return value},signal)}catch(error2){answer={deny:`Mod tool dispatch failed: ${String(error2)}`}}const referenced=!("deny"in answer)&&answer.ref!==void 0?refs.get(answer.ref):void 0;const selected=referenced?.completed??latest;const native=selected?.response;if(latest?.response.error&&(latest.response.executionStatus==="not_started"||latest.response.executionStatus==="cancelled")){if(!executed)return{response:latest.response,completed:latest};const message2=`An earlier Mod tool attempt ran. A later attempt failed: ${latest.response.error.message}`;return{completed:executed,response:{...latest.response,executionStatus:executed.response.executionStatus,error:new Error(message2),resultDisplay:message2,contentLength:message2.length,responseParts:[{functionResponse:{id:request.callId,name:request.name,response:{error:message2}}}]}}}if(referenced&&!("deny"in answer)&&isDeepStrictEqual(answer.result,referenced.value.result)){return{response:{...referenced.completed.response,executionStatus:executed?.response.executionStatus??referenced.completed.response.executionStatus},completed:executed??referenced.completed}}const message="deny"in answer?`${executed?"The tool ran; a Mod withheld its result. ":"Tool denied by Mod. "}${answer.deny}`:void 0;const result="deny"in answer?{error:message}:record(answer.result)&&Object.entries(answer.result).every(([key,value])=>(key==="output"||key==="error")&&typeof value==="string")?answer.result:{output:typeof answer.result==="string"?answer.result:JSON.stringify(answer.result)};const text=JSON.stringify(result);const error=message?new Error(message):native?.error??(!("deny"in answer)&&answer.isError?new Error("Mod returned an error result."):void 0);const response={...native,callId:request.callId,responseParts:[{functionResponse:{id:request.callId,name:request.name,response:result}}],resultDisplay:text,contentLength:text.length,executionStatus:executed?.response.executionStatus??native?.executionStatus??"not_started",error,errorType:native?.errorType??(error?"execution_denied":void 0)};return{response,completed:executed??selected}}__name(executeModTool,"executeModTool");async function executeToolCall(config,toolCallRequest,abortSignal,options={}){const execution=options.modToolCall&&await modToolRequest(config,toolCallRequest);if(execution&&options.modToolCall){const{response,completed}=await executeModTool(toolCallRequest,execution,options.modToolCall,async(request,signal,check)=>{let completed2;await executeToolCall(config,request,signal,{...options,modToolCall:void 0,modToolCheck:check,recordToolResult:false,onAllToolCallsComplete:__name(async calls=>{completed2=calls[0]},"onAllToolCallsComplete")});if(!completed2)throw new Error("Mod native tool did not complete.");return completed2},abortSignal);if(completed)await options.onAllToolCallsComplete?.([{...completed,response}]);if(options.recordToolResult!==false)config.getChatRecordingService()?.recordToolResult(response.responseParts,{...response,status:completed?.status??(response.error?"error":"success")});return response}return new Promise((resolve,reject)=>{new CoreToolScheduler({config,isFinished:options.isFinished,modToolCheck:options.modToolCheck,chatRecordingService:options.recordToolResult===false?void 0:config.getChatRecordingService(),outputUpdateHandler:options.outputUpdateHandler,onAllToolCallsComplete:__name(async completedToolCalls=>{if(options.onAllToolCallsComplete){await options.onAllToolCallsComplete(completedToolCalls)}resolve(completedToolCalls[0].response)},"onAllToolCallsComplete"),onToolCallsUpdate:options.onToolCallsUpdate,onToolResultFullTurnModel:options.onToolResultFullTurnModel,getPreferredEditor:__name(()=>void 0,"getPreferredEditor"),onEditorClose:__name(()=>{},"onEditorClose")}).schedule(toolCallRequest,abortSignal,options.runtimeView).catch(reject)})}__name(executeToolCall,"executeToolCall");export{modToolRequest,executeModTool,executeToolCall};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2026 Qwen Team
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{useKeypress}from"./chunk-
|
|
3
|
+
import{useKeypress}from"./chunk-LDP47G5M.js";import{require_react}from"./chunk-5QKDV4CD.js";import{t}from"./chunk-AUM57JI2.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
|