gerege-cli 0.26.7 → 0.26.8
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/bundled/gerege-video/SKILL.md +22 -0
- package/bundled/gerege-video/scripts/video.js +137 -0
- package/chunks/{MaxSizedBox-LSNOJEKM.js → MaxSizedBox-LUINLOQW.js} +1 -1
- package/chunks/{StandaloneSessionPicker-KSYGPMEV.js → StandaloneSessionPicker-B7N4QO5D.js} +1 -1
- package/chunks/{acp-subagent-executor-NSW2MFUI.js → acp-subagent-executor-J6H6FKUT.js} +1 -1
- package/chunks/{acpAgent-3DTOHTDM.js → acpAgent-XG6SM2VU.js} +3 -3
- package/chunks/{advisor-7JGQPS7X.js → advisor-SZVPQNPA.js} +1 -1
- package/chunks/{agent-PNKQJGDO.js → agent-N7QF7BJS.js} +1 -1
- package/chunks/{agent-headless-7D33X7QQ.js → agent-headless-GLP5GUEX.js} +1 -1
- package/chunks/{agent-host-client-3R2MAUVE.js → agent-host-client-H4VOB3M6.js} +1 -1
- package/chunks/{agent-host-connections-2D7DECAE.js → agent-host-connections-E4C3OC4M.js} +1 -1
- package/chunks/{anthropicContentGenerator-MGTJJGEQ.js → anthropicContentGenerator-5VTWQLT5.js} +1 -1
- package/chunks/{autofix-pr-OIHHZSPQ.js → autofix-pr-HDYQDJS4.js} +1 -1
- package/chunks/{batch-6UDAMPAA.js → batch-3CRVN5VJ.js} +1 -1
- package/chunks/{bridge-QXVXPNJ6.js → bridge-NZ6WVBLQ.js} +1 -1
- package/chunks/{channel-settings-store-P4W4R5SJ.js → channel-settings-store-Z7I2JI6M.js} +1 -1
- package/chunks/{chunk-HVP4UF2Q.js → chunk-236DHGNH.js} +1 -1
- package/chunks/{chunk-GA35LMSX.js → chunk-2M3ND5WN.js} +1 -1
- package/chunks/{chunk-IZXHCHJD.js → chunk-36A6EXHB.js} +1 -1
- package/chunks/{chunk-QHYSRPQR.js → chunk-3ANIQTDT.js} +1 -1
- package/chunks/{chunk-WK666FGZ.js → chunk-3QTR2HAE.js} +3 -3
- package/chunks/{chunk-3EZ5GCUT.js → chunk-3TTHYXT3.js} +1 -1
- package/chunks/{chunk-YWK3E4WJ.js → chunk-4CE4GMDL.js} +1 -1
- package/chunks/{chunk-VUNHJ74J.js → chunk-4FVT657Y.js} +1 -1
- package/chunks/{chunk-BY46PCWY.js → chunk-4HSISRRA.js} +1 -1
- package/chunks/{chunk-2LMSDH6P.js → chunk-4SZUJ5RT.js} +1 -1
- package/chunks/{chunk-53IB4U4E.js → chunk-57D2OB3I.js} +1 -1
- package/chunks/{chunk-QTKPC24L.js → chunk-5FGBLIXB.js} +1 -1
- package/chunks/{chunk-5TWAP4OG.js → chunk-5HX2QGVR.js} +1 -1
- package/chunks/{chunk-K7GN4CMV.js → chunk-5ZNXAWOG.js} +6 -6
- package/chunks/{chunk-QTVSPQZQ.js → chunk-6CKX56LJ.js} +1 -1
- package/chunks/{chunk-4W27Z3OL.js → chunk-6NIQFWXP.js} +1 -1
- package/chunks/{chunk-6YFNUVJR.js → chunk-6PC6MZHL.js} +1 -1
- package/chunks/{chunk-DQQN2HOP.js → chunk-6VQKGKMJ.js} +1 -1
- package/chunks/{chunk-MXZXQUVP.js → chunk-6ZEMLEK2.js} +1 -1
- package/chunks/{chunk-RT6J7PV4.js → chunk-72VY2PJA.js} +1 -1
- package/chunks/{chunk-EEPNACXJ.js → chunk-75I3NYBD.js} +1 -1
- package/chunks/{chunk-ATTJQLQV.js → chunk-76L7ZDEK.js} +1 -1
- package/chunks/{chunk-T3CQ72HC.js → chunk-7XQ5D34E.js} +6 -6
- package/chunks/{chunk-4AKTP4MM.js → chunk-AYX75VXG.js} +1 -1
- package/chunks/{chunk-MDCA4I63.js → chunk-BBDFEMCF.js} +1 -1
- package/chunks/{chunk-N4ZQC5HB.js → chunk-BOTX7S66.js} +1 -1
- package/chunks/{chunk-UVMLWDRU.js → chunk-CY2QKKZA.js} +1 -1
- package/chunks/{chunk-W2CV36HT.js → chunk-D5JWQUID.js} +1 -1
- package/chunks/{chunk-WEPC42YR.js → chunk-DMIPB7RZ.js} +1 -1
- package/chunks/{chunk-BVV7UXES.js → chunk-DSKA3P2C.js} +1 -1
- package/chunks/{chunk-SAVYMUU3.js → chunk-DVC65H4X.js} +1 -1
- package/chunks/{chunk-MS2XCBPP.js → chunk-DVJSDCMX.js} +1 -1
- package/chunks/{chunk-4QOVM2LL.js → chunk-E6CPFQX2.js} +1 -1
- package/chunks/{chunk-LYFRGP42.js → chunk-EIFBGEXJ.js} +1 -1
- package/chunks/{chunk-3ICJI5KW.js → chunk-EQOHDAYU.js} +1 -1
- package/chunks/{chunk-Q5RRVBTY.js → chunk-EZPM4DLR.js} +1 -1
- package/chunks/{chunk-ISQMHOCC.js → chunk-F6U6T7QD.js} +1 -1
- package/chunks/{chunk-WCI33URB.js → chunk-FCGFBUHS.js} +1 -1
- package/chunks/{chunk-CK3OKTTL.js → chunk-G2LTZU67.js} +1 -1
- package/chunks/{chunk-WSI4G7XC.js → chunk-GMJSEK4V.js} +1 -1
- package/chunks/{chunk-QONPET6Y.js → chunk-HJMUBVXZ.js} +2 -2
- package/chunks/{chunk-H5EXNXGW.js → chunk-HQZTAA2U.js} +1 -1
- package/chunks/{chunk-5R2JIZID.js → chunk-I63TIQOI.js} +1 -1
- package/chunks/{chunk-IY7M5HKF.js → chunk-I65LBJN7.js} +1 -1
- package/chunks/{chunk-H34KVVI4.js → chunk-IBDOC27R.js} +1 -1
- package/chunks/{chunk-N6EFYQ7M.js → chunk-IKF2HWEV.js} +1 -1
- package/chunks/{chunk-CDKBM72V.js → chunk-K6NS2HXT.js} +1 -1
- package/chunks/{chunk-BIPPD7W6.js → chunk-KTRNYPQP.js} +1 -1
- package/chunks/{chunk-DTX2OVQW.js → chunk-L3ANU5JZ.js} +1 -1
- package/chunks/{chunk-WXK7Z45R.js → chunk-LKPMADUO.js} +1 -1
- package/chunks/{chunk-4VR4DUUD.js → chunk-M56Y2B6N.js} +1 -1
- package/chunks/{chunk-YY4GWNTU.js → chunk-N5KRBAK5.js} +2 -2
- package/chunks/{chunk-DVUKYOCJ.js → chunk-NA2WJPOU.js} +1 -1
- package/chunks/{chunk-O3TUZQP4.js → chunk-NGOWLXYK.js} +1 -1
- package/chunks/{chunk-F7622ZRQ.js → chunk-NL7P73ZP.js} +1 -1
- package/chunks/{chunk-U5YOAOU3.js → chunk-NS3QR7D3.js} +1 -1
- package/chunks/{chunk-FTF2NFLB.js → chunk-O5JCCBMQ.js} +1 -1
- package/chunks/{chunk-DEJ47KJE.js → chunk-OOKFFZHF.js} +1 -1
- package/chunks/{chunk-4A663FE6.js → chunk-OTYPLLMT.js} +5 -5
- package/chunks/{chunk-NPAENNRO.js → chunk-P7NHWX27.js} +1 -1
- package/chunks/{chunk-HXTYFGSQ.js → chunk-PC5QZUKR.js} +1 -1
- package/chunks/{chunk-RULGA7WE.js → chunk-PS7MQL57.js} +2 -2
- package/chunks/{chunk-FKUDVIME.js → chunk-PXWHOFAA.js} +1 -1
- package/chunks/{chunk-6WV5RKYB.js → chunk-Q65LVCDR.js} +1 -1
- package/chunks/{chunk-ULLW2AYD.js → chunk-QDUDLELH.js} +1 -1
- package/chunks/{chunk-PMBI46K4.js → chunk-QF22ILPV.js} +1 -1
- package/chunks/{chunk-LY4XTBL4.js → chunk-QW7MAG2E.js} +1 -1
- package/chunks/{chunk-IIHUDJX7.js → chunk-RXK6XD6F.js} +1 -1
- package/chunks/{chunk-QSPXKBUX.js → chunk-SVDFCWS7.js} +1 -1
- package/chunks/{chunk-NHPKD7LY.js → chunk-TKP3GAUI.js} +1 -1
- package/chunks/{chunk-WF7Q3ZSQ.js → chunk-TUS74LFI.js} +1 -1
- package/chunks/{chunk-OZFZBGZG.js → chunk-U7YGHPSL.js} +1 -1
- package/chunks/{chunk-G4MWPXNY.js → chunk-UB37RBSK.js} +1 -1
- package/chunks/{chunk-4LC4INFI.js → chunk-UK5SIRH4.js} +1 -1
- package/chunks/{chunk-7HFFTOAD.js → chunk-UTTSBCFR.js} +1 -1
- package/chunks/{chunk-IQMKQKKD.js → chunk-UYV4ZVXY.js} +2 -2
- package/chunks/{chunk-E3KWSRJN.js → chunk-VC3JJL7E.js} +1 -1
- package/chunks/{chunk-FRVXSKL4.js → chunk-VKWVIWLK.js} +1 -1
- package/chunks/{chunk-L7LO3YRT.js → chunk-VUI6STKU.js} +1 -1
- package/chunks/{chunk-VK7LOUOJ.js → chunk-W3YXE55M.js} +1 -1
- package/chunks/{chunk-JHC22BZH.js → chunk-WAIPC47V.js} +1 -1
- package/chunks/{chunk-P2MZZMCS.js → chunk-WMJ6UHDP.js} +1 -1
- package/chunks/{chunk-6JAXAFX7.js → chunk-WZU2ECUD.js} +1 -1
- package/chunks/{chunk-HJLRKM3W.js → chunk-XAGIZY2Y.js} +1 -1
- package/chunks/{chunk-2J2BQ3PL.js → chunk-XGZYVULJ.js} +2 -2
- package/chunks/{chunk-QVHDM6N7.js → chunk-XJIHDVPX.js} +1 -1
- package/chunks/{chunk-ZFOEVHWG.js → chunk-XVDIHFRH.js} +1 -1
- package/chunks/{chunk-F5SLLEJY.js → chunk-YMEW4TTT.js} +1 -1
- package/chunks/{chunk-NYBYDW6R.js → chunk-Z32URWBG.js} +1 -1
- package/chunks/{chunk-WMLYHZZX.js → chunk-Z6HRXHJP.js} +1 -1
- package/chunks/{chunk-UM5KBBYP.js → chunk-ZO4F6ZWR.js} +1 -1
- package/chunks/{codex-subagent-executor-GPTKVP7H.js → codex-subagent-executor-DDKYNU42.js} +1 -1
- package/chunks/{config-utils-6B5FHBSF.js → config-utils-S7Z2ZZ2E.js} +1 -1
- package/chunks/{contextCommand-FGRDE3GA.js → contextCommand-7F4PGV2A.js} +1 -1
- package/chunks/{core-runtime-OFEHSKDB.js → core-runtime-LBH3U7ZF.js} +1 -1
- package/chunks/{create-sub-session-D2KEWVHQ.js → create-sub-session-56DS2T6L.js} +1 -1
- package/chunks/{cron-create-RFGGKTL7.js → cron-create-PBP3C46Q.js} +1 -1
- package/chunks/{daemon-git-worktree-guard-AV752IOZ.js → daemon-git-worktree-guard-WJS6FBDA.js} +1 -1
- package/chunks/{daemon-status-provider-GHQBRDMC.js → daemon-status-provider-UPPAEHJ6.js} +1 -1
- package/chunks/{daemon-trust-policy-24ENJNTQ.js → daemon-trust-policy-4Z5HSNUX.js} +1 -1
- package/chunks/{daemon-trust-policy-monitor-NMSQAGWV.js → daemon-trust-policy-monitor-WFWDOYX3.js} +1 -1
- package/chunks/{deferred-core-runtime-5BAMFFOI.js → deferred-core-runtime-MJYNEA4N.js} +1 -1
- package/chunks/{edit-XCECLEH3.js → edit-U7TGKKK3.js} +1 -1
- package/chunks/{enterPlanMode-SEN2PMRM.js → enterPlanMode-27HC5AXN.js} +1 -1
- package/chunks/{environment-CCPQJYKS.js → environment-PHWY6C4P.js} +1 -1
- package/chunks/{errors-Y6HHUTGK.js → errors-F2EYYFI3.js} +1 -1
- package/chunks/{execution-tool-HADWGMIG.js → execution-tool-O4KJ5SMM.js} +1 -1
- package/chunks/{execution-worker-GZS7WOQL.js → execution-worker-AMFXZ7JD.js} +1 -1
- package/chunks/{exitPlanMode-76B5HDLT.js → exitPlanMode-LDYL43PB.js} +1 -1
- package/chunks/{fast-path-OEV7LQYV.js → fast-path-HTODEVOR.js} +1 -1
- package/chunks/{glob-NLWCQRMS.js → glob-NKQJJZND.js} +1 -1
- package/chunks/{goal-tools-43XV33BT.js → goal-tools-47I455VV.js} +1 -1
- package/chunks/{handleAutoUpdate-JDQWGSSP.js → handleAutoUpdate-MJKTDJUO.js} +1 -1
- package/chunks/{i18n-JW6BVEGF.js → i18n-TCOB4TC5.js} +1 -1
- package/chunks/{initializer-UT6JLZ3O.js → initializer-NLYOGZZS.js} +1 -1
- package/chunks/{installationInfo-LKWDV3S2.js → installationInfo-TF2RSJOG.js} +1 -1
- package/chunks/{interactive-mod-session-2KWKYVPC.js → interactive-mod-session-5F7R3KSA.js} +1 -1
- package/chunks/{list-BKINK3S2.js → list-U2AEVLFP.js} +1 -1
- package/chunks/{llm-3RWXAVM2.js → llm-EV2QTQBU.js} +4 -4
- package/chunks/{llm-content-generator-MDRBSH73.js → llm-content-generator-ZXUSPPG2.js} +1 -1
- package/chunks/{loadedSettingsAdapter-WWJUKWUN.js → loadedSettingsAdapter-TLRI22X7.js} +1 -1
- package/chunks/{local-TT4FLCTR.js → local-ZTSBSKWV.js} +1 -1
- package/chunks/{local-execution-environment-OBA6VWYL.js → local-execution-environment-F263PSIM.js} +1 -1
- package/chunks/{loggingContentGenerator-CK7IKYQH.js → loggingContentGenerator-2XHSIJQD.js} +1 -1
- package/chunks/{loop-wakeup-4MSRX3DY.js → loop-wakeup-5ET3JHUT.js} +1 -1
- package/chunks/{manage-memory-PX5PZJKZ.js → manage-memory-MJEQ47H2.js} +1 -1
- package/chunks/{managed-execution-engine-WMAUR3ZK.js → managed-execution-engine-ODPR5OEH.js} +1 -1
- package/chunks/{managed-local-serve-X7REHGB4.js → managed-local-serve-S5R4Z5OL.js} +1 -1
- package/chunks/managed-npm-update-BUI5APGY.js +8 -0
- package/chunks/{managed-runtime-attestation-worker-F4AT53M5.js → managed-runtime-attestation-worker-BQP4E7LQ.js} +1 -1
- package/chunks/{managed-runtime-bootstrap-3BP5JRJX.js → managed-runtime-bootstrap-SRBDFSKK.js} +1 -1
- package/chunks/{managed-runtime-session-worker-2PO7J5UK.js → managed-runtime-session-worker-UI23BTYJ.js} +1 -1
- package/chunks/{managed-runtime-ssh-worker-4N7EMRSV.js → managed-runtime-ssh-worker-HU4CIJRK.js} +1 -1
- package/chunks/{managed-session-authority-MYOYTUM2.js → managed-session-authority-XSSTLAEY.js} +1 -1
- package/chunks/{mcp-5OTEMZ7P.js → mcp-WLHDOKP7.js} +1 -1
- package/chunks/{memory-TNW7RSAV.js → memory-OUUHPSDD.js} +1 -1
- package/chunks/{model-call-collection-KNTWFZQS.js → model-call-collection-4A2EB76B.js} +1 -1
- package/chunks/{model-configuration-U5C5P5UQ.js → model-configuration-4CGUFKEP.js} +1 -1
- package/chunks/{modelConfigUtils-R4KFI2WK.js → modelConfigUtils-HUEERWBA.js} +1 -1
- package/chunks/{monitor-RD2PFK42.js → monitor-FXL5UNMP.js} +1 -1
- package/chunks/{nonInteractiveCli-QQ72HZSH.js → nonInteractiveCli-W7M2O43W.js} +1 -1
- package/chunks/{nonInteractiveToolExecutor-QPQYR6IS.js → nonInteractiveToolExecutor-EMLI363Q.js} +1 -1
- package/chunks/{notebook-edit-YLRN3UZT.js → notebook-edit-R5RSLSSH.js} +1 -1
- package/chunks/{omni-CUJ52EW5.js → omni-DNZGITTE.js} +1 -1
- package/chunks/{openaiContentGenerator-6B5MAU54.js → openaiContentGenerator-PKOPYMHR.js} +1 -1
- package/chunks/{openaiResponsesContentGenerator-I245I3R7.js → openaiResponsesContentGenerator-MHH2MF3V.js} +1 -1
- package/chunks/{pidfile-P2HIGAUA.js → pidfile-5ZNJWMKG.js} +1 -1
- package/chunks/{processUtils-JSKN5UGS.js → processUtils-JIHQDASW.js} +1 -1
- package/chunks/{prompt-terminal-ledger-F5TSXVGU.js → prompt-terminal-ledger-L3LZ5SLR.js} +1 -1
- package/chunks/{qwenContentGenerator-IEDZONWG.js → qwenContentGenerator-QCZL7HJJ.js} +1 -1
- package/chunks/{reactive-degrade-FYZBJCF6.js → reactive-degrade-YUXOUQG4.js} +1 -1
- package/chunks/{read-file-VNZNSD6X.js → read-file-FBNU3AVX.js} +1 -1
- package/chunks/{resumeHistoryUtils-IDPE6N2N.js → resumeHistoryUtils-5FPRTI4A.js} +1 -1
- package/chunks/{review-TBJRZWTD.js → review-NLFYSNM3.js} +1 -1
- package/chunks/{ripGrep-4W5B5FOE.js → ripGrep-JUAPC5LD.js} +1 -1
- package/chunks/{run-qwen-serve-44X262G5.js → run-qwen-serve-JP64UQ3Y.js} +1 -1
- package/chunks/{runtime-6H6LKD73.js → runtime-D2QUYM6U.js} +1 -1
- package/chunks/{sandboxConfig-SQXDRGVN.js → sandboxConfig-7VZJQV6H.js} +1 -1
- package/chunks/{scheduled-tasks-62IZKHJG.js → scheduled-tasks-PC6EH75E.js} +1 -1
- package/chunks/{scheduler-QUCXJYRL.js → scheduler-RUV2FNDR.js} +1 -1
- package/chunks/{search-memory-TC2Z34QN.js → search-memory-YJTJ7BRU.js} +1 -1
- package/chunks/{send-message-TFZX7KI7.js → send-message-EEEFFTHX.js} +1 -1
- package/chunks/{serve-WSICDFGG.js → serve-KMIZDYON.js} +1 -1
- package/chunks/{server-GYYVTNGY.js → server-DUPK3V7B.js} +3 -3
- package/chunks/{session-KF3O23ZJ.js → session-CW5YMFMP.js} +1 -1
- package/chunks/{session-attachments-root-7HFUSONH.js → session-attachments-root-5H5GFHLI.js} +1 -1
- package/chunks/{session-execution-engine-selector-NVILT6BR.js → session-execution-engine-selector-MVXM2HZW.js} +1 -1
- package/chunks/{session-pr-refresh-3KDFTDEV.js → session-pr-refresh-4UPONX4L.js} +1 -1
- package/chunks/{sessionService-XRTFLPDW.js → sessionService-GGCYISSL.js} +1 -1
- package/chunks/{settings-QPPK6WXE.js → settings-AASJCESS.js} +1 -1
- package/chunks/{shell-WYQDZWL7.js → shell-V4WWLW3Q.js} +1 -1
- package/chunks/{skill-FYPT6AU7.js → skill-NDEBB7VX.js} +1 -1
- package/chunks/{skill-settings-OGFI5KZF.js → skill-settings-YAI3GYU5.js} +1 -1
- package/chunks/{spawnChannel-ANOOVPG7.js → spawnChannel-6JKVJAXZ.js} +1 -1
- package/chunks/{standalone-update-45WTDY4E.js → standalone-update-NJP5OCKJ.js} +1 -1
- package/chunks/{start-opentui-ui-TL5WK33V.js → start-opentui-ui-M4B4SXRM.js} +1 -1
- package/chunks/{startInteractiveUI-N2IREVBM.js → startInteractiveUI-O4JUDEAU.js} +1 -1
- package/chunks/{team-create-R77PRZ5U.js → team-create-NLJ7QBLD.js} +1 -1
- package/chunks/{team-plan-approval-6DCRKB5I.js → team-plan-approval-XKYPVWNG.js} +1 -1
- package/chunks/{terminal-image-renderer-TB7EX2WW.js → terminal-image-renderer-47TD747D.js} +1 -1
- package/chunks/{theme-manager-RQDXJGVR.js → theme-manager-AANEBPLJ.js} +1 -1
- package/chunks/{tool-call-LVB4NCDT.js → tool-call-ETH3LS7Y.js} +1 -1
- package/chunks/{tool-result-media-LRBB2KS6.js → tool-result-media-EFOEPAF2.js} +1 -1
- package/chunks/{tool-search-OG73QAQZ.js → tool-search-J3CF5PRN.js} +1 -1
- package/chunks/{total-session-admission-A4CUF6AD.js → total-session-admission-3DC52PLQ.js} +1 -1
- package/chunks/{trustedFolders-LSGOYTU2.js → trustedFolders-4KPWZZKB.js} +1 -1
- package/chunks/{update-relaunch-OGC6BZO7.js → update-relaunch-A67BS7QS.js} +1 -1
- package/chunks/{updateCheck-7J3GXTER.js → updateCheck-X623JRSY.js} +1 -1
- package/chunks/{upload-config-ML5XEJIF.js → upload-config-X2CR3F26.js} +1 -1
- package/chunks/{useAutoAcceptIndicator-6DH6GQ2X.js → useAutoAcceptIndicator-INIOQGJH.js} +1 -1
- package/chunks/{validateNonInterActiveAuth-KJDAGZCM.js → validateNonInterActiveAuth-XJ2U5CLB.js} +1 -1
- package/chunks/{version-7JN2YXL2.js → version-MFHRMM7W.js} +1 -1
- package/chunks/{web-fetch-42ZR4FEZ.js → web-fetch-3GEJ62DH.js} +1 -1
- package/chunks/{web-search-74NLPMZJ.js → web-search-WJZO3Q3A.js} +1 -1
- package/chunks/{workflow-WNPHX42I.js → workflow-ML7ITCMH.js} +1 -1
- package/chunks/{workflow-ancestor-trust-HGF6G7LQ.js → workflow-ancestor-trust-M3VFMS73.js} +1 -1
- package/chunks/{workspace-agents-3YFBFAK3.js → workspace-agents-YFZMV7EF.js} +1 -1
- package/chunks/{workspace-providers-status-EPJI6KRV.js → workspace-providers-status-3COKLBCI.js} +1 -1
- package/chunks/{workspace-recovery-worker-T3FK5YOD.js → workspace-recovery-worker-QURA3WFZ.js} +1 -1
- package/chunks/{workspace-registration-store-VEXYBDMA.js → workspace-registration-store-F3AGIOBW.js} +1 -1
- package/chunks/{workspace-registry-NRZYTP2X.js → workspace-registry-QUBL3RW6.js} +1 -1
- package/chunks/{workspace-runtime-coordinator-USNSTP2V.js → workspace-runtime-coordinator-22TSDHXX.js} +1 -1
- package/chunks/{workspace-service-USATWO56.js → workspace-service-UUENTHNO.js} +1 -1
- package/chunks/{workspace-skills-status-M5JTSFDL.js → workspace-skills-status-NNQQBBCJ.js} +1 -1
- package/chunks/{workspace-trust-reconciler-ZUZ2O5WC.js → workspace-trust-reconciler-3CMMNCGG.js} +1 -1
- package/chunks/{write-file-UMJVKE4S.js → write-file-DEAFIK4C.js} +1 -1
- package/chunks/{zoom-image-76XYHQ3Z.js → zoom-image-YYO22PQG.js} +1 -1
- package/cli-entry.js +2 -3
- package/cli.js +2 -2
- package/execution-worker.js +1 -1
- package/export-transcript-document.js +1 -1
- package/package.json +2 -12
- package/chunks/managed-npm-update-6HUVAJH7.js +0 -8
- package/opentui-assets/@opentui/core/assets/javascript/highlights.scm +0 -205
- package/opentui-assets/@opentui/core/assets/javascript/tree-sitter-javascript.wasm +0 -0
- package/opentui-assets/@opentui/core/assets/markdown/highlights.scm +0 -150
- package/opentui-assets/@opentui/core/assets/markdown/injections.scm +0 -27
- package/opentui-assets/@opentui/core/assets/markdown/tree-sitter-markdown.wasm +0 -0
- package/opentui-assets/@opentui/core/assets/markdown_inline/highlights.scm +0 -115
- package/opentui-assets/@opentui/core/assets/markdown_inline/tree-sitter-markdown_inline.wasm +0 -0
- package/opentui-assets/@opentui/core/assets/typescript/highlights.scm +0 -604
- package/opentui-assets/@opentui/core/assets/typescript/tree-sitter-typescript.wasm +0 -0
- package/opentui-assets/@opentui/core/assets/zig/highlights.scm +0 -284
- package/opentui-assets/@opentui/core/assets/zig/tree-sitter-zig.wasm +0 -0
- package/opentui-assets/@opentui/core/parser.worker.js +0 -4566
- package/opentui-assets/@opentui/core-darwin-arm64/libopentui.dylib +0 -0
- package/opentui-assets/@opentui/core-darwin-x64/libopentui.dylib +0 -0
- package/opentui-assets/@opentui/core-linux-arm64/libopentui.so +0 -0
- package/opentui-assets/@opentui/core-linux-x64/libopentui.so +0 -0
- package/opentui-assets/web-tree-sitter/tree-sitter.wasm +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{GATE_OUTPUT_BUDGET_BYTES,jsonBytes}from"./chunk-PBCOQPHE.js";import{MAX_CHECK_FIX_PUSHES,MAX_FAILING_CHECKS,MAX_NEEDS_HUMAN,MAX_PUSHES,NO_FOLLOW,REPLY_MARKER,TASK_OPTION,assertNoFixInFlight,assertOwnedBySession,assertPositiveInteger,assertWatching,autofixPrPaths,checkAttemptKey,checkoutHoldsWork,cleanupCommand,clearAbandonedFix,cloneWorktreeRoots,currentSessionId,findWatchRoot,fixEndCommand,fixInFlight,fixSnapshotPath,fixStartCommand,freshAttempt,ghNotFound,hasUncommittedChanges,historyPath,isAncestor,isBranchName,isCommandSafeName,isRegularFile,networkGit,networkGitEnv,readFixMarker,readGateCursor,readHistory,readState,remoteRef,requireState,requireWorktree,rerunFloors,resolveWatchRoot,sameRepository,scheduleCommand,statePaths,statusCommand,taskArg,trustAnchor,vouchedScanRoots,watchRoot,withKnownHead,withWatchLock,writeAnchor,writeGateCursor,writeState}from"./chunk-
|
|
3
|
+
import{GATE_OUTPUT_BUDGET_BYTES,jsonBytes}from"./chunk-PBCOQPHE.js";import{MAX_CHECK_FIX_PUSHES,MAX_FAILING_CHECKS,MAX_NEEDS_HUMAN,MAX_PUSHES,NO_FOLLOW,REPLY_MARKER,TASK_OPTION,assertNoFixInFlight,assertOwnedBySession,assertPositiveInteger,assertWatching,autofixPrPaths,checkAttemptKey,checkoutHoldsWork,cleanupCommand,clearAbandonedFix,cloneWorktreeRoots,currentSessionId,findWatchRoot,fixEndCommand,fixInFlight,fixSnapshotPath,fixStartCommand,freshAttempt,ghNotFound,hasUncommittedChanges,historyPath,isAncestor,isBranchName,isCommandSafeName,isRegularFile,networkGit,networkGitEnv,readFixMarker,readGateCursor,readHistory,readState,remoteRef,requireState,requireWorktree,rerunFloors,resolveWatchRoot,sameRepository,scheduleCommand,statePaths,statusCommand,taskArg,trustAnchor,vouchedScanRoots,watchRoot,withKnownHead,withWatchLock,writeAnchor,writeGateCursor,writeState}from"./chunk-QDUDLELH.js";import{currentUser,ensureAuthenticated,gh,ghWithInput,isOwnerRepo,resolveGhHost,setGhHost}from"./chunk-UPWFKIG7.js";import{git,gitOpt,gitRaw,redirectedAncestor,refExists,repoRoot}from"./chunk-UK5SIRH4.js";import{matchRemotes,normalizeSegment}from"./chunk-CTMNGGOU.js";import{isWithinRoot}from"./chunk-IDXJIDME.js";import"./chunk-G2LTZU67.js";import"./chunk-QS2ZMQIS.js";import"./chunk-S7IKHQ6I.js";import"./chunk-PAD5GPDY.js";import"./chunk-MD3ZEOBX.js";import"./chunk-SSYS5YN5.js";import"./chunk-X5QSFJVS.js";import"./chunk-OMDTFGTX.js";import"./chunk-3TTHYXT3.js";import"./chunk-46VUDNCL.js";import"./chunk-MKH3EH7O.js";import"./chunk-VC3JJL7E.js";import"./chunk-VKWVIWLK.js";import"./chunk-HW6SU6MX.js";import"./chunk-ZHHFNZ5J.js";import"./chunk-AKWYMQKU.js";import"./chunk-MZUOREFD.js";import"./chunk-DSKA3P2C.js";import"./chunk-7XZVMIY5.js";import"./chunk-4HSISRRA.js";import"./chunk-ZZJXFLVM.js";import"./chunk-RKDS7A4H.js";import"./chunk-QF22ILPV.js";import"./chunk-IV3HAIUN.js";import"./chunk-XFMPZINJ.js";import"./chunk-DECUAM3U.js";import"./chunk-QX7W2HY7.js";import"./chunk-HN5UYLPU.js";import"./chunk-PGRN3GZY.js";import"./chunk-HTW7PYHK.js";import"./chunk-AMGUAA4G.js";import"./chunk-YFTVFH2A.js";import"./chunk-ZBHL2CXR.js";import"./chunk-NIOS3B3V.js";import"./chunk-7XQ5D34E.js";import"./chunk-R2EHHA2C.js";import"./chunk-YK7NDQKM.js";import"./chunk-ZLZF2ZDD.js";import"./chunk-OMSVOFTC.js";import"./chunk-PHIPLV2I.js";import"./chunk-ZOTKZI2P.js";import"./chunk-A6G5TAIF.js";import"./chunk-YVBHCSZD.js";import"./chunk-FIXDX63I.js";import"./chunk-T7CHK6C2.js";import"./chunk-PT7NZBDY.js";import"./chunk-TWP72VRH.js";import"./chunk-UYEWRLGD.js";import"./chunk-QVPT37XZ.js";import"./chunk-YVD4O5ZB.js";import"./chunk-T6W33SET.js";import"./chunk-WK2IBT6D.js";import"./chunk-QZV4PFQK.js";import"./chunk-ILECDNJX.js";import"./chunk-QXQGUM3Y.js";import"./chunk-UQ7IROJH.js";import"./chunk-SZCBUCNH.js";import"./chunk-BEKROCWN.js";import"./chunk-5SUFJTQQ.js";import"./chunk-BYU42MLK.js";import"./chunk-JWQXU3SR.js";import"./chunk-5LZ2DPLH.js";import"./chunk-XQJOZDV7.js";import"./chunk-CV2UAEZA.js";import"./chunk-FUBDS3AV.js";import"./chunk-HW6AWS7W.js";import"./chunk-KLC3OD2M.js";import"./chunk-Q5IZXKUJ.js";import"./chunk-G5PYYZMM.js";import"./chunk-BG67XABA.js";import"./chunk-OBOU4ZZM.js";import"./chunk-D7XCQWP2.js";import"./chunk-AE5OMKRY.js";import"./chunk-OBV7RNHV.js";import"./chunk-7CQMWEMY.js";import"./chunk-GOZYWU4B.js";import"./chunk-OUC3WICA.js";import"./chunk-JZK2WGXA.js";import"./chunk-MPHSE7M4.js";import"./chunk-S2ZKZXHX.js";import"./chunk-7UK4WJWS.js";import"./chunk-4GP3PH7Z.js";import"./chunk-4QQKOW5M.js";import"./chunk-OV3EBH6J.js";import"./chunk-EBMCWXGZ.js";import"./chunk-XZTE4YTN.js";import"./chunk-LSASUDF2.js";import"./chunk-2V5EKGDK.js";import"./chunk-MOKVM4PT.js";import"./chunk-YIW3H46P.js";import"./chunk-EOMRLUNZ.js";import"./chunk-4ZRCV3JY.js";import"./chunk-TL6MLBXR.js";import"./chunk-NMY3PYNO.js";import"./chunk-YGLM5XPP.js";import"./chunk-WGNF7FPC.js";import"./chunk-4NPYOXJO.js";import"./chunk-MWGB5RCF.js";import"./chunk-SCD5TUBG.js";import"./chunk-NTRFETZB.js";import"./chunk-TL3SF2GA.js";import"./chunk-LMJPU2JM.js";import"./chunk-VFB6Q74I.js";import"./chunk-4JNHUZ7M.js";import"./chunk-SW54YEPK.js";import"./chunk-ZCRL73DT.js";import"./chunk-A6LT3FIJ.js";import"./chunk-S6RXVOY6.js";import"./chunk-YZFNBUKG.js";import"./chunk-AGEDDL7Z.js";import"./chunk-2NJJHZ52.js";import"./chunk-BN4FIQ77.js";import"./chunk-X64RXJQQ.js";import"./chunk-HETUGUHE.js";import"./chunk-ET2Z7ZGF.js";import"./chunk-XFPYXD2P.js";import"./chunk-3YWXKSOI.js";import"./chunk-5CWTKFI4.js";import"./chunk-C4MVD5OI.js";import"./chunk-Z2W7S4O4.js";import"./chunk-476F6QIM.js";import"./chunk-4R67LXKL.js";import"./chunk-FQRF6B65.js";import"./chunk-ZWPSBU7K.js";import"./chunk-UQFTXKEB.js";import"./chunk-HDGTWJ24.js";import"./chunk-W5NWIGKO.js";import"./chunk-KVA6DHHF.js";import"./chunk-PWOQASXT.js";import"./chunk-K7JCVESI.js";import"./chunk-Y6HHV4LC.js";import"./chunk-RP57XAJ2.js";import"./chunk-Z6AR5XE5.js";import"./chunk-7DOOXUDG.js";import"./chunk-77V43YOE.js";import"./chunk-7U7CWMP7.js";import"./chunk-EFTJIDS3.js";import"./chunk-4DIWAQ5G.js";import"./chunk-Q6UAOTP3.js";import"./chunk-HQZTAA2U.js";import"./chunk-GOR7FFVE.js";import"./chunk-4ZBZL23U.js";import{atomicWriteFileSync}from"./chunk-BMHYEQTI.js";import"./chunk-ZZZAYAJW.js";import"./chunk-XMANRGPK.js";import"./chunk-3XVPZY7X.js";import"./chunk-KQX4H2D3.js";import"./chunk-URNNJMIC.js";import"./chunk-GU22I6TY.js";import"./chunk-YEYW7PPR.js";import{writeStdoutLine}from"./chunk-M4ECEHLX.js";import"./chunk-DBRQGEEI.js";import"./chunk-B3ZFUGTC.js";import"./chunk-IRINPFG7.js";import"./chunk-6GTPLW7K.js";import"./chunk-NGVRCUYD.js";import"./chunk-5DTFN37U.js";import"./chunk-2YUBAWQ6.js";import"./chunk-O5EKX7LG.js";import"./chunk-TM6ZCBR7.js";import"./chunk-SVAPAMMG.js";import"./chunk-3KUHQGOS.js";import"./chunk-I6S7NGX3.js";import"./chunk-SBZFGYYS.js";import"./chunk-JAUJI56S.js";import"./chunk-I4H7NUVP.js";import"./chunk-EPODBRBP.js";import{realpathNearestExisting}from"./chunk-OKN3Z5C5.js";import"./chunk-XYB7GC5U.js";import"./chunk-2UOMCYQG.js";import"./chunk-I7L2TX4M.js";import"./chunk-MK3OONRA.js";import"./chunk-COGTQ5KZ.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();import{existsSync,mkdirSync,statSync}from"node:fs";import{dirname}from"node:path";var PR_FIELDS="number,state,url,isDraft,headRefName,headRefOid,baseRefName,isCrossRepository,maintainerCanModify,headRepository,headRepositoryOwner,author";var WRITE_PERMISSIONS=new Set(["WRITE","MAINTAIN","ADMIN"]);function eligibilityError(pr,repo,viewer){if(pr.state!=="OPEN"){return`PR #${pr.number} is ${pr.state.toLowerCase()}; autofix needs an open PR.`}if(!pr.headRepository||!pr.headRepositoryOwner){return`PR #${pr.number}'s head repository no longer exists.`}if(!isBranchName(pr.headRefName)){return`PR #${pr.number}'s head branch ${JSON.stringify(pr.headRefName)} is not a name autofix can hand to git.`}if(!isBranchName(pr.baseRefName)||!isCommandSafeName(pr.baseRefName)){return`PR #${pr.number}'s base branch ${JSON.stringify(pr.baseRefName)} cannot be named in a command as it is.`}if(!pr.isCrossRepository&&pr.headRefName===repo.defaultBranchRef?.name){return`PR #${pr.number}'s head is the default branch (${pr.headRefName}); autofix never pushes there.`}const canWrite=WRITE_PERMISSIONS.has(repo.viewerPermission??"");if(!pr.isCrossRepository){return canWrite?null:`${viewer} cannot push to this repository (permission: ${repo.viewerPermission??"none"}).`}if(pr.headRepositoryOwner.login===viewer)return null;if(canWrite&&pr.maintainerCanModify)return null;return`${viewer} cannot push to the fork ${pr.headRepositoryOwner.login}/${pr.headRepository.name}: the PR does not allow edits from maintainers.`}__name(eligibilityError,"eligibilityError");function pushUrl(host,owner,repo,protocol){if(protocol!=="ssh")return`https://${host}/${owner}/${repo}.git`;return host.includes(":")?`ssh://git@${host}/${owner}/${repo}.git`:`git@${host}:${owner}/${repo}.git`}__name(pushUrl,"pushUrl");function onlyRemote(remoteV,owner,repo,host){const{matched}=matchRemotes(remoteV,{owner,repo,host});return matched.length===1?matched[0]:null}__name(onlyRemote,"onlyRemote");function pushTargetFor(remoteV,host,owner,repo){const remote=onlyRemote(remoteV,owner,repo,host);if(remote!==null&&remotePushesTo(remote,host,owner,repo)){return remote}return pushUrl(host,owner,repo,gh("config","get","git_protocol","-h",host))}__name(pushTargetFor,"pushTargetFor");function remotePushesTo(remote,host,owner,repo){const pushUrls=gitOpt("remote","get-url","--push","--all",remote);if(pushUrls===null)return false;const urls=pushUrls.split("\n").map(line=>line.trim()).filter(line=>line!=="");return urls.length>0&&urls.every(url=>matchRemotes(`${remote} ${url} (fetch)`,{owner,repo,host}).matched.includes(remote))}__name(remotePushesTo,"remotePushesTo");function authorCanPush(slug,author,viewer){if(!author)return false;if(author===viewer)return true;try{const permission=gh("api",`repos/${slug}/collaborators/${encodeURIComponent(author)}/permission`,"--jq",".permission");return permission==="admin"||permission==="write"}catch(err){if(ghNotFound(err))return false;const text=`${err.message}
|
|
4
4
|
${String(err.stderr??"")}`;throw new Error(`could not ask GitHub whether ${author} can push to ${slug}; try again: ${text.trim().split("\n").at(-1)??""}`)}}__name(authorCanPush,"authorCanPush");function report(state,extra){writeStdoutLine(JSON.stringify({worktreePath:state.worktreePath,branch:state.branch,headSha:state.lastKnownHeadSha,headRefName:state.headRefName,baseRefName:state.baseRefName,pushTarget:state.pushTarget,viewer:state.viewer,prAuthor:state.prAuthor,sessionId:state.sessionId,host:state.host,preparedAt:state.preparedAt??null,authorCanPush:state.authorCanPush??false,...extra}))}__name(report,"report");function localCopy(state){const upstream=gitOpt("for-each-ref","--format=%(upstream:short)",`refs/heads/${state.headRefName}`);if(upstream!==`${state.pushTarget}/${state.headRefName}`){return{localUnpushedCommits:0,localUncommittedChanges:false,localWorkUnknown:false}}const unpushed=gitOpt("rev-list","--count",`refs/heads/${state.headRefName}`,"--not",state.lastKnownHeadSha);const checkouts=worktreeCheckouts(state.headRefName);const work=checkouts?.map(checkoutHoldsWork)??null;return{localUnpushedCommits:unpushed===null?0:Number(unpushed),localUncommittedChanges:work?.some(held=>held===true)??false,localWorkUnknown:unpushed===null||work===null||work.some(held=>held===null)}}__name(localCopy,"localCopy");function worktreeCheckouts(branch){const z=gitOpt("worktree","list","--porcelain","-z");if(z!==null)return parseWorktrees(z.split("\0"),branch);const plain=gitOpt("worktree","list","--porcelain");return plain===null?null:parseWorktrees(plain.split("\n"),branch)}__name(worktreeCheckouts,"worktreeCheckouts");function parseWorktrees(fields,branch){const paths=[];let worktree=null;for(const field of fields){if(field===""){worktree=null}else if(field.startsWith("worktree ")){worktree=field.slice("worktree ".length)}else if(worktree!==null&&field===`branch refs/heads/${branch}`){paths.push(worktree)}}return paths}__name(parseWorktrees,"parseWorktrees");function remotesFor(host,owner,repo,headOwner,headName){const remoteV=git("remote","-v");const remote=onlyRemote(remoteV,owner,repo,host);if(!remote){throw new Error(`no single git remote here serves ${host}/${owner}/${repo}; autofix needs a clone of the PR's repository.`)}if(!isBranchName(remote)||!isCommandSafeName(remote)){throw new Error(`the remote ${JSON.stringify(remote)} cannot be named in a command as it is; rename it (\`git remote rename\`) to watch this PR.`)}return{remote,pushTarget:pushTargetFor(remoteV,host,headOwner,headName)}}__name(remotesFor,"remotesFor");function assertSessionCanRunWorktree(root,worktreePath){if(process.env["QWEN_CODE_SERVE"]!=="1")return;const sessionDir=realpathNearestExisting(process.cwd());if(isWithinRoot(realpathNearestExisting(worktreePath),sessionDir))return;throw new Error(`${worktreePath} is outside this session's working directory (${sessionDir}): the daemon runs the fix agent's commands only there, so a watch here could never run its checks, commit or push. Prepare the PR from ${root}, where the worktree is inside the session's directory.`)}__name(assertSessionCanRunWorktree,"assertSessionCanRunWorktree");function reconcileHistory(prNumber,repository,local,localRoot){const union=__name((a=[],b=[])=>[...new Set([...a,...b])],"union");const copies=[];const consider=__name((h,path)=>{if(!h||!sameRepository(h,repository))return;let mtimeMs=0;try{mtimeMs=statSync(path).mtimeMs}catch{}copies.push({history:h,mtimeMs})},"consider");consider(local,historyPath(autofixPrPaths(localRoot,prNumber),repository));const exclude=realpathNearestExisting(localRoot);for(const root of vouchedScanRoots(cloneWorktreeRoots())){if(realpathNearestExisting(root)===exclude)continue;const path=historyPath(autofixPrPaths(root,prNumber),repository);let h=null;try{h=readHistory(path)}catch{continue}consider(h,path)}if(copies.length===0)return null;let merged={...copies[0].history};for(const{history}of copies.slice(1)){merged={...merged,handledCommentIds:union(merged.handledCommentIds,history.handledCommentIds),postedCommentIds:union(merged.postedCommentIds,history.postedCommentIds),handledChecks:union(merged.handledChecks,history.handledChecks),rerunChecks:union(merged.rerunChecks,history.rerunChecks)}}const newest=copies.reduce((a,b)=>b.mtimeMs>a.mtimeMs?b:a).history;const settledFloors=new Set(merged.rerunChecks??[]);return{...merged,handledConflictSha:newest.handledConflictSha??null,heldChecks:(newest.heldChecks??[]).filter(hold=>!settledFloors.has(hold.replace(/^\d+:/,""))),deferredRuns:newest.deferredRuns??[],pendingPosts:newest.pendingPosts??[]}}__name(reconcileHistory,"reconcileHistory");function runInPlacePrepare(args,owner,repoName,host){const prNumber=args.pr;const found=findWatchRoot(prNumber);if(found!==null){throw new Error(`PR #${prNumber} already has a watch in this clone (${found}); run \`qwen autofix-pr cleanup ${prNumber}\` first.`)}const checkout=git("rev-parse","--show-toplevel");const sessionDir=realpathNearestExisting(process.cwd());const checkoutReal=realpathNearestExisting(checkout);if(process.env["QWEN_CODE_SERVE"]==="1"){if(!isWithinRoot(checkoutReal,sessionDir)){throw new Error(`--in-place needs the session opened at the checkout root (${checkout}): the daemon runs the fix agent's commands only inside the session's working directory (${sessionDir}).`)}}else if(!isWithinRoot(sessionDir,checkoutReal)){throw new Error(`run --in-place from inside the checkout of the PR's head branch (${checkout}).`)}ensureAuthenticated();const pr=JSON.parse(gh("pr","view",String(prNumber),"-R",args.repo,"--json",PR_FIELDS));const repo=JSON.parse(gh("repo","view",args.repo,"--json","viewerPermission,defaultBranchRef"));const viewer=currentUser();const refusal=eligibilityError(pr,repo,viewer);if(refusal)throw new Error(refusal);const canPush=authorCanPush(args.repo,pr.author?.login??"",viewer);const{remote,pushTarget}=remotesFor(host,owner,repoName,pr.headRepositoryOwner.login,pr.headRepository.name);const head=gitOpt("-C",checkout,"symbolic-ref","-q","HEAD");if(head!==`refs/heads/${pr.headRefName}`){throw new Error(`--in-place needs the PR's head branch ${pr.headRefName} checked out in ${checkout} (it has ${head?`branch ${head.replace(/^refs\/heads\//,"")}`:"a detached HEAD"}); switch to it yourself first.`)}const remoteNames=(gitOpt("remote")??"").split("\n").filter(name=>name!=="");if(!remoteNames.includes(pushTarget)){throw new Error(`--in-place needs a named git remote whose fetch and push URLs both serve ${pr.headRepositoryOwner.login}/${pr.headRepository.name}; add one (git remote add <name> <url>) and set ${pr.headRefName}'s upstream to <name>/${pr.headRefName}.`)}const upstream=gitOpt("for-each-ref","--format=%(upstream:short)",`refs/heads/${pr.headRefName}`);if(upstream!==`${pushTarget}/${pr.headRefName}`){throw new Error(`the branch ${pr.headRefName} must track ${pushTarget}/${pr.headRefName} for --in-place (it tracks ${upstream||"nothing"}); set its upstream first.`)}const holds=checkoutHoldsWork(checkout);if(holds===null){throw new Error(`git cannot read ${checkout}; --in-place needs a readable, clean checkout.`)}if(holds){throw new Error(`${checkout} has uncommitted changes; commit or stash them before starting --in-place.`)}const paths=autofixPrPaths(checkout,prNumber);networkGit(["-C",checkout,"fetch","--quiet","--no-recurse-submodules",remote,`+refs/pull/${prNumber}/head:${paths.headRef}`]);const headSha=git("-C",checkout,"rev-parse",`${paths.headRef}^{commit}`);const localSha=git("-C",checkout,"rev-parse",`refs/heads/${pr.headRefName}`);if(localSha!==headSha&&!isAncestor(checkout,localSha,headSha)){throw new Error(`${pr.headRefName} has commits the PR does not have; reconcile it with the PR head ${headSha.slice(0,12)} first \u2014 an in-place watch never discards or rewrites your commits.`)}mkdirSync(dirname(paths.lockPath),{recursive:true});const state=withWatchLock(paths,prNumber,()=>{if(readState(paths.statePath)){throw new Error(`PR #${prNumber} already has a watch in this clone; run \`qwen autofix-pr cleanup ${prNumber}\` first.`)}let history=null;try{history=readHistory(historyPath(paths,{host,owner,repo:repoName}))}catch{}if(history&&!sameRepository(history,{host,owner,repo:repoName})){history=null}history=reconcileHistory(prNumber,{host,owner,repo:repoName},history,checkout);const next={version:1,sessionId:currentSessionId(),host,owner,repo:repoName,prNumber,remote,pushTarget,headRefName:pr.headRefName,baseRefName:pr.baseRefName,branch:pr.headRefName,worktreePath:checkout,inPlace:true,viewer,prAuthor:pr.author?.login??"",authorCanPush:canPush,lastKnownHeadSha:headSha,preparedAt:new Date().toISOString(),pushedShas:[],handledCommentIds:history?.handledCommentIds??[],postedCommentIds:history?.postedCommentIds??[],...history?{handledChecks:history.handledChecks,rerunChecks:history.rerunChecks,handledConflictSha:history.handledConflictSha??null,pendingPosts:history.pendingPosts??[],deferredRuns:history.deferredRuns??[],heldChecks:history.heldChecks??[]}:{}};writeAnchor({host,owner,repo:repoName},prNumber,repoRoot());writeState(paths.statePath,next);return next});report(state,{resumed:false,inPlace:true,url:pr.url,isDraft:pr.isDraft,isCrossRepository:pr.isCrossRepository,...localCopy(state)})}__name(runInPlacePrepare,"runInPlacePrepare");function runPrepare(args){if(!isOwnerRepo(args.repo)){throw new TypeError(`--repo must be <owner>/<repo>, got ${args.repo}`)}const[owner,repoName]=args.repo.split("/");const host=resolveGhHost(args.host)??"github.com";if(args.inPlace){runInPlacePrepare(args,owner,repoName,host);return}const root=findWatchRoot(args.pr)??watchRoot();const paths=autofixPrPaths(root,args.pr);const redirected=redirectedAncestor(dirname(paths.worktreePath),root);if(redirected!==null){throw new Error(`refusing to prepare ${paths.worktreePath}: ${redirected} is a symlink.`)}assertSessionCanRunWorktree(root,paths.worktreePath);const sameWatch=__name(state2=>{if(!sameRepository(state2,{host,owner,repo:repoName})){const watched=`${state2.host}/${state2.owner}/${state2.repo}`;throw new Error(`PR #${args.pr} here is a watch of ${watched}, not ${host}/${args.repo}. Run \`qwen autofix-pr cleanup ${args.pr}\` first.`)}},"sameWatch");const inPlaceMismatch=`PR #${args.pr} here is an in-place watch (the user's own checkout); run \`qwen autofix-pr cleanup ${args.pr}\` first, then prepare again (with --in-place to keep fixing in your checkout).`;let existing=readState(paths.statePath);if(existing?.inPlace){throw new Error(inPlaceMismatch)}let tookOver=false;let recreated=false;let wasEnded;const takesOver=__name(state2=>args.takeOver===true&&state2.sessionId!==currentSessionId(),"takesOver");if(existing){sameWatch(existing);assertNoFixInFlight(paths,args.pr);if(existsSync(paths.worktreePath)){if(!takesOver(existing))assertOwnedBySession(existing);ensureAuthenticated();const live=JSON.parse(gh("pr","view",String(args.pr),"-R",args.repo,"--json","author,headRepository,headRepositoryOwner,headRefOid"));if(!live.headRepository||!live.headRepositoryOwner){throw new Error(`PR #${args.pr}'s head repository no longer exists; nothing can be pushed to it.`)}const canPush2=authorCanPush(args.repo,live.author?.login??"",currentUser());const remotes=remotesFor(host,owner,repoName,live.headRepositoryOwner.login,live.headRepository.name);existing=withWatchLock(paths,args.pr,()=>{const current=requireState(paths.statePath,args.pr);if(takesOver(current))tookOver=true;else assertOwnedBySession(current);assertNoFixInFlight(paths,args.pr);if(tookOver)clearAbandonedFix(paths);wasEnded=current.ended;const{ended:_resumed,...rest}=current;const next={...rest,sessionId:currentSessionId(),authorCanPush:canPush2,...remotes};writeAnchor(current,current.prNumber,repoRoot());if(JSON.stringify(next)!==JSON.stringify(current)){writeState(paths.statePath,next)}return next});report({...existing,worktreePath:paths.worktreePath},{resumed:true,...localCopy({...existing,lastKnownHeadSha:live.headRefOid}),...tookOver?{tookOver}:{},...wasEnded?{wasEnded}:{}});return}if(!args.takeOver)assertOwnedBySession(existing)}ensureAuthenticated();const pr=JSON.parse(gh("pr","view",String(args.pr),"-R",args.repo,"--json",PR_FIELDS));const repo=JSON.parse(gh("repo","view",args.repo,"--json","viewerPermission,defaultBranchRef"));const viewer=currentUser();const refusal=eligibilityError(pr,repo,viewer);if(refusal)throw new Error(refusal);const headOwner=pr.headRepositoryOwner.login;const headName=pr.headRepository.name;const canPush=authorCanPush(args.repo,pr.author?.login??"",viewer);const{remote,pushTarget}=remotesFor(host,owner,repoName,headOwner,headName);mkdirSync(dirname(paths.lockPath),{recursive:true});const state=withWatchLock(paths,args.pr,()=>{existing=readState(paths.statePath);if(existing?.inPlace){throw new Error(inPlaceMismatch)}if(existing){sameWatch(existing);if(takesOver(existing))tookOver=true;else assertOwnedBySession(existing);assertNoFixInFlight(paths,args.pr);if(tookOver)clearAbandonedFix(paths);recreated=true;if(existing.ended)wasEnded=existing.ended}const leftover=`Run \`qwen autofix-pr cleanup ${args.pr}\` first.`;if(existsSync(paths.worktreePath)){throw new Error(`${paths.worktreePath} is left over from an earlier watch. ${leftover}`)}gitOpt("worktree","prune");if(refExists(`refs/heads/${paths.branch}`)){const ahead=existing?gitOpt("rev-list","--count",`refs/heads/${paths.branch}`,"--not",existing.lastKnownHeadSha):null;if(ahead!=="0"){throw new Error(`branch ${paths.branch} is left over from an earlier watch and may hold unpushed work. ${leftover}`)}git("branch","-D",paths.branch)}networkGit(["fetch","--quiet","--no-recurse-submodules",remote,`+refs/pull/${args.pr}/head:refs/heads/${paths.branch}`]);const headSha=git("rev-parse",`refs/heads/${paths.branch}`);mkdirSync(dirname(paths.worktreePath),{recursive:true});try{git("-c","submodule.recurse=false","worktree","add","--quiet",paths.worktreePath,paths.branch)}catch(err){gitOpt("worktree","remove","--force",paths.worktreePath);gitOpt("worktree","prune");gitOpt("branch","-D",paths.branch);throw err}let history=null;try{history=readHistory(historyPath(paths,{host,owner,repo:repoName}))}catch{}if(history&&!sameRepository(history,{host,owner,repo:repoName})){history=null}if(!existing){history=reconcileHistory(args.pr,{host,owner,repo:repoName},history,root)}const state2={version:1,sessionId:currentSessionId(),host,owner,repo:repoName,prNumber:args.pr,remote,pushTarget,headRefName:pr.headRefName,baseRefName:pr.baseRefName,branch:paths.branch,worktreePath:paths.worktreePath,viewer,prAuthor:pr.author?.login??"",authorCanPush:canPush,lastKnownHeadSha:headSha,preparedAt:new Date().toISOString(),pushedShas:existing?.pushedShas??[],handledCommentIds:existing?.handledCommentIds??history?.handledCommentIds??[],postedCommentIds:existing?.postedCommentIds??history?.postedCommentIds??[],...history&&!existing?{handledChecks:history.handledChecks,rerunChecks:history.rerunChecks,handledConflictSha:history.handledConflictSha??null,pendingPosts:history.pendingPosts??[],deferredRuns:history.deferredRuns??[],heldChecks:history.heldChecks??[]}:{},...existing?{handledChecks:existing.handledChecks,rerunChecks:existing.rerunChecks,handledConflictSha:existing.handledConflictSha,pushCount:existing.pushCount,summarizedSha:existing.summarizedSha,reportedNeedsHuman:existing.reportedNeedsHuman,pendingPosts:existing.pendingPosts,deferredRuns:existing.deferredRuns,heldChecks:existing.heldChecks,failingChecks:existing.failingChecks,watch:existing.watch,needsHuman:existing.needsHuman}:{}};writeAnchor({host,owner,repo:repoName},args.pr,repoRoot());const known=withKnownHead(state2,headSha);writeState(paths.statePath,known);return known});report(state,{resumed:false,...recreated?{recreated}:{},...wasEnded?{wasEnded}:{},url:pr.url,isDraft:pr.isDraft,isCrossRepository:pr.isCrossRepository,...localCopy(state),...tookOver?{tookOver}:{}})}__name(runPrepare,"runPrepare");var prepareCommand={command:"prepare <pr>",describe:"Check that a PR can be watched and pushed to, then create its worktree and state file (re-running resumes an existing watch)",builder:__name(yargs=>yargs.positional("pr",{type:"number",demandOption:true,describe:"PR number"}).option("repo",{type:"string",demandOption:true,describe:"The PR repository as <owner>/<repo>"}).option("host",{type:"string",describe:"GitHub host (omitted: inherit an exported GH_HOST, else github.com)"}).option("take-over",{type:"boolean",default:false,describe:"Move a watch of this PR that another session owns to this session"}).option("in-place",{type:"boolean",default:false,describe:"Fix in the user's own checkout of the PR head branch: attended, one round per start, nothing ever discarded"}),"builder"),handler:__name(argv=>{const host=argv.host;setGhHost(host);runPrepare({pr:Number(argv["pr"]),repo:String(argv["repo"]),host,takeOver:Boolean(argv["takeOver"]),inPlace:Boolean(argv["inPlace"])})},"handler")};init_esbuild_shims();import{lstatSync,mkdirSync as mkdirSync2,readFileSync,utimesSync,writeFileSync}from"node:fs";import{dirname as dirname2}from"node:path";var CHECK_CONTEXT_FIELDS=`nodes {
|
|
5
5
|
__typename
|
|
6
6
|
... on CheckRun {
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{batchCommand,listWorkflowCommand,prepareEndpoint,resolveEndpoint}from"./chunk-
|
|
3
|
+
import{batchCommand,listWorkflowCommand,prepareEndpoint,resolveEndpoint}from"./chunk-XJIHDVPX.js";import"./chunk-SZBGWRES.js";import"./chunk-XKSB7VTV.js";import"./chunk-DVC65H4X.js";import"./chunk-GT4TCQ3R.js";import"./chunk-EZPM4DLR.js";import"./chunk-UWCF7JIF.js";import"./chunk-UB37RBSK.js";import"./chunk-LMUSSYJH.js";import"./chunk-NO7VTKRL.js";import"./chunk-U7HZUZKP.js";import"./chunk-ZO4F6ZWR.js";import"./chunk-PKK2D2W4.js";import"./chunk-N3AQAZ7D.js";import"./chunk-E5T4R2PM.js";import"./chunk-DOLUT3XC.js";import"./chunk-PTHIQ7ZN.js";import"./chunk-4CE4GMDL.js";import"./chunk-EIPLDYEY.js";import"./chunk-IDXJIDME.js";import"./chunk-G2LTZU67.js";import"./chunk-QS2ZMQIS.js";import"./chunk-S7IKHQ6I.js";import"./chunk-PAD5GPDY.js";import"./chunk-MD3ZEOBX.js";import"./chunk-SSYS5YN5.js";import"./chunk-X5QSFJVS.js";import"./chunk-OMDTFGTX.js";import"./chunk-3TTHYXT3.js";import"./chunk-46VUDNCL.js";import"./chunk-MKH3EH7O.js";import"./chunk-VC3JJL7E.js";import"./chunk-VKWVIWLK.js";import"./chunk-HW6SU6MX.js";import"./chunk-ZHHFNZ5J.js";import"./chunk-AKWYMQKU.js";import"./chunk-MZUOREFD.js";import"./chunk-DSKA3P2C.js";import"./chunk-7XZVMIY5.js";import"./chunk-4HSISRRA.js";import"./chunk-ZZJXFLVM.js";import"./chunk-RKDS7A4H.js";import"./chunk-QF22ILPV.js";import"./chunk-IV3HAIUN.js";import"./chunk-XFMPZINJ.js";import"./chunk-DECUAM3U.js";import"./chunk-QX7W2HY7.js";import"./chunk-HN5UYLPU.js";import"./chunk-PGRN3GZY.js";import"./chunk-HTW7PYHK.js";import"./chunk-AMGUAA4G.js";import"./chunk-YFTVFH2A.js";import"./chunk-ZBHL2CXR.js";import"./chunk-NIOS3B3V.js";import"./chunk-7XQ5D34E.js";import"./chunk-R2EHHA2C.js";import"./chunk-YK7NDQKM.js";import"./chunk-ZLZF2ZDD.js";import"./chunk-OMSVOFTC.js";import"./chunk-PHIPLV2I.js";import"./chunk-ZOTKZI2P.js";import"./chunk-A6G5TAIF.js";import"./chunk-YVBHCSZD.js";import"./chunk-FIXDX63I.js";import"./chunk-T7CHK6C2.js";import"./chunk-PT7NZBDY.js";import"./chunk-TWP72VRH.js";import"./chunk-UYEWRLGD.js";import"./chunk-QVPT37XZ.js";import"./chunk-YVD4O5ZB.js";import"./chunk-T6W33SET.js";import"./chunk-WK2IBT6D.js";import"./chunk-QZV4PFQK.js";import"./chunk-ILECDNJX.js";import"./chunk-QXQGUM3Y.js";import"./chunk-UQ7IROJH.js";import"./chunk-SZCBUCNH.js";import"./chunk-BEKROCWN.js";import"./chunk-5SUFJTQQ.js";import"./chunk-BYU42MLK.js";import"./chunk-JWQXU3SR.js";import"./chunk-5LZ2DPLH.js";import"./chunk-XQJOZDV7.js";import"./chunk-CV2UAEZA.js";import"./chunk-FUBDS3AV.js";import"./chunk-HW6AWS7W.js";import"./chunk-KLC3OD2M.js";import"./chunk-Q5IZXKUJ.js";import"./chunk-G5PYYZMM.js";import"./chunk-BG67XABA.js";import"./chunk-OBOU4ZZM.js";import"./chunk-D7XCQWP2.js";import"./chunk-AE5OMKRY.js";import"./chunk-OBV7RNHV.js";import"./chunk-7CQMWEMY.js";import"./chunk-GOZYWU4B.js";import"./chunk-OUC3WICA.js";import"./chunk-JZK2WGXA.js";import"./chunk-MPHSE7M4.js";import"./chunk-S2ZKZXHX.js";import"./chunk-7UK4WJWS.js";import"./chunk-4GP3PH7Z.js";import"./chunk-4QQKOW5M.js";import"./chunk-OV3EBH6J.js";import"./chunk-EBMCWXGZ.js";import"./chunk-XZTE4YTN.js";import"./chunk-LSASUDF2.js";import"./chunk-2V5EKGDK.js";import"./chunk-MOKVM4PT.js";import"./chunk-YIW3H46P.js";import"./chunk-EOMRLUNZ.js";import"./chunk-4ZRCV3JY.js";import"./chunk-TL6MLBXR.js";import"./chunk-NMY3PYNO.js";import"./chunk-YGLM5XPP.js";import"./chunk-WGNF7FPC.js";import"./chunk-4NPYOXJO.js";import"./chunk-MWGB5RCF.js";import"./chunk-SCD5TUBG.js";import"./chunk-NTRFETZB.js";import"./chunk-TL3SF2GA.js";import"./chunk-LMJPU2JM.js";import"./chunk-VFB6Q74I.js";import"./chunk-4JNHUZ7M.js";import"./chunk-SW54YEPK.js";import"./chunk-ZCRL73DT.js";import"./chunk-A6LT3FIJ.js";import"./chunk-S6RXVOY6.js";import"./chunk-YZFNBUKG.js";import"./chunk-AGEDDL7Z.js";import"./chunk-2NJJHZ52.js";import"./chunk-BN4FIQ77.js";import"./chunk-X64RXJQQ.js";import"./chunk-HETUGUHE.js";import"./chunk-ET2Z7ZGF.js";import"./chunk-XFPYXD2P.js";import"./chunk-3YWXKSOI.js";import"./chunk-5CWTKFI4.js";import"./chunk-C4MVD5OI.js";import"./chunk-Z2W7S4O4.js";import"./chunk-476F6QIM.js";import"./chunk-4R67LXKL.js";import"./chunk-FQRF6B65.js";import"./chunk-ZWPSBU7K.js";import"./chunk-UQFTXKEB.js";import"./chunk-HDGTWJ24.js";import"./chunk-W5NWIGKO.js";import"./chunk-KVA6DHHF.js";import"./chunk-PWOQASXT.js";import"./chunk-K7JCVESI.js";import"./chunk-Y6HHV4LC.js";import"./chunk-RP57XAJ2.js";import"./chunk-Z6AR5XE5.js";import"./chunk-7DOOXUDG.js";import"./chunk-77V43YOE.js";import"./chunk-7U7CWMP7.js";import"./chunk-EFTJIDS3.js";import"./chunk-4DIWAQ5G.js";import"./chunk-Q6UAOTP3.js";import"./chunk-HQZTAA2U.js";import"./chunk-GOR7FFVE.js";import"./chunk-4ZBZL23U.js";import"./chunk-BMHYEQTI.js";import"./chunk-ZZZAYAJW.js";import"./chunk-XMANRGPK.js";import"./chunk-3XVPZY7X.js";import"./chunk-KQX4H2D3.js";import"./chunk-URNNJMIC.js";import"./chunk-GU22I6TY.js";import"./chunk-YEYW7PPR.js";import"./chunk-M4ECEHLX.js";import"./chunk-DBRQGEEI.js";import"./chunk-B3ZFUGTC.js";import"./chunk-IRINPFG7.js";import"./chunk-6GTPLW7K.js";import"./chunk-NGVRCUYD.js";import"./chunk-5DTFN37U.js";import"./chunk-2YUBAWQ6.js";import"./chunk-O5EKX7LG.js";import"./chunk-TM6ZCBR7.js";import"./chunk-SVAPAMMG.js";import"./chunk-3KUHQGOS.js";import"./chunk-I6S7NGX3.js";import"./chunk-SBZFGYYS.js";import"./chunk-JAUJI56S.js";import"./chunk-I4H7NUVP.js";import"./chunk-EPODBRBP.js";import"./chunk-OKN3Z5C5.js";import"./chunk-XYB7GC5U.js";import"./chunk-2UOMCYQG.js";import"./chunk-I7L2TX4M.js";import"./chunk-MK3OONRA.js";import"./chunk-COGTQ5KZ.js";import"./chunk-VKDAXTCZ.js";import"./chunk-KBWJGX7I.js";export{batchCommand,listWorkflowCommand,prepareEndpoint,resolveEndpoint};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{classifyTurnErrorKind,createAcpSessionBridge,createHttpAcpBridge,extractErrorCode,extractErrorMessage}from"./chunk-
|
|
3
|
+
import{classifyTurnErrorKind,createAcpSessionBridge,createHttpAcpBridge,extractErrorCode,extractErrorMessage}from"./chunk-236DHGNH.js";import"./chunk-BWQ5AIEA.js";import"./chunk-WDR5XP3Y.js";import"./chunk-IFPLGH5C.js";import"./chunk-WBDNGVHU.js";import"./chunk-BC4C6F32.js";import"./chunk-2QYDBHYZ.js";import"./chunk-LUDNUVSA.js";import"./chunk-VTZZXEWA.js";import"./chunk-L5UULTGF.js";import"./chunk-3KZHPZVZ.js";import"./chunk-CFTFKWPW.js";import"./chunk-NIEO2TBE.js";import"./chunk-WSOEJTOC.js";import"./chunk-G2LTZU67.js";import"./chunk-QS2ZMQIS.js";import"./chunk-S7IKHQ6I.js";import"./chunk-PAD5GPDY.js";import"./chunk-MD3ZEOBX.js";import"./chunk-SSYS5YN5.js";import"./chunk-X5QSFJVS.js";import"./chunk-OMDTFGTX.js";import"./chunk-3TTHYXT3.js";import"./chunk-46VUDNCL.js";import"./chunk-MKH3EH7O.js";import"./chunk-VC3JJL7E.js";import"./chunk-VKWVIWLK.js";import"./chunk-HW6SU6MX.js";import"./chunk-ZHHFNZ5J.js";import"./chunk-AKWYMQKU.js";import"./chunk-MZUOREFD.js";import"./chunk-DSKA3P2C.js";import"./chunk-7XZVMIY5.js";import"./chunk-4HSISRRA.js";import"./chunk-ZZJXFLVM.js";import"./chunk-RKDS7A4H.js";import"./chunk-QF22ILPV.js";import"./chunk-IV3HAIUN.js";import"./chunk-XFMPZINJ.js";import"./chunk-DECUAM3U.js";import"./chunk-QX7W2HY7.js";import"./chunk-HN5UYLPU.js";import"./chunk-PGRN3GZY.js";import"./chunk-HTW7PYHK.js";import"./chunk-AMGUAA4G.js";import"./chunk-YFTVFH2A.js";import"./chunk-ZBHL2CXR.js";import"./chunk-NIOS3B3V.js";import"./chunk-7XQ5D34E.js";import"./chunk-R2EHHA2C.js";import"./chunk-YK7NDQKM.js";import"./chunk-ZLZF2ZDD.js";import"./chunk-OMSVOFTC.js";import"./chunk-PHIPLV2I.js";import"./chunk-ZOTKZI2P.js";import"./chunk-A6G5TAIF.js";import"./chunk-YVBHCSZD.js";import"./chunk-FIXDX63I.js";import"./chunk-T7CHK6C2.js";import"./chunk-PT7NZBDY.js";import"./chunk-TWP72VRH.js";import"./chunk-UYEWRLGD.js";import"./chunk-QVPT37XZ.js";import"./chunk-YVD4O5ZB.js";import"./chunk-T6W33SET.js";import"./chunk-WK2IBT6D.js";import"./chunk-QZV4PFQK.js";import"./chunk-ILECDNJX.js";import"./chunk-QXQGUM3Y.js";import"./chunk-UQ7IROJH.js";import"./chunk-SZCBUCNH.js";import"./chunk-BEKROCWN.js";import"./chunk-5SUFJTQQ.js";import"./chunk-BYU42MLK.js";import"./chunk-JWQXU3SR.js";import"./chunk-5LZ2DPLH.js";import"./chunk-XQJOZDV7.js";import"./chunk-CV2UAEZA.js";import"./chunk-FUBDS3AV.js";import"./chunk-HW6AWS7W.js";import"./chunk-KLC3OD2M.js";import"./chunk-Q5IZXKUJ.js";import"./chunk-G5PYYZMM.js";import"./chunk-BG67XABA.js";import"./chunk-OBOU4ZZM.js";import"./chunk-D7XCQWP2.js";import"./chunk-AE5OMKRY.js";import"./chunk-OBV7RNHV.js";import"./chunk-7CQMWEMY.js";import"./chunk-GOZYWU4B.js";import"./chunk-OUC3WICA.js";import"./chunk-JZK2WGXA.js";import"./chunk-MPHSE7M4.js";import"./chunk-S2ZKZXHX.js";import"./chunk-7UK4WJWS.js";import"./chunk-4GP3PH7Z.js";import"./chunk-4QQKOW5M.js";import"./chunk-OV3EBH6J.js";import"./chunk-EBMCWXGZ.js";import"./chunk-XZTE4YTN.js";import"./chunk-LSASUDF2.js";import"./chunk-2V5EKGDK.js";import"./chunk-MOKVM4PT.js";import"./chunk-YIW3H46P.js";import"./chunk-EOMRLUNZ.js";import"./chunk-4ZRCV3JY.js";import"./chunk-TL6MLBXR.js";import"./chunk-NMY3PYNO.js";import"./chunk-YGLM5XPP.js";import"./chunk-WGNF7FPC.js";import"./chunk-4NPYOXJO.js";import"./chunk-MWGB5RCF.js";import"./chunk-SCD5TUBG.js";import"./chunk-NTRFETZB.js";import"./chunk-TL3SF2GA.js";import"./chunk-LMJPU2JM.js";import"./chunk-VFB6Q74I.js";import"./chunk-4JNHUZ7M.js";import"./chunk-SW54YEPK.js";import"./chunk-ZCRL73DT.js";import"./chunk-A6LT3FIJ.js";import"./chunk-S6RXVOY6.js";import"./chunk-YZFNBUKG.js";import"./chunk-AGEDDL7Z.js";import"./chunk-2NJJHZ52.js";import"./chunk-BN4FIQ77.js";import"./chunk-X64RXJQQ.js";import"./chunk-HETUGUHE.js";import"./chunk-ET2Z7ZGF.js";import"./chunk-XFPYXD2P.js";import"./chunk-3YWXKSOI.js";import"./chunk-5CWTKFI4.js";import"./chunk-C4MVD5OI.js";import"./chunk-Z2W7S4O4.js";import"./chunk-476F6QIM.js";import"./chunk-4R67LXKL.js";import"./chunk-FQRF6B65.js";import"./chunk-ZWPSBU7K.js";import"./chunk-UQFTXKEB.js";import"./chunk-HDGTWJ24.js";import"./chunk-W5NWIGKO.js";import"./chunk-KVA6DHHF.js";import"./chunk-PWOQASXT.js";import"./chunk-K7JCVESI.js";import"./chunk-Y6HHV4LC.js";import"./chunk-RP57XAJ2.js";import"./chunk-Z6AR5XE5.js";import"./chunk-7DOOXUDG.js";import"./chunk-77V43YOE.js";import"./chunk-7U7CWMP7.js";import"./chunk-EFTJIDS3.js";import"./chunk-4DIWAQ5G.js";import"./chunk-Q6UAOTP3.js";import"./chunk-HQZTAA2U.js";import"./chunk-GOR7FFVE.js";import"./chunk-4ZBZL23U.js";import"./chunk-BMHYEQTI.js";import"./chunk-ZZZAYAJW.js";import"./chunk-XMANRGPK.js";import"./chunk-3XVPZY7X.js";import"./chunk-KQX4H2D3.js";import"./chunk-URNNJMIC.js";import"./chunk-GU22I6TY.js";import"./chunk-YEYW7PPR.js";import"./chunk-DBRQGEEI.js";import"./chunk-B3ZFUGTC.js";import"./chunk-IRINPFG7.js";import"./chunk-6GTPLW7K.js";import"./chunk-NGVRCUYD.js";import"./chunk-5DTFN37U.js";import"./chunk-2YUBAWQ6.js";import"./chunk-O5EKX7LG.js";import"./chunk-TM6ZCBR7.js";import"./chunk-SVAPAMMG.js";import"./chunk-3KUHQGOS.js";import"./chunk-I6S7NGX3.js";import"./chunk-SBZFGYYS.js";import"./chunk-JAUJI56S.js";import"./chunk-I4H7NUVP.js";import"./chunk-EPODBRBP.js";import"./chunk-OKN3Z5C5.js";import"./chunk-XYB7GC5U.js";import"./chunk-2UOMCYQG.js";import"./chunk-I7L2TX4M.js";import"./chunk-MK3OONRA.js";import"./chunk-COGTQ5KZ.js";import"./chunk-VKDAXTCZ.js";import"./chunk-KBWJGX7I.js";export{classifyTurnErrorKind,createAcpSessionBridge,createHttpAcpBridge,extractErrorCode,extractErrorMessage};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{ChannelSettingsError,WorkspaceChannelSettingsStore,assertValidChannelSecretUpdates}from"./chunk-
|
|
3
|
+
import{ChannelSettingsError,WorkspaceChannelSettingsStore,assertValidChannelSecretUpdates}from"./chunk-6VQKGKMJ.js";import"./chunk-MMQY4FJL.js";import"./chunk-NY56CL2X.js";import"./chunk-TL6RUTMP.js";import"./chunk-W7V6J2VV.js";import"./chunk-QN7NYEE3.js";import"./chunk-WSOEJTOC.js";import"./chunk-EZPM4DLR.js";import"./chunk-UWCF7JIF.js";import"./chunk-UB37RBSK.js";import"./chunk-LMUSSYJH.js";import"./chunk-NO7VTKRL.js";import"./chunk-U7HZUZKP.js";import"./chunk-ZO4F6ZWR.js";import"./chunk-PKK2D2W4.js";import"./chunk-N3AQAZ7D.js";import"./chunk-E5T4R2PM.js";import"./chunk-DOLUT3XC.js";import"./chunk-PTHIQ7ZN.js";import"./chunk-4CE4GMDL.js";import"./chunk-EIPLDYEY.js";import"./chunk-IDXJIDME.js";import"./chunk-G2LTZU67.js";import"./chunk-QS2ZMQIS.js";import"./chunk-S7IKHQ6I.js";import"./chunk-PAD5GPDY.js";import"./chunk-MD3ZEOBX.js";import"./chunk-SSYS5YN5.js";import"./chunk-X5QSFJVS.js";import"./chunk-OMDTFGTX.js";import"./chunk-3TTHYXT3.js";import"./chunk-46VUDNCL.js";import"./chunk-MKH3EH7O.js";import"./chunk-VC3JJL7E.js";import"./chunk-VKWVIWLK.js";import"./chunk-HW6SU6MX.js";import"./chunk-ZHHFNZ5J.js";import"./chunk-AKWYMQKU.js";import"./chunk-MZUOREFD.js";import"./chunk-DSKA3P2C.js";import"./chunk-7XZVMIY5.js";import"./chunk-4HSISRRA.js";import"./chunk-ZZJXFLVM.js";import"./chunk-RKDS7A4H.js";import"./chunk-QF22ILPV.js";import"./chunk-IV3HAIUN.js";import"./chunk-XFMPZINJ.js";import"./chunk-DECUAM3U.js";import"./chunk-QX7W2HY7.js";import"./chunk-HN5UYLPU.js";import"./chunk-PGRN3GZY.js";import"./chunk-HTW7PYHK.js";import"./chunk-AMGUAA4G.js";import"./chunk-YFTVFH2A.js";import"./chunk-ZBHL2CXR.js";import"./chunk-NIOS3B3V.js";import"./chunk-7XQ5D34E.js";import"./chunk-R2EHHA2C.js";import"./chunk-YK7NDQKM.js";import"./chunk-ZLZF2ZDD.js";import"./chunk-OMSVOFTC.js";import"./chunk-PHIPLV2I.js";import"./chunk-ZOTKZI2P.js";import"./chunk-A6G5TAIF.js";import"./chunk-YVBHCSZD.js";import"./chunk-FIXDX63I.js";import"./chunk-T7CHK6C2.js";import"./chunk-PT7NZBDY.js";import"./chunk-TWP72VRH.js";import"./chunk-UYEWRLGD.js";import"./chunk-QVPT37XZ.js";import"./chunk-YVD4O5ZB.js";import"./chunk-T6W33SET.js";import"./chunk-WK2IBT6D.js";import"./chunk-QZV4PFQK.js";import"./chunk-ILECDNJX.js";import"./chunk-QXQGUM3Y.js";import"./chunk-UQ7IROJH.js";import"./chunk-SZCBUCNH.js";import"./chunk-BEKROCWN.js";import"./chunk-5SUFJTQQ.js";import"./chunk-BYU42MLK.js";import"./chunk-JWQXU3SR.js";import"./chunk-5LZ2DPLH.js";import"./chunk-XQJOZDV7.js";import"./chunk-CV2UAEZA.js";import"./chunk-FUBDS3AV.js";import"./chunk-HW6AWS7W.js";import"./chunk-KLC3OD2M.js";import"./chunk-Q5IZXKUJ.js";import"./chunk-G5PYYZMM.js";import"./chunk-BG67XABA.js";import"./chunk-OBOU4ZZM.js";import"./chunk-D7XCQWP2.js";import"./chunk-AE5OMKRY.js";import"./chunk-OBV7RNHV.js";import"./chunk-7CQMWEMY.js";import"./chunk-GOZYWU4B.js";import"./chunk-OUC3WICA.js";import"./chunk-JZK2WGXA.js";import"./chunk-MPHSE7M4.js";import"./chunk-S2ZKZXHX.js";import"./chunk-7UK4WJWS.js";import"./chunk-4GP3PH7Z.js";import"./chunk-4QQKOW5M.js";import"./chunk-OV3EBH6J.js";import"./chunk-EBMCWXGZ.js";import"./chunk-XZTE4YTN.js";import"./chunk-LSASUDF2.js";import"./chunk-2V5EKGDK.js";import"./chunk-MOKVM4PT.js";import"./chunk-YIW3H46P.js";import"./chunk-EOMRLUNZ.js";import"./chunk-4ZRCV3JY.js";import"./chunk-TL6MLBXR.js";import"./chunk-NMY3PYNO.js";import"./chunk-YGLM5XPP.js";import"./chunk-WGNF7FPC.js";import"./chunk-4NPYOXJO.js";import"./chunk-MWGB5RCF.js";import"./chunk-SCD5TUBG.js";import"./chunk-NTRFETZB.js";import"./chunk-TL3SF2GA.js";import"./chunk-LMJPU2JM.js";import"./chunk-VFB6Q74I.js";import"./chunk-4JNHUZ7M.js";import"./chunk-SW54YEPK.js";import"./chunk-ZCRL73DT.js";import"./chunk-A6LT3FIJ.js";import"./chunk-S6RXVOY6.js";import"./chunk-YZFNBUKG.js";import"./chunk-AGEDDL7Z.js";import"./chunk-2NJJHZ52.js";import"./chunk-BN4FIQ77.js";import"./chunk-X64RXJQQ.js";import"./chunk-HETUGUHE.js";import"./chunk-ET2Z7ZGF.js";import"./chunk-XFPYXD2P.js";import"./chunk-3YWXKSOI.js";import"./chunk-5CWTKFI4.js";import"./chunk-C4MVD5OI.js";import"./chunk-Z2W7S4O4.js";import"./chunk-476F6QIM.js";import"./chunk-4R67LXKL.js";import"./chunk-FQRF6B65.js";import"./chunk-ZWPSBU7K.js";import"./chunk-UQFTXKEB.js";import"./chunk-HDGTWJ24.js";import"./chunk-W5NWIGKO.js";import"./chunk-KVA6DHHF.js";import"./chunk-PWOQASXT.js";import"./chunk-K7JCVESI.js";import"./chunk-Y6HHV4LC.js";import"./chunk-RP57XAJ2.js";import"./chunk-Z6AR5XE5.js";import"./chunk-7DOOXUDG.js";import"./chunk-77V43YOE.js";import"./chunk-7U7CWMP7.js";import"./chunk-EFTJIDS3.js";import"./chunk-4DIWAQ5G.js";import"./chunk-Q6UAOTP3.js";import"./chunk-HQZTAA2U.js";import"./chunk-GOR7FFVE.js";import"./chunk-4ZBZL23U.js";import"./chunk-BMHYEQTI.js";import"./chunk-ZZZAYAJW.js";import"./chunk-XMANRGPK.js";import"./chunk-3XVPZY7X.js";import"./chunk-KQX4H2D3.js";import"./chunk-URNNJMIC.js";import"./chunk-GU22I6TY.js";import"./chunk-YEYW7PPR.js";import"./chunk-M4ECEHLX.js";import"./chunk-DBRQGEEI.js";import"./chunk-B3ZFUGTC.js";import"./chunk-IRINPFG7.js";import"./chunk-6GTPLW7K.js";import"./chunk-NGVRCUYD.js";import"./chunk-5DTFN37U.js";import"./chunk-2YUBAWQ6.js";import"./chunk-O5EKX7LG.js";import"./chunk-TM6ZCBR7.js";import"./chunk-SVAPAMMG.js";import"./chunk-3KUHQGOS.js";import"./chunk-I6S7NGX3.js";import"./chunk-SBZFGYYS.js";import"./chunk-JAUJI56S.js";import"./chunk-I4H7NUVP.js";import"./chunk-EPODBRBP.js";import"./chunk-OKN3Z5C5.js";import"./chunk-XYB7GC5U.js";import"./chunk-2UOMCYQG.js";import"./chunk-I7L2TX4M.js";import"./chunk-MK3OONRA.js";import"./chunk-COGTQ5KZ.js";import"./chunk-VKDAXTCZ.js";import"./chunk-KBWJGX7I.js";export{ChannelSettingsError,WorkspaceChannelSettingsStore,assertValidChannelSecretUpdates};
|
|
@@ -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-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}
|
|
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-7XQ5D34E.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.
|