decocms 4.192.7 → 4.192.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/assets/{AlertCircle-CrPTg7No.js → AlertCircle-BOSW8McT.js} +1 -1
- package/dist/client/assets/{AreaChart-tiBy2zpY.js → AreaChart-BTNlYG5x.js} +1 -1
- package/dist/client/assets/{ArrowUp-CIA12Ft8.js → ArrowUp-BkBtF6n3.js} +1 -1
- package/dist/client/assets/{ArrowUpRight-BXb5bWZv.js → ArrowUpRight-X95YsCqU.js} +1 -1
- package/dist/client/assets/{Check-BnRBTd85.js → Check-DAA34cln.js} +1 -1
- package/dist/client/assets/{CheckCircle-CBgF5Rm2.js → CheckCircle-CKafcGp3.js} +1 -1
- package/dist/client/assets/{ChevronDown-Cy4TAhau.js → ChevronDown-Dps4jr8v.js} +1 -1
- package/dist/client/assets/{ChevronRight-De_XPs2J.js → ChevronRight-DjBBp7VZ.js} +1 -1
- package/dist/client/assets/{ChevronUp-MtxRwI_P.js → ChevronUp-pxXEzY82.js} +1 -1
- package/dist/client/assets/{Copy01-Cna9zOFE.js → Copy01-Cfx261cq.js} +1 -1
- package/dist/client/assets/{CpuChip01-BTs5EmAK.js → CpuChip01-wzcmBaJo.js} +1 -1
- package/dist/client/assets/{CreditCard01-D5vSzbnW.js → CreditCard01-VWcD7Vun.js} +1 -1
- package/dist/client/assets/{DotsVertical-D1sFRI3y.js → DotsVertical-HvZM7xK4.js} +1 -1
- package/dist/client/assets/{Eye-D3Qlftta.js → Eye-Bphtm2bA.js} +1 -1
- package/dist/client/assets/{FilterLines-BWJyLICS.js → FilterLines-C9V01c7j.js} +1 -1
- package/dist/client/assets/{HardDrive-CnGIgAcW.js → HardDrive-DPTTUbIK.js} +1 -1
- package/dist/client/assets/{Key01-BtzimodV.js → Key01-Cym6c56a.js} +1 -1
- package/dist/client/assets/{LayoutLeft-Bok-19yc.js → LayoutLeft-Bl-RtHw_.js} +1 -1
- package/dist/client/assets/{LinkExternal01-DRRE-MEW.js → LinkExternal01-ysNP7Rwg.js} +1 -1
- package/dist/client/assets/{LogOut01-XC88FbH6.js → LogOut01-nYnoQ2Rv.js} +1 -1
- package/dist/client/assets/{Monitor01-C0_dBUR9.js → Monitor01-BZjrIPQe.js} +1 -1
- package/dist/client/assets/{Palette-Ct5N9Uum.js → Palette-C4JBsoLG.js} +1 -1
- package/dist/client/assets/{Play-B9tb-IAb.js → Play-BJa69jMZ.js} +1 -1
- package/dist/client/assets/{Plus-cYmSDHgU.js → Plus-CFb-UdyS.js} +1 -1
- package/dist/client/assets/{SearchLg-Be_T2R0D.js → SearchLg-C8XesIzu.js} +1 -1
- package/dist/client/assets/{SearchMd-CIqlXmg-.js → SearchMd-CvZT8N8n.js} +1 -1
- package/dist/client/assets/{Settings02-Cd96ZcWx.js → Settings02-BNGOoScu.js} +1 -1
- package/dist/client/assets/{Shield01-g9Pmi2fz.js → Shield01-DPcW6OQd.js} +1 -1
- package/dist/client/assets/{Star01-BdbwBCs_.js → Star01-B8cGpZgZ.js} +1 -1
- package/dist/client/assets/{Stars01-4Xp1dlQa.js → Stars01-BjeZCA0g.js} +1 -1
- package/dist/client/assets/{Stars02-B4nh6_6J.js → Stars02-CjVHZR0r.js} +1 -1
- package/dist/client/assets/{Sun-C1gnjPxJ.js → Sun-BJyHkDWZ.js} +1 -1
- package/dist/client/assets/{SwitchHorizontal01-BQASu3Ld.js → SwitchHorizontal01-WNRytacj.js} +1 -1
- package/dist/client/assets/{Tool01-BQBlAfKK.js → Tool01-Cqq8NF60.js} +1 -1
- package/dist/client/assets/{Tool02-EfT7Aj_N.js → Tool02-uDZtzT-0.js} +1 -1
- package/dist/client/assets/{Trash01-qhWeifH9.js → Trash01-D1X5X_Ql.js} +1 -1
- package/dist/client/assets/{TrendUp01--l5g3LV7.js → TrendUp01-Bds_rQN9.js} +1 -1
- package/dist/client/assets/{Upload01-DB8t6fYP.js → Upload01-RwrIk9fS.js} +1 -1
- package/dist/client/assets/{User01-PQ_zrkhy.js → User01-ByEicosz.js} +1 -1
- package/dist/client/assets/{Users01-D0oW6faK.js → Users01-Ctr_QrYH.js} +1 -1
- package/dist/client/assets/{Users03-89bzO49O.js → Users03-C-4z227b.js} +1 -1
- package/dist/client/assets/{X-XOpfjAzX.js → X-DYd9-bQR.js} +1 -1
- package/dist/client/assets/{XCircle-CPiaBR9U.js → XCircle-BEyMaIJs.js} +1 -1
- package/dist/client/assets/{XClose-BBgkL7xx.js → XClose-DmQBmGj4.js} +1 -1
- package/dist/client/assets/{Zap-B3YPgxSD.js → Zap-BuYeosmu.js} +1 -1
- package/dist/client/assets/{ZapSquare-p78bcJrZ.js → ZapSquare-BqLBxjeD.js} +1 -1
- package/dist/client/assets/{access-gate-CSs0hmqm.js → access-gate-B3sDUJw_.js} +1 -1
- package/dist/client/assets/{agent-icon-IchZk8Sr.js → agent-icon-BRzdzDMX.js} +1 -1
- package/dist/client/assets/{agents-list-BELa4Qbi.js → agents-list-tPn0OJmn.js} +1 -1
- package/dist/client/assets/{ai-providers-BIzKRt3u.js → ai-providers-3QDyDVoz.js} +1 -1
- package/dist/client/assets/{alert-STtEcxfy.js → alert-CYaiW3B6.js} +1 -1
- package/dist/client/assets/{alert-dialog-DNVAKC3E.js → alert-dialog-CT4c7zEm.js} +1 -1
- package/dist/client/assets/{app-editor-FaPWiBOg.js → app-editor-Bhzmzlld.js} +1 -1
- package/dist/client/assets/{auth-catchall-Vhmd-pZb.js → auth-catchall-DYYUFH9-.js} +1 -1
- package/dist/client/assets/{auth-entry-DqnrlknX.js → auth-entry-Cfp5XWiu.js} +1 -1
- package/dist/client/assets/{auth-split-layout-CQFaIdTr.js → auth-split-layout-Bn5eVfxs.js} +1 -1
- package/dist/client/assets/{auth-RIRzVJ_F.js → auth-vIM2JGjs.js} +1 -1
- package/dist/client/assets/{authenticate-and-persist-oauth-DTJQ2RW5.js → authenticate-and-persist-oauth-DtAJWfgY.js} +1 -1
- package/dist/client/assets/{automation-list-row-LBe18aeG.js → automation-list-row-V-NusB7F.js} +1 -1
- package/dist/client/assets/{automation-runs-rqNz0rC6.js → automation-runs-DNYBsdFO.js} +1 -1
- package/dist/client/assets/{automations-DsxhOqDQ.js → automations-Cb0VW9jw.js} +1 -1
- package/dist/client/assets/{avatar-DTYC3n17.js → avatar-DpgmzM-C.js} +1 -1
- package/dist/client/assets/{badge-7qIblq2m.js → badge-DhInOzSE.js} +1 -1
- package/dist/client/assets/{billing-kPnkyznO.js → billing-BcUJMZOu.js} +1 -1
- package/dist/client/assets/{block-document-BELebIgi.js → block-document-CFq9iPdj.js} +1 -1
- package/dist/client/assets/{brand-context-DgWSLLc-.js → brand-context-BAFyliQ3.js} +1 -1
- package/dist/client/assets/{buckets-t7lL_JmS.js → buckets-DZRTWljI.js} +1 -1
- package/dist/client/assets/{bulk-category-panel-BT_WoOli.js → bulk-category-panel-BYxu06yv.js} +1 -1
- package/dist/client/assets/{capability-load-error-B_2iPv1g.js → capability-load-error-DQq6a2oP.js} +1 -1
- package/dist/client/assets/{card-BM5YAxhc.js → card-muiAefpm.js} +1 -1
- package/dist/client/assets/{category-editor--8nv-lbZ.js → category-editor-Uczlyq7g.js} +1 -1
- package/dist/client/assets/{chat-context-C2dsySEt.js → chat-context-Cfqv2xst.js} +1 -1
- package/dist/client/assets/{checkbox-DUTZPi5Z.js → checkbox-DAr-1UV0.js} +1 -1
- package/dist/client/assets/{cli-auth-success-Cb5YaOny.js → cli-auth-success-BQCM8lhx.js} +1 -1
- package/dist/client/assets/{collection-detail-D-0eec2n.js → collection-detail-BQEHIwJe.js} +1 -1
- package/dist/client/assets/{collection-display-button-C85sEykc.js → collection-display-button-BzK14mIZ.js} +1 -1
- package/dist/client/assets/{collection-search-B4aAzdt3.js → collection-search-z0gLwVLv.js} +1 -1
- package/dist/client/assets/{collection-table-wrapper-BJL7k6gA.js → collection-table-wrapper-CNPSvwWw.js} +1 -1
- package/dist/client/assets/{collection-tabs-E2Di7cti.js → collection-tabs-D_FJmToO.js} +1 -1
- package/dist/client/assets/{command-DLmCdwW8.js → command-DTLsE6pF.js} +1 -1
- package/dist/client/assets/{commerce-onboarding-CleoeHM2.js → commerce-onboarding-CWDK2Ljt.js} +1 -1
- package/dist/client/assets/{connect-BgaWoDo0.js → connect-55fmh1K3.js} +1 -1
- package/dist/client/assets/{connection-card-CcOb_S6j.js → connection-card-C6G9D7Un.js} +1 -1
- package/dist/client/assets/{connection-detail-Dx1OplZ2.js → connection-detail-BE-yJjN7.js} +1 -1
- package/dist/client/assets/{connection-form-helpers-CN2A1A9y.js → connection-form-helpers-fkOHOaEd.js} +1 -1
- package/dist/client/assets/{connection-BFRX1eza.js → connection-xMrA-dJr.js} +1 -1
- package/dist/client/assets/{connections-DTn_S2co.js → connections-CxIr9UQO.js} +1 -1
- package/dist/client/assets/{decopilot-sse-pool-YrN0OqM2.js → decopilot-sse-pool-LCU3rvfW.js} +1 -1
- package/dist/client/assets/{dialog-C14SMLwt.js → dialog-DiF_CqBf.js} +1 -1
- package/dist/client/assets/{domain-settings-Cktoj9Pg.js → domain-settings-U7Ky1ZpV.js} +1 -1
- package/dist/client/assets/{drawer-BlwkhsOh.js → drawer-CfIU42Lb.js} +1 -1
- package/dist/client/assets/{dropdown-menu-Cza4sblW.js → dropdown-menu-hheVK5sl.js} +1 -1
- package/dist/client/assets/{empty-state-BT3eZ3t6.js → empty-state-B7fT4jSY.js} +1 -1
- package/dist/client/assets/{extract-connection-data-DAdthAVN.js → extract-connection-data-D0vyyJLn.js} +1 -1
- package/dist/client/assets/{file-explorer-BDrfu6vK.js → file-explorer-CPxhUx9E.js} +1 -1
- package/dist/client/assets/{form-CDwptF3_.js → form-lOM9JBIR.js} +1 -1
- package/dist/client/assets/{general-DS05-Sgj.js → general-E_BNDsCa.js} +1 -1
- package/dist/client/assets/{github-repo-picker-CscDiobR.js → github-repo-picker-Bp8iDkD4.js} +1 -1
- package/dist/client/assets/{hooks-DF_D3yjz.js → hooks-J5boFMaD.js} +1 -1
- package/dist/client/assets/{index-CkTN0St6.js → index-7Ss9D2ap.js} +1 -1
- package/dist/client/assets/{index-a4eq1Xeg.js → index-B6z_wYKG.js} +1 -1
- package/dist/client/assets/{index-BTG8kyya.js → index-BMP-hd0g.js} +1 -1
- package/dist/client/assets/{index-C-jc6NUA.js → index-ByczaLH7.js} +1 -1
- package/dist/client/assets/{index-CqgMAdZ1.js → index-CDB7Y_ga.js} +1 -1
- package/dist/client/assets/{index-TC3tVDwp.js → index-CWIwRZmI.js} +1 -1
- package/dist/client/assets/{index-DK6z4kxh.js → index-CbyQSWBO.js} +1 -1
- package/dist/client/assets/{index-B7idRLgU.js → index-DeQW5CVX.js} +1 -1
- package/dist/client/assets/{index-BLQzaBqp.js → index-DfoOkcJo.js} +3 -3
- package/dist/client/assets/{index-DZO0tTUF.js → index-Y18wPxLA.js} +1 -1
- package/dist/client/assets/{index-YBcH-y-a.js → index-aRoQGgld.js} +45 -45
- package/dist/client/assets/{index-redirect-taDw4dpf.js → index-redirect-BvILdLAD.js} +1 -1
- package/dist/client/assets/{input-DqRWUg_X.js → input-DXr1Spkt.js} +1 -1
- package/dist/client/assets/{integration-icon-MYUnDpsF.js → integration-icon-DUYQwAKy.js} +1 -1
- package/dist/client/assets/{invite-member-dialog-DoErhEvL.js → invite-member-dialog-TF3IFTRY.js} +1 -1
- package/dist/client/assets/{label-BshhAzRV.js → label-DcnmyKme.js} +1 -1
- package/dist/client/assets/{layout-JxE1Xnl7.js → layout-DspIRnBn.js} +1 -1
- package/dist/client/assets/{login-BfN-zR0E.js → login-ngXaQ9Bq.js} +1 -1
- package/dist/client/assets/{mcp-oauth-4WKZZaaI.js → mcp-oauth-DAcqJUw4.js} +1 -1
- package/dist/client/assets/{members-BZgTmgnG.js → members-BSmMuJim.js} +1 -1
- package/dist/client/assets/{monaco-editor-B_CX8Zr7.js → monaco-editor-D9F4nlJ1.js} +1 -1
- package/dist/client/assets/{monitoring-stats-row-BoGfdehq.js → monitoring-stats-row-8RZT3C2Q.js} +1 -1
- package/dist/client/assets/{multi-select-CrbmnexR.js → multi-select-CiLN3n8i.js} +1 -1
- package/dist/client/assets/{oauth-callback-D6V30oFQ.js → oauth-callback-BCRuuvzk.js} +1 -1
- package/dist/client/assets/{oauth-callback-ai-provider-CSJnTXv_.js → oauth-callback-ai-provider-C4C55jop.js} +1 -1
- package/dist/client/assets/{onboarding-BCNCpvpq.js → onboarding-CEORDVRe.js} +1 -1
- package/dist/client/assets/{org-layout-E2gRJphB.js → org-layout-CrhZn9qB.js} +1 -1
- package/dist/client/assets/{organization-choice-0J5xCyfo.js → organization-choice-CWy_lJnO.js} +1 -1
- package/dist/client/assets/{orgs-0Df2rFZM.js → orgs-B4O4wWbM.js} +1 -1
- package/dist/client/assets/{page-seo-form-CqPX9GFP.js → page-seo-form-kal-3x9A.js} +1 -1
- package/dist/client/assets/{popover-Bx5oqEx8.js → popover-DZhWA-Tj.js} +1 -1
- package/dist/client/assets/{post-editor-CRsA4SKG.js → post-editor-BC5boYrq.js} +1 -1
- package/dist/client/assets/{primitives-BZta1p6M.js → primitives-CM8WvcDT.js} +1 -1
- package/dist/client/assets/{profile-BXdbUd2R.js → profile-nxtROYOv.js} +1 -1
- package/dist/client/assets/{project-app-view-Bupj8bfK.js → project-app-view-DISsTazD.js} +1 -1
- package/dist/client/assets/record-editor-YxfS8Aye.js +1 -0
- package/dist/client/assets/{redirect-editor-BpmIW6_k.js → redirect-editor-Cao8L96B.js} +1 -1
- package/dist/client/assets/registry-DnMz1ZTz.js +2 -0
- package/dist/client/assets/{registry-layout-DcjX7Zlv.js → registry-layout-C67p0TBZ.js} +1 -1
- package/dist/client/assets/{reports-GWHHYvKk.js → reports-DWW3_iec.js} +1 -1
- package/dist/client/assets/{require-capability-Di-8DrsT.js → require-capability-j7XfwDGW.js} +1 -1
- package/dist/client/assets/{required-auth-layout-COsg3fQu.js → required-auth-layout-C90qoEH-.js} +1 -1
- package/dist/client/assets/{reset-password-B1YEx0OV.js → reset-password-Pl7HZ7VZ.js} +1 -1
- package/dist/client/assets/{roles-EDxWkorY.js → roles-D8-48yZO.js} +1 -1
- package/dist/client/assets/{search-input-p8Zj-yoq.js → search-input-UXmWS5tO.js} +1 -1
- package/dist/client/assets/{secrets-CG9MVAhj.js → secrets-PmA8VrI2.js} +1 -1
- package/dist/client/assets/{sections-editor-3J6fiIE3.js → sections-editor-B2sOhMUu.js} +1 -1
- package/dist/client/assets/{select-BnjaOaK4.js → select-BK3qiJGa.js} +1 -1
- package/dist/client/assets/{select-model-bGvPj-Yy.js → select-model-jpOlLXZw.js} +1 -1
- package/dist/client/assets/{self-tool-result-DY6Cs88K.js → self-tool-result-BVBvSU4V.js} +1 -1
- package/dist/client/assets/{seo-editor-DlrMfO0C.js → seo-editor-4YKqDpHQ.js} +1 -1
- package/dist/client/assets/{settings-layout-Jq8ewdvX.js → settings-layout--vR_7BnE.js} +1 -1
- package/dist/client/assets/{settings-section-dCOi8NXz.js → settings-section-CUWo_eFU.js} +1 -1
- package/dist/client/assets/{shell-controls-sNNpK9Ox.js → shell-controls-DierNWP_.js} +1 -1
- package/dist/client/assets/{shell-layout-D674F3MK.js → shell-layout-DTjLAcVA.js} +1 -1
- package/dist/client/assets/{sidebar-CYolSc7W.js → sidebar-54i_6TYm.js} +1 -1
- package/dist/client/assets/{skeleton-kylkRkJL.js → skeleton-DHUlxYay.js} +1 -1
- package/dist/client/assets/{spinner-Cpm_FgXI.js → spinner-CWIrnFEV.js} +1 -1
- package/dist/client/assets/{sso-UnfAzoNH.js → sso-UBNll3tV.js} +1 -1
- package/dist/client/assets/{store-qsxuMwFM.js → store-B8Dn6q50.js} +1 -1
- package/dist/client/assets/store-registry-BINLmvF3.js +2 -0
- package/dist/client/assets/{studio-tools-CqkAaE56.js → studio-tools-BIbFnBXE.js} +1 -1
- package/dist/client/assets/{switch-2Gbfs8A3.js → switch-BoqQXRvX.js} +1 -1
- package/dist/client/assets/{tab-id-C_Nz879h.js → tab-id-Dpmvvd5t.js} +1 -1
- package/dist/client/assets/{table--uMbezaR.js → table-Dh7FhtZl.js} +1 -1
- package/dist/client/assets/{tabs-AF9xbuOq.js → tabs-C2MXbO58.js} +1 -1
- package/dist/client/assets/{textarea-CaGR5BSW.js → textarea-BkdMh9DN.js} +1 -1
- package/dist/client/assets/{toggle-group-Cz-Qz3yI.js → toggle-group-Ip28xVX6.js} +1 -1
- package/dist/client/assets/{toolbar-7SzUuTow.js → toolbar-BSvlIrrP.js} +1 -1
- package/dist/client/assets/{tooltip-pEMnAu2z.js → tooltip-BS3U8OVU.js} +1 -1
- package/dist/client/assets/{use-ai-providers-CF0wvQRN.js → use-ai-providers-CnezSGcD.js} +1 -1
- package/dist/client/assets/{use-automations-BnYeuFV5.js → use-automations-BBnT6YrU.js} +1 -1
- package/dist/client/assets/{use-autosave-GVMngDQ5.js → use-autosave-Oyl6am1G.js} +1 -1
- package/dist/client/assets/{use-capability-Mrgv-isI.js → use-capability-CiHI9DwH.js} +1 -1
- package/dist/client/assets/{use-clock-tick-CaQwC1ct.js → use-clock-tick-DhgxrDoC.js} +1 -1
- package/dist/client/assets/{use-connection-Bpd3SbKJ.js → use-connection-Be8xsycK.js} +1 -1
- package/dist/client/assets/{use-copy-CCO4IbpG.js → use-copy-DkcKhlkI.js} +1 -1
- package/dist/client/assets/{use-create-virtual-mcp-CAlERGk1.js → use-create-virtual-mcp-CzzSh-y9.js} +1 -1
- package/dist/client/assets/{use-debounced-autosave-ZN-fh-JT.js → use-debounced-autosave-CkrkyMdT.js} +1 -1
- package/dist/client/assets/{use-debounced-value-DRt9VufC.js → use-debounced-value-BCeEQ_Pu.js} +1 -1
- package/dist/client/assets/{use-deco-credits-ia60QQ_5.js → use-deco-credits-D62kDUUQ.js} +1 -1
- package/dist/client/assets/{use-decopilot-events-Ba_nm49q.js → use-decopilot-events-Ce-YVlMd.js} +1 -1
- package/dist/client/assets/{use-delete-connection-BOH-auJ7.js → use-delete-connection-BM1yShXx.js} +1 -1
- package/dist/client/assets/{use-deployment-admin-ClfKO8-6.js → use-deployment-admin-DCBOTLr0.js} +1 -1
- package/dist/client/assets/{use-file-configs-CK7ilKFm.js → use-file-configs-DYEvkWht.js} +1 -1
- package/dist/client/assets/{use-infinite-scroll-COkSGeCQ.js → use-infinite-scroll-i-g233uh.js} +1 -1
- package/dist/client/assets/{use-join-requests-BMbGlLA1.js → use-join-requests-CYb5ODj2.js} +1 -1
- package/dist/client/assets/{use-mcp-client-D3_O582k.js → use-mcp-client-JNWoK2mW.js} +1 -1
- package/dist/client/assets/{use-mcp-tools-CYCyBiDo.js → use-mcp-tools-DqWTgfG0.js} +1 -1
- package/dist/client/assets/{use-members-DpL8h_63.js → use-members-CiZKGxVy.js} +1 -1
- package/dist/client/assets/{use-mobile-8cBnDbFR.js → use-mobile-BamQqYS0.js} +1 -1
- package/dist/client/assets/{use-navigate-to-agent-Cajm0dwo.js → use-navigate-to-agent-KXTuAO9Q.js} +1 -1
- package/dist/client/assets/{use-open-billing-url-BY0R7rhj.js → use-open-billing-url-DYOUliDT.js} +1 -1
- package/dist/client/assets/{use-org-auth-client-c30FIVxP.js → use-org-auth-client-B9ZPbAD8.js} +1 -1
- package/dist/client/assets/{use-org-sso-CqyBFPOS.js → use-org-sso-DavpnXMG.js} +1 -1
- package/dist/client/assets/{use-organization-roles-B6qTwsCe.js → use-organization-roles-CxAzembA.js} +1 -1
- package/dist/client/assets/{use-organization-settings-DTbPHIkP.js → use-organization-settings-BaY-OHxS.js} +1 -1
- package/dist/client/assets/{use-registry-connections-CIDSY_R4.js → use-registry-connections-qOB4Znqu.js} +1 -1
- package/dist/client/assets/{use-secrets-C9EtgdjO.js → use-secrets-DIb0hAOL.js} +1 -1
- package/dist/client/assets/{use-section-preview-base-B5R928ud.js → use-section-preview-base-DJY13yCB.js} +1 -1
- package/dist/client/assets/{use-status-sounds-CU1P-DAS.js → use-status-sounds-BKvRISS9.js} +1 -1
- package/dist/client/assets/{use-tags-CvxWwuAD.js → use-tags-D_DHB3az.js} +1 -1
- package/dist/client/assets/{use-view-mode-CNZOuy-V.js → use-view-mode-Z-TRQKId.js} +1 -1
- package/dist/client/assets/{use-virtual-mcp-uyaNdGW1.js → use-virtual-mcp-MNxD6f7j.js} +1 -1
- package/dist/client/assets/useInfiniteQuery-T3LRIki8.js +1 -0
- package/dist/client/assets/{useRouterState-CEV2fYj5.js → useRouterState-NWXn0w1-.js} +1 -1
- package/dist/client/assets/useSuspenseInfiniteQuery-CMjwiI0t.js +1 -0
- package/dist/client/assets/{users-DdICln4m.js → users-Ct2Gz6Kf.js} +1 -1
- package/dist/client/assets/{variant-calendar-DW0WI87W.js → variant-calendar-si9NxmK1.js} +1 -1
- package/dist/client/assets/{view-mode-toggle-DJEb-NoL.js → view-mode-toggle-CDzORX16.js} +1 -1
- package/dist/client/index.html +1 -1
- package/dist/server/cli.js +2 -2
- package/dist/server/server.js +2 -2
- package/package.json +1 -1
- package/dist/client/assets/record-editor-D99pxZjJ.js +0 -1
- package/dist/client/assets/registry-CO9d81wl.js +0 -2
- package/dist/client/assets/store-registry-DXsP6g0C.js +0 -2
- package/dist/client/assets/useInfiniteQuery-CeMD7BLn.js +0 -1
- package/dist/client/assets/useSuspenseInfiniteQuery-Dvl3BS-i.js +0 -1
package/dist/server/cli.js
CHANGED
|
@@ -1310,7 +1310,7 @@ Usage: deco services <up|down|status>`),process.exit(1)}}var Jc1=O(()=>{Tx()});f
|
|
|
1310
1310
|
`.execute($);if(Number(W.rows[0]?.cnt)===0){console.warn(`Failed to migrate ${J}/${K}, keeping in old table`);continue}}await af`
|
|
1311
1311
|
DELETE FROM kysely_migration WHERE name = ${X}
|
|
1312
1312
|
`.execute($)}}async function Pi1($){await Tu6($),await Ru6($);let Z=new zi1({db:$,provider:{getMigrations:()=>Promise.resolve(Il0)}}),{error:X,results:Q}=await Z.migrateToLatest(),Y=0;if(Q?.forEach((G)=>{if(G.status==="Success")Y++;else if(G.status==="Error")console.error(`Failed to execute migration "${G.migrationName}"`)}),X)throw console.error("Failed to migrate"),console.error(X),X;return Y}async function Iu6($){let{keepOpen:Z=!1,database:X,skipBetterAuth:Q=!1}=$??{},Y="skipped";if(!Q&&!X)Y=await $h0();let G=X??H6(),J=async()=>{if(!Z&&!X)await Nw(G).catch((K)=>{console.warn("Warning: Error closing database:",K)})};try{let K=await Pi1(G.db);return await J(),{betterAuth:Y,kysely:K}}catch(K){throw await J(),K}}async function qu6(){let $=H6(),Z=new zi1({db:$.db,provider:{getMigrations:()=>Promise.resolve(Il0)}}),{error:X,results:Q}=await Z.migrateDown();if(Q?.forEach((Y)=>{if(Y.status==="Success")console.log(`\u2705 Migration "${Y.migrationName}" rolled back successfully`);else if(Y.status==="Error")console.error(`\u274C Failed to rollback migration "${Y.migrationName}"`)}),X)throw console.error("Failed to rollback migration"),console.error(X),X}var Ti1=O(()=>{Ei1();Zh0();n7()});async function u50($){let Z={...process.env},X=x00($,Z);console.log(uU1(X.settings.encryptionKey));let Q=X.settings.betterAuthSecret||(X.settings.localMode?yl1(X.settings.dataDir):""),{ensureServices:Y}=await Promise.resolve().then(() => (a$0(),r$0)),{outputs:G,services:J}=await Y({home:X.settings.dataDir,externalDatabaseUrl:X.externalDatabaseUrl,externalNatsUrl:X.externalNatsUrl});if(!X.skipMigrations){let{migrateBetterAuth:W}=await Promise.resolve().then(() => (Zh0(),hl1));await W(G.databaseUrl);let{createDatabase:H}=await Promise.resolve().then(() => (n7(),Zl1)),{migrateToLatest:N}=await Promise.resolve().then(() => (Ti1(),Ai1)),U=H(G.databaseUrl);await N({keepOpen:!0,database:U,skipBetterAuth:!0})}let K={...X.settings,betterAuthSecret:Q,databaseUrl:G.databaseUrl,natsUrls:G.natsUrls,...G.s3?{s3Endpoint:G.s3.endpoint,s3Bucket:G.s3.bucket,s3AccessKeyId:G.s3.accessKeyId,s3SecretAccessKey:G.s3.secretAccessKey,s3ForcePathStyle:G.s3.forcePathStyle}:{},...G.natsTunnel?{natsPublicUrl:G.natsTunnel.publicUrl,natsAccountJwt:G.natsTunnel.accountJwt,natsAccountSigningKey:G.natsTunnel.accountSigningKey,natsOperatorJwt:G.natsTunnel.operatorJwt,natsTunnelPublicEnabled:!0,natsCredsPath:G.natsTunnel.credsPath}:{}};return Kc1(K),{settings:K,services:J.map((W)=>({name:W.name==="PostgreSQL"?"Postgres":W.name,port:W.port})),managedServiceNames:J.filter((W)=>W.owner==="managed").map((W)=>W.name)}}var ql0=O(()=>{Tx();gl1();b8()});var qi1={};w0(qi1,{updateService:()=>dD,subscribeCliState:()=>Vl0,setTuiConsoleIntercepted:()=>c50,setServerUrl:()=>Rm,setMigrationsDone:()=>Tm,setDevMode:()=>Vu6,resetCliStateForTests:()=>Mu6,isTuiConsoleIntercepted:()=>l50,getCliState:()=>kl0,addLogEntry:()=>Ow});function Ri1(){return{services:[{name:"Postgres",status:"pending",port:0},{name:"NATS",status:"pending",port:0}],migrationsStatus:"pending",serverUrl:null,logs:[]}}function Mu6(){VQ=Ri1()}function ku6(){return[{name:"Postgres",status:"pending",port:0},{name:"NATS",status:"pending",port:0}]}function Am(){for(let $ of Ml0)$()}function kl0(){return VQ}function Vl0($){return Ml0.add($),()=>Ml0.delete($)}function dD($){VQ={...VQ,services:VQ.services.map((Z)=>Z.name===$.name?$:Z)},Am()}function Tm(){VQ={...VQ,migrationsStatus:"done"},Am()}function Rm($){VQ={...VQ,serverUrl:$},Am()}function Ow($){let Z=[...VQ.logs,$];VQ={...VQ,logs:Z.length>500?Z.slice(-500):Z},Am()}function Vu6(){VQ={...VQ,services:[...ku6(),{name:"API",status:"pending",port:0},{name:"Vite",status:"pending",port:0}]},Am()}function c50($){Ii1=$}function l50(){return Ii1}var VQ,Ml0,Ii1=!1;var mD=O(()=>{VQ=Ri1();Ml0=new Set});import{createServer as Mi1}from"net";function Su6($){return new Promise((Z)=>{let X=Mi1();X.once("error",()=>Z(!1)),X.listen($,"0.0.0.0",()=>{X.close(()=>Z(!0))})})}async function Im($){if(await Su6($))return $;let Z=await new Promise((X,Q)=>{let Y=Mi1();Y.once("error",Q),Y.listen(0,"0.0.0.0",()=>{let G=Y.address(),J=typeof G==="object"&&G?G.port:0;Y.close(()=>X(J))})});return console.warn(`Port ${$} is in use, using port ${Z} instead.`),Z}var Sl0=()=>{};function qm($){return $.replace(/\x1b\[[0-9;]*m/g,"")}var Cl0={};w0(Cl0,{startDevServer:()=>_u6});import{join as Cu6}from"path";function ki1($){let Z=$.getReader(),X=new TextDecoder,Q="";function Y(){let G=Q.split(`
|
|
1313
|
-
`);Q=G.pop()??"";for(let J of G){let K=qm(J).replace(/^\[\d+\]\s*/,"").trim();if(!K)continue;Ow({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:K})}}(async()=>{for(;;){let{done:G,value:J}=await Z.read();if(G)break;Q+=X.decode(J,{stream:!0}),Y()}if(Q.trim()){let G=qm(Q).replace(/^\[\d+\]\s*/,"").trim();if(G)Ow({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:G})}})()}async function _u6($){let{baseUrl:Z,noTui:X}=$,Q=process.env.HOST==="0.0.0.0"&&Boolean(process.env.PORT),Y=Q?process.env.PORT:$.vitePort,G=Z||`http://localhost:${Y}`,J=Q?await Im(Number(Y)+1):await Im(Number($.port)),{settings:K,services:W,managedServiceNames:H}=await u50({port:String(J),home:$.home,baseUrl:$.baseUrl,localMode:$.localMode,skipMigrations:$.skipMigrations,noTui:$.noTui,vitePort:$.vitePort});for(let L of W)dD({name:L.name,status:"ready",port:L.port});Tm();let N=Cu6(import.meta.dir,"..","..","..","..",".."),U=X===!0,F=Bun.spawn(["bun","run","dev:servers"],{cwd:N,env:{...process.env,PORT:String(K.port),VITE_PORT:String(Y),DATABASE_URL:K.databaseUrl,NATS_URL:K.natsUrls.join(","),NODE_ENV:K.nodeEnv,BASE_URL:G,DECOCMS_LOCAL_MODE:String(K.localMode),DECOCMS_HOME:K.dataDir,DATA_DIR:K.dataDir,DECO_CLI:"1",...K.betterAuthSecret?{BETTER_AUTH_SECRET:K.betterAuthSecret}:{},...K.s3Endpoint?{S3_ENDPOINT:K.s3Endpoint,S3_BUCKET:K.s3Bucket??"",S3_ACCESS_KEY_ID:K.s3AccessKeyId??"",S3_SECRET_ACCESS_KEY:K.s3SecretAccessKey??"",S3_FORCE_PATH_STYLE:String(K.s3ForcePathStyle)}:{},...K.natsPublicUrl&&K.natsAccountJwt&&K.natsAccountSigningKey?{NATS_PUBLIC_URL:K.natsPublicUrl,NATS_ACCOUNT_JWT:K.natsAccountJwt,NATS_ACCOUNT_SIGNING_KEY:K.natsAccountSigningKey,NATS_OPERATOR_JWT:K.natsOperatorJwt??"",NATS_TUNNEL_PUBLIC_ENABLED:"true",...K.natsCredsPath?{NATS_CREDS:K.natsCredsPath}:{}}:{}},stdio:["inherit",U?"inherit":"pipe",U?"inherit":"pipe"]});if(!U)ki1(F.stdout),ki1(F.stderr);Rm(G),dD({name:"Vite",status:"ready",port:Number(Y)}),dD({name:"API",status:"ready",port:Number(K.port)});let B=async(L)=>{if(F.kill(L),await F.exited,H.length>0){let{stopServices:D}=await Promise.resolve().then(() => (a$0(),r$0));await D(K.dataDir)}};return process.on("SIGINT",()=>B("SIGINT")),process.on("SIGTERM",()=>B("SIGTERM")),{port:Number(Y),process:F}}var _l0=O(()=>{ql0();mD();Sl0()});var d50;var vl0=O(()=>{d50={name:"decocms",version:"4.192.7",description:"Deco CMS \u2014 Self-hostable MCP Gateway for managing AI connections and tools",author:"Deco team",repository:{type:"git",url:"git+https://github.com/decocms/studio.git",directory:"apps/api"},bugs:{url:"https://github.com/decocms/studio/issues"},type:"module",bin:{deco:"./dist/server/cli.js"},files:["dist/**/*"],scripts:{dev:"bun run migrate && bun run dev:server","dev:server":"bun run --cwd=../../packages/sandbox build && NODE_ENV=development bun --env-file=.env --hot run src/index.ts",build:"bun run build:server","build:server":"bun run scripts/bundle-server-script.ts --dist ./dist/server","generate:tool-contracts":"bun run scripts/generate-tool-contracts.ts","db:migrate":"bun run ./dist/server/migrate.js",check:"tsc --noEmit",start:"bun run ./dist/server/server.js",migrate:"bun run src/database/migrate.ts",test:"bun test src","better-auth:migrate":"bunx --bun @better-auth/cli migrate -y --config src/auth/index.ts",prepublishOnly:"bun run --cwd=../.. build:studio"},optionalDependencies:{"@duckdb/node-api":"^1.5.0-r.1"},dependencies:{"@ai-sdk/anthropic":"^3.0.85","@ai-sdk/google":"^3.0.83","@ai-sdk/openai":"^3.0.73","@anthropic-ai/sdk":"^0.105.0","@aws-sdk/client-s3":"^3.1013.0","@aws-sdk/client-sts":"^3.1013.0","@aws-sdk/lib-storage":"^3.1013.0","@aws-sdk/s3-request-presigner":"^3.1013.0","@clickhouse/client":"^1.8.1","@dbos-inc/dbos-sdk":"^4.21.6","@inkjs/ui":"^2.0.0","@nats-io/jetstream":"3.4.0","@nats-io/kv":"3.4.0","@nats-io/nats-core":"3.4.0","@nats-io/transport-node":"3.4.0","@openrouter/ai-sdk-provider":"^2.9.1","@opentelemetry/core":"^2.6.0","embedded-postgres":"^18.3.0-beta.16",ink:"^6.8.0",kysely:"^0.28.12","posthog-node":"^5.0.0",react:"^19.2.6","react-dom":"^19.2.6"},devDependencies:{"@ai-sdk/provider":"^3.0.10","@better-auth/sso":"1.4.1","@decocms/better-auth":"1.5.17","@decocms/bindings":"workspace:*","@decocms/mcp-utils":"workspace:*","@decocms/runtime":"workspace:*","@decocms/sandbox":"workspace:*","@decocms/shared":"workspace:*","@jitl/quickjs-wasmfile-release-sync":"0.31.0","@modelcontextprotocol/sdk":"1.29.0","@nats-io/jwt":"0.0.10-5","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.211.0","@opentelemetry/exporter-logs-otlp-proto":"^0.211.0","@opentelemetry/exporter-prometheus":"^0.208.0","@opentelemetry/exporter-trace-otlp-proto":"^0.207.0","@opentelemetry/instrumentation-runtime-node":"^0.24.0","@opentelemetry/resources":"^2.6.0","@opentelemetry/sdk-logs":"^0.211.0","@opentelemetry/sdk-metrics":"^2.2.0","@opentelemetry/sdk-node":"^0.207.0","@opentelemetry/sdk-trace-base":"^2.5.0","@types/bun":"^1.3.1","@types/google.maps":"^3.65.2","@types/pg":"^8.15.6","@types/react-syntax-highlighter":"^15.5.13","@vercel/nft":"^1.1.1",ai:"^6.0.208","better-auth":"1.4.22",croner:"^9.1.0",degit:"^2.8.4",hono:"^4.10.7",jose:"^6.0.11",nanoid:"^5.1.6",pg:"^8.16.3",typescript:"^7.0.2",typescript5:"npm:typescript@^5.9.3",zod:"4.3.6"},homepage:"https://github.com/decocms/studio",keywords:["mcp","model-context-protocol","ai","gateway","self-hosted","tools"],license:"MIT",publishConfig:{access:"public"}}});import{Box as xu6,Text as Vi1}from"ink";import{jsx as fu6,jsxs as Si1}from"react/jsx-runtime";function Ci1({version:$}){return Si1(xu6,{flexDirection:"column",marginTop:1,children:[E50.map((Z,X)=>fu6(Vi1,{color:z50[X],children:Z},X)),Si1(Vi1,{dimColor:!0,children:[" v",$]})]})}var _i1=O(()=>{Um()});import{Box as iD,Text as Lw}from"ink";import{Spinner as bu6}from"@inkjs/ui";import{jsx as yY,jsxs as sf}from"react/jsx-runtime";function vi1({status:$}){if($==="pending")return yY(bu6,{label:""});return yY(Lw,{color:"green",children:"\u2713"})}function yu6($){return`${$.name}: ${$.port||"...."}`}function xi1({services:$,migrationsStatus:Z,home:X,serverUrl:Q}){return sf(iD,{flexDirection:"column",paddingBottom:1,children:[yY(Ci1,{version:d50.version}),yY(iD,{marginBottom:1,children:yY(Lw,{dimColor:!0,children:"\u2500".repeat(80)})}),yY(iD,{children:sf(Lw,{dimColor:!0,children:["Home: ",X]})}),sf(iD,{gap:2,children:[$.map((Y)=>sf(iD,{gap:1,children:[yY(Lw,{children:yu6(Y)}),yY(vi1,{status:Y.status})]},Y.name)),sf(iD,{gap:1,children:[yY(Lw,{children:"Migrations"}),yY(vi1,{status:Z})]})]}),yY(iD,{children:Q?sf(Lw,{children:["Open in browser: ",yY(Lw,{color:"cyan",children:Q})]}):yY(Lw,{dimColor:!0,children:"Starting..."})})]})}var fi1=O(()=>{vl0();_i1()});import{Box as gu6,Text as Mm}from"ink";import{jsx as xl0,jsxs as fl0}from"react/jsx-runtime";function hu6($){if($>=500)return"red";if($>=400)return"yellow";if($>=300)return"cyan";return"green"}function bi1({logs:$}){return xl0(gu6,{flexDirection:"column",children:$.map((Z,X)=>{if(Z.rawLine)return xl0(Mm,{dimColor:!0,children:Z.rawLine},X);let Q=Z.duration<1000?`${Z.duration}ms`:`${(Z.duration/1000).toFixed(1)}s`;return fl0(Mm,{children:[fl0(Mm,{dimColor:!0,children:[Z.method.padEnd(6)," ",Z.path.padEnd(30)," "]}),xl0(Mm,{color:hu6(Z.status),children:Z.status}),fl0(Mm,{dimColor:!0,children:[" ",Q.padStart(8)]})]},X)})})}var yi1=()=>{};var bl0={};w0(bl0,{App:()=>lu6});import{Box as uu6}from"ink";import{useSyncExternalStore as cu6}from"react";import{jsx as gi1,jsxs as du6}from"react/jsx-runtime";function lu6({home:$}){let Z=cu6(Vl0,kl0);return du6(uu6,{flexDirection:"column",children:[gi1(xi1,{services:Z.services,migrationsStatus:Z.migrationsStatus,home:$,serverUrl:Z.serverUrl}),gi1(bi1,{logs:Z.logs})]})}var yl0=O(()=>{fi1();yi1();mD()});var KJ="thread-gate",kN="decopilot-hosted-harness",mG="automations",Dw="background-tools";var hi1="7";function ui1($){return{name:"decocms",systemDatabaseUrl:$.systemDatabaseUrl,systemDatabaseSchemaName:"dbos",systemDatabasePoolSize:$.poolSize,runAdminServer:!1,executorID:$.executorID,applicationVersion:hi1,...$.listenQueues!==void 0?{listenQueues:$.listenQueues}:{}}}var ci1=()=>{};function mu6(){let $=(process.env.BUN_OPTIONS??"").split(/\s+/).filter(Boolean);return[...process.argv.slice(1),...$]}function gl0($,Z){for(let X=0;X<$.length;X++){let Q=$[X];if(Q===void 0)continue;if(Q===Z)return $[X+1];if(Q.startsWith(`${Z}=`))return Q.slice(Z.length+1)}return}function li1(){let $=mu6();if($.includes("--cpu-prof")){console.log(JSON.stringify({msg:"cpu-profiling-active",dir:gl0($,"--cpu-prof-dir")??process.cwd(),name:gl0($,"--cpu-prof-name"),markdown:$.includes("--cpu-prof-md"),intervalUs:Number(gl0($,"--cpu-prof-interval")??1000),note:"profile is written on process exit"}));return}if(process.env.CPU_PROFILE)console.warn(JSON.stringify({msg:"cpu-profiling-requested-but-inactive",hint:'CPU profiling is a Bun launch flag. Set BUN_OPTIONS="--cpu-prof --cpu-prof-md --cpu-prof-dir=/tmp" before starting the process.'}))}function di1(){if(process.env.HEAP_WATCH!=="1")return()=>{};let $=Number(process.env.HEAP_WATCH_INTERVAL_MS??60000),Z=async()=>{let X=hD();if(!X)return;let Q={};try{let{heapStats:Y}=await import("bun:jsc"),G=Y(),J=Object.entries(G.objectTypeCounts).sort((K,W)=>W[1]-K[1]).slice(0,20);Q={objectCount:G.objectCount,heapSize:G.heapSize,top:Object.fromEntries(J)}}catch{}console.log(JSON.stringify({msg:"heap-watch",ts:new Date().toISOString(),uptimeS:Math.round(process.uptime()),rss:X.rss,heapUsed:X.heapUsed,heapTotal:X.heapTotal,external:X.external,arrayBuffers:X.arrayBuffers,...Q}))};return Z().catch(()=>{}),m50=setInterval(()=>void Z().catch(()=>{}),$),m50.unref?.(),process.on("SIGUSR2",()=>{try{let X=Bun.generateHeapSnapshot("v8"),Q=typeof X==="string"?X:JSON.stringify(X),Y=`/tmp/heap-${process.pid}-${Date.now()}.heapsnapshot`;Bun.write(Y,Q),console.log(JSON.stringify({msg:"heap-snapshot-written",path:Y}))}catch(X){console.error("[heap-watch] snapshot failed:",X)}}),()=>{if(m50)clearInterval(m50)}}var m50;var mi1=()=>{};import*as iu6 from"bun:jsc";function ii1(){if(process.env.STALL_WATCHDOG!=="1")return()=>{};let $=Number(process.env.STALL_WATCHDOG_MS??100),Z=Number(process.env.STALL_WATCHDOG_TICK_MS??50);try{nu6()}catch(G){return console.error("[stall-watchdog] failed to start sampling profiler:",G),()=>{}}let X,Q=performance.now()+Z,Y=()=>{let G=performance.now(),J=G-Q;Q=G+Z;let K=[];try{K=pu6()?.traces??[]}catch{}if(J>$&&K.length>0){let W=new Map;for(let N of K){let U=N.frames.find((B)=>B.sourceURL&&!/Unknown Executable/.test(B.category??""))??N.frames[0];if(!U)continue;let F=(U.sourceURL??"?").replace(/^.*\/node_modules\//,"node_modules/"),w=`${U.name??"?"} @ ${F}:${U.line??"?"}`;W.set(w,(W.get(w)??0)+1)}let H=[...W.entries()].sort((N,U)=>U[1]-N[1]).slice(0,8).map(([N,U])=>({frame:N,count:U}));console.warn(JSON.stringify({msg:"stall-stack",ts:new Date().toISOString(),lagMs:Math.round(J),samplesInWindow:K.length,top:H}))}X=setTimeout(Y,Z),X.unref?.()};return X=setTimeout(Y,Z),X.unref?.(),()=>{if(X)clearTimeout(X)}}var nu6,pu6;var ni1=O(()=>{({startSamplingProfiler:nu6,samplingProfilerStackTraces:pu6}=iu6)});function pi1(){li1();let $=[di1(),pc1(),ii1()];return()=>{for(let Z of $)Z()}}var ti1=O(()=>{mg0();mi1();ni1()});var nD=_((oi1)=>{Object.defineProperty(oi1,"__esModule",{value:!0});oi1.RepublishHeaders=oi1.DirectMsgHeaders=oi1.JsHeaders=oi1.AdvisoryKind=void 0;oi1.isOrderedPushConsumerOptions=tu6;oi1.isPullConsumer=ou6;oi1.isPushConsumer=ru6;oi1.isBoundPushConsumerOptions=au6;function tu6($){if($&&typeof $==="object")return"name_prefix"in $||"deliver_subject_prefix"in $||"filter_subjects"in $||"filter_subject"in $||"deliver_policy"in $||"opt_start_seq"in $||"opt_start_time"in $||"replay_policy"in $||"inactive_threshold"in $||"headers_only"in $||"deliver_prefix"in $;return!1}function ou6($){return $.isPullConsumer()}function ru6($){return $.isPushConsumer()}function au6($){if($&&typeof $==="object")return"deliver_subject"in $||"deliver_group"in $||"idle_heartbeat"in $;return!1}oi1.AdvisoryKind={API:"api_audit",StreamAction:"stream_action",ConsumerAction:"consumer_action",SnapshotCreate:"snapshot_create",SnapshotComplete:"snapshot_complete",RestoreCreate:"restore_create",RestoreComplete:"restore_complete",MaxDeliver:"max_deliver",Terminated:"terminated",Ack:"consumer_ack",StreamLeaderElected:"stream_leader_elected",StreamQuorumLost:"stream_quorum_lost",ConsumerLeaderElected:"consumer_leader_elected",ConsumerQuorumLost:"consumer_quorum_lost"};oi1.JsHeaders={StreamSourceHdr:"Nats-Stream-Source",LastConsumerSeqHdr:"Nats-Last-Consumer",LastStreamSeqHdr:"Nats-Last-Stream",ConsumerStalledHdr:"Nats-Consumer-Stalled",MessageSizeHdr:"Nats-Msg-Size",RollupHdr:"Nats-Rollup",RollupValueSubject:"sub",RollupValueAll:"all",PendingMessagesHdr:"Nats-Pending-Messages",PendingBytesHdr:"Nats-Pending-Bytes",RequiredApiLevel:"Nats-Required-Api-Level"};oi1.DirectMsgHeaders={Stream:"Nats-Stream",Sequence:"Nats-Sequence",TimeStamp:"Nats-Time-Stamp",Subject:"Nats-Subject",LastSequence:"Nats-Last-Sequence",NumPending:"Nats-Num-Pending"};oi1.RepublishHeaders={Stream:"Nats-Stream",Subject:"Nats-Subject",Sequence:"Nats-Sequence",LastSequence:"Nats-Last-Sequence",Size:"Nats-Msg-Size"}});var gY=_((ai1)=>{Object.defineProperty(ai1,"__esModule",{value:!0});ai1.TD=ai1.TE=ai1.Empty=void 0;ai1.encode=Jc6;ai1.decode=Kc6;ai1.Empty=new Uint8Array(0);ai1.TE=new TextEncoder;ai1.TD=new TextDecoder;function Gc6(...$){let Z=0;for(let Y=0;Y<$.length;Y++)Z+=$[Y].length;let X=new Uint8Array(Z),Q=0;for(let Y=0;Y<$.length;Y++)X.set($[Y],Q),Q+=$[Y].length;return X}function Jc6(...$){let Z=[];for(let X=0;X<$.length;X++)Z.push(ai1.TE.encode($[X]));if(Z.length===0)return ai1.Empty;if(Z.length===1)return Z[0];return Gc6(...Z)}function Kc6($){if(!$||$.length===0)return"";return ai1.TD.decode($)}});var hY=_(($n1)=>{Object.defineProperty($n1,"__esModule",{value:!0});$n1.errors=$n1.PermissionViolationError=$n1.NoRespondersError=$n1.TimeoutError=$n1.RequestError=$n1.ProtocolError=$n1.ConnectionError=$n1.DrainingConnectionError=$n1.ClosedConnectionError=$n1.AuthorizationError=$n1.UserAuthenticationExpiredError=$n1.InvalidOperationError=$n1.InvalidArgumentError=$n1.InvalidSubjectError=void 0;class ul0 extends Error{constructor($,Z){super(`illegal subject: '${$}'`,Z);this.name="InvalidSubjectError"}}$n1.InvalidSubjectError=ul0;class i50 extends Error{constructor($,Z){super($,Z);this.name="InvalidArgumentError"}static format($,Z,X){if(Array.isArray(Z)&&Z.length>1)Z=Z[0];if(Array.isArray($))$=$.map((Q)=>`'${Q}'`),$=$.join(",");else $=`'${$}'`;return new i50(`${$} ${Z}`,X)}}$n1.InvalidArgumentError=i50;class cl0 extends Error{constructor($,Z){super($,Z);this.name="InvalidOperationError"}}$n1.InvalidOperationError=cl0;class n50 extends Error{constructor($,Z){super($,Z);this.name="UserAuthenticationExpiredError"}static parse($){if($.toLowerCase().indexOf("user authentication expired")!==-1)return new n50($);return null}}$n1.UserAuthenticationExpiredError=n50;class p50 extends Error{constructor($,Z){super($,Z);this.name="AuthorizationError"}static parse($){let Z=["authorization violation","account authentication expired","authentication timeout"],X=$.toLowerCase();for(let Q=0;Q<Z.length;Q++)if(X.indexOf(Z[Q])!==-1)return new p50($);return null}}$n1.AuthorizationError=p50;class ll0 extends Error{constructor(){super("closed connection");this.name="ClosedConnectionError"}}$n1.ClosedConnectionError=ll0;class dl0 extends Error{constructor(){super("connection draining");this.name="DrainingConnectionError"}}$n1.DrainingConnectionError=dl0;class ml0 extends Error{constructor($,Z){super($,Z);this.name="ConnectionError"}}$n1.ConnectionError=ml0;class il0 extends Error{constructor($,Z){super($,Z);this.name="ProtocolError"}}$n1.ProtocolError=il0;class nl0 extends Error{constructor($="",Z){super($,Z);this.name="RequestError"}isNoResponders(){return this.cause instanceof t50}}$n1.RequestError=nl0;class pl0 extends Error{constructor($){super("timeout",$);this.name="TimeoutError"}}$n1.TimeoutError=pl0;class t50 extends Error{subject;constructor($,Z){super(`no responders: '${$}'`,Z);this.subject=$,this.name="NoResponders"}}$n1.NoRespondersError=t50;class o50 extends Error{operation;subject;queue;constructor($,Z,X,Q,Y){super($,Y);this.name="PermissionViolationError",this.operation=Z,this.subject=X,this.queue=Q}static parse($){if(($?$.toLowerCase():"").indexOf("permissions violation")===-1)return null;let X="publish",Q="",Y=void 0,G=$.match(/(Publish|Subscription) to "(\S+)"/);if(G){if(X=G[1].toLowerCase(),Q=G[2],X==="subscription"){let J=$.match(/using queue "(\S+)"/);if(J)Y=J[1]}}return new o50($,X,Q,Y)}}$n1.PermissionViolationError=o50;$n1.errors={AuthorizationError:p50,ClosedConnectionError:ll0,ConnectionError:ml0,DrainingConnectionError:dl0,InvalidArgumentError:i50,InvalidOperationError:cl0,InvalidSubjectError:ul0,NoRespondersError:t50,PermissionViolationError:o50,ProtocolError:il0,RequestError:nl0,TimeoutError:pl0,UserAuthenticationExpiredError:n50}});var WJ=_((Gn1)=>{Object.defineProperty(Gn1,"__esModule",{value:!0});Gn1.SimpleMutex=Gn1.Perf=void 0;Gn1.extend=Rc6;Gn1.render=Ic6;Gn1.timeout=qc6;Gn1.delay=Mc6;Gn1.deadline=kc6;Gn1.deferred=ol0;Gn1.debugDeferred=Vc6;Gn1.shuffle=Sc6;Gn1.collect=Cc6;Gn1.jitter=Yn1;Gn1.backoff=_c6;Gn1.nanos=vc6;Gn1.millis=xc6;Gn1.randomToken=yc6;var Tc6=gY(),tl0=hY();function Rc6($,...Z){for(let X=0;X<Z.length;X++){let Q=Z[X];Object.keys(Q).forEach(function(Y){$[Y]=Q[Y]})}return $}function Ic6($){return Tc6.TD.decode($).replace(/\n/g,"\u240A").replace(/\r/g,"\u240D")}function qc6($,Z=!0){let X=Z?new tl0.TimeoutError:null,Q,Y,G=new Promise((J,K)=>{Q={cancel:()=>{if(Y)clearTimeout(Y)}},Y=setTimeout(()=>{if(X===null)K(new tl0.TimeoutError);else K(X)},$)});return Object.assign(G,Q)}function Mc6($=0){let Z,X=new Promise((Q)=>{let Y=setTimeout(()=>{Q()},$);Z={cancel:()=>{if(Y)clearTimeout(Y),Q()}}});return Object.assign(X,Z)}async function kc6($,Z=1000){let X=ol0(),Q=setTimeout(()=>{X.reject(new tl0.TimeoutError)},Z);try{return await Promise.race([$,X])}finally{clearTimeout(Q)}}function ol0(){let $={},Z=new Promise((X,Q)=>{$={resolve:X,reject:Q}});return Object.assign(Z,$)}function Vc6(){let $={},Z=new Promise((X,Q)=>{$={resolve:(Y)=>{console.trace("resolve",Y),X(Y)},reject:(Y)=>{console.trace("reject"),Q(Y)}}});return Object.assign(Z,$)}function Sc6($){for(let Z=$.length-1;Z>0;Z--){let X=Math.floor(Math.random()*(Z+1));[$[Z],$[X]]=[$[X],$[Z]]}return $}async function Cc6($){let Z=[];for await(let X of $)Z.push(X);return Z}class Xn1{timers;measures;constructor(){this.timers=new Map,this.measures=new Map}mark($){this.timers.set($,performance.now())}measure($,Z,X){let Q=this.timers.get(Z);if(Q===void 0)throw Error(`${Z} is not defined`);let Y=this.timers.get(X);if(Y===void 0)throw Error(`${X} is not defined`);this.measures.set($,Y-Q)}getEntries(){let $=[];return this.measures.forEach((Z,X)=>{$.push({name:X,duration:Z})}),$}}Gn1.Perf=Xn1;class Qn1{max;current;waiting;constructor($=1){this.max=$,this.current=0,this.waiting=[]}lock(){if(this.current++,this.current<=this.max)return Promise.resolve();let $=ol0();return this.waiting.push($),$}unlock(){this.current--,this.waiting.pop()?.resolve()}}Gn1.SimpleMutex=Qn1;function Yn1($){if($===0)return 0;return Math.floor($/2+Math.random()*$)}function _c6($=[0,250,250,500,500,3000,5000]){if(!Array.isArray($))$=[0,250,250,500,500,3000,5000];let Z=$.length-1;return{backoff(X){return Yn1(X>Z?$[Z]:$[X])}}}function vc6($){return $*1e6}function xc6($){return Math.floor($/1e6)}var fc6="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",VN=new Uint8Array(62);for(let $=0;$<62;$++)VN[$]=fc6.charCodeAt($);var bc6=218340105584896;function yc6(){let $=Math.floor(Math.random()*bc6),Z=$%62,X=VN[Z];$=($-Z)/62,Z=$%62;let Q=VN[Z];$=($-Z)/62,Z=$%62;let Y=VN[Z];$=($-Z)/62,Z=$%62;let G=VN[Z];$=($-Z)/62,Z=$%62;let J=VN[Z];$=($-Z)/62,Z=$%62;let K=VN[Z];$=($-Z)/62,Z=$%62;let W=VN[Z];$=($-Z)/62;let H=VN[$];return String.fromCharCode(X,Q,Y,G,J,K,W,H)}});var wn1=_((Un1)=>{Object.defineProperty(Un1,"__esModule",{value:!0});Un1.nuid=Un1.NuidImpl=void 0;var ec6="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Ew=62,a50=12,Hn1=10,Kn1=33,$l6=333,Wn1=a50+Hn1,al0=new Uint8Array(Ew);for(let $=0;$<Ew;$++)al0[$]=ec6.charCodeAt($);var r50=4294967296,Nn1=BigInt(Ew)**BigInt(Hn1),km=Number(Nn1/(1n<<32n)),rl0=Number(Nn1%(1n<<32n));function Zl6($){for(let Z=0;Z<$.length;Z++)$[Z]=Math.floor(Math.random()*256)}function Xl6($){if(globalThis?.crypto?.getRandomValues)globalThis.crypto.getRandomValues($);else Zl6($)}class sl0{buf;cbuf;seqHi;seqLo;inc;inited;constructor(){this.buf=new Uint8Array(Wn1),this.cbuf=new Uint8Array(a50),this.inited=!1}init(){this.inited=!0,this.setPre(),this.initSeqAndInc(),this.fillSeq()}initSeqAndInc(){let $=0;do this.seqHi=Math.floor(Math.random()*(km+1)),this.seqLo=Math.floor(Math.random()*r50);while($++<8&&this.seqHi===km&&this.seqLo>=rl0);if(this.seqHi===km&&this.seqLo>=rl0)this.seqLo=0;this.inc=Math.random()*($l6-Kn1)+Kn1|0}setPre(){Xl6(this.cbuf);for(let $=0;$<a50;$++)this.buf[$]=al0[this.cbuf[$]%Ew]}fillSeq(){let $=this.seqHi,Z=this.seqLo;for(let X=Wn1-1;X>=a50;X--){let Q=Math.floor($/Ew),G=($-Q*Ew)*r50+Z,J=Math.floor(G/Ew),K=G-J*Ew;this.buf[X]=al0[K],$=Q,Z=J}}next(){if(!this.inited)this.init();if(this.seqLo+=this.inc,this.seqLo>=r50)this.seqLo-=r50,this.seqHi+=1;if(this.seqHi>km||this.seqHi===km&&this.seqLo>=rl0)this.setPre(),this.initSeqAndInc();this.fillSeq();let $=this.buf;return String.fromCharCode($[0],$[1],$[2],$[3],$[4],$[5],$[6],$[7],$[8],$[9],$[10],$[11],$[12],$[13],$[14],$[15],$[16],$[17],$[18],$[19],$[20],$[21])}reset(){this.init()}}Un1.NuidImpl=sl0;Un1.nuid=new sl0});var Dn1=_((On1)=>{Object.defineProperty(On1,"__esModule",{value:!0});On1.nuid=On1.Nuid=void 0;var Bn1=wn1();On1.Nuid=Bn1.NuidImpl;On1.nuid=Bn1.nuid});var e50=_((s50)=>{Object.defineProperty(s50,"__esModule",{value:!0});s50.nuid=s50.Nuid=void 0;var En1=Dn1();Object.defineProperty(s50,"Nuid",{enumerable:!0,get:function(){return En1.Nuid}});Object.defineProperty(s50,"nuid",{enumerable:!0,get:function(){return En1.nuid}})});var zw=_((zn1)=>{Object.defineProperty(zn1,"__esModule",{value:!0});zn1.DEFAULT_HOST=zn1.DEFAULT_PORT=zn1.Match=void 0;zn1.syncIterator=Wl6;zn1.createInbox=Hl6;var Jl6=e50(),Kl6=hY();zn1.Match={Exact:"exact",CanonicalMIME:"canonical",IgnoreCase:"insensitive"};function Wl6($){let Z=$[Symbol.asyncIterator]();return{async next(){let X=await Z.next();if(X.done)return Promise.resolve(null);return Promise.resolve(X.value)}}}function Hl6($=""){if($=$||"_INBOX",typeof $!=="string")throw TypeError("prefix must be a string");return $.split(".").forEach((Z)=>{if(Z==="*"||Z===">")throw Kl6.InvalidArgumentError.format("prefix",`cannot have wildcards ('${$}')`)}),`${$}.${Jl6.nuid.next()}`}zn1.DEFAULT_PORT=4222;zn1.DEFAULT_HOST="127.0.0.1"});var Vm=_((Tn1)=>{Object.defineProperty(Tn1,"__esModule",{value:!0});Tn1.DataBuffer=void 0;var Pn1=gY();class An1{buffers;byteLength;constructor(){this.buffers=[],this.byteLength=0}static concat(...$){let Z=0;for(let Y=0;Y<$.length;Y++)Z+=$[Y].length;let X=new Uint8Array(Z),Q=0;for(let Y=0;Y<$.length;Y++)X.set($[Y],Q),Q+=$[Y].length;return X}static fromAscii($){if(!$)$="";return Pn1.TE.encode($)}static toAscii($){return Pn1.TD.decode($)}reset(){this.buffers.length=0,this.byteLength=0}pack(){if(this.buffers.length>1){let $=new Uint8Array(this.byteLength),Z=0;for(let X=0;X<this.buffers.length;X++)$.set(this.buffers[X],Z),Z+=this.buffers[X].length;this.buffers.length=0,this.buffers.push($)}}shift(){if(this.buffers.length){let $=this.buffers.shift();if($)return this.byteLength-=$.length,$}return new Uint8Array(0)}drain($){if(this.buffers.length){this.pack();let Z=this.buffers.pop();if(Z){let X=this.byteLength;if($===void 0||$>X)$=X;let Q=Z.subarray(0,$);if(X>$)this.buffers.push(Z.subarray($));return this.byteLength=X-$,Q}}return new Uint8Array(0)}fill($,...Z){if($)this.buffers.push($),this.byteLength+=$.length;for(let X=0;X<Z.length;X++)if(Z[X]&&Z[X].length)this.buffers.push(Z[X]),this.byteLength+=Z[X].length}peek(){if(this.buffers.length)return this.pack(),this.buffers[0];return new Uint8Array(0)}size(){return this.byteLength}length(){return this.buffers.length}}Tn1.DataBuffer=An1});var pD=_((qn1)=>{Object.defineProperty(qn1,"__esModule",{value:!0});qn1.LF=qn1.CR=qn1.CRLF=qn1.CR_LF_LEN=qn1.CR_LF=void 0;qn1.setTransportFactory=Dl6;qn1.defaultPort=El6;qn1.getUrlParseFn=zl6;qn1.newTransport=jl6;qn1.getResolveFn=Pl6;qn1.protoLen=In1;qn1.extractProtocolMessage=Al6;var Bl6=gY(),Ol6=zw(),Ll6=Vm(),uY;function Dl6($){uY=$}function El6(){return uY!==void 0&&uY.defaultPort!==void 0?uY.defaultPort:Ol6.DEFAULT_PORT}function zl6(){return uY!==void 0&&uY.urlParseFn?uY.urlParseFn:void 0}function jl6(){if(!uY||typeof uY.factory!=="function")throw Error("transport fn is not set");return uY.factory()}function Pl6(){return uY!==void 0&&uY.dnsResolveFn?uY.dnsResolveFn:void 0}qn1.CR_LF=`\r
|
|
1313
|
+
`);Q=G.pop()??"";for(let J of G){let K=qm(J).replace(/^\[\d+\]\s*/,"").trim();if(!K)continue;Ow({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:K})}}(async()=>{for(;;){let{done:G,value:J}=await Z.read();if(G)break;Q+=X.decode(J,{stream:!0}),Y()}if(Q.trim()){let G=qm(Q).replace(/^\[\d+\]\s*/,"").trim();if(G)Ow({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:G})}})()}async function _u6($){let{baseUrl:Z,noTui:X}=$,Q=process.env.HOST==="0.0.0.0"&&Boolean(process.env.PORT),Y=Q?process.env.PORT:$.vitePort,G=Z||`http://localhost:${Y}`,J=Q?await Im(Number(Y)+1):await Im(Number($.port)),{settings:K,services:W,managedServiceNames:H}=await u50({port:String(J),home:$.home,baseUrl:$.baseUrl,localMode:$.localMode,skipMigrations:$.skipMigrations,noTui:$.noTui,vitePort:$.vitePort});for(let L of W)dD({name:L.name,status:"ready",port:L.port});Tm();let N=Cu6(import.meta.dir,"..","..","..","..",".."),U=X===!0,F=Bun.spawn(["bun","run","dev:servers"],{cwd:N,env:{...process.env,PORT:String(K.port),VITE_PORT:String(Y),DATABASE_URL:K.databaseUrl,NATS_URL:K.natsUrls.join(","),NODE_ENV:K.nodeEnv,BASE_URL:G,DECOCMS_LOCAL_MODE:String(K.localMode),DECOCMS_HOME:K.dataDir,DATA_DIR:K.dataDir,DECO_CLI:"1",...K.betterAuthSecret?{BETTER_AUTH_SECRET:K.betterAuthSecret}:{},...K.s3Endpoint?{S3_ENDPOINT:K.s3Endpoint,S3_BUCKET:K.s3Bucket??"",S3_ACCESS_KEY_ID:K.s3AccessKeyId??"",S3_SECRET_ACCESS_KEY:K.s3SecretAccessKey??"",S3_FORCE_PATH_STYLE:String(K.s3ForcePathStyle)}:{},...K.natsPublicUrl&&K.natsAccountJwt&&K.natsAccountSigningKey?{NATS_PUBLIC_URL:K.natsPublicUrl,NATS_ACCOUNT_JWT:K.natsAccountJwt,NATS_ACCOUNT_SIGNING_KEY:K.natsAccountSigningKey,NATS_OPERATOR_JWT:K.natsOperatorJwt??"",NATS_TUNNEL_PUBLIC_ENABLED:"true",...K.natsCredsPath?{NATS_CREDS:K.natsCredsPath}:{}}:{}},stdio:["inherit",U?"inherit":"pipe",U?"inherit":"pipe"]});if(!U)ki1(F.stdout),ki1(F.stderr);Rm(G),dD({name:"Vite",status:"ready",port:Number(Y)}),dD({name:"API",status:"ready",port:Number(K.port)});let B=async(L)=>{if(F.kill(L),await F.exited,H.length>0){let{stopServices:D}=await Promise.resolve().then(() => (a$0(),r$0));await D(K.dataDir)}};return process.on("SIGINT",()=>B("SIGINT")),process.on("SIGTERM",()=>B("SIGTERM")),{port:Number(Y),process:F}}var _l0=O(()=>{ql0();mD();Sl0()});var d50;var vl0=O(()=>{d50={name:"decocms",version:"4.192.8",description:"Deco CMS \u2014 Self-hostable MCP Gateway for managing AI connections and tools",author:"Deco team",repository:{type:"git",url:"git+https://github.com/decocms/studio.git",directory:"apps/api"},bugs:{url:"https://github.com/decocms/studio/issues"},type:"module",bin:{deco:"./dist/server/cli.js"},files:["dist/**/*"],scripts:{dev:"bun run migrate && bun run dev:server","dev:server":"bun run --cwd=../../packages/sandbox build && NODE_ENV=development bun --env-file=.env --hot run src/index.ts",build:"bun run build:server","build:server":"bun run scripts/bundle-server-script.ts --dist ./dist/server","generate:tool-contracts":"bun run scripts/generate-tool-contracts.ts","db:migrate":"bun run ./dist/server/migrate.js",check:"tsc --noEmit",start:"bun run ./dist/server/server.js",migrate:"bun run src/database/migrate.ts",test:"bun test src","better-auth:migrate":"bunx --bun @better-auth/cli migrate -y --config src/auth/index.ts",prepublishOnly:"bun run --cwd=../.. build:studio"},optionalDependencies:{"@duckdb/node-api":"^1.5.0-r.1"},dependencies:{"@ai-sdk/anthropic":"^3.0.85","@ai-sdk/google":"^3.0.83","@ai-sdk/openai":"^3.0.73","@anthropic-ai/sdk":"^0.105.0","@aws-sdk/client-s3":"^3.1013.0","@aws-sdk/client-sts":"^3.1013.0","@aws-sdk/lib-storage":"^3.1013.0","@aws-sdk/s3-request-presigner":"^3.1013.0","@clickhouse/client":"^1.8.1","@dbos-inc/dbos-sdk":"^4.21.6","@inkjs/ui":"^2.0.0","@nats-io/jetstream":"3.4.0","@nats-io/kv":"3.4.0","@nats-io/nats-core":"3.4.0","@nats-io/transport-node":"3.4.0","@openrouter/ai-sdk-provider":"^2.9.1","@opentelemetry/core":"^2.6.0","embedded-postgres":"^18.3.0-beta.16",ink:"^6.8.0",kysely:"^0.28.12","posthog-node":"^5.0.0",react:"^19.2.6","react-dom":"^19.2.6"},devDependencies:{"@ai-sdk/provider":"^3.0.10","@better-auth/sso":"1.4.1","@decocms/better-auth":"1.5.17","@decocms/bindings":"workspace:*","@decocms/mcp-utils":"workspace:*","@decocms/runtime":"workspace:*","@decocms/sandbox":"workspace:*","@decocms/shared":"workspace:*","@jitl/quickjs-wasmfile-release-sync":"0.31.0","@modelcontextprotocol/sdk":"1.29.0","@nats-io/jwt":"0.0.10-5","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.211.0","@opentelemetry/exporter-logs-otlp-proto":"^0.211.0","@opentelemetry/exporter-prometheus":"^0.208.0","@opentelemetry/exporter-trace-otlp-proto":"^0.207.0","@opentelemetry/instrumentation-runtime-node":"^0.24.0","@opentelemetry/resources":"^2.6.0","@opentelemetry/sdk-logs":"^0.211.0","@opentelemetry/sdk-metrics":"^2.2.0","@opentelemetry/sdk-node":"^0.207.0","@opentelemetry/sdk-trace-base":"^2.5.0","@types/bun":"^1.3.1","@types/google.maps":"^3.65.2","@types/pg":"^8.15.6","@types/react-syntax-highlighter":"^15.5.13","@vercel/nft":"^1.1.1",ai:"^6.0.208","better-auth":"1.4.22",croner:"^9.1.0",degit:"^2.8.4",hono:"^4.10.7",jose:"^6.0.11",nanoid:"^5.1.6",pg:"^8.16.3",typescript:"^7.0.2",typescript5:"npm:typescript@^5.9.3",zod:"4.3.6"},homepage:"https://github.com/decocms/studio",keywords:["mcp","model-context-protocol","ai","gateway","self-hosted","tools"],license:"MIT",publishConfig:{access:"public"}}});import{Box as xu6,Text as Vi1}from"ink";import{jsx as fu6,jsxs as Si1}from"react/jsx-runtime";function Ci1({version:$}){return Si1(xu6,{flexDirection:"column",marginTop:1,children:[E50.map((Z,X)=>fu6(Vi1,{color:z50[X],children:Z},X)),Si1(Vi1,{dimColor:!0,children:[" v",$]})]})}var _i1=O(()=>{Um()});import{Box as iD,Text as Lw}from"ink";import{Spinner as bu6}from"@inkjs/ui";import{jsx as yY,jsxs as sf}from"react/jsx-runtime";function vi1({status:$}){if($==="pending")return yY(bu6,{label:""});return yY(Lw,{color:"green",children:"\u2713"})}function yu6($){return`${$.name}: ${$.port||"...."}`}function xi1({services:$,migrationsStatus:Z,home:X,serverUrl:Q}){return sf(iD,{flexDirection:"column",paddingBottom:1,children:[yY(Ci1,{version:d50.version}),yY(iD,{marginBottom:1,children:yY(Lw,{dimColor:!0,children:"\u2500".repeat(80)})}),yY(iD,{children:sf(Lw,{dimColor:!0,children:["Home: ",X]})}),sf(iD,{gap:2,children:[$.map((Y)=>sf(iD,{gap:1,children:[yY(Lw,{children:yu6(Y)}),yY(vi1,{status:Y.status})]},Y.name)),sf(iD,{gap:1,children:[yY(Lw,{children:"Migrations"}),yY(vi1,{status:Z})]})]}),yY(iD,{children:Q?sf(Lw,{children:["Open in browser: ",yY(Lw,{color:"cyan",children:Q})]}):yY(Lw,{dimColor:!0,children:"Starting..."})})]})}var fi1=O(()=>{vl0();_i1()});import{Box as gu6,Text as Mm}from"ink";import{jsx as xl0,jsxs as fl0}from"react/jsx-runtime";function hu6($){if($>=500)return"red";if($>=400)return"yellow";if($>=300)return"cyan";return"green"}function bi1({logs:$}){return xl0(gu6,{flexDirection:"column",children:$.map((Z,X)=>{if(Z.rawLine)return xl0(Mm,{dimColor:!0,children:Z.rawLine},X);let Q=Z.duration<1000?`${Z.duration}ms`:`${(Z.duration/1000).toFixed(1)}s`;return fl0(Mm,{children:[fl0(Mm,{dimColor:!0,children:[Z.method.padEnd(6)," ",Z.path.padEnd(30)," "]}),xl0(Mm,{color:hu6(Z.status),children:Z.status}),fl0(Mm,{dimColor:!0,children:[" ",Q.padStart(8)]})]},X)})})}var yi1=()=>{};var bl0={};w0(bl0,{App:()=>lu6});import{Box as uu6}from"ink";import{useSyncExternalStore as cu6}from"react";import{jsx as gi1,jsxs as du6}from"react/jsx-runtime";function lu6({home:$}){let Z=cu6(Vl0,kl0);return du6(uu6,{flexDirection:"column",children:[gi1(xi1,{services:Z.services,migrationsStatus:Z.migrationsStatus,home:$,serverUrl:Z.serverUrl}),gi1(bi1,{logs:Z.logs})]})}var yl0=O(()=>{fi1();yi1();mD()});var KJ="thread-gate",kN="decopilot-hosted-harness",mG="automations",Dw="background-tools";var hi1="7";function ui1($){return{name:"decocms",systemDatabaseUrl:$.systemDatabaseUrl,systemDatabaseSchemaName:"dbos",systemDatabasePoolSize:$.poolSize,runAdminServer:!1,executorID:$.executorID,applicationVersion:hi1,...$.listenQueues!==void 0?{listenQueues:$.listenQueues}:{}}}var ci1=()=>{};function mu6(){let $=(process.env.BUN_OPTIONS??"").split(/\s+/).filter(Boolean);return[...process.argv.slice(1),...$]}function gl0($,Z){for(let X=0;X<$.length;X++){let Q=$[X];if(Q===void 0)continue;if(Q===Z)return $[X+1];if(Q.startsWith(`${Z}=`))return Q.slice(Z.length+1)}return}function li1(){let $=mu6();if($.includes("--cpu-prof")){console.log(JSON.stringify({msg:"cpu-profiling-active",dir:gl0($,"--cpu-prof-dir")??process.cwd(),name:gl0($,"--cpu-prof-name"),markdown:$.includes("--cpu-prof-md"),intervalUs:Number(gl0($,"--cpu-prof-interval")??1000),note:"profile is written on process exit"}));return}if(process.env.CPU_PROFILE)console.warn(JSON.stringify({msg:"cpu-profiling-requested-but-inactive",hint:'CPU profiling is a Bun launch flag. Set BUN_OPTIONS="--cpu-prof --cpu-prof-md --cpu-prof-dir=/tmp" before starting the process.'}))}function di1(){if(process.env.HEAP_WATCH!=="1")return()=>{};let $=Number(process.env.HEAP_WATCH_INTERVAL_MS??60000),Z=async()=>{let X=hD();if(!X)return;let Q={};try{let{heapStats:Y}=await import("bun:jsc"),G=Y(),J=Object.entries(G.objectTypeCounts).sort((K,W)=>W[1]-K[1]).slice(0,20);Q={objectCount:G.objectCount,heapSize:G.heapSize,top:Object.fromEntries(J)}}catch{}console.log(JSON.stringify({msg:"heap-watch",ts:new Date().toISOString(),uptimeS:Math.round(process.uptime()),rss:X.rss,heapUsed:X.heapUsed,heapTotal:X.heapTotal,external:X.external,arrayBuffers:X.arrayBuffers,...Q}))};return Z().catch(()=>{}),m50=setInterval(()=>void Z().catch(()=>{}),$),m50.unref?.(),process.on("SIGUSR2",()=>{try{let X=Bun.generateHeapSnapshot("v8"),Q=typeof X==="string"?X:JSON.stringify(X),Y=`/tmp/heap-${process.pid}-${Date.now()}.heapsnapshot`;Bun.write(Y,Q),console.log(JSON.stringify({msg:"heap-snapshot-written",path:Y}))}catch(X){console.error("[heap-watch] snapshot failed:",X)}}),()=>{if(m50)clearInterval(m50)}}var m50;var mi1=()=>{};import*as iu6 from"bun:jsc";function ii1(){if(process.env.STALL_WATCHDOG!=="1")return()=>{};let $=Number(process.env.STALL_WATCHDOG_MS??100),Z=Number(process.env.STALL_WATCHDOG_TICK_MS??50);try{nu6()}catch(G){return console.error("[stall-watchdog] failed to start sampling profiler:",G),()=>{}}let X,Q=performance.now()+Z,Y=()=>{let G=performance.now(),J=G-Q;Q=G+Z;let K=[];try{K=pu6()?.traces??[]}catch{}if(J>$&&K.length>0){let W=new Map;for(let N of K){let U=N.frames.find((B)=>B.sourceURL&&!/Unknown Executable/.test(B.category??""))??N.frames[0];if(!U)continue;let F=(U.sourceURL??"?").replace(/^.*\/node_modules\//,"node_modules/"),w=`${U.name??"?"} @ ${F}:${U.line??"?"}`;W.set(w,(W.get(w)??0)+1)}let H=[...W.entries()].sort((N,U)=>U[1]-N[1]).slice(0,8).map(([N,U])=>({frame:N,count:U}));console.warn(JSON.stringify({msg:"stall-stack",ts:new Date().toISOString(),lagMs:Math.round(J),samplesInWindow:K.length,top:H}))}X=setTimeout(Y,Z),X.unref?.()};return X=setTimeout(Y,Z),X.unref?.(),()=>{if(X)clearTimeout(X)}}var nu6,pu6;var ni1=O(()=>{({startSamplingProfiler:nu6,samplingProfilerStackTraces:pu6}=iu6)});function pi1(){li1();let $=[di1(),pc1(),ii1()];return()=>{for(let Z of $)Z()}}var ti1=O(()=>{mg0();mi1();ni1()});var nD=_((oi1)=>{Object.defineProperty(oi1,"__esModule",{value:!0});oi1.RepublishHeaders=oi1.DirectMsgHeaders=oi1.JsHeaders=oi1.AdvisoryKind=void 0;oi1.isOrderedPushConsumerOptions=tu6;oi1.isPullConsumer=ou6;oi1.isPushConsumer=ru6;oi1.isBoundPushConsumerOptions=au6;function tu6($){if($&&typeof $==="object")return"name_prefix"in $||"deliver_subject_prefix"in $||"filter_subjects"in $||"filter_subject"in $||"deliver_policy"in $||"opt_start_seq"in $||"opt_start_time"in $||"replay_policy"in $||"inactive_threshold"in $||"headers_only"in $||"deliver_prefix"in $;return!1}function ou6($){return $.isPullConsumer()}function ru6($){return $.isPushConsumer()}function au6($){if($&&typeof $==="object")return"deliver_subject"in $||"deliver_group"in $||"idle_heartbeat"in $;return!1}oi1.AdvisoryKind={API:"api_audit",StreamAction:"stream_action",ConsumerAction:"consumer_action",SnapshotCreate:"snapshot_create",SnapshotComplete:"snapshot_complete",RestoreCreate:"restore_create",RestoreComplete:"restore_complete",MaxDeliver:"max_deliver",Terminated:"terminated",Ack:"consumer_ack",StreamLeaderElected:"stream_leader_elected",StreamQuorumLost:"stream_quorum_lost",ConsumerLeaderElected:"consumer_leader_elected",ConsumerQuorumLost:"consumer_quorum_lost"};oi1.JsHeaders={StreamSourceHdr:"Nats-Stream-Source",LastConsumerSeqHdr:"Nats-Last-Consumer",LastStreamSeqHdr:"Nats-Last-Stream",ConsumerStalledHdr:"Nats-Consumer-Stalled",MessageSizeHdr:"Nats-Msg-Size",RollupHdr:"Nats-Rollup",RollupValueSubject:"sub",RollupValueAll:"all",PendingMessagesHdr:"Nats-Pending-Messages",PendingBytesHdr:"Nats-Pending-Bytes",RequiredApiLevel:"Nats-Required-Api-Level"};oi1.DirectMsgHeaders={Stream:"Nats-Stream",Sequence:"Nats-Sequence",TimeStamp:"Nats-Time-Stamp",Subject:"Nats-Subject",LastSequence:"Nats-Last-Sequence",NumPending:"Nats-Num-Pending"};oi1.RepublishHeaders={Stream:"Nats-Stream",Subject:"Nats-Subject",Sequence:"Nats-Sequence",LastSequence:"Nats-Last-Sequence",Size:"Nats-Msg-Size"}});var gY=_((ai1)=>{Object.defineProperty(ai1,"__esModule",{value:!0});ai1.TD=ai1.TE=ai1.Empty=void 0;ai1.encode=Jc6;ai1.decode=Kc6;ai1.Empty=new Uint8Array(0);ai1.TE=new TextEncoder;ai1.TD=new TextDecoder;function Gc6(...$){let Z=0;for(let Y=0;Y<$.length;Y++)Z+=$[Y].length;let X=new Uint8Array(Z),Q=0;for(let Y=0;Y<$.length;Y++)X.set($[Y],Q),Q+=$[Y].length;return X}function Jc6(...$){let Z=[];for(let X=0;X<$.length;X++)Z.push(ai1.TE.encode($[X]));if(Z.length===0)return ai1.Empty;if(Z.length===1)return Z[0];return Gc6(...Z)}function Kc6($){if(!$||$.length===0)return"";return ai1.TD.decode($)}});var hY=_(($n1)=>{Object.defineProperty($n1,"__esModule",{value:!0});$n1.errors=$n1.PermissionViolationError=$n1.NoRespondersError=$n1.TimeoutError=$n1.RequestError=$n1.ProtocolError=$n1.ConnectionError=$n1.DrainingConnectionError=$n1.ClosedConnectionError=$n1.AuthorizationError=$n1.UserAuthenticationExpiredError=$n1.InvalidOperationError=$n1.InvalidArgumentError=$n1.InvalidSubjectError=void 0;class ul0 extends Error{constructor($,Z){super(`illegal subject: '${$}'`,Z);this.name="InvalidSubjectError"}}$n1.InvalidSubjectError=ul0;class i50 extends Error{constructor($,Z){super($,Z);this.name="InvalidArgumentError"}static format($,Z,X){if(Array.isArray(Z)&&Z.length>1)Z=Z[0];if(Array.isArray($))$=$.map((Q)=>`'${Q}'`),$=$.join(",");else $=`'${$}'`;return new i50(`${$} ${Z}`,X)}}$n1.InvalidArgumentError=i50;class cl0 extends Error{constructor($,Z){super($,Z);this.name="InvalidOperationError"}}$n1.InvalidOperationError=cl0;class n50 extends Error{constructor($,Z){super($,Z);this.name="UserAuthenticationExpiredError"}static parse($){if($.toLowerCase().indexOf("user authentication expired")!==-1)return new n50($);return null}}$n1.UserAuthenticationExpiredError=n50;class p50 extends Error{constructor($,Z){super($,Z);this.name="AuthorizationError"}static parse($){let Z=["authorization violation","account authentication expired","authentication timeout"],X=$.toLowerCase();for(let Q=0;Q<Z.length;Q++)if(X.indexOf(Z[Q])!==-1)return new p50($);return null}}$n1.AuthorizationError=p50;class ll0 extends Error{constructor(){super("closed connection");this.name="ClosedConnectionError"}}$n1.ClosedConnectionError=ll0;class dl0 extends Error{constructor(){super("connection draining");this.name="DrainingConnectionError"}}$n1.DrainingConnectionError=dl0;class ml0 extends Error{constructor($,Z){super($,Z);this.name="ConnectionError"}}$n1.ConnectionError=ml0;class il0 extends Error{constructor($,Z){super($,Z);this.name="ProtocolError"}}$n1.ProtocolError=il0;class nl0 extends Error{constructor($="",Z){super($,Z);this.name="RequestError"}isNoResponders(){return this.cause instanceof t50}}$n1.RequestError=nl0;class pl0 extends Error{constructor($){super("timeout",$);this.name="TimeoutError"}}$n1.TimeoutError=pl0;class t50 extends Error{subject;constructor($,Z){super(`no responders: '${$}'`,Z);this.subject=$,this.name="NoResponders"}}$n1.NoRespondersError=t50;class o50 extends Error{operation;subject;queue;constructor($,Z,X,Q,Y){super($,Y);this.name="PermissionViolationError",this.operation=Z,this.subject=X,this.queue=Q}static parse($){if(($?$.toLowerCase():"").indexOf("permissions violation")===-1)return null;let X="publish",Q="",Y=void 0,G=$.match(/(Publish|Subscription) to "(\S+)"/);if(G){if(X=G[1].toLowerCase(),Q=G[2],X==="subscription"){let J=$.match(/using queue "(\S+)"/);if(J)Y=J[1]}}return new o50($,X,Q,Y)}}$n1.PermissionViolationError=o50;$n1.errors={AuthorizationError:p50,ClosedConnectionError:ll0,ConnectionError:ml0,DrainingConnectionError:dl0,InvalidArgumentError:i50,InvalidOperationError:cl0,InvalidSubjectError:ul0,NoRespondersError:t50,PermissionViolationError:o50,ProtocolError:il0,RequestError:nl0,TimeoutError:pl0,UserAuthenticationExpiredError:n50}});var WJ=_((Gn1)=>{Object.defineProperty(Gn1,"__esModule",{value:!0});Gn1.SimpleMutex=Gn1.Perf=void 0;Gn1.extend=Rc6;Gn1.render=Ic6;Gn1.timeout=qc6;Gn1.delay=Mc6;Gn1.deadline=kc6;Gn1.deferred=ol0;Gn1.debugDeferred=Vc6;Gn1.shuffle=Sc6;Gn1.collect=Cc6;Gn1.jitter=Yn1;Gn1.backoff=_c6;Gn1.nanos=vc6;Gn1.millis=xc6;Gn1.randomToken=yc6;var Tc6=gY(),tl0=hY();function Rc6($,...Z){for(let X=0;X<Z.length;X++){let Q=Z[X];Object.keys(Q).forEach(function(Y){$[Y]=Q[Y]})}return $}function Ic6($){return Tc6.TD.decode($).replace(/\n/g,"\u240A").replace(/\r/g,"\u240D")}function qc6($,Z=!0){let X=Z?new tl0.TimeoutError:null,Q,Y,G=new Promise((J,K)=>{Q={cancel:()=>{if(Y)clearTimeout(Y)}},Y=setTimeout(()=>{if(X===null)K(new tl0.TimeoutError);else K(X)},$)});return Object.assign(G,Q)}function Mc6($=0){let Z,X=new Promise((Q)=>{let Y=setTimeout(()=>{Q()},$);Z={cancel:()=>{if(Y)clearTimeout(Y),Q()}}});return Object.assign(X,Z)}async function kc6($,Z=1000){let X=ol0(),Q=setTimeout(()=>{X.reject(new tl0.TimeoutError)},Z);try{return await Promise.race([$,X])}finally{clearTimeout(Q)}}function ol0(){let $={},Z=new Promise((X,Q)=>{$={resolve:X,reject:Q}});return Object.assign(Z,$)}function Vc6(){let $={},Z=new Promise((X,Q)=>{$={resolve:(Y)=>{console.trace("resolve",Y),X(Y)},reject:(Y)=>{console.trace("reject"),Q(Y)}}});return Object.assign(Z,$)}function Sc6($){for(let Z=$.length-1;Z>0;Z--){let X=Math.floor(Math.random()*(Z+1));[$[Z],$[X]]=[$[X],$[Z]]}return $}async function Cc6($){let Z=[];for await(let X of $)Z.push(X);return Z}class Xn1{timers;measures;constructor(){this.timers=new Map,this.measures=new Map}mark($){this.timers.set($,performance.now())}measure($,Z,X){let Q=this.timers.get(Z);if(Q===void 0)throw Error(`${Z} is not defined`);let Y=this.timers.get(X);if(Y===void 0)throw Error(`${X} is not defined`);this.measures.set($,Y-Q)}getEntries(){let $=[];return this.measures.forEach((Z,X)=>{$.push({name:X,duration:Z})}),$}}Gn1.Perf=Xn1;class Qn1{max;current;waiting;constructor($=1){this.max=$,this.current=0,this.waiting=[]}lock(){if(this.current++,this.current<=this.max)return Promise.resolve();let $=ol0();return this.waiting.push($),$}unlock(){this.current--,this.waiting.pop()?.resolve()}}Gn1.SimpleMutex=Qn1;function Yn1($){if($===0)return 0;return Math.floor($/2+Math.random()*$)}function _c6($=[0,250,250,500,500,3000,5000]){if(!Array.isArray($))$=[0,250,250,500,500,3000,5000];let Z=$.length-1;return{backoff(X){return Yn1(X>Z?$[Z]:$[X])}}}function vc6($){return $*1e6}function xc6($){return Math.floor($/1e6)}var fc6="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",VN=new Uint8Array(62);for(let $=0;$<62;$++)VN[$]=fc6.charCodeAt($);var bc6=218340105584896;function yc6(){let $=Math.floor(Math.random()*bc6),Z=$%62,X=VN[Z];$=($-Z)/62,Z=$%62;let Q=VN[Z];$=($-Z)/62,Z=$%62;let Y=VN[Z];$=($-Z)/62,Z=$%62;let G=VN[Z];$=($-Z)/62,Z=$%62;let J=VN[Z];$=($-Z)/62,Z=$%62;let K=VN[Z];$=($-Z)/62,Z=$%62;let W=VN[Z];$=($-Z)/62;let H=VN[$];return String.fromCharCode(X,Q,Y,G,J,K,W,H)}});var wn1=_((Un1)=>{Object.defineProperty(Un1,"__esModule",{value:!0});Un1.nuid=Un1.NuidImpl=void 0;var ec6="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Ew=62,a50=12,Hn1=10,Kn1=33,$l6=333,Wn1=a50+Hn1,al0=new Uint8Array(Ew);for(let $=0;$<Ew;$++)al0[$]=ec6.charCodeAt($);var r50=4294967296,Nn1=BigInt(Ew)**BigInt(Hn1),km=Number(Nn1/(1n<<32n)),rl0=Number(Nn1%(1n<<32n));function Zl6($){for(let Z=0;Z<$.length;Z++)$[Z]=Math.floor(Math.random()*256)}function Xl6($){if(globalThis?.crypto?.getRandomValues)globalThis.crypto.getRandomValues($);else Zl6($)}class sl0{buf;cbuf;seqHi;seqLo;inc;inited;constructor(){this.buf=new Uint8Array(Wn1),this.cbuf=new Uint8Array(a50),this.inited=!1}init(){this.inited=!0,this.setPre(),this.initSeqAndInc(),this.fillSeq()}initSeqAndInc(){let $=0;do this.seqHi=Math.floor(Math.random()*(km+1)),this.seqLo=Math.floor(Math.random()*r50);while($++<8&&this.seqHi===km&&this.seqLo>=rl0);if(this.seqHi===km&&this.seqLo>=rl0)this.seqLo=0;this.inc=Math.random()*($l6-Kn1)+Kn1|0}setPre(){Xl6(this.cbuf);for(let $=0;$<a50;$++)this.buf[$]=al0[this.cbuf[$]%Ew]}fillSeq(){let $=this.seqHi,Z=this.seqLo;for(let X=Wn1-1;X>=a50;X--){let Q=Math.floor($/Ew),G=($-Q*Ew)*r50+Z,J=Math.floor(G/Ew),K=G-J*Ew;this.buf[X]=al0[K],$=Q,Z=J}}next(){if(!this.inited)this.init();if(this.seqLo+=this.inc,this.seqLo>=r50)this.seqLo-=r50,this.seqHi+=1;if(this.seqHi>km||this.seqHi===km&&this.seqLo>=rl0)this.setPre(),this.initSeqAndInc();this.fillSeq();let $=this.buf;return String.fromCharCode($[0],$[1],$[2],$[3],$[4],$[5],$[6],$[7],$[8],$[9],$[10],$[11],$[12],$[13],$[14],$[15],$[16],$[17],$[18],$[19],$[20],$[21])}reset(){this.init()}}Un1.NuidImpl=sl0;Un1.nuid=new sl0});var Dn1=_((On1)=>{Object.defineProperty(On1,"__esModule",{value:!0});On1.nuid=On1.Nuid=void 0;var Bn1=wn1();On1.Nuid=Bn1.NuidImpl;On1.nuid=Bn1.nuid});var e50=_((s50)=>{Object.defineProperty(s50,"__esModule",{value:!0});s50.nuid=s50.Nuid=void 0;var En1=Dn1();Object.defineProperty(s50,"Nuid",{enumerable:!0,get:function(){return En1.Nuid}});Object.defineProperty(s50,"nuid",{enumerable:!0,get:function(){return En1.nuid}})});var zw=_((zn1)=>{Object.defineProperty(zn1,"__esModule",{value:!0});zn1.DEFAULT_HOST=zn1.DEFAULT_PORT=zn1.Match=void 0;zn1.syncIterator=Wl6;zn1.createInbox=Hl6;var Jl6=e50(),Kl6=hY();zn1.Match={Exact:"exact",CanonicalMIME:"canonical",IgnoreCase:"insensitive"};function Wl6($){let Z=$[Symbol.asyncIterator]();return{async next(){let X=await Z.next();if(X.done)return Promise.resolve(null);return Promise.resolve(X.value)}}}function Hl6($=""){if($=$||"_INBOX",typeof $!=="string")throw TypeError("prefix must be a string");return $.split(".").forEach((Z)=>{if(Z==="*"||Z===">")throw Kl6.InvalidArgumentError.format("prefix",`cannot have wildcards ('${$}')`)}),`${$}.${Jl6.nuid.next()}`}zn1.DEFAULT_PORT=4222;zn1.DEFAULT_HOST="127.0.0.1"});var Vm=_((Tn1)=>{Object.defineProperty(Tn1,"__esModule",{value:!0});Tn1.DataBuffer=void 0;var Pn1=gY();class An1{buffers;byteLength;constructor(){this.buffers=[],this.byteLength=0}static concat(...$){let Z=0;for(let Y=0;Y<$.length;Y++)Z+=$[Y].length;let X=new Uint8Array(Z),Q=0;for(let Y=0;Y<$.length;Y++)X.set($[Y],Q),Q+=$[Y].length;return X}static fromAscii($){if(!$)$="";return Pn1.TE.encode($)}static toAscii($){return Pn1.TD.decode($)}reset(){this.buffers.length=0,this.byteLength=0}pack(){if(this.buffers.length>1){let $=new Uint8Array(this.byteLength),Z=0;for(let X=0;X<this.buffers.length;X++)$.set(this.buffers[X],Z),Z+=this.buffers[X].length;this.buffers.length=0,this.buffers.push($)}}shift(){if(this.buffers.length){let $=this.buffers.shift();if($)return this.byteLength-=$.length,$}return new Uint8Array(0)}drain($){if(this.buffers.length){this.pack();let Z=this.buffers.pop();if(Z){let X=this.byteLength;if($===void 0||$>X)$=X;let Q=Z.subarray(0,$);if(X>$)this.buffers.push(Z.subarray($));return this.byteLength=X-$,Q}}return new Uint8Array(0)}fill($,...Z){if($)this.buffers.push($),this.byteLength+=$.length;for(let X=0;X<Z.length;X++)if(Z[X]&&Z[X].length)this.buffers.push(Z[X]),this.byteLength+=Z[X].length}peek(){if(this.buffers.length)return this.pack(),this.buffers[0];return new Uint8Array(0)}size(){return this.byteLength}length(){return this.buffers.length}}Tn1.DataBuffer=An1});var pD=_((qn1)=>{Object.defineProperty(qn1,"__esModule",{value:!0});qn1.LF=qn1.CR=qn1.CRLF=qn1.CR_LF_LEN=qn1.CR_LF=void 0;qn1.setTransportFactory=Dl6;qn1.defaultPort=El6;qn1.getUrlParseFn=zl6;qn1.newTransport=jl6;qn1.getResolveFn=Pl6;qn1.protoLen=In1;qn1.extractProtocolMessage=Al6;var Bl6=gY(),Ol6=zw(),Ll6=Vm(),uY;function Dl6($){uY=$}function El6(){return uY!==void 0&&uY.defaultPort!==void 0?uY.defaultPort:Ol6.DEFAULT_PORT}function zl6(){return uY!==void 0&&uY.urlParseFn?uY.urlParseFn:void 0}function jl6(){if(!uY||typeof uY.factory!=="function")throw Error("transport fn is not set");return uY.factory()}function Pl6(){return uY!==void 0&&uY.dnsResolveFn?uY.dnsResolveFn:void 0}qn1.CR_LF=`\r
|
|
1314
1314
|
`;qn1.CR_LF_LEN=qn1.CR_LF.length;qn1.CRLF=Ll6.DataBuffer.fromAscii(qn1.CR_LF);qn1.CR=new Uint8Array(qn1.CRLF)[0];qn1.LF=new Uint8Array(qn1.CRLF)[1];function In1($){for(let Z=0;Z<$.length;Z++){let X=Z+1;if($.byteLength>X&&$[Z]===qn1.CR&&$[X]===qn1.LF)return X+1}return 0}function Al6($){let Z=In1($);if(Z>0){let Q=new Uint8Array($).slice(0,Z);return Bl6.TD.decode(Q)}return""}});var Qd0=_((xn1)=>{Object.defineProperty(xn1,"__esModule",{value:!0});xn1.ipV4=Cn1;xn1.isIP=vl6;xn1.parseIP=_n1;var Sm=4,tD=16,$90=48,Sn1=57,kn1=65,Cl6=70,Vn1=97,_l6=102,Xd0=16777215;function Cn1($,Z,X,Q){let Y=new Uint8Array(tD);return[0,0,0,0,0,0,0,0,0,0,255,255].forEach((J,K)=>{Y[K]=J}),Y[12]=$,Y[13]=Z,Y[14]=X,Y[15]=Q,Y}function vl6($){return _n1($)!==void 0}function _n1($){for(let Z=0;Z<$.length;Z++)switch($[Z]){case".":return vn1($);case":":return xl6($)}return}function vn1($){let Z=new Uint8Array(Sm);for(let X=0;X<Sm;X++){if($.length===0)return;if(X>0){if($[0]!==".")return;$=$.substring(1)}let{n:Q,c:Y,ok:G}=fl6($);if(!G||Q>255)return;$=$.substring(Y),Z[X]=Q}return Cn1(Z[0],Z[1],Z[2],Z[3])}function xl6($){let Z=new Uint8Array(tD),X=-1;if($.length>=2&&$[0]===":"&&$[1]===":"){if(X=0,$=$.substring(2),$.length===0)return Z}let Q=0;while(Q<tD){let{n:Y,c:G,ok:J}=bl6($);if(!J||Y>65535)return;if(G<$.length&&$[G]==="."){if(X<0&&Q!=tD-Sm)return;if(Q+Sm>tD)return;let K=vn1($);if(K===void 0)return;Z[Q]=K[12],Z[Q+1]=K[13],Z[Q+2]=K[14],Z[Q+3]=K[15],$="",Q+=Sm;break}if(Z[Q]=Y>>8,Z[Q+1]=Y,Q+=2,$=$.substring(G),$.length===0)break;if($[0]!==":"||$.length==1)return;if($=$.substring(1),$[0]===":"){if(X>=0)return;if(X=Q,$=$.substring(1),$.length===0)break}}if($.length!==0)return;if(Q<tD){if(X<0)return;let Y=tD-Q;for(let G=Q-1;G>=X;G--)Z[G+Y]=Z[G];for(let G=X+Y-1;G>=X;G--)Z[G]=0}else if(X>=0)return;return Z}function fl6($){let Z=0,X=0;for(Z=0;Z<$.length&&$90<=$.charCodeAt(Z)&&$.charCodeAt(Z)<=Sn1;Z++)if(X=X*10+($.charCodeAt(Z)-$90),X>=Xd0)return{n:Xd0,c:Z,ok:!1};if(Z===0)return{n:0,c:0,ok:!1};return{n:X,c:Z,ok:!0}}function bl6($){let Z=0,X=0;for(X=0;X<$.length;X++){if($90<=$.charCodeAt(X)&&$.charCodeAt(X)<=Sn1)Z*=16,Z+=$.charCodeAt(X)-$90;else if(Vn1<=$.charCodeAt(X)&&$.charCodeAt(X)<=_l6)Z*=16,Z+=$.charCodeAt(X)-Vn1+10;else if(kn1<=$.charCodeAt(X)&&$.charCodeAt(X)<=Cl6)Z*=16,Z+=$.charCodeAt(X)-kn1+10;else break;if(Z>=Xd0)return{n:0,c:X,ok:!1}}if(X===0)return{n:0,c:X,ok:!1};return{n:Z,c:X,ok:!0}}});var Hd0=_((bn1)=>{Object.defineProperty(bn1,"__esModule",{value:!0});bn1.Servers=bn1.ServerImpl=void 0;bn1.isIPV4OrHostname=fn1;bn1.hostPort=Wd0;var Yd0=pD(),Gd0=WJ(),Jd0=Qd0(),ul6=zw(),cl6=hY();function fn1($){if($.indexOf("[")!==-1||$.indexOf("::")!==-1)return!1;if($.indexOf(".")!==-1)return!0;if($.split(":").length<=2)return!0;return!1}function Kd0($){return!fn1($)}function ll6($){let X=$.toUpperCase().indexOf("::FFFF:");if(X!==-1&&$.indexOf(".")!==-1){let Q=$.substring(X+7);return Q=Q.replace("[",""),Q.replace("]","")}return $}function Wd0($){if($=$.trim(),$.match(/^(.*:\/\/)(.*)/m))$=$.replace(/^(.*:\/\/)(.*)/gm,"$2");if($=ll6($),Kd0($)&&$.indexOf("[")===-1)$=`[${$}]`;let Z=Kd0($)?$.match(/(]:)(\d+)/):$.match(/(:)(\d+)/),X=Z&&Z.length===3&&Z[1]&&Z[2]?parseInt(Z[2]):ul6.DEFAULT_PORT,Y=new URL(`${X===80?"https":"http"}://${$}`);Y.port=`${X}`;let G=Y.hostname;if(G.charAt(0)==="[")G=G.substring(1,G.length-1);return{listen:Y.host,hostname:G,port:X}}class ef{src;listen;hostname;port;didConnect;reconnects;lastConnect;gossiped;tlsName;resolves;constructor($,Z=!1){this.src=$,this.tlsName="";let X=Wd0($);this.listen=X.listen,this.hostname=X.hostname,this.port=X.port,this.didConnect=!1,this.reconnects=0,this.lastConnect=0,this.gossiped=Z}toString(){return this.listen}async resolve($){if(!$.fn||$.resolve===!1)return[this];let Z=[];if((0,Jd0.isIP)(this.hostname))return[this];else{let X=await $.fn(this.hostname);if($.debug)console.log(`resolve ${this.hostname} = ${X.join(",")}`);for(let Q of X){let Y=this.port===80?"https":"http",G=new URL(`${Y}://${Kd0(Q)?"["+Q+"]":Q}`);G.port=`${this.port}`;let J=new ef(G.host,!1);J.tlsName=this.hostname,Z.push(J)}}if($.randomize)(0,Gd0.shuffle)(Z);return this.resolves=Z,Z}}bn1.ServerImpl=ef;class Z90{firstSelect;servers;currentServer;tlsName;randomize;constructor($={}){this.firstSelect=!0,this.servers=[],this.tlsName="",this.randomize=$.randomize||!1}setServers($){if(!Array.isArray($)||$.length===0)throw cl6.InvalidArgumentError.format("servers","cannot be empty");let Z=(0,Yd0.getUrlParseFn)(),X=new Map;for(let Y of this.servers)X.set(Y.listen,Y);let Q=[];for(let Y of $){Y=Z?Z(Y):Y;let{listen:G}=Wd0(Y),J=X.get(G);if(J)J.gossiped=!1,Q.push(J);else Q.push(new ef(Y))}if(this.randomize)(0,Gd0.shuffle)(Q);if(this.servers=Q,this.currentServer===void 0||!Q.includes(this.currentServer))this.currentServer=Q[0],this.firstSelect=!0}clear(){this.servers.length=0}updateTLSName(){let $=this.getCurrentServer();if(!(0,Jd0.isIP)($.hostname))this.tlsName=$.hostname,this.servers.forEach((Z)=>{if(Z.gossiped)Z.tlsName=this.tlsName})}getCurrentServer(){return this.currentServer}addServer($,Z=!1){let X=(0,Yd0.getUrlParseFn)();$=X?X($):$;let Q=new ef($,Z);if((0,Jd0.isIP)(Q.hostname))Q.tlsName=this.tlsName;this.servers.push(Q)}selectServer(){if(this.firstSelect)return this.firstSelect=!1,this.currentServer;let $=this.servers.shift();if($)this.servers.push($),this.currentServer=$;return $}removeCurrentServer(){this.removeServer(this.currentServer)}removeServer($){if($){let Z=this.servers.indexOf($);this.servers.splice(Z,1)}}snapshot(){return Z90.freezeAll(this.servers)}snapshotForHandler(){let $=this.currentServer;if(!$)return this.snapshot();let Z=this.servers.indexOf($);if(Z<=0)return this.snapshot();return Z90.freezeAll([$,...this.servers.slice(0,Z),...this.servers.slice(Z+1)])}static freezeAll($){return $.map((Z)=>Object.freeze({hostname:Z.hostname,port:Z.port,listen:Z.listen,src:Z.src,tlsName:Z.tlsName,reconnects:Z.reconnects,lastConnect:Z.lastConnect,gossiped:Z.gossiped,didConnect:Z.didConnect}))}find($){return this.servers.find((Z)=>Z.listen===$.listen)}setCurrent($){this.currentServer=$}length(){return this.servers.length}next(){return this.servers.length?this.servers[0]:void 0}getServers(){return this.servers}update($,Z){let X=[],Q=[],Y=(0,Yd0.getUrlParseFn)(),G=new Map;if($.connect_urls&&$.connect_urls.length>0)$.connect_urls.forEach((K)=>{K=Y?Y(K,Z):K;let W=new ef(K,!0);G.set(K,W)});let J=[];if(this.servers.forEach((K,W)=>{let H=K.listen;if(K.gossiped&&this.currentServer.listen!==H&&G.get(H)===void 0)J.push(W);G.delete(H)}),J.reverse(),J.forEach((K)=>{let W=this.servers.splice(K,1);Q=Q.concat(W[0].listen)}),G.forEach((K,W)=>{this.servers.push(K),X.push(W)}),this.randomize&&X.length>0){let K=this.currentServer,W=this.servers.filter((H)=>H!==K);(0,Gd0.shuffle)(W),this.servers=K?[K,...W]:W}return{added:X,deleted:Q}}}bn1.Servers=Z90});var X90=_((un1)=>{Object.defineProperty(un1,"__esModule",{value:!0});un1.QueuedIteratorImpl=void 0;var Nd0=WJ(),gn1=hY();class hn1{inflight;processed;received;noIterator;iterClosed;done;signal;yields;filtered;pendingFiltered;ctx;_data;err;time;profile;yielding;didBreak;constructor(){this.inflight=0,this.filtered=0,this.pendingFiltered=0,this.processed=0,this.received=0,this.noIterator=!1,this.done=!1,this.signal=(0,Nd0.deferred)(),this.yields=[],this.iterClosed=(0,Nd0.deferred)(),this.time=0,this.yielding=!1,this.didBreak=!1,this.profile=!1}[Symbol.asyncIterator](){return this.iterate()}push($){if(this.done)return;if(this.didBreak){if(typeof $==="function"){let Z=$;try{Z()}catch(X){}}return}if(typeof $==="function")this.pendingFiltered++;this.yields.push($),this.signal.resolve()}async*iterate(){if(this.noIterator)throw new gn1.InvalidOperationError("iterator cannot be used when a callback is registered");if(this.yielding)throw new gn1.InvalidOperationError("iterator is already yielding");this.yielding=!0;try{while(!0){if(this.yields.length===0)await this.signal;if(this.err)throw this.err;let $=this.yields;this.inflight=$.length,this.yields=[];for(let Z=0;Z<$.length;Z++){if(typeof $[Z]==="function"){this.pendingFiltered--;let Q=$[Z];try{Q()}catch(Y){throw Y}if(this.err)throw this.err;continue}this.processed++,this.inflight--;let X=this.profile?Date.now():0;yield $[Z],this.time=this.profile?Date.now()-X:0}if(this.done)break;else if(this.yields.length===0)$.length=0,this.yields=$,this.signal=(0,Nd0.deferred)()}}finally{this.didBreak=!0,this.stop()}}stop($){if(this.done)return;this.err=$,this.done=!0,this.signal.resolve(),this.iterClosed.resolve($)}getProcessed(){return this.noIterator?this.received:this.processed}getPending(){return this.yields.length+this.inflight-this.pendingFiltered}getReceived(){return this.received-this.filtered}}un1.QueuedIteratorImpl=hn1});var Ud0=_((mn1)=>{Object.defineProperty(mn1,"__esModule",{value:!0});mn1.MuxSubscription=void 0;var nl6=zw(),ln1=hY();class dn1{baseInbox;reqs;constructor(){this.reqs=new Map}size(){return this.reqs.size}init($){return this.baseInbox=`${(0,nl6.createInbox)($)}.`,this.baseInbox}add($){if(!isNaN($.received))$.received=0;this.reqs.set($.token,$)}get($){return this.reqs.get($)}cancel($){this.reqs.delete($.token)}getToken($){let Z=$.subject||"";if(Z.indexOf(this.baseInbox)===0)return Z.substring(this.baseInbox.length);return null}all(){return Array.from(this.reqs.values())}handleError($,Z){if($)return this.all().forEach((X)=>{X.resolver(Z,{})}),!0;if(Z.operation==="publish"){let X=this.all().find((Q)=>{return Q.requestSubject===Z.subject});if(X)return X.resolver(Z,{}),!0}return!1}dispatcher(){return($,Z)=>{let X=this.getToken(Z);if(X){let Q=this.get(X);if(Q){if($===null)$=Z?.data?.length===0&&Z.headers?.code===503?new ln1.NoRespondersError(Q.requestSubject):null;Q.resolver($,Z)}}}}close(){let $=new ln1.RequestError("connection closed");this.reqs.forEach((Z)=>{Z.resolver($,{})})}}mn1.MuxSubscription=dn1});var Fd0=_((pn1)=>{Object.defineProperty(pn1,"__esModule",{value:!0});pn1.Heartbeat=void 0;var pl6=WJ();class nn1{ph;interval;maxOut;timer;pendings;constructor($,Z,X){this.ph=$,this.interval=Z,this.maxOut=X,this.pendings=[]}start(){this.cancel(),this._schedule()}cancel($){if(this.timer)clearTimeout(this.timer),this.timer=void 0;if(this._reset(),$)this.ph.disconnect()}_schedule(){this.timer=setTimeout(()=>{if(this.ph.dispatchStatus({type:"ping",pendingPings:this.pendings.length+1}),this.pendings.length===this.maxOut){this.cancel(!0);return}let $=(0,pl6.deferred)();this.ph.flush($).then(()=>{this._reset()}).catch(()=>{this.cancel()}),this.pendings.push($),this._schedule()},this.interval)}_reset(){this.pendings=this.pendings.filter(($)=>{return $.resolve(),!1})}}pn1.Heartbeat=nn1});var Od0=_((sn1)=>{Object.defineProperty(sn1,"__esModule",{value:!0});sn1.DenoBuffer=sn1.MAX_SIZE=sn1.AssertionError=void 0;sn1.assert=rn1;sn1.concat=an1;sn1.append=ol6;sn1.readAll=rl6;sn1.writeAll=al6;var tl6=gY();class wd0 extends Error{constructor($){super($);this.name="AssertionError"}}sn1.AssertionError=wd0;function rn1($,Z="Assertion failed."){if(!$)throw new wd0(Z)}var on1=32768;sn1.MAX_SIZE=4294967294;function Q90($,Z,X=0){let Q=Z.byteLength-X;if($.byteLength>Q)$=$.subarray(0,Q);return Z.set($,X),$.byteLength}function an1($,Z){if($===void 0&&Z===void 0)return new Uint8Array(0);if($===void 0)return Z;if(Z===void 0)return $;let X=new Uint8Array($.length+Z.length);return X.set($,0),X.set(Z,$.length),X}function ol6($,Z){return an1($,Uint8Array.of(Z))}class Bd0{_buf;_off;constructor($){if(this._off=0,$==null){this._buf=new Uint8Array(0);return}this._buf=new Uint8Array($)}bytes($={copy:!0}){if($.copy===!1)return this._buf.subarray(this._off);return this._buf.slice(this._off)}empty(){return this._buf.byteLength<=this._off}get length(){return this._buf.byteLength-this._off}get capacity(){return this._buf.buffer.byteLength}truncate($){if($===0){this.reset();return}if($<0||$>this.length)throw Error("bytes.Buffer: truncation out of range");this._reslice(this._off+$)}reset(){this._reslice(0),this._off=0}_tryGrowByReslice($){let Z=this._buf.byteLength;if($<=this.capacity-Z)return this._reslice(Z+$),Z;return-1}_reslice($){rn1($<=this._buf.buffer.byteLength),this._buf=new Uint8Array(this._buf.buffer,0,$)}readByte(){let $=new Uint8Array(1);if(this.read($))return $[0];return null}read($){if(this.empty()){if(this.reset(),$.byteLength===0)return 0;return null}let Z=Q90(this._buf.subarray(this._off),$);return this._off+=Z,Z}writeByte($){return this.write(Uint8Array.of($))}writeString($){return this.write(tl6.TE.encode($))}write($){let Z=this._grow($.byteLength);return Q90($,this._buf,Z)}_grow($){let Z=this.length;if(Z===0&&this._off!==0)this.reset();let X=this._tryGrowByReslice($);if(X>=0)return X;let Q=this.capacity;if($<=Math.floor(Q/2)-Z)Q90(this._buf.subarray(this._off),this._buf);else if(Q+$>sn1.MAX_SIZE)throw Error("The buffer cannot be grown beyond the maximum size.");else{let Y=new Uint8Array(Math.min(2*Q+$,sn1.MAX_SIZE));Q90(this._buf.subarray(this._off),Y),this._buf=Y}return this._off=0,this._reslice(Math.min(Z+$,sn1.MAX_SIZE)),Z}grow($){if($<0)throw Error("Buffer._grow: negative count");let Z=this._grow($);this._reslice(Z)}readFrom($){let Z=0,X=new Uint8Array(on1);while(!0){let Q=this.capacity-this.length<on1,Y=Q?X:new Uint8Array(this._buf.buffer,this.length),G=$.read(Y);if(G===null)return Z;if(Q)this.write(Y.subarray(0,G));else this._reslice(this.length+G);Z+=G}}}sn1.DenoBuffer=Bd0;function rl6($){let Z=new Bd0;return Z.readFrom($),Z.bytes()}function al6($,Z){let X=0;while(X<Z.length)X+=$.write(Z.subarray(X))}});var Ed0=_((Qp1)=>{Object.defineProperty(Qp1,"__esModule",{value:!0});Qp1.cc=Qp1.State=Qp1.Parser=Qp1.Kind=void 0;Qp1.describe=Yd6;var Ld0=Od0(),Dd0=gY();Qp1.Kind={OK:0,ERR:1,MSG:2,INFO:3,PING:4,PONG:5};function Yd6($){let Z,X="";switch($.kind){case Qp1.Kind.MSG:Z="MSG";break;case Qp1.Kind.OK:Z="OK";break;case Qp1.Kind.ERR:Z="ERR",X=Dd0.TD.decode($.data);break;case Qp1.Kind.PING:Z="PING";break;case Qp1.Kind.PONG:Z="PONG";break;case Qp1.Kind.INFO:Z="INFO",X=Dd0.TD.decode($.data)}return`${Z}: ${X}`}function $p1(){let $={};return $.sid=-1,$.hdr=-1,$.size=-1,$}var Zp1=48,Gd6=57,$b=67108864;class Xp1{dispatcher;state;as;drop;hdr;ma;argBuf;msgBuf;constructor($){this.dispatcher=$,this.state=Qp1.State.OP_START,this.as=0,this.drop=0,this.hdr=0}parse($){let Z;for(Z=0;Z<$.length;Z++){let X=$[Z];switch(this.state){case Qp1.State.OP_START:switch(X){case Qp1.cc.M:case Qp1.cc.m:this.state=Qp1.State.OP_M,this.hdr=-1,this.ma=$p1();break;case Qp1.cc.H:case Qp1.cc.h:this.state=Qp1.State.OP_H,this.hdr=0,this.ma=$p1();break;case Qp1.cc.P:case Qp1.cc.p:this.state=Qp1.State.OP_P;break;case Qp1.cc.PLUS:this.state=Qp1.State.OP_PLUS;break;case Qp1.cc.MINUS:this.state=Qp1.State.OP_MINUS;break;case Qp1.cc.I:case Qp1.cc.i:this.state=Qp1.State.OP_I;break;default:throw this.fail($.subarray(Z))}break;case Qp1.State.OP_H:switch(X){case Qp1.cc.M:case Qp1.cc.m:this.state=Qp1.State.OP_M;break;default:throw this.fail($.subarray(Z))}break;case Qp1.State.OP_M:switch(X){case Qp1.cc.S:case Qp1.cc.s:this.state=Qp1.State.OP_MS;break;default:throw this.fail($.subarray(Z))}break;case Qp1.State.OP_MS:switch(X){case Qp1.cc.G:case Qp1.cc.g:this.state=Qp1.State.OP_MSG;break;default:throw this.fail($.subarray(Z))}break;case Qp1.State.OP_MSG:switch(X){case Qp1.cc.SPACE:case Qp1.cc.TAB:this.state=Qp1.State.OP_MSG_SPC;break;default:throw this.fail($.subarray(Z))}break;case Qp1.State.OP_MSG_SPC:switch(X){case Qp1.cc.SPACE:case Qp1.cc.TAB:continue;default:this.state=Qp1.State.MSG_ARG,this.as=Z}break;case Qp1.State.MSG_ARG:switch(X){case Qp1.cc.CR:this.drop=1;break;case Qp1.cc.NL:{let Q=this.argBuf?this.argBuf.bytes():$.subarray(this.as,Z-this.drop);this.processMsgArgs(Q),this.drop=0,this.as=Z+1,this.state=Qp1.State.MSG_PAYLOAD,Z=this.as+this.ma.size-1;break}default:if(this.argBuf)this.argBuf.writeByte(X)}break;case Qp1.State.MSG_PAYLOAD:if(this.msgBuf)if(this.msgBuf.length>=this.ma.size){let Q=this.msgBuf.bytes({copy:!1});this.dispatcher.push({kind:Qp1.Kind.MSG,msg:this.ma,data:Q}),this.argBuf=void 0,this.msgBuf=void 0,this.state=Qp1.State.MSG_END}else{let Q=this.ma.size-this.msgBuf.length,Y=$.length-Z;if(Y<Q)Q=Y;if(Q>0)this.msgBuf.write($.subarray(Z,Z+Q)),Z=Z+Q-1;else this.msgBuf.writeByte(X)}else if(Z-this.as>=this.ma.size)this.dispatcher.push({kind:Qp1.Kind.MSG,msg:this.ma,data:$.subarray(this.as,Z)}),this.argBuf=void 0,this.msgBuf=void 0,this.state=Qp1.State.MSG_END;break;case Qp1.State.MSG_END:switch(X){case Qp1.cc.NL:this.drop=0,this.as=Z+1,this.state=Qp1.State.OP_START;break;default:continue}break;case Qp1.State.OP_PLUS:switch(X){case Qp1.cc.O:case Qp1.cc.o:this.state=Qp1.State.OP_PLUS_O;break;default:throw this.fail($.subarray(Z))}break;case Qp1.State.OP_PLUS_O:switch(X){case Qp1.cc.K:case Qp1.cc.k:this.state=Qp1.State.OP_PLUS_OK;break;default:throw this.fail($.subarray(Z))}break;case Qp1.State.OP_PLUS_OK:switch(X){case Qp1.cc.NL:this.dispatcher.push({kind:Qp1.Kind.OK}),this.drop=0,this.state=Qp1.State.OP_START;break}break;case Qp1.State.OP_MINUS:switch(X){case Qp1.cc.E:case Qp1.cc.e:this.state=Qp1.State.OP_MINUS_E;break;default:throw this.fail($.subarray(Z))}break;case Qp1.State.OP_MINUS_E:switch(X){case Qp1.cc.R:case Qp1.cc.r:this.state=Qp1.State.OP_MINUS_ER;break;default:throw this.fail($.subarray(Z))}break;case Qp1.State.OP_MINUS_ER:switch(X){case Qp1.cc.R:case Qp1.cc.r:this.state=Qp1.State.OP_MINUS_ERR;break;default:throw this.fail($.subarray(Z))}break;case Qp1.State.OP_MINUS_ERR:switch(X){case Qp1.cc.SPACE:case Qp1.cc.TAB:this.state=Qp1.State.OP_MINUS_ERR_SPC;break;default:throw this.fail($.subarray(Z))}break;case Qp1.State.OP_MINUS_ERR_SPC:switch(X){case Qp1.cc.SPACE:case Qp1.cc.TAB:continue;default:this.state=Qp1.State.MINUS_ERR_ARG,this.as=Z}break;case Qp1.State.MINUS_ERR_ARG:switch(X){case Qp1.cc.CR:this.drop=1;break;case Qp1.cc.NL:{let Q;if(this.argBuf)Q=this.argBuf.bytes(),this.argBuf=void 0;else Q=$.subarray(this.as,Z-this.drop);this.dispatcher.push({kind:Qp1.Kind.ERR,data:Q}),this.drop=0,this.as=Z+1,this.state=Qp1.State.OP_START;break}default:if(this.argBuf)this.argBuf.write(Uint8Array.of(X))}break;case Qp1.State.OP_P:switch(X){case Qp1.cc.I:case Qp1.cc.i:this.state=Qp1.State.OP_PI;break;case Qp1.cc.O:case Qp1.cc.o:this.state=Qp1.State.OP_PO;break;default:throw this.fail($.subarray(Z))}break;case Qp1.State.OP_PO:switch(X){case Qp1.cc.N:case Qp1.cc.n:this.state=Qp1.State.OP_PON;break;default:throw this.fail($.subarray(Z))}break;case Qp1.State.OP_PON:switch(X){case Qp1.cc.G:case Qp1.cc.g:this.state=Qp1.State.OP_PONG;break;default:throw this.fail($.subarray(Z))}break;case Qp1.State.OP_PONG:switch(X){case Qp1.cc.NL:this.dispatcher.push({kind:Qp1.Kind.PONG}),this.drop=0,this.state=Qp1.State.OP_START;break}break;case Qp1.State.OP_PI:switch(X){case Qp1.cc.N:case Qp1.cc.n:this.state=Qp1.State.OP_PIN;break;default:throw this.fail($.subarray(Z))}break;case Qp1.State.OP_PIN:switch(X){case Qp1.cc.G:case Qp1.cc.g:this.state=Qp1.State.OP_PING;break;default:throw this.fail($.subarray(Z))}break;case Qp1.State.OP_PING:switch(X){case Qp1.cc.NL:this.dispatcher.push({kind:Qp1.Kind.PING}),this.drop=0,this.state=Qp1.State.OP_START;break}break;case Qp1.State.OP_I:switch(X){case Qp1.cc.N:case Qp1.cc.n:this.state=Qp1.State.OP_IN;break;default:throw this.fail($.subarray(Z))}break;case Qp1.State.OP_IN:switch(X){case Qp1.cc.F:case Qp1.cc.f:this.state=Qp1.State.OP_INF;break;default:throw this.fail($.subarray(Z))}break;case Qp1.State.OP_INF:switch(X){case Qp1.cc.O:case Qp1.cc.o:this.state=Qp1.State.OP_INFO;break;default:throw this.fail($.subarray(Z))}break;case Qp1.State.OP_INFO:switch(X){case Qp1.cc.SPACE:case Qp1.cc.TAB:this.state=Qp1.State.OP_INFO_SPC;break;default:throw this.fail($.subarray(Z))}break;case Qp1.State.OP_INFO_SPC:switch(X){case Qp1.cc.SPACE:case Qp1.cc.TAB:continue;default:this.state=Qp1.State.INFO_ARG,this.as=Z}break;case Qp1.State.INFO_ARG:switch(X){case Qp1.cc.CR:this.drop=1;break;case Qp1.cc.NL:{let Q;if(this.argBuf)Q=this.argBuf.bytes(),this.argBuf=void 0;else Q=$.subarray(this.as,Z-this.drop);this.dispatcher.push({kind:Qp1.Kind.INFO,data:Q}),this.drop=0,this.as=Z+1,this.state=Qp1.State.OP_START;break}default:if(this.argBuf)this.argBuf.writeByte(X)}break;default:throw this.fail($.subarray(Z))}}if((this.state===Qp1.State.MSG_ARG||this.state===Qp1.State.MINUS_ERR_ARG||this.state===Qp1.State.INFO_ARG)&&!this.argBuf)this.argBuf=new Ld0.DenoBuffer($.subarray(this.as,Z-this.drop));if(this.state===Qp1.State.MSG_PAYLOAD&&!this.msgBuf){if(!this.argBuf)this.cloneMsgArg();this.msgBuf=new Ld0.DenoBuffer($.subarray(this.as))}}cloneMsgArg(){let $=this.ma.subject.length,Z=this.ma.reply?this.ma.reply.length:0,X=new Uint8Array($+Z);if(X.set(this.ma.subject),this.ma.reply)X.set(this.ma.reply,$);if(this.argBuf=new Ld0.DenoBuffer(X),this.ma.subject=X.subarray(0,$),this.ma.reply)this.ma.reply=X.subarray($)}processMsgArgs($){if(this.hdr>=0)return this.processHeaderMsgArgs($);let Z=[],X=-1;for(let Q=0;Q<$.length;Q++)switch($[Q]){case Qp1.cc.SPACE:case Qp1.cc.TAB:case Qp1.cc.CR:case Qp1.cc.NL:if(X>=0)Z.push($.subarray(X,Q)),X=-1;break;default:if(X<0)X=Q}if(X>=0)Z.push($.subarray(X));switch(Z.length){case 3:this.ma.subject=Z[0],this.ma.sid=this.protoParseInt(Z[1]),this.ma.reply=void 0,this.ma.size=this.protoParseInt(Z[2],$b);break;case 4:this.ma.subject=Z[0],this.ma.sid=this.protoParseInt(Z[1]),this.ma.reply=Z[2],this.ma.size=this.protoParseInt(Z[3],$b);break;default:throw this.fail($,"processMsgArgs Parse Error")}if(this.ma.sid<0)throw this.fail($,"processMsgArgs Bad or Missing Sid Error");if(this.ma.size<0)throw this.fail($,"processMsgArgs Bad or Missing Size Error")}fail($,Z=""){if(!Z)Z=`parse error [${this.state}]`;else Z=`${Z} [${this.state}]`;return Error(`${Z}: ${Dd0.TD.decode($)}`)}processHeaderMsgArgs($){let Z=[],X=-1;for(let Q=0;Q<$.length;Q++)switch($[Q]){case Qp1.cc.SPACE:case Qp1.cc.TAB:case Qp1.cc.CR:case Qp1.cc.NL:if(X>=0)Z.push($.subarray(X,Q)),X=-1;break;default:if(X<0)X=Q}if(X>=0)Z.push($.subarray(X));switch(Z.length){case 4:this.ma.subject=Z[0],this.ma.sid=this.protoParseInt(Z[1]),this.ma.reply=void 0,this.ma.hdr=this.protoParseInt(Z[2],$b),this.ma.size=this.protoParseInt(Z[3],$b);break;case 5:this.ma.subject=Z[0],this.ma.sid=this.protoParseInt(Z[1]),this.ma.reply=Z[2],this.ma.hdr=this.protoParseInt(Z[3],$b),this.ma.size=this.protoParseInt(Z[4],$b);break;default:throw this.fail($,"processHeaderMsgArgs Parse Error")}if(this.ma.sid<0)throw this.fail($,"processHeaderMsgArgs Bad or Missing Sid Error");if(this.ma.hdr<0||this.ma.hdr>this.ma.size)throw this.fail($,"processHeaderMsgArgs Bad or Missing Header Size Error");if(this.ma.size<0)throw this.fail($,"processHeaderMsgArgs Bad or Missing Size Error")}protoParseInt($,Z){if($.length===0||$.length>15)return-1;let X=0;for(let Q=0;Q<$.length;Q++){if($[Q]<Zp1||$[Q]>Gd6)return-1;X=X*10+($[Q]-Zp1)}return Z!==void 0&&X>Z?-1:X}}Qp1.Parser=Xp1;Qp1.State={OP_START:0,OP_PLUS:1,OP_PLUS_O:2,OP_PLUS_OK:3,OP_MINUS:4,OP_MINUS_E:5,OP_MINUS_ER:6,OP_MINUS_ERR:7,OP_MINUS_ERR_SPC:8,MINUS_ERR_ARG:9,OP_M:10,OP_MS:11,OP_MSG:12,OP_MSG_SPC:13,MSG_ARG:14,MSG_PAYLOAD:15,MSG_END:16,OP_H:17,OP_P:18,OP_PI:19,OP_PIN:20,OP_PING:21,OP_PO:22,OP_PON:23,OP_PONG:24,OP_I:25,OP_IN:26,OP_INF:27,OP_INFO:28,OP_INFO_SPC:29,INFO_ARG:30};Qp1.cc={CR:13,E:69,e:101,F:70,f:102,G:71,g:103,H:72,h:104,I:73,i:105,K:75,k:107,M:77,m:109,MINUS:45,N:78,n:110,NL:10,O:79,o:111,P:80,p:112,PLUS:43,R:82,r:114,S:83,s:115,SPACE:32,TAB:9}});var J90=_((Gp1)=>{Object.defineProperty(Gp1,"__esModule",{value:!0});Gp1.MsgHdrsImpl=void 0;Gp1.canonicalMIMEHeaderKey=jd0;Gp1.headers=Wd6;var Yp1=gY(),HJ=zw(),G90=hY();function jd0($){let N=!0,U=Array($.length);for(let F=0;F<$.length;F++){let w=$.charCodeAt(F);if(w===58||w<33||w>126)throw G90.InvalidArgumentError.format("header",`'${$[F]}' is not a valid character in a header name`);if(N&&97<=w&&w<=122)w-=32;else if(!N&&65<=w&&w<=90)w+=32;U[F]=w,N=w==45}return String.fromCharCode(...U)}function Wd6($=0,Z=""){if($===0&&Z!=="")throw G90.InvalidArgumentError.format("code","is required");else if($>0&&Z==="")throw G90.InvalidArgumentError.format("description","is required");return new Zb($,Z)}var zd0="NATS/1.0";class Zb{_code;headers;_description;constructor($=0,Z=""){this._code=$,this._description=Z,this.headers=new Map}[Symbol.iterator](){return this.headers.entries()}size(){return this.headers.size}equals($){if($&&this.headers.size===$.headers.size&&this._code===$._code){for(let[Z,X]of this.headers){let Q=$.values(Z);if(X.length!==Q.length)return!1;let Y=[...X].sort(),G=[...Q].sort();for(let J=0;J<Y.length;J++)if(Y[J]!==G[J])return!1}return!0}return!1}static decode($){let Z=new Zb,Q=Yp1.TD.decode($).split(`\r
|
|
1315
1315
|
`),Y=Q[0];if(Y!==zd0){let G=Y.replace(zd0,"").trim();if(G.length>0){if(Z._code=parseInt(G,10),isNaN(Z._code))Z._code=0;let J=Z._code.toString();G=G.replace(J,""),Z._description=G.trim()}}if(Q.length>=1)Q.slice(1).map((G)=>{if(G){let J=G.indexOf(":");if(J>-1){let K=G.slice(0,J),W=G.slice(J+1).trim();Z.append(K,W)}}});return Z}toString(){if(this.headers.size===0&&this._code===0)return"";let $=zd0;if(this._code>0&&this._description!=="")$+=` ${this._code} ${this._description}`;for(let[Z,X]of this.headers)for(let Q=0;Q<X.length;Q++)$=`${$}\r
|
|
1316
1316
|
${Z}: ${X[Q]}`;return`${$}\r
|
|
@@ -2490,7 +2490,7 @@ ${H}`:H;return{...J,description:N,inputExamples:X?void 0:J.inputExamples}});retu
|
|
|
2490
2490
|
`);let Q=Z.pax;if(Q)for(let Y in Q)X+=o$1(" "+Y+"="+Q[Y]+`
|
|
2491
2491
|
`);return l4.from(X)};Ey4.decodePax=function(Z){let X={};while(Z.length){let Q=0;while(Q<Z.length&&Z[Q]!==32)Q++;let Y=parseInt(l4.toString(Z.subarray(0,Q)),10);if(!Y)return X;let G=l4.toString(Z.subarray(Q+1,Y-1)),J=G.indexOf("=");if(J===-1)return X;X[G.slice(0,J)]=G.slice(J+1),Z=Z.subarray(Y)}return X};Ey4.encode=function(Z){let X=l4.alloc(512),Q=Z.name,Y="";if(Z.typeflag===5&&Q[Q.length-1]!=="/")Q+="/";if(l4.byteLength(Q)!==Q.length)return null;while(l4.byteLength(Q)>100){let G=Q.indexOf("/");if(G===-1)return null;Y+=Y?"/"+Q.slice(0,G):Q.slice(0,G),Q=Q.slice(G+1)}if(l4.byteLength(Q)>100||l4.byteLength(Y)>155)return null;if(Z.linkname&&l4.byteLength(Z.linkname)>100)return null;if(l4.write(X,Q),l4.write(X,xO(Z.mode&4095,6),100),l4.write(X,xO(Z.uid,6),108),l4.write(X,xO(Z.gid,6),116),Ly4(Z.size,X,124),l4.write(X,xO(Z.mtime.getTime()/1000|0,11),136),X[156]=48+By4(Z.type),Z.linkname)l4.write(X,Z.linkname,157);if(l4.copy(l28,X,257),l4.copy(Ky4,X,263),Z.uname)l4.write(X,Z.uname,265);if(Z.gname)l4.write(X,Z.gname,297);if(l4.write(X,xO(Z.devmajor||0,6),329),l4.write(X,xO(Z.devminor||0,6),337),Y)l4.write(X,Y,345);return l4.write(X,xO(m28(X),6),148),X};Ey4.decode=function(Z,X,Q){let Y=Z[156]===0?0:Z[156]-48,G=dh(Z,0,100,X),J=vO(Z,100,8),K=vO(Z,108,8),W=vO(Z,116,8),H=vO(Z,124,12),N=vO(Z,136,12),U=wy4(Y),F=Z[157]===0?null:dh(Z,157,100,X),w=dh(Z,265,32),B=dh(Z,297,32),L=vO(Z,329,8),D=vO(Z,337,8),E=m28(Z);if(E===256)return null;if(E!==vO(Z,148,8))throw Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");if(Ny4(Z)){if(Z[345])G=dh(Z,345,155,X)+"/"+G}else if(Uy4(Z));else if(!Q)throw Error("Invalid tar header: unknown format.");if(Y===0&&G&&G[G.length-1]==="/")Y=5;return{name:G,mode:J,uid:K,gid:W,size:H,mtime:new Date(1000*N),type:U,linkname:F,uname:w,gname:B,devmajor:L,devminor:D,pax:null}};function Ny4($){return l4.equals(l28,$.subarray(257,263))}function Uy4($){return l4.equals(Wy4,$.subarray(257,263))&&l4.equals(Hy4,$.subarray(263,265))}function Fy4($,Z,X){if(typeof $!=="number")return X;if($=~~$,$>=Z)return Z;if($>=0)return $;if($+=Z,$>=0)return $;return 0}function wy4($){switch($){case 0:return"file";case 1:return"link";case 2:return"symlink";case 3:return"character-device";case 4:return"block-device";case 5:return"directory";case 6:return"fifo";case 7:return"contiguous-file";case 72:return"pax-header";case 55:return"pax-global-header";case 27:return"gnu-long-link-path";case 28:case 30:return"gnu-long-path"}return null}function By4($){switch($){case"file":return 0;case"link":return 1;case"symlink":return 2;case"character-device":return 3;case"block-device":return 4;case"directory":return 5;case"fifo":return 6;case"contiguous-file":return 7;case"pax-header":return 72}return 0}function d28($,Z,X,Q){for(;X<Q;X++)if($[X]===Z)return X;return Q}function m28($){let Z=256;for(let X=0;X<148;X++)Z+=$[X];for(let X=156;X<512;X++)Z+=$[X];return Z}function xO($,Z){if($=$.toString(8),$.length>Z)return"7777777777777777777".slice(0,Z)+" ";return"0000000000000000000".slice(0,Z-$.length)+$+" "}function Oy4($,Z,X){Z[X]=128;for(let Q=11;Q>0;Q--)Z[X+Q]=$&255,$=Math.floor($/256)}function Ly4($,Z,X){if($.toString(8).length>11)Oy4($,Z,X);else l4.write(Z,xO($,11),X)}function Dy4($){let Z;if($[0]===128)Z=!0;else if($[0]===255)Z=!1;else return null;let X=[],Q;for(Q=$.length-1;Q>0;Q--){let J=$[Q];if(Z)X.push(J);else X.push(255-J)}let Y=0,G=X.length;for(Q=0;Q<G;Q++)Y+=X[Q]*Math.pow(256,Q);return Z?Y:-1*Y}function vO($,Z,X){if($=$.subarray(Z,Z+X),Z=0,$[Z]&128)return Dy4($);else{while(Z<$.length&&$[Z]===32)Z++;let Q=Fy4(d28($,32,Z,$.length),$.length,$.length);while(Z<Q&&$[Z]===0)Z++;if(Q===Z)return 0;return parseInt(l4.toString($.subarray(Z,Q)),8)}}function dh($,Z,X,Q){return l4.toString($.subarray(Z,d28($,0,Z,Z+X)),Q)}function o$1($){let Z=l4.byteLength($),X=Math.floor(Math.log(Z)/Math.log(10))+1;if(Z+X>=Math.pow(10,X))X++;return Z+X+$}});var s28=_((L1Z,a28)=>{var{Writable:Ry4,Readable:Iy4,getStreamError:i28}=t$1(),qy4=l$1(),n28=lh(),mh=r$1(),My4=n28.alloc(0);class p28{constructor(){this.buffered=0,this.shifted=0,this.queue=new qy4,this._offset=0}push($){this.buffered+=$.byteLength,this.queue.push($)}shiftFirst($){return this._buffered===0?null:this._next($)}shift($){if($>this.buffered)return null;if($===0)return My4;let Z=this._next($);if($===Z.byteLength)return Z;let X=[Z];while(($-=Z.byteLength)>0)Z=this._next($),X.push(Z);return n28.concat(X)}_next($){let Z=this.queue.peek(),X=Z.byteLength-this._offset;if($>=X){let Q=this._offset?Z.subarray(this._offset,Z.byteLength):Z;return this.queue.shift(),this._offset=0,this.buffered-=X,this.shifted+=X,Q}return this.buffered-=$,this.shifted+=$,Z.subarray(this._offset,this._offset+=$)}}class t28 extends Iy4{constructor($,Z,X){super();this.header=Z,this.offset=X,this._parent=$}_read($){if(this.header.size===0)this.push(null);if(this._parent._stream===this)this._parent._update();$(null)}_predestroy(){this._parent.destroy(i28(this))}_detach(){if(this._parent._stream===this)this._parent._stream=null,this._parent._missing=r28(this.header.size),this._parent._update()}_destroy($){this._detach(),$(null)}}class o28 extends Ry4{constructor($){super($);if(!$)$={};this._buffer=new p28,this._offset=0,this._header=null,this._stream=null,this._missing=0,this._longHeader=!1,this._callback=a$1,this._locked=!1,this._finished=!1,this._pax=null,this._paxGlobal=null,this._gnuLongPath=null,this._gnuLongLinkPath=null,this._filenameEncoding=$.filenameEncoding||"utf-8",this._allowUnknownFormat=!!$.allowUnknownFormat,this._unlockBound=this._unlock.bind(this)}_unlock($){if(this._locked=!1,$){this.destroy($),this._continueWrite($);return}this._update()}_consumeHeader(){if(this._locked)return!1;this._offset=this._buffer.shifted;try{this._header=mh.decode(this._buffer.shift(512),this._filenameEncoding,this._allowUnknownFormat)}catch($){return this._continueWrite($),!1}if(!this._header)return!0;switch(this._header.type){case"gnu-long-path":case"gnu-long-link-path":case"pax-global-header":case"pax-header":return this._longHeader=!0,this._missing=this._header.size,!0}if(this._locked=!0,this._applyLongHeaders(),this._header.size===0||this._header.type==="directory")return this.emit("entry",this._header,this._createStream(),this._unlockBound),!0;return this._stream=this._createStream(),this._missing=this._header.size,this.emit("entry",this._header,this._stream,this._unlockBound),!0}_applyLongHeaders(){if(this._gnuLongPath)this._header.name=this._gnuLongPath,this._gnuLongPath=null;if(this._gnuLongLinkPath)this._header.linkname=this._gnuLongLinkPath,this._gnuLongLinkPath=null;if(this._pax){if(this._pax.path)this._header.name=this._pax.path;if(this._pax.linkpath)this._header.linkname=this._pax.linkpath;if(this._pax.size)this._header.size=parseInt(this._pax.size,10);this._header.pax=this._pax,this._pax=null}}_decodeLongHeader($){switch(this._header.type){case"gnu-long-path":this._gnuLongPath=mh.decodeLongPath($,this._filenameEncoding);break;case"gnu-long-link-path":this._gnuLongLinkPath=mh.decodeLongPath($,this._filenameEncoding);break;case"pax-global-header":this._paxGlobal=mh.decodePax($);break;case"pax-header":this._pax=this._paxGlobal===null?mh.decodePax($):Object.assign({},this._paxGlobal,mh.decodePax($));break}}_consumeLongHeader(){this._longHeader=!1,this._missing=r28(this._header.size);let $=this._buffer.shift(this._header.size);try{this._decodeLongHeader($)}catch(Z){return this._continueWrite(Z),!1}return!0}_consumeStream(){let $=this._buffer.shiftFirst(this._missing);if($===null)return!1;this._missing-=$.byteLength;let Z=this._stream.push($);if(this._missing===0){if(this._stream.push(null),Z)this._stream._detach();return Z&&this._locked===!1}return Z}_createStream(){return new t28(this,this._header,this._offset)}_update(){while(this._buffer.buffered>0&&!this.destroying){if(this._missing>0){if(this._stream!==null){if(this._consumeStream()===!1)return;continue}if(this._longHeader===!0){if(this._missing>this._buffer.buffered)break;if(this._consumeLongHeader()===!1)return!1;continue}let $=this._buffer.shiftFirst(this._missing);if($!==null)this._missing-=$.byteLength;continue}if(this._buffer.buffered<512)break;if(this._stream!==null||this._consumeHeader()===!1)return}this._continueWrite(null)}_continueWrite($){let Z=this._callback;this._callback=a$1,Z($)}_write($,Z){this._callback=Z,this._buffer.push($),this._update()}_final($){this._finished=this._missing===0&&this._buffer.buffered===0,$(this._finished?null:Error("Unexpected end of data"))}_predestroy(){this._continueWrite(null)}_destroy($){if(this._stream)this._stream.destroy(i28(this));$(null)}[Symbol.asyncIterator](){let $=null,Z=null,X=null,Q=null,Y=null,G=this;return this.on("entry",W),this.on("error",(U)=>{$=U}),this.on("close",H),{[Symbol.asyncIterator](){return this},next(){return new Promise(K)},return(){return N(null)},throw(U){return N(U)}};function J(U){if(!Y)return;let F=Y;Y=null,F(U)}function K(U,F){if($)return F($);if(Q){U({value:Q,done:!1}),Q=null;return}if(Z=U,X=F,J(null),G._finished&&Z)Z({value:void 0,done:!0}),Z=X=null}function W(U,F,w){if(Y=w,F.on("error",a$1),Z)Z({value:F,done:!1}),Z=X=null;else Q=F}function H(){if(J($),!Z)return;if($)X($);else Z({value:void 0,done:!0});Z=X=null}function N(U){return G.destroy(U),J(U),new Promise((F,w)=>{if(G.destroyed)return F({value:void 0,done:!0});G.once("close",function(){if(U)w(U);else F({value:void 0,done:!0})})})}}}a28.exports=function(Z){return new o28(Z)};function a$1(){}function r28($){return $&=511,$&&512-$}});var $q8=_((D1Z,s$1)=>{var e28={S_IFMT:61440,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960};try{s$1.exports=U0("fs").constants||e28}catch{s$1.exports=e28}});var Kq8=_((E1Z,Jq8)=>{var{Readable:ky4,Writable:Vy4,getStreamError:Zq8}=t$1(),f_=lh(),ih=$q8(),wj0=r$1(),Xq8=f_.alloc(1024);class Qq8 extends Vy4{constructor($,Z,X){super({mapWritable:Cy4,eagerOpen:!0});if(this.written=0,this.header=Z,this._callback=X,this._linkname=null,this._isLinkname=Z.type==="symlink"&&!Z.linkname,this._isVoid=Z.type!=="file"&&Z.type!=="contiguous-file",this._finished=!1,this._pack=$,this._openCallback=null,this._pack._stream===null)this._pack._stream=this;else this._pack._pending.push(this)}_open($){if(this._openCallback=$,this._pack._stream===this)this._continueOpen()}_continuePack($){if(this._callback===null)return;let Z=this._callback;this._callback=null,Z($)}_continueOpen(){if(this._pack._stream===null)this._pack._stream=this;let $=this._openCallback;if(this._openCallback=null,$===null)return;if(this._pack.destroying)return $(Error("pack stream destroyed"));if(this._pack._finalized)return $(Error("pack stream is already finalized"));if(this._pack._stream=this,!this._isLinkname)this._pack._encode(this.header);if(this._isVoid)this._finish(),this._continuePack(null);$(null)}_write($,Z){if(this._isLinkname)return this._linkname=this._linkname?f_.concat([this._linkname,$]):$,Z(null);if(this._isVoid){if($.byteLength>0)return Z(Error("No body allowed for this entry"));return Z()}if(this.written+=$.byteLength,this._pack.push($))return Z();this._pack._drain=Z}_finish(){if(this._finished)return;if(this._finished=!0,this._isLinkname)this.header.linkname=this._linkname?f_.toString(this._linkname,"utf-8"):"",this._pack._encode(this.header);Gq8(this._pack,this.header.size),this._pack._done(this)}_final($){if(this.written!==this.header.size)return $(Error("Size mismatch"));this._finish(),$(null)}_getError(){return Zq8(this)||Error("tar entry destroyed")}_predestroy(){this._pack.destroy(this._getError())}_destroy($){this._pack._done(this),this._continuePack(this._finished?null:this._getError()),$()}}class Yq8 extends ky4{constructor($){super($);this._drain=e$1,this._finalized=!1,this._finalizing=!1,this._pending=[],this._stream=null}entry($,Z,X){if(this._finalized||this.destroying)throw Error("already finalized or destroyed");if(typeof Z==="function")X=Z,Z=null;if(!X)X=e$1;if(!$.size||$.type==="symlink")$.size=0;if(!$.type)$.type=Sy4($.mode);if(!$.mode)$.mode=$.type==="directory"?493:420;if(!$.uid)$.uid=0;if(!$.gid)$.gid=0;if(!$.mtime)$.mtime=new Date;if(typeof Z==="string")Z=f_.from(Z);let Q=new Qq8(this,$,X);if(f_.isBuffer(Z))return $.size=Z.byteLength,Q.write(Z),Q.end(),Q;if(Q._isVoid)return Q;return Q}finalize(){if(this._stream||this._pending.length>0){this._finalizing=!0;return}if(this._finalized)return;this._finalized=!0,this.push(Xq8),this.push(null)}_done($){if($!==this._stream)return;if(this._stream=null,this._finalizing)this.finalize();if(this._pending.length)this._pending.shift()._continueOpen()}_encode($){if(!$.pax){let Z=wj0.encode($);if(Z){this.push(Z);return}}this._encodePax($)}_encodePax($){let Z=wj0.encodePax({name:$.name,linkname:$.linkname,pax:$.pax}),X={name:"PaxHeader",mode:$.mode,uid:$.uid,gid:$.gid,size:Z.byteLength,mtime:$.mtime,type:"pax-header",linkname:$.linkname&&"PaxHeader",uname:$.uname,gname:$.gname,devmajor:$.devmajor,devminor:$.devminor};this.push(wj0.encode(X)),this.push(Z),Gq8(this,Z.byteLength),X.size=$.size,X.type=$.type,this.push(wj0.encode(X))}_doDrain(){let $=this._drain;this._drain=e$1,$()}_predestroy(){let $=Zq8(this);if(this._stream)this._stream.destroy($);while(this._pending.length){let Z=this._pending.shift();Z.destroy($),Z._continueOpen()}this._doDrain()}_read($){this._doDrain(),$()}}Jq8.exports=function(Z){return new Yq8(Z)};function Sy4($){switch($&ih.S_IFMT){case ih.S_IFBLK:return"block-device";case ih.S_IFCHR:return"character-device";case ih.S_IFDIR:return"directory";case ih.S_IFIFO:return"fifo";case ih.S_IFLNK:return"symlink"}return"file"}function e$1(){}function Gq8($,Z){if(Z&=511,Z)$.push(Xq8.subarray(0,512-Z))}function Cy4($){return f_.isBuffer($)?$:f_.from($)}});var Wq8=_((_y4)=>{_y4.extract=s28();_y4.pack=Kq8()});var Uq8=_((j1Z,Nq8)=>{Nq8.exports=Hq8;function Hq8($,Z){if($&&Z)return Hq8($)(Z);if(typeof $!=="function")throw TypeError("need wrapper function");return Object.keys($).forEach(function(Q){X[Q]=$[Q]}),X;function X(){var Q=Array(arguments.length);for(var Y=0;Y<Q.length;Y++)Q[Y]=arguments[Y];var G=$.apply(this,Q),J=Q[Q.length-1];if(typeof G==="function"&&G!==J)Object.keys(J).forEach(function(K){G[K]=J[K]});return G}}});var Z51=_((P1Z,$51)=>{var Fq8=Uq8();$51.exports=Fq8(Bj0);$51.exports.strict=Fq8(wq8);Bj0.proto=Bj0(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return Bj0(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return wq8(this)},configurable:!0})});function Bj0($){var Z=function(){if(Z.called)return Z.value;return Z.called=!0,Z.value=$.apply(this,arguments)};return Z.called=!1,Z}function wq8($){var Z=function(){if(Z.called)throw Error(Z.onceError);return Z.called=!0,Z.value=$.apply(this,arguments)},X=$.name||"Function wrapped with `once`";return Z.onceError=X+" shouldn't be called more than once",Z.called=!1,Z}});var Lq8=_((A1Z,Oq8)=>{var fy4=Z51(),by4=function(){},yy4=global.Bare?queueMicrotask:process.nextTick.bind(process),gy4=function($){return $.setHeader&&typeof $.abort==="function"},hy4=function($){return $.stdio&&Array.isArray($.stdio)&&$.stdio.length===3},Bq8=function($,Z,X){if(typeof Z==="function")return Bq8($,null,Z);if(!Z)Z={};X=fy4(X||by4);var{_writableState:Q,_readableState:Y}=$,G=Z.readable||Z.readable!==!1&&$.readable,J=Z.writable||Z.writable!==!1&&$.writable,K=!1,W=function(){if(!$.writable)H()},H=function(){if(J=!1,!G)X.call($)},N=function(){if(G=!1,!J)X.call($)},U=function(D){X.call($,D?Error("exited with error code: "+D):null)},F=function(D){X.call($,D)},w=function(){yy4(B)},B=function(){if(K)return;if(G&&!(Y&&(Y.ended&&!Y.destroyed)))return X.call($,Error("premature close"));if(J&&!(Q&&(Q.ended&&!Q.destroyed)))return X.call($,Error("premature close"))},L=function(){$.req.on("finish",H)};if(gy4($))if($.on("complete",H),$.on("abort",w),$.req)L();else $.on("request",L);else if(J&&!Q)$.on("end",W),$.on("close",W);if(hy4($))$.on("exit",U);if($.on("end",N),$.on("finish",H),Z.error!==!1)$.on("error",F);return $.on("close",w),function(){if(K=!0,$.removeListener("complete",H),$.removeListener("abort",w),$.removeListener("request",L),$.req)$.req.removeListener("finish",H);$.removeListener("end",W),$.removeListener("close",W),$.removeListener("finish",H),$.removeListener("exit",U),$.removeListener("end",N),$.removeListener("error",F),$.removeListener("close",w)}};Oq8.exports=Bq8});var zq8=_((T1Z,Eq8)=>{var uy4=Z51(),cy4=Lq8(),Oj0;try{Oj0=U0("fs")}catch($){}var er=function(){},ly4=typeof process>"u"?!1:/^v?\.0/.test(process.version),Lj0=function($){return typeof $==="function"},dy4=function($){if(!ly4)return!1;if(!Oj0)return!1;return($ instanceof(Oj0.ReadStream||er)||$ instanceof(Oj0.WriteStream||er))&&Lj0($.close)},my4=function($){return $.setHeader&&Lj0($.abort)},iy4=function($,Z,X,Q){Q=uy4(Q);var Y=!1;$.on("close",function(){Y=!0}),cy4($,{readable:Z,writable:X},function(J){if(J)return Q(J);Y=!0,Q()});var G=!1;return function(J){if(Y)return;if(G)return;if(G=!0,dy4($))return $.close(er);if(my4($))return $.abort();if(Lj0($.destroy))return $.destroy();Q(J||Error("stream was destroyed"))}},Dq8=function($){$()},ny4=function($,Z){return $.pipe(Z)},py4=function(){var $=Array.prototype.slice.call(arguments),Z=Lj0($[$.length-1]||er)&&$.pop()||er;if(Array.isArray($[0]))$=$[0];if($.length<2)throw Error("pump requires two streams per minimum");var X,Q=$.map(function(Y,G){var J=G<$.length-1,K=G>0;return iy4(Y,J,K,function(W){if(!X)X=W;if(W)Q.forEach(Dq8);if(J)return;Q.forEach(Dq8),Z(X)})});return $.reduce(ny4)};Eq8.exports=py4});var kq8=_((ay4)=>{var jq8=Wq8(),Pq8=zq8(),Aq8=U0("fs"),w9=U0("path"),$a=(global.Bare?global.Bare.platform:process.platform)==="win32";ay4.pack=function(Z,X){if(!Z)Z=".";if(!X)X={};let Q=X.fs||Aq8,Y=X.ignore||X.filter||Za,G=X.mapStream||qq8,J=ry4(Q,X.dereference?Q.stat:Q.lstat,Z,Y,X.entries,X.sort),K=X.strict!==!1,W=typeof X.umask==="number"?~X.umask:~Tq8(),H=X.pack||jq8.pack(),N=X.finish||Za,U=X.map||Za,F=typeof X.dmode==="number"?X.dmode:0,w=typeof X.fmode==="number"?X.fmode:0;if(X.strip)U=Mq8(U,X.strip);if(X.readable)F|=parseInt(555,8),w|=parseInt(444,8);if(X.writable)F|=parseInt(333,8),w|=parseInt(222,8);D();function B(E,z){Q.readlink(w9.join(Z,E),function(j,A){if(j)return H.destroy(j);z.linkname=X51(A),H.entry(z,D)})}function L(E,z,j){if(H.destroyed)return;if(E)return H.destroy(E);if(!z){if(X.finalize!==!1)H.finalize();return N(H)}if(j.isSocket())return D();let A={name:X51(z),mode:(j.mode|(j.isDirectory()?F:w))&W,mtime:j.mtime,size:j.size,type:"file",uid:j.uid,gid:j.gid};if(j.isDirectory())return A.size=0,A.type="directory",A=U(A)||A,H.entry(A,D);if(j.isSymbolicLink())return A.size=0,A.type="symlink",A=U(A)||A,B(z,A);if(A=U(A)||A,!j.isFile()){if(K)return H.destroy(Error("unsupported type for "+z));return D()}let P=H.entry(A,D),q=G(Q.createReadStream(w9.join(Z,z),{start:0,end:A.size>0?A.size-1:A.size}),A);q.on("error",function(k){P.destroy(k)}),Pq8(q,P)}function D(E){if(E)return H.destroy(E);J(L)}return H};function ty4($){return $.length?$[$.length-1]:null}function oy4(){return!global.Bare&&process.getuid?process.getuid():-1}function Tq8(){return!global.Bare&&process.umask?process.umask():0}ay4.extract=function(Z,X){if(!Z)Z=".";if(!X)X={};Z=w9.resolve(Z);let Q=X.fs||Aq8,Y=X.ignore||X.filter||Za,G=X.mapStream||qq8,J=X.chown!==!1&&!$a&&oy4()===0,K=X.extract||jq8.extract(),W=[],H=new Date,N=typeof X.umask==="number"?~X.umask:~Tq8(),U=X.strict!==!1,F=X.validateSymlinks!==!1,w=X.map||Za,B=typeof X.dmode==="number"?X.dmode:0,L=typeof X.fmode==="number"?X.fmode:0;if(X.strip)w=Mq8(w,X.strip);if(X.readable)B|=parseInt(555,8),L|=parseInt(444,8);if(X.writable)B|=parseInt(333,8),L|=parseInt(222,8);if(K.on("entry",D),X.finish)K.on("finish",X.finish);return K;function D(P,q,k){P=w(P)||P,P.name=X51(P.name);let M=w9.join(Z,w9.join("/",P.name));if(Y(M,P))return q.resume(),k();let C=w9.join(M,".")===w9.join(Z,".")?Z:w9.dirname(M);Iq8(Q,C,w9.join(Z,"."),function(Z0,D0){if(Z0)return k(Z0);if(!D0)return k(Error(C+" is not a valid path"));if(P.type==="directory")return W.push([M,P.mtime]),A(M,{fs:Q,own:J,uid:P.uid,gid:P.gid,mode:P.mode},d);A(C,{fs:Q,own:J,uid:P.uid,gid:P.gid,mode:493},function(R0){if(R0)return k(R0);switch(P.type){case"file":return y();case"link":return b();case"symlink":return v()}if(U)return k(Error("unsupported type for "+M+" ("+P.type+")"));q.resume(),k()})});function d(Z0){if(Z0)return k(Z0);z(M,P,function(D0){if(D0)return k(D0);if($a)return k();j(M,P,k)})}function v(){if($a)return k();Q.unlink(M,function(){let Z0=w9.resolve(w9.dirname(M),P.linkname);if(!t(Z0)&&F)return k(Error(M+" is not a valid symlink"));Rq8(Q,Z0,w9.join(Z,"."),function(D0,R0){if(D0)return k(D0);if(!R0&&F)return k(Error(M+" is not a valid symlink"));Q.symlink(P.linkname,M,d)})})}function b(){if($a)return k();Q.unlink(M,function(){let Z0=w9.join(Z,w9.join("/",P.linkname));Q.realpath(Z0,function(D0,R0){if(D0||!t(R0))return k(Error(M+" is not a valid hardlink"));Q.link(R0,M,function($0){if($0&&$0.code==="EPERM"&&X.hardlinkAsFilesFallback)return q=Q.createReadStream(R0),y();d($0)})})})}function t(Z0){return Z0===Z||Z0.startsWith(Z+w9.sep)}function y(){let Z0=Q.createWriteStream(M),D0=G(q,P);Z0.on("error",function(R0){D0.destroy(R0)}),Pq8(D0,Z0,function(R0){if(R0)return k(R0);Z0.on("close",d)})}}function E(P,q){let k;while((k=ty4(W))&&P.slice(0,k[0].length)!==k[0])W.pop();if(!k)return q();Q.utimes(k[0],H,k[1],q)}function z(P,q,k){if(X.utimes===!1)return k();if(q.type==="directory")return Q.utimes(P,H,q.mtime,k);if(q.type==="symlink")return E(P,k);Q.utimes(P,H,q.mtime,function(M){if(M)return k(M);E(P,k)})}function j(P,q,k){let M=q.type==="symlink",C=M?Q.lchmod:Q.chmod,d=M?Q.lchown:Q.chown;if(!C)return k();let v=(q.mode|(q.type==="directory"?B:L))&N;if(d&&J)d.call(Q,P,q.uid,q.gid,b);else b(null);function b(t){if(t)return k(t);if(!C)return k();C.call(Q,P,v,k)}}function A(P,q,k){Q.stat(P,function(M){if(!M)return k(null);if(M.code!=="ENOENT")return k(M);Q.mkdir(P,{mode:q.mode,recursive:!0},function(C,d){if(C)return k(C);j(P,q,k)})})}};function Rq8($,Z,X,Q){if(Z===X)return Q(null,!0);if(!Z.startsWith(X+w9.sep))return Q(null,!1);$.lstat(Z,function(Y,G){if(Y&&Y.code!=="ENOENT"&&Y.code!=="EPERM")return Q(Y);if(Y||!G.isSymbolicLink())return Rq8($,w9.join(Z,".."),X,Q);Q(null,!1)})}function Iq8($,Z,X,Q){if(Z===X)return Q(null,!0);$.lstat(Z,function(Y,G){if(Y&&Y.code!=="ENOENT"&&Y.code!=="EPERM")return Q(Y);if(Y||G.isDirectory())return Iq8($,w9.join(Z,".."),X,Q);Q(null,!1)})}function Za(){}function qq8($){return $}function X51($){return $a?$.replace(/\\/g,"/").replace(/[:?<>|]/g,"_"):$}function ry4($,Z,X,Q,Y,G){if(!Y)Y=["."];let J=Y.slice(0);return function(W){if(!J.length)return W(null);let H=J.shift(),N=w9.join(X,H);Z.call($,N,function(U,F){if(U)return W(Y.indexOf(H)===-1&&U.code==="ENOENT"?null:U);if(!F.isDirectory())return W(null,H,F);$.readdir(N,function(w,B){if(w)return W(w);if(G)B.sort();for(let L=0;L<B.length;L++)if(!Q(w9.join(X,H,B[L])))J.push(w9.join(H,B[L]));W(null,H,F)})})}}function Mq8($,Z){return function(X){X.name=X.name.split("/").slice(Z).join("/");let Q=X.linkname;if(Q&&(X.type==="link"||w9.isAbsolute(Q)))X.linkname=Q.split("/").slice(Z).join("/");return $(X)}}});var $g4,Zg4;var Vq8=O(()=>{u$1();$g4=V(L28(),1),Zg4=V(kq8(),1)});var Dj0=()=>{};var Sq8=O(()=>{Cz0()});var Cq8=O(()=>{Yj0();Qj0();Dj0()});var _q8=()=>{};var vq8=()=>{};var Q51=O(()=>{aI8();g$1();Yj0();X28();b$1();u$1();Q28();Y28();G28();J28();y$1();K28();Vq8();Dj0();Sq8();Cq8();_q8();vq8();Dj0()});var v9,p9,b_,Xa;var Qa=O(()=>{v9={CLAIM_API_GROUP:"extensions.agents.x-k8s.io",CLAIM_API_VERSION:"v1alpha1",CLAIM_PLURAL:"sandboxclaims",SANDBOX_API_GROUP:"agents.x-k8s.io",SANDBOX_API_VERSION:"v1alpha1",SANDBOX_PLURAL:"sandboxes",POD_NAME_ANNOTATION:"agents.x-k8s.io/pod-name"};p9=class p9 extends Error{cause;constructor($,Z){super($);if(this.name="SandboxError",this.cause=Z,Z instanceof Error&&Z.stack)this.stack=`${this.stack}
|
|
2492
2492
|
Caused by: ${Z.stack}`}};b_=class b_ extends p9{constructor($,Z){super($,Z);this.name="SandboxTimeoutError"}};Xa=class Xa extends p9{constructor($,Z){super($,Z);this.name="SandboxAlreadyExistsError"}}});async function Xg4($){let Z=$.getCurrentCluster();if(!Z)throw new p9("No active cluster in kubeconfig");let X={};await $.applyToHTTPSOptions(X);let Q={},Y=X.headers??{};for(let[G,J]of Object.entries(Y))if(Array.isArray(J))Q[G]=J.join(", ");else if(J!==void 0)Q[G]=String(J);if(typeof X.auth==="string"&&!Q.Authorization)Q.Authorization=`Basic ${Buffer.from(X.auth).toString("base64")}`;return{server:Z.server.replace(/\/+$/,""),headers:Q,tls:{cert:Y51(X.cert),key:Y51(X.key),ca:Y51(X.ca),rejectUnauthorized:Z.skipTLSVerify?!1:void 0}}}function Y51($){if($==null)return;if(typeof $==="string")return $;if(Buffer.isBuffer($))return $.toString("utf8");return String($)}async function FK($,Z){let X=await Xg4($),Q={...X.headers,...Z.headers};if(Z.method==="PATCH")Q["content-type"]=Z.patchType==="apply"?"application/apply-patch+yaml":Z.patchType==="strategic-merge"?"application/strategic-merge-patch+json":"application/merge-patch+json";else if(Z.body!==void 0&&!("content-type"in Q))Q["content-type"]="application/json";let Y={method:Z.method,headers:Q,body:Z.body===void 0?void 0:JSON.stringify(Z.body),signal:Z.signal,tls:X.tls,...Z.stream?{timeout:!1}:{}};return fetch(`${X.server}${Z.path}`,Y)}async function G51($){try{return await $.json()}catch{return null}}async function Ej0($,Z){if($.ok)return;let X=await G51($),Q=X?.message??`${Z} failed: ${$.status} ${$.statusText}`;throw new xq8($.status,X,Q)}async function nh($,Z,X,Q,Y="none"){try{let G=await FK($,Z);if(G.status===404)return null;if(await Ej0(G,X),Y==="json")return await G.json();return null}catch(G){throw new p9(Q,G)}}async function Ya($,Z,X){let Q=`${J51}/${encodeURIComponent(Z)}/${v9.CLAIM_PLURAL}`,Y;try{Y=await FK($,{method:"POST",path:Q,body:X})}catch(H){let N=H instanceof Error?H.message:String(H);throw console.warn(`[agent-sandbox/client] createSandboxClaim ${X.metadata.name} transport error: ${N}`),new p9(`Failed to create SandboxClaim: ${X.metadata.name} (transport error: ${N})`,H)}if(Y.ok)return;let G=await G51(Y),J=G?.reason?` ${G.reason}`:"",K=G?.message??Y.statusText,W=`Failed to create SandboxClaim: ${X.metadata.name} (${Y.status}${J}: ${K})`;if(console.warn(`[agent-sandbox/client] createSandboxClaim ${X.metadata.name} rejected: status=${Y.status} reason=${G?.reason??"<none>"} message=${K}`),Y.status===409)throw new Xa(W);throw new p9(W)}async function zj0($,Z,X,Q=60000){let Y=Date.now()+Q,G=500,J;while(!0){let K=await wK($,Z,X).catch(()=>{return});if(!K)return;if(J=K,Date.now()>=Y){let W=J.metadata?.finalizers??[],H=J.metadata?.deletionTimestamp??"<unknown>";throw new b_(`SandboxClaim ${X} still terminating after ${Q}ms (deletionTimestamp=${H}, finalizers=[${W.join(", ")}])`)}await _8(500)}}function K51($,Z){return`${J51}/${encodeURIComponent($)}/${v9.CLAIM_PLURAL}/${encodeURIComponent(Z)}`}async function jj0($,Z,X,Q){await nh($,{method:"PATCH",path:K51(Z,X),patchType:"merge",body:{spec:{lifecycle:{shutdownPolicy:"Delete",shutdownTime:Q}}}},"patchSandboxClaimShutdown",`Failed to patch SandboxClaim shutdownTime: ${X}`)}async function fO($,Z,X){await nh($,{method:"DELETE",path:K51(Z,X)},"deleteSandboxClaim",`Failed to delete SandboxClaim: ${X}`)}async function wK($,Z,X){return await nh($,{method:"GET",path:K51(Z,X)},"getSandboxClaim",`Failed to get SandboxClaim: ${X}`,"json")??void 0}async function fq8($,Z,X,Q=60){let Y=Date.now()+Q*1000,G=200;while(Date.now()<Y){let K=(await wK($,Z,X).catch(()=>{return}))?.status?.sandbox?.name;if(K)return K;await _8(200)}throw new b_(`SandboxClaim ${X} did not record an adopted Sandbox (status.sandbox.name) within ${Q}s`)}async function bq8($,Z,X){let Y=(await nh($,{method:"GET",path:`${J51}/${encodeURIComponent(Z)}/sandboxwarmpools/${encodeURIComponent(X)}`},"getSandboxWarmPool",`Failed to get SandboxWarmPool: ${X}`,"json"))?.status?.selector;if(!Y)return null;let G=await FK($,{method:"GET",path:`/api/v1/namespaces/${encodeURIComponent(Z)}/pods?labelSelector=${encodeURIComponent(Y)}`});return await Ej0(G,"listWarmPoolPods"),((await G.json()).items??[]).filter((K)=>K.status?.phase==="Running").flatMap((K)=>K.metadata?.name&&K.metadata.uid?[{name:K.metadata.name,uid:K.metadata.uid,labels:K.metadata.labels??{}}]:[])}async function yq8($,Z,X,Q){try{let Y=await FK($,{method:"GET",path:`/api/v1/namespaces/${encodeURIComponent(Z)}/pods/${encodeURIComponent(X)}`});if(!Y.ok)return!1;return!(await Y.json()).metadata?.labels?.[Q]}catch{return!1}}function W51($,Z){return`${Qg4}/${encodeURIComponent($)}/${uq8}/${encodeURIComponent(Z)}`}async function Pj0($,Z,X){let Q=new URLSearchParams({fieldManager:lq8,force:"true"}),Y=`${W51(Z,X.metadata.name)}?${Q}`;try{let G=await FK($,{method:"PATCH",path:Y,patchType:"apply",body:X});await Ej0(G,"applyHttpRoute")}catch(G){throw new p9(`Failed to apply HTTPRoute: ${X.metadata.name}`,G)}}async function Aj0($,Z,X){await nh($,{method:"DELETE",path:W51(Z,X)},"deleteHttpRoute",`Failed to delete HTTPRoute: ${X}`)}async function cq8($,Z,X){return await nh($,{method:"GET",path:W51(Z,X)},"getHttpRoute",`Failed to get HTTPRoute: ${X}`,"json")??void 0}async function dq8($,Z,X,Q){let Y={apiVersion:"v1",kind:"Service",metadata:{name:X},spec:{ports:[{name:Q.name,port:Q.port,targetPort:Q.targetPort,protocol:Q.protocol??"TCP"}]}},G=new URLSearchParams({fieldManager:lq8,force:"true"}),J=`/api/v1/namespaces/${encodeURIComponent(Z)}/services/${encodeURIComponent(X)}?${G}`;try{let K=await FK($,{method:"PATCH",path:J,patchType:"apply",body:Y});await Ej0(K,"ensureServicePort")}catch(K){throw new p9(`Failed to apply Service ports: ${X}`,K)}}function Tj0($,Z,X,Q=180){let Y=`/apis/${v9.SANDBOX_API_GROUP}/${v9.SANDBOX_API_VERSION}/namespaces/${encodeURIComponent(Z)}/${v9.SANDBOX_PLURAL}?watch=true&fieldSelector=${encodeURIComponent(`metadata.name=${X}`)}`,{resolve:G,reject:J,promise:K}=Promise.withResolvers(),W=new AbortController,H=!1,N=setTimeout(()=>{if(H)return;H=!0,W.abort(),J(new b_(`Sandbox did not become ready within ${Q} seconds`))},Q*1000),U=(F)=>{if(H)return;H=!0,clearTimeout(N),W.abort(),F()};return(async()=>{let F;try{F=await FK($,{method:"GET",path:Y,signal:W.signal,headers:{accept:"application/json"},stream:!0})}catch(w){U(()=>J(new p9("Failed to start watch for sandbox readiness",w)));return}if(!F.ok||!F.body){let w=await G51(F).catch(()=>null);U(()=>J(new p9(`Watch handshake failed (${F.status}): ${w?.message??F.statusText}`)));return}try{for await(let w of H51(F.body)){if(H)return;if(w.type==="ERROR"){let z=w.object;U(()=>J(new p9(`Watch stream error while waiting for sandbox: ${z.message??"unknown"}`)));return}if(w.type!=="ADDED"&&w.type!=="MODIFIED")continue;let B=w.object;if(!B.status?.conditions?.find((z)=>z.type==="Ready"&&z.status==="True"))continue;let D=B.metadata?.name;if(!D){U(()=>J(new p9("Sandbox metadata or name is missing")));return}let E=B.metadata?.annotations?.[v9.POD_NAME_ANNOTATION]??D;U(()=>G({sandboxName:D,podName:E}));return}U(()=>J(new p9("Watch stream closed before sandbox became ready")))}catch(w){if(H)return;if(w instanceof Error&&(w.name==="AbortError"||W.signal.aborted))return;U(()=>J(new p9("Watch stream error while waiting for sandbox",w)))}})(),K}async function*H51($){let Z=$.getReader(),X=new TextDecoder,Q="";try{while(!0){let{value:G,done:J}=await Z.read();if(J)break;Q+=X.decode(G,{stream:!0});let K;while((K=Q.indexOf(`
|
|
2493
|
-
`))>=0){let W=Q.slice(0,K).trim();if(Q=Q.slice(K+1),!W)continue;yield JSON.parse(W)}}let Y=Q.trim();if(Y)yield JSON.parse(Y)}finally{Z.releaseLock()}}var xq8,J51,gq8="gateway.networking.k8s.io",hq8="v1",uq8="httproutes",Qg4,Ga,lq8="mesh-sandbox-runner";var Ja=O(()=>{H$();Qa();xq8=class xq8 extends Error{status;body;constructor($,Z,X){super(X);this.status=$;this.body=Z;this.name="KubeHttpError"}};J51=`/apis/${v9.CLAIM_API_GROUP}/${v9.CLAIM_API_VERSION}/namespaces`;Qg4=`/apis/${gq8}/${hq8}/namespaces`;Ga={API_GROUP:gq8,API_VERSION:hq8,PLURAL:uq8}});function Gg4($){return($.items??[]).some((Z)=>{if(Z.status?.phase!=="Pending")return!1;return(Z.status?.conditions??[]).some((X)=>X.type==="PodScheduled"&&X.status==="False"&&X.reason==="Unschedulable")})}function iq8($,Z){let X=0,Q=!0,Y=null,G=async()=>{try{let J=await FK($,{method:"GET",path:`/api/v1/namespaces/${encodeURIComponent(Z)}/pods?fieldSelector=status.phase%3DPending`});if(!J.ok)return mq8;let K=await J.json();return!Gg4(K)}catch{return mq8}};return async()=>{if(Date.now()-X<Yg4)return Q;return Y??=G().finally(()=>{Y=null}),Q=await Y,X=Date.now(),Q}}var Yg4=3000,mq8=!0;var nq8=O(()=>{Ja()});var N51=O(()=>{H$();G41()});async function Ij0($){try{let Z=await fetch(`${$}/health`,{signal:AbortSignal.timeout(Jg4)});if(!Z.ok)return null;let X=await Z.json();if(typeof X==="object"&&X!==null&&typeof X.bootId==="string"&&typeof X.ready==="boolean"&&X.setup&&typeof X.setup.running==="boolean"&&typeof X.setup.done==="boolean")return X;return null}catch{return null}}async function F51($){for(let Z=0;Z<pq8;Z++){if(await Ij0($)!==null)return;let X=(Math.random()*2-1)*Kg4;await _8(tq8+X)}throw Error(`sandbox daemon at ${$} did not respond on /health within ${pq8*tq8/1000}s`)}async function y_($,Z,X,Q,Y){return Wg4($,Z,"POST",X,Q,Y)}async function Wg4($,Z,X,Q,Y,G){let J={...Q};if(Y&&Y.rotateToken!==void 0)J.auth=Y;let K=await fetch(`${$}/_sandbox/config`,{method:X,headers:{"Content-Type":"application/json",Authorization:`Bearer ${Z}`},body:JSON.stringify(J),signal:AbortSignal.timeout(G?.timeoutMs??U51)}),W=await K.text();if(!K.ok)throw new Rj0(K.status,W);return JSON.parse(W)}async function oq8($,Z,X){let Q=await fetch(`${$}/_sandbox/setup/${X}`,{method:"POST",headers:{Authorization:`Bearer ${Z}`},signal:AbortSignal.timeout(U51)});if(!Q.ok)throw Error(`sandbox daemon /_sandbox/setup/${X} returned ${Q.status}: ${await Q.text()}`)}async function rq8($,Z,X){let Q=await fetch(`${$}/_sandbox/orgfs-config`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Z}`},body:X,signal:AbortSignal.timeout(U51)}),Y=await Q.text();if(!Q.ok)throw Error(`sandbox daemon /_sandbox/orgfs-config returned ${Q.status}: ${Y}`);return JSON.parse(Y)}async function Ka($,Z,X,Q){let Y=new Headers(Q.headers);for(let K of Hg4)Y.delete(K);Y.set("authorization",`Bearer ${Z}`);let G=Q.method!=="GET"&&Q.method!=="HEAD",J=`${$}${X.startsWith("/")?X:`/${X}`}`;return fetch(J,{method:Q.method,headers:Y,body:G?Q.body:void 0,redirect:"manual",signal:Q.signal,duplex:G?"half":void 0})}var Rj0,Jg4=500,U51=30000,pq8=25,tq8=200,Kg4=50,Hg4;var aq8=O(()=>{N51();Rj0=class Rj0 extends Error{status;constructor($,Z){super(`sandbox daemon /_sandbox/config returned ${$}: ${Z}`);this.status=$;this.name="ConfigRequestError"}};Hg4=["cookie","host","connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","accept-encoding","content-length"]});async function*$M8($){let Z=$.now??(()=>Date.now()),X=Z(),Q=$.schedulingTimeoutMs??Fg4,Y={pod:{},sandbox:{},events:{hasPulling:!1,hasPulled:!1},startedAt:X},G=[],J=null,K=!1,W=(z)=>{if(K)return;if(J){let j=J;J=null,j(z)}else G.push(z)},H=()=>{if(G.length>0)return Promise.resolve(G.shift());if(K)return Promise.resolve(null);return new Promise((z)=>{J=z})},N=()=>{if(K)return;if(K=!0,J){let z=J;J=null,z(null)}},U=new AbortController,F=()=>{U.abort(),N()};if($.signal)if($.signal.aborted)U.abort(),N();else $.signal.addEventListener("abort",F,{once:!0});let w=Math.max(0,Q-(Z()-X)),B=setTimeout(()=>W("tick"),w+100),L,D=new Promise((z)=>{L=z}),E=Promise.allSettled([wg4($.kc,$.namespace,$.claimName,U.signal,Y,W,Z,L),Og4($.kc,$.namespace,$.claimName,U.signal,Y,W),Lg4($.kc,$.namespace,$.claimName,D,U.signal,Y,W,Z)]);try{let z=null,j=-1,A=sq8(Y,Q,Z);if(z=B51(A),!w51(A))j=eq8(A);if(yield A,w51(A))return;while(!K){if(await H()===null)break;let q=sq8(Y,Q,Z);if(w51(q)){let C=B51(q);if(C!==z)z=C,yield q;return}let k=eq8(q);if(k<j)continue;let M=B51(q);if(M!==z)z=M,j=k,yield q}}finally{if(clearTimeout(B),U.abort(),$.signal)$.signal.removeEventListener("abort",F);N(),await E.catch(()=>{})}}function sq8($,Z,X){let{pod:Q,sandbox:Y,events:G,startedAt:J}=$;if(Y.ready)return{kind:"ready"};let K=Q.containerWaitingReason;if(K==="ImagePullBackOff"||K==="ErrImagePull")return{kind:"failed",reason:"image-pull-backoff",message:"Sandbox image failed to download. The cluster may be missing pull credentials or the image tag may not exist."};if(K==="CrashLoopBackOff")return{kind:"failed",reason:"crash-loop-backoff",message:"Sandbox crashed during startup and is now in CrashLoopBackOff. Check pod logs."};if(!Q.scheduled&&G.lastFailedSchedulingAt!==void 0&&X()-J>Z)return{kind:"failed",reason:"scheduling-timeout",message:G.failedSchedulingMessage??`Pod could not be scheduled within ${Math.round(Z/1000)}s.`};if(Q.containerRunning&&!Q.containerReady)return{kind:"warming-daemon",since:J};if(G.hasPulling&&!G.hasPulled)return{kind:"pulling-image",since:J};if(K==="ContainerCreating"||K==="PodInitializing"||Q.scheduled&&!Q.containerRunning)return{kind:"starting-container",since:J};if(Q.scheduledFalseReason==="Unschedulable"||G.lastFailedSchedulingAt!==void 0&&!Q.scheduled)return{kind:"waiting-for-capacity",since:J,message:G.failedSchedulingMessage??Q.scheduledFalseMessage,nodeClaim:G.nominatedNodeClaim};return{kind:"claiming",since:J}}function w51($){return $.kind==="ready"||$.kind==="failed"}function eq8($){switch($.kind){case"claiming":return 0;case"waiting-for-capacity":return 1;case"pulling-image":return 2;case"starting-container":return 3;case"warming-daemon":return 4;case"ready":case"failed":return 99}}function B51($){switch($.kind){case"claiming":case"pulling-image":case"starting-container":case"warming-daemon":return $.kind;case"waiting-for-capacity":return`waiting-for-capacity:${$.message??""}:${$.nodeClaim??""}`;case"ready":return"ready";case"failed":return`failed:${$.reason}:${$.message}`}}async function wg4($,Z,X,Q,Y,G,J,K){let W=`/api/v1/namespaces/${encodeURIComponent(Z)}/pods?watch=true&labelSelector=${encodeURIComponent(`${Ng4}=${X}`)}`;return qj0({kc:$,path:W,signal:Q,label:`pod/${X}`,onEvent:(H)=>{if(H.type!=="ADDED"&&H.type!=="MODIFIED")return;let N=H.object;if(N.metadata?.name)K(N.metadata.name);Bg4(N,Y,J),G("pod")}})}function Bg4($,Z,X){let Y=($.status?.conditions??[]).find((J)=>J.type==="PodScheduled");if(Y?.status==="True")Z.pod.scheduled=!0,Z.pod.scheduledFalseReason=void 0,Z.pod.scheduledFalseMessage=void 0;else if(Y?.status==="False")Z.pod.scheduled=!1,Z.pod.scheduledFalseReason=Y.reason,Z.pod.scheduledFalseMessage=Y.message;let G=($.status?.containerStatuses??[]).find((J)=>J.name===Ug4);if(G)Z.pod.containerWaitingReason=G.state?.waiting?.reason,Z.pod.containerRunning=!!G.state?.running,Z.pod.containerReady=G.ready===!0}async function Og4($,Z,X,Q,Y,G){let J=`/apis/${v9.CLAIM_API_GROUP}/${v9.CLAIM_API_VERSION}/namespaces/${encodeURIComponent(Z)}/${v9.CLAIM_PLURAL}?watch=true&fieldSelector=${encodeURIComponent(`metadata.name=${X}`)}`;return qj0({kc:$,path:J,signal:Q,label:`sandboxclaim/${X}`,onEvent:(K)=>{if(K.type!=="ADDED"&&K.type!=="MODIFIED")return;let H=K.object.status?.conditions?.find((N)=>N.type==="Ready");if(!H)return;if(H.status==="True")Y.sandbox.ready=!0,Y.sandbox.notReadyReason=void 0,Y.sandbox.notReadyMessage=void 0;else Y.sandbox.ready=!1,Y.sandbox.notReadyReason=H.reason,Y.sandbox.notReadyMessage=H.message;G("sandbox")}})}async function Lg4($,Z,X,Q,Y,G,J,K){let W=await Promise.race([Q,new Promise((N)=>{if(Y.aborted){N(X);return}Y.addEventListener("abort",()=>N(X),{once:!0})})]);if(Y.aborted)return;let H=`/api/v1/namespaces/${encodeURIComponent(Z)}/events?watch=true&fieldSelector=${encodeURIComponent(`involvedObject.name=${W},involvedObject.kind=Pod`)}`;return qj0({kc:$,path:H,signal:Y,label:`events/${X}`,onEvent:(N)=>{if(N.type!=="ADDED"&&N.type!=="MODIFIED")return;let U=N.object,F=U.reason;if(!F)return;switch(F){case"Pulling":G.events.hasPulling=!0;break;case"Pulled":G.events.hasPulling=!0,G.events.hasPulled=!0;break;case"FailedScheduling":G.events.lastFailedSchedulingAt=K(),G.events.failedSchedulingMessage=U.message;break;case"Nominated":{let w=U.message?.match(/nodeclaim\/([\w-]+)/);if(w)G.events.nominatedNodeClaim=w[1];break}default:return}J("event")}})}async function ZM8($){let{kc:Z,namespace:X,labelSelector:Q,signal:Y,onDelete:G}=$,J=`/apis/${v9.CLAIM_API_GROUP}/${v9.CLAIM_API_VERSION}/namespaces/${encodeURIComponent(X)}/${v9.CLAIM_PLURAL}?watch=true&labelSelector=${encodeURIComponent(Q)}`;return qj0({kc:Z,path:J,signal:Y,label:"sandboxclaim-reaper",onEvent:(K)=>{if(K.type!=="DELETED")return;let W=K.object.metadata?.name;if(W)G(W)}})}async function qj0($){let{kc:Z,path:X,signal:Q,label:Y,onEvent:G}=$,J=0;while(!Q.aborted){try{let W=await FK(Z,{method:"GET",path:X,signal:Q,headers:{accept:"application/json"},stream:!0});if(!W.ok||!W.body){try{await W.body?.cancel()}catch{}if(W.status===401||W.status===403){console.warn(`[lifecycle-watcher] ${Y} stopped: watch denied (${W.status} ${W.statusText}). `+"The kubeconfig in use cannot watch SandboxClaims \u2014 if you are running locally, "+"this provider should not be active (check STUDIO_SANDBOX_PROVIDER / your sandbox preference).");return}throw Error(`watch handshake failed: ${W.status} ${W.statusText}`)}J=0;for await(let H of H51(W.body)){if(Q.aborted)return;try{G(H)}catch(N){console.warn(`[lifecycle-watcher] ${Y} onEvent threw: ${N instanceof Error?N.message:String(N)}`)}}}catch(W){if(Q.aborted)return;let H=W instanceof Error?W.message:String(W);console.warn(`[lifecycle-watcher] ${Y} watch ended: ${H}`)}if(Q.aborted)return;let K=CX(5000,250,J,2,0);J+=1,await _8(K,{signal:Q}).catch(()=>{})}}var Ng4="studio.decocms.com/sandbox-handle",Ug4="sandbox",Fg4=300000;var XM8=O(()=>{H$();Qa();Ja()});import{z as I3}from"zod";function QM8($){if(!$||$.trim()==="")return[];let Z=I3.array(Dg4).parse(JSON.parse($)),X=new Set;for(let Q of Z){if(X.has(Q.name))throw Error(`STUDIO_SANDBOX_TENANT_POOLS: duplicate pool name ${Q.name}`);X.add(Q.name)}return Z}function Eg4($){try{let[Z,X]=new URL($).pathname.replace(/^\/+/,"").split("/"),Q=X?.replace(/\.git$/,"");return Z&&Q?`${Z}/${Q}`.toLowerCase():null}catch{return null}}function YM8($,Z){let{orgId:X,cloneUrl:Q}=Z;if(Z.cloneOnly===!0)return null;if(!X||!Q)return null;let Y=Eg4(Q);if(!Y)return null;return $.find((G)=>G.orgId===X&&G.repo.toLowerCase()===Y)??null}function GM8($,Z){return $?.name??(Z?"default":"none")}function JM8($,Z,X){let Q=X.replace(/^refs\/heads\//,"");return $.filter((Y)=>Y.repo.toLowerCase()===Z.toLowerCase()&&Y.branch===Q)}function KM8($){return`https://github.com/${$.repo}.git`}var Dg4;var O51=O(()=>{Dg4=I3.object({name:I3.string().regex(/^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/,"pool name must be a DNS label (lowercase alphanumeric and '-')"),orgId:I3.string().min(1),repo:I3.string().regex(/^[^/\s]+\/[^/\s]+$/,"repo must be `owner/name`"),connectionId:I3.string().min(1).optional(),branch:I3.string().min(1).default("main"),workload:I3.object({runtime:I3.enum(["node","bun","deno"]).default("node"),packageManager:I3.enum(["npm","pnpm","yarn","bun","deno"]).optional(),packageManagerPath:I3.string().optional(),devPort:I3.number().int().positive().optional()}).default({runtime:"node"})})});async function WM8($,Z,X){let Q=new Map;for(let Y of $){let G=Z(Y);if(!G)continue;let J=Q.get(G);if(J)J.push(Y);else Q.set(G,[Y])}await Promise.allSettled([...Q.values()].map(async(Y)=>{for(let G of Y)await X(G).catch(()=>{})}))}import{createHash as zg4,randomBytes as jg4,randomUUID as Pg4}from"crypto";import*as BM8 from"net";import{PassThrough as Ag4}from"stream";function Tg4($){if($ instanceof Error)return $.message;if($&&typeof $==="object"){let Z=$;if(Z.error instanceof Error)return Z.error.message;if(typeof Z.message==="string"&&Z.message)return Z.message}return String($)}class P51{kind=wY;records=new Map;inflight=new a30;stateStore;previewUrlPattern;kubeConfig;capacityProbe;portForward;namespace;sandboxTemplateName;envName;tokenGenerator;idleTtlMs;metrics;previewGateway;sentinelToken;mintCloneUrl;tenantPools;tenantPoolRefreshMs;poolPods=new Map;dirtyPools=new Set;closed=!1;claimWatchAbort=new AbortController;constructor($={}){this.stateStore=$.stateStore??null,this.previewUrlPattern=$.previewUrlPattern??null,this.kubeConfig=$.kubeConfig??bg4(),this.portForward=new c$1(this.kubeConfig),this.namespace=$.namespace??Rg4,this.sandboxTemplateName=$.sandboxTemplateName??Ig4,this.envName=lg4($.envName),this.tokenGenerator=$.tokenGenerator??(()=>jg4(qg4).toString("hex")),this.idleTtlMs=$.idleTtlMs??kg4,this.metrics=$.meter?fg4($.meter):null,this.previewGateway=$.previewGateway&&$.previewUrlPattern?{...$.previewGateway}:null;let Z=$.sentinelToken?.trim()??"";if(this.sentinelToken=Z.length>0?Z:null,this.mintCloneUrl=$.mintCloneUrl,this.tenantPools=this.sentinelToken!==null?$.tenantPools??[]:[],this.sentinelToken===null&&($.tenantPools?.length??0)>0)console.warn(`[${r$}] tenant pools configured without a sentinel token \u2014 ignoring them (warm-pool mode is off)`);this.tenantPoolRefreshMs=$.tenantPoolRefreshMs??Sg4,this.startClaimReaper(),this.startCredentialRefresher(),this.startTenantPoolReconciler()}startClaimReaper(){let $=["app.kubernetes.io/managed-by=studio","app.kubernetes.io/name=studio-sandbox",...this.envName?[`${BY.env}=${this.envName}`]:[]].join(",");ZM8({kc:this.kubeConfig,namespace:this.namespace,labelSelector:$,signal:this.claimWatchAbort.signal,onDelete:(Z)=>this.invalidateRecord(Z)})}async ensure($,Z={}){let X=Wj($);if(X.startsWith("s-"))throw Error(`ensure: projectRef has no slug source: ${$.projectRef}`);return this.inflight.run(X,()=>s30(this.stateStore,$,wY,(Q)=>this.ensureLocked($,X,Z,Q)))}async delete($){let Z=await this.getRecord($);if(this.records.delete($),Z)this.closeForwarder(Z.daemonForward),this.metrics?.active.add(-1,z51(Z.tenant));if(await this.deleteHttpRouteIfManaged($).catch((X)=>{console.warn(`[${r$}] HTTPRoute delete failed for ${$}: ${X instanceof Error?X.message:String(X)}`)}),await fO(this.kubeConfig,this.namespace,$),this.stateStore)if(Z)await this.stateStore.delete(Z.id,wY);else await this.stateStore.deleteByHandle(wY,$)}async alive($){return await wK(this.kubeConfig,this.namespace,$)!==void 0}watchClaimLifecycle($,Z){return $M8({kc:this.kubeConfig,namespace:this.namespace,claimName:$,signal:Z})}hasSchedulableCapacity(){return this.capacityProbe??=iq8(this.kubeConfig,this.namespace),this.capacityProbe()}async getPreviewUrl($){let Z=await this.getRecord($);if(!Z)return null;return this.composePreviewUrl(Z)}async proxyDaemonRequest($,Z,X){let Q=await this.getRecord($);if(!Q&&this.previewUrlPattern&&this.stateStore){let W=await this.stateStore.getByHandle(wY,$),H=W?.state,N=H?.token;if(W&&N){let F=`http://${H?.adoptedSandboxName??$}.${this.namespace}.svc.cluster.local:${yU}`;try{let w=await Ka(F,N,Z,X);if(w.status!==404)return w;try{await w.body?.cancel()}catch{}}catch{}}}if(!Q)Q=await this.resurrectByHandle($);if(!Q)return new Response(JSON.stringify({error:"sandbox not found"}),{status:404,headers:{"content-type":"application/json"}});let Y=Q,G=performance.now(),J=0,K=!(X.body instanceof ReadableStream);try{let W=await Ka(Q.daemonUrl,Q.token,Z,X);if(W.status===401&&K){this.invalidateRecord($);let H=await this.getRecord($).catch(()=>null)??await this.resurrectByHandle($).catch(()=>null);if(H)Y=H,W=await Ka(H.daemonUrl,H.token,Z,X)}return J=W.status,W}catch(W){if(!K)throw W;this.invalidateRecord($);let H=await this.resurrectByHandle($)??await this.getRecord($).catch(()=>null);if(!H)throw W;Y=H;let N=await Ka(H.daemonUrl,H.token,Z,X);return J=N.status,N}finally{this.recordProxyDuration("daemon",J,Y,performance.now()-G)}}async adoptLiveClaim($,Z){if(this.records.has(Z))return!0;let X=await wK(this.kubeConfig,this.namespace,Z).catch(()=>{return});if(!X||X.metadata?.deletionTimestamp)return!1;return await this.inflight.run(Z,async()=>{let Y=this.records.get(Z);if(Y)return this.toSandbox(Y);let G=await this.adopt($,Z,X);if(!G)throw Error(`cannot adopt live claim ${Z}`);return s30(this.stateStore,$,wY,(J)=>this.finish(G,J,!0,!0,"adopt"))}).catch(()=>null)!=null}async resolvePreviewUpstreamUrl($){if(this.previewUrlPattern)return`http://${await this.resolveServiceNameForHandle($)}.${this.namespace}.svc.cluster.local:${yU}`;let Z=await this.getRecord($);if(Z)return Z.daemonUrl;let X=await this.resurrectByHandle($);return X?X.daemonUrl:null}async resolveServiceNameForHandle($){let Z=this.records.get($);if(Z)return Z.adoptedSandboxName;if(this.stateStore){let Q=(await this.stateStore.getByHandle(wY,$).catch(()=>null))?.state?.adoptedSandboxName;if(Q)return Q}return $}async proxyPreviewRequest($,Z){let X=performance.now(),Q=this.records.get($)??null,Y=0;try{let G=await this.resolvePreviewUpstreamUrl($);if(!G){Y=404;let B=D51(404,{error:"sandbox not found"});return B.headers.set(h_,"1"),B}let J=new URL(Z.url);if((J.pathname==="/_sandbox"||J.pathname.startsWith("/_sandbox/")||J.pathname==="/_decopilot_vm"||J.pathname.startsWith("/_decopilot_vm/"))&&Z.method!=="GET")return Y=404,D51(404,{error:"not found"});let W=(B)=>`${B}${J.pathname}${J.search}`,H=new Headers(Z.headers);for(let B of vg4)H.delete(B);let N=Z.method!=="GET"&&Z.method!=="HEAD",U={method:Z.method,headers:H,body:N?Z.body:void 0,redirect:"manual",signal:Z.signal,duplex:N?"half":void 0},F;try{F=await fetch(W(G),U)}catch(B){let L=`${G}${J.pathname}`;if(console.warn(`[${r$}] preview fetch to ${L} failed: ${B instanceof Error?B.message:String(B)}`),Z.method==="GET"||Z.method==="HEAD"){if(this.invalidateRecord($),await this.resurrectByHandle($).catch(()=>null)){let z=await this.resolvePreviewUpstreamUrl($);if(z)try{F=await fetch(W(z),U);let j=new Headers;for(let[A,P]of F.headers.entries())if(!UM8.includes(A.toLowerCase()))j.set(A,P);return Y=F.status,new Response(F.body,{status:F.status,statusText:F.statusText,headers:j})}catch(j){console.warn(`[${r$}] preview fetch retry to ${L} failed: ${j instanceof Error?j.message:String(j)}`)}}}else this.invalidateRecord($);Y=502;let D=D51(502,{error:"sandbox daemon unreachable"});return D.headers.set(h_,"1"),D}let w=new Headers;for(let[B,L]of F.headers.entries())if(!UM8.includes(B.toLowerCase()))w.set(B,L);return Y=F.status,new Response(F.body,{status:F.status,statusText:F.statusText,headers:w})}finally{this.recordProxyDuration("preview",Y,Q,performance.now()-X,$)}}async ensureLocked($,Z,X,Q){if(X.image)console.warn(`[${r$}] opts.image ignored (template ${this.sandboxTemplateName} pins image): got ${X.image}`);if(Q){let J=await Q.get($,wY);if(J){let K=await this.rehydrate($,Z,J);if(K)return await this.refreshDaemonGitCredential(K,X),this.finish(K,Q,!1,!0,"resume");await Q.delete($,wY)}}let Y=await wK(this.kubeConfig,this.namespace,Z).catch(()=>{return});if(Y)if(Y.metadata?.deletionTimestamp)await zj0(this.kubeConfig,this.namespace,Z).catch((J)=>{console.warn(`[${r$}] wait for terminating claim ${Z} failed: ${J instanceof Error?J.message:String(J)}`)});else{let J=await this.adopt($,Z,Y).catch((K)=>{return console.warn(`[${r$}] adopt ${Z} failed, recreating: ${K instanceof Error?K.message:String(K)}`),null});if(J)return await this.refreshDaemonGitCredential(J,X),this.finish(J,Q,!0,!0,"adopt");await fO(this.kubeConfig,this.namespace,Z).catch(()=>{}),await zj0(this.kubeConfig,this.namespace,Z).catch((K)=>{console.warn(`[${r$}] wait for deleted claim ${Z} failed: ${K instanceof Error?K.message:String(K)}`)})}let G=await this.provision($,Z,X);return this.finish(G,Q,!0,!1,"fresh")}async finish($,Z,X,Q,Y){let G=this.records.get($.handle),J=G!==void 0;if(G&&G.daemonForward!==$.daemonForward)this.closeForwarder(G.daemonForward);if(this.records.set($.handle,$),X)await this.persist(Z,$);if(Q)await jj0(this.kubeConfig,this.namespace,$.handle,this.computeShutdownTime()).catch((K)=>console.warn(`[${r$}] TTL refresh failed for ${$.handle}: ${K instanceof Error?K.message:String(K)}`));if(this.metrics){let K=z51($.tenant);if(this.metrics.ensureOutcome.add(1,{...K,outcome:Y}),!J)this.metrics.active.add(1,K)}return this.toSandbox($)}buildEnvMap($,Z){let X={},Q=[];for(let[Y,G]of Object.entries($.env??{}))if(Mg4.has(Y))Q.push(Y);else X[Y]=G;if(Q.length>0)console.warn(`[${r$}] opts.env keys overlap reserved bootstrap names and were dropped: ${Q.join(",")}`);return{...X,DAEMON_TOKEN:Z.token,DAEMON_BOOT_ID:Z.daemonBootId,APP_ROOT:Z.workdir,PROXY_PORT:String(yU)}}buildClaim($,Z,X){let Q=this.sentinelToken!==null,Y=YM8(this.tenantPools,{orgId:Z.tenant?.orgId,cloneUrl:Z.repo?.cloneUrl,cloneOnly:Z.cloneOnly}),G=Q?[]:Object.entries(this.buildEnvMap(Z,X)).sort(([W],[H])=>W<H?-1:W>H?1:0).map(([W,H])=>({name:W,value:H})),J=ig4(Z),K=Object.keys(J).length>0;return{apiVersion:`${v9.CLAIM_API_GROUP}/${v9.CLAIM_API_VERSION}`,kind:"SandboxClaim",metadata:{name:$,namespace:this.namespace,labels:{"app.kubernetes.io/name":"studio-sandbox","app.kubernetes.io/managed-by":"studio",...this.envName?{[BY.env]:this.envName}:{},...E51(Z.tenant)},...K?{annotations:J}:{}},spec:{sandboxTemplateRef:{name:this.sandboxTemplateName},additionalPodMetadata:{labels:E51(Z.tenant,{[BY.role]:"claimed",[BY.sandboxHandle]:$,...this.envName?{[BY.env]:this.envName}:{}}),...K?{annotations:J}:{}},env:G,warmpool:GM8(Y,Q),lifecycle:{shutdownPolicy:"Delete",shutdownTime:this.computeShutdownTime()}}}}async provision($,Z,X){let Q=this.tokenGenerator(),Y=Pg4(),G=L51,J=this.buildClaim(Z,X,{token:Q,daemonBootId:Y,workdir:G});try{await Ya(this.kubeConfig,this.namespace,J)}catch(F){if(F instanceof Xa)await zj0(this.kubeConfig,this.namespace,Z),await Ya(this.kubeConfig,this.namespace,J);else throw F}let K;try{K=await fq8(this.kubeConfig,this.namespace,Z),await Tj0(this.kubeConfig,this.namespace,K)}catch(F){throw await fO(this.kubeConfig,this.namespace,Z).catch(()=>{}),F}try{await this.ensureServicePortForAdoptedSandbox(K),await this.ensureHttpRouteForHandle(Z,K,X.tenant??null)}catch(F){throw await fO(this.kubeConfig,this.namespace,Z).catch(()=>{}),F}let W=await this.openForwarder(K,yU,Z),H=`http://127.0.0.1:${W.localPort}`,N=this.workloadConfigPayload(X),U=Y;try{if(await F51(H),this.sentinelToken!==null){let F=await Ij0(H);if(F)U=F.bootId;await y_(H,this.sentinelToken,N??{},{rotateToken:Q})}else if(N)await y_(H,Q,N);await this.relayOrgFsConfig(H,Q,X.orgFsConfigJson)}catch(F){throw this.closeForwarder(W),await this.deleteHttpRouteIfManaged(Z).catch(()=>{}),await fO(this.kubeConfig,this.namespace,Z).catch(()=>{}),F}return{id:$,handle:Z,adoptedSandboxName:K,token:Q,workdir:G,daemonUrl:H,daemonForward:W,workload:X.workload??null,daemonBootId:U,tenant:X.tenant??null,ensureOpts:og4(X)}}workloadConfigPayload($){return $J0({runtime:$?.workload?.runtime??"node",packageManager:$?.workload?.packageManager?{name:$.workload.packageManager,...$.workload.packageManagerPath?{path:$.workload.packageManagerPath}:{}}:null,repo:$?.repo??null,port:$?.workload?.devPort??HM8,tenant:$?.tenant??void 0,...$?{cloneOnly:$.cloneOnly===!0}:{}})}async relayOrgFsConfig($,Z,X){if(!X)return;await rq8($,Z,X).catch((Q)=>console.warn("[org-fs] sidecar config relay failed",Q))}async refreshDaemonGitCredential($,Z){let X=J41(Z);if(!X)return;try{await y_($.daemonUrl,$.token,X)}catch(Q){console.warn(`[${r$}] git credential refresh failed for ${$.handle}: ${Q instanceof Error?Q.message:String(Q)}`)}}async withFreshCloneUrl($,Z){if(!this.mintCloneUrl)return $;try{let X=await this.mintCloneUrl($,Z!==void 0?{bufferMs:Z}:void 0);return X?{...$,cloneUrl:X}:$}catch(X){return console.warn(`[${r$}] clone credential re-mint failed: ${X instanceof Error?X.message:String(X)}`),$}}startCredentialRefresher(){if(!this.mintCloneUrl)return;let{signal:$}=this.claimWatchAbort;(async()=>{while(!$.aborted){if(await _8(Cg4,{signal:$}).catch(()=>{}),$.aborted)break;try{await this.refreshAllGitCredentials()}catch(Z){console.warn(`[${r$}] periodic credential refresh failed: ${Z instanceof Error?Z.message:String(Z)}`)}}})()}startTenantPoolReconciler(){if(this.tenantPools.length===0)return;let{signal:$}=this.claimWatchAbort;(async()=>{while(!$.aborted){try{await this.reconcileTenantPools()}catch(Z){console.warn(`[${r$}] tenant pool reconcile failed: ${Z instanceof Error?Z.message:String(Z)}`)}await _8(Vg4,{signal:$}).catch(()=>{})}})()}markTenantPoolsDirty($,Z){let X=JM8(this.tenantPools,$,Z);for(let Q of X)this.dirtyPools.add(Q.name);return X.map((Q)=>Q.name)}async reconcileTenantPools(){for(let $ of this.tenantPools){let Z=await bq8(this.kubeConfig,this.namespace,$.name);if(Z===null){console.warn(`[${r$}] tenant pool ${$.name}: no SandboxWarmPool (or no selector yet) in ${this.namespace}`);continue}let X=this.dirtyPools.delete($.name),Q=Z.filter((Y)=>!Y.labels[BY.sandboxHandle]);for(let[Y]of this.poolPods)if(!Z.some((G)=>G.uid===Y))this.poolPods.delete(Y);for(let Y of Q){if(this.claimWatchAbort.signal.aborted)return;await this.warmPoolPod($,Y,X)}this.recordPoolDepth($,Z,Q)}}recordPoolDepth($,Z,X){let Q=this.metrics?.poolPods;if(!Q)return;let Y=0,G=0;for(let K of X){let W=this.poolPods.get(K.uid);if(!W)continue;if(W.failures>=Mj0)G++;else if(W.lastConfigAt>0)Y++}let J={pool:$.name,org:$.orgId};Q.record(Y,{...J,state:"ready"}),Q.record(Z.length-X.length,{...J,state:"bound"}),Q.record(X.length-Y-G,{...J,state:"pending"}),Q.record(G,{...J,state:"failed"})}async warmPoolPod($,Z,X){let Q=this.poolPods.get(Z.uid);if(Q&&Q.failures>=Mj0){if(Date.now()-Q.lastFailureAt<NM8)return;this.poolPods.set(Z.uid,{...Q,failures:0})}let Y=X||Q!==void 0&&Date.now()-Q.lastConfigAt>=this.tenantPoolRefreshMs;if(Q&&!Y)return;let G={cloneUrl:KM8($),connectionId:$.connectionId,branch:$.branch,userName:"",userEmail:""},J=await this.withFreshCloneUrl(G);if($.connectionId&&J.cloneUrl===G.cloneUrl){this.recordPoolFailure(Z,$,"clone credential mint failed");return}let K=await this.openForwarder(Z.name,yU,Z.name).catch(()=>null);if(!K){this.recordPoolFailure(Z,$,"port-forward failed");return}let W=`http://127.0.0.1:${K.localPort}`;try{await F51(W);let H=this.sentinelToken;if(!H)return;if(!await this.isPoolPodUnbound(Z))return;let N=$J0({runtime:$.workload.runtime,packageManager:$.workload.packageManager?{name:$.workload.packageManager,...$.workload.packageManagerPath?{path:$.workload.packageManagerPath}:{}}:null,repo:J,port:$.workload.devPort??HM8})??{},{transition:U}=await y_(W,H,N);if(Y&&U!=="bootstrap"&&await this.isPoolPodUnbound(Z))await oq8(W,H,"clone");this.poolPods.set(Z.uid,{lastConfigAt:Date.now(),lastFailureAt:0,failures:0}),console.log(`[${r$}] tenant pool ${$.name}: warmed ${Z.name} (${U})`)}catch(H){this.recordPoolFailure(Z,$,H instanceof Error?H.message:String(H))}finally{this.closeForwarder(K)}}isPoolPodUnbound($){return yq8(this.kubeConfig,this.namespace,$.name,BY.sandboxHandle)}recordPoolFailure($,Z,X){let Q=this.poolPods.get($.uid),Y=(Q?.failures??0)+1;this.poolPods.set($.uid,{lastConfigAt:Q?.lastConfigAt??0,lastFailureAt:Date.now(),failures:Y});let G=Y>=Mj0?` \u2014 backing off ${NM8/60000}min`:"";console.warn(`[${r$}] tenant pool ${Z.name}: warming ${$.name} failed (${Y}/${Mj0})${G}: ${X}`)}async refreshAllGitCredentials(){await WM8(this.records.values(),($)=>$.ensureOpts?.repo?.connectionId,async($)=>{if(this.claimWatchAbort.signal.aborted)return;let Z=$.ensureOpts?.repo;if(!Z)return;let X=await this.withFreshCloneUrl(Z,_g4);await this.refreshDaemonGitCredential($,{...$.ensureOpts,repo:X}),$.ensureOpts={...$.ensureOpts,repo:X}})}async rebootstrapDaemon($,Z,X){if(this.sentinelToken===null)return!1;let Q=this.workloadConfigPayload(X)??{};try{return await y_($,this.sentinelToken,Q,{rotateToken:Z}),await this.relayOrgFsConfig($,Z,X?.orgFsConfigJson),!0}catch(Y){if(Y instanceof Rj0&&Y.status===401)try{return await y_($,Z,Q,{rotateToken:Z}),await this.relayOrgFsConfig($,Z,X?.orgFsConfigJson),!0}catch(G){return console.warn(`[${r$}] re-bootstrap retry with claim token failed: ${G instanceof Error?G.message:String(G)}`),!1}return console.warn(`[${r$}] re-bootstrap failed: ${Y instanceof Error?Y.message:String(Y)}`),!1}}async ensureServicePortForAdoptedSandbox($){if(!this.previewGateway||!this.previewUrlPattern)return;await dq8(this.kubeConfig,this.namespace,$,{name:"daemon",port:yU,targetPort:yU})}async ensureHttpRouteForHandle($,Z,X){if(!this.previewGateway||!this.previewUrlPattern)return;let Q=rg4(this.previewUrlPattern,$);if(!Q)throw new p9(`Unable to derive preview hostname for ${$} from pattern: ${this.previewUrlPattern}`);let Y={apiVersion:`${Ga.API_GROUP}/${Ga.API_VERSION}`,kind:"HTTPRoute",metadata:{name:$,namespace:this.namespace,labels:E51(X??void 0,{[BY.role]:"claimed",[BY.sandboxHandle]:$,"app.kubernetes.io/name":"studio-sandbox","app.kubernetes.io/managed-by":"studio",...this.envName?{[BY.env]:this.envName}:{}})},spec:{parentRefs:[{kind:"Gateway",group:"gateway.networking.k8s.io",name:this.previewGateway.name,namespace:this.previewGateway.namespace}],hostnames:[Q],rules:[{backendRefs:[{group:"",kind:"Service",name:Z,port:yU}]}]}};await Pj0(this.kubeConfig,this.namespace,Y)}async deleteHttpRouteIfManaged($){if(!this.previewGateway)return;await Aj0(this.kubeConfig,this.namespace,$)}async rehydrate($,Z,X){let Q=X.state;if(!Q.adoptedSandboxName&&!Q.podName||!Q.token)return null;let Y=await wK(this.kubeConfig,this.namespace,Z).catch(()=>{return});if(!Y||!FM8(Y))return null;let G=Y.status?.sandbox?.name??Q.adoptedSandboxName??Q.podName??Z,J=await this.openAndProbeDaemon(G,Z);if(!J)return null;if(Q.daemonBootId&&Q.daemonBootId!==J.bootId){if(this.sentinelToken!==null){let K=Q.ensureOpts?.repo?{...Q.ensureOpts,repo:await this.withFreshCloneUrl(Q.ensureOpts.repo)}:Q.ensureOpts??null;if(!await this.rebootstrapDaemon(J.daemonUrl,Q.token,K))return this.closeForwarder(J.daemonForward),null}else console.warn(`[${r$}] daemon restart detected (handle=${Z}): stored bootId=${Q.daemonBootId} live bootId=${J.bootId}`);await this.stateStore?.put($,wY,{handle:Z,state:{...Q,daemonBootId:J.bootId}}).catch((K)=>console.warn(`[${r$}] bootId persist failed for ${Z}: ${K instanceof Error?K.message:String(K)}`))}return{id:$,handle:Z,adoptedSandboxName:G,token:Q.token,workdir:Q.workdir??L51,daemonUrl:J.daemonUrl,daemonForward:J.daemonForward,workload:Q.workload??null,daemonBootId:J.bootId,tenant:Q.tenant??null,ensureOpts:Q.ensureOpts??null}}async adopt($,Z,X){if(!FM8(X))return null;let Q=X.status?.sandbox?.name??Z;if(this.sentinelToken!==null)return null;let Y=yg4(X);if(!Y)return null;let G=await this.openAndProbeDaemon(Q,Z);if(!G)return null;let J=ng4(X);if(this.previewGateway)await this.ensureServicePortForAdoptedSandbox(Q).catch((K)=>{console.warn(`[${r$}] Service port backfill failed for ${Z}: ${K instanceof Error?K.message:String(K)}`)}),await this.ensureHttpRouteForHandle(Z,Q,J).catch((K)=>{console.warn(`[${r$}] HTTPRoute backfill failed for ${Z}: ${K instanceof Error?K.message:String(K)}`)});return{id:$,handle:Z,adoptedSandboxName:Q,token:Y,workdir:L51,daemonUrl:G.daemonUrl,daemonForward:G.daemonForward,workload:null,daemonBootId:G.bootId,tenant:J,ensureOpts:null}}async openAndProbeDaemon($,Z){let X=await this.openForwarder($,yU,Z).catch(()=>null);if(!X)return null;let Q=`http://127.0.0.1:${X.localPort}`,Y=await Ij0(Q);if(!Y)return this.closeForwarder(X),null;return{daemonForward:X,daemonUrl:Q,bootId:Y.bootId}}async getRecord($){let Z=this.records.get($);if(Z)return Z;if(!this.stateStore)return null;let X=await this.stateStore.getByHandle(wY,$);if(!X)return null;let Q=await this.rehydrate(X.id,$,X);if(Q)this.records.set($,Q);return Q}async resurrectByHandle($){if(!this.stateStore)return null;let Z=await this.stateStore.getByHandle(wY,$);if(!Z)return null;let X=Z.state.ensureOpts;if(!X)return null;let Q=X.repo?{...X,repo:await this.withFreshCloneUrl(X.repo)}:X;if(Wj(Z.id)!==$)return null;return await this.ensure(Z.id,Q),this.records.get($)??null}invalidateRecord($){let Z=this.records.get($);if(!Z)return;this.records.delete($),this.closeForwarder(Z.daemonForward)}recordProxyDuration($,Z,X,Q,Y){if(!this.metrics)return;this.metrics.proxyDurationMs.record(Q,{...z51(X?.tenant??null),source:$,sandbox_handle:X?.handle??Y??"",status_code:Z||0})}composePreviewUrl($){if(this.previewUrlPattern)return e30(this.previewUrlPattern,$.handle);return`http://127.0.0.1:${$.daemonForward.localPort}/`}toSandbox($){return{handle:$.handle,workdir:$.workdir,previewUrl:this.composePreviewUrl($)}}async persist($,Z){if(!$)return;let X={adoptedSandboxName:Z.adoptedSandboxName,token:Z.token,workdir:Z.workdir,workload:Z.workload,daemonBootId:Z.daemonBootId,tenant:Z.tenant,...Z.ensureOpts?{ensureOpts:Z.ensureOpts}:{}};await $.put(Z.id,wY,{handle:Z.handle,state:X})}computeShutdownTime(){return new Date(Date.now()+this.idleTtlMs).toISOString()}async releaseAfter($,Z){let X=await wK(this.kubeConfig,this.namespace,$);if(!X)return;let Q=pg4(X.spec?.lifecycle?.shutdownTime,new Date(Date.now()+Z));if(!Q)return;await jj0(this.kubeConfig,this.namespace,$,Q).catch((Y)=>console.warn(`[${r$}] release failed for ${$}: ${Y instanceof Error?Y.message:String(Y)}`))}async renewTtl($){let Z=await wK(this.kubeConfig,this.namespace,$);if(!Z)return;let X=tg4(Z.spec?.lifecycle?.shutdownTime,new Date(Date.now()+this.idleTtlMs));if(!X)return;await jj0(this.kubeConfig,this.namespace,$,X).catch((Q)=>console.warn(`[${r$}] TTL renew failed for ${$}: ${Q instanceof Error?Q.message:String(Q)}`))}openForwarder($,Z,X=$){let Q=gg4(X,Z);return new Promise((Y,G)=>{let J=(K,W)=>{let H=BM8.createServer((N)=>this.handleForwardedConnection(N,$,Z,X));H.once("error",(N)=>{if(N.code==="EADDRINUSE"&&W<xg4){try{H.close()}catch{}let U=j51+(K-j51+1)%OM8;J(U,W+1);return}G(N)}),H.listen(K,"127.0.0.1",()=>{let N=H.address();if(!N||typeof N==="string"){H.close(),G(Error("port-forward listener failed to bind"));return}Y({server:H,localPort:N.port})})};J(Q,0)})}handleForwardedConnection($,Z,X,Q){let Y=new Ag4,G=null,J=!1,K=()=>{if(J)return;if(J=!0,Y.destroy(),G)try{G.close()}catch{}if(!$.destroyed)$.destroy()};$.pipe(Y),$.on("error",K),$.on("close",K),this.portForward.portForward(this.namespace,Z,[X],$,null,Y).then((W)=>{let H=typeof W==="function"?W():W;if(!H){K();return}if(G=H,G.on("close",K),G.on("error",()=>{this.invalidateRecord(Q),K()}),J)try{G.close()}catch{}}).catch((W)=>{console.warn(`[${r$}] port-forward to ${Z}:${X} failed: ${Tg4(W)}`,JSON.stringify(LM8(W))),this.invalidateRecord(Q),K()})}closeForwarder($){$.server.close((Z)=>{if(Z)console.warn(`[${r$}] port-forward close on :${$.localPort} errored: ${Z instanceof Error?Z.message:String(Z)}`)})}close(){if(this.closed)return;this.closed=!0,this.claimWatchAbort.abort();for(let $ of this.records.values())this.closeForwarder($.daemonForward);this.records.clear()}}function fg4($){return{active:$.createUpDownCounter("studio.sandbox.active",{description:"Active sandbox count, by runner kind, owning org, and daemon impl. Cross-checks the cAdvisor-derived count from the cluster \u2014 divergence between the two indicates orphaned claims (studio deleted but K8s didn't reap) or unattributed pods.",unit:"{sandbox}"}),ensureOutcome:$.createCounter("studio.sandbox.ensure.outcome",{description:"Outcome of each ensure() call: fresh provision, resume from state-store after restart, or adopt of a cluster-side claim studio didn't know about. Cold-start ratio is the primary input for warm-pool sizing.",unit:"{call}"}),proxyDurationMs:$.createHistogram("studio.sandbox.proxy.duration_ms",{description:"Wall-clock latency of studio-mediated requests to the sandbox daemon: tool exec proxies (source=daemon) and preview iframe traffic (source=preview).",unit:"ms"}),poolPods:$.createGauge("studio.sandbox.pool.pods",{description:"Tenant warm pool depth by pool and state: ready (warmed and unbound \u2014 what a claim can actually bind instantly), bound (serving a user), pending (unbound, not yet warmed), failed (gave up after repeated bootstrap failures). Alert on sustained ready=0: a pool that is always empty is doing nothing while costing N pods.",unit:"{pod}"})}}function LM8($){let Z=[],X=$;for(let Q=0;Q<5&&X instanceof Error;Q++){let Y=X;if(Z.push({name:Y.name,message:Y.message,...Y.code!==void 0?{code:Y.code}:{},...Y.errno!==void 0?{errno:Y.errno}:{}}),Y.cause===X)break;X=Y.cause}if(X!==void 0&&!(X instanceof Error)&&X!==null){let Q=X,Y=Q.error instanceof Error?LM8(Q.error).chain:void 0;Z.push({nonError:String(X),...typeof Q.type==="string"?{type:Q.type}:{},...typeof Q.message==="string"?{message:Q.message}:{},...Q.code!==void 0?{code:Q.code}:{},...typeof Q.reason==="string"?{reason:Q.reason}:{},...Y?{error:Y}:{},...Y===void 0&&Q.error!==void 0?{rawError:String(Q.error)}:{},keys:Object.keys(Q)})}return{chain:Z}}function bg4(){let $=new ch;return $.loadFromDefault(),$}function FM8($){return Boolean($.status?.conditions?.some((Z)=>Z.type==="Ready"&&Z.status==="True"))}function yg4($){let Z=$.spec?.env;if(!Z)return null;for(let X of Z)if(X.name==="DAEMON_TOKEN"&&X.value)return X.value;return null}function gg4($,Z){let X=zg4("sha256").update(`${$}:${Z}`).digest();return j51+X.readUInt32BE(0)%OM8}function D51($,Z){return new Response(JSON.stringify(Z),{status:$,headers:{"content-type":"application/json","access-control-allow-origin":"*"}})}function wM8($){let Z=$.slice(0,ug4);return hg4.test(Z)?Z:""}function lg4($){if($===void 0)return null;let Z=$.trim();if(Z==="")return null;if(!cg4.test(Z))throw Error(`AgentSandboxProvider: envName=${JSON.stringify(Z)} is not a valid DNS-label-safe environment name (lowercase alphanumeric or '-', starts with a letter, ends alphanumeric, \u226432 chars). Studio sets this from STUDIO_ENV; check the studio chart's configMap.`);return Z}function E51($,Z={}){let X={...Z};if($){let Q=wM8($.orgId),Y=wM8($.userId);if(Q)X[BY.orgId]=Q;if(Y)X[BY.userId]=Y}return X}function g_($){let Z="";for(let X of $){let Q=X.codePointAt(0)??0;Z+=Q<32||Q===127?" ":X}return Z.slice(0,dg4)}function mg4($){try{let Z=new URL($);return Z.username="",Z.password="",Z.toString()}catch{return""}}function ig4($){let Z={},X=$.tenant;if(X?.orgSlug)Z[BK.orgSlug]=g_(X.orgSlug);if(X?.orgName)Z[BK.orgName]=g_(X.orgName);if(X?.userEmail)Z[BK.userEmail]=g_(X.userEmail);if(X?.userName)Z[BK.userName]=g_(X.userName);let Q=$.repo;if(Q){if(Q.displayName)Z[BK.gitRepo]=g_(Q.displayName);let Y=mg4(Q.cloneUrl);if(Y)Z[BK.gitRepoUrl]=g_(Y);let G=$.branch??Q.branch;if(G)Z[BK.gitBranch]=g_(G)}return Z}function ng4($){let Z=$.metadata?.labels;if(!Z)return null;let X=Z[BY.orgId],Q=Z[BY.userId];if(!X||!Q)return null;let Y=$.metadata?.annotations??{};return{orgId:X,userId:Q,orgSlug:Y[BK.orgSlug],orgName:Y[BK.orgName],userEmail:Y[BK.userEmail],userName:Y[BK.userName]}}function pg4($,Z){if($){let X=new Date($).getTime();if(Number.isFinite(X)&&X<=Z.getTime())return null}return Z.toISOString()}function tg4($,Z){if($){let X=new Date($).getTime();if(Number.isFinite(X)&&X>=Z.getTime())return null}return Z.toISOString()}function z51($){return{org_id:$?.orgId??"",user_id:$?.userId??"",runner_kind:wY}}function og4($){let Z={};if($.branch)Z.branch=$.branch;if($.repo)Z.repo=$.repo;if($.workload)Z.workload=$.workload;if($.env&&Object.keys($.env).length>0)Z.env=$.env;if($.tenant)Z.tenant=$.tenant;if($.orgFsConfigJson)Z.orgFsConfigJson=$.orgFsConfigJson;return Object.keys(Z).length>0?Z:null}function rg4($,Z){try{return new URL(e30($,Z)).hostname||null}catch{return null}}var wY="agent-sandbox",r$="AgentSandboxProvider",h_="x-sandbox-preview-not-ready",Rg4="agent-sandbox-system",Ig4="studio-sandbox",yU=9000,HM8=3000,L51="/app",qg4=32,Mg4,kg4=900000,Vg4=60000,Sg4=1800000,Mj0=3,NM8=1800000,Cg4=900000,_g4=1800000,vg4,UM8,j51=40000,OM8=1e4,xg4=256,BY,BK,hg4,ug4=63,cg4,dg4=253;var DM8=O(()=>{H$();nq8();Q51();aq8();K41();Ja();Qa();XM8();O51();Mg4=new Set(["DAEMON_TOKEN","DAEMON_BOOT_ID","APP_ROOT","PROXY_PORT"]),vg4=["cookie","host","connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","accept-encoding","content-length","upgrade"],UM8=["connection","keep-alive","transfer-encoding","content-encoding","content-length"];BY={role:"studio.decocms.com/role",sandboxHandle:"studio.decocms.com/sandbox-handle",orgId:"studio.decocms.com/org-id",userId:"studio.decocms.com/user-id",env:"studio.decocms.com/env"},BK={orgSlug:"studio.decocms.com/org-slug",orgName:"studio.decocms.com/org-name",userEmail:"studio.decocms.com/user-email",userName:"studio.decocms.com/user-name",gitRepo:"studio.decocms.com/git-repo",gitRepoUrl:"studio.decocms.com/git-repo-url",gitBranch:"studio.decocms.com/git-branch"},hg4=/^([A-Za-z0-9]([-A-Za-z0-9_.]*[A-Za-z0-9])?)?$/;cg4=/^[a-z]([a-z0-9-]{0,30}[a-z0-9])?$/});var EM8={};w0(EM8,{waitForSandboxReady:()=>Tj0,parseTenantPools:()=>QM8,getSandboxClaim:()=>wK,getHttpRoute:()=>cq8,deleteSandboxClaim:()=>fO,deleteHttpRoute:()=>Aj0,createSandboxClaim:()=>Ya,applyHttpRoute:()=>Pj0,SandboxTimeoutError:()=>b_,SandboxError:()=>p9,PREVIEW_NOT_READY_HEADER:()=>h_,KubeConfig:()=>ch,K8S_CONSTANTS:()=>v9,HTTPROUTE_CONSTANTS:()=>Ga,AgentSandboxProvider:()=>P51});var A51=O(()=>{Q51();Qa();Ja();DM8();O51()});var RM8={};w0(RM8,{subscribeLifecycle:()=>q51,getSandboxProviderByKind:()=>R51,getOrInitSharedRunner:()=>I51,__resetSharedLifecyclesForTesting:()=>Wh4});function AM8($,Z){let X=zM8[$];if(X)return Promise.resolve(X);let Q=T51[$];if(Q)return Q;let Y=Z().then((G)=>{return zM8[$]=G,G}).finally(()=>{delete T51[$]});return T51[$]=Y,Y}function eg4(){let $=process.env.STUDIO_SANDBOX_PREVIEW_URL_PATTERN;return $&&$.trim()!==""?$:void 0}function $h4(){let $=process.env.STUDIO_SANDBOX_TEMPLATE_NAME;return $&&$.trim()!==""?$:void 0}function Zh4(){let $=process.env.STUDIO_ENV;return $&&$.trim()!==""?$:void 0}function Xh4(){let $=process.env.STUDIO_SANDBOX_SENTINEL_TOKEN;return $&&$.trim()!==""?$:void 0}function Qh4(){let $=process.env.STUDIO_SANDBOX_PREVIEW_GATEWAY_NAME?.trim(),Z=process.env.STUDIO_SANDBOX_PREVIEW_GATEWAY_NAMESPACE?.trim();if(!$&&!Z)return;if(!$||!Z)throw Error("STUDIO_SANDBOX_PREVIEW_GATEWAY_NAME and STUDIO_SANDBOX_PREVIEW_GATEWAY_NAMESPACE must both be set, or both unset. Half-configured per-claim HTTPRoute routing would silently fail to attach.");return{name:$,namespace:Z}}async function TM8($,Z){let X=new br(Z),Q=eg4();switch($){case"agent-sandbox":{let{AgentSandboxProvider:Y,parseTenantPools:G}=await Promise.resolve().then(() => (A51(),EM8)),J=new iN(Z1().encryptionKey);return new Y({stateStore:X,previewUrlPattern:Q,sandboxTemplateName:$h4(),envName:Zh4(),previewGateway:Qh4(),sentinelToken:Xh4(),tenantPools:G(process.env.STUDIO_SANDBOX_TENANT_POOLS),meter:D6,mintCloneUrl:async(K,W)=>{if(!K.connectionId)return null;let H=HP8(K.cloneUrl);if(!H)return null;let{cloneUrl:N}=await RO(K.connectionId,H.owner,H.name,Z,J,{bufferMs:W?.bufferMs});return N}})}case"user-desktop":throw Error("user-desktop provider cannot be instantiated without a per-run link claim \u2014 call resolveSandboxProvider, which binds the link before constructing the provider.");default:throw Error(`Unknown sandbox provider kind: ${String($)}`)}}function R51($,Z){return AM8(Z,()=>TM8(Z,$.db))}async function I51(){let $;try{$=Hj()}catch(X){return console.warn("[lifecycle] cannot resolve sandbox runner:",X instanceof Error?X.message:String(X)),null}return await AM8($,()=>TM8($,H6().db))}function q51($,Z,X){let Q=bO.get(Z);if(Q){if(Q.terminated){if(Q.lastPhase)try{X(Q.lastPhase)}catch{}return{unsubscribe:Jh4}}if(Q.listeners.add(X),Q.lastPhase)try{X(Q.lastPhase)}catch{}return jM8(Z,Q,X)}let Y=new AbortController,G={lastPhase:null,terminated:!1,listeners:new Set([X]),abort:Y};return bO.set(Z,G),Kh4($,Z,G),jM8(Z,G,X)}function Jh4(){}function jM8($,Z,X){return{unsubscribe(){if(bO.get($)!==Z)return;if(Z.listeners.delete(X),Z.listeners.size===0)bO.delete($),Z.abort.abort()}}}async function Kh4($,Z,X){let Q=null;try{for await(let Y of $.watchClaimLifecycle(Z,X.abort.signal)){if(X.abort.signal.aborted)break;X.lastPhase=Y;let G=Y.kind==="ready"||Y.kind==="failed";if(G)X.terminated=!0;let J=Array.from(X.listeners);for(let K of J)try{K(Y)}catch{}if(G)break}}catch(Y){Q=Y}finally{if(!X.terminated&&!X.abort.signal.aborted&&X.listeners.size>0){let Y={kind:"failed",reason:"unknown",message:Q instanceof Error?Q.message:"Lifecycle watcher ended unexpectedly"};X.lastPhase=Y,X.terminated=!0;for(let G of Array.from(X.listeners))try{G(Y)}catch{}}if(bO.get(Z)===X)bO.delete(Z)}}function Wh4(){for(let $ of bO.values())$.abort.abort();bO.clear()}var ag4,sg4,PM8,zM8,T51,Yh4,Gh4,bO;var Wa=O(()=>{SU();n7();q5();N41();yr();ci();b8();ag4=Symbol.for("decocms.sandbox.lifecycle.runners"),sg4=Symbol.for("decocms.sandbox.lifecycle.inflight"),PM8=globalThis,zM8=PM8[ag4]??={},T51=PM8[sg4]??={};Yh4=Symbol.for("decocms.sandbox.lifecycle.shared-lifecycles"),Gh4=globalThis,bO=Gh4[Yh4]??=new Map});async function UQ($,Z){let{userId:X,branch:Q,virtualMcpMetadata:Y,explicitKind:G}=Z;if(G)return Ha($,G);if($.sandboxPreference==="agent-sandbox")return Ha($,"agent-sandbox");if($.sandboxPreference==="cluster-default")return Ha($,Hj());let[J,...K]=Hh4(Y,X,Q);if(J)return Ha($,K.length===0?J:Nh4(J,K));return Ha($,IM8())}function Hh4($,Z,X){let Q=n5($)[Z]?.[X];if(!Q)return[];let Y=zJ(Q);return Object.keys(Y)}function Nh4($,Z){let X=IM8();if(X===$||Z.includes(X))return X;return $}function IM8(){return Hj()}async function Ha($,Z){let X=Z==="user-desktop"?"agent-sandbox":Z;return{provider:await R51($,X),kind:X}}var yO=O(()=>{R6();SU();KY();Wa()});var Na;var M51=O(()=>{Na={npm:{install:"npm install",run:($)=>`npm run ${$}`,runtime:"node"},pnpm:{install:"pnpm install",run:($)=>`pnpm run ${$}`,runtime:"node"},yarn:{install:"yarn install",run:($)=>`yarn run ${$}`,runtime:"node"},bun:{install:"bun install",run:($)=>`bun run ${$}`,runtime:"bun"},deno:{install:"deno install",run:($)=>`deno task ${$}`,runtime:"deno"}}});function OK($,Z){return Z?`thread:${$}/${Z}`:`thread:${$}`}function gU($){return`sandbox/thread-${$.replace(/^thread:/,"").replace(/\//g,"-")}`}function gO($){if(!$||!$.startsWith("thread:"))return null;return $.slice(7).split("/")[0]||null}async function hU($,Z,X){let Q=gO(Z);if(!Q)return X;return(await $.storage.threads.get(Q).catch(()=>null))?.created_by??X}async function u_($,Z){if(!Z)return null;let X=await $.storage.threads.get(Z).catch(()=>null);if(!X)return null;return X.metadata??{}}async function qM8($,Z){let Q=(await u_($,Z))?.headRef;return typeof Q==="string"&&Q.length>0?Q:null}async function MM8($,Z,X){let Q=await u_($,Z);if(!Q)return;if(Q.headRef===X)return;await $.storage.threads.update(Z,{metadata:{...Q,headRef:X}}).catch((Y)=>console.warn("[thread-repo] setThreadHeadRef failed",Y))}async function hO($,Z){return(await u_($,Z))?.githubRepo??null}function k51($){if($.pinnedRef)return $.pinnedRef;if($.runBranch&&$.runBranch===OK($.threadId))return $.runBranch;if($.threadRepo)return OK($.threadId,$.threadRepo.connectionId);if(!$.agentRepo)return"ephemeral";return $.runBranch??`thread:${$.threadId}`}async function V51($,Z){let Q=(await u_($,Z))?.pinnedRef;return typeof Q==="string"&&Q.length>0?Q:null}async function kM8($,Z){let[X,Q]=await Promise.all([hO($,Z.threadId),V51($,Z.threadId)]);return k51({...Z,threadRepo:X,pinnedRef:Q})}async function VM8($,Z,X,Q,Y,G){let J=await u_($,Z);if(!J)return;let K=fr(n5(J),X,Q,Y,G);await $.storage.threads.update(Z,{metadata:{...J,sandboxMap:K}}).catch((W)=>console.warn("[thread-repo] setThreadSandboxMapEntry failed",W))}async function kj0($,Z){return n5(await u_($,Z))}async function SM8($,Z,X,Q,Y){let G=await u_($,Z);if(!G)return;let J=H41(n5(G),X,Q,Y);if(!J)return;await $.storage.threads.update(Z,{metadata:{...G,sandboxMap:J}}).catch((K)=>console.warn("[thread-repo] removeThreadSandboxMapEntry failed",K))}var LK=O(()=>{KY()});function Vj0($){if(!$)return null;let Z=$.runtime;if(!Z||typeof Z!=="object")return null;let X=Z.env;if(!Array.isArray(X))return null;let Q=[];for(let Y of X){if(!Y||typeof Y!=="object")continue;let G=Y;if(typeof G.key!=="string"||!YZ0.test(G.key))continue;if(G.kind==="literal"&&typeof G.value==="string"){Q.push({key:G.key,kind:"literal",value:G.value});continue}if(G.kind==="secret"&&typeof G.secretId==="string"&&G.secretId.length>0)Q.push({key:G.key,kind:"secret",secretId:G.secretId})}return Q.length===0?null:Q}function CM8($){if(!$)return null;let Z=$.runtime;if(!Z||typeof Z!=="object")return null;let X=Z.submoduleCredentials;if(!Array.isArray(X))return null;let Q=[];for(let Y of X){if(!Y||typeof Y!=="object")continue;let G=Y;if(typeof G.host==="string"&&G.host.length>0&&typeof G.secretId==="string"&&G.secretId.length>0)Q.push({host:G.host,secretId:G.secretId})}return Q.length===0?null:Q}async function _M8($,Z){N0(Z);let X=J0(Z);await Z.access.check();let Q=z1(Z);if(!Q)throw Error("User ID required");let Y=await Z.storage.virtualMcps.findById($.virtualMcpId);if(!Y||Y.organization_id!==X.id)throw Error("Virtual MCP not found");let G=Y.metadata??{},J=n5(G),K=await hU(Z,$.branch,Q),W=WH(J,K,$.branch,$.sandboxProviderKind);return{virtualMcp:Y,metadata:G,userId:Q,sandboxUserId:K,entry:W,organization:X}}function Uh4($){if($===null||!/^\d+$/.test($))return null;let Z=Number($);return Z>=1&&Z<=65535?$:null}function vM8($){let Z=$.runtime??null,Q=Z?.selected??null,Y=Uh4(Z?.port??null),G=Z?.path??null;if(!Q||!(Q in Na))return{packageManager:null,runtime:null,port:Y,packageManagerPath:G,runtimeBinPath:null};let J=Na[Q].runtime;return{packageManager:Q,runtime:J,port:Y,packageManagerPath:G,runtimeBinPath:J==="deno"?"/opt/deno/bin":J==="bun"?"/opt/bun/bin":null}}var Ua=O(()=>{R6();M51();KY();LK()});async function uO($,Z){let X=$.body?.getReader();if(!X)return $.text();let Q=new TextDecoder,Y="",G=0;for(;;){let{done:J,value:K}=await X.read();if(J)break;if(G+=K.byteLength,G>Z)throw await X.cancel().catch(()=>{}),new xM8(`Upstream response exceeded ${Z} bytes`);Y+=Q.decode(K,{stream:!0})}return Y+=Q.decode(),Y}var xM8;var Fa=O(()=>{xM8=class xM8 extends Error{}});async function Sj0({ctx:$,runner:Z,handle:X,orgId:Q,userId:Y,entries:G}){if(!G||G.length===0)return;let J={};for(let W of G){if(W.kind==="literal"){J[W.key]=W.value;continue}try{let{value:H}=await $.storage.secrets.resolveById(W.secretId,Q,Y);J[W.key]=H}catch(H){if(H instanceof K3||H instanceof uB){console.warn(`[SANDBOX_START] skipping env ${W.key}: ${H.message}. Re-link or recreate the secret to restore.`);continue}throw H}}if(Object.keys(J).length===0)return;let K=await Z.proxyDaemonRequest(X,"/_sandbox/config",{method:"PUT",headers:new Headers({"content-type":"application/json"}),body:JSON.stringify({env:J})});if(!K.ok){let W=await uO(K,Fh4).catch(()=>K.statusText);console.warn(`[SANDBOX_START] daemon rejected env patch (${K.status}): ${W}`)}}var Fh4=10485760;var S51=O(()=>{Wt();Fa()});async function fM8({ctx:$,orgId:Z,userId:X,entries:Q}){if(!Q||Q.length===0)return[];let Y=[];for(let G of Q)try{let{value:J}=await $.storage.secrets.resolveById(G.secretId,Z,X);Y.push({host:G.host,token:J})}catch(J){if(J instanceof K3||J instanceof uB){console.warn(`[SANDBOX_START] skipping submodule credential for ${G.host}: ${J.message}. Re-link or recreate the secret to restore.`);continue}throw J}return Y}var bM8=O(()=>{Wt()});async function hM8($,Z,X,Q,Y){let G=await EU({connectionId:$,tokenStorage:new _5(Q,Y)});if(!G.accessToken)return null;return cM8(Z,X,G.accessToken)}function uM8($,Z){return cM8($,Z,null)}async function cM8($,Z,X){let Q=new Map,Y=new Set(yM8.map((W)=>W.path));for(let W of Object.values(gM8))for(let H of W??[])Y.add(H);await Promise.all(Array.from(Y).map(async(W)=>{Q.set(W,await Bh4($,Z,W,X))}));let G=yM8.find(({path:W})=>Q.get(W)!==null);if(!G)return null;let J=gM8[G.pm]??[],K=null;for(let W of J)if(K=Oh4(Q.get(W)??null),K)break;return{packageManager:G.pm,devPort:K}}async function Bh4($,Z,X,Q){let Y=`https://api.github.com/repos/${$}/${Z}/contents/${encodeURIComponent(X)}`;try{let G={Accept:"application/vnd.github+json","User-Agent":"studio-runtime-detect"};if(Q)G.Authorization=`token ${Q}`;let J=await fetch(Y,{headers:G,signal:AbortSignal.timeout(5000)});if(!J.ok)return null;let K=await J.json();if(!K.content||K.encoding!=="base64")return null;return Buffer.from(K.content,"base64").toString("utf8")}catch{return null}}function Oh4($){if(!$)return null;try{let Z=JSON.parse($),X=Z.tasks??Z.scripts??{};return(X.dev??X.start??"").match(wh4)?.[1]??null}catch{return null}}var yM8,gM8,wh4;var lM8=O(()=>{KO();eJ();yM8=[{path:"deno.json",pm:"deno"},{path:"deno.jsonc",pm:"deno"},{path:"bun.lock",pm:"bun"},{path:"bunfig.toml",pm:"bun"},{path:"pnpm-lock.yaml",pm:"pnpm"},{path:"yarn.lock",pm:"yarn"},{path:"package-lock.json",pm:"npm"},{path:"package.json",pm:"bun"}],gM8={deno:["deno.json","deno.jsonc"],bun:["package.json"],pnpm:["package.json"],yarn:["package.json"],npm:["package.json"]},wh4=/(?:--port|PORT=|:)(\d{4,5})/});function Lh4($){return($??"").normalize("NFKD").replace(/[\u0300-\u036F]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"user"}function Cj0($){return $?.name||$?.email?.split("@")[0]||void 0}function _j0($){let Z=Lh4($),X=Date.now().toString(36).split("").reverse().join("");return`${Z}-${X}`}function dM8($){let{current:Z,detached:X,base:Q}=$.status??{};if(typeof Z!=="string"||Z.length===0)return null;if(X===!0)return null;if(Z===$.requestedRef)return null;if(Dh4.has(Z))return null;if(typeof Q==="string"&&Q.length>0&&Z===Q)return null;return Z}function mM8($){if(!$.branch.startsWith("thread:"))return $.branch;if($.sticky&&$.recordedHeadRef)return $.recordedHeadRef;return $.derivedRef}var Dh4;var C51=O(()=>{Dh4=new Set(["main","master","trunk","develop","HEAD"])});async function iM8($,Z){if(!$)return{hosts:[],allowSameHostDev:!1};let X;try{X=await $.presignedGetUrl("link-dispatch/_allowlist_probe",60,{requireFetchable:!0})}catch{return{hosts:[],allowSameHostDev:!1}}let Q;try{Q=new URL(X)}catch{return{hosts:[],allowSameHostDev:!1}}if(Q.protocol!=="https:"&&Q.protocol!=="http:")return{hosts:[],allowSameHostDev:!1};let Y=Q.hostname,G=Eh4.has(Y);return{hosts:[Y],allowSameHostDev:G&&!Z.isProduction}}var Eh4;var nM8=O(()=>{Eh4=new Set(["127.0.0.1","localhost","::1","[::1]","0.0.0.0"])});import{z as BH}from"zod";async function ph($,Z){N0(Z);let X=J0(Z),Q=z1(Z);if(!Q)throw Error("User ID required");let Y=await Z.storage.virtualMcps.findById($.virtualMcpId);if(!Y||Y.organization_id!==X.id)throw Error("Virtual MCP not found");let G=Y.metadata??{},J=await hU(Z,$.branch,Q),K=WH(n5(G),J,$.branch,$.sandboxProviderKind),W=$.sandboxProviderKind,{provider:H}=await UQ(Z,{userId:J,branch:$.branch,virtualMcpMetadata:G,explicitKind:W});if(K){if(W!=="user-desktop")return K;if(await H.alive(K.sandboxHandle).catch(()=>!1))return K;await TO(Z.storage.virtualMcps,$.virtualMcpId,Q,J,$.branch,W).catch((B)=>{console.warn("[ensureSandbox] failed to reap stale user-desktop entry",B)})}let U=await hO(Z,gO($.branch)??Z.metadata?.threadId)??G.githubRepo??null,{entry:F}=await tM8({ctx:Z,userId:Q,sandboxUserId:J,orgId:X.id,virtualMcpId:$.virtualMcpId,branch:$.branch,metadata:G,githubRepo:U,existing:null,providerKind:W,runner:H,...$.cloneOnly?{cloneOnly:!0}:{}});return F}async function tM8($){let{ctx:Z,userId:X,sandboxUserId:Q,orgId:Y,virtualMcpId:G,branch:J,metadata:K,githubRepo:W,existing:H,runner:N,cloneOnly:U}=$,{runtime:F,packageManager:w,port:B,packageManagerPath:L}=vM8(K),D;if(W){if(W.connectionId)await Sh({ctx:Z,connectionId:W.connectionId,organizationId:Y,forceRefresh:!0,onLegacyMintError:(p0)=>{console.error("[provisionSandbox] repo-scoped legacy token mint failed",{connectionId:W.connectionId,error:p0.message})}});let{cloneUrl:R0,gitUserName:$0,gitUserEmail:s}=W.connectionId?await RO(W.connectionId,W.owner,W.name,Z.db,Z.vault):WP8(W.owner,W.name);if(!w){let p0=W.connectionId?await hM8(W.connectionId,W.owner,W.name,Z.db,Z.vault):await uM8(W.owner,W.name);if(p0)w=p0.packageManager,F=Na[p0.packageManager].runtime,B=p0.devPort??B,await jh4(Z,G,X,p0.packageManager,p0.devPort)}let A0=Z1().sandboxStickyHeadRefEnabled,Q0=mM8({branch:J,derivedRef:gU(J),recordedHeadRef:A0?await qM8(Z,gO(J)):null,sticky:A0}),I0=await fM8({ctx:Z,orgId:Y,userId:X,entries:CM8(K)});D={cloneUrl:R0,...W.connectionId?{connectionId:W.connectionId}:{},userName:$0,userEmail:s,branch:Q0,displayName:`${W.owner}/${W.name}`,...I0.length>0?{submoduleCredentials:I0}:{}}}let E=typeof K.productionUrl==="string"&&K.productionUrl.trim()?K.productionUrl.trim():void 0,z=F&&w&&!U?{runtime:F,packageManager:w,...B!==null?{devPort:Number(B)}:{},...L?{packageManagerPath:L}:{},...E?{productionUrl:E}:{}}:void 0,j=_r({orgId:Y,virtualMcpId:G,branch:J}),A=N.kind==="user-desktop"?await iM8(Z.objectStorage,{isProduction:Z1().nodeEnv==="production"}):null,P=(N.kind==="user-desktop"||N.kind==="agent-sandbox")&&!Z1().orgFsMountsDisabled,q;if(P){let R0=Z.organization?.slug??(await Z.db.selectFrom("organization").select(["slug"]).where("id","=",Y).executeTakeFirst())?.slug;if(R0)q=await DB8(Z,{orgSlug:R0,orgId:Y,baseUrl:kQ()})}await Ah4(N);let k=await N.ensure({userId:Q,projectRef:j},{branch:J,repo:D,workload:z,cloneOnly:U===!0,tenant:{orgId:Y,userId:Q,...Z.organization?.slug?{orgSlug:Z.organization.slug}:{},...Z.organization?.name?{orgName:Z.organization.name}:{},...Z.auth.user?.email?{userEmail:Z.auth.user.email}:{},...Z.auth.user?.name?{userName:Z.auth.user.name}:{}},...A?{offloadAllowedHosts:A.hosts,offloadAllowSameHostDev:A.allowSameHostDev}:{},...q?{orgFsConfigJson:q}:{}}),M=K.runtime?.env??null;await Sj0({ctx:Z,runner:N,handle:k.handle,orgId:Y,userId:X,entries:M});let d=!!H&&H.sandboxHandle===k.handle&&H?.createdAt?H.createdAt:Date.now(),v=K.runtime?.selected??null,b=K.runtime?.port??null,t=K.runtime?.path??null,y={sandboxHandle:k.handle,previewUrl:k.previewUrl,sandboxApiUrl:k.previewUrl,sandboxProviderKind:N.kind,createdAt:d,startedWith:{packageManager:v,port:b,path:t}};await sj8(Z.storage.virtualMcps,G,X,Q,J,$.providerKind,y);let Z0=gO(J);if(Z0)await VM8(Z,Z0,Q,J,$.providerKind,y);let D0=!H||H.sandboxHandle!==k.handle;return{entry:y,isNewVm:D0}}async function jh4($,Z,X,Q,Y){let G=await $.storage.virtualMcps.findById(Z);if(!G)return;let J=G.metadata??{};await $.storage.virtualMcps.update(Z,X,{metadata:{...J,runtime:{selected:Q,port:Y}}})}async function Ah4($){if(!$.hasSchedulableCapacity)return;let Z=Date.now()+pM8,X=!1;while(!await $.hasSchedulableCapacity()){if(Date.now()>=Z)throw Error(`sandbox provisioning failed: the cluster has had no room to schedule another sandbox for ${Math.round(pM8/1000)}s`);if(!X)X=!0,console.warn("[ensureSandbox] waiting for cluster capacity \u2014 a sandbox pod cannot be scheduled right now");await _8(Ph4)}}var zh4,_51,pM8=150000,Ph4=5000;var wa=O(()=>{SU();H$();t0();Ua();S51();bM8();KY();yr();lM8();M51();yO();LK();C51();nM8();b8();YZ();po();KY();zh4=BH.enum(["agent-sandbox","user-desktop","cluster"]),_51=o({name:"SANDBOX_START",description:"Start a sandbox with the connected GitHub repo and dev server.",annotations:{title:"Start VM Preview",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0},_meta:{ui:{visibility:"app"}},inputSchema:BH.object({virtualMcpId:BH.string().describe("Virtual MCP ID"),branch:BH.string().min(1).optional().describe("Git branch to check out. Pass the thread's branch whenever the caller has one: when omitted the handler mints a fresh `<user-slug>-<timestamp>` name, which becomes a SEPARATE sandbox from the one the thread's own branch resolves to. The resolved branch is returned in the response so callers can persist it."),sandboxProviderKind:zh4.optional().describe("Explicit runtime choice. Hosted provider is `agent-sandbox`; legacy `cluster` input is accepted only for compatibility and normalized to `agent-sandbox`. When omitted, defaults to `user-desktop` if the acting user's link daemon is online, else the env kind.")}),outputSchema:BH.object({previewUrl:BH.string().nullable(),sandboxHandle:BH.string(),branch:BH.string(),isNewVm:BH.boolean(),sandboxProviderKind:BH.enum(["agent-sandbox","user-desktop"])}),handler:async($,Z)=>{N0(Z);let X=J0(Z);await Z.access.check();let Q=$.branch??_j0(Cj0(Z.auth.user)),Y=z1(Z);if(!Y)throw Error("User ID required");let G=await hU(Z,Q,Y),J=await Z.storage.virtualMcps.findById($.virtualMcpId);if(!J||J.organization_id!==X.id)throw Error("Virtual MCP not found");let K=J.metadata??{},W=$.sandboxProviderKind?Kj($.sandboxProviderKind):void 0,{provider:H,kind:N}=await UQ(Z,{userId:G,branch:Q,virtualMcpMetadata:K,explicitKind:W}),U=WH(n5(K),G,Q,N),w=await hO(Z,gO(Q)??Z.metadata?.threadId)??K.githubRepo??null,{entry:B,isNewVm:L}=await tM8({ctx:Z,userId:Y,sandboxUserId:G,orgId:X.id,virtualMcpId:$.virtualMcpId,branch:Q,metadata:K,githubRepo:w,existing:U,providerKind:N,runner:H});return{...B,branch:Q,isNewVm:L,sandboxProviderKind:N}}})});function Th4($){let{publicUrl:Z,agentId:X,organization:Q,target:Y,threadId:G}=$;if(Y==="agent-tools")return`${Z}/mcp/virtual-mcp/${X}`;if(!Q.slug)throw new rM8(Q.id);if(Y==="task-run"){if(!G)throw Error("a task-run MCP endpoint is scoped to a run: threadId is required");return`${Z}/api/${Q.slug}/mcp/task-run/${encodeURIComponent(G)}`}return`${Z}/api/${Q.slug}/mcp/self`}async function vj0($,Z,X,Q,Y="agent-tools",G){let J=Th4({publicUrl:kQ(),agentId:Z,organization:X,target:Y,...G?{threadId:G}:{}}),K=await $.boundAuth.apiKey.create({name:Q,permissions:{"*":["*"]},expiresIn:oM8,metadata:{organization:{id:X.id,slug:X.slug,name:X.name}}});return{url:J,headers:{Authorization:`Bearer ${K.key}`,"x-org-id":X.id},expiresAt:Date.now()+oM8*1000}}var oM8=3600,rM8;var v51=O(()=>{YZ();rM8=class rM8 extends Error{constructor($){super(`cannot mint a management MCP endpoint for organization "${$}": the org-scoped path /api/<slug>/mcp/self needs the org slug, which was not loaded.`);this.name="MissingOrganizationSlugError"}}});async function Rh4($,Z,X,Q){try{let Y=$.organization;if(!Y)return;let G=await vj0($,Q.virtualMcpId,Y,"tool-scripting"),J=await Z.proxyDaemonRequest(X,"/_sandbox/tools/sync",{method:"POST",headers:new Headers({"content-type":"application/json"}),body:JSON.stringify(G)});if(!J.ok)console.warn("[cluster-sandbox-fs] tools/sync failed",J.status,await J.text().catch(()=>""))}catch(Y){console.warn("[cluster-sandbox-fs] tools/sync failed",Y)}}async function th($,Z){let{provider:X,kind:Q}=await UQ($,{userId:Z.userId,branch:Z.branch,virtualMcpMetadata:null}),Y=null,G=()=>{if(!Y){if(Y=ph({virtualMcpId:Z.virtualMcpId,branch:Z.branch,sandboxProviderKind:Q},$).then((W)=>W.sandboxHandle),Y.catch(()=>{Y=null}),Z.syncTools)Y.then((W)=>Rh4($,X,W,{virtualMcpId:Z.virtualMcpId,providerKind:Q})).catch(()=>{})}return Y},J=Z.branch==="ephemeral"||Q==="user-desktop";return W41(X,{ensureHandle:G,invalidateHandle:async(W)=>{let H=Y;if(Y=null,!J&&!W?.force)return;try{await TO($.storage.virtualMcps,Z.virtualMcpId,Z.userId,Z.userId,Z.branch,Q)}catch(N){console.warn("[cluster-sandbox-fs] failed to reap vmMap entry",N)}if(H&&typeof X.forgetHandle==="function")try{let N=await H;await X.forgetHandle(N)}catch(N){console.warn("[cluster-sandbox-fs] forgetHandle failed",N)}},canAutoRestart:J})}async function aM8($,Z){try{let X=await th($,Z),{stdout:Q}=await X.onBash("test -d .deco && echo __DECO_SITE__");return Q.includes("__DECO_SITE__")}catch(X){return console.warn("[cluster-sandbox-fs] .deco probe failed; assuming deco site",X),!0}}var xj0=O(()=>{SU();v51();yO();wa();KY()});import{z as sM8}from"zod";function oh($){let Z=[];for(let X of $){if(X.status!=="active")continue;let Q=YQ(X);if(!Q)continue;Z.push({connectionId:X.id,owner:Q.owner,repo:Q.repo,installationId:Q.installationId})}return Z}async function qh4($,Z){let{items:X}=await $.storage.connections.list(Z,{slug:"mcp-github"});return oh(X)}function Mh4($){let Z=$.split(`
|
|
2493
|
+
`))>=0){let W=Q.slice(0,K).trim();if(Q=Q.slice(K+1),!W)continue;yield JSON.parse(W)}}let Y=Q.trim();if(Y)yield JSON.parse(Y)}finally{Z.releaseLock()}}var xq8,J51,gq8="gateway.networking.k8s.io",hq8="v1",uq8="httproutes",Qg4,Ga,lq8="mesh-sandbox-runner";var Ja=O(()=>{H$();Qa();xq8=class xq8 extends Error{status;body;constructor($,Z,X){super(X);this.status=$;this.body=Z;this.name="KubeHttpError"}};J51=`/apis/${v9.CLAIM_API_GROUP}/${v9.CLAIM_API_VERSION}/namespaces`;Qg4=`/apis/${gq8}/${hq8}/namespaces`;Ga={API_GROUP:gq8,API_VERSION:hq8,PLURAL:uq8}});function Gg4($){return($.items??[]).some((Z)=>{if(Z.status?.phase!=="Pending")return!1;return(Z.status?.conditions??[]).some((X)=>X.type==="PodScheduled"&&X.status==="False"&&X.reason==="Unschedulable")})}function iq8($,Z){let X=0,Q=!0,Y=null,G=async()=>{try{let J=await FK($,{method:"GET",path:`/api/v1/namespaces/${encodeURIComponent(Z)}/pods?fieldSelector=status.phase%3DPending`});if(!J.ok)return mq8;let K=await J.json();return!Gg4(K)}catch{return mq8}};return async()=>{if(Date.now()-X<Yg4)return Q;return Y??=G().finally(()=>{Y=null}),Q=await Y,X=Date.now(),Q}}var Yg4=3000,mq8=!0;var nq8=O(()=>{Ja()});var N51=O(()=>{H$();G41()});async function Ij0($){try{let Z=await fetch(`${$}/health`,{signal:AbortSignal.timeout(Jg4)});if(!Z.ok)return null;let X=await Z.json();if(typeof X==="object"&&X!==null&&typeof X.bootId==="string"&&typeof X.ready==="boolean"&&X.setup&&typeof X.setup.running==="boolean"&&typeof X.setup.done==="boolean")return X;return null}catch{return null}}async function F51($){for(let Z=0;Z<pq8;Z++){if(await Ij0($)!==null)return;let X=(Math.random()*2-1)*Kg4;await _8(tq8+X)}throw Error(`sandbox daemon at ${$} did not respond on /health within ${pq8*tq8/1000}s`)}async function y_($,Z,X,Q,Y){return Wg4($,Z,"POST",X,Q,Y)}async function Wg4($,Z,X,Q,Y,G){let J={...Q};if(Y&&Y.rotateToken!==void 0)J.auth=Y;let K=await fetch(`${$}/_sandbox/config`,{method:X,headers:{"Content-Type":"application/json",Authorization:`Bearer ${Z}`},body:JSON.stringify(J),signal:AbortSignal.timeout(G?.timeoutMs??U51)}),W=await K.text();if(!K.ok)throw new Rj0(K.status,W);return JSON.parse(W)}async function oq8($,Z,X){let Q=await fetch(`${$}/_sandbox/setup/${X}`,{method:"POST",headers:{Authorization:`Bearer ${Z}`},signal:AbortSignal.timeout(U51)});if(!Q.ok)throw Error(`sandbox daemon /_sandbox/setup/${X} returned ${Q.status}: ${await Q.text()}`)}async function rq8($,Z,X){let Q=await fetch(`${$}/_sandbox/orgfs-config`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Z}`},body:X,signal:AbortSignal.timeout(U51)}),Y=await Q.text();if(!Q.ok)throw Error(`sandbox daemon /_sandbox/orgfs-config returned ${Q.status}: ${Y}`);return JSON.parse(Y)}async function Ka($,Z,X,Q){let Y=new Headers(Q.headers);for(let K of Hg4)Y.delete(K);Y.set("authorization",`Bearer ${Z}`);let G=Q.method!=="GET"&&Q.method!=="HEAD",J=`${$}${X.startsWith("/")?X:`/${X}`}`;return fetch(J,{method:Q.method,headers:Y,body:G?Q.body:void 0,redirect:"manual",signal:Q.signal,duplex:G?"half":void 0})}var Rj0,Jg4=500,U51=30000,pq8=25,tq8=200,Kg4=50,Hg4;var aq8=O(()=>{N51();Rj0=class Rj0 extends Error{status;constructor($,Z){super(`sandbox daemon /_sandbox/config returned ${$}: ${Z}`);this.status=$;this.name="ConfigRequestError"}};Hg4=["cookie","host","connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","accept-encoding","content-length"]});async function*$M8($){let Z=$.now??(()=>Date.now()),X=Z(),Q=$.schedulingTimeoutMs??Fg4,Y={pod:{},sandbox:{},events:{hasPulling:!1,hasPulled:!1},startedAt:X},G=[],J=null,K=!1,W=(z)=>{if(K)return;if(J){let j=J;J=null,j(z)}else G.push(z)},H=()=>{if(G.length>0)return Promise.resolve(G.shift());if(K)return Promise.resolve(null);return new Promise((z)=>{J=z})},N=()=>{if(K)return;if(K=!0,J){let z=J;J=null,z(null)}},U=new AbortController,F=()=>{U.abort(),N()};if($.signal)if($.signal.aborted)U.abort(),N();else $.signal.addEventListener("abort",F,{once:!0});let w=Math.max(0,Q-(Z()-X)),B=setTimeout(()=>W("tick"),w+100),L,D=new Promise((z)=>{L=z}),E=Promise.allSettled([wg4($.kc,$.namespace,$.claimName,U.signal,Y,W,Z,L),Og4($.kc,$.namespace,$.claimName,U.signal,Y,W),Lg4($.kc,$.namespace,$.claimName,D,U.signal,Y,W,Z)]);try{let z=null,j=-1,A=sq8(Y,Q,Z);if(z=B51(A),!w51(A))j=eq8(A);if(yield A,w51(A))return;while(!K){if(await H()===null)break;let q=sq8(Y,Q,Z);if(w51(q)){let C=B51(q);if(C!==z)z=C,yield q;return}let k=eq8(q);if(k<j)continue;let M=B51(q);if(M!==z)z=M,j=k,yield q}}finally{if(clearTimeout(B),U.abort(),$.signal)$.signal.removeEventListener("abort",F);N(),await E.catch(()=>{})}}function sq8($,Z,X){let{pod:Q,sandbox:Y,events:G,startedAt:J}=$;if(Y.ready)return{kind:"ready"};let K=Q.containerWaitingReason;if(K==="ImagePullBackOff"||K==="ErrImagePull")return{kind:"failed",reason:"image-pull-backoff",message:"Sandbox image failed to download. The cluster may be missing pull credentials or the image tag may not exist."};if(K==="CrashLoopBackOff")return{kind:"failed",reason:"crash-loop-backoff",message:"Sandbox crashed during startup and is now in CrashLoopBackOff. Check pod logs."};if(!Q.scheduled&&G.lastFailedSchedulingAt!==void 0&&X()-J>Z)return{kind:"failed",reason:"scheduling-timeout",message:G.failedSchedulingMessage??`Pod could not be scheduled within ${Math.round(Z/1000)}s.`};if(Q.containerRunning&&!Q.containerReady)return{kind:"warming-daemon",since:J};if(G.hasPulling&&!G.hasPulled)return{kind:"pulling-image",since:J};if(K==="ContainerCreating"||K==="PodInitializing"||Q.scheduled&&!Q.containerRunning)return{kind:"starting-container",since:J};if(Q.scheduledFalseReason==="Unschedulable"||G.lastFailedSchedulingAt!==void 0&&!Q.scheduled)return{kind:"waiting-for-capacity",since:J,message:G.failedSchedulingMessage??Q.scheduledFalseMessage,nodeClaim:G.nominatedNodeClaim};return{kind:"claiming",since:J}}function w51($){return $.kind==="ready"||$.kind==="failed"}function eq8($){switch($.kind){case"claiming":return 0;case"waiting-for-capacity":return 1;case"pulling-image":return 2;case"starting-container":return 3;case"warming-daemon":return 4;case"ready":case"failed":return 99}}function B51($){switch($.kind){case"claiming":case"pulling-image":case"starting-container":case"warming-daemon":return $.kind;case"waiting-for-capacity":return`waiting-for-capacity:${$.message??""}:${$.nodeClaim??""}`;case"ready":return"ready";case"failed":return`failed:${$.reason}:${$.message}`}}async function wg4($,Z,X,Q,Y,G,J,K){let W=`/api/v1/namespaces/${encodeURIComponent(Z)}/pods?watch=true&labelSelector=${encodeURIComponent(`${Ng4}=${X}`)}`;return qj0({kc:$,path:W,signal:Q,label:`pod/${X}`,onEvent:(H)=>{if(H.type!=="ADDED"&&H.type!=="MODIFIED")return;let N=H.object;if(N.metadata?.name)K(N.metadata.name);Bg4(N,Y,J),G("pod")}})}function Bg4($,Z,X){let Y=($.status?.conditions??[]).find((J)=>J.type==="PodScheduled");if(Y?.status==="True")Z.pod.scheduled=!0,Z.pod.scheduledFalseReason=void 0,Z.pod.scheduledFalseMessage=void 0;else if(Y?.status==="False")Z.pod.scheduled=!1,Z.pod.scheduledFalseReason=Y.reason,Z.pod.scheduledFalseMessage=Y.message;let G=($.status?.containerStatuses??[]).find((J)=>J.name===Ug4);if(G)Z.pod.containerWaitingReason=G.state?.waiting?.reason,Z.pod.containerRunning=!!G.state?.running,Z.pod.containerReady=G.ready===!0}async function Og4($,Z,X,Q,Y,G){let J=`/apis/${v9.CLAIM_API_GROUP}/${v9.CLAIM_API_VERSION}/namespaces/${encodeURIComponent(Z)}/${v9.CLAIM_PLURAL}?watch=true&fieldSelector=${encodeURIComponent(`metadata.name=${X}`)}`;return qj0({kc:$,path:J,signal:Q,label:`sandboxclaim/${X}`,onEvent:(K)=>{if(K.type!=="ADDED"&&K.type!=="MODIFIED")return;let H=K.object.status?.conditions?.find((N)=>N.type==="Ready");if(!H)return;if(H.status==="True")Y.sandbox.ready=!0,Y.sandbox.notReadyReason=void 0,Y.sandbox.notReadyMessage=void 0;else Y.sandbox.ready=!1,Y.sandbox.notReadyReason=H.reason,Y.sandbox.notReadyMessage=H.message;G("sandbox")}})}async function Lg4($,Z,X,Q,Y,G,J,K){let W=await Promise.race([Q,new Promise((N)=>{if(Y.aborted){N(X);return}Y.addEventListener("abort",()=>N(X),{once:!0})})]);if(Y.aborted)return;let H=`/api/v1/namespaces/${encodeURIComponent(Z)}/events?watch=true&fieldSelector=${encodeURIComponent(`involvedObject.name=${W},involvedObject.kind=Pod`)}`;return qj0({kc:$,path:H,signal:Y,label:`events/${X}`,onEvent:(N)=>{if(N.type!=="ADDED"&&N.type!=="MODIFIED")return;let U=N.object,F=U.reason;if(!F)return;switch(F){case"Pulling":G.events.hasPulling=!0;break;case"Pulled":G.events.hasPulling=!0,G.events.hasPulled=!0;break;case"FailedScheduling":G.events.lastFailedSchedulingAt=K(),G.events.failedSchedulingMessage=U.message;break;case"Nominated":{let w=U.message?.match(/nodeclaim\/([\w-]+)/);if(w)G.events.nominatedNodeClaim=w[1];break}default:return}J("event")}})}async function ZM8($){let{kc:Z,namespace:X,labelSelector:Q,signal:Y,onDelete:G}=$,J=`/apis/${v9.CLAIM_API_GROUP}/${v9.CLAIM_API_VERSION}/namespaces/${encodeURIComponent(X)}/${v9.CLAIM_PLURAL}?watch=true&labelSelector=${encodeURIComponent(Q)}`;return qj0({kc:Z,path:J,signal:Y,label:"sandboxclaim-reaper",onEvent:(K)=>{if(K.type!=="DELETED")return;let W=K.object.metadata?.name;if(W)G(W)}})}async function qj0($){let{kc:Z,path:X,signal:Q,label:Y,onEvent:G}=$,J=0;while(!Q.aborted){try{let W=await FK(Z,{method:"GET",path:X,signal:Q,headers:{accept:"application/json"},stream:!0});if(!W.ok||!W.body){try{await W.body?.cancel()}catch{}if(W.status===401||W.status===403){console.warn(`[lifecycle-watcher] ${Y} stopped: watch denied (${W.status} ${W.statusText}). `+"The kubeconfig in use cannot watch SandboxClaims \u2014 if you are running locally, "+"this provider should not be active (check STUDIO_SANDBOX_PROVIDER / your sandbox preference).");return}throw Error(`watch handshake failed: ${W.status} ${W.statusText}`)}J=0;for await(let H of H51(W.body)){if(Q.aborted)return;try{G(H)}catch(N){console.warn(`[lifecycle-watcher] ${Y} onEvent threw: ${N instanceof Error?N.message:String(N)}`)}}}catch(W){if(Q.aborted)return;let H=W instanceof Error?W.message:String(W);console.warn(`[lifecycle-watcher] ${Y} watch ended: ${H}`)}if(Q.aborted)return;let K=CX(5000,250,J,2,0);J+=1,await _8(K,{signal:Q}).catch(()=>{})}}var Ng4="studio.decocms.com/sandbox-handle",Ug4="sandbox",Fg4=300000;var XM8=O(()=>{H$();Qa();Ja()});import{z as I3}from"zod";function QM8($){if(!$||$.trim()==="")return[];let Z=I3.array(Dg4).parse(JSON.parse($)),X=new Set;for(let Q of Z){if(X.has(Q.name))throw Error(`STUDIO_SANDBOX_TENANT_POOLS: duplicate pool name ${Q.name}`);X.add(Q.name)}return Z}function Eg4($){try{let[Z,X]=new URL($).pathname.replace(/^\/+/,"").split("/"),Q=X?.replace(/\.git$/,"");return Z&&Q?`${Z}/${Q}`.toLowerCase():null}catch{return null}}function YM8($,Z){let{orgId:X,cloneUrl:Q}=Z;if(Z.cloneOnly===!0)return null;if(!X||!Q)return null;let Y=Eg4(Q);if(!Y)return null;return $.find((G)=>G.orgId===X&&G.repo.toLowerCase()===Y)??null}function GM8($,Z,X){return $?.name??(Z?X:"none")}function JM8($,Z,X){let Q=X.replace(/^refs\/heads\//,"");return $.filter((Y)=>Y.repo.toLowerCase()===Z.toLowerCase()&&Y.branch===Q)}function KM8($){return`https://github.com/${$.repo}.git`}var Dg4;var O51=O(()=>{Dg4=I3.object({name:I3.string().regex(/^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/,"pool name must be a DNS label (lowercase alphanumeric and '-')"),orgId:I3.string().min(1),repo:I3.string().regex(/^[^/\s]+\/[^/\s]+$/,"repo must be `owner/name`"),connectionId:I3.string().min(1).optional(),branch:I3.string().min(1).default("main"),workload:I3.object({runtime:I3.enum(["node","bun","deno"]).default("node"),packageManager:I3.enum(["npm","pnpm","yarn","bun","deno"]).optional(),packageManagerPath:I3.string().optional(),devPort:I3.number().int().positive().optional()}).default({runtime:"node"})})});async function WM8($,Z,X){let Q=new Map;for(let Y of $){let G=Z(Y);if(!G)continue;let J=Q.get(G);if(J)J.push(Y);else Q.set(G,[Y])}await Promise.allSettled([...Q.values()].map(async(Y)=>{for(let G of Y)await X(G).catch(()=>{})}))}import{createHash as zg4,randomBytes as jg4,randomUUID as Pg4}from"crypto";import*as BM8 from"net";import{PassThrough as Ag4}from"stream";function Tg4($){if($ instanceof Error)return $.message;if($&&typeof $==="object"){let Z=$;if(Z.error instanceof Error)return Z.error.message;if(typeof Z.message==="string"&&Z.message)return Z.message}return String($)}class P51{kind=wY;records=new Map;inflight=new a30;stateStore;previewUrlPattern;kubeConfig;capacityProbe;portForward;namespace;sandboxTemplateName;envName;tokenGenerator;idleTtlMs;metrics;previewGateway;sentinelToken;mintCloneUrl;tenantPools;tenantPoolRefreshMs;poolPods=new Map;dirtyPools=new Set;closed=!1;claimWatchAbort=new AbortController;constructor($={}){this.stateStore=$.stateStore??null,this.previewUrlPattern=$.previewUrlPattern??null,this.kubeConfig=$.kubeConfig??bg4(),this.portForward=new c$1(this.kubeConfig),this.namespace=$.namespace??Rg4,this.sandboxTemplateName=$.sandboxTemplateName??Ig4,this.envName=lg4($.envName),this.tokenGenerator=$.tokenGenerator??(()=>jg4(qg4).toString("hex")),this.idleTtlMs=$.idleTtlMs??kg4,this.metrics=$.meter?fg4($.meter):null,this.previewGateway=$.previewGateway&&$.previewUrlPattern?{...$.previewGateway}:null;let Z=$.sentinelToken?.trim()??"";if(this.sentinelToken=Z.length>0?Z:null,this.mintCloneUrl=$.mintCloneUrl,this.tenantPools=this.sentinelToken!==null?$.tenantPools??[]:[],this.sentinelToken===null&&($.tenantPools?.length??0)>0)console.warn(`[${r$}] tenant pools configured without a sentinel token \u2014 ignoring them (warm-pool mode is off)`);this.tenantPoolRefreshMs=$.tenantPoolRefreshMs??Sg4,this.startClaimReaper(),this.startCredentialRefresher(),this.startTenantPoolReconciler()}startClaimReaper(){let $=["app.kubernetes.io/managed-by=studio","app.kubernetes.io/name=studio-sandbox",...this.envName?[`${BY.env}=${this.envName}`]:[]].join(",");ZM8({kc:this.kubeConfig,namespace:this.namespace,labelSelector:$,signal:this.claimWatchAbort.signal,onDelete:(Z)=>this.invalidateRecord(Z)})}async ensure($,Z={}){let X=Wj($);if(X.startsWith("s-"))throw Error(`ensure: projectRef has no slug source: ${$.projectRef}`);return this.inflight.run(X,()=>s30(this.stateStore,$,wY,(Q)=>this.ensureLocked($,X,Z,Q)))}async delete($){let Z=await this.getRecord($);if(this.records.delete($),Z)this.closeForwarder(Z.daemonForward),this.metrics?.active.add(-1,z51(Z.tenant));if(await this.deleteHttpRouteIfManaged($).catch((X)=>{console.warn(`[${r$}] HTTPRoute delete failed for ${$}: ${X instanceof Error?X.message:String(X)}`)}),await fO(this.kubeConfig,this.namespace,$),this.stateStore)if(Z)await this.stateStore.delete(Z.id,wY);else await this.stateStore.deleteByHandle(wY,$)}async alive($){return await wK(this.kubeConfig,this.namespace,$)!==void 0}watchClaimLifecycle($,Z){return $M8({kc:this.kubeConfig,namespace:this.namespace,claimName:$,signal:Z})}hasSchedulableCapacity(){return this.capacityProbe??=iq8(this.kubeConfig,this.namespace),this.capacityProbe()}async getPreviewUrl($){let Z=await this.getRecord($);if(!Z)return null;return this.composePreviewUrl(Z)}async proxyDaemonRequest($,Z,X){let Q=await this.getRecord($);if(!Q&&this.previewUrlPattern&&this.stateStore){let W=await this.stateStore.getByHandle(wY,$),H=W?.state,N=H?.token;if(W&&N){let F=`http://${H?.adoptedSandboxName??$}.${this.namespace}.svc.cluster.local:${yU}`;try{let w=await Ka(F,N,Z,X);if(w.status!==404)return w;try{await w.body?.cancel()}catch{}}catch{}}}if(!Q)Q=await this.resurrectByHandle($);if(!Q)return new Response(JSON.stringify({error:"sandbox not found"}),{status:404,headers:{"content-type":"application/json"}});let Y=Q,G=performance.now(),J=0,K=!(X.body instanceof ReadableStream);try{let W=await Ka(Q.daemonUrl,Q.token,Z,X);if(W.status===401&&K){this.invalidateRecord($);let H=await this.getRecord($).catch(()=>null)??await this.resurrectByHandle($).catch(()=>null);if(H)Y=H,W=await Ka(H.daemonUrl,H.token,Z,X)}return J=W.status,W}catch(W){if(!K)throw W;this.invalidateRecord($);let H=await this.resurrectByHandle($)??await this.getRecord($).catch(()=>null);if(!H)throw W;Y=H;let N=await Ka(H.daemonUrl,H.token,Z,X);return J=N.status,N}finally{this.recordProxyDuration("daemon",J,Y,performance.now()-G)}}async adoptLiveClaim($,Z){if(this.records.has(Z))return!0;let X=await wK(this.kubeConfig,this.namespace,Z).catch(()=>{return});if(!X||X.metadata?.deletionTimestamp)return!1;return await this.inflight.run(Z,async()=>{let Y=this.records.get(Z);if(Y)return this.toSandbox(Y);let G=await this.adopt($,Z,X);if(!G)throw Error(`cannot adopt live claim ${Z}`);return s30(this.stateStore,$,wY,(J)=>this.finish(G,J,!0,!0,"adopt"))}).catch(()=>null)!=null}async resolvePreviewUpstreamUrl($){if(this.previewUrlPattern)return`http://${await this.resolveServiceNameForHandle($)}.${this.namespace}.svc.cluster.local:${yU}`;let Z=await this.getRecord($);if(Z)return Z.daemonUrl;let X=await this.resurrectByHandle($);return X?X.daemonUrl:null}async resolveServiceNameForHandle($){let Z=this.records.get($);if(Z)return Z.adoptedSandboxName;if(this.stateStore){let Q=(await this.stateStore.getByHandle(wY,$).catch(()=>null))?.state?.adoptedSandboxName;if(Q)return Q}return $}async proxyPreviewRequest($,Z){let X=performance.now(),Q=this.records.get($)??null,Y=0;try{let G=await this.resolvePreviewUpstreamUrl($);if(!G){Y=404;let B=D51(404,{error:"sandbox not found"});return B.headers.set(h_,"1"),B}let J=new URL(Z.url);if((J.pathname==="/_sandbox"||J.pathname.startsWith("/_sandbox/")||J.pathname==="/_decopilot_vm"||J.pathname.startsWith("/_decopilot_vm/"))&&Z.method!=="GET")return Y=404,D51(404,{error:"not found"});let W=(B)=>`${B}${J.pathname}${J.search}`,H=new Headers(Z.headers);for(let B of vg4)H.delete(B);let N=Z.method!=="GET"&&Z.method!=="HEAD",U={method:Z.method,headers:H,body:N?Z.body:void 0,redirect:"manual",signal:Z.signal,duplex:N?"half":void 0},F;try{F=await fetch(W(G),U)}catch(B){let L=`${G}${J.pathname}`;if(console.warn(`[${r$}] preview fetch to ${L} failed: ${B instanceof Error?B.message:String(B)}`),Z.method==="GET"||Z.method==="HEAD"){if(this.invalidateRecord($),await this.resurrectByHandle($).catch(()=>null)){let z=await this.resolvePreviewUpstreamUrl($);if(z)try{F=await fetch(W(z),U);let j=new Headers;for(let[A,P]of F.headers.entries())if(!UM8.includes(A.toLowerCase()))j.set(A,P);return Y=F.status,new Response(F.body,{status:F.status,statusText:F.statusText,headers:j})}catch(j){console.warn(`[${r$}] preview fetch retry to ${L} failed: ${j instanceof Error?j.message:String(j)}`)}}}else this.invalidateRecord($);Y=502;let D=D51(502,{error:"sandbox daemon unreachable"});return D.headers.set(h_,"1"),D}let w=new Headers;for(let[B,L]of F.headers.entries())if(!UM8.includes(B.toLowerCase()))w.set(B,L);return Y=F.status,new Response(F.body,{status:F.status,statusText:F.statusText,headers:w})}finally{this.recordProxyDuration("preview",Y,Q,performance.now()-X,$)}}async ensureLocked($,Z,X,Q){if(X.image)console.warn(`[${r$}] opts.image ignored (template ${this.sandboxTemplateName} pins image): got ${X.image}`);if(Q){let J=await Q.get($,wY);if(J){let K=await this.rehydrate($,Z,J);if(K)return await this.refreshDaemonGitCredential(K,X),this.finish(K,Q,!1,!0,"resume");await Q.delete($,wY)}}let Y=await wK(this.kubeConfig,this.namespace,Z).catch(()=>{return});if(Y)if(Y.metadata?.deletionTimestamp)await zj0(this.kubeConfig,this.namespace,Z).catch((J)=>{console.warn(`[${r$}] wait for terminating claim ${Z} failed: ${J instanceof Error?J.message:String(J)}`)});else{let J=await this.adopt($,Z,Y).catch((K)=>{return console.warn(`[${r$}] adopt ${Z} failed, recreating: ${K instanceof Error?K.message:String(K)}`),null});if(J)return await this.refreshDaemonGitCredential(J,X),this.finish(J,Q,!0,!0,"adopt");await fO(this.kubeConfig,this.namespace,Z).catch(()=>{}),await zj0(this.kubeConfig,this.namespace,Z).catch((K)=>{console.warn(`[${r$}] wait for deleted claim ${Z} failed: ${K instanceof Error?K.message:String(K)}`)})}let G=await this.provision($,Z,X);return this.finish(G,Q,!0,!1,"fresh")}async finish($,Z,X,Q,Y){let G=this.records.get($.handle),J=G!==void 0;if(G&&G.daemonForward!==$.daemonForward)this.closeForwarder(G.daemonForward);if(this.records.set($.handle,$),X)await this.persist(Z,$);if(Q)await jj0(this.kubeConfig,this.namespace,$.handle,this.computeShutdownTime()).catch((K)=>console.warn(`[${r$}] TTL refresh failed for ${$.handle}: ${K instanceof Error?K.message:String(K)}`));if(this.metrics){let K=z51($.tenant);if(this.metrics.ensureOutcome.add(1,{...K,outcome:Y}),!J)this.metrics.active.add(1,K)}return this.toSandbox($)}buildEnvMap($,Z){let X={},Q=[];for(let[Y,G]of Object.entries($.env??{}))if(Mg4.has(Y))Q.push(Y);else X[Y]=G;if(Q.length>0)console.warn(`[${r$}] opts.env keys overlap reserved bootstrap names and were dropped: ${Q.join(",")}`);return{...X,DAEMON_TOKEN:Z.token,DAEMON_BOOT_ID:Z.daemonBootId,APP_ROOT:Z.workdir,PROXY_PORT:String(yU)}}buildClaim($,Z,X){let Q=this.sentinelToken!==null,Y=YM8(this.tenantPools,{orgId:Z.tenant?.orgId,cloneUrl:Z.repo?.cloneUrl,cloneOnly:Z.cloneOnly}),G=Q?[]:Object.entries(this.buildEnvMap(Z,X)).sort(([W],[H])=>W<H?-1:W>H?1:0).map(([W,H])=>({name:W,value:H})),J=ig4(Z),K=Object.keys(J).length>0;return{apiVersion:`${v9.CLAIM_API_GROUP}/${v9.CLAIM_API_VERSION}`,kind:"SandboxClaim",metadata:{name:$,namespace:this.namespace,labels:{"app.kubernetes.io/name":"studio-sandbox","app.kubernetes.io/managed-by":"studio",...this.envName?{[BY.env]:this.envName}:{},...E51(Z.tenant)},...K?{annotations:J}:{}},spec:{sandboxTemplateRef:{name:this.sandboxTemplateName},additionalPodMetadata:{labels:E51(Z.tenant,{[BY.role]:"claimed",[BY.sandboxHandle]:$,...this.envName?{[BY.env]:this.envName}:{}}),...K?{annotations:J}:{}},env:G,warmpool:GM8(Y,Q,this.sandboxTemplateName),lifecycle:{shutdownPolicy:"Delete",shutdownTime:this.computeShutdownTime()}}}}async provision($,Z,X){let Q=this.tokenGenerator(),Y=Pg4(),G=L51,J=this.buildClaim(Z,X,{token:Q,daemonBootId:Y,workdir:G});try{await Ya(this.kubeConfig,this.namespace,J)}catch(F){if(F instanceof Xa)await zj0(this.kubeConfig,this.namespace,Z),await Ya(this.kubeConfig,this.namespace,J);else throw F}let K;try{K=await fq8(this.kubeConfig,this.namespace,Z),await Tj0(this.kubeConfig,this.namespace,K)}catch(F){throw await fO(this.kubeConfig,this.namespace,Z).catch(()=>{}),F}try{await this.ensureServicePortForAdoptedSandbox(K),await this.ensureHttpRouteForHandle(Z,K,X.tenant??null)}catch(F){throw await fO(this.kubeConfig,this.namespace,Z).catch(()=>{}),F}let W=await this.openForwarder(K,yU,Z),H=`http://127.0.0.1:${W.localPort}`,N=this.workloadConfigPayload(X),U=Y;try{if(await F51(H),this.sentinelToken!==null){let F=await Ij0(H);if(F)U=F.bootId;await y_(H,this.sentinelToken,N??{},{rotateToken:Q})}else if(N)await y_(H,Q,N);await this.relayOrgFsConfig(H,Q,X.orgFsConfigJson)}catch(F){throw this.closeForwarder(W),await this.deleteHttpRouteIfManaged(Z).catch(()=>{}),await fO(this.kubeConfig,this.namespace,Z).catch(()=>{}),F}return{id:$,handle:Z,adoptedSandboxName:K,token:Q,workdir:G,daemonUrl:H,daemonForward:W,workload:X.workload??null,daemonBootId:U,tenant:X.tenant??null,ensureOpts:og4(X)}}workloadConfigPayload($){return $J0({runtime:$?.workload?.runtime??"node",packageManager:$?.workload?.packageManager?{name:$.workload.packageManager,...$.workload.packageManagerPath?{path:$.workload.packageManagerPath}:{}}:null,repo:$?.repo??null,port:$?.workload?.devPort??HM8,tenant:$?.tenant??void 0,...$?{cloneOnly:$.cloneOnly===!0}:{}})}async relayOrgFsConfig($,Z,X){if(!X)return;await rq8($,Z,X).catch((Q)=>console.warn("[org-fs] sidecar config relay failed",Q))}async refreshDaemonGitCredential($,Z){let X=J41(Z);if(!X)return;try{await y_($.daemonUrl,$.token,X)}catch(Q){console.warn(`[${r$}] git credential refresh failed for ${$.handle}: ${Q instanceof Error?Q.message:String(Q)}`)}}async withFreshCloneUrl($,Z){if(!this.mintCloneUrl)return $;try{let X=await this.mintCloneUrl($,Z!==void 0?{bufferMs:Z}:void 0);return X?{...$,cloneUrl:X}:$}catch(X){return console.warn(`[${r$}] clone credential re-mint failed: ${X instanceof Error?X.message:String(X)}`),$}}startCredentialRefresher(){if(!this.mintCloneUrl)return;let{signal:$}=this.claimWatchAbort;(async()=>{while(!$.aborted){if(await _8(Cg4,{signal:$}).catch(()=>{}),$.aborted)break;try{await this.refreshAllGitCredentials()}catch(Z){console.warn(`[${r$}] periodic credential refresh failed: ${Z instanceof Error?Z.message:String(Z)}`)}}})()}startTenantPoolReconciler(){if(this.tenantPools.length===0)return;let{signal:$}=this.claimWatchAbort;(async()=>{while(!$.aborted){try{await this.reconcileTenantPools()}catch(Z){console.warn(`[${r$}] tenant pool reconcile failed: ${Z instanceof Error?Z.message:String(Z)}`)}await _8(Vg4,{signal:$}).catch(()=>{})}})()}markTenantPoolsDirty($,Z){let X=JM8(this.tenantPools,$,Z);for(let Q of X)this.dirtyPools.add(Q.name);return X.map((Q)=>Q.name)}async reconcileTenantPools(){for(let $ of this.tenantPools){let Z=await bq8(this.kubeConfig,this.namespace,$.name);if(Z===null){console.warn(`[${r$}] tenant pool ${$.name}: no SandboxWarmPool (or no selector yet) in ${this.namespace}`);continue}let X=this.dirtyPools.delete($.name),Q=Z.filter((Y)=>!Y.labels[BY.sandboxHandle]);for(let[Y]of this.poolPods)if(!Z.some((G)=>G.uid===Y))this.poolPods.delete(Y);for(let Y of Q){if(this.claimWatchAbort.signal.aborted)return;await this.warmPoolPod($,Y,X)}this.recordPoolDepth($,Z,Q)}}recordPoolDepth($,Z,X){let Q=this.metrics?.poolPods;if(!Q)return;let Y=0,G=0;for(let K of X){let W=this.poolPods.get(K.uid);if(!W)continue;if(W.failures>=Mj0)G++;else if(W.lastConfigAt>0)Y++}let J={pool:$.name,org:$.orgId};Q.record(Y,{...J,state:"ready"}),Q.record(Z.length-X.length,{...J,state:"bound"}),Q.record(X.length-Y-G,{...J,state:"pending"}),Q.record(G,{...J,state:"failed"})}async warmPoolPod($,Z,X){let Q=this.poolPods.get(Z.uid);if(Q&&Q.failures>=Mj0){if(Date.now()-Q.lastFailureAt<NM8)return;this.poolPods.set(Z.uid,{...Q,failures:0})}let Y=X||Q!==void 0&&Date.now()-Q.lastConfigAt>=this.tenantPoolRefreshMs;if(Q&&!Y)return;let G={cloneUrl:KM8($),connectionId:$.connectionId,branch:$.branch,userName:"",userEmail:""},J=await this.withFreshCloneUrl(G);if($.connectionId&&J.cloneUrl===G.cloneUrl){this.recordPoolFailure(Z,$,"clone credential mint failed");return}let K=await this.openForwarder(Z.name,yU,Z.name).catch(()=>null);if(!K){this.recordPoolFailure(Z,$,"port-forward failed");return}let W=`http://127.0.0.1:${K.localPort}`;try{await F51(W);let H=this.sentinelToken;if(!H)return;if(!await this.isPoolPodUnbound(Z))return;let N=$J0({runtime:$.workload.runtime,packageManager:$.workload.packageManager?{name:$.workload.packageManager,...$.workload.packageManagerPath?{path:$.workload.packageManagerPath}:{}}:null,repo:J,port:$.workload.devPort??HM8})??{},{transition:U}=await y_(W,H,N);if(Y&&U!=="bootstrap"&&await this.isPoolPodUnbound(Z))await oq8(W,H,"clone");this.poolPods.set(Z.uid,{lastConfigAt:Date.now(),lastFailureAt:0,failures:0}),console.log(`[${r$}] tenant pool ${$.name}: warmed ${Z.name} (${U})`)}catch(H){this.recordPoolFailure(Z,$,H instanceof Error?H.message:String(H))}finally{this.closeForwarder(K)}}isPoolPodUnbound($){return yq8(this.kubeConfig,this.namespace,$.name,BY.sandboxHandle)}recordPoolFailure($,Z,X){let Q=this.poolPods.get($.uid),Y=(Q?.failures??0)+1;this.poolPods.set($.uid,{lastConfigAt:Q?.lastConfigAt??0,lastFailureAt:Date.now(),failures:Y});let G=Y>=Mj0?` \u2014 backing off ${NM8/60000}min`:"";console.warn(`[${r$}] tenant pool ${Z.name}: warming ${$.name} failed (${Y}/${Mj0})${G}: ${X}`)}async refreshAllGitCredentials(){await WM8(this.records.values(),($)=>$.ensureOpts?.repo?.connectionId,async($)=>{if(this.claimWatchAbort.signal.aborted)return;let Z=$.ensureOpts?.repo;if(!Z)return;let X=await this.withFreshCloneUrl(Z,_g4);await this.refreshDaemonGitCredential($,{...$.ensureOpts,repo:X}),$.ensureOpts={...$.ensureOpts,repo:X}})}async rebootstrapDaemon($,Z,X){if(this.sentinelToken===null)return!1;let Q=this.workloadConfigPayload(X)??{};try{return await y_($,this.sentinelToken,Q,{rotateToken:Z}),await this.relayOrgFsConfig($,Z,X?.orgFsConfigJson),!0}catch(Y){if(Y instanceof Rj0&&Y.status===401)try{return await y_($,Z,Q,{rotateToken:Z}),await this.relayOrgFsConfig($,Z,X?.orgFsConfigJson),!0}catch(G){return console.warn(`[${r$}] re-bootstrap retry with claim token failed: ${G instanceof Error?G.message:String(G)}`),!1}return console.warn(`[${r$}] re-bootstrap failed: ${Y instanceof Error?Y.message:String(Y)}`),!1}}async ensureServicePortForAdoptedSandbox($){if(!this.previewGateway||!this.previewUrlPattern)return;await dq8(this.kubeConfig,this.namespace,$,{name:"daemon",port:yU,targetPort:yU})}async ensureHttpRouteForHandle($,Z,X){if(!this.previewGateway||!this.previewUrlPattern)return;let Q=rg4(this.previewUrlPattern,$);if(!Q)throw new p9(`Unable to derive preview hostname for ${$} from pattern: ${this.previewUrlPattern}`);let Y={apiVersion:`${Ga.API_GROUP}/${Ga.API_VERSION}`,kind:"HTTPRoute",metadata:{name:$,namespace:this.namespace,labels:E51(X??void 0,{[BY.role]:"claimed",[BY.sandboxHandle]:$,"app.kubernetes.io/name":"studio-sandbox","app.kubernetes.io/managed-by":"studio",...this.envName?{[BY.env]:this.envName}:{}})},spec:{parentRefs:[{kind:"Gateway",group:"gateway.networking.k8s.io",name:this.previewGateway.name,namespace:this.previewGateway.namespace}],hostnames:[Q],rules:[{backendRefs:[{group:"",kind:"Service",name:Z,port:yU}]}]}};await Pj0(this.kubeConfig,this.namespace,Y)}async deleteHttpRouteIfManaged($){if(!this.previewGateway)return;await Aj0(this.kubeConfig,this.namespace,$)}async rehydrate($,Z,X){let Q=X.state;if(!Q.adoptedSandboxName&&!Q.podName||!Q.token)return null;let Y=await wK(this.kubeConfig,this.namespace,Z).catch(()=>{return});if(!Y||!FM8(Y))return null;let G=Y.status?.sandbox?.name??Q.adoptedSandboxName??Q.podName??Z,J=await this.openAndProbeDaemon(G,Z);if(!J)return null;if(Q.daemonBootId&&Q.daemonBootId!==J.bootId){if(this.sentinelToken!==null){let K=Q.ensureOpts?.repo?{...Q.ensureOpts,repo:await this.withFreshCloneUrl(Q.ensureOpts.repo)}:Q.ensureOpts??null;if(!await this.rebootstrapDaemon(J.daemonUrl,Q.token,K))return this.closeForwarder(J.daemonForward),null}else console.warn(`[${r$}] daemon restart detected (handle=${Z}): stored bootId=${Q.daemonBootId} live bootId=${J.bootId}`);await this.stateStore?.put($,wY,{handle:Z,state:{...Q,daemonBootId:J.bootId}}).catch((K)=>console.warn(`[${r$}] bootId persist failed for ${Z}: ${K instanceof Error?K.message:String(K)}`))}return{id:$,handle:Z,adoptedSandboxName:G,token:Q.token,workdir:Q.workdir??L51,daemonUrl:J.daemonUrl,daemonForward:J.daemonForward,workload:Q.workload??null,daemonBootId:J.bootId,tenant:Q.tenant??null,ensureOpts:Q.ensureOpts??null}}async adopt($,Z,X){if(!FM8(X))return null;let Q=X.status?.sandbox?.name??Z;if(this.sentinelToken!==null)return null;let Y=yg4(X);if(!Y)return null;let G=await this.openAndProbeDaemon(Q,Z);if(!G)return null;let J=ng4(X);if(this.previewGateway)await this.ensureServicePortForAdoptedSandbox(Q).catch((K)=>{console.warn(`[${r$}] Service port backfill failed for ${Z}: ${K instanceof Error?K.message:String(K)}`)}),await this.ensureHttpRouteForHandle(Z,Q,J).catch((K)=>{console.warn(`[${r$}] HTTPRoute backfill failed for ${Z}: ${K instanceof Error?K.message:String(K)}`)});return{id:$,handle:Z,adoptedSandboxName:Q,token:Y,workdir:L51,daemonUrl:G.daemonUrl,daemonForward:G.daemonForward,workload:null,daemonBootId:G.bootId,tenant:J,ensureOpts:null}}async openAndProbeDaemon($,Z){let X=await this.openForwarder($,yU,Z).catch(()=>null);if(!X)return null;let Q=`http://127.0.0.1:${X.localPort}`,Y=await Ij0(Q);if(!Y)return this.closeForwarder(X),null;return{daemonForward:X,daemonUrl:Q,bootId:Y.bootId}}async getRecord($){let Z=this.records.get($);if(Z)return Z;if(!this.stateStore)return null;let X=await this.stateStore.getByHandle(wY,$);if(!X)return null;let Q=await this.rehydrate(X.id,$,X);if(Q)this.records.set($,Q);return Q}async resurrectByHandle($){if(!this.stateStore)return null;let Z=await this.stateStore.getByHandle(wY,$);if(!Z)return null;let X=Z.state.ensureOpts;if(!X)return null;let Q=X.repo?{...X,repo:await this.withFreshCloneUrl(X.repo)}:X;if(Wj(Z.id)!==$)return null;return await this.ensure(Z.id,Q),this.records.get($)??null}invalidateRecord($){let Z=this.records.get($);if(!Z)return;this.records.delete($),this.closeForwarder(Z.daemonForward)}recordProxyDuration($,Z,X,Q,Y){if(!this.metrics)return;this.metrics.proxyDurationMs.record(Q,{...z51(X?.tenant??null),source:$,sandbox_handle:X?.handle??Y??"",status_code:Z||0})}composePreviewUrl($){if(this.previewUrlPattern)return e30(this.previewUrlPattern,$.handle);return`http://127.0.0.1:${$.daemonForward.localPort}/`}toSandbox($){return{handle:$.handle,workdir:$.workdir,previewUrl:this.composePreviewUrl($)}}async persist($,Z){if(!$)return;let X={adoptedSandboxName:Z.adoptedSandboxName,token:Z.token,workdir:Z.workdir,workload:Z.workload,daemonBootId:Z.daemonBootId,tenant:Z.tenant,...Z.ensureOpts?{ensureOpts:Z.ensureOpts}:{}};await $.put(Z.id,wY,{handle:Z.handle,state:X})}computeShutdownTime(){return new Date(Date.now()+this.idleTtlMs).toISOString()}async releaseAfter($,Z){let X=await wK(this.kubeConfig,this.namespace,$);if(!X)return;let Q=pg4(X.spec?.lifecycle?.shutdownTime,new Date(Date.now()+Z));if(!Q)return;await jj0(this.kubeConfig,this.namespace,$,Q).catch((Y)=>console.warn(`[${r$}] release failed for ${$}: ${Y instanceof Error?Y.message:String(Y)}`))}async renewTtl($){let Z=await wK(this.kubeConfig,this.namespace,$);if(!Z)return;let X=tg4(Z.spec?.lifecycle?.shutdownTime,new Date(Date.now()+this.idleTtlMs));if(!X)return;await jj0(this.kubeConfig,this.namespace,$,X).catch((Q)=>console.warn(`[${r$}] TTL renew failed for ${$}: ${Q instanceof Error?Q.message:String(Q)}`))}openForwarder($,Z,X=$){let Q=gg4(X,Z);return new Promise((Y,G)=>{let J=(K,W)=>{let H=BM8.createServer((N)=>this.handleForwardedConnection(N,$,Z,X));H.once("error",(N)=>{if(N.code==="EADDRINUSE"&&W<xg4){try{H.close()}catch{}let U=j51+(K-j51+1)%OM8;J(U,W+1);return}G(N)}),H.listen(K,"127.0.0.1",()=>{let N=H.address();if(!N||typeof N==="string"){H.close(),G(Error("port-forward listener failed to bind"));return}Y({server:H,localPort:N.port})})};J(Q,0)})}handleForwardedConnection($,Z,X,Q){let Y=new Ag4,G=null,J=!1,K=()=>{if(J)return;if(J=!0,Y.destroy(),G)try{G.close()}catch{}if(!$.destroyed)$.destroy()};$.pipe(Y),$.on("error",K),$.on("close",K),this.portForward.portForward(this.namespace,Z,[X],$,null,Y).then((W)=>{let H=typeof W==="function"?W():W;if(!H){K();return}if(G=H,G.on("close",K),G.on("error",()=>{this.invalidateRecord(Q),K()}),J)try{G.close()}catch{}}).catch((W)=>{console.warn(`[${r$}] port-forward to ${Z}:${X} failed: ${Tg4(W)}`,JSON.stringify(LM8(W))),this.invalidateRecord(Q),K()})}closeForwarder($){$.server.close((Z)=>{if(Z)console.warn(`[${r$}] port-forward close on :${$.localPort} errored: ${Z instanceof Error?Z.message:String(Z)}`)})}close(){if(this.closed)return;this.closed=!0,this.claimWatchAbort.abort();for(let $ of this.records.values())this.closeForwarder($.daemonForward);this.records.clear()}}function fg4($){return{active:$.createUpDownCounter("studio.sandbox.active",{description:"Active sandbox count, by runner kind, owning org, and daemon impl. Cross-checks the cAdvisor-derived count from the cluster \u2014 divergence between the two indicates orphaned claims (studio deleted but K8s didn't reap) or unattributed pods.",unit:"{sandbox}"}),ensureOutcome:$.createCounter("studio.sandbox.ensure.outcome",{description:"Outcome of each ensure() call: fresh provision, resume from state-store after restart, or adopt of a cluster-side claim studio didn't know about. Cold-start ratio is the primary input for warm-pool sizing.",unit:"{call}"}),proxyDurationMs:$.createHistogram("studio.sandbox.proxy.duration_ms",{description:"Wall-clock latency of studio-mediated requests to the sandbox daemon: tool exec proxies (source=daemon) and preview iframe traffic (source=preview).",unit:"ms"}),poolPods:$.createGauge("studio.sandbox.pool.pods",{description:"Tenant warm pool depth by pool and state: ready (warmed and unbound \u2014 what a claim can actually bind instantly), bound (serving a user), pending (unbound, not yet warmed), failed (gave up after repeated bootstrap failures). Alert on sustained ready=0: a pool that is always empty is doing nothing while costing N pods.",unit:"{pod}"})}}function LM8($){let Z=[],X=$;for(let Q=0;Q<5&&X instanceof Error;Q++){let Y=X;if(Z.push({name:Y.name,message:Y.message,...Y.code!==void 0?{code:Y.code}:{},...Y.errno!==void 0?{errno:Y.errno}:{}}),Y.cause===X)break;X=Y.cause}if(X!==void 0&&!(X instanceof Error)&&X!==null){let Q=X,Y=Q.error instanceof Error?LM8(Q.error).chain:void 0;Z.push({nonError:String(X),...typeof Q.type==="string"?{type:Q.type}:{},...typeof Q.message==="string"?{message:Q.message}:{},...Q.code!==void 0?{code:Q.code}:{},...typeof Q.reason==="string"?{reason:Q.reason}:{},...Y?{error:Y}:{},...Y===void 0&&Q.error!==void 0?{rawError:String(Q.error)}:{},keys:Object.keys(Q)})}return{chain:Z}}function bg4(){let $=new ch;return $.loadFromDefault(),$}function FM8($){return Boolean($.status?.conditions?.some((Z)=>Z.type==="Ready"&&Z.status==="True"))}function yg4($){let Z=$.spec?.env;if(!Z)return null;for(let X of Z)if(X.name==="DAEMON_TOKEN"&&X.value)return X.value;return null}function gg4($,Z){let X=zg4("sha256").update(`${$}:${Z}`).digest();return j51+X.readUInt32BE(0)%OM8}function D51($,Z){return new Response(JSON.stringify(Z),{status:$,headers:{"content-type":"application/json","access-control-allow-origin":"*"}})}function wM8($){let Z=$.slice(0,ug4);return hg4.test(Z)?Z:""}function lg4($){if($===void 0)return null;let Z=$.trim();if(Z==="")return null;if(!cg4.test(Z))throw Error(`AgentSandboxProvider: envName=${JSON.stringify(Z)} is not a valid DNS-label-safe environment name (lowercase alphanumeric or '-', starts with a letter, ends alphanumeric, \u226432 chars). Studio sets this from STUDIO_ENV; check the studio chart's configMap.`);return Z}function E51($,Z={}){let X={...Z};if($){let Q=wM8($.orgId),Y=wM8($.userId);if(Q)X[BY.orgId]=Q;if(Y)X[BY.userId]=Y}return X}function g_($){let Z="";for(let X of $){let Q=X.codePointAt(0)??0;Z+=Q<32||Q===127?" ":X}return Z.slice(0,dg4)}function mg4($){try{let Z=new URL($);return Z.username="",Z.password="",Z.toString()}catch{return""}}function ig4($){let Z={},X=$.tenant;if(X?.orgSlug)Z[BK.orgSlug]=g_(X.orgSlug);if(X?.orgName)Z[BK.orgName]=g_(X.orgName);if(X?.userEmail)Z[BK.userEmail]=g_(X.userEmail);if(X?.userName)Z[BK.userName]=g_(X.userName);let Q=$.repo;if(Q){if(Q.displayName)Z[BK.gitRepo]=g_(Q.displayName);let Y=mg4(Q.cloneUrl);if(Y)Z[BK.gitRepoUrl]=g_(Y);let G=$.branch??Q.branch;if(G)Z[BK.gitBranch]=g_(G)}return Z}function ng4($){let Z=$.metadata?.labels;if(!Z)return null;let X=Z[BY.orgId],Q=Z[BY.userId];if(!X||!Q)return null;let Y=$.metadata?.annotations??{};return{orgId:X,userId:Q,orgSlug:Y[BK.orgSlug],orgName:Y[BK.orgName],userEmail:Y[BK.userEmail],userName:Y[BK.userName]}}function pg4($,Z){if($){let X=new Date($).getTime();if(Number.isFinite(X)&&X<=Z.getTime())return null}return Z.toISOString()}function tg4($,Z){if($){let X=new Date($).getTime();if(Number.isFinite(X)&&X>=Z.getTime())return null}return Z.toISOString()}function z51($){return{org_id:$?.orgId??"",user_id:$?.userId??"",runner_kind:wY}}function og4($){let Z={};if($.branch)Z.branch=$.branch;if($.repo)Z.repo=$.repo;if($.workload)Z.workload=$.workload;if($.env&&Object.keys($.env).length>0)Z.env=$.env;if($.tenant)Z.tenant=$.tenant;if($.orgFsConfigJson)Z.orgFsConfigJson=$.orgFsConfigJson;return Object.keys(Z).length>0?Z:null}function rg4($,Z){try{return new URL(e30($,Z)).hostname||null}catch{return null}}var wY="agent-sandbox",r$="AgentSandboxProvider",h_="x-sandbox-preview-not-ready",Rg4="agent-sandbox-system",Ig4="studio-sandbox",yU=9000,HM8=3000,L51="/app",qg4=32,Mg4,kg4=900000,Vg4=60000,Sg4=1800000,Mj0=3,NM8=1800000,Cg4=900000,_g4=1800000,vg4,UM8,j51=40000,OM8=1e4,xg4=256,BY,BK,hg4,ug4=63,cg4,dg4=253;var DM8=O(()=>{H$();nq8();Q51();aq8();K41();Ja();Qa();XM8();O51();Mg4=new Set(["DAEMON_TOKEN","DAEMON_BOOT_ID","APP_ROOT","PROXY_PORT"]),vg4=["cookie","host","connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","accept-encoding","content-length","upgrade"],UM8=["connection","keep-alive","transfer-encoding","content-encoding","content-length"];BY={role:"studio.decocms.com/role",sandboxHandle:"studio.decocms.com/sandbox-handle",orgId:"studio.decocms.com/org-id",userId:"studio.decocms.com/user-id",env:"studio.decocms.com/env"},BK={orgSlug:"studio.decocms.com/org-slug",orgName:"studio.decocms.com/org-name",userEmail:"studio.decocms.com/user-email",userName:"studio.decocms.com/user-name",gitRepo:"studio.decocms.com/git-repo",gitRepoUrl:"studio.decocms.com/git-repo-url",gitBranch:"studio.decocms.com/git-branch"},hg4=/^([A-Za-z0-9]([-A-Za-z0-9_.]*[A-Za-z0-9])?)?$/;cg4=/^[a-z]([a-z0-9-]{0,30}[a-z0-9])?$/});var EM8={};w0(EM8,{waitForSandboxReady:()=>Tj0,parseTenantPools:()=>QM8,getSandboxClaim:()=>wK,getHttpRoute:()=>cq8,deleteSandboxClaim:()=>fO,deleteHttpRoute:()=>Aj0,createSandboxClaim:()=>Ya,applyHttpRoute:()=>Pj0,SandboxTimeoutError:()=>b_,SandboxError:()=>p9,PREVIEW_NOT_READY_HEADER:()=>h_,KubeConfig:()=>ch,K8S_CONSTANTS:()=>v9,HTTPROUTE_CONSTANTS:()=>Ga,AgentSandboxProvider:()=>P51});var A51=O(()=>{Q51();Qa();Ja();DM8();O51()});var RM8={};w0(RM8,{subscribeLifecycle:()=>q51,getSandboxProviderByKind:()=>R51,getOrInitSharedRunner:()=>I51,__resetSharedLifecyclesForTesting:()=>Wh4});function AM8($,Z){let X=zM8[$];if(X)return Promise.resolve(X);let Q=T51[$];if(Q)return Q;let Y=Z().then((G)=>{return zM8[$]=G,G}).finally(()=>{delete T51[$]});return T51[$]=Y,Y}function eg4(){let $=process.env.STUDIO_SANDBOX_PREVIEW_URL_PATTERN;return $&&$.trim()!==""?$:void 0}function $h4(){let $=process.env.STUDIO_SANDBOX_TEMPLATE_NAME;return $&&$.trim()!==""?$:void 0}function Zh4(){let $=process.env.STUDIO_ENV;return $&&$.trim()!==""?$:void 0}function Xh4(){let $=process.env.STUDIO_SANDBOX_SENTINEL_TOKEN;return $&&$.trim()!==""?$:void 0}function Qh4(){let $=process.env.STUDIO_SANDBOX_PREVIEW_GATEWAY_NAME?.trim(),Z=process.env.STUDIO_SANDBOX_PREVIEW_GATEWAY_NAMESPACE?.trim();if(!$&&!Z)return;if(!$||!Z)throw Error("STUDIO_SANDBOX_PREVIEW_GATEWAY_NAME and STUDIO_SANDBOX_PREVIEW_GATEWAY_NAMESPACE must both be set, or both unset. Half-configured per-claim HTTPRoute routing would silently fail to attach.");return{name:$,namespace:Z}}async function TM8($,Z){let X=new br(Z),Q=eg4();switch($){case"agent-sandbox":{let{AgentSandboxProvider:Y,parseTenantPools:G}=await Promise.resolve().then(() => (A51(),EM8)),J=new iN(Z1().encryptionKey);return new Y({stateStore:X,previewUrlPattern:Q,sandboxTemplateName:$h4(),envName:Zh4(),previewGateway:Qh4(),sentinelToken:Xh4(),tenantPools:G(process.env.STUDIO_SANDBOX_TENANT_POOLS),meter:D6,mintCloneUrl:async(K,W)=>{if(!K.connectionId)return null;let H=HP8(K.cloneUrl);if(!H)return null;let{cloneUrl:N}=await RO(K.connectionId,H.owner,H.name,Z,J,{bufferMs:W?.bufferMs});return N}})}case"user-desktop":throw Error("user-desktop provider cannot be instantiated without a per-run link claim \u2014 call resolveSandboxProvider, which binds the link before constructing the provider.");default:throw Error(`Unknown sandbox provider kind: ${String($)}`)}}function R51($,Z){return AM8(Z,()=>TM8(Z,$.db))}async function I51(){let $;try{$=Hj()}catch(X){return console.warn("[lifecycle] cannot resolve sandbox runner:",X instanceof Error?X.message:String(X)),null}return await AM8($,()=>TM8($,H6().db))}function q51($,Z,X){let Q=bO.get(Z);if(Q){if(Q.terminated){if(Q.lastPhase)try{X(Q.lastPhase)}catch{}return{unsubscribe:Jh4}}if(Q.listeners.add(X),Q.lastPhase)try{X(Q.lastPhase)}catch{}return jM8(Z,Q,X)}let Y=new AbortController,G={lastPhase:null,terminated:!1,listeners:new Set([X]),abort:Y};return bO.set(Z,G),Kh4($,Z,G),jM8(Z,G,X)}function Jh4(){}function jM8($,Z,X){return{unsubscribe(){if(bO.get($)!==Z)return;if(Z.listeners.delete(X),Z.listeners.size===0)bO.delete($),Z.abort.abort()}}}async function Kh4($,Z,X){let Q=null;try{for await(let Y of $.watchClaimLifecycle(Z,X.abort.signal)){if(X.abort.signal.aborted)break;X.lastPhase=Y;let G=Y.kind==="ready"||Y.kind==="failed";if(G)X.terminated=!0;let J=Array.from(X.listeners);for(let K of J)try{K(Y)}catch{}if(G)break}}catch(Y){Q=Y}finally{if(!X.terminated&&!X.abort.signal.aborted&&X.listeners.size>0){let Y={kind:"failed",reason:"unknown",message:Q instanceof Error?Q.message:"Lifecycle watcher ended unexpectedly"};X.lastPhase=Y,X.terminated=!0;for(let G of Array.from(X.listeners))try{G(Y)}catch{}}if(bO.get(Z)===X)bO.delete(Z)}}function Wh4(){for(let $ of bO.values())$.abort.abort();bO.clear()}var ag4,sg4,PM8,zM8,T51,Yh4,Gh4,bO;var Wa=O(()=>{SU();n7();q5();N41();yr();ci();b8();ag4=Symbol.for("decocms.sandbox.lifecycle.runners"),sg4=Symbol.for("decocms.sandbox.lifecycle.inflight"),PM8=globalThis,zM8=PM8[ag4]??={},T51=PM8[sg4]??={};Yh4=Symbol.for("decocms.sandbox.lifecycle.shared-lifecycles"),Gh4=globalThis,bO=Gh4[Yh4]??=new Map});async function UQ($,Z){let{userId:X,branch:Q,virtualMcpMetadata:Y,explicitKind:G}=Z;if(G)return Ha($,G);if($.sandboxPreference==="agent-sandbox")return Ha($,"agent-sandbox");if($.sandboxPreference==="cluster-default")return Ha($,Hj());let[J,...K]=Hh4(Y,X,Q);if(J)return Ha($,K.length===0?J:Nh4(J,K));return Ha($,IM8())}function Hh4($,Z,X){let Q=n5($)[Z]?.[X];if(!Q)return[];let Y=zJ(Q);return Object.keys(Y)}function Nh4($,Z){let X=IM8();if(X===$||Z.includes(X))return X;return $}function IM8(){return Hj()}async function Ha($,Z){let X=Z==="user-desktop"?"agent-sandbox":Z;return{provider:await R51($,X),kind:X}}var yO=O(()=>{R6();SU();KY();Wa()});var Na;var M51=O(()=>{Na={npm:{install:"npm install",run:($)=>`npm run ${$}`,runtime:"node"},pnpm:{install:"pnpm install",run:($)=>`pnpm run ${$}`,runtime:"node"},yarn:{install:"yarn install",run:($)=>`yarn run ${$}`,runtime:"node"},bun:{install:"bun install",run:($)=>`bun run ${$}`,runtime:"bun"},deno:{install:"deno install",run:($)=>`deno task ${$}`,runtime:"deno"}}});function OK($,Z){return Z?`thread:${$}/${Z}`:`thread:${$}`}function gU($){return`sandbox/thread-${$.replace(/^thread:/,"").replace(/\//g,"-")}`}function gO($){if(!$||!$.startsWith("thread:"))return null;return $.slice(7).split("/")[0]||null}async function hU($,Z,X){let Q=gO(Z);if(!Q)return X;return(await $.storage.threads.get(Q).catch(()=>null))?.created_by??X}async function u_($,Z){if(!Z)return null;let X=await $.storage.threads.get(Z).catch(()=>null);if(!X)return null;return X.metadata??{}}async function qM8($,Z){let Q=(await u_($,Z))?.headRef;return typeof Q==="string"&&Q.length>0?Q:null}async function MM8($,Z,X){let Q=await u_($,Z);if(!Q)return;if(Q.headRef===X)return;await $.storage.threads.update(Z,{metadata:{...Q,headRef:X}}).catch((Y)=>console.warn("[thread-repo] setThreadHeadRef failed",Y))}async function hO($,Z){return(await u_($,Z))?.githubRepo??null}function k51($){if($.pinnedRef)return $.pinnedRef;if($.runBranch&&$.runBranch===OK($.threadId))return $.runBranch;if($.threadRepo)return OK($.threadId,$.threadRepo.connectionId);if(!$.agentRepo)return"ephemeral";return $.runBranch??`thread:${$.threadId}`}async function V51($,Z){let Q=(await u_($,Z))?.pinnedRef;return typeof Q==="string"&&Q.length>0?Q:null}async function kM8($,Z){let[X,Q]=await Promise.all([hO($,Z.threadId),V51($,Z.threadId)]);return k51({...Z,threadRepo:X,pinnedRef:Q})}async function VM8($,Z,X,Q,Y,G){let J=await u_($,Z);if(!J)return;let K=fr(n5(J),X,Q,Y,G);await $.storage.threads.update(Z,{metadata:{...J,sandboxMap:K}}).catch((W)=>console.warn("[thread-repo] setThreadSandboxMapEntry failed",W))}async function kj0($,Z){return n5(await u_($,Z))}async function SM8($,Z,X,Q,Y){let G=await u_($,Z);if(!G)return;let J=H41(n5(G),X,Q,Y);if(!J)return;await $.storage.threads.update(Z,{metadata:{...G,sandboxMap:J}}).catch((K)=>console.warn("[thread-repo] removeThreadSandboxMapEntry failed",K))}var LK=O(()=>{KY()});function Vj0($){if(!$)return null;let Z=$.runtime;if(!Z||typeof Z!=="object")return null;let X=Z.env;if(!Array.isArray(X))return null;let Q=[];for(let Y of X){if(!Y||typeof Y!=="object")continue;let G=Y;if(typeof G.key!=="string"||!YZ0.test(G.key))continue;if(G.kind==="literal"&&typeof G.value==="string"){Q.push({key:G.key,kind:"literal",value:G.value});continue}if(G.kind==="secret"&&typeof G.secretId==="string"&&G.secretId.length>0)Q.push({key:G.key,kind:"secret",secretId:G.secretId})}return Q.length===0?null:Q}function CM8($){if(!$)return null;let Z=$.runtime;if(!Z||typeof Z!=="object")return null;let X=Z.submoduleCredentials;if(!Array.isArray(X))return null;let Q=[];for(let Y of X){if(!Y||typeof Y!=="object")continue;let G=Y;if(typeof G.host==="string"&&G.host.length>0&&typeof G.secretId==="string"&&G.secretId.length>0)Q.push({host:G.host,secretId:G.secretId})}return Q.length===0?null:Q}async function _M8($,Z){N0(Z);let X=J0(Z);await Z.access.check();let Q=z1(Z);if(!Q)throw Error("User ID required");let Y=await Z.storage.virtualMcps.findById($.virtualMcpId);if(!Y||Y.organization_id!==X.id)throw Error("Virtual MCP not found");let G=Y.metadata??{},J=n5(G),K=await hU(Z,$.branch,Q),W=WH(J,K,$.branch,$.sandboxProviderKind);return{virtualMcp:Y,metadata:G,userId:Q,sandboxUserId:K,entry:W,organization:X}}function Uh4($){if($===null||!/^\d+$/.test($))return null;let Z=Number($);return Z>=1&&Z<=65535?$:null}function vM8($){let Z=$.runtime??null,Q=Z?.selected??null,Y=Uh4(Z?.port??null),G=Z?.path??null;if(!Q||!(Q in Na))return{packageManager:null,runtime:null,port:Y,packageManagerPath:G,runtimeBinPath:null};let J=Na[Q].runtime;return{packageManager:Q,runtime:J,port:Y,packageManagerPath:G,runtimeBinPath:J==="deno"?"/opt/deno/bin":J==="bun"?"/opt/bun/bin":null}}var Ua=O(()=>{R6();M51();KY();LK()});async function uO($,Z){let X=$.body?.getReader();if(!X)return $.text();let Q=new TextDecoder,Y="",G=0;for(;;){let{done:J,value:K}=await X.read();if(J)break;if(G+=K.byteLength,G>Z)throw await X.cancel().catch(()=>{}),new xM8(`Upstream response exceeded ${Z} bytes`);Y+=Q.decode(K,{stream:!0})}return Y+=Q.decode(),Y}var xM8;var Fa=O(()=>{xM8=class xM8 extends Error{}});async function Sj0({ctx:$,runner:Z,handle:X,orgId:Q,userId:Y,entries:G}){if(!G||G.length===0)return;let J={};for(let W of G){if(W.kind==="literal"){J[W.key]=W.value;continue}try{let{value:H}=await $.storage.secrets.resolveById(W.secretId,Q,Y);J[W.key]=H}catch(H){if(H instanceof K3||H instanceof uB){console.warn(`[SANDBOX_START] skipping env ${W.key}: ${H.message}. Re-link or recreate the secret to restore.`);continue}throw H}}if(Object.keys(J).length===0)return;let K=await Z.proxyDaemonRequest(X,"/_sandbox/config",{method:"PUT",headers:new Headers({"content-type":"application/json"}),body:JSON.stringify({env:J})});if(!K.ok){let W=await uO(K,Fh4).catch(()=>K.statusText);console.warn(`[SANDBOX_START] daemon rejected env patch (${K.status}): ${W}`)}}var Fh4=10485760;var S51=O(()=>{Wt();Fa()});async function fM8({ctx:$,orgId:Z,userId:X,entries:Q}){if(!Q||Q.length===0)return[];let Y=[];for(let G of Q)try{let{value:J}=await $.storage.secrets.resolveById(G.secretId,Z,X);Y.push({host:G.host,token:J})}catch(J){if(J instanceof K3||J instanceof uB){console.warn(`[SANDBOX_START] skipping submodule credential for ${G.host}: ${J.message}. Re-link or recreate the secret to restore.`);continue}throw J}return Y}var bM8=O(()=>{Wt()});async function hM8($,Z,X,Q,Y){let G=await EU({connectionId:$,tokenStorage:new _5(Q,Y)});if(!G.accessToken)return null;return cM8(Z,X,G.accessToken)}function uM8($,Z){return cM8($,Z,null)}async function cM8($,Z,X){let Q=new Map,Y=new Set(yM8.map((W)=>W.path));for(let W of Object.values(gM8))for(let H of W??[])Y.add(H);await Promise.all(Array.from(Y).map(async(W)=>{Q.set(W,await Bh4($,Z,W,X))}));let G=yM8.find(({path:W})=>Q.get(W)!==null);if(!G)return null;let J=gM8[G.pm]??[],K=null;for(let W of J)if(K=Oh4(Q.get(W)??null),K)break;return{packageManager:G.pm,devPort:K}}async function Bh4($,Z,X,Q){let Y=`https://api.github.com/repos/${$}/${Z}/contents/${encodeURIComponent(X)}`;try{let G={Accept:"application/vnd.github+json","User-Agent":"studio-runtime-detect"};if(Q)G.Authorization=`token ${Q}`;let J=await fetch(Y,{headers:G,signal:AbortSignal.timeout(5000)});if(!J.ok)return null;let K=await J.json();if(!K.content||K.encoding!=="base64")return null;return Buffer.from(K.content,"base64").toString("utf8")}catch{return null}}function Oh4($){if(!$)return null;try{let Z=JSON.parse($),X=Z.tasks??Z.scripts??{};return(X.dev??X.start??"").match(wh4)?.[1]??null}catch{return null}}var yM8,gM8,wh4;var lM8=O(()=>{KO();eJ();yM8=[{path:"deno.json",pm:"deno"},{path:"deno.jsonc",pm:"deno"},{path:"bun.lock",pm:"bun"},{path:"bunfig.toml",pm:"bun"},{path:"pnpm-lock.yaml",pm:"pnpm"},{path:"yarn.lock",pm:"yarn"},{path:"package-lock.json",pm:"npm"},{path:"package.json",pm:"bun"}],gM8={deno:["deno.json","deno.jsonc"],bun:["package.json"],pnpm:["package.json"],yarn:["package.json"],npm:["package.json"]},wh4=/(?:--port|PORT=|:)(\d{4,5})/});function Lh4($){return($??"").normalize("NFKD").replace(/[\u0300-\u036F]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"user"}function Cj0($){return $?.name||$?.email?.split("@")[0]||void 0}function _j0($){let Z=Lh4($),X=Date.now().toString(36).split("").reverse().join("");return`${Z}-${X}`}function dM8($){let{current:Z,detached:X,base:Q}=$.status??{};if(typeof Z!=="string"||Z.length===0)return null;if(X===!0)return null;if(Z===$.requestedRef)return null;if(Dh4.has(Z))return null;if(typeof Q==="string"&&Q.length>0&&Z===Q)return null;return Z}function mM8($){if(!$.branch.startsWith("thread:"))return $.branch;if($.sticky&&$.recordedHeadRef)return $.recordedHeadRef;return $.derivedRef}var Dh4;var C51=O(()=>{Dh4=new Set(["main","master","trunk","develop","HEAD"])});async function iM8($,Z){if(!$)return{hosts:[],allowSameHostDev:!1};let X;try{X=await $.presignedGetUrl("link-dispatch/_allowlist_probe",60,{requireFetchable:!0})}catch{return{hosts:[],allowSameHostDev:!1}}let Q;try{Q=new URL(X)}catch{return{hosts:[],allowSameHostDev:!1}}if(Q.protocol!=="https:"&&Q.protocol!=="http:")return{hosts:[],allowSameHostDev:!1};let Y=Q.hostname,G=Eh4.has(Y);return{hosts:[Y],allowSameHostDev:G&&!Z.isProduction}}var Eh4;var nM8=O(()=>{Eh4=new Set(["127.0.0.1","localhost","::1","[::1]","0.0.0.0"])});import{z as BH}from"zod";async function ph($,Z){N0(Z);let X=J0(Z),Q=z1(Z);if(!Q)throw Error("User ID required");let Y=await Z.storage.virtualMcps.findById($.virtualMcpId);if(!Y||Y.organization_id!==X.id)throw Error("Virtual MCP not found");let G=Y.metadata??{},J=await hU(Z,$.branch,Q),K=WH(n5(G),J,$.branch,$.sandboxProviderKind),W=$.sandboxProviderKind,{provider:H}=await UQ(Z,{userId:J,branch:$.branch,virtualMcpMetadata:G,explicitKind:W});if(K){if(W!=="user-desktop")return K;if(await H.alive(K.sandboxHandle).catch(()=>!1))return K;await TO(Z.storage.virtualMcps,$.virtualMcpId,Q,J,$.branch,W).catch((B)=>{console.warn("[ensureSandbox] failed to reap stale user-desktop entry",B)})}let U=await hO(Z,gO($.branch)??Z.metadata?.threadId)??G.githubRepo??null,{entry:F}=await tM8({ctx:Z,userId:Q,sandboxUserId:J,orgId:X.id,virtualMcpId:$.virtualMcpId,branch:$.branch,metadata:G,githubRepo:U,existing:null,providerKind:W,runner:H,...$.cloneOnly?{cloneOnly:!0}:{}});return F}async function tM8($){let{ctx:Z,userId:X,sandboxUserId:Q,orgId:Y,virtualMcpId:G,branch:J,metadata:K,githubRepo:W,existing:H,runner:N,cloneOnly:U}=$,{runtime:F,packageManager:w,port:B,packageManagerPath:L}=vM8(K),D;if(W){if(W.connectionId)await Sh({ctx:Z,connectionId:W.connectionId,organizationId:Y,forceRefresh:!0,onLegacyMintError:(p0)=>{console.error("[provisionSandbox] repo-scoped legacy token mint failed",{connectionId:W.connectionId,error:p0.message})}});let{cloneUrl:R0,gitUserName:$0,gitUserEmail:s}=W.connectionId?await RO(W.connectionId,W.owner,W.name,Z.db,Z.vault):WP8(W.owner,W.name);if(!w){let p0=W.connectionId?await hM8(W.connectionId,W.owner,W.name,Z.db,Z.vault):await uM8(W.owner,W.name);if(p0)w=p0.packageManager,F=Na[p0.packageManager].runtime,B=p0.devPort??B,await jh4(Z,G,X,p0.packageManager,p0.devPort)}let A0=Z1().sandboxStickyHeadRefEnabled,Q0=mM8({branch:J,derivedRef:gU(J),recordedHeadRef:A0?await qM8(Z,gO(J)):null,sticky:A0}),I0=await fM8({ctx:Z,orgId:Y,userId:X,entries:CM8(K)});D={cloneUrl:R0,...W.connectionId?{connectionId:W.connectionId}:{},userName:$0,userEmail:s,branch:Q0,displayName:`${W.owner}/${W.name}`,...I0.length>0?{submoduleCredentials:I0}:{}}}let E=typeof K.productionUrl==="string"&&K.productionUrl.trim()?K.productionUrl.trim():void 0,z=F&&w&&!U?{runtime:F,packageManager:w,...B!==null?{devPort:Number(B)}:{},...L?{packageManagerPath:L}:{},...E?{productionUrl:E}:{}}:void 0,j=_r({orgId:Y,virtualMcpId:G,branch:J}),A=N.kind==="user-desktop"?await iM8(Z.objectStorage,{isProduction:Z1().nodeEnv==="production"}):null,P=(N.kind==="user-desktop"||N.kind==="agent-sandbox")&&!Z1().orgFsMountsDisabled,q;if(P){let R0=Z.organization?.slug??(await Z.db.selectFrom("organization").select(["slug"]).where("id","=",Y).executeTakeFirst())?.slug;if(R0)q=await DB8(Z,{orgSlug:R0,orgId:Y,baseUrl:kQ()})}await Ah4(N);let k=await N.ensure({userId:Q,projectRef:j},{branch:J,repo:D,workload:z,cloneOnly:U===!0,tenant:{orgId:Y,userId:Q,...Z.organization?.slug?{orgSlug:Z.organization.slug}:{},...Z.organization?.name?{orgName:Z.organization.name}:{},...Z.auth.user?.email?{userEmail:Z.auth.user.email}:{},...Z.auth.user?.name?{userName:Z.auth.user.name}:{}},...A?{offloadAllowedHosts:A.hosts,offloadAllowSameHostDev:A.allowSameHostDev}:{},...q?{orgFsConfigJson:q}:{}}),M=K.runtime?.env??null;await Sj0({ctx:Z,runner:N,handle:k.handle,orgId:Y,userId:X,entries:M});let d=!!H&&H.sandboxHandle===k.handle&&H?.createdAt?H.createdAt:Date.now(),v=K.runtime?.selected??null,b=K.runtime?.port??null,t=K.runtime?.path??null,y={sandboxHandle:k.handle,previewUrl:k.previewUrl,sandboxApiUrl:k.previewUrl,sandboxProviderKind:N.kind,createdAt:d,startedWith:{packageManager:v,port:b,path:t}};await sj8(Z.storage.virtualMcps,G,X,Q,J,$.providerKind,y);let Z0=gO(J);if(Z0)await VM8(Z,Z0,Q,J,$.providerKind,y);let D0=!H||H.sandboxHandle!==k.handle;return{entry:y,isNewVm:D0}}async function jh4($,Z,X,Q,Y){let G=await $.storage.virtualMcps.findById(Z);if(!G)return;let J=G.metadata??{};await $.storage.virtualMcps.update(Z,X,{metadata:{...J,runtime:{selected:Q,port:Y}}})}async function Ah4($){if(!$.hasSchedulableCapacity)return;let Z=Date.now()+pM8,X=!1;while(!await $.hasSchedulableCapacity()){if(Date.now()>=Z)throw Error(`sandbox provisioning failed: the cluster has had no room to schedule another sandbox for ${Math.round(pM8/1000)}s`);if(!X)X=!0,console.warn("[ensureSandbox] waiting for cluster capacity \u2014 a sandbox pod cannot be scheduled right now");await _8(Ph4)}}var zh4,_51,pM8=150000,Ph4=5000;var wa=O(()=>{SU();H$();t0();Ua();S51();bM8();KY();yr();lM8();M51();yO();LK();C51();nM8();b8();YZ();po();KY();zh4=BH.enum(["agent-sandbox","user-desktop","cluster"]),_51=o({name:"SANDBOX_START",description:"Start a sandbox with the connected GitHub repo and dev server.",annotations:{title:"Start VM Preview",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0},_meta:{ui:{visibility:"app"}},inputSchema:BH.object({virtualMcpId:BH.string().describe("Virtual MCP ID"),branch:BH.string().min(1).optional().describe("Git branch to check out. Pass the thread's branch whenever the caller has one: when omitted the handler mints a fresh `<user-slug>-<timestamp>` name, which becomes a SEPARATE sandbox from the one the thread's own branch resolves to. The resolved branch is returned in the response so callers can persist it."),sandboxProviderKind:zh4.optional().describe("Explicit runtime choice. Hosted provider is `agent-sandbox`; legacy `cluster` input is accepted only for compatibility and normalized to `agent-sandbox`. When omitted, defaults to `user-desktop` if the acting user's link daemon is online, else the env kind.")}),outputSchema:BH.object({previewUrl:BH.string().nullable(),sandboxHandle:BH.string(),branch:BH.string(),isNewVm:BH.boolean(),sandboxProviderKind:BH.enum(["agent-sandbox","user-desktop"])}),handler:async($,Z)=>{N0(Z);let X=J0(Z);await Z.access.check();let Q=$.branch??_j0(Cj0(Z.auth.user)),Y=z1(Z);if(!Y)throw Error("User ID required");let G=await hU(Z,Q,Y),J=await Z.storage.virtualMcps.findById($.virtualMcpId);if(!J||J.organization_id!==X.id)throw Error("Virtual MCP not found");let K=J.metadata??{},W=$.sandboxProviderKind?Kj($.sandboxProviderKind):void 0,{provider:H,kind:N}=await UQ(Z,{userId:G,branch:Q,virtualMcpMetadata:K,explicitKind:W}),U=WH(n5(K),G,Q,N),w=await hO(Z,gO(Q)??Z.metadata?.threadId)??K.githubRepo??null,{entry:B,isNewVm:L}=await tM8({ctx:Z,userId:Y,sandboxUserId:G,orgId:X.id,virtualMcpId:$.virtualMcpId,branch:Q,metadata:K,githubRepo:w,existing:U,providerKind:N,runner:H});return{...B,branch:Q,isNewVm:L,sandboxProviderKind:N}}})});function Th4($){let{publicUrl:Z,agentId:X,organization:Q,target:Y,threadId:G}=$;if(Y==="agent-tools")return`${Z}/mcp/virtual-mcp/${X}`;if(!Q.slug)throw new rM8(Q.id);if(Y==="task-run"){if(!G)throw Error("a task-run MCP endpoint is scoped to a run: threadId is required");return`${Z}/api/${Q.slug}/mcp/task-run/${encodeURIComponent(G)}`}return`${Z}/api/${Q.slug}/mcp/self`}async function vj0($,Z,X,Q,Y="agent-tools",G){let J=Th4({publicUrl:kQ(),agentId:Z,organization:X,target:Y,...G?{threadId:G}:{}}),K=await $.boundAuth.apiKey.create({name:Q,permissions:{"*":["*"]},expiresIn:oM8,metadata:{organization:{id:X.id,slug:X.slug,name:X.name}}});return{url:J,headers:{Authorization:`Bearer ${K.key}`,"x-org-id":X.id},expiresAt:Date.now()+oM8*1000}}var oM8=3600,rM8;var v51=O(()=>{YZ();rM8=class rM8 extends Error{constructor($){super(`cannot mint a management MCP endpoint for organization "${$}": the org-scoped path /api/<slug>/mcp/self needs the org slug, which was not loaded.`);this.name="MissingOrganizationSlugError"}}});async function Rh4($,Z,X,Q){try{let Y=$.organization;if(!Y)return;let G=await vj0($,Q.virtualMcpId,Y,"tool-scripting"),J=await Z.proxyDaemonRequest(X,"/_sandbox/tools/sync",{method:"POST",headers:new Headers({"content-type":"application/json"}),body:JSON.stringify(G)});if(!J.ok)console.warn("[cluster-sandbox-fs] tools/sync failed",J.status,await J.text().catch(()=>""))}catch(Y){console.warn("[cluster-sandbox-fs] tools/sync failed",Y)}}async function th($,Z){let{provider:X,kind:Q}=await UQ($,{userId:Z.userId,branch:Z.branch,virtualMcpMetadata:null}),Y=null,G=()=>{if(!Y){if(Y=ph({virtualMcpId:Z.virtualMcpId,branch:Z.branch,sandboxProviderKind:Q},$).then((W)=>W.sandboxHandle),Y.catch(()=>{Y=null}),Z.syncTools)Y.then((W)=>Rh4($,X,W,{virtualMcpId:Z.virtualMcpId,providerKind:Q})).catch(()=>{})}return Y},J=Z.branch==="ephemeral"||Q==="user-desktop";return W41(X,{ensureHandle:G,invalidateHandle:async(W)=>{let H=Y;if(Y=null,!J&&!W?.force)return;try{await TO($.storage.virtualMcps,Z.virtualMcpId,Z.userId,Z.userId,Z.branch,Q)}catch(N){console.warn("[cluster-sandbox-fs] failed to reap vmMap entry",N)}if(H&&typeof X.forgetHandle==="function")try{let N=await H;await X.forgetHandle(N)}catch(N){console.warn("[cluster-sandbox-fs] forgetHandle failed",N)}},canAutoRestart:J})}async function aM8($,Z){try{let X=await th($,Z),{stdout:Q}=await X.onBash("test -d .deco && echo __DECO_SITE__");return Q.includes("__DECO_SITE__")}catch(X){return console.warn("[cluster-sandbox-fs] .deco probe failed; assuming deco site",X),!0}}var xj0=O(()=>{SU();v51();yO();wa();KY()});import{z as sM8}from"zod";function oh($){let Z=[];for(let X of $){if(X.status!=="active")continue;let Q=YQ(X);if(!Q)continue;Z.push({connectionId:X.id,owner:Q.owner,repo:Q.repo,installationId:Q.installationId})}return Z}async function qh4($,Z){let{items:X}=await $.storage.connections.list(Z,{slug:"mcp-github"});return oh(X)}function Mh4($){let Z=$.split(`
|
|
2494
2494
|
`).map((Q)=>Q.trim()).filter((Q)=>Q&&Q!==".git"&&Q!=="__CLONED__"),X=Z.length>0;return{cloned:X,listing:X?Z.join(`
|
|
2495
2495
|
`):""}}function kh4($){let Z="Load a GitHub repository into this conversation's sandbox so the file tools (read/write/edit/bash/grep/glob) and dev server operate on that repo, and open its live Preview. Waits until the repo is cloned before returning. Calling it again switches the repo. File tools operate on the loaded repo from your NEXT message (this turn's tools are still bound to the previous workspace), so after loading, prefer the file listing this tool returns over re-running bash in the same turn.",X=$.map((Q)=>`- ${Q.owner}/${Q.repo} (connectionId: ${Q.connectionId})`).join(`
|
|
2496
2496
|
`);return`${Z}
|