decocms 4.213.2 → 4.213.3
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-BtaPB3r3.js → AlertCircle-CHfb9x-t.js} +1 -1
- package/dist/client/assets/{AreaChart-D5z3kdQF.js → AreaChart-DgCu30RO.js} +1 -1
- package/dist/client/assets/{ArrowLeft-CWRzKYG7.js → ArrowLeft-BppNd44v.js} +1 -1
- package/dist/client/assets/{ArrowUp-BQptHrCQ.js → ArrowUp-CoPBJP5F.js} +1 -1
- package/dist/client/assets/{ArrowUpRight-CrVt_V-y.js → ArrowUpRight-BoRcUfPT.js} +1 -1
- package/dist/client/assets/{Check-C9YirVC4.js → Check-oDnQWrwG.js} +1 -1
- package/dist/client/assets/{CheckCircle-BNrL_lWP.js → CheckCircle-DYHnrji_.js} +1 -1
- package/dist/client/assets/{ChevronDown-CK4ZVZU5.js → ChevronDown-B_Kkx94b.js} +1 -1
- package/dist/client/assets/{ChevronRight-DRaQJ8sH.js → ChevronRight-zfsu59r1.js} +1 -1
- package/dist/client/assets/{ChevronUp-_4Y6lyxd.js → ChevronUp-EPvH8PkI.js} +1 -1
- package/dist/client/assets/{Copy01-CLX1AbOl.js → Copy01-eDDf5Tut.js} +1 -1
- package/dist/client/assets/{CpuChip01-BDJy1J19.js → CpuChip01-CLo4Ix8E.js} +1 -1
- package/dist/client/assets/{CreditCard01-Dn0eZmYP.js → CreditCard01-xE5_nqV3.js} +1 -1
- package/dist/client/assets/{DotsVertical-DrdjZfrd.js → DotsVertical-D_v8MV1q.js} +1 -1
- package/dist/client/assets/{Eye-BzFG1M0K.js → Eye-C-shpZBx.js} +1 -1
- package/dist/client/assets/{FilterLines-DAnm9bXM.js → FilterLines-eIVOYmnR.js} +1 -1
- package/dist/client/assets/{Globe01-T4l6-g3P.js → Globe01-CRzaXNDn.js} +1 -1
- package/dist/client/assets/{Globe04-8mu0fUFk.js → Globe04-DNZHTV5G.js} +1 -1
- package/dist/client/assets/{HardDrive-qcwOZA_m.js → HardDrive-D838hg9y.js} +1 -1
- package/dist/client/assets/{Key01-DoHyECqo.js → Key01-D5nk6wZa.js} +1 -1
- package/dist/client/assets/{LayoutLeft-BwNnkGLE.js → LayoutLeft-lpjOn5oi.js} +1 -1
- package/dist/client/assets/{LinkExternal01-4giR9ii8.js → LinkExternal01-i_xcWupG.js} +1 -1
- package/dist/client/assets/{LogOut01-Bd09T8FP.js → LogOut01-BjxuTdOd.js} +1 -1
- package/dist/client/assets/{Monitor01-B5dFm4gD.js → Monitor01-CdHR20C9.js} +1 -1
- package/dist/client/assets/{Palette-D2vpD9pq.js → Palette-C4JrvRwY.js} +1 -1
- package/dist/client/assets/{Play-DhkCqwFM.js → Play-B_-mBOJ3.js} +1 -1
- package/dist/client/assets/{Plus-Dm4WmNSG.js → Plus-CM2iw1bv.js} +1 -1
- package/dist/client/assets/{SearchLg-Ck20GG--.js → SearchLg-DzzT_0F0.js} +1 -1
- package/dist/client/assets/{SearchMd-CfFkukig.js → SearchMd-CCKu2g_A.js} +1 -1
- package/dist/client/assets/{Settings02-CVAq2JK_.js → Settings02-G48i2TjO.js} +1 -1
- package/dist/client/assets/{Share07-D22bkXr_.js → Share07-DsYUX-zt.js} +1 -1
- package/dist/client/assets/{Shield01-AckE4Fkx.js → Shield01-BoXn0azv.js} +1 -1
- package/dist/client/assets/{Star01-CxRj8IxJ.js → Star01-BDPsn3iM.js} +1 -1
- package/dist/client/assets/{Stars01-Sd1pfysM.js → Stars01-DfGag_qD.js} +1 -1
- package/dist/client/assets/{Stars02-B1BVyXRS.js → Stars02-uHXuTrxv.js} +1 -1
- package/dist/client/assets/{Sun-C10MgYGY.js → Sun-C1BvCEJt.js} +1 -1
- package/dist/client/assets/{SwitchHorizontal01-BQiSEYjX.js → SwitchHorizontal01-B1Yc4H4f.js} +1 -1
- package/dist/client/assets/{Tool01-DLaPhB7V.js → Tool01-CGHeK1WE.js} +1 -1
- package/dist/client/assets/{Tool02-DrvkBQ68.js → Tool02-B1POxF2I.js} +1 -1
- package/dist/client/assets/{Trash01-BVokhopT.js → Trash01-CpLttFqU.js} +1 -1
- package/dist/client/assets/{TrendUp01-BhfBb2kU.js → TrendUp01-CjL_HE91.js} +1 -1
- package/dist/client/assets/{Upload01-DbpOiMD9.js → Upload01-Jc9Qf52D.js} +1 -1
- package/dist/client/assets/{User01-xEWYNlJX.js → User01-DdVFKZ7n.js} +1 -1
- package/dist/client/assets/{Users01-CJZJiXpK.js → Users01-H9nHn8vh.js} +1 -1
- package/dist/client/assets/{Users03-aGMnn7GC.js → Users03-DLe7GAgY.js} +1 -1
- package/dist/client/assets/{X-CPPWzFGv.js → X-BJV63bzn.js} +1 -1
- package/dist/client/assets/{XCircle-DiqaNpK5.js → XCircle-e8oZxnqK.js} +1 -1
- package/dist/client/assets/{XClose-DmdEfX7d.js → XClose-CZmy9H1H.js} +1 -1
- package/dist/client/assets/{Zap-BrN9iJhf.js → Zap-Blr-6e3X.js} +1 -1
- package/dist/client/assets/{ZapSquare-D3etv_p8.js → ZapSquare-BakcP9-y.js} +1 -1
- package/dist/client/assets/{access-gate-C6VLyHTX.js → access-gate-DmHQwKVk.js} +1 -1
- package/dist/client/assets/{agent-icon-Bvh_dN2q.js → agent-icon-CcGcwzy7.js} +1 -1
- package/dist/client/assets/{agents-list-5yWNyWYm.js → agents-list-Be_OHGrc.js} +1 -1
- package/dist/client/assets/{ai-providers-D-iMsrLU.js → ai-providers-CmgiWm5v.js} +1 -1
- package/dist/client/assets/{alert-DX1Ywn4R.js → alert-CI_5B43q.js} +1 -1
- package/dist/client/assets/{alert-dialog-N5y_pt8L.js → alert-dialog-r60zVmnF.js} +1 -1
- package/dist/client/assets/{app-editor-C_aXlWBV.js → app-editor-CN-vz_rI.js} +1 -1
- package/dist/client/assets/{auth-CVA5G64j.js → auth-CqUqMsnu.js} +1 -1
- package/dist/client/assets/{auth-catchall--u2uHz-l.js → auth-catchall-CIvttEN1.js} +1 -1
- package/dist/client/assets/{auth-entry-BajIlMdm.js → auth-entry-D4lmldKW.js} +1 -1
- package/dist/client/assets/{auth-split-layout-D6WedxZg.js → auth-split-layout-BJHpY4m1.js} +1 -1
- package/dist/client/assets/{authenticate-and-persist-oauth-m-asDg6n.js → authenticate-and-persist-oauth-C2niz4aW.js} +1 -1
- package/dist/client/assets/{automation-list-row-DJMycimP.js → automation-list-row-DOKJeKYO.js} +1 -1
- package/dist/client/assets/{automation-runs-CqHPmpxv.js → automation-runs-OtdSB4BI.js} +1 -1
- package/dist/client/assets/{automations-C2Lr7QaY.js → automations-B9ewyt3l.js} +1 -1
- package/dist/client/assets/{avatar-BWQUoICI.js → avatar-BXWNF77j.js} +1 -1
- package/dist/client/assets/{badge-BD99e01N.js → badge-DAoU6Imp.js} +1 -1
- package/dist/client/assets/{billing-DVQqzRq6.js → billing-B_QTma3a.js} +1 -1
- package/dist/client/assets/{block-document-Dv7Gc42u.js → block-document-BjlKi5WF.js} +1 -1
- package/dist/client/assets/{brand-context-C0OLaukl.js → brand-context-D4Ly8FY6.js} +1 -1
- package/dist/client/assets/{buckets-9Z92uR8k.js → buckets-Bqv0L4nF.js} +1 -1
- package/dist/client/assets/{bulk-category-panel-BBWt46dQ.js → bulk-category-panel-D6dr2KuO.js} +1 -1
- package/dist/client/assets/{capability-load-error-aoMpKIlH.js → capability-load-error-D7FJThIs.js} +1 -1
- package/dist/client/assets/{card-Q8NTBpN6.js → card-CqzhZRSV.js} +1 -1
- package/dist/client/assets/{cards-CPa_UBVS.js → cards--2WkELWt.js} +1 -1
- package/dist/client/assets/{category-editor-DJlTri60.js → category-editor-DzJMnASB.js} +1 -1
- package/dist/client/assets/{chat-context-CoLr-7Td.js → chat-context-CPTHsiXT.js} +1 -1
- package/dist/client/assets/{checkbox-BASIfudC.js → checkbox-DQLcQWSw.js} +1 -1
- package/dist/client/assets/{cli-auth-success-BGb-r5QN.js → cli-auth-success-DjUc2KM9.js} +1 -1
- package/dist/client/assets/{collection-detail-D-wnO3ND.js → collection-detail-CQ42GoY4.js} +1 -1
- package/dist/client/assets/{collection-display-button-DqZ6npbm.js → collection-display-button-Cblelkyf.js} +1 -1
- package/dist/client/assets/{collection-search-DcjOoVI2.js → collection-search-DgyknVYJ.js} +1 -1
- package/dist/client/assets/{collection-table-wrapper-Dk-tpqRQ.js → collection-table-wrapper-CLzjGn94.js} +1 -1
- package/dist/client/assets/{collection-tabs-B3mYYxtz.js → collection-tabs-_w1KzSrn.js} +1 -1
- package/dist/client/assets/{command-Ceu-kj97.js → command-ZczUCKOE.js} +1 -1
- package/dist/client/assets/{commerce-onboarding-DUJNwI7O.js → commerce-onboarding-Ch2Kvk2v.js} +1 -1
- package/dist/client/assets/{connect-BEPfCsr6.js → connect-C3Le2MXn.js} +1 -1
- package/dist/client/assets/{connection-DOaeV_kP.js → connection-CEk4ULDk.js} +1 -1
- package/dist/client/assets/{connection-card-Deg3-TR-.js → connection-card-DdbLECLO.js} +1 -1
- package/dist/client/assets/{connection-detail-Bk5VXyWe.js → connection-detail-C3tTPFQD.js} +1 -1
- package/dist/client/assets/{connection-form-helpers-CFUSjuXx.js → connection-form-helpers-pxk9NpaA.js} +1 -1
- package/dist/client/assets/{connections-LSfHgCu1.js → connections-DgpUiyqr.js} +1 -1
- package/dist/client/assets/{decopilot-sse-pool-Bq7TSvHG.js → decopilot-sse-pool-l6_CQjlA.js} +1 -1
- package/dist/client/assets/{dialog-BZBN7yPR.js → dialog-C1nMHamp.js} +1 -1
- package/dist/client/assets/{domain-settings-DrtoaW-K.js → domain-settings-DS_O4W-Z.js} +1 -1
- package/dist/client/assets/{drawer-Dj5L09kg.js → drawer-DEkxI9w4.js} +1 -1
- package/dist/client/assets/{dropdown-menu-DHH3iD92.js → dropdown-menu-A0sNkJ-D.js} +1 -1
- package/dist/client/assets/{empty-state-CMN5pa17.js → empty-state-DXjPkc2c.js} +1 -1
- package/dist/client/assets/{extract-connection-data-DAqv-qPI.js → extract-connection-data-Cn56rg8y.js} +1 -1
- package/dist/client/assets/{file-explorer-C557qhnE.js → file-explorer-C3DFjQ2p.js} +1 -1
- package/dist/client/assets/{file-type-icon-DmvBRayd.js → file-type-icon-CfHt3K89.js} +1 -1
- package/dist/client/assets/{form-gddDxci6.js → form-R10hO2J-.js} +1 -1
- package/dist/client/assets/{general-NAmVMCQn.js → general-BR8lLLsO.js} +1 -1
- package/dist/client/assets/{github-repo-picker-DoldcKAI.js → github-repo-picker-C7HmB7sD.js} +1 -1
- package/dist/client/assets/{hooks-BivAORDM.js → hooks-PrPdbNKh.js} +1 -1
- package/dist/client/assets/{index-BI8RlZy1.js → index-6CjSbeiO.js} +6 -6
- package/dist/client/assets/{index-BXVYW9oP.js → index-B3atnTOD.js} +3 -3
- package/dist/client/assets/{index-D6wAeEnj.js → index-BncSXQMZ.js} +1 -1
- package/dist/client/assets/{index-C3e4oIeI.js → index-CWpL3L1c.js} +1 -1
- package/dist/client/assets/{index-CZBiyydb.js → index-D05cQ3iM.js} +1 -1
- package/dist/client/assets/{index-BZh9-lzE.js → index-D0v2h85f.js} +1 -1
- package/dist/client/assets/{index-vqCvC9eJ.js → index-D5m1bkFb.js} +1 -1
- package/dist/client/assets/{index-BLUB_qjx.js → index-S4-F33Y4.js} +1 -1
- package/dist/client/assets/{index-DGR7yvKF.js → index-UJExPiWH.js} +1 -1
- package/dist/client/assets/{index-DdGA8161.js → index-fnW3g-fp.js} +1 -1
- package/dist/client/assets/{index-redirect-CTbbS_hA.js → index-redirect-pKYyB43h.js} +1 -1
- package/dist/client/assets/{input-DtyDjASp.js → input-CGnplup6.js} +1 -1
- package/dist/client/assets/{integration-icon-C9RLqPaZ.js → integration-icon-C_pPMzGj.js} +1 -1
- package/dist/client/assets/{invite-member-dialog-Br5PsR4J.js → invite-member-dialog-C_aJOXl_.js} +1 -1
- package/dist/client/assets/{label-D2Kr2ps4.js → label-DfxdANU7.js} +1 -1
- package/dist/client/assets/{layout-_DSy7bld.js → layout-uQx0l2IO.js} +1 -1
- package/dist/client/assets/{login-B-vpJ6Sv.js → login-CqR87GVZ.js} +1 -1
- package/dist/client/assets/{mcp-oauth-D6VatWgr.js → mcp-oauth-BsOFbQiK.js} +1 -1
- package/dist/client/assets/{members-CqY-mSvl.js → members-B_mSaJSC.js} +1 -1
- package/dist/client/assets/{monaco-editor-D6W9Jn6M.js → monaco-editor-7A-fQDgF.js} +1 -1
- package/dist/client/assets/{monitoring-stats-row-BYYAmZwq.js → monitoring-stats-row-BIhRW2GN.js} +1 -1
- package/dist/client/assets/{multi-select-F0tvBxHe.js → multi-select-CYuaNCqS.js} +1 -1
- package/dist/client/assets/{oauth-callback-Duy_WTtg.js → oauth-callback-D3o7fRHA.js} +1 -1
- package/dist/client/assets/{oauth-callback-ai-provider-BbYdrMki.js → oauth-callback-ai-provider-BDp9u1N_.js} +1 -1
- package/dist/client/assets/{onboarding-D8vUdXJm.js → onboarding-CWgzyIuE.js} +1 -1
- package/dist/client/assets/{org-layout-PT-cdJq6.js → org-layout-hJGjBdI1.js} +1 -1
- package/dist/client/assets/{organization-choice-B4oxFfFi.js → organization-choice-CfASQLFM.js} +1 -1
- package/dist/client/assets/{orgs-B72jiP78.js → orgs-BCbdr2Ag.js} +1 -1
- package/dist/client/assets/{page-seo-form-D9BIlNMP.js → page-seo-form-CZ55g9px.js} +1 -1
- package/dist/client/assets/{popover-f75RcDnM.js → popover-CWSecgpe.js} +1 -1
- package/dist/client/assets/{post-editor-aKLsNoxQ.js → post-editor--VaER4Le.js} +1 -1
- package/dist/client/assets/{primitives-BulEqTk5.js → primitives-DUTJ8tSg.js} +1 -1
- package/dist/client/assets/{profile-Bz5nmZG8.js → profile-BHMEwPiN.js} +1 -1
- package/dist/client/assets/{project-app-view-CrLLWzk_.js → project-app-view-CnenONgb.js} +1 -1
- package/dist/client/assets/record-editor-dBivEJpB.js +1 -0
- package/dist/client/assets/redirect-editor-CW3Oe-2X.js +1 -0
- package/dist/client/assets/registry-C21U36Lk.js +2 -0
- package/dist/client/assets/{registry-layout-L13Wfh9O.js → registry-layout-qYPm_LZb.js} +1 -1
- package/dist/client/assets/{reports-CQfwgHi2.js → reports-Dlzghqyq.js} +1 -1
- package/dist/client/assets/{require-capability-DQT0lYQq.js → require-capability-BG_iELo7.js} +1 -1
- package/dist/client/assets/{required-auth-layout-D7c0rFdn.js → required-auth-layout-D6aEDoml.js} +1 -1
- package/dist/client/assets/{reset-password-BMk18Luc.js → reset-password-CtLUTKQQ.js} +1 -1
- package/dist/client/assets/{roles-wTfozYTs.js → roles-D6ATKv7U.js} +1 -1
- package/dist/client/assets/{search-input-Cf-LChTS.js → search-input-hKyul0tm.js} +1 -1
- package/dist/client/assets/{secrets-OFSQumDS.js → secrets-D9vMgbHZ.js} +1 -1
- package/dist/client/assets/{sections-editor-Bwa2gdDU.js → sections-editor-BlmmXO47.js} +1 -1
- package/dist/client/assets/{select-model-CPsRo-oU.js → select-model-CoMCgT-3.js} +2 -2
- package/dist/client/assets/{select-aJ268xVp.js → select-n13gZUR4.js} +1 -1
- package/dist/client/assets/{self-tool-result-DXhPzl10.js → self-tool-result-DUk5meEa.js} +1 -1
- package/dist/client/assets/{seo-editor-B9rgHeRD.js → seo-editor-C1qvHDNz.js} +1 -1
- package/dist/client/assets/{settings-layout-B6Iq9TWm.js → settings-layout-CApJl47p.js} +1 -1
- package/dist/client/assets/{settings-section-LwQq77KG.js → settings-section-D4f-00oI.js} +1 -1
- package/dist/client/assets/{shell-controls-BX1rmK9p.js → shell-controls-BnST0ag_.js} +1 -1
- package/dist/client/assets/{shell-layout-CPkbkQME.js → shell-layout-CPfuamIU.js} +1 -1
- package/dist/client/assets/{sidebar-D0z5Cxuk.js → sidebar-Lv799Z-V.js} +1 -1
- package/dist/client/assets/{skeleton-SjlBCcjX.js → skeleton-Djn5TkUR.js} +1 -1
- package/dist/client/assets/{spinner-CQMfz22E.js → spinner-ChNwS7_i.js} +1 -1
- package/dist/client/assets/{sso-C_4KT5op.js → sso-BkEIQ9Cs.js} +1 -1
- package/dist/client/assets/{store-kZT1zfks.js → store-Cc1VFpBL.js} +1 -1
- package/dist/client/assets/store-registry-DBPVslgv.js +2 -0
- package/dist/client/assets/{studio-tools-B0_AcSKZ.js → studio-tools-BtWHGFPU.js} +1 -1
- package/dist/client/assets/{switch-CIB0IRpT.js → switch-1BnhIFND.js} +1 -1
- package/dist/client/assets/{synced-repos-DMVeJBA2.js → synced-repos-BKWg-xbi.js} +1 -1
- package/dist/client/assets/{tab-id-Byz2SGQX.js → tab-id-CRGilEHg.js} +1 -1
- package/dist/client/assets/{table-DfBXbFhT.js → table-0E7ZOwvy.js} +1 -1
- package/dist/client/assets/{tabs-CI8QRrap.js → tabs-D8y23nM4.js} +1 -1
- package/dist/client/assets/{textarea-BUW4RF90.js → textarea-C5-ccd3M.js} +1 -1
- package/dist/client/assets/{toggle-group-toV2h8do.js → toggle-group-DHdlMPfI.js} +1 -1
- package/dist/client/assets/{toolbar-xM6JfAiK.js → toolbar-DDqrHoei.js} +1 -1
- package/dist/client/assets/{tooltip-CB-3W3BK.js → tooltip-KklTekq-.js} +1 -1
- package/dist/client/assets/{track-AKOKRozN.js → track-Dw02MQy6.js} +1 -1
- package/dist/client/assets/{use-ai-providers-0mfYVNtG.js → use-ai-providers-CN1yjbVc.js} +1 -1
- package/dist/client/assets/{use-automations-zV3k_hCm.js → use-automations-CC95HsJ3.js} +1 -1
- package/dist/client/assets/{use-autosave-CCaPm49b.js → use-autosave-DqUaFQu2.js} +1 -1
- package/dist/client/assets/{use-capability-Bx72zdZ_.js → use-capability-BJXC5dNN.js} +1 -1
- package/dist/client/assets/{use-clock-tick-C6Dl4_Ba.js → use-clock-tick-D1xip4IB.js} +1 -1
- package/dist/client/assets/{use-connection-CU1SASjJ.js → use-connection-C1X3lSVO.js} +1 -1
- package/dist/client/assets/{use-copy-Ba8GdO7e.js → use-copy-CeBzb7Hf.js} +1 -1
- package/dist/client/assets/{use-create-virtual-mcp-CyajPsvg.js → use-create-virtual-mcp-C5qrolYI.js} +1 -1
- package/dist/client/assets/{use-debounced-autosave-XWEF6ylb.js → use-debounced-autosave-BQ-qnhi7.js} +1 -1
- package/dist/client/assets/{use-debounced-value-DaP2Vfp5.js → use-debounced-value-D7TAcVXO.js} +1 -1
- package/dist/client/assets/{use-deco-credits-D5amWKZw.js → use-deco-credits-LrXk-MBS.js} +1 -1
- package/dist/client/assets/{use-decopilot-events-DT8RjZZF.js → use-decopilot-events-CxiZgv6A.js} +1 -1
- package/dist/client/assets/{use-delete-connection-DWapIKyB.js → use-delete-connection-BAm9G1ay.js} +1 -1
- package/dist/client/assets/{use-deployment-admin-CQ19naZH.js → use-deployment-admin-DCwfUCBl.js} +1 -1
- package/dist/client/assets/{use-file-configs-we2-KED_.js → use-file-configs-MR70qXpO.js} +1 -1
- package/dist/client/assets/{use-infinite-scroll-f_QDwgM2.js → use-infinite-scroll-B7qrPvcH.js} +1 -1
- package/dist/client/assets/{use-join-requests-CM9otB1q.js → use-join-requests-DHGypITc.js} +1 -1
- package/dist/client/assets/{use-mcp-client-B3Khr26S.js → use-mcp-client-DkEyYZ91.js} +1 -1
- package/dist/client/assets/{use-mcp-tools-DWI2d4P3.js → use-mcp-tools-Bt0DfVe_.js} +1 -1
- package/dist/client/assets/{use-members-nTp0kq-0.js → use-members-JHZsQmeP.js} +1 -1
- package/dist/client/assets/{use-mobile-BY2sIYXP.js → use-mobile-C4LZ2U9I.js} +1 -1
- package/dist/client/assets/{use-navigate-to-agent-BHUKMXo3.js → use-navigate-to-agent-BsT9Q7NC.js} +1 -1
- package/dist/client/assets/{use-open-billing-url-95NAs9uM.js → use-open-billing-url-DPFRpHrg.js} +1 -1
- package/dist/client/assets/{use-org-auth-client-DNlUjzOt.js → use-org-auth-client-Cmf_KmfK.js} +1 -1
- package/dist/client/assets/{use-org-sso-BnAzSLsE.js → use-org-sso-C2ZQyqYB.js} +1 -1
- package/dist/client/assets/{use-organization-roles-ISpyLphz.js → use-organization-roles-Bk3bgJkD.js} +1 -1
- package/dist/client/assets/{use-organization-settings-DfmtKg6Y.js → use-organization-settings-DkHjE6yi.js} +1 -1
- package/dist/client/assets/{use-registry-connections-CDv9RFLk.js → use-registry-connections-DcHhsRqb.js} +1 -1
- package/dist/client/assets/{use-secrets-C_hE5_Ph.js → use-secrets-BGgsRw_P.js} +1 -1
- package/dist/client/assets/{use-section-preview-base-DtbFyFHR.js → use-section-preview-base-DIDG5POH.js} +1 -1
- package/dist/client/assets/{use-status-sounds-Bhnnb3cr.js → use-status-sounds-hGNAJHvg.js} +1 -1
- package/dist/client/assets/{use-tags-BDvedplZ.js → use-tags-DEzUFQ7U.js} +1 -1
- package/dist/client/assets/{use-view-mode-D9uXQ7e4.js → use-view-mode-BegGRW-e.js} +1 -1
- package/dist/client/assets/{use-virtual-mcp-C-5DJUHP.js → use-virtual-mcp-BUnJVmrT.js} +1 -1
- package/dist/client/assets/useInfiniteQuery-BtNh17CA.js +1 -0
- package/dist/client/assets/{useRouterState-Cv8oHX_r.js → useRouterState-Ca4BToWn.js} +1 -1
- package/dist/client/assets/useSuspenseInfiniteQuery-BT-eDQF7.js +1 -0
- package/dist/client/assets/{users-BHiQlXv0.js → users-DLfBM_bR.js} +1 -1
- package/dist/client/assets/{variant-calendar-6Gxt9aCh.js → variant-calendar-Buhzl5PJ.js} +1 -1
- package/dist/client/assets/{view-mode-toggle-bHA445xz.js → view-mode-toggle-CAtnr8E3.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-Ex3YfX4K.js +0 -1
- package/dist/client/assets/redirect-editor-BoPWn8Ri.js +0 -1
- package/dist/client/assets/registry-DpLBrpGJ.js +0 -2
- package/dist/client/assets/store-registry-Jb0qyTz9.js +0 -2
- package/dist/client/assets/useInfiniteQuery-BhIEZ0f1.js +0 -1
- package/dist/client/assets/useSuspenseInfiniteQuery-Dlc1Th2H.js +0 -1
package/dist/server/cli.js
CHANGED
|
@@ -1332,7 +1332,7 @@ Usage: deco services <up|down|status>`),process.exit(1)}}var jd1=O(()=>{ix()});f
|
|
|
1332
1332
|
`.execute($);if(Number(W.rows[0]?.cnt)===0){console.warn(`Failed to migrate ${J}/${K}, keeping in old table`);continue}}await zb`
|
|
1333
1333
|
DELETE FROM kysely_migration WHERE name = ${X}
|
|
1334
1334
|
`.execute($)}}async function gp1($){await km6($),await Sm6($);let Z=new bp1({db:$,provider:{getMigrations:()=>Promise.resolve(Gm0)}}),{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 Cm6($){let{keepOpen:Z=!1,database:X,skipBetterAuth:Q=!1}=$??{},Y="skipped";if(!Q&&!X)Y=await ku0();let G=X??N6(),J=async()=>{if(!Z&&!X)await jw(G).catch((K)=>{console.warn("Warning: Error closing database:",K)})};try{let K=await gp1(G.db);return await J(),{betterAuth:Y,kysely:K}}catch(K){throw await J(),K}}async function _m6(){let $=N6(),Z=new bp1({db:$.db,provider:{getMigrations:()=>Promise.resolve(Gm0)}}),{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 up1=O(()=>{fp1();Su0();$X()});async function _90($){let Z={...process.env},X=I10($,Z);console.log($B1(X.settings.encryptionKey));let Q=X.settings.betterAuthSecret||(X.settings.localMode?am1(X.settings.dataDir):""),{ensureServices:Y}=await Promise.resolve().then(() => (l50(),c50)),{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(() => (Su0(),em1));await W(G.databaseUrl);let{createDatabase:H}=await Promise.resolve().then(() => ($X(),Om1)),{migrateToLatest:U}=await Promise.resolve().then(() => (up1(),hp1)),N=H(G.databaseUrl);await U({keepOpen:!0,database:N,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 Pd1(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 Jm0=O(()=>{ix();sm1();k8()});var dp1={};B0(dp1,{updateService:()=>QE,subscribeCliState:()=>Hm0,setTuiConsoleIntercepted:()=>v90,setServerUrl:()=>$i,setMigrationsDone:()=>em,setDevMode:()=>fm6,resetCliStateForTests:()=>vm6,isTuiConsoleIntercepted:()=>x90,getCliState:()=>Wm0,addLogEntry:()=>Iw});function cp1(){return{services:[{name:"Postgres",status:"pending",port:0},{name:"NATS",status:"pending",port:0}],migrationsStatus:"pending",serverUrl:null,logs:[]}}function vm6(){fQ=cp1()}function xm6(){return[{name:"Postgres",status:"pending",port:0},{name:"NATS",status:"pending",port:0}]}function sm(){for(let $ of Km0)$()}function Wm0(){return fQ}function Hm0($){return Km0.add($),()=>Km0.delete($)}function QE($){fQ={...fQ,services:fQ.services.map((Z)=>Z.name===$.name?$:Z)},sm()}function em(){fQ={...fQ,migrationsStatus:"done"},sm()}function $i($){fQ={...fQ,serverUrl:$},sm()}function Iw($){let Z=[...fQ.logs,$];fQ={...fQ,logs:Z.length>500?Z.slice(-500):Z},sm()}function fm6(){fQ={...fQ,services:[...xm6(),{name:"API",status:"pending",port:0},{name:"Vite",status:"pending",port:0}]},sm()}function v90($){lp1=$}function x90(){return lp1}var fQ,Km0,lp1=!1;var YE=O(()=>{fQ=cp1();Km0=new Set});import{createServer as mp1}from"net";function bm6($){return new Promise((Z)=>{let X=mp1();X.once("error",()=>Z(!1)),X.listen($,"0.0.0.0",()=>{X.close(()=>Z(!0))})})}async function Zi($){if(await bm6($))return $;let Z=await new Promise((X,Q)=>{let Y=mp1();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 Um0=()=>{};function Xi($){return $.replace(/\x1b\[[0-9;]*m/g,"")}var Nm0={};B0(Nm0,{startDevServer:()=>gm6});import{join as ym6}from"path";function ip1($){let Z=$.getReader(),X=new TextDecoder,Q="";function Y(){let G=Q.split(`
|
|
1335
|
-
`);Q=G.pop()??"";for(let J of G){let K=Xi(J).replace(/^\[\d+\]\s*/,"").trim();if(!K)continue;Iw({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=Xi(Q).replace(/^\[\d+\]\s*/,"").trim();if(G)Iw({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:G})}})()}async function gm6($){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 Zi(Number(Y)+1):await Zi(Number($.port)),{settings:K,services:W,managedServiceNames:H}=await _90({port:String(J),home:$.home,baseUrl:$.baseUrl,localMode:$.localMode,skipMigrations:$.skipMigrations,noTui:$.noTui,vitePort:$.vitePort});for(let L of W)QE({name:L.name,status:"ready",port:L.port});em();let U=ym6(import.meta.dir,"..","..","..","..",".."),N=X===!0,F=Bun.spawn(["bun","run","dev:servers"],{cwd:U,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",N?"inherit":"pipe",N?"inherit":"pipe"]});if(!N)ip1(F.stdout),ip1(F.stderr);$i(G),QE({name:"Vite",status:"ready",port:Number(Y)}),QE({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(() => (l50(),c50));await D(K.dataDir)}};return process.on("SIGINT",()=>B("SIGINT")),process.on("SIGTERM",()=>B("SIGTERM")),{port:Number(Y),process:F}}var Fm0=O(()=>{Jm0();YE();Um0()});var f90;var wm0=O(()=>{f90={name:"decocms",version:"4.213.2",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 um6,Text as np1}from"ink";import{jsx as cm6,jsxs as pp1}from"react/jsx-runtime";function tp1({version:$}){return pp1(um6,{flexDirection:"column",marginTop:1,children:[H90.map((Z,X)=>cm6(np1,{color:U90[X],children:Z},X)),pp1(np1,{dimColor:!0,children:[" v",$]})]})}var op1=O(()=>{cm()});import{Box as GE,Text as qw}from"ink";import{Spinner as lm6}from"@inkjs/ui";import{jsx as nY,jsxs as jb}from"react/jsx-runtime";function rp1({status:$}){if($==="pending")return nY(lm6,{label:""});return nY(qw,{color:"green",children:"\u2713"})}function dm6($){return`${$.name}: ${$.port||"...."}`}function ap1({services:$,migrationsStatus:Z,home:X,serverUrl:Q}){return jb(GE,{flexDirection:"column",paddingBottom:1,children:[nY(tp1,{version:f90.version}),nY(GE,{marginBottom:1,children:nY(qw,{dimColor:!0,children:"\u2500".repeat(80)})}),nY(GE,{children:jb(qw,{dimColor:!0,children:["Home: ",X]})}),jb(GE,{gap:2,children:[$.map((Y)=>jb(GE,{gap:1,children:[nY(qw,{children:dm6(Y)}),nY(rp1,{status:Y.status})]},Y.name)),jb(GE,{gap:1,children:[nY(qw,{children:"Migrations"}),nY(rp1,{status:Z})]})]}),nY(GE,{children:Q?jb(qw,{children:["Open in browser: ",nY(qw,{color:"cyan",children:Q})]}):nY(qw,{dimColor:!0,children:"Starting..."})})]})}var sp1=O(()=>{wm0();op1()});import{Box as mm6,Text as Qi}from"ink";import{jsx as Bm0,jsxs as Om0}from"react/jsx-runtime";function im6($){if($>=500)return"red";if($>=400)return"yellow";if($>=300)return"cyan";return"green"}function ep1({logs:$}){return Bm0(mm6,{flexDirection:"column",children:$.map((Z,X)=>{if(Z.rawLine)return Bm0(Qi,{dimColor:!0,children:Z.rawLine},X);let Q=Z.duration<1000?`${Z.duration}ms`:`${(Z.duration/1000).toFixed(1)}s`;return Om0(Qi,{children:[Om0(Qi,{dimColor:!0,children:[Z.method.padEnd(6)," ",Z.path.padEnd(30)," "]}),Bm0(Qi,{color:im6(Z.status),children:Z.status}),Om0(Qi,{dimColor:!0,children:[" ",Q.padStart(8)]})]},X)})})}var $t1=()=>{};var Lm0={};B0(Lm0,{App:()=>tm6});import{Box as nm6}from"ink";import{useSyncExternalStore as pm6}from"react";import{jsx as Zt1,jsxs as om6}from"react/jsx-runtime";function tm6({home:$}){let Z=pm6(Hm0,Wm0);return om6(nm6,{flexDirection:"column",children:[Zt1(ap1,{services:Z.services,migrationsStatus:Z.migrationsStatus,home:$,serverUrl:Z.serverUrl}),Zt1(ep1,{logs:Z.logs})]})}var Dm0=O(()=>{sp1();$t1();YE()});var AJ="thread-gate",yU="decopilot-hosted-harness",Z3="automations",Mw="background-tools",JE="task-board-github-reads";var Xt1="7";function Qt1($){return{name:"decocms",systemDatabaseUrl:$.systemDatabaseUrl,systemDatabaseSchemaName:"dbos",systemDatabasePoolSize:$.poolSize,runAdminServer:!1,executorID:$.executorID,applicationVersion:Xt1,...$.listenQueues!==void 0?{listenQueues:$.listenQueues}:{}}}var Yt1=()=>{};function rm6(){let $=(process.env.BUN_OPTIONS??"").split(/\s+/).filter(Boolean);return[...process.argv.slice(1),...$]}function Em0($,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 Gt1(){let $=rm6();if($.includes("--cpu-prof")){console.log(JSON.stringify({msg:"cpu-profiling-active",dir:Em0($,"--cpu-prof-dir")??process.cwd(),name:Em0($,"--cpu-prof-name"),markdown:$.includes("--cpu-prof-md"),intervalUs:Number(Em0($,"--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 Jt1(){if(process.env.HEAP_WATCH!=="1")return()=>{};let $=Number(process.env.HEAP_WATCH_INTERVAL_MS??60000),Z=async()=>{let X=eD();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(()=>{}),b90=setInterval(()=>void Z().catch(()=>{}),$),b90.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(b90)clearInterval(b90)}}var b90;var Kt1=()=>{};import*as am6 from"bun:jsc";function Wt1(){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{sm6()}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=em6()?.traces??[]}catch{}if(J>$&&K.length>0){let W=new Map;for(let U of K){let N=U.frames.find((B)=>B.sourceURL&&!/Unknown Executable/.test(B.category??""))??U.frames[0];if(!N)continue;let F=(N.sourceURL??"?").replace(/^.*\/node_modules\//,"node_modules/"),w=`${N.name??"?"} @ ${F}:${N.line??"?"}`;W.set(w,(W.get(w)??0)+1)}let H=[...W.entries()].sort((U,N)=>N[1]-U[1]).slice(0,8).map(([U,N])=>({frame:U,count:N}));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 sm6,em6;var Ht1=O(()=>{({startSamplingProfiler:sm6,samplingProfilerStackTraces:em6}=am6)});function Ut1(){Gt1();let $=[Jt1(),Km1(),Wt1()];return()=>{for(let Z of $)Z()}}var Nt1=O(()=>{zu0();Kt1();Ht1()});var KE=_((Ft1)=>{Object.defineProperty(Ft1,"__esModule",{value:!0});Ft1.RepublishHeaders=Ft1.DirectMsgHeaders=Ft1.JsHeaders=Ft1.AdvisoryKind=void 0;Ft1.isOrderedPushConsumerOptions=$i6;Ft1.isPullConsumer=Zi6;Ft1.isPushConsumer=Xi6;Ft1.isBoundPushConsumerOptions=Qi6;function $i6($){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 Zi6($){return $.isPullConsumer()}function Xi6($){return $.isPushConsumer()}function Qi6($){if($&&typeof $==="object")return"deliver_subject"in $||"deliver_group"in $||"idle_heartbeat"in $;return!1}Ft1.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"};Ft1.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"};Ft1.DirectMsgHeaders={Stream:"Nats-Stream",Sequence:"Nats-Sequence",TimeStamp:"Nats-Time-Stamp",Subject:"Nats-Subject",LastSequence:"Nats-Last-Sequence",NumPending:"Nats-Num-Pending"};Ft1.RepublishHeaders={Stream:"Nats-Stream",Subject:"Nats-Subject",Sequence:"Nats-Sequence",LastSequence:"Nats-Last-Sequence",Size:"Nats-Msg-Size"}});var pY=_((Bt1)=>{Object.defineProperty(Bt1,"__esModule",{value:!0});Bt1.TD=Bt1.TE=Bt1.Empty=void 0;Bt1.encode=Fi6;Bt1.decode=wi6;Bt1.Empty=new Uint8Array(0);Bt1.TE=new TextEncoder;Bt1.TD=new TextDecoder;function Ni6(...$){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 Fi6(...$){let Z=[];for(let X=0;X<$.length;X++)Z.push(Bt1.TE.encode($[X]));if(Z.length===0)return Bt1.Empty;if(Z.length===1)return Z[0];return Ni6(...Z)}function wi6($){if(!$||$.length===0)return"";return Bt1.TD.decode($)}});var tY=_((Dt1)=>{Object.defineProperty(Dt1,"__esModule",{value:!0});Dt1.errors=Dt1.PermissionViolationError=Dt1.NoRespondersError=Dt1.TimeoutError=Dt1.RequestError=Dt1.ProtocolError=Dt1.ConnectionError=Dt1.DrainingConnectionError=Dt1.ClosedConnectionError=Dt1.AuthorizationError=Dt1.UserAuthenticationExpiredError=Dt1.InvalidOperationError=Dt1.InvalidArgumentError=Dt1.InvalidSubjectError=void 0;class jm0 extends Error{constructor($,Z){super(`illegal subject: '${$}'`,Z);this.name="InvalidSubjectError"}}Dt1.InvalidSubjectError=jm0;class y90 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 y90(`${$} ${Z}`,X)}}Dt1.InvalidArgumentError=y90;class Pm0 extends Error{constructor($,Z){super($,Z);this.name="InvalidOperationError"}}Dt1.InvalidOperationError=Pm0;class g90 extends Error{constructor($,Z){super($,Z);this.name="UserAuthenticationExpiredError"}static parse($){if($.toLowerCase().indexOf("user authentication expired")!==-1)return new g90($);return null}}Dt1.UserAuthenticationExpiredError=g90;class h90 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 h90($);return null}}Dt1.AuthorizationError=h90;class Am0 extends Error{constructor(){super("closed connection");this.name="ClosedConnectionError"}}Dt1.ClosedConnectionError=Am0;class Tm0 extends Error{constructor(){super("connection draining");this.name="DrainingConnectionError"}}Dt1.DrainingConnectionError=Tm0;class Rm0 extends Error{constructor($,Z){super($,Z);this.name="ConnectionError"}}Dt1.ConnectionError=Rm0;class Im0 extends Error{constructor($,Z){super($,Z);this.name="ProtocolError"}}Dt1.ProtocolError=Im0;class qm0 extends Error{constructor($="",Z){super($,Z);this.name="RequestError"}isNoResponders(){return this.cause instanceof u90}}Dt1.RequestError=qm0;class Mm0 extends Error{constructor($){super("timeout",$);this.name="TimeoutError"}}Dt1.TimeoutError=Mm0;class u90 extends Error{subject;constructor($,Z){super(`no responders: '${$}'`,Z);this.subject=$,this.name="NoResponders"}}Dt1.NoRespondersError=u90;class c90 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 c90($,X,Q,Y)}}Dt1.PermissionViolationError=c90;Dt1.errors={AuthorizationError:h90,ClosedConnectionError:Am0,ConnectionError:Rm0,DrainingConnectionError:Tm0,InvalidArgumentError:y90,InvalidOperationError:Pm0,InvalidSubjectError:jm0,NoRespondersError:u90,PermissionViolationError:c90,ProtocolError:Im0,RequestError:qm0,TimeoutError:Mm0,UserAuthenticationExpiredError:g90}});var TJ=_((At1)=>{Object.defineProperty(At1,"__esModule",{value:!0});At1.SimpleMutex=At1.Perf=void 0;At1.extend=Si6;At1.render=Ci6;At1.timeout=_i6;At1.delay=vi6;At1.deadline=xi6;At1.deferred=km0;At1.debugDeferred=fi6;At1.shuffle=bi6;At1.collect=yi6;At1.jitter=Pt1;At1.backoff=gi6;At1.nanos=hi6;At1.millis=ui6;At1.randomToken=di6;var ki6=pY(),Vm0=tY();function Si6($,...Z){for(let X=0;X<Z.length;X++){let Q=Z[X];Object.keys(Q).forEach(function(Y){$[Y]=Q[Y]})}return $}function Ci6($){return ki6.TD.decode($).replace(/\n/g,"\u240A").replace(/\r/g,"\u240D")}function _i6($,Z=!0){let X=Z?new Vm0.TimeoutError:null,Q,Y,G=new Promise((J,K)=>{Q={cancel:()=>{if(Y)clearTimeout(Y)}},Y=setTimeout(()=>{if(X===null)K(new Vm0.TimeoutError);else K(X)},$)});return Object.assign(G,Q)}function vi6($=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 xi6($,Z=1000){let X=km0(),Q=setTimeout(()=>{X.reject(new Vm0.TimeoutError)},Z);try{return await Promise.race([$,X])}finally{clearTimeout(Q)}}function km0(){let $={},Z=new Promise((X,Q)=>{$={resolve:X,reject:Q}});return Object.assign(Z,$)}function fi6(){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 bi6($){for(let Z=$.length-1;Z>0;Z--){let X=Math.floor(Math.random()*(Z+1));[$[Z],$[X]]=[$[X],$[Z]]}return $}async function yi6($){let Z=[];for await(let X of $)Z.push(X);return Z}class zt1{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})}),$}}At1.Perf=zt1;class jt1{max;current;waiting;constructor($=1){this.max=$,this.current=0,this.waiting=[]}lock(){if(this.current++,this.current<=this.max)return Promise.resolve();let $=km0();return this.waiting.push($),$}unlock(){this.current--,this.waiting.pop()?.resolve()}}At1.SimpleMutex=jt1;function Pt1($){if($===0)return 0;return Math.floor($/2+Math.random()*$)}function gi6($=[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 Pt1(X>Z?$[Z]:$[X])}}}function hi6($){return $*1e6}function ui6($){return Math.floor($/1e6)}var ci6="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",gU=new Uint8Array(62);for(let $=0;$<62;$++)gU[$]=ci6.charCodeAt($);var li6=218340105584896;function di6(){let $=Math.floor(Math.random()*li6),Z=$%62,X=gU[Z];$=($-Z)/62,Z=$%62;let Q=gU[Z];$=($-Z)/62,Z=$%62;let Y=gU[Z];$=($-Z)/62,Z=$%62;let G=gU[Z];$=($-Z)/62,Z=$%62;let J=gU[Z];$=($-Z)/62,Z=$%62;let K=gU[Z];$=($-Z)/62,Z=$%62;let W=gU[Z];$=($-Z)/62;let H=gU[$];return String.fromCharCode(X,Q,Y,G,J,K,W,H)}});var St1=_((Vt1)=>{Object.defineProperty(Vt1,"__esModule",{value:!0});Vt1.nuid=Vt1.NuidImpl=void 0;var Gn6="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Vw=62,d90=12,qt1=10,Rt1=33,Jn6=333,It1=d90+qt1,Cm0=new Uint8Array(Vw);for(let $=0;$<Vw;$++)Cm0[$]=Gn6.charCodeAt($);var l90=4294967296,Mt1=BigInt(Vw)**BigInt(qt1),Yi=Number(Mt1/(1n<<32n)),Sm0=Number(Mt1%(1n<<32n));function Kn6($){for(let Z=0;Z<$.length;Z++)$[Z]=Math.floor(Math.random()*256)}function Wn6($){if(globalThis?.crypto?.getRandomValues)globalThis.crypto.getRandomValues($);else Kn6($)}class _m0{buf;cbuf;seqHi;seqLo;inc;inited;constructor(){this.buf=new Uint8Array(It1),this.cbuf=new Uint8Array(d90),this.inited=!1}init(){this.inited=!0,this.setPre(),this.initSeqAndInc(),this.fillSeq()}initSeqAndInc(){let $=0;do this.seqHi=Math.floor(Math.random()*(Yi+1)),this.seqLo=Math.floor(Math.random()*l90);while($++<8&&this.seqHi===Yi&&this.seqLo>=Sm0);if(this.seqHi===Yi&&this.seqLo>=Sm0)this.seqLo=0;this.inc=Math.random()*(Jn6-Rt1)+Rt1|0}setPre(){Wn6(this.cbuf);for(let $=0;$<d90;$++)this.buf[$]=Cm0[this.cbuf[$]%Vw]}fillSeq(){let $=this.seqHi,Z=this.seqLo;for(let X=It1-1;X>=d90;X--){let Q=Math.floor($/Vw),G=($-Q*Vw)*l90+Z,J=Math.floor(G/Vw),K=G-J*Vw;this.buf[X]=Cm0[K],$=Q,Z=J}}next(){if(!this.inited)this.init();if(this.seqLo+=this.inc,this.seqLo>=l90)this.seqLo-=l90,this.seqHi+=1;if(this.seqHi>Yi||this.seqHi===Yi&&this.seqLo>=Sm0)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()}}Vt1.NuidImpl=_m0;Vt1.nuid=new _m0});var xt1=_((_t1)=>{Object.defineProperty(_t1,"__esModule",{value:!0});_t1.nuid=_t1.Nuid=void 0;var Ct1=St1();_t1.Nuid=Ct1.NuidImpl;_t1.nuid=Ct1.nuid});var i90=_((m90)=>{Object.defineProperty(m90,"__esModule",{value:!0});m90.nuid=m90.Nuid=void 0;var ft1=xt1();Object.defineProperty(m90,"Nuid",{enumerable:!0,get:function(){return ft1.Nuid}});Object.defineProperty(m90,"nuid",{enumerable:!0,get:function(){return ft1.nuid}})});var kw=_((bt1)=>{Object.defineProperty(bt1,"__esModule",{value:!0});bt1.DEFAULT_HOST=bt1.DEFAULT_PORT=bt1.Match=void 0;bt1.syncIterator=Bn6;bt1.createInbox=On6;var Fn6=i90(),wn6=tY();bt1.Match={Exact:"exact",CanonicalMIME:"canonical",IgnoreCase:"insensitive"};function Bn6($){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 On6($=""){if($=$||"_INBOX",typeof $!=="string")throw TypeError("prefix must be a string");return $.split(".").forEach((Z)=>{if(Z==="*"||Z===">")throw wn6.InvalidArgumentError.format("prefix",`cannot have wildcards ('${$}')`)}),`${$}.${Fn6.nuid.next()}`}bt1.DEFAULT_PORT=4222;bt1.DEFAULT_HOST="127.0.0.1"});var Gi=_((ut1)=>{Object.defineProperty(ut1,"__esModule",{value:!0});ut1.DataBuffer=void 0;var gt1=pY();class ht1{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 gt1.TE.encode($)}static toAscii($){return gt1.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}}ut1.DataBuffer=ht1});var WE=_((dt1)=>{Object.defineProperty(dt1,"__esModule",{value:!0});dt1.LF=dt1.CR=dt1.CRLF=dt1.CR_LF_LEN=dt1.CR_LF=void 0;dt1.setTransportFactory=Tn6;dt1.defaultPort=Rn6;dt1.getUrlParseFn=In6;dt1.newTransport=qn6;dt1.getResolveFn=Mn6;dt1.protoLen=lt1;dt1.extractProtocolMessage=Vn6;var jn6=pY(),Pn6=kw(),An6=Gi(),oY;function Tn6($){oY=$}function Rn6(){return oY!==void 0&&oY.defaultPort!==void 0?oY.defaultPort:Pn6.DEFAULT_PORT}function In6(){return oY!==void 0&&oY.urlParseFn?oY.urlParseFn:void 0}function qn6(){if(!oY||typeof oY.factory!=="function")throw Error("transport fn is not set");return oY.factory()}function Mn6(){return oY!==void 0&&oY.dnsResolveFn?oY.dnsResolveFn:void 0}dt1.CR_LF=`\r
|
|
1335
|
+
`);Q=G.pop()??"";for(let J of G){let K=Xi(J).replace(/^\[\d+\]\s*/,"").trim();if(!K)continue;Iw({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=Xi(Q).replace(/^\[\d+\]\s*/,"").trim();if(G)Iw({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:G})}})()}async function gm6($){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 Zi(Number(Y)+1):await Zi(Number($.port)),{settings:K,services:W,managedServiceNames:H}=await _90({port:String(J),home:$.home,baseUrl:$.baseUrl,localMode:$.localMode,skipMigrations:$.skipMigrations,noTui:$.noTui,vitePort:$.vitePort});for(let L of W)QE({name:L.name,status:"ready",port:L.port});em();let U=ym6(import.meta.dir,"..","..","..","..",".."),N=X===!0,F=Bun.spawn(["bun","run","dev:servers"],{cwd:U,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",N?"inherit":"pipe",N?"inherit":"pipe"]});if(!N)ip1(F.stdout),ip1(F.stderr);$i(G),QE({name:"Vite",status:"ready",port:Number(Y)}),QE({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(() => (l50(),c50));await D(K.dataDir)}};return process.on("SIGINT",()=>B("SIGINT")),process.on("SIGTERM",()=>B("SIGTERM")),{port:Number(Y),process:F}}var Fm0=O(()=>{Jm0();YE();Um0()});var f90;var wm0=O(()=>{f90={name:"decocms",version:"4.213.3",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 um6,Text as np1}from"ink";import{jsx as cm6,jsxs as pp1}from"react/jsx-runtime";function tp1({version:$}){return pp1(um6,{flexDirection:"column",marginTop:1,children:[H90.map((Z,X)=>cm6(np1,{color:U90[X],children:Z},X)),pp1(np1,{dimColor:!0,children:[" v",$]})]})}var op1=O(()=>{cm()});import{Box as GE,Text as qw}from"ink";import{Spinner as lm6}from"@inkjs/ui";import{jsx as nY,jsxs as jb}from"react/jsx-runtime";function rp1({status:$}){if($==="pending")return nY(lm6,{label:""});return nY(qw,{color:"green",children:"\u2713"})}function dm6($){return`${$.name}: ${$.port||"...."}`}function ap1({services:$,migrationsStatus:Z,home:X,serverUrl:Q}){return jb(GE,{flexDirection:"column",paddingBottom:1,children:[nY(tp1,{version:f90.version}),nY(GE,{marginBottom:1,children:nY(qw,{dimColor:!0,children:"\u2500".repeat(80)})}),nY(GE,{children:jb(qw,{dimColor:!0,children:["Home: ",X]})}),jb(GE,{gap:2,children:[$.map((Y)=>jb(GE,{gap:1,children:[nY(qw,{children:dm6(Y)}),nY(rp1,{status:Y.status})]},Y.name)),jb(GE,{gap:1,children:[nY(qw,{children:"Migrations"}),nY(rp1,{status:Z})]})]}),nY(GE,{children:Q?jb(qw,{children:["Open in browser: ",nY(qw,{color:"cyan",children:Q})]}):nY(qw,{dimColor:!0,children:"Starting..."})})]})}var sp1=O(()=>{wm0();op1()});import{Box as mm6,Text as Qi}from"ink";import{jsx as Bm0,jsxs as Om0}from"react/jsx-runtime";function im6($){if($>=500)return"red";if($>=400)return"yellow";if($>=300)return"cyan";return"green"}function ep1({logs:$}){return Bm0(mm6,{flexDirection:"column",children:$.map((Z,X)=>{if(Z.rawLine)return Bm0(Qi,{dimColor:!0,children:Z.rawLine},X);let Q=Z.duration<1000?`${Z.duration}ms`:`${(Z.duration/1000).toFixed(1)}s`;return Om0(Qi,{children:[Om0(Qi,{dimColor:!0,children:[Z.method.padEnd(6)," ",Z.path.padEnd(30)," "]}),Bm0(Qi,{color:im6(Z.status),children:Z.status}),Om0(Qi,{dimColor:!0,children:[" ",Q.padStart(8)]})]},X)})})}var $t1=()=>{};var Lm0={};B0(Lm0,{App:()=>tm6});import{Box as nm6}from"ink";import{useSyncExternalStore as pm6}from"react";import{jsx as Zt1,jsxs as om6}from"react/jsx-runtime";function tm6({home:$}){let Z=pm6(Hm0,Wm0);return om6(nm6,{flexDirection:"column",children:[Zt1(ap1,{services:Z.services,migrationsStatus:Z.migrationsStatus,home:$,serverUrl:Z.serverUrl}),Zt1(ep1,{logs:Z.logs})]})}var Dm0=O(()=>{sp1();$t1();YE()});var AJ="thread-gate",yU="decopilot-hosted-harness",Z3="automations",Mw="background-tools",JE="task-board-github-reads";var Xt1="7";function Qt1($){return{name:"decocms",systemDatabaseUrl:$.systemDatabaseUrl,systemDatabaseSchemaName:"dbos",systemDatabasePoolSize:$.poolSize,runAdminServer:!1,executorID:$.executorID,applicationVersion:Xt1,...$.listenQueues!==void 0?{listenQueues:$.listenQueues}:{}}}var Yt1=()=>{};function rm6(){let $=(process.env.BUN_OPTIONS??"").split(/\s+/).filter(Boolean);return[...process.argv.slice(1),...$]}function Em0($,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 Gt1(){let $=rm6();if($.includes("--cpu-prof")){console.log(JSON.stringify({msg:"cpu-profiling-active",dir:Em0($,"--cpu-prof-dir")??process.cwd(),name:Em0($,"--cpu-prof-name"),markdown:$.includes("--cpu-prof-md"),intervalUs:Number(Em0($,"--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 Jt1(){if(process.env.HEAP_WATCH!=="1")return()=>{};let $=Number(process.env.HEAP_WATCH_INTERVAL_MS??60000),Z=async()=>{let X=eD();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(()=>{}),b90=setInterval(()=>void Z().catch(()=>{}),$),b90.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(b90)clearInterval(b90)}}var b90;var Kt1=()=>{};import*as am6 from"bun:jsc";function Wt1(){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{sm6()}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=em6()?.traces??[]}catch{}if(J>$&&K.length>0){let W=new Map;for(let U of K){let N=U.frames.find((B)=>B.sourceURL&&!/Unknown Executable/.test(B.category??""))??U.frames[0];if(!N)continue;let F=(N.sourceURL??"?").replace(/^.*\/node_modules\//,"node_modules/"),w=`${N.name??"?"} @ ${F}:${N.line??"?"}`;W.set(w,(W.get(w)??0)+1)}let H=[...W.entries()].sort((U,N)=>N[1]-U[1]).slice(0,8).map(([U,N])=>({frame:U,count:N}));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 sm6,em6;var Ht1=O(()=>{({startSamplingProfiler:sm6,samplingProfilerStackTraces:em6}=am6)});function Ut1(){Gt1();let $=[Jt1(),Km1(),Wt1()];return()=>{for(let Z of $)Z()}}var Nt1=O(()=>{zu0();Kt1();Ht1()});var KE=_((Ft1)=>{Object.defineProperty(Ft1,"__esModule",{value:!0});Ft1.RepublishHeaders=Ft1.DirectMsgHeaders=Ft1.JsHeaders=Ft1.AdvisoryKind=void 0;Ft1.isOrderedPushConsumerOptions=$i6;Ft1.isPullConsumer=Zi6;Ft1.isPushConsumer=Xi6;Ft1.isBoundPushConsumerOptions=Qi6;function $i6($){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 Zi6($){return $.isPullConsumer()}function Xi6($){return $.isPushConsumer()}function Qi6($){if($&&typeof $==="object")return"deliver_subject"in $||"deliver_group"in $||"idle_heartbeat"in $;return!1}Ft1.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"};Ft1.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"};Ft1.DirectMsgHeaders={Stream:"Nats-Stream",Sequence:"Nats-Sequence",TimeStamp:"Nats-Time-Stamp",Subject:"Nats-Subject",LastSequence:"Nats-Last-Sequence",NumPending:"Nats-Num-Pending"};Ft1.RepublishHeaders={Stream:"Nats-Stream",Subject:"Nats-Subject",Sequence:"Nats-Sequence",LastSequence:"Nats-Last-Sequence",Size:"Nats-Msg-Size"}});var pY=_((Bt1)=>{Object.defineProperty(Bt1,"__esModule",{value:!0});Bt1.TD=Bt1.TE=Bt1.Empty=void 0;Bt1.encode=Fi6;Bt1.decode=wi6;Bt1.Empty=new Uint8Array(0);Bt1.TE=new TextEncoder;Bt1.TD=new TextDecoder;function Ni6(...$){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 Fi6(...$){let Z=[];for(let X=0;X<$.length;X++)Z.push(Bt1.TE.encode($[X]));if(Z.length===0)return Bt1.Empty;if(Z.length===1)return Z[0];return Ni6(...Z)}function wi6($){if(!$||$.length===0)return"";return Bt1.TD.decode($)}});var tY=_((Dt1)=>{Object.defineProperty(Dt1,"__esModule",{value:!0});Dt1.errors=Dt1.PermissionViolationError=Dt1.NoRespondersError=Dt1.TimeoutError=Dt1.RequestError=Dt1.ProtocolError=Dt1.ConnectionError=Dt1.DrainingConnectionError=Dt1.ClosedConnectionError=Dt1.AuthorizationError=Dt1.UserAuthenticationExpiredError=Dt1.InvalidOperationError=Dt1.InvalidArgumentError=Dt1.InvalidSubjectError=void 0;class jm0 extends Error{constructor($,Z){super(`illegal subject: '${$}'`,Z);this.name="InvalidSubjectError"}}Dt1.InvalidSubjectError=jm0;class y90 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 y90(`${$} ${Z}`,X)}}Dt1.InvalidArgumentError=y90;class Pm0 extends Error{constructor($,Z){super($,Z);this.name="InvalidOperationError"}}Dt1.InvalidOperationError=Pm0;class g90 extends Error{constructor($,Z){super($,Z);this.name="UserAuthenticationExpiredError"}static parse($){if($.toLowerCase().indexOf("user authentication expired")!==-1)return new g90($);return null}}Dt1.UserAuthenticationExpiredError=g90;class h90 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 h90($);return null}}Dt1.AuthorizationError=h90;class Am0 extends Error{constructor(){super("closed connection");this.name="ClosedConnectionError"}}Dt1.ClosedConnectionError=Am0;class Tm0 extends Error{constructor(){super("connection draining");this.name="DrainingConnectionError"}}Dt1.DrainingConnectionError=Tm0;class Rm0 extends Error{constructor($,Z){super($,Z);this.name="ConnectionError"}}Dt1.ConnectionError=Rm0;class Im0 extends Error{constructor($,Z){super($,Z);this.name="ProtocolError"}}Dt1.ProtocolError=Im0;class qm0 extends Error{constructor($="",Z){super($,Z);this.name="RequestError"}isNoResponders(){return this.cause instanceof u90}}Dt1.RequestError=qm0;class Mm0 extends Error{constructor($){super("timeout",$);this.name="TimeoutError"}}Dt1.TimeoutError=Mm0;class u90 extends Error{subject;constructor($,Z){super(`no responders: '${$}'`,Z);this.subject=$,this.name="NoResponders"}}Dt1.NoRespondersError=u90;class c90 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 c90($,X,Q,Y)}}Dt1.PermissionViolationError=c90;Dt1.errors={AuthorizationError:h90,ClosedConnectionError:Am0,ConnectionError:Rm0,DrainingConnectionError:Tm0,InvalidArgumentError:y90,InvalidOperationError:Pm0,InvalidSubjectError:jm0,NoRespondersError:u90,PermissionViolationError:c90,ProtocolError:Im0,RequestError:qm0,TimeoutError:Mm0,UserAuthenticationExpiredError:g90}});var TJ=_((At1)=>{Object.defineProperty(At1,"__esModule",{value:!0});At1.SimpleMutex=At1.Perf=void 0;At1.extend=Si6;At1.render=Ci6;At1.timeout=_i6;At1.delay=vi6;At1.deadline=xi6;At1.deferred=km0;At1.debugDeferred=fi6;At1.shuffle=bi6;At1.collect=yi6;At1.jitter=Pt1;At1.backoff=gi6;At1.nanos=hi6;At1.millis=ui6;At1.randomToken=di6;var ki6=pY(),Vm0=tY();function Si6($,...Z){for(let X=0;X<Z.length;X++){let Q=Z[X];Object.keys(Q).forEach(function(Y){$[Y]=Q[Y]})}return $}function Ci6($){return ki6.TD.decode($).replace(/\n/g,"\u240A").replace(/\r/g,"\u240D")}function _i6($,Z=!0){let X=Z?new Vm0.TimeoutError:null,Q,Y,G=new Promise((J,K)=>{Q={cancel:()=>{if(Y)clearTimeout(Y)}},Y=setTimeout(()=>{if(X===null)K(new Vm0.TimeoutError);else K(X)},$)});return Object.assign(G,Q)}function vi6($=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 xi6($,Z=1000){let X=km0(),Q=setTimeout(()=>{X.reject(new Vm0.TimeoutError)},Z);try{return await Promise.race([$,X])}finally{clearTimeout(Q)}}function km0(){let $={},Z=new Promise((X,Q)=>{$={resolve:X,reject:Q}});return Object.assign(Z,$)}function fi6(){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 bi6($){for(let Z=$.length-1;Z>0;Z--){let X=Math.floor(Math.random()*(Z+1));[$[Z],$[X]]=[$[X],$[Z]]}return $}async function yi6($){let Z=[];for await(let X of $)Z.push(X);return Z}class zt1{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})}),$}}At1.Perf=zt1;class jt1{max;current;waiting;constructor($=1){this.max=$,this.current=0,this.waiting=[]}lock(){if(this.current++,this.current<=this.max)return Promise.resolve();let $=km0();return this.waiting.push($),$}unlock(){this.current--,this.waiting.pop()?.resolve()}}At1.SimpleMutex=jt1;function Pt1($){if($===0)return 0;return Math.floor($/2+Math.random()*$)}function gi6($=[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 Pt1(X>Z?$[Z]:$[X])}}}function hi6($){return $*1e6}function ui6($){return Math.floor($/1e6)}var ci6="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",gU=new Uint8Array(62);for(let $=0;$<62;$++)gU[$]=ci6.charCodeAt($);var li6=218340105584896;function di6(){let $=Math.floor(Math.random()*li6),Z=$%62,X=gU[Z];$=($-Z)/62,Z=$%62;let Q=gU[Z];$=($-Z)/62,Z=$%62;let Y=gU[Z];$=($-Z)/62,Z=$%62;let G=gU[Z];$=($-Z)/62,Z=$%62;let J=gU[Z];$=($-Z)/62,Z=$%62;let K=gU[Z];$=($-Z)/62,Z=$%62;let W=gU[Z];$=($-Z)/62;let H=gU[$];return String.fromCharCode(X,Q,Y,G,J,K,W,H)}});var St1=_((Vt1)=>{Object.defineProperty(Vt1,"__esModule",{value:!0});Vt1.nuid=Vt1.NuidImpl=void 0;var Gn6="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Vw=62,d90=12,qt1=10,Rt1=33,Jn6=333,It1=d90+qt1,Cm0=new Uint8Array(Vw);for(let $=0;$<Vw;$++)Cm0[$]=Gn6.charCodeAt($);var l90=4294967296,Mt1=BigInt(Vw)**BigInt(qt1),Yi=Number(Mt1/(1n<<32n)),Sm0=Number(Mt1%(1n<<32n));function Kn6($){for(let Z=0;Z<$.length;Z++)$[Z]=Math.floor(Math.random()*256)}function Wn6($){if(globalThis?.crypto?.getRandomValues)globalThis.crypto.getRandomValues($);else Kn6($)}class _m0{buf;cbuf;seqHi;seqLo;inc;inited;constructor(){this.buf=new Uint8Array(It1),this.cbuf=new Uint8Array(d90),this.inited=!1}init(){this.inited=!0,this.setPre(),this.initSeqAndInc(),this.fillSeq()}initSeqAndInc(){let $=0;do this.seqHi=Math.floor(Math.random()*(Yi+1)),this.seqLo=Math.floor(Math.random()*l90);while($++<8&&this.seqHi===Yi&&this.seqLo>=Sm0);if(this.seqHi===Yi&&this.seqLo>=Sm0)this.seqLo=0;this.inc=Math.random()*(Jn6-Rt1)+Rt1|0}setPre(){Wn6(this.cbuf);for(let $=0;$<d90;$++)this.buf[$]=Cm0[this.cbuf[$]%Vw]}fillSeq(){let $=this.seqHi,Z=this.seqLo;for(let X=It1-1;X>=d90;X--){let Q=Math.floor($/Vw),G=($-Q*Vw)*l90+Z,J=Math.floor(G/Vw),K=G-J*Vw;this.buf[X]=Cm0[K],$=Q,Z=J}}next(){if(!this.inited)this.init();if(this.seqLo+=this.inc,this.seqLo>=l90)this.seqLo-=l90,this.seqHi+=1;if(this.seqHi>Yi||this.seqHi===Yi&&this.seqLo>=Sm0)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()}}Vt1.NuidImpl=_m0;Vt1.nuid=new _m0});var xt1=_((_t1)=>{Object.defineProperty(_t1,"__esModule",{value:!0});_t1.nuid=_t1.Nuid=void 0;var Ct1=St1();_t1.Nuid=Ct1.NuidImpl;_t1.nuid=Ct1.nuid});var i90=_((m90)=>{Object.defineProperty(m90,"__esModule",{value:!0});m90.nuid=m90.Nuid=void 0;var ft1=xt1();Object.defineProperty(m90,"Nuid",{enumerable:!0,get:function(){return ft1.Nuid}});Object.defineProperty(m90,"nuid",{enumerable:!0,get:function(){return ft1.nuid}})});var kw=_((bt1)=>{Object.defineProperty(bt1,"__esModule",{value:!0});bt1.DEFAULT_HOST=bt1.DEFAULT_PORT=bt1.Match=void 0;bt1.syncIterator=Bn6;bt1.createInbox=On6;var Fn6=i90(),wn6=tY();bt1.Match={Exact:"exact",CanonicalMIME:"canonical",IgnoreCase:"insensitive"};function Bn6($){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 On6($=""){if($=$||"_INBOX",typeof $!=="string")throw TypeError("prefix must be a string");return $.split(".").forEach((Z)=>{if(Z==="*"||Z===">")throw wn6.InvalidArgumentError.format("prefix",`cannot have wildcards ('${$}')`)}),`${$}.${Fn6.nuid.next()}`}bt1.DEFAULT_PORT=4222;bt1.DEFAULT_HOST="127.0.0.1"});var Gi=_((ut1)=>{Object.defineProperty(ut1,"__esModule",{value:!0});ut1.DataBuffer=void 0;var gt1=pY();class ht1{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 gt1.TE.encode($)}static toAscii($){return gt1.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}}ut1.DataBuffer=ht1});var WE=_((dt1)=>{Object.defineProperty(dt1,"__esModule",{value:!0});dt1.LF=dt1.CR=dt1.CRLF=dt1.CR_LF_LEN=dt1.CR_LF=void 0;dt1.setTransportFactory=Tn6;dt1.defaultPort=Rn6;dt1.getUrlParseFn=In6;dt1.newTransport=qn6;dt1.getResolveFn=Mn6;dt1.protoLen=lt1;dt1.extractProtocolMessage=Vn6;var jn6=pY(),Pn6=kw(),An6=Gi(),oY;function Tn6($){oY=$}function Rn6(){return oY!==void 0&&oY.defaultPort!==void 0?oY.defaultPort:Pn6.DEFAULT_PORT}function In6(){return oY!==void 0&&oY.urlParseFn?oY.urlParseFn:void 0}function qn6(){if(!oY||typeof oY.factory!=="function")throw Error("transport fn is not set");return oY.factory()}function Mn6(){return oY!==void 0&&oY.dnsResolveFn?oY.dnsResolveFn:void 0}dt1.CR_LF=`\r
|
|
1336
1336
|
`;dt1.CR_LF_LEN=dt1.CR_LF.length;dt1.CRLF=An6.DataBuffer.fromAscii(dt1.CR_LF);dt1.CR=new Uint8Array(dt1.CRLF)[0];dt1.LF=new Uint8Array(dt1.CRLF)[1];function lt1($){for(let Z=0;Z<$.length;Z++){let X=Z+1;if($.byteLength>X&&$[Z]===dt1.CR&&$[X]===dt1.LF)return X+1}return 0}function Vn6($){let Z=lt1($);if(Z>0){let Q=new Uint8Array($).slice(0,Z);return jn6.TD.decode(Q)}return""}});var ym0=_((at1)=>{Object.defineProperty(at1,"__esModule",{value:!0});at1.ipV4=tt1;at1.isIP=hn6;at1.parseIP=ot1;var Ji=4,HE=16,n90=48,pt1=57,it1=65,yn6=70,nt1=97,gn6=102,bm0=16777215;function tt1($,Z,X,Q){let Y=new Uint8Array(HE);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 hn6($){return ot1($)!==void 0}function ot1($){for(let Z=0;Z<$.length;Z++)switch($[Z]){case".":return rt1($);case":":return un6($)}return}function rt1($){let Z=new Uint8Array(Ji);for(let X=0;X<Ji;X++){if($.length===0)return;if(X>0){if($[0]!==".")return;$=$.substring(1)}let{n:Q,c:Y,ok:G}=cn6($);if(!G||Q>255)return;$=$.substring(Y),Z[X]=Q}return tt1(Z[0],Z[1],Z[2],Z[3])}function un6($){let Z=new Uint8Array(HE),X=-1;if($.length>=2&&$[0]===":"&&$[1]===":"){if(X=0,$=$.substring(2),$.length===0)return Z}let Q=0;while(Q<HE){let{n:Y,c:G,ok:J}=ln6($);if(!J||Y>65535)return;if(G<$.length&&$[G]==="."){if(X<0&&Q!=HE-Ji)return;if(Q+Ji>HE)return;let K=rt1($);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+=Ji;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<HE){if(X<0)return;let Y=HE-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 cn6($){let Z=0,X=0;for(Z=0;Z<$.length&&n90<=$.charCodeAt(Z)&&$.charCodeAt(Z)<=pt1;Z++)if(X=X*10+($.charCodeAt(Z)-n90),X>=bm0)return{n:bm0,c:Z,ok:!1};if(Z===0)return{n:0,c:0,ok:!1};return{n:X,c:Z,ok:!0}}function ln6($){let Z=0,X=0;for(X=0;X<$.length;X++){if(n90<=$.charCodeAt(X)&&$.charCodeAt(X)<=pt1)Z*=16,Z+=$.charCodeAt(X)-n90;else if(nt1<=$.charCodeAt(X)&&$.charCodeAt(X)<=gn6)Z*=16,Z+=$.charCodeAt(X)-nt1+10;else if(it1<=$.charCodeAt(X)&&$.charCodeAt(X)<=yn6)Z*=16,Z+=$.charCodeAt(X)-it1+10;else break;if(Z>=bm0)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 dm0=_((et1)=>{Object.defineProperty(et1,"__esModule",{value:!0});et1.Servers=et1.ServerImpl=void 0;et1.isIPV4OrHostname=st1;et1.hostPort=lm0;var gm0=WE(),hm0=TJ(),um0=ym0(),nn6=kw(),pn6=tY();function st1($){if($.indexOf("[")!==-1||$.indexOf("::")!==-1)return!1;if($.indexOf(".")!==-1)return!0;if($.split(":").length<=2)return!0;return!1}function cm0($){return!st1($)}function tn6($){let X=$.toUpperCase().indexOf("::FFFF:");if(X!==-1&&$.indexOf(".")!==-1){let Q=$.substring(X+7);return Q=Q.replace("[",""),Q.replace("]","")}return $}function lm0($){if($=$.trim(),$.match(/^(.*:\/\/)(.*)/m))$=$.replace(/^(.*:\/\/)(.*)/gm,"$2");if($=tn6($),cm0($)&&$.indexOf("[")===-1)$=`[${$}]`;let Z=cm0($)?$.match(/(]:)(\d+)/):$.match(/(:)(\d+)/),X=Z&&Z.length===3&&Z[1]&&Z[2]?parseInt(Z[2]):nn6.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 Pb{src;listen;hostname;port;didConnect;reconnects;lastConnect;gossiped;tlsName;resolves;constructor($,Z=!1){this.src=$,this.tlsName="";let X=lm0($);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,um0.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}://${cm0(Q)?"["+Q+"]":Q}`);G.port=`${this.port}`;let J=new Pb(G.host,!1);J.tlsName=this.hostname,Z.push(J)}}if($.randomize)(0,hm0.shuffle)(Z);return this.resolves=Z,Z}}et1.ServerImpl=Pb;class p90{firstSelect;servers;currentServer;tlsName;randomize;constructor($={}){this.firstSelect=!0,this.servers=[],this.tlsName="",this.randomize=$.randomize||!1}setServers($){if(!Array.isArray($)||$.length===0)throw pn6.InvalidArgumentError.format("servers","cannot be empty");let Z=(0,gm0.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}=lm0(Y),J=X.get(G);if(J)J.gossiped=!1,Q.push(J);else Q.push(new Pb(Y))}if(this.randomize)(0,hm0.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,um0.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,gm0.getUrlParseFn)();$=X?X($):$;let Q=new Pb($,Z);if((0,um0.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 p90.freezeAll(this.servers)}snapshotForHandler(){let $=this.currentServer;if(!$)return this.snapshot();let Z=this.servers.indexOf($);if(Z<=0)return this.snapshot();return p90.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,gm0.getUrlParseFn)(),G=new Map;if($.connect_urls&&$.connect_urls.length>0)$.connect_urls.forEach((K)=>{K=Y?Y(K,Z):K;let W=new Pb(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,hm0.shuffle)(W),this.servers=K?[K,...W]:W}return{added:X,deleted:Q}}}et1.Servers=p90});var t90=_((Qo1)=>{Object.defineProperty(Qo1,"__esModule",{value:!0});Qo1.QueuedIteratorImpl=void 0;var mm0=TJ(),Zo1=tY();class Xo1{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,mm0.deferred)(),this.yields=[],this.iterClosed=(0,mm0.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 Zo1.InvalidOperationError("iterator cannot be used when a callback is registered");if(this.yielding)throw new Zo1.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,mm0.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}}Qo1.QueuedIteratorImpl=Xo1});var im0=_((Ko1)=>{Object.defineProperty(Ko1,"__esModule",{value:!0});Ko1.MuxSubscription=void 0;var sn6=kw(),Go1=tY();class Jo1{baseInbox;reqs;constructor(){this.reqs=new Map}size(){return this.reqs.size}init($){return this.baseInbox=`${(0,sn6.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 Go1.NoRespondersError(Q.requestSubject):null;Q.resolver($,Z)}}}}close(){let $=new Go1.RequestError("connection closed");this.reqs.forEach((Z)=>{Z.resolver($,{})})}}Ko1.MuxSubscription=Jo1});var nm0=_((Uo1)=>{Object.defineProperty(Uo1,"__esModule",{value:!0});Uo1.Heartbeat=void 0;var en6=TJ();class Ho1{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,en6.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})}}Uo1.Heartbeat=Ho1});var om0=_((Oo1)=>{Object.defineProperty(Oo1,"__esModule",{value:!0});Oo1.DenoBuffer=Oo1.MAX_SIZE=Oo1.AssertionError=void 0;Oo1.assert=wo1;Oo1.concat=Bo1;Oo1.append=Zp6;Oo1.readAll=Xp6;Oo1.writeAll=Qp6;var $p6=pY();class pm0 extends Error{constructor($){super($);this.name="AssertionError"}}Oo1.AssertionError=pm0;function wo1($,Z="Assertion failed."){if(!$)throw new pm0(Z)}var Fo1=32768;Oo1.MAX_SIZE=4294967294;function o90($,Z,X=0){let Q=Z.byteLength-X;if($.byteLength>Q)$=$.subarray(0,Q);return Z.set($,X),$.byteLength}function Bo1($,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 Zp6($,Z){return Bo1($,Uint8Array.of(Z))}class tm0{_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($){wo1($<=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=o90(this._buf.subarray(this._off),$);return this._off+=Z,Z}writeByte($){return this.write(Uint8Array.of($))}writeString($){return this.write($p6.TE.encode($))}write($){let Z=this._grow($.byteLength);return o90($,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)o90(this._buf.subarray(this._off),this._buf);else if(Q+$>Oo1.MAX_SIZE)throw Error("The buffer cannot be grown beyond the maximum size.");else{let Y=new Uint8Array(Math.min(2*Q+$,Oo1.MAX_SIZE));o90(this._buf.subarray(this._off),Y),this._buf=Y}return this._off=0,this._reslice(Math.min(Z+$,Oo1.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(Fo1);while(!0){let Q=this.capacity-this.length<Fo1,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}}}Oo1.DenoBuffer=tm0;function Xp6($){let Z=new tm0;return Z.readFrom($),Z.bytes()}function Qp6($,Z){let X=0;while(X<Z.length)X+=$.write(Z.subarray(X))}});var sm0=_((jo1)=>{Object.defineProperty(jo1,"__esModule",{value:!0});jo1.cc=jo1.State=jo1.Parser=jo1.Kind=void 0;jo1.describe=Up6;var rm0=om0(),am0=pY();jo1.Kind={OK:0,ERR:1,MSG:2,INFO:3,PING:4,PONG:5};function Up6($){let Z,X="";switch($.kind){case jo1.Kind.MSG:Z="MSG";break;case jo1.Kind.OK:Z="OK";break;case jo1.Kind.ERR:Z="ERR",X=am0.TD.decode($.data);break;case jo1.Kind.PING:Z="PING";break;case jo1.Kind.PONG:Z="PONG";break;case jo1.Kind.INFO:Z="INFO",X=am0.TD.decode($.data)}return`${Z}: ${X}`}function Do1(){let $={};return $.sid=-1,$.hdr=-1,$.size=-1,$}var Eo1=48,Np6=57,Ab=67108864;class zo1{dispatcher;state;as;drop;hdr;ma;argBuf;msgBuf;constructor($){this.dispatcher=$,this.state=jo1.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 jo1.State.OP_START:switch(X){case jo1.cc.M:case jo1.cc.m:this.state=jo1.State.OP_M,this.hdr=-1,this.ma=Do1();break;case jo1.cc.H:case jo1.cc.h:this.state=jo1.State.OP_H,this.hdr=0,this.ma=Do1();break;case jo1.cc.P:case jo1.cc.p:this.state=jo1.State.OP_P;break;case jo1.cc.PLUS:this.state=jo1.State.OP_PLUS;break;case jo1.cc.MINUS:this.state=jo1.State.OP_MINUS;break;case jo1.cc.I:case jo1.cc.i:this.state=jo1.State.OP_I;break;default:throw this.fail($.subarray(Z))}break;case jo1.State.OP_H:switch(X){case jo1.cc.M:case jo1.cc.m:this.state=jo1.State.OP_M;break;default:throw this.fail($.subarray(Z))}break;case jo1.State.OP_M:switch(X){case jo1.cc.S:case jo1.cc.s:this.state=jo1.State.OP_MS;break;default:throw this.fail($.subarray(Z))}break;case jo1.State.OP_MS:switch(X){case jo1.cc.G:case jo1.cc.g:this.state=jo1.State.OP_MSG;break;default:throw this.fail($.subarray(Z))}break;case jo1.State.OP_MSG:switch(X){case jo1.cc.SPACE:case jo1.cc.TAB:this.state=jo1.State.OP_MSG_SPC;break;default:throw this.fail($.subarray(Z))}break;case jo1.State.OP_MSG_SPC:switch(X){case jo1.cc.SPACE:case jo1.cc.TAB:continue;default:this.state=jo1.State.MSG_ARG,this.as=Z}break;case jo1.State.MSG_ARG:switch(X){case jo1.cc.CR:this.drop=1;break;case jo1.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=jo1.State.MSG_PAYLOAD,Z=this.as+this.ma.size-1;break}default:if(this.argBuf)this.argBuf.writeByte(X)}break;case jo1.State.MSG_PAYLOAD:if(this.msgBuf)if(this.msgBuf.length>=this.ma.size){let Q=this.msgBuf.bytes({copy:!1});this.dispatcher.push({kind:jo1.Kind.MSG,msg:this.ma,data:Q}),this.argBuf=void 0,this.msgBuf=void 0,this.state=jo1.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:jo1.Kind.MSG,msg:this.ma,data:$.subarray(this.as,Z)}),this.argBuf=void 0,this.msgBuf=void 0,this.state=jo1.State.MSG_END;break;case jo1.State.MSG_END:switch(X){case jo1.cc.NL:this.drop=0,this.as=Z+1,this.state=jo1.State.OP_START;break;default:continue}break;case jo1.State.OP_PLUS:switch(X){case jo1.cc.O:case jo1.cc.o:this.state=jo1.State.OP_PLUS_O;break;default:throw this.fail($.subarray(Z))}break;case jo1.State.OP_PLUS_O:switch(X){case jo1.cc.K:case jo1.cc.k:this.state=jo1.State.OP_PLUS_OK;break;default:throw this.fail($.subarray(Z))}break;case jo1.State.OP_PLUS_OK:switch(X){case jo1.cc.NL:this.dispatcher.push({kind:jo1.Kind.OK}),this.drop=0,this.state=jo1.State.OP_START;break}break;case jo1.State.OP_MINUS:switch(X){case jo1.cc.E:case jo1.cc.e:this.state=jo1.State.OP_MINUS_E;break;default:throw this.fail($.subarray(Z))}break;case jo1.State.OP_MINUS_E:switch(X){case jo1.cc.R:case jo1.cc.r:this.state=jo1.State.OP_MINUS_ER;break;default:throw this.fail($.subarray(Z))}break;case jo1.State.OP_MINUS_ER:switch(X){case jo1.cc.R:case jo1.cc.r:this.state=jo1.State.OP_MINUS_ERR;break;default:throw this.fail($.subarray(Z))}break;case jo1.State.OP_MINUS_ERR:switch(X){case jo1.cc.SPACE:case jo1.cc.TAB:this.state=jo1.State.OP_MINUS_ERR_SPC;break;default:throw this.fail($.subarray(Z))}break;case jo1.State.OP_MINUS_ERR_SPC:switch(X){case jo1.cc.SPACE:case jo1.cc.TAB:continue;default:this.state=jo1.State.MINUS_ERR_ARG,this.as=Z}break;case jo1.State.MINUS_ERR_ARG:switch(X){case jo1.cc.CR:this.drop=1;break;case jo1.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:jo1.Kind.ERR,data:Q}),this.drop=0,this.as=Z+1,this.state=jo1.State.OP_START;break}default:if(this.argBuf)this.argBuf.write(Uint8Array.of(X))}break;case jo1.State.OP_P:switch(X){case jo1.cc.I:case jo1.cc.i:this.state=jo1.State.OP_PI;break;case jo1.cc.O:case jo1.cc.o:this.state=jo1.State.OP_PO;break;default:throw this.fail($.subarray(Z))}break;case jo1.State.OP_PO:switch(X){case jo1.cc.N:case jo1.cc.n:this.state=jo1.State.OP_PON;break;default:throw this.fail($.subarray(Z))}break;case jo1.State.OP_PON:switch(X){case jo1.cc.G:case jo1.cc.g:this.state=jo1.State.OP_PONG;break;default:throw this.fail($.subarray(Z))}break;case jo1.State.OP_PONG:switch(X){case jo1.cc.NL:this.dispatcher.push({kind:jo1.Kind.PONG}),this.drop=0,this.state=jo1.State.OP_START;break}break;case jo1.State.OP_PI:switch(X){case jo1.cc.N:case jo1.cc.n:this.state=jo1.State.OP_PIN;break;default:throw this.fail($.subarray(Z))}break;case jo1.State.OP_PIN:switch(X){case jo1.cc.G:case jo1.cc.g:this.state=jo1.State.OP_PING;break;default:throw this.fail($.subarray(Z))}break;case jo1.State.OP_PING:switch(X){case jo1.cc.NL:this.dispatcher.push({kind:jo1.Kind.PING}),this.drop=0,this.state=jo1.State.OP_START;break}break;case jo1.State.OP_I:switch(X){case jo1.cc.N:case jo1.cc.n:this.state=jo1.State.OP_IN;break;default:throw this.fail($.subarray(Z))}break;case jo1.State.OP_IN:switch(X){case jo1.cc.F:case jo1.cc.f:this.state=jo1.State.OP_INF;break;default:throw this.fail($.subarray(Z))}break;case jo1.State.OP_INF:switch(X){case jo1.cc.O:case jo1.cc.o:this.state=jo1.State.OP_INFO;break;default:throw this.fail($.subarray(Z))}break;case jo1.State.OP_INFO:switch(X){case jo1.cc.SPACE:case jo1.cc.TAB:this.state=jo1.State.OP_INFO_SPC;break;default:throw this.fail($.subarray(Z))}break;case jo1.State.OP_INFO_SPC:switch(X){case jo1.cc.SPACE:case jo1.cc.TAB:continue;default:this.state=jo1.State.INFO_ARG,this.as=Z}break;case jo1.State.INFO_ARG:switch(X){case jo1.cc.CR:this.drop=1;break;case jo1.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:jo1.Kind.INFO,data:Q}),this.drop=0,this.as=Z+1,this.state=jo1.State.OP_START;break}default:if(this.argBuf)this.argBuf.writeByte(X)}break;default:throw this.fail($.subarray(Z))}}if((this.state===jo1.State.MSG_ARG||this.state===jo1.State.MINUS_ERR_ARG||this.state===jo1.State.INFO_ARG)&&!this.argBuf)this.argBuf=new rm0.DenoBuffer($.subarray(this.as,Z-this.drop));if(this.state===jo1.State.MSG_PAYLOAD&&!this.msgBuf){if(!this.argBuf)this.cloneMsgArg();this.msgBuf=new rm0.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 rm0.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 jo1.cc.SPACE:case jo1.cc.TAB:case jo1.cc.CR:case jo1.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],Ab);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],Ab);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}: ${am0.TD.decode($)}`)}processHeaderMsgArgs($){let Z=[],X=-1;for(let Q=0;Q<$.length;Q++)switch($[Q]){case jo1.cc.SPACE:case jo1.cc.TAB:case jo1.cc.CR:case jo1.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],Ab),this.ma.size=this.protoParseInt(Z[3],Ab);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],Ab),this.ma.size=this.protoParseInt(Z[4],Ab);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]<Eo1||$[Q]>Np6)return-1;X=X*10+($[Q]-Eo1)}return Z!==void 0&&X>Z?-1:X}}jo1.Parser=zo1;jo1.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};jo1.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 s90=_((Ao1)=>{Object.defineProperty(Ao1,"__esModule",{value:!0});Ao1.MsgHdrsImpl=void 0;Ao1.canonicalMIMEHeaderKey=$i0;Ao1.headers=Bp6;var Po1=pY(),RJ=kw(),a90=tY();function $i0($){let U=!0,N=Array($.length);for(let F=0;F<$.length;F++){let w=$.charCodeAt(F);if(w===58||w<33||w>126)throw a90.InvalidArgumentError.format("header",`'${$[F]}' is not a valid character in a header name`);if(U&&97<=w&&w<=122)w-=32;else if(!U&&65<=w&&w<=90)w+=32;N[F]=w,U=w==45}return String.fromCharCode(...N)}function Bp6($=0,Z=""){if($===0&&Z!=="")throw a90.InvalidArgumentError.format("code","is required");else if($>0&&Z==="")throw a90.InvalidArgumentError.format("description","is required");return new Tb($,Z)}var em0="NATS/1.0";class Tb{_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 Tb,Q=Po1.TD.decode($).split(`\r
|
|
1337
1337
|
`),Y=Q[0];if(Y!==em0){let G=Y.replace(em0,"").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 $=em0;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
|
|
1338
1338
|
${Z}: ${X[Q]}`;return`${$}\r
|
|
@@ -2315,7 +2315,7 @@ ${Y}`:Y}var BD8,JI4;var E81=O(()=>{BD8=/[\r\n<>]/,JI4=/^[^\s@<>]+@[^\s@<>]+\.[^\
|
|
|
2315
2315
|
`);let Q=Z.pax;if(Q)for(let Y in Q)X+=N41(" "+Y+"="+Q[Y]+`
|
|
2316
2316
|
`);return m4.from(X)};kv4.decodePax=function(Z){let X={};while(Z.length){let Q=0;while(Q<Z.length&&Z[Q]!==32)Q++;let Y=parseInt(m4.toString(Z.subarray(0,Q)),10);if(!Y)return X;let G=m4.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};kv4.encode=function(Z){let X=m4.alloc(512),Q=Z.name,Y="";if(Z.typeflag===5&&Q[Q.length-1]!=="/")Q+="/";if(m4.byteLength(Q)!==Q.length)return null;while(m4.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(m4.byteLength(Q)>100||m4.byteLength(Y)>155)return null;if(Z.linkname&&m4.byteLength(Z.linkname)>100)return null;if(m4.write(X,Q),m4.write(X,qO(Z.mode&4095,6),100),m4.write(X,qO(Z.uid,6),108),m4.write(X,qO(Z.gid,6),116),Mv4(Z.size,X,124),m4.write(X,qO(Z.mtime.getTime()/1000|0,11),136),X[156]=48+Iv4(Z.type),Z.linkname)m4.write(X,Z.linkname,157);if(m4.copy(WT8,X,257),m4.copy(Ev4,X,263),Z.uname)m4.write(X,Z.uname,265);if(Z.gname)m4.write(X,Z.gname,297);if(m4.write(X,qO(Z.devmajor||0,6),329),m4.write(X,qO(Z.devminor||0,6),337),Y)m4.write(X,Y,345);return m4.write(X,qO(UT8(X),6),148),X};kv4.decode=function(Z,X,Q){let Y=Z[156]===0?0:Z[156]-48,G=Vh(Z,0,100,X),J=IO(Z,100,8),K=IO(Z,108,8),W=IO(Z,116,8),H=IO(Z,124,12),U=IO(Z,136,12),N=Rv4(Y),F=Z[157]===0?null:Vh(Z,157,100,X),w=Vh(Z,265,32),B=Vh(Z,297,32),L=IO(Z,329,8),D=IO(Z,337,8),E=UT8(Z);if(E===256)return null;if(E!==IO(Z,148,8))throw Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");if(Pv4(Z)){if(Z[345])G=Vh(Z,345,155,X)+"/"+G}else if(Av4(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*U),type:N,linkname:F,uname:w,gname:B,devmajor:L,devminor:D,pax:null}};function Pv4($){return m4.equals(WT8,$.subarray(257,263))}function Av4($){return m4.equals(zv4,$.subarray(257,263))&&m4.equals(jv4,$.subarray(263,265))}function Tv4($,Z,X){if(typeof $!=="number")return X;if($=~~$,$>=Z)return Z;if($>=0)return $;if($+=Z,$>=0)return $;return 0}function Rv4($){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 Iv4($){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 HT8($,Z,X,Q){for(;X<Q;X++)if($[X]===Z)return X;return Q}function UT8($){let Z=256;for(let X=0;X<148;X++)Z+=$[X];for(let X=156;X<512;X++)Z+=$[X];return Z}function qO($,Z){if($=$.toString(8),$.length>Z)return"7777777777777777777".slice(0,Z)+" ";return"0000000000000000000".slice(0,Z-$.length)+$+" "}function qv4($,Z,X){Z[X]=128;for(let Q=11;Q>0;Q--)Z[X+Q]=$&255,$=Math.floor($/256)}function Mv4($,Z,X){if($.toString(8).length>11)qv4($,Z,X);else m4.write(Z,qO($,11),X)}function Vv4($){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 IO($,Z,X){if($=$.subarray(Z,Z+X),Z=0,$[Z]&128)return Vv4($);else{while(Z<$.length&&$[Z]===32)Z++;let Q=Tv4(HT8($,32,Z,$.length),$.length,$.length);while(Z<Q&&$[Z]===0)Z++;if(Q===Z)return 0;return parseInt(m4.toString($.subarray(Z,Q)),8)}}function Vh($,Z,X,Q){return m4.toString($.subarray(Z,HT8($,0,Z,Z+X)),Q)}function N41($){let Z=m4.byteLength($),X=Math.floor(Math.log(Z)/Math.log(10))+1;if(Z+X>=Math.pow(10,X))X++;return Z+X+$}});var ET8=_((ai9,DT8)=>{var{Writable:fv4,Readable:bv4,getStreamError:NT8}=U41(),yv4=Y41(),FT8=Mh(),kh=F41(),gv4=FT8.alloc(0);class wT8{constructor(){this.buffered=0,this.shifted=0,this.queue=new yv4,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 gv4;let Z=this._next($);if($===Z.byteLength)return Z;let X=[Z];while(($-=Z.byteLength)>0)Z=this._next($),X.push(Z);return FT8.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 BT8 extends bv4{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(NT8(this))}_detach(){if(this._parent._stream===this)this._parent._stream=null,this._parent._missing=LT8(this.header.size),this._parent._update()}_destroy($){this._detach(),$(null)}}class OT8 extends fv4{constructor($){super($);if(!$)$={};this._buffer=new wT8,this._offset=0,this._header=null,this._stream=null,this._missing=0,this._longHeader=!1,this._callback=w41,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=kh.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=kh.decodeLongPath($,this._filenameEncoding);break;case"gnu-long-link-path":this._gnuLongLinkPath=kh.decodeLongPath($,this._filenameEncoding);break;case"pax-global-header":this._paxGlobal=kh.decodePax($);break;case"pax-header":this._pax=this._paxGlobal===null?kh.decodePax($):Object.assign({},this._paxGlobal,kh.decodePax($));break}}_consumeLongHeader(){this._longHeader=!1,this._missing=LT8(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 BT8(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=w41,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(NT8(this));$(null)}[Symbol.asyncIterator](){let $=null,Z=null,X=null,Q=null,Y=null,G=this;return this.on("entry",W),this.on("error",(N)=>{$=N}),this.on("close",H),{[Symbol.asyncIterator](){return this},next(){return new Promise(K)},return(){return U(null)},throw(N){return U(N)}};function J(N){if(!Y)return;let F=Y;Y=null,F(N)}function K(N,F){if($)return F($);if(Q){N({value:Q,done:!1}),Q=null;return}if(Z=N,X=F,J(null),G._finished&&Z)Z({value:void 0,done:!0}),Z=X=null}function W(N,F,w){if(Y=w,F.on("error",w41),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 U(N){return G.destroy(N),J(N),new Promise((F,w)=>{if(G.destroyed)return F({value:void 0,done:!0});G.once("close",function(){if(N)w(N);else F({value:void 0,done:!0})})})}}}DT8.exports=function(Z){return new OT8(Z)};function w41(){}function LT8($){return $&=511,$&&512-$}});var jT8=_((si9,B41)=>{var zT8={S_IFMT:61440,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960};try{B41.exports=N0("fs").constants||zT8}catch{B41.exports=zT8}});var MT8=_((ei9,qT8)=>{var{Readable:hv4,Writable:uv4,getStreamError:PT8}=U41(),T_=Mh(),Sh=jT8(),yz0=F41(),AT8=T_.alloc(1024);class TT8 extends uv4{constructor($,Z,X){super({mapWritable:lv4,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?T_.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?T_.toString(this._linkname,"utf-8"):"",this._pack._encode(this.header);IT8(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 PT8(this)||Error("tar entry destroyed")}_predestroy(){this._pack.destroy(this._getError())}_destroy($){this._pack._done(this),this._continuePack(this._finished?null:this._getError()),$()}}class RT8 extends hv4{constructor($){super($);this._drain=O41,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=O41;if(!$.size||$.type==="symlink")$.size=0;if(!$.type)$.type=cv4($.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=T_.from(Z);let Q=new TT8(this,$,X);if(T_.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(AT8),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=yz0.encode($);if(Z){this.push(Z);return}}this._encodePax($)}_encodePax($){let Z=yz0.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(yz0.encode(X)),this.push(Z),IT8(this,Z.byteLength),X.size=$.size,X.type=$.type,this.push(yz0.encode(X))}_doDrain(){let $=this._drain;this._drain=O41,$()}_predestroy(){let $=PT8(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(),$()}}qT8.exports=function(Z){return new RT8(Z)};function cv4($){switch($&Sh.S_IFMT){case Sh.S_IFBLK:return"block-device";case Sh.S_IFCHR:return"character-device";case Sh.S_IFDIR:return"directory";case Sh.S_IFIFO:return"fifo";case Sh.S_IFLNK:return"symlink"}return"file"}function O41(){}function IT8($,Z){if(Z&=511,Z)$.push(AT8.subarray(0,512-Z))}function lv4($){return T_.isBuffer($)?$:T_.from($)}});var VT8=_((dv4)=>{dv4.extract=ET8();dv4.pack=MT8()});var CT8=_((Zn9,ST8)=>{ST8.exports=kT8;function kT8($,Z){if($&&Z)return kT8($)(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 D41=_((Xn9,L41)=>{var _T8=CT8();L41.exports=_T8(gz0);L41.exports.strict=_T8(vT8);gz0.proto=gz0(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return gz0(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return vT8(this)},configurable:!0})});function gz0($){var Z=function(){if(Z.called)return Z.value;return Z.called=!0,Z.value=$.apply(this,arguments)};return Z.called=!1,Z}function vT8($){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 bT8=_((Qn9,fT8)=>{var nv4=D41(),pv4=function(){},tv4=global.Bare?queueMicrotask:process.nextTick.bind(process),ov4=function($){return $.setHeader&&typeof $.abort==="function"},rv4=function($){return $.stdio&&Array.isArray($.stdio)&&$.stdio.length===3},xT8=function($,Z,X){if(typeof Z==="function")return xT8($,null,Z);if(!Z)Z={};X=nv4(X||pv4);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($)},U=function(){if(G=!1,!J)X.call($)},N=function(D){X.call($,D?Error("exited with error code: "+D):null)},F=function(D){X.call($,D)},w=function(){tv4(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(ov4($))if($.on("complete",H),$.on("abort",w),$.req)L();else $.on("request",L);else if(J&&!Q)$.on("end",W),$.on("close",W);if(rv4($))$.on("exit",N);if($.on("end",U),$.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",N),$.removeListener("end",U),$.removeListener("error",F),$.removeListener("close",w)}};fT8.exports=xT8});var hT8=_((Yn9,gT8)=>{var av4=D41(),sv4=bT8(),hz0;try{hz0=N0("fs")}catch($){}var ro=function(){},ev4=typeof process>"u"?!1:/^v?\.0/.test(process.version),uz0=function($){return typeof $==="function"},$x4=function($){if(!ev4)return!1;if(!hz0)return!1;return($ instanceof(hz0.ReadStream||ro)||$ instanceof(hz0.WriteStream||ro))&&uz0($.close)},Zx4=function($){return $.setHeader&&uz0($.abort)},Xx4=function($,Z,X,Q){Q=av4(Q);var Y=!1;$.on("close",function(){Y=!0}),sv4($,{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,$x4($))return $.close(ro);if(Zx4($))return $.abort();if(uz0($.destroy))return $.destroy();Q(J||Error("stream was destroyed"))}},yT8=function($){$()},Qx4=function($,Z){return $.pipe(Z)},Yx4=function(){var $=Array.prototype.slice.call(arguments),Z=uz0($[$.length-1]||ro)&&$.pop()||ro;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 Xx4(Y,J,K,function(W){if(!X)X=W;if(W)Q.forEach(yT8);if(J)return;Q.forEach(yT8),Z(X)})});return $.reduce(Qx4)};gT8.exports=Yx4});var tT8=_((Wx4)=>{var uT8=VT8(),cT8=hT8(),lT8=N0("fs"),B9=N0("path"),ao=(global.Bare?global.Bare.platform:process.platform)==="win32";Wx4.pack=function(Z,X){if(!Z)Z=".";if(!X)X={};let Q=X.fs||lT8,Y=X.ignore||X.filter||so,G=X.mapStream||nT8,J=Kx4(Q,X.dereference?Q.stat:Q.lstat,Z,Y,X.entries,X.sort),K=X.strict!==!1,W=typeof X.umask==="number"?~X.umask:~dT8(),H=X.pack||uT8.pack(),U=X.finish||so,N=X.map||so,F=typeof X.dmode==="number"?X.dmode:0,w=typeof X.fmode==="number"?X.fmode:0;if(X.strip)N=pT8(N,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(B9.join(Z,E),function(j,A){if(j)return H.destroy(j);z.linkname=E41(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 U(H)}if(j.isSocket())return D();let A={name:E41(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=N(A)||A,H.entry(A,D);if(j.isSymbolicLink())return A.size=0,A.type="symlink",A=N(A)||A,B(z,A);if(A=N(A)||A,!j.isFile()){if(K)return H.destroy(Error("unsupported type for "+z));return D()}let P=H.entry(A,D),I=G(Q.createReadStream(B9.join(Z,z),{start:0,end:A.size>0?A.size-1:A.size}),A);I.on("error",function(V){P.destroy(V)}),cT8(I,P)}function D(E){if(E)return H.destroy(E);J(L)}return H};function Gx4($){return $.length?$[$.length-1]:null}function Jx4(){return!global.Bare&&process.getuid?process.getuid():-1}function dT8(){return!global.Bare&&process.umask?process.umask():0}Wx4.extract=function(Z,X){if(!Z)Z=".";if(!X)X={};Z=B9.resolve(Z);let Q=X.fs||lT8,Y=X.ignore||X.filter||so,G=X.mapStream||nT8,J=X.chown!==!1&&!ao&&Jx4()===0,K=X.extract||uT8.extract(),W=[],H=new Date,U=typeof X.umask==="number"?~X.umask:~dT8(),N=X.strict!==!1,F=X.validateSymlinks!==!1,w=X.map||so,B=typeof X.dmode==="number"?X.dmode:0,L=typeof X.fmode==="number"?X.fmode:0;if(X.strip)w=pT8(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,I,V){P=w(P)||P,P.name=E41(P.name);let M=B9.join(Z,B9.join("/",P.name));if(Y(M,P))return I.resume(),V();let C=B9.join(M,".")===B9.join(Z,".")?Z:B9.dirname(M);iT8(Q,C,B9.join(Z,"."),function(a,F0){if(a)return V(a);if(!F0)return V(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},m);A(C,{fs:Q,own:J,uid:P.uid,gid:P.gid,mode:493},function(j0){if(j0)return V(j0);switch(P.type){case"file":return b();case"link":return y();case"symlink":return f()}if(N)return V(Error("unsupported type for "+M+" ("+P.type+")"));I.resume(),V()})});function m(a){if(a)return V(a);z(M,P,function(F0){if(F0)return V(F0);if(ao)return V();j(M,P,V)})}function f(){if(ao)return V();Q.unlink(M,function(){let a=B9.resolve(B9.dirname(M),P.linkname);if(!o(a)&&F)return V(Error(M+" is not a valid symlink"));mT8(Q,a,B9.join(Z,"."),function(F0,j0){if(F0)return V(F0);if(!j0&&F)return V(Error(M+" is not a valid symlink"));Q.symlink(P.linkname,M,m)})})}function y(){if(ao)return V();Q.unlink(M,function(){let a=B9.join(Z,B9.join("/",P.linkname));Q.realpath(a,function(F0,j0){if(F0||!o(j0))return V(Error(M+" is not a valid hardlink"));Q.link(j0,M,function(Z0){if(Z0&&Z0.code==="EPERM"&&X.hardlinkAsFilesFallback)return I=Q.createReadStream(j0),b();m(Z0)})})})}function o(a){return a===Z||a.startsWith(Z+B9.sep)}function b(){let a=Q.createWriteStream(M),F0=G(I,P);a.on("error",function(j0){F0.destroy(j0)}),cT8(F0,a,function(j0){if(j0)return V(j0);a.on("close",m)})}}function E(P,I){let V;while((V=Gx4(W))&&P.slice(0,V[0].length)!==V[0])W.pop();if(!V)return I();Q.utimes(V[0],H,V[1],I)}function z(P,I,V){if(X.utimes===!1)return V();if(I.type==="directory")return Q.utimes(P,H,I.mtime,V);if(I.type==="symlink")return E(P,V);Q.utimes(P,H,I.mtime,function(M){if(M)return V(M);E(P,V)})}function j(P,I,V){let M=I.type==="symlink",C=M?Q.lchmod:Q.chmod,m=M?Q.lchown:Q.chown;if(!C)return V();let f=(I.mode|(I.type==="directory"?B:L))&U;if(m&&J)m.call(Q,P,I.uid,I.gid,y);else y(null);function y(o){if(o)return V(o);if(!C)return V();C.call(Q,P,f,V)}}function A(P,I,V){Q.stat(P,function(M){if(!M)return V(null);if(M.code!=="ENOENT")return V(M);Q.mkdir(P,{mode:I.mode,recursive:!0},function(C,m){if(C)return V(C);j(P,I,V)})})}};function mT8($,Z,X,Q){if(Z===X)return Q(null,!0);if(!Z.startsWith(X+B9.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 mT8($,B9.join(Z,".."),X,Q);Q(null,!1)})}function iT8($,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 iT8($,B9.join(Z,".."),X,Q);Q(null,!1)})}function so(){}function nT8($){return $}function E41($){return ao?$.replace(/\\/g,"/").replace(/[:?<>|]/g,"_"):$}function Kx4($,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(),U=B9.join(X,H);Z.call($,U,function(N,F){if(N)return W(Y.indexOf(H)===-1&&N.code==="ENOENT"?null:N);if(!F.isDirectory())return W(null,H,F);$.readdir(U,function(w,B){if(w)return W(w);if(G)B.sort();for(let L=0;L<B.length;L++)if(!Q(B9.join(X,H,B[L])))J.push(B9.join(H,B[L]));W(null,H,F)})})}}function pT8($,Z){return function(X){X.name=X.name.split("/").slice(Z).join("/");let Q=X.linkname;if(Q&&(X.type==="link"||B9.isAbsolute(Q)))X.linkname=Q.split("/").slice(Z).join("/");return $(X)}}});var Nx4,Fx4;var oT8=O(()=>{X41();Nx4=k(bA8(),1),Fx4=k(tT8(),1)});var cz0=()=>{};var rT8=O(()=>{Zz0()});var aT8=O(()=>{Vz0();Mz0();cz0()});var sT8=()=>{};var eT8=()=>{};var z41=O(()=>{DA8();$41();Vz0();AA8();s61();X41();TA8();RA8();IA8();qA8();e61();MA8();oT8();cz0();rT8();aT8();sT8();eT8();cz0()});var f9,a9,R_,eo;var $r=O(()=>{f9={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"};a9=class a9 extends Error{cause;constructor($,Z){super($);if(this.name="SandboxError",this.cause=Z,Z instanceof Error&&Z.stack)this.stack=`${this.stack}
|
|
2317
2317
|
Caused by: ${Z.stack}`}};R_=class R_ extends a9{constructor($,Z){super($,Z);this.name="SandboxTimeoutError"}};eo=class eo extends a9{constructor($,Z){super($,Z);this.name="SandboxAlreadyExistsError"}}});async function wx4($){let Z=$.getCurrentCluster();if(!Z)throw new a9("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:j41(X.cert),key:j41(X.key),ca:j41(X.ca),rejectUnauthorized:Z.skipTLSVerify?!1:void 0}}}function j41($){if($==null)return;if(typeof $==="string")return $;if(Buffer.isBuffer($))return $.toString("utf8");return String($)}async function LK($,Z){let X=await wx4($),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 P41($){try{return await $.json()}catch{return null}}async function lz0($,Z){if($.ok)return;let X=await P41($),Q=X?.message??`${Z} failed: ${$.status} ${$.statusText}`;throw new $R8($.status,X,Q)}async function Ch($,Z,X,Q,Y="none"){try{let G=await LK($,Z);if(G.status===404)return null;if(await lz0(G,X),Y==="json")return await G.json();return null}catch(G){throw new a9(Q,G)}}async function Zr($,Z,X){let Q=`${A41}/${encodeURIComponent(Z)}/${f9.CLAIM_PLURAL}`,Y;try{Y=await LK($,{method:"POST",path:Q,body:X})}catch(H){let U=H instanceof Error?H.message:String(H);throw console.warn(`[agent-sandbox/client] createSandboxClaim ${X.metadata.name} transport error: ${U}`),new a9(`Failed to create SandboxClaim: ${X.metadata.name} (transport error: ${U})`,H)}if(Y.ok)return;let G=await P41(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 eo(W);throw new a9(W)}async function dz0($,Z,X,Q=60000){let Y=Date.now()+Q,G=500,J;while(!0){let K=await DK($,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 R_(`SandboxClaim ${X} still terminating after ${Q}ms (deletionTimestamp=${H}, finalizers=[${W.join(", ")}])`)}await T8(500)}}function T41($,Z){return`${A41}/${encodeURIComponent($)}/${f9.CLAIM_PLURAL}/${encodeURIComponent(Z)}`}async function mz0($,Z,X,Q){await Ch($,{method:"PATCH",path:T41(Z,X),patchType:"merge",body:{spec:{lifecycle:{shutdownPolicy:"Delete",shutdownTime:Q}}}},"patchSandboxClaimShutdown",`Failed to patch SandboxClaim shutdownTime: ${X}`)}async function MO($,Z,X){await Ch($,{method:"DELETE",path:T41(Z,X)},"deleteSandboxClaim",`Failed to delete SandboxClaim: ${X}`)}async function DK($,Z,X){return await Ch($,{method:"GET",path:T41(Z,X)},"getSandboxClaim",`Failed to get SandboxClaim: ${X}`,"json")??void 0}async function ZR8($,Z,X,Q=60){let Y=Date.now()+Q*1000,G=200;while(Date.now()<Y){let K=(await DK($,Z,X).catch(()=>{return}))?.status?.sandbox?.name;if(K)return K;await T8(200)}throw new R_(`SandboxClaim ${X} did not record an adopted Sandbox (status.sandbox.name) within ${Q}s`)}async function XR8($,Z,X){let Y=(await Ch($,{method:"GET",path:`${A41}/${encodeURIComponent(Z)}/sandboxwarmpools/${encodeURIComponent(X)}`},"getSandboxWarmPool",`Failed to get SandboxWarmPool: ${X}`,"json"))?.status?.selector;if(!Y)return null;let G=await LK($,{method:"GET",path:`/api/v1/namespaces/${encodeURIComponent(Z)}/pods?labelSelector=${encodeURIComponent(Y)}`});return await lz0(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 QR8($,Z,X,Q){try{let Y=await LK($,{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 R41($,Z){return`${Bx4}/${encodeURIComponent($)}/${JR8}/${encodeURIComponent(Z)}`}async function iz0($,Z,X){let Q=new URLSearchParams({fieldManager:WR8,force:"true"}),Y=`${R41(Z,X.metadata.name)}?${Q}`;try{let G=await LK($,{method:"PATCH",path:Y,patchType:"apply",body:X});await lz0(G,"applyHttpRoute")}catch(G){throw new a9(`Failed to apply HTTPRoute: ${X.metadata.name}`,G)}}async function nz0($,Z,X){await Ch($,{method:"DELETE",path:R41(Z,X)},"deleteHttpRoute",`Failed to delete HTTPRoute: ${X}`)}async function KR8($,Z,X){return await Ch($,{method:"GET",path:R41(Z,X)},"getHttpRoute",`Failed to get HTTPRoute: ${X}`,"json")??void 0}async function HR8($,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:WR8,force:"true"}),J=`/api/v1/namespaces/${encodeURIComponent(Z)}/services/${encodeURIComponent(X)}?${G}`;try{let K=await LK($,{method:"PATCH",path:J,patchType:"apply",body:Y});await lz0(K,"ensureServicePort")}catch(K){throw new a9(`Failed to apply Service ports: ${X}`,K)}}function pz0($,Z,X,Q=180){let Y=`/apis/${f9.SANDBOX_API_GROUP}/${f9.SANDBOX_API_VERSION}/namespaces/${encodeURIComponent(Z)}/${f9.SANDBOX_PLURAL}?watch=true&fieldSelector=${encodeURIComponent(`metadata.name=${X}`)}`,{resolve:G,reject:J,promise:K}=Promise.withResolvers(),W=new AbortController,H=!1,U=setTimeout(()=>{if(H)return;H=!0,W.abort(),J(new R_(`Sandbox did not become ready within ${Q} seconds`))},Q*1000),N=(F)=>{if(H)return;H=!0,clearTimeout(U),W.abort(),F()};return(async()=>{let F;try{F=await LK($,{method:"GET",path:Y,signal:W.signal,headers:{accept:"application/json"},stream:!0})}catch(w){N(()=>J(new a9("Failed to start watch for sandbox readiness",w)));return}if(!F.ok||!F.body){let w=await P41(F).catch(()=>null);N(()=>J(new a9(`Watch handshake failed (${F.status}): ${w?.message??F.statusText}`)));return}try{for await(let w of I41(F.body)){if(H)return;if(w.type==="ERROR"){let z=w.object;N(()=>J(new a9(`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){N(()=>J(new a9("Sandbox metadata or name is missing")));return}let E=B.metadata?.annotations?.[f9.POD_NAME_ANNOTATION]??D;N(()=>G({sandboxName:D,podName:E}));return}N(()=>J(new a9("Watch stream closed before sandbox became ready")))}catch(w){if(H)return;if(w instanceof Error&&(w.name==="AbortError"||W.signal.aborted))return;N(()=>J(new a9("Watch stream error while waiting for sandbox",w)))}})(),K}async function*I41($){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(`
|
|
2318
|
-
`))>=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 $R8,A41,YR8="gateway.networking.k8s.io",GR8="v1",JR8="httproutes",Bx4,Xr,WR8="mesh-sandbox-runner";var Qr=O(()=>{a4();$r();$R8=class $R8 extends Error{status;body;constructor($,Z,X){super(X);this.status=$;this.body=Z;this.name="KubeHttpError"}};A41=`/apis/${f9.CLAIM_API_GROUP}/${f9.CLAIM_API_VERSION}/namespaces`;Bx4=`/apis/${YR8}/${GR8}/namespaces`;Xr={API_GROUP:YR8,API_VERSION:GR8,PLURAL:JR8}});function Lx4($){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 NR8($,Z){let X=0,Q=!0,Y=null,G=async()=>{try{let J=await LK($,{method:"GET",path:`/api/v1/namespaces/${encodeURIComponent(Z)}/pods?fieldSelector=status.phase%3DPending`});if(!J.ok)return UR8;let K=await J.json();return!Lx4(K)}catch{return UR8}};return async()=>{if(Date.now()-X<Ox4)return Q;return Y??=G().finally(()=>{Y=null}),Q=await Y,X=Date.now(),Q}}var Ox4=3000,UR8=!0;var FR8=O(()=>{Qr()});var tz0=O(()=>{a4();E81()});async function rz0($){try{let Z=await fetch(`${$}/health`,{signal:AbortSignal.timeout(Dx4)});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 M41($){for(let Z=0;Z<wR8;Z++){if(await rz0($)!==null)return;let X=(Math.random()*2-1)*Ex4;await T8(BR8+X)}throw Error(`sandbox daemon at ${$} did not respond on /health within ${wR8*BR8/1000}s`)}async function I_($,Z,X,Q,Y){return zx4($,Z,"POST",X,Q,Y)}async function zx4($,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??q41)}),W=await K.text();if(!K.ok)throw new oz0(K.status,W);return JSON.parse(W)}async function OR8($,Z,X){let Q=await fetch(`${$}/_sandbox/setup/${X}`,{method:"POST",headers:{Authorization:`Bearer ${Z}`},signal:AbortSignal.timeout(q41)});if(!Q.ok)throw Error(`sandbox daemon /_sandbox/setup/${X} returned ${Q.status}: ${await Q.text()}`)}async function LR8($,Z,X){let Q=await fetch(`${$}/_sandbox/orgfs-config`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Z}`},body:X,signal:AbortSignal.timeout(q41)}),Y=await Q.text();if(!Q.ok)throw Error(`sandbox daemon /_sandbox/orgfs-config returned ${Q.status}: ${Y}`);return JSON.parse(Y)}async function Yr($,Z,X,Q){let Y=new Headers(Q.headers);for(let K of jx4)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 oz0,Dx4=500,q41=30000,wR8=25,BR8=200,Ex4=50,jx4;var DR8=O(()=>{tz0();oz0=class oz0 extends Error{status;constructor($,Z){super(`sandbox daemon /_sandbox/config returned ${$}: ${Z}`);this.status=$;this.name="ConfigRequestError"}};jx4=["cookie","host","connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","accept-encoding","content-length"]});async function*jR8($){let Z=$.now??(()=>Date.now()),X=Z(),Q=$.schedulingTimeoutMs??Tx4,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})},U=()=>{if(K)return;if(K=!0,J){let z=J;J=null,z(null)}},N=new AbortController,F=()=>{N.abort(),U()};if($.signal)if($.signal.aborted)N.abort(),U();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([Rx4($.kc,$.namespace,$.claimName,N.signal,Y,W,Z,L),qx4($.kc,$.namespace,$.claimName,N.signal,Y,W),Mx4($.kc,$.namespace,$.claimName,D,N.signal,Y,W,Z)]);try{let z=null,j=-1,A=ER8(Y,Q,Z);if(z=k41(A),!V41(A))j=zR8(A);if(yield A,V41(A))return;while(!K){if(await H()===null)break;let I=ER8(Y,Q,Z);if(V41(I)){let C=k41(I);if(C!==z)z=C,yield I;return}let V=zR8(I);if(V<j)continue;let M=k41(I);if(M!==z)z=M,j=V,yield I}}finally{if(clearTimeout(B),N.abort(),$.signal)$.signal.removeEventListener("abort",F);U(),await E.catch(()=>{})}}function ER8($,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 V41($){return $.kind==="ready"||$.kind==="failed"}function zR8($){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 k41($){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 Rx4($,Z,X,Q,Y,G,J,K){let W=`/api/v1/namespaces/${encodeURIComponent(Z)}/pods?watch=true&labelSelector=${encodeURIComponent(`${Px4}=${X}`)}`;return az0({kc:$,path:W,signal:Q,label:`pod/${X}`,onEvent:(H)=>{if(H.type!=="ADDED"&&H.type!=="MODIFIED")return;let U=H.object;if(U.metadata?.name)K(U.metadata.name);Ix4(U,Y,J),G("pod")}})}function Ix4($,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===Ax4);if(G)Z.pod.containerWaitingReason=G.state?.waiting?.reason,Z.pod.containerRunning=!!G.state?.running,Z.pod.containerReady=G.ready===!0}async function qx4($,Z,X,Q,Y,G){let J=`/apis/${f9.CLAIM_API_GROUP}/${f9.CLAIM_API_VERSION}/namespaces/${encodeURIComponent(Z)}/${f9.CLAIM_PLURAL}?watch=true&fieldSelector=${encodeURIComponent(`metadata.name=${X}`)}`;return az0({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((U)=>U.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 Mx4($,Z,X,Q,Y,G,J,K){let W=await Promise.race([Q,new Promise((U)=>{if(Y.aborted){U(X);return}Y.addEventListener("abort",()=>U(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 az0({kc:$,path:H,signal:Y,label:`events/${X}`,onEvent:(U)=>{if(U.type!=="ADDED"&&U.type!=="MODIFIED")return;let N=U.object,F=N.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=N.message;break;case"Nominated":{let w=N.message?.match(/nodeclaim\/([\w-]+)/);if(w)G.events.nominatedNodeClaim=w[1];break}default:return}J("event")}})}async function PR8($){let{kc:Z,namespace:X,labelSelector:Q,signal:Y,onDelete:G}=$,J=`/apis/${f9.CLAIM_API_GROUP}/${f9.CLAIM_API_VERSION}/namespaces/${encodeURIComponent(X)}/${f9.CLAIM_PLURAL}?watch=true&labelSelector=${encodeURIComponent(Q)}`;return az0({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 az0($){let{kc:Z,path:X,signal:Q,label:Y,onEvent:G}=$,J=0;while(!Q.aborted){try{let W=await LK(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 I41(W.body)){if(Q.aborted)return;try{G(H)}catch(U){console.warn(`[lifecycle-watcher] ${Y} onEvent threw: ${U instanceof Error?U.message:String(U)}`)}}}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=K7(5000,250,J,2,0);J+=1,await T8(K,{signal:Q}).catch(()=>{})}}var Px4="studio.decocms.com/sandbox-handle",Ax4="sandbox",Tx4=300000;var AR8=O(()=>{a4();$r();Qr()});import{z as q3}from"zod";function TR8($){if(!$||$.trim()==="")return[];let Z=q3.array(Vx4).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 kx4($){try{let[Z,X]=new URL($).pathname.replace(/^\/+/,"").split("/"),Q=X?.replace(/\.git$/,"");return Z&&Q?`${Z}/${Q}`.toLowerCase():null}catch{return null}}function RR8($,Z){let{orgId:X,cloneUrl:Q}=Z;if(Z.cloneOnly===!0)return null;if(!X||!Q)return null;let Y=kx4(Q);if(!Y)return null;return $.find((G)=>G.orgId===X&&G.repo.toLowerCase()===Y)??null}function IR8($,Z,X){return $?.name??(Z?X:"none")}function qR8($,Z,X){let Q=X.replace(/^refs\/heads\//,"");return $.filter((Y)=>Y.repo.toLowerCase()===Z.toLowerCase()&&Y.branch===Q)}function MR8($){return`https://github.com/${$.repo}.git`}var Vx4;var S41=O(()=>{Vx4=q3.object({name:q3.string().regex(/^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/,"pool name must be a DNS label (lowercase alphanumeric and '-')"),orgId:q3.string().min(1),repo:q3.string().regex(/^[^/\s]+\/[^/\s]+$/,"repo must be `owner/name`"),connectionId:q3.string().min(1).optional(),branch:q3.string().min(1).default("main"),workload:q3.object({runtime:q3.enum(["node","bun","deno"]).default("node"),packageManager:q3.enum(["npm","pnpm","yarn","bun","deno"]).optional(),packageManagerPath:q3.string().optional(),devPort:q3.number().int().positive().optional()}).default({runtime:"node"})})});async function VR8($,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 Sx4,randomBytes as Cx4,randomUUID as _x4}from"crypto";import*as fR8 from"net";import{PassThrough as vx4}from"stream";function kR8($){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 y41{kind=OY;records=new Map;inflight=new j30;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??nx4(),this.portForward=new Q41(this.kubeConfig),this.namespace=$.namespace??xx4,this.sandboxTemplateName=$.sandboxTemplateName??fx4,this.envName=sx4($.envName),this.tokenGenerator=$.tokenGenerator??(()=>Cx4(bx4).toString("hex")),this.idleTtlMs=$.idleTtlMs??gx4,this.metrics=$.meter?ix4($.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(`[${u$}] tenant pools configured without a sentinel token \u2014 ignoring them (warm-pool mode is off)`);this.tenantPoolRefreshMs=$.tenantPoolRefreshMs??ux4,this.startClaimReaper(),this.startCredentialRefresher(),this.startTenantPoolReconciler()}startClaimReaper(){let $=["app.kubernetes.io/managed-by=studio","app.kubernetes.io/name=studio-sandbox",...this.envName?[`${LY.env}=${this.envName}`]:[]].join(",");PR8({kc:this.kubeConfig,namespace:this.namespace,labelSelector:$,signal:this.claimWatchAbort.signal,onDelete:(Z)=>this.invalidateRecord(Z)})}async ensure($,Z={}){let X=rz($);if(X.startsWith("s-"))throw Error(`ensure: projectRef has no slug source: ${$.projectRef}`);return this.inflight.run(X,()=>P30(this.stateStore,$,OY,(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,x41(Z.tenant));if(await this.deleteHttpRouteIfManaged($).catch((X)=>{console.warn(`[${u$}] HTTPRoute delete failed for ${$}: ${X instanceof Error?X.message:String(X)}`)}),await MO(this.kubeConfig,this.namespace,$),this.stateStore)if(Z)await this.stateStore.delete(Z.id,OY);else await this.stateStore.deleteByHandle(OY,$)}async alive($){return await DK(this.kubeConfig,this.namespace,$)!==void 0}watchClaimLifecycle($,Z){return jR8({kc:this.kubeConfig,namespace:this.namespace,claimName:$,signal:Z})}hasSchedulableCapacity(){return this.capacityProbe??=NR8(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(OY,$),H=W?.state,U=H?.token;if(W&&U){let F=`http://${H?.adoptedSandboxName??$}.${this.namespace}.svc.cluster.local:${vN}`;try{let w=await Yr(F,U,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 Yr(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 Yr(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 U=await Yr(H.daemonUrl,H.token,Z,X);return J=U.status,U}finally{this.recordProxyDuration("daemon",J,Y,performance.now()-G)}}async adoptLiveClaim($,Z){if(this.records.has(Z))return!0;let X=await DK(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 P30(this.stateStore,$,OY,(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:${vN}`;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(OY,$).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=_41(404,{error:"sandbox not found"});return B.headers.set(M_,"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,_41(404,{error:"not found"});let W=(B)=>`${B}${J.pathname}${J.search}`,H=new Headers(Z.headers);for(let B of dx4)H.delete(B);let U=Z.method!=="GET"&&Z.method!=="HEAD",N={method:Z.method,headers:H,body:U?Z.body:void 0,redirect:"manual",signal:Z.signal,duplex:U?"half":void 0},F;try{F=await fetch(W(G),N)}catch(B){let L=`${G}${J.pathname}`;if(console.warn(`[${u$}] 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),N);let j=new Headers;for(let[A,P]of F.headers.entries())if(!_R8.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(`[${u$}] preview fetch retry to ${L} failed: ${j instanceof Error?j.message:String(j)}`)}}}else this.invalidateRecord($);Y=502;let D=_41(502,{error:"sandbox daemon unreachable"});return D.headers.set(M_,"1"),D}let w=new Headers;for(let[B,L]of F.headers.entries())if(!_R8.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(`[${u$}] opts.image ignored (template ${this.sandboxTemplateName} pins image): got ${X.image}`);if(Q){let J=await Q.get($,OY);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($,OY)}}let Y=await DK(this.kubeConfig,this.namespace,Z).catch(()=>{return});if(Y)if(Y.metadata?.deletionTimestamp)await dz0(this.kubeConfig,this.namespace,Z).catch((J)=>{console.warn(`[${u$}] 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(`[${u$}] 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 MO(this.kubeConfig,this.namespace,Z).catch(()=>{}),await dz0(this.kubeConfig,this.namespace,Z).catch((K)=>{console.warn(`[${u$}] 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 mz0(this.kubeConfig,this.namespace,$.handle,this.computeShutdownTime()).catch((K)=>console.warn(`[${u$}] TTL refresh failed for ${$.handle}: ${K instanceof Error?K.message:String(K)}`));if(this.metrics){let K=x41($.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(yx4.has(Y))Q.push(Y);else X[Y]=G;if(Q.length>0)console.warn(`[${u$}] 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(vN)}}buildClaim($,Z,X){let Q=this.sentinelToken!==null,Y=RR8(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=Zf4(Z),K=Object.keys(J).length>0;return{apiVersion:`${f9.CLAIM_API_GROUP}/${f9.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?{[LY.env]:this.envName}:{},...v41(Z.tenant)},...K?{annotations:J}:{}},spec:{sandboxTemplateRef:{name:this.sandboxTemplateName},additionalPodMetadata:{labels:v41(Z.tenant,{[LY.role]:"claimed",[LY.sandboxHandle]:$,...this.envName?{[LY.env]:this.envName}:{}}),...K?{annotations:J}:{}},env:G,warmpool:IR8(Y,Q,this.sandboxTemplateName),lifecycle:{shutdownPolicy:"Delete",shutdownTime:this.computeShutdownTime()}}}}async provision($,Z,X){let Q=this.tokenGenerator(),Y=_x4(),G=C41,J=this.buildClaim(Z,X,{token:Q,daemonBootId:Y,workdir:G});try{await Zr(this.kubeConfig,this.namespace,J)}catch(F){if(F instanceof eo)await dz0(this.kubeConfig,this.namespace,Z),await Zr(this.kubeConfig,this.namespace,J);else throw F}let K;try{K=await ZR8(this.kubeConfig,this.namespace,Z),await pz0(this.kubeConfig,this.namespace,K)}catch(F){throw await MO(this.kubeConfig,this.namespace,Z).catch(()=>{}),F}try{await this.ensureServicePortForAdoptedSandbox(K),await this.ensureHttpRouteForHandle(Z,K,X.tenant??null)}catch(F){throw await MO(this.kubeConfig,this.namespace,Z).catch(()=>{}),F}let W=await this.openForwarder(K,vN,Z),H=`http://127.0.0.1:${W.localPort}`,U=this.workloadConfigPayload(X),N=Y;try{if(await M41(H),this.sentinelToken!==null){let F=await rz0(H);if(F)N=F.bootId;await I_(H,this.sentinelToken,U??{},{rotateToken:Q})}else if(U)await I_(H,Q,U);await this.relayOrgFsConfig(H,Q,X.orgFsConfigJson)}catch(F){throw this.closeForwarder(W),await this.deleteHttpRouteIfManaged(Z).catch(()=>{}),await MO(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:N,tenant:X.tenant??null,ensureOpts:Gf4(X)}}workloadConfigPayload($){return T30({runtime:$?.workload?.runtime??"node",packageManager:$?.workload?.packageManager?{name:$.workload.packageManager,...$.workload.packageManagerPath?{path:$.workload.packageManagerPath}:{}}:null,repo:$?.repo??null,port:$?.workload?.devPort??SR8,tenant:$?.tenant??void 0,...$?{cloneOnly:$.cloneOnly===!0}:{}})}async relayOrgFsConfig($,Z,X){if(!X)return;await LR8($,Z,X).catch((Q)=>console.warn("[org-fs] sidecar config relay failed",Q))}async refreshDaemonGitCredential($,Z){let X=z81(Z);if(!X)return;try{await I_($.daemonUrl,$.token,X)}catch(Q){console.warn(`[${u$}] 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(`[${u$}] 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 T8(cx4,{signal:$}).catch(()=>{}),$.aborted)break;try{await this.refreshAllGitCredentials()}catch(Z){console.warn(`[${u$}] 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(`[${u$}] tenant pool reconcile failed: ${Z instanceof Error?Z.message:String(Z)}`)}await T8(hx4,{signal:$}).catch(()=>{})}})()}markTenantPoolsDirty($,Z){let X=qR8(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 XR8(this.kubeConfig,this.namespace,$.name);if(Z===null){console.warn(`[${u$}] 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[LY.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>=sz0)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>=sz0){if(Date.now()-Q.lastFailureAt<CR8)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:MR8($),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,vN,Z.name).catch(()=>null);if(!K){this.recordPoolFailure(Z,$,"port-forward failed");return}let W=`http://127.0.0.1:${K.localPort}`;try{await M41(W);let H=this.sentinelToken;if(!H)return;if(!await this.isPoolPodUnbound(Z))return;let U=T30({runtime:$.workload.runtime,packageManager:$.workload.packageManager?{name:$.workload.packageManager,...$.workload.packageManagerPath?{path:$.workload.packageManagerPath}:{}}:null,repo:J,port:$.workload.devPort??SR8})??{},{transition:N}=await I_(W,H,U);if(Y&&N!=="bootstrap"&&await this.isPoolPodUnbound(Z))await OR8(W,H,"clone");this.poolPods.set(Z.uid,{lastConfigAt:Date.now(),lastFailureAt:0,failures:0}),console.log(`[${u$}] tenant pool ${$.name}: warmed ${Z.name} (${N})`)}catch(H){this.recordPoolFailure(Z,$,H instanceof Error?H.message:String(H))}finally{this.closeForwarder(K)}}isPoolPodUnbound($){return QR8(this.kubeConfig,this.namespace,$.name,LY.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>=sz0?` \u2014 backing off ${CR8/60000}min`:"";console.warn(`[${u$}] tenant pool ${Z.name}: warming ${$.name} failed (${Y}/${sz0})${G}: ${X}`)}async refreshAllGitCredentials(){await VR8(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,lx4);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 I_($,this.sentinelToken,Q,{rotateToken:Z}),await this.relayOrgFsConfig($,Z,X?.orgFsConfigJson),!0}catch(Y){if(Y instanceof oz0&&Y.status===401)try{return await I_($,Z,Q,{rotateToken:Z}),await this.relayOrgFsConfig($,Z,X?.orgFsConfigJson),!0}catch(G){return console.warn(`[${u$}] re-bootstrap retry with claim token failed: ${G instanceof Error?G.message:String(G)}`),!1}return console.warn(`[${u$}] re-bootstrap failed: ${Y instanceof Error?Y.message:String(Y)}`),!1}}async ensureServicePortForAdoptedSandbox($){if(!this.previewGateway||!this.previewUrlPattern)return;await HR8(this.kubeConfig,this.namespace,$,{name:"daemon",port:vN,targetPort:vN})}async ensureHttpRouteForHandle($,Z,X){if(!this.previewGateway||!this.previewUrlPattern)return;let Q=Jf4(this.previewUrlPattern,$);if(!Q)throw new a9(`Unable to derive preview hostname for ${$} from pattern: ${this.previewUrlPattern}`);let Y={apiVersion:`${Xr.API_GROUP}/${Xr.API_VERSION}`,kind:"HTTPRoute",metadata:{name:$,namespace:this.namespace,labels:v41(X??void 0,{[LY.role]:"claimed",[LY.sandboxHandle]:$,"app.kubernetes.io/name":"studio-sandbox","app.kubernetes.io/managed-by":"studio",...this.envName?{[LY.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:vN}]}]}};await iz0(this.kubeConfig,this.namespace,Y)}async deleteHttpRouteIfManaged($){if(!this.previewGateway)return;await nz0(this.kubeConfig,this.namespace,$)}async rehydrate($,Z,X){let Q=X.state;if(!Q.adoptedSandboxName&&!Q.podName||!Q.token)return null;let Y=await DK(this.kubeConfig,this.namespace,Z).catch(()=>{return});if(!Y||!vR8(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(`[${u$}] daemon restart detected (handle=${Z}): stored bootId=${Q.daemonBootId} live bootId=${J.bootId}`);await this.stateStore?.put($,OY,{handle:Z,state:{...Q,daemonBootId:J.bootId}}).catch((K)=>console.warn(`[${u$}] bootId persist failed for ${Z}: ${K instanceof Error?K.message:String(K)}`))}return{id:$,handle:Z,adoptedSandboxName:G,token:Q.token,workdir:Q.workdir??C41,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(!vR8(X))return null;let Q=X.status?.sandbox?.name??Z;if(this.sentinelToken!==null)return null;let Y=px4(X);if(!Y)return null;let G=await this.openAndProbeDaemon(Q,Z);if(!G)return null;let J=Xf4(X);if(this.previewGateway)await this.ensureServicePortForAdoptedSandbox(Q).catch((K)=>{console.warn(`[${u$}] Service port backfill failed for ${Z}: ${K instanceof Error?K.message:String(K)}`)}),await this.ensureHttpRouteForHandle(Z,Q,J).catch((K)=>{console.warn(`[${u$}] HTTPRoute backfill failed for ${Z}: ${K instanceof Error?K.message:String(K)}`)});return{id:$,handle:Z,adoptedSandboxName:Q,token:Y,workdir:C41,daemonUrl:G.daemonUrl,daemonForward:G.daemonForward,workload:null,daemonBootId:G.bootId,tenant:J,ensureOpts:null}}async openAndProbeDaemon($,Z){let X=await this.openForwarder($,vN,Z).catch(()=>null);if(!X)return null;let Q=`http://127.0.0.1:${X.localPort}`,Y=await rz0(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(OY,$);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(OY,$);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(rz(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,{...x41(X?.tenant??null),source:$,sandbox_handle:X?.handle??Y??"",status_code:Z||0})}composePreviewUrl($){if(this.previewUrlPattern)return A30(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,OY,{handle:Z.handle,state:X})}computeShutdownTime(){return new Date(Date.now()+this.idleTtlMs).toISOString()}async releaseAfter($,Z){let X=await DK(this.kubeConfig,this.namespace,$);if(!X)return;let Q=Qf4(X.spec?.lifecycle?.shutdownTime,new Date(Date.now()+Z));if(!Q)return;await mz0(this.kubeConfig,this.namespace,$,Q).catch((Y)=>console.warn(`[${u$}] release failed for ${$}: ${Y instanceof Error?Y.message:String(Y)}`))}async renewTtl($){let Z=await DK(this.kubeConfig,this.namespace,$);if(!Z)return;let X=Yf4(Z.spec?.lifecycle?.shutdownTime,new Date(Date.now()+this.idleTtlMs));if(!X)return;await mz0(this.kubeConfig,this.namespace,$,X).catch((Q)=>console.warn(`[${u$}] TTL renew failed for ${$}: ${Q instanceof Error?Q.message:String(Q)}`))}openForwarder($,Z,X=$){let Q=tx4(X,Z);return new Promise((Y,G)=>{let J=(K,W)=>{let H=fR8.createServer((U)=>this.handleForwardedConnection(U,$,Z,X));H.once("error",(U)=>{if(U.code==="EADDRINUSE"&&W<mx4){try{H.close()}catch{}let N=f41+(K-f41+1)%bR8;J(N,W+1);return}G(U)}),H.listen(K,"127.0.0.1",()=>{let U=H.address();if(!U||typeof U==="string"){H.close(),G(Error("port-forward listener failed to bind"));return}Y({server:H,localPort:U.port})})};J(Q,0)})}handleForwardedConnection($,Z,X,Q){let Y=new vx4,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",(U)=>{console.warn(`[${u$}] port-forward to ${Z}:${X} dropped mid-connection: ${kR8(U)}`,JSON.stringify(b41(U))),this.invalidateRecord(Q),K()}),J)try{G.close()}catch{}}).catch((W)=>{console.warn(`[${u$}] port-forward to ${Z}:${X} failed: ${kR8(W)}`,JSON.stringify(b41(W))),this.invalidateRecord(Q),K()})}closeForwarder($){$.server.close((Z)=>{if(Z)console.warn(`[${u$}] 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 ix4($){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 b41($){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?b41(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 nx4(){let $=new qh;return $.loadFromDefault(),$}function vR8($){return Boolean($.status?.conditions?.some((Z)=>Z.type==="Ready"&&Z.status==="True"))}function px4($){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 tx4($,Z){let X=Sx4("sha256").update(`${$}:${Z}`).digest();return f41+X.readUInt32BE(0)%bR8}function _41($,Z){return new Response(JSON.stringify(Z),{status:$,headers:{"content-type":"application/json","access-control-allow-origin":"*"}})}function xR8($){let Z=$.slice(0,rx4);return ox4.test(Z)?Z:""}function sx4($){if($===void 0)return null;let Z=$.trim();if(Z==="")return null;if(!ax4.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 v41($,Z={}){let X={...Z};if($){let Q=xR8($.orgId),Y=xR8($.userId);if(Q)X[LY.orgId]=Q;if(Y)X[LY.userId]=Y}return X}function q_($){let Z="";for(let X of $){let Q=X.codePointAt(0)??0;Z+=Q<32||Q===127?" ":X}return Z.slice(0,ex4)}function $f4($){try{let Z=new URL($);return Z.username="",Z.password="",Z.toString()}catch{return""}}function Zf4($){let Z={},X=$.tenant;if(X?.orgSlug)Z[EK.orgSlug]=q_(X.orgSlug);if(X?.orgName)Z[EK.orgName]=q_(X.orgName);if(X?.userEmail)Z[EK.userEmail]=q_(X.userEmail);if(X?.userName)Z[EK.userName]=q_(X.userName);let Q=$.repo;if(Q){if(Q.displayName)Z[EK.gitRepo]=q_(Q.displayName);let Y=$f4(Q.cloneUrl);if(Y)Z[EK.gitRepoUrl]=q_(Y);let G=$.branch??Q.branch;if(G)Z[EK.gitBranch]=q_(G)}return Z}function Xf4($){let Z=$.metadata?.labels;if(!Z)return null;let X=Z[LY.orgId],Q=Z[LY.userId];if(!X||!Q)return null;let Y=$.metadata?.annotations??{};return{orgId:X,userId:Q,orgSlug:Y[EK.orgSlug],orgName:Y[EK.orgName],userEmail:Y[EK.userEmail],userName:Y[EK.userName]}}function Qf4($,Z){if($){let X=new Date($).getTime();if(Number.isFinite(X)&&X<=Z.getTime())return null}return Z.toISOString()}function Yf4($,Z){if($){let X=new Date($).getTime();if(Number.isFinite(X)&&X>=Z.getTime())return null}return Z.toISOString()}function x41($){return{org_id:$?.orgId??"",user_id:$?.userId??"",runner_kind:OY}}function Gf4($){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 Jf4($,Z){try{return new URL(A30($,Z)).hostname||null}catch{return null}}var OY="agent-sandbox",u$="AgentSandboxProvider",M_="x-sandbox-preview-not-ready",xx4="agent-sandbox-system",fx4="studio-sandbox",vN=9000,SR8=3000,C41="/app",bx4=32,yx4,gx4=900000,hx4=60000,ux4=1800000,sz0=3,CR8=1800000,cx4=900000,lx4=1800000,dx4,_R8,f41=40000,bR8=1e4,mx4=256,LY,EK,ox4,rx4=63,ax4,ex4=253;var yR8=O(()=>{a4();FR8();z41();DR8();j81();Qr();$r();AR8();S41();yx4=new Set(["DAEMON_TOKEN","DAEMON_BOOT_ID","APP_ROOT","PROXY_PORT"]),dx4=["cookie","host","connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","accept-encoding","content-length","upgrade"],_R8=["connection","keep-alive","transfer-encoding","content-encoding","content-length"];LY={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"},EK={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"},ox4=/^([A-Za-z0-9]([-A-Za-z0-9_.]*[A-Za-z0-9])?)?$/;ax4=/^[a-z]([a-z0-9-]{0,30}[a-z0-9])?$/});var gR8={};B0(gR8,{waitForSandboxReady:()=>pz0,parseTenantPools:()=>TR8,getSandboxClaim:()=>DK,getHttpRoute:()=>KR8,deleteSandboxClaim:()=>MO,deleteHttpRoute:()=>nz0,createSandboxClaim:()=>Zr,applyHttpRoute:()=>iz0,SandboxTimeoutError:()=>R_,SandboxError:()=>a9,PREVIEW_NOT_READY_HEADER:()=>M_,KubeConfig:()=>qh,K8S_CONSTANTS:()=>f9,HTTPROUTE_CONSTANTS:()=>Xr,AgentSandboxProvider:()=>y41});var g41=O(()=>{z41();$r();Qr();yR8();S41()});var mR8={};B0(mR8,{subscribeLifecycle:()=>l41,getSandboxProviderByKind:()=>u41,getOrInitSharedRunner:()=>c41,__resetSharedLifecyclesForTesting:()=>Ef4});function lR8($,Z){let X=hR8[$];if(X)return Promise.resolve(X);let Q=h41[$];if(Q)return Q;let Y=Z().then((G)=>{return hR8[$]=G,G}).finally(()=>{delete h41[$]});return h41[$]=Y,Y}function Hf4(){let $=process.env.STUDIO_SANDBOX_PREVIEW_URL_PATTERN;return $&&$.trim()!==""?$:void 0}function Uf4(){let $=process.env.STUDIO_SANDBOX_TEMPLATE_NAME;return $&&$.trim()!==""?$:void 0}function Nf4(){let $=process.env.STUDIO_ENV;return $&&$.trim()!==""?$:void 0}function Ff4(){let $=process.env.STUDIO_SANDBOX_SENTINEL_TOKEN;return $&&$.trim()!==""?$:void 0}function wf4(){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 dR8($,Z){let X=new _o(Z),Q=Hf4();switch($){case"agent-sandbox":{let{AgentSandboxProvider:Y,parseTenantPools:G}=await Promise.resolve().then(() => (g41(),gR8)),J=new iU(a0().encryptionKey);return new Y({stateStore:X,previewUrlPattern:Q,sandboxTemplateName:Uf4(),envName:Nf4(),previewGateway:wf4(),sentinelToken:Ff4(),tenantPools:G(process.env.STUDIO_SANDBOX_TENANT_POOLS),meter:y8,mintCloneUrl:async(K,W)=>{if(!K.connectionId)return null;let H=kD8(K.cloneUrl);if(!H)return null;let{cloneUrl:U}=await LO(K.connectionId,H.owner,H.name,Z,J,{bufferMs:W?.bufferMs});return U}})}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 u41($,Z){return lR8(Z,()=>dR8(Z,$.db))}async function c41(){let $;try{$=az()}catch(X){return console.warn("[lifecycle] cannot resolve sandbox runner:",X instanceof Error?X.message:String(X)),null}return await lR8($,()=>dR8($,N6().db))}function l41($,Z,X){let Q=VO.get(Z);if(Q){if(Q.terminated){if(Q.lastPhase)try{X(Q.lastPhase)}catch{}return{unsubscribe:Lf4}}if(Q.listeners.add(X),Q.lastPhase)try{X(Q.lastPhase)}catch{}return uR8(Z,Q,X)}let Y=new AbortController,G={lastPhase:null,terminated:!1,listeners:new Set([X]),abort:Y};return VO.set(Z,G),Df4($,Z,G),uR8(Z,G,X)}function Lf4(){}function uR8($,Z,X){return{unsubscribe(){if(VO.get($)!==Z)return;if(Z.listeners.delete(X),Z.listeners.size===0)VO.delete($),Z.abort.abort()}}}async function Df4($,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(VO.get(Z)===X)VO.delete(Z)}}function Ef4(){for(let $ of VO.values())$.abort.abort();VO.clear()}var Kf4,Wf4,cR8,hR8,h41,Bf4,Of4,VO;var Gr=O(()=>{qN();$X();t$();T81();Oh();xi();k8();Kf4=Symbol.for("decocms.sandbox.lifecycle.runners"),Wf4=Symbol.for("decocms.sandbox.lifecycle.inflight"),cR8=globalThis,hR8=cR8[Kf4]??={},h41=cR8[Wf4]??={};Bf4=Symbol.for("decocms.sandbox.lifecycle.shared-lifecycles"),Of4=globalThis,VO=Of4[Bf4]??=new Map});async function OQ($,Z){let{userId:X,branch:Q,virtualMcpMetadata:Y,explicitKind:G}=Z;if(G)return Jr($,G);if($.sandboxPreference==="agent-sandbox")return Jr($,"agent-sandbox");if($.sandboxPreference==="cluster-default")return Jr($,az());let[J,...K]=zf4(Y,X,Q);if(J)return Jr($,K.length===0?J:jf4(J,K));return Jr($,iR8())}function zf4($,Z,X){let Q=o5($)[Z]?.[X];if(!Q)return[];let Y=xJ(Q);return Object.keys(Y)}function jf4($,Z){let X=iR8();if(X===$||Z.includes(X))return X;return $}function iR8(){return az()}async function Jr($,Z){let X=Z==="user-desktop"?"agent-sandbox":Z;return{provider:await u41($,X),kind:X}}var kO=O(()=>{q6();qN();HY();Gr()});var Kr;var d41=O(()=>{Kr={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 zK($,Z){return Z?`thread:${$}/${Z}`:`thread:${$}`}function xN($){return`sandbox/thread-${$.replace(/^thread:/,"").replace(/\//g,"-")}`}function SO($){if(!$||!$.startsWith("thread:"))return null;return $.slice(7).split("/")[0]||null}async function fN($,Z,X){let Q=SO(Z);if(!Q)return X;return(await $.storage.threads.get(Q).catch(()=>null))?.created_by??X}async function V_($,Z){if(!Z)return null;let X=await $.storage.threads.get(Z).catch(()=>null);if(!X)return null;return X.metadata??{}}async function nR8($,Z){let Q=(await V_($,Z))?.headRef;return typeof Q==="string"&&Q.length>0?Q:null}async function pR8($,Z,X){let Q=await V_($,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))}function Pf4($,Z){let X=xG0(Z,$.owner,$.name);if(!X||X.id===$.connectionId)return null;let Q=x5(X);return{...$,connectionId:X.id,...Q?.installationId?{installationId:Q.installationId}:{}}}async function CO($,Z){let X=await V_($,Z),Q=X?.githubRepo??null;if(!Z||!X||!Q?.connectionId)return Q;try{let Y=$.storage.threads.getOrganizationId();if(!Y)return Q;if(await $.storage.connections.findById(Q.connectionId,Y))return Q;let{items:G}=await $.storage.connections.list(Y),J=Pf4(Q,G);if(!J)return Q;return await $.storage.threads.update(Z,{metadata:{...X,githubRepo:J}}),console.warn("[thread-repo] re-pointed thread at a live repo connection",{threadId:Z,from:Q.connectionId,to:J.connectionId}),J}catch(Y){return console.warn("[thread-repo] repoint check failed",Y),Q}}function m41($){if($.pinnedRef)return $.pinnedRef;if($.runBranch&&$.runBranch===zK($.threadId))return $.runBranch;if($.threadRepo)return zK($.threadId,$.threadRepo.connectionId);if(!$.agentRepo)return"ephemeral";return $.runBranch??`thread:${$.threadId}`}async function i41($,Z){let Q=(await V_($,Z))?.pinnedRef;return typeof Q==="string"&&Q.length>0?Q:null}async function tR8($,Z){let[X,Q]=await Promise.all([CO($,Z.threadId),i41($,Z.threadId)]);return m41({...Z,threadRepo:X,pinnedRef:Q})}async function oR8($,Z,X,Q,Y,G){let J=await V_($,Z);if(!J)return;let K=Co(o5(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 ez0($,Z){return o5(await V_($,Z))}async function rR8($,Z,X,Q,Y){let G=await V_($,Z);if(!G)return;let J=A81(o5(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 jK=O(()=>{oQ();HY()});function _h($){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"||!aZ0.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 aR8($){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}async function sR8($,Z){W0(Z);let X=Y0(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=o5(G),K=await fN(Z,$.branch,Q),W=KH(J,K,$.branch,$.sandboxProviderKind);return{virtualMcp:Y,metadata:G,userId:Q,sandboxUserId:K,entry:W,organization:X}}function Af4($){if($===null||!/^\d+$/.test($))return null;let Z=Number($);return Z>=1&&Z<=65535?$:null}function eR8($){let Z=$.runtime??null,Q=Z?.selected??null,Y=Af4(Z?.port??null),G=Z?.path??null;if(!Q||!(Q in Kr))return{packageManager:null,runtime:null,port:Y,packageManagerPath:G,runtimeBinPath:null};let J=Kr[Q].runtime;return{packageManager:Q,runtime:J,port:Y,packageManagerPath:G,runtimeBinPath:J==="deno"?"/opt/deno/bin":J==="bun"?"/opt/bun/bin":null}}var Wr=O(()=>{q6();d41();HY();jK()});import{sql as Tf4}from"kysely";function $28($){return $ instanceof Date?$.toISOString():String($)}class n41{db;vault;constructor($,Z){this.db=$;this.vault=Z}rowToInfo($){return{id:$.id,organizationId:$.organization_id,scope:$.scope,userId:$.user_id,name:$.name,description:$.description,createdBy:$.created_by,createdAt:$28($.created_at),updatedBy:$.updated_by,updatedAt:$28($.updated_at)}}assertVisible($,Z){if($.scope==="user"&&$.user_id!==Z)throw new _O($.id)}async create($){let Z=Z4("sec"),X=await this.vault.encrypt($.value),Q=new Date,Y=await this.db.insertInto("secrets").values({id:Z,organization_id:$.organizationId,scope:$.scope.kind,user_id:$.scope.kind==="user"?$.scope.userId:null,name:$.name,encrypted_value:X,description:$.description??null,created_by:$.createdBy,created_at:Q,updated_by:$.createdBy,updated_at:Q}).returning($j0).executeTakeFirstOrThrow();return this.rowToInfo(Y)}async update($){let Z=await this.db.selectFrom("secrets").where("id","=",$.id).where("organization_id","=",$.organizationId).select(["id","scope","user_id"]).executeTakeFirst();if(!Z)throw new M3($.id);this.assertVisible(Z,$.callerUserId);let X={updated_by:$.updatedBy,updated_at:new Date};if($.value!==void 0)X.encrypted_value=await this.vault.encrypt($.value);if($.description!==void 0)X.description=$.description;let Q=await this.db.updateTable("secrets").set(X).where("id","=",$.id).where("organization_id","=",$.organizationId).returning($j0).executeTakeFirstOrThrow();return this.rowToInfo(Q)}async delete($,Z,X){let Q=await this.db.selectFrom("secrets").where("id","=",$).where("organization_id","=",Z).select(["id","scope","user_id"]).executeTakeFirst();if(!Q)throw new M3($);this.assertVisible(Q,X),await this.db.deleteFrom("secrets").where("id","=",$).where("organization_id","=",Z).execute()}async list($){let Z=this.db.selectFrom("secrets").where("organization_id","=",$.organizationId).select($j0);if($.scope?.kind==="user")Z=Z.where("scope","=","user").where("user_id","=",$.scope.userId);else if($.scope?.kind==="organization")Z=Z.where("scope","=","organization");else Z=Z.where((Q)=>Q.or([Q("scope","=","organization"),Q.and([Q("scope","=","user"),Q("user_id","=",$.callerUserId)])]));return(await Z.orderBy("created_at","desc").execute()).map((Q)=>this.rowToInfo(Q))}async findById($,Z,X){let Q=await this.db.selectFrom("secrets").where("id","=",$).where("organization_id","=",Z).select($j0).executeTakeFirst();if(!Q)throw new M3($);return this.assertVisible(Q,X),this.rowToInfo(Q)}async resolveById($,Z,X){let Q=await this.db.selectFrom("secrets").where("id","=",$).where("organization_id","=",Z).selectAll().executeTakeFirst();if(!Q)throw new M3($);this.assertVisible(Q,X);let Y=await this.vault.decrypt(Q.encrypted_value);return{info:this.rowToInfo(Q),value:Y}}async resolveByName($){let Z=this.db.selectFrom("secrets").where("organization_id","=",$.organizationId).where("scope","=",$.scope.kind).where(Tf4`lower(name) = lower(${$.name})`).selectAll();if($.scope.kind==="user")Z=Z.where("user_id","=",$.scope.userId);let X=await Z.executeTakeFirst();if(!X)throw new M3(`${$.scope.kind}:${$.name}`);let Q=await this.vault.decrypt(X.encrypted_value);return{info:this.rowToInfo(X),value:Q}}}var $j0,M3,_O;var Hr=O(()=>{$Q();$j0=["id","organization_id","scope","user_id","name","description","created_by","created_at","updated_by","updated_at"];M3=class M3 extends Error{constructor($){super(`Secret ${$} not found`);this.name="SecretNotFoundError"}};_O=class _O extends Error{constructor($){super(`Access denied for secret ${$}`);this.name="SecretAccessDeniedError"}}});async function vO($,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 Z28(`Upstream response exceeded ${Z} bytes`);Y+=Q.decode(K,{stream:!0})}return Y+=Q.decode(),Y}var Z28;var Ur=O(()=>{Z28=class Z28 extends Error{}});async function Zj0({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 M3||H instanceof _O){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 vO(K,Rf4).catch(()=>K.statusText);console.warn(`[SANDBOX_START] daemon rejected env patch (${K.status}): ${W}`)}}var Rf4=10485760;var p41=O(()=>{Hr();Ur()});async function X28({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 M3||J instanceof _O){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 Q28=O(()=>{Hr()});async function J28($,Z,X,Q,Y){let G=await BG({connectionId:$,tokenStorage:new g$(Q,Y)});if(!G.accessToken)return null;return W28(Z,X,G.accessToken)}function K28($,Z){return W28($,Z,null)}async function W28($,Z,X){let Q=new Map,Y=new Set(Y28.map((W)=>W.path));for(let W of Object.values(G28))for(let H of W??[])Y.add(H);await Promise.all(Array.from(Y).map(async(W)=>{Q.set(W,await qf4($,Z,W,X))}));let G=Y28.find(({path:W})=>Q.get(W)!==null);if(!G)return null;let J=G28[G.pm]??[],K=null;for(let W of J)if(K=Mf4(Q.get(W)??null),K)break;return{packageManager:G.pm,devPort:K}}async function qf4($,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 Mf4($){if(!$)return null;try{let Z=JSON.parse($),X=Z.tasks??Z.scripts??{},Y=(X.dev??X.start??"").match(If4)?.[1]??null;if(!Y)return null;let G=Number(Y);return G>=1&&G<=65535?Y:null}catch{return null}}var Y28,G28,If4;var H28=O(()=>{WH();WG();Y28=[{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"}],G28={deno:["deno.json","deno.jsonc"],bun:["package.json"],pnpm:["package.json"],yarn:["package.json"],npm:["package.json"]},If4=/(?:--port|PORT=|:)(\d{4,5})/});function Vf4($){return($??"").normalize("NFKD").replace(/[\u0300-\u036F]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"user"}function Xj0($){return $?.name||$?.email?.split("@")[0]||void 0}function Qj0($){let Z=Vf4($),X=Date.now().toString(36).split("").reverse().join("");return`${Z}-${X}`}function U28($){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(kf4.has(Z))return null;if(typeof Q==="string"&&Q.length>0&&Z===Q)return null;return Z}function Yj0($){if(!$.branch.startsWith("thread:"))return $.branch;if($.sticky&&$.recordedHeadRef)return $.recordedHeadRef;return $.derivedRef}var kf4;var Gj0=O(()=>{kf4=new Set(["main","master","trunk","develop","HEAD"])});async function N28($,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=Sf4.has(Y);return{hosts:[Y],allowSameHostDev:G&&!Z.isProduction}}var Sf4;var F28=O(()=>{Sf4=new Set(["127.0.0.1","localhost","::1","[::1]","0.0.0.0"])});var k_="home";var Jj0=()=>{};function Kj0($){if(!xw($))return`Invalid volume name ${JSON.stringify($)} \u2014 use 1-128 chars of letters, digits, "_", "-" or "."`;if(Cf4.has($))return`Volume "${$}" is reserved`;if(PW($))return'Volume names starting with "public-" are reserved for shared skill sets';if($.startsWith("."))return'Volume names starting with "." are reserved';if(!/^[A-Za-z0-9]/.test($))return"Volume names must start with a letter or digit";return null}async function Wj0($,Z){try{let X=await $.storage.connections.findById(Z.connectionId,Z.organizationId);if(!X)throw Error("sync connection not found in this organization");await OO({ctx:$,connectionId:X.id,organizationId:Z.organizationId,onLegacyMintError:(J)=>console.warn("[org-repo-sync] repo-scoped mint failed",{configId:Z.id,error:J instanceof Error?J.message:String(J)})});let Q=await BG({connectionId:X.id,tokenStorage:new g$($.db,$.vault)});if(!Q.accessToken)throw Error("No GitHub token for the sync connection \u2014 reconnect the mcp-github integration.");let Y=Q.accessToken,G=await Un0($.db,{orgId:Z.organizationId,baseUrl:$.baseUrl,volume:Z.volume,source:{repo:`${Z.repoOwner}/${Z.repoName}`,ref:Z.ref,paths:Z.paths},authToken:Y,skipVolumeQuota:!1});return await $.storage.orgRepoSyncs.recordSyncResult(Z.id,{error:null}),{id:Z.id,volume:Z.volume,...G}}catch(X){let Q=X instanceof Error?X.message:String(X);return await $.storage.orgRepoSyncs.recordSyncResult(Z.id,{error:Q}).catch(()=>{}),{id:Z.id,volume:Z.volume,error:Q}}}var Cf4,t41=10;var Hj0=O(()=>{Oh();WH();WG();xb();jE();CZ0();Cf4=new Set(["home","outputs","uploads","public","output","upload"])});function xO($,Z){let X;if($==="home")X=`org/${k_}`;else if($==="outputs")X=`org/${w28}`;else if($==="uploads")X=`org/${B28}`;else if(PW($))X=`org/public/${$.slice(7)}`;else X=`org/${$}`;return Z?`${X}/${Z}`:X}function vf4($){return{baseUrl:$.baseUrl.replace(/\/+$/,""),orgSlug:$.orgSlug,token:$.token,mounts:[{volume:"home",path:k_},..._f4.map((Z)=>({...Z})),...($.publicSets??[]).map((Z)=>({volume:bw(Z),path:`public/${Z}`,readonly:!0})),...($.syncedVolumes??[]).filter((Z)=>Kj0(Z)===null).map((Z)=>({volume:Z,path:Z,readonly:!0}))]}}async function O28($,Z){try{let X=await $.boundAuth.apiKey.create({name:`orgfs-${Z.orgSlug}`,permissions:{self:["ORG_FS_READ","ORG_FS_WRITE"]},expiresIn:xf4,metadata:{organization:{id:Z.orgId,slug:Z.orgSlug}}}),Q=await $.storage.orgRepoSyncs.listEnabledVolumes(Z.orgId).catch(()=>[]);return JSON.stringify(vf4({baseUrl:Z.baseUrl,orgSlug:Z.orgSlug,token:X.key,publicSets:X3().map((Y)=>Y.set),syncedVolumes:Q}))}catch(X){console.warn("[org-fs] token mint failed; mounts disabled for this sandbox",X);return}}var w28=".outputs",B28=".uploads",_f4,xf4=604800;var Nr=O(()=>{Jj0();Hj0();jE();_f4=[{volume:"outputs",path:w28},{volume:"uploads",path:B28}]});import{z as BH}from"zod";async function vh($,Z){W0(Z);let X=Y0(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 fN(Z,$.branch,Q),K=KH(o5(G),J,$.branch,$.sandboxProviderKind),W=$.sandboxProviderKind,{provider:H}=await OQ(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 BO(Z.storage.virtualMcps,$.virtualMcpId,Q,J,$.branch,W).catch((B)=>{console.warn("[ensureSandbox] failed to reap stale user-desktop entry",B)})}let N=await CO(Z,SO($.branch)??Z.metadata?.threadId)??G.githubRepo??null,{entry:F}=await D28({ctx:Z,userId:Q,sandboxUserId:J,orgId:X.id,virtualMcpId:$.virtualMcpId,branch:$.branch,metadata:G,githubRepo:N,existing:null,providerKind:W,runner:H,...$.cloneOnly?{cloneOnly:!0}:{}});return F}async function D28($){let{ctx:Z,userId:X,sandboxUserId:Q,orgId:Y,virtualMcpId:G,branch:J,metadata:K,existing:W,runner:H,cloneOnly:U}=$,N=$.githubRepo?await bf4({ctx:Z,orgId:Y,virtualMcpId:G,userId:X,githubRepo:$.githubRepo}):null,{runtime:F,packageManager:w,port:B,packageManagerPath:L}=eR8(K),D;if(N){if(N.connectionId)await OO({ctx:Z,connectionId:N.connectionId,organizationId:Y,forceRefresh:!0,onLegacyMintError:(R0)=>{console.error("[provisionSandbox] repo-scoped legacy token mint failed",{connectionId:N.connectionId,error:R0.message})}});let{cloneUrl:F0,gitUserName:j0,gitUserEmail:Z0}=N.connectionId?await LO(N.connectionId,N.owner,N.name,Z.db,Z.vault):VD8(N.owner,N.name);if(!w){let R0=N.connectionId?await J28(N.connectionId,N.owner,N.name,Z.db,Z.vault):await K28(N.owner,N.name);if(R0)w=R0.packageManager,F=Kr[R0.packageManager].runtime,B=R0.devPort??B,await yf4(Z,G,X,R0.packageManager,R0.devPort)}let e=a0().sandboxStickyHeadRefEnabled,T0=Yj0({branch:J,derivedRef:xN(J),recordedHeadRef:e?await nR8(Z,SO(J)):null,sticky:e}),Q0=await X28({ctx:Z,orgId:Y,userId:X,entries:aR8(K)});D={cloneUrl:F0,...N.connectionId?{connectionId:N.connectionId}:{},userName:j0,userEmail:Z0,branch:T0,displayName:`${N.owner}/${N.name}`,submoduleCredentials:Q0}}let E=F&&w&&!U?{runtime:F,packageManager:w,...B!==null?{devPort:Number(B)}:{},...L?{packageManagerPath:L}:{}}:void 0,z=ko({orgId:Y,virtualMcpId:G,branch:J}),j=H.kind==="user-desktop"?await N28(Z.objectStorage,{isProduction:a0().nodeEnv==="production"}):null,A=(H.kind==="user-desktop"||H.kind==="agent-sandbox")&&!a0().orgFsMountsDisabled,P;if(A){let F0=Z.organization?.slug??(await Z.db.selectFrom("organization").select(["slug"]).where("id","=",Y).executeTakeFirst())?.slug;if(F0)P=await O28(Z,{orgSlug:F0,orgId:Y,baseUrl:xQ()})}await hf4(H);let I=await H.ensure({userId:Q,projectRef:z},{branch:J,repo:D,workload:E,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}:{}},...j?{offloadAllowedHosts:j.hosts,offloadAllowSameHostDev:j.allowSameHostDev}:{},...P?{orgFsConfigJson:P}:{}}),V=_h(K);await Zj0({ctx:Z,runner:H,handle:I.handle,orgId:Y,userId:X,entries:V});let C=!!W&&W.sandboxHandle===I.handle&&W?.createdAt?W.createdAt:Date.now(),m=K.runtime?.selected??null,f=K.runtime?.port??null,y=K.runtime?.path??null,o={sandboxHandle:I.handle,previewUrl:I.previewUrl,sandboxApiUrl:I.previewUrl,sandboxProviderKind:H.kind,createdAt:C,startedWith:{packageManager:m,port:f,path:y}};await ED8(Z.storage.virtualMcps,G,X,Q,J,$.providerKind,o);let b=SO(J)??Z.metadata?.threadId;if(b)await oR8(Z,b,Q,J,$.providerKind,o);let a=!W||W.sandboxHandle!==I.handle;return{entry:o,isNewVm:a}}async function bf4($){let{ctx:Z,orgId:X,virtualMcpId:Q,userId:Y,githubRepo:G}=$;if(!G.connectionId)return G;if(await Z.storage.connections.findById(G.connectionId,X))return G;let{items:K}=await Z.storage.connections.list(X),W=xG0(K,G.owner,G.name);if(!W)return console.warn("[provisionSandbox] recorded repo connection no longer exists and no live connection covers the repo",{virtualMcpId:Q,connectionId:G.connectionId}),G;console.warn("[provisionSandbox] healed dangling repo connection",{virtualMcpId:Q,staleConnectionId:G.connectionId,connectionId:W.id});try{let U=(await Z.storage.virtualMcps.findById(Q))?.metadata??{},N=U.githubRepo;if(N?.connectionId===G.connectionId){let F=x5(W);await Z.storage.virtualMcps.update(Q,Y,{metadata:{...U,githubRepo:{...N,connectionId:W.id,...F?{installationId:F.installationId}:{}}}})}}catch(H){console.warn("[provisionSandbox] failed to persist healed repo connection",{virtualMcpId:Q,error:H.message})}return{...G,connectionId:W.id}}async function yf4($,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 hf4($){if(!$.hasSchedulableCapacity)return;let Z=Date.now()+L28,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(L28/1000)}s`);if(!X)X=!0,console.warn("[ensureSandbox] waiting for cluster capacity \u2014 a sandbox pod cannot be scheduled right now");await T8(gf4)}}var ff4,o41,L28=150000,gf4=5000;var Fr=O(()=>{qN();a4();p0();Wr();p41();Q28();HY();oQ();Oh();H28();d41();kO();jK();Gj0();F28();k8();UZ();Nr();HY();ff4=BH.enum(["agent-sandbox","user-desktop","cluster"]),o41=t({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:ff4.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)=>{W0(Z);let X=Y0(Z);await Z.access.check();let Q=$.branch??Qj0(Xj0(Z.auth.user)),Y=z1(Z);if(!Y)throw Error("User ID required");let G=await fN(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?oz($.sandboxProviderKind):void 0,{provider:H,kind:U}=await OQ(Z,{userId:G,branch:Q,virtualMcpMetadata:K,explicitKind:W}),N=KH(o5(K),G,Q,U),w=await CO(Z,SO(Q)??Z.metadata?.threadId)??K.githubRepo??null,{entry:B,isNewVm:L}=await D28({ctx:Z,userId:Y,sandboxUserId:G,orgId:X.id,virtualMcpId:$.virtualMcpId,branch:Q,metadata:K,githubRepo:w,existing:N,providerKind:U,runner:H});return{...B,branch:Q,isNewVm:L,sandboxProviderKind:U}}})});function uf4($){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 z28(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 Uj0($,Z,X,Q,Y="agent-tools",G){let J=uf4({publicUrl:xQ(),agentId:Z,organization:X,target:Y,...G?{threadId:G}:{}}),K=await $.boundAuth.apiKey.create({name:Q,permissions:{"*":["*"]},expiresIn:E28,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()+E28*1000}}var E28=3600,z28;var r41=O(()=>{UZ();z28=class z28 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 cf4($,Z,X,Q){try{let Y=$.organization;if(!Y)return;let G=await Uj0($,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 xh($,Z){let{provider:X,kind:Q}=await OQ($,{userId:Z.userId,branch:Z.branch,virtualMcpMetadata:null}),Y=null,G=()=>{if(!Y){if(Y=vh({virtualMcpId:Z.virtualMcpId,branch:Z.branch,sandboxProviderKind:Q},$).then((W)=>W.sandboxHandle),Y.catch(()=>{Y=null}),Z.syncTools)Y.then((W)=>cf4($,X,W,{virtualMcpId:Z.virtualMcpId,providerKind:Q})).catch(()=>{})}return Y},J=Z.branch==="ephemeral"||Q==="user-desktop";return P81(X,{ensureHandle:G,invalidateHandle:async(W)=>{let H=Y;if(Y=null,!J&&!W?.force)return;try{await BO($.storage.virtualMcps,Z.virtualMcpId,Z.userId,Z.userId,Z.branch,Q)}catch(U){console.warn("[cluster-sandbox-fs] failed to reap vmMap entry",U)}if(H&&typeof X.forgetHandle==="function")try{let U=await H;await X.forgetHandle(U)}catch(U){console.warn("[cluster-sandbox-fs] forgetHandle failed",U)}},canAutoRestart:J,threadId:Z.threadId})}async function j28($,Z){try{let X=await xh($,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 Nj0=O(()=>{qN();r41();kO();Fr();HY()});import{z as P28}from"zod";function fh($){let Z=[];for(let X of $){if(X.status!=="active")continue;let Q=x5(X);if(!Q)continue;Z.push({connectionId:X.id,owner:Q.owner,repo:Q.repo,installationId:Q.installationId})}return Z}async function df4($,Z){let{items:X}=await $.storage.connections.list(Z,{slug:"mcp-github"});return fh(X)}function mf4($){let Z=$.split(`
|
|
2318
|
+
`))>=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 $R8,A41,YR8="gateway.networking.k8s.io",GR8="v1",JR8="httproutes",Bx4,Xr,WR8="mesh-sandbox-runner";var Qr=O(()=>{a4();$r();$R8=class $R8 extends Error{status;body;constructor($,Z,X){super(X);this.status=$;this.body=Z;this.name="KubeHttpError"}};A41=`/apis/${f9.CLAIM_API_GROUP}/${f9.CLAIM_API_VERSION}/namespaces`;Bx4=`/apis/${YR8}/${GR8}/namespaces`;Xr={API_GROUP:YR8,API_VERSION:GR8,PLURAL:JR8}});function Lx4($){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 NR8($,Z){let X=0,Q=!0,Y=null,G=async()=>{try{let J=await LK($,{method:"GET",path:`/api/v1/namespaces/${encodeURIComponent(Z)}/pods?fieldSelector=status.phase%3DPending`});if(!J.ok)return UR8;let K=await J.json();return!Lx4(K)}catch{return UR8}};return async()=>{if(Date.now()-X<Ox4)return Q;return Y??=G().finally(()=>{Y=null}),Q=await Y,X=Date.now(),Q}}var Ox4=3000,UR8=!0;var FR8=O(()=>{Qr()});var tz0=O(()=>{a4();E81()});async function rz0($){try{let Z=await fetch(`${$}/health`,{signal:AbortSignal.timeout(Dx4)});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 M41($){for(let Z=0;Z<wR8;Z++){if(await rz0($)!==null)return;let X=(Math.random()*2-1)*Ex4;await T8(BR8+X)}throw Error(`sandbox daemon at ${$} did not respond on /health within ${wR8*BR8/1000}s`)}async function I_($,Z,X,Q,Y){return zx4($,Z,"POST",X,Q,Y)}async function zx4($,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??q41)}),W=await K.text();if(!K.ok)throw new oz0(K.status,W);return JSON.parse(W)}async function OR8($,Z,X){let Q=await fetch(`${$}/_sandbox/setup/${X}`,{method:"POST",headers:{Authorization:`Bearer ${Z}`},signal:AbortSignal.timeout(q41)});if(!Q.ok)throw Error(`sandbox daemon /_sandbox/setup/${X} returned ${Q.status}: ${await Q.text()}`)}async function LR8($,Z,X){let Q=await fetch(`${$}/_sandbox/orgfs-config`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Z}`},body:X,signal:AbortSignal.timeout(q41)}),Y=await Q.text();if(!Q.ok)throw Error(`sandbox daemon /_sandbox/orgfs-config returned ${Q.status}: ${Y}`);return JSON.parse(Y)}async function Yr($,Z,X,Q){let Y=new Headers(Q.headers);for(let K of jx4)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 oz0,Dx4=500,q41=30000,wR8=25,BR8=200,Ex4=50,jx4;var DR8=O(()=>{tz0();oz0=class oz0 extends Error{status;constructor($,Z){super(`sandbox daemon /_sandbox/config returned ${$}: ${Z}`);this.status=$;this.name="ConfigRequestError"}};jx4=["cookie","host","connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","accept-encoding","content-length"]});async function*jR8($){let Z=$.now??(()=>Date.now()),X=Z(),Q=$.schedulingTimeoutMs??Tx4,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})},U=()=>{if(K)return;if(K=!0,J){let z=J;J=null,z(null)}},N=new AbortController,F=()=>{N.abort(),U()};if($.signal)if($.signal.aborted)N.abort(),U();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([Rx4($.kc,$.namespace,$.claimName,N.signal,Y,W,Z,L),qx4($.kc,$.namespace,$.claimName,N.signal,Y,W),Mx4($.kc,$.namespace,$.claimName,D,N.signal,Y,W,Z)]);try{let z=null,j=-1,A=ER8(Y,Q,Z);if(z=k41(A),!V41(A))j=zR8(A);if(yield A,V41(A))return;while(!K){if(await H()===null)break;let I=ER8(Y,Q,Z);if(V41(I)){let C=k41(I);if(C!==z)z=C,yield I;return}let V=zR8(I);if(V<j)continue;let M=k41(I);if(M!==z)z=M,j=V,yield I}}finally{if(clearTimeout(B),N.abort(),$.signal)$.signal.removeEventListener("abort",F);U(),await E.catch(()=>{})}}function ER8($,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 V41($){return $.kind==="ready"||$.kind==="failed"}function zR8($){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 k41($){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 Rx4($,Z,X,Q,Y,G,J,K){let W=`/api/v1/namespaces/${encodeURIComponent(Z)}/pods?watch=true&labelSelector=${encodeURIComponent(`${Px4}=${X}`)}`;return az0({kc:$,path:W,signal:Q,label:`pod/${X}`,onEvent:(H)=>{if(H.type!=="ADDED"&&H.type!=="MODIFIED")return;let U=H.object;if(U.metadata?.name)K(U.metadata.name);Ix4(U,Y,J),G("pod")}})}function Ix4($,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===Ax4);if(G)Z.pod.containerWaitingReason=G.state?.waiting?.reason,Z.pod.containerRunning=!!G.state?.running,Z.pod.containerReady=G.ready===!0}async function qx4($,Z,X,Q,Y,G){let J=`/apis/${f9.CLAIM_API_GROUP}/${f9.CLAIM_API_VERSION}/namespaces/${encodeURIComponent(Z)}/${f9.CLAIM_PLURAL}?watch=true&fieldSelector=${encodeURIComponent(`metadata.name=${X}`)}`;return az0({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((U)=>U.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 Mx4($,Z,X,Q,Y,G,J,K){let W=await Promise.race([Q,new Promise((U)=>{if(Y.aborted){U(X);return}Y.addEventListener("abort",()=>U(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 az0({kc:$,path:H,signal:Y,label:`events/${X}`,onEvent:(U)=>{if(U.type!=="ADDED"&&U.type!=="MODIFIED")return;let N=U.object,F=N.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=N.message;break;case"Nominated":{let w=N.message?.match(/nodeclaim\/([\w-]+)/);if(w)G.events.nominatedNodeClaim=w[1];break}default:return}J("event")}})}async function PR8($){let{kc:Z,namespace:X,labelSelector:Q,signal:Y,onDelete:G}=$,J=`/apis/${f9.CLAIM_API_GROUP}/${f9.CLAIM_API_VERSION}/namespaces/${encodeURIComponent(X)}/${f9.CLAIM_PLURAL}?watch=true&labelSelector=${encodeURIComponent(Q)}`;return az0({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 az0($){let{kc:Z,path:X,signal:Q,label:Y,onEvent:G}=$,J=0;while(!Q.aborted){try{let W=await LK(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 I41(W.body)){if(Q.aborted)return;try{G(H)}catch(U){console.warn(`[lifecycle-watcher] ${Y} onEvent threw: ${U instanceof Error?U.message:String(U)}`)}}}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=K7(5000,250,J,2,0);J+=1,await T8(K,{signal:Q}).catch(()=>{})}}var Px4="studio.decocms.com/sandbox-handle",Ax4="sandbox",Tx4=300000;var AR8=O(()=>{a4();$r();Qr()});import{z as q3}from"zod";function TR8($){if(!$||$.trim()==="")return[];let Z=q3.array(Vx4).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 kx4($){try{let[Z,X]=new URL($).pathname.replace(/^\/+/,"").split("/"),Q=X?.replace(/\.git$/,"");return Z&&Q?`${Z}/${Q}`.toLowerCase():null}catch{return null}}function RR8($,Z){let{orgId:X,cloneUrl:Q}=Z;if(Z.cloneOnly===!0)return null;if(!X||!Q)return null;let Y=kx4(Q);if(!Y)return null;return $.find((G)=>G.orgId===X&&G.repo.toLowerCase()===Y)??null}function IR8($,Z,X){return $?.name??(Z?X:"none")}function qR8($,Z,X){let Q=X.replace(/^refs\/heads\//,"");return $.filter((Y)=>Y.repo.toLowerCase()===Z.toLowerCase()&&Y.branch===Q)}function MR8($){return`https://github.com/${$.repo}.git`}var Vx4;var S41=O(()=>{Vx4=q3.object({name:q3.string().regex(/^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/,"pool name must be a DNS label (lowercase alphanumeric and '-')"),orgId:q3.string().min(1),repo:q3.string().regex(/^[^/\s]+\/[^/\s]+$/,"repo must be `owner/name`"),connectionId:q3.string().min(1).optional(),branch:q3.string().min(1).default("main"),workload:q3.object({runtime:q3.enum(["node","bun","deno"]).default("node"),packageManager:q3.enum(["npm","pnpm","yarn","bun","deno"]).optional(),packageManagerPath:q3.string().optional(),devPort:q3.number().int().positive().optional()}).default({runtime:"node"})})});async function VR8($,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 Sx4,randomBytes as Cx4,randomUUID as _x4}from"crypto";import*as fR8 from"net";import{PassThrough as vx4}from"stream";function kR8($){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 y41{kind=OY;records=new Map;inflight=new j30;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??nx4(),this.portForward=new Q41(this.kubeConfig),this.namespace=$.namespace??xx4,this.sandboxTemplateName=$.sandboxTemplateName??fx4,this.envName=sx4($.envName),this.tokenGenerator=$.tokenGenerator??(()=>Cx4(bx4).toString("hex")),this.idleTtlMs=$.idleTtlMs??gx4,this.metrics=$.meter?ix4($.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(`[${u$}] tenant pools configured without a sentinel token \u2014 ignoring them (warm-pool mode is off)`);this.tenantPoolRefreshMs=$.tenantPoolRefreshMs??ux4,this.startClaimReaper(),this.startCredentialRefresher(),this.startTenantPoolReconciler()}startClaimReaper(){let $=["app.kubernetes.io/managed-by=studio","app.kubernetes.io/name=studio-sandbox",...this.envName?[`${LY.env}=${this.envName}`]:[]].join(",");PR8({kc:this.kubeConfig,namespace:this.namespace,labelSelector:$,signal:this.claimWatchAbort.signal,onDelete:(Z)=>this.invalidateRecord(Z)})}async ensure($,Z={}){let X=rz($);if(X.startsWith("s-"))throw Error(`ensure: projectRef has no slug source: ${$.projectRef}`);return this.inflight.run(X,()=>P30(this.stateStore,$,OY,(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,x41(Z.tenant));if(await this.deleteHttpRouteIfManaged($).catch((X)=>{console.warn(`[${u$}] HTTPRoute delete failed for ${$}: ${X instanceof Error?X.message:String(X)}`)}),await MO(this.kubeConfig,this.namespace,$),this.stateStore)if(Z)await this.stateStore.delete(Z.id,OY);else await this.stateStore.deleteByHandle(OY,$)}async alive($){return await DK(this.kubeConfig,this.namespace,$)!==void 0}watchClaimLifecycle($,Z){return jR8({kc:this.kubeConfig,namespace:this.namespace,claimName:$,signal:Z})}hasSchedulableCapacity(){return this.capacityProbe??=NR8(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(OY,$),H=W?.state,U=H?.token;if(W&&U){let F=`http://${H?.adoptedSandboxName??$}.${this.namespace}.svc.cluster.local:${vN}`;try{let w=await Yr(F,U,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 Yr(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 Yr(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 U=await Yr(H.daemonUrl,H.token,Z,X);return J=U.status,U}finally{this.recordProxyDuration("daemon",J,Y,performance.now()-G)}}async adoptLiveClaim($,Z){if(this.records.has(Z))return!0;let X=await DK(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 P30(this.stateStore,$,OY,(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:${vN}`;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(OY,$).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=_41(404,{error:"sandbox not found"});return B.headers.set(M_,"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,_41(404,{error:"not found"});let W=(B)=>`${B}${J.pathname}${J.search}`,H=new Headers(Z.headers);for(let B of dx4)H.delete(B);let U=Z.method!=="GET"&&Z.method!=="HEAD",N={method:Z.method,headers:H,body:U?Z.body:void 0,redirect:"manual",signal:Z.signal,duplex:U?"half":void 0},F;try{F=await fetch(W(G),N)}catch(B){let L=`${G}${J.pathname}`;if(console.warn(`[${u$}] 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),N);let j=new Headers;for(let[A,P]of F.headers.entries())if(!_R8.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(`[${u$}] preview fetch retry to ${L} failed: ${j instanceof Error?j.message:String(j)}`)}}}else this.invalidateRecord($);Y=502;let D=_41(502,{error:"sandbox daemon unreachable"});return D.headers.set(M_,"1"),D}let w=new Headers;for(let[B,L]of F.headers.entries())if(!_R8.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(`[${u$}] opts.image ignored (template ${this.sandboxTemplateName} pins image): got ${X.image}`);if(Q){let J=await Q.get($,OY);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($,OY)}}let Y=await DK(this.kubeConfig,this.namespace,Z).catch(()=>{return});if(Y)if(Y.metadata?.deletionTimestamp)await dz0(this.kubeConfig,this.namespace,Z).catch((J)=>{console.warn(`[${u$}] 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(`[${u$}] 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 MO(this.kubeConfig,this.namespace,Z).catch(()=>{}),await dz0(this.kubeConfig,this.namespace,Z).catch((K)=>{console.warn(`[${u$}] 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 mz0(this.kubeConfig,this.namespace,$.handle,this.computeShutdownTime()).catch((K)=>console.warn(`[${u$}] TTL refresh failed for ${$.handle}: ${K instanceof Error?K.message:String(K)}`));if(this.metrics){let K=x41($.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(yx4.has(Y))Q.push(Y);else X[Y]=G;if(Q.length>0)console.warn(`[${u$}] 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(vN)}}buildClaim($,Z,X){let Q=this.sentinelToken!==null,Y=RR8(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=Zf4(Z),K=Object.keys(J).length>0;return{apiVersion:`${f9.CLAIM_API_GROUP}/${f9.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?{[LY.env]:this.envName}:{},...v41(Z.tenant)},...K?{annotations:J}:{}},spec:{sandboxTemplateRef:{name:this.sandboxTemplateName},additionalPodMetadata:{labels:v41(Z.tenant,{[LY.role]:"claimed",[LY.sandboxHandle]:$,...this.envName?{[LY.env]:this.envName}:{}}),...K?{annotations:J}:{}},env:G,warmpool:IR8(Y,Q,this.sandboxTemplateName),lifecycle:{shutdownPolicy:"Delete",shutdownTime:this.computeShutdownTime()}}}}async provision($,Z,X){let Q=this.tokenGenerator(),Y=_x4(),G=C41,J=this.buildClaim(Z,X,{token:Q,daemonBootId:Y,workdir:G});try{await Zr(this.kubeConfig,this.namespace,J)}catch(F){if(F instanceof eo)await dz0(this.kubeConfig,this.namespace,Z),await Zr(this.kubeConfig,this.namespace,J);else throw F}let K;try{K=await ZR8(this.kubeConfig,this.namespace,Z),await pz0(this.kubeConfig,this.namespace,K)}catch(F){throw await MO(this.kubeConfig,this.namespace,Z).catch(()=>{}),F}try{await this.ensureServicePortForAdoptedSandbox(K),await this.ensureHttpRouteForHandle(Z,K,X.tenant??null)}catch(F){throw await MO(this.kubeConfig,this.namespace,Z).catch(()=>{}),F}let W=await this.openForwarder(K,vN,Z),H=`http://127.0.0.1:${W.localPort}`,U=this.workloadConfigPayload(X),N=Y;try{if(await M41(H),this.sentinelToken!==null){let F=await rz0(H);if(F)N=F.bootId;await I_(H,this.sentinelToken,U??{},{rotateToken:Q})}else if(U)await I_(H,Q,U);await this.relayOrgFsConfig(H,Q,X.orgFsConfigJson)}catch(F){throw this.closeForwarder(W),await this.deleteHttpRouteIfManaged(Z).catch(()=>{}),await MO(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:N,tenant:X.tenant??null,ensureOpts:Gf4(X)}}workloadConfigPayload($){return T30({runtime:$?.workload?.runtime??"node",packageManager:$?.workload?.packageManager?{name:$.workload.packageManager,...$.workload.packageManagerPath?{path:$.workload.packageManagerPath}:{}}:null,repo:$?.repo??null,port:$?.workload?.devPort??SR8,tenant:$?.tenant??void 0,...$?{cloneOnly:$.cloneOnly===!0}:{}})}async relayOrgFsConfig($,Z,X){if(!X)return;await LR8($,Z,X).catch((Q)=>console.warn("[org-fs] sidecar config relay failed",Q))}async refreshDaemonGitCredential($,Z){let X=z81(Z);if(!X)return;try{await I_($.daemonUrl,$.token,X)}catch(Q){console.warn(`[${u$}] 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(`[${u$}] 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 T8(cx4,{signal:$}).catch(()=>{}),$.aborted)break;try{await this.refreshAllGitCredentials()}catch(Z){console.warn(`[${u$}] 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(`[${u$}] tenant pool reconcile failed: ${Z instanceof Error?Z.message:String(Z)}`)}await T8(hx4,{signal:$}).catch(()=>{})}})()}markTenantPoolsDirty($,Z){let X=qR8(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 XR8(this.kubeConfig,this.namespace,$.name);if(Z===null){console.warn(`[${u$}] 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[LY.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>=sz0)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>=sz0){if(Date.now()-Q.lastFailureAt<CR8)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:MR8($),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,vN,Z.name).catch(()=>null);if(!K){this.recordPoolFailure(Z,$,"port-forward failed");return}let W=`http://127.0.0.1:${K.localPort}`;try{await M41(W);let H=this.sentinelToken;if(!H)return;if(!await this.isPoolPodUnbound(Z))return;let U=T30({runtime:$.workload.runtime,packageManager:$.workload.packageManager?{name:$.workload.packageManager,...$.workload.packageManagerPath?{path:$.workload.packageManagerPath}:{}}:null,repo:J,port:$.workload.devPort??SR8})??{},{transition:N}=await I_(W,H,U);if(Y&&N!=="bootstrap"&&await this.isPoolPodUnbound(Z))await OR8(W,H,"clone");this.poolPods.set(Z.uid,{lastConfigAt:Date.now(),lastFailureAt:0,failures:0}),console.log(`[${u$}] tenant pool ${$.name}: warmed ${Z.name} (${N})`)}catch(H){this.recordPoolFailure(Z,$,H instanceof Error?H.message:String(H))}finally{this.closeForwarder(K)}}isPoolPodUnbound($){return QR8(this.kubeConfig,this.namespace,$.name,LY.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>=sz0?` \u2014 backing off ${CR8/60000}min`:"";console.warn(`[${u$}] tenant pool ${Z.name}: warming ${$.name} failed (${Y}/${sz0})${G}: ${X}`)}async refreshAllGitCredentials(){await VR8(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,lx4);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 I_($,this.sentinelToken,Q,{rotateToken:Z}),await this.relayOrgFsConfig($,Z,X?.orgFsConfigJson),!0}catch(Y){if(Y instanceof oz0&&Y.status===401)try{return await I_($,Z,Q,{rotateToken:Z}),await this.relayOrgFsConfig($,Z,X?.orgFsConfigJson),!0}catch(G){return console.warn(`[${u$}] re-bootstrap retry with claim token failed: ${G instanceof Error?G.message:String(G)}`),!1}return console.warn(`[${u$}] re-bootstrap failed: ${Y instanceof Error?Y.message:String(Y)}`),!1}}async ensureServicePortForAdoptedSandbox($){if(!this.previewGateway||!this.previewUrlPattern)return;await HR8(this.kubeConfig,this.namespace,$,{name:"daemon",port:vN,targetPort:vN})}async ensureHttpRouteForHandle($,Z,X){if(!this.previewGateway||!this.previewUrlPattern)return;let Q=Jf4(this.previewUrlPattern,$);if(!Q)throw new a9(`Unable to derive preview hostname for ${$} from pattern: ${this.previewUrlPattern}`);let Y={apiVersion:`${Xr.API_GROUP}/${Xr.API_VERSION}`,kind:"HTTPRoute",metadata:{name:$,namespace:this.namespace,labels:v41(X??void 0,{[LY.role]:"claimed",[LY.sandboxHandle]:$,"app.kubernetes.io/name":"studio-sandbox","app.kubernetes.io/managed-by":"studio",...this.envName?{[LY.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:vN}]}]}};await iz0(this.kubeConfig,this.namespace,Y)}async deleteHttpRouteIfManaged($){if(!this.previewGateway)return;await nz0(this.kubeConfig,this.namespace,$)}async rehydrate($,Z,X){let Q=X.state;if(!Q.adoptedSandboxName&&!Q.podName||!Q.token)return null;let Y=await DK(this.kubeConfig,this.namespace,Z).catch(()=>{return});if(!Y||!vR8(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(`[${u$}] daemon restart detected (handle=${Z}): stored bootId=${Q.daemonBootId} live bootId=${J.bootId}`);await this.stateStore?.put($,OY,{handle:Z,state:{...Q,daemonBootId:J.bootId}}).catch((K)=>console.warn(`[${u$}] bootId persist failed for ${Z}: ${K instanceof Error?K.message:String(K)}`))}return{id:$,handle:Z,adoptedSandboxName:G,token:Q.token,workdir:Q.workdir??C41,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(!vR8(X))return null;let Q=X.status?.sandbox?.name??Z;if(this.sentinelToken!==null)return null;let Y=px4(X);if(!Y)return null;let G=await this.openAndProbeDaemon(Q,Z);if(!G)return null;let J=Xf4(X);if(this.previewGateway)await this.ensureServicePortForAdoptedSandbox(Q).catch((K)=>{console.warn(`[${u$}] Service port backfill failed for ${Z}: ${K instanceof Error?K.message:String(K)}`)}),await this.ensureHttpRouteForHandle(Z,Q,J).catch((K)=>{console.warn(`[${u$}] HTTPRoute backfill failed for ${Z}: ${K instanceof Error?K.message:String(K)}`)});return{id:$,handle:Z,adoptedSandboxName:Q,token:Y,workdir:C41,daemonUrl:G.daemonUrl,daemonForward:G.daemonForward,workload:null,daemonBootId:G.bootId,tenant:J,ensureOpts:null}}async openAndProbeDaemon($,Z){let X=await this.openForwarder($,vN,Z).catch(()=>null);if(!X)return null;let Q=`http://127.0.0.1:${X.localPort}`,Y=await rz0(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(OY,$);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(OY,$);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(rz(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,{...x41(X?.tenant??null),source:$,sandbox_handle:X?.handle??Y??"",status_code:Z||0})}composePreviewUrl($){if(this.previewUrlPattern)return A30(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,OY,{handle:Z.handle,state:X})}computeShutdownTime(){return new Date(Date.now()+this.idleTtlMs).toISOString()}async releaseAfter($,Z){let X=await DK(this.kubeConfig,this.namespace,$);if(!X)return;let Q=Qf4(X.spec?.lifecycle?.shutdownTime,new Date(Date.now()+Z));if(!Q)return;await mz0(this.kubeConfig,this.namespace,$,Q).catch((Y)=>console.warn(`[${u$}] release failed for ${$}: ${Y instanceof Error?Y.message:String(Y)}`))}async renewTtl($){let Z=await DK(this.kubeConfig,this.namespace,$);if(!Z)return;let X=Yf4(Z.spec?.lifecycle?.shutdownTime,new Date(Date.now()+this.idleTtlMs));if(!X)return;await mz0(this.kubeConfig,this.namespace,$,X).catch((Q)=>console.warn(`[${u$}] TTL renew failed for ${$}: ${Q instanceof Error?Q.message:String(Q)}`))}openForwarder($,Z,X=$){let Q=tx4(X,Z);return new Promise((Y,G)=>{let J=(K,W)=>{let H=fR8.createServer((U)=>this.handleForwardedConnection(U,$,Z,X));H.once("error",(U)=>{if(U.code==="EADDRINUSE"&&W<mx4){try{H.close()}catch{}let N=f41+(K-f41+1)%bR8;J(N,W+1);return}G(U)}),H.listen(K,"127.0.0.1",()=>{let U=H.address();if(!U||typeof U==="string"){H.close(),G(Error("port-forward listener failed to bind"));return}Y({server:H,localPort:U.port})})};J(Q,0)})}handleForwardedConnection($,Z,X,Q){let Y=new vx4,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",(U)=>{console.warn(`[${u$}] port-forward to ${Z}:${X} dropped mid-connection: ${kR8(U)}`,JSON.stringify(b41(U))),this.invalidateRecord(Q),K()}),J)try{G.close()}catch{}}).catch((W)=>{console.warn(`[${u$}] port-forward to ${Z}:${X} failed: ${kR8(W)}`,JSON.stringify(b41(W))),this.invalidateRecord(Q),K()})}closeForwarder($){$.server.close((Z)=>{if(Z)console.warn(`[${u$}] 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 ix4($){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 b41($){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?b41(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 nx4(){let $=new qh;return $.loadFromDefault(),$}function vR8($){return Boolean($.status?.conditions?.some((Z)=>Z.type==="Ready"&&Z.status==="True"))}function px4($){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 tx4($,Z){let X=Sx4("sha256").update(`${$}:${Z}`).digest();return f41+X.readUInt32BE(0)%bR8}function _41($,Z){return new Response(JSON.stringify(Z),{status:$,headers:{"content-type":"application/json","access-control-allow-origin":"*"}})}function xR8($){let Z=$.slice(0,rx4);return ox4.test(Z)?Z:""}function sx4($){if($===void 0)return null;let Z=$.trim();if(Z==="")return null;if(!ax4.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 v41($,Z={}){let X={...Z};if($){let Q=xR8($.orgId),Y=xR8($.userId);if(Q)X[LY.orgId]=Q;if(Y)X[LY.userId]=Y}return X}function q_($){let Z="";for(let X of $){let Q=X.codePointAt(0)??0;Z+=Q<32||Q===127?" ":X}return Z.slice(0,ex4)}function $f4($){try{let Z=new URL($);return Z.username="",Z.password="",Z.toString()}catch{return""}}function Zf4($){let Z={},X=$.tenant;if(X?.orgSlug)Z[EK.orgSlug]=q_(X.orgSlug);if(X?.orgName)Z[EK.orgName]=q_(X.orgName);if(X?.userEmail)Z[EK.userEmail]=q_(X.userEmail);if(X?.userName)Z[EK.userName]=q_(X.userName);let Q=$.repo;if(Q){if(Q.displayName)Z[EK.gitRepo]=q_(Q.displayName);let Y=$f4(Q.cloneUrl);if(Y)Z[EK.gitRepoUrl]=q_(Y);let G=$.branch??Q.branch;if(G)Z[EK.gitBranch]=q_(G)}return Z}function Xf4($){let Z=$.metadata?.labels;if(!Z)return null;let X=Z[LY.orgId],Q=Z[LY.userId];if(!X||!Q)return null;let Y=$.metadata?.annotations??{};return{orgId:X,userId:Q,orgSlug:Y[EK.orgSlug],orgName:Y[EK.orgName],userEmail:Y[EK.userEmail],userName:Y[EK.userName]}}function Qf4($,Z){if($){let X=new Date($).getTime();if(Number.isFinite(X)&&X<=Z.getTime())return null}return Z.toISOString()}function Yf4($,Z){if($){let X=new Date($).getTime();if(Number.isFinite(X)&&X>=Z.getTime())return null}return Z.toISOString()}function x41($){return{org_id:$?.orgId??"",user_id:$?.userId??"",runner_kind:OY}}function Gf4($){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($.cloneOnly)Z.cloneOnly=!0;if($.orgFsConfigJson)Z.orgFsConfigJson=$.orgFsConfigJson;return Object.keys(Z).length>0?Z:null}function Jf4($,Z){try{return new URL(A30($,Z)).hostname||null}catch{return null}}var OY="agent-sandbox",u$="AgentSandboxProvider",M_="x-sandbox-preview-not-ready",xx4="agent-sandbox-system",fx4="studio-sandbox",vN=9000,SR8=3000,C41="/app",bx4=32,yx4,gx4=900000,hx4=60000,ux4=1800000,sz0=3,CR8=1800000,cx4=900000,lx4=1800000,dx4,_R8,f41=40000,bR8=1e4,mx4=256,LY,EK,ox4,rx4=63,ax4,ex4=253;var yR8=O(()=>{a4();FR8();z41();DR8();j81();Qr();$r();AR8();S41();yx4=new Set(["DAEMON_TOKEN","DAEMON_BOOT_ID","APP_ROOT","PROXY_PORT"]),dx4=["cookie","host","connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","accept-encoding","content-length","upgrade"],_R8=["connection","keep-alive","transfer-encoding","content-encoding","content-length"];LY={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"},EK={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"},ox4=/^([A-Za-z0-9]([-A-Za-z0-9_.]*[A-Za-z0-9])?)?$/;ax4=/^[a-z]([a-z0-9-]{0,30}[a-z0-9])?$/});var gR8={};B0(gR8,{waitForSandboxReady:()=>pz0,parseTenantPools:()=>TR8,getSandboxClaim:()=>DK,getHttpRoute:()=>KR8,deleteSandboxClaim:()=>MO,deleteHttpRoute:()=>nz0,createSandboxClaim:()=>Zr,applyHttpRoute:()=>iz0,SandboxTimeoutError:()=>R_,SandboxError:()=>a9,PREVIEW_NOT_READY_HEADER:()=>M_,KubeConfig:()=>qh,K8S_CONSTANTS:()=>f9,HTTPROUTE_CONSTANTS:()=>Xr,AgentSandboxProvider:()=>y41});var g41=O(()=>{z41();$r();Qr();yR8();S41()});var mR8={};B0(mR8,{subscribeLifecycle:()=>l41,getSandboxProviderByKind:()=>u41,getOrInitSharedRunner:()=>c41,__resetSharedLifecyclesForTesting:()=>Ef4});function lR8($,Z){let X=hR8[$];if(X)return Promise.resolve(X);let Q=h41[$];if(Q)return Q;let Y=Z().then((G)=>{return hR8[$]=G,G}).finally(()=>{delete h41[$]});return h41[$]=Y,Y}function Hf4(){let $=process.env.STUDIO_SANDBOX_PREVIEW_URL_PATTERN;return $&&$.trim()!==""?$:void 0}function Uf4(){let $=process.env.STUDIO_SANDBOX_TEMPLATE_NAME;return $&&$.trim()!==""?$:void 0}function Nf4(){let $=process.env.STUDIO_ENV;return $&&$.trim()!==""?$:void 0}function Ff4(){let $=process.env.STUDIO_SANDBOX_SENTINEL_TOKEN;return $&&$.trim()!==""?$:void 0}function wf4(){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 dR8($,Z){let X=new _o(Z),Q=Hf4();switch($){case"agent-sandbox":{let{AgentSandboxProvider:Y,parseTenantPools:G}=await Promise.resolve().then(() => (g41(),gR8)),J=new iU(a0().encryptionKey);return new Y({stateStore:X,previewUrlPattern:Q,sandboxTemplateName:Uf4(),envName:Nf4(),previewGateway:wf4(),sentinelToken:Ff4(),tenantPools:G(process.env.STUDIO_SANDBOX_TENANT_POOLS),meter:y8,mintCloneUrl:async(K,W)=>{if(!K.connectionId)return null;let H=kD8(K.cloneUrl);if(!H)return null;let{cloneUrl:U}=await LO(K.connectionId,H.owner,H.name,Z,J,{bufferMs:W?.bufferMs});return U}})}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 u41($,Z){return lR8(Z,()=>dR8(Z,$.db))}async function c41(){let $;try{$=az()}catch(X){return console.warn("[lifecycle] cannot resolve sandbox runner:",X instanceof Error?X.message:String(X)),null}return await lR8($,()=>dR8($,N6().db))}function l41($,Z,X){let Q=VO.get(Z);if(Q){if(Q.terminated){if(Q.lastPhase)try{X(Q.lastPhase)}catch{}return{unsubscribe:Lf4}}if(Q.listeners.add(X),Q.lastPhase)try{X(Q.lastPhase)}catch{}return uR8(Z,Q,X)}let Y=new AbortController,G={lastPhase:null,terminated:!1,listeners:new Set([X]),abort:Y};return VO.set(Z,G),Df4($,Z,G),uR8(Z,G,X)}function Lf4(){}function uR8($,Z,X){return{unsubscribe(){if(VO.get($)!==Z)return;if(Z.listeners.delete(X),Z.listeners.size===0)VO.delete($),Z.abort.abort()}}}async function Df4($,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(VO.get(Z)===X)VO.delete(Z)}}function Ef4(){for(let $ of VO.values())$.abort.abort();VO.clear()}var Kf4,Wf4,cR8,hR8,h41,Bf4,Of4,VO;var Gr=O(()=>{qN();$X();t$();T81();Oh();xi();k8();Kf4=Symbol.for("decocms.sandbox.lifecycle.runners"),Wf4=Symbol.for("decocms.sandbox.lifecycle.inflight"),cR8=globalThis,hR8=cR8[Kf4]??={},h41=cR8[Wf4]??={};Bf4=Symbol.for("decocms.sandbox.lifecycle.shared-lifecycles"),Of4=globalThis,VO=Of4[Bf4]??=new Map});async function OQ($,Z){let{userId:X,branch:Q,virtualMcpMetadata:Y,explicitKind:G}=Z;if(G)return Jr($,G);if($.sandboxPreference==="agent-sandbox")return Jr($,"agent-sandbox");if($.sandboxPreference==="cluster-default")return Jr($,az());let[J,...K]=zf4(Y,X,Q);if(J)return Jr($,K.length===0?J:jf4(J,K));return Jr($,iR8())}function zf4($,Z,X){let Q=o5($)[Z]?.[X];if(!Q)return[];let Y=xJ(Q);return Object.keys(Y)}function jf4($,Z){let X=iR8();if(X===$||Z.includes(X))return X;return $}function iR8(){return az()}async function Jr($,Z){let X=Z==="user-desktop"?"agent-sandbox":Z;return{provider:await u41($,X),kind:X}}var kO=O(()=>{q6();qN();HY();Gr()});var Kr;var d41=O(()=>{Kr={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 zK($,Z){return Z?`thread:${$}/${Z}`:`thread:${$}`}function xN($){return`sandbox/thread-${$.replace(/^thread:/,"").replace(/\//g,"-")}`}function SO($){if(!$||!$.startsWith("thread:"))return null;return $.slice(7).split("/")[0]||null}async function fN($,Z,X){let Q=SO(Z);if(!Q)return X;return(await $.storage.threads.get(Q).catch(()=>null))?.created_by??X}async function V_($,Z){if(!Z)return null;let X=await $.storage.threads.get(Z).catch(()=>null);if(!X)return null;return X.metadata??{}}async function nR8($,Z){let Q=(await V_($,Z))?.headRef;return typeof Q==="string"&&Q.length>0?Q:null}async function pR8($,Z,X){let Q=await V_($,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))}function Pf4($,Z){let X=xG0(Z,$.owner,$.name);if(!X||X.id===$.connectionId)return null;let Q=x5(X);return{...$,connectionId:X.id,...Q?.installationId?{installationId:Q.installationId}:{}}}async function CO($,Z){let X=await V_($,Z),Q=X?.githubRepo??null;if(!Z||!X||!Q?.connectionId)return Q;try{let Y=$.storage.threads.getOrganizationId();if(!Y)return Q;if(await $.storage.connections.findById(Q.connectionId,Y))return Q;let{items:G}=await $.storage.connections.list(Y),J=Pf4(Q,G);if(!J)return Q;return await $.storage.threads.update(Z,{metadata:{...X,githubRepo:J}}),console.warn("[thread-repo] re-pointed thread at a live repo connection",{threadId:Z,from:Q.connectionId,to:J.connectionId}),J}catch(Y){return console.warn("[thread-repo] repoint check failed",Y),Q}}function m41($){if($.pinnedRef)return $.pinnedRef;if($.runBranch&&$.runBranch===zK($.threadId))return $.runBranch;if($.threadRepo)return zK($.threadId,$.threadRepo.connectionId);if(!$.agentRepo)return"ephemeral";return $.runBranch??`thread:${$.threadId}`}async function i41($,Z){let Q=(await V_($,Z))?.pinnedRef;return typeof Q==="string"&&Q.length>0?Q:null}async function tR8($,Z){let[X,Q]=await Promise.all([CO($,Z.threadId),i41($,Z.threadId)]);return m41({...Z,threadRepo:X,pinnedRef:Q})}async function oR8($,Z,X,Q,Y,G){let J=await V_($,Z);if(!J)return;let K=Co(o5(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 ez0($,Z){return o5(await V_($,Z))}async function rR8($,Z,X,Q,Y){let G=await V_($,Z);if(!G)return;let J=A81(o5(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 jK=O(()=>{oQ();HY()});function _h($){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"||!aZ0.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 aR8($){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}async function sR8($,Z){W0(Z);let X=Y0(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=o5(G),K=await fN(Z,$.branch,Q),W=KH(J,K,$.branch,$.sandboxProviderKind);return{virtualMcp:Y,metadata:G,userId:Q,sandboxUserId:K,entry:W,organization:X}}function Af4($){if($===null||!/^\d+$/.test($))return null;let Z=Number($);return Z>=1&&Z<=65535?$:null}function eR8($){let Z=$.runtime??null,Q=Z?.selected??null,Y=Af4(Z?.port??null),G=Z?.path??null;if(!Q||!(Q in Kr))return{packageManager:null,runtime:null,port:Y,packageManagerPath:G,runtimeBinPath:null};let J=Kr[Q].runtime;return{packageManager:Q,runtime:J,port:Y,packageManagerPath:G,runtimeBinPath:J==="deno"?"/opt/deno/bin":J==="bun"?"/opt/bun/bin":null}}var Wr=O(()=>{q6();d41();HY();jK()});import{sql as Tf4}from"kysely";function $28($){return $ instanceof Date?$.toISOString():String($)}class n41{db;vault;constructor($,Z){this.db=$;this.vault=Z}rowToInfo($){return{id:$.id,organizationId:$.organization_id,scope:$.scope,userId:$.user_id,name:$.name,description:$.description,createdBy:$.created_by,createdAt:$28($.created_at),updatedBy:$.updated_by,updatedAt:$28($.updated_at)}}assertVisible($,Z){if($.scope==="user"&&$.user_id!==Z)throw new _O($.id)}async create($){let Z=Z4("sec"),X=await this.vault.encrypt($.value),Q=new Date,Y=await this.db.insertInto("secrets").values({id:Z,organization_id:$.organizationId,scope:$.scope.kind,user_id:$.scope.kind==="user"?$.scope.userId:null,name:$.name,encrypted_value:X,description:$.description??null,created_by:$.createdBy,created_at:Q,updated_by:$.createdBy,updated_at:Q}).returning($j0).executeTakeFirstOrThrow();return this.rowToInfo(Y)}async update($){let Z=await this.db.selectFrom("secrets").where("id","=",$.id).where("organization_id","=",$.organizationId).select(["id","scope","user_id"]).executeTakeFirst();if(!Z)throw new M3($.id);this.assertVisible(Z,$.callerUserId);let X={updated_by:$.updatedBy,updated_at:new Date};if($.value!==void 0)X.encrypted_value=await this.vault.encrypt($.value);if($.description!==void 0)X.description=$.description;let Q=await this.db.updateTable("secrets").set(X).where("id","=",$.id).where("organization_id","=",$.organizationId).returning($j0).executeTakeFirstOrThrow();return this.rowToInfo(Q)}async delete($,Z,X){let Q=await this.db.selectFrom("secrets").where("id","=",$).where("organization_id","=",Z).select(["id","scope","user_id"]).executeTakeFirst();if(!Q)throw new M3($);this.assertVisible(Q,X),await this.db.deleteFrom("secrets").where("id","=",$).where("organization_id","=",Z).execute()}async list($){let Z=this.db.selectFrom("secrets").where("organization_id","=",$.organizationId).select($j0);if($.scope?.kind==="user")Z=Z.where("scope","=","user").where("user_id","=",$.scope.userId);else if($.scope?.kind==="organization")Z=Z.where("scope","=","organization");else Z=Z.where((Q)=>Q.or([Q("scope","=","organization"),Q.and([Q("scope","=","user"),Q("user_id","=",$.callerUserId)])]));return(await Z.orderBy("created_at","desc").execute()).map((Q)=>this.rowToInfo(Q))}async findById($,Z,X){let Q=await this.db.selectFrom("secrets").where("id","=",$).where("organization_id","=",Z).select($j0).executeTakeFirst();if(!Q)throw new M3($);return this.assertVisible(Q,X),this.rowToInfo(Q)}async resolveById($,Z,X){let Q=await this.db.selectFrom("secrets").where("id","=",$).where("organization_id","=",Z).selectAll().executeTakeFirst();if(!Q)throw new M3($);this.assertVisible(Q,X);let Y=await this.vault.decrypt(Q.encrypted_value);return{info:this.rowToInfo(Q),value:Y}}async resolveByName($){let Z=this.db.selectFrom("secrets").where("organization_id","=",$.organizationId).where("scope","=",$.scope.kind).where(Tf4`lower(name) = lower(${$.name})`).selectAll();if($.scope.kind==="user")Z=Z.where("user_id","=",$.scope.userId);let X=await Z.executeTakeFirst();if(!X)throw new M3(`${$.scope.kind}:${$.name}`);let Q=await this.vault.decrypt(X.encrypted_value);return{info:this.rowToInfo(X),value:Q}}}var $j0,M3,_O;var Hr=O(()=>{$Q();$j0=["id","organization_id","scope","user_id","name","description","created_by","created_at","updated_by","updated_at"];M3=class M3 extends Error{constructor($){super(`Secret ${$} not found`);this.name="SecretNotFoundError"}};_O=class _O extends Error{constructor($){super(`Access denied for secret ${$}`);this.name="SecretAccessDeniedError"}}});async function vO($,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 Z28(`Upstream response exceeded ${Z} bytes`);Y+=Q.decode(K,{stream:!0})}return Y+=Q.decode(),Y}var Z28;var Ur=O(()=>{Z28=class Z28 extends Error{}});async function Zj0({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 M3||H instanceof _O){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 vO(K,Rf4).catch(()=>K.statusText);console.warn(`[SANDBOX_START] daemon rejected env patch (${K.status}): ${W}`)}}var Rf4=10485760;var p41=O(()=>{Hr();Ur()});async function X28({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 M3||J instanceof _O){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 Q28=O(()=>{Hr()});async function J28($,Z,X,Q,Y){let G=await BG({connectionId:$,tokenStorage:new g$(Q,Y)});if(!G.accessToken)return null;return W28(Z,X,G.accessToken)}function K28($,Z){return W28($,Z,null)}async function W28($,Z,X){let Q=new Map,Y=new Set(Y28.map((W)=>W.path));for(let W of Object.values(G28))for(let H of W??[])Y.add(H);await Promise.all(Array.from(Y).map(async(W)=>{Q.set(W,await qf4($,Z,W,X))}));let G=Y28.find(({path:W})=>Q.get(W)!==null);if(!G)return null;let J=G28[G.pm]??[],K=null;for(let W of J)if(K=Mf4(Q.get(W)??null),K)break;return{packageManager:G.pm,devPort:K}}async function qf4($,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 Mf4($){if(!$)return null;try{let Z=JSON.parse($),X=Z.tasks??Z.scripts??{},Y=(X.dev??X.start??"").match(If4)?.[1]??null;if(!Y)return null;let G=Number(Y);return G>=1&&G<=65535?Y:null}catch{return null}}var Y28,G28,If4;var H28=O(()=>{WH();WG();Y28=[{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"}],G28={deno:["deno.json","deno.jsonc"],bun:["package.json"],pnpm:["package.json"],yarn:["package.json"],npm:["package.json"]},If4=/(?:--port|PORT=|:)(\d{4,5})/});function Vf4($){return($??"").normalize("NFKD").replace(/[\u0300-\u036F]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"user"}function Xj0($){return $?.name||$?.email?.split("@")[0]||void 0}function Qj0($){let Z=Vf4($),X=Date.now().toString(36).split("").reverse().join("");return`${Z}-${X}`}function U28($){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(kf4.has(Z))return null;if(typeof Q==="string"&&Q.length>0&&Z===Q)return null;return Z}function Yj0($){if(!$.branch.startsWith("thread:"))return $.branch;if($.sticky&&$.recordedHeadRef)return $.recordedHeadRef;return $.derivedRef}var kf4;var Gj0=O(()=>{kf4=new Set(["main","master","trunk","develop","HEAD"])});async function N28($,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=Sf4.has(Y);return{hosts:[Y],allowSameHostDev:G&&!Z.isProduction}}var Sf4;var F28=O(()=>{Sf4=new Set(["127.0.0.1","localhost","::1","[::1]","0.0.0.0"])});var k_="home";var Jj0=()=>{};function Kj0($){if(!xw($))return`Invalid volume name ${JSON.stringify($)} \u2014 use 1-128 chars of letters, digits, "_", "-" or "."`;if(Cf4.has($))return`Volume "${$}" is reserved`;if(PW($))return'Volume names starting with "public-" are reserved for shared skill sets';if($.startsWith("."))return'Volume names starting with "." are reserved';if(!/^[A-Za-z0-9]/.test($))return"Volume names must start with a letter or digit";return null}async function Wj0($,Z){try{let X=await $.storage.connections.findById(Z.connectionId,Z.organizationId);if(!X)throw Error("sync connection not found in this organization");await OO({ctx:$,connectionId:X.id,organizationId:Z.organizationId,onLegacyMintError:(J)=>console.warn("[org-repo-sync] repo-scoped mint failed",{configId:Z.id,error:J instanceof Error?J.message:String(J)})});let Q=await BG({connectionId:X.id,tokenStorage:new g$($.db,$.vault)});if(!Q.accessToken)throw Error("No GitHub token for the sync connection \u2014 reconnect the mcp-github integration.");let Y=Q.accessToken,G=await Un0($.db,{orgId:Z.organizationId,baseUrl:$.baseUrl,volume:Z.volume,source:{repo:`${Z.repoOwner}/${Z.repoName}`,ref:Z.ref,paths:Z.paths},authToken:Y,skipVolumeQuota:!1});return await $.storage.orgRepoSyncs.recordSyncResult(Z.id,{error:null}),{id:Z.id,volume:Z.volume,...G}}catch(X){let Q=X instanceof Error?X.message:String(X);return await $.storage.orgRepoSyncs.recordSyncResult(Z.id,{error:Q}).catch(()=>{}),{id:Z.id,volume:Z.volume,error:Q}}}var Cf4,t41=10;var Hj0=O(()=>{Oh();WH();WG();xb();jE();CZ0();Cf4=new Set(["home","outputs","uploads","public","output","upload"])});function xO($,Z){let X;if($==="home")X=`org/${k_}`;else if($==="outputs")X=`org/${w28}`;else if($==="uploads")X=`org/${B28}`;else if(PW($))X=`org/public/${$.slice(7)}`;else X=`org/${$}`;return Z?`${X}/${Z}`:X}function vf4($){return{baseUrl:$.baseUrl.replace(/\/+$/,""),orgSlug:$.orgSlug,token:$.token,mounts:[{volume:"home",path:k_},..._f4.map((Z)=>({...Z})),...($.publicSets??[]).map((Z)=>({volume:bw(Z),path:`public/${Z}`,readonly:!0})),...($.syncedVolumes??[]).filter((Z)=>Kj0(Z)===null).map((Z)=>({volume:Z,path:Z,readonly:!0}))]}}async function O28($,Z){try{let X=await $.boundAuth.apiKey.create({name:`orgfs-${Z.orgSlug}`,permissions:{self:["ORG_FS_READ","ORG_FS_WRITE"]},expiresIn:xf4,metadata:{organization:{id:Z.orgId,slug:Z.orgSlug}}}),Q=await $.storage.orgRepoSyncs.listEnabledVolumes(Z.orgId).catch(()=>[]);return JSON.stringify(vf4({baseUrl:Z.baseUrl,orgSlug:Z.orgSlug,token:X.key,publicSets:X3().map((Y)=>Y.set),syncedVolumes:Q}))}catch(X){console.warn("[org-fs] token mint failed; mounts disabled for this sandbox",X);return}}var w28=".outputs",B28=".uploads",_f4,xf4=604800;var Nr=O(()=>{Jj0();Hj0();jE();_f4=[{volume:"outputs",path:w28},{volume:"uploads",path:B28}]});import{z as BH}from"zod";async function vh($,Z){W0(Z);let X=Y0(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 fN(Z,$.branch,Q),K=KH(o5(G),J,$.branch,$.sandboxProviderKind),W=$.sandboxProviderKind,{provider:H}=await OQ(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 BO(Z.storage.virtualMcps,$.virtualMcpId,Q,J,$.branch,W).catch((B)=>{console.warn("[ensureSandbox] failed to reap stale user-desktop entry",B)})}let N=await CO(Z,SO($.branch)??Z.metadata?.threadId)??G.githubRepo??null,{entry:F}=await D28({ctx:Z,userId:Q,sandboxUserId:J,orgId:X.id,virtualMcpId:$.virtualMcpId,branch:$.branch,metadata:G,githubRepo:N,existing:null,providerKind:W,runner:H,...$.cloneOnly?{cloneOnly:!0}:{}});return F}async function D28($){let{ctx:Z,userId:X,sandboxUserId:Q,orgId:Y,virtualMcpId:G,branch:J,metadata:K,existing:W,runner:H,cloneOnly:U}=$,N=$.githubRepo?await bf4({ctx:Z,orgId:Y,virtualMcpId:G,userId:X,githubRepo:$.githubRepo}):null,{runtime:F,packageManager:w,port:B,packageManagerPath:L}=eR8(K),D;if(N){if(N.connectionId)await OO({ctx:Z,connectionId:N.connectionId,organizationId:Y,forceRefresh:!0,onLegacyMintError:(R0)=>{console.error("[provisionSandbox] repo-scoped legacy token mint failed",{connectionId:N.connectionId,error:R0.message})}});let{cloneUrl:F0,gitUserName:j0,gitUserEmail:Z0}=N.connectionId?await LO(N.connectionId,N.owner,N.name,Z.db,Z.vault):VD8(N.owner,N.name);if(!w){let R0=N.connectionId?await J28(N.connectionId,N.owner,N.name,Z.db,Z.vault):await K28(N.owner,N.name);if(R0)w=R0.packageManager,F=Kr[R0.packageManager].runtime,B=R0.devPort??B,await yf4(Z,G,X,R0.packageManager,R0.devPort)}let e=a0().sandboxStickyHeadRefEnabled,T0=Yj0({branch:J,derivedRef:xN(J),recordedHeadRef:e?await nR8(Z,SO(J)):null,sticky:e}),Q0=await X28({ctx:Z,orgId:Y,userId:X,entries:aR8(K)});D={cloneUrl:F0,...N.connectionId?{connectionId:N.connectionId}:{},userName:j0,userEmail:Z0,branch:T0,displayName:`${N.owner}/${N.name}`,submoduleCredentials:Q0}}let E=F&&w&&!U?{runtime:F,packageManager:w,...B!==null?{devPort:Number(B)}:{},...L?{packageManagerPath:L}:{}}:void 0,z=ko({orgId:Y,virtualMcpId:G,branch:J}),j=H.kind==="user-desktop"?await N28(Z.objectStorage,{isProduction:a0().nodeEnv==="production"}):null,A=(H.kind==="user-desktop"||H.kind==="agent-sandbox")&&!a0().orgFsMountsDisabled,P;if(A){let F0=Z.organization?.slug??(await Z.db.selectFrom("organization").select(["slug"]).where("id","=",Y).executeTakeFirst())?.slug;if(F0)P=await O28(Z,{orgSlug:F0,orgId:Y,baseUrl:xQ()})}await hf4(H);let I=await H.ensure({userId:Q,projectRef:z},{branch:J,repo:D,workload:E,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}:{}},...j?{offloadAllowedHosts:j.hosts,offloadAllowSameHostDev:j.allowSameHostDev}:{},...P?{orgFsConfigJson:P}:{}}),V=_h(K);await Zj0({ctx:Z,runner:H,handle:I.handle,orgId:Y,userId:X,entries:V});let C=!!W&&W.sandboxHandle===I.handle&&W?.createdAt?W.createdAt:Date.now(),m=K.runtime?.selected??null,f=K.runtime?.port??null,y=K.runtime?.path??null,o={sandboxHandle:I.handle,previewUrl:I.previewUrl,sandboxApiUrl:I.previewUrl,sandboxProviderKind:H.kind,createdAt:C,startedWith:{packageManager:m,port:f,path:y}};await ED8(Z.storage.virtualMcps,G,X,Q,J,$.providerKind,o);let b=SO(J)??Z.metadata?.threadId;if(b)await oR8(Z,b,Q,J,$.providerKind,o);let a=!W||W.sandboxHandle!==I.handle;return{entry:o,isNewVm:a}}async function bf4($){let{ctx:Z,orgId:X,virtualMcpId:Q,userId:Y,githubRepo:G}=$;if(!G.connectionId)return G;if(await Z.storage.connections.findById(G.connectionId,X))return G;let{items:K}=await Z.storage.connections.list(X),W=xG0(K,G.owner,G.name);if(!W)return console.warn("[provisionSandbox] recorded repo connection no longer exists and no live connection covers the repo",{virtualMcpId:Q,connectionId:G.connectionId}),G;console.warn("[provisionSandbox] healed dangling repo connection",{virtualMcpId:Q,staleConnectionId:G.connectionId,connectionId:W.id});try{let U=(await Z.storage.virtualMcps.findById(Q))?.metadata??{},N=U.githubRepo;if(N?.connectionId===G.connectionId){let F=x5(W);await Z.storage.virtualMcps.update(Q,Y,{metadata:{...U,githubRepo:{...N,connectionId:W.id,...F?{installationId:F.installationId}:{}}}})}}catch(H){console.warn("[provisionSandbox] failed to persist healed repo connection",{virtualMcpId:Q,error:H.message})}return{...G,connectionId:W.id}}async function yf4($,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 hf4($){if(!$.hasSchedulableCapacity)return;let Z=Date.now()+L28,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(L28/1000)}s`);if(!X)X=!0,console.warn("[ensureSandbox] waiting for cluster capacity \u2014 a sandbox pod cannot be scheduled right now");await T8(gf4)}}var ff4,o41,L28=150000,gf4=5000;var Fr=O(()=>{qN();a4();p0();Wr();p41();Q28();HY();oQ();Oh();H28();d41();kO();jK();Gj0();F28();k8();UZ();Nr();HY();ff4=BH.enum(["agent-sandbox","user-desktop","cluster"]),o41=t({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:ff4.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)=>{W0(Z);let X=Y0(Z);await Z.access.check();let Q=$.branch??Qj0(Xj0(Z.auth.user)),Y=z1(Z);if(!Y)throw Error("User ID required");let G=await fN(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?oz($.sandboxProviderKind):void 0,{provider:H,kind:U}=await OQ(Z,{userId:G,branch:Q,virtualMcpMetadata:K,explicitKind:W}),N=KH(o5(K),G,Q,U),w=await CO(Z,SO(Q)??Z.metadata?.threadId)??K.githubRepo??null,{entry:B,isNewVm:L}=await D28({ctx:Z,userId:Y,sandboxUserId:G,orgId:X.id,virtualMcpId:$.virtualMcpId,branch:Q,metadata:K,githubRepo:w,existing:N,providerKind:U,runner:H});return{...B,branch:Q,isNewVm:L,sandboxProviderKind:U}}})});function uf4($){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 z28(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 Uj0($,Z,X,Q,Y="agent-tools",G){let J=uf4({publicUrl:xQ(),agentId:Z,organization:X,target:Y,...G?{threadId:G}:{}}),K=await $.boundAuth.apiKey.create({name:Q,permissions:{"*":["*"]},expiresIn:E28,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()+E28*1000}}var E28=3600,z28;var r41=O(()=>{UZ();z28=class z28 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 cf4($,Z,X,Q){try{let Y=$.organization;if(!Y)return;let G=await Uj0($,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 xh($,Z){let{provider:X,kind:Q}=await OQ($,{userId:Z.userId,branch:Z.branch,virtualMcpMetadata:null}),Y=null,G=()=>{if(!Y){if(Y=vh({virtualMcpId:Z.virtualMcpId,branch:Z.branch,sandboxProviderKind:Q},$).then((W)=>W.sandboxHandle),Y.catch(()=>{Y=null}),Z.syncTools)Y.then((W)=>cf4($,X,W,{virtualMcpId:Z.virtualMcpId,providerKind:Q})).catch(()=>{})}return Y},J=Z.branch==="ephemeral"||Q==="user-desktop";return P81(X,{ensureHandle:G,invalidateHandle:async(W)=>{let H=Y;if(Y=null,!J&&!W?.force)return;try{await BO($.storage.virtualMcps,Z.virtualMcpId,Z.userId,Z.userId,Z.branch,Q)}catch(U){console.warn("[cluster-sandbox-fs] failed to reap vmMap entry",U)}if(H&&typeof X.forgetHandle==="function")try{let U=await H;await X.forgetHandle(U)}catch(U){console.warn("[cluster-sandbox-fs] forgetHandle failed",U)}},canAutoRestart:J,threadId:Z.threadId})}async function j28($,Z){try{let X=await xh($,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 Nj0=O(()=>{qN();r41();kO();Fr();HY()});import{z as P28}from"zod";function fh($){let Z=[];for(let X of $){if(X.status!=="active")continue;let Q=x5(X);if(!Q)continue;Z.push({connectionId:X.id,owner:Q.owner,repo:Q.repo,installationId:Q.installationId})}return Z}async function df4($,Z){let{items:X}=await $.storage.connections.list(Z,{slug:"mcp-github"});return fh(X)}function mf4($){let Z=$.split(`
|
|
2319
2319
|
`).map((Q)=>Q.trim()).filter((Q)=>Q&&Q!==".git"&&Q!=="__CLONED__"),X=Z.length>0;return{cloned:X,listing:X?Z.join(`
|
|
2320
2320
|
`):""}}function if4($){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(`
|
|
2321
2321
|
`);return`${Z}
|