gerege-cli 0.26.5 → 0.26.7
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/README.md +8 -8
- package/chunks/{MaxSizedBox-VMVLMS4X.js → MaxSizedBox-LSNOJEKM.js} +1 -1
- package/chunks/{StandaloneSessionPicker-UNORCVYY.js → StandaloneSessionPicker-KSYGPMEV.js} +1 -1
- package/chunks/{acp-subagent-executor-623ZUTJT.js → acp-subagent-executor-NSW2MFUI.js} +1 -1
- package/chunks/{acpAgent-MTTDTK2C.js → acpAgent-3DTOHTDM.js} +3 -3
- package/chunks/{advisor-ANUGICJ5.js → advisor-7JGQPS7X.js} +1 -1
- package/chunks/{agent-GNCQDICJ.js → agent-PNKQJGDO.js} +1 -1
- package/chunks/{agent-headless-OPUXAXQM.js → agent-headless-7D33X7QQ.js} +1 -1
- package/chunks/{agent-host-client-K6GRPTFD.js → agent-host-client-3R2MAUVE.js} +1 -1
- package/chunks/{agent-host-connections-MF3YBZU2.js → agent-host-connections-2D7DECAE.js} +1 -1
- package/chunks/{anthropicContentGenerator-OK4PFE5Y.js → anthropicContentGenerator-MGTJJGEQ.js} +1 -1
- package/chunks/{autofix-pr-MABTGEHZ.js → autofix-pr-OIHHZSPQ.js} +1 -1
- package/chunks/{batch-V2NJT3M5.js → batch-6UDAMPAA.js} +1 -1
- package/chunks/{bridge-BJQ627CX.js → bridge-QXVXPNJ6.js} +1 -1
- package/chunks/{channel-settings-store-4JMCI4UR.js → channel-settings-store-P4W4R5SJ.js} +1 -1
- package/chunks/{chunk-ZN57TOVA.js → chunk-2DU2WMTL.js} +1 -1
- package/chunks/{chunk-ISGF3BVD.js → chunk-2J2BQ3PL.js} +2 -2
- package/chunks/{chunk-TQTIEK2W.js → chunk-2LMSDH6P.js} +1 -1
- package/chunks/{chunk-EIILQ6KT.js → chunk-3EZ5GCUT.js} +1 -1
- package/chunks/{chunk-UY2ET2AL.js → chunk-3ICJI5KW.js} +1 -1
- package/chunks/{chunk-VDRE7U3P.js → chunk-4A663FE6.js} +5 -5
- package/chunks/{chunk-2IGE2K5V.js → chunk-4AKTP4MM.js} +1 -1
- package/chunks/{chunk-NO26JN24.js → chunk-4LC4INFI.js} +1 -1
- package/chunks/{chunk-CKZRJP4F.js → chunk-4ME3BUJK.js} +1 -1
- package/chunks/{chunk-3XBJYUWP.js → chunk-4QOVM2LL.js} +1 -1
- package/chunks/{chunk-ZYTG6R7S.js → chunk-4VR4DUUD.js} +1 -1
- package/chunks/{chunk-DE53B2R7.js → chunk-4W27Z3OL.js} +1 -1
- package/chunks/{chunk-QOYRDEXR.js → chunk-53IB4U4E.js} +1 -1
- package/chunks/{chunk-CCOUFBOY.js → chunk-5R2JIZID.js} +1 -1
- package/chunks/{chunk-MPAR4JBP.js → chunk-5TWAP4OG.js} +1 -1
- package/chunks/{chunk-3NQESE5K.js → chunk-6JAXAFX7.js} +1 -1
- package/chunks/{chunk-POA4NX4N.js → chunk-6WV5RKYB.js} +1 -1
- package/chunks/{chunk-KN27BFXM.js → chunk-6YFNUVJR.js} +1 -1
- package/chunks/{chunk-2X3UF2CF.js → chunk-7HFFTOAD.js} +1 -1
- package/chunks/{chunk-KDYUZBZC.js → chunk-ATTJQLQV.js} +1 -1
- package/chunks/{chunk-USJFJZ23.js → chunk-BGELKSQ4.js} +1 -1
- package/chunks/{chunk-X4BFEDWU.js → chunk-BIPPD7W6.js} +1 -1
- package/chunks/{chunk-DEMXCA3K.js → chunk-BVV7UXES.js} +1 -1
- package/chunks/{chunk-2VCDJ6UF.js → chunk-BY46PCWY.js} +1 -1
- package/chunks/{chunk-CXGGC4NO.js → chunk-CDKBM72V.js} +1 -1
- package/chunks/{chunk-5WLKN3GD.js → chunk-CK3OKTTL.js} +1 -1
- package/chunks/{chunk-FHBGTZ4K.js → chunk-DEJ47KJE.js} +1 -1
- package/chunks/{chunk-DTTC4ZKY.js → chunk-DQQN2HOP.js} +1 -1
- package/chunks/{chunk-PN62SUYK.js → chunk-DTX2OVQW.js} +1 -1
- package/chunks/{chunk-IBYFSHBB.js → chunk-DVUKYOCJ.js} +1 -1
- package/chunks/{chunk-Q5E5SOY2.js → chunk-E3KWSRJN.js} +1 -1
- package/chunks/{chunk-IDUGQMTP.js → chunk-EEPNACXJ.js} +1 -1
- package/chunks/{chunk-E5YRAQXM.js → chunk-EKRUF347.js} +1 -1
- package/chunks/{chunk-HSYBIGMS.js → chunk-F5SLLEJY.js} +1 -1
- package/chunks/{chunk-5ZQWQ3RK.js → chunk-F7622ZRQ.js} +1 -1
- package/chunks/{chunk-KKBOCRPF.js → chunk-FKUDVIME.js} +1 -1
- package/chunks/{chunk-62NLMVVT.js → chunk-FRVXSKL4.js} +1 -1
- package/chunks/{chunk-FIM7MM25.js → chunk-FTF2NFLB.js} +1 -1
- package/chunks/{chunk-OHXQYU6S.js → chunk-G4MWPXNY.js} +1 -1
- package/chunks/{chunk-SELRSZFK.js → chunk-GA35LMSX.js} +1 -1
- package/chunks/{chunk-SMYBY353.js → chunk-H34KVVI4.js} +1 -1
- package/chunks/{chunk-NGOIJH7K.js → chunk-H5EXNXGW.js} +1 -1
- package/chunks/{chunk-UBXLQ6TP.js → chunk-HJLRKM3W.js} +1 -1
- package/chunks/{chunk-CAPG7UVH.js → chunk-HVP4UF2Q.js} +1 -1
- package/chunks/{chunk-H57IX45A.js → chunk-HXTYFGSQ.js} +1 -1
- package/chunks/{chunk-55RVKT4O.js → chunk-IIHUDJX7.js} +1 -1
- package/chunks/{chunk-XFLLE2J3.js → chunk-IQMKQKKD.js} +2 -2
- package/chunks/{chunk-SQQORHMS.js → chunk-ISQMHOCC.js} +1 -1
- package/chunks/{chunk-YLAI26PX.js → chunk-IY7M5HKF.js} +1 -1
- package/chunks/{chunk-FDUXQAGW.js → chunk-IZXHCHJD.js} +1 -1
- package/chunks/{chunk-ZOBX6C7E.js → chunk-JHC22BZH.js} +1 -1
- package/chunks/{chunk-26ISBUM7.js → chunk-K7GN4CMV.js} +6 -6
- package/chunks/{chunk-4GC5HJZO.js → chunk-L7LO3YRT.js} +1 -1
- package/chunks/{chunk-ZSVSRF4C.js → chunk-LT3J74BZ.js} +1 -1
- package/chunks/{chunk-2PY7R7GG.js → chunk-LY4XTBL4.js} +1 -1
- package/chunks/{chunk-7IERHQ63.js → chunk-LYFRGP42.js} +1 -1
- package/chunks/{chunk-FPZPCZFS.js → chunk-MDCA4I63.js} +1 -1
- package/chunks/{chunk-2LLPGSUK.js → chunk-MS2XCBPP.js} +1 -1
- package/chunks/{chunk-3Y6LSWEW.js → chunk-MXZXQUVP.js} +1 -1
- package/chunks/{chunk-IH2PFVWO.js → chunk-N4ZQC5HB.js} +1 -1
- package/chunks/{chunk-MTW3A3KT.js → chunk-N6EFYQ7M.js} +1 -1
- package/chunks/{chunk-AQWHCRKY.js → chunk-NHPKD7LY.js} +1 -1
- package/chunks/{chunk-ABJGFEES.js → chunk-NO7VTKRL.js} +1 -1
- package/chunks/{chunk-CNFA5UUM.js → chunk-NPAENNRO.js} +1 -1
- package/chunks/{chunk-IA4K4PGK.js → chunk-NYBYDW6R.js} +1 -1
- package/chunks/{chunk-FNB3DPQZ.js → chunk-O3TUZQP4.js} +1 -1
- package/chunks/{chunk-RVJJFDF3.js → chunk-OZFZBGZG.js} +1 -1
- package/chunks/{chunk-B6D3KTUK.js → chunk-P2MZZMCS.js} +1 -1
- package/chunks/{chunk-GSOBASYW.js → chunk-PMBI46K4.js} +1 -1
- package/chunks/{chunk-WI4UMN3Q.js → chunk-Q5RRVBTY.js} +1 -1
- package/chunks/{chunk-5UZT4SXG.js → chunk-QHYSRPQR.js} +1 -1
- package/chunks/{chunk-2NOMOJWE.js → chunk-QONPET6Y.js} +2 -2
- package/chunks/{chunk-MOPJNP5I.js → chunk-QSPXKBUX.js} +1 -1
- package/chunks/{chunk-C56YJIEI.js → chunk-QTKPC24L.js} +1 -1
- package/chunks/{chunk-6X73W4TL.js → chunk-QTVSPQZQ.js} +1 -1
- package/chunks/{chunk-ADZI3OFT.js → chunk-QVHDM6N7.js} +1 -1
- package/chunks/{chunk-NVSKOSFG.js → chunk-RT6J7PV4.js} +1 -1
- package/chunks/{chunk-7MTBINFX.js → chunk-RULGA7WE.js} +2 -2
- package/chunks/{chunk-AMTFJVDD.js → chunk-SAVYMUU3.js} +1 -1
- package/chunks/{chunk-Z5XENA4A.js → chunk-T3CQ72HC.js} +8 -7
- package/chunks/{chunk-OPYGNTZP.js → chunk-U5YOAOU3.js} +1 -1
- package/chunks/{chunk-HFV6CQWE.js → chunk-ULLW2AYD.js} +1 -1
- package/chunks/{chunk-KGJ47CI5.js → chunk-UM5KBBYP.js} +1 -1
- package/chunks/{chunk-F26LTWDZ.js → chunk-UVMLWDRU.js} +1 -1
- package/chunks/{chunk-BRPJ5EHA.js → chunk-VK7LOUOJ.js} +1 -1
- package/chunks/{chunk-4EQWJTJR.js → chunk-VUNHJ74J.js} +1 -1
- package/chunks/{chunk-WB34KMOT.js → chunk-W2CV36HT.js} +1 -1
- package/chunks/{chunk-ADTFKUH2.js → chunk-WCI33URB.js} +1 -1
- package/chunks/{chunk-4TYTJQWR.js → chunk-WEPC42YR.js} +1 -1
- package/chunks/{chunk-YGHM5CDT.js → chunk-WF7Q3ZSQ.js} +1 -1
- package/chunks/{chunk-UJYOILZR.js → chunk-WK666FGZ.js} +3 -3
- package/chunks/{chunk-3WQPUP5U.js → chunk-WMLYHZZX.js} +1 -1
- package/chunks/{chunk-OCBJCZC2.js → chunk-WSI4G7XC.js} +1 -1
- package/chunks/{chunk-Q6QS5JTK.js → chunk-WXK7Z45R.js} +1 -1
- package/chunks/{chunk-6NI33TVK.js → chunk-X2TY7VTY.js} +1 -1
- package/chunks/{chunk-BBOJUFMW.js → chunk-YWK3E4WJ.js} +1 -1
- package/chunks/{chunk-FNXO5KWB.js → chunk-YY4GWNTU.js} +2 -2
- package/chunks/{chunk-FLJLUMQF.js → chunk-ZFOEVHWG.js} +1 -1
- package/chunks/{codex-subagent-executor-EK3A2WBH.js → codex-subagent-executor-GPTKVP7H.js} +1 -1
- package/chunks/{config-utils-DLOK7OLM.js → config-utils-6B5FHBSF.js} +1 -1
- package/chunks/{contextCommand-AVCUCHQC.js → contextCommand-FGRDE3GA.js} +1 -1
- package/chunks/{core-runtime-QSS4ZTG6.js → core-runtime-OFEHSKDB.js} +1 -1
- package/chunks/{create-sub-session-PNF7QDKC.js → create-sub-session-D2KEWVHQ.js} +1 -1
- package/chunks/{cron-create-C6JOFIU4.js → cron-create-RFGGKTL7.js} +1 -1
- package/chunks/{daemon-git-worktree-guard-5XZAZ7D2.js → daemon-git-worktree-guard-AV752IOZ.js} +1 -1
- package/chunks/{daemon-status-provider-MRNELSNJ.js → daemon-status-provider-GHQBRDMC.js} +1 -1
- package/chunks/{daemon-trust-policy-26CMW3WY.js → daemon-trust-policy-24ENJNTQ.js} +1 -1
- package/chunks/{daemon-trust-policy-monitor-3DWO6NQY.js → daemon-trust-policy-monitor-NMSQAGWV.js} +1 -1
- package/chunks/{deferred-core-runtime-DEC3N46T.js → deferred-core-runtime-5BAMFFOI.js} +1 -1
- package/chunks/{edit-3HMQPCHN.js → edit-XCECLEH3.js} +1 -1
- package/chunks/{enterPlanMode-QHJF4JXZ.js → enterPlanMode-SEN2PMRM.js} +1 -1
- package/chunks/{environment-NGIBJWOT.js → environment-CCPQJYKS.js} +1 -1
- package/chunks/{errors-MSTGCVGJ.js → errors-Y6HHUTGK.js} +1 -1
- package/chunks/{execution-tool-VR4TGOI4.js → execution-tool-HADWGMIG.js} +1 -1
- package/chunks/{execution-worker-EJH7HIE2.js → execution-worker-GZS7WOQL.js} +1 -1
- package/chunks/{exitPlanMode-P25OHQJ6.js → exitPlanMode-76B5HDLT.js} +1 -1
- package/chunks/{fast-path-II433ZDP.js → fast-path-OEV7LQYV.js} +1 -1
- package/chunks/{glob-4Q6DCT3F.js → glob-NLWCQRMS.js} +1 -1
- package/chunks/{goal-tools-FFMAJW6V.js → goal-tools-43XV33BT.js} +1 -1
- package/chunks/{handleAutoUpdate-QNM26NZK.js → handleAutoUpdate-JDQWGSSP.js} +1 -1
- package/chunks/{i18n-L5URVOBB.js → i18n-JW6BVEGF.js} +1 -1
- package/chunks/{initializer-NQ2NECYP.js → initializer-UT6JLZ3O.js} +1 -1
- package/chunks/{installationInfo-BCTXASUM.js → installationInfo-LKWDV3S2.js} +1 -1
- package/chunks/{interactive-mod-session-PPTBI37E.js → interactive-mod-session-2KWKYVPC.js} +1 -1
- package/chunks/{list-7TE5TUZJ.js → list-BKINK3S2.js} +1 -1
- package/chunks/{llm-BWWKUBBZ.js → llm-3RWXAVM2.js} +4 -4
- package/chunks/{llm-content-generator-QOTGPBYC.js → llm-content-generator-MDRBSH73.js} +1 -1
- package/chunks/{loadedSettingsAdapter-THAGI5M2.js → loadedSettingsAdapter-WWJUKWUN.js} +1 -1
- package/chunks/{local-7BTAGV4J.js → local-TT4FLCTR.js} +1 -1
- package/chunks/{local-execution-environment-S3OR4KSC.js → local-execution-environment-OBA6VWYL.js} +1 -1
- package/chunks/{loggingContentGenerator-AXJ5E5RS.js → loggingContentGenerator-CK7IKYQH.js} +1 -1
- package/chunks/{loop-wakeup-AJTLMLRX.js → loop-wakeup-4MSRX3DY.js} +1 -1
- package/chunks/{manage-memory-JHTUVMDJ.js → manage-memory-PX5PZJKZ.js} +1 -1
- package/chunks/{managed-execution-engine-U6GNJ4U4.js → managed-execution-engine-WMAUR3ZK.js} +1 -1
- package/chunks/{managed-local-serve-P4ZXVRBU.js → managed-local-serve-X7REHGB4.js} +1 -1
- package/chunks/{managed-npm-update-UDUILNR5.js → managed-npm-update-6HUVAJH7.js} +1 -1
- package/chunks/{managed-runtime-attestation-worker-P34ZBNRG.js → managed-runtime-attestation-worker-F4AT53M5.js} +1 -1
- package/chunks/{managed-runtime-bootstrap-CLMYNPH5.js → managed-runtime-bootstrap-3BP5JRJX.js} +1 -1
- package/chunks/{managed-runtime-session-worker-7H7AZJBV.js → managed-runtime-session-worker-2PO7J5UK.js} +1 -1
- package/chunks/{managed-runtime-ssh-worker-5KEMC7FD.js → managed-runtime-ssh-worker-4N7EMRSV.js} +1 -1
- package/chunks/{managed-session-authority-CFUZ45HT.js → managed-session-authority-MYOYTUM2.js} +1 -1
- package/chunks/{mcp-YMG4RVMC.js → mcp-5OTEMZ7P.js} +1 -1
- package/chunks/{memory-7STURUXK.js → memory-TNW7RSAV.js} +1 -1
- package/chunks/mn-JMS6SWTO.js +8 -0
- package/chunks/{model-call-collection-WBWTO3EG.js → model-call-collection-KNTWFZQS.js} +1 -1
- package/chunks/{model-configuration-6KCZZSZD.js → model-configuration-U5C5P5UQ.js} +1 -1
- package/chunks/{modelConfigUtils-Z2EKFSPN.js → modelConfigUtils-R4KFI2WK.js} +1 -1
- package/chunks/{monitor-U5E33JO6.js → monitor-RD2PFK42.js} +1 -1
- package/chunks/{nonInteractiveCli-BVCL5I5R.js → nonInteractiveCli-QQ72HZSH.js} +1 -1
- package/chunks/{nonInteractiveToolExecutor-B4EUOMYF.js → nonInteractiveToolExecutor-QPQYR6IS.js} +1 -1
- package/chunks/{notebook-edit-MXKD5J2C.js → notebook-edit-YLRN3UZT.js} +1 -1
- package/chunks/{omni-I5YECZBW.js → omni-CUJ52EW5.js} +1 -1
- package/chunks/{openaiContentGenerator-Q5SINFJJ.js → openaiContentGenerator-6B5MAU54.js} +1 -1
- package/chunks/{openaiResponsesContentGenerator-R3XCZLZY.js → openaiResponsesContentGenerator-I245I3R7.js} +1 -1
- package/chunks/{pidfile-UOGUNUTK.js → pidfile-P2HIGAUA.js} +1 -1
- package/chunks/{processUtils-QGQGZHBA.js → processUtils-JSKN5UGS.js} +1 -1
- package/chunks/{prompt-terminal-ledger-L57JMVSR.js → prompt-terminal-ledger-F5TSXVGU.js} +1 -1
- package/chunks/{qwenContentGenerator-UKZ237LC.js → qwenContentGenerator-IEDZONWG.js} +1 -1
- package/chunks/{reactive-degrade-3OM3HWVA.js → reactive-degrade-FYZBJCF6.js} +1 -1
- package/chunks/{read-file-63ZLWMOW.js → read-file-VNZNSD6X.js} +1 -1
- package/chunks/{resumeHistoryUtils-R5YQS4YQ.js → resumeHistoryUtils-IDPE6N2N.js} +1 -1
- package/chunks/{review-AT6OWVDO.js → review-TBJRZWTD.js} +1 -1
- package/chunks/{ripGrep-7KBZGTPV.js → ripGrep-4W5B5FOE.js} +1 -1
- package/chunks/{run-qwen-serve-CLBG7W6F.js → run-qwen-serve-44X262G5.js} +1 -1
- package/chunks/{runtime-R3QIGB7U.js → runtime-6H6LKD73.js} +1 -1
- package/chunks/{sandboxConfig-PM3ZRQYV.js → sandboxConfig-SQXDRGVN.js} +1 -1
- package/chunks/{scheduled-tasks-PUMNN5XV.js → scheduled-tasks-62IZKHJG.js} +1 -1
- package/chunks/{scheduler-KTPM226B.js → scheduler-QUCXJYRL.js} +1 -1
- package/chunks/{search-memory-7I5MGDNV.js → search-memory-TC2Z34QN.js} +1 -1
- package/chunks/{send-message-J526AEBI.js → send-message-TFZX7KI7.js} +1 -1
- package/chunks/{serve-KLTMPK4W.js → serve-WSICDFGG.js} +1 -1
- package/chunks/{server-VLRNY6KG.js → server-GYYVTNGY.js} +3 -3
- package/chunks/{session-2EB57NXY.js → session-KF3O23ZJ.js} +1 -1
- package/chunks/{session-attachments-root-I7TESMWL.js → session-attachments-root-7HFUSONH.js} +1 -1
- package/chunks/{session-execution-engine-selector-5FAMSPSO.js → session-execution-engine-selector-NVILT6BR.js} +1 -1
- package/chunks/{session-pr-refresh-JCPVQPNJ.js → session-pr-refresh-3KDFTDEV.js} +1 -1
- package/chunks/{sessionService-YRW2IFPR.js → sessionService-XRTFLPDW.js} +1 -1
- package/chunks/{settings-KO2Q47JP.js → settings-QPPK6WXE.js} +1 -1
- package/chunks/{shell-OLZVNTQZ.js → shell-WYQDZWL7.js} +1 -1
- package/chunks/{skill-XW2AQS7M.js → skill-FYPT6AU7.js} +1 -1
- package/chunks/{skill-settings-TKAVQ4XP.js → skill-settings-OGFI5KZF.js} +1 -1
- package/chunks/{spawnChannel-MBGCTK2J.js → spawnChannel-ANOOVPG7.js} +1 -1
- package/chunks/{standalone-update-A3YLLIAN.js → standalone-update-45WTDY4E.js} +1 -1
- package/chunks/{start-opentui-ui-G5ROAR4V.js → start-opentui-ui-TL5WK33V.js} +1 -1
- package/chunks/{startInteractiveUI-PZQR4U53.js → startInteractiveUI-N2IREVBM.js} +1 -1
- package/chunks/{team-create-S5ZY2UMF.js → team-create-R77PRZ5U.js} +1 -1
- package/chunks/{team-plan-approval-KX6RXEST.js → team-plan-approval-6DCRKB5I.js} +1 -1
- package/chunks/{terminal-image-renderer-SCJREXE6.js → terminal-image-renderer-TB7EX2WW.js} +1 -1
- package/chunks/{theme-manager-DZSM4EBR.js → theme-manager-RQDXJGVR.js} +1 -1
- package/chunks/{tool-call-UK56SWCT.js → tool-call-LVB4NCDT.js} +1 -1
- package/chunks/{tool-result-media-JLLSLGFL.js → tool-result-media-LRBB2KS6.js} +1 -1
- package/chunks/{tool-search-OWPFLVV5.js → tool-search-OG73QAQZ.js} +1 -1
- package/chunks/{total-session-admission-NQU4ACKH.js → total-session-admission-A4CUF6AD.js} +1 -1
- package/chunks/{trustedFolders-N7GXFYSF.js → trustedFolders-LSGOYTU2.js} +1 -1
- package/chunks/{update-relaunch-5SPXXHM2.js → update-relaunch-OGC6BZO7.js} +1 -1
- package/chunks/{updateCheck-VXUIX2XG.js → updateCheck-7J3GXTER.js} +1 -1
- package/chunks/{upload-config-OWLL4SRQ.js → upload-config-ML5XEJIF.js} +1 -1
- package/chunks/{useAutoAcceptIndicator-OUYRR56F.js → useAutoAcceptIndicator-6DH6GQ2X.js} +1 -1
- package/chunks/{validateNonInterActiveAuth-PSVJO5HK.js → validateNonInterActiveAuth-KJDAGZCM.js} +1 -1
- package/chunks/{version-C26S7UAW.js → version-7JN2YXL2.js} +1 -1
- package/chunks/{web-fetch-AYOYV7R4.js → web-fetch-42ZR4FEZ.js} +1 -1
- package/chunks/{web-search-DAREKD3Z.js → web-search-74NLPMZJ.js} +1 -1
- package/chunks/{workflow-WBGPKVO6.js → workflow-WNPHX42I.js} +1 -1
- package/chunks/{workflow-ancestor-trust-GEEB53TB.js → workflow-ancestor-trust-HGF6G7LQ.js} +1 -1
- package/chunks/{workspace-agents-IMAQME4W.js → workspace-agents-3YFBFAK3.js} +1 -1
- package/chunks/{workspace-providers-status-VALHVEU2.js → workspace-providers-status-EPJI6KRV.js} +1 -1
- package/chunks/{workspace-recovery-worker-AIAVRDGU.js → workspace-recovery-worker-T3FK5YOD.js} +1 -1
- package/chunks/{workspace-registration-store-FXEGZG3L.js → workspace-registration-store-VEXYBDMA.js} +1 -1
- package/chunks/{workspace-registry-GYFFHWCD.js → workspace-registry-NRZYTP2X.js} +1 -1
- package/chunks/{workspace-runtime-coordinator-VZ462TLU.js → workspace-runtime-coordinator-USNSTP2V.js} +1 -1
- package/chunks/{workspace-service-5DIZM4IZ.js → workspace-service-USATWO56.js} +1 -1
- package/chunks/{workspace-skills-status-DOOBVL5N.js → workspace-skills-status-M5JTSFDL.js} +1 -1
- package/chunks/{workspace-trust-reconciler-LOICVUVW.js → workspace-trust-reconciler-ZUZ2O5WC.js} +1 -1
- package/chunks/{write-file-EJNMAHQD.js → write-file-UMJVKE4S.js} +1 -1
- package/chunks/{zoom-image-S3OARMYP.js → zoom-image-76XYHQ3Z.js} +1 -1
- package/cli.js +2 -2
- package/execution-worker.js +1 -1
- package/export-transcript-document.js +1 -1
- package/gerege.mjs +64 -15
- package/locales/mn.js +2702 -3774
- package/package.json +3 -3
- package/chunks/mn-YH2OTBWJ.js +0 -8
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{MAX_EXTERNAL_RECORD_ID_LENGTH,MAX_EXTERNAL_RECORD_MENTION_IDS,MAX_EXTERNAL_RECORD_STEP_TITLE_LENGTH,MAX_EXTERNAL_RECORD_TEXT_LENGTH,canReuseNativeSession,isTerminalSessionAgentRunStatus,isValidSessionAgentsSessionId,listSessionAgentsSessionIds,readSessionAgents,trimTerminalRuns,writeSessionAgents}from"./chunk-3WQPUP5U.js";import{AGENT_SESSION_SOURCE_TYPE,sessionAgentNativeSessionId}from"./chunk-DHYCGKLG.js";import{extractErrorMessage}from"./chunk-CAPG7UVH.js";import{SessionNotFoundError}from"./chunk-VTZZXEWA.js";import{formatHostForAuthority,isLoopbackAddress,isLoopbackBind,isWildcardBind}from"./chunk-3SHHYK7S.js";import{require_express}from"./chunk-6SOKP7IN.js";import{AGENT_INPUT_CHAR_BUDGET,AGENT_MENTION_SUBTYPE,AGENT_MESSAGE_SUBTYPE,DEFAULT_AGENT_CHAIN_LIMIT,DEFAULT_AGENT_TOKEN_BUDGET,HOST_PROTOCOL_VERSION,MAX_AGENT_MESSAGE_DISPLAY_TEXT_CHARS,MAX_AGENT_MESSAGE_STEPS,MIN_PROGRAM_VERSIONS,SESSION_SQUADS_SCHEMA_VERSION,isBlankAgentText}from"./chunk-5WLKN3GD.js";import{AGENT_NAME_PATTERN,STORE_DIR_MODE,STORE_FILE_OPTIONS,SessionService,findAgentByName,formatAgentMentionModelText,formatAgentMessageModelText,getAgentsDir,isAgentAddressable,maxConcurrentRunsFor,readWorkspaceAgents,withAgentStoreTransaction}from"./chunk-Z5XENA4A.js";import{atomicWriteJSON}from"./chunk-BMHYEQTI.js";import{writeStderrLine}from"./chunk-M4ECEHLX.js";import{getErrorMessage,isNodeError}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();var MENTION_PATTERN=/(?<![A-Za-z0-9_.])@([\p{L}\p{N}][\p{L}\p{N}_-]{0,47})/gu;function agentForToken(agents,token){const exact=findAgentByName(agents,token);if(exact)return exact;const lowered=token.toLowerCase();let best;for(const agent of agents){if(!lowered.startsWith(agent.name.toLowerCase()))continue;const rest=token.slice(agent.name.length);if(/^[A-Za-z0-9_-]/.test(rest))continue;if(/^[\p{Script=Latin}\p{Nd}]/u.test(rest))continue;if(!best||agent.name.length>best.name.length)best=agent}return best}__name(agentForToken,"agentForToken");function nearMissOf(name,token){const a=name.toLowerCase();const b=token.toLowerCase();if(Math.abs(a.length-b.length)>2)return false;let prev=Array.from({length:b.length+1},(_,j)=>j);for(let i=1;i<=a.length;i++){const curr=[i];let rowMin=i;for(let j=1;j<=b.length;j++){const cost=a[i-1]===b[j-1]?0:1;curr[j]=Math.min(prev[j]+1,curr[j-1]+1,prev[j-1]+cost);rowMin=Math.min(rowMin,curr[j])}if(rowMin>2)return false;prev=curr}return prev[b.length]<=2}__name(nearMissOf,"nearMissOf");function parseMentions(text,agents){const ids=[];const unknown=[];const seenIds=new Set;const seenUnknown=new Set;for(const match of text.matchAll(MENTION_PATTERN)){const name=match[1];if(!name)continue;if(match.index!==void 0&&text[match.index+match[0].length]==="/"){continue}const agent=agentForToken(agents,name);if(!agent){if(!agents.some(candidate=>nearMissOf(candidate.name,name))){continue}const lowered=name.toLowerCase();if(!seenUnknown.has(lowered)){seenUnknown.add(lowered);unknown.push(name)}continue}if(seenIds.has(agent.id))continue;seenIds.add(agent.id);ids.push(agent.id)}return{ids,unknown}}__name(parseMentions,"parseMentions");function neutralizeMentions(text,agents,breaker){return text.replace(MENTION_PATTERN,(token,name,offset)=>text[offset+token.length]!=="/"&&agentForToken(agents,name)?`@${breaker}${token.slice(1)}`:token)}__name(neutralizeMentions,"neutralizeMentions");init_esbuild_shims();import*as fs from"node:fs/promises";import*as path from"node:path";import{randomUUID}from"node:crypto";var SQUADS_FILENAME="squads.json";var SQUAD_ID_PATTERN=/^sq_[A-Za-z0-9-]{1,64}$/;var MAX_DESCRIPTION_CHARS=2e3;var MAX_INSTRUCTIONS_CHARS=2e4;var MAX_ROLE_CHARS=200;var MAX_MEMBERS=32;var SquadStoreError=class extends Error{constructor(status,code,message){super(message);this.status=status;this.code=code;this.name="SquadStoreError"}static{__name(this,"SquadStoreError")}};function getSquadsFilePath(projectRoot){return path.join(getAgentsDir(projectRoot),SQUADS_FILENAME)}__name(getSquadsFilePath,"getSquadsFilePath");function isValidSquadId(value){return typeof value==="string"&&SQUAD_ID_PATTERN.test(value)}__name(isValidSquadId,"isValidSquadId");function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord,"isRecord");function isOptionalString(value){return value===void 0||typeof value==="string"}__name(isOptionalString,"isOptionalString");function isValidMember(value){return isRecord(value)&&typeof value["agentId"]==="string"&&isOptionalString(value["role"])}__name(isValidMember,"isValidMember");function isValidSquad(value){return isRecord(value)&&isValidSquadId(value["id"])&&typeof value["name"]==="string"&&AGENT_NAME_PATTERN.test(value["name"])&&isOptionalString(value["description"])&&isOptionalString(value["instructions"])&&typeof value["leaderAgentId"]==="string"&&Array.isArray(value["members"])&&value["members"].every(isValidMember)&&typeof value["createdAt"]==="number"&&typeof value["updatedAt"]==="number"&&(value["retiredAt"]===void 0||typeof value["retiredAt"]==="number")}__name(isValidSquad,"isValidSquad");function parseSquadsFile(value,filePath="<memory>"){if(!isRecord(value)){throw new Error(`Malformed squads file ${filePath}.`)}if(value["schemaVersion"]!==SESSION_SQUADS_SCHEMA_VERSION){throw new Error(`Unsupported squads schema version ${JSON.stringify(value["schemaVersion"])} in ${filePath}; this build supports version ${SESSION_SQUADS_SCHEMA_VERSION}.`)}const squads=value["squads"];if(!Array.isArray(squads)||!squads.every(isValidSquad)){throw new Error(`Malformed squads file ${filePath}.`)}return{schemaVersion:SESSION_SQUADS_SCHEMA_VERSION,squads}}__name(parseSquadsFile,"parseSquadsFile");async function readSquadsUnlocked(projectRoot){const filePath=getSquadsFilePath(projectRoot);let raw;try{raw=await fs.readFile(filePath,"utf-8")}catch(error){if(isNodeError(error)&&error.code==="ENOENT")return[];throw error}let parsed;try{parsed=JSON.parse(raw)}catch{throw new Error(`Malformed JSON in ${filePath} \u2014 fix or delete the file; refusing to treat it as empty.`)}return parseSquadsFile(parsed,filePath).squads}__name(readSquadsUnlocked,"readSquadsUnlocked");async function writeSquadsUnlocked(projectRoot,squads){const record={schemaVersion:SESSION_SQUADS_SCHEMA_VERSION,squads:[...squads]};parseSquadsFile(record);await fs.mkdir(getAgentsDir(projectRoot),{recursive:true,mode:STORE_DIR_MODE});await atomicWriteJSON(getSquadsFilePath(projectRoot),record,STORE_FILE_OPTIONS)}__name(writeSquadsUnlocked,"writeSquadsUnlocked");function squadLeaderIssue(squad,agents){const leader=agents.find(agent=>agent.id===squad.leaderAgentId);if(!leader)return"missing";if(leader.retiredAt!==void 0)return"retired";if(!isAgentAddressable(leader))return"disabled";return void 0}__name(squadLeaderIssue,"squadLeaderIssue");function pruneSquadMembers(squad,agents){const live=new Set(agents.filter(agent=>agent.retiredAt===void 0).map(agent=>agent.id));const members=squad.members.filter(member=>live.has(member.agentId));return members.length===squad.members.length?squad:{...squad,members}}__name(pruneSquadMembers,"pruneSquadMembers");function toSquadView(squad,agents){const pruned=pruneSquadMembers(squad,agents);const byId=new Map(agents.map(agent=>[agent.id,agent]));const leaderIssue=squadLeaderIssue(pruned,agents);const leaderName=byId.get(pruned.leaderAgentId)?.name;return{...pruned,...leaderName?{leaderName}:{},...leaderIssue?{leaderIssue}:{},members:pruned.members.map(member=>({...member,name:byId.get(member.agentId)?.name??member.agentId}))}}__name(toSquadView,"toSquadView");function nameTaken(name,agents,squads,exceptSquadId){const lowered=name.toLowerCase();return agents.some(agent=>agent.name.toLowerCase()===lowered)||squads.some(squad=>squad.id!==exceptSquadId&&squad.name.toLowerCase()===lowered)}__name(nameTaken,"nameTaken");function optionalText(value,field,max){if(value===void 0||value===null)return void 0;if(typeof value!=="string"||value.length>max){throw new SquadStoreError(400,`invalid_${field}`,`${field} must be a string of at most ${max} characters.`)}const trimmed=value.trim();return trimmed?trimmed:void 0}__name(optionalText,"optionalText");function validateName(value,agents,squads,exceptSquadId){if(typeof value!=="string"||!AGENT_NAME_PATTERN.test(value)){throw new SquadStoreError(400,"invalid_name",'A squad name is 1-48 letters, digits, "_" or "-", starting with a letter or digit (no "@" or ".").')}if(nameTaken(value,agents,squads,exceptSquadId)){throw new SquadStoreError(409,"name_taken",`"${value}" is already the name of an agent or a squad.`)}return value}__name(validateName,"validateName");function validateLeader(value,agents){if(typeof value!=="string"){throw new SquadStoreError(400,"invalid_leader","leaderAgentId is required.")}const issue=squadLeaderIssue({leaderAgentId:value},agents);if(issue){throw new SquadStoreError(400,"invalid_leader",issue==="missing"?"The leader must be an agent of this workspace.":`The leader agent is ${issue}; pick an enabled agent.`)}return value}__name(validateLeader,"validateLeader");function validateMembers(value,agents){if(!Array.isArray(value)||value.length>MAX_MEMBERS){throw new SquadStoreError(400,"invalid_members",`members must be a list of at most ${MAX_MEMBERS} agents.`)}const seen=new Set;return value.map(entry=>{const agentId=isRecord(entry)?entry["agentId"]:void 0;const agent=typeof agentId==="string"?agents.find(candidate=>candidate.id===agentId):void 0;if(!agent||agent.retiredAt!==void 0){throw new SquadStoreError(400,"invalid_members","Every member must be an agent of this workspace that is not retired.")}if(seen.has(agent.id)){throw new SquadStoreError(400,"invalid_members",`${agent.name} is listed twice.`)}seen.add(agent.id);const role=optionalText(entry["role"],"role",MAX_ROLE_CHARS);return{agentId:agent.id,...role?{role}:{}}})}__name(validateMembers,"validateMembers");async function mutateSquads(projectRoot,mutate){return withAgentStoreTransaction(projectRoot,async transaction=>{const agents=await transaction.readAgents();const current=(await readSquadsUnlocked(projectRoot)).map(squad=>pruneSquadMembers(squad,agents));const{squads,result}=mutate(current,agents);await writeSquadsUnlocked(projectRoot,squads);return{result,agents}})}__name(mutateSquads,"mutateSquads");async function updateWorkspaceAgentsWithSquads(projectRoot,mutate){return withAgentStoreTransaction(projectRoot,async transaction=>{const squads=await readSquadsUnlocked(projectRoot);const next=mutate(await transaction.readAgents(),squads);await transaction.writeAgents(next);return next})}__name(updateWorkspaceAgentsWithSquads,"updateWorkspaceAgentsWithSquads");async function readSquads(projectRoot){return withAgentStoreTransaction(projectRoot,async transaction=>{const agents=await transaction.readAgents();return(await readSquadsUnlocked(projectRoot)).map(squad=>pruneSquadMembers(squad,agents))})}__name(readSquads,"readSquads");async function listSquadViews(projectRoot){return withAgentStoreTransaction(projectRoot,async transaction=>{const agents=await transaction.readAgents();return(await readSquadsUnlocked(projectRoot)).map(squad=>toSquadView(squad,agents))})}__name(listSquadViews,"listSquadViews");async function createSquad(projectRoot,input,now=Date.now()){const{result,agents}=await mutateSquads(projectRoot,(squads,roster)=>{const name=validateName(input.name,roster,squads);const leaderAgentId=validateLeader(input.leaderAgentId,roster);const members=validateMembers(input.members??[],roster);const description=optionalText(input.description,"description",MAX_DESCRIPTION_CHARS);const instructions=optionalText(input.instructions,"instructions",MAX_INSTRUCTIONS_CHARS);const squad={id:`sq_${randomUUID()}`,name,...description?{description}:{},...instructions?{instructions}:{},leaderAgentId,members,createdAt:now,updatedAt:now};return{squads:[...squads,squad],result:squad}});return toSquadView(result,agents)}__name(createSquad,"createSquad");async function updateSquad(projectRoot,squadId,patch,now=Date.now()){const{result,agents}=await mutateSquads(projectRoot,(squads,roster)=>{const existing=squads.find(squad=>squad.id===squadId);if(!existing){throw new SquadStoreError(404,"squad_not_found","No such squad.")}if(existing.retiredAt!==void 0){throw new SquadStoreError(409,"squad_retired","This squad is retired.")}const next={...existing,updatedAt:now};if(patch.name!==void 0&&patch.name!==existing.name){next.name=validateName(patch.name,roster,squads,squadId)}if(patch.leaderAgentId!==void 0){next.leaderAgentId=validateLeader(patch.leaderAgentId,roster)}if(patch.members!==void 0){next.members=validateMembers(patch.members,roster)}for(const[field,max]of[["description",MAX_DESCRIPTION_CHARS],["instructions",MAX_INSTRUCTIONS_CHARS]]){if(patch[field]===void 0)continue;const value=optionalText(patch[field],field,max);if(value)next[field]=value;else delete next[field]}return{squads:squads.map(squad=>squad.id===squadId?next:squad),result:next}});return toSquadView(result,agents)}__name(updateSquad,"updateSquad");async function retireSquad(projectRoot,squadId,now=Date.now()){const{result,agents}=await mutateSquads(projectRoot,squads=>{const existing=squads.find(squad=>squad.id===squadId);if(!existing){throw new SquadStoreError(404,"squad_not_found","No such squad.")}if(existing.retiredAt!==void 0){return{squads,result:existing}}const retired={...existing,retiredAt:now,updatedAt:now};return{squads:squads.map(squad=>squad.id===squadId?retired:squad),result:retired}});return toSquadView(result,agents)}__name(retireSquad,"retireSquad");function resolveMentionTargets(text,roster,authorAgentId){const parsed=parseMentions(text,roster);const byId=new Map(roster.map(agent=>[agent.id,agent]));const agents=[];const unavailable=[];let selfMentioned=false;for(const id of parsed.ids){const agent=byId.get(id);if(!agent)continue;if(authorAgentId!==void 0&&id===authorAgentId){selfMentioned=true;continue}if(isAgentAddressable(agent))agents.push(agent);else unavailable.push(agent)}return{agents,unavailable,unknown:parsed.unknown,selfMentioned}}__name(resolveMentionTargets,"resolveMentionTargets");var SQUAD_TOKEN_ID_PREFIX="squad\0";function resolveMentionTargetsWithSquads(text,roster,squads,authorAgentId){const squadEntries=squads.map(squad=>({id:`${SQUAD_TOKEN_ID_PREFIX}${squad.id}`,name:squad.name,createdAt:squad.createdAt}));const parsed=parseMentions(text,[...roster,...squadEntries]);const picked=new Set(parsed.ids);const agentTargets=resolveMentionTargets(text,roster.filter(agent=>picked.has(agent.id)),authorAgentId);const byId=new Map(squads.map(squad=>[squad.id,squad]));const engaged=[];const unavailableSquads=[];for(const id of parsed.ids){if(!id.startsWith(SQUAD_TOKEN_ID_PREFIX))continue;const squad=byId.get(id.slice(SQUAD_TOKEN_ID_PREFIX.length));if(!squad)continue;if(squad.retiredAt!==void 0){unavailableSquads.push({squad,reason:"retired"});continue}const issue=squadLeaderIssue(squad,roster);if(issue){unavailableSquads.push({squad,reason:`leader_${issue}`});continue}engaged.push(squad)}return{...agentTargets,unknown:parsed.unknown,squads:engaged,unavailableSquads}}__name(resolveMentionTargetsWithSquads,"resolveMentionTargetsWithSquads");function nextChainDepth(trigger){return trigger.kind==="human"?0:Math.max(0,trigger.chainDepth)+1}__name(nextChainDepth,"nextChainDepth");function isWithinChainLimit(chainDepth,limit){if(!Number.isInteger(limit)||limit<=0)return true;return chainDepth<=limit}__name(isWithinChainLimit,"isWithinChainLimit");function normalizeAgentChainLimit(raw){return typeof raw==="number"&&Number.isInteger(raw)&&raw>=0?raw:DEFAULT_AGENT_CHAIN_LIMIT}__name(normalizeAgentChainLimit,"normalizeAgentChainLimit");function coalesceChainDepth(current,incoming){return Math.min(current,incoming)}__name(coalesceChainDepth,"coalesceChainDepth");function normalizeAgentTokenBudget(raw){return typeof raw==="number"&&Number.isFinite(raw)&&raw>=0?Math.floor(raw):DEFAULT_AGENT_TOKEN_BUDGET}__name(normalizeAgentTokenBudget,"normalizeAgentTokenBudget");function isWithinTokenBudget(spent,budget){return budget===0||spent<budget}__name(isWithinTokenBudget,"isWithinTokenBudget");init_esbuild_shims();init_esbuild_shims();import{execFile}from"node:child_process";import{accessSync,constants,statSync}from"node:fs";import{delimiter,isAbsolute,join as join3,resolve}from"node:path";init_esbuild_shims();import{mkdtemp,rm,writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{join as join2}from"node:path";init_esbuild_shims();import{execFileSync,spawn as nodeSpawn}from"node:child_process";function quoteForCmd(arg){if(arg==="")return'""';if(!/[\s"&|<>^%!()]/.test(arg))return arg;return`"${arg.replace(/"/g,'""')}"`}__name(quoteForCmd,"quoteForCmd");var spawnAgentProcess=__name((command,args,options)=>{const isWindowsShim=process.platform==="win32"&&/\.(cmd|bat)$/i.test(command);if(isWindowsShim){return nodeSpawn([command,...args].map(quoteForCmd).join(" "),[],{cwd:options.cwd,env:options.env,stdio:["pipe","pipe","pipe"],shell:true,windowsHide:true})}return nodeSpawn(command,[...args],{cwd:options.cwd,env:options.env,stdio:["pipe","pipe","pipe"],detached:process.platform!=="win32",windowsHide:true})},"spawnAgentProcess");function killAgentProcessTree(child,signal){const pid=child.pid;if(!pid){try{child.kill(signal)}catch{}return}if(process.platform==="win32"){try{execFileSync("taskkill",["/pid",String(pid),"/T","/F"],{stdio:"ignore",windowsHide:true})}catch{}return}try{process.kill(-pid,signal)}catch{try{child.kill(signal)}catch{}}}__name(killAgentProcessTree,"killAgentProcessTree");function hasExited(child){return child.exitCode!==null||child.signalCode!==null}__name(hasExited,"hasExited");function waitForExit(child){if(hasExited(child))return Promise.resolve();return new Promise(resolve2=>{child.once("exit",()=>resolve2())})}__name(waitForExit,"waitForExit");async function terminateAgentProcess(child,graceMs){try{child.stdin?.end()}catch{}if(hasExited(child))return;killAgentProcessTree(child,"SIGTERM");let timer;const exited=await Promise.race([waitForExit(child).then(()=>true),new Promise(resolve2=>{timer=setTimeout(()=>resolve2(false),graceMs);timer.unref?.()})]);if(timer)clearTimeout(timer);if(!exited)killAgentProcessTree(child,"SIGKILL")}__name(terminateAgentProcess,"terminateAgentProcess");var LineTooLongError=class extends Error{constructor(limit){super(`A line from the agent program exceeded ${limit} bytes.`);this.limit=limit;this.name="LineTooLongError"}static{__name(this,"LineTooLongError")}};var DEFAULT_MAX_LINE_BYTES=64*1024*1024;function readJsonLines(stream,onLine,maxLineBytes=DEFAULT_MAX_LINE_BYTES){return new Promise((resolve2,reject)=>{let pending=[];let pendingBytes=0;let failed=false;const emit=__name(buffer=>{const line=buffer.toString("utf8").trim();if(line)onLine(line)},"emit");const onData=__name(chunk=>{if(failed)return;let data=typeof chunk==="string"?Buffer.from(chunk):chunk;for(;;){const newline=data.indexOf(10);if(newline===-1)break;const head=data.subarray(0,newline);if(pendingBytes+head.length>maxLineBytes){fail();return}pending.push(head);const line=Buffer.concat(pending);pending=[];pendingBytes=0;try{emit(line)}catch{}data=data.subarray(newline+1)}if(data.length>0){pendingBytes+=data.length;if(pendingBytes>maxLineBytes){fail();return}pending.push(data)}},"onData");const fail=__name(()=>{failed=true;pending=[];stream.off("data",onData);stream.resume();reject(new LineTooLongError(maxLineBytes))},"fail");stream.on("data",onData);let ended=false;const finish=__name(()=>{if(failed||ended)return;ended=true;if(pendingBytes>0){try{emit(Buffer.concat(pending))}catch{}}resolve2()},"finish");stream.once("end",finish);stream.once("close",finish);stream.once("error",error=>{if(!failed)reject(error)})})}__name(readJsonLines,"readJsonLines");var TailBuffer=class{constructor(limit=8192){this.limit=limit}static{__name(this,"TailBuffer")}text="";append(chunk){this.text=(this.text+chunk.toString()).slice(-this.limit)}toString(){return this.text}};var SCRUBBED_ENV_KEYS=new Set(["CLAUDECODE","CLAUDE_CODE_ENTRYPOINT","CLAUDE_CODE_EXECPATH","CLAUDE_CODE_SESSION_ID","CLAUDE_CODE_SSE_PORT"]);function scrubAgentEnv(env,extra){const out={};for(const[key,value]of Object.entries(env)){if(value===void 0)continue;if(SCRUBBED_ENV_KEYS.has(key)||key.startsWith("CLAUDECODE_"))continue;if(key==="QWEN_SESSION_SEND_TOKEN")continue;out[key]=value}return{...out,...extra??{}}}__name(scrubAgentEnv,"scrubAgentEnv");function previewJson(value,max){if(value===void 0)return void 0;try{const text=typeof value==="string"?value:JSON.stringify(value);if(text===void 0)return void 0;return text.length>max?`${text.slice(0,max)}\u2026`:text}catch{return void 0}}__name(previewJson,"previewJson");var CLAUDE_PATH_ENV="QWEN_AGENT_CLAUDE_PATH";var SESSION_SEND_MCP_SERVER_NAME="qwen-session";var DEFAULT_TERMINATE_GRACE_MS=5e3;var STDOUT_DRAIN_GRACE_MS=2e3;var MAX_INPUT_PREVIEW_CHARS=2e3;var MAX_TITLE_SUMMARY_CHARS=160;var MAX_STEP_TITLE_CHARS=200;var RESUME_REJECTED_PHRASES=["no conversation found","no saved session found","\u5DF2\u7ED1\u5B9A\u53E6\u5916","bound to another account","bound to a different account"];var PROMPT_TOO_LONG="prompt_too_long";function buildClaudeArgs(options){const args=["-p","--output-format","stream-json","--input-format","stream-json","--verbose","--permission-mode","default","--permission-prompt-tool","stdio","--disallowedTools","AskUserQuestion"];if(options.model)args.push("--model",options.model);if(options.resumeSessionId){args.push("--resume",options.resumeSessionId)}else if(options.instructions){args.push("--append-system-prompt",options.instructions)}if(options.mcpConfigPath){args.push("--mcp-config",options.mcpConfigPath)}return args}__name(buildClaudeArgs,"buildClaudeArgs");function buildClaudeUserMessage(prompt){return`${JSON.stringify({type:"user",message:{role:"user",content:[{type:"text",text:prompt}]}})}
|
|
3
|
+
import{MAX_EXTERNAL_RECORD_ID_LENGTH,MAX_EXTERNAL_RECORD_MENTION_IDS,MAX_EXTERNAL_RECORD_STEP_TITLE_LENGTH,MAX_EXTERNAL_RECORD_TEXT_LENGTH,canReuseNativeSession,isTerminalSessionAgentRunStatus,isValidSessionAgentsSessionId,listSessionAgentsSessionIds,readSessionAgents,trimTerminalRuns,writeSessionAgents}from"./chunk-WMLYHZZX.js";import{AGENT_SESSION_SOURCE_TYPE,sessionAgentNativeSessionId}from"./chunk-DHYCGKLG.js";import{extractErrorMessage}from"./chunk-HVP4UF2Q.js";import{SessionNotFoundError}from"./chunk-VTZZXEWA.js";import{formatHostForAuthority,isLoopbackAddress,isLoopbackBind,isWildcardBind}from"./chunk-3SHHYK7S.js";import{require_express}from"./chunk-6SOKP7IN.js";import{AGENT_INPUT_CHAR_BUDGET,AGENT_MENTION_SUBTYPE,AGENT_MESSAGE_SUBTYPE,DEFAULT_AGENT_CHAIN_LIMIT,DEFAULT_AGENT_TOKEN_BUDGET,HOST_PROTOCOL_VERSION,MAX_AGENT_MESSAGE_DISPLAY_TEXT_CHARS,MAX_AGENT_MESSAGE_STEPS,MIN_PROGRAM_VERSIONS,SESSION_SQUADS_SCHEMA_VERSION,isBlankAgentText}from"./chunk-CK3OKTTL.js";import{AGENT_NAME_PATTERN,STORE_DIR_MODE,STORE_FILE_OPTIONS,SessionService,findAgentByName,formatAgentMentionModelText,formatAgentMessageModelText,getAgentsDir,isAgentAddressable,maxConcurrentRunsFor,readWorkspaceAgents,withAgentStoreTransaction}from"./chunk-T3CQ72HC.js";import{atomicWriteJSON}from"./chunk-BMHYEQTI.js";import{writeStderrLine}from"./chunk-M4ECEHLX.js";import{getErrorMessage,isNodeError}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();var MENTION_PATTERN=/(?<![A-Za-z0-9_.])@([\p{L}\p{N}][\p{L}\p{N}_-]{0,47})/gu;function agentForToken(agents,token){const exact=findAgentByName(agents,token);if(exact)return exact;const lowered=token.toLowerCase();let best;for(const agent of agents){if(!lowered.startsWith(agent.name.toLowerCase()))continue;const rest=token.slice(agent.name.length);if(/^[A-Za-z0-9_-]/.test(rest))continue;if(/^[\p{Script=Latin}\p{Nd}]/u.test(rest))continue;if(!best||agent.name.length>best.name.length)best=agent}return best}__name(agentForToken,"agentForToken");function nearMissOf(name,token){const a=name.toLowerCase();const b=token.toLowerCase();if(Math.abs(a.length-b.length)>2)return false;let prev=Array.from({length:b.length+1},(_,j)=>j);for(let i=1;i<=a.length;i++){const curr=[i];let rowMin=i;for(let j=1;j<=b.length;j++){const cost=a[i-1]===b[j-1]?0:1;curr[j]=Math.min(prev[j]+1,curr[j-1]+1,prev[j-1]+cost);rowMin=Math.min(rowMin,curr[j])}if(rowMin>2)return false;prev=curr}return prev[b.length]<=2}__name(nearMissOf,"nearMissOf");function parseMentions(text,agents){const ids=[];const unknown=[];const seenIds=new Set;const seenUnknown=new Set;for(const match of text.matchAll(MENTION_PATTERN)){const name=match[1];if(!name)continue;if(match.index!==void 0&&text[match.index+match[0].length]==="/"){continue}const agent=agentForToken(agents,name);if(!agent){if(!agents.some(candidate=>nearMissOf(candidate.name,name))){continue}const lowered=name.toLowerCase();if(!seenUnknown.has(lowered)){seenUnknown.add(lowered);unknown.push(name)}continue}if(seenIds.has(agent.id))continue;seenIds.add(agent.id);ids.push(agent.id)}return{ids,unknown}}__name(parseMentions,"parseMentions");function neutralizeMentions(text,agents,breaker){return text.replace(MENTION_PATTERN,(token,name,offset)=>text[offset+token.length]!=="/"&&agentForToken(agents,name)?`@${breaker}${token.slice(1)}`:token)}__name(neutralizeMentions,"neutralizeMentions");init_esbuild_shims();import*as fs from"node:fs/promises";import*as path from"node:path";import{randomUUID}from"node:crypto";var SQUADS_FILENAME="squads.json";var SQUAD_ID_PATTERN=/^sq_[A-Za-z0-9-]{1,64}$/;var MAX_DESCRIPTION_CHARS=2e3;var MAX_INSTRUCTIONS_CHARS=2e4;var MAX_ROLE_CHARS=200;var MAX_MEMBERS=32;var SquadStoreError=class extends Error{constructor(status,code,message){super(message);this.status=status;this.code=code;this.name="SquadStoreError"}static{__name(this,"SquadStoreError")}};function getSquadsFilePath(projectRoot){return path.join(getAgentsDir(projectRoot),SQUADS_FILENAME)}__name(getSquadsFilePath,"getSquadsFilePath");function isValidSquadId(value){return typeof value==="string"&&SQUAD_ID_PATTERN.test(value)}__name(isValidSquadId,"isValidSquadId");function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord,"isRecord");function isOptionalString(value){return value===void 0||typeof value==="string"}__name(isOptionalString,"isOptionalString");function isValidMember(value){return isRecord(value)&&typeof value["agentId"]==="string"&&isOptionalString(value["role"])}__name(isValidMember,"isValidMember");function isValidSquad(value){return isRecord(value)&&isValidSquadId(value["id"])&&typeof value["name"]==="string"&&AGENT_NAME_PATTERN.test(value["name"])&&isOptionalString(value["description"])&&isOptionalString(value["instructions"])&&typeof value["leaderAgentId"]==="string"&&Array.isArray(value["members"])&&value["members"].every(isValidMember)&&typeof value["createdAt"]==="number"&&typeof value["updatedAt"]==="number"&&(value["retiredAt"]===void 0||typeof value["retiredAt"]==="number")}__name(isValidSquad,"isValidSquad");function parseSquadsFile(value,filePath="<memory>"){if(!isRecord(value)){throw new Error(`Malformed squads file ${filePath}.`)}if(value["schemaVersion"]!==SESSION_SQUADS_SCHEMA_VERSION){throw new Error(`Unsupported squads schema version ${JSON.stringify(value["schemaVersion"])} in ${filePath}; this build supports version ${SESSION_SQUADS_SCHEMA_VERSION}.`)}const squads=value["squads"];if(!Array.isArray(squads)||!squads.every(isValidSquad)){throw new Error(`Malformed squads file ${filePath}.`)}return{schemaVersion:SESSION_SQUADS_SCHEMA_VERSION,squads}}__name(parseSquadsFile,"parseSquadsFile");async function readSquadsUnlocked(projectRoot){const filePath=getSquadsFilePath(projectRoot);let raw;try{raw=await fs.readFile(filePath,"utf-8")}catch(error){if(isNodeError(error)&&error.code==="ENOENT")return[];throw error}let parsed;try{parsed=JSON.parse(raw)}catch{throw new Error(`Malformed JSON in ${filePath} \u2014 fix or delete the file; refusing to treat it as empty.`)}return parseSquadsFile(parsed,filePath).squads}__name(readSquadsUnlocked,"readSquadsUnlocked");async function writeSquadsUnlocked(projectRoot,squads){const record={schemaVersion:SESSION_SQUADS_SCHEMA_VERSION,squads:[...squads]};parseSquadsFile(record);await fs.mkdir(getAgentsDir(projectRoot),{recursive:true,mode:STORE_DIR_MODE});await atomicWriteJSON(getSquadsFilePath(projectRoot),record,STORE_FILE_OPTIONS)}__name(writeSquadsUnlocked,"writeSquadsUnlocked");function squadLeaderIssue(squad,agents){const leader=agents.find(agent=>agent.id===squad.leaderAgentId);if(!leader)return"missing";if(leader.retiredAt!==void 0)return"retired";if(!isAgentAddressable(leader))return"disabled";return void 0}__name(squadLeaderIssue,"squadLeaderIssue");function pruneSquadMembers(squad,agents){const live=new Set(agents.filter(agent=>agent.retiredAt===void 0).map(agent=>agent.id));const members=squad.members.filter(member=>live.has(member.agentId));return members.length===squad.members.length?squad:{...squad,members}}__name(pruneSquadMembers,"pruneSquadMembers");function toSquadView(squad,agents){const pruned=pruneSquadMembers(squad,agents);const byId=new Map(agents.map(agent=>[agent.id,agent]));const leaderIssue=squadLeaderIssue(pruned,agents);const leaderName=byId.get(pruned.leaderAgentId)?.name;return{...pruned,...leaderName?{leaderName}:{},...leaderIssue?{leaderIssue}:{},members:pruned.members.map(member=>({...member,name:byId.get(member.agentId)?.name??member.agentId}))}}__name(toSquadView,"toSquadView");function nameTaken(name,agents,squads,exceptSquadId){const lowered=name.toLowerCase();return agents.some(agent=>agent.name.toLowerCase()===lowered)||squads.some(squad=>squad.id!==exceptSquadId&&squad.name.toLowerCase()===lowered)}__name(nameTaken,"nameTaken");function optionalText(value,field,max){if(value===void 0||value===null)return void 0;if(typeof value!=="string"||value.length>max){throw new SquadStoreError(400,`invalid_${field}`,`${field} must be a string of at most ${max} characters.`)}const trimmed=value.trim();return trimmed?trimmed:void 0}__name(optionalText,"optionalText");function validateName(value,agents,squads,exceptSquadId){if(typeof value!=="string"||!AGENT_NAME_PATTERN.test(value)){throw new SquadStoreError(400,"invalid_name",'A squad name is 1-48 letters, digits, "_" or "-", starting with a letter or digit (no "@" or ".").')}if(nameTaken(value,agents,squads,exceptSquadId)){throw new SquadStoreError(409,"name_taken",`"${value}" is already the name of an agent or a squad.`)}return value}__name(validateName,"validateName");function validateLeader(value,agents){if(typeof value!=="string"){throw new SquadStoreError(400,"invalid_leader","leaderAgentId is required.")}const issue=squadLeaderIssue({leaderAgentId:value},agents);if(issue){throw new SquadStoreError(400,"invalid_leader",issue==="missing"?"The leader must be an agent of this workspace.":`The leader agent is ${issue}; pick an enabled agent.`)}return value}__name(validateLeader,"validateLeader");function validateMembers(value,agents){if(!Array.isArray(value)||value.length>MAX_MEMBERS){throw new SquadStoreError(400,"invalid_members",`members must be a list of at most ${MAX_MEMBERS} agents.`)}const seen=new Set;return value.map(entry=>{const agentId=isRecord(entry)?entry["agentId"]:void 0;const agent=typeof agentId==="string"?agents.find(candidate=>candidate.id===agentId):void 0;if(!agent||agent.retiredAt!==void 0){throw new SquadStoreError(400,"invalid_members","Every member must be an agent of this workspace that is not retired.")}if(seen.has(agent.id)){throw new SquadStoreError(400,"invalid_members",`${agent.name} is listed twice.`)}seen.add(agent.id);const role=optionalText(entry["role"],"role",MAX_ROLE_CHARS);return{agentId:agent.id,...role?{role}:{}}})}__name(validateMembers,"validateMembers");async function mutateSquads(projectRoot,mutate){return withAgentStoreTransaction(projectRoot,async transaction=>{const agents=await transaction.readAgents();const current=(await readSquadsUnlocked(projectRoot)).map(squad=>pruneSquadMembers(squad,agents));const{squads,result}=mutate(current,agents);await writeSquadsUnlocked(projectRoot,squads);return{result,agents}})}__name(mutateSquads,"mutateSquads");async function updateWorkspaceAgentsWithSquads(projectRoot,mutate){return withAgentStoreTransaction(projectRoot,async transaction=>{const squads=await readSquadsUnlocked(projectRoot);const next=mutate(await transaction.readAgents(),squads);await transaction.writeAgents(next);return next})}__name(updateWorkspaceAgentsWithSquads,"updateWorkspaceAgentsWithSquads");async function readSquads(projectRoot){return withAgentStoreTransaction(projectRoot,async transaction=>{const agents=await transaction.readAgents();return(await readSquadsUnlocked(projectRoot)).map(squad=>pruneSquadMembers(squad,agents))})}__name(readSquads,"readSquads");async function listSquadViews(projectRoot){return withAgentStoreTransaction(projectRoot,async transaction=>{const agents=await transaction.readAgents();return(await readSquadsUnlocked(projectRoot)).map(squad=>toSquadView(squad,agents))})}__name(listSquadViews,"listSquadViews");async function createSquad(projectRoot,input,now=Date.now()){const{result,agents}=await mutateSquads(projectRoot,(squads,roster)=>{const name=validateName(input.name,roster,squads);const leaderAgentId=validateLeader(input.leaderAgentId,roster);const members=validateMembers(input.members??[],roster);const description=optionalText(input.description,"description",MAX_DESCRIPTION_CHARS);const instructions=optionalText(input.instructions,"instructions",MAX_INSTRUCTIONS_CHARS);const squad={id:`sq_${randomUUID()}`,name,...description?{description}:{},...instructions?{instructions}:{},leaderAgentId,members,createdAt:now,updatedAt:now};return{squads:[...squads,squad],result:squad}});return toSquadView(result,agents)}__name(createSquad,"createSquad");async function updateSquad(projectRoot,squadId,patch,now=Date.now()){const{result,agents}=await mutateSquads(projectRoot,(squads,roster)=>{const existing=squads.find(squad=>squad.id===squadId);if(!existing){throw new SquadStoreError(404,"squad_not_found","No such squad.")}if(existing.retiredAt!==void 0){throw new SquadStoreError(409,"squad_retired","This squad is retired.")}const next={...existing,updatedAt:now};if(patch.name!==void 0&&patch.name!==existing.name){next.name=validateName(patch.name,roster,squads,squadId)}if(patch.leaderAgentId!==void 0){next.leaderAgentId=validateLeader(patch.leaderAgentId,roster)}if(patch.members!==void 0){next.members=validateMembers(patch.members,roster)}for(const[field,max]of[["description",MAX_DESCRIPTION_CHARS],["instructions",MAX_INSTRUCTIONS_CHARS]]){if(patch[field]===void 0)continue;const value=optionalText(patch[field],field,max);if(value)next[field]=value;else delete next[field]}return{squads:squads.map(squad=>squad.id===squadId?next:squad),result:next}});return toSquadView(result,agents)}__name(updateSquad,"updateSquad");async function retireSquad(projectRoot,squadId,now=Date.now()){const{result,agents}=await mutateSquads(projectRoot,squads=>{const existing=squads.find(squad=>squad.id===squadId);if(!existing){throw new SquadStoreError(404,"squad_not_found","No such squad.")}if(existing.retiredAt!==void 0){return{squads,result:existing}}const retired={...existing,retiredAt:now,updatedAt:now};return{squads:squads.map(squad=>squad.id===squadId?retired:squad),result:retired}});return toSquadView(result,agents)}__name(retireSquad,"retireSquad");function resolveMentionTargets(text,roster,authorAgentId){const parsed=parseMentions(text,roster);const byId=new Map(roster.map(agent=>[agent.id,agent]));const agents=[];const unavailable=[];let selfMentioned=false;for(const id of parsed.ids){const agent=byId.get(id);if(!agent)continue;if(authorAgentId!==void 0&&id===authorAgentId){selfMentioned=true;continue}if(isAgentAddressable(agent))agents.push(agent);else unavailable.push(agent)}return{agents,unavailable,unknown:parsed.unknown,selfMentioned}}__name(resolveMentionTargets,"resolveMentionTargets");var SQUAD_TOKEN_ID_PREFIX="squad\0";function resolveMentionTargetsWithSquads(text,roster,squads,authorAgentId){const squadEntries=squads.map(squad=>({id:`${SQUAD_TOKEN_ID_PREFIX}${squad.id}`,name:squad.name,createdAt:squad.createdAt}));const parsed=parseMentions(text,[...roster,...squadEntries]);const picked=new Set(parsed.ids);const agentTargets=resolveMentionTargets(text,roster.filter(agent=>picked.has(agent.id)),authorAgentId);const byId=new Map(squads.map(squad=>[squad.id,squad]));const engaged=[];const unavailableSquads=[];for(const id of parsed.ids){if(!id.startsWith(SQUAD_TOKEN_ID_PREFIX))continue;const squad=byId.get(id.slice(SQUAD_TOKEN_ID_PREFIX.length));if(!squad)continue;if(squad.retiredAt!==void 0){unavailableSquads.push({squad,reason:"retired"});continue}const issue=squadLeaderIssue(squad,roster);if(issue){unavailableSquads.push({squad,reason:`leader_${issue}`});continue}engaged.push(squad)}return{...agentTargets,unknown:parsed.unknown,squads:engaged,unavailableSquads}}__name(resolveMentionTargetsWithSquads,"resolveMentionTargetsWithSquads");function nextChainDepth(trigger){return trigger.kind==="human"?0:Math.max(0,trigger.chainDepth)+1}__name(nextChainDepth,"nextChainDepth");function isWithinChainLimit(chainDepth,limit){if(!Number.isInteger(limit)||limit<=0)return true;return chainDepth<=limit}__name(isWithinChainLimit,"isWithinChainLimit");function normalizeAgentChainLimit(raw){return typeof raw==="number"&&Number.isInteger(raw)&&raw>=0?raw:DEFAULT_AGENT_CHAIN_LIMIT}__name(normalizeAgentChainLimit,"normalizeAgentChainLimit");function coalesceChainDepth(current,incoming){return Math.min(current,incoming)}__name(coalesceChainDepth,"coalesceChainDepth");function normalizeAgentTokenBudget(raw){return typeof raw==="number"&&Number.isFinite(raw)&&raw>=0?Math.floor(raw):DEFAULT_AGENT_TOKEN_BUDGET}__name(normalizeAgentTokenBudget,"normalizeAgentTokenBudget");function isWithinTokenBudget(spent,budget){return budget===0||spent<budget}__name(isWithinTokenBudget,"isWithinTokenBudget");init_esbuild_shims();init_esbuild_shims();import{execFile}from"node:child_process";import{accessSync,constants,statSync}from"node:fs";import{delimiter,isAbsolute,join as join3,resolve}from"node:path";init_esbuild_shims();import{mkdtemp,rm,writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{join as join2}from"node:path";init_esbuild_shims();import{execFileSync,spawn as nodeSpawn}from"node:child_process";function quoteForCmd(arg){if(arg==="")return'""';if(!/[\s"&|<>^%!()]/.test(arg))return arg;return`"${arg.replace(/"/g,'""')}"`}__name(quoteForCmd,"quoteForCmd");var spawnAgentProcess=__name((command,args,options)=>{const isWindowsShim=process.platform==="win32"&&/\.(cmd|bat)$/i.test(command);if(isWindowsShim){return nodeSpawn([command,...args].map(quoteForCmd).join(" "),[],{cwd:options.cwd,env:options.env,stdio:["pipe","pipe","pipe"],shell:true,windowsHide:true})}return nodeSpawn(command,[...args],{cwd:options.cwd,env:options.env,stdio:["pipe","pipe","pipe"],detached:process.platform!=="win32",windowsHide:true})},"spawnAgentProcess");function killAgentProcessTree(child,signal){const pid=child.pid;if(!pid){try{child.kill(signal)}catch{}return}if(process.platform==="win32"){try{execFileSync("taskkill",["/pid",String(pid),"/T","/F"],{stdio:"ignore",windowsHide:true})}catch{}return}try{process.kill(-pid,signal)}catch{try{child.kill(signal)}catch{}}}__name(killAgentProcessTree,"killAgentProcessTree");function hasExited(child){return child.exitCode!==null||child.signalCode!==null}__name(hasExited,"hasExited");function waitForExit(child){if(hasExited(child))return Promise.resolve();return new Promise(resolve2=>{child.once("exit",()=>resolve2())})}__name(waitForExit,"waitForExit");async function terminateAgentProcess(child,graceMs){try{child.stdin?.end()}catch{}if(hasExited(child))return;killAgentProcessTree(child,"SIGTERM");let timer;const exited=await Promise.race([waitForExit(child).then(()=>true),new Promise(resolve2=>{timer=setTimeout(()=>resolve2(false),graceMs);timer.unref?.()})]);if(timer)clearTimeout(timer);if(!exited)killAgentProcessTree(child,"SIGKILL")}__name(terminateAgentProcess,"terminateAgentProcess");var LineTooLongError=class extends Error{constructor(limit){super(`A line from the agent program exceeded ${limit} bytes.`);this.limit=limit;this.name="LineTooLongError"}static{__name(this,"LineTooLongError")}};var DEFAULT_MAX_LINE_BYTES=64*1024*1024;function readJsonLines(stream,onLine,maxLineBytes=DEFAULT_MAX_LINE_BYTES){return new Promise((resolve2,reject)=>{let pending=[];let pendingBytes=0;let failed=false;const emit=__name(buffer=>{const line=buffer.toString("utf8").trim();if(line)onLine(line)},"emit");const onData=__name(chunk=>{if(failed)return;let data=typeof chunk==="string"?Buffer.from(chunk):chunk;for(;;){const newline=data.indexOf(10);if(newline===-1)break;const head=data.subarray(0,newline);if(pendingBytes+head.length>maxLineBytes){fail();return}pending.push(head);const line=Buffer.concat(pending);pending=[];pendingBytes=0;try{emit(line)}catch{}data=data.subarray(newline+1)}if(data.length>0){pendingBytes+=data.length;if(pendingBytes>maxLineBytes){fail();return}pending.push(data)}},"onData");const fail=__name(()=>{failed=true;pending=[];stream.off("data",onData);stream.resume();reject(new LineTooLongError(maxLineBytes))},"fail");stream.on("data",onData);let ended=false;const finish=__name(()=>{if(failed||ended)return;ended=true;if(pendingBytes>0){try{emit(Buffer.concat(pending))}catch{}}resolve2()},"finish");stream.once("end",finish);stream.once("close",finish);stream.once("error",error=>{if(!failed)reject(error)})})}__name(readJsonLines,"readJsonLines");var TailBuffer=class{constructor(limit=8192){this.limit=limit}static{__name(this,"TailBuffer")}text="";append(chunk){this.text=(this.text+chunk.toString()).slice(-this.limit)}toString(){return this.text}};var SCRUBBED_ENV_KEYS=new Set(["CLAUDECODE","CLAUDE_CODE_ENTRYPOINT","CLAUDE_CODE_EXECPATH","CLAUDE_CODE_SESSION_ID","CLAUDE_CODE_SSE_PORT"]);function scrubAgentEnv(env,extra){const out={};for(const[key,value]of Object.entries(env)){if(value===void 0)continue;if(SCRUBBED_ENV_KEYS.has(key)||key.startsWith("CLAUDECODE_"))continue;if(key==="QWEN_SESSION_SEND_TOKEN")continue;out[key]=value}return{...out,...extra??{}}}__name(scrubAgentEnv,"scrubAgentEnv");function previewJson(value,max){if(value===void 0)return void 0;try{const text=typeof value==="string"?value:JSON.stringify(value);if(text===void 0)return void 0;return text.length>max?`${text.slice(0,max)}\u2026`:text}catch{return void 0}}__name(previewJson,"previewJson");var CLAUDE_PATH_ENV="QWEN_AGENT_CLAUDE_PATH";var SESSION_SEND_MCP_SERVER_NAME="qwen-session";var DEFAULT_TERMINATE_GRACE_MS=5e3;var STDOUT_DRAIN_GRACE_MS=2e3;var MAX_INPUT_PREVIEW_CHARS=2e3;var MAX_TITLE_SUMMARY_CHARS=160;var MAX_STEP_TITLE_CHARS=200;var RESUME_REJECTED_PHRASES=["no conversation found","no saved session found","\u5DF2\u7ED1\u5B9A\u53E6\u5916","bound to another account","bound to a different account"];var PROMPT_TOO_LONG="prompt_too_long";function buildClaudeArgs(options){const args=["-p","--output-format","stream-json","--input-format","stream-json","--verbose","--permission-mode","default","--permission-prompt-tool","stdio","--disallowedTools","AskUserQuestion"];if(options.model)args.push("--model",options.model);if(options.resumeSessionId){args.push("--resume",options.resumeSessionId)}else if(options.instructions){args.push("--append-system-prompt",options.instructions)}if(options.mcpConfigPath){args.push("--mcp-config",options.mcpConfigPath)}return args}__name(buildClaudeArgs,"buildClaudeArgs");function buildClaudeUserMessage(prompt){return`${JSON.stringify({type:"user",message:{role:"user",content:[{type:"text",text:prompt}]}})}
|
|
4
4
|
`}__name(buildClaudeUserMessage,"buildClaudeUserMessage");function claudeResumeWasRejected(requested,emitted,failed,texts){if(!failed||!requested)return false;for(const text of texts){const lower=text.toLowerCase();if(RESUME_REJECTED_PHRASES.some(phrase=>lower.includes(phrase))){return true}}return Boolean(emitted&&emitted!==requested)}__name(claudeResumeWasRejected,"claudeResumeWasRejected");function summarizeToolInput(input){if(!input||typeof input!=="object")return"";const record=input;for(const key of["command","file_path","path","notebook_path","pattern","url","query","description"]){const value=record[key];if(typeof value==="string"&&value.trim()){const line=value.trim().replace(/\s+/g," ");return line.length>MAX_TITLE_SUMMARY_CHARS?`${line.slice(0,MAX_TITLE_SUMMARY_CHARS)}\u2026`:line}}return""}__name(summarizeToolInput,"summarizeToolInput");function toolTitle(name,input){const summary=summarizeToolInput(input);return(summary?`${name}: ${summary}`:name).slice(0,MAX_STEP_TITLE_CHARS)}__name(toolTitle,"toolTitle");function forceForeground(input){return input["run_in_background"]===true?{...input,run_in_background:false}:input}__name(forceForeground,"forceForeground");var PERMISSION_OPTIONS=[{optionId:"allow_once",name:"Allow",kind:"allow_once"},{optionId:"reject_once",name:"Deny",kind:"reject_once"}];var DENIED_MESSAGE="The user denied this tool call.";var RUN_ENDED_MESSAGE="The run ended before the user answered this permission request.";function claudeUsageTotal(usage){if(!usage)return void 0;const total=(usage.input_tokens??0)+(usage.output_tokens??0)+(usage.cache_read_input_tokens??0)+(usage.cache_creation_input_tokens??0);return total>0?total:void 0}__name(claudeUsageTotal,"claudeUsageTotal");function createClaudeCliAdapter(options={}){const executable=options.executable||"claude";const baseEnv=options.env??process.env;const spawnProcess=options.spawn??spawnAgentProcess;const graceMs=options.terminateGraceMs??DEFAULT_TERMINATE_GRACE_MS;const attempt=__name(async(input,resumeSessionId,mcpConfigPath)=>{const args=buildClaudeArgs({model:input.model,resumeSessionId,instructions:input.instructions,mcpConfigPath});let child;try{child=spawnProcess(executable,args,{cwd:input.cwd,env:scrubAgentEnv(baseEnv)})}catch(error2){return{result:{status:"failed",outputText:"",error:`Could not start claude (${executable}): ${error2.message}`},retireSession:false,toolUses:0}}let spawnError=void 0;const exited=new Promise(resolve2=>{child.on("error",error2=>{spawnError=error2;resolve2()});void waitForExit(child).then(resolve2)});const stderr=new TailBuffer;child.stderr?.on("data",chunk=>stderr.append(chunk));child.stdin?.on("error",()=>{});let sessionId=void 0;let lastAssistantText="";let resultText=void 0;let sawResult=false;let resultIsError=false;let terminalReason=void 0;let totalTokens=void 0;let toolUses=0;const steps=new Map;const openPermissions=new Map;let permissionChain=Promise.resolve();const withdrawAllPermissions=__name(()=>{for(const withdraw of openPermissions.values())withdraw();openPermissions.clear()},"withdrawAllPermissions");const send=__name(payload=>{const stdin=child.stdin;if(!stdin||stdin.destroyed||stdin.writableEnded)return;stdin.write(`${JSON.stringify(payload)}
|
|
5
5
|
`)},"send");const closeStdin=__name(()=>{try{child.stdin?.end()}catch{}},"closeStdin");const emitStep=__name(step=>{steps.set(step.id,step);input.onEvent({type:"step",step})},"emitStep");const handleControlRequest=__name(line=>{const requestId=line.request_id;if(!requestId)return;const request=line.request??{};if(request.subtype!=="can_use_tool"){send({type:"control_response",response:{subtype:"error",request_id:requestId,error:`Unsupported control request: ${request.subtype??"unknown"}`}});return}const toolName=request.tool_name??"tool";const toolInput=request.input&&typeof request.input==="object"?request.input:{};const executedInput=forceForeground(toolInput);const inputPreview=previewJson(executedInput,MAX_INPUT_PREVIEW_CHARS);const prompt={requestId,title:toolTitle(toolName,executedInput),toolName,...inputPreview?{inputPreview}:{},options:PERMISSION_OPTIONS};let withdraw;const withdrawn=new Promise(resolve2=>{withdraw=__name(()=>resolve2("withdrawn"),"withdraw")});openPermissions.set(requestId,withdraw);permissionChain=permissionChain.then(async()=>{if(!openPermissions.has(requestId))return;input.onEvent({type:"permission_request",prompt});const decision=await Promise.race([withdrawn,input.awaitPermission(prompt).then(optionId=>{if(optionId==="allow_once"||optionId==="allow_always"){return{behavior:"allow",updatedInput:executedInput}}return{behavior:"deny",message:DENIED_MESSAGE}},()=>({behavior:"deny",message:RUN_ENDED_MESSAGE}))]);if(decision==="withdrawn"||!openPermissions.delete(requestId)){return}send({type:"control_response",response:{subtype:"success",request_id:requestId,response:decision}});input.onEvent({type:"permission_resolved",requestId})}).catch(()=>{})},"handleControlRequest");const handleLine=__name(raw=>{let line;try{line=JSON.parse(raw)}catch{return}switch(line.type){case"system":if(line.session_id&&line.session_id!==sessionId){sessionId=line.session_id;input.onEvent({type:"native_session",nativeSessionId:sessionId})}break;case"assistant":{const content=line.message?.content;if(!Array.isArray(content))break;let text="";for(const block of content){if(block.type==="text"&&block.text){text+=block.text;input.onEvent({type:"text_delta",text:block.text})}else if(block.type==="thinking"){const thought=block.thinking??block.text;if(thought)input.onEvent({type:"thought_delta",text:thought})}else if(block.type==="tool_use"&&block.id){toolUses+=1;emitStep({id:block.id,title:toolTitle(block.name??"tool",block.input),status:"running"})}}if(text)lastAssistantText=text;break}case"user":{const content=line.message?.content;if(!Array.isArray(content))break;for(const block of content){if(block.type!=="tool_result"||!block.tool_use_id)continue;const previous=steps.get(block.tool_use_id);emitStep({id:block.tool_use_id,title:previous?.title??"tool",status:block.is_error?"failed":"completed"})}break}case"result":sawResult=true;resultText=line.result;resultIsError=line.is_error===true;terminalReason=line.terminal_reason;if(line.session_id)sessionId=line.session_id;totalTokens=claudeUsageTotal(line.usage)??totalTokens;if(totalTokens!==void 0){input.onEvent({type:"usage",totalTokens})}closeStdin();break;case"control_request":handleControlRequest(line);break;case"control_cancel_request":{const requestId=line.request_id;const withdraw=requestId?openPermissions.get(requestId):void 0;if(requestId&&withdraw){openPermissions.delete(requestId);withdraw();input.onEvent({type:"permission_resolved",requestId})}break}default:break}},"handleLine");const reading=child.stdout?readJsonLines(child.stdout,handleLine).catch(()=>{}):Promise.resolve();setImmediate(()=>{const stdin=child.stdin;if(!stdin||stdin.destroyed||stdin.writableEnded)return;stdin.write(buildClaudeUserMessage(resumeSessionId?input.prompt:input.freshPrompt??input.prompt))});let aborted=false;const onAbort=__name(()=>{aborted=true;void terminateAgentProcess(child,graceMs)},"onAbort");if(input.signal.aborted)onAbort();else input.signal.addEventListener("abort",onAbort,{once:true});await exited;let graceTimer;await Promise.race([reading,new Promise(resolve2=>{graceTimer=setTimeout(resolve2,STDOUT_DRAIN_GRACE_MS);graceTimer.unref?.()})]);if(graceTimer)clearTimeout(graceTimer);child.stdout?.destroy();await reading;input.signal.removeEventListener("abort",onAbort);withdrawAllPermissions();const stderrTail=stderr.toString().trim();const fallbackText=resultText?.trim()?resultText:lastAssistantText;const withSession=__name(result=>({...result,...sessionId?{nativeSessionId:sessionId}:{},...totalTokens!==void 0?{totalTokens}:{}}),"withSession");if(aborted){return{result:withSession({status:"cancelled",outputText:lastAssistantText}),retireSession:false,toolUses}}if(spawnError){return{result:{status:"failed",outputText:"",error:`Could not start claude (${executable}): ${spawnError.message}`},retireSession:false,toolUses}}let failure;let overflow=false;if(!sawResult){failure=`claude exited without a result${child.exitCode!==null?` (exit code ${child.exitCode})`:""}.`}else if(terminalReason===PROMPT_TOO_LONG){overflow=true;failure="claude ended the turn with terminal_reason=prompt_too_long: the session's context window is exhausted."}else if(resultIsError){failure=resultText?.trim()||"claude reported an error."}if(failure===void 0){return{result:withSession({status:"completed",outputText:fallbackText}),retireSession:false,toolUses}}const error=stderrTail?`${failure}
|
|
6
6
|
${stderrTail.slice(-2e3)}`:failure;const rejected=claudeResumeWasRejected(resumeSessionId,sessionId,true,[failure,stderrTail]);const retire=rejected||overflow&&Boolean(resumeSessionId);return{result:{status:"failed",outputText:lastAssistantText,error,...sessionId&&!rejected?{nativeSessionId:sessionId}:{},...totalTokens!==void 0?{totalTokens}:{}},retireSession:retire,toolUses}},"attempt");return{program:"claude",async runTurn(input){let mcpDir;let mcpConfigPath;try{if(input.sessionSendServer){mcpDir=await mkdtemp(join2(tmpdir(),"qwen-agent-mcp-"));mcpConfigPath=join2(mcpDir,"mcp-config.json");const server=input.sessionSendServer;await writeFile(mcpConfigPath,JSON.stringify({mcpServers:{[SESSION_SEND_MCP_SERVER_NAME]:{command:server.command,args:server.args,...server.env?{env:server.env}:{}}}}),{mode:384})}const first=await attempt(input,input.nativeSessionId,mcpConfigPath);if(!first.retireSession||input.signal.aborted||first.toolUses>0){return{...first.result,...first.retireSession?{resumeRejected:true}:{}}}const second=await attempt(input,void 0,mcpConfigPath);return{...second.result,resumeRejected:true}}catch(error){return{status:"failed",outputText:"",error:error.message}}finally{if(mcpDir)await rm(mcpDir,{recursive:true,force:true}).catch(()=>{})}}}}__name(createClaudeCliAdapter,"createClaudeCliAdapter");init_esbuild_shims();var CODEX_PATH_ENV="QWEN_AGENT_CODEX_PATH";var DEFAULT_CODEX_TIMEOUTS={handshakeMs:3e4,threadSetupMs:6e4,firstTurnNoProgressMs:6e4,inactivityMs:10*6e4,terminateGraceMs:5e3,interruptMs:5e3};var MAX_INPUT_PREVIEW_CHARS2=2e3;var MAX_TITLE_CHARS=200;var JSON_RPC_METHOD_NOT_FOUND=-32601;function codexMcpOverrides(server){const prefix=`mcp_servers.${SESSION_SEND_MCP_SERVER_NAME}`;const args=["-c",`${prefix}.command=${JSON.stringify(server.command)}`,"-c",`${prefix}.args=${JSON.stringify(server.args)}`];for(const[key,value]of Object.entries(server.env??{})){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))continue;args.push("-c",`${prefix}.env.${key}=${JSON.stringify(value)}`)}return args}__name(codexMcpOverrides,"codexMcpOverrides");function buildCodexArgs(sessionSendServer){return["app-server","--listen","stdio://",...sessionSendServer?codexMcpOverrides(sessionSendServer):[]]}__name(buildCodexArgs,"buildCodexArgs");var CodexRpcError=class extends Error{constructor(method,code,message){super(`${method}: ${message}${code!==void 0?` (code=${code})`:""}`);this.method=method;this.code=code;this.name="CodexRpcError"}static{__name(this,"CodexRpcError")}};var CodexTransportError=class extends Error{constructor(message,overflow=false){super(message);this.overflow=overflow;this.name="CodexTransportError"}static{__name(this,"CodexTransportError")}};function asRecord(value){return value&&typeof value==="object"&&!Array.isArray(value)?value:void 0}__name(asRecord,"asRecord");function nestedString(value,...keys){let current=value;for(const key of keys){const record=asRecord(current);if(!record)return void 0;current=record[key]}return typeof current==="string"?current:void 0}__name(nestedString,"nestedString");function nestedNumber(value,...keys){let current=value;for(const key of keys){const record=asRecord(current);if(!record)return void 0;current=record[key]}return typeof current==="number"?current:void 0}__name(nestedNumber,"nestedNumber");function clip(text,max=MAX_TITLE_CHARS){const line=text.trim().replace(/\s+/g," ");return line.length>max?`${line.slice(0,max)}\u2026`:line}__name(clip,"clip");function commandText(command){if(typeof command==="string")return command;if(Array.isArray(command))return command.map(String).join(" ");return""}__name(commandText,"commandText");var CodexTurnGate=class{static{__name(this,"CodexTurnGate")}armed=false;started=false;turnId;arm(){this.armed=true}accept(method,params){if(!this.armed)return false;if(method==="turn/started"){this.started=true;this.turnId=nestedString(params,"turn","id");return true}if(method==="turn/completed"){if(!this.started)return true;const id=nestedString(params,"turn","id");return!this.turnId||!id||id===this.turnId}if(method.startsWith("item/")||method==="thread/status/changed"){if(!this.started)return true;const id=typeof params?.["turnId"]==="string"?params["turnId"]:void 0;return!this.turnId||!id||id===this.turnId}return true}};var APPROVAL_METHODS={"item/commandExecution/requestApproval":{kind:"command",legacy:false},execCommandApproval:{kind:"command",legacy:true},"item/fileChange/requestApproval":{kind:"fileChange",legacy:false},applyPatchApproval:{kind:"fileChange",legacy:true},"item/permissions/requestApproval":{kind:"permissions",legacy:false},"mcpServer/elicitation/request":{kind:"elicitation",legacy:false}};var FULL_OPTIONS=[{optionId:"allow_once",name:"Allow",kind:"allow_once"},{optionId:"allow_always",name:"Allow for the rest of this chat",kind:"allow_always"},{optionId:"reject_once",name:"Deny",kind:"reject_once"}];var ONCE_OPTIONS=[{optionId:"allow_once",name:"Allow",kind:"allow_once"},{optionId:"reject_once",name:"Deny",kind:"reject_once"}];function codexApprovalPrompt(requestId,method,params){const spec=APPROVAL_METHODS[method];if(!spec)return void 0;let title;let toolName;switch(spec.kind){case"command":{toolName="exec_command";const command=commandText(params?.["command"]);title=command?`exec_command: ${clip(command)}`:"exec_command";break}case"fileChange":toolName="patch_apply";title="patch_apply: edit files";break;case"permissions":toolName="permissions";title="permissions: grant additional access";break;case"elicitation":{toolName="mcp_elicitation";const server=typeof params?.["serverName"]==="string"?params["serverName"]:"";title=server?`mcp_elicitation: ${clip(server)}`:"mcp_elicitation";break}default:{const exhaustive=spec.kind;return exhaustive}}const reason=typeof params?.["reason"]==="string"?params["reason"]:"";if(reason)title=clip(`${title} (${reason})`);const inputPreview=previewJson(params,MAX_INPUT_PREVIEW_CHARS2);return{requestId,title,toolName,...inputPreview?{inputPreview}:{},options:spec.kind==="command"||spec.kind==="fileChange"?FULL_OPTIONS:ONCE_OPTIONS}}__name(codexApprovalPrompt,"codexApprovalPrompt");function codexApprovalResponse(method,params,optionId){const spec=APPROVAL_METHODS[method];const allow=optionId==="allow_once"||optionId==="allow_always";const always=optionId==="allow_always";if(!spec)return{};switch(spec.kind){case"command":case"fileChange":if(spec.legacy){return{decision:allow?always?"approved_for_session":"approved":"denied"}}return{decision:allow?always?"acceptForSession":"accept":"decline"};case"permissions":{const granted={};const requested=asRecord(params?.["permissions"]);if(allow&&requested){for(const key of["network","fileSystem"]){if(requested[key]!==void 0&&requested[key]!==null){granted[key]=requested[key]}}}return{permissions:granted,scope:"turn"}}case"elicitation":return allow?{action:"accept",content:null}:{action:"decline",content:null};default:return{}}}__name(codexApprovalResponse,"codexApprovalResponse");function createCodexAppServerAdapter(options={}){const executable=options.executable||"codex";const baseEnv=options.env??process.env;const spawnProcess=options.spawn??spawnAgentProcess;const timeouts={...DEFAULT_CODEX_TIMEOUTS,...options.timeouts};const maxLineBytes=options.maxLineBytes??DEFAULT_MAX_LINE_BYTES;const attempt=__name(async(input,resumeThreadId)=>{let child;try{child=spawnProcess(executable,buildCodexArgs(input.sessionSendServer),{cwd:input.cwd,env:scrubAgentEnv(baseEnv)})}catch(error){return{result:{status:"failed",outputText:"",error:`Could not start codex (${executable}): ${error.message}`},retryFresh:false}}const stderr=new TailBuffer;child.stderr?.on("data",chunk=>stderr.append(chunk));child.stdin?.on("error",()=>{});let nextId=0;const pending=new Map;let transportError=void 0;const failTransport=__name(error=>{transportError??=error;for(const[id,request2]of pending){if(request2.timer)clearTimeout(request2.timer);pending.delete(id);request2.reject(transportError)}settleTurn()},"failTransport");const write=__name(message=>{const stdin=child.stdin;if(!stdin||stdin.destroyed||stdin.writableEnded)return;stdin.write(`${JSON.stringify({jsonrpc:"2.0",...message})}
|
|
@@ -13,7 +13,7 @@ ${body}
|
|
|
13
13
|
|
|
14
14
|
${open}
|
|
15
15
|
${body}
|
|
16
|
-
${close}`,lastRecordId:records.at(-1)?.uuid??readThroughRecordId,omittedCount,cursorLost}}__name(buildAgentInput,"buildAgentInput");init_esbuild_shims();var RUN_FRAME_THROTTLE_MS=100;var SessionAgentEventHub=class{constructor(throttleMs=RUN_FRAME_THROTTLE_MS){this.throttleMs=throttleMs}static{__name(this,"SessionAgentEventHub")}subscribers=new Set;pending=new Map;deliveredStatus=new Map;subscribe(listener,sessionId){const subscriber={listener,sessionId};this.subscribers.add(subscriber);return()=>{this.subscribers.delete(subscriber)}}publish(frame,options={}){if(frame.type!=="run"){this.deliver(frame);return}const key=`${frame.sessionId}\0${frame.runId}`;const existing=this.pending.get(key);const statusChanged=options.immediate===true||this.deliveredStatus.get(key)!==frameStateKey(frame);if(statusChanged){if(existing)clearTimeout(existing.timer);this.pending.delete(key);this.deliverRun(key,frame);return}if(existing){existing.frame=frame;return}const timer=setTimeout(()=>{const entry=this.pending.get(key);this.pending.delete(key);if(entry)this.deliverRun(key,entry.frame)},this.throttleMs);timer.unref?.();this.pending.set(key,{frame,timer})}forgetRun(sessionId,runId){const key=`${sessionId}\0${runId}`;const entry=this.pending.get(key);if(entry){clearTimeout(entry.timer);this.pending.delete(key);this.deliverRun(key,entry.frame)}this.deliveredStatus.delete(key)}dispose(){for(const entry of this.pending.values())clearTimeout(entry.timer);this.pending.clear();this.deliveredStatus.clear();this.subscribers.clear()}deliverRun(key,frame){this.deliveredStatus.set(key,frameStateKey(frame));this.deliver(frame)}deliver(frame){for(const subscriber of[...this.subscribers]){if(frame.type==="run"&&subscriber.sessionId!==void 0&&subscriber.sessionId!==frame.sessionId){continue}try{subscriber.listener(frame)}catch{}}}};var hubs=new Map;function getSessionAgentEventHub(workspaceCwd){let hub=hubs.get(workspaceCwd);if(!hub){hub=new SessionAgentEventHub;hubs.set(workspaceCwd,hub)}return hub}__name(getSessionAgentEventHub,"getSessionAgentEventHub");function frameStateKey(frame){return[frame.status,frame.recorded===void 0?"":String(frame.recorded),frame.permission?.requestId??"",frame.retryable?"retryable":""].join("|")}__name(frameStateKey,"frameStateKey");init_esbuild_shims();function isExecutingRun(run){return run.status==="running"||run.status==="awaiting_approval"}__name(isExecutingRun,"isExecutingRun");function isQueuedRun(run){return run.status==="queued"}__name(isQueuedRun,"isQueuedRun");function enqueueTrigger(runs2,input){const live=runs2.filter(run2=>run2.agentId===input.agentId&&(isQueuedRun(run2)||isExecutingRun(run2)));const duplicate=live.find(run2=>run2.triggerRecordIds.includes(input.recordId));if(duplicate)return{kind:"duplicate",run:duplicate};const queued=live.find(isQueuedRun);if(queued){queued.triggerRecordIds.push(input.recordId);queued.chainDepth=coalesceChainDepth(queued.chainDepth,input.chainDepth);if(input.squadId!==void 0)queued.squadId??=input.squadId;return{kind:"coalesced",run:queued}}const run={id:input.newRunId(),agentId:input.agentId,status:"queued",triggerRecordIds:[input.recordId],chainDepth:input.chainDepth,createdAt:input.now,attempts:0,...input.squadId!==void 0?{squadId:input.squadId}:{}};runs2.push(run);return{kind:"created",run}}__name(enqueueTrigger,"enqueueTrigger");function nextRunnable(runs2,agentId){const mine=runs2.filter(run=>run.agentId===agentId);if(mine.some(isExecutingRun))return void 0;return mine.filter(isQueuedRun).sort((a,b)=>a.createdAt-b.createdAt)[0]}__name(nextRunnable,"nextRunnable");function queuePosition(runs2,run){if(!isQueuedRun(run))return void 0;const queued=runs2.filter(candidate=>candidate.agentId===run.agentId&&isQueuedRun(candidate)).sort((a,b)=>a.createdAt-b.createdAt);const index=queued.findIndex(candidate=>candidate.id===run.id);return index===-1?void 0:index+1}__name(queuePosition,"queuePosition");var LOCAL_SESSION_AGENT_RUNTIME_ID="local";var SESSION_AGENT_STALL_TIMEOUT_MS=15*6e4;var SESSION_AGENT_STALLED_ERROR="agent_run_stalled";var SESSION_AGENT_RESTARTED_ERROR="daemon restarted";var SESSION_AGENT_STOPPED_ERRORS={shutdown:SESSION_AGENT_RESTARTED_ERROR,runtime_replaced:"stopped: the workspace runtime was restarted",workspace_closed:"stopped: the workspace was closed",workspace_untrusted:"stopped: the workspace is no longer trusted",collaboration_disabled:"stopped: agent collaboration was turned off"};var SESSION_AGENT_OFFLINE_ERROR="runtime went offline";var SESSION_AGENT_HOST_REMOVED_ERROR="its Agent Host was removed";var SESSION_AGENT_REPLY_NOT_RECORDED_ERROR="the reply was not recorded before the daemon stopped";var HOST_TURN_LEASE_MS=6e4;var SWEEP_INTERVAL_MS=5e3;var MAX_OUTPUT_CHARS=MAX_AGENT_MESSAGE_DISPLAY_TEXT_CHARS;var MAX_THOUGHT_CHARS=65536;var MAX_FRAME_STEPS=8;var MAX_RUN_STEPS=MAX_AGENT_MESSAGE_STEPS;var CLIENT_MESSAGE_ID_PATTERN=/^[A-Za-z0-9_.:-]{1,128}$/;var MAX_MENTION_TEXT_CHARS=MAX_EXTERNAL_RECORD_TEXT_LENGTH;var CLIPPED_REPLY_NOTE="\n\n[Reply truncated.]";var UNREPORTED_TURN_TOKENS=1e4;var PENDING_POST_TTL_MS=60*6e4;var RECORD_WATCH_INITIAL_MS=1e3;var RECORD_WATCH_MAX_INTERVAL_MS=15e3;var RECORD_WATCH_MAX_MS=PENDING_POST_TTL_MS;var RECORD_RECOVERY_WATCH_MAX_MS=3e4;var MAX_SETTLED_RUNS=200;var CANCELLED_LEASE_TTL_MS=10*6e4;var SessionAgentError=class extends Error{constructor(status,code,message,details){super(message);this.status=status;this.code=code;this.details=details;this.name="SessionAgentError"}static{__name(this,"SessionAgentError")}};function clipReplyText(text){if(text.length<=MAX_AGENT_MESSAGE_DISPLAY_TEXT_CHARS)return text;let end=MAX_AGENT_MESSAGE_DISPLAY_TEXT_CHARS-CLIPPED_REPLY_NOTE.length;const last=text.charCodeAt(end-1);if(last>=55296&&last<=56319)end-=1;return text.slice(0,end)+CLIPPED_REPLY_NOTE}__name(clipReplyText,"clipReplyText");function recordSteps(steps){return[...steps].filter(step=>step.id.length<=MAX_EXTERNAL_RECORD_ID_LENGTH).slice(-MAX_AGENT_MESSAGE_STEPS).map(step=>step.title.length>MAX_EXTERNAL_RECORD_STEP_TITLE_LENGTH?{...step,title:step.title.slice(0,MAX_EXTERNAL_RECORD_STEP_TITLE_LENGTH)}:step)}__name(recordSteps,"recordSteps");function assertMentionFitsRecord(agents,squads){if(agents>MAX_EXTERNAL_RECORD_MENTION_IDS||squads>MAX_EXTERNAL_RECORD_MENTION_IDS){throw new SessionAgentError(400,"too_many_mentions",`A message can address at most ${MAX_EXTERNAL_RECORD_MENTION_IDS} agents and ${MAX_EXTERNAL_RECORD_MENTION_IDS} squads.`)}}__name(assertMentionFitsRecord,"assertMentionFitsRecord");function recordWriteError(error){const data=error?.data;const kind=typeof data==="object"&&data!==null?data.errorKind:void 0;const message=getErrorMessage(error);if(kind==="managed_session_unsupported"||message.includes("managed_session_unsupported")||message.includes("not supported in managed sessions")){return new SessionAgentError(400,"managed_session_unsupported","Session agents are not supported in managed sessions.")}return new SessionAgentError(502,"record_write_failed",message)}__name(recordWriteError,"recordWriteError");function triggerIdFor(response,recordKey){return response.deferred||!response.recordId?`pending:${recordKey}`:response.recordId}__name(triggerIdFor,"triggerIdFor");function programForAgent(agent,hostPrograms){if(agent.execution?.mode!=="managed-host"){return agent.execution?.provider??"qwen"}const provider=agent.execution.provider;if(!hostPrograms)return provider??"qwen";if(provider)return hostPrograms.includes(provider)?provider:void 0;return hostPrograms.includes("qwen")?"qwen":hostPrograms[0]}__name(programForAgent,"programForAgent");function authorFor(agent,runtimeId,program){return{agentId:agent.id,name:agent.name,...agent.color?{color:agent.color}:{},...program?{program}:{},...runtimeId?{runtimeId}:{}}}__name(authorFor,"authorFor");var LOOPBACK_HOSTNAMES=new Set(["127.0.0.1","localhost","[::1]","::1"]);function isLoopbackUrl(url){try{const parsed=new URL(url);return(parsed.protocol==="http:"||parsed.protocol==="https:")&&LOOPBACK_HOSTNAMES.has(parsed.hostname)}catch{return false}}__name(isLoopbackUrl,"isLoopbackUrl");function buildSessionSendServer(url,token){const cliEntry=process.env["QWEN_CLI_ENTRY"]||process.argv[1];if(!cliEntry)return void 0;const execArgv=process.execArgv.filter(arg=>!/^--(inspect|debug)/.test(arg));return{command:process.execPath,args:[...execArgv,cliEntry,"agents","session-send-mcp","--url",url],env:{QWEN_SESSION_SEND_TOKEN:token}}}__name(buildSessionSendServer,"buildSessionSendServer");function tokensMatch(expected,given){const a=Buffer.from(expected);const b=Buffer.from(given);return a.length===b.length&&timingSafeEqual(a,b)}__name(tokensMatch,"tokensMatch");function tokenBudgetError(budget,names){return`Agent token budget (${budget.toLocaleString("en-US")} tokens since your last message) reached; not started: ${names.map(name=>`@${name}`).join(", ")}. Post a message to continue.`}__name(tokenBudgetError,"tokenBudgetError");function unreachedAgentsError(unavailable,unknown){const reasons=[...unavailable.length>0?[`${unavailable.map(agent=>`@${agent.name}`).join(", ")} cannot run (paused or retired)`]:[],...unknown.length>0?[`${unknown.map(name=>`@${name}`).join(", ")} matched no agent`]:[]];return reasons.length>0?`This post reached no agent: ${reasons.join("; ")}.`:void 0}__name(unreachedAgentsError,"unreachedAgentsError");function squadUnavailableError(unavailable){return unavailable.map(({squad,reason})=>reason==="retired"?`Squad @${squad.name} is retired.`:reason==="leader_disabled"?`Squad @${squad.name} was not started: its leader is paused. Resume the leader or pick another one.`:`Squad @${squad.name} was not started: it needs a new leader (the leader agent was ${reason==="leader_retired"?"retired":"removed"}).`).join(" ")}__name(squadUnavailableError,"squadUnavailableError");var PROGRAM_LABELS={qwen:"Qwen Code",claude:"Claude Code",codex:"Codex"};function joinErrors(...errors){const present=errors.filter(error=>!!error);return present.length>0?present.join(" "):void 0}__name(joinErrors,"joinErrors");function chainLimitError(limit,names){return`Agent chain limit (${limit}) reached; not started: ${names.map(name=>`@${name}`).join(", ")}.`}__name(chainLimitError,"chainLimitError");async function defaultLoadDefinition(workspaceCwd,name){const{createDaemonSubagentManager}=await import("./workspace-agents-IMAQME4W.js");return createDaemonSubagentManager(workspaceCwd).loadSubagent(name)}__name(defaultLoadDefinition,"defaultLoadDefinition");async function resolveTurnPersona(agent,program,loadDefinition){let definitionPrompt;let definitionModel;if(agent.agentType){const loaded=await loadDefinition(agent.agentType);if(!loaded){throw new Error(`Agent definition "${agent.agentType}" is unavailable.`)}if(loaded.executor!==void 0){throw new Error(`Agent definition "${agent.agentType}" declares an external executor, which a workspace Agent cannot use. Set execution.mode to "managed-host" on the Agent instead, or use a definition without an executor block.`)}if(program!=="qwen"&&(loaded.tools?.length&&!loaded.tools.includes("*")||loaded.disallowedTools?.length)){throw new Error(`Agent definition "${agent.agentType}" restricts tools, which the ${program} runtime cannot enforce. Use the Qwen runtime for this definition, or choose a definition without tool restrictions.`)}definitionPrompt=loaded.systemPrompt?.trim()||void 0;definitionModel=loaded.model?.trim()||void 0}const instructions=[definitionPrompt,agent.instructions?.trim()].filter(Boolean).join("\n\n");const model=agent.model??(program==="qwen"&&definitionModel&&definitionModel!=="inherit"?definitionModel:void 0);return{...instructions?{instructions}:{},...model?{model}:{}}}__name(resolveTurnPersona,"resolveTurnPersona");var SessionAgentOrchestrator=class{static{__name(this,"SessionAgentOrchestrator")}workspaceCwd;bridge;hub;chainLimit;tokenBudget;readAgents;readSquads;squadNames=new Map;loadRecords;adapterFor;now;stallTimeoutMs;leaseMs;sessionSendUrl;recordWatchMs;restoreSession;loadDefinition;sessions=new Map;startupStates=new Map;states=new Map;live=new Map;pendingPosts=new Map;settled=new Map;cancelledLeases=new Map;sendTokens=new Map;dirty=new Set;recovered;sweepTimer;stopped=false;stoppedError=SESSION_AGENT_RESTARTED_ERROR;constructor(options){this.workspaceCwd=options.workspaceCwd;this.bridge=options.bridge;this.hub=options.hub??getSessionAgentEventHub(options.workspaceCwd);this.chainLimit=options.chainLimit??(()=>0);this.tokenBudget=options.tokenBudget??(()=>DEFAULT_AGENT_TOKEN_BUDGET);this.readAgents=options.readAgents??readWorkspaceAgents;this.readSquads=options.readSquads??readSquads;this.loadRecords=options.loadRecords??(async sessionId=>{const data=await new SessionService(this.workspaceCwd).loadSession(sessionId);return data?.conversation.messages??[]});this.adapterFor=options.getAdapter??getAdapter;this.now=options.now??Date.now;this.stallTimeoutMs=options.stallTimeoutMs??SESSION_AGENT_STALL_TIMEOUT_MS;this.leaseMs=options.leaseMs??HOST_TURN_LEASE_MS;this.sessionSendUrl=options.sessionSendUrl;this.recordWatchMs=options.recordWatchMs??RECORD_WATCH_INITIAL_MS;this.restoreSession=options.restoreSession??(async sessionId=>{await this.bridge.resumeSession({sessionId,workspaceCwd:this.workspaceCwd})});this.loadDefinition=options.loadDefinition??defaultLoadDefinition;this.recovered=this.recoverOnStartup().catch(error=>{writeStderrLine(`qwen serve: session agent recovery failed in ${this.workspaceCwd}: ${getErrorMessage(error)}`)});if(options.startTimers!==false){this.sweepTimer=setInterval(()=>this.sweep(),SWEEP_INTERVAL_MS);this.sweepTimer.unref?.()}}async mention(sessionId,input){this.assertRunning();if(!isValidSessionAgentsSessionId(sessionId)){throw new SessionAgentError(400,"invalid_session_id","Invalid session id.")}const{text,clientMessageId}=input;if(typeof text!=="string"||text.trim().length===0||text.length>MAX_MENTION_TEXT_CHARS){throw new SessionAgentError(400,"invalid_text","text is required.")}if(typeof clientMessageId!=="string"||!CLIENT_MESSAGE_ID_PATTERN.test(clientMessageId)){throw new SessionAgentError(400,"invalid_client_message_id","clientMessageId must be 1-128 characters of [A-Za-z0-9_.:-].")}const roster=await this.readAgents(this.workspaceCwd);const squads=await this.loadSquads();const targets=resolveMentionTargetsWithSquads(text,roster,squads);const squadLeaders=targets.squads.flatMap(squad=>{const leader=roster.find(agent=>agent.id===squad.leaderAgentId);return leader?[{squad,leader}]:[]});assertMentionFitsRecord(targets.agents.length,squadLeaders.length);const squadError=targets.unavailableSquads.length>0?squadUnavailableError(targets.unavailableSquads):void 0;if(targets.agents.length===0&&squadLeaders.length===0){const details={unavailable:targets.unavailable.map(agent=>agent.name),unknown:targets.unknown,...targets.unavailableSquads.length>0?{unavailableSquads:targets.unavailableSquads.map(({squad,reason})=>({name:squad.name,reason}))}:{}};if(squadError){throw new SessionAgentError(400,"squad_unavailable",squadError,details)}throw new SessionAgentError(400,"no_agents_mentioned","The message does not @-mention any available agent.",details)}const state=await this.session(sessionId);const recordKey=`mention:${clientMessageId}`;let record;try{record=await this.appendRecord(sessionId,{kind:"agent_mention",recordKey,modelText:formatAgentMentionModelText(text,[...targets.agents.map(agent=>agent.name),...squadLeaders.map(({squad})=>squad.name)]),payload:{displayText:text,mentionedAgentIds:targets.agents.map(agent=>agent.id),...squadLeaders.length>0?{mentionedSquadIds:squadLeaders.map(({squad})=>squad.id)}:{},...squadError?{error:squadError}:{}}})}catch(error){throw recordWriteError(error)}const triggerId=triggerIdFor(record,recordKey);if(!record.created){return{recordId:record.recordId,...record.deferred?{deferred:true}:{},runs:state.file.runs.filter(run=>run.triggerRecordIds.includes(triggerId)).map(run=>({runId:run.id,agentId:run.agentId,status:run.status}))}}if(record.deferred){this.addPendingPost({sessionId,id:triggerId,kind:"agent_mention",speaker:"User",text,createdAt:this.now()})}delete state.file.chainTokens;const depth=nextChainDepth({kind:"human"});const runs2=[];const addRun=__name(summary=>{if(!runs2.some(existing=>existing.runId===summary.runId)){runs2.push(summary)}},"addRun");for(const{squad,leader}of squadLeaders){this.startEngagement(state,squad,triggerId);addRun(this.enqueue(state,leader,triggerId,depth,squad.id))}for(const agent of targets.agents){addRun(this.enqueue(state,agent,triggerId,depth))}await this.persist(state).catch(()=>{});for(const agent of targets.agents)this.pumpAgent(agent.id);for(const{leader}of squadLeaders)this.pumpAgent(leader.id);return{recordId:record.recordId,...record.deferred?{deferred:true}:{},runs:runs2,...squadError?{squadError}:{}}}async cancel(sessionId,runId){const live=this.live.get(runId);if(!live||live.sessionId!==sessionId){const settled=this.settled.get(runId);if(settled?.sessionId!==sessionId||!settled.frame.retryable){return false}this.dropSettled(runId,{});const state2=await this.session(sessionId);const run=state2.file.runs.find(candidate=>candidate.id===runId);if(run?.recorded===false){delete run.recorded;await this.persist(state2).catch(()=>{})}return true}const state=await this.session(sessionId);await this.cancelLive(state,live);return true}async retry(sessionId,runId){this.assertRunning();if(!isValidSessionAgentsSessionId(sessionId)){throw new SessionAgentError(400,"invalid_session_id","Invalid session id.")}const state=await this.session(sessionId);const run=state.file.runs.find(candidate=>candidate.id===runId);if(!run){throw new SessionAgentError(404,"run_not_found","No such run.")}if(run.status!=="failed"&&run.status!=="offline"&&this.settled.get(runId)?.frame.retryable!==true){throw new SessionAgentError(409,"run_not_retryable","Only a failed or offline run can be retried.")}const roster=await this.readAgents(this.workspaceCwd);const agent=roster.find(candidate=>candidate.id===run.agentId);if(!agent||!isAgentAddressable(agent)){throw new SessionAgentError(409,"agent_unavailable","This agent is disabled or no longer exists.")}const ledSquad=run.squadId?(await this.loadSquads()).find(candidate=>candidate.id===run.squadId&&candidate.leaderAgentId===agent.id):void 0;if(state.file.runs.some(candidate=>candidate.retryOf===runId)){throw new SessionAgentError(409,"run_already_retried","This run was already retried.")}const trigger=run.triggerRecordIds[0];if(trigger===void 0){throw new SessionAgentError(409,"run_not_retryable","This run has no trigger to answer.")}if(ledSquad)this.startEngagement(state,ledSquad,trigger);let summary;for(const triggerId of run.triggerRecordIds){summary=this.enqueue(state,agent,triggerId,run.chainDepth,ledSquad?.id)}const retried=summary&&this.live.get(summary.runId)?.run;if(!retried){throw new SessionAgentError(409,"run_not_retryable","This run has no trigger to answer.")}retried.retryOf??=runId;if(run.recorded===false)delete run.recorded;for(const{squadId}of this.settled.get(runId)?.wakes??[]){this.trackDelegation(state,squadId,retried.id)}this.dropSettled(runId,{retriedAsRunId:retried.id});this.settleEngagements(state);await this.persist(state).catch(()=>{});this.pumpAgent(agent.id);return{runId:retried.id,agentId:agent.id,status:retried.status}}async stopAll(sessionId){let droppedWakes=false;for(const settled of this.settled.values()){if(settled.sessionId===sessionId&&settled.wakes){delete settled.wakes;droppedWakes=true}}const runs2=[...this.live.values()].filter(live=>live.sessionId===sessionId);if(runs2.length===0){if(droppedWakes){const state2=await this.session(sessionId);if(this.settleEngagements(state2)){await this.persist(state2).catch(()=>{})}}return[]}const state=await this.session(sessionId);runs2.sort((a,b)=>Number(isExecutingRun(a.run))-Number(isExecutingRun(b.run)));for(const live of runs2)await this.cancelLive(state,live);return runs2.map(live=>live.run.id)}resolvePermission(sessionId,runId,requestId,optionId,voter){const live=this.live.get(runId);if(!live||live.sessionId!==sessionId){throw new SessionAgentError(404,"run_not_found","No such live run.")}const prompt=live.frame.permission;if(!prompt||prompt.requestId!==requestId){throw new SessionAgentError(404,"permission_not_found","No pending permission request for this run.")}if(typeof optionId!=="string"||!prompt.options.some(option=>option.optionId===optionId)){throw new SessionAgentError(400,"invalid_option","Unknown optionId.")}if(live.remote){const decision={runId,attempt:live.run.attempts,requestId,optionId,decisionId:randomUUID3()};live.remote.decisions=[...live.remote.decisions.filter(existing=>existing.requestId!==requestId),decision];this.publish(live,{immediate:true});return}const pending=live.pendingPermissions.get(requestId);if(!pending){throw new SessionAgentError(409,"permission_already_answered","This permission request was already answered.")}if(voter)live.voterContexts.set(requestId,voter);live.pendingPermissions.delete(requestId);pending.resolve(optionId)}async postFromAgent(sessionId,agentId,token,text){this.assertRunning();const expected=this.sendTokens.get(this.sendKey(sessionId,agentId));if(!expected||!tokensMatch(expected,token)){throw new SessionAgentError(401,"invalid_session_send_token","Unknown agent binding or invalid session_send token.")}if(typeof text!=="string"||isBlankAgentText(text)||text.length>MAX_MENTION_TEXT_CHARS){throw new SessionAgentError(400,"invalid_text","text is required.")}const live=[...this.live.values()].find(candidate=>candidate.sessionId===sessionId&&candidate.run.agentId===agentId&&!candidate.remote&&!candidate.abortReason&&isExecutingRun(candidate.run));if(!live){throw new SessionAgentError(409,"run_not_running","The agent has no running turn in this session.")}const state=await this.session(sessionId);live.frame.activityAt=this.now();await this.queueSessionSend(state,live,text)}async snapshot(sessionId){if(!isValidSessionAgentsSessionId(sessionId)){throw new SessionAgentError(400,"invalid_session_id","Invalid session id.")}await this.recovered;const frames=[...this.live.values()].filter(live=>live.sessionId===sessionId).map(live=>this.buildFrame(live));for(const settled of this.settled.values()){if(settled.sessionId===sessionId)frames.push({...settled.frame})}return frames}async liveRuns(){await this.recovered;return[...this.live.values()].map(live=>({sessionId:live.sessionId,runId:live.run.id,agentId:live.run.agentId,status:live.run.status,...live.remote?{hostId:live.remote.hostId}:{}}))}ready(){return this.recovered}async dispose(reason="shutdown"){if(this.stopped)return;this.stopped=true;this.stoppedError=SESSION_AGENT_STOPPED_ERRORS[reason];if(this.sweepTimer)clearInterval(this.sweepTimer);for(const settled of this.settled.values()){if(settled.timer)clearTimeout(settled.timer)}for(const live of this.live.values()){if(live.remote||live.author.runtimeId!==LOCAL_SESSION_AGENT_RUNTIME_ID||!isExecutingRun(live.run)){continue}live.abortReason="shutdown";for(const pending of live.pendingPermissions.values()){pending.reject(new Error("daemon stopping"))}live.pendingPermissions.clear();live.controller?.abort()}for(const state of this.dirty)await this.persist(state).catch(()=>{});this.dirty.clear()}async pickupForHost(hostId,programs){if(this.stopped)return void 0;await this.recovered;const roster=await this.readAgents(this.workspaceCwd);const queued=[...this.live.values()].filter(live=>live.run.status==="queued").sort((a,b)=>a.run.createdAt-b.run.createdAt);for(const live of queued){const{run}=live;if(run.status!=="queued")continue;const agent=roster.find(candidate=>candidate.id===run.agentId);if(!agent||!isAgentAddressable(agent)||agent.execution?.mode!=="managed-host"||!agent.execution.hostIds.includes(hostId)){continue}live.maxConcurrent=maxConcurrentRunsFor(agent);if(this.executingCount(agent.id)>=live.maxConcurrent)continue;const program=programForAgent(agent,programs);if(!program)continue;const state=await this.session(live.sessionId);if(run.status!=="queued")continue;if(nextRunnable(state.file.runs,agent.id)?.id!==run.id)continue;if(this.executingCount(agent.id)>=live.maxConcurrent)continue;const now=this.now();run.status="running";run.attempts+=1;run.startedAt=now;delete run.error;const lease={hostId,leaseId:randomUUID3(),attempt:run.attempts,expiresAt:now+this.leaseMs,lastSequence:0};run.lease=lease;live.author=authorFor(agent,hostId,program);live.remote={hostId,program,decisions:[]};live.frame.activityAt=now;this.republishQueued(agent.id);try{const persona=await resolveTurnPersona(agent,program,name=>this.loadDefinition(this.workspaceCwd,name));const binding=state.file.bindings[agent.id]??{agentId:agent.id};const records=await this.loadRecords(live.sessionId);const squad=await this.squadBriefingFor(live,roster);const sameRuntime=binding.runtimeId===hostId&&canReuseNativeSession(binding,hostId,program);const nativeSessionId=sameRuntime?binding.nativeSessionId:void 0;const readThroughRecordId=sameRuntime?binding.readThroughRecordId:void 0;const inputOptions={records,trigger:{agentId:agent.id,agentName:agent.name,recordIds:run.triggerRecordIds},budgetChars:AGENT_INPUT_CHAR_BUDGET,pendingMessages:this.pendingFor(live.sessionId,agent.id,records),...squad?{squad}:{}};const input=buildAgentInput({...inputOptions,readThroughRecordId});live.lastRecordId=input.lastRecordId;const freshPrompt=nativeSessionId&&readThroughRecordId!==void 0?buildAgentInput(inputOptions).prompt:void 0;live.offeredFreshPrompt=freshPrompt!==void 0;await this.persist(state);this.publish(live);return{protocol:HOST_PROTOCOL_VERSION,sessionId:live.sessionId,runId:run.id,attempt:lease.attempt,leaseId:lease.leaseId,leaseExpiresAt:lease.expiresAt,agent:{...this.authorOf(live),...persona},program,prompt:input.prompt,...freshPrompt!==void 0?{freshPrompt}:{},...nativeSessionId?{nativeSessionId}:{}}}catch(error){await this.finishRun(state,live,{status:"failed",outputText:"",error:getErrorMessage(error)})}}return void 0}renewLease(hostId,runId,attempt,leaseId){const fenced=this.fence(hostId,runId,attempt,leaseId);if(!fenced.ok)return fenced;const lease=fenced.live.run.lease;lease.expiresAt=this.now()+this.leaseMs;return{ok:true,leaseExpiresAt:lease.expiresAt}}releaseHostAssignment(hostId,assignment){const fenced=this.fence(hostId,assignment.runId,assignment.attempt,assignment.leaseId,assignment.sessionId);if(!fenced.ok)return fenced;const{live}=fenced;live.run.status="queued";delete live.run.lease;delete live.run.startedAt;delete live.remote;live.author={...live.author};delete live.author.runtimeId;delete live.frame.permission;delete live.frame.outputText;delete live.frame.thoughtText;delete live.frame.steps;live.steps.clear();const state=this.states.get(live.sessionId);if(state)void this.persist(state).catch(()=>{});this.publish(live);this.republishQueued(live.run.agentId);return{ok:true}}acceptHostEvents(hostId,batch){const fenced=this.fence(hostId,batch.runId,batch.attempt,batch.leaseId,batch.sessionId);if(!fenced.ok)return fenced;const{live}=fenced;const lease=live.run.lease;if(batch.sequence<=(lease.lastSequence??0)){return{ok:true,duplicate:true}}lease.lastSequence=batch.sequence;lease.expiresAt=this.now()+this.leaseMs;const state=this.states.get(live.sessionId);if(state){this.dirty.add(state);for(const event of batch.events)this.applyEvent(state,live,event)}return{ok:true,leaseExpiresAt:lease.expiresAt}}async completeHostTurn(hostId,result){const fenced=this.fence(hostId,result.runId,result.attempt,result.leaseId,result.sessionId);if(!fenced.ok)return fenced;const state=await this.session(result.sessionId);await fenced.live.sendChain;await this.finishRun(state,fenced.live,{status:result.result.status,outputText:result.result.outputText,...result.result.error?{error:result.result.error}:{},...result.result.nativeSessionId?{nativeSessionId:result.result.nativeSessionId}:{},...result.result.totalTokens!==void 0?{totalTokens:result.result.totalTokens}:{},...result.result.resumeRejected?{resumeRejected:true}:{}});return{ok:true}}decisionsForHost(hostId){const decisions=[];for(const live of this.live.values()){if(live.remote?.hostId!==hostId)continue;decisions.push(...live.remote.decisions)}return decisions}async endRunsForRemovedHost(hostId,agentsMadeLocal){await this.recovered;const madeLocal=new Set(agentsMadeLocal);const stranded=[...this.live.values()].filter(live=>live.remote?.hostId===hostId||live.run.status==="queued"&&madeLocal.has(live.run.agentId));for(const live of stranded){const state=await this.session(live.sessionId);await this.finishRun(state,live,{status:"offline",outputText:live.frame.outputText??"",error:SESSION_AGENT_HOST_REMOVED_ERROR,...live.run.status==="queued"?{totalTokens:0}:{}})}return stranded.length}sweep(){const now=this.now();for(const state of this.dirty)void this.persist(state).catch(()=>{});this.dirty.clear();for(const[runId,cancelled]of[...this.cancelledLeases]){if(now-cancelled.at>CANCELLED_LEASE_TTL_MS){this.cancelledLeases.delete(runId)}}for(const live of[...this.live.values()]){if(!isExecutingRun(live.run))continue;if(live.remote){const lease=live.run.lease;if(lease&&lease.expiresAt<now){void this.session(live.sessionId).then(state=>this.finishRun(state,live,{status:"offline",outputText:live.frame.outputText??"",error:SESSION_AGENT_OFFLINE_ERROR}))}continue}if(live.frame.permission)continue;if(now-live.frame.activityAt>=this.stallTimeoutMs){live.abortReason="stalled";live.controller?.abort()}}}assertRunning(){if(this.stopped){throw new SessionAgentError(503,"orchestrator_stopped","Session agents are stopping in this workspace.")}}session(sessionId){let state=this.sessions.get(sessionId);if(!state){state=this.recovered.then(async()=>{const recovered=this.startupStates.get(sessionId);if(recovered)return recovered;const file=await readSessionAgents(this.workspaceCwd,sessionId);return this.adopt(file,void 0)});this.sessions.set(sessionId,state);state.catch(()=>{if(this.sessions.get(sessionId)===state){this.sessions.delete(sessionId)}})}return state}adopt(file,roster){const state={sessionId:file.sessionId,file,writeChain:Promise.resolve()};this.states.set(file.sessionId,state);const now=this.now();let changed=false;const authorOf2=__name(run=>{const agent=roster?.find(candidate=>candidate.id===run.agentId);return agent?authorFor(agent,agent.execution?.mode==="managed-host"?void 0:LOCAL_SESSION_AGENT_RUNTIME_ID,programForAgent(agent)):{agentId:run.agentId,name:run.agentId}},"authorOf");for(const run of file.runs){if(isTerminalSessionAgentRunStatus(run.status)){if(run.status==="cancelled"&&run.lease&&now-(run.endedAt??run.createdAt)<=CANCELLED_LEASE_TTL_MS){this.rememberCancelledLease(file.sessionId,run)}if(run.recorded===false&&!this.settled.has(run.id)){if(this.adoptUnrecorded(file,run,authorOf2(run),now)){changed=true}}continue}if(this.live.has(run.id))continue;const agent=roster?.find(candidate=>candidate.id===run.agentId);const remoteAgent=agent!==void 0&&agent.execution?.mode==="managed-host";if(run.status==="queued"&&remoteAgent){this.live.set(run.id,this.newLive(file.sessionId,run,agent));continue}if(run.status==="running"&&run.lease&&remoteAgent){const live=this.newLive(file.sessionId,run,agent);const program=programForAgent(agent)??"qwen";live.author=authorFor(agent,run.lease.hostId,program);live.remote={hostId:run.lease.hostId,program,decisions:[]};run.lease.expiresAt=now+this.leaseMs;this.live.set(run.id,live);changed=true;continue}if(run.lease)this.rememberCancelledLease(file.sessionId,run);run.status="failed";run.error=SESSION_AGENT_RESTARTED_ERROR;run.endedAt=now;run.recorded=false;delete run.lease;changed=true;this.addSettled(run.id,{sessionId:file.sessionId,frame:{type:"run",sessionId:file.sessionId,runId:run.id,author:authorOf2(run),status:"failed",error:SESSION_AGENT_RESTARTED_ERROR,activityAt:now,recorded:false,retryable:true}})}this.restorePendingWakes(state,roster);if(this.settleEngagements(state))changed=true;if(changed)void this.persist(state).catch(()=>{});return state}adoptUnrecorded(file,run,author,now){if(run.status==="cancelled"||file.runs.some(candidate=>candidate.retryOf===run.id)){delete run.recorded;return true}const wroteRecord=run.status!=="offline"&&!Object.values(SESSION_AGENT_STOPPED_ERRORS).includes(run.error??"");this.addSettled(run.id,{sessionId:file.sessionId,frame:{type:"run",sessionId:file.sessionId,runId:run.id,author,status:run.status,error:run.error??SESSION_AGENT_REPLY_NOT_RECORDED_ERROR,...run.totalTokens!==void 0?{totalTokens:run.totalTokens}:{},activityAt:run.endedAt??now,recorded:false,retryable:true},...wroteRecord?{recovered:true}:{}});if(wroteRecord)this.watchRecord(run.id);return false}restorePendingWakes(state,roster){if(!roster)return;for(const[squadId,engagement]of Object.entries(state.file.squads??{})){if(!engagement.active||!engagement.pendingWakeRunIds)continue;const leader=roster.find(agent=>agent.id===engagement.leaderAgentId);if(!leader||!isAgentAddressable(leader)){writeStderrLine(`qwen serve: squad ${squadId} in session ${state.sessionId} lost its leader across a restart; its pending wake was dropped.`);continue}for(const runId of engagement.pendingWakeRunIds){const settled=this.settled.get(runId);const run=state.file.runs.find(candidate=>candidate.id===runId);if(!run||!settled?.recovered)continue;if(settled.sessionId!==state.sessionId)continue;const wakes=settled.wakes??=[];if(wakes.some(wake=>wake.squadId===squadId))continue;wakes.push({squadId,leader,chainDepth:nextChainDepth({kind:"agent",chainDepth:run.chainDepth})})}}}async recoverOnStartup(){const ids=await listSessionAgentsSessionIds(this.workspaceCwd);if(ids.length===0)return;let roster;for(const sessionId of ids){let file;try{file=await readSessionAgents(this.workspaceCwd,sessionId)}catch(error){writeStderrLine(`qwen serve: skipping unreadable session agents file for ${sessionId}: ${getErrorMessage(error)}`);continue}if(file.runs.every(run=>isTerminalSessionAgentRunStatus(run.status)&&!(run.status==="cancelled"&&run.lease)&&run.recorded!==false)){continue}roster??=await this.readAgents(this.workspaceCwd);const state=this.adopt(file,roster);this.startupStates.set(sessionId,state);if(!this.sessions.has(sessionId)){this.sessions.set(sessionId,Promise.resolve(state))}}}newLive(sessionId,run,agent){const maxConcurrent=maxConcurrentRunsFor(agent);const author=authorFor(agent,agent.execution?.mode==="managed-host"?void 0:LOCAL_SESSION_AGENT_RUNTIME_ID,programForAgent(agent));return{sessionId,run,author,maxConcurrent,frame:{type:"run",sessionId,runId:run.id,author,status:run.status,activityAt:this.now()},steps:new Map,pendingPermissions:new Map,voterContexts:new Map,sendCount:0,sendChain:Promise.resolve()}}enqueue(state,agent,recordId,chainDepth,squadId){const squad=squadId??this.activeSquadLedBy(state,agent.id);const outcome=enqueueTrigger(state.file.runs,{agentId:agent.id,recordId,chainDepth,now:this.now(),newRunId:__name(()=>`sr_${randomUUID3()}`,"newRunId"),...squad?{squadId:squad}:{}});let live=this.live.get(outcome.run.id);if(!live){live=this.newLive(state.sessionId,outcome.run,agent);this.live.set(outcome.run.id,live)}this.publish(live);return{runId:outcome.run.id,agentId:agent.id,status:outcome.run.status}}executingCount(agentId){let count=0;for(const live of this.live.values()){if(live.run.agentId===agentId&&isExecutingRun(live.run))count+=1}return count}pumpAgent(agentId){if(this.stopped)return;const queued=[...this.live.values()].filter(live=>live.run.agentId===agentId&&live.run.status==="queued"&&live.author.runtimeId===LOCAL_SESSION_AGENT_RUNTIME_ID).sort((a,b)=>a.run.createdAt-b.run.createdAt);for(const live of queued){if(this.executingCount(agentId)>=live.maxConcurrent)break;const state=this.states.get(live.sessionId);if(!state)continue;if(nextRunnable(state.file.runs,agentId)?.id!==live.run.id)continue;void this.runLocal(state,live).catch(error=>{writeStderrLine(`qwen serve: session agent run ${live.run.id} crashed: ${getErrorMessage(error)}`)})}this.republishQueued(agentId)}republishQueued(agentId){for(const live of this.live.values()){if(live.run.agentId===agentId&&live.run.status==="queued"){this.publish(live)}}}async runLocal(state,live){const{run}=live;run.status="running";run.startedAt=this.now();run.attempts+=1;delete run.error;const controller=new AbortController;live.controller=controller;live.frame.activityAt=this.now();this.publish(live);let outcome;try{const roster=await this.readAgents(this.workspaceCwd);const agent=roster.find(candidate=>candidate.id===run.agentId);if(!agent||!isAgentAddressable(agent)){throw new Error("This agent is disabled or no longer exists.")}if(agent.execution?.mode==="managed-host"){throw new Error("This agent now runs on a remote runtime.")}const program=programForAgent(agent);live.author=authorFor(agent,LOCAL_SESSION_AGENT_RUNTIME_ID,program);live.maxConcurrent=maxConcurrentRunsFor(agent);const persona=program==="qwen"?{...agent.instructions?{instructions:agent.instructions}:{},...agent.model?{model:agent.model}:{}}:await resolveTurnPersona(agent,program,name=>this.loadDefinition(this.workspaceCwd,name));const binding=state.file.bindings[agent.id]??{agentId:agent.id};const records=await this.loadRecords(state.sessionId);const squad=await this.squadBriefingFor(live,roster);const sameNativeSession=canReuseNativeSession(binding,LOCAL_SESSION_AGENT_RUNTIME_ID,program);const resumable=sameNativeSession&&binding.runtimeId===LOCAL_SESSION_AGENT_RUNTIME_ID?binding.nativeSessionId:void 0;const nativeSessionId=program==="qwen"?sessionAgentNativeSessionId(agent.id,state.sessionId):resumable;const readThroughRecordId=sameNativeSession?binding.readThroughRecordId:void 0;const inputOptions={records,trigger:{agentId:agent.id,agentName:agent.name,recordIds:run.triggerRecordIds},budgetChars:AGENT_INPUT_CHAR_BUDGET,pendingMessages:this.pendingFor(state.sessionId,agent.id,records),...squad?{squad}:{}};const input=buildAgentInput({...inputOptions,readThroughRecordId});live.lastRecordId=input.lastRecordId;const freshPrompt=nativeSessionId&&readThroughRecordId!==void 0?buildAgentInput(inputOptions).prompt:void 0;live.offeredFreshPrompt=freshPrompt!==void 0;state.file.bindings[agent.id]={...binding,agentId:agent.id,...nativeSessionId?{nativeSessionId,runtimeId:LOCAL_SESSION_AGENT_RUNTIME_ID}:{}};await this.persist(state);if(controller.signal.aborted)throw new Error("cancelled");const sessionSend={isCurrent:__name(()=>this.sendTokenIsCurrent(state.sessionId,agent.id),"isCurrent"),rotate:__name(()=>this.rotateSendToken(state.sessionId,agent.id),"rotate")};const sessionSendServer=program==="qwen"?void 0:this.rotateSendToken(state.sessionId,agent.id);const adapter=this.adapterFor(program,{workspaceCwd:this.workspaceCwd,bridge:this.bridge,agentId:agent.id,permissionVoteContext:__name(requestId=>live.voterContexts.get(requestId),"permissionVoteContext"),sessionSend});const result=await adapter.runTurn({prompt:input.prompt,...freshPrompt!==void 0?{freshPrompt}:{},...persona,...nativeSessionId?{nativeSessionId}:{},cwd:this.workspaceCwd,...sessionSendServer?{sessionSendServer}:{},signal:controller.signal,onEvent:__name(event=>this.applyEvent(state,live,event),"onEvent"),awaitPermission:__name(prompt=>this.awaitPermission(live,prompt),"awaitPermission")});outcome={status:result.status,outputText:result.outputText,...result.error?{error:result.error}:{},...result.nativeSessionId?{nativeSessionId:result.nativeSessionId}:{},...result.totalTokens!==void 0?{totalTokens:result.totalTokens}:{},...result.resumeRejected?{resumeRejected:true}:{}}}catch(error){outcome={status:controller.signal.aborted?"cancelled":"failed",outputText:live.frame.outputText??"",error:getErrorMessage(error)}}if(live.abortReason==="stalled"){outcome={...outcome,status:"failed",error:SESSION_AGENT_STALLED_ERROR}}else if(live.abortReason==="cancelled"){outcome={...outcome,status:"cancelled"};delete outcome.error}else if(live.abortReason==="shutdown"){outcome={...outcome,status:"failed",error:this.stoppedError}}await live.sendChain;await this.finishRun(state,live,outcome)}awaitPermission(live,prompt){return new Promise((resolve2,reject)=>{if(live.controller?.signal.aborted){reject(new Error("cancelled"));return}live.pendingPermissions.set(prompt.requestId,{resolve:resolve2,reject})})}applyEvent(state,live,event){if(isTerminalSessionAgentRunStatus(live.run.status))return;if(live.abortReason&&event.type!=="usage"&&event.type!=="native_session"){return}const frame=live.frame;frame.activityAt=this.now();switch(event.type){case"native_session":live.nativeSessionId=event.nativeSessionId;break;case"text_delta":frame.outputText=((frame.outputText??"")+event.text).slice(-MAX_OUTPUT_CHARS);break;case"thought_delta":frame.thoughtText=((frame.thoughtText??"")+event.text).slice(-MAX_THOUGHT_CHARS);break;case"step":live.steps.set(event.step.id,event.step);for(const id of live.steps.keys()){if(live.steps.size<=MAX_RUN_STEPS)break;live.steps.delete(id)}frame.steps=[...live.steps.values()].slice(-MAX_FRAME_STEPS);break;case"permission_request":frame.permission=event.prompt;live.run.status="awaiting_approval";void this.persist(state).catch(()=>{});break;case"permission_resolved":if(frame.permission?.requestId===event.requestId){delete frame.permission;live.run.status="running";void this.persist(state).catch(()=>{})}live.pendingPermissions.delete(event.requestId);live.voterContexts.delete(event.requestId);if(live.remote){live.remote.decisions=live.remote.decisions.filter(decision=>decision.requestId!==event.requestId)}break;case"usage":live.totalTokens=event.totalTokens;frame.totalTokens=event.totalTokens;break;case"session_send":void this.queueSessionSend(state,live,event.text).catch(()=>{});break;default:{const exhaustive=event;void exhaustive}}this.publish(live)}queueSessionSend(state,live,text){const done=live.sendChain.then(()=>this.handleSessionSend(state,live,text));live.sendChain=done.catch(error=>{live.frame.error=getErrorMessage(error);this.publish(live)});return done}async handleSessionSend(state,live,text){if(isBlankAgentText(text))return;if(text.length>MAX_MENTION_TEXT_CHARS){throw new SessionAgentError(400,"invalid_text",`A session_send post of ${text.length.toLocaleString("en-US")} characters was not posted: the limit is ${MAX_MENTION_TEXT_CHARS.toLocaleString("en-US")}.`)}const roster=await this.readAgents(this.workspaceCwd);const targets=resolveMentionTargetsWithSquads(text,roster,await this.loadSquads(),live.run.agentId);const squadTargets=this.agentSquadTargets(state,live.run.agentId,targets.squads,roster);assertMentionFitsRecord(targets.agents.length,squadTargets.length);const squadError=targets.unavailableSquads.length>0?squadUnavailableError(targets.unavailableSquads):void 0;const postError=joinErrors(squadError,targets.agents.length===0&&squadTargets.length===0?unreachedAgentsError(targets.unavailable,targets.unknown):void 0);const squadMembers=await this.squadMembersFor(live);live.sendCount+=1;const recordKey=`send:${live.run.id}:${live.sendCount}`;let record;try{record=await this.appendRecord(state.sessionId,{kind:"agent_mention",recordKey,modelText:formatAgentMentionModelText(text,[...targets.agents.map(agent=>agent.name),...squadTargets.map(({squad})=>squad.name)],{authorName:live.author.name}),payload:{displayText:text,mentionedAgentIds:targets.agents.map(agent=>agent.id),...squadTargets.length>0?{mentionedSquadIds:squadTargets.map(({squad})=>squad.id)}:{},author:live.author,...postError?{error:postError}:{}}})}catch(error){throw recordWriteError(error)}if(postError){live.frame.error=postError;this.publish(live)}const triggerId=triggerIdFor(record,recordKey);if(record.deferred){this.addPendingPost({sessionId:state.sessionId,id:triggerId,kind:"agent_mention",speaker:`${live.author.name} (agent)`,text,authorAgentId:live.run.agentId,createdAt:this.now()})}const limitError=this.routeMentions(state,live,targets.agents,triggerId,squadMembers,squadTargets);if(limitError){live.frame.error=limitError;this.publish(live)}}routeMentions(state,author,agents,recordId,squadMembers,squads=[]){if(agents.length===0&&squads.length===0||this.stopped){return void 0}const names=[...agents.map(agent=>agent.name),...squads.map(({squad})=>squad.name)];const depth=nextChainDepth({kind:"agent",chainDepth:author.run.chainDepth});const limit=normalizeAgentChainLimit(this.chainLimit());if(!isWithinChainLimit(depth,limit)){return chainLimitError(limit,names)}const budget=normalizeAgentTokenBudget(this.tokenBudget());if(!isWithinTokenBudget(state.file.chainTokens??0,budget)){return tokenBudgetError(budget,names)}for(const{squad,leader}of squads){this.startEngagement(state,squad,recordId);this.enqueue(state,leader,recordId,depth,squad.id)}for(const agent of agents){const summary=this.enqueue(state,agent,recordId,depth);if(squadMembers?.has(agent.id)){this.trackDelegation(state,author.run.squadId,summary.runId)}}void this.persist(state).catch(()=>{}).then(()=>{for(const{leader}of squads)this.pumpAgent(leader.id);for(const agent of agents)this.pumpAgent(agent.id)});return void 0}async cancelLive(state,live){const{run}=live;if(isTerminalSessionAgentRunStatus(run.status))return;if(run.status==="queued"){run.status="cancelled";run.endedAt=this.now();this.live.delete(run.id);this.releaseOutstanding(state,run.id);this.settleEngagements(state);this.publish(live);this.hub.forgetRun(state.sessionId,run.id);this.republishQueued(run.agentId);await this.persist(state).catch(()=>{});return}if(live.remote){this.rememberCancelledLease(state.sessionId,run);await live.sendChain;await this.finishRun(state,live,{status:"cancelled",outputText:live.frame.outputText??""});return}live.abortReason="cancelled";for(const pending of live.pendingPermissions.values()){pending.reject(new Error("cancelled"))}live.pendingPermissions.clear();if(live.frame.permission||run.status==="awaiting_approval"){delete live.frame.permission;run.status="running";this.publish(live)}live.controller?.abort()}async finishRun(state,live,outcome){const{run}=live;if(isTerminalSessionAgentRunStatus(run.status))return;run.status=outcome.status;run.endedAt=this.now();const runtimeId=live.remote?.hostId??LOCAL_SESSION_AGENT_RUNTIME_ID;for(const pending of live.pendingPermissions.values()){pending.reject(new Error("run ended"))}live.pendingPermissions.clear();const replyText=!isBlankAgentText(outcome.outputText)?outcome.outputText:outcome.status==="completed"?"":live.frame.outputText??"";const displayText=isBlankAgentText(replyText)?"":clipReplyText(replyText);const retryable=outcome.status==="offline"||live.abortReason==="shutdown";const nativeSessionId=outcome.nativeSessionId??live.nativeSessionId;const totalTokens=outcome.totalTokens??live.totalTokens;const chargedTokens=totalTokens??UNREPORTED_TURN_TOKENS;let followUps=[];let squadFollowUps=[];let error=outcome.error;if(outcome.status==="completed"&&displayText.trim()&&!this.stopped){try{const roster=await this.readAgents(this.workspaceCwd);const targets=resolveMentionTargetsWithSquads(displayText,roster,await this.loadSquads(),run.agentId);followUps=targets.agents;squadFollowUps=this.agentSquadTargets(state,run.agentId,targets.squads,roster);if(targets.unavailableSquads.length>0){error=joinErrors(error,squadUnavailableError(targets.unavailableSquads))}const names=[...followUps.map(agent=>agent.name),...squadFollowUps.map(({squad})=>squad.name)];const depth=nextChainDepth({kind:"agent",chainDepth:run.chainDepth});const limit=normalizeAgentChainLimit(this.chainLimit());const budget=normalizeAgentTokenBudget(this.tokenBudget());const spent=(state.file.chainTokens??0)+chargedTokens;if(names.length>0&&!isWithinChainLimit(depth,limit)){error=joinErrors(error,chainLimitError(limit,names));followUps=[];squadFollowUps=[]}else if(names.length>0&&!isWithinTokenBudget(spent,budget)){error=joinErrors(error,tokenBudgetError(budget,names));followUps=[];squadFollowUps=[]}}catch(routeError){error=`Could not route mentions: ${getErrorMessage(routeError)}`;followUps=[];squadFollowUps=[]}}const squadMembers=followUps.length>0?await this.squadMembersFor(live):void 0;const wakes=[];const waiting=this.releaseOutstanding(state,run.id);if(!run.squadId&&waiting.length>0)live.memberSquadId=waiting[0];const memberSquadName=live.memberSquadId?this.squadNames.get(live.memberSquadId):void 0;if(waiting.length>0&&outcome.status!=="cancelled"&&!this.stopped){try{const roster=await this.readAgents(this.workspaceCwd);const depth=nextChainDepth({kind:"agent",chainDepth:run.chainDepth});const limit=normalizeAgentChainLimit(this.chainLimit());const budget=normalizeAgentTokenBudget(this.tokenBudget());const spent=(state.file.chainTokens??0)+chargedTokens;for(const squadId of waiting){const leaderId=state.file.squads?.[squadId]?.leaderAgentId;const leader=roster.find(agent=>agent.id===leaderId);if(!leader||!isAgentAddressable(leader)){error=joinErrors(error,`Squad @${this.squadNames.get(squadId)??squadId} stops here: its leader is unavailable.`)}else if(!isWithinChainLimit(depth,limit)){error=joinErrors(error,chainLimitError(limit,[leader.name]))}else if(!isWithinTokenBudget(spent,budget)){error=joinErrors(error,tokenBudgetError(budget,[leader.name]))}else{wakes.push({squadId,leader})}}}catch(wakeError){error=joinErrors(error,`Could not wake the squad leader: ${getErrorMessage(wakeError)}`)}}const payload={displayText,author:{...this.authorOf(live),runtimeId,...memberSquadName?{memberSquadName}:{}},runId:run.id,status:outcome.status,...error?{error}:{},...live.steps.size>0?{steps:recordSteps(live.steps.values())}:{},...nativeSessionId?{nativeSessionId}:{},...totalTokens!==void 0?{totalTokens}:{},...run.triggerRecordIds.length>0?{triggerRecordId:run.triggerRecordIds.at(-1)}:{},...run.squadId&&outcome.status==="completed"&&displayText.trim().length===0?{squadOutcome:"no_action"}:{}};let recordId;let landedRecordId;const recordKey=`agent:${run.id}`;const request={kind:"agent_message",recordKey,modelText:formatAgentMessageModelText(payload),payload};let watch=false;if(!retryable){try{const written=await this.appendRecord(state.sessionId,request);recordId=triggerIdFor(written,recordKey);if(written.deferred||!written.recordId){watch=true;if(displayText.trim()){this.addPendingPost({sessionId:state.sessionId,id:recordId,kind:"agent_message",speaker:`${live.author.name} (agent)`,text:displayText,authorAgentId:run.agentId,runId:run.id,createdAt:this.now()})}}else{landedRecordId=written.recordId}}catch(writeError){const refusal=recordWriteError(writeError);error=`Could not record the reply: ${refusal.message}`;followUps=[];squadFollowUps=[];watch=refusal.code!=="managed_session_unsupported"}}const nextDepth=nextChainDepth({kind:"agent",chainDepth:run.chainDepth});let wakeTrigger=recordId;if(!wakeTrigger&&wakes.length>0&&!watch){wakeTrigger=this.addUnrecordedReply(state.sessionId,run.id,this.authorOf(live),displayText,error)}const binding=state.file.bindings[run.agentId]??{agentId:run.agentId};if(nativeSessionId){binding.nativeSessionId=nativeSessionId;binding.runtimeId=runtimeId;if(live.author.program)binding.program=live.author.program}if(outcome.resumeRejected&&!live.offeredFreshPrompt){delete binding.readThroughRecordId}else if(outcome.status==="completed"&&live.lastRecordId){binding.readThroughRecordId=live.lastRecordId}state.file.bindings[run.agentId]=binding;if(error)run.error=error;else delete run.error;if(landedRecordId)run.recorded=true;else if(watch||retryable)run.recorded=false;else delete run.recorded;if(totalTokens!==void 0)run.totalTokens=totalTokens;state.file.chainTokens=(state.file.chainTokens??0)+chargedTokens;if(!(outcome.status==="cancelled"&&live.remote))delete run.lease;state.file.runs=trimTerminalRuns(state.file.runs);live.frame.error=error;if(!error)delete live.frame.error;delete live.frame.permission;if(landedRecordId){live.frame.recorded=true;live.frame.recordId=landedRecordId}else if(watch||retryable){live.frame.recorded=false}if(retryable)live.frame.retryable=true;this.publish(live);this.hub.forgetRun(state.sessionId,run.id);this.live.delete(run.id);if(retryable){this.addSettled(run.id,{sessionId:state.sessionId,frame:this.buildFrame(live)})}else if(watch){this.addSettled(run.id,{sessionId:state.sessionId,frame:this.buildFrame(live),request,...payload.error?{recordedError:payload.error}:{},...!wakeTrigger&&wakes.length>0?{wakes:wakes.map(({squadId,leader})=>({squadId,leader,chainDepth:nextDepth}))}:{}});this.watchRecord(run.id)}if(recordId){for(const{squad,leader}of squadFollowUps){this.startEngagement(state,squad,recordId);this.enqueue(state,leader,recordId,nextDepth,squad.id)}for(const agent of followUps){const summary=this.enqueue(state,agent,recordId,nextDepth);if(squadMembers?.has(agent.id)){this.trackDelegation(state,run.squadId,summary.runId)}}}if(wakeTrigger){for(const{squadId,leader}of wakes){this.enqueue(state,leader,wakeTrigger,nextDepth,squadId)}}this.settleEngagements(state);await this.persist(state).catch(()=>{});this.pumpAgent(run.agentId);for(const{leader}of squadFollowUps)this.pumpAgent(leader.id);for(const agent of followUps)this.pumpAgent(agent.id);if(wakeTrigger)for(const{leader}of wakes)this.pumpAgent(leader.id)}addUnrecordedReply(sessionId,runId,author,displayText,error){const id=`pending:unrecorded:${runId}`;const note=error?`[This reply is not in the conversation record: ${error}]`:"[This reply is not in the conversation record.]";this.addPendingPost({sessionId,id,kind:"agent_message",speaker:`${author.name} (agent)`,text:`${displayText.trim()?displayText:"(no reply text)"}
|
|
16
|
+
${close}`,lastRecordId:records.at(-1)?.uuid??readThroughRecordId,omittedCount,cursorLost}}__name(buildAgentInput,"buildAgentInput");init_esbuild_shims();var RUN_FRAME_THROTTLE_MS=100;var SessionAgentEventHub=class{constructor(throttleMs=RUN_FRAME_THROTTLE_MS){this.throttleMs=throttleMs}static{__name(this,"SessionAgentEventHub")}subscribers=new Set;pending=new Map;deliveredStatus=new Map;subscribe(listener,sessionId){const subscriber={listener,sessionId};this.subscribers.add(subscriber);return()=>{this.subscribers.delete(subscriber)}}publish(frame,options={}){if(frame.type!=="run"){this.deliver(frame);return}const key=`${frame.sessionId}\0${frame.runId}`;const existing=this.pending.get(key);const statusChanged=options.immediate===true||this.deliveredStatus.get(key)!==frameStateKey(frame);if(statusChanged){if(existing)clearTimeout(existing.timer);this.pending.delete(key);this.deliverRun(key,frame);return}if(existing){existing.frame=frame;return}const timer=setTimeout(()=>{const entry=this.pending.get(key);this.pending.delete(key);if(entry)this.deliverRun(key,entry.frame)},this.throttleMs);timer.unref?.();this.pending.set(key,{frame,timer})}forgetRun(sessionId,runId){const key=`${sessionId}\0${runId}`;const entry=this.pending.get(key);if(entry){clearTimeout(entry.timer);this.pending.delete(key);this.deliverRun(key,entry.frame)}this.deliveredStatus.delete(key)}dispose(){for(const entry of this.pending.values())clearTimeout(entry.timer);this.pending.clear();this.deliveredStatus.clear();this.subscribers.clear()}deliverRun(key,frame){this.deliveredStatus.set(key,frameStateKey(frame));this.deliver(frame)}deliver(frame){for(const subscriber of[...this.subscribers]){if(frame.type==="run"&&subscriber.sessionId!==void 0&&subscriber.sessionId!==frame.sessionId){continue}try{subscriber.listener(frame)}catch{}}}};var hubs=new Map;function getSessionAgentEventHub(workspaceCwd){let hub=hubs.get(workspaceCwd);if(!hub){hub=new SessionAgentEventHub;hubs.set(workspaceCwd,hub)}return hub}__name(getSessionAgentEventHub,"getSessionAgentEventHub");function frameStateKey(frame){return[frame.status,frame.recorded===void 0?"":String(frame.recorded),frame.permission?.requestId??"",frame.retryable?"retryable":""].join("|")}__name(frameStateKey,"frameStateKey");init_esbuild_shims();function isExecutingRun(run){return run.status==="running"||run.status==="awaiting_approval"}__name(isExecutingRun,"isExecutingRun");function isQueuedRun(run){return run.status==="queued"}__name(isQueuedRun,"isQueuedRun");function enqueueTrigger(runs2,input){const live=runs2.filter(run2=>run2.agentId===input.agentId&&(isQueuedRun(run2)||isExecutingRun(run2)));const duplicate=live.find(run2=>run2.triggerRecordIds.includes(input.recordId));if(duplicate)return{kind:"duplicate",run:duplicate};const queued=live.find(isQueuedRun);if(queued){queued.triggerRecordIds.push(input.recordId);queued.chainDepth=coalesceChainDepth(queued.chainDepth,input.chainDepth);if(input.squadId!==void 0)queued.squadId??=input.squadId;return{kind:"coalesced",run:queued}}const run={id:input.newRunId(),agentId:input.agentId,status:"queued",triggerRecordIds:[input.recordId],chainDepth:input.chainDepth,createdAt:input.now,attempts:0,...input.squadId!==void 0?{squadId:input.squadId}:{}};runs2.push(run);return{kind:"created",run}}__name(enqueueTrigger,"enqueueTrigger");function nextRunnable(runs2,agentId){const mine=runs2.filter(run=>run.agentId===agentId);if(mine.some(isExecutingRun))return void 0;return mine.filter(isQueuedRun).sort((a,b)=>a.createdAt-b.createdAt)[0]}__name(nextRunnable,"nextRunnable");function queuePosition(runs2,run){if(!isQueuedRun(run))return void 0;const queued=runs2.filter(candidate=>candidate.agentId===run.agentId&&isQueuedRun(candidate)).sort((a,b)=>a.createdAt-b.createdAt);const index=queued.findIndex(candidate=>candidate.id===run.id);return index===-1?void 0:index+1}__name(queuePosition,"queuePosition");var LOCAL_SESSION_AGENT_RUNTIME_ID="local";var SESSION_AGENT_STALL_TIMEOUT_MS=15*6e4;var SESSION_AGENT_STALLED_ERROR="agent_run_stalled";var SESSION_AGENT_RESTARTED_ERROR="daemon restarted";var SESSION_AGENT_STOPPED_ERRORS={shutdown:SESSION_AGENT_RESTARTED_ERROR,runtime_replaced:"stopped: the workspace runtime was restarted",workspace_closed:"stopped: the workspace was closed",workspace_untrusted:"stopped: the workspace is no longer trusted",collaboration_disabled:"stopped: agent collaboration was turned off"};var SESSION_AGENT_OFFLINE_ERROR="runtime went offline";var SESSION_AGENT_HOST_REMOVED_ERROR="its Agent Host was removed";var SESSION_AGENT_REPLY_NOT_RECORDED_ERROR="the reply was not recorded before the daemon stopped";var HOST_TURN_LEASE_MS=6e4;var SWEEP_INTERVAL_MS=5e3;var MAX_OUTPUT_CHARS=MAX_AGENT_MESSAGE_DISPLAY_TEXT_CHARS;var MAX_THOUGHT_CHARS=65536;var MAX_FRAME_STEPS=8;var MAX_RUN_STEPS=MAX_AGENT_MESSAGE_STEPS;var CLIENT_MESSAGE_ID_PATTERN=/^[A-Za-z0-9_.:-]{1,128}$/;var MAX_MENTION_TEXT_CHARS=MAX_EXTERNAL_RECORD_TEXT_LENGTH;var CLIPPED_REPLY_NOTE="\n\n[Reply truncated.]";var UNREPORTED_TURN_TOKENS=1e4;var PENDING_POST_TTL_MS=60*6e4;var RECORD_WATCH_INITIAL_MS=1e3;var RECORD_WATCH_MAX_INTERVAL_MS=15e3;var RECORD_WATCH_MAX_MS=PENDING_POST_TTL_MS;var RECORD_RECOVERY_WATCH_MAX_MS=3e4;var MAX_SETTLED_RUNS=200;var CANCELLED_LEASE_TTL_MS=10*6e4;var SessionAgentError=class extends Error{constructor(status,code,message,details){super(message);this.status=status;this.code=code;this.details=details;this.name="SessionAgentError"}static{__name(this,"SessionAgentError")}};function clipReplyText(text){if(text.length<=MAX_AGENT_MESSAGE_DISPLAY_TEXT_CHARS)return text;let end=MAX_AGENT_MESSAGE_DISPLAY_TEXT_CHARS-CLIPPED_REPLY_NOTE.length;const last=text.charCodeAt(end-1);if(last>=55296&&last<=56319)end-=1;return text.slice(0,end)+CLIPPED_REPLY_NOTE}__name(clipReplyText,"clipReplyText");function recordSteps(steps){return[...steps].filter(step=>step.id.length<=MAX_EXTERNAL_RECORD_ID_LENGTH).slice(-MAX_AGENT_MESSAGE_STEPS).map(step=>step.title.length>MAX_EXTERNAL_RECORD_STEP_TITLE_LENGTH?{...step,title:step.title.slice(0,MAX_EXTERNAL_RECORD_STEP_TITLE_LENGTH)}:step)}__name(recordSteps,"recordSteps");function assertMentionFitsRecord(agents,squads){if(agents>MAX_EXTERNAL_RECORD_MENTION_IDS||squads>MAX_EXTERNAL_RECORD_MENTION_IDS){throw new SessionAgentError(400,"too_many_mentions",`A message can address at most ${MAX_EXTERNAL_RECORD_MENTION_IDS} agents and ${MAX_EXTERNAL_RECORD_MENTION_IDS} squads.`)}}__name(assertMentionFitsRecord,"assertMentionFitsRecord");function recordWriteError(error){const data=error?.data;const kind=typeof data==="object"&&data!==null?data.errorKind:void 0;const message=getErrorMessage(error);if(kind==="managed_session_unsupported"||message.includes("managed_session_unsupported")||message.includes("not supported in managed sessions")){return new SessionAgentError(400,"managed_session_unsupported","Session agents are not supported in managed sessions.")}return new SessionAgentError(502,"record_write_failed",message)}__name(recordWriteError,"recordWriteError");function triggerIdFor(response,recordKey){return response.deferred||!response.recordId?`pending:${recordKey}`:response.recordId}__name(triggerIdFor,"triggerIdFor");function programForAgent(agent,hostPrograms){if(agent.execution?.mode!=="managed-host"){return agent.execution?.provider??"qwen"}const provider=agent.execution.provider;if(!hostPrograms)return provider??"qwen";if(provider)return hostPrograms.includes(provider)?provider:void 0;return hostPrograms.includes("qwen")?"qwen":hostPrograms[0]}__name(programForAgent,"programForAgent");function authorFor(agent,runtimeId,program){return{agentId:agent.id,name:agent.name,...agent.color?{color:agent.color}:{},...program?{program}:{},...runtimeId?{runtimeId}:{}}}__name(authorFor,"authorFor");var LOOPBACK_HOSTNAMES=new Set(["127.0.0.1","localhost","[::1]","::1"]);function isLoopbackUrl(url){try{const parsed=new URL(url);return(parsed.protocol==="http:"||parsed.protocol==="https:")&&LOOPBACK_HOSTNAMES.has(parsed.hostname)}catch{return false}}__name(isLoopbackUrl,"isLoopbackUrl");function buildSessionSendServer(url,token){const cliEntry=process.env["QWEN_CLI_ENTRY"]||process.argv[1];if(!cliEntry)return void 0;const execArgv=process.execArgv.filter(arg=>!/^--(inspect|debug)/.test(arg));return{command:process.execPath,args:[...execArgv,cliEntry,"agents","session-send-mcp","--url",url],env:{QWEN_SESSION_SEND_TOKEN:token}}}__name(buildSessionSendServer,"buildSessionSendServer");function tokensMatch(expected,given){const a=Buffer.from(expected);const b=Buffer.from(given);return a.length===b.length&&timingSafeEqual(a,b)}__name(tokensMatch,"tokensMatch");function tokenBudgetError(budget,names){return`Agent token budget (${budget.toLocaleString("en-US")} tokens since your last message) reached; not started: ${names.map(name=>`@${name}`).join(", ")}. Post a message to continue.`}__name(tokenBudgetError,"tokenBudgetError");function unreachedAgentsError(unavailable,unknown){const reasons=[...unavailable.length>0?[`${unavailable.map(agent=>`@${agent.name}`).join(", ")} cannot run (paused or retired)`]:[],...unknown.length>0?[`${unknown.map(name=>`@${name}`).join(", ")} matched no agent`]:[]];return reasons.length>0?`This post reached no agent: ${reasons.join("; ")}.`:void 0}__name(unreachedAgentsError,"unreachedAgentsError");function squadUnavailableError(unavailable){return unavailable.map(({squad,reason})=>reason==="retired"?`Squad @${squad.name} is retired.`:reason==="leader_disabled"?`Squad @${squad.name} was not started: its leader is paused. Resume the leader or pick another one.`:`Squad @${squad.name} was not started: it needs a new leader (the leader agent was ${reason==="leader_retired"?"retired":"removed"}).`).join(" ")}__name(squadUnavailableError,"squadUnavailableError");var PROGRAM_LABELS={qwen:"Qwen Code",claude:"Claude Code",codex:"Codex"};function joinErrors(...errors){const present=errors.filter(error=>!!error);return present.length>0?present.join(" "):void 0}__name(joinErrors,"joinErrors");function chainLimitError(limit,names){return`Agent chain limit (${limit}) reached; not started: ${names.map(name=>`@${name}`).join(", ")}.`}__name(chainLimitError,"chainLimitError");async function defaultLoadDefinition(workspaceCwd,name){const{createDaemonSubagentManager}=await import("./workspace-agents-3YFBFAK3.js");return createDaemonSubagentManager(workspaceCwd).loadSubagent(name)}__name(defaultLoadDefinition,"defaultLoadDefinition");async function resolveTurnPersona(agent,program,loadDefinition){let definitionPrompt;let definitionModel;if(agent.agentType){const loaded=await loadDefinition(agent.agentType);if(!loaded){throw new Error(`Agent definition "${agent.agentType}" is unavailable.`)}if(loaded.executor!==void 0){throw new Error(`Agent definition "${agent.agentType}" declares an external executor, which a workspace Agent cannot use. Set execution.mode to "managed-host" on the Agent instead, or use a definition without an executor block.`)}if(program!=="qwen"&&(loaded.tools?.length&&!loaded.tools.includes("*")||loaded.disallowedTools?.length)){throw new Error(`Agent definition "${agent.agentType}" restricts tools, which the ${program} runtime cannot enforce. Use the Qwen runtime for this definition, or choose a definition without tool restrictions.`)}definitionPrompt=loaded.systemPrompt?.trim()||void 0;definitionModel=loaded.model?.trim()||void 0}const instructions=[definitionPrompt,agent.instructions?.trim()].filter(Boolean).join("\n\n");const model=agent.model??(program==="qwen"&&definitionModel&&definitionModel!=="inherit"?definitionModel:void 0);return{...instructions?{instructions}:{},...model?{model}:{}}}__name(resolveTurnPersona,"resolveTurnPersona");var SessionAgentOrchestrator=class{static{__name(this,"SessionAgentOrchestrator")}workspaceCwd;bridge;hub;chainLimit;tokenBudget;readAgents;readSquads;squadNames=new Map;loadRecords;adapterFor;now;stallTimeoutMs;leaseMs;sessionSendUrl;recordWatchMs;restoreSession;loadDefinition;sessions=new Map;startupStates=new Map;states=new Map;live=new Map;pendingPosts=new Map;settled=new Map;cancelledLeases=new Map;sendTokens=new Map;dirty=new Set;recovered;sweepTimer;stopped=false;stoppedError=SESSION_AGENT_RESTARTED_ERROR;constructor(options){this.workspaceCwd=options.workspaceCwd;this.bridge=options.bridge;this.hub=options.hub??getSessionAgentEventHub(options.workspaceCwd);this.chainLimit=options.chainLimit??(()=>0);this.tokenBudget=options.tokenBudget??(()=>DEFAULT_AGENT_TOKEN_BUDGET);this.readAgents=options.readAgents??readWorkspaceAgents;this.readSquads=options.readSquads??readSquads;this.loadRecords=options.loadRecords??(async sessionId=>{const data=await new SessionService(this.workspaceCwd).loadSession(sessionId);return data?.conversation.messages??[]});this.adapterFor=options.getAdapter??getAdapter;this.now=options.now??Date.now;this.stallTimeoutMs=options.stallTimeoutMs??SESSION_AGENT_STALL_TIMEOUT_MS;this.leaseMs=options.leaseMs??HOST_TURN_LEASE_MS;this.sessionSendUrl=options.sessionSendUrl;this.recordWatchMs=options.recordWatchMs??RECORD_WATCH_INITIAL_MS;this.restoreSession=options.restoreSession??(async sessionId=>{await this.bridge.resumeSession({sessionId,workspaceCwd:this.workspaceCwd})});this.loadDefinition=options.loadDefinition??defaultLoadDefinition;this.recovered=this.recoverOnStartup().catch(error=>{writeStderrLine(`qwen serve: session agent recovery failed in ${this.workspaceCwd}: ${getErrorMessage(error)}`)});if(options.startTimers!==false){this.sweepTimer=setInterval(()=>this.sweep(),SWEEP_INTERVAL_MS);this.sweepTimer.unref?.()}}async mention(sessionId,input){this.assertRunning();if(!isValidSessionAgentsSessionId(sessionId)){throw new SessionAgentError(400,"invalid_session_id","Invalid session id.")}const{text,clientMessageId}=input;if(typeof text!=="string"||text.trim().length===0||text.length>MAX_MENTION_TEXT_CHARS){throw new SessionAgentError(400,"invalid_text","text is required.")}if(typeof clientMessageId!=="string"||!CLIENT_MESSAGE_ID_PATTERN.test(clientMessageId)){throw new SessionAgentError(400,"invalid_client_message_id","clientMessageId must be 1-128 characters of [A-Za-z0-9_.:-].")}const roster=await this.readAgents(this.workspaceCwd);const squads=await this.loadSquads();const targets=resolveMentionTargetsWithSquads(text,roster,squads);const squadLeaders=targets.squads.flatMap(squad=>{const leader=roster.find(agent=>agent.id===squad.leaderAgentId);return leader?[{squad,leader}]:[]});assertMentionFitsRecord(targets.agents.length,squadLeaders.length);const squadError=targets.unavailableSquads.length>0?squadUnavailableError(targets.unavailableSquads):void 0;if(targets.agents.length===0&&squadLeaders.length===0){const details={unavailable:targets.unavailable.map(agent=>agent.name),unknown:targets.unknown,...targets.unavailableSquads.length>0?{unavailableSquads:targets.unavailableSquads.map(({squad,reason})=>({name:squad.name,reason}))}:{}};if(squadError){throw new SessionAgentError(400,"squad_unavailable",squadError,details)}throw new SessionAgentError(400,"no_agents_mentioned","The message does not @-mention any available agent.",details)}const state=await this.session(sessionId);const recordKey=`mention:${clientMessageId}`;let record;try{record=await this.appendRecord(sessionId,{kind:"agent_mention",recordKey,modelText:formatAgentMentionModelText(text,[...targets.agents.map(agent=>agent.name),...squadLeaders.map(({squad})=>squad.name)]),payload:{displayText:text,mentionedAgentIds:targets.agents.map(agent=>agent.id),...squadLeaders.length>0?{mentionedSquadIds:squadLeaders.map(({squad})=>squad.id)}:{},...squadError?{error:squadError}:{}}})}catch(error){throw recordWriteError(error)}const triggerId=triggerIdFor(record,recordKey);if(!record.created){return{recordId:record.recordId,...record.deferred?{deferred:true}:{},runs:state.file.runs.filter(run=>run.triggerRecordIds.includes(triggerId)).map(run=>({runId:run.id,agentId:run.agentId,status:run.status}))}}if(record.deferred){this.addPendingPost({sessionId,id:triggerId,kind:"agent_mention",speaker:"User",text,createdAt:this.now()})}delete state.file.chainTokens;const depth=nextChainDepth({kind:"human"});const runs2=[];const addRun=__name(summary=>{if(!runs2.some(existing=>existing.runId===summary.runId)){runs2.push(summary)}},"addRun");for(const{squad,leader}of squadLeaders){this.startEngagement(state,squad,triggerId);addRun(this.enqueue(state,leader,triggerId,depth,squad.id))}for(const agent of targets.agents){addRun(this.enqueue(state,agent,triggerId,depth))}await this.persist(state).catch(()=>{});for(const agent of targets.agents)this.pumpAgent(agent.id);for(const{leader}of squadLeaders)this.pumpAgent(leader.id);return{recordId:record.recordId,...record.deferred?{deferred:true}:{},runs:runs2,...squadError?{squadError}:{}}}async cancel(sessionId,runId){const live=this.live.get(runId);if(!live||live.sessionId!==sessionId){const settled=this.settled.get(runId);if(settled?.sessionId!==sessionId||!settled.frame.retryable){return false}this.dropSettled(runId,{});const state2=await this.session(sessionId);const run=state2.file.runs.find(candidate=>candidate.id===runId);if(run?.recorded===false){delete run.recorded;await this.persist(state2).catch(()=>{})}return true}const state=await this.session(sessionId);await this.cancelLive(state,live);return true}async retry(sessionId,runId){this.assertRunning();if(!isValidSessionAgentsSessionId(sessionId)){throw new SessionAgentError(400,"invalid_session_id","Invalid session id.")}const state=await this.session(sessionId);const run=state.file.runs.find(candidate=>candidate.id===runId);if(!run){throw new SessionAgentError(404,"run_not_found","No such run.")}if(run.status!=="failed"&&run.status!=="offline"&&this.settled.get(runId)?.frame.retryable!==true){throw new SessionAgentError(409,"run_not_retryable","Only a failed or offline run can be retried.")}const roster=await this.readAgents(this.workspaceCwd);const agent=roster.find(candidate=>candidate.id===run.agentId);if(!agent||!isAgentAddressable(agent)){throw new SessionAgentError(409,"agent_unavailable","This agent is disabled or no longer exists.")}const ledSquad=run.squadId?(await this.loadSquads()).find(candidate=>candidate.id===run.squadId&&candidate.leaderAgentId===agent.id):void 0;if(state.file.runs.some(candidate=>candidate.retryOf===runId)){throw new SessionAgentError(409,"run_already_retried","This run was already retried.")}const trigger=run.triggerRecordIds[0];if(trigger===void 0){throw new SessionAgentError(409,"run_not_retryable","This run has no trigger to answer.")}if(ledSquad)this.startEngagement(state,ledSquad,trigger);let summary;for(const triggerId of run.triggerRecordIds){summary=this.enqueue(state,agent,triggerId,run.chainDepth,ledSquad?.id)}const retried=summary&&this.live.get(summary.runId)?.run;if(!retried){throw new SessionAgentError(409,"run_not_retryable","This run has no trigger to answer.")}retried.retryOf??=runId;if(run.recorded===false)delete run.recorded;for(const{squadId}of this.settled.get(runId)?.wakes??[]){this.trackDelegation(state,squadId,retried.id)}this.dropSettled(runId,{retriedAsRunId:retried.id});this.settleEngagements(state);await this.persist(state).catch(()=>{});this.pumpAgent(agent.id);return{runId:retried.id,agentId:agent.id,status:retried.status}}async stopAll(sessionId){let droppedWakes=false;for(const settled of this.settled.values()){if(settled.sessionId===sessionId&&settled.wakes){delete settled.wakes;droppedWakes=true}}const runs2=[...this.live.values()].filter(live=>live.sessionId===sessionId);if(runs2.length===0){if(droppedWakes){const state2=await this.session(sessionId);if(this.settleEngagements(state2)){await this.persist(state2).catch(()=>{})}}return[]}const state=await this.session(sessionId);runs2.sort((a,b)=>Number(isExecutingRun(a.run))-Number(isExecutingRun(b.run)));for(const live of runs2)await this.cancelLive(state,live);return runs2.map(live=>live.run.id)}resolvePermission(sessionId,runId,requestId,optionId,voter){const live=this.live.get(runId);if(!live||live.sessionId!==sessionId){throw new SessionAgentError(404,"run_not_found","No such live run.")}const prompt=live.frame.permission;if(!prompt||prompt.requestId!==requestId){throw new SessionAgentError(404,"permission_not_found","No pending permission request for this run.")}if(typeof optionId!=="string"||!prompt.options.some(option=>option.optionId===optionId)){throw new SessionAgentError(400,"invalid_option","Unknown optionId.")}if(live.remote){const decision={runId,attempt:live.run.attempts,requestId,optionId,decisionId:randomUUID3()};live.remote.decisions=[...live.remote.decisions.filter(existing=>existing.requestId!==requestId),decision];this.publish(live,{immediate:true});return}const pending=live.pendingPermissions.get(requestId);if(!pending){throw new SessionAgentError(409,"permission_already_answered","This permission request was already answered.")}if(voter)live.voterContexts.set(requestId,voter);live.pendingPermissions.delete(requestId);pending.resolve(optionId)}async postFromAgent(sessionId,agentId,token,text){this.assertRunning();const expected=this.sendTokens.get(this.sendKey(sessionId,agentId));if(!expected||!tokensMatch(expected,token)){throw new SessionAgentError(401,"invalid_session_send_token","Unknown agent binding or invalid session_send token.")}if(typeof text!=="string"||isBlankAgentText(text)||text.length>MAX_MENTION_TEXT_CHARS){throw new SessionAgentError(400,"invalid_text","text is required.")}const live=[...this.live.values()].find(candidate=>candidate.sessionId===sessionId&&candidate.run.agentId===agentId&&!candidate.remote&&!candidate.abortReason&&isExecutingRun(candidate.run));if(!live){throw new SessionAgentError(409,"run_not_running","The agent has no running turn in this session.")}const state=await this.session(sessionId);live.frame.activityAt=this.now();await this.queueSessionSend(state,live,text)}async snapshot(sessionId){if(!isValidSessionAgentsSessionId(sessionId)){throw new SessionAgentError(400,"invalid_session_id","Invalid session id.")}await this.recovered;const frames=[...this.live.values()].filter(live=>live.sessionId===sessionId).map(live=>this.buildFrame(live));for(const settled of this.settled.values()){if(settled.sessionId===sessionId)frames.push({...settled.frame})}return frames}async liveRuns(){await this.recovered;return[...this.live.values()].map(live=>({sessionId:live.sessionId,runId:live.run.id,agentId:live.run.agentId,status:live.run.status,...live.remote?{hostId:live.remote.hostId}:{}}))}ready(){return this.recovered}async dispose(reason="shutdown"){if(this.stopped)return;this.stopped=true;this.stoppedError=SESSION_AGENT_STOPPED_ERRORS[reason];if(this.sweepTimer)clearInterval(this.sweepTimer);for(const settled of this.settled.values()){if(settled.timer)clearTimeout(settled.timer)}for(const live of this.live.values()){if(live.remote||live.author.runtimeId!==LOCAL_SESSION_AGENT_RUNTIME_ID||!isExecutingRun(live.run)){continue}live.abortReason="shutdown";for(const pending of live.pendingPermissions.values()){pending.reject(new Error("daemon stopping"))}live.pendingPermissions.clear();live.controller?.abort()}for(const state of this.dirty)await this.persist(state).catch(()=>{});this.dirty.clear()}async pickupForHost(hostId,programs){if(this.stopped)return void 0;await this.recovered;const roster=await this.readAgents(this.workspaceCwd);const queued=[...this.live.values()].filter(live=>live.run.status==="queued").sort((a,b)=>a.run.createdAt-b.run.createdAt);for(const live of queued){const{run}=live;if(run.status!=="queued")continue;const agent=roster.find(candidate=>candidate.id===run.agentId);if(!agent||!isAgentAddressable(agent)||agent.execution?.mode!=="managed-host"||!agent.execution.hostIds.includes(hostId)){continue}live.maxConcurrent=maxConcurrentRunsFor(agent);if(this.executingCount(agent.id)>=live.maxConcurrent)continue;const program=programForAgent(agent,programs);if(!program)continue;const state=await this.session(live.sessionId);if(run.status!=="queued")continue;if(nextRunnable(state.file.runs,agent.id)?.id!==run.id)continue;if(this.executingCount(agent.id)>=live.maxConcurrent)continue;const now=this.now();run.status="running";run.attempts+=1;run.startedAt=now;delete run.error;const lease={hostId,leaseId:randomUUID3(),attempt:run.attempts,expiresAt:now+this.leaseMs,lastSequence:0};run.lease=lease;live.author=authorFor(agent,hostId,program);live.remote={hostId,program,decisions:[]};live.frame.activityAt=now;this.republishQueued(agent.id);try{const persona=await resolveTurnPersona(agent,program,name=>this.loadDefinition(this.workspaceCwd,name));const binding=state.file.bindings[agent.id]??{agentId:agent.id};const records=await this.loadRecords(live.sessionId);const squad=await this.squadBriefingFor(live,roster);const sameRuntime=binding.runtimeId===hostId&&canReuseNativeSession(binding,hostId,program);const nativeSessionId=sameRuntime?binding.nativeSessionId:void 0;const readThroughRecordId=sameRuntime?binding.readThroughRecordId:void 0;const inputOptions={records,trigger:{agentId:agent.id,agentName:agent.name,recordIds:run.triggerRecordIds},budgetChars:AGENT_INPUT_CHAR_BUDGET,pendingMessages:this.pendingFor(live.sessionId,agent.id,records),...squad?{squad}:{}};const input=buildAgentInput({...inputOptions,readThroughRecordId});live.lastRecordId=input.lastRecordId;const freshPrompt=nativeSessionId&&readThroughRecordId!==void 0?buildAgentInput(inputOptions).prompt:void 0;live.offeredFreshPrompt=freshPrompt!==void 0;await this.persist(state);this.publish(live);return{protocol:HOST_PROTOCOL_VERSION,sessionId:live.sessionId,runId:run.id,attempt:lease.attempt,leaseId:lease.leaseId,leaseExpiresAt:lease.expiresAt,agent:{...this.authorOf(live),...persona},program,prompt:input.prompt,...freshPrompt!==void 0?{freshPrompt}:{},...nativeSessionId?{nativeSessionId}:{}}}catch(error){await this.finishRun(state,live,{status:"failed",outputText:"",error:getErrorMessage(error)})}}return void 0}renewLease(hostId,runId,attempt,leaseId){const fenced=this.fence(hostId,runId,attempt,leaseId);if(!fenced.ok)return fenced;const lease=fenced.live.run.lease;lease.expiresAt=this.now()+this.leaseMs;return{ok:true,leaseExpiresAt:lease.expiresAt}}releaseHostAssignment(hostId,assignment){const fenced=this.fence(hostId,assignment.runId,assignment.attempt,assignment.leaseId,assignment.sessionId);if(!fenced.ok)return fenced;const{live}=fenced;live.run.status="queued";delete live.run.lease;delete live.run.startedAt;delete live.remote;live.author={...live.author};delete live.author.runtimeId;delete live.frame.permission;delete live.frame.outputText;delete live.frame.thoughtText;delete live.frame.steps;live.steps.clear();const state=this.states.get(live.sessionId);if(state)void this.persist(state).catch(()=>{});this.publish(live);this.republishQueued(live.run.agentId);return{ok:true}}acceptHostEvents(hostId,batch){const fenced=this.fence(hostId,batch.runId,batch.attempt,batch.leaseId,batch.sessionId);if(!fenced.ok)return fenced;const{live}=fenced;const lease=live.run.lease;if(batch.sequence<=(lease.lastSequence??0)){return{ok:true,duplicate:true}}lease.lastSequence=batch.sequence;lease.expiresAt=this.now()+this.leaseMs;const state=this.states.get(live.sessionId);if(state){this.dirty.add(state);for(const event of batch.events)this.applyEvent(state,live,event)}return{ok:true,leaseExpiresAt:lease.expiresAt}}async completeHostTurn(hostId,result){const fenced=this.fence(hostId,result.runId,result.attempt,result.leaseId,result.sessionId);if(!fenced.ok)return fenced;const state=await this.session(result.sessionId);await fenced.live.sendChain;await this.finishRun(state,fenced.live,{status:result.result.status,outputText:result.result.outputText,...result.result.error?{error:result.result.error}:{},...result.result.nativeSessionId?{nativeSessionId:result.result.nativeSessionId}:{},...result.result.totalTokens!==void 0?{totalTokens:result.result.totalTokens}:{},...result.result.resumeRejected?{resumeRejected:true}:{}});return{ok:true}}decisionsForHost(hostId){const decisions=[];for(const live of this.live.values()){if(live.remote?.hostId!==hostId)continue;decisions.push(...live.remote.decisions)}return decisions}async endRunsForRemovedHost(hostId,agentsMadeLocal){await this.recovered;const madeLocal=new Set(agentsMadeLocal);const stranded=[...this.live.values()].filter(live=>live.remote?.hostId===hostId||live.run.status==="queued"&&madeLocal.has(live.run.agentId));for(const live of stranded){const state=await this.session(live.sessionId);await this.finishRun(state,live,{status:"offline",outputText:live.frame.outputText??"",error:SESSION_AGENT_HOST_REMOVED_ERROR,...live.run.status==="queued"?{totalTokens:0}:{}})}return stranded.length}sweep(){const now=this.now();for(const state of this.dirty)void this.persist(state).catch(()=>{});this.dirty.clear();for(const[runId,cancelled]of[...this.cancelledLeases]){if(now-cancelled.at>CANCELLED_LEASE_TTL_MS){this.cancelledLeases.delete(runId)}}for(const live of[...this.live.values()]){if(!isExecutingRun(live.run))continue;if(live.remote){const lease=live.run.lease;if(lease&&lease.expiresAt<now){void this.session(live.sessionId).then(state=>this.finishRun(state,live,{status:"offline",outputText:live.frame.outputText??"",error:SESSION_AGENT_OFFLINE_ERROR}))}continue}if(live.frame.permission)continue;if(now-live.frame.activityAt>=this.stallTimeoutMs){live.abortReason="stalled";live.controller?.abort()}}}assertRunning(){if(this.stopped){throw new SessionAgentError(503,"orchestrator_stopped","Session agents are stopping in this workspace.")}}session(sessionId){let state=this.sessions.get(sessionId);if(!state){state=this.recovered.then(async()=>{const recovered=this.startupStates.get(sessionId);if(recovered)return recovered;const file=await readSessionAgents(this.workspaceCwd,sessionId);return this.adopt(file,void 0)});this.sessions.set(sessionId,state);state.catch(()=>{if(this.sessions.get(sessionId)===state){this.sessions.delete(sessionId)}})}return state}adopt(file,roster){const state={sessionId:file.sessionId,file,writeChain:Promise.resolve()};this.states.set(file.sessionId,state);const now=this.now();let changed=false;const authorOf2=__name(run=>{const agent=roster?.find(candidate=>candidate.id===run.agentId);return agent?authorFor(agent,agent.execution?.mode==="managed-host"?void 0:LOCAL_SESSION_AGENT_RUNTIME_ID,programForAgent(agent)):{agentId:run.agentId,name:run.agentId}},"authorOf");for(const run of file.runs){if(isTerminalSessionAgentRunStatus(run.status)){if(run.status==="cancelled"&&run.lease&&now-(run.endedAt??run.createdAt)<=CANCELLED_LEASE_TTL_MS){this.rememberCancelledLease(file.sessionId,run)}if(run.recorded===false&&!this.settled.has(run.id)){if(this.adoptUnrecorded(file,run,authorOf2(run),now)){changed=true}}continue}if(this.live.has(run.id))continue;const agent=roster?.find(candidate=>candidate.id===run.agentId);const remoteAgent=agent!==void 0&&agent.execution?.mode==="managed-host";if(run.status==="queued"&&remoteAgent){this.live.set(run.id,this.newLive(file.sessionId,run,agent));continue}if(run.status==="running"&&run.lease&&remoteAgent){const live=this.newLive(file.sessionId,run,agent);const program=programForAgent(agent)??"qwen";live.author=authorFor(agent,run.lease.hostId,program);live.remote={hostId:run.lease.hostId,program,decisions:[]};run.lease.expiresAt=now+this.leaseMs;this.live.set(run.id,live);changed=true;continue}if(run.lease)this.rememberCancelledLease(file.sessionId,run);run.status="failed";run.error=SESSION_AGENT_RESTARTED_ERROR;run.endedAt=now;run.recorded=false;delete run.lease;changed=true;this.addSettled(run.id,{sessionId:file.sessionId,frame:{type:"run",sessionId:file.sessionId,runId:run.id,author:authorOf2(run),status:"failed",error:SESSION_AGENT_RESTARTED_ERROR,activityAt:now,recorded:false,retryable:true}})}this.restorePendingWakes(state,roster);if(this.settleEngagements(state))changed=true;if(changed)void this.persist(state).catch(()=>{});return state}adoptUnrecorded(file,run,author,now){if(run.status==="cancelled"||file.runs.some(candidate=>candidate.retryOf===run.id)){delete run.recorded;return true}const wroteRecord=run.status!=="offline"&&!Object.values(SESSION_AGENT_STOPPED_ERRORS).includes(run.error??"");this.addSettled(run.id,{sessionId:file.sessionId,frame:{type:"run",sessionId:file.sessionId,runId:run.id,author,status:run.status,error:run.error??SESSION_AGENT_REPLY_NOT_RECORDED_ERROR,...run.totalTokens!==void 0?{totalTokens:run.totalTokens}:{},activityAt:run.endedAt??now,recorded:false,retryable:true},...wroteRecord?{recovered:true}:{}});if(wroteRecord)this.watchRecord(run.id);return false}restorePendingWakes(state,roster){if(!roster)return;for(const[squadId,engagement]of Object.entries(state.file.squads??{})){if(!engagement.active||!engagement.pendingWakeRunIds)continue;const leader=roster.find(agent=>agent.id===engagement.leaderAgentId);if(!leader||!isAgentAddressable(leader)){writeStderrLine(`qwen serve: squad ${squadId} in session ${state.sessionId} lost its leader across a restart; its pending wake was dropped.`);continue}for(const runId of engagement.pendingWakeRunIds){const settled=this.settled.get(runId);const run=state.file.runs.find(candidate=>candidate.id===runId);if(!run||!settled?.recovered)continue;if(settled.sessionId!==state.sessionId)continue;const wakes=settled.wakes??=[];if(wakes.some(wake=>wake.squadId===squadId))continue;wakes.push({squadId,leader,chainDepth:nextChainDepth({kind:"agent",chainDepth:run.chainDepth})})}}}async recoverOnStartup(){const ids=await listSessionAgentsSessionIds(this.workspaceCwd);if(ids.length===0)return;let roster;for(const sessionId of ids){let file;try{file=await readSessionAgents(this.workspaceCwd,sessionId)}catch(error){writeStderrLine(`qwen serve: skipping unreadable session agents file for ${sessionId}: ${getErrorMessage(error)}`);continue}if(file.runs.every(run=>isTerminalSessionAgentRunStatus(run.status)&&!(run.status==="cancelled"&&run.lease)&&run.recorded!==false)){continue}roster??=await this.readAgents(this.workspaceCwd);const state=this.adopt(file,roster);this.startupStates.set(sessionId,state);if(!this.sessions.has(sessionId)){this.sessions.set(sessionId,Promise.resolve(state))}}}newLive(sessionId,run,agent){const maxConcurrent=maxConcurrentRunsFor(agent);const author=authorFor(agent,agent.execution?.mode==="managed-host"?void 0:LOCAL_SESSION_AGENT_RUNTIME_ID,programForAgent(agent));return{sessionId,run,author,maxConcurrent,frame:{type:"run",sessionId,runId:run.id,author,status:run.status,activityAt:this.now()},steps:new Map,pendingPermissions:new Map,voterContexts:new Map,sendCount:0,sendChain:Promise.resolve()}}enqueue(state,agent,recordId,chainDepth,squadId){const squad=squadId??this.activeSquadLedBy(state,agent.id);const outcome=enqueueTrigger(state.file.runs,{agentId:agent.id,recordId,chainDepth,now:this.now(),newRunId:__name(()=>`sr_${randomUUID3()}`,"newRunId"),...squad?{squadId:squad}:{}});let live=this.live.get(outcome.run.id);if(!live){live=this.newLive(state.sessionId,outcome.run,agent);this.live.set(outcome.run.id,live)}this.publish(live);return{runId:outcome.run.id,agentId:agent.id,status:outcome.run.status}}executingCount(agentId){let count=0;for(const live of this.live.values()){if(live.run.agentId===agentId&&isExecutingRun(live.run))count+=1}return count}pumpAgent(agentId){if(this.stopped)return;const queued=[...this.live.values()].filter(live=>live.run.agentId===agentId&&live.run.status==="queued"&&live.author.runtimeId===LOCAL_SESSION_AGENT_RUNTIME_ID).sort((a,b)=>a.run.createdAt-b.run.createdAt);for(const live of queued){if(this.executingCount(agentId)>=live.maxConcurrent)break;const state=this.states.get(live.sessionId);if(!state)continue;if(nextRunnable(state.file.runs,agentId)?.id!==live.run.id)continue;void this.runLocal(state,live).catch(error=>{writeStderrLine(`qwen serve: session agent run ${live.run.id} crashed: ${getErrorMessage(error)}`)})}this.republishQueued(agentId)}republishQueued(agentId){for(const live of this.live.values()){if(live.run.agentId===agentId&&live.run.status==="queued"){this.publish(live)}}}async runLocal(state,live){const{run}=live;run.status="running";run.startedAt=this.now();run.attempts+=1;delete run.error;const controller=new AbortController;live.controller=controller;live.frame.activityAt=this.now();this.publish(live);let outcome;try{const roster=await this.readAgents(this.workspaceCwd);const agent=roster.find(candidate=>candidate.id===run.agentId);if(!agent||!isAgentAddressable(agent)){throw new Error("This agent is disabled or no longer exists.")}if(agent.execution?.mode==="managed-host"){throw new Error("This agent now runs on a remote runtime.")}const program=programForAgent(agent);live.author=authorFor(agent,LOCAL_SESSION_AGENT_RUNTIME_ID,program);live.maxConcurrent=maxConcurrentRunsFor(agent);const persona=program==="qwen"?{...agent.instructions?{instructions:agent.instructions}:{},...agent.model?{model:agent.model}:{}}:await resolveTurnPersona(agent,program,name=>this.loadDefinition(this.workspaceCwd,name));const binding=state.file.bindings[agent.id]??{agentId:agent.id};const records=await this.loadRecords(state.sessionId);const squad=await this.squadBriefingFor(live,roster);const sameNativeSession=canReuseNativeSession(binding,LOCAL_SESSION_AGENT_RUNTIME_ID,program);const resumable=sameNativeSession&&binding.runtimeId===LOCAL_SESSION_AGENT_RUNTIME_ID?binding.nativeSessionId:void 0;const nativeSessionId=program==="qwen"?sessionAgentNativeSessionId(agent.id,state.sessionId):resumable;const readThroughRecordId=sameNativeSession?binding.readThroughRecordId:void 0;const inputOptions={records,trigger:{agentId:agent.id,agentName:agent.name,recordIds:run.triggerRecordIds},budgetChars:AGENT_INPUT_CHAR_BUDGET,pendingMessages:this.pendingFor(state.sessionId,agent.id,records),...squad?{squad}:{}};const input=buildAgentInput({...inputOptions,readThroughRecordId});live.lastRecordId=input.lastRecordId;const freshPrompt=nativeSessionId&&readThroughRecordId!==void 0?buildAgentInput(inputOptions).prompt:void 0;live.offeredFreshPrompt=freshPrompt!==void 0;state.file.bindings[agent.id]={...binding,agentId:agent.id,...nativeSessionId?{nativeSessionId,runtimeId:LOCAL_SESSION_AGENT_RUNTIME_ID}:{}};await this.persist(state);if(controller.signal.aborted)throw new Error("cancelled");const sessionSend={isCurrent:__name(()=>this.sendTokenIsCurrent(state.sessionId,agent.id),"isCurrent"),rotate:__name(()=>this.rotateSendToken(state.sessionId,agent.id),"rotate")};const sessionSendServer=program==="qwen"?void 0:this.rotateSendToken(state.sessionId,agent.id);const adapter=this.adapterFor(program,{workspaceCwd:this.workspaceCwd,bridge:this.bridge,agentId:agent.id,permissionVoteContext:__name(requestId=>live.voterContexts.get(requestId),"permissionVoteContext"),sessionSend});const result=await adapter.runTurn({prompt:input.prompt,...freshPrompt!==void 0?{freshPrompt}:{},...persona,...nativeSessionId?{nativeSessionId}:{},cwd:this.workspaceCwd,...sessionSendServer?{sessionSendServer}:{},signal:controller.signal,onEvent:__name(event=>this.applyEvent(state,live,event),"onEvent"),awaitPermission:__name(prompt=>this.awaitPermission(live,prompt),"awaitPermission")});outcome={status:result.status,outputText:result.outputText,...result.error?{error:result.error}:{},...result.nativeSessionId?{nativeSessionId:result.nativeSessionId}:{},...result.totalTokens!==void 0?{totalTokens:result.totalTokens}:{},...result.resumeRejected?{resumeRejected:true}:{}}}catch(error){outcome={status:controller.signal.aborted?"cancelled":"failed",outputText:live.frame.outputText??"",error:getErrorMessage(error)}}if(live.abortReason==="stalled"){outcome={...outcome,status:"failed",error:SESSION_AGENT_STALLED_ERROR}}else if(live.abortReason==="cancelled"){outcome={...outcome,status:"cancelled"};delete outcome.error}else if(live.abortReason==="shutdown"){outcome={...outcome,status:"failed",error:this.stoppedError}}await live.sendChain;await this.finishRun(state,live,outcome)}awaitPermission(live,prompt){return new Promise((resolve2,reject)=>{if(live.controller?.signal.aborted){reject(new Error("cancelled"));return}live.pendingPermissions.set(prompt.requestId,{resolve:resolve2,reject})})}applyEvent(state,live,event){if(isTerminalSessionAgentRunStatus(live.run.status))return;if(live.abortReason&&event.type!=="usage"&&event.type!=="native_session"){return}const frame=live.frame;frame.activityAt=this.now();switch(event.type){case"native_session":live.nativeSessionId=event.nativeSessionId;break;case"text_delta":frame.outputText=((frame.outputText??"")+event.text).slice(-MAX_OUTPUT_CHARS);break;case"thought_delta":frame.thoughtText=((frame.thoughtText??"")+event.text).slice(-MAX_THOUGHT_CHARS);break;case"step":live.steps.set(event.step.id,event.step);for(const id of live.steps.keys()){if(live.steps.size<=MAX_RUN_STEPS)break;live.steps.delete(id)}frame.steps=[...live.steps.values()].slice(-MAX_FRAME_STEPS);break;case"permission_request":frame.permission=event.prompt;live.run.status="awaiting_approval";void this.persist(state).catch(()=>{});break;case"permission_resolved":if(frame.permission?.requestId===event.requestId){delete frame.permission;live.run.status="running";void this.persist(state).catch(()=>{})}live.pendingPermissions.delete(event.requestId);live.voterContexts.delete(event.requestId);if(live.remote){live.remote.decisions=live.remote.decisions.filter(decision=>decision.requestId!==event.requestId)}break;case"usage":live.totalTokens=event.totalTokens;frame.totalTokens=event.totalTokens;break;case"session_send":void this.queueSessionSend(state,live,event.text).catch(()=>{});break;default:{const exhaustive=event;void exhaustive}}this.publish(live)}queueSessionSend(state,live,text){const done=live.sendChain.then(()=>this.handleSessionSend(state,live,text));live.sendChain=done.catch(error=>{live.frame.error=getErrorMessage(error);this.publish(live)});return done}async handleSessionSend(state,live,text){if(isBlankAgentText(text))return;if(text.length>MAX_MENTION_TEXT_CHARS){throw new SessionAgentError(400,"invalid_text",`A session_send post of ${text.length.toLocaleString("en-US")} characters was not posted: the limit is ${MAX_MENTION_TEXT_CHARS.toLocaleString("en-US")}.`)}const roster=await this.readAgents(this.workspaceCwd);const targets=resolveMentionTargetsWithSquads(text,roster,await this.loadSquads(),live.run.agentId);const squadTargets=this.agentSquadTargets(state,live.run.agentId,targets.squads,roster);assertMentionFitsRecord(targets.agents.length,squadTargets.length);const squadError=targets.unavailableSquads.length>0?squadUnavailableError(targets.unavailableSquads):void 0;const postError=joinErrors(squadError,targets.agents.length===0&&squadTargets.length===0?unreachedAgentsError(targets.unavailable,targets.unknown):void 0);const squadMembers=await this.squadMembersFor(live);live.sendCount+=1;const recordKey=`send:${live.run.id}:${live.sendCount}`;let record;try{record=await this.appendRecord(state.sessionId,{kind:"agent_mention",recordKey,modelText:formatAgentMentionModelText(text,[...targets.agents.map(agent=>agent.name),...squadTargets.map(({squad})=>squad.name)],{authorName:live.author.name}),payload:{displayText:text,mentionedAgentIds:targets.agents.map(agent=>agent.id),...squadTargets.length>0?{mentionedSquadIds:squadTargets.map(({squad})=>squad.id)}:{},author:live.author,...postError?{error:postError}:{}}})}catch(error){throw recordWriteError(error)}if(postError){live.frame.error=postError;this.publish(live)}const triggerId=triggerIdFor(record,recordKey);if(record.deferred){this.addPendingPost({sessionId:state.sessionId,id:triggerId,kind:"agent_mention",speaker:`${live.author.name} (agent)`,text,authorAgentId:live.run.agentId,createdAt:this.now()})}const limitError=this.routeMentions(state,live,targets.agents,triggerId,squadMembers,squadTargets);if(limitError){live.frame.error=limitError;this.publish(live)}}routeMentions(state,author,agents,recordId,squadMembers,squads=[]){if(agents.length===0&&squads.length===0||this.stopped){return void 0}const names=[...agents.map(agent=>agent.name),...squads.map(({squad})=>squad.name)];const depth=nextChainDepth({kind:"agent",chainDepth:author.run.chainDepth});const limit=normalizeAgentChainLimit(this.chainLimit());if(!isWithinChainLimit(depth,limit)){return chainLimitError(limit,names)}const budget=normalizeAgentTokenBudget(this.tokenBudget());if(!isWithinTokenBudget(state.file.chainTokens??0,budget)){return tokenBudgetError(budget,names)}for(const{squad,leader}of squads){this.startEngagement(state,squad,recordId);this.enqueue(state,leader,recordId,depth,squad.id)}for(const agent of agents){const summary=this.enqueue(state,agent,recordId,depth);if(squadMembers?.has(agent.id)){this.trackDelegation(state,author.run.squadId,summary.runId)}}void this.persist(state).catch(()=>{}).then(()=>{for(const{leader}of squads)this.pumpAgent(leader.id);for(const agent of agents)this.pumpAgent(agent.id)});return void 0}async cancelLive(state,live){const{run}=live;if(isTerminalSessionAgentRunStatus(run.status))return;if(run.status==="queued"){run.status="cancelled";run.endedAt=this.now();this.live.delete(run.id);this.releaseOutstanding(state,run.id);this.settleEngagements(state);this.publish(live);this.hub.forgetRun(state.sessionId,run.id);this.republishQueued(run.agentId);await this.persist(state).catch(()=>{});return}if(live.remote){this.rememberCancelledLease(state.sessionId,run);await live.sendChain;await this.finishRun(state,live,{status:"cancelled",outputText:live.frame.outputText??""});return}live.abortReason="cancelled";for(const pending of live.pendingPermissions.values()){pending.reject(new Error("cancelled"))}live.pendingPermissions.clear();if(live.frame.permission||run.status==="awaiting_approval"){delete live.frame.permission;run.status="running";this.publish(live)}live.controller?.abort()}async finishRun(state,live,outcome){const{run}=live;if(isTerminalSessionAgentRunStatus(run.status))return;run.status=outcome.status;run.endedAt=this.now();const runtimeId=live.remote?.hostId??LOCAL_SESSION_AGENT_RUNTIME_ID;for(const pending of live.pendingPermissions.values()){pending.reject(new Error("run ended"))}live.pendingPermissions.clear();const replyText=!isBlankAgentText(outcome.outputText)?outcome.outputText:outcome.status==="completed"?"":live.frame.outputText??"";const displayText=isBlankAgentText(replyText)?"":clipReplyText(replyText);const retryable=outcome.status==="offline"||live.abortReason==="shutdown";const nativeSessionId=outcome.nativeSessionId??live.nativeSessionId;const totalTokens=outcome.totalTokens??live.totalTokens;const chargedTokens=totalTokens??UNREPORTED_TURN_TOKENS;let followUps=[];let squadFollowUps=[];let error=outcome.error;if(outcome.status==="completed"&&displayText.trim()&&!this.stopped){try{const roster=await this.readAgents(this.workspaceCwd);const targets=resolveMentionTargetsWithSquads(displayText,roster,await this.loadSquads(),run.agentId);followUps=targets.agents;squadFollowUps=this.agentSquadTargets(state,run.agentId,targets.squads,roster);if(targets.unavailableSquads.length>0){error=joinErrors(error,squadUnavailableError(targets.unavailableSquads))}const names=[...followUps.map(agent=>agent.name),...squadFollowUps.map(({squad})=>squad.name)];const depth=nextChainDepth({kind:"agent",chainDepth:run.chainDepth});const limit=normalizeAgentChainLimit(this.chainLimit());const budget=normalizeAgentTokenBudget(this.tokenBudget());const spent=(state.file.chainTokens??0)+chargedTokens;if(names.length>0&&!isWithinChainLimit(depth,limit)){error=joinErrors(error,chainLimitError(limit,names));followUps=[];squadFollowUps=[]}else if(names.length>0&&!isWithinTokenBudget(spent,budget)){error=joinErrors(error,tokenBudgetError(budget,names));followUps=[];squadFollowUps=[]}}catch(routeError){error=`Could not route mentions: ${getErrorMessage(routeError)}`;followUps=[];squadFollowUps=[]}}const squadMembers=followUps.length>0?await this.squadMembersFor(live):void 0;const wakes=[];const waiting=this.releaseOutstanding(state,run.id);if(!run.squadId&&waiting.length>0)live.memberSquadId=waiting[0];const memberSquadName=live.memberSquadId?this.squadNames.get(live.memberSquadId):void 0;if(waiting.length>0&&outcome.status!=="cancelled"&&!this.stopped){try{const roster=await this.readAgents(this.workspaceCwd);const depth=nextChainDepth({kind:"agent",chainDepth:run.chainDepth});const limit=normalizeAgentChainLimit(this.chainLimit());const budget=normalizeAgentTokenBudget(this.tokenBudget());const spent=(state.file.chainTokens??0)+chargedTokens;for(const squadId of waiting){const leaderId=state.file.squads?.[squadId]?.leaderAgentId;const leader=roster.find(agent=>agent.id===leaderId);if(!leader||!isAgentAddressable(leader)){error=joinErrors(error,`Squad @${this.squadNames.get(squadId)??squadId} stops here: its leader is unavailable.`)}else if(!isWithinChainLimit(depth,limit)){error=joinErrors(error,chainLimitError(limit,[leader.name]))}else if(!isWithinTokenBudget(spent,budget)){error=joinErrors(error,tokenBudgetError(budget,[leader.name]))}else{wakes.push({squadId,leader})}}}catch(wakeError){error=joinErrors(error,`Could not wake the squad leader: ${getErrorMessage(wakeError)}`)}}const payload={displayText,author:{...this.authorOf(live),runtimeId,...memberSquadName?{memberSquadName}:{}},runId:run.id,status:outcome.status,...error?{error}:{},...live.steps.size>0?{steps:recordSteps(live.steps.values())}:{},...nativeSessionId?{nativeSessionId}:{},...totalTokens!==void 0?{totalTokens}:{},...run.triggerRecordIds.length>0?{triggerRecordId:run.triggerRecordIds.at(-1)}:{},...run.squadId&&outcome.status==="completed"&&displayText.trim().length===0?{squadOutcome:"no_action"}:{}};let recordId;let landedRecordId;const recordKey=`agent:${run.id}`;const request={kind:"agent_message",recordKey,modelText:formatAgentMessageModelText(payload),payload};let watch=false;if(!retryable){try{const written=await this.appendRecord(state.sessionId,request);recordId=triggerIdFor(written,recordKey);if(written.deferred||!written.recordId){watch=true;if(displayText.trim()){this.addPendingPost({sessionId:state.sessionId,id:recordId,kind:"agent_message",speaker:`${live.author.name} (agent)`,text:displayText,authorAgentId:run.agentId,runId:run.id,createdAt:this.now()})}}else{landedRecordId=written.recordId}}catch(writeError){const refusal=recordWriteError(writeError);error=`Could not record the reply: ${refusal.message}`;followUps=[];squadFollowUps=[];watch=refusal.code!=="managed_session_unsupported"}}const nextDepth=nextChainDepth({kind:"agent",chainDepth:run.chainDepth});let wakeTrigger=recordId;if(!wakeTrigger&&wakes.length>0&&!watch){wakeTrigger=this.addUnrecordedReply(state.sessionId,run.id,this.authorOf(live),displayText,error)}const binding=state.file.bindings[run.agentId]??{agentId:run.agentId};if(nativeSessionId){binding.nativeSessionId=nativeSessionId;binding.runtimeId=runtimeId;if(live.author.program)binding.program=live.author.program}if(outcome.resumeRejected&&!live.offeredFreshPrompt){delete binding.readThroughRecordId}else if(outcome.status==="completed"&&live.lastRecordId){binding.readThroughRecordId=live.lastRecordId}state.file.bindings[run.agentId]=binding;if(error)run.error=error;else delete run.error;if(landedRecordId)run.recorded=true;else if(watch||retryable)run.recorded=false;else delete run.recorded;if(totalTokens!==void 0)run.totalTokens=totalTokens;state.file.chainTokens=(state.file.chainTokens??0)+chargedTokens;if(!(outcome.status==="cancelled"&&live.remote))delete run.lease;state.file.runs=trimTerminalRuns(state.file.runs);live.frame.error=error;if(!error)delete live.frame.error;delete live.frame.permission;if(landedRecordId){live.frame.recorded=true;live.frame.recordId=landedRecordId}else if(watch||retryable){live.frame.recorded=false}if(retryable)live.frame.retryable=true;this.publish(live);this.hub.forgetRun(state.sessionId,run.id);this.live.delete(run.id);if(retryable){this.addSettled(run.id,{sessionId:state.sessionId,frame:this.buildFrame(live)})}else if(watch){this.addSettled(run.id,{sessionId:state.sessionId,frame:this.buildFrame(live),request,...payload.error?{recordedError:payload.error}:{},...!wakeTrigger&&wakes.length>0?{wakes:wakes.map(({squadId,leader})=>({squadId,leader,chainDepth:nextDepth}))}:{}});this.watchRecord(run.id)}if(recordId){for(const{squad,leader}of squadFollowUps){this.startEngagement(state,squad,recordId);this.enqueue(state,leader,recordId,nextDepth,squad.id)}for(const agent of followUps){const summary=this.enqueue(state,agent,recordId,nextDepth);if(squadMembers?.has(agent.id)){this.trackDelegation(state,run.squadId,summary.runId)}}}if(wakeTrigger){for(const{squadId,leader}of wakes){this.enqueue(state,leader,wakeTrigger,nextDepth,squadId)}}this.settleEngagements(state);await this.persist(state).catch(()=>{});this.pumpAgent(run.agentId);for(const{leader}of squadFollowUps)this.pumpAgent(leader.id);for(const agent of followUps)this.pumpAgent(agent.id);if(wakeTrigger)for(const{leader}of wakes)this.pumpAgent(leader.id)}addUnrecordedReply(sessionId,runId,author,displayText,error){const id=`pending:unrecorded:${runId}`;const note=error?`[This reply is not in the conversation record: ${error}]`:"[This reply is not in the conversation record.]";this.addPendingPost({sessionId,id,kind:"agent_message",speaker:`${author.name} (agent)`,text:`${displayText.trim()?displayText:"(no reply text)"}
|
|
17
17
|
|
|
18
18
|
${note}`,authorAgentId:author.agentId,runId,createdAt:this.now()});return id}wakeLeaders(sessionId,wakes,triggerId){const state=this.states.get(sessionId);if(!state||this.stopped)return;const woken=[];for(const{squadId,leader,chainDepth}of wakes){if(!state.file.squads?.[squadId]?.active)continue;this.enqueue(state,leader,triggerId,chainDepth,squadId);woken.push(leader.id)}this.settleEngagements(state);void this.persist(state).catch(()=>{}).then(()=>{for(const agentId of woken)this.pumpAgent(agentId)})}addPendingPost(post){this.pendingPosts.set(`${post.sessionId}\0${post.id}`,post)}pendingFor(sessionId,agentId,records){const now=this.now();const out=[];for(const[key,post]of[...this.pendingPosts]){if(post.sessionId!==sessionId)continue;const landed=records.some(record=>{if(record.subtype!==post.kind)return false;const payload=record.systemPayload;return payload?.displayText===post.text&&(post.runId===void 0||payload.runId===post.runId)&&(payload.author?.agentId??void 0)===post.authorAgentId});if(landed||now-post.createdAt>PENDING_POST_TTL_MS){this.pendingPosts.delete(key);continue}if(post.authorAgentId===agentId)continue;out.push({id:post.id,speaker:post.speaker,text:post.text})}return out}async appendRecord(sessionId,request){try{return await this.bridge.appendExternalRecord(sessionId,request)}catch(error){if(!(error instanceof SessionNotFoundError))throw error;await this.restoreSession(sessionId);return this.bridge.appendExternalRecord(sessionId,request)}}fence(hostId,runId,attempt,leaseId,sessionId){const cancelled=this.cancelledLeases.get(runId);if(cancelled&&cancelled.hostId===hostId&&cancelled.leaseId===leaseId&&cancelled.attempt===attempt&&(sessionId===void 0||cancelled.sessionId===sessionId)){return{ok:false,reason:"cancelled",cancelled:true}}const live=this.live.get(runId);if(!live||sessionId!==void 0&&live.sessionId!==sessionId){return{ok:false,reason:"unknown_run"}}const lease=live.run.lease;if(!live.remote||!lease||!isExecutingRun(live.run)||lease.hostId!==hostId||lease.leaseId!==leaseId||lease.attempt!==attempt){return{ok:false,reason:"lease_mismatch"}}return{ok:true,live}}rememberCancelledLease(sessionId,run){if(!run.lease)return;this.cancelledLeases.set(run.id,{sessionId,hostId:run.lease.hostId,leaseId:run.lease.leaseId,attempt:run.lease.attempt,at:run.endedAt??this.now()})}sendKey(sessionId,agentId){return`${sessionId}\0${agentId}`}sendUrlFor(sessionId,agentId){const url=this.sessionSendUrl?.(sessionId,agentId);return url&&isLoopbackUrl(url)?url:void 0}rotateSendToken(sessionId,agentId){const key=this.sendKey(sessionId,agentId);const url=this.sendUrlFor(sessionId,agentId);if(!url){this.sendTokens.delete(key);return void 0}const token=randomBytes(32).toString("hex");this.sendTokens.set(key,token);return buildSessionSendServer(url,token)}sendTokenIsCurrent(sessionId,agentId){if(!this.sendUrlFor(sessionId,agentId))return true;return this.sendTokens.has(this.sendKey(sessionId,agentId))}addSettled(runId,settled){this.settled.set(runId,settled);while(this.settled.size>MAX_SETTLED_RUNS){const oldest=this.settled.keys().next().value;if(oldest===void 0)break;const evicted=this.settled.get(oldest);if(evicted?.timer)clearTimeout(evicted.timer);this.settled.delete(oldest)}}dropSettled(runId,extra){const settled=this.settled.get(runId);if(!settled)return;if(settled.timer)clearTimeout(settled.timer);this.settled.delete(runId);const frame={...settled.frame,...extra};delete frame.recorded;delete frame.retryable;this.hub.publish(frame);this.hub.forgetRun(settled.sessionId,runId)}watchRecord(runId){const settled=this.settled.get(runId);const request=settled?.request;if(!settled||!request&&!settled.recovered)return;const{sessionId}=settled;const startedAt=this.now();const maxMs=request?RECORD_WATCH_MAX_MS:RECORD_RECOVERY_WATCH_MAX_MS;let delayMs=this.recordWatchMs;const check=__name(async()=>{settled.timer=void 0;if(this.stopped||this.settled.get(runId)!==settled)return;let recordId;if(!request){recordId=await this.findAgentMessageRecord(sessionId,runId).catch(()=>void 0)}else{try{const response=await this.bridge.appendExternalRecord(sessionId,request);if(!response.deferred&&response.recordId){recordId=response.recordId}}catch(error){if(error instanceof SessionNotFoundError){try{recordId=await this.findAgentMessageRecord(sessionId,runId);if(!recordId){const response=await this.appendRecord(sessionId,request);if(!response.deferred&&response.recordId){recordId=response.recordId}}}catch{}}}}if(this.stopped||this.settled.get(runId)!==settled)return;if(recordId){this.settled.delete(runId);const frame={...settled.frame,recorded:true,recordId};delete frame.retryable;if(settled.recordedError)frame.error=settled.recordedError;else delete frame.error;this.hub.publish(frame);this.hub.forgetRun(sessionId,runId);this.markRecorded(sessionId,runId);if(settled.wakes)this.wakeLeaders(sessionId,settled.wakes,recordId);return}if(this.now()-startedAt>=maxMs){const wakes=settled.wakes;if(wakes){delete settled.wakes;const reply=request?.kind==="agent_message"?request.payload:void 0;const trigger=this.addUnrecordedReply(sessionId,runId,reply?.author??settled.frame.author,reply?.displayText??"",settled.frame.error);this.wakeLeaders(sessionId,wakes,trigger)}return}delayMs=Math.min(delayMs*2,RECORD_WATCH_MAX_INTERVAL_MS);schedule()},"check");const schedule=__name(()=>{settled.timer=setTimeout(()=>void check(),delayMs);settled.timer.unref?.()},"schedule");schedule()}markRecorded(sessionId,runId){const state=this.states.get(sessionId);const run=state?.file.runs.find(candidate=>candidate.id===runId);if(!state||!run||run.recorded===true)return;run.recorded=true;void this.persist(state).catch(()=>{})}async findAgentMessageRecord(sessionId,runId){const records=await this.loadRecords(sessionId);return records.find(record=>record.subtype===AGENT_MESSAGE_SUBTYPE&&record.systemPayload?.runId===runId)?.uuid}buildFrame(live){const position=queuePosition([...this.live.values()].map(candidate=>candidate.run),live.run);const frame={...live.frame,author:this.authorOf(live),status:live.run.status,...live.frame.steps?{steps:[...live.frame.steps]}:{}};if(position!==void 0)frame.queuePosition=position;else delete frame.queuePosition;const squadId=live.run.squadId??this.memberSquadOf(live)??live.memberSquadId;const squadName=squadId?this.squadNames.get(squadId):void 0;if(squadId)frame.squadId=squadId;else delete frame.squadId;if(squadName)frame.squadName=squadName;else delete frame.squadName;return frame}async loadSquads(){try{const squads=await this.readSquads(this.workspaceCwd);for(const squad of squads)this.squadNames.set(squad.id,squad.name);return squads}catch(error){writeStderrLine(`qwen serve: could not read squads in ${this.workspaceCwd}: ${getErrorMessage(error)}`);return[]}}authorOf(live){const squadId=live.run.squadId;const squadName=squadId===void 0?void 0:live.squadName??this.squadNames.get(squadId);return squadName?{...live.author,squadName}:live.author}startEngagement(state,squad,triggerId){const engagements=state.file.squads??={};const existing=engagements[squad.id];if(existing?.active){existing.leaderAgentId=squad.leaderAgentId;return}engagements[squad.id]={leaderAgentId:squad.leaderAgentId,startedByRecordId:triggerId,outstandingRunIds:[],active:true}}agentSquadTargets(state,authorAgentId,squads,roster){return squads.flatMap(squad=>{if(squad.leaderAgentId===authorAgentId)return[];if(state.file.squads?.[squad.id]?.active&&squad.members.some(member=>member.agentId===authorAgentId)){return[]}const leader=roster.find(agent=>agent.id===squad.leaderAgentId);return leader?[{squad,leader}]:[]})}activeSquadLedBy(state,agentId){for(const[squadId,engagement]of Object.entries(state.file.squads??{})){if(engagement.active&&engagement.leaderAgentId===agentId){return squadId}}return void 0}memberSquadOf(live){const engagements=this.states.get(live.sessionId)?.file.squads;for(const[squadId,engagement]of Object.entries(engagements??{})){if(engagement.outstandingRunIds.includes(live.run.id))return squadId}return void 0}async squadMembersFor(live){const squadId=live.run.squadId;if(!squadId)return void 0;const squad=(await this.loadSquads()).find(candidate=>candidate.id===squadId);if(!squad)return void 0;return new Set(squad.members.map(member=>member.agentId).filter(agentId=>agentId!==live.run.agentId))}trackDelegation(state,squadId,runId){const engagement=squadId?state.file.squads?.[squadId]:void 0;if(!engagement?.active)return;if(!engagement.outstandingRunIds.includes(runId)){engagement.outstandingRunIds.push(runId)}const live=this.live.get(runId);if(live)this.publish(live)}releaseOutstanding(state,runId){const released=[];for(const[squadId,engagement]of Object.entries(state.file.squads??{})){if(!engagement.outstandingRunIds.includes(runId))continue;engagement.outstandingRunIds=engagement.outstandingRunIds.filter(id=>id!==runId);if(engagement.active)released.push(squadId)}return released}settleEngagements(state){let changed=false;for(const[squadId,engagement]of Object.entries(state.file.squads??{})){const owed=[];for(const[runId,settled]of this.settled){if(settled.sessionId===state.sessionId&&settled.wakes?.some(wake=>wake.squadId===squadId)===true){owed.push(runId)}}const saved=engagement.pendingWakeRunIds??[];if(saved.length!==owed.length||saved.some((runId,index)=>runId!==owed[index])){if(owed.length>0)engagement.pendingWakeRunIds=owed;else delete engagement.pendingWakeRunIds;changed=true}if(!engagement.active)continue;const outstanding=engagement.outstandingRunIds.filter(runId=>this.live.get(runId)?.sessionId===state.sessionId);if(outstanding.length!==engagement.outstandingRunIds.length){engagement.outstandingRunIds=outstanding;changed=true}if(outstanding.length>0)continue;const leading=[...this.live.values()].some(live=>live.sessionId===state.sessionId&&live.run.squadId===squadId&&!isTerminalSessionAgentRunStatus(live.run.status));if(leading)continue;if(owed.length>0)continue;engagement.active=false;changed=true}return changed}async squadBriefingFor(live,roster){const squadId=live.run.squadId;if(!squadId)return void 0;const squad=(await this.loadSquads()).find(candidate=>candidate.id===squadId);if(!squad)return void 0;live.squadName=squad.name;const byId=new Map(roster.map(agent=>[agent.id,agent]));return{name:squad.name,...squad.instructions?{instructions:squad.instructions}:{},members:squad.members.flatMap(member=>{const agent=byId.get(member.agentId);if(!agent||agent.id===live.run.agentId||!isAgentAddressable(agent)){return[]}const program=programForAgent(agent);return[{name:agent.name,...member.role?{role:member.role}:{},...agent.description?{description:agent.description}:{},...program?{program:PROGRAM_LABELS[program]}:{},runtime:agent.execution?.mode==="managed-host"?`remote runtime ${agent.execution.hostIds.join(", ")}`:"this computer"}]})}}publish(live,options={}){live.frame.status=live.run.status;live.frame.author=live.author;this.hub.publish(this.buildFrame(live),options)}persist(state){const next=state.writeChain.then(async()=>{await writeSessionAgents(this.workspaceCwd,state.file)});state.writeChain=next.catch(error=>{writeStderrLine(`qwen serve: could not save session agents for ${state.sessionId}: ${getErrorMessage(error)}`)});return next}};var orchestrators=new Map;function getSessionAgentOrchestrator(workspaceCwd){return orchestrators.get(workspaceCwd)}__name(getSessionAgentOrchestrator,"getSessionAgentOrchestrator");function ensureSessionAgentOrchestrator(options){const existing=orchestrators.get(options.workspaceCwd);if(existing&&existing.bridge===options.bridge)return existing;if(existing)void existing.dispose("runtime_replaced");const created=new SessionAgentOrchestrator(options);orchestrators.set(options.workspaceCwd,created);return created}__name(ensureSessionAgentOrchestrator,"ensureSessionAgentOrchestrator");async function disposeSessionAgentOrchestrator(workspaceCwd,reason="shutdown"){const existing=orchestrators.get(workspaceCwd);if(!existing)return;orchestrators.delete(workspaceCwd);await existing.dispose(reason)}__name(disposeSessionAgentOrchestrator,"disposeSessionAgentOrchestrator");async function disposeAllSessionAgentOrchestrators(reason="shutdown"){const all=[...orchestrators.keys()];await Promise.all(all.map(cwd=>disposeSessionAgentOrchestrator(cwd,reason)))}__name(disposeAllSessionAgentOrchestrators,"disposeAllSessionAgentOrchestrators");init_esbuild_shims();function getHostProgramProbe(){return probeAgentPrograms()}__name(getHostProgramProbe,"getHostProgramProbe");function availablePrograms(probes){return probes.filter(probe=>probe.available).map(probe=>probe.program)}__name(availablePrograms,"availablePrograms");init_esbuild_shims();var import_express=__toESM(require_express(),1);import{randomBytes as randomBytes2,timingSafeEqual as timingSafeEqual2}from"node:crypto";var AGENT_HOST_RELAY_PATH="/agent-host-relay/runs";var MAX_SEND_TEXT=MAX_EXTERNAL_RECORD_TEXT_LENGTH;var runs=new Map;var baseUrlGetter;function relayBaseUrl(options){if(!options.port||options.tls)return void 0;const scheme="http";let authority;if(options.hostname.toLowerCase()==="localhost"){authority="127.0.0.1"}else if(isLoopbackBind(options.hostname)){authority=formatHostForAuthority(options.hostname)}else if(isWildcardBind(options.hostname)){authority=options.hostname.includes(":")?"[::1]":"127.0.0.1"}return authority?`${scheme}://${authority}:${options.port}`:void 0}__name(relayBaseUrl,"relayBaseUrl");function isLoopbackPeer(req){const address=(req.socket.remoteAddress??"").replace(/^::ffff:/i,"");return isLoopbackAddress(address)}__name(isLoopbackPeer,"isLoopbackPeer");function bearer(req){const match=/^Bearer ([A-Za-z0-9_-]{16,256})$/.exec(req.get("authorization")??"");return match?Buffer.from(match[1]):void 0}__name(bearer,"bearer");function registerAgentHostRelayRoutes(app,options){baseUrlGetter=__name(()=>relayBaseUrl({hostname:options.hostname,port:options.getPort(),tls:options.tls}),"baseUrlGetter");app.post(`${AGENT_HOST_RELAY_PATH}/:runId/send`,import_express.default.json({limit:"512kb"}),(req,res)=>{if(!isLoopbackPeer(req)){res.status(403).json({error:"loopback_only"});return}const run=runs.get(String(req.params["runId"]));const token=bearer(req);if(!run||!token||token.length!==run.token.length||!timingSafeEqual2(token,run.token)){res.status(401).json({error:"invalid_session_send_token"});return}const text=req.body?.text;if(typeof text!=="string"||!text.trim()||text.length>MAX_SEND_TEXT){res.status(400).json({error:"invalid_text"});return}run.push(text);res.json({ok:true})})}__name(registerAgentHostRelayRoutes,"registerAgentHostRelayRoutes");function hasAgentHostRelay(){return Boolean(baseUrlGetter?.())}__name(hasAgentHostRelay,"hasAgentHostRelay");function openAgentHostRelayRun(runId,push){const base=baseUrlGetter?.();if(!base)return void 0;const token=randomBytes2(32).toString("base64url");const entry={token:Buffer.from(token),push};runs.set(runId,entry);return{url:`${base}${AGENT_HOST_RELAY_PATH}/${encodeURIComponent(runId)}/send`,token,close:__name(()=>{if(runs.get(runId)===entry)runs.delete(runId)},"close")}}__name(openAgentHostRelayRun,"openAgentHostRelayRun");init_esbuild_shims();function hostDecisionKey(decision){return typeof decision.decisionId==="string"&&decision.decisionId?`id:${decision.decisionId}`:`option:${decision.optionId}`}__name(hostDecisionKey,"hostDecisionKey");function decisionsForAwaited(decisions,awaited){return decisions.filter(decision=>awaited.some(entry=>entry.runId===decision.runId&&entry.attempt===decision.attempt&&entry.requestId===decision.requestId&&!entry.seen.includes(hostDecisionKey(decision))))}__name(decisionsForAwaited,"decisionsForAwaited");export{SquadStoreError,isValidSquadId,updateWorkspaceAgentsWithSquads,readSquads,listSquadViews,createSquad,updateSquad,retireSquad,neutralizeMentions,resolveMentionTargetsWithSquads,normalizeAgentChainLimit,normalizeAgentTokenBudget,probeAgentPrograms,getAdapter,getSessionAgentEventHub,HOST_TURN_LEASE_MS,SessionAgentError,buildSessionSendServer,getSessionAgentOrchestrator,ensureSessionAgentOrchestrator,disposeSessionAgentOrchestrator,disposeAllSessionAgentOrchestrators,getHostProgramProbe,availablePrograms,relayBaseUrl,registerAgentHostRelayRoutes,hasAgentHostRelay,openAgentHostRelayRun,hostDecisionKey,decisionsForAwaited};
|
|
19
19
|
/**
|