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
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// Force strict mode and setup for ESM
|
|
2
|
+
"use strict";
|
|
3
|
+
import{require_semver}from"./chunk-YZUKMJW7.js";import{getNpmCliPath,getNpmNodePath}from"./chunk-26MNTKT2.js";import"./chunk-2HLVSWM6.js";import"./chunk-E5T4R2PM.js";import"./chunk-G2LTZU67.js";import"./chunk-QS2ZMQIS.js";import"./chunk-S7IKHQ6I.js";import"./chunk-IEWZIDC6.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{require_proper_lockfile}from"./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{createDebugLogger}from"./chunk-JAUJI56S.js";import"./chunk-I4H7NUVP.js";import{Storage}from"./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{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_proper_lockfile=__toESM(require_proper_lockfile(),1);var import_semver=__toESM(require_semver(),1);import{execFile,execFileSync,spawn}from"node:child_process";import{createHash}from"node:crypto";import*as fs from"node:fs";import*as fsPromises from"node:fs/promises";import*as path from"node:path";import{promisify}from"node:util";var PACKAGE_NAME="gerege-cli";var debugLogger=createDebugLogger("MANAGED_NPM_UPDATE");var execFileAsync=promisify(execFile);function assertVersion(version){if(import_semver.default.valid(version)!==version){throw new Error(`Invalid update version: ${version}`)}}__name(assertVersion,"assertVersion");function packageDir(prefix){return path.join(prefix,"node_modules",PACKAGE_NAME)}__name(packageDir,"packageDir");function resolveBootstrapPath(bootstrapPath){if(!bootstrapPath){throw new Error("Unable to identify the Qwen Code npm launcher")}return fs.realpathSync(bootstrapPath)}__name(resolveBootstrapPath,"resolveBootstrapPath");function launcherId(bootstrapPath){return createHash("sha256").update(bootstrapPath).digest("hex").slice(0,16)}__name(launcherId,"launcherId");function processDoesNotExist(pidText){const pid=Number(pidText);if(!Number.isSafeInteger(pid))return false;try{process.kill(pid,0);return false}catch(error){return error.code==="ESRCH"}}__name(processDoesNotExist,"processDoesNotExist");function readDirectoryEntries(directory){try{return fs.readdirSync(directory,{withFileTypes:true})}catch{return[]}}__name(readDirectoryEntries,"readDirectoryEntries");function cleanupOrphanedManagedNpmUpdateArtifacts(launcherRoot,versionsDir){for(const entry of readDirectoryEntries(versionsDir)){const match=/^\.(.+)-([1-9]\d*)-[A-Za-z0-9]{6}$/.exec(entry.name);if(!entry.isDirectory()||entry.isSymbolicLink()||!match||import_semver.default.valid(match[1])!==match[1]||!processDoesNotExist(match[2])){continue}try{fs.rmSync(path.join(versionsDir,entry.name),{recursive:true,force:true})}catch{continue}}for(const entry of readDirectoryEntries(launcherRoot)){const match=/^active\.json\.([1-9]\d*)$/.exec(entry.name);if(!entry.isFile()||entry.isSymbolicLink()||!match||!processDoesNotExist(match[1])){continue}try{fs.rmSync(path.join(launcherRoot,entry.name),{force:true})}catch{continue}}}__name(cleanupOrphanedManagedNpmUpdateArtifacts,"cleanupOrphanedManagedNpmUpdateArtifacts");function resolveNpmGlobalConfigPath(){const configured=process.env["NPM_CONFIG_GLOBALCONFIG"];if(configured)return path.resolve(configured);const nodePath=getNpmNodePath();const npmCliPath=getNpmCliPath(nodePath,process.platform);const runNpm=__name(args=>execFileSync(nodePath,[npmCliPath,...args],{encoding:"utf8",timeout:1e4,stdio:["ignore","pipe","pipe"]}).trim(),"runNpm");let output;try{output=runNpm(["config","get","globalconfig","--global"])}catch{output=runNpm(["exec","--offline","-c",`"${nodePath}" -p "process.env.npm_config_globalconfig || require('path').resolve(process.env.npm_config_global_prefix, 'etc', 'npmrc')"`]).split(/\r?\n/).at(-1)??""}if(!output||output==="null"||output==="undefined"){throw new Error("Unable to resolve the global npm configuration")}return output}__name(resolveNpmGlobalConfigPath,"resolveNpmGlobalConfigPath");function readBaseInstallation(bootstrapPath){const manifest=JSON.parse(fs.readFileSync(path.join(path.dirname(bootstrapPath),"package.json"),"utf8"));if(manifest.name!==PACKAGE_NAME||typeof manifest.version!=="string"){throw new Error("Unable to identify the base Qwen Code npm installation")}return{version:manifest.version,ctimeMs:fs.statSync(bootstrapPath).ctimeMs}}__name(readBaseInstallation,"readBaseInstallation");async function validateInstallation(prefix,version){const root=packageDir(prefix);const manifest=JSON.parse(await fsPromises.readFile(path.join(root,"package.json"),"utf8"));if(manifest.name!==PACKAGE_NAME||manifest.version!==version){throw new Error(`Installed package did not match ${PACKAGE_NAME}@${version}`)}await fsPromises.access(path.join(root,"cli.js"))}__name(validateInstallation,"validateInstallation");async function smokeTest(prefix){const env={...process.env};delete env["CLI_VERSION"];delete env["QWEN_CODE_RELAUNCH_ARGS"];await execFileAsync(getNpmNodePath(),[path.join(packageDir(prefix),"cli-entry.js"),"--help"],{encoding:"utf8",env,timeout:1e4})}__name(smokeTest,"smokeTest");async function restoreVendoredRipgrepExecBits(prefix){const ripgrepDir=path.join(packageDir(prefix),"vendor","ripgrep");let names;try{names=await fsPromises.readdir(ripgrepDir)}catch{return}for(const name of names){try{await fsPromises.chmod(path.join(ripgrepDir,name,"rg"),493)}catch{}}}__name(restoreVendoredRipgrepExecBits,"restoreVendoredRipgrepExecBits");async function readActiveVersion(activeFile,expected){try{const active=JSON.parse(await fsPromises.readFile(activeFile,"utf8"));return typeof active.version==="string"&&import_semver.default.valid(active.version)!==null&&active.bootstrap===expected.bootstrap&&active.baseVersion===expected.baseVersion&&active.bootstrapCtimeMs===expected.bootstrapCtimeMs?active.version:null}catch{return null}}__name(readActiveVersion,"readActiveVersion");function prepareManagedNpmUpdate(version,bootstrapPath=process.env["QWEN_CODE_CLI"],updateRoot=process.env["QWEN_CODE_MANAGED_NPM_ROOT"]??path.join(Storage.getGlobalQwenDir(),"updates","npm")){assertVersion(version);const resolvedBootstrapPath=resolveBootstrapPath(bootstrapPath);const base=readBaseInstallation(resolvedBootstrapPath);const npmGlobalConfigPath=resolveNpmGlobalConfigPath();const launcherRoot=path.join(updateRoot,launcherId(resolvedBootstrapPath));const versionsDir=path.join(launcherRoot,"versions");fs.mkdirSync(versionsDir,{recursive:true});cleanupOrphanedManagedNpmUpdateArtifacts(launcherRoot,versionsDir);const stagingDir=fs.mkdtempSync(path.join(versionsDir,`.${version}-${process.pid}-`));return{stagingDir,versionDir:path.join(versionsDir,version),launcherRoot,baseVersion:base.version,bootstrapCtimeMs:base.ctimeMs,installArgs:["install","--globalconfig",npmGlobalConfigPath,"--prefix",stagingDir,"--global=false","--no-save","--package-lock=false","--no-audit","--no-fund",`${PACKAGE_NAME}@${version}`]}}__name(prepareManagedNpmUpdate,"prepareManagedNpmUpdate");async function installManagedNpmUpdate(version,bootstrapPath=process.env["QWEN_CODE_CLI"],updateRoot=process.env["QWEN_CODE_MANAGED_NPM_ROOT"]??path.join(Storage.getGlobalQwenDir(),"updates","npm"),spawnFn=spawn){const update=await stageManagedNpmUpdate(version,bootstrapPath,updateRoot,spawnFn);try{await activateManagedNpmUpdate(update,version,bootstrapPath)}catch(error){await cleanupManagedNpmUpdate(update);throw error}}__name(installManagedNpmUpdate,"installManagedNpmUpdate");async function stageManagedNpmUpdate(version,bootstrapPath=process.env["QWEN_CODE_CLI"],updateRoot=process.env["QWEN_CODE_MANAGED_NPM_ROOT"]??path.join(Storage.getGlobalQwenDir(),"updates","npm"),spawnFn=spawn){const update=prepareManagedNpmUpdate(version,bootstrapPath,updateRoot);const env={...process.env};for(const key of["NPM_CONFIG_USERCONFIG","npm_config_userconfig"]){const configured=env[key];if(configured)env[key]=path.resolve(configured)}try{await new Promise((resolve2,reject)=>{const child=spawnFn(getNpmNodePath(),[getNpmCliPath(getNpmNodePath(),process.platform),...update.installArgs],{cwd:update.stagingDir,env,stdio:["ignore","ignore","inherit"],timeout:10*6e4,windowsHide:true});child.once("error",reject);child.once("close",code=>{if(code===0)resolve2();else reject(new Error(`npm install exited with code ${code}`))})});await validateInstallation(update.stagingDir,version);return update}catch(error){await cleanupManagedNpmUpdate(update);throw error}}__name(stageManagedNpmUpdate,"stageManagedNpmUpdate");async function activateManagedNpmUpdate(update,version,bootstrapPath=process.env["QWEN_CODE_CLI"]){assertVersion(version);const resolvedBootstrapPath=resolveBootstrapPath(bootstrapPath);if(path.join(path.dirname(update.launcherRoot),launcherId(resolvedBootstrapPath))!==update.launcherRoot){throw new Error("The npm update does not match the active launcher")}await validateInstallation(update.stagingDir,version);await smokeTest(update.stagingDir);await restoreVendoredRipgrepExecBits(update.stagingDir);const activeFile=path.join(update.launcherRoot,"active.json");const release=await import_proper_lockfile.default.lock(activeFile,{realpath:false,stale:3e4,retries:{retries:50,minTimeout:20,maxTimeout:100},onCompromised:__name(err=>{debugLogger.warn("managed npm update lock compromised:",err)},"onCompromised")});try{const base=readBaseInstallation(resolvedBootstrapPath);if(base.version!==update.baseVersion||base.ctimeMs!==update.bootstrapCtimeMs){throw new Error("The base Qwen Code npm installation changed during update")}const activeVersion=await readActiveVersion(activeFile,{bootstrap:resolvedBootstrapPath,baseVersion:base.version,bootstrapCtimeMs:base.ctimeMs});if(activeVersion&&import_semver.default.gt(activeVersion,version)){try{const activeDir=path.join(update.launcherRoot,"versions",activeVersion);await validateInstallation(activeDir,activeVersion);await restoreVendoredRipgrepExecBits(activeDir);await cleanupManagedNpmUpdate(update);return}catch{}}try{await fsPromises.rename(update.stagingDir,update.versionDir)}catch(error){if(!fs.existsSync(update.versionDir))throw error;await validateInstallation(update.versionDir,version);await restoreVendoredRipgrepExecBits(update.versionDir);await cleanupManagedNpmUpdate(update)}const temporaryActivePath=`${activeFile}.${process.pid}`;try{await fsPromises.writeFile(temporaryActivePath,JSON.stringify({version,bootstrap:resolvedBootstrapPath,baseVersion:base.version,bootstrapCtimeMs:base.ctimeMs}),{mode:384});await fsPromises.rename(temporaryActivePath,activeFile)}finally{await fsPromises.rm(temporaryActivePath,{force:true})}}finally{try{await release()}catch(error){debugLogger.warn("Failed to release managed npm update lock:",error)}}}__name(activateManagedNpmUpdate,"activateManagedNpmUpdate");async function cleanupManagedNpmUpdate(update){await fsPromises.rm(update.stagingDir,{recursive:true,force:true}).catch(()=>{})}__name(cleanupManagedNpmUpdate,"cleanupManagedNpmUpdate");export{activateManagedNpmUpdate,cleanupManagedNpmUpdate,installManagedNpmUpdate,prepareManagedNpmUpdate,stageManagedNpmUpdate};
|
|
4
|
+
/**
|
|
5
|
+
* @license
|
|
6
|
+
* Copyright 2026 Qwen Code
|
|
7
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
8
|
+
*/
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{CSI_FILES_RETIREMENT_CAPABILITY_DIGEST,CSI_FILE_FINALIZATION_FORMAT,CSI_FILE_HISTORY_PATH,HOSTED_GLOB_TOO_COMPLEX,LocalShellResultCapture,MANAGED_CSI_ACK_LIMIT_BYTES,MANAGED_CSI_ACK_PATH,MANAGED_CSI_ATTEST_PATH,MANAGED_CSI_DRAIN_PATH,MANAGED_CSI_FILE_PREFIX,MANAGED_CSI_FILE_PROTOCOL,MANAGED_CSI_FILE_ROUTES,MANAGED_CSI_PROTOCOL,MANAGED_HOOK_MAX_REQUEST_BYTES,MANAGED_HOOK_MAX_RUNNING,MANAGED_HOOK_ROUTE,MANAGED_MCP_MAX_CONNECTIONS,MANAGED_MCP_ROUTE,MANAGED_MCP_TOOL,MANAGED_RUNTIME_PROVIDER_ROUTE,MANAGED_WORKSPACE_CONTEXT_FILES,MANAGED_WORKSPACE_CONTEXT_FILE_CHARS,MAX_PROVIDER_INLINE_MEDIA_BASE64_BYTES,MAX_PROVIDER_MEDIA_RESULT_BYTES,ManagedAutomationGateTool,ManagedCsiAckRequestError,ManagedCsiDrainRequestError,ManagedRuntimeProviderProtocolError,RESIDENT_WORKSPACE_CAPABILITY_DIGEST,WORKSPACE_ACTIVATION_ROUTE,WORKSPACE_CAPABILITY_DIGEST,WORKSPACE_CONTEXT_CONFIG_REF,WorkspaceActivations,checkHostedGlobPattern,compileManagedExtensionPackage,createManagedCsiFileReady,fitManagedRuntimeProviderResult,linuxDeviceNumber,managedRuntimeProviderLimit,minimatch,parseManagedCsiAckJson,parseManagedCsiAckRequest,parseManagedCsiAckResponse,parseManagedCsiAcknowledgement,parseManagedCsiBoot,parseManagedCsiCaptureIdentity,parseManagedCsiDrainRequest,parseManagedCsiFileBoot,parseManagedCsiFileJson,parseManagedRuntimeProviderRequest,parseManagedRuntimeProviderResult,readCsiFileHistoryEnvelope,readCsiFileHistoryObservation,readCsiNativeRequest,readCsiPreparationEvidence,readCurrentCsiNative,readManagedCsiFileContext,readManagedCsiFileDrain,validateManagedCsiAttestationRequest,validateManagedCsiAttestationResponse,validateManagedCsiFileAttestationRequest,validateManagedCsiFileAttestationResponse,validateManagedCsiPodIdentity,wrapManagedCsiFileContext}from"./chunk-2LMSDH6P.js";import"./chunk-XXUK6YLA.js";import{MANAGED_CONTEXT_ROUTES,ManagedContextInstallations,checkManagedContextAttestation,createManagedContextAttestationResponse,createManagedContextReady,parseManagedContextBoot}from"./chunk-36TKFM4Z.js";import{MANAGED_TOOL_FILE_HISTORY_MAX_BYTES,captureManagedToolExecutionContext,historyPath,parseToolPublicationBinding}from"./chunk-H34KVVI4.js";import{computeManagedContextDigest,normalizeWorkspaceRelativePath}from"./chunk-YJ6APXNB.js";import"./chunk-6S5XOXJ2.js";import{MANAGED_SHELL_PUBLISHER_ROUTE,ManagedShellPublisherRegistry,publisherFields}from"./chunk-Z7WGIXI4.js";import{CLOSE_SWEEP_TIMEOUT_MS,GROUP_EXIT_EVIDENCE_TIMEOUT_MS,ManagedRuntimeLedger,managedRuntimeLedgerFromEnvironment,signalProcessGroup}from"./chunk-6QU44IVK.js";import{MANAGED_RUNTIME_TOOL_RESULT_BODY_LIMIT_BYTES,OWNED_MANAGED_RUNTIME_ROUTES,authorizeManagedRuntime,handleManagedRuntimeJsonError,managedRuntimeJsonBody,managedRuntimeNoStore,nameManagedRuntimeIncarnation,ownedManagedRuntimeRouteGate,registerManagedRuntimeAttestationRoute}from"./chunk-XLCTS6G3.js";import"./chunk-BC4C6F32.js";import"./chunk-2QYDBHYZ.js";import"./chunk-LUDNUVSA.js";import"./chunk-VTZZXEWA.js";import"./chunk-3SHHYK7S.js";import{require_express}from"./chunk-6SOKP7IN.js";import"./chunk-L5UULTGF.js";import"./chunk-CFTFKWPW.js";import"./chunk-NIEO2TBE.js";import"./chunk-ELUOCI74.js";import"./chunk-IS7CHVXD.js";import"./chunk-WSOEJTOC.js";import{scrubAndReportInheritedLoaderEnv}from"./chunk-N3AQAZ7D.js";import"./chunk-E5T4R2PM.js";import"./chunk-CK3OKTTL.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-3EZ5GCUT.js";import"./chunk-46VUDNCL.js";import"./chunk-MKH3EH7O.js";import"./chunk-E3KWSRJN.js";import"./chunk-FRVXSKL4.js";import"./chunk-HW6SU6MX.js";import{TodoWriteTool}from"./chunk-ZYDOCKNF.js";import{WebFetchTool}from"./chunk-FNURB45T.js";import{GlobTool}from"./chunk-M7MGE5IU.js";import"./chunk-ZHHFNZ5J.js";import{WriteFileTool}from"./chunk-W2CV36HT.js";import{EditTool}from"./chunk-O3TUZQP4.js";import"./chunk-WXK7Z45R.js";import"./chunk-UJP2MPBI.js";import"./chunk-AKWYMQKU.js";import"./chunk-MZUOREFD.js";import"./chunk-BVV7UXES.js";import"./chunk-7XZVMIY5.js";import"./chunk-BY46PCWY.js";import"./chunk-ZZJXFLVM.js";import"./chunk-RKDS7A4H.js";import"./chunk-PMBI46K4.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{Client,Config,Ct,DEFAULT_INHERITED_ENV_VARS,EventSource,FileHistoryService,HookCommandCgroup,HookCommandIsolationUnavailableError,HookRegistry,HookRunner,LocalManagedSessionResourceStore,MAX_ARCHIVE_ENTRIES,MAX_ARCHIVE_EXPANDED_BYTES,MAX_ARCHIVE_PATH_BYTES,ManagedSessionConflictError,ManagedToolProtocolError,SessionWriterLease,ShellTool,So,StdioClientTransport,StreamableHTTPClientTransport,UnauthorizedError,auth,createFetchWithInit,deriveConfig,deserializeSnapshots,detectLineEnding,encodeTextFileContentAsync,extractWWWAuthenticateParams,firePostToolUseFailureHook,firePostToolUseHook,firePreToolUseHook,generateToolUseId,interpolateUrl,isModifiableDeclarativeTool,isOperationGrantSuccessor,isSinglePathSegment,managedSessionResourceRoot,managedToolDigest,normalizeHeaders,parseManagedExtensionApplyCommand,parseManagedExtensionPin,parseManagedExtensionPins,parseManagedToolContentModification,parseManagedToolMediaContext,parseOperationGrant,resolveCommandHookTimeoutMs,serializeManagedToolConfirmation,serializeSnapshot}from"./chunk-T3CQ72HC.js";import"./chunk-R2EHHA2C.js";import{CallToolResultSchema,GetPromptResultSchema,JSONRPCMessageSchema,ListPromptsResultSchema,ListResourcesResultSchema,ListToolsResultSchema,ReadBuffer,ReadResourceResultSchema,serializeMessage}from"./chunk-YK7NDQKM.js";import"./chunk-ZLZF2ZDD.js";import{MANAGED_TOOL_RESULT_KINDS,MANAGED_TOOL_RESULT_LIMITS,MANAGED_TOOL_RESULT_PROTOCOL,MANAGED_TOOL_RESULT_ROUTES,ManagedSessionRecordError,assertManagedSessionDigest,assertManagedSessionDurableRef,assertManagedSessionKey,assertManagedSessionSequence,assertManagedSessionStableId,isToolResultPageAt,parseToolResultManifestBytes,parseToolResultPageBytes,parseToolResultPrefixRequest,parseToolResultPublishRequest,parseToolResultSealRequest}from"./chunk-OMSVOFTC.js";import"./chunk-PHIPLV2I.js";import"./chunk-ZOTKZI2P.js";import"./chunk-A6G5TAIF.js";import"./chunk-YVBHCSZD.js";import"./chunk-FIXDX63I.js";import{isShellResultDisplay}from"./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{openNoFollow}from"./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{getShellContextEnvVars}from"./chunk-NMY3PYNO.js";import"./chunk-YGLM5XPP.js";import"./chunk-WGNF7FPC.js";import"./chunk-4NPYOXJO.js";import{promptIdContext}from"./chunk-MWGB5RCF.js";import{getShellConfiguration}from"./chunk-SCD5TUBG.js";import"./chunk-NTRFETZB.js";import"./chunk-TL3SF2GA.js";import{sanitizeChildEnv}from"./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{captureHookExecutionOwner,runWithHookExecutionOwner}from"./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{createAbortController}from"./chunk-476F6QIM.js";import"./chunk-4R67LXKL.js";import"./chunk-FQRF6B65.js";import"./chunk-LG4NL2M7.js";import{ReadFileTool}from"./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{FileReadOpenError,decodeBufferWithEncodingInfoAsync,digestFileReadSource,readFileHandleBytes,readTextContentRangeFromHandle}from"./chunk-Y6HHV4LC.js";import"./chunk-RP57XAJ2.js";import"./chunk-Z6AR5XE5.js";import"./chunk-7DOOXUDG.js";import"./chunk-77V43YOE.js";import"./chunk-7U7CWMP7.js";import{runWithInvocationContext}from"./chunk-EFTJIDS3.js";import"./chunk-4DIWAQ5G.js";import"./chunk-Q6UAOTP3.js";import"./chunk-H5EXNXGW.js";import"./chunk-GOR7FFVE.js";import"./chunk-4ZBZL23U.js";import{atomicWriteJSON}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"./chunk-M4ECEHLX.js";import"./chunk-DBRQGEEI.js";import"./chunk-B3ZFUGTC.js";import"./chunk-IRINPFG7.js";import{HookEventName,HooksConfigSource,getHookKey}from"./chunk-6GTPLW7K.js";import"./chunk-NGVRCUYD.js";import"./chunk-5DTFN37U.js";import{isPathWithinRoot}from"./chunk-2YUBAWQ6.js";import{ToolConfirmationOutcome}from"./chunk-O5EKX7LG.js";import"./chunk-TM6ZCBR7.js";import"./chunk-SVAPAMMG.js";import"./chunk-3KUHQGOS.js";import"./chunk-I6S7NGX3.js";import{ToolNames}from"./chunk-SBZFGYYS.js";import{createDebugLogger,registerSessionProjectDir,sessionIdContext,unregisterSessionModel,unregisterSessionProjectDir}from"./chunk-JAUJI56S.js";import"./chunk-I4H7NUVP.js";import{Storage}from"./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{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_express3=__toESM(require_express(),1);import{createServer as createServer2}from"node:http";import{createReadStream as createReadStream3}from"node:fs";import{mkdtemp as mkdtemp2}from"node:fs/promises";import path15 from"node:path";init_esbuild_shims();import{createHash as createHash10}from"node:crypto";import{isDeepStrictEqual as isDeepStrictEqual4}from"node:util";init_esbuild_shims();import{constants,promises as fs}from"node:fs";import path from"node:path";async function executable(command,cwd,environment){const candidates=command.includes("/")?[path.resolve(cwd,command)]:(environment["PATH"]??"/usr/bin:/bin").split(path.delimiter).map(directory=>path.resolve(cwd,directory,command));for(const candidate of candidates){try{if(!(await fs.stat(candidate)).isFile())continue;await fs.access(candidate,constants.X_OK);return candidate}catch{}}throw new Error(`Extension executable is unavailable: ${command}`)}__name(executable,"executable");async function preflightManagedExtensionPackage(contributions,root,cwd,environment){const env={...environment,QWEN_EXTENSION_ROOT:root,CLAUDE_PLUGIN_ROOT:root,extensionPath:root};const expand=__name((value,executionEnvironment=env)=>value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)/gu,(original,braced,plain)=>executionEnvironment[braced??plain]??original),"expand");let dynamicCommands=0;const check=__name(async(command,args,executionEnvironment=env)=>{const resolved=await executable(expand(command,executionEnvironment),cwd,executionEnvironment);const handle=await fs.open(resolved,"r");let head;try{const buffer=Buffer.alloc(512);const read=await handle.read(buffer,0,512,0);head=buffer.subarray(0,read.bytesRead).toString()}finally{await handle.close()}if(head.startsWith("#!")){const shebang=head.split("\n")[0].slice(2).trim().split(/\s+/u);await executable(shebang[0],cwd,executionEnvironment);if(path.basename(shebang[0])==="env"&&shebang[1]&&!shebang[1].startsWith("-"))await executable(shebang[1],cwd,executionEnvironment)}if(path.basename(resolved)==="env"&&args.length){if(args[0].startsWith("-")||args[0].includes("=")){dynamicCommands++;return}await check(args[0],args.slice(1),executionEnvironment);return}if(args.includes("-e")||args.includes("--eval")||args.includes("-c")){dynamicCommands++;return}for(const argument of args.filter(value=>!value.startsWith("-")&&/\.(?:[cm]?js|py|rb|sh)$/u.test(value))){const script=path.resolve(cwd,expand(argument,executionEnvironment));if(!(await fs.stat(script)).isFile())throw new Error("Extension script is unavailable.");await fs.access(script,constants.R_OK)}},"check");const shell=__name(async(command,executionEnvironment=env)=>{if(/[|;&><`\n]|\$\(/u.test(command)){dynamicCommands++;return}const tokens=[...command.matchAll(/"([^"]*)"|'([^']*)'|([^\s]+)/gu)].map(match=>match[1]??match[2]??match[3]);if(!tokens.length)return;if(tokens.some(token=>token.includes("$")&&expand(token,executionEnvironment)===token)){dynamicCommands++;return}if(/^[A-Za-z_][A-Za-z0-9_]*=/u.test(tokens[0])){dynamicCommands++;return}if([":","[","alias","bg","break","cd","continue","exit","export","false","fg","getopts","hash","jobs","pwd","read","readonly","return","set","shift","test","times","trap","true","type","ulimit","umask","unalias","unset","wait"].includes(tokens[0]))return;if(tokens[0]==="eval"){dynamicCommands++;return}if(["exec","command"].includes(tokens[0]))tokens.shift();if(tokens.length)await check(tokens[0],tokens.slice(1),executionEnvironment)},"shell");for(const value of Object.values(contributions.mcpServers)){const recipe=value;if(recipe.command)await check(recipe.command,recipe.args??[],{...env,...recipe.env})}for(const groups of Object.values(contributions.hooks)){for(const group of groups){for(const hook of group.hooks??[])if(hook.type==="command"&&hook.command)await shell(hook.command,{...env,...hook.env})}}for(const command of contributions.commands)for(const match of command.prompt.matchAll(/!\{([^}]*)\}/gu))await shell(match[1]);return{dynamicCommands}}__name(preflightManagedExtensionPackage,"preflightManagedExtensionPackage");init_esbuild_shims();function managedExtensionEnvironment(inherited,directory,extension={}){const environment={};for(const key of["PATH","LANG","LC_ALL","LC_CTYPE","TZ","TMPDIR","TMP","TEMP"]){const value=inherited[key];if(value!==void 0)environment[key]=value}return{...environment,HOME:directory,USERPROFILE:directory,...extension}}__name(managedExtensionEnvironment,"managedExtensionEnvironment");init_esbuild_shims();import{createHash as createHash2}from"node:crypto";import{promises as fs3}from"node:fs";import path3 from"node:path";init_esbuild_shims();import{createHash,randomUUID}from"node:crypto";import{createReadStream,createWriteStream,promises as fs2}from"node:fs";import path2 from"node:path";import{Transform}from"node:stream";import{pipeline}from"node:stream/promises";var MANAGED_EXTENSION_ARCHIVE_MAX_BYTES=100*1024*1024;var DIGEST=/^[0-9a-f]{64}$/u;var ManagedExtensionCache=class{constructor(directory){this.directory=directory;if(!path2.isAbsolute(directory))throw new Error("Invalid package cache.")}static{__name(this,"ManagedExtensionCache")}async upload(digest3,source){this.assertDigest(digest3);await fs2.mkdir(this.directory,{recursive:true,mode:448});const temporary=path2.join(this.directory,`.upload-${randomUUID()}`);const hash=createHash("sha256");let bytes=0;const limit=new Transform({transform(chunk,_encoding,callback){bytes+=chunk.byteLength;if(bytes>MANAGED_EXTENSION_ARCHIVE_MAX_BYTES){callback(new Error("Package archive exceeds its size limit."));return}hash.update(chunk);callback(null,chunk)}});try{await pipeline(source,limit,createWriteStream(temporary,{flags:"wx",mode:384}));if(hash.digest("hex")!==digest3)throw new Error("Package archive digest mismatch.");await this.validateArchive(temporary);await fs2.rename(temporary,this.archivePath(digest3))}finally{await fs2.rm(temporary,{force:true})}}materialize(digest3){this.assertDigest(digest3);return this.extract(digest3)}async extract(digest3){const archive=this.archivePath(digest3);const hash=createHash("sha256");for await(const chunk of createReadStream(archive))hash.update(chunk);if(hash.digest("hex")!==digest3)throw new Error("Cached package archive digest mismatch.");await this.validateArchive(archive);const destination=path2.join(this.directory,`${digest3}-${randomUUID()}`);await fs2.mkdir(destination,{mode:448});try{await So({file:archive,cwd:destination,strict:true,noChmod:true});await fs2.writeFile(`${destination}.integrity`,await this.treeDigest(destination),{mode:384,flag:"wx"});return destination}catch(error){await fs2.rm(destination,{recursive:true,force:true});throw error}}async restoreMaterialized(digest3,directory){this.assertDigest(digest3);if(path2.dirname(directory)!==this.directory||!new RegExp(`^${digest3}-[0-9a-f-]{36}$`,"u").test(path2.basename(directory))||!(await fs2.lstat(this.directory)).isDirectory())throw new Error("Extension cache scope conflicts.");try{await this.verifyMaterialized(digest3,directory);return}catch{}const fresh=await this.materialize(digest3);const quarantine=path2.join(this.directory,`.quarantine-${randomUUID()}`);const moveIfPresent=__name(async(source,target)=>{try{await fs2.rename(source,target)}catch(error){if(error.code!=="ENOENT")throw error}},"moveIfPresent");try{await moveIfPresent(directory,quarantine);await moveIfPresent(`${directory}.integrity`,`${quarantine}.integrity`);await fs2.rename(fresh,directory);await fs2.rename(`${fresh}.integrity`,`${directory}.integrity`);await this.verifyMaterialized(digest3,directory);await fs2.rm(quarantine,{recursive:true,force:true});await fs2.rm(`${quarantine}.integrity`,{force:true})}finally{await fs2.rm(fresh,{recursive:true,force:true});await fs2.rm(`${fresh}.integrity`,{force:true})}}async verifyMaterialized(digest3,directory){this.assertDigest(digest3);if(path2.dirname(directory)!==this.directory||!path2.basename(directory).startsWith(`${digest3}-`))throw new Error("Extension cache scope conflicts.");if(!(await fs2.lstat(directory)).isDirectory())throw new Error("Extension cache root is unsafe.");const expected=await fs2.readFile(`${directory}.integrity`,"utf8");if(await this.treeDigest(directory)!==expected)throw new Error("Extension package assets drifted.")}async treeDigest(directory){const hash=createHash("sha256");const visit=__name(async relative=>{const entries=await fs2.readdir(path2.join(directory,relative),{withFileTypes:true});for(const entry of entries.sort((a,b)=>a.name.localeCompare(b.name,"en"))){const child=path2.posix.join(relative,entry.name);if(!entry.isDirectory()&&!entry.isFile())throw new Error("Extension assets contain an unsafe entry.");hash.update(JSON.stringify([child,entry.isDirectory()?"directory":"file"]));if(entry.isDirectory())await visit(child);else{const content=createHash("sha256");for await(const chunk of createReadStream(path2.join(directory,child)))content.update(chunk);hash.update(content.digest())}}},"visit");await visit("");return hash.digest("hex")}async validateArchive(file){let count=0;let bytes=0;let pathBytes=0;let invalid3=false;const seen=new Set;const source=createReadStream(file);const parser=Ct({strict:true,onReadEntry(entry){const normalized=path2.posix.normalize(entry.path).replace(/\/$/u,"");count++;bytes+=entry.size;pathBytes+=Buffer.byteLength(entry.path);if(!["File","Directory","OldFile","ContiguousFile"].includes(entry.type)||entry.path.includes("\\")||entry.path.includes("\0")||path2.posix.isAbsolute(entry.path)||/^[a-zA-Z]:/u.test(entry.path)||normalized===".."||normalized.startsWith("../")||seen.has(normalized)||count>MAX_ARCHIVE_ENTRIES||bytes>MAX_ARCHIVE_EXPANDED_BYTES||pathBytes>MAX_ARCHIVE_PATH_BYTES){invalid3=true;source.destroy(new Error("Unsafe package archive."))}seen.add(normalized)}});await pipeline(source,parser);if(invalid3)throw new Error("Unsafe package archive.")}archivePath(digest3){return path2.join(this.directory,`${digest3}.tar.gz`)}assertDigest(digest3){if(!DIGEST.test(digest3))throw new Error("Invalid package digest.")}};var MANAGED_EXTENSION_RUNTIME_ROUTE=Object.freeze({key:"extensions",method:"POST",path:"/internal/managed-runtime/v3/extensions"});var MANAGED_EXTENSION_RETIRE_ROUTE=Object.freeze({key:"extension-retire",method:"POST",path:"/internal/managed-runtime/v3/extensions/retire"});var MANAGED_EXTENSION_UPLOAD_ROUTE=Object.freeze({key:"extension-package-upload",method:"PUT",path:"/internal/managed-runtime/v3/extensions/packages/:digest"});var ManagedExtensionRuntime=class{constructor(dependencies){this.dependencies=dependencies;if(!path3.isAbsolute(dependencies.directory))throw new Error("Invalid extension Runtime directory.");this.cache=new ManagedExtensionCache(path3.join(dependencies.directory,"packages"))}static{__name(this,"ManagedExtensionRuntime")}cache;prepared=new Map;active=new Map;busy=new Set;environments=new Map;sessionOwners=new Map;ownerSessions=new Map;async status(sessionId){await this.requireSession(sessionId);let pendingOperationId;try{pendingOperationId=parseManagedExtensionApplyCommand(JSON.parse(await fs3.readFile(this.pendingPath(sessionId),"utf8"))).operationId}catch(error){if(error.code!=="ENOENT")throw error}const pending=pendingOperationId?{pendingOperationId}:{};const installed=this.active.get(sessionId);if(installed)return{...this.state(installed.command),...pending};try{const stored=JSON.parse(await fs3.readFile(this.statePath(sessionId),"utf8"));const command=parseManagedExtensionApplyCommand(stored);const stopped=await fs3.stat(`${this.operationPath(sessionId,command.operationId)}.stopped`).then(()=>true,error=>{if(error.code==="ENOENT")return false;throw error});return{...this.state(command),...stopped?{state:"failed"}:{},...pending}}catch(error){if(error.code==="ENOENT")return{state:pendingOperationId?"outcome_unknown":"active",executionMode:this.dependencies.executionMode,revision:0,extensions:[],operationId:null,...pending};throw error}}async operationStatus(sessionId,operationId){const current=await this.status(sessionId);try{const proof=JSON.parse(await fs3.readFile(`${this.operationPath(sessionId,operationId)}.stopped`,"utf8"));if(proof["operationId"]!==operationId||proof["executionMode"]!==this.dependencies.executionMode||proof["state"]!=="stopped")throw new Error("Original stop proof conflicts.");return proof}catch(error){if(error.code!=="ENOENT")throw error}if(current.operationId===operationId&&!current.pendingOperationId)return current;const prepared=this.prepared.get(this.preparedKey(sessionId,operationId))??await this.loadPrepared(sessionId,operationId);if(prepared&&!current.pendingOperationId)return this.preparedView(prepared);return{...current,state:"outcome_unknown",operationId}}async prepare(sessionId,value,base={baseMcpServers:[],baseHookCatalog:null}){const command=parseManagedExtensionApplyCommand(value);return this.lock(sessionId,async()=>{const status=await this.status(sessionId);const key=this.preparedKey(sessionId,command.operationId);const existing=this.prepared.get(key)??await this.loadPrepared(sessionId,command.operationId);const publicBase={baseMcpServers:base.baseMcpServers,baseHookCatalog:base.baseHookCatalog};if(existing){if(JSON.stringify(existing.command)!==JSON.stringify(command)||JSON.stringify(existing.base)!==JSON.stringify(publicBase))throw new Error("Extension operation identity conflicts.");for(const pkg of existing.packages){await this.cache.restoreMaterialized(pkg.pin.packageDigest,pkg.assetRoot);const contributions=await this.dependencies.compile(pkg.assetRoot,pkg.pin,base.settings?.[pkg.pin.extensionId]??{},sessionId,base.packageManifests?.[pkg.pin.extensionId]);validateExtensionToolProfile(contributions,base.toolProfile);if(JSON.stringify(contributions)!==JSON.stringify(pkg.contributions))throw new Error("Prepared extension package drifted.")}const catalogs2=this.dependencies.stage?await this.dependencies.stage(sessionId,command,existing.packages,{...publicBase,preparedMcpServers:existing.mcpServers}):{mcpServers:[],hookCatalog:null};if(JSON.stringify(catalogs2.mcpServers)!==JSON.stringify(existing.mcpServers)||JSON.stringify(catalogs2.hookCatalog)!==JSON.stringify(existing.hookCatalog))throw new Error("Prepared extension catalogs drifted.");this.environments.set(key,base.settings??{});this.prepared.set(key,existing);return this.preparedView(existing)}if(status.pendingOperationId)throw new Error("Original extension activation outcome is unknown.");if(status.revision!==command.expectedRevision)throw new Error("Extension configuration revision conflicts.");if(!this.dependencies.idle(sessionId))throw new Error("Extension configuration requires an idle Session.");const packages=[];try{for(const pin2 of command.extensions){const unchanged=this.active.get(sessionId)?.packages.find(entry=>JSON.stringify(entry.pin)===JSON.stringify(pin2));const assetRoot=unchanged?.assetRoot??await this.cache.materialize(pin2.packageDigest);await this.cache.restoreMaterialized(pin2.packageDigest,assetRoot);packages.push({pin:pin2,assetRoot,contributions:{skills:[],commands:[],agents:[],context:[],mcpServers:{},hooks:{},settings:[]}});const contributions=await this.dependencies.compile(assetRoot,pin2,base.settings?.[pin2.extensionId]??{},sessionId,base.packageManifests?.[pin2.extensionId]);validateExtensionToolProfile(contributions,base.toolProfile);packages[packages.length-1]={pin:pin2,assetRoot,contributions}}}catch(error){await Promise.all(packages.map(entry=>this.active.get(sessionId)?.packages.some(active=>active.assetRoot===entry.assetRoot)?Promise.resolve():fs3.rm(entry.assetRoot,{recursive:true,force:true})));throw error}const catalogs=this.dependencies.stage?await this.dependencies.stage(sessionId,command,packages,base):{mcpServers:[],hookCatalog:null};if(!this.dependencies.stage&&packages.some(entry=>Object.keys(entry.contributions.mcpServers).length||Object.keys(entry.contributions.hooks).length))throw new Error("Extension process components are unsupported.");const prepared={ownerJournalId:this.dependencies.ownerJournalId??"in-memory",command,packages,base:publicBase,mcpServers:catalogs.mcpServers,hookCatalog:catalogs.hookCatalog};const view2=this.preparedView(prepared);await fs3.mkdir(path3.dirname(this.operationPath(sessionId,command.operationId)),{recursive:true,mode:448});await atomicWriteJSON(this.operationPath(sessionId,command.operationId),prepared,{mode:384});this.environments.set(key,base.settings??{});this.prepared.set(key,prepared);return view2})}async reconcile(sessionId,operationId,expectedRevision,revision){return this.lock(sessionId,async()=>{const prepared=await this.loadPrepared(sessionId,operationId);if(!prepared)throw new Error("Original extension owner journal is unavailable.");try{const proof2=JSON.parse(await fs3.readFile(`${this.operationPath(sessionId,operationId)}.stopped`,"utf8"));if(proof2["operationId"]!==operationId||proof2["revision"]!==revision||expectedRevision+1!==revision||proof2["executionMode"]!==this.dependencies.executionMode||proof2["state"]!=="stopped")throw new Error("Original stop proof conflicts.");return proof2}catch(error){if(error.code!=="ENOENT")throw error}const command=prepared.command;const current=await this.status(sessionId);if(command.operationId!==operationId||command.expectedRevision!==expectedRevision||revision!==expectedRevision+1||current.pendingOperationId!==void 0&¤t.pendingOperationId!==operationId||current.revision!==expectedRevision&&(current.operationId!==operationId||current.revision!==revision||JSON.stringify(current.extensions)!==JSON.stringify(command.extensions)))throw new Error("Original extension operation conflicts.");const receipts=this.dependencies.reconcile?await this.dependencies.reconcile(sessionId):void 0;if(!receipts||receipts.length===0||receipts.some(entry=>entry.state!=="stopped"))return{operationId,revision,state:"outcome_unknown",executionMode:this.dependencies.executionMode};const proof={operationId,revision,state:"stopped",executionMode:this.dependencies.executionMode,receipts};await atomicWriteJSON(`${this.operationPath(sessionId,operationId)}.stopped`,proof,{mode:384});await atomicWriteJSON(this.statePath(sessionId),command,{mode:384});this.active.delete(sessionId);await fs3.rm(this.pendingPath(sessionId),{force:true});return proof})}async activate(sessionId,operationId){return this.lock(sessionId,async()=>{const status=await this.status(sessionId);if(status.pendingOperationId)throw new Error("Original extension activation outcome is unknown.");if(status.operationId===operationId){if(!this.active.has(sessionId)){const restored=this.prepared.get(this.preparedKey(sessionId,operationId));if(!restored)throw new Error("Active extension configuration requires exact reprepare.");await this.dependencies.install(sessionId,restored.packages,restored.command);this.active.set(sessionId,restored)}return status}const prepared=this.prepared.get(this.preparedKey(sessionId,operationId));if(!prepared||status.revision!==prepared.command.expectedRevision)throw new Error("Extension configuration was not prepared.");if(!this.dependencies.idle(sessionId))throw new Error("Extension configuration requires an idle Session.");await fs3.mkdir(path3.dirname(this.statePath(sessionId)),{recursive:true,mode:448});await atomicWriteJSON(this.pendingPath(sessionId),prepared.command,{mode:384});await this.dependencies.drain(sessionId,prepared.command);await this.requireSession(sessionId);if(!this.dependencies.idle(sessionId))throw new Error("Extension Session acquired work while draining.");await this.dependencies.install(sessionId,prepared.packages,prepared.command);await fs3.mkdir(path3.dirname(this.statePath(sessionId)),{recursive:true,mode:448});await atomicWriteJSON(this.statePath(sessionId),prepared.command,{mode:384});this.active.set(sessionId,prepared);await fs3.rm(this.pendingPath(sessionId));return this.state(prepared.command)})}async getToolContext(sessionId,configRevision,value){await this.requireSession(sessionId);if(this.busy.has(sessionId))throw new Error("Extension configuration is changing.");const status=await this.status(sessionId);const active=this.active.get(sessionId);const pin2=parseManagedExtensionPin(value);const pkg=active?.packages.find(entry=>JSON.stringify(entry.pin)===JSON.stringify(pin2));if(!active||!pkg||status.pendingOperationId||status.revision!==configRevision)throw new Error("Extension tool configuration is unavailable.");const environment=this.environments.get(this.preparedKey(sessionId,active.command.operationId));if(!environment)throw new Error("Extension settings require exact reprepare.");await this.cache.verifyMaterialized(pin2.packageDigest,pkg.assetRoot);return{assetRoot:pkg.assetRoot,environment:{...environment[pin2.extensionId],QWEN_EXTENSION_ROOT:pkg.assetRoot}}}async bindSession(sessionId,runtimeSessionId,contextBinding){if(this.dependencies.bindContext)await this.dependencies.bindContext(sessionId,contextBinding);if(runtimeSessionId===void 0)return;const existing=this.ownerSessions.get(runtimeSessionId);if(existing&&existing!==sessionId)throw new Error("Extension Runtime owner conflicts.");this.ownerSessions.set(runtimeSessionId,sessionId);this.sessionOwners.set(sessionId,runtimeSessionId)}runtimeSessionId(sessionId){return this.sessionOwners.get(sessionId)??sessionId}isChanging(sessionId){return this.busy.has(this.ownerSessions.get(sessionId)??sessionId)}async readAsset(sessionId,revision,extensionId,relativePath){const root=await this.assetRoot(sessionId,revision,extensionId);const file=await this.contained(root,relativePath);const handle=await fs3.open(file,"r");try{const stat=await handle.stat();if(!stat.isFile()||stat.size>256*1024)throw new Error("Extension asset exceeds the read limit.");return{path:relativePath,content:await handle.readFile("utf8")}}finally{await handle.close()}}async globAssets(sessionId,revision,extensionId,pattern){const root=await this.assetRoot(sessionId,revision,extensionId);if(pattern.length>1024||pattern.includes("\0"))throw new Error("Invalid extension glob.");const paths=[];const visit=__name(async directory=>{for(const entry of await fs3.readdir(directory,{withFileTypes:true})){const filename=path3.join(directory,entry.name);const relative=path3.relative(root,filename).split(path3.sep).join("/");if(entry.isSymbolicLink())throw new Error("Extension assets contain a link.");if(entry.isDirectory())await visit(filename);else if(entry.isFile()&&minimatch(relative,pattern,{dot:true})){if(paths.length===2048)throw new Error("Extension glob exceeds its result limit.");paths.push(relative)}}},"visit");await visit(root);return paths.sort()}async assetRoot(sessionId,revision,extensionId){const status=await this.status(sessionId);const active=this.active.get(sessionId);if(this.isChanging(sessionId)||!active||status.revision!==revision)throw new Error("Extension configuration is unavailable.");const entry=active.packages.find(item=>item.pin.extensionId===extensionId);if(!entry)throw new Error("Extension package is not active in this Session.");if(status.pendingOperationId)throw new Error("Extension activation outcome is unknown.");await this.cache.verifyMaterialized(entry.pin.packageDigest,entry.assetRoot);return fs3.realpath(entry.assetRoot)}async contained(root,relative){if(!relative||relative.includes("\\")||relative.includes("\0")||path3.isAbsolute(relative))throw new Error("Invalid extension asset path.");const filename=await fs3.realpath(path3.resolve(root,relative));const resolved=path3.relative(root,filename);if(resolved===".."||resolved.startsWith(`..${path3.sep}`)||path3.isAbsolute(resolved))throw new Error("Extension asset path escapes its package.");return filename}preparedView(value){const result={operationId:value.command.operationId,state:"prepared",expectedRevision:value.command.expectedRevision,revision:value.command.expectedRevision+1,executionMode:this.dependencies.executionMode,packages:value.packages,mcpServers:value.mcpServers,hookCatalog:value.hookCatalog};if(Buffer.byteLength(JSON.stringify(result))>8*1024*1024)throw new Error("Extension prepare response exceeds its size limit.");return result}state(command){return{state:"active",executionMode:this.dependencies.executionMode,revision:command.expectedRevision+1,extensions:command.extensions,operationId:command.operationId}}async loadPrepared(sessionId,operationId){try{const value=JSON.parse(await fs3.readFile(this.operationPath(sessionId,operationId),"utf8"));if(value.ownerJournalId!==(this.dependencies.ownerJournalId??"in-memory"))throw new Error("Original extension owner journal is unavailable.");const command=parseManagedExtensionApplyCommand(value.command);if(command.operationId!==operationId||!Array.isArray(value.packages)||value.packages.length!==command.extensions.length)throw new Error("Invalid prepared extension receipt.");const pins=parseManagedExtensionPins(value.packages.map(pkg=>pkg.pin));if(JSON.stringify(pins)!==JSON.stringify(command.extensions))throw new Error("Prepared extension pins conflict.");for(const pkg of value.packages){if(typeof pkg.assetRoot!=="string"||path3.dirname(pkg.assetRoot)!==this.cache.directory||!path3.basename(pkg.assetRoot).startsWith(`${pkg.pin.packageDigest}-`))throw new Error("Invalid prepared extension asset root.")}this.preparedView(value);return value}catch(error){if(error.code==="ENOENT")return void 0;throw error}}operationPath(sessionId,operationId){return`${this.statePath(sessionId)}.${createHash2("sha256").update(operationId).digest("hex")}.prepared`}statePath(sessionId){return path3.join(this.dependencies.directory,"sessions",`${createHash2("sha256").update(sessionId).digest("hex")}.json`)}pendingPath(sessionId){return`${this.statePath(sessionId)}.pending`}preparedKey(sessionId,operationId){return`${sessionId}\0${operationId}`}async requireSession(sessionId){if(!sessionId||!await this.dependencies.admitted(sessionId))throw new Error("Extension Session is unavailable.")}async lock(sessionId,work){if(this.busy.has(sessionId))throw new Error("Extension Session configuration is changing.");this.busy.add(sessionId);try{await this.requireSession(sessionId);return await work()}finally{this.busy.delete(sessionId)}}};function registerManagedExtensionRuntimeRoutes(app,identity,runtime){app.put(MANAGED_EXTENSION_UPLOAD_ROUTE.path,managedRuntimeNoStore,authorizeManagedRuntime(identity),async(req,res)=>{try{if(req.headers["content-type"]!=="application/gzip")throw new Error("Invalid package content type.");await runtime.cache.upload(String(req.params["digest"]),req);res.json({protocolVersion:1,packageDigest:req.params["digest"]})}catch{res.status(400).json({code:"managed_extension_package_invalid"})}});app.post(MANAGED_EXTENSION_RUNTIME_ROUTE.path,managedRuntimeNoStore,authorizeManagedRuntime(identity),managedRuntimeJsonBody(512*1024),async(req,res)=>{try{const body2=req.body;if(!body2||!["contextBinding,operation,protocolVersion,sessionKey","contextBinding,operation,protocolVersion,runtimeSessionId,sessionKey"].includes(Object.keys(body2).sort().join(","))||body2["protocolVersion"]!==1||body2["runtimeSessionId"]!==void 0&&typeof body2["runtimeSessionId"]!=="string")throw new Error("Invalid extension request.");const runtimeSessionId=body2["runtimeSessionId"];const sessionKey=body2["sessionKey"];if(!sessionKey||Object.keys(sessionKey).sort().join(",")!=="sessionId,tenantId,workspaceId"||sessionKey["tenantId"]!==identity.tenantId||sessionKey["workspaceId"]!==identity.workspaceId||typeof sessionKey["sessionId"]!=="string"||!/^[A-Za-z0-9._:-]{1,128}$/u.test(sessionKey["sessionId"]))throw new Error("Extension Session scope conflicts.");const sessionId=sessionKey["sessionId"];await runtime.bindSession(sessionId,runtimeSessionId,body2["contextBinding"]);const operation=body2["operation"];let result;if(operation["kind"]==="prepare"||operation["kind"]==="extension-prepare"){const control=operation;const parsed=parseManagedExtensionApplyCommand(control.command);if(control.kind==="extension-prepare"&&(control.operationId!==parsed.operationId||control.expectedRevision!==parsed.expectedRevision||JSON.stringify(control.extensions)!==JSON.stringify(parsed.extensions)))throw new Error("Extension prepare identity conflicts.");result=await runtime.prepare(sessionId,parsed,control.kind==="extension-prepare"?{toolProfile:typeof operation["toolProfile"]==="string"?operation["toolProfile"]:void 0,packageManifests:operation["packageManifests"],baseMcpServers:control.baseMcpServers,baseHookCatalog:control.baseHookCatalog,settings:operation["settings"]}:void 0)}else if((operation["kind"]==="activate"||operation["kind"]==="extension-activate")&&typeof operation["operationId"]==="string")result=await runtime.activate(sessionId,operation["operationId"]);else if(operation["kind"]==="extension-reconcile"&&typeof operation["operationId"]==="string"&&Number.isSafeInteger(operation["expectedRevision"])&&Number.isSafeInteger(operation["revision"]))result=await runtime.reconcile(sessionId,operation["operationId"],Number(operation["expectedRevision"]),Number(operation["revision"]));else if(operation["kind"]==="status"||operation["kind"]==="extension-status")result=typeof operation["operationId"]==="string"?await runtime.operationStatus(sessionId,operation["operationId"]):await runtime.status(sessionId);else if((operation["kind"]==="asset-read"||operation["kind"]==="extension-asset-read")&&Number.isSafeInteger(operation["revision"])&&typeof operation["extensionId"]==="string"&&typeof operation["path"]==="string")result=await runtime.readAsset(sessionId,Number(operation["revision"]),operation["extensionId"],operation["path"]);else if((operation["kind"]==="asset-glob"||operation["kind"]==="extension-asset-glob")&&Number.isSafeInteger(operation["revision"])&&typeof operation["extensionId"]==="string"&&typeof operation["pattern"]==="string")result=await runtime.globAssets(sessionId,Number(operation["revision"]),operation["extensionId"],operation["pattern"]);else throw new Error("Invalid extension operation.");if(typeof operation["operationId"]==="string"&&String(operation["kind"]).includes("asset-"))result=Array.isArray(result)?{operationId:operation["operationId"],paths:result}:{...result,operationId:operation["operationId"]};res.json({protocolVersion:1,sessionKey,...runtimeSessionId?{runtimeSessionId}:{},result})}catch{res.status(409).json({code:"managed_extension_configuration_unavailable"})}})}__name(registerManagedExtensionRuntimeRoutes,"registerManagedExtensionRuntimeRoutes");function validateExtensionToolProfile(value,profile){if(profile===void 0)return;const shell=profile==="hosted-workspace-shell/1"||profile==="hosted-workspace-team-lead/1";const mcp=shell||profile==="hosted-workspace-mcp/1";if(!mcp&&Object.keys(value.mcpServers).length)throw new Error("Session profile does not admit extension MCP.");if(!shell&&(JSON.stringify(value.hooks).includes('"type":"command"')||Object.values(value.mcpServers).some(recipe=>recipe&&typeof recipe==="object"&&"command"in recipe)||value.commands.some(command=>/!\{|!`/u.test(command.prompt))))throw new Error("Session profile does not admit extension Shell execution.");const base=["read_file","glob"];if(profile!=="hosted-workspace-read/1")base.push("write_file","edit","list_directory","grep_search","todo_write");if(shell)base.push("run_shell_command");for(const agent of value.agents)if(agent.tools?.some(tool=>!base.includes(tool)&&!(mcp&&tool.startsWith("mcp__"))))throw new Error("Extension agent tools exceed the Session profile.")}__name(validateExtensionToolProfile,"validateExtensionToolProfile");init_esbuild_shims();init_esbuild_shims();var ManagedExtensionExecutionUnknownError=class extends Error{static{__name(this,"ManagedExtensionExecutionUnknownError")}};async function runManagedExtensionShell(owners,input){input.signal.throwIfAborted();const shell=getShellConfiguration();const{child,ownerId}=await owners.start({sessionId:input.sessionId,configRevision:input.configRevision,executable:shell.executable,args:[...shell.argsPrefix,input.command],cwd:input.cwd,env:input.environment});const streamsClosed=new Promise(resolve=>child.once("close",()=>resolve()));if(child.pid)input.capture?.setStarted(child.pid);child.stdin?.end();const chunks=[];let retained=0;let exceeded=false;const captures={stdout:Promise.resolve(),stderr:Promise.resolve()};for(const id of["stdout","stderr"]){child[id]?.on("data",chunk=>{if(input.capture){child[id]?.pause();captures[id]=captures[id].then(()=>input.capture.write(id,chunk)).finally(()=>child[id]?.resume())}const remaining=Math.max(0,1024*1024-retained);if(chunk.length>remaining)exceeded=true;if(remaining){const prefix=chunk.subarray(0,remaining);chunks.push(prefix);retained+=prefix.length}})}let timedOut=false;let timer;let wake;const stop=__name(()=>{wake?.()},"stop");try{const exited=new Promise(resolve=>{if(child.exitCode!==null||child.signalCode!==null)resolve();else child.once("exit",()=>resolve())});const interrupted=new Promise(resolve=>{wake=resolve;input.signal.addEventListener("abort",stop,{once:true});if(input.signal.aborted)resolve();timer=setTimeout(()=>{timedOut=true;resolve()},input.timeoutMs??12e4)});await Promise.race([exited,interrupted]);const receipt2=await owners.stop(ownerId).catch(()=>{throw new ManagedExtensionExecutionUnknownError("Extension Shell process stop is unknown.")});if(receipt2.state!=="stopped")throw new ManagedExtensionExecutionUnknownError("Extension Shell process stop is unknown.");let drainTimer;try{await Promise.race([streamsClosed,new Promise((_resolve,reject)=>{drainTimer=setTimeout(()=>reject(new ManagedExtensionExecutionUnknownError("Extension Shell output closure is unknown.")),5e3)})])}finally{if(drainTimer)clearTimeout(drainTimer)}await Promise.all(Object.values(captures));const rawOutput=Buffer.concat(chunks);const output=rawOutput.toString("utf8");const result={rawOutput,output,exitCode:child.exitCode,signal:null,error:null,aborted:input.signal.aborted||timedOut,pid:child.pid,executionMethod:"child_process",outputCaptureLimitExceeded:exceeded};input.capture?.setProcessResult(result);await input.capture?.finish("stdout",true);await input.capture?.finish("stderr",true);return{llmContent:`${output}${exceeded?"\n[Output truncated]":""}${timedOut?"\n[Command timed out]":""}`,returnDisplay:output,...child.exitCode!==0||result.aborted?{error:{message:result.aborted?"Shell command stopped.":`Shell exited with code ${child.exitCode}.`,type:"execution_failed"}}:{}}}finally{if(timer)clearTimeout(timer);input.signal.removeEventListener("abort",stop)}}__name(runManagedExtensionShell,"runManagedExtensionShell");init_esbuild_shims();import{createHash as createHash5}from"node:crypto";import{promises as fs5}from"node:fs";import path6 from"node:path";init_esbuild_shims();function gateKey(sessionKey,operationId){const key=assertManagedSessionKey(sessionKey);const id=assertManagedSessionStableId(operationId,"operationId");return`${key.tenantId}\0${key.workspaceId}\0${key.sessionId}\0${id}`}__name(gateKey,"gateKey");var ManagedOperationGrantGate=class{static{__name(this,"ManagedOperationGrantGate")}entries=new Map;install(value){const grant=parseOperationGrant(value);const key=gateKey(grant.sessionKey,grant.operationId);const entry=this.entries.get(key);if(entry!==void 0&&grant.operationRevision<=entry.revokedThrough){throw new ManagedSessionConflictError(`operation ${grant.operationId} revision ${grant.operationRevision} was revoked.`)}const current=entry?.grant;if(current!==void 0){if(JSON.stringify(current)===JSON.stringify(grant)){return"unchanged"}if(!isOperationGrantSuccessor(current,grant)){throw new ManagedSessionConflictError(`grant revision ${grant.operationRevision} of operation ${grant.operationId} cannot replace revision ${current.operationRevision}.`)}}this.entries.set(key,{grant,revokedThrough:entry?.revokedThrough??0});return"installed"}revoke(sessionKey,operationId,operationRevision){const key=gateKey(sessionKey,operationId);assertManagedSessionSequence(operationRevision,"operationRevision");if(operationRevision<1){throw new ManagedSessionRecordError("operationRevision must be a positive safe integer.")}const entry=this.entries.get(key)??{grant:void 0,revokedThrough:0};entry.revokedThrough=Math.max(entry.revokedThrough,operationRevision);this.entries.set(key,entry)}admits(sessionKey,operationId,phase,now){const entry=this.entries.get(gateKey(sessionKey,operationId));if(entry?.grant===void 0)return false;const{grant}=entry;return grant.operationRevision>entry.revokedThrough&&now<grant.expiresAt&&grant.resourceScope.phases.includes(phase)}};init_esbuild_shims();import path5 from"node:path";import{promises as fs4}from"node:fs";import{lstat as lstat2,readlink,realpath}from"node:fs/promises";import{isDeepStrictEqual as isDeepStrictEqual2}from"node:util";init_esbuild_shims();import{createHash as createHash3}from"node:crypto";import{createReadStream as createReadStream2}from"node:fs";import{lstat}from"node:fs/promises";import path4 from"node:path";import{isDeepStrictEqual}from"node:util";init_esbuild_shims();function copySnapshots(snapshots){return snapshots.map(snapshot=>({promptId:snapshot.promptId,timestamp:snapshot.timestamp,trackedFileBackups:Object.fromEntries(Object.entries(snapshot.trackedFileBackups).map(([filePath,backup])=>{if(!Number.isSafeInteger(backup.version)||backup.version<0){throw new Error("Invalid managed file history backup version.")}return[filePath,{backupFileName:backup.backupFileName,version:backup.version,backupTime:backup.backupTime,...backup.failed?{failed:true}:{}}]}))}))}__name(copySnapshots,"copySnapshots");var ManagedToolFileHistory=class{constructor(ownerSessionId,cwd,serializedSnapshots,retainedStorage){this.ownerSessionId=ownerSessionId;this.service=new FileHistoryService(ownerSessionId,true,cwd,()=>this.capture(),retainedStorage);this.service.restoreFromSnapshots(deserializeSnapshots(copySnapshots(serializedSnapshots)));this.snapshots=this.readSnapshots();this.snapshotJson=JSON.stringify(this.snapshots);this.startedPrompts=new Set(this.snapshots.map(({promptId})=>promptId));this.initialization=this.service.validateRestoredSnapshots();void this.initialization.catch(()=>{})}static{__name(this,"ManagedToolFileHistory")}service;initialization;pending=Promise.resolve();startedPrompts;revision=0;snapshots;snapshotJson;ready(){return this.initialization}state(){return{ownerSessionId:this.ownerSessionId,revision:this.revision,snapshots:structuredClone(this.snapshots)}}checkpoint(promptId){return this.run(async()=>{if(this.service.getSnapshots().at(-1)?.promptId===promptId)return;if(this.startedPrompts.has(promptId)){throw new Error("Managed file history cannot reopen an earlier turn.")}await this.service.makeSnapshot(promptId);this.startedPrompts.add(promptId)})}run(operation){const result=this.pending.then(async()=>{await this.initialization;try{return await operation()}finally{this.capture()}});this.pending=result.then(()=>{},()=>{});return result}async drain(){const pending=this.pending;await this.initialization;await pending}readSnapshots(){return copySnapshots(this.service.getSnapshots().map(serializeSnapshot))}capture(){const snapshots=this.readSnapshots();const snapshotJson=JSON.stringify(snapshots);if(snapshotJson===this.snapshotJson)return;this.snapshots=snapshots;this.snapshotJson=snapshotJson;this.revision++}};var ManagedRuntimeFileHistory=class{constructor(ownerSessionId,directory,state,retainedStorage){this.ownerSessionId=ownerSessionId;this.directory=directory;this.retainedStorage=retainedStorage;this.history=new ManagedToolFileHistory(ownerSessionId,directory,state?.snapshots.map(s=>({...s,trackedFileBackups:Object.fromEntries(Object.entries(s.trackedFileBackups).map(([file,backup])=>[file.split("/").join(path4.sep),backup]))}))??[],retainedStorage);this.files=Object.assign(Object.create(null),structuredClone(state?.files??{}))}static{__name(this,"ManagedRuntimeFileHistory")}history;files;prepared=new Set;async ready(checkPaths=true){await this.history.ready();await this.history.service.validateRestoredSnapshots();const checked=new Set;for(const snapshot of this.history.state().snapshots){for(const[file,backup]of Object.entries(snapshot.trackedFileBackups)){if(backup.failed)throw new Error("Hosted file history backup is unavailable.");if(checkPaths&&!checked.has(file)){await this.resolve(file.split(path4.sep).join("/"));checked.add(file)}}}}state(){return{ownerSessionId:this.ownerSessionId,snapshots:this.history.state().snapshots.map(s=>({...s,trackedFileBackups:Object.fromEntries(Object.entries(s.trackedFileBackups).map(([file,backup])=>[file.split(path4.sep).join("/"),backup]))})),files:structuredClone(this.files)}}async prepare(promptId,paths){await this.ready();const snapshots=this.history.state().snapshots;if(snapshots.length>=100&&snapshots.at(-1)?.promptId!==promptId)throw new Error("Hosted file history has reached its 100 snapshot limit.");const newPrompt=snapshots.at(-1)?.promptId!==promptId;const observed=Object.create(null);for(const file of new Set([...newPrompt?Object.keys(this.files):[],...paths])){observed[file]=await this.fingerprint(file);if(!newPrompt&&Object.hasOwn(this.files,file)&&!isDeepStrictEqual(observed[file],this.files[file]))throw new Error("Hosted file changed outside tracked mutations.")}const previous=new ManagedToolFileHistory(this.ownerSessionId,this.directory,snapshots,this.retainedStorage);await previous.ready();try{await this.history.checkpoint(promptId);await this.history.run(async()=>{for(const file of paths){const absolute=await this.resolve(file);await this.history.service.trackEdit(absolute);const backups=this.history.service.getSnapshots().at(-1)?.trackedFileBackups;const key=file.split("/").join(path4.sep);if(!backups||!Object.hasOwn(backups,key)||backups[key].failed)throw new Error("Hosted file backup failed; mutation was not started.")}await this.ready();for(const[file,expected]of Object.entries(observed))if(!isDeepStrictEqual(await this.fingerprint(file),expected))throw new Error("Hosted file changed during backup preparation.");Object.assign(this.files,observed);if(newPrompt)this.prepared.clear();for(const file of paths)this.prepared.add(file)})}catch(error){this.history=previous;throw error}}async execute(file,action){historyPath(file);if(!this.prepared.has(file))throw new Error("Hosted file mutation has no prepared backup.");return this.history.run(async()=>{await this.ready();if(!isDeepStrictEqual(await this.fingerprint(file),this.files[file]))throw new Error("Hosted file changed after backup preparation.");try{return await action()}finally{this.files[file]=await this.fingerprint(file)}})}async rewind(promptId){if(this.retainedStorage)throw new Error("Retained history cannot rewind.");await this.ready(false);return this.history.run(async()=>{let conflict2=false;try{for(const file of Object.keys(this.files)){if(!isDeepStrictEqual(await this.fingerprint(file),this.files[file])){conflict2=true;break}}}catch{conflict2=true}if(conflict2)return{state:this.state(),filesChanged:[],filesFailed:[],conflict:true};const result=await this.history.service.rewind(promptId,false);for(const file of Object.keys(this.files))this.files[file]=await this.fingerprint(file);return{state:this.state(),filesChanged:result.filesChanged.map(file=>path4.relative(this.directory,file).split(path4.sep).join("/")),filesFailed:result.filesFailed.map(file=>path4.relative(this.directory,file).split(path4.sep).join("/")),conflict:false}})}async resolve(file){historyPath(file);if(this.retainedStorage){const absolute=path4.join(this.directory,file);return this.retainedStorage.withWorkingFile(absolute,async()=>absolute)}let current=this.directory;const segments=file.split("/");for(const[index,segment]of segments.entries()){current=path4.join(current,segment);try{const info=await lstat(current);if(info.isSymbolicLink()||(index<segments.length-1?!info.isDirectory():!info.isFile()))throw new Error("Hosted file history requires ordinary Workspace files.")}catch(error){if(error.code!=="ENOENT")throw error}}return current}async fingerprint(file){historyPath(file);if(this.retainedStorage)return this.retainedStorage.withWorkingFile(path4.join(this.directory,file),async source=>source?{digest:`sha256:${await digestFileReadSource(source)}`,mode:source.stats.mode&4095}:null);const absolute=await this.resolve(file);try{const before=await lstat(absolute);const digest3=createHash3("sha256");for await(const chunk of createReadStream2(absolute))digest3.update(chunk);const after=await lstat(absolute);if(before.ino!==after.ino||before.size!==after.size||before.mtimeMs!==after.mtimeMs||before.mode!==after.mode)throw new Error("Hosted file changed while reading history.");return{digest:`sha256:${digest3.digest("hex")}`,mode:after.mode&4095}}catch(error){if(error.code==="ENOENT")return null;throw error}}};init_esbuild_shims();import{createHash as createHash4}from"node:crypto";import{readFileSync}from"node:fs";init_esbuild_shims();var SseError=class extends Error{static{__name(this,"SseError")}constructor(code,message,event){super(`SSE error: ${message}`);this.code=code;this.event=event}};var SSEClientTransport=class{static{__name(this,"SSEClientTransport")}constructor(url,opts){this._url=url;this._resourceMetadataUrl=void 0;this._scope=void 0;this._eventSourceInit=opts?.eventSourceInit;this._requestInit=opts?.requestInit;this._authProvider=opts?.authProvider;this._fetch=opts?.fetch;this._fetchWithInit=createFetchWithInit(opts?.fetch,opts?.requestInit)}async _authThenStart(){if(!this._authProvider){throw new UnauthorizedError("No auth provider")}let result;try{result=await auth(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(error){this.onerror?.(error);throw error}if(result!=="AUTHORIZED"){throw new UnauthorizedError}return await this._startOrAuth()}async _commonHeaders(){const headers={};if(this._authProvider){const tokens=await this._authProvider.tokens();if(tokens){headers["Authorization"]=`Bearer ${tokens.access_token}`}}if(this._protocolVersion){headers["mcp-protocol-version"]=this._protocolVersion}const extraHeaders=normalizeHeaders(this._requestInit?.headers);return new Headers({...headers,...extraHeaders})}_startOrAuth(){const fetchImpl=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((resolve,reject)=>{this._eventSource=new EventSource(this._url.href,{...this._eventSourceInit,fetch:__name(async(url,init)=>{const headers=await this._commonHeaders();headers.set("Accept","text/event-stream");const response=await fetchImpl(url,{...init,headers});if(response.status===401&&response.headers.has("www-authenticate")){const{resourceMetadataUrl,scope:scope3}=extractWWWAuthenticateParams(response);this._resourceMetadataUrl=resourceMetadataUrl;this._scope=scope3}return response},"fetch")});this._abortController=new AbortController;this._eventSource.onerror=event=>{if(event.code===401&&this._authProvider){this._authThenStart().then(resolve,reject);return}const error=new SseError(event.code,event.message,event);reject(error);this.onerror?.(error)};this._eventSource.onopen=()=>{};this._eventSource.addEventListener("endpoint",event=>{const messageEvent=event;try{this._endpoint=new URL(messageEvent.data,this._url);if(this._endpoint.origin!==this._url.origin){throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}}catch(error){reject(error);this.onerror?.(error);void this.close();return}resolve()});this._eventSource.onmessage=event=>{const messageEvent=event;let message;try{message=JSONRPCMessageSchema.parse(JSON.parse(messageEvent.data))}catch(error){this.onerror?.(error);return}this.onmessage?.(message)}})}async start(){if(this._eventSource){throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.")}return await this._startOrAuth()}async finishAuth(authorizationCode){if(!this._authProvider){throw new UnauthorizedError("No auth provider")}const result=await auth(this._authProvider,{serverUrl:this._url,authorizationCode,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit});if(result!=="AUTHORIZED"){throw new UnauthorizedError("Failed to authorize")}}async close(){this._abortController?.abort();this._eventSource?.close();this.onclose?.()}async send(message){if(!this._endpoint){throw new Error("Not connected")}try{const headers=await this._commonHeaders();headers.set("content-type","application/json");const init={...this._requestInit,method:"POST",headers,body:JSON.stringify(message),signal:this._abortController?.signal};const response=await(this._fetch??fetch)(this._endpoint,init);if(!response.ok){const text2=await response.text().catch(()=>null);if(response.status===401&&this._authProvider){const{resourceMetadataUrl,scope:scope3}=extractWWWAuthenticateParams(response);this._resourceMetadataUrl=resourceMetadataUrl;this._scope=scope3;const result=await auth(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit});if(result!=="AUTHORIZED"){throw new UnauthorizedError}return this.send(message)}throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text2}`)}await response.body?.cancel()}catch(error){this.onerror?.(error);throw error}}setProtocolVersion(version){this._protocolVersion=version}};init_esbuild_shims();var LAUNCHER=String.raw`
|
|
3
|
+
import{CSI_FILES_RETIREMENT_CAPABILITY_DIGEST,CSI_FILE_FINALIZATION_FORMAT,CSI_FILE_HISTORY_PATH,HOSTED_GLOB_TOO_COMPLEX,LocalShellResultCapture,MANAGED_CSI_ACK_LIMIT_BYTES,MANAGED_CSI_ACK_PATH,MANAGED_CSI_ATTEST_PATH,MANAGED_CSI_DRAIN_PATH,MANAGED_CSI_FILE_PREFIX,MANAGED_CSI_FILE_PROTOCOL,MANAGED_CSI_FILE_ROUTES,MANAGED_CSI_PROTOCOL,MANAGED_HOOK_MAX_REQUEST_BYTES,MANAGED_HOOK_MAX_RUNNING,MANAGED_HOOK_ROUTE,MANAGED_MCP_MAX_CONNECTIONS,MANAGED_MCP_ROUTE,MANAGED_MCP_TOOL,MANAGED_RUNTIME_PROVIDER_ROUTE,MANAGED_WORKSPACE_CONTEXT_FILES,MANAGED_WORKSPACE_CONTEXT_FILE_CHARS,MAX_PROVIDER_INLINE_MEDIA_BASE64_BYTES,MAX_PROVIDER_MEDIA_RESULT_BYTES,ManagedAutomationGateTool,ManagedCsiAckRequestError,ManagedCsiDrainRequestError,ManagedRuntimeProviderProtocolError,RESIDENT_WORKSPACE_CAPABILITY_DIGEST,WORKSPACE_ACTIVATION_ROUTE,WORKSPACE_CAPABILITY_DIGEST,WORKSPACE_CONTEXT_CONFIG_REF,WorkspaceActivations,checkHostedGlobPattern,compileManagedExtensionPackage,createManagedCsiFileReady,fitManagedRuntimeProviderResult,linuxDeviceNumber,managedRuntimeProviderLimit,minimatch,parseManagedCsiAckJson,parseManagedCsiAckRequest,parseManagedCsiAckResponse,parseManagedCsiAcknowledgement,parseManagedCsiBoot,parseManagedCsiCaptureIdentity,parseManagedCsiDrainRequest,parseManagedCsiFileBoot,parseManagedCsiFileJson,parseManagedRuntimeProviderRequest,parseManagedRuntimeProviderResult,readCsiFileHistoryEnvelope,readCsiFileHistoryObservation,readCsiNativeRequest,readCsiPreparationEvidence,readCurrentCsiNative,readManagedCsiFileContext,readManagedCsiFileDrain,validateManagedCsiAttestationRequest,validateManagedCsiAttestationResponse,validateManagedCsiFileAttestationRequest,validateManagedCsiFileAttestationResponse,validateManagedCsiPodIdentity,wrapManagedCsiFileContext}from"./chunk-4SZUJ5RT.js";import"./chunk-XXUK6YLA.js";import{MANAGED_CONTEXT_ROUTES,ManagedContextInstallations,checkManagedContextAttestation,createManagedContextAttestationResponse,createManagedContextReady,parseManagedContextBoot}from"./chunk-36TKFM4Z.js";import{MANAGED_TOOL_FILE_HISTORY_MAX_BYTES,captureManagedToolExecutionContext,historyPath,parseToolPublicationBinding}from"./chunk-IBDOC27R.js";import{computeManagedContextDigest,normalizeWorkspaceRelativePath}from"./chunk-YJ6APXNB.js";import"./chunk-6S5XOXJ2.js";import{MANAGED_SHELL_PUBLISHER_ROUTE,ManagedShellPublisherRegistry,publisherFields}from"./chunk-Z7WGIXI4.js";import{CLOSE_SWEEP_TIMEOUT_MS,GROUP_EXIT_EVIDENCE_TIMEOUT_MS,ManagedRuntimeLedger,managedRuntimeLedgerFromEnvironment,signalProcessGroup}from"./chunk-6QU44IVK.js";import{MANAGED_RUNTIME_TOOL_RESULT_BODY_LIMIT_BYTES,OWNED_MANAGED_RUNTIME_ROUTES,authorizeManagedRuntime,handleManagedRuntimeJsonError,managedRuntimeJsonBody,managedRuntimeNoStore,nameManagedRuntimeIncarnation,ownedManagedRuntimeRouteGate,registerManagedRuntimeAttestationRoute}from"./chunk-XLCTS6G3.js";import"./chunk-BC4C6F32.js";import"./chunk-2QYDBHYZ.js";import"./chunk-LUDNUVSA.js";import"./chunk-VTZZXEWA.js";import"./chunk-3SHHYK7S.js";import{require_express}from"./chunk-6SOKP7IN.js";import"./chunk-L5UULTGF.js";import"./chunk-CFTFKWPW.js";import"./chunk-NIEO2TBE.js";import"./chunk-ELUOCI74.js";import"./chunk-IS7CHVXD.js";import"./chunk-WSOEJTOC.js";import{scrubAndReportInheritedLoaderEnv}from"./chunk-N3AQAZ7D.js";import"./chunk-E5T4R2PM.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{TodoWriteTool}from"./chunk-ZYDOCKNF.js";import{WebFetchTool}from"./chunk-FNURB45T.js";import{GlobTool}from"./chunk-M7MGE5IU.js";import"./chunk-ZHHFNZ5J.js";import{WriteFileTool}from"./chunk-D5JWQUID.js";import{EditTool}from"./chunk-NGOWLXYK.js";import"./chunk-LKPMADUO.js";import"./chunk-UJP2MPBI.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{Client,Config,Ct,DEFAULT_INHERITED_ENV_VARS,EventSource,FileHistoryService,HookCommandCgroup,HookCommandIsolationUnavailableError,HookRegistry,HookRunner,LocalManagedSessionResourceStore,MAX_ARCHIVE_ENTRIES,MAX_ARCHIVE_EXPANDED_BYTES,MAX_ARCHIVE_PATH_BYTES,ManagedSessionConflictError,ManagedToolProtocolError,SessionWriterLease,ShellTool,So,StdioClientTransport,StreamableHTTPClientTransport,UnauthorizedError,auth,createFetchWithInit,deriveConfig,deserializeSnapshots,detectLineEnding,encodeTextFileContentAsync,extractWWWAuthenticateParams,firePostToolUseFailureHook,firePostToolUseHook,firePreToolUseHook,generateToolUseId,interpolateUrl,isModifiableDeclarativeTool,isOperationGrantSuccessor,isSinglePathSegment,managedSessionResourceRoot,managedToolDigest,normalizeHeaders,parseManagedExtensionApplyCommand,parseManagedExtensionPin,parseManagedExtensionPins,parseManagedToolContentModification,parseManagedToolMediaContext,parseOperationGrant,resolveCommandHookTimeoutMs,serializeManagedToolConfirmation,serializeSnapshot}from"./chunk-7XQ5D34E.js";import"./chunk-R2EHHA2C.js";import{CallToolResultSchema,GetPromptResultSchema,JSONRPCMessageSchema,ListPromptsResultSchema,ListResourcesResultSchema,ListToolsResultSchema,ReadBuffer,ReadResourceResultSchema,serializeMessage}from"./chunk-YK7NDQKM.js";import"./chunk-ZLZF2ZDD.js";import{MANAGED_TOOL_RESULT_KINDS,MANAGED_TOOL_RESULT_LIMITS,MANAGED_TOOL_RESULT_PROTOCOL,MANAGED_TOOL_RESULT_ROUTES,ManagedSessionRecordError,assertManagedSessionDigest,assertManagedSessionDurableRef,assertManagedSessionKey,assertManagedSessionSequence,assertManagedSessionStableId,isToolResultPageAt,parseToolResultManifestBytes,parseToolResultPageBytes,parseToolResultPrefixRequest,parseToolResultPublishRequest,parseToolResultSealRequest}from"./chunk-OMSVOFTC.js";import"./chunk-PHIPLV2I.js";import"./chunk-ZOTKZI2P.js";import"./chunk-A6G5TAIF.js";import"./chunk-YVBHCSZD.js";import"./chunk-FIXDX63I.js";import{isShellResultDisplay}from"./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{openNoFollow}from"./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{getShellContextEnvVars}from"./chunk-NMY3PYNO.js";import"./chunk-YGLM5XPP.js";import"./chunk-WGNF7FPC.js";import"./chunk-4NPYOXJO.js";import{promptIdContext}from"./chunk-MWGB5RCF.js";import{getShellConfiguration}from"./chunk-SCD5TUBG.js";import"./chunk-NTRFETZB.js";import"./chunk-TL3SF2GA.js";import{sanitizeChildEnv}from"./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{captureHookExecutionOwner,runWithHookExecutionOwner}from"./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{createAbortController}from"./chunk-476F6QIM.js";import"./chunk-4R67LXKL.js";import"./chunk-FQRF6B65.js";import"./chunk-LG4NL2M7.js";import{ReadFileTool}from"./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{FileReadOpenError,decodeBufferWithEncodingInfoAsync,digestFileReadSource,readFileHandleBytes,readTextContentRangeFromHandle}from"./chunk-Y6HHV4LC.js";import"./chunk-RP57XAJ2.js";import"./chunk-Z6AR5XE5.js";import"./chunk-7DOOXUDG.js";import"./chunk-77V43YOE.js";import"./chunk-7U7CWMP7.js";import{runWithInvocationContext}from"./chunk-EFTJIDS3.js";import"./chunk-4DIWAQ5G.js";import"./chunk-Q6UAOTP3.js";import"./chunk-HQZTAA2U.js";import"./chunk-GOR7FFVE.js";import"./chunk-4ZBZL23U.js";import{atomicWriteJSON}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"./chunk-M4ECEHLX.js";import"./chunk-DBRQGEEI.js";import"./chunk-B3ZFUGTC.js";import"./chunk-IRINPFG7.js";import{HookEventName,HooksConfigSource,getHookKey}from"./chunk-6GTPLW7K.js";import"./chunk-NGVRCUYD.js";import"./chunk-5DTFN37U.js";import{isPathWithinRoot}from"./chunk-2YUBAWQ6.js";import{ToolConfirmationOutcome}from"./chunk-O5EKX7LG.js";import"./chunk-TM6ZCBR7.js";import"./chunk-SVAPAMMG.js";import"./chunk-3KUHQGOS.js";import"./chunk-I6S7NGX3.js";import{ToolNames}from"./chunk-SBZFGYYS.js";import{createDebugLogger,registerSessionProjectDir,sessionIdContext,unregisterSessionModel,unregisterSessionProjectDir}from"./chunk-JAUJI56S.js";import"./chunk-I4H7NUVP.js";import{Storage}from"./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{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_express3=__toESM(require_express(),1);import{createServer as createServer2}from"node:http";import{createReadStream as createReadStream3}from"node:fs";import{mkdtemp as mkdtemp2}from"node:fs/promises";import path15 from"node:path";init_esbuild_shims();import{createHash as createHash10}from"node:crypto";import{isDeepStrictEqual as isDeepStrictEqual4}from"node:util";init_esbuild_shims();import{constants,promises as fs}from"node:fs";import path from"node:path";async function executable(command,cwd,environment){const candidates=command.includes("/")?[path.resolve(cwd,command)]:(environment["PATH"]??"/usr/bin:/bin").split(path.delimiter).map(directory=>path.resolve(cwd,directory,command));for(const candidate of candidates){try{if(!(await fs.stat(candidate)).isFile())continue;await fs.access(candidate,constants.X_OK);return candidate}catch{}}throw new Error(`Extension executable is unavailable: ${command}`)}__name(executable,"executable");async function preflightManagedExtensionPackage(contributions,root,cwd,environment){const env={...environment,QWEN_EXTENSION_ROOT:root,CLAUDE_PLUGIN_ROOT:root,extensionPath:root};const expand=__name((value,executionEnvironment=env)=>value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)/gu,(original,braced,plain)=>executionEnvironment[braced??plain]??original),"expand");let dynamicCommands=0;const check=__name(async(command,args,executionEnvironment=env)=>{const resolved=await executable(expand(command,executionEnvironment),cwd,executionEnvironment);const handle=await fs.open(resolved,"r");let head;try{const buffer=Buffer.alloc(512);const read=await handle.read(buffer,0,512,0);head=buffer.subarray(0,read.bytesRead).toString()}finally{await handle.close()}if(head.startsWith("#!")){const shebang=head.split("\n")[0].slice(2).trim().split(/\s+/u);await executable(shebang[0],cwd,executionEnvironment);if(path.basename(shebang[0])==="env"&&shebang[1]&&!shebang[1].startsWith("-"))await executable(shebang[1],cwd,executionEnvironment)}if(path.basename(resolved)==="env"&&args.length){if(args[0].startsWith("-")||args[0].includes("=")){dynamicCommands++;return}await check(args[0],args.slice(1),executionEnvironment);return}if(args.includes("-e")||args.includes("--eval")||args.includes("-c")){dynamicCommands++;return}for(const argument of args.filter(value=>!value.startsWith("-")&&/\.(?:[cm]?js|py|rb|sh)$/u.test(value))){const script=path.resolve(cwd,expand(argument,executionEnvironment));if(!(await fs.stat(script)).isFile())throw new Error("Extension script is unavailable.");await fs.access(script,constants.R_OK)}},"check");const shell=__name(async(command,executionEnvironment=env)=>{if(/[|;&><`\n]|\$\(/u.test(command)){dynamicCommands++;return}const tokens=[...command.matchAll(/"([^"]*)"|'([^']*)'|([^\s]+)/gu)].map(match=>match[1]??match[2]??match[3]);if(!tokens.length)return;if(tokens.some(token=>token.includes("$")&&expand(token,executionEnvironment)===token)){dynamicCommands++;return}if(/^[A-Za-z_][A-Za-z0-9_]*=/u.test(tokens[0])){dynamicCommands++;return}if([":","[","alias","bg","break","cd","continue","exit","export","false","fg","getopts","hash","jobs","pwd","read","readonly","return","set","shift","test","times","trap","true","type","ulimit","umask","unalias","unset","wait"].includes(tokens[0]))return;if(tokens[0]==="eval"){dynamicCommands++;return}if(["exec","command"].includes(tokens[0]))tokens.shift();if(tokens.length)await check(tokens[0],tokens.slice(1),executionEnvironment)},"shell");for(const value of Object.values(contributions.mcpServers)){const recipe=value;if(recipe.command)await check(recipe.command,recipe.args??[],{...env,...recipe.env})}for(const groups of Object.values(contributions.hooks)){for(const group of groups){for(const hook of group.hooks??[])if(hook.type==="command"&&hook.command)await shell(hook.command,{...env,...hook.env})}}for(const command of contributions.commands)for(const match of command.prompt.matchAll(/!\{([^}]*)\}/gu))await shell(match[1]);return{dynamicCommands}}__name(preflightManagedExtensionPackage,"preflightManagedExtensionPackage");init_esbuild_shims();function managedExtensionEnvironment(inherited,directory,extension={}){const environment={};for(const key of["PATH","LANG","LC_ALL","LC_CTYPE","TZ","TMPDIR","TMP","TEMP"]){const value=inherited[key];if(value!==void 0)environment[key]=value}return{...environment,HOME:directory,USERPROFILE:directory,...extension}}__name(managedExtensionEnvironment,"managedExtensionEnvironment");init_esbuild_shims();import{createHash as createHash2}from"node:crypto";import{promises as fs3}from"node:fs";import path3 from"node:path";init_esbuild_shims();import{createHash,randomUUID}from"node:crypto";import{createReadStream,createWriteStream,promises as fs2}from"node:fs";import path2 from"node:path";import{Transform}from"node:stream";import{pipeline}from"node:stream/promises";var MANAGED_EXTENSION_ARCHIVE_MAX_BYTES=100*1024*1024;var DIGEST=/^[0-9a-f]{64}$/u;var ManagedExtensionCache=class{constructor(directory){this.directory=directory;if(!path2.isAbsolute(directory))throw new Error("Invalid package cache.")}static{__name(this,"ManagedExtensionCache")}async upload(digest3,source){this.assertDigest(digest3);await fs2.mkdir(this.directory,{recursive:true,mode:448});const temporary=path2.join(this.directory,`.upload-${randomUUID()}`);const hash=createHash("sha256");let bytes=0;const limit=new Transform({transform(chunk,_encoding,callback){bytes+=chunk.byteLength;if(bytes>MANAGED_EXTENSION_ARCHIVE_MAX_BYTES){callback(new Error("Package archive exceeds its size limit."));return}hash.update(chunk);callback(null,chunk)}});try{await pipeline(source,limit,createWriteStream(temporary,{flags:"wx",mode:384}));if(hash.digest("hex")!==digest3)throw new Error("Package archive digest mismatch.");await this.validateArchive(temporary);await fs2.rename(temporary,this.archivePath(digest3))}finally{await fs2.rm(temporary,{force:true})}}materialize(digest3){this.assertDigest(digest3);return this.extract(digest3)}async extract(digest3){const archive=this.archivePath(digest3);const hash=createHash("sha256");for await(const chunk of createReadStream(archive))hash.update(chunk);if(hash.digest("hex")!==digest3)throw new Error("Cached package archive digest mismatch.");await this.validateArchive(archive);const destination=path2.join(this.directory,`${digest3}-${randomUUID()}`);await fs2.mkdir(destination,{mode:448});try{await So({file:archive,cwd:destination,strict:true,noChmod:true});await fs2.writeFile(`${destination}.integrity`,await this.treeDigest(destination),{mode:384,flag:"wx"});return destination}catch(error){await fs2.rm(destination,{recursive:true,force:true});throw error}}async restoreMaterialized(digest3,directory){this.assertDigest(digest3);if(path2.dirname(directory)!==this.directory||!new RegExp(`^${digest3}-[0-9a-f-]{36}$`,"u").test(path2.basename(directory))||!(await fs2.lstat(this.directory)).isDirectory())throw new Error("Extension cache scope conflicts.");try{await this.verifyMaterialized(digest3,directory);return}catch{}const fresh=await this.materialize(digest3);const quarantine=path2.join(this.directory,`.quarantine-${randomUUID()}`);const moveIfPresent=__name(async(source,target)=>{try{await fs2.rename(source,target)}catch(error){if(error.code!=="ENOENT")throw error}},"moveIfPresent");try{await moveIfPresent(directory,quarantine);await moveIfPresent(`${directory}.integrity`,`${quarantine}.integrity`);await fs2.rename(fresh,directory);await fs2.rename(`${fresh}.integrity`,`${directory}.integrity`);await this.verifyMaterialized(digest3,directory);await fs2.rm(quarantine,{recursive:true,force:true});await fs2.rm(`${quarantine}.integrity`,{force:true})}finally{await fs2.rm(fresh,{recursive:true,force:true});await fs2.rm(`${fresh}.integrity`,{force:true})}}async verifyMaterialized(digest3,directory){this.assertDigest(digest3);if(path2.dirname(directory)!==this.directory||!path2.basename(directory).startsWith(`${digest3}-`))throw new Error("Extension cache scope conflicts.");if(!(await fs2.lstat(directory)).isDirectory())throw new Error("Extension cache root is unsafe.");const expected=await fs2.readFile(`${directory}.integrity`,"utf8");if(await this.treeDigest(directory)!==expected)throw new Error("Extension package assets drifted.")}async treeDigest(directory){const hash=createHash("sha256");const visit=__name(async relative=>{const entries=await fs2.readdir(path2.join(directory,relative),{withFileTypes:true});for(const entry of entries.sort((a,b)=>a.name.localeCompare(b.name,"en"))){const child=path2.posix.join(relative,entry.name);if(!entry.isDirectory()&&!entry.isFile())throw new Error("Extension assets contain an unsafe entry.");hash.update(JSON.stringify([child,entry.isDirectory()?"directory":"file"]));if(entry.isDirectory())await visit(child);else{const content=createHash("sha256");for await(const chunk of createReadStream(path2.join(directory,child)))content.update(chunk);hash.update(content.digest())}}},"visit");await visit("");return hash.digest("hex")}async validateArchive(file){let count=0;let bytes=0;let pathBytes=0;let invalid3=false;const seen=new Set;const source=createReadStream(file);const parser=Ct({strict:true,onReadEntry(entry){const normalized=path2.posix.normalize(entry.path).replace(/\/$/u,"");count++;bytes+=entry.size;pathBytes+=Buffer.byteLength(entry.path);if(!["File","Directory","OldFile","ContiguousFile"].includes(entry.type)||entry.path.includes("\\")||entry.path.includes("\0")||path2.posix.isAbsolute(entry.path)||/^[a-zA-Z]:/u.test(entry.path)||normalized===".."||normalized.startsWith("../")||seen.has(normalized)||count>MAX_ARCHIVE_ENTRIES||bytes>MAX_ARCHIVE_EXPANDED_BYTES||pathBytes>MAX_ARCHIVE_PATH_BYTES){invalid3=true;source.destroy(new Error("Unsafe package archive."))}seen.add(normalized)}});await pipeline(source,parser);if(invalid3)throw new Error("Unsafe package archive.")}archivePath(digest3){return path2.join(this.directory,`${digest3}.tar.gz`)}assertDigest(digest3){if(!DIGEST.test(digest3))throw new Error("Invalid package digest.")}};var MANAGED_EXTENSION_RUNTIME_ROUTE=Object.freeze({key:"extensions",method:"POST",path:"/internal/managed-runtime/v3/extensions"});var MANAGED_EXTENSION_RETIRE_ROUTE=Object.freeze({key:"extension-retire",method:"POST",path:"/internal/managed-runtime/v3/extensions/retire"});var MANAGED_EXTENSION_UPLOAD_ROUTE=Object.freeze({key:"extension-package-upload",method:"PUT",path:"/internal/managed-runtime/v3/extensions/packages/:digest"});var ManagedExtensionRuntime=class{constructor(dependencies){this.dependencies=dependencies;if(!path3.isAbsolute(dependencies.directory))throw new Error("Invalid extension Runtime directory.");this.cache=new ManagedExtensionCache(path3.join(dependencies.directory,"packages"))}static{__name(this,"ManagedExtensionRuntime")}cache;prepared=new Map;active=new Map;busy=new Set;environments=new Map;sessionOwners=new Map;ownerSessions=new Map;async status(sessionId){await this.requireSession(sessionId);let pendingOperationId;try{pendingOperationId=parseManagedExtensionApplyCommand(JSON.parse(await fs3.readFile(this.pendingPath(sessionId),"utf8"))).operationId}catch(error){if(error.code!=="ENOENT")throw error}const pending=pendingOperationId?{pendingOperationId}:{};const installed=this.active.get(sessionId);if(installed)return{...this.state(installed.command),...pending};try{const stored=JSON.parse(await fs3.readFile(this.statePath(sessionId),"utf8"));const command=parseManagedExtensionApplyCommand(stored);const stopped=await fs3.stat(`${this.operationPath(sessionId,command.operationId)}.stopped`).then(()=>true,error=>{if(error.code==="ENOENT")return false;throw error});return{...this.state(command),...stopped?{state:"failed"}:{},...pending}}catch(error){if(error.code==="ENOENT")return{state:pendingOperationId?"outcome_unknown":"active",executionMode:this.dependencies.executionMode,revision:0,extensions:[],operationId:null,...pending};throw error}}async operationStatus(sessionId,operationId){const current=await this.status(sessionId);try{const proof=JSON.parse(await fs3.readFile(`${this.operationPath(sessionId,operationId)}.stopped`,"utf8"));if(proof["operationId"]!==operationId||proof["executionMode"]!==this.dependencies.executionMode||proof["state"]!=="stopped")throw new Error("Original stop proof conflicts.");return proof}catch(error){if(error.code!=="ENOENT")throw error}if(current.operationId===operationId&&!current.pendingOperationId)return current;const prepared=this.prepared.get(this.preparedKey(sessionId,operationId))??await this.loadPrepared(sessionId,operationId);if(prepared&&!current.pendingOperationId)return this.preparedView(prepared);return{...current,state:"outcome_unknown",operationId}}async prepare(sessionId,value,base={baseMcpServers:[],baseHookCatalog:null}){const command=parseManagedExtensionApplyCommand(value);return this.lock(sessionId,async()=>{const status=await this.status(sessionId);const key=this.preparedKey(sessionId,command.operationId);const existing=this.prepared.get(key)??await this.loadPrepared(sessionId,command.operationId);const publicBase={baseMcpServers:base.baseMcpServers,baseHookCatalog:base.baseHookCatalog};if(existing){if(JSON.stringify(existing.command)!==JSON.stringify(command)||JSON.stringify(existing.base)!==JSON.stringify(publicBase))throw new Error("Extension operation identity conflicts.");for(const pkg of existing.packages){await this.cache.restoreMaterialized(pkg.pin.packageDigest,pkg.assetRoot);const contributions=await this.dependencies.compile(pkg.assetRoot,pkg.pin,base.settings?.[pkg.pin.extensionId]??{},sessionId,base.packageManifests?.[pkg.pin.extensionId]);validateExtensionToolProfile(contributions,base.toolProfile);if(JSON.stringify(contributions)!==JSON.stringify(pkg.contributions))throw new Error("Prepared extension package drifted.")}const catalogs2=this.dependencies.stage?await this.dependencies.stage(sessionId,command,existing.packages,{...publicBase,preparedMcpServers:existing.mcpServers}):{mcpServers:[],hookCatalog:null};if(JSON.stringify(catalogs2.mcpServers)!==JSON.stringify(existing.mcpServers)||JSON.stringify(catalogs2.hookCatalog)!==JSON.stringify(existing.hookCatalog))throw new Error("Prepared extension catalogs drifted.");this.environments.set(key,base.settings??{});this.prepared.set(key,existing);return this.preparedView(existing)}if(status.pendingOperationId)throw new Error("Original extension activation outcome is unknown.");if(status.revision!==command.expectedRevision)throw new Error("Extension configuration revision conflicts.");if(!this.dependencies.idle(sessionId))throw new Error("Extension configuration requires an idle Session.");const packages=[];try{for(const pin2 of command.extensions){const unchanged=this.active.get(sessionId)?.packages.find(entry=>JSON.stringify(entry.pin)===JSON.stringify(pin2));const assetRoot=unchanged?.assetRoot??await this.cache.materialize(pin2.packageDigest);await this.cache.restoreMaterialized(pin2.packageDigest,assetRoot);packages.push({pin:pin2,assetRoot,contributions:{skills:[],commands:[],agents:[],context:[],mcpServers:{},hooks:{},settings:[]}});const contributions=await this.dependencies.compile(assetRoot,pin2,base.settings?.[pin2.extensionId]??{},sessionId,base.packageManifests?.[pin2.extensionId]);validateExtensionToolProfile(contributions,base.toolProfile);packages[packages.length-1]={pin:pin2,assetRoot,contributions}}}catch(error){await Promise.all(packages.map(entry=>this.active.get(sessionId)?.packages.some(active=>active.assetRoot===entry.assetRoot)?Promise.resolve():fs3.rm(entry.assetRoot,{recursive:true,force:true})));throw error}const catalogs=this.dependencies.stage?await this.dependencies.stage(sessionId,command,packages,base):{mcpServers:[],hookCatalog:null};if(!this.dependencies.stage&&packages.some(entry=>Object.keys(entry.contributions.mcpServers).length||Object.keys(entry.contributions.hooks).length))throw new Error("Extension process components are unsupported.");const prepared={ownerJournalId:this.dependencies.ownerJournalId??"in-memory",command,packages,base:publicBase,mcpServers:catalogs.mcpServers,hookCatalog:catalogs.hookCatalog};const view2=this.preparedView(prepared);await fs3.mkdir(path3.dirname(this.operationPath(sessionId,command.operationId)),{recursive:true,mode:448});await atomicWriteJSON(this.operationPath(sessionId,command.operationId),prepared,{mode:384});this.environments.set(key,base.settings??{});this.prepared.set(key,prepared);return view2})}async reconcile(sessionId,operationId,expectedRevision,revision){return this.lock(sessionId,async()=>{const prepared=await this.loadPrepared(sessionId,operationId);if(!prepared)throw new Error("Original extension owner journal is unavailable.");try{const proof2=JSON.parse(await fs3.readFile(`${this.operationPath(sessionId,operationId)}.stopped`,"utf8"));if(proof2["operationId"]!==operationId||proof2["revision"]!==revision||expectedRevision+1!==revision||proof2["executionMode"]!==this.dependencies.executionMode||proof2["state"]!=="stopped")throw new Error("Original stop proof conflicts.");return proof2}catch(error){if(error.code!=="ENOENT")throw error}const command=prepared.command;const current=await this.status(sessionId);if(command.operationId!==operationId||command.expectedRevision!==expectedRevision||revision!==expectedRevision+1||current.pendingOperationId!==void 0&¤t.pendingOperationId!==operationId||current.revision!==expectedRevision&&(current.operationId!==operationId||current.revision!==revision||JSON.stringify(current.extensions)!==JSON.stringify(command.extensions)))throw new Error("Original extension operation conflicts.");const receipts=this.dependencies.reconcile?await this.dependencies.reconcile(sessionId):void 0;if(!receipts||receipts.length===0||receipts.some(entry=>entry.state!=="stopped"))return{operationId,revision,state:"outcome_unknown",executionMode:this.dependencies.executionMode};const proof={operationId,revision,state:"stopped",executionMode:this.dependencies.executionMode,receipts};await atomicWriteJSON(`${this.operationPath(sessionId,operationId)}.stopped`,proof,{mode:384});await atomicWriteJSON(this.statePath(sessionId),command,{mode:384});this.active.delete(sessionId);await fs3.rm(this.pendingPath(sessionId),{force:true});return proof})}async activate(sessionId,operationId){return this.lock(sessionId,async()=>{const status=await this.status(sessionId);if(status.pendingOperationId)throw new Error("Original extension activation outcome is unknown.");if(status.operationId===operationId){if(!this.active.has(sessionId)){const restored=this.prepared.get(this.preparedKey(sessionId,operationId));if(!restored)throw new Error("Active extension configuration requires exact reprepare.");await this.dependencies.install(sessionId,restored.packages,restored.command);this.active.set(sessionId,restored)}return status}const prepared=this.prepared.get(this.preparedKey(sessionId,operationId));if(!prepared||status.revision!==prepared.command.expectedRevision)throw new Error("Extension configuration was not prepared.");if(!this.dependencies.idle(sessionId))throw new Error("Extension configuration requires an idle Session.");await fs3.mkdir(path3.dirname(this.statePath(sessionId)),{recursive:true,mode:448});await atomicWriteJSON(this.pendingPath(sessionId),prepared.command,{mode:384});await this.dependencies.drain(sessionId,prepared.command);await this.requireSession(sessionId);if(!this.dependencies.idle(sessionId))throw new Error("Extension Session acquired work while draining.");await this.dependencies.install(sessionId,prepared.packages,prepared.command);await fs3.mkdir(path3.dirname(this.statePath(sessionId)),{recursive:true,mode:448});await atomicWriteJSON(this.statePath(sessionId),prepared.command,{mode:384});this.active.set(sessionId,prepared);await fs3.rm(this.pendingPath(sessionId));return this.state(prepared.command)})}async getToolContext(sessionId,configRevision,value){await this.requireSession(sessionId);if(this.busy.has(sessionId))throw new Error("Extension configuration is changing.");const status=await this.status(sessionId);const active=this.active.get(sessionId);const pin2=parseManagedExtensionPin(value);const pkg=active?.packages.find(entry=>JSON.stringify(entry.pin)===JSON.stringify(pin2));if(!active||!pkg||status.pendingOperationId||status.revision!==configRevision)throw new Error("Extension tool configuration is unavailable.");const environment=this.environments.get(this.preparedKey(sessionId,active.command.operationId));if(!environment)throw new Error("Extension settings require exact reprepare.");await this.cache.verifyMaterialized(pin2.packageDigest,pkg.assetRoot);return{assetRoot:pkg.assetRoot,environment:{...environment[pin2.extensionId],QWEN_EXTENSION_ROOT:pkg.assetRoot}}}async bindSession(sessionId,runtimeSessionId,contextBinding){if(this.dependencies.bindContext)await this.dependencies.bindContext(sessionId,contextBinding);if(runtimeSessionId===void 0)return;const existing=this.ownerSessions.get(runtimeSessionId);if(existing&&existing!==sessionId)throw new Error("Extension Runtime owner conflicts.");this.ownerSessions.set(runtimeSessionId,sessionId);this.sessionOwners.set(sessionId,runtimeSessionId)}runtimeSessionId(sessionId){return this.sessionOwners.get(sessionId)??sessionId}isChanging(sessionId){return this.busy.has(this.ownerSessions.get(sessionId)??sessionId)}async readAsset(sessionId,revision,extensionId,relativePath){const root=await this.assetRoot(sessionId,revision,extensionId);const file=await this.contained(root,relativePath);const handle=await fs3.open(file,"r");try{const stat=await handle.stat();if(!stat.isFile()||stat.size>256*1024)throw new Error("Extension asset exceeds the read limit.");return{path:relativePath,content:await handle.readFile("utf8")}}finally{await handle.close()}}async globAssets(sessionId,revision,extensionId,pattern){const root=await this.assetRoot(sessionId,revision,extensionId);if(pattern.length>1024||pattern.includes("\0"))throw new Error("Invalid extension glob.");const paths=[];const visit=__name(async directory=>{for(const entry of await fs3.readdir(directory,{withFileTypes:true})){const filename=path3.join(directory,entry.name);const relative=path3.relative(root,filename).split(path3.sep).join("/");if(entry.isSymbolicLink())throw new Error("Extension assets contain a link.");if(entry.isDirectory())await visit(filename);else if(entry.isFile()&&minimatch(relative,pattern,{dot:true})){if(paths.length===2048)throw new Error("Extension glob exceeds its result limit.");paths.push(relative)}}},"visit");await visit(root);return paths.sort()}async assetRoot(sessionId,revision,extensionId){const status=await this.status(sessionId);const active=this.active.get(sessionId);if(this.isChanging(sessionId)||!active||status.revision!==revision)throw new Error("Extension configuration is unavailable.");const entry=active.packages.find(item=>item.pin.extensionId===extensionId);if(!entry)throw new Error("Extension package is not active in this Session.");if(status.pendingOperationId)throw new Error("Extension activation outcome is unknown.");await this.cache.verifyMaterialized(entry.pin.packageDigest,entry.assetRoot);return fs3.realpath(entry.assetRoot)}async contained(root,relative){if(!relative||relative.includes("\\")||relative.includes("\0")||path3.isAbsolute(relative))throw new Error("Invalid extension asset path.");const filename=await fs3.realpath(path3.resolve(root,relative));const resolved=path3.relative(root,filename);if(resolved===".."||resolved.startsWith(`..${path3.sep}`)||path3.isAbsolute(resolved))throw new Error("Extension asset path escapes its package.");return filename}preparedView(value){const result={operationId:value.command.operationId,state:"prepared",expectedRevision:value.command.expectedRevision,revision:value.command.expectedRevision+1,executionMode:this.dependencies.executionMode,packages:value.packages,mcpServers:value.mcpServers,hookCatalog:value.hookCatalog};if(Buffer.byteLength(JSON.stringify(result))>8*1024*1024)throw new Error("Extension prepare response exceeds its size limit.");return result}state(command){return{state:"active",executionMode:this.dependencies.executionMode,revision:command.expectedRevision+1,extensions:command.extensions,operationId:command.operationId}}async loadPrepared(sessionId,operationId){try{const value=JSON.parse(await fs3.readFile(this.operationPath(sessionId,operationId),"utf8"));if(value.ownerJournalId!==(this.dependencies.ownerJournalId??"in-memory"))throw new Error("Original extension owner journal is unavailable.");const command=parseManagedExtensionApplyCommand(value.command);if(command.operationId!==operationId||!Array.isArray(value.packages)||value.packages.length!==command.extensions.length)throw new Error("Invalid prepared extension receipt.");const pins=parseManagedExtensionPins(value.packages.map(pkg=>pkg.pin));if(JSON.stringify(pins)!==JSON.stringify(command.extensions))throw new Error("Prepared extension pins conflict.");for(const pkg of value.packages){if(typeof pkg.assetRoot!=="string"||path3.dirname(pkg.assetRoot)!==this.cache.directory||!path3.basename(pkg.assetRoot).startsWith(`${pkg.pin.packageDigest}-`))throw new Error("Invalid prepared extension asset root.")}this.preparedView(value);return value}catch(error){if(error.code==="ENOENT")return void 0;throw error}}operationPath(sessionId,operationId){return`${this.statePath(sessionId)}.${createHash2("sha256").update(operationId).digest("hex")}.prepared`}statePath(sessionId){return path3.join(this.dependencies.directory,"sessions",`${createHash2("sha256").update(sessionId).digest("hex")}.json`)}pendingPath(sessionId){return`${this.statePath(sessionId)}.pending`}preparedKey(sessionId,operationId){return`${sessionId}\0${operationId}`}async requireSession(sessionId){if(!sessionId||!await this.dependencies.admitted(sessionId))throw new Error("Extension Session is unavailable.")}async lock(sessionId,work){if(this.busy.has(sessionId))throw new Error("Extension Session configuration is changing.");this.busy.add(sessionId);try{await this.requireSession(sessionId);return await work()}finally{this.busy.delete(sessionId)}}};function registerManagedExtensionRuntimeRoutes(app,identity,runtime){app.put(MANAGED_EXTENSION_UPLOAD_ROUTE.path,managedRuntimeNoStore,authorizeManagedRuntime(identity),async(req,res)=>{try{if(req.headers["content-type"]!=="application/gzip")throw new Error("Invalid package content type.");await runtime.cache.upload(String(req.params["digest"]),req);res.json({protocolVersion:1,packageDigest:req.params["digest"]})}catch{res.status(400).json({code:"managed_extension_package_invalid"})}});app.post(MANAGED_EXTENSION_RUNTIME_ROUTE.path,managedRuntimeNoStore,authorizeManagedRuntime(identity),managedRuntimeJsonBody(512*1024),async(req,res)=>{try{const body2=req.body;if(!body2||!["contextBinding,operation,protocolVersion,sessionKey","contextBinding,operation,protocolVersion,runtimeSessionId,sessionKey"].includes(Object.keys(body2).sort().join(","))||body2["protocolVersion"]!==1||body2["runtimeSessionId"]!==void 0&&typeof body2["runtimeSessionId"]!=="string")throw new Error("Invalid extension request.");const runtimeSessionId=body2["runtimeSessionId"];const sessionKey=body2["sessionKey"];if(!sessionKey||Object.keys(sessionKey).sort().join(",")!=="sessionId,tenantId,workspaceId"||sessionKey["tenantId"]!==identity.tenantId||sessionKey["workspaceId"]!==identity.workspaceId||typeof sessionKey["sessionId"]!=="string"||!/^[A-Za-z0-9._:-]{1,128}$/u.test(sessionKey["sessionId"]))throw new Error("Extension Session scope conflicts.");const sessionId=sessionKey["sessionId"];await runtime.bindSession(sessionId,runtimeSessionId,body2["contextBinding"]);const operation=body2["operation"];let result;if(operation["kind"]==="prepare"||operation["kind"]==="extension-prepare"){const control=operation;const parsed=parseManagedExtensionApplyCommand(control.command);if(control.kind==="extension-prepare"&&(control.operationId!==parsed.operationId||control.expectedRevision!==parsed.expectedRevision||JSON.stringify(control.extensions)!==JSON.stringify(parsed.extensions)))throw new Error("Extension prepare identity conflicts.");result=await runtime.prepare(sessionId,parsed,control.kind==="extension-prepare"?{toolProfile:typeof operation["toolProfile"]==="string"?operation["toolProfile"]:void 0,packageManifests:operation["packageManifests"],baseMcpServers:control.baseMcpServers,baseHookCatalog:control.baseHookCatalog,settings:operation["settings"]}:void 0)}else if((operation["kind"]==="activate"||operation["kind"]==="extension-activate")&&typeof operation["operationId"]==="string")result=await runtime.activate(sessionId,operation["operationId"]);else if(operation["kind"]==="extension-reconcile"&&typeof operation["operationId"]==="string"&&Number.isSafeInteger(operation["expectedRevision"])&&Number.isSafeInteger(operation["revision"]))result=await runtime.reconcile(sessionId,operation["operationId"],Number(operation["expectedRevision"]),Number(operation["revision"]));else if(operation["kind"]==="status"||operation["kind"]==="extension-status")result=typeof operation["operationId"]==="string"?await runtime.operationStatus(sessionId,operation["operationId"]):await runtime.status(sessionId);else if((operation["kind"]==="asset-read"||operation["kind"]==="extension-asset-read")&&Number.isSafeInteger(operation["revision"])&&typeof operation["extensionId"]==="string"&&typeof operation["path"]==="string")result=await runtime.readAsset(sessionId,Number(operation["revision"]),operation["extensionId"],operation["path"]);else if((operation["kind"]==="asset-glob"||operation["kind"]==="extension-asset-glob")&&Number.isSafeInteger(operation["revision"])&&typeof operation["extensionId"]==="string"&&typeof operation["pattern"]==="string")result=await runtime.globAssets(sessionId,Number(operation["revision"]),operation["extensionId"],operation["pattern"]);else throw new Error("Invalid extension operation.");if(typeof operation["operationId"]==="string"&&String(operation["kind"]).includes("asset-"))result=Array.isArray(result)?{operationId:operation["operationId"],paths:result}:{...result,operationId:operation["operationId"]};res.json({protocolVersion:1,sessionKey,...runtimeSessionId?{runtimeSessionId}:{},result})}catch{res.status(409).json({code:"managed_extension_configuration_unavailable"})}})}__name(registerManagedExtensionRuntimeRoutes,"registerManagedExtensionRuntimeRoutes");function validateExtensionToolProfile(value,profile){if(profile===void 0)return;const shell=profile==="hosted-workspace-shell/1"||profile==="hosted-workspace-team-lead/1";const mcp=shell||profile==="hosted-workspace-mcp/1";if(!mcp&&Object.keys(value.mcpServers).length)throw new Error("Session profile does not admit extension MCP.");if(!shell&&(JSON.stringify(value.hooks).includes('"type":"command"')||Object.values(value.mcpServers).some(recipe=>recipe&&typeof recipe==="object"&&"command"in recipe)||value.commands.some(command=>/!\{|!`/u.test(command.prompt))))throw new Error("Session profile does not admit extension Shell execution.");const base=["read_file","glob"];if(profile!=="hosted-workspace-read/1")base.push("write_file","edit","list_directory","grep_search","todo_write");if(shell)base.push("run_shell_command");for(const agent of value.agents)if(agent.tools?.some(tool=>!base.includes(tool)&&!(mcp&&tool.startsWith("mcp__"))))throw new Error("Extension agent tools exceed the Session profile.")}__name(validateExtensionToolProfile,"validateExtensionToolProfile");init_esbuild_shims();init_esbuild_shims();var ManagedExtensionExecutionUnknownError=class extends Error{static{__name(this,"ManagedExtensionExecutionUnknownError")}};async function runManagedExtensionShell(owners,input){input.signal.throwIfAborted();const shell=getShellConfiguration();const{child,ownerId}=await owners.start({sessionId:input.sessionId,configRevision:input.configRevision,executable:shell.executable,args:[...shell.argsPrefix,input.command],cwd:input.cwd,env:input.environment});const streamsClosed=new Promise(resolve=>child.once("close",()=>resolve()));if(child.pid)input.capture?.setStarted(child.pid);child.stdin?.end();const chunks=[];let retained=0;let exceeded=false;const captures={stdout:Promise.resolve(),stderr:Promise.resolve()};for(const id of["stdout","stderr"]){child[id]?.on("data",chunk=>{if(input.capture){child[id]?.pause();captures[id]=captures[id].then(()=>input.capture.write(id,chunk)).finally(()=>child[id]?.resume())}const remaining=Math.max(0,1024*1024-retained);if(chunk.length>remaining)exceeded=true;if(remaining){const prefix=chunk.subarray(0,remaining);chunks.push(prefix);retained+=prefix.length}})}let timedOut=false;let timer;let wake;const stop=__name(()=>{wake?.()},"stop");try{const exited=new Promise(resolve=>{if(child.exitCode!==null||child.signalCode!==null)resolve();else child.once("exit",()=>resolve())});const interrupted=new Promise(resolve=>{wake=resolve;input.signal.addEventListener("abort",stop,{once:true});if(input.signal.aborted)resolve();timer=setTimeout(()=>{timedOut=true;resolve()},input.timeoutMs??12e4)});await Promise.race([exited,interrupted]);const receipt2=await owners.stop(ownerId).catch(()=>{throw new ManagedExtensionExecutionUnknownError("Extension Shell process stop is unknown.")});if(receipt2.state!=="stopped")throw new ManagedExtensionExecutionUnknownError("Extension Shell process stop is unknown.");let drainTimer;try{await Promise.race([streamsClosed,new Promise((_resolve,reject)=>{drainTimer=setTimeout(()=>reject(new ManagedExtensionExecutionUnknownError("Extension Shell output closure is unknown.")),5e3)})])}finally{if(drainTimer)clearTimeout(drainTimer)}await Promise.all(Object.values(captures));const rawOutput=Buffer.concat(chunks);const output=rawOutput.toString("utf8");const result={rawOutput,output,exitCode:child.exitCode,signal:null,error:null,aborted:input.signal.aborted||timedOut,pid:child.pid,executionMethod:"child_process",outputCaptureLimitExceeded:exceeded};input.capture?.setProcessResult(result);await input.capture?.finish("stdout",true);await input.capture?.finish("stderr",true);return{llmContent:`${output}${exceeded?"\n[Output truncated]":""}${timedOut?"\n[Command timed out]":""}`,returnDisplay:output,...child.exitCode!==0||result.aborted?{error:{message:result.aborted?"Shell command stopped.":`Shell exited with code ${child.exitCode}.`,type:"execution_failed"}}:{}}}finally{if(timer)clearTimeout(timer);input.signal.removeEventListener("abort",stop)}}__name(runManagedExtensionShell,"runManagedExtensionShell");init_esbuild_shims();import{createHash as createHash5}from"node:crypto";import{promises as fs5}from"node:fs";import path6 from"node:path";init_esbuild_shims();function gateKey(sessionKey,operationId){const key=assertManagedSessionKey(sessionKey);const id=assertManagedSessionStableId(operationId,"operationId");return`${key.tenantId}\0${key.workspaceId}\0${key.sessionId}\0${id}`}__name(gateKey,"gateKey");var ManagedOperationGrantGate=class{static{__name(this,"ManagedOperationGrantGate")}entries=new Map;install(value){const grant=parseOperationGrant(value);const key=gateKey(grant.sessionKey,grant.operationId);const entry=this.entries.get(key);if(entry!==void 0&&grant.operationRevision<=entry.revokedThrough){throw new ManagedSessionConflictError(`operation ${grant.operationId} revision ${grant.operationRevision} was revoked.`)}const current=entry?.grant;if(current!==void 0){if(JSON.stringify(current)===JSON.stringify(grant)){return"unchanged"}if(!isOperationGrantSuccessor(current,grant)){throw new ManagedSessionConflictError(`grant revision ${grant.operationRevision} of operation ${grant.operationId} cannot replace revision ${current.operationRevision}.`)}}this.entries.set(key,{grant,revokedThrough:entry?.revokedThrough??0});return"installed"}revoke(sessionKey,operationId,operationRevision){const key=gateKey(sessionKey,operationId);assertManagedSessionSequence(operationRevision,"operationRevision");if(operationRevision<1){throw new ManagedSessionRecordError("operationRevision must be a positive safe integer.")}const entry=this.entries.get(key)??{grant:void 0,revokedThrough:0};entry.revokedThrough=Math.max(entry.revokedThrough,operationRevision);this.entries.set(key,entry)}admits(sessionKey,operationId,phase,now){const entry=this.entries.get(gateKey(sessionKey,operationId));if(entry?.grant===void 0)return false;const{grant}=entry;return grant.operationRevision>entry.revokedThrough&&now<grant.expiresAt&&grant.resourceScope.phases.includes(phase)}};init_esbuild_shims();import path5 from"node:path";import{promises as fs4}from"node:fs";import{lstat as lstat2,readlink,realpath}from"node:fs/promises";import{isDeepStrictEqual as isDeepStrictEqual2}from"node:util";init_esbuild_shims();import{createHash as createHash3}from"node:crypto";import{createReadStream as createReadStream2}from"node:fs";import{lstat}from"node:fs/promises";import path4 from"node:path";import{isDeepStrictEqual}from"node:util";init_esbuild_shims();function copySnapshots(snapshots){return snapshots.map(snapshot=>({promptId:snapshot.promptId,timestamp:snapshot.timestamp,trackedFileBackups:Object.fromEntries(Object.entries(snapshot.trackedFileBackups).map(([filePath,backup])=>{if(!Number.isSafeInteger(backup.version)||backup.version<0){throw new Error("Invalid managed file history backup version.")}return[filePath,{backupFileName:backup.backupFileName,version:backup.version,backupTime:backup.backupTime,...backup.failed?{failed:true}:{}}]}))}))}__name(copySnapshots,"copySnapshots");var ManagedToolFileHistory=class{constructor(ownerSessionId,cwd,serializedSnapshots,retainedStorage){this.ownerSessionId=ownerSessionId;this.service=new FileHistoryService(ownerSessionId,true,cwd,()=>this.capture(),retainedStorage);this.service.restoreFromSnapshots(deserializeSnapshots(copySnapshots(serializedSnapshots)));this.snapshots=this.readSnapshots();this.snapshotJson=JSON.stringify(this.snapshots);this.startedPrompts=new Set(this.snapshots.map(({promptId})=>promptId));this.initialization=this.service.validateRestoredSnapshots();void this.initialization.catch(()=>{})}static{__name(this,"ManagedToolFileHistory")}service;initialization;pending=Promise.resolve();startedPrompts;revision=0;snapshots;snapshotJson;ready(){return this.initialization}state(){return{ownerSessionId:this.ownerSessionId,revision:this.revision,snapshots:structuredClone(this.snapshots)}}checkpoint(promptId){return this.run(async()=>{if(this.service.getSnapshots().at(-1)?.promptId===promptId)return;if(this.startedPrompts.has(promptId)){throw new Error("Managed file history cannot reopen an earlier turn.")}await this.service.makeSnapshot(promptId);this.startedPrompts.add(promptId)})}run(operation){const result=this.pending.then(async()=>{await this.initialization;try{return await operation()}finally{this.capture()}});this.pending=result.then(()=>{},()=>{});return result}async drain(){const pending=this.pending;await this.initialization;await pending}readSnapshots(){return copySnapshots(this.service.getSnapshots().map(serializeSnapshot))}capture(){const snapshots=this.readSnapshots();const snapshotJson=JSON.stringify(snapshots);if(snapshotJson===this.snapshotJson)return;this.snapshots=snapshots;this.snapshotJson=snapshotJson;this.revision++}};var ManagedRuntimeFileHistory=class{constructor(ownerSessionId,directory,state,retainedStorage){this.ownerSessionId=ownerSessionId;this.directory=directory;this.retainedStorage=retainedStorage;this.history=new ManagedToolFileHistory(ownerSessionId,directory,state?.snapshots.map(s=>({...s,trackedFileBackups:Object.fromEntries(Object.entries(s.trackedFileBackups).map(([file,backup])=>[file.split("/").join(path4.sep),backup]))}))??[],retainedStorage);this.files=Object.assign(Object.create(null),structuredClone(state?.files??{}))}static{__name(this,"ManagedRuntimeFileHistory")}history;files;prepared=new Set;async ready(checkPaths=true){await this.history.ready();await this.history.service.validateRestoredSnapshots();const checked=new Set;for(const snapshot of this.history.state().snapshots){for(const[file,backup]of Object.entries(snapshot.trackedFileBackups)){if(backup.failed)throw new Error("Hosted file history backup is unavailable.");if(checkPaths&&!checked.has(file)){await this.resolve(file.split(path4.sep).join("/"));checked.add(file)}}}}state(){return{ownerSessionId:this.ownerSessionId,snapshots:this.history.state().snapshots.map(s=>({...s,trackedFileBackups:Object.fromEntries(Object.entries(s.trackedFileBackups).map(([file,backup])=>[file.split(path4.sep).join("/"),backup]))})),files:structuredClone(this.files)}}async prepare(promptId,paths){await this.ready();const snapshots=this.history.state().snapshots;if(snapshots.length>=100&&snapshots.at(-1)?.promptId!==promptId)throw new Error("Hosted file history has reached its 100 snapshot limit.");const newPrompt=snapshots.at(-1)?.promptId!==promptId;const observed=Object.create(null);for(const file of new Set([...newPrompt?Object.keys(this.files):[],...paths])){observed[file]=await this.fingerprint(file);if(!newPrompt&&Object.hasOwn(this.files,file)&&!isDeepStrictEqual(observed[file],this.files[file]))throw new Error("Hosted file changed outside tracked mutations.")}const previous=new ManagedToolFileHistory(this.ownerSessionId,this.directory,snapshots,this.retainedStorage);await previous.ready();try{await this.history.checkpoint(promptId);await this.history.run(async()=>{for(const file of paths){const absolute=await this.resolve(file);await this.history.service.trackEdit(absolute);const backups=this.history.service.getSnapshots().at(-1)?.trackedFileBackups;const key=file.split("/").join(path4.sep);if(!backups||!Object.hasOwn(backups,key)||backups[key].failed)throw new Error("Hosted file backup failed; mutation was not started.")}await this.ready();for(const[file,expected]of Object.entries(observed))if(!isDeepStrictEqual(await this.fingerprint(file),expected))throw new Error("Hosted file changed during backup preparation.");Object.assign(this.files,observed);if(newPrompt)this.prepared.clear();for(const file of paths)this.prepared.add(file)})}catch(error){this.history=previous;throw error}}async execute(file,action){historyPath(file);if(!this.prepared.has(file))throw new Error("Hosted file mutation has no prepared backup.");return this.history.run(async()=>{await this.ready();if(!isDeepStrictEqual(await this.fingerprint(file),this.files[file]))throw new Error("Hosted file changed after backup preparation.");try{return await action()}finally{this.files[file]=await this.fingerprint(file)}})}async rewind(promptId){if(this.retainedStorage)throw new Error("Retained history cannot rewind.");await this.ready(false);return this.history.run(async()=>{let conflict2=false;try{for(const file of Object.keys(this.files)){if(!isDeepStrictEqual(await this.fingerprint(file),this.files[file])){conflict2=true;break}}}catch{conflict2=true}if(conflict2)return{state:this.state(),filesChanged:[],filesFailed:[],conflict:true};const result=await this.history.service.rewind(promptId,false);for(const file of Object.keys(this.files))this.files[file]=await this.fingerprint(file);return{state:this.state(),filesChanged:result.filesChanged.map(file=>path4.relative(this.directory,file).split(path4.sep).join("/")),filesFailed:result.filesFailed.map(file=>path4.relative(this.directory,file).split(path4.sep).join("/")),conflict:false}})}async resolve(file){historyPath(file);if(this.retainedStorage){const absolute=path4.join(this.directory,file);return this.retainedStorage.withWorkingFile(absolute,async()=>absolute)}let current=this.directory;const segments=file.split("/");for(const[index,segment]of segments.entries()){current=path4.join(current,segment);try{const info=await lstat(current);if(info.isSymbolicLink()||(index<segments.length-1?!info.isDirectory():!info.isFile()))throw new Error("Hosted file history requires ordinary Workspace files.")}catch(error){if(error.code!=="ENOENT")throw error}}return current}async fingerprint(file){historyPath(file);if(this.retainedStorage)return this.retainedStorage.withWorkingFile(path4.join(this.directory,file),async source=>source?{digest:`sha256:${await digestFileReadSource(source)}`,mode:source.stats.mode&4095}:null);const absolute=await this.resolve(file);try{const before=await lstat(absolute);const digest3=createHash3("sha256");for await(const chunk of createReadStream2(absolute))digest3.update(chunk);const after=await lstat(absolute);if(before.ino!==after.ino||before.size!==after.size||before.mtimeMs!==after.mtimeMs||before.mode!==after.mode)throw new Error("Hosted file changed while reading history.");return{digest:`sha256:${digest3.digest("hex")}`,mode:after.mode&4095}}catch(error){if(error.code==="ENOENT")return null;throw error}}};init_esbuild_shims();import{createHash as createHash4}from"node:crypto";import{readFileSync}from"node:fs";init_esbuild_shims();var SseError=class extends Error{static{__name(this,"SseError")}constructor(code,message,event){super(`SSE error: ${message}`);this.code=code;this.event=event}};var SSEClientTransport=class{static{__name(this,"SSEClientTransport")}constructor(url,opts){this._url=url;this._resourceMetadataUrl=void 0;this._scope=void 0;this._eventSourceInit=opts?.eventSourceInit;this._requestInit=opts?.requestInit;this._authProvider=opts?.authProvider;this._fetch=opts?.fetch;this._fetchWithInit=createFetchWithInit(opts?.fetch,opts?.requestInit)}async _authThenStart(){if(!this._authProvider){throw new UnauthorizedError("No auth provider")}let result;try{result=await auth(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(error){this.onerror?.(error);throw error}if(result!=="AUTHORIZED"){throw new UnauthorizedError}return await this._startOrAuth()}async _commonHeaders(){const headers={};if(this._authProvider){const tokens=await this._authProvider.tokens();if(tokens){headers["Authorization"]=`Bearer ${tokens.access_token}`}}if(this._protocolVersion){headers["mcp-protocol-version"]=this._protocolVersion}const extraHeaders=normalizeHeaders(this._requestInit?.headers);return new Headers({...headers,...extraHeaders})}_startOrAuth(){const fetchImpl=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((resolve,reject)=>{this._eventSource=new EventSource(this._url.href,{...this._eventSourceInit,fetch:__name(async(url,init)=>{const headers=await this._commonHeaders();headers.set("Accept","text/event-stream");const response=await fetchImpl(url,{...init,headers});if(response.status===401&&response.headers.has("www-authenticate")){const{resourceMetadataUrl,scope:scope3}=extractWWWAuthenticateParams(response);this._resourceMetadataUrl=resourceMetadataUrl;this._scope=scope3}return response},"fetch")});this._abortController=new AbortController;this._eventSource.onerror=event=>{if(event.code===401&&this._authProvider){this._authThenStart().then(resolve,reject);return}const error=new SseError(event.code,event.message,event);reject(error);this.onerror?.(error)};this._eventSource.onopen=()=>{};this._eventSource.addEventListener("endpoint",event=>{const messageEvent=event;try{this._endpoint=new URL(messageEvent.data,this._url);if(this._endpoint.origin!==this._url.origin){throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}}catch(error){reject(error);this.onerror?.(error);void this.close();return}resolve()});this._eventSource.onmessage=event=>{const messageEvent=event;let message;try{message=JSONRPCMessageSchema.parse(JSON.parse(messageEvent.data))}catch(error){this.onerror?.(error);return}this.onmessage?.(message)}})}async start(){if(this._eventSource){throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.")}return await this._startOrAuth()}async finishAuth(authorizationCode){if(!this._authProvider){throw new UnauthorizedError("No auth provider")}const result=await auth(this._authProvider,{serverUrl:this._url,authorizationCode,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit});if(result!=="AUTHORIZED"){throw new UnauthorizedError("Failed to authorize")}}async close(){this._abortController?.abort();this._eventSource?.close();this.onclose?.()}async send(message){if(!this._endpoint){throw new Error("Not connected")}try{const headers=await this._commonHeaders();headers.set("content-type","application/json");const init={...this._requestInit,method:"POST",headers,body:JSON.stringify(message),signal:this._abortController?.signal};const response=await(this._fetch??fetch)(this._endpoint,init);if(!response.ok){const text2=await response.text().catch(()=>null);if(response.status===401&&this._authProvider){const{resourceMetadataUrl,scope:scope3}=extractWWWAuthenticateParams(response);this._resourceMetadataUrl=resourceMetadataUrl;this._scope=scope3;const result=await auth(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit});if(result!=="AUTHORIZED"){throw new UnauthorizedError}return this.send(message)}throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text2}`)}await response.body?.cancel()}catch(error){this.onerror?.(error);throw error}}setProtocolVersion(version){this._protocolVersion=version}};init_esbuild_shims();var LAUNCHER=String.raw`
|
|
4
4
|
const { spawn } = require('node:child_process');
|
|
5
5
|
const [executable, argsJson] = process.argv.slice(1);
|
|
6
6
|
const args = JSON.parse(argsJson);
|
package/chunks/{managed-runtime-bootstrap-3BP5JRJX.js → managed-runtime-bootstrap-SRBDFSKK.js}
RENAMED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{SSH_RETIRE_PATH,SshBootstrapError,executeSshBootstrap,inspectSshStorage,readSshPrivateJson,readSshRuntimeRecord,runManagedRuntimeBootstrap,sshCleanProof,sshResourcePath,sshRuntimeHeaders,verifySshStorage,writeSshPrivateJson}from"./chunk-
|
|
3
|
+
import{SSH_RETIRE_PATH,SshBootstrapError,executeSshBootstrap,inspectSshStorage,readSshPrivateJson,readSshRuntimeRecord,runManagedRuntimeBootstrap,sshCleanProof,sshResourcePath,sshRuntimeHeaders,verifySshStorage,writeSshPrivateJson}from"./chunk-RXK6XD6F.js";import"./chunk-36TKFM4Z.js";import"./chunk-YJ6APXNB.js";import"./chunk-6ZEMLEK2.js";import"./chunk-O4EDHV64.js";import"./chunk-VKDAXTCZ.js";import"./chunk-KBWJGX7I.js";export{SSH_RETIRE_PATH,SshBootstrapError,executeSshBootstrap,inspectSshStorage,readSshPrivateJson,readSshRuntimeRecord,runManagedRuntimeBootstrap,sshCleanProof,sshResourcePath,sshRuntimeHeaders,verifySshStorage,writeSshPrivateJson};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{ProcessExitError,ProcessRegistry}from"./chunk-ESSOEHTE.js";import{LedgerSweepRetiredError,LedgerSweepUnprovenError,MANAGED_RUNTIME_LEDGER_ENV,ensureLedgerDirectory,processGroupLiveness,startLedgerReaper,sweepStaleLedgers,sweepWorkerLedger}from"./chunk-6QU44IVK.js";import{isNodeOptionsEnvKey,processBootLoaderEnv}from"./chunk-N3AQAZ7D.js";import"./chunk-E5T4R2PM.js";import"./chunk-S7IKHQ6I.js";import{LocalExecutionEnvironment}from"./chunk-ZFOEVHWG.js";import"./chunk-M7MGE5IU.js";import"./chunk-S7Z7SUH3.js";import"./chunk-ZHHFNZ5J.js";import"./chunk-FK5M3433.js";import"./chunk-N6EFYQ7M.js";import"./chunk-GXWDEHFP.js";import"./chunk-W2CV36HT.js";import"./chunk-O3TUZQP4.js";import"./chunk-WXK7Z45R.js";import"./chunk-UJP2MPBI.js";import"./chunk-AKWYMQKU.js";import"./chunk-MZUOREFD.js";import{managedToolDigest,managedToolFailureMessage,managedToolResponseParts}from"./chunk-T3CQ72HC.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{MANAGED_RUNTIME_TOOL_NAMES,ManagedRuntimeOutcomeUnknownError}from"./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{promptIdContext}from"./chunk-MWGB5RCF.js";import"./chunk-SCD5TUBG.js";import"./chunk-NTRFETZB.js";import"./chunk-TL3SF2GA.js";import"./chunk-LMJPU2JM.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-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-H5EXNXGW.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{ToolNames}from"./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{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{spawn}from"node:child_process";import{createHash,randomBytes,randomUUID}from"node:crypto";import{existsSync}from"node:fs";import http from"node:http";import path from"node:path";import{createInterface}from"node:readline";var READY_TIMEOUT_MS=3e4;var CANCEL_SETTLE_TIMEOUT_MS=15e3;var STATUS_POLL_MS=100;var EXIT_GRACE_MS=100;var CONTROL_REQUEST_TIMEOUT_MS=1e4;var MANAGED_RUNTIME_RESPONSE_LIMIT_BYTES=2*1024*1024;var LOCAL_CAPABILITY_DIGEST=`sha256:${createHash("sha256").update("qwen-code/managed-session-runtime/1").digest("hex")}`;var WorkerTransportError=class extends Error{static{__name(this,"WorkerTransportError")}undelivered;constructor(message,options,undelivered){super(message,options);this.undelivered=undelivered??options?.cause?.code==="ECONNREFUSED"}};var INSPECT_FLAGS=new Set(["--inspect","--inspect-brk","--inspect-brk-node","--inspect-wait","--inspect-port","--debug-port"]);var OPTIONS_FILE_FLAGS=new Set(["--env-file","--env-file-if-exists","--experimental-config-file","--experimental-default-config-file"]);var SEPARATE_VALUE_FLAGS=new Set(["--inspect-port","--debug-port","--env-file","--env-file-if-exists","--experimental-config-file"]);function withheldOptionIndexes(options){const indexes=new Set;for(let index=0;index<options.length;index++){const option=options[index];if(!option.startsWith("--"))continue;const flag=option.split("=",1)[0].replaceAll("_","-");if(!INSPECT_FLAGS.has(flag)&&!OPTIONS_FILE_FLAGS.has(flag))continue;indexes.add(index);if(SEPARATE_VALUE_FLAGS.has(flag)&&!option.includes("=")){indexes.add(++index)}}return indexes}__name(withheldOptionIndexes,"withheldOptionIndexes");function workerExecArgv(options){const indexes=withheldOptionIndexes(options);return options.filter((_,index)=>!indexes.has(index))}__name(workerExecArgv,"workerExecArgv");function nodeOptionsWithoutInspectFlags(value){const entries=[];let option="";let written="";let quoted=false;const endEntry=__name(()=>{if(option!=="")entries.push({option,written});option="";written=""},"endEntry");for(let index=0;index<value.length;index++){const char=value[index];if(char===" "&&!quoted){endEntry();continue}written+=char;if(char==='"'){quoted=!quoted}else if(char==="\\"&"ed&&index+1<value.length){option+=value[++index];written+=value[index]}else{option+=char}}endEntry();const indexes=withheldOptionIndexes(entries.map(entry=>entry.option));if(indexes.size===0)return value;return entries.filter((_,index)=>!indexes.has(index)).map(entry=>entry.written).join(" ")}__name(nodeOptionsWithoutInspectFlags,"nodeOptionsWithoutInspectFlags");function currentCliWorkerLaunch(){const cliEntry=process.env["QWEN_CLI_ENTRY"]||process.argv[1];if(!cliEntry){throw new Error("The Managed Runtime worker needs the CLI entry script.")}const env={...process.env,...Object.fromEntries(processBootLoaderEnv)};for(const key of Object.keys(env)){const nodeOptions=env[key];if(!isNodeOptionsEnvKey(key)||nodeOptions===void 0)continue;const kept=nodeOptionsWithoutInspectFlags(nodeOptions);if(kept===nodeOptions)continue;if(kept!=="")env[key]=kept;else delete env[key]}return{command:process.execPath,args:[...workerExecArgv(process.execArgv),cliEntry,"managed-runtime-worker"],env}}__name(currentCliWorkerLaunch,"currentCliWorkerLaunch");var ManagedSessionRuntimeWorker=class{constructor(sessionId,directory,launch=currentCliWorkerLaunch,cancelSettleTimeoutMs=CANCEL_SETTLE_TIMEOUT_MS,options={}){this.sessionId=sessionId;this.directory=directory;this.launch=launch;this.cancelSettleTimeoutMs=cancelSettleTimeoutMs;this.options=options}static{__name(this,"ManagedSessionRuntimeWorker")}registry=new ProcessRegistry;starting;closed=false;ledgerPaths=new Set;async execute(toolName,input,signal,callId=randomUUID()){signal.throwIfAborted();const worker=await this.ensureStarted(signal);if(worker===void 0){return{executionStatus:"cancelled",responseParts:[]}}return this.executeIn(worker,toolName,JSON.parse(JSON.stringify(input)),signal,this.referenceFor(callId,input))}async ensureStarted(signal){signal.throwIfAborted();let stopWatching=__name(()=>{},"stopWatching");const cancelled=new Promise(resolve=>{const onAbort=__name(()=>resolve(void 0),"onAbort");signal.addEventListener("abort",onAbort,{once:true});stopWatching=__name(()=>signal.removeEventListener("abort",onAbort),"stopWatching")});let worker;try{worker=await Promise.race([this.start(),cancelled])}catch(error){if(this.closed){throw new Error("The Managed session is closing.",{cause:error})}throw error}finally{stopWatching()}if(this.closed)throw new Error("The Managed session is closing.");if(worker===void 0||signal.aborted)return void 0;return worker}async executeIn(worker,toolName,input,signal,reference){signal.throwIfAborted();let settled=false;let cancelling;const giveUp=new AbortController;const ended=new AbortController;let giveUpTimer;const cancel=__name(()=>{giveUpTimer=setTimeout(()=>giveUp.abort(),this.cancelSettleTimeoutMs);cancelling=(async()=>{while(!ended.signal.aborted&&!giveUp.signal.aborted){const answer=await this.request(worker,"cancel",{protocolVersion:2,reference}).catch(()=>void 0);if(answer?.body?.state!=="unknown"){return}await new Promise(resolve=>setTimeout(resolve,STATUS_POLL_MS))}})()},"cancel");signal.addEventListener("abort",cancel,{once:true});try{let response;try{response=await this.request(worker,"execute",{protocolVersion:2,reference,toolName,input},giveUp.signal)}catch(error){if(!(error instanceof WorkerTransportError))throw error;if(error.undelivered){this.forget(worker);settled=true;return{executionStatus:"not_started",responseParts:[],error:{message:"The Runtime worker was not running."}}}await exitOrTimeout(worker.gone,EXIT_GRACE_MS)}if(response?.status===200){const result2=settledResult(response.body);if(result2){settled=true;return result2}}else if(response!==void 0&&response.status>=400&&response.status<500){settled=true;return{executionStatus:"not_started",responseParts:[],error:{message:refusalMessage(response.body)}}}const result=await this.awaitSettlement(worker,reference,giveUp.signal);settled=true;return result}finally{ended.abort();signal.removeEventListener("abort",cancel);clearTimeout(giveUpTimer);if(!settled)await cancelling}}referenceFor(callId,params){const normalized=JSON.parse(JSON.stringify(params));return{sessionId:this.sessionId,promptId:promptIdContext.getStore()??"unknown",callId,argsDigest:`sha256:${managedToolDigest(normalized)}`}}async acknowledge(reference){let worker;try{worker=this.starting!==void 0?await this.starting:void 0}catch{return}if(worker===void 0||this.closed)return;try{await this.request(worker,"acknowledge",{protocolVersion:2,reference})}catch{}}async close(){this.closed=true;const failures=[];try{await this.registry.shutdown()}catch(error){const parts=error instanceof AggregateError?error.errors:[error];failures.push(...parts.filter(part=>!(part instanceof ProcessExitError)))}for(const ledgerPath of[...this.ledgerPaths]){const armedReason=this.unprovenLedgerPaths.get(ledgerPath);if(armedReason!==void 0){failures.push(armedReason);continue}try{await this.sweepLedgerOnce(ledgerPath)}catch(error){failures.push(toRuntimeError(error))}}if(failures.length>0){throw new AggregateError(failures,"The Runtime worker did not stop.")}}unprovenLedgerPaths=new Map;reportUnproven(ledgerPath,reason){if(this.unprovenLedgerPaths.has(ledgerPath))return;this.unprovenLedgerPaths.set(ledgerPath,reason);this.options.quarantine?.report(reason);let lastNamed=unprovenGroupsOf(reason);let sawRetired=sweepRetiredLedger(reason);startLedgerReaper(async()=>{let verdict;try{verdict=await sweepWorkerLedger(ledgerPath)}catch(error){sawRetired=sawRetired||sweepRetiredLedger(error);lastNamed=[...new Set([...lastNamed,...unprovenGroupsOf(error)])];throw error}if(verdict==="proven")return"proven";const alive=lastNamed.filter(pgid=>processGroupLiveness(pgid)!=="gone");if(alive.length===0){return sawRetired||lastNamed.length===0?"terminal":"proven"}lastNamed=alive;return"unproven"},()=>{this.unprovenLedgerPaths.delete(ledgerPath);this.options.quarantine?.lift(reason)})}sweepsInFlight=new Map;async sweepLedgerOnce(ledgerPath){const inFlight=this.sweepsInFlight.get(ledgerPath);if(inFlight!==void 0)return inFlight;const promise=(async()=>{try{await sweepWorkerLedger(ledgerPath,{exitWitnessed:true})}catch(error){this.reportUnproven(ledgerPath,toRuntimeError(error));throw error}})();this.sweepsInFlight.set(ledgerPath,promise);try{await promise}finally{if(this.sweepsInFlight.get(ledgerPath)===promise){this.sweepsInFlight.delete(ledgerPath)}}}async sweepDeadWorkerLedger(worker){if(!worker.ledgerPath)return;await this.sweepLedgerOnce(worker.ledgerPath).catch(()=>void 0)}async awaitSettlement(worker,reference,giveUp){while(true){if(worker.gone.aborted||this.closed){throw new ManagedRuntimeOutcomeUnknownError("The Runtime worker exited during a tool call.")}const lastLook=giveUp.aborted;let response;try{response=await this.request(worker,"status",{protocolVersion:2,reference})}catch(error){throw new ManagedRuntimeOutcomeUnknownError("The Runtime worker stopped answering for a tool call.",{cause:error})}const body=response.body;if(response.status!==200||body?.state==="unknown"){throw new ManagedRuntimeOutcomeUnknownError("The Runtime worker does not know how a tool call ended.")}const result=settledResult(response.body);if(result)return result;if(lastLook){throw new ManagedRuntimeOutcomeUnknownError("A cancelled Runtime tool call did not settle.")}await new Promise(resolve=>setTimeout(resolve,STATUS_POLL_MS))}}start(){if(this.closed){return Promise.reject(new Error("The Managed session is closing."))}if(this.starting)return this.starting;const starting=this.launchWorker();this.starting=starting;const forget=__name(()=>{if(this.starting===starting&&!this.closed)this.starting=void 0},"forget");void starting.then(worker=>worker.tracked.exited.then(()=>this.sweepAfterExit(worker)),forget);return starting}sweepAfterExit(worker){void this.sweepDeadWorkerLedger(worker);void this.starting?.then(current=>{if(current===worker&&!this.closed)this.starting=void 0},()=>void 0)}forget(worker){void this.starting?.then(current=>{if(current===worker&&!this.closed)this.starting=void 0},()=>void 0);void worker.tracked.terminate().catch(()=>void 0)}async launchWorker(){const boot={type:"boot",version:1,token:randomBytes(32).toString("hex"),runtimeInstanceId:this.sessionId,runtimeIncarnation:randomUUID(),leaseId:randomUUID(),epoch:1,provisionRequestId:randomUUID(),tenantId:"local",workspaceId:"local",workspaceGeneration:"1",workspaceCwd:this.directory,capabilityDigest:LOCAL_CAPABILITY_DIGEST,isolationClass:"session"};const{MANAGED_RUNTIME_INCARNATION_HEADER,OWNED_MANAGED_RUNTIME_ROUTES}=await import("./managed-runtime-attestation-contract-FUULB2VI.js");const routes=new Map(OWNED_MANAGED_RUNTIME_ROUTES.map(route=>[route.key,route.path]));const launch=this.launch();const ledgerPath=this.options.ledgerDir?path.join(this.options.ledgerDir,`${boot.runtimeIncarnation}.json`):void 0;if(ledgerPath!==void 0){ensureLedgerDirectory(path.dirname(ledgerPath));this.ledgerPaths.add(ledgerPath);launchedLedgerPaths.add(ledgerPath)}const reservation=this.registry.reserve();let child;try{child=spawn(launch.command,[...launch.args],{cwd:this.directory,env:ledgerPath===void 0?launch.env??process.env:{...launch.env??process.env,[MANAGED_RUNTIME_LEDGER_ENV]:ledgerPath},stdio:["pipe","pipe","inherit","ipc"],detached:process.platform!=="win32",windowsHide:true})}catch(error){reservation.cancel();if(ledgerPath!==void 0)launchedLedgerPaths.delete(ledgerPath);throw error}const tracked=reservation.attach(child,{ownsProcessTree:true});const gone=new AbortController;void tracked.exited.then(()=>gone.abort(),()=>gone.abort());try{child.stdin.on("error",()=>void 0);child.stdin.end(JSON.stringify(boot));const ready=await readReady(child.stdout,tracked);if(ready.type!=="ready"||ready.version!==1||ready.runtimeInstanceId!==boot.runtimeInstanceId||ready.runtimeIncarnation!==boot.runtimeIncarnation||ready.leaseId!==boot.leaseId||ready.epoch!==boot.epoch||typeof ready.url!=="string"||!/^http:\/\/127\.0\.0\.1:\d+$/u.test(ready.url)){throw new Error("The Managed Runtime worker is not the one started.")}const worker={tracked,url:new URL(ready.url),boot,routes,incarnationHeader:MANAGED_RUNTIME_INCARNATION_HEADER.toLowerCase(),gone:gone.signal,ledgerPath};const attested=await this.request(worker,"attest",{protocolVersion:2,provisionRequestId:boot.provisionRequestId,tenantId:boot.tenantId,workspaceId:boot.workspaceId,workspaceGeneration:boot.workspaceGeneration,workspaceCwd:boot.workspaceCwd,capabilityDigest:boot.capabilityDigest,isolationClass:boot.isolationClass});const identity=attested.body;if(attested.status!==200||identity?.["runtimeIncarnation"]!==boot.runtimeIncarnation||identity?.["leaseId"]!==boot.leaseId){throw new Error("The Managed Runtime worker failed attestation.")}return worker}catch(error){await tracked.terminate().catch(()=>void 0);if(ledgerPath!==void 0){launchedLedgerPaths.delete(ledgerPath);void this.sweepLedgerOnce(ledgerPath).catch(()=>void 0)}throw error}}request(worker,route,body,stop){if(worker.gone.aborted){return Promise.reject(new WorkerTransportError("The Runtime worker exited.",void 0,true))}const payload=Buffer.from(JSON.stringify(body));return new Promise((resolve,reject)=>{const request=http.request({host:worker.url.hostname,port:worker.url.port,path:worker.routes.get(route),method:"POST",agent:false,headers:{Authorization:`Bearer ${worker.boot.token}`,"Cache-Control":"no-store","Content-Type":"application/json","Content-Length":payload.byteLength,"X-Qwen-Managed-Lease-Id":worker.boot.leaseId,"X-Qwen-Managed-Lease-Epoch":String(worker.boot.epoch)}},response=>{if(route!=="attest"&&response.statusCode===200&&response.headers[worker.incarnationHeader]!==worker.boot.runtimeIncarnation){reject(new WorkerTransportError("The Runtime worker did not answer as itself."));request.destroy();return}const chunks=[];let size=0;response.on("data",chunk=>{size+=chunk.byteLength;if(size>MANAGED_RUNTIME_RESPONSE_LIMIT_BYTES){response.destroy(new WorkerTransportError("Runtime worker response is too large."));return}chunks.push(chunk)});response.on("error",error=>reject(new WorkerTransportError(error.message,{cause:error})));response.on("end",()=>{let parsed;try{const text=Buffer.concat(chunks).toString("utf8");parsed=text.length>0?JSON.parse(text):void 0}catch(error){reject(new WorkerTransportError("Runtime worker response is invalid.",{cause:error}));return}resolve({status:response.statusCode??0,body:parsed})})});request.on("error",error=>reject(new WorkerTransportError(error.message,{cause:error})));const exited=__name(()=>request.destroy(new WorkerTransportError("The Runtime worker exited.")),"exited");worker.gone.addEventListener("abort",exited,{once:true});request.on("close",()=>worker.gone.removeEventListener("abort",exited));if(stop){const abandon=__name(()=>request.destroy(new WorkerTransportError("Abandoned the request.")),"abandon");if(stop.aborted)abandon();else stop.addEventListener("abort",abandon,{once:true});request.on("close",()=>stop.removeEventListener("abort",abandon))}else{request.setTimeout(CONTROL_REQUEST_TIMEOUT_MS,()=>request.destroy(new WorkerTransportError("The request timed out.")))}request.end(payload)})}};function isWithin(root,candidate){const relative=path.relative(path.resolve(root),path.resolve(root,candidate));return relative!==".."&&!relative.startsWith(`..${path.sep}`)&&!path.isAbsolute(relative)}__name(isWithin,"isWithin");function exitOrTimeout(gone,ms){if(gone.aborted)return Promise.resolve();return new Promise(resolve=>{const done=__name(()=>{clearTimeout(timer);gone.removeEventListener("abort",done);resolve()},"done");const timer=setTimeout(done,ms);gone.addEventListener("abort",done,{once:true})})}__name(exitOrTimeout,"exitOrTimeout");function readReady(stdout,tracked){const lines=createInterface({input:stdout,crlfDelay:Infinity});return new Promise((resolve,reject)=>{let settled=false;const finish=__name((error,ready)=>{if(settled)return;settled=true;clearTimeout(timer);if(error)reject(error);else resolve(ready)},"finish");const timer=setTimeout(()=>finish(new Error("The Managed Runtime worker did not get ready.")),READY_TIMEOUT_MS);timer.unref();lines.on("line",line=>{if(settled)return;try{finish(void 0,JSON.parse(line))}catch{finish(new Error("The Managed Runtime worker is not ready."))}});void tracked.exited.then(()=>finish(new Error("The Managed Runtime worker exited before it was ready.")))})}__name(readReady,"readReady");function toRuntimeError(error){return error instanceof Error?error:new Error(String(error))}__name(toRuntimeError,"toRuntimeError");function settledResult(body){const view=body;return view?.state==="settled"&&view.result?view.result:void 0}__name(settledResult,"settledResult");function refusalMessage(body){const error=body?.error;return typeof error==="string"?error:"The Runtime worker refused the tool call."}__name(refusalMessage,"refusalMessage");function toToolResult(payload){const parts=managedToolResponseParts(payload.responseParts);const text=parts.map(part=>part.text).filter(value=>typeof value==="string").join("\n");if(payload.executionStatus==="success"){return{llmContent:parts,returnDisplay:text}}const message=managedToolFailureMessage(payload);return{llmContent:parts.length>0?parts:message,returnDisplay:text||message,error:{message,...payload.error?.type?{type:payload.error.type}:{}}}}__name(toToolResult,"toToolResult");var launchedLedgerPaths=new Set;var armedStaleSweeps=new Set;var dirSweepsInFlight=new Map;function sweepStaleRuntimeLedgers(ledgerDir,quarantine){if(dirSweepsInFlight.has(ledgerDir))return;const options={skip:launchedLedgerPaths};const sweeping=sweepStaleLedgers(ledgerDir,options).catch(error=>{if(armedStaleSweeps.has(ledgerDir))return;armedStaleSweeps.add(ledgerDir);const reason=toRuntimeError(error);quarantine.report(reason);let sawRetired=sweepRetiredLedger(error);const armedFiles=new Set(workFilesOf(error));const namedByFile=new Map;const recordNames=__name(failure=>{const failures=failure instanceof AggregateError?failure.errors:[failure];for(const each of failures){if(each instanceof LedgerSweepUnprovenError&&each.remaining.length>0){const named=namedByFile.get(each.workFile)??new Set;for(const pgid of each.remaining)named.add(pgid);namedByFile.set(each.workFile,named)}}},"recordNames");recordNames(error);const provenFiles=new Set;startLedgerReaper(async()=>{const judged=new Set;try{await sweepStaleLedgers(ledgerDir,options,workFile=>{judged.add(workFile);provenFiles.add(workFile)})}catch(retryError){sawRetired=sawRetired||sweepRetiredLedger(retryError);recordNames(retryError);for(const workFile of workFilesOf(retryError)){armedFiles.add(workFile)}throw retryError}const vanished=[];for(const workFile of armedFiles){if(provenFiles.has(workFile)||judged.has(workFile))continue;if(!existsSync(workFile)){vanished.push(workFile);continue}return"unproven"}if(vanished.length===0)return"proven";let namedAlive=0;let unevidenced=false;for(const workFile of vanished){const named=namedByFile.get(workFile);if(named===void 0){unevidenced=true;continue}const alive=[...named].filter(pgid=>processGroupLiveness(pgid)!=="gone");namedByFile.set(workFile,new Set(alive));namedAlive+=alive.length}if(namedAlive>0)return"unproven";return unevidenced||sawRetired?"terminal":"proven"},()=>{armedStaleSweeps.delete(ledgerDir);quarantine.lift(reason)})});dirSweepsInFlight.set(ledgerDir,sweeping);void sweeping.finally(()=>{if(dirSweepsInFlight.get(ledgerDir)===sweeping){dirSweepsInFlight.delete(ledgerDir)}})}__name(sweepStaleRuntimeLedgers,"sweepStaleRuntimeLedgers");function workFilesOf(error){const failures=error instanceof AggregateError?error.errors:[error];return failures.flatMap(failure=>failure instanceof LedgerSweepUnprovenError||failure instanceof LedgerSweepRetiredError?[failure.workFile]:[])}__name(workFilesOf,"workFilesOf");function unprovenGroupsOf(error){const failures=error instanceof AggregateError?error.errors:[error];return[...new Set(failures.flatMap(failure=>failure instanceof LedgerSweepUnprovenError?[...failure.remaining]:[]))]}__name(unprovenGroupsOf,"unprovenGroupsOf");function sweepRetiredLedger(error){const failures=error instanceof AggregateError?error.errors:[error];return failures.some(failure=>failure instanceof LedgerSweepRetiredError)}__name(sweepRetiredLedger,"sweepRetiredLedger");function createManagedRuntimeEnvironment(config,launch){const sessionDirectory=config.getTargetDir();const ledgerDir=path.join(config.storage.getProjectTempDir(),"managed-runtime");const quarantine={report:__name(reason=>config.reportManagedEngineQuarantine(reason),"report"),lift:__name(reason=>config.clearManagedEngineQuarantine(reason),"lift")};try{ensureLedgerDirectory(ledgerDir)}catch{}sweepStaleRuntimeLedgers(ledgerDir,quarantine);const worker=new ManagedSessionRuntimeWorker(config.getSessionId(),sessionDirectory,launch,CANCEL_SETTLE_TIMEOUT_MS,{ledgerDir,quarantine});const prepared=new LocalExecutionEnvironment(config,{toolNames:MANAGED_RUNTIME_TOOL_NAMES,run:__name(async(call,signal)=>{const outcomes=config.getManagedRuntimeOutcomes();if(!outcomes){throw new Error("This Managed session records no log.")}const started=await worker.ensureStarted(signal);if(!started){return toToolResult({executionStatus:"cancelled",responseParts:[]})}const params=JSON.parse(JSON.stringify(call.params));const promptId=promptIdContext.getStore()??"unknown";const callId=call.callId??call.id;await outcomes.admit({functionCallId:callId,toolName:call.toolName,promptId,params,toolDefinition:prepared.toolDefinition(call.toolName),workerIncarnation:started.boot.runtimeIncarnation});const settleCall=__name(async outcome=>{try{await outcomes.settle({functionCallId:callId,executionStatus:outcome.executionStatus,payload:outcome})}catch(error){if(outcomes.hasCommittedReceipt(callId))return;const blocked=new ManagedRuntimeOutcomeUnknownError("The durable settlement of a Runtime tool call failed.",{cause:error});config.blockManagedSession(blocked);await worker.close().catch(()=>void 0);throw blocked}},"settleCall");if(signal.aborted){const payload2={executionStatus:"cancelled",responseParts:[],error:{message:managedToolFailureMessage({executionStatus:"cancelled"})}};await settleCall(payload2);return toToolResult(payload2)}const reference=worker.referenceFor(callId,params);let payload;try{payload=await worker.executeIn(started,call.toolName,params,signal,reference)}catch(error){if(error instanceof ManagedRuntimeOutcomeUnknownError){config.blockManagedSession(error);await worker.close().catch(()=>void 0)}throw error}await settleCall(payload);void worker.acknowledge(reference);const result=toToolResult(payload);return call.toolName===ToolNames.READ_FILE&&!result.error?{...result,returnDisplay:""}:result},"run")});return{toolNames:prepared.toolNames,prepare:__name(async(request,signal)=>{const preparation=await prepared.prepare(request,signal);if(request.toolName===ToolNames.SHELL){const directory=preparation.params["directory"];const refusal=preparation.params["is_background"]===true?"A Managed session runs shell commands in the foreground only.":typeof directory==="string"&&directory!==""&&!isWithin(sessionDirectory,directory)?`A Managed session runs shell commands only in ${sessionDirectory}.`:void 0;if(refusal){await prepared.release(request.id,signal);throw new Error(refusal)}}return preparation},"prepare"),permission:__name((id,signal)=>prepared.permission(id,signal),"permission"),confirmation:__name((id,signal)=>prepared.confirmation(id,signal),"confirmation"),confirm:__name((id,outcome,payload,signal)=>prepared.confirm(id,outcome,payload,signal),"confirm"),execute:__name((id,signal,updateOutput)=>prepared.execute(id,signal,updateOutput),"execute"),modificationContent:__name((toolName,params,signal)=>prepared.modificationContent(toolName,params,signal),"modificationContent"),release:__name((id,signal)=>prepared.release(id,signal),"release"),invalidateReadCache:__name(()=>Promise.resolve(),"invalidateReadCache"),dispose:__name(async()=>{try{await prepared.dispose()}finally{await worker.close()}},"dispose")}}__name(createManagedRuntimeEnvironment,"createManagedRuntimeEnvironment");export{MANAGED_RUNTIME_RESPONSE_LIMIT_BYTES,ManagedSessionRuntimeWorker,createManagedRuntimeEnvironment,currentCliWorkerLaunch,nodeOptionsWithoutInspectFlags,toToolResult,workerExecArgv};
|
|
3
|
+
import{ProcessExitError,ProcessRegistry}from"./chunk-ESSOEHTE.js";import{LedgerSweepRetiredError,LedgerSweepUnprovenError,MANAGED_RUNTIME_LEDGER_ENV,ensureLedgerDirectory,processGroupLiveness,startLedgerReaper,sweepStaleLedgers,sweepWorkerLedger}from"./chunk-6QU44IVK.js";import{isNodeOptionsEnvKey,processBootLoaderEnv}from"./chunk-N3AQAZ7D.js";import"./chunk-E5T4R2PM.js";import"./chunk-S7IKHQ6I.js";import{LocalExecutionEnvironment}from"./chunk-XVDIHFRH.js";import"./chunk-M7MGE5IU.js";import"./chunk-S7Z7SUH3.js";import"./chunk-ZHHFNZ5J.js";import"./chunk-FK5M3433.js";import"./chunk-IKF2HWEV.js";import"./chunk-GXWDEHFP.js";import"./chunk-D5JWQUID.js";import"./chunk-NGOWLXYK.js";import"./chunk-LKPMADUO.js";import"./chunk-UJP2MPBI.js";import"./chunk-AKWYMQKU.js";import"./chunk-MZUOREFD.js";import{managedToolDigest,managedToolFailureMessage,managedToolResponseParts}from"./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{MANAGED_RUNTIME_TOOL_NAMES,ManagedRuntimeOutcomeUnknownError}from"./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{promptIdContext}from"./chunk-MWGB5RCF.js";import"./chunk-SCD5TUBG.js";import"./chunk-NTRFETZB.js";import"./chunk-TL3SF2GA.js";import"./chunk-LMJPU2JM.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-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{ToolNames}from"./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{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{spawn}from"node:child_process";import{createHash,randomBytes,randomUUID}from"node:crypto";import{existsSync}from"node:fs";import http from"node:http";import path from"node:path";import{createInterface}from"node:readline";var READY_TIMEOUT_MS=3e4;var CANCEL_SETTLE_TIMEOUT_MS=15e3;var STATUS_POLL_MS=100;var EXIT_GRACE_MS=100;var CONTROL_REQUEST_TIMEOUT_MS=1e4;var MANAGED_RUNTIME_RESPONSE_LIMIT_BYTES=2*1024*1024;var LOCAL_CAPABILITY_DIGEST=`sha256:${createHash("sha256").update("qwen-code/managed-session-runtime/1").digest("hex")}`;var WorkerTransportError=class extends Error{static{__name(this,"WorkerTransportError")}undelivered;constructor(message,options,undelivered){super(message,options);this.undelivered=undelivered??options?.cause?.code==="ECONNREFUSED"}};var INSPECT_FLAGS=new Set(["--inspect","--inspect-brk","--inspect-brk-node","--inspect-wait","--inspect-port","--debug-port"]);var OPTIONS_FILE_FLAGS=new Set(["--env-file","--env-file-if-exists","--experimental-config-file","--experimental-default-config-file"]);var SEPARATE_VALUE_FLAGS=new Set(["--inspect-port","--debug-port","--env-file","--env-file-if-exists","--experimental-config-file"]);function withheldOptionIndexes(options){const indexes=new Set;for(let index=0;index<options.length;index++){const option=options[index];if(!option.startsWith("--"))continue;const flag=option.split("=",1)[0].replaceAll("_","-");if(!INSPECT_FLAGS.has(flag)&&!OPTIONS_FILE_FLAGS.has(flag))continue;indexes.add(index);if(SEPARATE_VALUE_FLAGS.has(flag)&&!option.includes("=")){indexes.add(++index)}}return indexes}__name(withheldOptionIndexes,"withheldOptionIndexes");function workerExecArgv(options){const indexes=withheldOptionIndexes(options);return options.filter((_,index)=>!indexes.has(index))}__name(workerExecArgv,"workerExecArgv");function nodeOptionsWithoutInspectFlags(value){const entries=[];let option="";let written="";let quoted=false;const endEntry=__name(()=>{if(option!=="")entries.push({option,written});option="";written=""},"endEntry");for(let index=0;index<value.length;index++){const char=value[index];if(char===" "&&!quoted){endEntry();continue}written+=char;if(char==='"'){quoted=!quoted}else if(char==="\\"&"ed&&index+1<value.length){option+=value[++index];written+=value[index]}else{option+=char}}endEntry();const indexes=withheldOptionIndexes(entries.map(entry=>entry.option));if(indexes.size===0)return value;return entries.filter((_,index)=>!indexes.has(index)).map(entry=>entry.written).join(" ")}__name(nodeOptionsWithoutInspectFlags,"nodeOptionsWithoutInspectFlags");function currentCliWorkerLaunch(){const cliEntry=process.env["QWEN_CLI_ENTRY"]||process.argv[1];if(!cliEntry){throw new Error("The Managed Runtime worker needs the CLI entry script.")}const env={...process.env,...Object.fromEntries(processBootLoaderEnv)};for(const key of Object.keys(env)){const nodeOptions=env[key];if(!isNodeOptionsEnvKey(key)||nodeOptions===void 0)continue;const kept=nodeOptionsWithoutInspectFlags(nodeOptions);if(kept===nodeOptions)continue;if(kept!=="")env[key]=kept;else delete env[key]}return{command:process.execPath,args:[...workerExecArgv(process.execArgv),cliEntry,"managed-runtime-worker"],env}}__name(currentCliWorkerLaunch,"currentCliWorkerLaunch");var ManagedSessionRuntimeWorker=class{constructor(sessionId,directory,launch=currentCliWorkerLaunch,cancelSettleTimeoutMs=CANCEL_SETTLE_TIMEOUT_MS,options={}){this.sessionId=sessionId;this.directory=directory;this.launch=launch;this.cancelSettleTimeoutMs=cancelSettleTimeoutMs;this.options=options}static{__name(this,"ManagedSessionRuntimeWorker")}registry=new ProcessRegistry;starting;closed=false;ledgerPaths=new Set;async execute(toolName,input,signal,callId=randomUUID()){signal.throwIfAborted();const worker=await this.ensureStarted(signal);if(worker===void 0){return{executionStatus:"cancelled",responseParts:[]}}return this.executeIn(worker,toolName,JSON.parse(JSON.stringify(input)),signal,this.referenceFor(callId,input))}async ensureStarted(signal){signal.throwIfAborted();let stopWatching=__name(()=>{},"stopWatching");const cancelled=new Promise(resolve=>{const onAbort=__name(()=>resolve(void 0),"onAbort");signal.addEventListener("abort",onAbort,{once:true});stopWatching=__name(()=>signal.removeEventListener("abort",onAbort),"stopWatching")});let worker;try{worker=await Promise.race([this.start(),cancelled])}catch(error){if(this.closed){throw new Error("The Managed session is closing.",{cause:error})}throw error}finally{stopWatching()}if(this.closed)throw new Error("The Managed session is closing.");if(worker===void 0||signal.aborted)return void 0;return worker}async executeIn(worker,toolName,input,signal,reference){signal.throwIfAborted();let settled=false;let cancelling;const giveUp=new AbortController;const ended=new AbortController;let giveUpTimer;const cancel=__name(()=>{giveUpTimer=setTimeout(()=>giveUp.abort(),this.cancelSettleTimeoutMs);cancelling=(async()=>{while(!ended.signal.aborted&&!giveUp.signal.aborted){const answer=await this.request(worker,"cancel",{protocolVersion:2,reference}).catch(()=>void 0);if(answer?.body?.state!=="unknown"){return}await new Promise(resolve=>setTimeout(resolve,STATUS_POLL_MS))}})()},"cancel");signal.addEventListener("abort",cancel,{once:true});try{let response;try{response=await this.request(worker,"execute",{protocolVersion:2,reference,toolName,input},giveUp.signal)}catch(error){if(!(error instanceof WorkerTransportError))throw error;if(error.undelivered){this.forget(worker);settled=true;return{executionStatus:"not_started",responseParts:[],error:{message:"The Runtime worker was not running."}}}await exitOrTimeout(worker.gone,EXIT_GRACE_MS)}if(response?.status===200){const result2=settledResult(response.body);if(result2){settled=true;return result2}}else if(response!==void 0&&response.status>=400&&response.status<500){settled=true;return{executionStatus:"not_started",responseParts:[],error:{message:refusalMessage(response.body)}}}const result=await this.awaitSettlement(worker,reference,giveUp.signal);settled=true;return result}finally{ended.abort();signal.removeEventListener("abort",cancel);clearTimeout(giveUpTimer);if(!settled)await cancelling}}referenceFor(callId,params){const normalized=JSON.parse(JSON.stringify(params));return{sessionId:this.sessionId,promptId:promptIdContext.getStore()??"unknown",callId,argsDigest:`sha256:${managedToolDigest(normalized)}`}}async acknowledge(reference){let worker;try{worker=this.starting!==void 0?await this.starting:void 0}catch{return}if(worker===void 0||this.closed)return;try{await this.request(worker,"acknowledge",{protocolVersion:2,reference})}catch{}}async close(){this.closed=true;const failures=[];try{await this.registry.shutdown()}catch(error){const parts=error instanceof AggregateError?error.errors:[error];failures.push(...parts.filter(part=>!(part instanceof ProcessExitError)))}for(const ledgerPath of[...this.ledgerPaths]){const armedReason=this.unprovenLedgerPaths.get(ledgerPath);if(armedReason!==void 0){failures.push(armedReason);continue}try{await this.sweepLedgerOnce(ledgerPath)}catch(error){failures.push(toRuntimeError(error))}}if(failures.length>0){throw new AggregateError(failures,"The Runtime worker did not stop.")}}unprovenLedgerPaths=new Map;reportUnproven(ledgerPath,reason){if(this.unprovenLedgerPaths.has(ledgerPath))return;this.unprovenLedgerPaths.set(ledgerPath,reason);this.options.quarantine?.report(reason);let lastNamed=unprovenGroupsOf(reason);let sawRetired=sweepRetiredLedger(reason);startLedgerReaper(async()=>{let verdict;try{verdict=await sweepWorkerLedger(ledgerPath)}catch(error){sawRetired=sawRetired||sweepRetiredLedger(error);lastNamed=[...new Set([...lastNamed,...unprovenGroupsOf(error)])];throw error}if(verdict==="proven")return"proven";const alive=lastNamed.filter(pgid=>processGroupLiveness(pgid)!=="gone");if(alive.length===0){return sawRetired||lastNamed.length===0?"terminal":"proven"}lastNamed=alive;return"unproven"},()=>{this.unprovenLedgerPaths.delete(ledgerPath);this.options.quarantine?.lift(reason)})}sweepsInFlight=new Map;async sweepLedgerOnce(ledgerPath){const inFlight=this.sweepsInFlight.get(ledgerPath);if(inFlight!==void 0)return inFlight;const promise=(async()=>{try{await sweepWorkerLedger(ledgerPath,{exitWitnessed:true})}catch(error){this.reportUnproven(ledgerPath,toRuntimeError(error));throw error}})();this.sweepsInFlight.set(ledgerPath,promise);try{await promise}finally{if(this.sweepsInFlight.get(ledgerPath)===promise){this.sweepsInFlight.delete(ledgerPath)}}}async sweepDeadWorkerLedger(worker){if(!worker.ledgerPath)return;await this.sweepLedgerOnce(worker.ledgerPath).catch(()=>void 0)}async awaitSettlement(worker,reference,giveUp){while(true){if(worker.gone.aborted||this.closed){throw new ManagedRuntimeOutcomeUnknownError("The Runtime worker exited during a tool call.")}const lastLook=giveUp.aborted;let response;try{response=await this.request(worker,"status",{protocolVersion:2,reference})}catch(error){throw new ManagedRuntimeOutcomeUnknownError("The Runtime worker stopped answering for a tool call.",{cause:error})}const body=response.body;if(response.status!==200||body?.state==="unknown"){throw new ManagedRuntimeOutcomeUnknownError("The Runtime worker does not know how a tool call ended.")}const result=settledResult(response.body);if(result)return result;if(lastLook){throw new ManagedRuntimeOutcomeUnknownError("A cancelled Runtime tool call did not settle.")}await new Promise(resolve=>setTimeout(resolve,STATUS_POLL_MS))}}start(){if(this.closed){return Promise.reject(new Error("The Managed session is closing."))}if(this.starting)return this.starting;const starting=this.launchWorker();this.starting=starting;const forget=__name(()=>{if(this.starting===starting&&!this.closed)this.starting=void 0},"forget");void starting.then(worker=>worker.tracked.exited.then(()=>this.sweepAfterExit(worker)),forget);return starting}sweepAfterExit(worker){void this.sweepDeadWorkerLedger(worker);void this.starting?.then(current=>{if(current===worker&&!this.closed)this.starting=void 0},()=>void 0)}forget(worker){void this.starting?.then(current=>{if(current===worker&&!this.closed)this.starting=void 0},()=>void 0);void worker.tracked.terminate().catch(()=>void 0)}async launchWorker(){const boot={type:"boot",version:1,token:randomBytes(32).toString("hex"),runtimeInstanceId:this.sessionId,runtimeIncarnation:randomUUID(),leaseId:randomUUID(),epoch:1,provisionRequestId:randomUUID(),tenantId:"local",workspaceId:"local",workspaceGeneration:"1",workspaceCwd:this.directory,capabilityDigest:LOCAL_CAPABILITY_DIGEST,isolationClass:"session"};const{MANAGED_RUNTIME_INCARNATION_HEADER,OWNED_MANAGED_RUNTIME_ROUTES}=await import("./managed-runtime-attestation-contract-FUULB2VI.js");const routes=new Map(OWNED_MANAGED_RUNTIME_ROUTES.map(route=>[route.key,route.path]));const launch=this.launch();const ledgerPath=this.options.ledgerDir?path.join(this.options.ledgerDir,`${boot.runtimeIncarnation}.json`):void 0;if(ledgerPath!==void 0){ensureLedgerDirectory(path.dirname(ledgerPath));this.ledgerPaths.add(ledgerPath);launchedLedgerPaths.add(ledgerPath)}const reservation=this.registry.reserve();let child;try{child=spawn(launch.command,[...launch.args],{cwd:this.directory,env:ledgerPath===void 0?launch.env??process.env:{...launch.env??process.env,[MANAGED_RUNTIME_LEDGER_ENV]:ledgerPath},stdio:["pipe","pipe","inherit","ipc"],detached:process.platform!=="win32",windowsHide:true})}catch(error){reservation.cancel();if(ledgerPath!==void 0)launchedLedgerPaths.delete(ledgerPath);throw error}const tracked=reservation.attach(child,{ownsProcessTree:true});const gone=new AbortController;void tracked.exited.then(()=>gone.abort(),()=>gone.abort());try{child.stdin.on("error",()=>void 0);child.stdin.end(JSON.stringify(boot));const ready=await readReady(child.stdout,tracked);if(ready.type!=="ready"||ready.version!==1||ready.runtimeInstanceId!==boot.runtimeInstanceId||ready.runtimeIncarnation!==boot.runtimeIncarnation||ready.leaseId!==boot.leaseId||ready.epoch!==boot.epoch||typeof ready.url!=="string"||!/^http:\/\/127\.0\.0\.1:\d+$/u.test(ready.url)){throw new Error("The Managed Runtime worker is not the one started.")}const worker={tracked,url:new URL(ready.url),boot,routes,incarnationHeader:MANAGED_RUNTIME_INCARNATION_HEADER.toLowerCase(),gone:gone.signal,ledgerPath};const attested=await this.request(worker,"attest",{protocolVersion:2,provisionRequestId:boot.provisionRequestId,tenantId:boot.tenantId,workspaceId:boot.workspaceId,workspaceGeneration:boot.workspaceGeneration,workspaceCwd:boot.workspaceCwd,capabilityDigest:boot.capabilityDigest,isolationClass:boot.isolationClass});const identity=attested.body;if(attested.status!==200||identity?.["runtimeIncarnation"]!==boot.runtimeIncarnation||identity?.["leaseId"]!==boot.leaseId){throw new Error("The Managed Runtime worker failed attestation.")}return worker}catch(error){await tracked.terminate().catch(()=>void 0);if(ledgerPath!==void 0){launchedLedgerPaths.delete(ledgerPath);void this.sweepLedgerOnce(ledgerPath).catch(()=>void 0)}throw error}}request(worker,route,body,stop){if(worker.gone.aborted){return Promise.reject(new WorkerTransportError("The Runtime worker exited.",void 0,true))}const payload=Buffer.from(JSON.stringify(body));return new Promise((resolve,reject)=>{const request=http.request({host:worker.url.hostname,port:worker.url.port,path:worker.routes.get(route),method:"POST",agent:false,headers:{Authorization:`Bearer ${worker.boot.token}`,"Cache-Control":"no-store","Content-Type":"application/json","Content-Length":payload.byteLength,"X-Qwen-Managed-Lease-Id":worker.boot.leaseId,"X-Qwen-Managed-Lease-Epoch":String(worker.boot.epoch)}},response=>{if(route!=="attest"&&response.statusCode===200&&response.headers[worker.incarnationHeader]!==worker.boot.runtimeIncarnation){reject(new WorkerTransportError("The Runtime worker did not answer as itself."));request.destroy();return}const chunks=[];let size=0;response.on("data",chunk=>{size+=chunk.byteLength;if(size>MANAGED_RUNTIME_RESPONSE_LIMIT_BYTES){response.destroy(new WorkerTransportError("Runtime worker response is too large."));return}chunks.push(chunk)});response.on("error",error=>reject(new WorkerTransportError(error.message,{cause:error})));response.on("end",()=>{let parsed;try{const text=Buffer.concat(chunks).toString("utf8");parsed=text.length>0?JSON.parse(text):void 0}catch(error){reject(new WorkerTransportError("Runtime worker response is invalid.",{cause:error}));return}resolve({status:response.statusCode??0,body:parsed})})});request.on("error",error=>reject(new WorkerTransportError(error.message,{cause:error})));const exited=__name(()=>request.destroy(new WorkerTransportError("The Runtime worker exited.")),"exited");worker.gone.addEventListener("abort",exited,{once:true});request.on("close",()=>worker.gone.removeEventListener("abort",exited));if(stop){const abandon=__name(()=>request.destroy(new WorkerTransportError("Abandoned the request.")),"abandon");if(stop.aborted)abandon();else stop.addEventListener("abort",abandon,{once:true});request.on("close",()=>stop.removeEventListener("abort",abandon))}else{request.setTimeout(CONTROL_REQUEST_TIMEOUT_MS,()=>request.destroy(new WorkerTransportError("The request timed out.")))}request.end(payload)})}};function isWithin(root,candidate){const relative=path.relative(path.resolve(root),path.resolve(root,candidate));return relative!==".."&&!relative.startsWith(`..${path.sep}`)&&!path.isAbsolute(relative)}__name(isWithin,"isWithin");function exitOrTimeout(gone,ms){if(gone.aborted)return Promise.resolve();return new Promise(resolve=>{const done=__name(()=>{clearTimeout(timer);gone.removeEventListener("abort",done);resolve()},"done");const timer=setTimeout(done,ms);gone.addEventListener("abort",done,{once:true})})}__name(exitOrTimeout,"exitOrTimeout");function readReady(stdout,tracked){const lines=createInterface({input:stdout,crlfDelay:Infinity});return new Promise((resolve,reject)=>{let settled=false;const finish=__name((error,ready)=>{if(settled)return;settled=true;clearTimeout(timer);if(error)reject(error);else resolve(ready)},"finish");const timer=setTimeout(()=>finish(new Error("The Managed Runtime worker did not get ready.")),READY_TIMEOUT_MS);timer.unref();lines.on("line",line=>{if(settled)return;try{finish(void 0,JSON.parse(line))}catch{finish(new Error("The Managed Runtime worker is not ready."))}});void tracked.exited.then(()=>finish(new Error("The Managed Runtime worker exited before it was ready.")))})}__name(readReady,"readReady");function toRuntimeError(error){return error instanceof Error?error:new Error(String(error))}__name(toRuntimeError,"toRuntimeError");function settledResult(body){const view=body;return view?.state==="settled"&&view.result?view.result:void 0}__name(settledResult,"settledResult");function refusalMessage(body){const error=body?.error;return typeof error==="string"?error:"The Runtime worker refused the tool call."}__name(refusalMessage,"refusalMessage");function toToolResult(payload){const parts=managedToolResponseParts(payload.responseParts);const text=parts.map(part=>part.text).filter(value=>typeof value==="string").join("\n");if(payload.executionStatus==="success"){return{llmContent:parts,returnDisplay:text}}const message=managedToolFailureMessage(payload);return{llmContent:parts.length>0?parts:message,returnDisplay:text||message,error:{message,...payload.error?.type?{type:payload.error.type}:{}}}}__name(toToolResult,"toToolResult");var launchedLedgerPaths=new Set;var armedStaleSweeps=new Set;var dirSweepsInFlight=new Map;function sweepStaleRuntimeLedgers(ledgerDir,quarantine){if(dirSweepsInFlight.has(ledgerDir))return;const options={skip:launchedLedgerPaths};const sweeping=sweepStaleLedgers(ledgerDir,options).catch(error=>{if(armedStaleSweeps.has(ledgerDir))return;armedStaleSweeps.add(ledgerDir);const reason=toRuntimeError(error);quarantine.report(reason);let sawRetired=sweepRetiredLedger(error);const armedFiles=new Set(workFilesOf(error));const namedByFile=new Map;const recordNames=__name(failure=>{const failures=failure instanceof AggregateError?failure.errors:[failure];for(const each of failures){if(each instanceof LedgerSweepUnprovenError&&each.remaining.length>0){const named=namedByFile.get(each.workFile)??new Set;for(const pgid of each.remaining)named.add(pgid);namedByFile.set(each.workFile,named)}}},"recordNames");recordNames(error);const provenFiles=new Set;startLedgerReaper(async()=>{const judged=new Set;try{await sweepStaleLedgers(ledgerDir,options,workFile=>{judged.add(workFile);provenFiles.add(workFile)})}catch(retryError){sawRetired=sawRetired||sweepRetiredLedger(retryError);recordNames(retryError);for(const workFile of workFilesOf(retryError)){armedFiles.add(workFile)}throw retryError}const vanished=[];for(const workFile of armedFiles){if(provenFiles.has(workFile)||judged.has(workFile))continue;if(!existsSync(workFile)){vanished.push(workFile);continue}return"unproven"}if(vanished.length===0)return"proven";let namedAlive=0;let unevidenced=false;for(const workFile of vanished){const named=namedByFile.get(workFile);if(named===void 0){unevidenced=true;continue}const alive=[...named].filter(pgid=>processGroupLiveness(pgid)!=="gone");namedByFile.set(workFile,new Set(alive));namedAlive+=alive.length}if(namedAlive>0)return"unproven";return unevidenced||sawRetired?"terminal":"proven"},()=>{armedStaleSweeps.delete(ledgerDir);quarantine.lift(reason)})});dirSweepsInFlight.set(ledgerDir,sweeping);void sweeping.finally(()=>{if(dirSweepsInFlight.get(ledgerDir)===sweeping){dirSweepsInFlight.delete(ledgerDir)}})}__name(sweepStaleRuntimeLedgers,"sweepStaleRuntimeLedgers");function workFilesOf(error){const failures=error instanceof AggregateError?error.errors:[error];return failures.flatMap(failure=>failure instanceof LedgerSweepUnprovenError||failure instanceof LedgerSweepRetiredError?[failure.workFile]:[])}__name(workFilesOf,"workFilesOf");function unprovenGroupsOf(error){const failures=error instanceof AggregateError?error.errors:[error];return[...new Set(failures.flatMap(failure=>failure instanceof LedgerSweepUnprovenError?[...failure.remaining]:[]))]}__name(unprovenGroupsOf,"unprovenGroupsOf");function sweepRetiredLedger(error){const failures=error instanceof AggregateError?error.errors:[error];return failures.some(failure=>failure instanceof LedgerSweepRetiredError)}__name(sweepRetiredLedger,"sweepRetiredLedger");function createManagedRuntimeEnvironment(config,launch){const sessionDirectory=config.getTargetDir();const ledgerDir=path.join(config.storage.getProjectTempDir(),"managed-runtime");const quarantine={report:__name(reason=>config.reportManagedEngineQuarantine(reason),"report"),lift:__name(reason=>config.clearManagedEngineQuarantine(reason),"lift")};try{ensureLedgerDirectory(ledgerDir)}catch{}sweepStaleRuntimeLedgers(ledgerDir,quarantine);const worker=new ManagedSessionRuntimeWorker(config.getSessionId(),sessionDirectory,launch,CANCEL_SETTLE_TIMEOUT_MS,{ledgerDir,quarantine});const prepared=new LocalExecutionEnvironment(config,{toolNames:MANAGED_RUNTIME_TOOL_NAMES,run:__name(async(call,signal)=>{const outcomes=config.getManagedRuntimeOutcomes();if(!outcomes){throw new Error("This Managed session records no log.")}const started=await worker.ensureStarted(signal);if(!started){return toToolResult({executionStatus:"cancelled",responseParts:[]})}const params=JSON.parse(JSON.stringify(call.params));const promptId=promptIdContext.getStore()??"unknown";const callId=call.callId??call.id;await outcomes.admit({functionCallId:callId,toolName:call.toolName,promptId,params,toolDefinition:prepared.toolDefinition(call.toolName),workerIncarnation:started.boot.runtimeIncarnation});const settleCall=__name(async outcome=>{try{await outcomes.settle({functionCallId:callId,executionStatus:outcome.executionStatus,payload:outcome})}catch(error){if(outcomes.hasCommittedReceipt(callId))return;const blocked=new ManagedRuntimeOutcomeUnknownError("The durable settlement of a Runtime tool call failed.",{cause:error});config.blockManagedSession(blocked);await worker.close().catch(()=>void 0);throw blocked}},"settleCall");if(signal.aborted){const payload2={executionStatus:"cancelled",responseParts:[],error:{message:managedToolFailureMessage({executionStatus:"cancelled"})}};await settleCall(payload2);return toToolResult(payload2)}const reference=worker.referenceFor(callId,params);let payload;try{payload=await worker.executeIn(started,call.toolName,params,signal,reference)}catch(error){if(error instanceof ManagedRuntimeOutcomeUnknownError){config.blockManagedSession(error);await worker.close().catch(()=>void 0)}throw error}await settleCall(payload);void worker.acknowledge(reference);const result=toToolResult(payload);return call.toolName===ToolNames.READ_FILE&&!result.error?{...result,returnDisplay:""}:result},"run")});return{toolNames:prepared.toolNames,prepare:__name(async(request,signal)=>{const preparation=await prepared.prepare(request,signal);if(request.toolName===ToolNames.SHELL){const directory=preparation.params["directory"];const refusal=preparation.params["is_background"]===true?"A Managed session runs shell commands in the foreground only.":typeof directory==="string"&&directory!==""&&!isWithin(sessionDirectory,directory)?`A Managed session runs shell commands only in ${sessionDirectory}.`:void 0;if(refusal){await prepared.release(request.id,signal);throw new Error(refusal)}}return preparation},"prepare"),permission:__name((id,signal)=>prepared.permission(id,signal),"permission"),confirmation:__name((id,signal)=>prepared.confirmation(id,signal),"confirmation"),confirm:__name((id,outcome,payload,signal)=>prepared.confirm(id,outcome,payload,signal),"confirm"),execute:__name((id,signal,updateOutput)=>prepared.execute(id,signal,updateOutput),"execute"),modificationContent:__name((toolName,params,signal)=>prepared.modificationContent(toolName,params,signal),"modificationContent"),release:__name((id,signal)=>prepared.release(id,signal),"release"),invalidateReadCache:__name(()=>Promise.resolve(),"invalidateReadCache"),dispose:__name(async()=>{try{await prepared.dispose()}finally{await worker.close()}},"dispose")}}__name(createManagedRuntimeEnvironment,"createManagedRuntimeEnvironment");export{MANAGED_RUNTIME_RESPONSE_LIMIT_BYTES,ManagedSessionRuntimeWorker,createManagedRuntimeEnvironment,currentCliWorkerLaunch,nodeOptionsWithoutInspectFlags,toToolResult,workerExecArgv};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2026 Qwen Team
|
package/chunks/{managed-runtime-ssh-worker-4N7EMRSV.js → managed-runtime-ssh-worker-HU4CIJRK.js}
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{SSH_RETIRE_PATH,readSshPrivateJson,readSshRuntimeRecord,sshCleanProof,sshResourcePath,verifySshStorage,writeSshPrivateJson}from"./chunk-
|
|
3
|
+
import{SSH_RETIRE_PATH,readSshPrivateJson,readSshRuntimeRecord,sshCleanProof,sshResourcePath,verifySshStorage,writeSshPrivateJson}from"./chunk-RXK6XD6F.js";import"./chunk-36TKFM4Z.js";import"./chunk-YJ6APXNB.js";import{ManagedRuntimeLedger}from"./chunk-6QU44IVK.js";import{authorizeManagedRuntime,managedRuntimeJsonBody,managedRuntimeNoStore,nameManagedRuntimeIncarnation}from"./chunk-XLCTS6G3.js";import"./chunk-6SOKP7IN.js";import"./chunk-ELUOCI74.js";import"./chunk-IS7CHVXD.js";import{getCliVersion}from"./chunk-6ZEMLEK2.js";import"./chunk-O4EDHV64.js";import"./chunk-PHIPLV2I.js";import"./chunk-LG4NL2M7.js";import"./chunk-JAUJI56S.js";import"./chunk-I4H7NUVP.js";import"./chunk-EPODBRBP.js";import"./chunk-OKN3Z5C5.js";import"./chunk-XYB7GC5U.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();import path from"node:path";import{access}from"node:fs/promises";var ManagedSshRuntime=class{constructor(record,ledger){this.record=record;this.ledger=ledger;this.finished=new Promise(resolve=>{this.finish=resolve})}static{__name(this,"ManagedSshRuntime")}route={method:"POST",path:SSH_RETIRE_PATH};finished;finish;retirement;verifyStorage(){return verifySshStorage(this.record.identity,this.record.marker)}register(app,boot,executor){app.post(this.route.path,managedRuntimeNoStore,authorizeManagedRuntime(boot),nameManagedRuntimeIncarnation(boot),managedRuntimeJsonBody(16*1024),async(req,res)=>{try{const body=req.body;if(!body||typeof body!=="object"||Array.isArray(body))throw new Error("Invalid retirement.");const request=body;if(Object.keys(request).length!==3||request["protocolVersion"]!==1||request["resourceId"]!==this.record.resourceId||typeof request["retirementId"]!=="string")throw new Error("Invalid retirement.");const retirementId=request["retirementId"];const directory=sshResourcePath(this.record);const stop=await readSshPrivateJson(path.join(directory,"stop.json"));if(JSON.stringify(stop)!==JSON.stringify({retirementId}))throw new Error("Retirement claim conflicts.");await this.verifyStorage();executor.sealAdmission(retirementId);this.retirement??=(async()=>{await executor.retireSsh(retirementId);await this.verifyStorage();const proof2=sshCleanProof(this.record,retirementId,new Date().toISOString());await writeSshPrivateJson(path.join(directory,"clean.json"),proof2);return proof2})().catch(error=>{this.retirement=void 0;throw error});const proof=await this.retirement;res.once("finish",this.finish);res.once("close",this.finish);res.json({protocolVersion:1,ok:true,result:{cleanProof:proof}})}catch{res.status(409).json({protocolVersion:1,ok:false,error:{code:"ssh_runtime_retirement_unverified",message:"Original Runtime retirement is unverified.",retryable:true}})}})}};async function runManagedRuntimeBootstrapWorker(directory){const record=await readSshRuntimeRecord(directory);if(record.expectedQwenVersion!==await getCliVersion())throw new Error("Pinned Qwen version changed before Runtime startup.");await verifySshStorage(record.identity,record.marker);await writeSshPrivateJson(path.join(directory,"pid.json"),{pid:process.pid});const closing=__name(async()=>{try{await access(path.join(directory,"stop.json"));return true}catch(error){if(error.code==="ENOENT")return false;throw error}},"closing");if(await closing())throw new Error("Runtime startup was fenced by retirement.");for(const key of Object.keys(process.env)){if(key.startsWith("QWEN_MANAGED_")||key==="NODE_OPTIONS"||key==="NODE_PATH")delete process.env[key]}const ledger=ManagedRuntimeLedger.create({workFile:path.join(directory,"shell-ledger.json"),worker:{pid:process.pid,pgid:process.pid,incarnation:record.boot.runtimeIncarnation,startedAt:Date.now(),uptimeMs:(await import("node:os")).uptime()*1e3}});ledger.watch();const runtime=new ManagedSshRuntime(record,ledger);const{startManagedRuntimeAttestationWorker}=await import("./managed-runtime-attestation-worker-BQP4E7LQ.js");const{ManagedShellPublisherRegistry}=await import("./managed-shell-publisher-JLAES2XP.js");const worker=await startManagedRuntimeAttestationWorker(record.boot,void 0,new ManagedShellPublisherRegistry,false,runtime);if(await closing()){await worker.close();throw new Error("Runtime startup was fenced by retirement.")}await writeSshPrivateJson(path.join(directory,"ready.json"),worker.ready);const interrupted=new Promise(resolve=>{process.once("SIGINT",resolve);process.once("SIGTERM",resolve)});await Promise.race([runtime.finished,interrupted]);await worker.close()}__name(runManagedRuntimeBootstrapWorker,"runManagedRuntimeBootstrapWorker");export{ManagedSshRuntime,runManagedRuntimeBootstrapWorker};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2026 Qwen Team
|