gerege-cli 0.26.6 → 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/chunks/{MaxSizedBox-QCIXIS4P.js → MaxSizedBox-LSNOJEKM.js} +1 -1
- package/chunks/{StandaloneSessionPicker-BAFAIRT7.js → StandaloneSessionPicker-KSYGPMEV.js} +1 -1
- package/chunks/{acp-subagent-executor-TPVXURLW.js → acp-subagent-executor-NSW2MFUI.js} +1 -1
- package/chunks/{acpAgent-67UN66PB.js → acpAgent-3DTOHTDM.js} +3 -3
- package/chunks/{advisor-SAXMI4QZ.js → advisor-7JGQPS7X.js} +1 -1
- package/chunks/{agent-KV7BXY6C.js → agent-PNKQJGDO.js} +1 -1
- package/chunks/{agent-headless-FQX3JGG6.js → agent-headless-7D33X7QQ.js} +1 -1
- package/chunks/{agent-host-client-L5EHC4AC.js → agent-host-client-3R2MAUVE.js} +1 -1
- package/chunks/{agent-host-connections-EDBMCVQF.js → agent-host-connections-2D7DECAE.js} +1 -1
- package/chunks/{anthropicContentGenerator-V7TX2NXP.js → anthropicContentGenerator-MGTJJGEQ.js} +1 -1
- package/chunks/{autofix-pr-WP34NYHL.js → autofix-pr-OIHHZSPQ.js} +1 -1
- package/chunks/{batch-XFVQ4BLM.js → batch-6UDAMPAA.js} +1 -1
- package/chunks/{bridge-AE7AFEXB.js → bridge-QXVXPNJ6.js} +1 -1
- package/chunks/{channel-settings-store-X63P5OVT.js → channel-settings-store-P4W4R5SJ.js} +1 -1
- package/chunks/{chunk-RXN7DUMP.js → chunk-2J2BQ3PL.js} +2 -2
- package/chunks/{chunk-7453BHJO.js → chunk-2LMSDH6P.js} +1 -1
- package/chunks/{chunk-32XHDDIA.js → chunk-3EZ5GCUT.js} +1 -1
- package/chunks/{chunk-AYVCT5FF.js → chunk-3ICJI5KW.js} +1 -1
- package/chunks/{chunk-VRKYBH5G.js → chunk-4A663FE6.js} +5 -5
- package/chunks/{chunk-DA6LOBSB.js → chunk-4AKTP4MM.js} +1 -1
- package/chunks/{chunk-T53VMDXH.js → chunk-4LC4INFI.js} +1 -1
- package/chunks/{chunk-65ME4BOH.js → chunk-4QOVM2LL.js} +1 -1
- package/chunks/{chunk-MYV7GY3H.js → chunk-4VR4DUUD.js} +1 -1
- package/chunks/{chunk-GRAECADD.js → chunk-4W27Z3OL.js} +1 -1
- package/chunks/{chunk-B37YY4XU.js → chunk-53IB4U4E.js} +1 -1
- package/chunks/{chunk-OK7LBM5G.js → chunk-5R2JIZID.js} +1 -1
- package/chunks/{chunk-I6PUY2T3.js → chunk-5TWAP4OG.js} +1 -1
- package/chunks/{chunk-CBE6ZIHU.js → chunk-6JAXAFX7.js} +1 -1
- package/chunks/{chunk-OOJ2AQT3.js → chunk-6WV5RKYB.js} +1 -1
- package/chunks/{chunk-ELDZ4MNL.js → chunk-6YFNUVJR.js} +1 -1
- package/chunks/{chunk-3W32X2DH.js → chunk-7HFFTOAD.js} +1 -1
- package/chunks/{chunk-YH2XRWRF.js → chunk-ATTJQLQV.js} +1 -1
- package/chunks/{chunk-T5DKF33F.js → chunk-BIPPD7W6.js} +1 -1
- package/chunks/{chunk-CF6SZJNP.js → chunk-BVV7UXES.js} +1 -1
- package/chunks/{chunk-CGDFZEER.js → chunk-BY46PCWY.js} +1 -1
- package/chunks/{chunk-AEZYXPFS.js → chunk-CDKBM72V.js} +1 -1
- package/chunks/{chunk-OU7CEG7Q.js → chunk-CK3OKTTL.js} +1 -1
- package/chunks/{chunk-FKL3V5BO.js → chunk-DEJ47KJE.js} +1 -1
- package/chunks/{chunk-FEP6W4NJ.js → chunk-DQQN2HOP.js} +1 -1
- package/chunks/{chunk-SKGJ26HQ.js → chunk-DTX2OVQW.js} +1 -1
- package/chunks/{chunk-EXIFPXMB.js → chunk-DVUKYOCJ.js} +1 -1
- package/chunks/{chunk-FKZ46GKL.js → chunk-E3KWSRJN.js} +1 -1
- package/chunks/{chunk-BAUMVH4Q.js → chunk-EEPNACXJ.js} +1 -1
- package/chunks/{chunk-76FSYQTG.js → chunk-F5SLLEJY.js} +1 -1
- package/chunks/{chunk-IZ5MWA6E.js → chunk-F7622ZRQ.js} +1 -1
- package/chunks/{chunk-TB4AUC2L.js → chunk-FKUDVIME.js} +1 -1
- package/chunks/{chunk-SP6CQ3MO.js → chunk-FRVXSKL4.js} +1 -1
- package/chunks/{chunk-XISR37DQ.js → chunk-FTF2NFLB.js} +1 -1
- package/chunks/{chunk-NONBHCXP.js → chunk-G4MWPXNY.js} +1 -1
- package/chunks/{chunk-JRTOPEM3.js → chunk-GA35LMSX.js} +1 -1
- package/chunks/{chunk-GHIFIXNX.js → chunk-H34KVVI4.js} +1 -1
- package/chunks/{chunk-AFO5ER23.js → chunk-H5EXNXGW.js} +1 -1
- package/chunks/{chunk-ZENMAISJ.js → chunk-HJLRKM3W.js} +1 -1
- package/chunks/{chunk-BCI62WSL.js → chunk-HVP4UF2Q.js} +1 -1
- package/chunks/{chunk-AEKEZRIU.js → chunk-HXTYFGSQ.js} +1 -1
- package/chunks/{chunk-KJGRCIVY.js → chunk-IIHUDJX7.js} +1 -1
- package/chunks/{chunk-RSLTOIG5.js → chunk-IQMKQKKD.js} +2 -2
- package/chunks/{chunk-JWNKPINR.js → chunk-ISQMHOCC.js} +1 -1
- package/chunks/{chunk-OJ4K62S2.js → chunk-IY7M5HKF.js} +1 -1
- package/chunks/{chunk-LBLLWAKK.js → chunk-IZXHCHJD.js} +1 -1
- package/chunks/{chunk-NVOI6UDQ.js → chunk-JHC22BZH.js} +1 -1
- package/chunks/{chunk-BPFFRPWE.js → chunk-K7GN4CMV.js} +6 -6
- package/chunks/{chunk-N7PWZBXV.js → chunk-L7LO3YRT.js} +1 -1
- package/chunks/{chunk-MGATL4OA.js → chunk-LY4XTBL4.js} +1 -1
- package/chunks/{chunk-JEDL4IKF.js → chunk-LYFRGP42.js} +1 -1
- package/chunks/{chunk-G6DALGGS.js → chunk-MDCA4I63.js} +1 -1
- package/chunks/{chunk-W5Z4BWWA.js → chunk-MS2XCBPP.js} +1 -1
- package/chunks/{chunk-GBSRWT7J.js → chunk-MXZXQUVP.js} +1 -1
- package/chunks/{chunk-VD2GSW64.js → chunk-N4ZQC5HB.js} +1 -1
- package/chunks/{chunk-2LWJGXTW.js → chunk-N6EFYQ7M.js} +1 -1
- package/chunks/{chunk-P62S5JGM.js → chunk-NHPKD7LY.js} +1 -1
- package/chunks/{chunk-W66WWTOP.js → chunk-NPAENNRO.js} +1 -1
- package/chunks/{chunk-EYPLBTMI.js → chunk-NYBYDW6R.js} +1 -1
- package/chunks/{chunk-7RNOS7R4.js → chunk-O3TUZQP4.js} +1 -1
- package/chunks/{chunk-JH3V5SPA.js → chunk-OZFZBGZG.js} +1 -1
- package/chunks/{chunk-QDCUR3JB.js → chunk-P2MZZMCS.js} +1 -1
- package/chunks/{chunk-KZNYALFU.js → chunk-PMBI46K4.js} +1 -1
- package/chunks/{chunk-2TAJ5STJ.js → chunk-Q5RRVBTY.js} +1 -1
- package/chunks/{chunk-H3IR3GIE.js → chunk-QHYSRPQR.js} +1 -1
- package/chunks/{chunk-NA4ZF2FE.js → chunk-QONPET6Y.js} +2 -2
- package/chunks/{chunk-W2RQIZ6B.js → chunk-QSPXKBUX.js} +1 -1
- package/chunks/{chunk-WGFX3EL3.js → chunk-QTKPC24L.js} +1 -1
- package/chunks/{chunk-BHIDG6VZ.js → chunk-QTVSPQZQ.js} +1 -1
- package/chunks/{chunk-HOG66S6K.js → chunk-QVHDM6N7.js} +1 -1
- package/chunks/{chunk-4NDJKNN6.js → chunk-RT6J7PV4.js} +1 -1
- package/chunks/{chunk-NEKPQLFY.js → chunk-RULGA7WE.js} +2 -2
- package/chunks/{chunk-LTE4N6L3.js → chunk-SAVYMUU3.js} +1 -1
- package/chunks/{chunk-2JGTWRZJ.js → chunk-T3CQ72HC.js} +6 -6
- package/chunks/{chunk-FYBJGRX7.js → chunk-U5YOAOU3.js} +1 -1
- package/chunks/{chunk-EFIRES46.js → chunk-ULLW2AYD.js} +1 -1
- package/chunks/{chunk-MPVQDYPH.js → chunk-UM5KBBYP.js} +1 -1
- package/chunks/{chunk-M6KB5RVD.js → chunk-UVMLWDRU.js} +1 -1
- package/chunks/{chunk-5EXL4TKQ.js → chunk-VK7LOUOJ.js} +1 -1
- package/chunks/{chunk-T2YTHAJW.js → chunk-VUNHJ74J.js} +1 -1
- package/chunks/{chunk-HTAUIJB4.js → chunk-W2CV36HT.js} +1 -1
- package/chunks/{chunk-ET5M5WFN.js → chunk-WCI33URB.js} +1 -1
- package/chunks/{chunk-P3JEEDQZ.js → chunk-WEPC42YR.js} +1 -1
- package/chunks/{chunk-BQZF3UKI.js → chunk-WF7Q3ZSQ.js} +1 -1
- package/chunks/{chunk-GSPGIGO5.js → chunk-WK666FGZ.js} +3 -3
- package/chunks/{chunk-CUP2TNJK.js → chunk-WMLYHZZX.js} +1 -1
- package/chunks/{chunk-2N3NBTYJ.js → chunk-WSI4G7XC.js} +1 -1
- package/chunks/{chunk-U3Q72OGV.js → chunk-WXK7Z45R.js} +1 -1
- package/chunks/{chunk-MTDBCIDA.js → chunk-YWK3E4WJ.js} +1 -1
- package/chunks/{chunk-34HC2AXI.js → chunk-YY4GWNTU.js} +2 -2
- package/chunks/{chunk-UKLXKJKL.js → chunk-ZFOEVHWG.js} +1 -1
- package/chunks/{codex-subagent-executor-OLMGVPVS.js → codex-subagent-executor-GPTKVP7H.js} +1 -1
- package/chunks/{config-utils-OWY5G5Y2.js → config-utils-6B5FHBSF.js} +1 -1
- package/chunks/{contextCommand-IXFUZH65.js → contextCommand-FGRDE3GA.js} +1 -1
- package/chunks/{core-runtime-O4LC4NY3.js → core-runtime-OFEHSKDB.js} +1 -1
- package/chunks/{create-sub-session-6F7C3TMT.js → create-sub-session-D2KEWVHQ.js} +1 -1
- package/chunks/{cron-create-2422NBSJ.js → cron-create-RFGGKTL7.js} +1 -1
- package/chunks/{daemon-git-worktree-guard-EWPQA6NO.js → daemon-git-worktree-guard-AV752IOZ.js} +1 -1
- package/chunks/{daemon-status-provider-FAHOXNFW.js → daemon-status-provider-GHQBRDMC.js} +1 -1
- package/chunks/{daemon-trust-policy-L3DM6AI5.js → daemon-trust-policy-24ENJNTQ.js} +1 -1
- package/chunks/{daemon-trust-policy-monitor-HNPY5KJ4.js → daemon-trust-policy-monitor-NMSQAGWV.js} +1 -1
- package/chunks/{deferred-core-runtime-JF42NQJK.js → deferred-core-runtime-5BAMFFOI.js} +1 -1
- package/chunks/{edit-E5LEI2LL.js → edit-XCECLEH3.js} +1 -1
- package/chunks/{enterPlanMode-3COTUV5V.js → enterPlanMode-SEN2PMRM.js} +1 -1
- package/chunks/{environment-XBBIB3VA.js → environment-CCPQJYKS.js} +1 -1
- package/chunks/{errors-LNMQ7TUK.js → errors-Y6HHUTGK.js} +1 -1
- package/chunks/{execution-tool-QDDKJD2K.js → execution-tool-HADWGMIG.js} +1 -1
- package/chunks/{execution-worker-TXGZRZXE.js → execution-worker-GZS7WOQL.js} +1 -1
- package/chunks/{exitPlanMode-Z7QEMWPE.js → exitPlanMode-76B5HDLT.js} +1 -1
- package/chunks/{fast-path-M6K2RACY.js → fast-path-OEV7LQYV.js} +1 -1
- package/chunks/{glob-N2QT4U7U.js → glob-NLWCQRMS.js} +1 -1
- package/chunks/{goal-tools-CUSQD3DG.js → goal-tools-43XV33BT.js} +1 -1
- package/chunks/{handleAutoUpdate-QF2YQHF6.js → handleAutoUpdate-JDQWGSSP.js} +1 -1
- package/chunks/{i18n-AGOA6MUI.js → i18n-JW6BVEGF.js} +1 -1
- package/chunks/{initializer-FRKYDUSX.js → initializer-UT6JLZ3O.js} +1 -1
- package/chunks/{installationInfo-OKA4WXAS.js → installationInfo-LKWDV3S2.js} +1 -1
- package/chunks/{interactive-mod-session-MWYN5IFK.js → interactive-mod-session-2KWKYVPC.js} +1 -1
- package/chunks/{list-DE7VUIR2.js → list-BKINK3S2.js} +1 -1
- package/chunks/{llm-N3JGJHYC.js → llm-3RWXAVM2.js} +4 -4
- package/chunks/{llm-content-generator-VMUBA7OJ.js → llm-content-generator-MDRBSH73.js} +1 -1
- package/chunks/{loadedSettingsAdapter-5C36OZ7N.js → loadedSettingsAdapter-WWJUKWUN.js} +1 -1
- package/chunks/{local-BE624O3A.js → local-TT4FLCTR.js} +1 -1
- package/chunks/{local-execution-environment-OPGM7Y6L.js → local-execution-environment-OBA6VWYL.js} +1 -1
- package/chunks/{loggingContentGenerator-2MHAI6JR.js → loggingContentGenerator-CK7IKYQH.js} +1 -1
- package/chunks/{loop-wakeup-BDLATBXH.js → loop-wakeup-4MSRX3DY.js} +1 -1
- package/chunks/{manage-memory-BBCEIIWB.js → manage-memory-PX5PZJKZ.js} +1 -1
- package/chunks/{managed-execution-engine-SRFALTCX.js → managed-execution-engine-WMAUR3ZK.js} +1 -1
- package/chunks/{managed-local-serve-ICNAS3E6.js → managed-local-serve-X7REHGB4.js} +1 -1
- package/chunks/{managed-npm-update-CTL6LH5Z.js → managed-npm-update-6HUVAJH7.js} +1 -1
- package/chunks/{managed-runtime-attestation-worker-ZRDWKXCI.js → managed-runtime-attestation-worker-F4AT53M5.js} +1 -1
- package/chunks/{managed-runtime-bootstrap-6NTGZXQL.js → managed-runtime-bootstrap-3BP5JRJX.js} +1 -1
- package/chunks/{managed-runtime-session-worker-RKQBBFR6.js → managed-runtime-session-worker-2PO7J5UK.js} +1 -1
- package/chunks/{managed-runtime-ssh-worker-FCGV6FSW.js → managed-runtime-ssh-worker-4N7EMRSV.js} +1 -1
- package/chunks/{managed-session-authority-C7IW6TJX.js → managed-session-authority-MYOYTUM2.js} +1 -1
- package/chunks/{mcp-VC4CJPE5.js → mcp-5OTEMZ7P.js} +1 -1
- package/chunks/{memory-S6OJA3ZD.js → memory-TNW7RSAV.js} +1 -1
- package/chunks/{model-call-collection-MJZWRQSU.js → model-call-collection-KNTWFZQS.js} +1 -1
- package/chunks/{model-configuration-SKU6L3QI.js → model-configuration-U5C5P5UQ.js} +1 -1
- package/chunks/{modelConfigUtils-TJCB6NXT.js → modelConfigUtils-R4KFI2WK.js} +1 -1
- package/chunks/{monitor-M3PNLCYP.js → monitor-RD2PFK42.js} +1 -1
- package/chunks/{nonInteractiveCli-MR7JLAWU.js → nonInteractiveCli-QQ72HZSH.js} +1 -1
- package/chunks/{nonInteractiveToolExecutor-YKA6JMTY.js → nonInteractiveToolExecutor-QPQYR6IS.js} +1 -1
- package/chunks/{notebook-edit-ENTFB5D7.js → notebook-edit-YLRN3UZT.js} +1 -1
- package/chunks/{omni-6YBX4R6K.js → omni-CUJ52EW5.js} +1 -1
- package/chunks/{openaiContentGenerator-XRXX33FY.js → openaiContentGenerator-6B5MAU54.js} +1 -1
- package/chunks/{openaiResponsesContentGenerator-L6ONEHMR.js → openaiResponsesContentGenerator-I245I3R7.js} +1 -1
- package/chunks/{pidfile-XR4JF2Z6.js → pidfile-P2HIGAUA.js} +1 -1
- package/chunks/{processUtils-GQYNJRBJ.js → processUtils-JSKN5UGS.js} +1 -1
- package/chunks/{prompt-terminal-ledger-7BM7YDLG.js → prompt-terminal-ledger-F5TSXVGU.js} +1 -1
- package/chunks/{qwenContentGenerator-QSA32XEL.js → qwenContentGenerator-IEDZONWG.js} +1 -1
- package/chunks/{reactive-degrade-TFNBAAPZ.js → reactive-degrade-FYZBJCF6.js} +1 -1
- package/chunks/{read-file-VD7OFO2E.js → read-file-VNZNSD6X.js} +1 -1
- package/chunks/{resumeHistoryUtils-2B4KPI7G.js → resumeHistoryUtils-IDPE6N2N.js} +1 -1
- package/chunks/{review-C365WGCW.js → review-TBJRZWTD.js} +1 -1
- package/chunks/{ripGrep-D7WPMBXR.js → ripGrep-4W5B5FOE.js} +1 -1
- package/chunks/{run-qwen-serve-NZWQHWQA.js → run-qwen-serve-44X262G5.js} +1 -1
- package/chunks/{runtime-J6SPBSCS.js → runtime-6H6LKD73.js} +1 -1
- package/chunks/{sandboxConfig-QS2XBPZG.js → sandboxConfig-SQXDRGVN.js} +1 -1
- package/chunks/{scheduled-tasks-YNNIOOPM.js → scheduled-tasks-62IZKHJG.js} +1 -1
- package/chunks/{scheduler-KCMSPHON.js → scheduler-QUCXJYRL.js} +1 -1
- package/chunks/{search-memory-EUBJ7IAV.js → search-memory-TC2Z34QN.js} +1 -1
- package/chunks/{send-message-CWWZUPSK.js → send-message-TFZX7KI7.js} +1 -1
- package/chunks/{serve-4CB4BWJ5.js → serve-WSICDFGG.js} +1 -1
- package/chunks/{server-JNANUIGC.js → server-GYYVTNGY.js} +3 -3
- package/chunks/{session-3LQLXPUA.js → session-KF3O23ZJ.js} +1 -1
- package/chunks/{session-attachments-root-BWIVWFHJ.js → session-attachments-root-7HFUSONH.js} +1 -1
- package/chunks/{session-execution-engine-selector-5OLRX57L.js → session-execution-engine-selector-NVILT6BR.js} +1 -1
- package/chunks/{session-pr-refresh-RLF3EXS3.js → session-pr-refresh-3KDFTDEV.js} +1 -1
- package/chunks/{sessionService-U7ACD2HP.js → sessionService-XRTFLPDW.js} +1 -1
- package/chunks/{settings-FTGWYTUH.js → settings-QPPK6WXE.js} +1 -1
- package/chunks/{shell-E4RENYQC.js → shell-WYQDZWL7.js} +1 -1
- package/chunks/{skill-OLNPHRWB.js → skill-FYPT6AU7.js} +1 -1
- package/chunks/{skill-settings-R2BV2GEK.js → skill-settings-OGFI5KZF.js} +1 -1
- package/chunks/{spawnChannel-LOPAR5T2.js → spawnChannel-ANOOVPG7.js} +1 -1
- package/chunks/{standalone-update-IGDX2RGN.js → standalone-update-45WTDY4E.js} +1 -1
- package/chunks/{start-opentui-ui-33QLBNRC.js → start-opentui-ui-TL5WK33V.js} +1 -1
- package/chunks/{startInteractiveUI-RQKHD7MM.js → startInteractiveUI-N2IREVBM.js} +1 -1
- package/chunks/{team-create-HAVKHNU5.js → team-create-R77PRZ5U.js} +1 -1
- package/chunks/{team-plan-approval-7MCQX67C.js → team-plan-approval-6DCRKB5I.js} +1 -1
- package/chunks/{terminal-image-renderer-XT5JVEO6.js → terminal-image-renderer-TB7EX2WW.js} +1 -1
- package/chunks/{theme-manager-DR5EYGLT.js → theme-manager-RQDXJGVR.js} +1 -1
- package/chunks/{tool-call-LZHZ5RVH.js → tool-call-LVB4NCDT.js} +1 -1
- package/chunks/{tool-result-media-XCXCF4YC.js → tool-result-media-LRBB2KS6.js} +1 -1
- package/chunks/{tool-search-K6S3ON7M.js → tool-search-OG73QAQZ.js} +1 -1
- package/chunks/{total-session-admission-LGSS2VWS.js → total-session-admission-A4CUF6AD.js} +1 -1
- package/chunks/{trustedFolders-IIR2UZRL.js → trustedFolders-LSGOYTU2.js} +1 -1
- package/chunks/{update-relaunch-WVIFX5CN.js → update-relaunch-OGC6BZO7.js} +1 -1
- package/chunks/{updateCheck-CMEWLLZJ.js → updateCheck-7J3GXTER.js} +1 -1
- package/chunks/{upload-config-TCCFCNCD.js → upload-config-ML5XEJIF.js} +1 -1
- package/chunks/{useAutoAcceptIndicator-5RTTH3OW.js → useAutoAcceptIndicator-6DH6GQ2X.js} +1 -1
- package/chunks/{validateNonInterActiveAuth-AO336KDX.js → validateNonInterActiveAuth-KJDAGZCM.js} +1 -1
- package/chunks/{version-JYWKKMNP.js → version-7JN2YXL2.js} +1 -1
- package/chunks/{web-fetch-HWTAWXFM.js → web-fetch-42ZR4FEZ.js} +1 -1
- package/chunks/{web-search-HAI5LW3G.js → web-search-74NLPMZJ.js} +1 -1
- package/chunks/{workflow-BZ2YFGF6.js → workflow-WNPHX42I.js} +1 -1
- package/chunks/{workflow-ancestor-trust-26TFXFPO.js → workflow-ancestor-trust-HGF6G7LQ.js} +1 -1
- package/chunks/{workspace-agents-DLI4JQJZ.js → workspace-agents-3YFBFAK3.js} +1 -1
- package/chunks/{workspace-providers-status-64C7DJZU.js → workspace-providers-status-EPJI6KRV.js} +1 -1
- package/chunks/{workspace-recovery-worker-IFRT3KKP.js → workspace-recovery-worker-T3FK5YOD.js} +1 -1
- package/chunks/{workspace-registration-store-MYKJM2SK.js → workspace-registration-store-VEXYBDMA.js} +1 -1
- package/chunks/{workspace-registry-GZJRONAY.js → workspace-registry-NRZYTP2X.js} +1 -1
- package/chunks/{workspace-runtime-coordinator-44KW6HSN.js → workspace-runtime-coordinator-USNSTP2V.js} +1 -1
- package/chunks/{workspace-service-YHTSZYYD.js → workspace-service-USATWO56.js} +1 -1
- package/chunks/{workspace-skills-status-NEB62X24.js → workspace-skills-status-M5JTSFDL.js} +1 -1
- package/chunks/{workspace-trust-reconciler-HZLOOZWM.js → workspace-trust-reconciler-ZUZ2O5WC.js} +1 -1
- package/chunks/{write-file-HD5LHXGL.js → write-file-UMJVKE4S.js} +1 -1
- package/chunks/{zoom-image-W4BMRC5T.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 +11 -0
- package/package.json +1 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{DEFAULT_RING_SIZE,EVENT_SCHEMA_VERSION,EventBus,isSummaryReplayEvent,logEventSizingFailed,mcpAppTextFallback,serializedBridgeEventByteLength,summarizeReplay,summarizeReplayEvent}from"./chunk-BWQ5AIEA.js";import{JOURNAL_GROWTH_HARD_CAP_BYTES,normalizeCompactedReplayMaxBytes,normalizeJournalGrowthPoolBytes,normalizeMaxJournalBytes,normalizeMaxJournalEvents}from"./chunk-WDR5XP3Y.js";import{MCP_RESTART_SERVER_DEADLINE_MS}from"./chunk-IFPLGH5C.js";import{ACTIVE_WORK_CLOSE_IF_UNHELD_PARAM,ACTIVE_WORK_CLOSE_TIMEOUT_MS,ACTIVE_WORK_HEARTBEAT_INTERVAL_MS,ACTIVE_WORK_HEARTBEAT_META_KEY,ACTIVE_WORK_HEARTBEAT_VERSION,ACTIVE_WORK_HOLD_CATEGORIES,ACTIVE_WORK_MAX_SESSION_HOLDS,ACTIVE_WORK_MAX_SNAPSHOT_SESSIONS,ACTIVE_WORK_NOTIFICATION_METHOD,ACTIVE_WORK_STALE_INTERVALS,CHANNEL_LIVENESS_META_KEY,CHANNEL_LIVENESS_VERSION,CHANNEL_OUTPUT_MODE_META_KEY,CHANNEL_PROMPT_META_KEY,CHANNEL_STARTUP_PROFILE_META_KEY,CHANNEL_STARTUP_PROFILE_VERSION,DAEMON_ATTACHMENT_CONTEXT_META_KEY,DAEMON_ATTACHMENT_REFERENCES_META_KEY,DAEMON_CHANNEL_DELIVERY_META_KEY,DAEMON_INPUT_ANNOTATIONS_META_KEY,DAEMON_MODEL_PROMPT_META_KEY,DAEMON_PERMISSION_CANCEL_REASON_META_KEY,DAEMON_PROMPT_DISPLAY_TEXT_META_KEY,DAEMON_RESTORE_ASK_USER_QUESTION_META_KEY,DAEMON_SUBMITTED_PROMPT_META_KEY,DAEMON_SUPPRESS_RESTORE_ASK_USER_QUESTION_META_KEY,DAEMON_SUPPRESS_WORKTREE_CONTEXT_RESTORE_META_KEY,IMAGE_ONLY_PROMPT_TEXT,LOAD_REPLAY_BULK_MODE,LOAD_REPLAY_HIDE_INHERITED_META_KEY,LOAD_REPLAY_MAX_UPDATES,LOAD_REPLAY_META_KEY,LOAD_REPLAY_MODE_META_KEY,LOAD_REPLAY_PAGE_SIZE_META_KEY,LOAD_REPLAY_VERSION,MID_TURN_QUEUE_DRAIN_METHOD,MID_TURN_RECONCILIATION_RING_SIZE,MID_TURN_SEND_NOW_METHOD,PROMPT_CANCEL_METHOD,PROMPT_CANCEL_REASON_META_KEY,REQUESTED_SESSION_ID_META_KEY,SESSION_INITIALIZATION_DEADLINE_META_KEY,SESSION_INITIALIZATION_TIMEOUT_ERROR_KIND,SESSION_MODEL_PERSIST_DEFAULT_META_KEY,SUBMITTED_PROMPT_META_KEY,TODO_STOP_GUARD_CONTINUATION_CLAIM_METHOD,TODO_STOP_GUARD_QUEUE_RELEASE_METHOD,USER_CANCEL_ABORT_REASON,WORKTREE_MCP_DEFER_META_KEY,activeWorkCloseRetryDelayMs,clampActiveWorkIntervalMs,getPromptCancelAbortReason,isValidTrustedModelPrompt,parseBackgroundNotificationTurn,sessionCloseDrainBudgetMs}from"./chunk-WBDNGVHU.js";import{channelFactoryForwardsChildEnv,defaultSpawnChannelFactory}from"./chunk-BC4C6F32.js";import{BridgeChannelClosedError,BridgeTimeoutError,SERVE_CONTROL_EXT_METHODS,SERVE_STATUS_EXT_METHODS,STATUS_SCHEMA_VERSION,SessionRestoreTimeoutError,createIdleWorkspaceExtensionsStatus,createIdleWorkspaceHooksStatus}from"./chunk-LUDNUVSA.js";import{BranchWhilePromptActiveError,BridgeChannelQuarantinedError,CancelSentinelCollisionError,CdWhilePromptActiveError,InvalidClientIdError,InvalidPermissionOptionError,InvalidRewindTargetError,InvalidSessionMetadataError,InvalidSessionScopeError,ManagedSessionBranchUnsupportedError,McpAuthenticationInProgressError,PermissionForbiddenError,PromptDeadlineExceededError,PromptQueueFullError,RequestedSessionIdRejectedError,RestoreInProgressError,SessionBusyError,SessionLimitExceededError,SessionNotFoundError,SessionResetPendingError,SessionShellClientRequiredError,SessionShellDisabledError,StandaloneSessionSpawnError,WorkspaceChangePartiallyAppliedError,WorkspaceDrainingError,WorkspaceMismatchError,WorkspaceRuntimeStopError,isNotCurrentlyGeneratingCancelError}from"./chunk-VTZZXEWA.js";import{canonicalizeWorkspace,translateAndCheckAbsoluteWorkspacePath}from"./chunk-L5UULTGF.js";import{CHANNEL_DELIVERY_ERROR_CODES,LIVE_TASK_TOOL_NAMES,MAX_LIVE_SCREEN_CONTEXT_TEXT_CHARS,MAX_LIVE_SPEAK_TO_USER_MESSAGE_CHARS,MAX_SUB_SESSION_NAME_CHARS}from"./chunk-3KZHPZVZ.js";import{EXTERNAL_TOOL_GUARD_READY_META_KEY,EXTERNAL_TOOL_GUARD_REQUIRED_VALUE,isValidExternalToolGuardDenialReason}from"./chunk-NIEO2TBE.js";import{ClientSideConnection,PROTOCOL_VERSION,RequestError}from"./chunk-WSOEJTOC.js";import{PRIVATE_CONVERSATIONS_RUNTIME_ENABLE,PRIVATE_CONVERSATIONS_RUNTIME_ENV}from"./chunk-S7IKHQ6I.js";import{MAX_SUB_SESSION_PROMPT_CHARS}from"./chunk-MD3ZEOBX.js";import{MAX_DIRECTORY_ARTIFACT_DEPTH,MAX_DIRECTORY_ARTIFACT_FILES,collectRecordableWorkspaceFiles,isOfficeDocumentExtension,isRecordableDerivedChild,pathHasSkippedDirectoryComponent}from"./chunk-MZUOREFD.js";import{MAX_CRON_GATE_CHARS,SESSION_PR_LIST_LIMIT,SESSION_PR_URL_MAX_LENGTH,SESSION_TRANSCRIPT_MAX_LIMIT,TURN_RESULT_CODE_TEXT_TRUNCATED,TURN_RESULT_TEXT_MAX_CHARS,TrustGateError,canonicalSessionPrUrl,normalizeTurnResultError,toSessionPrInfo}from"./chunk-2JGTWRZJ.js";import{SESSION_EXECUTION_ENGINE_META_KEY}from"./chunk-YVBHCSZD.js";import{MAX_CRON_TASK_ROUTING_ID_LENGTH,isValidCronTaskRoutingId}from"./chunk-T6W33SET.js";import{isUnverifiableIdentityError,openNoFollow}from"./chunk-QXQGUM3Y.js";import{PUBLISHED_CONTENT_SHA256_METADATA_KEY,SESSION_ARTIFACT_PERSISTENCE_VERSION,WORKSPACE_CONTENT_MTIME_MS_METADATA_KEY,WORKSPACE_CONTENT_SHA256_METADATA_KEY,WORKSPACE_CONTENT_SIZE_BYTES_METADATA_KEY,deleteArtifactSnapshot,getWebPreviewSnapshotId,isAdoptableContentFingerprintKey,isPrototypeMetadataKey,isReservedWorkspaceMetadataKey,metadataBudgetBytes,normalizeSnapshotPayload,retainArtifactSnapshot,sessionArtifactIdentityKey,stableSessionArtifactId}from"./chunk-UQ7IROJH.js";import{SessionSourceError,validateSessionSourceInput}from"./chunk-G5PYYZMM.js";import{APPROVAL_MODES}from"./chunk-JZK2WGXA.js";import{ShellExecutionService}from"./chunk-NMY3PYNO.js";import{DAEMON_TRACEPARENT_META_KEY,DAEMON_TRACESTATE_META_KEY}from"./chunk-FQRF6B65.js";import{getSpecificMimeType}from"./chunk-Y6HHV4LC.js";import{INVOCATION_CONTEXT_META_KEY,PRIVATE_ACP_CAPABILITY_ENV,PRIVATE_PARENT_CAPABILITY_META_KEY}from"./chunk-EFTJIDS3.js";import{REASONING_EFFORT_TIERS}from"./chunk-GOR7FFVE.js";import{Storage}from"./chunk-EPODBRBP.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();init_esbuild_shims();import{inspect}from"node:util";function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord,"isRecord");var LogSafeAcpRequestError=class extends RequestError{constructor(code,message,data,reservePreparedResponse){super(code,message,data);this.reservePreparedResponse=reservePreparedResponse}static{__name(this,"LogSafeAcpRequestError")}toResult(){const result=super.toResult();if("error"in result){Object.defineProperty(result.error,inspect.custom,{configurable:true,value:__name(()=>({code:result.error.code,payloadOmitted:true}),"value")});try{this.reservePreparedResponse?.(result.error)}catch{}}return result}};var MAX_LOG_SAFE_ACP_ERROR_DETAILS_CHARS=1024;var MAX_LOG_SAFE_ACP_ERROR_KIND_CHARS=128;var MAX_LOG_SAFE_ACP_ERROR_HINT_CHARS=512;function logSafeAcpErrorDetails(error){const details=error instanceof Error?error.message:isRecord(error)&&typeof error["message"]==="string"?error["message"]:void 0;if(!details)return void 0;return{details:details.length<=MAX_LOG_SAFE_ACP_ERROR_DETAILS_CHARS?details:`${details.slice(0,MAX_LOG_SAFE_ACP_ERROR_DETAILS_CHARS)}\u2026`}}__name(logSafeAcpErrorDetails,"logSafeAcpErrorDetails");function boundedAcpErrorString(value,maxChars){return value.length<=maxChars?value:`${value.slice(0,maxChars)}\u2026`}__name(boundedAcpErrorString,"boundedAcpErrorString");function logSafeRequestErrorMessage(code){switch(code){case-32700:return"Parse error";case-32600:return"Invalid request";case-32601:return"Method not found";case-32602:return"Invalid params";case-32603:return"Internal error";case-32e3:return"Authentication required";case-32002:return"Resource not found";default:return"ACP client request failed"}}__name(logSafeRequestErrorMessage,"logSafeRequestErrorMessage");function logSafeRequestErrorData(data){if(!isRecord(data)||typeof data["errorKind"]!=="string"){return void 0}const status=data["status"];const hint=data["hint"];return{errorKind:boundedAcpErrorString(data["errorKind"],MAX_LOG_SAFE_ACP_ERROR_KIND_CHARS),...typeof status==="number"&&Number.isFinite(status)?{status}:{},...typeof hint==="string"?{hint:boundedAcpErrorString(hint,MAX_LOG_SAFE_ACP_ERROR_HINT_CHARS)}:{}}}__name(logSafeRequestErrorData,"logSafeRequestErrorData");var AcpInboundHandlerLimitError=class extends Error{constructor(maxActiveHandlers,maxActiveHandlerBytes,requiredBytes,availableBytes){super("ACP inbound handler capacity exceeded");this.maxActiveHandlers=maxActiveHandlers;this.maxActiveHandlerBytes=maxActiveHandlerBytes;this.requiredBytes=requiredBytes;this.availableBytes=availableBytes;this.name="AcpInboundHandlerLimitError"}static{__name(this,"AcpInboundHandlerLimitError")}code="acp_handler_limit_exceeded"};function estimateAcpHandlerBytes(value,limitBytes){let bytes=0;const stack=[value];const seen=new WeakSet;while(stack.length>0){const current=stack.pop();if(current===null){bytes+=4}else if(typeof current==="string"){bytes+=Buffer.byteLength(current)+2}else if(typeof current==="number"){bytes+=24}else if(typeof current==="boolean"){bytes+=5}else if(Array.isArray(current)){if(seen.has(current))return limitBytes+1;seen.add(current);bytes+=2+Math.max(0,current.length-1);if(bytes+current.length>limitBytes)return limitBytes+1;for(let index=current.length-1;index>=0;index--){stack.push(current[index])}}else if(isRecord(current)){if(seen.has(current))return limitBytes+1;seen.add(current);const entries=Object.entries(current);bytes+=2+Math.max(0,entries.length-1);for(const[key,entryValue]of entries){bytes+=Buffer.byteLength(key)+3;stack.push(entryValue)}}else{bytes+=4}if(bytes>limitBytes)return limitBytes+1}return Math.max(1,bytes)}__name(estimateAcpHandlerBytes,"estimateAcpHandlerBytes");var AcpInboundHandlerAdmission=class{constructor(guard){this.guard=guard}static{__name(this,"AcpInboundHandlerAdmission")}activeHandlers=0;activeBytes=0;async run(params,operation){const envelopeBytes=Math.min(2048,this.guard.maxActiveHandlerBytes);const requiredBytes=envelopeBytes+estimateAcpHandlerBytes(params,Math.max(0,this.guard.maxActiveHandlerBytes-envelopeBytes));const availableBytes=Math.max(0,this.guard.maxActiveHandlerBytes-this.activeBytes);if(this.activeHandlers>=this.guard.maxActiveHandlers||requiredBytes>availableBytes){const error=new AcpInboundHandlerLimitError(this.guard.maxActiveHandlers,this.guard.maxActiveHandlerBytes,requiredBytes,availableBytes);this.guard.fail(error);throw error}this.activeHandlers++;this.activeBytes+=requiredBytes;try{return await operation()}finally{this.activeHandlers--;this.activeBytes-=requiredBytes}}};async function withLogSafeAcpError(operation,reservePreparedResponse){try{return await operation()}catch(error){if(error instanceof RequestError){const code=Number.isFinite(error.code)?error.code:-32603;throw new LogSafeAcpRequestError(code,logSafeRequestErrorMessage(code),logSafeRequestErrorData(error.data),reservePreparedResponse)}throw new LogSafeAcpRequestError(-32603,"Internal error",logSafeAcpErrorDetails(error),reservePreparedResponse)}}__name(withLogSafeAcpError,"withLogSafeAcpError");function createLogSafeAcpClient(client,transportGuard){const admission=new AcpInboundHandlerAdmission(transportGuard);const runNotification=__name((params,operation)=>withLogSafeAcpError(()=>admission.run(params,operation)),"runNotification");const runRequest=__name((params,operation)=>withLogSafeAcpError(()=>admission.run(params,async()=>{const result=await operation();transportGuard.reservePreparedResponse(result??null);return result}),transportGuard.reservePreparedResponse),"runRequest");return{requestPermission:__name(params=>runRequest(params,()=>client.requestPermission(params)),"requestPermission"),sessionUpdate:__name(params=>runNotification(params,()=>client.sessionUpdate(params)),"sessionUpdate"),writeTextFile:client.writeTextFile?params=>runRequest(params,()=>client.writeTextFile(params)):void 0,readTextFile:client.readTextFile?params=>runRequest(params,()=>client.readTextFile(params)):void 0,createTerminal:client.createTerminal?params=>runRequest(params,()=>client.createTerminal(params)):void 0,terminalOutput:client.terminalOutput?params=>runRequest(params,()=>client.terminalOutput(params)):void 0,releaseTerminal:client.releaseTerminal?params=>runRequest(params,async()=>await client.releaseTerminal(params)??{}):void 0,waitForTerminalExit:client.waitForTerminalExit?params=>runRequest(params,()=>client.waitForTerminalExit(params)):void 0,killTerminal:client.killTerminal?params=>runRequest(params,async()=>await client.killTerminal(params)??{}):void 0,extMethod:client.extMethod?(method,params)=>runRequest(params,()=>client.extMethod(method,params)):void 0,extNotification:client.extNotification?(method,params)=>runNotification(params,()=>client.extNotification(method,params)):void 0}}__name(createLogSafeAcpClient,"createLogSafeAcpClient");var OUTBOUND_GUARDED_CONNECTION_METHODS=new Set(["initialize","newSession","loadSession","unstable_forkSession","unstable_listSessions","unstable_resumeSession","setSessionMode","unstable_setSessionModel","setSessionConfigOption","authenticate","prompt","cancel","extMethod","extNotification"]);function createOutboundGuardedConnection(connection,transportGuard){const wrappers=new Map;return new Proxy(connection,{get(target,property){const value=Reflect.get(target,property,target);if(typeof value!=="function"||!OUTBOUND_GUARDED_CONNECTION_METHODS.has(property)){return value}let wrapper=wrappers.get(property);if(!wrapper){wrapper=__name(async(...args)=>{const release=transportGuard.reserveOutboundOperation(args);try{return await Reflect.apply(value,target,args)}finally{release()}},"wrapper");wrappers.set(property,wrapper)}return wrapper}})}__name(createOutboundGuardedConnection,"createOutboundGuardedConnection");function createHarnessConnection(client,channel){const rawConnection=new ClientSideConnection(()=>channel.transportGuard?createLogSafeAcpClient(client,channel.transportGuard):client,channel.stream);return channel.transportGuard?createOutboundGuardedConnection(rawConnection,channel.transportGuard):rawConnection}__name(createHarnessConnection,"createHarnessConnection");init_esbuild_shims();function createChannelLifecycle(defaultEngine){const channels=new Map;const aliveChannels=new Set;const starting=new Map;return{get current(){return channels.get(defaultEngine)},get starting(){return starting.get(defaultEngine)},currentFor:__name((engine=defaultEngine)=>channels.get(engine),"currentFor"),startingFor:__name((engine=defaultEngine)=>starting.get(engine),"startingFor"),startups:__name(()=>starting.values(),"startups"),get size(){return aliveChannels.size},has(info){return aliveChannels.has(info)},values(){return aliveChannels.values()},track(info){aliveChannels.add(info)},publish(info){channels.set(info.executionEngine,info)},remove(info){aliveChannels.delete(info);if(channels.get(info.executionEngine)===info)channels.delete(info.executionEngine)},startSpawn(spawn,engine=defaultEngine){let promise=starting.get(engine);if(!promise){promise=spawn();starting.set(engine,promise)}return promise},finishSpawn(engine=defaultEngine){starting.delete(engine)}}}__name(createChannelLifecycle,"createChannelLifecycle");init_esbuild_shims();import{randomBytes,randomUUID}from"node:crypto";init_esbuild_shims();function isRecord2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord2,"isRecord");function createChannelInitializeRequest(privateParentCapability,delegateReadTextFileToClient){return{protocolVersion:PROTOCOL_VERSION,_meta:{[ACTIVE_WORK_HEARTBEAT_META_KEY]:{v:ACTIVE_WORK_HEARTBEAT_VERSION,intervalMs:ACTIVE_WORK_HEARTBEAT_INTERVAL_MS,categories:[...ACTIVE_WORK_HOLD_CATEGORIES]},[CHANNEL_STARTUP_PROFILE_META_KEY]:{v:CHANNEL_STARTUP_PROFILE_VERSION},[CHANNEL_LIVENESS_META_KEY]:{v:CHANNEL_LIVENESS_VERSION},[PRIVATE_PARENT_CAPABILITY_META_KEY]:privateParentCapability},clientCapabilities:{_meta:{"qwen.goalProposals":true,"qwen.mcpAppHost":true},fs:{readTextFile:delegateReadTextFileToClient,writeTextFile:true}},clientInfo:{name:"qwen-serve-bridge",version:"0"}}}__name(createChannelInitializeRequest,"createChannelInitializeRequest");function negotiateChannelCapabilities(response,requireExternalToolGuard){if(requireExternalToolGuard){const guardAck=response._meta?.[EXTERNAL_TOOL_GUARD_READY_META_KEY];if(guardAck!==EXTERNAL_TOOL_GUARD_REQUIRED_VALUE){throw new Error(`ACP child did not acknowledge the required external tool guard (received: ${JSON.stringify(guardAck)}).`)}}let activeWork;const activeWorkCapability=isRecord2(response._meta)?response._meta[ACTIVE_WORK_HEARTBEAT_META_KEY]:void 0;if(isRecord2(activeWorkCapability)&&activeWorkCapability["v"]===ACTIVE_WORK_HEARTBEAT_VERSION){const advertised=activeWorkCapability["categories"];activeWork={intervalMs:clampActiveWorkIntervalMs(activeWorkCapability["intervalMs"]),categories:Array.isArray(advertised)?ACTIVE_WORK_HOLD_CATEGORIES.filter(category=>advertised.includes(category)):[]}}const channelLivenessCapability=isRecord2(response._meta)?response._meta[CHANNEL_LIVENESS_META_KEY]:void 0;return{activeWork,channelLiveness:isRecord2(channelLivenessCapability)&&channelLivenessCapability["v"]===CHANNEL_LIVENESS_VERSION}}__name(negotiateChannelCapabilities,"negotiateChannelCapabilities");init_esbuild_shims();init_esbuild_shims();async function withTimeout(p,ms,label){let timer;const timeoutP=new Promise((_,reject)=>{timer=setTimeout(()=>reject(new BridgeTimeoutError(label,ms)),ms)});try{return await Promise.race([p,timeoutP])}finally{if(timer)clearTimeout(timer)}}__name(withTimeout,"withTimeout");async function terminateChannel(channel,timeoutMs,context){try{await withTimeout(channel.kill(),timeoutMs,`${context} teardown`)}catch(error){try{channel.killSync()}catch(forceError){throw new AggregateError([error,forceError],`ACP channel teardown failed (${context})`)}throw error}}__name(terminateChannel,"terminateChannel");function channelUnavailableReject(channel,context){const unavailable=channel.transportFailed?Promise.race([channel.exited,channel.transportFailed]):channel.exited;const reject=__name(()=>{throw new BridgeChannelClosedError(context)},"reject");return unavailable.then(reject,reject)}__name(channelUnavailableReject,"channelUnavailableReject");init_esbuild_shims();import{performance as performance2}from"node:perf_hooks";var CHANNEL_LIVENESS_INTERVAL_MS=15e3;var CHANNEL_LIVENESS_PROBE_TIMEOUT_MS=1e4;var CHANNEL_LIVENESS_FAILURE_THRESHOLD=2;var CHANNEL_LIVENESS_TIMER_LATE_TOLERANCE_MS=1e3;var CHANNEL_LIVENESS_TIMEOUT_CODE="acp_channel_liveness_timeout";var CHANNEL_LIVENESS_PROTOCOL_ERROR_CODE="acp_channel_liveness_protocol_error";var ChannelLivenessFailure=class extends Error{constructor(code){super(code===CHANNEL_LIVENESS_TIMEOUT_CODE?"ACP channel failed consecutive liveness probes":"ACP channel returned an invalid liveness response");this.code=code;this.name="ChannelLivenessFailure"}static{__name(this,"ChannelLivenessFailure")}};function isValidResponse(response,nonce){return typeof response==="object"&&response!==null&&!Array.isArray(response)&&response["v"]===CHANNEL_LIVENESS_VERSION&&response["nonce"]===nonce}__name(isValidResponse,"isValidResponse");function startChannelLivenessMonitor(options){const now=options.now??(()=>performance2.now());let stopped=false;let timer;let consecutiveTimeouts=0;let nextNonce=0;let resolveStopped;const stoppedOutcome=new Promise(resolve3=>{resolveStopped=resolve3});const isActive=__name(()=>!stopped&&options.isActive(),"isActive");const stop=__name(()=>{stopped=true;if(timer!==void 0){clearTimeout(timer);timer=void 0}resolveStopped({kind:"stopped"})},"stop");const fail=__name(error=>{if(!isActive())return;stop();options.onFailure(error)},"fail");const timerWasLate=__name(expectedAt=>now()>expectedAt+CHANNEL_LIVENESS_TIMER_LATE_TOLERANCE_MS,"timerWasLate");const runProbe=__name(async()=>{if(!isActive())return;const nonce=nextNonce;nextNonce=nonce===Number.MAX_SAFE_INTEGER?0:Math.max(0,nonce+1);const response=Promise.resolve().then(()=>options.probe(nonce)).then(value=>({kind:"response",response:value}),()=>({kind:"rejected"}));let outcome;while(true){const expectedAt=now()+CHANNEL_LIVENESS_PROBE_TIMEOUT_MS;const timeout=new Promise(resolve3=>{timer=setTimeout(()=>{timer=void 0;resolve3(timerWasLate(expectedAt)?{kind:"local_delay"}:{kind:"timeout"})},CHANNEL_LIVENESS_PROBE_TIMEOUT_MS);timer.unref()});outcome=await Promise.race([response,timeout,stoppedOutcome]);if(timer!==void 0){clearTimeout(timer);timer=void 0}if(outcome.kind==="stopped"||!isActive())return;if(outcome.kind!=="local_delay")break;consecutiveTimeouts=0}if(outcome.kind==="response"){if(!isValidResponse(outcome.response,nonce)){fail(new ChannelLivenessFailure(CHANNEL_LIVENESS_PROTOCOL_ERROR_CODE));return}consecutiveTimeouts=0;schedule(CHANNEL_LIVENESS_INTERVAL_MS);return}if(outcome.kind==="rejected"){await Promise.resolve();fail(new ChannelLivenessFailure(CHANNEL_LIVENESS_PROTOCOL_ERROR_CODE));return}consecutiveTimeouts++;if(consecutiveTimeouts>=CHANNEL_LIVENESS_FAILURE_THRESHOLD){fail(new ChannelLivenessFailure(CHANNEL_LIVENESS_TIMEOUT_CODE));return}void runProbe()},"runProbe");function schedule(delayMs){if(!isActive())return;const expectedAt=now()+delayMs;timer=setTimeout(()=>{timer=void 0;if(!isActive())return;if(timerWasLate(expectedAt)){consecutiveTimeouts=0;schedule(CHANNEL_LIVENESS_INTERVAL_MS);return}void runProbe()},delayMs);timer.unref()}__name(schedule,"schedule");schedule(CHANNEL_LIVENESS_INTERVAL_MS);return{stop}}__name(startChannelLivenessMonitor,"startChannelLivenessMonitor");init_esbuild_shims();var MAX_PROFILE_DURATION_MS=6e5;var ATTRIBUTE_PREFIX="qwen-code.daemon.acp_startup";function isRecord3(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}__name(isRecord3,"isRecord");function readDuration(source,key){const value=source[key];return typeof value==="number"&&Number.isFinite(value)&&value>=0&&value<=MAX_PROFILE_DURATION_MS?value:void 0}__name(readDuration,"readDuration");function readDurations(source,keys){if(!isRecord3(source)){return{values:{},complete:false}}const values={};let complete=true;for(const key of keys){const value=readDuration(source,key);if(value===void 0){complete=false}else{values[key]=value}}return{values,complete}}__name(readDurations,"readDurations");function addDurationAttributes(attributes,group,values){for(const[key,value]of Object.entries(values)){if(group==="phase"&&key==="unattributedMs")continue;const attributeKey=key.replace(/[A-Z]/g,letter=>`_${letter.toLowerCase()}`);attributes[`${ATTRIBUTE_PREFIX}.${group}.${attributeKey}`]=value}}__name(addDurationAttributes,"addDurationAttributes");var PHASE_KEYS=["processToProfilerReadyMs","geminiImportMs","argsParseMs","settingsLoadMs","configConstructionMs","appInitializationMs","acpImportMs","bootstrapConfigInitializationMs","transportSetupMs","initializeHandlerMs","unattributedMs"];var CONFIG_KEYS=["extensionsInitialMs","hooksMs","skillsMs","extensionsFinalMs","hierarchicalMemoryMs","toolRegistryMs","ripgrepProbeMs","toolWarmupMs","otherMs"];function getChannelStartupProfileAttributes(response,receivedAtEpochMs,initializeTimeoutMs){if(!isRecord3(response)||!isRecord3(response["_meta"])){return void 0}const profile=response["_meta"][CHANNEL_STARTUP_PROFILE_META_KEY];if(!isRecord3(profile)||profile["v"]!==CHANNEL_STARTUP_PROFILE_VERSION){return void 0}const phases=readDurations(profile["phases"],PHASE_KEYS);const config=readDurations(profile["config"],CONFIG_KEYS);const processToResponseMs=readDuration(profile,"processToResponseMs");const responseBuiltAtEpochMs=profile["responseBuiltAtEpochMs"];const childComplete=profile["complete"]===true;const validResponseEpoch=typeof responseBuiltAtEpochMs==="number"&&Number.isFinite(responseBuiltAtEpochMs)&&responseBuiltAtEpochMs>=0;const effectiveComplete=childComplete&&phases.complete&&config.complete&&processToResponseMs!==void 0&&validResponseEpoch;const attributes={[`${ATTRIBUTE_PREFIX}.profile.version`]:CHANNEL_STARTUP_PROFILE_VERSION,[`${ATTRIBUTE_PREFIX}.profile.complete`]:effectiveComplete};if(processToResponseMs!==void 0){attributes[`${ATTRIBUTE_PREFIX}.child.process_to_response_ms`]=processToResponseMs}if(phases.values["unattributedMs"]!==void 0){attributes[`${ATTRIBUTE_PREFIX}.child.unattributed_ms`]=phases.values["unattributedMs"]}addDurationAttributes(attributes,"phase",phases.values);addDurationAttributes(attributes,"config",config.values);if(validResponseEpoch){const transportMs=receivedAtEpochMs-responseBuiltAtEpochMs;if(Number.isFinite(transportMs)&&transportMs>=0&&transportMs<=initializeTimeoutMs){attributes[`${ATTRIBUTE_PREFIX}.response_transport_ms`]=transportMs}}return attributes}__name(getChannelStartupProfileAttributes,"getChannelStartupProfileAttributes");init_esbuild_shims();function writeStderrLine(message){process.stderr.write(message.endsWith("\n")?message:`${message}
|
|
3
|
+
import{DEFAULT_RING_SIZE,EVENT_SCHEMA_VERSION,EventBus,isSummaryReplayEvent,logEventSizingFailed,mcpAppTextFallback,serializedBridgeEventByteLength,summarizeReplay,summarizeReplayEvent}from"./chunk-BWQ5AIEA.js";import{JOURNAL_GROWTH_HARD_CAP_BYTES,normalizeCompactedReplayMaxBytes,normalizeJournalGrowthPoolBytes,normalizeMaxJournalBytes,normalizeMaxJournalEvents}from"./chunk-WDR5XP3Y.js";import{MCP_RESTART_SERVER_DEADLINE_MS}from"./chunk-IFPLGH5C.js";import{ACTIVE_WORK_CLOSE_IF_UNHELD_PARAM,ACTIVE_WORK_CLOSE_TIMEOUT_MS,ACTIVE_WORK_HEARTBEAT_INTERVAL_MS,ACTIVE_WORK_HEARTBEAT_META_KEY,ACTIVE_WORK_HEARTBEAT_VERSION,ACTIVE_WORK_HOLD_CATEGORIES,ACTIVE_WORK_MAX_SESSION_HOLDS,ACTIVE_WORK_MAX_SNAPSHOT_SESSIONS,ACTIVE_WORK_NOTIFICATION_METHOD,ACTIVE_WORK_STALE_INTERVALS,CHANNEL_LIVENESS_META_KEY,CHANNEL_LIVENESS_VERSION,CHANNEL_OUTPUT_MODE_META_KEY,CHANNEL_PROMPT_META_KEY,CHANNEL_STARTUP_PROFILE_META_KEY,CHANNEL_STARTUP_PROFILE_VERSION,DAEMON_ATTACHMENT_CONTEXT_META_KEY,DAEMON_ATTACHMENT_REFERENCES_META_KEY,DAEMON_CHANNEL_DELIVERY_META_KEY,DAEMON_INPUT_ANNOTATIONS_META_KEY,DAEMON_MODEL_PROMPT_META_KEY,DAEMON_PERMISSION_CANCEL_REASON_META_KEY,DAEMON_PROMPT_DISPLAY_TEXT_META_KEY,DAEMON_RESTORE_ASK_USER_QUESTION_META_KEY,DAEMON_SUBMITTED_PROMPT_META_KEY,DAEMON_SUPPRESS_RESTORE_ASK_USER_QUESTION_META_KEY,DAEMON_SUPPRESS_WORKTREE_CONTEXT_RESTORE_META_KEY,IMAGE_ONLY_PROMPT_TEXT,LOAD_REPLAY_BULK_MODE,LOAD_REPLAY_HIDE_INHERITED_META_KEY,LOAD_REPLAY_MAX_UPDATES,LOAD_REPLAY_META_KEY,LOAD_REPLAY_MODE_META_KEY,LOAD_REPLAY_PAGE_SIZE_META_KEY,LOAD_REPLAY_VERSION,MID_TURN_QUEUE_DRAIN_METHOD,MID_TURN_RECONCILIATION_RING_SIZE,MID_TURN_SEND_NOW_METHOD,PROMPT_CANCEL_METHOD,PROMPT_CANCEL_REASON_META_KEY,REQUESTED_SESSION_ID_META_KEY,SESSION_INITIALIZATION_DEADLINE_META_KEY,SESSION_INITIALIZATION_TIMEOUT_ERROR_KIND,SESSION_MODEL_PERSIST_DEFAULT_META_KEY,SUBMITTED_PROMPT_META_KEY,TODO_STOP_GUARD_CONTINUATION_CLAIM_METHOD,TODO_STOP_GUARD_QUEUE_RELEASE_METHOD,USER_CANCEL_ABORT_REASON,WORKTREE_MCP_DEFER_META_KEY,activeWorkCloseRetryDelayMs,clampActiveWorkIntervalMs,getPromptCancelAbortReason,isValidTrustedModelPrompt,parseBackgroundNotificationTurn,sessionCloseDrainBudgetMs}from"./chunk-WBDNGVHU.js";import{channelFactoryForwardsChildEnv,defaultSpawnChannelFactory}from"./chunk-BC4C6F32.js";import{BridgeChannelClosedError,BridgeTimeoutError,SERVE_CONTROL_EXT_METHODS,SERVE_STATUS_EXT_METHODS,STATUS_SCHEMA_VERSION,SessionRestoreTimeoutError,createIdleWorkspaceExtensionsStatus,createIdleWorkspaceHooksStatus}from"./chunk-LUDNUVSA.js";import{BranchWhilePromptActiveError,BridgeChannelQuarantinedError,CancelSentinelCollisionError,CdWhilePromptActiveError,InvalidClientIdError,InvalidPermissionOptionError,InvalidRewindTargetError,InvalidSessionMetadataError,InvalidSessionScopeError,ManagedSessionBranchUnsupportedError,McpAuthenticationInProgressError,PermissionForbiddenError,PromptDeadlineExceededError,PromptQueueFullError,RequestedSessionIdRejectedError,RestoreInProgressError,SessionBusyError,SessionLimitExceededError,SessionNotFoundError,SessionResetPendingError,SessionShellClientRequiredError,SessionShellDisabledError,StandaloneSessionSpawnError,WorkspaceChangePartiallyAppliedError,WorkspaceDrainingError,WorkspaceMismatchError,WorkspaceRuntimeStopError,isNotCurrentlyGeneratingCancelError}from"./chunk-VTZZXEWA.js";import{canonicalizeWorkspace,translateAndCheckAbsoluteWorkspacePath}from"./chunk-L5UULTGF.js";import{CHANNEL_DELIVERY_ERROR_CODES,LIVE_TASK_TOOL_NAMES,MAX_LIVE_SCREEN_CONTEXT_TEXT_CHARS,MAX_LIVE_SPEAK_TO_USER_MESSAGE_CHARS,MAX_SUB_SESSION_NAME_CHARS}from"./chunk-3KZHPZVZ.js";import{EXTERNAL_TOOL_GUARD_READY_META_KEY,EXTERNAL_TOOL_GUARD_REQUIRED_VALUE,isValidExternalToolGuardDenialReason}from"./chunk-NIEO2TBE.js";import{ClientSideConnection,PROTOCOL_VERSION,RequestError}from"./chunk-WSOEJTOC.js";import{PRIVATE_CONVERSATIONS_RUNTIME_ENABLE,PRIVATE_CONVERSATIONS_RUNTIME_ENV}from"./chunk-S7IKHQ6I.js";import{MAX_SUB_SESSION_PROMPT_CHARS}from"./chunk-MD3ZEOBX.js";import{MAX_DIRECTORY_ARTIFACT_DEPTH,MAX_DIRECTORY_ARTIFACT_FILES,collectRecordableWorkspaceFiles,isOfficeDocumentExtension,isRecordableDerivedChild,pathHasSkippedDirectoryComponent}from"./chunk-MZUOREFD.js";import{MAX_CRON_GATE_CHARS,SESSION_PR_LIST_LIMIT,SESSION_PR_URL_MAX_LENGTH,SESSION_TRANSCRIPT_MAX_LIMIT,TURN_RESULT_CODE_TEXT_TRUNCATED,TURN_RESULT_TEXT_MAX_CHARS,TrustGateError,canonicalSessionPrUrl,normalizeTurnResultError,toSessionPrInfo}from"./chunk-T3CQ72HC.js";import{SESSION_EXECUTION_ENGINE_META_KEY}from"./chunk-YVBHCSZD.js";import{MAX_CRON_TASK_ROUTING_ID_LENGTH,isValidCronTaskRoutingId}from"./chunk-T6W33SET.js";import{isUnverifiableIdentityError,openNoFollow}from"./chunk-QXQGUM3Y.js";import{PUBLISHED_CONTENT_SHA256_METADATA_KEY,SESSION_ARTIFACT_PERSISTENCE_VERSION,WORKSPACE_CONTENT_MTIME_MS_METADATA_KEY,WORKSPACE_CONTENT_SHA256_METADATA_KEY,WORKSPACE_CONTENT_SIZE_BYTES_METADATA_KEY,deleteArtifactSnapshot,getWebPreviewSnapshotId,isAdoptableContentFingerprintKey,isPrototypeMetadataKey,isReservedWorkspaceMetadataKey,metadataBudgetBytes,normalizeSnapshotPayload,retainArtifactSnapshot,sessionArtifactIdentityKey,stableSessionArtifactId}from"./chunk-UQ7IROJH.js";import{SessionSourceError,validateSessionSourceInput}from"./chunk-G5PYYZMM.js";import{APPROVAL_MODES}from"./chunk-JZK2WGXA.js";import{ShellExecutionService}from"./chunk-NMY3PYNO.js";import{DAEMON_TRACEPARENT_META_KEY,DAEMON_TRACESTATE_META_KEY}from"./chunk-FQRF6B65.js";import{getSpecificMimeType}from"./chunk-Y6HHV4LC.js";import{INVOCATION_CONTEXT_META_KEY,PRIVATE_ACP_CAPABILITY_ENV,PRIVATE_PARENT_CAPABILITY_META_KEY}from"./chunk-EFTJIDS3.js";import{REASONING_EFFORT_TIERS}from"./chunk-GOR7FFVE.js";import{Storage}from"./chunk-EPODBRBP.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();init_esbuild_shims();import{inspect}from"node:util";function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord,"isRecord");var LogSafeAcpRequestError=class extends RequestError{constructor(code,message,data,reservePreparedResponse){super(code,message,data);this.reservePreparedResponse=reservePreparedResponse}static{__name(this,"LogSafeAcpRequestError")}toResult(){const result=super.toResult();if("error"in result){Object.defineProperty(result.error,inspect.custom,{configurable:true,value:__name(()=>({code:result.error.code,payloadOmitted:true}),"value")});try{this.reservePreparedResponse?.(result.error)}catch{}}return result}};var MAX_LOG_SAFE_ACP_ERROR_DETAILS_CHARS=1024;var MAX_LOG_SAFE_ACP_ERROR_KIND_CHARS=128;var MAX_LOG_SAFE_ACP_ERROR_HINT_CHARS=512;function logSafeAcpErrorDetails(error){const details=error instanceof Error?error.message:isRecord(error)&&typeof error["message"]==="string"?error["message"]:void 0;if(!details)return void 0;return{details:details.length<=MAX_LOG_SAFE_ACP_ERROR_DETAILS_CHARS?details:`${details.slice(0,MAX_LOG_SAFE_ACP_ERROR_DETAILS_CHARS)}\u2026`}}__name(logSafeAcpErrorDetails,"logSafeAcpErrorDetails");function boundedAcpErrorString(value,maxChars){return value.length<=maxChars?value:`${value.slice(0,maxChars)}\u2026`}__name(boundedAcpErrorString,"boundedAcpErrorString");function logSafeRequestErrorMessage(code){switch(code){case-32700:return"Parse error";case-32600:return"Invalid request";case-32601:return"Method not found";case-32602:return"Invalid params";case-32603:return"Internal error";case-32e3:return"Authentication required";case-32002:return"Resource not found";default:return"ACP client request failed"}}__name(logSafeRequestErrorMessage,"logSafeRequestErrorMessage");function logSafeRequestErrorData(data){if(!isRecord(data)||typeof data["errorKind"]!=="string"){return void 0}const status=data["status"];const hint=data["hint"];return{errorKind:boundedAcpErrorString(data["errorKind"],MAX_LOG_SAFE_ACP_ERROR_KIND_CHARS),...typeof status==="number"&&Number.isFinite(status)?{status}:{},...typeof hint==="string"?{hint:boundedAcpErrorString(hint,MAX_LOG_SAFE_ACP_ERROR_HINT_CHARS)}:{}}}__name(logSafeRequestErrorData,"logSafeRequestErrorData");var AcpInboundHandlerLimitError=class extends Error{constructor(maxActiveHandlers,maxActiveHandlerBytes,requiredBytes,availableBytes){super("ACP inbound handler capacity exceeded");this.maxActiveHandlers=maxActiveHandlers;this.maxActiveHandlerBytes=maxActiveHandlerBytes;this.requiredBytes=requiredBytes;this.availableBytes=availableBytes;this.name="AcpInboundHandlerLimitError"}static{__name(this,"AcpInboundHandlerLimitError")}code="acp_handler_limit_exceeded"};function estimateAcpHandlerBytes(value,limitBytes){let bytes=0;const stack=[value];const seen=new WeakSet;while(stack.length>0){const current=stack.pop();if(current===null){bytes+=4}else if(typeof current==="string"){bytes+=Buffer.byteLength(current)+2}else if(typeof current==="number"){bytes+=24}else if(typeof current==="boolean"){bytes+=5}else if(Array.isArray(current)){if(seen.has(current))return limitBytes+1;seen.add(current);bytes+=2+Math.max(0,current.length-1);if(bytes+current.length>limitBytes)return limitBytes+1;for(let index=current.length-1;index>=0;index--){stack.push(current[index])}}else if(isRecord(current)){if(seen.has(current))return limitBytes+1;seen.add(current);const entries=Object.entries(current);bytes+=2+Math.max(0,entries.length-1);for(const[key,entryValue]of entries){bytes+=Buffer.byteLength(key)+3;stack.push(entryValue)}}else{bytes+=4}if(bytes>limitBytes)return limitBytes+1}return Math.max(1,bytes)}__name(estimateAcpHandlerBytes,"estimateAcpHandlerBytes");var AcpInboundHandlerAdmission=class{constructor(guard){this.guard=guard}static{__name(this,"AcpInboundHandlerAdmission")}activeHandlers=0;activeBytes=0;async run(params,operation){const envelopeBytes=Math.min(2048,this.guard.maxActiveHandlerBytes);const requiredBytes=envelopeBytes+estimateAcpHandlerBytes(params,Math.max(0,this.guard.maxActiveHandlerBytes-envelopeBytes));const availableBytes=Math.max(0,this.guard.maxActiveHandlerBytes-this.activeBytes);if(this.activeHandlers>=this.guard.maxActiveHandlers||requiredBytes>availableBytes){const error=new AcpInboundHandlerLimitError(this.guard.maxActiveHandlers,this.guard.maxActiveHandlerBytes,requiredBytes,availableBytes);this.guard.fail(error);throw error}this.activeHandlers++;this.activeBytes+=requiredBytes;try{return await operation()}finally{this.activeHandlers--;this.activeBytes-=requiredBytes}}};async function withLogSafeAcpError(operation,reservePreparedResponse){try{return await operation()}catch(error){if(error instanceof RequestError){const code=Number.isFinite(error.code)?error.code:-32603;throw new LogSafeAcpRequestError(code,logSafeRequestErrorMessage(code),logSafeRequestErrorData(error.data),reservePreparedResponse)}throw new LogSafeAcpRequestError(-32603,"Internal error",logSafeAcpErrorDetails(error),reservePreparedResponse)}}__name(withLogSafeAcpError,"withLogSafeAcpError");function createLogSafeAcpClient(client,transportGuard){const admission=new AcpInboundHandlerAdmission(transportGuard);const runNotification=__name((params,operation)=>withLogSafeAcpError(()=>admission.run(params,operation)),"runNotification");const runRequest=__name((params,operation)=>withLogSafeAcpError(()=>admission.run(params,async()=>{const result=await operation();transportGuard.reservePreparedResponse(result??null);return result}),transportGuard.reservePreparedResponse),"runRequest");return{requestPermission:__name(params=>runRequest(params,()=>client.requestPermission(params)),"requestPermission"),sessionUpdate:__name(params=>runNotification(params,()=>client.sessionUpdate(params)),"sessionUpdate"),writeTextFile:client.writeTextFile?params=>runRequest(params,()=>client.writeTextFile(params)):void 0,readTextFile:client.readTextFile?params=>runRequest(params,()=>client.readTextFile(params)):void 0,createTerminal:client.createTerminal?params=>runRequest(params,()=>client.createTerminal(params)):void 0,terminalOutput:client.terminalOutput?params=>runRequest(params,()=>client.terminalOutput(params)):void 0,releaseTerminal:client.releaseTerminal?params=>runRequest(params,async()=>await client.releaseTerminal(params)??{}):void 0,waitForTerminalExit:client.waitForTerminalExit?params=>runRequest(params,()=>client.waitForTerminalExit(params)):void 0,killTerminal:client.killTerminal?params=>runRequest(params,async()=>await client.killTerminal(params)??{}):void 0,extMethod:client.extMethod?(method,params)=>runRequest(params,()=>client.extMethod(method,params)):void 0,extNotification:client.extNotification?(method,params)=>runNotification(params,()=>client.extNotification(method,params)):void 0}}__name(createLogSafeAcpClient,"createLogSafeAcpClient");var OUTBOUND_GUARDED_CONNECTION_METHODS=new Set(["initialize","newSession","loadSession","unstable_forkSession","unstable_listSessions","unstable_resumeSession","setSessionMode","unstable_setSessionModel","setSessionConfigOption","authenticate","prompt","cancel","extMethod","extNotification"]);function createOutboundGuardedConnection(connection,transportGuard){const wrappers=new Map;return new Proxy(connection,{get(target,property){const value=Reflect.get(target,property,target);if(typeof value!=="function"||!OUTBOUND_GUARDED_CONNECTION_METHODS.has(property)){return value}let wrapper=wrappers.get(property);if(!wrapper){wrapper=__name(async(...args)=>{const release=transportGuard.reserveOutboundOperation(args);try{return await Reflect.apply(value,target,args)}finally{release()}},"wrapper");wrappers.set(property,wrapper)}return wrapper}})}__name(createOutboundGuardedConnection,"createOutboundGuardedConnection");function createHarnessConnection(client,channel){const rawConnection=new ClientSideConnection(()=>channel.transportGuard?createLogSafeAcpClient(client,channel.transportGuard):client,channel.stream);return channel.transportGuard?createOutboundGuardedConnection(rawConnection,channel.transportGuard):rawConnection}__name(createHarnessConnection,"createHarnessConnection");init_esbuild_shims();function createChannelLifecycle(defaultEngine){const channels=new Map;const aliveChannels=new Set;const starting=new Map;return{get current(){return channels.get(defaultEngine)},get starting(){return starting.get(defaultEngine)},currentFor:__name((engine=defaultEngine)=>channels.get(engine),"currentFor"),startingFor:__name((engine=defaultEngine)=>starting.get(engine),"startingFor"),startups:__name(()=>starting.values(),"startups"),get size(){return aliveChannels.size},has(info){return aliveChannels.has(info)},values(){return aliveChannels.values()},track(info){aliveChannels.add(info)},publish(info){channels.set(info.executionEngine,info)},remove(info){aliveChannels.delete(info);if(channels.get(info.executionEngine)===info)channels.delete(info.executionEngine)},startSpawn(spawn,engine=defaultEngine){let promise=starting.get(engine);if(!promise){promise=spawn();starting.set(engine,promise)}return promise},finishSpawn(engine=defaultEngine){starting.delete(engine)}}}__name(createChannelLifecycle,"createChannelLifecycle");init_esbuild_shims();import{randomBytes,randomUUID}from"node:crypto";init_esbuild_shims();function isRecord2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord2,"isRecord");function createChannelInitializeRequest(privateParentCapability,delegateReadTextFileToClient){return{protocolVersion:PROTOCOL_VERSION,_meta:{[ACTIVE_WORK_HEARTBEAT_META_KEY]:{v:ACTIVE_WORK_HEARTBEAT_VERSION,intervalMs:ACTIVE_WORK_HEARTBEAT_INTERVAL_MS,categories:[...ACTIVE_WORK_HOLD_CATEGORIES]},[CHANNEL_STARTUP_PROFILE_META_KEY]:{v:CHANNEL_STARTUP_PROFILE_VERSION},[CHANNEL_LIVENESS_META_KEY]:{v:CHANNEL_LIVENESS_VERSION},[PRIVATE_PARENT_CAPABILITY_META_KEY]:privateParentCapability},clientCapabilities:{_meta:{"qwen.goalProposals":true,"qwen.mcpAppHost":true},fs:{readTextFile:delegateReadTextFileToClient,writeTextFile:true}},clientInfo:{name:"qwen-serve-bridge",version:"0"}}}__name(createChannelInitializeRequest,"createChannelInitializeRequest");function negotiateChannelCapabilities(response,requireExternalToolGuard){if(requireExternalToolGuard){const guardAck=response._meta?.[EXTERNAL_TOOL_GUARD_READY_META_KEY];if(guardAck!==EXTERNAL_TOOL_GUARD_REQUIRED_VALUE){throw new Error(`ACP child did not acknowledge the required external tool guard (received: ${JSON.stringify(guardAck)}).`)}}let activeWork;const activeWorkCapability=isRecord2(response._meta)?response._meta[ACTIVE_WORK_HEARTBEAT_META_KEY]:void 0;if(isRecord2(activeWorkCapability)&&activeWorkCapability["v"]===ACTIVE_WORK_HEARTBEAT_VERSION){const advertised=activeWorkCapability["categories"];activeWork={intervalMs:clampActiveWorkIntervalMs(activeWorkCapability["intervalMs"]),categories:Array.isArray(advertised)?ACTIVE_WORK_HOLD_CATEGORIES.filter(category=>advertised.includes(category)):[]}}const channelLivenessCapability=isRecord2(response._meta)?response._meta[CHANNEL_LIVENESS_META_KEY]:void 0;return{activeWork,channelLiveness:isRecord2(channelLivenessCapability)&&channelLivenessCapability["v"]===CHANNEL_LIVENESS_VERSION}}__name(negotiateChannelCapabilities,"negotiateChannelCapabilities");init_esbuild_shims();init_esbuild_shims();async function withTimeout(p,ms,label){let timer;const timeoutP=new Promise((_,reject)=>{timer=setTimeout(()=>reject(new BridgeTimeoutError(label,ms)),ms)});try{return await Promise.race([p,timeoutP])}finally{if(timer)clearTimeout(timer)}}__name(withTimeout,"withTimeout");async function terminateChannel(channel,timeoutMs,context){try{await withTimeout(channel.kill(),timeoutMs,`${context} teardown`)}catch(error){try{channel.killSync()}catch(forceError){throw new AggregateError([error,forceError],`ACP channel teardown failed (${context})`)}throw error}}__name(terminateChannel,"terminateChannel");function channelUnavailableReject(channel,context){const unavailable=channel.transportFailed?Promise.race([channel.exited,channel.transportFailed]):channel.exited;const reject=__name(()=>{throw new BridgeChannelClosedError(context)},"reject");return unavailable.then(reject,reject)}__name(channelUnavailableReject,"channelUnavailableReject");init_esbuild_shims();import{performance as performance2}from"node:perf_hooks";var CHANNEL_LIVENESS_INTERVAL_MS=15e3;var CHANNEL_LIVENESS_PROBE_TIMEOUT_MS=1e4;var CHANNEL_LIVENESS_FAILURE_THRESHOLD=2;var CHANNEL_LIVENESS_TIMER_LATE_TOLERANCE_MS=1e3;var CHANNEL_LIVENESS_TIMEOUT_CODE="acp_channel_liveness_timeout";var CHANNEL_LIVENESS_PROTOCOL_ERROR_CODE="acp_channel_liveness_protocol_error";var ChannelLivenessFailure=class extends Error{constructor(code){super(code===CHANNEL_LIVENESS_TIMEOUT_CODE?"ACP channel failed consecutive liveness probes":"ACP channel returned an invalid liveness response");this.code=code;this.name="ChannelLivenessFailure"}static{__name(this,"ChannelLivenessFailure")}};function isValidResponse(response,nonce){return typeof response==="object"&&response!==null&&!Array.isArray(response)&&response["v"]===CHANNEL_LIVENESS_VERSION&&response["nonce"]===nonce}__name(isValidResponse,"isValidResponse");function startChannelLivenessMonitor(options){const now=options.now??(()=>performance2.now());let stopped=false;let timer;let consecutiveTimeouts=0;let nextNonce=0;let resolveStopped;const stoppedOutcome=new Promise(resolve3=>{resolveStopped=resolve3});const isActive=__name(()=>!stopped&&options.isActive(),"isActive");const stop=__name(()=>{stopped=true;if(timer!==void 0){clearTimeout(timer);timer=void 0}resolveStopped({kind:"stopped"})},"stop");const fail=__name(error=>{if(!isActive())return;stop();options.onFailure(error)},"fail");const timerWasLate=__name(expectedAt=>now()>expectedAt+CHANNEL_LIVENESS_TIMER_LATE_TOLERANCE_MS,"timerWasLate");const runProbe=__name(async()=>{if(!isActive())return;const nonce=nextNonce;nextNonce=nonce===Number.MAX_SAFE_INTEGER?0:Math.max(0,nonce+1);const response=Promise.resolve().then(()=>options.probe(nonce)).then(value=>({kind:"response",response:value}),()=>({kind:"rejected"}));let outcome;while(true){const expectedAt=now()+CHANNEL_LIVENESS_PROBE_TIMEOUT_MS;const timeout=new Promise(resolve3=>{timer=setTimeout(()=>{timer=void 0;resolve3(timerWasLate(expectedAt)?{kind:"local_delay"}:{kind:"timeout"})},CHANNEL_LIVENESS_PROBE_TIMEOUT_MS);timer.unref()});outcome=await Promise.race([response,timeout,stoppedOutcome]);if(timer!==void 0){clearTimeout(timer);timer=void 0}if(outcome.kind==="stopped"||!isActive())return;if(outcome.kind!=="local_delay")break;consecutiveTimeouts=0}if(outcome.kind==="response"){if(!isValidResponse(outcome.response,nonce)){fail(new ChannelLivenessFailure(CHANNEL_LIVENESS_PROTOCOL_ERROR_CODE));return}consecutiveTimeouts=0;schedule(CHANNEL_LIVENESS_INTERVAL_MS);return}if(outcome.kind==="rejected"){await Promise.resolve();fail(new ChannelLivenessFailure(CHANNEL_LIVENESS_PROTOCOL_ERROR_CODE));return}consecutiveTimeouts++;if(consecutiveTimeouts>=CHANNEL_LIVENESS_FAILURE_THRESHOLD){fail(new ChannelLivenessFailure(CHANNEL_LIVENESS_TIMEOUT_CODE));return}void runProbe()},"runProbe");function schedule(delayMs){if(!isActive())return;const expectedAt=now()+delayMs;timer=setTimeout(()=>{timer=void 0;if(!isActive())return;if(timerWasLate(expectedAt)){consecutiveTimeouts=0;schedule(CHANNEL_LIVENESS_INTERVAL_MS);return}void runProbe()},delayMs);timer.unref()}__name(schedule,"schedule");schedule(CHANNEL_LIVENESS_INTERVAL_MS);return{stop}}__name(startChannelLivenessMonitor,"startChannelLivenessMonitor");init_esbuild_shims();var MAX_PROFILE_DURATION_MS=6e5;var ATTRIBUTE_PREFIX="qwen-code.daemon.acp_startup";function isRecord3(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}__name(isRecord3,"isRecord");function readDuration(source,key){const value=source[key];return typeof value==="number"&&Number.isFinite(value)&&value>=0&&value<=MAX_PROFILE_DURATION_MS?value:void 0}__name(readDuration,"readDuration");function readDurations(source,keys){if(!isRecord3(source)){return{values:{},complete:false}}const values={};let complete=true;for(const key of keys){const value=readDuration(source,key);if(value===void 0){complete=false}else{values[key]=value}}return{values,complete}}__name(readDurations,"readDurations");function addDurationAttributes(attributes,group,values){for(const[key,value]of Object.entries(values)){if(group==="phase"&&key==="unattributedMs")continue;const attributeKey=key.replace(/[A-Z]/g,letter=>`_${letter.toLowerCase()}`);attributes[`${ATTRIBUTE_PREFIX}.${group}.${attributeKey}`]=value}}__name(addDurationAttributes,"addDurationAttributes");var PHASE_KEYS=["processToProfilerReadyMs","geminiImportMs","argsParseMs","settingsLoadMs","configConstructionMs","appInitializationMs","acpImportMs","bootstrapConfigInitializationMs","transportSetupMs","initializeHandlerMs","unattributedMs"];var CONFIG_KEYS=["extensionsInitialMs","hooksMs","skillsMs","extensionsFinalMs","hierarchicalMemoryMs","toolRegistryMs","ripgrepProbeMs","toolWarmupMs","otherMs"];function getChannelStartupProfileAttributes(response,receivedAtEpochMs,initializeTimeoutMs){if(!isRecord3(response)||!isRecord3(response["_meta"])){return void 0}const profile=response["_meta"][CHANNEL_STARTUP_PROFILE_META_KEY];if(!isRecord3(profile)||profile["v"]!==CHANNEL_STARTUP_PROFILE_VERSION){return void 0}const phases=readDurations(profile["phases"],PHASE_KEYS);const config=readDurations(profile["config"],CONFIG_KEYS);const processToResponseMs=readDuration(profile,"processToResponseMs");const responseBuiltAtEpochMs=profile["responseBuiltAtEpochMs"];const childComplete=profile["complete"]===true;const validResponseEpoch=typeof responseBuiltAtEpochMs==="number"&&Number.isFinite(responseBuiltAtEpochMs)&&responseBuiltAtEpochMs>=0;const effectiveComplete=childComplete&&phases.complete&&config.complete&&processToResponseMs!==void 0&&validResponseEpoch;const attributes={[`${ATTRIBUTE_PREFIX}.profile.version`]:CHANNEL_STARTUP_PROFILE_VERSION,[`${ATTRIBUTE_PREFIX}.profile.complete`]:effectiveComplete};if(processToResponseMs!==void 0){attributes[`${ATTRIBUTE_PREFIX}.child.process_to_response_ms`]=processToResponseMs}if(phases.values["unattributedMs"]!==void 0){attributes[`${ATTRIBUTE_PREFIX}.child.unattributed_ms`]=phases.values["unattributedMs"]}addDurationAttributes(attributes,"phase",phases.values);addDurationAttributes(attributes,"config",config.values);if(validResponseEpoch){const transportMs=receivedAtEpochMs-responseBuiltAtEpochMs;if(Number.isFinite(transportMs)&&transportMs>=0&&transportMs<=initializeTimeoutMs){attributes[`${ATTRIBUTE_PREFIX}.response_transport_ms`]=transportMs}}return attributes}__name(getChannelStartupProfileAttributes,"getChannelStartupProfileAttributes");init_esbuild_shims();function writeStderrLine(message){process.stderr.write(message.endsWith("\n")?message:`${message}
|
|
4
4
|
`)}__name(writeStderrLine,"writeStderrLine");function isRecord4(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord4,"isRecord");function safeTransportFailureCode(error){if(!isRecord4(error))return void 0;const code=error["code"];return typeof code==="string"&&/^[a-z0-9_.-]{1,64}$/iu.test(code)?code:void 0}__name(safeTransportFailureCode,"safeTransportFailureCode");function safeTransportFailureDetail(error){if(!isRecord4(error)||error["code"]!=="ndjson_queue_limit_exceeded"){return void 0}const queueError=error;const budget=typeof queueError.budget==="string"&&/^[a-z0-9_.-]{1,64}$/iu.test(queueError.budget)?queueError.budget:"unknown";const numbers=[];for(const value of[queueError.requiredBytes,queueError.availableBytes,queueError.maxQueuedBytes]){numbers.push(typeof value==="number"&&Number.isFinite(value)?String(Math.max(0,Math.floor(value))):"?")}return`${budget}:required=${numbers[0]}:available=${numbers[1]}:cap=${numbers[2]}`}__name(safeTransportFailureDetail,"safeTransportFailureDetail");function createChannelStartup({channelFactory,executionEngines,boundWorkspace,childEnvOverrides,initTimeoutMs,telemetry,channelLifecycle,initialRuntimeEpoch,runtimeEpochSource,delegateReadTextFileToClient,isExternalToolGuardRequired,isShuttingDown,constructHarnessChannel,handleChannelTransportUnavailable,handleChannelExit,killChannelWithLog,sessionCount}){let runtimeEpoch=initialRuntimeEpoch;async function start(engine){const factory=engine===void 0?channelFactory:executionEngines[engine];const privateParentCapability=randomBytes(32).toString("base64url");const acpChannelId=randomUUID();const startupStartedAt=Date.now();const startupAbort=new AbortController;const startup={};const factoryPromise=telemetry.withSpan("channel.spawn",{"qwen-code.daemon.bridge.operation":"channel.spawn","qwen-code.daemon.channel.reused":false,"qwen-code.daemon.acp_channel.id":acpChannelId},async()=>await factory(boundWorkspace,{...childEnvOverrides,[PRIVATE_ACP_CAPABILITY_ENV]:privateParentCapability},startupAbort.signal,startup));let channel;try{channel=await withTimeout(factoryPromise,initTimeoutMs,"channel factory")}catch(error){const failure=error instanceof BridgeTimeoutError?startup.getTimeoutError?.()??error:error;startupAbort.abort(failure);void factoryPromise.then(lateChannel=>terminateChannel(lateChannel,initTimeoutMs,"late channel factory result").catch(teardownError=>{writeStderrLine(`qwen serve: late ACP channel teardown failed: ${String(teardownError)}`)}),()=>void 0);throw failure}let info;try{info=constructHarnessChannel(channel,acpChannelId,engine)}catch(error){try{channel.killSync()}catch{}try{await Promise.race([channel.exited.then(()=>void 0),terminateChannel(channel,initTimeoutMs,"channel construction failure")])}catch(teardownError){throw new AggregateError([error,teardownError],"ACP channel construction and teardown failed")}throw error}const{connection}=info;const markTransportFailed=__name(error=>{if(!info.isDying){info.transportFailureInitiatedTeardown=true}info.transportFailed=true;info.transportFailureCode=safeTransportFailureCode(error);info.transportFailureDetail=safeTransportFailureDetail(error);info.isDying=true;info.channelLiveness?.stop();handleChannelTransportUnavailable(info)},"markTransportFailed");void channel.transportFailed?.then(markTransportFailed,markTransportFailed);channelLifecycle.track(info);const engineChannelCount=[...channelLifecycle.values()].filter(candidate=>candidate.executionEngine===engine).length;if(engineChannelCount>2){writeStderrLine(`qwen serve: WARNING engine=${engine??"single"} channelCount=${engineChannelCount} (expected 1, max 2 per engine during killSession-then-spawnOrAttach overlap) \u2014 possible channel leak; check that prior channels' channel.exited fired and the handler ran cleanup.`)}void channel.exited.then(exitInfo=>{handleChannelExit(info,exitInfo)});let channelLivenessNegotiated=false;try{await telemetry.withSpan("channel.initialize",{"qwen-code.daemon.bridge.operation":"channel.initialize","qwen-code.daemon.acp_channel.id":acpChannelId},async()=>{const remainingStartupMs=Math.max(1,initTimeoutMs-(Date.now()-startupStartedAt));const response=await withTimeout(Promise.race([connection.initialize(createChannelInitializeRequest(privateParentCapability,delegateReadTextFileToClient)),channelUnavailableReject(channel,"during initialize")]),remainingStartupMs,"initialize");const capabilities=negotiateChannelCapabilities(response,isExternalToolGuardRequired());if(capabilities.activeWork){info.activeWork={...capabilities.activeWork,seq:0}}channelLivenessNegotiated=capabilities.channelLiveness;try{const attributes=getChannelStartupProfileAttributes(response,Date.now(),initTimeoutMs);if(attributes&&telemetry.setActiveSpanAttributes){telemetry.setActiveSpanAttributes(attributes)}}catch{}return response})}catch(err){info.isDying=true;startupAbort.abort(err);await terminateChannel(channel,initTimeoutMs,"channel initialization failure").catch(()=>void 0);throw err}if(info.isDying){await channel.kill().catch(()=>{});throw new BridgeChannelClosedError("during initialize")}if(isShuttingDown()){info.isDying=true;startupAbort.abort(new Error("AcpSessionBridge is shutting down"));await terminateChannel(channel,initTimeoutMs,"late shutdown").catch(()=>void 0);throw new Error("AcpSessionBridge is shutting down")}if(!channelLifecycle.has(info)){info.isDying=true;const error=new BridgeChannelClosedError("during channel initialization");startupAbort.abort(error);await terminateChannel(channel,initTimeoutMs,"exited during initialization").catch(()=>void 0);throw error}const previousRuntimeEpoch=runtimeEpochSource.current();const nextRuntimeEpoch=runtimeEpochSource.allocate();if(!Number.isSafeInteger(previousRuntimeEpoch)||previousRuntimeEpoch<runtimeEpoch||!Number.isSafeInteger(nextRuntimeEpoch)||nextRuntimeEpoch<=previousRuntimeEpoch){info.isDying=true;const epochError=new Error(`Runtime epoch source must increase monotonically (local=${runtimeEpoch}, current=${previousRuntimeEpoch}, next=${nextRuntimeEpoch}).`);startupAbort.abort(epochError);await terminateChannel(channel,initTimeoutMs,"invalid runtime epoch").catch(()=>void 0);throw epochError}runtimeEpoch=nextRuntimeEpoch;info.runtimeEpoch=nextRuntimeEpoch;info.lastUsedAt=Date.now();channelLifecycle.publish(info);info.handshakeComplete=true;if(channelLivenessNegotiated){const failChannelLiveness=__name(error=>{if(info.isDying||!channelLifecycle.has(info))return;markTransportFailed(error);telemetry.event("channel.liveness_failed",{"qwen-code.daemon.acp_channel.id":info.id,"qwen-code.daemon.channel.session_count":sessionCount(info),"qwen-code.daemon.channel.transport_error_code":error.code});writeStderrLine(`qwen serve: channel liveness failed (${error.code}); killing channel`);if(info.channel.transportGuard){info.channel.transportGuard.fail(error)}else{void killChannelWithLog(info,"channel liveness failure")}},"failChannelLiveness");info.channelLiveness=startChannelLivenessMonitor({probe:__name(nonce=>info.connection.extMethod(SERVE_STATUS_EXT_METHODS.channelPing,{v:CHANNEL_LIVENESS_VERSION,nonce}),"probe"),onFailure:failChannelLiveness,isActive:__name(()=>channelLifecycle.currentFor(engine)===info&&channelLifecycle.has(info)&&!info.isDying&&!isShuttingDown(),"isActive")})}telemetry.metrics?.channelLifecycle("spawn");return info}__name(start,"start");return{get epoch(){return runtimeEpoch},start}}__name(createChannelStartup,"createChannelStartup");function isRecord5(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord5,"isRecord");function createChannelHarness(options){const{initTimeoutMs,telemetry,isShuttingDown,hasNoSessionWork,hasNoWorkspaceWork,channelShouldReapWhenIdle,sessionCount}=options;const defaultEngine=options.executionEngines?"legacy":void 0;const channelLifecycle=createChannelLifecycle(defaultEngine);let keepAliveUntil=0;const runtimeOperationReservations=new Map;const pendingKeepAliveDeadlines=new Map;const idleTimers=new Map;const pendingIdleTimers=new Set;function liveHarnessChannel(engine=defaultEngine){const channel=channelLifecycle.currentFor(engine);return channel&&!channel.isDying?channel:void 0}__name(liveHarnessChannel,"liveHarnessChannel");function hasNoChannelWork(ci,exclusions){if(!hasNoSessionWork(ci,exclusions))return false;if(ci.retireWhenSessionsDrain)return true;return ci.workspaceControlInFlight===0&&hasNoWorkspaceWork(ci)&&(runtimeOperationReservations.get(ci.executionEngine)??0)===0}__name(hasNoChannelWork,"hasNoChannelWork");function cancelIdleTimer(channel){if(channel)pendingIdleTimers.delete(channel);else pendingIdleTimers.clear();for(const[owner,timer]of idleTimers){if(channel!==void 0&&owner!==channel)continue;clearTimeout(timer);idleTimers.delete(owner)}}__name(cancelIdleTimer,"cancelIdleTimer");async function killChannelWithLog(ci,context){ci.isDying=true;options.onChannelTerminationStart?.(ci);cancelIdleTimer(ci);ci.channelLiveness?.stop();await terminateChannel(ci.channel,initTimeoutMs,context??"channel kill").catch(err=>{writeStderrLine(`qwen serve: channel kill failed${context?` (${context})`:""}: ${String(err)}`)})}__name(killChannelWithLog,"killChannelWithLog");async function retireChannelAfterSessionsDrain(ci,context){if(ci.isDying)return;if(hasNoSessionWork(ci)){await killChannelWithLog(ci,context);return}ci.retireWhenSessionsDrain=true;writeStderrLine(`qwen serve: ${context}; deferring channel retirement until ${sessionCount(ci)} active session(s) drain`)}__name(retireChannelAfterSessionsDrain,"retireChannelAfterSessionsDrain");async function retireChannelOnTimeout(ci,error,context){if(error instanceof BridgeTimeoutError&&!ci.isDying){await retireChannelAfterSessionsDrain(ci,context)}}__name(retireChannelOnTimeout,"retireChannelOnTimeout");function configuredChannelIdleTimeoutMs(){const raw=options.getChannelIdleTimeoutMs();return raw!==void 0&&Number.isFinite(raw)&&raw>0?Math.min(raw,2147483647):0}__name(configuredChannelIdleTimeoutMs,"configuredChannelIdleTimeoutMs");function resolvedChannelIdleTimeoutMs(engine=defaultEngine){const configured=configuredChannelIdleTimeoutMs();if(engine!==defaultEngine)return configured;const now=Date.now();let pendingKeepAliveMs=0;for(const deadline of pendingKeepAliveDeadlines.values()){pendingKeepAliveMs=Math.max(pendingKeepAliveMs,deadline-now)}return Math.max(configured,keepAliveUntil-now,pendingKeepAliveMs)}__name(resolvedChannelIdleTimeoutMs,"resolvedChannelIdleTimeoutMs");async function startIdleTimer(ci,context,exclusions){if(options.isRuntimeStopping()||ci.isDying||liveHarnessChannel(ci.executionEngine)!==ci)return;if(!hasNoChannelWork(ci,exclusions)){pendingIdleTimers.add(ci);return}cancelIdleTimer(ci);const timeoutMs=resolvedChannelIdleTimeoutMs(ci.executionEngine);if(timeoutMs<=0){await killChannelWithLog(ci,context);return}const idleTimer=setTimeout(()=>{idleTimers.delete(ci);if(hasNoChannelWork(ci)){writeStderrLine(`qwen serve: idle timeout (${timeoutMs}ms) expired, killing channel`);void killChannelWithLog(ci,"idle timeout")}else{pendingIdleTimers.add(ci)}},timeoutMs);idleTimers.set(ci,idleTimer);idleTimer.unref()}__name(startIdleTimer,"startIdleTimer");function retireChannel(info,context){info.isDying=true;cancelIdleTimer(info);if(info.executionEngine===defaultEngine)keepAliveUntil=0;info.channelLiveness?.stop();return terminateChannel(info.channel,initTimeoutMs,context)}__name(retireChannel,"retireChannel");async function reapPendingEmptyChannel(ci,opts){if(!channelShouldReapWhenIdle(ci)||!hasNoChannelWork(ci,opts))return;ci.emptyReapPending=false;ci.isDying=true;options.onChannelTerminationStart?.(ci);ci.channelLiveness?.stop();await terminateChannel(ci.channel,initTimeoutMs,"pending empty channel").catch(()=>{})}__name(reapPendingEmptyChannel,"reapPendingEmptyChannel");async function withWorkspaceControl(ci,fn,recordUse=true){if(options.isRuntimeStopping())throw new WorkspaceDrainingError(options.boundWorkspace??"");if(liveHarnessChannel(ci.executionEngine)===ci)cancelIdleTimer(ci);if(recordUse)ci.lastUsedAt=Date.now();ci.workspaceControlInFlight++;try{return await fn()}catch(error){await retireChannelOnTimeout(ci,error,"workspace control timeout");throw error}finally{if(recordUse)ci.lastUsedAt=Date.now();ci.workspaceControlInFlight=Math.max(0,ci.workspaceControlInFlight-1);await reapPendingEmptyChannel(ci);if(!ci.isDying&&liveHarnessChannel(ci.executionEngine)===ci){await startIdleTimer(ci,"workspace control")}}}__name(withWorkspaceControl,"withWorkspaceControl");async function settleReleasedRuntimeWork(context){const channels=Array.from(channelLifecycle.values());for(const ci of channels){await reapPendingEmptyChannel(ci)}for(const ci of channels){if(!ci.isDying&&pendingIdleTimers.has(ci)&&!idleTimers.has(ci)&&hasNoChannelWork(ci)){await startIdleTimer(ci,context)}}}__name(settleReleasedRuntimeWork,"settleReleasedRuntimeWork");function reserveRuntimeOperation(engine=defaultEngine){runtimeOperationReservations.set(engine,(runtimeOperationReservations.get(engine)??0)+1)}__name(reserveRuntimeOperation,"reserveRuntimeOperation");function decrementRuntimeOperationReservation(engine=defaultEngine){const remaining=(runtimeOperationReservations.get(engine)??0)-1;if(remaining>0)runtimeOperationReservations.set(engine,remaining);else runtimeOperationReservations.delete(engine)}__name(decrementRuntimeOperationReservation,"decrementRuntimeOperationReservation");async function releaseRuntimeOperationReservation(context,engine=defaultEngine){decrementRuntimeOperationReservation(engine);const channel=liveHarnessChannel(engine);if(channel)pendingIdleTimers.add(channel);await settleReleasedRuntimeWork(context)}__name(releaseRuntimeOperationReservation,"releaseRuntimeOperationReservation");async function ensureChannel(engine=defaultEngine){if(options.isRuntimeStopping())throw new WorkspaceDrainingError(options.boundWorkspace??"");if(isShuttingDown()){throw new Error("AcpSessionBridge is shutting down")}const current=channelLifecycle.currentFor(engine);if(current)cancelIdleTimer(current);if(current&&!current.isDying)return current;const starting=channelLifecycle.startingFor(engine);if(starting)return await starting;const promise=channelLifecycle.startSpawn(()=>channelStartup.start(engine),engine);try{return await promise}finally{channelLifecycle.finishSpawn(engine)}}__name(ensureChannel,"ensureChannel");const preheat=__name(async options2=>{if(isShuttingDown()){throw new Error("AcpSessionBridge is shutting down")}reserveRuntimeOperation();const rawKeepAliveMs=options2?.keepAliveMs;const keepAliveMs=rawKeepAliveMs!==void 0&&Number.isFinite(rawKeepAliveMs)&&rawKeepAliveMs>0?Math.min(rawKeepAliveMs,2147483647):void 0;const pendingKeepAliveToken=keepAliveMs===void 0?void 0:Symbol();if(pendingKeepAliveToken&&keepAliveMs!==void 0){pendingKeepAliveDeadlines.set(pendingKeepAliveToken,Date.now()+keepAliveMs)}let channel;try{await telemetry.withSpan("channel.preheat",{"qwen-code.daemon.bridge.operation":"channel.preheat"},async()=>{const info=await ensureChannel();channel=info;info.lastUsedAt=Date.now();if(keepAliveMs!==void 0){keepAliveUntil=Math.max(keepAliveUntil,Date.now()+keepAliveMs)}})}finally{if(pendingKeepAliveToken){pendingKeepAliveDeadlines.delete(pendingKeepAliveToken)}decrementRuntimeOperationReservation();if(channel&&channelLifecycle.has(channel)&&resolvedChannelIdleTimeoutMs()>0){pendingIdleTimers.add(channel)}await settleReleasedRuntimeWork("channel preheat")}},"preheat");const channelStartup=createChannelStartup({...options,channelLifecycle,killChannelWithLog,handleChannelExit(info,exitInfo){info.channelLiveness?.stop();options.handleChannelTransportUnavailable(info);cancelIdleTimer(info);options.beforeChannelExit(info);channelLifecycle.remove(info);options.handleChannelExit(info,exitInfo)}});return{get current(){return channelLifecycle.current},get starting(){return channelLifecycle.starting},currentFor:channelLifecycle.currentFor,startingFor:channelLifecycle.startingFor,startups:channelLifecycle.startups,get epoch(){return channelStartup.epoch},get runtimeOperationReservations(){return Array.from(runtimeOperationReservations.values()).reduce((total,count)=>total+count,0)},get pendingKeepAliveCount(){return pendingKeepAliveDeadlines.size},createConnection:createHarnessConnection,withWorktreeInitialization(request,worktree){return worktree?{...request,_meta:{...isRecord5(request._meta)?request._meta:{},[WORKTREE_MCP_DEFER_META_KEY]:true}}:request},changeSessionCwd(channel,sessionId,req){return channel.connection.extMethod(SERVE_CONTROL_EXT_METHODS.sessionCd,{sessionId,path:req.path,...req.allowedRoots?{allowedRoots:req.allowedRoots}:{},...req.managedRelocation?{managedRelocation:req.managedRelocation}:{},...req.conversationDirectoryExpectation?{conversationDirectoryExpectation:req.conversationDirectoryExpectation}:{}})},executeShell(command,cwd,onOutput,signal){return ShellExecutionService.execute(command,cwd,onOutput,signal,false,{terminalWidth:120,terminalHeight:40},{streamStdout:true})},values:channelLifecycle.values,has:channelLifecycle.has,ensure:ensureChannel,configuredChannelIdleTimeoutMs,cancelIdleTimer,startIdleTimer,killChannelWithLog,retireChannelAfterSessionsDrain,retireChannelOnTimeout,hasNoChannelWork,reapPendingEmptyChannel,withWorkspaceControl,reserveRuntimeOperation,releaseRuntimeOperationReservation,settleReleasedRuntimeWork,preheat,reclaimIdleChannel(info){writeStderrLine(`qwen serve: reclaiming idle ACP channel ${info.id}`);return retireChannel(info,"capacity reclamation")},stopChannel(info){return retireChannel(info,"user-confirmed workspace stop")},markDying(channels){for(const ci of channels){ci.isDying=true;ci.channelLiveness?.stop()}},killAllSync(channels){for(const info of channels){info.channelLiveness?.stop();try{info.channel.killSync()}catch{}}},terminate(channel){return terminateChannel(channel.channel,initTimeoutMs,"bridge shutdown")}}}__name(createChannelHarness,"createChannelHarness");init_esbuild_shims();init_esbuild_shims();var SessionStartupConfigError=class extends Error{constructor(code,message,sessionId){super(message);this.code=code;this.sessionId=sessionId}static{__name(this,"SessionStartupConfigError")}name="SessionStartupConfigError"};function isReasoningSelection(value){return typeof value==="string"&&(value==="default"||value==="none"||REASONING_EFFORT_TIERS.some(tier=>tier===value))}__name(isReasoningSelection,"isReasoningSelection");function parseSessionStartupConfig(value,request={}){if(value===void 0)return void 0;const config=value;if(!config||typeof config!=="object"||Array.isArray(config)||Object.keys(config).some(key=>key!=="modelServiceId"&&key!=="reasoningEffort")||typeof config.modelServiceId!=="string"||!config.modelServiceId.trim()||config.modelServiceId.length>MAX_CRON_TASK_ROUTING_ID_LENGTH||new RegExp("\\p{Cc}","u").test(config.modelServiceId)||config.reasoningEffort!==void 0&&!isReasoningSelection(config.reasoningEffort)||request.modelServiceId!==void 0||request.sessionScope==="single"){throw new SessionStartupConfigError("invalid_startup_config","startupConfig requires modelServiceId (1-256 characters) and an optional valid reasoningEffort, without unknown fields, a legacy modelServiceId or single session scope.")}return{modelServiceId:config.modelServiceId.trim(),...config.reasoningEffort!==void 0?{reasoningEffort:config.reasoningEffort}:{}}}__name(parseSessionStartupConfig,"parseSessionStartupConfig");function rejectInvalidSelection(error,sessionId){if(error===null||typeof error!=="object"||!("code"in error)||!("message"in error)||typeof error.message!=="string"){throw error}if(error.code===-32602){throw new SessionStartupConfigError("startup_config_rejected",error.message,sessionId)}throw error}__name(rejectInvalidSelection,"rejectInvalidSelection");async function applySessionStartupConfig(bridge,sessionId,config){const model=await bridge.setSessionConfigOption(sessionId,{sessionId,configId:"model",value:config.modelServiceId}).catch(error=>rejectInvalidSelection(error,sessionId));const modelServiceId=model.configOptions?.find(option=>option.id==="model")?.currentValue;if(!modelServiceId){throw new SessionStartupConfigError("startup_config_rejected","The session did not confirm its model selection.",sessionId)}if(config.reasoningEffort===void 0)return{modelServiceId};const result=await bridge.setSessionConfigOption(sessionId,{sessionId,configId:"reasoning_effort",value:config.reasoningEffort}).catch(error=>rejectInvalidSelection(error,sessionId));const reasoning=result.configOptions?.find(option=>option.id==="reasoning_effort");const currentModel=result.configOptions?.find(option=>option.id==="model")?.currentValue;const selection=reasoning?.currentValue;if(currentModel!==modelServiceId||!isReasoningSelection(selection)||config.reasoningEffort!=="default"&&selection!==config.reasoningEffort){throw new SessionStartupConfigError("startup_config_rejected","The session did not confirm its model and reasoning selection.",sessionId)}const meta=reasoning?._meta?.["qwenCode/reasoning"];const toggleOnly=meta!==null&&typeof meta==="object"&&"toggleOnly"in meta&&meta.toggleOnly===true;return{modelServiceId,reasoningEffort:config.reasoningEffort,effectiveReasoning:selection==="none"?{state:"disabled"}:selection==="default"?toggleOnly?{state:"enabled"}:{state:"provider-default"}:{state:"enabled",effort:selection}}}__name(applySessionStartupConfig,"applySessionStartupConfig");import{randomUUID as randomUUID4}from"node:crypto";import*as path5 from"node:path";init_esbuild_shims();var TURN_BOUNDARY_TYPES=new Set(["turn_complete","turn_error"]);var TRANSIENT_TYPES=new Set(["history_truncated","slow_client_warning","client_evicted","replay_complete","stream_error","session_rewound"]);var LATEST_WINS_UPDATES=new Set(["available_commands_update","current_mode_update"]);var REPLAY_SEGMENT_COMPACT_THRESHOLD=64;var LIVE_JOURNAL_TEXT_CHUNKS_PER_EVENT=256;function createLiveJournalState(){return{entries:[],entryBytes:[],entryEvents:[],totalBytes:0,totalEvents:0,truncatedEvents:0}}__name(createLiveJournalState,"createLiveJournalState");function replayRecordId(event){if(event.type!=="session_update")return void 0;const data=event.data;if(!data||typeof data!=="object"||Array.isArray(data))return void 0;const update=data["update"];if(!update||typeof update!=="object"||Array.isArray(update)){return void 0}const meta=update["_meta"];if(!meta||typeof meta!=="object"||Array.isArray(meta)){return void 0}const recordId=meta["qwen.session.recordId"];return typeof recordId==="string"?recordId:void 0}__name(replayRecordId,"replayRecordId");function lastRecordIdIn(events){for(let i=events.length-1;i>=0;i--){const id=replayRecordId(events[i]);if(id!==void 0)return id}return void 0}__name(lastRecordIdIn,"lastRecordIdIn");function lastSummaryRecordIdIn(events){for(let i=events.length-1;i>=0;i--){if(!isSummaryReplayEvent(events[i]))continue;const id=replayRecordId(events[i]);if(id!==void 0)return id}return void 0}__name(lastSummaryRecordIdIn,"lastSummaryRecordIdIn");var JOURNAL_GROWTH_REASK_INTERVAL_MS=1e4;var JOURNAL_GROWTH_MAX_GRANTS_PER_BREACH=64;var TurnBoundaryCompactionEngine=class{static{__name(this,"TurnBoundaryCompactionEngine")}maxReplayBytes;maxJournalEvents;maxJournalBytes;onJournalGrowth;now;journalGrowthDeniedAt;onReplayWindowEviction;replaySegments=[];replaySegmentStart=0;replayBytes=0;fullJournal=createLiveJournalState();summaryJournal=createLiveJournalState();lastEventId=0;closed=false;truncatedEvents=0;truncatedTurns=0;activeRecordId;summaryRecordId;replayAnchorRecordId;slots=[];toolSlotIndex=new Map;textSlotIndex={text:new Map,thought:new Map};constructor(opts={}){this.maxReplayBytes=normalizeCompactedReplayMaxBytes(opts.maxReplayBytes);this.maxJournalEvents=normalizeMaxJournalEvents(opts.maxJournalEvents);this.maxJournalBytes=normalizeMaxJournalBytes(opts.maxJournalBytes);this.onJournalGrowth=opts.onJournalGrowth;this.now=opts.now??(()=>performance.now());this.onReplayWindowEviction=opts.onReplayWindowEviction}journalLimits(){return{maxEvents:this.maxJournalEvents,maxBytes:this.maxJournalBytes}}ingest(event,byteLength){if(this.closed)return;if(event.id!==void 0){this.lastEventId=event.id}if(TRANSIENT_TYPES.has(event.type))return;const summaryEvent=summarizeReplayEvent(event);const seenRecordId=replayRecordId(event);if(seenRecordId!==void 0){this.activeRecordId=seenRecordId;if(summaryEvent)this.summaryRecordId=seenRecordId}this.appendLiveJournal(this.fullJournal,event,byteLength);if(summaryEvent){this.appendLiveJournal(this.summaryJournal,summaryEvent,summaryEvent===event?byteLength:void 0)}if(TURN_BOUNDARY_TYPES.has(event.type)){this.compactCurrentTurn(event);return}if(event.type==="session_update"){this.classifySessionUpdate(event);return}this.slots.push({kind:"misc",event})}snapshot(liveReplayMode="full"){const compactedTurns=this.flattenReplaySegments();if(this.truncatedEvents>0){compactedTurns.unshift(this.makeHistoryTruncatedEvent(compactedTurns.length))}return{compactedTurns,liveJournal:this.liveJournalSnapshot(liveReplayMode),lastEventId:this.lastEventId}}liveJournalSnapshot(liveReplayMode="full"){const journal=liveReplayMode==="summary"?this.summaryJournal:this.fullJournal;const journalRecordId=liveReplayMode==="summary"?this.summaryRecordId:this.activeRecordId;const liveJournal=journal.entries.map(entry=>isLiveJournalTextSegment(entry)?mergeLiveJournalTextEvent(entry.firstEvent,entry.lastEvent,entry.chunks):entry);if(journal.truncatedEvents>0){liveJournal.unshift({v:EVENT_SCHEMA_VERSION,type:"history_truncated",data:{reason:"replay_window_exceeded",scope:"live_journal",truncatedEvents:journal.truncatedEvents,retainedEvents:journal.totalEvents,maxBytes:this.maxJournalBytes,maxEvents:this.maxJournalEvents,...journalRecordId!==void 0?{recordId:journalRecordId}:{},fullTranscriptAvailable:true}})}return liveJournal}seed(snapshot){if(this.closed)return;this.resetReplayWindow();this.lastEventId=snapshot.lastEventId;this.activeRecordId=void 0;this.summaryRecordId=void 0;this.activeRecordId=lastRecordIdIn(snapshot.compactedTurns);this.summaryRecordId=lastSummaryRecordIdIn(snapshot.compactedTurns);for(const event of snapshot.compactedTurns){if(TRANSIENT_TYPES.has(event.type))continue;this.addReplaySegment([event],0)}this.resetJournal();this.slots=[];this.toolSlotIndex.clear();this.clearTextSlotIndex()}seedReplayEvents(events){if(this.closed)return;this.resetReplayWindow();this.activeRecordId=void 0;this.summaryRecordId=void 0;this.activeRecordId=lastRecordIdIn(events);this.summaryRecordId=lastSummaryRecordIdIn(events);let recordEvents=[];let recordId;const flushRecord=__name(()=>{this.addReplaySegment(recordEvents,0);recordEvents=[];recordId=void 0},"flushRecord");for(const event of events){this.recordLastEventId(event);if(TRANSIENT_TYPES.has(event.type))continue;const nextRecordId=replayRecordId(event);if(nextRecordId===void 0){flushRecord();this.addReplaySegment([event],0);continue}if(recordId!==void 0&&recordId!==nextRecordId){flushRecord()}recordId=nextRecordId;recordEvents.push(event)}flushRecord();this.resetJournal();this.slots=[];this.toolSlotIndex.clear();this.clearTextSlotIndex()}close(){if(this.closed)return;this.closed=true;this.resetReplayWindow();this.resetJournal();this.activeRecordId=void 0;this.summaryRecordId=void 0;this.slots=[];this.toolSlotIndex.clear();this.clearTextSlotIndex()}appendLiveJournal(journal,event,byteLength){const bytes=byteLength??serializedBridgeEventByteLength(event)??0;const textChunk=liveJournalTextChunk(event);const current=journal.textSegment;const currentIndex=journal.entries.length-1;if(textChunk&¤t&&journal.entries[currentIndex]===current&¤t.chunks.length<LIVE_JOURNAL_TEXT_CHUNKS_PER_EVENT&&journal.entryBytes[currentIndex]+bytes<=this.maxJournalBytes&¤t.sessionUpdate===textChunk.sessionUpdate&¤t.parentToolCallId===textChunk.parentToolCallId&&stringArraysEqual(current.sourceRecordIds,textChunk.sourceRecordIds)&¤t.promptId===event.promptId&¤t.originatorClientId===event.originatorClientId&¤t.sessionId===captureSessionId(event)&&hasOnlyTimestampEnvelopeMeta(current.lastEvent._meta)&&hasOnlyTimestampEnvelopeMeta(event._meta)){current.chunks.push(textChunk.text);current.lastEvent=event;journal.entryBytes[currentIndex]+=bytes;journal.entryEvents[currentIndex]+=1;journal.totalBytes+=bytes;journal.totalEvents+=1}else{let entry=event;if(textChunk){const segment={sessionUpdate:textChunk.sessionUpdate,chunks:[textChunk.text],sourceRecordIds:textChunk.sourceRecordIds,parentToolCallId:textChunk.parentToolCallId,promptId:event.promptId,originatorClientId:event.originatorClientId,sessionId:captureSessionId(event),firstEvent:event,lastEvent:event};entry=segment;journal.textSegment=segment}else{journal.textSegment=void 0}journal.entries.push(entry);journal.entryBytes.push(bytes);journal.entryEvents.push(1);journal.totalBytes+=bytes;journal.totalEvents+=1}if(!TURN_BOUNDARY_TYPES.has(event.type)&&(journal.entries.length>this.maxJournalEvents||journal.totalBytes>this.maxJournalBytes&&journal.entries.length>1)){this.maybeGrowJournalLimits(journal)}while(journal.entries.length>this.maxJournalEvents||journal.totalBytes>this.maxJournalBytes&&journal.entries.length>1){const dropped=journal.entries.shift();journal.totalBytes-=journal.entryBytes.shift()??0;const droppedEvents=journal.entryEvents.shift()??0;journal.totalEvents-=droppedEvents;journal.truncatedEvents+=droppedEvents;if(dropped===journal.textSegment){journal.textSegment=void 0}}}maybeGrowJournalLimits(journal){const advisor=this.onJournalGrowth;if(!advisor||this.closed)return;const now=this.now();if(this.journalGrowthDeniedAt!==void 0){const sinceDenialMs=now-this.journalGrowthDeniedAt;if(sinceDenialMs>=0&&sinceDenialMs<JOURNAL_GROWTH_REASK_INTERVAL_MS){return}}const originalEvents=this.maxJournalEvents;const originalBytes=this.maxJournalBytes;const originalRetained=this.retainedTailCount(journal,originalEvents,originalBytes);for(let step=0;step<JOURNAL_GROWTH_MAX_GRANTS_PER_BREACH;step++){let grant;try{grant=advisor({maxEvents:this.maxJournalEvents,maxBytes:this.maxJournalBytes})}catch{grant=void 0}if(!grant||!Number.isSafeInteger(grant.maxBytes)||!Number.isSafeInteger(grant.maxEvents)||grant.maxBytes<=this.maxJournalBytes||grant.maxEvents<this.maxJournalEvents){break}this.maxJournalBytes=grant.maxBytes;this.maxJournalEvents=grant.maxEvents;if(this.retainedTailCount(journal,grant.maxEvents,grant.maxBytes)>originalRetained){this.journalGrowthDeniedAt=void 0;return}}this.maxJournalEvents=originalEvents;this.maxJournalBytes=originalBytes;this.journalGrowthDeniedAt=now}retainedTailCount(journal,maxEvents,maxBytes){let count=0;let bytes=0;for(let i=journal.entries.length-1;i>=0;i--){const entryBytes=journal.entryBytes[i]??0;if(count+1>maxEvents)break;if(count>=1&&bytes+entryBytes>maxBytes)break;count+=1;bytes+=entryBytes}return count}classifySessionUpdate(event){const data=event.data;const updateType=data?.update?.sessionUpdate;if(!updateType){this.slots.push({kind:"misc",event});return}switch(updateType){case"agent_message_chunk":{const meta=data?.update?._meta;if(hasDiscreteMessageMeta(data?.update?._meta)||meta?.["executionLifecycle"]!==void 0){this.slots.push({kind:"misc",event});break}this.mergeTextSlot("text",event,data);break}case"agent_thought_chunk":{if(hasDiscreteMessageMeta(data?.update?._meta)){this.slots.push({kind:"misc",event});break}this.mergeTextSlot("thought",event,data);break}case"tool_call":case"tool_call_update":{const update=data?.update;const meta=update?.["_meta"];if(meta?.["toolLifecycle"]!==void 0&&update?.["status"]===void 0&&update?.["content"]===void 0){this.slots.push({kind:"misc",event});break}const toolCallId=data?.update?.toolCallId;if(!toolCallId){this.slots.push({kind:"misc",event});break}const existingIdx=this.toolSlotIndex.get(toolCallId);if(existingIdx!==void 0){const slot=this.slots[existingIdx];slot.event=mergeToolCallEvent(slot.event,event)}else{const normalizedEvent=normalizeToolCallType(event);this.toolSlotIndex.set(toolCallId,this.slots.length);this.slots.push({kind:"tool",toolCallId,event:normalizedEvent});const toolParent=extractParentToolCallIdFromMeta(data?.update?._meta);if(toolParent){this.textSlotIndex.text.delete(toolParent);this.textSlotIndex.thought.delete(toolParent)}}break}default:{if(LATEST_WINS_UPDATES.has(updateType)){const existingIdx=this.slots.findIndex(s=>s.kind==="latestWins"&&s.key===updateType);if(existingIdx!==-1){this.slots[existingIdx].event=event}else{this.slots.push({kind:"latestWins",key:updateType,event})}}else{this.slots.push({kind:"misc",event})}break}}}mergeTextSlot(kind,event,data){const text=data?.update?.content?.text??"";const meta=data?.update?._meta;const parentToolCallId=extractParentToolCallIdFromMeta(meta);const sourceRecordIds=extractSourceRecordIdsFromMeta(meta);if(parentToolCallId!=null){const entries=this.textSlotIndex[kind].get(parentToolCallId)??[];const existingIdx=entries.find(entry=>stringArraysEqual(entry.sourceRecordIds,sourceRecordIds))?.index;if(existingIdx!==void 0){const slot=this.slots[existingIdx];slot.chunks.push(text);if(event.id!==void 0)slot.lastEventId=event.id;slot.lastMeta=mergeTranscriptUpdateMeta(slot.lastMeta,meta);slot.lastEnvelopeMeta=event._meta??slot.lastEnvelopeMeta;slot.lastTurn=captureTurnFields(event,slot.lastTurn);slot.lastSessionId=captureSessionId(event)??slot.lastSessionId}else{entries.push({sourceRecordIds,index:this.slots.length});this.textSlotIndex[kind].set(parentToolCallId,entries);this.slots.push({kind,parentToolCallId,chunks:[text],sourceRecordIds,lastEventId:event.id??0,lastMeta:meta,lastEnvelopeMeta:event._meta,lastTurn:captureTurnFields(event),lastSessionId:captureSessionId(event)})}}else{const lastSlot=this.slots[this.slots.length-1];if(lastSlot&&lastSlot.kind===kind&&lastSlot.parentToolCallId==null&&stringArraysEqual(lastSlot.sourceRecordIds,sourceRecordIds)){lastSlot.chunks.push(text);if(event.id!==void 0)lastSlot.lastEventId=event.id;lastSlot.lastMeta=mergeTranscriptUpdateMeta(lastSlot.lastMeta,meta);lastSlot.lastEnvelopeMeta=event._meta??lastSlot.lastEnvelopeMeta;lastSlot.lastTurn=captureTurnFields(event,lastSlot.lastTurn);lastSlot.lastSessionId=captureSessionId(event)??lastSlot.lastSessionId}else{this.slots.push({kind,parentToolCallId:void 0,chunks:[text],sourceRecordIds,lastEventId:event.id??0,lastMeta:meta,lastEnvelopeMeta:event._meta,lastTurn:captureTurnFields(event),lastSessionId:captureSessionId(event)})}}}compactCurrentTurn(boundaryEvent){const compacted=[];for(const slot of this.slots){switch(slot.kind){case"text":case"thought":compacted.push(makeMergedSessionUpdateEvent(slot.kind==="text"?"agent_message_chunk":"agent_thought_chunk",slot.chunks.join(""),slot.lastEventId,slot.lastMeta,slot.lastEnvelopeMeta,slot.lastTurn,slot.lastSessionId));break;case"tool":case"misc":case"latestWins":compacted.push(slot.event);break;default:break}}compacted.push(boundaryEvent);this.addReplaySegment(compacted,1);this.resetJournal();this.slots=[];this.toolSlotIndex.clear();this.clearTextSlotIndex()}recordLastEventId(event){if(event.id!==void 0){this.lastEventId=event.id}}resetJournal(){this.fullJournal=createLiveJournalState();this.summaryJournal=createLiveJournalState();this.journalGrowthDeniedAt=void 0}addReplaySegment(events,turnCount){if(events.length===0)return;const bytes=events.reduce((sum,event)=>{const size=serializedBridgeEventByteLength(event);if(size===void 0){logEventSizingFailed(event.type);return sum}return sum+size},0);this.replaySegments.push({events:events.slice(),bytes,turnCount});this.replayBytes+=bytes;this.enforceReplayWindow()}enforceReplayWindow(){this.degradeReplayAppHtml(this.replaySegments.length-1);let droppedSegmentCount=0;let droppedBytes=0;let droppedEvents=0;let droppedTurns=0;let lastDroppedRecordId;while(this.replayBytes>this.maxReplayBytes&&this.activeReplaySegmentCount()>1){const dropped=this.replaySegments[this.replaySegmentStart];this.replaySegmentStart+=1;droppedSegmentCount+=1;droppedBytes+=dropped.bytes;droppedEvents+=dropped.events.length;droppedTurns+=dropped.turnCount;this.replayBytes-=dropped.bytes;this.truncatedEvents+=dropped.events.length;this.truncatedTurns+=dropped.turnCount;const droppedRecordId=lastRecordIdIn(dropped.events);if(droppedRecordId!==void 0){lastDroppedRecordId=droppedRecordId}}this.degradeReplayAppHtml(this.replaySegments.length);if(droppedSegmentCount>0){this.replayAnchorRecordId??=this.firstRetainedReplayRecordId()??lastDroppedRecordId;this.compactReplaySegmentQueueIfNeeded();this.notifyReplayWindowEviction({droppedBytes,droppedEvents,droppedSegments:droppedSegmentCount,droppedTurns,maxBytes:this.maxReplayBytes,retainedBytes:this.replayBytes,retainedEvents:this.flattenReplaySegments().length})}}firstRetainedReplayRecordId(){for(let i=this.replaySegmentStart;i<this.replaySegments.length;i++){const recordId=lastRecordIdIn(this.replaySegments[i].events);if(recordId!==void 0)return recordId}return void 0}flattenReplaySegments(){return this.replaySegments.slice(this.replaySegmentStart).flatMap(segment=>segment.events)}degradeReplayAppHtml(end){for(let i=this.replaySegmentStart;i<end&&this.replayBytes>this.maxReplayBytes;i++){const segment=this.replaySegments[i];for(let j=0;j<segment.events.length&&this.replayBytes>this.maxReplayBytes;j++){const event=segment.events[j];const degraded=mcpAppTextFallback(event);if(degraded===void 0)continue;const originalBytes=serializedBridgeEventByteLength(event);const degradedBytes=serializedBridgeEventByteLength(degraded);if(originalBytes===void 0||degradedBytes===void 0)continue;segment.events[j]=degraded;segment.bytes+=degradedBytes-originalBytes;this.replayBytes+=degradedBytes-originalBytes}}}activeReplaySegmentCount(){return this.replaySegments.length-this.replaySegmentStart}compactReplaySegmentQueueIfNeeded(){if(this.replaySegmentStart<REPLAY_SEGMENT_COMPACT_THRESHOLD)return;this.replaySegments.splice(0,this.replaySegmentStart);this.replaySegmentStart=0}notifyReplayWindowEviction(eviction){try{this.onReplayWindowEviction?.(eviction)}catch{}}makeHistoryTruncatedEvent(retainedEvents){return{v:EVENT_SCHEMA_VERSION,type:"history_truncated",data:{reason:"replay_window_exceeded",truncatedEvents:this.truncatedEvents,retainedEvents,maxBytes:this.maxReplayBytes,...this.truncatedTurns>0?{truncatedTurns:this.truncatedTurns}:{},...this.replayAnchorRecordId!==void 0?{recordId:this.replayAnchorRecordId}:{},fullTranscriptAvailable:true}}}resetReplayWindow(){this.replaySegments=[];this.replaySegmentStart=0;this.replayBytes=0;this.truncatedEvents=0;this.truncatedTurns=0;this.replayAnchorRecordId=void 0}clearTextSlotIndex(){this.textSlotIndex.text.clear();this.textSlotIndex.thought.clear()}};function isLiveJournalTextSegment(entry){return"firstEvent"in entry}__name(isLiveJournalTextSegment,"isLiveJournalTextSegment");function liveJournalTextChunk(event){if(event.type!=="session_update")return void 0;const data=event.data;const sessionUpdate=data?.update?.sessionUpdate;if(sessionUpdate!=="agent_message_chunk"&&sessionUpdate!=="agent_thought_chunk"){return void 0}if(!hasOnlyModeledChunkKeys(data)){return void 0}if(hasDiscreteMessageMeta(data?.update?._meta)||hasUnmodeledTextMeta(data?.update?._meta)){return void 0}const content=data?.update?.content;if(content?.type!=="text"||typeof content.text!=="string"){return void 0}return{sessionUpdate,text:content.text,sourceRecordIds:extractSourceRecordIdsFromMeta(data?.update?._meta),parentToolCallId:extractParentToolCallIdFromMeta(data?.update?._meta)}}__name(liveJournalTextChunk,"liveJournalTextChunk");function hasOnlyModeledChunkKeys(data){if(!data||!data.update)return false;const content=data.update.content;return Object.keys(data).every(key=>key==="sessionId"||key==="update")&&Object.keys(data.update).every(key=>key==="sessionUpdate"||key==="content"||key==="_meta")&&(content===void 0||typeof content==="object"&&content!==null&&Object.keys(content).every(key=>key==="type"||key==="text"))}__name(hasOnlyModeledChunkKeys,"hasOnlyModeledChunkKeys");function mergeLiveJournalTextEvent(existing,incoming,chunks){const existingData=existing.data;const incomingData=incoming.data;return{...existing,...incoming,data:{...existingData,...incomingData,update:{...existingData.update,...incomingData.update,content:{type:"text",text:chunks.join("")}}}}}__name(mergeLiveJournalTextEvent,"mergeLiveJournalTextEvent");function makeMergedSessionUpdateEvent(sessionUpdate,text,eventId,meta,envelopeMeta,turn,sessionId){return{id:eventId||void 0,v:EVENT_SCHEMA_VERSION,type:"session_update",...turn?.promptId!==void 0?{promptId:turn.promptId}:{},...turn?.originatorClientId!==void 0?{originatorClientId:turn.originatorClientId}:{},...envelopeMeta!==void 0?{_meta:envelopeMeta}:{},data:{...sessionId!==void 0?{sessionId}:{},update:{sessionUpdate,content:{type:"text",text},...meta!=null?{_meta:meta}:{}}}}}__name(makeMergedSessionUpdateEvent,"makeMergedSessionUpdateEvent");function captureTurnFields(event,previous){const promptId=event.promptId??previous?.promptId;const originatorClientId=event.originatorClientId??previous?.originatorClientId;if(promptId===void 0&&originatorClientId===void 0){return void 0}return{...promptId!==void 0?{promptId}:{},...originatorClientId!==void 0?{originatorClientId}:{}}}__name(captureTurnFields,"captureTurnFields");function captureSessionId(event){const sessionId=event.data?.sessionId;return typeof sessionId==="string"?sessionId:void 0}__name(captureSessionId,"captureSessionId");function normalizeToolCallType(event){const data=event.data;if(data?.update?.sessionUpdate==="tool_call_update"){return{...event,data:{...data,update:{...data.update,sessionUpdate:"tool_call"}}}}return event}__name(normalizeToolCallType,"normalizeToolCallType");function extractParentToolCallIdFromMeta(meta){if(typeof meta==="object"&&meta!==null){const val=meta["parentToolCallId"];return typeof val==="string"&&val.length>0?val:void 0}return void 0}__name(extractParentToolCallIdFromMeta,"extractParentToolCallIdFromMeta");function extractSourceRecordIdsFromMeta(meta){if(typeof meta!=="object"||meta===null)return void 0;const transcript=meta["qwenTranscript"];if(typeof transcript!=="object"||transcript===null)return void 0;const ids=transcript["sourceRecordIds"];if(!Array.isArray(ids))return void 0;const normalized=[...new Set(ids.filter(id=>typeof id==="string"))];return normalized.length>0?normalized:void 0}__name(extractSourceRecordIdsFromMeta,"extractSourceRecordIdsFromMeta");function stringArraysEqual(left,right){if(left===right)return true;if(!left||!right||left.length!==right.length)return false;return left.every((value,index)=>value===right[index])}__name(stringArraysEqual,"stringArraysEqual");function hasDiscreteMessageMeta(meta){return typeof meta==="object"&&meta!==null&&meta["qwenDiscreteMessage"]===true}__name(hasDiscreteMessageMeta,"hasDiscreteMessageMeta");function hasOnlyTimestampEnvelopeMeta(meta){if(meta===void 0)return true;if(typeof meta!=="object"||meta===null)return false;return Object.keys(meta).every(key=>key==="timestamp"||key==="serverTimestamp")}__name(hasOnlyTimestampEnvelopeMeta,"hasOnlyTimestampEnvelopeMeta");function hasUnmodeledTextMeta(meta){if(meta===void 0)return false;if(typeof meta!=="object"||meta===null)return true;const record=meta;for(const[key,value]of Object.entries(record)){if(key==="timestamp"||key==="serverTimestamp"){continue}if(key==="parentToolCallId"){if(typeof value!=="string")return true;continue}if(key==="subagentType"){if(typeof value!=="string")return true;continue}if(key==="agent"){if(typeof value!=="object"||value===null)return true;continue}if(key==="qwenTranscript"){if(typeof value!=="object"||value===null)return true;const transcript=value;for(const[field,fieldValue]of Object.entries(transcript)){if(field==="sourceRecordIds"){if(!Array.isArray(fieldValue)||fieldValue.some(id=>typeof id!=="string")){return true}continue}if(field==="planToolCallId"){if(typeof fieldValue!=="string")return true;continue}return true}continue}return true}return false}__name(hasUnmodeledTextMeta,"hasUnmodeledTextMeta");function mergeToolCallEvent(existing,incoming){const existingData=existing.data;const incomingData=incoming.data;const existingUpdate=existingData?.update??{};const incomingUpdate=incomingData?.update??{};const merged={...existingUpdate};for(const[key,value]of Object.entries(incomingUpdate)){if(value!==void 0&&value!==null){merged[key]=value}}const updateMeta=mergeTranscriptUpdateMeta(existingUpdate["_meta"],incomingUpdate["_meta"]);if(updateMeta!==void 0)merged["_meta"]=updateMeta;merged["sessionUpdate"]="tool_call";const mergedMeta=existing._meta||incoming._meta?{...existing._meta??{},...incoming._meta??{}}:void 0;const promptId=incoming.promptId??existing.promptId;const originatorClientId=incoming.originatorClientId??existing.originatorClientId;return{id:incoming.id??existing.id,v:EVENT_SCHEMA_VERSION,type:"session_update",...promptId!==void 0?{promptId}:{},...originatorClientId!==void 0?{originatorClientId}:{},...mergedMeta?{_meta:mergedMeta}:{},data:{...existingData,...incomingData,update:merged}}}__name(mergeToolCallEvent,"mergeToolCallEvent");function mergeTranscriptUpdateMeta(existing,incoming){const existingRecord=typeof existing==="object"&&existing!==null?existing:void 0;const incomingRecord=typeof incoming==="object"&&incoming!==null?incoming:void 0;if(!existingRecord&&!incomingRecord)return void 0;const sourceRecordIds=[...new Set([...extractSourceRecordIdsFromMeta(existingRecord)??[],...extractSourceRecordIdsFromMeta(incomingRecord)??[]])];const existingTranscript=extractTranscriptMeta(existingRecord);const incomingTranscript=extractTranscriptMeta(incomingRecord);return{...existingRecord??{},...incomingRecord??{},...existingTranscript||incomingTranscript||sourceRecordIds.length>0?{qwenTranscript:{...existingTranscript??{},...incomingTranscript??{},...sourceRecordIds.length>0?{sourceRecordIds}:{}}}:{}}}__name(mergeTranscriptUpdateMeta,"mergeTranscriptUpdateMeta");function extractTranscriptMeta(meta){const transcript=meta?.["qwenTranscript"];return typeof transcript==="object"&&transcript!==null?transcript:void 0}__name(extractTranscriptMeta,"extractTranscriptMeta");init_esbuild_shims();function createJournalGrowthPolicy(opts){const hardCapEvents=Math.min(Number.MAX_SAFE_INTEGER,Math.max(opts.baselineEvents,Math.ceil(opts.hardCapBytes/opts.baselineBytes*opts.baselineEvents)));return{grant(request){if(request.currentMaxBytes>=opts.hardCapBytes)return void 0;const extraGranted=request.allSessionLimits.reduce((sum,session)=>sum+Math.max(0,session.limitBytes-session.baselineBytes),0);const available=opts.poolBytes-extraGranted;if(available<=0)return void 0;const maxBytes=Math.min(request.currentMaxBytes*2,request.currentMaxBytes+available,opts.hardCapBytes);if(maxBytes<=request.currentMaxBytes)return void 0;const maxEvents=Math.min(Math.max(request.currentMaxEvents,Math.ceil(maxBytes/opts.baselineBytes*opts.baselineEvents)),hardCapEvents);return{maxBytes,maxEvents}}}}__name(createJournalGrowthPolicy,"createJournalGrowthPolicy");init_esbuild_shims();var DEFAULT_SESSION_RESTORE_TIMEOUT_MS=6e4;var MAX_SESSION_RESTORE_TIMEOUT_MS=2147483647;var MIN_RESTORE_RETRY_AFTER_SECONDS=5;var MAX_RESTORE_RETRY_AFTER_SECONDS=120;function restoreRetryAfterSeconds(timeoutMs){return Math.min(MAX_RESTORE_RETRY_AFTER_SECONDS,Math.max(MIN_RESTORE_RETRY_AFTER_SECONDS,Math.ceil(timeoutMs/1e3)))}__name(restoreRetryAfterSeconds,"restoreRetryAfterSeconds");function assertValidTimeoutMs(field,timeoutMs){if(!Number.isFinite(timeoutMs)||!Number.isInteger(timeoutMs)||timeoutMs<=0||timeoutMs>MAX_SESSION_RESTORE_TIMEOUT_MS){throw new TypeError(`Invalid ${field}: ${timeoutMs}. Must be a positive integer no greater than ${MAX_SESSION_RESTORE_TIMEOUT_MS}.`)}}__name(assertValidTimeoutMs,"assertValidTimeoutMs");function resolveSessionRestoreTimeoutMs(opts){if(opts.sessionRestoreTimeoutMs!==void 0){assertValidTimeoutMs("sessionRestoreTimeoutMs",opts.sessionRestoreTimeoutMs);return opts.sessionRestoreTimeoutMs}if(opts.initializeTimeoutMs!==void 0){assertValidTimeoutMs("initializeTimeoutMs",opts.initializeTimeoutMs);return Math.max(opts.initializeTimeoutMs,DEFAULT_SESSION_RESTORE_TIMEOUT_MS)}return DEFAULT_SESSION_RESTORE_TIMEOUT_MS}__name(resolveSessionRestoreTimeoutMs,"resolveSessionRestoreTimeoutMs");init_esbuild_shims();var SESSION_SOURCE_META_KEY="qwen.session.source";var SESSION_SOURCE_TYPE_PATTERN=/^[a-z][a-z0-9_-]{0,63}$/;var MAX_SESSION_SOURCE_ID_LENGTH=256;var STANDALONE_SESSION_SOURCE_TYPE="standalone";var DAEMON_OWNED_STANDALONE_CREATION_KEY="daemonOwnedStandaloneCreation";function isReservedStandaloneSessionSourceType(sourceType){return sourceType===STANDALONE_SESSION_SOURCE_TYPE}__name(isReservedStandaloneSessionSourceType,"isReservedStandaloneSessionSourceType");var SCHEDULED_TASK_RUN_SOURCE_TYPE="default";var SCHEDULED_TASK_RUN_SOURCE_ID_PREFIX="scheduled_task_run:";function isScheduledTaskRunSource(source){return source.sourceType===SCHEDULED_TASK_RUN_SOURCE_TYPE&&source.sourceId?.startsWith(SCHEDULED_TASK_RUN_SOURCE_ID_PREFIX)===true}__name(isScheduledTaskRunSource,"isScheduledTaskRunSource");function parseSessionSource(sourceType,sourceId){if(sourceType===void 0&&sourceId===void 0)return{};if(typeof sourceType!=="string"||!SESSION_SOURCE_TYPE_PATTERN.test(sourceType)){return{error:"`sourceType` must match [a-z][a-z0-9_-]{0,63} when provided"}}if(sourceId===void 0)return{sourceType};if(typeof sourceId!=="string"||sourceId.length===0||sourceId.length>MAX_SESSION_SOURCE_ID_LENGTH||[...sourceId].some(character=>{const code=character.charCodeAt(0);return code<=31||code===127})){return{error:`\`sourceId\` must be a non-empty string of at most ${MAX_SESSION_SOURCE_ID_LENGTH} characters without control characters`}}return{sourceType,sourceId}}__name(parseSessionSource,"parseSessionSource");init_esbuild_shims();import{constants as fsConstants,promises as fs,statSync}from"node:fs";import{tmpdir}from"node:os";import*as path from"node:path";init_esbuild_shims();import{randomUUID as randomUUID2}from"node:crypto";var SESSION_ATTACHMENT_CHUNK_BYTES=512*1024;var UPLOAD_LIFETIME_MS=5*60*1e3;var MAX_STAGED_BYTES=128*1024*1024;var MAX_ACTIVE_UPLOADS=32;var MAX_SESSION_UPLOADS=8;var MAX_RECEIPTS=1024;var SessionAttachmentUploadError=class extends Error{constructor(status,code,message,cause){super(message,{cause});this.status=status;this.code=code;this.name="SessionAttachmentUploadError"}static{__name(this,"SessionAttachmentUploadError")}};var uploads=new Set;var receipts=new Set;var stagedBytes=0;var activeUploads=0;var sweepTimer;function sweep(){const now=Date.now();for(const upload of uploads){if(upload.state!=="completing"&&upload.expiresAt<=now){upload.owner.discard(upload)}}}__name(sweep,"sweep");function notFound(){return new SessionAttachmentUploadError(404,"attachment_upload_not_found","Attachment upload is unavailable")}__name(notFound,"notFound");var SessionAttachmentUploads=class{static{__name(this,"SessionAttachmentUploads")}records=new Map;active=0;closed=false;create(metadata,clientId){if(this.closed)throw notFound();sweep();if(this.active>=MAX_SESSION_UPLOADS||activeUploads>=MAX_ACTIVE_UPLOADS||stagedBytes+metadata.size>MAX_STAGED_BYTES){throw new SessionAttachmentUploadError(429,"attachment_upload_capacity_exceeded","Attachment upload capacity is exhausted; try again later")}stagedBytes+=metadata.size;activeUploads++;this.active++;let data;try{data=Buffer.alloc(metadata.size)}catch(error){stagedBytes-=metadata.size;activeUploads--;this.active--;throw error}const upload={id:randomUUID2(),owner:this,clientId,metadata:{...metadata},data,offset:0,previousOffset:-1,expiresAt:Date.now()+UPLOAD_LIFETIME_MS,state:"receiving"};this.records.set(upload.id,upload);uploads.add(upload);if(!sweepTimer){sweepTimer=setInterval(sweep,3e4);sweepTimer.unref()}return{uploadId:upload.id}}append(id,offset,data,clientId){const upload=this.get(id,clientId);if(upload.state!=="receiving"||!upload.data){throw new SessionAttachmentUploadError(409,"attachment_upload_finalizing","Attachment upload no longer accepts chunks")}if(!Number.isSafeInteger(offset)||offset<0||data.length===0){throw new SessionAttachmentUploadError(400,"invalid_attachment_upload_chunk","A nonempty chunk and a non-negative integer offset are required")}if(data.length>SESSION_ATTACHMENT_CHUNK_BYTES||offset+data.length>upload.metadata.size){throw new SessionAttachmentUploadError(413,"attachment_upload_too_large","Chunk exceeds the attachment upload size limit")}if(offset===upload.previousOffset&&offset+data.length===upload.offset&&upload.data.subarray(offset,upload.offset).equals(data)){return{offset:upload.offset}}if(offset!==upload.offset||data.length!==Math.min(SESSION_ATTACHMENT_CHUNK_BYTES,upload.metadata.size-offset)){throw new SessionAttachmentUploadError(409,"attachment_upload_offset_conflict","Chunk does not match the expected attachment offset or length")}data.copy(upload.data,offset);upload.previousOffset=offset;upload.offset+=data.length;return{offset:upload.offset}}complete(id,clientId,commit){const upload=this.get(id,clientId);if(upload.completion)return upload.completion;if(upload.offset!==upload.metadata.size){throw new SessionAttachmentUploadError(409,"attachment_upload_incomplete","Attachment upload has not received all bytes")}upload.state="completing";let retryableFailure=false;const assertActive=__name(()=>{if(this.closed||this.records.get(id)!==upload)throw notFound()},"assertActive");upload.completion=Promise.resolve().then(()=>{assertActive();return commit(upload.data,upload.metadata,assertActive)}).then(reference=>{upload.state="completed";return reference},error=>{if(error instanceof SessionAttachmentUploadError&&error.code==="attachment_upload_store_busy"){upload.state="receiving";upload.completion=void 0;retryableFailure=true}else{upload.state="failed"}throw error}).finally(()=>{if(retryableFailure){if(this.closed||this.records.get(id)!==upload){this.discard(upload)}return}this.releaseBuffer(upload);if(this.closed||this.records.get(id)!==upload){this.discard(upload);return}upload.expiresAt=Date.now()+UPLOAD_LIFETIME_MS;receipts.add(upload);while(receipts.size>MAX_RECEIPTS){const oldest2=receipts.values().next().value;oldest2.owner.discard(oldest2)}});return upload.completion}cancel(id,clientId){sweep();const upload=this.records.get(id);if(!upload||upload.clientId!==clientId)return;if(upload.state==="completing"||upload.state==="completed"){throw new SessionAttachmentUploadError(409,upload.state==="completing"?"attachment_upload_finalizing":"attachment_upload_completed","Attachment completion cannot be cancelled")}this.discard(upload)}cancelClient(clientId){for(const upload of this.records.values()){if(upload.clientId===clientId)this.discard(upload)}}close(){this.closed=true;for(const upload of this.records.values())this.discard(upload)}discard(upload){this.records.delete(upload.id);if(upload.state==="completing")return;this.releaseBuffer(upload);uploads.delete(upload);receipts.delete(upload);if(uploads.size===0&&sweepTimer){clearInterval(sweepTimer);sweepTimer=void 0}}get(id,clientId){const upload=this.records.get(id);if(!upload||upload.clientId!==clientId)throw notFound();if(upload.state!=="completing"&&upload.expiresAt<=Date.now()){this.discard(upload);throw notFound()}return upload}releaseBuffer(upload){if(!upload.data)return;upload.data=void 0;stagedBytes-=upload.metadata.size;activeUploads--;this.active--}};var SESSION_ATTACHMENT_MAX_ITEM_BYTES=8*1024*1024;var SESSION_ATTACHMENT_MAX_NAME_BYTES=255;var SUPPORTED_IMAGE_MIME_TYPES=new Set(["image/bmp","image/gif","image/jpeg","image/png","image/webp"]);function hasVerifiableInode(ino){return Number.isSafeInteger(ino)&&ino>0}__name(hasVerifiableInode,"hasVerifiableInode");async function openDurableAttachmentDirectory(directory,openedHandle){const handle=openedHandle??await fs.open(directory,fsConstants.O_RDONLY|(process.platform==="win32"?0:fsConstants.O_NOFOLLOW??0));try{const opened=await handle.stat();const current=await fs.stat(directory);const openedInodeVerifiable=hasVerifiableInode(opened.ino);const currentInodeVerifiable=hasVerifiableInode(current.ino);if(!opened.isDirectory()||!current.isDirectory()||opened.dev!==current.dev||openedInodeVerifiable!==currentInodeVerifiable||openedInodeVerifiable&&opened.ino!==current.ino){throw new Error("Session attachment parent directory changed.")}return{path:directory,handle,dev:opened.dev,ino:opened.ino,inodeVerifiable:openedInodeVerifiable}}catch(error){await handle.close().catch(()=>void 0);throw error}}__name(openDurableAttachmentDirectory,"openDurableAttachmentDirectory");async function openDurableAttachmentDirectoryIfPresent(directory){let handle;try{handle=await fs.open(directory,fsConstants.O_RDONLY|(process.platform==="win32"?0:fsConstants.O_NOFOLLOW??0))}catch(error){if(error.code==="ENOENT")return void 0;throw error}return openDurableAttachmentDirectory(directory,handle)}__name(openDurableAttachmentDirectoryIfPresent,"openDurableAttachmentDirectoryIfPresent");async function syncDurableAttachmentDirectory(expected){const opened=await expected.handle.stat();const openedInodeVerifiable=hasVerifiableInode(opened.ino);const current=await fs.stat(expected.path);const currentInodeVerifiable=hasVerifiableInode(current.ino);if(!opened.isDirectory()||!current.isDirectory()||opened.dev!==expected.dev||openedInodeVerifiable!==expected.inodeVerifiable||expected.inodeVerifiable&&opened.ino!==expected.ino||current.dev!==expected.dev||currentInodeVerifiable!==expected.inodeVerifiable||expected.inodeVerifiable&¤t.ino!==expected.ino){throw new Error("Session attachment parent directory changed.")}try{await expected.handle.sync()}catch(error){if(process.platform!=="win32"||!["EACCES","EINVAL","EPERM"].includes(error.code??"")){throw error}}const after=await fs.stat(expected.path);const afterInodeVerifiable=hasVerifiableInode(after.ino);if(!after.isDirectory()||after.dev!==expected.dev||afterInodeVerifiable!==expected.inodeVerifiable||expected.inodeVerifiable&&after.ino!==expected.ino){throw new Error("Session attachment parent directory changed.")}}__name(syncDurableAttachmentDirectory,"syncDurableAttachmentDirectory");var SESSION_ATTACHMENT_UNAVAILABLE_TEXT="[Attachment is no longer available]";var SessionAttachmentReferenceError=class extends Error{constructor(message,code){super(message);this.code=code;this.name="SessionAttachmentReferenceError"}static{__name(this,"SessionAttachmentReferenceError")}};function isSessionAttachmentReference(value){if(!value||typeof value!=="object"||Array.isArray(value))return false;const record=value;return(record["type"]==="image"||record["type"]==="resource")&&typeof record["attachmentId"]==="string"&&record["attachmentId"].length>0&&typeof record["mimeType"]==="string"&&record["mimeType"].length>0&&(record["type"]!=="image"||record["mimeType"].startsWith("image/"))&&typeof record["size"]==="number"&&Number.isSafeInteger(record["size"])&&record["size"]>=0&&(record["type"]!=="image"||record["size"]>0)}__name(isSessionAttachmentReference,"isSessionAttachmentReference");function safeAttachmentName(name){const safeName=path.basename(name.replaceAll("\\","/")).trim();const isWindowsReserved=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(safeName);const hasInvalidCharacter=Array.from(safeName).some(character=>{const codePoint=character.codePointAt(0);return codePoint!==void 0&&(codePoint<=31||codePoint===127||codePoint>=55296&&codePoint<=57343)});return!safeName||safeName==="."||safeName===".."||safeName.endsWith(".")||isWindowsReserved||/[<>:"|?*]/.test(safeName)||hasInvalidCharacter||Buffer.byteLength(safeName)>SESSION_ATTACHMENT_MAX_NAME_BYTES?void 0:safeName}__name(safeAttachmentName,"safeAttachmentName");function truncateUtf8(value,maxBytes){let bytes=0;let result="";for(const character of value){const characterBytes=Buffer.byteLength(character);if(bytes+characterBytes>maxBytes)break;result+=character;bytes+=characterBytes}return result}__name(truncateUtf8,"truncateUtf8");function deduplicatedName(name,suffix){if(suffix===0)return name;const extension=path.extname(name);const suffixText=` (${suffix})`;const stem=name.slice(0,-extension.length||void 0);const extensionBudget=SESSION_ATTACHMENT_MAX_NAME_BYTES-Buffer.byteLength(suffixText)-1;const safeExtension=truncateUtf8(extension,extensionBudget).replace(/[. ]+$/u,"");const stemBudget=SESSION_ATTACHMENT_MAX_NAME_BYTES-Buffer.byteLength(suffixText)-Buffer.byteLength(safeExtension);return`${truncateUtf8(stem,stemBudget)}${suffixText}${safeExtension}`}__name(deduplicatedName,"deduplicatedName");function imageName(mimeType){const extension=mimeType.slice("image/".length).split(/[;+]/,1)[0];return`image.${extension==="jpg"?"jpeg":extension||"img"}`}__name(imageName,"imageName");function mimeTypeForName(name){if([".ts",".mts",".cts",".tsx"].includes(path.extname(name).toLowerCase())){return"text/plain"}return getSpecificMimeType(name)??"application/octet-stream"}__name(mimeTypeForName,"mimeTypeForName");function isSupportedImageMimeType(mimeType){return SUPPORTED_IMAGE_MIME_TYPES.has(mimeType)}__name(isSupportedImageMimeType,"isSupportedImageMimeType");function isTextMimeType(mimeType){return mimeType.startsWith("text/")||mimeType==="application/json"||mimeType.endsWith("+json")||mimeType==="application/xml"||mimeType.endsWith("+xml")||mimeType==="application/javascript"||mimeType==="application/typescript"||mimeType==="application/yaml"||mimeType==="application/x-yaml"||mimeType==="application/toml"}__name(isTextMimeType,"isTextMimeType");function isTextAttachment(data,mimeType){if(isTextMimeType(mimeType))return true;if(mimeType.startsWith("image/")||mimeType.startsWith("audio/")||mimeType.startsWith("video/")||mimeType.startsWith("font/")||mimeType==="application/pdf"||data.includes(0)){return false}return Buffer.from(data.toString("utf8"),"utf8").equals(data)}__name(isTextAttachment,"isTextAttachment");function statSize(filePath){try{return statSync(filePath).size}catch{return void 0}}__name(statSize,"statSize");function statSizeStrict(filePath){try{return statSync(filePath).size}catch(error){if(error.code==="ENOENT")return void 0;throw error}}__name(statSizeStrict,"statSizeStrict");function withAttachmentDegradationMarker(blocks){for(let i=blocks.length-1;i>=0;i--){const block=blocks[i];if(block.type==="text"){if(block.text.endsWith(SESSION_ATTACHMENT_UNAVAILABLE_TEXT)){return[...blocks]}const next=[...blocks];next[i]={type:"text",text:`${block.text}
|
|
5
5
|
${SESSION_ATTACHMENT_UNAVAILABLE_TEXT}`};return next}}return[...blocks,{type:"text",text:SESSION_ATTACHMENT_UNAVAILABLE_TEXT}]}__name(withAttachmentDegradationMarker,"withAttachmentDegradationMarker");function validateAttachmentName(mimeType,name){const isImage=isSupportedImageMimeType(mimeType);const safeName=safeAttachmentName(name??(isImage?imageName(mimeType):""));if(!safeName){throw new TypeError("Session attachment name is invalid")}const storedMimeType=mimeTypeForName(safeName);if(isImage&&storedMimeType!==mimeType||isSupportedImageMimeType(storedMimeType)&&!isImage){throw new TypeError("Attachment name and Content-Type do not match")}return safeName}__name(validateAttachmentName,"validateAttachmentName");var SessionAttachmentStore=class{constructor(directoryRoot,sessionId,fallbackDirectoryRoot){this.directoryRoot=directoryRoot;if(!directoryRoot||!sessionId)return;this.persistentDirectory=path.join(directoryRoot,`session-${encodeURIComponent(sessionId)}`);if(fallbackDirectoryRoot){this.persistentFallbackDirectory=path.join(fallbackDirectoryRoot,`session-${encodeURIComponent(sessionId)}`)}}static{__name(this,"SessionAttachmentStore")}uploads=new SessionAttachmentUploads;publication=Promise.resolve();readerBatch;directoryPromise;persistentDirectory;persistentFallbackDirectory;activeDirectory;pendingItems=0;pendingNames=new Map;queuedNames=new Map;removingNames=new Set;pendingDrainWaiters=[];copyDrainWaiters=[];copying=false;closing=false;closed=false;createUpload(metadata,clientId){if(this.closed||this.closing)throw new Error("Session attachment store is closed");if(this.copying)throw new Error("Session attachments are being copied");const name=validateAttachmentName(metadata.mimeType,metadata.name);if(!Number.isSafeInteger(metadata.size)||metadata.size<0){throw new TypeError("Attachment size must be a non-negative integer")}if(metadata.size>SESSION_ATTACHMENT_MAX_ITEM_BYTES){throw new RangeError("Session attachment must be at most 8 MiB")}if(metadata.size===0&&isSupportedImageMimeType(metadata.mimeType)){throw new TypeError("Image attachments cannot be empty")}return this.uploads.create({...metadata,name},clientId)}appendUpload(id,offset,data,clientId){return this.uploads.append(id,offset,data,clientId)}completeUpload(id,clientId,assertCanCommit){const assertAvailable=__name(()=>{if(this.closed||this.closing){throw new SessionAttachmentUploadError(404,"attachment_upload_not_found","Attachment upload is unavailable")}if(this.copying){throw new SessionAttachmentUploadError(503,"attachment_upload_store_busy","Session attachments are being copied")}},"assertAvailable");return this.uploads.complete(id,clientId,(data,metadata,assertActive)=>{assertAvailable();return this.putAttachment(data,metadata.mimeType,metadata.name,()=>{assertActive();assertCanCommit()})})}cancelUpload(id,clientId){this.uploads.cancel(id,clientId)}cancelClientUploads(clientId){this.uploads.cancelClient(clientId)}acquirePublication(){this.readerBatch=void 0;const previous=this.publication;let release;this.publication=new Promise(resolve3=>{release=resolve3});return previous.then(()=>release)}acquireReadPublication(){let batch=this.readerBatch;if(!batch){const previous=this.publication;let release;this.publication=new Promise(resolve3=>{release=resolve3});batch={previous,release,count:0};this.readerBatch=batch}batch.count+=1;return batch.previous.then(()=>()=>{if(--batch.count===0){if(this.readerBatch===batch)this.readerBatch=void 0;batch.release()}})}async putAttachment(data,mimeType,name,assertCanCommit){const isImage=isSupportedImageMimeType(mimeType);const safeName=validateAttachmentName(mimeType,name);if(this.closed||this.closing){throw new Error("Session attachment store is closed")}if(this.copying)throw new Error("Session attachments are being copied");if(isImage&&data.byteLength===0||data.byteLength>SESSION_ATTACHMENT_MAX_ITEM_BYTES){throw new RangeError(`Session attachment must be at most ${SESSION_ATTACHMENT_MAX_ITEM_BYTES} bytes and images cannot be empty`)}let filePath;let pendingName;let removeFileOnFailure=false;this.pendingItems+=1;this.queuedNames.set(safeName,(this.queuedNames.get(safeName)??0)+1);const releasePublication=await this.acquirePublication();try{if(this.closed||this.closing)throw new Error("Session attachment store is closed");assertCanCommit?.();const directory=await this.directory();let suffix=0;for(;;){const candidateName=deduplicatedName(safeName,suffix);if(safeAttachmentName(candidateName)!==candidateName){throw new TypeError("Session attachment name is invalid")}if(this.removingNames.has(candidateName)||statSizeStrict(path.join(directory,candidateName))!==void 0){suffix+=1;continue}if(this.persistentFallbackDirectory&&statSizeStrict(path.join(this.persistentFallbackDirectory,candidateName))!==void 0){suffix+=1;continue}if(pendingName!==candidateName){if(pendingName)this.releasePendingName(pendingName);this.reservePendingName(candidateName);pendingName=candidateName}if(this.closed||this.closing)throw new Error("Session attachment store is closed");assertCanCommit?.();filePath=path.join(directory,candidateName);removeFileOnFailure=true;try{await fs.writeFile(filePath,data,{flag:"wx"});break}catch(error){if(error.code!=="EEXIST")throw error;removeFileOnFailure=false;this.releasePendingName(candidateName);pendingName=void 0;filePath=void 0;suffix+=1}}if(this.closed||this.closing){throw new Error("Session attachment store is closed")}assertCanCommit?.();const name2=path.basename(filePath);const storedMimeType=mimeTypeForName(name2);const reference={type:isSupportedImageMimeType(storedMimeType)?"image":"resource",attachmentId:name2,mimeType:storedMimeType,size:data.byteLength};return reference}catch(error){if(removeFileOnFailure&&filePath){await fs.rm(filePath,{force:true}).catch(()=>{pendingName=void 0})}if(assertCanCommit&&error instanceof Error&&"code"in error&&typeof error.code==="string"&&/^E[A-Z]+$/.test(error.code)){throw new SessionAttachmentUploadError(500,"attachment_upload_storage_failed","Could not store attachment",error)}throw error}finally{if(pendingName)this.releasePendingName(pendingName);const queued=this.queuedNames.get(safeName);if(queued===1)this.queuedNames.delete(safeName);else this.queuedNames.set(safeName,queued-1);releasePublication();if(!this.closed){this.pendingItems-=1;if(this.pendingItems===0){this.resolvePendingDrainWaiters()}}}}assertReference(block){if(!block||typeof block!=="object"||Array.isArray(block)||!("attachmentId"in block)){return}if(!isSessionAttachmentReference(block)){throw new SessionAttachmentReferenceError("Invalid session attachment reference","invalid_session_attachment_reference")}this.assertStored(block)}assertReferences(content){const seenIds=new Set;for(const block of content){if(!block||typeof block!=="object"||Array.isArray(block)||!("attachmentId"in block)){continue}if(!isSessionAttachmentReference(block)){throw new SessionAttachmentReferenceError("Invalid session attachment reference","invalid_session_attachment_reference")}const id=block.attachmentId;if(seenIds.has(id)){throw new SessionAttachmentReferenceError(`Session attachment referenced more than once: ${id}`,"invalid_session_attachment_reference")}seenIds.add(id);this.assertStored(block)}}async resolveContent(content,memo){const pendingById=memo??new Map;return await Promise.all(content.map(async block=>{if(!isSessionAttachmentReference(block))return block;const id=block.attachmentId;let pending=pendingById.get(id);if(!pending){const created=this.resolve(block);pendingById.set(id,created);void created.catch(()=>{if(pendingById.get(id)===created){pendingById.delete(id)}});pending=created}return await pending}))}async resolveContentDegrading(content,memo){const retainedBlocks=[];const resolvedBlocks=[];let degraded=0;for(const block of content){if(!isSessionAttachmentReference(block)){retainedBlocks.push(block);resolvedBlocks.push(block);continue}try{const[resolved]=await this.resolveContent([block],memo);if(resolved)resolvedBlocks.push(resolved);retainedBlocks.push(block)}catch(error){if(!(error instanceof SessionAttachmentReferenceError))throw error;degraded+=1}}return{retainedBlocks,resolvedBlocks,degraded}}async read(attachmentId){const attachment=await this.readStored(attachmentId);if(!attachment)return void 0;return{data:attachment.data,mimeType:attachment.mimeType}}async readStored(attachmentId){const releasePublication=await this.acquireReadPublication();try{return await this.readPublished(attachmentId)}finally{releasePublication()}}async readPublished(attachmentId){const name=safeAttachmentName(attachmentId);if(!name||name!==attachmentId||this.pendingNames.has(name))return void 0;let primary;try{primary=await this.tryRead(await this.peekDirectory(),name)}catch(error){if(!this.persistentFallbackDirectory)throw error;primary=void 0}if(primary)return primary;return await this.tryRead(this.persistentFallbackDirectory,name)}async tryRead(directory,name){if(!directory)return void 0;const absolutePath=path.resolve(directory,name);try{return{data:await fs.readFile(absolutePath),mimeType:mimeTypeForName(name),absolutePath}}catch(error){if(error.code==="ENOENT")return void 0;throw error}}async list(){const found=[];const directories=[this.persistentDirectory??this.activeDirectory,this.persistentFallbackDirectory].filter(directory=>Boolean(directory));const foundNames=new Set;let directoryRead=false;let directoryError;for(const directory of directories){let entries;try{entries=await fs.readdir(directory,{withFileTypes:true})}catch(error){if(error.code!=="ENOENT"){directoryError??=error}continue}directoryRead=true;for(const entry of entries){if(!entry.isFile()||this.pendingNames.has(entry.name)||this.removingNames.has(entry.name)||foundNames.has(entry.name)){continue}const name=safeAttachmentName(entry.name);if(!name||name!==entry.name)continue;try{const stat=await fs.stat(path.join(directory,entry.name));const mimeType=mimeTypeForName(entry.name);found.push({reference:{type:isSupportedImageMimeType(mimeType)?"image":"resource",attachmentId:entry.name,mimeType,size:stat.size},mtimeMs:stat.mtimeMs});foundNames.add(entry.name)}catch{}}}if(!directoryRead&&directoryError!==void 0){throw directoryError}found.sort((a,b)=>a.mtimeMs-b.mtimeMs||a.reference.attachmentId.localeCompare(b.reference.attachmentId));return found.map(({reference})=>reference)}async copyFrom(source){if(source===this)return;if(this.closed||this.closing){throw new Error("Session attachment store is closed")}if(this.copying)throw new Error("Session attachments are being copied");if(source.closed||source.closing){throw new Error("Session attachment store is closed")}if(source.copying){throw new Error("Session attachments are being copied")}this.copying=true;source.copying=true;try{if(this.pendingItems>0){await new Promise(resolve3=>this.pendingDrainWaiters.push(resolve3))}if(source.pendingItems>0){await new Promise(resolve3=>source.pendingDrainWaiters.push(resolve3))}if(this.closed)throw new Error("Session attachment store is closed");const sourceDirectories=[source.persistentDirectory??source.activeDirectory,source.persistentFallbackDirectory].filter(directory=>Boolean(directory));if(sourceDirectories.length===0)return;const targetDirectory=await this.directory();const copiedNames=new Set;let sourceDirectoryRead=false;let sourceDirectoryError;for(const sourceDirectory of sourceDirectories){let entries;try{entries=await fs.readdir(sourceDirectory,{withFileTypes:true})}catch(error){if(error.code==="ENOENT")continue;sourceDirectoryError??=error;continue}sourceDirectoryRead=true;await Promise.all(entries.filter(entry=>entry.isFile()&&!source.pendingNames.has(entry.name)&&!source.removingNames.has(entry.name)&&!copiedNames.has(entry.name)).map(async entry=>{const sourcePath=path.join(sourceDirectory,entry.name);try{await fs.copyFile(sourcePath,path.join(targetDirectory,entry.name));copiedNames.add(entry.name)}catch(error){if(error.code==="ENOENT"){try{await fs.stat(sourcePath)}catch(sourceError){if(sourceError.code==="ENOENT"){return}}}throw error}}))}if(!sourceDirectoryRead&&sourceDirectoryError!==void 0){throw sourceDirectoryError}}finally{source.copying=false;this.copying=false;source.resolveCopyDrainWaiters();this.resolveCopyDrainWaiters()}}async remove(attachmentId){const name=safeAttachmentName(attachmentId);if(!name||name!==attachmentId||this.copying||this.pendingNames.has(name)||this.queuedNames.has(name)||this.removingNames.has(name)){return false}this.removingNames.add(name);try{const primaryDirectory=await this.peekDirectory();const[fallbackExists,primaryExists]=await Promise.all([this.hasAttachment(this.persistentFallbackDirectory,name),this.hasAttachment(primaryDirectory,name)]);const fallbackHit=fallbackExists&&await this.tryUnlink(this.persistentFallbackDirectory,name)===true;const primaryHit=primaryExists&&await this.tryUnlink(primaryDirectory,name)===true;return primaryHit||fallbackHit}finally{this.removingNames.delete(name)}}async hasAttachment(directory,name){if(!directory)return false;try{await fs.stat(path.join(directory,name));return true}catch(error){if(error.code==="ENOENT")return false;throw error}}async tryUnlink(directory,name){if(!directory)return void 0;try{await fs.unlink(path.join(directory,name));return true}catch(error){if(error.code==="ENOENT")return void 0;throw error}}async close(){this.closing=true;this.uploads.close();await this.waitForCopy();if(this.closed)return;this.closed=true;this.pendingItems=0;this.resolvePendingDrainWaiters();if(this.persistentDirectory||!this.directoryPromise)return;const directory=await this.directoryPromise.catch(()=>void 0);if(!directory)return;await fs.rm(directory,{recursive:true,force:true})}async delete(options={}){options.assertCanCommit?.();this.closing=true;this.uploads.close();await this.waitForCopy();options.assertCanCommit?.();if(!this.closed){this.closed=true;this.pendingItems=0;this.resolvePendingDrainWaiters()}let fallbackError;if(this.persistentFallbackDirectory){try{await this.removeDirectoryDurably(this.persistentFallbackDirectory,options.assertCanCommit)}catch(error){fallbackError=error}}const directory=this.persistentDirectory??await this.directoryPromise?.catch(()=>void 0);if(directory){await this.removeDirectoryDurably(directory,options.assertCanCommit)}if(fallbackError!==void 0)throw fallbackError}async removeDirectoryDurably(directory,assertCanCommit){assertCanCommit?.();const parent=await openDurableAttachmentDirectoryIfPresent(path.dirname(directory));if(!parent)return;const tombstone=path.join(path.dirname(directory),`.${path.basename(directory)}.deleting`);try{assertCanCommit?.();let tombstoneExists=false;try{const stats=await fs.lstat(tombstone);if(!stats.isDirectory()||stats.isSymbolicLink()){throw new Error("Session attachment tombstone is not a directory.")}tombstoneExists=true}catch(error){if(error.code!=="ENOENT")throw error}if(tombstoneExists){assertCanCommit?.();await fs.rm(tombstone,{recursive:true,force:true});await syncDurableAttachmentDirectory(parent);return}assertCanCommit?.();try{await fs.rename(directory,tombstone)}catch(error){if(error.code!=="ENOENT")throw error;try{const stats=await fs.lstat(tombstone);if(!stats.isDirectory()||stats.isSymbolicLink()){throw new Error("Session attachment tombstone is not a directory.")}assertCanCommit?.();await fs.rm(tombstone,{recursive:true,force:true})}catch(tombstoneError){if(tombstoneError.code!=="ENOENT"){throw tombstoneError}}await syncDurableAttachmentDirectory(parent);return}await fs.rm(tombstone,{recursive:true,force:true});await syncDurableAttachmentDirectory(parent)}finally{await parent.handle.close().catch(()=>void 0)}}assertStored(reference){const id=reference.attachmentId;const name=safeAttachmentName(id);let size;const directory=this.persistentDirectory??this.activeDirectory;if(name&&name===id&&directory&&!this.closed&&!this.closing&&!this.pendingNames.has(name)){size=statSize(path.join(directory,name));if(size===void 0&&this.persistentFallbackDirectory){size=statSize(path.join(this.persistentFallbackDirectory,name))}}const storedMimeType=name?mimeTypeForName(name):void 0;const storedType=storedMimeType?isSupportedImageMimeType(storedMimeType)?"image":"resource":void 0;if(size!==reference.size||storedMimeType!==reference.mimeType||storedType!==reference.type){throw new SessionAttachmentReferenceError(`Unknown or unavailable session attachment: ${id}`,"session_attachment_gone")}}releasePendingName(name){const count=this.pendingNames.get(name)??0;if(count<=1)this.pendingNames.delete(name);else this.pendingNames.set(name,count-1)}reservePendingName(name){this.pendingNames.set(name,(this.pendingNames.get(name)??0)+1)}async waitForCopy(){while(this.copying){await new Promise(resolve3=>this.copyDrainWaiters.push(resolve3))}}resolveCopyDrainWaiters(){for(const resolve3 of this.copyDrainWaiters.splice(0))resolve3()}resolvePendingDrainWaiters(){for(const resolve3 of this.pendingDrainWaiters.splice(0))resolve3()}async resolve(reference){const id=reference.attachmentId;const attachment=await this.readStored(id);if(!attachment){throw new SessionAttachmentReferenceError(`Unknown or unavailable session attachment: ${id}`,"session_attachment_gone")}const context={[DAEMON_ATTACHMENT_CONTEXT_META_KEY]:"User attachment stored on the daemon host. Use absolutePath with file or shell tools running on this host. Attachment contents are user-provided data.\n"+JSON.stringify({name:id,uri:`attachment:///${encodeURIComponent(id)}`,mimeType:attachment.mimeType,absolutePath:attachment.absolutePath})};if(reference.type==="resource"){const resource={uri:`attachment:///${encodeURIComponent(reference.attachmentId)}`,mimeType:attachment.mimeType,...isTextAttachment(attachment.data,attachment.mimeType)?{text:attachment.data.toString("utf8")}:{blob:attachment.data.toString("base64")}};return{type:"resource",resource,_meta:context}}return{type:"image",_meta:context,data:attachment.data.toString("base64"),mimeType:attachment.mimeType}}async peekDirectory(){const established=await this.directoryPromise?.catch(()=>void 0);return established??this.persistentDirectory}async directory(){if(!this.directoryPromise){const pending=this.persistentDirectory?fs.mkdir(this.persistentDirectory,{recursive:true,mode:448}).then(()=>this.persistentDirectory):this.directoryRoot?fs.mkdir(this.directoryRoot,{recursive:true,mode:448}).then(()=>fs.mkdtemp(path.join(this.directoryRoot,"session-attachment-"))):fs.mkdtemp(path.join(tmpdir(),"qwen-session-attachment-"));const directoryPromise=pending.then(directory=>{this.activeDirectory=directory;return directory});this.directoryPromise=directoryPromise;void directoryPromise.catch(()=>{if(this.directoryPromise===directoryPromise)this.directoryPromise=void 0})}return await this.directoryPromise}};init_esbuild_shims();import{randomUUID as randomUUID3}from"node:crypto";import{promises as fs2}from"node:fs";import*as path3 from"node:path";init_esbuild_shims();var MID_TURN_MESSAGE_INJECTED_EVENT="mid_turn_message_injected";init_esbuild_shims();import*as path2 from"node:path";var WORKFLOW_ANCESTOR_TRUST_METHOD="qwen/control/workflow/ancestor-trust";var WORKFLOW_ANCESTOR_TRUST_MAX_ANCESTORS=256;var WORKFLOW_ANCESTOR_TRUST_MAX_PATH_CHARS=32768;var WORKFLOW_ANCESTOR_TRUST_MAX_PATH_BYTES=1024*1024;function isPath(value){return typeof value==="string"&&value.length<=WORKFLOW_ANCESTOR_TRUST_MAX_PATH_CHARS&&!value.includes("\0")&&path2.isAbsolute(value)}__name(isPath,"isPath");function parseWorkflowAncestorTrustRequest(value){if(!value||typeof value!=="object"||Array.isArray(value))return;const request=value;if(request["v"]!==1||typeof request["sessionId"]!=="string"||request["sessionId"].trim().length===0||request["sessionId"].includes("\0")||!isPath(request["canonicalTargetDir"])||!Array.isArray(request["ancestorDirs"])||request["ancestorDirs"].length>WORKFLOW_ANCESTOR_TRUST_MAX_ANCESTORS)return;const ancestorDirs=[];let bytes=Buffer.byteLength(request["canonicalTargetDir"],"utf8");for(let index=0;index<request["ancestorDirs"].length;index++){if(!Object.hasOwn(request["ancestorDirs"],index))return;const ancestor=request["ancestorDirs"][index];if(!isPath(ancestor))return;bytes+=Buffer.byteLength(ancestor,"utf8");if(bytes>WORKFLOW_ANCESTOR_TRUST_MAX_PATH_BYTES)return;ancestorDirs.push(ancestor)}return{v:1,sessionId:request["sessionId"],canonicalTargetDir:request["canonicalTargetDir"],ancestorDirs}}__name(parseWorkflowAncestorTrustRequest,"parseWorkflowAncestorTrustRequest");function isWorkflowAncestorTrustResponse(value,expectedLength){if(!value||typeof value!=="object"||Array.isArray(value))return false;const response=value;const trusted=response["trusted"];if(response["v"]!==1||!Array.isArray(trusted)||trusted.length!==expectedLength)return false;for(let index=0;index<trusted.length;index++){if(!Object.hasOwn(trusted,index)||typeof trusted[index]!=="boolean")return false}return true}__name(isWorkflowAncestorTrustResponse,"isWorkflowAncestorTrustResponse");init_esbuild_shims();init_esbuild_shims();var CANCEL_VOTE_SENTINEL="__cancelled__";var MAX_RESOLVED_PERMISSION_RECORDS=512;function stringifyError(err){try{if(err instanceof Error)return`${err.name}: ${err.message}`;return String(err)}catch{return"[unstringifiable error]"}}__name(stringifyError,"stringifyError");function createNoOpPermissionAuditPublisher(){return{recordRequested(){},recordVoted(){},recordForbidden(){},recordResolved(){},recordTimeout(){}}}__name(createNoOpPermissionAuditPublisher,"createNoOpPermissionAuditPublisher");var MultiClientPermissionMediator=class{static{__name(this,"MultiClientPermissionMediator")}policy;deps;pending=new Map;resolved=new Map;resolvedOrder=[];unanimityBreadcrumbEmitted=false;constructor(policy,deps){this.policy=policy;this.deps=deps}request(record,timeoutMs){if(record.allowedOptionIds.has(CANCEL_VOTE_SENTINEL)){throw new CancelSentinelCollisionError(record.requestId,CANCEL_VOTE_SENTINEL)}return new Promise(resolve3=>{const policy=this.policy;const votersAtIssue=this.deps.votersForSession(record.sessionId);const pending={requestId:record.requestId,sessionId:record.sessionId,promptId:record.promptId,policy,originatorClientId:record.originatorClientId,allowedOptionIds:record.allowedOptionIds,issuedAtMs:record.issuedAtMs,timeoutMs,resolve:resolve3,tallies:new Map,votersAtIssue,timer:void 0,consensusQuorumCapNoted:false};this.pending.set(record.requestId,pending);this.safeAudit(()=>this.deps.audit.recordRequested(record,policy,votersAtIssue));const unresolvedWithoutDecision=timeoutMs>0?`voter cancellation, session cancellation, or permissionTimeoutMs (${timeoutMs}ms)`:"voter or session cancellation because permissionTimeoutMs is disabled";if(policy==="consensus"&&votersAtIssue.size===0){try{process.stderr.write(`permissionMediator: consensus request ${record.requestId} for session ${record.sessionId} issued with empty votersAtIssue; can only resolve via ${unresolvedWithoutDecision}
|
|
6
6
|
`)}catch{}}if(policy==="consensus"&&this.deps.consensusQuorum===void 0&&votersAtIssue.size>=2&&Math.floor(votersAtIssue.size/2)+1===votersAtIssue.size&&!this.unanimityBreadcrumbEmitted){this.unanimityBreadcrumbEmitted=true;try{process.stderr.write(`permissionMediator: consensus request ${record.requestId} for session ${record.sessionId} requires unanimity (votersAtIssue.size=${votersAtIssue.size}, default quorum=floor(M/2)+1=${votersAtIssue.size}); split votes will only resolve via ${unresolvedWithoutDecision}. This breadcrumb fires once per mediator lifetime; subsequent unanimity-required requests are silent.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{collectInlineImages,extractInlineContentRuns}from"./chunk-VRNYIKVL.js";import{formatHistoryGapNotice,indexGapsByChild}from"./chunk-2DU2WMTL.js";import{t}from"./chunk-NO7VTKRL.js";import{isGoalCheckpointBookkeepingRecord}from"./chunk-OU7CEG7Q.js";import{GoalPersistenceUnavailableError,computeInitialTurnFromHistory,getRecordRewindId,getToolResponseDisplayText}from"./chunk-2JGTWRZJ.js";import{projectUserTranscriptForDisplay}from"./chunk-SZCBUCNH.js";import{parseGoalStateRecordPayloadV2}from"./chunk-HW6AWS7W.js";import{ToolDisplayNames}from"./chunk-SBZFGYYS.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as path from"node:path";init_esbuild_shims();init_esbuild_shims();var EstimatedArtWidth=59;var BoxBorderWidth=1;var BOX_PADDING_X=1;var UI_WIDTH=EstimatedArtWidth+BOX_PADDING_X*2+BoxBorderWidth*2;var SHELL_COMMAND_NAME="Shell Command";var SHELL_NAME="Shell";var TOOL_STATUS={SUCCESS:"\u2713",PENDING:"o",EXECUTING:"\u22B7",CONFIRMING:"?",CANCELED:"-",ERROR:"x"};var _VS15="\uFE0E";var ICON={DIAMOND:`\u25C6${_VS15}`,CIRCLE_FILLED:`\u25CF${_VS15}`,TRIANGLE:`\u25B3${_VS15}`,CIRCLE_EMPTY:`\u25CB${_VS15}`,BULLSEYE:`\u25CE${_VS15}`,REFERENCE:`\u203B${_VS15}`,THEREFORE:`\u2234${_VS15}`,BECAUSE:`\u2235${_VS15}`,STAR:`\u2605${_VS15}`,SPARKLE:`\u2733${_VS15}`,RADIO_FILLED:`\u25C9${_VS15}`,CIRCLE_LEFT_HALF:`\u25D0${_VS15}`,CHECK:`\u2713${_VS15}`,CROSS:`\u2716${_VS15}`};var SPINNER_FRAMES=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];var SPINNER_INTERVAL_MS=80;var WAITING_SPINNER_FRAME="\u280F";var TOOL_NAME_TO_CATEGORY={[ToolDisplayNames.READ_FILE]:"read",[ToolDisplayNames.EDIT]:"edit",[ToolDisplayNames.WRITE_FILE]:"write",[ToolDisplayNames.NOTEBOOK_EDIT]:"edit",[ToolDisplayNames.GREP]:"search",[ToolDisplayNames.GLOB]:"search",[ToolDisplayNames.LS]:"list",[ToolDisplayNames.SHELL]:"command",[SHELL_COMMAND_NAME]:"command",[ToolDisplayNames.AGENT]:"agent",[ToolDisplayNames.WORKFLOW]:"agent",[ToolDisplayNames.SEND_MESSAGE]:"agent","Read File":"read","Read File(s)":"read","Read Directory":"list",SearchFiles:"search",FindFiles:"search",ReadFolder:"list",Task:"agent",TodoWrite:"other"};var CATEGORY_TEMPLATES={read:{past:{one:"Read {{count}} file",many:"Read {{count}} files"},active:{one:"Reading {{count}} file",many:"Reading {{count}} files"},pastVerb:"Read",activeVerb:"Reading"},edit:{past:{one:"Edited {{count}} file",many:"Edited {{count}} files"},active:{one:"Editing {{count}} file",many:"Editing {{count}} files"},pastVerb:"Edited",activeVerb:"Editing"},write:{past:{one:"Wrote {{count}} file",many:"Wrote {{count}} files"},active:{one:"Writing {{count}} file",many:"Writing {{count}} files"},pastVerb:"Wrote",activeVerb:"Writing"},search:{past:{one:"Searched {{count}} pattern",many:"Searched {{count}} patterns"},active:{one:"Searching {{count}} pattern",many:"Searching {{count}} patterns"},pastVerb:"Searched",activeVerb:"Searching"},list:{past:{one:"Listed {{count}} directory",many:"Listed {{count}} directories"},active:{one:"Listing {{count}} directory",many:"Listing {{count}} directories"},pastVerb:"Listed",activeVerb:"Listing"},command:{past:{one:"Ran {{count}} command",many:"Ran {{count}} commands"},active:{one:"Running {{count}} command",many:"Running {{count}} commands"},pastVerb:"Ran",activeVerb:"Running"},agent:{past:{one:"Ran {{count}} agent",many:"Ran {{count}} agents"},active:{one:"Running {{count}} agent",many:"Running {{count}} agents"},pastVerb:"Ran",activeVerb:"Running"},other:{past:{one:"Used {{count}} tool",many:"Used {{count}} tools"},active:{one:"Using {{count}} tool",many:"Using {{count}} tools"},pastVerb:"Used",activeVerb:"Using"}};var CATEGORY_ORDER=["search","read","list","command","edit","write","agent","other"];var COLLAPSIBLE_CATEGORIES=new Set(["read","search","list"]);function getToolCategory(toolName){return TOOL_NAME_TO_CATEGORY[toolName]??"other"}__name(getToolCategory,"getToolCategory");function isCollapsibleTool(toolName){return COLLAPSIBLE_CATEGORIES.has(getToolCategory(toolName))}__name(isCollapsibleTool,"isCollapsibleTool");function safeDescription(raw){if(!raw)return void 0;const stripped=raw.replace(/\x1b\][^\x07]*\x07|\x1b[()][A-Z0-9]|\x1b\[[0-9;]*[a-zA-Z]|\x1b./g,"");const cleaned=stripped.replace(/[\x00-\x1f\x7f]/g," ").trim();if(cleaned.startsWith("{")||cleaned.startsWith("[")){try{const parsed=JSON.parse(cleaned);if(typeof parsed==="object"&&parsed!==null)return void 0}catch{}}return cleaned||void 0}__name(safeDescription,"safeDescription");function categoryShowsDescriptionsInline(toolCalls,category){const sameCategory=toolCalls.filter(tc=>getToolCategory(tc.name)===category);if(sameCategory.length>DESCRIPTION_INLINE_LIMIT)return false;return sameCategory.every(tc=>safeDescription(tc.description)!==void 0)}__name(categoryShowsDescriptionsInline,"categoryShowsDescriptionsInline");function getActiveToolHint(toolCalls){if(toolCalls.length<2)return void 0;const statuses=["Confirming","Executing","Pending"];for(const status of statuses){for(let index=toolCalls.length-1;index>=0;index--){const tool=toolCalls[index];if(tool.status===status){const category=getToolCategory(tool.name);const hasCategoryPeers=toolCalls.some((candidate,candidateIndex)=>candidateIndex!==index&&getToolCategory(candidate.name)===category);if(!hasCategoryPeers)return void 0;if(categoryShowsDescriptionsInline(toolCalls,category))return void 0;return safeDescription(tool.description)}}}return void 0}__name(getActiveToolHint,"getActiveToolHint");var DESCRIPTION_INLINE_LIMIT=3;var DESCRIPTION_PREVIEW_COUNT=2;function buildToolSummary(toolCalls,isActive){if(toolCalls.length===0)return"";const toolsByCategory=new Map;for(const tool of toolCalls){const cat=getToolCategory(tool.name);const arr=toolsByCategory.get(cat)??[];arr.push(tool);toolsByCategory.set(cat,arr)}const parts=[];for(const cat of CATEGORY_ORDER){const tools=toolsByCategory.get(cat);if(!tools||tools.length===0)continue;const template=CATEGORY_TEMPLATES[cat];const verb=isActive?template.activeVerb:template.pastVerb;let part;if(tools.length===1){const safeDesc=safeDescription(tools[0].description);if(safeDesc!==void 0){part=`${verb} ${safeDesc}`}else{part=t(isActive?template.active.one:template.past.one,{count:"1"})}}else if(tools.length<=DESCRIPTION_INLINE_LIMIT){const descriptions=tools.map(tc=>safeDescription(tc.description)).filter(d=>d!==void 0);if(descriptions.length===tools.length){part=`${verb} ${descriptions.join(", ")}`}else{const forms=isActive?template.active:template.past;part=t(forms.many,{count:String(tools.length)})}}else{const previewDescs=tools.slice(0,DESCRIPTION_PREVIEW_COUNT).map(tc=>safeDescription(tc.description)).filter(d=>d!==void 0);if(previewDescs.length===DESCRIPTION_PREVIEW_COUNT){const remaining=tools.length-DESCRIPTION_PREVIEW_COUNT;const morePhrase=t("... and {{count}} more",{count:String(remaining)});part=`${verb} ${previewDescs.join(", ")}, ${morePhrase}`}else{const forms=isActive?template.active:template.past;part=t(forms.many,{count:String(tools.length)})}}if(parts.length>0){part=part.charAt(0).toLowerCase()+part.slice(1)}parts.push(part)}return parts.join(", ")}__name(buildToolSummary,"buildToolSummary");function isSubagentToolEntry(tool){const rd=tool.resultDisplay;return typeof rd==="object"&&rd!==null&&"type"in rd&&rd.type==="task_execution"}__name(isSubagentToolEntry,"isSubagentToolEntry");init_esbuild_shims();var SUPERSEDED_FINDINGS_MESSAGE="(findings replaced by a later report_findings call)";function isFindingsListDisplay(value){return typeof value==="object"&&value!==null&&"type"in value&&value.type==="findings_list"}__name(isFindingsListDisplay,"isFindingsListDisplay");function coalesceFindingsHistoryItems(items){let lastItem=-1;let lastTool=-1;for(let i=items.length-1;i>=0&&lastItem===-1;i-=1){const item=items[i];if(item.type!=="tool_group")continue;for(let j=item.tools.length-1;j>=0;j-=1){if(isFindingsListDisplay(item.tools[j].resultDisplay)){lastItem=i;lastTool=j;break}}}if(lastItem===-1)return items;let changed=false;const next=items.map((item,i)=>{if(item.type!=="tool_group")return item;let toolsChanged=false;const tools=item.tools.map((tool,j)=>{if(i===lastItem&&j===lastTool)return tool;if(!isFindingsListDisplay(tool.resultDisplay))return tool;toolsChanged=true;return{...tool,resultDisplay:SUPERSEDED_FINDINGS_MESSAGE,supersededFindingsDisplay:tool.supersededFindingsDisplay??tool.resultDisplay}});if(!toolsChanged)return item;changed=true;return{...item,tools}});return changed?next:items}__name(coalesceFindingsHistoryItems,"coalesceFindingsHistoryItems");function recoalesceFindingsHistoryItems(items){let restored=false;const next=items.map(item=>{if(item.type!=="tool_group")return item;let toolsChanged=false;const tools=item.tools.map(tool=>{if(tool.resultDisplay!==SUPERSEDED_FINDINGS_MESSAGE||!tool.supersededFindingsDisplay){return tool}toolsChanged=true;return{...tool,resultDisplay:tool.supersededFindingsDisplay,supersededFindingsDisplay:void 0}});if(!toolsChanged)return item;restored=true;return{...item,tools}});return coalesceFindingsHistoryItems(restored?next:items)}__name(recoalesceFindingsHistoryItems,"recoalesceFindingsHistoryItems");init_esbuild_shims();function shouldDisplayGoalStateCause(cause){switch(cause){case"turn_finished":case"checkpoint":case"verifier_accept":return false;case"verifier_reject":case"create":case"replace":case"edit":case"pause":case"resume":case"complete":case"blocked":case"usage_limited":case"clear":case"migrated":return true;default:{const exhaustive=cause;return exhaustive}}}__name(shouldDisplayGoalStateCause,"shouldDisplayGoalStateCause");async function waitForGoalRuntime(config,options={}){const awaitReady=__name(async()=>{try{await config.getGoalRuntimeReady()}catch(error){if(!(error instanceof GoalPersistenceUnavailableError))throw error}},"awaitReady");const{timeoutMs}=options;if(timeoutMs==null||timeoutMs<=0){await awaitReady();return true}let timer;const timeout=new Promise(resolve=>{timer=setTimeout(()=>resolve("timeout"),timeoutMs);timer.unref?.()});try{const winner=await Promise.race([awaitReady(),timeout]);return winner!=="timeout"}finally{if(timer)clearTimeout(timer)}}__name(waitForGoalRuntime,"waitForGoalRuntime");function extractTextFromParts(parts){if(!parts)return"";const textParts=[];for(const part of parts){if("text"in part&&part.text){if(!("thought"in part&&part.thought)){textParts.push(part.text)}}}return textParts.join("\n")}__name(extractTextFromParts,"extractTextFromParts");function extractThoughtTextFromParts(parts){if(!parts)return"";const thoughtParts=[];for(const part of parts){if("text"in part&&part.text&&"thought"in part&&part.thought){thoughtParts.push(part.text)}}return thoughtParts.join("\n")}__name(extractThoughtTextFromParts,"extractThoughtTextFromParts");function extractFunctionCalls(parts){if(!parts)return[];const calls=[];for(const part of parts){if("functionCall"in part&&part.functionCall){const fc=part.functionCall;calls.push({id:fc.id||`call-${calls.length}`,name:fc.name||"unknown",args:fc.args||{}})}}return calls}__name(extractFunctionCalls,"extractFunctionCalls");function getTool(config,name){if(!config)return void 0;const toolRegistry=config.getToolRegistry();return toolRegistry.getTool(name)}__name(getTool,"getTool");function formatToolDescription(tool,args){try{const invocation=tool.build(args);return invocation.getDescription()}catch{if(typeof args["description"]==="string"){return args["description"]}return""}}__name(formatToolDescription,"formatToolDescription");function restoreHistoryItem(raw){if(!raw||typeof raw!=="object"){return}const clone={...raw};if("timestamp"in clone){const ts=clone["timestamp"];if(typeof ts==="string"||typeof ts==="number"){clone["timestamp"]=new Date(ts)}}if(typeof clone["type"]!=="string"){return}return clone}__name(restoreHistoryItem,"restoreHistoryItem");function createHistoryGapItem(gap){return{type:"info",text:formatHistoryGapNotice(gap)}}__name(createHistoryGapItem,"createHistoryGapItem");function convertToHistoryItems(conversation,config,historyGaps){const items=[];const gapByChildUuid=indexGapsByChild(historyGaps);const pendingAtCommands=[];let atCommandCounter=0;let lastGoalStateSnapshot;let lastGoalStateCause;const pendingToolCalls=new Map;let currentToolGroup=[];const buildAtCommandDisplays=__name(payload=>{if(payload.status==="error"){atCommandCounter+=1;const filesLabel=payload.filesRead?.length?payload.filesRead.join(", "):"files";return[{callId:`at-command-${atCommandCounter}`,name:"Read File(s)",description:"Error attempting to read files",status:"Error",resultDisplay:payload.message||`Error reading files (${filesLabel})`,confirmationDetails:void 0}]}if(!payload.filesRead?.length){atCommandCounter+=1;return[{callId:`at-command-${atCommandCounter}`,name:"Read File",description:"Read File(s)",status:"Success",resultDisplay:void 0,confirmationDetails:void 0}]}return payload.filesRead.map(filePath=>{atCommandCounter+=1;const isDir=filePath.endsWith("/");return{callId:`at-command-${atCommandCounter}`,name:isDir?"Read Directory":"Read File",description:isDir?`Read directory ${path.basename(filePath)}`:`Read file ${path.basename(filePath)}`,status:"Success",resultDisplay:void 0,confirmationDetails:void 0}})},"buildAtCommandDisplays");for(const record of conversation.messages){const promptId=typeof record.promptId==="string"&&record.promptId.length>0?record.promptId:void 0;const rewindId=promptId?void 0:getRecordRewindId(record);const gap=gapByChildUuid.get(record.uuid);if(gap){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}pendingAtCommands.length=0;lastGoalStateSnapshot=void 0;lastGoalStateCause=void 0;items.push(createHistoryGapItem(gap))}if(record.type==="system"){if(record.subtype==="goal_state"){const payload=parseGoalStateRecordPayloadV2(record.systemPayload);if(payload){const bookkeepingOnly=isGoalCheckpointBookkeepingRecord({cause:payload.cause,previousCause:lastGoalStateCause,previous:lastGoalStateSnapshot,next:payload.snapshot});lastGoalStateCause=payload.cause;lastGoalStateSnapshot=payload.snapshot;if(shouldDisplayGoalStateCause(payload.cause)&&!bookkeepingOnly){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}items.push({type:"goal_state",snapshot:payload.snapshot,cause:payload.cause})}}continue}if(record.subtype==="slash_command"){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}const payload=record.systemPayload;if(!payload)continue;if(payload.phase==="invocation"&&payload.rawCommand&&!payload.hiddenInvocation){const sentToModel=typeof payload.sentToModel==="boolean"?payload.sentToModel:void 0;items.push({type:"user",text:payload.rawCommand,...promptId?{promptId}:{},...sentToModel===void 0?{}:{sentToModel}})}if(payload.phase==="result"){const outputs=payload.outputHistoryItems??[];for(const raw of outputs){const restored=restoreHistoryItem(raw);if(restored){items.push(restored)}}}}if(record.subtype==="at_command"){const payload=record.systemPayload;if(!payload)continue;pendingAtCommands.push(payload)}if(record.subtype==="rewind"){items.push({type:"info",text:"Conversation rewound."})}continue}switch(record.type){case"user":{if(record.subtype==="goal_runtime")break;if(record.subtype==="notification"||record.subtype==="cron"){const payload2=record.systemPayload;const fallback=record.subtype==="cron"?"Cron job fired":"Background agent completed";const text2=payload2?.displayText||extractTextFromParts(record.message?.parts)||fallback;items.push({type:"notification",text:text2});break}if(record.subtype==="agent_mention"||record.subtype==="agent_message"){const payload2=record.systemPayload;const text2=payload2?.displayText;if(text2){if(record.subtype==="agent_mention"&&!payload2?.author){items.push({type:"user",text:text2,sentToModel:false})}else{const name=payload2?.author?.name??record.agentName;items.push({type:"notification",text:name?`${name}: ${text2}`:text2})}}break}if(record.subtype==="mid_turn_user_message"){const payload2=record.systemPayload;const hasAttachmentReferences2=Array.isArray(payload2?.attachmentReferences)&&payload2.attachmentReferences.length>0;const text2=payload2?.displayText||(hasAttachmentReferences2?"[User message with attachments]":extractTextFromParts(record.message?.parts));if(text2){items.push({type:"user",text:text2,sentToModel:false})}break}if(pendingAtCommands.length>0){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}const payload2=pendingAtCommands.shift();const projection2=projectUserTranscriptForDisplay(record);const text2=payload2.userText||(projection2.displayText??extractTextFromParts(projection2.parts));if(text2){items.push({type:"user",text:text2,...promptId?{promptId}:{},...rewindId?{rewindId}:{}})}const toolDisplays=buildAtCommandDisplays(payload2);if(toolDisplays.length>0){items.push({type:"tool_group",tools:toolDisplays})}break}if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}const projection=projectUserTranscriptForDisplay(record);const payload=record.systemPayload;const hasAttachmentReferences=Array.isArray(payload?.attachmentReferences)&&payload.attachmentReferences.length>0;const text=projection.displayText||(hasAttachmentReferences?"[User message with attachments]":extractTextFromParts(projection.parts));if(text){items.push({type:"user",text,...promptId?{promptId}:{},...rewindId?{rewindId}:{}})}break}case"assistant":{const parts=record.message?.parts;const thoughtText=!config?extractThoughtTextFromParts(parts):"";const displayRuns=extractInlineContentRuns(parts,"\n");const functionCalls=extractFunctionCalls(parts);if(thoughtText){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}items.push({type:"gemini_thought",text:thoughtText})}if(displayRuns.length>0){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}for(const[index,run]of displayRuns.entries()){const type=index===0?"gemini":"gemini_content";const timestamp=index===0?{timestamp:new Date(record.timestamp).getTime()}:{};if(run.kind==="text"){items.push({type,text:run.text,...timestamp})}else if(run.kind==="image"){items.push({type,text:"",images:[run.image],...timestamp})}else{items.push({type,text:"",omittedImageCount:run.count,...timestamp})}}}for(const fc of functionCalls){const tool=getTool(config,fc.name);pendingToolCalls.set(fc.id,{name:fc.name,args:fc.args});currentToolGroup.push({callId:fc.id,name:tool?.displayName||fc.name,description:tool?formatToolDescription(tool,fc.args):"",args:fc.args,resultDisplay:void 0,status:"Error",confirmationDetails:void 0})}break}case"tool_result":{if(record.toolCallResult){const callId=record.toolCallResult.callId;const toolCall=currentToolGroup.find(t2=>t2.callId===callId);if(toolCall){const responseParts=record.toolCallResult.responseParts??record.message?.parts;const rawDisplay=record.toolCallResult.resultDisplay;toolCall.resultDisplay=rawDisplay;if(record.toolCallResult.visionBridgeNotice!==void 0){toolCall.visionBridgeNotice=record.toolCallResult.visionBridgeNotice}const rawStatus=record.toolCallResult["status"];toolCall.status=rawStatus==="error"?"Error":rawStatus==="cancelled"?"Canceled":"Success";const{images,omittedImageCount}=collectInlineImages(responseParts);if(images.length>0){toolCall.images=images}if(omittedImageCount>0){toolCall.omittedImageCount=omittedImageCount}if(toolCall.status==="Success"&&isCollapsibleTool(toolCall.name)){toolCall.detailedDisplay=getToolResponseDisplayText(responseParts)}}pendingToolCalls.delete(callId||"")}break}default:break}}if(pendingAtCommands.length>0){for(const payload of pendingAtCommands){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}const text=payload.userText;if(text){items.push({type:"user",text})}const toolDisplays=buildAtCommandDisplays(payload);if(toolDisplays.length>0){items.push({type:"tool_group",tools:toolDisplays})}}}if(currentToolGroup.length>0){items.push({type:"tool_group",tools:currentToolGroup})}return coalesceFindingsHistoryItems(items)}__name(convertToHistoryItems,"convertToHistoryItems");function buildResumedHistoryItems(sessionData,config,baseTimestamp=Date.now()){const items=[];let idCounter=1;const getNextId=__name(()=>baseTimestamp+idCounter++,"getNextId");const historyItems=convertToHistoryItems(sessionData.conversation,config,sessionData.historyGaps);for(const item of historyItems){items.push({...item,id:getNextId()})}return items}__name(buildResumedHistoryItems,"buildResumedHistoryItems");function applyResumeDisplayPolicy(items){return items.map(item=>({...item,display:{...item.display,suppressOnRestore:true}}))}__name(applyResumeDisplayPolicy,"applyResumeDisplayPolicy");function createHistoryCollapseSummaryItem(messageCount){const n=String(messageCount);return{type:"info",text:t("History collapsed: {{n}} messages hidden. Use /history expand-now to show.",{n}),display:{kind:"collapse-summary"}}}__name(createHistoryCollapseSummaryItem,"createHistoryCollapseSummaryItem");function stripSuppressOnRestore(item){if(!item.display?.suppressOnRestore)return item;const{suppressOnRestore:_,...rest}=item.display;return{...item,display:Object.keys(rest).length>0?rest:void 0}}__name(stripSuppressOnRestore,"stripSuppressOnRestore");function computeResumedPromptCountSeed(records,sessionId){const userTurnCount=records.filter(m=>m.type==="user"&&m.subtype!=="mid_turn_user_message"&&m.subtype!=="realtime_message").length;if(records.length===0){return 0}return Math.max(userTurnCount,computeInitialTurnFromHistory(records,sessionId)+1)}__name(computeResumedPromptCountSeed,"computeResumedPromptCountSeed");function expandCollapsedHistory(items){return items.filter(item=>item.display?.kind!=="collapse-summary").map(stripSuppressOnRestore)}__name(expandCollapsedHistory,"expandCollapsedHistory");function applyCollapsePolicyAndSummary(rawItems,collapseOnResume,collapsePreviewCount=0){if(!collapseOnResume)return rawItems;if(collapsePreviewCount===-1)return rawItems;let boundary=rawItems.length;if(collapsePreviewCount>0){let userTurnCount=0;for(let i=rawItems.length-1;i>=0;i--){const item=rawItems[i];if(item.type==="user"&&item.sentToModel!==false){userTurnCount++;if(userTurnCount===collapsePreviewCount){boundary=i;break}}}if(userTurnCount<collapsePreviewCount){boundary=0}}const hiddenItems=applyResumeDisplayPolicy(rawItems.slice(0,boundary));const visibleItems=rawItems.slice(boundary);const uiHistoryItems=[...hiddenItems,...visibleItems];if(boundary>0){const nextId=rawItems[rawItems.length-1].id+1;return[...uiHistoryItems,{id:nextId,...createHistoryCollapseSummaryItem(boundary)}]}return uiHistoryItems}__name(applyCollapsePolicyAndSummary,"applyCollapsePolicyAndSummary");export{SHELL_COMMAND_NAME,SHELL_NAME,TOOL_STATUS,ICON,SPINNER_FRAMES,SPINNER_INTERVAL_MS,WAITING_SPINNER_FRAME,isCollapsibleTool,getActiveToolHint,buildToolSummary,isSubagentToolEntry,isFindingsListDisplay,coalesceFindingsHistoryItems,recoalesceFindingsHistoryItems,shouldDisplayGoalStateCause,waitForGoalRuntime,buildResumedHistoryItems,stripSuppressOnRestore,computeResumedPromptCountSeed,expandCollapsedHistory,applyCollapsePolicyAndSummary};
|
|
3
|
+
import{collectInlineImages,extractInlineContentRuns}from"./chunk-VRNYIKVL.js";import{formatHistoryGapNotice,indexGapsByChild}from"./chunk-2DU2WMTL.js";import{t}from"./chunk-NO7VTKRL.js";import{isGoalCheckpointBookkeepingRecord}from"./chunk-CK3OKTTL.js";import{GoalPersistenceUnavailableError,computeInitialTurnFromHistory,getRecordRewindId,getToolResponseDisplayText}from"./chunk-T3CQ72HC.js";import{projectUserTranscriptForDisplay}from"./chunk-SZCBUCNH.js";import{parseGoalStateRecordPayloadV2}from"./chunk-HW6AWS7W.js";import{ToolDisplayNames}from"./chunk-SBZFGYYS.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as path from"node:path";init_esbuild_shims();init_esbuild_shims();var EstimatedArtWidth=59;var BoxBorderWidth=1;var BOX_PADDING_X=1;var UI_WIDTH=EstimatedArtWidth+BOX_PADDING_X*2+BoxBorderWidth*2;var SHELL_COMMAND_NAME="Shell Command";var SHELL_NAME="Shell";var TOOL_STATUS={SUCCESS:"\u2713",PENDING:"o",EXECUTING:"\u22B7",CONFIRMING:"?",CANCELED:"-",ERROR:"x"};var _VS15="\uFE0E";var ICON={DIAMOND:`\u25C6${_VS15}`,CIRCLE_FILLED:`\u25CF${_VS15}`,TRIANGLE:`\u25B3${_VS15}`,CIRCLE_EMPTY:`\u25CB${_VS15}`,BULLSEYE:`\u25CE${_VS15}`,REFERENCE:`\u203B${_VS15}`,THEREFORE:`\u2234${_VS15}`,BECAUSE:`\u2235${_VS15}`,STAR:`\u2605${_VS15}`,SPARKLE:`\u2733${_VS15}`,RADIO_FILLED:`\u25C9${_VS15}`,CIRCLE_LEFT_HALF:`\u25D0${_VS15}`,CHECK:`\u2713${_VS15}`,CROSS:`\u2716${_VS15}`};var SPINNER_FRAMES=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];var SPINNER_INTERVAL_MS=80;var WAITING_SPINNER_FRAME="\u280F";var TOOL_NAME_TO_CATEGORY={[ToolDisplayNames.READ_FILE]:"read",[ToolDisplayNames.EDIT]:"edit",[ToolDisplayNames.WRITE_FILE]:"write",[ToolDisplayNames.NOTEBOOK_EDIT]:"edit",[ToolDisplayNames.GREP]:"search",[ToolDisplayNames.GLOB]:"search",[ToolDisplayNames.LS]:"list",[ToolDisplayNames.SHELL]:"command",[SHELL_COMMAND_NAME]:"command",[ToolDisplayNames.AGENT]:"agent",[ToolDisplayNames.WORKFLOW]:"agent",[ToolDisplayNames.SEND_MESSAGE]:"agent","Read File":"read","Read File(s)":"read","Read Directory":"list",SearchFiles:"search",FindFiles:"search",ReadFolder:"list",Task:"agent",TodoWrite:"other"};var CATEGORY_TEMPLATES={read:{past:{one:"Read {{count}} file",many:"Read {{count}} files"},active:{one:"Reading {{count}} file",many:"Reading {{count}} files"},pastVerb:"Read",activeVerb:"Reading"},edit:{past:{one:"Edited {{count}} file",many:"Edited {{count}} files"},active:{one:"Editing {{count}} file",many:"Editing {{count}} files"},pastVerb:"Edited",activeVerb:"Editing"},write:{past:{one:"Wrote {{count}} file",many:"Wrote {{count}} files"},active:{one:"Writing {{count}} file",many:"Writing {{count}} files"},pastVerb:"Wrote",activeVerb:"Writing"},search:{past:{one:"Searched {{count}} pattern",many:"Searched {{count}} patterns"},active:{one:"Searching {{count}} pattern",many:"Searching {{count}} patterns"},pastVerb:"Searched",activeVerb:"Searching"},list:{past:{one:"Listed {{count}} directory",many:"Listed {{count}} directories"},active:{one:"Listing {{count}} directory",many:"Listing {{count}} directories"},pastVerb:"Listed",activeVerb:"Listing"},command:{past:{one:"Ran {{count}} command",many:"Ran {{count}} commands"},active:{one:"Running {{count}} command",many:"Running {{count}} commands"},pastVerb:"Ran",activeVerb:"Running"},agent:{past:{one:"Ran {{count}} agent",many:"Ran {{count}} agents"},active:{one:"Running {{count}} agent",many:"Running {{count}} agents"},pastVerb:"Ran",activeVerb:"Running"},other:{past:{one:"Used {{count}} tool",many:"Used {{count}} tools"},active:{one:"Using {{count}} tool",many:"Using {{count}} tools"},pastVerb:"Used",activeVerb:"Using"}};var CATEGORY_ORDER=["search","read","list","command","edit","write","agent","other"];var COLLAPSIBLE_CATEGORIES=new Set(["read","search","list"]);function getToolCategory(toolName){return TOOL_NAME_TO_CATEGORY[toolName]??"other"}__name(getToolCategory,"getToolCategory");function isCollapsibleTool(toolName){return COLLAPSIBLE_CATEGORIES.has(getToolCategory(toolName))}__name(isCollapsibleTool,"isCollapsibleTool");function safeDescription(raw){if(!raw)return void 0;const stripped=raw.replace(/\x1b\][^\x07]*\x07|\x1b[()][A-Z0-9]|\x1b\[[0-9;]*[a-zA-Z]|\x1b./g,"");const cleaned=stripped.replace(/[\x00-\x1f\x7f]/g," ").trim();if(cleaned.startsWith("{")||cleaned.startsWith("[")){try{const parsed=JSON.parse(cleaned);if(typeof parsed==="object"&&parsed!==null)return void 0}catch{}}return cleaned||void 0}__name(safeDescription,"safeDescription");function categoryShowsDescriptionsInline(toolCalls,category){const sameCategory=toolCalls.filter(tc=>getToolCategory(tc.name)===category);if(sameCategory.length>DESCRIPTION_INLINE_LIMIT)return false;return sameCategory.every(tc=>safeDescription(tc.description)!==void 0)}__name(categoryShowsDescriptionsInline,"categoryShowsDescriptionsInline");function getActiveToolHint(toolCalls){if(toolCalls.length<2)return void 0;const statuses=["Confirming","Executing","Pending"];for(const status of statuses){for(let index=toolCalls.length-1;index>=0;index--){const tool=toolCalls[index];if(tool.status===status){const category=getToolCategory(tool.name);const hasCategoryPeers=toolCalls.some((candidate,candidateIndex)=>candidateIndex!==index&&getToolCategory(candidate.name)===category);if(!hasCategoryPeers)return void 0;if(categoryShowsDescriptionsInline(toolCalls,category))return void 0;return safeDescription(tool.description)}}}return void 0}__name(getActiveToolHint,"getActiveToolHint");var DESCRIPTION_INLINE_LIMIT=3;var DESCRIPTION_PREVIEW_COUNT=2;function buildToolSummary(toolCalls,isActive){if(toolCalls.length===0)return"";const toolsByCategory=new Map;for(const tool of toolCalls){const cat=getToolCategory(tool.name);const arr=toolsByCategory.get(cat)??[];arr.push(tool);toolsByCategory.set(cat,arr)}const parts=[];for(const cat of CATEGORY_ORDER){const tools=toolsByCategory.get(cat);if(!tools||tools.length===0)continue;const template=CATEGORY_TEMPLATES[cat];const verb=isActive?template.activeVerb:template.pastVerb;let part;if(tools.length===1){const safeDesc=safeDescription(tools[0].description);if(safeDesc!==void 0){part=`${verb} ${safeDesc}`}else{part=t(isActive?template.active.one:template.past.one,{count:"1"})}}else if(tools.length<=DESCRIPTION_INLINE_LIMIT){const descriptions=tools.map(tc=>safeDescription(tc.description)).filter(d=>d!==void 0);if(descriptions.length===tools.length){part=`${verb} ${descriptions.join(", ")}`}else{const forms=isActive?template.active:template.past;part=t(forms.many,{count:String(tools.length)})}}else{const previewDescs=tools.slice(0,DESCRIPTION_PREVIEW_COUNT).map(tc=>safeDescription(tc.description)).filter(d=>d!==void 0);if(previewDescs.length===DESCRIPTION_PREVIEW_COUNT){const remaining=tools.length-DESCRIPTION_PREVIEW_COUNT;const morePhrase=t("... and {{count}} more",{count:String(remaining)});part=`${verb} ${previewDescs.join(", ")}, ${morePhrase}`}else{const forms=isActive?template.active:template.past;part=t(forms.many,{count:String(tools.length)})}}if(parts.length>0){part=part.charAt(0).toLowerCase()+part.slice(1)}parts.push(part)}return parts.join(", ")}__name(buildToolSummary,"buildToolSummary");function isSubagentToolEntry(tool){const rd=tool.resultDisplay;return typeof rd==="object"&&rd!==null&&"type"in rd&&rd.type==="task_execution"}__name(isSubagentToolEntry,"isSubagentToolEntry");init_esbuild_shims();var SUPERSEDED_FINDINGS_MESSAGE="(findings replaced by a later report_findings call)";function isFindingsListDisplay(value){return typeof value==="object"&&value!==null&&"type"in value&&value.type==="findings_list"}__name(isFindingsListDisplay,"isFindingsListDisplay");function coalesceFindingsHistoryItems(items){let lastItem=-1;let lastTool=-1;for(let i=items.length-1;i>=0&&lastItem===-1;i-=1){const item=items[i];if(item.type!=="tool_group")continue;for(let j=item.tools.length-1;j>=0;j-=1){if(isFindingsListDisplay(item.tools[j].resultDisplay)){lastItem=i;lastTool=j;break}}}if(lastItem===-1)return items;let changed=false;const next=items.map((item,i)=>{if(item.type!=="tool_group")return item;let toolsChanged=false;const tools=item.tools.map((tool,j)=>{if(i===lastItem&&j===lastTool)return tool;if(!isFindingsListDisplay(tool.resultDisplay))return tool;toolsChanged=true;return{...tool,resultDisplay:SUPERSEDED_FINDINGS_MESSAGE,supersededFindingsDisplay:tool.supersededFindingsDisplay??tool.resultDisplay}});if(!toolsChanged)return item;changed=true;return{...item,tools}});return changed?next:items}__name(coalesceFindingsHistoryItems,"coalesceFindingsHistoryItems");function recoalesceFindingsHistoryItems(items){let restored=false;const next=items.map(item=>{if(item.type!=="tool_group")return item;let toolsChanged=false;const tools=item.tools.map(tool=>{if(tool.resultDisplay!==SUPERSEDED_FINDINGS_MESSAGE||!tool.supersededFindingsDisplay){return tool}toolsChanged=true;return{...tool,resultDisplay:tool.supersededFindingsDisplay,supersededFindingsDisplay:void 0}});if(!toolsChanged)return item;restored=true;return{...item,tools}});return coalesceFindingsHistoryItems(restored?next:items)}__name(recoalesceFindingsHistoryItems,"recoalesceFindingsHistoryItems");init_esbuild_shims();function shouldDisplayGoalStateCause(cause){switch(cause){case"turn_finished":case"checkpoint":case"verifier_accept":return false;case"verifier_reject":case"create":case"replace":case"edit":case"pause":case"resume":case"complete":case"blocked":case"usage_limited":case"clear":case"migrated":return true;default:{const exhaustive=cause;return exhaustive}}}__name(shouldDisplayGoalStateCause,"shouldDisplayGoalStateCause");async function waitForGoalRuntime(config,options={}){const awaitReady=__name(async()=>{try{await config.getGoalRuntimeReady()}catch(error){if(!(error instanceof GoalPersistenceUnavailableError))throw error}},"awaitReady");const{timeoutMs}=options;if(timeoutMs==null||timeoutMs<=0){await awaitReady();return true}let timer;const timeout=new Promise(resolve=>{timer=setTimeout(()=>resolve("timeout"),timeoutMs);timer.unref?.()});try{const winner=await Promise.race([awaitReady(),timeout]);return winner!=="timeout"}finally{if(timer)clearTimeout(timer)}}__name(waitForGoalRuntime,"waitForGoalRuntime");function extractTextFromParts(parts){if(!parts)return"";const textParts=[];for(const part of parts){if("text"in part&&part.text){if(!("thought"in part&&part.thought)){textParts.push(part.text)}}}return textParts.join("\n")}__name(extractTextFromParts,"extractTextFromParts");function extractThoughtTextFromParts(parts){if(!parts)return"";const thoughtParts=[];for(const part of parts){if("text"in part&&part.text&&"thought"in part&&part.thought){thoughtParts.push(part.text)}}return thoughtParts.join("\n")}__name(extractThoughtTextFromParts,"extractThoughtTextFromParts");function extractFunctionCalls(parts){if(!parts)return[];const calls=[];for(const part of parts){if("functionCall"in part&&part.functionCall){const fc=part.functionCall;calls.push({id:fc.id||`call-${calls.length}`,name:fc.name||"unknown",args:fc.args||{}})}}return calls}__name(extractFunctionCalls,"extractFunctionCalls");function getTool(config,name){if(!config)return void 0;const toolRegistry=config.getToolRegistry();return toolRegistry.getTool(name)}__name(getTool,"getTool");function formatToolDescription(tool,args){try{const invocation=tool.build(args);return invocation.getDescription()}catch{if(typeof args["description"]==="string"){return args["description"]}return""}}__name(formatToolDescription,"formatToolDescription");function restoreHistoryItem(raw){if(!raw||typeof raw!=="object"){return}const clone={...raw};if("timestamp"in clone){const ts=clone["timestamp"];if(typeof ts==="string"||typeof ts==="number"){clone["timestamp"]=new Date(ts)}}if(typeof clone["type"]!=="string"){return}return clone}__name(restoreHistoryItem,"restoreHistoryItem");function createHistoryGapItem(gap){return{type:"info",text:formatHistoryGapNotice(gap)}}__name(createHistoryGapItem,"createHistoryGapItem");function convertToHistoryItems(conversation,config,historyGaps){const items=[];const gapByChildUuid=indexGapsByChild(historyGaps);const pendingAtCommands=[];let atCommandCounter=0;let lastGoalStateSnapshot;let lastGoalStateCause;const pendingToolCalls=new Map;let currentToolGroup=[];const buildAtCommandDisplays=__name(payload=>{if(payload.status==="error"){atCommandCounter+=1;const filesLabel=payload.filesRead?.length?payload.filesRead.join(", "):"files";return[{callId:`at-command-${atCommandCounter}`,name:"Read File(s)",description:"Error attempting to read files",status:"Error",resultDisplay:payload.message||`Error reading files (${filesLabel})`,confirmationDetails:void 0}]}if(!payload.filesRead?.length){atCommandCounter+=1;return[{callId:`at-command-${atCommandCounter}`,name:"Read File",description:"Read File(s)",status:"Success",resultDisplay:void 0,confirmationDetails:void 0}]}return payload.filesRead.map(filePath=>{atCommandCounter+=1;const isDir=filePath.endsWith("/");return{callId:`at-command-${atCommandCounter}`,name:isDir?"Read Directory":"Read File",description:isDir?`Read directory ${path.basename(filePath)}`:`Read file ${path.basename(filePath)}`,status:"Success",resultDisplay:void 0,confirmationDetails:void 0}})},"buildAtCommandDisplays");for(const record of conversation.messages){const promptId=typeof record.promptId==="string"&&record.promptId.length>0?record.promptId:void 0;const rewindId=promptId?void 0:getRecordRewindId(record);const gap=gapByChildUuid.get(record.uuid);if(gap){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}pendingAtCommands.length=0;lastGoalStateSnapshot=void 0;lastGoalStateCause=void 0;items.push(createHistoryGapItem(gap))}if(record.type==="system"){if(record.subtype==="goal_state"){const payload=parseGoalStateRecordPayloadV2(record.systemPayload);if(payload){const bookkeepingOnly=isGoalCheckpointBookkeepingRecord({cause:payload.cause,previousCause:lastGoalStateCause,previous:lastGoalStateSnapshot,next:payload.snapshot});lastGoalStateCause=payload.cause;lastGoalStateSnapshot=payload.snapshot;if(shouldDisplayGoalStateCause(payload.cause)&&!bookkeepingOnly){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}items.push({type:"goal_state",snapshot:payload.snapshot,cause:payload.cause})}}continue}if(record.subtype==="slash_command"){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}const payload=record.systemPayload;if(!payload)continue;if(payload.phase==="invocation"&&payload.rawCommand&&!payload.hiddenInvocation){const sentToModel=typeof payload.sentToModel==="boolean"?payload.sentToModel:void 0;items.push({type:"user",text:payload.rawCommand,...promptId?{promptId}:{},...sentToModel===void 0?{}:{sentToModel}})}if(payload.phase==="result"){const outputs=payload.outputHistoryItems??[];for(const raw of outputs){const restored=restoreHistoryItem(raw);if(restored){items.push(restored)}}}}if(record.subtype==="at_command"){const payload=record.systemPayload;if(!payload)continue;pendingAtCommands.push(payload)}if(record.subtype==="rewind"){items.push({type:"info",text:"Conversation rewound."})}continue}switch(record.type){case"user":{if(record.subtype==="goal_runtime")break;if(record.subtype==="notification"||record.subtype==="cron"){const payload2=record.systemPayload;const fallback=record.subtype==="cron"?"Cron job fired":"Background agent completed";const text2=payload2?.displayText||extractTextFromParts(record.message?.parts)||fallback;items.push({type:"notification",text:text2});break}if(record.subtype==="agent_mention"||record.subtype==="agent_message"){const payload2=record.systemPayload;const text2=payload2?.displayText;if(text2){if(record.subtype==="agent_mention"&&!payload2?.author){items.push({type:"user",text:text2,sentToModel:false})}else{const name=payload2?.author?.name??record.agentName;items.push({type:"notification",text:name?`${name}: ${text2}`:text2})}}break}if(record.subtype==="mid_turn_user_message"){const payload2=record.systemPayload;const hasAttachmentReferences2=Array.isArray(payload2?.attachmentReferences)&&payload2.attachmentReferences.length>0;const text2=payload2?.displayText||(hasAttachmentReferences2?"[User message with attachments]":extractTextFromParts(record.message?.parts));if(text2){items.push({type:"user",text:text2,sentToModel:false})}break}if(pendingAtCommands.length>0){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}const payload2=pendingAtCommands.shift();const projection2=projectUserTranscriptForDisplay(record);const text2=payload2.userText||(projection2.displayText??extractTextFromParts(projection2.parts));if(text2){items.push({type:"user",text:text2,...promptId?{promptId}:{},...rewindId?{rewindId}:{}})}const toolDisplays=buildAtCommandDisplays(payload2);if(toolDisplays.length>0){items.push({type:"tool_group",tools:toolDisplays})}break}if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}const projection=projectUserTranscriptForDisplay(record);const payload=record.systemPayload;const hasAttachmentReferences=Array.isArray(payload?.attachmentReferences)&&payload.attachmentReferences.length>0;const text=projection.displayText||(hasAttachmentReferences?"[User message with attachments]":extractTextFromParts(projection.parts));if(text){items.push({type:"user",text,...promptId?{promptId}:{},...rewindId?{rewindId}:{}})}break}case"assistant":{const parts=record.message?.parts;const thoughtText=!config?extractThoughtTextFromParts(parts):"";const displayRuns=extractInlineContentRuns(parts,"\n");const functionCalls=extractFunctionCalls(parts);if(thoughtText){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}items.push({type:"gemini_thought",text:thoughtText})}if(displayRuns.length>0){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}for(const[index,run]of displayRuns.entries()){const type=index===0?"gemini":"gemini_content";const timestamp=index===0?{timestamp:new Date(record.timestamp).getTime()}:{};if(run.kind==="text"){items.push({type,text:run.text,...timestamp})}else if(run.kind==="image"){items.push({type,text:"",images:[run.image],...timestamp})}else{items.push({type,text:"",omittedImageCount:run.count,...timestamp})}}}for(const fc of functionCalls){const tool=getTool(config,fc.name);pendingToolCalls.set(fc.id,{name:fc.name,args:fc.args});currentToolGroup.push({callId:fc.id,name:tool?.displayName||fc.name,description:tool?formatToolDescription(tool,fc.args):"",args:fc.args,resultDisplay:void 0,status:"Error",confirmationDetails:void 0})}break}case"tool_result":{if(record.toolCallResult){const callId=record.toolCallResult.callId;const toolCall=currentToolGroup.find(t2=>t2.callId===callId);if(toolCall){const responseParts=record.toolCallResult.responseParts??record.message?.parts;const rawDisplay=record.toolCallResult.resultDisplay;toolCall.resultDisplay=rawDisplay;if(record.toolCallResult.visionBridgeNotice!==void 0){toolCall.visionBridgeNotice=record.toolCallResult.visionBridgeNotice}const rawStatus=record.toolCallResult["status"];toolCall.status=rawStatus==="error"?"Error":rawStatus==="cancelled"?"Canceled":"Success";const{images,omittedImageCount}=collectInlineImages(responseParts);if(images.length>0){toolCall.images=images}if(omittedImageCount>0){toolCall.omittedImageCount=omittedImageCount}if(toolCall.status==="Success"&&isCollapsibleTool(toolCall.name)){toolCall.detailedDisplay=getToolResponseDisplayText(responseParts)}}pendingToolCalls.delete(callId||"")}break}default:break}}if(pendingAtCommands.length>0){for(const payload of pendingAtCommands){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}const text=payload.userText;if(text){items.push({type:"user",text})}const toolDisplays=buildAtCommandDisplays(payload);if(toolDisplays.length>0){items.push({type:"tool_group",tools:toolDisplays})}}}if(currentToolGroup.length>0){items.push({type:"tool_group",tools:currentToolGroup})}return coalesceFindingsHistoryItems(items)}__name(convertToHistoryItems,"convertToHistoryItems");function buildResumedHistoryItems(sessionData,config,baseTimestamp=Date.now()){const items=[];let idCounter=1;const getNextId=__name(()=>baseTimestamp+idCounter++,"getNextId");const historyItems=convertToHistoryItems(sessionData.conversation,config,sessionData.historyGaps);for(const item of historyItems){items.push({...item,id:getNextId()})}return items}__name(buildResumedHistoryItems,"buildResumedHistoryItems");function applyResumeDisplayPolicy(items){return items.map(item=>({...item,display:{...item.display,suppressOnRestore:true}}))}__name(applyResumeDisplayPolicy,"applyResumeDisplayPolicy");function createHistoryCollapseSummaryItem(messageCount){const n=String(messageCount);return{type:"info",text:t("History collapsed: {{n}} messages hidden. Use /history expand-now to show.",{n}),display:{kind:"collapse-summary"}}}__name(createHistoryCollapseSummaryItem,"createHistoryCollapseSummaryItem");function stripSuppressOnRestore(item){if(!item.display?.suppressOnRestore)return item;const{suppressOnRestore:_,...rest}=item.display;return{...item,display:Object.keys(rest).length>0?rest:void 0}}__name(stripSuppressOnRestore,"stripSuppressOnRestore");function computeResumedPromptCountSeed(records,sessionId){const userTurnCount=records.filter(m=>m.type==="user"&&m.subtype!=="mid_turn_user_message"&&m.subtype!=="realtime_message").length;if(records.length===0){return 0}return Math.max(userTurnCount,computeInitialTurnFromHistory(records,sessionId)+1)}__name(computeResumedPromptCountSeed,"computeResumedPromptCountSeed");function expandCollapsedHistory(items){return items.filter(item=>item.display?.kind!=="collapse-summary").map(stripSuppressOnRestore)}__name(expandCollapsedHistory,"expandCollapsedHistory");function applyCollapsePolicyAndSummary(rawItems,collapseOnResume,collapsePreviewCount=0){if(!collapseOnResume)return rawItems;if(collapsePreviewCount===-1)return rawItems;let boundary=rawItems.length;if(collapsePreviewCount>0){let userTurnCount=0;for(let i=rawItems.length-1;i>=0;i--){const item=rawItems[i];if(item.type==="user"&&item.sentToModel!==false){userTurnCount++;if(userTurnCount===collapsePreviewCount){boundary=i;break}}}if(userTurnCount<collapsePreviewCount){boundary=0}}const hiddenItems=applyResumeDisplayPolicy(rawItems.slice(0,boundary));const visibleItems=rawItems.slice(boundary);const uiHistoryItems=[...hiddenItems,...visibleItems];if(boundary>0){const nextId=rawItems[rawItems.length-1].id+1;return[...uiHistoryItems,{id:nextId,...createHistoryCollapseSummaryItem(boundary)}]}return uiHistoryItems}__name(applyCollapsePolicyAndSummary,"applyCollapsePolicyAndSummary");export{SHELL_COMMAND_NAME,SHELL_NAME,TOOL_STATUS,ICON,SPINNER_FRAMES,SPINNER_INTERVAL_MS,WAITING_SPINNER_FRAME,isCollapsibleTool,getActiveToolHint,buildToolSummary,isSubagentToolEntry,isFindingsListDisplay,coalesceFindingsHistoryItems,recoalesceFindingsHistoryItems,shouldDisplayGoalStateCause,waitForGoalRuntime,buildResumedHistoryItems,stripSuppressOnRestore,computeResumedPromptCountSeed,expandCollapsedHistory,applyCollapsePolicyAndSummary};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2025 Google LLC
|