gerege-cli 0.26.5 → 0.26.6
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/README.md +8 -8
- package/chunks/{MaxSizedBox-VMVLMS4X.js → MaxSizedBox-QCIXIS4P.js} +1 -1
- package/chunks/{StandaloneSessionPicker-UNORCVYY.js → StandaloneSessionPicker-BAFAIRT7.js} +1 -1
- package/chunks/{acp-subagent-executor-623ZUTJT.js → acp-subagent-executor-TPVXURLW.js} +1 -1
- package/chunks/{acpAgent-MTTDTK2C.js → acpAgent-67UN66PB.js} +3 -3
- package/chunks/{advisor-ANUGICJ5.js → advisor-SAXMI4QZ.js} +1 -1
- package/chunks/{agent-GNCQDICJ.js → agent-KV7BXY6C.js} +1 -1
- package/chunks/{agent-headless-OPUXAXQM.js → agent-headless-FQX3JGG6.js} +1 -1
- package/chunks/{agent-host-client-K6GRPTFD.js → agent-host-client-L5EHC4AC.js} +1 -1
- package/chunks/{agent-host-connections-MF3YBZU2.js → agent-host-connections-EDBMCVQF.js} +1 -1
- package/chunks/{anthropicContentGenerator-OK4PFE5Y.js → anthropicContentGenerator-V7TX2NXP.js} +1 -1
- package/chunks/{autofix-pr-MABTGEHZ.js → autofix-pr-WP34NYHL.js} +1 -1
- package/chunks/{batch-V2NJT3M5.js → batch-XFVQ4BLM.js} +1 -1
- package/chunks/{bridge-BJQ627CX.js → bridge-AE7AFEXB.js} +1 -1
- package/chunks/{channel-settings-store-4JMCI4UR.js → channel-settings-store-X63P5OVT.js} +1 -1
- package/chunks/{chunk-ZN57TOVA.js → chunk-2DU2WMTL.js} +1 -1
- package/chunks/{chunk-Z5XENA4A.js → chunk-2JGTWRZJ.js} +8 -7
- package/chunks/{chunk-MTW3A3KT.js → chunk-2LWJGXTW.js} +1 -1
- package/chunks/{chunk-OCBJCZC2.js → chunk-2N3NBTYJ.js} +1 -1
- package/chunks/{chunk-WI4UMN3Q.js → chunk-2TAJ5STJ.js} +1 -1
- package/chunks/{chunk-EIILQ6KT.js → chunk-32XHDDIA.js} +1 -1
- package/chunks/{chunk-FNXO5KWB.js → chunk-34HC2AXI.js} +2 -2
- package/chunks/{chunk-2X3UF2CF.js → chunk-3W32X2DH.js} +1 -1
- package/chunks/{chunk-CKZRJP4F.js → chunk-4ME3BUJK.js} +1 -1
- package/chunks/{chunk-NVSKOSFG.js → chunk-4NDJKNN6.js} +1 -1
- package/chunks/{chunk-BRPJ5EHA.js → chunk-5EXL4TKQ.js} +1 -1
- package/chunks/{chunk-3XBJYUWP.js → chunk-65ME4BOH.js} +1 -1
- package/chunks/{chunk-TQTIEK2W.js → chunk-7453BHJO.js} +1 -1
- package/chunks/{chunk-HSYBIGMS.js → chunk-76FSYQTG.js} +1 -1
- package/chunks/{chunk-FNB3DPQZ.js → chunk-7RNOS7R4.js} +1 -1
- package/chunks/{chunk-H57IX45A.js → chunk-AEKEZRIU.js} +1 -1
- package/chunks/{chunk-CXGGC4NO.js → chunk-AEZYXPFS.js} +1 -1
- package/chunks/{chunk-NGOIJH7K.js → chunk-AFO5ER23.js} +1 -1
- package/chunks/{chunk-UY2ET2AL.js → chunk-AYVCT5FF.js} +1 -1
- package/chunks/{chunk-QOYRDEXR.js → chunk-B37YY4XU.js} +1 -1
- package/chunks/{chunk-IDUGQMTP.js → chunk-BAUMVH4Q.js} +1 -1
- package/chunks/{chunk-CAPG7UVH.js → chunk-BCI62WSL.js} +1 -1
- package/chunks/{chunk-USJFJZ23.js → chunk-BGELKSQ4.js} +1 -1
- package/chunks/{chunk-6X73W4TL.js → chunk-BHIDG6VZ.js} +1 -1
- package/chunks/{chunk-26ISBUM7.js → chunk-BPFFRPWE.js} +6 -6
- package/chunks/{chunk-YGHM5CDT.js → chunk-BQZF3UKI.js} +1 -1
- package/chunks/{chunk-3NQESE5K.js → chunk-CBE6ZIHU.js} +1 -1
- package/chunks/{chunk-DEMXCA3K.js → chunk-CF6SZJNP.js} +1 -1
- package/chunks/{chunk-2VCDJ6UF.js → chunk-CGDFZEER.js} +1 -1
- package/chunks/{chunk-3WQPUP5U.js → chunk-CUP2TNJK.js} +1 -1
- package/chunks/{chunk-2IGE2K5V.js → chunk-DA6LOBSB.js} +1 -1
- package/chunks/{chunk-HFV6CQWE.js → chunk-EFIRES46.js} +1 -1
- package/chunks/{chunk-E5YRAQXM.js → chunk-EKRUF347.js} +1 -1
- package/chunks/{chunk-KN27BFXM.js → chunk-ELDZ4MNL.js} +1 -1
- package/chunks/{chunk-ADTFKUH2.js → chunk-ET5M5WFN.js} +1 -1
- package/chunks/{chunk-IBYFSHBB.js → chunk-EXIFPXMB.js} +1 -1
- package/chunks/{chunk-IA4K4PGK.js → chunk-EYPLBTMI.js} +1 -1
- package/chunks/{chunk-DTTC4ZKY.js → chunk-FEP6W4NJ.js} +1 -1
- package/chunks/{chunk-FHBGTZ4K.js → chunk-FKL3V5BO.js} +1 -1
- package/chunks/{chunk-Q5E5SOY2.js → chunk-FKZ46GKL.js} +1 -1
- package/chunks/{chunk-OPYGNTZP.js → chunk-FYBJGRX7.js} +1 -1
- package/chunks/{chunk-FPZPCZFS.js → chunk-G6DALGGS.js} +1 -1
- package/chunks/{chunk-3Y6LSWEW.js → chunk-GBSRWT7J.js} +1 -1
- package/chunks/{chunk-SMYBY353.js → chunk-GHIFIXNX.js} +1 -1
- package/chunks/{chunk-DE53B2R7.js → chunk-GRAECADD.js} +1 -1
- package/chunks/{chunk-UJYOILZR.js → chunk-GSPGIGO5.js} +3 -3
- package/chunks/{chunk-5UZT4SXG.js → chunk-H3IR3GIE.js} +1 -1
- package/chunks/{chunk-ADZI3OFT.js → chunk-HOG66S6K.js} +1 -1
- package/chunks/{chunk-WB34KMOT.js → chunk-HTAUIJB4.js} +1 -1
- package/chunks/{chunk-MPAR4JBP.js → chunk-I6PUY2T3.js} +1 -1
- package/chunks/{chunk-5ZQWQ3RK.js → chunk-IZ5MWA6E.js} +1 -1
- package/chunks/{chunk-7IERHQ63.js → chunk-JEDL4IKF.js} +1 -1
- package/chunks/{chunk-RVJJFDF3.js → chunk-JH3V5SPA.js} +1 -1
- package/chunks/{chunk-SELRSZFK.js → chunk-JRTOPEM3.js} +1 -1
- package/chunks/{chunk-SQQORHMS.js → chunk-JWNKPINR.js} +1 -1
- package/chunks/{chunk-55RVKT4O.js → chunk-KJGRCIVY.js} +1 -1
- package/chunks/{chunk-GSOBASYW.js → chunk-KZNYALFU.js} +1 -1
- package/chunks/{chunk-FDUXQAGW.js → chunk-LBLLWAKK.js} +1 -1
- package/chunks/{chunk-ZSVSRF4C.js → chunk-LT3J74BZ.js} +1 -1
- package/chunks/{chunk-AMTFJVDD.js → chunk-LTE4N6L3.js} +1 -1
- package/chunks/{chunk-F26LTWDZ.js → chunk-M6KB5RVD.js} +1 -1
- package/chunks/{chunk-2PY7R7GG.js → chunk-MGATL4OA.js} +1 -1
- package/chunks/{chunk-KGJ47CI5.js → chunk-MPVQDYPH.js} +1 -1
- package/chunks/{chunk-BBOJUFMW.js → chunk-MTDBCIDA.js} +1 -1
- package/chunks/{chunk-ZYTG6R7S.js → chunk-MYV7GY3H.js} +1 -1
- package/chunks/{chunk-4GC5HJZO.js → chunk-N7PWZBXV.js} +1 -1
- package/chunks/{chunk-2NOMOJWE.js → chunk-NA4ZF2FE.js} +2 -2
- package/chunks/{chunk-7MTBINFX.js → chunk-NEKPQLFY.js} +2 -2
- package/chunks/{chunk-ABJGFEES.js → chunk-NO7VTKRL.js} +1 -1
- package/chunks/{chunk-OHXQYU6S.js → chunk-NONBHCXP.js} +1 -1
- package/chunks/{chunk-ZOBX6C7E.js → chunk-NVOI6UDQ.js} +1 -1
- package/chunks/{chunk-YLAI26PX.js → chunk-OJ4K62S2.js} +1 -1
- package/chunks/{chunk-CCOUFBOY.js → chunk-OK7LBM5G.js} +1 -1
- package/chunks/{chunk-POA4NX4N.js → chunk-OOJ2AQT3.js} +1 -1
- package/chunks/{chunk-5WLKN3GD.js → chunk-OU7CEG7Q.js} +1 -1
- package/chunks/{chunk-4TYTJQWR.js → chunk-P3JEEDQZ.js} +1 -1
- package/chunks/{chunk-AQWHCRKY.js → chunk-P62S5JGM.js} +1 -1
- package/chunks/{chunk-B6D3KTUK.js → chunk-QDCUR3JB.js} +1 -1
- package/chunks/{chunk-XFLLE2J3.js → chunk-RSLTOIG5.js} +2 -2
- package/chunks/{chunk-ISGF3BVD.js → chunk-RXN7DUMP.js} +2 -2
- package/chunks/{chunk-PN62SUYK.js → chunk-SKGJ26HQ.js} +1 -1
- package/chunks/{chunk-62NLMVVT.js → chunk-SP6CQ3MO.js} +1 -1
- package/chunks/{chunk-4EQWJTJR.js → chunk-T2YTHAJW.js} +1 -1
- package/chunks/{chunk-NO26JN24.js → chunk-T53VMDXH.js} +1 -1
- package/chunks/{chunk-X4BFEDWU.js → chunk-T5DKF33F.js} +1 -1
- package/chunks/{chunk-KKBOCRPF.js → chunk-TB4AUC2L.js} +1 -1
- package/chunks/{chunk-Q6QS5JTK.js → chunk-U3Q72OGV.js} +1 -1
- package/chunks/{chunk-FLJLUMQF.js → chunk-UKLXKJKL.js} +1 -1
- package/chunks/{chunk-IH2PFVWO.js → chunk-VD2GSW64.js} +1 -1
- package/chunks/{chunk-VDRE7U3P.js → chunk-VRKYBH5G.js} +5 -5
- package/chunks/{chunk-MOPJNP5I.js → chunk-W2RQIZ6B.js} +1 -1
- package/chunks/{chunk-2LLPGSUK.js → chunk-W5Z4BWWA.js} +1 -1
- package/chunks/{chunk-CNFA5UUM.js → chunk-W66WWTOP.js} +1 -1
- package/chunks/{chunk-C56YJIEI.js → chunk-WGFX3EL3.js} +1 -1
- package/chunks/{chunk-6NI33TVK.js → chunk-X2TY7VTY.js} +1 -1
- package/chunks/{chunk-FIM7MM25.js → chunk-XISR37DQ.js} +1 -1
- package/chunks/{chunk-KDYUZBZC.js → chunk-YH2XRWRF.js} +1 -1
- package/chunks/{chunk-UBXLQ6TP.js → chunk-ZENMAISJ.js} +1 -1
- package/chunks/{codex-subagent-executor-EK3A2WBH.js → codex-subagent-executor-OLMGVPVS.js} +1 -1
- package/chunks/{config-utils-DLOK7OLM.js → config-utils-OWY5G5Y2.js} +1 -1
- package/chunks/{contextCommand-AVCUCHQC.js → contextCommand-IXFUZH65.js} +1 -1
- package/chunks/{core-runtime-QSS4ZTG6.js → core-runtime-O4LC4NY3.js} +1 -1
- package/chunks/{create-sub-session-PNF7QDKC.js → create-sub-session-6F7C3TMT.js} +1 -1
- package/chunks/{cron-create-C6JOFIU4.js → cron-create-2422NBSJ.js} +1 -1
- package/chunks/{daemon-git-worktree-guard-5XZAZ7D2.js → daemon-git-worktree-guard-EWPQA6NO.js} +1 -1
- package/chunks/{daemon-status-provider-MRNELSNJ.js → daemon-status-provider-FAHOXNFW.js} +1 -1
- package/chunks/{daemon-trust-policy-26CMW3WY.js → daemon-trust-policy-L3DM6AI5.js} +1 -1
- package/chunks/{daemon-trust-policy-monitor-3DWO6NQY.js → daemon-trust-policy-monitor-HNPY5KJ4.js} +1 -1
- package/chunks/{deferred-core-runtime-DEC3N46T.js → deferred-core-runtime-JF42NQJK.js} +1 -1
- package/chunks/{edit-3HMQPCHN.js → edit-E5LEI2LL.js} +1 -1
- package/chunks/{enterPlanMode-QHJF4JXZ.js → enterPlanMode-3COTUV5V.js} +1 -1
- package/chunks/{environment-NGIBJWOT.js → environment-XBBIB3VA.js} +1 -1
- package/chunks/{errors-MSTGCVGJ.js → errors-LNMQ7TUK.js} +1 -1
- package/chunks/{execution-tool-VR4TGOI4.js → execution-tool-QDDKJD2K.js} +1 -1
- package/chunks/{execution-worker-EJH7HIE2.js → execution-worker-TXGZRZXE.js} +1 -1
- package/chunks/{exitPlanMode-P25OHQJ6.js → exitPlanMode-Z7QEMWPE.js} +1 -1
- package/chunks/{fast-path-II433ZDP.js → fast-path-M6K2RACY.js} +1 -1
- package/chunks/{glob-4Q6DCT3F.js → glob-N2QT4U7U.js} +1 -1
- package/chunks/{goal-tools-FFMAJW6V.js → goal-tools-CUSQD3DG.js} +1 -1
- package/chunks/{handleAutoUpdate-QNM26NZK.js → handleAutoUpdate-QF2YQHF6.js} +1 -1
- package/chunks/{i18n-L5URVOBB.js → i18n-AGOA6MUI.js} +1 -1
- package/chunks/{initializer-NQ2NECYP.js → initializer-FRKYDUSX.js} +1 -1
- package/chunks/{installationInfo-BCTXASUM.js → installationInfo-OKA4WXAS.js} +1 -1
- package/chunks/{interactive-mod-session-PPTBI37E.js → interactive-mod-session-MWYN5IFK.js} +1 -1
- package/chunks/{list-7TE5TUZJ.js → list-DE7VUIR2.js} +1 -1
- package/chunks/{llm-BWWKUBBZ.js → llm-N3JGJHYC.js} +4 -4
- package/chunks/{llm-content-generator-QOTGPBYC.js → llm-content-generator-VMUBA7OJ.js} +1 -1
- package/chunks/{loadedSettingsAdapter-THAGI5M2.js → loadedSettingsAdapter-5C36OZ7N.js} +1 -1
- package/chunks/{local-7BTAGV4J.js → local-BE624O3A.js} +1 -1
- package/chunks/{local-execution-environment-S3OR4KSC.js → local-execution-environment-OPGM7Y6L.js} +1 -1
- package/chunks/{loggingContentGenerator-AXJ5E5RS.js → loggingContentGenerator-2MHAI6JR.js} +1 -1
- package/chunks/{loop-wakeup-AJTLMLRX.js → loop-wakeup-BDLATBXH.js} +1 -1
- package/chunks/{manage-memory-JHTUVMDJ.js → manage-memory-BBCEIIWB.js} +1 -1
- package/chunks/{managed-execution-engine-U6GNJ4U4.js → managed-execution-engine-SRFALTCX.js} +1 -1
- package/chunks/{managed-local-serve-P4ZXVRBU.js → managed-local-serve-ICNAS3E6.js} +1 -1
- package/chunks/{managed-npm-update-UDUILNR5.js → managed-npm-update-CTL6LH5Z.js} +1 -1
- package/chunks/{managed-runtime-attestation-worker-P34ZBNRG.js → managed-runtime-attestation-worker-ZRDWKXCI.js} +1 -1
- package/chunks/{managed-runtime-bootstrap-CLMYNPH5.js → managed-runtime-bootstrap-6NTGZXQL.js} +1 -1
- package/chunks/{managed-runtime-session-worker-7H7AZJBV.js → managed-runtime-session-worker-RKQBBFR6.js} +1 -1
- package/chunks/{managed-runtime-ssh-worker-5KEMC7FD.js → managed-runtime-ssh-worker-FCGV6FSW.js} +1 -1
- package/chunks/{managed-session-authority-CFUZ45HT.js → managed-session-authority-C7IW6TJX.js} +1 -1
- package/chunks/{mcp-YMG4RVMC.js → mcp-VC4CJPE5.js} +1 -1
- package/chunks/{memory-7STURUXK.js → memory-S6OJA3ZD.js} +1 -1
- package/chunks/mn-JMS6SWTO.js +8 -0
- package/chunks/{model-call-collection-WBWTO3EG.js → model-call-collection-MJZWRQSU.js} +1 -1
- package/chunks/{model-configuration-6KCZZSZD.js → model-configuration-SKU6L3QI.js} +1 -1
- package/chunks/{modelConfigUtils-Z2EKFSPN.js → modelConfigUtils-TJCB6NXT.js} +1 -1
- package/chunks/{monitor-U5E33JO6.js → monitor-M3PNLCYP.js} +1 -1
- package/chunks/{nonInteractiveCli-BVCL5I5R.js → nonInteractiveCli-MR7JLAWU.js} +1 -1
- package/chunks/{nonInteractiveToolExecutor-B4EUOMYF.js → nonInteractiveToolExecutor-YKA6JMTY.js} +1 -1
- package/chunks/{notebook-edit-MXKD5J2C.js → notebook-edit-ENTFB5D7.js} +1 -1
- package/chunks/{omni-I5YECZBW.js → omni-6YBX4R6K.js} +1 -1
- package/chunks/{openaiContentGenerator-Q5SINFJJ.js → openaiContentGenerator-XRXX33FY.js} +1 -1
- package/chunks/{openaiResponsesContentGenerator-R3XCZLZY.js → openaiResponsesContentGenerator-L6ONEHMR.js} +1 -1
- package/chunks/{pidfile-UOGUNUTK.js → pidfile-XR4JF2Z6.js} +1 -1
- package/chunks/{processUtils-QGQGZHBA.js → processUtils-GQYNJRBJ.js} +1 -1
- package/chunks/{prompt-terminal-ledger-L57JMVSR.js → prompt-terminal-ledger-7BM7YDLG.js} +1 -1
- package/chunks/{qwenContentGenerator-UKZ237LC.js → qwenContentGenerator-QSA32XEL.js} +1 -1
- package/chunks/{reactive-degrade-3OM3HWVA.js → reactive-degrade-TFNBAAPZ.js} +1 -1
- package/chunks/{read-file-63ZLWMOW.js → read-file-VD7OFO2E.js} +1 -1
- package/chunks/{resumeHistoryUtils-R5YQS4YQ.js → resumeHistoryUtils-2B4KPI7G.js} +1 -1
- package/chunks/{review-AT6OWVDO.js → review-C365WGCW.js} +1 -1
- package/chunks/{ripGrep-7KBZGTPV.js → ripGrep-D7WPMBXR.js} +1 -1
- package/chunks/{run-qwen-serve-CLBG7W6F.js → run-qwen-serve-NZWQHWQA.js} +1 -1
- package/chunks/{runtime-R3QIGB7U.js → runtime-J6SPBSCS.js} +1 -1
- package/chunks/{sandboxConfig-PM3ZRQYV.js → sandboxConfig-QS2XBPZG.js} +1 -1
- package/chunks/{scheduled-tasks-PUMNN5XV.js → scheduled-tasks-YNNIOOPM.js} +1 -1
- package/chunks/{scheduler-KTPM226B.js → scheduler-KCMSPHON.js} +1 -1
- package/chunks/{search-memory-7I5MGDNV.js → search-memory-EUBJ7IAV.js} +1 -1
- package/chunks/{send-message-J526AEBI.js → send-message-CWWZUPSK.js} +1 -1
- package/chunks/{serve-KLTMPK4W.js → serve-4CB4BWJ5.js} +1 -1
- package/chunks/{server-VLRNY6KG.js → server-JNANUIGC.js} +3 -3
- package/chunks/{session-2EB57NXY.js → session-3LQLXPUA.js} +1 -1
- package/chunks/{session-attachments-root-I7TESMWL.js → session-attachments-root-BWIVWFHJ.js} +1 -1
- package/chunks/{session-execution-engine-selector-5FAMSPSO.js → session-execution-engine-selector-5OLRX57L.js} +1 -1
- package/chunks/{session-pr-refresh-JCPVQPNJ.js → session-pr-refresh-RLF3EXS3.js} +1 -1
- package/chunks/{sessionService-YRW2IFPR.js → sessionService-U7ACD2HP.js} +1 -1
- package/chunks/{settings-KO2Q47JP.js → settings-FTGWYTUH.js} +1 -1
- package/chunks/{shell-OLZVNTQZ.js → shell-E4RENYQC.js} +1 -1
- package/chunks/{skill-XW2AQS7M.js → skill-OLNPHRWB.js} +1 -1
- package/chunks/{skill-settings-TKAVQ4XP.js → skill-settings-R2BV2GEK.js} +1 -1
- package/chunks/{spawnChannel-MBGCTK2J.js → spawnChannel-LOPAR5T2.js} +1 -1
- package/chunks/{standalone-update-A3YLLIAN.js → standalone-update-IGDX2RGN.js} +1 -1
- package/chunks/{start-opentui-ui-G5ROAR4V.js → start-opentui-ui-33QLBNRC.js} +1 -1
- package/chunks/{startInteractiveUI-PZQR4U53.js → startInteractiveUI-RQKHD7MM.js} +1 -1
- package/chunks/{team-create-S5ZY2UMF.js → team-create-HAVKHNU5.js} +1 -1
- package/chunks/{team-plan-approval-KX6RXEST.js → team-plan-approval-7MCQX67C.js} +1 -1
- package/chunks/{terminal-image-renderer-SCJREXE6.js → terminal-image-renderer-XT5JVEO6.js} +1 -1
- package/chunks/{theme-manager-DZSM4EBR.js → theme-manager-DR5EYGLT.js} +1 -1
- package/chunks/{tool-call-UK56SWCT.js → tool-call-LZHZ5RVH.js} +1 -1
- package/chunks/{tool-result-media-JLLSLGFL.js → tool-result-media-XCXCF4YC.js} +1 -1
- package/chunks/{tool-search-OWPFLVV5.js → tool-search-K6S3ON7M.js} +1 -1
- package/chunks/{total-session-admission-NQU4ACKH.js → total-session-admission-LGSS2VWS.js} +1 -1
- package/chunks/{trustedFolders-N7GXFYSF.js → trustedFolders-IIR2UZRL.js} +1 -1
- package/chunks/{update-relaunch-5SPXXHM2.js → update-relaunch-WVIFX5CN.js} +1 -1
- package/chunks/{updateCheck-VXUIX2XG.js → updateCheck-CMEWLLZJ.js} +1 -1
- package/chunks/{upload-config-OWLL4SRQ.js → upload-config-TCCFCNCD.js} +1 -1
- package/chunks/{useAutoAcceptIndicator-OUYRR56F.js → useAutoAcceptIndicator-5RTTH3OW.js} +1 -1
- package/chunks/{validateNonInterActiveAuth-PSVJO5HK.js → validateNonInterActiveAuth-AO336KDX.js} +1 -1
- package/chunks/{version-C26S7UAW.js → version-JYWKKMNP.js} +1 -1
- package/chunks/{web-fetch-AYOYV7R4.js → web-fetch-HWTAWXFM.js} +1 -1
- package/chunks/{web-search-DAREKD3Z.js → web-search-HAI5LW3G.js} +1 -1
- package/chunks/{workflow-WBGPKVO6.js → workflow-BZ2YFGF6.js} +1 -1
- package/chunks/{workflow-ancestor-trust-GEEB53TB.js → workflow-ancestor-trust-26TFXFPO.js} +1 -1
- package/chunks/{workspace-agents-IMAQME4W.js → workspace-agents-DLI4JQJZ.js} +1 -1
- package/chunks/{workspace-providers-status-VALHVEU2.js → workspace-providers-status-64C7DJZU.js} +1 -1
- package/chunks/{workspace-recovery-worker-AIAVRDGU.js → workspace-recovery-worker-IFRT3KKP.js} +1 -1
- package/chunks/{workspace-registration-store-FXEGZG3L.js → workspace-registration-store-MYKJM2SK.js} +1 -1
- package/chunks/{workspace-registry-GYFFHWCD.js → workspace-registry-GZJRONAY.js} +1 -1
- package/chunks/{workspace-runtime-coordinator-VZ462TLU.js → workspace-runtime-coordinator-44KW6HSN.js} +1 -1
- package/chunks/{workspace-service-5DIZM4IZ.js → workspace-service-YHTSZYYD.js} +1 -1
- package/chunks/{workspace-skills-status-DOOBVL5N.js → workspace-skills-status-NEB62X24.js} +1 -1
- package/chunks/{workspace-trust-reconciler-LOICVUVW.js → workspace-trust-reconciler-HZLOOZWM.js} +1 -1
- package/chunks/{write-file-EJNMAHQD.js → write-file-HD5LHXGL.js} +1 -1
- package/chunks/{zoom-image-S3OARMYP.js → zoom-image-W4BMRC5T.js} +1 -1
- package/cli.js +2 -2
- package/execution-worker.js +1 -1
- package/export-transcript-document.js +1 -1
- package/gerege.mjs +53 -15
- package/locales/mn.js +2702 -3774
- package/package.json +3 -3
- package/chunks/mn-YH2OTBWJ.js +0 -8
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{MarkdownCommandDefSchema,parseMarkdownCommand}from"./chunk-XXUK6YLA.js";import{MANAGED_EXTENSION_DEVELOPER_CAPABILITY_DIGEST,MANAGED_EXTENSION_LINUX_CAPABILITY_DIGEST,createManagedContextAttestationResponse,createManagedContextReady,parseManagedContextBoot}from"./chunk-36TKFM4Z.js";import{historyPath,parseHostedFileHistoryState,parseManagedToolFileHistoryBinding,parseManagedToolFileHistoryPromptId,parseManagedToolFileHistoryState}from"./chunk-SMYBY353.js";import{computeManagedContextDigest,isCanonicalDecimalText}from"./chunk-YJ6APXNB.js";import{resolveManagedRuntimeBrokerBaseUrl}from"./chunk-6S5XOXJ2.js";import{authorizeManagedRuntime,handleManagedRuntimeJsonError,managedRuntimeJsonBody,managedRuntimeNoStore}from"./chunk-XLCTS6G3.js";import{DAEMON_ACP_NDJSON_LIMITS,hasBoundedJsonStructure}from"./chunk-BC4C6F32.js";import{MAX_ARCHIVE_ENTRIES,MAX_ARCHIVE_EXPANDED_BYTES,Qn,cloneFromGit,convertClaudeToQwenConfig,convertGeminiToQwenConfig,createCronGateRunner,downloadFromArchiveUrl,downloadFromGitHubRelease,downloadFromNpmRegistry,extractArchiveFile,gateCommandError,managedToolDigest,parseManagedToolCallIdentity,parseManagedToolConfirmationPayload,parseManagedToolContentModification,parseManagedToolInvocationReference,parseManagedToolMediaContext,require_toml}from"./chunk-Z5XENA4A.js";import{MANAGED_SESSION_LIMITS,MANAGED_TOOL_RESULT_KINDS,MANAGED_TOOL_RESULT_LIMITS,MANAGED_TOOL_RESULT_PROTOCOL,assertManagedSessionDurableRef,assertManagedSessionStableId,impliedStatus,parseManagedSessionRecordJson,parseToolResultManifest,parseToolResultPage}from"./chunk-OMSVOFTC.js";import{isShellResultDisplay}from"./chunk-T7CHK6C2.js";import{parseSkillContent}from"./chunk-5SUFJTQQ.js";import{qualifySkillName}from"./chunk-CV2UAEZA.js";import{require_brace_expansion}from"./chunk-OBOU4ZZM.js";import{BaseDeclarativeTool,BaseToolInvocation,ToolConfirmationOutcome}from"./chunk-O5EKX7LG.js";import{resolveBuiltinToolName}from"./chunk-SBZFGYYS.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();var MAX_MANAGED_MEDIA_RESPONSE_BYTES=DAEMON_ACP_NDJSON_LIMITS.maxFrameBytes-64*1024;function record(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)?value:void 0}__name(record,"record");function isBase64(data){if(data.length%4!==0)return false;const padding=data.endsWith("==")?2:data.endsWith("=")?1:0;const body=data.slice(0,data.length-padding);if(/[^A-Za-z0-9+/]/.test(body))return false;if(padding===0)return true;const last="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(body.at(-1));return padding===2?(last&15)===0:(last&3)===0}__name(isBase64,"isBase64");function managedToolResponseMediaBytes(result,operation){const json=JSON.stringify(result);if(json===void 0||Buffer.byteLength(json)>MAX_MANAGED_MEDIA_RESPONSE_BYTES){throw new Error("Managed Runtime media response exceeded its size limit.")}const wire=JSON.parse(json);if(!hasBoundedJsonStructure({jsonrpc:"2.0",id:"0",result:wire})){throw new Error("Managed Runtime media response exceeded ACP structure limits.")}const status=record(wire);if(operation!=="execute"&&status?.["state"]!=="settled")return 0;const execution2=operation==="execute"?status:record(status?.["result"]);if(!["not_started","success","error","cancelled"].includes(String(execution2?.["executionStatus"])))return 0;const content=record(execution2?.["result"])?.["llmContent"];const parts=Array.isArray(content)?content:[content];let mediaBytes=0;for(const part of parts){const object5=record(part);if(!object5||!Object.hasOwn(object5,"inlineData"))continue;const inline=record(object5["inlineData"]);if(!inline||typeof inline["data"]!=="string"||typeof inline["mimeType"]!=="string"||!/^(?:(?:image|audio|video)\/[a-z0-9.+-]+|application\/pdf)$/i.test(inline["mimeType"])||!isBase64(inline["data"])){throw new Error("Managed Runtime returned invalid inline media.")}mediaBytes+=inline["data"].length}return mediaBytes}__name(managedToolResponseMediaBytes,"managedToolResponseMediaBytes");var MANAGED_RUNTIME_PROVIDER_PROTOCOL="managed-runtime-provider/1";var MAX_PROVIDER_INLINE_MEDIA_BASE64_BYTES=768*1024;var MAX_PROVIDER_MEDIA_RESULT_BYTES=896*1024;var MANAGED_RUNTIME_PROVIDER_ROUTE=Object.freeze({key:"provider-control",method:"POST",path:"/internal/managed-runtime/provider/v1/control",protocolVersion:1,requestBodyLimitBytes:8*1024*1024,responseBodyLimitBytes:8*1024*1024,cacheControl:"no-store"});var MANAGED_WORKSPACE_CONTEXT_FILES=["QWEN.md","AGENTS.md"];var MANAGED_WORKSPACE_CONTEXT_FILE_CHARS=64*1024;var ManagedRuntimeProviderProtocolError=class extends Error{constructor(message="Managed Runtime provider request is invalid.",status=400,code="managed_runtime_provider_invalid"){super(message);this.status=status;this.code=code;this.name="ManagedRuntimeProviderProtocolError"}static{__name(this,"ManagedRuntimeProviderProtocolError")}};function object(value){if(!value||typeof value!=="object"||Array.isArray(value))throw new ManagedRuntimeProviderProtocolError;return value}__name(object,"object");function keys(value,required,optional=[]){if(required.some(key=>!Object.hasOwn(value,key))||Object.keys(value).some(key=>!required.includes(key)&&!optional.includes(key)))throw new ManagedRuntimeProviderProtocolError}__name(keys,"keys");function id(value){if(typeof value!=="string"||!value.length||value.length>512||value.includes("\0"))throw new ManagedRuntimeProviderProtocolError;return value}__name(id,"id");var SESSION_ID=/^[A-Za-z0-9._-]{1,512}$/;function envelopeSessionId(value){if(typeof value!=="string"||!SESSION_ID.test(value)||value==="."||value.includes(".."))throw new ManagedRuntimeProviderProtocolError("Managed Runtime provider Session identity must be 1-512 ASCII letters, digits, '.', '_' or '-', without '..'.")}__name(envelopeSessionId,"envelopeSessionId");function sequence(value){if(!Number.isSafeInteger(value)||Number(value)<0)throw new ManagedRuntimeProviderProtocolError}__name(sequence,"sequence");function oneOf(value,values){return typeof value==="string"&&values.includes(value)}__name(oneOf,"oneOf");function checkSession(identity,session){if(identity.sessionId!==session.runtimeSessionId)throw new ManagedRuntimeProviderProtocolError("Managed Runtime provider Session identity conflicts.",409,"managed_runtime_identity_conflict")}__name(checkSession,"checkSession");function managedRuntimeProviderLimit(kind){return["bind-history","checkpoint","history"].includes(kind)?8*1024*1024:1024*1024}__name(managedRuntimeProviderLimit,"managedRuntimeProviderLimit");function parseManagedRuntimeProviderOperation(value,session,boundedByCaller=false){const op=object(value);const kind=id(op["kind"]);if(!boundedByCaller)managedToolDigest(value,managedRuntimeProviderLimit(kind));switch(kind){case"raw-file-history":{const action=op["action"];if(action==="bind"){keys(op,["kind","action","state"]);if(op["state"]!==null)parseHostedFileHistoryState(op["state"],session.harnessSessionId)}else if(action==="prepare"){keys(op,["kind","action","promptId","paths"]);parseManagedToolFileHistoryPromptId(op["promptId"]);if(!Array.isArray(op["paths"])||!op["paths"].length)throw new ManagedRuntimeProviderProtocolError;op["paths"].forEach(historyPath)}else if(action==="rewind"){keys(op,["kind","action","promptId"]);parseManagedToolFileHistoryPromptId(op["promptId"])}else if(action==="snapshot")keys(op,["kind","action"]);else throw new ManagedRuntimeProviderProtocolError;break}case"acquire":case"release":case"manifest":case"history":case"workspace-context":keys(op,["kind"]);break;case"begin-turn":case"prepare":{keys(op,kind==="prepare"?["kind","identity","toolName","input"]:["kind","identity"],kind==="prepare"?["modification","mediaContext"]:[]);checkSession(parseManagedToolCallIdentity(op["identity"]),session);if(kind==="prepare"){id(op["toolName"]);object(op["input"]);if("modification"in op)checkSession(parseManagedToolContentModification(op["modification"]).source,session);if("mediaContext"in op)parseManagedToolMediaContext(op["mediaContext"])}break}case"confirmation":case"confirm":case"preflight":case"execute":case"status":case"cancel":keys(op,kind==="confirm"?["kind","reference","outcome"]:["kind","reference"],kind==="confirm"?["payload","phase"]:kind==="status"?["afterSequence"]:[]);checkSession(parseManagedToolInvocationReference(op["reference"]),session);if(kind==="confirm"){if(!Object.values(ToolConfirmationOutcome).includes(op["outcome"])||op["outcome"]==="restore_previous")throw new ManagedRuntimeProviderProtocolError;if("payload"in op)parseManagedToolConfirmationPayload(op["payload"]);if("phase"in op&&!oneOf(op["phase"],["permission","preflight"]))throw new ManagedRuntimeProviderProtocolError}if("afterSequence"in op)sequence(op["afterSequence"]);break;case"bind-history":{keys(op,["kind","binding"]);const binding=parseManagedToolFileHistoryBinding(op["binding"]);if(binding.ownerSessionId!==session.harnessSessionId||binding.ownerRuntimeSessionId!==session.runtimeSessionId)throw new ManagedRuntimeProviderProtocolError("Managed Runtime file history owner conflicts.",409,"managed_runtime_identity_conflict");break}case"checkpoint":keys(op,["kind","promptId"]);parseManagedToolFileHistoryPromptId(op["promptId"]);break;default:throw new ManagedRuntimeProviderProtocolError("Managed Runtime provider operation is unsupported.",501,"managed_runtime_provider_unsupported")}return structuredClone(value)}__name(parseManagedRuntimeProviderOperation,"parseManagedRuntimeProviderOperation");function parseManagedRuntimeProviderRequest(value){const request=object(value);keys(request,["protocolVersion","providerProtocol","session","operation"]);if(request["protocolVersion"]!==1||request["providerProtocol"]!==MANAGED_RUNTIME_PROVIDER_PROTOCOL)throw new ManagedRuntimeProviderProtocolError("Managed Runtime provider protocol is incompatible.",409,"managed_runtime_provider_incompatible");const session=object(request["session"]);keys(session,["harnessSessionId","runtimeSessionId","turnKind"]);envelopeSessionId(session["harnessSessionId"]);envelopeSessionId(session["runtimeSessionId"]);if(!oneOf(session["turnKind"],["bootstrap","continuation"]))throw new ManagedRuntimeProviderProtocolError;const parsedSession=session;const parsed={protocolVersion:1,providerProtocol:MANAGED_RUNTIME_PROVIDER_PROTOCOL,session:structuredClone(parsedSession),operation:parseManagedRuntimeProviderOperation(request["operation"],parsedSession,true)};managedToolDigest(value,managedRuntimeProviderLimit(parsed.operation.kind));return parsed}__name(parseManagedRuntimeProviderRequest,"parseManagedRuntimeProviderRequest");function parseManagedRuntimeProviderResult(operation,value,session){managedToolDigest(value,managedRuntimeProviderLimit(operation.kind));if(operation.kind==="begin-turn"||operation.kind==="confirm"){if(value!==null)throw new ManagedRuntimeProviderProtocolError;return null}if(operation.kind==="acquire"||operation.kind==="release"){if(value!==true)throw new ManagedRuntimeProviderProtocolError;return true}const result=object(value);switch(operation.kind){case"raw-file-history":{if(operation.action!=="rewind")return parseHostedFileHistoryState(value,session.harnessSessionId);keys(result,["state","filesChanged","filesFailed","conflict"]);const state=parseHostedFileHistoryState(result["state"],session.harnessSessionId);if(!Array.isArray(result["filesChanged"])||!Array.isArray(result["filesFailed"])||typeof result["conflict"]!=="boolean")throw new ManagedRuntimeProviderProtocolError;result["filesChanged"].forEach(historyPath);result["filesFailed"].forEach(historyPath);if(new Set(result["filesChanged"]).size!==result["filesChanged"].length||result["filesChanged"].some(file=>!Object.hasOwn(state.files,file))||!state.snapshots.some(snapshot=>snapshot.promptId===operation.promptId)||result["conflict"]&&result["filesChanged"].length!==0)throw new ManagedRuntimeProviderProtocolError("Invalid Hosted file history rewind outcome.");break}case"workspace-context":{keys(result,["files"]);if(!Array.isArray(result["files"]))throw new ManagedRuntimeProviderProtocolError;let next=0;for(const entry of result["files"]){const file=object(entry);keys(file,["name","text"]);const index=MANAGED_WORKSPACE_CONTEXT_FILES.indexOf(file["name"]);if(index<next||typeof file["text"]!=="string"||file["text"].length>MANAGED_WORKSPACE_CONTEXT_FILE_CHARS)throw new ManagedRuntimeProviderProtocolError("Invalid Workspace context result.");next=index+1}return result["files"]}case"bind-history":case"checkpoint":case"history":{const state=parseManagedToolFileHistoryState(value);if(state.ownerSessionId!==session.harnessSessionId)throw new ManagedRuntimeProviderProtocolError("Managed file history owner changed.");return state}case"manifest":keys(result,["tools","capabilityDigest","policyRevision"]);id(result["policyRevision"]);if(!Array.isArray(result["tools"])||managedToolDigest(result["tools"],1024*1024)!==result["capabilityDigest"])throw new ManagedRuntimeProviderProtocolError("Managed tool manifest digest changed.");for(const tool of result["tools"]){const descriptor=object(tool);id(descriptor["name"]);object(descriptor["schema"])}break;case"prepare":{const reference=Object.fromEntries(["sessionId","promptId","callId","capabilityDigest","policyRevision","invocationId","argsDigest"].map(key=>[key,result[key]]));checkSession(parseManagedToolInvocationReference(reference),session);for(const[key,expected]of Object.entries(operation.identity))if(result[key]!==expected)throw new ManagedRuntimeProviderProtocolError;object(result["params"]);if(managedToolDigest(result["params"])!==result["argsDigest"]||typeof result["description"]!=="string"||!Array.isArray(result["locations"])||!oneOf(result["defaultPermission"],["allow","ask","deny","default"])||typeof result["requiresUserInteraction"]!=="boolean")throw new ManagedRuntimeProviderProtocolError;id(result["toolUseId"]);break}case"confirmation":{if(!oneOf(result["type"],["edit","exec","mcp","info"])||typeof result["title"]!=="string")throw new ManagedRuntimeProviderProtocolError;const required={edit:["fileName","filePath","fileDiff","newContent"],exec:["command","rootCommand"],mcp:["serverName","toolName","toolDisplayName"],info:["prompt"]}[result["type"]];if(required.some(key=>typeof result[key]!=="string")||result["type"]==="edit"&&result["originalContent"]!==null&&typeof result["originalContent"]!=="string")throw new ManagedRuntimeProviderProtocolError;break}case"preflight":if(typeof result["shouldProceed"]!=="boolean")throw new ManagedRuntimeProviderProtocolError;break;case"execute":if(!oneOf(result["executionStatus"],["not_started","success","error","cancelled"]))throw new ManagedRuntimeProviderProtocolError;if(result["executionStatus"]==="success")object(result["result"]);break;case"status":case"cancel":if(result["state"]==="unknown"){keys(result,["state"]);break}if(!oneOf(result["state"],["prepared","executing","cancel_requested","settled"])||typeof result["cancelRequested"]!=="boolean"||typeof result["progressGap"]!=="boolean"||!Array.isArray(result["progress"]))throw new ManagedRuntimeProviderProtocolError;sequence(result["lastSeq"]);sequence(result["firstAvailableSeq"]);if(result["state"]==="settled")parseManagedRuntimeProviderResult({kind:"execute",reference:operation.reference},result["result"],session);else if("result"in result)throw new ManagedRuntimeProviderProtocolError;break;default:throw new ManagedRuntimeProviderProtocolError}return structuredClone(value)}__name(parseManagedRuntimeProviderResult,"parseManagedRuntimeProviderResult");function providerFitNotice(omitted,budgetBytes){return`
|
|
3
|
+
import{MarkdownCommandDefSchema,parseMarkdownCommand}from"./chunk-XXUK6YLA.js";import{MANAGED_EXTENSION_DEVELOPER_CAPABILITY_DIGEST,MANAGED_EXTENSION_LINUX_CAPABILITY_DIGEST,createManagedContextAttestationResponse,createManagedContextReady,parseManagedContextBoot}from"./chunk-36TKFM4Z.js";import{historyPath,parseHostedFileHistoryState,parseManagedToolFileHistoryBinding,parseManagedToolFileHistoryPromptId,parseManagedToolFileHistoryState}from"./chunk-GHIFIXNX.js";import{computeManagedContextDigest,isCanonicalDecimalText}from"./chunk-YJ6APXNB.js";import{resolveManagedRuntimeBrokerBaseUrl}from"./chunk-6S5XOXJ2.js";import{authorizeManagedRuntime,handleManagedRuntimeJsonError,managedRuntimeJsonBody,managedRuntimeNoStore}from"./chunk-XLCTS6G3.js";import{DAEMON_ACP_NDJSON_LIMITS,hasBoundedJsonStructure}from"./chunk-BC4C6F32.js";import{MAX_ARCHIVE_ENTRIES,MAX_ARCHIVE_EXPANDED_BYTES,Qn,cloneFromGit,convertClaudeToQwenConfig,convertGeminiToQwenConfig,createCronGateRunner,downloadFromArchiveUrl,downloadFromGitHubRelease,downloadFromNpmRegistry,extractArchiveFile,gateCommandError,managedToolDigest,parseManagedToolCallIdentity,parseManagedToolConfirmationPayload,parseManagedToolContentModification,parseManagedToolInvocationReference,parseManagedToolMediaContext,require_toml}from"./chunk-2JGTWRZJ.js";import{MANAGED_SESSION_LIMITS,MANAGED_TOOL_RESULT_KINDS,MANAGED_TOOL_RESULT_LIMITS,MANAGED_TOOL_RESULT_PROTOCOL,assertManagedSessionDurableRef,assertManagedSessionStableId,impliedStatus,parseManagedSessionRecordJson,parseToolResultManifest,parseToolResultPage}from"./chunk-OMSVOFTC.js";import{isShellResultDisplay}from"./chunk-T7CHK6C2.js";import{parseSkillContent}from"./chunk-5SUFJTQQ.js";import{qualifySkillName}from"./chunk-CV2UAEZA.js";import{require_brace_expansion}from"./chunk-OBOU4ZZM.js";import{BaseDeclarativeTool,BaseToolInvocation,ToolConfirmationOutcome}from"./chunk-O5EKX7LG.js";import{resolveBuiltinToolName}from"./chunk-SBZFGYYS.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();var MAX_MANAGED_MEDIA_RESPONSE_BYTES=DAEMON_ACP_NDJSON_LIMITS.maxFrameBytes-64*1024;function record(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)?value:void 0}__name(record,"record");function isBase64(data){if(data.length%4!==0)return false;const padding=data.endsWith("==")?2:data.endsWith("=")?1:0;const body=data.slice(0,data.length-padding);if(/[^A-Za-z0-9+/]/.test(body))return false;if(padding===0)return true;const last="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(body.at(-1));return padding===2?(last&15)===0:(last&3)===0}__name(isBase64,"isBase64");function managedToolResponseMediaBytes(result,operation){const json=JSON.stringify(result);if(json===void 0||Buffer.byteLength(json)>MAX_MANAGED_MEDIA_RESPONSE_BYTES){throw new Error("Managed Runtime media response exceeded its size limit.")}const wire=JSON.parse(json);if(!hasBoundedJsonStructure({jsonrpc:"2.0",id:"0",result:wire})){throw new Error("Managed Runtime media response exceeded ACP structure limits.")}const status=record(wire);if(operation!=="execute"&&status?.["state"]!=="settled")return 0;const execution2=operation==="execute"?status:record(status?.["result"]);if(!["not_started","success","error","cancelled"].includes(String(execution2?.["executionStatus"])))return 0;const content=record(execution2?.["result"])?.["llmContent"];const parts=Array.isArray(content)?content:[content];let mediaBytes=0;for(const part of parts){const object5=record(part);if(!object5||!Object.hasOwn(object5,"inlineData"))continue;const inline=record(object5["inlineData"]);if(!inline||typeof inline["data"]!=="string"||typeof inline["mimeType"]!=="string"||!/^(?:(?:image|audio|video)\/[a-z0-9.+-]+|application\/pdf)$/i.test(inline["mimeType"])||!isBase64(inline["data"])){throw new Error("Managed Runtime returned invalid inline media.")}mediaBytes+=inline["data"].length}return mediaBytes}__name(managedToolResponseMediaBytes,"managedToolResponseMediaBytes");var MANAGED_RUNTIME_PROVIDER_PROTOCOL="managed-runtime-provider/1";var MAX_PROVIDER_INLINE_MEDIA_BASE64_BYTES=768*1024;var MAX_PROVIDER_MEDIA_RESULT_BYTES=896*1024;var MANAGED_RUNTIME_PROVIDER_ROUTE=Object.freeze({key:"provider-control",method:"POST",path:"/internal/managed-runtime/provider/v1/control",protocolVersion:1,requestBodyLimitBytes:8*1024*1024,responseBodyLimitBytes:8*1024*1024,cacheControl:"no-store"});var MANAGED_WORKSPACE_CONTEXT_FILES=["QWEN.md","AGENTS.md"];var MANAGED_WORKSPACE_CONTEXT_FILE_CHARS=64*1024;var ManagedRuntimeProviderProtocolError=class extends Error{constructor(message="Managed Runtime provider request is invalid.",status=400,code="managed_runtime_provider_invalid"){super(message);this.status=status;this.code=code;this.name="ManagedRuntimeProviderProtocolError"}static{__name(this,"ManagedRuntimeProviderProtocolError")}};function object(value){if(!value||typeof value!=="object"||Array.isArray(value))throw new ManagedRuntimeProviderProtocolError;return value}__name(object,"object");function keys(value,required,optional=[]){if(required.some(key=>!Object.hasOwn(value,key))||Object.keys(value).some(key=>!required.includes(key)&&!optional.includes(key)))throw new ManagedRuntimeProviderProtocolError}__name(keys,"keys");function id(value){if(typeof value!=="string"||!value.length||value.length>512||value.includes("\0"))throw new ManagedRuntimeProviderProtocolError;return value}__name(id,"id");var SESSION_ID=/^[A-Za-z0-9._-]{1,512}$/;function envelopeSessionId(value){if(typeof value!=="string"||!SESSION_ID.test(value)||value==="."||value.includes(".."))throw new ManagedRuntimeProviderProtocolError("Managed Runtime provider Session identity must be 1-512 ASCII letters, digits, '.', '_' or '-', without '..'.")}__name(envelopeSessionId,"envelopeSessionId");function sequence(value){if(!Number.isSafeInteger(value)||Number(value)<0)throw new ManagedRuntimeProviderProtocolError}__name(sequence,"sequence");function oneOf(value,values){return typeof value==="string"&&values.includes(value)}__name(oneOf,"oneOf");function checkSession(identity,session){if(identity.sessionId!==session.runtimeSessionId)throw new ManagedRuntimeProviderProtocolError("Managed Runtime provider Session identity conflicts.",409,"managed_runtime_identity_conflict")}__name(checkSession,"checkSession");function managedRuntimeProviderLimit(kind){return["bind-history","checkpoint","history"].includes(kind)?8*1024*1024:1024*1024}__name(managedRuntimeProviderLimit,"managedRuntimeProviderLimit");function parseManagedRuntimeProviderOperation(value,session,boundedByCaller=false){const op=object(value);const kind=id(op["kind"]);if(!boundedByCaller)managedToolDigest(value,managedRuntimeProviderLimit(kind));switch(kind){case"raw-file-history":{const action=op["action"];if(action==="bind"){keys(op,["kind","action","state"]);if(op["state"]!==null)parseHostedFileHistoryState(op["state"],session.harnessSessionId)}else if(action==="prepare"){keys(op,["kind","action","promptId","paths"]);parseManagedToolFileHistoryPromptId(op["promptId"]);if(!Array.isArray(op["paths"])||!op["paths"].length)throw new ManagedRuntimeProviderProtocolError;op["paths"].forEach(historyPath)}else if(action==="rewind"){keys(op,["kind","action","promptId"]);parseManagedToolFileHistoryPromptId(op["promptId"])}else if(action==="snapshot")keys(op,["kind","action"]);else throw new ManagedRuntimeProviderProtocolError;break}case"acquire":case"release":case"manifest":case"history":case"workspace-context":keys(op,["kind"]);break;case"begin-turn":case"prepare":{keys(op,kind==="prepare"?["kind","identity","toolName","input"]:["kind","identity"],kind==="prepare"?["modification","mediaContext"]:[]);checkSession(parseManagedToolCallIdentity(op["identity"]),session);if(kind==="prepare"){id(op["toolName"]);object(op["input"]);if("modification"in op)checkSession(parseManagedToolContentModification(op["modification"]).source,session);if("mediaContext"in op)parseManagedToolMediaContext(op["mediaContext"])}break}case"confirmation":case"confirm":case"preflight":case"execute":case"status":case"cancel":keys(op,kind==="confirm"?["kind","reference","outcome"]:["kind","reference"],kind==="confirm"?["payload","phase"]:kind==="status"?["afterSequence"]:[]);checkSession(parseManagedToolInvocationReference(op["reference"]),session);if(kind==="confirm"){if(!Object.values(ToolConfirmationOutcome).includes(op["outcome"])||op["outcome"]==="restore_previous")throw new ManagedRuntimeProviderProtocolError;if("payload"in op)parseManagedToolConfirmationPayload(op["payload"]);if("phase"in op&&!oneOf(op["phase"],["permission","preflight"]))throw new ManagedRuntimeProviderProtocolError}if("afterSequence"in op)sequence(op["afterSequence"]);break;case"bind-history":{keys(op,["kind","binding"]);const binding=parseManagedToolFileHistoryBinding(op["binding"]);if(binding.ownerSessionId!==session.harnessSessionId||binding.ownerRuntimeSessionId!==session.runtimeSessionId)throw new ManagedRuntimeProviderProtocolError("Managed Runtime file history owner conflicts.",409,"managed_runtime_identity_conflict");break}case"checkpoint":keys(op,["kind","promptId"]);parseManagedToolFileHistoryPromptId(op["promptId"]);break;default:throw new ManagedRuntimeProviderProtocolError("Managed Runtime provider operation is unsupported.",501,"managed_runtime_provider_unsupported")}return structuredClone(value)}__name(parseManagedRuntimeProviderOperation,"parseManagedRuntimeProviderOperation");function parseManagedRuntimeProviderRequest(value){const request=object(value);keys(request,["protocolVersion","providerProtocol","session","operation"]);if(request["protocolVersion"]!==1||request["providerProtocol"]!==MANAGED_RUNTIME_PROVIDER_PROTOCOL)throw new ManagedRuntimeProviderProtocolError("Managed Runtime provider protocol is incompatible.",409,"managed_runtime_provider_incompatible");const session=object(request["session"]);keys(session,["harnessSessionId","runtimeSessionId","turnKind"]);envelopeSessionId(session["harnessSessionId"]);envelopeSessionId(session["runtimeSessionId"]);if(!oneOf(session["turnKind"],["bootstrap","continuation"]))throw new ManagedRuntimeProviderProtocolError;const parsedSession=session;const parsed={protocolVersion:1,providerProtocol:MANAGED_RUNTIME_PROVIDER_PROTOCOL,session:structuredClone(parsedSession),operation:parseManagedRuntimeProviderOperation(request["operation"],parsedSession,true)};managedToolDigest(value,managedRuntimeProviderLimit(parsed.operation.kind));return parsed}__name(parseManagedRuntimeProviderRequest,"parseManagedRuntimeProviderRequest");function parseManagedRuntimeProviderResult(operation,value,session){managedToolDigest(value,managedRuntimeProviderLimit(operation.kind));if(operation.kind==="begin-turn"||operation.kind==="confirm"){if(value!==null)throw new ManagedRuntimeProviderProtocolError;return null}if(operation.kind==="acquire"||operation.kind==="release"){if(value!==true)throw new ManagedRuntimeProviderProtocolError;return true}const result=object(value);switch(operation.kind){case"raw-file-history":{if(operation.action!=="rewind")return parseHostedFileHistoryState(value,session.harnessSessionId);keys(result,["state","filesChanged","filesFailed","conflict"]);const state=parseHostedFileHistoryState(result["state"],session.harnessSessionId);if(!Array.isArray(result["filesChanged"])||!Array.isArray(result["filesFailed"])||typeof result["conflict"]!=="boolean")throw new ManagedRuntimeProviderProtocolError;result["filesChanged"].forEach(historyPath);result["filesFailed"].forEach(historyPath);if(new Set(result["filesChanged"]).size!==result["filesChanged"].length||result["filesChanged"].some(file=>!Object.hasOwn(state.files,file))||!state.snapshots.some(snapshot=>snapshot.promptId===operation.promptId)||result["conflict"]&&result["filesChanged"].length!==0)throw new ManagedRuntimeProviderProtocolError("Invalid Hosted file history rewind outcome.");break}case"workspace-context":{keys(result,["files"]);if(!Array.isArray(result["files"]))throw new ManagedRuntimeProviderProtocolError;let next=0;for(const entry of result["files"]){const file=object(entry);keys(file,["name","text"]);const index=MANAGED_WORKSPACE_CONTEXT_FILES.indexOf(file["name"]);if(index<next||typeof file["text"]!=="string"||file["text"].length>MANAGED_WORKSPACE_CONTEXT_FILE_CHARS)throw new ManagedRuntimeProviderProtocolError("Invalid Workspace context result.");next=index+1}return result["files"]}case"bind-history":case"checkpoint":case"history":{const state=parseManagedToolFileHistoryState(value);if(state.ownerSessionId!==session.harnessSessionId)throw new ManagedRuntimeProviderProtocolError("Managed file history owner changed.");return state}case"manifest":keys(result,["tools","capabilityDigest","policyRevision"]);id(result["policyRevision"]);if(!Array.isArray(result["tools"])||managedToolDigest(result["tools"],1024*1024)!==result["capabilityDigest"])throw new ManagedRuntimeProviderProtocolError("Managed tool manifest digest changed.");for(const tool of result["tools"]){const descriptor=object(tool);id(descriptor["name"]);object(descriptor["schema"])}break;case"prepare":{const reference=Object.fromEntries(["sessionId","promptId","callId","capabilityDigest","policyRevision","invocationId","argsDigest"].map(key=>[key,result[key]]));checkSession(parseManagedToolInvocationReference(reference),session);for(const[key,expected]of Object.entries(operation.identity))if(result[key]!==expected)throw new ManagedRuntimeProviderProtocolError;object(result["params"]);if(managedToolDigest(result["params"])!==result["argsDigest"]||typeof result["description"]!=="string"||!Array.isArray(result["locations"])||!oneOf(result["defaultPermission"],["allow","ask","deny","default"])||typeof result["requiresUserInteraction"]!=="boolean")throw new ManagedRuntimeProviderProtocolError;id(result["toolUseId"]);break}case"confirmation":{if(!oneOf(result["type"],["edit","exec","mcp","info"])||typeof result["title"]!=="string")throw new ManagedRuntimeProviderProtocolError;const required={edit:["fileName","filePath","fileDiff","newContent"],exec:["command","rootCommand"],mcp:["serverName","toolName","toolDisplayName"],info:["prompt"]}[result["type"]];if(required.some(key=>typeof result[key]!=="string")||result["type"]==="edit"&&result["originalContent"]!==null&&typeof result["originalContent"]!=="string")throw new ManagedRuntimeProviderProtocolError;break}case"preflight":if(typeof result["shouldProceed"]!=="boolean")throw new ManagedRuntimeProviderProtocolError;break;case"execute":if(!oneOf(result["executionStatus"],["not_started","success","error","cancelled"]))throw new ManagedRuntimeProviderProtocolError;if(result["executionStatus"]==="success")object(result["result"]);break;case"status":case"cancel":if(result["state"]==="unknown"){keys(result,["state"]);break}if(!oneOf(result["state"],["prepared","executing","cancel_requested","settled"])||typeof result["cancelRequested"]!=="boolean"||typeof result["progressGap"]!=="boolean"||!Array.isArray(result["progress"]))throw new ManagedRuntimeProviderProtocolError;sequence(result["lastSeq"]);sequence(result["firstAvailableSeq"]);if(result["state"]==="settled")parseManagedRuntimeProviderResult({kind:"execute",reference:operation.reference},result["result"],session);else if("result"in result)throw new ManagedRuntimeProviderProtocolError;break;default:throw new ManagedRuntimeProviderProtocolError}return structuredClone(value)}__name(parseManagedRuntimeProviderResult,"parseManagedRuntimeProviderResult");function providerFitNotice(omitted,budgetBytes){return`
|
|
4
4
|
[Managed Runtime provider omitted ${omitted} characters here to fit the ${budgetBytes}-byte wire limit.]
|
|
5
5
|
`}__name(providerFitNotice,"providerFitNotice");var PROVIDER_RESULT_STUB="[Managed Runtime provider omitted this tool result to fit the wire limit.]";function providerFitSlots(target){const slots=[];const collect=__name((owner,key,mark)=>{if(typeof owner[key]!=="string")return;slots.push({get:__name(()=>owner[key],"get"),set:__name(next=>{owner[key]=next;mark?.()},"set")})},"collect");const result=target["result"];if(result&&typeof result==="object"&&!Array.isArray(result)){const toolResult=result;const llmContent=toolResult["llmContent"];if(typeof llmContent==="string")collect(toolResult,"llmContent");else if(Array.isArray(llmContent)){for(const part of llmContent)if(part&&typeof part==="object"&&!Array.isArray(part))collect(part,"text")}const display=toolResult["returnDisplay"];if(typeof display==="string")collect(toolResult,"returnDisplay");else if(isShellResultDisplay(display)){const mark=__name(()=>{display.truncated=true},"mark");const record2=display;collect(record2,"output",mark);collect(record2,"text",mark);collect(record2,"error",mark);display.notices.forEach((_,index)=>slots.push({get:__name(()=>display.notices[index],"get"),set:__name(next=>{display.notices[index]=next;mark()},"set")}))}}const error=target["error"];if(error&&typeof error==="object"&&!Array.isArray(error))collect(error,"message");return slots}__name(providerFitSlots,"providerFitSlots");function jsonCodePointBytes(codePoint){if(codePoint===34||codePoint===92)return 2;if(codePoint<32)return[8,9,10,12,13].includes(codePoint)?2:6;if(codePoint<128)return 1;if(codePoint<2048)return 2;if(codePoint>=55296&&codePoint<=57343)return 6;return codePoint<65536?3:4}__name(jsonCodePointBytes,"jsonCodePointBytes");function jsonTextBytes(text2){return Buffer.byteLength(JSON.stringify(text2),"utf8")-2}__name(jsonTextBytes,"jsonTextBytes");function cutProviderFitSlot(slot,targetBytes,budgetBytes){const text2=slot.get();const size=jsonTextBytes(text2);if(size<=targetBytes)return;const keep=Math.max(0,targetBytes-jsonTextBytes(providerFitNotice(text2.length,budgetBytes)));let head=0;let headBytes=0;while(head<text2.length){const codePoint=text2.codePointAt(head);const cost=jsonCodePointBytes(codePoint);if(headBytes+cost>Math.ceil(keep/2))break;headBytes+=cost;head+=codePoint>65535?2:1}let tail=text2.length;let tailBytes=0;while(tail>head){let start=tail-1;const unit=text2.charCodeAt(start);if(unit>=56320&&unit<=57343&&start>head){const previous=text2.charCodeAt(start-1);if(previous>=55296&&previous<=56319)start--}const cost=jsonCodePointBytes(text2.codePointAt(start));if(headBytes+tailBytes+cost>keep)break;tailBytes+=cost;tail=start}let omitted=0;for(const _ of text2.slice(head,tail))omitted++;const next=text2.slice(0,head)+providerFitNotice(omitted,budgetBytes)+text2.slice(tail);if(omitted>0&&jsonTextBytes(next)<size)slot.set(next)}__name(cutProviderFitSlot,"cutProviderFitSlot");function providerFitShed(slots,level){return slots.reduce((shed,{bytes,floor})=>shed+Math.max(0,bytes-Math.max(level,floor)),0)}__name(providerFitShed,"providerFitShed");function providerFitLevel(slots,excess){let low=0;let high=slots.reduce((largest,{bytes})=>Math.max(largest,bytes),0);while(low<high){const middle=Math.ceil((low+high)/2);if(providerFitShed(slots,middle)>=excess)low=middle;else high=middle-1}return low}__name(providerFitLevel,"providerFitLevel");function fitManagedRuntimeProviderResult(operation,value,budgetBytes){if(operation.kind!=="execute"&&operation.kind!=="status"&&operation.kind!=="cancel")return value;if(!value||typeof value!=="object"||Array.isArray(value))return value;const root=value;const fits=__name(()=>Buffer.byteLength(JSON.stringify(root),"utf8")<=budgetBytes,"fits");const status=operation.kind==="execute"?void 0:root;const execution2=operation.kind==="execute"?root:status?.["result"];const toolResult=execution2?.["result"];const content=toolResult&&typeof toolResult==="object"&&!Array.isArray(toolResult)?toolResult["llmContent"]:void 0;const mediaResult=(Array.isArray(content)?content:[content]).some(part=>part!==null&&typeof part==="object"&&!Array.isArray(part)&&Object.hasOwn(part,"inlineData"));if(mediaResult){let mediaBytes;try{mediaBytes=managedToolResponseMediaBytes({executionStatus:execution2?.["executionStatus"],result:toolResult},"execute")}catch{throw new ManagedRuntimeProviderProtocolError("Managed Runtime provider returned invalid inline media.")}if(mediaBytes>MAX_PROVIDER_INLINE_MEDIA_BASE64_BYTES||Buffer.byteLength(JSON.stringify(toolResult),"utf8")>MAX_PROVIDER_MEDIA_RESULT_BYTES){throw new ManagedRuntimeProviderProtocolError("Managed Runtime provider media result exceeds its admitted budget.")}}if(fits())return value;const progress=status?.["progress"];if(status!==void 0&&Array.isArray(progress)&&progress.length>0){const lastSeq=typeof status["lastSeq"]==="number"?status["lastSeq"]:0;const sizes=progress.map(event=>Buffer.byteLength(JSON.stringify(event),"utf8")+1);let bytes=Buffer.byteLength(JSON.stringify(root),"utf8");let evict=0;while(evict<progress.length&&bytes>budgetBytes)bytes-=sizes[evict++];let retained=progress.slice(evict);while(true){status["progress"]=retained;const first=retained[0];status["firstAvailableSeq"]=first&&typeof first==="object"&&typeof first["seq"]==="number"?first["seq"]:lastSeq+1;status["progressGap"]=true;if(retained.length===0||Buffer.byteLength(JSON.stringify(root),"utf8")<=budgetBytes)break;retained=retained.slice(1)}}if(mediaResult&&execution2){if(!fits()){const hook=execution2["postHook"];if(hook&&typeof hook==="object"&&!Array.isArray(hook)&&typeof hook["shouldStop"]==="boolean"){const fields=hook;const reason=fields["stopReason"];const hookError=fields["hookError"];execution2["postHook"]={shouldStop:fields["shouldStop"],...typeof reason==="string"?{stopReason:reason}:{},...typeof hookError==="string"?{hookError}:{}}}else{delete execution2["postHook"]}delete execution2["failureHook"];const retained=execution2["postHook"];if(retained){const diagnostics=["stopReason","hookError"].filter(field=>typeof retained[field]==="string").sort((a,b)=>Buffer.byteLength(retained[b],"utf8")-Buffer.byteLength(retained[a],"utf8"));for(const field of diagnostics){if(fits())break;retained[field]=`Runtime Hook ${field} omitted to fit the media response.`}}}if(!fits())throw new ManagedRuntimeProviderProtocolError("Managed Runtime provider media observation exceeds its wire budget.");return value}if(execution2&&!fits()){const measure=__name(()=>providerFitSlots(execution2).map(slot=>({slot,bytes:jsonTextBytes(slot.get()),floor:jsonTextBytes(providerFitNotice(slot.get().length,budgetBytes))})),"measure");let slots=measure();const overflows=__name(()=>Buffer.byteLength(JSON.stringify(root),"utf8")-providerFitShed(slots,0)>budgetBytes,"overflows");const result=execution2["result"];const toolResult2=result&&typeof result==="object"&&!Array.isArray(result)?result:void 0;const display=toolResult2?.["returnDisplay"];if(toolResult2&&display!==void 0&&typeof display!=="string"&&overflows()){toolResult2["returnDisplay"]=PROVIDER_RESULT_STUB;slots=measure()}if(toolResult2&&toolResult2["artifacts"]!==void 0&&overflows())delete toolResult2["artifacts"];if(overflows()){delete execution2["postHook"];delete execution2["failureHook"]}if(!fits()){const level=providerFitLevel(slots,Buffer.byteLength(JSON.stringify(root),"utf8")-budgetBytes);for(const{slot,bytes}of slots)if(bytes>level)cutProviderFitSlot(slot,level,budgetBytes)}}if(!fits()&&execution2){const result=execution2["result"];if(result&&typeof result==="object"&&!Array.isArray(result))result["llmContent"]=PROVIDER_RESULT_STUB}return value}__name(fitManagedRuntimeProviderResult,"fitManagedRuntimeProviderResult");init_esbuild_shims();var WORKSPACE_EXECUTION_PROFILE="managed-workspace-execution/1";var WORKSPACE_CONTEXT_CONFIG_REF="sha256:5fa15183dcfe582ce54c28bf25aff62801d19038a9ec649e9bfc67b06f2a389f";var WORKSPACE_CAPABILITY_DIGEST="sha256:7df3981fa14b397fe09f6ba84ed0c096c71902394da667bf47f3b315866e7f91";var RESIDENT_WORKSPACE_PROFILE="resident-workspace-files/1";var RESIDENT_WORKSPACE_CAPABILITY_DIGEST="sha256:2cbf6f3825230848a65a546ec70714fbb2a53d1862a6caba73ae4cebf307b4ad";var WORKSPACE_ACTIVATION_ROUTE=Object.freeze({key:"activation",method:"POST",path:"/internal/managed-runtime/v3/activation",protocolVersion:1,requestBodyLimitBytes:16*1024,responseBodyLimitBytes:16*1024,cacheControl:"no-store"});var KEYS=["contextConfigRef","contextDigest","operation","profile","protocolVersion","sessionId"].join(",");var WorkspaceActivations=class{static{__name(this,"WorkspaceActivations")}sessions=new Map;isActive(sessionId){return this.sessions.get(sessionId)===true}register(app,boot,installations,executor){app.post(WORKSPACE_ACTIVATION_ROUTE.path,managedRuntimeNoStore,authorizeManagedRuntime(boot),managedRuntimeJsonBody(WORKSPACE_ACTIVATION_ROUTE.requestBodyLimitBytes),async(req,res)=>{const body=req.body;if(body===null||typeof body!=="object"||Array.isArray(body)||Object.keys(body).sort().join(",")!==KEYS){res.status(400).json({code:"managed_activation_invalid"});return}const request=body;const binding=typeof request["sessionId"]==="string"?installations.installed(request["sessionId"]):void 0;if(request["protocolVersion"]!==1||request["operation"]!=="activate"&&request["operation"]!=="release"||(boot.capabilityDigest===RESIDENT_WORKSPACE_CAPABILITY_DIGEST?boot.isolationClass!=="workspace"||request["profile"]!==RESIDENT_WORKSPACE_PROFILE:![WORKSPACE_CAPABILITY_DIGEST,...boot.managedExtensions?[MANAGED_EXTENSION_LINUX_CAPABILITY_DIGEST,MANAGED_EXTENSION_DEVELOPER_CAPABILITY_DIGEST]:[]].includes(boot.capabilityDigest)||request["profile"]!==WORKSPACE_EXECUTION_PROFILE)||binding===void 0||binding.contextConfigRef!==WORKSPACE_CONTEXT_CONFIG_REF||request["contextConfigRef"]!==binding.contextConfigRef||request["contextDigest"]!==computeManagedContextDigest(binding)){res.status(409).json({code:"managed_activation_conflict"});return}const sessionId=request["sessionId"];const active=request["operation"]==="activate";if(active&&(!executor.isAdmissionOpen||this.sessions.get(sessionId)===false||boot.capabilityDigest===RESIDENT_WORKSPACE_CAPABILITY_DIGEST&&[...this.sessions].some(([id3,admitted])=>id3!==sessionId&&admitted))){res.status(409).json({code:"managed_activation_conflict"});return}if(!active&&executor.hasActiveSession(sessionId)){await executor.stopBackgroundSession(sessionId);if(executor.hasActiveSession(sessionId)){res.status(409).json({code:"managed_activation_conflict"});return}}this.sessions.set(sessionId,active);res.json({...request,runtimeInstanceId:boot.runtimeInstanceId,runtimeIncarnation:boot.runtimeIncarnation,epoch:boot.epoch,active})},handleManagedRuntimeJsonError)}};init_esbuild_shims();var CSI_FILES_RETIREMENT_CAPABILITY_DIGEST="sha256:116dcd2afce7292bdf0bf4c76010964f7a7148ad512b2939e48e3d55ea91118d";init_esbuild_shims();import{createHash}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=closed(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=closed(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 reference;let acknowledgement;const context=createManagedContextAttestationResponse(boot.context);try{request=closed(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=closed(request["reference"],["argsDigest","callId","promptId","sessionId"]);if(!invocationDigest(ref2["argsDigest"]))throw new Error;reference={sessionId:stableId(ref2["sessionId"]),promptId:stableId(ref2["promptId"]),callId:stableId(ref2["callId"]),argsDigest:ref2["argsDigest"]};acknowledgement=parseManagedCsiAcknowledgement(request["acknowledgement"]);closed(request["context"],Object.keys(context).sort());closed(request["storage"],STORAGE_KEYS);closed(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,acknowledgement}}__name(parseManagedCsiAckRequest,"parseManagedCsiAckRequest");function parseManagedCsiAckResponse(value,boot,pod){try{const response=closed(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=closed(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=closed(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=closed(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=closed(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=closed(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=closed(response[key],Object.keys(expected).sort());if(!Object.entries(expected).every(([name,field])=>fields[name]===field))throw new Error}const mount=closed(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,positive){return typeof value==="string"&&/^(?:0|[1-9][0-9]{0,19})$/.test(value)&&(!positive||value!=="0")&&BigInt(value)<=maximum}__name(unsignedDecimal,"unsignedDecimal");var BOOT_KEYS=["context","managedCsi","storage","type","version"];var STORAGE_KEYS=["backendDomain","clusterDomain","diskSerial","driver","namespace","physicalKey","pvUid","pvcUid","registrationRevision","reservationId","reservationRevision","volumeHandle"];var INVALID="Managed CSI boot document is invalid.";function parseManagedCsiBoot(value){try{const boot=closed(value,BOOT_KEYS);const storage=closed(boot["storage"],STORAGE_KEYS);const context=parseManagedContextBoot(boot["context"]);if(boot["type"]!=="boot"||boot["version"]!==3||boot["managedCsi"]!==MANAGED_CSI_PROTOCOL){throw new Error(INVALID)}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(INVALID)}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(INVALID);return Object.freeze({type:"boot",version:3,managedCsi:MANAGED_CSI_PROTOCOL,context,storage:Object.freeze({...storage})})}catch{throw new Error(INVALID)}}__name(parseManagedCsiBoot,"parseManagedCsiBoot");function physicalKey(backend,driver,handle){const hash=createHash("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 closed(value,keys2){if(!value||typeof value!=="object"||Array.isArray(value))throw new Error(INVALID);const fields=Object.keys(value).sort();if(fields.length!==keys2.length||!fields.every((field,index)=>field===keys2[index]))throw new Error(INVALID);return value}__name(closed,"closed");init_esbuild_shims();import{isDeepStrictEqual}from"node:util";var MANAGED_CSI_FILE_PROTOCOL="managed-csi/2";var MANAGED_CSI_FILE_PREFIX="/internal/managed-runtime/csi/v2";var CSI_FILE_FINALIZATION_FORMAT="qwen-csi-file-finalize/1";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||value.version===6);const finalizationBoot=authorityBoot&&value.version===6;const boot=closed2(value,[...authorityBoot?["authority"]:[],"context",...finalizationBoot?["finalization"]:[],"identity","managedCsi","storage","type","version"]);const identity=closed2(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||finalizationBoot&&boot["finalization"]!==CSI_FILE_FINALIZATION_FORMAT||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 finalizationBoot?Object.freeze({...fields,version:6,authority:readManagedCsiNativeAuthority(boot["authority"]),finalization:CSI_FILE_FINALIZATION_FORMAT}):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=closed2(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 body=closed2(value,["context","identity","managedCsi","protocolVersion"]);checkIdentity(body,boot);return body["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(!isDeepStrictEqual(value,createManagedCsiFileAttestationRequest(boot)))throw new Error("CSI file identity conflicts.")}__name(validateManagedCsiFileAttestationRequest,"validateManagedCsiFileAttestationRequest");function validateManagedCsiFileAttestationResponse(value,boot,pod){const body=closed2(value,["context","identity","managedCsi","mount","pod","protocolVersion","storage"]);checkIdentity(body,boot);const{identity:_identity,...data}=body;validateManagedCsiAttestationResponse({...data,protocolVersion:1,managedCsi:MANAGED_CSI_PROTOCOL},dataBoot(boot),pod)}__name(validateManagedCsiFileAttestationResponse,"validateManagedCsiFileAttestationResponse");function readManagedCsiFileDrain(value,boot,pod){const body=closed2(value,["context","identity","managedCsi","operation","pod","protocolVersion","retirementId","storage"]);checkIdentity(body,boot);const{identity:_identity,...data}=body;return parseManagedCsiDrainRequest({...data,protocolVersion:1,managedCsi:MANAGED_CSI_PROTOCOL},dataBoot(boot),pod)}__name(readManagedCsiFileDrain,"readManagedCsiFileDrain");function checkIdentity(body,boot){if(body["protocolVersion"]!==2||body["managedCsi"]!==MANAGED_CSI_FILE_PROTOCOL||!isDeepStrictEqual(body["identity"],boot.identity))throw new Error("CSI file identity conflicts.")}__name(checkIdentity,"checkIdentity");function closed2(value,keys2){if(!value||typeof value!=="object"||Array.isArray(value)||!isDeepStrictEqual(Object.keys(value).sort(),keys2))throw new Error;return{...value}}__name(closed2,"closed");init_esbuild_shims();var import_toml=__toESM(require_toml(),1);import{createHash as createHash2}from"node:crypto";import*as fs from"node:fs/promises";import{createReadStream}from"node:fs";import*as path from"node:path";import*as os from"node:os";var MANAGED_PACKAGE_COMPILER_VERSION=1;var MANAGED_PACKAGE_MAX_ARCHIVE_BYTES=100*1024*1024;var ManagedPackageCompatibilityError=class extends Error{constructor(reasons){super(`Managed extension package is incompatible: ${reasons.join(", ")}`);this.reasons=reasons;this.name="ManagedPackageCompatibilityError"}static{__name(this,"ManagedPackageCompatibilityError")}};function object2(value,field){if(!value||typeof value!=="object"||Array.isArray(value))throw new ManagedPackageCompatibilityError([`${field}: invalid object`]);return value}__name(object2,"object");function text(value,field,maxBytes=512*1024){if(typeof value!=="string"||!value.trim()||Buffer.byteLength(value)>maxBytes)throw new ManagedPackageCompatibilityError([`${field}: invalid text`]);return value}__name(text,"text");function managedPackageRelativePath(value){const normalized=value.replace(/^\.\//,"");if(!normalized||normalized.includes("\\")||normalized.includes(":")||normalized.includes("\0")||normalized.startsWith("/")||normalized.split("/").some(part=>!part||part==="."||part===".."))throw new ManagedPackageCompatibilityError(["package resource path escapes its root"]);return normalized}__name(managedPackageRelativePath,"managedPackageRelativePath");function frontmatter(content){const parsed=parseMarkdownCommand(content);return{metadata:parsed.frontmatter??{},body:parsed.prompt}}__name(frontmatter,"frontmatter");function hasValue(value){return value!==void 0&&value!==null&&value!==false&&value!==""&&(!Array.isArray(value)||value.length>0)&&(typeof value!=="object"||Array.isArray(value)||Object.keys(value).length>0)}__name(hasValue,"hasValue");function rejectFields(value,fields,source){const reasons=fields.filter(key=>hasValue(value[key])).map(key=>`${source}.${key}: unsupported`);if(reasons.length)throw new ManagedPackageCompatibilityError(reasons)}__name(rejectFields,"rejectFields");var PRIVATE_FILES=new Set([".git",".env",".qwen-extension-settings.json",".qwen-extension-git-credentials.json",".qwen-extension-install.json"]);async function filesUnder(root,excludePrivate=false){const files=[];let total=0;const visit=__name(async relative=>{const entries=await fs.readdir(path.join(root,relative),{withFileTypes:true});for(const entry of entries.sort((a,b)=>a.name.localeCompare(b.name))){if(excludePrivate&&(PRIVATE_FILES.has(entry.name)||entry.name.startsWith(".env.")))continue;const name=relative?`${relative}/${entry.name}`:entry.name;managedPackageRelativePath(name);if(entry.isSymbolicLink()||!entry.isDirectory()&&!entry.isFile())throw new ManagedPackageCompatibilityError([`${name}: unsupported resource type`]);if(entry.isDirectory())await visit(name);else{total+=(await fs.lstat(path.join(root,name))).size;files.push(name);if(files.length>MAX_ARCHIVE_ENTRIES||total>MAX_ARCHIVE_EXPANDED_BYTES)throw new ManagedPackageCompatibilityError(["package resource limit exceeded"])}}},"visit");await visit("");return files}__name(filesUnder,"filesUnder");async function readText(root,relative){const file=managedPackageRelativePath(relative);const info=await fs.lstat(path.join(root,file));if(!info.isFile()||info.isSymbolicLink()||info.size>1024*1024)throw new ManagedPackageCompatibilityError([`${file}: invalid text resource`]);return new TextDecoder("utf-8",{fatal:true}).decode(await fs.readFile(path.join(root,file)))}__name(readText,"readText");async function readObject(root,relative){return object2(JSON.parse(await readText(root,relative)),relative)}__name(readObject,"readObject");async function rawConfig(root,files){if(files.includes("qwen-extension.json"))return readObject(root,"qwen-extension.json");if(files.includes("gemini-extension.json")){const raw=await readObject(root,"gemini-extension.json");rejectFields(raw,["lspServers","channels","workflows","executor","outputStyles"],"gemini-extension.json");return{...raw,...convertGeminiToQwenConfig(root)}}const pluginFile=files.includes(".claude-plugin/plugin.json")?".claude-plugin/plugin.json":files.includes(".qoder-plugin/plugin.json")?".qoder-plugin/plugin.json":void 0;if(pluginFile){const raw=await readObject(root,pluginFile);rejectFields(raw,["lspServers","channels","workflows","outputStyles","executor"],pluginFile);const config={...convertClaudeToQwenConfig(raw),name:raw["name"],version:raw["version"]??"1.0.0"};for(const key of["commands","skills","agents","contextFileName","settings","mcpServers","hooks"])if(raw[key]!==void 0)config[key]=raw[key];return config}if(files.includes("plugin.json")){const raw=await readObject(root,"plugin.json");if(raw["$schema"]!=="https://agent-plugins.org/schemas/1.0.0/plugin.schema.json")throw new ManagedPackageCompatibilityError(["plugin.json: unsupported schema"]);rejectFields(raw,["lspServers","channels","workflows","executor","outputStyles"],"plugin.json");return{...raw,name:raw["name"],version:raw["version"]??"1.0.0"}}throw new ManagedPackageCompatibilityError(["extension manifest missing"])}__name(rawConfig,"rawConfig");function resourceRoots(config,key,fallback){const value=config[key]??fallback;const roots=typeof value==="string"?[value]:value;if(!Array.isArray(roots)||roots.some(item=>typeof item!=="string"))throw new ManagedPackageCompatibilityError([`${key}: invalid resource roots`]);return roots.map(managedPackageRelativePath)}__name(resourceRoots,"resourceRoots");function selectedFiles(files,roots){return files.filter(file=>roots.some(root=>file===root||file.startsWith(`${root}/`)))}__name(selectedFiles,"selectedFiles");function strings(value,field){if(value===void 0)return void 0;const entries=typeof value==="string"?value.split(",").map(item=>item.trim()).filter(Boolean):value;if(!Array.isArray(entries)||entries.some(entry=>typeof entry!=="string"||!entry))throw new ManagedPackageCompatibilityError([`${field}: invalid list`]);return entries.map(entry=>resolveBuiltinToolName(entry)??entry)}__name(strings,"strings");async function compileManagedExtensionPackage(root,options){const files=await filesUnder(root);if(files.some(file=>file.split("/").some(part=>PRIVATE_FILES.has(part)||part.startsWith(".env."))))throw new ManagedPackageCompatibilityError(["package contains private settings or credentials"]);const config=await rawConfig(root,files);let packageTarget=options.target;if(config["managedTarget"]!==void 0){const target=object2(config["managedTarget"],"managedTarget");if(target["platform"]!==options.target.platform||target["arch"]!=="any"&&target["arch"]!==options.target.arch){throw new ManagedPackageCompatibilityError(["package target does not match this Runtime"])}packageTarget={platform:options.target.platform,arch:target["arch"]}}rejectFields(config,["lspServers","channels","workflows","executor","outputStyles"],"manifest");if(files.some(file=>/^(?:workflows|channels|lsp)\//.test(file)))throw new ManagedPackageCompatibilityError(["package contains unsupported executable components"]);const name=text(config["name"],"name",128);if(!/^[A-Za-z0-9][A-Za-z0-9_.-]*$/.test(name))throw new ManagedPackageCompatibilityError(["name: invalid identity"]);const contributions={skills:[],commands:[],agents:[],context:[],mcpServers:{},hooks:{},settings:[]};for(const file of selectedFiles(files,resourceRoots(config,"skills","skills")).filter(file2=>file2.endsWith("/SKILL.md"))){const content=await readText(root,file);const{metadata}=frontmatter(content);rejectFields(metadata,["allowedTools","allowed-tools","hooks","paths","arguments","args-file"],file);if(metadata["model"]!==void 0&&metadata["model"]!=="inherit")throw new ManagedPackageCompatibilityError([`${file}.model: unsupported`]);const skill=parseSkillContent(content,file);contributions.skills.push({name:qualifySkillName(name,skill.name),description:skill.description,body:skill.body,assetDirectory:path.posix.dirname(file),model_invocable:skill.disableModelInvocation!==true,user_invocable:skill.userInvocable!==false})}const commandRoots=resourceRoots(config,"commands","commands");for(const file of selectedFiles(files,commandRoots).filter(file2=>/\.(?:md|toml)$/.test(file2))){const content=await readText(root,file);const parsed=file.endsWith(".toml")?{metadata:{},body:"",definition:object2((0,import_toml.parse)(content),file)}:{...frontmatter(content),definition:void 0};if(!parsed.definition)MarkdownCommandDefSchema.parse({frontmatter:parsed.metadata,prompt:parsed.body});const metadata=parsed.definition??parsed.metadata;rejectFields(metadata,["allowed-tools","allowedTools","hooks","model","context","agent"],file);const relative=commandRoots.find(entry=>file.startsWith(`${entry}/`));const authored=(relative?file.slice(relative.length+1):path.posix.basename(file)).replace(/\.(?:md|toml)$/,"").split("/").map(part=>part.replaceAll(":","_")).join(":");contributions.commands.push({name:`${name}:${authored}`,description:typeof metadata["description"]==="string"?metadata["description"]:authored,prompt:text(parsed.definition?.["prompt"]??parsed.body,file),...typeof metadata["argument-hint"]==="string"?{argumentHint:metadata["argument-hint"]}:{},modelInvocable:metadata["disable-model-invocation"]!==true&&metadata["disable-model-invocation"]!=="true"})}for(const file of selectedFiles(files,resourceRoots(config,"agents","agents")).filter(file2=>file2.endsWith(".md"))){const{metadata,body}=frontmatter(await readText(root,file));rejectFields(metadata,["mcpServers","mcp_servers","hooks","executor","container","isolation","skills","permissionMode","approvalMode","background","memory"],file);const agent={name:`${name}:${text(metadata["name"]??path.posix.basename(file,".md"),file,128)}`,description:text(metadata["description"],`${file}.description`,4096),systemPrompt:text(body,file),...metadata["tools"]!==void 0?{tools:strings(metadata["tools"],file)}:{},...metadata["disallowedTools"]!==void 0?{disallowedTools:strings(metadata["disallowedTools"],file)}:{},...metadata["model"]!==void 0?{model:text(metadata["model"],`${file}.model`,512)}:{}};contributions.agents.push(agent)}const contextRoots=config["contextFileName"]===void 0?files.includes("QWEN.md")?["QWEN.md"]:files.includes("system-prompt.md")?["system-prompt.md"]:[]:resourceRoots(config,"contextFileName","QWEN.md");for(const file of contextRoots)contributions.context.push({path:file,body:await readText(root,file)});let mcp=config["mcpServers"];if(typeof mcp==="string")mcp=await readObject(root,managedPackageRelativePath(mcp));if(mcp===void 0&&files.includes(".mcp.json")){const loaded=await readObject(root,".mcp.json");mcp=loaded["mcpServers"]??loaded}if(mcp===void 0&&files.includes("mcp.json")){const loaded=await readObject(root,"mcp.json");mcp=loaded["mcpServers"]??loaded["servers"]??loaded}if(mcp!==void 0)contributions.mcpServers=object2(mcp,"mcpServers");let hooks=config["hooks"];if(typeof hooks==="string")hooks=await readObject(root,managedPackageRelativePath(hooks));if(hooks===void 0&&files.includes("hooks/hooks.json"))hooks=await readObject(root,"hooks/hooks.json");if(hooks!==void 0){const loaded=object2(hooks,"hooks");contributions.hooks=object2(loaded["hooks"]??loaded,"hooks")}if(config["settings"]!==void 0){if(!Array.isArray(config["settings"]))throw new ManagedPackageCompatibilityError(["settings: invalid list"]);contributions.settings=config["settings"].map(entry=>{const setting=object2(entry,"setting");const envVar=text(setting["envVar"],"setting.envVar",128);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(envVar)||envVar.startsWith("QWEN_MANAGED_")||["QWEN_EXTENSION_ROOT","CLAUDE_PLUGIN_ROOT","extensionPath","workspacePath"].includes(envVar))throw new ManagedPackageCompatibilityError(["setting.envVar: reserved or invalid"]);return{name:text(setting["name"],"setting.name",512),envVar,sensitive:setting["sensitive"]===true}})}if(options.resolveRecipes!==false){const environment={...options.environment,extensionPath:root,CLAUDE_PLUGIN_ROOT:root,QWEN_EXTENSION_ROOT:root,workspacePath:options.workspaceDirectory??"",workspaceFolder:options.workspaceDirectory??"",pathSeparator:"/","/":"/"};const hydrate=__name(value=>{if(typeof value==="string")return value.replace(/\$\{([^}]+)\}/g,(_,variable)=>{if(!Object.hasOwn(environment,variable))throw new ManagedPackageCompatibilityError([`setting ${variable}: required`]);return environment[variable]});if(Array.isArray(value))return value.map(hydrate);if(value&&typeof value==="object")return Object.fromEntries(Object.entries(value).map(([key,item])=>[key,hydrate(item)]));return value},"hydrate");contributions.mcpServers=hydrate(contributions.mcpServers);contributions.hooks=hydrate(contributions.hooks)}for(const entries of[contributions.skills,contributions.commands,contributions.agents]){if(new Set(entries.map(entry=>entry.name)).size!==entries.length)throw new ManagedPackageCompatibilityError(["duplicate component identity"])}if(contributions.skills.length>256||Object.keys(contributions.mcpServers).length>16)throw new ManagedPackageCompatibilityError(["component catalog limit exceeded"]);const components=[];if(contributions.skills.length)components.push("skills");if(contributions.commands.length)components.push("commands");if(contributions.agents.length)components.push("agents");if(contributions.context.length)components.push("context");if(Object.keys(contributions.mcpServers).length)components.push("mcp");if(Object.keys(contributions.hooks).length)components.push("hooks");if(contributions.settings.length)components.push("settings");return{manifest:{schemaVersion:1,compilerVersion:MANAGED_PACKAGE_COMPILER_VERSION,name,version:text(config["version"]??"1.0.0","version",128),target:packageTarget,components,...config["managedSource"]?{sourceType:text(object2(config["managedSource"],"managedSource")["type"],"sourceType",64),sourceRevision:text(object2(config["managedSource"],"managedSource")["revision"],"sourceRevision",256)}:{}},contributions}}__name(compileManagedExtensionPackage,"compileManagedExtensionPackage");async function prepareManagedExtensionPackage(source,options){if(["local","link","snapshot"].includes(source.type)){const isDirectory=(await fs.stat(source.source)).isDirectory();const installed=isDirectory&&await fs.lstat(path.join(source.source,".qwen-extension-install.json")).catch(error=>{if(error.code!=="ENOENT")throw error;return void 0});if(installed)throw new ManagedPackageCompatibilityError(["installed package requires its original source"])}const temporary=await fs.mkdtemp(path.join(os.tmpdir(),"qwen-managed-package-"));const root=path.join(temporary,"package");await fs.mkdir(root);let sourceRevision=source.ref??"";try{if(source.type==="git")sourceRevision=await cloneFromGit(source,root,options.signal);else if(source.type==="npm"){const result=await downloadFromNpmRegistry({...source},root,options.signal,{enforceResourceLimits:true});sourceRevision=result.version}else if(source.type==="github-release"){const result=await downloadFromGitHubRelease(source,root,options.signal,options.target,{enforceResourceLimits:true});sourceRevision=result.tagName}else if(source.type==="archive-url")await downloadFromArchiveUrl(source,root,options.signal,{enforceResourceLimits:true});else if(/\.(?:zip|tar\.gz)$/i.test(source.source))await extractArchiveFile(source.source,root,options.signal,{enforceResourceLimits:true});else{const files2=await filesUnder(source.source,true);for(const file of files2){const destination=path.join(root,file);await fs.mkdir(path.dirname(destination),{recursive:true});await fs.copyFile(path.join(source.source,file),destination)}}options.signal?.throwIfAborted();const scrub=__name(async directory=>{for(const entry of await fs.readdir(directory,{withFileTypes:true})){const file=path.join(directory,entry.name);if(PRIVATE_FILES.has(entry.name)||entry.name.startsWith(".env.")){await fs.rm(file,{recursive:true,force:true})}else if(entry.isDirectory())await scrub(file)}},"scrub");await scrub(root);let files=await filesUnder(root);const config=await rawConfig(root,files);config["managedTarget"]=options.target;config["managedSource"]={type:source.type==="local"?/\.(?:zip|tar\.gz)$/i.test(source.source)?"archive":"directory":source.type,revision:sourceRevision||text(config["version"]??"snapshot","version",128)};await fs.writeFile(path.join(root,"qwen-extension.json"),JSON.stringify(config));files=await filesUnder(root);const compiled=await compileManagedExtensionPackage(root,{target:options.target,resolveRecipes:false});await fs.mkdir(options.destination,{recursive:true});const archivePath=path.join(options.destination,"package.tar.gz");await Qn({cwd:root,file:archivePath,gzip:true,portable:true,noMtime:true},files.sort());if((await fs.stat(archivePath)).size>MANAGED_PACKAGE_MAX_ARCHIVE_BYTES)throw new ManagedPackageCompatibilityError(["compressed package limit exceeded"]);const hash=createHash2("sha256");for await(const chunk of createReadStream(archivePath))hash.update(chunk);const packageDigest=hash.digest("hex");return{archivePath,packageDigest,manifest:compiled.manifest,sourceRevision:sourceRevision||packageDigest}}finally{await fs.rm(temporary,{recursive:true,force:true})}}__name(prepareManagedExtensionPackage,"prepareManagedExtensionPackage");init_esbuild_shims();var import_brace_expansion=__toESM(require_brace_expansion(),1);init_esbuild_shims();var MAX_PATTERN_LENGTH=1024*64;var assertValidPattern=__name(pattern=>{if(typeof pattern!=="string"){throw new TypeError("invalid pattern")}if(pattern.length>MAX_PATTERN_LENGTH){throw new TypeError("pattern is too long")}},"assertValidPattern");init_esbuild_shims();init_esbuild_shims();var posixClasses={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",true],"[:alpha:]":["\\p{L}\\p{Nl}",true],"[:ascii:]":["\\x00-\\x7f",false],"[:blank:]":["\\p{Zs}\\t",true],"[:cntrl:]":["\\p{Cc}",true],"[:digit:]":["\\p{Nd}",true],"[:graph:]":["\\p{Z}\\p{C}",true,true],"[:lower:]":["\\p{Ll}",true],"[:print:]":["\\p{C}",true],"[:punct:]":["\\p{P}",true],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",true],"[:upper:]":["\\p{Lu}",true],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",true],"[:xdigit:]":["A-Fa-f0-9",false]};var braceEscape=__name(s=>s.replace(/[[\]\\-]/g,"\\$&"),"braceEscape");var regexpEscape=__name(s=>s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),"regexpEscape");var rangesToString=__name(ranges=>ranges.join(""),"rangesToString");var parseClass=__name((glob,position)=>{const pos=position;if(glob.charAt(pos)!=="["){throw new Error("not in a brace expression")}const ranges=[];const negs=[];let i=pos+1;let sawStart=false;let uflag=false;let escaping=false;let negate=false;let endPos=pos;let rangeStart="";WHILE:while(i<glob.length){const c=glob.charAt(i);if((c==="!"||c==="^")&&i===pos+1){negate=true;i++;continue}if(c==="]"&&sawStart&&!escaping){endPos=i+1;break}sawStart=true;if(c==="\\"){if(!escaping){escaping=true;i++;continue}}if(c==="["&&!escaping){for(const[cls,[unip,u,neg]]of Object.entries(posixClasses)){if(glob.startsWith(cls,i)){if(rangeStart){return["$.",false,glob.length-pos,true]}i+=cls.length;if(neg)negs.push(unip);else ranges.push(unip);uflag=uflag||u;continue WHILE}}}escaping=false;if(rangeStart){if(c>rangeStart){ranges.push(braceEscape(rangeStart)+"-"+braceEscape(c))}else if(c===rangeStart){ranges.push(braceEscape(c))}rangeStart="";i++;continue}if(glob.startsWith("-]",i+1)){ranges.push(braceEscape(c+"-"));i+=2;continue}if(glob.startsWith("-",i+1)){rangeStart=c;i+=2;continue}ranges.push(braceEscape(c));i++}if(endPos<i){return["",false,0,false]}if(!ranges.length&&!negs.length){return["$.",false,glob.length-pos,true]}if(negs.length===0&&ranges.length===1&&/^\\?.$/.test(ranges[0])&&!negate){const r=ranges[0].length===2?ranges[0].slice(-1):ranges[0];return[regexpEscape(r),false,endPos-pos,false]}const sranges="["+(negate?"^":"")+rangesToString(ranges)+"]";const snegs="["+(negate?"":"^")+rangesToString(negs)+"]";const comb=ranges.length&&negs.length?"("+sranges+"|"+snegs+")":ranges.length?sranges:snegs;return[comb,uflag,endPos-pos,true]},"parseClass");init_esbuild_shims();var unescape=__name((s,{windowsPathsNoEscape=false}={})=>{return windowsPathsNoEscape?s.replace(/\[([^\/\\])\]/g,"$1"):s.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1")},"unescape");var _a;var types=new Set(["!","?","+","*","@"]);var isExtglobType=__name(c=>types.has(c),"isExtglobType");var isExtglobAST=__name(c=>isExtglobType(c.type),"isExtglobAST");var adoptionMap=new Map([["!",["@"]],["?",["?","@"]],["@",["@"]],["*",["*","+","?","@"]],["+",["+","@"]]]);var adoptionWithSpaceMap=new Map([["!",["?"]],["@",["?"]],["+",["?","*"]]]);var adoptionAnyMap=new Map([["!",["?","@"]],["?",["?","@"]],["@",["?","@"]],["*",["*","+","?","@"]],["+",["+","@","?","*"]]]);var usurpMap=new Map([["!",new Map([["!","@"]])],["?",new Map([["*","*"],["+","*"]])],["@",new Map([["!","!"],["?","?"],["@","@"],["*","*"],["+","+"]])],["+",new Map([["?","*"],["*","*"]])]]);var startNoTraversal="(?!(?:^|/)\\.\\.?(?:$|/))";var startNoDot="(?!\\.)";var addPatternStart=new Set(["[","."]);var justDots=new Set(["..","."]);var reSpecials=new Set("().*{}+?[]^$\\!");var regExpEscape=__name(s=>s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),"regExpEscape");var qmark="[^/]";var star=qmark+"*?";var starNoEmpty=qmark+"+?";var AST=class{static{__name(this,"AST")}type;#root;#hasMagic;#uflag=false;#parts=[];#parent;#parentIndex;#negs;#filledNegs=false;#options;#toString;#emptyExt=false;constructor(type,parent,options={}){this.type=type;if(type)this.#hasMagic=true;this.#parent=parent;this.#root=this.#parent?this.#parent.#root:this;this.#options=this.#root===this?options:this.#root.#options;this.#negs=this.#root===this?[]:this.#root.#negs;if(type==="!"&&!this.#root.#filledNegs)this.#negs.push(this);this.#parentIndex=this.#parent?this.#parent.#parts.length:0}get hasMagic(){if(this.#hasMagic!==void 0)return this.#hasMagic;for(const p of this.#parts){if(typeof p==="string")continue;if(p.type||p.hasMagic)return this.#hasMagic=true}return this.#hasMagic}toString(){if(this.#toString!==void 0)return this.#toString;if(!this.type){return this.#toString=this.#parts.map(p=>String(p)).join("")}else{return this.#toString=this.type+"("+this.#parts.map(p=>String(p)).join("|")+")"}}#fillNegs(){if(this!==this.#root)throw new Error("should only call on root");if(this.#filledNegs)return this;this.toString();this.#filledNegs=true;let n;while(n=this.#negs.pop()){if(n.type!=="!")continue;let p=n;let pp=p.#parent;while(pp){for(let i=p.#parentIndex+1;!pp.type&&i<pp.#parts.length;i++){for(const part of n.#parts){if(typeof part==="string"){throw new Error("string part in extglob AST??")}part.copyIn(pp.#parts[i])}}p=pp;pp=p.#parent}}return this}push(...parts){for(const p of parts){if(p==="")continue;if(typeof p!=="string"&&!(p instanceof _a&&p.#parent===this)){throw new Error("invalid part: "+p)}this.#parts.push(p)}}toJSON(){const ret=this.type===null?this.#parts.slice().map(p=>typeof p==="string"?p:p.toJSON()):[this.type,...this.#parts.map(p=>p.toJSON())];if(this.isStart()&&!this.type)ret.unshift([]);if(this.isEnd()&&(this===this.#root||this.#root.#filledNegs&&this.#parent?.type==="!")){ret.push({})}return ret}isStart(){if(this.#root===this)return true;if(!this.#parent?.isStart())return false;if(this.#parentIndex===0)return true;const p=this.#parent;for(let i=0;i<this.#parentIndex;i++){const pp=p.#parts[i];if(!(pp instanceof _a&&pp.type==="!")){return false}}return true}isEnd(){if(this.#root===this)return true;if(this.#parent?.type==="!")return true;if(!this.#parent?.isEnd())return false;if(!this.type)return this.#parent?.isEnd();const pl=this.#parent?this.#parent.#parts.length:0;return this.#parentIndex===pl-1}copyIn(part){if(typeof part==="string")this.push(part);else this.push(part.clone(this))}clone(parent){const c=new _a(this.type,parent);for(const p of this.#parts){c.copyIn(p)}return c}static#parseAST(str,ast,pos,opt,extDepth){const maxDepth=opt.maxExtglobRecursion??2;let escaping=false;let inBrace=false;let braceStart=-1;let braceNeg=false;if(ast.type===null){let i2=pos;let acc2="";while(i2<str.length){const c=str.charAt(i2++);if(escaping||c==="\\"){escaping=!escaping;acc2+=c;continue}if(inBrace){if(i2===braceStart+1){if(c==="^"||c==="!"){braceNeg=true}}else if(c==="]"&&!(i2===braceStart+2&&braceNeg)){inBrace=false}acc2+=c;continue}else if(c==="["){inBrace=true;braceStart=i2;braceNeg=false;acc2+=c;continue}const doRecurse=!opt.noext&&isExtglobType(c)&&str.charAt(i2)==="("&&extDepth<=maxDepth;if(doRecurse){ast.push(acc2);acc2="";const ext2=new _a(c,ast);i2=_a.#parseAST(str,ext2,i2,opt,extDepth+1);ast.push(ext2);continue}acc2+=c}ast.push(acc2);return i2}let i=pos+1;let part=new _a(null,ast);const parts=[];let acc="";while(i<str.length){const c=str.charAt(i++);if(escaping||c==="\\"){escaping=!escaping;acc+=c;continue}if(inBrace){if(i===braceStart+1){if(c==="^"||c==="!"){braceNeg=true}}else if(c==="]"&&!(i===braceStart+2&&braceNeg)){inBrace=false}acc+=c;continue}else if(c==="["){inBrace=true;braceStart=i;braceNeg=false;acc+=c;continue}const doRecurse=isExtglobType(c)&&str.charAt(i)==="("&&(extDepth<=maxDepth||ast&&ast.#canAdoptType(c));if(doRecurse){const depthAdd=ast&&ast.#canAdoptType(c)?0:1;part.push(acc);acc="";const ext2=new _a(c,part);part.push(ext2);i=_a.#parseAST(str,ext2,i,opt,extDepth+depthAdd);continue}if(c==="|"){part.push(acc);acc="";parts.push(part);part=new _a(null,ast);continue}if(c===")"){if(acc===""&&ast.#parts.length===0){ast.#emptyExt=true}part.push(acc);acc="";ast.push(...parts,part);return i}acc+=c}ast.type=null;ast.#hasMagic=void 0;ast.#parts=[str.substring(pos-1)];return i}#canAdoptWithSpace(child){return this.#canAdopt(child,adoptionWithSpaceMap)}#canAdopt(child,map=adoptionMap){if(!child||typeof child!=="object"||child.type!==null||child.#parts.length!==1||this.type===null){return false}const gc=child.#parts[0];if(!gc||typeof gc!=="object"||gc.type===null){return false}return this.#canAdoptType(gc.type,map)}#canAdoptType(c,map=adoptionAnyMap){return!!map.get(this.type)?.includes(c)}#adoptWithSpace(child,index){const gc=child.#parts[0];const blank=new _a(null,gc,this.options);blank.#parts.push("");gc.push(blank);this.#adopt(child,index)}#adopt(child,index){const gc=child.#parts[0];this.#parts.splice(index,1,...gc.#parts);for(const p of gc.#parts){if(typeof p==="object")p.#parent=this}this.#toString=void 0}#canUsurpType(c){const m=usurpMap.get(this.type);return!!m?.has(c)}#canUsurp(child){if(!child||typeof child!=="object"||child.type!==null||child.#parts.length!==1||this.type===null||this.#parts.length!==1){return false}const gc=child.#parts[0];if(!gc||typeof gc!=="object"||gc.type===null){return false}return this.#canUsurpType(gc.type)}#usurp(child){const m=usurpMap.get(this.type);const gc=child.#parts[0];const nt=m?.get(gc.type);if(!nt)return false;this.#parts=gc.#parts;for(const p of this.#parts){if(typeof p==="object")p.#parent=this}this.type=nt;this.#toString=void 0;this.#emptyExt=false}#flatten(){if(!isExtglobAST(this)){for(const p of this.#parts){if(typeof p==="object")p.#flatten()}}else{let iterations=0;let done=false;do{done=true;for(let i=0;i<this.#parts.length;i++){const c=this.#parts[i];if(typeof c==="object"){c.#flatten();if(this.#canAdopt(c)){done=false;this.#adopt(c,i)}else if(this.#canAdoptWithSpace(c)){done=false;this.#adoptWithSpace(c,i)}else if(this.#canUsurp(c)){done=false;this.#usurp(c)}}}}while(!done&&++iterations<10)}this.#toString=void 0}static fromGlob(pattern,options={}){const ast=new _a(null,void 0,options);_a.#parseAST(pattern,ast,0,options,0);return ast}toMMPattern(){if(this!==this.#root)return this.#root.toMMPattern();const glob=this.toString();const[re,body,hasMagic,uflag]=this.toRegExpSource();const anyMagic=hasMagic||this.#hasMagic||this.#options.nocase&&!this.#options.nocaseMagicOnly&&glob.toUpperCase()!==glob.toLowerCase();if(!anyMagic){return body}const flags=(this.#options.nocase?"i":"")+(uflag?"u":"");return Object.assign(new RegExp(`^${re}$`,flags),{_src:re,_glob:glob})}get options(){return this.#options}toRegExpSource(allowDot){const dot=allowDot??!!this.#options.dot;if(this.#root===this){this.#flatten();this.#fillNegs()}if(!isExtglobAST(this)){const noEmpty=this.isStart()&&this.isEnd();const src=this.#parts.map(p=>{const[re,_,hasMagic,uflag]=typeof p==="string"?_a.#parseGlob(p,this.#hasMagic,noEmpty):p.toRegExpSource(allowDot);this.#hasMagic=this.#hasMagic||hasMagic;this.#uflag=this.#uflag||uflag;return re}).join("");let start2="";if(this.isStart()){if(typeof this.#parts[0]==="string"){const dotTravAllowed=this.#parts.length===1&&justDots.has(this.#parts[0]);if(!dotTravAllowed){const aps=addPatternStart;const needNoTrav=dot&&aps.has(src.charAt(0))||src.startsWith("\\.")&&aps.has(src.charAt(2))||src.startsWith("\\.\\.")&&aps.has(src.charAt(4));const needNoDot=!dot&&!allowDot&&aps.has(src.charAt(0));start2=needNoTrav?startNoTraversal:needNoDot?startNoDot:""}}}let end="";if(this.isEnd()&&this.#root.#filledNegs&&this.#parent?.type==="!"){end="(?:$|\\/)"}const final2=start2+src+end;return[final2,unescape(src),this.#hasMagic=!!this.#hasMagic,this.#uflag]}const repeated=this.type==="*"||this.type==="+";const start=this.type==="!"?"(?:(?!(?:":"(?:";let body=this.#partsToRegExp(dot);if(this.isStart()&&this.isEnd()&&!body&&this.type!=="!"){const s=this.toString();const me=this;me.#parts=[s];me.type=null;me.#hasMagic=void 0;return[s,unescape(this.toString()),false,false]}let bodyDotAllowed=!repeated||allowDot||dot||!startNoDot?"":this.#partsToRegExp(true);if(bodyDotAllowed===body){bodyDotAllowed=""}if(bodyDotAllowed){body=`(?:${body})(?:${bodyDotAllowed})*?`}let final="";if(this.type==="!"&&this.#emptyExt){final=(this.isStart()&&!dot?startNoDot:"")+starNoEmpty}else{const close=this.type==="!"?"))"+(this.isStart()&&!dot&&!allowDot?startNoDot:"")+star+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&bodyDotAllowed?")":this.type==="*"&&bodyDotAllowed?`)?`:`)${this.type}`;final=start+body+close}return[final,unescape(body),this.#hasMagic=!!this.#hasMagic,this.#uflag]}#partsToRegExp(dot){return this.#parts.map(p=>{if(typeof p==="string"){throw new Error("string type in extglob ast??")}const[re,_,_hasMagic,uflag]=p.toRegExpSource(dot);this.#uflag=this.#uflag||uflag;return re}).filter(p=>!(this.isStart()&&this.isEnd())||!!p).join("|")}static#parseGlob(glob,hasMagic,noEmpty=false){let escaping=false;let re="";let uflag=false;let inStar=false;for(let i=0;i<glob.length;i++){const c=glob.charAt(i);if(escaping){escaping=false;re+=(reSpecials.has(c)?"\\":"")+c;inStar=false;continue}if(c==="\\"){if(i===glob.length-1){re+="\\\\"}else{escaping=true}continue}if(c==="["){const[src,needUflag,consumed,magic]=parseClass(glob,i);if(consumed){re+=src;uflag=uflag||needUflag;i+=consumed-1;hasMagic=hasMagic||magic;inStar=false;continue}}if(c==="*"){if(inStar)continue;inStar=true;re+=noEmpty&&/^[*]+$/.test(glob)?starNoEmpty:star;hasMagic=true;continue}else{inStar=false}if(c==="?"){re+=qmark;hasMagic=true;continue}re+=regExpEscape(c)}return[re,unescape(glob),!!hasMagic,uflag]}};_a=AST;init_esbuild_shims();var escape=__name((s,{windowsPathsNoEscape=false}={})=>{return windowsPathsNoEscape?s.replace(/[?*()[\]]/g,"[$&]"):s.replace(/[?*()[\]\\]/g,"\\$&")},"escape");var minimatch=__name((p,pattern,options={})=>{assertValidPattern(pattern);if(!options.nocomment&&pattern.charAt(0)==="#"){return false}return new Minimatch(pattern,options).match(p)},"minimatch");var starDotExtRE=/^\*+([^+@!?\*\[\(]*)$/;var starDotExtTest=__name(ext2=>f=>!f.startsWith(".")&&f.endsWith(ext2),"starDotExtTest");var starDotExtTestDot=__name(ext2=>f=>f.endsWith(ext2),"starDotExtTestDot");var starDotExtTestNocase=__name(ext2=>{ext2=ext2.toLowerCase();return f=>!f.startsWith(".")&&f.toLowerCase().endsWith(ext2)},"starDotExtTestNocase");var starDotExtTestNocaseDot=__name(ext2=>{ext2=ext2.toLowerCase();return f=>f.toLowerCase().endsWith(ext2)},"starDotExtTestNocaseDot");var starDotStarRE=/^\*+\.\*+$/;var starDotStarTest=__name(f=>!f.startsWith(".")&&f.includes("."),"starDotStarTest");var starDotStarTestDot=__name(f=>f!=="."&&f!==".."&&f.includes("."),"starDotStarTestDot");var dotStarRE=/^\.\*+$/;var dotStarTest=__name(f=>f!=="."&&f!==".."&&f.startsWith("."),"dotStarTest");var starRE=/^\*+$/;var starTest=__name(f=>f.length!==0&&!f.startsWith("."),"starTest");var starTestDot=__name(f=>f.length!==0&&f!=="."&&f!=="..","starTestDot");var qmarksRE=/^\?+([^+@!?\*\[\(]*)?$/;var qmarksTestNocase=__name(([$0,ext2=""])=>{const noext=qmarksTestNoExt([$0]);if(!ext2)return noext;ext2=ext2.toLowerCase();return f=>noext(f)&&f.toLowerCase().endsWith(ext2)},"qmarksTestNocase");var qmarksTestNocaseDot=__name(([$0,ext2=""])=>{const noext=qmarksTestNoExtDot([$0]);if(!ext2)return noext;ext2=ext2.toLowerCase();return f=>noext(f)&&f.toLowerCase().endsWith(ext2)},"qmarksTestNocaseDot");var qmarksTestDot=__name(([$0,ext2=""])=>{const noext=qmarksTestNoExtDot([$0]);return!ext2?noext:f=>noext(f)&&f.endsWith(ext2)},"qmarksTestDot");var qmarksTest=__name(([$0,ext2=""])=>{const noext=qmarksTestNoExt([$0]);return!ext2?noext:f=>noext(f)&&f.endsWith(ext2)},"qmarksTest");var qmarksTestNoExt=__name(([$0])=>{const len=$0.length;return f=>f.length===len&&!f.startsWith(".")},"qmarksTestNoExt");var qmarksTestNoExtDot=__name(([$0])=>{const len=$0.length;return f=>f.length===len&&f!=="."&&f!==".."},"qmarksTestNoExtDot");var defaultPlatform=typeof process==="object"&&process?typeof process.env==="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix";var path2={win32:{sep:"\\"},posix:{sep:"/"}};var sep=defaultPlatform==="win32"?path2.win32.sep:path2.posix.sep;minimatch.sep=sep;var GLOBSTAR=Symbol("globstar **");minimatch.GLOBSTAR=GLOBSTAR;var qmark2="[^/]";var star2=qmark2+"*?";var twoStarDot="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";var twoStarNoDot="(?:(?!(?:\\/|^)\\.).)*?";var filter=__name((pattern,options={})=>p=>minimatch(p,pattern,options),"filter");minimatch.filter=filter;var ext=__name((a,b={})=>Object.assign({},a,b),"ext");var defaults=__name(def=>{if(!def||typeof def!=="object"||!Object.keys(def).length){return minimatch}const orig=minimatch;const m=__name((p,pattern,options={})=>orig(p,pattern,ext(def,options)),"m");return Object.assign(m,{Minimatch:class Minimatch extends orig.Minimatch{static{__name(this,"Minimatch")}constructor(pattern,options={}){super(pattern,ext(def,options))}static defaults(options){return orig.defaults(ext(def,options)).Minimatch}},AST:class AST extends orig.AST{static{__name(this,"AST")}constructor(type,parent,options={}){super(type,parent,ext(def,options))}static fromGlob(pattern,options={}){return orig.AST.fromGlob(pattern,ext(def,options))}},unescape:__name((s,options={})=>orig.unescape(s,ext(def,options)),"unescape"),escape:__name((s,options={})=>orig.escape(s,ext(def,options)),"escape"),filter:__name((pattern,options={})=>orig.filter(pattern,ext(def,options)),"filter"),defaults:__name(options=>orig.defaults(ext(def,options)),"defaults"),makeRe:__name((pattern,options={})=>orig.makeRe(pattern,ext(def,options)),"makeRe"),braceExpand:__name((pattern,options={})=>orig.braceExpand(pattern,ext(def,options)),"braceExpand"),match:__name((list2,pattern,options={})=>orig.match(list2,pattern,ext(def,options)),"match"),sep:orig.sep,GLOBSTAR})},"defaults");minimatch.defaults=defaults;var braceExpand=__name((pattern,options={})=>{assertValidPattern(pattern);if(options.nobrace||!/\{(?:(?!\{).)*\}/.test(pattern)){return[pattern]}return(0,import_brace_expansion.default)(pattern)},"braceExpand");minimatch.braceExpand=braceExpand;var makeRe=__name((pattern,options={})=>new Minimatch(pattern,options).makeRe(),"makeRe");minimatch.makeRe=makeRe;var match=__name((list2,pattern,options={})=>{const mm=new Minimatch(pattern,options);list2=list2.filter(f=>mm.match(f));if(mm.options.nonull&&!list2.length){list2.push(pattern)}return list2},"match");minimatch.match=match;var globMagic=/[?*]|[+@!]\(.*?\)|\[|\]/;var regExpEscape2=__name(s=>s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),"regExpEscape");var Minimatch=class{static{__name(this,"Minimatch")}options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;regexp;constructor(pattern,options={}){assertValidPattern(pattern);options=options||{};this.options=options;this.maxGlobstarRecursion=options.maxGlobstarRecursion??200;this.pattern=pattern;this.platform=options.platform||defaultPlatform;this.isWindows=this.platform==="win32";this.windowsPathsNoEscape=!!options.windowsPathsNoEscape||options.allowWindowsEscape===false;if(this.windowsPathsNoEscape){this.pattern=this.pattern.replace(/\\/g,"/")}this.preserveMultipleSlashes=!!options.preserveMultipleSlashes;this.regexp=null;this.negate=false;this.nonegate=!!options.nonegate;this.comment=false;this.empty=false;this.partial=!!options.partial;this.nocase=!!this.options.nocase;this.windowsNoMagicRoot=options.windowsNoMagicRoot!==void 0?options.windowsNoMagicRoot:!!(this.isWindows&&this.nocase);this.globSet=[];this.globParts=[];this.set=[];this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1){return true}for(const pattern of this.set){for(const part of pattern){if(typeof part!=="string")return true}}return false}debug(..._){}make(){const pattern=this.pattern;const options=this.options;if(!options.nocomment&&pattern.charAt(0)==="#"){this.comment=true;return}if(!pattern){this.empty=true;return}this.parseNegate();this.globSet=[...new Set(this.braceExpand())];if(options.debug){this.debug=(...args)=>console.error(...args)}this.debug(this.pattern,this.globSet);const rawGlobParts=this.globSet.map(s=>this.slashSplit(s));this.globParts=this.preprocess(rawGlobParts);this.debug(this.pattern,this.globParts);let set=this.globParts.map((s,_,__)=>{if(this.isWindows&&this.windowsNoMagicRoot){const isUNC=s[0]===""&&s[1]===""&&(s[2]==="?"||!globMagic.test(s[2]))&&!globMagic.test(s[3]);const isDrive=/^[a-z]:/i.test(s[0]);if(isUNC){return[...s.slice(0,4),...s.slice(4).map(ss=>this.parse(ss))]}else if(isDrive){return[s[0],...s.slice(1).map(ss=>this.parse(ss))]}}return s.map(ss=>this.parse(ss))});this.debug(this.pattern,set);this.set=set.filter(s=>s.indexOf(false)===-1);if(this.isWindows){for(let i=0;i<this.set.length;i++){const p=this.set[i];if(p[0]===""&&p[1]===""&&this.globParts[i][2]==="?"&&typeof p[3]==="string"&&/^[a-z]:$/i.test(p[3])){p[2]="?"}}}this.debug(this.pattern,this.set)}preprocess(globParts){if(this.options.noglobstar){for(let i=0;i<globParts.length;i++){for(let j=0;j<globParts[i].length;j++){if(globParts[i][j]==="**"){globParts[i][j]="*"}}}}const{optimizationLevel=1}=this.options;if(optimizationLevel>=2){globParts=this.firstPhasePreProcess(globParts);globParts=this.secondPhasePreProcess(globParts)}else if(optimizationLevel>=1){globParts=this.levelOneOptimize(globParts)}else{globParts=this.adjascentGlobstarOptimize(globParts)}return globParts}adjascentGlobstarOptimize(globParts){return globParts.map(parts=>{let gs=-1;while(-1!==(gs=parts.indexOf("**",gs+1))){let i=gs;while(parts[i+1]==="**"){i++}if(i!==gs){parts.splice(gs,i-gs)}}return parts})}levelOneOptimize(globParts){return globParts.map(parts=>{parts=parts.reduce((set,part)=>{const prev=set[set.length-1];if(part==="**"&&prev==="**"){return set}if(part===".."){if(prev&&prev!==".."&&prev!=="."&&prev!=="**"){set.pop();return set}}set.push(part);return set},[]);return parts.length===0?[""]:parts})}levelTwoFileOptimize(parts){if(!Array.isArray(parts)){parts=this.slashSplit(parts)}let didSomething=false;do{didSomething=false;if(!this.preserveMultipleSlashes){for(let i=1;i<parts.length-1;i++){const p=parts[i];if(i===1&&p===""&&parts[0]==="")continue;if(p==="."||p===""){didSomething=true;parts.splice(i,1);i--}}if(parts[0]==="."&&parts.length===2&&(parts[1]==="."||parts[1]==="")){didSomething=true;parts.pop()}}let dd=0;while(-1!==(dd=parts.indexOf("..",dd+1))){const p=parts[dd-1];if(p&&p!=="."&&p!==".."&&p!=="**"){didSomething=true;parts.splice(dd-1,2);dd-=2}}}while(didSomething);return parts.length===0?[""]:parts}firstPhasePreProcess(globParts){let didSomething=false;do{didSomething=false;for(let parts of globParts){let gs=-1;while(-1!==(gs=parts.indexOf("**",gs+1))){let gss=gs;while(parts[gss+1]==="**"){gss++}if(gss>gs){parts.splice(gs+1,gss-gs)}let next=parts[gs+1];const p=parts[gs+2];const p2=parts[gs+3];if(next!=="..")continue;if(!p||p==="."||p===".."||!p2||p2==="."||p2===".."){continue}didSomething=true;parts.splice(gs,1);const other=parts.slice(0);other[gs]="**";globParts.push(other);gs--}if(!this.preserveMultipleSlashes){for(let i=1;i<parts.length-1;i++){const p=parts[i];if(i===1&&p===""&&parts[0]==="")continue;if(p==="."||p===""){didSomething=true;parts.splice(i,1);i--}}if(parts[0]==="."&&parts.length===2&&(parts[1]==="."||parts[1]==="")){didSomething=true;parts.pop()}}let dd=0;while(-1!==(dd=parts.indexOf("..",dd+1))){const p=parts[dd-1];if(p&&p!=="."&&p!==".."&&p!=="**"){didSomething=true;const needDot=dd===1&&parts[dd+1]==="**";const splin=needDot?["."]:[];parts.splice(dd-1,2,...splin);if(parts.length===0)parts.push("");dd-=2}}}}while(didSomething);return globParts}secondPhasePreProcess(globParts){for(let i=0;i<globParts.length-1;i++){for(let j=i+1;j<globParts.length;j++){const matched=this.partsMatch(globParts[i],globParts[j],!this.preserveMultipleSlashes);if(matched){globParts[i]=[];globParts[j]=matched;break}}}return globParts.filter(gs=>gs.length)}partsMatch(a,b,emptyGSMatch=false){let ai=0;let bi=0;let result=[];let which="";while(ai<a.length&&bi<b.length){if(a[ai]===b[bi]){result.push(which==="b"?b[bi]:a[ai]);ai++;bi++}else if(emptyGSMatch&&a[ai]==="**"&&b[bi]===a[ai+1]){result.push(a[ai]);ai++}else if(emptyGSMatch&&b[bi]==="**"&&a[ai]===b[bi+1]){result.push(b[bi]);bi++}else if(a[ai]==="*"&&b[bi]&&(this.options.dot||!b[bi].startsWith("."))&&b[bi]!=="**"){if(which==="b")return false;which="a";result.push(a[ai]);ai++;bi++}else if(b[bi]==="*"&&a[ai]&&(this.options.dot||!a[ai].startsWith("."))&&a[ai]!=="**"){if(which==="a")return false;which="b";result.push(b[bi]);ai++;bi++}else{return false}}return a.length===b.length&&result}parseNegate(){if(this.nonegate)return;const pattern=this.pattern;let negate=false;let negateOffset=0;for(let i=0;i<pattern.length&&pattern.charAt(i)==="!";i++){negate=!negate;negateOffset++}if(negateOffset)this.pattern=pattern.slice(negateOffset);this.negate=negate}matchOne(file,pattern,partial=false){let fileStartIndex=0;let patternStartIndex=0;if(this.isWindows){const fileDrive=typeof file[0]==="string"&&/^[a-z]:$/i.test(file[0]);const fileUNC=!fileDrive&&file[0]===""&&file[1]===""&&file[2]==="?"&&/^[a-z]:$/i.test(file[3]);const patternDrive=typeof pattern[0]==="string"&&/^[a-z]:$/i.test(pattern[0]);const patternUNC=!patternDrive&&pattern[0]===""&&pattern[1]===""&&pattern[2]==="?"&&typeof pattern[3]==="string"&&/^[a-z]:$/i.test(pattern[3]);const fdi=fileUNC?3:fileDrive?0:void 0;const pdi=patternUNC?3:patternDrive?0:void 0;if(typeof fdi==="number"&&typeof pdi==="number"){const[fd,pd]=[file[fdi],pattern[pdi]];if(fd.toLowerCase()===pd.toLowerCase()){pattern[pdi]=fd;patternStartIndex=pdi;fileStartIndex=fdi}}}const{optimizationLevel=1}=this.options;if(optimizationLevel>=2){file=this.levelTwoFileOptimize(file)}if(pattern.includes(GLOBSTAR)){return this.#matchGlobstar(file,pattern,partial,fileStartIndex,patternStartIndex)}return this.#matchOne(file,pattern,partial,fileStartIndex,patternStartIndex)}#matchGlobstar(file,pattern,partial,fileIndex,patternIndex){const firstgs=pattern.indexOf(GLOBSTAR,patternIndex);const lastgs=pattern.lastIndexOf(GLOBSTAR);const[head,body,tail]=partial?[pattern.slice(patternIndex,firstgs),pattern.slice(firstgs+1),[]]:[pattern.slice(patternIndex,firstgs),pattern.slice(firstgs+1,lastgs),pattern.slice(lastgs+1)];if(head.length){const fileHead=file.slice(fileIndex,fileIndex+head.length);if(!this.#matchOne(fileHead,head,partial,0,0))return false;fileIndex+=head.length}let fileTailMatch=0;if(tail.length){if(tail.length+fileIndex>file.length)return false;let tailStart=file.length-tail.length;if(this.#matchOne(file,tail,partial,tailStart,0)){fileTailMatch=tail.length}else{if(file[file.length-1]!==""||fileIndex+tail.length===file.length){return false}tailStart--;if(!this.#matchOne(file,tail,partial,tailStart,0))return false;fileTailMatch=tail.length+1}}if(!body.length){let sawSome=!!fileTailMatch;for(let i2=fileIndex;i2<file.length-fileTailMatch;i2++){const f=String(file[i2]);sawSome=true;if(f==="."||f===".."||!this.options.dot&&f.startsWith(".")){return false}}return partial||sawSome}const bodySegments=[[[],0]];let currentBody=bodySegments[0];let nonGsParts=0;const nonGsPartsSums=[0];for(const b of body){if(b===GLOBSTAR){nonGsPartsSums.push(nonGsParts);currentBody=[[],0];bodySegments.push(currentBody)}else{currentBody[0].push(b);nonGsParts++}}let i=bodySegments.length-1;const fileLength=file.length-fileTailMatch;for(const b of bodySegments){b[1]=fileLength-(nonGsPartsSums[i--]+b[0].length)}return!!this.#matchGlobStarBodySections(file,bodySegments,fileIndex,0,partial,0,!!fileTailMatch)}#matchGlobStarBodySections(file,bodySegments,fileIndex,bodyIndex,partial,globStarDepth,sawTail){const bs=bodySegments[bodyIndex];if(!bs){for(let i=fileIndex;i<file.length;i++){sawTail=true;const f=file[i];if(f==="."||f===".."||!this.options.dot&&f.startsWith(".")){return false}}return sawTail}const[body,after]=bs;while(fileIndex<=after){const m=this.#matchOne(file.slice(0,fileIndex+body.length),body,partial,fileIndex,0);if(m&&globStarDepth<this.maxGlobstarRecursion){const sub=this.#matchGlobStarBodySections(file,bodySegments,fileIndex+body.length,bodyIndex+1,partial,globStarDepth+1,sawTail);if(sub!==false)return sub}const f=file[fileIndex];if(f==="."||f===".."||!this.options.dot&&f.startsWith(".")){return false}fileIndex++}return partial||null}#matchOne(file,pattern,partial,fileIndex,patternIndex){let fi;let pi;let pl;let fl;for(fi=fileIndex,pi=patternIndex,fl=file.length,pl=pattern.length;fi<fl&&pi<pl;fi++,pi++){this.debug("matchOne loop");let p=pattern[pi];let f=file[fi];this.debug(pattern,p,f);if(p===false||p===GLOBSTAR)return false;let hit;if(typeof p==="string"){hit=f===p;this.debug("string match",p,f,hit)}else{hit=p.test(f);this.debug("pattern match",p,f,hit)}if(!hit)return false}if(fi===fl&&pi===pl){return true}else if(fi===fl){return partial}else if(pi===pl){return fi===fl-1&&file[fi]===""}else{throw new Error("wtf?")}}braceExpand(){return braceExpand(this.pattern,this.options)}parse(pattern){assertValidPattern(pattern);const options=this.options;if(pattern==="**")return GLOBSTAR;if(pattern==="")return"";let m;let fastTest=null;if(m=pattern.match(starRE)){fastTest=options.dot?starTestDot:starTest}else if(m=pattern.match(starDotExtRE)){fastTest=(options.nocase?options.dot?starDotExtTestNocaseDot:starDotExtTestNocase:options.dot?starDotExtTestDot:starDotExtTest)(m[1])}else if(m=pattern.match(qmarksRE)){fastTest=(options.nocase?options.dot?qmarksTestNocaseDot:qmarksTestNocase:options.dot?qmarksTestDot:qmarksTest)(m)}else if(m=pattern.match(starDotStarRE)){fastTest=options.dot?starDotStarTestDot:starDotStarTest}else if(m=pattern.match(dotStarRE)){fastTest=dotStarTest}const re=AST.fromGlob(pattern,this.options).toMMPattern();if(fastTest&&typeof re==="object"){Reflect.defineProperty(re,"test",{value:fastTest})}return re}makeRe(){if(this.regexp||this.regexp===false)return this.regexp;const set=this.set;if(!set.length){this.regexp=false;return this.regexp}const options=this.options;const twoStar=options.noglobstar?star2:options.dot?twoStarDot:twoStarNoDot;const flags=new Set(options.nocase?["i"]:[]);let re=set.map(pattern=>{const pp=pattern.map(p=>{if(p instanceof RegExp){for(const f of p.flags.split(""))flags.add(f)}return typeof p==="string"?regExpEscape2(p):p===GLOBSTAR?GLOBSTAR:p._src});pp.forEach((p,i)=>{const next=pp[i+1];const prev=pp[i-1];if(p!==GLOBSTAR||prev===GLOBSTAR){return}if(prev===void 0){if(next!==void 0&&next!==GLOBSTAR){pp[i+1]="(?:\\/|"+twoStar+"\\/)?"+next}else{pp[i]=twoStar}}else if(next===void 0){pp[i-1]=prev+"(?:\\/|"+twoStar+")?"}else if(next!==GLOBSTAR){pp[i-1]=prev+"(?:\\/|\\/"+twoStar+"\\/)"+next;pp[i+1]=GLOBSTAR}});return pp.filter(p=>p!==GLOBSTAR).join("/")}).join("|");const[open,close]=set.length>1?["(?:",")"]:["",""];re="^"+open+re+close+"$";if(this.negate)re="^(?!"+re+").+$";try{this.regexp=new RegExp(re,[...flags].join(""))}catch(ex){this.regexp=false}return this.regexp}slashSplit(p){if(this.preserveMultipleSlashes){return p.split("/")}else if(this.isWindows&&/^\/\/[^\/]+/.test(p)){return["",...p.split(/\/+/)]}else{return p.split(/\/+/)}}match(f,partial=this.partial){this.debug("match",f,this.pattern);if(this.comment){return false}if(this.empty){return f===""}if(f==="/"&&partial){return true}const options=this.options;if(this.isWindows){f=f.split("\\").join("/")}const ff=this.slashSplit(f);this.debug(this.pattern,"split",ff);const set=this.set;this.debug(this.pattern,"set",set);let filename=ff[ff.length-1];if(!filename){for(let i=ff.length-2;!filename&&i>=0;i--){filename=ff[i]}}for(let i=0;i<set.length;i++){const pattern=set[i];let file=ff;if(options.matchBase&&pattern.length===1){file=[filename]}const hit=this.matchOne(file,pattern,partial);if(hit){if(options.flipNegate){return true}return!this.negate}}if(options.flipNegate){return false}return this.negate}static defaults(def){return minimatch.defaults(def).Minimatch}};minimatch.AST=AST;minimatch.Minimatch=Minimatch;minimatch.escape=escape;minimatch.unescape=unescape;init_esbuild_shims();import path3 from"node:path";var HOSTED_GLOB_PATTERN_MAX_LENGTH=1024;var HOSTED_GLOB_MAX_ALTERNATIVES=64;var MAX_BRACE_DEPTH=8;var SEQUENCE=/^(?:(-?\d+)\.\.(-?\d+)|([a-zA-Z])\.\.([a-zA-Z]))(?:\.\.(-?\d+))?$/;var HOSTED_GLOB_TOO_COMPLEX=`Hosted glob patterns are limited to ${HOSTED_GLOB_PATTERN_MAX_LENGTH} characters, balanced braces and ${HOSTED_GLOB_MAX_ALTERNATIVES} brace alternatives. Split the search into simpler patterns and retry.`;function checkHostedGlobPattern(pattern){if(pattern.length>HOSTED_GLOB_PATTERN_MAX_LENGTH||alternativesBound(pattern)>HOSTED_GLOB_MAX_ALTERNATIVES)return"too-complex";return braceExpand(pattern).some(alternative=>{const shape=unescape(alternative);return path3.isAbsolute(shape)||shape.split(/[\\/]/).includes("..")})?"escapes":"ok"}__name(checkHostedGlobPattern,"checkHostedGlobPattern");function alternativesBound(text2){let index=0;const limit=HOSTED_GLOB_MAX_ALTERNATIVES+1;const sequence2=__name(depth=>{let product=1;while(index<text2.length){const char=text2[index];if(char==="\\"){index+=2}else if(char==="{"){if(depth>=MAX_BRACE_DEPTH)return Infinity;index++;product=Math.min(product*group(depth+1),limit)}else if((char===","||char==="}")&&depth>0){return product}else if(char==="}"){return Infinity}else{index++}}return depth>0?Infinity:product},"sequence");const group=__name(depth=>{const start=index;const items=[sequence2(depth)];while(text2[index]===","){index++;items.push(sequence2(depth))}if(text2[index]!=="}")return Infinity;const body=text2.slice(start,index);index++;if(items.length>1)return Math.min(items.reduce((sum,item)=>sum+item,0),limit);if(items[0]>1||body.includes("{"))return Infinity;const range=SEQUENCE.exec(body);if(!range)return 1;if([range[1],range[2],range[5]].some(value=>value!==void 0&&!Number.isSafeInteger(Number(value))))return Infinity;const step=Math.max(Math.abs(Number(range[5]??1)),1);const span=range[1]!==void 0?Math.abs(Number(range[2])-Number(range[1])):Math.abs(range[4].charCodeAt(0)-range[3].charCodeAt(0));if(!Number.isSafeInteger(span))return Infinity;return Math.min(Math.floor(span/step)+1,limit)},"group");return sequence2(0)}__name(alternativesBound,"alternativesBound");init_esbuild_shims();import{createHash as createHash3}from"node:crypto";import{constants}from"node:os";var SEGMENT_BYTES=1024*1024;var SEGMENTS_PER_PAGE=512;function stream(id3){return{id:id3,buffer:Buffer.allocUnsafe(SEGMENT_BYTES),hash:createHash3("sha256"),pages:[],pendingSegments:[],used:0,byteLength:0,ordinal:0,pageOffset:0,pageOrdinal:0,observed:0,ended:false,sealed:false,queue:Promise.resolve()}}__name(stream,"stream");function signalName(value){if(value===null)return null;return Object.entries(constants.signals).find(([name,number])=>name.startsWith("SIG")&&number===value)?.[0]??null}__name(signalName,"signalName");var LocalShellResultCapture=class{constructor(store,resources2,identity,assertWritable=async()=>{}){this.store=store;this.resources=resources2;this.identity=identity;this.assertWritable=assertWritable;if(identity.revision!==1){throw new Error("Foreground Shell capture requires revision 1.")}}static{__name(this,"LocalShellResultCapture")}streams={stdout:stream("stdout"),stderr:stream("stderr")};started=false;processResult=null;failed=false;failureReason=null;finalEnvelope=null;setStarted(_pid){this.started=true}setProcessResult(result){this.processResult=result}setStopRequested(){}failCapture(){this.fail(new Error("Capture transport failed."))}write(id3,chunk){const state=this.streams[id3];state.observed+=chunk.byteLength;return state.queue=state.queue.then(()=>this.append(state,chunk))}async append(state,chunk){if(this.failed||state.ended)return;try{for(let offset=0;offset<chunk.byteLength;){const length=Math.min(SEGMENT_BYTES-state.used,chunk.byteLength-offset);chunk.copy(state.buffer,state.used,offset,offset+length);state.used+=length;offset+=length;if(state.used===SEGMENT_BYTES)await this.publishSegment(state)}}catch(cause){this.fail(cause)}}finish(id3,complete){const state=this.streams[id3];return state.queue=state.queue.then(()=>this.end(state,complete))}async end(state,complete){const id3=state.id;if(state.ended)return;state.ended=true;try{if(!this.failed&&state.used>0)await this.publishSegment(state);if(!this.failed&&complete){const sealed=await this.store.seal({captureId:this.identity.captureId,streamId:id3,segmentCount:state.ordinal,byteLength:state.byteLength,digest:state.hash.copy().digest("hex")});if(sealed.status!=="ok")throw new Error(sealed.code);state.sealed=true}}catch(cause){this.fail(cause)}finally{state.buffer=Buffer.alloc(0);state.used=0}}fail(cause){this.failed=true;this.failureReason=cause instanceof Error&&cause.message==="size_limit"?"size_limit":cause instanceof Error&&cause.message==="quota_exhausted"?"quota_exhausted":"storage_failed"}async publishSegment(state){await this.assertWritable();if(state.ordinal>MANAGED_TOOL_RESULT_LIMITS.maxOrdinal){throw new Error("size_limit")}const bytes=state.buffer.subarray(0,state.used);const published=await this.store.publish({captureId:this.identity.captureId,streamId:state.id,ordinal:state.ordinal,bytes});if(published.status!=="ok")throw new Error(published.code);state.hash.update(bytes);state.byteLength+=bytes.byteLength;state.pendingSegments.push({byteLength:published.result.byteLength,digest:published.result.digest});state.ordinal++;state.used=0;if(state.pendingSegments.length===SEGMENTS_PER_PAGE){await this.publishPage(state)}}async publishPage(state){if(state.pendingSegments.length===0)return;await this.assertWritable();if(state.pages.length>=MANAGED_TOOL_RESULT_LIMITS.maxPagesPerStream){this.failureReason="size_limit";throw new Error("size_limit")}const page=parseToolResultPage({toolResult:MANAGED_TOOL_RESULT_PROTOCOL,type:"page",captureId:this.identity.captureId,streamId:state.id,firstOrdinal:state.pageOrdinal,offset:state.pageOffset,segments:state.pendingSegments});const bytes=Buffer.from(JSON.stringify(page));if(bytes.byteLength>MANAGED_TOOL_RESULT_LIMITS.maxPageBytes){this.failureReason="size_limit";throw new Error("size_limit")}const ref2=await this.resources.publish(MANAGED_TOOL_RESULT_KINDS.page,bytes);const byteLength=state.pendingSegments.reduce((length,segment)=>length+segment.byteLength,0);state.pages.push({ref:ref2,segmentCount:state.pendingSegments.length,byteLength});state.pageOffset+=byteLength;state.pageOrdinal+=state.pendingSegments.length;state.pendingSegments.length=0}async finalize(executionStatus,responseParts,error){if(this.finalEnvelope)return this.finalEnvelope;if(!this.started){this.finalEnvelope={executionStatus:"not_started",responseParts,...error?{error}:{},capture:null};return this.finalEnvelope}if(!this.processResult){throw new Error("Started Shell has no physical outcome.")}if(executionStatus==="not_started"){throw new Error("Started Shell cannot have a not_started result.")}let pagesAvailable=!this.failed;if(pagesAvailable){for(const state of Object.values(this.streams)){try{await this.publishPage(state)}catch(cause){this.fail(cause);pagesAvailable=false;break}}}const contents=pagesAvailable?Object.values(this.streams).map(state=>({streamId:state.id,role:state.id,mimeType:"application/octet-stream",state:state.sealed?"sealed":"incomplete",byteLength:state.byteLength,digest:state.hash.copy().digest("hex"),missingRanges:state.sealed?[]:[{start:state.byteLength,end:null}],body:{pages:state.pages}})):[];const implied=impliedStatus(contents);const captureStatus=implied==="pending"?"partial":implied;const captureReason=captureStatus==="complete"?null:this.failureReason??"producer_lost";let manifestRef=null;try{const manifest=parseToolResultManifest({toolResult:MANAGED_TOOL_RESULT_PROTOCOL,type:"manifest",...this.identity,executionStatus,exitCode:this.processResult.exitCode,signal:signalName(this.processResult.signal),captureScope:"process_pipes",capturePolicy:"complete_required",captureStatus,captureReason,upstreamTruncated:false,contents});const bytes=Buffer.from(JSON.stringify(manifest));if(bytes.byteLength>MANAGED_TOOL_RESULT_LIMITS.maxManifestBytes){throw new Error("size_limit")}await this.assertWritable();manifestRef=await this.resources.publish(MANAGED_TOOL_RESULT_KINDS.manifest,bytes)}catch(cause){this.fail(cause)}const status=manifestRef?captureStatus:"unavailable";this.finalEnvelope={executionStatus,responseParts,...error?{error}:{},capture:{captureStatus:status,captureReason:manifestRef?captureReason:this.failureReason??"storage_failed",manifest:manifestRef,previewTruncated:this.streams.stdout.observed+this.streams.stderr.observed>Math.min(this.processResult.rawOutput.byteLength,3e4),deliveryStatus:"pending"}};return this.finalEnvelope}};init_esbuild_shims();var MANAGED_MCP_TOOL="managed_mcp_call";var MANAGED_MCP_ROUTE="/internal/managed-runtime/v3/mcp";var MANAGED_MCP_MAX_CONNECTIONS=16;init_esbuild_shims();var MANAGED_AUTOMATION_GATE_TOOL="managed_automation_gate";var MANAGED_AUTOMATION_GATE_TIMEOUT_MS=2e4;var ManagedAutomationGateInvocation=class extends BaseToolInvocation{constructor(config,params){super(params);this.config=config}static{__name(this,"ManagedAutomationGateInvocation")}getDescription(){return`Automation gate: ${this.params.gate}`}async execute(signal,_updateOutput,_shellExecutionConfig,onProcessGroup){const run=createCronGateRunner(this.config,{timeoutMs:MANAGED_AUTOMATION_GATE_TIMEOUT_MS,...onProcessGroup?{onProcessGroup}:{}});const result=await run(this.params.gate,{signal,approvedInProcess:true});return{llmContent:JSON.stringify(result),returnDisplay:`Automation gate ${result.kind}`}}};var ManagedAutomationGateTool=class _ManagedAutomationGateTool extends BaseDeclarativeTool{constructor(config){super(_ManagedAutomationGateTool.Name,"Automation gate","Runs a managed automation definition gate command outside the model. Internal to the Runtime worker.","execute",{type:"object",properties:{gate:{type:"string",description:"The gate command to run in the Session directory."}},required:["gate"]});this.config=config}static{__name(this,"ManagedAutomationGateTool")}static Name=MANAGED_AUTOMATION_GATE_TOOL;validateToolParamValues(params){const error=gateCommandError(params.gate);return error===null?null:`gate ${error}`}createInvocation(params){return new ManagedAutomationGateInvocation(this.config,params)}};function parseManagedAutomationGateResult(responseParts){const first=responseParts[0];const text2=first&&typeof first==="object"&&"text"in first?first.text:void 0;if(typeof text2!=="string")return null;let parsed;try{parsed=JSON.parse(text2)}catch{return null}if(!parsed||typeof parsed!=="object"||Array.isArray(parsed)){return null}const result=parsed;const durationMs=typeof result["durationMs"]==="number"&&Number.isFinite(result["durationMs"])?Math.max(0,Math.round(result["durationMs"])):void 0;switch(result["kind"]){case"quiet":return durationMs!==void 0?{kind:"quiet",durationMs}:null;case"output":return typeof result["stdout"]==="string"&&typeof result["truncated"]==="boolean"&&durationMs!==void 0?{kind:"output",stdout:result["stdout"],truncated:result["truncated"],durationMs}:null;case"failed":return typeof result["detail"]==="string"&&typeof result["stderr"]==="string"&&durationMs!==void 0?{kind:"failed",detail:result["detail"],stderr:result["stderr"],durationMs}:null;case"blocked":return typeof result["reason"]==="string"?{kind:"blocked",reason:result["reason"],...typeof result["rule"]==="string"?{rule:result["rule"]}:{}}:null;default:return null}}__name(parseManagedAutomationGateResult,"parseManagedAutomationGateResult");init_esbuild_shims();import{createHash as createHash4,randomUUID}from"node:crypto";import{isDeepStrictEqual as isDeepStrictEqual2}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 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 CONFIG=`sha256:${createHash4("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 body=closed3(value,[...COMMON,"subject"]);common(body);switch(body["action"]){case"bind":ensure(body["subject"]===null);break;case"prepare":ref(body["subject"],"managed-file_history");break;case"execute":id2(body["subject"]);break;default:throw invalid()}ensure(Buffer.byteLength(JSON.stringify(body))<=CSI_NATIVE_REQUEST_LIMIT);return structuredClone(body)}__name(readCsiNativeRequest,"readCsiNativeRequest");function readCsiNativeResponse(value,request){readCsiNativeRequest(request);const body=closed3(value,[...COMMON,"head","evidence"]);common(body);for(const field of COMMON)ensure(isDeepStrictEqual2(body[field],request[field]));const head=closed3(body["head"],["revision","sequence","digest"]);ensure(counter(head["revision"])>0&&counter(head["sequence"])>0);digest(head["digest"]);const owner=object3(body["identity"])["sessionId"];const evidence=object3(body["evidence"]);switch(body["action"]){case"bind":closed3(evidence,["kind"]);ensure(evidence["kind"]==="ready");break;case"prepare":{closed3(evidence,["kind","intentRef","resources","members"]);ensure(evidence["kind"]==="intent"&&isDeepStrictEqual2(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":{closed3(evidence,["kind","executionReference","preparedRef","authorizationRevision","authorizationSequence","grant","resources"]);ensure(evidence["kind"]==="authorization");const reference=execution(evidence["executionReference"],owner);const required=new Map;const inputRef=ref(reference["inputRef"],"managed-tool-input");add(required,inputRef);add(required,ref(reference["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&&isDeepStrictEqual2(grant["executionReference"],reference)&&isDeepStrictEqual2(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(isDeepStrictEqual2(grant[field],body[field]));const bytes=resources(evidence["resources"],required);const input=closed3(parseManagedCsiFileJson(bytes.get(inputRef.resourceId),64*1024),["harnessSessionId","runtimeSessionId","payloadJson"]);ensure(input["harnessSessionId"]===owner&&input["runtimeSessionId"]===owner&&typeof input["payloadJson"]==="string");ensure(`sha256:${createHash4("sha256").update(input["payloadJson"]).digest("hex")}`===reference["argsDigest"]);const payload=closed3(parseManagedSessionRecordJson(input["payloadJson"],64*1024),["toolName","input"]);if(prepared===null)ensure(payload["toolName"]==="read_file");break}default:throw invalid()}ensure(Buffer.byteLength(JSON.stringify(body))<=CSI_NATIVE_RESPONSE_LIMIT);return structuredClone(body)}__name(readCsiNativeResponse,"readCsiNativeResponse");function readCsiNativeGrant(value){const grant=closed3(value,["protocolVersion","runtimeBindingId","bindingGeneration","authorizedBindingVersion","executionCallId","dispatchGeneration","authorizationRevision","authorizationSequence","executionReference","intent","checkpointRef","preparedRef","identity","context","installedContext"]);ensure(grant["protocolVersion"]===1);commonContext(grant);id2(grant["runtimeBindingId"]);id2(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=closed3(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=closed3(value["identity"],["profile","sessionId","capabilityDigest"]);ensure(identity["profile"]==="csi-files-retirement/1"&&identity["capabilityDigest"]===CSI_FILES_RETIREMENT_CAPABILITY_DIGEST);uuid(identity["sessionId"]);const context=closed3(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=closed3(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=createHash4("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=closed3(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=closed3(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]);id2(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=closed3(candidate,["reference","bytesBase64"]);const reference=object3(entry["reference"]);const resourceId=id2(reference["resourceId"]);ensure(required.has(resourceId)&&isDeepStrictEqual2(required.get(resourceId),reference));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===reference["byteLength"]&&createHash4("sha256").update(bytes).digest("hex")===reference["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<=(kind==="managed-checkpoint"?MANAGED_SESSION_LIMITS.maxEventBytes:64*1024));return result}__name(ref,"ref");function add(required,reference){const previous=required.get(reference.resourceId);ensure(previous===void 0||isDeepStrictEqual2(previous,reference));required.set(reference.resourceId,reference)}__name(add,"add");function counter(value){ensure(Number.isSafeInteger(value)&&value>=0);return value}__name(counter,"counter");function id2(value){return assertManagedSessionStableId(value,"CSI native identity")}__name(id2,"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"&&UUID.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 closed3(value,keys2){const result=object3(value);ensure(isDeepStrictEqual2(Object.keys(result).sort(),[...keys2].sort()));return result}__name(closed3,"closed");function ensure(condition){if(!condition)throw invalid()}__name(ensure,"ensure");function invalid(){return new Error("Invalid private CSI native readback.")}__name(invalid,"invalid");async function readCurrentCsiNative(boot,installedContext,action,subject){if(boot.version!==5&&boot.version!==6)throw invalid();const request=readCsiNativeRequest({protocolVersion:1,requestId:randomUUID(),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 invalid();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 isDeepStrictEqual3}from"node:util";import{createHash as createHash5}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 body=closed4(parseManagedCsiFileJson(bytes,64*1024),["operationId","revision","previousRecordRef","schemaVersion","profile","runtimeSessionId","state","backupDirectory","retainedBackups","preparation","record"]);ensure2(body["schemaVersion"]===2&&body["profile"]==="csi-files-retirement/1"&&body["runtimeSessionId"]===owner);const preparation=closed4(body["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=closed4(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(isDeepStrictEqual3(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=closed4(parseManagedCsiFileJson(inputBytes,64*1024),["harnessSessionId","runtimeSessionId","payloadJson"]);ensure2(wrapper["harnessSessionId"]===owner&&wrapper["runtimeSessionId"]===owner&&typeof wrapper["payloadJson"]==="string");ensure2(`sha256:${createHash5("sha256").update(wrapper["payloadJson"]).digest("hex")}`===invocation["requestDigest"]);const payload=closed4(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&&isDeepStrictEqual3([...paths].sort(),preparation["paths"]));return{preparation:structuredClone(preparation),observation:readCsiFileHistoryObservation({state:body["state"],backupDirectory:body["backupDirectory"],retainedBackups:body["retainedBackups"]},owner)}}__name(readCsiPreparationEvidence,"readCsiPreparationEvidence");function readCsiFileHistoryOperation(value){const operation=object4(value);closed4(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 reference=assertManagedSessionDurableRef(operation["preparationRef"],"CSI preparation");ensure2(reference.kind==="managed-file_history"&&reference.schemaVersion===1&&reference.byteLength>0&&reference.byteLength<=64*1024)}return structuredClone(operation)}__name(readCsiFileHistoryOperation,"readCsiFileHistoryOperation");function readCsiFileHistoryEnvelope(value,boot,installedContext){const body=closed4(value,["protocolVersion","managedCsi","identity","context","installedContext","operation"]);ensure2((boot.version===5||boot.version===6)&&body["protocolVersion"]===2&&body["managedCsi"]===MANAGED_CSI_FILE_PROTOCOL);ensure2(isDeepStrictEqual3(body["identity"],boot.identity)&&isDeepStrictEqual3(body["context"],createManagedContextAttestationResponse(boot.context))&&isDeepStrictEqual3(body["installedContext"],installedContext));readCsiNativeRequest({protocolVersion:1,requestId:"00000000-0000-4000-8000-000000000000",action:"bind",identity:boot.identity,context:body["context"],installedContext,subject:null});return readCsiFileHistoryOperation(body["operation"])}__name(readCsiFileHistoryEnvelope,"readCsiFileHistoryEnvelope");function readCsiFileHistoryObservation(value,owner){const body=closed4(value,["state","backupDirectory","retainedBackups"]);const state=parseHostedFileHistoryState(body["state"],owner);const directory=closed4(body["backupDirectory"],["volumeDevice","volumeInode","directoryDevice","directoryInode"]);for(const value2 of Object.values(directory))decimal(value2);ensure2(directory["volumeDevice"]===directory["directoryDevice"]);ensure2(Array.isArray(body["retainedBackups"]));const pins=new Map;let previous="";for(const candidate of body["retainedBackups"]){const pin=closed4(candidate,["name","device","inode","byteLength","digest","mode"]);const name=pin["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(pin["device"]);decimal(pin["inode"]);ensure2(pin["device"]===directory["volumeDevice"]);ensure2(Number.isSafeInteger(pin["byteLength"])&&pin["byteLength"]>=0&&pin["byteLength"]<Number.MAX_SAFE_INTEGER);ensure2(Number.isSafeInteger(pin["mode"])&&pin["mode"]>=0&&pin["mode"]<=4095);ensure2(typeof pin["digest"]==="string"&&/^[0-9a-f]{64}$/.test(pin["digest"]));pins.set(name,structuredClone(pin));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 closed4(value,keys2){const body=object4(value);ensure2(isDeepStrictEqual3(Object.keys(body).sort(),[...keys2].sort()));return body}__name(closed4,"closed");function ensure2(condition){if(!condition)throw new Error("Invalid private CSI file history.")}__name(ensure2,"ensure");function csiHistoryContentDigest(content){const canonical=__name(value=>{if(Array.isArray(value))return`[${value.map(canonical).join(",")}]`;if(value!==null&&typeof value==="object")return`{${Object.keys(value).sort().map(key=>`${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}`;const result=JSON.stringify(value);ensure2(result!==void 0);return result},"canonical");const semantic={...content};delete semantic["record"];return createHash5("sha256").update(canonical(semantic)).digest("hex")}__name(csiHistoryContentDigest,"csiHistoryContentDigest");init_esbuild_shims();var MANAGED_HOOK_ROUTE="/internal/managed-runtime/v3/hooks";var MANAGED_HOOK_MAX_RUNNING=16;var MANAGED_HOOK_MAX_REQUEST_BYTES=8*1024*1024;export{ManagedPackageCompatibilityError,compileManagedExtensionPackage,prepareManagedExtensionPackage,MANAGED_HOOK_ROUTE,MANAGED_HOOK_MAX_RUNNING,MANAGED_HOOK_MAX_REQUEST_BYTES,MAX_PROVIDER_INLINE_MEDIA_BASE64_BYTES,MAX_PROVIDER_MEDIA_RESULT_BYTES,MANAGED_RUNTIME_PROVIDER_ROUTE,MANAGED_WORKSPACE_CONTEXT_FILES,MANAGED_WORKSPACE_CONTEXT_FILE_CHARS,ManagedRuntimeProviderProtocolError,managedRuntimeProviderLimit,parseManagedRuntimeProviderRequest,parseManagedRuntimeProviderResult,fitManagedRuntimeProviderResult,WORKSPACE_CONTEXT_CONFIG_REF,WORKSPACE_CAPABILITY_DIGEST,RESIDENT_WORKSPACE_CAPABILITY_DIGEST,WORKSPACE_ACTIVATION_ROUTE,WorkspaceActivations,minimatch,HOSTED_GLOB_TOO_COMPLEX,checkHostedGlobPattern,LocalShellResultCapture,MANAGED_MCP_TOOL,MANAGED_MCP_ROUTE,MANAGED_MCP_MAX_CONNECTIONS,MANAGED_AUTOMATION_GATE_TOOL,MANAGED_AUTOMATION_GATE_TIMEOUT_MS,ManagedAutomationGateTool,parseManagedAutomationGateResult,CSI_FILES_RETIREMENT_CAPABILITY_DIGEST,MANAGED_CSI_PROTOCOL,MANAGED_CSI_ATTEST_PATH,MANAGED_CSI_DRAIN_PATH,MANAGED_CSI_ACK_PATH,MANAGED_CSI_ACK_LIMIT_BYTES,ManagedCsiAckRequestError,parseManagedCsiAckJson,parseManagedCsiAcknowledgement,parseManagedCsiCaptureIdentity,parseManagedCsiAckRequest,parseManagedCsiAckResponse,ManagedCsiDrainRequestError,parseManagedCsiDrainRequest,validateManagedCsiAttestationRequest,validateManagedCsiPodIdentity,validateManagedCsiAttestationResponse,linuxDeviceNumber,parseManagedCsiBoot,MANAGED_CSI_FILE_PROTOCOL,MANAGED_CSI_FILE_PREFIX,CSI_FILE_FINALIZATION_FORMAT,MANAGED_CSI_FILE_ROUTES,parseManagedCsiFileJson,parseManagedCsiFileBoot,createManagedCsiFileReady,wrapManagedCsiFileContext,readManagedCsiFileContext,validateManagedCsiFileAttestationRequest,validateManagedCsiFileAttestationResponse,readManagedCsiFileDrain,CSI_NATIVE_RESPONSE_LIMIT,readCsiNativeRequest,readCsiNativeGrant,readCurrentCsiNative,CSI_FILE_HISTORY_PATH,readCsiPreparationEvidence,readCsiFileHistoryEnvelope,readCsiFileHistoryObservation,csiHistoryContentDigest};
|
|
6
6
|
/**
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
3
|
import{remarkParse,unified}from"./chunk-AZ3CKMCT.js";import{estimateTextTokens}from"./chunk-RP57XAJ2.js";import{ignoreBrokenPipe}from"./chunk-M4ECEHLX.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{homedir}from"node:os";import path2 from"node:path";import*as fs2 from"node:fs/promises";init_esbuild_shims();init_esbuild_shims();var MEMORY_IMPORT_BUDGET={maxCalls:32,maxReservedTokens:512e3,batchSections:8,sourceBytes:65536,contextBytes:32768,outputTokens:8192,promptBytes:32768};function packMemoryImportSections(sections){const groups=new Map;for(const section of[...sections].sort((a,b)=>a.id.localeCompare(b.id))){const key=`${section.scope??""}:${section.groupId}`;const group=groups.get(key)??[];group.push(section);groups.set(key,group)}const batches=[];for(const group of groups.values()){let batch=[];let bytes=0;for(const section of group){const size=Buffer.byteLength(section.content);if(batch.length&&(batch.length===MEMORY_IMPORT_BUDGET.batchSections||bytes+size>MEMORY_IMPORT_BUDGET.sourceBytes)){batches.push(batch);batch=[];bytes=0}batch.push(section);bytes+=size}if(batch.length)batches.push(batch)}return batches}__name(packMemoryImportSections,"packMemoryImportSections");function estimateMemoryImport(sections){const batches=packMemoryImportSections(sections);const modelCalls=batches.length*2;const sourceTokens=sections.reduce((n,section)=>n+estimateTextTokens(section.content),0);const sourceBytes=Buffer.byteLength(JSON.stringify(sections.map(({id,content})=>({id,content}))));const reservedTokens=modelCalls*(MEMORY_IMPORT_BUDGET.contextBytes+MEMORY_IMPORT_BUDGET.promptBytes+MEMORY_IMPORT_BUDGET.outputTokens+1024)+sourceBytes+modelCalls;return{basis:"source-only-with-context-reserve",modelCalls,sourceTokens,maxOutputTokens:modelCalls*MEMORY_IMPORT_BUDGET.outputTokens,reservedTokens,exceedsBudget:modelCalls>MEMORY_IMPORT_BUDGET.maxCalls||reservedTokens>MEMORY_IMPORT_BUDGET.maxReservedTokens,limits:MEMORY_IMPORT_BUDGET}}__name(estimateMemoryImport,"estimateMemoryImport");import{createHash}from"node:crypto";import*as fs from"node:fs/promises";import path from"node:path";import{constants}from"node:fs";var MemoryImportRequestError=class extends Error{static{__name(this,"MemoryImportRequestError")}};var IMPORT_LIMITS={files:256,fileBytes:512*1024,totalBytes:8*1024*1024,sectionBytes:64*1024,headings:4096,markdownLines:16384,inlineMarkers:4096};function digest(value){return createHash("sha256").update(value).digest("hex")}__name(digest,"digest");function record(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}__name(record,"record");function validSourcePath(value){return value.length<=512&&!/[\\\p{Cc}]/u.test(value)&&!value.startsWith("/")&&!/^[a-z]:/i.test(value)&&value.split("/").every(part=>part!==""&&part!=="."&&part!=="..")&&(/^(?:MEMORY|memory_summary)\.md$/.test(value)||/^rollout_summaries\/[\w.-]+\.md$/.test(value))}__name(validSourcePath,"validSourcePath");function validateSource(value){if(!record(value)||value["version"]!==1||value["source"]!=="codex"||!Array.isArray(value["files"])||value["files"].length===0||value["files"].length>IMPORT_LIMITS.files)throw new MemoryImportRequestError("Invalid version 1 Codex source set.");let bytes=0;const seen=new Set;const files=value["files"].map(file=>{if(!record(file)||typeof file["path"]!=="string"||!validSourcePath(file["path"])||typeof file["content"]!=="string"||file["content"].includes("\0"))throw new MemoryImportRequestError("Invalid Codex Markdown resource. Only memory Markdown and rollout_summaries/*.md are accepted.");const size=Buffer.byteLength(file["content"]);bytes+=size;if(size>IMPORT_LIMITS.fileBytes||bytes>IMPORT_LIMITS.totalBytes||seen.has(file["path"].toLowerCase()))throw new MemoryImportRequestError("Source exceeds limits or contains duplicate paths.");seen.add(file["path"].toLowerCase());return{path:file["path"],content:file["content"]}});if(!files.some(file=>file.path==="MEMORY.md"||file.path==="memory_summary.md"))throw new MemoryImportRequestError("Select the Codex memories folder containing MEMORY.md or memory_summary.md.");return{version:1,source:"codex",files:files.sort((a,b)=>a.path.localeCompare(b.path))}}__name(validateSource,"validateSource");var parser=unified().use(remarkParse);function headingTitle(raw){const atx=raw.match(/^ {0,3}#{1,6}(?:[\t ]+|$)/);if(atx)return raw.slice(atx[0].length).replace(/[\t ]+#+[\t ]*$/,"").trim();return raw.split(/\r\n|[\r\n]/).slice(0,-1).join(" ").trim()}__name(headingTitle,"headingTitle");function scopeFor(content,title,summary){const scopes=[];for(const match of content.matchAll(/(?:^|[\s;(])cwd\s*[=:]\s*(?:`([^`\n]+)`|([^\r\n,;()\s]+))/gim)){if(match[1]!==void 0){scopes.push({value:match[1].trim(),quoted:true,prose:false});continue}const trailing=content.slice(match.index+match[0].length).split(/\r\n|[\r\n]/,1)[0].trim();scopes.push({value:match[2].trim(),quoted:false,prose:/[^\s,;()]/.test(trailing)})}const heading=title.trim();if(/^(?:\/|[A-Za-z]:[\\/])/.test(heading))scopes.push({value:heading.replace(/^`|`$/g,""),quoted:false,prose:false});const strip=__name(value=>value.replace(/[\\/]+$/,"").replace(/[.:!?'"]+$/,""),"strip");const unique=[...new Set(scopes.map(scope=>strip(scope.value)))];if(unique.length===1&&/^(?:\/|[A-Za-z]:[\\/])/.test(unique[0])&&scopes.every(scope=>!scope.prose&&!/[*?{}[\]\p{Cc}]|\bcwd\s*[=:]/u.test(scope.value)&&(scope.quoted||!/\s/.test(scope.value))))return{suggestedScope:"project",sourceProject:unique[0],reason:"Source project hint; explicit target mapping is required."};if(scopes.length)return{suggestedScope:"unassigned",reason:"Ambiguous or unsupported project scope; assign explicitly."};if(summary&&/^(?:user profile|user preferences)$/i.test(title))return{suggestedScope:"user",reason:"Explicit user-level summary section."};return{suggestedScope:"unassigned",reason:"No reliable project scope; assign explicitly."}}__name(scopeFor,"scopeFor");function previewSource(input){const source=validateSource(input);const sections=[];const warnings=[];let headingCount=0;let lineCount=0;let markerCount=0;let expandedBytes=0;const paths=new Set(source.files.map(file=>file.path));const referenced=new Set;for(const file of source.files.filter(f=>!f.path.startsWith("rollout_summaries/"))){for(const match of file.content.matchAll(/rollout_summaries\/[\w.-]+\.md/g))referenced.add(match[0])}for(const ref of referenced)if(!paths.has(ref))warnings.push(`Missing referenced Markdown: ${ref}`);for(const file of source.files){if(file.path.startsWith("rollout_summaries/")&&!referenced.has(file.path)){warnings.push(`Unreferenced supporting resource excluded: ${file.path}`);continue}const atxCandidates=file.content.match(/^ {0,3}#{1,6}(?:[\t ]|$)/gm)?.length??0;if(headingCount+atxCandidates>4*IMPORT_LIMITS.headings)throw new MemoryImportRequestError("Source exceeds the supported heading limit.");for(let i=0;i<file.content.length;i++){const char=file.content[i];if(char==="\n"||char==="\r"&&file.content[i+1]!=="\n")lineCount++;if("*_~[]<>!`&\\".includes(char))markerCount++;if(lineCount>IMPORT_LIMITS.markdownLines||markerCount>IMPORT_LIMITS.inlineMarkers)throw new MemoryImportRequestError("Source exceeds the Markdown complexity limit; split it into smaller source sets before importing.")}const tree=parser.parse(file.content);const headings=tree.children.filter(node=>node.type==="heading").map((node,index,nodes)=>({offset:node.position.start.offset,line:node.position.start.line,depth:node.depth,title:headingTitle(file.content.slice(node.position.start.offset,node.position.end.offset)),preface:file.content.slice(node.position.start.offset,nodes[index+1]?.position.start.offset).trim()}));headingCount+=headings.length;if(headingCount>IMPORT_LIMITS.headings)throw new MemoryImportRequestError("Source exceeds the supported heading limit.");const scopedDepths=headings.filter(heading=>/^(?:`?\/|`?[A-Za-z]:[\\/])/.test(heading.title)||/\bcwd\s*[=:]/i.test(heading.preface)).map(heading=>heading.depth);const minDepth=headings.length?Math.min(...headings.map(h=>h.depth)):1;const depth=Math.max(file.path==="memory_summary.md"?2:minDepth,...scopedDepths);const boundaries=headings.filter(heading=>heading.depth<=depth);if(!boundaries.length||boundaries[0].offset>0)boundaries.unshift({offset:0,line:1,title:file.path,depth:0,preface:""});for(let i=0;i<boundaries.length;i++){const boundary=boundaries[i];const own=file.content.slice(boundary.offset,boundaries[i+1]?.offset).trim();if(!own||/^v\d+$/.test(own)||own.split(/\r\n|[\r\n]/).every(line=>!line.trim()||/^#{1,6}\s/.test(line)))continue;const ancestors=[];for(const heading of headings){if(heading.offset>=boundary.offset)break;while(ancestors.length&&ancestors.at(-1).depth>=heading.depth)ancestors.pop();ancestors.push(heading)}while(ancestors.length&&ancestors.at(-1).depth>=boundary.depth)ancestors.pop();const parts=[...ancestors.map(heading=>heading.preface),own];expandedBytes+=parts.reduce((bytes,part)=>bytes+Buffer.byteLength(part),0)+2*(parts.length-1);if(expandedBytes>IMPORT_LIMITS.totalBytes)throw new MemoryImportRequestError("Source expanded context exceeds 8 MiB; split shared context and project groups before importing.");const content=parts.join("\n\n");let scope=scopeFor(content,boundary.title,file.path==="memory_summary.md");if(scope.suggestedScope==="unassigned"&&!/\bcwd\s*[=:]/i.test(content)){const parent=ancestors.at(-1);if(parent)scope=scopeFor(content,parent.title,file.path==="memory_summary.md")}const references=[...new Set(Array.from(content.matchAll(/rollout_summaries\/[\w.-]+\.md/g),m=>m[0]))];const selectable=Buffer.byteLength(content)<=IMPORT_LIMITS.sectionBytes;if(!selectable)warnings.push(`${file.path}:${boundary.line}: section exceeds ${IMPORT_LIMITS.sectionBytes} bytes; split it before import.`);const id=digest(`${file.path}\0${content}`);if(sections.some(section=>section.id===id))continue;sections.push({id,groupId:digest(`${scope.suggestedScope}\0${scope.sourceProject??""}`),title:boundary.title,path:file.path,line:boundary.line,content,references,...scope,selectable})}}const groups=new Map;for(const section of sections){const group=groups.get(section.groupId)??{id:section.groupId,scope:section.suggestedScope,sourceProject:section.sourceProject,sectionIds:[]};group.sectionIds.push(section.id);groups.set(group.id,group)}return{version:1,kind:"preview",digest:digest(JSON.stringify(source)),groups:[...groups.values()].map(group=>({...group,estimate:estimateMemoryImport(sections.filter(section=>section.selectable&§ion.groupId===group.id))})),sections,warnings,estimate:estimateMemoryImport(sections.filter(section=>section.selectable))}}__name(previewSource,"previewSource");async function readLocalSource(directory){const root=await fs.realpath(directory);const files=[];const read=__name(async relative=>{const file=path.join(root,relative);const info=await fs.lstat(file);if(!info.isFile()||info.isSymbolicLink()||info.size>IMPORT_LIMITS.fileBytes)throw new Error("Source must contain regular bounded Markdown files.");const handle=await fs.open(file,constants.O_RDONLY|(constants.O_NOFOLLOW??0)|(constants.O_NONBLOCK??0));try{const opened=await handle.stat();if(!opened.isFile()||opened.size>IMPORT_LIMITS.fileBytes)throw new Error("Source changed while opening.");const buffer=Buffer.alloc(IMPORT_LIMITS.fileBytes+1);let length=0;while(length<buffer.length){const read2=await handle.read(buffer,length,buffer.length-length,null);if(!read2.bytesRead)break;length+=read2.bytesRead}if(length>IMPORT_LIMITS.fileBytes||files.reduce((sum,entry)=>sum+Buffer.byteLength(entry.content),length)>IMPORT_LIMITS.totalBytes)throw new Error("Source exceeds byte limits.");files.push({path:relative,content:buffer.subarray(0,length).toString("utf8")})}finally{await handle.close()}},"read");for(const name of["MEMORY.md","memory_summary.md"]){try{await read(name)}catch(error){if(error.code!=="ENOENT")throw error}}const refs=new Set(files.flatMap(file=>Array.from(file.content.matchAll(/rollout_summaries\/[\w.-]+\.md/g),m=>m[0])));if(refs.size+files.length>IMPORT_LIMITS.files)throw new Error("Too many referenced source files.");if(refs.size){const dir=await fs.lstat(path.join(root,"rollout_summaries")).catch(error=>{if(error.code==="ENOENT")return void 0;throw error});if(dir&&(!dir.isDirectory()||dir.isSymbolicLink()))throw new Error("Supporting resource directory must not be a symlink.");if(dir)for(const ref of refs){try{await read(ref)}catch(error){if(error.code!=="ENOENT")throw error}}}return validateSource({version:1,source:"codex",files})}__name(readLocalSource,"readLocalSource");var writeStdoutLineFlushed=__name(message=>new Promise((resolve,reject)=>process.stdout.write(message.endsWith("\n")?message:`${message}
|
|
4
|
-
`,error=>error&&error.code!=="EPIPE"?reject(error):resolve())),"writeStdoutLineFlushed");var memoryCommand={command:"memory",describe:"Preview and import external memories",builder:__name(argv=>argv.command({command:"import codex",describe:"Preview Codex memory; explicitly confirm selected sections to consolidate",builder:__name(args=>args.positional("codex",{type:"string",describe:"External memory source",choices:["codex"]}).option("source",{type:"string",describe:"Codex memories directory"}).option("dry-run",{type:"boolean",default:false,describe:"Offline preview; no model or memory writes"}).option("json",{type:"boolean",default:false}).option("apply",{type:"boolean",default:false,describe:"Authorize model consolidation of an explicit selection"}).option("selection",{type:"string",describe:"JSON array of {id, scope: project|user}"}).option("idempotency-key",{type:"string",describe:"Stable caller key for this selection"}).option("retry",{type:"boolean",default:false,describe:"Retry unfinished items of this submitted batch"}).strict(),"builder"),handler:__name(async args=>{ignoreBrokenPipe();if(args["apply"]&&args["dry-run"])throw new Error("--apply and --dry-run cannot be combined.");if(args["apply"]&&(args["bare"]||args["safeMode"]||args["safe-mode"]))throw new Error("Confirmed memory import is unavailable in bare or safe mode. Offline preview remains available.");if(args["source"]!==void 0&&typeof args["source"]!=="string")throw new Error("Provide a single --source directory.");const directory=typeof args["source"]==="string"?args["source"]:path2.join(process.env["CODEX_HOME"]?.trim()||path2.join(homedir(),".codex"),"memories");const source=await readLocalSource(directory);const preview=previewSource(source);if(!args["apply"]){if(args["json"])await writeStdoutLineFlushed(JSON.stringify(preview));else{const lines=[`Preview only: ${preview.sections.length} source sections. No memory was written.`,...preview.groups.map(group=>`[${group.sectionIds.length} sections] ${group.scope}: ${JSON.stringify(group.sourceProject??"No project hint")}`),`Estimated usage (all selectable sections): ${preview.estimate.modelCalls} model calls, ${preview.estimate.sourceTokens} source tokens, up to ${preview.estimate.maxOutputTokens} output tokens; ${preview.estimate.reservedTokens} reserved token units including context.`,`Task limits: ${preview.estimate.limits.maxCalls} calls / ${preview.estimate.limits.maxReservedTokens} reserved token units. Estimates are not billing quotes; explicit selection and existing context affect usage.`];if(preview.estimate.exceedsBudget)lines.push("Warning: the full selection may exceed the task budget; select fewer sections before confirming.");for(const warning of preview.warnings)lines.push(`Warning: ${JSON.stringify(warning)}`);lines.push("Use --json for section IDs, details and source text. To import, provide --apply --selection <JSON file> --idempotency-key <key>. Unassigned sections require an explicit scope.");await writeStdoutLineFlushed(lines.join("\n"))}return}if(typeof args["selection"]!=="string"||typeof args["idempotency-key"]!=="string")throw new Error("--apply requires --selection and --idempotency-key.");const stat=await fs2.lstat(args["selection"]);if(!stat.isFile()||stat.isSymbolicLink()||stat.size>512*1024)throw new Error("Selection must be a bounded regular JSON file.");const selection=JSON.parse(await fs2.readFile(args["selection"],"utf8"));const{createLocalMemoryImportService}=await import("./local-
|
|
4
|
+
`,error=>error&&error.code!=="EPIPE"?reject(error):resolve())),"writeStdoutLineFlushed");var memoryCommand={command:"memory",describe:"Preview and import external memories",builder:__name(argv=>argv.command({command:"import codex",describe:"Preview Codex memory; explicitly confirm selected sections to consolidate",builder:__name(args=>args.positional("codex",{type:"string",describe:"External memory source",choices:["codex"]}).option("source",{type:"string",describe:"Codex memories directory"}).option("dry-run",{type:"boolean",default:false,describe:"Offline preview; no model or memory writes"}).option("json",{type:"boolean",default:false}).option("apply",{type:"boolean",default:false,describe:"Authorize model consolidation of an explicit selection"}).option("selection",{type:"string",describe:"JSON array of {id, scope: project|user}"}).option("idempotency-key",{type:"string",describe:"Stable caller key for this selection"}).option("retry",{type:"boolean",default:false,describe:"Retry unfinished items of this submitted batch"}).strict(),"builder"),handler:__name(async args=>{ignoreBrokenPipe();if(args["apply"]&&args["dry-run"])throw new Error("--apply and --dry-run cannot be combined.");if(args["apply"]&&(args["bare"]||args["safeMode"]||args["safe-mode"]))throw new Error("Confirmed memory import is unavailable in bare or safe mode. Offline preview remains available.");if(args["source"]!==void 0&&typeof args["source"]!=="string")throw new Error("Provide a single --source directory.");const directory=typeof args["source"]==="string"?args["source"]:path2.join(process.env["CODEX_HOME"]?.trim()||path2.join(homedir(),".codex"),"memories");const source=await readLocalSource(directory);const preview=previewSource(source);if(!args["apply"]){if(args["json"])await writeStdoutLineFlushed(JSON.stringify(preview));else{const lines=[`Preview only: ${preview.sections.length} source sections. No memory was written.`,...preview.groups.map(group=>`[${group.sectionIds.length} sections] ${group.scope}: ${JSON.stringify(group.sourceProject??"No project hint")}`),`Estimated usage (all selectable sections): ${preview.estimate.modelCalls} model calls, ${preview.estimate.sourceTokens} source tokens, up to ${preview.estimate.maxOutputTokens} output tokens; ${preview.estimate.reservedTokens} reserved token units including context.`,`Task limits: ${preview.estimate.limits.maxCalls} calls / ${preview.estimate.limits.maxReservedTokens} reserved token units. Estimates are not billing quotes; explicit selection and existing context affect usage.`];if(preview.estimate.exceedsBudget)lines.push("Warning: the full selection may exceed the task budget; select fewer sections before confirming.");for(const warning of preview.warnings)lines.push(`Warning: ${JSON.stringify(warning)}`);lines.push("Use --json for section IDs, details and source text. To import, provide --apply --selection <JSON file> --idempotency-key <key>. Unassigned sections require an explicit scope.");await writeStdoutLineFlushed(lines.join("\n"))}return}if(typeof args["selection"]!=="string"||typeof args["idempotency-key"]!=="string")throw new Error("--apply requires --selection and --idempotency-key.");const stat=await fs2.lstat(args["selection"]);if(!stat.isFile()||stat.isSymbolicLink()||stat.size>512*1024)throw new Error("Selection must be a bounded regular JSON file.");const selection=JSON.parse(await fs2.readFile(args["selection"],"utf8"));const{createLocalMemoryImportService}=await import("./local-BE624O3A.js");const service=await createLocalMemoryImportService();let task=await service.submit(source,selection,args["idempotency-key"]);if(args["retry"])task=await service.retry(task.id);task=await service.idle(task.id);await writeStdoutLineFlushed(JSON.stringify(task));if(task.status!=="completed"||task.items.some(item=>item.status==="conflict"))process.exitCode=1},"handler")}).demandCommand(1).version(false),"builder"),handler:__name(()=>{},"handler")};export{MEMORY_IMPORT_BUDGET,packMemoryImportSections,MemoryImportRequestError,digest,previewSource,memoryCommand};
|
|
5
5
|
/**
|
|
6
6
|
* @license
|
|
7
7
|
* Copyright 2026 Qwen Team
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{captureRuntimeFileVersion,writeRuntimeFile}from"./chunk-
|
|
3
|
+
import{captureRuntimeFileVersion,writeRuntimeFile}from"./chunk-U3Q72OGV.js";import{checkTeamMemorySecrets,checkWorkspaceTeamMemorySecrets}from"./chunk-UJP2MPBI.js";import{buildWorkspaceArtifactCandidate,formatRecordArtifactReminder}from"./chunk-AKWYMQKU.js";import{CommitAttributionService,FileEncoding,checkPriorRead,createPatchSmart,detectLineEnding,getDiffStat,needsUtf8Bom}from"./chunk-2JGTWRZJ.js";import{backgroundFixHolding}from"./chunk-YVD4O5ZB.js";import{getCurrentAgentId}from"./chunk-YZFNBUKG.js";import{FileOperationEvent,ReadFileTool,getLanguageFromFilePath,logFileOperation}from"./chunk-ZWPSBU7K.js";import{isAnyAutoMemPath,isTeamAutoMemPath}from"./chunk-KVA6DHHF.js";import{fileExists,getSpecificMimeType}from"./chunk-Y6HHV4LC.js";import{safeLiteralReplace}from"./chunk-DBRQGEEI.js";import{BaseDeclarativeTool,StructuredToolError}from"./chunk-O5EKX7LG.js";import{ToolDisplayNames,ToolNames}from"./chunk-SBZFGYYS.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{makeRelative,shortenPath,unescapePath}from"./chunk-OKN3Z5C5.js";import{getErrorMessage,isNodeError}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs";import*as path from"node:path";init_esbuild_shims();var UNICODE_EQUIVALENT_MAP={"\u2010":"-","\u2011":"-","\u2012":"-","\u2013":"-","\u2014":"-","\u2015":"-","\u2212":"-","\u2018":"'","\u2019":"'","\u201A":"'","\u201B":"'","\u201C":'"',"\u201D":'"',"\u201E":'"',"\u201F":'"',"\xA0":" ","\u2002":" ","\u2003":" ","\u2004":" ","\u2005":" ","\u2006":" ","\u2007":" ","\u2008":" ","\u2009":" ","\u200A":" ","\u202F":" ","\u205F":" ","\u3000":" "};function normalizeBasicCharacters(text){if(text===""){return text}let normalized="";for(const char of text){normalized+=UNICODE_EQUIVALENT_MAP[char]??char}return normalized}__name(normalizeBasicCharacters,"normalizeBasicCharacters");var LINE_COMPARISON_PASSES=[value=>value,value=>value.trimEnd()];function normalizeLineForComparison(value){return normalizeBasicCharacters(value).trimEnd()}__name(normalizeLineForComparison,"normalizeLineForComparison");function seekSequenceWithTransform(lines,pattern,transform){if(pattern.length===0){return 0}if(pattern.length>lines.length){return null}outer:for(let i=0;i<=lines.length-pattern.length;i++){for(let p=0;p<pattern.length;p++){if(transform(lines[i+p])!==transform(pattern[p])){continue outer}}return i}return null}__name(seekSequenceWithTransform,"seekSequenceWithTransform");function buildLineIndex(text){const lines=text.split("\n");const offsets=new Array(lines.length+1);let cursor=0;for(let i=0;i<lines.length;i++){offsets[i]=cursor;cursor+=lines[i].length;if(i<lines.length-1){cursor+=1}}offsets[lines.length]=text.length;return{lines,offsets}}__name(buildLineIndex,"buildLineIndex");function sliceFromLines(text,offsets,lines,startLine,lineCount,includeTrailingNewline){if(lineCount===0){return includeTrailingNewline?"\n":""}const startIndex=offsets[startLine]??0;const lastLineIndex=startLine+lineCount-1;const lastLineStart=offsets[lastLineIndex]??0;let endIndex=lastLineStart+(lines[lastLineIndex]?.length??0);if(includeTrailingNewline){const nextLineStart=offsets[startLine+lineCount];if(nextLineStart!==void 0){endIndex=nextLineStart}else if(text.endsWith("\n")){endIndex=text.length}}return text.slice(startIndex,endIndex)}__name(sliceFromLines,"sliceFromLines");function findLineBasedMatch(haystack,needle){const{lines,offsets}=buildLineIndex(haystack);const patternLines=needle.split("\n");const endsWithNewline=needle.endsWith("\n");if(patternLines.length===0){return null}const attemptMatch=__name(candidate=>{for(const pass of LINE_COMPARISON_PASSES){const idx=seekSequenceWithTransform(lines,candidate,pass);if(idx!==null){return idx}}return seekSequenceWithTransform(lines,candidate,normalizeLineForComparison)},"attemptMatch");let matchIndex=attemptMatch(patternLines);if(matchIndex!==null){return{slice:sliceFromLines(haystack,offsets,lines,matchIndex,patternLines.length-(endsWithNewline?1:0),endsWithNewline),removedTrailingFinalEmptyLine:false,lineBasedMatch:true}}if(patternLines.at(-1)===""){const trimmedPattern=patternLines.slice(0,-1);if(trimmedPattern.length===0){return null}matchIndex=attemptMatch(trimmedPattern);if(matchIndex!==null){return{slice:sliceFromLines(haystack,offsets,lines,matchIndex,trimmedPattern.length,false),removedTrailingFinalEmptyLine:true,lineBasedMatch:true}}}return null}__name(findLineBasedMatch,"findLineBasedMatch");function findMatchedSlice(haystack,needle){if(needle===""){return null}const literalIndex=haystack.indexOf(needle);if(literalIndex!==-1){return{slice:haystack.slice(literalIndex,literalIndex+needle.length),removedTrailingFinalEmptyLine:false}}const normalizedHaystack=normalizeBasicCharacters(haystack);const normalizedNeedleChars=normalizeBasicCharacters(needle);const normalizedIndex=normalizedHaystack.indexOf(normalizedNeedleChars);if(normalizedIndex!==-1){return{slice:haystack.slice(normalizedIndex,normalizedIndex+needle.length),removedTrailingFinalEmptyLine:false}}return findLineBasedMatch(haystack,needle)}__name(findMatchedSlice,"findMatchedSlice");function removeTrailingNewline(text){if(text.endsWith("\r\n")){return text.slice(0,-2)}if(text.endsWith("\n")||text.endsWith("\r")){return text.slice(0,-1)}return text}__name(removeTrailingNewline,"removeTrailingNewline");function adjustNewStringForTrailingLine(newString,removedTrailingLine){return removedTrailingLine?removeTrailingNewline(newString):newString}__name(adjustNewStringForTrailingLine,"adjustNewStringForTrailingLine");function normalizeEditStrings(fileContent,oldString,newString){if(fileContent===null||oldString===""){return{oldString,newString}}const canonicalOriginal=findMatchedSlice(fileContent,oldString);if(canonicalOriginal!==null){return{oldString:canonicalOriginal.slice,newString:adjustNewStringForTrailingLine(newString,canonicalOriginal.removedTrailingFinalEmptyLine),...canonicalOriginal.lineBasedMatch?{lineBasedMatch:true}:{}}}return{oldString,newString}}__name(normalizeEditStrings,"normalizeEditStrings");function maybeAugmentOldStringForDeletion(fileContent,oldString,newString,lineBasedMatch=false){if(fileContent===null||oldString===""||newString!==""||oldString.endsWith("\n")){return oldString}const candidate=`${oldString}
|
|
4
4
|
`;const hasCandidate=lineBasedMatch?findLineBasedMatchOffsets(fileContent,candidate).length>0:fileContent.includes(candidate);return hasCandidate?candidate:oldString}__name(maybeAugmentOldStringForDeletion,"maybeAugmentOldStringForDeletion");function countOccurrences(source,substr){if(substr===""){return 0}let count=0;let index=source.indexOf(substr);while(index!==-1){count++;index=source.indexOf(substr,index+substr.length)}return count}__name(countOccurrences,"countOccurrences");function findLineBasedMatchOffsets(source,substr){const offsets=[];if(substr===""){return offsets}let index=source.indexOf(substr);while(index!==-1){const end=index+substr.length;const startsLine=index===0||source[index-1]==="\n";const endsLine=substr.endsWith("\n")||end===source.length||source[end]==="\n";if(startsLine&&endsLine){offsets.push(index);index=source.indexOf(substr,end)}else{index=source.indexOf(substr,index+1)}}return offsets}__name(findLineBasedMatchOffsets,"findLineBasedMatchOffsets");var SNIPPET_CONTEXT_LINES=4;var SNIPPET_MAX_LINES=1e3;function extractEditSnippet(oldContent,newContent){const newLines=newContent.split("\n");const totalLines=newLines.length;if(oldContent===null){return{startLine:1,endLine:totalLines,totalLines,content:newContent}}if(oldContent===newContent||!newContent){return null}const oldLines=oldContent.split("\n");let firstDiffLine=0;const minLength=Math.min(oldLines.length,newLines.length);while(firstDiffLine<minLength){if(oldLines[firstDiffLine]!==newLines[firstDiffLine]){break}firstDiffLine++}let oldEndIndex=oldLines.length-1;let newEndIndex=newLines.length-1;while(oldEndIndex>=firstDiffLine&&newEndIndex>=firstDiffLine){if(oldLines[oldEndIndex]!==newLines[newEndIndex]){break}oldEndIndex--;newEndIndex--}const changeStart=firstDiffLine+1;const changeEnd=newEndIndex+1;if(changeEnd-changeStart>SNIPPET_MAX_LINES){return null}const snippetStart=Math.max(1,changeStart-SNIPPET_CONTEXT_LINES);const snippetEnd=Math.min(totalLines,changeEnd+SNIPPET_CONTEXT_LINES);const snippetLines=newLines.slice(snippetStart-1,snippetEnd);return{startLine:snippetStart,endLine:snippetEnd,totalLines,content:snippetLines.join("\n")}}__name(extractEditSnippet,"extractEditSnippet");var debugLogger=createDebugLogger("EDIT_PRIOR_READ");function applyReplacement(currentContent,oldString,newString,isNewFile,matchOffsets){if(isNewFile){return newString}if(currentContent===null){return oldString===""?newString:""}if(oldString===""&&!isNewFile){return currentContent}if(matchOffsets!==void 0){const pieces=[];let cursor=0;for(const offset of matchOffsets){pieces.push(currentContent.slice(cursor,offset),newString);cursor=offset+oldString.length}pieces.push(currentContent.slice(cursor));return pieces.join("")}return safeLiteralReplace(currentContent,oldString,newString)}__name(applyReplacement,"applyReplacement");var EditToolInvocation=class{constructor(config,params){this.config=config;this.params=params}static{__name(this,"EditToolInvocation")}toolLocations(){return[{path:this.params.file_path}]}async calculateEdit(params,original,signal){const observation=original??await this.config.getFileSystemService().textFileIo?.inspect(params.file_path,signal);const sandboxFileVersion=captureRuntimeFileVersion(this.config,params.file_path);const replaceAll=params.replace_all??false;let currentContent=null;let fileExists2=observation?observation.kind==="file":await fileExists(params.file_path);let isNewFile=false;let finalNewString=params.new_string;let finalOldString=params.old_string;let occurrences=0;let error=void 0;let useBOM=false;let detectedEncoding="utf-8";let detectedLineEnding="lf";if(!this.config.getFileReadCacheDisabled()){const decision=await checkPriorRead(this.config.getFileReadCache(),params.file_path,"editing");if(!decision.ok){return{currentContent:null,newContent:"",occurrences:0,error:{display:decision.displayMessage,raw:decision.rawMessage,type:decision.type},isNewFile:false,encoding:"utf-8",bom:false,lineEnding:"lf"}}}if(fileExists2){try{const fileInfo=observation?.kind==="file"?observation.response:await this.config.getFileSystemService().readTextFile({path:params.file_path});if(fileInfo._meta?.bom!==void 0){useBOM=fileInfo._meta.bom}else{useBOM=fileInfo.content.length>0&&fileInfo.content.codePointAt(0)===65279}detectedEncoding=fileInfo._meta?.encoding||"utf-8";detectedLineEnding=detectLineEnding(fileInfo.content);currentContent=fileInfo.content.replace(/\r\n/g,"\n");fileExists2=true}catch(err){if(!isNodeError(err)||err.code!=="ENOENT"){throw err}fileExists2=false}}if(fileExists2&&!this.config.getFileReadCacheDisabled()){const postDecision=await checkPriorRead(this.config.getFileReadCache(),params.file_path,"editing",{expectExisting:true});if(!postDecision.ok){debugLogger.warn("post-read TOCTOU rejection",{path:params.file_path,reason:postDecision.type});return{currentContent:null,newContent:"",occurrences:0,error:{display:postDecision.displayMessage,raw:postDecision.rawMessage,type:postDecision.type},isNewFile:false,encoding:"utf-8",bom:false,lineEnding:"lf"}}}const normalizedStrings=normalizeEditStrings(currentContent,finalOldString,finalNewString);finalOldString=normalizedStrings.oldString;finalNewString=normalizedStrings.newString;let matchOffsets;if(finalOldString===""&&!fileExists2){isNewFile=true}else if(!fileExists2){error={display:`File not found. Cannot apply edit. Use an empty old_string to create a new file.`,raw:`File not found: ${params.file_path}`,type:"file_not_found"}}else if(currentContent!==null){finalOldString=maybeAugmentOldStringForDeletion(currentContent,finalOldString,finalNewString,normalizedStrings.lineBasedMatch);if(normalizedStrings.lineBasedMatch){matchOffsets=findLineBasedMatchOffsets(currentContent,finalOldString)}occurrences=matchOffsets?.length??countOccurrences(currentContent,finalOldString);if(params.old_string===""){error={display:`Failed to edit. Attempted to create a file that already exists.`,raw:`File already exists, cannot create: ${params.file_path}`,type:"attempt_to_create_existing_file"}}else if(occurrences===0){error={display:`Failed to edit, could not find the string to replace.`,raw:`Failed to edit, 0 occurrences found for old_string in ${params.file_path}. No edits made. The exact text in old_string was not found. Ensure you're not escaping content incorrectly and check whitespace, indentation, and context. Use ${ReadFileTool.Name} tool to verify.`,type:"edit_no_occurrence_found"}}else if(!replaceAll&&occurrences>1){error={display:`Failed to edit because the text matches multiple locations. Provide more context or set replace_all to true.`,raw:`Failed to edit. Found ${occurrences} occurrences for old_string in ${params.file_path} but replace_all was not enabled.`,type:"edit_expected_occurrence_mismatch"}}else if(finalOldString===finalNewString){error={display:`No changes to apply. The old_string and new_string are identical.`,raw:`No changes to apply. The old_string and new_string are identical in file: ${params.file_path}`,type:"edit_no_change"}}}else{error={display:`Failed to read content of file.`,raw:`Failed to read content of existing file: ${params.file_path}`,type:"read_content_failure"}}const newContent=!error?applyReplacement(currentContent,finalOldString,finalNewString,isNewFile,matchOffsets):currentContent??"";if(!error&&fileExists2&¤tContent===newContent){error={display:"No changes to apply. The new content is identical to the current content.",raw:`No changes to apply. The new content is identical to the current content in file: ${params.file_path}`,type:"edit_no_change"}}if(!error){const teamMemoryError=(this.config.getFileSystemService().textFileIo?checkWorkspaceTeamMemorySecrets:checkTeamMemorySecrets)(params.file_path,newContent,this.config.getProjectRoot());if(teamMemoryError){const preExisting=currentContent!==null&&(this.config.getFileSystemService().textFileIo?checkWorkspaceTeamMemorySecrets:checkTeamMemorySecrets)(params.file_path,currentContent,this.config.getProjectRoot())!==null;const message=preExisting?`${teamMemoryError} Note: the secret already exists in the current file content, so removing it from your edit alone is not enough \u2014 delete the committed secret from the file.`:teamMemoryError;error={display:message,raw:message,type:"invalid_tool_params"}}}return{currentContent,newContent,sandboxFileVersion,occurrences,error,isNewFile,bom:useBOM,encoding:detectedEncoding,lineEnding:detectedLineEnding}}requiresUserInteraction(){return backgroundFixHolding(this.params.file_path,getCurrentAgentId())!==void 0}async getDefaultPermission(){if(this.config.getFileSystemService().textFileIo)return"ask";const projectRoot=this.config.getProjectRoot();const filePath=path.resolve(this.params.file_path);if(isTeamAutoMemPath(filePath,projectRoot)){return"ask"}if(isAnyAutoMemPath(filePath,projectRoot)){return"allow"}return"ask"}async getConfirmationDetails(abortSignal){let editData;try{editData=await this.calculateEdit(this.params,void 0,abortSignal)}catch(error){if(abortSignal.aborted){throw error}const errorMsg=isNodeError(error)&&error.code==="EISDIR"?`Target is a directory, not a file: ${this.params.file_path} (${error.code})`:getErrorMessage(error);throw new Error(`Error preparing edit: ${errorMsg}`)}if(editData.error){throw new StructuredToolError(editData.error.raw,editData.error.type)}const fileName=path.basename(this.params.file_path);const fileDiff=createPatchSmart(fileName,editData.currentContent??"",editData.newContent,"Current","Proposed");const confirmationDetails={type:"edit",title:`Confirm Edit: ${shortenPath(makeRelative(this.params.file_path,this.config.getTargetDir()))}`,fileName,filePath:this.params.file_path,fileDiff,originalContent:editData.currentContent,newContent:editData.newContent,onConfirm:__name(async outcome=>{if(outcome==="proceed_always"){this.config.setApprovalMode("auto-edit")}},"onConfirm")};return confirmationDetails}getDescription(){const relativePath=makeRelative(this.params.file_path,this.config.getTargetDir());if(this.params.old_string===""){return`Create ${shortenPath(relativePath)}`}if(this.params.old_string===this.params.new_string){return`No file changes to ${shortenPath(relativePath)}`}return shortenPath(relativePath)}async execute(signal){try{const io=this.config.getFileSystemService().textFileIo;return io?await io.withMutation(this.params.file_path,signal,mutation=>this.executeObserved(signal,mutation)):await this.executeObserved(signal)}catch(error){if(signal.aborted)throw error;return this.writeFailure(error)}}async executeObserved(signal,mutation){let editData;try{editData=await this.calculateEdit(this.params,mutation?.original,signal)}catch(error){if(signal.aborted){throw error}const errorMsg=getErrorMessage(error);return{llmContent:`Error preparing edit: ${errorMsg}`,returnDisplay:`Error preparing edit: ${errorMsg}`,error:{message:errorMsg,type:"edit_preparation_failure"}}}if(editData.error){return{llmContent:editData.error.raw,returnDisplay:`Error: ${editData.error.display}`,error:{message:editData.error.raw,type:editData.error.type}}}try{try{await this.config.getFileHistoryService().trackEdit(this.params.file_path)}catch{}if(!this.config.getFileReadCacheDisabled()){const writeDecision=await checkPriorRead(this.config.getFileReadCache(),this.params.file_path,"editing",{expectExisting:!editData.isNewFile});if(!writeDecision.ok){debugLogger.warn("pre-write TOCTOU rejection",{path:this.params.file_path,reason:writeDecision.type});return{llmContent:writeDecision.rawMessage,returnDisplay:`Error: ${writeDecision.displayMessage}`,error:{message:writeDecision.rawMessage,type:writeDecision.type}}}}if(!mutation&&!this.config.getShellExecutionSandbox?.()){this.ensureParentDirectoriesExist(this.params.file_path)}let committedStats;const write=__name(async params=>{if(mutation)committedStats=await mutation.write(params);else await writeRuntimeFile(this.config,params,editData.sandboxFileVersion,signal)},"write");if(editData.isNewFile){const userEncoding=this.config.getDefaultFileEncoding();let useBOM=false;if(userEncoding===FileEncoding.UTF8_BOM){useBOM=true}else if(userEncoding===void 0){useBOM=needsUtf8Bom(this.params.file_path)}await write({path:this.params.file_path,content:editData.newContent,toolWriteOrigin:"edit",_meta:{bom:useBOM}})}else{await write({path:this.params.file_path,content:editData.newContent,toolWriteOrigin:"edit",_meta:{bom:editData.bom,encoding:editData.encoding,lineEnding:editData.lineEnding}})}if(!mutation&&!this.params.modified_by_user){CommitAttributionService.getInstance().recordEdit(this.params.file_path,editData.currentContent,editData.newContent)}let postWriteSizeBytes;try{if(mutation&&!committedStats)throw new Error("Scoped file write returned no committed stats.");const postWriteStats=mutation?committedStats:fs.statSync(this.params.file_path);postWriteSizeBytes=postWriteStats.size;this.config.getFileReadCache().recordWrite(this.params.file_path,postWriteStats)}catch(error){if(mutation)throw error}const fileName=path.basename(this.params.file_path);const originallyProposedContent=this.params.ai_proposed_content||editData.newContent;const diffStat=getDiffStat(fileName,editData.currentContent??"",originallyProposedContent,editData.newContent);const fileDiff=createPatchSmart(fileName,editData.currentContent??"",editData.newContent,"Current","Proposed");const displayResult={fileDiff,fileName,filePath:this.params.file_path,originalContent:editData.currentContent,newContent:editData.newContent,diffStat};const mimetype=getSpecificMimeType(this.params.file_path);const programmingLanguage=getLanguageFromFilePath(this.params.file_path);const extension=path.extname(this.params.file_path);const operation=editData.isNewFile?"create":"update";logFileOperation(this.config,new FileOperationEvent(EditTool.Name,operation,editData.newContent.split("\n").length,mimetype,extension,programmingLanguage));const llmSuccessMessageParts=[editData.isNewFile?`Created new file: ${this.params.file_path} with provided content.`:`The file: ${this.params.file_path} has been updated.`];const artifact=buildWorkspaceArtifactCandidate(this.config,this.params.file_path,{recordAsArtifact:this.params.record_as_artifact,sizeBytes:postWriteSizeBytes});if(artifact&&!artifact.updateOnly){llmSuccessMessageParts.push(formatRecordArtifactReminder(artifact.workspacePath))}const snippetResult=extractEditSnippet(editData.currentContent,editData.newContent);if(snippetResult){const snippetText=`Showing lines ${snippetResult.startLine}-${snippetResult.endLine} of ${snippetResult.totalLines} from the edited file:
|
|
5
5
|
|
|
6
6
|
---
|