@qwen-code/qwen-code 0.25.2-preview.1 → 0.25.2
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-CF4NN4Y7.js → MaxSizedBox-CGJP7S5S.js} +1 -1
- package/chunks/{StandaloneSessionPicker-Q23KTB6U.js → StandaloneSessionPicker-H6NONKPP.js} +1 -1
- package/chunks/{acp-subagent-executor-LXOLDTFY.js → acp-subagent-executor-7OCKCTA5.js} +1 -1
- package/chunks/{acpAgent-QRKZVQAG.js → acpAgent-VCKTBLFO.js} +3 -3
- package/chunks/{advisor-VZZJU7BR.js → advisor-UQJ45FLG.js} +1 -1
- package/chunks/{agent-LP66VBC4.js → agent-KMSCVRSG.js} +1 -1
- package/chunks/{agent-headless-W5P4KPX4.js → agent-headless-3FWQ5QNO.js} +1 -1
- package/chunks/{agent-host-client-OW4HBXRL.js → agent-host-client-PXIIFCCS.js} +1 -1
- package/chunks/{agent-host-connections-D7IC6WWL.js → agent-host-connections-QUYGQNJX.js} +1 -1
- package/chunks/{anthropicContentGenerator-6I25Q3Y6.js → anthropicContentGenerator-MDETV5LU.js} +1 -1
- package/chunks/{batch-7E5KJ625.js → batch-RQO2HWFV.js} +1 -1
- package/chunks/{bridge-BITC2AVN.js → bridge-OA3GEU2I.js} +1 -1
- package/chunks/{channel-settings-store-VAVG6ONF.js → channel-settings-store-YN23NP2H.js} +1 -1
- package/chunks/{chunk-4NCTKE4Z.js → chunk-2PQ5ZRTI.js} +1 -1
- package/chunks/{chunk-OJHTHXBC.js → chunk-32UFT5HU.js} +1 -1
- package/chunks/{chunk-2HJZ3OYW.js → chunk-3C34EMBZ.js} +1 -1
- package/chunks/{chunk-UXFLNZNB.js → chunk-3FPPMGVC.js} +1 -1
- package/chunks/{chunk-74YXI5IJ.js → chunk-445NIH5T.js} +1 -1
- package/chunks/{chunk-MXXYBMBZ.js → chunk-45EKBDFD.js} +1 -1
- package/chunks/{chunk-JV5FCFG4.js → chunk-4WFWZWR3.js} +1 -1
- package/chunks/{chunk-AAOAX46J.js → chunk-56NX3ASC.js} +1 -1
- package/chunks/{chunk-IBS4PHD2.js → chunk-5FY6TL3Z.js} +1 -1
- package/chunks/{chunk-UGI3XPRM.js → chunk-5GJPVNHI.js} +1 -1
- package/chunks/{chunk-7BZGY7AH.js → chunk-5XAVUYY6.js} +6 -6
- package/chunks/{chunk-V3WNU4F5.js → chunk-655XEN5H.js} +1 -1
- package/chunks/{chunk-APX7ODYT.js → chunk-6PHAGUA6.js} +1 -1
- package/chunks/{chunk-CD6C4OHZ.js → chunk-7YX6LW5H.js} +1 -1
- package/chunks/{chunk-C2NFZSGI.js → chunk-AAVRYR5T.js} +1 -1
- package/chunks/{chunk-EO35BRIG.js → chunk-ANUAITTH.js} +1 -1
- package/chunks/{chunk-CNQ6AOFN.js → chunk-AZ5GFEKG.js} +1 -1
- package/chunks/{chunk-KAEW65QP.js → chunk-B5XDGUAK.js} +1 -1
- package/chunks/{chunk-X6QHNKUW.js → chunk-BCNBZOGV.js} +1 -1
- package/chunks/{chunk-W5DIWPQB.js → chunk-BDXWLZJD.js} +1 -1
- package/chunks/{chunk-ZASVUARY.js → chunk-BPX4A433.js} +1 -1
- package/chunks/{chunk-CDSI44GJ.js → chunk-BUI6W6CU.js} +1 -1
- package/chunks/{chunk-ZEYCGUHI.js → chunk-BVARURDD.js} +1 -1
- package/chunks/{chunk-PZ5UPKIG.js → chunk-BW5CHWEJ.js} +2 -2
- package/chunks/{chunk-7TUP75C2.js → chunk-C4DSH4A3.js} +1 -1
- package/chunks/{chunk-R4KMBENY.js → chunk-CCBWBPJL.js} +1 -1
- package/chunks/{chunk-TU6DWKVI.js → chunk-CKJ3OUIV.js} +2 -2
- package/chunks/{chunk-SG5P4CK4.js → chunk-CRZ7QRFB.js} +1 -1
- package/chunks/{chunk-UYFL7K4Z.js → chunk-CTEBIP2S.js} +1 -1
- package/chunks/{chunk-WSIDVWGO.js → chunk-DBOWUORN.js} +1 -1
- package/chunks/{chunk-NAHKSVYI.js → chunk-DPBXGGQX.js} +1 -1
- package/chunks/{chunk-BMOJDKDZ.js → chunk-DSSSLNXD.js} +3 -3
- package/chunks/{chunk-FP2RLPWJ.js → chunk-EKGFFEH4.js} +1 -1
- package/chunks/{chunk-L7W3J427.js → chunk-EMEQR2LX.js} +1 -1
- package/chunks/{chunk-YRYMLJAC.js → chunk-ENUYA7BO.js} +1 -1
- package/chunks/{chunk-4CWBH6LP.js → chunk-EORORGZC.js} +1 -1
- package/chunks/{chunk-RBH3BOVF.js → chunk-EUK64V6Z.js} +1 -1
- package/chunks/{chunk-AII4DN7M.js → chunk-FBV4LUUL.js} +1 -1
- package/chunks/{chunk-YVEPPENZ.js → chunk-FFLFTXO7.js} +1 -1
- package/chunks/{chunk-2HSFO66N.js → chunk-FHXH3GSI.js} +1 -1
- package/chunks/{chunk-RH6PMH32.js → chunk-FVBDVZD7.js} +1 -1
- package/chunks/{chunk-Y2HLDUZG.js → chunk-I2D2ZUKF.js} +1 -1
- package/chunks/{chunk-6PUZWUMQ.js → chunk-I3FZ733S.js} +1 -1
- package/chunks/{chunk-GG7RNHZW.js → chunk-IFAUFERF.js} +5 -5
- package/chunks/{chunk-JQ7BCB3L.js → chunk-IYFUH3JB.js} +1 -1
- package/chunks/{chunk-VAMQAYF3.js → chunk-JB5I5QAD.js} +1 -1
- package/chunks/{chunk-Z3UZTCKY.js → chunk-JD3QDS7D.js} +1 -1
- package/chunks/{chunk-TFVPY43T.js → chunk-JG2UNQOW.js} +1 -1
- package/chunks/{chunk-E4MRBL4O.js → chunk-JSXHTTFE.js} +1 -1
- package/chunks/{chunk-QTYA6TES.js → chunk-LJLS3MDJ.js} +1 -1
- package/chunks/{chunk-RZISIEQL.js → chunk-MEIW5WVJ.js} +1 -1
- package/chunks/{chunk-ZD4U3GR4.js → chunk-MGL36H3B.js} +1 -1
- package/chunks/{chunk-HXA3X4PB.js → chunk-MJUFVFH3.js} +1 -1
- package/chunks/{chunk-SYIDPXVT.js → chunk-MSR6LYHS.js} +1 -1
- package/chunks/{chunk-4MJ67O5W.js → chunk-MTXJRB7G.js} +2 -2
- package/chunks/{chunk-F5P3BWS7.js → chunk-MXFBSMIM.js} +1 -1
- package/chunks/{chunk-W6TNBCKX.js → chunk-MYHJ4WUH.js} +1 -1
- package/chunks/{chunk-CWU5NJOB.js → chunk-NHXKNS7F.js} +1 -1
- package/chunks/{chunk-6OIJIF6G.js → chunk-NT74NPQT.js} +1 -1
- package/chunks/{chunk-O47FCWNF.js → chunk-NWXW4UNC.js} +1 -1
- package/chunks/{chunk-JASL4RZR.js → chunk-O77LM4EW.js} +1 -1
- package/chunks/{chunk-ZDNTENP2.js → chunk-OB7T2MDO.js} +1 -1
- package/chunks/{chunk-L7WFW57T.js → chunk-PODFLAH7.js} +1 -1
- package/chunks/{chunk-R3ZMQ7WR.js → chunk-Q2G675WT.js} +1 -1
- package/chunks/{chunk-H3QROVUO.js → chunk-QT27SK62.js} +1 -1
- package/chunks/{chunk-UELAXFT7.js → chunk-QZPNBV4F.js} +1 -1
- package/chunks/{chunk-B3L4LODR.js → chunk-RV54BGL2.js} +1 -1
- package/chunks/{chunk-KLXL3FSI.js → chunk-SFETIBPP.js} +1 -1
- package/chunks/{chunk-F3YGAXZ5.js → chunk-SGKINIQB.js} +1 -1
- package/chunks/{chunk-MBPT3YYO.js → chunk-SHJNP7OV.js} +1 -1
- package/chunks/{chunk-U3YSYIQE.js → chunk-SPFRORFN.js} +1 -1
- package/chunks/{chunk-S3B4TZVJ.js → chunk-SPLINFM7.js} +1 -1
- package/chunks/{chunk-ORIS5AVH.js → chunk-SYO5FPHL.js} +1 -1
- package/chunks/{chunk-AGHGPOH6.js → chunk-TEE4MM5S.js} +1 -1
- package/chunks/{chunk-WHF3HYZI.js → chunk-TPZTO4K3.js} +1 -1
- package/chunks/{chunk-KJO757RN.js → chunk-UY2CSL5W.js} +1 -1
- package/chunks/{chunk-VCTZRPKP.js → chunk-W7QYXFWW.js} +1 -1
- package/chunks/{chunk-T3ECMT6I.js → chunk-WQOZJ6V7.js} +2 -2
- package/chunks/{chunk-INEI2ZW2.js → chunk-WZK7RC36.js} +1 -1
- package/chunks/{chunk-Y5JLH3SN.js → chunk-X22435IN.js} +4 -4
- package/chunks/{chunk-WHNAY3QQ.js → chunk-X2KF6AUQ.js} +1 -1
- package/chunks/{chunk-MUEIZGTI.js → chunk-YHPHQX6M.js} +1 -1
- package/chunks/{chunk-5OOO3YIH.js → chunk-YL7QMYOX.js} +1 -1
- package/chunks/{chunk-43E3XC2W.js → chunk-YQEOEO5V.js} +1 -1
- package/chunks/{chunk-624P32LD.js → chunk-YZ374XTK.js} +1 -1
- package/chunks/{codex-subagent-executor-2MPLWNLD.js → codex-subagent-executor-MC3QB2AN.js} +1 -1
- package/chunks/{config-utils-MJEEBLQW.js → config-utils-FYT7PUIC.js} +1 -1
- package/chunks/{contextCommand-BP566QVE.js → contextCommand-DXMSMSR7.js} +1 -1
- package/chunks/{core-runtime-BOAIFYAZ.js → core-runtime-ZLB6QZ3Z.js} +1 -1
- package/chunks/{create-sub-session-HJVK7AXV.js → create-sub-session-YUI3G5AF.js} +1 -1
- package/chunks/{daemon-git-worktree-guard-KA2Y6FHL.js → daemon-git-worktree-guard-5PYZMC6T.js} +1 -1
- package/chunks/{daemon-status-provider-JGR5JT2T.js → daemon-status-provider-GC567FVE.js} +1 -1
- package/chunks/{daemon-trust-policy-EP4DHXOW.js → daemon-trust-policy-LLD2UMPF.js} +1 -1
- package/chunks/{daemon-trust-policy-monitor-W3VZRKOK.js → daemon-trust-policy-monitor-MRMB2CRJ.js} +1 -1
- package/chunks/{deferred-core-runtime-Q3JH7XDL.js → deferred-core-runtime-4HLTINJ6.js} +1 -1
- package/chunks/{edit-S7DCBMAL.js → edit-CZ6FEXDU.js} +1 -1
- package/chunks/{enterPlanMode-UX7B6KWX.js → enterPlanMode-O3CJ3I2J.js} +1 -1
- package/chunks/{environment-ZBW6HDG3.js → environment-OJWH4FYL.js} +1 -1
- package/chunks/{errors-7ZRLUHEB.js → errors-NWKSQVL3.js} +1 -1
- package/chunks/{execution-tool-R244Q3GW.js → execution-tool-7UCADALN.js} +1 -1
- package/chunks/{execution-worker-JR44JTC4.js → execution-worker-LWHQMPBV.js} +1 -1
- package/chunks/{exitPlanMode-2PTTZXGO.js → exitPlanMode-JDM6ZZWI.js} +1 -1
- package/chunks/{fast-path-NQQ42XUR.js → fast-path-4WHPMNMD.js} +1 -1
- package/chunks/{glob-4JP6RQNK.js → glob-LAU4YJ6J.js} +1 -1
- package/chunks/{goal-tools-MO7NIH7B.js → goal-tools-AF2FQO3H.js} +1 -1
- package/chunks/{handleAutoUpdate-STUVMCIU.js → handleAutoUpdate-WBWK4775.js} +1 -1
- package/chunks/{i18n-UTIILRKE.js → i18n-O4Q2KHOA.js} +1 -1
- package/chunks/{initializer-YI2WT6LZ.js → initializer-2AH3EKBL.js} +1 -1
- package/chunks/{installationInfo-PW2JHHJV.js → installationInfo-77WYXG4W.js} +1 -1
- package/chunks/{list-SAOL2OZI.js → list-RAU3ZJQS.js} +1 -1
- package/chunks/{llm-LMY62H6Z.js → llm-MJMQ34KB.js} +4 -4
- package/chunks/{llm-content-generator-6RPOZ2YR.js → llm-content-generator-MJPR2TWC.js} +1 -1
- package/chunks/{loadedSettingsAdapter-RNXWDDE2.js → loadedSettingsAdapter-WRWWNGHZ.js} +1 -1
- package/chunks/{local-execution-environment-GIWY2LO6.js → local-execution-environment-VVJ7OYBT.js} +1 -1
- package/chunks/{loggingContentGenerator-AOKEDXK6.js → loggingContentGenerator-722BJL7T.js} +1 -1
- package/chunks/{manage-memory-WKPWLYDD.js → manage-memory-GN56UQHG.js} +1 -1
- package/chunks/{managed-npm-update-LFFWFATA.js → managed-npm-update-5VE662JS.js} +1 -1
- package/chunks/{managed-runtime-attestation-worker-IV6ZNIAK.js → managed-runtime-attestation-worker-ASGGZMFM.js} +1 -1
- package/chunks/{managed-runtime-session-worker-3NU4FOXD.js → managed-runtime-session-worker-YUSO7WFB.js} +1 -1
- package/chunks/{mcp-RDDGN4JK.js → mcp-6D236MEH.js} +1 -1
- package/chunks/{model-call-collection-JARTJD6S.js → model-call-collection-UAE2W6VV.js} +1 -1
- package/chunks/{model-configuration-7H6PEOLY.js → model-configuration-VHPSBCQI.js} +1 -1
- package/chunks/{modelConfigUtils-Q63ZZTXY.js → modelConfigUtils-XKDXYQRJ.js} +1 -1
- package/chunks/{monitor-HLO366TQ.js → monitor-JIKXBXDK.js} +1 -1
- package/chunks/{nonInteractiveCli-JO5EG6OK.js → nonInteractiveCli-IXTK5V4Q.js} +1 -1
- package/chunks/{nonInteractiveToolExecutor-T7AKBX25.js → nonInteractiveToolExecutor-3MSROJV5.js} +1 -1
- package/chunks/{notebook-edit-XKULPMG7.js → notebook-edit-VDWBIBMG.js} +1 -1
- package/chunks/{omni-H3GFC6KR.js → omni-MEUE65XC.js} +1 -1
- package/chunks/{openaiContentGenerator-RT4S6OYR.js → openaiContentGenerator-KNZTYVNK.js} +1 -1
- package/chunks/{openaiResponsesContentGenerator-JD4ZBCAL.js → openaiResponsesContentGenerator-G7GRJXES.js} +1 -1
- package/chunks/{pidfile-JXCPPGC6.js → pidfile-HMEKKPWO.js} +1 -1
- package/chunks/{processUtils-FF7LHGHW.js → processUtils-KHWNT3KU.js} +1 -1
- package/chunks/{prompt-terminal-ledger-VLIEJ5BB.js → prompt-terminal-ledger-EY72RU3D.js} +1 -1
- package/chunks/{qwenContentGenerator-6SGQI4ES.js → qwenContentGenerator-A7WREYLV.js} +1 -1
- package/chunks/{reactive-degrade-2UJPX4AU.js → reactive-degrade-O6WBGQ5X.js} +1 -1
- package/chunks/{read-file-27DWTM5N.js → read-file-A4MQWC6T.js} +1 -1
- package/chunks/{resumeHistoryUtils-KRF2LD7T.js → resumeHistoryUtils-KNUVMH5J.js} +1 -1
- package/chunks/{review-IPFFTVGV.js → review-OC76PLQ4.js} +1 -1
- package/chunks/{ripGrep-75QL35XD.js → ripGrep-JR6DHTIW.js} +1 -1
- package/chunks/{run-qwen-serve-WW74NSUL.js → run-qwen-serve-NFPGPJJ2.js} +2 -2
- package/chunks/{runtime-Z2NIOF6Y.js → runtime-BPHFAZOP.js} +1 -1
- package/chunks/{sandboxConfig-WMQAKX7Q.js → sandboxConfig-KXTV3QBG.js} +1 -1
- package/chunks/{scheduled-tasks-LMJJ5ZM7.js → scheduled-tasks-2GNFZH4N.js} +1 -1
- package/chunks/{scheduler-KHWWXW6H.js → scheduler-CKLZCETX.js} +1 -1
- package/chunks/{search-memory-WEO3M674.js → search-memory-ICNU2EJA.js} +1 -1
- package/chunks/{send-message-E2EVXDU4.js → send-message-T32PFXX5.js} +1 -1
- package/chunks/{serve-E7ZGE7PD.js → serve-O7XBFM36.js} +1 -1
- package/chunks/{server-SSHP5IO4.js → server-7H2EGX7C.js} +3 -3
- package/chunks/{session-UWUQU3NV.js → session-SO4TKKO3.js} +1 -1
- package/chunks/{session-attachments-root-I35OUD7P.js → session-attachments-root-QPBJB3Y2.js} +1 -1
- package/chunks/{session-execution-engine-selector-S7HXLYKG.js → session-execution-engine-selector-73JQ7AG6.js} +1 -1
- package/chunks/{session-pr-refresh-34FLQB2Z.js → session-pr-refresh-XPDBRBQV.js} +1 -1
- package/chunks/{sessionService-BBC2563F.js → sessionService-DDLWVLNC.js} +1 -1
- package/chunks/{settings-BXCTAYMU.js → settings-TUEKBNAX.js} +1 -1
- package/chunks/{shell-ORZNRZKX.js → shell-SXSN7UYK.js} +1 -1
- package/chunks/{skill-3MJ6V2VQ.js → skill-XAYT7HGV.js} +1 -1
- package/chunks/{skill-settings-A7TTYJGH.js → skill-settings-X3O75XUN.js} +1 -1
- package/chunks/{spawnChannel-UPHPUPIJ.js → spawnChannel-3523LPUW.js} +1 -1
- package/chunks/{standalone-update-GGHQ54QB.js → standalone-update-T7AUODLV.js} +1 -1
- package/chunks/{start-opentui-ui-O6WMWLGS.js → start-opentui-ui-IKBADQQS.js} +1 -1
- package/chunks/{startInteractiveUI-N3ZPR2FK.js → startInteractiveUI-PV2JETB4.js} +1 -1
- package/chunks/{team-create-EYLFAQVU.js → team-create-ZKTBFE7Z.js} +1 -1
- package/chunks/{team-plan-approval-2WFSX4XE.js → team-plan-approval-SCTAN2HM.js} +1 -1
- package/chunks/{terminal-image-renderer-A5HEJZTW.js → terminal-image-renderer-EDBYTK3B.js} +1 -1
- package/chunks/{theme-manager-TQHNJSKQ.js → theme-manager-ZLXHLO2Y.js} +1 -1
- package/chunks/{tool-call-UBLAA45C.js → tool-call-ULUE3W3P.js} +1 -1
- package/chunks/{tool-result-media-53AD3EHK.js → tool-result-media-VXS7QTX7.js} +1 -1
- package/chunks/{tool-search-D6PSBDDZ.js → tool-search-VWM6VCVU.js} +1 -1
- package/chunks/{total-session-admission-CUMMWSM2.js → total-session-admission-FZDBG232.js} +1 -1
- package/chunks/{trustedFolders-TERXKVJ6.js → trustedFolders-VIPEDZNB.js} +1 -1
- package/chunks/{update-relaunch-PXCI66U2.js → update-relaunch-N6TNUHQE.js} +1 -1
- package/chunks/{updateCheck-2P4ANPL7.js → updateCheck-367IR3FW.js} +1 -1
- package/chunks/{upload-config-G2WZG4DM.js → upload-config-5W4WTLML.js} +1 -1
- package/chunks/{useAutoAcceptIndicator-H7I7JP34.js → useAutoAcceptIndicator-SGT7EBCJ.js} +1 -1
- package/chunks/{validateNonInterActiveAuth-VLRV5LCK.js → validateNonInterActiveAuth-7WEBPZ4S.js} +1 -1
- package/chunks/{version-AOKDKXXZ.js → version-3OKRQ6LC.js} +1 -1
- package/chunks/{web-fetch-OUJS56AV.js → web-fetch-BV7BK5NT.js} +1 -1
- package/chunks/{web-search-3S4ZIGLP.js → web-search-DFQ74G7V.js} +1 -1
- package/chunks/{workflow-6W4WB4L5.js → workflow-EXSCHLQK.js} +1 -1
- package/chunks/{workspace-agents-7GB2RLY5.js → workspace-agents-HPOPFXKJ.js} +1 -1
- package/chunks/{workspace-providers-status-OMD57CUW.js → workspace-providers-status-UQCSR2PB.js} +1 -1
- package/chunks/{workspace-registration-store-WKLFVMQ2.js → workspace-registration-store-Q5U4WD5M.js} +1 -1
- package/chunks/{workspace-registry-6WJOPYIS.js → workspace-registry-I2O2LXTZ.js} +1 -1
- package/chunks/{workspace-runtime-coordinator-XG7G7DG3.js → workspace-runtime-coordinator-MVVDZYYX.js} +1 -1
- package/chunks/{workspace-service-YLX46RJM.js → workspace-service-CFJ2EUB7.js} +1 -1
- package/chunks/{workspace-skills-status-JZZR7QHN.js → workspace-skills-status-LLNIK3NS.js} +1 -1
- package/chunks/{workspace-trust-reconciler-AO3I5KYO.js → workspace-trust-reconciler-VLGJXLCZ.js} +1 -1
- package/chunks/{write-file-MGYLC32T.js → write-file-RG7HHIYP.js} +1 -1
- package/chunks/{zoom-image-TZ527ASZ.js → zoom-image-AKW6CA4K.js} +1 -1
- package/cli.js +2 -2
- package/execution-worker.js +1 -1
- package/export-transcript-document.js +1 -1
- package/package.json +3 -3
- package/web-shell/assets/{PierreFilePreview-Cq9imG0c.js → PierreFilePreview-Cij36lF-.js} +1 -1
- package/web-shell/assets/{SpreadsheetPreview-Blho0kkO.js → SpreadsheetPreview-kDlHrK21.js} +1 -1
- package/web-shell/assets/{WorkspaceFileBrowser-DjeX-ArR.js → WorkspaceFileBrowser-DBXW9l-s.js} +1 -1
- package/web-shell/assets/{abnfDiagram-VCTEODGH-mEfLgGao.js → abnfDiagram-VCTEODGH-DBrfOx4O.js} +1 -1
- package/web-shell/assets/{agents-route-Bg4_tLdL.js → agents-route-6E_3XRjk.js} +1 -1
- package/web-shell/assets/{arc-DEVpMJqB.js → arc-RwrvKU6y.js} +1 -1
- package/web-shell/assets/{architectureDiagram-5GKGNRK7-CGhqKvd1.js → architectureDiagram-5GKGNRK7-B2_hfNn6.js} +1 -1
- package/web-shell/assets/{blockDiagram-NRAW4CY4-DxpWdCdl.js → blockDiagram-NRAW4CY4-C755qTFO.js} +1 -1
- package/web-shell/assets/{c4Diagram-UCG6FXSJ-CE1W0_yu.js → c4Diagram-UCG6FXSJ-CARC2uHQ.js} +1 -1
- package/web-shell/assets/channel-U9JRrjem.js +1 -0
- package/web-shell/assets/{chunk-2Q5K7J3B-ibHTXjoH.js → chunk-2Q5K7J3B-BS1ldEp9.js} +1 -1
- package/web-shell/assets/{chunk-5VM5RSS4-BEZ2-gCE.js → chunk-5VM5RSS4-DckOEd3N.js} +1 -1
- package/web-shell/assets/{chunk-F27PBJKO-CKyPZ7Jh.js → chunk-F27PBJKO-fZstOLLL.js} +1 -1
- package/web-shell/assets/{chunk-G27WJ6UU-WHNRb7iQ.js → chunk-G27WJ6UU-Bf4QkrJ7.js} +1 -1
- package/web-shell/assets/{chunk-JWPE2WC7-Dm4G-fLP.js → chunk-JWPE2WC7-uBW51XO_.js} +1 -1
- package/web-shell/assets/{chunk-LCL6LL3I-BvTm39E-.js → chunk-LCL6LL3I-D2MYZdE_.js} +1 -1
- package/web-shell/assets/{chunk-POPQ4Y6H-C0zAbzIo.js → chunk-POPQ4Y6H-CzTHTST7.js} +1 -1
- package/web-shell/assets/{chunk-SVP7TREG-B36K-VPq.js → chunk-SVP7TREG-fL48tjL5.js} +1 -1
- package/web-shell/assets/{chunk-XXDRQBXY-D1opdtZ1.js → chunk-XXDRQBXY-R1jjDz-e.js} +1 -1
- package/web-shell/assets/classDiagram-DTDB5LWJ-r255RW6f.js +1 -0
- package/web-shell/assets/classDiagram-v2-JRS7N3AN-r255RW6f.js +1 -0
- package/web-shell/assets/{cose-bilkent-JH36ORCC-S_IO4ZW5.js → cose-bilkent-JH36ORCC-DTK6Alrt.js} +1 -1
- package/web-shell/assets/{cynefin-OW5HDTMX-CGUKfurr.js → cynefin-OW5HDTMX-C1JYDjN4.js} +1 -1
- package/web-shell/assets/{cynefinDiagram-5FMLGOSQ-BqUpO_VD.js → cynefinDiagram-5FMLGOSQ-C3bR18IM.js} +1 -1
- package/web-shell/assets/{dagre-3AP2YEHR-CiKqZpUi.js → dagre-3AP2YEHR-D4oUlW7g.js} +1 -1
- package/web-shell/assets/{diagram-S7CK7UJ4-B3CQED4o.js → diagram-S7CK7UJ4-m-a-vk_2.js} +1 -1
- package/web-shell/assets/{diagram-UQ7AKVKN-BewunX5H.js → diagram-UQ7AKVKN-CVGSVvpJ.js} +1 -1
- package/web-shell/assets/{diagram-VSXAHHWV-C5j1hiVn.js → diagram-VSXAHHWV-DcLovKfd.js} +1 -1
- package/web-shell/assets/{diagram-VX7I27RA-CWDIIA61.js → diagram-VX7I27RA-DAwY09qQ.js} +1 -1
- package/web-shell/assets/{diagram-Z3DM3KII-COa1V8UD.js → diagram-Z3DM3KII-D4BWV8Yb.js} +1 -1
- package/web-shell/assets/{ebnfDiagram-PWID7BFC-CP33EIO8.js → ebnfDiagram-PWID7BFC-AhqQLlAR.js} +1 -1
- package/web-shell/assets/{erDiagram-SSCWMZ5O-V2pL2JAp.js → erDiagram-SSCWMZ5O-DcIpsPuK.js} +1 -1
- package/web-shell/assets/{flowDiagram-A5DVABFB-CF-YQlR_.js → flowDiagram-A5DVABFB-Cdu3v56D.js} +1 -1
- package/web-shell/assets/{ganttDiagram-EL5Y4UJY-TXUid-Q2.js → ganttDiagram-EL5Y4UJY-D8o98Muo.js} +1 -1
- package/web-shell/assets/{gitGraphDiagram-WWUBYQGX-QNcIYsgn.js → gitGraphDiagram-WWUBYQGX-fIAd56jC.js} +1 -1
- package/web-shell/assets/{index-CKa6aZMZ.js → index-CJmvuO8Q.js} +1 -1
- package/web-shell/assets/{index-N9F4X44H.js → index-DSh5Yfsf.js} +5 -5
- package/web-shell/assets/{infoDiagram-RXCK75RN-Dn1biwuc.js → infoDiagram-RXCK75RN-dPnP0Koe.js} +1 -1
- package/web-shell/assets/{ishikawaDiagram-5VMMS53U-iBYO7WCt.js → ishikawaDiagram-5VMMS53U-f9Oq8YH7.js} +1 -1
- package/web-shell/assets/{journeyDiagram-EYS64GPL-D98LzO4k.js → journeyDiagram-EYS64GPL-CqwSlUQ1.js} +1 -1
- package/web-shell/assets/{kanban-definition-3QL26DDD-lQMIgDSM.js → kanban-definition-3QL26DDD-Bh_KTp2S.js} +1 -1
- package/web-shell/assets/{layout-BgOy6tFo.js → layout-0e-hGnuM.js} +1 -1
- package/web-shell/assets/{linear-En8RXsBs.js → linear-BtxWFISv.js} +1 -1
- package/web-shell/assets/{mermaid.core-BneKXyZr.js → mermaid.core-Dik4l-jM.js} +6 -6
- package/web-shell/assets/{mindmap-definition-FBJOCRG2-NkP_9BC4.js → mindmap-definition-FBJOCRG2-B7gext3e.js} +1 -1
- package/web-shell/assets/{pegDiagram-XKGWAZYB-B0ie-nkt.js → pegDiagram-XKGWAZYB-BfyKzGY0.js} +1 -1
- package/web-shell/assets/{pieDiagram-E7YTZNPT-Qa86cFZc.js → pieDiagram-E7YTZNPT-vfeVyHgh.js} +1 -1
- package/web-shell/assets/{quadrantDiagram-AXDQQJYC-CkjUzR0e.js → quadrantDiagram-AXDQQJYC-DGAZmngq.js} +1 -1
- package/web-shell/assets/{railroadDiagram-O6MQD6OU-mN7KpgJG.js → railroadDiagram-O6MQD6OU-Dgxiy8W5.js} +1 -1
- package/web-shell/assets/{requirementDiagram-EFPCY7ZU-Bmn2z6x2.js → requirementDiagram-EFPCY7ZU-D7TFokdR.js} +1 -1
- package/web-shell/assets/{sankeyDiagram-P5KCCOFB-CYWnwpoW.js → sankeyDiagram-P5KCCOFB-BZU_UYd-.js} +1 -1
- package/web-shell/assets/{sequenceDiagram-WJ2MYXX4-BFyWlR1P.js → sequenceDiagram-WJ2MYXX4-Bz94qtvq.js} +1 -1
- package/web-shell/assets/{sizeCapture-X5ZJPWSS-BwCPrn2w.js → sizeCapture-X5ZJPWSS-DVlzIShY.js} +1 -1
- package/web-shell/assets/{stateDiagram-HBIQ2CUA-oqL3E0Ws.js → stateDiagram-HBIQ2CUA-CE9Il33j.js} +1 -1
- package/web-shell/assets/stateDiagram-v2-4QOOHH4V-BVL1rIGD.js +1 -0
- package/web-shell/assets/{swimlanes-XN3QIQJK-C3FAVL8g.js → swimlanes-XN3QIQJK-Cr2CyF9L.js} +1 -1
- package/web-shell/assets/swimlanesDiagram-VK2B7HYN-BeWJAUmf.js +8 -0
- package/web-shell/assets/{timeline-definition-24CTP7MA-BdwxFsPJ.js → timeline-definition-24CTP7MA-DWbRlUDe.js} +1 -1
- package/web-shell/assets/{vennDiagram-4TSXK5OY-j_G2AbSj.js → vennDiagram-4TSXK5OY-Bp5BiaRL.js} +1 -1
- package/web-shell/assets/{wardleyDiagram-VM6X3IG4-Dy_fHHBq.js → wardleyDiagram-VM6X3IG4-DoQIUrT8.js} +1 -1
- package/web-shell/assets/{xychartDiagram-S5SC5T6Z-CnLgG50x.js → xychartDiagram-S5SC5T6Z-BTO308Vv.js} +1 -1
- package/web-shell/index.html +1 -1
- package/web-shell/sw.js +1 -1
- package/web-shell/assets/channel-CHCXOu89.js +0 -1
- package/web-shell/assets/classDiagram-DTDB5LWJ-DXIqcod_.js +0 -1
- package/web-shell/assets/classDiagram-v2-JRS7N3AN-DXIqcod_.js +0 -1
- package/web-shell/assets/stateDiagram-v2-4QOOHH4V-Cmho6gw2.js +0 -1
- package/web-shell/assets/swimlanesDiagram-VK2B7HYN-D9Sfkn7b.js +0 -8
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{CLOSE_SWEEP_TIMEOUT_MS,GROUP_EXIT_EVIDENCE_TIMEOUT_MS,managedRuntimeLedgerFromEnvironment,signalProcessGroup}from"./chunk-R3GIVUCR.js";import{HOSTED_GLOB_TOO_COMPLEX,LocalShellResultCapture,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_SHELL_PUBLISHER_ROUTE,MANAGED_WORKSPACE_CONTEXT_FILES,MANAGED_WORKSPACE_CONTEXT_FILE_CHARS,ManagedRuntimeProviderProtocolError,ManagedShellPublisherRegistry,WORKSPACE_ACTIVATION_ROUTE,WORKSPACE_CAPABILITY_DIGEST,WORKSPACE_CONTEXT_CONFIG_REF,WorkspaceActivations,checkHostedGlobPattern,fitManagedRuntimeProviderResult,managedRuntimeProviderLimit,parseManagedRuntimeProviderRequest,parseManagedRuntimeProviderResult}from"./chunk-PMQ74TUZ.js";import{resolveManagedRuntimeBrokerBaseUrl}from"./chunk-6S5XOXJ2.js";import{MANAGED_RUNTIME_TOOL_RESULT_BODY_LIMIT_BYTES,OWNED_MANAGED_RUNTIME_ROUTES,authorizeManagedRuntime,handleManagedRuntimeJsonError,managedRuntimeJsonBody,managedRuntimeNoStore,nameManagedRuntimeIncarnation,ownedManagedRuntimeRouteGate,registerManagedRuntimeAttestationRoute}from"./chunk-IT34OWRH.js";import"./chunk-3SHHYK7S.js";import{require_express}from"./chunk-6SOKP7IN.js";import"./chunk-ELUOCI74.js";import"./chunk-IS7CHVXD.js";import{MANAGED_TOOL_FILE_HISTORY_MAX_BYTES,captureManagedToolExecutionContext,computeManagedContextDigest,historyPath,isCanonicalDecimalText,isManagedIdentifier,isWorkspaceStorageId,normalizeWorkspaceRelativePath,parseHostedFileHistoryState,parseToolPublicationBinding}from"./chunk-QIU62EU7.js";import{scrubAndReportInheritedLoaderEnv}from"./chunk-CVMMNPLX.js";import"./chunk-S7IKHQ6I.js";import{WriteFileTool}from"./chunk-ZEYCGUHI.js";import"./chunk-NZFR5IY7.js";import{EditTool}from"./chunk-KLXL3FSI.js";import"./chunk-UELAXFT7.js";import{GlobTool}from"./chunk-6OP7FXSJ.js";import"./chunk-6GLM4FUL.js";import{Client,Config,DEFAULT_INHERITED_ENV_VARS,EventSource,FileHistoryService,HookCommandCgroup,HookCommandIsolationUnavailableError,HookRegistry,HookRunner,ShellTool,StdioClientTransport,StreamableHTTPClientTransport,UnauthorizedError,auth,createFetchWithInit,deriveConfig,deserializeSnapshots,detectLineEnding,encodeTextFileContentAsync,extractWWWAuthenticateParams,firePostToolUseFailureHook,firePostToolUseHook,firePreToolUseHook,generateToolUseId,interpolateUrl,isModifiableDeclarativeTool,normalizeHeaders,serializeSnapshot}from"./chunk-GG7RNHZW.js";import"./chunk-R2EHHA2C.js";import"./chunk-ZLZF2ZDD.js";import{CallToolResultSchema,GetPromptResultSchema,JSONRPCMessageSchema,ListPromptsResultSchema,ListResourcesResultSchema,ListToolsResultSchema,ReadResourceResultSchema}from"./chunk-YK7NDQKM.js";import"./chunk-JUPGJYC2.js";import"./chunk-PHIPLV2I.js";import{isShellResultDisplay}from"./chunk-T7CHK6C2.js";import"./chunk-VZDZ34KK.js";import"./chunk-PT7NZBDY.js";import"./chunk-TWP72VRH.js";import{MANAGED_TOOL_RESULT_KINDS,MANAGED_TOOL_RESULT_LIMITS,MANAGED_TOOL_RESULT_PROTOCOL,MANAGED_TOOL_RESULT_ROUTES,ManagedSessionConflictError,ManagedSessionRecordError,ManagedToolProtocolError,assertManagedSessionDurableRef,assertManagedSessionKey,assertManagedSessionSequence,assertManagedSessionStableId,isOperationGrantSuccessor,managedToolDigest,parseManagedSessionRecordJson,parseManagedToolContentModification,parseManagedToolMediaContext,parseOperationGrant,parseToolResultPrefixRequest,parseToolResultPublishRequest,parseToolResultSealRequest,serializeManagedToolConfirmation}from"./chunk-R2AGF6ET.js";import"./chunk-OGI5HG6N.js";import"./chunk-ZQWGATC2.js";import"./chunk-EVVLG5RD.js";import"./chunk-LLX4BCWK.js";import"./chunk-QXQGUM3Y.js";import"./chunk-AG3SSCAF.js";import"./chunk-BMSATZXW.js";import"./chunk-GCIMHMRU.js";import"./chunk-EOMQENJY.js";import"./chunk-QVPT37XZ.js";import"./chunk-VMQO3VPA.js";import"./chunk-HATHFJPW.js";import"./chunk-XQJOZDV7.js";import"./chunk-CV2UAEZA.js";import"./chunk-GNQGC2DJ.js";import"./chunk-YPIUTOL3.js";import"./chunk-KLC3OD2M.js";import"./chunk-K6EQXZMK.js";import"./chunk-BG67XABA.js";import"./chunk-BEKROCWN.js";import"./chunk-Y77BXKWA.js";import"./chunk-LKE7NTQV.js";import"./chunk-UEO3N2FM.js";import"./chunk-JVJS2YFU.js";import"./chunk-G5PYYZMM.js";import"./chunk-D7XCQWP2.js";import"./chunk-OBOU4ZZM.js";import"./chunk-D6UTJ3SP.js";import"./chunk-MPHSE7M4.js";import"./chunk-FQQMMFT6.js";import"./chunk-JZK2WGXA.js";import"./chunk-LGKVMW44.js";import"./chunk-JIL7UY37.js";import"./chunk-JKXBHBE3.js";import"./chunk-FP2RLPWJ.js";import"./chunk-TFVPY43T.js";import"./chunk-S2ZKZXHX.js";import"./chunk-JANYB2IR.js";import"./chunk-EBMCWXGZ.js";import"./chunk-MYFKO4WS.js";import"./chunk-7KVWF3T4.js";import"./chunk-4ZRCV3JY.js";import{getShellContextEnvVars}from"./chunk-AH64K6DM.js";import"./chunk-YGLM5XPP.js";import"./chunk-4NPYOXJO.js";import{promptIdContext}from"./chunk-MWGB5RCF.js";import{getShellConfiguration}from"./chunk-XWEXQT3X.js";import"./chunk-NTRFETZB.js";import"./chunk-TL3SF2GA.js";import"./chunk-YIW3H46P.js";import"./chunk-7UK4WJWS.js";import"./chunk-4GP3PH7Z.js";import{sanitizeChildEnv}from"./chunk-LFKUPU57.js";import"./chunk-T2F7KYYR.js";import"./chunk-SW54YEPK.js";import"./chunk-APX7ODYT.js";import{captureHookExecutionOwner,runWithHookExecutionOwner}from"./chunk-7J2TOJMG.js";import"./chunk-AGEDDL7Z.js";import"./chunk-2NJJHZ52.js";import"./chunk-3YWXKSOI.js";import"./chunk-OW25BC3M.js";import"./chunk-2PMQL4KE.js";import"./chunk-V3XYE727.js";import"./chunk-S6RXVOY6.js";import"./chunk-BRPC43OM.js";import"./chunk-KAEW65QP.js";import"./chunk-WZDBBDRD.js";import{createAbortController}from"./chunk-476F6QIM.js";import"./chunk-4R67LXKL.js";import"./chunk-WW7MJFAN.js";import"./chunk-LG4NL2M7.js";import{ReadFileTool}from"./chunk-KBPIYGHG.js";import"./chunk-UQFTXKEB.js";import"./chunk-HDGTWJ24.js";import"./chunk-W5NWIGKO.js";import{FileReadOpenError,decodeBufferWithEncodingInfoAsync,digestFileReadSource,readFileHandleBytes,readTextContentRangeFromHandle}from"./chunk-JU2HHQR5.js";import"./chunk-6C4YRBLR.js";import"./chunk-37KFLBKZ.js";import"./chunk-PWOQASXT.js";import"./chunk-Z6AR5XE5.js";import"./chunk-7U7CWMP7.js";import"./chunk-77V43YOE.js";import{runWithInvocationContext}from"./chunk-SLD7H2FA.js";import"./chunk-7DOOXUDG.js";import"./chunk-P3RLMP7L.js";import"./chunk-R54OXALA.js";import"./chunk-HXA3X4PB.js";import"./chunk-TAAJ7TDB.js";import"./chunk-4ZBZL23U.js";import"./chunk-ZZZAYAJW.js";import"./chunk-XMANRGPK.js";import"./chunk-AWTUIQ7W.js";import"./chunk-KQX4H2D3.js";import"./chunk-BWU6AH5O.js";import"./chunk-BMHYEQTI.js";import"./chunk-CPVAVCGD.js";import"./chunk-SLPJ4OII.js";import"./chunk-4YLXNRRH.js";import"./chunk-65UCR6OZ.js";import"./chunk-CN2TQ3PU.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-I6S7NGX3.js";import"./chunk-SVAPAMMG.js";import"./chunk-3KUHQGOS.js";import{ToolNames}from"./chunk-2UNFJQ2D.js";import{createDebugLogger,registerSessionProjectDir,sessionIdContext,unregisterSessionModel,unregisterSessionProjectDir}from"./chunk-JAUJI56S.js";import"./chunk-I4H7NUVP.js";import"./chunk-EPODBRBP.js";import"./chunk-OKN3Z5C5.js";import"./chunk-XYB7GC5U.js";import"./chunk-2UOMCYQG.js";import"./chunk-I7L2TX4M.js";import"./chunk-MK3OONRA.js";import"./chunk-COGTQ5KZ.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__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 createReadStream2}from"node:fs";import path7 from"node:path";init_esbuild_shims();var MANAGED_CONTEXT_PROTOCOL="managed-context/1";var MANAGED_CONTEXT_BOOT_VERSION=2;var MANAGED_CONTEXT_READY_VERSION=2;var MANAGED_CONTEXT_BODY_LIMIT_BYTES=16*1024;var MANAGED_CONTEXT_ROUTES=Object.freeze([Object.freeze({key:"attest",method:"POST",path:"/internal/managed-runtime/v3/attest",protocolVersion:3,requestBodyLimitBytes:MANAGED_CONTEXT_BODY_LIMIT_BYTES,responseBodyLimitBytes:MANAGED_CONTEXT_BODY_LIMIT_BYTES,cacheControl:"no-store"}),Object.freeze({key:"context",method:"POST",path:"/internal/managed-runtime/v3/context",protocolVersion:3,requestBodyLimitBytes:MANAGED_CONTEXT_BODY_LIMIT_BYTES,responseBodyLimitBytes:MANAGED_CONTEXT_BODY_LIMIT_BYTES,cacheControl:"no-store"})]);var PROTOCOL_VERSION=MANAGED_CONTEXT_ROUTES[0].protocolVersion;var INVALID_BOOT_MESSAGE="Managed context boot document is invalid.";var MAXIMUM_MOUNT_ROOT_BYTES=4096;var MAXIMUM_SESSION_ID_LENGTH=512;var MAXIMUM_PORT=65535;var DIGEST_PATTERN=/^sha256:[0-9a-f]{64}$/;var BEARER_TOKEN_PATTERN=/^[A-Za-z0-9._~+/-]+=*$/;var MAXIMUM_TOKEN_LENGTH=512;var LONE_SURROGATE_PATTERN=/[\ud800-\udfff]/u;var ABSOLUTE_PATH_PATTERN=/^(?:\/|[A-Za-z]:[\\/]|\\\\)/;var BOOT_KEYS=Object.freeze(["capabilityDigest","epoch","isolationClass","leaseId","managedContext","mountRoot","provisionRequestId","runtimeIncarnation","runtimeInstanceId","storageId","tenantId","token","type","version","workspaceGeneration","workspaceId"]);var READY_KEYS=Object.freeze(["epoch","leaseId","managedContext","runtimeIncarnation","runtimeInstanceId","type","url","version"]);var ATTESTATION_KEYS=Object.freeze(["capabilityDigest","isolationClass","managedContext","mountRoot","protocolVersion","provisionRequestId","storageId","tenantId","workspaceGeneration","workspaceId"]);var INSTALLATION_KEYS=Object.freeze(["binding","contextDigest","managedContext","operationId","protocolVersion","sessionId"]);var BINDING_KEYS=Object.freeze(["contextConfigRef","contextRevision","cwdRelative","storageId","tenantId","workspaceGeneration","workspaceId"]);var ATTESTED_KEYS=Object.freeze(["provisionRequestId","tenantId","workspaceId","workspaceGeneration","storageId","mountRoot","capabilityDigest","isolationClass"]);var WORKSPACE_KEYS=Object.freeze(["tenantId","workspaceId","workspaceGeneration","storageId"]);var INVALID=Object.freeze({status:400,code:"managed_runtime_attestation_invalid"});var IDENTITY_CONFLICT=Object.freeze({status:409,code:"managed_runtime_identity_conflict"});var CONTEXT_CONFLICT=Object.freeze({status:409,code:"managed_context_conflict"});var CONTEXT_UNAVAILABLE=Object.freeze({status:409,code:"managed_context_unavailable"});function parseManagedContextBoot(value){const boot=readClosed(value,BOOT_KEYS);if(!boot||boot.type!=="boot"||boot.version!==MANAGED_CONTEXT_BOOT_VERSION||boot.managedContext!==MANAGED_CONTEXT_PROTOCOL||!isBearerToken(boot.token)||!isManagedIdentifier(boot.runtimeInstanceId)||!isManagedIdentifier(boot.runtimeIncarnation)||!isManagedIdentifier(boot.leaseId)||!isEpoch(boot.epoch)||!hasValidAttestedFields(boot)){throw new Error(INVALID_BOOT_MESSAGE)}return Object.freeze(boot)}__name(parseManagedContextBoot,"parseManagedContextBoot");function createManagedContextReady(boot,port){const identity=parseManagedContextBoot(boot);if(!Number.isInteger(port)||port<1||port>MAXIMUM_PORT){throw new Error("Managed context ready port is invalid.")}return Object.freeze({type:"ready",version:MANAGED_CONTEXT_READY_VERSION,managedContext:MANAGED_CONTEXT_PROTOCOL,runtimeInstanceId:identity.runtimeInstanceId,runtimeIncarnation:identity.runtimeIncarnation,leaseId:identity.leaseId,epoch:identity.epoch,url:`http://127.0.0.1:${port}`})}__name(createManagedContextReady,"createManagedContextReady");function createManagedContextAttestationResponse(boot){return attestationResponse(parseManagedContextBoot(boot))}__name(createManagedContextAttestationResponse,"createManagedContextAttestationResponse");function checkManagedContextAttestation(body2,boot){const identity=parseManagedContextBoot(boot);const request=readClosed(body2,ATTESTATION_KEYS);if(!request||request.protocolVersion!==PROTOCOL_VERSION||request.managedContext!==MANAGED_CONTEXT_PROTOCOL||!hasValidAttestedFields(request)){return INVALID}if(ATTESTED_KEYS.some(key=>request[key]!==identity[key])){return IDENTITY_CONFLICT}return{status:200,body:attestationResponse(identity)}}__name(checkManagedContextAttestation,"checkManagedContextAttestation");var ManagedContextInstallations=class{static{__name(this,"ManagedContextInstallations")}#boot;#operations=new Map;#sessions=new Map;constructor(boot){this.#boot=parseManagedContextBoot(boot)}async install(body2,verify,canRecord=()=>true){const request=this.#read(body2);if("status"in request){return request}const earlier=this.#match(request);if(earlier){return earlier}if(!canRecord())return CONTEXT_UNAVAILABLE;const verified=await verify(request.binding);return this.#match(request)??(verified&&canRecord()?this.#record(request):CONTEXT_UNAVAILABLE)}installed(sessionId){return this.#sessions.get(sessionId)?.binding}installation(sessionId){const request=this.#sessions.get(sessionId);return request?Object.freeze({protocolVersion:PROTOCOL_VERSION,managedContext:MANAGED_CONTEXT_PROTOCOL,...request}):void 0}bindings(){return[...this.#sessions.entries()].map(([sessionId,request])=>[sessionId,request.binding])}#read(body2){const request=readClosed(body2,INSTALLATION_KEYS);const binding=request&&readClosed(request.binding,BINDING_KEYS);if(!request||!binding||request.protocolVersion!==PROTOCOL_VERSION||request.managedContext!==MANAGED_CONTEXT_PROTOCOL||!isManagedIdentifier(request.operationId)||!isRuntimeSessionId(request.sessionId)||!isDigest(request.contextDigest)){return INVALID}const contextDigest=digestOf(binding);if(contextDigest===void 0||contextDigest!==request.contextDigest){return INVALID}if(WORKSPACE_KEYS.some(key=>binding[key]!==this.#boot[key])){return IDENTITY_CONFLICT}return{operationId:request.operationId,sessionId:request.sessionId,contextDigest,binding:Object.freeze(binding)}}#match(request){const previous=this.#operations.get(request.operationId);if(previous){return previous.sessionId===request.sessionId&&previous.contextDigest===request.contextDigest?{status:200,body:previous.receipt}:CONTEXT_CONFLICT}const installed=this.#sessions.get(request.sessionId);return installed!==void 0&&installed.contextDigest!==request.contextDigest?CONTEXT_CONFLICT:void 0}#record(request){const{operationId,sessionId,contextDigest,binding}=request;const receipt2=Object.freeze({protocolVersion:PROTOCOL_VERSION,managedContext:MANAGED_CONTEXT_PROTOCOL,operationId,sessionId,runtimeInstanceId:this.#boot.runtimeInstanceId,runtimeIncarnation:this.#boot.runtimeIncarnation,epoch:this.#boot.epoch,contextDigest,contextRevision:binding.contextRevision,workspaceGeneration:binding.workspaceGeneration});this.#operations.set(operationId,Object.freeze({sessionId,contextDigest,receipt:receipt2}));this.#sessions.set(sessionId,request);return{status:200,body:receipt2}}};function attestationResponse(identity){return Object.freeze({protocolVersion:PROTOCOL_VERSION,managedContext:MANAGED_CONTEXT_PROTOCOL,runtimeInstanceId:identity.runtimeInstanceId,runtimeIncarnation:identity.runtimeIncarnation,leaseId:identity.leaseId,epoch:identity.epoch,provisionRequestId:identity.provisionRequestId,tenantId:identity.tenantId,workspaceId:identity.workspaceId,workspaceGeneration:identity.workspaceGeneration,storageId:identity.storageId,mountRoot:identity.mountRoot,capabilityDigest:identity.capabilityDigest,isolationClass:identity.isolationClass})}__name(attestationResponse,"attestationResponse");function readClosed(value,keys){if(typeof value!=="object"||value===null||Array.isArray(value)){return void 0}const present=Object.keys(value).sort();if(present.length!==keys.length||!present.every((key,index)=>key===keys[index])){return void 0}const snapshot={};for(const key of keys){snapshot[key]=value[key]}return snapshot}__name(readClosed,"readClosed");function hasValidAttestedFields(fields){return isManagedIdentifier(fields.provisionRequestId)&&isManagedIdentifier(fields.tenantId)&&isManagedIdentifier(fields.workspaceId)&&isCanonicalDecimalText(fields.workspaceGeneration)&&isWorkspaceStorageId(fields.storageId)&&isMountRoot(fields.mountRoot)&&isDigest(fields.capabilityDigest)&&(fields.isolationClass==="session"||fields.isolationClass==="workspace")}__name(hasValidAttestedFields,"hasValidAttestedFields");function digestOf(binding){try{return computeManagedContextDigest(binding)}catch{return void 0}}__name(digestOf,"digestOf");function isNonEmptyString(value){return typeof value==="string"&&value.length>0}__name(isNonEmptyString,"isNonEmptyString");function isRuntimeSessionId(value){return isNonEmptyString(value)&&value.length<=MAXIMUM_SESSION_ID_LENGTH&&!value.includes("\0")&&!LONE_SURROGATE_PATTERN.test(value)}__name(isRuntimeSessionId,"isRuntimeSessionId");function isBearerToken(value){return matches(BEARER_TOKEN_PATTERN,value)&&value.length<=MAXIMUM_TOKEN_LENGTH}__name(isBearerToken,"isBearerToken");function matches(pattern,value){return typeof value==="string"&&pattern.test(value)}__name(matches,"matches");function isEpoch(value){return Number.isSafeInteger(value)&&value>=1}__name(isEpoch,"isEpoch");function isDigest(value){return matches(DIGEST_PATTERN,value)}__name(isDigest,"isDigest");function isMountRoot(value){if(typeof value!=="string"||value.length>MAXIMUM_MOUNT_ROOT_BYTES||!ABSOLUTE_PATH_PATTERN.test(value)){return false}for(const character of value){const codePoint=character.codePointAt(0)??0;if(codePoint<=31||codePoint>=127&&codePoint<=159||codePoint>=55296&&codePoint<=57343){return false}}return Buffer.byteLength(value,"utf8")<=MAXIMUM_MOUNT_ROOT_BYTES}__name(isMountRoot,"isMountRoot");init_esbuild_shims();import{createHash as createHash6}from"node:crypto";init_esbuild_shims();var CSI_FILES_RETIREMENT_CAPABILITY_DIGEST="sha256:116dcd2afce7292bdf0bf4c76010964f7a7148ad512b2939e48e3d55ea91118d";import{constants as constants2,promises as fs3}from"node:fs";import path4 from"node:path";init_esbuild_shims();import path2 from"node:path";import{promises as fs}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}from"node:crypto";import{createReadStream}from"node:fs";import{lstat}from"node:fs/promises";import path 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(path.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(path.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(path.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(path.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=>path.relative(this.directory,file).split(path.sep).join("/")),filesFailed:result.filesFailed.map(file=>path.relative(this.directory,file).split(path.sep).join("/")),conflict:false}})}async resolve(file){historyPath(file);if(this.retainedStorage){const absolute=path.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=path.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(path.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 digest2=createHash("sha256");for await(const chunk of createReadStream(absolute))digest2.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:${digest2.digest("hex")}`,mode:after.mode&4095}}catch(error){if(error.code==="ENOENT")return null;throw error}}};init_esbuild_shims();import{createHash as createHash2}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();function gateKey(sessionKey,operationId){const key=assertManagedSessionKey(sessionKey);const id2=assertManagedSessionStableId(operationId,"operationId");return`${key.tenantId}\0${key.workspaceId}\0${key.sessionId}\0${id2}`}__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)}};var ManagedMcpError=class extends Error{constructor(code){super(code);this.code=code}static{__name(this,"ManagedMcpError")}};var MAX_INFLIGHT=32;var MAX_MANIFEST_BYTES=1024*1024;var MAX_RESULT_BYTES=60*1024;var MAX_CATALOG_CATEGORY_BYTES=16*1024;var MAX_CATALOG_PAGES=64;var TIMEOUT_MS=25e3;var REQUEST_TIMEOUT_MS=6e5;var identifier=/^[A-Za-z0-9._:-]{1,128}$/u;function object(value){if(!value||typeof value!=="object"||Array.isArray(value))throw new ManagedMcpError("managed_mcp_invalid");return value}__name(object,"object");function closed(value,fields){if(Object.keys(value).some(key=>!fields.includes(key)))throw new ManagedMcpError("managed_mcp_invalid")}__name(closed,"closed");function positive(value){return typeof value==="number"&&Number.isSafeInteger(value)&&value>0}__name(positive,"positive");function strings(value){return!!value&&typeof value==="object"&&!Array.isArray(value)&&Object.values(value).every(item=>typeof item==="string")}__name(strings,"strings");function scope(key){return`${key.tenantId}\0${key.workspaceId}\0${key.sessionId}`}__name(scope,"scope");function bindingKey(runtimeSessionId,serverId,revision,generation){return`${runtimeSessionId}\0${serverId}\0${revision}\0${generation}`}__name(bindingKey,"bindingKey");function fingerprint(value){return createHash2("sha256").update(JSON.stringify(value)).digest("hex")}__name(fingerprint,"fingerprint");function parseManagedMcpControl(value){const control=object(value);const key=object(control["sessionKey"]);closed(key,["tenantId","workspaceId","sessionId"]);if(["tenantId","workspaceId","sessionId"].some(name=>typeof key[name]!=="string"||!identifier.test(key[name]))||typeof control["operationId"]!=="string"||!identifier.test(control["operationId"]))throw new ManagedMcpError("managed_mcp_invalid");const base=["kind","sessionKey","operationId"];if(control["kind"]==="mcp-status"||control["kind"]==="mcp-cancel"){closed(control,[...base,"targetOperationId"]);if(typeof control["targetOperationId"]!=="string"||!identifier.test(control["targetOperationId"]))throw new ManagedMcpError("managed_mcp_invalid");return structuredClone(control)}if(!["mcp-configure","mcp-discover","mcp-invoke","mcp-release"].includes(String(control["kind"]))||typeof control["serverId"]!=="string"||!identifier.test(control["serverId"])||!positive(control["serverRevision"]))throw new ManagedMcpError("managed_mcp_invalid");const server=[...base,"serverId","serverRevision","grant"];if(control["kind"]==="mcp-configure"){closed(control,[...server,"configRevision","definitionDigest"]);if(!positive(control["configRevision"])||typeof control["definitionDigest"]!=="string"||!/^[a-f0-9]{64}$/u.test(control["definitionDigest"]))throw new ManagedMcpError("managed_mcp_invalid")}else{if(!positive(control["connectionGeneration"]))throw new ManagedMcpError("managed_mcp_invalid");if(control["kind"]==="mcp-invoke"){closed(control,[...server,"configRevision","connectionGeneration","catalogRevision","request"]);if(!positive(control["configRevision"])||!positive(control["catalogRevision"]))throw new ManagedMcpError("managed_mcp_invalid");const request=object(control["request"]);if(request["kind"]==="resource_read"){closed(request,["kind","uri"]);if(typeof request["uri"]!=="string"||request["uri"].length===0)throw new ManagedMcpError("managed_mcp_invalid")}else if(request["kind"]==="tool_call"||request["kind"]==="prompt_get"){closed(request,["kind","name","arguments"]);if(typeof request["name"]!=="string"||request["name"].length===0)throw new ManagedMcpError("managed_mcp_invalid");object(request["arguments"]);if(request["kind"]==="prompt_get"&&!strings(request["arguments"]))throw new ManagedMcpError("managed_mcp_invalid")}else throw new ManagedMcpError("managed_mcp_invalid")}else closed(control,[...server,"connectionGeneration"])}try{parseOperationGrant(control["grant"])}catch{throw new ManagedMcpError("managed_mcp_grant_invalid")}return structuredClone(control)}__name(parseManagedMcpControl,"parseManagedMcpControl");function loadManagedMcpManifest(file){if(!file)return{version:1,servers:[]};try{const bytes=readFileSync(file);if(bytes.length>MAX_MANIFEST_BYTES)throw new ManagedMcpError("managed_mcp_manifest_invalid");return parseManifest(JSON.parse(bytes.toString("utf8")))}catch(error){throw error instanceof ManagedMcpError?error:new ManagedMcpError("managed_mcp_manifest_invalid")}}__name(loadManagedMcpManifest,"loadManagedMcpManifest");function parseManifest(value){const manifest=object(value);closed(manifest,["version","servers"]);if(manifest["version"]!==1||!Array.isArray(manifest["servers"]))throw new ManagedMcpError("managed_mcp_manifest_invalid");const keys=new Set;for(const item of manifest["servers"]){const definition=object(item);closed(definition,["tenantId","workspaceId","serverId","serverRevision","definitionDigest","transport","command","args","env","url","headers","timeoutMs"]);if(["tenantId","workspaceId","serverId"].some(key=>typeof definition[key]!=="string"||!identifier.test(definition[key]))||!positive(definition["serverRevision"])||typeof definition["definitionDigest"]!=="string"||!/^[a-f0-9]{64}$/u.test(definition["definitionDigest"]))throw new ManagedMcpError("managed_mcp_manifest_invalid");if(definition["timeoutMs"]!==void 0&&(!positive(definition["timeoutMs"])||Number(definition["timeoutMs"])>REQUEST_TIMEOUT_MS))throw new ManagedMcpError("managed_mcp_manifest_invalid");const id2=`${definition["tenantId"]}\0${definition["workspaceId"]}\0${definition["serverId"]}\0${definition["serverRevision"]}`;if(keys.has(id2))throw new ManagedMcpError("managed_mcp_definition_conflict");keys.add(id2);if(definition["transport"]==="stdio"){if(typeof definition["command"]!=="string"||!definition["command"]||definition["command"].includes("\0")||definition["url"]!==void 0||definition["headers"]!==void 0||definition["args"]!==void 0&&(!Array.isArray(definition["args"])||!definition["args"].every(arg=>typeof arg==="string"&&!arg.includes("\0")))||definition["env"]!==void 0&&(!strings(definition["env"])||Object.entries(definition["env"]).some(([key,value2])=>key.includes("\0")||value2.includes("\0"))))throw new ManagedMcpError("managed_mcp_manifest_invalid")}else if(definition["transport"]==="streamable-http"||definition["transport"]==="sse"){if(typeof definition["url"]!=="string"||definition["command"]!==void 0||definition["args"]!==void 0||definition["env"]!==void 0||definition["headers"]!==void 0&&!strings(definition["headers"]))throw new ManagedMcpError("managed_mcp_manifest_invalid");const url=new URL(definition["url"]);if(!["http:","https:"].includes(url.protocol)||url.username||url.password)throw new ManagedMcpError("managed_mcp_manifest_invalid")}else throw new ManagedMcpError("managed_mcp_transport_unsupported")}return structuredClone(manifest)}__name(parseManifest,"parseManifest");var ManagedMcpRuntime=class{constructor(workspace,sessionDirectory,manifest){this.workspace=workspace;this.sessionDirectory=sessionDirectory;this.definitions=parseManifest(manifest)}static{__name(this,"ManagedMcpRuntime")}definitions;connections=new Map;operations=new Map;gates=new ManagedOperationGrantGate;generation=0;closing=false;admissionSealed=false;grantInstalled=false;pendingStarts=0;sealAdmission(){this.admissionSealed=true}getDrainInspection(){return{pendingStarts:this.pendingStarts,pendingInvocations:[...this.operations.values()].filter(operation=>operation.view.state==="running"||operation.connection?.pending.has(operation.control.operationId)).length,hasActivity:this.grantInstalled||this.operations.size>0||this.connections.size>0}}assertAdmission(control){if(this.admissionSealed&&control.kind!=="mcp-release")throw new ManagedMcpError("managed_mcp_closed")}async control(runtimeSessionId,value,allowTool=false){const control=parseManagedMcpControl(value);this.assertScope(control.sessionKey);if(control.kind==="mcp-invoke"&&control.request.kind==="tool_call"&&!allowTool)throw new ManagedMcpError("managed_mcp_tool_requires_execution");if(control.kind==="mcp-status"||control.kind==="mcp-cancel"){const existing2=this.operations.get(`${scope(control.sessionKey)}\0${control.targetOperationId}`);if(!existing2||existing2.runtimeSessionId!==runtimeSessionId)return{operationId:control.targetOperationId,state:"outcome_unknown"};return structuredClone(existing2.view)}if(!("grant"in control))throw new ManagedMcpError("managed_mcp_invalid");const key=`${scope(control.sessionKey)}\0${control.operationId}`;const{grant:_grant,...effect}=control;const content=fingerprint(effect);const existing=this.operations.get(key);if(existing){if(existing.runtimeSessionId!==runtimeSessionId||existing.fingerprint!==content)throw new ManagedMcpError("managed_mcp_operation_conflict");return structuredClone(existing.view)}if(this.closing)throw new ManagedMcpError("managed_mcp_closed");this.assertAdmission(control);const phase=control.kind.slice(4);const grant=parseOperationGrant(control.grant);if((control.kind==="mcp-configure"||control.kind==="mcp-invoke"&&control.request.kind!=="tool_call")&&grant.operationId!==control.operationId||scope(grant.sessionKey)!==scope(control.sessionKey)||grant.workspaceGeneration!==this.workspace.workspaceGeneration||grant.domain!==(control.kind==="mcp-invoke"&&control.request.kind!=="tool_call"?"mcp_operation":"mcp_configuration"))throw new ManagedMcpError("managed_mcp_grant_invalid");try{this.gates.install(grant);this.grantInstalled=true}catch{throw new ManagedMcpError("managed_mcp_grant_invalid")}if(!this.gates.admits(control.sessionKey,grant.operationId,phase,Date.now()))throw new ManagedMcpError("managed_mcp_grant_invalid");let directory;if(control.kind!=="mcp-release"){this.pendingStarts++;try{directory=await this.sessionDirectory(runtimeSessionId)}finally{this.pendingStarts--}}if(!directory&&control.kind!=="mcp-release")throw new ManagedMcpError("managed_mcp_session_unavailable");if(this.operations.has(key))return this.control(runtimeSessionId,control,allowTool);this.assertAdmission(control);if(this.closing||!this.gates.admits(control.sessionKey,grant.operationId,phase,Date.now()))throw new ManagedMcpError("managed_mcp_grant_invalid");let resolve=__name(()=>void 0,"resolve");const done=new Promise(complete=>{resolve=complete});const operation={fingerprint:content,runtimeSessionId,control,view:{operationId:control.operationId,state:"running"},done,resolve};this.operations.set(key,operation);if(control.kind==="mcp-invoke"){this.invoke(operation,control)}else{void this.configureOrMaintain(operation,directory).catch(error=>{this.settled(operation,{error:{code:error instanceof ManagedMcpError?error.code:"managed_mcp_connection_failed"}})})}return structuredClone(operation.view)}async invokeTool(runtimeSessionId,input){const control=parseManagedMcpControl(input);if(control.kind!=="mcp-invoke"||control.request.kind!=="tool_call")throw new ManagedMcpError("managed_mcp_invalid");await this.control(runtimeSessionId,control,true);const operation=this.operations.get(`${scope(control.sessionKey)}\0${control.operationId}`);await operation.done;return structuredClone(operation.view)}hasHolds(runtimeSessionId){return[...this.connections.values()].some(entry=>entry.runtimeSessionId===runtimeSessionId&&(!entry.closed||entry.pending.size>0))}toolStatus(runtimeSessionId,input){const control=parseManagedMcpControl(input);const operation=this.operations.get(`${scope(control.sessionKey)}\0${control.operationId}`);return operation?.runtimeSessionId===runtimeSessionId?structuredClone(operation.view):{operationId:control.operationId,state:"outcome_unknown"}}cancelTool(runtimeSessionId,input){const control=parseManagedMcpControl(input);void this.control(runtimeSessionId,{kind:"mcp-cancel",sessionKey:control.sessionKey,operationId:control.operationId,targetOperationId:control.operationId})}async close(){this.closing=true;await Promise.allSettled([...this.connections.values()].map(entry=>this.closeConnection(entry)))}assertScope(key){if(key.tenantId!==this.workspace.tenantId||key.workspaceId!==this.workspace.workspaceId)throw new ManagedMcpError("managed_mcp_scope_conflict")}connection(operation,control){if(!("serverId"in control)||!("connectionGeneration"in control))throw new ManagedMcpError("managed_mcp_invalid");const connection=this.connections.get(bindingKey(operation.runtimeSessionId,control.serverId,control.serverRevision,control.connectionGeneration));if(!connection||connection.closed&&control.kind!=="mcp-release"||scope(connection.sessionKey)!==scope(control.sessionKey)||!("connectionGeneration"in control)||connection.generation!==control.connectionGeneration)throw new ManagedMcpError("managed_mcp_binding_conflict");if("grant"in control&&(control.kind!=="mcp-invoke"||control.request.kind==="tool_call")&&control.grant.operationId!==connection.configurationOperationId)throw new ManagedMcpError("managed_mcp_grant_invalid");return connection}async configureOrMaintain(operation,directory){const control=operation.control;if(control.kind==="mcp-configure"){const definition=this.definitions.servers.find(item=>item.tenantId===control.sessionKey.tenantId&&item.workspaceId===control.sessionKey.workspaceId&&item.serverId===control.serverId&&item.serverRevision===control.serverRevision);if(!definition||definition.definitionDigest!==control.definitionDigest)throw new ManagedMcpError("managed_mcp_definition_unavailable");const siblings=[...this.connections.values()].filter(entry=>entry.runtimeSessionId===operation.runtimeSessionId&&entry.definition.serverId===control.serverId);if(siblings.some(entry=>entry.configRevision>=control.configRevision||entry.definition.serverRevision>control.serverRevision))throw new ManagedMcpError("managed_mcp_revision_conflict");if([...this.connections.values()].filter(entry=>!entry.closed).length>=MANAGED_MCP_MAX_CONNECTIONS)throw new ManagedMcpError("managed_mcp_connection_quota");const transport=definition.transport==="stdio"?new StdioClientTransport({command:definition.command,args:definition.args,cwd:directory,stderr:"pipe",env:{...Object.fromEntries(DEFAULT_INHERITED_ENV_VARS.map(key=>[key,""])),PATH:process.env["PATH"]??"",HOME:directory,USERPROFILE:directory,...process.env["SystemRoot"]?{SYSTEMROOT:process.env["SystemRoot"]}:{},...definition.env}}):definition.transport==="streamable-http"?new StreamableHTTPClientTransport(new URL(definition.url),{requestInit:{headers:definition.headers,redirect:"error"}}):new SSEClientTransport(new URL(definition.url),{requestInit:{headers:definition.headers,redirect:"error"},eventSourceInit:{fetch:__name((url,init)=>fetch(url,{...init,redirect:"error"}),"fetch")}});const client=new Client({name:"qwen-managed-mcp",version:"1"},{capabilities:{}});if(transport instanceof StdioClientTransport)transport.stderr?.on("data",()=>void 0);let confirmClose=__name(()=>void 0,"confirmClose");const closeDone=new Promise(resolve=>{confirmClose=resolve});const connection={runtimeSessionId:operation.runtimeSessionId,sessionKey:control.sessionKey,definition,client,transport,pending:new Map,drained:new Set,closeDone,configRevision:control.configRevision,configurationOperationId:control.grant.operationId,generation:++this.generation,catalogChanges:{tools:0,resources:0,prompts:0},retiring:false,closed:false};operation.connection=connection;this.connections.set(bindingKey(operation.runtimeSessionId,control.serverId,control.serverRevision,connection.generation),connection);client.onclose=()=>{connection.closed=true;confirmClose();for(const pending of connection.pending.values())this.unknown(pending,"managed_mcp_connection_lost")};client.onerror=()=>{connection.retiring=true;if(connection.pending.size===0)void this.closeConnection(connection).catch(()=>void 0)};try{await client.connect(transport,{timeout:TIMEOUT_MS});const onmessage=transport.onmessage;transport.onmessage=message=>{if("method"in message){const changed={"notifications/tools/list_changed":"tools","notifications/resources/list_changed":"resources","notifications/prompts/list_changed":"prompts"};const kind=Object.hasOwn(changed,message.method)?changed[message.method]:void 0;if(kind){connection.catalogChanges[kind]++;if(connection.catalog)connection.catalog={...connection.catalog,catalogRevision:connection.catalog.catalogRevision+1,discovery:{...connection.catalog.discovery,[kind]:"stale"}}}}if("id"in message&&typeof message.id==="string"&&!("method"in message)){const pending=connection.pending.get(message.id);if(pending)this.receive(pending,message);return}onmessage(message)};await this.discover(connection);for(const sibling of siblings){sibling.retiring=true;if(sibling.pending.size===0)await this.closeConnection(sibling).catch(()=>void 0)}this.settled(operation,{catalog:connection.catalog})}catch{try{await this.closeConnection(connection)}catch{this.unknown(operation,"managed_mcp_drain_unknown");return}throw new ManagedMcpError("managed_mcp_connection_failed")}}else if(control.kind==="mcp-discover"){const connection=this.connection(operation,control);if(connection.retiring)throw new ManagedMcpError("managed_mcp_retiring");if(!connection.catalog||Object.values(connection.catalog.discovery).some(state=>state==="stale"||state==="failed"))await this.discover(connection);this.settled(operation,{catalog:connection.catalog})}else if(control.kind==="mcp-release"){const connection=this.connection(operation,control);connection.retiring=true;operation.timer=setTimeout(()=>this.unknown(operation,"managed_mcp_drain_unknown"),TIMEOUT_MS);while(connection.pending.size>0){await new Promise(resolve=>connection.drained.add(resolve))}try{await this.closeConnection(connection)}catch{this.unknown(operation,"managed_mcp_drain_unknown");void connection.closeDone.then(()=>this.settled(operation,{response:{released:true}}));return}this.settled(operation,{response:{released:true}})}}async discover(connection){connection.catalogWork=(connection.catalogWork??Promise.resolve()).then(()=>this.refreshCatalog(connection));return connection.catalogWork}async refreshCatalog(connection){const previous=connection.catalog;const changes={...connection.catalogChanges};const lists=await Promise.all([this.list(connection.client,"tools",ListToolsResultSchema),this.list(connection.client,"resources",ListResourcesResultSchema),this.list(connection.client,"prompts",ListPromptsResultSchema)]);const values=lists.map((result,index)=>result.state==="failed"&&previous&&[previous.discovery.tools,previous.discovery.resources,previous.discovery.prompts][index]!=="failed"?{values:[previous.tools,previous.resources,previous.prompts][index],state:"stale"}:result);const catalog={serverId:connection.definition.serverId,serverRevision:connection.definition.serverRevision,definitionDigest:connection.definition.definitionDigest,configRevision:connection.configRevision,connectionGeneration:connection.generation,catalogRevision:connection.catalog?.catalogRevision??0,tools:values[0].values,resources:values[1].values,prompts:values[2].values,discovery:{tools:changes.tools===connection.catalogChanges.tools?values[0].state:"stale",resources:changes.resources===connection.catalogChanges.resources?values[1].state:"stale",prompts:changes.prompts===connection.catalogChanges.prompts?values[2].state:"stale"}};if(fingerprint(catalog)!==fingerprint(connection.catalog??null))connection.catalog={...catalog,catalogRevision:catalog.catalogRevision+1}}async list(client,kind,schema){const values=[];const cursors=new Set;let cursor;try{do{if(cursors.size>=MAX_CATALOG_PAGES)throw new Error("pages");const result=await client.request({method:`${kind}/list`,params:cursor?{cursor}:{}},schema,{timeout:TIMEOUT_MS});const entries=result[kind];for(const entry of entries){const fields=kind==="tools"?["name","description","inputSchema"]:kind==="resources"?["name","uri","description","mimeType"]:["name","description","arguments"];const value=Object.fromEntries(fields.filter(name=>entry[name]!==void 0).map(name=>[name,entry[name]]));if(Buffer.byteLength(JSON.stringify([...values,value]))>MAX_CATALOG_CATEGORY_BYTES)throw new Error("limit");values.push(value)}cursor=result.nextCursor;if(cursor&&cursors.has(cursor))throw new Error("cursor");if(cursor)cursors.add(cursor)}while(cursor);return{values,state:"complete"}}catch(error){if(objectOrUndefined(error)?.["code"]===-32601&&values.length===0)return{values,state:"complete"};return{values,state:values.length>0?"partial":"failed"}}}invoke(operation,control){let connection;try{connection=this.connection(operation,control);const catalog=connection.catalog;if(connection.retiring||!catalog||catalog.configRevision!==control.configRevision||catalog.catalogRevision!==control.catalogRevision)throw new ManagedMcpError("managed_mcp_catalog_conflict");const request=control.request;const permitted=request.kind==="tool_call"?["complete","partial"].includes(catalog.discovery.tools)&&catalog.tools.some(tool=>tool.name===request.name):request.kind==="resource_read"?["complete","partial"].includes(catalog.discovery.resources)&&catalog.resources.some(resource=>resource.uri===request.uri):["complete","partial"].includes(catalog.discovery.prompts)&&catalog.prompts.some(prompt=>prompt.name===request.name);if(!permitted)throw new ManagedMcpError("managed_mcp_capability_unavailable");if([...this.connections.values()].reduce((count,entry)=>count+(entry.closed?0:[...entry.pending.values()].filter(pending=>pending.awaitingReply).length),0)>=MAX_INFLIGHT)throw new ManagedMcpError("managed_mcp_inflight_quota");operation.connection=connection;operation.awaitingReply=true;connection.pending.set(control.operationId,operation);operation.timer=setTimeout(()=>this.unknown(operation,"managed_mcp_timeout"),connection.definition.timeoutMs??REQUEST_TIMEOUT_MS);const method=request.kind==="tool_call"?"tools/call":request.kind==="resource_read"?"resources/read":"prompts/get";const params=request.kind==="resource_read"?{uri:request.uri}:{name:request.name,arguments:request.arguments};void connection.transport.send({jsonrpc:"2.0",id:control.operationId,method,params}).catch(()=>this.unknown(operation,"managed_mcp_send_unknown"))}catch(error){this.settled(operation,{error:{code:error instanceof ManagedMcpError?error.code:"managed_mcp_invalid"}})}}receive(operation,message){operation.awaitingReply=false;const control=operation.control;if(message.error!==void 0){this.settled(operation,{error:{code:"managed_mcp_remote_error"}})}else{try{const schema=control.request.kind==="tool_call"?CallToolResultSchema:control.request.kind==="resource_read"?ReadResourceResultSchema:GetPromptResultSchema;const result=schema.parse(message.result);if(Buffer.byteLength(JSON.stringify(result))>MAX_RESULT_BYTES){this.settled(operation,{error:{code:"managed_mcp_output_limit"}});return}this.settled(operation,{response:result})}catch{this.unknown(operation,"managed_mcp_response_invalid")}}}settled(operation,result){if(operation.timer)clearTimeout(operation.timer);operation.connection?.pending.delete(operation.control.operationId);if(operation.connection?.pending.size===0){for(const resolve of operation.connection.drained)resolve();operation.connection.drained.clear();if(operation.connection.retiring&&!operation.connection.closed)void this.closeConnection(operation.connection).catch(()=>void 0)}operation.view={operationId:operation.control.operationId,state:"settled",...result};operation.resolve()}unknown(operation,code){if(operation.view.state==="settled")return;if(operation.timer)clearTimeout(operation.timer);operation.view={operationId:operation.control.operationId,state:"outcome_unknown",error:{code}};operation.resolve()}closeConnection(connection){if(connection.closed)return Promise.resolve();connection.closing??=this.drainConnection(connection).finally(()=>{connection.closing=void 0});return connection.closing}async drainConnection(connection){connection.retiring=true;let timer;try{await Promise.race([(async()=>{if(connection.transport instanceof StreamableHTTPClientTransport){let terminationTimer;try{await Promise.race([connection.transport.terminateSession().catch(()=>void 0),new Promise(resolve=>{terminationTimer=setTimeout(resolve,1e3)})])}finally{if(terminationTimer)clearTimeout(terminationTimer)}}await connection.client.close();await connection.closeDone})(),new Promise((_,reject)=>{timer=setTimeout(()=>reject(new ManagedMcpError("managed_mcp_drain_unknown")),5e3)})])}finally{if(timer)clearTimeout(timer)}}};function objectOrUndefined(value){return value!==null&&typeof value==="object"?value:void 0}__name(objectOrUndefined,"objectOrUndefined");init_esbuild_shims();import{createHash as createHash3}from"node:crypto";var MANAGED_CSI_PROTOCOL="managed-csi/1";var MANAGED_CSI_ATTEST_PATH="/internal/managed-runtime/csi/v1/attest";var MANAGED_CSI_DRAIN_PATH="/internal/managed-runtime/csi/v1/drain";var MANAGED_CSI_ACK_PATH="/internal/managed-runtime/csi/v1/acknowledge";var MANAGED_CSI_WORKER_ACK_PROTOCOL="managed-csi-original-worker-ack/1";var MANAGED_CSI_ACK_LIMIT_BYTES=16*1024;var ManagedCsiAckRequestError=class extends Error{constructor(status){super("Managed CSI acknowledgement conflicts.");this.status=status}static{__name(this,"ManagedCsiAckRequestError")}};function parseManagedCsiAckJson(bytes){const text2=new TextDecoder("utf-8",{fatal:true}).decode(bytes);parseManagedSessionRecordJson(text2,MANAGED_CSI_ACK_LIMIT_BYTES);return JSON.parse(text2,(_key,value,context)=>{if(typeof value==="number"&&(context?.source===void 0||!/^[1-9][0-9]*$/.test(context.source)))throw new Error("Managed CSI acknowledgement JSON is invalid.");return value})}__name(parseManagedCsiAckJson,"parseManagedCsiAckJson");function parseManagedCsiAcknowledgement(value){const ack=closed2(value,["deliveryStatus","executionCallId","historyRevision","manifest"]);const manifest=assertManagedSessionDurableRef(ack["manifest"],"manifest");if(ack["deliveryStatus"]!=="committed"||!Number.isSafeInteger(ack["historyRevision"])||ack["historyRevision"]<1||manifest.kind!=="managed-tool-result-manifest"||manifest.schemaVersion!==1||manifest.byteLength<1||manifest.byteLength>65536)throw new Error;return{executionCallId:stableId(ack["executionCallId"]),manifest,deliveryStatus:"committed",historyRevision:ack["historyRevision"]}}__name(parseManagedCsiAcknowledgement,"parseManagedCsiAcknowledgement");function parseManagedCsiCaptureIdentity(value){const identity=closed2(value,["bindingGeneration","callId","captureId","executionCallId","invocationDigest","revision","sessionId","tenantId","turnId"]);if(!isCanonicalDecimalText(identity["bindingGeneration"])||identity["revision"]!==1||typeof identity["captureId"]!=="string"||!/^[a-z0-9_-]{1,128}$/.test(identity["captureId"])||!invocationDigest(identity["invocationDigest"]))throw new Error;return{tenantId:stableId(identity["tenantId"]),sessionId:stableId(identity["sessionId"]),turnId:stableId(identity["turnId"]),executionCallId:stableId(identity["executionCallId"]),callId:stableId(identity["callId"]),invocationDigest:identity["invocationDigest"],bindingGeneration:identity["bindingGeneration"],captureId:identity["captureId"],revision:1}}__name(parseManagedCsiCaptureIdentity,"parseManagedCsiCaptureIdentity");function parseManagedCsiAckRequest(value,boot,pod){let request;let reference2;let acknowledgement;const context=createManagedContextAttestationResponse(boot.context);try{request=closed2(value,ACK_REQUEST_KEYS);if(typeof request["retirementId"]!=="string"||!/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(request["retirementId"]))throw new Error;const ref2=closed2(request["reference"],["argsDigest","callId","promptId","sessionId"]);if(!invocationDigest(ref2["argsDigest"]))throw new Error;reference2={sessionId:stableId(ref2["sessionId"]),promptId:stableId(ref2["promptId"]),callId:stableId(ref2["callId"]),argsDigest:ref2["argsDigest"]};acknowledgement=parseManagedCsiAcknowledgement(request["acknowledgement"]);closed2(request["context"],Object.keys(context).sort());closed2(request["storage"],STORAGE_KEYS);closed2(request["pod"],["namespace","nodeName","uid"])}catch{throw new ManagedCsiAckRequestError(400)}try{validateManagedCsiPodIdentity(pod,boot.storage.namespace);if(request["protocolVersion"]!==1||request["managedCsi"]!==MANAGED_CSI_PROTOCOL||request["workerAck"]!==MANAGED_CSI_WORKER_ACK_PROTOCOL||boot.context.isolationClass!=="workspace")throw new Error;for(const[key,expected]of[["context",context],["storage",boot.storage],["pod",pod]]){const fields=request[key];if(!Object.entries(expected).every(([name,field])=>fields[name]===field))throw new Error}}catch{throw new ManagedCsiAckRequestError(409)}return{protocolVersion:1,managedCsi:MANAGED_CSI_PROTOCOL,workerAck:MANAGED_CSI_WORKER_ACK_PROTOCOL,retirementId:request["retirementId"],context,storage:{...boot.storage},pod:{...pod},reference:reference2,acknowledgement}}__name(parseManagedCsiAckRequest,"parseManagedCsiAckRequest");function parseManagedCsiAckResponse(value,boot,pod){try{const response=closed2(value,[...ACK_REQUEST_KEYS,"captureIdentity","state"].sort());if(response["state"]!=="ACKNOWLEDGED")throw new Error;const request=parseManagedCsiAckRequest(Object.fromEntries(ACK_REQUEST_KEYS.map(key=>[key,response[key]])),boot,pod);const identity=parseManagedCsiCaptureIdentity(response["captureIdentity"]);if(identity.tenantId!==boot.context.tenantId||identity.executionCallId!==request.acknowledgement.executionCallId||identity.callId!==request.reference.callId||identity.invocationDigest!==request.reference.argsDigest)throw new Error;return{...request,state:"ACKNOWLEDGED",captureIdentity:identity}}catch{throw new ManagedCsiAckRequestError(409)}}__name(parseManagedCsiAckResponse,"parseManagedCsiAckResponse");var ACK_REQUEST_KEYS=["acknowledgement","context","managedCsi","pod","protocolVersion","reference","retirementId","storage","workerAck"];function stableId(value){return assertManagedSessionStableId(value,"id")}__name(stableId,"stableId");function invocationDigest(value){return typeof value==="string"&&/^(?:sha256:)?[0-9a-f]{64}$/.test(value)}__name(invocationDigest,"invocationDigest");function createManagedCsiAttestationRequest(boot){return Object.freeze({protocolVersion:1,managedCsi:MANAGED_CSI_PROTOCOL,provisionRequestId:boot.context.provisionRequestId,physicalKey:boot.storage.physicalKey,registrationRevision:boot.storage.registrationRevision,reservationId:boot.storage.reservationId,reservationRevision:boot.storage.reservationRevision})}__name(createManagedCsiAttestationRequest,"createManagedCsiAttestationRequest");var ManagedCsiDrainRequestError=class extends Error{constructor(status){super("Managed CSI drain request is invalid.");this.status=status}static{__name(this,"ManagedCsiDrainRequestError")}};function parseManagedCsiDrainRequest(value,boot,pod){let request;try{request=closed2(value,["context","managedCsi","operation","pod","protocolVersion","retirementId","storage"]);if(request["operation"]!=="seal"&&request["operation"]!=="status"||typeof request["retirementId"]!=="string"||!/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(request["retirementId"]))throw new Error}catch{throw new ManagedCsiDrainRequestError(400)}try{validateManagedCsiPodIdentity(pod,boot.storage.namespace);if(request["protocolVersion"]!==1||request["managedCsi"]!==MANAGED_CSI_PROTOCOL)throw new Error;for(const[key,expected]of[["context",createManagedContextAttestationResponse(boot.context)],["storage",boot.storage],["pod",pod]]){const actual=closed2(request[key],Object.keys(expected).sort());if(!Object.entries(expected).every(([name,field])=>actual[name]===field))throw new Error}}catch{throw new ManagedCsiDrainRequestError(409)}return{operation:request["operation"],retirementId:request["retirementId"]}}__name(parseManagedCsiDrainRequest,"parseManagedCsiDrainRequest");function validateManagedCsiAttestationRequest(value,boot){const expected=createManagedCsiAttestationRequest(boot);try{const actual=closed2(value,Object.keys(expected).sort());if(!Object.entries(expected).every(([key,field])=>actual[key]===field))throw new Error}catch{throw new Error("Managed CSI attestation request is invalid.")}}__name(validateManagedCsiAttestationRequest,"validateManagedCsiAttestationRequest");function validateManagedCsiPodIdentity(value,namespace){const pod=closed2(value,["namespace","nodeName","uid"]);if(typeof pod["uid"]!=="string"||!/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(pod["uid"])||pod["namespace"]!==namespace||typeof pod["nodeName"]!=="string"||pod["nodeName"].length>253||!pod["nodeName"].split(".").every(label=>/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(label)))throw new Error("Managed CSI Pod identity is unavailable.")}__name(validateManagedCsiPodIdentity,"validateManagedCsiPodIdentity");function validateManagedCsiAttestationResponse(value,boot,expectedPod){try{validateManagedCsiPodIdentity(expectedPod,boot.storage.namespace);const response=closed2(value,["context","managedCsi","mount","pod","protocolVersion","storage"]);const context=createManagedContextAttestationResponse(boot.context);for(const[key,expected]of[["context",context],["storage",boot.storage],["pod",expectedPod]]){const fields=closed2(response[key],Object.keys(expected).sort());if(!Object.entries(expected).every(([name,field])=>fields[name]===field))throw new Error}const mount=closed2(response["mount"],["device","diskSerial","mountId","rootDevice","rootInode","source"]);if(response["protocolVersion"]!==1||response["managedCsi"]!==MANAGED_CSI_PROTOCOL||!unsignedDecimal(mount["mountId"],0xffffffffn,true)||typeof mount["source"]!=="string"||mount["source"].length>128||!/^\/dev\/nvme(?:0|[1-9][0-9]*)n[1-9][0-9]*$/.test(mount["source"])||mount["diskSerial"]!==boot.storage.diskSerial||!unsignedDecimal(mount["rootDevice"],0xffffffffffffffffn,false)||!unsignedDecimal(mount["rootInode"],0xffffffffffffffffn,true)||linuxDeviceNumber(mount["device"])!==mount["rootDevice"])throw new Error}catch{throw new Error("Managed CSI attestation response is invalid.")}}__name(validateManagedCsiAttestationResponse,"validateManagedCsiAttestationResponse");function linuxDeviceNumber(value){if(typeof value!=="string")throw new Error;const parts=value.split(":");if(parts.length!==2||!parts.every(part=>unsignedDecimal(part,0xffffffffn,false)))throw new Error;const major=BigInt(parts[0]);const minor=BigInt(parts[1]);return((major&0xfffn)<<8n|(major&0xfffff000n)<<32n|minor&0xffn|(minor&0xffffff00n)<<12n).toString()}__name(linuxDeviceNumber,"linuxDeviceNumber");function unsignedDecimal(value,maximum,positive3){return typeof value==="string"&&/^(?:0|[1-9][0-9]{0,19})$/.test(value)&&(!positive3||value!=="0")&&BigInt(value)<=maximum}__name(unsignedDecimal,"unsignedDecimal");var BOOT_KEYS2=["context","managedCsi","storage","type","version"];var STORAGE_KEYS=["backendDomain","clusterDomain","diskSerial","driver","namespace","physicalKey","pvUid","pvcUid","registrationRevision","reservationId","reservationRevision","volumeHandle"];var INVALID2="Managed CSI boot document is invalid.";function parseManagedCsiBoot(value){try{const boot=closed2(value,BOOT_KEYS2);const storage=closed2(boot["storage"],STORAGE_KEYS);const context=parseManagedContextBoot(boot["context"]);if(boot["type"]!=="boot"||boot["version"]!==3||boot["managedCsi"]!==MANAGED_CSI_PROTOCOL){throw new Error(INVALID2)}for(const[key,maximum]of[["clusterDomain",256],["backendDomain",256],["volumeHandle",512],["pvcUid",128],["pvUid",128]]){const text2=storage[key];if(typeof text2!=="string"||text2===""||/^[ \u1680\u2000-\u2006\u2008-\u200a\u2028\u2029\u205f\u3000]+$/u.test(text2)||text2.length>maximum||Array.from(text2).some(char=>char.charCodeAt(0)<=31||char.charCodeAt(0)>=127&&char.charCodeAt(0)<=159)||/[\ud800-\udfff]/u.test(text2))throw new Error(INVALID2)}if(typeof storage["namespace"]!=="string"||!/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(storage["namespace"])||storage["driver"]!=="diskplugin.csi.alibabacloud.com"||typeof storage["diskSerial"]!=="string"||!/^[A-Za-z0-9._:-]{1,128}$/.test(storage["diskSerial"])||!isCanonicalDecimalText(storage["registrationRevision"])||!isCanonicalDecimalText(storage["reservationRevision"])||typeof storage["reservationId"]!=="string"||!/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(storage["reservationId"])||typeof storage["physicalKey"]!=="string"||!/^[0-9a-f]{64}$/.test(storage["physicalKey"])||!context.mountRoot.startsWith("/")||context.mountRoot.length>2048||context.mountRoot.includes("\\")||!context.mountRoot.slice(1).split("/").every(part=>part!==""&&part!=="."&&part!=="..")||physicalKey(storage["backendDomain"],storage["driver"],storage["volumeHandle"])!==storage["physicalKey"])throw new Error(INVALID2);return Object.freeze({type:"boot",version:3,managedCsi:MANAGED_CSI_PROTOCOL,context,storage:Object.freeze({...storage})})}catch{throw new Error(INVALID2)}}__name(parseManagedCsiBoot,"parseManagedCsiBoot");function physicalKey(backend,driver,handle){const hash=createHash3("sha256");for(const field of["qwen-csi-physical/1",backend,driver,handle]){const bytes=Buffer.from(field,"utf8");const size=Buffer.alloc(4);size.writeUInt32BE(bytes.byteLength);hash.update(size).update(bytes)}return hash.digest("hex")}__name(physicalKey,"physicalKey");function closed2(value,keys){if(!value||typeof value!=="object"||Array.isArray(value))throw new Error(INVALID2);const fields=Object.keys(value).sort();if(fields.length!==keys.length||!fields.every((field,index)=>field===keys[index]))throw new Error(INVALID2);return value}__name(closed2,"closed");init_esbuild_shims();import{spawn}from"node:child_process";import{readFileSync as readFileSync2}from"node:fs";import{join}from"node:path";var ManagedChildRunProcess=class{constructor(unitName,unit,child){this.unitName=unitName;this.unit=unit;this.child=child;child.on("error",()=>void 0);child.on("exit",(code,signal)=>{this.exitEvidence={exitCode:code,exitSignal:typeof signal==="string"?signal:null}})}static{__name(this,"ManagedChildRunProcess")}exitEvidence=null;settled=false;get exited(){return this.evidence!==null}get evidence(){if(this.exitEvidence!==null)return this.exitEvidence;if(this.child.exitCode!==null||this.child.signalCode!==null){return{exitCode:this.child.exitCode,exitSignal:this.child.signalCode}}return null}async terminate(graceMs){if(this.settled)return this.evidence;if(this.exited&&this.unit.empty()){this.unit.remove();this.settled=true;return this.evidence}try{await this.unit.terminate(graceMs)}catch(error){if(!this.settled)throw error}if(this.settled)return this.evidence;if(!this.unit.empty())return null;this.unit.remove();this.settled=true;return this.evidence}async settleOnEmpty(){if(this.settled)return this.evidence;if(!this.exited)return null;await this.unit.waitForEmpty(Number.MAX_SAFE_INTEGER/2,()=>this.settled);if(this.settled)return this.evidence;if(!this.unit.empty())return null;this.unit.remove();this.settled=true;return this.evidence}};var ManagedChildRunSupervisor=class _ManagedChildRunSupervisor{constructor(cgroupRoot){this.cgroupRoot=cgroupRoot}static{__name(this,"ManagedChildRunSupervisor")}processes=new Map;static create(options){if(options.cgroupRoot===void 0)throw new HookCommandIsolationUnavailableError("root_missing");return new _ManagedChildRunSupervisor(options.cgroupRoot)}get size(){return this.processes.size}process(unitName){return this.processes.get(unitName)}async start(spec,membership){const unit=HookCommandCgroup.create(this.cgroupRoot,spec.unitName);const launch=unit.launch(spec.executable,[...spec.args],spec.env);const child=spawn(launch.executable,launch.args,{cwd:spec.cwd,env:launch.env,stdio:["ignore","pipe","pipe","pipe"]});child.on("error",()=>void 0);child.stdout?.on("data",chunk=>spec.onOutput("stdout",chunk));child.stderr?.on("data",chunk=>spec.onOutput("stderr",chunk));let status="";child.stdio[3]?.on("data",data=>{status+=data.toString()});const prove=membership?.prove??(async(launched,inUnit)=>{for(let attempt=0;attempt<40;attempt++){if(status.includes("joined\n"))return true;if(status.includes("unavailable\n"))return false;try{const members=readFileSync2(join(inUnit.directory,"cgroup.procs"),"utf8");if(launched.pid!==void 0&&members.split("\n").includes(String(launched.pid))){return true}}catch{}await new Promise(resolve=>setTimeout(resolve,50))}return false});if(!await prove(child,unit)){child.kill("SIGKILL");unit.remove();throw new HookCommandIsolationUnavailableError("membership_unproven")}const process_=new ManagedChildRunProcess(spec.unitName,unit,child);this.processes.set(spec.unitName,process_);return process_}attach(unitName){return HookCommandCgroup.attach(this.cgroupRoot,unitName)}forget(unitName){this.processes.delete(unitName)}};init_esbuild_shims();import{once}from"node:events";import{setTimeout as delay}from"node:timers/promises";import{constants}from"node:os";var ManagedBackgroundShellRegistry=class{constructor(eofGraceMs=5e3){this.eofGraceMs=eofGraceMs}static{__name(this,"ManagedBackgroundShellRegistry")}entries=new Map;finished=new Map;get size(){return this.entries.size}hasHolds(sessionId){return this.countBySession(sessionId)>0}countBySession(sessionId){let count=0;for(const entry of this.entries.values()){if(entry.sessionId===sessionId)count++}return count}describe(unitName){const entry=this.entries.get(unitName);return entry?{sessionId:entry.sessionId}:void 0}describeFinished(unitName){return this.finished.get(unitName)}register(params){const entry={...params,stopRequested:false,completion:void 0};entry.completion=this.complete(entry);this.entries.set(params.unitName,entry);return entry.completion}receipt(unitName){return this.entries.get(unitName)?.completion}async terminate(unitName,graceMs){const entry=this.entries.get(unitName);if(!entry)return void 0;entry.stopRequested=true;const evidence=await entry.process.terminate(graceMs);if(evidence===null){return{unitName,evidence:null,captureError:null}}return entry.completion}async stopAll(graceMs){const completions=[...this.entries.values()].map(async entry=>{await this.terminate(entry.unitName,graceMs)});await Promise.allSettled(completions)}async stopSession(sessionId,graceMs){await Promise.allSettled([...this.entries.values()].filter(entry=>entry.sessionId===sessionId).map(async entry=>{await this.terminate(entry.unitName,graceMs)}))}async complete(entry){const{unitName,process:process2,sink,publisher,identity}=entry;let evidence=null;let captureError=null;try{const ended=process2.exited&&process2.evidence!==null?Promise.resolve(process2.evidence):new Promise(resolve=>{process2.child.once("exit",()=>resolve(process2.evidence));process2.child.once("error",cause=>{captureError??=cause instanceof Error?cause.message:String(cause);resolve(null)})});const root=await ended;evidence=root===null?null:await process2.settleOnEmpty();const eof={stdout:false,stderr:false};await Promise.all(["stdout","stderr"].map(async name=>{const stream=process2.child[name];if(!stream||stream.readableEnded){eof[name]=true;return}await Promise.race([once(stream,"end").then(()=>{eof[name]=true}),delay(this.eofGraceMs)])}));sink.setStarted(process2.child.pid??0);sink.setProcessResult({rawOutput:Buffer.alloc(0),output:"",exitCode:evidence?.exitCode??null,signal:signalNumber(evidence?.exitSignal??null),error:null,aborted:false,pid:process2.child.pid,executionMethod:"child_process"});if(entry.stopRequested)sink.setStopRequested();await sink.finish("stdout",eof.stdout&&evidence!==null);await sink.finish("stderr",eof.stderr&&evidence!==null);const envelope=await sink.finalize(evidence?.exitCode===0?"success":"error",[],evidence?.exitCode===0?void 0:{message:evidence===null?"Background Shell ended without exit evidence.":evidence.exitSignal!==null?`Background Shell terminated with ${evidence.exitSignal}.`:"Background Shell exited nonzero."});try{if(publisher.finish){await publisher.finish(identity,envelope)}else if(publisher.accept){const receipt3=await publisher.accept(identity,envelope);void receipt3}}catch(cause){captureError=cause instanceof Error?cause.message:String(cause)}}catch(cause){captureError??=cause instanceof Error?cause.message:String(cause)}finally{this.entries.delete(unitName)}const receipt2={unitName,evidence,captureError};this.finished.set(entry.unitName,{sessionId:entry.sessionId,receipt:receipt2});return receipt2}};function signalNumber(name){if(name===null)return null;const number=constants.signals[name];return typeof number==="number"?number:null}__name(signalNumber,"signalNumber");init_esbuild_shims();var ManagedMonitorRegistry=class{static{__name(this,"ManagedMonitorRegistry")}physical;constructor(eofGraceMs){this.physical=new ManagedBackgroundShellRegistry(eofGraceMs)}get size(){return this.physical.size}hasHolds(sessionId){return this.physical.hasHolds(sessionId)}countBySession(sessionId){return this.physical.countBySession(sessionId)}register(params){return this.physical.register(params)}describe(unitName){return this.physical.describe(unitName)}describeFinished(unitName){return this.physical.describeFinished(unitName)}async terminate(unitName,graceMs){return this.physical.terminate(unitName,graceMs)}async stopSession(sessionId,graceMs){await this.physical.stopSession(sessionId,graceMs)}async stopAll(graceMs){await this.physical.stopAll(graceMs)}};init_esbuild_shims();import{randomUUID}from"node:crypto";import{StringDecoder}from"node:string_decoder";var MONITOR_PARTIAL_LINE_CAP_BYTES=4096;var ManagedMonitorWatcher=class{constructor(supervisor){this.supervisor=supervisor}static{__name(this,"ManagedMonitorWatcher")}async start(command,onLine,onExit,identity){const text2=command["command"];if(typeof text2!=="string"||text2.length===0)throw new Error("Monitor watch names no command.");const shell=getShellConfiguration();const unitName=identity?.unitName??`qwen-mon-${randomUUID()}`;const cwd=identity?.cwd??process.cwd();const decoder=new StringDecoder("utf8");let remainder="";const watch=await this.supervisor.start({unitName,executable:shell.executable,args:[...shell.argsPrefix,text2],env:sanitizeChildEnv(),cwd,onOutput:__name((stream,chunk)=>{identity?.onChunk?.(stream,chunk);if(stream!=="stdout")return;remainder+=decoder.write(chunk);let at=remainder.indexOf("\n");while(at>=0){const line=remainder.slice(0,at);remainder=remainder.slice(at+1);if(line.length>0)onLine(line);at=remainder.indexOf("\n")}if(remainder.length>MONITOR_PARTIAL_LINE_CAP_BYTES)remainder=""},"onOutput")});let exited=false;const end=__name(failed=>{if(exited)return;exited=true;remainder+=decoder.end();if(remainder.length>0){onLine(remainder);remainder=""}onExit(failed)},"end");watch.child.once("exit",()=>end(false));watch.child.once("error",()=>end(true));if(watch.child.exitCode!=null||watch.child.signalCode!=null)setImmediate(()=>end(false));return{receipt:{unitName,pid:watch.child.pid??0,started:true},process:watch,terminate:__name(async()=>await watch.terminate(5e3)!==null,"terminate")}}};var debugLogger=createDebugLogger("MANAGED_TOOL_EXECUTOR");var ManagedMcpToolUnknownError=class extends Error{static{__name(this,"ManagedMcpToolUnknownError")}};var ISOLATION_REFUSAL_CLAUSES={platform:"this Runtime does not run Linux with cgroup v2",root_missing:"no delegated cgroup v2 root is configured on this Runtime",root_shape:"the delegated root on this Runtime is not a cgroup v2 domain directory",root_unreadable:"the delegated cgroup v2 root on this Runtime is missing or unreadable",unit_name_invalid:"its cgroup unit name is not valid on this Runtime",unit_name_taken:"a cgroup unit with the same name already exists on this Runtime",unit_not_empty:"another unit still holds processes under that name on this Runtime",membership_unproven:"the process never proved its cgroup membership on this Runtime"};function isolationRefusal(tool,cause){const{reason}=cause;if(reason===void 0)return{message:`${tool} requires a delegated Linux cgroup v2 directory on this Runtime.`};return{message:`${tool} requires a delegated Linux cgroup v2 directory: ${ISOLATION_REFUSAL_CLAUSES[reason]}.`,type:`managed_isolation_${reason}`}}__name(isolationRefusal,"isolationRefusal");var MANAGED_WORKSPACE_CONTEXT_FILE_BYTES=MANAGED_WORKSPACE_CONTEXT_FILE_CHARS*4;async function readContextFilePrefix(file){const handle=await fs.open(file,"r");try{const buffer=Buffer.allocUnsafe(MANAGED_WORKSPACE_CONTEXT_FILE_BYTES);const{bytesRead}=await handle.read(buffer,0,MANAGED_WORKSPACE_CONTEXT_FILE_BYTES,0);return buffer.toString("utf8",0,bytesRead)}finally{await handle.close()}}__name(readContextFilePrefix,"readContextFilePrefix");var ManagedToolConflictError=class extends Error{constructor(message,code="managed_runtime_identity_conflict"){super(message);this.code=code}static{__name(this,"ManagedToolConflictError")}};var ManagedToolInvalidError=class extends Error{static{__name(this,"ManagedToolInvalidError")}};var ManagedToolUnavailableError=class extends Error{static{__name(this,"ManagedToolUnavailableError")}code="managed_context_unavailable"};var ADMITTED_TOOL_NAMES=new Set([ReadFileTool.Name,WriteFileTool.Name,EditTool.Name,ShellTool.Name,GlobTool.Name]);var MANAGED_BACKGROUND_MAX_SHELLS=8;var MANAGED_MONITOR_MAX_WATCHES=4;var MANAGED_BACKGROUND_OUTPUT_PAUSE_BYTES=16*1024*1024;var MANAGED_BACKGROUND_OUTPUT_RESUME_BYTES=4*1024*1024;var ManagedToolExecutor=class _ManagedToolExecutor{constructor(toolsFor,capturePublisher,mcp,hooks,ownsAnotherSessionDir,backgroundSupervisor,backgroundRegistry,monitorRegistry,options={}){this.toolsFor=toolsFor;this.capturePublisher=capturePublisher;this.mcp=mcp;this.hooks=hooks;this.ownsAnotherSessionDir=ownsAnotherSessionDir;this.backgroundSupervisor=backgroundSupervisor;this.options=options;this.backgroundRegistry=backgroundRegistry??new ManagedBackgroundShellRegistry;this.monitorRegistry=monitorRegistry??new ManagedMonitorRegistry;this.monitorWatcher=backgroundSupervisor?new ManagedMonitorWatcher(backgroundSupervisor):void 0}static{__name(this,"ManagedToolExecutor")}entries=new Map;backgroundRegistry;monitorRegistry;monitorWatcher;mcpCalls=new Map;providerSessions=new Set;closedSessions=new Set;provider;closing=false;retirementId;providerWasUsed=false;capturePreparationStarted=false;historyControlOutcomeUnknown=false;pendingStarts=new Set;fileHistories=new Map;historyControls=new Set;get isAdmissionOpen(){return!this.closing&&this.retirementId===void 0}get isAdmissionSealed(){return this.retirementId!==void 0}sealAdmission(retirementId){if(!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(retirementId))throw new ManagedToolInvalidError("Retirement identity is invalid.");if(this.retirementId!==void 0&&this.retirementId!==retirementId)throw new ManagedToolConflictError("Retirement identity conflicts.");this.retirementId=retirementId;this.mcp?.sealAdmission();this.hooks?.sealAdmission()}getDrainObservation(retirementId){if(this.retirementId===void 0||this.retirementId!==retirementId)throw new ManagedToolConflictError("Retirement identity conflicts.");const blockers=new Set;if(this.closing)blockers.add("shutdown_started");if(this.capturePreparationStarted)blockers.add("capture_preparation_unqualified");if(this.capturePublisher?.hasInstalledPublication)blockers.add("publication_lifecycle_unqualified");if(this.historyControlOutcomeUnknown)blockers.add("history_control_outcome_unknown");let pendingInvocations=0;for(const entry of this.entries.values()){if(entry.toolName===ShellTool.Name)blockers.add("shell_lifecycle_unqualified");if(entry.state==="unknown")blockers.add("execution_outcome_unknown");else if(entry.state==="acknowledged")continue;else if(entry.state!=="settled")pendingInvocations++;else if(entry.version===2&&!entry.result)blockers.add("execution_result_missing");else if(entry.version===3){const result=entry.v3Result;if(!result)blockers.add("execution_result_missing");else if(result.executionStatus!=="not_started"){if(result.capture?.captureStatus!=="complete")blockers.add("capture_incomplete");if(result.capture?.deliveryStatus!=="committed"||entry.acknowledgement?.deliveryStatus!=="committed")blockers.add("capture_uncommitted")}}}const provider=this.provider?.getDrainInspection();if(this.providerWasUsed||provider?.hasActivity)blockers.add("provider_lifecycle_unqualified");pendingInvocations+=provider?.pendingInvocations??0;const mcp=this.mcp?.getDrainInspection();if(this.mcpCalls.size>0||mcp?.hasActivity)blockers.add("mcp_lifecycle_unqualified");pendingInvocations+=mcp?.pendingInvocations??0;const hooks=this.hooks?.getDrainInspection();if(hooks?.hasActivity)blockers.add("hook_lifecycle_unqualified");pendingInvocations+=hooks?.pendingInvocations??0;const pendingStarts=this.pendingStarts.size+(mcp?.pendingStarts??0)+(hooks?.pendingStarts??0);return{state:"DRAINING",workState:blockers.size>0?"BLOCKED":pendingStarts>0||pendingInvocations>0?"PENDING":"QUIESCENT",pendingStarts,pendingInvocations,blockers:[...blockers].sort()}}controlFileHistory(ownerSessionId,sessionId,operation){if(this.isAdmissionSealed){const history2=this.fileHistories.get(sessionId);if(operation.action!=="snapshot")return Promise.reject(new ManagedToolUnavailableError("Managed Runtime admission is sealed."));if(!history2||history2.ownerSessionId!==ownerSessionId)return Promise.reject(new ManagedToolConflictError("File history is not bound to this Workspace."));if(this.hasActiveSession(sessionId))return Promise.reject(new ManagedToolConflictError("File history requires an idle Runtime Session."));return Promise.resolve(history2.state())}return this.trackStart(()=>this.controlFileHistoryAdmitted(ownerSessionId,sessionId,operation))}async controlFileHistoryAdmitted(ownerSessionId,sessionId,operation){this.assertLegacySession(sessionId);if(this.closing||this.hasActiveToolSession(sessionId)||operation.action==="rewind"&&this.hooks?.hasHolds(sessionId)===true||[...this.entries.values()].some(entry=>entry.reference.sessionId===sessionId&&entry.state==="unknown"))throw new ManagedToolConflictError("File history requires an idle Runtime Session.");this.historyControls.add(sessionId);let mutationStarted=false;try{const tools=await this.toolsFor({sessionId,promptId:sessionId,callId:"history",argsDigest:""});if(!this.isAdmissionOpen||!tools?.directory||tools.isActive?.()===false)throw new ManagedToolUnavailableError("File history Workspace is unavailable.");const existingHistory=this.fileHistories.get(sessionId);let history2=tools.fileHistory??existingHistory;if(tools.retainedFileHistory&&!tools.fileHistory)throw new ManagedToolConflictError("Retained file history requires its original composition.");if(tools.fileHistory&&(tools.fileHistory.ownerSessionId!==ownerSessionId||tools.fileHistory.directory!==tools.directory||existingHistory&&existingHistory!==tools.fileHistory))throw new ManagedToolConflictError("File history binding conflicts.");if(operation.action==="bind"){if(!history2){history2=new ManagedRuntimeFileHistory(ownerSessionId,tools.directory,operation.state);await history2.ready();if(!this.isAdmissionOpen)throw new ManagedToolUnavailableError("Managed Runtime admission is sealed.");this.fileHistories.set(sessionId,history2)}else if(history2.ownerSessionId!==ownerSessionId||history2.directory!==tools.directory||!isDeepStrictEqual2(history2.state(),operation.state??{ownerSessionId,snapshots:[],files:{}})){throw new ManagedToolConflictError("File history binding conflicts.")}}if(!history2||history2.ownerSessionId!==ownerSessionId||history2.directory!==tools.directory)throw new ManagedToolConflictError("File history is not bound to this Workspace.");this.fileHistories.set(sessionId,history2);if(operation.action==="prepare"){mutationStarted=true;await history2.prepare(operation.promptId,operation.paths)}if(operation.action==="rewind"){mutationStarted=true;const result=await history2.rewind(operation.promptId);if(result.filesFailed.length>0)this.historyControlOutcomeUnknown=true;return result}await history2.ready();return history2.state()}catch(error){if(mutationStarted)this.historyControlOutcomeUnknown=true;throw error}finally{this.historyControls.delete(sessionId)}}async readWorkspaceContext(sessionId){return this.trackStart(()=>this.readWorkspaceContextAdmitted(sessionId))}async readWorkspaceContextAdmitted(sessionId){if(this.closedSessions.has(sessionId))throw new ManagedToolUnavailableError("Workspace context is unavailable.");const tools=await this.toolsFor({sessionId,promptId:sessionId,callId:"workspace-context",argsDigest:""});if(!this.isAdmissionOpen||!tools?.directory||tools.isActive?.()===false)throw new ManagedToolUnavailableError("Workspace context is unavailable.");let boundary;try{boundary=await fs.realpath(tools.directory)}catch{throw new ManagedToolUnavailableError("Workspace context is unavailable.")}const files=[];const seen=new Set;for(const name of MANAGED_WORKSPACE_CONTEXT_FILES){let text2;try{const real=await fs.realpath(path2.join(tools.directory,name));const rel=path2.relative(boundary,real);if(rel===".."||rel.startsWith(`..${path2.sep}`)||path2.isAbsolute(rel))continue;if(await this.ownsAnotherSessionDir?.(tools.sessionId,real,boundary))continue;if(seen.has(real))continue;seen.add(real);const stat=await fs.stat(real);if(!stat.isFile())continue;text2=stat.size>MANAGED_WORKSPACE_CONTEXT_FILE_BYTES?await readContextFilePrefix(real):await fs.readFile(real,"utf8")}catch{continue}if(text2.length>MANAGED_WORKSPACE_CONTEXT_FILE_CHARS){const note="\n[Truncated: the file exceeds the Hosted context limit.]";text2=text2.slice(0,MANAGED_WORKSPACE_CONTEXT_FILE_CHARS-note.length);if(/[\uD800-\uDBFF]$/.test(text2))text2=text2.slice(0,-1);text2+=note}files.push({name,text:text2})}return{files}}static forWorkspace(workspaceCwd,runtimeInstanceId,options){const tools=createManagedToolSet(workspaceCwd,runtimeInstanceId);return new _ManagedToolExecutor(async()=>tools,void 0,void 0,void 0,void 0,void 0,void 0,void 0,options)}hasTool(toolName){return ADMITTED_TOOL_NAMES.has(toolName)||toolName===MANAGED_MCP_TOOL&&this.mcp!==void 0}attachProvider(provider){this.provider=provider}claimProviderSession(sessionId){if(!this.isAdmissionOpen||this.historyControls.has(sessionId)||this.fileHistories.has(sessionId)||this.closedSessions.has(sessionId)||[...this.entries.values()].some(entry=>entry.reference.sessionId===sessionId)||[...this.mcpCalls.values()].some(entry=>entry.reference.sessionId===sessionId)){throw new ManagedToolConflictError("Managed Runtime Session conflicts.")}this.providerWasUsed=true;this.providerSessions.add(sessionId)}unclaimProviderSession(sessionId){this.providerSessions.delete(sessionId)}closeSessionAdmission(sessionId){if(this.hasActiveSession(sessionId)){throw new ManagedToolConflictError("Managed Runtime Session still owns unfinished work.","managed_runtime_owner_hold_pending")}this.closedSessions.add(sessionId);if(this.retirementId===void 0)this.fileHistories.delete(sessionId)}assertLegacySession(sessionId){if(this.historyControls.has(sessionId)||this.providerSessions.has(sessionId)||this.closedSessions.has(sessionId)){throw new ManagedToolConflictError("Managed Runtime protocol conflicts.")}}execute(reference2,toolName,input){return this.trackStart(()=>this.executeAdmitted(reference2,toolName,input))}async executeAdmitted(reference2,toolName,input){this.assertLegacySession(reference2.sessionId);if(this.closing){throw new ManagedToolUnavailableError("Managed Runtime worker is closing.")}if(toolName===MANAGED_MCP_TOOL&&this.mcp){const existing2=this.mcpCalls.get(reference2.callId);const inputJson2=JSON.stringify(input);if(this.entries.has(reference2.callId)||existing2&&(!sameReference(existing2.reference,reference2)||existing2.inputJson!==inputJson2))throw new ManagedToolConflictError("Managed MCP invocation identity conflicts.");if(existing2?.refusal)return existing2.refusal;if(!existing2){this.assertAdmissionOpen();const tools2=await this.toolsFor(reference2);this.assertLegacySession(reference2.sessionId);if(!this.isAdmissionOpen||!tools2||tools2.isActive?.()===false)throw new ManagedToolUnavailableError("Managed MCP Session is unavailable.");if(this.mcpCalls.has(reference2.callId))return this.execute(reference2,toolName,input);const control=parseManagedMcpControl(input);if(control.kind!=="mcp-invoke"||control.request.kind!=="tool_call"||control.operationId!==reference2.callId)throw new ManagedToolInvalidError("Managed MCP tool input is invalid.");this.mcpCalls.set(reference2.callId,{reference:reference2,input:structuredClone(input),inputJson:inputJson2})}let result;try{result=await this.mcp.invokeTool(reference2.sessionId,input)}catch(error){if(!(error instanceof ManagedMcpError))throw error;const refusal2={executionStatus:"not_started",responseParts:[],error:{type:error.code,message:error.code}};this.mcpCalls.get(reference2.callId).refusal=refusal2;return refusal2}if(result.state!=="settled")throw new ManagedMcpToolUnknownError("Managed MCP execution outcome is unknown.");return mcpPayload(result)}if(this.mcpCalls.has(reference2.callId))throw new ManagedToolConflictError("Managed Runtime protocol conflicts.");let inputJson;try{inputJson=JSON.stringify(input)}catch{throw new ManagedToolInvalidError("Managed Runtime tool request is invalid.")}const existing=this.entries.get(reference2.callId);if(existing){if(existing.version!==2){throw new ManagedToolConflictError("Managed Runtime protocol conflicts.")}return join2(existing,reference2,toolName,inputJson)}this.assertAdmissionOpen();const tools=await this.toolsFor(reference2);this.assertLegacySession(reference2.sessionId);const joined=this.entries.get(reference2.callId);if(joined){if(joined.version!==2){throw new ManagedToolConflictError("Managed Runtime protocol conflicts.")}return join2(joined,reference2,toolName,inputJson)}if(!this.isAdmissionOpen){throw new ManagedToolUnavailableError("Managed Runtime worker is closing.")}if(tools===void 0||tools.isActive?.()===false){throw new ManagedToolUnavailableError("Managed context directory is unavailable.")}const tool=tools.tools.get(toolName);if(!tool){throw new ManagedToolConflictError(`Managed Runtime does not admit tool ${toolName}.`)}if(toolName===ShellTool.Name){let isBackground=false;try{const params=structuredClone(input);isBackground=tool.validateToolParams(params)===null&¶ms["is_background"]===true}catch{}if(isBackground){throw new ManagedToolConflictError("Managed Runtime does not admit background shell execution.")}}const entry={version:2,reference:reference2,toolName,input,inputJson,state:"prepared",lastSequence:0,controller:new AbortController};this.entries.set(reference2.callId,entry);entry.promise=this.run(entry,tool,tools,tools.directory);return join2(entry,reference2,toolName,inputJson)}executeV3(request){return this.trackStart(()=>this.executeV3Admitted(request))}async executeV3Admitted(request){if(this.closing){throw new ManagedToolUnavailableError("Managed Runtime worker is closing.")}const{reference:reference2,capture:capture2,toolName,input}=request;this.assertLegacySession(reference2.sessionId);let inputJson;let inputDigest;try{inputJson=JSON.stringify(input);inputDigest=managedToolDigest(input)}catch{throw new ManagedToolInvalidError("Managed Runtime tool request is invalid.")}if(reference2.argsDigest.replace(/^sha256:/,"")!==inputDigest){throw new ManagedToolConflictError("Managed Runtime invocation digest conflicts.")}const existing=this.entries.get(reference2.callId);if(existing){if(existing.version!==3||!sameReference(existing.reference,reference2)||existing.toolName!==toolName||!sameCapture(existing.v3Capture,capture2)){throw new ManagedToolConflictError("Managed Runtime invocation identity conflicts.")}if(!existing.capturePublisher?.finish)await existing.promise;return v3View(existing)}this.assertAdmissionOpen();if(!this.capturePublisher||toolName!==ShellTool.Name&&toolName!=="monitor"){throw new ManagedToolUnavailableError("Tool v3 capture is not available.")}const tools=await this.toolsFor(reference2);this.assertLegacySession(reference2.sessionId);const joined=this.entries.get(reference2.callId);if(joined)return this.executeV3(request);if(!this.isAdmissionOpen||!tools||tools.isActive?.()===false){throw new ManagedToolUnavailableError("Managed context directory is unavailable.")}if(toolName==="monitor"){return this.executeV3Monitor(request,tools,structuredClone(input))}const normalized=structuredClone(input);if(normalized["is_background"]===true){return this.executeV3Background(request,tools,normalized)}if(normalized["is_monitor"]===true){return this.executeV3Monitor(request,tools,normalized)}const tool=tools.tools.get(toolName);if(!tool)throw new ManagedToolUnavailableError("Foreground Shell is unavailable.");let prepared;try{this.capturePreparationStarted=true;prepared=await this.capturePublisher.prepare({reference:reference2,capture:capture2})}catch(cause){throw new ManagedToolUnavailableError(cause instanceof Error?cause.message:String(cause))}if(this.entries.has(reference2.callId))return this.executeV3(request);this.assertLegacySession(reference2.sessionId);if(!this.isAdmissionOpen||tools.isActive?.()===false){throw new ManagedToolUnavailableError("Managed Runtime worker is no longer active.")}const entry={version:3,reference:reference2,toolName,input,inputJson,v3Capture:capture2,captureSink:prepared.sink,capturePublisher:prepared.publisher??this.capturePublisher,state:"prepared",lastSequence:0,controller:new AbortController};this.entries.set(reference2.callId,entry);entry.promise=this.run(entry,tool,tools);if(!entry.capturePublisher?.finish)await entry.promise;return v3View(entry)}async executeV3Background(request,tools,normalized){const{reference:reference2,capture:capture2,input}=request;if(this.entries.has(reference2.callId))return this.executeV3(request);const entry={version:3,reference:reference2,toolName:request.toolName,input,inputJson:JSON.stringify(input),v3Capture:capture2,state:"prepared",lastSequence:0,controller:new AbortController};this.entries.set(reference2.callId,entry);const settle=__name(result=>{entry.v3Result=result;entry.state="settled";entry.lastSequence=1;this.entries.set(reference2.callId,entry);return v3View(entry)},"settle");if(!this.backgroundSupervisor){return settle({executionStatus:"not_started",responseParts:[],capture:null,error:{message:"Background Shell requires a delegated Linux cgroup v2 root on this Runtime.",type:"managed_isolation_root_missing"}})}let directory;const requestedDirectory=normalized["directory"];if(typeof requestedDirectory==="string"&&requestedDirectory!==""){if(!tools.admitsDirectory(requestedDirectory)){return settle({executionStatus:"not_started",responseParts:[],capture:null,error:{message:`Directory '${requestedDirectory}' is not within any of the registered workspace directories.`}})}directory=requestedDirectory}else if(tools.directory!==void 0){directory=tools.directory}else{return settle({executionStatus:"not_started",responseParts:[],capture:null,error:{message:"Managed Runtime Session has no workspace directory."}})}const command=normalized["command"];if(typeof command!=="string"||!command.trim()){return settle({executionStatus:"not_started",responseParts:[],capture:null,error:{message:"Hosted Shell requires a nonempty command."}})}if(this.backgroundRegistry.countBySession(reference2.sessionId)>=MANAGED_BACKGROUND_MAX_SHELLS){return settle({executionStatus:"not_started",responseParts:[],capture:null,error:{message:`Session already runs ${MANAGED_BACKGROUND_MAX_SHELLS} background Shells.`}})}let prepared;try{prepared=await this.capturePublisher.prepare({reference:reference2,capture:{...capture2,background:true}})}catch(cause){return settle({executionStatus:"not_started",responseParts:[],capture:null,error:{message:`Background Shell capture could not be prepared: ${cause instanceof Error?cause.message:String(cause)}`}})}if(this.closing||tools.isActive?.()===false){return settle({executionStatus:"not_started",responseParts:[],capture:null,error:{message:"Managed Runtime worker is no longer active."}})}const sink=prepared.sink;const publisher=prepared.publisher??this.capturePublisher;const unitName=`qwen-bg-${reference2.callId.replace(/[^a-zA-Z0-9._-]/g,"-")}`;const shellConfig=getShellConfiguration();let process2;let bufferedBytes=0;let paused=false;const applyPause=__name(next=>{paused=next;const child=process2?.child;if(!child)return;for(const stream of[child.stdout,child.stderr]){if(!stream)continue;if(next){if(!stream.isPaused())stream.pause()}else if(stream.isPaused()){stream.resume()}}},"applyPause");try{process2=await this.backgroundSupervisor.start({unitName,executable:shellConfig.executable,args:[...shellConfig.argsPrefix,command],env:backgroundEnv(tools.sessionId),cwd:directory,onOutput:__name((stream,chunk)=>{bufferedBytes+=chunk.byteLength;if(paused)applyPause(true);const written=sink.write(stream,chunk);void written.then(()=>{bufferedBytes-=chunk.byteLength;if(paused&&bufferedBytes<=MANAGED_BACKGROUND_OUTPUT_RESUME_BYTES)applyPause(false)},()=>{bufferedBytes-=chunk.byteLength;if(paused&&bufferedBytes<=MANAGED_BACKGROUND_OUTPUT_RESUME_BYTES)applyPause(false)});if(!paused&&bufferedBytes>=MANAGED_BACKGROUND_OUTPUT_PAUSE_BYTES)applyPause(true)},"onOutput")})}catch(cause){return settle({executionStatus:"not_started",responseParts:[],capture:null,error:cause instanceof HookCommandIsolationUnavailableError?isolationRefusal("Background Shell",cause):{message:`Background Shell could not start: ${cause instanceof Error?cause.message:String(cause)}`}})}sink.setStarted(process2.child.pid??0);if(paused)applyPause(true);this.backgroundRegistry.register({unitName,sessionId:reference2.sessionId,process:process2,sink,publisher,identity:prepared.identity});return settle({executionStatus:"success",responseParts:[{text:`Background shell started under unit ${unitName}. It keeps running after this result and holds its Runtime until it exits; read its status and output through the task surface.`}],capture:{captureStatus:"detached",captureReason:null,manifest:null,previewTruncated:false,deliveryStatus:"pending"}})}async executeV3Monitor(request,tools,normalized){const{reference:reference2,capture:capture2,input}=request;if(this.entries.has(reference2.callId))return this.executeV3(request);const entry={version:3,reference:reference2,toolName:request.toolName,input,inputJson:JSON.stringify(input),v3Capture:capture2,state:"prepared",lastSequence:0,controller:new AbortController};this.entries.set(reference2.callId,entry);const settle=__name(result=>{entry.v3Result=result;entry.state="settled";entry.lastSequence=1;this.entries.set(reference2.callId,entry);return v3View(entry)},"settle");if(this.monitorWatcher===void 0){return settle({executionStatus:"not_started",responseParts:[],capture:null,error:{message:"Monitor watch requires a delegated Linux cgroup v2 root on this Runtime.",type:"managed_isolation_root_missing"}})}const command=normalized["command"];if(typeof command!=="string"||!command.trim()){return settle({executionStatus:"not_started",responseParts:[],capture:null,error:{message:"Monitor watch requires a nonempty command."}})}if(this.capturePublisher===void 0){return settle({executionStatus:"not_started",responseParts:[],capture:null,error:{message:"Monitor watch capture is unavailable."}})}if(this.monitorRegistry.countBySession(reference2.sessionId)>=MANAGED_MONITOR_MAX_WATCHES){return settle({executionStatus:"not_started",responseParts:[],capture:null,error:{message:`Session already runs ${MANAGED_MONITOR_MAX_WATCHES} Monitor watches.`}})}let directory=tools.directory;if(typeof normalized["directory"]==="string"&&normalized["directory"]!==""){if(!tools.admitsDirectory(normalized["directory"])){return settle({executionStatus:"not_started",responseParts:[],capture:null,error:{message:`Directory '${normalized["directory"]}' is not within any of the registered workspace directories.`}})}directory=normalized["directory"]}let prepared;try{prepared=await this.capturePublisher.prepare({reference:reference2,capture:{...capture2,background:true,monitoring:true}})}catch(cause){return settle({executionStatus:"not_started",responseParts:[],capture:null,error:{message:`Monitor watch capture could not be prepared: ${cause instanceof Error?cause.message:String(cause)}`}})}if(this.closing||tools.isActive?.()===false){return settle({executionStatus:"not_started",responseParts:[],capture:null,error:{message:"Managed Runtime worker is no longer active."}})}const sink=prepared.sink;const publisher=prepared.publisher??this.capturePublisher;const unitName=`qwen-mon-${reference2.callId.replace(/[^a-zA-Z0-9._-]/g,"-")}`;let watchHandle;let bufferedBytes=0;let paused=false;const applyPause=__name(next=>{paused=next;const child=watchHandle?.process?.child;if(!child)return;for(const stream of[child.stdout,child.stderr]){if(!stream)continue;if(next){if(!stream.isPaused())stream.pause()}else if(stream.isPaused()){stream.resume()}}},"applyPause");const acceptChunk=__name((stream,chunk)=>{bufferedBytes+=chunk.byteLength;if(paused)applyPause(true);const written=sink.write(stream,chunk);const release=__name(()=>{bufferedBytes-=chunk.byteLength;if(paused&&bufferedBytes<=MANAGED_BACKGROUND_OUTPUT_RESUME_BYTES)applyPause(false)},"release");void written.then(release,release);if(!paused&&bufferedBytes>=MANAGED_BACKGROUND_OUTPUT_PAUSE_BYTES)applyPause(true)},"acceptChunk");try{watchHandle=await this.monitorWatcher.start({command},_observationLine=>{},()=>void 0,{unitName,cwd:directory,onChunk:acceptChunk})}catch(cause){return settle({executionStatus:"not_started",responseParts:[],capture:null,error:cause instanceof HookCommandIsolationUnavailableError?isolationRefusal("Monitor watch",cause):{message:`Monitor watch could not start: ${cause instanceof Error?cause.message:String(cause)}`}})}const watchProcess=watchHandle.process;if(watchProcess===void 0){return settle({executionStatus:"not_started",responseParts:[],capture:null,error:{message:"Monitor watch reported no supervised unit."}})}sink.setStarted(watchProcess.child.pid??0);if(paused)applyPause(true);this.monitorRegistry.register({unitName,sessionId:reference2.sessionId,process:watchProcess,sink,publisher,identity:prepared.identity});return settle({executionStatus:"success",responseParts:[{text:`Monitor watch started under unit ${unitName}. It keeps running after this result and holds its Runtime until it exits; read its status and output through the task surface.`}],capture:{captureStatus:"detached",captureReason:null,manifest:null,previewTruncated:false,deliveryStatus:"pending"}})}statusV3(reference2){const entry=this.entries.get(reference2.callId);if(!entry)return{state:"unknown"};if(entry.version!==3||!sameReference(entry.reference,reference2)){throw new ManagedToolConflictError("Managed Runtime protocol conflicts.")}return v3View(entry)}cancelV3(reference2){const entry=this.entries.get(reference2.callId);if(!entry)return{state:"unknown"};if(entry.version!==3||!sameReference(entry.reference,reference2)){throw new ManagedToolConflictError("Managed Runtime protocol conflicts.")}if(entry.state==="prepared"){entry.v3Result={executionStatus:"not_started",responseParts:[],capture:null};entry.state="settled";entry.lastSequence++}else if(entry.state==="executing"){entry.state="cancel_requested";entry.lastSequence++;entry.controller.abort()}return v3View(entry)}acknowledgeV3(reference2,receipt2){const entry=this.entries.get(reference2.callId);if(!entry)return{state:"unknown"};if(entry.version!==3||!sameReference(entry.reference,reference2)){throw new ManagedToolConflictError("Managed Runtime protocol conflicts.")}if(!entry.v3Result||entry.state!=="settled"){throw new ManagedToolConflictError("Tool result has not settled.","managed_tool_result_conflict")}const actual=entry.v3Result.capture;if(receipt2.executionCallId!==entry.v3Capture?.executionCallId){throw new ManagedToolConflictError("Tool result receipt conflicts.","managed_tool_result_conflict")}if(actual===null?receipt2.manifest!==null:JSON.stringify(receipt2.manifest)!==JSON.stringify(actual.manifest)){throw new ManagedToolConflictError("Tool result receipt conflicts.","managed_tool_result_conflict")}if(actual!==null&&receipt2.deliveryStatus==="committed"&&(actual.captureStatus!=="complete"||!Number.isSafeInteger(receipt2.historyRevision)||(receipt2.historyRevision??0)<1)){throw new ManagedToolConflictError("Tool result receipt conflicts.","managed_tool_result_conflict")}if(receipt2.deliveryStatus==="blocked"&&receipt2.historyRevision!==null){throw new ManagedToolConflictError("Tool result receipt conflicts.","managed_tool_result_conflict")}if(entry.acknowledgement&&JSON.stringify(entry.acknowledgement)!==JSON.stringify(receipt2)){throw new ManagedToolConflictError("Tool result was acknowledged differently.","managed_tool_result_conflict")}entry.acknowledgement=receipt2;entry.v3Result={...entry.v3Result,capture:actual===null?null:{captureStatus:actual.captureStatus,captureReason:actual.captureReason,manifest:actual.manifest,previewTruncated:actual.previewTruncated,deliveryStatus:receipt2.deliveryStatus}};return v3View(entry)}acknowledgeOriginalCsi(request,boot,pod){const parsed=parseManagedCsiAckRequest(request,boot,pod);const entry=this.entries.get(parsed.reference.callId);if(this.retirementId!==parsed.retirementId||!entry||entry.version!==3||!sameReference(entry.reference,parsed.reference)||entry.state!=="settled"||!entry.v3Result||!["success","error","cancelled"].includes(entry.v3Result.executionStatus)||entry.v3Result.capture?.captureStatus!=="complete"||entry.v3Result.capture.deliveryStatus==="blocked"||!entry.v3Capture||!entry.captureSink)throw new ManagedCsiAckRequestError(409);try{const identity=parseManagedCsiCaptureIdentity(entry.captureSink.identity);if(identity.tenantId!==boot.context.tenantId||identity.tenantId!==entry.v3Capture.tenantId||identity.sessionId!==entry.v3Capture.sessionId||identity.turnId!==entry.v3Capture.turnId||identity.executionCallId!==entry.v3Capture.executionCallId||identity.bindingGeneration!==entry.v3Capture.bindingGeneration||identity.callId!==entry.reference.callId||identity.invocationDigest!==entry.reference.argsDigest)throw new Error;const actual=parseManagedCsiAcknowledgement({executionCallId:entry.v3Capture.executionCallId,manifest:entry.v3Result.capture.manifest,deliveryStatus:"committed",historyRevision:parsed.acknowledgement.historyRevision});if(!isDeepStrictEqual2(actual,parsed.acknowledgement)||entry.acknowledgement&&!isDeepStrictEqual2(parseManagedCsiAcknowledgement(entry.acknowledgement),parsed.acknowledgement))throw new Error;const response=parseManagedCsiAckResponse({...parsed,state:"ACKNOWLEDGED",captureIdentity:identity},boot,pod);const json=JSON.stringify(response);if(Buffer.byteLength(json,"utf8")>MANAGED_CSI_ACK_LIMIT_BYTES)throw new Error;if(entry.acknowledgement){if(entry.v3Result.capture.deliveryStatus!=="committed")throw new Error}else{this.acknowledgeV3(entry.reference,{...parsed.acknowledgement,manifest:entry.v3Result.capture.manifest})}return{response,json}}catch{throw new ManagedCsiAckRequestError(409)}}hasActiveSession(sessionId){return this.hooks?.hasHolds(sessionId)===true||this.hasActiveToolSession(sessionId)}hasActiveToolSession(sessionId){if(this.historyControls.has(sessionId))return true;return this.mcp?.hasHolds(sessionId)===true||this.provider?.hasActiveSession(sessionId)===true||this.backgroundRegistry.hasHolds(sessionId)||this.monitorRegistry.hasHolds(sessionId)||[...this.entries.values()].some(entry=>entry.reference.sessionId===sessionId&&entry.state!=="settled"&&entry.state!=="acknowledged"&&entry.state!=="unknown")}status(reference2){const mcp=this.mcpCalls.get(reference2.callId);if(mcp&&this.mcp){if(!sameReference(mcp.reference,reference2))return null;if(mcp.refusal)return{state:"settled",lastSequence:1,result:mcp.refusal};return mcpView(this.mcp.toolStatus(reference2.sessionId,mcp.input))}const entry=this.entries.get(reference2.callId);if(entry&&entry.version!==2){throw new ManagedToolConflictError("Managed Runtime protocol conflicts.")}if(!entry||!sameReference(entry.reference,reference2)){return null}return view(entry)}cancel(reference2){const mcp=this.mcpCalls.get(reference2.callId);if(mcp&&this.mcp){if(!sameReference(mcp.reference,reference2))return null;if(mcp.refusal)return{state:"settled",lastSequence:1,result:mcp.refusal};this.mcp.cancelTool(reference2.sessionId,mcp.input);return mcpView(this.mcp.toolStatus(reference2.sessionId,mcp.input))}const entry=this.entries.get(reference2.callId);if(entry&&entry.version!==2){throw new ManagedToolConflictError("Managed Runtime protocol conflicts.")}if(!entry||!sameReference(entry.reference,reference2)){return null}if(entry.state==="prepared"){entry.result={executionStatus:"cancelled",responseParts:[]};entry.state="settled";entry.lastSequence+=1;return view(entry)}if(entry.state==="executing"){entry.state="cancel_requested";entry.lastSequence+=1;entry.controller.abort()}return view(entry)}acknowledge(reference2){const entry=this.entries.get(reference2.callId);if(entry&&entry.version!==2){throw new ManagedToolConflictError("Managed Runtime protocol conflicts.")}if(!entry||!sameReference(entry.reference,reference2)){return null}if(entry.state!=="settled"){if(entry.state==="acknowledged")return view(entry);throw new ManagedToolConflictError("Managed Runtime tool call has not settled.")}entry.input=void 0;entry.inputJson=void 0;entry.result=void 0;entry.state="acknowledged";entry.lastSequence+=1;return view(entry)}async close(){this.closing=true;await Promise.all([this.mcp?.close(),this.hooks?.close()]);for(const entry of this.entries.values()){if(entry.state==="executing"||entry.state==="cancel_requested"){entry.controller.abort()}}await Promise.allSettled([...this.pendingStarts,...[...this.entries.values()].flatMap(entry=>entry.promise?[entry.promise]:[]),this.provider?.close(),this.backgroundRegistry.stopAll(5e3),this.monitorRegistry.stopAll(5e3)]);if(this.options.ledger){try{const remaining=await this.options.ledger.killOutstanding();if(remaining.length===0){this.options.ledger.complete()}else{debugLogger.warn(`Managed Runtime worker could not prove ${remaining.length} Shell process group(s) stopped: ${remaining.map(group=>group.pgid).join(", ")}`)}}catch(error){debugLogger.warn(`Managed Runtime worker could not sweep its ledger on close: ${error instanceof Error?error.message:String(error)}`)}}}async stopBackgroundSession(sessionId){await Promise.all([this.backgroundRegistry.stopSession(sessionId,5e3),this.monitorRegistry.stopSession(sessionId,5e3)])}trackStart(action){if(this.closing){return Promise.reject(new ManagedToolUnavailableError("Managed Runtime worker is closing."))}const pending=action();this.pendingStarts.add(pending);void pending.then(()=>this.pendingStarts.delete(pending),()=>this.pendingStarts.delete(pending));return pending}assertAdmissionOpen(){if(!this.isAdmissionOpen)throw new ManagedToolUnavailableError("Managed Runtime admission is sealed.")}static isCancelRequested(entry){return entry.state==="cancel_requested"}async run(entry,tool,tools,directory){const{sessionId}=tools;entry.state="executing";entry.lastSequence+=1;let payload;let shellPgid;let invocationStarted=false;try{const params=structuredClone(entry.input);let fileInvocation;if(directory&&entry.toolName!==ShellTool.Name&&entry.toolName!==GlobTool.Name&&typeof params["file_path"]==="string"){params["file_path"]=path2.resolve(directory,params["file_path"].trim());let buildError;try{fileInvocation=sessionIdContext.run(sessionId,()=>tool.build(params))}catch(error){buildError=error}const realTarget=tools.retainedFileHistory?params["file_path"]:await realpathDeepestExisting(params["file_path"]);const realDirectory=tools.retainedFileHistory?directory:await realpathDeepestExisting(directory);const relative=path2.relative(realDirectory,realTarget);let outOfBoundary=false;if(relative===".."||relative.startsWith(`..${path2.sep}`)||path2.isAbsolute(relative)){const workspaceRoot=tools.workspaceRoot;outOfBoundary=tools.retainedFileHistory!==void 0||workspaceRoot===void 0||escapesSession(path2.relative(await realpathDeepestExisting(workspaceRoot),realTarget))}outOfBoundary||=Boolean(await this.ownsAnotherSessionDir?.(tools.sessionId,realTarget,realDirectory));if(outOfBoundary){throw new Error(`Path '${entry.input["file_path"]}' is not within the Session working directory.`)}if(buildError!==void 0)throw buildError}if(entry.toolName===GlobTool.Name){const root=tools.directory;if(root===void 0)throw new ManagedToolUnavailableError("Managed context directory is unavailable.");const pattern=typeof params["pattern"]==="string"?params["pattern"]:"";const check=checkHostedGlobPattern(pattern);if(check==="too-complex")throw new Error(HOSTED_GLOB_TOO_COMPLEX);if(check==="escapes"){throw new Error("Glob pattern must stay within the Session working directory.")}let globBuildError;try{fileInvocation=sessionIdContext.run(sessionId,()=>tool.build(params))}catch(error){globBuildError=error}const requested=typeof params["path"]==="string"?params["path"].trim():"";const resolved=requested===""||requested==="."?root:path2.resolve(root,requested);const realRoot=await realpathDeepestExisting(root);const realResolved=await realpathDeepestExisting(resolved);if(escapesSession(path2.relative(realRoot,realResolved))||await this.ownsAnotherSessionDir?.(tools.sessionId,realResolved,realRoot)){throw new Error(`Path '${requested}' is not within the Session working directory.`)}if(globBuildError!==void 0)throw globBuildError;params["path"]=resolved}if(entry.toolName===ShellTool.Name&&typeof params["directory"]==="string"&¶ms["directory"]!==""&&!tools.admitsDirectory(params["directory"])){throw new Error(`Directory '${params["directory"]}' is not within any of the registered workspace directories.`)}const invoke=__name(()=>{this.assertAdmissionOpen();return sessionIdContext.run(sessionId,()=>{const invocation=fileInvocation??tool.build(params);invocationStarted=true;if(entry.version===3&&entry.captureSink){return invocation.execute(entry.controller.signal,void 0,void 0,void 0,void 0,void 0,entry.captureSink)}if(entry.toolName===ShellTool.Name&&this.options.ledger){const ledger=this.options.ledger;return invocation.execute(entry.controller.signal,void 0,void 0,pid=>{shellPgid=pid;try{ledger.addGroup({pgid:pid,callId:entry.reference.callId,startedAt:Date.now()})}catch(error){signalProcessGroup(pid,"SIGKILL");void ledger.waitForGroupExit(pid,CLOSE_SWEEP_TIMEOUT_MS);throw error}})}return invocation.execute(entry.controller.signal)})},"invoke");const registeredHistory=this.fileHistories.get(entry.reference.sessionId);const history2=tools.fileHistory??registeredHistory;const mutating=[WriteFileTool.Name,EditTool.Name].includes(entry.toolName);if(history2&&(history2.directory!==tools.directory||tools.fileHistory&&history2.ownerSessionId!==entry.reference.sessionId||registeredHistory&®isteredHistory!==history2)||mutating&&tools.retainedFileHistory&&!tools.fileHistory)throw new ManagedToolConflictError("File history binding conflicts.");let result;if(history2&&mutating){let outcome;let invoked=false;try{const file=path2.relative(history2.directory,params["file_path"]).split(path2.sep).join("/");outcome=await history2.execute(file,async()=>{invoked=true;try{return{result:await invoke()}}catch(error){return{error}}})}catch(error){if(!invoked)throw error;entry.state="unknown";entry.lastSequence++;return}if("error"in outcome)throw outcome.error;result=outcome.result}else{result=await invoke()}if(entry.toolName===GlobTool.Name){const root=tools.directory;if(root===void 0)throw new ManagedToolUnavailableError("Managed context directory is unavailable.");const resultPaths=result.collectedFilePaths??result.resultFilePaths;if(Array.isArray(resultPaths)){const realRoot=await realpathDeepestExisting(root);for(const hit of resultPaths){if(typeof hit!=="string")continue;const effective=path2.join(await realpathDeepestExisting(path2.dirname(hit)),path2.basename(hit));const relative=path2.relative(realRoot,effective);if(escapesSession(relative)||await this.ownsAnotherSessionDir?.(tools.sessionId,effective,realRoot)){throw new Error("Glob results must stay within the Session working directory.")}}}result=relativizeGlobResult(result,root)}payload=toPayload(result,_ManagedToolExecutor.isCancelRequested(entry))}catch(error){const message=error instanceof Error?error.message:String(error);payload={executionStatus:!invocationStarted&&this.isAdmissionSealed&&error instanceof ManagedToolUnavailableError?"not_started":_ManagedToolExecutor.isCancelRequested(entry)?"cancelled":"error",responseParts:[],error:{message:entry.toolName===GlobTool.Name&&tools.directory!==void 0?relativizeGlobText(message,tools.directory):message}}}if(entry.version===2&&shellPgid!==void 0&&entry.controller.signal.aborted&&this.options.ledger){let state="denied";try{state=await this.options.ledger.waitForGroupExit(shellPgid,this.options.groupEvidenceTimeoutMs??GROUP_EXIT_EVIDENCE_TIMEOUT_MS)}catch(error){debugLogger.warn(`Managed Runtime group-exit evidence failed: ${error instanceof Error?error.message:String(error)}`)}if(state!=="gone"){entry.state="unknown";entry.lastSequence++;return}}if(entry.version===3){try{entry.v3Result=await entry.captureSink.finalize(payload.executionStatus,payload.responseParts,payload.error);if(Buffer.byteLength(JSON.stringify({protocolVersion:3,toolResult:MANAGED_TOOL_RESULT_PROTOCOL,state:"settled",lastSequence:entry.lastSequence+1,result:entry.v3Result}))>MANAGED_RUNTIME_TOOL_RESULT_BODY_LIMIT_BYTES){entry.v3Result={...entry.v3Result,responseParts:[],error:{message:"Managed Runtime tool preview exceeds 1 MiB."}}}if(entry.v3Result.capture){if(entry.capturePublisher.finish){await entry.capturePublisher.finish(entry.captureSink.identity,entry.v3Result)}else if(entry.capturePublisher.accept){const receipt2=await entry.capturePublisher.accept(entry.captureSink.identity,entry.v3Result);entry.v3Result={...entry.v3Result,capture:{...entry.v3Result.capture,deliveryStatus:receipt2.deliveryStatus}};entry.acknowledgement={executionCallId:receipt2.executionCallId,manifest:receipt2.manifest,deliveryStatus:receipt2.deliveryStatus,historyRevision:receipt2.historyRevision}}}}catch{entry.state="unknown";entry.lastSequence++;return}entry.state="settled";entry.lastSequence++;return}entry.result=payload;entry.state="settled";entry.lastSequence+=1;if(Buffer.byteLength(JSON.stringify({protocolVersion:2,...view(entry)}))>MANAGED_RUNTIME_TOOL_RESULT_BODY_LIMIT_BYTES){entry.result={executionStatus:payload.executionStatus==="cancelled"?"cancelled":"error",responseParts:[],error:{message:"Managed Runtime tool result exceeds 1 MiB."}}}}};function backgroundEnv(sessionId){const env={...sessionIdContext.run(sessionId,getShellContextEnvVars)};for(const key of["PATH","HOME","LANG","LC_ALL","TMPDIR","USER","SHELL"]){const value=process.env[key];if(value!==void 0)env[key]=value}return env}__name(backgroundEnv,"backgroundEnv");function mcpView(view2){return{state:view2.state==="running"?"executing":view2.state==="outcome_unknown"?"unknown":"settled",lastSequence:view2.state==="running"?1:2,...view2.state==="settled"?{result:mcpPayload(view2)}:{}}}__name(mcpView,"mcpView");function mcpPayload(view2){const response=view2.response;return{executionStatus:view2.error?["managed_mcp_remote_error","managed_mcp_output_limit"].includes(view2.error.code)?"error":"not_started":response?.["isError"]===true?"error":"success",responseParts:response?[{text:JSON.stringify(response)}]:[],...view2.error?{error:{type:view2.error.code,message:view2.error.code}}:{}}}__name(mcpPayload,"mcpPayload");function v3View(entry){return{state:entry.state,lastSequence:entry.lastSequence,...entry.state==="settled"?{result:entry.v3Result}:{}}}__name(v3View,"v3View");function createManagedToolSet(directory,sessionId,workspaceRoot=directory){const config=new Config({sessionId,targetDir:directory,cwd:directory,includeDirectories:[workspaceRoot],model:"managed-runtime-worker",debugMode:false,usageStatisticsEnabled:false,approvalMode:"yolo",fileCheckpointingEnabled:false,fileReadCacheDisabled:true});registerSessionProjectDir(sessionId,config.storage.getProjectDir());return{sessionId,directory,workspaceRoot,admitsDirectory:__name(candidate=>config.getWorkspaceContext().isPathWithinWorkspace(candidate),"admitsDirectory"),tools:new Map([new ReadFileTool(config),new WriteFileTool(config),new EditTool(config),new GlobTool(config,{containmentRoot:directory,executionTimeoutMs:5e3}),new ShellTool(config)].map(tool=>[tool.name,tool]))}}__name(createManagedToolSet,"createManagedToolSet");async function join2(entry,reference2,toolName,inputJson){if(!sameInvocation(entry,reference2,toolName,inputJson)){throw new ManagedToolConflictError("Managed Runtime invocation identity conflicts.")}await entry.promise;if(entry.state==="unknown")throw new ManagedMcpToolUnknownError("Managed Runtime tool outcome is unknown.");return entry.result}__name(join2,"join");function view(entry){return{state:entry.state,lastSequence:entry.lastSequence,...entry.state==="settled"?{result:entry.result}:{}}}__name(view,"view");function sameReference(left,right){return left.sessionId===right.sessionId&&left.promptId===right.promptId&&left.callId===right.callId&&left.argsDigest===right.argsDigest}__name(sameReference,"sameReference");function sameCapture(left,right){return left?.tenantId===right.tenantId&&left.sessionId===right.sessionId&&left.turnId===right.turnId&&left.executionCallId===right.executionCallId&&left.bindingGeneration===right.bindingGeneration&&left.capturePolicy===right.capturePolicy}__name(sameCapture,"sameCapture");function sameInvocation(entry,reference2,toolName,inputJson){return entry.inputJson!==void 0&&sameReference(entry.reference,reference2)&&entry.toolName===toolName&&entry.inputJson===inputJson}__name(sameInvocation,"sameInvocation");function relativizeGlobText(text2,directory){const root=path2.resolve(directory);if(root===path2.sep)return text2;const prefix=root.endsWith(path2.sep)?root:root+path2.sep;const escape=__name(value=>value.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"escape");const tokenPrefix=new RegExp(`(?<![\\w./\\\\-])${escape(prefix)}`,"g");const bareRoot=new RegExp(`(?<![\\w./\\-])${escape(root)}(?![/\\w.-])`,"g");return text2.replace(tokenPrefix,"").replace(bareRoot,".")}__name(relativizeGlobText,"relativizeGlobText");function relativizeGlobResult(result,directory){const next={...result};if(typeof next.llmContent==="string"){next.llmContent=relativizeGlobText(next.llmContent,directory)}if(typeof next.error?.message==="string"){next.error={...next.error,message:relativizeGlobText(next.error.message,directory)}}return next}__name(relativizeGlobResult,"relativizeGlobResult");function escapesSession(relative){return relative===".."||relative.startsWith(`..${path2.sep}`)||path2.isAbsolute(relative)}__name(escapesSession,"escapesSession");async function realpathDeepestExisting(candidate){let resolved=candidate;const tail=[];try{for(;;){try{return path2.join(await realpath(resolved),...tail)}catch(error){if(error?.code!=="ENOENT")throw error}try{if((await lstat2(resolved)).isSymbolicLink()){resolved=path2.resolve(await realpath(path2.dirname(resolved)),await readlink(resolved));continue}}catch(error){if(error?.code!=="ENOENT")throw error}const parent=path2.dirname(resolved);if(parent===resolved)return path2.join(resolved,...tail);tail.unshift(path2.basename(resolved));resolved=parent}}catch(error){const code=error?.code;throw new Error(`Path could not be resolved (${code??"unknown error"}).`)}}__name(realpathDeepestExisting,"realpathDeepestExisting");function toPayload(result,cancelRequested){const content=result.llmContent;const responseParts=typeof content==="string"?[{type:"text",text:content}]:Array.isArray(content)?content:[];const toolError=result.error;if(cancelRequested){return{executionStatus:"cancelled",responseParts,...toolError?{error:{message:toolError.message,...toolError.type?{type:toolError.type}:{}}}:{}}}if(toolError){return{executionStatus:"error",responseParts,error:{message:toolError.message,...toolError.type?{type:toolError.type}:{}}}}return{executionStatus:"success",responseParts}}__name(toPayload,"toPayload");init_esbuild_shims();import{createHash as createHash4,randomUUID as randomUUID2}from"node:crypto";import{isDeepStrictEqual as isDeepStrictEqual3}from"node:util";var PUBLICATION_INSTALL_ROUTE=Object.freeze({key:"publication-install",method:"POST",path:"/internal/managed-runtime/v3/publications:install",protocolVersion:3,requestBodyLimitBytes:64*1024,responseBodyLimitBytes:16*1024,cacheControl:"no-store"});var PublicationRejection=class extends Error{constructor(status,code){super("Publication service rejected HTTP "+status+".");this.status=status;this.code=code}static{__name(this,"PublicationRejection")}};function refusal(error){if(!(error instanceof PublicationRejection))return null;return error.code==="managed_tool_result_invalid"||error.code==="managed_tool_result_conflict"||error.code==="managed_tool_result_digest_mismatch"?error.code:null}__name(refusal,"refusal");function record(value){if(!value||typeof value!=="object"||Array.isArray(value))throw new Error("Publication record is invalid.");return value}__name(record,"record");function same(left,right){return isDeepStrictEqual3(left,right)}__name(same,"same");function endpoint(value){const url=new URL(value);if(url.username||url.password||url.search||url.hash||url.pathname!=="/"||url.protocol!=="https:"&&!(url.protocol==="http:"&&["127.0.0.1","[::1]","localhost"].includes(url.hostname)))throw new Error("Publication service URL is invalid.");return url}__name(endpoint,"endpoint");async function boundedJson(response){let body2;try{const reader=response.body?.getReader();if(!reader)throw new Error("Publication service returned no response.");const chunks=[];let length=0;try{while(true){const item=await reader.read();if(item.done)break;length+=item.value.byteLength;if(length>1024*1024)throw new Error("Publication response is too large.");chunks.push(item.value)}}finally{reader.releaseLock()}body2=record(JSON.parse(Buffer.concat(chunks).toString("utf8")))}catch(failure2){if(!response.ok)throw new PublicationRejection(response.status,"unknown");throw failure2}if(!response.ok){const failure2=body2["error"];const code=failure2&&typeof failure2==="object"&&!Array.isArray(failure2)?String(failure2["code"]??"unknown"):"unknown";if(code==="managed_tool_publication_quota_exhausted")throw new Error("quota_exhausted");throw new PublicationRejection(response.status,code)}return body2}__name(boundedJson,"boundedJson");var PublicationClient=class{constructor(installed){this.installed=installed;this.base=endpoint(installed.serviceBaseUrl);this.key=record(installed.binding["sessionKey"])}static{__name(this,"PublicationClient")}base;key;tail=Promise.resolve();url(suffix){const sessionId=encodeURIComponent(String(this.key["sessionId"]));const publicationId=encodeURIComponent(this.installed.publicationId);const url=new URL(`/internal/managed-tool-publications/v1/sessions/${sessionId}/publications/${publicationId}${suffix}`,this.base);url.searchParams.set("workspaceId",String(this.key["workspaceId"]));return url}async request(suffix,operationId,body2,headers={}){const response=await fetch(this.url(suffix),{method:body2?"POST":"GET",headers:{"X-Qwen-Tenant-Id":String(this.key["tenantId"]),"X-Qwen-Tool-Publication-Token":this.installed.publicationToken,"X-Qwen-Tool-Publication-Operation":operationId,"X-Qwen-Tool-Publication-Async":"1","Cache-Control":"no-store",...headers},...body2?{body:body2}:{},redirect:"error",signal:AbortSignal.timeout(3e4)});return boundedJson(response)}async operation(suffix,operationId,body2,headers){const previous=this.tail;let release;this.tail=new Promise(resolve=>{release=resolve});await previous;try{return await this.performOperation(suffix,operationId,body2,headers)}finally{release()}}async performOperation(suffix,operationId,body2,headers){const deadline=Date.now()+30*6e4;let recoveries=0;const statusPath=`/operations/${encodeURIComponent(operationId)}`;const resumableRefusal=__name(failure2=>failure2.status===409&&["managed_tool_publication_operation_expired","managed_tool_publication_claim_expired","managed_tool_publication_claim_lost","managed_tool_publication_busy"].includes(failure2.code),"resumableRefusal");const retryable=__name(failure2=>failure2 instanceof PublicationRejection?failure2.status===429||failure2.status>=500||failure2.status===409&&failure2.code==="managed_tool_publication_busy":failure2 instanceof TypeError||failure2 instanceof DOMException&&["AbortError","TimeoutError"].includes(failure2.name),"retryable");const observe=__name(async()=>{while(Date.now()<deadline){try{return await this.request(statusPath,operationId)}catch(failure2){if(failure2 instanceof PublicationRejection&&failure2.code==="managed_tool_publication_operation_unknown")return null;if(!retryable(failure2))throw failure2;await new Promise(resolve=>setTimeout(resolve,250))}}throw new Error("Publication operation exceeded its observation deadline.")},"observe");while(Date.now()<deadline){let initial;try{initial=await this.request(suffix,operationId,body2,headers)}catch(failure2){if(failure2 instanceof Error&&failure2.message==="quota_exhausted")throw failure2;if(failure2 instanceof PublicationRejection&&failure2.code==="managed_tool_publication_storage_denied")throw failure2;const status2=await observe();if(status2!==null){if(failure2 instanceof PublicationRejection&&failure2.status>=400&&failure2.status<500&&failure2.status!==429&&!resumableRefusal(failure2)&&status2["state"]!=="SUCCEEDED")throw failure2;initial=status2}else{if(!retryable(failure2))throw failure2;await new Promise(resolve=>setTimeout(resolve,250));continue}}if(initial["state"]===void 0)return initial;let status=initial;while(Date.now()<deadline){if(status["state"]==="SUCCEEDED")return record(status["receipt"]);if(status["state"]==="FAILED"){const error=record(status["error"]);if(!Number.isInteger(error["status"])||Number(error["status"])<400||Number(error["status"])>599||typeof error["code"]!=="string"||!error["code"])throw new Error("Invalid publication failure response.");if(error["code"]==="managed_tool_publication_quota_exhausted")throw new Error("quota_exhausted");throw new PublicationRejection(Number(error["status"]),error["code"])}if(status["state"]==="RETRYABLE")break;if(status["state"]==="EXPIRED"&&recoveries<3){recoveries++;try{status=await this.request(`${statusPath}/recover`,operationId,Buffer.from("{}"))}catch(failure2){if(!retryable(failure2))throw failure2;if(failure2 instanceof PublicationRejection&&[409,429].includes(failure2.status)&&failure2.code==="managed_tool_publication_busy")recoveries--;await new Promise(resolve=>setTimeout(resolve,250));status=await observe()??status}continue}if(status["state"]!=="PENDING")throw new Error(`Publication operation ended as ${String(status["state"])}.`);await new Promise(resolve=>setTimeout(resolve,250));const current=await observe();if(current===null)throw new Error("Publication operation disappeared during observation.");status=current}await new Promise(resolve=>setTimeout(resolve,250))}throw new Error("Publication operation exceeded its observation deadline.")}};var RemoteShellResultPublisher=class{static{__name(this,"RemoteShellResultPublisher")}grants=new Map;clients=new Map;get hasInstalledPublication(){return this.grants.size>0}hasExecution(executionCallId){return this.grants.has(executionCallId)}install(value,boot){const body2=record(value);if(!same(Object.keys(body2).sort(),["binding","protocolVersion","publication","publicationId","publicationToken","serviceBaseUrl"])||body2["protocolVersion"]!==3||body2["publication"]!=="managed-tool-publication/1"||typeof body2["publicationId"]!=="string"||!/^[a-z0-9_-]{1,128}$/u.test(body2["publicationId"])||typeof body2["publicationToken"]!=="string"||!/^[A-Za-z0-9_-]{43}$/u.test(body2["publicationToken"])||typeof body2["serviceBaseUrl"]!=="string")throw new Error("Publication installation is invalid.");endpoint(body2["serviceBaseUrl"]);const binding=parseToolPublicationBinding(body2["binding"]);const key=record(binding["sessionKey"]);const reference2=record(binding["reference"]);if(binding["publicationId"]!==body2["publicationId"]||binding["publication"]!=="managed-tool-publication/1"||key["tenantId"]!==boot.tenantId||key["workspaceId"]!==boot.workspaceId||reference2["sessionId"]!==void 0&&typeof reference2["sessionId"]!=="string"||binding["captureScope"]!=="process_pipes"||binding["capturePolicy"]!=="complete_required"||binding["revision"]!==1||typeof binding["executionCallId"]!=="string"||typeof binding["captureId"]!=="string")throw new Error("Publication binding conflicts with this worker.");const grant={...body2,binding};const prior=this.grants.get(binding["executionCallId"]);if(prior&&!same(prior,grant))throw new Error("Original publication installation conflicts.");this.grants.set(binding["executionCallId"],grant);if(!prior)this.clients.set(binding["executionCallId"],new PublicationClient(grant))}prepare(request){const grant=this.grants.get(request.capture.executionCallId);if(!grant)throw new Error("Original publication grant is missing.");const binding=grant.binding;const key=record(binding["sessionKey"]);const reference2=record(binding["reference"]);if(request.reference.sessionId!==reference2["sessionId"]||request.reference.promptId!==reference2["promptId"]||request.reference.callId!==reference2["callId"]||request.reference.argsDigest!==reference2["argsDigest"]||request.capture.tenantId!==key["tenantId"]||request.capture.sessionId!==key["sessionId"]||request.capture.turnId!==binding["turnId"]||request.capture.bindingGeneration!==binding["bindingGeneration"]||request.capture.capturePolicy!=="complete_required")throw new Error("Shell invocation conflicts with its publication grant.");const identity={tenantId:request.capture.tenantId,sessionId:request.capture.sessionId,turnId:request.capture.turnId,executionCallId:request.capture.executionCallId,callId:request.reference.callId,invocationDigest:request.reference.argsDigest,bindingGeneration:request.capture.bindingGeneration,captureId:String(binding["captureId"]),revision:1};const client=this.clients.get(request.capture.executionCallId);if(!client)throw new Error("Original publication client is missing.");const store={publish:__name(async raw=>{let item;try{item=parseToolResultPublishRequest(raw)}catch(cause){if(cause instanceof ManagedSessionRecordError)return{status:"refused",code:"managed_tool_result_invalid"};throw cause}if(item.captureId!==identity.captureId)return{status:"refused",code:"managed_tool_result_conflict"};if(!["stdout","stderr"].includes(item.streamId))return{status:"refused",code:"managed_tool_result_invalid"};const stream=item.streamId;const ordinal=item.ordinal;const bytes=Buffer.from(item.bytes);const digest2=createHash4("sha256").update(bytes).digest("hex");if(item.expectedDigest&&item.expectedDigest!==digest2)return{status:"refused",code:"managed_tool_result_digest_mismatch"};let receipt2;try{receipt2=await client.operation(`/segments/${stream}/${ordinal}`,`seg-${stream}-${ordinal}`,bytes,{"X-Qwen-Tool-Segment-Digest":digest2})}catch(cause){const code=refusal(cause);if(code)return{status:"refused",code};throw cause}if(receipt2["ordinal"]!==ordinal||receipt2["byteLength"]!==bytes.length||receipt2["digest"]!==digest2||receipt2["captureId"]!==identity.captureId||receipt2["streamId"]!==stream)throw new Error("Original segment receipt conflicts.");return{status:"ok",result:{ordinal,byteLength:bytes.length,digest:digest2}}},"publish"),seal:__name(async raw=>{let item;try{item=parseToolResultSealRequest(raw)}catch(cause){if(cause instanceof ManagedSessionRecordError)return{status:"refused",code:"managed_tool_result_invalid"};throw cause}if(item.captureId!==identity.captureId)return{status:"refused",code:"managed_tool_result_conflict"};if(!["stdout","stderr"].includes(item.streamId))return{status:"refused",code:"managed_tool_result_invalid"};const stream=item.streamId;const body2=Buffer.from(JSON.stringify({segmentCount:item["segmentCount"],byteLength:item["byteLength"],digest:item["digest"]}));let receipt2;try{receipt2=await client.operation(`/streams/${stream}/seal`,"seal-"+stream+"-"+createHash4("sha256").update(body2).digest("hex").slice(0,32),body2,{"Content-Type":"application/json"})}catch(cause){const code=refusal(cause);if(code)return{status:"refused",code};throw cause}if(receipt2["segmentCount"]!==item["segmentCount"]||receipt2["byteLength"]!==item["byteLength"]||receipt2["digest"]!==item["digest"])throw new Error("Original seal receipt conflicts.");return{status:"ok",result:{segmentCount:item.segmentCount,byteLength:item.byteLength,digest:item.digest}}},"seal"),prefix:__name(async raw=>{let item;try{item=parseToolResultPrefixRequest(raw)}catch(cause){if(cause instanceof ManagedSessionRecordError)return{status:"refused",code:"managed_tool_result_invalid"};throw cause}if(item.captureId!==identity.captureId)return{status:"refused",code:"managed_tool_result_conflict"};if(!["stdout","stderr"].includes(item.streamId))return{status:"ok",result:{segmentCount:0,byteLength:0,digest:createHash4("sha256").digest("hex"),sealed:false}};let receipt2;try{receipt2=await client.operation(`/streams/${item.streamId}/prefix`,"prefix-"+item.streamId+"-"+randomUUID2(),Buffer.alloc(0))}catch(cause){const code=refusal(cause);if(code)return{status:"refused",code};throw cause}if(!Number.isSafeInteger(receipt2["segmentCount"])||!Number.isSafeInteger(receipt2["byteLength"])||typeof receipt2["digest"]!=="string"||typeof receipt2["sealed"]!=="boolean")throw new Error("Original prefix receipt is invalid.");return{status:"ok",result:{segmentCount:receipt2["segmentCount"],byteLength:receipt2["byteLength"],digest:receipt2["digest"],sealed:receipt2["sealed"]}}},"prefix"),readRange:__name(async()=>{throw new Error("Worker range lookup is unavailable.")},"readRange"),close:__name(async()=>{},"close")};const resources2={publish:__name(async(kind,bytes)=>{const metadata=record(JSON.parse(bytes.toString("utf8")));const slot=kind==="managed-tool-result-manifest"?"manifest:1":`page:${String(metadata["streamId"])}:${String(metadata["firstOrdinal"])}`;const published=await client.operation(`/resources/${kind}/${encodeURIComponent(slot)}`,`res-${slot.replaceAll(":","-")}`,bytes);const ref2=assertManagedSessionDurableRef(published,"published result resource");if(ref2.kind!==kind||ref2.byteLength!==bytes.length||ref2.digest!==createHash4("sha256").update(bytes).digest("hex"))throw new Error("Original resource receipt conflicts.");return ref2},"publish"),read:__name(async()=>{throw new Error("Worker resource reads are unavailable.")},"read")};return Promise.resolve({identity,sink:new LocalShellResultCapture(store,resources2,identity)})}async finish(identity,envelope){const grant=this.grants.get(identity.executionCallId);if(!grant||grant.binding["captureId"]!==identity.captureId)throw new Error("Original publication grant changed.");const bytes=Buffer.from(JSON.stringify(envelope));const client=this.clients.get(identity.executionCallId);if(!client)throw new Error("Original publication client is missing.");const receipt2=await client.operation("/finish","finish",bytes,{"Content-Type":"application/json"});const terminal=record(receipt2["terminal"]);if(receipt2["producerPhase"]!=="FINISHED"||terminal["byteLength"]!==bytes.length||terminal["digest"]!==createHash4("sha256").update(bytes).digest("hex"))throw new Error("Publication finish was not confirmed.")}registerInstallRoute(app,boot,admissionOpen=()=>true){app.post(PUBLICATION_INSTALL_ROUTE.path,managedRuntimeNoStore,authorizeManagedRuntime(boot),managedRuntimeJsonBody(PUBLICATION_INSTALL_ROUTE.requestBodyLimitBytes),(req,res)=>{try{if(!admissionOpen())throw new Error("Publication admission is sealed.");this.install(req.body,boot);res.json({protocolVersion:3,publication:"managed-tool-publication/1",installed:true})}catch{res.status(409).json({code:"managed_tool_publication_conflict",error:"Publication installation conflicts."})}},handleManagedRuntimeJsonError)}};init_esbuild_shims();var REFERENCE_KEYS=Object.freeze(["argsDigest","callId","promptId","sessionId"]);var INVALID_MESSAGE="Managed Runtime tool request is invalid.";function isNonEmptyString2(value){return typeof value==="string"&&value.length>0}__name(isNonEmptyString2,"isNonEmptyString");function parseReference(value){if(!value||typeof value!=="object"||Array.isArray(value)){return null}const keys=Object.keys(value).sort();if(keys.length!==REFERENCE_KEYS.length||!keys.every((key,index)=>key===REFERENCE_KEYS[index])){return null}const reference2=value;if(!isNonEmptyString2(reference2["sessionId"])||!isNonEmptyString2(reference2["promptId"])||!isNonEmptyString2(reference2["callId"])||!isNonEmptyString2(reference2["argsDigest"])){return null}return reference2}__name(parseReference,"parseReference");function parseClosedBody(value,requiredKeys,optionalKeys=[]){if(!value||typeof value!=="object"||Array.isArray(value)){return null}const body2=value;if(body2["protocolVersion"]!==2){return null}const allowed=new Set([...requiredKeys,...optionalKeys]);if(Object.keys(body2).some(key=>!allowed.has(key))){return null}if(requiredKeys.some(key=>!(key in body2))){return null}return body2}__name(parseClosedBody,"parseClosedBody");function invalid(res){res.status(400).json({code:"managed_runtime_attestation_invalid",error:INVALID_MESSAGE})}__name(invalid,"invalid");function registerManagedRuntimeToolRoutes(app,identity,executor){const routes=new Map(OWNED_MANAGED_RUNTIME_ROUTES.filter(route=>route.key!=="attest").map(route=>[route.key,route]));app.post(routes.get("execute").path,managedRuntimeNoStore,authorizeManagedRuntime(identity),nameManagedRuntimeIncarnation(identity),managedRuntimeJsonBody(routes.get("execute").requestBodyLimitBytes),async(req,res)=>{const body2=parseClosedBody(req.body,["protocolVersion","reference","toolName","input"]);const reference2=body2&&parseReference(body2["reference"]);const toolName=body2?.["toolName"];const input=body2?.["input"];if(!body2||!reference2||!isNonEmptyString2(toolName)||!input||typeof input!=="object"||Array.isArray(input)){invalid(res);return}if(!executor.hasTool(toolName)){res.status(409).json({code:"managed_runtime_identity_conflict",error:"Managed Runtime does not admit this tool."});return}try{const result=await executor.execute(reference2,toolName,input);res.status(200).json({protocolVersion:2,state:"settled",result})}catch(error){if(error instanceof ManagedMcpError){res.status(400).json({code:error.code});return}if(error instanceof ManagedMcpToolUnknownError){res.status(200).json({protocolVersion:2,state:"unknown"});return}if(error instanceof ManagedToolInvalidError){invalid(res);return}if(error instanceof ManagedToolConflictError||error instanceof ManagedToolUnavailableError){res.status(409).json({code:error.code,error:error.message});return}throw error}},handleManagedRuntimeJsonError);app.post(routes.get("status").path,managedRuntimeNoStore,authorizeManagedRuntime(identity),nameManagedRuntimeIncarnation(identity),managedRuntimeJsonBody(routes.get("status").requestBodyLimitBytes),(req,res)=>{const body2=parseClosedBody(req.body,["protocolVersion","reference"],["afterSequence"]);const reference2=body2&&parseReference(body2["reference"]);const afterSequence=body2?.["afterSequence"];if(!body2||!reference2||afterSequence!==void 0&&(typeof afterSequence!=="number"||!Number.isSafeInteger(afterSequence)||afterSequence<0)){invalid(res);return}try{const view2=executor.status(reference2);if(!view2){res.status(200).json({protocolVersion:2,state:"unknown"});return}res.status(200).json({protocolVersion:2,state:view2.state,...view2.state==="settled"?{result:view2.result}:{},lastSequence:view2.lastSequence})}catch(error){if(error instanceof ManagedToolConflictError){res.status(409).json({code:error.code,error:error.message});return}throw error}},handleManagedRuntimeJsonError);app.post(routes.get("cancel").path,managedRuntimeNoStore,authorizeManagedRuntime(identity),nameManagedRuntimeIncarnation(identity),managedRuntimeJsonBody(routes.get("cancel").requestBodyLimitBytes),(req,res)=>{const body2=parseClosedBody(req.body,["protocolVersion","reference"]);const reference2=body2&&parseReference(body2["reference"]);if(!body2||!reference2){invalid(res);return}try{const view2=executor.cancel(reference2);if(!view2){res.status(200).json({protocolVersion:2,state:"unknown"});return}res.status(200).json({protocolVersion:2,state:view2.state,...view2.state==="settled"?{result:view2.result}:{}})}catch(error){if(error instanceof ManagedToolConflictError){res.status(409).json({code:error.code,error:error.message});return}throw error}},handleManagedRuntimeJsonError);app.post(routes.get("acknowledge").path,managedRuntimeNoStore,authorizeManagedRuntime(identity),nameManagedRuntimeIncarnation(identity),managedRuntimeJsonBody(routes.get("acknowledge").requestBodyLimitBytes),(req,res)=>{const body2=parseClosedBody(req.body,["protocolVersion","reference"]);const reference2=body2&&parseReference(body2["reference"]);if(!body2||!reference2){invalid(res);return}try{const view2=executor.acknowledge(reference2);if(!view2){res.status(200).json({protocolVersion:2,state:"unknown"});return}res.status(200).json({protocolVersion:2,state:view2.state})}catch(error){if(error instanceof ManagedToolConflictError){res.status(409).json({code:error.code,error:error.message});return}throw error}},handleManagedRuntimeJsonError)}__name(registerManagedRuntimeToolRoutes,"registerManagedRuntimeToolRoutes");init_esbuild_shims();function closed3(value,keys,optional=[]){if(!value||typeof value!=="object"||Array.isArray(value))return null;const body2=value;if(Object.keys(body2).some(key=>!keys.includes(key)))return null;if(keys.some(key=>!optional.includes(key)&&!(key in body2)))return null;return body2}__name(closed3,"closed");function reference(value){const body2=closed3(value,["sessionId","promptId","callId","argsDigest"]);if(!body2||typeof body2["argsDigest"]!=="string"||!/^(?:sha256:)?[0-9a-f]{64}$/.test(body2["argsDigest"]))return null;try{for(const key of["sessionId","promptId","callId"]){assertManagedSessionStableId(body2[key],`reference.${key}`)}}catch{return null}return body2}__name(reference,"reference");function body(value,keys,optional=[]){const parsed=closed3(value,["protocolVersion","toolResult",...keys],optional);return parsed?.["protocolVersion"]===3&&parsed["toolResult"]===MANAGED_TOOL_RESULT_PROTOCOL?parsed:null}__name(body,"body");function capture(value){const parsed=closed3(value,["tenantId","sessionId","turnId","executionCallId","bindingGeneration","capturePolicy"]);if(!parsed||parsed["capturePolicy"]!=="complete_required"||typeof parsed["bindingGeneration"]!=="string"||!/^[1-9][0-9]{0,18}$/.test(parsed["bindingGeneration"])||BigInt(parsed["bindingGeneration"])>2n**63n-1n)return null;try{for(const key of["tenantId","sessionId","turnId","executionCallId"]){assertManagedSessionStableId(parsed[key],`capture.${key}`)}}catch{return null}return parsed}__name(capture,"capture");function receipt(value){const parsed=closed3(value,["executionCallId","manifest","deliveryStatus","historyRevision"]);if(!parsed)return null;try{assertManagedSessionStableId(parsed["executionCallId"],"receipt.executionCallId")}catch{return null}const deliveryStatus=parsed["deliveryStatus"];if(deliveryStatus!=="committed"&&deliveryStatus!=="blocked")return null;let manifest=null;try{if(parsed["manifest"]!==null){manifest=assertManagedSessionDurableRef(parsed["manifest"],"receipt.manifest");if(manifest.kind!==MANAGED_TOOL_RESULT_KINDS.manifest||manifest.byteLength<1||manifest.byteLength>MANAGED_TOOL_RESULT_LIMITS.maxManifestBytes)return null}}catch{return null}const historyRevision=parsed["historyRevision"];if(deliveryStatus==="committed"?!Number.isSafeInteger(historyRevision)||historyRevision<1:historyRevision!==null)return null;return{executionCallId:parsed["executionCallId"],manifest,deliveryStatus,historyRevision}}__name(receipt,"receipt");function invalid2(res){res.status(400).json({code:"managed_runtime_attestation_invalid",error:"Managed Tool v3 request is invalid."})}__name(invalid2,"invalid");function failure(res,cause){if(cause instanceof ManagedToolInvalidError)return invalid2(res);if(cause instanceof ManagedToolConflictError||cause instanceof ManagedToolUnavailableError){res.status(409).json({code:cause.code,error:cause.message});return}throw cause}__name(failure,"failure");function registerManagedRuntimeToolV3Routes(app,identity,executor){const routes=Object.fromEntries(MANAGED_TOOL_RESULT_ROUTES.map(route=>[route.key,route]));const prefix={protocolVersion:3,toolResult:MANAGED_TOOL_RESULT_PROTOCOL};app.post(routes["execute"].path,managedRuntimeNoStore,authorizeManagedRuntime(identity),managedRuntimeJsonBody(routes["execute"].requestBodyLimitBytes),async(req,res)=>{const parsed=body(req.body,["reference","toolName","input","capture"]);const ref2=reference(parsed?.["reference"]);const cap=capture(parsed?.["capture"]);const input=parsed?.["input"];if(!parsed||!ref2||!cap||parsed["toolName"]!=="run_shell_command"&&parsed["toolName"]!=="monitor"||!input||typeof input!=="object"||Array.isArray(input))return invalid2(res);try{const view2=await executor.executeV3({reference:ref2,capture:cap,toolName:parsed["toolName"],input});res.status(200).json({...prefix,state:view2.state,...view2.result?{result:view2.result}:{}})}catch(cause){failure(res,cause)}},handleManagedRuntimeJsonError);app.post(routes["status"].path,managedRuntimeNoStore,authorizeManagedRuntime(identity),managedRuntimeJsonBody(routes["status"].requestBodyLimitBytes),(req,res)=>{const parsed=body(req.body,["reference","afterSequence"],["afterSequence"]);const ref2=reference(parsed?.["reference"]);const after=parsed?.["afterSequence"];if(!parsed||!ref2||after!==void 0&&(!Number.isSafeInteger(after)||after<0))return invalid2(res);try{const view2=executor.statusV3(ref2);res.status(200).json({...prefix,state:view2.state,...view2.result?{result:view2.result}:{},...view2.lastSequence!==void 0?{lastSequence:view2.lastSequence}:{}})}catch(cause){failure(res,cause)}},handleManagedRuntimeJsonError);app.post(routes["cancel"].path,managedRuntimeNoStore,authorizeManagedRuntime(identity),managedRuntimeJsonBody(routes["cancel"].requestBodyLimitBytes),(req,res)=>{const parsed=body(req.body,["reference"]);const ref2=reference(parsed?.["reference"]);if(!parsed||!ref2)return invalid2(res);try{const view2=executor.cancelV3(ref2);res.status(200).json({...prefix,state:view2.state,...view2.result?{result:view2.result}:{}})}catch(cause){failure(res,cause)}},handleManagedRuntimeJsonError);app.post(routes["acknowledge"].path,managedRuntimeNoStore,authorizeManagedRuntime(identity),managedRuntimeJsonBody(routes["acknowledge"].requestBodyLimitBytes),(req,res)=>{const parsed=body(req.body,["reference","receipt"]);const ref2=reference(parsed?.["reference"]);const ack=receipt(parsed?.["receipt"]);if(!parsed||!ref2||!ack)return invalid2(res);try{const view2=executor.acknowledgeV3(ref2,ack);res.status(200).json({...prefix,state:view2.state,...view2.result?{result:view2.result}:{}})}catch(cause){failure(res,cause)}},handleManagedRuntimeJsonError)}__name(registerManagedRuntimeToolV3Routes,"registerManagedRuntimeToolV3Routes");init_esbuild_shims();import{randomUUID as randomUUID4}from"node:crypto";import fs2 from"node:fs";import path3 from"node:path";init_esbuild_shims();import{randomUUID as randomUUID3}from"node:crypto";function invocationParams(params){const projected=JSON.parse(JSON.stringify(params));managedToolDigest(projected);return projected}__name(invocationParams,"invocationParams");function refuseUpdatedInput(result){const{updatedInput,...rest}=result;if(updatedInput===void 0||!rest.shouldProceed&&rest.blockType!=="ask"){return rest}return{...rest,shouldProceed:false,blockType:"denied",blockReason:"PreToolUse updatedInput is not supported for managed tool invocations; the tool was not run."}}__name(refuseUpdatedInput,"refuseUpdatedInput");var ManagedToolPreparationError=class extends Error{static{__name(this,"ManagedToolPreparationError")}};var MAX_INVOCATIONS=1024;var MAX_PROGRESS_BYTES=1024*1024;var ManagedToolRuntime=class{constructor(config,tools,policyRevision,sharedFileHistory,bindMediaTool){this.config=config;this.tools=tools;this.policyRevision=policyRevision;this.sharedFileHistory=sharedFileHistory;this.bindMediaTool=bindMediaTool}static{__name(this,"ManagedToolRuntime")}entries=new Map;calls=new Map;lifetime=new AbortController;activePrompt;pendingBuilds=0;pendingPreparations=0;snapshotPending=false;startedPrompts=new Set;disposal;manifest(){this.lifetime.signal.throwIfAborted();const tools=this.tools().map(tool=>({name:tool.name,displayName:tool.displayName,description:tool.description,kind:tool.kind,schema:tool.schema,canUpdateOutput:tool.canUpdateOutput,isOutputMarkdown:tool.isOutputMarkdown,shouldDefer:tool.shouldDefer,alwaysLoad:tool.alwaysLoad,...tool.searchHint===void 0?{}:{searchHint:tool.searchHint},...tool.maxOutputChars===void 0?{}:{maxOutputChars:tool.maxOutputChars===Infinity?"unlimited":tool.maxOutputChars},truncateKeep:tool.truncateKeep}));return{tools:structuredClone(tools),capabilityDigest:managedToolDigest(tools,1024*1024),policyRevision:this.policyRevision()}}assertCurrent(identity){this.lifetime.signal.throwIfAborted();const current=this.manifest();if(identity.sessionId!==this.config.getSessionId().toLowerCase()||identity.capabilityDigest!==current.capabilityDigest||identity.policyRevision!==current.policyRevision)throw new Error("Managed tool Session or capability changed.")}get(reference2){const entry=this.entries.get(reference2.invocationId);if(!entry||managedToolDigest(reference2)!==managedToolDigest(entry.reference)){throw new Error("Managed tool invocation identity does not match.")}return entry}scoped(identity,action){const owner="invocationId"in identity&&typeof identity.invocationId==="string"?this.entries.get(identity.invocationId)?.hookOwner:captureHookExecutionOwner(this.config);return runWithHookExecutionOwner(owner,()=>promptIdContext.run(identity.promptId,()=>runWithInvocationContext({version:1,sessionId:identity.sessionId,promptId:identity.promptId},action)))}beginTurn(identity){this.assertCurrent(identity);if(this.activePrompt?.id===identity.promptId)return this.activePrompt.snapshot;if(this.snapshotPending||this.pendingPreparations||[...this.entries.values()].some(entry=>!entry.result)){throw new Error("Managed Runtime still owns an unfinished tool invocation.")}if(this.startedPrompts.has(identity.promptId)){throw new Error("Managed Runtime cannot reopen a previous tool turn.")}this.entries.clear();this.calls.clear();identity=structuredClone(identity);this.snapshotPending=true;this.startedPrompts.add(identity.promptId);const snapshot=this.scoped(identity,async()=>{try{if(this.sharedFileHistory){await this.sharedFileHistory.prepareTurn(identity)}else{await this.config.getFileHistoryService().makeSnapshot(identity.promptId)}this.assertCurrent(identity)}finally{this.snapshotPending=false}});this.activePrompt={id:identity.promptId,snapshot};void snapshot.catch(()=>{});return snapshot}prepare(identity,toolName,input,modification,mediaContext){this.assertCurrent(identity);managedToolDigest(input);identity=structuredClone(identity);const copied=structuredClone(input);const media=mediaContext===void 0?void 0:parseManagedToolMediaContext(mediaContext);const contentModification=modification===void 0?void 0:parseManagedToolContentModification(modification);const inputDigest=managedToolDigest({identity,toolName,input:copied,...media===void 0?{}:{mediaContext:media},...contentModification===void 0?{}:{modification:contentModification}},1024*1024);const key=JSON.stringify([identity.promptId,identity.callId]);const slot=this.calls.get(key)??{};const previous=slot.pending;this.pendingPreparations++;const pending=(async()=>{await previous?.catch(()=>{});const entry=slot.current;if(entry){if(entry.inputDigest===inputDigest)return entry;if(!entry.controller.signal.aborted||entry.execution){throw new Error("Managed tool call already owns another invocation.")}await entry.cancellation}this.assertCurrent(identity);if(this.activePrompt?.id!==identity.promptId){throw new Error("Managed Runtime tool turn has not started.")}if(this.entries.size+this.pendingBuilds>=MAX_INVOCATIONS){throw new Error("Managed tool invocation capacity is exhausted.")}this.pendingBuilds++;try{await this.activePrompt.snapshot;this.assertCurrent(identity);const built=await this.scoped(identity,()=>this.build(identity,toolName,copied,inputDigest,contentModification,entry,media));slot.current=built;return built}finally{this.pendingBuilds--}})();void pending.then(()=>{this.pendingPreparations--},()=>{this.pendingPreparations--});slot.pending=pending;this.calls.set(key,slot);void pending.catch(()=>{if(slot.pending===pending&&!slot.current)this.calls.delete(key)});return pending.then(entry=>structuredClone(entry.prepared))}async build(identity,toolName,input,inputDigest,modification,source,mediaContext){const hookOwner=source?source.hookOwner:captureHookExecutionOwner(this.config);let tool=this.tools().find(candidate=>candidate.name===toolName);if(!tool)throw new ManagedToolPreparationError("Managed Runtime tool is unavailable.");if(mediaContext!==void 0){if(!this.bindMediaTool)throw new Error("Managed Runtime tool does not support media context.");tool=this.bindMediaTool(tool,mediaContext)}if(modification){if(!source||this.get(modification.source)!==source||source.tool!==tool||tool.name!==ToolNames.NOTEBOOK_EDIT||!isModifiableDeclarativeTool(tool)||!source.controller.signal.aborted||source.execution||managedToolDigest(input)!==source.reference.argsDigest)throw new Error("Managed content modification source does not match.");const details=await source.confirmation;if(details?.type!=="edit"||typeof details.originalContent!=="string")throw new Error("Managed content modification requires an edit confirmation.");this.assertCurrent(identity);input=tool.getModifyContext(this.lifetime.signal).createUpdatedParams(details.originalContent,modification.newContent,source.invocation.params)}let invocation;try{invocation=tool.build(input)}catch(error){throw new ManagedToolPreparationError(error instanceof Error?error.message:"Managed Runtime tool input is invalid.")}const aware=invocation;aware.setCallId?.(identity.callId);aware.setPromptId?.(identity.promptId);const defaultPermission=await invocation.getDefaultPermission();this.assertCurrent(identity);const reference2={...identity,invocationId:randomUUID3(),argsDigest:managedToolDigest(invocationParams(invocation.params))};const toolUseId=generateToolUseId();const entry={hookOwner,reference:reference2,inputDigest,tool,invocation,controller:new AbortController,toolUseId,prepared:{...reference2,params:invocationParams(invocation.params),description:invocation.getDescription(),locations:invocation.toolLocations(),defaultPermission,requiresUserInteraction:invocation.requiresUserInteraction?.()??false,toolUseId},decisions:new Map,hookConfirmed:false,progress:[],progressBytes:0,sequence:0};this.entries.set(reference2.invocationId,entry);return entry}async confirmation(reference2){const entry=this.get(reference2);this.assertExecutable(entry);entry.confirmation??=this.scoped(reference2,async()=>{const details2=await entry.invocation.getConfirmationDetails(entry.controller.signal);serializeManagedToolConfirmation(details2);return details2});const details=await entry.confirmation;this.assertExecutable(entry);return serializeManagedToolConfirmation(details)}async confirm(reference2,outcome,payload,phase="permission"){const entry=this.get(reference2);reference2=entry.reference;payload=payload===void 0?void 0:structuredClone(payload);if(phase!=="permission"&&phase!=="preflight")throw new Error("Invalid managed confirmation phase.");if(!Object.values(ToolConfirmationOutcome).includes(outcome)||outcome==="restore_previous"){throw new Error("Unsupported managed tool confirmation outcome.")}const digest2=managedToolDigest({outcome,...payload?{payload}:{}});const previous=entry.decisions.get(phase);if(previous){if(previous.digest!==digest2)throw new Error("Managed tool confirmation already decided.");return previous.promise}this.assertExecutable(entry);if(phase==="permission"&&entry.preflight)throw new Error("Managed tool preflight already started.");if(phase==="preflight"&&entry.preflightResult?.blockType!=="ask")throw new Error("Managed tool preflight did not request confirmation.");if(payload?.updatedInput!==void 0||payload?.newContent!==void 0||outcome==="modify_with_editor"){this.cancel(reference2);throw new Error("Modified tool arguments require a new preparation.")}const pending=(async()=>{await this.confirmation(reference2);this.assertExecutable(entry);const details=await entry.confirmation;await this.scoped(reference2,()=>details.onConfirm(runtimeLocalOutcome(outcome),payload));if(outcome==="cancel"){this.requestCancel(entry);return}this.assertExecutable(entry);if(phase==="preflight")entry.hookConfirmed=true})();const decision={digest:digest2,promise:pending,settled:false};entry.decisions.set(phase,decision);void pending.then(()=>{decision.settled=true},()=>{decision.settled=true});return pending}assertExecutable(entry){this.assertCurrent(entry.reference);entry.controller.signal.throwIfAborted();if(entry.execution)throw new Error("Managed tool invocation already dispatched.");if(managedToolDigest(invocationParams(entry.invocation.params))!==entry.reference.argsDigest){throw new Error("Managed tool parameters changed after preparation.")}}async preflight(reference2){const entry=this.get(reference2);this.assertExecutable(entry);entry.preflight??=this.scoped(reference2,async()=>{for(const decision of entry.decisions.values())await decision.promise;this.assertExecutable(entry);const result=await firePreToolUseHook(this.config.getDisableAllHooks()?void 0:this.config.getMessageBus(),entry.tool.name,entry.invocation.params,entry.toolUseId,this.config.getApprovalMode(),entry.controller.signal,entry.reference.callId,entry.hookOwner);this.assertExecutable(entry);const settled=refuseUpdatedInput(result);entry.preflightResult=structuredClone(settled);return settled});return structuredClone(await entry.preflight)}execute(reference2){const entry=this.get(reference2);if(entry.execution)return entry.execution.then(result=>structuredClone(result));this.assertExecutable(entry);const preflight=entry.preflightResult;if(!preflight||!preflight.shouldProceed&&!(preflight.blockType==="ask"&&entry.hookConfirmed)){throw new Error("Managed tool preflight has not permitted execution.")}if([...entry.decisions.values()].some(decision=>!decision.settled)){throw new Error("Managed tool confirmation is still pending.")}entry.execution=this.scoped(reference2,()=>this.sharedFileHistory?this.sharedFileHistory.execute(()=>this.run(entry)):this.run(entry)).catch(error=>{entry.result??={executionStatus:"not_started",error:{message:error instanceof Error?error.message:String(error),type:"execution_failed"}};throw error});void entry.execution.catch(()=>{});return entry.execution.then(result=>structuredClone(result))}progress(entry,output){const seq=++entry.sequence;const event={seq,output:structuredClone(output)};const bytes=Buffer.byteLength(JSON.stringify(event));if(bytes>MAX_PROGRESS_BYTES){entry.progress=[];entry.progressBytes=0;return}entry.progress.push({...event,bytes});entry.progressBytes+=bytes;while(entry.progressBytes>MAX_PROGRESS_BYTES){entry.progressBytes-=entry.progress.shift().bytes}}async run(entry){const signal=entry.controller.signal;const messageBus=this.config.getDisableAllHooks()?void 0:this.config.getMessageBus();let result;let executionStarted=false;try{signal.throwIfAborted();this.assertCurrent(entry.reference);executionStarted=true;const raw=await entry.invocation.execute(signal,output=>this.progress(entry,output),this.config.getShellExecutionConfig());result={executionStatus:isShellResultDisplay(raw.returnDisplay)&&raw.returnDisplay.outcome==="cancelled"?"cancelled":raw.error?signal.aborted?"cancelled":"error":"success"};try{result.result=structuredClone({llmContent:raw.llmContent,returnDisplay:raw.returnDisplay,...raw.error===void 0?{}:{error:raw.error},...raw.resultFilePaths===void 0?{}:{resultFilePaths:raw.resultFilePaths},...raw.persistedOutputFiles===void 0?{}:{persistedOutputFiles:raw.persistedOutputFiles},...raw.artifacts===void 0?{}:{artifacts:raw.artifacts}})}catch(error){result.error={message:`Cannot serialize managed tool result: ${String(error)}`,type:"execution_failed"}}}catch(error){result={executionStatus:!executionStarted?"not_started":signal.aborted?"cancelled":"error",error:{message:error instanceof Error?error.message:String(error),type:"execution_failed"}}}try{if(result.executionStatus==="error"||result.executionStatus==="cancelled"||result.result?.error!==void 0){result.failureHook=await firePostToolUseFailureHook(messageBus,entry.toolUseId,entry.tool.name,entry.invocation.params,result.result?.error?.message??result.error?.message??"Tool execution failed.",result.executionStatus==="cancelled"||signal.aborted,this.config.getApprovalMode(),void 0,entry.reference.callId,void 0,entry.hookOwner)}else if(result.executionStatus==="success"&&result.result){result.postHook=await firePostToolUseHook(messageBus,entry.tool.name,entry.invocation.params,{llmContent:result.result.llmContent,returnDisplay:result.result.returnDisplay},entry.toolUseId,this.config.getApprovalMode(),void 0,entry.reference.callId,void 0,entry.hookOwner)}}catch(error){const hookError=error instanceof Error?error.message:String(error);if(result.executionStatus==="success")result.postHook={shouldStop:false,hookError};else result.failureHook={hookError}}entry.result=structuredClone(result);return entry.result}findStatus(reference2,afterSeq=0){return this.entries.has(reference2.invocationId)?this.status(reference2,afterSeq):void 0}status(reference2,afterSeq=0){if(!Number.isSafeInteger(afterSeq)||afterSeq<0)throw new Error("Invalid managed tool progress cursor.");const entry=this.get(reference2);const firstAvailableSeq=entry.progress[0]?.seq??entry.sequence+1;return{state:entry.result?"settled":entry.controller.signal.aborted?"cancel_requested":entry.execution?"executing":"prepared",cancelRequested:entry.controller.signal.aborted,lastSeq:entry.sequence,firstAvailableSeq,progressGap:afterSeq+1<firstAvailableSeq,progress:structuredClone(entry.progress.filter(event=>event.seq>afterSeq).map(({seq,output})=>({seq,output}))),...entry.result?{result:structuredClone(entry.result)}:{}}}requestCancel(entry){entry.controller.abort(new Error("Managed tool invocation cancelled."));if(!entry.execution){entry.cancellation??=(async()=>{await Promise.allSettled([entry.confirmation,entry.preflight,...[...entry.decisions.values()].map(decision=>decision.promise)]);entry.result={executionStatus:"not_started"}})()}}cancel(reference2){const entry=this.get(reference2);this.requestCancel(entry);return this.status(reference2)}hasActiveWork(){return this.snapshotPending||this.pendingPreparations>0||[...this.entries.values()].some(entry=>!entry.result)}async releasePrepared(){if(this.snapshotPending||this.pendingPreparations>0||[...this.entries.values()].some(entry=>entry.execution!==void 0&&!entry.result)){throw new Error("Managed Runtime still owns unfinished execution.")}for(const entry of this.entries.values()){if(!entry.result)this.requestCancel(entry)}await Promise.all([...this.entries.values()].map(entry=>entry.cancellation))}seal(){this.lifetime.abort(new Error("Managed tool Runtime is closed."));for(const entry of this.entries.values())this.requestCancel(entry)}dispose(){this.disposal??=(async()=>{this.seal();await Promise.allSettled([...[...this.calls.values()].map(slot=>slot.pending),this.activePrompt?.snapshot]);await Promise.allSettled([...this.entries.values()].flatMap(entry=>[entry.confirmation,entry.preflight,entry.execution,entry.cancellation,...[...entry.decisions.values()].map(decision=>decision.promise)]));this.entries.clear();this.calls.clear()})();return this.disposal}};function runtimeLocalOutcome(outcome){switch(outcome){case"proceed_always":case"proceed_always_server":case"proceed_always_tool":case"proceed_always_project":case"proceed_always_user":return"proceed_once";default:return outcome}}__name(runtimeLocalOutcome,"runtimeLocalOutcome");var debugLogger2=createDebugLogger("MANAGED_RUNTIME_PROVIDER");function conflict(message,code="managed_runtime_provider_operation_failed"){throw new ManagedToolConflictError(message,code)}__name(conflict,"conflict");function forgetSession(runtimeSessionId){unregisterSessionProjectDir(runtimeSessionId);unregisterSessionModel(runtimeSessionId)}__name(forgetSession,"forgetSession");var RETAINED_RELEASED_SESSIONS=8;function retire(entry){entry.retirement??=(async()=>{const value=entry.value;const errors=[];for(const step of[()=>value?.runtime.dispose(),()=>value?.history?.drain(),()=>value?.config.shutdown({shutdownTelemetry:false,skipSessionWriter:true})]){try{await step()}catch(error){errors.push(error)}}entry.value=void 0;entry.ready=void 0;if(errors.length>0)throw new AggregateError(errors,"Retiring a Managed Runtime Session failed.")})();return entry.retirement}__name(retire,"retire");function history(value){return value.history??conflict("Managed Runtime file history is not bound.")}__name(history,"history");function workspaceAdmits(config,directory){if(!path3.isAbsolute(directory))return false;try{const real=fs2.realpathSync.native(directory);return config.getWorkspaceContext().getDirectories().some(root=>isPathWithinRoot(real,fs2.realpathSync.native(root)))}catch{return false}}__name(workspaceAdmits,"workspaceAdmits");var WorkspaceShellTool=class extends ShellTool{constructor(config,workspace){super(config);this.workspace=workspace}static{__name(this,"WorkspaceShellTool")}validateToolParamValues(params){return super.validateToolParamValues(params)??this.outside(params)}createInvocation(params){const invocation=super.createInvocation(params);const execute=invocation.execute.bind(invocation);invocation.execute=(...args)=>{const refusal2=this.outside(params);if(refusal2)throw new Error(refusal2);return execute(...args)};return invocation}outside(params){const directory=params.directory;return typeof directory==="string"&&directory!==""&&!workspaceAdmits(this.workspace,directory)?`Directory '${directory}' is not within any of the registered workspace directories.`:null}};var ManagedRuntimeProviderWorker=class{constructor(executor,contextFor){this.executor=executor;this.contextFor=contextFor}static{__name(this,"ManagedRuntimeProviderWorker")}sessions=new Map;released=[];closing=false;hasActiveSession(sessionId){const session=this.sessions.get(sessionId);return session!==void 0&&(session.pending>0||session.value?.runtime.hasActiveWork()===true)}getDrainInspection(){return{pendingInvocations:[...this.sessions.values()].reduce((count,session)=>count+session.pending+(session.value?.runtime.hasActiveWork()?1:0),0),hasActivity:[...this.sessions.values()].some(session=>session.ready!==void 0||session.value!==void 0)}}assertAdmissionOpen(){if(!this.executor.isAdmissionOpen)throw new ManagedToolUnavailableError("Managed Runtime admission is sealed.")}lookup(identity){const session=this.sessions.get(identity.runtimeSessionId);if(session&&(session.identity.harnessSessionId!==identity.harnessSessionId||session.identity.turnKind!==identity.turnKind)){conflict("Managed Runtime Session identity conflicts.","managed_runtime_identity_conflict")}return session}async control(identity,operation){if(operation.kind==="workspace-context")return this.executor.readWorkspaceContext(identity.runtimeSessionId);if(operation.kind==="raw-file-history")return this.executor.controlFileHistory(identity.harnessSessionId,identity.runtimeSessionId,operation);let session=this.lookup(identity);if(operation.kind==="release"){if(session?.closed)return true;if(!session){this.executor.closeSessionAdmission(identity.runtimeSessionId);this.sessions.set(identity.runtimeSessionId,{identity,closed:true,pending:0});return true}if(session.release)return session.release;if(session.pending>0)conflict("Managed Runtime Session still owns unfinished work.","managed_runtime_owner_hold_pending");const entry=session;entry.release=(async()=>{await entry.value?.runtime.releasePrepared();this.executor.closeSessionAdmission(identity.runtimeSessionId);forgetSession(identity.runtimeSessionId);entry.closed=true;this.released.push(entry);await this.retireReleased();return true})().catch(error=>{entry.release=void 0;throw error});return entry.release}if(operation.kind==="acquire"){this.assertAdmissionOpen();if(this.closing||session?.closed||session?.release)conflict("Managed Runtime Session is closed.");if(!session){this.executor.claimProviderSession(identity.runtimeSessionId);session={identity,closed:false,pending:0};this.sessions.set(identity.runtimeSessionId,session)}if(!session.ready){const entry=session;entry.pending++;entry.ready=this.createRuntime(identity.runtimeSessionId).then(value=>{entry.value=value;return value}).catch(error=>{this.executor.unclaimProviderSession(identity.runtimeSessionId);this.sessions.delete(identity.runtimeSessionId);throw error}).finally(()=>{entry.pending--})}await session.ready;return true}if(session?.closed&&!session.ready){if(operation.kind==="status"||operation.kind==="cancel")return{state:"unknown"};conflict("Managed Runtime Session is closed.")}if(!session?.ready)conflict("Managed Runtime Session has not been acquired.");const observes=["status","cancel","history"].includes(operation.kind)||this.executor.isAdmissionSealed&&!this.closing&&operation.kind==="manifest";if(!observes)this.assertAdmissionOpen();if((this.closing||session.closed||session.release)&&!observes)conflict("Managed Runtime Session is closed.");session.pending++;try{const value=await session.ready;if(!observes)await this.assertContext(identity.runtimeSessionId,value);if(!observes)this.assertAdmissionOpen();return await sessionIdContext.run(identity.runtimeSessionId,()=>this.dispatch(value,operation))}finally{session.pending--}}async retireReleased(){while(this.released.length>RETAINED_RELEASED_SESSIONS){const index=this.released.findIndex(entry2=>entry2.pending===0);if(index<0)return;const[entry]=this.released.splice(index,1);await retire(entry).catch(error=>debugLogger2.warn("Retiring a released Session failed:",error))}}async assertContext(sessionId,value){const context=await this.contextFor(sessionId);if(!context||context.isActive?.()===false||context.directory!==value.context.directory||context.workspaceRoot!==value.context.workspaceRoot||context.preapproved!==value.context.preapproved){throw new ManagedToolUnavailableError("Managed context directory is unavailable.")}}async createRuntime(sessionId){const context=await this.contextFor(sessionId);if(this.executor.isAdmissionSealed)throw new ManagedToolUnavailableError("Managed Runtime admission is sealed.");if(!context||context.isActive?.()===false){throw new ManagedToolUnavailableError("Managed context directory is unavailable.")}return sessionIdContext.run(sessionId,()=>{const config=new Config({sessionId,targetDir:context.directory,cwd:context.directory,includeDirectories:[context.workspaceRoot],model:"managed-runtime-worker",debugMode:false,usageStatisticsEnabled:false,approvalMode:context.preapproved?"yolo":"default",fileCheckpointingEnabled:true,fileReadCacheDisabled:true});const toolConfig=deriveConfig(config,{getFileHistoryService:__name(()=>history(value).service,"getFileHistoryService")});const shell=new WorkspaceShellTool(toolConfig,config);const tools=[new ReadFileTool(toolConfig),new WriteFileTool(toolConfig),new EditTool(toolConfig),shell];const policyRevision=randomUUID4();const runtime=new ManagedToolRuntime(toolConfig,()=>tools,()=>policyRevision,{prepareTurn:__name(identity=>history(value).checkpoint(identity.promptId),"prepareTurn"),execute:__name(action=>history(value).run(()=>{if(this.executor.isAdmissionSealed)this.assertAdmissionOpen();return action()}),"execute")},(tool,media)=>{if(tool.name!==ReadFileTool.Name)conflict("Managed Runtime tool does not support media context.");return new ReadFileTool(deriveConfig(toolConfig,{getEffectiveInputModalities:__name(()=>({...media.inputModalities}),"getEffectiveInputModalities"),getFileReadCache:__name(()=>toolConfig.getFileReadCache(),"getFileReadCache"),getFileService:__name(()=>toolConfig.getFileService(),"getFileService")}))});const value={context,config,runtime,shell};registerSessionProjectDir(sessionId,config.storage.getProjectDir());return value})}async bindHistory(value,binding){if(binding.executionCwd!==value.context.directory||binding.executionContext!==void 0&&managedToolDigest(binding.executionContext)!==managedToolDigest(captureManagedToolExecutionContext(value.config))){conflict("Managed Runtime file history execution context conflicts.")}const digest2=managedToolDigest(binding,MANAGED_TOOL_FILE_HISTORY_MAX_BYTES);if(value.historyBinding!==void 0){if(value.historyBinding!==digest2)conflict("Managed Runtime file history binding conflicts.");await history(value).ready();return history(value).state()}if(value.runtime.hasActiveWork())conflict("Managed Runtime file history must be bound before starting a turn.");value.historyBinding=digest2;value.history=new ManagedToolFileHistory(binding.ownerSessionId,value.context.directory,binding.snapshots);await value.history.ready();return value.history.state()}async dispatch(value,operation){const runtime=value.runtime;switch(operation.kind){case"manifest":return runtime.manifest();case"begin-turn":await history(value).ready();this.assertAdmissionOpen();await runtime.beginTurn(operation.identity);return null;case"prepare":{if(operation.toolName===ShellTool.Name){const normalized=structuredClone(operation.input);if(value.shell.validateToolParams(normalized)===null&&normalized["is_background"]===true)conflict("Managed Runtime does not admit background shell execution.")}if(operation.modification!==void 0)throw new ManagedToolPreparationError("Managed Runtime provider profile does not admit content modification.");return runtime.prepare(operation.identity,operation.toolName,operation.input,void 0,operation.mediaContext)}case"confirmation":return runtime.confirmation(operation.reference);case"confirm":await runtime.confirm(operation.reference,operation.outcome,operation.payload,operation.phase);return null;case"preflight":return runtime.preflight(operation.reference);case"execute":return runtime.execute(operation.reference);case"status":case"cancel":{const status=runtime.findStatus(operation.reference,operation.kind==="status"?operation.afterSequence:0);if(!status)return{state:"unknown"};return operation.kind==="cancel"&&status.state!=="settled"?runtime.cancel(operation.reference):status}case"bind-history":return this.bindHistory(value,operation.binding);case"checkpoint":if(runtime.hasActiveWork())conflict("Managed Runtime Session still owns unfinished work.");await history(value).checkpoint(operation.promptId);return history(value).state();case"history":await history(value).drain();return history(value).state();case"acquire":case"release":default:throw new Error("Managed Runtime Session operation was not dispatched.")}}async close(){this.closing=true;await Promise.allSettled([...this.sessions.values()].map(async session=>{try{await session.ready;await retire(session)}finally{forgetSession(session.identity.runtimeSessionId)}}))}};function registerManagedRuntimeProviderRoute(app,identity,executor,contextFor){const provider=new ManagedRuntimeProviderWorker(executor,contextFor);executor.attachProvider(provider);app.post(MANAGED_RUNTIME_PROVIDER_ROUTE.path,managedRuntimeNoStore,authorizeManagedRuntime(identity),managedRuntimeJsonBody(MANAGED_RUNTIME_PROVIDER_ROUTE.requestBodyLimitBytes),async(req,res)=>{try{const request=parseManagedRuntimeProviderRequest(req.body);const raw=JSON.parse(JSON.stringify(await provider.control(request.session,request.operation)));const limit=Math.min(MANAGED_RUNTIME_PROVIDER_ROUTE.responseBodyLimitBytes,managedRuntimeProviderLimit(request.operation.kind));const envelopeOverhead=Buffer.byteLength(JSON.stringify({protocolVersion:request.protocolVersion,providerProtocol:request.providerProtocol,session:request.session,result:0}))-1;const result=fitManagedRuntimeProviderResult(request.operation,raw,limit-envelopeOverhead);parseManagedRuntimeProviderResult(request.operation,result,request.session);const json=JSON.stringify({protocolVersion:request.protocolVersion,providerProtocol:request.providerProtocol,session:request.session,result});if(Buffer.byteLength(json)>limit){res.status(413).json({code:"managed_runtime_provider_too_large",error:"Managed Runtime provider response exceeds its body size limit."});return}res.status(200).type("application/json").send(json)}catch(error){if(error instanceof ManagedRuntimeProviderProtocolError){res.status(error.status).json({code:error.code,error:error.message})}else if(error instanceof ManagedToolPreparationError){res.status(400).json({code:"managed_runtime_tool_invalid",error:error.message})}else if(error instanceof ManagedToolProtocolError){res.status(400).json({code:"managed_runtime_provider_invalid",error:error.message})}else{res.status(409).json({code:error instanceof ManagedToolUnavailableError||error instanceof ManagedToolConflictError?error.code:"managed_runtime_provider_operation_failed",error:error instanceof Error?error.message:"Managed Runtime provider operation failed."})}}},handleManagedRuntimeJsonError)}__name(registerManagedRuntimeProviderRoute,"registerManagedRuntimeProviderRoute");init_esbuild_shims();import{createHash as createHash5}from"node:crypto";import{readFileSync as readFileSync3}from"node:fs";import{isAbsolute}from"node:path";import{pathToFileURL}from"node:url";var ManagedHookError=class extends Error{constructor(code){super(code);this.code=code}static{__name(this,"ManagedHookError")}};var ManagedHookImportAbortedError=class extends Error{static{__name(this,"ManagedHookImportAbortedError")}};function importHookModule(modulePath,timeoutMs,signal,entry){return new Promise((resolve,reject)=>{let finished=false;const timer=setTimeout(()=>finish(new ManagedHookError("managed_hook_module_evaluation_timeout")),timeoutMs);const onAbort=__name(()=>finish(new ManagedHookImportAbortedError),"onAbort");function finish(error,module){if(finished)return;finished=true;clearTimeout(timer);signal.removeEventListener("abort",onAbort);if(error)reject(error);else resolve(module)}__name(finish,"finish");if(signal.aborted){onAbort();return}let href;try{href=pathToFileURL(modulePath).href}catch(cause){finish(cause instanceof Error?cause:new Error(String(cause)));return}signal.addEventListener("abort",onAbort,{once:true});entry.moduleEvaluationPending=true;import(href).then(module=>{entry.moduleEvaluationPending=false;settleAbandoned(entry,{state:"settled",result:{success:false,outcome:entry.view.error?.code==="managed_hook_module_evaluation_timeout"?"timeout":"cancelled",duration:0,notStarted:true}});finish(void 0,module)},()=>{entry.moduleEvaluationPending=false;settleAbandoned(entry,{state:"settled",error:{code:"managed_hook_handler_unavailable"}});finish(new ManagedHookError("managed_hook_handler_unavailable"))}).catch(()=>{entry.moduleEvaluationPending=false;settleAbandoned(entry,{state:"settled",error:{code:"managed_hook_handler_unavailable"}});finish(new ManagedHookError("managed_hook_handler_unavailable"))})})}__name(importHookModule,"importHookModule");var FENCED_EVALUATION_CODES=new Set(["managed_hook_module_evaluation_abandoned","managed_hook_module_evaluation_timeout"]);function settleAbandoned(entry,view2){if(!FENCED_EVALUATION_CODES.has(entry.view.error?.code??""))return;entry.view={operationId:entry.view.operationId,...view2}}__name(settleAbandoned,"settleAbandoned");var identifier2=/^[a-zA-Z0-9:_.-]{1,512}$/u;var MAX_OPERATIONS=4096;var MAX_BYTES=60*1024;var FUNCTION_SETTLEMENT_GRACE_MS=1e3;var MODULE_EVALUATION_MIN_TIMEOUT_MS=500;function object2(value){if(!value||typeof value!=="object"||Array.isArray(value))throw new ManagedHookError("managed_hook_invalid");return value}__name(object2,"object");function closed4(value,keys){if(Object.keys(value).some(key=>!keys.includes(key)))throw new ManagedHookError("managed_hook_invalid")}__name(closed4,"closed");function text(value){return typeof value==="string"&&identifier2.test(value)}__name(text,"text");function positive2(value){return Number.isSafeInteger(value)&&Number(value)>0}__name(positive2,"positive");function pin(value){const parsed=object2(value);closed4(parsed,["catalogId","catalogRevision","definitionDigest"]);if(!text(parsed["catalogId"])||!positive2(parsed["catalogRevision"])||typeof parsed["definitionDigest"]!=="string"||!/^[a-f0-9]{64}$/u.test(parsed["definitionDigest"]))throw new ManagedHookError("managed_hook_invalid");return parsed}__name(pin,"pin");function scope2(key){return`${key.tenantId}\0${key.workspaceId}\0${key.sessionId}`}__name(scope2,"scope");function fingerprint2(value){return createHash5("sha256").update(JSON.stringify(value)).digest("hex")}__name(fingerprint2,"fingerprint");function quotaExceeded(operationId){return{operationId,state:"settled",result:{success:false,outcome:"non_blocking_error",duration:0,error:"Managed hook execution quota exceeded before dispatch."}}}__name(quotaExceeded,"quotaExceeded");function parseManagedHookControl(value){const control=object2(value);const key=object2(control["sessionKey"]);closed4(key,["tenantId","workspaceId","sessionId"]);if(!["tenantId","workspaceId","sessionId"].every(field=>text(key[field]))||!text(control["operationId"]))throw new ManagedHookError("managed_hook_invalid");if(control["kind"]==="hook-status"||control["kind"]==="hook-cancel"){closed4(control,["kind","sessionKey","operationId","targetOperationId"]);if(!text(control["targetOperationId"]))throw new ManagedHookError("managed_hook_invalid")}else if(control["kind"]==="hook-catalog"){closed4(control,["kind","sessionKey","operationId","pin"]);pin(control["pin"])}else if(control["kind"]==="hook-execute"){closed4(control,["kind","sessionKey","operationId","pin","hookId","input","grant"]);pin(control["pin"]);const input=object2(control["input"]);if(!text(control["hookId"])||input["session_id"]!==key["sessionId"]||typeof input["cwd"]!=="string"||typeof input["transcript_path"]!=="string"||typeof input["timestamp"]!=="string"||input["messages"]!==void 0&&(!Array.isArray(input["messages"])||input["messages"].some(value2=>!value2||typeof value2!=="object"||Array.isArray(value2)))||!Object.values(HookEventName).includes(input["hook_event_name"]))throw new ManagedHookError("managed_hook_invalid");try{parseOperationGrant(control["grant"])}catch{throw new ManagedHookError("managed_hook_grant_invalid")}}else throw new ManagedHookError("managed_hook_invalid");return structuredClone(control)}__name(parseManagedHookControl,"parseManagedHookControl");function loadManagedHookManifest(path8){if(!path8)return{version:1,catalogs:[]};try{const bytes=readFileSync3(path8);if(bytes.length>1024*1024)throw new Error("too large");return parseManifest2(JSON.parse(bytes.toString("utf8")))}catch{throw new ManagedHookError("managed_hook_manifest_invalid")}}__name(loadManagedHookManifest,"loadManagedHookManifest");function parseManifest2(value){const manifest=object2(value);closed4(manifest,["version","catalogs"]);if(manifest["version"]!==1||!Array.isArray(manifest["catalogs"]))throw new ManagedHookError("managed_hook_manifest_invalid");const pins=new Set;for(const raw of manifest["catalogs"]){const catalog=object2(raw);closed4(catalog,["tenantId","workspaceId","catalogId","catalogRevision","definitionDigest","hooks"]);pin({catalogId:catalog["catalogId"],catalogRevision:catalog["catalogRevision"],definitionDigest:catalog["definitionDigest"]});if(!text(catalog["tenantId"])||!text(catalog["workspaceId"])||!Array.isArray(catalog["hooks"])||catalog["hooks"].length>128)throw new ManagedHookError("managed_hook_manifest_invalid");const identity=JSON.stringify([catalog["tenantId"],catalog["workspaceId"],catalog["catalogId"],catalog["catalogRevision"]]);if(pins.has(identity))throw new ManagedHookError("managed_hook_definition_conflict");pins.add(identity);const ids=new Set;for(const rawHook of catalog["hooks"]){const hook=object2(rawHook);closed4(hook,["hookId","eventName","matcher","sequential","onceKey","failClosed","async","config","handler","source","sourceTrusted","enabled","agentScope","owner"]);const config=object2(hook["config"]);if(hook["source"]!==void 0&&!Object.values(HooksConfigSource).includes(hook["source"])||["sourceTrusted","enabled"].some(key=>hook[key]!==void 0&&typeof hook[key]!=="boolean")||hook["agentScope"]!==void 0&&!text(hook["agentScope"]))throw new ManagedHookError("managed_hook_manifest_invalid");if(hook["owner"]!==void 0){const owner=object2(hook["owner"]);closed4(owner,["sessionId","agentId"]);if(!text(owner["sessionId"])||!(owner["agentId"]===null||text(owner["agentId"])))throw new ManagedHookError("managed_hook_manifest_invalid")}if(hook["source"]==="session"&&hook["owner"]===void 0||hook["agentScope"]!==void 0&&(hook["source"]!=="session"||object2(hook["owner"])["agentId"]===null))throw new ManagedHookError("managed_hook_manifest_invalid");if(!text(hook["hookId"])||ids.has(hook["hookId"])||!Object.values(HookEventName).includes(hook["eventName"])||!["sequential","failClosed","async"].every(key=>typeof hook[key]==="boolean")||!(hook["onceKey"]===null||text(hook["onceKey"]))||hook["matcher"]!==void 0&&typeof hook["matcher"]!=="string"||config["name"]!==void 0&&typeof config["name"]!=="string"||config["timeout"]!==void 0&&(!positive2(config["timeout"])||Number(config["timeout"])>6e5))throw new ManagedHookError("managed_hook_manifest_invalid");ids.add(hook["hookId"]);if(config["type"]==="command"){closed4(config,["type","name","command","timeout","env","shell"]);if(typeof config["command"]!=="string"||!config["command"]||config["command"].includes("\0")||config["shell"]!==void 0&&!["bash","powershell"].includes(String(config["shell"])))throw new ManagedHookError("managed_hook_manifest_invalid")}else if(config["type"]==="http"){closed4(config,["type","name","url","headers","allowedEnvVars","timeout"]);const url=new URL(String(config["url"]));if(!["http:","https:"].includes(url.protocol)||url.username||url.password||config["allowedEnvVars"]!==void 0&&(!Array.isArray(config["allowedEnvVars"])||!config["allowedEnvVars"].every(item=>typeof item==="string")))throw new ManagedHookError("managed_hook_manifest_invalid")}else if(config["type"]==="prompt"){closed4(config,["type","name","prompt","model","timeout"]);if(typeof config["prompt"]!=="string"||!config["prompt"]||config["model"]!==void 0&&typeof config["model"]!=="string")throw new ManagedHookError("managed_hook_manifest_invalid")}else if(config["type"]==="function"){closed4(config,["type","name","timeout"]);const handler=object2(hook["handler"]);closed4(handler,["handlerId","handlerRevision","modulePath","exportName"]);if(!text(handler["handlerId"])||!positive2(handler["handlerRevision"])||typeof handler["modulePath"]!=="string"||!isAbsolute(handler["modulePath"])||!text(handler["exportName"])||!positive2(config["timeout"]))throw new ManagedHookError("managed_hook_manifest_invalid")}else throw new ManagedHookError("managed_hook_manifest_invalid");if(config["type"]!=="function"&&hook["handler"]!==void 0)throw new ManagedHookError("managed_hook_manifest_invalid");if(hook["async"]&&config["type"]!=="command")throw new ManagedHookError("managed_hook_manifest_invalid");for(const field of["env","headers"]){if(config[field]!==void 0&&Object.entries(object2(config[field])).some(([key,value2])=>key.includes("\0")||typeof value2!=="string"||value2.includes("\0")))throw new ManagedHookError("managed_hook_manifest_invalid")}}}return structuredClone(manifest)}__name(parseManifest2,"parseManifest");var ManagedHookRuntime=class{constructor(workspace,sessionDirectory,manifest){this.workspace=workspace;this.sessionDirectory=sessionDirectory;this.manifest=parseManifest2(manifest)}static{__name(this,"ManagedHookRuntime")}manifest;operations=new Map;gates=new ManagedOperationGrantGate;shutdown=createAbortController();closing=false;admissionSealed=false;lifecycleStarted=false;pendingStarts=0;sealAdmission(){this.admissionSealed=true}getDrainInspection(){return{hasActivity:this.lifecycleStarted,pendingStarts:this.pendingStarts,pendingInvocations:[...this.operations.values()].filter(entry=>entry.view.state!=="settled").length}}requireAdmission(){if(this.closing||this.admissionSealed)throw new ManagedHookError("managed_hook_closed")}async control(runtimeSessionId,value){this.pendingStarts++;try{return await this.controlAdmitted(runtimeSessionId,value)}finally{this.pendingStarts--}}async controlAdmitted(runtimeSessionId,value){const control=parseManagedHookControl(value);if(control.sessionKey.tenantId!==this.workspace.tenantId||control.sessionKey.workspaceId!==this.workspace.workspaceId)throw new ManagedHookError("managed_hook_scope_conflict");if(control.kind==="hook-status"||control.kind==="hook-cancel"){const existing2=this.operations.get(`${scope2(control.sessionKey)}\0${control.targetOperationId}`);if(!existing2||existing2.runtimeSessionId!==runtimeSessionId)return{operationId:control.targetOperationId,state:"outcome_unknown"};if(control.kind==="hook-cancel")existing2.controller.abort();return structuredClone(existing2.view)}const{pin:expected}=control;const catalog=this.manifest.catalogs.find(entry2=>entry2.tenantId===control.sessionKey.tenantId&&entry2.workspaceId===control.sessionKey.workspaceId&&entry2.catalogId===expected.catalogId&&entry2.catalogRevision===expected.catalogRevision&&entry2.definitionDigest===expected.definitionDigest);if(!catalog)throw new ManagedHookError("managed_hook_catalog_unavailable");const key=`${scope2(control.sessionKey)}\0${control.operationId}`;const{grant:_grant,...effect}=control.kind==="hook-execute"?control:{...control,grant:void 0};const digest2=fingerprint2(effect);const existing=this.operations.get(key);if(existing){if(existing.runtimeSessionId!==runtimeSessionId||existing.fingerprint!==digest2)throw new ManagedHookError("managed_hook_operation_conflict");return structuredClone(existing.view)}this.requireAdmission();this.lifecycleStarted=true;const directory=await this.sessionDirectory(runtimeSessionId);this.requireAdmission();if(!directory)throw new ManagedHookError("managed_hook_session_unavailable");if(control.kind==="hook-catalog"){const exposed={...expected,hooks:await this.descriptors(catalog.hooks)};this.requireAdmission();if(Buffer.byteLength(JSON.stringify(exposed))>MAX_BYTES)throw new ManagedHookError("managed_hook_catalog_limit");return{operationId:control.operationId,state:"settled",catalog:exposed}}const definition=catalog.hooks.find(entry2=>entry2.hookId===control.hookId);if(!definition||definition.eventName!==control.input.hook_event_name||definition.sourceTrusted===false||definition.enabled===false||definition.owner&&(definition.owner.sessionId!==control.sessionKey.sessionId||definition.agentScope!==void 0&&definition.owner.agentId!==(control.input.agent_id??null)))throw new ManagedHookError("managed_hook_definition_unavailable");if(definition.config.type==="prompt")throw new ManagedHookError("managed_hook_requires_harness");const grant=control.grant;if(scope2(grant.sessionKey)!==scope2(control.sessionKey)||grant.domain!=="hook_execution"||grant.operationId!==control.operationId||grant.workspaceGeneration!==this.workspace.workspaceGeneration)throw new ManagedHookError("managed_hook_grant_invalid");if(this.operations.has(key))return this.control(runtimeSessionId,control);this.requireAdmission();if(this.operations.size>=MAX_OPERATIONS)return{operationId:control.operationId,state:"settled",result:{success:false,outcome:"blocking",duration:0,output:{continue:false,decision:"block",reason:"Managed Hook receipt capacity is exhausted.",...definition.eventName==="PermissionRequest"?{hookSpecificOutput:{decision:{behavior:"deny",interrupt:true,message:"Managed Hook receipt capacity is exhausted."}}}:{}}}};try{this.gates.install(grant)}catch{throw new ManagedHookError("managed_hook_grant_invalid")}if(!this.gates.admits(control.sessionKey,control.operationId,"execute",Date.now()))throw new ManagedHookError("managed_hook_grant_invalid");const atRunningLimit=[...this.operations.values()].filter(entry2=>entry2.view.state!=="settled").length>=MANAGED_HOOK_MAX_RUNNING;const entry={runtimeSessionId,fingerprint:digest2,sessionKey:control.sessionKey,controller:new AbortController,view:atRunningLimit?quotaExceeded(control.operationId):{operationId:control.operationId,state:"running"}};this.operations.set(key,entry);if(!atRunningLimit)entry.done=this.execute(entry,definition,control,directory);return structuredClone(entry.view)}async descriptors(definitions){const native=new Map;const sources=new Map;const agentHooks=[];const sessionHooks=[];for(const definition of definitions){if(definition.enabled===false||definition.sourceTrusted===false)continue;const config=definition.config.type==="function"?{...definition.config,type:"function",id:definition.handler.handlerId,callback:__name(async()=>void 0,"callback"),errorMessage:"Managed hook handler failed."}:{...definition.config};native.set(config,definition);const source=definition.source??"system";if(source==="session"){(definition.agentScope?agentHooks:sessionHooks).push({definition,config});continue}const grouped=sources.get(source)??{};(grouped[definition.eventName]??=[]).push({matcher:definition.matcher,sequential:definition.sequential,hooks:[config]});sources.set(source,grouped)}const registry=new HookRegistry({getProjectRoot:__name(()=>"","getProjectRoot"),isTrustedFolder:__name(()=>true,"isTrustedFolder"),getSystemHooks:__name(()=>sources.get("system"),"getSystemHooks"),getUserHooks:__name(()=>sources.get("user"),"getUserHooks"),getProjectHooks:__name(()=>sources.get("project"),"getProjectHooks"),getExtensions:__name(()=>[{isActive:true,hooks:sources.get("extensions")}],"getExtensions")});await registry.initialize();for(const{definition,config}of agentHooks){registry.addAgentHooks({[definition.eventName]:[{matcher:definition.matcher,sequential:definition.sequential,hooks:[config]}]},definition.agentScope,{owner:{sessionId:definition.owner.sessionId,agentId:definition.owner.agentId}})}const expose=__name((definition,config,deduplicate)=>{const{handler,config:_recipe,...descriptor}=definition;return{...descriptor,source:definition.source??"system",...deduplicate?{plannerKey:fingerprint2(getHookKey(config))}:{},config:config.type==="prompt"?definition.config:{type:config.type,...config.name?{name:config.name}:{}},...handler?{handler:{handlerId:handler.handlerId,handlerRevision:handler.handlerRevision}}:{}}},"expose");return[...Object.values(HookEventName).flatMap(event=>registry.getHooksForEvent(event).map(entry=>expose(native.get(entry.config),entry.config,true))),...sessionHooks.map(({definition,config})=>expose(definition,config,false))]}hasHolds(runtimeSessionId){return[...this.operations.values()].some(entry=>entry.runtimeSessionId===runtimeSessionId&&(entry.view.state!=="settled"||entry.moduleEvaluationPending===true))}async close(){this.closing=true;this.shutdown.abort();for(const entry of this.operations.values())entry.controller.abort();await Promise.all([...this.operations.values()].map(entry=>entry.done))}async execute(entry,definition,control,directory){let dispatched=false;let functionCompletion;try{let config;if(definition.config.type==="function"){const handler=definition.handler;let registered;try{const module=await importHookModule(handler.modulePath,Math.max(definition.config.timeout,MODULE_EVALUATION_MIN_TIMEOUT_MS),entry.controller.signal,entry);registered=object2(module[handler.exportName]);if(registered["handlerRevision"]!==handler.handlerRevision||typeof registered["callback"]!=="function"||registered["onHookSuccess"]!==void 0&&typeof registered["onHookSuccess"]!=="function")throw new Error("handler revision unavailable")}catch(error){if(error instanceof ManagedHookImportAbortedError){if(entry.moduleEvaluationPending)throw new ManagedHookError("managed_hook_module_evaluation_abandoned");entry.view={operationId:control.operationId,state:"settled",result:{success:false,outcome:"cancelled",duration:0,notStarted:true}};return}if(error instanceof ManagedHookError&&error.code==="managed_hook_module_evaluation_timeout")throw error;throw new ManagedHookError("managed_hook_handler_unavailable")}const callback=registered["callback"];config={...definition.config,type:"function",id:handler.handlerId,callback:__name((input,context)=>{const pending=Promise.resolve().then(()=>{this.requireAdmission();return callback(input,context)});functionCompletion=pending.then(()=>true,()=>true);return pending},"callback"),errorMessage:"Managed hook handler failed.",...registered["onHookSuccess"]?{onHookSuccess:registered["onHookSuccess"]}:{}}}else if(definition.config.type==="command"){config={...definition.config,async:false}}else{config=definition.config}const currentDirectory=await this.sessionDirectory(entry.runtimeSessionId);this.requireAdmission();if(!this.gates.admits(control.sessionKey,control.operationId,"execute",Date.now())||currentDirectory!==directory)throw new ManagedHookError("managed_hook_grant_invalid");if(entry.controller.signal.aborted){entry.view={operationId:control.operationId,state:"settled",result:{success:false,outcome:"cancelled",duration:0,notStarted:true}};return}const runner=new HookRunner(config.type==="http"?[interpolateUrl(config.url,config.allowedEnvVars??[])]:void 0);dispatched=true;const result=await runner.executeHook(config,definition.eventName,{...control.input,cwd:directory,session_id:control.sessionKey.sessionId},{signal:entry.controller.signal,...Array.isArray(control.input["messages"])?{messages:control.input.messages}:{},..."tool_use_id"in control.input&&typeof control.input.tool_use_id==="string"?{toolUseID:control.input.tool_use_id}:{}},config.type==="command"?{waitForProcessTree:true,cgroupRoot:process.env["QWEN_MANAGED_HOOK_CGROUP_ROOT"],environment:{PATH:process.env["PATH"]??"",HOME:directory,USERPROFILE:directory,...process.env["SystemRoot"]?{SYSTEMROOT:process.env["SystemRoot"]}:{}}}:config.type==="http"?{trackHttpRequest:true,httpRequestSignal:this.shutdown.signal}:void 0);if(result.error instanceof HookCommandIsolationUnavailableError){entry.view={operationId:control.operationId,state:"settled",error:{code:"managed_hook_command_isolation_unavailable"}};return}let functionSettled=true;if(config.type==="function"&&(result.outcome==="timeout"||result.outcome==="cancelled")&&functionCompletion){let timer;functionSettled=await Promise.race([functionCompletion,new Promise(resolve=>{timer=setTimeout(()=>resolve(false),FUNCTION_SETTLEMENT_GRACE_MS)})]);clearTimeout(timer)}const uncertain=config.type==="command"&&result.processTreeDrained!==true||config.type==="function"&&!functionSettled||config.type==="http"&&(!result.httpRequestState||result.httpRequestState==="outcome_unknown");if(uncertain){entry.view={operationId:control.operationId,state:"outcome_unknown",error:{code:"managed_hook_outcome_unknown"}};return}this.settle(entry,result)}catch(error){if(!dispatched&&error instanceof ManagedHookError&&error.code==="managed_hook_grant_invalid"){entry.view={operationId:control.operationId,state:"settled",result:{success:false,outcome:"non_blocking_error",duration:0,error:"Managed hook authorization expired before dispatch."}};return}if(!dispatched&&!(error instanceof ManagedHookError)){entry.view={operationId:control.operationId,state:"settled",result:{success:false,outcome:"non_blocking_error",duration:0,error:"Managed hook failed before dispatch."}};return}entry.view={operationId:control.operationId,state:dispatched?"outcome_unknown":"settled",error:{code:error instanceof ManagedHookError?error.code:"managed_hook_execution_failed"}}}}settle(entry,result){const view2={operationId:entry.view.operationId,state:"settled",result:{success:result.success,outcome:result.outcome??(result.success?"success":"non_blocking_error"),duration:result.duration,...result.output?{output:result.output}:{},...result.stdout?{stdout:result.stdout}:{},...result.stderr?{stderr:result.stderr}:{},...result.error?{error:"Managed hook execution failed."}:{}}};entry.view=Buffer.byteLength(JSON.stringify(view2))<=MAX_BYTES?view2:{operationId:entry.view.operationId,state:"settled",result:{success:false,outcome:"non_blocking_error",duration:result.duration,error:"Managed hook output exceeds the size limit."}}}};init_esbuild_shims();var MANAGED_HOOK_WORKER_ROUTE=Object.freeze({key:"hook",method:"POST",path:MANAGED_HOOK_ROUTE,protocolVersion:1,requestBodyLimitBytes:MANAGED_HOOK_MAX_REQUEST_BYTES,responseBodyLimitBytes:1024*1024,cacheControl:"no-store"});function registerManagedHookRoutes(app,identity,runtime){app.post(MANAGED_HOOK_ROUTE,managedRuntimeNoStore,authorizeManagedRuntime(identity),managedRuntimeJsonBody(MANAGED_HOOK_WORKER_ROUTE.requestBodyLimitBytes),async(req,res)=>{const body2=req.body;if(!body2||typeof body2!=="object"||Array.isArray(body2)){res.status(400).json({code:"managed_hook_invalid"});return}const request=body2;if(Object.keys(request).sort().join(",")!=="operation,protocolVersion,runtimeSessionId"||request["protocolVersion"]!==1||typeof request["runtimeSessionId"]!=="string"||!request["runtimeSessionId"]){res.status(400).json({code:"managed_hook_invalid"});return}try{const operation=await runtime.control(request["runtimeSessionId"],request["operation"]);res.json({protocolVersion:1,runtimeSessionId:request["runtimeSessionId"],operation})}catch(error){const code=error instanceof ManagedHookError?error.code:"managed_hook_unavailable";res.status(code==="managed_hook_invalid"?400:409).json({code})}},handleManagedRuntimeJsonError)}__name(registerManagedHookRoutes,"registerManagedHookRoutes");init_esbuild_shims();var MANAGED_MCP_WORKER_ROUTE=Object.freeze({key:"mcp",method:"POST",path:MANAGED_MCP_ROUTE,protocolVersion:1,requestBodyLimitBytes:256*1024,responseBodyLimitBytes:1024*1024,cacheControl:"no-store"});function registerManagedMcpRoutes(app,identity,runtime){app.post(MANAGED_MCP_ROUTE,managedRuntimeNoStore,authorizeManagedRuntime(identity),managedRuntimeJsonBody(MANAGED_MCP_WORKER_ROUTE.requestBodyLimitBytes),async(req,res)=>{const body2=req.body;if(!body2||typeof body2!=="object"||Array.isArray(body2)){res.status(400).json({code:"managed_mcp_invalid"});return}const request=body2;if(Object.keys(request).sort().join(",")!=="operation,protocolVersion,runtimeSessionId"||request["protocolVersion"]!==1||typeof request["runtimeSessionId"]!=="string"||!request["runtimeSessionId"]){res.status(400).json({code:"managed_mcp_invalid"});return}try{const operation=await runtime.control(request["runtimeSessionId"],request["operation"]);res.json({protocolVersion:1,runtimeSessionId:request["runtimeSessionId"],operation})}catch(error){const code=error instanceof ManagedMcpError?error.code:"managed_mcp_unavailable";res.status(code==="managed_mcp_invalid"?400:409).json({code})}},handleManagedRuntimeJsonError)}__name(registerManagedMcpRoutes,"registerManagedMcpRoutes");init_esbuild_shims();init_esbuild_shims();var MANAGED_SHELL_ROUTE="/internal/managed-runtime/v3/shells";function shellUnitNameOf(targetOperationId){return`qwen-bg-${targetOperationId.replace(/[^a-zA-Z0-9._-]/g,"-")}`}__name(shellUnitNameOf,"shellUnitNameOf");var ManagedShellError=class extends Error{constructor(code,message){super(message);this.code=code;this.name="ManagedShellError"}static{__name(this,"ManagedShellError")}};var KEYS=["kind","operationId","sessionKey","targetOperationId"];function parseOperation(value){if(!value||typeof value!=="object"||Array.isArray(value)){throw new ManagedShellError("managed_shell_invalid","Shell operation is invalid.")}const object5=value;if(Object.keys(object5).sort().join(",")!==[...KEYS].sort().join(",")){throw new ManagedShellError("managed_shell_invalid","Shell operation is invalid.")}const kind=object5["kind"];if(kind!=="shell-status"&&kind!=="shell-terminate"){throw new ManagedShellError("managed_shell_invalid","Shell operation is invalid.")}const sessionKey=object5["sessionKey"];if(!sessionKey||typeof sessionKey!=="object"||typeof sessionKey["tenantId"]!=="string"||typeof sessionKey["sessionId"]!=="string"){throw new ManagedShellError("managed_shell_invalid","Shell operation scope is invalid.")}for(const key of["operationId","targetOperationId"]){const field=object5[key];if(typeof field!=="string"||!field||field.length>512){throw new ManagedShellError("managed_shell_invalid",`Shell operation ${key} is invalid.`)}}return{kind,operationId:object5["operationId"],targetOperationId:object5["targetOperationId"]}}__name(parseOperation,"parseOperation");var ManagedShellRuntime=class{constructor(registry){this.registry=registry}static{__name(this,"ManagedShellRuntime")}async control(runtimeSessionId,value){const operation=parseOperation(value);const unitName=shellUnitNameOf(operation.targetOperationId);const registered=this.registry.describe(unitName);if(registered&®istered.sessionId===runtimeSessionId){if(operation.kind==="shell-status"){return{operationId:operation.targetOperationId,state:"running",unitName}}const receipt2=await this.registry.terminate(unitName,5e3);if(!receipt2||receipt2.evidence===null){return{operationId:operation.targetOperationId,state:"unknown"}}return{operationId:operation.targetOperationId,state:"exited",unitName,evidence:receipt2.evidence}}const finished=this.registry.describeFinished(unitName);if(finished&&finished.sessionId===runtimeSessionId&&finished.receipt.evidence!==null){return{operationId:operation.targetOperationId,state:"exited",unitName,evidence:finished.receipt.evidence}}return{operationId:operation.targetOperationId,state:"unknown"}}};init_esbuild_shims();var MANAGED_SHELL_WORKER_ROUTE=Object.freeze({key:"shell",method:"POST",path:MANAGED_SHELL_ROUTE,protocolVersion:1,requestBodyLimitBytes:16*1024,responseBodyLimitBytes:64*1024,cacheControl:"no-store"});function registerManagedShellRoutes(app,identity,runtime){app.post(MANAGED_SHELL_ROUTE,managedRuntimeNoStore,authorizeManagedRuntime(identity),managedRuntimeJsonBody(MANAGED_SHELL_WORKER_ROUTE.requestBodyLimitBytes),async(req,res)=>{const body2=req.body;if(!body2||typeof body2!=="object"||Array.isArray(body2)){res.status(400).json({code:"managed_shell_invalid"});return}const request=body2;if(Object.keys(request).sort().join(",")!=="operation,protocolVersion,runtimeSessionId"||request["protocolVersion"]!==1||typeof request["runtimeSessionId"]!=="string"||!request["runtimeSessionId"]){res.status(400).json({code:"managed_shell_invalid"});return}try{const operation=await runtime.control(request["runtimeSessionId"],request["operation"]);res.json({protocolVersion:1,runtimeSessionId:request["runtimeSessionId"],operation})}catch(error){const code=error instanceof ManagedShellError?error.code:"managed_shell_unavailable";res.status(code==="managed_shell_invalid"?400:409).json({code})}},handleManagedRuntimeJsonError)}__name(registerManagedShellRoutes,"registerManagedShellRoutes");init_esbuild_shims();init_esbuild_shims();var MANAGED_MONITOR_ROUTE="/internal/managed-runtime/v3/monitors";function monitorUnitNameOf(targetOperationId){return`qwen-mon-${targetOperationId.replace(/[^a-zA-Z0-9._-]/g,"-")}`}__name(monitorUnitNameOf,"monitorUnitNameOf");var ManagedMonitorError=class extends Error{constructor(code,message){super(message);this.code=code;this.name="ManagedMonitorError"}static{__name(this,"ManagedMonitorError")}};var KEYS2=["kind","operationId","sessionKey","targetOperationId"];function parseOperation2(value){if(!value||typeof value!=="object"||Array.isArray(value)){throw new ManagedMonitorError("managed_monitor_invalid","Monitor operation is invalid.")}const object5=value;if(Object.keys(object5).sort().join(",")!==[...KEYS2].sort().join(",")){throw new ManagedMonitorError("managed_monitor_invalid","Monitor operation is invalid.")}const kind=object5["kind"];if(kind!=="monitor-status"&&kind!=="monitor-stop"){throw new ManagedMonitorError("managed_monitor_invalid","Monitor operation is invalid.")}const sessionKey=object5["sessionKey"];if(!sessionKey||typeof sessionKey!=="object"||typeof sessionKey["tenantId"]!=="string"||typeof sessionKey["sessionId"]!=="string"){throw new ManagedMonitorError("managed_monitor_invalid","Monitor operation scope is invalid.")}for(const key of["operationId","targetOperationId"]){const field=object5[key];if(typeof field!=="string"||!field||field.length>512){throw new ManagedMonitorError("managed_monitor_invalid",`Monitor operation ${key} is invalid.`)}}return{kind,operationId:object5["operationId"],targetOperationId:object5["targetOperationId"]}}__name(parseOperation2,"parseOperation");var ManagedMonitorRuntime=class{constructor(registry){this.registry=registry}static{__name(this,"ManagedMonitorRuntime")}async control(runtimeSessionId,value){const operation=parseOperation2(value);const unitName=monitorUnitNameOf(operation.targetOperationId);const registered=this.registry.describe(unitName);if(registered&®istered.sessionId===runtimeSessionId){if(operation.kind==="monitor-status"){return{operationId:operation.targetOperationId,state:"running",unitName}}const receipt2=await this.registry.terminate(unitName,5e3);if(!receipt2||receipt2.evidence===null){return{operationId:operation.targetOperationId,state:"unknown"}}return{operationId:operation.targetOperationId,state:"exited",unitName,evidence:receipt2.evidence}}const finished=this.registry.describeFinished(unitName);if(finished&&finished.sessionId===runtimeSessionId&&finished.receipt.evidence!==null){return{operationId:operation.targetOperationId,state:"exited",unitName,evidence:finished.receipt.evidence}}return{operationId:operation.targetOperationId,state:"unknown"}}};init_esbuild_shims();var MANAGED_MONITOR_WORKER_ROUTE=Object.freeze({key:"monitor",method:"POST",path:MANAGED_MONITOR_ROUTE,protocolVersion:1,requestBodyLimitBytes:16*1024,responseBodyLimitBytes:64*1024,cacheControl:"no-store"});function registerManagedMonitorRoutes(app,identity,runtime){app.post(MANAGED_MONITOR_ROUTE,managedRuntimeNoStore,authorizeManagedRuntime(identity),managedRuntimeJsonBody(MANAGED_MONITOR_WORKER_ROUTE.requestBodyLimitBytes),async(req,res)=>{const body2=req.body;if(!body2||typeof body2!=="object"||Array.isArray(body2)){res.status(400).json({code:"managed_monitor_invalid"});return}const request=body2;if(Object.keys(request).sort().join(",")!=="operation,protocolVersion,runtimeSessionId"||request["protocolVersion"]!==1||typeof request["runtimeSessionId"]!=="string"||!request["runtimeSessionId"]){res.status(400).json({code:"managed_monitor_invalid"});return}try{const operation=await runtime.control(request["runtimeSessionId"],request["operation"]);res.json({protocolVersion:1,runtimeSessionId:request["runtimeSessionId"],operation})}catch(error){const code=error instanceof ManagedMonitorError?error.code:"managed_monitor_unavailable";res.status(code==="managed_monitor_invalid"?400:409).json({code})}},handleManagedRuntimeJsonError)}__name(registerManagedMonitorRoutes,"registerManagedMonitorRoutes");var MANAGED_CONTEXT_WORKER_ROUTES=Object.freeze([...MANAGED_CONTEXT_ROUTES,WORKSPACE_ACTIVATION_ROUTE,MANAGED_MCP_WORKER_ROUTE,MANAGED_HOOK_WORKER_ROUTE,MANAGED_SHELL_WORKER_ROUTE,MANAGED_MONITOR_WORKER_ROUTE,MANAGED_RUNTIME_PROVIDER_ROUTE,...OWNED_MANAGED_RUNTIME_ROUTES.filter(route=>route.key!=="attest")]);var REFUSAL_MESSAGES=Object.freeze({managed_runtime_attestation_invalid:"Managed Runtime attestation request is invalid.",managed_runtime_identity_conflict:"Managed Runtime immutable identity conflicts.",managed_context_conflict:"Managed context conflicts with an earlier installation.",managed_context_unavailable:"Managed context directory is unavailable."});var ManagedContextMount=class{static{__name(this,"ManagedContextMount")}#mountRoot;#root;constructor(mountRoot){this.#mountRoot=mountRoot}get isAvailable(){return true}async resolve(cwdRelative){if(!isHostAbsolute(this.#mountRoot)){return void 0}let rootStats;let directory;try{const root=await fs3.realpath(this.#mountRoot);rootStats=await fs3.stat(root,{bigint:true});directory=path4.join(root,...cwdRelative.split("/"));if(await fs3.realpath(directory)!==directory||!(await fs3.stat(directory)).isDirectory()){return void 0}await fs3.access(directory,constants2.R_OK|constants2.X_OK)}catch{return void 0}const pinned=this.#root;if(pinned===void 0){this.#root={dev:rootStats.dev,ino:rootStats.ino}}else if(pinned.dev!==rootStats.dev||pinned.ino!==rootStats.ino){return void 0}return directory}async rootDirectory(){if(!isHostAbsolute(this.#mountRoot)){return void 0}try{const root=await fs3.realpath(this.#mountRoot);const stats=await fs3.stat(root,{bigint:true});const pinned=this.#root;if(pinned!==void 0&&(pinned.dev!==stats.dev||pinned.ino!==stats.ino)){return void 0}return root}catch{return void 0}}};async function siblingDirectory(mount,cwdRelative){const resolved=await mount.resolve(cwdRelative);if(resolved!==void 0)return resolved;const root=await mount.rootDirectory();if(root===void 0)return void 0;const occupied=path4.join(root,...cwdRelative.split("/"));try{return await realpathDeepestExisting(occupied)}catch{return occupied}}__name(siblingDirectory,"siblingDirectory");function isHostAbsolute(mountRoot){return process.platform==="win32"?/^(?:[A-Za-z]:[\\/]|\\\\)/.test(mountRoot):mountRoot.startsWith("/")}__name(isHostAbsolute,"isHostAbsolute");function selectShellCapturePublisher(remotePublishers,remotePublisher){return{get hasInstalledPublication(){return remotePublishers.hasInstalledPublication||remotePublisher.hasInstalledPublication},async prepare(request){if(request.capture.background===true){if(!remotePublishers.hasSession(request.reference.sessionId))throw new Error("Background captures require their Session publisher.");return{...await remotePublishers.prepare(request),publisher:remotePublishers}}if(remotePublisher.hasExecution(request.capture.executionCallId)){return{...await remotePublisher.prepare(request),publisher:remotePublisher}}const selected=remotePublishers.hasSession(request.reference.sessionId)?remotePublishers:remotePublisher;return{...await selected.prepare(request),publisher:selected}}}}__name(selectShellCapturePublisher,"selectShellCapturePublisher");function registerManagedContextRoutes(app,bootDocument,capturePublisher,remotePublishers,mount=new ManagedContextMount(bootDocument.mountRoot)){const boot=parseManagedContextBoot(bootDocument);if(boot.capabilityDigest===CSI_FILES_RETIREMENT_CAPABILITY_DIGEST)throw new Error("Private CSI file profile requires its dedicated worker.");const installations=new ManagedContextInstallations(boot);const activations=new WorkspaceActivations;const requiresActivation=boot.capabilityDigest===WORKSPACE_CAPABILITY_DIGEST;const admissionOpen=__name(()=>executor.isAdmissionOpen,"admissionOpen");const remotePublisher=!capturePublisher&&requiresActivation?new RemoteShellResultPublisher:void 0;const publisher=capturePublisher??(remotePublishers&&remotePublisher?selectShellCapturePublisher(remotePublishers,remotePublisher):remotePublishers??remotePublisher);remotePublisher?.registerInstallRoute(app,boot,admissionOpen);const[attestRoute,contextRoute]=MANAGED_CONTEXT_ROUTES;app.post(attestRoute.path,managedRuntimeNoStore,authorizeManagedRuntime(boot),managedRuntimeJsonBody(attestRoute.requestBodyLimitBytes),(req,res)=>{send(res,checkManagedContextAttestation(req.body,boot))},handleManagedRuntimeJsonError);app.post(contextRoute.path,managedRuntimeNoStore,authorizeManagedRuntime(boot),managedRuntimeJsonBody(contextRoute.requestBodyLimitBytes),async(req,res)=>{send(res,await installations.install(req.body,async binding=>await mount.resolve(binding.cwdRelative)!==void 0,admissionOpen))},handleManagedRuntimeJsonError);const mcp=new ManagedMcpRuntime(boot,async runtimeSessionId=>{if(!admissionOpen()||!mount.isAvailable||!requiresActivation||!activations.isActive(runtimeSessionId))return void 0;const binding=installations.installed(runtimeSessionId);const directory=binding&&await mount.resolve(binding.cwdRelative);return admissionOpen()&&mount.isAvailable&&activations.isActive(runtimeSessionId)?directory:void 0},loadManagedMcpManifest(process.env["QWEN_MANAGED_MCP_CONFIG"]));registerManagedMcpRoutes(app,boot,mcp);const hooks=new ManagedHookRuntime(boot,async runtimeSessionId=>{if(!admissionOpen()||!mount.isAvailable||!requiresActivation||!activations.isActive(runtimeSessionId))return void 0;const binding=installations.installed(runtimeSessionId);const directory=binding&&await mount.resolve(binding.cwdRelative);return admissionOpen()&&mount.isAvailable&&activations.isActive(runtimeSessionId)?directory:void 0},loadManagedHookManifest(process.env["QWEN_MANAGED_HOOK_CONFIG"]));registerManagedHookRoutes(app,boot,hooks);const cgroupRoot=process.env["QWEN_MANAGED_HOOK_CGROUP_ROOT"];const backgroundSupervisor=cgroupRoot?ManagedChildRunSupervisor.create({cgroupRoot}):void 0;const backgroundRegistry=new ManagedBackgroundShellRegistry;const monitorRegistry=new ManagedMonitorRegistry;const executor=new ManagedToolExecutor(async reference2=>{const isActive=__name(()=>admissionOpen()&&mount.isAvailable&&(!requiresActivation||activations.isActive(reference2.sessionId)),"isActive");if(!isActive()){return void 0}const binding=installations.installed(reference2.sessionId);const directory=binding&&await mount.resolve(binding.cwdRelative);if(directory===void 0){return void 0}const sessionId=runtimeSessionKey(boot.runtimeInstanceId,reference2.sessionId);return{...sessionIdContext.run(sessionId,()=>createManagedToolSet(directory,sessionId,requiresActivation?boot.mountRoot:directory)),isActive}},publisher,mcp,hooks,async(sessionId,realPath,ownDirectory)=>{const contains=__name((directory,target)=>{const relative=path4.relative(directory,target);return relative!==".."&&!relative.startsWith(`..${path4.sep}`)&&!path4.isAbsolute(relative)},"contains");const root=await mount.rootDirectory();const ownEstate=contains(ownDirectory,realPath)&&root!==void 0&&ownDirectory!==root;for(const[otherId,binding]of installations.bindings()){if(otherId===sessionId)continue;const directory=await siblingDirectory(mount,binding.cwdRelative);if(directory===void 0){if(ownEstate&&await mount.rootDirectory()===root)continue;return true}if(root!==void 0&&directory===root)continue;if(!contains(directory,realPath))continue;if(!ownEstate||directory!==ownDirectory&&contains(ownDirectory,directory)){return true}}return false},backgroundSupervisor,backgroundRegistry,monitorRegistry);registerManagedShellRoutes(app,boot,new ManagedShellRuntime(backgroundRegistry));registerManagedMonitorRoutes(app,boot,new ManagedMonitorRuntime(monitorRegistry));registerManagedRuntimeProviderRoute(app,boot,executor,async sessionId=>{const binding=installations.installed(sessionId);if(!requiresActivation||binding!==void 0&&binding.contextConfigRef!==WORKSPACE_CONTEXT_CONFIG_REF){throw new ManagedRuntimeProviderProtocolError("Managed Runtime provider configuration is unsupported.",501,"managed_runtime_provider_unsupported")}const isActive=__name(()=>!executor.isAdmissionSealed&&mount.isAvailable&&activations.isActive(sessionId),"isActive");if(!isActive())return void 0;const directory=binding&&await mount.resolve(binding.cwdRelative);return directory===void 0?void 0:{directory,workspaceRoot:boot.mountRoot,preapproved:true,isActive}});activations.register(app,boot,installations,executor);registerManagedRuntimeToolRoutes(app,boot,executor);if(publisher){registerManagedRuntimeToolV3Routes(app,boot,executor)}remotePublishers?.register(app,boot,sessionId=>admissionOpen()&&mount.isAvailable&&requiresActivation&&activations.isActive(sessionId)&&installations.installed(sessionId)!==void 0);return executor}__name(registerManagedContextRoutes,"registerManagedContextRoutes");function runtimeSessionKey(runtimeInstanceId,sessionId){const digest2=createHash6("sha256").update(sessionId).digest("hex");return`${runtimeInstanceId}.${digest2.slice(0,32)}`}__name(runtimeSessionKey,"runtimeSessionKey");function send(res,outcome){if(outcome.status===200){res.status(200).json(outcome.body);return}res.status(outcome.status).json({code:outcome.code,error:REFUSAL_MESSAGES[outcome.code]})}__name(send,"send");init_esbuild_shims();import{constants as constants4,promises as fs5}from"node:fs";import path5 from"node:path";init_esbuild_shims();import{constants as constants3,promises as fs4}from"node:fs";var UNAVAILABLE="Managed CSI root directory is unavailable.";var ManagedCsiRootDirectoryCleanupError=class extends AggregateError{static{__name(this,"ManagedCsiRootDirectoryCleanupError")}constructor(openError,closeError){super([openError,closeError],"Managed CSI root directory cleanup failed.");this.name="ManagedCsiRootDirectoryCleanupError"}};var ManagedCsiRootDirectory=class _ManagedCsiRootDirectory{constructor(root,handle,stats){this.root=root;this.handle=handle;this.rootDevice=stats.dev.toString();this.rootInode=stats.ino.toString()}static{__name(this,"ManagedCsiRootDirectory")}rootDevice;rootInode;fenced=false;operations=new Set;closing;static async open(root,device){if(typeof constants3.O_DIRECTORY!=="number"||typeof constants3.O_NOFOLLOW!=="number")throw new Error(UNAVAILABLE);const before=await namedDirectory(root);if(before.dev.toString()!==device)throw new Error(UNAVAILABLE);const handle=await fs4.open(root,constants3.O_RDONLY|constants3.O_DIRECTORY|constants3.O_NOFOLLOW);let directory;try{const stats=await handle.stat({bigint:true});if(!sameDirectory(before,stats))throw new Error(UNAVAILABLE);directory=new _ManagedCsiRootDirectory(root,handle,stats);await directory.verify();return directory}catch(error){try{await(directory?directory.close():handle.close())}catch(closeError){throw new ManagedCsiRootDirectoryCleanupError(error,closeError)}throw error}}verify(){return this.withVerifiedDirectory(async()=>{})}get isAvailable(){return!this.fenced}async withVerifiedDirectory(operation){if(this.fenced)throw new Error(UNAVAILABLE);let complete;const pending=new Promise(resolve=>{complete=resolve});this.operations.add(pending);try{await this.inspect();try{return await operation(this.handle)}finally{await this.inspect()}}finally{this.operations.delete(pending);complete()}}async inspect(){if(this.fenced)throw new Error(UNAVAILABLE);try{const before=await namedDirectory(this.root);const descriptor=await this.handle.stat({bigint:true});const after=await namedDirectory(this.root);if(this.fenced||!sameDirectory(before,descriptor)||!sameDirectory(after,descriptor)||descriptor.dev.toString()!==this.rootDevice||descriptor.ino.toString()!==this.rootInode)throw new Error(UNAVAILABLE)}catch(error){void this.close().catch(()=>{});throw error}}close(){this.fenced=true;this.closing??=(async()=>{await Promise.all(this.operations);await this.handle.close()})();return this.closing}};async function namedDirectory(root){if(await fs4.realpath(root)!==root)throw new Error(UNAVAILABLE);const stats=await fs4.lstat(root,{bigint:true});if(!stats.isDirectory()||stats.dev<0n||stats.dev>0xffffffffffffffffn||stats.ino<=0n||stats.ino>0xffffffffffffffffn)throw new Error(UNAVAILABLE);return stats}__name(namedDirectory,"namedDirectory");function sameDirectory(left,right){return right.isDirectory()&&left.dev===right.dev&&left.ino===right.ino}__name(sameDirectory,"sameDirectory");var UNAVAILABLE2="Managed CSI mount is unavailable.";var MOUNTINFO_LIMIT=1024*1024;function parseManagedCsiMount(mountinfo,mountRoot){if(!isMountRoot2(mountRoot)||Buffer.byteLength(mountinfo)>MOUNTINFO_LIMIT||mountinfo.includes("\r")||mountinfo.includes("\0")){throw new Error(UNAVAILABLE2)}let observed;for(const line of mountinfo.split("\n")){if(!line)continue;const fields=line.split(" ");const separator=fields.indexOf("-");if(separator<6||fields.length!==separator+4){throw new Error(UNAVAILABLE2)}const target=unescapeField(fields[4]);if(target.startsWith(`${mountRoot}/`))throw new Error(UNAVAILABLE2);if(target!==mountRoot)continue;const source=unescapeField(fields[separator+2]);if(observed!==void 0||!/^[1-9][0-9]{0,9}$/.test(fields[0])||!/^(?:0|[1-9][0-9]{0,9}):(?:0|[1-9][0-9]{0,9})$/.test(fields[2])||BigInt(fields[0])>0xffffffffn||unescapeField(fields[3])!=="/"||fields[separator+1]!=="ext4"||!/^\/dev\/nvme(?:0|[1-9][0-9]*)n[1-9][0-9]*$/.test(source)||!writable(fields[5])||!writable(fields[separator+3])){throw new Error(UNAVAILABLE2)}observed=Object.freeze({mountId:fields[0],device:fields[2],source});try{linuxDeviceNumber(observed.device)}catch{throw new Error(UNAVAILABLE2)}}if(observed===void 0)throw new Error(UNAVAILABLE2);return observed}__name(parseManagedCsiMount,"parseManagedCsiMount");var ManagedCsiMount=class extends ManagedContextMount{static{__name(this,"ManagedCsiMount")}#mountRoot;#serial;#pinned;#closed=false;#observations=new Set;#directory;#closing;#closeFailure;constructor(mountRoot,trustedDiskSerial){super(mountRoot);if(!isMountRoot2(mountRoot)||!/^[A-Za-z0-9._:-]{1,128}$/.test(trustedDiskSerial)){throw new Error(UNAVAILABLE2)}this.#mountRoot=mountRoot;this.#serial=trustedDiskSerial}get isAvailable(){return!this.#closed&&this.#pinned!==void 0}async observe(){return this.withVerifiedRoot(async(_handle,receipt2)=>receipt2)}async withVerifiedRoot(operation){if(this.#closed||process.platform!=="linux"){void this.close().catch(()=>{});throw new Error(UNAVAILABLE2)}let complete;const pending=new Promise(resolve=>{complete=resolve});this.#observations.add(pending);try{const before=await this.kernelObservation();let directory;try{this.#directory??=ManagedCsiRootDirectory.open(this.#mountRoot,linuxDeviceNumber(before.device));directory=await this.#directory}catch{void this.close().catch(()=>{});throw new Error(UNAVAILABLE2)}try{return await directory.withVerifiedDirectory(async handle=>{const receipt2=await this.inspect(before,directory);try{return await operation(handle,receipt2)}finally{await this.inspect(before,directory)}})}catch(error){if(!directory.isAvailable)void this.close().catch(()=>{});throw error}}finally{this.#observations.delete(pending);complete()}}close(){this.#closed=true;this.#closing??=(async()=>{await Promise.all(this.#observations);try{await this.#directory?.then(directory=>directory.close(),error=>{if(error instanceof ManagedCsiRootDirectoryCleanupError)throw error})}catch(error){if(this.#closeFailure)throw new AggregateError([this.#closeFailure,error],UNAVAILABLE2);throw error}if(this.#closeFailure)throw this.#closeFailure})();return this.#closing}async resolve(cwdRelative){try{if(normalizeWorkspaceRelativePath(cwdRelative)!==cwdRelative)return void 0;return await this.withVerifiedRoot(async(root,receipt2)=>{const children=[];try{let parent=root;for(const component of cwdRelative==="."?[]:cwdRelative.split("/")){const address=`/proc/self/fd/${parent.fd}/${component}`;const before=await fs5.lstat(address,{bigint:true});const handle=await fs5.open(address,constants4.O_RDONLY|constants4.O_DIRECTORY|constants4.O_NOFOLLOW);const child={handle,address,stats:before};children.push(child);if(!sameDirectory2(before,await handle.stat({bigint:true}),receipt2.rootDevice))throw new Error(UNAVAILABLE2);parent=handle}await fs5.access(`/proc/self/fd/${parent.fd}`,constants4.R_OK|constants4.X_OK);return cwdRelative==="."?this.#mountRoot:path5.join(this.#mountRoot,...cwdRelative.split("/"))}finally{try{await verifyChildren(children,receipt2.rootDevice)}finally{await this.closeChildren(children.map(({handle})=>handle).reverse())}}})}catch{return void 0}}async rootDirectory(){try{return await this.withVerifiedRoot(async()=>this.#mountRoot)}catch{return void 0}}async closeChildren(handles){const results=await Promise.allSettled(handles.map(async handle=>handle.close()));const errors=results.flatMap(result=>result.status==="rejected"?[result.reason]:[]);if(errors.length>0){this.#closeFailure??=new AggregateError(errors,UNAVAILABLE2);void this.close().catch(()=>{});throw this.#closeFailure}}async kernelObservation(){try{const observation=parseManagedCsiMount(await readBounded("/proc/self/mountinfo",MOUNTINFO_LIMIT),this.#mountRoot);const serial=await readBounded(`/sys/dev/block/${observation.device}/device/serial`,256);if(this.#closed||serial.replace(/\n$/,"")!==this.#serial)throw new Error(UNAVAILABLE2);return observation}catch{void this.close().catch(()=>{});throw new Error(UNAVAILABLE2)}}async inspect(before,directory){const after=await this.kernelObservation();const identity=JSON.stringify([before.mountId,before.device,before.source,directory.rootDevice,directory.rootInode]);if(this.#closed||directory.rootDevice!==linuxDeviceNumber(before.device)||JSON.stringify(before)!==JSON.stringify(after)||this.#pinned!==void 0&&this.#pinned!==identity){void this.close().catch(()=>{});throw new Error(UNAVAILABLE2)}this.#pinned=identity;return Object.freeze({...before,diskSerial:this.#serial,rootDevice:directory.rootDevice,rootInode:directory.rootInode})}};async function verifyChildren(children,device){for(const child of children){if(!sameDirectory2(child.stats,await fs5.lstat(child.address,{bigint:true}),device))throw new Error(UNAVAILABLE2)}}__name(verifyChildren,"verifyChildren");function sameDirectory2(left,right,device){return left.isDirectory()&&right.isDirectory()&&left.dev.toString()===device&&right.dev===left.dev&&right.ino===left.ino}__name(sameDirectory2,"sameDirectory");function isMountRoot2(value){return value.startsWith("/")&&value.length<=2048&&!value.includes("\\")&&!Array.from(value).some(char=>char.charCodeAt(0)<=31||char.charCodeAt(0)>=127&&char.charCodeAt(0)<=159)&&!/[\ud800-\udfff]/u.test(value)&&value.slice(1).split("/").every(part=>part!==""&&part!=="."&&part!=="..")}__name(isMountRoot2,"isMountRoot");function writable(options){const fields=options.split(",");return fields.filter(field=>field==="rw").length===1&&!fields.includes("ro")}__name(writable,"writable");function unescapeField(value){if(/\\(?!040|011|012|134)/.test(value))throw new Error(UNAVAILABLE2);return value.replace(/\\(040|011|012|134)/g,(_,octal)=>String.fromCharCode(Number.parseInt(octal,8)))}__name(unescapeField,"unescapeField");async function readBounded(file,limit){const handle=await fs5.open(file,"r");try{const chunks=[];let size=0;while(size<=limit){const buffer=Buffer.alloc(Math.min(8192,limit+1-size));const{bytesRead}=await handle.read(buffer,0,buffer.length,null);if(bytesRead===0){return new TextDecoder("utf-8",{fatal:true}).decode(Buffer.concat(chunks))}chunks.push(buffer.subarray(0,bytesRead));size+=bytesRead}throw new Error(UNAVAILABLE2)}finally{await handle.close()}}__name(readBounded,"readBounded");init_esbuild_shims();import{isDeepStrictEqual as isDeepStrictEqual4}from"node:util";var MANAGED_CSI_FILE_PROTOCOL="managed-csi/2";var MANAGED_CSI_FILE_PREFIX="/internal/managed-runtime/csi/v2";var MANAGED_CSI_FILE_ROUTES=Object.freeze(["context-attest","context","attest","drain"].map(name=>Object.freeze({method:"POST",path:`${MANAGED_CSI_FILE_PREFIX}/${name}`})));function parseManagedCsiFileJson(bytes,limit){if(bytes.byteLength>limit)throw new Error("Invalid CSI file JSON.");const text2=new TextDecoder("utf-8",{fatal:true}).decode(bytes);parseManagedSessionRecordJson(text2,limit);return JSON.parse(text2,(_key,value,context)=>{if(typeof value==="number"&&(!Number.isSafeInteger(value)||context?.source===void 0||!/^(?:0|[1-9][0-9]*)$/.test(context.source)))throw new Error("Invalid CSI file JSON.");return value})}__name(parseManagedCsiFileJson,"parseManagedCsiFileJson");function parseManagedCsiFileBoot(value){try{const authorityBoot=value!==null&&typeof value==="object"&&"version"in value&&value.version===5;const boot=closed5(value,[...authorityBoot?["authority"]:[],"context","identity","managedCsi","storage","type","version"]);const identity=closed5(boot["identity"],["capabilityDigest","profile","sessionId"]);const data=parseManagedCsiBoot({type:"boot",version:3,managedCsi:MANAGED_CSI_PROTOCOL,context:boot["context"],storage:boot["storage"]});if(boot["type"]!=="boot"||boot["version"]!==4&&!authorityBoot||boot["managedCsi"]!==MANAGED_CSI_FILE_PROTOCOL||identity["profile"]!=="csi-files-retirement/1"||identity["capabilityDigest"]!==CSI_FILES_RETIREMENT_CAPABILITY_DIGEST||typeof identity["sessionId"]!=="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(identity["sessionId"])||data.context.isolationClass!=="session"||data.context.capabilityDigest!==identity["capabilityDigest"])throw new Error;const fields={type:"boot",managedCsi:MANAGED_CSI_FILE_PROTOCOL,identity:Object.freeze(identity),context:data.context,storage:data.storage};return authorityBoot?Object.freeze({...fields,version:5,authority:readManagedCsiNativeAuthority(boot["authority"])}):Object.freeze({...fields,version:4})}catch{throw new Error("Managed CSI file boot document is invalid.")}}__name(parseManagedCsiFileBoot,"parseManagedCsiFileBoot");function readManagedCsiNativeAuthority(value){const authority=closed5(value,["origin","protocolVersion"]);const origin=authority["origin"];if(authority["protocolVersion"]!==1||typeof origin!=="string"||origin.length>2048)throw new Error("Managed CSI authority origin is invalid.");const url=resolveManagedRuntimeBrokerBaseUrl(origin);const hostname=url.hostname;if(url.origin!==origin||/(^|\.)xn--/.test(hostname)||!hostname.startsWith("[")&&!/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*$/.test(hostname)||!hostname.startsWith("[")&&hostname.includes(".")&&!/^\d+\.\d+\.\d+\.\d+$/.test(hostname)&&!/^[a-z]/.test(hostname.split(".").at(-1)??"")||url.port!==""&&Number(url.port)===0)throw new Error("Managed CSI authority origin is not canonical.");return Object.freeze({protocolVersion:1,origin})}__name(readManagedCsiNativeAuthority,"readManagedCsiNativeAuthority");function dataBoot(boot){return{type:"boot",version:3,managedCsi:MANAGED_CSI_PROTOCOL,context:boot.context,storage:boot.storage}}__name(dataBoot,"dataBoot");function createManagedCsiFileReady(boot,port){return Object.freeze({type:"ready",version:boot.version,managedCsi:MANAGED_CSI_FILE_PROTOCOL,identity:boot.identity,context:createManagedContextReady(boot.context,port)})}__name(createManagedCsiFileReady,"createManagedCsiFileReady");function wrapManagedCsiFileContext(boot,context){return Object.freeze({protocolVersion:2,managedCsi:MANAGED_CSI_FILE_PROTOCOL,identity:boot.identity,context})}__name(wrapManagedCsiFileContext,"wrapManagedCsiFileContext");function readManagedCsiFileContext(value,boot){const body2=closed5(value,["context","identity","managedCsi","protocolVersion"]);checkIdentity(body2,boot);return body2["context"]}__name(readManagedCsiFileContext,"readManagedCsiFileContext");function createManagedCsiFileAttestationRequest(boot){return{...createManagedCsiAttestationRequest(dataBoot(boot)),protocolVersion:2,managedCsi:MANAGED_CSI_FILE_PROTOCOL,identity:boot.identity}}__name(createManagedCsiFileAttestationRequest,"createManagedCsiFileAttestationRequest");function validateManagedCsiFileAttestationRequest(value,boot){if(!isDeepStrictEqual4(value,createManagedCsiFileAttestationRequest(boot)))throw new Error("CSI file identity conflicts.")}__name(validateManagedCsiFileAttestationRequest,"validateManagedCsiFileAttestationRequest");function validateManagedCsiFileAttestationResponse(value,boot,pod){const body2=closed5(value,["context","identity","managedCsi","mount","pod","protocolVersion","storage"]);checkIdentity(body2,boot);const{identity:_identity,...data}=body2;validateManagedCsiAttestationResponse({...data,protocolVersion:1,managedCsi:MANAGED_CSI_PROTOCOL},dataBoot(boot),pod)}__name(validateManagedCsiFileAttestationResponse,"validateManagedCsiFileAttestationResponse");function readManagedCsiFileDrain(value,boot,pod){const body2=closed5(value,["context","identity","managedCsi","operation","pod","protocolVersion","retirementId","storage"]);checkIdentity(body2,boot);const{identity:_identity,...data}=body2;return parseManagedCsiDrainRequest({...data,protocolVersion:1,managedCsi:MANAGED_CSI_PROTOCOL},dataBoot(boot),pod)}__name(readManagedCsiFileDrain,"readManagedCsiFileDrain");function checkIdentity(body2,boot){if(body2["protocolVersion"]!==2||body2["managedCsi"]!==MANAGED_CSI_FILE_PROTOCOL||!isDeepStrictEqual4(body2["identity"],boot.identity))throw new Error("CSI file identity conflicts.")}__name(checkIdentity,"checkIdentity");function closed5(value,keys){if(!value||typeof value!=="object"||Array.isArray(value)||!isDeepStrictEqual4(Object.keys(value).sort(),keys))throw new Error;return{...value}}__name(closed5,"closed");init_esbuild_shims();var import_express=__toESM(require_express(),1);import{createHash as createHash10}from"node:crypto";import{isDeepStrictEqual as isDeepStrictEqual8}from"node:util";import{createServer}from"node:http";init_esbuild_shims();import{isDeepStrictEqual as isDeepStrictEqual5}from"node:util";init_esbuild_shims();import{createHash as createHash7,randomUUID as randomUUID5}from"node:crypto";import{constants as constants5,promises as fs6}from"node:fs";import path6 from"node:path";var PREFIX=".qwen-csi-file-history";var UNAVAILABLE3="Managed CSI file backend is unavailable.";var DIR_FLAGS=constants5.O_RDONLY|constants5.O_DIRECTORY|constants5.O_NOFOLLOW;var UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;var ManagedCsiFileBackend=class _ManagedCsiFileBackend{constructor(mount,directory,ownerSessionId){this.mount=mount;this.directory=directory;this.ownerSessionId=ownerSessionId;this.textFileIo={inspect:__name((file,signal)=>this.inspect(file,signal),"inspect"),withMutation:__name((file,signal,operation)=>this.withMutation(file,signal,operation),"withMutation")}}static{__name(this,"ManagedCsiFileBackend")}textFileIo;#directories=[];#directoryHandles=[];#attempts=new Map;#pending=new Set;#inventoryTail=Promise.resolve();#binding;#receipt;#closed=false;#failure;#closing;static async open(mount,ownerSessionId){if(process.platform!=="linux"||!UUID.test(ownerSessionId))throw new Error(UNAVAILABLE3);const directory=await mount.rootDirectory();if(!directory)throw new Error(UNAVAILABLE3);const backend=new _ManagedCsiFileBackend(mount,directory,ownerSessionId);try{await backend.run(async()=>{});return backend}catch(error){try{await backend.close()}catch(closeError){throw new AggregateError([error,closeError],UNAVAILABLE3)}throw error}}getDrainInspection(){return{pendingOperations:this.#pending.size,blocked:this.#failure!==void 0,closed:this.#closed}}async observeRetained(){if(this.#pending.size)throw new Error("Retained observation requires an idle backend.");return this.run(async()=>{const retainedBackups=[];for(const name of[...this.#attempts.keys()].sort()){const attempt=this.#attempts.get(name);await this.authenticate(attempt);retainedBackups.push({...attempt.pin})}if(this.#pending.size!==1)throw new Error("Retained observation requires an idle backend.");const directory=this.#directories[1];return{backupDirectory:{volumeDevice:this.#receipt.rootDevice,volumeInode:this.#receipt.rootInode,directoryDevice:directory.stats.dev.toString(),directoryInode:directory.stats.ino.toString()},retainedBackups}})}close(){this.#closed=true;this.#closing??=(async()=>{await Promise.all(this.#pending);const handles=[...[...this.#attempts.values()].flatMap(attempt=>attempt.handle?[attempt.handle]:[]),...this.#directoryHandles.slice().reverse()];const results=await Promise.allSettled(handles.map(async handle=>handle.close()));const errors=results.flatMap(result=>result.status==="rejected"?[result.reason]:[]);if(this.#failure)errors.unshift(this.#failure);if(errors.length)throw new AggregateError(errors,UNAVAILABLE3)})();return this.#closing}withWorkingFile(file,operation){const components=this.components(file);return this.run((root,receipt2)=>this.working(root,receipt2,components,false,async working=>operation(working.leaf?await this.source(working.leaf):null)))}withBackupFile(name,operation){if(!validLeaf(name))return Promise.reject(new Error("Invalid retained backup name."));return this.run(async()=>{const attempt=this.#attempts.get(name);if(!attempt)throw this.fault(new Error("Unknown retained backup."));await this.authenticate(attempt);try{return await operation(await this.backupSource(attempt))}finally{await this.authenticate(attempt)}})}createBackup(file,version){const components=this.components(file);if(!Number.isSafeInteger(version)||version<1)return Promise.reject(new Error("Invalid backup version."));return this.run((root,receipt2)=>this.working(root,receipt2,components,false,async working=>{if(!working.leaf)return{backupFileName:null,version,backupTime:new Date};const source=await this.source(working.leaf);const name=`${randomUUID5()}@v${version}`;const attempt={name};const address=this.backupAddress(name);try{await this.withInventory(async()=>{this.#attempts.set(name,attempt);attempt.handle=await fs6.open(address,constants5.O_RDWR|constants5.O_CREAT|constants5.O_EXCL|constants5.O_NOFOLLOW|constants5.O_NONBLOCK,384);attempt.stats=await attempt.handle.stat({bigint:true});this.requireFile(attempt.stats,receipt2.rootDevice)});const handle=attempt.handle;const digest2=createHash7("sha256");const bytes=Buffer.allocUnsafe(64*1024);let position=0;while(position<source.stats.size){const{bytesRead}=await source.fileHandle.read(bytes,0,Math.min(bytes.length,source.stats.size-position),position);if(bytesRead===0)throw new Error("Source changed during backup.");const chunk=bytes.subarray(0,bytesRead);digest2.update(chunk);await this.writeBytes(handle,chunk,position);position+=bytesRead}const rawDigest=digest2.digest("hex");if(await digestFileReadSource(source)!==rawDigest)throw new Error("Source changed during backup.");await handle.chmod(source.stats.mode&4095);await handle.sync();await this.#directories[1].handle.sync();const final=await handle.stat({bigint:true});if(!sameInode(final,attempt.stats)||final.size!==BigInt(source.stats.size)||final.nlink!==1n)throw new Error(UNAVAILABLE3);const pin2=Object.freeze({name,device:final.dev.toString(),inode:final.ino.toString(),byteLength:source.stats.size,digest:rawDigest,mode:Number(final.mode&0o7777n)});attempt.pin=pin2;await this.authenticate(attempt);return{backupFileName:name,version,backupTime:new Date}}catch(error){throw this.fault(error)}}))}withReadFile(request,operation){request.signal?.throwIfAborted();return this.withWorkingFile(request.path,async source=>{request.signal?.throwIfAborted();if(!source)throw new FileReadOpenError(Object.assign(new Error("File not found."),{code:"ENOENT"}));return operation(source)}).catch(error=>{const code=error instanceof Error?error.code:void 0;if(["EISDIR","ENOTDIR","ELOOP","EACCES"].includes(code??""))throw new FileReadOpenError(error);throw error})}readTextFile(params){return this.withWorkingFile(params.path,async source=>{if(!source)throw Object.assign(new Error("File not found."),{code:"ENOENT"});if((params.line??0)>0||Number.isFinite(params.limit)||params.maxOutputBytes!==void 0){const{content,...metadata}=await readTextContentRangeFromHandle(source.fileHandle,{fileSize:source.stats.size,offset:params.line??0,limit:params.limit??Infinity,maxOutputBytes:params.maxOutputBytes??256*1024,maxScanBytes:source.stats.size,signal:params.signal});return{content,_meta:metadata}}return this.text(source,params.signal)})}async writeTextFile(_params){throw new Error("Managed CSI text writes require the scoped mutation writer.")}findFiles(_fileName,_searchPaths){throw new Error("Managed CSI file tools do not support pathname glob.")}inspect(file,signal){signal?.throwIfAborted();return this.withWorkingFile(file,async source=>source?{kind:"file",response:await this.text(source,signal),stats:source.stats}:{kind:"missing"})}withMutation(file,signal,operation){const components=this.components(file);signal.throwIfAborted();return this.run((root,receipt2)=>this.working(root,receipt2,components,true,async working=>{const source=working.leaf?await this.source(working.leaf):null;const original=source?{kind:"file",response:await this.text(source,signal),stats:source.stats}:{kind:"missing"};let active=true;let write;try{return await operation({original,write:__name(params=>{if(!active||write||params.path!==file)return Promise.reject(new Error("CSI mutation writer is not available."));write=this.commit(working,params,signal);void write.catch(()=>{});return write},"write")})}finally{active=false;await write}}))}async commit(working,params,signal){signal.throwIfAborted();const bytes=await encodeTextFileContentAsync(params.path,params.content,params._meta);signal.throwIfAborted();let original;let changed=false;const originalName=working.missing.at(-1);try{if(working.leaf){await this.verifyEntry(working.leaf,true);original=await readFileHandleBytes(working.leaf.handle,Number(working.leaf.stats.size),signal);if(BigInt(original.length)!==working.leaf.stats.size)throw new Error(UNAVAILABLE3);await this.verifyEntry(working.leaf,true)}else{if(await this.lstat(addressOf(working.parent,working.missing[0])))throw new Error("CSI target appeared before mutation.");while(working.missing.length>1){const component=working.missing[0];const address2=addressOf(working.parent,component);await fs6.mkdir(address2,{mode:448});const entry=await this.openDirectory(address2,working.receipt.rootDevice,working.owned);working.parents.push(entry);await entry.handle.sync();await working.parent.sync();working.parent=entry.handle;working.missing.shift()}const address=addressOf(working.parent,working.missing[0]);const handle=await fs6.open(address,constants5.O_RDWR|constants5.O_CREAT|constants5.O_EXCL|constants5.O_NOFOLLOW|constants5.O_NONBLOCK,384);working.owned.push(handle);const stats=await handle.stat({bigint:true});this.requireFile(stats,working.receipt.rootDevice);working.leaf={handle,address,stats};working.missing=[];changed=true}const leaf=working.leaf;await this.checkAlias(leaf.stats);changed=true;await this.writeBytes(leaf.handle,bytes,0,signal);await leaf.handle.truncate(bytes.length);await leaf.handle.sync();await working.parent.sync();const committed=await leaf.handle.stat({bigint:true});if(!sameInode(leaf.stats,committed)||committed.mode!==leaf.stats.mode||committed.size!==BigInt(bytes.length))throw new Error(UNAVAILABLE3);leaf.stats=committed;await this.verifyEntry(leaf,true);return(await this.source(leaf)).stats}catch(error){if(changed&&working.leaf){try{const leaf=working.leaf;const named=await fs6.lstat(leaf.address,{bigint:true});const opened=await leaf.handle.stat({bigint:true});if(!named.isFile()||!sameInode(leaf.stats,named)||!sameInode(leaf.stats,opened)||named.mode!==leaf.stats.mode||opened.mode!==leaf.stats.mode)throw new Error(UNAVAILABLE3);await this.checkAlias(opened);if(original){await this.writeBytes(leaf.handle,original,0);await leaf.handle.truncate(original.length);await leaf.handle.sync();leaf.stats=await leaf.handle.stat({bigint:true});await this.verifyEntry(leaf,true)}else{await fs6.unlink(leaf.address);working.leaf=void 0;working.missing=[originalName]}await working.parent.sync()}catch(rollbackError){throw this.fault(new AggregateError([error,rollbackError],"CSI write rollback failed."))}}if(signal.aborted&&error===signal.reason)throw error;throw this.fault(error)}}async text(source,signal){const bytes=await readFileHandleBytes(source.fileHandle,source.stats.size,signal);if(bytes.length!==source.stats.size)throw this.fault(new Error("CSI file changed while reading."));const{content,encoding,bom}=await decodeBufferWithEncodingInfoAsync(bytes);signal?.throwIfAborted();return{content,_meta:{encoding,bom,lineEnding:detectLineEnding(content),originalLineCount:content.split("\n").length,originalLineCountExact:true,truncatedByBytes:false}}}components(file){if(!path6.isAbsolute(file)||path6.resolve(file)!==file||!file.startsWith(this.directory+"/"))throw new Error("CSI file path is not canonical.");const components=file.slice(this.directory.length+1).split("/");if(!components.every(validLeaf)||components[0]===PREFIX)throw new Error("CSI file path is reserved or invalid.");return components}async run(operation){if(this.#closed||this.#failure)throw this.#failure??new Error(UNAVAILABLE3);let complete;const pending=new Promise(resolve=>{complete=resolve});this.#pending.add(pending);let operationFailed=false;try{return await this.mount.withVerifiedRoot(async(root,receipt2)=>{this.#binding??=this.bind(root,receipt2);await this.#binding;await this.verifyStorage();try{return await operation(root,receipt2)}catch(error){operationFailed=true;throw error}finally{await this.verifyStorage()}})}catch(error){const code=error instanceof Error?error.code:void 0;if(!operationFailed||this.mount.isAvailable===false||["EIO","ENOSPC","EDQUOT","ENODEV","ESTALE","EBADF"].includes(code??""))this.fault(error);throw error}finally{this.#pending.delete(pending);complete()}}async bind(root,receipt2){this.#receipt=receipt2;try{const prefixAddress=addressOf(root,PREFIX);if(!await this.lstat(prefixAddress)){await fs6.mkdir(prefixAddress,{mode:448});await root.sync()}const prefix=await this.openDirectory(prefixAddress,receipt2.rootDevice,this.#directoryHandles);this.#directories.push(prefix);const ownerAddress=addressOf(prefix.handle,this.ownerSessionId);await fs6.mkdir(ownerAddress,{mode:448});await prefix.handle.sync();const owner=await this.openDirectory(ownerAddress,receipt2.rootDevice,this.#directoryHandles);this.#directories.push(owner);await owner.handle.sync();if((await fs6.readdir(`/proc/self/fd/${owner.handle.fd}`)).length)throw new Error("CSI history initial bind requires an empty directory.")}catch(error){throw this.fault(error)}}verifyStorage(){return this.withInventory(async()=>{try{if(this.#failure)throw this.#failure;for(const directory of this.#directories)await this.verifyEntry(directory,false);const owner=this.#directories[1];const names=(await fs6.readdir(`/proc/self/fd/${owner.handle.fd}`)).sort();const expected=[...this.#attempts.keys()].sort();if(names.length!==expected.length||names.some((name,i)=>name!==expected[i]))throw new Error("CSI history contains unknown or missing leaves.");for(const attempt of this.#attempts.values()){if(!attempt.handle||!attempt.stats)throw new Error("CSI backup registration is incomplete.");const named=await fs6.lstat(this.backupAddress(attempt.name),{bigint:true});const opened=await attempt.handle.stat({bigint:true});this.requireFile(named,this.#receipt.rootDevice);if(!sameInode(named,attempt.stats)||!sameInode(opened,attempt.stats))throw new Error(UNAVAILABLE3)}}catch(error){throw this.fault(error)}})}async working(root,receipt2,components,writable2,operation){const working={root,receipt:receipt2,parent:root,parents:[],owned:[],missing:components};let observed=false;try{for(let index=0;index<components.length-1;index++){const address=addressOf(working.parent,components[index]);if(!await this.lstat(address))break;const entry=await this.openDirectory(address,receipt2.rootDevice,working.owned);if(this.#directories.some(directory=>sameInode(directory.stats,entry.stats)))throw this.fault(new Error("CSI retained directory alias is forbidden."));working.parents.push(entry);working.parent=entry.handle;working.missing=components.slice(index+1)}if(working.missing.length===1){const address=addressOf(working.parent,working.missing[0]);const before=await this.lstat(address);if(before){this.requireFile(before,receipt2.rootDevice);const handle=await fs6.open(address,(writable2?constants5.O_RDWR:constants5.O_RDONLY)|constants5.O_NOFOLLOW|constants5.O_NONBLOCK);working.owned.push(handle);const opened=await handle.stat({bigint:true});if(!stableFile(before,opened))throw this.fault(new Error(UNAVAILABLE3));await this.checkAlias(opened);working.leaf={handle,address,stats:opened};working.missing=[]}}observed=true;return await operation(working)}finally{try{if(observed)await this.verifyWorking(working);else for(const parent of working.parents)await this.verifyEntry(parent,false)}finally{await this.closeEphemeral(working.owned.reverse())}}}async verifyWorking(working){if(working.leaf){await this.verifyEntry(working.leaf,true);await this.checkAlias(working.leaf.stats)}else if(await this.lstat(addressOf(working.parent,working.missing[0])))throw this.fault(new Error("CSI missing path changed during observation."));for(const parent of working.parents)await this.verifyEntry(parent,false)}async openDirectory(address,device,owned){const before=await fs6.lstat(address,{bigint:true});if(!before.isDirectory())throw Object.assign(new Error("CSI path parent is not a directory."),{code:before.isSymbolicLink()?"ELOOP":"ENOTDIR"});if(before.dev.toString()!==device)throw this.fault(new Error(UNAVAILABLE3));const handle=await fs6.open(address,DIR_FLAGS);owned.push(handle);try{const opened=await handle.stat({bigint:true});if(!opened.isDirectory()||!sameInode(before,opened))throw new Error(UNAVAILABLE3);return{handle,address,stats:opened}}catch(error){throw this.fault(error)}}async verifyEntry(entry,file){try{const named=await fs6.lstat(entry.address,{bigint:true});const opened=await entry.handle.stat({bigint:true});if(file?!stableFile(entry.stats,named)||!stableFile(entry.stats,opened):!named.isDirectory()||!opened.isDirectory()||!sameInode(entry.stats,named)||!sameInode(entry.stats,opened))throw new Error(UNAVAILABLE3)}catch(error){throw this.fault(error)}}async source(entry){const stats=await entry.handle.stat();if(!Number.isSafeInteger(stats.size)||stats.size<0||BigInt(stats.size)!==entry.stats.size)throw this.fault(new Error(UNAVAILABLE3));return{kind:"descriptor",fileHandle:entry.handle,stats}}async backupSource(attempt){return{kind:"descriptor",fileHandle:attempt.handle,stats:await attempt.handle.stat()}}async authenticate(attempt){try{const pin2=attempt.pin;if(!pin2||!attempt.handle||!attempt.stats)throw new Error("CSI retained backup is incomplete.");const opened=await attempt.handle.stat({bigint:true});const named=await fs6.lstat(this.backupAddress(attempt.name),{bigint:true});this.requireFile(opened,pin2.device);if(!sameInode(opened,attempt.stats)||!sameInode(named,attempt.stats)||!named.isFile()||opened.size!==BigInt(pin2.byteLength)||named.size!==opened.size||opened.mode!==named.mode||Number(opened.mode&0o7777n)!==pin2.mode||opened.nlink!==1n||await digestFileReadSource(await this.backupSource(attempt))!==pin2.digest)throw new Error("CSI retained backup pin changed.")}catch(error){throw this.fault(error)}}checkAlias(stats){return this.withInventory(async()=>{if([...this.#attempts.values()].some(attempt=>attempt.stats&&sameInode(attempt.stats,stats)))throw this.fault(new Error("CSI retained backup alias is forbidden."))})}withInventory(operation){const result=this.#inventoryTail.then(()=>{if(this.#failure)throw this.#failure;return operation()});this.#inventoryTail=result.then(()=>{},()=>{});return result}requireFile(stats,device){if(!stats.isFile())throw Object.assign(new Error("CSI tools require an ordinary file."),{code:stats.isDirectory()?"EISDIR":"ELOOP"});if(stats.dev.toString()!==device||stats.size<0n||stats.size>BigInt(Number.MAX_SAFE_INTEGER)){throw this.fault(Object.assign(new Error("CSI tools require an ordinary file on the original device."),stats.isDirectory()?{code:"EISDIR"}:{}))}}backupAddress(name){return addressOf(this.#directories[1].handle,name)}async lstat(address){try{return await fs6.lstat(address,{bigint:true})}catch(error){if(error.code==="ENOENT")return null;throw this.fault(error)}}async writeBytes(handle,bytes,position,signal){let offset=0;while(offset<bytes.length){signal?.throwIfAborted();const{bytesWritten}=await handle.write(bytes,offset,bytes.length-offset,position+offset);if(!Number.isSafeInteger(bytesWritten)||bytesWritten<=0||bytesWritten>bytes.length-offset)throw new Error("CSI file write did not progress.");offset+=bytesWritten}signal?.throwIfAborted()}async closeEphemeral(handles){const results=await Promise.allSettled(handles.map(async handle=>handle.close()));const errors=results.flatMap(result=>result.status==="rejected"?[result.reason]:[]);if(errors.length)throw this.fault(new AggregateError(errors,UNAVAILABLE3))}fault(error){this.#failure??=error instanceof Error?error:new Error(String(error));void this.close().catch(()=>{});return this.#failure}};function validLeaf(name){return name.length>0&&name!=="."&&name!==".."&&!name.includes("/")&&!name.includes("\\")&&[...name].every(character=>character.charCodeAt(0)>=32&&character.charCodeAt(0)!==127)}__name(validLeaf,"validLeaf");function addressOf(parent,name){return`/proc/self/fd/${parent.fd}/${name}`}__name(addressOf,"addressOf");function sameInode(a,b){return a.dev===b.dev&&a.ino===b.ino}__name(sameInode,"sameInode");function stableFile(a,b){return b.isFile()&&sameInode(a,b)&&a.size===b.size&&a.mode===b.mode&&a.mtimeNs===b.mtimeNs&&a.ctimeNs===b.ctimeNs}__name(stableFile,"stableFile");async function composeManagedCsiFiles(options){if(options.ownerSessionId!==options.runtimeSessionId||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(options.ownerSessionId)||options.profile!=="csi-files-retirement/1"||options.capabilityDigest!==CSI_FILES_RETIREMENT_CAPABILITY_DIGEST)throw new Error("Managed CSI file composition identity is unavailable.");let backend;try{return await options.mount.withVerifiedRoot(async()=>{backend=await ManagedCsiFileBackend.open(options.mount,options.ownerSessionId);const storage=backend;const directory=storage.directory;const config=new Config({sessionId:options.runtimeSessionId,targetDir:directory,cwd:directory,includeDirectories:[directory],model:"managed-runtime-worker",debugMode:false,usageStatisticsEnabled:false,approvalMode:"yolo",fileCheckpointingEnabled:false,fileReadCacheDisabled:true});config.setFileSystemService(storage);const history2=new ManagedRuntimeFileHistory(options.ownerSessionId,directory,null,storage);await history2.ready();let closed8=false;let closing;return{tools:{sessionId:options.runtimeSessionId,directory,workspaceRoot:directory,retainedFileHistory:storage,fileHistory:history2,admitsDirectory:__name(candidate=>candidate===directory,"admitsDirectory"),isActive:__name(()=>!closed8&&!storage.getDrainInspection().blocked&&!storage.getDrainInspection().closed,"isActive"),tools:new Map([new ReadFileTool(config),new WriteFileTool(config),new EditTool(config)].map(tool=>[tool.name,tool]))},history:history2,observe:__name(async()=>{if(closed8)throw new Error("Managed CSI file composition is closed.");await history2.history.drain();const result=history2.state();const observation=await storage.observeRetained();if(closed8||!isDeepStrictEqual5(result,history2.state()))throw new Error("Managed CSI history changed during observation.");return{history:result,storage:observation}},"observe"),close:__name(()=>{closed8=true;closing??=(async()=>{const joined=await Promise.allSettled([history2.history.drain(),storage.close()]);const mountResult=await Promise.allSettled([options.mount.close()]);const errors=[...joined,...mountResult].flatMap(result=>result.status==="rejected"?[result.reason]:[]);if(errors.length)throw new AggregateError(errors,"Managed CSI file composition close failed.")})();return closing},"close")}})}catch(error){const joined=await Promise.allSettled([backend?.close()]);const mountResult=await Promise.allSettled([options.mount.close()]);const errors=[error,...[...joined,...mountResult].flatMap(result=>result.status==="rejected"?[result.reason]:[])];throw new AggregateError(errors,"Managed CSI file composition failed.")}}__name(composeManagedCsiFiles,"composeManagedCsiFiles");init_esbuild_shims();import{createHash as createHash8,randomUUID as randomUUID6}from"node:crypto";import{isDeepStrictEqual as isDeepStrictEqual6}from"node:util";var CSI_NATIVE_READBACK_PATH="/internal/runtime-broker/csi/v1/native:read";var CSI_NATIVE_REQUEST_LIMIT=16*1024;var CSI_NATIVE_RESPONSE_LIMIT=8*1024*1024;var UUID2=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;var CONFIG=`sha256:${createHash8("sha256").update("csi-files-retirement-tools/1\0csi-files-retirement-policy/1").digest("hex")}`;var COMMON=["protocolVersion","requestId","action","identity","context","installedContext"];function readCsiNativeRequest(value){const body2=closed6(value,[...COMMON,"subject"]);common(body2);switch(body2["action"]){case"bind":ensure(body2["subject"]===null);break;case"prepare":ref(body2["subject"],"managed-file_history");break;case"execute":id(body2["subject"]);break;default:throw invalid3()}ensure(Buffer.byteLength(JSON.stringify(body2))<=CSI_NATIVE_REQUEST_LIMIT);return structuredClone(body2)}__name(readCsiNativeRequest,"readCsiNativeRequest");function readCsiNativeResponse(value,request){readCsiNativeRequest(request);const body2=closed6(value,[...COMMON,"head","evidence"]);common(body2);for(const field of COMMON)ensure(isDeepStrictEqual6(body2[field],request[field]));const head=closed6(body2["head"],["revision","sequence","digest"]);ensure(counter(head["revision"])>0&&counter(head["sequence"])>0);digest(head["digest"]);const owner=object3(body2["identity"])["sessionId"];const evidence=object3(body2["evidence"]);switch(body2["action"]){case"bind":closed6(evidence,["kind"]);ensure(evidence["kind"]==="ready");break;case"prepare":{closed6(evidence,["kind","intentRef","resources","members"]);ensure(evidence["kind"]==="intent"&&isDeepStrictEqual6(evidence["intentRef"],request.subject));const required=new Map;add(required,ref(evidence["intentRef"],"managed-file_history"));const members=list(evidence["members"]);ensure(members.length>0&&members.length<=4096);let previous=-1;let prompt;let batch;const calls=new Set;const functions=new Set;for(const candidate of members){const member=execution(candidate,owner);const ordinal=counter(member["ordinal"]);ensure(ordinal>previous&&!calls.has(member["callId"])&&!functions.has(member["functionCallId"]));ensure(prompt===void 0||prompt===member["promptId"]&&batch===member["batchId"]);prompt=member["promptId"];batch=member["batchId"];previous=ordinal;calls.add(member["callId"]);functions.add(member["functionCallId"]);add(required,ref(member["inputRef"],"managed-tool-input"));add(required,ref(member["toolDefinitionRef"],"managed-tool-definition"))}resources(evidence["resources"],required);break}case"execute":{closed6(evidence,["kind","executionReference","preparedRef","authorizationRevision","authorizationSequence","grant","resources"]);ensure(evidence["kind"]==="authorization");const reference2=execution(evidence["executionReference"],owner);const required=new Map;const inputRef=ref(reference2["inputRef"],"managed-tool-input");add(required,inputRef);add(required,ref(reference2["toolDefinitionRef"],"managed-tool-definition"));const prepared=evidence["preparedRef"];if(prepared!==null)add(required,ref(prepared,"managed-file_history"));const grant=readCsiNativeGrant(evidence["grant"]);ensure(grant["executionCallId"]===request.subject&&isDeepStrictEqual6(grant["executionReference"],reference2)&&isDeepStrictEqual6(grant["preparedRef"],prepared));for(const field of["authorizationRevision","authorizationSequence"]){const count=counter(evidence[field]);ensure(count===grant[field]&&count<=counter(head[field==="authorizationRevision"?"revision":"sequence"]))}for(const field of["identity","context","installedContext"])ensure(isDeepStrictEqual6(grant[field],body2[field]));const bytes=resources(evidence["resources"],required);const input=closed6(parseManagedCsiFileJson(bytes.get(inputRef.resourceId),64*1024),["harnessSessionId","runtimeSessionId","payloadJson"]);ensure(input["harnessSessionId"]===owner&&input["runtimeSessionId"]===owner&&typeof input["payloadJson"]==="string");ensure(`sha256:${createHash8("sha256").update(input["payloadJson"]).digest("hex")}`===reference2["argsDigest"]);const payload=closed6(parseManagedSessionRecordJson(input["payloadJson"],64*1024),["toolName","input"]);if(prepared===null)ensure(payload["toolName"]==="read_file");break}default:throw invalid3()}ensure(Buffer.byteLength(JSON.stringify(body2))<=CSI_NATIVE_RESPONSE_LIMIT);return structuredClone(body2)}__name(readCsiNativeResponse,"readCsiNativeResponse");function readCsiNativeGrant(value){const grant=closed6(value,["protocolVersion","runtimeBindingId","bindingGeneration","authorizedBindingVersion","executionCallId","dispatchGeneration","authorizationRevision","authorizationSequence","executionReference","intent","checkpointRef","preparedRef","identity","context","installedContext"]);ensure(grant["protocolVersion"]===1);commonContext(grant);id(grant["runtimeBindingId"]);id(grant["executionCallId"]);execution(grant["executionReference"],object3(grant["identity"])["sessionId"]);for(const field of["bindingGeneration","authorizedBindingVersion","dispatchGeneration"])ensure(isCanonicalDecimalText(grant[field]));for(const field of["authorizationRevision","authorizationSequence"])ensure(counter(grant[field])>0);const intent=closed6(grant["intent"],["revision","sequence"]);ensure(counter(intent["revision"])>0&&counter(intent["sequence"])>0&&counter(intent["revision"])<counter(grant["authorizationRevision"])&&counter(intent["sequence"])<counter(grant["authorizationSequence"]));ref(grant["checkpointRef"],"managed-checkpoint");if(grant["preparedRef"]!==null)ref(grant["preparedRef"],"managed-file_history");return grant}__name(readCsiNativeGrant,"readCsiNativeGrant");function common(value){ensure(value["protocolVersion"]===1);uuid(value["requestId"]);commonContext(value)}__name(common,"common");function commonContext(value){const identity=closed6(value["identity"],["profile","sessionId","capabilityDigest"]);ensure(identity["profile"]==="csi-files-retirement/1"&&identity["capabilityDigest"]===CSI_FILES_RETIREMENT_CAPABILITY_DIGEST);uuid(identity["sessionId"]);const context=closed6(value["context"],["protocolVersion","managedContext","runtimeInstanceId","runtimeIncarnation","leaseId","epoch","provisionRequestId","tenantId","workspaceId","workspaceGeneration","storageId","mountRoot","capabilityDigest","isolationClass"]);ensure(context["protocolVersion"]===3&&context["isolationClass"]==="session"&&context["capabilityDigest"]===identity["capabilityDigest"]);const{protocolVersion:_version,...fields}=context;parseManagedContextBoot({...fields,type:"boot",version:2,token:"validation-token"});const installed=closed6(value["installedContext"],["protocolVersion","managedContext","operationId","sessionId","contextDigest","binding"]);ensure(installed["protocolVersion"]===3&&installed["managedContext"]==="managed-context/1"&&installed["sessionId"]===identity["sessionId"]);const owner=identity["sessionId"];const hash=createHash8("md5").update(owner).digest();hash[6]=hash[6]&15|48;hash[8]=hash[8]&63|128;const hex=hash.toString("hex");ensure(installed["operationId"]===`${hex.slice(0,8)}-${hex.slice(8,12)}-${hex.slice(12,16)}-${hex.slice(16,20)}-${hex.slice(20)}`);const binding=closed6(installed["binding"],["tenantId","workspaceId","workspaceGeneration","storageId","cwdRelative","contextConfigRef","contextRevision"]);for(const field of["tenantId","workspaceId","workspaceGeneration","storageId"])ensure(binding[field]===context[field]);ensure(binding["cwdRelative"]==="."&&binding["contextRevision"]==="1"&&binding["contextConfigRef"]===CONFIG);ensure(computeManagedContextDigest(binding)===installed["contextDigest"])}__name(commonContext,"commonContext");function execution(value,owner){const result=closed6(value,["sessionId","promptId","callId","argsDigest","batchId","functionCallId","partIndex","ordinal","inputRef","toolDefinitionRef","dispatchMode"]);ensure(result["sessionId"]===owner&&result["dispatchMode"]==="deferred");for(const field of["promptId","callId","batchId"])uuid(result[field]);id(result["functionCallId"]);digest(result["argsDigest"],true);counter(result["partIndex"]);counter(result["ordinal"]);ensure(ref(result["inputRef"],"managed-tool-input").resourceId!==ref(result["toolDefinitionRef"],"managed-tool-definition").resourceId);return result}__name(execution,"execution");function resources(value,required){const result=new Map;for(const candidate of list(value)){const entry=closed6(candidate,["reference","bytesBase64"]);const reference2=object3(entry["reference"]);const resourceId=id(reference2["resourceId"]);ensure(required.has(resourceId)&&isDeepStrictEqual6(required.get(resourceId),reference2));ensure(typeof entry["bytesBase64"]==="string");const encoded=entry["bytesBase64"];const bytes=Buffer.from(encoded,"base64");ensure(bytes.toString("base64")===encoded&&bytes.length<=64*1024&&bytes.length===reference2["byteLength"]&&createHash8("sha256").update(bytes).digest("hex")===reference2["digest"]&&!result.has(resourceId));result.set(resourceId,bytes)}ensure(result.size===required.size);return result}__name(resources,"resources");function ref(value,kind){const result=assertManagedSessionDurableRef(value,"CSI native resource");ensure(result.kind===kind&&result.schemaVersion===1&&result.byteLength>0&&result.byteLength<=64*1024);return result}__name(ref,"ref");function add(required,reference2){const previous=required.get(reference2.resourceId);ensure(previous===void 0||isDeepStrictEqual6(previous,reference2));required.set(reference2.resourceId,reference2)}__name(add,"add");function counter(value){ensure(Number.isSafeInteger(value)&&value>=0);return value}__name(counter,"counter");function id(value){return assertManagedSessionStableId(value,"CSI native identity")}__name(id,"id");function digest(value,prefix=false){ensure(typeof value==="string"&&(prefix?/^sha256:[0-9a-f]{64}$/:/^[0-9a-f]{64}$/).test(value))}__name(digest,"digest");function uuid(value){ensure(typeof value==="string"&&UUID2.test(value))}__name(uuid,"uuid");function list(value){ensure(Array.isArray(value));return value}__name(list,"list");function object3(value){ensure(value!==null&&typeof value==="object"&&!Array.isArray(value));return value}__name(object3,"object");function closed6(value,keys){const result=object3(value);ensure(isDeepStrictEqual6(Object.keys(result).sort(),[...keys].sort()));return result}__name(closed6,"closed");function ensure(condition){if(!condition)throw invalid3()}__name(ensure,"ensure");function invalid3(){return new Error("Invalid private CSI native readback.")}__name(invalid3,"invalid");async function readCurrentCsiNative(boot,installedContext,action,subject){if(boot.version!==5)throw invalid3();const request=readCsiNativeRequest({protocolVersion:1,requestId:randomUUID6(),action,identity:boot.identity,context:createManagedContextAttestationResponse(boot.context),installedContext,subject});const response=await fetch(`${boot.authority.origin}${CSI_NATIVE_READBACK_PATH}`,{method:"POST",redirect:"error",signal:AbortSignal.timeout(15e3),headers:{authorization:`Bearer ${boot.context.token}`,"content-type":"application/json","cache-control":"no-store"},body:JSON.stringify(request)});ensure(response.status===200&&response.headers.get("content-encoding")===null&&response.headers.get("cache-control")==="no-store"&&response.headers.get("content-type")?.split(";")[0].trim()==="application/json");const reader=response.body?.getReader();if(!reader)throw invalid3();const chunks=[];let length=0;try{while(true){const next=await reader.read();if(next.done)break;length+=next.value.length;ensure(length<=CSI_NATIVE_RESPONSE_LIMIT);chunks.push(next.value)}}finally{await reader.cancel();reader.releaseLock()}return readCsiNativeResponse(parseManagedCsiFileJson(Buffer.concat(chunks),CSI_NATIVE_RESPONSE_LIMIT),request)}__name(readCurrentCsiNative,"readCurrentCsiNative");init_esbuild_shims();import{isDeepStrictEqual as isDeepStrictEqual7}from"node:util";import{createHash as createHash9}from"node:crypto";var CSI_FILE_HISTORY_PATH="/internal/managed-runtime/csi/v2/file-history";function readCsiPreparationEvidence(response){ensure2(response.action==="prepare");const owner=response.identity["sessionId"];ensure2(typeof owner==="string");const evidence=response.evidence;ensure2(evidence["kind"]==="intent"&&Array.isArray(evidence["resources"])&&Array.isArray(evidence["members"]));const resources2=new Map;for(const candidate of evidence["resources"]){const item=object4(candidate);const ref2=object4(item["reference"]);ensure2(typeof ref2["resourceId"]==="string"&&typeof item["bytesBase64"]==="string");resources2.set(ref2["resourceId"],Buffer.from(item["bytesBase64"],"base64"))}const originalRef=object4(evidence["intentRef"]);ensure2(typeof originalRef["resourceId"]==="string");const bytes=resources2.get(originalRef["resourceId"]);ensure2(bytes!==void 0);const body2=closed7(parseManagedCsiFileJson(bytes,64*1024),["operationId","revision","previousRecordRef","schemaVersion","profile","runtimeSessionId","state","backupDirectory","retainedBackups","preparation","record"]);ensure2(body2["schemaVersion"]===2&&body2["profile"]==="csi-files-retirement/1"&&body2["runtimeSessionId"]===owner);const preparation=closed7(body2["preparation"],["stage","turnId","promptId","batchId","invocations","paths"]);ensure2(preparation["stage"]==="intent"&&preparation["turnId"]===preparation["promptId"]&&Array.isArray(preparation["invocations"])&&Array.isArray(preparation["paths"])&&preparation["invocations"].length===evidence["members"].length);const paths=new Set;for(const[index,candidate]of preparation["invocations"].entries()){const invocation=closed7(candidate,["executionCallId","callId","functionCallId","toolName","partIndex","ordinal","requestDigest","inputRef","toolDefinitionRef"]);ensure2(typeof invocation["executionCallId"]==="string"&&invocation["executionCallId"].length>0);const member=object4(evidence["members"][index]);ensure2(isDeepStrictEqual7(member,{sessionId:owner,promptId:preparation["promptId"],batchId:preparation["batchId"],callId:invocation["callId"],functionCallId:invocation["functionCallId"],partIndex:invocation["partIndex"],ordinal:invocation["ordinal"],argsDigest:invocation["requestDigest"],inputRef:invocation["inputRef"],toolDefinitionRef:invocation["toolDefinitionRef"],dispatchMode:"deferred"}));const inputRef=object4(invocation["inputRef"]);ensure2(typeof inputRef["resourceId"]==="string");const inputBytes=resources2.get(inputRef["resourceId"]);ensure2(inputBytes!==void 0);const wrapper=closed7(parseManagedCsiFileJson(inputBytes,64*1024),["harnessSessionId","runtimeSessionId","payloadJson"]);ensure2(wrapper["harnessSessionId"]===owner&&wrapper["runtimeSessionId"]===owner&&typeof wrapper["payloadJson"]==="string");ensure2(`sha256:${createHash9("sha256").update(wrapper["payloadJson"]).digest("hex")}`===invocation["requestDigest"]);const payload=closed7(parseManagedSessionRecordJson(wrapper["payloadJson"],64*1024),["toolName","input"]);ensure2(payload["toolName"]===invocation["toolName"]&&["read_file","write_file","edit"].includes(String(invocation["toolName"])));const file=historyPath(object4(payload["input"])["file_path"]);if(invocation["toolName"]!=="read_file")paths.add(file)}ensure2(paths.size>0&&isDeepStrictEqual7([...paths].sort(),preparation["paths"]));return{preparation:structuredClone(preparation),observation:readCsiFileHistoryObservation({state:body2["state"],backupDirectory:body2["backupDirectory"],retainedBackups:body2["retainedBackups"]},owner)}}__name(readCsiPreparationEvidence,"readCsiPreparationEvidence");function readCsiFileHistoryOperation(value){const operation=object4(value);closed7(operation,["kind","version","action",...operation["action"]==="prepare"?["preparationRef"]:[]]);ensure2(operation["kind"]==="csi-file-history"&&operation["version"]===1);ensure2(["bind","snapshot","prepare"].includes(String(operation["action"])));if(operation["action"]==="prepare"){const reference2=assertManagedSessionDurableRef(operation["preparationRef"],"CSI preparation");ensure2(reference2.kind==="managed-file_history"&&reference2.schemaVersion===1&&reference2.byteLength>0&&reference2.byteLength<=64*1024)}return structuredClone(operation)}__name(readCsiFileHistoryOperation,"readCsiFileHistoryOperation");function readCsiFileHistoryEnvelope(value,boot,installedContext){const body2=closed7(value,["protocolVersion","managedCsi","identity","context","installedContext","operation"]);ensure2(boot.version===5&&body2["protocolVersion"]===2&&body2["managedCsi"]===MANAGED_CSI_FILE_PROTOCOL);ensure2(isDeepStrictEqual7(body2["identity"],boot.identity)&&isDeepStrictEqual7(body2["context"],createManagedContextAttestationResponse(boot.context))&&isDeepStrictEqual7(body2["installedContext"],installedContext));readCsiNativeRequest({protocolVersion:1,requestId:"00000000-0000-4000-8000-000000000000",action:"bind",identity:boot.identity,context:body2["context"],installedContext,subject:null});return readCsiFileHistoryOperation(body2["operation"])}__name(readCsiFileHistoryEnvelope,"readCsiFileHistoryEnvelope");function readCsiFileHistoryObservation(value,owner){const body2=closed7(value,["state","backupDirectory","retainedBackups"]);const state=parseHostedFileHistoryState(body2["state"],owner);const directory=closed7(body2["backupDirectory"],["volumeDevice","volumeInode","directoryDevice","directoryInode"]);for(const value2 of Object.values(directory))decimal(value2);ensure2(directory["volumeDevice"]===directory["directoryDevice"]);ensure2(Array.isArray(body2["retainedBackups"]));const pins=new Map;let previous="";for(const candidate of body2["retainedBackups"]){const pin2=closed7(candidate,["name","device","inode","byteLength","digest","mode"]);const name=pin2["name"];ensure2(typeof name==="string"&&name.length>0&&name.length<=256&&name!=="."&&name!==".."&&!/[/\\]/.test(name)&&[...name].every(char=>char.charCodeAt(0)>31&&char.charCodeAt(0)!==127)&&name>previous);decimal(pin2["device"]);decimal(pin2["inode"]);ensure2(pin2["device"]===directory["volumeDevice"]);ensure2(Number.isSafeInteger(pin2["byteLength"])&&pin2["byteLength"]>=0&&pin2["byteLength"]<Number.MAX_SAFE_INTEGER);ensure2(Number.isSafeInteger(pin2["mode"])&&pin2["mode"]>=0&&pin2["mode"]<=4095);ensure2(typeof pin2["digest"]==="string"&&/^[0-9a-f]{64}$/.test(pin2["digest"]));pins.set(name,structuredClone(pin2));previous=name}const names=new Set;for(const snapshot of state.snapshots){ensure2(snapshot.promptId.normalize("NFC")===snapshot.promptId&&Buffer.byteLength(snapshot.promptId)<=512&&[...snapshot.promptId].every(char=>char.charCodeAt(0)>31&&(char.charCodeAt(0)<127||char.charCodeAt(0)>159)));for(const backup of Object.values(snapshot.trackedFileBackups)){ensure2(backup.failed!==true&&backup.version<Number.MAX_SAFE_INTEGER);if(backup.backupFileName!==null){ensure2(pins.has(backup.backupFileName));names.add(backup.backupFileName)}}}ensure2(names.size===pins.size);return{state,backupDirectory:structuredClone(directory),retainedBackups:[...pins.values()]}}__name(readCsiFileHistoryObservation,"readCsiFileHistoryObservation");function decimal(value){ensure2(typeof value==="string"&&/^(?:0|[1-9][0-9]*)$/.test(value)&&value.length<=20&&BigInt(value)<=18446744073709551615n)}__name(decimal,"decimal");function object4(value){ensure2(value!==null&&typeof value==="object"&&!Array.isArray(value));return value}__name(object4,"object");function closed7(value,keys){const body2=object4(value);ensure2(isDeepStrictEqual7(Object.keys(body2).sort(),[...keys].sort()));return body2}__name(closed7,"closed");function ensure2(condition){if(!condition)throw new Error("Invalid private CSI file history.")}__name(ensure2,"ensure");var CONFIG2=`sha256:${createHash10("sha256").update("csi-files-retirement-tools/1\0csi-files-retirement-policy/1").digest("hex")}`;var HistoryCapacityError=class extends Error{static{__name(this,"HistoryCapacityError")}};function historyFits(request,before,promptId,paths){const projected=structuredClone(before);const snapshots=projected.state.snapshots;const newPrompt=snapshots.at(-1)?.promptId!==promptId;if(newPrompt&&snapshots.length>=100)return false;const tracked=new Set([...Object.keys(projected.state.files),...snapshots.flatMap(snapshot2=>Object.keys(snapshot2.trackedFileBackups)),...paths]);if(newPrompt)snapshots.push({promptId,timestamp:"9999-12-31T23:59:59.999Z",trackedFileBackups:{}});const snapshot=snapshots.at(-1);snapshot.trackedFileBackups=Object.assign(Object.create(null),snapshot.trackedFileBackups);projected.state.files=Object.assign(Object.create(null),projected.state.files);for(const file of tracked){if(newPrompt||!Object.hasOwn(snapshot.trackedFileBackups,file)){const name=`${"f".repeat(36)}@v${Number.MAX_SAFE_INTEGER}`;snapshot.trackedFileBackups[file]={backupFileName:name,version:Number.MAX_SAFE_INTEGER-1,backupTime:"9999-12-31T23:59:59.999Z"};projected.retainedBackups.push({name,device:projected.backupDirectory.volumeDevice,inode:"18446744073709551615",byteLength:Number.MAX_SAFE_INTEGER-1,digest:"f".repeat(64),mode:4095})}projected.state.files[file]={digest:`sha256:${"f".repeat(64)}`,mode:4095}}return Buffer.byteLength(JSON.stringify({...request,observation:projected}))+1024<=64*1024}__name(historyFits,"historyFits");async function startManagedCsiFileWorker(bootDocument){const boot=parseManagedCsiFileBoot(bootDocument);const pod={uid:process.env["QWEN_POD_UID"],namespace:process.env["QWEN_POD_NAMESPACE"],nodeName:process.env["QWEN_NODE_NAME"]};validateManagedCsiPodIdentity(pod,boot.storage.namespace);Object.freeze(pod);const mount=new ManagedCsiMount(boot.context.mountRoot,boot.storage.diskSerial);const installations=new ManagedContextInstallations(boot.context);let closed8=false;let retirementId;let composition;let binding;let bindIdentity;let historyFailed=false;let preparingHistory=false;let activeExecutions=0;let observationTail=Promise.resolve();const preparations=new Map;const operations=new Set;const track=__name(operation=>{operations.add(operation);void operation.then(()=>operations.delete(operation),()=>operations.delete(operation));return operation},"track");const canInstall=__name(()=>!closed8&&!historyFailed&&retirementId===void 0&&mount.isAvailable,"canInstall");const executor=new ManagedToolExecutor(async reference2=>canInstall()&&reference2.sessionId===boot.identity.sessionId?composition?.tools:void 0);const failHistory=__name(()=>{historyFailed=true;void executor.close().catch(()=>{})},"failHistory");const app=(0,import_express.default)();app.disable("x-powered-by");const refuse=__name((res,code="managed_csi_identity_conflict")=>res.status(409).json({code,error:"Managed CSI file context is unavailable or conflicts."}),"refuse");const middleware=[managedRuntimeNoStore,authorizeManagedRuntime(boot.context),nameManagedRuntimeIncarnation(boot.context),import_express.default.json({inflate:false,limit:16*1024,strict:true,type:"application/json",verify:__name((_req,_res,bytes)=>{try{parseManagedCsiFileJson(bytes,16*1024)}catch{throw new SyntaxError("Invalid CSI file request.")}},"verify")})];app.post(`${MANAGED_CSI_FILE_PREFIX}/context-attest`,...middleware,async(req,res)=>{try{const outcome=checkManagedContextAttestation(readManagedCsiFileContext(req.body,boot),boot.context);if(outcome.status!==200){res.status(outcome.status).json({code:outcome.code,error:"Managed CSI file identity conflicts."});return}await mount.observe();if(closed8||!mount.isAvailable)throw new Error;res.json(wrapManagedCsiFileContext(boot,outcome.body))}catch{refuse(res)}},handleManagedRuntimeJsonError);app.post(`${MANAGED_CSI_FILE_PREFIX}/context`,...middleware,async(req,res)=>{try{const context=readManagedCsiFileContext(req.body,boot);if(!context||typeof context!=="object"||!("sessionId"in context)||context.sessionId!==boot.identity.sessionId||!("binding"in context)||!context.binding||typeof context.binding!=="object"||!("cwdRelative"in context.binding)||context.binding.cwdRelative!=="."||!("contextConfigRef"in context.binding)||context.binding.contextConfigRef!==CONFIG2)throw new Error;if(boot.version===5)readCsiNativeRequest({protocolVersion:1,requestId:"00000000-0000-4000-8000-000000000000",action:"bind",identity:boot.identity,context:createManagedContextAttestationResponse(boot.context),installedContext:context,subject:null});if(!canInstall()){refuse(res,"managed_context_unavailable");return}const outcome=await installations.install(context,async()=>{try{await mount.observe();return canInstall()}catch{return false}},canInstall);if(!canInstall()){refuse(res,"managed_context_unavailable");return}if(outcome.status!==200){res.status(outcome.status).json({code:outcome.code,error:"Managed CSI file context conflicts."});return}res.json(wrapManagedCsiFileContext(boot,outcome.body))}catch{refuse(res)}},handleManagedRuntimeJsonError);app.post(`${MANAGED_CSI_FILE_PREFIX}/attest`,...middleware,async(req,res)=>{try{validateManagedCsiFileAttestationRequest(req.body,boot);const observation=await mount.observe();if(closed8||!mount.isAvailable)throw new Error;const response={protocolVersion:2,managedCsi:MANAGED_CSI_FILE_PROTOCOL,identity:boot.identity,context:createManagedContextAttestationResponse(boot.context),storage:boot.storage,pod,mount:observation};validateManagedCsiFileAttestationResponse(response,boot,pod);res.json(response)}catch{refuse(res)}},handleManagedRuntimeJsonError);app.post(CSI_FILE_HISTORY_PATH,...middleware,async(req,res)=>{try{if(boot.version!==5||closed8)throw new Error;if(historyFailed){refuse(res,"managed_csi_history_retirement_required");return}const installed=installations.installation(boot.identity.sessionId);if(!installed)throw new Error;const operation=readCsiFileHistoryEnvelope(req.body,boot,installed);const fingerprint3=JSON.stringify(installed);let observation;if(operation.action==="prepare"){if(!canInstall()||!binding||fingerprint3!==bindIdentity)throw new Error;const originalBinding=binding;const ref2=operation.preparationRef;let prepared=preparations.get(ref2.resourceId);if(prepared&&!isDeepStrictEqual8(prepared.reference,ref2))throw new Error;if(!prepared){let beforePreparation;const pending=track(observationTail.catch(()=>void 0).then(async()=>{preparingHistory=true;await originalBinding;if(!canInstall()||!composition||activeExecutions)throw new Error;const current=readCsiPreparationEvidence(await readCurrentCsiNative(boot,installed,"prepare",ref2));if(!canInstall())throw new Error;const before=await composition.observe();if(!isDeepStrictEqual8(current.observation,readCsiFileHistoryObservation({state:before.history,...before.storage},boot.identity.sessionId))||!canInstall())throw new Error;if(!historyFits(req.body,current.observation,current.preparation.promptId,current.preparation.paths))throw new HistoryCapacityError;beforePreparation=current.observation;await composition.history.prepare(current.preparation.promptId,current.preparation.paths);const after=await composition.observe();return readCsiFileHistoryObservation({state:after.history,...after.storage},boot.identity.sessionId)}).catch(async error=>{if(beforePreparation){try{const after=await composition.observe();if(!isDeepStrictEqual8(beforePreparation,readCsiFileHistoryObservation({state:after.history,...after.storage},boot.identity.sessionId)))failHistory()}catch{failHistory()}}if(!historyFailed)preparations.delete(ref2.resourceId);throw error}).finally(()=>{preparingHistory=false}));prepared={reference:structuredClone(ref2),observation:pending};preparations.set(ref2.resourceId,prepared);observationTail=pending}observation=await prepared.observation}else if(operation.action==="bind"){if(!canInstall())throw new Error;if(binding&&fingerprint3!==bindIdentity)throw new Error;if(!binding){bindIdentity=fingerprint3;binding=track(Promise.resolve().then(async()=>{await readCurrentCsiNative(boot,installed,"bind",null);if(!canInstall())throw new Error;composition=await composeManagedCsiFiles({mount,ownerSessionId:boot.identity.sessionId,runtimeSessionId:boot.identity.sessionId,profile:boot.identity.profile,capabilityDigest:boot.identity.capabilityDigest});if(!canInstall())throw new Error;const observed=await composition.observe();const result=readCsiFileHistoryObservation({state:observed.history,...observed.storage},boot.identity.sessionId);if(result.state.snapshots.length||Object.keys(result.state.files).length||result.retainedBackups.length)throw new Error;return result}).catch(error=>{if(!composition&&canInstall()){binding=void 0;bindIdentity=void 0}throw error}))}observation=await binding}else{if(!binding||fingerprint3!==bindIdentity)throw new Error;const originalBinding=binding;const pending=track(observationTail.catch(()=>void 0).then(async()=>{await originalBinding;if(closed8||historyFailed||!composition)throw new Error;const observed=await composition.observe();return readCsiFileHistoryObservation({state:observed.history,...observed.storage},boot.identity.sessionId)}));observationTail=pending;observation=await pending}if(closed8||historyFailed||operation.action!=="snapshot"&&!canInstall())throw new Error;const response={...req.body,observation};if(Buffer.byteLength(JSON.stringify(response))>64*1024){if(operation.action==="prepare")failHistory();throw new HistoryCapacityError}res.json(response)}catch(error){refuse(res,historyFailed?"managed_csi_history_retirement_required":error instanceof HistoryCapacityError?"managed_csi_history_capacity_exceeded":"managed_csi_history_unavailable")}},handleManagedRuntimeJsonError);app.post(`${MANAGED_CSI_FILE_PREFIX}/execute`,...middleware,async(req,res)=>{try{if(historyFailed){refuse(res,"managed_csi_history_retirement_required");return}const request=readCsiNativeRequest(req.body);const installed=installations.installation(boot.identity.sessionId);if(boot.version!==5||request.action!=="execute"||typeof request.subject!=="string"||!installed||!binding||bindIdentity!==JSON.stringify(installed)||!isDeepStrictEqual8(request.identity,boot.identity)||!isDeepStrictEqual8(request.context,createManagedContextAttestationResponse(boot.context))||!isDeepStrictEqual8(request.installedContext,installed)||preparingHistory||!canInstall())throw new Error;const originalBinding=binding;const result=await track(Promise.resolve().then(async()=>{await originalBinding;if(!canInstall()||!composition)throw new Error;const current=await readCurrentCsiNative(boot,installed,"execute",request.subject);if(!canInstall())throw new Error;const evidence=current.evidence;const reference2=evidence["executionReference"];const inputRef=reference2["inputRef"];const input=evidence["resources"].find(resource=>resource.reference.resourceId===inputRef.resourceId);if(!input)throw new Error;const wrapper=parseManagedCsiFileJson(Buffer.from(input.bytesBase64,"base64"),64*1024);const payloadJson=wrapper["payloadJson"];if(typeof payloadJson!=="string")throw new Error;const payload=parseManagedCsiFileJson(Buffer.from(payloadJson),64*1024);const toolName=payload["toolName"];if(!["read_file","write_file","edit"].includes(String(toolName))||reference2["argsDigest"]!==`sha256:${createHash10("sha256").update(payloadJson).digest("hex")}`||!canInstall())throw new Error;const preparedRef=evidence["preparedRef"];if(preparedRef!==null){const preparedResource=evidence["resources"].find(resource=>resource.reference.resourceId===preparedRef.resourceId);if(!preparedResource)throw new Error;const preparedBody=parseManagedCsiFileJson(Buffer.from(preparedResource.bytesBase64,"base64"),64*1024);const preparation=preparedBody["preparation"];const intentRef=preparation["intentRef"];const saved=preparations.get(intentRef.resourceId);const invocation=preparation["invocations"].find(item=>item["executionCallId"]===request.subject);if(preparedBody["schemaVersion"]!==2||preparedBody["profile"]!==boot.identity.profile||preparedBody["runtimeSessionId"]!==boot.identity.sessionId||preparation["stage"]!=="prepared"||preparation["promptId"]!==reference2["promptId"]||preparation["batchId"]!==reference2["batchId"]||!saved||!invocation||invocation["toolName"]!==toolName||invocation["requestDigest"]!==reference2["argsDigest"]||["callId","functionCallId","partIndex","ordinal","inputRef","toolDefinitionRef"].some(field=>!isDeepStrictEqual8(invocation[field],reference2[field]))||!isDeepStrictEqual8(saved.reference,intentRef)||!isDeepStrictEqual8(await saved.observation,readCsiFileHistoryObservation({state:preparedBody["state"],backupDirectory:preparedBody["backupDirectory"],retainedBackups:preparedBody["retainedBackups"]},boot.identity.sessionId))||!canInstall())throw new Error}else if(toolName!=="read_file"){throw new Error}if(preparingHistory)throw new Error;activeExecutions++;try{return await executor.execute({sessionId:reference2["sessionId"],promptId:reference2["promptId"],callId:reference2["callId"],argsDigest:reference2["argsDigest"]},toolName,payload["input"])}finally{activeExecutions--}}));const response={...request,state:"settled",result};if(closed8||Buffer.byteLength(JSON.stringify(response))>MANAGED_RUNTIME_TOOL_RESULT_BODY_LIMIT_BYTES+16*1024)throw new Error;res.json(response)}catch{refuse(res,"managed_csi_execution_unavailable")}},handleManagedRuntimeJsonError);app.post(`${MANAGED_CSI_FILE_PREFIX}/drain`,...middleware,async(req,res)=>{try{const request=readManagedCsiFileDrain(req.body,boot,pod);if(closed8||retirementId!==void 0&&retirementId!==request.retirementId||request.operation==="status"&&retirementId===void 0)throw new Error;if(request.operation==="seal"){retirementId??=request.retirementId;executor.sealAdmission(request.retirementId)}await Promise.allSettled([...operations]);res.json({protocolVersion:2,managedCsi:MANAGED_CSI_FILE_PROTOCOL,identity:boot.identity,retirementId:request.retirementId,context:createManagedContextAttestationResponse(boot.context),storage:boot.storage,pod,state:"DRAINING",workState:"BLOCKED",pendingStarts:0,pendingInvocations:0,blockers:["file-admission-unavailable",...binding?["retained-history-bound"]:[],...historyFailed?["history-prepare-failed"]:[]].sort()})}catch{refuse(res,"managed_csi_drain_conflict")}},handleManagedRuntimeJsonError);const server=createServer(ownedManagedRuntimeRouteGate(app,[...MANAGED_CSI_FILE_ROUTES,...boot.version===5?[{method:"POST",path:CSI_FILE_HISTORY_PATH},{method:"POST",path:`${MANAGED_CSI_FILE_PREFIX}/execute`}]:[]]));server.maxHeadersCount=32;server.headersTimeout=5e3;server.requestTimeout=5e3;server.keepAliveTimeout=1e3;let closing;const close=__name(()=>{closed8=true;closing??=(async()=>{const results=await Promise.allSettled([new Promise((resolve,reject)=>{if(!server.listening){resolve();return}server.close(error=>error?reject(error):resolve());server.closeAllConnections()})]);const joined=await Promise.allSettled([...operations]);const executed=await Promise.allSettled([executor.close()]);preparations.clear();const retained=await Promise.allSettled([composition?composition.close():mount.close()]);const errors=[...results,...joined,...executed,...retained].flatMap(result=>result.status==="rejected"?[result.reason]:[]);if(errors.length)throw new AggregateError(errors,"Managed CSI file worker close failed.")})();return closing},"close");try{await mount.observe();if(!mount.isAvailable)throw new Error("Managed CSI mount is unavailable.");await new Promise((resolve,reject)=>{const onError=__name(error=>{server.off("listening",onListening);reject(error)},"onError");const onListening=__name(()=>{server.off("error",onError);resolve()},"onListening");server.once("error",onError);server.once("listening",onListening);server.listen(43190,"0.0.0.0")});const address=server.address();if(!address)throw new Error("Managed Runtime worker listener is unavailable.");return{ready:createManagedCsiFileReady(boot,address.port),close}}catch(error){try{await close()}catch(cleanup){throw new AggregateError([error,cleanup],"Managed CSI file worker startup failed.")}throw error}}__name(startManagedCsiFileWorker,"startManagedCsiFileWorker");init_esbuild_shims();var import_express2=__toESM(require_express(),1);var MANAGED_CSI_ATTEST_ROUTE=Object.freeze({method:"POST",path:MANAGED_CSI_ATTEST_PATH});var MANAGED_CSI_DRAIN_ROUTE=Object.freeze({method:"POST",path:MANAGED_CSI_DRAIN_PATH});var MANAGED_CSI_ACK_ROUTE=Object.freeze({method:"POST",path:MANAGED_CSI_ACK_PATH});function registerManagedCsiAckRoute(app,boot,executor){const pod={uid:process.env["QWEN_POD_UID"],namespace:process.env["QWEN_POD_NAMESPACE"],nodeName:process.env["QWEN_NODE_NAME"]};validateManagedCsiPodIdentity(pod,boot.storage.namespace);app.post(MANAGED_CSI_ACK_PATH,managedRuntimeNoStore,authorizeManagedRuntime(boot.context),import_express2.default.json({inflate:false,limit:MANAGED_CSI_ACK_LIMIT_BYTES,strict:true,type:"application/json",verify:__name((_req,_res,bytes)=>{try{parseManagedCsiAckJson(bytes)}catch{throw new ManagedCsiAckRequestError(400)}},"verify")}),(req,res)=>{try{const request=parseManagedCsiAckRequest(req.body,boot,pod);const confirmed=executor.acknowledgeOriginalCsi(request,boot,pod);res.type("application/json").send(confirmed.json)}catch(error){if(!(error instanceof ManagedCsiAckRequestError))throw error;res.status(error.status).json({code:"managed_csi_ack_conflict",error:"Managed CSI acknowledgement conflicts."})}},(error,req,res,next)=>{if(error?.type==="entity.verify.failed"){res.status(400).json({code:"managed_csi_ack_conflict",error:"Managed CSI acknowledgement conflicts."});return}handleManagedRuntimeJsonError(error,req,res,next)})}__name(registerManagedCsiAckRoute,"registerManagedCsiAckRoute");function registerManagedCsiDrainRoute(app,boot,executor){const pod={uid:process.env["QWEN_POD_UID"],namespace:process.env["QWEN_POD_NAMESPACE"],nodeName:process.env["QWEN_NODE_NAME"]};validateManagedCsiPodIdentity(pod,boot.storage.namespace);app.post(MANAGED_CSI_DRAIN_PATH,managedRuntimeNoStore,authorizeManagedRuntime(boot.context),managedRuntimeJsonBody(16*1024),(req,res)=>{try{const request=parseManagedCsiDrainRequest(req.body,boot,pod);if(request.operation==="seal")executor.sealAdmission(request.retirementId);res.json({protocolVersion:1,managedCsi:MANAGED_CSI_PROTOCOL,retirementId:request.retirementId,context:createManagedContextAttestationResponse(boot.context),storage:boot.storage,pod,...executor.getDrainObservation(request.retirementId)})}catch(error){if(!(error instanceof ManagedCsiDrainRequestError)&&!(error instanceof ManagedToolConflictError))throw error;res.status(error instanceof ManagedCsiDrainRequestError?error.status:409).json({code:"managed_csi_drain_conflict",error:"Managed CSI drain request conflicts."})}},handleManagedRuntimeJsonError)}__name(registerManagedCsiDrainRoute,"registerManagedCsiDrainRoute");function registerManagedCsiAttestationRoute(app,boot,mount){const pod={uid:process.env["QWEN_POD_UID"],namespace:process.env["QWEN_POD_NAMESPACE"],nodeName:process.env["QWEN_NODE_NAME"]};validateManagedCsiPodIdentity(pod,boot.storage.namespace);app.post(MANAGED_CSI_ATTEST_PATH,managedRuntimeNoStore,authorizeManagedRuntime(boot.context),managedRuntimeJsonBody(16*1024),async(req,res)=>{try{validateManagedCsiAttestationRequest(req.body,boot)}catch{res.status(409).json({code:"managed_csi_identity_conflict",error:"Managed CSI identity conflicts."});return}try{const observation=await mount.observe();if(!mount.isAvailable)throw new Error;const response={protocolVersion:1,managedCsi:MANAGED_CSI_PROTOCOL,context:createManagedContextAttestationResponse(boot.context),storage:boot.storage,pod,mount:observation};validateManagedCsiAttestationResponse(response,boot,pod);res.status(200).json(response)}catch{res.status(409).json({code:"managed_csi_mount_unavailable",error:"Managed CSI mount is unavailable."})}},handleManagedRuntimeJsonError)}__name(registerManagedCsiAttestationRoute,"registerManagedCsiAttestationRoute");var MANAGED_RUNTIME_WORKER_BOOT_LIMIT_BYTES=32*1024;var MANAGED_RUNTIME_WORKER_BOOT_TIMEOUT_MS=3e4;var INVALID_BOOT_MESSAGE2="Managed Runtime worker boot payload is invalid.";var BOOT_KEYS3=Object.freeze(["capabilityDigest","epoch","isolationClass","leaseId","provisionRequestId","runtimeIncarnation","runtimeInstanceId","tenantId","token","type","version","workspaceCwd","workspaceGeneration","workspaceId"]);function isExactBoot(value){if(!value||typeof value!=="object"||Array.isArray(value))return false;const keys=Object.keys(value).sort();if(keys.length!==BOOT_KEYS3.length||!keys.every((key,index)=>key===BOOT_KEYS3[index])){return false}const boot=value;return boot["type"]==="boot"&&boot["version"]===1}__name(isExactBoot,"isExactBoot");async function collectManagedRuntimeWorkerBoot(input){const chunks=[];let size=0;for await(const chunk of input){const bytes=Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk);size+=bytes.byteLength;if(size>MANAGED_RUNTIME_WORKER_BOOT_LIMIT_BYTES){throw new Error(INVALID_BOOT_MESSAGE2)}chunks.push(bytes)}return Buffer.concat(chunks)}__name(collectManagedRuntimeWorkerBoot,"collectManagedRuntimeWorkerBoot");function parseWorkerBoot(document){let parsed;try{parsed=JSON.parse(document.toString("utf8"))}catch{throw new Error(INVALID_BOOT_MESSAGE2)}if(isExactBoot(parsed)){if(parsed.capabilityDigest===CSI_FILES_RETIREMENT_CAPABILITY_DIGEST)throw new Error(INVALID_BOOT_MESSAGE2);return parsed}try{new TextDecoder("utf-8",{fatal:true}).decode(document);const boot=parseManagedContextBoot(parsed);if(boot.capabilityDigest===CSI_FILES_RETIREMENT_CAPABILITY_DIGEST)throw new Error(INVALID_BOOT_MESSAGE2);return boot}catch{throw new Error(INVALID_BOOT_MESSAGE2)}}__name(parseWorkerBoot,"parseWorkerBoot");async function readManagedRuntimeWorkerBoot(input){return parseWorkerBoot(await readBootDocument(input))}__name(readManagedRuntimeWorkerBoot,"readManagedRuntimeWorkerBoot");async function readBootDocument(input){let timeout;const timedOut=new Promise((_,reject)=>{timeout=setTimeout(()=>{input.destroy();reject(new Error(INVALID_BOOT_MESSAGE2))},MANAGED_RUNTIME_WORKER_BOOT_TIMEOUT_MS);timeout.unref()});try{return await Promise.race([collectManagedRuntimeWorkerBoot(input),timedOut])}finally{if(timeout)clearTimeout(timeout)}}__name(readBootDocument,"readBootDocument");async function startManagedRuntimeAttestationWorker(bootDocument,capturePublisher,remotePublishers,containerMode=false){if(bootDocument.version===4||bootDocument.version===5){if(!containerMode||capturePublisher||remotePublishers)throw new Error(INVALID_BOOT_MESSAGE2);return startManagedCsiFileWorker(bootDocument)}const resolved=bootDocument.version===3?parseManagedCsiBoot(bootDocument):bootDocument;const csiBoot=resolved.version===3?resolved:void 0;const boot=resolved.version===3?resolved.context:resolved;if(boot.capabilityDigest===CSI_FILES_RETIREMENT_CAPABILITY_DIGEST||csiBoot!==void 0&&!containerMode||containerMode&&csiBoot===void 0&&(boot.version!==1||boot.isolationClass!=="session")){throw new Error(INVALID_BOOT_MESSAGE2)}const app=(0,import_express3.default)();app.disable("x-powered-by");const csiMount=csiBoot?new ManagedCsiMount(csiBoot.context.mountRoot,csiBoot.storage.diskSerial):void 0;let executor;try{if(csiBoot&&csiMount){await csiMount.observe();registerManagedCsiAttestationRoute(app,csiBoot,csiMount)}if(boot.version===2){executor=registerManagedContextRoutes(app,boot,capturePublisher,remotePublishers,csiMount)}else{registerManagedRuntimeAttestationRoute(app,boot);const ledger=managedRuntimeLedgerFromEnvironment(boot.runtimeIncarnation);ledger?.watch();executor=ManagedToolExecutor.forWorkspace(boot.workspaceCwd,boot.runtimeInstanceId,{ledger});registerManagedRuntimeToolRoutes(app,boot,executor);const mount=new ManagedContextMount(boot.workspaceCwd);registerManagedRuntimeProviderRoute(app,boot,executor,async()=>{const directory=await mount.resolve("");return directory===void 0?void 0:{directory,workspaceRoot:directory,preapproved:false}})}if(csiBoot){registerManagedCsiDrainRoute(app,csiBoot,executor);registerManagedCsiAckRoute(app,csiBoot,executor)}}catch(error){return closeCsiMountAfterError(csiMount,error)}const server=createServer2(ownedManagedRuntimeRouteGate(app,boot.version===2?capturePublisher||remotePublishers||boot.capabilityDigest===WORKSPACE_CAPABILITY_DIGEST?[...MANAGED_CONTEXT_WORKER_ROUTES,...csiBoot?[MANAGED_CSI_ATTEST_ROUTE,MANAGED_CSI_DRAIN_ROUTE,MANAGED_CSI_ACK_ROUTE]:[],...MANAGED_TOOL_RESULT_ROUTES,...remotePublishers?[MANAGED_SHELL_PUBLISHER_ROUTE]:[],...!capturePublisher&&boot.capabilityDigest===WORKSPACE_CAPABILITY_DIGEST?[PUBLICATION_INSTALL_ROUTE]:[]]:[...MANAGED_CONTEXT_WORKER_ROUTES,...csiBoot?[MANAGED_CSI_ATTEST_ROUTE,MANAGED_CSI_DRAIN_ROUTE,MANAGED_CSI_ACK_ROUTE]:[]]:[...OWNED_MANAGED_RUNTIME_ROUTES,MANAGED_RUNTIME_PROVIDER_ROUTE]));server.maxHeadersCount=32;server.headersTimeout=5e3;server.requestTimeout=5e3;server.keepAliveTimeout=1e3;try{await new Promise((resolve,reject)=>{const onError=__name(error=>{server.off("listening",onListening);reject(error)},"onError");const onListening=__name(()=>{server.off("error",onError);resolve()},"onListening");server.once("error",onError);server.once("listening",onListening);server.listen(containerMode?43190:0,containerMode?"0.0.0.0":"127.0.0.1")})}catch(error){return closeCsiMountAfterError(csiMount,error)}const address=server.address();if(!address){await new Promise(resolve=>server.close(()=>resolve()));return closeCsiMountAfterError(csiMount,new Error("Managed Runtime worker listener is unavailable."))}const ready=boot.version===2?createManagedContextReady(boot,address.port):Object.freeze({type:"ready",version:1,runtimeInstanceId:boot.runtimeInstanceId,runtimeIncarnation:boot.runtimeIncarnation,leaseId:boot.leaseId,epoch:boot.epoch,url:`http://127.0.0.1:${address.port}`});let closing;return{ready,close:__name(()=>{closing??=(async()=>{const errors=[];try{await executor.close()}catch(error){errors.push(error)}const cleanup=await Promise.allSettled([new Promise((resolve,reject)=>{server.close(error=>error?reject(error):resolve());server.closeAllConnections()}),csiMount?.close()]);errors.push(...cleanup.flatMap(result=>result.status==="rejected"?[result.reason]:[]));if(errors.length===1)throw errors[0];if(errors.length>1)throw new AggregateError(errors,errors[0]instanceof Error?errors[0].message:"Managed Runtime worker shutdown failed.",{cause:errors[0]})})();return closing},"close")}}__name(startManagedRuntimeAttestationWorker,"startManagedRuntimeAttestationWorker");async function closeCsiMountAfterError(mount,error){try{await mount?.close()}catch(cleanupError){throw new AggregateError([error,cleanupError],error instanceof Error?error.message:"Managed Runtime worker startup failed.",{cause:error})}throw error}__name(closeCsiMountAfterError,"closeCsiMountAfterError");async function readManagedRuntimeContainerBoot(bootPath){if(!path7.isAbsolute(bootPath))throw new Error(INVALID_BOOT_MESSAGE2);const input=createReadStream2(bootPath);try{const document=await readBootDocument(input);const parsed=JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(document));if(parsed&&typeof parsed==="object"&&"version"in parsed&&(parsed.version===4||parsed.version===5)){return parseManagedCsiFileBoot(parseManagedCsiFileJson(document,MANAGED_RUNTIME_WORKER_BOOT_LIMIT_BYTES))}if(parsed&&typeof parsed==="object"&&"version"in parsed&&parsed.version===3){const boot2=parseManagedCsiBoot(parsed);if(boot2.context.capabilityDigest===CSI_FILES_RETIREMENT_CAPABILITY_DIGEST)throw new Error(INVALID_BOOT_MESSAGE2);return boot2}const boot=parseWorkerBoot(document);if(boot.version!==1||boot.isolationClass!=="session"){throw new Error(INVALID_BOOT_MESSAGE2)}return boot}catch{throw new Error(INVALID_BOOT_MESSAGE2)}finally{input.destroy()}}__name(readManagedRuntimeContainerBoot,"readManagedRuntimeContainerBoot");async function runManagedRuntimeAttestationWorker(containerBootPath){if(typeof process.send==="function"){scrubAndReportInheritedLoaderEnv(process.env,"qwen","Managed Runtime worker")}let boot;try{boot=containerBootPath!==void 0?await readManagedRuntimeContainerBoot(containerBootPath):await readManagedRuntimeWorkerBoot(process.stdin)}catch(error){if(containerBootPath===void 0)throw error;process.stderr.write(`${INVALID_BOOT_MESSAGE2}
|
|
3
|
+
import{CLOSE_SWEEP_TIMEOUT_MS,GROUP_EXIT_EVIDENCE_TIMEOUT_MS,managedRuntimeLedgerFromEnvironment,signalProcessGroup}from"./chunk-R3GIVUCR.js";import{HOSTED_GLOB_TOO_COMPLEX,LocalShellResultCapture,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_SHELL_PUBLISHER_ROUTE,MANAGED_WORKSPACE_CONTEXT_FILES,MANAGED_WORKSPACE_CONTEXT_FILE_CHARS,ManagedRuntimeProviderProtocolError,ManagedShellPublisherRegistry,WORKSPACE_ACTIVATION_ROUTE,WORKSPACE_CAPABILITY_DIGEST,WORKSPACE_CONTEXT_CONFIG_REF,WorkspaceActivations,checkHostedGlobPattern,fitManagedRuntimeProviderResult,managedRuntimeProviderLimit,parseManagedRuntimeProviderRequest,parseManagedRuntimeProviderResult}from"./chunk-PMQ74TUZ.js";import{resolveManagedRuntimeBrokerBaseUrl}from"./chunk-6S5XOXJ2.js";import{MANAGED_RUNTIME_TOOL_RESULT_BODY_LIMIT_BYTES,OWNED_MANAGED_RUNTIME_ROUTES,authorizeManagedRuntime,handleManagedRuntimeJsonError,managedRuntimeJsonBody,managedRuntimeNoStore,nameManagedRuntimeIncarnation,ownedManagedRuntimeRouteGate,registerManagedRuntimeAttestationRoute}from"./chunk-IT34OWRH.js";import"./chunk-3SHHYK7S.js";import{require_express}from"./chunk-6SOKP7IN.js";import"./chunk-ELUOCI74.js";import"./chunk-IS7CHVXD.js";import{MANAGED_TOOL_FILE_HISTORY_MAX_BYTES,captureManagedToolExecutionContext,computeManagedContextDigest,historyPath,isCanonicalDecimalText,isManagedIdentifier,isWorkspaceStorageId,normalizeWorkspaceRelativePath,parseHostedFileHistoryState,parseToolPublicationBinding}from"./chunk-QIU62EU7.js";import{scrubAndReportInheritedLoaderEnv}from"./chunk-CVMMNPLX.js";import"./chunk-S7IKHQ6I.js";import{WriteFileTool}from"./chunk-BVARURDD.js";import"./chunk-NZFR5IY7.js";import{EditTool}from"./chunk-SFETIBPP.js";import"./chunk-QZPNBV4F.js";import{GlobTool}from"./chunk-6OP7FXSJ.js";import"./chunk-6GLM4FUL.js";import{Client,Config,DEFAULT_INHERITED_ENV_VARS,EventSource,FileHistoryService,HookCommandCgroup,HookCommandIsolationUnavailableError,HookRegistry,HookRunner,ShellTool,StdioClientTransport,StreamableHTTPClientTransport,UnauthorizedError,auth,createFetchWithInit,deriveConfig,deserializeSnapshots,detectLineEnding,encodeTextFileContentAsync,extractWWWAuthenticateParams,firePostToolUseFailureHook,firePostToolUseHook,firePreToolUseHook,generateToolUseId,interpolateUrl,isModifiableDeclarativeTool,normalizeHeaders,serializeSnapshot}from"./chunk-IFAUFERF.js";import"./chunk-R2EHHA2C.js";import"./chunk-ZLZF2ZDD.js";import{CallToolResultSchema,GetPromptResultSchema,JSONRPCMessageSchema,ListPromptsResultSchema,ListResourcesResultSchema,ListToolsResultSchema,ReadResourceResultSchema}from"./chunk-YK7NDQKM.js";import"./chunk-JUPGJYC2.js";import"./chunk-PHIPLV2I.js";import{isShellResultDisplay}from"./chunk-T7CHK6C2.js";import"./chunk-VZDZ34KK.js";import"./chunk-PT7NZBDY.js";import"./chunk-TWP72VRH.js";import{MANAGED_TOOL_RESULT_KINDS,MANAGED_TOOL_RESULT_LIMITS,MANAGED_TOOL_RESULT_PROTOCOL,MANAGED_TOOL_RESULT_ROUTES,ManagedSessionConflictError,ManagedSessionRecordError,ManagedToolProtocolError,assertManagedSessionDurableRef,assertManagedSessionKey,assertManagedSessionSequence,assertManagedSessionStableId,isOperationGrantSuccessor,managedToolDigest,parseManagedSessionRecordJson,parseManagedToolContentModification,parseManagedToolMediaContext,parseOperationGrant,parseToolResultPrefixRequest,parseToolResultPublishRequest,parseToolResultSealRequest,serializeManagedToolConfirmation}from"./chunk-R2AGF6ET.js";import"./chunk-OGI5HG6N.js";import"./chunk-ZQWGATC2.js";import"./chunk-EVVLG5RD.js";import"./chunk-LLX4BCWK.js";import"./chunk-QXQGUM3Y.js";import"./chunk-AG3SSCAF.js";import"./chunk-BMSATZXW.js";import"./chunk-GCIMHMRU.js";import"./chunk-EOMQENJY.js";import"./chunk-QVPT37XZ.js";import"./chunk-VMQO3VPA.js";import"./chunk-HATHFJPW.js";import"./chunk-XQJOZDV7.js";import"./chunk-CV2UAEZA.js";import"./chunk-GNQGC2DJ.js";import"./chunk-YPIUTOL3.js";import"./chunk-KLC3OD2M.js";import"./chunk-K6EQXZMK.js";import"./chunk-BG67XABA.js";import"./chunk-BEKROCWN.js";import"./chunk-Y77BXKWA.js";import"./chunk-LKE7NTQV.js";import"./chunk-UEO3N2FM.js";import"./chunk-JVJS2YFU.js";import"./chunk-G5PYYZMM.js";import"./chunk-D7XCQWP2.js";import"./chunk-OBOU4ZZM.js";import"./chunk-D6UTJ3SP.js";import"./chunk-MPHSE7M4.js";import"./chunk-FQQMMFT6.js";import"./chunk-JZK2WGXA.js";import"./chunk-LGKVMW44.js";import"./chunk-JIL7UY37.js";import"./chunk-JKXBHBE3.js";import"./chunk-EKGFFEH4.js";import"./chunk-JG2UNQOW.js";import"./chunk-S2ZKZXHX.js";import"./chunk-JANYB2IR.js";import"./chunk-EBMCWXGZ.js";import"./chunk-MYFKO4WS.js";import"./chunk-7KVWF3T4.js";import"./chunk-4ZRCV3JY.js";import{getShellContextEnvVars}from"./chunk-AH64K6DM.js";import"./chunk-YGLM5XPP.js";import"./chunk-4NPYOXJO.js";import{promptIdContext}from"./chunk-MWGB5RCF.js";import{getShellConfiguration}from"./chunk-XWEXQT3X.js";import"./chunk-NTRFETZB.js";import"./chunk-TL3SF2GA.js";import"./chunk-YIW3H46P.js";import"./chunk-7UK4WJWS.js";import"./chunk-4GP3PH7Z.js";import{sanitizeChildEnv}from"./chunk-LFKUPU57.js";import"./chunk-T2F7KYYR.js";import"./chunk-SW54YEPK.js";import"./chunk-6PHAGUA6.js";import{captureHookExecutionOwner,runWithHookExecutionOwner}from"./chunk-7J2TOJMG.js";import"./chunk-AGEDDL7Z.js";import"./chunk-2NJJHZ52.js";import"./chunk-3YWXKSOI.js";import"./chunk-OW25BC3M.js";import"./chunk-2PMQL4KE.js";import"./chunk-V3XYE727.js";import"./chunk-S6RXVOY6.js";import"./chunk-BRPC43OM.js";import"./chunk-B5XDGUAK.js";import"./chunk-WZDBBDRD.js";import{createAbortController}from"./chunk-476F6QIM.js";import"./chunk-4R67LXKL.js";import"./chunk-WW7MJFAN.js";import"./chunk-LG4NL2M7.js";import{ReadFileTool}from"./chunk-KBPIYGHG.js";import"./chunk-UQFTXKEB.js";import"./chunk-HDGTWJ24.js";import"./chunk-W5NWIGKO.js";import{FileReadOpenError,decodeBufferWithEncodingInfoAsync,digestFileReadSource,readFileHandleBytes,readTextContentRangeFromHandle}from"./chunk-JU2HHQR5.js";import"./chunk-6C4YRBLR.js";import"./chunk-37KFLBKZ.js";import"./chunk-PWOQASXT.js";import"./chunk-Z6AR5XE5.js";import"./chunk-7U7CWMP7.js";import"./chunk-77V43YOE.js";import{runWithInvocationContext}from"./chunk-SLD7H2FA.js";import"./chunk-7DOOXUDG.js";import"./chunk-P3RLMP7L.js";import"./chunk-R54OXALA.js";import"./chunk-MJUFVFH3.js";import"./chunk-TAAJ7TDB.js";import"./chunk-4ZBZL23U.js";import"./chunk-ZZZAYAJW.js";import"./chunk-XMANRGPK.js";import"./chunk-AWTUIQ7W.js";import"./chunk-KQX4H2D3.js";import"./chunk-BWU6AH5O.js";import"./chunk-BMHYEQTI.js";import"./chunk-CPVAVCGD.js";import"./chunk-SLPJ4OII.js";import"./chunk-4YLXNRRH.js";import"./chunk-65UCR6OZ.js";import"./chunk-CN2TQ3PU.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-I6S7NGX3.js";import"./chunk-SVAPAMMG.js";import"./chunk-3KUHQGOS.js";import{ToolNames}from"./chunk-2UNFJQ2D.js";import{createDebugLogger,registerSessionProjectDir,sessionIdContext,unregisterSessionModel,unregisterSessionProjectDir}from"./chunk-JAUJI56S.js";import"./chunk-I4H7NUVP.js";import"./chunk-EPODBRBP.js";import"./chunk-OKN3Z5C5.js";import"./chunk-XYB7GC5U.js";import"./chunk-2UOMCYQG.js";import"./chunk-I7L2TX4M.js";import"./chunk-MK3OONRA.js";import"./chunk-COGTQ5KZ.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__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 createReadStream2}from"node:fs";import path7 from"node:path";init_esbuild_shims();var MANAGED_CONTEXT_PROTOCOL="managed-context/1";var MANAGED_CONTEXT_BOOT_VERSION=2;var MANAGED_CONTEXT_READY_VERSION=2;var MANAGED_CONTEXT_BODY_LIMIT_BYTES=16*1024;var MANAGED_CONTEXT_ROUTES=Object.freeze([Object.freeze({key:"attest",method:"POST",path:"/internal/managed-runtime/v3/attest",protocolVersion:3,requestBodyLimitBytes:MANAGED_CONTEXT_BODY_LIMIT_BYTES,responseBodyLimitBytes:MANAGED_CONTEXT_BODY_LIMIT_BYTES,cacheControl:"no-store"}),Object.freeze({key:"context",method:"POST",path:"/internal/managed-runtime/v3/context",protocolVersion:3,requestBodyLimitBytes:MANAGED_CONTEXT_BODY_LIMIT_BYTES,responseBodyLimitBytes:MANAGED_CONTEXT_BODY_LIMIT_BYTES,cacheControl:"no-store"})]);var PROTOCOL_VERSION=MANAGED_CONTEXT_ROUTES[0].protocolVersion;var INVALID_BOOT_MESSAGE="Managed context boot document is invalid.";var MAXIMUM_MOUNT_ROOT_BYTES=4096;var MAXIMUM_SESSION_ID_LENGTH=512;var MAXIMUM_PORT=65535;var DIGEST_PATTERN=/^sha256:[0-9a-f]{64}$/;var BEARER_TOKEN_PATTERN=/^[A-Za-z0-9._~+/-]+=*$/;var MAXIMUM_TOKEN_LENGTH=512;var LONE_SURROGATE_PATTERN=/[\ud800-\udfff]/u;var ABSOLUTE_PATH_PATTERN=/^(?:\/|[A-Za-z]:[\\/]|\\\\)/;var BOOT_KEYS=Object.freeze(["capabilityDigest","epoch","isolationClass","leaseId","managedContext","mountRoot","provisionRequestId","runtimeIncarnation","runtimeInstanceId","storageId","tenantId","token","type","version","workspaceGeneration","workspaceId"]);var READY_KEYS=Object.freeze(["epoch","leaseId","managedContext","runtimeIncarnation","runtimeInstanceId","type","url","version"]);var ATTESTATION_KEYS=Object.freeze(["capabilityDigest","isolationClass","managedContext","mountRoot","protocolVersion","provisionRequestId","storageId","tenantId","workspaceGeneration","workspaceId"]);var INSTALLATION_KEYS=Object.freeze(["binding","contextDigest","managedContext","operationId","protocolVersion","sessionId"]);var BINDING_KEYS=Object.freeze(["contextConfigRef","contextRevision","cwdRelative","storageId","tenantId","workspaceGeneration","workspaceId"]);var ATTESTED_KEYS=Object.freeze(["provisionRequestId","tenantId","workspaceId","workspaceGeneration","storageId","mountRoot","capabilityDigest","isolationClass"]);var WORKSPACE_KEYS=Object.freeze(["tenantId","workspaceId","workspaceGeneration","storageId"]);var INVALID=Object.freeze({status:400,code:"managed_runtime_attestation_invalid"});var IDENTITY_CONFLICT=Object.freeze({status:409,code:"managed_runtime_identity_conflict"});var CONTEXT_CONFLICT=Object.freeze({status:409,code:"managed_context_conflict"});var CONTEXT_UNAVAILABLE=Object.freeze({status:409,code:"managed_context_unavailable"});function parseManagedContextBoot(value){const boot=readClosed(value,BOOT_KEYS);if(!boot||boot.type!=="boot"||boot.version!==MANAGED_CONTEXT_BOOT_VERSION||boot.managedContext!==MANAGED_CONTEXT_PROTOCOL||!isBearerToken(boot.token)||!isManagedIdentifier(boot.runtimeInstanceId)||!isManagedIdentifier(boot.runtimeIncarnation)||!isManagedIdentifier(boot.leaseId)||!isEpoch(boot.epoch)||!hasValidAttestedFields(boot)){throw new Error(INVALID_BOOT_MESSAGE)}return Object.freeze(boot)}__name(parseManagedContextBoot,"parseManagedContextBoot");function createManagedContextReady(boot,port){const identity=parseManagedContextBoot(boot);if(!Number.isInteger(port)||port<1||port>MAXIMUM_PORT){throw new Error("Managed context ready port is invalid.")}return Object.freeze({type:"ready",version:MANAGED_CONTEXT_READY_VERSION,managedContext:MANAGED_CONTEXT_PROTOCOL,runtimeInstanceId:identity.runtimeInstanceId,runtimeIncarnation:identity.runtimeIncarnation,leaseId:identity.leaseId,epoch:identity.epoch,url:`http://127.0.0.1:${port}`})}__name(createManagedContextReady,"createManagedContextReady");function createManagedContextAttestationResponse(boot){return attestationResponse(parseManagedContextBoot(boot))}__name(createManagedContextAttestationResponse,"createManagedContextAttestationResponse");function checkManagedContextAttestation(body2,boot){const identity=parseManagedContextBoot(boot);const request=readClosed(body2,ATTESTATION_KEYS);if(!request||request.protocolVersion!==PROTOCOL_VERSION||request.managedContext!==MANAGED_CONTEXT_PROTOCOL||!hasValidAttestedFields(request)){return INVALID}if(ATTESTED_KEYS.some(key=>request[key]!==identity[key])){return IDENTITY_CONFLICT}return{status:200,body:attestationResponse(identity)}}__name(checkManagedContextAttestation,"checkManagedContextAttestation");var ManagedContextInstallations=class{static{__name(this,"ManagedContextInstallations")}#boot;#operations=new Map;#sessions=new Map;constructor(boot){this.#boot=parseManagedContextBoot(boot)}async install(body2,verify,canRecord=()=>true){const request=this.#read(body2);if("status"in request){return request}const earlier=this.#match(request);if(earlier){return earlier}if(!canRecord())return CONTEXT_UNAVAILABLE;const verified=await verify(request.binding);return this.#match(request)??(verified&&canRecord()?this.#record(request):CONTEXT_UNAVAILABLE)}installed(sessionId){return this.#sessions.get(sessionId)?.binding}installation(sessionId){const request=this.#sessions.get(sessionId);return request?Object.freeze({protocolVersion:PROTOCOL_VERSION,managedContext:MANAGED_CONTEXT_PROTOCOL,...request}):void 0}bindings(){return[...this.#sessions.entries()].map(([sessionId,request])=>[sessionId,request.binding])}#read(body2){const request=readClosed(body2,INSTALLATION_KEYS);const binding=request&&readClosed(request.binding,BINDING_KEYS);if(!request||!binding||request.protocolVersion!==PROTOCOL_VERSION||request.managedContext!==MANAGED_CONTEXT_PROTOCOL||!isManagedIdentifier(request.operationId)||!isRuntimeSessionId(request.sessionId)||!isDigest(request.contextDigest)){return INVALID}const contextDigest=digestOf(binding);if(contextDigest===void 0||contextDigest!==request.contextDigest){return INVALID}if(WORKSPACE_KEYS.some(key=>binding[key]!==this.#boot[key])){return IDENTITY_CONFLICT}return{operationId:request.operationId,sessionId:request.sessionId,contextDigest,binding:Object.freeze(binding)}}#match(request){const previous=this.#operations.get(request.operationId);if(previous){return previous.sessionId===request.sessionId&&previous.contextDigest===request.contextDigest?{status:200,body:previous.receipt}:CONTEXT_CONFLICT}const installed=this.#sessions.get(request.sessionId);return installed!==void 0&&installed.contextDigest!==request.contextDigest?CONTEXT_CONFLICT:void 0}#record(request){const{operationId,sessionId,contextDigest,binding}=request;const receipt2=Object.freeze({protocolVersion:PROTOCOL_VERSION,managedContext:MANAGED_CONTEXT_PROTOCOL,operationId,sessionId,runtimeInstanceId:this.#boot.runtimeInstanceId,runtimeIncarnation:this.#boot.runtimeIncarnation,epoch:this.#boot.epoch,contextDigest,contextRevision:binding.contextRevision,workspaceGeneration:binding.workspaceGeneration});this.#operations.set(operationId,Object.freeze({sessionId,contextDigest,receipt:receipt2}));this.#sessions.set(sessionId,request);return{status:200,body:receipt2}}};function attestationResponse(identity){return Object.freeze({protocolVersion:PROTOCOL_VERSION,managedContext:MANAGED_CONTEXT_PROTOCOL,runtimeInstanceId:identity.runtimeInstanceId,runtimeIncarnation:identity.runtimeIncarnation,leaseId:identity.leaseId,epoch:identity.epoch,provisionRequestId:identity.provisionRequestId,tenantId:identity.tenantId,workspaceId:identity.workspaceId,workspaceGeneration:identity.workspaceGeneration,storageId:identity.storageId,mountRoot:identity.mountRoot,capabilityDigest:identity.capabilityDigest,isolationClass:identity.isolationClass})}__name(attestationResponse,"attestationResponse");function readClosed(value,keys){if(typeof value!=="object"||value===null||Array.isArray(value)){return void 0}const present=Object.keys(value).sort();if(present.length!==keys.length||!present.every((key,index)=>key===keys[index])){return void 0}const snapshot={};for(const key of keys){snapshot[key]=value[key]}return snapshot}__name(readClosed,"readClosed");function hasValidAttestedFields(fields){return isManagedIdentifier(fields.provisionRequestId)&&isManagedIdentifier(fields.tenantId)&&isManagedIdentifier(fields.workspaceId)&&isCanonicalDecimalText(fields.workspaceGeneration)&&isWorkspaceStorageId(fields.storageId)&&isMountRoot(fields.mountRoot)&&isDigest(fields.capabilityDigest)&&(fields.isolationClass==="session"||fields.isolationClass==="workspace")}__name(hasValidAttestedFields,"hasValidAttestedFields");function digestOf(binding){try{return computeManagedContextDigest(binding)}catch{return void 0}}__name(digestOf,"digestOf");function isNonEmptyString(value){return typeof value==="string"&&value.length>0}__name(isNonEmptyString,"isNonEmptyString");function isRuntimeSessionId(value){return isNonEmptyString(value)&&value.length<=MAXIMUM_SESSION_ID_LENGTH&&!value.includes("\0")&&!LONE_SURROGATE_PATTERN.test(value)}__name(isRuntimeSessionId,"isRuntimeSessionId");function isBearerToken(value){return matches(BEARER_TOKEN_PATTERN,value)&&value.length<=MAXIMUM_TOKEN_LENGTH}__name(isBearerToken,"isBearerToken");function matches(pattern,value){return typeof value==="string"&&pattern.test(value)}__name(matches,"matches");function isEpoch(value){return Number.isSafeInteger(value)&&value>=1}__name(isEpoch,"isEpoch");function isDigest(value){return matches(DIGEST_PATTERN,value)}__name(isDigest,"isDigest");function isMountRoot(value){if(typeof value!=="string"||value.length>MAXIMUM_MOUNT_ROOT_BYTES||!ABSOLUTE_PATH_PATTERN.test(value)){return false}for(const character of value){const codePoint=character.codePointAt(0)??0;if(codePoint<=31||codePoint>=127&&codePoint<=159||codePoint>=55296&&codePoint<=57343){return false}}return Buffer.byteLength(value,"utf8")<=MAXIMUM_MOUNT_ROOT_BYTES}__name(isMountRoot,"isMountRoot");init_esbuild_shims();import{createHash as createHash6}from"node:crypto";init_esbuild_shims();var CSI_FILES_RETIREMENT_CAPABILITY_DIGEST="sha256:116dcd2afce7292bdf0bf4c76010964f7a7148ad512b2939e48e3d55ea91118d";import{constants as constants2,promises as fs3}from"node:fs";import path4 from"node:path";init_esbuild_shims();import path2 from"node:path";import{promises as fs}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}from"node:crypto";import{createReadStream}from"node:fs";import{lstat}from"node:fs/promises";import path 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(path.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(path.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(path.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(path.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=>path.relative(this.directory,file).split(path.sep).join("/")),filesFailed:result.filesFailed.map(file=>path.relative(this.directory,file).split(path.sep).join("/")),conflict:false}})}async resolve(file){historyPath(file);if(this.retainedStorage){const absolute=path.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=path.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(path.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 digest2=createHash("sha256");for await(const chunk of createReadStream(absolute))digest2.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:${digest2.digest("hex")}`,mode:after.mode&4095}}catch(error){if(error.code==="ENOENT")return null;throw error}}};init_esbuild_shims();import{createHash as createHash2}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();function gateKey(sessionKey,operationId){const key=assertManagedSessionKey(sessionKey);const id2=assertManagedSessionStableId(operationId,"operationId");return`${key.tenantId}\0${key.workspaceId}\0${key.sessionId}\0${id2}`}__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)}};var ManagedMcpError=class extends Error{constructor(code){super(code);this.code=code}static{__name(this,"ManagedMcpError")}};var MAX_INFLIGHT=32;var MAX_MANIFEST_BYTES=1024*1024;var MAX_RESULT_BYTES=60*1024;var MAX_CATALOG_CATEGORY_BYTES=16*1024;var MAX_CATALOG_PAGES=64;var TIMEOUT_MS=25e3;var REQUEST_TIMEOUT_MS=6e5;var identifier=/^[A-Za-z0-9._:-]{1,128}$/u;function object(value){if(!value||typeof value!=="object"||Array.isArray(value))throw new ManagedMcpError("managed_mcp_invalid");return value}__name(object,"object");function closed(value,fields){if(Object.keys(value).some(key=>!fields.includes(key)))throw new ManagedMcpError("managed_mcp_invalid")}__name(closed,"closed");function positive(value){return typeof value==="number"&&Number.isSafeInteger(value)&&value>0}__name(positive,"positive");function strings(value){return!!value&&typeof value==="object"&&!Array.isArray(value)&&Object.values(value).every(item=>typeof item==="string")}__name(strings,"strings");function scope(key){return`${key.tenantId}\0${key.workspaceId}\0${key.sessionId}`}__name(scope,"scope");function bindingKey(runtimeSessionId,serverId,revision,generation){return`${runtimeSessionId}\0${serverId}\0${revision}\0${generation}`}__name(bindingKey,"bindingKey");function fingerprint(value){return createHash2("sha256").update(JSON.stringify(value)).digest("hex")}__name(fingerprint,"fingerprint");function parseManagedMcpControl(value){const control=object(value);const key=object(control["sessionKey"]);closed(key,["tenantId","workspaceId","sessionId"]);if(["tenantId","workspaceId","sessionId"].some(name=>typeof key[name]!=="string"||!identifier.test(key[name]))||typeof control["operationId"]!=="string"||!identifier.test(control["operationId"]))throw new ManagedMcpError("managed_mcp_invalid");const base=["kind","sessionKey","operationId"];if(control["kind"]==="mcp-status"||control["kind"]==="mcp-cancel"){closed(control,[...base,"targetOperationId"]);if(typeof control["targetOperationId"]!=="string"||!identifier.test(control["targetOperationId"]))throw new ManagedMcpError("managed_mcp_invalid");return structuredClone(control)}if(!["mcp-configure","mcp-discover","mcp-invoke","mcp-release"].includes(String(control["kind"]))||typeof control["serverId"]!=="string"||!identifier.test(control["serverId"])||!positive(control["serverRevision"]))throw new ManagedMcpError("managed_mcp_invalid");const server=[...base,"serverId","serverRevision","grant"];if(control["kind"]==="mcp-configure"){closed(control,[...server,"configRevision","definitionDigest"]);if(!positive(control["configRevision"])||typeof control["definitionDigest"]!=="string"||!/^[a-f0-9]{64}$/u.test(control["definitionDigest"]))throw new ManagedMcpError("managed_mcp_invalid")}else{if(!positive(control["connectionGeneration"]))throw new ManagedMcpError("managed_mcp_invalid");if(control["kind"]==="mcp-invoke"){closed(control,[...server,"configRevision","connectionGeneration","catalogRevision","request"]);if(!positive(control["configRevision"])||!positive(control["catalogRevision"]))throw new ManagedMcpError("managed_mcp_invalid");const request=object(control["request"]);if(request["kind"]==="resource_read"){closed(request,["kind","uri"]);if(typeof request["uri"]!=="string"||request["uri"].length===0)throw new ManagedMcpError("managed_mcp_invalid")}else if(request["kind"]==="tool_call"||request["kind"]==="prompt_get"){closed(request,["kind","name","arguments"]);if(typeof request["name"]!=="string"||request["name"].length===0)throw new ManagedMcpError("managed_mcp_invalid");object(request["arguments"]);if(request["kind"]==="prompt_get"&&!strings(request["arguments"]))throw new ManagedMcpError("managed_mcp_invalid")}else throw new ManagedMcpError("managed_mcp_invalid")}else closed(control,[...server,"connectionGeneration"])}try{parseOperationGrant(control["grant"])}catch{throw new ManagedMcpError("managed_mcp_grant_invalid")}return structuredClone(control)}__name(parseManagedMcpControl,"parseManagedMcpControl");function loadManagedMcpManifest(file){if(!file)return{version:1,servers:[]};try{const bytes=readFileSync(file);if(bytes.length>MAX_MANIFEST_BYTES)throw new ManagedMcpError("managed_mcp_manifest_invalid");return parseManifest(JSON.parse(bytes.toString("utf8")))}catch(error){throw error instanceof ManagedMcpError?error:new ManagedMcpError("managed_mcp_manifest_invalid")}}__name(loadManagedMcpManifest,"loadManagedMcpManifest");function parseManifest(value){const manifest=object(value);closed(manifest,["version","servers"]);if(manifest["version"]!==1||!Array.isArray(manifest["servers"]))throw new ManagedMcpError("managed_mcp_manifest_invalid");const keys=new Set;for(const item of manifest["servers"]){const definition=object(item);closed(definition,["tenantId","workspaceId","serverId","serverRevision","definitionDigest","transport","command","args","env","url","headers","timeoutMs"]);if(["tenantId","workspaceId","serverId"].some(key=>typeof definition[key]!=="string"||!identifier.test(definition[key]))||!positive(definition["serverRevision"])||typeof definition["definitionDigest"]!=="string"||!/^[a-f0-9]{64}$/u.test(definition["definitionDigest"]))throw new ManagedMcpError("managed_mcp_manifest_invalid");if(definition["timeoutMs"]!==void 0&&(!positive(definition["timeoutMs"])||Number(definition["timeoutMs"])>REQUEST_TIMEOUT_MS))throw new ManagedMcpError("managed_mcp_manifest_invalid");const id2=`${definition["tenantId"]}\0${definition["workspaceId"]}\0${definition["serverId"]}\0${definition["serverRevision"]}`;if(keys.has(id2))throw new ManagedMcpError("managed_mcp_definition_conflict");keys.add(id2);if(definition["transport"]==="stdio"){if(typeof definition["command"]!=="string"||!definition["command"]||definition["command"].includes("\0")||definition["url"]!==void 0||definition["headers"]!==void 0||definition["args"]!==void 0&&(!Array.isArray(definition["args"])||!definition["args"].every(arg=>typeof arg==="string"&&!arg.includes("\0")))||definition["env"]!==void 0&&(!strings(definition["env"])||Object.entries(definition["env"]).some(([key,value2])=>key.includes("\0")||value2.includes("\0"))))throw new ManagedMcpError("managed_mcp_manifest_invalid")}else if(definition["transport"]==="streamable-http"||definition["transport"]==="sse"){if(typeof definition["url"]!=="string"||definition["command"]!==void 0||definition["args"]!==void 0||definition["env"]!==void 0||definition["headers"]!==void 0&&!strings(definition["headers"]))throw new ManagedMcpError("managed_mcp_manifest_invalid");const url=new URL(definition["url"]);if(!["http:","https:"].includes(url.protocol)||url.username||url.password)throw new ManagedMcpError("managed_mcp_manifest_invalid")}else throw new ManagedMcpError("managed_mcp_transport_unsupported")}return structuredClone(manifest)}__name(parseManifest,"parseManifest");var ManagedMcpRuntime=class{constructor(workspace,sessionDirectory,manifest){this.workspace=workspace;this.sessionDirectory=sessionDirectory;this.definitions=parseManifest(manifest)}static{__name(this,"ManagedMcpRuntime")}definitions;connections=new Map;operations=new Map;gates=new ManagedOperationGrantGate;generation=0;closing=false;admissionSealed=false;grantInstalled=false;pendingStarts=0;sealAdmission(){this.admissionSealed=true}getDrainInspection(){return{pendingStarts:this.pendingStarts,pendingInvocations:[...this.operations.values()].filter(operation=>operation.view.state==="running"||operation.connection?.pending.has(operation.control.operationId)).length,hasActivity:this.grantInstalled||this.operations.size>0||this.connections.size>0}}assertAdmission(control){if(this.admissionSealed&&control.kind!=="mcp-release")throw new ManagedMcpError("managed_mcp_closed")}async control(runtimeSessionId,value,allowTool=false){const control=parseManagedMcpControl(value);this.assertScope(control.sessionKey);if(control.kind==="mcp-invoke"&&control.request.kind==="tool_call"&&!allowTool)throw new ManagedMcpError("managed_mcp_tool_requires_execution");if(control.kind==="mcp-status"||control.kind==="mcp-cancel"){const existing2=this.operations.get(`${scope(control.sessionKey)}\0${control.targetOperationId}`);if(!existing2||existing2.runtimeSessionId!==runtimeSessionId)return{operationId:control.targetOperationId,state:"outcome_unknown"};return structuredClone(existing2.view)}if(!("grant"in control))throw new ManagedMcpError("managed_mcp_invalid");const key=`${scope(control.sessionKey)}\0${control.operationId}`;const{grant:_grant,...effect}=control;const content=fingerprint(effect);const existing=this.operations.get(key);if(existing){if(existing.runtimeSessionId!==runtimeSessionId||existing.fingerprint!==content)throw new ManagedMcpError("managed_mcp_operation_conflict");return structuredClone(existing.view)}if(this.closing)throw new ManagedMcpError("managed_mcp_closed");this.assertAdmission(control);const phase=control.kind.slice(4);const grant=parseOperationGrant(control.grant);if((control.kind==="mcp-configure"||control.kind==="mcp-invoke"&&control.request.kind!=="tool_call")&&grant.operationId!==control.operationId||scope(grant.sessionKey)!==scope(control.sessionKey)||grant.workspaceGeneration!==this.workspace.workspaceGeneration||grant.domain!==(control.kind==="mcp-invoke"&&control.request.kind!=="tool_call"?"mcp_operation":"mcp_configuration"))throw new ManagedMcpError("managed_mcp_grant_invalid");try{this.gates.install(grant);this.grantInstalled=true}catch{throw new ManagedMcpError("managed_mcp_grant_invalid")}if(!this.gates.admits(control.sessionKey,grant.operationId,phase,Date.now()))throw new ManagedMcpError("managed_mcp_grant_invalid");let directory;if(control.kind!=="mcp-release"){this.pendingStarts++;try{directory=await this.sessionDirectory(runtimeSessionId)}finally{this.pendingStarts--}}if(!directory&&control.kind!=="mcp-release")throw new ManagedMcpError("managed_mcp_session_unavailable");if(this.operations.has(key))return this.control(runtimeSessionId,control,allowTool);this.assertAdmission(control);if(this.closing||!this.gates.admits(control.sessionKey,grant.operationId,phase,Date.now()))throw new ManagedMcpError("managed_mcp_grant_invalid");let resolve=__name(()=>void 0,"resolve");const done=new Promise(complete=>{resolve=complete});const operation={fingerprint:content,runtimeSessionId,control,view:{operationId:control.operationId,state:"running"},done,resolve};this.operations.set(key,operation);if(control.kind==="mcp-invoke"){this.invoke(operation,control)}else{void this.configureOrMaintain(operation,directory).catch(error=>{this.settled(operation,{error:{code:error instanceof ManagedMcpError?error.code:"managed_mcp_connection_failed"}})})}return structuredClone(operation.view)}async invokeTool(runtimeSessionId,input){const control=parseManagedMcpControl(input);if(control.kind!=="mcp-invoke"||control.request.kind!=="tool_call")throw new ManagedMcpError("managed_mcp_invalid");await this.control(runtimeSessionId,control,true);const operation=this.operations.get(`${scope(control.sessionKey)}\0${control.operationId}`);await operation.done;return structuredClone(operation.view)}hasHolds(runtimeSessionId){return[...this.connections.values()].some(entry=>entry.runtimeSessionId===runtimeSessionId&&(!entry.closed||entry.pending.size>0))}toolStatus(runtimeSessionId,input){const control=parseManagedMcpControl(input);const operation=this.operations.get(`${scope(control.sessionKey)}\0${control.operationId}`);return operation?.runtimeSessionId===runtimeSessionId?structuredClone(operation.view):{operationId:control.operationId,state:"outcome_unknown"}}cancelTool(runtimeSessionId,input){const control=parseManagedMcpControl(input);void this.control(runtimeSessionId,{kind:"mcp-cancel",sessionKey:control.sessionKey,operationId:control.operationId,targetOperationId:control.operationId})}async close(){this.closing=true;await Promise.allSettled([...this.connections.values()].map(entry=>this.closeConnection(entry)))}assertScope(key){if(key.tenantId!==this.workspace.tenantId||key.workspaceId!==this.workspace.workspaceId)throw new ManagedMcpError("managed_mcp_scope_conflict")}connection(operation,control){if(!("serverId"in control)||!("connectionGeneration"in control))throw new ManagedMcpError("managed_mcp_invalid");const connection=this.connections.get(bindingKey(operation.runtimeSessionId,control.serverId,control.serverRevision,control.connectionGeneration));if(!connection||connection.closed&&control.kind!=="mcp-release"||scope(connection.sessionKey)!==scope(control.sessionKey)||!("connectionGeneration"in control)||connection.generation!==control.connectionGeneration)throw new ManagedMcpError("managed_mcp_binding_conflict");if("grant"in control&&(control.kind!=="mcp-invoke"||control.request.kind==="tool_call")&&control.grant.operationId!==connection.configurationOperationId)throw new ManagedMcpError("managed_mcp_grant_invalid");return connection}async configureOrMaintain(operation,directory){const control=operation.control;if(control.kind==="mcp-configure"){const definition=this.definitions.servers.find(item=>item.tenantId===control.sessionKey.tenantId&&item.workspaceId===control.sessionKey.workspaceId&&item.serverId===control.serverId&&item.serverRevision===control.serverRevision);if(!definition||definition.definitionDigest!==control.definitionDigest)throw new ManagedMcpError("managed_mcp_definition_unavailable");const siblings=[...this.connections.values()].filter(entry=>entry.runtimeSessionId===operation.runtimeSessionId&&entry.definition.serverId===control.serverId);if(siblings.some(entry=>entry.configRevision>=control.configRevision||entry.definition.serverRevision>control.serverRevision))throw new ManagedMcpError("managed_mcp_revision_conflict");if([...this.connections.values()].filter(entry=>!entry.closed).length>=MANAGED_MCP_MAX_CONNECTIONS)throw new ManagedMcpError("managed_mcp_connection_quota");const transport=definition.transport==="stdio"?new StdioClientTransport({command:definition.command,args:definition.args,cwd:directory,stderr:"pipe",env:{...Object.fromEntries(DEFAULT_INHERITED_ENV_VARS.map(key=>[key,""])),PATH:process.env["PATH"]??"",HOME:directory,USERPROFILE:directory,...process.env["SystemRoot"]?{SYSTEMROOT:process.env["SystemRoot"]}:{},...definition.env}}):definition.transport==="streamable-http"?new StreamableHTTPClientTransport(new URL(definition.url),{requestInit:{headers:definition.headers,redirect:"error"}}):new SSEClientTransport(new URL(definition.url),{requestInit:{headers:definition.headers,redirect:"error"},eventSourceInit:{fetch:__name((url,init)=>fetch(url,{...init,redirect:"error"}),"fetch")}});const client=new Client({name:"qwen-managed-mcp",version:"1"},{capabilities:{}});if(transport instanceof StdioClientTransport)transport.stderr?.on("data",()=>void 0);let confirmClose=__name(()=>void 0,"confirmClose");const closeDone=new Promise(resolve=>{confirmClose=resolve});const connection={runtimeSessionId:operation.runtimeSessionId,sessionKey:control.sessionKey,definition,client,transport,pending:new Map,drained:new Set,closeDone,configRevision:control.configRevision,configurationOperationId:control.grant.operationId,generation:++this.generation,catalogChanges:{tools:0,resources:0,prompts:0},retiring:false,closed:false};operation.connection=connection;this.connections.set(bindingKey(operation.runtimeSessionId,control.serverId,control.serverRevision,connection.generation),connection);client.onclose=()=>{connection.closed=true;confirmClose();for(const pending of connection.pending.values())this.unknown(pending,"managed_mcp_connection_lost")};client.onerror=()=>{connection.retiring=true;if(connection.pending.size===0)void this.closeConnection(connection).catch(()=>void 0)};try{await client.connect(transport,{timeout:TIMEOUT_MS});const onmessage=transport.onmessage;transport.onmessage=message=>{if("method"in message){const changed={"notifications/tools/list_changed":"tools","notifications/resources/list_changed":"resources","notifications/prompts/list_changed":"prompts"};const kind=Object.hasOwn(changed,message.method)?changed[message.method]:void 0;if(kind){connection.catalogChanges[kind]++;if(connection.catalog)connection.catalog={...connection.catalog,catalogRevision:connection.catalog.catalogRevision+1,discovery:{...connection.catalog.discovery,[kind]:"stale"}}}}if("id"in message&&typeof message.id==="string"&&!("method"in message)){const pending=connection.pending.get(message.id);if(pending)this.receive(pending,message);return}onmessage(message)};await this.discover(connection);for(const sibling of siblings){sibling.retiring=true;if(sibling.pending.size===0)await this.closeConnection(sibling).catch(()=>void 0)}this.settled(operation,{catalog:connection.catalog})}catch{try{await this.closeConnection(connection)}catch{this.unknown(operation,"managed_mcp_drain_unknown");return}throw new ManagedMcpError("managed_mcp_connection_failed")}}else if(control.kind==="mcp-discover"){const connection=this.connection(operation,control);if(connection.retiring)throw new ManagedMcpError("managed_mcp_retiring");if(!connection.catalog||Object.values(connection.catalog.discovery).some(state=>state==="stale"||state==="failed"))await this.discover(connection);this.settled(operation,{catalog:connection.catalog})}else if(control.kind==="mcp-release"){const connection=this.connection(operation,control);connection.retiring=true;operation.timer=setTimeout(()=>this.unknown(operation,"managed_mcp_drain_unknown"),TIMEOUT_MS);while(connection.pending.size>0){await new Promise(resolve=>connection.drained.add(resolve))}try{await this.closeConnection(connection)}catch{this.unknown(operation,"managed_mcp_drain_unknown");void connection.closeDone.then(()=>this.settled(operation,{response:{released:true}}));return}this.settled(operation,{response:{released:true}})}}async discover(connection){connection.catalogWork=(connection.catalogWork??Promise.resolve()).then(()=>this.refreshCatalog(connection));return connection.catalogWork}async refreshCatalog(connection){const previous=connection.catalog;const changes={...connection.catalogChanges};const lists=await Promise.all([this.list(connection.client,"tools",ListToolsResultSchema),this.list(connection.client,"resources",ListResourcesResultSchema),this.list(connection.client,"prompts",ListPromptsResultSchema)]);const values=lists.map((result,index)=>result.state==="failed"&&previous&&[previous.discovery.tools,previous.discovery.resources,previous.discovery.prompts][index]!=="failed"?{values:[previous.tools,previous.resources,previous.prompts][index],state:"stale"}:result);const catalog={serverId:connection.definition.serverId,serverRevision:connection.definition.serverRevision,definitionDigest:connection.definition.definitionDigest,configRevision:connection.configRevision,connectionGeneration:connection.generation,catalogRevision:connection.catalog?.catalogRevision??0,tools:values[0].values,resources:values[1].values,prompts:values[2].values,discovery:{tools:changes.tools===connection.catalogChanges.tools?values[0].state:"stale",resources:changes.resources===connection.catalogChanges.resources?values[1].state:"stale",prompts:changes.prompts===connection.catalogChanges.prompts?values[2].state:"stale"}};if(fingerprint(catalog)!==fingerprint(connection.catalog??null))connection.catalog={...catalog,catalogRevision:catalog.catalogRevision+1}}async list(client,kind,schema){const values=[];const cursors=new Set;let cursor;try{do{if(cursors.size>=MAX_CATALOG_PAGES)throw new Error("pages");const result=await client.request({method:`${kind}/list`,params:cursor?{cursor}:{}},schema,{timeout:TIMEOUT_MS});const entries=result[kind];for(const entry of entries){const fields=kind==="tools"?["name","description","inputSchema"]:kind==="resources"?["name","uri","description","mimeType"]:["name","description","arguments"];const value=Object.fromEntries(fields.filter(name=>entry[name]!==void 0).map(name=>[name,entry[name]]));if(Buffer.byteLength(JSON.stringify([...values,value]))>MAX_CATALOG_CATEGORY_BYTES)throw new Error("limit");values.push(value)}cursor=result.nextCursor;if(cursor&&cursors.has(cursor))throw new Error("cursor");if(cursor)cursors.add(cursor)}while(cursor);return{values,state:"complete"}}catch(error){if(objectOrUndefined(error)?.["code"]===-32601&&values.length===0)return{values,state:"complete"};return{values,state:values.length>0?"partial":"failed"}}}invoke(operation,control){let connection;try{connection=this.connection(operation,control);const catalog=connection.catalog;if(connection.retiring||!catalog||catalog.configRevision!==control.configRevision||catalog.catalogRevision!==control.catalogRevision)throw new ManagedMcpError("managed_mcp_catalog_conflict");const request=control.request;const permitted=request.kind==="tool_call"?["complete","partial"].includes(catalog.discovery.tools)&&catalog.tools.some(tool=>tool.name===request.name):request.kind==="resource_read"?["complete","partial"].includes(catalog.discovery.resources)&&catalog.resources.some(resource=>resource.uri===request.uri):["complete","partial"].includes(catalog.discovery.prompts)&&catalog.prompts.some(prompt=>prompt.name===request.name);if(!permitted)throw new ManagedMcpError("managed_mcp_capability_unavailable");if([...this.connections.values()].reduce((count,entry)=>count+(entry.closed?0:[...entry.pending.values()].filter(pending=>pending.awaitingReply).length),0)>=MAX_INFLIGHT)throw new ManagedMcpError("managed_mcp_inflight_quota");operation.connection=connection;operation.awaitingReply=true;connection.pending.set(control.operationId,operation);operation.timer=setTimeout(()=>this.unknown(operation,"managed_mcp_timeout"),connection.definition.timeoutMs??REQUEST_TIMEOUT_MS);const method=request.kind==="tool_call"?"tools/call":request.kind==="resource_read"?"resources/read":"prompts/get";const params=request.kind==="resource_read"?{uri:request.uri}:{name:request.name,arguments:request.arguments};void connection.transport.send({jsonrpc:"2.0",id:control.operationId,method,params}).catch(()=>this.unknown(operation,"managed_mcp_send_unknown"))}catch(error){this.settled(operation,{error:{code:error instanceof ManagedMcpError?error.code:"managed_mcp_invalid"}})}}receive(operation,message){operation.awaitingReply=false;const control=operation.control;if(message.error!==void 0){this.settled(operation,{error:{code:"managed_mcp_remote_error"}})}else{try{const schema=control.request.kind==="tool_call"?CallToolResultSchema:control.request.kind==="resource_read"?ReadResourceResultSchema:GetPromptResultSchema;const result=schema.parse(message.result);if(Buffer.byteLength(JSON.stringify(result))>MAX_RESULT_BYTES){this.settled(operation,{error:{code:"managed_mcp_output_limit"}});return}this.settled(operation,{response:result})}catch{this.unknown(operation,"managed_mcp_response_invalid")}}}settled(operation,result){if(operation.timer)clearTimeout(operation.timer);operation.connection?.pending.delete(operation.control.operationId);if(operation.connection?.pending.size===0){for(const resolve of operation.connection.drained)resolve();operation.connection.drained.clear();if(operation.connection.retiring&&!operation.connection.closed)void this.closeConnection(operation.connection).catch(()=>void 0)}operation.view={operationId:operation.control.operationId,state:"settled",...result};operation.resolve()}unknown(operation,code){if(operation.view.state==="settled")return;if(operation.timer)clearTimeout(operation.timer);operation.view={operationId:operation.control.operationId,state:"outcome_unknown",error:{code}};operation.resolve()}closeConnection(connection){if(connection.closed)return Promise.resolve();connection.closing??=this.drainConnection(connection).finally(()=>{connection.closing=void 0});return connection.closing}async drainConnection(connection){connection.retiring=true;let timer;try{await Promise.race([(async()=>{if(connection.transport instanceof StreamableHTTPClientTransport){let terminationTimer;try{await Promise.race([connection.transport.terminateSession().catch(()=>void 0),new Promise(resolve=>{terminationTimer=setTimeout(resolve,1e3)})])}finally{if(terminationTimer)clearTimeout(terminationTimer)}}await connection.client.close();await connection.closeDone})(),new Promise((_,reject)=>{timer=setTimeout(()=>reject(new ManagedMcpError("managed_mcp_drain_unknown")),5e3)})])}finally{if(timer)clearTimeout(timer)}}};function objectOrUndefined(value){return value!==null&&typeof value==="object"?value:void 0}__name(objectOrUndefined,"objectOrUndefined");init_esbuild_shims();import{createHash as createHash3}from"node:crypto";var MANAGED_CSI_PROTOCOL="managed-csi/1";var MANAGED_CSI_ATTEST_PATH="/internal/managed-runtime/csi/v1/attest";var MANAGED_CSI_DRAIN_PATH="/internal/managed-runtime/csi/v1/drain";var MANAGED_CSI_ACK_PATH="/internal/managed-runtime/csi/v1/acknowledge";var MANAGED_CSI_WORKER_ACK_PROTOCOL="managed-csi-original-worker-ack/1";var MANAGED_CSI_ACK_LIMIT_BYTES=16*1024;var ManagedCsiAckRequestError=class extends Error{constructor(status){super("Managed CSI acknowledgement conflicts.");this.status=status}static{__name(this,"ManagedCsiAckRequestError")}};function parseManagedCsiAckJson(bytes){const text2=new TextDecoder("utf-8",{fatal:true}).decode(bytes);parseManagedSessionRecordJson(text2,MANAGED_CSI_ACK_LIMIT_BYTES);return JSON.parse(text2,(_key,value,context)=>{if(typeof value==="number"&&(context?.source===void 0||!/^[1-9][0-9]*$/.test(context.source)))throw new Error("Managed CSI acknowledgement JSON is invalid.");return value})}__name(parseManagedCsiAckJson,"parseManagedCsiAckJson");function parseManagedCsiAcknowledgement(value){const ack=closed2(value,["deliveryStatus","executionCallId","historyRevision","manifest"]);const manifest=assertManagedSessionDurableRef(ack["manifest"],"manifest");if(ack["deliveryStatus"]!=="committed"||!Number.isSafeInteger(ack["historyRevision"])||ack["historyRevision"]<1||manifest.kind!=="managed-tool-result-manifest"||manifest.schemaVersion!==1||manifest.byteLength<1||manifest.byteLength>65536)throw new Error;return{executionCallId:stableId(ack["executionCallId"]),manifest,deliveryStatus:"committed",historyRevision:ack["historyRevision"]}}__name(parseManagedCsiAcknowledgement,"parseManagedCsiAcknowledgement");function parseManagedCsiCaptureIdentity(value){const identity=closed2(value,["bindingGeneration","callId","captureId","executionCallId","invocationDigest","revision","sessionId","tenantId","turnId"]);if(!isCanonicalDecimalText(identity["bindingGeneration"])||identity["revision"]!==1||typeof identity["captureId"]!=="string"||!/^[a-z0-9_-]{1,128}$/.test(identity["captureId"])||!invocationDigest(identity["invocationDigest"]))throw new Error;return{tenantId:stableId(identity["tenantId"]),sessionId:stableId(identity["sessionId"]),turnId:stableId(identity["turnId"]),executionCallId:stableId(identity["executionCallId"]),callId:stableId(identity["callId"]),invocationDigest:identity["invocationDigest"],bindingGeneration:identity["bindingGeneration"],captureId:identity["captureId"],revision:1}}__name(parseManagedCsiCaptureIdentity,"parseManagedCsiCaptureIdentity");function parseManagedCsiAckRequest(value,boot,pod){let request;let reference2;let acknowledgement;const context=createManagedContextAttestationResponse(boot.context);try{request=closed2(value,ACK_REQUEST_KEYS);if(typeof request["retirementId"]!=="string"||!/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(request["retirementId"]))throw new Error;const ref2=closed2(request["reference"],["argsDigest","callId","promptId","sessionId"]);if(!invocationDigest(ref2["argsDigest"]))throw new Error;reference2={sessionId:stableId(ref2["sessionId"]),promptId:stableId(ref2["promptId"]),callId:stableId(ref2["callId"]),argsDigest:ref2["argsDigest"]};acknowledgement=parseManagedCsiAcknowledgement(request["acknowledgement"]);closed2(request["context"],Object.keys(context).sort());closed2(request["storage"],STORAGE_KEYS);closed2(request["pod"],["namespace","nodeName","uid"])}catch{throw new ManagedCsiAckRequestError(400)}try{validateManagedCsiPodIdentity(pod,boot.storage.namespace);if(request["protocolVersion"]!==1||request["managedCsi"]!==MANAGED_CSI_PROTOCOL||request["workerAck"]!==MANAGED_CSI_WORKER_ACK_PROTOCOL||boot.context.isolationClass!=="workspace")throw new Error;for(const[key,expected]of[["context",context],["storage",boot.storage],["pod",pod]]){const fields=request[key];if(!Object.entries(expected).every(([name,field])=>fields[name]===field))throw new Error}}catch{throw new ManagedCsiAckRequestError(409)}return{protocolVersion:1,managedCsi:MANAGED_CSI_PROTOCOL,workerAck:MANAGED_CSI_WORKER_ACK_PROTOCOL,retirementId:request["retirementId"],context,storage:{...boot.storage},pod:{...pod},reference:reference2,acknowledgement}}__name(parseManagedCsiAckRequest,"parseManagedCsiAckRequest");function parseManagedCsiAckResponse(value,boot,pod){try{const response=closed2(value,[...ACK_REQUEST_KEYS,"captureIdentity","state"].sort());if(response["state"]!=="ACKNOWLEDGED")throw new Error;const request=parseManagedCsiAckRequest(Object.fromEntries(ACK_REQUEST_KEYS.map(key=>[key,response[key]])),boot,pod);const identity=parseManagedCsiCaptureIdentity(response["captureIdentity"]);if(identity.tenantId!==boot.context.tenantId||identity.executionCallId!==request.acknowledgement.executionCallId||identity.callId!==request.reference.callId||identity.invocationDigest!==request.reference.argsDigest)throw new Error;return{...request,state:"ACKNOWLEDGED",captureIdentity:identity}}catch{throw new ManagedCsiAckRequestError(409)}}__name(parseManagedCsiAckResponse,"parseManagedCsiAckResponse");var ACK_REQUEST_KEYS=["acknowledgement","context","managedCsi","pod","protocolVersion","reference","retirementId","storage","workerAck"];function stableId(value){return assertManagedSessionStableId(value,"id")}__name(stableId,"stableId");function invocationDigest(value){return typeof value==="string"&&/^(?:sha256:)?[0-9a-f]{64}$/.test(value)}__name(invocationDigest,"invocationDigest");function createManagedCsiAttestationRequest(boot){return Object.freeze({protocolVersion:1,managedCsi:MANAGED_CSI_PROTOCOL,provisionRequestId:boot.context.provisionRequestId,physicalKey:boot.storage.physicalKey,registrationRevision:boot.storage.registrationRevision,reservationId:boot.storage.reservationId,reservationRevision:boot.storage.reservationRevision})}__name(createManagedCsiAttestationRequest,"createManagedCsiAttestationRequest");var ManagedCsiDrainRequestError=class extends Error{constructor(status){super("Managed CSI drain request is invalid.");this.status=status}static{__name(this,"ManagedCsiDrainRequestError")}};function parseManagedCsiDrainRequest(value,boot,pod){let request;try{request=closed2(value,["context","managedCsi","operation","pod","protocolVersion","retirementId","storage"]);if(request["operation"]!=="seal"&&request["operation"]!=="status"||typeof request["retirementId"]!=="string"||!/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(request["retirementId"]))throw new Error}catch{throw new ManagedCsiDrainRequestError(400)}try{validateManagedCsiPodIdentity(pod,boot.storage.namespace);if(request["protocolVersion"]!==1||request["managedCsi"]!==MANAGED_CSI_PROTOCOL)throw new Error;for(const[key,expected]of[["context",createManagedContextAttestationResponse(boot.context)],["storage",boot.storage],["pod",pod]]){const actual=closed2(request[key],Object.keys(expected).sort());if(!Object.entries(expected).every(([name,field])=>actual[name]===field))throw new Error}}catch{throw new ManagedCsiDrainRequestError(409)}return{operation:request["operation"],retirementId:request["retirementId"]}}__name(parseManagedCsiDrainRequest,"parseManagedCsiDrainRequest");function validateManagedCsiAttestationRequest(value,boot){const expected=createManagedCsiAttestationRequest(boot);try{const actual=closed2(value,Object.keys(expected).sort());if(!Object.entries(expected).every(([key,field])=>actual[key]===field))throw new Error}catch{throw new Error("Managed CSI attestation request is invalid.")}}__name(validateManagedCsiAttestationRequest,"validateManagedCsiAttestationRequest");function validateManagedCsiPodIdentity(value,namespace){const pod=closed2(value,["namespace","nodeName","uid"]);if(typeof pod["uid"]!=="string"||!/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(pod["uid"])||pod["namespace"]!==namespace||typeof pod["nodeName"]!=="string"||pod["nodeName"].length>253||!pod["nodeName"].split(".").every(label=>/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(label)))throw new Error("Managed CSI Pod identity is unavailable.")}__name(validateManagedCsiPodIdentity,"validateManagedCsiPodIdentity");function validateManagedCsiAttestationResponse(value,boot,expectedPod){try{validateManagedCsiPodIdentity(expectedPod,boot.storage.namespace);const response=closed2(value,["context","managedCsi","mount","pod","protocolVersion","storage"]);const context=createManagedContextAttestationResponse(boot.context);for(const[key,expected]of[["context",context],["storage",boot.storage],["pod",expectedPod]]){const fields=closed2(response[key],Object.keys(expected).sort());if(!Object.entries(expected).every(([name,field])=>fields[name]===field))throw new Error}const mount=closed2(response["mount"],["device","diskSerial","mountId","rootDevice","rootInode","source"]);if(response["protocolVersion"]!==1||response["managedCsi"]!==MANAGED_CSI_PROTOCOL||!unsignedDecimal(mount["mountId"],0xffffffffn,true)||typeof mount["source"]!=="string"||mount["source"].length>128||!/^\/dev\/nvme(?:0|[1-9][0-9]*)n[1-9][0-9]*$/.test(mount["source"])||mount["diskSerial"]!==boot.storage.diskSerial||!unsignedDecimal(mount["rootDevice"],0xffffffffffffffffn,false)||!unsignedDecimal(mount["rootInode"],0xffffffffffffffffn,true)||linuxDeviceNumber(mount["device"])!==mount["rootDevice"])throw new Error}catch{throw new Error("Managed CSI attestation response is invalid.")}}__name(validateManagedCsiAttestationResponse,"validateManagedCsiAttestationResponse");function linuxDeviceNumber(value){if(typeof value!=="string")throw new Error;const parts=value.split(":");if(parts.length!==2||!parts.every(part=>unsignedDecimal(part,0xffffffffn,false)))throw new Error;const major=BigInt(parts[0]);const minor=BigInt(parts[1]);return((major&0xfffn)<<8n|(major&0xfffff000n)<<32n|minor&0xffn|(minor&0xffffff00n)<<12n).toString()}__name(linuxDeviceNumber,"linuxDeviceNumber");function unsignedDecimal(value,maximum,positive3){return typeof value==="string"&&/^(?:0|[1-9][0-9]{0,19})$/.test(value)&&(!positive3||value!=="0")&&BigInt(value)<=maximum}__name(unsignedDecimal,"unsignedDecimal");var BOOT_KEYS2=["context","managedCsi","storage","type","version"];var STORAGE_KEYS=["backendDomain","clusterDomain","diskSerial","driver","namespace","physicalKey","pvUid","pvcUid","registrationRevision","reservationId","reservationRevision","volumeHandle"];var INVALID2="Managed CSI boot document is invalid.";function parseManagedCsiBoot(value){try{const boot=closed2(value,BOOT_KEYS2);const storage=closed2(boot["storage"],STORAGE_KEYS);const context=parseManagedContextBoot(boot["context"]);if(boot["type"]!=="boot"||boot["version"]!==3||boot["managedCsi"]!==MANAGED_CSI_PROTOCOL){throw new Error(INVALID2)}for(const[key,maximum]of[["clusterDomain",256],["backendDomain",256],["volumeHandle",512],["pvcUid",128],["pvUid",128]]){const text2=storage[key];if(typeof text2!=="string"||text2===""||/^[ \u1680\u2000-\u2006\u2008-\u200a\u2028\u2029\u205f\u3000]+$/u.test(text2)||text2.length>maximum||Array.from(text2).some(char=>char.charCodeAt(0)<=31||char.charCodeAt(0)>=127&&char.charCodeAt(0)<=159)||/[\ud800-\udfff]/u.test(text2))throw new Error(INVALID2)}if(typeof storage["namespace"]!=="string"||!/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(storage["namespace"])||storage["driver"]!=="diskplugin.csi.alibabacloud.com"||typeof storage["diskSerial"]!=="string"||!/^[A-Za-z0-9._:-]{1,128}$/.test(storage["diskSerial"])||!isCanonicalDecimalText(storage["registrationRevision"])||!isCanonicalDecimalText(storage["reservationRevision"])||typeof storage["reservationId"]!=="string"||!/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(storage["reservationId"])||typeof storage["physicalKey"]!=="string"||!/^[0-9a-f]{64}$/.test(storage["physicalKey"])||!context.mountRoot.startsWith("/")||context.mountRoot.length>2048||context.mountRoot.includes("\\")||!context.mountRoot.slice(1).split("/").every(part=>part!==""&&part!=="."&&part!=="..")||physicalKey(storage["backendDomain"],storage["driver"],storage["volumeHandle"])!==storage["physicalKey"])throw new Error(INVALID2);return Object.freeze({type:"boot",version:3,managedCsi:MANAGED_CSI_PROTOCOL,context,storage:Object.freeze({...storage})})}catch{throw new Error(INVALID2)}}__name(parseManagedCsiBoot,"parseManagedCsiBoot");function physicalKey(backend,driver,handle){const hash=createHash3("sha256");for(const field of["qwen-csi-physical/1",backend,driver,handle]){const bytes=Buffer.from(field,"utf8");const size=Buffer.alloc(4);size.writeUInt32BE(bytes.byteLength);hash.update(size).update(bytes)}return hash.digest("hex")}__name(physicalKey,"physicalKey");function closed2(value,keys){if(!value||typeof value!=="object"||Array.isArray(value))throw new Error(INVALID2);const fields=Object.keys(value).sort();if(fields.length!==keys.length||!fields.every((field,index)=>field===keys[index]))throw new Error(INVALID2);return value}__name(closed2,"closed");init_esbuild_shims();import{spawn}from"node:child_process";import{readFileSync as readFileSync2}from"node:fs";import{join}from"node:path";var ManagedChildRunProcess=class{constructor(unitName,unit,child){this.unitName=unitName;this.unit=unit;this.child=child;child.on("error",()=>void 0);child.on("exit",(code,signal)=>{this.exitEvidence={exitCode:code,exitSignal:typeof signal==="string"?signal:null}})}static{__name(this,"ManagedChildRunProcess")}exitEvidence=null;settled=false;get exited(){return this.evidence!==null}get evidence(){if(this.exitEvidence!==null)return this.exitEvidence;if(this.child.exitCode!==null||this.child.signalCode!==null){return{exitCode:this.child.exitCode,exitSignal:this.child.signalCode}}return null}async terminate(graceMs){if(this.settled)return this.evidence;if(this.exited&&this.unit.empty()){this.unit.remove();this.settled=true;return this.evidence}try{await this.unit.terminate(graceMs)}catch(error){if(!this.settled)throw error}if(this.settled)return this.evidence;if(!this.unit.empty())return null;this.unit.remove();this.settled=true;return this.evidence}async settleOnEmpty(){if(this.settled)return this.evidence;if(!this.exited)return null;await this.unit.waitForEmpty(Number.MAX_SAFE_INTEGER/2,()=>this.settled);if(this.settled)return this.evidence;if(!this.unit.empty())return null;this.unit.remove();this.settled=true;return this.evidence}};var ManagedChildRunSupervisor=class _ManagedChildRunSupervisor{constructor(cgroupRoot){this.cgroupRoot=cgroupRoot}static{__name(this,"ManagedChildRunSupervisor")}processes=new Map;static create(options){if(options.cgroupRoot===void 0)throw new HookCommandIsolationUnavailableError("root_missing");return new _ManagedChildRunSupervisor(options.cgroupRoot)}get size(){return this.processes.size}process(unitName){return this.processes.get(unitName)}async start(spec,membership){const unit=HookCommandCgroup.create(this.cgroupRoot,spec.unitName);const launch=unit.launch(spec.executable,[...spec.args],spec.env);const child=spawn(launch.executable,launch.args,{cwd:spec.cwd,env:launch.env,stdio:["ignore","pipe","pipe","pipe"]});child.on("error",()=>void 0);child.stdout?.on("data",chunk=>spec.onOutput("stdout",chunk));child.stderr?.on("data",chunk=>spec.onOutput("stderr",chunk));let status="";child.stdio[3]?.on("data",data=>{status+=data.toString()});const prove=membership?.prove??(async(launched,inUnit)=>{for(let attempt=0;attempt<40;attempt++){if(status.includes("joined\n"))return true;if(status.includes("unavailable\n"))return false;try{const members=readFileSync2(join(inUnit.directory,"cgroup.procs"),"utf8");if(launched.pid!==void 0&&members.split("\n").includes(String(launched.pid))){return true}}catch{}await new Promise(resolve=>setTimeout(resolve,50))}return false});if(!await prove(child,unit)){child.kill("SIGKILL");unit.remove();throw new HookCommandIsolationUnavailableError("membership_unproven")}const process_=new ManagedChildRunProcess(spec.unitName,unit,child);this.processes.set(spec.unitName,process_);return process_}attach(unitName){return HookCommandCgroup.attach(this.cgroupRoot,unitName)}forget(unitName){this.processes.delete(unitName)}};init_esbuild_shims();import{once}from"node:events";import{setTimeout as delay}from"node:timers/promises";import{constants}from"node:os";var ManagedBackgroundShellRegistry=class{constructor(eofGraceMs=5e3){this.eofGraceMs=eofGraceMs}static{__name(this,"ManagedBackgroundShellRegistry")}entries=new Map;finished=new Map;get size(){return this.entries.size}hasHolds(sessionId){return this.countBySession(sessionId)>0}countBySession(sessionId){let count=0;for(const entry of this.entries.values()){if(entry.sessionId===sessionId)count++}return count}describe(unitName){const entry=this.entries.get(unitName);return entry?{sessionId:entry.sessionId}:void 0}describeFinished(unitName){return this.finished.get(unitName)}register(params){const entry={...params,stopRequested:false,completion:void 0};entry.completion=this.complete(entry);this.entries.set(params.unitName,entry);return entry.completion}receipt(unitName){return this.entries.get(unitName)?.completion}async terminate(unitName,graceMs){const entry=this.entries.get(unitName);if(!entry)return void 0;entry.stopRequested=true;const evidence=await entry.process.terminate(graceMs);if(evidence===null){return{unitName,evidence:null,captureError:null}}return entry.completion}async stopAll(graceMs){const completions=[...this.entries.values()].map(async entry=>{await this.terminate(entry.unitName,graceMs)});await Promise.allSettled(completions)}async stopSession(sessionId,graceMs){await Promise.allSettled([...this.entries.values()].filter(entry=>entry.sessionId===sessionId).map(async entry=>{await this.terminate(entry.unitName,graceMs)}))}async complete(entry){const{unitName,process:process2,sink,publisher,identity}=entry;let evidence=null;let captureError=null;try{const ended=process2.exited&&process2.evidence!==null?Promise.resolve(process2.evidence):new Promise(resolve=>{process2.child.once("exit",()=>resolve(process2.evidence));process2.child.once("error",cause=>{captureError??=cause instanceof Error?cause.message:String(cause);resolve(null)})});const root=await ended;evidence=root===null?null:await process2.settleOnEmpty();const eof={stdout:false,stderr:false};await Promise.all(["stdout","stderr"].map(async name=>{const stream=process2.child[name];if(!stream||stream.readableEnded){eof[name]=true;return}await Promise.race([once(stream,"end").then(()=>{eof[name]=true}),delay(this.eofGraceMs)])}));sink.setStarted(process2.child.pid??0);sink.setProcessResult({rawOutput:Buffer.alloc(0),output:"",exitCode:evidence?.exitCode??null,signal:signalNumber(evidence?.exitSignal??null),error:null,aborted:false,pid:process2.child.pid,executionMethod:"child_process"});if(entry.stopRequested)sink.setStopRequested();await sink.finish("stdout",eof.stdout&&evidence!==null);await sink.finish("stderr",eof.stderr&&evidence!==null);const envelope=await sink.finalize(evidence?.exitCode===0?"success":"error",[],evidence?.exitCode===0?void 0:{message:evidence===null?"Background Shell ended without exit evidence.":evidence.exitSignal!==null?`Background Shell terminated with ${evidence.exitSignal}.`:"Background Shell exited nonzero."});try{if(publisher.finish){await publisher.finish(identity,envelope)}else if(publisher.accept){const receipt3=await publisher.accept(identity,envelope);void receipt3}}catch(cause){captureError=cause instanceof Error?cause.message:String(cause)}}catch(cause){captureError??=cause instanceof Error?cause.message:String(cause)}finally{this.entries.delete(unitName)}const receipt2={unitName,evidence,captureError};this.finished.set(entry.unitName,{sessionId:entry.sessionId,receipt:receipt2});return receipt2}};function signalNumber(name){if(name===null)return null;const number=constants.signals[name];return typeof number==="number"?number:null}__name(signalNumber,"signalNumber");init_esbuild_shims();var ManagedMonitorRegistry=class{static{__name(this,"ManagedMonitorRegistry")}physical;constructor(eofGraceMs){this.physical=new ManagedBackgroundShellRegistry(eofGraceMs)}get size(){return this.physical.size}hasHolds(sessionId){return this.physical.hasHolds(sessionId)}countBySession(sessionId){return this.physical.countBySession(sessionId)}register(params){return this.physical.register(params)}describe(unitName){return this.physical.describe(unitName)}describeFinished(unitName){return this.physical.describeFinished(unitName)}async terminate(unitName,graceMs){return this.physical.terminate(unitName,graceMs)}async stopSession(sessionId,graceMs){await this.physical.stopSession(sessionId,graceMs)}async stopAll(graceMs){await this.physical.stopAll(graceMs)}};init_esbuild_shims();import{randomUUID}from"node:crypto";import{StringDecoder}from"node:string_decoder";var MONITOR_PARTIAL_LINE_CAP_BYTES=4096;var ManagedMonitorWatcher=class{constructor(supervisor){this.supervisor=supervisor}static{__name(this,"ManagedMonitorWatcher")}async start(command,onLine,onExit,identity){const text2=command["command"];if(typeof text2!=="string"||text2.length===0)throw new Error("Monitor watch names no command.");const shell=getShellConfiguration();const unitName=identity?.unitName??`qwen-mon-${randomUUID()}`;const cwd=identity?.cwd??process.cwd();const decoder=new StringDecoder("utf8");let remainder="";const watch=await this.supervisor.start({unitName,executable:shell.executable,args:[...shell.argsPrefix,text2],env:sanitizeChildEnv(),cwd,onOutput:__name((stream,chunk)=>{identity?.onChunk?.(stream,chunk);if(stream!=="stdout")return;remainder+=decoder.write(chunk);let at=remainder.indexOf("\n");while(at>=0){const line=remainder.slice(0,at);remainder=remainder.slice(at+1);if(line.length>0)onLine(line);at=remainder.indexOf("\n")}if(remainder.length>MONITOR_PARTIAL_LINE_CAP_BYTES)remainder=""},"onOutput")});let exited=false;const end=__name(failed=>{if(exited)return;exited=true;remainder+=decoder.end();if(remainder.length>0){onLine(remainder);remainder=""}onExit(failed)},"end");watch.child.once("exit",()=>end(false));watch.child.once("error",()=>end(true));if(watch.child.exitCode!=null||watch.child.signalCode!=null)setImmediate(()=>end(false));return{receipt:{unitName,pid:watch.child.pid??0,started:true},process:watch,terminate:__name(async()=>await watch.terminate(5e3)!==null,"terminate")}}};var debugLogger=createDebugLogger("MANAGED_TOOL_EXECUTOR");var ManagedMcpToolUnknownError=class extends Error{static{__name(this,"ManagedMcpToolUnknownError")}};var ISOLATION_REFUSAL_CLAUSES={platform:"this Runtime does not run Linux with cgroup v2",root_missing:"no delegated cgroup v2 root is configured on this Runtime",root_shape:"the delegated root on this Runtime is not a cgroup v2 domain directory",root_unreadable:"the delegated cgroup v2 root on this Runtime is missing or unreadable",unit_name_invalid:"its cgroup unit name is not valid on this Runtime",unit_name_taken:"a cgroup unit with the same name already exists on this Runtime",unit_not_empty:"another unit still holds processes under that name on this Runtime",membership_unproven:"the process never proved its cgroup membership on this Runtime"};function isolationRefusal(tool,cause){const{reason}=cause;if(reason===void 0)return{message:`${tool} requires a delegated Linux cgroup v2 directory on this Runtime.`};return{message:`${tool} requires a delegated Linux cgroup v2 directory: ${ISOLATION_REFUSAL_CLAUSES[reason]}.`,type:`managed_isolation_${reason}`}}__name(isolationRefusal,"isolationRefusal");var MANAGED_WORKSPACE_CONTEXT_FILE_BYTES=MANAGED_WORKSPACE_CONTEXT_FILE_CHARS*4;async function readContextFilePrefix(file){const handle=await fs.open(file,"r");try{const buffer=Buffer.allocUnsafe(MANAGED_WORKSPACE_CONTEXT_FILE_BYTES);const{bytesRead}=await handle.read(buffer,0,MANAGED_WORKSPACE_CONTEXT_FILE_BYTES,0);return buffer.toString("utf8",0,bytesRead)}finally{await handle.close()}}__name(readContextFilePrefix,"readContextFilePrefix");var ManagedToolConflictError=class extends Error{constructor(message,code="managed_runtime_identity_conflict"){super(message);this.code=code}static{__name(this,"ManagedToolConflictError")}};var ManagedToolInvalidError=class extends Error{static{__name(this,"ManagedToolInvalidError")}};var ManagedToolUnavailableError=class extends Error{static{__name(this,"ManagedToolUnavailableError")}code="managed_context_unavailable"};var ADMITTED_TOOL_NAMES=new Set([ReadFileTool.Name,WriteFileTool.Name,EditTool.Name,ShellTool.Name,GlobTool.Name]);var MANAGED_BACKGROUND_MAX_SHELLS=8;var MANAGED_MONITOR_MAX_WATCHES=4;var MANAGED_BACKGROUND_OUTPUT_PAUSE_BYTES=16*1024*1024;var MANAGED_BACKGROUND_OUTPUT_RESUME_BYTES=4*1024*1024;var ManagedToolExecutor=class _ManagedToolExecutor{constructor(toolsFor,capturePublisher,mcp,hooks,ownsAnotherSessionDir,backgroundSupervisor,backgroundRegistry,monitorRegistry,options={}){this.toolsFor=toolsFor;this.capturePublisher=capturePublisher;this.mcp=mcp;this.hooks=hooks;this.ownsAnotherSessionDir=ownsAnotherSessionDir;this.backgroundSupervisor=backgroundSupervisor;this.options=options;this.backgroundRegistry=backgroundRegistry??new ManagedBackgroundShellRegistry;this.monitorRegistry=monitorRegistry??new ManagedMonitorRegistry;this.monitorWatcher=backgroundSupervisor?new ManagedMonitorWatcher(backgroundSupervisor):void 0}static{__name(this,"ManagedToolExecutor")}entries=new Map;backgroundRegistry;monitorRegistry;monitorWatcher;mcpCalls=new Map;providerSessions=new Set;closedSessions=new Set;provider;closing=false;retirementId;providerWasUsed=false;capturePreparationStarted=false;historyControlOutcomeUnknown=false;pendingStarts=new Set;fileHistories=new Map;historyControls=new Set;get isAdmissionOpen(){return!this.closing&&this.retirementId===void 0}get isAdmissionSealed(){return this.retirementId!==void 0}sealAdmission(retirementId){if(!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(retirementId))throw new ManagedToolInvalidError("Retirement identity is invalid.");if(this.retirementId!==void 0&&this.retirementId!==retirementId)throw new ManagedToolConflictError("Retirement identity conflicts.");this.retirementId=retirementId;this.mcp?.sealAdmission();this.hooks?.sealAdmission()}getDrainObservation(retirementId){if(this.retirementId===void 0||this.retirementId!==retirementId)throw new ManagedToolConflictError("Retirement identity conflicts.");const blockers=new Set;if(this.closing)blockers.add("shutdown_started");if(this.capturePreparationStarted)blockers.add("capture_preparation_unqualified");if(this.capturePublisher?.hasInstalledPublication)blockers.add("publication_lifecycle_unqualified");if(this.historyControlOutcomeUnknown)blockers.add("history_control_outcome_unknown");let pendingInvocations=0;for(const entry of this.entries.values()){if(entry.toolName===ShellTool.Name)blockers.add("shell_lifecycle_unqualified");if(entry.state==="unknown")blockers.add("execution_outcome_unknown");else if(entry.state==="acknowledged")continue;else if(entry.state!=="settled")pendingInvocations++;else if(entry.version===2&&!entry.result)blockers.add("execution_result_missing");else if(entry.version===3){const result=entry.v3Result;if(!result)blockers.add("execution_result_missing");else if(result.executionStatus!=="not_started"){if(result.capture?.captureStatus!=="complete")blockers.add("capture_incomplete");if(result.capture?.deliveryStatus!=="committed"||entry.acknowledgement?.deliveryStatus!=="committed")blockers.add("capture_uncommitted")}}}const provider=this.provider?.getDrainInspection();if(this.providerWasUsed||provider?.hasActivity)blockers.add("provider_lifecycle_unqualified");pendingInvocations+=provider?.pendingInvocations??0;const mcp=this.mcp?.getDrainInspection();if(this.mcpCalls.size>0||mcp?.hasActivity)blockers.add("mcp_lifecycle_unqualified");pendingInvocations+=mcp?.pendingInvocations??0;const hooks=this.hooks?.getDrainInspection();if(hooks?.hasActivity)blockers.add("hook_lifecycle_unqualified");pendingInvocations+=hooks?.pendingInvocations??0;const pendingStarts=this.pendingStarts.size+(mcp?.pendingStarts??0)+(hooks?.pendingStarts??0);return{state:"DRAINING",workState:blockers.size>0?"BLOCKED":pendingStarts>0||pendingInvocations>0?"PENDING":"QUIESCENT",pendingStarts,pendingInvocations,blockers:[...blockers].sort()}}controlFileHistory(ownerSessionId,sessionId,operation){if(this.isAdmissionSealed){const history2=this.fileHistories.get(sessionId);if(operation.action!=="snapshot")return Promise.reject(new ManagedToolUnavailableError("Managed Runtime admission is sealed."));if(!history2||history2.ownerSessionId!==ownerSessionId)return Promise.reject(new ManagedToolConflictError("File history is not bound to this Workspace."));if(this.hasActiveSession(sessionId))return Promise.reject(new ManagedToolConflictError("File history requires an idle Runtime Session."));return Promise.resolve(history2.state())}return this.trackStart(()=>this.controlFileHistoryAdmitted(ownerSessionId,sessionId,operation))}async controlFileHistoryAdmitted(ownerSessionId,sessionId,operation){this.assertLegacySession(sessionId);if(this.closing||this.hasActiveToolSession(sessionId)||operation.action==="rewind"&&this.hooks?.hasHolds(sessionId)===true||[...this.entries.values()].some(entry=>entry.reference.sessionId===sessionId&&entry.state==="unknown"))throw new ManagedToolConflictError("File history requires an idle Runtime Session.");this.historyControls.add(sessionId);let mutationStarted=false;try{const tools=await this.toolsFor({sessionId,promptId:sessionId,callId:"history",argsDigest:""});if(!this.isAdmissionOpen||!tools?.directory||tools.isActive?.()===false)throw new ManagedToolUnavailableError("File history Workspace is unavailable.");const existingHistory=this.fileHistories.get(sessionId);let history2=tools.fileHistory??existingHistory;if(tools.retainedFileHistory&&!tools.fileHistory)throw new ManagedToolConflictError("Retained file history requires its original composition.");if(tools.fileHistory&&(tools.fileHistory.ownerSessionId!==ownerSessionId||tools.fileHistory.directory!==tools.directory||existingHistory&&existingHistory!==tools.fileHistory))throw new ManagedToolConflictError("File history binding conflicts.");if(operation.action==="bind"){if(!history2){history2=new ManagedRuntimeFileHistory(ownerSessionId,tools.directory,operation.state);await history2.ready();if(!this.isAdmissionOpen)throw new ManagedToolUnavailableError("Managed Runtime admission is sealed.");this.fileHistories.set(sessionId,history2)}else if(history2.ownerSessionId!==ownerSessionId||history2.directory!==tools.directory||!isDeepStrictEqual2(history2.state(),operation.state??{ownerSessionId,snapshots:[],files:{}})){throw new ManagedToolConflictError("File history binding conflicts.")}}if(!history2||history2.ownerSessionId!==ownerSessionId||history2.directory!==tools.directory)throw new ManagedToolConflictError("File history is not bound to this Workspace.");this.fileHistories.set(sessionId,history2);if(operation.action==="prepare"){mutationStarted=true;await history2.prepare(operation.promptId,operation.paths)}if(operation.action==="rewind"){mutationStarted=true;const result=await history2.rewind(operation.promptId);if(result.filesFailed.length>0)this.historyControlOutcomeUnknown=true;return result}await history2.ready();return history2.state()}catch(error){if(mutationStarted)this.historyControlOutcomeUnknown=true;throw error}finally{this.historyControls.delete(sessionId)}}async readWorkspaceContext(sessionId){return this.trackStart(()=>this.readWorkspaceContextAdmitted(sessionId))}async readWorkspaceContextAdmitted(sessionId){if(this.closedSessions.has(sessionId))throw new ManagedToolUnavailableError("Workspace context is unavailable.");const tools=await this.toolsFor({sessionId,promptId:sessionId,callId:"workspace-context",argsDigest:""});if(!this.isAdmissionOpen||!tools?.directory||tools.isActive?.()===false)throw new ManagedToolUnavailableError("Workspace context is unavailable.");let boundary;try{boundary=await fs.realpath(tools.directory)}catch{throw new ManagedToolUnavailableError("Workspace context is unavailable.")}const files=[];const seen=new Set;for(const name of MANAGED_WORKSPACE_CONTEXT_FILES){let text2;try{const real=await fs.realpath(path2.join(tools.directory,name));const rel=path2.relative(boundary,real);if(rel===".."||rel.startsWith(`..${path2.sep}`)||path2.isAbsolute(rel))continue;if(await this.ownsAnotherSessionDir?.(tools.sessionId,real,boundary))continue;if(seen.has(real))continue;seen.add(real);const stat=await fs.stat(real);if(!stat.isFile())continue;text2=stat.size>MANAGED_WORKSPACE_CONTEXT_FILE_BYTES?await readContextFilePrefix(real):await fs.readFile(real,"utf8")}catch{continue}if(text2.length>MANAGED_WORKSPACE_CONTEXT_FILE_CHARS){const note="\n[Truncated: the file exceeds the Hosted context limit.]";text2=text2.slice(0,MANAGED_WORKSPACE_CONTEXT_FILE_CHARS-note.length);if(/[\uD800-\uDBFF]$/.test(text2))text2=text2.slice(0,-1);text2+=note}files.push({name,text:text2})}return{files}}static forWorkspace(workspaceCwd,runtimeInstanceId,options){const tools=createManagedToolSet(workspaceCwd,runtimeInstanceId);return new _ManagedToolExecutor(async()=>tools,void 0,void 0,void 0,void 0,void 0,void 0,void 0,options)}hasTool(toolName){return ADMITTED_TOOL_NAMES.has(toolName)||toolName===MANAGED_MCP_TOOL&&this.mcp!==void 0}attachProvider(provider){this.provider=provider}claimProviderSession(sessionId){if(!this.isAdmissionOpen||this.historyControls.has(sessionId)||this.fileHistories.has(sessionId)||this.closedSessions.has(sessionId)||[...this.entries.values()].some(entry=>entry.reference.sessionId===sessionId)||[...this.mcpCalls.values()].some(entry=>entry.reference.sessionId===sessionId)){throw new ManagedToolConflictError("Managed Runtime Session conflicts.")}this.providerWasUsed=true;this.providerSessions.add(sessionId)}unclaimProviderSession(sessionId){this.providerSessions.delete(sessionId)}closeSessionAdmission(sessionId){if(this.hasActiveSession(sessionId)){throw new ManagedToolConflictError("Managed Runtime Session still owns unfinished work.","managed_runtime_owner_hold_pending")}this.closedSessions.add(sessionId);if(this.retirementId===void 0)this.fileHistories.delete(sessionId)}assertLegacySession(sessionId){if(this.historyControls.has(sessionId)||this.providerSessions.has(sessionId)||this.closedSessions.has(sessionId)){throw new ManagedToolConflictError("Managed Runtime protocol conflicts.")}}execute(reference2,toolName,input){return this.trackStart(()=>this.executeAdmitted(reference2,toolName,input))}async executeAdmitted(reference2,toolName,input){this.assertLegacySession(reference2.sessionId);if(this.closing){throw new ManagedToolUnavailableError("Managed Runtime worker is closing.")}if(toolName===MANAGED_MCP_TOOL&&this.mcp){const existing2=this.mcpCalls.get(reference2.callId);const inputJson2=JSON.stringify(input);if(this.entries.has(reference2.callId)||existing2&&(!sameReference(existing2.reference,reference2)||existing2.inputJson!==inputJson2))throw new ManagedToolConflictError("Managed MCP invocation identity conflicts.");if(existing2?.refusal)return existing2.refusal;if(!existing2){this.assertAdmissionOpen();const tools2=await this.toolsFor(reference2);this.assertLegacySession(reference2.sessionId);if(!this.isAdmissionOpen||!tools2||tools2.isActive?.()===false)throw new ManagedToolUnavailableError("Managed MCP Session is unavailable.");if(this.mcpCalls.has(reference2.callId))return this.execute(reference2,toolName,input);const control=parseManagedMcpControl(input);if(control.kind!=="mcp-invoke"||control.request.kind!=="tool_call"||control.operationId!==reference2.callId)throw new ManagedToolInvalidError("Managed MCP tool input is invalid.");this.mcpCalls.set(reference2.callId,{reference:reference2,input:structuredClone(input),inputJson:inputJson2})}let result;try{result=await this.mcp.invokeTool(reference2.sessionId,input)}catch(error){if(!(error instanceof ManagedMcpError))throw error;const refusal2={executionStatus:"not_started",responseParts:[],error:{type:error.code,message:error.code}};this.mcpCalls.get(reference2.callId).refusal=refusal2;return refusal2}if(result.state!=="settled")throw new ManagedMcpToolUnknownError("Managed MCP execution outcome is unknown.");return mcpPayload(result)}if(this.mcpCalls.has(reference2.callId))throw new ManagedToolConflictError("Managed Runtime protocol conflicts.");let inputJson;try{inputJson=JSON.stringify(input)}catch{throw new ManagedToolInvalidError("Managed Runtime tool request is invalid.")}const existing=this.entries.get(reference2.callId);if(existing){if(existing.version!==2){throw new ManagedToolConflictError("Managed Runtime protocol conflicts.")}return join2(existing,reference2,toolName,inputJson)}this.assertAdmissionOpen();const tools=await this.toolsFor(reference2);this.assertLegacySession(reference2.sessionId);const joined=this.entries.get(reference2.callId);if(joined){if(joined.version!==2){throw new ManagedToolConflictError("Managed Runtime protocol conflicts.")}return join2(joined,reference2,toolName,inputJson)}if(!this.isAdmissionOpen){throw new ManagedToolUnavailableError("Managed Runtime worker is closing.")}if(tools===void 0||tools.isActive?.()===false){throw new ManagedToolUnavailableError("Managed context directory is unavailable.")}const tool=tools.tools.get(toolName);if(!tool){throw new ManagedToolConflictError(`Managed Runtime does not admit tool ${toolName}.`)}if(toolName===ShellTool.Name){let isBackground=false;try{const params=structuredClone(input);isBackground=tool.validateToolParams(params)===null&¶ms["is_background"]===true}catch{}if(isBackground){throw new ManagedToolConflictError("Managed Runtime does not admit background shell execution.")}}const entry={version:2,reference:reference2,toolName,input,inputJson,state:"prepared",lastSequence:0,controller:new AbortController};this.entries.set(reference2.callId,entry);entry.promise=this.run(entry,tool,tools,tools.directory);return join2(entry,reference2,toolName,inputJson)}executeV3(request){return this.trackStart(()=>this.executeV3Admitted(request))}async executeV3Admitted(request){if(this.closing){throw new ManagedToolUnavailableError("Managed Runtime worker is closing.")}const{reference:reference2,capture:capture2,toolName,input}=request;this.assertLegacySession(reference2.sessionId);let inputJson;let inputDigest;try{inputJson=JSON.stringify(input);inputDigest=managedToolDigest(input)}catch{throw new ManagedToolInvalidError("Managed Runtime tool request is invalid.")}if(reference2.argsDigest.replace(/^sha256:/,"")!==inputDigest){throw new ManagedToolConflictError("Managed Runtime invocation digest conflicts.")}const existing=this.entries.get(reference2.callId);if(existing){if(existing.version!==3||!sameReference(existing.reference,reference2)||existing.toolName!==toolName||!sameCapture(existing.v3Capture,capture2)){throw new ManagedToolConflictError("Managed Runtime invocation identity conflicts.")}if(!existing.capturePublisher?.finish)await existing.promise;return v3View(existing)}this.assertAdmissionOpen();if(!this.capturePublisher||toolName!==ShellTool.Name&&toolName!=="monitor"){throw new ManagedToolUnavailableError("Tool v3 capture is not available.")}const tools=await this.toolsFor(reference2);this.assertLegacySession(reference2.sessionId);const joined=this.entries.get(reference2.callId);if(joined)return this.executeV3(request);if(!this.isAdmissionOpen||!tools||tools.isActive?.()===false){throw new ManagedToolUnavailableError("Managed context directory is unavailable.")}if(toolName==="monitor"){return this.executeV3Monitor(request,tools,structuredClone(input))}const normalized=structuredClone(input);if(normalized["is_background"]===true){return this.executeV3Background(request,tools,normalized)}if(normalized["is_monitor"]===true){return this.executeV3Monitor(request,tools,normalized)}const tool=tools.tools.get(toolName);if(!tool)throw new ManagedToolUnavailableError("Foreground Shell is unavailable.");let prepared;try{this.capturePreparationStarted=true;prepared=await this.capturePublisher.prepare({reference:reference2,capture:capture2})}catch(cause){throw new ManagedToolUnavailableError(cause instanceof Error?cause.message:String(cause))}if(this.entries.has(reference2.callId))return this.executeV3(request);this.assertLegacySession(reference2.sessionId);if(!this.isAdmissionOpen||tools.isActive?.()===false){throw new ManagedToolUnavailableError("Managed Runtime worker is no longer active.")}const entry={version:3,reference:reference2,toolName,input,inputJson,v3Capture:capture2,captureSink:prepared.sink,capturePublisher:prepared.publisher??this.capturePublisher,state:"prepared",lastSequence:0,controller:new AbortController};this.entries.set(reference2.callId,entry);entry.promise=this.run(entry,tool,tools);if(!entry.capturePublisher?.finish)await entry.promise;return v3View(entry)}async executeV3Background(request,tools,normalized){const{reference:reference2,capture:capture2,input}=request;if(this.entries.has(reference2.callId))return this.executeV3(request);const entry={version:3,reference:reference2,toolName:request.toolName,input,inputJson:JSON.stringify(input),v3Capture:capture2,state:"prepared",lastSequence:0,controller:new AbortController};this.entries.set(reference2.callId,entry);const settle=__name(result=>{entry.v3Result=result;entry.state="settled";entry.lastSequence=1;this.entries.set(reference2.callId,entry);return v3View(entry)},"settle");if(!this.backgroundSupervisor){return settle({executionStatus:"not_started",responseParts:[],capture:null,error:{message:"Background Shell requires a delegated Linux cgroup v2 root on this Runtime.",type:"managed_isolation_root_missing"}})}let directory;const requestedDirectory=normalized["directory"];if(typeof requestedDirectory==="string"&&requestedDirectory!==""){if(!tools.admitsDirectory(requestedDirectory)){return settle({executionStatus:"not_started",responseParts:[],capture:null,error:{message:`Directory '${requestedDirectory}' is not within any of the registered workspace directories.`}})}directory=requestedDirectory}else if(tools.directory!==void 0){directory=tools.directory}else{return settle({executionStatus:"not_started",responseParts:[],capture:null,error:{message:"Managed Runtime Session has no workspace directory."}})}const command=normalized["command"];if(typeof command!=="string"||!command.trim()){return settle({executionStatus:"not_started",responseParts:[],capture:null,error:{message:"Hosted Shell requires a nonempty command."}})}if(this.backgroundRegistry.countBySession(reference2.sessionId)>=MANAGED_BACKGROUND_MAX_SHELLS){return settle({executionStatus:"not_started",responseParts:[],capture:null,error:{message:`Session already runs ${MANAGED_BACKGROUND_MAX_SHELLS} background Shells.`}})}let prepared;try{prepared=await this.capturePublisher.prepare({reference:reference2,capture:{...capture2,background:true}})}catch(cause){return settle({executionStatus:"not_started",responseParts:[],capture:null,error:{message:`Background Shell capture could not be prepared: ${cause instanceof Error?cause.message:String(cause)}`}})}if(this.closing||tools.isActive?.()===false){return settle({executionStatus:"not_started",responseParts:[],capture:null,error:{message:"Managed Runtime worker is no longer active."}})}const sink=prepared.sink;const publisher=prepared.publisher??this.capturePublisher;const unitName=`qwen-bg-${reference2.callId.replace(/[^a-zA-Z0-9._-]/g,"-")}`;const shellConfig=getShellConfiguration();let process2;let bufferedBytes=0;let paused=false;const applyPause=__name(next=>{paused=next;const child=process2?.child;if(!child)return;for(const stream of[child.stdout,child.stderr]){if(!stream)continue;if(next){if(!stream.isPaused())stream.pause()}else if(stream.isPaused()){stream.resume()}}},"applyPause");try{process2=await this.backgroundSupervisor.start({unitName,executable:shellConfig.executable,args:[...shellConfig.argsPrefix,command],env:backgroundEnv(tools.sessionId),cwd:directory,onOutput:__name((stream,chunk)=>{bufferedBytes+=chunk.byteLength;if(paused)applyPause(true);const written=sink.write(stream,chunk);void written.then(()=>{bufferedBytes-=chunk.byteLength;if(paused&&bufferedBytes<=MANAGED_BACKGROUND_OUTPUT_RESUME_BYTES)applyPause(false)},()=>{bufferedBytes-=chunk.byteLength;if(paused&&bufferedBytes<=MANAGED_BACKGROUND_OUTPUT_RESUME_BYTES)applyPause(false)});if(!paused&&bufferedBytes>=MANAGED_BACKGROUND_OUTPUT_PAUSE_BYTES)applyPause(true)},"onOutput")})}catch(cause){return settle({executionStatus:"not_started",responseParts:[],capture:null,error:cause instanceof HookCommandIsolationUnavailableError?isolationRefusal("Background Shell",cause):{message:`Background Shell could not start: ${cause instanceof Error?cause.message:String(cause)}`}})}sink.setStarted(process2.child.pid??0);if(paused)applyPause(true);this.backgroundRegistry.register({unitName,sessionId:reference2.sessionId,process:process2,sink,publisher,identity:prepared.identity});return settle({executionStatus:"success",responseParts:[{text:`Background shell started under unit ${unitName}. It keeps running after this result and holds its Runtime until it exits; read its status and output through the task surface.`}],capture:{captureStatus:"detached",captureReason:null,manifest:null,previewTruncated:false,deliveryStatus:"pending"}})}async executeV3Monitor(request,tools,normalized){const{reference:reference2,capture:capture2,input}=request;if(this.entries.has(reference2.callId))return this.executeV3(request);const entry={version:3,reference:reference2,toolName:request.toolName,input,inputJson:JSON.stringify(input),v3Capture:capture2,state:"prepared",lastSequence:0,controller:new AbortController};this.entries.set(reference2.callId,entry);const settle=__name(result=>{entry.v3Result=result;entry.state="settled";entry.lastSequence=1;this.entries.set(reference2.callId,entry);return v3View(entry)},"settle");if(this.monitorWatcher===void 0){return settle({executionStatus:"not_started",responseParts:[],capture:null,error:{message:"Monitor watch requires a delegated Linux cgroup v2 root on this Runtime.",type:"managed_isolation_root_missing"}})}const command=normalized["command"];if(typeof command!=="string"||!command.trim()){return settle({executionStatus:"not_started",responseParts:[],capture:null,error:{message:"Monitor watch requires a nonempty command."}})}if(this.capturePublisher===void 0){return settle({executionStatus:"not_started",responseParts:[],capture:null,error:{message:"Monitor watch capture is unavailable."}})}if(this.monitorRegistry.countBySession(reference2.sessionId)>=MANAGED_MONITOR_MAX_WATCHES){return settle({executionStatus:"not_started",responseParts:[],capture:null,error:{message:`Session already runs ${MANAGED_MONITOR_MAX_WATCHES} Monitor watches.`}})}let directory=tools.directory;if(typeof normalized["directory"]==="string"&&normalized["directory"]!==""){if(!tools.admitsDirectory(normalized["directory"])){return settle({executionStatus:"not_started",responseParts:[],capture:null,error:{message:`Directory '${normalized["directory"]}' is not within any of the registered workspace directories.`}})}directory=normalized["directory"]}let prepared;try{prepared=await this.capturePublisher.prepare({reference:reference2,capture:{...capture2,background:true,monitoring:true}})}catch(cause){return settle({executionStatus:"not_started",responseParts:[],capture:null,error:{message:`Monitor watch capture could not be prepared: ${cause instanceof Error?cause.message:String(cause)}`}})}if(this.closing||tools.isActive?.()===false){return settle({executionStatus:"not_started",responseParts:[],capture:null,error:{message:"Managed Runtime worker is no longer active."}})}const sink=prepared.sink;const publisher=prepared.publisher??this.capturePublisher;const unitName=`qwen-mon-${reference2.callId.replace(/[^a-zA-Z0-9._-]/g,"-")}`;let watchHandle;let bufferedBytes=0;let paused=false;const applyPause=__name(next=>{paused=next;const child=watchHandle?.process?.child;if(!child)return;for(const stream of[child.stdout,child.stderr]){if(!stream)continue;if(next){if(!stream.isPaused())stream.pause()}else if(stream.isPaused()){stream.resume()}}},"applyPause");const acceptChunk=__name((stream,chunk)=>{bufferedBytes+=chunk.byteLength;if(paused)applyPause(true);const written=sink.write(stream,chunk);const release=__name(()=>{bufferedBytes-=chunk.byteLength;if(paused&&bufferedBytes<=MANAGED_BACKGROUND_OUTPUT_RESUME_BYTES)applyPause(false)},"release");void written.then(release,release);if(!paused&&bufferedBytes>=MANAGED_BACKGROUND_OUTPUT_PAUSE_BYTES)applyPause(true)},"acceptChunk");try{watchHandle=await this.monitorWatcher.start({command},_observationLine=>{},()=>void 0,{unitName,cwd:directory,onChunk:acceptChunk})}catch(cause){return settle({executionStatus:"not_started",responseParts:[],capture:null,error:cause instanceof HookCommandIsolationUnavailableError?isolationRefusal("Monitor watch",cause):{message:`Monitor watch could not start: ${cause instanceof Error?cause.message:String(cause)}`}})}const watchProcess=watchHandle.process;if(watchProcess===void 0){return settle({executionStatus:"not_started",responseParts:[],capture:null,error:{message:"Monitor watch reported no supervised unit."}})}sink.setStarted(watchProcess.child.pid??0);if(paused)applyPause(true);this.monitorRegistry.register({unitName,sessionId:reference2.sessionId,process:watchProcess,sink,publisher,identity:prepared.identity});return settle({executionStatus:"success",responseParts:[{text:`Monitor watch started under unit ${unitName}. It keeps running after this result and holds its Runtime until it exits; read its status and output through the task surface.`}],capture:{captureStatus:"detached",captureReason:null,manifest:null,previewTruncated:false,deliveryStatus:"pending"}})}statusV3(reference2){const entry=this.entries.get(reference2.callId);if(!entry)return{state:"unknown"};if(entry.version!==3||!sameReference(entry.reference,reference2)){throw new ManagedToolConflictError("Managed Runtime protocol conflicts.")}return v3View(entry)}cancelV3(reference2){const entry=this.entries.get(reference2.callId);if(!entry)return{state:"unknown"};if(entry.version!==3||!sameReference(entry.reference,reference2)){throw new ManagedToolConflictError("Managed Runtime protocol conflicts.")}if(entry.state==="prepared"){entry.v3Result={executionStatus:"not_started",responseParts:[],capture:null};entry.state="settled";entry.lastSequence++}else if(entry.state==="executing"){entry.state="cancel_requested";entry.lastSequence++;entry.controller.abort()}return v3View(entry)}acknowledgeV3(reference2,receipt2){const entry=this.entries.get(reference2.callId);if(!entry)return{state:"unknown"};if(entry.version!==3||!sameReference(entry.reference,reference2)){throw new ManagedToolConflictError("Managed Runtime protocol conflicts.")}if(!entry.v3Result||entry.state!=="settled"){throw new ManagedToolConflictError("Tool result has not settled.","managed_tool_result_conflict")}const actual=entry.v3Result.capture;if(receipt2.executionCallId!==entry.v3Capture?.executionCallId){throw new ManagedToolConflictError("Tool result receipt conflicts.","managed_tool_result_conflict")}if(actual===null?receipt2.manifest!==null:JSON.stringify(receipt2.manifest)!==JSON.stringify(actual.manifest)){throw new ManagedToolConflictError("Tool result receipt conflicts.","managed_tool_result_conflict")}if(actual!==null&&receipt2.deliveryStatus==="committed"&&(actual.captureStatus!=="complete"||!Number.isSafeInteger(receipt2.historyRevision)||(receipt2.historyRevision??0)<1)){throw new ManagedToolConflictError("Tool result receipt conflicts.","managed_tool_result_conflict")}if(receipt2.deliveryStatus==="blocked"&&receipt2.historyRevision!==null){throw new ManagedToolConflictError("Tool result receipt conflicts.","managed_tool_result_conflict")}if(entry.acknowledgement&&JSON.stringify(entry.acknowledgement)!==JSON.stringify(receipt2)){throw new ManagedToolConflictError("Tool result was acknowledged differently.","managed_tool_result_conflict")}entry.acknowledgement=receipt2;entry.v3Result={...entry.v3Result,capture:actual===null?null:{captureStatus:actual.captureStatus,captureReason:actual.captureReason,manifest:actual.manifest,previewTruncated:actual.previewTruncated,deliveryStatus:receipt2.deliveryStatus}};return v3View(entry)}acknowledgeOriginalCsi(request,boot,pod){const parsed=parseManagedCsiAckRequest(request,boot,pod);const entry=this.entries.get(parsed.reference.callId);if(this.retirementId!==parsed.retirementId||!entry||entry.version!==3||!sameReference(entry.reference,parsed.reference)||entry.state!=="settled"||!entry.v3Result||!["success","error","cancelled"].includes(entry.v3Result.executionStatus)||entry.v3Result.capture?.captureStatus!=="complete"||entry.v3Result.capture.deliveryStatus==="blocked"||!entry.v3Capture||!entry.captureSink)throw new ManagedCsiAckRequestError(409);try{const identity=parseManagedCsiCaptureIdentity(entry.captureSink.identity);if(identity.tenantId!==boot.context.tenantId||identity.tenantId!==entry.v3Capture.tenantId||identity.sessionId!==entry.v3Capture.sessionId||identity.turnId!==entry.v3Capture.turnId||identity.executionCallId!==entry.v3Capture.executionCallId||identity.bindingGeneration!==entry.v3Capture.bindingGeneration||identity.callId!==entry.reference.callId||identity.invocationDigest!==entry.reference.argsDigest)throw new Error;const actual=parseManagedCsiAcknowledgement({executionCallId:entry.v3Capture.executionCallId,manifest:entry.v3Result.capture.manifest,deliveryStatus:"committed",historyRevision:parsed.acknowledgement.historyRevision});if(!isDeepStrictEqual2(actual,parsed.acknowledgement)||entry.acknowledgement&&!isDeepStrictEqual2(parseManagedCsiAcknowledgement(entry.acknowledgement),parsed.acknowledgement))throw new Error;const response=parseManagedCsiAckResponse({...parsed,state:"ACKNOWLEDGED",captureIdentity:identity},boot,pod);const json=JSON.stringify(response);if(Buffer.byteLength(json,"utf8")>MANAGED_CSI_ACK_LIMIT_BYTES)throw new Error;if(entry.acknowledgement){if(entry.v3Result.capture.deliveryStatus!=="committed")throw new Error}else{this.acknowledgeV3(entry.reference,{...parsed.acknowledgement,manifest:entry.v3Result.capture.manifest})}return{response,json}}catch{throw new ManagedCsiAckRequestError(409)}}hasActiveSession(sessionId){return this.hooks?.hasHolds(sessionId)===true||this.hasActiveToolSession(sessionId)}hasActiveToolSession(sessionId){if(this.historyControls.has(sessionId))return true;return this.mcp?.hasHolds(sessionId)===true||this.provider?.hasActiveSession(sessionId)===true||this.backgroundRegistry.hasHolds(sessionId)||this.monitorRegistry.hasHolds(sessionId)||[...this.entries.values()].some(entry=>entry.reference.sessionId===sessionId&&entry.state!=="settled"&&entry.state!=="acknowledged"&&entry.state!=="unknown")}status(reference2){const mcp=this.mcpCalls.get(reference2.callId);if(mcp&&this.mcp){if(!sameReference(mcp.reference,reference2))return null;if(mcp.refusal)return{state:"settled",lastSequence:1,result:mcp.refusal};return mcpView(this.mcp.toolStatus(reference2.sessionId,mcp.input))}const entry=this.entries.get(reference2.callId);if(entry&&entry.version!==2){throw new ManagedToolConflictError("Managed Runtime protocol conflicts.")}if(!entry||!sameReference(entry.reference,reference2)){return null}return view(entry)}cancel(reference2){const mcp=this.mcpCalls.get(reference2.callId);if(mcp&&this.mcp){if(!sameReference(mcp.reference,reference2))return null;if(mcp.refusal)return{state:"settled",lastSequence:1,result:mcp.refusal};this.mcp.cancelTool(reference2.sessionId,mcp.input);return mcpView(this.mcp.toolStatus(reference2.sessionId,mcp.input))}const entry=this.entries.get(reference2.callId);if(entry&&entry.version!==2){throw new ManagedToolConflictError("Managed Runtime protocol conflicts.")}if(!entry||!sameReference(entry.reference,reference2)){return null}if(entry.state==="prepared"){entry.result={executionStatus:"cancelled",responseParts:[]};entry.state="settled";entry.lastSequence+=1;return view(entry)}if(entry.state==="executing"){entry.state="cancel_requested";entry.lastSequence+=1;entry.controller.abort()}return view(entry)}acknowledge(reference2){const entry=this.entries.get(reference2.callId);if(entry&&entry.version!==2){throw new ManagedToolConflictError("Managed Runtime protocol conflicts.")}if(!entry||!sameReference(entry.reference,reference2)){return null}if(entry.state!=="settled"){if(entry.state==="acknowledged")return view(entry);throw new ManagedToolConflictError("Managed Runtime tool call has not settled.")}entry.input=void 0;entry.inputJson=void 0;entry.result=void 0;entry.state="acknowledged";entry.lastSequence+=1;return view(entry)}async close(){this.closing=true;await Promise.all([this.mcp?.close(),this.hooks?.close()]);for(const entry of this.entries.values()){if(entry.state==="executing"||entry.state==="cancel_requested"){entry.controller.abort()}}await Promise.allSettled([...this.pendingStarts,...[...this.entries.values()].flatMap(entry=>entry.promise?[entry.promise]:[]),this.provider?.close(),this.backgroundRegistry.stopAll(5e3),this.monitorRegistry.stopAll(5e3)]);if(this.options.ledger){try{const remaining=await this.options.ledger.killOutstanding();if(remaining.length===0){this.options.ledger.complete()}else{debugLogger.warn(`Managed Runtime worker could not prove ${remaining.length} Shell process group(s) stopped: ${remaining.map(group=>group.pgid).join(", ")}`)}}catch(error){debugLogger.warn(`Managed Runtime worker could not sweep its ledger on close: ${error instanceof Error?error.message:String(error)}`)}}}async stopBackgroundSession(sessionId){await Promise.all([this.backgroundRegistry.stopSession(sessionId,5e3),this.monitorRegistry.stopSession(sessionId,5e3)])}trackStart(action){if(this.closing){return Promise.reject(new ManagedToolUnavailableError("Managed Runtime worker is closing."))}const pending=action();this.pendingStarts.add(pending);void pending.then(()=>this.pendingStarts.delete(pending),()=>this.pendingStarts.delete(pending));return pending}assertAdmissionOpen(){if(!this.isAdmissionOpen)throw new ManagedToolUnavailableError("Managed Runtime admission is sealed.")}static isCancelRequested(entry){return entry.state==="cancel_requested"}async run(entry,tool,tools,directory){const{sessionId}=tools;entry.state="executing";entry.lastSequence+=1;let payload;let shellPgid;let invocationStarted=false;try{const params=structuredClone(entry.input);let fileInvocation;if(directory&&entry.toolName!==ShellTool.Name&&entry.toolName!==GlobTool.Name&&typeof params["file_path"]==="string"){params["file_path"]=path2.resolve(directory,params["file_path"].trim());let buildError;try{fileInvocation=sessionIdContext.run(sessionId,()=>tool.build(params))}catch(error){buildError=error}const realTarget=tools.retainedFileHistory?params["file_path"]:await realpathDeepestExisting(params["file_path"]);const realDirectory=tools.retainedFileHistory?directory:await realpathDeepestExisting(directory);const relative=path2.relative(realDirectory,realTarget);let outOfBoundary=false;if(relative===".."||relative.startsWith(`..${path2.sep}`)||path2.isAbsolute(relative)){const workspaceRoot=tools.workspaceRoot;outOfBoundary=tools.retainedFileHistory!==void 0||workspaceRoot===void 0||escapesSession(path2.relative(await realpathDeepestExisting(workspaceRoot),realTarget))}outOfBoundary||=Boolean(await this.ownsAnotherSessionDir?.(tools.sessionId,realTarget,realDirectory));if(outOfBoundary){throw new Error(`Path '${entry.input["file_path"]}' is not within the Session working directory.`)}if(buildError!==void 0)throw buildError}if(entry.toolName===GlobTool.Name){const root=tools.directory;if(root===void 0)throw new ManagedToolUnavailableError("Managed context directory is unavailable.");const pattern=typeof params["pattern"]==="string"?params["pattern"]:"";const check=checkHostedGlobPattern(pattern);if(check==="too-complex")throw new Error(HOSTED_GLOB_TOO_COMPLEX);if(check==="escapes"){throw new Error("Glob pattern must stay within the Session working directory.")}let globBuildError;try{fileInvocation=sessionIdContext.run(sessionId,()=>tool.build(params))}catch(error){globBuildError=error}const requested=typeof params["path"]==="string"?params["path"].trim():"";const resolved=requested===""||requested==="."?root:path2.resolve(root,requested);const realRoot=await realpathDeepestExisting(root);const realResolved=await realpathDeepestExisting(resolved);if(escapesSession(path2.relative(realRoot,realResolved))||await this.ownsAnotherSessionDir?.(tools.sessionId,realResolved,realRoot)){throw new Error(`Path '${requested}' is not within the Session working directory.`)}if(globBuildError!==void 0)throw globBuildError;params["path"]=resolved}if(entry.toolName===ShellTool.Name&&typeof params["directory"]==="string"&¶ms["directory"]!==""&&!tools.admitsDirectory(params["directory"])){throw new Error(`Directory '${params["directory"]}' is not within any of the registered workspace directories.`)}const invoke=__name(()=>{this.assertAdmissionOpen();return sessionIdContext.run(sessionId,()=>{const invocation=fileInvocation??tool.build(params);invocationStarted=true;if(entry.version===3&&entry.captureSink){return invocation.execute(entry.controller.signal,void 0,void 0,void 0,void 0,void 0,entry.captureSink)}if(entry.toolName===ShellTool.Name&&this.options.ledger){const ledger=this.options.ledger;return invocation.execute(entry.controller.signal,void 0,void 0,pid=>{shellPgid=pid;try{ledger.addGroup({pgid:pid,callId:entry.reference.callId,startedAt:Date.now()})}catch(error){signalProcessGroup(pid,"SIGKILL");void ledger.waitForGroupExit(pid,CLOSE_SWEEP_TIMEOUT_MS);throw error}})}return invocation.execute(entry.controller.signal)})},"invoke");const registeredHistory=this.fileHistories.get(entry.reference.sessionId);const history2=tools.fileHistory??registeredHistory;const mutating=[WriteFileTool.Name,EditTool.Name].includes(entry.toolName);if(history2&&(history2.directory!==tools.directory||tools.fileHistory&&history2.ownerSessionId!==entry.reference.sessionId||registeredHistory&®isteredHistory!==history2)||mutating&&tools.retainedFileHistory&&!tools.fileHistory)throw new ManagedToolConflictError("File history binding conflicts.");let result;if(history2&&mutating){let outcome;let invoked=false;try{const file=path2.relative(history2.directory,params["file_path"]).split(path2.sep).join("/");outcome=await history2.execute(file,async()=>{invoked=true;try{return{result:await invoke()}}catch(error){return{error}}})}catch(error){if(!invoked)throw error;entry.state="unknown";entry.lastSequence++;return}if("error"in outcome)throw outcome.error;result=outcome.result}else{result=await invoke()}if(entry.toolName===GlobTool.Name){const root=tools.directory;if(root===void 0)throw new ManagedToolUnavailableError("Managed context directory is unavailable.");const resultPaths=result.collectedFilePaths??result.resultFilePaths;if(Array.isArray(resultPaths)){const realRoot=await realpathDeepestExisting(root);for(const hit of resultPaths){if(typeof hit!=="string")continue;const effective=path2.join(await realpathDeepestExisting(path2.dirname(hit)),path2.basename(hit));const relative=path2.relative(realRoot,effective);if(escapesSession(relative)||await this.ownsAnotherSessionDir?.(tools.sessionId,effective,realRoot)){throw new Error("Glob results must stay within the Session working directory.")}}}result=relativizeGlobResult(result,root)}payload=toPayload(result,_ManagedToolExecutor.isCancelRequested(entry))}catch(error){const message=error instanceof Error?error.message:String(error);payload={executionStatus:!invocationStarted&&this.isAdmissionSealed&&error instanceof ManagedToolUnavailableError?"not_started":_ManagedToolExecutor.isCancelRequested(entry)?"cancelled":"error",responseParts:[],error:{message:entry.toolName===GlobTool.Name&&tools.directory!==void 0?relativizeGlobText(message,tools.directory):message}}}if(entry.version===2&&shellPgid!==void 0&&entry.controller.signal.aborted&&this.options.ledger){let state="denied";try{state=await this.options.ledger.waitForGroupExit(shellPgid,this.options.groupEvidenceTimeoutMs??GROUP_EXIT_EVIDENCE_TIMEOUT_MS)}catch(error){debugLogger.warn(`Managed Runtime group-exit evidence failed: ${error instanceof Error?error.message:String(error)}`)}if(state!=="gone"){entry.state="unknown";entry.lastSequence++;return}}if(entry.version===3){try{entry.v3Result=await entry.captureSink.finalize(payload.executionStatus,payload.responseParts,payload.error);if(Buffer.byteLength(JSON.stringify({protocolVersion:3,toolResult:MANAGED_TOOL_RESULT_PROTOCOL,state:"settled",lastSequence:entry.lastSequence+1,result:entry.v3Result}))>MANAGED_RUNTIME_TOOL_RESULT_BODY_LIMIT_BYTES){entry.v3Result={...entry.v3Result,responseParts:[],error:{message:"Managed Runtime tool preview exceeds 1 MiB."}}}if(entry.v3Result.capture){if(entry.capturePublisher.finish){await entry.capturePublisher.finish(entry.captureSink.identity,entry.v3Result)}else if(entry.capturePublisher.accept){const receipt2=await entry.capturePublisher.accept(entry.captureSink.identity,entry.v3Result);entry.v3Result={...entry.v3Result,capture:{...entry.v3Result.capture,deliveryStatus:receipt2.deliveryStatus}};entry.acknowledgement={executionCallId:receipt2.executionCallId,manifest:receipt2.manifest,deliveryStatus:receipt2.deliveryStatus,historyRevision:receipt2.historyRevision}}}}catch{entry.state="unknown";entry.lastSequence++;return}entry.state="settled";entry.lastSequence++;return}entry.result=payload;entry.state="settled";entry.lastSequence+=1;if(Buffer.byteLength(JSON.stringify({protocolVersion:2,...view(entry)}))>MANAGED_RUNTIME_TOOL_RESULT_BODY_LIMIT_BYTES){entry.result={executionStatus:payload.executionStatus==="cancelled"?"cancelled":"error",responseParts:[],error:{message:"Managed Runtime tool result exceeds 1 MiB."}}}}};function backgroundEnv(sessionId){const env={...sessionIdContext.run(sessionId,getShellContextEnvVars)};for(const key of["PATH","HOME","LANG","LC_ALL","TMPDIR","USER","SHELL"]){const value=process.env[key];if(value!==void 0)env[key]=value}return env}__name(backgroundEnv,"backgroundEnv");function mcpView(view2){return{state:view2.state==="running"?"executing":view2.state==="outcome_unknown"?"unknown":"settled",lastSequence:view2.state==="running"?1:2,...view2.state==="settled"?{result:mcpPayload(view2)}:{}}}__name(mcpView,"mcpView");function mcpPayload(view2){const response=view2.response;return{executionStatus:view2.error?["managed_mcp_remote_error","managed_mcp_output_limit"].includes(view2.error.code)?"error":"not_started":response?.["isError"]===true?"error":"success",responseParts:response?[{text:JSON.stringify(response)}]:[],...view2.error?{error:{type:view2.error.code,message:view2.error.code}}:{}}}__name(mcpPayload,"mcpPayload");function v3View(entry){return{state:entry.state,lastSequence:entry.lastSequence,...entry.state==="settled"?{result:entry.v3Result}:{}}}__name(v3View,"v3View");function createManagedToolSet(directory,sessionId,workspaceRoot=directory){const config=new Config({sessionId,targetDir:directory,cwd:directory,includeDirectories:[workspaceRoot],model:"managed-runtime-worker",debugMode:false,usageStatisticsEnabled:false,approvalMode:"yolo",fileCheckpointingEnabled:false,fileReadCacheDisabled:true});registerSessionProjectDir(sessionId,config.storage.getProjectDir());return{sessionId,directory,workspaceRoot,admitsDirectory:__name(candidate=>config.getWorkspaceContext().isPathWithinWorkspace(candidate),"admitsDirectory"),tools:new Map([new ReadFileTool(config),new WriteFileTool(config),new EditTool(config),new GlobTool(config,{containmentRoot:directory,executionTimeoutMs:5e3}),new ShellTool(config)].map(tool=>[tool.name,tool]))}}__name(createManagedToolSet,"createManagedToolSet");async function join2(entry,reference2,toolName,inputJson){if(!sameInvocation(entry,reference2,toolName,inputJson)){throw new ManagedToolConflictError("Managed Runtime invocation identity conflicts.")}await entry.promise;if(entry.state==="unknown")throw new ManagedMcpToolUnknownError("Managed Runtime tool outcome is unknown.");return entry.result}__name(join2,"join");function view(entry){return{state:entry.state,lastSequence:entry.lastSequence,...entry.state==="settled"?{result:entry.result}:{}}}__name(view,"view");function sameReference(left,right){return left.sessionId===right.sessionId&&left.promptId===right.promptId&&left.callId===right.callId&&left.argsDigest===right.argsDigest}__name(sameReference,"sameReference");function sameCapture(left,right){return left?.tenantId===right.tenantId&&left.sessionId===right.sessionId&&left.turnId===right.turnId&&left.executionCallId===right.executionCallId&&left.bindingGeneration===right.bindingGeneration&&left.capturePolicy===right.capturePolicy}__name(sameCapture,"sameCapture");function sameInvocation(entry,reference2,toolName,inputJson){return entry.inputJson!==void 0&&sameReference(entry.reference,reference2)&&entry.toolName===toolName&&entry.inputJson===inputJson}__name(sameInvocation,"sameInvocation");function relativizeGlobText(text2,directory){const root=path2.resolve(directory);if(root===path2.sep)return text2;const prefix=root.endsWith(path2.sep)?root:root+path2.sep;const escape=__name(value=>value.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"escape");const tokenPrefix=new RegExp(`(?<![\\w./\\\\-])${escape(prefix)}`,"g");const bareRoot=new RegExp(`(?<![\\w./\\-])${escape(root)}(?![/\\w.-])`,"g");return text2.replace(tokenPrefix,"").replace(bareRoot,".")}__name(relativizeGlobText,"relativizeGlobText");function relativizeGlobResult(result,directory){const next={...result};if(typeof next.llmContent==="string"){next.llmContent=relativizeGlobText(next.llmContent,directory)}if(typeof next.error?.message==="string"){next.error={...next.error,message:relativizeGlobText(next.error.message,directory)}}return next}__name(relativizeGlobResult,"relativizeGlobResult");function escapesSession(relative){return relative===".."||relative.startsWith(`..${path2.sep}`)||path2.isAbsolute(relative)}__name(escapesSession,"escapesSession");async function realpathDeepestExisting(candidate){let resolved=candidate;const tail=[];try{for(;;){try{return path2.join(await realpath(resolved),...tail)}catch(error){if(error?.code!=="ENOENT")throw error}try{if((await lstat2(resolved)).isSymbolicLink()){resolved=path2.resolve(await realpath(path2.dirname(resolved)),await readlink(resolved));continue}}catch(error){if(error?.code!=="ENOENT")throw error}const parent=path2.dirname(resolved);if(parent===resolved)return path2.join(resolved,...tail);tail.unshift(path2.basename(resolved));resolved=parent}}catch(error){const code=error?.code;throw new Error(`Path could not be resolved (${code??"unknown error"}).`)}}__name(realpathDeepestExisting,"realpathDeepestExisting");function toPayload(result,cancelRequested){const content=result.llmContent;const responseParts=typeof content==="string"?[{type:"text",text:content}]:Array.isArray(content)?content:[];const toolError=result.error;if(cancelRequested){return{executionStatus:"cancelled",responseParts,...toolError?{error:{message:toolError.message,...toolError.type?{type:toolError.type}:{}}}:{}}}if(toolError){return{executionStatus:"error",responseParts,error:{message:toolError.message,...toolError.type?{type:toolError.type}:{}}}}return{executionStatus:"success",responseParts}}__name(toPayload,"toPayload");init_esbuild_shims();import{createHash as createHash4,randomUUID as randomUUID2}from"node:crypto";import{isDeepStrictEqual as isDeepStrictEqual3}from"node:util";var PUBLICATION_INSTALL_ROUTE=Object.freeze({key:"publication-install",method:"POST",path:"/internal/managed-runtime/v3/publications:install",protocolVersion:3,requestBodyLimitBytes:64*1024,responseBodyLimitBytes:16*1024,cacheControl:"no-store"});var PublicationRejection=class extends Error{constructor(status,code){super("Publication service rejected HTTP "+status+".");this.status=status;this.code=code}static{__name(this,"PublicationRejection")}};function refusal(error){if(!(error instanceof PublicationRejection))return null;return error.code==="managed_tool_result_invalid"||error.code==="managed_tool_result_conflict"||error.code==="managed_tool_result_digest_mismatch"?error.code:null}__name(refusal,"refusal");function record(value){if(!value||typeof value!=="object"||Array.isArray(value))throw new Error("Publication record is invalid.");return value}__name(record,"record");function same(left,right){return isDeepStrictEqual3(left,right)}__name(same,"same");function endpoint(value){const url=new URL(value);if(url.username||url.password||url.search||url.hash||url.pathname!=="/"||url.protocol!=="https:"&&!(url.protocol==="http:"&&["127.0.0.1","[::1]","localhost"].includes(url.hostname)))throw new Error("Publication service URL is invalid.");return url}__name(endpoint,"endpoint");async function boundedJson(response){let body2;try{const reader=response.body?.getReader();if(!reader)throw new Error("Publication service returned no response.");const chunks=[];let length=0;try{while(true){const item=await reader.read();if(item.done)break;length+=item.value.byteLength;if(length>1024*1024)throw new Error("Publication response is too large.");chunks.push(item.value)}}finally{reader.releaseLock()}body2=record(JSON.parse(Buffer.concat(chunks).toString("utf8")))}catch(failure2){if(!response.ok)throw new PublicationRejection(response.status,"unknown");throw failure2}if(!response.ok){const failure2=body2["error"];const code=failure2&&typeof failure2==="object"&&!Array.isArray(failure2)?String(failure2["code"]??"unknown"):"unknown";if(code==="managed_tool_publication_quota_exhausted")throw new Error("quota_exhausted");throw new PublicationRejection(response.status,code)}return body2}__name(boundedJson,"boundedJson");var PublicationClient=class{constructor(installed){this.installed=installed;this.base=endpoint(installed.serviceBaseUrl);this.key=record(installed.binding["sessionKey"])}static{__name(this,"PublicationClient")}base;key;tail=Promise.resolve();url(suffix){const sessionId=encodeURIComponent(String(this.key["sessionId"]));const publicationId=encodeURIComponent(this.installed.publicationId);const url=new URL(`/internal/managed-tool-publications/v1/sessions/${sessionId}/publications/${publicationId}${suffix}`,this.base);url.searchParams.set("workspaceId",String(this.key["workspaceId"]));return url}async request(suffix,operationId,body2,headers={}){const response=await fetch(this.url(suffix),{method:body2?"POST":"GET",headers:{"X-Qwen-Tenant-Id":String(this.key["tenantId"]),"X-Qwen-Tool-Publication-Token":this.installed.publicationToken,"X-Qwen-Tool-Publication-Operation":operationId,"X-Qwen-Tool-Publication-Async":"1","Cache-Control":"no-store",...headers},...body2?{body:body2}:{},redirect:"error",signal:AbortSignal.timeout(3e4)});return boundedJson(response)}async operation(suffix,operationId,body2,headers){const previous=this.tail;let release;this.tail=new Promise(resolve=>{release=resolve});await previous;try{return await this.performOperation(suffix,operationId,body2,headers)}finally{release()}}async performOperation(suffix,operationId,body2,headers){const deadline=Date.now()+30*6e4;let recoveries=0;const statusPath=`/operations/${encodeURIComponent(operationId)}`;const resumableRefusal=__name(failure2=>failure2.status===409&&["managed_tool_publication_operation_expired","managed_tool_publication_claim_expired","managed_tool_publication_claim_lost","managed_tool_publication_busy"].includes(failure2.code),"resumableRefusal");const retryable=__name(failure2=>failure2 instanceof PublicationRejection?failure2.status===429||failure2.status>=500||failure2.status===409&&failure2.code==="managed_tool_publication_busy":failure2 instanceof TypeError||failure2 instanceof DOMException&&["AbortError","TimeoutError"].includes(failure2.name),"retryable");const observe=__name(async()=>{while(Date.now()<deadline){try{return await this.request(statusPath,operationId)}catch(failure2){if(failure2 instanceof PublicationRejection&&failure2.code==="managed_tool_publication_operation_unknown")return null;if(!retryable(failure2))throw failure2;await new Promise(resolve=>setTimeout(resolve,250))}}throw new Error("Publication operation exceeded its observation deadline.")},"observe");while(Date.now()<deadline){let initial;try{initial=await this.request(suffix,operationId,body2,headers)}catch(failure2){if(failure2 instanceof Error&&failure2.message==="quota_exhausted")throw failure2;if(failure2 instanceof PublicationRejection&&failure2.code==="managed_tool_publication_storage_denied")throw failure2;const status2=await observe();if(status2!==null){if(failure2 instanceof PublicationRejection&&failure2.status>=400&&failure2.status<500&&failure2.status!==429&&!resumableRefusal(failure2)&&status2["state"]!=="SUCCEEDED")throw failure2;initial=status2}else{if(!retryable(failure2))throw failure2;await new Promise(resolve=>setTimeout(resolve,250));continue}}if(initial["state"]===void 0)return initial;let status=initial;while(Date.now()<deadline){if(status["state"]==="SUCCEEDED")return record(status["receipt"]);if(status["state"]==="FAILED"){const error=record(status["error"]);if(!Number.isInteger(error["status"])||Number(error["status"])<400||Number(error["status"])>599||typeof error["code"]!=="string"||!error["code"])throw new Error("Invalid publication failure response.");if(error["code"]==="managed_tool_publication_quota_exhausted")throw new Error("quota_exhausted");throw new PublicationRejection(Number(error["status"]),error["code"])}if(status["state"]==="RETRYABLE")break;if(status["state"]==="EXPIRED"&&recoveries<3){recoveries++;try{status=await this.request(`${statusPath}/recover`,operationId,Buffer.from("{}"))}catch(failure2){if(!retryable(failure2))throw failure2;if(failure2 instanceof PublicationRejection&&[409,429].includes(failure2.status)&&failure2.code==="managed_tool_publication_busy")recoveries--;await new Promise(resolve=>setTimeout(resolve,250));status=await observe()??status}continue}if(status["state"]!=="PENDING")throw new Error(`Publication operation ended as ${String(status["state"])}.`);await new Promise(resolve=>setTimeout(resolve,250));const current=await observe();if(current===null)throw new Error("Publication operation disappeared during observation.");status=current}await new Promise(resolve=>setTimeout(resolve,250))}throw new Error("Publication operation exceeded its observation deadline.")}};var RemoteShellResultPublisher=class{static{__name(this,"RemoteShellResultPublisher")}grants=new Map;clients=new Map;get hasInstalledPublication(){return this.grants.size>0}hasExecution(executionCallId){return this.grants.has(executionCallId)}install(value,boot){const body2=record(value);if(!same(Object.keys(body2).sort(),["binding","protocolVersion","publication","publicationId","publicationToken","serviceBaseUrl"])||body2["protocolVersion"]!==3||body2["publication"]!=="managed-tool-publication/1"||typeof body2["publicationId"]!=="string"||!/^[a-z0-9_-]{1,128}$/u.test(body2["publicationId"])||typeof body2["publicationToken"]!=="string"||!/^[A-Za-z0-9_-]{43}$/u.test(body2["publicationToken"])||typeof body2["serviceBaseUrl"]!=="string")throw new Error("Publication installation is invalid.");endpoint(body2["serviceBaseUrl"]);const binding=parseToolPublicationBinding(body2["binding"]);const key=record(binding["sessionKey"]);const reference2=record(binding["reference"]);if(binding["publicationId"]!==body2["publicationId"]||binding["publication"]!=="managed-tool-publication/1"||key["tenantId"]!==boot.tenantId||key["workspaceId"]!==boot.workspaceId||reference2["sessionId"]!==void 0&&typeof reference2["sessionId"]!=="string"||binding["captureScope"]!=="process_pipes"||binding["capturePolicy"]!=="complete_required"||binding["revision"]!==1||typeof binding["executionCallId"]!=="string"||typeof binding["captureId"]!=="string")throw new Error("Publication binding conflicts with this worker.");const grant={...body2,binding};const prior=this.grants.get(binding["executionCallId"]);if(prior&&!same(prior,grant))throw new Error("Original publication installation conflicts.");this.grants.set(binding["executionCallId"],grant);if(!prior)this.clients.set(binding["executionCallId"],new PublicationClient(grant))}prepare(request){const grant=this.grants.get(request.capture.executionCallId);if(!grant)throw new Error("Original publication grant is missing.");const binding=grant.binding;const key=record(binding["sessionKey"]);const reference2=record(binding["reference"]);if(request.reference.sessionId!==reference2["sessionId"]||request.reference.promptId!==reference2["promptId"]||request.reference.callId!==reference2["callId"]||request.reference.argsDigest!==reference2["argsDigest"]||request.capture.tenantId!==key["tenantId"]||request.capture.sessionId!==key["sessionId"]||request.capture.turnId!==binding["turnId"]||request.capture.bindingGeneration!==binding["bindingGeneration"]||request.capture.capturePolicy!=="complete_required")throw new Error("Shell invocation conflicts with its publication grant.");const identity={tenantId:request.capture.tenantId,sessionId:request.capture.sessionId,turnId:request.capture.turnId,executionCallId:request.capture.executionCallId,callId:request.reference.callId,invocationDigest:request.reference.argsDigest,bindingGeneration:request.capture.bindingGeneration,captureId:String(binding["captureId"]),revision:1};const client=this.clients.get(request.capture.executionCallId);if(!client)throw new Error("Original publication client is missing.");const store={publish:__name(async raw=>{let item;try{item=parseToolResultPublishRequest(raw)}catch(cause){if(cause instanceof ManagedSessionRecordError)return{status:"refused",code:"managed_tool_result_invalid"};throw cause}if(item.captureId!==identity.captureId)return{status:"refused",code:"managed_tool_result_conflict"};if(!["stdout","stderr"].includes(item.streamId))return{status:"refused",code:"managed_tool_result_invalid"};const stream=item.streamId;const ordinal=item.ordinal;const bytes=Buffer.from(item.bytes);const digest2=createHash4("sha256").update(bytes).digest("hex");if(item.expectedDigest&&item.expectedDigest!==digest2)return{status:"refused",code:"managed_tool_result_digest_mismatch"};let receipt2;try{receipt2=await client.operation(`/segments/${stream}/${ordinal}`,`seg-${stream}-${ordinal}`,bytes,{"X-Qwen-Tool-Segment-Digest":digest2})}catch(cause){const code=refusal(cause);if(code)return{status:"refused",code};throw cause}if(receipt2["ordinal"]!==ordinal||receipt2["byteLength"]!==bytes.length||receipt2["digest"]!==digest2||receipt2["captureId"]!==identity.captureId||receipt2["streamId"]!==stream)throw new Error("Original segment receipt conflicts.");return{status:"ok",result:{ordinal,byteLength:bytes.length,digest:digest2}}},"publish"),seal:__name(async raw=>{let item;try{item=parseToolResultSealRequest(raw)}catch(cause){if(cause instanceof ManagedSessionRecordError)return{status:"refused",code:"managed_tool_result_invalid"};throw cause}if(item.captureId!==identity.captureId)return{status:"refused",code:"managed_tool_result_conflict"};if(!["stdout","stderr"].includes(item.streamId))return{status:"refused",code:"managed_tool_result_invalid"};const stream=item.streamId;const body2=Buffer.from(JSON.stringify({segmentCount:item["segmentCount"],byteLength:item["byteLength"],digest:item["digest"]}));let receipt2;try{receipt2=await client.operation(`/streams/${stream}/seal`,"seal-"+stream+"-"+createHash4("sha256").update(body2).digest("hex").slice(0,32),body2,{"Content-Type":"application/json"})}catch(cause){const code=refusal(cause);if(code)return{status:"refused",code};throw cause}if(receipt2["segmentCount"]!==item["segmentCount"]||receipt2["byteLength"]!==item["byteLength"]||receipt2["digest"]!==item["digest"])throw new Error("Original seal receipt conflicts.");return{status:"ok",result:{segmentCount:item.segmentCount,byteLength:item.byteLength,digest:item.digest}}},"seal"),prefix:__name(async raw=>{let item;try{item=parseToolResultPrefixRequest(raw)}catch(cause){if(cause instanceof ManagedSessionRecordError)return{status:"refused",code:"managed_tool_result_invalid"};throw cause}if(item.captureId!==identity.captureId)return{status:"refused",code:"managed_tool_result_conflict"};if(!["stdout","stderr"].includes(item.streamId))return{status:"ok",result:{segmentCount:0,byteLength:0,digest:createHash4("sha256").digest("hex"),sealed:false}};let receipt2;try{receipt2=await client.operation(`/streams/${item.streamId}/prefix`,"prefix-"+item.streamId+"-"+randomUUID2(),Buffer.alloc(0))}catch(cause){const code=refusal(cause);if(code)return{status:"refused",code};throw cause}if(!Number.isSafeInteger(receipt2["segmentCount"])||!Number.isSafeInteger(receipt2["byteLength"])||typeof receipt2["digest"]!=="string"||typeof receipt2["sealed"]!=="boolean")throw new Error("Original prefix receipt is invalid.");return{status:"ok",result:{segmentCount:receipt2["segmentCount"],byteLength:receipt2["byteLength"],digest:receipt2["digest"],sealed:receipt2["sealed"]}}},"prefix"),readRange:__name(async()=>{throw new Error("Worker range lookup is unavailable.")},"readRange"),close:__name(async()=>{},"close")};const resources2={publish:__name(async(kind,bytes)=>{const metadata=record(JSON.parse(bytes.toString("utf8")));const slot=kind==="managed-tool-result-manifest"?"manifest:1":`page:${String(metadata["streamId"])}:${String(metadata["firstOrdinal"])}`;const published=await client.operation(`/resources/${kind}/${encodeURIComponent(slot)}`,`res-${slot.replaceAll(":","-")}`,bytes);const ref2=assertManagedSessionDurableRef(published,"published result resource");if(ref2.kind!==kind||ref2.byteLength!==bytes.length||ref2.digest!==createHash4("sha256").update(bytes).digest("hex"))throw new Error("Original resource receipt conflicts.");return ref2},"publish"),read:__name(async()=>{throw new Error("Worker resource reads are unavailable.")},"read")};return Promise.resolve({identity,sink:new LocalShellResultCapture(store,resources2,identity)})}async finish(identity,envelope){const grant=this.grants.get(identity.executionCallId);if(!grant||grant.binding["captureId"]!==identity.captureId)throw new Error("Original publication grant changed.");const bytes=Buffer.from(JSON.stringify(envelope));const client=this.clients.get(identity.executionCallId);if(!client)throw new Error("Original publication client is missing.");const receipt2=await client.operation("/finish","finish",bytes,{"Content-Type":"application/json"});const terminal=record(receipt2["terminal"]);if(receipt2["producerPhase"]!=="FINISHED"||terminal["byteLength"]!==bytes.length||terminal["digest"]!==createHash4("sha256").update(bytes).digest("hex"))throw new Error("Publication finish was not confirmed.")}registerInstallRoute(app,boot,admissionOpen=()=>true){app.post(PUBLICATION_INSTALL_ROUTE.path,managedRuntimeNoStore,authorizeManagedRuntime(boot),managedRuntimeJsonBody(PUBLICATION_INSTALL_ROUTE.requestBodyLimitBytes),(req,res)=>{try{if(!admissionOpen())throw new Error("Publication admission is sealed.");this.install(req.body,boot);res.json({protocolVersion:3,publication:"managed-tool-publication/1",installed:true})}catch{res.status(409).json({code:"managed_tool_publication_conflict",error:"Publication installation conflicts."})}},handleManagedRuntimeJsonError)}};init_esbuild_shims();var REFERENCE_KEYS=Object.freeze(["argsDigest","callId","promptId","sessionId"]);var INVALID_MESSAGE="Managed Runtime tool request is invalid.";function isNonEmptyString2(value){return typeof value==="string"&&value.length>0}__name(isNonEmptyString2,"isNonEmptyString");function parseReference(value){if(!value||typeof value!=="object"||Array.isArray(value)){return null}const keys=Object.keys(value).sort();if(keys.length!==REFERENCE_KEYS.length||!keys.every((key,index)=>key===REFERENCE_KEYS[index])){return null}const reference2=value;if(!isNonEmptyString2(reference2["sessionId"])||!isNonEmptyString2(reference2["promptId"])||!isNonEmptyString2(reference2["callId"])||!isNonEmptyString2(reference2["argsDigest"])){return null}return reference2}__name(parseReference,"parseReference");function parseClosedBody(value,requiredKeys,optionalKeys=[]){if(!value||typeof value!=="object"||Array.isArray(value)){return null}const body2=value;if(body2["protocolVersion"]!==2){return null}const allowed=new Set([...requiredKeys,...optionalKeys]);if(Object.keys(body2).some(key=>!allowed.has(key))){return null}if(requiredKeys.some(key=>!(key in body2))){return null}return body2}__name(parseClosedBody,"parseClosedBody");function invalid(res){res.status(400).json({code:"managed_runtime_attestation_invalid",error:INVALID_MESSAGE})}__name(invalid,"invalid");function registerManagedRuntimeToolRoutes(app,identity,executor){const routes=new Map(OWNED_MANAGED_RUNTIME_ROUTES.filter(route=>route.key!=="attest").map(route=>[route.key,route]));app.post(routes.get("execute").path,managedRuntimeNoStore,authorizeManagedRuntime(identity),nameManagedRuntimeIncarnation(identity),managedRuntimeJsonBody(routes.get("execute").requestBodyLimitBytes),async(req,res)=>{const body2=parseClosedBody(req.body,["protocolVersion","reference","toolName","input"]);const reference2=body2&&parseReference(body2["reference"]);const toolName=body2?.["toolName"];const input=body2?.["input"];if(!body2||!reference2||!isNonEmptyString2(toolName)||!input||typeof input!=="object"||Array.isArray(input)){invalid(res);return}if(!executor.hasTool(toolName)){res.status(409).json({code:"managed_runtime_identity_conflict",error:"Managed Runtime does not admit this tool."});return}try{const result=await executor.execute(reference2,toolName,input);res.status(200).json({protocolVersion:2,state:"settled",result})}catch(error){if(error instanceof ManagedMcpError){res.status(400).json({code:error.code});return}if(error instanceof ManagedMcpToolUnknownError){res.status(200).json({protocolVersion:2,state:"unknown"});return}if(error instanceof ManagedToolInvalidError){invalid(res);return}if(error instanceof ManagedToolConflictError||error instanceof ManagedToolUnavailableError){res.status(409).json({code:error.code,error:error.message});return}throw error}},handleManagedRuntimeJsonError);app.post(routes.get("status").path,managedRuntimeNoStore,authorizeManagedRuntime(identity),nameManagedRuntimeIncarnation(identity),managedRuntimeJsonBody(routes.get("status").requestBodyLimitBytes),(req,res)=>{const body2=parseClosedBody(req.body,["protocolVersion","reference"],["afterSequence"]);const reference2=body2&&parseReference(body2["reference"]);const afterSequence=body2?.["afterSequence"];if(!body2||!reference2||afterSequence!==void 0&&(typeof afterSequence!=="number"||!Number.isSafeInteger(afterSequence)||afterSequence<0)){invalid(res);return}try{const view2=executor.status(reference2);if(!view2){res.status(200).json({protocolVersion:2,state:"unknown"});return}res.status(200).json({protocolVersion:2,state:view2.state,...view2.state==="settled"?{result:view2.result}:{},lastSequence:view2.lastSequence})}catch(error){if(error instanceof ManagedToolConflictError){res.status(409).json({code:error.code,error:error.message});return}throw error}},handleManagedRuntimeJsonError);app.post(routes.get("cancel").path,managedRuntimeNoStore,authorizeManagedRuntime(identity),nameManagedRuntimeIncarnation(identity),managedRuntimeJsonBody(routes.get("cancel").requestBodyLimitBytes),(req,res)=>{const body2=parseClosedBody(req.body,["protocolVersion","reference"]);const reference2=body2&&parseReference(body2["reference"]);if(!body2||!reference2){invalid(res);return}try{const view2=executor.cancel(reference2);if(!view2){res.status(200).json({protocolVersion:2,state:"unknown"});return}res.status(200).json({protocolVersion:2,state:view2.state,...view2.state==="settled"?{result:view2.result}:{}})}catch(error){if(error instanceof ManagedToolConflictError){res.status(409).json({code:error.code,error:error.message});return}throw error}},handleManagedRuntimeJsonError);app.post(routes.get("acknowledge").path,managedRuntimeNoStore,authorizeManagedRuntime(identity),nameManagedRuntimeIncarnation(identity),managedRuntimeJsonBody(routes.get("acknowledge").requestBodyLimitBytes),(req,res)=>{const body2=parseClosedBody(req.body,["protocolVersion","reference"]);const reference2=body2&&parseReference(body2["reference"]);if(!body2||!reference2){invalid(res);return}try{const view2=executor.acknowledge(reference2);if(!view2){res.status(200).json({protocolVersion:2,state:"unknown"});return}res.status(200).json({protocolVersion:2,state:view2.state})}catch(error){if(error instanceof ManagedToolConflictError){res.status(409).json({code:error.code,error:error.message});return}throw error}},handleManagedRuntimeJsonError)}__name(registerManagedRuntimeToolRoutes,"registerManagedRuntimeToolRoutes");init_esbuild_shims();function closed3(value,keys,optional=[]){if(!value||typeof value!=="object"||Array.isArray(value))return null;const body2=value;if(Object.keys(body2).some(key=>!keys.includes(key)))return null;if(keys.some(key=>!optional.includes(key)&&!(key in body2)))return null;return body2}__name(closed3,"closed");function reference(value){const body2=closed3(value,["sessionId","promptId","callId","argsDigest"]);if(!body2||typeof body2["argsDigest"]!=="string"||!/^(?:sha256:)?[0-9a-f]{64}$/.test(body2["argsDigest"]))return null;try{for(const key of["sessionId","promptId","callId"]){assertManagedSessionStableId(body2[key],`reference.${key}`)}}catch{return null}return body2}__name(reference,"reference");function body(value,keys,optional=[]){const parsed=closed3(value,["protocolVersion","toolResult",...keys],optional);return parsed?.["protocolVersion"]===3&&parsed["toolResult"]===MANAGED_TOOL_RESULT_PROTOCOL?parsed:null}__name(body,"body");function capture(value){const parsed=closed3(value,["tenantId","sessionId","turnId","executionCallId","bindingGeneration","capturePolicy"]);if(!parsed||parsed["capturePolicy"]!=="complete_required"||typeof parsed["bindingGeneration"]!=="string"||!/^[1-9][0-9]{0,18}$/.test(parsed["bindingGeneration"])||BigInt(parsed["bindingGeneration"])>2n**63n-1n)return null;try{for(const key of["tenantId","sessionId","turnId","executionCallId"]){assertManagedSessionStableId(parsed[key],`capture.${key}`)}}catch{return null}return parsed}__name(capture,"capture");function receipt(value){const parsed=closed3(value,["executionCallId","manifest","deliveryStatus","historyRevision"]);if(!parsed)return null;try{assertManagedSessionStableId(parsed["executionCallId"],"receipt.executionCallId")}catch{return null}const deliveryStatus=parsed["deliveryStatus"];if(deliveryStatus!=="committed"&&deliveryStatus!=="blocked")return null;let manifest=null;try{if(parsed["manifest"]!==null){manifest=assertManagedSessionDurableRef(parsed["manifest"],"receipt.manifest");if(manifest.kind!==MANAGED_TOOL_RESULT_KINDS.manifest||manifest.byteLength<1||manifest.byteLength>MANAGED_TOOL_RESULT_LIMITS.maxManifestBytes)return null}}catch{return null}const historyRevision=parsed["historyRevision"];if(deliveryStatus==="committed"?!Number.isSafeInteger(historyRevision)||historyRevision<1:historyRevision!==null)return null;return{executionCallId:parsed["executionCallId"],manifest,deliveryStatus,historyRevision}}__name(receipt,"receipt");function invalid2(res){res.status(400).json({code:"managed_runtime_attestation_invalid",error:"Managed Tool v3 request is invalid."})}__name(invalid2,"invalid");function failure(res,cause){if(cause instanceof ManagedToolInvalidError)return invalid2(res);if(cause instanceof ManagedToolConflictError||cause instanceof ManagedToolUnavailableError){res.status(409).json({code:cause.code,error:cause.message});return}throw cause}__name(failure,"failure");function registerManagedRuntimeToolV3Routes(app,identity,executor){const routes=Object.fromEntries(MANAGED_TOOL_RESULT_ROUTES.map(route=>[route.key,route]));const prefix={protocolVersion:3,toolResult:MANAGED_TOOL_RESULT_PROTOCOL};app.post(routes["execute"].path,managedRuntimeNoStore,authorizeManagedRuntime(identity),managedRuntimeJsonBody(routes["execute"].requestBodyLimitBytes),async(req,res)=>{const parsed=body(req.body,["reference","toolName","input","capture"]);const ref2=reference(parsed?.["reference"]);const cap=capture(parsed?.["capture"]);const input=parsed?.["input"];if(!parsed||!ref2||!cap||parsed["toolName"]!=="run_shell_command"&&parsed["toolName"]!=="monitor"||!input||typeof input!=="object"||Array.isArray(input))return invalid2(res);try{const view2=await executor.executeV3({reference:ref2,capture:cap,toolName:parsed["toolName"],input});res.status(200).json({...prefix,state:view2.state,...view2.result?{result:view2.result}:{}})}catch(cause){failure(res,cause)}},handleManagedRuntimeJsonError);app.post(routes["status"].path,managedRuntimeNoStore,authorizeManagedRuntime(identity),managedRuntimeJsonBody(routes["status"].requestBodyLimitBytes),(req,res)=>{const parsed=body(req.body,["reference","afterSequence"],["afterSequence"]);const ref2=reference(parsed?.["reference"]);const after=parsed?.["afterSequence"];if(!parsed||!ref2||after!==void 0&&(!Number.isSafeInteger(after)||after<0))return invalid2(res);try{const view2=executor.statusV3(ref2);res.status(200).json({...prefix,state:view2.state,...view2.result?{result:view2.result}:{},...view2.lastSequence!==void 0?{lastSequence:view2.lastSequence}:{}})}catch(cause){failure(res,cause)}},handleManagedRuntimeJsonError);app.post(routes["cancel"].path,managedRuntimeNoStore,authorizeManagedRuntime(identity),managedRuntimeJsonBody(routes["cancel"].requestBodyLimitBytes),(req,res)=>{const parsed=body(req.body,["reference"]);const ref2=reference(parsed?.["reference"]);if(!parsed||!ref2)return invalid2(res);try{const view2=executor.cancelV3(ref2);res.status(200).json({...prefix,state:view2.state,...view2.result?{result:view2.result}:{}})}catch(cause){failure(res,cause)}},handleManagedRuntimeJsonError);app.post(routes["acknowledge"].path,managedRuntimeNoStore,authorizeManagedRuntime(identity),managedRuntimeJsonBody(routes["acknowledge"].requestBodyLimitBytes),(req,res)=>{const parsed=body(req.body,["reference","receipt"]);const ref2=reference(parsed?.["reference"]);const ack=receipt(parsed?.["receipt"]);if(!parsed||!ref2||!ack)return invalid2(res);try{const view2=executor.acknowledgeV3(ref2,ack);res.status(200).json({...prefix,state:view2.state,...view2.result?{result:view2.result}:{}})}catch(cause){failure(res,cause)}},handleManagedRuntimeJsonError)}__name(registerManagedRuntimeToolV3Routes,"registerManagedRuntimeToolV3Routes");init_esbuild_shims();import{randomUUID as randomUUID4}from"node:crypto";import fs2 from"node:fs";import path3 from"node:path";init_esbuild_shims();import{randomUUID as randomUUID3}from"node:crypto";function invocationParams(params){const projected=JSON.parse(JSON.stringify(params));managedToolDigest(projected);return projected}__name(invocationParams,"invocationParams");function refuseUpdatedInput(result){const{updatedInput,...rest}=result;if(updatedInput===void 0||!rest.shouldProceed&&rest.blockType!=="ask"){return rest}return{...rest,shouldProceed:false,blockType:"denied",blockReason:"PreToolUse updatedInput is not supported for managed tool invocations; the tool was not run."}}__name(refuseUpdatedInput,"refuseUpdatedInput");var ManagedToolPreparationError=class extends Error{static{__name(this,"ManagedToolPreparationError")}};var MAX_INVOCATIONS=1024;var MAX_PROGRESS_BYTES=1024*1024;var ManagedToolRuntime=class{constructor(config,tools,policyRevision,sharedFileHistory,bindMediaTool){this.config=config;this.tools=tools;this.policyRevision=policyRevision;this.sharedFileHistory=sharedFileHistory;this.bindMediaTool=bindMediaTool}static{__name(this,"ManagedToolRuntime")}entries=new Map;calls=new Map;lifetime=new AbortController;activePrompt;pendingBuilds=0;pendingPreparations=0;snapshotPending=false;startedPrompts=new Set;disposal;manifest(){this.lifetime.signal.throwIfAborted();const tools=this.tools().map(tool=>({name:tool.name,displayName:tool.displayName,description:tool.description,kind:tool.kind,schema:tool.schema,canUpdateOutput:tool.canUpdateOutput,isOutputMarkdown:tool.isOutputMarkdown,shouldDefer:tool.shouldDefer,alwaysLoad:tool.alwaysLoad,...tool.searchHint===void 0?{}:{searchHint:tool.searchHint},...tool.maxOutputChars===void 0?{}:{maxOutputChars:tool.maxOutputChars===Infinity?"unlimited":tool.maxOutputChars},truncateKeep:tool.truncateKeep}));return{tools:structuredClone(tools),capabilityDigest:managedToolDigest(tools,1024*1024),policyRevision:this.policyRevision()}}assertCurrent(identity){this.lifetime.signal.throwIfAborted();const current=this.manifest();if(identity.sessionId!==this.config.getSessionId().toLowerCase()||identity.capabilityDigest!==current.capabilityDigest||identity.policyRevision!==current.policyRevision)throw new Error("Managed tool Session or capability changed.")}get(reference2){const entry=this.entries.get(reference2.invocationId);if(!entry||managedToolDigest(reference2)!==managedToolDigest(entry.reference)){throw new Error("Managed tool invocation identity does not match.")}return entry}scoped(identity,action){const owner="invocationId"in identity&&typeof identity.invocationId==="string"?this.entries.get(identity.invocationId)?.hookOwner:captureHookExecutionOwner(this.config);return runWithHookExecutionOwner(owner,()=>promptIdContext.run(identity.promptId,()=>runWithInvocationContext({version:1,sessionId:identity.sessionId,promptId:identity.promptId},action)))}beginTurn(identity){this.assertCurrent(identity);if(this.activePrompt?.id===identity.promptId)return this.activePrompt.snapshot;if(this.snapshotPending||this.pendingPreparations||[...this.entries.values()].some(entry=>!entry.result)){throw new Error("Managed Runtime still owns an unfinished tool invocation.")}if(this.startedPrompts.has(identity.promptId)){throw new Error("Managed Runtime cannot reopen a previous tool turn.")}this.entries.clear();this.calls.clear();identity=structuredClone(identity);this.snapshotPending=true;this.startedPrompts.add(identity.promptId);const snapshot=this.scoped(identity,async()=>{try{if(this.sharedFileHistory){await this.sharedFileHistory.prepareTurn(identity)}else{await this.config.getFileHistoryService().makeSnapshot(identity.promptId)}this.assertCurrent(identity)}finally{this.snapshotPending=false}});this.activePrompt={id:identity.promptId,snapshot};void snapshot.catch(()=>{});return snapshot}prepare(identity,toolName,input,modification,mediaContext){this.assertCurrent(identity);managedToolDigest(input);identity=structuredClone(identity);const copied=structuredClone(input);const media=mediaContext===void 0?void 0:parseManagedToolMediaContext(mediaContext);const contentModification=modification===void 0?void 0:parseManagedToolContentModification(modification);const inputDigest=managedToolDigest({identity,toolName,input:copied,...media===void 0?{}:{mediaContext:media},...contentModification===void 0?{}:{modification:contentModification}},1024*1024);const key=JSON.stringify([identity.promptId,identity.callId]);const slot=this.calls.get(key)??{};const previous=slot.pending;this.pendingPreparations++;const pending=(async()=>{await previous?.catch(()=>{});const entry=slot.current;if(entry){if(entry.inputDigest===inputDigest)return entry;if(!entry.controller.signal.aborted||entry.execution){throw new Error("Managed tool call already owns another invocation.")}await entry.cancellation}this.assertCurrent(identity);if(this.activePrompt?.id!==identity.promptId){throw new Error("Managed Runtime tool turn has not started.")}if(this.entries.size+this.pendingBuilds>=MAX_INVOCATIONS){throw new Error("Managed tool invocation capacity is exhausted.")}this.pendingBuilds++;try{await this.activePrompt.snapshot;this.assertCurrent(identity);const built=await this.scoped(identity,()=>this.build(identity,toolName,copied,inputDigest,contentModification,entry,media));slot.current=built;return built}finally{this.pendingBuilds--}})();void pending.then(()=>{this.pendingPreparations--},()=>{this.pendingPreparations--});slot.pending=pending;this.calls.set(key,slot);void pending.catch(()=>{if(slot.pending===pending&&!slot.current)this.calls.delete(key)});return pending.then(entry=>structuredClone(entry.prepared))}async build(identity,toolName,input,inputDigest,modification,source,mediaContext){const hookOwner=source?source.hookOwner:captureHookExecutionOwner(this.config);let tool=this.tools().find(candidate=>candidate.name===toolName);if(!tool)throw new ManagedToolPreparationError("Managed Runtime tool is unavailable.");if(mediaContext!==void 0){if(!this.bindMediaTool)throw new Error("Managed Runtime tool does not support media context.");tool=this.bindMediaTool(tool,mediaContext)}if(modification){if(!source||this.get(modification.source)!==source||source.tool!==tool||tool.name!==ToolNames.NOTEBOOK_EDIT||!isModifiableDeclarativeTool(tool)||!source.controller.signal.aborted||source.execution||managedToolDigest(input)!==source.reference.argsDigest)throw new Error("Managed content modification source does not match.");const details=await source.confirmation;if(details?.type!=="edit"||typeof details.originalContent!=="string")throw new Error("Managed content modification requires an edit confirmation.");this.assertCurrent(identity);input=tool.getModifyContext(this.lifetime.signal).createUpdatedParams(details.originalContent,modification.newContent,source.invocation.params)}let invocation;try{invocation=tool.build(input)}catch(error){throw new ManagedToolPreparationError(error instanceof Error?error.message:"Managed Runtime tool input is invalid.")}const aware=invocation;aware.setCallId?.(identity.callId);aware.setPromptId?.(identity.promptId);const defaultPermission=await invocation.getDefaultPermission();this.assertCurrent(identity);const reference2={...identity,invocationId:randomUUID3(),argsDigest:managedToolDigest(invocationParams(invocation.params))};const toolUseId=generateToolUseId();const entry={hookOwner,reference:reference2,inputDigest,tool,invocation,controller:new AbortController,toolUseId,prepared:{...reference2,params:invocationParams(invocation.params),description:invocation.getDescription(),locations:invocation.toolLocations(),defaultPermission,requiresUserInteraction:invocation.requiresUserInteraction?.()??false,toolUseId},decisions:new Map,hookConfirmed:false,progress:[],progressBytes:0,sequence:0};this.entries.set(reference2.invocationId,entry);return entry}async confirmation(reference2){const entry=this.get(reference2);this.assertExecutable(entry);entry.confirmation??=this.scoped(reference2,async()=>{const details2=await entry.invocation.getConfirmationDetails(entry.controller.signal);serializeManagedToolConfirmation(details2);return details2});const details=await entry.confirmation;this.assertExecutable(entry);return serializeManagedToolConfirmation(details)}async confirm(reference2,outcome,payload,phase="permission"){const entry=this.get(reference2);reference2=entry.reference;payload=payload===void 0?void 0:structuredClone(payload);if(phase!=="permission"&&phase!=="preflight")throw new Error("Invalid managed confirmation phase.");if(!Object.values(ToolConfirmationOutcome).includes(outcome)||outcome==="restore_previous"){throw new Error("Unsupported managed tool confirmation outcome.")}const digest2=managedToolDigest({outcome,...payload?{payload}:{}});const previous=entry.decisions.get(phase);if(previous){if(previous.digest!==digest2)throw new Error("Managed tool confirmation already decided.");return previous.promise}this.assertExecutable(entry);if(phase==="permission"&&entry.preflight)throw new Error("Managed tool preflight already started.");if(phase==="preflight"&&entry.preflightResult?.blockType!=="ask")throw new Error("Managed tool preflight did not request confirmation.");if(payload?.updatedInput!==void 0||payload?.newContent!==void 0||outcome==="modify_with_editor"){this.cancel(reference2);throw new Error("Modified tool arguments require a new preparation.")}const pending=(async()=>{await this.confirmation(reference2);this.assertExecutable(entry);const details=await entry.confirmation;await this.scoped(reference2,()=>details.onConfirm(runtimeLocalOutcome(outcome),payload));if(outcome==="cancel"){this.requestCancel(entry);return}this.assertExecutable(entry);if(phase==="preflight")entry.hookConfirmed=true})();const decision={digest:digest2,promise:pending,settled:false};entry.decisions.set(phase,decision);void pending.then(()=>{decision.settled=true},()=>{decision.settled=true});return pending}assertExecutable(entry){this.assertCurrent(entry.reference);entry.controller.signal.throwIfAborted();if(entry.execution)throw new Error("Managed tool invocation already dispatched.");if(managedToolDigest(invocationParams(entry.invocation.params))!==entry.reference.argsDigest){throw new Error("Managed tool parameters changed after preparation.")}}async preflight(reference2){const entry=this.get(reference2);this.assertExecutable(entry);entry.preflight??=this.scoped(reference2,async()=>{for(const decision of entry.decisions.values())await decision.promise;this.assertExecutable(entry);const result=await firePreToolUseHook(this.config.getDisableAllHooks()?void 0:this.config.getMessageBus(),entry.tool.name,entry.invocation.params,entry.toolUseId,this.config.getApprovalMode(),entry.controller.signal,entry.reference.callId,entry.hookOwner);this.assertExecutable(entry);const settled=refuseUpdatedInput(result);entry.preflightResult=structuredClone(settled);return settled});return structuredClone(await entry.preflight)}execute(reference2){const entry=this.get(reference2);if(entry.execution)return entry.execution.then(result=>structuredClone(result));this.assertExecutable(entry);const preflight=entry.preflightResult;if(!preflight||!preflight.shouldProceed&&!(preflight.blockType==="ask"&&entry.hookConfirmed)){throw new Error("Managed tool preflight has not permitted execution.")}if([...entry.decisions.values()].some(decision=>!decision.settled)){throw new Error("Managed tool confirmation is still pending.")}entry.execution=this.scoped(reference2,()=>this.sharedFileHistory?this.sharedFileHistory.execute(()=>this.run(entry)):this.run(entry)).catch(error=>{entry.result??={executionStatus:"not_started",error:{message:error instanceof Error?error.message:String(error),type:"execution_failed"}};throw error});void entry.execution.catch(()=>{});return entry.execution.then(result=>structuredClone(result))}progress(entry,output){const seq=++entry.sequence;const event={seq,output:structuredClone(output)};const bytes=Buffer.byteLength(JSON.stringify(event));if(bytes>MAX_PROGRESS_BYTES){entry.progress=[];entry.progressBytes=0;return}entry.progress.push({...event,bytes});entry.progressBytes+=bytes;while(entry.progressBytes>MAX_PROGRESS_BYTES){entry.progressBytes-=entry.progress.shift().bytes}}async run(entry){const signal=entry.controller.signal;const messageBus=this.config.getDisableAllHooks()?void 0:this.config.getMessageBus();let result;let executionStarted=false;try{signal.throwIfAborted();this.assertCurrent(entry.reference);executionStarted=true;const raw=await entry.invocation.execute(signal,output=>this.progress(entry,output),this.config.getShellExecutionConfig());result={executionStatus:isShellResultDisplay(raw.returnDisplay)&&raw.returnDisplay.outcome==="cancelled"?"cancelled":raw.error?signal.aborted?"cancelled":"error":"success"};try{result.result=structuredClone({llmContent:raw.llmContent,returnDisplay:raw.returnDisplay,...raw.error===void 0?{}:{error:raw.error},...raw.resultFilePaths===void 0?{}:{resultFilePaths:raw.resultFilePaths},...raw.persistedOutputFiles===void 0?{}:{persistedOutputFiles:raw.persistedOutputFiles},...raw.artifacts===void 0?{}:{artifacts:raw.artifacts}})}catch(error){result.error={message:`Cannot serialize managed tool result: ${String(error)}`,type:"execution_failed"}}}catch(error){result={executionStatus:!executionStarted?"not_started":signal.aborted?"cancelled":"error",error:{message:error instanceof Error?error.message:String(error),type:"execution_failed"}}}try{if(result.executionStatus==="error"||result.executionStatus==="cancelled"||result.result?.error!==void 0){result.failureHook=await firePostToolUseFailureHook(messageBus,entry.toolUseId,entry.tool.name,entry.invocation.params,result.result?.error?.message??result.error?.message??"Tool execution failed.",result.executionStatus==="cancelled"||signal.aborted,this.config.getApprovalMode(),void 0,entry.reference.callId,void 0,entry.hookOwner)}else if(result.executionStatus==="success"&&result.result){result.postHook=await firePostToolUseHook(messageBus,entry.tool.name,entry.invocation.params,{llmContent:result.result.llmContent,returnDisplay:result.result.returnDisplay},entry.toolUseId,this.config.getApprovalMode(),void 0,entry.reference.callId,void 0,entry.hookOwner)}}catch(error){const hookError=error instanceof Error?error.message:String(error);if(result.executionStatus==="success")result.postHook={shouldStop:false,hookError};else result.failureHook={hookError}}entry.result=structuredClone(result);return entry.result}findStatus(reference2,afterSeq=0){return this.entries.has(reference2.invocationId)?this.status(reference2,afterSeq):void 0}status(reference2,afterSeq=0){if(!Number.isSafeInteger(afterSeq)||afterSeq<0)throw new Error("Invalid managed tool progress cursor.");const entry=this.get(reference2);const firstAvailableSeq=entry.progress[0]?.seq??entry.sequence+1;return{state:entry.result?"settled":entry.controller.signal.aborted?"cancel_requested":entry.execution?"executing":"prepared",cancelRequested:entry.controller.signal.aborted,lastSeq:entry.sequence,firstAvailableSeq,progressGap:afterSeq+1<firstAvailableSeq,progress:structuredClone(entry.progress.filter(event=>event.seq>afterSeq).map(({seq,output})=>({seq,output}))),...entry.result?{result:structuredClone(entry.result)}:{}}}requestCancel(entry){entry.controller.abort(new Error("Managed tool invocation cancelled."));if(!entry.execution){entry.cancellation??=(async()=>{await Promise.allSettled([entry.confirmation,entry.preflight,...[...entry.decisions.values()].map(decision=>decision.promise)]);entry.result={executionStatus:"not_started"}})()}}cancel(reference2){const entry=this.get(reference2);this.requestCancel(entry);return this.status(reference2)}hasActiveWork(){return this.snapshotPending||this.pendingPreparations>0||[...this.entries.values()].some(entry=>!entry.result)}async releasePrepared(){if(this.snapshotPending||this.pendingPreparations>0||[...this.entries.values()].some(entry=>entry.execution!==void 0&&!entry.result)){throw new Error("Managed Runtime still owns unfinished execution.")}for(const entry of this.entries.values()){if(!entry.result)this.requestCancel(entry)}await Promise.all([...this.entries.values()].map(entry=>entry.cancellation))}seal(){this.lifetime.abort(new Error("Managed tool Runtime is closed."));for(const entry of this.entries.values())this.requestCancel(entry)}dispose(){this.disposal??=(async()=>{this.seal();await Promise.allSettled([...[...this.calls.values()].map(slot=>slot.pending),this.activePrompt?.snapshot]);await Promise.allSettled([...this.entries.values()].flatMap(entry=>[entry.confirmation,entry.preflight,entry.execution,entry.cancellation,...[...entry.decisions.values()].map(decision=>decision.promise)]));this.entries.clear();this.calls.clear()})();return this.disposal}};function runtimeLocalOutcome(outcome){switch(outcome){case"proceed_always":case"proceed_always_server":case"proceed_always_tool":case"proceed_always_project":case"proceed_always_user":return"proceed_once";default:return outcome}}__name(runtimeLocalOutcome,"runtimeLocalOutcome");var debugLogger2=createDebugLogger("MANAGED_RUNTIME_PROVIDER");function conflict(message,code="managed_runtime_provider_operation_failed"){throw new ManagedToolConflictError(message,code)}__name(conflict,"conflict");function forgetSession(runtimeSessionId){unregisterSessionProjectDir(runtimeSessionId);unregisterSessionModel(runtimeSessionId)}__name(forgetSession,"forgetSession");var RETAINED_RELEASED_SESSIONS=8;function retire(entry){entry.retirement??=(async()=>{const value=entry.value;const errors=[];for(const step of[()=>value?.runtime.dispose(),()=>value?.history?.drain(),()=>value?.config.shutdown({shutdownTelemetry:false,skipSessionWriter:true})]){try{await step()}catch(error){errors.push(error)}}entry.value=void 0;entry.ready=void 0;if(errors.length>0)throw new AggregateError(errors,"Retiring a Managed Runtime Session failed.")})();return entry.retirement}__name(retire,"retire");function history(value){return value.history??conflict("Managed Runtime file history is not bound.")}__name(history,"history");function workspaceAdmits(config,directory){if(!path3.isAbsolute(directory))return false;try{const real=fs2.realpathSync.native(directory);return config.getWorkspaceContext().getDirectories().some(root=>isPathWithinRoot(real,fs2.realpathSync.native(root)))}catch{return false}}__name(workspaceAdmits,"workspaceAdmits");var WorkspaceShellTool=class extends ShellTool{constructor(config,workspace){super(config);this.workspace=workspace}static{__name(this,"WorkspaceShellTool")}validateToolParamValues(params){return super.validateToolParamValues(params)??this.outside(params)}createInvocation(params){const invocation=super.createInvocation(params);const execute=invocation.execute.bind(invocation);invocation.execute=(...args)=>{const refusal2=this.outside(params);if(refusal2)throw new Error(refusal2);return execute(...args)};return invocation}outside(params){const directory=params.directory;return typeof directory==="string"&&directory!==""&&!workspaceAdmits(this.workspace,directory)?`Directory '${directory}' is not within any of the registered workspace directories.`:null}};var ManagedRuntimeProviderWorker=class{constructor(executor,contextFor){this.executor=executor;this.contextFor=contextFor}static{__name(this,"ManagedRuntimeProviderWorker")}sessions=new Map;released=[];closing=false;hasActiveSession(sessionId){const session=this.sessions.get(sessionId);return session!==void 0&&(session.pending>0||session.value?.runtime.hasActiveWork()===true)}getDrainInspection(){return{pendingInvocations:[...this.sessions.values()].reduce((count,session)=>count+session.pending+(session.value?.runtime.hasActiveWork()?1:0),0),hasActivity:[...this.sessions.values()].some(session=>session.ready!==void 0||session.value!==void 0)}}assertAdmissionOpen(){if(!this.executor.isAdmissionOpen)throw new ManagedToolUnavailableError("Managed Runtime admission is sealed.")}lookup(identity){const session=this.sessions.get(identity.runtimeSessionId);if(session&&(session.identity.harnessSessionId!==identity.harnessSessionId||session.identity.turnKind!==identity.turnKind)){conflict("Managed Runtime Session identity conflicts.","managed_runtime_identity_conflict")}return session}async control(identity,operation){if(operation.kind==="workspace-context")return this.executor.readWorkspaceContext(identity.runtimeSessionId);if(operation.kind==="raw-file-history")return this.executor.controlFileHistory(identity.harnessSessionId,identity.runtimeSessionId,operation);let session=this.lookup(identity);if(operation.kind==="release"){if(session?.closed)return true;if(!session){this.executor.closeSessionAdmission(identity.runtimeSessionId);this.sessions.set(identity.runtimeSessionId,{identity,closed:true,pending:0});return true}if(session.release)return session.release;if(session.pending>0)conflict("Managed Runtime Session still owns unfinished work.","managed_runtime_owner_hold_pending");const entry=session;entry.release=(async()=>{await entry.value?.runtime.releasePrepared();this.executor.closeSessionAdmission(identity.runtimeSessionId);forgetSession(identity.runtimeSessionId);entry.closed=true;this.released.push(entry);await this.retireReleased();return true})().catch(error=>{entry.release=void 0;throw error});return entry.release}if(operation.kind==="acquire"){this.assertAdmissionOpen();if(this.closing||session?.closed||session?.release)conflict("Managed Runtime Session is closed.");if(!session){this.executor.claimProviderSession(identity.runtimeSessionId);session={identity,closed:false,pending:0};this.sessions.set(identity.runtimeSessionId,session)}if(!session.ready){const entry=session;entry.pending++;entry.ready=this.createRuntime(identity.runtimeSessionId).then(value=>{entry.value=value;return value}).catch(error=>{this.executor.unclaimProviderSession(identity.runtimeSessionId);this.sessions.delete(identity.runtimeSessionId);throw error}).finally(()=>{entry.pending--})}await session.ready;return true}if(session?.closed&&!session.ready){if(operation.kind==="status"||operation.kind==="cancel")return{state:"unknown"};conflict("Managed Runtime Session is closed.")}if(!session?.ready)conflict("Managed Runtime Session has not been acquired.");const observes=["status","cancel","history"].includes(operation.kind)||this.executor.isAdmissionSealed&&!this.closing&&operation.kind==="manifest";if(!observes)this.assertAdmissionOpen();if((this.closing||session.closed||session.release)&&!observes)conflict("Managed Runtime Session is closed.");session.pending++;try{const value=await session.ready;if(!observes)await this.assertContext(identity.runtimeSessionId,value);if(!observes)this.assertAdmissionOpen();return await sessionIdContext.run(identity.runtimeSessionId,()=>this.dispatch(value,operation))}finally{session.pending--}}async retireReleased(){while(this.released.length>RETAINED_RELEASED_SESSIONS){const index=this.released.findIndex(entry2=>entry2.pending===0);if(index<0)return;const[entry]=this.released.splice(index,1);await retire(entry).catch(error=>debugLogger2.warn("Retiring a released Session failed:",error))}}async assertContext(sessionId,value){const context=await this.contextFor(sessionId);if(!context||context.isActive?.()===false||context.directory!==value.context.directory||context.workspaceRoot!==value.context.workspaceRoot||context.preapproved!==value.context.preapproved){throw new ManagedToolUnavailableError("Managed context directory is unavailable.")}}async createRuntime(sessionId){const context=await this.contextFor(sessionId);if(this.executor.isAdmissionSealed)throw new ManagedToolUnavailableError("Managed Runtime admission is sealed.");if(!context||context.isActive?.()===false){throw new ManagedToolUnavailableError("Managed context directory is unavailable.")}return sessionIdContext.run(sessionId,()=>{const config=new Config({sessionId,targetDir:context.directory,cwd:context.directory,includeDirectories:[context.workspaceRoot],model:"managed-runtime-worker",debugMode:false,usageStatisticsEnabled:false,approvalMode:context.preapproved?"yolo":"default",fileCheckpointingEnabled:true,fileReadCacheDisabled:true});const toolConfig=deriveConfig(config,{getFileHistoryService:__name(()=>history(value).service,"getFileHistoryService")});const shell=new WorkspaceShellTool(toolConfig,config);const tools=[new ReadFileTool(toolConfig),new WriteFileTool(toolConfig),new EditTool(toolConfig),shell];const policyRevision=randomUUID4();const runtime=new ManagedToolRuntime(toolConfig,()=>tools,()=>policyRevision,{prepareTurn:__name(identity=>history(value).checkpoint(identity.promptId),"prepareTurn"),execute:__name(action=>history(value).run(()=>{if(this.executor.isAdmissionSealed)this.assertAdmissionOpen();return action()}),"execute")},(tool,media)=>{if(tool.name!==ReadFileTool.Name)conflict("Managed Runtime tool does not support media context.");return new ReadFileTool(deriveConfig(toolConfig,{getEffectiveInputModalities:__name(()=>({...media.inputModalities}),"getEffectiveInputModalities"),getFileReadCache:__name(()=>toolConfig.getFileReadCache(),"getFileReadCache"),getFileService:__name(()=>toolConfig.getFileService(),"getFileService")}))});const value={context,config,runtime,shell};registerSessionProjectDir(sessionId,config.storage.getProjectDir());return value})}async bindHistory(value,binding){if(binding.executionCwd!==value.context.directory||binding.executionContext!==void 0&&managedToolDigest(binding.executionContext)!==managedToolDigest(captureManagedToolExecutionContext(value.config))){conflict("Managed Runtime file history execution context conflicts.")}const digest2=managedToolDigest(binding,MANAGED_TOOL_FILE_HISTORY_MAX_BYTES);if(value.historyBinding!==void 0){if(value.historyBinding!==digest2)conflict("Managed Runtime file history binding conflicts.");await history(value).ready();return history(value).state()}if(value.runtime.hasActiveWork())conflict("Managed Runtime file history must be bound before starting a turn.");value.historyBinding=digest2;value.history=new ManagedToolFileHistory(binding.ownerSessionId,value.context.directory,binding.snapshots);await value.history.ready();return value.history.state()}async dispatch(value,operation){const runtime=value.runtime;switch(operation.kind){case"manifest":return runtime.manifest();case"begin-turn":await history(value).ready();this.assertAdmissionOpen();await runtime.beginTurn(operation.identity);return null;case"prepare":{if(operation.toolName===ShellTool.Name){const normalized=structuredClone(operation.input);if(value.shell.validateToolParams(normalized)===null&&normalized["is_background"]===true)conflict("Managed Runtime does not admit background shell execution.")}if(operation.modification!==void 0)throw new ManagedToolPreparationError("Managed Runtime provider profile does not admit content modification.");return runtime.prepare(operation.identity,operation.toolName,operation.input,void 0,operation.mediaContext)}case"confirmation":return runtime.confirmation(operation.reference);case"confirm":await runtime.confirm(operation.reference,operation.outcome,operation.payload,operation.phase);return null;case"preflight":return runtime.preflight(operation.reference);case"execute":return runtime.execute(operation.reference);case"status":case"cancel":{const status=runtime.findStatus(operation.reference,operation.kind==="status"?operation.afterSequence:0);if(!status)return{state:"unknown"};return operation.kind==="cancel"&&status.state!=="settled"?runtime.cancel(operation.reference):status}case"bind-history":return this.bindHistory(value,operation.binding);case"checkpoint":if(runtime.hasActiveWork())conflict("Managed Runtime Session still owns unfinished work.");await history(value).checkpoint(operation.promptId);return history(value).state();case"history":await history(value).drain();return history(value).state();case"acquire":case"release":default:throw new Error("Managed Runtime Session operation was not dispatched.")}}async close(){this.closing=true;await Promise.allSettled([...this.sessions.values()].map(async session=>{try{await session.ready;await retire(session)}finally{forgetSession(session.identity.runtimeSessionId)}}))}};function registerManagedRuntimeProviderRoute(app,identity,executor,contextFor){const provider=new ManagedRuntimeProviderWorker(executor,contextFor);executor.attachProvider(provider);app.post(MANAGED_RUNTIME_PROVIDER_ROUTE.path,managedRuntimeNoStore,authorizeManagedRuntime(identity),managedRuntimeJsonBody(MANAGED_RUNTIME_PROVIDER_ROUTE.requestBodyLimitBytes),async(req,res)=>{try{const request=parseManagedRuntimeProviderRequest(req.body);const raw=JSON.parse(JSON.stringify(await provider.control(request.session,request.operation)));const limit=Math.min(MANAGED_RUNTIME_PROVIDER_ROUTE.responseBodyLimitBytes,managedRuntimeProviderLimit(request.operation.kind));const envelopeOverhead=Buffer.byteLength(JSON.stringify({protocolVersion:request.protocolVersion,providerProtocol:request.providerProtocol,session:request.session,result:0}))-1;const result=fitManagedRuntimeProviderResult(request.operation,raw,limit-envelopeOverhead);parseManagedRuntimeProviderResult(request.operation,result,request.session);const json=JSON.stringify({protocolVersion:request.protocolVersion,providerProtocol:request.providerProtocol,session:request.session,result});if(Buffer.byteLength(json)>limit){res.status(413).json({code:"managed_runtime_provider_too_large",error:"Managed Runtime provider response exceeds its body size limit."});return}res.status(200).type("application/json").send(json)}catch(error){if(error instanceof ManagedRuntimeProviderProtocolError){res.status(error.status).json({code:error.code,error:error.message})}else if(error instanceof ManagedToolPreparationError){res.status(400).json({code:"managed_runtime_tool_invalid",error:error.message})}else if(error instanceof ManagedToolProtocolError){res.status(400).json({code:"managed_runtime_provider_invalid",error:error.message})}else{res.status(409).json({code:error instanceof ManagedToolUnavailableError||error instanceof ManagedToolConflictError?error.code:"managed_runtime_provider_operation_failed",error:error instanceof Error?error.message:"Managed Runtime provider operation failed."})}}},handleManagedRuntimeJsonError)}__name(registerManagedRuntimeProviderRoute,"registerManagedRuntimeProviderRoute");init_esbuild_shims();import{createHash as createHash5}from"node:crypto";import{readFileSync as readFileSync3}from"node:fs";import{isAbsolute}from"node:path";import{pathToFileURL}from"node:url";var ManagedHookError=class extends Error{constructor(code){super(code);this.code=code}static{__name(this,"ManagedHookError")}};var ManagedHookImportAbortedError=class extends Error{static{__name(this,"ManagedHookImportAbortedError")}};function importHookModule(modulePath,timeoutMs,signal,entry){return new Promise((resolve,reject)=>{let finished=false;const timer=setTimeout(()=>finish(new ManagedHookError("managed_hook_module_evaluation_timeout")),timeoutMs);const onAbort=__name(()=>finish(new ManagedHookImportAbortedError),"onAbort");function finish(error,module){if(finished)return;finished=true;clearTimeout(timer);signal.removeEventListener("abort",onAbort);if(error)reject(error);else resolve(module)}__name(finish,"finish");if(signal.aborted){onAbort();return}let href;try{href=pathToFileURL(modulePath).href}catch(cause){finish(cause instanceof Error?cause:new Error(String(cause)));return}signal.addEventListener("abort",onAbort,{once:true});entry.moduleEvaluationPending=true;import(href).then(module=>{entry.moduleEvaluationPending=false;settleAbandoned(entry,{state:"settled",result:{success:false,outcome:entry.view.error?.code==="managed_hook_module_evaluation_timeout"?"timeout":"cancelled",duration:0,notStarted:true}});finish(void 0,module)},()=>{entry.moduleEvaluationPending=false;settleAbandoned(entry,{state:"settled",error:{code:"managed_hook_handler_unavailable"}});finish(new ManagedHookError("managed_hook_handler_unavailable"))}).catch(()=>{entry.moduleEvaluationPending=false;settleAbandoned(entry,{state:"settled",error:{code:"managed_hook_handler_unavailable"}});finish(new ManagedHookError("managed_hook_handler_unavailable"))})})}__name(importHookModule,"importHookModule");var FENCED_EVALUATION_CODES=new Set(["managed_hook_module_evaluation_abandoned","managed_hook_module_evaluation_timeout"]);function settleAbandoned(entry,view2){if(!FENCED_EVALUATION_CODES.has(entry.view.error?.code??""))return;entry.view={operationId:entry.view.operationId,...view2}}__name(settleAbandoned,"settleAbandoned");var identifier2=/^[a-zA-Z0-9:_.-]{1,512}$/u;var MAX_OPERATIONS=4096;var MAX_BYTES=60*1024;var FUNCTION_SETTLEMENT_GRACE_MS=1e3;var MODULE_EVALUATION_MIN_TIMEOUT_MS=500;function object2(value){if(!value||typeof value!=="object"||Array.isArray(value))throw new ManagedHookError("managed_hook_invalid");return value}__name(object2,"object");function closed4(value,keys){if(Object.keys(value).some(key=>!keys.includes(key)))throw new ManagedHookError("managed_hook_invalid")}__name(closed4,"closed");function text(value){return typeof value==="string"&&identifier2.test(value)}__name(text,"text");function positive2(value){return Number.isSafeInteger(value)&&Number(value)>0}__name(positive2,"positive");function pin(value){const parsed=object2(value);closed4(parsed,["catalogId","catalogRevision","definitionDigest"]);if(!text(parsed["catalogId"])||!positive2(parsed["catalogRevision"])||typeof parsed["definitionDigest"]!=="string"||!/^[a-f0-9]{64}$/u.test(parsed["definitionDigest"]))throw new ManagedHookError("managed_hook_invalid");return parsed}__name(pin,"pin");function scope2(key){return`${key.tenantId}\0${key.workspaceId}\0${key.sessionId}`}__name(scope2,"scope");function fingerprint2(value){return createHash5("sha256").update(JSON.stringify(value)).digest("hex")}__name(fingerprint2,"fingerprint");function quotaExceeded(operationId){return{operationId,state:"settled",result:{success:false,outcome:"non_blocking_error",duration:0,error:"Managed hook execution quota exceeded before dispatch."}}}__name(quotaExceeded,"quotaExceeded");function parseManagedHookControl(value){const control=object2(value);const key=object2(control["sessionKey"]);closed4(key,["tenantId","workspaceId","sessionId"]);if(!["tenantId","workspaceId","sessionId"].every(field=>text(key[field]))||!text(control["operationId"]))throw new ManagedHookError("managed_hook_invalid");if(control["kind"]==="hook-status"||control["kind"]==="hook-cancel"){closed4(control,["kind","sessionKey","operationId","targetOperationId"]);if(!text(control["targetOperationId"]))throw new ManagedHookError("managed_hook_invalid")}else if(control["kind"]==="hook-catalog"){closed4(control,["kind","sessionKey","operationId","pin"]);pin(control["pin"])}else if(control["kind"]==="hook-execute"){closed4(control,["kind","sessionKey","operationId","pin","hookId","input","grant"]);pin(control["pin"]);const input=object2(control["input"]);if(!text(control["hookId"])||input["session_id"]!==key["sessionId"]||typeof input["cwd"]!=="string"||typeof input["transcript_path"]!=="string"||typeof input["timestamp"]!=="string"||input["messages"]!==void 0&&(!Array.isArray(input["messages"])||input["messages"].some(value2=>!value2||typeof value2!=="object"||Array.isArray(value2)))||!Object.values(HookEventName).includes(input["hook_event_name"]))throw new ManagedHookError("managed_hook_invalid");try{parseOperationGrant(control["grant"])}catch{throw new ManagedHookError("managed_hook_grant_invalid")}}else throw new ManagedHookError("managed_hook_invalid");return structuredClone(control)}__name(parseManagedHookControl,"parseManagedHookControl");function loadManagedHookManifest(path8){if(!path8)return{version:1,catalogs:[]};try{const bytes=readFileSync3(path8);if(bytes.length>1024*1024)throw new Error("too large");return parseManifest2(JSON.parse(bytes.toString("utf8")))}catch{throw new ManagedHookError("managed_hook_manifest_invalid")}}__name(loadManagedHookManifest,"loadManagedHookManifest");function parseManifest2(value){const manifest=object2(value);closed4(manifest,["version","catalogs"]);if(manifest["version"]!==1||!Array.isArray(manifest["catalogs"]))throw new ManagedHookError("managed_hook_manifest_invalid");const pins=new Set;for(const raw of manifest["catalogs"]){const catalog=object2(raw);closed4(catalog,["tenantId","workspaceId","catalogId","catalogRevision","definitionDigest","hooks"]);pin({catalogId:catalog["catalogId"],catalogRevision:catalog["catalogRevision"],definitionDigest:catalog["definitionDigest"]});if(!text(catalog["tenantId"])||!text(catalog["workspaceId"])||!Array.isArray(catalog["hooks"])||catalog["hooks"].length>128)throw new ManagedHookError("managed_hook_manifest_invalid");const identity=JSON.stringify([catalog["tenantId"],catalog["workspaceId"],catalog["catalogId"],catalog["catalogRevision"]]);if(pins.has(identity))throw new ManagedHookError("managed_hook_definition_conflict");pins.add(identity);const ids=new Set;for(const rawHook of catalog["hooks"]){const hook=object2(rawHook);closed4(hook,["hookId","eventName","matcher","sequential","onceKey","failClosed","async","config","handler","source","sourceTrusted","enabled","agentScope","owner"]);const config=object2(hook["config"]);if(hook["source"]!==void 0&&!Object.values(HooksConfigSource).includes(hook["source"])||["sourceTrusted","enabled"].some(key=>hook[key]!==void 0&&typeof hook[key]!=="boolean")||hook["agentScope"]!==void 0&&!text(hook["agentScope"]))throw new ManagedHookError("managed_hook_manifest_invalid");if(hook["owner"]!==void 0){const owner=object2(hook["owner"]);closed4(owner,["sessionId","agentId"]);if(!text(owner["sessionId"])||!(owner["agentId"]===null||text(owner["agentId"])))throw new ManagedHookError("managed_hook_manifest_invalid")}if(hook["source"]==="session"&&hook["owner"]===void 0||hook["agentScope"]!==void 0&&(hook["source"]!=="session"||object2(hook["owner"])["agentId"]===null))throw new ManagedHookError("managed_hook_manifest_invalid");if(!text(hook["hookId"])||ids.has(hook["hookId"])||!Object.values(HookEventName).includes(hook["eventName"])||!["sequential","failClosed","async"].every(key=>typeof hook[key]==="boolean")||!(hook["onceKey"]===null||text(hook["onceKey"]))||hook["matcher"]!==void 0&&typeof hook["matcher"]!=="string"||config["name"]!==void 0&&typeof config["name"]!=="string"||config["timeout"]!==void 0&&(!positive2(config["timeout"])||Number(config["timeout"])>6e5))throw new ManagedHookError("managed_hook_manifest_invalid");ids.add(hook["hookId"]);if(config["type"]==="command"){closed4(config,["type","name","command","timeout","env","shell"]);if(typeof config["command"]!=="string"||!config["command"]||config["command"].includes("\0")||config["shell"]!==void 0&&!["bash","powershell"].includes(String(config["shell"])))throw new ManagedHookError("managed_hook_manifest_invalid")}else if(config["type"]==="http"){closed4(config,["type","name","url","headers","allowedEnvVars","timeout"]);const url=new URL(String(config["url"]));if(!["http:","https:"].includes(url.protocol)||url.username||url.password||config["allowedEnvVars"]!==void 0&&(!Array.isArray(config["allowedEnvVars"])||!config["allowedEnvVars"].every(item=>typeof item==="string")))throw new ManagedHookError("managed_hook_manifest_invalid")}else if(config["type"]==="prompt"){closed4(config,["type","name","prompt","model","timeout"]);if(typeof config["prompt"]!=="string"||!config["prompt"]||config["model"]!==void 0&&typeof config["model"]!=="string")throw new ManagedHookError("managed_hook_manifest_invalid")}else if(config["type"]==="function"){closed4(config,["type","name","timeout"]);const handler=object2(hook["handler"]);closed4(handler,["handlerId","handlerRevision","modulePath","exportName"]);if(!text(handler["handlerId"])||!positive2(handler["handlerRevision"])||typeof handler["modulePath"]!=="string"||!isAbsolute(handler["modulePath"])||!text(handler["exportName"])||!positive2(config["timeout"]))throw new ManagedHookError("managed_hook_manifest_invalid")}else throw new ManagedHookError("managed_hook_manifest_invalid");if(config["type"]!=="function"&&hook["handler"]!==void 0)throw new ManagedHookError("managed_hook_manifest_invalid");if(hook["async"]&&config["type"]!=="command")throw new ManagedHookError("managed_hook_manifest_invalid");for(const field of["env","headers"]){if(config[field]!==void 0&&Object.entries(object2(config[field])).some(([key,value2])=>key.includes("\0")||typeof value2!=="string"||value2.includes("\0")))throw new ManagedHookError("managed_hook_manifest_invalid")}}}return structuredClone(manifest)}__name(parseManifest2,"parseManifest");var ManagedHookRuntime=class{constructor(workspace,sessionDirectory,manifest){this.workspace=workspace;this.sessionDirectory=sessionDirectory;this.manifest=parseManifest2(manifest)}static{__name(this,"ManagedHookRuntime")}manifest;operations=new Map;gates=new ManagedOperationGrantGate;shutdown=createAbortController();closing=false;admissionSealed=false;lifecycleStarted=false;pendingStarts=0;sealAdmission(){this.admissionSealed=true}getDrainInspection(){return{hasActivity:this.lifecycleStarted,pendingStarts:this.pendingStarts,pendingInvocations:[...this.operations.values()].filter(entry=>entry.view.state!=="settled").length}}requireAdmission(){if(this.closing||this.admissionSealed)throw new ManagedHookError("managed_hook_closed")}async control(runtimeSessionId,value){this.pendingStarts++;try{return await this.controlAdmitted(runtimeSessionId,value)}finally{this.pendingStarts--}}async controlAdmitted(runtimeSessionId,value){const control=parseManagedHookControl(value);if(control.sessionKey.tenantId!==this.workspace.tenantId||control.sessionKey.workspaceId!==this.workspace.workspaceId)throw new ManagedHookError("managed_hook_scope_conflict");if(control.kind==="hook-status"||control.kind==="hook-cancel"){const existing2=this.operations.get(`${scope2(control.sessionKey)}\0${control.targetOperationId}`);if(!existing2||existing2.runtimeSessionId!==runtimeSessionId)return{operationId:control.targetOperationId,state:"outcome_unknown"};if(control.kind==="hook-cancel")existing2.controller.abort();return structuredClone(existing2.view)}const{pin:expected}=control;const catalog=this.manifest.catalogs.find(entry2=>entry2.tenantId===control.sessionKey.tenantId&&entry2.workspaceId===control.sessionKey.workspaceId&&entry2.catalogId===expected.catalogId&&entry2.catalogRevision===expected.catalogRevision&&entry2.definitionDigest===expected.definitionDigest);if(!catalog)throw new ManagedHookError("managed_hook_catalog_unavailable");const key=`${scope2(control.sessionKey)}\0${control.operationId}`;const{grant:_grant,...effect}=control.kind==="hook-execute"?control:{...control,grant:void 0};const digest2=fingerprint2(effect);const existing=this.operations.get(key);if(existing){if(existing.runtimeSessionId!==runtimeSessionId||existing.fingerprint!==digest2)throw new ManagedHookError("managed_hook_operation_conflict");return structuredClone(existing.view)}this.requireAdmission();this.lifecycleStarted=true;const directory=await this.sessionDirectory(runtimeSessionId);this.requireAdmission();if(!directory)throw new ManagedHookError("managed_hook_session_unavailable");if(control.kind==="hook-catalog"){const exposed={...expected,hooks:await this.descriptors(catalog.hooks)};this.requireAdmission();if(Buffer.byteLength(JSON.stringify(exposed))>MAX_BYTES)throw new ManagedHookError("managed_hook_catalog_limit");return{operationId:control.operationId,state:"settled",catalog:exposed}}const definition=catalog.hooks.find(entry2=>entry2.hookId===control.hookId);if(!definition||definition.eventName!==control.input.hook_event_name||definition.sourceTrusted===false||definition.enabled===false||definition.owner&&(definition.owner.sessionId!==control.sessionKey.sessionId||definition.agentScope!==void 0&&definition.owner.agentId!==(control.input.agent_id??null)))throw new ManagedHookError("managed_hook_definition_unavailable");if(definition.config.type==="prompt")throw new ManagedHookError("managed_hook_requires_harness");const grant=control.grant;if(scope2(grant.sessionKey)!==scope2(control.sessionKey)||grant.domain!=="hook_execution"||grant.operationId!==control.operationId||grant.workspaceGeneration!==this.workspace.workspaceGeneration)throw new ManagedHookError("managed_hook_grant_invalid");if(this.operations.has(key))return this.control(runtimeSessionId,control);this.requireAdmission();if(this.operations.size>=MAX_OPERATIONS)return{operationId:control.operationId,state:"settled",result:{success:false,outcome:"blocking",duration:0,output:{continue:false,decision:"block",reason:"Managed Hook receipt capacity is exhausted.",...definition.eventName==="PermissionRequest"?{hookSpecificOutput:{decision:{behavior:"deny",interrupt:true,message:"Managed Hook receipt capacity is exhausted."}}}:{}}}};try{this.gates.install(grant)}catch{throw new ManagedHookError("managed_hook_grant_invalid")}if(!this.gates.admits(control.sessionKey,control.operationId,"execute",Date.now()))throw new ManagedHookError("managed_hook_grant_invalid");const atRunningLimit=[...this.operations.values()].filter(entry2=>entry2.view.state!=="settled").length>=MANAGED_HOOK_MAX_RUNNING;const entry={runtimeSessionId,fingerprint:digest2,sessionKey:control.sessionKey,controller:new AbortController,view:atRunningLimit?quotaExceeded(control.operationId):{operationId:control.operationId,state:"running"}};this.operations.set(key,entry);if(!atRunningLimit)entry.done=this.execute(entry,definition,control,directory);return structuredClone(entry.view)}async descriptors(definitions){const native=new Map;const sources=new Map;const agentHooks=[];const sessionHooks=[];for(const definition of definitions){if(definition.enabled===false||definition.sourceTrusted===false)continue;const config=definition.config.type==="function"?{...definition.config,type:"function",id:definition.handler.handlerId,callback:__name(async()=>void 0,"callback"),errorMessage:"Managed hook handler failed."}:{...definition.config};native.set(config,definition);const source=definition.source??"system";if(source==="session"){(definition.agentScope?agentHooks:sessionHooks).push({definition,config});continue}const grouped=sources.get(source)??{};(grouped[definition.eventName]??=[]).push({matcher:definition.matcher,sequential:definition.sequential,hooks:[config]});sources.set(source,grouped)}const registry=new HookRegistry({getProjectRoot:__name(()=>"","getProjectRoot"),isTrustedFolder:__name(()=>true,"isTrustedFolder"),getSystemHooks:__name(()=>sources.get("system"),"getSystemHooks"),getUserHooks:__name(()=>sources.get("user"),"getUserHooks"),getProjectHooks:__name(()=>sources.get("project"),"getProjectHooks"),getExtensions:__name(()=>[{isActive:true,hooks:sources.get("extensions")}],"getExtensions")});await registry.initialize();for(const{definition,config}of agentHooks){registry.addAgentHooks({[definition.eventName]:[{matcher:definition.matcher,sequential:definition.sequential,hooks:[config]}]},definition.agentScope,{owner:{sessionId:definition.owner.sessionId,agentId:definition.owner.agentId}})}const expose=__name((definition,config,deduplicate)=>{const{handler,config:_recipe,...descriptor}=definition;return{...descriptor,source:definition.source??"system",...deduplicate?{plannerKey:fingerprint2(getHookKey(config))}:{},config:config.type==="prompt"?definition.config:{type:config.type,...config.name?{name:config.name}:{}},...handler?{handler:{handlerId:handler.handlerId,handlerRevision:handler.handlerRevision}}:{}}},"expose");return[...Object.values(HookEventName).flatMap(event=>registry.getHooksForEvent(event).map(entry=>expose(native.get(entry.config),entry.config,true))),...sessionHooks.map(({definition,config})=>expose(definition,config,false))]}hasHolds(runtimeSessionId){return[...this.operations.values()].some(entry=>entry.runtimeSessionId===runtimeSessionId&&(entry.view.state!=="settled"||entry.moduleEvaluationPending===true))}async close(){this.closing=true;this.shutdown.abort();for(const entry of this.operations.values())entry.controller.abort();await Promise.all([...this.operations.values()].map(entry=>entry.done))}async execute(entry,definition,control,directory){let dispatched=false;let functionCompletion;try{let config;if(definition.config.type==="function"){const handler=definition.handler;let registered;try{const module=await importHookModule(handler.modulePath,Math.max(definition.config.timeout,MODULE_EVALUATION_MIN_TIMEOUT_MS),entry.controller.signal,entry);registered=object2(module[handler.exportName]);if(registered["handlerRevision"]!==handler.handlerRevision||typeof registered["callback"]!=="function"||registered["onHookSuccess"]!==void 0&&typeof registered["onHookSuccess"]!=="function")throw new Error("handler revision unavailable")}catch(error){if(error instanceof ManagedHookImportAbortedError){if(entry.moduleEvaluationPending)throw new ManagedHookError("managed_hook_module_evaluation_abandoned");entry.view={operationId:control.operationId,state:"settled",result:{success:false,outcome:"cancelled",duration:0,notStarted:true}};return}if(error instanceof ManagedHookError&&error.code==="managed_hook_module_evaluation_timeout")throw error;throw new ManagedHookError("managed_hook_handler_unavailable")}const callback=registered["callback"];config={...definition.config,type:"function",id:handler.handlerId,callback:__name((input,context)=>{const pending=Promise.resolve().then(()=>{this.requireAdmission();return callback(input,context)});functionCompletion=pending.then(()=>true,()=>true);return pending},"callback"),errorMessage:"Managed hook handler failed.",...registered["onHookSuccess"]?{onHookSuccess:registered["onHookSuccess"]}:{}}}else if(definition.config.type==="command"){config={...definition.config,async:false}}else{config=definition.config}const currentDirectory=await this.sessionDirectory(entry.runtimeSessionId);this.requireAdmission();if(!this.gates.admits(control.sessionKey,control.operationId,"execute",Date.now())||currentDirectory!==directory)throw new ManagedHookError("managed_hook_grant_invalid");if(entry.controller.signal.aborted){entry.view={operationId:control.operationId,state:"settled",result:{success:false,outcome:"cancelled",duration:0,notStarted:true}};return}const runner=new HookRunner(config.type==="http"?[interpolateUrl(config.url,config.allowedEnvVars??[])]:void 0);dispatched=true;const result=await runner.executeHook(config,definition.eventName,{...control.input,cwd:directory,session_id:control.sessionKey.sessionId},{signal:entry.controller.signal,...Array.isArray(control.input["messages"])?{messages:control.input.messages}:{},..."tool_use_id"in control.input&&typeof control.input.tool_use_id==="string"?{toolUseID:control.input.tool_use_id}:{}},config.type==="command"?{waitForProcessTree:true,cgroupRoot:process.env["QWEN_MANAGED_HOOK_CGROUP_ROOT"],environment:{PATH:process.env["PATH"]??"",HOME:directory,USERPROFILE:directory,...process.env["SystemRoot"]?{SYSTEMROOT:process.env["SystemRoot"]}:{}}}:config.type==="http"?{trackHttpRequest:true,httpRequestSignal:this.shutdown.signal}:void 0);if(result.error instanceof HookCommandIsolationUnavailableError){entry.view={operationId:control.operationId,state:"settled",error:{code:"managed_hook_command_isolation_unavailable"}};return}let functionSettled=true;if(config.type==="function"&&(result.outcome==="timeout"||result.outcome==="cancelled")&&functionCompletion){let timer;functionSettled=await Promise.race([functionCompletion,new Promise(resolve=>{timer=setTimeout(()=>resolve(false),FUNCTION_SETTLEMENT_GRACE_MS)})]);clearTimeout(timer)}const uncertain=config.type==="command"&&result.processTreeDrained!==true||config.type==="function"&&!functionSettled||config.type==="http"&&(!result.httpRequestState||result.httpRequestState==="outcome_unknown");if(uncertain){entry.view={operationId:control.operationId,state:"outcome_unknown",error:{code:"managed_hook_outcome_unknown"}};return}this.settle(entry,result)}catch(error){if(!dispatched&&error instanceof ManagedHookError&&error.code==="managed_hook_grant_invalid"){entry.view={operationId:control.operationId,state:"settled",result:{success:false,outcome:"non_blocking_error",duration:0,error:"Managed hook authorization expired before dispatch."}};return}if(!dispatched&&!(error instanceof ManagedHookError)){entry.view={operationId:control.operationId,state:"settled",result:{success:false,outcome:"non_blocking_error",duration:0,error:"Managed hook failed before dispatch."}};return}entry.view={operationId:control.operationId,state:dispatched?"outcome_unknown":"settled",error:{code:error instanceof ManagedHookError?error.code:"managed_hook_execution_failed"}}}}settle(entry,result){const view2={operationId:entry.view.operationId,state:"settled",result:{success:result.success,outcome:result.outcome??(result.success?"success":"non_blocking_error"),duration:result.duration,...result.output?{output:result.output}:{},...result.stdout?{stdout:result.stdout}:{},...result.stderr?{stderr:result.stderr}:{},...result.error?{error:"Managed hook execution failed."}:{}}};entry.view=Buffer.byteLength(JSON.stringify(view2))<=MAX_BYTES?view2:{operationId:entry.view.operationId,state:"settled",result:{success:false,outcome:"non_blocking_error",duration:result.duration,error:"Managed hook output exceeds the size limit."}}}};init_esbuild_shims();var MANAGED_HOOK_WORKER_ROUTE=Object.freeze({key:"hook",method:"POST",path:MANAGED_HOOK_ROUTE,protocolVersion:1,requestBodyLimitBytes:MANAGED_HOOK_MAX_REQUEST_BYTES,responseBodyLimitBytes:1024*1024,cacheControl:"no-store"});function registerManagedHookRoutes(app,identity,runtime){app.post(MANAGED_HOOK_ROUTE,managedRuntimeNoStore,authorizeManagedRuntime(identity),managedRuntimeJsonBody(MANAGED_HOOK_WORKER_ROUTE.requestBodyLimitBytes),async(req,res)=>{const body2=req.body;if(!body2||typeof body2!=="object"||Array.isArray(body2)){res.status(400).json({code:"managed_hook_invalid"});return}const request=body2;if(Object.keys(request).sort().join(",")!=="operation,protocolVersion,runtimeSessionId"||request["protocolVersion"]!==1||typeof request["runtimeSessionId"]!=="string"||!request["runtimeSessionId"]){res.status(400).json({code:"managed_hook_invalid"});return}try{const operation=await runtime.control(request["runtimeSessionId"],request["operation"]);res.json({protocolVersion:1,runtimeSessionId:request["runtimeSessionId"],operation})}catch(error){const code=error instanceof ManagedHookError?error.code:"managed_hook_unavailable";res.status(code==="managed_hook_invalid"?400:409).json({code})}},handleManagedRuntimeJsonError)}__name(registerManagedHookRoutes,"registerManagedHookRoutes");init_esbuild_shims();var MANAGED_MCP_WORKER_ROUTE=Object.freeze({key:"mcp",method:"POST",path:MANAGED_MCP_ROUTE,protocolVersion:1,requestBodyLimitBytes:256*1024,responseBodyLimitBytes:1024*1024,cacheControl:"no-store"});function registerManagedMcpRoutes(app,identity,runtime){app.post(MANAGED_MCP_ROUTE,managedRuntimeNoStore,authorizeManagedRuntime(identity),managedRuntimeJsonBody(MANAGED_MCP_WORKER_ROUTE.requestBodyLimitBytes),async(req,res)=>{const body2=req.body;if(!body2||typeof body2!=="object"||Array.isArray(body2)){res.status(400).json({code:"managed_mcp_invalid"});return}const request=body2;if(Object.keys(request).sort().join(",")!=="operation,protocolVersion,runtimeSessionId"||request["protocolVersion"]!==1||typeof request["runtimeSessionId"]!=="string"||!request["runtimeSessionId"]){res.status(400).json({code:"managed_mcp_invalid"});return}try{const operation=await runtime.control(request["runtimeSessionId"],request["operation"]);res.json({protocolVersion:1,runtimeSessionId:request["runtimeSessionId"],operation})}catch(error){const code=error instanceof ManagedMcpError?error.code:"managed_mcp_unavailable";res.status(code==="managed_mcp_invalid"?400:409).json({code})}},handleManagedRuntimeJsonError)}__name(registerManagedMcpRoutes,"registerManagedMcpRoutes");init_esbuild_shims();init_esbuild_shims();var MANAGED_SHELL_ROUTE="/internal/managed-runtime/v3/shells";function shellUnitNameOf(targetOperationId){return`qwen-bg-${targetOperationId.replace(/[^a-zA-Z0-9._-]/g,"-")}`}__name(shellUnitNameOf,"shellUnitNameOf");var ManagedShellError=class extends Error{constructor(code,message){super(message);this.code=code;this.name="ManagedShellError"}static{__name(this,"ManagedShellError")}};var KEYS=["kind","operationId","sessionKey","targetOperationId"];function parseOperation(value){if(!value||typeof value!=="object"||Array.isArray(value)){throw new ManagedShellError("managed_shell_invalid","Shell operation is invalid.")}const object5=value;if(Object.keys(object5).sort().join(",")!==[...KEYS].sort().join(",")){throw new ManagedShellError("managed_shell_invalid","Shell operation is invalid.")}const kind=object5["kind"];if(kind!=="shell-status"&&kind!=="shell-terminate"){throw new ManagedShellError("managed_shell_invalid","Shell operation is invalid.")}const sessionKey=object5["sessionKey"];if(!sessionKey||typeof sessionKey!=="object"||typeof sessionKey["tenantId"]!=="string"||typeof sessionKey["sessionId"]!=="string"){throw new ManagedShellError("managed_shell_invalid","Shell operation scope is invalid.")}for(const key of["operationId","targetOperationId"]){const field=object5[key];if(typeof field!=="string"||!field||field.length>512){throw new ManagedShellError("managed_shell_invalid",`Shell operation ${key} is invalid.`)}}return{kind,operationId:object5["operationId"],targetOperationId:object5["targetOperationId"]}}__name(parseOperation,"parseOperation");var ManagedShellRuntime=class{constructor(registry){this.registry=registry}static{__name(this,"ManagedShellRuntime")}async control(runtimeSessionId,value){const operation=parseOperation(value);const unitName=shellUnitNameOf(operation.targetOperationId);const registered=this.registry.describe(unitName);if(registered&®istered.sessionId===runtimeSessionId){if(operation.kind==="shell-status"){return{operationId:operation.targetOperationId,state:"running",unitName}}const receipt2=await this.registry.terminate(unitName,5e3);if(!receipt2||receipt2.evidence===null){return{operationId:operation.targetOperationId,state:"unknown"}}return{operationId:operation.targetOperationId,state:"exited",unitName,evidence:receipt2.evidence}}const finished=this.registry.describeFinished(unitName);if(finished&&finished.sessionId===runtimeSessionId&&finished.receipt.evidence!==null){return{operationId:operation.targetOperationId,state:"exited",unitName,evidence:finished.receipt.evidence}}return{operationId:operation.targetOperationId,state:"unknown"}}};init_esbuild_shims();var MANAGED_SHELL_WORKER_ROUTE=Object.freeze({key:"shell",method:"POST",path:MANAGED_SHELL_ROUTE,protocolVersion:1,requestBodyLimitBytes:16*1024,responseBodyLimitBytes:64*1024,cacheControl:"no-store"});function registerManagedShellRoutes(app,identity,runtime){app.post(MANAGED_SHELL_ROUTE,managedRuntimeNoStore,authorizeManagedRuntime(identity),managedRuntimeJsonBody(MANAGED_SHELL_WORKER_ROUTE.requestBodyLimitBytes),async(req,res)=>{const body2=req.body;if(!body2||typeof body2!=="object"||Array.isArray(body2)){res.status(400).json({code:"managed_shell_invalid"});return}const request=body2;if(Object.keys(request).sort().join(",")!=="operation,protocolVersion,runtimeSessionId"||request["protocolVersion"]!==1||typeof request["runtimeSessionId"]!=="string"||!request["runtimeSessionId"]){res.status(400).json({code:"managed_shell_invalid"});return}try{const operation=await runtime.control(request["runtimeSessionId"],request["operation"]);res.json({protocolVersion:1,runtimeSessionId:request["runtimeSessionId"],operation})}catch(error){const code=error instanceof ManagedShellError?error.code:"managed_shell_unavailable";res.status(code==="managed_shell_invalid"?400:409).json({code})}},handleManagedRuntimeJsonError)}__name(registerManagedShellRoutes,"registerManagedShellRoutes");init_esbuild_shims();init_esbuild_shims();var MANAGED_MONITOR_ROUTE="/internal/managed-runtime/v3/monitors";function monitorUnitNameOf(targetOperationId){return`qwen-mon-${targetOperationId.replace(/[^a-zA-Z0-9._-]/g,"-")}`}__name(monitorUnitNameOf,"monitorUnitNameOf");var ManagedMonitorError=class extends Error{constructor(code,message){super(message);this.code=code;this.name="ManagedMonitorError"}static{__name(this,"ManagedMonitorError")}};var KEYS2=["kind","operationId","sessionKey","targetOperationId"];function parseOperation2(value){if(!value||typeof value!=="object"||Array.isArray(value)){throw new ManagedMonitorError("managed_monitor_invalid","Monitor operation is invalid.")}const object5=value;if(Object.keys(object5).sort().join(",")!==[...KEYS2].sort().join(",")){throw new ManagedMonitorError("managed_monitor_invalid","Monitor operation is invalid.")}const kind=object5["kind"];if(kind!=="monitor-status"&&kind!=="monitor-stop"){throw new ManagedMonitorError("managed_monitor_invalid","Monitor operation is invalid.")}const sessionKey=object5["sessionKey"];if(!sessionKey||typeof sessionKey!=="object"||typeof sessionKey["tenantId"]!=="string"||typeof sessionKey["sessionId"]!=="string"){throw new ManagedMonitorError("managed_monitor_invalid","Monitor operation scope is invalid.")}for(const key of["operationId","targetOperationId"]){const field=object5[key];if(typeof field!=="string"||!field||field.length>512){throw new ManagedMonitorError("managed_monitor_invalid",`Monitor operation ${key} is invalid.`)}}return{kind,operationId:object5["operationId"],targetOperationId:object5["targetOperationId"]}}__name(parseOperation2,"parseOperation");var ManagedMonitorRuntime=class{constructor(registry){this.registry=registry}static{__name(this,"ManagedMonitorRuntime")}async control(runtimeSessionId,value){const operation=parseOperation2(value);const unitName=monitorUnitNameOf(operation.targetOperationId);const registered=this.registry.describe(unitName);if(registered&®istered.sessionId===runtimeSessionId){if(operation.kind==="monitor-status"){return{operationId:operation.targetOperationId,state:"running",unitName}}const receipt2=await this.registry.terminate(unitName,5e3);if(!receipt2||receipt2.evidence===null){return{operationId:operation.targetOperationId,state:"unknown"}}return{operationId:operation.targetOperationId,state:"exited",unitName,evidence:receipt2.evidence}}const finished=this.registry.describeFinished(unitName);if(finished&&finished.sessionId===runtimeSessionId&&finished.receipt.evidence!==null){return{operationId:operation.targetOperationId,state:"exited",unitName,evidence:finished.receipt.evidence}}return{operationId:operation.targetOperationId,state:"unknown"}}};init_esbuild_shims();var MANAGED_MONITOR_WORKER_ROUTE=Object.freeze({key:"monitor",method:"POST",path:MANAGED_MONITOR_ROUTE,protocolVersion:1,requestBodyLimitBytes:16*1024,responseBodyLimitBytes:64*1024,cacheControl:"no-store"});function registerManagedMonitorRoutes(app,identity,runtime){app.post(MANAGED_MONITOR_ROUTE,managedRuntimeNoStore,authorizeManagedRuntime(identity),managedRuntimeJsonBody(MANAGED_MONITOR_WORKER_ROUTE.requestBodyLimitBytes),async(req,res)=>{const body2=req.body;if(!body2||typeof body2!=="object"||Array.isArray(body2)){res.status(400).json({code:"managed_monitor_invalid"});return}const request=body2;if(Object.keys(request).sort().join(",")!=="operation,protocolVersion,runtimeSessionId"||request["protocolVersion"]!==1||typeof request["runtimeSessionId"]!=="string"||!request["runtimeSessionId"]){res.status(400).json({code:"managed_monitor_invalid"});return}try{const operation=await runtime.control(request["runtimeSessionId"],request["operation"]);res.json({protocolVersion:1,runtimeSessionId:request["runtimeSessionId"],operation})}catch(error){const code=error instanceof ManagedMonitorError?error.code:"managed_monitor_unavailable";res.status(code==="managed_monitor_invalid"?400:409).json({code})}},handleManagedRuntimeJsonError)}__name(registerManagedMonitorRoutes,"registerManagedMonitorRoutes");var MANAGED_CONTEXT_WORKER_ROUTES=Object.freeze([...MANAGED_CONTEXT_ROUTES,WORKSPACE_ACTIVATION_ROUTE,MANAGED_MCP_WORKER_ROUTE,MANAGED_HOOK_WORKER_ROUTE,MANAGED_SHELL_WORKER_ROUTE,MANAGED_MONITOR_WORKER_ROUTE,MANAGED_RUNTIME_PROVIDER_ROUTE,...OWNED_MANAGED_RUNTIME_ROUTES.filter(route=>route.key!=="attest")]);var REFUSAL_MESSAGES=Object.freeze({managed_runtime_attestation_invalid:"Managed Runtime attestation request is invalid.",managed_runtime_identity_conflict:"Managed Runtime immutable identity conflicts.",managed_context_conflict:"Managed context conflicts with an earlier installation.",managed_context_unavailable:"Managed context directory is unavailable."});var ManagedContextMount=class{static{__name(this,"ManagedContextMount")}#mountRoot;#root;constructor(mountRoot){this.#mountRoot=mountRoot}get isAvailable(){return true}async resolve(cwdRelative){if(!isHostAbsolute(this.#mountRoot)){return void 0}let rootStats;let directory;try{const root=await fs3.realpath(this.#mountRoot);rootStats=await fs3.stat(root,{bigint:true});directory=path4.join(root,...cwdRelative.split("/"));if(await fs3.realpath(directory)!==directory||!(await fs3.stat(directory)).isDirectory()){return void 0}await fs3.access(directory,constants2.R_OK|constants2.X_OK)}catch{return void 0}const pinned=this.#root;if(pinned===void 0){this.#root={dev:rootStats.dev,ino:rootStats.ino}}else if(pinned.dev!==rootStats.dev||pinned.ino!==rootStats.ino){return void 0}return directory}async rootDirectory(){if(!isHostAbsolute(this.#mountRoot)){return void 0}try{const root=await fs3.realpath(this.#mountRoot);const stats=await fs3.stat(root,{bigint:true});const pinned=this.#root;if(pinned!==void 0&&(pinned.dev!==stats.dev||pinned.ino!==stats.ino)){return void 0}return root}catch{return void 0}}};async function siblingDirectory(mount,cwdRelative){const resolved=await mount.resolve(cwdRelative);if(resolved!==void 0)return resolved;const root=await mount.rootDirectory();if(root===void 0)return void 0;const occupied=path4.join(root,...cwdRelative.split("/"));try{return await realpathDeepestExisting(occupied)}catch{return occupied}}__name(siblingDirectory,"siblingDirectory");function isHostAbsolute(mountRoot){return process.platform==="win32"?/^(?:[A-Za-z]:[\\/]|\\\\)/.test(mountRoot):mountRoot.startsWith("/")}__name(isHostAbsolute,"isHostAbsolute");function selectShellCapturePublisher(remotePublishers,remotePublisher){return{get hasInstalledPublication(){return remotePublishers.hasInstalledPublication||remotePublisher.hasInstalledPublication},async prepare(request){if(request.capture.background===true){if(!remotePublishers.hasSession(request.reference.sessionId))throw new Error("Background captures require their Session publisher.");return{...await remotePublishers.prepare(request),publisher:remotePublishers}}if(remotePublisher.hasExecution(request.capture.executionCallId)){return{...await remotePublisher.prepare(request),publisher:remotePublisher}}const selected=remotePublishers.hasSession(request.reference.sessionId)?remotePublishers:remotePublisher;return{...await selected.prepare(request),publisher:selected}}}}__name(selectShellCapturePublisher,"selectShellCapturePublisher");function registerManagedContextRoutes(app,bootDocument,capturePublisher,remotePublishers,mount=new ManagedContextMount(bootDocument.mountRoot)){const boot=parseManagedContextBoot(bootDocument);if(boot.capabilityDigest===CSI_FILES_RETIREMENT_CAPABILITY_DIGEST)throw new Error("Private CSI file profile requires its dedicated worker.");const installations=new ManagedContextInstallations(boot);const activations=new WorkspaceActivations;const requiresActivation=boot.capabilityDigest===WORKSPACE_CAPABILITY_DIGEST;const admissionOpen=__name(()=>executor.isAdmissionOpen,"admissionOpen");const remotePublisher=!capturePublisher&&requiresActivation?new RemoteShellResultPublisher:void 0;const publisher=capturePublisher??(remotePublishers&&remotePublisher?selectShellCapturePublisher(remotePublishers,remotePublisher):remotePublishers??remotePublisher);remotePublisher?.registerInstallRoute(app,boot,admissionOpen);const[attestRoute,contextRoute]=MANAGED_CONTEXT_ROUTES;app.post(attestRoute.path,managedRuntimeNoStore,authorizeManagedRuntime(boot),managedRuntimeJsonBody(attestRoute.requestBodyLimitBytes),(req,res)=>{send(res,checkManagedContextAttestation(req.body,boot))},handleManagedRuntimeJsonError);app.post(contextRoute.path,managedRuntimeNoStore,authorizeManagedRuntime(boot),managedRuntimeJsonBody(contextRoute.requestBodyLimitBytes),async(req,res)=>{send(res,await installations.install(req.body,async binding=>await mount.resolve(binding.cwdRelative)!==void 0,admissionOpen))},handleManagedRuntimeJsonError);const mcp=new ManagedMcpRuntime(boot,async runtimeSessionId=>{if(!admissionOpen()||!mount.isAvailable||!requiresActivation||!activations.isActive(runtimeSessionId))return void 0;const binding=installations.installed(runtimeSessionId);const directory=binding&&await mount.resolve(binding.cwdRelative);return admissionOpen()&&mount.isAvailable&&activations.isActive(runtimeSessionId)?directory:void 0},loadManagedMcpManifest(process.env["QWEN_MANAGED_MCP_CONFIG"]));registerManagedMcpRoutes(app,boot,mcp);const hooks=new ManagedHookRuntime(boot,async runtimeSessionId=>{if(!admissionOpen()||!mount.isAvailable||!requiresActivation||!activations.isActive(runtimeSessionId))return void 0;const binding=installations.installed(runtimeSessionId);const directory=binding&&await mount.resolve(binding.cwdRelative);return admissionOpen()&&mount.isAvailable&&activations.isActive(runtimeSessionId)?directory:void 0},loadManagedHookManifest(process.env["QWEN_MANAGED_HOOK_CONFIG"]));registerManagedHookRoutes(app,boot,hooks);const cgroupRoot=process.env["QWEN_MANAGED_HOOK_CGROUP_ROOT"];const backgroundSupervisor=cgroupRoot?ManagedChildRunSupervisor.create({cgroupRoot}):void 0;const backgroundRegistry=new ManagedBackgroundShellRegistry;const monitorRegistry=new ManagedMonitorRegistry;const executor=new ManagedToolExecutor(async reference2=>{const isActive=__name(()=>admissionOpen()&&mount.isAvailable&&(!requiresActivation||activations.isActive(reference2.sessionId)),"isActive");if(!isActive()){return void 0}const binding=installations.installed(reference2.sessionId);const directory=binding&&await mount.resolve(binding.cwdRelative);if(directory===void 0){return void 0}const sessionId=runtimeSessionKey(boot.runtimeInstanceId,reference2.sessionId);return{...sessionIdContext.run(sessionId,()=>createManagedToolSet(directory,sessionId,requiresActivation?boot.mountRoot:directory)),isActive}},publisher,mcp,hooks,async(sessionId,realPath,ownDirectory)=>{const contains=__name((directory,target)=>{const relative=path4.relative(directory,target);return relative!==".."&&!relative.startsWith(`..${path4.sep}`)&&!path4.isAbsolute(relative)},"contains");const root=await mount.rootDirectory();const ownEstate=contains(ownDirectory,realPath)&&root!==void 0&&ownDirectory!==root;for(const[otherId,binding]of installations.bindings()){if(otherId===sessionId)continue;const directory=await siblingDirectory(mount,binding.cwdRelative);if(directory===void 0){if(ownEstate&&await mount.rootDirectory()===root)continue;return true}if(root!==void 0&&directory===root)continue;if(!contains(directory,realPath))continue;if(!ownEstate||directory!==ownDirectory&&contains(ownDirectory,directory)){return true}}return false},backgroundSupervisor,backgroundRegistry,monitorRegistry);registerManagedShellRoutes(app,boot,new ManagedShellRuntime(backgroundRegistry));registerManagedMonitorRoutes(app,boot,new ManagedMonitorRuntime(monitorRegistry));registerManagedRuntimeProviderRoute(app,boot,executor,async sessionId=>{const binding=installations.installed(sessionId);if(!requiresActivation||binding!==void 0&&binding.contextConfigRef!==WORKSPACE_CONTEXT_CONFIG_REF){throw new ManagedRuntimeProviderProtocolError("Managed Runtime provider configuration is unsupported.",501,"managed_runtime_provider_unsupported")}const isActive=__name(()=>!executor.isAdmissionSealed&&mount.isAvailable&&activations.isActive(sessionId),"isActive");if(!isActive())return void 0;const directory=binding&&await mount.resolve(binding.cwdRelative);return directory===void 0?void 0:{directory,workspaceRoot:boot.mountRoot,preapproved:true,isActive}});activations.register(app,boot,installations,executor);registerManagedRuntimeToolRoutes(app,boot,executor);if(publisher){registerManagedRuntimeToolV3Routes(app,boot,executor)}remotePublishers?.register(app,boot,sessionId=>admissionOpen()&&mount.isAvailable&&requiresActivation&&activations.isActive(sessionId)&&installations.installed(sessionId)!==void 0);return executor}__name(registerManagedContextRoutes,"registerManagedContextRoutes");function runtimeSessionKey(runtimeInstanceId,sessionId){const digest2=createHash6("sha256").update(sessionId).digest("hex");return`${runtimeInstanceId}.${digest2.slice(0,32)}`}__name(runtimeSessionKey,"runtimeSessionKey");function send(res,outcome){if(outcome.status===200){res.status(200).json(outcome.body);return}res.status(outcome.status).json({code:outcome.code,error:REFUSAL_MESSAGES[outcome.code]})}__name(send,"send");init_esbuild_shims();import{constants as constants4,promises as fs5}from"node:fs";import path5 from"node:path";init_esbuild_shims();import{constants as constants3,promises as fs4}from"node:fs";var UNAVAILABLE="Managed CSI root directory is unavailable.";var ManagedCsiRootDirectoryCleanupError=class extends AggregateError{static{__name(this,"ManagedCsiRootDirectoryCleanupError")}constructor(openError,closeError){super([openError,closeError],"Managed CSI root directory cleanup failed.");this.name="ManagedCsiRootDirectoryCleanupError"}};var ManagedCsiRootDirectory=class _ManagedCsiRootDirectory{constructor(root,handle,stats){this.root=root;this.handle=handle;this.rootDevice=stats.dev.toString();this.rootInode=stats.ino.toString()}static{__name(this,"ManagedCsiRootDirectory")}rootDevice;rootInode;fenced=false;operations=new Set;closing;static async open(root,device){if(typeof constants3.O_DIRECTORY!=="number"||typeof constants3.O_NOFOLLOW!=="number")throw new Error(UNAVAILABLE);const before=await namedDirectory(root);if(before.dev.toString()!==device)throw new Error(UNAVAILABLE);const handle=await fs4.open(root,constants3.O_RDONLY|constants3.O_DIRECTORY|constants3.O_NOFOLLOW);let directory;try{const stats=await handle.stat({bigint:true});if(!sameDirectory(before,stats))throw new Error(UNAVAILABLE);directory=new _ManagedCsiRootDirectory(root,handle,stats);await directory.verify();return directory}catch(error){try{await(directory?directory.close():handle.close())}catch(closeError){throw new ManagedCsiRootDirectoryCleanupError(error,closeError)}throw error}}verify(){return this.withVerifiedDirectory(async()=>{})}get isAvailable(){return!this.fenced}async withVerifiedDirectory(operation){if(this.fenced)throw new Error(UNAVAILABLE);let complete;const pending=new Promise(resolve=>{complete=resolve});this.operations.add(pending);try{await this.inspect();try{return await operation(this.handle)}finally{await this.inspect()}}finally{this.operations.delete(pending);complete()}}async inspect(){if(this.fenced)throw new Error(UNAVAILABLE);try{const before=await namedDirectory(this.root);const descriptor=await this.handle.stat({bigint:true});const after=await namedDirectory(this.root);if(this.fenced||!sameDirectory(before,descriptor)||!sameDirectory(after,descriptor)||descriptor.dev.toString()!==this.rootDevice||descriptor.ino.toString()!==this.rootInode)throw new Error(UNAVAILABLE)}catch(error){void this.close().catch(()=>{});throw error}}close(){this.fenced=true;this.closing??=(async()=>{await Promise.all(this.operations);await this.handle.close()})();return this.closing}};async function namedDirectory(root){if(await fs4.realpath(root)!==root)throw new Error(UNAVAILABLE);const stats=await fs4.lstat(root,{bigint:true});if(!stats.isDirectory()||stats.dev<0n||stats.dev>0xffffffffffffffffn||stats.ino<=0n||stats.ino>0xffffffffffffffffn)throw new Error(UNAVAILABLE);return stats}__name(namedDirectory,"namedDirectory");function sameDirectory(left,right){return right.isDirectory()&&left.dev===right.dev&&left.ino===right.ino}__name(sameDirectory,"sameDirectory");var UNAVAILABLE2="Managed CSI mount is unavailable.";var MOUNTINFO_LIMIT=1024*1024;function parseManagedCsiMount(mountinfo,mountRoot){if(!isMountRoot2(mountRoot)||Buffer.byteLength(mountinfo)>MOUNTINFO_LIMIT||mountinfo.includes("\r")||mountinfo.includes("\0")){throw new Error(UNAVAILABLE2)}let observed;for(const line of mountinfo.split("\n")){if(!line)continue;const fields=line.split(" ");const separator=fields.indexOf("-");if(separator<6||fields.length!==separator+4){throw new Error(UNAVAILABLE2)}const target=unescapeField(fields[4]);if(target.startsWith(`${mountRoot}/`))throw new Error(UNAVAILABLE2);if(target!==mountRoot)continue;const source=unescapeField(fields[separator+2]);if(observed!==void 0||!/^[1-9][0-9]{0,9}$/.test(fields[0])||!/^(?:0|[1-9][0-9]{0,9}):(?:0|[1-9][0-9]{0,9})$/.test(fields[2])||BigInt(fields[0])>0xffffffffn||unescapeField(fields[3])!=="/"||fields[separator+1]!=="ext4"||!/^\/dev\/nvme(?:0|[1-9][0-9]*)n[1-9][0-9]*$/.test(source)||!writable(fields[5])||!writable(fields[separator+3])){throw new Error(UNAVAILABLE2)}observed=Object.freeze({mountId:fields[0],device:fields[2],source});try{linuxDeviceNumber(observed.device)}catch{throw new Error(UNAVAILABLE2)}}if(observed===void 0)throw new Error(UNAVAILABLE2);return observed}__name(parseManagedCsiMount,"parseManagedCsiMount");var ManagedCsiMount=class extends ManagedContextMount{static{__name(this,"ManagedCsiMount")}#mountRoot;#serial;#pinned;#closed=false;#observations=new Set;#directory;#closing;#closeFailure;constructor(mountRoot,trustedDiskSerial){super(mountRoot);if(!isMountRoot2(mountRoot)||!/^[A-Za-z0-9._:-]{1,128}$/.test(trustedDiskSerial)){throw new Error(UNAVAILABLE2)}this.#mountRoot=mountRoot;this.#serial=trustedDiskSerial}get isAvailable(){return!this.#closed&&this.#pinned!==void 0}async observe(){return this.withVerifiedRoot(async(_handle,receipt2)=>receipt2)}async withVerifiedRoot(operation){if(this.#closed||process.platform!=="linux"){void this.close().catch(()=>{});throw new Error(UNAVAILABLE2)}let complete;const pending=new Promise(resolve=>{complete=resolve});this.#observations.add(pending);try{const before=await this.kernelObservation();let directory;try{this.#directory??=ManagedCsiRootDirectory.open(this.#mountRoot,linuxDeviceNumber(before.device));directory=await this.#directory}catch{void this.close().catch(()=>{});throw new Error(UNAVAILABLE2)}try{return await directory.withVerifiedDirectory(async handle=>{const receipt2=await this.inspect(before,directory);try{return await operation(handle,receipt2)}finally{await this.inspect(before,directory)}})}catch(error){if(!directory.isAvailable)void this.close().catch(()=>{});throw error}}finally{this.#observations.delete(pending);complete()}}close(){this.#closed=true;this.#closing??=(async()=>{await Promise.all(this.#observations);try{await this.#directory?.then(directory=>directory.close(),error=>{if(error instanceof ManagedCsiRootDirectoryCleanupError)throw error})}catch(error){if(this.#closeFailure)throw new AggregateError([this.#closeFailure,error],UNAVAILABLE2);throw error}if(this.#closeFailure)throw this.#closeFailure})();return this.#closing}async resolve(cwdRelative){try{if(normalizeWorkspaceRelativePath(cwdRelative)!==cwdRelative)return void 0;return await this.withVerifiedRoot(async(root,receipt2)=>{const children=[];try{let parent=root;for(const component of cwdRelative==="."?[]:cwdRelative.split("/")){const address=`/proc/self/fd/${parent.fd}/${component}`;const before=await fs5.lstat(address,{bigint:true});const handle=await fs5.open(address,constants4.O_RDONLY|constants4.O_DIRECTORY|constants4.O_NOFOLLOW);const child={handle,address,stats:before};children.push(child);if(!sameDirectory2(before,await handle.stat({bigint:true}),receipt2.rootDevice))throw new Error(UNAVAILABLE2);parent=handle}await fs5.access(`/proc/self/fd/${parent.fd}`,constants4.R_OK|constants4.X_OK);return cwdRelative==="."?this.#mountRoot:path5.join(this.#mountRoot,...cwdRelative.split("/"))}finally{try{await verifyChildren(children,receipt2.rootDevice)}finally{await this.closeChildren(children.map(({handle})=>handle).reverse())}}})}catch{return void 0}}async rootDirectory(){try{return await this.withVerifiedRoot(async()=>this.#mountRoot)}catch{return void 0}}async closeChildren(handles){const results=await Promise.allSettled(handles.map(async handle=>handle.close()));const errors=results.flatMap(result=>result.status==="rejected"?[result.reason]:[]);if(errors.length>0){this.#closeFailure??=new AggregateError(errors,UNAVAILABLE2);void this.close().catch(()=>{});throw this.#closeFailure}}async kernelObservation(){try{const observation=parseManagedCsiMount(await readBounded("/proc/self/mountinfo",MOUNTINFO_LIMIT),this.#mountRoot);const serial=await readBounded(`/sys/dev/block/${observation.device}/device/serial`,256);if(this.#closed||serial.replace(/\n$/,"")!==this.#serial)throw new Error(UNAVAILABLE2);return observation}catch{void this.close().catch(()=>{});throw new Error(UNAVAILABLE2)}}async inspect(before,directory){const after=await this.kernelObservation();const identity=JSON.stringify([before.mountId,before.device,before.source,directory.rootDevice,directory.rootInode]);if(this.#closed||directory.rootDevice!==linuxDeviceNumber(before.device)||JSON.stringify(before)!==JSON.stringify(after)||this.#pinned!==void 0&&this.#pinned!==identity){void this.close().catch(()=>{});throw new Error(UNAVAILABLE2)}this.#pinned=identity;return Object.freeze({...before,diskSerial:this.#serial,rootDevice:directory.rootDevice,rootInode:directory.rootInode})}};async function verifyChildren(children,device){for(const child of children){if(!sameDirectory2(child.stats,await fs5.lstat(child.address,{bigint:true}),device))throw new Error(UNAVAILABLE2)}}__name(verifyChildren,"verifyChildren");function sameDirectory2(left,right,device){return left.isDirectory()&&right.isDirectory()&&left.dev.toString()===device&&right.dev===left.dev&&right.ino===left.ino}__name(sameDirectory2,"sameDirectory");function isMountRoot2(value){return value.startsWith("/")&&value.length<=2048&&!value.includes("\\")&&!Array.from(value).some(char=>char.charCodeAt(0)<=31||char.charCodeAt(0)>=127&&char.charCodeAt(0)<=159)&&!/[\ud800-\udfff]/u.test(value)&&value.slice(1).split("/").every(part=>part!==""&&part!=="."&&part!=="..")}__name(isMountRoot2,"isMountRoot");function writable(options){const fields=options.split(",");return fields.filter(field=>field==="rw").length===1&&!fields.includes("ro")}__name(writable,"writable");function unescapeField(value){if(/\\(?!040|011|012|134)/.test(value))throw new Error(UNAVAILABLE2);return value.replace(/\\(040|011|012|134)/g,(_,octal)=>String.fromCharCode(Number.parseInt(octal,8)))}__name(unescapeField,"unescapeField");async function readBounded(file,limit){const handle=await fs5.open(file,"r");try{const chunks=[];let size=0;while(size<=limit){const buffer=Buffer.alloc(Math.min(8192,limit+1-size));const{bytesRead}=await handle.read(buffer,0,buffer.length,null);if(bytesRead===0){return new TextDecoder("utf-8",{fatal:true}).decode(Buffer.concat(chunks))}chunks.push(buffer.subarray(0,bytesRead));size+=bytesRead}throw new Error(UNAVAILABLE2)}finally{await handle.close()}}__name(readBounded,"readBounded");init_esbuild_shims();import{isDeepStrictEqual as isDeepStrictEqual4}from"node:util";var MANAGED_CSI_FILE_PROTOCOL="managed-csi/2";var MANAGED_CSI_FILE_PREFIX="/internal/managed-runtime/csi/v2";var MANAGED_CSI_FILE_ROUTES=Object.freeze(["context-attest","context","attest","drain"].map(name=>Object.freeze({method:"POST",path:`${MANAGED_CSI_FILE_PREFIX}/${name}`})));function parseManagedCsiFileJson(bytes,limit){if(bytes.byteLength>limit)throw new Error("Invalid CSI file JSON.");const text2=new TextDecoder("utf-8",{fatal:true}).decode(bytes);parseManagedSessionRecordJson(text2,limit);return JSON.parse(text2,(_key,value,context)=>{if(typeof value==="number"&&(!Number.isSafeInteger(value)||context?.source===void 0||!/^(?:0|[1-9][0-9]*)$/.test(context.source)))throw new Error("Invalid CSI file JSON.");return value})}__name(parseManagedCsiFileJson,"parseManagedCsiFileJson");function parseManagedCsiFileBoot(value){try{const authorityBoot=value!==null&&typeof value==="object"&&"version"in value&&value.version===5;const boot=closed5(value,[...authorityBoot?["authority"]:[],"context","identity","managedCsi","storage","type","version"]);const identity=closed5(boot["identity"],["capabilityDigest","profile","sessionId"]);const data=parseManagedCsiBoot({type:"boot",version:3,managedCsi:MANAGED_CSI_PROTOCOL,context:boot["context"],storage:boot["storage"]});if(boot["type"]!=="boot"||boot["version"]!==4&&!authorityBoot||boot["managedCsi"]!==MANAGED_CSI_FILE_PROTOCOL||identity["profile"]!=="csi-files-retirement/1"||identity["capabilityDigest"]!==CSI_FILES_RETIREMENT_CAPABILITY_DIGEST||typeof identity["sessionId"]!=="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(identity["sessionId"])||data.context.isolationClass!=="session"||data.context.capabilityDigest!==identity["capabilityDigest"])throw new Error;const fields={type:"boot",managedCsi:MANAGED_CSI_FILE_PROTOCOL,identity:Object.freeze(identity),context:data.context,storage:data.storage};return authorityBoot?Object.freeze({...fields,version:5,authority:readManagedCsiNativeAuthority(boot["authority"])}):Object.freeze({...fields,version:4})}catch{throw new Error("Managed CSI file boot document is invalid.")}}__name(parseManagedCsiFileBoot,"parseManagedCsiFileBoot");function readManagedCsiNativeAuthority(value){const authority=closed5(value,["origin","protocolVersion"]);const origin=authority["origin"];if(authority["protocolVersion"]!==1||typeof origin!=="string"||origin.length>2048)throw new Error("Managed CSI authority origin is invalid.");const url=resolveManagedRuntimeBrokerBaseUrl(origin);const hostname=url.hostname;if(url.origin!==origin||/(^|\.)xn--/.test(hostname)||!hostname.startsWith("[")&&!/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*$/.test(hostname)||!hostname.startsWith("[")&&hostname.includes(".")&&!/^\d+\.\d+\.\d+\.\d+$/.test(hostname)&&!/^[a-z]/.test(hostname.split(".").at(-1)??"")||url.port!==""&&Number(url.port)===0)throw new Error("Managed CSI authority origin is not canonical.");return Object.freeze({protocolVersion:1,origin})}__name(readManagedCsiNativeAuthority,"readManagedCsiNativeAuthority");function dataBoot(boot){return{type:"boot",version:3,managedCsi:MANAGED_CSI_PROTOCOL,context:boot.context,storage:boot.storage}}__name(dataBoot,"dataBoot");function createManagedCsiFileReady(boot,port){return Object.freeze({type:"ready",version:boot.version,managedCsi:MANAGED_CSI_FILE_PROTOCOL,identity:boot.identity,context:createManagedContextReady(boot.context,port)})}__name(createManagedCsiFileReady,"createManagedCsiFileReady");function wrapManagedCsiFileContext(boot,context){return Object.freeze({protocolVersion:2,managedCsi:MANAGED_CSI_FILE_PROTOCOL,identity:boot.identity,context})}__name(wrapManagedCsiFileContext,"wrapManagedCsiFileContext");function readManagedCsiFileContext(value,boot){const body2=closed5(value,["context","identity","managedCsi","protocolVersion"]);checkIdentity(body2,boot);return body2["context"]}__name(readManagedCsiFileContext,"readManagedCsiFileContext");function createManagedCsiFileAttestationRequest(boot){return{...createManagedCsiAttestationRequest(dataBoot(boot)),protocolVersion:2,managedCsi:MANAGED_CSI_FILE_PROTOCOL,identity:boot.identity}}__name(createManagedCsiFileAttestationRequest,"createManagedCsiFileAttestationRequest");function validateManagedCsiFileAttestationRequest(value,boot){if(!isDeepStrictEqual4(value,createManagedCsiFileAttestationRequest(boot)))throw new Error("CSI file identity conflicts.")}__name(validateManagedCsiFileAttestationRequest,"validateManagedCsiFileAttestationRequest");function validateManagedCsiFileAttestationResponse(value,boot,pod){const body2=closed5(value,["context","identity","managedCsi","mount","pod","protocolVersion","storage"]);checkIdentity(body2,boot);const{identity:_identity,...data}=body2;validateManagedCsiAttestationResponse({...data,protocolVersion:1,managedCsi:MANAGED_CSI_PROTOCOL},dataBoot(boot),pod)}__name(validateManagedCsiFileAttestationResponse,"validateManagedCsiFileAttestationResponse");function readManagedCsiFileDrain(value,boot,pod){const body2=closed5(value,["context","identity","managedCsi","operation","pod","protocolVersion","retirementId","storage"]);checkIdentity(body2,boot);const{identity:_identity,...data}=body2;return parseManagedCsiDrainRequest({...data,protocolVersion:1,managedCsi:MANAGED_CSI_PROTOCOL},dataBoot(boot),pod)}__name(readManagedCsiFileDrain,"readManagedCsiFileDrain");function checkIdentity(body2,boot){if(body2["protocolVersion"]!==2||body2["managedCsi"]!==MANAGED_CSI_FILE_PROTOCOL||!isDeepStrictEqual4(body2["identity"],boot.identity))throw new Error("CSI file identity conflicts.")}__name(checkIdentity,"checkIdentity");function closed5(value,keys){if(!value||typeof value!=="object"||Array.isArray(value)||!isDeepStrictEqual4(Object.keys(value).sort(),keys))throw new Error;return{...value}}__name(closed5,"closed");init_esbuild_shims();var import_express=__toESM(require_express(),1);import{createHash as createHash10}from"node:crypto";import{isDeepStrictEqual as isDeepStrictEqual8}from"node:util";import{createServer}from"node:http";init_esbuild_shims();import{isDeepStrictEqual as isDeepStrictEqual5}from"node:util";init_esbuild_shims();import{createHash as createHash7,randomUUID as randomUUID5}from"node:crypto";import{constants as constants5,promises as fs6}from"node:fs";import path6 from"node:path";var PREFIX=".qwen-csi-file-history";var UNAVAILABLE3="Managed CSI file backend is unavailable.";var DIR_FLAGS=constants5.O_RDONLY|constants5.O_DIRECTORY|constants5.O_NOFOLLOW;var UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;var ManagedCsiFileBackend=class _ManagedCsiFileBackend{constructor(mount,directory,ownerSessionId){this.mount=mount;this.directory=directory;this.ownerSessionId=ownerSessionId;this.textFileIo={inspect:__name((file,signal)=>this.inspect(file,signal),"inspect"),withMutation:__name((file,signal,operation)=>this.withMutation(file,signal,operation),"withMutation")}}static{__name(this,"ManagedCsiFileBackend")}textFileIo;#directories=[];#directoryHandles=[];#attempts=new Map;#pending=new Set;#inventoryTail=Promise.resolve();#binding;#receipt;#closed=false;#failure;#closing;static async open(mount,ownerSessionId){if(process.platform!=="linux"||!UUID.test(ownerSessionId))throw new Error(UNAVAILABLE3);const directory=await mount.rootDirectory();if(!directory)throw new Error(UNAVAILABLE3);const backend=new _ManagedCsiFileBackend(mount,directory,ownerSessionId);try{await backend.run(async()=>{});return backend}catch(error){try{await backend.close()}catch(closeError){throw new AggregateError([error,closeError],UNAVAILABLE3)}throw error}}getDrainInspection(){return{pendingOperations:this.#pending.size,blocked:this.#failure!==void 0,closed:this.#closed}}async observeRetained(){if(this.#pending.size)throw new Error("Retained observation requires an idle backend.");return this.run(async()=>{const retainedBackups=[];for(const name of[...this.#attempts.keys()].sort()){const attempt=this.#attempts.get(name);await this.authenticate(attempt);retainedBackups.push({...attempt.pin})}if(this.#pending.size!==1)throw new Error("Retained observation requires an idle backend.");const directory=this.#directories[1];return{backupDirectory:{volumeDevice:this.#receipt.rootDevice,volumeInode:this.#receipt.rootInode,directoryDevice:directory.stats.dev.toString(),directoryInode:directory.stats.ino.toString()},retainedBackups}})}close(){this.#closed=true;this.#closing??=(async()=>{await Promise.all(this.#pending);const handles=[...[...this.#attempts.values()].flatMap(attempt=>attempt.handle?[attempt.handle]:[]),...this.#directoryHandles.slice().reverse()];const results=await Promise.allSettled(handles.map(async handle=>handle.close()));const errors=results.flatMap(result=>result.status==="rejected"?[result.reason]:[]);if(this.#failure)errors.unshift(this.#failure);if(errors.length)throw new AggregateError(errors,UNAVAILABLE3)})();return this.#closing}withWorkingFile(file,operation){const components=this.components(file);return this.run((root,receipt2)=>this.working(root,receipt2,components,false,async working=>operation(working.leaf?await this.source(working.leaf):null)))}withBackupFile(name,operation){if(!validLeaf(name))return Promise.reject(new Error("Invalid retained backup name."));return this.run(async()=>{const attempt=this.#attempts.get(name);if(!attempt)throw this.fault(new Error("Unknown retained backup."));await this.authenticate(attempt);try{return await operation(await this.backupSource(attempt))}finally{await this.authenticate(attempt)}})}createBackup(file,version){const components=this.components(file);if(!Number.isSafeInteger(version)||version<1)return Promise.reject(new Error("Invalid backup version."));return this.run((root,receipt2)=>this.working(root,receipt2,components,false,async working=>{if(!working.leaf)return{backupFileName:null,version,backupTime:new Date};const source=await this.source(working.leaf);const name=`${randomUUID5()}@v${version}`;const attempt={name};const address=this.backupAddress(name);try{await this.withInventory(async()=>{this.#attempts.set(name,attempt);attempt.handle=await fs6.open(address,constants5.O_RDWR|constants5.O_CREAT|constants5.O_EXCL|constants5.O_NOFOLLOW|constants5.O_NONBLOCK,384);attempt.stats=await attempt.handle.stat({bigint:true});this.requireFile(attempt.stats,receipt2.rootDevice)});const handle=attempt.handle;const digest2=createHash7("sha256");const bytes=Buffer.allocUnsafe(64*1024);let position=0;while(position<source.stats.size){const{bytesRead}=await source.fileHandle.read(bytes,0,Math.min(bytes.length,source.stats.size-position),position);if(bytesRead===0)throw new Error("Source changed during backup.");const chunk=bytes.subarray(0,bytesRead);digest2.update(chunk);await this.writeBytes(handle,chunk,position);position+=bytesRead}const rawDigest=digest2.digest("hex");if(await digestFileReadSource(source)!==rawDigest)throw new Error("Source changed during backup.");await handle.chmod(source.stats.mode&4095);await handle.sync();await this.#directories[1].handle.sync();const final=await handle.stat({bigint:true});if(!sameInode(final,attempt.stats)||final.size!==BigInt(source.stats.size)||final.nlink!==1n)throw new Error(UNAVAILABLE3);const pin2=Object.freeze({name,device:final.dev.toString(),inode:final.ino.toString(),byteLength:source.stats.size,digest:rawDigest,mode:Number(final.mode&0o7777n)});attempt.pin=pin2;await this.authenticate(attempt);return{backupFileName:name,version,backupTime:new Date}}catch(error){throw this.fault(error)}}))}withReadFile(request,operation){request.signal?.throwIfAborted();return this.withWorkingFile(request.path,async source=>{request.signal?.throwIfAborted();if(!source)throw new FileReadOpenError(Object.assign(new Error("File not found."),{code:"ENOENT"}));return operation(source)}).catch(error=>{const code=error instanceof Error?error.code:void 0;if(["EISDIR","ENOTDIR","ELOOP","EACCES"].includes(code??""))throw new FileReadOpenError(error);throw error})}readTextFile(params){return this.withWorkingFile(params.path,async source=>{if(!source)throw Object.assign(new Error("File not found."),{code:"ENOENT"});if((params.line??0)>0||Number.isFinite(params.limit)||params.maxOutputBytes!==void 0){const{content,...metadata}=await readTextContentRangeFromHandle(source.fileHandle,{fileSize:source.stats.size,offset:params.line??0,limit:params.limit??Infinity,maxOutputBytes:params.maxOutputBytes??256*1024,maxScanBytes:source.stats.size,signal:params.signal});return{content,_meta:metadata}}return this.text(source,params.signal)})}async writeTextFile(_params){throw new Error("Managed CSI text writes require the scoped mutation writer.")}findFiles(_fileName,_searchPaths){throw new Error("Managed CSI file tools do not support pathname glob.")}inspect(file,signal){signal?.throwIfAborted();return this.withWorkingFile(file,async source=>source?{kind:"file",response:await this.text(source,signal),stats:source.stats}:{kind:"missing"})}withMutation(file,signal,operation){const components=this.components(file);signal.throwIfAborted();return this.run((root,receipt2)=>this.working(root,receipt2,components,true,async working=>{const source=working.leaf?await this.source(working.leaf):null;const original=source?{kind:"file",response:await this.text(source,signal),stats:source.stats}:{kind:"missing"};let active=true;let write;try{return await operation({original,write:__name(params=>{if(!active||write||params.path!==file)return Promise.reject(new Error("CSI mutation writer is not available."));write=this.commit(working,params,signal);void write.catch(()=>{});return write},"write")})}finally{active=false;await write}}))}async commit(working,params,signal){signal.throwIfAborted();const bytes=await encodeTextFileContentAsync(params.path,params.content,params._meta);signal.throwIfAborted();let original;let changed=false;const originalName=working.missing.at(-1);try{if(working.leaf){await this.verifyEntry(working.leaf,true);original=await readFileHandleBytes(working.leaf.handle,Number(working.leaf.stats.size),signal);if(BigInt(original.length)!==working.leaf.stats.size)throw new Error(UNAVAILABLE3);await this.verifyEntry(working.leaf,true)}else{if(await this.lstat(addressOf(working.parent,working.missing[0])))throw new Error("CSI target appeared before mutation.");while(working.missing.length>1){const component=working.missing[0];const address2=addressOf(working.parent,component);await fs6.mkdir(address2,{mode:448});const entry=await this.openDirectory(address2,working.receipt.rootDevice,working.owned);working.parents.push(entry);await entry.handle.sync();await working.parent.sync();working.parent=entry.handle;working.missing.shift()}const address=addressOf(working.parent,working.missing[0]);const handle=await fs6.open(address,constants5.O_RDWR|constants5.O_CREAT|constants5.O_EXCL|constants5.O_NOFOLLOW|constants5.O_NONBLOCK,384);working.owned.push(handle);const stats=await handle.stat({bigint:true});this.requireFile(stats,working.receipt.rootDevice);working.leaf={handle,address,stats};working.missing=[];changed=true}const leaf=working.leaf;await this.checkAlias(leaf.stats);changed=true;await this.writeBytes(leaf.handle,bytes,0,signal);await leaf.handle.truncate(bytes.length);await leaf.handle.sync();await working.parent.sync();const committed=await leaf.handle.stat({bigint:true});if(!sameInode(leaf.stats,committed)||committed.mode!==leaf.stats.mode||committed.size!==BigInt(bytes.length))throw new Error(UNAVAILABLE3);leaf.stats=committed;await this.verifyEntry(leaf,true);return(await this.source(leaf)).stats}catch(error){if(changed&&working.leaf){try{const leaf=working.leaf;const named=await fs6.lstat(leaf.address,{bigint:true});const opened=await leaf.handle.stat({bigint:true});if(!named.isFile()||!sameInode(leaf.stats,named)||!sameInode(leaf.stats,opened)||named.mode!==leaf.stats.mode||opened.mode!==leaf.stats.mode)throw new Error(UNAVAILABLE3);await this.checkAlias(opened);if(original){await this.writeBytes(leaf.handle,original,0);await leaf.handle.truncate(original.length);await leaf.handle.sync();leaf.stats=await leaf.handle.stat({bigint:true});await this.verifyEntry(leaf,true)}else{await fs6.unlink(leaf.address);working.leaf=void 0;working.missing=[originalName]}await working.parent.sync()}catch(rollbackError){throw this.fault(new AggregateError([error,rollbackError],"CSI write rollback failed."))}}if(signal.aborted&&error===signal.reason)throw error;throw this.fault(error)}}async text(source,signal){const bytes=await readFileHandleBytes(source.fileHandle,source.stats.size,signal);if(bytes.length!==source.stats.size)throw this.fault(new Error("CSI file changed while reading."));const{content,encoding,bom}=await decodeBufferWithEncodingInfoAsync(bytes);signal?.throwIfAborted();return{content,_meta:{encoding,bom,lineEnding:detectLineEnding(content),originalLineCount:content.split("\n").length,originalLineCountExact:true,truncatedByBytes:false}}}components(file){if(!path6.isAbsolute(file)||path6.resolve(file)!==file||!file.startsWith(this.directory+"/"))throw new Error("CSI file path is not canonical.");const components=file.slice(this.directory.length+1).split("/");if(!components.every(validLeaf)||components[0]===PREFIX)throw new Error("CSI file path is reserved or invalid.");return components}async run(operation){if(this.#closed||this.#failure)throw this.#failure??new Error(UNAVAILABLE3);let complete;const pending=new Promise(resolve=>{complete=resolve});this.#pending.add(pending);let operationFailed=false;try{return await this.mount.withVerifiedRoot(async(root,receipt2)=>{this.#binding??=this.bind(root,receipt2);await this.#binding;await this.verifyStorage();try{return await operation(root,receipt2)}catch(error){operationFailed=true;throw error}finally{await this.verifyStorage()}})}catch(error){const code=error instanceof Error?error.code:void 0;if(!operationFailed||this.mount.isAvailable===false||["EIO","ENOSPC","EDQUOT","ENODEV","ESTALE","EBADF"].includes(code??""))this.fault(error);throw error}finally{this.#pending.delete(pending);complete()}}async bind(root,receipt2){this.#receipt=receipt2;try{const prefixAddress=addressOf(root,PREFIX);if(!await this.lstat(prefixAddress)){await fs6.mkdir(prefixAddress,{mode:448});await root.sync()}const prefix=await this.openDirectory(prefixAddress,receipt2.rootDevice,this.#directoryHandles);this.#directories.push(prefix);const ownerAddress=addressOf(prefix.handle,this.ownerSessionId);await fs6.mkdir(ownerAddress,{mode:448});await prefix.handle.sync();const owner=await this.openDirectory(ownerAddress,receipt2.rootDevice,this.#directoryHandles);this.#directories.push(owner);await owner.handle.sync();if((await fs6.readdir(`/proc/self/fd/${owner.handle.fd}`)).length)throw new Error("CSI history initial bind requires an empty directory.")}catch(error){throw this.fault(error)}}verifyStorage(){return this.withInventory(async()=>{try{if(this.#failure)throw this.#failure;for(const directory of this.#directories)await this.verifyEntry(directory,false);const owner=this.#directories[1];const names=(await fs6.readdir(`/proc/self/fd/${owner.handle.fd}`)).sort();const expected=[...this.#attempts.keys()].sort();if(names.length!==expected.length||names.some((name,i)=>name!==expected[i]))throw new Error("CSI history contains unknown or missing leaves.");for(const attempt of this.#attempts.values()){if(!attempt.handle||!attempt.stats)throw new Error("CSI backup registration is incomplete.");const named=await fs6.lstat(this.backupAddress(attempt.name),{bigint:true});const opened=await attempt.handle.stat({bigint:true});this.requireFile(named,this.#receipt.rootDevice);if(!sameInode(named,attempt.stats)||!sameInode(opened,attempt.stats))throw new Error(UNAVAILABLE3)}}catch(error){throw this.fault(error)}})}async working(root,receipt2,components,writable2,operation){const working={root,receipt:receipt2,parent:root,parents:[],owned:[],missing:components};let observed=false;try{for(let index=0;index<components.length-1;index++){const address=addressOf(working.parent,components[index]);if(!await this.lstat(address))break;const entry=await this.openDirectory(address,receipt2.rootDevice,working.owned);if(this.#directories.some(directory=>sameInode(directory.stats,entry.stats)))throw this.fault(new Error("CSI retained directory alias is forbidden."));working.parents.push(entry);working.parent=entry.handle;working.missing=components.slice(index+1)}if(working.missing.length===1){const address=addressOf(working.parent,working.missing[0]);const before=await this.lstat(address);if(before){this.requireFile(before,receipt2.rootDevice);const handle=await fs6.open(address,(writable2?constants5.O_RDWR:constants5.O_RDONLY)|constants5.O_NOFOLLOW|constants5.O_NONBLOCK);working.owned.push(handle);const opened=await handle.stat({bigint:true});if(!stableFile(before,opened))throw this.fault(new Error(UNAVAILABLE3));await this.checkAlias(opened);working.leaf={handle,address,stats:opened};working.missing=[]}}observed=true;return await operation(working)}finally{try{if(observed)await this.verifyWorking(working);else for(const parent of working.parents)await this.verifyEntry(parent,false)}finally{await this.closeEphemeral(working.owned.reverse())}}}async verifyWorking(working){if(working.leaf){await this.verifyEntry(working.leaf,true);await this.checkAlias(working.leaf.stats)}else if(await this.lstat(addressOf(working.parent,working.missing[0])))throw this.fault(new Error("CSI missing path changed during observation."));for(const parent of working.parents)await this.verifyEntry(parent,false)}async openDirectory(address,device,owned){const before=await fs6.lstat(address,{bigint:true});if(!before.isDirectory())throw Object.assign(new Error("CSI path parent is not a directory."),{code:before.isSymbolicLink()?"ELOOP":"ENOTDIR"});if(before.dev.toString()!==device)throw this.fault(new Error(UNAVAILABLE3));const handle=await fs6.open(address,DIR_FLAGS);owned.push(handle);try{const opened=await handle.stat({bigint:true});if(!opened.isDirectory()||!sameInode(before,opened))throw new Error(UNAVAILABLE3);return{handle,address,stats:opened}}catch(error){throw this.fault(error)}}async verifyEntry(entry,file){try{const named=await fs6.lstat(entry.address,{bigint:true});const opened=await entry.handle.stat({bigint:true});if(file?!stableFile(entry.stats,named)||!stableFile(entry.stats,opened):!named.isDirectory()||!opened.isDirectory()||!sameInode(entry.stats,named)||!sameInode(entry.stats,opened))throw new Error(UNAVAILABLE3)}catch(error){throw this.fault(error)}}async source(entry){const stats=await entry.handle.stat();if(!Number.isSafeInteger(stats.size)||stats.size<0||BigInt(stats.size)!==entry.stats.size)throw this.fault(new Error(UNAVAILABLE3));return{kind:"descriptor",fileHandle:entry.handle,stats}}async backupSource(attempt){return{kind:"descriptor",fileHandle:attempt.handle,stats:await attempt.handle.stat()}}async authenticate(attempt){try{const pin2=attempt.pin;if(!pin2||!attempt.handle||!attempt.stats)throw new Error("CSI retained backup is incomplete.");const opened=await attempt.handle.stat({bigint:true});const named=await fs6.lstat(this.backupAddress(attempt.name),{bigint:true});this.requireFile(opened,pin2.device);if(!sameInode(opened,attempt.stats)||!sameInode(named,attempt.stats)||!named.isFile()||opened.size!==BigInt(pin2.byteLength)||named.size!==opened.size||opened.mode!==named.mode||Number(opened.mode&0o7777n)!==pin2.mode||opened.nlink!==1n||await digestFileReadSource(await this.backupSource(attempt))!==pin2.digest)throw new Error("CSI retained backup pin changed.")}catch(error){throw this.fault(error)}}checkAlias(stats){return this.withInventory(async()=>{if([...this.#attempts.values()].some(attempt=>attempt.stats&&sameInode(attempt.stats,stats)))throw this.fault(new Error("CSI retained backup alias is forbidden."))})}withInventory(operation){const result=this.#inventoryTail.then(()=>{if(this.#failure)throw this.#failure;return operation()});this.#inventoryTail=result.then(()=>{},()=>{});return result}requireFile(stats,device){if(!stats.isFile())throw Object.assign(new Error("CSI tools require an ordinary file."),{code:stats.isDirectory()?"EISDIR":"ELOOP"});if(stats.dev.toString()!==device||stats.size<0n||stats.size>BigInt(Number.MAX_SAFE_INTEGER)){throw this.fault(Object.assign(new Error("CSI tools require an ordinary file on the original device."),stats.isDirectory()?{code:"EISDIR"}:{}))}}backupAddress(name){return addressOf(this.#directories[1].handle,name)}async lstat(address){try{return await fs6.lstat(address,{bigint:true})}catch(error){if(error.code==="ENOENT")return null;throw this.fault(error)}}async writeBytes(handle,bytes,position,signal){let offset=0;while(offset<bytes.length){signal?.throwIfAborted();const{bytesWritten}=await handle.write(bytes,offset,bytes.length-offset,position+offset);if(!Number.isSafeInteger(bytesWritten)||bytesWritten<=0||bytesWritten>bytes.length-offset)throw new Error("CSI file write did not progress.");offset+=bytesWritten}signal?.throwIfAborted()}async closeEphemeral(handles){const results=await Promise.allSettled(handles.map(async handle=>handle.close()));const errors=results.flatMap(result=>result.status==="rejected"?[result.reason]:[]);if(errors.length)throw this.fault(new AggregateError(errors,UNAVAILABLE3))}fault(error){this.#failure??=error instanceof Error?error:new Error(String(error));void this.close().catch(()=>{});return this.#failure}};function validLeaf(name){return name.length>0&&name!=="."&&name!==".."&&!name.includes("/")&&!name.includes("\\")&&[...name].every(character=>character.charCodeAt(0)>=32&&character.charCodeAt(0)!==127)}__name(validLeaf,"validLeaf");function addressOf(parent,name){return`/proc/self/fd/${parent.fd}/${name}`}__name(addressOf,"addressOf");function sameInode(a,b){return a.dev===b.dev&&a.ino===b.ino}__name(sameInode,"sameInode");function stableFile(a,b){return b.isFile()&&sameInode(a,b)&&a.size===b.size&&a.mode===b.mode&&a.mtimeNs===b.mtimeNs&&a.ctimeNs===b.ctimeNs}__name(stableFile,"stableFile");async function composeManagedCsiFiles(options){if(options.ownerSessionId!==options.runtimeSessionId||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(options.ownerSessionId)||options.profile!=="csi-files-retirement/1"||options.capabilityDigest!==CSI_FILES_RETIREMENT_CAPABILITY_DIGEST)throw new Error("Managed CSI file composition identity is unavailable.");let backend;try{return await options.mount.withVerifiedRoot(async()=>{backend=await ManagedCsiFileBackend.open(options.mount,options.ownerSessionId);const storage=backend;const directory=storage.directory;const config=new Config({sessionId:options.runtimeSessionId,targetDir:directory,cwd:directory,includeDirectories:[directory],model:"managed-runtime-worker",debugMode:false,usageStatisticsEnabled:false,approvalMode:"yolo",fileCheckpointingEnabled:false,fileReadCacheDisabled:true});config.setFileSystemService(storage);const history2=new ManagedRuntimeFileHistory(options.ownerSessionId,directory,null,storage);await history2.ready();let closed8=false;let closing;return{tools:{sessionId:options.runtimeSessionId,directory,workspaceRoot:directory,retainedFileHistory:storage,fileHistory:history2,admitsDirectory:__name(candidate=>candidate===directory,"admitsDirectory"),isActive:__name(()=>!closed8&&!storage.getDrainInspection().blocked&&!storage.getDrainInspection().closed,"isActive"),tools:new Map([new ReadFileTool(config),new WriteFileTool(config),new EditTool(config)].map(tool=>[tool.name,tool]))},history:history2,observe:__name(async()=>{if(closed8)throw new Error("Managed CSI file composition is closed.");await history2.history.drain();const result=history2.state();const observation=await storage.observeRetained();if(closed8||!isDeepStrictEqual5(result,history2.state()))throw new Error("Managed CSI history changed during observation.");return{history:result,storage:observation}},"observe"),close:__name(()=>{closed8=true;closing??=(async()=>{const joined=await Promise.allSettled([history2.history.drain(),storage.close()]);const mountResult=await Promise.allSettled([options.mount.close()]);const errors=[...joined,...mountResult].flatMap(result=>result.status==="rejected"?[result.reason]:[]);if(errors.length)throw new AggregateError(errors,"Managed CSI file composition close failed.")})();return closing},"close")}})}catch(error){const joined=await Promise.allSettled([backend?.close()]);const mountResult=await Promise.allSettled([options.mount.close()]);const errors=[error,...[...joined,...mountResult].flatMap(result=>result.status==="rejected"?[result.reason]:[])];throw new AggregateError(errors,"Managed CSI file composition failed.")}}__name(composeManagedCsiFiles,"composeManagedCsiFiles");init_esbuild_shims();import{createHash as createHash8,randomUUID as randomUUID6}from"node:crypto";import{isDeepStrictEqual as isDeepStrictEqual6}from"node:util";var CSI_NATIVE_READBACK_PATH="/internal/runtime-broker/csi/v1/native:read";var CSI_NATIVE_REQUEST_LIMIT=16*1024;var CSI_NATIVE_RESPONSE_LIMIT=8*1024*1024;var UUID2=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;var CONFIG=`sha256:${createHash8("sha256").update("csi-files-retirement-tools/1\0csi-files-retirement-policy/1").digest("hex")}`;var COMMON=["protocolVersion","requestId","action","identity","context","installedContext"];function readCsiNativeRequest(value){const body2=closed6(value,[...COMMON,"subject"]);common(body2);switch(body2["action"]){case"bind":ensure(body2["subject"]===null);break;case"prepare":ref(body2["subject"],"managed-file_history");break;case"execute":id(body2["subject"]);break;default:throw invalid3()}ensure(Buffer.byteLength(JSON.stringify(body2))<=CSI_NATIVE_REQUEST_LIMIT);return structuredClone(body2)}__name(readCsiNativeRequest,"readCsiNativeRequest");function readCsiNativeResponse(value,request){readCsiNativeRequest(request);const body2=closed6(value,[...COMMON,"head","evidence"]);common(body2);for(const field of COMMON)ensure(isDeepStrictEqual6(body2[field],request[field]));const head=closed6(body2["head"],["revision","sequence","digest"]);ensure(counter(head["revision"])>0&&counter(head["sequence"])>0);digest(head["digest"]);const owner=object3(body2["identity"])["sessionId"];const evidence=object3(body2["evidence"]);switch(body2["action"]){case"bind":closed6(evidence,["kind"]);ensure(evidence["kind"]==="ready");break;case"prepare":{closed6(evidence,["kind","intentRef","resources","members"]);ensure(evidence["kind"]==="intent"&&isDeepStrictEqual6(evidence["intentRef"],request.subject));const required=new Map;add(required,ref(evidence["intentRef"],"managed-file_history"));const members=list(evidence["members"]);ensure(members.length>0&&members.length<=4096);let previous=-1;let prompt;let batch;const calls=new Set;const functions=new Set;for(const candidate of members){const member=execution(candidate,owner);const ordinal=counter(member["ordinal"]);ensure(ordinal>previous&&!calls.has(member["callId"])&&!functions.has(member["functionCallId"]));ensure(prompt===void 0||prompt===member["promptId"]&&batch===member["batchId"]);prompt=member["promptId"];batch=member["batchId"];previous=ordinal;calls.add(member["callId"]);functions.add(member["functionCallId"]);add(required,ref(member["inputRef"],"managed-tool-input"));add(required,ref(member["toolDefinitionRef"],"managed-tool-definition"))}resources(evidence["resources"],required);break}case"execute":{closed6(evidence,["kind","executionReference","preparedRef","authorizationRevision","authorizationSequence","grant","resources"]);ensure(evidence["kind"]==="authorization");const reference2=execution(evidence["executionReference"],owner);const required=new Map;const inputRef=ref(reference2["inputRef"],"managed-tool-input");add(required,inputRef);add(required,ref(reference2["toolDefinitionRef"],"managed-tool-definition"));const prepared=evidence["preparedRef"];if(prepared!==null)add(required,ref(prepared,"managed-file_history"));const grant=readCsiNativeGrant(evidence["grant"]);ensure(grant["executionCallId"]===request.subject&&isDeepStrictEqual6(grant["executionReference"],reference2)&&isDeepStrictEqual6(grant["preparedRef"],prepared));for(const field of["authorizationRevision","authorizationSequence"]){const count=counter(evidence[field]);ensure(count===grant[field]&&count<=counter(head[field==="authorizationRevision"?"revision":"sequence"]))}for(const field of["identity","context","installedContext"])ensure(isDeepStrictEqual6(grant[field],body2[field]));const bytes=resources(evidence["resources"],required);const input=closed6(parseManagedCsiFileJson(bytes.get(inputRef.resourceId),64*1024),["harnessSessionId","runtimeSessionId","payloadJson"]);ensure(input["harnessSessionId"]===owner&&input["runtimeSessionId"]===owner&&typeof input["payloadJson"]==="string");ensure(`sha256:${createHash8("sha256").update(input["payloadJson"]).digest("hex")}`===reference2["argsDigest"]);const payload=closed6(parseManagedSessionRecordJson(input["payloadJson"],64*1024),["toolName","input"]);if(prepared===null)ensure(payload["toolName"]==="read_file");break}default:throw invalid3()}ensure(Buffer.byteLength(JSON.stringify(body2))<=CSI_NATIVE_RESPONSE_LIMIT);return structuredClone(body2)}__name(readCsiNativeResponse,"readCsiNativeResponse");function readCsiNativeGrant(value){const grant=closed6(value,["protocolVersion","runtimeBindingId","bindingGeneration","authorizedBindingVersion","executionCallId","dispatchGeneration","authorizationRevision","authorizationSequence","executionReference","intent","checkpointRef","preparedRef","identity","context","installedContext"]);ensure(grant["protocolVersion"]===1);commonContext(grant);id(grant["runtimeBindingId"]);id(grant["executionCallId"]);execution(grant["executionReference"],object3(grant["identity"])["sessionId"]);for(const field of["bindingGeneration","authorizedBindingVersion","dispatchGeneration"])ensure(isCanonicalDecimalText(grant[field]));for(const field of["authorizationRevision","authorizationSequence"])ensure(counter(grant[field])>0);const intent=closed6(grant["intent"],["revision","sequence"]);ensure(counter(intent["revision"])>0&&counter(intent["sequence"])>0&&counter(intent["revision"])<counter(grant["authorizationRevision"])&&counter(intent["sequence"])<counter(grant["authorizationSequence"]));ref(grant["checkpointRef"],"managed-checkpoint");if(grant["preparedRef"]!==null)ref(grant["preparedRef"],"managed-file_history");return grant}__name(readCsiNativeGrant,"readCsiNativeGrant");function common(value){ensure(value["protocolVersion"]===1);uuid(value["requestId"]);commonContext(value)}__name(common,"common");function commonContext(value){const identity=closed6(value["identity"],["profile","sessionId","capabilityDigest"]);ensure(identity["profile"]==="csi-files-retirement/1"&&identity["capabilityDigest"]===CSI_FILES_RETIREMENT_CAPABILITY_DIGEST);uuid(identity["sessionId"]);const context=closed6(value["context"],["protocolVersion","managedContext","runtimeInstanceId","runtimeIncarnation","leaseId","epoch","provisionRequestId","tenantId","workspaceId","workspaceGeneration","storageId","mountRoot","capabilityDigest","isolationClass"]);ensure(context["protocolVersion"]===3&&context["isolationClass"]==="session"&&context["capabilityDigest"]===identity["capabilityDigest"]);const{protocolVersion:_version,...fields}=context;parseManagedContextBoot({...fields,type:"boot",version:2,token:"validation-token"});const installed=closed6(value["installedContext"],["protocolVersion","managedContext","operationId","sessionId","contextDigest","binding"]);ensure(installed["protocolVersion"]===3&&installed["managedContext"]==="managed-context/1"&&installed["sessionId"]===identity["sessionId"]);const owner=identity["sessionId"];const hash=createHash8("md5").update(owner).digest();hash[6]=hash[6]&15|48;hash[8]=hash[8]&63|128;const hex=hash.toString("hex");ensure(installed["operationId"]===`${hex.slice(0,8)}-${hex.slice(8,12)}-${hex.slice(12,16)}-${hex.slice(16,20)}-${hex.slice(20)}`);const binding=closed6(installed["binding"],["tenantId","workspaceId","workspaceGeneration","storageId","cwdRelative","contextConfigRef","contextRevision"]);for(const field of["tenantId","workspaceId","workspaceGeneration","storageId"])ensure(binding[field]===context[field]);ensure(binding["cwdRelative"]==="."&&binding["contextRevision"]==="1"&&binding["contextConfigRef"]===CONFIG);ensure(computeManagedContextDigest(binding)===installed["contextDigest"])}__name(commonContext,"commonContext");function execution(value,owner){const result=closed6(value,["sessionId","promptId","callId","argsDigest","batchId","functionCallId","partIndex","ordinal","inputRef","toolDefinitionRef","dispatchMode"]);ensure(result["sessionId"]===owner&&result["dispatchMode"]==="deferred");for(const field of["promptId","callId","batchId"])uuid(result[field]);id(result["functionCallId"]);digest(result["argsDigest"],true);counter(result["partIndex"]);counter(result["ordinal"]);ensure(ref(result["inputRef"],"managed-tool-input").resourceId!==ref(result["toolDefinitionRef"],"managed-tool-definition").resourceId);return result}__name(execution,"execution");function resources(value,required){const result=new Map;for(const candidate of list(value)){const entry=closed6(candidate,["reference","bytesBase64"]);const reference2=object3(entry["reference"]);const resourceId=id(reference2["resourceId"]);ensure(required.has(resourceId)&&isDeepStrictEqual6(required.get(resourceId),reference2));ensure(typeof entry["bytesBase64"]==="string");const encoded=entry["bytesBase64"];const bytes=Buffer.from(encoded,"base64");ensure(bytes.toString("base64")===encoded&&bytes.length<=64*1024&&bytes.length===reference2["byteLength"]&&createHash8("sha256").update(bytes).digest("hex")===reference2["digest"]&&!result.has(resourceId));result.set(resourceId,bytes)}ensure(result.size===required.size);return result}__name(resources,"resources");function ref(value,kind){const result=assertManagedSessionDurableRef(value,"CSI native resource");ensure(result.kind===kind&&result.schemaVersion===1&&result.byteLength>0&&result.byteLength<=64*1024);return result}__name(ref,"ref");function add(required,reference2){const previous=required.get(reference2.resourceId);ensure(previous===void 0||isDeepStrictEqual6(previous,reference2));required.set(reference2.resourceId,reference2)}__name(add,"add");function counter(value){ensure(Number.isSafeInteger(value)&&value>=0);return value}__name(counter,"counter");function id(value){return assertManagedSessionStableId(value,"CSI native identity")}__name(id,"id");function digest(value,prefix=false){ensure(typeof value==="string"&&(prefix?/^sha256:[0-9a-f]{64}$/:/^[0-9a-f]{64}$/).test(value))}__name(digest,"digest");function uuid(value){ensure(typeof value==="string"&&UUID2.test(value))}__name(uuid,"uuid");function list(value){ensure(Array.isArray(value));return value}__name(list,"list");function object3(value){ensure(value!==null&&typeof value==="object"&&!Array.isArray(value));return value}__name(object3,"object");function closed6(value,keys){const result=object3(value);ensure(isDeepStrictEqual6(Object.keys(result).sort(),[...keys].sort()));return result}__name(closed6,"closed");function ensure(condition){if(!condition)throw invalid3()}__name(ensure,"ensure");function invalid3(){return new Error("Invalid private CSI native readback.")}__name(invalid3,"invalid");async function readCurrentCsiNative(boot,installedContext,action,subject){if(boot.version!==5)throw invalid3();const request=readCsiNativeRequest({protocolVersion:1,requestId:randomUUID6(),action,identity:boot.identity,context:createManagedContextAttestationResponse(boot.context),installedContext,subject});const response=await fetch(`${boot.authority.origin}${CSI_NATIVE_READBACK_PATH}`,{method:"POST",redirect:"error",signal:AbortSignal.timeout(15e3),headers:{authorization:`Bearer ${boot.context.token}`,"content-type":"application/json","cache-control":"no-store"},body:JSON.stringify(request)});ensure(response.status===200&&response.headers.get("content-encoding")===null&&response.headers.get("cache-control")==="no-store"&&response.headers.get("content-type")?.split(";")[0].trim()==="application/json");const reader=response.body?.getReader();if(!reader)throw invalid3();const chunks=[];let length=0;try{while(true){const next=await reader.read();if(next.done)break;length+=next.value.length;ensure(length<=CSI_NATIVE_RESPONSE_LIMIT);chunks.push(next.value)}}finally{await reader.cancel();reader.releaseLock()}return readCsiNativeResponse(parseManagedCsiFileJson(Buffer.concat(chunks),CSI_NATIVE_RESPONSE_LIMIT),request)}__name(readCurrentCsiNative,"readCurrentCsiNative");init_esbuild_shims();import{isDeepStrictEqual as isDeepStrictEqual7}from"node:util";import{createHash as createHash9}from"node:crypto";var CSI_FILE_HISTORY_PATH="/internal/managed-runtime/csi/v2/file-history";function readCsiPreparationEvidence(response){ensure2(response.action==="prepare");const owner=response.identity["sessionId"];ensure2(typeof owner==="string");const evidence=response.evidence;ensure2(evidence["kind"]==="intent"&&Array.isArray(evidence["resources"])&&Array.isArray(evidence["members"]));const resources2=new Map;for(const candidate of evidence["resources"]){const item=object4(candidate);const ref2=object4(item["reference"]);ensure2(typeof ref2["resourceId"]==="string"&&typeof item["bytesBase64"]==="string");resources2.set(ref2["resourceId"],Buffer.from(item["bytesBase64"],"base64"))}const originalRef=object4(evidence["intentRef"]);ensure2(typeof originalRef["resourceId"]==="string");const bytes=resources2.get(originalRef["resourceId"]);ensure2(bytes!==void 0);const body2=closed7(parseManagedCsiFileJson(bytes,64*1024),["operationId","revision","previousRecordRef","schemaVersion","profile","runtimeSessionId","state","backupDirectory","retainedBackups","preparation","record"]);ensure2(body2["schemaVersion"]===2&&body2["profile"]==="csi-files-retirement/1"&&body2["runtimeSessionId"]===owner);const preparation=closed7(body2["preparation"],["stage","turnId","promptId","batchId","invocations","paths"]);ensure2(preparation["stage"]==="intent"&&preparation["turnId"]===preparation["promptId"]&&Array.isArray(preparation["invocations"])&&Array.isArray(preparation["paths"])&&preparation["invocations"].length===evidence["members"].length);const paths=new Set;for(const[index,candidate]of preparation["invocations"].entries()){const invocation=closed7(candidate,["executionCallId","callId","functionCallId","toolName","partIndex","ordinal","requestDigest","inputRef","toolDefinitionRef"]);ensure2(typeof invocation["executionCallId"]==="string"&&invocation["executionCallId"].length>0);const member=object4(evidence["members"][index]);ensure2(isDeepStrictEqual7(member,{sessionId:owner,promptId:preparation["promptId"],batchId:preparation["batchId"],callId:invocation["callId"],functionCallId:invocation["functionCallId"],partIndex:invocation["partIndex"],ordinal:invocation["ordinal"],argsDigest:invocation["requestDigest"],inputRef:invocation["inputRef"],toolDefinitionRef:invocation["toolDefinitionRef"],dispatchMode:"deferred"}));const inputRef=object4(invocation["inputRef"]);ensure2(typeof inputRef["resourceId"]==="string");const inputBytes=resources2.get(inputRef["resourceId"]);ensure2(inputBytes!==void 0);const wrapper=closed7(parseManagedCsiFileJson(inputBytes,64*1024),["harnessSessionId","runtimeSessionId","payloadJson"]);ensure2(wrapper["harnessSessionId"]===owner&&wrapper["runtimeSessionId"]===owner&&typeof wrapper["payloadJson"]==="string");ensure2(`sha256:${createHash9("sha256").update(wrapper["payloadJson"]).digest("hex")}`===invocation["requestDigest"]);const payload=closed7(parseManagedSessionRecordJson(wrapper["payloadJson"],64*1024),["toolName","input"]);ensure2(payload["toolName"]===invocation["toolName"]&&["read_file","write_file","edit"].includes(String(invocation["toolName"])));const file=historyPath(object4(payload["input"])["file_path"]);if(invocation["toolName"]!=="read_file")paths.add(file)}ensure2(paths.size>0&&isDeepStrictEqual7([...paths].sort(),preparation["paths"]));return{preparation:structuredClone(preparation),observation:readCsiFileHistoryObservation({state:body2["state"],backupDirectory:body2["backupDirectory"],retainedBackups:body2["retainedBackups"]},owner)}}__name(readCsiPreparationEvidence,"readCsiPreparationEvidence");function readCsiFileHistoryOperation(value){const operation=object4(value);closed7(operation,["kind","version","action",...operation["action"]==="prepare"?["preparationRef"]:[]]);ensure2(operation["kind"]==="csi-file-history"&&operation["version"]===1);ensure2(["bind","snapshot","prepare"].includes(String(operation["action"])));if(operation["action"]==="prepare"){const reference2=assertManagedSessionDurableRef(operation["preparationRef"],"CSI preparation");ensure2(reference2.kind==="managed-file_history"&&reference2.schemaVersion===1&&reference2.byteLength>0&&reference2.byteLength<=64*1024)}return structuredClone(operation)}__name(readCsiFileHistoryOperation,"readCsiFileHistoryOperation");function readCsiFileHistoryEnvelope(value,boot,installedContext){const body2=closed7(value,["protocolVersion","managedCsi","identity","context","installedContext","operation"]);ensure2(boot.version===5&&body2["protocolVersion"]===2&&body2["managedCsi"]===MANAGED_CSI_FILE_PROTOCOL);ensure2(isDeepStrictEqual7(body2["identity"],boot.identity)&&isDeepStrictEqual7(body2["context"],createManagedContextAttestationResponse(boot.context))&&isDeepStrictEqual7(body2["installedContext"],installedContext));readCsiNativeRequest({protocolVersion:1,requestId:"00000000-0000-4000-8000-000000000000",action:"bind",identity:boot.identity,context:body2["context"],installedContext,subject:null});return readCsiFileHistoryOperation(body2["operation"])}__name(readCsiFileHistoryEnvelope,"readCsiFileHistoryEnvelope");function readCsiFileHistoryObservation(value,owner){const body2=closed7(value,["state","backupDirectory","retainedBackups"]);const state=parseHostedFileHistoryState(body2["state"],owner);const directory=closed7(body2["backupDirectory"],["volumeDevice","volumeInode","directoryDevice","directoryInode"]);for(const value2 of Object.values(directory))decimal(value2);ensure2(directory["volumeDevice"]===directory["directoryDevice"]);ensure2(Array.isArray(body2["retainedBackups"]));const pins=new Map;let previous="";for(const candidate of body2["retainedBackups"]){const pin2=closed7(candidate,["name","device","inode","byteLength","digest","mode"]);const name=pin2["name"];ensure2(typeof name==="string"&&name.length>0&&name.length<=256&&name!=="."&&name!==".."&&!/[/\\]/.test(name)&&[...name].every(char=>char.charCodeAt(0)>31&&char.charCodeAt(0)!==127)&&name>previous);decimal(pin2["device"]);decimal(pin2["inode"]);ensure2(pin2["device"]===directory["volumeDevice"]);ensure2(Number.isSafeInteger(pin2["byteLength"])&&pin2["byteLength"]>=0&&pin2["byteLength"]<Number.MAX_SAFE_INTEGER);ensure2(Number.isSafeInteger(pin2["mode"])&&pin2["mode"]>=0&&pin2["mode"]<=4095);ensure2(typeof pin2["digest"]==="string"&&/^[0-9a-f]{64}$/.test(pin2["digest"]));pins.set(name,structuredClone(pin2));previous=name}const names=new Set;for(const snapshot of state.snapshots){ensure2(snapshot.promptId.normalize("NFC")===snapshot.promptId&&Buffer.byteLength(snapshot.promptId)<=512&&[...snapshot.promptId].every(char=>char.charCodeAt(0)>31&&(char.charCodeAt(0)<127||char.charCodeAt(0)>159)));for(const backup of Object.values(snapshot.trackedFileBackups)){ensure2(backup.failed!==true&&backup.version<Number.MAX_SAFE_INTEGER);if(backup.backupFileName!==null){ensure2(pins.has(backup.backupFileName));names.add(backup.backupFileName)}}}ensure2(names.size===pins.size);return{state,backupDirectory:structuredClone(directory),retainedBackups:[...pins.values()]}}__name(readCsiFileHistoryObservation,"readCsiFileHistoryObservation");function decimal(value){ensure2(typeof value==="string"&&/^(?:0|[1-9][0-9]*)$/.test(value)&&value.length<=20&&BigInt(value)<=18446744073709551615n)}__name(decimal,"decimal");function object4(value){ensure2(value!==null&&typeof value==="object"&&!Array.isArray(value));return value}__name(object4,"object");function closed7(value,keys){const body2=object4(value);ensure2(isDeepStrictEqual7(Object.keys(body2).sort(),[...keys].sort()));return body2}__name(closed7,"closed");function ensure2(condition){if(!condition)throw new Error("Invalid private CSI file history.")}__name(ensure2,"ensure");var CONFIG2=`sha256:${createHash10("sha256").update("csi-files-retirement-tools/1\0csi-files-retirement-policy/1").digest("hex")}`;var HistoryCapacityError=class extends Error{static{__name(this,"HistoryCapacityError")}};function historyFits(request,before,promptId,paths){const projected=structuredClone(before);const snapshots=projected.state.snapshots;const newPrompt=snapshots.at(-1)?.promptId!==promptId;if(newPrompt&&snapshots.length>=100)return false;const tracked=new Set([...Object.keys(projected.state.files),...snapshots.flatMap(snapshot2=>Object.keys(snapshot2.trackedFileBackups)),...paths]);if(newPrompt)snapshots.push({promptId,timestamp:"9999-12-31T23:59:59.999Z",trackedFileBackups:{}});const snapshot=snapshots.at(-1);snapshot.trackedFileBackups=Object.assign(Object.create(null),snapshot.trackedFileBackups);projected.state.files=Object.assign(Object.create(null),projected.state.files);for(const file of tracked){if(newPrompt||!Object.hasOwn(snapshot.trackedFileBackups,file)){const name=`${"f".repeat(36)}@v${Number.MAX_SAFE_INTEGER}`;snapshot.trackedFileBackups[file]={backupFileName:name,version:Number.MAX_SAFE_INTEGER-1,backupTime:"9999-12-31T23:59:59.999Z"};projected.retainedBackups.push({name,device:projected.backupDirectory.volumeDevice,inode:"18446744073709551615",byteLength:Number.MAX_SAFE_INTEGER-1,digest:"f".repeat(64),mode:4095})}projected.state.files[file]={digest:`sha256:${"f".repeat(64)}`,mode:4095}}return Buffer.byteLength(JSON.stringify({...request,observation:projected}))+1024<=64*1024}__name(historyFits,"historyFits");async function startManagedCsiFileWorker(bootDocument){const boot=parseManagedCsiFileBoot(bootDocument);const pod={uid:process.env["QWEN_POD_UID"],namespace:process.env["QWEN_POD_NAMESPACE"],nodeName:process.env["QWEN_NODE_NAME"]};validateManagedCsiPodIdentity(pod,boot.storage.namespace);Object.freeze(pod);const mount=new ManagedCsiMount(boot.context.mountRoot,boot.storage.diskSerial);const installations=new ManagedContextInstallations(boot.context);let closed8=false;let retirementId;let composition;let binding;let bindIdentity;let historyFailed=false;let preparingHistory=false;let activeExecutions=0;let observationTail=Promise.resolve();const preparations=new Map;const operations=new Set;const track=__name(operation=>{operations.add(operation);void operation.then(()=>operations.delete(operation),()=>operations.delete(operation));return operation},"track");const canInstall=__name(()=>!closed8&&!historyFailed&&retirementId===void 0&&mount.isAvailable,"canInstall");const executor=new ManagedToolExecutor(async reference2=>canInstall()&&reference2.sessionId===boot.identity.sessionId?composition?.tools:void 0);const failHistory=__name(()=>{historyFailed=true;void executor.close().catch(()=>{})},"failHistory");const app=(0,import_express.default)();app.disable("x-powered-by");const refuse=__name((res,code="managed_csi_identity_conflict")=>res.status(409).json({code,error:"Managed CSI file context is unavailable or conflicts."}),"refuse");const middleware=[managedRuntimeNoStore,authorizeManagedRuntime(boot.context),nameManagedRuntimeIncarnation(boot.context),import_express.default.json({inflate:false,limit:16*1024,strict:true,type:"application/json",verify:__name((_req,_res,bytes)=>{try{parseManagedCsiFileJson(bytes,16*1024)}catch{throw new SyntaxError("Invalid CSI file request.")}},"verify")})];app.post(`${MANAGED_CSI_FILE_PREFIX}/context-attest`,...middleware,async(req,res)=>{try{const outcome=checkManagedContextAttestation(readManagedCsiFileContext(req.body,boot),boot.context);if(outcome.status!==200){res.status(outcome.status).json({code:outcome.code,error:"Managed CSI file identity conflicts."});return}await mount.observe();if(closed8||!mount.isAvailable)throw new Error;res.json(wrapManagedCsiFileContext(boot,outcome.body))}catch{refuse(res)}},handleManagedRuntimeJsonError);app.post(`${MANAGED_CSI_FILE_PREFIX}/context`,...middleware,async(req,res)=>{try{const context=readManagedCsiFileContext(req.body,boot);if(!context||typeof context!=="object"||!("sessionId"in context)||context.sessionId!==boot.identity.sessionId||!("binding"in context)||!context.binding||typeof context.binding!=="object"||!("cwdRelative"in context.binding)||context.binding.cwdRelative!=="."||!("contextConfigRef"in context.binding)||context.binding.contextConfigRef!==CONFIG2)throw new Error;if(boot.version===5)readCsiNativeRequest({protocolVersion:1,requestId:"00000000-0000-4000-8000-000000000000",action:"bind",identity:boot.identity,context:createManagedContextAttestationResponse(boot.context),installedContext:context,subject:null});if(!canInstall()){refuse(res,"managed_context_unavailable");return}const outcome=await installations.install(context,async()=>{try{await mount.observe();return canInstall()}catch{return false}},canInstall);if(!canInstall()){refuse(res,"managed_context_unavailable");return}if(outcome.status!==200){res.status(outcome.status).json({code:outcome.code,error:"Managed CSI file context conflicts."});return}res.json(wrapManagedCsiFileContext(boot,outcome.body))}catch{refuse(res)}},handleManagedRuntimeJsonError);app.post(`${MANAGED_CSI_FILE_PREFIX}/attest`,...middleware,async(req,res)=>{try{validateManagedCsiFileAttestationRequest(req.body,boot);const observation=await mount.observe();if(closed8||!mount.isAvailable)throw new Error;const response={protocolVersion:2,managedCsi:MANAGED_CSI_FILE_PROTOCOL,identity:boot.identity,context:createManagedContextAttestationResponse(boot.context),storage:boot.storage,pod,mount:observation};validateManagedCsiFileAttestationResponse(response,boot,pod);res.json(response)}catch{refuse(res)}},handleManagedRuntimeJsonError);app.post(CSI_FILE_HISTORY_PATH,...middleware,async(req,res)=>{try{if(boot.version!==5||closed8)throw new Error;if(historyFailed){refuse(res,"managed_csi_history_retirement_required");return}const installed=installations.installation(boot.identity.sessionId);if(!installed)throw new Error;const operation=readCsiFileHistoryEnvelope(req.body,boot,installed);const fingerprint3=JSON.stringify(installed);let observation;if(operation.action==="prepare"){if(!canInstall()||!binding||fingerprint3!==bindIdentity)throw new Error;const originalBinding=binding;const ref2=operation.preparationRef;let prepared=preparations.get(ref2.resourceId);if(prepared&&!isDeepStrictEqual8(prepared.reference,ref2))throw new Error;if(!prepared){let beforePreparation;const pending=track(observationTail.catch(()=>void 0).then(async()=>{preparingHistory=true;await originalBinding;if(!canInstall()||!composition||activeExecutions)throw new Error;const current=readCsiPreparationEvidence(await readCurrentCsiNative(boot,installed,"prepare",ref2));if(!canInstall())throw new Error;const before=await composition.observe();if(!isDeepStrictEqual8(current.observation,readCsiFileHistoryObservation({state:before.history,...before.storage},boot.identity.sessionId))||!canInstall())throw new Error;if(!historyFits(req.body,current.observation,current.preparation.promptId,current.preparation.paths))throw new HistoryCapacityError;beforePreparation=current.observation;await composition.history.prepare(current.preparation.promptId,current.preparation.paths);const after=await composition.observe();return readCsiFileHistoryObservation({state:after.history,...after.storage},boot.identity.sessionId)}).catch(async error=>{if(beforePreparation){try{const after=await composition.observe();if(!isDeepStrictEqual8(beforePreparation,readCsiFileHistoryObservation({state:after.history,...after.storage},boot.identity.sessionId)))failHistory()}catch{failHistory()}}if(!historyFailed)preparations.delete(ref2.resourceId);throw error}).finally(()=>{preparingHistory=false}));prepared={reference:structuredClone(ref2),observation:pending};preparations.set(ref2.resourceId,prepared);observationTail=pending}observation=await prepared.observation}else if(operation.action==="bind"){if(!canInstall())throw new Error;if(binding&&fingerprint3!==bindIdentity)throw new Error;if(!binding){bindIdentity=fingerprint3;binding=track(Promise.resolve().then(async()=>{await readCurrentCsiNative(boot,installed,"bind",null);if(!canInstall())throw new Error;composition=await composeManagedCsiFiles({mount,ownerSessionId:boot.identity.sessionId,runtimeSessionId:boot.identity.sessionId,profile:boot.identity.profile,capabilityDigest:boot.identity.capabilityDigest});if(!canInstall())throw new Error;const observed=await composition.observe();const result=readCsiFileHistoryObservation({state:observed.history,...observed.storage},boot.identity.sessionId);if(result.state.snapshots.length||Object.keys(result.state.files).length||result.retainedBackups.length)throw new Error;return result}).catch(error=>{if(!composition&&canInstall()){binding=void 0;bindIdentity=void 0}throw error}))}observation=await binding}else{if(!binding||fingerprint3!==bindIdentity)throw new Error;const originalBinding=binding;const pending=track(observationTail.catch(()=>void 0).then(async()=>{await originalBinding;if(closed8||historyFailed||!composition)throw new Error;const observed=await composition.observe();return readCsiFileHistoryObservation({state:observed.history,...observed.storage},boot.identity.sessionId)}));observationTail=pending;observation=await pending}if(closed8||historyFailed||operation.action!=="snapshot"&&!canInstall())throw new Error;const response={...req.body,observation};if(Buffer.byteLength(JSON.stringify(response))>64*1024){if(operation.action==="prepare")failHistory();throw new HistoryCapacityError}res.json(response)}catch(error){refuse(res,historyFailed?"managed_csi_history_retirement_required":error instanceof HistoryCapacityError?"managed_csi_history_capacity_exceeded":"managed_csi_history_unavailable")}},handleManagedRuntimeJsonError);app.post(`${MANAGED_CSI_FILE_PREFIX}/execute`,...middleware,async(req,res)=>{try{if(historyFailed){refuse(res,"managed_csi_history_retirement_required");return}const request=readCsiNativeRequest(req.body);const installed=installations.installation(boot.identity.sessionId);if(boot.version!==5||request.action!=="execute"||typeof request.subject!=="string"||!installed||!binding||bindIdentity!==JSON.stringify(installed)||!isDeepStrictEqual8(request.identity,boot.identity)||!isDeepStrictEqual8(request.context,createManagedContextAttestationResponse(boot.context))||!isDeepStrictEqual8(request.installedContext,installed)||preparingHistory||!canInstall())throw new Error;const originalBinding=binding;const result=await track(Promise.resolve().then(async()=>{await originalBinding;if(!canInstall()||!composition)throw new Error;const current=await readCurrentCsiNative(boot,installed,"execute",request.subject);if(!canInstall())throw new Error;const evidence=current.evidence;const reference2=evidence["executionReference"];const inputRef=reference2["inputRef"];const input=evidence["resources"].find(resource=>resource.reference.resourceId===inputRef.resourceId);if(!input)throw new Error;const wrapper=parseManagedCsiFileJson(Buffer.from(input.bytesBase64,"base64"),64*1024);const payloadJson=wrapper["payloadJson"];if(typeof payloadJson!=="string")throw new Error;const payload=parseManagedCsiFileJson(Buffer.from(payloadJson),64*1024);const toolName=payload["toolName"];if(!["read_file","write_file","edit"].includes(String(toolName))||reference2["argsDigest"]!==`sha256:${createHash10("sha256").update(payloadJson).digest("hex")}`||!canInstall())throw new Error;const preparedRef=evidence["preparedRef"];if(preparedRef!==null){const preparedResource=evidence["resources"].find(resource=>resource.reference.resourceId===preparedRef.resourceId);if(!preparedResource)throw new Error;const preparedBody=parseManagedCsiFileJson(Buffer.from(preparedResource.bytesBase64,"base64"),64*1024);const preparation=preparedBody["preparation"];const intentRef=preparation["intentRef"];const saved=preparations.get(intentRef.resourceId);const invocation=preparation["invocations"].find(item=>item["executionCallId"]===request.subject);if(preparedBody["schemaVersion"]!==2||preparedBody["profile"]!==boot.identity.profile||preparedBody["runtimeSessionId"]!==boot.identity.sessionId||preparation["stage"]!=="prepared"||preparation["promptId"]!==reference2["promptId"]||preparation["batchId"]!==reference2["batchId"]||!saved||!invocation||invocation["toolName"]!==toolName||invocation["requestDigest"]!==reference2["argsDigest"]||["callId","functionCallId","partIndex","ordinal","inputRef","toolDefinitionRef"].some(field=>!isDeepStrictEqual8(invocation[field],reference2[field]))||!isDeepStrictEqual8(saved.reference,intentRef)||!isDeepStrictEqual8(await saved.observation,readCsiFileHistoryObservation({state:preparedBody["state"],backupDirectory:preparedBody["backupDirectory"],retainedBackups:preparedBody["retainedBackups"]},boot.identity.sessionId))||!canInstall())throw new Error}else if(toolName!=="read_file"){throw new Error}if(preparingHistory)throw new Error;activeExecutions++;try{return await executor.execute({sessionId:reference2["sessionId"],promptId:reference2["promptId"],callId:reference2["callId"],argsDigest:reference2["argsDigest"]},toolName,payload["input"])}finally{activeExecutions--}}));const response={...request,state:"settled",result};if(closed8||Buffer.byteLength(JSON.stringify(response))>MANAGED_RUNTIME_TOOL_RESULT_BODY_LIMIT_BYTES+16*1024)throw new Error;res.json(response)}catch{refuse(res,"managed_csi_execution_unavailable")}},handleManagedRuntimeJsonError);app.post(`${MANAGED_CSI_FILE_PREFIX}/drain`,...middleware,async(req,res)=>{try{const request=readManagedCsiFileDrain(req.body,boot,pod);if(closed8||retirementId!==void 0&&retirementId!==request.retirementId||request.operation==="status"&&retirementId===void 0)throw new Error;if(request.operation==="seal"){retirementId??=request.retirementId;executor.sealAdmission(request.retirementId)}await Promise.allSettled([...operations]);res.json({protocolVersion:2,managedCsi:MANAGED_CSI_FILE_PROTOCOL,identity:boot.identity,retirementId:request.retirementId,context:createManagedContextAttestationResponse(boot.context),storage:boot.storage,pod,state:"DRAINING",workState:"BLOCKED",pendingStarts:0,pendingInvocations:0,blockers:["file-admission-unavailable",...binding?["retained-history-bound"]:[],...historyFailed?["history-prepare-failed"]:[]].sort()})}catch{refuse(res,"managed_csi_drain_conflict")}},handleManagedRuntimeJsonError);const server=createServer(ownedManagedRuntimeRouteGate(app,[...MANAGED_CSI_FILE_ROUTES,...boot.version===5?[{method:"POST",path:CSI_FILE_HISTORY_PATH},{method:"POST",path:`${MANAGED_CSI_FILE_PREFIX}/execute`}]:[]]));server.maxHeadersCount=32;server.headersTimeout=5e3;server.requestTimeout=5e3;server.keepAliveTimeout=1e3;let closing;const close=__name(()=>{closed8=true;closing??=(async()=>{const results=await Promise.allSettled([new Promise((resolve,reject)=>{if(!server.listening){resolve();return}server.close(error=>error?reject(error):resolve());server.closeAllConnections()})]);const joined=await Promise.allSettled([...operations]);const executed=await Promise.allSettled([executor.close()]);preparations.clear();const retained=await Promise.allSettled([composition?composition.close():mount.close()]);const errors=[...results,...joined,...executed,...retained].flatMap(result=>result.status==="rejected"?[result.reason]:[]);if(errors.length)throw new AggregateError(errors,"Managed CSI file worker close failed.")})();return closing},"close");try{await mount.observe();if(!mount.isAvailable)throw new Error("Managed CSI mount is unavailable.");await new Promise((resolve,reject)=>{const onError=__name(error=>{server.off("listening",onListening);reject(error)},"onError");const onListening=__name(()=>{server.off("error",onError);resolve()},"onListening");server.once("error",onError);server.once("listening",onListening);server.listen(43190,"0.0.0.0")});const address=server.address();if(!address)throw new Error("Managed Runtime worker listener is unavailable.");return{ready:createManagedCsiFileReady(boot,address.port),close}}catch(error){try{await close()}catch(cleanup){throw new AggregateError([error,cleanup],"Managed CSI file worker startup failed.")}throw error}}__name(startManagedCsiFileWorker,"startManagedCsiFileWorker");init_esbuild_shims();var import_express2=__toESM(require_express(),1);var MANAGED_CSI_ATTEST_ROUTE=Object.freeze({method:"POST",path:MANAGED_CSI_ATTEST_PATH});var MANAGED_CSI_DRAIN_ROUTE=Object.freeze({method:"POST",path:MANAGED_CSI_DRAIN_PATH});var MANAGED_CSI_ACK_ROUTE=Object.freeze({method:"POST",path:MANAGED_CSI_ACK_PATH});function registerManagedCsiAckRoute(app,boot,executor){const pod={uid:process.env["QWEN_POD_UID"],namespace:process.env["QWEN_POD_NAMESPACE"],nodeName:process.env["QWEN_NODE_NAME"]};validateManagedCsiPodIdentity(pod,boot.storage.namespace);app.post(MANAGED_CSI_ACK_PATH,managedRuntimeNoStore,authorizeManagedRuntime(boot.context),import_express2.default.json({inflate:false,limit:MANAGED_CSI_ACK_LIMIT_BYTES,strict:true,type:"application/json",verify:__name((_req,_res,bytes)=>{try{parseManagedCsiAckJson(bytes)}catch{throw new ManagedCsiAckRequestError(400)}},"verify")}),(req,res)=>{try{const request=parseManagedCsiAckRequest(req.body,boot,pod);const confirmed=executor.acknowledgeOriginalCsi(request,boot,pod);res.type("application/json").send(confirmed.json)}catch(error){if(!(error instanceof ManagedCsiAckRequestError))throw error;res.status(error.status).json({code:"managed_csi_ack_conflict",error:"Managed CSI acknowledgement conflicts."})}},(error,req,res,next)=>{if(error?.type==="entity.verify.failed"){res.status(400).json({code:"managed_csi_ack_conflict",error:"Managed CSI acknowledgement conflicts."});return}handleManagedRuntimeJsonError(error,req,res,next)})}__name(registerManagedCsiAckRoute,"registerManagedCsiAckRoute");function registerManagedCsiDrainRoute(app,boot,executor){const pod={uid:process.env["QWEN_POD_UID"],namespace:process.env["QWEN_POD_NAMESPACE"],nodeName:process.env["QWEN_NODE_NAME"]};validateManagedCsiPodIdentity(pod,boot.storage.namespace);app.post(MANAGED_CSI_DRAIN_PATH,managedRuntimeNoStore,authorizeManagedRuntime(boot.context),managedRuntimeJsonBody(16*1024),(req,res)=>{try{const request=parseManagedCsiDrainRequest(req.body,boot,pod);if(request.operation==="seal")executor.sealAdmission(request.retirementId);res.json({protocolVersion:1,managedCsi:MANAGED_CSI_PROTOCOL,retirementId:request.retirementId,context:createManagedContextAttestationResponse(boot.context),storage:boot.storage,pod,...executor.getDrainObservation(request.retirementId)})}catch(error){if(!(error instanceof ManagedCsiDrainRequestError)&&!(error instanceof ManagedToolConflictError))throw error;res.status(error instanceof ManagedCsiDrainRequestError?error.status:409).json({code:"managed_csi_drain_conflict",error:"Managed CSI drain request conflicts."})}},handleManagedRuntimeJsonError)}__name(registerManagedCsiDrainRoute,"registerManagedCsiDrainRoute");function registerManagedCsiAttestationRoute(app,boot,mount){const pod={uid:process.env["QWEN_POD_UID"],namespace:process.env["QWEN_POD_NAMESPACE"],nodeName:process.env["QWEN_NODE_NAME"]};validateManagedCsiPodIdentity(pod,boot.storage.namespace);app.post(MANAGED_CSI_ATTEST_PATH,managedRuntimeNoStore,authorizeManagedRuntime(boot.context),managedRuntimeJsonBody(16*1024),async(req,res)=>{try{validateManagedCsiAttestationRequest(req.body,boot)}catch{res.status(409).json({code:"managed_csi_identity_conflict",error:"Managed CSI identity conflicts."});return}try{const observation=await mount.observe();if(!mount.isAvailable)throw new Error;const response={protocolVersion:1,managedCsi:MANAGED_CSI_PROTOCOL,context:createManagedContextAttestationResponse(boot.context),storage:boot.storage,pod,mount:observation};validateManagedCsiAttestationResponse(response,boot,pod);res.status(200).json(response)}catch{res.status(409).json({code:"managed_csi_mount_unavailable",error:"Managed CSI mount is unavailable."})}},handleManagedRuntimeJsonError)}__name(registerManagedCsiAttestationRoute,"registerManagedCsiAttestationRoute");var MANAGED_RUNTIME_WORKER_BOOT_LIMIT_BYTES=32*1024;var MANAGED_RUNTIME_WORKER_BOOT_TIMEOUT_MS=3e4;var INVALID_BOOT_MESSAGE2="Managed Runtime worker boot payload is invalid.";var BOOT_KEYS3=Object.freeze(["capabilityDigest","epoch","isolationClass","leaseId","provisionRequestId","runtimeIncarnation","runtimeInstanceId","tenantId","token","type","version","workspaceCwd","workspaceGeneration","workspaceId"]);function isExactBoot(value){if(!value||typeof value!=="object"||Array.isArray(value))return false;const keys=Object.keys(value).sort();if(keys.length!==BOOT_KEYS3.length||!keys.every((key,index)=>key===BOOT_KEYS3[index])){return false}const boot=value;return boot["type"]==="boot"&&boot["version"]===1}__name(isExactBoot,"isExactBoot");async function collectManagedRuntimeWorkerBoot(input){const chunks=[];let size=0;for await(const chunk of input){const bytes=Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk);size+=bytes.byteLength;if(size>MANAGED_RUNTIME_WORKER_BOOT_LIMIT_BYTES){throw new Error(INVALID_BOOT_MESSAGE2)}chunks.push(bytes)}return Buffer.concat(chunks)}__name(collectManagedRuntimeWorkerBoot,"collectManagedRuntimeWorkerBoot");function parseWorkerBoot(document){let parsed;try{parsed=JSON.parse(document.toString("utf8"))}catch{throw new Error(INVALID_BOOT_MESSAGE2)}if(isExactBoot(parsed)){if(parsed.capabilityDigest===CSI_FILES_RETIREMENT_CAPABILITY_DIGEST)throw new Error(INVALID_BOOT_MESSAGE2);return parsed}try{new TextDecoder("utf-8",{fatal:true}).decode(document);const boot=parseManagedContextBoot(parsed);if(boot.capabilityDigest===CSI_FILES_RETIREMENT_CAPABILITY_DIGEST)throw new Error(INVALID_BOOT_MESSAGE2);return boot}catch{throw new Error(INVALID_BOOT_MESSAGE2)}}__name(parseWorkerBoot,"parseWorkerBoot");async function readManagedRuntimeWorkerBoot(input){return parseWorkerBoot(await readBootDocument(input))}__name(readManagedRuntimeWorkerBoot,"readManagedRuntimeWorkerBoot");async function readBootDocument(input){let timeout;const timedOut=new Promise((_,reject)=>{timeout=setTimeout(()=>{input.destroy();reject(new Error(INVALID_BOOT_MESSAGE2))},MANAGED_RUNTIME_WORKER_BOOT_TIMEOUT_MS);timeout.unref()});try{return await Promise.race([collectManagedRuntimeWorkerBoot(input),timedOut])}finally{if(timeout)clearTimeout(timeout)}}__name(readBootDocument,"readBootDocument");async function startManagedRuntimeAttestationWorker(bootDocument,capturePublisher,remotePublishers,containerMode=false){if(bootDocument.version===4||bootDocument.version===5){if(!containerMode||capturePublisher||remotePublishers)throw new Error(INVALID_BOOT_MESSAGE2);return startManagedCsiFileWorker(bootDocument)}const resolved=bootDocument.version===3?parseManagedCsiBoot(bootDocument):bootDocument;const csiBoot=resolved.version===3?resolved:void 0;const boot=resolved.version===3?resolved.context:resolved;if(boot.capabilityDigest===CSI_FILES_RETIREMENT_CAPABILITY_DIGEST||csiBoot!==void 0&&!containerMode||containerMode&&csiBoot===void 0&&(boot.version!==1||boot.isolationClass!=="session")){throw new Error(INVALID_BOOT_MESSAGE2)}const app=(0,import_express3.default)();app.disable("x-powered-by");const csiMount=csiBoot?new ManagedCsiMount(csiBoot.context.mountRoot,csiBoot.storage.diskSerial):void 0;let executor;try{if(csiBoot&&csiMount){await csiMount.observe();registerManagedCsiAttestationRoute(app,csiBoot,csiMount)}if(boot.version===2){executor=registerManagedContextRoutes(app,boot,capturePublisher,remotePublishers,csiMount)}else{registerManagedRuntimeAttestationRoute(app,boot);const ledger=managedRuntimeLedgerFromEnvironment(boot.runtimeIncarnation);ledger?.watch();executor=ManagedToolExecutor.forWorkspace(boot.workspaceCwd,boot.runtimeInstanceId,{ledger});registerManagedRuntimeToolRoutes(app,boot,executor);const mount=new ManagedContextMount(boot.workspaceCwd);registerManagedRuntimeProviderRoute(app,boot,executor,async()=>{const directory=await mount.resolve("");return directory===void 0?void 0:{directory,workspaceRoot:directory,preapproved:false}})}if(csiBoot){registerManagedCsiDrainRoute(app,csiBoot,executor);registerManagedCsiAckRoute(app,csiBoot,executor)}}catch(error){return closeCsiMountAfterError(csiMount,error)}const server=createServer2(ownedManagedRuntimeRouteGate(app,boot.version===2?capturePublisher||remotePublishers||boot.capabilityDigest===WORKSPACE_CAPABILITY_DIGEST?[...MANAGED_CONTEXT_WORKER_ROUTES,...csiBoot?[MANAGED_CSI_ATTEST_ROUTE,MANAGED_CSI_DRAIN_ROUTE,MANAGED_CSI_ACK_ROUTE]:[],...MANAGED_TOOL_RESULT_ROUTES,...remotePublishers?[MANAGED_SHELL_PUBLISHER_ROUTE]:[],...!capturePublisher&&boot.capabilityDigest===WORKSPACE_CAPABILITY_DIGEST?[PUBLICATION_INSTALL_ROUTE]:[]]:[...MANAGED_CONTEXT_WORKER_ROUTES,...csiBoot?[MANAGED_CSI_ATTEST_ROUTE,MANAGED_CSI_DRAIN_ROUTE,MANAGED_CSI_ACK_ROUTE]:[]]:[...OWNED_MANAGED_RUNTIME_ROUTES,MANAGED_RUNTIME_PROVIDER_ROUTE]));server.maxHeadersCount=32;server.headersTimeout=5e3;server.requestTimeout=5e3;server.keepAliveTimeout=1e3;try{await new Promise((resolve,reject)=>{const onError=__name(error=>{server.off("listening",onListening);reject(error)},"onError");const onListening=__name(()=>{server.off("error",onError);resolve()},"onListening");server.once("error",onError);server.once("listening",onListening);server.listen(containerMode?43190:0,containerMode?"0.0.0.0":"127.0.0.1")})}catch(error){return closeCsiMountAfterError(csiMount,error)}const address=server.address();if(!address){await new Promise(resolve=>server.close(()=>resolve()));return closeCsiMountAfterError(csiMount,new Error("Managed Runtime worker listener is unavailable."))}const ready=boot.version===2?createManagedContextReady(boot,address.port):Object.freeze({type:"ready",version:1,runtimeInstanceId:boot.runtimeInstanceId,runtimeIncarnation:boot.runtimeIncarnation,leaseId:boot.leaseId,epoch:boot.epoch,url:`http://127.0.0.1:${address.port}`});let closing;return{ready,close:__name(()=>{closing??=(async()=>{const errors=[];try{await executor.close()}catch(error){errors.push(error)}const cleanup=await Promise.allSettled([new Promise((resolve,reject)=>{server.close(error=>error?reject(error):resolve());server.closeAllConnections()}),csiMount?.close()]);errors.push(...cleanup.flatMap(result=>result.status==="rejected"?[result.reason]:[]));if(errors.length===1)throw errors[0];if(errors.length>1)throw new AggregateError(errors,errors[0]instanceof Error?errors[0].message:"Managed Runtime worker shutdown failed.",{cause:errors[0]})})();return closing},"close")}}__name(startManagedRuntimeAttestationWorker,"startManagedRuntimeAttestationWorker");async function closeCsiMountAfterError(mount,error){try{await mount?.close()}catch(cleanupError){throw new AggregateError([error,cleanupError],error instanceof Error?error.message:"Managed Runtime worker startup failed.",{cause:error})}throw error}__name(closeCsiMountAfterError,"closeCsiMountAfterError");async function readManagedRuntimeContainerBoot(bootPath){if(!path7.isAbsolute(bootPath))throw new Error(INVALID_BOOT_MESSAGE2);const input=createReadStream2(bootPath);try{const document=await readBootDocument(input);const parsed=JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(document));if(parsed&&typeof parsed==="object"&&"version"in parsed&&(parsed.version===4||parsed.version===5)){return parseManagedCsiFileBoot(parseManagedCsiFileJson(document,MANAGED_RUNTIME_WORKER_BOOT_LIMIT_BYTES))}if(parsed&&typeof parsed==="object"&&"version"in parsed&&parsed.version===3){const boot2=parseManagedCsiBoot(parsed);if(boot2.context.capabilityDigest===CSI_FILES_RETIREMENT_CAPABILITY_DIGEST)throw new Error(INVALID_BOOT_MESSAGE2);return boot2}const boot=parseWorkerBoot(document);if(boot.version!==1||boot.isolationClass!=="session"){throw new Error(INVALID_BOOT_MESSAGE2)}return boot}catch{throw new Error(INVALID_BOOT_MESSAGE2)}finally{input.destroy()}}__name(readManagedRuntimeContainerBoot,"readManagedRuntimeContainerBoot");async function runManagedRuntimeAttestationWorker(containerBootPath){if(typeof process.send==="function"){scrubAndReportInheritedLoaderEnv(process.env,"qwen","Managed Runtime worker")}let boot;try{boot=containerBootPath!==void 0?await readManagedRuntimeContainerBoot(containerBootPath):await readManagedRuntimeWorkerBoot(process.stdin)}catch(error){if(containerBootPath===void 0)throw error;process.stderr.write(`${INVALID_BOOT_MESSAGE2}
|
|
4
4
|
`);process.exitCode=1;return}const contextBoot=boot.version===3||boot.version===4||boot.version===5?boot.context:boot;const worker=await startManagedRuntimeAttestationWorker(boot,void 0,contextBoot.version===2&&contextBoot.capabilityDigest===WORKSPACE_CAPABILITY_DIGEST?new ManagedShellPublisherRegistry:void 0,containerBootPath!==void 0);await new Promise((resolve,reject)=>{let closing=false;const close=__name(()=>{if(closing)return;closing=true;void worker.close().then(()=>{if(process.connected)process.disconnect();resolve()},reject)},"close");const closeAfterOutputFailure=__name(()=>{process.exitCode=1;close()},"closeAfterOutputFailure");process.once("SIGINT",close);process.once("SIGTERM",close);if(typeof process.send==="function"){process.channel?.unref();process.once("disconnect",close);if(!process.connected)close()}process.stdout.once("error",closeAfterOutputFailure);process.stdout.write(`${JSON.stringify(worker.ready)}
|
|
5
5
|
`,error=>{if(error)closeAfterOutputFailure()})})}__name(runManagedRuntimeAttestationWorker,"runManagedRuntimeAttestationWorker");export{readManagedRuntimeContainerBoot,readManagedRuntimeWorkerBoot,runManagedRuntimeAttestationWorker,startManagedRuntimeAttestationWorker};
|
|
6
6
|
/**
|