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{DashScopeUploader}from"./chunk-RKDS7A4H.js";import{OmniDegradationCache,OmniTransportGuardError,assertWithinByteLimit,assertWithinDurationLimit,assertWithinTokenLimit,effectiveMaxUploadFileBytes,effectiveOmniStorageMaxTotalBytes,estimateRawResourceTokens,runFixedPolicies,runOmniGcOnce}from"./chunk-GSOBASYW.js";import{MEDIA_DETECTOR_VERSION,MediaMemoryService}from"./chunk-XFMPZINJ.js";import{runStartupRecoveryOnce}from"./chunk-HN5UYLPU.js";import{DEFAULT_UPLOAD_CACHE_TTL_HOURS,OmniUploadCache}from"./chunk-HTW7PYHK.js";import{OmniObjectStore,prepareOmniDownloadsDir}from"./chunk-YFTVFH2A.js";import{extensionForMime,hashFileSha256,recognizeMediaFile,sniffMediaType}from"./chunk-ZBHL2CXR.js";import{isFfmpegAvailable,isFfprobeAvailable}from"./chunk-NIOS3B3V.js";import{isOmniDeliveryActive}from"./chunk-OBV7RNHV.js";import{requireEffectiveOmniUploadConfig}from"./chunk-XZTE4YTN.js";import{OMNI_DISCLOSURE_TEXT_PREFIX,OMNI_OMISSION_TEXT_PREFIX,OMNI_RESOURCE_HANDLE_TEXT_PREFIX,OMNI_RESOURCE_PATH_TEXT_PREFIX,OMNI_TRANSCRIPT_TEXT_PREFIX,formatDisclosureText,formatOmissionText,formatResourceHandleText,formatTranscriptText,harnessPathAnnotationPart,isHarnessAnnotationPart,parseResourceHandleText,parseResourcePathText,splitAnnotationBody,unescapeAnnotationName}from"./chunk-SW54YEPK.js";import{isPermittedRedirect,isPrivateHost,resolveNetworkTarget}from"./chunk-5CWTKFI4.js";import{ImageViewError,boundImageBuffer,sniffBoundableImageMime}from"./chunk-Z6AR5XE5.js";import{TOOL_RESULT_MEDIA_REMEDY,clampInlineMediaPart,getMaxInlineMediaBytes}from"./chunk-Q6UAOTP3.js";import{detectRuntime,loadUndici}from"./chunk-ZZZAYAJW.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{isAbortError}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{createHash}from"node:crypto";import path4 from"node:path";import fs4 from"node:fs/promises";init_esbuild_shims();function buildSessionConditionNamespace(config,reservedOutputTokens){const session={reservedOutputTokens};const windowSize=config.getContentGeneratorConfig?.()?.contextWindowSize;const contextWindowTokens=typeof windowSize==="number"&&Number.isFinite(windowSize)&&windowSize>0?windowSize:void 0;if(contextWindowTokens!==void 0){session.contextWindowTokens=contextWindowTokens}let promptTokenCount;try{const count=config.getGeminiClient?.()?.getChat?.()?.getLastPromptTokenCount();if(typeof count==="number"&&Number.isFinite(count)&&count>=0){promptTokenCount=count}}catch{}if(promptTokenCount!==void 0){session.promptTokenCount=promptTokenCount}if(contextWindowTokens!==void 0&&promptTokenCount!==void 0){session.availableContextTokens=Math.max(0,contextWindowTokens-promptTokenCount-reservedOutputTokens)}return session}__name(buildSessionConditionNamespace,"buildSessionConditionNamespace");init_esbuild_shims();import{randomBytes}from"node:crypto";import{once}from"node:events";import{createWriteStream}from"node:fs";import fs from"node:fs/promises";import path from"node:path";import{Readable}from"node:stream";import{pipeline}from"node:stream/promises";var debugLogger=createDebugLogger("omni:download");var OmniDownloadError=class extends Error{static{__name(this,"OmniDownloadError")}constructor(message,options){super(message,options);this.name="OmniDownloadError"}};var RESOLVE_TIMEOUT_MS=3e4;var HEADER_TIMEOUT_MS=3e4;var IDLE_TIMEOUT_MS=6e4;var MAX_REDIRECTS=5;function parseHttpUrlRef(pathName){if(!/^https?:\/\//i.test(pathName))return null;try{return new URL(pathName)}catch{return null}}__name(parseHttpUrlRef,"parseHttpUrlRef");function scrubPathsFromMessage(message){return message.replace(/(?:[A-Za-z]:)?(?:[\\/][^\s'"`\\/]+){2,}[\\/]?/g,match=>path.basename(match))}__name(scrubPathsFromMessage,"scrubPathsFromMessage");function formatCauseChain(err){const parts=[];let cause=err instanceof Error?err.cause:void 0;for(let depth=0;cause!=null&&depth<4;depth++){const code=cause.code;const message=cause instanceof Error?cause.message:typeof cause==="string"?cause:void 0;if(typeof code==="string"&&message&&!message.includes(code)){parts.push(`${code}: ${message}`)}else if(message){parts.push(message)}else if(typeof code==="string"){parts.push(code)}cause=cause instanceof Error?cause.cause:void 0}return parts.length>0?scrubPathsFromMessage(parts.join("; ")):void 0}__name(formatCauseChain,"formatCauseChain");function detectConfiguredProxy(undici){for(const key of["https_proxy","HTTPS_PROXY","http_proxy","HTTP_PROXY","all_proxy","ALL_PROXY"]){if(process.env[key])return true}try{return undici.getGlobalDispatcher()instanceof undici.EnvHttpProxyAgent}catch{return false}}__name(detectConfiguredProxy,"detectConfiguredProxy");async function downloadMediaUrl(params){const{url,downloadsDir,maxBytes,signal,resolveTimeoutMs=RESOLVE_TIMEOUT_MS,headerTimeoutMs=HEADER_TIMEOUT_MS,idleTimeoutMs=IDLE_TIMEOUT_MS}=params;const resolveTarget=params.resolveTarget??(target=>resolveNetworkTarget(target,"public",signal));if(isPrivateHost(url)){throw new OmniDownloadError(`URL host is not publicly routable (refused for safety): ${new URL(url).hostname}`)}let parsed;try{parsed=new URL(url)}catch{throw new OmniDownloadError("URL media ref is not a valid URL (refused).")}if(parsed.protocol!=="https:"){throw new OmniDownloadError(`URL media must be https (refused for safety): ${parsed.protocol}//${parsed.hostname}`)}if(parsed.username||parsed.password){throw new OmniDownloadError(`URL media must not embed credentials (refused for safety): ${parsed.hostname}`)}const runtime=detectRuntime();if(runtime!=="node"){throw new OmniDownloadError(`URL media requires the Node runtime to verify the connection target (refused for safety on ${runtime}): use a local file path instead of a URL, or run under Node.`)}const undici=await loadUndici();const proxied=params.detectProxy?params.detectProxy():detectConfiguredProxy(undici);if(proxied){throw new OmniDownloadError(`URL media fetching is not supported behind a proxy yet (refused): the connection pinning that enforces SSRF protection cannot be applied through a proxy. Download the file manually and use a local path instead.`)}try{await prepareOmniDownloadsDir(downloadsDir)}catch(err){throw new OmniDownloadError(`Could not prepare the downloads directory for URL media: ${err instanceof Error?scrubPathsFromMessage(err.message):String(err)}`,{cause:err})}const partPath=path.join(downloadsDir,`${randomBytes(8).toString("hex")}.part`);let currentUrl=url;let dispatcher;try{for(let redirects=0;;redirects++){let target;const resolveAbort=new AbortController;const resolveTimer=setTimeout(()=>resolveAbort.abort(new Error("resolve timeout")),resolveTimeoutMs);try{const pending=resolveTarget(currentUrl);pending.catch(()=>{});target=await Promise.race([pending,new Promise((_,reject)=>{resolveAbort.signal.addEventListener("abort",()=>reject(resolveAbort.signal.reason),{once:true})})])}catch(err){if(signal?.aborted)throw err;if(resolveAbort.signal.aborted){throw new OmniDownloadError(`Download timed out resolving ${new URL(currentUrl).hostname} (${resolveTimeoutMs/1e3}s)`)}const text=err instanceof Error?err.message:String(err);const reason=/blocked address/i.test(text)?"resolved to a non-public address":/did not resolve/i.test(text)?"did not resolve":"could not be verified";throw new OmniDownloadError(`URL host ${reason} (refused for safety): ${new URL(currentUrl).hostname}`,{cause:err})}finally{clearTimeout(resolveTimer)}if(!target.lookup){throw new OmniDownloadError(`URL host cannot be safely bound to a verified address (refused for safety): ${new URL(currentUrl).hostname}`)}const fetchFn=params.fetchFn??undici.fetch;const previousDispatcher=dispatcher;dispatcher=new undici.Agent({connect:{lookup:target.lookup}});await previousDispatcher?.close().catch(()=>{});const headerAbort=new AbortController;const headerTimer=setTimeout(()=>headerAbort.abort(new Error("header timeout")),headerTimeoutMs);const combined=AbortSignal.any(signal?[signal,headerAbort.signal]:[headerAbort.signal]);let res;try{res=await fetchFn(currentUrl,{redirect:"manual",signal:combined,dispatcher})}catch(err){if(signal?.aborted)throw err;if(headerAbort.signal.aborted){throw new OmniDownloadError(`Download timed out waiting for response headers from ${new URL(currentUrl).hostname} (${headerTimeoutMs/1e3}s)`)}const detail=err instanceof Error?scrubPathsFromMessage(err.message):String(err);const causeDetail=formatCauseChain(err);throw new OmniDownloadError(`Download request failed for ${new URL(currentUrl).hostname}: ${detail}${causeDetail?` (${causeDetail})`:""}`,{cause:err})}finally{clearTimeout(headerTimer)}if(res.status>=300&&res.status<400){await res.body?.cancel().catch(()=>{});const location=res.headers.get("location");if(!location||redirects>=MAX_REDIRECTS){throw new OmniDownloadError(`Too many or invalid redirects downloading from ${new URL(currentUrl).hostname}`)}let redirectUrl;try{redirectUrl=new URL(location,currentUrl).toString()}catch{throw new OmniDownloadError(`Redirect with a malformed Location header from ${new URL(currentUrl).hostname}`)}if(!isPermittedRedirect(currentUrl,redirectUrl)){throw new OmniDownloadError(`Cross-origin redirect refused: ${new URL(currentUrl).hostname} \u2192 ${new URL(redirectUrl).hostname}`)}currentUrl=redirectUrl;continue}if(!res.ok){await res.body?.cancel().catch(()=>{});throw new OmniDownloadError(`Download failed: HTTP ${res.status} from ${new URL(currentUrl).hostname}`)}const contentLength=Number(res.headers.get("content-length"));if(Number.isFinite(contentLength)&&contentLength>maxBytes){await res.body?.cancel().catch(()=>{});throw new OmniDownloadError(`Download exceeds the omni media limit: Content-Length ${contentLength} > ${maxBytes} bytes.`)}if(!res.body){throw new OmniDownloadError("Download response had no body.")}let written=0;const idleAbort=new AbortController;let idleTimer=setTimeout(()=>idleAbort.abort(new Error("idle timeout")),idleTimeoutMs);const streamSignal=AbortSignal.any(signal?[signal,idleAbort.signal]:[idleAbort.signal]);try{const source=Readable.fromWeb(res.body,{signal:streamSignal});const counter=__name(async function*(src){for await(const chunk of src){clearTimeout(idleTimer);idleTimer=setTimeout(()=>idleAbort.abort(new Error("idle timeout")),idleTimeoutMs);written+=chunk.length;if(written>maxBytes){throw new OmniDownloadError(`Download exceeds the omni media limit: >${maxBytes} bytes received.`)}yield chunk}},"counter");const destination=createWriteStream(partPath,{mode:384});await once(destination,"open");await pipeline(source,counter,destination)}catch(err){if(signal?.aborted)throw err;if(err instanceof OmniDownloadError)throw err;if(idleAbort.signal.aborted){throw new OmniDownloadError(`Download stalled from ${new URL(currentUrl).hostname}: no data for ${idleTimeoutMs/1e3}s`)}throw new OmniDownloadError(`Download interrupted from ${new URL(currentUrl).hostname}: ${err instanceof Error?scrubPathsFromMessage(err.message):String(err)}`,{cause:err})}finally{clearTimeout(idleTimer)}debugLogger.debug(`downloaded ${written} bytes from ${new URL(currentUrl).hostname}`);return{partPath}}}catch(err){await fs.rm(partPath,{force:true});throw err}finally{await dispatcher?.close().catch(()=>{})}}__name(downloadMediaUrl,"downloadMediaUrl");init_esbuild_shims();import{randomBytes as randomBytes2}from"node:crypto";import fs2 from"node:fs/promises";import path2 from"node:path";var debugLogger2=createDebugLogger("omni:tool-result");var MAX_UPLOADS_PER_TOOL_RESULT=8;var MAX_UPLOAD_BYTES_PER_TOOL_RESULT=128*1024*1024;async function boundDeclinedInlinePart(part,bytes,signal){const inline=part.inlineData;if(!inline?.data)return part;const inlineByteCeiling=getMaxInlineMediaBytes();let boundedPart=part;if(sniffBoundableImageMime(bytes.subarray(0,12))){try{const view=await boundImageBuffer(bytes,`tool-result media (${inline.mimeType??"unknown"})`,signal,inlineByteCeiling);if(view){boundedPart={inlineData:{...inline,data:view.bytes.toString("base64"),mimeType:view.mimeType}}}}catch(error){if(!(error instanceof ImageViewError)){throw error}debugLogger2.debug(`tool-result media kept inline could not be bounded: ${error.message}`)}}return clampInlineMediaPart(boundedPart,inlineByteCeiling,TOOL_RESULT_MEDIA_REMEDY)}__name(boundDeclinedInlinePart,"boundDeclinedInlinePart");async function processToolResultOmniMedia(responseParts,config,signal){if(!isOmniDeliveryActive(config))return responseParts;const modalities=config.getContentGeneratorConfig?.()?.modalities??{};let changed=false;let uploadsRemaining=MAX_UPLOADS_PER_TOOL_RESULT;let uploadBytesRemaining=MAX_UPLOAD_BYTES_PER_TOOL_RESULT;const keepInline=__name(async(part,bytes)=>{const kept=await boundDeclinedInlinePart(part,bytes,signal);if(kept!==part)changed=true;return[kept]},"keepInline");const convertPart=__name(async part=>{const inline=part.inlineData;if(!inline?.data||!inline.mimeType)return[part];const top=inline.mimeType.split("/")[0];if(top!=="image"&&top!=="audio"&&top!=="video")return[part];const bytes=Buffer.from(inline.data,"base64");const sniffed=sniffMediaType(bytes.subarray(0,4096));if(!sniffed)return keepInline(part,bytes);if(!modalities[sniffed.modality]){return keepInline(part,bytes)}if(uploadsRemaining<=0||bytes.length>uploadBytesRemaining){debugLogger2.debug(`tool-result media budget exhausted; keeping part inline (${bytes.length} bytes)`);return keepInline(part,bytes)}const store=new OmniObjectStore(config.storage.getQwenDir());let tempPath;const displayName=inline.displayName??`tool-media.${top}`;try{const stagingDir=await prepareOmniDownloadsDir(path2.join(store.getOmniRootDir(),"downloads"));tempPath=path2.join(stagingDir,`${randomBytes2(8).toString("hex")}.part`);await fs2.writeFile(tempPath,bytes,{mode:384});const delivery=await processMediaForOmniDelivery(tempPath,config,{expectedModality:sniffed.modality,signal,displayName,origin:"tool"});const transcriptParts=buildTranscriptParts(displayName,delivery.transcripts);const additionalParts=buildAdditionalMediaParts(displayName,delivery.additionalMedia);uploadsRemaining-=delivery.additionalMedia?.filter(e=>!e.omission).length??0;const handleParts=delivery.resourceId?[{text:formatResourceHandleText(displayName,delivery.resourceId)}]:[];if(delivery.omission){changed=true;return[...handleParts,{text:formatOmissionText(displayName,delivery.omission.reason)},...additionalParts,...transcriptParts]}if(!delivery.fileUri&&transcriptParts.length>0){changed=true;return delivery.disclosure?[...handleParts,{text:formatDisclosureText(displayName,delivery.disclosure)},...additionalParts,...transcriptParts]:[...handleParts,...additionalParts,...transcriptParts]}changed=true;uploadsRemaining--;uploadBytesRemaining-=bytes.length;const fileDataPart={fileData:{fileUri:delivery.fileUri,mimeType:delivery.mimeType,displayName}};return delivery.disclosure?[...handleParts,{text:formatDisclosureText(displayName,delivery.disclosure)},fileDataPart,...additionalParts,...transcriptParts]:[...handleParts,fileDataPart,...additionalParts,...transcriptParts]}catch(err){if(signal.aborted)throw err;if(err instanceof OmniTransportGuardError){changed=true;return[...err.sessionResourceId?[{text:formatResourceHandleText(displayName,err.sessionResourceId)}]:[],{text:`[Tool media part withheld by the omni transport guard: ${err.message}]`}]}debugLogger2.debug(`tool-result media upload failed, keeping inline: ${err instanceof Error?err.message:String(err)}`);return keepInline(part,bytes)}finally{if(tempPath!==void 0){await fs2.rm(tempPath,{force:true}).catch(()=>{})}}},"convertPart");const result=[];for(const part of responseParts){const nested=part.functionResponse?.parts;if(Array.isArray(nested)&&nested.length>0){const convertedNested=[];let nestedChanged=false;for(const nestedPart of nested){const converted=await convertPart(nestedPart);if(converted.length!==1||converted[0]!==nestedPart){nestedChanged=true}convertedNested.push(...converted)}if(nestedChanged){result.push({...part,functionResponse:{...part.functionResponse,parts:convertedNested}});changed=true}else{result.push(part)}continue}result.push(...await convertPart(part))}return changed?result:responseParts}__name(processToolResultOmniMedia,"processToolResultOmniMedia");init_esbuild_shims();import fs3 from"node:fs/promises";import path3 from"node:path";var debugLogger3=createDebugLogger("omni:export");function textOfPart(part){if(typeof part==="string")return part;if(typeof part==="object"&&part!==null&&"text"in part){const text=part.text;return typeof text==="string"?text:void 0}return void 0}__name(textOfPart,"textOfPart");function functionResponseOfPart(part){if(typeof part!=="object"||part===null)return void 0;const response=part.functionResponse;if(typeof response!=="object"||response===null)return void 0;const{id,parts}=response;return{id,...Array.isArray(parts)?{parts}:{}}}__name(functionResponseOfPart,"functionResponseOfPart");function isThoughtPart(part){return typeof part==="object"&&part!==null&&part.thought===true}__name(isThoughtPart,"isThoughtPart");function functionCallOfPart(part){if(typeof part!=="object"||part===null)return void 0;const fc=part.functionCall;if(typeof fc!=="object"||fc===null)return void 0;const{id,name,args}=fc;if(typeof name!=="string")return void 0;const cleanArgs=typeof args==="object"&&args!==null?{...args}:void 0;return{...typeof id==="string"?{callId:id}:{},name,...cleanArgs?{args:cleanArgs}:{}}}__name(functionCallOfPart,"functionCallOfPart");function stripSystemReminders(text){return text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g,"")}__name(stripSystemReminders,"stripSystemReminders");function mediaFor(turn,name){let media=turn.media.get(name);if(!media){media={name,disclosures:[],transcripts:[]};turn.media.set(name,media)}return media}__name(mediaFor,"mediaFor");function consumeAnnotationPart(turn,text,isHarnessAnnotation){if(text.startsWith(OMNI_RESOURCE_HANDLE_TEXT_PREFIX)){const resourceId=parseResourceHandleText(text);if(resourceId){const body=text.slice(OMNI_RESOURCE_HANDLE_TEXT_PREFIX.length);const name=unescapeAnnotationName(body.slice(0,body.length-resourceId.length-1));mediaFor(turn,name).resourceId=resourceId;return true}return false}if(text.startsWith(OMNI_RESOURCE_PATH_TEXT_PREFIX)){if(!isHarnessAnnotation)return false;const filePath=parseResourcePathText(text);if(filePath){mediaFor(turn,filePath.split(/[\\/]/).pop()??filePath);return true}return false}for(const[prefix,apply]of[[OMNI_DISCLOSURE_TEXT_PREFIX,(m,payload)=>{m.disclosures.push(payload)}],[OMNI_OMISSION_TEXT_PREFIX,(m,payload)=>{m.omitted=payload}],[OMNI_TRANSCRIPT_TEXT_PREFIX,(m,payload)=>{m.transcripts.push(payload)}]]){if(!text.startsWith(prefix))continue;const split=splitAnnotationBody(text.slice(prefix.length));if(!split)return false;apply(mediaFor(turn,split.name),split.payload);return true}return false}__name(consumeAnnotationPart,"consumeAnnotationPart");function consumeRecordParts(turn,record,collectProse){const parts=(record.message?.parts??[]).flatMap(part=>[part,...functionResponseOfPart(part)?.parts??[]]);for(const part of parts){const raw=textOfPart(part);if(raw===void 0)continue;const withoutReminders=stripSystemReminders(raw);const forAnnotation=withoutReminders.replace(/^\s+/,"");if(consumeAnnotationPart(turn,forAnnotation,isHarnessAnnotationPart(part)))continue;const prose=withoutReminders.trim();if(!prose)continue;if(collectProse)turn.requestTexts.push(prose)}}__name(consumeRecordParts,"consumeRecordParts");function finishTurn(turn,sessionId){return{kind:"turn",sessionId,turnIndex:turn.turnIndex,...turn.timestamp!==void 0?{timestamp:turn.timestamp}:{},request:{text:turn.requestTexts.join("\n"),media:[...turn.media.values()],...turn.recall!==void 0?{recall:turn.recall}:{}},response:{text:turn.responseTexts.join("\n"),toolCalls:turn.toolCalls}}}__name(finishTurn,"finishTurn");function activeChainRecords(records){const byUuid=new Map;for(const record of records){if(typeof record.uuid==="string")byUuid.set(record.uuid,record)}if(byUuid.size===0)return records;let leaf;for(let i=records.length-1;i>=0;i--){if(typeof records[i].uuid==="string"){leaf=records[i];break}}if(!leaf)return records;const active=new Set;let current=leaf;while(current?.uuid&&!active.has(current.uuid)){active.add(current.uuid);current=typeof current.parentUuid==="string"?byUuid.get(current.parentUuid):void 0}return records.filter(r=>typeof r.uuid!=="string"||active.has(r.uuid))}__name(activeChainRecords,"activeChainRecords");function buildTurnRecords(transcriptLines){const turns=[];let sessionId="";let current;for(const record of activeChainRecords(transcriptLines)){if(typeof record.sessionId==="string"&&sessionId===""){sessionId=record.sessionId}if(record.type==="user"&&record.subtype===void 0){if(current)turns.push(finishTurn(current,sessionId));current={turnIndex:turns.length,...record.timestamp!==void 0?{timestamp:record.timestamp}:{},requestTexts:[],media:new Map,responseTexts:[],toolCalls:[]};consumeRecordParts(current,record,true);continue}if(!current)continue;if(record.type==="system"&&record.subtype==="omni_recall"){current.recall=record.systemPayload;continue}if(record.type==="tool_result"){consumeRecordParts(current,record,false);continue}if(record.type==="assistant"){for(const part of record.message?.parts??[]){if(isThoughtPart(part))continue;const text=textOfPart(part);if(text!==void 0&&text.trim()){current.responseTexts.push(text);continue}const call=functionCallOfPart(part);if(call)current.toolCalls.push(call)}}}if(current)turns.push(finishTurn(current,sessionId));return turns}__name(buildTurnRecords,"buildTurnRecords");async function readSnapshotRaw(omniRootDir){const filePath=path3.join(omniRootDir,"memory.json");let raw;try{raw=await fs3.readFile(filePath,"utf8")}catch{return void 0}try{const parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null||[parsed.files,parsed.versions,parsed.executions,parsed.entries].some(c=>typeof c!=="object"||c===null||Array.isArray(c))){throw new Error("unexpected snapshot shape")}return parsed}catch(err){debugLogger3.debug(`trajectory export: memory unreadable, exporting transcript only: ${err instanceof Error?err.message:err}`);return void 0}}__name(readSnapshotRaw,"readSnapshotRaw");function buildMemoryRecords(snapshot){const files=[];const executions=[];for(const version of Object.values(snapshot.versions)){try{const file=snapshot.files[version.fileId];if(!file)continue;files.push({kind:"file",fileId:version.fileId,fileVersionId:version.fileVersionId,rootFileId:file.rootFileId,sha256:version.sha256,mediaType:version.mediaType,origin:file.origin,sizeBytes:version.sizeBytes,mimeType:version.mimeType,source:version.source,...version.producedByExecutionId!==void 0?{producedByExecutionId:version.producedByExecutionId}:{},...version.parentVersionId!==void 0?{parentVersionId:version.parentVersionId}:{},createdAt:version.createdAt})}catch{}}for(const execution of Object.values(snapshot.executions)){try{const outputs=execution.outputRefs.flatMap(entryId=>{const entry=snapshot.entries[entryId];if(!entry)return[];return[{kind:entry.kind,...entry.role!==void 0?{role:entry.role}:{},...entry.artifactRef?.managedId?.startsWith("sha256/")?{sha256:entry.artifactRef.managedId.slice("sha256/".length)}:{},...entry.artifactRef?.mimeType!==void 0?{mimeType:entry.artifactRef.mimeType}:{},...entry.artifactRef?.sizeBytes!==void 0?{sizeBytes:entry.artifactRef.sizeBytes}:{},...entry.disclosure!==void 0?{disclosure:entry.disclosure}:{}}]});executions.push({kind:"execution",executionId:execution.executionId,invocationId:execution.invocationId,executionOrigin:execution.executionOrigin,toolName:execution.toolName,...execution.toolVersion!==void 0?{toolVersion:execution.toolVersion}:{},finalArguments:execution.finalArguments,omniConfigHash:execution.omniConfigHash,sourceVersionId:execution.sourceVersionId,rootFileId:execution.rootFileId,startedAt:execution.startedAt,completedAt:execution.completedAt,...execution.reusedExecutionId!==void 0?{reusedExecutionId:execution.reusedExecutionId}:{},outputs})}catch{}}return{files,executions}}__name(buildMemoryRecords,"buildMemoryRecords");function filterToSession(memory,turns,transcriptLines){const callIds=new Set;for(const record of activeChainRecords(transcriptLines)){if(record.type!=="tool_result")continue;for(const part of record.message?.parts??[]){const id=functionResponseOfPart(part)?.id;if(typeof id==="string")callIds.add(id)}}const mediaNames=new Set;for(const turn of turns){for(const call of turn.response.toolCalls){if(call.callId)callIds.add(call.callId)}for(const media of turn.request.media)mediaNames.add(media.name)}const filesByVersion=new Map(memory.files.map(f=>[f.fileVersionId,f]));const versionsByFile=new Map;for(const f of memory.files){const list=versionsByFile.get(f.fileId)??[];list.push(f);versionsByFile.set(f.fileId,list)}const includedFiles=new Set;const includedExecutions=new Set;const includeFile=__name(fileId=>{if(!fileId||includedFiles.has(fileId))return false;if(!versionsByFile.has(fileId))return false;includedFiles.add(fileId);return true},"includeFile");for(const f of memory.files){if(mediaNames.has(f.source.locator))includeFile(f.fileId)}for(const e of memory.executions){if(callIds.has(e.invocationId))includedExecutions.add(e.executionId)}let changed=true;while(changed){changed=false;for(const e of memory.executions){const sourceFile=filesByVersion.get(e.sourceVersionId)?.fileId;if(!includedExecutions.has(e.executionId)){if(sourceFile&&includedFiles.has(sourceFile)){includedExecutions.add(e.executionId);changed=true}else{continue}}if(includeFile(sourceFile))changed=true}for(const f of memory.files){if(includedFiles.has(f.fileId))continue;if(f.producedByExecutionId!==void 0&&includedExecutions.has(f.producedByExecutionId)){includeFile(f.fileId);changed=true}}}return{files:memory.files.filter(f=>includedFiles.has(f.fileId)),executions:memory.executions.filter(e=>includedExecutions.has(e.executionId))}}__name(filterToSession,"filterToSession");async function exportOmniTrajectory(options){const raw=await fs3.readFile(options.transcriptPath,"utf8");const transcriptLines=[];for(const line of raw.split("\n")){if(!line.trim())continue;try{transcriptLines.push(JSON.parse(line))}catch{}}const turns=buildTurnRecords(transcriptLines);const records=[...turns];const snapshot=await readSnapshotRaw(options.omniRootDir);const memoryRecords=snapshot?filterToSession(buildMemoryRecords(snapshot),turns,transcriptLines):{files:[],executions:[]};records.push(...memoryRecords.files.sort((a,b)=>a.fileVersionId.localeCompare(b.fileVersionId)),...memoryRecords.executions.sort((a,b)=>a.executionId.localeCompare(b.executionId)));return records}__name(exportOmniTrajectory,"exportOmniTrajectory");function serializeOmniTrajectory(records){return records.map(r=>JSON.stringify(r)).join("\n")+"\n"}__name(serializeOmniTrajectory,"serializeOmniTrajectory");async function writeOmniTrajectoryJsonl(options){const outPath=path3.resolve(options.outPath);if(outPath===path3.resolve(options.transcriptPath)){throw new Error("trajectory outPath must differ from the transcript path")}const records=await exportOmniTrajectory(options);await fs3.mkdir(path3.dirname(outPath),{recursive:true});await fs3.writeFile(outPath,serializeOmniTrajectory(records),"utf8");return{records:records.length}}__name(writeOmniTrajectoryJsonl,"writeOmniTrajectoryJsonl");var debugLogger4=createDebugLogger("omni");function sanitizeErrorMessage(err,knownPaths=[]){let msg=err instanceof Error?err.message:String(err);for(const known of knownPaths){if(!known)continue;msg=msg.split(known).join(path4.basename(known));const segments=known.split(/[\\/]+/).filter(Boolean);if(/^[A-Za-z]:$/.test(segments[0]??""))segments.shift();if(segments.length>=2){const spelled=segments.map(segment=>segment.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("[\\\\/]+");msg=msg.replace(new RegExp(`(?:[A-Za-z]:)?[\\\\/]*${spelled}`,"g"),()=>path4.basename(known))}}return msg.replace(/(?:\/[^/\s'"]+)+\/([^/\s'"]+)/g,"$1").replace(/(?:[A-Za-z]:)?(?:\\[^\\\s'"]+)+\\([^\\\s'"]+)/g,"$1")}__name(sanitizeErrorMessage,"sanitizeErrorMessage");function buildAdditionalMediaParts(displayName,additionalMedia){const parts=[];for(const extra of additionalMedia??[]){if(extra.disclosure){parts.push({text:formatDisclosureText(displayName,extra.disclosure)})}if(extra.omission){parts.push({text:formatOmissionText(displayName,extra.omission.reason)})}else{parts.push({fileData:{fileUri:extra.fileUri,mimeType:extra.mimeType,displayName}})}}return parts}__name(buildAdditionalMediaParts,"buildAdditionalMediaParts");function buildTranscriptParts(displayName,transcripts){const parts=[];for(const t of transcripts??[]){if(t.disclosure){parts.push({text:formatDisclosureText(displayName,t.disclosure)})}parts.push({text:formatTranscriptText(displayName,t.text)})}return parts}__name(buildTranscriptParts,"buildTranscriptParts");var OmniDeliveryError=class extends Error{static{__name(this,"OmniDeliveryError")}constructor(message,options){super(message,options);this.name="OmniDeliveryError"}};function evaluateTransportLimits(config,recognized,displayName){try{assertWithinByteLimit(config,recognized.sizeBytes,displayName);assertWithinDurationLimit(config,recognized,displayName);return{estimate:assertWithinTokenLimit(config,recognized,displayName)}}catch(err){if(err instanceof OmniTransportGuardError){return{estimate:estimateRawResourceTokens(recognized),violation:err.message}}throw err}}__name(evaluateTransportLimits,"evaluateTransportLimits");async function processMediaForOmniDelivery(filePath,config,options){const{expectedModality,signal}=options??{};const displayName=options?.displayName??path4.basename(filePath);const[ffmpeg,ffprobe]=await Promise.all([isFfmpegAvailable(),isFfprobeAvailable()]);if(!ffmpeg||!ffprobe){throw new OmniDeliveryError("ffmpeg/ffprobe not available; omni media delivery requires both on PATH.")}await fs4.stat(filePath).catch(err=>{throw new OmniDeliveryError(`Cannot stat media file ${displayName}: ${sanitizeErrorMessage(err,[filePath])}`,{cause:err})});let recognized;try{recognized=await recognizeMediaFile(filePath,{expectedModality,signal})}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(`Media recognition failed for ${displayName}: ${sanitizeErrorMessage(err,[filePath])}`,{cause:err})}const store=new OmniObjectStore(config.storage.getQwenDir());const uploadConfig=requireEffectiveOmniUploadConfig(config);const cacheScope=createHash("sha256").update(`${uploadConfig.baseUrl}|${uploadConfig.apiKey}`).digest("hex").slice(0,16);const configuredTtl=config.getOmniUploadUrlTtlHours?.();const uploadCache=new OmniUploadCache(store.getOmniRootDir(),configuredTtl===void 0?DEFAULT_UPLOAD_CACHE_TTL_HOURS:configuredTtl,cacheScope);await runStartupRecoveryOnce(store,uploadCache,{quarantineRetentionDays:config.getOmniQuarantineRetentionDays?.(),quarantineMaxBytes:config.getOmniQuarantineMaxBytes?.(),degradationCache:new OmniDegradationCache(store.getOmniRootDir())});const processingConfig=config.getOmniProcessingConfig?.();const conditionContext=processingConfig?{session:buildSessionConditionNamespace(config,processingConfig.limits.reservedOutputTokens)}:void 0;const memoryConfig=config.getOmniMemoryConfig?.();const memoryService=memoryConfig?new MediaMemoryService(store.getOmniRootDir(),{maxInlineTextBytes:memoryConfig.collection.maxInlineTextBytes}):void 0;if(memoryService){void runOmniGcOnce({store,memoryService,registry:config.getOmniMediaResourceRegistry?.(),uploadCache,degradationCache:new OmniDegradationCache(store.getOmniRootDir()),retentionDays:config.getOmniStorageRetentionDays?.()??14,maxTotalBytes:typeof config.getOmniStorageMaxTotalBytes==="function"?effectiveOmniStorageMaxTotalBytes(config):20*1024*1024*1024})}const registry=memoryService?config.getOmniMediaResourceRegistry?.():void 0;const bindSessionResource=__name((item,fileRefOverride)=>registry&&item.memoryBinding?registry.bind({...item.memoryBinding,fileRef:fileRefOverride??item.filePath,mediaType:item.recognized.modality}):void 0,"bindSessionResource");let sourceSha256;let sourceBinding;let sourceFileRef=filePath;if(memoryService){try{sourceSha256=await hashFileSha256(filePath,signal)}catch(err){if(signal?.aborted)throw err;debugLogger4.debug(`omni memory: hashing ${displayName} failed, skipping collection: ${sanitizeErrorMessage(err,[filePath])}`)}if(sourceSha256){const origin=options?.origin??"user";const ephemeralSource=origin==="tool"||options?.sourceUrl!==void 0;sourceFileRef=ephemeralSource?store.objectPathFor(sourceSha256,extensionForMime(recognized.detectedMimeType)):filePath;sourceBinding=await memoryService.recordFileRecognized({fileRef:sourceFileRef,sha256:sourceSha256,mediaType:recognized.modality,metadata:recognized.metadata,sizeBytes:recognized.sizeBytes,mimeType:recognized.detectedMimeType,origin,source:options?.sourceUrl!==void 0?{protocol:"url",locator:options.sourceUrl}:origin==="tool"?{protocol:"managed",locator:`sha256/${sourceSha256}`}:{protocol:"local",locator:displayName},recognition:{ingestionConfigHash:"",detectorVersion:MEDIA_DETECTOR_VERSION,probeStatus:"complete"}})}}let final={filePath,recognized,sha256:sourceSha256,memoryBinding:sourceBinding};const sessionResourceId=bindSessionResource(final,sourceFileRef)?.resourceId;const guardRejection=__name((message,options2)=>{const err=new OmniTransportGuardError(message,options2);if(sessionResourceId!==void 0){err.sessionResourceId=sessionResourceId}return err},"guardRejection");let extraDeliveries=[];const transcripts=[];const collectTranscripts=__name(files=>{for(const file of files){transcripts.push({text:file.text,disclosure:file.disclosure})}},"collectTranscripts");const textOnlyDelivery=__name((recognizedFinal,tokenEstimate2,extras)=>({fileUri:"",mimeType:recognizedFinal.detectedMimeType,sha256:"",recognized:recognizedFinal,tokenEstimate:tokenEstimate2,deduped:false,uploadCacheHit:false,degraded:true,transcripts,resourceId:sessionResourceId,...extras}),"textOnlyDelivery");const policies=processingConfig?.fixedPolicies??[];if(policies.length>0){let deliveries;let fileDeliveries;try{({deliveries,fileDeliveries}=await runFixedPolicies(config,{filePath,recognized,displayName,origin:options?.origin??"user",sha256:sourceSha256},{store,policies,signal,limits:processingConfig?.limits,conditionContext,memory:memoryService?{service:memoryService,sourceBinding}:void 0}))}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(`Fixed-policy processing failed for ${displayName}: ${sanitizeErrorMessage(err,[filePath,store.getOmniRootDir()])}`,{cause:err})}collectTranscripts(fileDeliveries);if(deliveries.length===0&&transcripts.length>0){return textOnlyDelivery(recognized,evaluateTransportLimits(config,recognized,displayName).estimate)}if(deliveries.length===0){throw new OmniDeliveryError(`Fixed policies produced 0 media deliverables for ${displayName}; exactly one is supported.`)}final=deliveries[0];extraDeliveries=deliveries.slice(1);for(const delivery of deliveries)bindSessionResource(delivery)}const uploadModel=uploadConfig.model;const uploadResource=__name(async(item,estimate)=>{let sha256;try{sha256=item.sha256??await hashFileSha256(item.filePath,signal)}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(`Failed to hash media file ${displayName}: ${sanitizeErrorMessage(err,[item.filePath])}`,{cause:err})}const cachedUrl=await uploadCache.get(sha256,uploadModel);if(cachedUrl){debugLogger4.debug(`omni upload cache hit: sha256=${sha256.slice(0,12)}\u2026 model=${uploadModel}`);return{fileUri:cachedUrl,sha256,deduped:true,uploadCacheHit:true}}const extension=extensionForMime(item.recognized.detectedMimeType);let objectPath;let deduped;try{const put=await store.putFile(item.filePath,sha256,extension,signal);objectPath=put.objectPath;deduped=put.deduped}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(`Failed to store media in the omni object store: ${sanitizeErrorMessage(err,[item.filePath,store.getOmniRootDir()])}`,{cause:err})}const uploader=new DashScopeUploader({apiKey:uploadConfig.apiKey,baseUrl:uploadConfig.baseUrl});let fileUri;try{fileUri=await uploader.uploadFile({filePath:objectPath,model:uploadModel,mimeType:item.recognized.detectedMimeType,signal})}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(sanitizeErrorMessage(err,[objectPath,store.getOmniRootDir()]),{cause:err})}debugLogger4.debug(`omni ${item.recognized.modality} delivered: sha256=${sha256.slice(0,12)}\u2026 size=${item.recognized.sizeBytes} est=${estimate.estimatedTokenCount}(${estimate.status}) deduped=${deduped} degraded=${item.degraded===true} uri=${fileUri}`);await uploadCache.put(sha256,uploadModel,fileUri);return{fileUri,sha256,deduped,uploadCacheHit:false}},"uploadResource");const processAdditionalMedia=__name(async()=>{if(extraDeliveries.length===0)return void 0;return Promise.all(extraDeliveries.map(async extra=>{const extraGuard=evaluateTransportLimits(config,extra.recognized,displayName);if(extraGuard.violation){debugLogger4.debug(`omni additional ${extra.recognized.modality} explicitly omitted (transport guard): ${extraGuard.violation}`);return{fileUri:"",mimeType:extra.recognized.detectedMimeType,sha256:extra.sha256??"",disclosure:extra.disclosure,omission:{reason:extraGuard.violation}}}const uploaded2=await uploadResource(extra,extraGuard.estimate);return{fileUri:uploaded2.fileUri,mimeType:extra.recognized.detectedMimeType,sha256:uploaded2.sha256,disclosure:extra.disclosure}}))},"processAdditionalMedia");let guard=evaluateTransportLimits(config,final.recognized,displayName);if(guard.violation&&processingConfig){const maxPasses=processingConfig.limits.maxTransportPasses;for(let pass=0;guard.violation&&pass<maxPasses;pass++){const guardPolicies=processingConfig.transportGuardPolicies.filter(p=>p.mediaTypes.includes(final.recognized.modality));if(guardPolicies.length===0)break;let deliveries;let fileDeliveries;try{({deliveries,fileDeliveries}=await runFixedPolicies(config,{filePath:final.filePath,recognized:final.recognized,displayName,origin:options?.origin??"user",sha256:final.sha256},{store,policies:guardPolicies,signal,limits:processingConfig.limits,conditionContext,memory:memoryService?{service:memoryService,sourceBinding:final.memoryBinding}:void 0}))}catch(err){if(signal?.aborted)throw err;throw guardRejection(`Transport-guard processing failed for ${displayName}: ${sanitizeErrorMessage(err,[final.filePath,store.getOmniRootDir()])}`,{cause:err})}collectTranscripts(fileDeliveries);if(deliveries.length===0&&fileDeliveries.length>0){return textOnlyDelivery(final.recognized,guard.estimate,{disclosure:final.disclosure,additionalMedia:await processAdditionalMedia()})}if(deliveries.length!==1){throw guardRejection(`Transport-guard policies produced ${deliveries.length} media deliverables for ${displayName}; exactly one is supported.`)}if(deliveries[0].filePath===final.filePath){break}const priorDisclosure=final.disclosure;final=deliveries[0];if(priorDisclosure&&final.disclosure){final={...final,disclosure:`${priorDisclosure}\uFF1B${final.disclosure}`}}else if(priorDisclosure){final={...final,disclosure:priorDisclosure}}bindSessionResource(final);guard=evaluateTransportLimits(config,final.recognized,displayName)}}if(guard.violation){if(!processingConfig){throw guardRejection(guard.violation)}debugLogger4.debug(`omni ${final.recognized.modality} explicitly omitted (transport guard): ${guard.violation}`);return{fileUri:"",mimeType:final.recognized.detectedMimeType,sha256:final.sha256??"",recognized:final.recognized,tokenEstimate:guard.estimate,deduped:false,uploadCacheHit:false,disclosure:final.disclosure,degraded:final.degraded,omission:{reason:guard.violation},transcripts:transcripts.length>0?transcripts:void 0,additionalMedia:await processAdditionalMedia(),resourceId:sessionResourceId}}const tokenEstimate=guard.estimate;const uploaded=await uploadResource(final,tokenEstimate);return{fileUri:uploaded.fileUri,mimeType:final.recognized.detectedMimeType,sha256:uploaded.sha256,recognized:final.recognized,tokenEstimate,deduped:uploaded.deduped,uploadCacheHit:uploaded.uploadCacheHit,disclosure:final.disclosure,degraded:final.degraded,transcripts:transcripts.length>0?transcripts:void 0,additionalMedia:await processAdditionalMedia(),resourceId:sessionResourceId}}__name(processMediaForOmniDelivery,"processMediaForOmniDelivery");async function readMediaViaOmniDelivery(params){const{filePath,config,displayName,relativePathForDisplay,expectedModality,signal}=params;try{const delivery=await processMediaForOmniDelivery(filePath,config,{expectedModality,signal});const transcriptParts=buildTranscriptParts(displayName,delivery.transcripts);const additionalParts=buildAdditionalMediaParts(displayName,delivery.additionalMedia);const handleParts=(()=>{if(!delivery.resourceId)return[];const binding=config.getOmniMediaResourceRegistry?.()?.resolve(delivery.resourceId);if(binding&&binding.fileRef===filePath&&!/[\r\n]/.test(filePath)){return[harnessPathAnnotationPart(filePath)]}return[{text:formatResourceHandleText(displayName,delivery.resourceId)}]})();if(delivery.omission){const omissionPart={text:formatOmissionText(displayName,delivery.omission.reason)};return{llmContent:transcriptParts.length>0||additionalParts.length>0||handleParts.length>0?[...handleParts,omissionPart,...additionalParts,...transcriptParts]:omissionPart.text,returnDisplay:`Media omitted by the omni transport guard: ${relativePathForDisplay}`,tokenEstimate:delivery.tokenEstimate}}if(!delivery.fileUri&&transcriptParts.length>0){const disclosureParts=delivery.disclosure?[{text:formatDisclosureText(displayName,delivery.disclosure)}]:[];return{llmContent:[...handleParts,...disclosureParts,...additionalParts,...transcriptParts],returnDisplay:`Read ${delivery.recognized.modality} as transcript (omni policy): ${relativePathForDisplay}`,tokenEstimate:delivery.tokenEstimate}}const fileDataPart={fileData:{fileUri:delivery.fileUri,mimeType:delivery.mimeType,displayName}};const parts=[...handleParts];const{width,height}=delivery.recognized.metadata;if(delivery.recognized.modality==="image"&&width!==void 0&&height!==void 0){parts.push({text:delivery.disclosure?`Image ${displayName}: delivered at ${width}x${height} px after degradation. Use zoom_image to inspect details \u2014 it reads the original file.`:`Image ${displayName}: full resolution ${width}x${height} px. Use zoom_image for a closer look at details.`})}if(delivery.disclosure){parts.push({text:formatDisclosureText(displayName,delivery.disclosure)})}parts.push(fileDataPart);parts.push(...additionalParts);parts.push(...transcriptParts);const llmContent=parts.length===1?fileDataPart:parts;return{llmContent,returnDisplay:`Read ${delivery.recognized.modality} file (omni upload): ${relativePathForDisplay}`,tokenEstimate:delivery.tokenEstimate}}catch(err){if(isAbortError(err)||signal?.aborted)throw err;const message=sanitizeErrorMessage(err,[filePath]);return{llmContent:`[Omni media delivery failed for ${displayName}: ${message}]`,returnDisplay:`Failed to deliver media via omni upload: ${relativePathForDisplay}`,error:`Omni media delivery failed: ${displayName}: ${message}`,errorType:"read_content_failure"}}}__name(readMediaViaOmniDelivery,"readMediaViaOmniDelivery");function effectiveMaxDownloadFileBytes(config){const uploadCap=effectiveMaxUploadFileBytes(config);const configured=config.getOmniUrlDownloadMaxFileBytes?.();if(configured!==void 0&&configured>0){return Math.min(configured,uploadCap)}return uploadCap}__name(effectiveMaxDownloadFileBytes,"effectiveMaxDownloadFileBytes");export{OmniDownloadError,parseHttpUrlRef,downloadMediaUrl,exportOmniTrajectory,serializeOmniTrajectory,writeOmniTrajectoryJsonl,sanitizeErrorMessage,buildAdditionalMediaParts,buildTranscriptParts,OmniDeliveryError,processMediaForOmniDelivery,readMediaViaOmniDelivery,effectiveMaxDownloadFileBytes,processToolResultOmniMedia};
|
|
3
|
+
import{DashScopeUploader}from"./chunk-RKDS7A4H.js";import{OmniDegradationCache,OmniTransportGuardError,assertWithinByteLimit,assertWithinDurationLimit,assertWithinTokenLimit,effectiveMaxUploadFileBytes,effectiveOmniStorageMaxTotalBytes,estimateRawResourceTokens,runFixedPolicies,runOmniGcOnce}from"./chunk-PMBI46K4.js";import{MEDIA_DETECTOR_VERSION,MediaMemoryService}from"./chunk-XFMPZINJ.js";import{runStartupRecoveryOnce}from"./chunk-HN5UYLPU.js";import{DEFAULT_UPLOAD_CACHE_TTL_HOURS,OmniUploadCache}from"./chunk-HTW7PYHK.js";import{OmniObjectStore,prepareOmniDownloadsDir}from"./chunk-YFTVFH2A.js";import{extensionForMime,hashFileSha256,recognizeMediaFile,sniffMediaType}from"./chunk-ZBHL2CXR.js";import{isFfmpegAvailable,isFfprobeAvailable}from"./chunk-NIOS3B3V.js";import{isOmniDeliveryActive}from"./chunk-OBV7RNHV.js";import{requireEffectiveOmniUploadConfig}from"./chunk-XZTE4YTN.js";import{OMNI_DISCLOSURE_TEXT_PREFIX,OMNI_OMISSION_TEXT_PREFIX,OMNI_RESOURCE_HANDLE_TEXT_PREFIX,OMNI_RESOURCE_PATH_TEXT_PREFIX,OMNI_TRANSCRIPT_TEXT_PREFIX,formatDisclosureText,formatOmissionText,formatResourceHandleText,formatTranscriptText,harnessPathAnnotationPart,isHarnessAnnotationPart,parseResourceHandleText,parseResourcePathText,splitAnnotationBody,unescapeAnnotationName}from"./chunk-SW54YEPK.js";import{isPermittedRedirect,isPrivateHost,resolveNetworkTarget}from"./chunk-5CWTKFI4.js";import{ImageViewError,boundImageBuffer,sniffBoundableImageMime}from"./chunk-Z6AR5XE5.js";import{TOOL_RESULT_MEDIA_REMEDY,clampInlineMediaPart,getMaxInlineMediaBytes}from"./chunk-Q6UAOTP3.js";import{detectRuntime,loadUndici}from"./chunk-ZZZAYAJW.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{isAbortError}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{createHash}from"node:crypto";import path4 from"node:path";import fs4 from"node:fs/promises";init_esbuild_shims();function buildSessionConditionNamespace(config,reservedOutputTokens){const session={reservedOutputTokens};const windowSize=config.getContentGeneratorConfig?.()?.contextWindowSize;const contextWindowTokens=typeof windowSize==="number"&&Number.isFinite(windowSize)&&windowSize>0?windowSize:void 0;if(contextWindowTokens!==void 0){session.contextWindowTokens=contextWindowTokens}let promptTokenCount;try{const count=config.getGeminiClient?.()?.getChat?.()?.getLastPromptTokenCount();if(typeof count==="number"&&Number.isFinite(count)&&count>=0){promptTokenCount=count}}catch{}if(promptTokenCount!==void 0){session.promptTokenCount=promptTokenCount}if(contextWindowTokens!==void 0&&promptTokenCount!==void 0){session.availableContextTokens=Math.max(0,contextWindowTokens-promptTokenCount-reservedOutputTokens)}return session}__name(buildSessionConditionNamespace,"buildSessionConditionNamespace");init_esbuild_shims();import{randomBytes}from"node:crypto";import{once}from"node:events";import{createWriteStream}from"node:fs";import fs from"node:fs/promises";import path from"node:path";import{Readable}from"node:stream";import{pipeline}from"node:stream/promises";var debugLogger=createDebugLogger("omni:download");var OmniDownloadError=class extends Error{static{__name(this,"OmniDownloadError")}constructor(message,options){super(message,options);this.name="OmniDownloadError"}};var RESOLVE_TIMEOUT_MS=3e4;var HEADER_TIMEOUT_MS=3e4;var IDLE_TIMEOUT_MS=6e4;var MAX_REDIRECTS=5;function parseHttpUrlRef(pathName){if(!/^https?:\/\//i.test(pathName))return null;try{return new URL(pathName)}catch{return null}}__name(parseHttpUrlRef,"parseHttpUrlRef");function scrubPathsFromMessage(message){return message.replace(/(?:[A-Za-z]:)?(?:[\\/][^\s'"`\\/]+){2,}[\\/]?/g,match=>path.basename(match))}__name(scrubPathsFromMessage,"scrubPathsFromMessage");function formatCauseChain(err){const parts=[];let cause=err instanceof Error?err.cause:void 0;for(let depth=0;cause!=null&&depth<4;depth++){const code=cause.code;const message=cause instanceof Error?cause.message:typeof cause==="string"?cause:void 0;if(typeof code==="string"&&message&&!message.includes(code)){parts.push(`${code}: ${message}`)}else if(message){parts.push(message)}else if(typeof code==="string"){parts.push(code)}cause=cause instanceof Error?cause.cause:void 0}return parts.length>0?scrubPathsFromMessage(parts.join("; ")):void 0}__name(formatCauseChain,"formatCauseChain");function detectConfiguredProxy(undici){for(const key of["https_proxy","HTTPS_PROXY","http_proxy","HTTP_PROXY","all_proxy","ALL_PROXY"]){if(process.env[key])return true}try{return undici.getGlobalDispatcher()instanceof undici.EnvHttpProxyAgent}catch{return false}}__name(detectConfiguredProxy,"detectConfiguredProxy");async function downloadMediaUrl(params){const{url,downloadsDir,maxBytes,signal,resolveTimeoutMs=RESOLVE_TIMEOUT_MS,headerTimeoutMs=HEADER_TIMEOUT_MS,idleTimeoutMs=IDLE_TIMEOUT_MS}=params;const resolveTarget=params.resolveTarget??(target=>resolveNetworkTarget(target,"public",signal));if(isPrivateHost(url)){throw new OmniDownloadError(`URL host is not publicly routable (refused for safety): ${new URL(url).hostname}`)}let parsed;try{parsed=new URL(url)}catch{throw new OmniDownloadError("URL media ref is not a valid URL (refused).")}if(parsed.protocol!=="https:"){throw new OmniDownloadError(`URL media must be https (refused for safety): ${parsed.protocol}//${parsed.hostname}`)}if(parsed.username||parsed.password){throw new OmniDownloadError(`URL media must not embed credentials (refused for safety): ${parsed.hostname}`)}const runtime=detectRuntime();if(runtime!=="node"){throw new OmniDownloadError(`URL media requires the Node runtime to verify the connection target (refused for safety on ${runtime}): use a local file path instead of a URL, or run under Node.`)}const undici=await loadUndici();const proxied=params.detectProxy?params.detectProxy():detectConfiguredProxy(undici);if(proxied){throw new OmniDownloadError(`URL media fetching is not supported behind a proxy yet (refused): the connection pinning that enforces SSRF protection cannot be applied through a proxy. Download the file manually and use a local path instead.`)}try{await prepareOmniDownloadsDir(downloadsDir)}catch(err){throw new OmniDownloadError(`Could not prepare the downloads directory for URL media: ${err instanceof Error?scrubPathsFromMessage(err.message):String(err)}`,{cause:err})}const partPath=path.join(downloadsDir,`${randomBytes(8).toString("hex")}.part`);let currentUrl=url;let dispatcher;try{for(let redirects=0;;redirects++){let target;const resolveAbort=new AbortController;const resolveTimer=setTimeout(()=>resolveAbort.abort(new Error("resolve timeout")),resolveTimeoutMs);try{const pending=resolveTarget(currentUrl);pending.catch(()=>{});target=await Promise.race([pending,new Promise((_,reject)=>{resolveAbort.signal.addEventListener("abort",()=>reject(resolveAbort.signal.reason),{once:true})})])}catch(err){if(signal?.aborted)throw err;if(resolveAbort.signal.aborted){throw new OmniDownloadError(`Download timed out resolving ${new URL(currentUrl).hostname} (${resolveTimeoutMs/1e3}s)`)}const text=err instanceof Error?err.message:String(err);const reason=/blocked address/i.test(text)?"resolved to a non-public address":/did not resolve/i.test(text)?"did not resolve":"could not be verified";throw new OmniDownloadError(`URL host ${reason} (refused for safety): ${new URL(currentUrl).hostname}`,{cause:err})}finally{clearTimeout(resolveTimer)}if(!target.lookup){throw new OmniDownloadError(`URL host cannot be safely bound to a verified address (refused for safety): ${new URL(currentUrl).hostname}`)}const fetchFn=params.fetchFn??undici.fetch;const previousDispatcher=dispatcher;dispatcher=new undici.Agent({connect:{lookup:target.lookup}});await previousDispatcher?.close().catch(()=>{});const headerAbort=new AbortController;const headerTimer=setTimeout(()=>headerAbort.abort(new Error("header timeout")),headerTimeoutMs);const combined=AbortSignal.any(signal?[signal,headerAbort.signal]:[headerAbort.signal]);let res;try{res=await fetchFn(currentUrl,{redirect:"manual",signal:combined,dispatcher})}catch(err){if(signal?.aborted)throw err;if(headerAbort.signal.aborted){throw new OmniDownloadError(`Download timed out waiting for response headers from ${new URL(currentUrl).hostname} (${headerTimeoutMs/1e3}s)`)}const detail=err instanceof Error?scrubPathsFromMessage(err.message):String(err);const causeDetail=formatCauseChain(err);throw new OmniDownloadError(`Download request failed for ${new URL(currentUrl).hostname}: ${detail}${causeDetail?` (${causeDetail})`:""}`,{cause:err})}finally{clearTimeout(headerTimer)}if(res.status>=300&&res.status<400){await res.body?.cancel().catch(()=>{});const location=res.headers.get("location");if(!location||redirects>=MAX_REDIRECTS){throw new OmniDownloadError(`Too many or invalid redirects downloading from ${new URL(currentUrl).hostname}`)}let redirectUrl;try{redirectUrl=new URL(location,currentUrl).toString()}catch{throw new OmniDownloadError(`Redirect with a malformed Location header from ${new URL(currentUrl).hostname}`)}if(!isPermittedRedirect(currentUrl,redirectUrl)){throw new OmniDownloadError(`Cross-origin redirect refused: ${new URL(currentUrl).hostname} \u2192 ${new URL(redirectUrl).hostname}`)}currentUrl=redirectUrl;continue}if(!res.ok){await res.body?.cancel().catch(()=>{});throw new OmniDownloadError(`Download failed: HTTP ${res.status} from ${new URL(currentUrl).hostname}`)}const contentLength=Number(res.headers.get("content-length"));if(Number.isFinite(contentLength)&&contentLength>maxBytes){await res.body?.cancel().catch(()=>{});throw new OmniDownloadError(`Download exceeds the omni media limit: Content-Length ${contentLength} > ${maxBytes} bytes.`)}if(!res.body){throw new OmniDownloadError("Download response had no body.")}let written=0;const idleAbort=new AbortController;let idleTimer=setTimeout(()=>idleAbort.abort(new Error("idle timeout")),idleTimeoutMs);const streamSignal=AbortSignal.any(signal?[signal,idleAbort.signal]:[idleAbort.signal]);try{const source=Readable.fromWeb(res.body,{signal:streamSignal});const counter=__name(async function*(src){for await(const chunk of src){clearTimeout(idleTimer);idleTimer=setTimeout(()=>idleAbort.abort(new Error("idle timeout")),idleTimeoutMs);written+=chunk.length;if(written>maxBytes){throw new OmniDownloadError(`Download exceeds the omni media limit: >${maxBytes} bytes received.`)}yield chunk}},"counter");const destination=createWriteStream(partPath,{mode:384});await once(destination,"open");await pipeline(source,counter,destination)}catch(err){if(signal?.aborted)throw err;if(err instanceof OmniDownloadError)throw err;if(idleAbort.signal.aborted){throw new OmniDownloadError(`Download stalled from ${new URL(currentUrl).hostname}: no data for ${idleTimeoutMs/1e3}s`)}throw new OmniDownloadError(`Download interrupted from ${new URL(currentUrl).hostname}: ${err instanceof Error?scrubPathsFromMessage(err.message):String(err)}`,{cause:err})}finally{clearTimeout(idleTimer)}debugLogger.debug(`downloaded ${written} bytes from ${new URL(currentUrl).hostname}`);return{partPath}}}catch(err){await fs.rm(partPath,{force:true});throw err}finally{await dispatcher?.close().catch(()=>{})}}__name(downloadMediaUrl,"downloadMediaUrl");init_esbuild_shims();import{randomBytes as randomBytes2}from"node:crypto";import fs2 from"node:fs/promises";import path2 from"node:path";var debugLogger2=createDebugLogger("omni:tool-result");var MAX_UPLOADS_PER_TOOL_RESULT=8;var MAX_UPLOAD_BYTES_PER_TOOL_RESULT=128*1024*1024;async function boundDeclinedInlinePart(part,bytes,signal){const inline=part.inlineData;if(!inline?.data)return part;const inlineByteCeiling=getMaxInlineMediaBytes();let boundedPart=part;if(sniffBoundableImageMime(bytes.subarray(0,12))){try{const view=await boundImageBuffer(bytes,`tool-result media (${inline.mimeType??"unknown"})`,signal,inlineByteCeiling);if(view){boundedPart={inlineData:{...inline,data:view.bytes.toString("base64"),mimeType:view.mimeType}}}}catch(error){if(!(error instanceof ImageViewError)){throw error}debugLogger2.debug(`tool-result media kept inline could not be bounded: ${error.message}`)}}return clampInlineMediaPart(boundedPart,inlineByteCeiling,TOOL_RESULT_MEDIA_REMEDY)}__name(boundDeclinedInlinePart,"boundDeclinedInlinePart");async function processToolResultOmniMedia(responseParts,config,signal){if(!isOmniDeliveryActive(config))return responseParts;const modalities=config.getContentGeneratorConfig?.()?.modalities??{};let changed=false;let uploadsRemaining=MAX_UPLOADS_PER_TOOL_RESULT;let uploadBytesRemaining=MAX_UPLOAD_BYTES_PER_TOOL_RESULT;const keepInline=__name(async(part,bytes)=>{const kept=await boundDeclinedInlinePart(part,bytes,signal);if(kept!==part)changed=true;return[kept]},"keepInline");const convertPart=__name(async part=>{const inline=part.inlineData;if(!inline?.data||!inline.mimeType)return[part];const top=inline.mimeType.split("/")[0];if(top!=="image"&&top!=="audio"&&top!=="video")return[part];const bytes=Buffer.from(inline.data,"base64");const sniffed=sniffMediaType(bytes.subarray(0,4096));if(!sniffed)return keepInline(part,bytes);if(!modalities[sniffed.modality]){return keepInline(part,bytes)}if(uploadsRemaining<=0||bytes.length>uploadBytesRemaining){debugLogger2.debug(`tool-result media budget exhausted; keeping part inline (${bytes.length} bytes)`);return keepInline(part,bytes)}const store=new OmniObjectStore(config.storage.getQwenDir());let tempPath;const displayName=inline.displayName??`tool-media.${top}`;try{const stagingDir=await prepareOmniDownloadsDir(path2.join(store.getOmniRootDir(),"downloads"));tempPath=path2.join(stagingDir,`${randomBytes2(8).toString("hex")}.part`);await fs2.writeFile(tempPath,bytes,{mode:384});const delivery=await processMediaForOmniDelivery(tempPath,config,{expectedModality:sniffed.modality,signal,displayName,origin:"tool"});const transcriptParts=buildTranscriptParts(displayName,delivery.transcripts);const additionalParts=buildAdditionalMediaParts(displayName,delivery.additionalMedia);uploadsRemaining-=delivery.additionalMedia?.filter(e=>!e.omission).length??0;const handleParts=delivery.resourceId?[{text:formatResourceHandleText(displayName,delivery.resourceId)}]:[];if(delivery.omission){changed=true;return[...handleParts,{text:formatOmissionText(displayName,delivery.omission.reason)},...additionalParts,...transcriptParts]}if(!delivery.fileUri&&transcriptParts.length>0){changed=true;return delivery.disclosure?[...handleParts,{text:formatDisclosureText(displayName,delivery.disclosure)},...additionalParts,...transcriptParts]:[...handleParts,...additionalParts,...transcriptParts]}changed=true;uploadsRemaining--;uploadBytesRemaining-=bytes.length;const fileDataPart={fileData:{fileUri:delivery.fileUri,mimeType:delivery.mimeType,displayName}};return delivery.disclosure?[...handleParts,{text:formatDisclosureText(displayName,delivery.disclosure)},fileDataPart,...additionalParts,...transcriptParts]:[...handleParts,fileDataPart,...additionalParts,...transcriptParts]}catch(err){if(signal.aborted)throw err;if(err instanceof OmniTransportGuardError){changed=true;return[...err.sessionResourceId?[{text:formatResourceHandleText(displayName,err.sessionResourceId)}]:[],{text:`[Tool media part withheld by the omni transport guard: ${err.message}]`}]}debugLogger2.debug(`tool-result media upload failed, keeping inline: ${err instanceof Error?err.message:String(err)}`);return keepInline(part,bytes)}finally{if(tempPath!==void 0){await fs2.rm(tempPath,{force:true}).catch(()=>{})}}},"convertPart");const result=[];for(const part of responseParts){const nested=part.functionResponse?.parts;if(Array.isArray(nested)&&nested.length>0){const convertedNested=[];let nestedChanged=false;for(const nestedPart of nested){const converted=await convertPart(nestedPart);if(converted.length!==1||converted[0]!==nestedPart){nestedChanged=true}convertedNested.push(...converted)}if(nestedChanged){result.push({...part,functionResponse:{...part.functionResponse,parts:convertedNested}});changed=true}else{result.push(part)}continue}result.push(...await convertPart(part))}return changed?result:responseParts}__name(processToolResultOmniMedia,"processToolResultOmniMedia");init_esbuild_shims();import fs3 from"node:fs/promises";import path3 from"node:path";var debugLogger3=createDebugLogger("omni:export");function textOfPart(part){if(typeof part==="string")return part;if(typeof part==="object"&&part!==null&&"text"in part){const text=part.text;return typeof text==="string"?text:void 0}return void 0}__name(textOfPart,"textOfPart");function functionResponseOfPart(part){if(typeof part!=="object"||part===null)return void 0;const response=part.functionResponse;if(typeof response!=="object"||response===null)return void 0;const{id,parts}=response;return{id,...Array.isArray(parts)?{parts}:{}}}__name(functionResponseOfPart,"functionResponseOfPart");function isThoughtPart(part){return typeof part==="object"&&part!==null&&part.thought===true}__name(isThoughtPart,"isThoughtPart");function functionCallOfPart(part){if(typeof part!=="object"||part===null)return void 0;const fc=part.functionCall;if(typeof fc!=="object"||fc===null)return void 0;const{id,name,args}=fc;if(typeof name!=="string")return void 0;const cleanArgs=typeof args==="object"&&args!==null?{...args}:void 0;return{...typeof id==="string"?{callId:id}:{},name,...cleanArgs?{args:cleanArgs}:{}}}__name(functionCallOfPart,"functionCallOfPart");function stripSystemReminders(text){return text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g,"")}__name(stripSystemReminders,"stripSystemReminders");function mediaFor(turn,name){let media=turn.media.get(name);if(!media){media={name,disclosures:[],transcripts:[]};turn.media.set(name,media)}return media}__name(mediaFor,"mediaFor");function consumeAnnotationPart(turn,text,isHarnessAnnotation){if(text.startsWith(OMNI_RESOURCE_HANDLE_TEXT_PREFIX)){const resourceId=parseResourceHandleText(text);if(resourceId){const body=text.slice(OMNI_RESOURCE_HANDLE_TEXT_PREFIX.length);const name=unescapeAnnotationName(body.slice(0,body.length-resourceId.length-1));mediaFor(turn,name).resourceId=resourceId;return true}return false}if(text.startsWith(OMNI_RESOURCE_PATH_TEXT_PREFIX)){if(!isHarnessAnnotation)return false;const filePath=parseResourcePathText(text);if(filePath){mediaFor(turn,filePath.split(/[\\/]/).pop()??filePath);return true}return false}for(const[prefix,apply]of[[OMNI_DISCLOSURE_TEXT_PREFIX,(m,payload)=>{m.disclosures.push(payload)}],[OMNI_OMISSION_TEXT_PREFIX,(m,payload)=>{m.omitted=payload}],[OMNI_TRANSCRIPT_TEXT_PREFIX,(m,payload)=>{m.transcripts.push(payload)}]]){if(!text.startsWith(prefix))continue;const split=splitAnnotationBody(text.slice(prefix.length));if(!split)return false;apply(mediaFor(turn,split.name),split.payload);return true}return false}__name(consumeAnnotationPart,"consumeAnnotationPart");function consumeRecordParts(turn,record,collectProse){const parts=(record.message?.parts??[]).flatMap(part=>[part,...functionResponseOfPart(part)?.parts??[]]);for(const part of parts){const raw=textOfPart(part);if(raw===void 0)continue;const withoutReminders=stripSystemReminders(raw);const forAnnotation=withoutReminders.replace(/^\s+/,"");if(consumeAnnotationPart(turn,forAnnotation,isHarnessAnnotationPart(part)))continue;const prose=withoutReminders.trim();if(!prose)continue;if(collectProse)turn.requestTexts.push(prose)}}__name(consumeRecordParts,"consumeRecordParts");function finishTurn(turn,sessionId){return{kind:"turn",sessionId,turnIndex:turn.turnIndex,...turn.timestamp!==void 0?{timestamp:turn.timestamp}:{},request:{text:turn.requestTexts.join("\n"),media:[...turn.media.values()],...turn.recall!==void 0?{recall:turn.recall}:{}},response:{text:turn.responseTexts.join("\n"),toolCalls:turn.toolCalls}}}__name(finishTurn,"finishTurn");function activeChainRecords(records){const byUuid=new Map;for(const record of records){if(typeof record.uuid==="string")byUuid.set(record.uuid,record)}if(byUuid.size===0)return records;let leaf;for(let i=records.length-1;i>=0;i--){if(typeof records[i].uuid==="string"){leaf=records[i];break}}if(!leaf)return records;const active=new Set;let current=leaf;while(current?.uuid&&!active.has(current.uuid)){active.add(current.uuid);current=typeof current.parentUuid==="string"?byUuid.get(current.parentUuid):void 0}return records.filter(r=>typeof r.uuid!=="string"||active.has(r.uuid))}__name(activeChainRecords,"activeChainRecords");function buildTurnRecords(transcriptLines){const turns=[];let sessionId="";let current;for(const record of activeChainRecords(transcriptLines)){if(typeof record.sessionId==="string"&&sessionId===""){sessionId=record.sessionId}if(record.type==="user"&&record.subtype===void 0){if(current)turns.push(finishTurn(current,sessionId));current={turnIndex:turns.length,...record.timestamp!==void 0?{timestamp:record.timestamp}:{},requestTexts:[],media:new Map,responseTexts:[],toolCalls:[]};consumeRecordParts(current,record,true);continue}if(!current)continue;if(record.type==="system"&&record.subtype==="omni_recall"){current.recall=record.systemPayload;continue}if(record.type==="tool_result"){consumeRecordParts(current,record,false);continue}if(record.type==="assistant"){for(const part of record.message?.parts??[]){if(isThoughtPart(part))continue;const text=textOfPart(part);if(text!==void 0&&text.trim()){current.responseTexts.push(text);continue}const call=functionCallOfPart(part);if(call)current.toolCalls.push(call)}}}if(current)turns.push(finishTurn(current,sessionId));return turns}__name(buildTurnRecords,"buildTurnRecords");async function readSnapshotRaw(omniRootDir){const filePath=path3.join(omniRootDir,"memory.json");let raw;try{raw=await fs3.readFile(filePath,"utf8")}catch{return void 0}try{const parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null||[parsed.files,parsed.versions,parsed.executions,parsed.entries].some(c=>typeof c!=="object"||c===null||Array.isArray(c))){throw new Error("unexpected snapshot shape")}return parsed}catch(err){debugLogger3.debug(`trajectory export: memory unreadable, exporting transcript only: ${err instanceof Error?err.message:err}`);return void 0}}__name(readSnapshotRaw,"readSnapshotRaw");function buildMemoryRecords(snapshot){const files=[];const executions=[];for(const version of Object.values(snapshot.versions)){try{const file=snapshot.files[version.fileId];if(!file)continue;files.push({kind:"file",fileId:version.fileId,fileVersionId:version.fileVersionId,rootFileId:file.rootFileId,sha256:version.sha256,mediaType:version.mediaType,origin:file.origin,sizeBytes:version.sizeBytes,mimeType:version.mimeType,source:version.source,...version.producedByExecutionId!==void 0?{producedByExecutionId:version.producedByExecutionId}:{},...version.parentVersionId!==void 0?{parentVersionId:version.parentVersionId}:{},createdAt:version.createdAt})}catch{}}for(const execution of Object.values(snapshot.executions)){try{const outputs=execution.outputRefs.flatMap(entryId=>{const entry=snapshot.entries[entryId];if(!entry)return[];return[{kind:entry.kind,...entry.role!==void 0?{role:entry.role}:{},...entry.artifactRef?.managedId?.startsWith("sha256/")?{sha256:entry.artifactRef.managedId.slice("sha256/".length)}:{},...entry.artifactRef?.mimeType!==void 0?{mimeType:entry.artifactRef.mimeType}:{},...entry.artifactRef?.sizeBytes!==void 0?{sizeBytes:entry.artifactRef.sizeBytes}:{},...entry.disclosure!==void 0?{disclosure:entry.disclosure}:{}}]});executions.push({kind:"execution",executionId:execution.executionId,invocationId:execution.invocationId,executionOrigin:execution.executionOrigin,toolName:execution.toolName,...execution.toolVersion!==void 0?{toolVersion:execution.toolVersion}:{},finalArguments:execution.finalArguments,omniConfigHash:execution.omniConfigHash,sourceVersionId:execution.sourceVersionId,rootFileId:execution.rootFileId,startedAt:execution.startedAt,completedAt:execution.completedAt,...execution.reusedExecutionId!==void 0?{reusedExecutionId:execution.reusedExecutionId}:{},outputs})}catch{}}return{files,executions}}__name(buildMemoryRecords,"buildMemoryRecords");function filterToSession(memory,turns,transcriptLines){const callIds=new Set;for(const record of activeChainRecords(transcriptLines)){if(record.type!=="tool_result")continue;for(const part of record.message?.parts??[]){const id=functionResponseOfPart(part)?.id;if(typeof id==="string")callIds.add(id)}}const mediaNames=new Set;for(const turn of turns){for(const call of turn.response.toolCalls){if(call.callId)callIds.add(call.callId)}for(const media of turn.request.media)mediaNames.add(media.name)}const filesByVersion=new Map(memory.files.map(f=>[f.fileVersionId,f]));const versionsByFile=new Map;for(const f of memory.files){const list=versionsByFile.get(f.fileId)??[];list.push(f);versionsByFile.set(f.fileId,list)}const includedFiles=new Set;const includedExecutions=new Set;const includeFile=__name(fileId=>{if(!fileId||includedFiles.has(fileId))return false;if(!versionsByFile.has(fileId))return false;includedFiles.add(fileId);return true},"includeFile");for(const f of memory.files){if(mediaNames.has(f.source.locator))includeFile(f.fileId)}for(const e of memory.executions){if(callIds.has(e.invocationId))includedExecutions.add(e.executionId)}let changed=true;while(changed){changed=false;for(const e of memory.executions){const sourceFile=filesByVersion.get(e.sourceVersionId)?.fileId;if(!includedExecutions.has(e.executionId)){if(sourceFile&&includedFiles.has(sourceFile)){includedExecutions.add(e.executionId);changed=true}else{continue}}if(includeFile(sourceFile))changed=true}for(const f of memory.files){if(includedFiles.has(f.fileId))continue;if(f.producedByExecutionId!==void 0&&includedExecutions.has(f.producedByExecutionId)){includeFile(f.fileId);changed=true}}}return{files:memory.files.filter(f=>includedFiles.has(f.fileId)),executions:memory.executions.filter(e=>includedExecutions.has(e.executionId))}}__name(filterToSession,"filterToSession");async function exportOmniTrajectory(options){const raw=await fs3.readFile(options.transcriptPath,"utf8");const transcriptLines=[];for(const line of raw.split("\n")){if(!line.trim())continue;try{transcriptLines.push(JSON.parse(line))}catch{}}const turns=buildTurnRecords(transcriptLines);const records=[...turns];const snapshot=await readSnapshotRaw(options.omniRootDir);const memoryRecords=snapshot?filterToSession(buildMemoryRecords(snapshot),turns,transcriptLines):{files:[],executions:[]};records.push(...memoryRecords.files.sort((a,b)=>a.fileVersionId.localeCompare(b.fileVersionId)),...memoryRecords.executions.sort((a,b)=>a.executionId.localeCompare(b.executionId)));return records}__name(exportOmniTrajectory,"exportOmniTrajectory");function serializeOmniTrajectory(records){return records.map(r=>JSON.stringify(r)).join("\n")+"\n"}__name(serializeOmniTrajectory,"serializeOmniTrajectory");async function writeOmniTrajectoryJsonl(options){const outPath=path3.resolve(options.outPath);if(outPath===path3.resolve(options.transcriptPath)){throw new Error("trajectory outPath must differ from the transcript path")}const records=await exportOmniTrajectory(options);await fs3.mkdir(path3.dirname(outPath),{recursive:true});await fs3.writeFile(outPath,serializeOmniTrajectory(records),"utf8");return{records:records.length}}__name(writeOmniTrajectoryJsonl,"writeOmniTrajectoryJsonl");var debugLogger4=createDebugLogger("omni");function sanitizeErrorMessage(err,knownPaths=[]){let msg=err instanceof Error?err.message:String(err);for(const known of knownPaths){if(!known)continue;msg=msg.split(known).join(path4.basename(known));const segments=known.split(/[\\/]+/).filter(Boolean);if(/^[A-Za-z]:$/.test(segments[0]??""))segments.shift();if(segments.length>=2){const spelled=segments.map(segment=>segment.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("[\\\\/]+");msg=msg.replace(new RegExp(`(?:[A-Za-z]:)?[\\\\/]*${spelled}`,"g"),()=>path4.basename(known))}}return msg.replace(/(?:\/[^/\s'"]+)+\/([^/\s'"]+)/g,"$1").replace(/(?:[A-Za-z]:)?(?:\\[^\\\s'"]+)+\\([^\\\s'"]+)/g,"$1")}__name(sanitizeErrorMessage,"sanitizeErrorMessage");function buildAdditionalMediaParts(displayName,additionalMedia){const parts=[];for(const extra of additionalMedia??[]){if(extra.disclosure){parts.push({text:formatDisclosureText(displayName,extra.disclosure)})}if(extra.omission){parts.push({text:formatOmissionText(displayName,extra.omission.reason)})}else{parts.push({fileData:{fileUri:extra.fileUri,mimeType:extra.mimeType,displayName}})}}return parts}__name(buildAdditionalMediaParts,"buildAdditionalMediaParts");function buildTranscriptParts(displayName,transcripts){const parts=[];for(const t of transcripts??[]){if(t.disclosure){parts.push({text:formatDisclosureText(displayName,t.disclosure)})}parts.push({text:formatTranscriptText(displayName,t.text)})}return parts}__name(buildTranscriptParts,"buildTranscriptParts");var OmniDeliveryError=class extends Error{static{__name(this,"OmniDeliveryError")}constructor(message,options){super(message,options);this.name="OmniDeliveryError"}};function evaluateTransportLimits(config,recognized,displayName){try{assertWithinByteLimit(config,recognized.sizeBytes,displayName);assertWithinDurationLimit(config,recognized,displayName);return{estimate:assertWithinTokenLimit(config,recognized,displayName)}}catch(err){if(err instanceof OmniTransportGuardError){return{estimate:estimateRawResourceTokens(recognized),violation:err.message}}throw err}}__name(evaluateTransportLimits,"evaluateTransportLimits");async function processMediaForOmniDelivery(filePath,config,options){const{expectedModality,signal}=options??{};const displayName=options?.displayName??path4.basename(filePath);const[ffmpeg,ffprobe]=await Promise.all([isFfmpegAvailable(),isFfprobeAvailable()]);if(!ffmpeg||!ffprobe){throw new OmniDeliveryError("ffmpeg/ffprobe not available; omni media delivery requires both on PATH.")}await fs4.stat(filePath).catch(err=>{throw new OmniDeliveryError(`Cannot stat media file ${displayName}: ${sanitizeErrorMessage(err,[filePath])}`,{cause:err})});let recognized;try{recognized=await recognizeMediaFile(filePath,{expectedModality,signal})}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(`Media recognition failed for ${displayName}: ${sanitizeErrorMessage(err,[filePath])}`,{cause:err})}const store=new OmniObjectStore(config.storage.getQwenDir());const uploadConfig=requireEffectiveOmniUploadConfig(config);const cacheScope=createHash("sha256").update(`${uploadConfig.baseUrl}|${uploadConfig.apiKey}`).digest("hex").slice(0,16);const configuredTtl=config.getOmniUploadUrlTtlHours?.();const uploadCache=new OmniUploadCache(store.getOmniRootDir(),configuredTtl===void 0?DEFAULT_UPLOAD_CACHE_TTL_HOURS:configuredTtl,cacheScope);await runStartupRecoveryOnce(store,uploadCache,{quarantineRetentionDays:config.getOmniQuarantineRetentionDays?.(),quarantineMaxBytes:config.getOmniQuarantineMaxBytes?.(),degradationCache:new OmniDegradationCache(store.getOmniRootDir())});const processingConfig=config.getOmniProcessingConfig?.();const conditionContext=processingConfig?{session:buildSessionConditionNamespace(config,processingConfig.limits.reservedOutputTokens)}:void 0;const memoryConfig=config.getOmniMemoryConfig?.();const memoryService=memoryConfig?new MediaMemoryService(store.getOmniRootDir(),{maxInlineTextBytes:memoryConfig.collection.maxInlineTextBytes}):void 0;if(memoryService){void runOmniGcOnce({store,memoryService,registry:config.getOmniMediaResourceRegistry?.(),uploadCache,degradationCache:new OmniDegradationCache(store.getOmniRootDir()),retentionDays:config.getOmniStorageRetentionDays?.()??14,maxTotalBytes:typeof config.getOmniStorageMaxTotalBytes==="function"?effectiveOmniStorageMaxTotalBytes(config):20*1024*1024*1024})}const registry=memoryService?config.getOmniMediaResourceRegistry?.():void 0;const bindSessionResource=__name((item,fileRefOverride)=>registry&&item.memoryBinding?registry.bind({...item.memoryBinding,fileRef:fileRefOverride??item.filePath,mediaType:item.recognized.modality}):void 0,"bindSessionResource");let sourceSha256;let sourceBinding;let sourceFileRef=filePath;if(memoryService){try{sourceSha256=await hashFileSha256(filePath,signal)}catch(err){if(signal?.aborted)throw err;debugLogger4.debug(`omni memory: hashing ${displayName} failed, skipping collection: ${sanitizeErrorMessage(err,[filePath])}`)}if(sourceSha256){const origin=options?.origin??"user";const ephemeralSource=origin==="tool"||options?.sourceUrl!==void 0;sourceFileRef=ephemeralSource?store.objectPathFor(sourceSha256,extensionForMime(recognized.detectedMimeType)):filePath;sourceBinding=await memoryService.recordFileRecognized({fileRef:sourceFileRef,sha256:sourceSha256,mediaType:recognized.modality,metadata:recognized.metadata,sizeBytes:recognized.sizeBytes,mimeType:recognized.detectedMimeType,origin,source:options?.sourceUrl!==void 0?{protocol:"url",locator:options.sourceUrl}:origin==="tool"?{protocol:"managed",locator:`sha256/${sourceSha256}`}:{protocol:"local",locator:displayName},recognition:{ingestionConfigHash:"",detectorVersion:MEDIA_DETECTOR_VERSION,probeStatus:"complete"}})}}let final={filePath,recognized,sha256:sourceSha256,memoryBinding:sourceBinding};const sessionResourceId=bindSessionResource(final,sourceFileRef)?.resourceId;const guardRejection=__name((message,options2)=>{const err=new OmniTransportGuardError(message,options2);if(sessionResourceId!==void 0){err.sessionResourceId=sessionResourceId}return err},"guardRejection");let extraDeliveries=[];const transcripts=[];const collectTranscripts=__name(files=>{for(const file of files){transcripts.push({text:file.text,disclosure:file.disclosure})}},"collectTranscripts");const textOnlyDelivery=__name((recognizedFinal,tokenEstimate2,extras)=>({fileUri:"",mimeType:recognizedFinal.detectedMimeType,sha256:"",recognized:recognizedFinal,tokenEstimate:tokenEstimate2,deduped:false,uploadCacheHit:false,degraded:true,transcripts,resourceId:sessionResourceId,...extras}),"textOnlyDelivery");const policies=processingConfig?.fixedPolicies??[];if(policies.length>0){let deliveries;let fileDeliveries;try{({deliveries,fileDeliveries}=await runFixedPolicies(config,{filePath,recognized,displayName,origin:options?.origin??"user",sha256:sourceSha256},{store,policies,signal,limits:processingConfig?.limits,conditionContext,memory:memoryService?{service:memoryService,sourceBinding}:void 0}))}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(`Fixed-policy processing failed for ${displayName}: ${sanitizeErrorMessage(err,[filePath,store.getOmniRootDir()])}`,{cause:err})}collectTranscripts(fileDeliveries);if(deliveries.length===0&&transcripts.length>0){return textOnlyDelivery(recognized,evaluateTransportLimits(config,recognized,displayName).estimate)}if(deliveries.length===0){throw new OmniDeliveryError(`Fixed policies produced 0 media deliverables for ${displayName}; exactly one is supported.`)}final=deliveries[0];extraDeliveries=deliveries.slice(1);for(const delivery of deliveries)bindSessionResource(delivery)}const uploadModel=uploadConfig.model;const uploadResource=__name(async(item,estimate)=>{let sha256;try{sha256=item.sha256??await hashFileSha256(item.filePath,signal)}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(`Failed to hash media file ${displayName}: ${sanitizeErrorMessage(err,[item.filePath])}`,{cause:err})}const cachedUrl=await uploadCache.get(sha256,uploadModel);if(cachedUrl){debugLogger4.debug(`omni upload cache hit: sha256=${sha256.slice(0,12)}\u2026 model=${uploadModel}`);return{fileUri:cachedUrl,sha256,deduped:true,uploadCacheHit:true}}const extension=extensionForMime(item.recognized.detectedMimeType);let objectPath;let deduped;try{const put=await store.putFile(item.filePath,sha256,extension,signal);objectPath=put.objectPath;deduped=put.deduped}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(`Failed to store media in the omni object store: ${sanitizeErrorMessage(err,[item.filePath,store.getOmniRootDir()])}`,{cause:err})}const uploader=new DashScopeUploader({apiKey:uploadConfig.apiKey,baseUrl:uploadConfig.baseUrl});let fileUri;try{fileUri=await uploader.uploadFile({filePath:objectPath,model:uploadModel,mimeType:item.recognized.detectedMimeType,signal})}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(sanitizeErrorMessage(err,[objectPath,store.getOmniRootDir()]),{cause:err})}debugLogger4.debug(`omni ${item.recognized.modality} delivered: sha256=${sha256.slice(0,12)}\u2026 size=${item.recognized.sizeBytes} est=${estimate.estimatedTokenCount}(${estimate.status}) deduped=${deduped} degraded=${item.degraded===true} uri=${fileUri}`);await uploadCache.put(sha256,uploadModel,fileUri);return{fileUri,sha256,deduped,uploadCacheHit:false}},"uploadResource");const processAdditionalMedia=__name(async()=>{if(extraDeliveries.length===0)return void 0;return Promise.all(extraDeliveries.map(async extra=>{const extraGuard=evaluateTransportLimits(config,extra.recognized,displayName);if(extraGuard.violation){debugLogger4.debug(`omni additional ${extra.recognized.modality} explicitly omitted (transport guard): ${extraGuard.violation}`);return{fileUri:"",mimeType:extra.recognized.detectedMimeType,sha256:extra.sha256??"",disclosure:extra.disclosure,omission:{reason:extraGuard.violation}}}const uploaded2=await uploadResource(extra,extraGuard.estimate);return{fileUri:uploaded2.fileUri,mimeType:extra.recognized.detectedMimeType,sha256:uploaded2.sha256,disclosure:extra.disclosure}}))},"processAdditionalMedia");let guard=evaluateTransportLimits(config,final.recognized,displayName);if(guard.violation&&processingConfig){const maxPasses=processingConfig.limits.maxTransportPasses;for(let pass=0;guard.violation&&pass<maxPasses;pass++){const guardPolicies=processingConfig.transportGuardPolicies.filter(p=>p.mediaTypes.includes(final.recognized.modality));if(guardPolicies.length===0)break;let deliveries;let fileDeliveries;try{({deliveries,fileDeliveries}=await runFixedPolicies(config,{filePath:final.filePath,recognized:final.recognized,displayName,origin:options?.origin??"user",sha256:final.sha256},{store,policies:guardPolicies,signal,limits:processingConfig.limits,conditionContext,memory:memoryService?{service:memoryService,sourceBinding:final.memoryBinding}:void 0}))}catch(err){if(signal?.aborted)throw err;throw guardRejection(`Transport-guard processing failed for ${displayName}: ${sanitizeErrorMessage(err,[final.filePath,store.getOmniRootDir()])}`,{cause:err})}collectTranscripts(fileDeliveries);if(deliveries.length===0&&fileDeliveries.length>0){return textOnlyDelivery(final.recognized,guard.estimate,{disclosure:final.disclosure,additionalMedia:await processAdditionalMedia()})}if(deliveries.length!==1){throw guardRejection(`Transport-guard policies produced ${deliveries.length} media deliverables for ${displayName}; exactly one is supported.`)}if(deliveries[0].filePath===final.filePath){break}const priorDisclosure=final.disclosure;final=deliveries[0];if(priorDisclosure&&final.disclosure){final={...final,disclosure:`${priorDisclosure}\uFF1B${final.disclosure}`}}else if(priorDisclosure){final={...final,disclosure:priorDisclosure}}bindSessionResource(final);guard=evaluateTransportLimits(config,final.recognized,displayName)}}if(guard.violation){if(!processingConfig){throw guardRejection(guard.violation)}debugLogger4.debug(`omni ${final.recognized.modality} explicitly omitted (transport guard): ${guard.violation}`);return{fileUri:"",mimeType:final.recognized.detectedMimeType,sha256:final.sha256??"",recognized:final.recognized,tokenEstimate:guard.estimate,deduped:false,uploadCacheHit:false,disclosure:final.disclosure,degraded:final.degraded,omission:{reason:guard.violation},transcripts:transcripts.length>0?transcripts:void 0,additionalMedia:await processAdditionalMedia(),resourceId:sessionResourceId}}const tokenEstimate=guard.estimate;const uploaded=await uploadResource(final,tokenEstimate);return{fileUri:uploaded.fileUri,mimeType:final.recognized.detectedMimeType,sha256:uploaded.sha256,recognized:final.recognized,tokenEstimate,deduped:uploaded.deduped,uploadCacheHit:uploaded.uploadCacheHit,disclosure:final.disclosure,degraded:final.degraded,transcripts:transcripts.length>0?transcripts:void 0,additionalMedia:await processAdditionalMedia(),resourceId:sessionResourceId}}__name(processMediaForOmniDelivery,"processMediaForOmniDelivery");async function readMediaViaOmniDelivery(params){const{filePath,config,displayName,relativePathForDisplay,expectedModality,signal}=params;try{const delivery=await processMediaForOmniDelivery(filePath,config,{expectedModality,signal});const transcriptParts=buildTranscriptParts(displayName,delivery.transcripts);const additionalParts=buildAdditionalMediaParts(displayName,delivery.additionalMedia);const handleParts=(()=>{if(!delivery.resourceId)return[];const binding=config.getOmniMediaResourceRegistry?.()?.resolve(delivery.resourceId);if(binding&&binding.fileRef===filePath&&!/[\r\n]/.test(filePath)){return[harnessPathAnnotationPart(filePath)]}return[{text:formatResourceHandleText(displayName,delivery.resourceId)}]})();if(delivery.omission){const omissionPart={text:formatOmissionText(displayName,delivery.omission.reason)};return{llmContent:transcriptParts.length>0||additionalParts.length>0||handleParts.length>0?[...handleParts,omissionPart,...additionalParts,...transcriptParts]:omissionPart.text,returnDisplay:`Media omitted by the omni transport guard: ${relativePathForDisplay}`,tokenEstimate:delivery.tokenEstimate}}if(!delivery.fileUri&&transcriptParts.length>0){const disclosureParts=delivery.disclosure?[{text:formatDisclosureText(displayName,delivery.disclosure)}]:[];return{llmContent:[...handleParts,...disclosureParts,...additionalParts,...transcriptParts],returnDisplay:`Read ${delivery.recognized.modality} as transcript (omni policy): ${relativePathForDisplay}`,tokenEstimate:delivery.tokenEstimate}}const fileDataPart={fileData:{fileUri:delivery.fileUri,mimeType:delivery.mimeType,displayName}};const parts=[...handleParts];const{width,height}=delivery.recognized.metadata;if(delivery.recognized.modality==="image"&&width!==void 0&&height!==void 0){parts.push({text:delivery.disclosure?`Image ${displayName}: delivered at ${width}x${height} px after degradation. Use zoom_image to inspect details \u2014 it reads the original file.`:`Image ${displayName}: full resolution ${width}x${height} px. Use zoom_image for a closer look at details.`})}if(delivery.disclosure){parts.push({text:formatDisclosureText(displayName,delivery.disclosure)})}parts.push(fileDataPart);parts.push(...additionalParts);parts.push(...transcriptParts);const llmContent=parts.length===1?fileDataPart:parts;return{llmContent,returnDisplay:`Read ${delivery.recognized.modality} file (omni upload): ${relativePathForDisplay}`,tokenEstimate:delivery.tokenEstimate}}catch(err){if(isAbortError(err)||signal?.aborted)throw err;const message=sanitizeErrorMessage(err,[filePath]);return{llmContent:`[Omni media delivery failed for ${displayName}: ${message}]`,returnDisplay:`Failed to deliver media via omni upload: ${relativePathForDisplay}`,error:`Omni media delivery failed: ${displayName}: ${message}`,errorType:"read_content_failure"}}}__name(readMediaViaOmniDelivery,"readMediaViaOmniDelivery");function effectiveMaxDownloadFileBytes(config){const uploadCap=effectiveMaxUploadFileBytes(config);const configured=config.getOmniUrlDownloadMaxFileBytes?.();if(configured!==void 0&&configured>0){return Math.min(configured,uploadCap)}return uploadCap}__name(effectiveMaxDownloadFileBytes,"effectiveMaxDownloadFileBytes");export{OmniDownloadError,parseHttpUrlRef,downloadMediaUrl,exportOmniTrajectory,serializeOmniTrajectory,writeOmniTrajectoryJsonl,sanitizeErrorMessage,buildAdditionalMediaParts,buildTranscriptParts,OmniDeliveryError,processMediaForOmniDelivery,readMediaViaOmniDelivery,effectiveMaxDownloadFileBytes,processToolResultOmniMedia};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2025 Google LLC
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{MOD_MAX_BYTES,MOD_MAX_DEPTH,MOD_TOOL_RESERVED,jsonDepth,record,validateInput}from"./chunk-ZZJXFLVM.js";import{CoreToolScheduler}from"./chunk-
|
|
3
|
+
import{MOD_MAX_BYTES,MOD_MAX_DEPTH,MOD_TOOL_RESERVED,jsonDepth,record,validateInput}from"./chunk-ZZJXFLVM.js";import{CoreToolScheduler}from"./chunk-T3CQ72HC.js";import{ToolNames,canonicalToolName,resolveRegisteredToolName}from"./chunk-SBZFGYYS.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();import{isDeepStrictEqual}from"node:util";async function modToolRequest(config,request){const name=canonicalToolName(request.name);if(request.goalContext||name===ToolNames.STRUCTURED_OUTPUT||name===ToolNames.TOOL_SEARCH||name===ToolNames.SEARCH_MEMORY||request.executionOrigin?.kind==="fixed_policy")return void 0;if(name!==ToolNames.TOOL_CALL)return config.getToolRegistry().getTool(name)||config.getToolRegistry().getAllToolNames().includes(name)?{...request,name}:void 0;const targetName=request.args["name"];let args=request.args["arguments"];if(typeof args==="string"){try{args=JSON.parse(args)}catch{return void 0}}if(typeof targetName!=="string"||!record(args))return void 0;const registry=config.getToolRegistry();const resolved=resolveRegisteredToolName(canonicalToolName(targetName),registry.getAllToolNames());if(typeof resolved!=="string"||resolved===ToolNames.TOOL_CALL||resolved===ToolNames.TOOL_SEARCH||resolved===ToolNames.SEARCH_MEMORY)return void 0;let target;try{target=await registry.ensureTool(resolved)}catch{return void 0}if(!target||!registry.isDeferredAndHidden(target.name)||target.name===ToolNames.STRUCTURED_OUTPUT)return void 0;return{...request,name:target.name,args}}__name(modToolRequest,"modToolRequest");async function executeModTool(request,execution,middleware,execute,signal){const shadowed=Object.fromEntries(MOD_TOOL_RESERVED.filter(key=>Object.hasOwn(execution.args,key)).map(key=>[key,execution.args[key]]));const input={...execution.args,tool:execution.name,tool_use_id:request.callId};for(const key of MOD_TOOL_RESERVED)delete input[key];input.tool=execution.name;input.tool_use_id=request.callId;if(Object.keys(shadowed).length)input["$shadowed"]=shadowed;const refs=new Map;let latest;let executed;let attempts=0;let answer;try{answer=await middleware(input,async(changed,active,check)=>{active.throwIfAborted();validateInput("tool.call",changed,input);if(++attempts>64)throw new Error("Mod tool execution limit exceeded.");const args={...changed};for(const key of MOD_TOOL_RESERVED)delete args[key];Object.assign(args,shadowed);const nativeRequest=canonicalToolName(request.name)===ToolNames.TOOL_CALL?{...request,args:{...request.args,arguments:structuredClone(args)}}:{...request,args:structuredClone(args)};const completed=await execute(nativeRequest,active,check);latest=completed;if(completed.response.executionStatus==="success"||completed.response.executionStatus==="error"&&executed?.response.executionStatus!=="success")executed=completed;const response2=completed.response;let result2=response2.responseParts.find(part=>part.functionResponse)?.functionResponse?.response??{};let json=JSON.stringify(result2);if(Buffer.byteLength(json)>MOD_MAX_BYTES/2||jsonDepth(json)>MOD_MAX_DEPTH/2){result2={output:"[Native tool result exceeds the Mod payload limit; return this reference unchanged to retain it.]"};json=JSON.stringify(result2)}const value={ref:attempts,result:JSON.parse(json),text:(record(result2)&&typeof result2["output"]==="string"?result2["output"]:json).slice(0,16e3),...response2.error?{isError:true}:{}};refs.set(attempts,{completed,value});return value},signal)}catch(error2){answer={deny:`Mod tool dispatch failed: ${String(error2)}`}}const referenced=!("deny"in answer)&&answer.ref!==void 0?refs.get(answer.ref):void 0;const selected=referenced?.completed??latest;const native=selected?.response;if(latest?.response.error&&(latest.response.executionStatus==="not_started"||latest.response.executionStatus==="cancelled")){if(!executed)return{response:latest.response,completed:latest};const message2=`An earlier Mod tool attempt ran. A later attempt failed: ${latest.response.error.message}`;return{completed:executed,response:{...latest.response,executionStatus:executed.response.executionStatus,error:new Error(message2),resultDisplay:message2,contentLength:message2.length,responseParts:[{functionResponse:{id:request.callId,name:request.name,response:{error:message2}}}]}}}if(referenced&&!("deny"in answer)&&isDeepStrictEqual(answer.result,referenced.value.result)){return{response:{...referenced.completed.response,executionStatus:executed?.response.executionStatus??referenced.completed.response.executionStatus},completed:executed??referenced.completed}}const message="deny"in answer?`${executed?"The tool ran; a Mod withheld its result. ":"Tool denied by Mod. "}${answer.deny}`:void 0;const result="deny"in answer?{error:message}:record(answer.result)&&Object.entries(answer.result).every(([key,value])=>(key==="output"||key==="error")&&typeof value==="string")?answer.result:{output:typeof answer.result==="string"?answer.result:JSON.stringify(answer.result)};const text=JSON.stringify(result);const error=message?new Error(message):native?.error??(!("deny"in answer)&&answer.isError?new Error("Mod returned an error result."):void 0);const response={...native,callId:request.callId,responseParts:[{functionResponse:{id:request.callId,name:request.name,response:result}}],resultDisplay:text,contentLength:text.length,executionStatus:executed?.response.executionStatus??native?.executionStatus??"not_started",error,errorType:native?.errorType??(error?"execution_denied":void 0)};return{response,completed:executed??selected}}__name(executeModTool,"executeModTool");async function executeToolCall(config,toolCallRequest,abortSignal,options={}){const execution=options.modToolCall&&await modToolRequest(config,toolCallRequest);if(execution&&options.modToolCall){const{response,completed}=await executeModTool(toolCallRequest,execution,options.modToolCall,async(request,signal,check)=>{let completed2;await executeToolCall(config,request,signal,{...options,modToolCall:void 0,modToolCheck:check,recordToolResult:false,onAllToolCallsComplete:__name(async calls=>{completed2=calls[0]},"onAllToolCallsComplete")});if(!completed2)throw new Error("Mod native tool did not complete.");return completed2},abortSignal);if(completed)await options.onAllToolCallsComplete?.([{...completed,response}]);if(options.recordToolResult!==false)config.getChatRecordingService()?.recordToolResult(response.responseParts,{...response,status:completed?.status??(response.error?"error":"success")});return response}return new Promise((resolve,reject)=>{new CoreToolScheduler({config,modToolCheck:options.modToolCheck,chatRecordingService:options.recordToolResult===false?void 0:config.getChatRecordingService(),outputUpdateHandler:options.outputUpdateHandler,onAllToolCallsComplete:__name(async completedToolCalls=>{if(options.onAllToolCallsComplete){await options.onAllToolCallsComplete(completedToolCalls)}resolve(completedToolCalls[0].response)},"onAllToolCallsComplete"),onToolCallsUpdate:options.onToolCallsUpdate,onToolResultFullTurnModel:options.onToolResultFullTurnModel,getPreferredEditor:__name(()=>void 0,"getPreferredEditor"),onEditorClose:__name(()=>{},"onEditorClose")}).schedule(toolCallRequest,abortSignal,options.runtimeView).catch(reject)})}__name(executeToolCall,"executeToolCall");export{modToolRequest,executeModTool,executeToolCall};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2026 Qwen Team
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{require_source}from"./chunk-D2NY7HVY.js";import{loadSettings}from"./chunk-
|
|
3
|
+
import{require_source}from"./chunk-D2NY7HVY.js";import{loadSettings}from"./chunk-Q5RRVBTY.js";import{getCurrentLanguage,t}from"./chunk-NO7VTKRL.js";import{isWorkspaceTrusted}from"./chunk-YWK3E4WJ.js";import{ExtensionManager,getExtensionDescription,getExtensionDisplayName,require_prompts}from"./chunk-T3CQ72HC.js";import{resolveExtensionTelemetryProxy,resolveUsageStatisticsEnabled}from"./chunk-HW6AWS7W.js";import{stripAnsi}from"./chunk-YGLM5XPP.js";import{redactUrlCredentials}from"./chunk-3XVPZY7X.js";import{writeStdoutLine}from"./chunk-M4ECEHLX.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();var import_chalk=__toESM(require_source(),1);var import_prompts=__toESM(require_prompts(),1);async function requestConsentNonInteractive(consentDescription){writeStdoutLine(consentDescription);const result=await promptForConsentNonInteractive(t("Do you want to continue? [Y/n]: "));return result}__name(requestConsentNonInteractive,"requestConsentNonInteractive");async function requestChoicePluginNonInteractive(marketplace){const plugins=marketplace.plugins;if(plugins.length===0){throw new Error(t("No plugins available in this marketplace."))}const choices=plugins.map(plugin=>({title:import_chalk.default.green(import_chalk.default.bold(`[${plugin.name}]`)),value:plugin.name}));const response=await(0,import_prompts.default)({type:"select",name:"plugin",message:t('Select a plugin to install from marketplace "{{name}}":',{name:marketplace.name}),choices,initial:0});if(response.plugin===void 0){throw new Error(t("Plugin selection cancelled."))}return response.plugin}__name(requestChoicePluginNonInteractive,"requestChoicePluginNonInteractive");async function requestConsentInteractive(consentDescription,addExtensionUpdateConfirmationRequest){return promptForConsentInteractive(consentDescription+"\n\n"+t("Do you want to continue?"),addExtensionUpdateConfirmationRequest)}__name(requestConsentInteractive,"requestConsentInteractive");async function promptForConsentNonInteractive(prompt){const readline=await import("node:readline");const rl=readline.createInterface({input:process.stdin,output:process.stdout});return new Promise(resolve=>{rl.question(prompt,answer=>{rl.close();resolve(["y",""].includes(answer.trim().toLowerCase()))})})}__name(promptForConsentNonInteractive,"promptForConsentNonInteractive");async function promptForConsentInteractive(prompt,addExtensionUpdateConfirmationRequest){return new Promise(resolve=>{addExtensionUpdateConfirmationRequest({prompt,onConfirm:__name(resolvedConfirmed=>{resolve(resolvedConfirmed)},"onConfirm")})})}__name(promptForConsentInteractive,"promptForConsentInteractive");function extensionConsentString(extensionConfig,commands=[],skills=[],subagents=[],originSource="QwenCode",workflows=[]){const output=[];if(originSource!=="QwenCode"&&originSource!=="AgentPlugins"){output.push(t("You are installing an extension from {{originSource}}. Some features may not work perfectly with Qwen Code.",{originSource}))}const mcpServerEntries=Object.entries(extensionConfig.mcpServers||{});const displayLabel=extensionConfig.displayName??extensionConfig.name;output.push(t('Installing extension "{{name}}".',{name:displayLabel}));if(typeof extensionConfig.description==="string"&&extensionConfig.description){output.push(stripAnsi(extensionConfig.description))}output.push(t("**Extensions may introduce unexpected behavior. Ensure you have investigated the extension source and trust the author.**"));if(mcpServerEntries.length){output.push(t("This extension will run the following MCP servers:"));for(const[key,mcpServer]of mcpServerEntries){const isLocal=!!mcpServer.command;const source=mcpServer.httpUrl??`${mcpServer.command||""}${mcpServer.args?" "+mcpServer.args.join(" "):""}`;output.push(` * ${key} (${isLocal?t("local"):t("remote")}): ${source}`)}}if(commands&&commands.length>0){output.push(t("This extension will add the following commands: {{commands}}.",{commands:commands.join(", ")}))}if(extensionConfig.contextFileName){const fileName=Array.isArray(extensionConfig.contextFileName)?extensionConfig.contextFileName.join(", "):extensionConfig.contextFileName;output.push(t("This extension will append info to your QWEN.md context using {{fileName}}",{fileName}))}if(skills.length>0){output.push(t("This extension will install the following skills:"));for(const skill of skills){output.push(` * ${import_chalk.default.bold(skill.name)}: ${skill.description}`)}}if(subagents.length>0){output.push(t("This extension will install the following subagents:"));for(const subagent of subagents){output.push(` * ${import_chalk.default.bold(subagent.name)}: ${subagent.description}`)}}if(workflows.length>0){output.push(t("This extension will install the following workflows (JavaScript scripts that can start subagents):"));for(const workflow of workflows){const description=stripAnsi(workflow.description).replace(/\s+/g," ");output.push(` * ${import_chalk.default.bold(workflow.name)}: ${description}`)}}return output.join("\n")}__name(extensionConsentString,"extensionConsentString");function changedWorkflowScripts(workflows,previousWorkflows){const previousDigests=new Map(previousWorkflows.map(workflow=>[workflow.name,workflow.contentDigest]));return workflows.filter(workflow=>{const previous=previousDigests.get(workflow.name);return previous!==void 0&&previous!==workflow.contentDigest}).map(workflow=>workflow.name)}__name(changedWorkflowScripts,"changedWorkflowScripts");var requestConsentOrFail=__name(async(requestConsent,options)=>{if(!options)return;const{extensionConfig,originSource="QwenCode",commands=[],skills=[],subagents=[],workflows=[],previousExtensionConfig,previousCommands=[],previousSkills=[],previousSubagents=[],previousWorkflows=[]}=options;const extensionConsent=extensionConsentString(extensionConfig,commands,skills,subagents,originSource,workflows);const changedScripts=previousExtensionConfig?changedWorkflowScripts(workflows,previousWorkflows):[];if(previousExtensionConfig){const previousExtensionConsent=extensionConsentString(previousExtensionConfig,previousCommands,previousSkills,previousSubagents,originSource,previousWorkflows);if(previousExtensionConsent===extensionConsent&&changedScripts.length===0){return}}const consent=changedScripts.length>0?`${extensionConsent}
|
|
4
4
|
${t("These workflow scripts changed since the installed version: {{names}}.",{names:changedScripts.join(", ")})}`:extensionConsent;if(!await requestConsent(consent)){throw new Error(t('Installation cancelled for "{{name}}".',{name:extensionConfig.name}))}},"requestConsentOrFail");var import_chalk2=__toESM(require_source(),1);import*as os from"node:os";async function getExtensionManager(){const workspaceDir=process.cwd();const settings=loadSettings(workspaceDir).merged;const extensionManager=new ExtensionManager({workspaceDir,locale:getCurrentLanguage(),requestConsent:requestConsentOrFail.bind(null,requestConsentNonInteractive),requestChoicePlugin:requestChoicePluginNonInteractive,isWorkspaceTrusted:isWorkspaceTrusted(settings).isTrusted??true,usageStatisticsEnabled:resolveUsageStatisticsEnabled(settings.privacy?.usageStatisticsEnabled),proxy:resolveExtensionTelemetryProxy(settings.proxy)});await extensionManager.refreshCache();return extensionManager}__name(getExtensionManager,"getExtensionManager");var EXTENSION_COMMAND_SCOPES=["User","Workspace"];function extensionCommandScopesList(){return EXTENSION_COMMAND_SCOPES.map(s=>s.toLowerCase()).join(", ")}__name(extensionCommandScopesList,"extensionCommandScopesList");function resolveExtensionCommandScope(scope){if(!scope){return"User"}const normalized=scope.toLowerCase();const matched=EXTENSION_COMMAND_SCOPES.find(candidate=>candidate.toLowerCase()===normalized);if(matched){return matched}throw new Error(t("Invalid scope: {{scope}}. Please use one of {{scopes}}.",{scope,scopes:extensionCommandScopesList()}))}__name(resolveExtensionCommandScope,"resolveExtensionCommandScope");function extensionToOutputString(extension,extensionManager,workspaceDir,inline=false){const cwd=workspaceDir;const userEnabled=extensionManager.isEnabled(extension.config.name,os.homedir());const workspaceEnabled=extensionManager.isEnabled(extension.config.name,cwd);const status=workspaceEnabled?import_chalk2.default.green("\u2713"):import_chalk2.default.red("\u2717");const locale=getCurrentLanguage();const displayLabel=getExtensionDisplayName(extension,locale);let output=`${inline?"":status} ${displayLabel} (${extension.config.version})`;const desc=getExtensionDescription(extension,locale);if(desc){output+=`
|
|
5
5
|
${t("Description:")} ${stripAnsi(desc)}`}output+=`
|
|
6
6
|
${t("Path:")} ${extension.path}`;if(extension.installMetadata){output+=`
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{MAX_DROPPED_MSG_IDS,MAX_FRAME_BYTES,MAX_RETAINED_REPLY_TOKEN_CHARS,MAX_SENDER_KEY_CHARS,MAX_SOCKET_PATH_BYTES,SOCKET_DIR_NAME,isLocalIpcPath,parsePeerAuthLine,parsePeerFrame,peerSenderKey,probePeerSocketVerdict,resolvePeerSocketCandidates}from"./chunk-MKH3EH7O.js";import{scanForSecrets}from"./chunk-AKWYMQKU.js";import{collectPtyProcessTree}from"./chunk-PGRN3GZY.js";import{BudgetExhaustedError,IDE_DEFINITIONS,MCP_BUDGET_REARM_FRACTION,MCP_BUDGET_WARN_FRACTION,McpClient,ORPHAN_TOOL_USE_REPAIR_REASON,POOLED_TRANSPORTS_DEFAULT,QWEN_CODE_COMPANION_EXTENSION_NAME,SessionService,StandardFileSystemService,aggregateUsage,buildSessionHistoryFromConversation,buildSyntheticToolResponseParts,classifyShellCommandSafety,classifyShellCommandSafetyInDirectory,coerceMcpFilterEntries,connectionIdOf,convertToFunctionErrorResponse,convertToFunctionResponse,createForkedChat,detectTurnInterruption,discoveryTimeoutFor,estimateContentTokens,evaluateToolInvocationGuard,finalizeToolResponses,getCacheSafeParams,getCacheSafeParamsSessionId,getTimeRangeBounds,isPoolable,listDescendantPids,listExistingSkillDirNames,loadUsageHistoryWithLive,mcpSessionMetadataKey,mcpTransportOf,normalizeMcpIncludeEntry,observeToolResultBoundary,parseConnectionId,recursivelyHydrateStrings,repairOrphanedToolUseTurns,runForkedAgent,runWithForkedChatModel,runWithTimeout,sigtermPids,stripToolResultImages,toolResultBoundaryArtifact,toolResultPartDiagnosticValues,withoutAutoMemorySnapshots}from"./chunk-Z5XENA4A.js";import{shellResultText}from"./chunk-T7CHK6C2.js";import{runGit,runGitCapture,streamGitRecords}from"./chunk-ILECDNJX.js";import{hasVerifiableInode,openNoFollow,openSyncNoFollow}from"./chunk-QXQGUM3Y.js";import{projectUserTranscriptForDisplay}from"./chunk-SZCBUCNH.js";import{toolSearchBridgeSentence}from"./chunk-5SUFJTQQ.js";import{flattenPeerLabel}from"./chunk-BYU42MLK.js";import{isPidAlive}from"./chunk-5LZ2DPLH.js";import{getProjectSkillsRoot}from"./chunk-XQJOZDV7.js";import{parse}from"./chunk-KLC3OD2M.js";import{glob,globSync}from"./chunk-OBOU4ZZM.js";import{isDeferredToolBridgeAvailable}from"./chunk-7CQMWEMY.js";import{require_picomatch}from"./chunk-OUC3WICA.js";import{BUILT_IN_OUTPUT_STYLES,getBuiltInOutputStyle}from"./chunk-OV3EBH6J.js";import{NO_EXEC_CONFIG}from"./chunk-EBMCWXGZ.js";import{require_proper_lockfile}from"./chunk-YIW3H46P.js";import{disposeConoutWorker,loadPty,loadXtermHeadless,noteConPtyHostReleased,releaseConPtyHost}from"./chunk-NMY3PYNO.js";import{stripAnsi}from"./chunk-YGLM5XPP.js";import{resolveBundleDir}from"./chunk-4NPYOXJO.js";import{escapeJsonTagCharacters}from"./chunk-NTRFETZB.js";import{getModelsForProviderProtocol,tryResolveModelProtocol}from"./chunk-ET2Z7ZGF.js";import{fetchWithPolicy}from"./chunk-5CWTKFI4.js";import{COMBINED_PASS_TOLERANCE_FACTOR,TOOL_OUTPUT_TRUNCATED_PREFIX,TRUNCATION_FALLBACK_ENVELOPE_SLACK,addMCPStatusChangeListener,removeMCPStatusChangeListener,updateMCPServerStatus}from"./chunk-ZWPSBU7K.js";import{E_TIMEOUT,Mutex,withTimeout}from"./chunk-HDGTWJ24.js";import{runSideQuery}from"./chunk-K7JCVESI.js";import{MEMORY_SECTION_HEADER,VISION_BRIDGE_MAX_IMAGES,VISION_BRIDGE_MAX_IMAGE_BASE64_BYTES,detectFileType,getCurrentMemoryFilename,isCacheableReadResult,isWithinRoot,processSingleFileContent}from"./chunk-Y6HHV4LC.js";import{getInvocationContext}from"./chunk-EFTJIDS3.js";import{DEFAULT_IMAGE_TOKEN_ESTIMATE,estimatePartChars}from"./chunk-Q6UAOTP3.js";import{atomicWriteFile,atomicWriteJSON}from"./chunk-BMHYEQTI.js";import{isBinary,normalizeContent,stripAnsiAndControl,stripHtmlComments}from"./chunk-DBRQGEEI.js";import{cloneApiHistory,getFolderStructure,getStartupContextLength,stripSystemReminderBlocks}from"./chunk-B3ZFUGTC.js";import{getQwenIgnoreFileNames,require_ignore}from"./chunk-5DTFN37U.js";import{ToolNames,canonicalToolName}from"./chunk-SBZFGYYS.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{Storage}from"./chunk-EPODBRBP.js";import{PATH_ARG_KEYS,QWEN_DIR,tildeifyPath,unescapePath}from"./chunk-OKN3Z5C5.js";import{getErrorMessage,isAbortError,isNodeError}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__require,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var JsonFormatter=class{static{__name(this,"JsonFormatter")}format(response,stats,error){const output={};if(response!==void 0){output.response=stripAnsi(response)}if(stats){output.stats=stats}if(error){output.error=error}return JSON.stringify(output,null,2)}formatError(error,code){const jsonError={type:error.constructor.name,message:stripAnsi(error.message),...code&&{code}};return this.format(void 0,void 0,jsonError)}};init_esbuild_shims();function createPlanId(sessionId,historyLength){return`${sessionId}:${historyLength}`}__name(createPlanId,"createPlanId");function buildVisibleNotice(kind,repairs,historyGaps){if(kind==="clean"){return void 0}if(kind==="degraded_history"){return`Resumed session history is incomplete: detected ${historyGaps.length} missing parent link(s). Automatic continuation is disabled for this recovery.`}if(kind==="interrupted_prompt"){return"Previous session appears to have stopped after user input before the model completed a response."}const synthesized=repairs.filter(repair=>repair.type==="synthesized_tool_result").length;if(synthesized>0){return`Previous session appears to have stopped during tool execution. Synthesized ${synthesized} failed tool result(s) so the history can continue safely.`}return"Previous session appears to have stopped during tool execution."}__name(buildVisibleNotice,"buildVisibleNotice");function buildSessionRecoveryPlan({sessionId,conversation,historyGaps,options}){return buildSessionRecoveryPlanFromApiHistory({sessionId,...buildSessionHistoryFromConversation(conversation),historyGaps,options})}__name(buildSessionRecoveryPlan,"buildSessionRecoveryPlan");function buildSessionRecoveryPlanFromApiHistory({sessionId,apiHistory:inputApiHistory,completedToolCallIds,trailingSystemNotifications,historyGaps,options}){const originalApiHistory=inputApiHistory;const gaps=historyGaps??[];const planId=createPlanId(sessionId,originalApiHistory.length);const apiHistory=cloneApiHistory(originalApiHistory);const repairResult=repairOrphanedToolUseTurns(apiHistory);const repairs=[...repairResult.injected.map(repair=>({type:"synthesized_tool_result",callId:repair.callId,name:repair.name})),...repairResult.droppedDuplicates.map(repair=>({type:"dropped_duplicate_tool_result",callId:repair.callId,name:repair.name})),...gaps.map(gap=>({type:"history_gap",childUuid:gap.childUuid,missingParentUuid:gap.missingParentUuid}))];if(gaps.length>0){return{planId,sessionId,kind:"degraded_history",originalApiHistory,apiHistory,repairs,canContinue:false,canAutoContinue:false,requiresUserConfirmation:true,visibleNotice:buildVisibleNotice("degraded_history",repairs,gaps)}}const interruption=detectTurnInterruption(originalApiHistory,completedToolCallIds,trailingSystemNotifications);if(interruption.kind==="none"){return{planId,sessionId,kind:"clean",originalApiHistory,apiHistory,repairs,canContinue:false,canAutoContinue:false,requiresUserConfirmation:false}}if(interruption.kind==="interrupted_prompt"){const continuation2={mode:"retry_user_parts",parts:interruption.parts,displayText:"Continue interrupted user prompt"};return{planId,sessionId,kind:"interrupted_prompt",originalApiHistory,apiHistory,repairs,canContinue:true,canAutoContinue:options?.allowAutoContinue===true,requiresUserConfirmation:options?.allowAutoContinue!==true,visibleNotice:buildVisibleNotice("interrupted_prompt",repairs,gaps),continuation:continuation2}}const continuation={mode:"tool_result_parts",parts:buildSyntheticToolResponseParts(interruption.danglingCalls,ORPHAN_TOOL_USE_REPAIR_REASON),displayText:"Continue interrupted tool turn"};return{planId,sessionId,kind:"interrupted_turn",originalApiHistory,apiHistory,repairs,canContinue:true,canAutoContinue:false,requiresUserConfirmation:true,visibleNotice:buildVisibleNotice("interrupted_turn",repairs,gaps),continuation}}__name(buildSessionRecoveryPlanFromApiHistory,"buildSessionRecoveryPlanFromApiHistory");init_esbuild_shims();init_esbuild_shims();import{EventEmitter}from"node:events";init_esbuild_shims();var debugLogger=createDebugLogger("McpPool:Entry");function defaultPoolEntryOptions(transport){const isRemote=transport==="http"||transport==="sse"||transport==="websocket";return{drainDelayMs:3e4,maxIdleMs:5*6e4,maxReconnectAttempts:isRemote?5:3,reconnectStrategy:isRemote?{kind:"exponential",baseMs:1e3,capMs:16e3}:{kind:"fixed",delayMs:5e3}}}__name(defaultPoolEntryOptions,"defaultPoolEntryOptions");var PoolEntry=class{constructor(id,serverName,entryIndex,cfg,client,cliConfig,opts,onClosed,aggregateStatusByName){this.id=id;this.serverName=serverName;this.entryIndex=entryIndex;this.cfg=cfg;this.client=client;this.cliConfig=cliConfig;this.opts=opts;this.onClosed=onClosed;this.aggregateStatusByName=aggregateStatusByName;this.transportId=connectionIdOf(serverName,cfg);this.emitter.setMaxListeners(0);this.statusChangeListener=(name,status)=>{if(name!==this.serverName)return;if(status===void 0)return;if(this.suppressNextStatusEcho){this.suppressNextStatusEcho=false;return}if(this.client.getStatus()!==status)return;if(status===this.localStatus)return;this.localStatus=status;if(status==="disconnected"&&(this.state==="active"||this.state==="draining")&&!this.restartInProgress){const wasDraining=this.state==="draining";this.state="failed";if(wasDraining){this.cancelDrainTimer()}if(this.maxIdleTimer){clearTimeout(this.maxIdleTimer);this.maxIdleTimer=void 0}if(this.statusChangeListener){removeMCPStatusChangeListener(this.statusChangeListener);this.statusChangeListener=void 0}debugLogger.error(`PoolEntry ${this.id} silent transport drop (prev state='${wasDraining?"draining":"active"}', localStatus\u2192DISCONNECTED). Transitioning to 'failed'; evicting from pool.entries + pooledConnections (W122 R20).`);const upstreamError=this.client.getLastTransportError();this.emit({kind:"failed",serverName:this.serverName,generation:this._generation,lastError:upstreamError?`transport disconnected (silent transport drop): ${upstreamError.message}`:"transport disconnected (silent transport drop)"});for(const[sid]of[...this.subscribers]){this.detach(sid)}void this.sweepAndDisconnect("silent_drop").then(result=>{const partialSignal=result.descendantsFound!==void 0&&result.descendantsSignaled!==void 0&&result.descendantsSignaled<result.descendantsFound;if(result.pidSweepError!==void 0||partialSignal){debugLogger.warn(`PoolEntry ${this.id} silent-drop sweep observability: descendantsFound=${result.descendantsFound??"unknown"}, descendantsSignaled=${result.descendantsSignaled??"unknown"}, pidSweepError=${result.pidSweepError?.message??"none"}. Possible orphan-process pressure \u2014 operator should check for lingering subprocess descendants of the dead transport.`)}this.updateGlobalStatus()},()=>{this.updateGlobalStatus()});this.updateGlobalStatus();this.onClosed(this.id)}};addMCPStatusChangeListener(this.statusChangeListener)}static{__name(this,"PoolEntry")}localStatus="connecting";state="spawning";_generation=0;refs=new Set;subscribers=new Map;subscriberHandles=new Map;toolsSnapshot=[];promptsSnapshot=[];resourcesSnapshot=[];drainTimer;maxIdleTimer;firstIdleAt;restartInFlight;restartInProgress=false;emitter=new EventEmitter;statusChangeListener;suppressNextStatusEcho=false;transportId;get generation(){return this._generation}get currentState(){return this.state}get transportKind(){return mcpTransportOf(this.cfg)}isTerminated(){return this.state==="closed"||this.state==="failed"}markActive(initialTools,initialPrompts,initialResources){if(this.state==="closed"||this.state==="failed")return;this.toolsSnapshot=initialTools;this.promptsSnapshot=initialPrompts;this.resourcesSnapshot=initialResources;this.state="active";this.localStatus="connected";this.updateGlobalStatus()}attach(sessionId,view,opts){if(this.state==="closed"||this.state==="failed"){throw new Error(`Cannot attach to PoolEntry ${this.id} in state ${this.state}`)}const previousState=this.state;const hadRef=this.refs.has(sessionId);const previousView=this.subscribers.get(sessionId);const previousHandle=this.subscriberHandles.get(sessionId);this.refs.add(sessionId);this.subscribers.set(sessionId,view);this.cancelDrainTimer();if(this.state==="draining")this.state="active";if(this.state==="active"&&opts?.skipReplay!==true){try{view.applyTools(this.toolsSnapshot);view.applyPrompts(this.promptsSnapshot);view.applyResources(this.resourcesSnapshot)}catch(err){if(!hadRef){this.refs.delete(sessionId);this.subscribers.delete(sessionId);this.subscriberHandles.delete(sessionId);try{view.teardown()}catch{}}else if(previousView){this.subscribers.set(sessionId,previousView);if(previousHandle){this.subscriberHandles.set(sessionId,previousHandle)}}if(previousState==="draining"&&this.refs.size===0){this.startDrainTimer(this.opts.drainDelayMs)}else{this.state=previousState}debugLogger.error(`Snapshot replay failed for ${sessionId}/${this.serverName}: ${String(err)}`);throw err}}const handle=new PooledConnectionImpl(this,sessionId,opts?.release);this.subscriberHandles.set(sessionId,handle);return handle}updateSessionConfig(sessionId,cfg){if(this.isTerminated()){throw new Error(`Cannot update config on PoolEntry ${this.id} in state ${this.state}`)}const view=this.subscribers.get(sessionId);if(!view){throw new Error(`Cannot update config for detached session ${sessionId} on PoolEntry ${this.id}`)}if(!view.updateConfig(cfg))return;if(this.state==="active"){view.applyTools(this.toolsSnapshot);view.applyPrompts(this.promptsSnapshot);view.applyResources(this.resourcesSnapshot)}}detach(sessionId){const view=this.subscribers.get(sessionId);if(view){try{view.teardown()}catch(err){debugLogger.error(`View teardown failed for ${sessionId}/${this.serverName}: ${String(err)}`)}}this.subscribers.delete(sessionId);this.subscriberHandles.delete(sessionId);this.refs.delete(sessionId)}startDrainTimer(delayMs){this.cancelDrainTimer();this.state="draining";if(this.firstIdleAt===void 0){this.firstIdleAt=Date.now();this.maxIdleTimer=setTimeout(()=>{if(this.refs.size>0){debugLogger.debug(`PoolEntry ${this.id} max-idle reached but ${this.refs.size} sessions active; deferring close, resetting first-idle window`);this.maxIdleTimer=void 0;this.firstIdleAt=void 0;return}debugLogger.warn(`PoolEntry ${this.id} hit MAX_IDLE_MS (${this.opts.maxIdleMs}ms); force-closing`);void this.forceShutdown("max_idle")},this.opts.maxIdleMs);this.maxIdleTimer.unref?.()}this.drainTimer=setTimeout(()=>{void this.forceShutdown("drain_timer")},delayMs);this.drainTimer.unref?.()}cancelDrainTimer(){if(this.drainTimer){clearTimeout(this.drainTimer);this.drainTimer=void 0}}async forceShutdown(reason){if(this.state==="closed"||this.state==="failed")return;this.state="closed";this.localStatus="disconnected";this.suppressNextStatusEcho=true;this.cancelDrainTimer();if(this.maxIdleTimer){clearTimeout(this.maxIdleTimer);this.maxIdleTimer=void 0}if(this.statusChangeListener){removeMCPStatusChangeListener(this.statusChangeListener);this.statusChangeListener=void 0}this.emit({kind:"disconnected",serverName:this.serverName,generation:this._generation,reason:"transport_closed"});for(const[sid]of this.subscribers){this.detach(sid)}await this.sweepAndDisconnect(reason);this.updateGlobalStatus();this.onClosed(this.id)}async sweepAndDisconnect(reason){const result={};try{const rootPid=this.client.getTransportPid?.();if(rootPid!==void 0){const descendants=await listDescendantPids(rootPid);if(descendants.length>0){result.descendantsFound=descendants.length;result.descendantsSignaled=sigtermPids(descendants);debugLogger.debug(`Sent SIGTERM to ${result.descendantsSignaled}/${descendants.length} descendants of pid ${rootPid} for ${this.id} (${reason})`)}}}catch(err){result.pidSweepError=err instanceof Error?err:new Error(String(err));debugLogger.warn(`Descendant pid sweep failed for ${this.id} (${reason}): ${String(err)}. Proceeding with disconnect.`)}try{await this.client.disconnect()}catch(err){debugLogger.error(`client.disconnect failed for ${this.id} (${reason}): ${String(err)}`)}return result}async restart(){if(this.restartInFlight)return this.restartInFlight;this.restartInFlight=this.doRestart().finally(()=>{this.restartInFlight=void 0});return this.restartInFlight}async doRestart(){if(this.state==="closed"||this.state==="failed"){throw new Error(`Cannot restart PoolEntry ${this.id} in state ${this.state}`)}this.restartInProgress=true;try{return await this.doRestartInner()}finally{this.restartInProgress=false}}async doRestartInner(){this.cancelDrainTimer();if(this.maxIdleTimer){clearTimeout(this.maxIdleTimer);this.maxIdleTimer=void 0}this.firstIdleAt=void 0;if(this.state==="draining"){this.state="active"}const oldGen=this._generation;this._generation+=1;this.emit({kind:"disconnected",serverName:this.serverName,generation:oldGen,reason:"restart"});await this.sweepAndDisconnect("restart");let snap;try{const timeoutMs=discoveryTimeoutFor(this.cfg);snap=await runWithTimeout((async()=>{await this.client.connect();return this.client.discoverAndReturn(this.cliConfig,{applyConfigFilters:false})})(),timeoutMs,`pool restart for ${this.id} (pool will roll back the restart and free its budget slot)`)}catch(err){debugLogger.error(`Restart of ${this.id} failed at connect/discover: ${String(err)}. Transitioning to 'failed'.`);await this.sweepAndDisconnect("restart_failed");this.state="failed";this.localStatus="disconnected";this.suppressNextStatusEcho=true;this.updateGlobalStatus();if(this.statusChangeListener){removeMCPStatusChangeListener(this.statusChangeListener);this.statusChangeListener=void 0}this.emit({kind:"failed",serverName:this.serverName,generation:this._generation,lastError:err instanceof Error?err.message:String(err)});for(const[sid]of this.subscribers){this.detach(sid)}this.onClosed(this.id);throw err}if(oldGen+1!==this._generation){await this.sweepAndDisconnect("restart_superseded");throw new Error(`Restart of ${this.id} superseded by newer generation; discarded stale snapshot + swept new transport.`)}const currentState=this.state;if(currentState==="closed"||currentState==="failed"){await this.sweepAndDisconnect("restart_superseded");throw new Error(`Restart of ${this.id} aborted: entry state is ${currentState} (forceShutdown ran concurrently mid-restart). Snapshot discarded; new transport swept.`)}this.toolsSnapshot=snap.tools;this.promptsSnapshot=snap.prompts;if(snap.resources.length>0){this.resourcesSnapshot=snap.resources}for(const[sid,view]of this.subscribers){try{view.applyTools(this.toolsSnapshot);view.applyPrompts(this.promptsSnapshot);view.applyResources(this.resourcesSnapshot)}catch(err){debugLogger.error(`Restart fan-out to view ${sid}/${this.serverName} failed: ${String(err)}`)}}this.localStatus="connected";this.suppressNextStatusEcho=true;this.updateGlobalStatus();this.emit({kind:"reconnected",serverName:this.serverName,generation:this._generation});this.emit({kind:"toolsChanged",serverName:this.serverName,snapshot:this.toolsSnapshot,generation:this._generation});this.emit({kind:"promptsChanged",serverName:this.serverName,snapshot:this.promptsSnapshot,generation:this._generation});this.emit({kind:"resourcesChanged",serverName:this.serverName,snapshot:this.resourcesSnapshot,generation:this._generation})}emit(event){const listeners=this.emitter.listeners("event");for(const listener of listeners){try{listener(event)}catch(err){debugLogger.error(`PoolEntry listener error for ${this.id} (event.kind=${event.kind}): ${err instanceof Error?err.message:String(err)}`)}}}internalOn(listener){this.emitter.on("event",listener)}internalOff(listener){this.emitter.off("event",listener)}updateGlobalStatus(){const aggregated=this.aggregateStatusByName(this.serverName);updateMCPServerStatus(this.serverName,aggregated)}getLocalStatus(){return this.localStatus}};var PooledConnectionImpl=class{constructor(entry,sessionId,releaseCallback){this.entry=entry;this.sessionId=sessionId;this.releaseCallback=releaseCallback}static{__name(this,"PooledConnectionImpl")}listeners=new Set;released=false;get id(){return this.entry.id}get transportId(){return this.entry.transportId}get serverName(){return this.entry.serverName}get entryIndex(){return this.entry.entryIndex}get client(){return this.entry.client}get toolsSnapshot(){return this.entry.toolsSnapshot}get promptsSnapshot(){return this.entry.promptsSnapshot}get resourcesSnapshot(){return this.entry.resourcesSnapshot}updateConfig(cfg){if(this.released){throw new Error(`Cannot update config on released MCP connection ${this.id}`)}this.entry.updateSessionConfig(this.sessionId,cfg)}on(event,listener){if(event!=="event")return this;if(this.listeners.has(listener))return this;this.listeners.add(listener);this.entry.internalOn(listener);return this}off(event,listener){if(event!=="event")return this;this.listeners.delete(listener);this.entry.internalOff(listener);return this}release(){if(this.released)return;this.released=true;for(const l of this.listeners){this.entry.internalOff(l)}this.listeners.clear();this.releaseCallback?.()}};init_esbuild_shims();var debugLogger2=createDebugLogger("McpPool:View");function compileNameFilter(includeTools,excludeTools){return{excludeSet:excludeTools?new Set(coerceMcpFilterEntries(excludeTools)):void 0,includeSet:includeTools!=null?new Set(coerceMcpFilterEntries(includeTools).map(normalizeMcpIncludeEntry)):void 0}}__name(compileNameFilter,"compileNameFilter");function compiledFilterAccepts(filter2,name){if(filter2.excludeSet?.has(name))return false;if(!filter2.includeSet)return true;return filter2.includeSet.has(name)}__name(compiledFilterAccepts,"compiledFilterAccepts");var SessionMcpView=class{constructor(sessionToolRegistry,sessionPromptRegistry,sessionResourceRegistry,sessionId,serverName,cfg){this.sessionToolRegistry=sessionToolRegistry;this.sessionPromptRegistry=sessionPromptRegistry;this.sessionResourceRegistry=sessionResourceRegistry;this.sessionId=sessionId;this.serverName=serverName;this.cfg=cfg;this.metadataKey=mcpSessionMetadataKey(cfg)}static{__name(this,"SessionMcpView")}metadataKey;applyTools(snapshot){this.sessionToolRegistry.removeMcpToolsByServer(this.serverName);const filter2=compileNameFilter(this.cfg.includeTools,this.cfg.excludeTools);let registered=0;for(const tool of snapshot){if(!compiledFilterAccepts(filter2,tool.serverToolName)){continue}const sessionTool=tool.withSessionConfig(this.cfg.trust,this.cfg.alwaysLoadTools===true);try{this.sessionToolRegistry.registerTool(sessionTool);registered+=1}catch(err){debugLogger2.error(`SessionMcpView[${this.sessionId}/${this.serverName}] failed to register tool ${tool.serverToolName}: ${String(err instanceof Error?err.message:err)}`)}}debugLogger2.debug(`SessionMcpView[${this.sessionId}/${this.serverName}] applied ${snapshot.length} tools (filtered to ${registered} registered)`)}applyPrompts(snapshot){this.sessionPromptRegistry.removePromptsByServer(this.serverName);const filter2=compileNameFilter(this.cfg.includeTools,this.cfg.excludeTools);let registered=0;for(const prompt of snapshot){if(!compiledFilterAccepts(filter2,prompt.name)){continue}try{this.sessionPromptRegistry.registerPrompt(prompt);registered+=1}catch(err){debugLogger2.error(`SessionMcpView[${this.sessionId}/${this.serverName}] failed to register prompt ${prompt.name}: ${String(err instanceof Error?err.message:err)}`)}}debugLogger2.debug(`SessionMcpView[${this.sessionId}/${this.serverName}] applied ${snapshot.length} prompts (filtered to ${registered} registered)`)}applyResources(snapshot){if(snapshot.length===0){return}this.sessionResourceRegistry.removeResourcesByServer(this.serverName);for(const resource of snapshot){try{this.sessionResourceRegistry.registerResource(resource)}catch(err){debugLogger2.error(`SessionMcpView[${this.sessionId}/${this.serverName}] failed to register resource ${resource.uri}: ${String(err instanceof Error?err.message:err)}`)}}debugLogger2.debug(`SessionMcpView[${this.sessionId}/${this.serverName}] applied ${snapshot.length} resources`)}updateConfig(cfg){const nextKey=mcpSessionMetadataKey(cfg);const changed=this.metadataKey!==nextKey;this.cfg=cfg;this.metadataKey=nextKey;return changed}teardown(){this.sessionToolRegistry.removeMcpToolsByServer(this.serverName);this.sessionPromptRegistry.removePromptsByServer(this.serverName);this.sessionResourceRegistry.removeResourcesByServer(this.serverName);debugLogger2.debug(`SessionMcpView[${this.sessionId}/${this.serverName}] torn down`)}};var debugLogger3=createDebugLogger("McpPool");var McpTransportPool=class{constructor(cliConfig,options){this.cliConfig=cliConfig;this.opts={workspaceContext:options.workspaceContext,debugMode:options.debugMode,sendSdkMcpMessage:options.sendSdkMcpMessage,pooledTransports:options.pooledTransports??POOLED_TRANSPORTS_DEFAULT,drainDelayMs:options.drainDelayMs??3e4,entryOptions:options.entryOptions??defaultPoolEntryOptions,budget:options.budget}}static{__name(this,"McpTransportPool")}entries=new Map;unpooledIds=new Set;spawnInFlight=new Map;sessionToEntries=new Map;draining=false;nextIndexByName=new Map;opts;getBudget(){return this.opts.budget}hasNameSibling(serverName){for(const e of this.entries.values()){if(e.serverName===serverName)return true}for(const id of this.spawnInFlight.keys()){try{if(parseConnectionId(id).serverName===serverName)return true}catch{}}return false}async acquire(serverName,cfg,sessionId,sessionToolRegistry,sessionPromptRegistry,sessionResourceRegistry){if(this.draining){throw new Error(`McpTransportPool is draining; refusing acquire for ${serverName} (session ${sessionId})`)}const poolable=isPoolable(cfg,this.opts.pooledTransports);const id=poolable?connectionIdOf(serverName,cfg):void 0;if(id!==void 0){const existing=this.entries.get(id);if(existing&&!existing.isTerminated()){try{const conn=this.attachPooledSession(existing,id,serverName,cfg,sessionId,sessionToolRegistry,sessionPromptRegistry,sessionResourceRegistry);this.indexAttach(sessionId,id);return conn}catch(err){if(existing.isTerminated()){this.evictEntry(id,existing);debugLogger3.warn(`pool self-heal: evicted terminal entry ${id} (state='${existing.currentState}', serverName='${serverName}') mid-attach race; falling through to spawn fresh entry`)}else{throw err}}}else if(existing&&existing.isTerminated()){this.evictEntry(id,existing);debugLogger3.warn(`pool self-heal: evicted stale terminal entry ${id} (state='${existing.currentState}', serverName='${serverName}') before fast-path attach; falling through to spawn fresh entry`)}}let reservationResult;if(this.opts.budget!==void 0){const reservation=this.opts.budget.tryReserve(serverName);if(reservation==="refused"){const transport=mcpTransportOf(cfg);this.opts.budget.recordRefusal(serverName,transport);throw new BudgetExhaustedError(serverName,this.opts.budget.getBudget()??0,this.opts.budget.getReservedCount())}reservationResult=reservation}if(!poolable){try{return await this.createUnpooledConnection(serverName,cfg,sessionId,sessionToolRegistry,sessionPromptRegistry,sessionResourceRegistry)}catch(err){this.rollbackReservationOnSpawnFailure(reservationResult,serverName);throw err}}if(id===void 0){throw new Error("unreachable: poolable && id === undefined")}let inFlight=this.spawnInFlight.get(id);if(!inFlight){const spawnPromise=this.spawnEntry(serverName,cfg,id);inFlight=spawnPromise.finally(()=>{this.spawnInFlight.delete(id)}).catch(err=>{this.rollbackReservationOnSpawnFailure(reservationResult,serverName);throw err});this.spawnInFlight.set(id,inFlight)}this.indexAttach(sessionId,id);let entry;try{entry=await inFlight}catch(err){this.indexDetach(sessionId,id);throw err}if(!this.entries.has(id)||entry.isTerminated()){this.indexDetach(sessionId,id);throw new Error(`PoolEntry ${id} torn down before attach (concurrent release)`)}try{const conn=this.attachPooledSession(entry,id,serverName,cfg,sessionId,sessionToolRegistry,sessionPromptRegistry,sessionResourceRegistry);this.indexAttach(sessionId,id);return conn}catch(err){this.indexDetach(sessionId,id);throw err}}release(id,sessionId){const entry=this.entries.get(id);if(!entry)return;entry.detach(sessionId);this.indexDetach(sessionId,id);if(entry.refs.size===0){if(this.unpooledIds.has(id)){void entry.forceShutdown("manual");return}entry.startDrainTimer(this.opts.drainDelayMs)}}releaseSession(sessionId){const ids=this.sessionToEntries.get(sessionId);if(!ids)return;const idList=[...ids];for(const id of idList){const entry=this.entries.get(id);if(!entry)continue;entry.detach(sessionId);if(entry.refs.size===0){if(this.unpooledIds.has(id)){void entry.forceShutdown("manual");continue}entry.startDrainTimer(this.opts.drainDelayMs)}}this.sessionToEntries.delete(sessionId)}async restartByName(serverName,opts){if(this.draining)return[];const matching=[...this.entries.values()].filter(e=>e.serverName===serverName&&(opts?.entryIndex===void 0||e.entryIndex===opts.entryIndex));if(matching.length===0)return[];return Promise.all(matching.map(async entry=>{const started=Date.now();try{await entry.restart();if(entry.refs.size===0&&!this.unpooledIds.has(entry.id)){entry.startDrainTimer(this.opts.drainDelayMs)}return{entryIndex:entry.entryIndex,restarted:true,durationMs:Date.now()-started}}catch(err){return{entryIndex:entry.entryIndex,restarted:false,reason:String(err instanceof Error?err.message:err)}}}))}getSnapshot(){const byName=new Map;let total=0;let subprocessCount=0;for(const entry of this.entries.values()){const status=entry.getLocalStatus();if(status==="connected"){total+=1;if(entry.transportKind==="stdio"){subprocessCount+=1}}const row=byName.get(entry.serverName)??{entryCount:0,entrySummary:[]};row.entryCount+=1;row.entrySummary.push({entryIndex:entry.entryIndex,refs:entry.refs.size,status});byName.set(entry.serverName,row)}return{total,subprocessCount,byName:Object.fromEntries(byName.entries())}}aggregateStatusByName(serverName){let sawConnecting=false;for(const entry of this.entries.values()){if(entry.serverName!==serverName)continue;const s=entry.getLocalStatus();if(s==="connected")return"connected";if(s==="connecting")sawConnecting=true}return sawConnecting?"connecting":"disconnected"}async drainAll(opts){const timeoutMs=opts?.timeoutMs??1e4;const force=opts?.force??false;this.draining=true;const deadline=Date.now()+timeoutMs;if(this.spawnInFlight.size>0){const spawnWait=Promise.allSettled([...this.spawnInFlight.values()]);let inflightTimer;await Promise.race([spawnWait.then(()=>{if(inflightTimer)clearTimeout(inflightTimer)}),new Promise(resolve9=>{inflightTimer=setTimeout(()=>{const stuckIds=[...this.spawnInFlight.keys()];debugLogger3.warn(`drainAll: spawnInFlight wait timed out after ${timeoutMs}ms; ${stuckIds.length} spawn(s) still in-flight: ${stuckIds.join(", ")}. Proceeding with drain.`);resolve9()},Math.max(0,deadline-Date.now()));inflightTimer.unref?.()})])}const entries=[...this.entries.values()];const drained=[];const errors=[];const shutdownPromises=entries.map(entry=>entry.forceShutdown(force?"manual":"drain_timer").then(()=>drained.push(entry.entryIndex)).catch(err=>{errors.push({entryIndex:entry.entryIndex,serverName:entry.serverName,error:String(err instanceof Error?err.message:err)})}));let drainTimer;const remaining=Math.max(0,deadline-Date.now());await Promise.race([Promise.all(shutdownPromises).then(()=>{if(drainTimer)clearTimeout(drainTimer)}),new Promise(resolve9=>{drainTimer=setTimeout(()=>resolve9(),remaining);drainTimer.unref?.()})]);const drainedCount=drained.length;const errorsCount=errors.length;const forced=Math.max(0,entries.length-drainedCount-errorsCount);const errorsCopy=[...errors];this.entries.clear();this.unpooledIds.clear();this.sessionToEntries.clear();this.spawnInFlight.clear();return{drained:drainedCount,forced,errors:errorsCopy}}attachPooledSession(entry,id,serverName,cfg,sessionId,sessionToolRegistry,sessionPromptRegistry,sessionResourceRegistry){const view=new SessionMcpView(sessionToolRegistry,sessionPromptRegistry,sessionResourceRegistry,sessionId,serverName,cfg);return entry.attach(sessionId,view,{release:__name(()=>this.release(id,sessionId),"release")})}rollbackReservationOnSpawnFailure(reservationResult,serverName){if(this.opts.budget!==void 0&&reservationResult==="reserved"&&!this.hasNameSibling(serverName)){this.opts.budget.release(serverName)}}evictEntry(id,entry){if(entry===void 0)return;const current=this.entries.get(id);if(current!==entry)return;this.entries.delete(id);if(this.opts.budget!==void 0){if(!this.hasNameSibling(entry.serverName)){this.opts.budget.release(entry.serverName)}}}async spawnEntry(serverName,cfg,id){const entryIndex=this.allocateEntryIndex(serverName);const transport=mcpTransportOf(cfg);const entryOpts=this.opts.entryOptions(transport);const client=new McpClient(serverName,cfg,poisonedToolRegistry(serverName),poisonedPromptRegistry(serverName),this.opts.workspaceContext,this.opts.debugMode,this.opts.sendSdkMcpMessage);const entryRef={current:void 0};const onClosedForThisEntry=__name(closedId=>{this.evictEntry(closedId,entryRef.current)},"onClosedForThisEntry");const entry=new PoolEntry(id,serverName,entryIndex,cfg,client,this.cliConfig,entryOpts,onClosedForThisEntry,name=>this.aggregateStatusByName(name));entryRef.current=entry;try{const timeoutMs=discoveryTimeoutFor(cfg);const snap=await runWithTimeout((async()=>{await client.connect();return client.discoverAndReturn(this.cliConfig,{applyConfigFilters:false})})(),timeoutMs,`pool spawn for ${id} (pool will roll back the spawn and free its budget slot)`);if(this.draining){debugLogger3.warn(`Spawn for ${id} completed while pool is draining; discarding entry`);try{await entry.forceShutdown("manual")}catch{}throw new Error(`McpTransportPool is draining; discarded spawn ${id}`)}this.entries.set(id,entry);entry.markActive(snap.tools,snap.prompts,snap.resources);debugLogger3.info(`Spawned pool entry ${id} (entryIndex=${entryIndex}, transport=${transport})`);return entry}catch(err){debugLogger3.error(`Failed to spawn pool entry for '${serverName}' (id=${id}, transport=${transport}): ${String(err)}`);try{await entry.forceShutdown("manual")}catch{}this.entries.delete(id);try{await client.disconnect()}catch{}throw err}}allocateEntryIndex(serverName){const next=this.nextIndexByName.get(serverName)??0;this.nextIndexByName.set(serverName,next+1);return next}indexAttach(sessionId,id){let ids=this.sessionToEntries.get(sessionId);if(!ids){ids=new Set;this.sessionToEntries.set(sessionId,ids)}ids.add(id)}indexDetach(sessionId,id){const ids=this.sessionToEntries.get(sessionId);if(!ids)return;ids.delete(id);if(ids.size===0)this.sessionToEntries.delete(sessionId)}async createUnpooledConnection(serverName,cfg,sessionId,sessionToolRegistry,sessionPromptRegistry,sessionResourceRegistry){const entryIndex=this.allocateEntryIndex(serverName);const id=`${serverName}::unpooled-${entryIndex}`;const transport=mcpTransportOf(cfg);const entryOpts=this.opts.entryOptions(transport);const client=new McpClient(serverName,cfg,sessionToolRegistry,sessionPromptRegistry,this.opts.workspaceContext,this.opts.debugMode,this.opts.sendSdkMcpMessage);const view=new SessionMcpView(sessionToolRegistry,sessionPromptRegistry,sessionResourceRegistry,sessionId,serverName,cfg);const entry=new PoolEntry(id,serverName,entryIndex,cfg,client,this.cliConfig,entryOpts,closedId=>{this.entries.delete(closedId);this.unpooledIds.delete(closedId);if(this.opts.budget!==void 0){if(!this.hasNameSibling(serverName)){this.opts.budget.release(serverName)}}},()=>client.getStatus());try{this.entries.set(id,entry);this.unpooledIds.add(id);this.indexAttach(sessionId,id);const timeoutMs=discoveryTimeoutFor(cfg);const snap=await runWithTimeout((async()=>{await client.connect();return await client.discoverAndReturn(this.cliConfig,{applyConfigFilters:false})})(),timeoutMs,`unpooled spawn for ${id} (pool will roll back the spawn and free its budget slot)`);if(this.draining||!this.entries.has(id)||entry.isTerminated()){try{view.teardown()}catch{}try{await entry.forceShutdown("manual")}catch{}this.indexDetach(sessionId,id);throw new Error(`McpTransportPool is draining or unpooled ${id} was cancelled`)}entry.markActive(snap.tools,snap.prompts,snap.resources);const conn=entry.attach(sessionId,view,{release:__name(()=>{this.indexDetach(sessionId,id);void entry.forceShutdown("manual")},"release")});return conn}catch(err){try{await entry.forceShutdown("manual")}catch{}this.entries.delete(id);this.unpooledIds.delete(id);this.indexDetach(sessionId,id);try{await client.disconnect()}catch{}throw err}}};function poisonedToolRegistry(serverName){return{registerTool(){throw new Error(`Pool invariant violated: poisoned ToolRegistry for ${serverName} received registerTool. A pool path must use discoverAndReturn, not discover.`)}}}__name(poisonedToolRegistry,"poisonedToolRegistry");function poisonedPromptRegistry(serverName){return{registerPrompt(){throw new Error(`Pool invariant violated: poisoned PromptRegistry for ${serverName} received registerPrompt. A pool path must use discoverAndReturn.`)}}}__name(poisonedPromptRegistry,"poisonedPromptRegistry");init_esbuild_shims();var debugLogger4=createDebugLogger("McpPool:Budget");var WorkspaceMcpBudget=class{static{__name(this,"WorkspaceMcpBudget")}clientBudget;mode;onEvent;reservedSlots=new Set;pendingRefusalNames=new Set;pendingRefusalTransports=new Map;lastRefusedServerNames=[];warnArmed=true;bulkPassDepth=0;constructor(opts){this.clientBudget=opts.clientBudget;this.mode=opts.mode;this.onEvent=opts.mode==="off"?void 0:opts.onEvent}getMode(){return this.mode}getBudget(){return this.clientBudget}getReservedSlots(){return Array.from(this.reservedSlots)}getRefusedServerNames(){return this.lastRefusedServerNames}getReservedCount(){return this.reservedSlots.size}tryReserve(serverName){if(this.reservedSlots.has(serverName))return"already_held";if(this.clientBudget===void 0||this.mode==="off"){return"reserved"}if(this.mode==="enforce"&&this.reservedSlots.size>=this.clientBudget){return"refused"}this.reservedSlots.add(serverName);this.evaluateState();return"reserved"}release(serverName){const had=this.reservedSlots.delete(serverName);if(had)this.evaluateState();return had}recordRefusal(serverName,transport){if(this.mode!=="enforce")return;this.pendingRefusalNames.add(serverName);this.pendingRefusalTransports.set(serverName,transport);debugLogger4.warn(`MCP server '${serverName}' refused at pool acquire (budget exhausted, budget=${this.clientBudget}, mode=${this.mode})`);if(this.bulkPassDepth===0){this.flushRefusedBatch()}}beginBulkPass(){if(this.bulkPassDepth===0){this.lastRefusedServerNames=[]}this.bulkPassDepth+=1}endBulkPass(){if(this.bulkPassDepth===0){debugLogger4.warn("WorkspaceMcpBudget.endBulkPass called without matching beginBulkPass; ignoring");return}this.bulkPassDepth-=1;if(this.bulkPassDepth>0)return;this.flushRefusedBatch()}flushRefusedBatch(){if(this.pendingRefusalNames.size===0)return;if(this.clientBudget===void 0||this.mode!=="enforce"){this.pendingRefusalNames.clear();this.pendingRefusalTransports.clear();return}const refusedServers=[];const names=[];for(const name of this.pendingRefusalNames){const transport=this.pendingRefusalTransports.get(name)??"unknown";refusedServers.push({name,transport,reason:"budget_exhausted"});names.push(name)}this.lastRefusedServerNames=Object.freeze(names);this.pendingRefusalNames.clear();this.pendingRefusalTransports.clear();if(this.onEvent){try{this.onEvent({kind:"refused_batch",refusedServers,budget:this.clientBudget,liveCount:this.reservedSlots.size,reservedCount:this.reservedSlots.size,mode:"enforce"})}catch(err){debugLogger4.error(`WorkspaceMcpBudget refused_batch event delivery failed: ${err instanceof Error?err.message:String(err)}`)}}}evaluateState(){if(this.mode==="off"||this.clientBudget===void 0)return;const ratio=this.reservedSlots.size/this.clientBudget;if(this.warnArmed&&ratio>=MCP_BUDGET_WARN_FRACTION){this.warnArmed=false;debugLogger4.info(`MCP workspace budget warning fired (ratio=${ratio.toFixed(2)}, reservedCount=${this.reservedSlots.size}, budget=${this.clientBudget}, mode=${this.mode})`);if(this.onEvent){try{this.onEvent({kind:"budget_warning",liveCount:this.reservedSlots.size,reservedCount:this.reservedSlots.size,budget:this.clientBudget,thresholdRatio:MCP_BUDGET_WARN_FRACTION,mode:this.mode})}catch(err){debugLogger4.error(`WorkspaceMcpBudget budget_warning event delivery failed: ${err instanceof Error?err.message:String(err)}`)}}}else if(!this.warnArmed&&ratio<MCP_BUDGET_REARM_FRACTION){this.warnArmed=true;debugLogger4.info(`MCP workspace budget warning re-armed (ratio=${ratio.toFixed(2)}, budget=${this.clientBudget}; next 75% crossing will fire)`)}}};init_esbuild_shims();function preservePlaceholders(value,resolved,original){if(typeof original==="string"&&value===resolved)return original;if(Array.isArray(value)&&Array.isArray(resolved)&&Array.isArray(original)){return value.map((entry,index)=>preservePlaceholders(entry,resolved[index],original[index]))}if(value&&resolved&&original&&typeof value==="object"&&!Array.isArray(value)&&typeof resolved==="object"&&!Array.isArray(resolved)&&typeof original==="object"&&!Array.isArray(original)){return Object.fromEntries(Object.entries(value).map(([key,entry])=>[key,preservePlaceholders(entry,resolved[key],original[key])]))}return value}__name(preservePlaceholders,"preservePlaceholders");function preserveModelProviderPlaceholders(models,provider,resolvedProviders,rawProviders,mapping){const pairs=Object.entries(resolvedProviders).flatMap(([providerId,entries])=>{if(!Array.isArray(entries))return[];return entries.flatMap((entry,index)=>{const resolved=provider==="openai"?getModelsForProviderProtocol({[providerId]:[entry]},"openai",mapping)[0]:providerId===provider?entry:void 0;return resolved?[{providerId,resolved,source:entry,raw:rawProviders[providerId]?.[index]??entry}]:[]})});return models.map(model=>{const matches=pairs.filter(({resolved})=>resolved.id===model.id&&resolved.baseUrl===model.baseUrl&&tryResolveModelProtocol(provider,resolved,mapping)===tryResolveModelProtocol(provider,model,mapping));const sourceMatches=matches.filter(pair=>pair.providerId===matches[0]?.providerId);if(sourceMatches.length>1&&sourceMatches.some(pair=>JSON.stringify(pair.raw)!==JSON.stringify(pair.source))){throw new Error("Cannot preserve placeholders in an ambiguous model configuration. Remove duplicate model entries first.")}const match=matches[0];return match?preservePlaceholders(model,match.resolved,match.raw):model})}__name(preserveModelProviderPlaceholders,"preserveModelProviderPlaceholders");init_esbuild_shims();init_esbuild_shims();var DISCOVERY_TIMEOUT_MS=5e3;var DISCOVERY_MAX_BYTES=1024*1024;var MAX_MODEL_ID_LENGTH=256;var UNSAFE_MODEL_ID_CHARS=/[,\p{C}\p{Zl}\p{Zp}]/u;function readModels(value){if(!value||typeof value!=="object"||!("data"in value)){return null}const data=value.data;if(!Array.isArray(data)){return null}const models=[];const seen=new Set;for(const item of data){if(!item||typeof item!=="object"||!("id"in item)){return null}const id=item.id;if(typeof id!=="string"){return null}const trimmedId=id.trim();if(trimmedId&&trimmedId.length<=MAX_MODEL_ID_LENGTH&&!UNSAFE_MODEL_ID_CHARS.test(trimmedId)&&!seen.has(trimmedId)){seen.add(trimmedId);const created=item.created;const creationTime=typeof created==="number"&&Number.isFinite(created)&&created>=0?created:void 0;models.push({id:trimmedId,...creationTime===void 0?{}:{created:creationTime}})}}return models.length>0?models:null}__name(readModels,"readModels");function mergeModelSpecs(discoveredModels,staticModels){const staticModelsById=new Map(staticModels.map(model=>[model.id,model]));const orderedModels=[...discoveredModels];if(orderedModels.every(model=>model.created!==void 0)){orderedModels.sort((left,right)=>(right.created??0)-(left.created??0))}return orderedModels.map(({id})=>staticModelsById.get(id)??{id})}__name(mergeModelSpecs,"mergeModelSpecs");async function discoverProviderModels({baseUrl,apiKey,staticModels,signal}){const normalizedBaseUrl=baseUrl.trim();const normalizedApiKey=apiKey.trim();if(!normalizedBaseUrl||!normalizedApiKey){return null}try{const modelsUrl=`${normalizedBaseUrl.replace(/\/+$/,"")}/models`;const result=await fetchWithPolicy(modelsUrl,{timeoutMs:DISCOVERY_TIMEOUT_MS,maxBytes:DISCOVERY_MAX_BYTES,maxRedirects:2,headers:{Accept:"application/json",Authorization:`Bearer ${normalizedApiKey}`},signal});if(result.kind!=="response"||result.status<200||result.status>=300){return null}const models=readModels(JSON.parse(result.body.toString("utf8")));return models?mergeModelSpecs(models,staticModels):null}catch{return null}}__name(discoverProviderModels,"discoverProviderModels");init_esbuild_shims();var IMAGE_CAPABILITY=Object.freeze({autoHandlesWrongModel:true,maxBytes:VISION_BRIDGE_MAX_IMAGE_BASE64_BYTES,maxImagesPerTurn:VISION_BRIDGE_MAX_IMAGES});init_esbuild_shims();var debugLogger5=createDebugLogger("SESSION_RECAP");var RECENT_MESSAGE_WINDOW=30;var RECAP_SYSTEM_PROMPT=`You generate session recaps for a programming assistant CLI.
|
|
3
|
+
import{MAX_DROPPED_MSG_IDS,MAX_FRAME_BYTES,MAX_RETAINED_REPLY_TOKEN_CHARS,MAX_SENDER_KEY_CHARS,MAX_SOCKET_PATH_BYTES,SOCKET_DIR_NAME,isLocalIpcPath,parsePeerAuthLine,parsePeerFrame,peerSenderKey,probePeerSocketVerdict,resolvePeerSocketCandidates}from"./chunk-MKH3EH7O.js";import{scanForSecrets}from"./chunk-AKWYMQKU.js";import{collectPtyProcessTree}from"./chunk-PGRN3GZY.js";import{BudgetExhaustedError,IDE_DEFINITIONS,MCP_BUDGET_REARM_FRACTION,MCP_BUDGET_WARN_FRACTION,McpClient,ORPHAN_TOOL_USE_REPAIR_REASON,POOLED_TRANSPORTS_DEFAULT,QWEN_CODE_COMPANION_EXTENSION_NAME,SessionService,StandardFileSystemService,aggregateUsage,buildSessionHistoryFromConversation,buildSyntheticToolResponseParts,classifyShellCommandSafety,classifyShellCommandSafetyInDirectory,coerceMcpFilterEntries,connectionIdOf,convertToFunctionErrorResponse,convertToFunctionResponse,createForkedChat,detectTurnInterruption,discoveryTimeoutFor,estimateContentTokens,evaluateToolInvocationGuard,finalizeToolResponses,getCacheSafeParams,getCacheSafeParamsSessionId,getTimeRangeBounds,isPoolable,listDescendantPids,listExistingSkillDirNames,loadUsageHistoryWithLive,mcpSessionMetadataKey,mcpTransportOf,normalizeMcpIncludeEntry,observeToolResultBoundary,parseConnectionId,recursivelyHydrateStrings,repairOrphanedToolUseTurns,runForkedAgent,runWithForkedChatModel,runWithTimeout,sigtermPids,stripToolResultImages,toolResultBoundaryArtifact,toolResultPartDiagnosticValues,withoutAutoMemorySnapshots}from"./chunk-T3CQ72HC.js";import{shellResultText}from"./chunk-T7CHK6C2.js";import{runGit,runGitCapture,streamGitRecords}from"./chunk-ILECDNJX.js";import{hasVerifiableInode,openNoFollow,openSyncNoFollow}from"./chunk-QXQGUM3Y.js";import{projectUserTranscriptForDisplay}from"./chunk-SZCBUCNH.js";import{toolSearchBridgeSentence}from"./chunk-5SUFJTQQ.js";import{flattenPeerLabel}from"./chunk-BYU42MLK.js";import{isPidAlive}from"./chunk-5LZ2DPLH.js";import{getProjectSkillsRoot}from"./chunk-XQJOZDV7.js";import{parse}from"./chunk-KLC3OD2M.js";import{glob,globSync}from"./chunk-OBOU4ZZM.js";import{isDeferredToolBridgeAvailable}from"./chunk-7CQMWEMY.js";import{require_picomatch}from"./chunk-OUC3WICA.js";import{BUILT_IN_OUTPUT_STYLES,getBuiltInOutputStyle}from"./chunk-OV3EBH6J.js";import{NO_EXEC_CONFIG}from"./chunk-EBMCWXGZ.js";import{require_proper_lockfile}from"./chunk-YIW3H46P.js";import{disposeConoutWorker,loadPty,loadXtermHeadless,noteConPtyHostReleased,releaseConPtyHost}from"./chunk-NMY3PYNO.js";import{stripAnsi}from"./chunk-YGLM5XPP.js";import{resolveBundleDir}from"./chunk-4NPYOXJO.js";import{escapeJsonTagCharacters}from"./chunk-NTRFETZB.js";import{getModelsForProviderProtocol,tryResolveModelProtocol}from"./chunk-ET2Z7ZGF.js";import{fetchWithPolicy}from"./chunk-5CWTKFI4.js";import{COMBINED_PASS_TOLERANCE_FACTOR,TOOL_OUTPUT_TRUNCATED_PREFIX,TRUNCATION_FALLBACK_ENVELOPE_SLACK,addMCPStatusChangeListener,removeMCPStatusChangeListener,updateMCPServerStatus}from"./chunk-ZWPSBU7K.js";import{E_TIMEOUT,Mutex,withTimeout}from"./chunk-HDGTWJ24.js";import{runSideQuery}from"./chunk-K7JCVESI.js";import{MEMORY_SECTION_HEADER,VISION_BRIDGE_MAX_IMAGES,VISION_BRIDGE_MAX_IMAGE_BASE64_BYTES,detectFileType,getCurrentMemoryFilename,isCacheableReadResult,isWithinRoot,processSingleFileContent}from"./chunk-Y6HHV4LC.js";import{getInvocationContext}from"./chunk-EFTJIDS3.js";import{DEFAULT_IMAGE_TOKEN_ESTIMATE,estimatePartChars}from"./chunk-Q6UAOTP3.js";import{atomicWriteFile,atomicWriteJSON}from"./chunk-BMHYEQTI.js";import{isBinary,normalizeContent,stripAnsiAndControl,stripHtmlComments}from"./chunk-DBRQGEEI.js";import{cloneApiHistory,getFolderStructure,getStartupContextLength,stripSystemReminderBlocks}from"./chunk-B3ZFUGTC.js";import{getQwenIgnoreFileNames,require_ignore}from"./chunk-5DTFN37U.js";import{ToolNames,canonicalToolName}from"./chunk-SBZFGYYS.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{Storage}from"./chunk-EPODBRBP.js";import{PATH_ARG_KEYS,QWEN_DIR,tildeifyPath,unescapePath}from"./chunk-OKN3Z5C5.js";import{getErrorMessage,isAbortError,isNodeError}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__require,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var JsonFormatter=class{static{__name(this,"JsonFormatter")}format(response,stats,error){const output={};if(response!==void 0){output.response=stripAnsi(response)}if(stats){output.stats=stats}if(error){output.error=error}return JSON.stringify(output,null,2)}formatError(error,code){const jsonError={type:error.constructor.name,message:stripAnsi(error.message),...code&&{code}};return this.format(void 0,void 0,jsonError)}};init_esbuild_shims();function createPlanId(sessionId,historyLength){return`${sessionId}:${historyLength}`}__name(createPlanId,"createPlanId");function buildVisibleNotice(kind,repairs,historyGaps){if(kind==="clean"){return void 0}if(kind==="degraded_history"){return`Resumed session history is incomplete: detected ${historyGaps.length} missing parent link(s). Automatic continuation is disabled for this recovery.`}if(kind==="interrupted_prompt"){return"Previous session appears to have stopped after user input before the model completed a response."}const synthesized=repairs.filter(repair=>repair.type==="synthesized_tool_result").length;if(synthesized>0){return`Previous session appears to have stopped during tool execution. Synthesized ${synthesized} failed tool result(s) so the history can continue safely.`}return"Previous session appears to have stopped during tool execution."}__name(buildVisibleNotice,"buildVisibleNotice");function buildSessionRecoveryPlan({sessionId,conversation,historyGaps,options}){return buildSessionRecoveryPlanFromApiHistory({sessionId,...buildSessionHistoryFromConversation(conversation),historyGaps,options})}__name(buildSessionRecoveryPlan,"buildSessionRecoveryPlan");function buildSessionRecoveryPlanFromApiHistory({sessionId,apiHistory:inputApiHistory,completedToolCallIds,trailingSystemNotifications,historyGaps,options}){const originalApiHistory=inputApiHistory;const gaps=historyGaps??[];const planId=createPlanId(sessionId,originalApiHistory.length);const apiHistory=cloneApiHistory(originalApiHistory);const repairResult=repairOrphanedToolUseTurns(apiHistory);const repairs=[...repairResult.injected.map(repair=>({type:"synthesized_tool_result",callId:repair.callId,name:repair.name})),...repairResult.droppedDuplicates.map(repair=>({type:"dropped_duplicate_tool_result",callId:repair.callId,name:repair.name})),...gaps.map(gap=>({type:"history_gap",childUuid:gap.childUuid,missingParentUuid:gap.missingParentUuid}))];if(gaps.length>0){return{planId,sessionId,kind:"degraded_history",originalApiHistory,apiHistory,repairs,canContinue:false,canAutoContinue:false,requiresUserConfirmation:true,visibleNotice:buildVisibleNotice("degraded_history",repairs,gaps)}}const interruption=detectTurnInterruption(originalApiHistory,completedToolCallIds,trailingSystemNotifications);if(interruption.kind==="none"){return{planId,sessionId,kind:"clean",originalApiHistory,apiHistory,repairs,canContinue:false,canAutoContinue:false,requiresUserConfirmation:false}}if(interruption.kind==="interrupted_prompt"){const continuation2={mode:"retry_user_parts",parts:interruption.parts,displayText:"Continue interrupted user prompt"};return{planId,sessionId,kind:"interrupted_prompt",originalApiHistory,apiHistory,repairs,canContinue:true,canAutoContinue:options?.allowAutoContinue===true,requiresUserConfirmation:options?.allowAutoContinue!==true,visibleNotice:buildVisibleNotice("interrupted_prompt",repairs,gaps),continuation:continuation2}}const continuation={mode:"tool_result_parts",parts:buildSyntheticToolResponseParts(interruption.danglingCalls,ORPHAN_TOOL_USE_REPAIR_REASON),displayText:"Continue interrupted tool turn"};return{planId,sessionId,kind:"interrupted_turn",originalApiHistory,apiHistory,repairs,canContinue:true,canAutoContinue:false,requiresUserConfirmation:true,visibleNotice:buildVisibleNotice("interrupted_turn",repairs,gaps),continuation}}__name(buildSessionRecoveryPlanFromApiHistory,"buildSessionRecoveryPlanFromApiHistory");init_esbuild_shims();init_esbuild_shims();import{EventEmitter}from"node:events";init_esbuild_shims();var debugLogger=createDebugLogger("McpPool:Entry");function defaultPoolEntryOptions(transport){const isRemote=transport==="http"||transport==="sse"||transport==="websocket";return{drainDelayMs:3e4,maxIdleMs:5*6e4,maxReconnectAttempts:isRemote?5:3,reconnectStrategy:isRemote?{kind:"exponential",baseMs:1e3,capMs:16e3}:{kind:"fixed",delayMs:5e3}}}__name(defaultPoolEntryOptions,"defaultPoolEntryOptions");var PoolEntry=class{constructor(id,serverName,entryIndex,cfg,client,cliConfig,opts,onClosed,aggregateStatusByName){this.id=id;this.serverName=serverName;this.entryIndex=entryIndex;this.cfg=cfg;this.client=client;this.cliConfig=cliConfig;this.opts=opts;this.onClosed=onClosed;this.aggregateStatusByName=aggregateStatusByName;this.transportId=connectionIdOf(serverName,cfg);this.emitter.setMaxListeners(0);this.statusChangeListener=(name,status)=>{if(name!==this.serverName)return;if(status===void 0)return;if(this.suppressNextStatusEcho){this.suppressNextStatusEcho=false;return}if(this.client.getStatus()!==status)return;if(status===this.localStatus)return;this.localStatus=status;if(status==="disconnected"&&(this.state==="active"||this.state==="draining")&&!this.restartInProgress){const wasDraining=this.state==="draining";this.state="failed";if(wasDraining){this.cancelDrainTimer()}if(this.maxIdleTimer){clearTimeout(this.maxIdleTimer);this.maxIdleTimer=void 0}if(this.statusChangeListener){removeMCPStatusChangeListener(this.statusChangeListener);this.statusChangeListener=void 0}debugLogger.error(`PoolEntry ${this.id} silent transport drop (prev state='${wasDraining?"draining":"active"}', localStatus\u2192DISCONNECTED). Transitioning to 'failed'; evicting from pool.entries + pooledConnections (W122 R20).`);const upstreamError=this.client.getLastTransportError();this.emit({kind:"failed",serverName:this.serverName,generation:this._generation,lastError:upstreamError?`transport disconnected (silent transport drop): ${upstreamError.message}`:"transport disconnected (silent transport drop)"});for(const[sid]of[...this.subscribers]){this.detach(sid)}void this.sweepAndDisconnect("silent_drop").then(result=>{const partialSignal=result.descendantsFound!==void 0&&result.descendantsSignaled!==void 0&&result.descendantsSignaled<result.descendantsFound;if(result.pidSweepError!==void 0||partialSignal){debugLogger.warn(`PoolEntry ${this.id} silent-drop sweep observability: descendantsFound=${result.descendantsFound??"unknown"}, descendantsSignaled=${result.descendantsSignaled??"unknown"}, pidSweepError=${result.pidSweepError?.message??"none"}. Possible orphan-process pressure \u2014 operator should check for lingering subprocess descendants of the dead transport.`)}this.updateGlobalStatus()},()=>{this.updateGlobalStatus()});this.updateGlobalStatus();this.onClosed(this.id)}};addMCPStatusChangeListener(this.statusChangeListener)}static{__name(this,"PoolEntry")}localStatus="connecting";state="spawning";_generation=0;refs=new Set;subscribers=new Map;subscriberHandles=new Map;toolsSnapshot=[];promptsSnapshot=[];resourcesSnapshot=[];drainTimer;maxIdleTimer;firstIdleAt;restartInFlight;restartInProgress=false;emitter=new EventEmitter;statusChangeListener;suppressNextStatusEcho=false;transportId;get generation(){return this._generation}get currentState(){return this.state}get transportKind(){return mcpTransportOf(this.cfg)}isTerminated(){return this.state==="closed"||this.state==="failed"}markActive(initialTools,initialPrompts,initialResources){if(this.state==="closed"||this.state==="failed")return;this.toolsSnapshot=initialTools;this.promptsSnapshot=initialPrompts;this.resourcesSnapshot=initialResources;this.state="active";this.localStatus="connected";this.updateGlobalStatus()}attach(sessionId,view,opts){if(this.state==="closed"||this.state==="failed"){throw new Error(`Cannot attach to PoolEntry ${this.id} in state ${this.state}`)}const previousState=this.state;const hadRef=this.refs.has(sessionId);const previousView=this.subscribers.get(sessionId);const previousHandle=this.subscriberHandles.get(sessionId);this.refs.add(sessionId);this.subscribers.set(sessionId,view);this.cancelDrainTimer();if(this.state==="draining")this.state="active";if(this.state==="active"&&opts?.skipReplay!==true){try{view.applyTools(this.toolsSnapshot);view.applyPrompts(this.promptsSnapshot);view.applyResources(this.resourcesSnapshot)}catch(err){if(!hadRef){this.refs.delete(sessionId);this.subscribers.delete(sessionId);this.subscriberHandles.delete(sessionId);try{view.teardown()}catch{}}else if(previousView){this.subscribers.set(sessionId,previousView);if(previousHandle){this.subscriberHandles.set(sessionId,previousHandle)}}if(previousState==="draining"&&this.refs.size===0){this.startDrainTimer(this.opts.drainDelayMs)}else{this.state=previousState}debugLogger.error(`Snapshot replay failed for ${sessionId}/${this.serverName}: ${String(err)}`);throw err}}const handle=new PooledConnectionImpl(this,sessionId,opts?.release);this.subscriberHandles.set(sessionId,handle);return handle}updateSessionConfig(sessionId,cfg){if(this.isTerminated()){throw new Error(`Cannot update config on PoolEntry ${this.id} in state ${this.state}`)}const view=this.subscribers.get(sessionId);if(!view){throw new Error(`Cannot update config for detached session ${sessionId} on PoolEntry ${this.id}`)}if(!view.updateConfig(cfg))return;if(this.state==="active"){view.applyTools(this.toolsSnapshot);view.applyPrompts(this.promptsSnapshot);view.applyResources(this.resourcesSnapshot)}}detach(sessionId){const view=this.subscribers.get(sessionId);if(view){try{view.teardown()}catch(err){debugLogger.error(`View teardown failed for ${sessionId}/${this.serverName}: ${String(err)}`)}}this.subscribers.delete(sessionId);this.subscriberHandles.delete(sessionId);this.refs.delete(sessionId)}startDrainTimer(delayMs){this.cancelDrainTimer();this.state="draining";if(this.firstIdleAt===void 0){this.firstIdleAt=Date.now();this.maxIdleTimer=setTimeout(()=>{if(this.refs.size>0){debugLogger.debug(`PoolEntry ${this.id} max-idle reached but ${this.refs.size} sessions active; deferring close, resetting first-idle window`);this.maxIdleTimer=void 0;this.firstIdleAt=void 0;return}debugLogger.warn(`PoolEntry ${this.id} hit MAX_IDLE_MS (${this.opts.maxIdleMs}ms); force-closing`);void this.forceShutdown("max_idle")},this.opts.maxIdleMs);this.maxIdleTimer.unref?.()}this.drainTimer=setTimeout(()=>{void this.forceShutdown("drain_timer")},delayMs);this.drainTimer.unref?.()}cancelDrainTimer(){if(this.drainTimer){clearTimeout(this.drainTimer);this.drainTimer=void 0}}async forceShutdown(reason){if(this.state==="closed"||this.state==="failed")return;this.state="closed";this.localStatus="disconnected";this.suppressNextStatusEcho=true;this.cancelDrainTimer();if(this.maxIdleTimer){clearTimeout(this.maxIdleTimer);this.maxIdleTimer=void 0}if(this.statusChangeListener){removeMCPStatusChangeListener(this.statusChangeListener);this.statusChangeListener=void 0}this.emit({kind:"disconnected",serverName:this.serverName,generation:this._generation,reason:"transport_closed"});for(const[sid]of this.subscribers){this.detach(sid)}await this.sweepAndDisconnect(reason);this.updateGlobalStatus();this.onClosed(this.id)}async sweepAndDisconnect(reason){const result={};try{const rootPid=this.client.getTransportPid?.();if(rootPid!==void 0){const descendants=await listDescendantPids(rootPid);if(descendants.length>0){result.descendantsFound=descendants.length;result.descendantsSignaled=sigtermPids(descendants);debugLogger.debug(`Sent SIGTERM to ${result.descendantsSignaled}/${descendants.length} descendants of pid ${rootPid} for ${this.id} (${reason})`)}}}catch(err){result.pidSweepError=err instanceof Error?err:new Error(String(err));debugLogger.warn(`Descendant pid sweep failed for ${this.id} (${reason}): ${String(err)}. Proceeding with disconnect.`)}try{await this.client.disconnect()}catch(err){debugLogger.error(`client.disconnect failed for ${this.id} (${reason}): ${String(err)}`)}return result}async restart(){if(this.restartInFlight)return this.restartInFlight;this.restartInFlight=this.doRestart().finally(()=>{this.restartInFlight=void 0});return this.restartInFlight}async doRestart(){if(this.state==="closed"||this.state==="failed"){throw new Error(`Cannot restart PoolEntry ${this.id} in state ${this.state}`)}this.restartInProgress=true;try{return await this.doRestartInner()}finally{this.restartInProgress=false}}async doRestartInner(){this.cancelDrainTimer();if(this.maxIdleTimer){clearTimeout(this.maxIdleTimer);this.maxIdleTimer=void 0}this.firstIdleAt=void 0;if(this.state==="draining"){this.state="active"}const oldGen=this._generation;this._generation+=1;this.emit({kind:"disconnected",serverName:this.serverName,generation:oldGen,reason:"restart"});await this.sweepAndDisconnect("restart");let snap;try{const timeoutMs=discoveryTimeoutFor(this.cfg);snap=await runWithTimeout((async()=>{await this.client.connect();return this.client.discoverAndReturn(this.cliConfig,{applyConfigFilters:false})})(),timeoutMs,`pool restart for ${this.id} (pool will roll back the restart and free its budget slot)`)}catch(err){debugLogger.error(`Restart of ${this.id} failed at connect/discover: ${String(err)}. Transitioning to 'failed'.`);await this.sweepAndDisconnect("restart_failed");this.state="failed";this.localStatus="disconnected";this.suppressNextStatusEcho=true;this.updateGlobalStatus();if(this.statusChangeListener){removeMCPStatusChangeListener(this.statusChangeListener);this.statusChangeListener=void 0}this.emit({kind:"failed",serverName:this.serverName,generation:this._generation,lastError:err instanceof Error?err.message:String(err)});for(const[sid]of this.subscribers){this.detach(sid)}this.onClosed(this.id);throw err}if(oldGen+1!==this._generation){await this.sweepAndDisconnect("restart_superseded");throw new Error(`Restart of ${this.id} superseded by newer generation; discarded stale snapshot + swept new transport.`)}const currentState=this.state;if(currentState==="closed"||currentState==="failed"){await this.sweepAndDisconnect("restart_superseded");throw new Error(`Restart of ${this.id} aborted: entry state is ${currentState} (forceShutdown ran concurrently mid-restart). Snapshot discarded; new transport swept.`)}this.toolsSnapshot=snap.tools;this.promptsSnapshot=snap.prompts;if(snap.resources.length>0){this.resourcesSnapshot=snap.resources}for(const[sid,view]of this.subscribers){try{view.applyTools(this.toolsSnapshot);view.applyPrompts(this.promptsSnapshot);view.applyResources(this.resourcesSnapshot)}catch(err){debugLogger.error(`Restart fan-out to view ${sid}/${this.serverName} failed: ${String(err)}`)}}this.localStatus="connected";this.suppressNextStatusEcho=true;this.updateGlobalStatus();this.emit({kind:"reconnected",serverName:this.serverName,generation:this._generation});this.emit({kind:"toolsChanged",serverName:this.serverName,snapshot:this.toolsSnapshot,generation:this._generation});this.emit({kind:"promptsChanged",serverName:this.serverName,snapshot:this.promptsSnapshot,generation:this._generation});this.emit({kind:"resourcesChanged",serverName:this.serverName,snapshot:this.resourcesSnapshot,generation:this._generation})}emit(event){const listeners=this.emitter.listeners("event");for(const listener of listeners){try{listener(event)}catch(err){debugLogger.error(`PoolEntry listener error for ${this.id} (event.kind=${event.kind}): ${err instanceof Error?err.message:String(err)}`)}}}internalOn(listener){this.emitter.on("event",listener)}internalOff(listener){this.emitter.off("event",listener)}updateGlobalStatus(){const aggregated=this.aggregateStatusByName(this.serverName);updateMCPServerStatus(this.serverName,aggregated)}getLocalStatus(){return this.localStatus}};var PooledConnectionImpl=class{constructor(entry,sessionId,releaseCallback){this.entry=entry;this.sessionId=sessionId;this.releaseCallback=releaseCallback}static{__name(this,"PooledConnectionImpl")}listeners=new Set;released=false;get id(){return this.entry.id}get transportId(){return this.entry.transportId}get serverName(){return this.entry.serverName}get entryIndex(){return this.entry.entryIndex}get client(){return this.entry.client}get toolsSnapshot(){return this.entry.toolsSnapshot}get promptsSnapshot(){return this.entry.promptsSnapshot}get resourcesSnapshot(){return this.entry.resourcesSnapshot}updateConfig(cfg){if(this.released){throw new Error(`Cannot update config on released MCP connection ${this.id}`)}this.entry.updateSessionConfig(this.sessionId,cfg)}on(event,listener){if(event!=="event")return this;if(this.listeners.has(listener))return this;this.listeners.add(listener);this.entry.internalOn(listener);return this}off(event,listener){if(event!=="event")return this;this.listeners.delete(listener);this.entry.internalOff(listener);return this}release(){if(this.released)return;this.released=true;for(const l of this.listeners){this.entry.internalOff(l)}this.listeners.clear();this.releaseCallback?.()}};init_esbuild_shims();var debugLogger2=createDebugLogger("McpPool:View");function compileNameFilter(includeTools,excludeTools){return{excludeSet:excludeTools?new Set(coerceMcpFilterEntries(excludeTools)):void 0,includeSet:includeTools!=null?new Set(coerceMcpFilterEntries(includeTools).map(normalizeMcpIncludeEntry)):void 0}}__name(compileNameFilter,"compileNameFilter");function compiledFilterAccepts(filter2,name){if(filter2.excludeSet?.has(name))return false;if(!filter2.includeSet)return true;return filter2.includeSet.has(name)}__name(compiledFilterAccepts,"compiledFilterAccepts");var SessionMcpView=class{constructor(sessionToolRegistry,sessionPromptRegistry,sessionResourceRegistry,sessionId,serverName,cfg){this.sessionToolRegistry=sessionToolRegistry;this.sessionPromptRegistry=sessionPromptRegistry;this.sessionResourceRegistry=sessionResourceRegistry;this.sessionId=sessionId;this.serverName=serverName;this.cfg=cfg;this.metadataKey=mcpSessionMetadataKey(cfg)}static{__name(this,"SessionMcpView")}metadataKey;applyTools(snapshot){this.sessionToolRegistry.removeMcpToolsByServer(this.serverName);const filter2=compileNameFilter(this.cfg.includeTools,this.cfg.excludeTools);let registered=0;for(const tool of snapshot){if(!compiledFilterAccepts(filter2,tool.serverToolName)){continue}const sessionTool=tool.withSessionConfig(this.cfg.trust,this.cfg.alwaysLoadTools===true);try{this.sessionToolRegistry.registerTool(sessionTool);registered+=1}catch(err){debugLogger2.error(`SessionMcpView[${this.sessionId}/${this.serverName}] failed to register tool ${tool.serverToolName}: ${String(err instanceof Error?err.message:err)}`)}}debugLogger2.debug(`SessionMcpView[${this.sessionId}/${this.serverName}] applied ${snapshot.length} tools (filtered to ${registered} registered)`)}applyPrompts(snapshot){this.sessionPromptRegistry.removePromptsByServer(this.serverName);const filter2=compileNameFilter(this.cfg.includeTools,this.cfg.excludeTools);let registered=0;for(const prompt of snapshot){if(!compiledFilterAccepts(filter2,prompt.name)){continue}try{this.sessionPromptRegistry.registerPrompt(prompt);registered+=1}catch(err){debugLogger2.error(`SessionMcpView[${this.sessionId}/${this.serverName}] failed to register prompt ${prompt.name}: ${String(err instanceof Error?err.message:err)}`)}}debugLogger2.debug(`SessionMcpView[${this.sessionId}/${this.serverName}] applied ${snapshot.length} prompts (filtered to ${registered} registered)`)}applyResources(snapshot){if(snapshot.length===0){return}this.sessionResourceRegistry.removeResourcesByServer(this.serverName);for(const resource of snapshot){try{this.sessionResourceRegistry.registerResource(resource)}catch(err){debugLogger2.error(`SessionMcpView[${this.sessionId}/${this.serverName}] failed to register resource ${resource.uri}: ${String(err instanceof Error?err.message:err)}`)}}debugLogger2.debug(`SessionMcpView[${this.sessionId}/${this.serverName}] applied ${snapshot.length} resources`)}updateConfig(cfg){const nextKey=mcpSessionMetadataKey(cfg);const changed=this.metadataKey!==nextKey;this.cfg=cfg;this.metadataKey=nextKey;return changed}teardown(){this.sessionToolRegistry.removeMcpToolsByServer(this.serverName);this.sessionPromptRegistry.removePromptsByServer(this.serverName);this.sessionResourceRegistry.removeResourcesByServer(this.serverName);debugLogger2.debug(`SessionMcpView[${this.sessionId}/${this.serverName}] torn down`)}};var debugLogger3=createDebugLogger("McpPool");var McpTransportPool=class{constructor(cliConfig,options){this.cliConfig=cliConfig;this.opts={workspaceContext:options.workspaceContext,debugMode:options.debugMode,sendSdkMcpMessage:options.sendSdkMcpMessage,pooledTransports:options.pooledTransports??POOLED_TRANSPORTS_DEFAULT,drainDelayMs:options.drainDelayMs??3e4,entryOptions:options.entryOptions??defaultPoolEntryOptions,budget:options.budget}}static{__name(this,"McpTransportPool")}entries=new Map;unpooledIds=new Set;spawnInFlight=new Map;sessionToEntries=new Map;draining=false;nextIndexByName=new Map;opts;getBudget(){return this.opts.budget}hasNameSibling(serverName){for(const e of this.entries.values()){if(e.serverName===serverName)return true}for(const id of this.spawnInFlight.keys()){try{if(parseConnectionId(id).serverName===serverName)return true}catch{}}return false}async acquire(serverName,cfg,sessionId,sessionToolRegistry,sessionPromptRegistry,sessionResourceRegistry){if(this.draining){throw new Error(`McpTransportPool is draining; refusing acquire for ${serverName} (session ${sessionId})`)}const poolable=isPoolable(cfg,this.opts.pooledTransports);const id=poolable?connectionIdOf(serverName,cfg):void 0;if(id!==void 0){const existing=this.entries.get(id);if(existing&&!existing.isTerminated()){try{const conn=this.attachPooledSession(existing,id,serverName,cfg,sessionId,sessionToolRegistry,sessionPromptRegistry,sessionResourceRegistry);this.indexAttach(sessionId,id);return conn}catch(err){if(existing.isTerminated()){this.evictEntry(id,existing);debugLogger3.warn(`pool self-heal: evicted terminal entry ${id} (state='${existing.currentState}', serverName='${serverName}') mid-attach race; falling through to spawn fresh entry`)}else{throw err}}}else if(existing&&existing.isTerminated()){this.evictEntry(id,existing);debugLogger3.warn(`pool self-heal: evicted stale terminal entry ${id} (state='${existing.currentState}', serverName='${serverName}') before fast-path attach; falling through to spawn fresh entry`)}}let reservationResult;if(this.opts.budget!==void 0){const reservation=this.opts.budget.tryReserve(serverName);if(reservation==="refused"){const transport=mcpTransportOf(cfg);this.opts.budget.recordRefusal(serverName,transport);throw new BudgetExhaustedError(serverName,this.opts.budget.getBudget()??0,this.opts.budget.getReservedCount())}reservationResult=reservation}if(!poolable){try{return await this.createUnpooledConnection(serverName,cfg,sessionId,sessionToolRegistry,sessionPromptRegistry,sessionResourceRegistry)}catch(err){this.rollbackReservationOnSpawnFailure(reservationResult,serverName);throw err}}if(id===void 0){throw new Error("unreachable: poolable && id === undefined")}let inFlight=this.spawnInFlight.get(id);if(!inFlight){const spawnPromise=this.spawnEntry(serverName,cfg,id);inFlight=spawnPromise.finally(()=>{this.spawnInFlight.delete(id)}).catch(err=>{this.rollbackReservationOnSpawnFailure(reservationResult,serverName);throw err});this.spawnInFlight.set(id,inFlight)}this.indexAttach(sessionId,id);let entry;try{entry=await inFlight}catch(err){this.indexDetach(sessionId,id);throw err}if(!this.entries.has(id)||entry.isTerminated()){this.indexDetach(sessionId,id);throw new Error(`PoolEntry ${id} torn down before attach (concurrent release)`)}try{const conn=this.attachPooledSession(entry,id,serverName,cfg,sessionId,sessionToolRegistry,sessionPromptRegistry,sessionResourceRegistry);this.indexAttach(sessionId,id);return conn}catch(err){this.indexDetach(sessionId,id);throw err}}release(id,sessionId){const entry=this.entries.get(id);if(!entry)return;entry.detach(sessionId);this.indexDetach(sessionId,id);if(entry.refs.size===0){if(this.unpooledIds.has(id)){void entry.forceShutdown("manual");return}entry.startDrainTimer(this.opts.drainDelayMs)}}releaseSession(sessionId){const ids=this.sessionToEntries.get(sessionId);if(!ids)return;const idList=[...ids];for(const id of idList){const entry=this.entries.get(id);if(!entry)continue;entry.detach(sessionId);if(entry.refs.size===0){if(this.unpooledIds.has(id)){void entry.forceShutdown("manual");continue}entry.startDrainTimer(this.opts.drainDelayMs)}}this.sessionToEntries.delete(sessionId)}async restartByName(serverName,opts){if(this.draining)return[];const matching=[...this.entries.values()].filter(e=>e.serverName===serverName&&(opts?.entryIndex===void 0||e.entryIndex===opts.entryIndex));if(matching.length===0)return[];return Promise.all(matching.map(async entry=>{const started=Date.now();try{await entry.restart();if(entry.refs.size===0&&!this.unpooledIds.has(entry.id)){entry.startDrainTimer(this.opts.drainDelayMs)}return{entryIndex:entry.entryIndex,restarted:true,durationMs:Date.now()-started}}catch(err){return{entryIndex:entry.entryIndex,restarted:false,reason:String(err instanceof Error?err.message:err)}}}))}getSnapshot(){const byName=new Map;let total=0;let subprocessCount=0;for(const entry of this.entries.values()){const status=entry.getLocalStatus();if(status==="connected"){total+=1;if(entry.transportKind==="stdio"){subprocessCount+=1}}const row=byName.get(entry.serverName)??{entryCount:0,entrySummary:[]};row.entryCount+=1;row.entrySummary.push({entryIndex:entry.entryIndex,refs:entry.refs.size,status});byName.set(entry.serverName,row)}return{total,subprocessCount,byName:Object.fromEntries(byName.entries())}}aggregateStatusByName(serverName){let sawConnecting=false;for(const entry of this.entries.values()){if(entry.serverName!==serverName)continue;const s=entry.getLocalStatus();if(s==="connected")return"connected";if(s==="connecting")sawConnecting=true}return sawConnecting?"connecting":"disconnected"}async drainAll(opts){const timeoutMs=opts?.timeoutMs??1e4;const force=opts?.force??false;this.draining=true;const deadline=Date.now()+timeoutMs;if(this.spawnInFlight.size>0){const spawnWait=Promise.allSettled([...this.spawnInFlight.values()]);let inflightTimer;await Promise.race([spawnWait.then(()=>{if(inflightTimer)clearTimeout(inflightTimer)}),new Promise(resolve9=>{inflightTimer=setTimeout(()=>{const stuckIds=[...this.spawnInFlight.keys()];debugLogger3.warn(`drainAll: spawnInFlight wait timed out after ${timeoutMs}ms; ${stuckIds.length} spawn(s) still in-flight: ${stuckIds.join(", ")}. Proceeding with drain.`);resolve9()},Math.max(0,deadline-Date.now()));inflightTimer.unref?.()})])}const entries=[...this.entries.values()];const drained=[];const errors=[];const shutdownPromises=entries.map(entry=>entry.forceShutdown(force?"manual":"drain_timer").then(()=>drained.push(entry.entryIndex)).catch(err=>{errors.push({entryIndex:entry.entryIndex,serverName:entry.serverName,error:String(err instanceof Error?err.message:err)})}));let drainTimer;const remaining=Math.max(0,deadline-Date.now());await Promise.race([Promise.all(shutdownPromises).then(()=>{if(drainTimer)clearTimeout(drainTimer)}),new Promise(resolve9=>{drainTimer=setTimeout(()=>resolve9(),remaining);drainTimer.unref?.()})]);const drainedCount=drained.length;const errorsCount=errors.length;const forced=Math.max(0,entries.length-drainedCount-errorsCount);const errorsCopy=[...errors];this.entries.clear();this.unpooledIds.clear();this.sessionToEntries.clear();this.spawnInFlight.clear();return{drained:drainedCount,forced,errors:errorsCopy}}attachPooledSession(entry,id,serverName,cfg,sessionId,sessionToolRegistry,sessionPromptRegistry,sessionResourceRegistry){const view=new SessionMcpView(sessionToolRegistry,sessionPromptRegistry,sessionResourceRegistry,sessionId,serverName,cfg);return entry.attach(sessionId,view,{release:__name(()=>this.release(id,sessionId),"release")})}rollbackReservationOnSpawnFailure(reservationResult,serverName){if(this.opts.budget!==void 0&&reservationResult==="reserved"&&!this.hasNameSibling(serverName)){this.opts.budget.release(serverName)}}evictEntry(id,entry){if(entry===void 0)return;const current=this.entries.get(id);if(current!==entry)return;this.entries.delete(id);if(this.opts.budget!==void 0){if(!this.hasNameSibling(entry.serverName)){this.opts.budget.release(entry.serverName)}}}async spawnEntry(serverName,cfg,id){const entryIndex=this.allocateEntryIndex(serverName);const transport=mcpTransportOf(cfg);const entryOpts=this.opts.entryOptions(transport);const client=new McpClient(serverName,cfg,poisonedToolRegistry(serverName),poisonedPromptRegistry(serverName),this.opts.workspaceContext,this.opts.debugMode,this.opts.sendSdkMcpMessage);const entryRef={current:void 0};const onClosedForThisEntry=__name(closedId=>{this.evictEntry(closedId,entryRef.current)},"onClosedForThisEntry");const entry=new PoolEntry(id,serverName,entryIndex,cfg,client,this.cliConfig,entryOpts,onClosedForThisEntry,name=>this.aggregateStatusByName(name));entryRef.current=entry;try{const timeoutMs=discoveryTimeoutFor(cfg);const snap=await runWithTimeout((async()=>{await client.connect();return client.discoverAndReturn(this.cliConfig,{applyConfigFilters:false})})(),timeoutMs,`pool spawn for ${id} (pool will roll back the spawn and free its budget slot)`);if(this.draining){debugLogger3.warn(`Spawn for ${id} completed while pool is draining; discarding entry`);try{await entry.forceShutdown("manual")}catch{}throw new Error(`McpTransportPool is draining; discarded spawn ${id}`)}this.entries.set(id,entry);entry.markActive(snap.tools,snap.prompts,snap.resources);debugLogger3.info(`Spawned pool entry ${id} (entryIndex=${entryIndex}, transport=${transport})`);return entry}catch(err){debugLogger3.error(`Failed to spawn pool entry for '${serverName}' (id=${id}, transport=${transport}): ${String(err)}`);try{await entry.forceShutdown("manual")}catch{}this.entries.delete(id);try{await client.disconnect()}catch{}throw err}}allocateEntryIndex(serverName){const next=this.nextIndexByName.get(serverName)??0;this.nextIndexByName.set(serverName,next+1);return next}indexAttach(sessionId,id){let ids=this.sessionToEntries.get(sessionId);if(!ids){ids=new Set;this.sessionToEntries.set(sessionId,ids)}ids.add(id)}indexDetach(sessionId,id){const ids=this.sessionToEntries.get(sessionId);if(!ids)return;ids.delete(id);if(ids.size===0)this.sessionToEntries.delete(sessionId)}async createUnpooledConnection(serverName,cfg,sessionId,sessionToolRegistry,sessionPromptRegistry,sessionResourceRegistry){const entryIndex=this.allocateEntryIndex(serverName);const id=`${serverName}::unpooled-${entryIndex}`;const transport=mcpTransportOf(cfg);const entryOpts=this.opts.entryOptions(transport);const client=new McpClient(serverName,cfg,sessionToolRegistry,sessionPromptRegistry,this.opts.workspaceContext,this.opts.debugMode,this.opts.sendSdkMcpMessage);const view=new SessionMcpView(sessionToolRegistry,sessionPromptRegistry,sessionResourceRegistry,sessionId,serverName,cfg);const entry=new PoolEntry(id,serverName,entryIndex,cfg,client,this.cliConfig,entryOpts,closedId=>{this.entries.delete(closedId);this.unpooledIds.delete(closedId);if(this.opts.budget!==void 0){if(!this.hasNameSibling(serverName)){this.opts.budget.release(serverName)}}},()=>client.getStatus());try{this.entries.set(id,entry);this.unpooledIds.add(id);this.indexAttach(sessionId,id);const timeoutMs=discoveryTimeoutFor(cfg);const snap=await runWithTimeout((async()=>{await client.connect();return await client.discoverAndReturn(this.cliConfig,{applyConfigFilters:false})})(),timeoutMs,`unpooled spawn for ${id} (pool will roll back the spawn and free its budget slot)`);if(this.draining||!this.entries.has(id)||entry.isTerminated()){try{view.teardown()}catch{}try{await entry.forceShutdown("manual")}catch{}this.indexDetach(sessionId,id);throw new Error(`McpTransportPool is draining or unpooled ${id} was cancelled`)}entry.markActive(snap.tools,snap.prompts,snap.resources);const conn=entry.attach(sessionId,view,{release:__name(()=>{this.indexDetach(sessionId,id);void entry.forceShutdown("manual")},"release")});return conn}catch(err){try{await entry.forceShutdown("manual")}catch{}this.entries.delete(id);this.unpooledIds.delete(id);this.indexDetach(sessionId,id);try{await client.disconnect()}catch{}throw err}}};function poisonedToolRegistry(serverName){return{registerTool(){throw new Error(`Pool invariant violated: poisoned ToolRegistry for ${serverName} received registerTool. A pool path must use discoverAndReturn, not discover.`)}}}__name(poisonedToolRegistry,"poisonedToolRegistry");function poisonedPromptRegistry(serverName){return{registerPrompt(){throw new Error(`Pool invariant violated: poisoned PromptRegistry for ${serverName} received registerPrompt. A pool path must use discoverAndReturn.`)}}}__name(poisonedPromptRegistry,"poisonedPromptRegistry");init_esbuild_shims();var debugLogger4=createDebugLogger("McpPool:Budget");var WorkspaceMcpBudget=class{static{__name(this,"WorkspaceMcpBudget")}clientBudget;mode;onEvent;reservedSlots=new Set;pendingRefusalNames=new Set;pendingRefusalTransports=new Map;lastRefusedServerNames=[];warnArmed=true;bulkPassDepth=0;constructor(opts){this.clientBudget=opts.clientBudget;this.mode=opts.mode;this.onEvent=opts.mode==="off"?void 0:opts.onEvent}getMode(){return this.mode}getBudget(){return this.clientBudget}getReservedSlots(){return Array.from(this.reservedSlots)}getRefusedServerNames(){return this.lastRefusedServerNames}getReservedCount(){return this.reservedSlots.size}tryReserve(serverName){if(this.reservedSlots.has(serverName))return"already_held";if(this.clientBudget===void 0||this.mode==="off"){return"reserved"}if(this.mode==="enforce"&&this.reservedSlots.size>=this.clientBudget){return"refused"}this.reservedSlots.add(serverName);this.evaluateState();return"reserved"}release(serverName){const had=this.reservedSlots.delete(serverName);if(had)this.evaluateState();return had}recordRefusal(serverName,transport){if(this.mode!=="enforce")return;this.pendingRefusalNames.add(serverName);this.pendingRefusalTransports.set(serverName,transport);debugLogger4.warn(`MCP server '${serverName}' refused at pool acquire (budget exhausted, budget=${this.clientBudget}, mode=${this.mode})`);if(this.bulkPassDepth===0){this.flushRefusedBatch()}}beginBulkPass(){if(this.bulkPassDepth===0){this.lastRefusedServerNames=[]}this.bulkPassDepth+=1}endBulkPass(){if(this.bulkPassDepth===0){debugLogger4.warn("WorkspaceMcpBudget.endBulkPass called without matching beginBulkPass; ignoring");return}this.bulkPassDepth-=1;if(this.bulkPassDepth>0)return;this.flushRefusedBatch()}flushRefusedBatch(){if(this.pendingRefusalNames.size===0)return;if(this.clientBudget===void 0||this.mode!=="enforce"){this.pendingRefusalNames.clear();this.pendingRefusalTransports.clear();return}const refusedServers=[];const names=[];for(const name of this.pendingRefusalNames){const transport=this.pendingRefusalTransports.get(name)??"unknown";refusedServers.push({name,transport,reason:"budget_exhausted"});names.push(name)}this.lastRefusedServerNames=Object.freeze(names);this.pendingRefusalNames.clear();this.pendingRefusalTransports.clear();if(this.onEvent){try{this.onEvent({kind:"refused_batch",refusedServers,budget:this.clientBudget,liveCount:this.reservedSlots.size,reservedCount:this.reservedSlots.size,mode:"enforce"})}catch(err){debugLogger4.error(`WorkspaceMcpBudget refused_batch event delivery failed: ${err instanceof Error?err.message:String(err)}`)}}}evaluateState(){if(this.mode==="off"||this.clientBudget===void 0)return;const ratio=this.reservedSlots.size/this.clientBudget;if(this.warnArmed&&ratio>=MCP_BUDGET_WARN_FRACTION){this.warnArmed=false;debugLogger4.info(`MCP workspace budget warning fired (ratio=${ratio.toFixed(2)}, reservedCount=${this.reservedSlots.size}, budget=${this.clientBudget}, mode=${this.mode})`);if(this.onEvent){try{this.onEvent({kind:"budget_warning",liveCount:this.reservedSlots.size,reservedCount:this.reservedSlots.size,budget:this.clientBudget,thresholdRatio:MCP_BUDGET_WARN_FRACTION,mode:this.mode})}catch(err){debugLogger4.error(`WorkspaceMcpBudget budget_warning event delivery failed: ${err instanceof Error?err.message:String(err)}`)}}}else if(!this.warnArmed&&ratio<MCP_BUDGET_REARM_FRACTION){this.warnArmed=true;debugLogger4.info(`MCP workspace budget warning re-armed (ratio=${ratio.toFixed(2)}, budget=${this.clientBudget}; next 75% crossing will fire)`)}}};init_esbuild_shims();function preservePlaceholders(value,resolved,original){if(typeof original==="string"&&value===resolved)return original;if(Array.isArray(value)&&Array.isArray(resolved)&&Array.isArray(original)){return value.map((entry,index)=>preservePlaceholders(entry,resolved[index],original[index]))}if(value&&resolved&&original&&typeof value==="object"&&!Array.isArray(value)&&typeof resolved==="object"&&!Array.isArray(resolved)&&typeof original==="object"&&!Array.isArray(original)){return Object.fromEntries(Object.entries(value).map(([key,entry])=>[key,preservePlaceholders(entry,resolved[key],original[key])]))}return value}__name(preservePlaceholders,"preservePlaceholders");function preserveModelProviderPlaceholders(models,provider,resolvedProviders,rawProviders,mapping){const pairs=Object.entries(resolvedProviders).flatMap(([providerId,entries])=>{if(!Array.isArray(entries))return[];return entries.flatMap((entry,index)=>{const resolved=provider==="openai"?getModelsForProviderProtocol({[providerId]:[entry]},"openai",mapping)[0]:providerId===provider?entry:void 0;return resolved?[{providerId,resolved,source:entry,raw:rawProviders[providerId]?.[index]??entry}]:[]})});return models.map(model=>{const matches=pairs.filter(({resolved})=>resolved.id===model.id&&resolved.baseUrl===model.baseUrl&&tryResolveModelProtocol(provider,resolved,mapping)===tryResolveModelProtocol(provider,model,mapping));const sourceMatches=matches.filter(pair=>pair.providerId===matches[0]?.providerId);if(sourceMatches.length>1&&sourceMatches.some(pair=>JSON.stringify(pair.raw)!==JSON.stringify(pair.source))){throw new Error("Cannot preserve placeholders in an ambiguous model configuration. Remove duplicate model entries first.")}const match=matches[0];return match?preservePlaceholders(model,match.resolved,match.raw):model})}__name(preserveModelProviderPlaceholders,"preserveModelProviderPlaceholders");init_esbuild_shims();init_esbuild_shims();var DISCOVERY_TIMEOUT_MS=5e3;var DISCOVERY_MAX_BYTES=1024*1024;var MAX_MODEL_ID_LENGTH=256;var UNSAFE_MODEL_ID_CHARS=/[,\p{C}\p{Zl}\p{Zp}]/u;function readModels(value){if(!value||typeof value!=="object"||!("data"in value)){return null}const data=value.data;if(!Array.isArray(data)){return null}const models=[];const seen=new Set;for(const item of data){if(!item||typeof item!=="object"||!("id"in item)){return null}const id=item.id;if(typeof id!=="string"){return null}const trimmedId=id.trim();if(trimmedId&&trimmedId.length<=MAX_MODEL_ID_LENGTH&&!UNSAFE_MODEL_ID_CHARS.test(trimmedId)&&!seen.has(trimmedId)){seen.add(trimmedId);const created=item.created;const creationTime=typeof created==="number"&&Number.isFinite(created)&&created>=0?created:void 0;models.push({id:trimmedId,...creationTime===void 0?{}:{created:creationTime}})}}return models.length>0?models:null}__name(readModels,"readModels");function mergeModelSpecs(discoveredModels,staticModels){const staticModelsById=new Map(staticModels.map(model=>[model.id,model]));const orderedModels=[...discoveredModels];if(orderedModels.every(model=>model.created!==void 0)){orderedModels.sort((left,right)=>(right.created??0)-(left.created??0))}return orderedModels.map(({id})=>staticModelsById.get(id)??{id})}__name(mergeModelSpecs,"mergeModelSpecs");async function discoverProviderModels({baseUrl,apiKey,staticModels,signal}){const normalizedBaseUrl=baseUrl.trim();const normalizedApiKey=apiKey.trim();if(!normalizedBaseUrl||!normalizedApiKey){return null}try{const modelsUrl=`${normalizedBaseUrl.replace(/\/+$/,"")}/models`;const result=await fetchWithPolicy(modelsUrl,{timeoutMs:DISCOVERY_TIMEOUT_MS,maxBytes:DISCOVERY_MAX_BYTES,maxRedirects:2,headers:{Accept:"application/json",Authorization:`Bearer ${normalizedApiKey}`},signal});if(result.kind!=="response"||result.status<200||result.status>=300){return null}const models=readModels(JSON.parse(result.body.toString("utf8")));return models?mergeModelSpecs(models,staticModels):null}catch{return null}}__name(discoverProviderModels,"discoverProviderModels");init_esbuild_shims();var IMAGE_CAPABILITY=Object.freeze({autoHandlesWrongModel:true,maxBytes:VISION_BRIDGE_MAX_IMAGE_BASE64_BYTES,maxImagesPerTurn:VISION_BRIDGE_MAX_IMAGES});init_esbuild_shims();var debugLogger5=createDebugLogger("SESSION_RECAP");var RECENT_MESSAGE_WINDOW=30;var RECAP_SYSTEM_PROMPT=`You generate session recaps for a programming assistant CLI.
|
|
4
4
|
|
|
5
5
|
The user stepped away and is coming back. Recap in under 40 words, 1-2 plain sentences, no markdown. Lead with the overall goal and current task, then the one next action. Skip root-cause narrative, fix internals, secondary to-dos, and em-dash tangents.
|
|
6
6
|
|