@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{readConfigFile}from"./chunk-
|
|
3
|
+
import{readConfigFile}from"./chunk-4RJ2RRGZ.js";import{require_strip_json_comments,stripUtf8Bom}from"./chunk-EKRCICRK.js";import{normalizeClaudeMcpServer}from"./chunk-ZUWLTGSR.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs";import*as path from"node:path";var import_strip_json_comments=__toESM(require_strip_json_comments(),1);var PROJECT_MCP_FILENAME=".mcp.json";function loadProjectMcpServers(projectRoot,options={}){const filePath=path.join(projectRoot,PROJECT_MCP_FILENAME);let raw;try{raw=options.strict?readConfigFile(filePath):fs.readFileSync(filePath,"utf-8")}catch(e){if(!options.strict)return{servers:{},path:void 0,errors:[]};return{servers:{},path:filePath,errors:[`Failed to read ${filePath}: ${e.message}`]}}if(raw===void 0)return{servers:{},path:void 0,errors:[]};let parsed;try{parsed=JSON.parse((0,import_strip_json_comments.default)(stripUtf8Bom(raw)))}catch(e){return{servers:{},path:filePath,errors:[`Failed to parse ${filePath}: ${e.message}`]}}const mcpServers=parsed?.mcpServers;if(!mcpServers||typeof mcpServers!=="object"||Array.isArray(mcpServers)){return{servers:{},path:filePath,errors:[`${filePath} has no "mcpServers" object`]}}const servers=Object.create(null);const errors=[];for(const[name,value]of Object.entries(mcpServers)){if(!value||typeof value!=="object"||Array.isArray(value)){errors.push(`${filePath}: server "${name}" is not an object \u2014 skipped`);continue}servers[name]={...normalizeClaudeMcpServer(value),scope:"project"}}return{servers,path:filePath,errors}}__name(loadProjectMcpServers,"loadProjectMcpServers");export{loadProjectMcpServers};
|
|
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{SessionOrganizationService}from"./chunk-
|
|
3
|
+
import{SessionOrganizationService}from"./chunk-ZUWLTGSR.js";import{writeStderrLine}from"./chunk-M4ECEHLX.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();function createSessionOrganizationService(workspaceCwd){return new SessionOrganizationService(workspaceCwd,message=>{writeStderrLine(`qwen serve: session-org: ${message}`)})}__name(createSessionOrganizationService,"createSessionOrganizationService");export{createSessionOrganizationService};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2025 Qwen Team
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";init_esbuild_shims();var GIT_COMMIT_INFO="448638a9db";var CLI_VERSION="0.0.
|
|
3
|
+
import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";init_esbuild_shims();var GIT_COMMIT_INFO="448638a9db";var CLI_VERSION="0.0.9-beta";export{GIT_COMMIT_INFO,CLI_VERSION};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2026 Google LLC
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{buildModelReasoningRoutePreview}from"./chunk-
|
|
3
|
+
import{buildModelReasoningRoutePreview}from"./chunk-NHYFTK4O.js";import{snapshotProcessEnv}from"./chunk-EXVVGGII.js";import{publicAuxModelSelectorValue}from"./chunk-L42NTHIT.js";import{getModelConfigurationKey}from"./chunk-26JPBN6V.js";import{STATUS_SCHEMA_VERSION}from"./chunk-YCAEGUZI.js";import{loadSettings}from"./chunk-4RJ2RRGZ.js";import{getAuthTypeFromEnv,resolveCliGenerationConfig}from"./chunk-IYH3IZL4.js";import{ACP_ROUTE_ID_PREFIX,buildAcpModelOptions,getCurrentAcpModelId,parseAcpBaseModelId,sanitizeProviderBaseUrl}from"./chunk-YQXX44YA.js";import{APPROVAL_MODES}from"./chunk-JZK2WGXA.js";import{ModelsConfig,captureReasoningSnapshot,resolveReasoningForModel}from"./chunk-SINRWOVD.js";import{tokenLimit}from"./chunk-EV2CXPMN.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var debugLogger=createDebugLogger("WORKSPACE_PROVIDERS_STATUS");function createWorkspaceProvidersStatusProvider(options={}){return async(workspaceCwd,acpChannelLive)=>buildWorkspaceProvidersStatus(workspaceCwd,acpChannelLive,options)}__name(createWorkspaceProvidersStatusProvider,"createWorkspaceProvidersStatusProvider");function buildWorkspaceProvidersStatus(workspaceCwd,acpChannelLive,options){try{const loaded=loadSettings(workspaceCwd,options.env?{skipLoadEnvironment:true,skipWorkspaceSettings:options.workspaceTrusted===false,workspaceTrusted:options.workspaceTrusted}:{consumeCorruptionEnvVars:true,skipLoadEnvironment:options.workspaceTrusted===false,skipWorkspaceSettings:options.workspaceTrusted===false,workspaceTrusted:options.workspaceTrusted});const settings=loaded.merged;const env=options.env??snapshotProcessEnv();const selectedAuthType=settings.security?.auth?.selectedType??getAuthTypeFromEnv(env);const argv={model:options.argv?.model,openaiApiKey:options.argv?.openaiApiKey,openaiBaseUrl:options.argv?.openaiBaseUrl,openaiLogging:options.argv?.openaiLogging,openaiLoggingDir:options.argv?.openaiLoggingDir};const resolvedCliConfig=resolveCliGenerationConfig({argv,settings,selectedAuthType,env});const modelsConfig=new ModelsConfig({initialAuthType:resolvedCliConfig.authType,modelProvidersConfig:settings.modelProviders,providerProtocolConfig:settings.providerProtocol,generationConfig:resolvedCliConfig.generationConfig,generationConfigSources:resolvedCliConfig.sources});const currentAuth=resolvedCliConfig.authType;let currentModelId=(resolvedCliConfig.model||modelsConfig.getModel()||"").trim();const requestedModelId=currentModelId;if(currentAuth&&!modelsConfig.getResolvedModel(currentAuth,currentModelId)){modelsConfig.syncAfterAuthRefresh(currentAuth,currentModelId);currentModelId=(modelsConfig.getModel()||"").trim()}const usedFallback=currentModelId!==requestedModelId;const hasCurrentModel=currentModelId.length>0;const modelCameFromSettings=!argv.model&&settings.model?.name?.trim()===currentModelId;const currentBaseUrl=usedFallback?modelsConfig.getGenerationConfig().baseUrl:modelCameFromSettings&&settings.model?.baseUrl!==void 0?settings.model.baseUrl||void 0:resolvedCliConfig.sources["baseUrl"]?resolvedCliConfig.baseUrl||void 0:void 0;const currentRegistryBaseUrl=usedFallback?modelsConfig.getCurrentRegistryBaseUrl():modelCameFromSettings&¤tAuth?settings.model?.baseUrl!==void 0?settings.model.baseUrl||null:modelsConfig.getResolvedModel(currentAuth,currentModelId)?.registryBaseUrl??null:void 0;const models=modelsConfig.getAllConfiguredModels();const modelOptions=buildAcpModelOptions(models);const reasoningSnapshot=captureReasoningSnapshot(models);const currentAcpModelId=hasCurrentModel?getCurrentAcpModelId(modelOptions,currentModelId,currentAuth,currentRegistryBaseUrl):void 0;const fastModelId=typeof settings.fastModel==="string"&&settings.fastModel.length>0?settings.fastModel:void 0;const visionModelId=typeof settings.visionModel==="string"&&settings.visionModel.length>0?settings.visionModel:void 0;const approvalMode=resolveApprovalMode(settings);const providers=new Map;for(const option of modelOptions){const{model,effectiveModelId,modelId}=option;if(model.isRuntimeModel)continue;const authType=String(model.authType);let provider=providers.get(authType);if(!provider){provider={kind:"model_provider",status:"ok",authType,current:false,models:[]};providers.set(authType,provider)}const isCurrent=currentAuth===model.authType&¤tAcpModelId===modelId;const resolved=modelsConfig.getResolvedModel(model.authType,model.id,model.registryBaseUrl);const generation={...resolved?.generationConfig,model:model.id,authType:model.authType,baseUrl:resolved?.baseUrl,reasoningSnapshot,reasoningRouteBaseUrl:model.registryBaseUrl??null};const configOptions=buildModelReasoningRoutePreview(generation,resolveReasoningForModel(void 0,generation),settings.model?.reasoningEffort,modelId.startsWith(ACP_ROUTE_ID_PREFIX));const configurationKey=getModelConfigurationKey(loaded,authType,model.id,model.registryBaseUrl);const providerModel={...configurationKey?{configurationKey}:{},modelId,baseModelId:parseAcpBaseModelId(effectiveModelId),name:model.label,...model.description!==void 0?{description:model.description}:{},contextLimit:model.contextWindowSize!==void 0&&model.contextWindowSize>0?model.contextWindowSize:tokenLimit(effectiveModelId),...model.modalities!==void 0?{modalities:model.modalities}:{},...model.baseUrl!==void 0?{baseUrl:sanitizeProviderBaseUrl(model.baseUrl)}:{},...model.envKey!==void 0?{envKey:model.envKey}:{},isCurrent,isRuntime:false,...configOptions?{configOptions}:{}};provider.models.push(providerModel);if(isCurrent)provider.current=true}const current=buildCurrent(currentAuth,currentAcpModelId,currentBaseUrl,fastModelId,visionModelId);return{v:STATUS_SCHEMA_VERSION,workspaceCwd,initialized:true,acpChannelLive,...current?{current}:{},approvalMode,providers:[...providers.values()],...resolvedCliConfig.warnings.length>0?{errors:resolvedCliConfig.warnings.map(warning=>({kind:"providers",status:"warning",error:sanitizeProviderWarning(warning)}))}:{}}}catch(error){return{v:STATUS_SCHEMA_VERSION,workspaceCwd,initialized:false,acpChannelLive,providers:[],errors:[{kind:"providers",status:"error",error:sanitizeProviderWarning(error instanceof Error?error.message:String(error))}]}}}__name(buildWorkspaceProvidersStatus,"buildWorkspaceProvidersStatus");function resolveApprovalMode(settings){const value=settings.tools?.approvalMode;if(typeof value!=="string")return"auto";const normalized=value.trim().toLowerCase().replaceAll("_","-");const mode=normalized==="autoedit"?"auto-edit":normalized;if(APPROVAL_MODES.includes(mode)){return mode}if(value.trim().length>0){debugLogger.warn(`[workspace-providers-status] unrecognized approvalMode "${value}", falling back to auto`)}return"auto"}__name(resolveApprovalMode,"resolveApprovalMode");var URL_LIKE_PATTERN=/\b[A-Za-z][A-Za-z\d+.-]*:\/\/[^\s'"`<>]+/g;var URL_START_PATTERN=/\b[A-Za-z][A-Za-z\d+.-]*:\/\//g;function sanitizeProviderWarning(warning){let result="";let index=0;let next=findNextUrlStart(warning,index);while(next){result+=warning.slice(index,next.index);const segmentEnd=findUrlSegmentEnd(warning,next.index,next.marker);const segment=warning.slice(next.index,segmentEnd);result+=sanitizeProviderWarningSegment(segment,next.marker.length);index=segmentEnd;next=findNextUrlStart(warning,index)}return result+warning.slice(index)}__name(sanitizeProviderWarning,"sanitizeProviderWarning");function findNextUrlStart(value,from){URL_START_PATTERN.lastIndex=from;const match=URL_START_PATTERN.exec(value);return match?{index:match.index,marker:match[0]}:void 0}__name(findNextUrlStart,"findNextUrlStart");function findUrlSegmentEnd(value,start,marker){const afterMarker=start+marker.length;const carriageReturn=value.indexOf("\r",afterMarker);const lineFeed=value.indexOf("\n",afterMarker);let lineEnd=value.length;if(carriageReturn!==-1)lineEnd=Math.min(lineEnd,carriageReturn);if(lineFeed!==-1)lineEnd=Math.min(lineEnd,lineFeed);const nextUrl=findNextUrlStart(value,afterMarker);return Math.min(lineEnd,nextUrl?.index??value.length)}__name(findUrlSegmentEnd,"findUrlSegmentEnd");function sanitizeProviderWarningSegment(segment,markerLength){const at=segment.indexOf("@",markerLength);if(at!==-1&&hasCredentialPrefix(segment,markerLength,at)&&segment[at+1]!==void 0&&/[A-Za-z0-9.[\]-]/.test(segment[at+1])){return`${segment.slice(0,markerLength)}${segment.slice(at+1)}`}return segment.replace(URL_LIKE_PATTERN,url=>sanitizeProviderBaseUrl(url))}__name(sanitizeProviderWarningSegment,"sanitizeProviderWarningSegment");function hasCredentialPrefix(segment,markerLength,at){const colon=segment.indexOf(":",markerLength);if(colon===-1||colon>at)return false;const username=segment.slice(markerLength,colon);return!/[/?#\s'"`<>]/.test(username)}__name(hasCredentialPrefix,"hasCredentialPrefix");function buildCurrent(authType,modelId,baseUrl,fastModelId,visionModelId){if(!authType&&!modelId&&!baseUrl&&!fastModelId&&!visionModelId)return void 0;return{...authType?{authType:String(authType)}:{},...modelId?{modelId}:{},...baseUrl?{baseUrl:sanitizeProviderBaseUrl(baseUrl)}:{},...fastModelId?{fastModelId:publicAuxModelSelectorValue(fastModelId)}:{},...visionModelId?{visionModelId:publicAuxModelSelectorValue(visionModelId)}:{}}}__name(buildCurrent,"buildCurrent");export{createWorkspaceProvidersStatusProvider};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2025 Qwen Team
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{buildScheduledTaskRunPrompt,parseChannelDelivery,scheduledTaskRunSessionName,scheduledTaskRunSourceId}from"./chunk-XGPGIMZK.js";import{createSessionOrganizationService}from"./chunk-M3IQE5G4.js";import{requireTrustedWorkspaceRuntime,resolveWorkspaceRuntimeWithLiveCompatibilityFromParam,sendConversationRuntimeUnavailable,sendGenerationClosedError}from"./chunk-KZZ5ZQHX.js";import{parseCallerSuppliedSessionId}from"./chunk-LGFF5PJA.js";import{SCHEDULED_TASK_RUN_SOURCE_TYPE}from"./chunk-K2PGOAJP.js";import{SessionNotFoundError}from"./chunk-CVMEBFLL.js";import{isChannelDeliveryError}from"./chunk-O6ZQAVRG.js";import{MAX_JOBS,SessionService,gateCommandError,nextDurableFireMs,nextFireTime,parseCron}from"./chunk-POMEWCFJ.js";import{stripTerminalControlSequences}from"./chunk-R2EHHA2C.js";import{MAX_CRON_TASK_ROUTING_ID_LENGTH,annotateCronRunSession,appendCronRun,cronTaskSessionDeletionId,generateCronTaskId,getCronFilePath,isValidCronTaskRoutingId,readCronTasks,taskHasLegacyCondition,updateCronTasks,withTaskGate}from"./chunk-DXUYBMFK.js";import{writeStderrLine}from"./chunk-M4ECEHLX.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{isDeepStrictEqual}from"node:util";import{access}from"node:fs/promises";var MAX_SCHEDULED_TASKS=MAX_JOBS;var MAX_PROMPT_LENGTH=1e5;var MAX_NAME_LENGTH=200;var MAX_CRON_LENGTH=200;var MAX_ROUTING_ID_LENGTH=MAX_CRON_TASK_ROUTING_ID_LENGTH;var MAX_SESSION_NAME_LENGTH=60;function scheduledTaskSessionName(label){const cleaned=stripTerminalControlSequences(label).replace(/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g,"").trim().replace(/\s+/g," ");let short=cleaned;if(cleaned.length>MAX_SESSION_NAME_LENGTH){let cut=MAX_SESSION_NAME_LENGTH-1;const boundary=cleaned.charCodeAt(cut-1);if(boundary>=55296&&boundary<=56319)cut-=1;short=`${cleaned.slice(0,cut)}\u2026`}return short}__name(scheduledTaskSessionName,"scheduledTaskSessionName");var ExistingSessionScheduledTaskCreateError=class extends Error{constructor(status,code,message){super(message);this.status=status;this.code=code;this.name="ExistingSessionScheduledTaskCreateError"}static{__name(this,"ExistingSessionScheduledTaskCreateError")}};function assertReusableScheduledTaskSession(target,sessionId,allowActivePrompt,assertCallerPromptActive){const{bridge,workspaceCwd}=target;if(!bridge){throw new ExistingSessionScheduledTaskCreateError(409,"session_binding_unavailable","Session management is not available for this workspace")}assertCallerPromptActive?.();let owner;try{owner=target.resolveLiveSessionOwner?.(sessionId)}catch(error){writeStderrLine(`qwen serve: failed to resolve scheduled-task session owner '${sessionId}': ${error instanceof Error?error.message:String(error)}`);throw new ExistingSessionScheduledTaskCreateError(500,"scheduled_tasks_session_failed","Failed to look up the requested session")}if(owner?.kind==="unavailable"){throw new ExistingSessionScheduledTaskCreateError(503,"workspace_runtime_unavailable","The workspace runtime is unavailable")}if(owner?.kind==="ambiguous"){throw new ExistingSessionScheduledTaskCreateError(500,"ambiguous_session_owner",`Session owner is ambiguous for "${sessionId}"`)}if(owner?.kind==="found"&&owner.runtime.workspaceCwd!==workspaceCwd){throw new ExistingSessionScheduledTaskCreateError(400,"session_workspace_mismatch","The requested session belongs to a different workspace; use that workspace's scheduled-task endpoint")}let summary;try{summary=bridge.getSessionSummary(sessionId)}catch(error){if(error instanceof SessionNotFoundError){throw new ExistingSessionScheduledTaskCreateError(404,"session_not_found",`Session '${sessionId}' was not found`)}writeStderrLine(`qwen serve: failed to look up scheduled-task session '${sessionId}': ${error instanceof Error?error.message:String(error)}`);throw new ExistingSessionScheduledTaskCreateError(500,"scheduled_tasks_session_failed","Failed to look up the requested session")}if(summary.workspaceCwd!==workspaceCwd){throw new ExistingSessionScheduledTaskCreateError(400,"session_workspace_mismatch","The requested session belongs to a different workspace; use that workspace's scheduled-task endpoint")}if(!allowActivePrompt&&summary.hasActivePrompt||(summary.pendingInteractionCount??0)>0){throw new ExistingSessionScheduledTaskCreateError(409,"session_busy",allowActivePrompt?"The caller session has a pending interaction; resolve it before binding the session to a task":"The requested session is busy; wait for its active prompt or pending interaction to finish before binding it to a task")}if(summary.sourceType==="scheduled_task"){throw new ExistingSessionScheduledTaskCreateError(409,"session_already_bound","The requested session is already reserved for a scheduled task")}if(summary.parentSessionId!==void 0||summary.sourceId!==void 0||summary.sourceType!==void 0&&summary.sourceType!=="default"){throw new ExistingSessionScheduledTaskCreateError(409,"session_source_ineligible","The requested session source cannot own a scheduled task")}}__name(assertReusableScheduledTaskSession,"assertReusableScheduledTaskSession");async function createScheduledTaskWithExistingSession(target,input,options){if(input.cron.length===0||input.cron.length>MAX_CRON_LENGTH||validateCron(input.cron)!==null){throw new ExistingSessionScheduledTaskCreateError(400,"invalid_cron","The scheduled-task cron expression is invalid")}const prompt=input.prompt.trim();if(prompt.length===0||prompt.length>MAX_PROMPT_LENGTH){throw new ExistingSessionScheduledTaskCreateError(400,"invalid_prompt","The scheduled-task prompt is invalid")}const gate=input.gate?.trim();if(gate!==void 0){const gateError=gateCommandError(gate);if(gateError){throw new ExistingSessionScheduledTaskCreateError(400,"invalid_gate",`The scheduled-task gate ${gateError}`)}if(!input.recurring){throw new ExistingSessionScheduledTaskCreateError(400,"gate_requires_recurring",GATE_REQUIRES_RECURRING_MESSAGE)}}const allowActivePrompt=options.source==="cron-tool";const assertCallerPromptActive=options.source==="cron-tool"?options.assertCallerPromptActive:void 0;assertReusableScheduledTaskSession(target,input.sessionId,allowActivePrompt,assertCallerPromptActive);target.assertGenerationOpen?.();if(options.source==="rest"){const ensurePersisted=target.bridge?.ensureDefaultSessionPersisted;if(!ensurePersisted){throw new ExistingSessionScheduledTaskCreateError(409,"session_binding_unavailable","Session persistence is not available for this workspace")}try{await ensurePersisted.call(target.bridge,input.sessionId)}catch(error){target.assertGenerationOpen?.();if(error instanceof SessionNotFoundError){throw new ExistingSessionScheduledTaskCreateError(404,"session_not_found",`Session '${input.sessionId}' was not found`)}writeStderrLine(`qwen serve: failed to persist scheduled-task session '${input.sessionId}': ${error instanceof Error?error.message:String(error)}`);throw new ExistingSessionScheduledTaskCreateError(500,"session_persistence_failed","Failed to persist the requested session")}target.assertGenerationOpen?.()}const now=Date.now();const task=withTaskGate({id:generateCronTaskId(),cron:input.cron,prompt,recurring:input.recurring,createdAt:now,lastFiredAt:now-now%6e4,enabled:input.enabled!==false,sessionId:input.sessionId,sessionOwnedByTask:false,sessionMode:input.sessionMode==="per_run"?"per_run":"persistent",...input.sessionMode==="per_run"&&input.modelServiceId!==void 0?{modelServiceId:input.modelServiceId}:{},...input.sessionMode==="per_run"&&input.groupId!==void 0?{groupId:input.groupId}:{},...input.delivery!==void 0?{delivery:input.delivery}:{},...input.name!==void 0?{name:input.name}:{}},gate);let before;let after;await runWithScheduledTaskTarget(target,()=>updateCronTasks(target.workspaceCwd,tasks=>{assertReusableScheduledTaskSession(target,input.sessionId,allowActivePrompt,assertCallerPromptActive);if(tasks.some(candidate=>candidate.sessionId===input.sessionId)){throw new ExistingSessionScheduledTaskCreateError(409,"session_already_bound","The requested session is already bound to another scheduled task")}if(tasks.length>=MAX_SCHEDULED_TASKS){throw new ExistingSessionScheduledTaskCreateError(409,"max_tasks_reached",`Maximum number of scheduled tasks (${MAX_SCHEDULED_TASKS}) reached`)}before=tasks;after=[...tasks,task];return after},{assertCanCommit:target.assertGenerationOpen}));try{target.assertGenerationOpen?.()}catch(error){await rollbackCronMutation(target,before,after,"scheduled-task create");throw error}return task}__name(createScheduledTaskWithExistingSession,"createScheduledTaskWithExistingSession");function requireOpenGeneration(target,res){try{target.assertGenerationOpen?.();return true}catch(error){if(sendGenerationClosedError(res,error))return false;throw error}}__name(requireOpenGeneration,"requireOpenGeneration");async function rollbackCronMutation(target,before,after,route){if(!before||!after)return;await runWithScheduledTaskTarget(target,()=>updateCronTasks(target.workspaceCwd,tasks=>isDeepStrictEqual(tasks,after)?before:tasks)).catch(error=>{writeStderrLine(`qwen serve: ${route} failed to roll back a stale task mutation: ${error instanceof Error?error.message:String(error)}`)})}__name(rollbackCronMutation,"rollbackCronMutation");async function restoreConsumedOneShot(target,before,failedTask,removalGenerations,route){const id=failedTask.id;const index=before?.findIndex(t=>t.id===id)??-1;const original=index===-1?void 0:before[index];if(!original||!removalGenerations)return;let restoreGenerations;await runWithScheduledTaskTarget(target,()=>updateCronTasks(target.workspaceCwd,tasks=>{if([...removalGenerations].some(([key,generation])=>restoreGenerations?.get(key)!==generation))return tasks;if(tasks.some(t=>t.id===id))return tasks;const restored=[...tasks];restored.splice(Math.min(index,restored.length),0,{...failedTask,enabled:false});return restored},{observeDeletionIds:[...removalGenerations.keys()],onDeletionGenerations:__name(generations=>{restoreGenerations=generations},"onDeletionGenerations")})).catch(error=>{writeStderrLine(`qwen serve: ${route} failed to restore the consumed one-shot task: ${error instanceof Error?error.message:String(error)}`)})}__name(restoreConsumedOneShot,"restoreConsumedOneShot");async function teardownBoundSession(target,sessionId){if(target.cleanupSession){await target.cleanupSession(sessionId).catch(()=>{})}else if(target.bridge){await target.bridge.closeSession(sessionId).catch(()=>{});const removed=await new SessionService(target.workspaceCwd,{runtimeBaseDir:target.runtimeBaseDir}).removeSession(sessionId).catch(()=>false);if(removed)target.bridge.markSessionCatalogChanged?.()}}__name(teardownBoundSession,"teardownBoundSession");async function dispatchTaskToFreshSession(target,task){const{bridge}=target;const sendPrompt=bridge?.sendPrompt?.bind(bridge);if(!bridge||!sendPrompt||!task.sessionId){throw new Error("Fresh-session dispatch is unavailable for this task")}const triggeredAt=task.lastFiredAt??Date.now();const child=await runWithScheduledTaskTarget(target,()=>bridge.spawnOrAttach({workspaceCwd:target.workspaceCwd,...task.modelServiceId?{modelServiceId:task.modelServiceId}:{},sessionScope:"thread",parentSessionId:task.sessionId,sourceType:SCHEDULED_TASK_RUN_SOURCE_TYPE,sourceId:scheduledTaskRunSourceId(task.id)}));try{if(task.modelServiceId&&child.modelApplied===false){throw new Error(`Scheduled task model selection failed: ${task.modelServiceId}`)}try{bridge.updateSessionMetadata(child.sessionId,{displayName:scheduledTaskRunSessionName(task.name??task.prompt,triggeredAt),titleSource:"auto"})}catch{}let markPromptAdmitted;const promptAdmitted=new Promise(resolve=>{markPromptAdmitted=resolve});const turn=sendPrompt(child.sessionId,{sessionId:child.sessionId,prompt:[{type:"text",text:buildScheduledTaskRunPrompt({id:task.id,name:task.name,cron:task.cron,prompt:task.prompt,triggeredAt,trigger:"manual",...task.gate?{gate:task.gate}:{}})}]},void 0,{onPromptAdmitted:markPromptAdmitted});void turn.catch(error=>{writeStderrLine(`qwen serve: scheduled-task session ${child.sessionId} prompt failed: ${error instanceof Error?error.message:String(error)}`)});await Promise.race([promptAdmitted,turn.then(()=>void 0,error=>Promise.reject(error))]);if(task.groupId){try{await runWithScheduledTaskTarget(target,()=>createSessionOrganizationService(target.workspaceCwd).updateSessionOrganization(child.sessionId,{groupId:task.groupId,color:null}));bridge.markSessionCatalogChanged?.()}catch(error){writeStderrLine(`qwen serve: scheduled-task session ${child.sessionId} could not be assigned to group ${task.groupId}: ${error instanceof Error?error.message:String(error)}`)}}}catch(error){await teardownBoundSession(target,child.sessionId);throw error}return child.sessionId}__name(dispatchTaskToFreshSession,"dispatchTaskToFreshSession");async function runWithScheduledTaskTarget(target,fn){const result=target.runtimeBaseDir===void 0?fn():Storage.runWithResolvedRuntimeBaseDir(target.runtimeBaseDir,fn);return await result}__name(runWithScheduledTaskTarget,"runWithScheduledTaskTarget");function sendActivityGateError(res,error){if(!error||typeof error!=="object"||error.code!=="daemon_draining"){return false}res.status(503).json({error:"The daemon is draining and no longer accepts work.",code:"daemon_draining"});return true}__name(sendActivityGateError,"sendActivityGateError");var GATE_REQUIRES_RECURRING_MESSAGE="A gate needs a recurring task: a one-shot whose gate prints nothing would be consumed with nothing delivered";function computeNextRunAt(task){if(task.enabled===false)return null;return nextDurableFireMs(task)}__name(computeNextRunAt,"computeNextRunAt");function toView(task){return{id:task.id,name:typeof task.name==="string"&&task.name.length>0?task.name:null,cron:task.cron,prompt:task.prompt,recurring:task.recurring,enabled:task.enabled!==false&&!taskHasLegacyCondition(task),createdAt:task.createdAt,lastFiredAt:task.lastFiredAt,nextRunAt:taskHasLegacyCondition(task)?null:computeNextRunAt(task),sessionId:typeof task.sessionId==="string"&&task.sessionId.length>0?task.sessionId:null,sessionMode:task.sessionMode==="per_run"?"per_run":"persistent",modelServiceId:task.modelServiceId??null,groupId:task.groupId??null,runs:Array.isArray(task.runs)?task.runs:[],...task.delivery!==void 0?{delivery:task.delivery}:{},gate:typeof task.gate==="string"&&task.gate.length>0?task.gate:null,gateStatus:task.gateStatus??null}}__name(toView,"toView");function validateCron(cron){try{parseCron(cron);nextFireTime(cron,new Date);return null}catch(err){return err instanceof Error?err.message:String(err)}}__name(validateCron,"validateCron");function canonicalCron(cron){try{const f=parseCron(cron);const s=__name(set=>[...set].sort((a,b)=>a-b).join(","),"s");return[s(f.minute),s(f.hour),s(f.dayOfMonth),s(f.month),s(f.dayOfWeek),f.domIsWild?"W":"",f.dowIsWild?"W":""].join("|")}catch{return null}}__name(canonicalCron,"canonicalCron");function registerScheduledTaskCrudRoutes(app,deps){const{prefix,resolveTarget,mutate,safeBody,channelDeliveryAuthorizations}=deps;const base=`${prefix}/scheduled-tasks`;const withTarget=__name(handler=>async(req,res)=>{const target=resolveTarget(req,res);if(!target)return;const operation=__name(async()=>{if(!requireOpenGeneration(target,res))return;await handler(req,res,target)},"operation");try{if(target.activity){await target.activity.run(operation)}else{await operation()}}catch(error){if(sendActivityGateError(res,error))return;throw error}},"withTarget");app.get(base,withTarget(async(_req,res,target)=>{try{const tasks=await runWithScheduledTaskTarget(target,()=>readCronTasks(target.workspaceCwd));if(!requireOpenGeneration(target,res))return;res.status(200).json({v:1,tasks:tasks.map(toView)})}catch(err){if(sendActivityGateError(res,err))return;writeStderrLine(`qwen serve: GET ${base} failed: ${err instanceof Error?err.message:String(err)}`);res.status(500).json({error:"Failed to read scheduled tasks (the tasks file may be corrupt)",code:"scheduled_tasks_read_failed"})}}));app.post(base,mutate(),withTarget(async(req,res,target)=>{const{workspaceCwd,bridge}=target;const body=safeBody(req);const cron=typeof body["cron"]==="string"?body["cron"].trim():"";if(cron.length===0){res.status(400).json({error:"`cron` is required and must be a non-empty string",code:"invalid_cron"});return}if(cron.length>MAX_CRON_LENGTH){res.status(400).json({error:`\`cron\` exceeds ${MAX_CRON_LENGTH}-character limit`,code:"invalid_cron"});return}const cronError=validateCron(cron);if(cronError){res.status(400).json({error:cronError,code:"invalid_cron"});return}const prompt=typeof body["prompt"]==="string"?body["prompt"].trim():"";if(prompt.length===0){res.status(400).json({error:"`prompt` is required and must be a non-empty string",code:"invalid_prompt"});return}if(prompt.length>MAX_PROMPT_LENGTH){res.status(400).json({error:`\`prompt\` exceeds ${MAX_PROMPT_LENGTH}-character limit`,code:"invalid_prompt"});return}const nameResult=parseNameField(body["name"]);if(nameResult.error){res.status(400).json({error:nameResult.error,code:"invalid_name"});return}if(body["recurring"]!==void 0&&typeof body["recurring"]!=="boolean"){res.status(400).json({error:"`recurring` must be a boolean",code:"invalid_recurring"});return}if(body["enabled"]!==void 0&&typeof body["enabled"]!=="boolean"){res.status(400).json({error:"`enabled` must be a boolean",code:"invalid_enabled"});return}const sessionMode=body["sessionMode"]===void 0?"persistent":body["sessionMode"];if(sessionMode!=="persistent"&&sessionMode!=="per_run"){res.status(400).json({error:'`sessionMode` must be "persistent" or "per_run"',code:"invalid_session_mode"});return}const modelServiceId=body["modelServiceId"];if(modelServiceId!==void 0&&!isValidCronTaskRoutingId(modelServiceId)){res.status(400).json({error:`\`modelServiceId\` must be a non-empty string of at most ${MAX_ROUTING_ID_LENGTH} characters without control characters`,code:"invalid_model_service_id"});return}const groupId=body["groupId"];if(groupId!==void 0&&!isValidCronTaskRoutingId(groupId)){res.status(400).json({error:`\`groupId\` must be a non-empty string of at most ${MAX_ROUTING_ID_LENGTH} characters without control characters`,code:"invalid_group_id"});return}if(sessionMode!=="per_run"&&(modelServiceId!==void 0||groupId!==void 0)){res.status(400).json({error:'`modelServiceId` and `groupId` are only supported when `sessionMode` is "per_run"',code:"session_routing_requires_per_run"});return}if(typeof groupId==="string"){const groups=await runWithScheduledTaskTarget(target,()=>createSessionOrganizationService(workspaceCwd).listGroups());if(!groups.groups.some(group=>group.id===groupId)){res.status(400).json({error:`Group not found: ${groupId}`,code:"group_not_found"});return}}const parsedSessionId=parseCallerSuppliedSessionId(body["sessionId"]);if(parsedSessionId.kind==="invalid"){res.status(400).json({error:'`sessionId` must be an RFC UUID v1-v5 (e.g. "550e8400-e29b-41d4-a716-446655440000")',code:"invalid_session_id"});return}const providedSessionId=parsedSessionId.kind==="valid"?parsedSessionId.sessionId:void 0;let delivery;if(body["delivery"]!==void 0){try{delivery=parseChannelDelivery(body["delivery"])}catch(err){if(!isChannelDeliveryError(err))throw err;res.status(400).json({error:err.message,code:err.code});return}}if(sessionMode==="per_run"&&delivery!==void 0){res.status(400).json({error:"Per-run sessions do not support channel delivery",code:"session_mode_delivery_unsupported"});return}const removedField=findRemovedTaskField(body);if(removedField){res.status(400).json(removedFieldError(removedField));return}const recurring=body["recurring"]!==false;const enabled=body["enabled"]!==false;let gate;if(body["gate"]!==void 0&&body["gate"]!==null){const gateError=gateCommandError(body["gate"]);if(gateError){res.status(400).json({error:`\`gate\` ${gateError}`,code:"invalid_gate"});return}gate=body["gate"].trim();if(!recurring){res.status(400).json({error:GATE_REQUIRES_RECURRING_MESSAGE,code:"gate_requires_recurring"});return}}const taskId=generateCronTaskId();if(sessionMode==="per_run"&&(!bridge||!bridge.sendPrompt)){res.status(409).json({error:"Fresh-session dispatch is not available for this workspace",code:"session_mode_unavailable"});return}if(providedSessionId!==void 0){try{const task2=await createScheduledTaskWithExistingSession(target,{sessionId:providedSessionId,cron,prompt,recurring,enabled,sessionMode,...typeof modelServiceId==="string"?{modelServiceId}:{},...typeof groupId==="string"?{groupId}:{},...delivery!==void 0?{delivery}:{},...nameResult.value!==void 0?{name:nameResult.value}:{},...gate!==void 0?{gate}:{}},{source:"rest"});if(task2.delivery&&task2.sessionId){channelDeliveryAuthorizations?.registerScheduledTask(workspaceCwd,{sessionId:task2.sessionId,taskId:task2.id,target:task2.delivery.target,recurring:task2.recurring,lastFiredAt:task2.lastFiredAt??void 0})}res.status(201).json(toView(task2))}catch(error){if(error instanceof ExistingSessionScheduledTaskCreateError){if(error.code==="workspace_runtime_unavailable"){res.set("Retry-After","1")}res.status(error.status).json({error:error.message,code:error.code});return}if(sendActivityGateError(res,error))return;if(sendGenerationClosedError(res,error))return;writeStderrLine(`qwen serve: POST ${base} failed to create a task for session '${providedSessionId}': ${error instanceof Error?error.message:String(error)}`);res.status(500).json({error:"Failed to create scheduled task",code:"scheduled_tasks_write_failed"})}return}let boundSessionId;let sessionMintedHere=false;if(bridge){try{const tasks=await runWithScheduledTaskTarget(target,()=>readCronTasks(workspaceCwd));if(tasks.length>=MAX_SCHEDULED_TASKS){res.status(409).json({error:`Maximum number of scheduled tasks (${MAX_SCHEDULED_TASKS}) reached`,code:"max_tasks_reached"});return}}catch{}if(!requireOpenGeneration(target,res))return;try{const session=await runWithScheduledTaskTarget(target,()=>bridge.spawnOrAttach({workspaceCwd,sessionScope:"thread",sourceType:"scheduled_task",sourceId:taskId}));boundSessionId=session.sessionId;sessionMintedHere=true;if(!requireOpenGeneration(target,res)){await teardownBoundSession(target,boundSessionId);return}try{await runWithScheduledTaskTarget(target,async()=>bridge.updateSessionMetadata(boundSessionId,{displayName:scheduledTaskSessionName(nameResult.value??prompt),titleSource:"auto"}))}catch{}}catch(err){if(sendActivityGateError(res,err))return;if(sendGenerationClosedError(res,err))return;writeStderrLine(`qwen serve: POST ${base} failed to create the task's session: ${err instanceof Error?err.message:String(err)}`);res.status(500).json({error:"Failed to create the task's session",code:"scheduled_tasks_session_failed"});return}}const now=Date.now();const task=withTaskGate({id:taskId,cron,prompt,recurring,createdAt:now,lastFiredAt:now-now%6e4,enabled,sessionMode,...typeof modelServiceId==="string"?{modelServiceId}:{},...typeof groupId==="string"?{groupId}:{},...delivery!==void 0?{delivery}:{},...boundSessionId!==void 0?{sessionId:boundSessionId}:{},...nameResult.value!==void 0?{name:nameResult.value}:{}},gate);const rollbackSession=__name(async()=>{if(boundSessionId!==void 0&&sessionMintedHere){await teardownBoundSession(target,boundSessionId)}},"rollbackSession");let overCap=false;let rollbackBefore;let rollbackAfter;try{await runWithScheduledTaskTarget(target,()=>updateCronTasks(workspaceCwd,tasks=>{if(tasks.length>=MAX_SCHEDULED_TASKS){overCap=true;return tasks}rollbackBefore=tasks;rollbackAfter=[...tasks,task];return rollbackAfter},{assertCanCommit:target.assertGenerationOpen}))}catch(err){await rollbackSession();if(sendActivityGateError(res,err))return;if(sendGenerationClosedError(res,err))return;writeStderrLine(`qwen serve: POST ${base} failed: ${err instanceof Error?err.message:String(err)}`);res.status(500).json({error:"Failed to create scheduled task",code:"scheduled_tasks_write_failed"});return}if(rollbackBefore&&rollbackAfter){try{target.assertGenerationOpen?.()}catch(error){await rollbackCronMutation(target,rollbackBefore,rollbackAfter,`POST ${base}`);await rollbackSession();if(sendGenerationClosedError(res,error))return;throw error}}if(overCap){await rollbackSession();res.status(409).json({error:`Maximum number of scheduled tasks (${MAX_SCHEDULED_TASKS}) reached`,code:"max_tasks_reached"});return}if(task.delivery&&task.sessionId){channelDeliveryAuthorizations?.registerScheduledTask(workspaceCwd,{sessionId:task.sessionId,taskId:task.id,target:task.delivery.target,recurring:task.recurring,lastFiredAt:task.lastFiredAt??void 0})}res.status(201).json(toView(task))}));app.patch(`${base}/:id`,mutate(),withTarget(async(req,res,target)=>{const{workspaceCwd,bridge}=target;const id=typeof req.params["id"]==="string"?req.params["id"]:"";if(id.length===0){res.status(400).json({error:"Task id is required",code:"invalid_id"});return}const body=safeBody(req);const patch={};let clearName=false;let clearDelivery=false;let clearModelServiceId=false;let clearGroupId=false;let clearGate=false;let missingGroupId;const removedPatchField=findRemovedTaskField(body);if(removedPatchField){res.status(400).json(removedFieldError(removedPatchField));return}if("cron"in body){const cron=typeof body["cron"]==="string"?body["cron"].trim():"";if(cron.length===0||cron.length>MAX_CRON_LENGTH){res.status(400).json({error:"`cron` must be a non-empty string within the length limit",code:"invalid_cron"});return}const cronError=validateCron(cron);if(cronError){res.status(400).json({error:cronError,code:"invalid_cron"});return}patch.cron=cron}if("prompt"in body){const prompt=typeof body["prompt"]==="string"?body["prompt"].trim():"";if(prompt.length===0||prompt.length>MAX_PROMPT_LENGTH){res.status(400).json({error:"`prompt` must be a non-empty string within the length limit",code:"invalid_prompt"});return}patch.prompt=prompt}if("name"in body){const nameResult=parseNameField(body["name"]);if(nameResult.error){res.status(400).json({error:nameResult.error,code:"invalid_name"});return}if(nameResult.value===void 0){clearName=true}else{patch.name=nameResult.value}}if("recurring"in body){if(typeof body["recurring"]!=="boolean"){res.status(400).json({error:"`recurring` must be a boolean",code:"invalid_recurring"});return}patch.recurring=body["recurring"]}if("enabled"in body){if(typeof body["enabled"]!=="boolean"){res.status(400).json({error:"`enabled` must be a boolean",code:"invalid_enabled"});return}patch.enabled=body["enabled"]}if("sessionMode"in body){if(body["sessionMode"]!=="persistent"&&body["sessionMode"]!=="per_run"){res.status(400).json({error:'`sessionMode` must be "persistent" or "per_run"',code:"invalid_session_mode"});return}patch.sessionMode=body["sessionMode"]}if("modelServiceId"in body){const value=body["modelServiceId"];if(value===null||value===""){clearModelServiceId=true}else if(!isValidCronTaskRoutingId(value)){res.status(400).json({error:`\`modelServiceId\` must be null or a non-empty string of at most ${MAX_ROUTING_ID_LENGTH} characters without control characters`,code:"invalid_model_service_id"});return}else{patch.modelServiceId=value}}if("groupId"in body){const value=body["groupId"];if(value===null||value===""){clearGroupId=true}else if(!isValidCronTaskRoutingId(value)){res.status(400).json({error:`\`groupId\` must be null or a non-empty string of at most ${MAX_ROUTING_ID_LENGTH} characters without control characters`,code:"invalid_group_id"});return}else{const groups=await runWithScheduledTaskTarget(target,()=>createSessionOrganizationService(workspaceCwd).listGroups());if(!groups.groups.some(group=>group.id===value)){missingGroupId=value}patch.groupId=value}}if("delivery"in body){if(body["delivery"]===null){clearDelivery=true}else{try{patch.delivery=parseChannelDelivery(body["delivery"])}catch(err){if(!isChannelDeliveryError(err))throw err;res.status(400).json({error:err.message,code:err.code});return}}}if("gate"in body){if(body["gate"]===null||body["gate"]===""){clearGate=true}else{const gateError=gateCommandError(body["gate"]);if(gateError){res.status(400).json({error:`\`gate\` must be null or a shell command; it ${gateError}`,code:"invalid_gate"});return}patch.gate=body["gate"].trim()}}if(Object.keys(patch).length===0&&!clearName&&!clearDelivery&&!clearModelServiceId&&!clearGroupId&&!clearGate){res.status(400).json({error:"No updatable fields provided",code:"empty_patch"});return}let found=false;let updated;let blockedByArchive=false;let blockedLegacy=false;let blockedGateOneShot=false;let blockedSessionModeDelivery=false;let blockedSessionModeUnavailable=false;let blockedSessionModeUnbound=false;let blockedGroupNotFound=false;let rollbackBefore;let rollbackAfter;try{await runWithScheduledTaskTarget(target,()=>updateCronTasks(workspaceCwd,tasks=>{const idx=tasks.findIndex(t=>t.id===id);if(idx===-1)return tasks;found=true;const current=tasks[idx];if(missingGroupId!==void 0&¤t.groupId!==missingGroupId){blockedGroupNotFound=true;return tasks}const convertingToPerRun=patch.sessionMode==="per_run"&¤t.sessionMode!=="per_run";if(convertingToPerRun&&(!bridge||!bridge.sendPrompt)){blockedSessionModeUnavailable=true;return tasks}if(convertingToPerRun&&!current.sessionId){blockedSessionModeUnbound=true;return tasks}if(patch.enabled===true&&taskHasLegacyCondition(current)){blockedLegacy=true;return tasks}if((patch.gate!==void 0||clearGate)&&taskHasLegacyCondition(current)){blockedLegacy=true;return tasks}if(patch.enabled===true&¤t.disabledByArchive===true){blockedByArchive=true;return tasks}let next={...current,...patch};if(clearName)delete next.name;if(clearDelivery)delete next.delivery;if(clearModelServiceId)delete next.modelServiceId;if(clearGroupId)delete next.groupId;if(next.sessionMode!=="per_run"){delete next.modelServiceId;delete next.groupId}if(next.sessionMode==="per_run"&&next.delivery){blockedSessionModeDelivery=true;return tasks}if(clearGate||patch.gate!==void 0){next=withTaskGate(next,clearGate?void 0:patch.gate);if(clearGate||patch.gate!==current.gate){delete next.gateStatus}}if(next.gate!==void 0&&!next.recurring&&(patch.gate!==void 0&&patch.gate!==current.gate||patch.recurring===false&¤t.recurring!==false)){blockedGateOneShot=true;return tasks}const justReEnabled=current.enabled===false&&patch.enabled===true;const cronChanged=patch.cron!==void 0&&canonicalCron(patch.cron)!==canonicalCron(current.cron);const becameRecurring=patch.recurring===true&¤t.recurring!==true;const becameOneShot=patch.recurring===false&¤t.recurring!==false;const retryFailedOneShot=!next.recurring&&justReEnabled&&!cronChanged&&!becameOneShot&¤t.runs?.at(-1)?.sessionDispatchFailed===true;{const now=Date.now();const minute=now-now%6e4;if(next.recurring&&(justReEnabled||cronChanged||becameRecurring)){next.lastFiredAt=minute}else if(!next.recurring&&!retryFailedOneShot&&(justReEnabled||cronChanged||becameOneShot)){next.createdAt=now;next.lastFiredAt=minute}}updated=next;rollbackBefore=tasks;rollbackAfter=tasks.map((t,i)=>i===idx?next:t);return rollbackAfter},{assertCanCommit:target.assertGenerationOpen}))}catch(err){if(sendActivityGateError(res,err))return;if(sendGenerationClosedError(res,err))return;writeStderrLine(`qwen serve: PATCH ${base}/${id} failed: ${err instanceof Error?err.message:String(err)}`);res.status(500).json({error:"Failed to update scheduled task",code:"scheduled_tasks_write_failed"});return}if(rollbackBefore&&rollbackAfter){try{target.assertGenerationOpen?.()}catch(error){await rollbackCronMutation(target,rollbackBefore,rollbackAfter,`PATCH ${base}/${id}`);if(sendGenerationClosedError(res,error))return;throw error}}if(!found){res.status(404).json({error:"Task not found",code:"task_not_found"});return}if(missingGroupId!==void 0&&blockedGroupNotFound){res.status(400).json({error:`Group not found: ${missingGroupId}`,code:"group_not_found"});return}if(blockedLegacy){res.status(409).json({error:"This task uses the removed isolated run mode with a precondition and can no longer be enabled or run. Recreate it (and call the `create_sub_session` tool from the prompt if you need per-run isolation).",code:"task_legacy_unsupported"});return}if(blockedByArchive){res.status(409).json({error:"This task was disabled by archiving its session; unarchive the session to re-enable it.",code:"task_session_archived"});return}if(blockedSessionModeUnavailable){res.status(409).json({error:"Fresh-session dispatch is not available for this workspace",code:"session_mode_unavailable"});return}if(blockedSessionModeUnbound){res.status(409).json({error:"This task is not bound to a session yet, so it cannot run in a new session every run. Try again once it has run or been opened at least once.",code:"session_mode_requires_bound_session"});return}if(blockedSessionModeDelivery){res.status(409).json({error:"Per-run sessions do not support channel delivery",code:"session_mode_delivery_unsupported"});return}if(blockedGateOneShot){res.status(400).json({error:GATE_REQUIRES_RECURRING_MESSAGE,code:"gate_requires_recurring"});return}if(!updated){res.status(404).json({error:"Task not found",code:"task_not_found"});return}const effectiveLabelChanged=patch.name!==void 0||clearName||patch.prompt!==void 0&&updated.name===void 0;if(bridge&&updated.sessionId&&updated.sessionOwnedByTask!==false&&effectiveLabelChanged){try{bridge.updateSessionMetadata(updated.sessionId,{displayName:scheduledTaskSessionName(updated.name??updated.prompt),titleSource:"auto"})}catch{}}if(updated.delivery&&updated.sessionId){channelDeliveryAuthorizations?.registerScheduledTask(workspaceCwd,{sessionId:updated.sessionId,taskId:updated.id,target:updated.delivery.target,recurring:updated.recurring,lastFiredAt:updated.lastFiredAt??void 0})}if(clearDelivery&&updated.sessionId){channelDeliveryAuthorizations?.revokeScheduledTask(workspaceCwd,updated.sessionId,updated.id)}res.status(200).json(toView(updated))}));app.delete(`${base}/:id`,mutate(),withTarget(async(req,res,target)=>{const{workspaceCwd,bridge}=target;const id=typeof req.params["id"]==="string"?req.params["id"]:"";if(id.length===0){res.status(400).json({error:"Task id is required",code:"invalid_id"});return}let boundSessionId;let sessionOwnedByTask=true;let removed=false;let rollbackBefore;let rollbackAfter;try{await runWithScheduledTaskTarget(target,async()=>{try{await access(getCronFilePath(workspaceCwd))}catch(error){if(error.code==="ENOENT")return;throw error}await updateCronTasks(workspaceCwd,tasks=>{const idx=tasks.findIndex(t=>t.id===id);if(idx===-1)return tasks;const match=tasks[idx].sessionId;if(typeof match==="string"&&match.length>0){boundSessionId=match;sessionOwnedByTask=tasks[idx].sessionOwnedByTask!==false}removed=true;rollbackBefore=tasks;rollbackAfter=tasks.filter((_,i)=>i!==idx);return rollbackAfter},{assertCanCommit:target.assertGenerationOpen,deletionIds:[id]})})}catch(err){if(sendActivityGateError(res,err))return;if(sendGenerationClosedError(res,err))return;writeStderrLine(`qwen serve: DELETE ${base}/${id} failed: ${err instanceof Error?err.message:String(err)}`);res.status(500).json({error:"Failed to delete scheduled task",code:"scheduled_tasks_write_failed"});return}if(rollbackBefore&&rollbackAfter){try{target.assertGenerationOpen?.()}catch(error){await rollbackCronMutation(target,rollbackBefore,rollbackAfter,`DELETE ${base}/${id}`);if(sendGenerationClosedError(res,error))return;throw error}}if(!removed){res.status(404).json({error:"Task not found",code:"task_not_found"});return}if(boundSessionId&&sessionOwnedByTask&&bridge){try{await runWithScheduledTaskTarget(target,()=>bridge.closeSession(boundSessionId,void 0,{closeIfUnheld:true,reason:"scheduled_task_deleted"}))}catch(error){if(sendActivityGateError(res,error))return}}if(boundSessionId){channelDeliveryAuthorizations?.revokeScheduledTask(workspaceCwd,boundSessionId,id)}res.status(200).json({deleted:true,id})}));app.post(`${base}/:id/run`,mutate(),withTarget(async(req,res,target)=>{const{workspaceCwd}=target;const id=typeof req.params["id"]==="string"?req.params["id"]:"";if(id.length===0){res.status(400).json({error:"Task id is required",code:"invalid_id"});return}const now=Date.now();let found=false;let blockedDisabled=false;let blockedLegacy=false;let updated;let rollbackBefore;let rollbackAfter;let removalGenerations;try{await runWithScheduledTaskTarget(target,()=>updateCronTasks(workspaceCwd,tasks=>{const idx=tasks.findIndex(t=>t.id===id);if(idx===-1)return tasks;found=true;const current=tasks[idx];if(taskHasLegacyCondition(current)){blockedLegacy=true;return tasks}if(current.enabled===false){blockedDisabled=true;return tasks}const next={...current,lastFiredAt:now,runs:appendCronRun(current.runs,{at:now,kind:"manual",...current.sessionMode!=="per_run"&¤t.sessionId?{sessionId:current.sessionId}:{}})};updated=next;rollbackBefore=tasks;const nextTasks=!current.recurring?tasks.filter((_,i)=>i!==idx):tasks.map((t,i)=>i===idx?next:t);rollbackAfter=nextTasks;return nextTasks},{assertCanCommit:target.assertGenerationOpen,observeDeletionIds:__name(tasks=>{const task=tasks.find(task2=>task2.id===id);return task?.sessionId?[id,cronTaskSessionDeletionId(task.sessionId)]:[id]},"observeDeletionIds"),onDeletionGenerations:__name(generations=>{removalGenerations=generations},"onDeletionGenerations")}))}catch(err){if(sendActivityGateError(res,err))return;if(sendGenerationClosedError(res,err))return;writeStderrLine(`qwen serve: POST ${base}/${id}/run failed: ${err instanceof Error?err.message:String(err)}`);res.status(500).json({error:"Failed to record scheduled task run",code:"scheduled_tasks_write_failed"});return}if(rollbackBefore&&rollbackAfter){try{target.assertGenerationOpen?.()}catch(error){await rollbackCronMutation(target,rollbackBefore,rollbackAfter,`POST ${base}/${id}/run`);if(sendGenerationClosedError(res,error))return;throw error}}if(blockedLegacy){res.status(409).json({error:"This task uses the removed isolated run mode with a precondition and can no longer run. Recreate it (and call the `create_sub_session` tool from the prompt if you need per-run isolation).",code:"task_legacy_unsupported"});return}if(blockedDisabled){res.status(409).json({error:"Cannot run a disabled task; enable it first (unarchive its session if it was archived).",code:"task_disabled"});return}if(!found||!updated){res.status(404).json({error:"Task not found",code:"task_not_found"});return}if(updated.sessionMode==="per_run"){const persistOutcome=__name(async outcome=>{if(!updated.recurring)return;await runWithScheduledTaskTarget(target,()=>updateCronTasks(workspaceCwd,tasks=>tasks.map(task=>task.id===id?annotateCronRunSession(task,now,outcome):task),{assertCanCommit:target.assertGenerationOpen}))},"persistOutcome");let childSessionId;try{childSessionId=await dispatchTaskToFreshSession(target,updated)}catch(error){updated=annotateCronRunSession(updated,now,{dispatchFailed:true});if(updated.recurring){await persistOutcome({dispatchFailed:true}).catch(persistError=>{writeStderrLine(`qwen serve: POST ${base}/${id}/run could not record the failed dispatch: ${persistError instanceof Error?persistError.message:String(persistError)}`)})}else{await restoreConsumedOneShot(target,rollbackBefore,updated,removalGenerations,`POST ${base}/${id}/run fresh-session dispatch`)}writeStderrLine(`qwen serve: POST ${base}/${id}/run could not create a fresh session: ${error instanceof Error?error.message:String(error)}`);res.status(500).json({error:"Failed to create a fresh session for the scheduled task",code:"scheduled_task_session_dispatch_failed"});return}updated=annotateCronRunSession(updated,now,{sessionId:childSessionId});await persistOutcome({sessionId:childSessionId}).catch(error=>{writeStderrLine(`qwen serve: POST ${base}/${id}/run could not attribute fresh session ${childSessionId}: ${error instanceof Error?error.message:String(error)}`)})}if(!updated.recurring&&updated.sessionId){channelDeliveryAuthorizations?.revokeScheduledTask(workspaceCwd,updated.sessionId,updated.id)}const view=toView(updated);if(!updated.recurring)view.nextRunAt=null;res.status(200).json(view)}))}__name(registerScheduledTaskCrudRoutes,"registerScheduledTaskCrudRoutes");function registerScheduledTasksRoutes(app,deps){const{boundWorkspace,mutate,safeBody,bridge,channelDeliveryAuthorizations}=deps;registerScheduledTaskCrudRoutes(app,{prefix:"",resolveTarget:__name((_req,res)=>{const runtime=deps.getRuntime?.();if(deps.getRuntime&&!runtime){res.set("Retry-After","1");res.status(503).json({error:"Workspace runtime is not active",code:"workspace_runtime_unavailable"});return null}if(runtime&&!requireTrustedWorkspaceRuntime(runtime,res))return null;return{workspaceCwd:boundWorkspace,...runtime?{runtimeBaseDir:runtime.sessionRuntimeBaseDir,...deps.cleanupSession?{cleanupSession:__name(sessionId=>deps.cleanupSession(runtime,sessionId),"cleanupSession")}:{}}:{},bridge:bridge===void 0?void 0:runtime?.bridge??bridge,...runtime?.generationGuard?{assertGenerationOpen:__name(()=>runtime.generationGuard?.assertOpen(),"assertGenerationOpen")}:{},...deps.workspaceRegistry?{resolveLiveSessionOwner:__name(sessionId=>deps.workspaceRegistry.resolveLiveSessionOwner(sessionId),"resolveLiveSessionOwner")}:{}}},"resolveTarget"),mutate,safeBody,channelDeliveryAuthorizations})}__name(registerScheduledTasksRoutes,"registerScheduledTasksRoutes");function registerWorkspaceQualifiedScheduledTasksRoutes(app,deps){const{workspaceRegistry,mutate,safeBody,manageScheduledTaskSessions,channelDeliveryAuthorizations,cleanupSession}=deps;registerScheduledTaskCrudRoutes(app,{prefix:"/workspaces/:workspace",resolveTarget:__name((req,res)=>{const runtime=resolveWorkspaceRuntimeWithLiveCompatibilityFromParam(workspaceRegistry,req,res);if(!runtime)return null;if(!requireTrustedWorkspaceRuntime(runtime,res))return null;if(runtime.provenance==="live-conversation"&&!deps.conversationRuntimeActivity){sendConversationRuntimeUnavailable(res);return null}if(runtime.provenance==="live-conversation"&&req.method==="POST"&&req.params["id"]===void 0&&parseCallerSuppliedSessionId(safeBody(req)["sessionId"]).kind==="absent"){res.status(400).json({error:"Generic scheduled tasks cannot create sessions in the Conversations workspace.",code:"live_session_creation_reserved"});return null}return{workspaceCwd:runtime.workspaceCwd,runtimeBaseDir:runtime.sessionRuntimeBaseDir,...runtime.provenance==="live-conversation"&&deps.conversationRuntimeActivity?{activity:deps.conversationRuntimeActivity}:{},...cleanupSession?{cleanupSession:__name(sessionId=>cleanupSession(runtime,sessionId),"cleanupSession")}:{},bridge:manageScheduledTaskSessions?runtime.bridge:void 0,...runtime.generationGuard?{assertGenerationOpen:__name(()=>runtime.generationGuard?.assertOpen(),"assertGenerationOpen")}:{},resolveLiveSessionOwner:__name(sessionId=>workspaceRegistry.resolveLiveSessionOwner(sessionId),"resolveLiveSessionOwner")}},"resolveTarget"),mutate,safeBody,channelDeliveryAuthorizations})}__name(registerWorkspaceQualifiedScheduledTasksRoutes,"registerWorkspaceQualifiedScheduledTasksRoutes");var REMOVED_TASK_FIELDS=["runMode","condition"];function findRemovedTaskField(body){return REMOVED_TASK_FIELDS.find(field=>field in body)}__name(findRemovedTaskField,"findRemovedTaskField");function removedFieldError(field){return{error:`\`${field}\` is no longer supported: the isolated scheduled-task run mode was removed. Every task now runs in its bound session; call the \`create_sub_session\` tool from the task prompt for per-run isolation.`,code:"unsupported_field"}}__name(removedFieldError,"removedFieldError");function parseNameField(raw){if(raw===void 0||raw===null)return{value:void 0};if(typeof raw!=="string"){return{error:"`name` must be a string"}}const trimmed=raw.trim();if(trimmed.length===0)return{value:void 0};if(trimmed.length>MAX_NAME_LENGTH){return{error:`\`name\` exceeds ${MAX_NAME_LENGTH}-character limit`}}return{value:trimmed}}__name(parseNameField,"parseNameField");export{scheduledTaskSessionName,ExistingSessionScheduledTaskCreateError,createScheduledTaskWithExistingSession,registerScheduledTasksRoutes,registerWorkspaceQualifiedScheduledTasksRoutes};
|
|
3
|
+
import{buildScheduledTaskRunPrompt,parseChannelDelivery,scheduledTaskRunSessionName,scheduledTaskRunSourceId}from"./chunk-J52J35K4.js";import{createSessionOrganizationService}from"./chunk-G4ATLMDH.js";import{requireTrustedWorkspaceRuntime,resolveWorkspaceRuntimeWithLiveCompatibilityFromParam,sendConversationRuntimeUnavailable,sendGenerationClosedError}from"./chunk-MMGGGYSJ.js";import{parseCallerSuppliedSessionId}from"./chunk-LGFF5PJA.js";import{SCHEDULED_TASK_RUN_SOURCE_TYPE}from"./chunk-LY2DRNTZ.js";import{SessionNotFoundError}from"./chunk-CVMEBFLL.js";import{isChannelDeliveryError}from"./chunk-O6ZQAVRG.js";import{MAX_JOBS,SessionService,gateCommandError,nextDurableFireMs,nextFireTime,parseCron}from"./chunk-ZUWLTGSR.js";import{stripTerminalControlSequences}from"./chunk-R2EHHA2C.js";import{MAX_CRON_TASK_ROUTING_ID_LENGTH,annotateCronRunSession,appendCronRun,cronTaskSessionDeletionId,generateCronTaskId,getCronFilePath,isValidCronTaskRoutingId,readCronTasks,taskHasLegacyCondition,updateCronTasks,withTaskGate}from"./chunk-DXUYBMFK.js";import{writeStderrLine}from"./chunk-M4ECEHLX.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{isDeepStrictEqual}from"node:util";import{access}from"node:fs/promises";var MAX_SCHEDULED_TASKS=MAX_JOBS;var MAX_PROMPT_LENGTH=1e5;var MAX_NAME_LENGTH=200;var MAX_CRON_LENGTH=200;var MAX_ROUTING_ID_LENGTH=MAX_CRON_TASK_ROUTING_ID_LENGTH;var MAX_SESSION_NAME_LENGTH=60;function scheduledTaskSessionName(label){const cleaned=stripTerminalControlSequences(label).replace(/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g,"").trim().replace(/\s+/g," ");let short=cleaned;if(cleaned.length>MAX_SESSION_NAME_LENGTH){let cut=MAX_SESSION_NAME_LENGTH-1;const boundary=cleaned.charCodeAt(cut-1);if(boundary>=55296&&boundary<=56319)cut-=1;short=`${cleaned.slice(0,cut)}\u2026`}return short}__name(scheduledTaskSessionName,"scheduledTaskSessionName");var ExistingSessionScheduledTaskCreateError=class extends Error{constructor(status,code,message){super(message);this.status=status;this.code=code;this.name="ExistingSessionScheduledTaskCreateError"}static{__name(this,"ExistingSessionScheduledTaskCreateError")}};function assertReusableScheduledTaskSession(target,sessionId,allowActivePrompt,assertCallerPromptActive){const{bridge,workspaceCwd}=target;if(!bridge){throw new ExistingSessionScheduledTaskCreateError(409,"session_binding_unavailable","Session management is not available for this workspace")}assertCallerPromptActive?.();let owner;try{owner=target.resolveLiveSessionOwner?.(sessionId)}catch(error){writeStderrLine(`qwen serve: failed to resolve scheduled-task session owner '${sessionId}': ${error instanceof Error?error.message:String(error)}`);throw new ExistingSessionScheduledTaskCreateError(500,"scheduled_tasks_session_failed","Failed to look up the requested session")}if(owner?.kind==="unavailable"){throw new ExistingSessionScheduledTaskCreateError(503,"workspace_runtime_unavailable","The workspace runtime is unavailable")}if(owner?.kind==="ambiguous"){throw new ExistingSessionScheduledTaskCreateError(500,"ambiguous_session_owner",`Session owner is ambiguous for "${sessionId}"`)}if(owner?.kind==="found"&&owner.runtime.workspaceCwd!==workspaceCwd){throw new ExistingSessionScheduledTaskCreateError(400,"session_workspace_mismatch","The requested session belongs to a different workspace; use that workspace's scheduled-task endpoint")}let summary;try{summary=bridge.getSessionSummary(sessionId)}catch(error){if(error instanceof SessionNotFoundError){throw new ExistingSessionScheduledTaskCreateError(404,"session_not_found",`Session '${sessionId}' was not found`)}writeStderrLine(`qwen serve: failed to look up scheduled-task session '${sessionId}': ${error instanceof Error?error.message:String(error)}`);throw new ExistingSessionScheduledTaskCreateError(500,"scheduled_tasks_session_failed","Failed to look up the requested session")}if(summary.workspaceCwd!==workspaceCwd){throw new ExistingSessionScheduledTaskCreateError(400,"session_workspace_mismatch","The requested session belongs to a different workspace; use that workspace's scheduled-task endpoint")}if(!allowActivePrompt&&summary.hasActivePrompt||(summary.pendingInteractionCount??0)>0){throw new ExistingSessionScheduledTaskCreateError(409,"session_busy",allowActivePrompt?"The caller session has a pending interaction; resolve it before binding the session to a task":"The requested session is busy; wait for its active prompt or pending interaction to finish before binding it to a task")}if(summary.sourceType==="scheduled_task"){throw new ExistingSessionScheduledTaskCreateError(409,"session_already_bound","The requested session is already reserved for a scheduled task")}if(summary.parentSessionId!==void 0||summary.sourceId!==void 0||summary.sourceType!==void 0&&summary.sourceType!=="default"){throw new ExistingSessionScheduledTaskCreateError(409,"session_source_ineligible","The requested session source cannot own a scheduled task")}}__name(assertReusableScheduledTaskSession,"assertReusableScheduledTaskSession");async function createScheduledTaskWithExistingSession(target,input,options){if(input.cron.length===0||input.cron.length>MAX_CRON_LENGTH||validateCron(input.cron)!==null){throw new ExistingSessionScheduledTaskCreateError(400,"invalid_cron","The scheduled-task cron expression is invalid")}const prompt=input.prompt.trim();if(prompt.length===0||prompt.length>MAX_PROMPT_LENGTH){throw new ExistingSessionScheduledTaskCreateError(400,"invalid_prompt","The scheduled-task prompt is invalid")}const gate=input.gate?.trim();if(gate!==void 0){const gateError=gateCommandError(gate);if(gateError){throw new ExistingSessionScheduledTaskCreateError(400,"invalid_gate",`The scheduled-task gate ${gateError}`)}if(!input.recurring){throw new ExistingSessionScheduledTaskCreateError(400,"gate_requires_recurring",GATE_REQUIRES_RECURRING_MESSAGE)}}const allowActivePrompt=options.source==="cron-tool";const assertCallerPromptActive=options.source==="cron-tool"?options.assertCallerPromptActive:void 0;assertReusableScheduledTaskSession(target,input.sessionId,allowActivePrompt,assertCallerPromptActive);target.assertGenerationOpen?.();if(options.source==="rest"){const ensurePersisted=target.bridge?.ensureDefaultSessionPersisted;if(!ensurePersisted){throw new ExistingSessionScheduledTaskCreateError(409,"session_binding_unavailable","Session persistence is not available for this workspace")}try{await ensurePersisted.call(target.bridge,input.sessionId)}catch(error){target.assertGenerationOpen?.();if(error instanceof SessionNotFoundError){throw new ExistingSessionScheduledTaskCreateError(404,"session_not_found",`Session '${input.sessionId}' was not found`)}writeStderrLine(`qwen serve: failed to persist scheduled-task session '${input.sessionId}': ${error instanceof Error?error.message:String(error)}`);throw new ExistingSessionScheduledTaskCreateError(500,"session_persistence_failed","Failed to persist the requested session")}target.assertGenerationOpen?.()}const now=Date.now();const task=withTaskGate({id:generateCronTaskId(),cron:input.cron,prompt,recurring:input.recurring,createdAt:now,lastFiredAt:now-now%6e4,enabled:input.enabled!==false,sessionId:input.sessionId,sessionOwnedByTask:false,sessionMode:input.sessionMode==="per_run"?"per_run":"persistent",...input.sessionMode==="per_run"&&input.modelServiceId!==void 0?{modelServiceId:input.modelServiceId}:{},...input.sessionMode==="per_run"&&input.groupId!==void 0?{groupId:input.groupId}:{},...input.delivery!==void 0?{delivery:input.delivery}:{},...input.name!==void 0?{name:input.name}:{}},gate);let before;let after;await runWithScheduledTaskTarget(target,()=>updateCronTasks(target.workspaceCwd,tasks=>{assertReusableScheduledTaskSession(target,input.sessionId,allowActivePrompt,assertCallerPromptActive);if(tasks.some(candidate=>candidate.sessionId===input.sessionId)){throw new ExistingSessionScheduledTaskCreateError(409,"session_already_bound","The requested session is already bound to another scheduled task")}if(tasks.length>=MAX_SCHEDULED_TASKS){throw new ExistingSessionScheduledTaskCreateError(409,"max_tasks_reached",`Maximum number of scheduled tasks (${MAX_SCHEDULED_TASKS}) reached`)}before=tasks;after=[...tasks,task];return after},{assertCanCommit:target.assertGenerationOpen}));try{target.assertGenerationOpen?.()}catch(error){await rollbackCronMutation(target,before,after,"scheduled-task create");throw error}return task}__name(createScheduledTaskWithExistingSession,"createScheduledTaskWithExistingSession");function requireOpenGeneration(target,res){try{target.assertGenerationOpen?.();return true}catch(error){if(sendGenerationClosedError(res,error))return false;throw error}}__name(requireOpenGeneration,"requireOpenGeneration");async function rollbackCronMutation(target,before,after,route){if(!before||!after)return;await runWithScheduledTaskTarget(target,()=>updateCronTasks(target.workspaceCwd,tasks=>isDeepStrictEqual(tasks,after)?before:tasks)).catch(error=>{writeStderrLine(`qwen serve: ${route} failed to roll back a stale task mutation: ${error instanceof Error?error.message:String(error)}`)})}__name(rollbackCronMutation,"rollbackCronMutation");async function restoreConsumedOneShot(target,before,failedTask,removalGenerations,route){const id=failedTask.id;const index=before?.findIndex(t=>t.id===id)??-1;const original=index===-1?void 0:before[index];if(!original||!removalGenerations)return;let restoreGenerations;await runWithScheduledTaskTarget(target,()=>updateCronTasks(target.workspaceCwd,tasks=>{if([...removalGenerations].some(([key,generation])=>restoreGenerations?.get(key)!==generation))return tasks;if(tasks.some(t=>t.id===id))return tasks;const restored=[...tasks];restored.splice(Math.min(index,restored.length),0,{...failedTask,enabled:false});return restored},{observeDeletionIds:[...removalGenerations.keys()],onDeletionGenerations:__name(generations=>{restoreGenerations=generations},"onDeletionGenerations")})).catch(error=>{writeStderrLine(`qwen serve: ${route} failed to restore the consumed one-shot task: ${error instanceof Error?error.message:String(error)}`)})}__name(restoreConsumedOneShot,"restoreConsumedOneShot");async function teardownBoundSession(target,sessionId){if(target.cleanupSession){await target.cleanupSession(sessionId).catch(()=>{})}else if(target.bridge){await target.bridge.closeSession(sessionId).catch(()=>{});const removed=await new SessionService(target.workspaceCwd,{runtimeBaseDir:target.runtimeBaseDir}).removeSession(sessionId).catch(()=>false);if(removed)target.bridge.markSessionCatalogChanged?.()}}__name(teardownBoundSession,"teardownBoundSession");async function dispatchTaskToFreshSession(target,task){const{bridge}=target;const sendPrompt=bridge?.sendPrompt?.bind(bridge);if(!bridge||!sendPrompt||!task.sessionId){throw new Error("Fresh-session dispatch is unavailable for this task")}const triggeredAt=task.lastFiredAt??Date.now();const child=await runWithScheduledTaskTarget(target,()=>bridge.spawnOrAttach({workspaceCwd:target.workspaceCwd,...task.modelServiceId?{modelServiceId:task.modelServiceId}:{},sessionScope:"thread",parentSessionId:task.sessionId,sourceType:SCHEDULED_TASK_RUN_SOURCE_TYPE,sourceId:scheduledTaskRunSourceId(task.id)}));try{if(task.modelServiceId&&child.modelApplied===false){throw new Error(`Scheduled task model selection failed: ${task.modelServiceId}`)}try{bridge.updateSessionMetadata(child.sessionId,{displayName:scheduledTaskRunSessionName(task.name??task.prompt,triggeredAt),titleSource:"auto"})}catch{}let markPromptAdmitted;const promptAdmitted=new Promise(resolve=>{markPromptAdmitted=resolve});const turn=sendPrompt(child.sessionId,{sessionId:child.sessionId,prompt:[{type:"text",text:buildScheduledTaskRunPrompt({id:task.id,name:task.name,cron:task.cron,prompt:task.prompt,triggeredAt,trigger:"manual",...task.gate?{gate:task.gate}:{}})}]},void 0,{onPromptAdmitted:markPromptAdmitted});void turn.catch(error=>{writeStderrLine(`qwen serve: scheduled-task session ${child.sessionId} prompt failed: ${error instanceof Error?error.message:String(error)}`)});await Promise.race([promptAdmitted,turn.then(()=>void 0,error=>Promise.reject(error))]);if(task.groupId){try{await runWithScheduledTaskTarget(target,()=>createSessionOrganizationService(target.workspaceCwd).updateSessionOrganization(child.sessionId,{groupId:task.groupId,color:null}));bridge.markSessionCatalogChanged?.()}catch(error){writeStderrLine(`qwen serve: scheduled-task session ${child.sessionId} could not be assigned to group ${task.groupId}: ${error instanceof Error?error.message:String(error)}`)}}}catch(error){await teardownBoundSession(target,child.sessionId);throw error}return child.sessionId}__name(dispatchTaskToFreshSession,"dispatchTaskToFreshSession");async function runWithScheduledTaskTarget(target,fn){const result=target.runtimeBaseDir===void 0?fn():Storage.runWithResolvedRuntimeBaseDir(target.runtimeBaseDir,fn);return await result}__name(runWithScheduledTaskTarget,"runWithScheduledTaskTarget");function sendActivityGateError(res,error){if(!error||typeof error!=="object"||error.code!=="daemon_draining"){return false}res.status(503).json({error:"The daemon is draining and no longer accepts work.",code:"daemon_draining"});return true}__name(sendActivityGateError,"sendActivityGateError");var GATE_REQUIRES_RECURRING_MESSAGE="A gate needs a recurring task: a one-shot whose gate prints nothing would be consumed with nothing delivered";function computeNextRunAt(task){if(task.enabled===false)return null;return nextDurableFireMs(task)}__name(computeNextRunAt,"computeNextRunAt");function toView(task){return{id:task.id,name:typeof task.name==="string"&&task.name.length>0?task.name:null,cron:task.cron,prompt:task.prompt,recurring:task.recurring,enabled:task.enabled!==false&&!taskHasLegacyCondition(task),createdAt:task.createdAt,lastFiredAt:task.lastFiredAt,nextRunAt:taskHasLegacyCondition(task)?null:computeNextRunAt(task),sessionId:typeof task.sessionId==="string"&&task.sessionId.length>0?task.sessionId:null,sessionMode:task.sessionMode==="per_run"?"per_run":"persistent",modelServiceId:task.modelServiceId??null,groupId:task.groupId??null,runs:Array.isArray(task.runs)?task.runs:[],...task.delivery!==void 0?{delivery:task.delivery}:{},gate:typeof task.gate==="string"&&task.gate.length>0?task.gate:null,gateStatus:task.gateStatus??null}}__name(toView,"toView");function validateCron(cron){try{parseCron(cron);nextFireTime(cron,new Date);return null}catch(err){return err instanceof Error?err.message:String(err)}}__name(validateCron,"validateCron");function canonicalCron(cron){try{const f=parseCron(cron);const s=__name(set=>[...set].sort((a,b)=>a-b).join(","),"s");return[s(f.minute),s(f.hour),s(f.dayOfMonth),s(f.month),s(f.dayOfWeek),f.domIsWild?"W":"",f.dowIsWild?"W":""].join("|")}catch{return null}}__name(canonicalCron,"canonicalCron");function registerScheduledTaskCrudRoutes(app,deps){const{prefix,resolveTarget,mutate,safeBody,channelDeliveryAuthorizations}=deps;const base=`${prefix}/scheduled-tasks`;const withTarget=__name(handler=>async(req,res)=>{const target=resolveTarget(req,res);if(!target)return;const operation=__name(async()=>{if(!requireOpenGeneration(target,res))return;await handler(req,res,target)},"operation");try{if(target.activity){await target.activity.run(operation)}else{await operation()}}catch(error){if(sendActivityGateError(res,error))return;throw error}},"withTarget");app.get(base,withTarget(async(_req,res,target)=>{try{const tasks=await runWithScheduledTaskTarget(target,()=>readCronTasks(target.workspaceCwd));if(!requireOpenGeneration(target,res))return;res.status(200).json({v:1,tasks:tasks.map(toView)})}catch(err){if(sendActivityGateError(res,err))return;writeStderrLine(`qwen serve: GET ${base} failed: ${err instanceof Error?err.message:String(err)}`);res.status(500).json({error:"Failed to read scheduled tasks (the tasks file may be corrupt)",code:"scheduled_tasks_read_failed"})}}));app.post(base,mutate(),withTarget(async(req,res,target)=>{const{workspaceCwd,bridge}=target;const body=safeBody(req);const cron=typeof body["cron"]==="string"?body["cron"].trim():"";if(cron.length===0){res.status(400).json({error:"`cron` is required and must be a non-empty string",code:"invalid_cron"});return}if(cron.length>MAX_CRON_LENGTH){res.status(400).json({error:`\`cron\` exceeds ${MAX_CRON_LENGTH}-character limit`,code:"invalid_cron"});return}const cronError=validateCron(cron);if(cronError){res.status(400).json({error:cronError,code:"invalid_cron"});return}const prompt=typeof body["prompt"]==="string"?body["prompt"].trim():"";if(prompt.length===0){res.status(400).json({error:"`prompt` is required and must be a non-empty string",code:"invalid_prompt"});return}if(prompt.length>MAX_PROMPT_LENGTH){res.status(400).json({error:`\`prompt\` exceeds ${MAX_PROMPT_LENGTH}-character limit`,code:"invalid_prompt"});return}const nameResult=parseNameField(body["name"]);if(nameResult.error){res.status(400).json({error:nameResult.error,code:"invalid_name"});return}if(body["recurring"]!==void 0&&typeof body["recurring"]!=="boolean"){res.status(400).json({error:"`recurring` must be a boolean",code:"invalid_recurring"});return}if(body["enabled"]!==void 0&&typeof body["enabled"]!=="boolean"){res.status(400).json({error:"`enabled` must be a boolean",code:"invalid_enabled"});return}const sessionMode=body["sessionMode"]===void 0?"persistent":body["sessionMode"];if(sessionMode!=="persistent"&&sessionMode!=="per_run"){res.status(400).json({error:'`sessionMode` must be "persistent" or "per_run"',code:"invalid_session_mode"});return}const modelServiceId=body["modelServiceId"];if(modelServiceId!==void 0&&!isValidCronTaskRoutingId(modelServiceId)){res.status(400).json({error:`\`modelServiceId\` must be a non-empty string of at most ${MAX_ROUTING_ID_LENGTH} characters without control characters`,code:"invalid_model_service_id"});return}const groupId=body["groupId"];if(groupId!==void 0&&!isValidCronTaskRoutingId(groupId)){res.status(400).json({error:`\`groupId\` must be a non-empty string of at most ${MAX_ROUTING_ID_LENGTH} characters without control characters`,code:"invalid_group_id"});return}if(sessionMode!=="per_run"&&(modelServiceId!==void 0||groupId!==void 0)){res.status(400).json({error:'`modelServiceId` and `groupId` are only supported when `sessionMode` is "per_run"',code:"session_routing_requires_per_run"});return}if(typeof groupId==="string"){const groups=await runWithScheduledTaskTarget(target,()=>createSessionOrganizationService(workspaceCwd).listGroups());if(!groups.groups.some(group=>group.id===groupId)){res.status(400).json({error:`Group not found: ${groupId}`,code:"group_not_found"});return}}const parsedSessionId=parseCallerSuppliedSessionId(body["sessionId"]);if(parsedSessionId.kind==="invalid"){res.status(400).json({error:'`sessionId` must be an RFC UUID v1-v5 (e.g. "550e8400-e29b-41d4-a716-446655440000")',code:"invalid_session_id"});return}const providedSessionId=parsedSessionId.kind==="valid"?parsedSessionId.sessionId:void 0;let delivery;if(body["delivery"]!==void 0){try{delivery=parseChannelDelivery(body["delivery"])}catch(err){if(!isChannelDeliveryError(err))throw err;res.status(400).json({error:err.message,code:err.code});return}}if(sessionMode==="per_run"&&delivery!==void 0){res.status(400).json({error:"Per-run sessions do not support channel delivery",code:"session_mode_delivery_unsupported"});return}const removedField=findRemovedTaskField(body);if(removedField){res.status(400).json(removedFieldError(removedField));return}const recurring=body["recurring"]!==false;const enabled=body["enabled"]!==false;let gate;if(body["gate"]!==void 0&&body["gate"]!==null){const gateError=gateCommandError(body["gate"]);if(gateError){res.status(400).json({error:`\`gate\` ${gateError}`,code:"invalid_gate"});return}gate=body["gate"].trim();if(!recurring){res.status(400).json({error:GATE_REQUIRES_RECURRING_MESSAGE,code:"gate_requires_recurring"});return}}const taskId=generateCronTaskId();if(sessionMode==="per_run"&&(!bridge||!bridge.sendPrompt)){res.status(409).json({error:"Fresh-session dispatch is not available for this workspace",code:"session_mode_unavailable"});return}if(providedSessionId!==void 0){try{const task2=await createScheduledTaskWithExistingSession(target,{sessionId:providedSessionId,cron,prompt,recurring,enabled,sessionMode,...typeof modelServiceId==="string"?{modelServiceId}:{},...typeof groupId==="string"?{groupId}:{},...delivery!==void 0?{delivery}:{},...nameResult.value!==void 0?{name:nameResult.value}:{},...gate!==void 0?{gate}:{}},{source:"rest"});if(task2.delivery&&task2.sessionId){channelDeliveryAuthorizations?.registerScheduledTask(workspaceCwd,{sessionId:task2.sessionId,taskId:task2.id,target:task2.delivery.target,recurring:task2.recurring,lastFiredAt:task2.lastFiredAt??void 0})}res.status(201).json(toView(task2))}catch(error){if(error instanceof ExistingSessionScheduledTaskCreateError){if(error.code==="workspace_runtime_unavailable"){res.set("Retry-After","1")}res.status(error.status).json({error:error.message,code:error.code});return}if(sendActivityGateError(res,error))return;if(sendGenerationClosedError(res,error))return;writeStderrLine(`qwen serve: POST ${base} failed to create a task for session '${providedSessionId}': ${error instanceof Error?error.message:String(error)}`);res.status(500).json({error:"Failed to create scheduled task",code:"scheduled_tasks_write_failed"})}return}let boundSessionId;let sessionMintedHere=false;if(bridge){try{const tasks=await runWithScheduledTaskTarget(target,()=>readCronTasks(workspaceCwd));if(tasks.length>=MAX_SCHEDULED_TASKS){res.status(409).json({error:`Maximum number of scheduled tasks (${MAX_SCHEDULED_TASKS}) reached`,code:"max_tasks_reached"});return}}catch{}if(!requireOpenGeneration(target,res))return;try{const session=await runWithScheduledTaskTarget(target,()=>bridge.spawnOrAttach({workspaceCwd,sessionScope:"thread",sourceType:"scheduled_task",sourceId:taskId}));boundSessionId=session.sessionId;sessionMintedHere=true;if(!requireOpenGeneration(target,res)){await teardownBoundSession(target,boundSessionId);return}try{await runWithScheduledTaskTarget(target,async()=>bridge.updateSessionMetadata(boundSessionId,{displayName:scheduledTaskSessionName(nameResult.value??prompt),titleSource:"auto"}))}catch{}}catch(err){if(sendActivityGateError(res,err))return;if(sendGenerationClosedError(res,err))return;writeStderrLine(`qwen serve: POST ${base} failed to create the task's session: ${err instanceof Error?err.message:String(err)}`);res.status(500).json({error:"Failed to create the task's session",code:"scheduled_tasks_session_failed"});return}}const now=Date.now();const task=withTaskGate({id:taskId,cron,prompt,recurring,createdAt:now,lastFiredAt:now-now%6e4,enabled,sessionMode,...typeof modelServiceId==="string"?{modelServiceId}:{},...typeof groupId==="string"?{groupId}:{},...delivery!==void 0?{delivery}:{},...boundSessionId!==void 0?{sessionId:boundSessionId}:{},...nameResult.value!==void 0?{name:nameResult.value}:{}},gate);const rollbackSession=__name(async()=>{if(boundSessionId!==void 0&&sessionMintedHere){await teardownBoundSession(target,boundSessionId)}},"rollbackSession");let overCap=false;let rollbackBefore;let rollbackAfter;try{await runWithScheduledTaskTarget(target,()=>updateCronTasks(workspaceCwd,tasks=>{if(tasks.length>=MAX_SCHEDULED_TASKS){overCap=true;return tasks}rollbackBefore=tasks;rollbackAfter=[...tasks,task];return rollbackAfter},{assertCanCommit:target.assertGenerationOpen}))}catch(err){await rollbackSession();if(sendActivityGateError(res,err))return;if(sendGenerationClosedError(res,err))return;writeStderrLine(`qwen serve: POST ${base} failed: ${err instanceof Error?err.message:String(err)}`);res.status(500).json({error:"Failed to create scheduled task",code:"scheduled_tasks_write_failed"});return}if(rollbackBefore&&rollbackAfter){try{target.assertGenerationOpen?.()}catch(error){await rollbackCronMutation(target,rollbackBefore,rollbackAfter,`POST ${base}`);await rollbackSession();if(sendGenerationClosedError(res,error))return;throw error}}if(overCap){await rollbackSession();res.status(409).json({error:`Maximum number of scheduled tasks (${MAX_SCHEDULED_TASKS}) reached`,code:"max_tasks_reached"});return}if(task.delivery&&task.sessionId){channelDeliveryAuthorizations?.registerScheduledTask(workspaceCwd,{sessionId:task.sessionId,taskId:task.id,target:task.delivery.target,recurring:task.recurring,lastFiredAt:task.lastFiredAt??void 0})}res.status(201).json(toView(task))}));app.patch(`${base}/:id`,mutate(),withTarget(async(req,res,target)=>{const{workspaceCwd,bridge}=target;const id=typeof req.params["id"]==="string"?req.params["id"]:"";if(id.length===0){res.status(400).json({error:"Task id is required",code:"invalid_id"});return}const body=safeBody(req);const patch={};let clearName=false;let clearDelivery=false;let clearModelServiceId=false;let clearGroupId=false;let clearGate=false;let missingGroupId;const removedPatchField=findRemovedTaskField(body);if(removedPatchField){res.status(400).json(removedFieldError(removedPatchField));return}if("cron"in body){const cron=typeof body["cron"]==="string"?body["cron"].trim():"";if(cron.length===0||cron.length>MAX_CRON_LENGTH){res.status(400).json({error:"`cron` must be a non-empty string within the length limit",code:"invalid_cron"});return}const cronError=validateCron(cron);if(cronError){res.status(400).json({error:cronError,code:"invalid_cron"});return}patch.cron=cron}if("prompt"in body){const prompt=typeof body["prompt"]==="string"?body["prompt"].trim():"";if(prompt.length===0||prompt.length>MAX_PROMPT_LENGTH){res.status(400).json({error:"`prompt` must be a non-empty string within the length limit",code:"invalid_prompt"});return}patch.prompt=prompt}if("name"in body){const nameResult=parseNameField(body["name"]);if(nameResult.error){res.status(400).json({error:nameResult.error,code:"invalid_name"});return}if(nameResult.value===void 0){clearName=true}else{patch.name=nameResult.value}}if("recurring"in body){if(typeof body["recurring"]!=="boolean"){res.status(400).json({error:"`recurring` must be a boolean",code:"invalid_recurring"});return}patch.recurring=body["recurring"]}if("enabled"in body){if(typeof body["enabled"]!=="boolean"){res.status(400).json({error:"`enabled` must be a boolean",code:"invalid_enabled"});return}patch.enabled=body["enabled"]}if("sessionMode"in body){if(body["sessionMode"]!=="persistent"&&body["sessionMode"]!=="per_run"){res.status(400).json({error:'`sessionMode` must be "persistent" or "per_run"',code:"invalid_session_mode"});return}patch.sessionMode=body["sessionMode"]}if("modelServiceId"in body){const value=body["modelServiceId"];if(value===null||value===""){clearModelServiceId=true}else if(!isValidCronTaskRoutingId(value)){res.status(400).json({error:`\`modelServiceId\` must be null or a non-empty string of at most ${MAX_ROUTING_ID_LENGTH} characters without control characters`,code:"invalid_model_service_id"});return}else{patch.modelServiceId=value}}if("groupId"in body){const value=body["groupId"];if(value===null||value===""){clearGroupId=true}else if(!isValidCronTaskRoutingId(value)){res.status(400).json({error:`\`groupId\` must be null or a non-empty string of at most ${MAX_ROUTING_ID_LENGTH} characters without control characters`,code:"invalid_group_id"});return}else{const groups=await runWithScheduledTaskTarget(target,()=>createSessionOrganizationService(workspaceCwd).listGroups());if(!groups.groups.some(group=>group.id===value)){missingGroupId=value}patch.groupId=value}}if("delivery"in body){if(body["delivery"]===null){clearDelivery=true}else{try{patch.delivery=parseChannelDelivery(body["delivery"])}catch(err){if(!isChannelDeliveryError(err))throw err;res.status(400).json({error:err.message,code:err.code});return}}}if("gate"in body){if(body["gate"]===null||body["gate"]===""){clearGate=true}else{const gateError=gateCommandError(body["gate"]);if(gateError){res.status(400).json({error:`\`gate\` must be null or a shell command; it ${gateError}`,code:"invalid_gate"});return}patch.gate=body["gate"].trim()}}if(Object.keys(patch).length===0&&!clearName&&!clearDelivery&&!clearModelServiceId&&!clearGroupId&&!clearGate){res.status(400).json({error:"No updatable fields provided",code:"empty_patch"});return}let found=false;let updated;let blockedByArchive=false;let blockedLegacy=false;let blockedGateOneShot=false;let blockedSessionModeDelivery=false;let blockedSessionModeUnavailable=false;let blockedSessionModeUnbound=false;let blockedGroupNotFound=false;let rollbackBefore;let rollbackAfter;try{await runWithScheduledTaskTarget(target,()=>updateCronTasks(workspaceCwd,tasks=>{const idx=tasks.findIndex(t=>t.id===id);if(idx===-1)return tasks;found=true;const current=tasks[idx];if(missingGroupId!==void 0&¤t.groupId!==missingGroupId){blockedGroupNotFound=true;return tasks}const convertingToPerRun=patch.sessionMode==="per_run"&¤t.sessionMode!=="per_run";if(convertingToPerRun&&(!bridge||!bridge.sendPrompt)){blockedSessionModeUnavailable=true;return tasks}if(convertingToPerRun&&!current.sessionId){blockedSessionModeUnbound=true;return tasks}if(patch.enabled===true&&taskHasLegacyCondition(current)){blockedLegacy=true;return tasks}if((patch.gate!==void 0||clearGate)&&taskHasLegacyCondition(current)){blockedLegacy=true;return tasks}if(patch.enabled===true&¤t.disabledByArchive===true){blockedByArchive=true;return tasks}let next={...current,...patch};if(clearName)delete next.name;if(clearDelivery)delete next.delivery;if(clearModelServiceId)delete next.modelServiceId;if(clearGroupId)delete next.groupId;if(next.sessionMode!=="per_run"){delete next.modelServiceId;delete next.groupId}if(next.sessionMode==="per_run"&&next.delivery){blockedSessionModeDelivery=true;return tasks}if(clearGate||patch.gate!==void 0){next=withTaskGate(next,clearGate?void 0:patch.gate);if(clearGate||patch.gate!==current.gate){delete next.gateStatus}}if(next.gate!==void 0&&!next.recurring&&(patch.gate!==void 0&&patch.gate!==current.gate||patch.recurring===false&¤t.recurring!==false)){blockedGateOneShot=true;return tasks}const justReEnabled=current.enabled===false&&patch.enabled===true;const cronChanged=patch.cron!==void 0&&canonicalCron(patch.cron)!==canonicalCron(current.cron);const becameRecurring=patch.recurring===true&¤t.recurring!==true;const becameOneShot=patch.recurring===false&¤t.recurring!==false;const retryFailedOneShot=!next.recurring&&justReEnabled&&!cronChanged&&!becameOneShot&¤t.runs?.at(-1)?.sessionDispatchFailed===true;{const now=Date.now();const minute=now-now%6e4;if(next.recurring&&(justReEnabled||cronChanged||becameRecurring)){next.lastFiredAt=minute}else if(!next.recurring&&!retryFailedOneShot&&(justReEnabled||cronChanged||becameOneShot)){next.createdAt=now;next.lastFiredAt=minute}}updated=next;rollbackBefore=tasks;rollbackAfter=tasks.map((t,i)=>i===idx?next:t);return rollbackAfter},{assertCanCommit:target.assertGenerationOpen}))}catch(err){if(sendActivityGateError(res,err))return;if(sendGenerationClosedError(res,err))return;writeStderrLine(`qwen serve: PATCH ${base}/${id} failed: ${err instanceof Error?err.message:String(err)}`);res.status(500).json({error:"Failed to update scheduled task",code:"scheduled_tasks_write_failed"});return}if(rollbackBefore&&rollbackAfter){try{target.assertGenerationOpen?.()}catch(error){await rollbackCronMutation(target,rollbackBefore,rollbackAfter,`PATCH ${base}/${id}`);if(sendGenerationClosedError(res,error))return;throw error}}if(!found){res.status(404).json({error:"Task not found",code:"task_not_found"});return}if(missingGroupId!==void 0&&blockedGroupNotFound){res.status(400).json({error:`Group not found: ${missingGroupId}`,code:"group_not_found"});return}if(blockedLegacy){res.status(409).json({error:"This task uses the removed isolated run mode with a precondition and can no longer be enabled or run. Recreate it (and call the `create_sub_session` tool from the prompt if you need per-run isolation).",code:"task_legacy_unsupported"});return}if(blockedByArchive){res.status(409).json({error:"This task was disabled by archiving its session; unarchive the session to re-enable it.",code:"task_session_archived"});return}if(blockedSessionModeUnavailable){res.status(409).json({error:"Fresh-session dispatch is not available for this workspace",code:"session_mode_unavailable"});return}if(blockedSessionModeUnbound){res.status(409).json({error:"This task is not bound to a session yet, so it cannot run in a new session every run. Try again once it has run or been opened at least once.",code:"session_mode_requires_bound_session"});return}if(blockedSessionModeDelivery){res.status(409).json({error:"Per-run sessions do not support channel delivery",code:"session_mode_delivery_unsupported"});return}if(blockedGateOneShot){res.status(400).json({error:GATE_REQUIRES_RECURRING_MESSAGE,code:"gate_requires_recurring"});return}if(!updated){res.status(404).json({error:"Task not found",code:"task_not_found"});return}const effectiveLabelChanged=patch.name!==void 0||clearName||patch.prompt!==void 0&&updated.name===void 0;if(bridge&&updated.sessionId&&updated.sessionOwnedByTask!==false&&effectiveLabelChanged){try{bridge.updateSessionMetadata(updated.sessionId,{displayName:scheduledTaskSessionName(updated.name??updated.prompt),titleSource:"auto"})}catch{}}if(updated.delivery&&updated.sessionId){channelDeliveryAuthorizations?.registerScheduledTask(workspaceCwd,{sessionId:updated.sessionId,taskId:updated.id,target:updated.delivery.target,recurring:updated.recurring,lastFiredAt:updated.lastFiredAt??void 0})}if(clearDelivery&&updated.sessionId){channelDeliveryAuthorizations?.revokeScheduledTask(workspaceCwd,updated.sessionId,updated.id)}res.status(200).json(toView(updated))}));app.delete(`${base}/:id`,mutate(),withTarget(async(req,res,target)=>{const{workspaceCwd,bridge}=target;const id=typeof req.params["id"]==="string"?req.params["id"]:"";if(id.length===0){res.status(400).json({error:"Task id is required",code:"invalid_id"});return}let boundSessionId;let sessionOwnedByTask=true;let removed=false;let rollbackBefore;let rollbackAfter;try{await runWithScheduledTaskTarget(target,async()=>{try{await access(getCronFilePath(workspaceCwd))}catch(error){if(error.code==="ENOENT")return;throw error}await updateCronTasks(workspaceCwd,tasks=>{const idx=tasks.findIndex(t=>t.id===id);if(idx===-1)return tasks;const match=tasks[idx].sessionId;if(typeof match==="string"&&match.length>0){boundSessionId=match;sessionOwnedByTask=tasks[idx].sessionOwnedByTask!==false}removed=true;rollbackBefore=tasks;rollbackAfter=tasks.filter((_,i)=>i!==idx);return rollbackAfter},{assertCanCommit:target.assertGenerationOpen,deletionIds:[id]})})}catch(err){if(sendActivityGateError(res,err))return;if(sendGenerationClosedError(res,err))return;writeStderrLine(`qwen serve: DELETE ${base}/${id} failed: ${err instanceof Error?err.message:String(err)}`);res.status(500).json({error:"Failed to delete scheduled task",code:"scheduled_tasks_write_failed"});return}if(rollbackBefore&&rollbackAfter){try{target.assertGenerationOpen?.()}catch(error){await rollbackCronMutation(target,rollbackBefore,rollbackAfter,`DELETE ${base}/${id}`);if(sendGenerationClosedError(res,error))return;throw error}}if(!removed){res.status(404).json({error:"Task not found",code:"task_not_found"});return}if(boundSessionId&&sessionOwnedByTask&&bridge){try{await runWithScheduledTaskTarget(target,()=>bridge.closeSession(boundSessionId,void 0,{closeIfUnheld:true,reason:"scheduled_task_deleted"}))}catch(error){if(sendActivityGateError(res,error))return}}if(boundSessionId){channelDeliveryAuthorizations?.revokeScheduledTask(workspaceCwd,boundSessionId,id)}res.status(200).json({deleted:true,id})}));app.post(`${base}/:id/run`,mutate(),withTarget(async(req,res,target)=>{const{workspaceCwd}=target;const id=typeof req.params["id"]==="string"?req.params["id"]:"";if(id.length===0){res.status(400).json({error:"Task id is required",code:"invalid_id"});return}const now=Date.now();let found=false;let blockedDisabled=false;let blockedLegacy=false;let updated;let rollbackBefore;let rollbackAfter;let removalGenerations;try{await runWithScheduledTaskTarget(target,()=>updateCronTasks(workspaceCwd,tasks=>{const idx=tasks.findIndex(t=>t.id===id);if(idx===-1)return tasks;found=true;const current=tasks[idx];if(taskHasLegacyCondition(current)){blockedLegacy=true;return tasks}if(current.enabled===false){blockedDisabled=true;return tasks}const next={...current,lastFiredAt:now,runs:appendCronRun(current.runs,{at:now,kind:"manual",...current.sessionMode!=="per_run"&¤t.sessionId?{sessionId:current.sessionId}:{}})};updated=next;rollbackBefore=tasks;const nextTasks=!current.recurring?tasks.filter((_,i)=>i!==idx):tasks.map((t,i)=>i===idx?next:t);rollbackAfter=nextTasks;return nextTasks},{assertCanCommit:target.assertGenerationOpen,observeDeletionIds:__name(tasks=>{const task=tasks.find(task2=>task2.id===id);return task?.sessionId?[id,cronTaskSessionDeletionId(task.sessionId)]:[id]},"observeDeletionIds"),onDeletionGenerations:__name(generations=>{removalGenerations=generations},"onDeletionGenerations")}))}catch(err){if(sendActivityGateError(res,err))return;if(sendGenerationClosedError(res,err))return;writeStderrLine(`qwen serve: POST ${base}/${id}/run failed: ${err instanceof Error?err.message:String(err)}`);res.status(500).json({error:"Failed to record scheduled task run",code:"scheduled_tasks_write_failed"});return}if(rollbackBefore&&rollbackAfter){try{target.assertGenerationOpen?.()}catch(error){await rollbackCronMutation(target,rollbackBefore,rollbackAfter,`POST ${base}/${id}/run`);if(sendGenerationClosedError(res,error))return;throw error}}if(blockedLegacy){res.status(409).json({error:"This task uses the removed isolated run mode with a precondition and can no longer run. Recreate it (and call the `create_sub_session` tool from the prompt if you need per-run isolation).",code:"task_legacy_unsupported"});return}if(blockedDisabled){res.status(409).json({error:"Cannot run a disabled task; enable it first (unarchive its session if it was archived).",code:"task_disabled"});return}if(!found||!updated){res.status(404).json({error:"Task not found",code:"task_not_found"});return}if(updated.sessionMode==="per_run"){const persistOutcome=__name(async outcome=>{if(!updated.recurring)return;await runWithScheduledTaskTarget(target,()=>updateCronTasks(workspaceCwd,tasks=>tasks.map(task=>task.id===id?annotateCronRunSession(task,now,outcome):task),{assertCanCommit:target.assertGenerationOpen}))},"persistOutcome");let childSessionId;try{childSessionId=await dispatchTaskToFreshSession(target,updated)}catch(error){updated=annotateCronRunSession(updated,now,{dispatchFailed:true});if(updated.recurring){await persistOutcome({dispatchFailed:true}).catch(persistError=>{writeStderrLine(`qwen serve: POST ${base}/${id}/run could not record the failed dispatch: ${persistError instanceof Error?persistError.message:String(persistError)}`)})}else{await restoreConsumedOneShot(target,rollbackBefore,updated,removalGenerations,`POST ${base}/${id}/run fresh-session dispatch`)}writeStderrLine(`qwen serve: POST ${base}/${id}/run could not create a fresh session: ${error instanceof Error?error.message:String(error)}`);res.status(500).json({error:"Failed to create a fresh session for the scheduled task",code:"scheduled_task_session_dispatch_failed"});return}updated=annotateCronRunSession(updated,now,{sessionId:childSessionId});await persistOutcome({sessionId:childSessionId}).catch(error=>{writeStderrLine(`qwen serve: POST ${base}/${id}/run could not attribute fresh session ${childSessionId}: ${error instanceof Error?error.message:String(error)}`)})}if(!updated.recurring&&updated.sessionId){channelDeliveryAuthorizations?.revokeScheduledTask(workspaceCwd,updated.sessionId,updated.id)}const view=toView(updated);if(!updated.recurring)view.nextRunAt=null;res.status(200).json(view)}))}__name(registerScheduledTaskCrudRoutes,"registerScheduledTaskCrudRoutes");function registerScheduledTasksRoutes(app,deps){const{boundWorkspace,mutate,safeBody,bridge,channelDeliveryAuthorizations}=deps;registerScheduledTaskCrudRoutes(app,{prefix:"",resolveTarget:__name((_req,res)=>{const runtime=deps.getRuntime?.();if(deps.getRuntime&&!runtime){res.set("Retry-After","1");res.status(503).json({error:"Workspace runtime is not active",code:"workspace_runtime_unavailable"});return null}if(runtime&&!requireTrustedWorkspaceRuntime(runtime,res))return null;return{workspaceCwd:boundWorkspace,...runtime?{runtimeBaseDir:runtime.sessionRuntimeBaseDir,...deps.cleanupSession?{cleanupSession:__name(sessionId=>deps.cleanupSession(runtime,sessionId),"cleanupSession")}:{}}:{},bridge:bridge===void 0?void 0:runtime?.bridge??bridge,...runtime?.generationGuard?{assertGenerationOpen:__name(()=>runtime.generationGuard?.assertOpen(),"assertGenerationOpen")}:{},...deps.workspaceRegistry?{resolveLiveSessionOwner:__name(sessionId=>deps.workspaceRegistry.resolveLiveSessionOwner(sessionId),"resolveLiveSessionOwner")}:{}}},"resolveTarget"),mutate,safeBody,channelDeliveryAuthorizations})}__name(registerScheduledTasksRoutes,"registerScheduledTasksRoutes");function registerWorkspaceQualifiedScheduledTasksRoutes(app,deps){const{workspaceRegistry,mutate,safeBody,manageScheduledTaskSessions,channelDeliveryAuthorizations,cleanupSession}=deps;registerScheduledTaskCrudRoutes(app,{prefix:"/workspaces/:workspace",resolveTarget:__name((req,res)=>{const runtime=resolveWorkspaceRuntimeWithLiveCompatibilityFromParam(workspaceRegistry,req,res);if(!runtime)return null;if(!requireTrustedWorkspaceRuntime(runtime,res))return null;if(runtime.provenance==="live-conversation"&&!deps.conversationRuntimeActivity){sendConversationRuntimeUnavailable(res);return null}if(runtime.provenance==="live-conversation"&&req.method==="POST"&&req.params["id"]===void 0&&parseCallerSuppliedSessionId(safeBody(req)["sessionId"]).kind==="absent"){res.status(400).json({error:"Generic scheduled tasks cannot create sessions in the Conversations workspace.",code:"live_session_creation_reserved"});return null}return{workspaceCwd:runtime.workspaceCwd,runtimeBaseDir:runtime.sessionRuntimeBaseDir,...runtime.provenance==="live-conversation"&&deps.conversationRuntimeActivity?{activity:deps.conversationRuntimeActivity}:{},...cleanupSession?{cleanupSession:__name(sessionId=>cleanupSession(runtime,sessionId),"cleanupSession")}:{},bridge:manageScheduledTaskSessions?runtime.bridge:void 0,...runtime.generationGuard?{assertGenerationOpen:__name(()=>runtime.generationGuard?.assertOpen(),"assertGenerationOpen")}:{},resolveLiveSessionOwner:__name(sessionId=>workspaceRegistry.resolveLiveSessionOwner(sessionId),"resolveLiveSessionOwner")}},"resolveTarget"),mutate,safeBody,channelDeliveryAuthorizations})}__name(registerWorkspaceQualifiedScheduledTasksRoutes,"registerWorkspaceQualifiedScheduledTasksRoutes");var REMOVED_TASK_FIELDS=["runMode","condition"];function findRemovedTaskField(body){return REMOVED_TASK_FIELDS.find(field=>field in body)}__name(findRemovedTaskField,"findRemovedTaskField");function removedFieldError(field){return{error:`\`${field}\` is no longer supported: the isolated scheduled-task run mode was removed. Every task now runs in its bound session; call the \`create_sub_session\` tool from the task prompt for per-run isolation.`,code:"unsupported_field"}}__name(removedFieldError,"removedFieldError");function parseNameField(raw){if(raw===void 0||raw===null)return{value:void 0};if(typeof raw!=="string"){return{error:"`name` must be a string"}}const trimmed=raw.trim();if(trimmed.length===0)return{value:void 0};if(trimmed.length>MAX_NAME_LENGTH){return{error:`\`name\` exceeds ${MAX_NAME_LENGTH}-character limit`}}return{value:trimmed}}__name(parseNameField,"parseNameField");export{scheduledTaskSessionName,ExistingSessionScheduledTaskCreateError,createScheduledTaskWithExistingSession,registerScheduledTasksRoutes,registerWorkspaceQualifiedScheduledTasksRoutes};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2025 Qwen Team
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{t}from"./chunk-
|
|
3
|
+
import{t}from"./chunk-AUM57JI2.js";import{writeStderrLine}from"./chunk-M4ECEHLX.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var LOOP_DETECTED_FALLBACK_MESSAGE="A potential loop was detected. This can happen due to repetitive tool calls or other model behavior. The request has been halted.";var LOOP_TYPE_LABELS={["consecutive_identical_tool_calls"]:"the model repeated the same tool call with identical arguments",["chanting_identical_sentences"]:"the model repeated the same sentence in its output or reasoning",["repetitive_thoughts"]:"the model repeated the same reasoning thought",["read_file_loop"]:"the model spent too many consecutive calls reading files without making progress",["action_stagnation"]:"the model kept calling the same tool without making progress",["shell_command_stagnation"]:"the model repeated similar shell inspection commands without making progress",["global_tool_call_duplicate"]:"the model repeated the same tool call across the turn, even when not back-to-back",["alternating_tool_call_pattern"]:"the model alternated between the same two tool calls in a repeating pattern",["turn_tool_call_cap"]:"the turn reached the per-turn tool-call limit",["invalid_tool_params_stagnation"]:"the model repeatedly sent invalid tool parameters without correcting them",["repeated_tool_execution_failure"]:"the same tool execution failure continued after a corrective reminder"};var ALWAYS_ON_HINT=" This is an always-on guard and cannot be disabled via `model.skipLoopDetection`.";var GOVERNED_HINT=' Set `model.loopProtection` to "warn" to remind the model instead of stopping, or to "off" to disable this guard.';var HEURISTIC_HINT=' Set `model.loopProtection` to "warn" to remind the model instead of stopping, or `model.skipLoopDetection` to true to disable this check.';var SKIP_HINT=" Set the `model.skipLoopDetection` setting to true to disable.";function reasonLabel(stop){const limit=stop.toolCallLimit;switch(stop.loopReason){case"explicit_cap":return`the turn reached the per-turn tool-call limit set by \`model.maxToolCallsPerTurn\`${limit!==void 0?` (${limit})`:""}`;case"backstop":return limit!==void 0?`the turn reached the ${limit}-call backstop of the adaptive per-turn cap`:"the turn reached the backstop of the adaptive per-turn cap";case"stuck_repetition":return limit!==void 0?`past ${limit} tool calls the model kept repeating the same tool call`:"past the per-turn soft cap the model kept repeating the same tool call";case"provider_duplicate_id":return"the provider replayed a tool call id that had already run";default:return void 0}}__name(reasonLabel,"reasonLabel");function hint(stop){switch(stop.loopReason){case"explicit_cap":return" Raise `model.maxToolCallsPerTurn`, or set it to 0 to disable the cap.";case"backstop":return" Set `model.maxToolCallsPerTurn` to choose a fixed cap instead (0 disables it).";case"stuck_repetition":return' Give the model a more specific instruction, or set `model.loopProtection` to "warn" to remind it instead of stopping. An explicit `model.maxToolCallsPerTurn` replaces this repetition check with a fixed cap (0 disables it).';case"repeated_call":return HEURISTIC_HINT;case"provider_duplicate_id":return ALWAYS_ON_HINT;default:break}switch(stop.loopType){case"turn_tool_call_cap":return" A per-turn tool-call cap was reached. The default is adaptive (allows up to 1000 diverse calls, halting only on repeated calls); an explicitly set `model.maxToolCallsPerTurn` is a hard cap. If the model was repeating the same call, investigate the repetition; otherwise unset the value to use the adaptive default, or raise it (set 0 to disable).";case"consecutive_identical_tool_calls":case"shell_command_stagnation":case"invalid_tool_params_stagnation":return GOVERNED_HINT;case"repeated_tool_execution_failure":return ALWAYS_ON_HINT;case"chanting_identical_sentences":case"repetitive_thoughts":case void 0:return SKIP_HINT;default:return HEURISTIC_HINT}}__name(hint,"hint");function describeLoopStop(stop){if(!stop?.loopType)return void 0;return reasonLabel(stop)??LOOP_TYPE_LABELS[stop.loopType]}__name(describeLoopStop,"describeLoopStop");function formatLoopDetectedMessage(stop){const cause=describeLoopStop(stop);const detail=cause?` (${stop?.loopType}: ${cause})`:"";return`Loop detection halted the run${detail}.${hint(stop??{})}`}__name(formatLoopDetectedMessage,"formatLoopDetectedMessage");function formatInteractiveLoopDetectedMessage(stop){return stop?.loopType?formatLoopDetectedMessage(stop):LOOP_DETECTED_FALLBACK_MESSAGE}__name(formatInteractiveLoopDetectedMessage,"formatInteractiveLoopDetectedMessage");init_esbuild_shims();import{randomUUID}from"node:crypto";var CHAT_RECORDING_FAILURE_MESSAGE="Session recording stopped after a write failure. New messages for the affected session will not be saved. Check disk space and permissions, then start a new session to resume recording. See the debug log for details.";var TUI_CHAT_RECORDING_FAILURE_MESSAGE="Session recording stopped after a write failure. New messages for the affected session will not be saved. Check disk space and permissions, then run `/clear` to start a new recorded session. See the debug log for details.";var CHAT_RECORDING_SETTLE_TIMEOUT_MS=2e3;var debugLogger=createDebugLogger("CHAT_RECORDING");function createChatRecordingFailureSystemMessage(event){return{type:"system",subtype:"session_recording_degraded",uuid:randomUUID(),session_id:event.sessionId,parent_tool_use_id:null,data:{session_id:event.sessionId,reason:"write_failed",message:CHAT_RECORDING_FAILURE_MESSAGE}}}__name(createChatRecordingFailureSystemMessage,"createChatRecordingFailureSystemMessage");function reportChatRecordingFailureToAdapter(adapter,event){adapter.emitMessage(createChatRecordingFailureSystemMessage(event))}__name(reportChatRecordingFailureToAdapter,"reportChatRecordingFailureToAdapter");function subscribeToHeadlessChatRecordingFailures(config,adapter){if(typeof config.onChatRecordingFailure!=="function")return()=>{};return config.onChatRecordingFailure(event=>{if(config.getOutputFormat()==="text"){writeStderrLine(`Warning: ${t(CHAT_RECORDING_FAILURE_MESSAGE)}`);return}reportChatRecordingFailureToAdapter(adapter,event)})}__name(subscribeToHeadlessChatRecordingFailures,"subscribeToHeadlessChatRecordingFailures");async function settleChatRecording(config,options){if(typeof config.getChatRecordingService!=="function")return"settled";const recorder=config.getChatRecordingService();if(!recorder)return"settled";if(options.finalize)recorder.finalize();let timer;const timeout=new Promise(resolve=>{timer=setTimeout(()=>{debugLogger.debug("Timed out waiting for chat recording to flush");resolve("timeout")},CHAT_RECORDING_SETTLE_TIMEOUT_MS)});const settled=recorder.flush().then(()=>"settled",()=>"settled");try{return await Promise.race([settled,timeout])}finally{if(timer)clearTimeout(timer)}}__name(settleChatRecording,"settleChatRecording");export{describeLoopStop,formatLoopDetectedMessage,formatInteractiveLoopDetectedMessage,TUI_CHAT_RECORDING_FAILURE_MESSAGE,reportChatRecordingFailureToAdapter,subscribeToHeadlessChatRecordingFailures,settleChatRecording};
|
|
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{t}from"./chunk-
|
|
3
|
+
import{t}from"./chunk-AUM57JI2.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();function formatHistoryGapNotice(_gap){return t("\u26A0\uFE0F History gap: earlier conversation was lost before this point (storage interruption) and could not be recovered.")}__name(formatHistoryGapNotice,"formatHistoryGapNotice");function indexGapsByChild(gaps){const byChild=new Map;for(const gap of gaps??[]){byChild.set(gap.childUuid,gap)}return byChild}__name(indexGapsByChild,"indexGapsByChild");export{formatHistoryGapNotice,indexGapsByChild};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2025 Qwen Code
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{getUserSettingsPath,v1ToV2Migration}from"./chunk-
|
|
3
|
+
import{getUserSettingsPath,v1ToV2Migration}from"./chunk-4RJ2RRGZ.js";import{require_strip_json_comments}from"./chunk-EKRCICRK.js";import{getSystemDefaultsPath,getSystemSettingsPath}from"./chunk-ERGT5BD3.js";import{LoadedTrustedFolders,TrustLevel,getExplicitTrustLevel,getTrustedFoldersPath,isWorkflowAncestorDirectorySafe,parseJsoncObject}from"./chunk-EYECE2PH.js";import{arePathsEquivalent}from"./chunk-IDXJIDME.js";import{ideContextStore}from"./chunk-ZUWLTGSR.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{createHash}from"node:crypto";import*as fs from"node:fs/promises";var import_strip_json_comments=__toESM(require_strip_json_comments(),1);var MAX_TRUSTED_FOLDERS_BYTES=1024*1024;var MAX_SETTINGS_BYTES=4*1024*1024;function evaluateDaemonWorkflowAncestorTrust(snapshot,query){const denied=__name(()=>query.ancestorDirs.map(()=>false),"denied");if(snapshot.settingsError)return denied();if(!snapshot.folderTrustEnabled){return query.ancestorDirs.map(isWorkflowAncestorDirectorySafe)}if(snapshot.trustedFoldersError||snapshot.ideTrust===false&&(arePathsEquivalent(query.workspaceCwd,query.ideScopeCwd)||arePathsEquivalent(query.canonicalTargetDir,query.ideScopeCwd))){return denied()}const folders=new LoadedTrustedFolders({path:getTrustedFoldersPath(),config:{...snapshot.trustedFolders}},[]);if(folders.isPathTrusted(query.canonicalTargetDir)!==true){return denied()}return query.ancestorDirs.map(directory=>folders.isPathTrusted(directory)===true)}__name(evaluateDaemonWorkflowAncestorTrust,"evaluateDaemonWorkflowAncestorTrust");function policyError(code,filePath,error){return{code,path:filePath,message:error instanceof Error?error.message:String(error)}}__name(policyError,"policyError");async function readJsonObject(filePath,maxBytes,requireRegularFile,retryMissing=false,allowTrailingComma=false){const delays=[0,50,200];let result={};for(const delay of delays){if(delay>0){await new Promise(resolve=>setTimeout(resolve,delay))}result=await readJsonObjectOnce(filePath,maxBytes,requireRegularFile,allowTrailingComma);if(!result.error&&(!result.missing||!retryMissing))return result}return result}__name(readJsonObject,"readJsonObject");async function readJsonObjectOnce(filePath,maxBytes,requireRegularFile,allowTrailingComma){let stat2;try{stat2=await fs.lstat(filePath)}catch(error){if(error instanceof Error&&"code"in error&&error.code==="ENOENT"){return{value:{},missing:true}}return{error:policyError("trust_policy_unreadable",filePath,error)}}if(!requireRegularFile&&stat2.isSymbolicLink()){try{stat2=await fs.stat(filePath)}catch(error){return{error:policyError("trust_policy_unreadable",filePath,error)}}}if(requireRegularFile&&stat2.isSymbolicLink()||!stat2.isFile()){return{error:policyError("trust_policy_invalid",filePath,new Error("Trust policy input must be a regular file."))}}if(stat2.size>maxBytes){return{error:policyError("trust_policy_invalid",filePath,new Error(`Trust policy input exceeds ${maxBytes} bytes.`))}}try{const raw=await fs.readFile(filePath,"utf8");const parsed=allowTrailingComma?parseJsoncObject(raw):JSON.parse((0,import_strip_json_comments.default)(raw));if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed)){throw new Error("Trust policy input must contain a JSON object.")}return{value:parsed}}catch(error){if(error instanceof Error&&"code"in error&&error.code==="ENOENT"){return{value:{},missing:true}}return{error:policyError("trust_policy_invalid",filePath,error)}}}__name(readJsonObjectOnce,"readJsonObjectOnce");function migrateFolderTrustSettings(value,scope){if(!value||!v1ToV2Migration.shouldMigrate(value))return value;return v1ToV2Migration.migrate(value,scope).settings}__name(migrateFolderTrustSettings,"migrateFolderTrustSettings");function folderTrustSetting(value,filePath){if(!value||!("security"in value))return{};const security=value?.["security"];if(typeof security!=="object"||security===null||Array.isArray(security)){return{error:policyError("trust_policy_invalid",filePath,new Error("`security` must be an object."))}}if(!("folderTrust"in security))return{};const folderTrust=security["folderTrust"];if(typeof folderTrust!=="object"||folderTrust===null||Array.isArray(folderTrust)){return{error:policyError("trust_policy_invalid",filePath,new Error("`security.folderTrust` must be an object."))}}if(!("enabled"in folderTrust))return{};const enabled=folderTrust["enabled"];if(typeof enabled==="boolean")return{value:enabled};return{error:policyError("trust_policy_invalid",filePath,new Error("`security.folderTrust.enabled` must be a boolean."))}}__name(folderTrustSetting,"folderTrustSetting");function parseTrustedFolders(value,filePath){const config={};for(const[rulePath,rawLevel]of Object.entries(value??{})){if(!Object.values(TrustLevel).includes(rawLevel)){return{config:{},error:policyError("trust_policy_invalid",filePath,new Error(`Invalid trust level for ${JSON.stringify(rulePath)}.`))}}config[rulePath]=rawLevel}return{config}}__name(parseTrustedFolders,"parseTrustedFolders");function semanticRevision(input){const sortedRules=Object.entries(input.trustedFolders).sort(([a],[b])=>a.localeCompare(b));return createHash("sha256").update(JSON.stringify({folderTrustEnabled:input.folderTrustEnabled,ideTrust:input.ideTrust??null,trustedFolders:sortedRules,settingsError:input.settingsError?.code??null,trustedFoldersError:input.trustedFoldersError?.code??null})).digest("hex")}__name(semanticRevision,"semanticRevision");async function readDaemonTrustPolicySnapshot(){const[user,system,systemDefaults]=await Promise.all([readJsonObject(getUserSettingsPath(),MAX_SETTINGS_BYTES,false),readJsonObject(getSystemSettingsPath(),MAX_SETTINGS_BYTES,false),readJsonObject(getSystemDefaultsPath(),MAX_SETTINGS_BYTES,false)]);const systemFolderTrust=folderTrustSetting(migrateFolderTrustSettings(system.value,"System"),getSystemSettingsPath());const userFolderTrust=folderTrustSetting(migrateFolderTrustSettings(user.value,"User"),getUserSettingsPath());const defaultsFolderTrust=folderTrustSetting(migrateFolderTrustSettings(systemDefaults.value,"SystemDefaults"),getSystemDefaultsPath());const settingsError=system.error??systemFolderTrust.error??user.error??userFolderTrust.error??systemDefaults.error??defaultsFolderTrust.error;const folderTrustEnabled=systemFolderTrust.value??userFolderTrust.value??defaultsFolderTrust.value??false;const trustedFoldersFile=await readJsonObject(getTrustedFoldersPath(),MAX_TRUSTED_FOLDERS_BYTES,true,folderTrustEnabled,true);const parsedTrustedFolders=parseTrustedFolders(trustedFoldersFile.value,getTrustedFoldersPath());const trustedFoldersError=trustedFoldersFile.error??parsedTrustedFolders.error;const ideTrust=ideContextStore.get()?.workspaceState?.isTrusted;const revision=semanticRevision({folderTrustEnabled,ideTrust,trustedFolders:parsedTrustedFolders.config,...settingsError?{settingsError}:{},...trustedFoldersError?{trustedFoldersError}:{}});return{revision,folderTrustEnabled,ideTrust,trustedFolders:Object.freeze({...parsedTrustedFolders.config}),...settingsError?{settingsError}:{},...trustedFoldersError?{trustedFoldersError}:{}}}__name(readDaemonTrustPolicySnapshot,"readDaemonTrustPolicySnapshot");function explicitTrustLevel(snapshot,workspaceCwd){return getExplicitTrustLevel(snapshot.trustedFolders,workspaceCwd)}__name(explicitTrustLevel,"explicitTrustLevel");function evaluateDaemonWorkspaceTrust(snapshot,workspaceCwd,processCwd=process.cwd()){if(snapshot.settingsError){return{state:"error",targetTrusted:false,source:"none",explicitTrustLevel:null,error:snapshot.settingsError}}if(!snapshot.folderTrustEnabled){return{state:"trusted",targetTrusted:true,source:"disabled",explicitTrustLevel:null}}if(snapshot.ideTrust!==void 0&&arePathsEquivalent(workspaceCwd,processCwd)){return{state:snapshot.ideTrust?"trusted":"untrusted",targetTrusted:snapshot.ideTrust,source:"ide",explicitTrustLevel:null}}if(snapshot.trustedFoldersError){return{state:"error",targetTrusted:false,source:"none",explicitTrustLevel:null,error:snapshot.trustedFoldersError}}const folders=new LoadedTrustedFolders({path:getTrustedFoldersPath(),config:{...snapshot.trustedFolders}},[]);const trusted=folders.isPathTrusted(workspaceCwd);return{state:trusted===true?"trusted":trusted===false?"untrusted":"unknown",targetTrusted:trusted===true,source:trusted===void 0?"none":"file",explicitTrustLevel:explicitTrustLevel(snapshot,workspaceCwd)}}__name(evaluateDaemonWorkspaceTrust,"evaluateDaemonWorkspaceTrust");export{evaluateDaemonWorkflowAncestorTrust,readDaemonTrustPolicySnapshot,evaluateDaemonWorkspaceTrust};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2026 Qwen Team
|