gerege-cli 0.26.6 → 0.26.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/chunks/{MaxSizedBox-QCIXIS4P.js → MaxSizedBox-LSNOJEKM.js} +1 -1
- package/chunks/{StandaloneSessionPicker-BAFAIRT7.js → StandaloneSessionPicker-KSYGPMEV.js} +1 -1
- package/chunks/{acp-subagent-executor-TPVXURLW.js → acp-subagent-executor-NSW2MFUI.js} +1 -1
- package/chunks/{acpAgent-67UN66PB.js → acpAgent-3DTOHTDM.js} +3 -3
- package/chunks/{advisor-SAXMI4QZ.js → advisor-7JGQPS7X.js} +1 -1
- package/chunks/{agent-KV7BXY6C.js → agent-PNKQJGDO.js} +1 -1
- package/chunks/{agent-headless-FQX3JGG6.js → agent-headless-7D33X7QQ.js} +1 -1
- package/chunks/{agent-host-client-L5EHC4AC.js → agent-host-client-3R2MAUVE.js} +1 -1
- package/chunks/{agent-host-connections-EDBMCVQF.js → agent-host-connections-2D7DECAE.js} +1 -1
- package/chunks/{anthropicContentGenerator-V7TX2NXP.js → anthropicContentGenerator-MGTJJGEQ.js} +1 -1
- package/chunks/{autofix-pr-WP34NYHL.js → autofix-pr-OIHHZSPQ.js} +1 -1
- package/chunks/{batch-XFVQ4BLM.js → batch-6UDAMPAA.js} +1 -1
- package/chunks/{bridge-AE7AFEXB.js → bridge-QXVXPNJ6.js} +1 -1
- package/chunks/{channel-settings-store-X63P5OVT.js → channel-settings-store-P4W4R5SJ.js} +1 -1
- package/chunks/{chunk-RXN7DUMP.js → chunk-2J2BQ3PL.js} +2 -2
- package/chunks/{chunk-7453BHJO.js → chunk-2LMSDH6P.js} +1 -1
- package/chunks/{chunk-32XHDDIA.js → chunk-3EZ5GCUT.js} +1 -1
- package/chunks/{chunk-AYVCT5FF.js → chunk-3ICJI5KW.js} +1 -1
- package/chunks/{chunk-VRKYBH5G.js → chunk-4A663FE6.js} +5 -5
- package/chunks/{chunk-DA6LOBSB.js → chunk-4AKTP4MM.js} +1 -1
- package/chunks/{chunk-T53VMDXH.js → chunk-4LC4INFI.js} +1 -1
- package/chunks/{chunk-65ME4BOH.js → chunk-4QOVM2LL.js} +1 -1
- package/chunks/{chunk-MYV7GY3H.js → chunk-4VR4DUUD.js} +1 -1
- package/chunks/{chunk-GRAECADD.js → chunk-4W27Z3OL.js} +1 -1
- package/chunks/{chunk-B37YY4XU.js → chunk-53IB4U4E.js} +1 -1
- package/chunks/{chunk-OK7LBM5G.js → chunk-5R2JIZID.js} +1 -1
- package/chunks/{chunk-I6PUY2T3.js → chunk-5TWAP4OG.js} +1 -1
- package/chunks/{chunk-CBE6ZIHU.js → chunk-6JAXAFX7.js} +1 -1
- package/chunks/{chunk-OOJ2AQT3.js → chunk-6WV5RKYB.js} +1 -1
- package/chunks/{chunk-ELDZ4MNL.js → chunk-6YFNUVJR.js} +1 -1
- package/chunks/{chunk-3W32X2DH.js → chunk-7HFFTOAD.js} +1 -1
- package/chunks/{chunk-YH2XRWRF.js → chunk-ATTJQLQV.js} +1 -1
- package/chunks/{chunk-T5DKF33F.js → chunk-BIPPD7W6.js} +1 -1
- package/chunks/{chunk-CF6SZJNP.js → chunk-BVV7UXES.js} +1 -1
- package/chunks/{chunk-CGDFZEER.js → chunk-BY46PCWY.js} +1 -1
- package/chunks/{chunk-AEZYXPFS.js → chunk-CDKBM72V.js} +1 -1
- package/chunks/{chunk-OU7CEG7Q.js → chunk-CK3OKTTL.js} +1 -1
- package/chunks/{chunk-FKL3V5BO.js → chunk-DEJ47KJE.js} +1 -1
- package/chunks/{chunk-FEP6W4NJ.js → chunk-DQQN2HOP.js} +1 -1
- package/chunks/{chunk-SKGJ26HQ.js → chunk-DTX2OVQW.js} +1 -1
- package/chunks/{chunk-EXIFPXMB.js → chunk-DVUKYOCJ.js} +1 -1
- package/chunks/{chunk-FKZ46GKL.js → chunk-E3KWSRJN.js} +1 -1
- package/chunks/{chunk-BAUMVH4Q.js → chunk-EEPNACXJ.js} +1 -1
- package/chunks/{chunk-76FSYQTG.js → chunk-F5SLLEJY.js} +1 -1
- package/chunks/{chunk-IZ5MWA6E.js → chunk-F7622ZRQ.js} +1 -1
- package/chunks/{chunk-TB4AUC2L.js → chunk-FKUDVIME.js} +1 -1
- package/chunks/{chunk-SP6CQ3MO.js → chunk-FRVXSKL4.js} +1 -1
- package/chunks/{chunk-XISR37DQ.js → chunk-FTF2NFLB.js} +1 -1
- package/chunks/{chunk-NONBHCXP.js → chunk-G4MWPXNY.js} +1 -1
- package/chunks/{chunk-JRTOPEM3.js → chunk-GA35LMSX.js} +1 -1
- package/chunks/{chunk-GHIFIXNX.js → chunk-H34KVVI4.js} +1 -1
- package/chunks/{chunk-AFO5ER23.js → chunk-H5EXNXGW.js} +1 -1
- package/chunks/{chunk-ZENMAISJ.js → chunk-HJLRKM3W.js} +1 -1
- package/chunks/{chunk-BCI62WSL.js → chunk-HVP4UF2Q.js} +1 -1
- package/chunks/{chunk-AEKEZRIU.js → chunk-HXTYFGSQ.js} +1 -1
- package/chunks/{chunk-KJGRCIVY.js → chunk-IIHUDJX7.js} +1 -1
- package/chunks/{chunk-RSLTOIG5.js → chunk-IQMKQKKD.js} +2 -2
- package/chunks/{chunk-JWNKPINR.js → chunk-ISQMHOCC.js} +1 -1
- package/chunks/{chunk-OJ4K62S2.js → chunk-IY7M5HKF.js} +1 -1
- package/chunks/{chunk-LBLLWAKK.js → chunk-IZXHCHJD.js} +1 -1
- package/chunks/{chunk-NVOI6UDQ.js → chunk-JHC22BZH.js} +1 -1
- package/chunks/{chunk-BPFFRPWE.js → chunk-K7GN4CMV.js} +6 -6
- package/chunks/{chunk-N7PWZBXV.js → chunk-L7LO3YRT.js} +1 -1
- package/chunks/{chunk-MGATL4OA.js → chunk-LY4XTBL4.js} +1 -1
- package/chunks/{chunk-JEDL4IKF.js → chunk-LYFRGP42.js} +1 -1
- package/chunks/{chunk-G6DALGGS.js → chunk-MDCA4I63.js} +1 -1
- package/chunks/{chunk-W5Z4BWWA.js → chunk-MS2XCBPP.js} +1 -1
- package/chunks/{chunk-GBSRWT7J.js → chunk-MXZXQUVP.js} +1 -1
- package/chunks/{chunk-VD2GSW64.js → chunk-N4ZQC5HB.js} +1 -1
- package/chunks/{chunk-2LWJGXTW.js → chunk-N6EFYQ7M.js} +1 -1
- package/chunks/{chunk-P62S5JGM.js → chunk-NHPKD7LY.js} +1 -1
- package/chunks/{chunk-W66WWTOP.js → chunk-NPAENNRO.js} +1 -1
- package/chunks/{chunk-EYPLBTMI.js → chunk-NYBYDW6R.js} +1 -1
- package/chunks/{chunk-7RNOS7R4.js → chunk-O3TUZQP4.js} +1 -1
- package/chunks/{chunk-JH3V5SPA.js → chunk-OZFZBGZG.js} +1 -1
- package/chunks/{chunk-QDCUR3JB.js → chunk-P2MZZMCS.js} +1 -1
- package/chunks/{chunk-KZNYALFU.js → chunk-PMBI46K4.js} +1 -1
- package/chunks/{chunk-2TAJ5STJ.js → chunk-Q5RRVBTY.js} +1 -1
- package/chunks/{chunk-H3IR3GIE.js → chunk-QHYSRPQR.js} +1 -1
- package/chunks/{chunk-NA4ZF2FE.js → chunk-QONPET6Y.js} +2 -2
- package/chunks/{chunk-W2RQIZ6B.js → chunk-QSPXKBUX.js} +1 -1
- package/chunks/{chunk-WGFX3EL3.js → chunk-QTKPC24L.js} +1 -1
- package/chunks/{chunk-BHIDG6VZ.js → chunk-QTVSPQZQ.js} +1 -1
- package/chunks/{chunk-HOG66S6K.js → chunk-QVHDM6N7.js} +1 -1
- package/chunks/{chunk-4NDJKNN6.js → chunk-RT6J7PV4.js} +1 -1
- package/chunks/{chunk-NEKPQLFY.js → chunk-RULGA7WE.js} +2 -2
- package/chunks/{chunk-LTE4N6L3.js → chunk-SAVYMUU3.js} +1 -1
- package/chunks/{chunk-2JGTWRZJ.js → chunk-T3CQ72HC.js} +6 -6
- package/chunks/{chunk-FYBJGRX7.js → chunk-U5YOAOU3.js} +1 -1
- package/chunks/{chunk-EFIRES46.js → chunk-ULLW2AYD.js} +1 -1
- package/chunks/{chunk-MPVQDYPH.js → chunk-UM5KBBYP.js} +1 -1
- package/chunks/{chunk-M6KB5RVD.js → chunk-UVMLWDRU.js} +1 -1
- package/chunks/{chunk-5EXL4TKQ.js → chunk-VK7LOUOJ.js} +1 -1
- package/chunks/{chunk-T2YTHAJW.js → chunk-VUNHJ74J.js} +1 -1
- package/chunks/{chunk-HTAUIJB4.js → chunk-W2CV36HT.js} +1 -1
- package/chunks/{chunk-ET5M5WFN.js → chunk-WCI33URB.js} +1 -1
- package/chunks/{chunk-P3JEEDQZ.js → chunk-WEPC42YR.js} +1 -1
- package/chunks/{chunk-BQZF3UKI.js → chunk-WF7Q3ZSQ.js} +1 -1
- package/chunks/{chunk-GSPGIGO5.js → chunk-WK666FGZ.js} +3 -3
- package/chunks/{chunk-CUP2TNJK.js → chunk-WMLYHZZX.js} +1 -1
- package/chunks/{chunk-2N3NBTYJ.js → chunk-WSI4G7XC.js} +1 -1
- package/chunks/{chunk-U3Q72OGV.js → chunk-WXK7Z45R.js} +1 -1
- package/chunks/{chunk-MTDBCIDA.js → chunk-YWK3E4WJ.js} +1 -1
- package/chunks/{chunk-34HC2AXI.js → chunk-YY4GWNTU.js} +2 -2
- package/chunks/{chunk-UKLXKJKL.js → chunk-ZFOEVHWG.js} +1 -1
- package/chunks/{codex-subagent-executor-OLMGVPVS.js → codex-subagent-executor-GPTKVP7H.js} +1 -1
- package/chunks/{config-utils-OWY5G5Y2.js → config-utils-6B5FHBSF.js} +1 -1
- package/chunks/{contextCommand-IXFUZH65.js → contextCommand-FGRDE3GA.js} +1 -1
- package/chunks/{core-runtime-O4LC4NY3.js → core-runtime-OFEHSKDB.js} +1 -1
- package/chunks/{create-sub-session-6F7C3TMT.js → create-sub-session-D2KEWVHQ.js} +1 -1
- package/chunks/{cron-create-2422NBSJ.js → cron-create-RFGGKTL7.js} +1 -1
- package/chunks/{daemon-git-worktree-guard-EWPQA6NO.js → daemon-git-worktree-guard-AV752IOZ.js} +1 -1
- package/chunks/{daemon-status-provider-FAHOXNFW.js → daemon-status-provider-GHQBRDMC.js} +1 -1
- package/chunks/{daemon-trust-policy-L3DM6AI5.js → daemon-trust-policy-24ENJNTQ.js} +1 -1
- package/chunks/{daemon-trust-policy-monitor-HNPY5KJ4.js → daemon-trust-policy-monitor-NMSQAGWV.js} +1 -1
- package/chunks/{deferred-core-runtime-JF42NQJK.js → deferred-core-runtime-5BAMFFOI.js} +1 -1
- package/chunks/{edit-E5LEI2LL.js → edit-XCECLEH3.js} +1 -1
- package/chunks/{enterPlanMode-3COTUV5V.js → enterPlanMode-SEN2PMRM.js} +1 -1
- package/chunks/{environment-XBBIB3VA.js → environment-CCPQJYKS.js} +1 -1
- package/chunks/{errors-LNMQ7TUK.js → errors-Y6HHUTGK.js} +1 -1
- package/chunks/{execution-tool-QDDKJD2K.js → execution-tool-HADWGMIG.js} +1 -1
- package/chunks/{execution-worker-TXGZRZXE.js → execution-worker-GZS7WOQL.js} +1 -1
- package/chunks/{exitPlanMode-Z7QEMWPE.js → exitPlanMode-76B5HDLT.js} +1 -1
- package/chunks/{fast-path-M6K2RACY.js → fast-path-OEV7LQYV.js} +1 -1
- package/chunks/{glob-N2QT4U7U.js → glob-NLWCQRMS.js} +1 -1
- package/chunks/{goal-tools-CUSQD3DG.js → goal-tools-43XV33BT.js} +1 -1
- package/chunks/{handleAutoUpdate-QF2YQHF6.js → handleAutoUpdate-JDQWGSSP.js} +1 -1
- package/chunks/{i18n-AGOA6MUI.js → i18n-JW6BVEGF.js} +1 -1
- package/chunks/{initializer-FRKYDUSX.js → initializer-UT6JLZ3O.js} +1 -1
- package/chunks/{installationInfo-OKA4WXAS.js → installationInfo-LKWDV3S2.js} +1 -1
- package/chunks/{interactive-mod-session-MWYN5IFK.js → interactive-mod-session-2KWKYVPC.js} +1 -1
- package/chunks/{list-DE7VUIR2.js → list-BKINK3S2.js} +1 -1
- package/chunks/{llm-N3JGJHYC.js → llm-3RWXAVM2.js} +4 -4
- package/chunks/{llm-content-generator-VMUBA7OJ.js → llm-content-generator-MDRBSH73.js} +1 -1
- package/chunks/{loadedSettingsAdapter-5C36OZ7N.js → loadedSettingsAdapter-WWJUKWUN.js} +1 -1
- package/chunks/{local-BE624O3A.js → local-TT4FLCTR.js} +1 -1
- package/chunks/{local-execution-environment-OPGM7Y6L.js → local-execution-environment-OBA6VWYL.js} +1 -1
- package/chunks/{loggingContentGenerator-2MHAI6JR.js → loggingContentGenerator-CK7IKYQH.js} +1 -1
- package/chunks/{loop-wakeup-BDLATBXH.js → loop-wakeup-4MSRX3DY.js} +1 -1
- package/chunks/{manage-memory-BBCEIIWB.js → manage-memory-PX5PZJKZ.js} +1 -1
- package/chunks/{managed-execution-engine-SRFALTCX.js → managed-execution-engine-WMAUR3ZK.js} +1 -1
- package/chunks/{managed-local-serve-ICNAS3E6.js → managed-local-serve-X7REHGB4.js} +1 -1
- package/chunks/{managed-npm-update-CTL6LH5Z.js → managed-npm-update-6HUVAJH7.js} +1 -1
- package/chunks/{managed-runtime-attestation-worker-ZRDWKXCI.js → managed-runtime-attestation-worker-F4AT53M5.js} +1 -1
- package/chunks/{managed-runtime-bootstrap-6NTGZXQL.js → managed-runtime-bootstrap-3BP5JRJX.js} +1 -1
- package/chunks/{managed-runtime-session-worker-RKQBBFR6.js → managed-runtime-session-worker-2PO7J5UK.js} +1 -1
- package/chunks/{managed-runtime-ssh-worker-FCGV6FSW.js → managed-runtime-ssh-worker-4N7EMRSV.js} +1 -1
- package/chunks/{managed-session-authority-C7IW6TJX.js → managed-session-authority-MYOYTUM2.js} +1 -1
- package/chunks/{mcp-VC4CJPE5.js → mcp-5OTEMZ7P.js} +1 -1
- package/chunks/{memory-S6OJA3ZD.js → memory-TNW7RSAV.js} +1 -1
- package/chunks/{model-call-collection-MJZWRQSU.js → model-call-collection-KNTWFZQS.js} +1 -1
- package/chunks/{model-configuration-SKU6L3QI.js → model-configuration-U5C5P5UQ.js} +1 -1
- package/chunks/{modelConfigUtils-TJCB6NXT.js → modelConfigUtils-R4KFI2WK.js} +1 -1
- package/chunks/{monitor-M3PNLCYP.js → monitor-RD2PFK42.js} +1 -1
- package/chunks/{nonInteractiveCli-MR7JLAWU.js → nonInteractiveCli-QQ72HZSH.js} +1 -1
- package/chunks/{nonInteractiveToolExecutor-YKA6JMTY.js → nonInteractiveToolExecutor-QPQYR6IS.js} +1 -1
- package/chunks/{notebook-edit-ENTFB5D7.js → notebook-edit-YLRN3UZT.js} +1 -1
- package/chunks/{omni-6YBX4R6K.js → omni-CUJ52EW5.js} +1 -1
- package/chunks/{openaiContentGenerator-XRXX33FY.js → openaiContentGenerator-6B5MAU54.js} +1 -1
- package/chunks/{openaiResponsesContentGenerator-L6ONEHMR.js → openaiResponsesContentGenerator-I245I3R7.js} +1 -1
- package/chunks/{pidfile-XR4JF2Z6.js → pidfile-P2HIGAUA.js} +1 -1
- package/chunks/{processUtils-GQYNJRBJ.js → processUtils-JSKN5UGS.js} +1 -1
- package/chunks/{prompt-terminal-ledger-7BM7YDLG.js → prompt-terminal-ledger-F5TSXVGU.js} +1 -1
- package/chunks/{qwenContentGenerator-QSA32XEL.js → qwenContentGenerator-IEDZONWG.js} +1 -1
- package/chunks/{reactive-degrade-TFNBAAPZ.js → reactive-degrade-FYZBJCF6.js} +1 -1
- package/chunks/{read-file-VD7OFO2E.js → read-file-VNZNSD6X.js} +1 -1
- package/chunks/{resumeHistoryUtils-2B4KPI7G.js → resumeHistoryUtils-IDPE6N2N.js} +1 -1
- package/chunks/{review-C365WGCW.js → review-TBJRZWTD.js} +1 -1
- package/chunks/{ripGrep-D7WPMBXR.js → ripGrep-4W5B5FOE.js} +1 -1
- package/chunks/{run-qwen-serve-NZWQHWQA.js → run-qwen-serve-44X262G5.js} +1 -1
- package/chunks/{runtime-J6SPBSCS.js → runtime-6H6LKD73.js} +1 -1
- package/chunks/{sandboxConfig-QS2XBPZG.js → sandboxConfig-SQXDRGVN.js} +1 -1
- package/chunks/{scheduled-tasks-YNNIOOPM.js → scheduled-tasks-62IZKHJG.js} +1 -1
- package/chunks/{scheduler-KCMSPHON.js → scheduler-QUCXJYRL.js} +1 -1
- package/chunks/{search-memory-EUBJ7IAV.js → search-memory-TC2Z34QN.js} +1 -1
- package/chunks/{send-message-CWWZUPSK.js → send-message-TFZX7KI7.js} +1 -1
- package/chunks/{serve-4CB4BWJ5.js → serve-WSICDFGG.js} +1 -1
- package/chunks/{server-JNANUIGC.js → server-GYYVTNGY.js} +3 -3
- package/chunks/{session-3LQLXPUA.js → session-KF3O23ZJ.js} +1 -1
- package/chunks/{session-attachments-root-BWIVWFHJ.js → session-attachments-root-7HFUSONH.js} +1 -1
- package/chunks/{session-execution-engine-selector-5OLRX57L.js → session-execution-engine-selector-NVILT6BR.js} +1 -1
- package/chunks/{session-pr-refresh-RLF3EXS3.js → session-pr-refresh-3KDFTDEV.js} +1 -1
- package/chunks/{sessionService-U7ACD2HP.js → sessionService-XRTFLPDW.js} +1 -1
- package/chunks/{settings-FTGWYTUH.js → settings-QPPK6WXE.js} +1 -1
- package/chunks/{shell-E4RENYQC.js → shell-WYQDZWL7.js} +1 -1
- package/chunks/{skill-OLNPHRWB.js → skill-FYPT6AU7.js} +1 -1
- package/chunks/{skill-settings-R2BV2GEK.js → skill-settings-OGFI5KZF.js} +1 -1
- package/chunks/{spawnChannel-LOPAR5T2.js → spawnChannel-ANOOVPG7.js} +1 -1
- package/chunks/{standalone-update-IGDX2RGN.js → standalone-update-45WTDY4E.js} +1 -1
- package/chunks/{start-opentui-ui-33QLBNRC.js → start-opentui-ui-TL5WK33V.js} +1 -1
- package/chunks/{startInteractiveUI-RQKHD7MM.js → startInteractiveUI-N2IREVBM.js} +1 -1
- package/chunks/{team-create-HAVKHNU5.js → team-create-R77PRZ5U.js} +1 -1
- package/chunks/{team-plan-approval-7MCQX67C.js → team-plan-approval-6DCRKB5I.js} +1 -1
- package/chunks/{terminal-image-renderer-XT5JVEO6.js → terminal-image-renderer-TB7EX2WW.js} +1 -1
- package/chunks/{theme-manager-DR5EYGLT.js → theme-manager-RQDXJGVR.js} +1 -1
- package/chunks/{tool-call-LZHZ5RVH.js → tool-call-LVB4NCDT.js} +1 -1
- package/chunks/{tool-result-media-XCXCF4YC.js → tool-result-media-LRBB2KS6.js} +1 -1
- package/chunks/{tool-search-K6S3ON7M.js → tool-search-OG73QAQZ.js} +1 -1
- package/chunks/{total-session-admission-LGSS2VWS.js → total-session-admission-A4CUF6AD.js} +1 -1
- package/chunks/{trustedFolders-IIR2UZRL.js → trustedFolders-LSGOYTU2.js} +1 -1
- package/chunks/{update-relaunch-WVIFX5CN.js → update-relaunch-OGC6BZO7.js} +1 -1
- package/chunks/{updateCheck-CMEWLLZJ.js → updateCheck-7J3GXTER.js} +1 -1
- package/chunks/{upload-config-TCCFCNCD.js → upload-config-ML5XEJIF.js} +1 -1
- package/chunks/{useAutoAcceptIndicator-5RTTH3OW.js → useAutoAcceptIndicator-6DH6GQ2X.js} +1 -1
- package/chunks/{validateNonInterActiveAuth-AO336KDX.js → validateNonInterActiveAuth-KJDAGZCM.js} +1 -1
- package/chunks/{version-JYWKKMNP.js → version-7JN2YXL2.js} +1 -1
- package/chunks/{web-fetch-HWTAWXFM.js → web-fetch-42ZR4FEZ.js} +1 -1
- package/chunks/{web-search-HAI5LW3G.js → web-search-74NLPMZJ.js} +1 -1
- package/chunks/{workflow-BZ2YFGF6.js → workflow-WNPHX42I.js} +1 -1
- package/chunks/{workflow-ancestor-trust-26TFXFPO.js → workflow-ancestor-trust-HGF6G7LQ.js} +1 -1
- package/chunks/{workspace-agents-DLI4JQJZ.js → workspace-agents-3YFBFAK3.js} +1 -1
- package/chunks/{workspace-providers-status-64C7DJZU.js → workspace-providers-status-EPJI6KRV.js} +1 -1
- package/chunks/{workspace-recovery-worker-IFRT3KKP.js → workspace-recovery-worker-T3FK5YOD.js} +1 -1
- package/chunks/{workspace-registration-store-MYKJM2SK.js → workspace-registration-store-VEXYBDMA.js} +1 -1
- package/chunks/{workspace-registry-GZJRONAY.js → workspace-registry-NRZYTP2X.js} +1 -1
- package/chunks/{workspace-runtime-coordinator-44KW6HSN.js → workspace-runtime-coordinator-USNSTP2V.js} +1 -1
- package/chunks/{workspace-service-YHTSZYYD.js → workspace-service-USATWO56.js} +1 -1
- package/chunks/{workspace-skills-status-NEB62X24.js → workspace-skills-status-M5JTSFDL.js} +1 -1
- package/chunks/{workspace-trust-reconciler-HZLOOZWM.js → workspace-trust-reconciler-ZUZ2O5WC.js} +1 -1
- package/chunks/{write-file-HD5LHXGL.js → write-file-UMJVKE4S.js} +1 -1
- package/chunks/{zoom-image-W4BMRC5T.js → zoom-image-76XYHQ3Z.js} +1 -1
- package/cli.js +2 -2
- package/execution-worker.js +1 -1
- package/export-transcript-document.js +1 -1
- package/gerege.mjs +11 -0
- package/package.json +1 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{runQwenServe}from"./chunk-NA4ZF2FE.js";import"./chunk-APLMCZ35.js";import"./chunk-UKMS3RLB.js";import{createHostedHarnessContract}from"./chunk-JH3V5SPA.js";import"./chunk-M7PWCW6A.js";import"./chunk-XIFNBULA.js";import"./chunk-6S5XOXJ2.js";import"./chunk-R7TNFTT4.js";import{require_semver}from"./chunk-YZUKMJW7.js";import"./chunk-SVGTUGV2.js";import"./chunk-LGFF5PJA.js";import"./chunk-UJJSBKTX.js";import"./chunk-QSHWWIZT.js";import"./chunk-M5KJJE2X.js";import"./chunk-ASTRUET5.js";import"./chunk-BWQ5AIEA.js";import"./chunk-WDR5XP3Y.js";import"./chunk-WBDNGVHU.js";import"./chunk-2QYDBHYZ.js";import"./chunk-VTZZXEWA.js";import"./chunk-AJRRKTEY.js";import{signedManagedHeaders}from"./chunk-YOIAVGN5.js";import"./chunk-D5YXZ4RA.js";import"./chunk-3SHHYK7S.js";import"./chunk-LLKORW26.js";import{resolveWebShellDir}from"./chunk-N6DRGTL5.js";import"./chunk-6SOKP7IN.js";import"./chunk-BYVINSWZ.js";import"./chunk-P56D6ZAA.js";import"./chunk-W66WWTOP.js";import"./chunk-L5UULTGF.js";import"./chunk-FC5GHM3G.js";import"./chunk-B75LYOXZ.js";import"./chunk-AVJJ62OC.js";import"./chunk-VNV7VKZL.js";import"./chunk-KOJ7WZ63.js";import"./chunk-O6ZQAVRG.js";import"./chunk-3KZHPZVZ.js";import"./chunk-CFTFKWPW.js";import"./chunk-NIEO2TBE.js";import"./chunk-SPYNWVDZ.js";import"./chunk-E4UMXDOZ.js";import"./chunk-ELUOCI74.js";import"./chunk-TL6RUTMP.js";import"./chunk-IS7CHVXD.js";import{getAuthTypeFromEnv,resolveCliGenerationConfig}from"./chunk-LTE4N6L3.js";import"./chunk-GT4TCQ3R.js";import"./chunk-QN7NYEE3.js";import"./chunk-WSOEJTOC.js";import{loadSettings}from"./chunk-2TAJ5STJ.js";import"./chunk-UWCF7JIF.js";import"./chunk-NONBHCXP.js";import"./chunk-LMUSSYJH.js";import"./chunk-NO7VTKRL.js";import"./chunk-U7HZUZKP.js";import"./chunk-MPVQDYPH.js";import"./chunk-PKK2D2W4.js";import"./chunk-N3AQAZ7D.js";import"./chunk-E5T4R2PM.js";import"./chunk-DOLUT3XC.js";import"./chunk-PTHIQ7ZN.js";import"./chunk-MTDBCIDA.js";import"./chunk-EIPLDYEY.js";import"./chunk-IDXJIDME.js";import"./chunk-OU7CEG7Q.js";import"./chunk-QS2ZMQIS.js";import"./chunk-S7IKHQ6I.js";import"./chunk-IEWZIDC6.js";import{getCliVersion}from"./chunk-GBSRWT7J.js";import"./chunk-O4EDHV64.js";import"./chunk-PAD5GPDY.js";import"./chunk-MD3ZEOBX.js";import"./chunk-SSYS5YN5.js";import"./chunk-X5QSFJVS.js";import"./chunk-OMDTFGTX.js";import"./chunk-32XHDDIA.js";import"./chunk-46VUDNCL.js";import"./chunk-MKH3EH7O.js";import"./chunk-FKZ46GKL.js";import"./chunk-SP6CQ3MO.js";import"./chunk-HW6SU6MX.js";import"./chunk-ZHHFNZ5J.js";import"./chunk-AKWYMQKU.js";import"./chunk-MZUOREFD.js";import"./chunk-CF6SZJNP.js";import"./chunk-7XZVMIY5.js";import"./chunk-CGDFZEER.js";import"./chunk-ZZJXFLVM.js";import"./chunk-RKDS7A4H.js";import"./chunk-KZNYALFU.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-2JGTWRZJ.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{ModelsConfig}from"./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-LG4NL2M7.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-AFO5ER23.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-H4XFFVZ2.js";import"./chunk-X7QN6R6K.js";import{writeStderrLine,writeStdoutLine}from"./chunk-M4ECEHLX.js";import"./chunk-DBRQGEEI.js";import"./chunk-B3ZFUGTC.js";import"./chunk-IRINPFG7.js";import"./chunk-6GTPLW7K.js";import"./chunk-NGVRCUYD.js";import"./chunk-5DTFN37U.js";import"./chunk-2YUBAWQ6.js";import"./chunk-O5EKX7LG.js";import"./chunk-TM6ZCBR7.js";import"./chunk-SVAPAMMG.js";import"./chunk-3KUHQGOS.js";import"./chunk-I6S7NGX3.js";import"./chunk-SBZFGYYS.js";import"./chunk-JAUJI56S.js";import"./chunk-I4H7NUVP.js";import{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();import{spawn}from"node:child_process";import{createHash as createHash3}from"node:crypto";import{closeSync,openSync}from"node:fs";import path4 from"node:path";import{setTimeout as delay}from"node:timers/promises";init_esbuild_shims();import{execFile}from"node:child_process";import{createHash as createHash2}from"node:crypto";import{constants,createReadStream}from"node:fs";import{access,lstat as lstat2,readFile as readFile2,realpath,stat}from"node:fs/promises";import path2 from"node:path";import{promisify}from"node:util";init_esbuild_shims();var import_proper_lockfile=__toESM(require_proper_lockfile(),1);var import_semver=__toESM(require_semver(),1);import{createHash}from"node:crypto";import{createWriteStream}from"node:fs";import{lstat,mkdir,mkdtemp,open,readFile,readdir,rename,rm,writeFile}from"node:fs/promises";import path from"node:path";import{Readable,Transform}from"node:stream";import{pipeline}from"node:stream/promises";async function download(url,destination,limit,signal,version){const response=await fetch(url,{signal,headers:{"User-Agent":`qwen-code/${version}`}});if(!response.ok||!response.body){await response.body?.cancel();throw new Error(`Download returned HTTP ${response.status}.`)}if(Number(response.headers.get("content-length"))>limit){await response.body.cancel();throw new Error("Download exceeds the size limit.")}const digest=createHash("sha256");let received=0;await pipeline(Readable.fromWeb(response.body),new Transform({transform(chunk,_encoding,callback){received+=chunk.length;if(received>limit){callback(new Error("Download exceeds the size limit."));return}digest.update(chunk);callback(null,chunk)}}),createWriteStream(destination,{flags:"wx",mode:384}));return digest.digest("hex")}__name(download,"download");async function installManagedLocalRuntime(version,target,directory){if(version.length>128||(0,import_semver.valid)(version)!==version||!/^(?:darwin|linux)-(?:arm64|x64)$/u.test(target)){throw new Error("Managed runtime download requires a release version and supported target.")}const parent=path.dirname(directory);await mkdir(parent,{recursive:true,mode:448});const release=await import_proper_lockfile.default.lock(directory,{realpath:false,stale:12e4,retries:{retries:600,minTimeout:1e3,maxTimeout:1e3}});try{try{await lstat(directory);return}catch(error){if(error.code!=="ENOENT")throw error}const temporaryPrefix=`.${target}-download-`;for(const entry of await readdir(parent)){if(entry.startsWith(temporaryPrefix)){await rm(path.join(parent,entry),{recursive:true,force:true})}}const tag=encodeURIComponent(`v${version}`);const name=`qwen-managed-agent-server-${version}.jar`;const sources=[`https://qwen-code-assets.oss-cn-hangzhou.aliyuncs.com/releases/qwen-code/${tag}`,`https://github.com/QwenLM/qwen-code/releases/download/${tag}`];const errors=[];for(const source of sources){const temporary=await mkdtemp(path.join(parent,temporaryPrefix));try{writeStderrLine(`Downloading Managed server ${version} from ${new URL(source).hostname}...`);const signal=AbortSignal.timeout(3e5);const checksumFile=path.join(temporary,"checksum");await download(`${source}/${name}.sha256`,checksumFile,1024,signal,version);const checksum=(await readFile(checksumFile,"utf8")).trim();const expected=/^([a-f0-9]{64}) {2}(\S+)$/u.exec(checksum);if(!expected||expected[2]!==name){throw new Error("Invalid Managed server checksum file.")}const serverJar=path.join(temporary,"server.jar");const actual=await download(`${source}/${name}`,serverJar,256*1024*1024,signal,version);if(actual!==expected[1])throw new Error("Server checksum mismatch.");const jar=await open(serverJar,"r");try{const header=Buffer.alloc(4);await jar.read(header,0,header.length,0);if(header.toString("hex")!=="504b0304"){throw new Error("Managed server is not a JAR.")}}finally{await jar.close()}await rm(checksumFile);await writeFile(path.join(temporary,"manifest.json"),`${JSON.stringify({schemaVersion:1,cliVersion:version,target,javaMajor:21,javaSource:"system",serverSha256:actual},null,2)}
|
|
3
|
+
import{runQwenServe}from"./chunk-QONPET6Y.js";import"./chunk-APLMCZ35.js";import"./chunk-UKMS3RLB.js";import{createHostedHarnessContract}from"./chunk-OZFZBGZG.js";import"./chunk-M7PWCW6A.js";import"./chunk-XIFNBULA.js";import"./chunk-6S5XOXJ2.js";import"./chunk-R7TNFTT4.js";import{require_semver}from"./chunk-YZUKMJW7.js";import"./chunk-SVGTUGV2.js";import"./chunk-LGFF5PJA.js";import"./chunk-UJJSBKTX.js";import"./chunk-QSHWWIZT.js";import"./chunk-M5KJJE2X.js";import"./chunk-ASTRUET5.js";import"./chunk-BWQ5AIEA.js";import"./chunk-WDR5XP3Y.js";import"./chunk-WBDNGVHU.js";import"./chunk-2QYDBHYZ.js";import"./chunk-VTZZXEWA.js";import"./chunk-AJRRKTEY.js";import{signedManagedHeaders}from"./chunk-YOIAVGN5.js";import"./chunk-D5YXZ4RA.js";import"./chunk-3SHHYK7S.js";import"./chunk-LLKORW26.js";import{resolveWebShellDir}from"./chunk-N6DRGTL5.js";import"./chunk-6SOKP7IN.js";import"./chunk-BYVINSWZ.js";import"./chunk-P56D6ZAA.js";import"./chunk-NPAENNRO.js";import"./chunk-L5UULTGF.js";import"./chunk-FC5GHM3G.js";import"./chunk-B75LYOXZ.js";import"./chunk-AVJJ62OC.js";import"./chunk-VNV7VKZL.js";import"./chunk-KOJ7WZ63.js";import"./chunk-O6ZQAVRG.js";import"./chunk-3KZHPZVZ.js";import"./chunk-CFTFKWPW.js";import"./chunk-NIEO2TBE.js";import"./chunk-SPYNWVDZ.js";import"./chunk-E4UMXDOZ.js";import"./chunk-ELUOCI74.js";import"./chunk-TL6RUTMP.js";import"./chunk-IS7CHVXD.js";import{getAuthTypeFromEnv,resolveCliGenerationConfig}from"./chunk-SAVYMUU3.js";import"./chunk-GT4TCQ3R.js";import"./chunk-QN7NYEE3.js";import"./chunk-WSOEJTOC.js";import{loadSettings}from"./chunk-Q5RRVBTY.js";import"./chunk-UWCF7JIF.js";import"./chunk-G4MWPXNY.js";import"./chunk-LMUSSYJH.js";import"./chunk-NO7VTKRL.js";import"./chunk-U7HZUZKP.js";import"./chunk-UM5KBBYP.js";import"./chunk-PKK2D2W4.js";import"./chunk-N3AQAZ7D.js";import"./chunk-E5T4R2PM.js";import"./chunk-DOLUT3XC.js";import"./chunk-PTHIQ7ZN.js";import"./chunk-YWK3E4WJ.js";import"./chunk-EIPLDYEY.js";import"./chunk-IDXJIDME.js";import"./chunk-CK3OKTTL.js";import"./chunk-QS2ZMQIS.js";import"./chunk-S7IKHQ6I.js";import"./chunk-IEWZIDC6.js";import{getCliVersion}from"./chunk-MXZXQUVP.js";import"./chunk-O4EDHV64.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"./chunk-ZHHFNZ5J.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"./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"./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{ModelsConfig}from"./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-LG4NL2M7.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-H4XFFVZ2.js";import"./chunk-X7QN6R6K.js";import{writeStderrLine,writeStdoutLine}from"./chunk-M4ECEHLX.js";import"./chunk-DBRQGEEI.js";import"./chunk-B3ZFUGTC.js";import"./chunk-IRINPFG7.js";import"./chunk-6GTPLW7K.js";import"./chunk-NGVRCUYD.js";import"./chunk-5DTFN37U.js";import"./chunk-2YUBAWQ6.js";import"./chunk-O5EKX7LG.js";import"./chunk-TM6ZCBR7.js";import"./chunk-SVAPAMMG.js";import"./chunk-3KUHQGOS.js";import"./chunk-I6S7NGX3.js";import"./chunk-SBZFGYYS.js";import"./chunk-JAUJI56S.js";import"./chunk-I4H7NUVP.js";import{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();import{spawn}from"node:child_process";import{createHash as createHash3}from"node:crypto";import{closeSync,openSync}from"node:fs";import path4 from"node:path";import{setTimeout as delay}from"node:timers/promises";init_esbuild_shims();import{execFile}from"node:child_process";import{createHash as createHash2}from"node:crypto";import{constants,createReadStream}from"node:fs";import{access,lstat as lstat2,readFile as readFile2,realpath,stat}from"node:fs/promises";import path2 from"node:path";import{promisify}from"node:util";init_esbuild_shims();var import_proper_lockfile=__toESM(require_proper_lockfile(),1);var import_semver=__toESM(require_semver(),1);import{createHash}from"node:crypto";import{createWriteStream}from"node:fs";import{lstat,mkdir,mkdtemp,open,readFile,readdir,rename,rm,writeFile}from"node:fs/promises";import path from"node:path";import{Readable,Transform}from"node:stream";import{pipeline}from"node:stream/promises";async function download(url,destination,limit,signal,version){const response=await fetch(url,{signal,headers:{"User-Agent":`qwen-code/${version}`}});if(!response.ok||!response.body){await response.body?.cancel();throw new Error(`Download returned HTTP ${response.status}.`)}if(Number(response.headers.get("content-length"))>limit){await response.body.cancel();throw new Error("Download exceeds the size limit.")}const digest=createHash("sha256");let received=0;await pipeline(Readable.fromWeb(response.body),new Transform({transform(chunk,_encoding,callback){received+=chunk.length;if(received>limit){callback(new Error("Download exceeds the size limit."));return}digest.update(chunk);callback(null,chunk)}}),createWriteStream(destination,{flags:"wx",mode:384}));return digest.digest("hex")}__name(download,"download");async function installManagedLocalRuntime(version,target,directory){if(version.length>128||(0,import_semver.valid)(version)!==version||!/^(?:darwin|linux)-(?:arm64|x64)$/u.test(target)){throw new Error("Managed runtime download requires a release version and supported target.")}const parent=path.dirname(directory);await mkdir(parent,{recursive:true,mode:448});const release=await import_proper_lockfile.default.lock(directory,{realpath:false,stale:12e4,retries:{retries:600,minTimeout:1e3,maxTimeout:1e3}});try{try{await lstat(directory);return}catch(error){if(error.code!=="ENOENT")throw error}const temporaryPrefix=`.${target}-download-`;for(const entry of await readdir(parent)){if(entry.startsWith(temporaryPrefix)){await rm(path.join(parent,entry),{recursive:true,force:true})}}const tag=encodeURIComponent(`v${version}`);const name=`qwen-managed-agent-server-${version}.jar`;const sources=[`https://qwen-code-assets.oss-cn-hangzhou.aliyuncs.com/releases/qwen-code/${tag}`,`https://github.com/QwenLM/qwen-code/releases/download/${tag}`];const errors=[];for(const source of sources){const temporary=await mkdtemp(path.join(parent,temporaryPrefix));try{writeStderrLine(`Downloading Managed server ${version} from ${new URL(source).hostname}...`);const signal=AbortSignal.timeout(3e5);const checksumFile=path.join(temporary,"checksum");await download(`${source}/${name}.sha256`,checksumFile,1024,signal,version);const checksum=(await readFile(checksumFile,"utf8")).trim();const expected=/^([a-f0-9]{64}) {2}(\S+)$/u.exec(checksum);if(!expected||expected[2]!==name){throw new Error("Invalid Managed server checksum file.")}const serverJar=path.join(temporary,"server.jar");const actual=await download(`${source}/${name}`,serverJar,256*1024*1024,signal,version);if(actual!==expected[1])throw new Error("Server checksum mismatch.");const jar=await open(serverJar,"r");try{const header=Buffer.alloc(4);await jar.read(header,0,header.length,0);if(header.toString("hex")!=="504b0304"){throw new Error("Managed server is not a JAR.")}}finally{await jar.close()}await rm(checksumFile);await writeFile(path.join(temporary,"manifest.json"),`${JSON.stringify({schemaVersion:1,cliVersion:version,target,javaMajor:21,javaSource:"system",serverSha256:actual},null,2)}
|
|
4
4
|
`,{mode:384});await rename(temporary,directory);writeStderrLine(`Managed server ${version} installed. Subsequent starts use the local cache.`);return}catch(error){errors.push(`${new URL(source).hostname}: ${error instanceof Error?error.message:String(error)}`)}finally{await rm(temporary,{recursive:true,force:true})}}throw new Error(`Could not install Managed runtime for CLI ${version}, ${target} at ${directory}. ${errors.join(" ")} Retry when the release is available, or preinstall a matching managed-runtime archive for offline use.`)}finally{await release()}}__name(installManagedLocalRuntime,"installManagedLocalRuntime");var execFileAsync=promisify(execFile);async function resolveSystemJava(){const javaHome=process.env["JAVA_HOME"];const candidates=javaHome?[path2.resolve(javaHome,"bin","java")]:(process.env["PATH"]??"").split(path2.delimiter).map(directory=>path2.resolve(directory,"java"));let java;for(const candidate of candidates){try{await access(candidate,constants.X_OK);if(!(await stat(candidate)).isFile())continue;java=await realpath(candidate);break}catch{continue}}const requirement="Managed local serve requires local Java 21. Set JAVA_HOME to a Java 21 home or put Java 21 on PATH.";if(!java){throw new Error(`${requirement} No executable java found ${javaHome?"in JAVA_HOME/bin":"on PATH"}.`)}try{const{stdout,stderr}=await execFileAsync(java,["-XshowSettings:properties","-version"],{timeout:1e4,maxBuffer:64*1024});if(!/^\s*java\.specification\.version\s*=\s*21\s*$/mu.test(`${stdout}
|
|
5
5
|
${stderr}`)){throw new Error("Wrong Java version")}}catch{throw new Error(`${requirement} Could not verify Java 21 at ${java}.`)}return java}__name(resolveSystemJava,"resolveSystemJava");async function resolveManagedLocalRuntime(cliEntry=process.argv[1],runtimeDirectory=process.env["QWEN_MANAGED_LOCAL_RUNTIME_DIR"]){if(process.platform!=="darwin"&&process.platform!=="linux"){throw new Error("Managed local serve supports native macOS and Linux.")}if("bun"in process.versions||Number(process.versions.node.split(".")[0])<22){throw new Error("Managed local serve requires Node.js 22 or newer; Bun is unsupported.")}if(!cliEntry)throw new Error("Cannot determine the installed CLI entry.");const entry=await realpath(cliEntry);const version=await getCliVersion();const target=`${process.platform}-${process.arch}`;const installed=path2.join(Storage.getGlobalQwenDir(),"managed-runtime",version,target);let directory=runtimeDirectory;let systemJava;if(directory===void 0){const colocated=path2.join(path2.dirname(entry),"managed-runtime");try{await lstat2(colocated);directory=colocated}catch(error){if(error.code!=="ENOENT")throw error;directory=installed;try{await lstat2(installed)}catch(installedError){if(installedError.code!=="ENOENT"){throw installedError}systemJava=await resolveSystemJava();await installManagedLocalRuntime(version,target,installed)}}}directory=path2.resolve(directory);let manifest;try{manifest=JSON.parse(await readFile2(path2.join(directory,"manifest.json"),"utf8"))}catch{throw new Error(`Managed runtime is missing or invalid at ${directory}. Install the managed-runtime archive for CLI ${version}, ${target} into ${Storage.getGlobalQwenDir()}, use the complete Managed local distribution, or set QWEN_MANAGED_LOCAL_RUNTIME_DIR to its payload directory.`)}if(!manifest||typeof manifest!=="object"||!("schemaVersion"in manifest)||manifest.schemaVersion!==1||!("cliVersion"in manifest)||manifest.cliVersion!==version||!("target"in manifest)||manifest.target!==target||!("javaMajor"in manifest)||manifest.javaMajor!==21||"javaSource"in manifest&&manifest.javaSource!=="bundled"&&manifest.javaSource!=="system"||!("serverSha256"in manifest)||typeof manifest.serverSha256!=="string"||!/^[a-f0-9]{64}$/u.test(manifest.serverSha256)){throw new Error(`Managed runtime must match CLI ${version}, ${target}, and Java 21.`)}const serverJar=path2.join(directory,"server.jar");let java=path2.join(directory,"jre","bin","java");const digest=createHash2("sha256");try{for await(const chunk of createReadStream(serverJar))digest.update(chunk);if(digest.digest("hex")!==manifest.serverSha256){throw new Error("Server checksum mismatch")}if(!(await stat(serverJar)).isFile())throw new Error("Not a server JAR");if("javaSource"in manifest&&manifest.javaSource==="system"){java=systemJava??await resolveSystemJava()}else{await access(java,constants.X_OK);const release=await readFile2(path2.join(directory,"jre","release"),"utf8");if(!/^JAVA_VERSION="21(?:[.\-+"])/mu.test(release)){throw new Error("Java runtime is not Java 21")}}}catch(error){throw new Error(`Managed runtime verification failed: ${error instanceof Error?error.message:String(error)}`)}return{java,serverJar,cliEntry:entry}}__name(resolveManagedLocalRuntime,"resolveManagedLocalRuntime");init_esbuild_shims();var import_proper_lockfile2=__toESM(require_proper_lockfile(),1);import{randomBytes,randomUUID}from"node:crypto";import{access as access2,chmod,lstat as lstat3,mkdir as mkdir2,readFile as readFile3,readdir as readdir2,realpath as realpath2,rename as rename2,writeFile as writeFile2}from"node:fs/promises";import path3 from"node:path";import{createServer}from"node:net";var HEX_SECRETS=["publicToken","signingKey","harnessToken","brokerToken","writerBindingKey"];function validateManagedLocalState(value){if(!value||typeof value!=="object")throw new Error("Invalid local state");const state=value;if(state["schemaVersion"]!==1||typeof state["installationId"]!=="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u.test(state["installationId"])||HEX_SECRETS.some(key=>typeof state[key]!=="string"||!/^[0-9a-f]{64}$/u.test(state[key]))||typeof state["runtimeCredentialKey"]!=="string"||!/^[A-Za-z0-9+/]{43}=$/u.test(state["runtimeCredentialKey"])||typeof state["capabilityDigest"]!=="string"||!/^sha256:[0-9a-f]{64}$/u.test(state["capabilityDigest"])||["javaPort","harnessPort","brokerPort"].some(key=>!Number.isInteger(state[key])||Number(state[key])<1||Number(state[key])>65535)||new Set([state["javaPort"],state["harnessPort"],state["brokerPort"]]).size!==3)throw new Error("Invalid local state; restore the original state.json and data together.");return value}__name(validateManagedLocalState,"validateManagedLocalState");async function freePort(){return new Promise((resolve,reject)=>{const server=createServer();server.once("error",reject);server.listen(0,"127.0.0.1",()=>{const address=server.address();if(!address||typeof address==="string"){server.close();reject(new Error("Cannot allocate a local service port"));return}server.close(error=>error?reject(error):resolve(address.port))})})}__name(freePort,"freePort");async function openManagedLocalState(directory=path3.join(Storage.getGlobalQwenDir(),"managed-local")){const requested=path3.resolve(directory);await mkdir2(requested,{recursive:true,mode:448});if((await lstat3(requested)).isSymbolicLink())throw new Error("Managed data directory cannot be a symbolic link.");const canonical=await realpath2(requested);for(let ancestor=canonical;;ancestor=path3.dirname(ancestor)){let inGit=false;try{await access2(path3.join(ancestor,".git"));inGit=true}catch{}if(inGit)throw new Error("Managed data must be outside every Git worktree. Use --managed-data-dir outside the project.");if(path3.dirname(ancestor)===ancestor)break}const existing=await readdir2(canonical);if(existing.length&&!existing.includes("state.json")&&existing.some(entry=>entry!==".launcher.lock")){throw new Error("Managed data has no state.json; restore the original state and database together.")}await chmod(canonical,448);const release=await import_proper_lockfile2.default.lock(canonical,{realpath:true,retries:0,stale:12e4,lockfilePath:path3.join(canonical,".launcher.lock")}).catch(()=>{throw new Error("Managed data directory is already in use; stop its launcher before retrying.")});try{const file=path3.join(canonical,"state.json");let state;const entries=await readdir2(canonical);if(entries.includes("state.json")){const metadata=await lstat3(file);if(!metadata.isFile()||metadata.isSymbolicLink()||metadata.size>16*1024||(metadata.mode&63)!==0){throw new Error("Managed state.json must be a private regular file (mode 0600).")}state=validateManagedLocalState(JSON.parse(await readFile3(file,"utf8")))}else{if(entries.some(name=>name!==".launcher.lock")){throw new Error("Managed data has no state.json; restore the original state and database together.")}const ports=new Set;while(ports.size<3)ports.add(await freePort());const[javaPort,harnessPort,brokerPort]=[...ports];const secret=__name(()=>randomBytes(32).toString("hex"),"secret");state={schemaVersion:1,installationId:randomUUID(),publicToken:secret(),signingKey:secret(),harnessToken:secret(),brokerToken:secret(),writerBindingKey:secret(),runtimeCredentialKey:randomBytes(32).toString("base64"),capabilityDigest:`sha256:${secret()}`,javaPort,harnessPort,brokerPort};const temporary=path3.join(canonical,`state-${randomUUID()}.tmp`);await writeFile2(temporary,`${JSON.stringify(state,null,2)}
|
|
6
6
|
`,{mode:384,flag:"wx"});await rename2(temporary,file)}for(const child of["database","runtime","worker-home","harness","workspaces","legacy","logs"]){const target=path3.join(canonical,child);await mkdir2(target,{recursive:true,mode:448});const metadata=await lstat3(target);if(!metadata.isDirectory()||metadata.isSymbolicLink()){throw new Error(`Managed ${child} must be a private directory.`)}await chmod(target,448)}return{directory:canonical,state,release}}catch(error){await release();throw error}}__name(openManagedLocalState,"openManagedLocalState");init_esbuild_shims();function loadManagedLocalModels(){const{merged}=loadSettings(process.cwd(),{skipLoadEnvironment:true,skipWorkspaceSettings:true,workspaceTrusted:false});const configured=new ModelsConfig({modelProvidersConfig:merged.modelProviders,providerProtocolConfig:merged.providerProtocol}).getAllConfiguredModels();const selection=resolveCliGenerationConfig({argv:{},settings:merged,selectedAuthType:merged.security?.auth?.selectedType??getAuthTypeFromEnv()});const models=configured.filter(model=>model.authType!=="qwen-oauth"&&!model.fastOnly&&!model.voiceOnly&&!model.visionOnly&&!model.imageOnly&&configured.filter(candidate=>candidate.id===model.id).length===1).map(model=>({modelId:model.id,label:model.label||model.id}));const selected=models.findIndex(model=>model.modelId===selection.model&&configured.some(candidate=>candidate.id===model.modelId&&candidate.authType===selection.authType));if(selected>0)models.unshift(...models.splice(selected,1));return{models,defaultModelId:selected>=0?selection.model:void 0}}__name(loadManagedLocalModels,"loadManagedLocalModels");function managedLocalJavaEnvironment(state,directory,runtime,models=[]){const environment=Object.fromEntries(Object.entries(process.env).filter(([name])=>!name.startsWith("SPRING_")&&!name.startsWith("QWEN_MANAGED_AGENT_")&&!name.startsWith("QWEN_HOSTED_")&&name!=="QWEN_SERVER_TOKEN"));return{...environment,SPRING_APPLICATION_JSON:JSON.stringify({"qwen.managed-agent.runtime-broker.session-worktrees-enabled":process.platform!=="win32","qwen.managed-agent.model-catalog":models,"qwen.managed-agent.definition-models":models.map(model=>model.modelId),"qwen.managed-agent.definition-tool-profiles":["hosted-workspace-shell/1"]}),SPRING_PROFILES_ACTIVE:"managed-local",SERVER_PORT:String(state.javaPort),QWEN_MANAGED_AGENT_LOCAL_DATA_DIRECTORY:directory,QWEN_MANAGED_AGENT_AUTH_MODE:"signed",QWEN_MANAGED_AGENT_AUTH_SIGNING_KEY:state.signingKey,QWEN_MANAGED_AGENT_TRUSTED_ACTOR_HEADER:"",QWEN_MANAGED_AGENT_LOCAL_DIRECTORY_IMPORT_ENABLED:"true",QWEN_MANAGED_AGENT_SERVER_ADDRESS:"127.0.0.1",QWEN_MANAGED_AGENT_SESSION_STORE_ENABLED:"true",QWEN_MANAGED_AGENT_SESSION_STORE_BASE_URL:`http://127.0.0.1:${state.javaPort}`,QWEN_MANAGED_AGENT_SESSION_STORE_BINDING_KEY:state.writerBindingKey,QWEN_MANAGED_AGENT_WORKSPACE_ID:createHash3("sha256").update(path4.join(directory,"legacy")).digest("hex").slice(0,16),QWEN_MANAGED_AGENT_WORKSPACE_CWD:path4.join(directory,"legacy"),QWEN_MANAGED_AGENT_WORKSPACE_CREATION_ROOT:path4.join(directory,"workspaces"),QWEN_MANAGED_AGENT_HARNESS_ENABLED:"true",QWEN_MANAGED_AGENT_HARNESS_BASE_URL:`http://127.0.0.1:${state.harnessPort}`,QWEN_MANAGED_AGENT_HARNESS_TOKEN:state.harnessToken,QWEN_MANAGED_AGENT_CAPABILITY_DIGEST:state.capabilityDigest,QWEN_MANAGED_AGENT_WORKSPACE_FILES_ENABLED:"true",QWEN_MANAGED_AGENT_WORKSPACE_SHELL_ENABLED:"true",QWEN_MANAGED_AGENT_APPROVAL_MODE:"default",QWEN_MANAGED_AGENT_RUNTIME_BROKER_ENABLED:"true",QWEN_MANAGED_AGENT_RUNTIME_BROKER_HOST:"127.0.0.1",QWEN_MANAGED_AGENT_RUNTIME_BROKER_PORT:String(state.brokerPort),QWEN_MANAGED_AGENT_RUNTIME_BROKER_TOKEN:state.brokerToken,QWEN_MANAGED_AGENT_RUNTIME_PROVISIONER:"local-process",QWEN_MANAGED_AGENT_RUNTIME_DURABLE_LOCAL_PROCESS:"true",QWEN_MANAGED_AGENT_RUNTIME_TRUSTED_LOCAL_REBOOT_RECOVERY:"false",QWEN_MANAGED_AGENT_RUNTIME_VERIFIED_WORKSPACE_RECOVERY_ENABLED:"true",QWEN_MANAGED_AGENT_RUNTIME_CREDENTIAL_KEY_ID:"managed-local-v1",QWEN_MANAGED_AGENT_RUNTIME_CREDENTIAL_KEY:state.runtimeCredentialKey,QWEN_MANAGED_AGENT_RUNTIME_STATE_DIRECTORY:path4.join(directory,"runtime"),QWEN_MANAGED_AGENT_NODE_EXECUTABLE:process.execPath,QWEN_MANAGED_AGENT_RUNTIME_WORKER_ENTRY:runtime.cliEntry,QWEN_HOME:path4.join(directory,"worker-home")}}__name(managedLocalJavaEnvironment,"managedLocalJavaEnvironment");async function stopChild(child,processGroup){if(child.exitCode!==null||child.signalCode!==null||!child.pid)return;const exited=new Promise(resolve=>child.once("exit",()=>resolve()));child.kill("SIGTERM");const stopped=await Promise.race([exited.then(()=>true),delay(35e3,false,{ref:false})]);if(!stopped){try{if(processGroup)process.kill(-child.pid,"SIGKILL");else child.kill("SIGKILL")}catch(error){if(error.code!=="ESRCH")throw error}await exited}}__name(stopChild,"stopChild");async function runManagedLocalServe(options){if(!Number.isInteger(options.port)||options.port<0||options.port>65535){throw new Error("--port must be an integer from 0 to 65535.")}const runtime=await resolveManagedLocalRuntime();const webShellDir=resolveWebShellDir();if(!webShellDir)throw new Error("The Managed distribution requires built WebShell assets.");const local=await openManagedLocalState(options.dataDirectory);const{state,directory}=local;const children=[];let frontDoor;let ready=false;let failure;let closing;let finish=__name(()=>{},"finish");const finished=new Promise(resolve=>{finish=resolve});const shutdown=__name(code=>{closing??=(async()=>{let exitCode=code;const cleanup=__name(async action=>{try{await action()}catch(error){exitCode=1;writeStderrLine(`Managed shutdown: ${error instanceof Error?error.message:String(error)}`)}},"cleanup");await cleanup(async()=>frontDoor?.close());for(const child of[...children].reverse()){await cleanup(()=>stopChild(child.process,child.group))}process.off("SIGINT",onSignal);process.off("SIGTERM",onSignal);process.off("SIGHUP",onSignal);await cleanup(local.release);finish(exitCode)})();return closing},"shutdown");const onSignal=__name(()=>{void shutdown(0)},"onSignal");process.on("SIGINT",onSignal);process.on("SIGTERM",onSignal);process.on("SIGHUP",onSignal);const start=__name((name,command,args,env,group)=>{if(closing)throw new Error("Managed startup interrupted.");const logPath=path4.join(directory,"logs",`${name}.log`);const fd=openSync(logPath,"a",384);let child;try{child=spawn(command,args,{cwd:directory,env,stdio:["ignore",fd,fd],detached:true})}finally{closeSync(fd)}children.push({process:child,group});const failed=__name(reason=>{failure??=new Error(`${name} ${reason}. See ${logPath}`);if(ready&&!closing){writeStderrLine(`qwen serve --managed: ${failure.message}`);void shutdown(1)}},"failed");child.once("error",error=>failed(error.message));child.once("exit",(code,signal)=>failed(`exited (${signal??code})`))},"start");const waitFor=__name(async(name,probe)=>{const deadline=Date.now()+12e4;while(Date.now()<deadline){if(failure)throw failure;if(closing)throw new Error("Managed startup interrupted.");try{if(await probe())return}catch{}await delay(200)}throw new Error(`${name} did not become ready. See ${path4.join(directory,"logs")}`)},"waitFor");try{const{models,defaultModelId}=loadManagedLocalModels();if([state.javaPort,state.harnessPort,state.brokerPort].includes(options.port)){throw new Error("Public --port conflicts with a persisted private service port. Choose another public port.")}writeStdoutLine(`Starting Managed local services. Data: ${directory}`);const javaUrl=`http://127.0.0.1:${state.javaPort}`;const harnessUrl=`http://127.0.0.1:${state.harnessPort}`;const lifecycleV2Profiles=createHostedHarnessContract(state.capabilityDigest).lifecycleV2Profiles;start("harness",process.execPath,[runtime.cliEntry,"serve","--profile","hosted-harness","--hostname","127.0.0.1","--port",String(state.harnessPort),"--require-auth","--no-web","--workspace",path4.join(directory,"harness")],{...process.env,QWEN_SERVER_TOKEN:state.harnessToken,QWEN_HOSTED_HARNESS_CAPABILITY_DIGEST:state.capabilityDigest,QWEN_MANAGED_RUNTIME_BROKER_URL:`http://127.0.0.1:${state.brokerPort}`,QWEN_MANAGED_RUNTIME_BROKER_TOKEN:state.brokerToken,QWEN_RUNTIME_DIR:path4.join(directory,"harness")},true);start("server",runtime.java,["-jar",runtime.serverJar],managedLocalJavaEnvironment(state,directory,runtime,models),false);await waitFor("Hosted Harness",async()=>{const response=await fetch(`${harnessUrl}/capabilities`,{headers:{Authorization:`Bearer ${state.harnessToken}`},signal:AbortSignal.timeout(3e3)});if(!response.ok){await response.body?.cancel();return false}const body2=await response.json();return Boolean(body2&&typeof body2==="object"&&"hostedHarness"in body2&&body2.hostedHarness&&typeof body2.hostedHarness==="object"&&"capabilityDigest"in body2.hostedHarness&&body2.hostedHarness.capabilityDigest===state.capabilityDigest&&"lifecycleV2Profiles"in body2.hostedHarness&&Array.isArray(body2.hostedHarness.lifecycleV2Profiles)&&JSON.stringify(body2.hostedHarness.lifecycleV2Profiles)===JSON.stringify(lifecycleV2Profiles))});await waitFor("Java control plane",async()=>{const response=await fetch(`${javaUrl}/actuator/health/readiness`,{signal:AbortSignal.timeout(3e3)});const ok=response.ok;await response.body?.cancel();return ok});const tenantId=`local-${state.installationId}`;const actorId="local-user";const modelPresets=models.map(({modelId,label})=>({agentId:"qwen-code",modelId,label}));if(models.length&&!defaultModelId){modelPresets.unshift({agentId:"qwen-code",label:"Server default model"})}const route="/api/agent/web-shell/v1/workspaces/create";const body=Buffer.from(JSON.stringify({displayName:"Local workspace",idempotencyKey:"managed-local-default-workspace-v1"}));const bootstrap=await fetch(`${javaUrl}${route}`,{method:"POST",headers:{...signedManagedHeaders({method:"POST",path:route,body,signingKey:state.signingKey,tenantId,actorId}),"Content-Type":"application/json"},body,signal:AbortSignal.timeout(3e4)});if(!bootstrap.ok){const message=(await bootstrap.text()).slice(0,2e3);throw new Error(`Local Workspace admission failed (${bootstrap.status}): ${message}`)}await bootstrap.body?.cancel();if(failure)throw failure;if(closing)throw new Error("Managed startup interrupted.");frontDoor=await runQwenServe({port:options.port,hostname:"127.0.0.1",mode:"http-bridge",token:state.publicToken,requireAuth:true,workspace:process.cwd(),serveWebShell:true,requireWebShell:true},{installSignalHandlers:false,preheatBridge:false,managedLocalWeb:{javaUrl,signingKey:state.signingKey,tenantId,actorId,productScope:`local:${state.installationId}`,agentId:"qwen-code",modelPresets}});frontDoor.server.once("close",()=>{if(!closing){writeStderrLine("qwen serve --managed: daemon listener closed.");void shutdown(1)}});ready=true;if(failure||closing){await frontDoor.close();throw failure??new Error("Managed startup interrupted.")}writeStdoutLine(`Managed workspaces: ${path4.join(directory,"workspaces")}`);writeStdoutLine(`WebShell: ${frontDoor.url}/#token=${encodeURIComponent(state.publicToken)}`);return{url:frontDoor.url,resolvedToken:state.publicToken,webShellMounted:true,finished,close:__name(()=>shutdown(0),"close")}}catch(error){await shutdown(1);throw error}}__name(runManagedLocalServe,"runManagedLocalServe");export{managedLocalJavaEnvironment,runManagedLocalServe};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
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-OU7CEG7Q.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-32XHDDIA.js";import"./chunk-46VUDNCL.js";import"./chunk-MKH3EH7O.js";import"./chunk-FKZ46GKL.js";import"./chunk-SP6CQ3MO.js";import"./chunk-HW6SU6MX.js";import"./chunk-ZHHFNZ5J.js";import"./chunk-AKWYMQKU.js";import"./chunk-MZUOREFD.js";import"./chunk-CF6SZJNP.js";import"./chunk-7XZVMIY5.js";import"./chunk-CGDFZEER.js";import"./chunk-ZZJXFLVM.js";import"./chunk-RKDS7A4H.js";import"./chunk-KZNYALFU.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-2JGTWRZJ.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-AFO5ER23.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","@qwen-code","qwen-code")}__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};
|
|
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-CK3OKTTL.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-3EZ5GCUT.js";import"./chunk-46VUDNCL.js";import"./chunk-MKH3EH7O.js";import"./chunk-E3KWSRJN.js";import"./chunk-FRVXSKL4.js";import"./chunk-HW6SU6MX.js";import"./chunk-ZHHFNZ5J.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"./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"./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-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-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","@qwen-code","qwen-code")}__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
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2026 Qwen Code
|
|
@@ -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-7453BHJO.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-GHIFIXNX.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-OU7CEG7Q.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-32XHDDIA.js";import"./chunk-46VUDNCL.js";import"./chunk-MKH3EH7O.js";import"./chunk-FKZ46GKL.js";import"./chunk-SP6CQ3MO.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-HTAUIJB4.js";import{EditTool}from"./chunk-7RNOS7R4.js";import"./chunk-U3Q72OGV.js";import"./chunk-UJP2MPBI.js";import"./chunk-AKWYMQKU.js";import"./chunk-MZUOREFD.js";import"./chunk-CF6SZJNP.js";import"./chunk-7XZVMIY5.js";import"./chunk-CGDFZEER.js";import"./chunk-ZZJXFLVM.js";import"./chunk-RKDS7A4H.js";import"./chunk-KZNYALFU.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-2JGTWRZJ.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-AFO5ER23.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-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`
|
|
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-6NTGZXQL.js → managed-runtime-bootstrap-3BP5JRJX.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-IIHUDJX7.js";import"./chunk-36TKFM4Z.js";import"./chunk-YJ6APXNB.js";import"./chunk-MXZXQUVP.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};
|