decocms 4.321.3 → 4.321.4

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.
Files changed (248) hide show
  1. package/dist/client/assets/{AlertCircle-DlZdUT4y.js → AlertCircle-Dv6G1zch.js} +1 -1
  2. package/dist/client/assets/{AreaChart-CDaTYOly.js → AreaChart-Bh324PJ7.js} +1 -1
  3. package/dist/client/assets/{ArrowLeft-B_C58IhS.js → ArrowLeft-Dyo7ZseM.js} +1 -1
  4. package/dist/client/assets/{ArrowUp-0zKbGhZX.js → ArrowUp-Dl1f2e9F.js} +1 -1
  5. package/dist/client/assets/{Check-Bu3XsPtR.js → Check-DiuzOTdo.js} +1 -1
  6. package/dist/client/assets/{CheckCircle-DKTcHnyM.js → CheckCircle-BTMeEcth.js} +1 -1
  7. package/dist/client/assets/{ChevronRight-DuX1hKVe.js → ChevronRight-CYJzqw1W.js} +1 -1
  8. package/dist/client/assets/{ChevronSelectorVertical-CUY38lF0.js → ChevronSelectorVertical-C0Fdqi9U.js} +1 -1
  9. package/dist/client/assets/{ChevronUp-DDdMqJL1.js → ChevronUp-CHN7dU5d.js} +1 -1
  10. package/dist/client/assets/{Copy01-BbXi4FYi.js → Copy01-CZOGrHZ9.js} +1 -1
  11. package/dist/client/assets/{CreditCard01-gu6q0yZd.js → CreditCard01-CxZhImMf.js} +1 -1
  12. package/dist/client/assets/{DotsVertical-PUVVFLTP.js → DotsVertical-CsIT64BQ.js} +1 -1
  13. package/dist/client/assets/{Download01-AtmH14NN.js → Download01-DEU1JkfL.js} +1 -1
  14. package/dist/client/assets/{ErrorBarContext-qLO8ohog.js → ErrorBarContext-44kQWZkn.js} +1 -1
  15. package/dist/client/assets/{Eye-Z_2DhwO_.js → Eye-DNWGZGwG.js} +1 -1
  16. package/dist/client/assets/{GitBranch01-BritbDKe.js → GitBranch01-4HvT92Fb.js} +1 -1
  17. package/dist/client/assets/{Globe01-DIQAtDkP.js → Globe01-CySbwdvS.js} +1 -1
  18. package/dist/client/assets/{HardDrive-DjrfIOu4.js → HardDrive-CkhRSS5J.js} +1 -1
  19. package/dist/client/assets/{Image01-CGO7yG2R.js → Image01-CnSVldaE.js} +1 -1
  20. package/dist/client/assets/{Key01-m5a-9O7E.js → Key01-BvfZtZef.js} +1 -1
  21. package/dist/client/assets/{Link01-_3xhMoAr.js → Link01-DELnIRjt.js} +1 -1
  22. package/dist/client/assets/{LinkExternal01-DFZf17HG.js → LinkExternal01-6r85JlVB.js} +1 -1
  23. package/dist/client/assets/{Monitor01-Cym0a0IH.js → Monitor01-Ciyr-Z_-.js} +1 -1
  24. package/dist/client/assets/{Package-BA5DvHbm.js → Package-CGoiEMne.js} +1 -1
  25. package/dist/client/assets/{Palette-DVp1cbTL.js → Palette-CLInuq6o.js} +1 -1
  26. package/dist/client/assets/{Play-CC767BNc.js → Play-CFcccqRE.js} +1 -1
  27. package/dist/client/assets/{Plus-BsdY3vta.js → Plus-DfniZcTj.js} +1 -1
  28. package/dist/client/assets/{SearchMd-CQywkGC8.js → SearchMd-MV7l96VN.js} +1 -1
  29. package/dist/client/assets/{Sector-6c8v6F9Y.js → Sector-CXJOKUEx.js} +1 -1
  30. package/dist/client/assets/{Settings02-B3BHuFlc.js → Settings02-DLKKNdDt.js} +1 -1
  31. package/dist/client/assets/{Share07-DQRfeucj.js → Share07-BdYeKEPF.js} +1 -1
  32. package/dist/client/assets/{Shield01-CfLUCs7T.js → Shield01-Dbav6S5n.js} +1 -1
  33. package/dist/client/assets/{Stars01-D7oX_8Wb.js → Stars01-PjG8UcMP.js} +1 -1
  34. package/dist/client/assets/{Sun-DwFd1air.js → Sun-DmqaD0GF.js} +1 -1
  35. package/dist/client/assets/{Tool01-Dh-2dHg7.js → Tool01-CdkG5j9q.js} +1 -1
  36. package/dist/client/assets/{Tool02-C5-ESFs5.js → Tool02-CtS9_9Au.js} +1 -1
  37. package/dist/client/assets/{Trash01-DgYh1NxX.js → Trash01-DpQq-xrz.js} +1 -1
  38. package/dist/client/assets/{TrendUp01-0nrjwpEZ.js → TrendUp01-Dwgdtlxo.js} +1 -1
  39. package/dist/client/assets/{Upload01-jkHCXrUI.js → Upload01-C-aUSpkq.js} +1 -1
  40. package/dist/client/assets/{User01-yXo0r48U.js → User01-CIlNhP30.js} +1 -1
  41. package/dist/client/assets/{UserSquare-B19aw2mP.js → UserSquare-CDP0762p.js} +1 -1
  42. package/dist/client/assets/{Users01-BiFVZazG.js → Users01-CJ-REDik.js} +1 -1
  43. package/dist/client/assets/{Users03-C9WBhoi4.js → Users03-C7y8d7lq.js} +1 -1
  44. package/dist/client/assets/{XCircle-DRYTYfoJ.js → XCircle-D4lh-8UY.js} +1 -1
  45. package/dist/client/assets/{XClose-D_sSgqWY.js → XClose-CUFBDVP-.js} +1 -1
  46. package/dist/client/assets/{Zap-BwqaqJR6.js → Zap-BD_2K_N7.js} +1 -1
  47. package/dist/client/assets/{ZoomOut-DL9fn9Rn.js → ZoomOut-CYflMQc3.js} +1 -1
  48. package/dist/client/assets/{access-gate-Cr4kGdoG.js → access-gate-B8SIJFr7.js} +1 -1
  49. package/dist/client/assets/{agent-icon-RpsSZWOm.js → agent-icon-Dj2ko6xN.js} +1 -1
  50. package/dist/client/assets/agents-list-DedSGOjL.js +1 -0
  51. package/dist/client/assets/{ai-providers-dfmBmLi1.js → ai-providers-PLInDAtU.js} +1 -1
  52. package/dist/client/assets/{alert-DDOSdHF1.js → alert-D50pTGlG.js} +1 -1
  53. package/dist/client/assets/{alert-dialog-BwkydmfJ.js → alert-dialog-DN6vGwKb.js} +1 -1
  54. package/dist/client/assets/{analytics-tab-CfuMS2EL.js → analytics-tab-DkOamiBu.js} +1 -1
  55. package/dist/client/assets/api-keys-BT6wuuDI.js +1 -0
  56. package/dist/client/assets/{api-keys-DMRP4EpN.js → api-keys-CUuIcLOK.js} +1 -1
  57. package/dist/client/assets/{app-editor-DqP-YnLu.js → app-editor-CXxJdDRj.js} +1 -1
  58. package/dist/client/assets/{auth-1n-nSaCp.js → auth-BF15VDKW.js} +1 -1
  59. package/dist/client/assets/{auth-catchall-DjUs0QfG.js → auth-catchall-CfznBWAb.js} +1 -1
  60. package/dist/client/assets/{auth-entry-l2FufJt_.js → auth-entry-BmdnPyAe.js} +1 -1
  61. package/dist/client/assets/{auth-split-layout-BFjeh5RK.js → auth-split-layout-D8Qd5X5d.js} +1 -1
  62. package/dist/client/assets/{authenticate-and-persist-oauth-CczjH39y.js → authenticate-and-persist-oauth-ORS2OKxY.js} +1 -1
  63. package/dist/client/assets/{automation-list-row-DJmiHAcQ.js → automation-list-row-D_CbqNGG.js} +1 -1
  64. package/dist/client/assets/{automation-runs-CPO7lLwq.js → automation-runs-oTVIsV-n.js} +1 -1
  65. package/dist/client/assets/{automations-nuUr74Pw.js → automations-CkLUemPj.js} +1 -1
  66. package/dist/client/assets/{avatar-D7BI9kIY.js → avatar-BLCEls6Y.js} +1 -1
  67. package/dist/client/assets/{badge-C7G_dwIu.js → badge-CSQtV4I1.js} +1 -1
  68. package/dist/client/assets/{block-document-DoNf7H3D.js → block-document-DHWwd1Xg.js} +1 -1
  69. package/dist/client/assets/{breadcrumb-BAjbmNYL.js → breadcrumb-BY2L4Yur.js} +1 -1
  70. package/dist/client/assets/{buckets-BzOMvHnI.js → buckets-BgzCy0Wo.js} +1 -1
  71. package/dist/client/assets/{bulk-category-panel-CDcCaEVa.js → bulk-category-panel-BsKaZScD.js} +1 -1
  72. package/dist/client/assets/{capability-load-error-DdUEYVnx.js → capability-load-error-CpA6LOWl.js} +1 -1
  73. package/dist/client/assets/{cards-evwCQ3BJ.js → cards-DDW_x79J.js} +1 -1
  74. package/dist/client/assets/{category-editor-BUgoXsGS.js → category-editor-Ddez8F9D.js} +1 -1
  75. package/dist/client/assets/{cdn-tab-C7HzaQJs.js → cdn-tab-DFZvtAMl.js} +1 -1
  76. package/dist/client/assets/{chart-BbiPqYsI.js → chart-CMxD7edM.js} +1 -1
  77. package/dist/client/assets/{chat-context-5h3SEksi.js → chat-context-C5TtMbeA.js} +1 -1
  78. package/dist/client/assets/{checkbox-DrLBm6Hu.js → checkbox-CHvOkNek.js} +1 -1
  79. package/dist/client/assets/{choose-editor-C_UqQB0X.js → choose-editor-Bl3IlbHF.js} +1 -1
  80. package/dist/client/assets/{cli-auth-success-mbtPKAeO.js → cli-auth-success-CEFSPlKa.js} +1 -1
  81. package/dist/client/assets/{client-icons-Dx7ZT4qY.js → client-icons-CIyJtQzW.js} +1 -1
  82. package/dist/client/assets/{collection-detail-3F2jLAIe.js → collection-detail-V8ouNFsx.js} +1 -1
  83. package/dist/client/assets/{collection-display-button-BuGIMFHI.js → collection-display-button-ch8VsZJ-.js} +1 -1
  84. package/dist/client/assets/{collection-search-Byf9covb.js → collection-search-C0aemqyU.js} +1 -1
  85. package/dist/client/assets/{collection-table-wrapper-C9hfGOql.js → collection-table-wrapper-RraLzE6q.js} +1 -1
  86. package/dist/client/assets/{collection-tabs-4YD6nwky.js → collection-tabs-DM3JgymS.js} +1 -1
  87. package/dist/client/assets/{command-Bz-l73oK.js → command-aq94pylP.js} +1 -1
  88. package/dist/client/assets/{commerce-onboarding-Dt2M_QAS.js → commerce-onboarding-C6pquuZu.js} +1 -1
  89. package/dist/client/assets/{connect-DaJLytlD.js → connect-Db_FA2vM.js} +1 -1
  90. package/dist/client/assets/{connect-layout-D7bRiFvQ.js → connect-layout-DUtKqe8O.js} +1 -1
  91. package/dist/client/assets/{connection-Corqb4nW.js → connection-D4KVb2vi.js} +1 -1
  92. package/dist/client/assets/{connection-card-kBzgkq3q.js → connection-card-DZD9pIth.js} +1 -1
  93. package/dist/client/assets/{connection-detail-BixLRE2Y.js → connection-detail-Rd3BNYmU.js} +1 -1
  94. package/dist/client/assets/{connection-form-helpers-CkY6wGpq.js → connection-form-helpers-CJ7gQUqN.js} +1 -1
  95. package/dist/client/assets/{connections-NFtaWcpm.js → connections-DP-c-cpk.js} +1 -1
  96. package/dist/client/assets/{create-organization-dialog-CZnpESma.js → create-organization-dialog-BFeoMeJI.js} +1 -1
  97. package/dist/client/assets/{decopilot-sse-pool-Ccw1vgMp.js → decopilot-sse-pool-B2Ek6f9E.js} +1 -1
  98. package/dist/client/assets/{dialog-lVg2I_FW.js → dialog-BVuXhd_n.js} +1 -1
  99. package/dist/client/assets/{domain-settings-2IuIzWRo.js → domain-settings-Creutor_.js} +1 -1
  100. package/dist/client/assets/{drawer-F0hkjkWK.js → drawer-CXBUq1b4.js} +1 -1
  101. package/dist/client/assets/{dropdown-menu-QVhpTnbw.js → dropdown-menu-7nrlUaMG.js} +1 -1
  102. package/dist/client/assets/{e2e-tab-CIhvZ7jB.js → e2e-tab-Dr-mwFjd.js} +1 -1
  103. package/dist/client/assets/{editor-DHSROqSc.js → editor-CSXnkhqo.js} +1 -1
  104. package/dist/client/assets/{empty-state-B6_Ul4U9.js → empty-state-D1TMU-hy.js} +1 -1
  105. package/dist/client/assets/{empty-state-BoTu9lkL.js → empty-state-N8rf9YSi.js} +1 -1
  106. package/dist/client/assets/{extract-connection-data-DcfPnaRL.js → extract-connection-data-fYPcP0VJ.js} +1 -1
  107. package/dist/client/assets/{file-explorer-FGaad9SC.js → file-explorer-Ku7EjWAL.js} +1 -1
  108. package/dist/client/assets/{file-type-icon-iSdqxvCJ.js → file-type-icon-BnBH2hK9.js} +1 -1
  109. package/dist/client/assets/{folder-icon-DoL1wgM6.js → folder-icon-1xzQyJ7C.js} +1 -1
  110. package/dist/client/assets/{form-BzptyBk4.js → form-D7fAV9eN.js} +1 -1
  111. package/dist/client/assets/{general-D6b_Y3aW.js → general-DLE7dZPk.js} +1 -1
  112. package/dist/client/assets/{github-repo-picker-B1n6OBj4.js → github-repo-picker-CVdHp0M0.js} +1 -1
  113. package/dist/client/assets/{hooks-bhKP99Ax.js → hooks-y1rkw2ir.js} +1 -1
  114. package/dist/client/assets/{hosting-tab-s8sW7wxN.js → hosting-tab-BAPE6MlT.js} +1 -1
  115. package/dist/client/assets/{index-fXvyzo6h.js → index-B9n6l693.js} +1 -1
  116. package/dist/client/assets/{index-MnhhExK7.js → index-BOJEwmSU.js} +1 -1
  117. package/dist/client/assets/{index-D7xeSGeI.js → index-BgfHML7J.js} +1 -1
  118. package/dist/client/assets/{index-CGetbWoq.js → index-CbU-T1m1.js} +1 -1
  119. package/dist/client/assets/{index-CW6L2S49.js → index-Ciqhx4Es.js} +2 -2
  120. package/dist/client/assets/{index-nFRHQC-L.js → index-CmirxoQz.js} +1 -1
  121. package/dist/client/assets/{index-BNJPAEna.js → index-DHZW87eM.js} +1 -1
  122. package/dist/client/assets/{index-DWxzACaY.js → index-DK46XAl9.js} +6 -6
  123. package/dist/client/assets/{index-ruQQqW4p.js → index-Dr0vXAye.js} +1 -1
  124. package/dist/client/assets/{index-Bw600I7i.js → index-o5eMIupH.js} +1 -1
  125. package/dist/client/assets/{index-redirect-CGJzac9E.js → index-redirect-Dy4llany.js} +1 -1
  126. package/dist/client/assets/{infra-billing-DzmhWVEh.js → infra-billing-CDH62RCF.js} +1 -1
  127. package/dist/client/assets/{input-DPKIPveM.js → input-HiBvv-tS.js} +1 -1
  128. package/dist/client/assets/{integration-icon-D9FdHsn5.js → integration-icon-B63L2HtM.js} +1 -1
  129. package/dist/client/assets/{invite-member-dialog-CyxMgQZJ.js → invite-member-dialog-S-x8vUoc.js} +1 -1
  130. package/dist/client/assets/{label-CqIRBXyv.js → label-CGF50XGa.js} +1 -1
  131. package/dist/client/assets/{layout-C4M3_yhL.js → layout-Cf_v7v8J.js} +1 -1
  132. package/dist/client/assets/{login-qzbpt226.js → login-BRT3iRa2.js} +1 -1
  133. package/dist/client/assets/{markdown-BiJIqYGv.js → markdown-Srunai6w.js} +1 -1
  134. package/dist/client/assets/{mcp-oauth-HjvSjKSb.js → mcp-oauth-Bmt9vIvY.js} +1 -1
  135. package/dist/client/assets/{members-D2It71TM.js → members-_klSSf7w.js} +1 -1
  136. package/dist/client/assets/{monaco-editor-DkHBERIE.js → monaco-editor-BXDxtePS.js} +1 -1
  137. package/dist/client/assets/{monitoring-stats-row-B68839YD.js → monitoring-stats-row-D1pJtu9I.js} +1 -1
  138. package/dist/client/assets/{multi-select-jl7Hbzaz.js → multi-select-BZ-tCaud.js} +1 -1
  139. package/dist/client/assets/{oauth-callback--dbFGP9K.js → oauth-callback-F8D4D968.js} +1 -1
  140. package/dist/client/assets/{oauth-callback-ai-provider-BRBN5fiB.js → oauth-callback-ai-provider-DlKy27tT.js} +1 -1
  141. package/dist/client/assets/{onboarding-HFAUcTGc.js → onboarding-CoNP24fk.js} +1 -1
  142. package/dist/client/assets/org-layout-D6WucjyK.js +1 -0
  143. package/dist/client/assets/{organization-choice-G8mAnjMS.js → organization-choice-nbe4I9kY.js} +1 -1
  144. package/dist/client/assets/{orgs-CgeiXFFD.js → orgs-o3NxI1V6.js} +1 -1
  145. package/dist/client/assets/{page-seo-form-DTFWlSs6.js → page-seo-form-DDV7VjV-.js} +1 -1
  146. package/dist/client/assets/{popover-Cfo1Nvgv.js → popover-CRkM20y5.js} +1 -1
  147. package/dist/client/assets/{post-calendar-D0PKhtb8.js → post-calendar-BacBxT2V.js} +1 -1
  148. package/dist/client/assets/{post-editor-BsMV7w5K.js → post-editor-4rU4mFOM.js} +1 -1
  149. package/dist/client/assets/{primitives-Dshx-6vZ.js → primitives-RPdPdtiK.js} +1 -1
  150. package/dist/client/assets/{profile-6Ncb3Njd.js → profile-weZdXHvp.js} +1 -1
  151. package/dist/client/assets/{project-app-view-DJ4h95de.js → project-app-view-Ben78Ktd.js} +1 -1
  152. package/dist/client/assets/{prompts-6dW4jofl.js → prompts-DqEM2vI1.js} +1 -1
  153. package/dist/client/assets/record-editor-CcDRxPdh.js +1 -0
  154. package/dist/client/assets/redirect-editor-DN0sxwSC.js +1 -0
  155. package/dist/client/assets/registry-4_qn65ff.js +2 -0
  156. package/dist/client/assets/{registry-layout-CEF3gBC_.js → registry-layout-BmS41XeK.js} +1 -1
  157. package/dist/client/assets/{reports-hh8ZI3ZJ.js → reports-Ex-p9Q6U.js} +1 -1
  158. package/dist/client/assets/{require-capability-B7CJKsKK.js → require-capability-B6bbEttD.js} +1 -1
  159. package/dist/client/assets/{required-auth-layout-BASPIPDt.js → required-auth-layout-BNGtvzOt.js} +1 -1
  160. package/dist/client/assets/{reset-password-B5OEAnS-.js → reset-password-CKdYnon5.js} +1 -1
  161. package/dist/client/assets/{review-settings-DJxQp0XZ.js → review-settings-DHtFpGrU.js} +1 -1
  162. package/dist/client/assets/{roles-Bx1AV-1M.js → roles-DEuEeqHH.js} +1 -1
  163. package/dist/client/assets/{schema-CmTu1Qcv.js → schema-BSi9J6XG.js} +1 -1
  164. package/dist/client/assets/{scroll-area-gq3Q2AeD.js → scroll-area-CjEkqIar.js} +1 -1
  165. package/dist/client/assets/{search-input-B-_TRDC7.js → search-input-kDCevv38.js} +1 -1
  166. package/dist/client/assets/{secrets-C8NxHpd-.js → secrets-FJlGtZJz.js} +1 -1
  167. package/dist/client/assets/{sections-editor-Bh7OpK8E.js → sections-editor-Db_XanCD.js} +1 -1
  168. package/dist/client/assets/{select-DamLPfhf.js → select-Dx7GTm0n.js} +1 -1
  169. package/dist/client/assets/{select-model-QU5hzlSe.js → select-model-BkS3JCk0.js} +1 -1
  170. package/dist/client/assets/{self-tool-result-Lz_-Z0nG.js → self-tool-result-9rkDiIrM.js} +1 -1
  171. package/dist/client/assets/{seo-editor-DwIreVEK.js → seo-editor-BLeAZw1O.js} +1 -1
  172. package/dist/client/assets/settings-layout-B0kIHXCh.js +1 -0
  173. package/dist/client/assets/{settings-sidebar-BfPvugP6.js → settings-sidebar-BAeW8psv.js} +1 -1
  174. package/dist/client/assets/{shell-controls-CeHXl7mZ.js → shell-controls-jJMoCrxb.js} +1 -1
  175. package/dist/client/assets/{shell-layout-CBZfZSo4.js → shell-layout-r6wI2dxA.js} +1 -1
  176. package/dist/client/assets/{skill-preview-Cq3_PFMf.js → skill-preview-BV5lD9Ur.js} +1 -1
  177. package/dist/client/assets/{skills-BHXTZ7NQ.js → skills-mHNv9mjy.js} +1 -1
  178. package/dist/client/assets/{sso-DU8cw1b0.js → sso-DQXV-Z9b.js} +1 -1
  179. package/dist/client/assets/{store-BVdwdwPL.js → store-B5QBWbgI.js} +1 -1
  180. package/dist/client/assets/store-registry-8k7WpgtY.js +2 -0
  181. package/dist/client/assets/{switch-Mdu4u0WR.js → switch-U7uzAFmD.js} +1 -1
  182. package/dist/client/assets/{synced-repos-DaH0mQuQ.js → synced-repos-CPCzRDss.js} +1 -1
  183. package/dist/client/assets/{table-D3m7ArKR.js → table-D3Y6ENY8.js} +1 -1
  184. package/dist/client/assets/{tabs-C6SXoslH.js → tabs-DuT8Yq6b.js} +1 -1
  185. package/dist/client/assets/{task-board-BR_hukMd.js → task-board-DWHUF-M8.js} +1 -1
  186. package/dist/client/assets/{task-route-Dm9sxint.js → task-route-CushdBcU.js} +1 -1
  187. package/dist/client/assets/{tasks-BRPJVj0A.js → tasks-Bj-Geic7.js} +1 -1
  188. package/dist/client/assets/{textarea-DoEBjnc4.js → textarea-bCfy8lu-.js} +1 -1
  189. package/dist/client/assets/{thread-intent-1OmKxTfG.js → thread-intent-CisrByhq.js} +1 -1
  190. package/dist/client/assets/{thread-route-xvjmSQIh.js → thread-route-b08GDb6K.js} +1 -1
  191. package/dist/client/assets/{toggle-group-CNANG2fZ.js → toggle-group-3YvrBCWM.js} +1 -1
  192. package/dist/client/assets/{toolbar-B341Epq4.js → toolbar-BtJG1jFO.js} +1 -1
  193. package/dist/client/assets/{toolbar-icon-button-BO82E-n0.js → toolbar-icon-button-CCWdMNhD.js} +1 -1
  194. package/dist/client/assets/{track-Bj2VKdRl.js → track-CIoIWcra.js} +1 -1
  195. package/dist/client/assets/{types-DLFi4V7L.js → types-BL_Cd649.js} +1 -1
  196. package/dist/client/assets/{use-ai-providers-tSdCWAm9.js → use-ai-providers-ZNJMa2Qe.js} +1 -1
  197. package/dist/client/assets/{use-automations-DjM5YwJ5.js → use-automations-CO5qll04.js} +1 -1
  198. package/dist/client/assets/{use-autosave-DdDTzW-p.js → use-autosave-CWnBHJNw.js} +1 -1
  199. package/dist/client/assets/{use-connection--sEuYWk0.js → use-connection-BY4RTRF-.js} +1 -1
  200. package/dist/client/assets/{use-copy-IMBiDrGI.js → use-copy-MarDfxAW.js} +1 -1
  201. package/dist/client/assets/{use-create-virtual-mcp-DsfSBfvB.js → use-create-virtual-mcp-BZY8HplW.js} +1 -1
  202. package/dist/client/assets/{use-debounced-autosave-DyX30vD8.js → use-debounced-autosave-CKZ9WmVu.js} +1 -1
  203. package/dist/client/assets/{use-debounced-value-DS9pfZWp.js → use-debounced-value-DM_0TZ22.js} +1 -1
  204. package/dist/client/assets/{use-decopilot-events-DNS0SnLr.js → use-decopilot-events-GHwUJFdQ.js} +1 -1
  205. package/dist/client/assets/{use-delete-connection-DIc-Qfav.js → use-delete-connection-p_Lc_Grq.js} +1 -1
  206. package/dist/client/assets/{use-deployment-admin-CH4neEKc.js → use-deployment-admin-BZ1DWC9e.js} +1 -1
  207. package/dist/client/assets/{use-destination-route-7JP5O6OJ.js → use-destination-route-BbzQn-n1.js} +1 -1
  208. package/dist/client/assets/{use-file-configs-CUpgfUZo.js → use-file-configs-Dme4FNCs.js} +1 -1
  209. package/dist/client/assets/{use-infinite-scroll-BYZDUtLT.js → use-infinite-scroll-BnNCHFKn.js} +1 -1
  210. package/dist/client/assets/{use-join-requests-DLCB2F3F.js → use-join-requests-Camfhmzs.js} +1 -1
  211. package/dist/client/assets/{use-mcp-auth-status-DS3icTNp.js → use-mcp-auth-status-DwCKSgFq.js} +1 -1
  212. package/dist/client/assets/{use-mcp-client-BkpxeCP2.js → use-mcp-client-CLQpYb65.js} +1 -1
  213. package/dist/client/assets/{use-mcp-prompts-DCcZ3Vir.js → use-mcp-prompts-B4YApHQz.js} +1 -1
  214. package/dist/client/assets/{use-mcp-tools-zprouZ07.js → use-mcp-tools-DxNdkpqp.js} +1 -1
  215. package/dist/client/assets/{use-members-CI2nYVE7.js → use-members-Nw1pRVDm.js} +1 -1
  216. package/dist/client/assets/{use-navigate-to-agent-ChEjWy4D.js → use-navigate-to-agent-BP5fBiR_.js} +1 -1
  217. package/dist/client/assets/{use-org-auth-client-S97f03iK.js → use-org-auth-client-CKoQfJfQ.js} +1 -1
  218. package/dist/client/assets/{use-org-sso-BjH4Z9oA.js → use-org-sso-DaGSGBc8.js} +1 -1
  219. package/dist/client/assets/{use-organization-roles-CPwpLNzf.js → use-organization-roles-G6vi9RUF.js} +1 -1
  220. package/dist/client/assets/{use-organization-settings-BPN8rXNO.js → use-organization-settings-Bj_N-FZ1.js} +1 -1
  221. package/dist/client/assets/{use-panel-navigate-fLU7dGE0.js → use-panel-navigate-ChqtBgPV.js} +1 -1
  222. package/dist/client/assets/{use-project-scope-BgyywlH_.js → use-project-scope-DuXQlLft.js} +1 -1
  223. package/dist/client/assets/{use-registry-connections-Dzb0fhHm.js → use-registry-connections-DzkmhEYo.js} +1 -1
  224. package/dist/client/assets/{use-secrets-Dts0cF77.js → use-secrets-CPol22BF.js} +1 -1
  225. package/dist/client/assets/{use-section-preview-base-D94KMpp4.js → use-section-preview-base-CIXOY0XP.js} +1 -1
  226. package/dist/client/assets/{use-status-sounds-DHbTO7IH.js → use-status-sounds-DjB7YACH.js} +1 -1
  227. package/dist/client/assets/{use-tags-C7VYYpbH.js → use-tags-DhPuQwXu.js} +1 -1
  228. package/dist/client/assets/{use-view-mode-DsDWXQJ2.js → use-view-mode-XpzZpQOU.js} +1 -1
  229. package/dist/client/assets/{use-virtual-mcp-BhEuXWFl.js → use-virtual-mcp-Dc_tNJd3.js} +1 -1
  230. package/dist/client/assets/useInfiniteQuery-DYvex915.js +1 -0
  231. package/dist/client/assets/useSuspenseInfiniteQuery-zzJOxA7J.js +1 -0
  232. package/dist/client/assets/{users-CuirzC-v.js → users-B-Fjt6R6.js} +1 -1
  233. package/dist/client/assets/{variant-calendar-Bhuv7S39.js → variant-calendar-BXwjNPsZ.js} +1 -1
  234. package/dist/client/assets/{view-mode-toggle-CvuuImgL.js → view-mode-toggle-BMxnYhp9.js} +1 -1
  235. package/dist/client/index.html +1 -1
  236. package/dist/server/cli.js +2 -2
  237. package/dist/server/server.js +2 -2
  238. package/package.json +1 -1
  239. package/dist/client/assets/agents-list-D2gG4rxl.js +0 -1
  240. package/dist/client/assets/api-keys-aPYST39a.js +0 -1
  241. package/dist/client/assets/org-layout-H_iF2Jpr.js +0 -1
  242. package/dist/client/assets/record-editor-C1_htYBv.js +0 -1
  243. package/dist/client/assets/redirect-editor-Cj58js0D.js +0 -1
  244. package/dist/client/assets/registry-Blrslzvj.js +0 -2
  245. package/dist/client/assets/settings-layout-C-8zm3_h.js +0 -1
  246. package/dist/client/assets/store-registry-DUIUtqr7.js +0 -2
  247. package/dist/client/assets/useInfiniteQuery-BNd4lP3z.js +0 -1
  248. package/dist/client/assets/useSuspenseInfiniteQuery-DOhopmGX.js +0 -1
@@ -977,7 +977,7 @@ Caused by: ${Z.stack}`}};Gn=class Gn extends OZ{constructor($,Z){super($,Z);this
977
977
  `).some((X)=>X.indexOf("(https.js:")!==-1||X.indexOf("node:https:")!==-1)}incrementSockets($){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;if(!this.sockets[$])this.sockets[$]=[];let Z=new jJ4.Socket({writable:!1});return this.sockets[$].push(Z),this.totalSocketCount++,Z}decrementSockets($,Z){if(!this.sockets[$]||Z===null)return;let X=this.sockets[$],Q=X.indexOf(Z);if(Q!==-1){if(X.splice(Q,1),this.totalSocketCount--,X.length===0)delete this.sockets[$]}}getName($){if(this.isSecureEndpoint($))return zJ4.Agent.prototype.getName.call(this,$);return super.getName($)}createSocket($,Z,X){let Q={...Z,secureEndpoint:this.isSecureEndpoint(Z)},Y=this.getName(Q),G=this.incrementSockets(Y);Promise.resolve().then(()=>this.connect($,Q)).then((J)=>{if(this.decrementSockets(Y,G),J instanceof AQ$.Agent)try{return J.addRequest($,Q)}catch(W){return X(W)}this[vK].currentSocket=J,super.createSocket($,Z,X)},(J)=>{this.decrementSockets(Y,G),X(J)})}createConnection(){let $=this[vK].currentSocket;if(this[vK].currentSocket=void 0,!$)throw Error("No socket was returned in the `connect()` function");return $}get defaultPort(){return this[vK].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort($){if(this[vK])this[vK].defaultPort=$}get protocol(){return this[vK].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol($){if(this[vK])this[vK].protocol=$}}sY.Agent=IQ$});var MQ$=_((YJ)=>{var PJ4=YJ&&YJ.__createBinding||(Object.create?function($,Z,X,Q){if(Q===void 0)Q=X;var Y=Object.getOwnPropertyDescriptor(Z,X);if(!Y||("get"in Y?!Z.__esModule:Y.writable||Y.configurable))Y={enumerable:!0,get:function(){return Z[X]}};Object.defineProperty($,Q,Y)}:function($,Z,X,Q){if(Q===void 0)Q=X;$[Q]=Z[X]}),AJ4=YJ&&YJ.__setModuleDefault||(Object.create?function($,Z){Object.defineProperty($,"default",{enumerable:!0,value:Z})}:function($,Z){$.default=Z}),_p0=YJ&&YJ.__importStar||function($){if($&&$.__esModule)return $;var Z={};if($!=null){for(var X in $)if(X!=="default"&&Object.prototype.hasOwnProperty.call($,X))PJ4(Z,$,X)}return AJ4(Z,$),Z},TJ4=YJ&&YJ.__importDefault||function($){return $&&$.__esModule?$:{default:$}};Object.defineProperty(YJ,"__esModule",{value:!0});YJ.SocksProxyAgent=void 0;var RJ4=EQ$(),IJ4=qQ$(),qJ4=TJ4(P0("debug")),MJ4=_p0(P0("dns")),kJ4=_p0(P0("net")),VJ4=_p0(P0("tls")),SJ4=P0("url"),zO0=(0,qJ4.default)("socks-proxy-agent"),CJ4=($)=>{if($.servername===void 0&&$.host&&!kJ4.isIP($.host))return{...$,servername:$.host};return $};function _J4($){let Z=!1,X=5,Q=$.hostname,Y=parseInt($.port,10)||1080;switch($.protocol.replace(":","")){case"socks4":Z=!0,X=4;break;case"socks4a":X=4;break;case"socks5":Z=!0,X=5;break;case"socks":X=5;break;case"socks5h":X=5;break;default:throw TypeError(`A "socks" protocol must be specified! Got: ${String($.protocol)}`)}let G={host:Q,port:Y,type:X};if($.username)Object.defineProperty(G,"userId",{value:decodeURIComponent($.username),enumerable:!1});if($.password!=null)Object.defineProperty(G,"password",{value:decodeURIComponent($.password),enumerable:!1});return{lookup:Z,proxy:G}}class vp0 extends IJ4.Agent{constructor($,Z){super(Z);let X=typeof $==="string"?new SJ4.URL($):$,{proxy:Q,lookup:Y}=_J4(X);this.shouldLookup=Y,this.proxy=Q,this.timeout=Z?.timeout??null,this.socketOptions=Z?.socketOptions??null}async connect($,Z){let{shouldLookup:X,proxy:Q,timeout:Y}=this;if(!Z.host)throw Error("No `host` defined!");let{host:G}=Z,{port:J,lookup:W=MJ4.lookup}=Z;if(X)G=await new Promise((N,U)=>{W(G,{},(B,O)=>{if(B)U(B);else N(O)})});let K={proxy:Q,destination:{host:G,port:typeof J==="number"?J:parseInt(J,10)},command:"connect",timeout:Y??void 0,socket_options:this.socketOptions??void 0},F=(N)=>{if($.destroy(),H.destroy(),N)N.destroy()};zO0("Creating socks proxy connection: %o",K);let{socket:H}=await RJ4.SocksClient.createConnection(K);if(zO0("Successfully created socks proxy connection"),Y!==null)H.setTimeout(Y),H.on("timeout",()=>F());if(Z.secureEndpoint){zO0("Upgrading socket connection to TLS");let N=VJ4.connect({...vJ4(CJ4(Z),"host","path","port"),socket:H});return N.once("error",(U)=>{zO0("Socket TLS error",U.message),F(N)}),N}return H}}vp0.protocols=["socks","socks4","socks4a","socks5","socks5h"];YJ.SocksProxyAgent=vp0;function vJ4($,...Z){let X={},Q;for(Q in $)if(!Z.includes(Q))X[Q]=$[Q];return X}});var _Q$=_((Xz9,CQ$)=>{var fp0=P0("https"),bp0=P0("http"),{URL:kQ$}=P0("url");class VQ$ extends bp0.Agent{constructor($){let{proxy:Z,proxyRequestOptions:X,...Q}=$;super(Q);this.proxy=typeof Z==="string"?new kQ$(Z):Z,this.proxyRequestOptions=X||{}}createConnection($,Z){let X={...this.proxyRequestOptions,method:"CONNECT",host:this.proxy.hostname,port:this.proxy.port,path:`${$.host}:${$.port}`,setHost:!1,headers:{...this.proxyRequestOptions.headers,connection:this.keepAlive?"keep-alive":"close",host:`${$.host}:${$.port}`},agent:!1,timeout:$.timeout||0};if(this.proxy.username||this.proxy.password){let Y=Buffer.from(`${decodeURIComponent(this.proxy.username||"")}:${decodeURIComponent(this.proxy.password||"")}`).toString("base64");X.headers["proxy-authorization"]=`Basic ${Y}`}if(this.proxy.protocol==="https:")X.servername=this.proxy.hostname;let Q=(this.proxy.protocol==="http:"?bp0:fp0).request(X);Q.once("connect",(Y,G,J)=>{if(Q.removeAllListeners(),G.removeAllListeners(),Y.statusCode===200)Z(null,G);else G.destroy(),Z(Error(`Bad response: ${Y.statusCode}`),null)}),Q.once("timeout",()=>{Q.destroy(Error("Proxy timeout"))}),Q.once("error",(Y)=>{Q.removeAllListeners(),Z(Y,null)}),Q.end()}}class SQ$ extends fp0.Agent{constructor($){let{proxy:Z,proxyRequestOptions:X,...Q}=$;super(Q);this.proxy=typeof Z==="string"?new kQ$(Z):Z,this.proxyRequestOptions=X||{}}createConnection($,Z){let X={...this.proxyRequestOptions,method:"CONNECT",host:this.proxy.hostname,port:this.proxy.port,path:`${$.host}:${$.port}`,setHost:!1,headers:{...this.proxyRequestOptions.headers,connection:this.keepAlive?"keep-alive":"close",host:`${$.host}:${$.port}`},agent:!1,timeout:$.timeout||0};if(this.proxy.username||this.proxy.password){let Y=Buffer.from(`${decodeURIComponent(this.proxy.username||"")}:${decodeURIComponent(this.proxy.password||"")}`).toString("base64");X.headers["proxy-authorization"]=`Basic ${Y}`}if(this.proxy.protocol==="https:")X.servername=this.proxy.hostname;let Q=(this.proxy.protocol==="http:"?bp0:fp0).request(X);Q.once("connect",(Y,G,J)=>{if(Q.removeAllListeners(),G.removeAllListeners(),Y.statusCode===200){let W=super.createConnection({...$,socket:G});Z(null,W)}else G.destroy(),Z(Error(`Bad response: ${Y.statusCode}`),null)}),Q.once("timeout",()=>{Q.destroy(Error("Proxy timeout"))}),Q.once("error",(Y)=>{Q.removeAllListeners(),Z(Y,null)}),Q.end()}}CQ$.exports={HttpProxyAgent:VQ$,HttpsProxyAgent:SQ$}});var xp0,vQ$,fQ$;var bQ$=D(()=>{xp0=V(_Q$(),1),vQ$=xp0.default.HttpProxyAgent,fQ$=xp0.default.HttpsProxyAgent});import nH from"fs";import fJ4 from"https";import bJ4 from"http";import xJ4 from"net";import BC from"path";import{Headers as yJ4}from"node-fetch";import PO0 from"child_process";function yp0($){try{return nH.accessSync($),!0}catch{return!1}}class AO0{addAuthenticator($){this.custom_authenticators.push($)}constructor(){this.authenticators=[new yi0,new li0,new hi0,new ui0,new zn],this.custom_authenticators=[],this.contexts=[],this.clusters=[],this.users=[]}getContexts(){return this.contexts}getClusters(){return this.clusters}getUsers(){return this.users}getCurrentContext(){return this.currentContext}setCurrentContext($){this.currentContext=$}getContextObject($){if(!this.contexts)return null;return up0(this.contexts,$,"context")}getCurrentCluster(){let $=this.getCurrentContextObject();if(!$)return null;return this.getCluster($.cluster)}getCluster($){return up0(this.clusters,$,"cluster")}getCurrentUser(){let $=this.getCurrentContextObject();if(!$)return null;return this.getUser($.user)}getUser($){return up0(this.users,$,"user")}loadFromFile($,Z){let X=BC.dirname($);this.loadFromString(nH.readFileSync($).toString("utf-8"),Z),this.makePathsAbsolute(X)}async applyToFetchOptions($){await this.applyToHTTPSOptions($);let Z=new yJ4;for(let[X,Q]of Object.entries($.headers||{}))if(Array.isArray(Q))Q.forEach((Y)=>{Z.append(X,Y)});else if(typeof Q==="number"||typeof Q==="string")Z.set(X,Q.toString());if($.auth)Z.set("Authorization","Basic "+Buffer.from($.auth).toString("base64"));return{agent:$.agent,headers:Z,method:$.method,timeout:$.timeout}}async applyToHTTPSOptions($){let Z=this.getCurrentUser(),X=this.getCurrentCluster();if(await this.applyOptions($),Z&&Z.username)$.auth=`${Z.username}:${Z.password}`;let Q={};if(Q.ca=$.ca,Q.cert=$.cert,Q.key=$.key,Q.pfx=$.pfx,Q.passphrase=$.passphrase,$.rejectUnauthorized!==void 0)Q.rejectUnauthorized=$.rejectUnauthorized;Q.timeout=$.timeout,Q.servername=$.servername,Q.ciphers=$.ciphers,Q.honorCipherOrder=$.honorCipherOrder,Q.ecdhCurve=$.ecdhCurve,Q.clientCertEngine=$.clientCertEngine,Q.crl=$.crl,Q.dhparam=$.dhparam,Q.secureOptions=$.secureOptions,Q.secureProtocol=$.secureProtocol,Q.sessionIdContext=$.sessionIdContext,$.agent=this.createAgent(X,Q)}async applySecurityAuthentication($){let Z=this.getCurrentCluster(),X=this.getCurrentUser(),Q={},Y={};if(await this.applyOptions(Y),Z&&Z.skipTLSVerify)Q.rejectUnauthorized=!1;if(Z&&Z.tlsServerName)Q.servername=Z.tlsServerName;if(X&&X.username){let J=Buffer.from(`${X.username}:${X.password}`).toString("base64");$.setHeaderParam("Authorization",`Basic ${J}`)}let G=Y.headers||{};if(Object.entries(G).forEach(([J,W])=>{$.setHeaderParam(J,`${W}`)}),Q.ca=Y.ca,Q.cert=Y.cert,Q.key=Y.key,Q.pfx=Y.pfx,Q.passphrase=Y.passphrase,Y.rejectUnauthorized!==void 0)Q.rejectUnauthorized=Y.rejectUnauthorized;$.setAgent(this.createAgent(Z,Q))}getName(){return"kubeconfig authentication"}loadFromString($,Z){let X=_i0.load($);this.clusters=KZ$(X.clusters,Z),this.contexts=UZ$(X.contexts,Z),this.users=HZ$(X.users,Z),this.currentContext=X["current-context"]}loadFromOptions($){this.clusters=$.clusters,this.contexts=$.contexts,this.users=$.users,this.currentContext=$.currentContext}loadFromClusterAndUser($,Z){this.clusters=[$],this.users=[Z],this.currentContext="loaded-context",this.contexts=[{cluster:$.name,user:Z.name,name:this.currentContext}]}loadFromCluster($=""){let Z=process.env.KUBERNETES_SERVICE_HOST,X=process.env.KUBERNETES_SERVICE_PORT,Q="inCluster",Y="inClusterUser",G="inClusterContext",J="https";if(X==="80"||X==="8080"||X==="8001")J="http";let W=Z;if(Z&&xJ4.isIPv6(Z))W=`[${Z}]`;this.clusters=[{name:"inCluster",caFile:`${$}${gJ4}`,server:`${J}://${W}:${X}`,skipTLSVerify:!1}],this.users=[{name:"inClusterUser",authProvider:{name:"tokenFile",config:{tokenFile:`${$}${xQ$}`}}}];let K=`${$}${hJ4}`,F;if(yp0(K))F=nH.readFileSync(K).toString("utf-8");this.contexts=[{cluster:"inCluster",name:"inClusterContext",user:"inClusterUser",namespace:F}],this.currentContext="inClusterContext"}mergeConfig($,Z=!1){if(!Z&&$.currentContext)this.currentContext=$.currentContext;$.clusters.forEach((X)=>{this.addCluster(X)}),$.users.forEach((X)=>{this.addUser(X)}),$.contexts.forEach((X)=>{this.addContext(X)})}addCluster($){if(!this.clusters)this.clusters=[];this.clusters.forEach((Z,X)=>{if(Z.name===$.name)throw Error(`Duplicate cluster: ${Z.name}`)}),this.clusters.push($)}addUser($){if(!this.users)this.users=[];this.users.forEach((Z,X)=>{if(Z.name===$.name)throw Error(`Duplicate user: ${Z.name}`)}),this.users.push($)}addContext($){if(!this.contexts)this.contexts=[];this.contexts.forEach((Z,X)=>{if(Z.name===$.name)throw Error(`Duplicate context: ${Z.name}`)}),this.contexts.push($)}loadFromDefault($,Z=!1,X=process.platform){if(process.env.KUBECONFIG&&process.env.KUBECONFIG.length>0){let Y=process.env.KUBECONFIG.split(BC.delimiter).filter((G)=>G);this.loadFromFile(Y[0],$);for(let G=1;G<Y.length;G++){let J=new AO0;J.loadFromFile(Y[G],$),this.mergeConfig(J,Z)}return}let Q=uJ4(X);if(Q){let Y=BC.join(Q,".kube","config");if(yp0(Y)){this.loadFromFile(Y,$);return}}if(X==="win32"){try{let Y=PO0.spawnSync("wsl.exe",["bash","-c","printenv KUBECONFIG"]);if(Y.status===0&&Y.stdout.length>0){let G=PO0.spawnSync("wsl.exe",["cat",Y.stdout.toString("utf8")]);if(G.status===0){this.loadFromString(G.stdout.toString("utf8"),$);return}}}catch{}try{let Y=PO0.spawnSync("wsl.exe",["cat","~/.kube/config"]);if(Y.status===0){this.loadFromString(Y.stdout.toString("utf8"),$);let G=PO0.spawnSync("wsl.exe",["wslpath","-w","~/.kube"]);if(G.status===0)this.makePathsAbsolute(G.stdout.toString("utf8"));return}}catch{}}if(yp0(xQ$)){this.loadFromCluster();return}this.loadFromClusterAndUser({name:"cluster",server:"http://localhost:8080"},{name:"user"})}makeApiClient($){let Z=this.getCurrentCluster();if(!Z)throw Error("No active cluster!");let X={default:this},Q=new iB0(Z.server,{}),Y=ti0({baseServer:Q,authMethods:X});return new $(Y)}makePathsAbsolute($){this.clusters.forEach((Z)=>{if(Z.caFile)Z.caFile=gp0($,Z.caFile)}),this.users.forEach((Z)=>{if(Z.certFile)Z.certFile=gp0($,Z.certFile);if(Z.keyFile)Z.keyFile=gp0($,Z.keyFile)})}exportConfig(){let $={apiVersion:"v1",kind:"Config",clusters:this.clusters.map(FZ$),users:this.users.map(NZ$),contexts:this.contexts.map(BZ$),preferences:{},"current-context":this.getCurrentContext()};return JSON.stringify($)}getCurrentContextObject(){return this.getContextObject(this.currentContext)}createAgent($,Z){var X,Q;let Y;if($&&$.proxyUrl)if($.proxyUrl.startsWith("socks"))Y=new gQ$.SocksProxyAgent($.proxyUrl,Z);else if($.server.startsWith("https")){let G=Z;G.proxy=$.proxyUrl,Y=new fQ$(G)}else if($.server.startsWith("http")){let G=Z;G.proxy=$.proxyUrl,Y=new vQ$(G)}else throw Error("Unsupported proxy type");else if(((X=$===null||$===void 0?void 0:$.server)===null||X===void 0?void 0:X.startsWith("http:"))&&$.skipTLSVerify)Y=new bJ4.Agent(Z);else if(((Q=$===null||$===void 0?void 0:$.server)===null||Q===void 0?void 0:Q.startsWith("http:"))&&!$.skipTLSVerify)throw Error("HTTP protocol is not allowed when skipTLSVerify is not set or false");else Y=new fJ4.Agent(Z);return Y}applyHTTPSOptions($){var Z;let X=this.getCurrentCluster(),Q=this.getCurrentUser();if(!Q)return;if(X!=null&&X.skipTLSVerify)$.rejectUnauthorized=!1;if(X!=null&&X.tlsServerName)$.servername=X.tlsServerName;let Y=X!=null?hp0(X.caFile,X.caData):null;if(Y)$.ca=Y;let G=hp0(Q.certFile,Q.certData);if(G)$.cert=G;let J=hp0(Q.keyFile,Q.keyData);if(J)$.key=J;if(Q.impersonateUser!=null)(Z=$.headers)!==null&&Z!==void 0||($.headers={}),$.headers["Impersonate-User"]=Q.impersonateUser}async applyAuthorizationHeader($){let Z=this.getCurrentUser();if(!Z)return;let X=this.authenticators.find((Q)=>{return Q.isAuthProvider(Z)});if(!X)X=this.custom_authenticators.find((Q)=>{return Q.isAuthProvider(Z)});if(!$.headers)$.headers={};if(X)await X.applyAuthentication(Z,$);if(Z.token)$.headers.Authorization=`Bearer ${Z.token}`}async applyOptions($){this.applyHTTPSOptions($),await this.applyAuthorizationHeader($)}}function gp0($,Z){if(!$||BC.isAbsolute(Z))return Z;return BC.join($,Z)}function hp0($,Z){if($)return nH.readFileSync($);if(Z)return Buffer.from(Z,"base64");return null}function yQ$($){return $.reduce((Z,X)=>{if(X&&!Z.includes(X))return Z.concat(X);else return Z},[])}function uJ4($=process.platform){if($!=="win32"){if(process.env.HOME)try{return nH.accessSync(process.env.HOME),process.env.HOME}catch{}return null}let Z=process.env.HOMEDRIVE&&process.env.HOMEPATH?BC.join(process.env.HOMEDRIVE,process.env.HOMEPATH):"",X=process.env.HOME||"",Q=process.env.USERPROFILE||"",Y=yQ$([X,Z,Q]),G=yQ$([X,Q,Z]);for(let J of Y)try{return nH.accessSync(BC.join(J,".kube","config")),J}catch{}for(let J of G)try{return nH.accessSync(J,nH.constants.W_OK),J}catch{}for(let J of G)try{return nH.accessSync(J),J}catch{}return G[0]||null}function up0($,Z,X){if(!$)return null;for(let Q of $)if(Q.name===Z){if(Q[X])return Q[X].name=Z,Q[X];return Q}return null}var gQ$,lp0="/var/run/secrets/kubernetes.io/serviceaccount",gJ4,xQ$,hJ4;var hQ$=D(()=>{vi0();WZ$();OZ$();DZ$();wZ$();LZ$();aB0();PX$();bQ$();gQ$=V(MQ$(),1),gJ4=lp0+"/ca.crt",xQ$=lp0+"/token",hJ4=lp0+"/namespace"});import{STATUS_CODES as lJ4}from"http";import{createInterface as cJ4}from"readline";import dJ4 from"node-fetch";class cp0{constructor($){this.config=$}async watch($,Z,X,Q){let Y=this.config.getCurrentCluster();if(!Y)throw Error("No currently active cluster");let G=new URL(Y.server+$);G.searchParams.set("watch","true");for(let[N,U]of Object.entries(Z||{}))if(U!==void 0)G.searchParams.set(N,U.toString());let J=await this.config.applyToFetchOptions({}),W=new AbortController,K=AbortSignal.timeout(30000);J.signal=AbortSignal.any([W.signal,K]),J.signal=W.signal,J.method="GET";let F=!1,H=(N)=>{if(!F)F=!0,W.abort(),Q(N)};try{let N=await dJ4(G,J);if(J.agent&&typeof J.agent==="object")for(let U of Object.values(J.agent.sockets).flat())U===null||U===void 0||U.setKeepAlive(!0,30000);if(N.status===200){let U=N.body;U.on("error",H),U.on("close",()=>H(null)),U.on("finish",()=>H(null));let B=cJ4(U);B.on("error",H),B.on("close",()=>H(null)),B.on("finish",()=>H(null)),B.on("line",(O)=>{try{let w=JSON.parse(O.toString());X(w.type,w.object,w)}catch{}})}else{let U=N.statusText||lJ4[N.status]||"Internal Server Error",B=Error(U);throw B.statusCode=N.status,B}}catch(N){H(N)}return W}}var dp0=D(()=>{cp0.SERVER_SIDE_CLOSE={error:"Connection closed on server"}});var mp0=D(()=>{ip0();dp0()});class c3{serialize(){let $={};for(let Z of c3.attributeTypeMap)if(this[Z.baseName]!==void 0)$[Z.name]=T1.serialize(this[Z.baseName],Z.type,Z.format);for(let[Z,X]of Object.entries(this)){if(c3.attributeTypeMap.find((Q)=>Q.name===Z))continue;$[Z]=X}return $}static fromUnknown($){if(!TO0($))throw Error(`Unable to deseriliaze non-Kubernetes object ${$}.`);let Z=new c3;for(let X of c3.attributeTypeMap)if($[X.baseName]!==void 0)Z[X.name]=T1.deserialize($[X.baseName],X.type,X.format);for(let[X,Q]of Object.entries($)){if(c3.attributeTypeMap.find((Y)=>Y.name===X))continue;Z[X]=Q}return Z}}var TO0=($)=>!!$&&typeof $==="object"&&("apiVersion"in $)&&("kind"in $),uQ$=({group:$,version:Z})=>[$,Z].join("/"),mJ4=($)=>{let[Z,X]=$.apiVersion.split("/");return{kind:$.kind,group:X?Z:"",version:X?X:Z}},xO;var RO0=D(()=>{r1();c3.attributeTypeMap=[{name:"apiVersion",baseName:"apiVersion",type:"string",format:""},{name:"kind",baseName:"kind",type:"string",format:""},{name:"metadata",baseName:"metadata",type:"V1ObjectMeta",format:""}];xO=class xO extends T1{static registerModel($,Z){var X,Q;let Y=uQ$($),G=(X=(Q=this.modelRegistry)[Y])!==null&&X!==void 0?X:Q[Y]={};if(G[$.kind])throw Error(`Kind ${$.kind} of ${Y} is already defined`);G[$.kind]=Z}static clearModelRegistry(){this.modelRegistry={}}static getSerializerForObject($){var Z;if(!TO0($))return;let X=mJ4($);return(Z=xO.modelRegistry[uQ$(X)])===null||Z===void 0?void 0:Z[X.kind]}static serialize($,Z,X=""){let Q=xO.getSerializerForObject($);if(Q)return Q.serialize($,Z,X);if($ instanceof c3)return $.serialize();let Y=T1.serialize($,Z,X);if(Y!==$)return Y;if(!TO0($))return Y;let G={};for(let J of c3.attributeTypeMap)if($[J.baseName]!==void 0)G[J.name]=T1.serialize($[J.baseName],J.type,J.format);for(let[J,W]of Object.entries($)){if(c3.attributeTypeMap.find((K)=>K.name===J))continue;G[J]=W}return G}static deserialize($,Z,X=""){let Q=xO.getSerializerForObject($);if(Q)return Q.deserialize($,Z,X);let Y=T1.deserialize($,Z,X);if(Y!==$)return Y;if(!TO0($))return Y;return c3.fromUnknown($)}};xO.modelRegistry={}});var ip0=D(()=>{mp0();RO0()});var IO0=D(()=>{aB0()});var pp0=()=>{};import lQ$ from"ws"with{type:"jsx"};class z5{static supportsClose($){return $==="v5.channel.k8s.io"}static closeStream($,Z){switch($){case z5.StdinStream:Z.stdin.pause();break;case z5.StdoutStream:Z.stdout.end();break;case z5.StderrStream:Z.stderr.end();break}}static handleStandardStreams($,Z,X,Q){if(Z.length<1)return null;if(X&&$===z5.StdoutStream)X.write(Z);else if(Q&&$===z5.StderrStream)Q.write(Z);else if($===z5.StatusStream){if(X&&X!==process.stdout)X.end();if(Q&&Q!==process.stderr)Q.end();return JSON.parse(Z.toString("utf8"))}else throw Error("Unknown stream: "+$);return null}static handleStandardInput($,Z,X=0){return Z.on("data",(Q)=>{$.send(dQ$(X,Q,Z.readableEncoding))}),Z.on("end",()=>{if(z5.supportsClose($.protocol)){let Q=Buffer.alloc(2);Q.writeUint8(this.CloseStream,0),Q.writeUint8(this.StdinStream,1),$.send(Q);return}$.close()}),!0}static async processData($,Z,X,Q=0,Y=3,G){let J=dQ$(Q,$,G),W=0;for(;W<Y;++W)if(Z!==null&&Z.readyState===lQ$.OPEN){Z.send(J);break}else Z=await X();if(W>=Y)throw Error("can't send data to ws");return Z}static restartableHandleStandardInput($,Z,X=0,Q=3,Y=!1){if(Q<0)throw Error("retryCount can't be lower than 0.");let G=Promise.resolve(),J=null;if(Z.on("data",(W)=>{G=G.then(async()=>{J=await z5.processData(W,J,$,X,Q,Z.readableEncoding)})}),Y)Z.on("flush",async()=>{await G});return Z.on("end",()=>{if(J!==null)J.close()}),()=>J}constructor($,Z,X={stdin:process.stdin,stdout:process.stdout,stderr:process.stderr}){this.config=$,this.socketFactory=Z,this.streams=X}async connect($,Z,X){let Q=this.config.getCurrentCluster();if(!Q)throw Error("No cluster is defined.");let Y=Q.server,G=Y.startsWith("https://"),J=G?Y.substr(8):Y.substr(7),K=`${G?"wss":"ws"}://${J}${$}`,F={};return await this.config.applyToHTTPSOptions(F),await new Promise((H,N)=>{let U=this.socketFactory?this.socketFactory(K,cQ$,F):new lQ$(K,cQ$,F),B=!1;U.onopen=()=>{B=!0,H(U)},U.onerror=(O)=>{if(!B)N(O)},U.onmessage=({data:O})=>{if(typeof O==="string"){if(O.charCodeAt(0)===z5.CloseStream)z5.closeStream(O.charCodeAt(1),this.streams);if(Z&&!Z(O))U.close()}else if(O instanceof Buffer){let w=O.readUint8(0);if(w===z5.CloseStream)z5.closeStream(O.readInt8(1),this.streams);if(X&&!X(w,O.slice(1)))U.close()}}})}}function dQ$($,Z,X){let Q;if(Z instanceof Buffer)Q=Buffer.alloc(Z.length+1),Z.copy(Q,1);else{X!==null&&X!==void 0||(X="utf-8");let Y=Buffer.byteLength(Z,X);Q=Buffer.alloc(Y+1),Q.write(Z,1,Y,X)}return Q.writeInt8($,0),Q}var cQ$;var qO0=D(()=>{cQ$=["v5.channel.k8s.io","v4.channel.k8s.io","v3.channel.k8s.io","v2.channel.k8s.io","channel.k8s.io"];z5.StdinStream=0;z5.StdoutStream=1;z5.StderrStream=2;z5.StatusStream=3;z5.ResizeStream=4;z5.CloseStream=255});var mQ$=D(()=>{pp0();qO0()});var np0=D(()=>{pp0();qO0()});import nJ4 from"querystring";class tp0{constructor($,Z,X){this.handler=X||new z5($),this.disconnectOnErr=Z===void 0?!0:Z}async portForward($,Z,X,Q,Y,G,J=0){if(X.length===0)throw Error("You must provide at least one port to forward to.");if(X.length>1)throw Error("Only one port is currently supported for port-forward");let W={ports:X[0]},K=nJ4.stringify(W),F=[];X.forEach((U,B)=>{F[B*2]=!0,F[B*2+1]=!0});let H=`/api/v1/namespaces/${$}/pods/${Z}/portforward?${K}`,N=()=>{return this.handler.connect(H,null,(U,B)=>{if(U>=X.length*2)return!this.disconnectOnErr;if(F[U])B=B.slice(2),F[U]=!1;if(U%2===1){if(Y)Y.write(B)}else Q.write(B);return!0})};if(J<1){let U=await N();return z5.handleStandardInput(U,G,0),U}return z5.restartableHandleStandardInput(N,G,0,J)}}var iQ$=D(()=>{qO0()});var pQ$=()=>{};var nQ$=D(()=>{vi0();RO0()});var tQ$=D(()=>{IO0()});var oQ$=()=>{};var MO0=_((EP9,rQ$)=>{rQ$.exports={DEFAULT_INITIAL_SIZE:8192,DEFAULT_INCREMENT_AMOUNT:8192,DEFAULT_FREQUENCY:1,DEFAULT_CHUNK_SIZE:1024}});var eQ$=_((jP9,sQ$)=>{var aQ$=P0("stream"),kO0=MO0(),rJ4=P0("util"),aJ4=sQ$.exports=function($){var Z=this;$=$||{},aQ$.Readable.call(this,$),this.stopped=!1;var X=$.hasOwnProperty("frequency")?$.frequency:kO0.DEFAULT_FREQUENCY,Q=$.chunkSize||kO0.DEFAULT_CHUNK_SIZE,Y=$.initialSize||kO0.DEFAULT_INITIAL_SIZE,G=$.incrementAmount||kO0.DEFAULT_INCREMENT_AMOUNT,J=0,W=new Buffer(Y),K=!1,F=function(){var U=Math.min(Q,J),B=!1;if(U>0){var O=null;O=new Buffer(U),W.copy(O,0,0,U),B=Z.push(O)!==!1,K=B,W.copy(W,0,U,J),J-=U}if(J===0&&Z.stopped)Z.push(null);if(B)F.timeout=setTimeout(F,X);else F.timeout=null};this.stop=function(){if(this.stopped)throw Error("stop() called on already stopped ReadableStreamBuffer");if(this.stopped=!0,J===0)this.push(null)},this.size=function(){return J},this.maxSize=function(){return W.length};var H=function(U){if(W.length-J<U){var B=Math.ceil((U-(W.length-J))/G),O=new Buffer(W.length+G*B);W.copy(O,0,0,J),W=O}},N=function(){if(!F.timeout&&K)F.timeout=setTimeout(F,X)};this.put=function(U,B){if(Z.stopped)throw Error("Tried to write data to a stopped ReadableStreamBuffer");if(Buffer.isBuffer(U))H(U.length),U.copy(W,J,0),J+=U.length;else{U=U+"";var O=Buffer.byteLength(U);H(O),W.write(U,J,B||"utf8"),J+=O}N()},this._read=function(){K=!0,N()}};rJ4.inherits(aJ4,aQ$.Readable)});var QY$=_((zP9,XY$)=>{var sJ4=P0("util"),ZY$=P0("stream"),$Y$=MO0(),eJ4=XY$.exports=function($){$=$||{},$.decodeStrings=!0,ZY$.Writable.call(this,$);var Z=$.initialSize||$Y$.DEFAULT_INITIAL_SIZE,X=$.incrementAmount||$Y$.DEFAULT_INCREMENT_AMOUNT,Q=new Buffer(Z),Y=0;this.size=function(){return Y},this.maxSize=function(){return Q.length},this.getContents=function(J){if(!Y)return!1;var W=new Buffer(Math.min(J||Y,Y));if(Q.copy(W,0,0,W.length),W.length<Y)Q.copy(Q,0,W.length);return Y-=W.length,W},this.getContentsAsString=function(J,W){if(!Y)return!1;var K=Q.toString(J||"utf8",0,Math.min(W||Y,Y)),F=Buffer.byteLength(K);if(F<Y)Q.copy(Q,0,F);return Y-=F,K};var G=function(J){if(Q.length-Y<J){var W=Math.ceil((J-(Q.length-Y))/X),K=new Buffer(Q.length+X*W);Q.copy(K,0,0,Y),Q=K}};this._write=function(J,W,K){G(J.length),J.copy(Q,Y,0),Y+=J.length,K()}};sJ4.inherits(eJ4,ZY$.Writable)});var YY$=_((PP9,VO0)=>{VO0.exports=MO0();VO0.exports.ReadableStreamBuffer=eQ$();VO0.exports.WritableStreamBuffer=QY$()});var JY$=_((AP9,GY$)=>{GY$.exports=class{constructor(Z){if(!(Z>0)||(Z-1&Z)!==0)throw Error("Max size for a FixedFIFO should be a power of two");this.buffer=Array(Z),this.mask=Z-1,this.top=0,this.btm=0,this.next=null}clear(){this.top=this.btm=0,this.next=null,this.buffer.fill(void 0)}push(Z){if(this.buffer[this.top]!==void 0)return!1;return this.buffer[this.top]=Z,this.top=this.top+1&this.mask,!0}shift(){let Z=this.buffer[this.btm];if(Z===void 0)return;return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,Z}peek(){return this.buffer[this.btm]}isEmpty(){return this.buffer[this.btm]===void 0}}});var op0=_((TP9,KY$)=>{var WY$=JY$();KY$.exports=class{constructor(Z){this.hwm=Z||16,this.head=new WY$(this.hwm),this.tail=this.head,this.length=0}clear(){this.head=this.tail,this.head.clear(),this.length=0}push(Z){if(this.length++,!this.head.push(Z)){let X=this.head;this.head=X.next=new WY$(2*this.head.buffer.length),this.head.push(Z)}}shift(){if(this.length!==0)this.length--;let Z=this.tail.shift();if(Z===void 0&&this.tail.next){let X=this.tail.next;return this.tail.next=null,this.tail=X,this.tail.shift()}return Z}peek(){let Z=this.tail.peek();if(Z===void 0&&this.tail.next)return this.tail.next.peek();return Z}isEmpty(){return this.length===0}}});var cy=_((RP9,FY$)=>{function $34($){return Buffer.isBuffer($)||$ instanceof Uint8Array}function Z34($){return Buffer.isEncoding($)}function X34($,Z,X){return Buffer.alloc($,Z,X)}function Q34($){return Buffer.allocUnsafe($)}function Y34($){return Buffer.allocUnsafeSlow($)}function G34($,Z){return Buffer.byteLength($,Z)}function J34($,Z){return Buffer.compare($,Z)}function W34($,Z){return Buffer.concat($,Z)}function K34($,Z,X,Q,Y){return x6($).copy(Z,X,Q,Y)}function F34($,Z){return x6($).equals(Z)}function H34($,Z,X,Q,Y){return x6($).fill(Z,X,Q,Y)}function N34($,Z,X){return Buffer.from($,Z,X)}function U34($,Z,X,Q){return x6($).includes(Z,X,Q)}function B34($,Z,X,Q){return x6($).indexOf(Z,X,Q)}function O34($,Z,X,Q){return x6($).lastIndexOf(Z,X,Q)}function D34($){return x6($).swap16()}function w34($){return x6($).swap32()}function L34($){return x6($).swap64()}function x6($){if(Buffer.isBuffer($))return $;return Buffer.from($.buffer,$.byteOffset,$.byteLength)}function E34($,Z,X,Q){return x6($).toString(Z,X,Q)}function j34($,Z,X,Q,Y){return x6($).write(Z,X,Q,Y)}function z34($,Z){return x6($).readDoubleBE(Z)}function P34($,Z){return x6($).readDoubleLE(Z)}function A34($,Z){return x6($).readFloatBE(Z)}function T34($,Z){return x6($).readFloatLE(Z)}function R34($,Z){return x6($).readInt32BE(Z)}function I34($,Z){return x6($).readInt32LE(Z)}function q34($,Z){return x6($).readUInt32BE(Z)}function M34($,Z){return x6($).readUInt32LE(Z)}function k34($,Z,X){return x6($).writeDoubleBE(Z,X)}function V34($,Z,X){return x6($).writeDoubleLE(Z,X)}function S34($,Z,X){return x6($).writeFloatBE(Z,X)}function C34($,Z,X){return x6($).writeFloatLE(Z,X)}function _34($,Z,X){return x6($).writeInt32BE(Z,X)}function v34($,Z,X){return x6($).writeInt32LE(Z,X)}function f34($,Z,X){return x6($).writeUInt32BE(Z,X)}function b34($,Z,X){return x6($).writeUInt32LE(Z,X)}FY$.exports={isBuffer:$34,isEncoding:Z34,alloc:X34,allocUnsafe:Q34,allocUnsafeSlow:Y34,byteLength:G34,compare:J34,concat:W34,copy:K34,equals:F34,fill:H34,from:N34,includes:U34,indexOf:B34,lastIndexOf:O34,swap16:D34,swap32:w34,swap64:L34,toBuffer:x6,toString:E34,write:j34,readDoubleBE:z34,readDoubleLE:P34,readFloatBE:A34,readFloatLE:T34,readInt32BE:R34,readInt32LE:I34,readUInt32BE:q34,readUInt32LE:M34,writeDoubleBE:k34,writeDoubleLE:V34,writeFloatBE:S34,writeFloatLE:C34,writeInt32BE:_34,writeInt32LE:v34,writeUInt32BE:f34,writeUInt32LE:b34}});var NY$=_((IP9,HY$)=>{var x34=cy();HY$.exports=class{constructor(Z){this.encoding=Z}get remaining(){return 0}decode(Z){return x34.toString(Z,this.encoding)}flush(){return""}}});var DY$=_((qP9,OY$)=>{var UY$=cy();OY$.exports=class{constructor(){this._reset()}get remaining(){return this.bytesSeen}decode(Z){if(Z.byteLength===0)return"";if(this.bytesNeeded===0&&BY$(Z,0)===0)return this.bytesSeen=y34(Z),UY$.toString(Z,"utf8");let X="",Q=0;if(this.bytesNeeded>0){while(Q<Z.byteLength){let J=Z[Q];if(J<this.lowerBoundary||J>this.upperBoundary){X+="\uFFFD",this._reset();break}if(this.lowerBoundary=128,this.upperBoundary=191,this.codePoint=this.codePoint<<6|J&63,this.bytesSeen++,Q++,this.bytesSeen===this.bytesNeeded){X+=String.fromCodePoint(this.codePoint),this._reset();break}}if(this.bytesNeeded>0)return X}let Y=BY$(Z,Q),G=Z.byteLength-Y;if(G>Q)X+=UY$.toString(Z,"utf8",Q,G);for(let J=G;J<Z.byteLength;J++){let W=Z[J];if(this.bytesNeeded===0){if(W<=127)this.bytesSeen=0,X+=String.fromCharCode(W);else if(W>=194&&W<=223)this.bytesNeeded=2,this.bytesSeen=1,this.codePoint=W&31;else if(W>=224&&W<=239){if(W===224)this.lowerBoundary=160;else if(W===237)this.upperBoundary=159;this.bytesNeeded=3,this.bytesSeen=1,this.codePoint=W&15}else if(W>=240&&W<=244){if(W===240)this.lowerBoundary=144;else if(W===244)this.upperBoundary=143;this.bytesNeeded=4,this.bytesSeen=1,this.codePoint=W&7}else this.bytesSeen=1,X+="\uFFFD";continue}if(W<this.lowerBoundary||W>this.upperBoundary){X+="\uFFFD",J--,this._reset();continue}if(this.lowerBoundary=128,this.upperBoundary=191,this.codePoint=this.codePoint<<6|W&63,this.bytesSeen++,this.bytesSeen===this.bytesNeeded)X+=String.fromCodePoint(this.codePoint),this._reset()}return X}flush(){let Z=this.bytesNeeded>0?"\uFFFD":"";return this._reset(),Z}_reset(){this.codePoint=0,this.bytesNeeded=0,this.bytesSeen=0,this.lowerBoundary=128,this.upperBoundary=191}};function BY$($,Z){let X=$.byteLength;if(X<=Z)return 0;let Q=Math.max(Z,X-4),Y=X-1;while(Y>Q&&($[Y]&192)===128)Y--;if(Y<Z)return 0;let G=$[Y],J;if(G<=127)return 0;if(G>=194&&G<=223)J=2;else if(G>=224&&G<=239)J=3;else if(G>=240&&G<=244)J=4;else return 0;let W=X-Y;return W<J?W:0}function y34($){let Z=$.byteLength;if(Z===0)return 0;let X=$[Z-1];if(X<=127)return 0;if((X&192)!==128)return 1;let Q=Math.max(0,Z-4),Y=Z-2;while(Y>=Q&&($[Y]&192)===128)Y--;if(Y<0)return 1;let G=$[Y],J;if(G>=194&&G<=223)J=2;else if(G>=224&&G<=239)J=3;else if(G>=240&&G<=244)J=4;else return 1;if(Z-Y!==J)return 1;if(J>=3){let W=$[Y+1];if(G===224&&W<160)return 1;if(G===237&&W>159)return 1;if(G===240&&W<144)return 1;if(G===244&&W>143)return 1}return 0}});var LY$=_((MP9,wY$)=>{var g34=NY$(),h34=DY$();wY$.exports=class{constructor(Z="utf8"){switch(this.encoding=u34(Z),this.encoding){case"utf8":this.decoder=new h34;break;case"utf16le":case"base64":throw Error("Unsupported encoding: "+this.encoding);default:this.decoder=new g34(this.encoding)}}get remaining(){return this.decoder.remaining}push(Z){if(typeof Z==="string")return Z;return this.decoder.decode(Z)}write(Z){return this.push(Z)}end(Z){let X="";if(Z)X=this.push(Z);return X+=this.decoder.flush(),X}};function u34($){switch($=$.toLowerCase(),$){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return $;default:throw Error("Unknown encoding: "+$)}}});var Zn0=_((kP9,VY$)=>{var{EventEmitter:l34}=P0("events"),CO0=Error("Stream was destroyed"),rp0=Error("Premature close"),jY$=op0(),c34=LY$(),ap0=typeof queueMicrotask>"u"?($)=>global.process.nextTick($):queueMicrotask,SO0=Symbol.asyncIterator||Symbol("asyncIterator");class sp0{constructor($,{highWaterMark:Z=16384,map:X=null,mapWritable:Q,byteLength:Y,byteLengthWritable:G}={}){this.stream=$,this.queue=new jY$,this.highWaterMark=Z,this.buffered=0,this.error=null,this.pipeline=null,this.drains=null,this.byteLength=G||Y||kY$,this.map=Q||X,this.afterWrite=i34.bind(this),this.afterUpdateNextTick=t34.bind(this)}get ending(){return(this.stream._duplexState&134217728)!==0}get ended(){return(this.stream._duplexState&8388608)!==0}push($){if((this.stream._duplexState&142606350)!==0)return!1;if(this.map!==null)$=this.map($);if(this.buffered+=this.byteLength($),this.queue.push($),this.buffered<this.highWaterMark)return this.stream._duplexState|=2097152,!0;return this.stream._duplexState|=6291456,!1}shift(){let $=this.queue.shift();if(this.buffered-=this.byteLength($),this.buffered===0)this.stream._duplexState&=534773759;return $}end($){if(typeof $==="function")this.stream.once("finish",$);else if($!==void 0&&$!==null)this.push($);this.stream._duplexState=(this.stream._duplexState|134217728)&535822335}autoBatch($,Z){let X=[],Q=this.stream;X.push($);while((Q._duplexState&270794767)===2359296)X.push(Q._writableState.shift());if((Q._duplexState&15)!==0)return Z(null);Q._writev(X,Z)}update(){let $=this.stream;$._duplexState|=524288;do{while(($._duplexState&270794767)===2097152){let Z=this.shift();$._duplexState|=67371008,$._write(Z,this.afterWrite)}if(($._duplexState&1310720)===0)this.updateNonPrimary()}while(this.continueUpdate()===!0);$._duplexState&=536346623}updateNonPrimary(){let $=this.stream;if(($._duplexState&144965647)===134217728){$._duplexState=$._duplexState|262144,$._final(m34.bind(this));return}if(($._duplexState&14)===4){if(($._duplexState&33587200)===0)$._duplexState|=262160,$._destroy(TY$.bind(this));return}if(($._duplexState&33587215)===1)$._duplexState=($._duplexState|262160)&536870910,$._open(RY$.bind(this))}continueUpdate(){if((this.stream._duplexState&33554432)===0)return!1;return this.stream._duplexState&=503316479,!0}updateCallback(){if((this.stream._duplexState&35127311)===1048576)this.update();else this.updateNextTick()}updateNextTick(){if((this.stream._duplexState&33554432)!==0)return;if(this.stream._duplexState|=33554432,(this.stream._duplexState&524288)===0)ap0(this.afterUpdateNextTick)}}class zY${constructor($,{highWaterMark:Z=16384,map:X=null,mapReadable:Q,byteLength:Y,byteLengthReadable:G}={}){this.stream=$,this.queue=new jY$,this.highWaterMark=Z===0?1:Z,this.buffered=0,this.readAhead=Z>0,this.error=null,this.pipeline=null,this.byteLength=G||Y||kY$,this.map=Q||X,this.pipeTo=null,this.afterRead=p34.bind(this),this.afterUpdateNextTick=n34.bind(this)}get ending(){return(this.stream._duplexState&1024)!==0}get ended(){return(this.stream._duplexState&16384)!==0}pipe($,Z){if(this.pipeTo!==null)throw Error("Can only pipe to one destination");if(typeof Z!=="function")Z=null;if(this.stream._duplexState|=512,this.pipeTo=$,this.pipeline=new AY$(this.stream,$,Z),Z)this.stream.on("error",EY$);if(Tn($)){if($._writableState.pipeline=this.pipeline,Z)$.on("error",EY$);$.on("finish",this.pipeline.finished.bind(this.pipeline))}else{let X=this.pipeline.done.bind(this.pipeline,$),Q=this.pipeline.done.bind(this.pipeline,$,null);$.on("error",X),$.on("close",Q),$.on("finish",this.pipeline.finished.bind(this.pipeline))}$.on("drain",d34.bind(this)),this.stream.emit("piping",$),$.emit("pipe",this.stream)}push($){let Z=this.stream;if($===null)return this.highWaterMark=0,Z._duplexState=(Z._duplexState|1024)&536805311,!1;if(this.map!==null){if($=this.map($),$===null)return Z._duplexState&=536805375,this.buffered<this.highWaterMark}return this.buffered+=this.byteLength($),this.queue.push($),Z._duplexState=(Z._duplexState|128)&536805375,this.buffered<this.highWaterMark}shift(){let $=this.queue.shift();if(this.buffered-=this.byteLength($),this.buffered===0)this.stream._duplexState&=536862591;return $}unshift($){let Z=[this.map!==null?this.map($):$];while(this.buffered>0)Z.push(this.shift());for(let X=0;X<Z.length-1;X++){let Q=Z[X];this.buffered+=this.byteLength(Q),this.queue.push(Q)}this.push(Z[Z.length-1])}read(){let $=this.stream;if(($._duplexState&16527)===128){let Z=this.shift();if(this.pipeTo!==null&&this.pipeTo.write(Z)===!1)$._duplexState&=536870143;if(($._duplexState&2048)!==0)$.emit("data",Z);return Z}if(this.readAhead===!1)$._duplexState|=131072,this.updateNextTick();return null}drain(){let $=this.stream;while(($._duplexState&16527)===128&&($._duplexState&768)!==0){let Z=this.shift();if(this.pipeTo!==null&&this.pipeTo.write(Z)===!1)$._duplexState&=536870143;if(($._duplexState&2048)!==0)$.emit("data",Z)}}update(){let $=this.stream;$._duplexState|=32;do{this.drain();while(this.buffered<this.highWaterMark&&($._duplexState&214047)===131072)$._duplexState|=65552,$._read(this.afterRead),this.drain();if(($._duplexState&12431)===4224)$._duplexState|=8192,$.emit("readable");if(($._duplexState&80)===0)this.updateNonPrimary()}while(this.continueUpdate()===!0);$._duplexState&=536870879}updateNonPrimary(){let $=this.stream;if(($._duplexState&1167)===1024){if($._duplexState=($._duplexState|16384)&536869887,$.emit("end"),($._duplexState&8405006)===8404992)$._duplexState|=4;if(this.pipeTo!==null)this.pipeTo.end()}if(($._duplexState&14)===4){if(($._duplexState&33587200)===0)$._duplexState|=262160,$._destroy(TY$.bind(this));return}if(($._duplexState&33587215)===1)$._duplexState=($._duplexState|262160)&536870910,$._open(RY$.bind(this))}continueUpdate(){if((this.stream._duplexState&32768)===0)return!1;return this.stream._duplexState&=536838143,!0}updateCallback(){if((this.stream._duplexState&32879)===64)this.update();else this.updateNextTick()}updateNextTickIfOpen(){if((this.stream._duplexState&32769)!==0)return;if(this.stream._duplexState|=32768,(this.stream._duplexState&32)===0)ap0(this.afterUpdateNextTick)}updateNextTick(){if((this.stream._duplexState&32768)!==0)return;if(this.stream._duplexState|=32768,(this.stream._duplexState&32)===0)ap0(this.afterUpdateNextTick)}}class PY${constructor($){this.data=null,this.afterTransform=r34.bind($),this.afterFinal=null}}class AY${constructor($,Z,X){this.from=$,this.to=Z,this.afterPipe=X,this.error=null,this.pipeToFinished=!1}finished(){this.pipeToFinished=!0}done($,Z){if(Z)this.error=Z;if($===this.to){if(this.to=null,this.from!==null){if((this.from._duplexState&16384)===0||!this.pipeToFinished)this.from.destroy(this.error||Error("Writable stream closed prematurely"));return}}if($===this.from){if(this.from=null,this.to!==null){if(($._duplexState&16384)===0)this.to.destroy(this.error||Error("Readable stream closed before ending"));return}}if(this.afterPipe!==null)this.afterPipe(this.error);this.to=this.from=this.afterPipe=null}}function d34(){this.stream._duplexState|=512,this.updateCallback()}function m34($){let Z=this.stream;if($)Z.destroy($);if((Z._duplexState&14)===0)Z._duplexState|=8388608,Z.emit("finish");if((Z._duplexState&8405006)===8404992)Z._duplexState|=4;if(Z._duplexState&=402391039,(Z._duplexState&524288)===0)this.update();else this.updateNextTick()}function TY$($){let Z=this.stream;if(!$&&this.error!==CO0)$=this.error;if($)Z.emit("error",$);Z._duplexState|=8,Z.emit("close");let{_readableState:X,_writableState:Q}=Z;if(X!==null&&X.pipeline!==null)X.pipeline.done(Z,$);if(Q!==null){while(Q.drains!==null&&Q.drains.length>0)Q.drains.shift().resolve(!1);if(Q.pipeline!==null)Q.pipeline.done(Z,$)}}function i34($){let Z=this.stream;if($)Z.destroy($);if(Z._duplexState&=469499903,this.drains!==null)o34(this.drains);if((Z._duplexState&6553615)===4194304){if(Z._duplexState&=532676607,(Z._duplexState&16777216)===16777216)Z.emit("drain")}this.updateCallback()}function p34($){if($)this.stream.destroy($);if(this.stream._duplexState&=536870895,this.readAhead===!1&&(this.stream._duplexState&256)===0)this.stream._duplexState&=536739839;this.updateCallback()}function n34(){if((this.stream._duplexState&32)===0)this.stream._duplexState&=536838143,this.update()}function t34(){if((this.stream._duplexState&524288)===0)this.stream._duplexState&=503316479,this.update()}function o34($){for(let Z=0;Z<$.length;Z++)if(--$[Z].writes===0)$.shift().resolve(!0),Z--}function RY$($){let Z=this.stream;if($)Z.destroy($);if((Z._duplexState&4)===0){if((Z._duplexState&17423)===0)Z._duplexState|=64;if((Z._duplexState&142606351)===0)Z._duplexState|=1048576;Z.emit("open")}if(Z._duplexState&=536608751,Z._writableState!==null)Z._writableState.updateCallback();if(Z._readableState!==null)Z._readableState.updateCallback()}function r34($,Z){if(Z!==void 0&&Z!==null)this.push(Z);this._writableState.afterWrite($)}function a34($){if(this._readableState!==null){if($==="data")this._duplexState|=133376,this._readableState.updateNextTick();if($==="readable")this._duplexState|=4096,this._readableState.updateNextTick()}if(this._writableState!==null){if($==="drain")this._duplexState|=16777216,this._writableState.updateNextTick()}}class _O0 extends l34{constructor($){super();if(this._duplexState=0,this._readableState=null,this._writableState=null,$){if($.open)this._open=$.open;if($.destroy)this._destroy=$.destroy;if($.predestroy)this._predestroy=$.predestroy;if($.signal)$.signal.addEventListener("abort",FW4.bind(this))}this.on("newListener",a34)}_open($){$(null)}_destroy($){$(null)}_predestroy(){}get readable(){return this._readableState!==null?!0:void 0}get writable(){return this._writableState!==null?!0:void 0}get destroyed(){return(this._duplexState&8)!==0}get destroying(){return(this._duplexState&14)!==0}destroy($){if((this._duplexState&14)===0){if(!$)$=CO0;if(this._duplexState=(this._duplexState|4)&535822271,this._readableState!==null)this._readableState.highWaterMark=0,this._readableState.error=$;if(this._writableState!==null)this._writableState.highWaterMark=0,this._writableState.error=$;if(this._duplexState|=2,this._predestroy(),this._duplexState&=536870909,this._readableState!==null)this._readableState.updateNextTick();if(this._writableState!==null)this._writableState.updateNextTick()}}}class An extends _O0{constructor($){super($);if(this._duplexState|=8519681,this._readableState=new zY$(this,$),$){if(this._readableState.readAhead===!1)this._duplexState&=536739839;if($.read)this._read=$.read;if($.eagerOpen)this._readableState.updateNextTick();if($.encoding)this.setEncoding($.encoding)}}setEncoding($){let Z=new c34($),X=this._readableState.map||$W4;return this._readableState.map=Q,this;function Q(Y){let G=Z.push(Y);return G===""&&(Y.byteLength!==0||Z.remaining>0)?null:X(G)}}_read($){$(null)}pipe($,Z){return this._readableState.updateNextTick(),this._readableState.pipe($,Z),$}read(){return this._readableState.updateNextTick(),this._readableState.read()}push($){return this._readableState.updateNextTickIfOpen(),this._readableState.push($)}unshift($){return this._readableState.updateNextTickIfOpen(),this._readableState.unshift($)}resume(){return this._duplexState|=131328,this._readableState.updateNextTick(),this}pause(){return this._duplexState&=this._readableState.readAhead===!1?536739583:536870655,this}static _fromAsyncIterator($,Z){let X,Q=new An({...Z,read(G){$.next().then(Y).then(G.bind(null,null)).catch(G)},predestroy(){X=$.return()},destroy(G){if(!X)return G(null);X.then(G.bind(null,null)).catch(G)}});return Q;function Y(G){if(G.done)Q.push(null);else Q.push(G.value)}}static from($,Z){if(JW4($))return $;if($[SO0])return this._fromAsyncIterator($[SO0](),Z);if(!Array.isArray($))$=$===void 0?[]:[$];let X=0;return new An({...Z,read(Q){this.push(X===$.length?null:$[X++]),Q(null)}})}static isBackpressured($){return($._duplexState&17422)!==0||$._readableState.buffered>=$._readableState.highWaterMark}static isPaused($){return($._duplexState&256)===0}[SO0](){let $=this,Z=null,X=null,Q=null;return this.on("error",(K)=>{Z=K}),this.on("readable",Y),this.on("close",G),{[SO0](){return this},next(){return new Promise(function(K,F){X=K,Q=F;let H=$.read();if(H!==null)J(H);else if(($._duplexState&8)!==0)J(null)})},return(){return W(null)},throw(K){return W(K)}};function Y(){if(X!==null)J($.read())}function G(){if(X!==null)J(null)}function J(K){if(Q===null)return;if(Z)Q(Z);else if(K===null&&($._duplexState&16384)===0)Q(CO0);else X({value:K,done:K===null});Q=X=null}function W(K){return $.destroy(K),new Promise((F,H)=>{if($._duplexState&8)return F({value:void 0,done:!0});$.once("close",function(){if(K)H(K);else F({value:void 0,done:!0})})})}}}class ep0 extends _O0{constructor($){super($);if(this._duplexState|=16385,this._writableState=new sp0(this,$),$){if($.writev)this._writev=$.writev;if($.write)this._write=$.write;if($.final)this._final=$.final;if($.eagerOpen)this._writableState.updateNextTick()}}cork(){this._duplexState|=268435456}uncork(){this._duplexState&=268435455,this._writableState.updateNextTick()}_writev($,Z){Z(null)}_write($,Z){this._writableState.autoBatch($,Z)}_final($){$(null)}static isBackpressured($){return($._duplexState&146800654)!==0}static drained($){if($.destroyed)return Promise.resolve(!1);let Z=$._writableState,Q=(HW4($)?Math.min(1,Z.queue.length):Z.queue.length)+($._duplexState&67108864?1:0);if(Q===0)return Promise.resolve(!0);if(Z.drains===null)Z.drains=[];return new Promise((Y)=>{Z.drains.push({writes:Q,resolve:Y})})}write($){return this._writableState.updateNextTick(),this._writableState.push($)}end($){return this._writableState.updateNextTick(),this._writableState.end($),this}}class vO0 extends An{constructor($){super($);if(this._duplexState=1|this._duplexState&131072,this._writableState=new sp0(this,$),$){if($.writev)this._writev=$.writev;if($.write)this._write=$.write;if($.final)this._final=$.final}}cork(){this._duplexState|=268435456}uncork(){this._duplexState&=268435455,this._writableState.updateNextTick()}_writev($,Z){Z(null)}_write($,Z){this._writableState.autoBatch($,Z)}_final($){$(null)}write($){return this._writableState.updateNextTick(),this._writableState.push($)}end($){return this._writableState.updateNextTick(),this._writableState.end($),this}}class $n0 extends vO0{constructor($){super($);if(this._transformState=new PY$(this),$){if($.transform)this._transform=$.transform;if($.flush)this._flush=$.flush}}_write($,Z){if(this._readableState.buffered>=this._readableState.highWaterMark)this._transformState.data=$;else this._transform($,this._transformState.afterTransform)}_read($){if(this._transformState.data!==null){let Z=this._transformState.data;this._transformState.data=null,$(null),this._transform(Z,this._transformState.afterTransform)}else $(null)}destroy($){if(super.destroy($),this._transformState.data!==null)this._transformState.data=null,this._transformState.afterTransform()}_transform($,Z){Z(null,$)}_flush($){$(null)}_final($){this._transformState.afterFinal=$,this._flush(s34.bind(this))}}class IY$ extends $n0{}function s34($,Z){let X=this._transformState.afterFinal;if($)return X($);if(Z!==null&&Z!==void 0)this.push(Z);this.push(null),X(null)}function e34(...$){return new Promise((Z,X)=>{return qY$(...$,(Q)=>{if(Q)return X(Q);Z()})})}function qY$($,...Z){let X=Array.isArray($)?[...$,...Z]:[$,...Z],Q=X.length&&typeof X[X.length-1]==="function"?X.pop():null;if(X.length<2)throw Error("Pipeline requires at least 2 streams");let Y=X[0],G=null,J=null;for(let F=1;F<X.length;F++){if(G=X[F],Tn(Y))Y.pipe(G,K);else W(Y,!0,F>1,K),Y.pipe(G);Y=G}if(Q){let F=!1,H=Tn(G)||!!(G._writableState&&G._writableState.autoDestroy);if(G.on("error",(N)=>{if(J===null)J=N}),G.on("finish",()=>{if(F=!0,!H)Q(J)}),H)G.on("close",()=>Q(J||(F?null:rp0)))}return G;function W(F,H,N,U){F.on("error",U),F.on("close",B);function B(){if(H&&F._readableState&&!F._readableState.ended)return U(rp0);if(N&&F._writableState&&!F._writableState.ended)return U(rp0)}}function K(F){if(!F||J)return;J=F;for(let H of X)H.destroy(F)}}function $W4($){return $}function MY$($){return!!$._readableState||!!$._writableState}function Tn($){return typeof $._duplexState==="number"&&MY$($)}function ZW4($){return!!$._readableState&&$._readableState.ending}function XW4($){return!!$._readableState&&$._readableState.ended}function QW4($){return!!$._writableState&&$._writableState.ending}function YW4($){return!!$._writableState&&$._writableState.ended}function GW4($,Z={}){let X=$._readableState&&$._readableState.error||$._writableState&&$._writableState.error;return!Z.all&&X===CO0?null:X}function JW4($){return Tn($)&&$.readable}function WW4($){return($._duplexState&1)!==1||($._duplexState&4)===4||($._duplexState&33587200)!==0}function KW4($){return typeof $==="object"&&$!==null&&typeof $.byteLength==="number"}function kY$($){return KW4($)?$.byteLength:1024}function EY$(){}function FW4(){this.destroy(Error("Stream aborted."))}function HW4($){return $._writev!==ep0.prototype._writev&&$._writev!==vO0.prototype._writev}VY$.exports={pipeline:qY$,pipelinePromise:e34,isStream:MY$,isStreamx:Tn,isEnding:ZW4,isEnded:XW4,isFinishing:QW4,isFinished:YW4,isDisturbed:WW4,getStreamError:GW4,Stream:_O0,Writable:ep0,Readable:An,Duplex:vO0,Transform:$n0,PassThrough:IY$}});var Qn0=_((AW4)=>{var g4=cy(),SY$=g4.from([117,115,116,97,114,0]),NW4=g4.from([48,48]),UW4=g4.from([117,115,116,97,114,32]),BW4=g4.from([32,0]);AW4.decodeLongPath=function(Z,X){return dy(Z,0,Z.length,X)};AW4.encodePax=function(Z){let X="";if(Z.name)X+=Xn0(" path="+Z.name+`
978
978
  `);if(Z.linkname)X+=Xn0(" linkpath="+Z.linkname+`
979
979
  `);let Q=Z.pax;if(Q)for(let Y in Q)X+=Xn0(" "+Y+"="+Q[Y]+`
980
- `);return g4.from(X)};AW4.decodePax=function(Z){let X={};while(Z.length){let Q=0;while(Q<Z.length&&Z[Q]!==32)Q++;let Y=parseInt(g4.toString(Z.subarray(0,Q)),10);if(!Y)return X;let G=g4.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};AW4.encode=function(Z){let X=g4.alloc(512),Q=Z.name,Y="";if(Z.typeflag===5&&Q[Q.length-1]!=="/")Q+="/";if(g4.byteLength(Q)!==Q.length)return null;while(g4.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(g4.byteLength(Q)>100||g4.byteLength(Y)>155)return null;if(Z.linkname&&g4.byteLength(Z.linkname)>100)return null;if(g4.write(X,Q),g4.write(X,gO(Z.mode&4095,6),100),g4.write(X,gO(Z.uid,6),108),g4.write(X,gO(Z.gid,6),116),zW4(Z.size,X,124),g4.write(X,gO(Z.mtime.getTime()/1000|0,11),136),X[156]=48+EW4(Z.type),Z.linkname)g4.write(X,Z.linkname,157);if(g4.copy(SY$,X,257),g4.copy(NW4,X,263),Z.uname)g4.write(X,Z.uname,265);if(Z.gname)g4.write(X,Z.gname,297);if(g4.write(X,gO(Z.devmajor||0,6),329),g4.write(X,gO(Z.devminor||0,6),337),Y)g4.write(X,Y,345);return g4.write(X,gO(_Y$(X),6),148),X};AW4.decode=function(Z,X,Q){let Y=Z[156]===0?0:Z[156]-48,G=dy(Z,0,100,X),J=yO(Z,100,8),W=yO(Z,108,8),K=yO(Z,116,8),F=yO(Z,124,12),H=yO(Z,136,12),N=LW4(Y),U=Z[157]===0?null:dy(Z,157,100,X),B=dy(Z,265,32),O=dy(Z,297,32),w=yO(Z,329,8),L=yO(Z,337,8),E=_Y$(Z);if(E===256)return null;if(E!==yO(Z,148,8))throw Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");if(OW4(Z)){if(Z[345])G=dy(Z,345,155,X)+"/"+G}else if(DW4(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:W,gid:K,size:F,mtime:new Date(1000*H),type:N,linkname:U,uname:B,gname:O,devmajor:w,devminor:L,pax:null}};function OW4($){return g4.equals(SY$,$.subarray(257,263))}function DW4($){return g4.equals(UW4,$.subarray(257,263))&&g4.equals(BW4,$.subarray(263,265))}function wW4($,Z,X){if(typeof $!=="number")return X;if($=~~$,$>=Z)return Z;if($>=0)return $;if($+=Z,$>=0)return $;return 0}function LW4($){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 EW4($){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 CY$($,Z,X,Q){for(;X<Q;X++)if($[X]===Z)return X;return Q}function _Y$($){let Z=256;for(let X=0;X<148;X++)Z+=$[X];for(let X=156;X<512;X++)Z+=$[X];return Z}function gO($,Z){if($=$.toString(8),$.length>Z)return"7777777777777777777".slice(0,Z)+" ";return"0000000000000000000".slice(0,Z-$.length)+$+" "}function jW4($,Z,X){Z[X]=128;for(let Q=11;Q>0;Q--)Z[X+Q]=$&255,$=Math.floor($/256)}function zW4($,Z,X){if($.toString(8).length>11)jW4($,Z,X);else g4.write(Z,gO($,11),X)}function PW4($){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 yO($,Z,X){if($=$.subarray(Z,Z+X),Z=0,$[Z]&128)return PW4($);else{while(Z<$.length&&$[Z]===32)Z++;let Q=wW4(CY$($,32,Z,$.length),$.length,$.length);while(Z<Q&&$[Z]===0)Z++;if(Q===Z)return 0;return parseInt(g4.toString($.subarray(Z,Q)),8)}}function dy($,Z,X,Q){return g4.toString($.subarray(Z,CY$($,0,Z,Z+X)),Q)}function Xn0($){let Z=g4.byteLength($),X=Math.floor(Math.log(Z)/Math.log(10))+1;if(Z+X>=Math.pow(10,X))X++;return Z+X+$}});var uY$=_((SP9,hY$)=>{var{Writable:kW4,Readable:VW4,getStreamError:vY$}=Zn0(),SW4=op0(),fY$=cy(),my=Qn0(),CW4=fY$.alloc(0);class bY${constructor(){this.buffered=0,this.shifted=0,this.queue=new SW4,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 CW4;let Z=this._next($);if($===Z.byteLength)return Z;let X=[Z];while(($-=Z.byteLength)>0)Z=this._next($),X.push(Z);return fY$.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 xY$ extends VW4{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(vY$(this))}_detach(){if(this._parent._stream===this)this._parent._stream=null,this._parent._missing=gY$(this.header.size),this._parent._update()}_destroy($){this._detach(),$(null)}}class yY$ extends kW4{constructor($){super($);if(!$)$={};this._buffer=new bY$,this._offset=0,this._header=null,this._stream=null,this._missing=0,this._longHeader=!1,this._callback=Yn0,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=my.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=my.decodeLongPath($,this._filenameEncoding);break;case"gnu-long-link-path":this._gnuLongLinkPath=my.decodeLongPath($,this._filenameEncoding);break;case"pax-global-header":this._paxGlobal=my.decodePax($);break;case"pax-header":this._pax=this._paxGlobal===null?my.decodePax($):Object.assign({},this._paxGlobal,my.decodePax($));break}}_consumeLongHeader(){this._longHeader=!1,this._missing=gY$(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 xY$(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=Yn0,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(vY$(this));$(null)}[Symbol.asyncIterator](){let $=null,Z=null,X=null,Q=null,Y=null,G=this;return this.on("entry",K),this.on("error",(N)=>{$=N}),this.on("close",F),{[Symbol.asyncIterator](){return this},next(){return new Promise(W)},return(){return H(null)},throw(N){return H(N)}};function J(N){if(!Y)return;let U=Y;Y=null,U(N)}function W(N,U){if($)return U($);if(Q){N({value:Q,done:!1}),Q=null;return}if(Z=N,X=U,J(null),G._finished&&Z)Z({value:void 0,done:!0}),Z=X=null}function K(N,U,B){if(Y=B,U.on("error",Yn0),Z)Z({value:U,done:!1}),Z=X=null;else Q=U}function F(){if(J($),!Z)return;if($)X($);else Z({value:void 0,done:!0});Z=X=null}function H(N){return G.destroy(N),J(N),new Promise((U,B)=>{if(G.destroyed)return U({value:void 0,done:!0});G.once("close",function(){if(N)B(N);else U({value:void 0,done:!0})})})}}}hY$.exports=function(Z){return new yY$(Z)};function Yn0(){}function gY$($){return $&=511,$&&512-$}});var cY$=_((CP9,Gn0)=>{var lY$={S_IFMT:61440,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960};try{Gn0.exports=P0("fs").constants||lY$}catch{Gn0.exports=lY$}});var oY$=_((_P9,tY$)=>{var{Readable:_W4,Writable:vW4,getStreamError:dY$}=Zn0(),OC=cy(),iy=cY$(),fO0=Qn0(),mY$=OC.alloc(1024);class iY$ extends vW4{constructor($,Z,X){super({mapWritable:bW4,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?OC.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?OC.toString(this._linkname,"utf-8"):"",this._pack._encode(this.header);nY$(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 dY$(this)||Error("tar entry destroyed")}_predestroy(){this._pack.destroy(this._getError())}_destroy($){this._pack._done(this),this._continuePack(this._finished?null:this._getError()),$()}}class pY$ extends _W4{constructor($){super($);this._drain=Jn0,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=Jn0;if(!$.size||$.type==="symlink")$.size=0;if(!$.type)$.type=fW4($.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=OC.from(Z);let Q=new iY$(this,$,X);if(OC.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(mY$),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=fO0.encode($);if(Z){this.push(Z);return}}this._encodePax($)}_encodePax($){let Z=fO0.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(fO0.encode(X)),this.push(Z),nY$(this,Z.byteLength),X.size=$.size,X.type=$.type,this.push(fO0.encode(X))}_doDrain(){let $=this._drain;this._drain=Jn0,$()}_predestroy(){let $=dY$(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(),$()}}tY$.exports=function(Z){return new pY$(Z)};function fW4($){switch($&iy.S_IFMT){case iy.S_IFBLK:return"block-device";case iy.S_IFCHR:return"character-device";case iy.S_IFDIR:return"directory";case iy.S_IFIFO:return"fifo";case iy.S_IFLNK:return"symlink"}return"file"}function Jn0(){}function nY$($,Z){if(Z&=511,Z)$.push(mY$.subarray(0,512-Z))}function bW4($){return OC.isBuffer($)?$:OC.from($)}});var rY$=_((xW4)=>{xW4.extract=uY$();xW4.pack=oY$()});var eY$=_((fP9,sY$)=>{sY$.exports=aY$;function aY$($,Z){if($&&Z)return aY$($)(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(W){G[W]=J[W]});return G}}});var Kn0=_((bP9,Wn0)=>{var $G$=eY$();Wn0.exports=$G$(bO0);Wn0.exports.strict=$G$(ZG$);bO0.proto=bO0(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return bO0(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return ZG$(this)},configurable:!0})});function bO0($){var Z=function(){if(Z.called)return Z.value;return Z.called=!0,Z.value=$.apply(this,arguments)};return Z.called=!1,Z}function ZG$($){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 YG$=_((xP9,QG$)=>{var hW4=Kn0(),uW4=function(){},lW4=global.Bare?queueMicrotask:process.nextTick.bind(process),cW4=function($){return $.setHeader&&typeof $.abort==="function"},dW4=function($){return $.stdio&&Array.isArray($.stdio)&&$.stdio.length===3},XG$=function($,Z,X){if(typeof Z==="function")return XG$($,null,Z);if(!Z)Z={};X=hW4(X||uW4);var{_writableState:Q,_readableState:Y}=$,G=Z.readable||Z.readable!==!1&&$.readable,J=Z.writable||Z.writable!==!1&&$.writable,W=!1,K=function(){if(!$.writable)F()},F=function(){if(J=!1,!G)X.call($)},H=function(){if(G=!1,!J)X.call($)},N=function(L){X.call($,L?Error("exited with error code: "+L):null)},U=function(L){X.call($,L)},B=function(){lW4(O)},O=function(){if(W)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"))},w=function(){$.req.on("finish",F)};if(cW4($))if($.on("complete",F),$.on("abort",B),$.req)w();else $.on("request",w);else if(J&&!Q)$.on("end",K),$.on("close",K);if(dW4($))$.on("exit",N);if($.on("end",H),$.on("finish",F),Z.error!==!1)$.on("error",U);return $.on("close",B),function(){if(W=!0,$.removeListener("complete",F),$.removeListener("abort",B),$.removeListener("request",w),$.req)$.req.removeListener("finish",F);$.removeListener("end",K),$.removeListener("close",K),$.removeListener("finish",F),$.removeListener("exit",N),$.removeListener("end",H),$.removeListener("error",U),$.removeListener("close",B)}};QG$.exports=XG$});var WG$=_((yP9,JG$)=>{var mW4=Kn0(),iW4=YG$(),xO0;try{xO0=P0("fs")}catch($){}var Rn=function(){},pW4=typeof process>"u"?!1:/^v?\.0/.test(process.version),yO0=function($){return typeof $==="function"},nW4=function($){if(!pW4)return!1;if(!xO0)return!1;return($ instanceof(xO0.ReadStream||Rn)||$ instanceof(xO0.WriteStream||Rn))&&yO0($.close)},tW4=function($){return $.setHeader&&yO0($.abort)},oW4=function($,Z,X,Q){Q=mW4(Q);var Y=!1;$.on("close",function(){Y=!0}),iW4($,{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,nW4($))return $.close(Rn);if(tW4($))return $.abort();if(yO0($.destroy))return $.destroy();Q(J||Error("stream was destroyed"))}},GG$=function($){$()},rW4=function($,Z){return $.pipe(Z)},aW4=function(){var $=Array.prototype.slice.call(arguments),Z=yO0($[$.length-1]||Rn)&&$.pop()||Rn;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,W=G>0;return oW4(Y,J,W,function(K){if(!X)X=K;if(K)Q.forEach(GG$);if(J)return;Q.forEach(GG$),Z(X)})});return $.reduce(rW4)};JG$.exports=aW4});var wG$=_((ZK4)=>{var KG$=rY$(),FG$=WG$(),HG$=P0("fs"),F9=P0("path"),In=(global.Bare?global.Bare.platform:process.platform)==="win32";ZK4.pack=function(Z,X){if(!Z)Z=".";if(!X)X={};let Q=X.fs||HG$,Y=X.ignore||X.filter||qn,G=X.mapStream||OG$,J=$K4(Q,X.dereference?Q.stat:Q.lstat,Z,Y,X.entries,X.sort),W=X.strict!==!1,K=typeof X.umask==="number"?~X.umask:~NG$(),F=X.pack||KG$.pack(),H=X.finish||qn,N=X.map||qn,U=typeof X.dmode==="number"?X.dmode:0,B=typeof X.fmode==="number"?X.fmode:0;if(X.strip)N=DG$(N,X.strip);if(X.readable)U|=parseInt(555,8),B|=parseInt(444,8);if(X.writable)U|=parseInt(333,8),B|=parseInt(222,8);L();function O(E,j){Q.readlink(F9.join(Z,E),function(z,P){if(z)return F.destroy(z);j.linkname=Fn0(P),F.entry(j,L)})}function w(E,j,z){if(F.destroyed)return;if(E)return F.destroy(E);if(!j){if(X.finalize!==!1)F.finalize();return H(F)}if(z.isSocket())return L();let P={name:Fn0(j),mode:(z.mode|(z.isDirectory()?U:B))&K,mtime:z.mtime,size:z.size,type:"file",uid:z.uid,gid:z.gid};if(z.isDirectory())return P.size=0,P.type="directory",P=N(P)||P,F.entry(P,L);if(z.isSymbolicLink())return P.size=0,P.type="symlink",P=N(P)||P,O(j,P);if(P=N(P)||P,!z.isFile()){if(W)return F.destroy(Error("unsupported type for "+j));return L()}let A=F.entry(P,L),I=G(Q.createReadStream(F9.join(Z,j),{start:0,end:P.size>0?P.size-1:P.size}),P);I.on("error",function(k){A.destroy(k)}),FG$(I,A)}function L(E){if(E)return F.destroy(E);J(w)}return F};function sW4($){return $.length?$[$.length-1]:null}function eW4(){return!global.Bare&&process.getuid?process.getuid():-1}function NG$(){return!global.Bare&&process.umask?process.umask():0}ZK4.extract=function(Z,X){if(!Z)Z=".";if(!X)X={};Z=F9.resolve(Z);let Q=X.fs||HG$,Y=X.ignore||X.filter||qn,G=X.mapStream||OG$,J=X.chown!==!1&&!In&&eW4()===0,W=X.extract||KG$.extract(),K=[],F=new Date,H=typeof X.umask==="number"?~X.umask:~NG$(),N=X.strict!==!1,U=X.validateSymlinks!==!1,B=X.map||qn,O=typeof X.dmode==="number"?X.dmode:0,w=typeof X.fmode==="number"?X.fmode:0;if(X.strip)B=DG$(B,X.strip);if(X.readable)O|=parseInt(555,8),w|=parseInt(444,8);if(X.writable)O|=parseInt(333,8),w|=parseInt(222,8);if(W.on("entry",L),X.finish)W.on("finish",X.finish);return W;function L(A,I,k){A=B(A)||A,A.name=Fn0(A.name);let M=F9.join(Z,F9.join("/",A.name));if(Y(M,A))return I.resume(),k();let S=F9.join(M,".")===F9.join(Z,".")?Z:F9.dirname(M);BG$(Q,S,F9.join(Z,"."),function(o,U0){if(o)return k(o);if(!U0)return k(Error(S+" is not a valid path"));if(A.type==="directory")return K.push([M,A.mtime]),P(M,{fs:Q,own:J,uid:A.uid,gid:A.gid,mode:A.mode},m);P(S,{fs:Q,own:J,uid:A.uid,gid:A.gid,mode:493},function(j0){if(j0)return k(j0);switch(A.type){case"file":return l();case"link":return b();case"symlink":return f()}if(N)return k(Error("unsupported type for "+M+" ("+A.type+")"));I.resume(),k()})});function m(o){if(o)return k(o);j(M,A,function(U0){if(U0)return k(U0);if(In)return k();z(M,A,k)})}function f(){if(In)return k();Q.unlink(M,function(){let o=F9.resolve(F9.dirname(M),A.linkname);if(!i(o)&&U)return k(Error(M+" is not a valid symlink"));UG$(Q,o,F9.join(Z,"."),function(U0,j0){if(U0)return k(U0);if(!j0&&U)return k(Error(M+" is not a valid symlink"));Q.symlink(A.linkname,M,m)})})}function b(){if(In)return k();Q.unlink(M,function(){let o=F9.join(Z,F9.join("/",A.linkname));Q.realpath(o,function(U0,j0){if(U0||!i(j0))return k(Error(M+" is not a valid hardlink"));Q.link(j0,M,function(a){if(a&&a.code==="EPERM"&&X.hardlinkAsFilesFallback)return I=Q.createReadStream(j0),l();m(a)})})})}function i(o){return o===Z||o.startsWith(Z+F9.sep)}function l(){let o=Q.createWriteStream(M),U0=G(I,A);o.on("error",function(j0){U0.destroy(j0)}),FG$(U0,o,function(j0){if(j0)return k(j0);o.on("close",m)})}}function E(A,I){let k;while((k=sW4(K))&&A.slice(0,k[0].length)!==k[0])K.pop();if(!k)return I();Q.utimes(k[0],F,k[1],I)}function j(A,I,k){if(X.utimes===!1)return k();if(I.type==="directory")return Q.utimes(A,F,I.mtime,k);if(I.type==="symlink")return E(A,k);Q.utimes(A,F,I.mtime,function(M){if(M)return k(M);E(A,k)})}function z(A,I,k){let M=I.type==="symlink",S=M?Q.lchmod:Q.chmod,m=M?Q.lchown:Q.chown;if(!S)return k();let f=(I.mode|(I.type==="directory"?O:w))&H;if(m&&J)m.call(Q,A,I.uid,I.gid,b);else b(null);function b(i){if(i)return k(i);if(!S)return k();S.call(Q,A,f,k)}}function P(A,I,k){Q.stat(A,function(M){if(!M)return k(null);if(M.code!=="ENOENT")return k(M);Q.mkdir(A,{mode:I.mode,recursive:!0},function(S,m){if(S)return k(S);z(A,I,k)})})}};function UG$($,Z,X,Q){if(Z===X)return Q(null,!0);if(!Z.startsWith(X+F9.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 UG$($,F9.join(Z,".."),X,Q);Q(null,!1)})}function BG$($,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 BG$($,F9.join(Z,".."),X,Q);Q(null,!1)})}function qn(){}function OG$($){return $}function Fn0($){return In?$.replace(/\\/g,"/").replace(/[:?<>|]/g,"_"):$}function $K4($,Z,X,Q,Y,G){if(!Y)Y=["."];let J=Y.slice(0);return function(K){if(!J.length)return K(null);let F=J.shift(),H=F9.join(X,F);Z.call($,H,function(N,U){if(N)return K(Y.indexOf(F)===-1&&N.code==="ENOENT"?null:N);if(!U.isDirectory())return K(null,F,U);$.readdir(H,function(B,O){if(B)return K(B);if(G)O.sort();for(let w=0;w<O.length;w++)if(!Q(F9.join(X,F,O[w])))J.push(F9.join(F,O[w]));K(null,F,U)})})}}function DG$($,Z){return function(X){X.name=X.name.split("/").slice(Z).join("/");let Q=X.linkname;if(Q&&(X.type==="link"||F9.isAbsolute(Q)))X.linkname=Q.split("/").slice(Z).join("/");return $(X)}}});var YK4,GK4;var LG$=D(()=>{np0();YK4=V(YY$(),1),GK4=V(wG$(),1)});var gO0=()=>{};var EG$=D(()=>{aB0()});var jG$=D(()=>{IO0();RO0();gO0()});var zG$=()=>{};var PG$=()=>{};var AG$=D(()=>{hQ$();ip0();IO0();mQ$();dp0();np0();iQ$();pQ$();nQ$();tQ$();mp0();oQ$();LG$();gO0();EG$();jG$();zG$();PG$();gO0()});var hO0=D(()=>{X4();tm0()});function JK4($){if($ instanceof TypeError)return!0;if($ instanceof DOMException&&$.name==="AbortError")return!0;return!1}async function Hn0($,Z,X){try{return await w6(async()=>{let Y=await fetch($,Z);return{status:Y.status,ok:Y.ok,body:await Y.text()}},{maxAttempts:3,minTimeout:50,maxTimeout:500,multiplier:2,jitter:0.5,isRetriable:JK4})}catch(Q){let Y=Q instanceof Error?Q.message:String(Q);throw Error(`[SANDBOX_UNREACHABLE] sandbox daemon ${X} request failed: ${Y}`,{cause:Q})}}async function lO0($){try{let Z=await fetch(`${$}/health`,{signal:AbortSignal.timeout(WK4)});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 Un0($){for(let Z=0;Z<TG$;Z++){if(await lO0($)!==null)return;let X=(Math.random()*2-1)*KK4;await w$(RG$+X)}throw Error(`sandbox daemon at ${$} did not respond on /health within ${TG$*RG$/1000}s`)}async function DC($,Z,X,Q,Y){return FK4($,Z,"POST",X,Q,Y)}async function FK4($,Z,X,Q,Y,G){let J={...Q};if(Y&&Y.rotateToken!==void 0)J.auth=Y;let W=await Hn0(`${$}/_sandbox/config`,{method:X,headers:{"Content-Type":"application/json",Authorization:`Bearer ${Z}`},body:JSON.stringify(J),signal:AbortSignal.timeout(G?.timeoutMs??Nn0)},"/_sandbox/config");if(!W.ok)throw new uO0(W.status,W.body);return MG$(W.body,"/_sandbox/config")}async function IG$($,Z,X){let Q=await Hn0(`${$}/_sandbox/setup/${X}`,{method:"POST",headers:{Authorization:`Bearer ${Z}`},signal:AbortSignal.timeout(Nn0)},`/_sandbox/setup/${X}`);if(!Q.ok)throw Error(`sandbox daemon /_sandbox/setup/${X} returned ${Q.status}: ${Q.body}`)}async function qG$($,Z,X){let Q=await Hn0(`${$}/_sandbox/orgfs-config`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Z}`},body:X,signal:AbortSignal.timeout(Nn0)},"/_sandbox/orgfs-config");if(!Q.ok)throw Error(`sandbox daemon /_sandbox/orgfs-config returned ${Q.status}: ${Q.body}`);return MG$(Q.body,"/_sandbox/orgfs-config")}function MG$($,Z){try{return JSON.parse($)}catch(X){throw Error(`sandbox daemon ${Z} returned a malformed JSON body: ${$.slice(0,200)}`,{cause:X})}}async function Mn($,Z,X,Q){let Y=new Headers(Q.headers);for(let W of HK4)Y.delete(W);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 uO0,WK4=500,Nn0=30000,TG$=25,RG$=200,KK4=50,HK4;var kG$=D(()=>{hO0();X4();uO0=class uO0 extends Error{status;constructor($,Z){super(`sandbox daemon /_sandbox/config returned ${$}: ${Z}`);this.status=$;this.name="ConfigRequestError"}};HK4=["cookie","host","connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","accept-encoding","content-length"]});async function*CG$($){let Z=$.now??(()=>Date.now()),X=Z(),Q=$.schedulingTimeoutMs??UK4,Y={pod:{},sandbox:{},events:{hasPulling:!1,hasPulled:!1},startedAt:X},G=[],J=null,W=!1,K=(j)=>{if(W)return;if(J){let z=J;J=null,z(j)}else G.push(j)},F=()=>{if(G.length>0)return Promise.resolve(G.shift());if(W)return Promise.resolve(null);return new Promise((j)=>{J=j})},H=()=>{if(W)return;if(W=!0,J){let j=J;J=null,j(null)}},N=new AbortController,U=()=>{N.abort(),H()};if($.signal)if($.signal.aborted)N.abort(),H();else $.signal.addEventListener("abort",U,{once:!0});let B=Math.max(0,Q-(Z()-X)),O=setTimeout(()=>K("tick"),B+100),w,L=new Promise((j)=>{w=j}),E=Promise.allSettled([BK4($.kc,$.namespace,$.claimName,N.signal,Y,K,Z,w),DK4($.kc,$.namespace,$.claimName,N.signal,Y,K),wK4($.kc,$.namespace,$.claimName,L,N.signal,Y,K,Z)]);try{let j=null,z=-1,P=VG$(Y,Q,Z);if(j=On0(P),!Bn0(P))z=SG$(P);if(yield P,Bn0(P))return;while(!W){if(await F()===null)break;let I=VG$(Y,Q,Z);if(Bn0(I)){let S=On0(I);if(S!==j)j=S,yield I;return}let k=SG$(I);if(k<z)continue;let M=On0(I);if(M!==j)j=M,z=k,yield I}}finally{if(clearTimeout(O),N.abort(),$.signal)$.signal.removeEventListener("abort",U);H(),await E.catch(()=>{})}}function VG$($,Z,X){let{pod:Q,sandbox:Y,events:G,startedAt:J}=$;if(Y.ready)return{kind:"ready"};let W=Q.containerWaitingReason;if(W==="ImagePullBackOff"||W==="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(W==="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(W==="ContainerCreating"||W==="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 Bn0($){return $.kind==="ready"||$.kind==="failed"}function SG$($){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 On0($){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 BK4($,Z,X,Q,Y,G,J,W){let K=`/api/v1/namespaces/${encodeURIComponent(Z)}/pods?watch=true&labelSelector=${encodeURIComponent(`${NK4}=${X}`)}`;return cO0({kc:$,path:K,signal:Q,label:`pod/${X}`,onEvent:(F)=>{if(F.type!=="ADDED"&&F.type!=="MODIFIED")return;let H=F.object;if(H.metadata?.name)W(H.metadata.name);OK4(H,Y,J),G("pod")}})}function OK4($,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===K9.MAIN_CONTAINER_NAME);if(G)Z.pod.containerWaitingReason=G.state?.waiting?.reason,Z.pod.containerRunning=!!G.state?.running,Z.pod.containerReady=G.ready===!0}async function DK4($,Z,X,Q,Y,G){let J=`/apis/${K9.CLAIM_API_GROUP}/${K9.CLAIM_API_VERSION}/namespaces/${encodeURIComponent(Z)}/${K9.CLAIM_PLURAL}?watch=true&fieldSelector=${encodeURIComponent(`metadata.name=${X}`)}`;return cO0({kc:$,path:J,signal:Q,label:`sandboxclaim/${X}`,onEvent:(W)=>{if(W.type!=="ADDED"&&W.type!=="MODIFIED")return;let F=W.object.status?.conditions?.find((H)=>H.type==="Ready");if(!F)return;if(F.status==="True")Y.sandbox.ready=!0,Y.sandbox.notReadyReason=void 0,Y.sandbox.notReadyMessage=void 0;else Y.sandbox.ready=!1,Y.sandbox.notReadyReason=F.reason,Y.sandbox.notReadyMessage=F.message;G("sandbox")}})}async function wK4($,Z,X,Q,Y,G,J,W){let K=await Promise.race([Q,new Promise((H)=>{if(Y.aborted){H(X);return}Y.addEventListener("abort",()=>H(X),{once:!0})})]);if(Y.aborted)return;let F=`/api/v1/namespaces/${encodeURIComponent(Z)}/events?watch=true&fieldSelector=${encodeURIComponent(`involvedObject.name=${K},involvedObject.kind=Pod`)}`;return cO0({kc:$,path:F,signal:Y,label:`events/${X}`,onEvent:(H)=>{if(H.type!=="ADDED"&&H.type!=="MODIFIED")return;let N=H.object,U=N.reason;if(!U)return;switch(U){case"Pulling":G.events.hasPulling=!0;break;case"Pulled":G.events.hasPulling=!0,G.events.hasPulled=!0;break;case"FailedScheduling":G.events.lastFailedSchedulingAt=W(),G.events.failedSchedulingMessage=N.message;break;case"Nominated":{let B=N.message?.match(/nodeclaim\/([\w-]+)/);if(B)G.events.nominatedNodeClaim=B[1];break}default:return}J("event")}})}async function _G$($){let{kc:Z,namespace:X,labelSelector:Q,signal:Y,onDelete:G}=$,J=`/apis/${K9.CLAIM_API_GROUP}/${K9.CLAIM_API_VERSION}/namespaces/${encodeURIComponent(X)}/${K9.CLAIM_PLURAL}?watch=true&labelSelector=${encodeURIComponent(Q)}`;return cO0({kc:Z,path:J,signal:Y,label:"sandboxclaim-reaper",onEvent:(W)=>{if(W.type!=="DELETED")return;let K=W.object.metadata?.name;if(K)G(K)}})}async function cO0($){let{kc:Z,path:X,signal:Q,label:Y,onEvent:G}=$,J=0;while(!Q.aborted){try{let K=await oY(Z,{method:"GET",path:X,signal:Q,headers:{accept:"application/json"},stream:!0});if(!K.ok||!K.body){try{await K.body?.cancel()}catch{}if(K.status===401||K.status===403){console.warn(`[lifecycle-watcher] ${Y} stopped: watch denied (${K.status} ${K.statusText}). `+"The kubeconfig in use cannot watch SandboxClaims \u2014 if you are running locally, "+"this provider should not be active (check STUDIO_AGENT_SANDBOX_ENABLED).");return}throw Error(`watch handshake failed: ${K.status} ${K.statusText}`)}J=0;for await(let F of Li0(K.body)){if(Q.aborted)return;try{G(F)}catch(H){console.warn(`[lifecycle-watcher] ${Y} onEvent threw: ${H instanceof Error?H.message:String(H)}`)}}}catch(K){if(Q.aborted)return;let F=K instanceof Error?K.message:String(K);console.warn(`[lifecycle-watcher] ${Y} watch ended: ${F}`)}if(Q.aborted)return;let W=eZ(5000,250,J,2,0);J+=1,await w$(W,{signal:Q}).catch(()=>{})}}var NK4="studio.decocms.com/sandbox-handle",UK4=300000;var vG$=D(()=>{X4();E70();A70()});import{z as GJ}from"zod";function fG$($){if(!$||$.trim()==="")return[];let Z=GJ.array(LK4).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 EK4($){try{let[Z,X]=new URL($).pathname.replace(/^\/+/,"").split("/"),Q=X?.replace(/\.git$/,"");return Z&&Q?`${Z}/${Q}`.toLowerCase():null}catch{return null}}function bG$($,Z){let{orgId:X,cloneUrl:Q}=Z;if(Z.purpose==="harness-run")return null;if(!X||!Q)return null;let Y=EK4(Q);if(!Y)return null;return $.find((G)=>G.orgId===X&&G.repo.toLowerCase()===Y)??null}function xG$($,Z,X){return $?.name??(Z?X:"none")}function jK4($,Z){return $==="harness-run"?`${Z}-medium`:Z}async function yG$($){let Z=jK4($.purpose,$.templateName);if(Z===$.templateName)return{name:Z,probe:$.probe};let X=$.probe!==null&&$.now-$.probe.checkedAt<$.ttlMs?$.probe:{checkedAt:$.now,present:await $.exists(Z)};if(X.present)return{name:Z,probe:X};if($.probe?.present!==!1)$.onAbsent?.(Z);return{name:$.templateName,probe:X}}function gG$($,Z,X){let Q=X.replace(/^refs\/heads\//,"");return $.filter((Y)=>Y.repo.toLowerCase()===Z.toLowerCase()&&Y.branch===Q)}function hG$($){return`https://github.com/${$.repo}.git`}var LK4;var Dn0=D(()=>{LK4=GJ.object({name:GJ.string().regex(/^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/,"pool name must be a DNS label (lowercase alphanumeric and '-')"),orgId:GJ.string().min(1),repo:GJ.string().regex(/^[^/\s]+\/[^/\s]+$/,"repo must be `owner/name`"),connectionId:GJ.string().min(1).optional(),branch:GJ.string().min(1).default("main"),workload:GJ.object({runtime:GJ.enum(["node","bun","deno"]).default("node"),packageManager:GJ.enum(["npm","pnpm","yarn","bun","deno"]).optional(),packageManagerPath:GJ.string().optional(),devPort:GJ.number().int().positive().optional()}).default({runtime:"node"})})});async function uG$($,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 zK4,randomBytes as PK4,randomUUID as AK4}from"crypto";import*as nG$ from"net";import{PassThrough as TK4}from"stream";function lG$($){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 An0{records=new Map;inflight=new $70;activeGauge=new eZ0;stateStore;previewUrlPattern;kubeConfig;capacityProbe;portForward;namespace;sandboxTemplateName;envName;tokenGenerator;idleTtlMs;metrics;previewGateway;sentinelToken;mintCloneUrl;mintOrgFsConfig;tenantPools;tenantPoolRefreshMs;poolPods=new Map;mediumTemplateProbe=null;dirtyPools=new Set;closed=!1;claimWatchAbort=new AbortController;constructor($={}){this.stateStore=$.stateStore??null,this.previewUrlPattern=$.previewUrlPattern??null,this.kubeConfig=$.kubeConfig??yK4(),this.portForward=new tp0(this.kubeConfig),this.namespace=$.namespace??RK4,this.sandboxTemplateName=$.sandboxTemplateName??IK4,this.envName=dK4($.envName),this.tokenGenerator=$.tokenGenerator??(()=>PK4(MK4).toString("hex")),this.idleTtlMs=$.idleTtlMs??VK4,this.metrics=$.meter?xK4($.meter):null,this.previewGateway=$.previewGateway&&$.previewUrlPattern?{...$.previewGateway}:null;let Z=$.sentinelToken?.trim()??"";if(this.sentinelToken=Z.length>0?Z:null,this.mintCloneUrl=$.mintCloneUrl,this.mintOrgFsConfig=$.mintOrgFsConfig,this.tenantPools=this.sentinelToken!==null?$.tenantPools??[]:[],this.sentinelToken===null&&($.tenantPools?.length??0)>0)console.warn(`[${H6}] tenant pools configured without a sentinel token \u2014 ignoring them (warm-pool mode is off)`);this.tenantPoolRefreshMs=$.tenantPoolRefreshMs??CK4,this.startClaimReaper(),this.startCredentialRefresher(),this.startTenantPoolReconciler()}startClaimReaper(){let $=["app.kubernetes.io/managed-by=studio","app.kubernetes.io/name=studio-sandbox",...this.envName?[`${QQ.env}=${this.envName}`]:[]].join(",");_G$({kc:this.kubeConfig,namespace:this.namespace,labelSelector:$,signal:this.claimWatchAbort.signal,onDelete:(Z)=>this.invalidateRecord(Z)})}async ensure($,Z={}){let X=yE($);if(X.startsWith("s-"))throw Error(`ensure: projectRef has no slug source: ${$.projectRef}`);return this.inflight.run(X,()=>Z70(this.stateStore,$,(Q)=>this.ensureLocked($,X,Z,Q)))}async delete($){let Z=await this.getRecord($);if(this.records.delete($),Z)this.dropRecord(Z);if(await this.deleteHttpRouteIfManaged($).catch((X)=>{console.warn(`[${H6}] HTTPRoute delete failed for ${$}: ${X instanceof Error?X.message:String(X)}`)}),await Cy(this.kubeConfig,this.namespace,$),this.stateStore)if(Z)await this.stateStore.delete(Z.id);else await this.stateStore.deleteByHandle($)}lastTermination($){return h5$(this.kubeConfig,this.namespace,QQ.sandboxHandle,$,K9.MAIN_CONTAINER_NAME)}async alive($){return await lH(this.kubeConfig,this.namespace,$)!==void 0}watchClaimLifecycle($,Z){return CG$({kc:this.kubeConfig,namespace:this.namespace,claimName:$,signal:Z})}hasSchedulableCapacity(){return this.capacityProbe??=r5$(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 K=await this.stateStore.getByHandle($),F=K?.state,H=F?.token;if(K&&H){let U=`http://${F?.adoptedSandboxName??$}.${this.namespace}.svc.cluster.local:${tH}`;try{let B=await Mn(U,H,Z,X);if(B.status!==404)return B;try{await B.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,W=!(X.body instanceof ReadableStream);try{let K=await Mn(Q.daemonUrl,Q.token,Z,X);if(K.status===401&&W){this.invalidateRecord($);let F=await this.getRecord($).catch(()=>null)??await this.resurrectByHandle($).catch(()=>null);if(F){try{await K.body?.cancel()}catch{}Y=F,K=await Mn(F.daemonUrl,F.token,Z,X)}}return J=K.status,K}catch(K){if(!W)throw K;this.invalidateRecord($);let F=await this.resurrectByHandle($)??await this.getRecord($).catch(()=>null);if(!F)throw K;Y=F;let H=await Mn(F.daemonUrl,F.token,Z,X);return J=H.status,H}finally{this.recordProxyDuration("daemon",J,Y,performance.now()-G)}}async adoptLiveClaim($,Z){if(this.records.has(Z))return!0;let X=await lH(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 Z70(this.stateStore,$,(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:${tH}`;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($).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 O=Ln0(404,{error:"sandbox not found"});return O.headers.set(LC,"1"),O}let J=new URL(Z.url);if((J.pathname==="/_sandbox"||J.pathname.startsWith("/_sandbox/"))&&Z.method!=="GET")return Y=404,Ln0(404,{error:"not found"});let K=(O)=>`${O}${J.pathname}${J.search}`,F=new Headers(Z.headers);for(let O of fK4)F.delete(O);let H=Z.method!=="GET"&&Z.method!=="HEAD",N={method:Z.method,headers:F,body:H?Z.body:void 0,redirect:"manual",signal:Z.signal,duplex:H?"half":void 0},U;try{U=await fetch(K(G),N)}catch(O){let w=`${G}${J.pathname}`;if(console.warn(`[${H6}] preview fetch to ${w} failed: ${O instanceof Error?O.message:String(O)}`),Z.method==="GET"||Z.method==="HEAD"){if(this.invalidateRecord($),await this.resurrectByHandle($).catch(()=>null)){let j=await this.resolvePreviewUpstreamUrl($);if(j)try{U=await fetch(K(j),N);let z=new Headers;for(let[P,A]of U.headers.entries())if(!mG$.includes(P.toLowerCase()))z.set(P,A);return Y=U.status,new Response(U.body,{status:U.status,statusText:U.statusText,headers:z})}catch(z){console.warn(`[${H6}] preview fetch retry to ${w} failed: ${z instanceof Error?z.message:String(z)}`)}}}else this.invalidateRecord($);Y=502;let L=Ln0(502,{error:"sandbox daemon unreachable"});return L.headers.set(LC,"1"),L}let B=new Headers;for(let[O,w]of U.headers.entries())if(!mG$.includes(O.toLowerCase()))B.set(O,w);return Y=U.status,new Response(U.body,{status:U.status,statusText:U.statusText,headers:B})}finally{this.recordProxyDuration("preview",Y,Q,performance.now()-X,$)}}async ensureLocked($,Z,X,Q){if(X.image)console.warn(`[${H6}] opts.image ignored (template ${this.sandboxTemplateName} pins image): got ${X.image}`);if(Q){let J=await Q.get($);if(J){let W=await this.rehydrate($,Z,J);if(W)return await this.refreshDaemonGitCredential(W,X),await this.relayOrgFsConfig(W.daemonUrl,W.token,X.orgFsConfigJson),this.finish(W,Q,!1,!0,"resume");await Q.delete($)}}let Y=await lH(this.kubeConfig,this.namespace,Z).catch(()=>{return});if(Y)if(Y.metadata?.deletionTimestamp)await z70(this.kubeConfig,this.namespace,Z).catch((J)=>{console.warn(`[${H6}] wait for terminating claim ${Z} failed: ${J instanceof Error?J.message:String(J)}`)});else{let J=await this.adopt($,Z,Y).catch((W)=>{return console.warn(`[${H6}] adopt ${Z} failed, recreating: ${W instanceof Error?W.message:String(W)}`),null});if(J)return await this.refreshDaemonGitCredential(J,X),await this.relayOrgFsConfig(J.daemonUrl,J.token,X.orgFsConfigJson),this.finish(J,Q,!0,!0,"adopt");await Cy(this.kubeConfig,this.namespace,Z).catch(()=>{}),await z70(this.kubeConfig,this.namespace,Z).catch((W)=>{console.warn(`[${H6}] wait for deleted claim ${Z} failed: ${W instanceof Error?W.message:String(W)}`)})}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 P70(this.kubeConfig,this.namespace,$.handle,this.computeShutdownTime()).catch((W)=>console.warn(`[${H6}] TTL refresh failed for ${$.handle}: ${W instanceof Error?W.message:String(W)}`));if(this.metrics){let W=jn0($.tenant);if(this.metrics.ensureOutcome.add(1,{...W,outcome:Y}),!J)this.metrics.active.add(1,W),this.activeGauge.markCounted($.handle)}return this.toSandbox($)}buildEnvMap($,Z){let X={},Q=[];for(let[Y,G]of Object.entries($.env??{}))if(kK4.has(Y))Q.push(Y);else X[Y]=G;if(Q.length>0)console.warn(`[${H6}] 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(tH)}}async resolveTemplateName($){let{name:Z,probe:X}=await yG$({purpose:$,templateName:this.sandboxTemplateName,probe:this.mediumTemplateProbe,now:Date.now(),ttlMs:qK4,exists:(Q)=>b5$(this.kubeConfig,this.namespace,Q),onAbsent:(Q)=>console.warn(`[${H6}] SandboxTemplate ${Q} not found (or not readable) \u2014 harness-run claims fall back to ${this.sandboxTemplateName}. Upgrade the sandbox-env chart to the version that renders it.`)});return this.mediumTemplateProbe=X,Z}buildClaim($,Z,X,Q){let Y=this.sentinelToken!==null,G=bG$(this.tenantPools,{orgId:Z.tenant?.orgId,cloneUrl:Z.repo?.cloneUrl,purpose:Z.purpose}),J=Y?[]:Object.entries(this.buildEnvMap(Z,X)).sort(([F],[H])=>F<H?-1:F>H?1:0).map(([F,H])=>({name:F,value:H})),W=pK4(Z),K=Object.keys(W).length>0;return{apiVersion:`${K9.CLAIM_API_GROUP}/${K9.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?{[QQ.env]:this.envName}:{},...En0(Z.tenant)},...K?{annotations:W}:{}},spec:{sandboxTemplateRef:{name:Q},additionalPodMetadata:{labels:En0(Z.tenant,{[QQ.role]:"claimed",[QQ.sandboxHandle]:$,...this.envName?{[QQ.env]:this.envName}:{}}),...K?{annotations:W}:{}},env:J,warmpool:xG$(G,Y,Q),lifecycle:{shutdownPolicy:"Delete",shutdownTime:this.computeShutdownTime()}}}}async provision($,Z,X){let Q=this.tokenGenerator(),Y=AK4(),G=wn0,J=this.buildClaim(Z,X,{token:Q,daemonBootId:Y,workdir:G},await this.resolveTemplateName(X.purpose));try{await Oi0(this.kubeConfig,this.namespace,J)}catch(U){if(U instanceof Jn)await z70(this.kubeConfig,this.namespace,Z),await Oi0(this.kubeConfig,this.namespace,J);else throw U}let W;try{W=await x5$(this.kubeConfig,this.namespace,Z),await t5$(this.kubeConfig,this.namespace,W)}catch(U){throw await Cy(this.kubeConfig,this.namespace,Z).catch(()=>{}),U}try{await this.ensureServicePortForAdoptedSandbox(W),await this.ensureHttpRouteForHandle(Z,W,X.tenant??null)}catch(U){throw await Cy(this.kubeConfig,this.namespace,Z).catch(()=>{}),U}let K=await this.openForwarder(W,tH,Z),F=`http://127.0.0.1:${K.localPort}`,H=this.workloadConfigPayload(X),N=Y;try{if(await Un0(F),this.sentinelToken!==null){let U=await lO0(F);if(U)N=U.bootId;await DC(F,this.sentinelToken,H??{},{rotateToken:Q})}else if(H)await DC(F,Q,H);await this.relayOrgFsConfig(F,Q,X.orgFsConfigJson)}catch(U){throw this.closeForwarder(K),await this.deleteHttpRouteIfManaged(Z).catch(()=>{}),await Cy(this.kubeConfig,this.namespace,Z).catch(()=>{}),U}return{id:$,handle:Z,adoptedSandboxName:W,token:Q,workdir:G,daemonUrl:F,daemonForward:K,workload:X.workload??null,daemonBootId:N,tenant:X.tenant??null,ensureOpts:aK4(X)}}workloadConfigPayload($){return Q70({runtime:$?.workload?.runtime??"node",packageManager:$?.workload?.packageManager?{name:$.workload.packageManager,...$.workload.packageManagerPath?{path:$.workload.packageManagerPath}:{}}:null,repo:$?.repo??null,extraRepos:$?.extraRepos??[],port:$?.workload?.devPort??cG$,tenant:$?.tenant??void 0,...$?{cloneOnly:$.cloneOnly===!0}:{}})}async relayOrgFsConfig($,Z,X){if(!X)return;await qG$($,Z,X).catch((Q)=>console.warn("[org-fs] sidecar config relay failed",Q))}async refreshDaemonGitCredential($,Z){let X=om0(Z);if(!X)return;try{await DC($.daemonUrl,$.token,X)}catch(Q){console.warn(`[${H6}] 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(`[${H6}] clone credential re-mint failed: ${X instanceof Error?X.message:String(X)}`),$}}async withFreshCredentials($){return{...$,...$.repo?{repo:await this.withFreshCloneUrl($.repo)}:{},...$.orgFsConfigJson?{orgFsConfigJson:await rK4($,this.mintOrgFsConfig)}:{}}}startCredentialRefresher(){if(!this.mintCloneUrl)return;let{signal:$}=this.claimWatchAbort;(async()=>{while(!$.aborted){if(await w$(_K4,{signal:$}).catch(()=>{}),$.aborted)break;try{await this.refreshAllGitCredentials()}catch(Z){console.warn(`[${H6}] 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(`[${H6}] tenant pool reconcile failed: ${Z instanceof Error?Z.message:String(Z)}`)}await w$(SK4,{signal:$}).catch(()=>{})}})()}markTenantPoolsDirty($,Z){let X=gG$(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 y5$(this.kubeConfig,this.namespace,$.name);if(Z===null){console.warn(`[${H6}] 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[QQ.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 W of X){let K=this.poolPods.get(W.uid);if(!K)continue;if(K.failures>=dO0)G++;else if(K.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>=dO0){if(Date.now()-Q.lastFailureAt<dG$)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:hG$($),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 W=await this.openForwarder(Z.name,tH,Z.name).catch(()=>null);if(!W){this.recordPoolFailure(Z,$,"port-forward failed");return}let K=`http://127.0.0.1:${W.localPort}`;try{await Un0(K);let F=this.sentinelToken;if(!F)return;if(!await this.isPoolPodUnbound(Z))return;let H=Q70({runtime:$.workload.runtime,packageManager:$.workload.packageManager?{name:$.workload.packageManager,...$.workload.packageManagerPath?{path:$.workload.packageManagerPath}:{}}:null,repo:J,port:$.workload.devPort??cG$})??{},{transition:N}=await DC(K,F,H);if(Y&&N!=="bootstrap"&&await this.isPoolPodUnbound(Z))await IG$(K,F,"clone");this.poolPods.set(Z.uid,{lastConfigAt:Date.now(),lastFailureAt:0,failures:0}),console.log(`[${H6}] tenant pool ${$.name}: warmed ${Z.name} (${N})`)}catch(F){this.recordPoolFailure(Z,$,F instanceof Error?F.message:String(F))}finally{this.closeForwarder(W)}}isPoolPodUnbound($){return g5$(this.kubeConfig,this.namespace,$.name,QQ.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>=dO0?` \u2014 backing off ${dG$/60000}min`:"";console.warn(`[${H6}] tenant pool ${Z.name}: warming ${$.name} failed (${Y}/${dO0})${G}: ${X}`)}async refreshAllGitCredentials(){await uG$(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,vK4);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 DC($,this.sentinelToken,Q,{rotateToken:Z}),await this.relayOrgFsConfig($,Z,X?.orgFsConfigJson),!0}catch(Y){if(Y instanceof uO0&&Y.status===401)try{return await DC($,Z,Q,{rotateToken:Z}),await this.relayOrgFsConfig($,Z,X?.orgFsConfigJson),!0}catch(G){return console.warn(`[${H6}] re-bootstrap retry with claim token failed: ${G instanceof Error?G.message:String(G)}`),!1}return console.warn(`[${H6}] re-bootstrap failed: ${Y instanceof Error?Y.message:String(Y)}`),!1}}async ensureServicePortForAdoptedSandbox($){if(!this.previewGateway||!this.previewUrlPattern)return;await n5$(this.kubeConfig,this.namespace,$,{name:"daemon",port:tH,targetPort:tH})}async ensureHttpRouteForHandle($,Z,X){if(!this.previewGateway||!this.previewUrlPattern)return;let Q=sK4(this.previewUrlPattern,$);if(!Q)throw new OZ(`Unable to derive preview hostname for ${$} from pattern: ${this.previewUrlPattern}`);let Y={apiVersion:`${wi0.API_GROUP}/${wi0.API_VERSION}`,kind:"HTTPRoute",metadata:{name:$,namespace:this.namespace,labels:En0(X??void 0,{[QQ.role]:"claimed",[QQ.sandboxHandle]:$,"app.kubernetes.io/name":"studio-sandbox","app.kubernetes.io/managed-by":"studio",...this.envName?{[QQ.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:tH}]}]}};await m5$(this.kubeConfig,this.namespace,Y)}async deleteHttpRouteIfManaged($){if(!this.previewGateway)return;await i5$(this.kubeConfig,this.namespace,$)}async rehydrate($,Z,X){let Q=X.state;if(!Q.adoptedSandboxName&&!Q.podName||!Q.token)return null;let Y=await lH(this.kubeConfig,this.namespace,Z).catch(()=>{return});if(!Y||!iG$(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 W=Q.ensureOpts?await this.withFreshCredentials(Q.ensureOpts):null;if(!await this.rebootstrapDaemon(J.daemonUrl,Q.token,W))return this.closeForwarder(J.daemonForward),null}else console.warn(`[${H6}] daemon restart detected (handle=${Z}): stored bootId=${Q.daemonBootId} live bootId=${J.bootId}`);await this.stateStore?.put($,{handle:Z,state:{...Q,daemonBootId:J.bootId}}).catch((W)=>console.warn(`[${H6}] bootId persist failed for ${Z}: ${W instanceof Error?W.message:String(W)}`))}return{id:$,handle:Z,adoptedSandboxName:G,token:Q.token,workdir:Q.workdir??wn0,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(!iG$(X))return null;let Q=X.status?.sandbox?.name??Z;if(this.sentinelToken!==null)return null;let Y=gK4(X);if(!Y)return null;let G=await this.openAndProbeDaemon(Q,Z);if(!G)return null;let J=nK4(X);if(this.previewGateway)await this.ensureServicePortForAdoptedSandbox(Q).catch((W)=>{console.warn(`[${H6}] Service port backfill failed for ${Z}: ${W instanceof Error?W.message:String(W)}`)}),await this.ensureHttpRouteForHandle(Z,Q,J).catch((W)=>{console.warn(`[${H6}] HTTPRoute backfill failed for ${Z}: ${W instanceof Error?W.message:String(W)}`)});return{id:$,handle:Z,adoptedSandboxName:Q,token:Y,workdir:wn0,daemonUrl:G.daemonUrl,daemonForward:G.daemonForward,workload:null,daemonBootId:G.bootId,tenant:J,ensureOpts:null}}async openAndProbeDaemon($,Z){let X=await this.openForwarder($,tH,Z).catch(()=>null);if(!X)return null;let Q=`http://127.0.0.1:${X.localPort}`,Y=await lO0(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($);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($);if(!Z)return null;let X=Z.state.ensureOpts;if(!X)return null;let Q=await this.withFreshCredentials(X);if(yE(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.dropRecord(Z)}dropRecord($){if(this.closeForwarder($.daemonForward),this.metrics&&this.activeGauge.consume($.handle))this.metrics.active.add(-1,jn0($.tenant))}recordProxyDuration($,Z,X,Q,Y){if(!this.metrics)return;this.metrics.proxyDurationMs.record(Q,{...jn0(X?.tenant??null),source:$,sandbox_handle:X?.handle??Y??"",status_code:Z||0})}composePreviewUrl($){if(this.previewUrlPattern)return X70(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,{handle:Z.handle,state:X})}computeShutdownTime(){return new Date(Date.now()+this.idleTtlMs).toISOString()}async releaseAfter($,Z){let X=await lH(this.kubeConfig,this.namespace,$);if(!X)return;let Q=tK4(X.spec?.lifecycle?.shutdownTime,new Date(Date.now()+Z));if(!Q)return;await P70(this.kubeConfig,this.namespace,$,Q).catch((Y)=>console.warn(`[${H6}] release failed for ${$}: ${Y instanceof Error?Y.message:String(Y)}`))}async renewTtl($){let Z=await lH(this.kubeConfig,this.namespace,$);if(!Z)return;let X=oK4(Z.spec?.lifecycle?.shutdownTime,new Date(Date.now()+this.idleTtlMs));if(!X)return;await P70(this.kubeConfig,this.namespace,$,X).catch((Q)=>console.warn(`[${H6}] TTL renew failed for ${$}: ${Q instanceof Error?Q.message:String(Q)}`))}openForwarder($,Z,X=$){let Q=hK4(X,Z);return new Promise((Y,G)=>{let J=(W,K)=>{let F=nG$.createServer((H)=>this.handleForwardedConnection(H,$,Z,X));F.once("error",(H)=>{if(H.code==="EADDRINUSE"&&K<bK4){try{F.close()}catch{}let N=zn0+(W-zn0+1)%tG$;J(N,K+1);return}G(H)}),F.listen(W,"127.0.0.1",()=>{let H=F.address();if(!H||typeof H==="string"){F.close(),G(Error("port-forward listener failed to bind"));return}Y({server:F,localPort:H.port})})};J(Q,0)})}handleForwardedConnection($,Z,X,Q){let Y=new TK4,G=null,J=!1,W=()=>{if(J)return;if(J=!0,Y.destroy(),G)try{G.close()}catch{}if(!$.destroyed)$.destroy()};$.pipe(Y),$.on("error",W),$.on("close",W),this.portForward.portForward(this.namespace,Z,[X],$,null,Y).then((K)=>{let F=typeof K==="function"?K():K;if(!F){W();return}if(G=F,G.on("close",W),G.on("error",(H)=>{console.warn(`[${H6}] port-forward to ${Z}:${X} dropped mid-connection: ${lG$(H)}`,JSON.stringify(Pn0(H))),this.invalidateRecord(Q),W()}),J)try{G.close()}catch{}}).catch((K)=>{console.warn(`[${H6}] port-forward to ${Z}:${X} failed: ${lG$(K)}`,JSON.stringify(Pn0(K))),this.invalidateRecord(Q),W()})}closeForwarder($){$.server.close((Z)=>{if(Z)console.warn(`[${H6}] 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.dropRecord($);this.records.clear()}}function xK4($){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 Pn0($){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?Pn0(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 yK4(){let $=new AO0;return $.loadFromDefault(),$}function iG$($){return Boolean($.status?.conditions?.some((Z)=>Z.type==="Ready"&&Z.status==="True"))}function gK4($){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 hK4($,Z){let X=zK4("sha256").update(`${$}:${Z}`).digest();return zn0+X.readUInt32BE(0)%tG$}function Ln0($,Z){return new Response(JSON.stringify(Z),{status:$,headers:{"content-type":"application/json","access-control-allow-origin":"*"}})}function pG$($){let Z=$.slice(0,lK4);return uK4.test(Z)?Z:""}function dK4($){if($===void 0)return null;let Z=$.trim();if(Z==="")return null;if(!cK4.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 En0($,Z={}){let X={...Z};if($){let Q=pG$($.orgId),Y=pG$($.userId);if(Q)X[QQ.orgId]=Q;if(Y)X[QQ.userId]=Y}return X}function wC($){let Z="";for(let X of $){let Q=X.codePointAt(0)??0;Z+=Q<32||Q===127?" ":X}return Z.slice(0,mK4)}function iK4($){try{let Z=new URL($);return Z.username="",Z.password="",Z.toString()}catch{return""}}function pK4($){let Z={},X=$.tenant;if(X?.orgSlug)Z[d3.orgSlug]=wC(X.orgSlug);if(X?.orgName)Z[d3.orgName]=wC(X.orgName);if(X?.userEmail)Z[d3.userEmail]=wC(X.userEmail);if(X?.userName)Z[d3.userName]=wC(X.userName);let Q=$.repo;if(Q){if(Q.displayName)Z[d3.gitRepo]=wC(Q.displayName);let Y=iK4(Q.cloneUrl);if(Y)Z[d3.gitRepoUrl]=wC(Y);let G=$.branch??Q.branch;if(G)Z[d3.gitBranch]=wC(G)}return Z}function nK4($){let Z=$.metadata?.labels;if(!Z)return null;let X=Z[QQ.orgId],Q=Z[QQ.userId];if(!X||!Q)return null;let Y=$.metadata?.annotations??{};return{orgId:X,userId:Q,orgSlug:Y[d3.orgSlug],orgName:Y[d3.orgName],userEmail:Y[d3.userEmail],userName:Y[d3.userName]}}function tK4($,Z){if($){let X=new Date($).getTime();if(Number.isFinite(X)&&X<=Z.getTime())return null}return Z.toISOString()}function oK4($,Z){if($){let X=new Date($).getTime();if(Number.isFinite(X)&&X>=Z.getTime())return null}return Z.toISOString()}function jn0($){return{org_id:$?.orgId??"",user_id:$?.userId??"",runner_kind:"agent-sandbox"}}async function rK4($,Z){if(!Z||!$.tenant)return $.orgFsConfigJson;try{return await Z($.tenant)??$.orgFsConfigJson}catch(X){return console.warn(`[${H6}] org-fs credential re-mint failed: ${X instanceof Error?X.message:String(X)}`),$.orgFsConfigJson}}function aK4($){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($.purpose)Z.purpose=$.purpose;if($.orgFsConfigJson)Z.orgFsConfigJson=$.orgFsConfigJson;return Object.keys(Z).length>0?Z:null}function sK4($,Z){try{return new URL(X70($,Z)).hostname||null}catch{return null}}var H6="AgentSandboxProvider",LC="x-sandbox-preview-not-ready",RK4="agent-sandbox-system",IK4="studio-sandbox",qK4=300000,tH=9000,cG$=3000,wn0="/app",MK4=32,kK4,VK4=900000,SK4=60000,CK4=1800000,dO0=3,dG$=1800000,_K4=900000,vK4=1800000,fK4,mG$,zn0=40000,tG$=1e4,bK4=256,QQ,d3,uK4,lK4=63,cK4,mK4=253;var oG$=D(()=>{X4();a5$();AG$();kG$();rm0();A70();E70();vG$();Dn0();kK4=new Set(["DAEMON_TOKEN","DAEMON_BOOT_ID","APP_ROOT","PROXY_PORT"]),fK4=["cookie","host","connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","accept-encoding","content-length","upgrade"],mG$=["connection","keep-alive","transfer-encoding","content-encoding","content-length"];QQ={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"},d3={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"},uK4=/^([A-Za-z0-9]([-A-Za-z0-9_.]*[A-Za-z0-9])?)?$/;cK4=/^[a-z]([a-z0-9-]{0,30}[a-z0-9])?$/});var rG$={};L4(rG$,{parseTenantPools:()=>fG$,PREVIEW_NOT_READY_HEADER:()=>LC,AgentSandboxProvider:()=>An0});var Tn0=D(()=>{oG$();Dn0()});var eG$={};L4(eG$,{subscribeLifecycle:()=>Vn0,getOrInitSharedRunner:()=>kn0,getAgentSandboxProviderForTeardown:()=>Mn0,getAgentSandboxProvider:()=>YQ,__resetSharedLifecyclesForTesting:()=>KF4});function In0($){let Z=kn[aG$];if(Z)return Promise.resolve(Z);let X=kn[Rn0];if(X)return X;let Q=$().then((Y)=>{return kn[aG$]=Y,Y}).finally(()=>{delete kn[Rn0]});return kn[Rn0]=Q,Q}function eK4(){let $=process.env.STUDIO_SANDBOX_PREVIEW_URL_PATTERN;return $&&$.trim()!==""?$:void 0}function $F4(){let $=process.env.STUDIO_SANDBOX_TEMPLATE_NAME;return $&&$.trim()!==""?$:void 0}function ZF4(){let $=process.env.STUDIO_ENV;return $&&$.trim()!==""?$:void 0}function XF4(){let $=process.env.STUDIO_SANDBOX_SENTINEL_TOKEN;return $&&$.trim()!==""?$:void 0}function QF4(){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 qn0($){let Z=new Qn($),X=eK4(),{AgentSandboxProvider:Q,parseTenantPools:Y}=await Promise.resolve().then(() => (Tn0(),rG$)),G=new JH(_0().encryptionKey);return new Q({stateStore:Z,previewUrlPattern:X,sandboxTemplateName:$F4(),envName:ZF4(),previewGateway:QF4(),sentinelToken:XF4(),tenantPools:Y(process.env.STUDIO_SANDBOX_TENANT_POOLS),meter:J$,mintCloneUrl:async(J,W)=>{if(!J.connectionId)return null;let K=C5$(J.cloneUrl);if(!K)return null;let{cloneUrl:F}=await MK(J.connectionId,K.owner,K.name,$,G,{bufferMs:W?.bufferMs});return F},mintOrgFsConfig:async(J)=>{if(!J.orgSlug)return null;return await L70({boundAuth:{apiKey:{create:(K)=>a$.api.createApiKey({body:{...K,userId:J.userId}})}},storage:{orgRepoSyncs:new cE($)}},{orgSlug:J.orgSlug,orgId:J.orgId,baseUrl:y9()})??null}})}function YQ($){if(!_0().agentSandboxEnabled)throw Error("Agent sandbox is disabled. Set STUDIO_AGENT_SANDBOX_ENABLED=true to enable it.");return In0(()=>qn0($.db))}function Mn0($){return In0(()=>qn0($.db))}async function kn0(){if(!_0().agentSandboxEnabled)return null;return In0(()=>qn0(U8().db))}function Vn0($,Z,X){let Q=hO.get(Z);if(Q){if(Q.terminated){if(Q.lastPhase)try{X(Q.lastPhase)}catch{}return{unsubscribe:JF4}}if(Q.listeners.add(X),Q.lastPhase)try{X(Q.lastPhase)}catch{}return sG$(Z,Q,X)}let Y=new AbortController,G={lastPhase:null,terminated:!1,listeners:new Set([X]),abort:Y};return hO.set(Z,G),WF4($,Z,G),sG$(Z,G,X)}function JF4(){}function sG$($,Z,X){return{unsubscribe(){if(hO.get($)!==Z)return;if(Z.listeners.delete(X),Z.listeners.size===0)hO.delete($),Z.abort.abort()}}}async function WF4($,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 W of J)try{W(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(hO.get(Z)===X)hO.delete(Z)}}function KF4(){for(let $ of hO.values())$.abort.abort();hO.clear()}var aG$,Rn0,kn,YF4,GF4,hO;var m3=D(()=>{mG();W6();Fi0();Vy();$d();L$();lE();cY();X9();aG$=Symbol.for("decocms.sandbox.lifecycle.agent-sandbox-runner"),Rn0=Symbol.for("decocms.sandbox.lifecycle.agent-sandbox-inflight"),kn=globalThis;YF4=Symbol.for("decocms.sandbox.lifecycle.shared-lifecycles"),GF4=globalThis,hO=GF4[YF4]??=new Map});async function Vn($,Z,X){try{await $.storage.threads.stampRuntimeIfAbsent(Z,X)}catch(Q){console.warn(`[stampRuntimeIfAbsent] ${Z}: ${Q instanceof Error?Q.message:String(Q)}`)}}function $J$($){let Z=$?.trim();if(!Z)return null;try{let X=new URL(Z);if(X.protocol!=="http:"&&X.protocol!=="https:")return null;return X.href}catch{return null}}function mO0($){return $J$($?.previewServerUrl)??$J$($?.productionUrl)}var Sn0=()=>{};function EC($){return $==="cms"||$==="sandbox"?$:null}function FF4($){return!!mO0($)&&$?.fastPreview===!0}function iO0($){return FF4($)?"cms":"sandbox"}var Cn0;var py=D(()=>{Sn0();Cn0=["cms","sandbox"]});function ZJ$($){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(HF4.has(Z))return null;if(typeof Q==="string"&&Q.length>0&&Z===Q)return null;return Z}function pO0($){if(!$.branch.startsWith("thread:"))return $.branch;if($.sticky&&$.recordedHeadRef)return $.recordedHeadRef;return $.derivedRef}var HF4;var nO0=D(()=>{HF4=new Set(["main","master","trunk","develop","HEAD"])});import{z as oH}from"zod";async function ny($,Z){t(Z);let X=n(Z),Q=o0(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 gE(Z,$.branch,Q),W=qK(M9(G),J,$.branch),K=await YQ(Z);if(W){if(await K.alive(W.sandboxHandle).catch(()=>!0))return W;await TO(Z.storage.virtualMcps,$.virtualMcpId,Q,J,$.branch).catch((O)=>{console.warn("[ensureSandbox] failed to reap stale entry",O)})}let F=ZJ($.branch)??Z.metadata?.threadId;if(F)Vn(Z,F,"sandbox");let N=await IO(Z,F)??G.githubRepo??null;await $.onColdStart?.().catch(()=>{});let{entry:U}=await QJ$({ctx:Z,userId:Q,sandboxUserId:J,orgId:X.id,virtualMcpId:$.virtualMcpId,branch:$.branch,metadata:G,githubRepo:N,threadRepos:await Zi0(Z,F),existing:null,runner:K,...$.purpose?{purpose:$.purpose}:{}});return U}async function NF4($){let Z=$.primary?`${$.primary.owner}/${$.primary.name}`.toLowerCase():null,X=$.repos.filter((G)=>`${G.owner}/${G.name}`.toLowerCase()!==Z),Q=rp(X),Y=[];for(let[G,J]of X.entries()){if(!J.connectionId)continue;try{let{cloneUrl:W}=await MK(J.connectionId,J.owner,J.name,$.ctx.db,$.ctx.vault);Y.push({cloneUrl:W,connectionId:J.connectionId,userName:$.gitUserName,userEmail:$.gitUserEmail,displayName:`${J.owner}/${J.name}`,directoryName:Q[G],submoduleCredentials:[]})}catch(W){console.warn(`[provisionSandbox] skipping secondary ${J.owner}/${J.name}:`,W instanceof Error?W.message:W)}}return Y}async function QJ$($){let{ctx:Z,userId:X,sandboxUserId:Q,orgId:Y,virtualMcpId:G,branch:J,metadata:W,threadRepos:K,existing:F,runner:H,purpose:N}=$,U=N==="harness-run",B=$.githubRepo?await UF4({ctx:Z,orgId:Y,virtualMcpId:G,userId:X,githubRepo:$.githubRepo}):null,{runtime:O,packageManager:w,port:L,packageManagerPath:E}=F5$(W),j;if(B){if(B.connectionId)await kO({ctx:Z,connectionId:B.connectionId,organizationId:Y,forceRefresh:!0,onLegacyMintError:(I0)=>{console.error("[provisionSandbox] repo-scoped legacy token mint failed",{connectionId:B.connectionId,error:I0.message})}});let{cloneUrl:a,gitUserName:r,gitUserEmail:z0}=B.connectionId?await MK(B.connectionId,B.owner,B.name,Z.db,Z.vault):E5$(B.owner,B.name);if(!w){let I0=B.connectionId?await P5$(B.connectionId,B.owner,B.name,Z.db,Z.vault):await A5$(B.owner,B.name);if(I0)w=I0.packageManager,O=ap[I0.packageManager].runtime,L=I0.devPort??L,await BF4(Z,G,X,I0.packageManager,I0.devPort)}let Z0=_0().sandboxStickyHeadRefEnabled,A0=pO0({branch:J,derivedRef:uH(J),recordedHeadRef:Z0?await Q5$(Z,ZJ(J)):null,sticky:Z0}),g0=await U5$({ctx:Z,orgId:Y,userId:X,entries:W5$(W)});j={cloneUrl:a,...B.connectionId?{connectionId:B.connectionId}:{},userName:r,userEmail:z0,branch:A0,displayName:`${B.owner}/${B.name}`,submoduleCredentials:g0}}let z=await NF4({ctx:Z,orgId:Y,repos:K??[],primary:B,gitUserName:j?.userName??"",gitUserEmail:j?.userEmail??""}),P=O&&w&&!U?{runtime:O,packageManager:w,...L!==null?{devPort:Number(L)}:{},...E?{packageManagerPath:E}:{}}:void 0,A=np({orgId:Y,virtualMcpId:G,branch:J}),I=!_0().orgFsMountsDisabled,k;if(I){let a=Z.organization?.slug??(await Z.db.selectFrom("organization").select(["slug"]).where("id","=",Y).executeTakeFirst())?.slug;if(a)k=await L70(Z,{orgSlug:a,orgId:Y,baseUrl:y9()})}await DF4(H);let M=await H.ensure({userId:Q,projectRef:A},{branch:J,repo:j,extraRepos:z,workload:P,cloneOnly:U,...N?{purpose:N}:{},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}:{}},...k?{orgFsConfigJson:k}:{}}),S=My(W);await W70({ctx:Z,runner:H,handle:M.handle,orgId:Y,userId:X,entries:S});let f=!!F&&F.sandboxHandle===M.handle&&F?.createdAt?F.createdAt:Date.now(),b=W.runtime?.selected??null,i=W.runtime?.port??null,l=W.runtime?.path??null,o={sandboxHandle:M.handle,previewUrl:M.previewUrl,createdAt:f,startedWith:{packageManager:b,port:i,path:l}};await p6$(Z.storage.virtualMcps,G,X,Q,J,o);let U0=ZJ(J)??Z.metadata?.threadId;if(U0)await G5$(Z,U0,Q,J,o);let j0=!F||F.sandboxHandle!==M.handle;return{entry:o,isNewVm:j0}}async function UF4($){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:W}=await Z.storage.connections.list(X),K=BZ0(W,G.owner,G.name);if(!K)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:K.id});try{let H=(await Z.storage.virtualMcps.findById(Q))?.metadata??{},N=H.githubRepo;if(N?.connectionId===G.connectionId){let U=V5(K);await Z.storage.virtualMcps.update(Q,Y,{metadata:{...H,githubRepo:{...N,connectionId:K.id,...U?{installationId:U.installationId}:{}}}})}}catch(F){console.warn("[provisionSandbox] failed to persist healed repo connection",{virtualMcpId:Q,error:F.message})}return{...G,connectionId:K.id}}async function BF4($,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 DF4($){let Z=Date.now()+XJ$,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(XJ$/1000)}s`);if(!X)X=!0,console.warn("[ensureSandbox] waiting for cluster capacity \u2014 a sandbox pod cannot be scheduled right now");await w$(OF4)}}var _n0,XJ$=150000,OF4=5000;var Sn=D(()=>{op();X4();M0();sp();Gi0();B5$();pQ();fQ();Vy();R5$();sm0();m3();py();h3();nO0();L$();X9();lE();pQ();_n0=u({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:oH.object({virtualMcpId:oH.string().describe("Virtual MCP ID"),branch:oH.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."),threadId:oH.string().optional().describe("The session asking for a sandbox. A thread stamped `cms` is refused \u2014 that session reads and writes over the decofile API and a pod would be invisible to it. Optional: an unstamped (legacy) thread is always allowed, and so is a caller with no thread.")}),outputSchema:oH.object({previewUrl:oH.string().nullable(),sandboxHandle:oH.string(),branch:oH.string(),isNewVm:oH.boolean()}),handler:async($,Z)=>{t(Z);let X=n(Z);await Z.access.check();let Q=$.branch??N70(H70(Z.auth.user)),Y=ZJ(Q)??$.threadId??Z.metadata?.threadId;if(Y){let w=await Z.storage.threads.get(Y).catch(()=>null);if(EC(w?.metadata?.runtime)==="cms")throw Error("This chat is a CMS session and does not use a sandbox. Start a coding session to get one.")}let G=o0(Z);if(!G)throw Error("User ID required");let J=await gE(Z,Q,G),W=await Z.storage.virtualMcps.findById($.virtualMcpId);if(!W||W.organization_id!==X.id)throw Error("Virtual MCP not found");let K=W.metadata??{},F=await YQ(Z),H=qK(M9(K),J,Q),U=await IO(Z,ZJ(Q)??Z.metadata?.threadId)??K.githubRepo??null,{entry:B,isNewVm:O}=await QJ$({ctx:Z,userId:G,sandboxUserId:J,orgId:X.id,virtualMcpId:$.virtualMcpId,branch:Q,metadata:K,githubRepo:U,threadRepos:await Zi0(Z,ZJ(Q)??Z.metadata?.threadId),existing:H,runner:F});if(Y)Vn(Z,Y,"sandbox");return{...B,branch:Q,isNewVm:O}}})});function wF4($){let{publicUrl:Z,agentId:X,organization:Q,target:Y,threadId:G}=$;if(Y==="agent-tools")return`${Z}/mcp/virtual-mcp/${encodeURIComponent(X)}`;if(!Q.slug)throw new GJ$(Q.id,Y);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 tO0($,Z,X,Q,Y="agent-tools",G,J={"*":["*"]}){let W=wF4({publicUrl:y9(),agentId:Z,organization:X,target:Y,...G?{threadId:G}:{}}),K=await $.boundAuth.apiKey.create({name:Q,permissions:J,expiresIn:YJ$,metadata:{organization:{id:X.id,slug:X.slug,name:X.name}}});return{url:W,headers:{Authorization:`Bearer ${K.key}`,"x-org-id":X.id},expiresAt:Date.now()+YJ$*1000}}function JJ$($){let{publicUrl:Z,organizationSlug:X,headers:Q,connections:Y}=$,G=new Set;return Y.map((J)=>{let W=LF4(J.slug??J.title??"")||"mcp",K=W;for(let F=2;G.has(K);F++)K=`${W}-${F}`;return G.add(K),{name:K,url:`${Z}/api/${X}/mcp/${encodeURIComponent(J.id)}`,headers:Q}})}function LF4($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function WJ$($){return{self:[...$.toolNames],...$.grants}}var YJ$=3600,GJ$;var vn0=D(()=>{X9();GJ$=class GJ$ extends Error{constructor($,Z){super(`cannot mint a "${Z}" MCP endpoint for organization "${$}": the org-scoped path needs the org slug, which was not loaded.`);this.name="MissingOrganizationSlugError"}}});async function EF4($,Z,X,Q){try{let Y=$.organization;if(!Y)return;let G=await tO0($,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("[agent-sandbox-fs] tools/sync failed",J.status,await J.text().catch(()=>""))}catch(Y){console.warn("[agent-sandbox-fs] tools/sync failed",Y)}}async function ty($,Z){let X=await YQ($),Q=null,Y=()=>{if(!Q){if(Q=ny({virtualMcpId:Z.virtualMcpId,branch:Z.branch},$).then((W)=>W.sandboxHandle),Q.catch(()=>{Q=null}),Z.syncTools)Q.then((W)=>EF4($,X,W,{virtualMcpId:Z.virtualMcpId})).catch(()=>{})}return Q},G=Z.branch==="ephemeral";return am0(X,{ensureHandle:Y,invalidateHandle:async(W)=>{if(Q=null,!G&&!W?.force)return;try{await TO($.storage.virtualMcps,Z.virtualMcpId,Z.userId,Z.userId,Z.branch)}catch(K){console.warn("[agent-sandbox-fs] failed to reap vmMap entry",K)}},canAutoRestart:G,threadId:Z.threadId})}async function KJ$($,Z){try{let X=await ty($,Z),{stdout:Q}=await X.onBash("test -d .deco && echo __DECO_SITE__");return Q.includes("__DECO_SITE__")}catch(X){return console.warn("[agent-sandbox-fs] .deco probe failed; assuming deco site",X),!0}}var oO0=D(()=>{op();vn0();m3();Sn();pQ()});import{z as FJ$}from"zod";function oy($){let Z=[];for(let X of $){if(X.status!=="active")continue;let Q=V5(X);if(!Q)continue;Z.push({connectionId:X.id,owner:Q.owner,repo:Q.repo,installationId:Q.installationId})}return Z}async function zF4($,Z){let{items:X}=await $.storage.connections.list(Z,{slug:"mcp-github"});return oy(X)}function PF4($){let Z=$.split(`
980
+ `);return g4.from(X)};AW4.decodePax=function(Z){let X={};while(Z.length){let Q=0;while(Q<Z.length&&Z[Q]!==32)Q++;let Y=parseInt(g4.toString(Z.subarray(0,Q)),10);if(!Y)return X;let G=g4.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};AW4.encode=function(Z){let X=g4.alloc(512),Q=Z.name,Y="";if(Z.typeflag===5&&Q[Q.length-1]!=="/")Q+="/";if(g4.byteLength(Q)!==Q.length)return null;while(g4.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(g4.byteLength(Q)>100||g4.byteLength(Y)>155)return null;if(Z.linkname&&g4.byteLength(Z.linkname)>100)return null;if(g4.write(X,Q),g4.write(X,gO(Z.mode&4095,6),100),g4.write(X,gO(Z.uid,6),108),g4.write(X,gO(Z.gid,6),116),zW4(Z.size,X,124),g4.write(X,gO(Z.mtime.getTime()/1000|0,11),136),X[156]=48+EW4(Z.type),Z.linkname)g4.write(X,Z.linkname,157);if(g4.copy(SY$,X,257),g4.copy(NW4,X,263),Z.uname)g4.write(X,Z.uname,265);if(Z.gname)g4.write(X,Z.gname,297);if(g4.write(X,gO(Z.devmajor||0,6),329),g4.write(X,gO(Z.devminor||0,6),337),Y)g4.write(X,Y,345);return g4.write(X,gO(_Y$(X),6),148),X};AW4.decode=function(Z,X,Q){let Y=Z[156]===0?0:Z[156]-48,G=dy(Z,0,100,X),J=yO(Z,100,8),W=yO(Z,108,8),K=yO(Z,116,8),F=yO(Z,124,12),H=yO(Z,136,12),N=LW4(Y),U=Z[157]===0?null:dy(Z,157,100,X),B=dy(Z,265,32),O=dy(Z,297,32),w=yO(Z,329,8),L=yO(Z,337,8),E=_Y$(Z);if(E===256)return null;if(E!==yO(Z,148,8))throw Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");if(OW4(Z)){if(Z[345])G=dy(Z,345,155,X)+"/"+G}else if(DW4(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:W,gid:K,size:F,mtime:new Date(1000*H),type:N,linkname:U,uname:B,gname:O,devmajor:w,devminor:L,pax:null}};function OW4($){return g4.equals(SY$,$.subarray(257,263))}function DW4($){return g4.equals(UW4,$.subarray(257,263))&&g4.equals(BW4,$.subarray(263,265))}function wW4($,Z,X){if(typeof $!=="number")return X;if($=~~$,$>=Z)return Z;if($>=0)return $;if($+=Z,$>=0)return $;return 0}function LW4($){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 EW4($){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 CY$($,Z,X,Q){for(;X<Q;X++)if($[X]===Z)return X;return Q}function _Y$($){let Z=256;for(let X=0;X<148;X++)Z+=$[X];for(let X=156;X<512;X++)Z+=$[X];return Z}function gO($,Z){if($=$.toString(8),$.length>Z)return"7777777777777777777".slice(0,Z)+" ";return"0000000000000000000".slice(0,Z-$.length)+$+" "}function jW4($,Z,X){Z[X]=128;for(let Q=11;Q>0;Q--)Z[X+Q]=$&255,$=Math.floor($/256)}function zW4($,Z,X){if($.toString(8).length>11)jW4($,Z,X);else g4.write(Z,gO($,11),X)}function PW4($){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 yO($,Z,X){if($=$.subarray(Z,Z+X),Z=0,$[Z]&128)return PW4($);else{while(Z<$.length&&$[Z]===32)Z++;let Q=wW4(CY$($,32,Z,$.length),$.length,$.length);while(Z<Q&&$[Z]===0)Z++;if(Q===Z)return 0;return parseInt(g4.toString($.subarray(Z,Q)),8)}}function dy($,Z,X,Q){return g4.toString($.subarray(Z,CY$($,0,Z,Z+X)),Q)}function Xn0($){let Z=g4.byteLength($),X=Math.floor(Math.log(Z)/Math.log(10))+1;if(Z+X>=Math.pow(10,X))X++;return Z+X+$}});var uY$=_((SP9,hY$)=>{var{Writable:kW4,Readable:VW4,getStreamError:vY$}=Zn0(),SW4=op0(),fY$=cy(),my=Qn0(),CW4=fY$.alloc(0);class bY${constructor(){this.buffered=0,this.shifted=0,this.queue=new SW4,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 CW4;let Z=this._next($);if($===Z.byteLength)return Z;let X=[Z];while(($-=Z.byteLength)>0)Z=this._next($),X.push(Z);return fY$.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 xY$ extends VW4{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(vY$(this))}_detach(){if(this._parent._stream===this)this._parent._stream=null,this._parent._missing=gY$(this.header.size),this._parent._update()}_destroy($){this._detach(),$(null)}}class yY$ extends kW4{constructor($){super($);if(!$)$={};this._buffer=new bY$,this._offset=0,this._header=null,this._stream=null,this._missing=0,this._longHeader=!1,this._callback=Yn0,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=my.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=my.decodeLongPath($,this._filenameEncoding);break;case"gnu-long-link-path":this._gnuLongLinkPath=my.decodeLongPath($,this._filenameEncoding);break;case"pax-global-header":this._paxGlobal=my.decodePax($);break;case"pax-header":this._pax=this._paxGlobal===null?my.decodePax($):Object.assign({},this._paxGlobal,my.decodePax($));break}}_consumeLongHeader(){this._longHeader=!1,this._missing=gY$(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 xY$(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=Yn0,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(vY$(this));$(null)}[Symbol.asyncIterator](){let $=null,Z=null,X=null,Q=null,Y=null,G=this;return this.on("entry",K),this.on("error",(N)=>{$=N}),this.on("close",F),{[Symbol.asyncIterator](){return this},next(){return new Promise(W)},return(){return H(null)},throw(N){return H(N)}};function J(N){if(!Y)return;let U=Y;Y=null,U(N)}function W(N,U){if($)return U($);if(Q){N({value:Q,done:!1}),Q=null;return}if(Z=N,X=U,J(null),G._finished&&Z)Z({value:void 0,done:!0}),Z=X=null}function K(N,U,B){if(Y=B,U.on("error",Yn0),Z)Z({value:U,done:!1}),Z=X=null;else Q=U}function F(){if(J($),!Z)return;if($)X($);else Z({value:void 0,done:!0});Z=X=null}function H(N){return G.destroy(N),J(N),new Promise((U,B)=>{if(G.destroyed)return U({value:void 0,done:!0});G.once("close",function(){if(N)B(N);else U({value:void 0,done:!0})})})}}}hY$.exports=function(Z){return new yY$(Z)};function Yn0(){}function gY$($){return $&=511,$&&512-$}});var cY$=_((CP9,Gn0)=>{var lY$={S_IFMT:61440,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960};try{Gn0.exports=P0("fs").constants||lY$}catch{Gn0.exports=lY$}});var oY$=_((_P9,tY$)=>{var{Readable:_W4,Writable:vW4,getStreamError:dY$}=Zn0(),OC=cy(),iy=cY$(),fO0=Qn0(),mY$=OC.alloc(1024);class iY$ extends vW4{constructor($,Z,X){super({mapWritable:bW4,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?OC.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?OC.toString(this._linkname,"utf-8"):"",this._pack._encode(this.header);nY$(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 dY$(this)||Error("tar entry destroyed")}_predestroy(){this._pack.destroy(this._getError())}_destroy($){this._pack._done(this),this._continuePack(this._finished?null:this._getError()),$()}}class pY$ extends _W4{constructor($){super($);this._drain=Jn0,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=Jn0;if(!$.size||$.type==="symlink")$.size=0;if(!$.type)$.type=fW4($.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=OC.from(Z);let Q=new iY$(this,$,X);if(OC.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(mY$),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=fO0.encode($);if(Z){this.push(Z);return}}this._encodePax($)}_encodePax($){let Z=fO0.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(fO0.encode(X)),this.push(Z),nY$(this,Z.byteLength),X.size=$.size,X.type=$.type,this.push(fO0.encode(X))}_doDrain(){let $=this._drain;this._drain=Jn0,$()}_predestroy(){let $=dY$(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(),$()}}tY$.exports=function(Z){return new pY$(Z)};function fW4($){switch($&iy.S_IFMT){case iy.S_IFBLK:return"block-device";case iy.S_IFCHR:return"character-device";case iy.S_IFDIR:return"directory";case iy.S_IFIFO:return"fifo";case iy.S_IFLNK:return"symlink"}return"file"}function Jn0(){}function nY$($,Z){if(Z&=511,Z)$.push(mY$.subarray(0,512-Z))}function bW4($){return OC.isBuffer($)?$:OC.from($)}});var rY$=_((xW4)=>{xW4.extract=uY$();xW4.pack=oY$()});var eY$=_((fP9,sY$)=>{sY$.exports=aY$;function aY$($,Z){if($&&Z)return aY$($)(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(W){G[W]=J[W]});return G}}});var Kn0=_((bP9,Wn0)=>{var $G$=eY$();Wn0.exports=$G$(bO0);Wn0.exports.strict=$G$(ZG$);bO0.proto=bO0(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return bO0(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return ZG$(this)},configurable:!0})});function bO0($){var Z=function(){if(Z.called)return Z.value;return Z.called=!0,Z.value=$.apply(this,arguments)};return Z.called=!1,Z}function ZG$($){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 YG$=_((xP9,QG$)=>{var hW4=Kn0(),uW4=function(){},lW4=global.Bare?queueMicrotask:process.nextTick.bind(process),cW4=function($){return $.setHeader&&typeof $.abort==="function"},dW4=function($){return $.stdio&&Array.isArray($.stdio)&&$.stdio.length===3},XG$=function($,Z,X){if(typeof Z==="function")return XG$($,null,Z);if(!Z)Z={};X=hW4(X||uW4);var{_writableState:Q,_readableState:Y}=$,G=Z.readable||Z.readable!==!1&&$.readable,J=Z.writable||Z.writable!==!1&&$.writable,W=!1,K=function(){if(!$.writable)F()},F=function(){if(J=!1,!G)X.call($)},H=function(){if(G=!1,!J)X.call($)},N=function(L){X.call($,L?Error("exited with error code: "+L):null)},U=function(L){X.call($,L)},B=function(){lW4(O)},O=function(){if(W)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"))},w=function(){$.req.on("finish",F)};if(cW4($))if($.on("complete",F),$.on("abort",B),$.req)w();else $.on("request",w);else if(J&&!Q)$.on("end",K),$.on("close",K);if(dW4($))$.on("exit",N);if($.on("end",H),$.on("finish",F),Z.error!==!1)$.on("error",U);return $.on("close",B),function(){if(W=!0,$.removeListener("complete",F),$.removeListener("abort",B),$.removeListener("request",w),$.req)$.req.removeListener("finish",F);$.removeListener("end",K),$.removeListener("close",K),$.removeListener("finish",F),$.removeListener("exit",N),$.removeListener("end",H),$.removeListener("error",U),$.removeListener("close",B)}};QG$.exports=XG$});var WG$=_((yP9,JG$)=>{var mW4=Kn0(),iW4=YG$(),xO0;try{xO0=P0("fs")}catch($){}var Rn=function(){},pW4=typeof process>"u"?!1:/^v?\.0/.test(process.version),yO0=function($){return typeof $==="function"},nW4=function($){if(!pW4)return!1;if(!xO0)return!1;return($ instanceof(xO0.ReadStream||Rn)||$ instanceof(xO0.WriteStream||Rn))&&yO0($.close)},tW4=function($){return $.setHeader&&yO0($.abort)},oW4=function($,Z,X,Q){Q=mW4(Q);var Y=!1;$.on("close",function(){Y=!0}),iW4($,{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,nW4($))return $.close(Rn);if(tW4($))return $.abort();if(yO0($.destroy))return $.destroy();Q(J||Error("stream was destroyed"))}},GG$=function($){$()},rW4=function($,Z){return $.pipe(Z)},aW4=function(){var $=Array.prototype.slice.call(arguments),Z=yO0($[$.length-1]||Rn)&&$.pop()||Rn;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,W=G>0;return oW4(Y,J,W,function(K){if(!X)X=K;if(K)Q.forEach(GG$);if(J)return;Q.forEach(GG$),Z(X)})});return $.reduce(rW4)};JG$.exports=aW4});var wG$=_((ZK4)=>{var KG$=rY$(),FG$=WG$(),HG$=P0("fs"),F9=P0("path"),In=(global.Bare?global.Bare.platform:process.platform)==="win32";ZK4.pack=function(Z,X){if(!Z)Z=".";if(!X)X={};let Q=X.fs||HG$,Y=X.ignore||X.filter||qn,G=X.mapStream||OG$,J=$K4(Q,X.dereference?Q.stat:Q.lstat,Z,Y,X.entries,X.sort),W=X.strict!==!1,K=typeof X.umask==="number"?~X.umask:~NG$(),F=X.pack||KG$.pack(),H=X.finish||qn,N=X.map||qn,U=typeof X.dmode==="number"?X.dmode:0,B=typeof X.fmode==="number"?X.fmode:0;if(X.strip)N=DG$(N,X.strip);if(X.readable)U|=parseInt(555,8),B|=parseInt(444,8);if(X.writable)U|=parseInt(333,8),B|=parseInt(222,8);L();function O(E,j){Q.readlink(F9.join(Z,E),function(z,P){if(z)return F.destroy(z);j.linkname=Fn0(P),F.entry(j,L)})}function w(E,j,z){if(F.destroyed)return;if(E)return F.destroy(E);if(!j){if(X.finalize!==!1)F.finalize();return H(F)}if(z.isSocket())return L();let P={name:Fn0(j),mode:(z.mode|(z.isDirectory()?U:B))&K,mtime:z.mtime,size:z.size,type:"file",uid:z.uid,gid:z.gid};if(z.isDirectory())return P.size=0,P.type="directory",P=N(P)||P,F.entry(P,L);if(z.isSymbolicLink())return P.size=0,P.type="symlink",P=N(P)||P,O(j,P);if(P=N(P)||P,!z.isFile()){if(W)return F.destroy(Error("unsupported type for "+j));return L()}let A=F.entry(P,L),I=G(Q.createReadStream(F9.join(Z,j),{start:0,end:P.size>0?P.size-1:P.size}),P);I.on("error",function(k){A.destroy(k)}),FG$(I,A)}function L(E){if(E)return F.destroy(E);J(w)}return F};function sW4($){return $.length?$[$.length-1]:null}function eW4(){return!global.Bare&&process.getuid?process.getuid():-1}function NG$(){return!global.Bare&&process.umask?process.umask():0}ZK4.extract=function(Z,X){if(!Z)Z=".";if(!X)X={};Z=F9.resolve(Z);let Q=X.fs||HG$,Y=X.ignore||X.filter||qn,G=X.mapStream||OG$,J=X.chown!==!1&&!In&&eW4()===0,W=X.extract||KG$.extract(),K=[],F=new Date,H=typeof X.umask==="number"?~X.umask:~NG$(),N=X.strict!==!1,U=X.validateSymlinks!==!1,B=X.map||qn,O=typeof X.dmode==="number"?X.dmode:0,w=typeof X.fmode==="number"?X.fmode:0;if(X.strip)B=DG$(B,X.strip);if(X.readable)O|=parseInt(555,8),w|=parseInt(444,8);if(X.writable)O|=parseInt(333,8),w|=parseInt(222,8);if(W.on("entry",L),X.finish)W.on("finish",X.finish);return W;function L(A,I,k){A=B(A)||A,A.name=Fn0(A.name);let M=F9.join(Z,F9.join("/",A.name));if(Y(M,A))return I.resume(),k();let S=F9.join(M,".")===F9.join(Z,".")?Z:F9.dirname(M);BG$(Q,S,F9.join(Z,"."),function(o,U0){if(o)return k(o);if(!U0)return k(Error(S+" is not a valid path"));if(A.type==="directory")return K.push([M,A.mtime]),P(M,{fs:Q,own:J,uid:A.uid,gid:A.gid,mode:A.mode},m);P(S,{fs:Q,own:J,uid:A.uid,gid:A.gid,mode:493},function(j0){if(j0)return k(j0);switch(A.type){case"file":return l();case"link":return b();case"symlink":return f()}if(N)return k(Error("unsupported type for "+M+" ("+A.type+")"));I.resume(),k()})});function m(o){if(o)return k(o);j(M,A,function(U0){if(U0)return k(U0);if(In)return k();z(M,A,k)})}function f(){if(In)return k();Q.unlink(M,function(){let o=F9.resolve(F9.dirname(M),A.linkname);if(!i(o)&&U)return k(Error(M+" is not a valid symlink"));UG$(Q,o,F9.join(Z,"."),function(U0,j0){if(U0)return k(U0);if(!j0&&U)return k(Error(M+" is not a valid symlink"));Q.symlink(A.linkname,M,m)})})}function b(){if(In)return k();Q.unlink(M,function(){let o=F9.join(Z,F9.join("/",A.linkname));Q.realpath(o,function(U0,j0){if(U0||!i(j0))return k(Error(M+" is not a valid hardlink"));Q.link(j0,M,function(a){if(a&&a.code==="EPERM"&&X.hardlinkAsFilesFallback)return I=Q.createReadStream(j0),l();m(a)})})})}function i(o){return o===Z||o.startsWith(Z+F9.sep)}function l(){let o=Q.createWriteStream(M),U0=G(I,A);o.on("error",function(j0){U0.destroy(j0)}),FG$(U0,o,function(j0){if(j0)return k(j0);o.on("close",m)})}}function E(A,I){let k;while((k=sW4(K))&&A.slice(0,k[0].length)!==k[0])K.pop();if(!k)return I();Q.utimes(k[0],F,k[1],I)}function j(A,I,k){if(X.utimes===!1)return k();if(I.type==="directory")return Q.utimes(A,F,I.mtime,k);if(I.type==="symlink")return E(A,k);Q.utimes(A,F,I.mtime,function(M){if(M)return k(M);E(A,k)})}function z(A,I,k){let M=I.type==="symlink",S=M?Q.lchmod:Q.chmod,m=M?Q.lchown:Q.chown;if(!S)return k();let f=(I.mode|(I.type==="directory"?O:w))&H;if(m&&J)m.call(Q,A,I.uid,I.gid,b);else b(null);function b(i){if(i)return k(i);if(!S)return k();S.call(Q,A,f,k)}}function P(A,I,k){Q.stat(A,function(M){if(!M)return k(null);if(M.code!=="ENOENT")return k(M);Q.mkdir(A,{mode:I.mode,recursive:!0},function(S,m){if(S)return k(S);z(A,I,k)})})}};function UG$($,Z,X,Q){if(Z===X)return Q(null,!0);if(!Z.startsWith(X+F9.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 UG$($,F9.join(Z,".."),X,Q);Q(null,!1)})}function BG$($,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 BG$($,F9.join(Z,".."),X,Q);Q(null,!1)})}function qn(){}function OG$($){return $}function Fn0($){return In?$.replace(/\\/g,"/").replace(/[:?<>|]/g,"_"):$}function $K4($,Z,X,Q,Y,G){if(!Y)Y=["."];let J=Y.slice(0);return function(K){if(!J.length)return K(null);let F=J.shift(),H=F9.join(X,F);Z.call($,H,function(N,U){if(N)return K(Y.indexOf(F)===-1&&N.code==="ENOENT"?null:N);if(!U.isDirectory())return K(null,F,U);$.readdir(H,function(B,O){if(B)return K(B);if(G)O.sort();for(let w=0;w<O.length;w++)if(!Q(F9.join(X,F,O[w])))J.push(F9.join(F,O[w]));K(null,F,U)})})}}function DG$($,Z){return function(X){X.name=X.name.split("/").slice(Z).join("/");let Q=X.linkname;if(Q&&(X.type==="link"||F9.isAbsolute(Q)))X.linkname=Q.split("/").slice(Z).join("/");return $(X)}}});var YK4,GK4;var LG$=D(()=>{np0();YK4=V(YY$(),1),GK4=V(wG$(),1)});var gO0=()=>{};var EG$=D(()=>{aB0()});var jG$=D(()=>{IO0();RO0();gO0()});var zG$=()=>{};var PG$=()=>{};var AG$=D(()=>{hQ$();ip0();IO0();mQ$();dp0();np0();iQ$();pQ$();nQ$();tQ$();mp0();oQ$();LG$();gO0();EG$();jG$();zG$();PG$();gO0()});var hO0=D(()=>{X4();tm0()});function JK4($){if($ instanceof TypeError)return!0;if($ instanceof DOMException&&$.name==="AbortError")return!0;return!1}async function Hn0($,Z,X,Q){try{return await w6(async()=>{let G=await fetch($,{...Z,signal:AbortSignal.timeout(Q)});return{status:G.status,ok:G.ok,body:await G.text()}},{maxAttempts:3,minTimeout:50,maxTimeout:500,multiplier:2,jitter:0.5,isRetriable:JK4})}catch(Y){let G=Y instanceof Error?Y.message:String(Y);throw Error(`[SANDBOX_UNREACHABLE] sandbox daemon ${X} request failed: ${G}`,{cause:Y})}}async function lO0($){try{let Z=await fetch(`${$}/health`,{signal:AbortSignal.timeout(WK4)});if(!Z.ok){try{await Z.text()}catch{}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 Un0($){for(let Z=0;Z<TG$;Z++){if(await lO0($)!==null)return;let X=(Math.random()*2-1)*KK4;await w$(RG$+X)}throw Error(`sandbox daemon at ${$} did not respond on /health within ${TG$*RG$/1000}s`)}async function DC($,Z,X,Q,Y){return FK4($,Z,"POST",X,Q,Y)}async function FK4($,Z,X,Q,Y,G){let J={...Q};if(Y&&Y.rotateToken!==void 0)J.auth=Y;let W=await Hn0(`${$}/_sandbox/config`,{method:X,headers:{"Content-Type":"application/json",Authorization:`Bearer ${Z}`},body:JSON.stringify(J)},"/_sandbox/config",G?.timeoutMs??Nn0);if(!W.ok)throw new uO0(W.status,W.body);return MG$(W.body,"/_sandbox/config")}async function IG$($,Z,X){let Q=await Hn0(`${$}/_sandbox/setup/${X}`,{method:"POST",headers:{Authorization:`Bearer ${Z}`}},`/_sandbox/setup/${X}`,Nn0);if(!Q.ok)throw Error(`sandbox daemon /_sandbox/setup/${X} returned ${Q.status}: ${Q.body}`)}async function qG$($,Z,X){let Q=await Hn0(`${$}/_sandbox/orgfs-config`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Z}`},body:X},"/_sandbox/orgfs-config",Nn0);if(!Q.ok)throw Error(`sandbox daemon /_sandbox/orgfs-config returned ${Q.status}: ${Q.body}`);return MG$(Q.body,"/_sandbox/orgfs-config")}function MG$($,Z){try{return JSON.parse($)}catch(X){throw Error(`sandbox daemon ${Z} returned a malformed JSON body: ${$.slice(0,200)}`,{cause:X})}}async function Mn($,Z,X,Q){let Y=new Headers(Q.headers);for(let W of HK4)Y.delete(W);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 uO0,WK4=500,Nn0=30000,TG$=25,RG$=200,KK4=50,HK4;var kG$=D(()=>{hO0();X4();uO0=class uO0 extends Error{status;constructor($,Z){super(`sandbox daemon /_sandbox/config returned ${$}: ${Z}`);this.status=$;this.name="ConfigRequestError"}};HK4=["cookie","host","connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","accept-encoding","content-length"]});async function*CG$($){let Z=$.now??(()=>Date.now()),X=Z(),Q=$.schedulingTimeoutMs??UK4,Y={pod:{},sandbox:{},events:{hasPulling:!1,hasPulled:!1},startedAt:X},G=[],J=null,W=!1,K=(j)=>{if(W)return;if(J){let z=J;J=null,z(j)}else G.push(j)},F=()=>{if(G.length>0)return Promise.resolve(G.shift());if(W)return Promise.resolve(null);return new Promise((j)=>{J=j})},H=()=>{if(W)return;if(W=!0,J){let j=J;J=null,j(null)}},N=new AbortController,U=()=>{N.abort(),H()};if($.signal)if($.signal.aborted)N.abort(),H();else $.signal.addEventListener("abort",U,{once:!0});let B=Math.max(0,Q-(Z()-X)),O=setTimeout(()=>K("tick"),B+100),w,L=new Promise((j)=>{w=j}),E=Promise.allSettled([BK4($.kc,$.namespace,$.claimName,N.signal,Y,K,Z,w),DK4($.kc,$.namespace,$.claimName,N.signal,Y,K),wK4($.kc,$.namespace,$.claimName,L,N.signal,Y,K,Z)]);try{let j=null,z=-1,P=VG$(Y,Q,Z);if(j=On0(P),!Bn0(P))z=SG$(P);if(yield P,Bn0(P))return;while(!W){if(await F()===null)break;let I=VG$(Y,Q,Z);if(Bn0(I)){let S=On0(I);if(S!==j)j=S,yield I;return}let k=SG$(I);if(k<z)continue;let M=On0(I);if(M!==j)j=M,z=k,yield I}}finally{if(clearTimeout(O),N.abort(),$.signal)$.signal.removeEventListener("abort",U);H(),await E.catch(()=>{})}}function VG$($,Z,X){let{pod:Q,sandbox:Y,events:G,startedAt:J}=$;if(Y.ready)return{kind:"ready"};let W=Q.containerWaitingReason;if(W==="ImagePullBackOff"||W==="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(W==="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(W==="ContainerCreating"||W==="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 Bn0($){return $.kind==="ready"||$.kind==="failed"}function SG$($){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 On0($){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 BK4($,Z,X,Q,Y,G,J,W){let K=`/api/v1/namespaces/${encodeURIComponent(Z)}/pods?watch=true&labelSelector=${encodeURIComponent(`${NK4}=${X}`)}`;return cO0({kc:$,path:K,signal:Q,label:`pod/${X}`,onEvent:(F)=>{if(F.type!=="ADDED"&&F.type!=="MODIFIED")return;let H=F.object;if(H.metadata?.name)W(H.metadata.name);OK4(H,Y,J),G("pod")}})}function OK4($,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===K9.MAIN_CONTAINER_NAME);if(G)Z.pod.containerWaitingReason=G.state?.waiting?.reason,Z.pod.containerRunning=!!G.state?.running,Z.pod.containerReady=G.ready===!0}async function DK4($,Z,X,Q,Y,G){let J=`/apis/${K9.CLAIM_API_GROUP}/${K9.CLAIM_API_VERSION}/namespaces/${encodeURIComponent(Z)}/${K9.CLAIM_PLURAL}?watch=true&fieldSelector=${encodeURIComponent(`metadata.name=${X}`)}`;return cO0({kc:$,path:J,signal:Q,label:`sandboxclaim/${X}`,onEvent:(W)=>{if(W.type!=="ADDED"&&W.type!=="MODIFIED")return;let F=W.object.status?.conditions?.find((H)=>H.type==="Ready");if(!F)return;if(F.status==="True")Y.sandbox.ready=!0,Y.sandbox.notReadyReason=void 0,Y.sandbox.notReadyMessage=void 0;else Y.sandbox.ready=!1,Y.sandbox.notReadyReason=F.reason,Y.sandbox.notReadyMessage=F.message;G("sandbox")}})}async function wK4($,Z,X,Q,Y,G,J,W){let K=await Promise.race([Q,new Promise((H)=>{if(Y.aborted){H(X);return}Y.addEventListener("abort",()=>H(X),{once:!0})})]);if(Y.aborted)return;let F=`/api/v1/namespaces/${encodeURIComponent(Z)}/events?watch=true&fieldSelector=${encodeURIComponent(`involvedObject.name=${K},involvedObject.kind=Pod`)}`;return cO0({kc:$,path:F,signal:Y,label:`events/${X}`,onEvent:(H)=>{if(H.type!=="ADDED"&&H.type!=="MODIFIED")return;let N=H.object,U=N.reason;if(!U)return;switch(U){case"Pulling":G.events.hasPulling=!0;break;case"Pulled":G.events.hasPulling=!0,G.events.hasPulled=!0;break;case"FailedScheduling":G.events.lastFailedSchedulingAt=W(),G.events.failedSchedulingMessage=N.message;break;case"Nominated":{let B=N.message?.match(/nodeclaim\/([\w-]+)/);if(B)G.events.nominatedNodeClaim=B[1];break}default:return}J("event")}})}async function _G$($){let{kc:Z,namespace:X,labelSelector:Q,signal:Y,onDelete:G}=$,J=`/apis/${K9.CLAIM_API_GROUP}/${K9.CLAIM_API_VERSION}/namespaces/${encodeURIComponent(X)}/${K9.CLAIM_PLURAL}?watch=true&labelSelector=${encodeURIComponent(Q)}`;return cO0({kc:Z,path:J,signal:Y,label:"sandboxclaim-reaper",onEvent:(W)=>{if(W.type!=="DELETED")return;let K=W.object.metadata?.name;if(K)G(K)}})}async function cO0($){let{kc:Z,path:X,signal:Q,label:Y,onEvent:G}=$,J=0;while(!Q.aborted){try{let K=await oY(Z,{method:"GET",path:X,signal:Q,headers:{accept:"application/json"},stream:!0});if(!K.ok||!K.body){try{await K.body?.cancel()}catch{}if(K.status===401||K.status===403){console.warn(`[lifecycle-watcher] ${Y} stopped: watch denied (${K.status} ${K.statusText}). `+"The kubeconfig in use cannot watch SandboxClaims \u2014 if you are running locally, "+"this provider should not be active (check STUDIO_AGENT_SANDBOX_ENABLED).");return}throw Error(`watch handshake failed: ${K.status} ${K.statusText}`)}J=0;for await(let F of Li0(K.body)){if(Q.aborted)return;try{G(F)}catch(H){console.warn(`[lifecycle-watcher] ${Y} onEvent threw: ${H instanceof Error?H.message:String(H)}`)}}}catch(K){if(Q.aborted)return;let F=K instanceof Error?K.message:String(K);console.warn(`[lifecycle-watcher] ${Y} watch ended: ${F}`)}if(Q.aborted)return;let W=eZ(5000,250,J,2,0);J+=1,await w$(W,{signal:Q}).catch(()=>{})}}var NK4="studio.decocms.com/sandbox-handle",UK4=300000;var vG$=D(()=>{X4();E70();A70()});import{z as GJ}from"zod";function fG$($){if(!$||$.trim()==="")return[];let Z=GJ.array(LK4).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 EK4($){try{let[Z,X]=new URL($).pathname.replace(/^\/+/,"").split("/"),Q=X?.replace(/\.git$/,"");return Z&&Q?`${Z}/${Q}`.toLowerCase():null}catch{return null}}function bG$($,Z){let{orgId:X,cloneUrl:Q}=Z;if(Z.purpose==="harness-run")return null;if(!X||!Q)return null;let Y=EK4(Q);if(!Y)return null;return $.find((G)=>G.orgId===X&&G.repo.toLowerCase()===Y)??null}function xG$($,Z,X){return $?.name??(Z?X:"none")}function jK4($,Z){return $==="harness-run"?`${Z}-medium`:Z}async function yG$($){let Z=jK4($.purpose,$.templateName);if(Z===$.templateName)return{name:Z,probe:$.probe};let X=$.probe!==null&&$.now-$.probe.checkedAt<$.ttlMs?$.probe:{checkedAt:$.now,present:await $.exists(Z)};if(X.present)return{name:Z,probe:X};if($.probe?.present!==!1)$.onAbsent?.(Z);return{name:$.templateName,probe:X}}function gG$($,Z,X){let Q=X.replace(/^refs\/heads\//,"");return $.filter((Y)=>Y.repo.toLowerCase()===Z.toLowerCase()&&Y.branch===Q)}function hG$($){return`https://github.com/${$.repo}.git`}var LK4;var Dn0=D(()=>{LK4=GJ.object({name:GJ.string().regex(/^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/,"pool name must be a DNS label (lowercase alphanumeric and '-')"),orgId:GJ.string().min(1),repo:GJ.string().regex(/^[^/\s]+\/[^/\s]+$/,"repo must be `owner/name`"),connectionId:GJ.string().min(1).optional(),branch:GJ.string().min(1).default("main"),workload:GJ.object({runtime:GJ.enum(["node","bun","deno"]).default("node"),packageManager:GJ.enum(["npm","pnpm","yarn","bun","deno"]).optional(),packageManagerPath:GJ.string().optional(),devPort:GJ.number().int().positive().optional()}).default({runtime:"node"})})});async function uG$($,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 zK4,randomBytes as PK4,randomUUID as AK4}from"crypto";import*as nG$ from"net";import{PassThrough as TK4}from"stream";function lG$($){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 An0{records=new Map;inflight=new $70;activeGauge=new eZ0;stateStore;previewUrlPattern;kubeConfig;capacityProbe;portForward;namespace;sandboxTemplateName;envName;tokenGenerator;idleTtlMs;metrics;previewGateway;sentinelToken;mintCloneUrl;mintOrgFsConfig;tenantPools;tenantPoolRefreshMs;poolPods=new Map;mediumTemplateProbe=null;dirtyPools=new Set;closed=!1;claimWatchAbort=new AbortController;constructor($={}){this.stateStore=$.stateStore??null,this.previewUrlPattern=$.previewUrlPattern??null,this.kubeConfig=$.kubeConfig??yK4(),this.portForward=new tp0(this.kubeConfig),this.namespace=$.namespace??RK4,this.sandboxTemplateName=$.sandboxTemplateName??IK4,this.envName=dK4($.envName),this.tokenGenerator=$.tokenGenerator??(()=>PK4(MK4).toString("hex")),this.idleTtlMs=$.idleTtlMs??VK4,this.metrics=$.meter?xK4($.meter):null,this.previewGateway=$.previewGateway&&$.previewUrlPattern?{...$.previewGateway}:null;let Z=$.sentinelToken?.trim()??"";if(this.sentinelToken=Z.length>0?Z:null,this.mintCloneUrl=$.mintCloneUrl,this.mintOrgFsConfig=$.mintOrgFsConfig,this.tenantPools=this.sentinelToken!==null?$.tenantPools??[]:[],this.sentinelToken===null&&($.tenantPools?.length??0)>0)console.warn(`[${H6}] tenant pools configured without a sentinel token \u2014 ignoring them (warm-pool mode is off)`);this.tenantPoolRefreshMs=$.tenantPoolRefreshMs??CK4,this.startClaimReaper(),this.startCredentialRefresher(),this.startTenantPoolReconciler()}startClaimReaper(){let $=["app.kubernetes.io/managed-by=studio","app.kubernetes.io/name=studio-sandbox",...this.envName?[`${QQ.env}=${this.envName}`]:[]].join(",");_G$({kc:this.kubeConfig,namespace:this.namespace,labelSelector:$,signal:this.claimWatchAbort.signal,onDelete:(Z)=>this.invalidateRecord(Z)})}async ensure($,Z={}){let X=yE($);if(X.startsWith("s-"))throw Error(`ensure: projectRef has no slug source: ${$.projectRef}`);return this.inflight.run(X,()=>Z70(this.stateStore,$,(Q)=>this.ensureLocked($,X,Z,Q)))}async delete($){let Z=await this.getRecord($);if(this.records.delete($),Z)this.dropRecord(Z);if(await this.deleteHttpRouteIfManaged($).catch((X)=>{console.warn(`[${H6}] HTTPRoute delete failed for ${$}: ${X instanceof Error?X.message:String(X)}`)}),await Cy(this.kubeConfig,this.namespace,$),this.stateStore)if(Z)await this.stateStore.delete(Z.id);else await this.stateStore.deleteByHandle($)}lastTermination($){return h5$(this.kubeConfig,this.namespace,QQ.sandboxHandle,$,K9.MAIN_CONTAINER_NAME)}async alive($){return await lH(this.kubeConfig,this.namespace,$)!==void 0}watchClaimLifecycle($,Z){return CG$({kc:this.kubeConfig,namespace:this.namespace,claimName:$,signal:Z})}hasSchedulableCapacity(){return this.capacityProbe??=r5$(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 K=await this.stateStore.getByHandle($),F=K?.state,H=F?.token;if(K&&H){let U=`http://${F?.adoptedSandboxName??$}.${this.namespace}.svc.cluster.local:${tH}`;try{let B=await Mn(U,H,Z,X);if(B.status!==404)return B;try{await B.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,W=!(X.body instanceof ReadableStream);try{let K=await Mn(Q.daemonUrl,Q.token,Z,X);if(K.status===401&&W){this.invalidateRecord($);let F=await this.getRecord($).catch(()=>null)??await this.resurrectByHandle($).catch(()=>null);if(F){try{await K.body?.cancel()}catch{}Y=F,K=await Mn(F.daemonUrl,F.token,Z,X)}}return J=K.status,K}catch(K){if(!W)throw K;this.invalidateRecord($);let F=await this.resurrectByHandle($)??await this.getRecord($).catch(()=>null);if(!F)throw K;Y=F;let H=await Mn(F.daemonUrl,F.token,Z,X);return J=H.status,H}finally{this.recordProxyDuration("daemon",J,Y,performance.now()-G)}}async adoptLiveClaim($,Z){if(this.records.has(Z))return!0;let X=await lH(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 Z70(this.stateStore,$,(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:${tH}`;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($).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 O=Ln0(404,{error:"sandbox not found"});return O.headers.set(LC,"1"),O}let J=new URL(Z.url);if((J.pathname==="/_sandbox"||J.pathname.startsWith("/_sandbox/"))&&Z.method!=="GET")return Y=404,Ln0(404,{error:"not found"});let K=(O)=>`${O}${J.pathname}${J.search}`,F=new Headers(Z.headers);for(let O of fK4)F.delete(O);let H=Z.method!=="GET"&&Z.method!=="HEAD",N={method:Z.method,headers:F,body:H?Z.body:void 0,redirect:"manual",signal:Z.signal,duplex:H?"half":void 0},U;try{U=await fetch(K(G),N)}catch(O){let w=`${G}${J.pathname}`;if(console.warn(`[${H6}] preview fetch to ${w} failed: ${O instanceof Error?O.message:String(O)}`),Z.method==="GET"||Z.method==="HEAD"){if(this.invalidateRecord($),await this.resurrectByHandle($).catch(()=>null)){let j=await this.resolvePreviewUpstreamUrl($);if(j)try{U=await fetch(K(j),N);let z=new Headers;for(let[P,A]of U.headers.entries())if(!mG$.includes(P.toLowerCase()))z.set(P,A);return Y=U.status,new Response(U.body,{status:U.status,statusText:U.statusText,headers:z})}catch(z){console.warn(`[${H6}] preview fetch retry to ${w} failed: ${z instanceof Error?z.message:String(z)}`)}}}else this.invalidateRecord($);Y=502;let L=Ln0(502,{error:"sandbox daemon unreachable"});return L.headers.set(LC,"1"),L}let B=new Headers;for(let[O,w]of U.headers.entries())if(!mG$.includes(O.toLowerCase()))B.set(O,w);return Y=U.status,new Response(U.body,{status:U.status,statusText:U.statusText,headers:B})}finally{this.recordProxyDuration("preview",Y,Q,performance.now()-X,$)}}async ensureLocked($,Z,X,Q){if(X.image)console.warn(`[${H6}] opts.image ignored (template ${this.sandboxTemplateName} pins image): got ${X.image}`);if(Q){let J=await Q.get($);if(J){let W=await this.rehydrate($,Z,J);if(W)return await this.refreshDaemonGitCredential(W,X),await this.relayOrgFsConfig(W.daemonUrl,W.token,X.orgFsConfigJson),this.finish(W,Q,!1,!0,"resume");await Q.delete($)}}let Y=await lH(this.kubeConfig,this.namespace,Z).catch(()=>{return});if(Y)if(Y.metadata?.deletionTimestamp)await z70(this.kubeConfig,this.namespace,Z).catch((J)=>{console.warn(`[${H6}] wait for terminating claim ${Z} failed: ${J instanceof Error?J.message:String(J)}`)});else{let J=await this.adopt($,Z,Y).catch((W)=>{return console.warn(`[${H6}] adopt ${Z} failed, recreating: ${W instanceof Error?W.message:String(W)}`),null});if(J)return await this.refreshDaemonGitCredential(J,X),await this.relayOrgFsConfig(J.daemonUrl,J.token,X.orgFsConfigJson),this.finish(J,Q,!0,!0,"adopt");await Cy(this.kubeConfig,this.namespace,Z).catch(()=>{}),await z70(this.kubeConfig,this.namespace,Z).catch((W)=>{console.warn(`[${H6}] wait for deleted claim ${Z} failed: ${W instanceof Error?W.message:String(W)}`)})}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 P70(this.kubeConfig,this.namespace,$.handle,this.computeShutdownTime()).catch((W)=>console.warn(`[${H6}] TTL refresh failed for ${$.handle}: ${W instanceof Error?W.message:String(W)}`));if(this.metrics){let W=jn0($.tenant);if(this.metrics.ensureOutcome.add(1,{...W,outcome:Y}),!J)this.metrics.active.add(1,W),this.activeGauge.markCounted($.handle)}return this.toSandbox($)}buildEnvMap($,Z){let X={},Q=[];for(let[Y,G]of Object.entries($.env??{}))if(kK4.has(Y))Q.push(Y);else X[Y]=G;if(Q.length>0)console.warn(`[${H6}] 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(tH)}}async resolveTemplateName($){let{name:Z,probe:X}=await yG$({purpose:$,templateName:this.sandboxTemplateName,probe:this.mediumTemplateProbe,now:Date.now(),ttlMs:qK4,exists:(Q)=>b5$(this.kubeConfig,this.namespace,Q),onAbsent:(Q)=>console.warn(`[${H6}] SandboxTemplate ${Q} not found (or not readable) \u2014 harness-run claims fall back to ${this.sandboxTemplateName}. Upgrade the sandbox-env chart to the version that renders it.`)});return this.mediumTemplateProbe=X,Z}buildClaim($,Z,X,Q){let Y=this.sentinelToken!==null,G=bG$(this.tenantPools,{orgId:Z.tenant?.orgId,cloneUrl:Z.repo?.cloneUrl,purpose:Z.purpose}),J=Y?[]:Object.entries(this.buildEnvMap(Z,X)).sort(([F],[H])=>F<H?-1:F>H?1:0).map(([F,H])=>({name:F,value:H})),W=pK4(Z),K=Object.keys(W).length>0;return{apiVersion:`${K9.CLAIM_API_GROUP}/${K9.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?{[QQ.env]:this.envName}:{},...En0(Z.tenant)},...K?{annotations:W}:{}},spec:{sandboxTemplateRef:{name:Q},additionalPodMetadata:{labels:En0(Z.tenant,{[QQ.role]:"claimed",[QQ.sandboxHandle]:$,...this.envName?{[QQ.env]:this.envName}:{}}),...K?{annotations:W}:{}},env:J,warmpool:xG$(G,Y,Q),lifecycle:{shutdownPolicy:"Delete",shutdownTime:this.computeShutdownTime()}}}}async provision($,Z,X){let Q=this.tokenGenerator(),Y=AK4(),G=wn0,J=this.buildClaim(Z,X,{token:Q,daemonBootId:Y,workdir:G},await this.resolveTemplateName(X.purpose));try{await Oi0(this.kubeConfig,this.namespace,J)}catch(U){if(U instanceof Jn)await z70(this.kubeConfig,this.namespace,Z),await Oi0(this.kubeConfig,this.namespace,J);else throw U}let W;try{W=await x5$(this.kubeConfig,this.namespace,Z),await t5$(this.kubeConfig,this.namespace,W)}catch(U){throw await Cy(this.kubeConfig,this.namespace,Z).catch(()=>{}),U}try{await this.ensureServicePortForAdoptedSandbox(W),await this.ensureHttpRouteForHandle(Z,W,X.tenant??null)}catch(U){throw await Cy(this.kubeConfig,this.namespace,Z).catch(()=>{}),U}let K=await this.openForwarder(W,tH,Z),F=`http://127.0.0.1:${K.localPort}`,H=this.workloadConfigPayload(X),N=Y;try{if(await Un0(F),this.sentinelToken!==null){let U=await lO0(F);if(U)N=U.bootId;await DC(F,this.sentinelToken,H??{},{rotateToken:Q})}else if(H)await DC(F,Q,H);await this.relayOrgFsConfig(F,Q,X.orgFsConfigJson)}catch(U){throw this.closeForwarder(K),await this.deleteHttpRouteIfManaged(Z).catch(()=>{}),await Cy(this.kubeConfig,this.namespace,Z).catch(()=>{}),U}return{id:$,handle:Z,adoptedSandboxName:W,token:Q,workdir:G,daemonUrl:F,daemonForward:K,workload:X.workload??null,daemonBootId:N,tenant:X.tenant??null,ensureOpts:aK4(X)}}workloadConfigPayload($){return Q70({runtime:$?.workload?.runtime??"node",packageManager:$?.workload?.packageManager?{name:$.workload.packageManager,...$.workload.packageManagerPath?{path:$.workload.packageManagerPath}:{}}:null,repo:$?.repo??null,extraRepos:$?.extraRepos??[],port:$?.workload?.devPort??cG$,tenant:$?.tenant??void 0,...$?{cloneOnly:$.cloneOnly===!0}:{}})}async relayOrgFsConfig($,Z,X){if(!X)return;await qG$($,Z,X).catch((Q)=>console.warn("[org-fs] sidecar config relay failed",Q))}async refreshDaemonGitCredential($,Z){let X=om0(Z);if(!X)return;try{await DC($.daemonUrl,$.token,X)}catch(Q){console.warn(`[${H6}] 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(`[${H6}] clone credential re-mint failed: ${X instanceof Error?X.message:String(X)}`),$}}async withFreshCredentials($){return{...$,...$.repo?{repo:await this.withFreshCloneUrl($.repo)}:{},...$.orgFsConfigJson?{orgFsConfigJson:await rK4($,this.mintOrgFsConfig)}:{}}}startCredentialRefresher(){if(!this.mintCloneUrl)return;let{signal:$}=this.claimWatchAbort;(async()=>{while(!$.aborted){if(await w$(_K4,{signal:$}).catch(()=>{}),$.aborted)break;try{await this.refreshAllGitCredentials()}catch(Z){console.warn(`[${H6}] 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(`[${H6}] tenant pool reconcile failed: ${Z instanceof Error?Z.message:String(Z)}`)}await w$(SK4,{signal:$}).catch(()=>{})}})()}markTenantPoolsDirty($,Z){let X=gG$(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 y5$(this.kubeConfig,this.namespace,$.name);if(Z===null){console.warn(`[${H6}] 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[QQ.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 W of X){let K=this.poolPods.get(W.uid);if(!K)continue;if(K.failures>=dO0)G++;else if(K.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>=dO0){if(Date.now()-Q.lastFailureAt<dG$)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:hG$($),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 W=await this.openForwarder(Z.name,tH,Z.name).catch(()=>null);if(!W){this.recordPoolFailure(Z,$,"port-forward failed");return}let K=`http://127.0.0.1:${W.localPort}`;try{await Un0(K);let F=this.sentinelToken;if(!F)return;if(!await this.isPoolPodUnbound(Z))return;let H=Q70({runtime:$.workload.runtime,packageManager:$.workload.packageManager?{name:$.workload.packageManager,...$.workload.packageManagerPath?{path:$.workload.packageManagerPath}:{}}:null,repo:J,port:$.workload.devPort??cG$})??{},{transition:N}=await DC(K,F,H);if(Y&&N!=="bootstrap"&&await this.isPoolPodUnbound(Z))await IG$(K,F,"clone");this.poolPods.set(Z.uid,{lastConfigAt:Date.now(),lastFailureAt:0,failures:0}),console.log(`[${H6}] tenant pool ${$.name}: warmed ${Z.name} (${N})`)}catch(F){this.recordPoolFailure(Z,$,F instanceof Error?F.message:String(F))}finally{this.closeForwarder(W)}}isPoolPodUnbound($){return g5$(this.kubeConfig,this.namespace,$.name,QQ.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>=dO0?` \u2014 backing off ${dG$/60000}min`:"";console.warn(`[${H6}] tenant pool ${Z.name}: warming ${$.name} failed (${Y}/${dO0})${G}: ${X}`)}async refreshAllGitCredentials(){await uG$(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,vK4);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 DC($,this.sentinelToken,Q,{rotateToken:Z}),await this.relayOrgFsConfig($,Z,X?.orgFsConfigJson),!0}catch(Y){if(Y instanceof uO0&&Y.status===401)try{return await DC($,Z,Q,{rotateToken:Z}),await this.relayOrgFsConfig($,Z,X?.orgFsConfigJson),!0}catch(G){return console.warn(`[${H6}] re-bootstrap retry with claim token failed: ${G instanceof Error?G.message:String(G)}`),!1}return console.warn(`[${H6}] re-bootstrap failed: ${Y instanceof Error?Y.message:String(Y)}`),!1}}async ensureServicePortForAdoptedSandbox($){if(!this.previewGateway||!this.previewUrlPattern)return;await n5$(this.kubeConfig,this.namespace,$,{name:"daemon",port:tH,targetPort:tH})}async ensureHttpRouteForHandle($,Z,X){if(!this.previewGateway||!this.previewUrlPattern)return;let Q=sK4(this.previewUrlPattern,$);if(!Q)throw new OZ(`Unable to derive preview hostname for ${$} from pattern: ${this.previewUrlPattern}`);let Y={apiVersion:`${wi0.API_GROUP}/${wi0.API_VERSION}`,kind:"HTTPRoute",metadata:{name:$,namespace:this.namespace,labels:En0(X??void 0,{[QQ.role]:"claimed",[QQ.sandboxHandle]:$,"app.kubernetes.io/name":"studio-sandbox","app.kubernetes.io/managed-by":"studio",...this.envName?{[QQ.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:tH}]}]}};await m5$(this.kubeConfig,this.namespace,Y)}async deleteHttpRouteIfManaged($){if(!this.previewGateway)return;await i5$(this.kubeConfig,this.namespace,$)}async rehydrate($,Z,X){let Q=X.state;if(!Q.adoptedSandboxName&&!Q.podName||!Q.token)return null;let Y=await lH(this.kubeConfig,this.namespace,Z).catch(()=>{return});if(!Y||!iG$(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 W=Q.ensureOpts?await this.withFreshCredentials(Q.ensureOpts):null;if(!await this.rebootstrapDaemon(J.daemonUrl,Q.token,W))return this.closeForwarder(J.daemonForward),null}else console.warn(`[${H6}] daemon restart detected (handle=${Z}): stored bootId=${Q.daemonBootId} live bootId=${J.bootId}`);await this.stateStore?.put($,{handle:Z,state:{...Q,daemonBootId:J.bootId}}).catch((W)=>console.warn(`[${H6}] bootId persist failed for ${Z}: ${W instanceof Error?W.message:String(W)}`))}return{id:$,handle:Z,adoptedSandboxName:G,token:Q.token,workdir:Q.workdir??wn0,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(!iG$(X))return null;let Q=X.status?.sandbox?.name??Z;if(this.sentinelToken!==null)return null;let Y=gK4(X);if(!Y)return null;let G=await this.openAndProbeDaemon(Q,Z);if(!G)return null;let J=nK4(X);if(this.previewGateway)await this.ensureServicePortForAdoptedSandbox(Q).catch((W)=>{console.warn(`[${H6}] Service port backfill failed for ${Z}: ${W instanceof Error?W.message:String(W)}`)}),await this.ensureHttpRouteForHandle(Z,Q,J).catch((W)=>{console.warn(`[${H6}] HTTPRoute backfill failed for ${Z}: ${W instanceof Error?W.message:String(W)}`)});return{id:$,handle:Z,adoptedSandboxName:Q,token:Y,workdir:wn0,daemonUrl:G.daemonUrl,daemonForward:G.daemonForward,workload:null,daemonBootId:G.bootId,tenant:J,ensureOpts:null}}async openAndProbeDaemon($,Z){let X=await this.openForwarder($,tH,Z).catch(()=>null);if(!X)return null;let Q=`http://127.0.0.1:${X.localPort}`,Y=await lO0(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($);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($);if(!Z)return null;let X=Z.state.ensureOpts;if(!X)return null;let Q=await this.withFreshCredentials(X);if(yE(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.dropRecord(Z)}dropRecord($){if(this.closeForwarder($.daemonForward),this.metrics&&this.activeGauge.consume($.handle))this.metrics.active.add(-1,jn0($.tenant))}recordProxyDuration($,Z,X,Q,Y){if(!this.metrics)return;this.metrics.proxyDurationMs.record(Q,{...jn0(X?.tenant??null),source:$,sandbox_handle:X?.handle??Y??"",status_code:Z||0})}composePreviewUrl($){if(this.previewUrlPattern)return X70(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,{handle:Z.handle,state:X})}computeShutdownTime(){return new Date(Date.now()+this.idleTtlMs).toISOString()}async releaseAfter($,Z){let X=await lH(this.kubeConfig,this.namespace,$);if(!X)return;let Q=tK4(X.spec?.lifecycle?.shutdownTime,new Date(Date.now()+Z));if(!Q)return;await P70(this.kubeConfig,this.namespace,$,Q).catch((Y)=>console.warn(`[${H6}] release failed for ${$}: ${Y instanceof Error?Y.message:String(Y)}`))}async renewTtl($){let Z=await lH(this.kubeConfig,this.namespace,$);if(!Z)return;let X=oK4(Z.spec?.lifecycle?.shutdownTime,new Date(Date.now()+this.idleTtlMs));if(!X)return;await P70(this.kubeConfig,this.namespace,$,X).catch((Q)=>console.warn(`[${H6}] TTL renew failed for ${$}: ${Q instanceof Error?Q.message:String(Q)}`))}openForwarder($,Z,X=$){let Q=hK4(X,Z);return new Promise((Y,G)=>{let J=(W,K)=>{let F=nG$.createServer((H)=>this.handleForwardedConnection(H,$,Z,X));F.once("error",(H)=>{if(H.code==="EADDRINUSE"&&K<bK4){try{F.close()}catch{}let N=zn0+(W-zn0+1)%tG$;J(N,K+1);return}G(H)}),F.listen(W,"127.0.0.1",()=>{let H=F.address();if(!H||typeof H==="string"){F.close(),G(Error("port-forward listener failed to bind"));return}Y({server:F,localPort:H.port})})};J(Q,0)})}handleForwardedConnection($,Z,X,Q){let Y=new TK4,G=null,J=!1,W=()=>{if(J)return;if(J=!0,Y.destroy(),G)try{G.close()}catch{}if(!$.destroyed)$.destroy()};$.pipe(Y),$.on("error",W),$.on("close",W),this.portForward.portForward(this.namespace,Z,[X],$,null,Y).then((K)=>{let F=typeof K==="function"?K():K;if(!F){W();return}if(G=F,G.on("close",W),G.on("error",(H)=>{console.warn(`[${H6}] port-forward to ${Z}:${X} dropped mid-connection: ${lG$(H)}`,JSON.stringify(Pn0(H))),this.invalidateRecord(Q),W()}),J)try{G.close()}catch{}}).catch((K)=>{console.warn(`[${H6}] port-forward to ${Z}:${X} failed: ${lG$(K)}`,JSON.stringify(Pn0(K))),this.invalidateRecord(Q),W()})}closeForwarder($){$.server.close((Z)=>{if(Z)console.warn(`[${H6}] 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.dropRecord($);this.records.clear()}}function xK4($){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 Pn0($){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?Pn0(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 yK4(){let $=new AO0;return $.loadFromDefault(),$}function iG$($){return Boolean($.status?.conditions?.some((Z)=>Z.type==="Ready"&&Z.status==="True"))}function gK4($){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 hK4($,Z){let X=zK4("sha256").update(`${$}:${Z}`).digest();return zn0+X.readUInt32BE(0)%tG$}function Ln0($,Z){return new Response(JSON.stringify(Z),{status:$,headers:{"content-type":"application/json","access-control-allow-origin":"*"}})}function pG$($){let Z=$.slice(0,lK4);return uK4.test(Z)?Z:""}function dK4($){if($===void 0)return null;let Z=$.trim();if(Z==="")return null;if(!cK4.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 En0($,Z={}){let X={...Z};if($){let Q=pG$($.orgId),Y=pG$($.userId);if(Q)X[QQ.orgId]=Q;if(Y)X[QQ.userId]=Y}return X}function wC($){let Z="";for(let X of $){let Q=X.codePointAt(0)??0;Z+=Q<32||Q===127?" ":X}return Z.slice(0,mK4)}function iK4($){try{let Z=new URL($);return Z.username="",Z.password="",Z.toString()}catch{return""}}function pK4($){let Z={},X=$.tenant;if(X?.orgSlug)Z[d3.orgSlug]=wC(X.orgSlug);if(X?.orgName)Z[d3.orgName]=wC(X.orgName);if(X?.userEmail)Z[d3.userEmail]=wC(X.userEmail);if(X?.userName)Z[d3.userName]=wC(X.userName);let Q=$.repo;if(Q){if(Q.displayName)Z[d3.gitRepo]=wC(Q.displayName);let Y=iK4(Q.cloneUrl);if(Y)Z[d3.gitRepoUrl]=wC(Y);let G=$.branch??Q.branch;if(G)Z[d3.gitBranch]=wC(G)}return Z}function nK4($){let Z=$.metadata?.labels;if(!Z)return null;let X=Z[QQ.orgId],Q=Z[QQ.userId];if(!X||!Q)return null;let Y=$.metadata?.annotations??{};return{orgId:X,userId:Q,orgSlug:Y[d3.orgSlug],orgName:Y[d3.orgName],userEmail:Y[d3.userEmail],userName:Y[d3.userName]}}function tK4($,Z){if($){let X=new Date($).getTime();if(Number.isFinite(X)&&X<=Z.getTime())return null}return Z.toISOString()}function oK4($,Z){if($){let X=new Date($).getTime();if(Number.isFinite(X)&&X>=Z.getTime())return null}return Z.toISOString()}function jn0($){return{org_id:$?.orgId??"",user_id:$?.userId??"",runner_kind:"agent-sandbox"}}async function rK4($,Z){if(!Z||!$.tenant)return $.orgFsConfigJson;try{return await Z($.tenant)??$.orgFsConfigJson}catch(X){return console.warn(`[${H6}] org-fs credential re-mint failed: ${X instanceof Error?X.message:String(X)}`),$.orgFsConfigJson}}function aK4($){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($.purpose)Z.purpose=$.purpose;if($.orgFsConfigJson)Z.orgFsConfigJson=$.orgFsConfigJson;return Object.keys(Z).length>0?Z:null}function sK4($,Z){try{return new URL(X70($,Z)).hostname||null}catch{return null}}var H6="AgentSandboxProvider",LC="x-sandbox-preview-not-ready",RK4="agent-sandbox-system",IK4="studio-sandbox",qK4=300000,tH=9000,cG$=3000,wn0="/app",MK4=32,kK4,VK4=900000,SK4=60000,CK4=1800000,dO0=3,dG$=1800000,_K4=900000,vK4=1800000,fK4,mG$,zn0=40000,tG$=1e4,bK4=256,QQ,d3,uK4,lK4=63,cK4,mK4=253;var oG$=D(()=>{X4();a5$();AG$();kG$();rm0();A70();E70();vG$();Dn0();kK4=new Set(["DAEMON_TOKEN","DAEMON_BOOT_ID","APP_ROOT","PROXY_PORT"]),fK4=["cookie","host","connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","accept-encoding","content-length","upgrade"],mG$=["connection","keep-alive","transfer-encoding","content-encoding","content-length"];QQ={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"},d3={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"},uK4=/^([A-Za-z0-9]([-A-Za-z0-9_.]*[A-Za-z0-9])?)?$/;cK4=/^[a-z]([a-z0-9-]{0,30}[a-z0-9])?$/});var rG$={};L4(rG$,{parseTenantPools:()=>fG$,PREVIEW_NOT_READY_HEADER:()=>LC,AgentSandboxProvider:()=>An0});var Tn0=D(()=>{oG$();Dn0()});var eG$={};L4(eG$,{subscribeLifecycle:()=>Vn0,getOrInitSharedRunner:()=>kn0,getAgentSandboxProviderForTeardown:()=>Mn0,getAgentSandboxProvider:()=>YQ,__resetSharedLifecyclesForTesting:()=>KF4});function In0($){let Z=kn[aG$];if(Z)return Promise.resolve(Z);let X=kn[Rn0];if(X)return X;let Q=$().then((Y)=>{return kn[aG$]=Y,Y}).finally(()=>{delete kn[Rn0]});return kn[Rn0]=Q,Q}function eK4(){let $=process.env.STUDIO_SANDBOX_PREVIEW_URL_PATTERN;return $&&$.trim()!==""?$:void 0}function $F4(){let $=process.env.STUDIO_SANDBOX_TEMPLATE_NAME;return $&&$.trim()!==""?$:void 0}function ZF4(){let $=process.env.STUDIO_ENV;return $&&$.trim()!==""?$:void 0}function XF4(){let $=process.env.STUDIO_SANDBOX_SENTINEL_TOKEN;return $&&$.trim()!==""?$:void 0}function QF4(){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 qn0($){let Z=new Qn($),X=eK4(),{AgentSandboxProvider:Q,parseTenantPools:Y}=await Promise.resolve().then(() => (Tn0(),rG$)),G=new JH(_0().encryptionKey);return new Q({stateStore:Z,previewUrlPattern:X,sandboxTemplateName:$F4(),envName:ZF4(),previewGateway:QF4(),sentinelToken:XF4(),tenantPools:Y(process.env.STUDIO_SANDBOX_TENANT_POOLS),meter:J$,mintCloneUrl:async(J,W)=>{if(!J.connectionId)return null;let K=C5$(J.cloneUrl);if(!K)return null;let{cloneUrl:F}=await MK(J.connectionId,K.owner,K.name,$,G,{bufferMs:W?.bufferMs});return F},mintOrgFsConfig:async(J)=>{if(!J.orgSlug)return null;return await L70({boundAuth:{apiKey:{create:(K)=>a$.api.createApiKey({body:{...K,userId:J.userId}})}},storage:{orgRepoSyncs:new cE($)}},{orgSlug:J.orgSlug,orgId:J.orgId,baseUrl:y9()})??null}})}function YQ($){if(!_0().agentSandboxEnabled)throw Error("Agent sandbox is disabled. Set STUDIO_AGENT_SANDBOX_ENABLED=true to enable it.");return In0(()=>qn0($.db))}function Mn0($){return In0(()=>qn0($.db))}async function kn0(){if(!_0().agentSandboxEnabled)return null;return In0(()=>qn0(U8().db))}function Vn0($,Z,X){let Q=hO.get(Z);if(Q){if(Q.terminated){if(Q.lastPhase)try{X(Q.lastPhase)}catch{}return{unsubscribe:JF4}}if(Q.listeners.add(X),Q.lastPhase)try{X(Q.lastPhase)}catch{}return sG$(Z,Q,X)}let Y=new AbortController,G={lastPhase:null,terminated:!1,listeners:new Set([X]),abort:Y};return hO.set(Z,G),WF4($,Z,G),sG$(Z,G,X)}function JF4(){}function sG$($,Z,X){return{unsubscribe(){if(hO.get($)!==Z)return;if(Z.listeners.delete(X),Z.listeners.size===0)hO.delete($),Z.abort.abort()}}}async function WF4($,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 W of J)try{W(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(hO.get(Z)===X)hO.delete(Z)}}function KF4(){for(let $ of hO.values())$.abort.abort();hO.clear()}var aG$,Rn0,kn,YF4,GF4,hO;var m3=D(()=>{mG();W6();Fi0();Vy();$d();L$();lE();cY();X9();aG$=Symbol.for("decocms.sandbox.lifecycle.agent-sandbox-runner"),Rn0=Symbol.for("decocms.sandbox.lifecycle.agent-sandbox-inflight"),kn=globalThis;YF4=Symbol.for("decocms.sandbox.lifecycle.shared-lifecycles"),GF4=globalThis,hO=GF4[YF4]??=new Map});async function Vn($,Z,X){try{await $.storage.threads.stampRuntimeIfAbsent(Z,X)}catch(Q){console.warn(`[stampRuntimeIfAbsent] ${Z}: ${Q instanceof Error?Q.message:String(Q)}`)}}function $J$($){let Z=$?.trim();if(!Z)return null;try{let X=new URL(Z);if(X.protocol!=="http:"&&X.protocol!=="https:")return null;return X.href}catch{return null}}function mO0($){return $J$($?.previewServerUrl)??$J$($?.productionUrl)}var Sn0=()=>{};function EC($){return $==="cms"||$==="sandbox"?$:null}function FF4($){return!!mO0($)&&$?.fastPreview===!0}function iO0($){return FF4($)?"cms":"sandbox"}var Cn0;var py=D(()=>{Sn0();Cn0=["cms","sandbox"]});function ZJ$($){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(HF4.has(Z))return null;if(typeof Q==="string"&&Q.length>0&&Z===Q)return null;return Z}function pO0($){if(!$.branch.startsWith("thread:"))return $.branch;if($.sticky&&$.recordedHeadRef)return $.recordedHeadRef;return $.derivedRef}var HF4;var nO0=D(()=>{HF4=new Set(["main","master","trunk","develop","HEAD"])});import{z as oH}from"zod";async function ny($,Z){t(Z);let X=n(Z),Q=o0(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 gE(Z,$.branch,Q),W=qK(M9(G),J,$.branch),K=await YQ(Z);if(W){if(await K.alive(W.sandboxHandle).catch(()=>!0))return W;await TO(Z.storage.virtualMcps,$.virtualMcpId,Q,J,$.branch).catch((O)=>{console.warn("[ensureSandbox] failed to reap stale entry",O)})}let F=ZJ($.branch)??Z.metadata?.threadId;if(F)Vn(Z,F,"sandbox");let N=await IO(Z,F)??G.githubRepo??null;await $.onColdStart?.().catch(()=>{});let{entry:U}=await QJ$({ctx:Z,userId:Q,sandboxUserId:J,orgId:X.id,virtualMcpId:$.virtualMcpId,branch:$.branch,metadata:G,githubRepo:N,threadRepos:await Zi0(Z,F),existing:null,runner:K,...$.purpose?{purpose:$.purpose}:{}});return U}async function NF4($){let Z=$.primary?`${$.primary.owner}/${$.primary.name}`.toLowerCase():null,X=$.repos.filter((G)=>`${G.owner}/${G.name}`.toLowerCase()!==Z),Q=rp(X),Y=[];for(let[G,J]of X.entries()){if(!J.connectionId)continue;try{let{cloneUrl:W}=await MK(J.connectionId,J.owner,J.name,$.ctx.db,$.ctx.vault);Y.push({cloneUrl:W,connectionId:J.connectionId,userName:$.gitUserName,userEmail:$.gitUserEmail,displayName:`${J.owner}/${J.name}`,directoryName:Q[G],submoduleCredentials:[]})}catch(W){console.warn(`[provisionSandbox] skipping secondary ${J.owner}/${J.name}:`,W instanceof Error?W.message:W)}}return Y}async function QJ$($){let{ctx:Z,userId:X,sandboxUserId:Q,orgId:Y,virtualMcpId:G,branch:J,metadata:W,threadRepos:K,existing:F,runner:H,purpose:N}=$,U=N==="harness-run",B=$.githubRepo?await UF4({ctx:Z,orgId:Y,virtualMcpId:G,userId:X,githubRepo:$.githubRepo}):null,{runtime:O,packageManager:w,port:L,packageManagerPath:E}=F5$(W),j;if(B){if(B.connectionId)await kO({ctx:Z,connectionId:B.connectionId,organizationId:Y,forceRefresh:!0,onLegacyMintError:(I0)=>{console.error("[provisionSandbox] repo-scoped legacy token mint failed",{connectionId:B.connectionId,error:I0.message})}});let{cloneUrl:a,gitUserName:r,gitUserEmail:z0}=B.connectionId?await MK(B.connectionId,B.owner,B.name,Z.db,Z.vault):E5$(B.owner,B.name);if(!w){let I0=B.connectionId?await P5$(B.connectionId,B.owner,B.name,Z.db,Z.vault):await A5$(B.owner,B.name);if(I0)w=I0.packageManager,O=ap[I0.packageManager].runtime,L=I0.devPort??L,await BF4(Z,G,X,I0.packageManager,I0.devPort)}let Z0=_0().sandboxStickyHeadRefEnabled,A0=pO0({branch:J,derivedRef:uH(J),recordedHeadRef:Z0?await Q5$(Z,ZJ(J)):null,sticky:Z0}),g0=await U5$({ctx:Z,orgId:Y,userId:X,entries:W5$(W)});j={cloneUrl:a,...B.connectionId?{connectionId:B.connectionId}:{},userName:r,userEmail:z0,branch:A0,displayName:`${B.owner}/${B.name}`,submoduleCredentials:g0}}let z=await NF4({ctx:Z,orgId:Y,repos:K??[],primary:B,gitUserName:j?.userName??"",gitUserEmail:j?.userEmail??""}),P=O&&w&&!U?{runtime:O,packageManager:w,...L!==null?{devPort:Number(L)}:{},...E?{packageManagerPath:E}:{}}:void 0,A=np({orgId:Y,virtualMcpId:G,branch:J}),I=!_0().orgFsMountsDisabled,k;if(I){let a=Z.organization?.slug??(await Z.db.selectFrom("organization").select(["slug"]).where("id","=",Y).executeTakeFirst())?.slug;if(a)k=await L70(Z,{orgSlug:a,orgId:Y,baseUrl:y9()})}await DF4(H);let M=await H.ensure({userId:Q,projectRef:A},{branch:J,repo:j,extraRepos:z,workload:P,cloneOnly:U,...N?{purpose:N}:{},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}:{}},...k?{orgFsConfigJson:k}:{}}),S=My(W);await W70({ctx:Z,runner:H,handle:M.handle,orgId:Y,userId:X,entries:S});let f=!!F&&F.sandboxHandle===M.handle&&F?.createdAt?F.createdAt:Date.now(),b=W.runtime?.selected??null,i=W.runtime?.port??null,l=W.runtime?.path??null,o={sandboxHandle:M.handle,previewUrl:M.previewUrl,createdAt:f,startedWith:{packageManager:b,port:i,path:l}};await p6$(Z.storage.virtualMcps,G,X,Q,J,o);let U0=ZJ(J)??Z.metadata?.threadId;if(U0)await G5$(Z,U0,Q,J,o);let j0=!F||F.sandboxHandle!==M.handle;return{entry:o,isNewVm:j0}}async function UF4($){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:W}=await Z.storage.connections.list(X),K=BZ0(W,G.owner,G.name);if(!K)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:K.id});try{let H=(await Z.storage.virtualMcps.findById(Q))?.metadata??{},N=H.githubRepo;if(N?.connectionId===G.connectionId){let U=V5(K);await Z.storage.virtualMcps.update(Q,Y,{metadata:{...H,githubRepo:{...N,connectionId:K.id,...U?{installationId:U.installationId}:{}}}})}}catch(F){console.warn("[provisionSandbox] failed to persist healed repo connection",{virtualMcpId:Q,error:F.message})}return{...G,connectionId:K.id}}async function BF4($,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 DF4($){let Z=Date.now()+XJ$,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(XJ$/1000)}s`);if(!X)X=!0,console.warn("[ensureSandbox] waiting for cluster capacity \u2014 a sandbox pod cannot be scheduled right now");await w$(OF4)}}var _n0,XJ$=150000,OF4=5000;var Sn=D(()=>{op();X4();M0();sp();Gi0();B5$();pQ();fQ();Vy();R5$();sm0();m3();py();h3();nO0();L$();X9();lE();pQ();_n0=u({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:oH.object({virtualMcpId:oH.string().describe("Virtual MCP ID"),branch:oH.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."),threadId:oH.string().optional().describe("The session asking for a sandbox. A thread stamped `cms` is refused \u2014 that session reads and writes over the decofile API and a pod would be invisible to it. Optional: an unstamped (legacy) thread is always allowed, and so is a caller with no thread.")}),outputSchema:oH.object({previewUrl:oH.string().nullable(),sandboxHandle:oH.string(),branch:oH.string(),isNewVm:oH.boolean()}),handler:async($,Z)=>{t(Z);let X=n(Z);await Z.access.check();let Q=$.branch??N70(H70(Z.auth.user)),Y=ZJ(Q)??$.threadId??Z.metadata?.threadId;if(Y){let w=await Z.storage.threads.get(Y).catch(()=>null);if(EC(w?.metadata?.runtime)==="cms")throw Error("This chat is a CMS session and does not use a sandbox. Start a coding session to get one.")}let G=o0(Z);if(!G)throw Error("User ID required");let J=await gE(Z,Q,G),W=await Z.storage.virtualMcps.findById($.virtualMcpId);if(!W||W.organization_id!==X.id)throw Error("Virtual MCP not found");let K=W.metadata??{},F=await YQ(Z),H=qK(M9(K),J,Q),U=await IO(Z,ZJ(Q)??Z.metadata?.threadId)??K.githubRepo??null,{entry:B,isNewVm:O}=await QJ$({ctx:Z,userId:G,sandboxUserId:J,orgId:X.id,virtualMcpId:$.virtualMcpId,branch:Q,metadata:K,githubRepo:U,threadRepos:await Zi0(Z,ZJ(Q)??Z.metadata?.threadId),existing:H,runner:F});if(Y)Vn(Z,Y,"sandbox");return{...B,branch:Q,isNewVm:O}}})});function wF4($){let{publicUrl:Z,agentId:X,organization:Q,target:Y,threadId:G}=$;if(Y==="agent-tools")return`${Z}/mcp/virtual-mcp/${encodeURIComponent(X)}`;if(!Q.slug)throw new GJ$(Q.id,Y);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 tO0($,Z,X,Q,Y="agent-tools",G,J={"*":["*"]}){let W=wF4({publicUrl:y9(),agentId:Z,organization:X,target:Y,...G?{threadId:G}:{}}),K=await $.boundAuth.apiKey.create({name:Q,permissions:J,expiresIn:YJ$,metadata:{organization:{id:X.id,slug:X.slug,name:X.name}}});return{url:W,headers:{Authorization:`Bearer ${K.key}`,"x-org-id":X.id},expiresAt:Date.now()+YJ$*1000}}function JJ$($){let{publicUrl:Z,organizationSlug:X,headers:Q,connections:Y}=$,G=new Set;return Y.map((J)=>{let W=LF4(J.slug??J.title??"")||"mcp",K=W;for(let F=2;G.has(K);F++)K=`${W}-${F}`;return G.add(K),{name:K,url:`${Z}/api/${X}/mcp/${encodeURIComponent(J.id)}`,headers:Q}})}function LF4($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function WJ$($){return{self:[...$.toolNames],...$.grants}}var YJ$=3600,GJ$;var vn0=D(()=>{X9();GJ$=class GJ$ extends Error{constructor($,Z){super(`cannot mint a "${Z}" MCP endpoint for organization "${$}": the org-scoped path needs the org slug, which was not loaded.`);this.name="MissingOrganizationSlugError"}}});async function EF4($,Z,X,Q){try{let Y=$.organization;if(!Y)return;let G=await tO0($,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("[agent-sandbox-fs] tools/sync failed",J.status,await J.text().catch(()=>""))}catch(Y){console.warn("[agent-sandbox-fs] tools/sync failed",Y)}}async function ty($,Z){let X=await YQ($),Q=null,Y=()=>{if(!Q){if(Q=ny({virtualMcpId:Z.virtualMcpId,branch:Z.branch},$).then((W)=>W.sandboxHandle),Q.catch(()=>{Q=null}),Z.syncTools)Q.then((W)=>EF4($,X,W,{virtualMcpId:Z.virtualMcpId})).catch(()=>{})}return Q},G=Z.branch==="ephemeral";return am0(X,{ensureHandle:Y,invalidateHandle:async(W)=>{if(Q=null,!G&&!W?.force)return;try{await TO($.storage.virtualMcps,Z.virtualMcpId,Z.userId,Z.userId,Z.branch)}catch(K){console.warn("[agent-sandbox-fs] failed to reap vmMap entry",K)}},canAutoRestart:G,threadId:Z.threadId})}async function KJ$($,Z){try{let X=await ty($,Z),{stdout:Q}=await X.onBash("test -d .deco && echo __DECO_SITE__");return Q.includes("__DECO_SITE__")}catch(X){return console.warn("[agent-sandbox-fs] .deco probe failed; assuming deco site",X),!0}}var oO0=D(()=>{op();vn0();m3();Sn();pQ()});import{z as FJ$}from"zod";function oy($){let Z=[];for(let X of $){if(X.status!=="active")continue;let Q=V5(X);if(!Q)continue;Z.push({connectionId:X.id,owner:Q.owner,repo:Q.repo,installationId:Q.installationId})}return Z}async function zF4($,Z){let{items:X}=await $.storage.connections.list(Z,{slug:"mcp-github"});return oy(X)}function PF4($){let Z=$.split(`
981
981
  `).map((Q)=>Q.trim()).filter((Q)=>Q&&Q!==".git"&&Q!=="__CLONED__"),X=Z.length>0;return{cloned:X,listing:X?Z.join(`
982
982
  `):""}}function AF4($){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(`
983
983
  `);return`${Z}
@@ -2947,7 +2947,7 @@ Respond with ONLY a JSON object of this shape, and nothing else:
2947
2947
  ${G.join(`
2948
2948
  `)}`:Y}function fH6($){let Z=new Set;for(let X of $)for(let Q of X.split(`
2949
2949
  `)){let Y=Q.trim();if(/^Co-authored-by:\s/i.test(Y))Z.add(Y)}return[...Z]}var ol$=200,RH6=12,qH6,kH6=300,G71=3;var J71=D(()=>{cD();KT0();qH6={aheadBy:0,behindBy:0,files:[]}});function xH6($){if(!$||$.includes(".."))return!1;return bH6.test($)}function al$($){let Z=typeof $.__resolveType==="string"?$.__resolveType:null;if(!Z||!xH6(Z))return null;let{__resolveType:X,...Q}=$;return{resolveType:Z,payload:Q}}function sl$($,Z){return`${$.replace(/\/+$/,"")}/deco/invoke/${Z}`}var bH6;var el$=D(()=>{bH6=/^[\w./@-]+$/});function Fs($,Z){let X=$?.githubRepo;if(!X?.owner||!X?.name)return null;if(!X.connectionId)return X;if(!Z.includes(X.connectionId))return null;return X}async function $c$($,Z,X,Q){if(!Q.connectionId)throw new Bv("Push requires a connected GitHub account. Connect mcp-github for this project and restart the sandbox.");let Y=$.organization?.id;if(!Y)throw new Bv(W9);await kO({ctx:$,connectionId:Q.connectionId,organizationId:Y,forceRefresh:!0,onLegacyMintError:(H)=>{let N=H instanceof Error?H.message:W9;throw new Bv(N)}});let{cloneUrl:G,gitUserName:J,gitUserEmail:W}=await MK(Q.connectionId,Q.owner,Q.name,$.db,$.vault).catch((H)=>{let{code:N,message:U}=L5$(H instanceof Error?H.message:String(H));throw N?new Bv(U):H}),K=hu($),F=await Z.proxyDaemonRequest(X,"/_sandbox/config",{method:"PUT",headers:new Headers({"content-type":"application/json"}),body:JSON.stringify({git:{repository:{cloneUrl:G},identity:{userName:J,userEmail:W}},...K?{operator:K}:{}})});if(!F.ok){let H=await MO(F,yH6).catch(()=>F.statusText);throw Error(`Failed to refresh sandbox git credentials (${F.status}): ${H}`)}}var yH6=10485760,Bv;var W71=D(()=>{QJ();aA0();$n();Ki0();Vy();Bv=class Bv extends Error{constructor($){super($);this.name="GitPushAuthError"}}});function hH6($){let Z=$.startsWith("thread:")?$.slice(7):$;if(!Z||Z.length>255||Z.includes("..")||Z.startsWith("/")||Z.endsWith("/")||Z.endsWith(".lock")||!gH6.test(Z))throw Error(`Invalid branch name: ${$}`)}function Ov($){return AbortSignal.any([$.req.raw.signal,AbortSignal.timeout(lH6)])}async function dH6($,Z){let X=$.var.studioContext,Q=ZJ(Z.branch),Y=$.req.query("thread")??Q,G=Y&&Y===Q?Z.branchThread:Y?await X.storage.threads.get(Y).catch(()=>null):null,J=G?.virtual_mcp_id===Z.virtualMcpId?G:null,W=EC(J?.metadata?.runtime);if(W)return W;let K=iO0(Z.virtualMcpMetadata),F=K==="cms"?await lZ1(X,{claimName:Z.claimName}):"alive",H=K==="cms"&&F!=="alive"?"cms":"sandbox",N=!!J&&(F==="gone"||F==="alive"&&K==="cms");if(N&&J)Vn(X,J.id,H);if(K==="cms")console.log("sandbox proxy: no runtime stamp",{route:$.req.path,method:$.req.method,reason:J?"unstamped":"threadless",liveness:F,resolved:H,stamped:N});return H}async function mH6($){let Z=$.get("vmClaim");if(Z.runner)return Z.runner;try{return await YQ($.var.studioContext)}catch{return null}}function Dv($){let{runner:Z}=$.get("vmClaim");if(!Z)return $.json({error:"No sandbox runner configured"},503);return Z}async function mu($){let{virtualMcpMetadata:Z,connectionIds:X}=$.get("vmClaim"),Q=$.var.studioContext,Y=Fs(Z,X);if(!Y)throw new l4(404,"AUTH","repo","Project has no GitHub repository");let G=n(Q);return sA0(Q,G.id,Y)}function K71($,Z){if(Z instanceof $A0)return $.json({error:Z.message},429,{...T5,...Z.retryAfterMs===null?{}:{"Retry-After":String(Math.ceil(Z.retryAfterMs/1000))}});if(Z instanceof l4){let Q=Z.status===404?404:Z.status===409||Z.status===422?409:502;return $.json({error:Z.message},Q,T5)}let X=Z instanceof Error?Z.message:String(Z);return $.json({error:X},502,T5)}async function Qc$($,Z,X){let Q;try{Q=await fetch(Z,X)}catch{return $.json({error:"Preview unreachable"},502)}let Y;try{Y=await Q.text()}catch{return $.json({error:"Preview unreachable"},502)}return new Response(Y,{status:Q.status,headers:{"content-type":Q.headers.get("content-type")??"application/json"}})}async function Yc$($){try{let Z=await mu($),X=await FT0(Z,$.get("vmClaim").branch);return $.json(X,200,T5)}catch(Z){return K71($,Z)}}function Hs($,Z){let Q=(UT0.get($)??Promise.resolve()).catch(()=>{}).then(Z),Y=Q.catch(()=>{});return UT0.set($,Y),Y.finally(()=>{if(UT0.get($)===Y)UT0.delete($)}),Q}async function rZ($,Z,X){if(!X?.runner&&$.get("vmClaim").runtime==="cms")return $.json({error:"sandbox not found: this session is sandbox-less"},404,T5);let Q=X?.runner??Dv($);if(Q instanceof Response)return Q;let{claimName:Y,userId:G,projectRef:J}=$.get("vmClaim"),W=X?.method??"POST",K=null,F=new Headers;if(X?.jsonBody!==void 0)K=X.jsonBody,F.set("content-type","application/json");else if(X?.forwardJsonBody)K=await $.req.text(),F.set("content-type","application/json");let H=X?.signal,N={method:W,headers:F,body:K,...H?{signal:H}:{}},U=async()=>{let B=await Q.proxyDaemonRequest(Y,Z,N);if(X?.map404to410&&B.status===404){try{await B.body?.cancel()}catch{}if(await Q.adoptLiveClaim({userId:G,projectRef:J},Y))B=await Q.proxyDaemonRequest(Y,Z,N);if(B.status===404){try{await B.body?.cancel()}catch{}return new Response(JSON.stringify({error:"Sandbox handle is gone. The sandbox needs to be re-provisioned."}),{status:410,headers:{"content-type":"application/json",...T5}})}}let O=await B.text(),w=X?.redactRepoDir?iH6(O):O,L=B.headers.get("content-type")??"application/json";return new Response(w,{status:B.status,headers:{"content-type":L,...T5}})};try{if(H){let B=U();return B.catch(()=>{}),await Promise.race([B,new Promise((w,L)=>{if(H.aborted)return L(H.reason);H.addEventListener("abort",()=>L(H.reason),{once:!0})})])}return await U()}catch(B){let O=B instanceof Error?B.message:String(B);return $.json({error:`Daemon unreachable: ${O}`},502)}}function iH6($){try{let Z=JSON.parse($);if(Z&&typeof Z==="object"&&!Array.isArray(Z)&&"repoDir"in Z)return JSON.stringify({...Z,repoDir:null})}catch{}return $}async function BT0($,Z,X,Q="GET",Y){let G=await $.proxyDaemonRequest(Z,X,{method:Q,headers:new Headers,body:null});if(G.status===404&&Y){try{await G.body?.cancel()}catch{}if(await $.adoptLiveClaim(Y,Z))G=await $.proxyDaemonRequest(Z,X,{method:Q,headers:new Headers,body:null})}if(G.status===404){try{await G.body?.cancel()}catch{}throw Error("SANDBOX_GONE")}let J=await G.text();if(!G.ok){let W=`Daemon error (${G.status})`;try{W=JSON.parse(J).error??W}catch{}throw Error(W)}return JSON.parse(J)}function pH6($){return Gc$.includes($)}var gH6,Zc$=524288,uH6=65536,lH6=1e4,Xc$=2000,cH6,UT0,T5,Gc$,Jc$=()=>{let $=new K1;$.use("/:virtualMcpId/:branch/*",cH6),$.post("/:virtualMcpId/:branch/write",(X)=>rZ(X,"/_sandbox/write",{forwardJsonBody:!0,signal:Ov(X)})),$.post("/:virtualMcpId/:branch/unlink",(X)=>rZ(X,"/_sandbox/unlink",{forwardJsonBody:!0,signal:Ov(X)})),$.post("/:virtualMcpId/:branch/mkdir",(X)=>rZ(X,"/_sandbox/mkdir",{forwardJsonBody:!0,signal:Ov(X)})),$.post("/:virtualMcpId/:branch/rename",(X)=>rZ(X,"/_sandbox/rename",{forwardJsonBody:!0,signal:Ov(X)})),$.post("/:virtualMcpId/:branch/read",(X)=>rZ(X,"/_sandbox/read",{forwardJsonBody:!0,signal:Ov(X)})),$.post("/:virtualMcpId/:branch/glob",(X)=>rZ(X,"/_sandbox/glob",{forwardJsonBody:!0,signal:Ov(X)})),$.post("/:virtualMcpId/:branch/grep",(X)=>rZ(X,"/_sandbox/grep",{forwardJsonBody:!0,signal:Ov(X)})),$.post("/:virtualMcpId/:branch/exec/:script",async(X)=>{let Q=X.req.param("script");if(!Q)return X.json({error:"missing script name"},400);return rZ(X,`/_sandbox/exec/${encodeURIComponent(Q)}`)}),$.post("/:virtualMcpId/:branch/exec/:script/kill",async(X)=>{let Q=X.req.param("script");if(!Q)return X.json({error:"missing script name"},400);return rZ(X,`/_sandbox/exec/${encodeURIComponent(Q)}/kill`)}),$.get("/:virtualMcpId/:branch/config",(X)=>rZ(X,"/_sandbox/config",{method:"GET",map404to410:!0,redactRepoDir:!0})),$.put("/:virtualMcpId/:branch/config",(X)=>rZ(X,"/_sandbox/config",{method:"PUT",forwardJsonBody:!0,map404to410:!0})),$.post("/:virtualMcpId/:branch/setup/:step",async(X)=>{let Q=X.req.param("step");if(!Q||!pH6(Q))return X.json({error:`step must be one of: ${Gc$.join(", ")}`},400);let Y=X.get("vmClaim"),G=await lZ1(X.var.studioContext,{claimName:Y.claimName})==="gone"?null:await mH6(X);if(!G)return X.json({error:"sandbox not found: nothing is running at this ref"},404,T5);if(Q==="start"){let J=n(X.var.studioContext),W=My(Y.virtualMcpMetadata);try{await W70({ctx:X.var.studioContext,runner:G,handle:Y.claimName,orgId:J.id,userId:Y.callerUserId,entries:W})}catch(K){let F=K instanceof Error?K.message:String(K);return X.json({error:`Failed to push env to daemon: ${F}`},502)}}return rZ(X,`/_sandbox/setup/${Q}`,{signal:X.req.raw.signal,map404to410:!0,runner:G})}),$.get("/:virtualMcpId/:branch/events",(X)=>{let Q=X.get("vmClaim");if(!Q.runner)return iN(X,async(Y)=>{await Y.writeSSE({event:"phase",data:JSON.stringify({kind:"failed",reason:"unknown",message:"No sandbox runner configured on this studio instance."})})});return Jl$(X,{ctx:X.var.studioContext,claimName:Q.claimName,runner:Q.runner,virtualMcpId:Q.virtualMcpId,branch:Q.branch,userId:Q.userId,projectRef:Q.projectRef,virtualMcpMetadata:Q.virtualMcpMetadata})}),$.get("/:virtualMcpId/:branch/git/status",(X)=>{if(X.get("vmClaim").runtime==="cms")return Yc$(X);return Z(X)});let Z=(X)=>rZ(X,"/_sandbox/git/status",{method:"GET",map404to410:!0,signal:AbortSignal.any([X.req.raw.signal,AbortSignal.timeout(Xc$)])});return $.post("/:virtualMcpId/:branch/git/status",(X)=>{if(X.get("vmClaim").runtime==="cms")return Yc$(X);return rZ(X,"/_sandbox/git/status",{map404to410:!0,signal:AbortSignal.any([X.req.raw.signal,AbortSignal.timeout(Xc$)])})}),$.post("/:virtualMcpId/:branch/git/diff",async(X)=>{let Q=X.get("vmClaim");if(Q.runtime==="cms")try{let Y=await X.req.json().catch(()=>({})),G=await mu(X),J=await HT0(G,Q.branch,Y.base);return X.json(J,200,T5)}catch(Y){return K71(X,Y)}return rZ(X,"/_sandbox/git/diff",{forwardJsonBody:!0,map404to410:!0})}),$.post("/:virtualMcpId/:branch/git/publish",async(X)=>{if(X.get("vmClaim").runtime==="cms")return X.json({ok:!0},200,T5);let Q=Dv(X);if(Q instanceof Response)return Q;let{claimName:Y,virtualMcpMetadata:G,connectionIds:J}=X.get("vmClaim"),W=X.var.studioContext;return Hs(Y,async()=>{try{await cZ1(W,Q,Y);let K=Fs(G,J);if(K)await $c$(W,Q,Y,K)}catch(K){if(K instanceof Bv)return X.json({error:K.message},403,T5);let F=K instanceof Error?K.message:String(K);return X.json({error:F},502,T5)}return rZ(X,"/_sandbox/git/publish",{forwardJsonBody:!0,map404to410:!0})})}),$.post("/:virtualMcpId/:branch/git/discard",async(X)=>{let Q=X.get("vmClaim");if(Q.runtime==="cms")return Hs(Q.claimName,async()=>{let Y=await X.req.json().catch(()=>({})),G=Array.isArray(Y.filepaths)?Y.filepaths.filter((J)=>typeof J==="string"):[];if(G.length===0)return X.json({error:"filepaths is required"},400,T5);try{let J=await mu(X);return await rl$(J,Q.branch,G),X.json({ok:!0},200,T5)}catch(J){let W=J instanceof l4&&J.status===409?409:502,K=J instanceof Error?J.message:String(J);return X.json({error:K},W,T5)}});return Hs(Q.claimName,()=>rZ(X,"/_sandbox/git/discard",{forwardJsonBody:!0,map404to410:!0}))}),$.post("/:virtualMcpId/:branch/git/rebase",async(X)=>{let Q=X.get("vmClaim");if(Q.runtime==="cms")return Hs(Q.claimName,async()=>{try{let W=await X.req.json().catch(()=>({})),K=await mu(X),F=W.base??await K.getDefaultBranch();return await NT0(K,Q.branch,F),X.json({ok:!0},200,T5)}catch(W){return K71(X,W)}});let Y=Dv(X);if(Y instanceof Response)return Y;let{claimName:G}=X.get("vmClaim"),J=X.var.studioContext;return Hs(G,async()=>{try{await cZ1(J,Y,G)}catch(W){let K=W instanceof Error?W.message:String(W);return X.json({error:K},502,T5)}return rZ(X,"/_sandbox/git/rebase",{forwardJsonBody:!0,map404to410:!0})})}),$.post("/:virtualMcpId/:branch/git/suggest-commit",_9({maxSize:Zc$,onError:(X)=>X.json({error:"Payload too large"},413,T5)}),async(X)=>{let Q=X.get("vmClaim"),Y=null;if(Q.runtime!=="cms"){let F=Dv(X);if(F instanceof Response)return F;Y=F}let{claimName:G,userId:J,projectRef:W}=Q,K=X.var.studioContext;try{let F=await X.req.json().catch(()=>({})),H=F.status,N=F.diff,U=N!=null&&typeof N.diffs==="object"&&N.diffs!==null,[B,O]=iZ1(H)&&U?[H,N]:Y?await Promise.all([BT0(Y,G,"/_sandbox/git/status","GET",{userId:J,projectRef:W}),BT0(Y,G,"/_sandbox/git/diff","GET",{userId:J,projectRef:W})]):await(async()=>{let L=await mu(X);return Promise.all([FT0(L,Q.branch),HT0(L,Q.branch)])})(),w=await Nl$(K,B,O);return X.json(w,200,T5)}catch(F){let H=F instanceof Error?F.message:String(F);if(H==="SANDBOX_GONE")return X.json({error:"Sandbox handle is gone. The sandbox needs to be re-provisioned."},410,T5);return X.json({error:H},502,T5)}}),$.post("/:virtualMcpId/:branch/git/judge-review",_9({maxSize:Zc$,onError:(X)=>X.json({error:"Payload too large"},413,T5)}),async(X)=>{let Q=X.get("vmClaim"),Y=null;if(Q.runtime!=="cms"){let F=Dv(X);if(F instanceof Response)return F;Y=F}let{claimName:G,userId:J,projectRef:W}=Q,K=X.var.studioContext;try{let F=await X.req.json().catch(()=>({})),H=F.status,N=F.diff,U=N!=null&&typeof N.diffs==="object"&&N.diffs!==null,[B,O]=iZ1(H)&&U?[H,N]:Y?await Promise.all([BT0(Y,G,"/_sandbox/git/status","GET",{userId:J,projectRef:W}),BT0(Y,G,"/_sandbox/git/diff","GET",{userId:J,projectRef:W})]):await(async()=>{let L=await mu(X);return Promise.all([FT0(L,Q.branch),HT0(L,Q.branch)])})(),w=await Bl$(K,B,O,typeof F.language==="string"?F.language:void 0);return X.json(w,200,T5)}catch(F){let H=F instanceof Error?F.message:String(F);if(H==="SANDBOX_GONE")return X.json({error:"Sandbox handle is gone. The sandbox needs to be re-provisioned."},410,T5);return X.json({error:H},502,T5)}}),$.get("/:virtualMcpId/:branch/preview-fetch",async(X)=>{let Q=Dv(X);if(Q instanceof Response)return Q;let{claimName:Y}=X.get("vmClaim"),G=X.req.query("path");if(!G||!G.startsWith("/")||G.startsWith("//")||G.includes("..")||G.includes("\\"))return X.json({error:"Path not allowed"},403);let J;try{J=await Q.getPreviewUrl(Y)}catch{return X.json({error:"Preview not available"},502)}if(!J)return X.json({error:"Preview not available"},502);let W=J.replace(/\/+$/,"");return Qc$(X,`${W}${G}`)}),$.post("/:virtualMcpId/:branch/preview-invoke",_9({maxSize:uH6,onError:(X)=>X.json({error:"Payload too large"},413)}),async(X)=>{let Q=Dv(X);if(Q instanceof Response)return Q;let{claimName:Y}=X.get("vmClaim"),G;try{G=await Q.getPreviewUrl(Y)}catch{return X.json({error:"Preview not available"},502)}if(!G)return X.json({error:"Preview not available"},502);let J;try{J=await X.req.json()}catch{return X.json({error:"Invalid JSON body"},400)}if(!J||typeof J!=="object"||Array.isArray(J))return X.json({error:"Invalid JSON body"},400);let W=al$(J);if(!W)return X.json({error:"Invalid or missing __resolveType"},400);let K=sl$(G,W.resolveType);return Qc$(X,K,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(W.payload),signal:AbortSignal.timeout(30000)})}),$};var Wc$=D(()=>{Z8();yN();gu();uZ1();op();Ql$();h3();py();Yl$();m3();Gl$();Wl$();Gi0();sp();tZ1();Ol$();rZ1();cD();J71();el$();W71();gH6=/^[a-zA-Z0-9][a-zA-Z0-9/._-]*$/;cH6=rA0(async($,Z)=>{let X=$.var.studioContext;try{t(X)}catch{return $.json({error:"Unauthorized"},401)}let Q=o0(X);if(!Q)return $.json({error:"Unauthorized"},401);let Y;try{Y=n(X)}catch{return $.json({error:"Organization scope required"},403)}let G=$.req.param("virtualMcpId"),J=$.req.param("branch");if(!G||!J)return $.json({error:"virtualMcpId and branch are required"},400);try{hH6(J)}catch(w){let L=w instanceof Error?w.message:String(w);return $.json({error:L},400)}let W=await X.storage.virtualMcps.findById(G);if(!W||W.organization_id!==Y.id)return $.json({error:"Virtual MCP not found"},404);let K=np({orgId:Y.id,virtualMcpId:G,branch:J}),F=await em0(X,J),H=$i0(F,Q),N=Xl$({userId:H,projectRef:K}),U=W.metadata??null,B=await dH6($,{claimName:N,branch:J,virtualMcpId:G,sandboxUserId:H,virtualMcpMetadata:U,branchThread:F});if(B==="cms")return $.set("vmClaim",{claimName:N,callerUserId:Q,runner:null,virtualMcpId:G,branch:J,userId:H,projectRef:K,virtualMcpMetadata:U,connectionIds:W.connections?.map((w)=>w.connection_id)??[],runtime:B}),Z();let O;try{O=await YQ(X)}catch{O=null}if(!O)return $.json({error:"No sandbox runner found"},404);return $.set("vmClaim",{claimName:N,callerUserId:Q,runner:O,virtualMcpId:G,branch:J,userId:H,projectRef:K,virtualMcpMetadata:U,connectionIds:W.connections?.map((w)=>w.connection_id)??[],runtime:B}),Z()});UT0=new Map;T5={"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache"};Gc$=["clone","install","start"]});function Kc$($,Z,X){let Q=F71.get($);if(!Q)Q={pending:null,running:!1},F71.set($,Q);if(!Q.pending)Q.pending={set:new Map,del:new Set,deps:Z,resolvers:[],rejecters:[]};let Y=Q.pending;Y.deps=Z;for(let[J,W]of Object.entries(X.set??{}))Y.set.set(J,W),Y.del.delete(J);for(let J of X.delete??[])Y.del.add(J),Y.set.delete(J);let G=new Promise((J,W)=>{Y.resolvers.push(J),Y.rejecters.push(W)});if(!Q.running)tH6($,Q);return G}async function tH6($,Z){Z.running=!0;try{while(Z.pending){let X=Z.pending;Z.pending=null;try{let Q=await oH6(X);for(let Y of X.resolvers)Y(Q)}catch(Q){for(let Y of X.rejecters)Y(Q)}}}finally{if(Z.running=!1,!Z.pending)F71.delete($)}}async function oH6($){let{client:Z,branch:X,packagePath:Q}=$.deps;for(let Y=0;;Y++){let G=await du(Z,X),J=await Z.getCommitTreeSha(G),W=await Z.getDecofileTree(J,Q),K=Q71(W,Q),F=[],H=new Map(K.map((O)=>[O.path,{stem:O.stem,sha:O.sha}]));for(let[O,w]of $.set){let L=Y71(K,O),E=`${JSON.stringify(w,null,2)}
2950
- `,j=await Z.createBlob(E);await pl$(Z.owner,Z.repo,j,E);let z=L[0]??`${WT0(Q)}/${sZ1(O)}.json`;F.push({path:z,mode:"100644",type:"blob",sha:j});let P=z.slice(z.lastIndexOf("/")+1,-5);H.set(z,{stem:P,sha:j,content:E});for(let A of L.slice(1))F.push({path:A,mode:"100644",type:"blob",sha:null}),H.delete(A)}for(let O of $.del)for(let w of Y71(K,O))F.push({path:w,mode:"100644",type:"blob",sha:null}),H.delete(w);if(F.length===0)return G;let N=Q?`${Q}/.deco/blocks.gen.json`:".deco/blocks.gen.json";if(W.some((O)=>O.type==="blob"&&O.path===N)){let O=await Promise.all([...H.values()].map(async(j)=>({stem:j.stem,content:j.content??await Z.getBlobText(j.sha)}))),{decofile:w,skipped:L}=Gs(O);if(L.length>0)console.warn("decofile gen: dropped blocks that were not valid JSON",{repo:`${Z.owner}/${Z.repo}`,branch:X,packagePath:Q,blocks:L.map((j)=>j.key)});let E=await Z.createBlob(w);F.push({path:N,mode:"100644",type:"blob",sha:E})}let U=await Z.createTree(J,F),B=await Z.createCommit({message:rH6($),treeSha:U,parentShas:[G]});try{return await Z.updateRef(X,B),B}catch(O){if(!(O instanceof l4&&O.status===422)||Y>=nH6-1)throw O;await w$(eZ(2000,200,Y,2,0.5))}}}function rH6($){let Z=(Y)=>{let G=Y.slice(0,3).join(", ");return Y.length>3?`${G} (+${Y.length-3} more)`:G},X=[];if($.set.size>0)X.push(`update ${Z([...$.set.keys()])}`);if($.del.size>0)X.push(`delete ${Z([...$.del])}`);let Q=`chore(decofile): ${X.join("; ")}`;return nm0(Q,$.deps.coAuthor)}var nH6=3,F71;var Fc$=D(()=>{hO0();$T0();X4();cD();KT0();F71=new Map});import{createHmac as Hc$,randomBytes as aH6,timingSafeEqual as sH6}from"crypto";function Nc$(){if(OT0)return OT0;let $;try{let Z=_0();$=Z.studioJwtSecret??Z.betterAuthSecret}catch{$=void 0}return OT0=$?Buffer.from($):aH6(32),OT0}function H71($){let Z=$.nowMs??Date.now(),X={o:$.organizationId,m:$.virtualMcpId,b:$.branch,e:Math.floor((Z+eH6)/1000)},Q=Buffer.from(JSON.stringify(X)).toString("base64url"),Y=Hc$("sha256",Nc$()).update(Q).digest("base64url");return`${Q}.${Y}`}function Uc$($,Z){let X=$.indexOf(".");if(X<0)return!1;let Q=$.slice(0,X),Y=Buffer.from($.slice(X+1)),G=Buffer.from(Hc$("sha256",Nc$()).update(Q).digest("base64url"));if(Y.length!==G.length||!sH6(Y,G))return!1;let J;try{J=JSON.parse(Buffer.from(Q,"base64url").toString())}catch{return!1}let W=Math.floor((Z.nowMs??Date.now())/1000);return J.o===Z.organizationId&&J.m===Z.virtualMcpId&&J.b===Z.branch&&typeof J.e==="number"&&J.e>=W}var eH6=21600000,OT0=null;var Bc$=D(()=>{L$()});import{z as iu}from"zod";function ZN6($){return $.length>0&&$.length<=255&&!$.includes("..")&&!$.endsWith("/")&&!$.endsWith(".lock")&&$N6.test($)}function Ec$($){return $.req.header("x-forwarded-host")??new URL($.req.url).host}async function Ns($){let Z=$.get("decofileScope");return sA0($.var.studioContext,Z.organizationId,Z.githubRepo)}function Us($,Z){if(Z instanceof l4){let Q=Z.status===404?404:Z.status===409?409:Z.status===422?409:502;return $.json({error:Z.message},Q)}let X=Z instanceof Error?Z.message:String(Z);return $.json({error:X},500)}function jc$(){let $=new K1;return $.use("/:virtualMcpId/:branch",Lc$),$.use("/:virtualMcpId/:branch/*",Lc$),$.get("/:virtualMcpId/:branch",async(Z)=>{let X=Z.get("decofileScope");try{let Q=await Ns(Z),Y=await nl$(Q,X.branch,X.packagePath,{createBranchIfMissing:!!X.userId}),G={ETag:`"${Y.sha}"`,"Cache-Control":"no-store","Access-Control-Allow-Origin":"*"};if(Z.req.header("if-none-match")===`"${Y.sha}"`)return Z.body(null,304,G);if(!X.userId)return Z.body(Y.decofile,200,{...G,"content-type":"application/json"});let J=H71({organizationId:X.organizationId,virtualMcpId:X.virtualMcpId,branch:X.branch});return Z.body(`{"version":${JSON.stringify(Y.sha)},"token":${JSON.stringify(J)},"apiHost":${JSON.stringify(Ec$(Z))},"decofile":${Y.decofile}}`,200,{...G,"content-type":"application/json"})}catch(Q){return Us(Z,Q)}}),$.get("/:virtualMcpId/:branch/meta",async(Z)=>{let X=Z.get("decofileScope"),Q=X.packagePath?`${X.packagePath}/.deco/meta.gen.json`:".deco/meta.gen.json";try{let Y=await Ns(Z),G=await Y.getFileTextAtRef(X.branch,Q);if(G===null){let J=await Y.getDefaultBranch();if(J!==X.branch)G=await Y.getFileTextAtRef(J,Q)}if(G===null)return Z.json({error:"meta.gen.json not committed"},404);return Z.body(G,200,{"content-type":"application/json","Cache-Control":"no-store","Access-Control-Allow-Origin":"*"})}catch(Y){return Us(Z,Y)}}),$.patch("/:virtualMcpId/:branch",QN6,async(Z)=>{let X=Z.get("decofileScope"),Q=Z.var.studioContext,Y=YN6.safeParse(await Z.req.json().catch(()=>null));if(!Y.success)return Z.json({error:"Invalid body",details:Y.error.issues},400);let G=Y.data;for(let J of[...Object.keys(G.set??{}),...G.delete??[]])try{eA0(J)}catch(W){let K=W instanceof Error?W.message:String(W);return Z.json({error:K},400)}for(let[J,W]of Object.entries(G.set??{})){if(typeof W!=="object"||W===null||Array.isArray(W))return Z.json({error:`Block "${J}" must be a JSON object`},400);if(aZ1(J))return Z.json({error:`Block key "${J}" collides with a framework resolver module and cannot be written`},400)}try{let J=await Ns(Z),W=await Kc$(`${X.organizationId}/${X.virtualMcpId}/${X.branch}`,{client:J,branch:X.branch,packagePath:X.packagePath,coAuthor:hu(Q)},G),K=H71({organizationId:X.organizationId,virtualMcpId:X.virtualMcpId,branch:X.branch});return Z.json({version:W,token:K,apiHost:Ec$(Z)})}catch(J){return Us(Z,J)}}),$.post("/:virtualMcpId/:branch/publish",async(Z)=>{let X=Z.get("decofileScope");try{let Q=await Ns(Z),Y=await Q.getDefaultBranch();if(Y===X.branch)return Z.json({error:"Branch is already the default branch"},400);let G=`chore(decofile): publish ${X.branch}`;try{let J;try{J=await Q.mergeBranch(Y,X.branch,G)}catch(W){if(!(W instanceof l4&&W.status===409))throw W;await NT0(Q,X.branch,Y),J=await Q.mergeBranch(Y,X.branch,G)}return J?Z.json({result:"merged",sha:J}):Z.json({result:"up-to-date"})}catch(J){if(J instanceof l4&&J.status===409)return Z.json({error:"merge-conflict"},409);if(J instanceof l4&&J.status===405){let K=await Q.findOpenPullRequest(Y,X.branch)??await Q.createPullRequest({base:Y,head:X.branch,title:`Publish ${X.branch}`});return Z.json({result:"pull-request",number:K.number,url:K.html_url})}throw J}}catch(Q){return Us(Z,Q)}}),$.get("/:virtualMcpId/:branch/status",async(Z)=>{let X=Z.get("decofileScope");try{let Q=await Ns(Z),Y=await Q.getDefaultBranch();if(Y===X.branch)return Z.json({baseBranch:Y,aheadBy:0,behindBy:0,lastCommitAt:null});try{let[{aheadBy:G,behindBy:J},W]=await Promise.all([Q.compare(Y,X.branch),Q.getBranchHead(X.branch)]);return Z.json({baseBranch:Y,aheadBy:G,behindBy:J,lastCommitAt:W.committedAt})}catch(G){if(G instanceof l4&&G.status===404)return Z.json({baseBranch:Y,aheadBy:0,behindBy:0,lastCommitAt:null});throw G}}catch(Q){return Us(Z,Q)}}),$}var $N6,Oc$=500,Dc$=1048576,wc$=1024,XN6=8388608,QN6,YN6,Lc$;var zc$=D(()=>{Sn0();$T0();Z8();yN();uZ1();aA0();W71();rZ1();Fc$();Bc$();J71();cD();KT0();$N6=/^[a-zA-Z0-9][a-zA-Z0-9/._-]*$/;QN6=_9({maxSize:XN6,onError:($)=>$.json({error:"Payload too large"},413)}),YN6=iu.object({set:iu.record(iu.string(),iu.unknown()).optional(),delete:iu.array(iu.string()).optional()}).refine(($)=>Object.keys($.set??{}).length>0||($.delete?.length??0)>0,{message:"Patch must set or delete at least one block"}).refine(($)=>Object.keys($.set??{}).length+($.delete?.length??0)<=Oc$,{message:`Patch cannot touch more than ${Oc$} blocks`}).refine(($)=>Object.values($.set??{}).every((Z)=>JSON.stringify(Z).length<=Dc$),{message:`Each block must be at most ${Dc$} bytes`}).refine(($)=>[...Object.keys($.set??{}),...$.delete??[]].every((Z)=>Z.length<=wc$),{message:`Each block key must be at most ${wc$} characters`}),Lc$=rA0(async($,Z)=>{let X=$.var.studioContext,Q=X.organization;if(!Q)return $.json({error:"Organization scope required"},500);let Y=$.req.param("virtualMcpId"),G=$.req.param("branch");if(!Y||!G)return $.json({error:"virtualMcpId and branch are required"},400);if(!ZN6(G))return $.json({error:`Invalid branch name: ${G}`},400);let J=X.auth?.user?.id??null;if(!J){let B=$.req.query("token");if(!($.req.method==="GET"&&!$.req.path.match(/\/(publish|status)$/)))return $.json({error:"Unauthorized"},401);if(!B||!Uc$(B,{organizationId:Q.id,virtualMcpId:Y,branch:G}))return $.json({error:"Unauthorized"},401)}let W=await X.storage.virtualMcps.findById(Y);if(!W||W.organization_id!==Q.id)return $.json({error:"Virtual MCP not found"},404);let K=W.metadata??null;if(!mO0(K))return $.json({error:"Project has no preview server configured"},404);let H=W.connections?.map((B)=>B.connection_id)??[],N=Fs(K,H);if(!N)return $.json({error:"Project has no GitHub repository"},404);let U=K?.runtime;return $.set("decofileScope",{organizationId:Q.id,virtualMcpId:Y,branch:G,packagePath:U?.path?.replace(/^\/+|\/+$/g,"")||null,githubRepo:N,userId:J}),Z()})});var Pc$=($)=>{let Z=new K1;if(Z.use("*",Zv),Z.route("/",HA0()),Z.route("/",yy$()),Z.route("/",du$()),Z.route("/",uu$()),Z.route("/",nA0()),Z.route("/tools",ru$()),Z.route("/",nu$()),Z.route("/",ju$({kvStorage:$.kvStorage})),Z.route("/",Lu$()),Z.route("/fs",vu$({getConnection:$.getNatsConnection})),Z.route("/sandbox",Jc$()),Z.route("/decofile",jc$()),Z.route("/",yu$()),Z.route("/deco-sites",UA0()),Z.route("/hosting",qy$()),Z.route("/monitor",vy$()),Z.route("/sso",YA0()),Z.route("/",tA0({tokenStorage:$.tokenStorage,automationEventDispatcher:$.automationEventDispatcher})),Z.route("/webhooks",Py$()),$.mountDevAssets)Z.route("/dev-assets",wA0({orgFromPath:!0}));return Z.use("/mcp/:connectionId?",$.mcpAuth),Z.use("/mcp/:connectionId/ui-resource",$.mcpAuth),Z.use("/mcp/gateway/:virtualMcpId?",$.mcpAuth),Z.use("/mcp/virtual-mcp/:virtualMcpId?",$.mcpAuth),Z.use("/mcp/self",$.mcpAuth),Z.use("/mcp/task-run/:threadId",$.mcpAuth),Z.route("/",pf$()),Z.get("/mcp/:gateway?/:connectionId/.well-known/oauth-protected-resource/*",$.betterAuthProtectedResourceHandler),Z.get("/mcp/.well-known/oauth-protected-resource",$.betterAuthProtectedResourceHandler),Z.route("/mcp/task-run",bu$()),Z.route("/mcp",FL0()),Z.route("/mcp/self",pA0()),Z.route("/mcp",UL0()),Z.all("/oauth-proxy/:connectionId/*",$.oauthProxyHandler),Z.get("/watch",$.watchHandler),Z};var Ac$=D(()=>{Z8();sP0();Ay$();H91();My$();fy$();LA0();Ca();G91();Eu$();zu$();fu$();vt();e51();BL0();vZ1();xu$();gu$();lu$();mu$();tu$();bZ1();au$();xZ1();HL0();Wc$();zc$()});function GN6($){return $.filter((Z)=>Z.vendors?.alias).map((Z)=>({name:Z.name,title:Z.title,description:Z.description,logo:Z.logo,category:Z.category,vendor:{alias:Z.vendors.alias,url:Z.vendors.url}}))}var JN6=async($,Z)=>{if(!$.get("studioContext").auth.user?.id)return $.json({error:"Unauthorized"},401);return Z()},Tc$=()=>{let $=new K1;return $.use("*",JN6),$.get("/",async(Z)=>{let X=_0(),Q=X.decoSupabaseUrl,Y=X.decoSupabaseServiceKey;if(!Q||!Y)return Z.json({apps:[]});try{let G=await DY(Q,Y,"apps?select=name,title,description,logo,category,vendors(alias,url)");return Z.json({apps:GN6(G)})}catch(G){return console.error("[deco-apps] GET error:",G),Z.json({error:"Failed to fetch apps"},502)}}),$};var Rc$=D(()=>{Z8();L$();QP0()});import{z as M1}from"zod";function AF($,Z="invalid_request_error",X=null,Q=null){return{error:{message:$,type:Z,param:X,code:Q}}}function wN6($){if(!$)return null;let Z=$.indexOf(":");if(Z===-1)return{credentialId:null,modelId:$};let X=$.substring(0,Z),Q=$.substring(Z+1);if(!X||!Q)return null;return{credentialId:X,modelId:Q}}function LN6($,Z,X){try{return JSON.parse($)}catch{throw new Mc$(`Invalid JSON in tool call arguments for function '${X}' (tool_call_id: ${Z}): ${$}`)}}function EN6($){let Z={};for(let X of $)if(X.role==="assistant"&&X.tool_calls)for(let Q of X.tool_calls)Z[Q.id]=Q.function.name;return $.map((X)=>{switch(X.role){case"system":return{role:"system",content:X.content};case"user":if(typeof X.content==="string")return{role:"user",content:X.content};return{role:"user",content:X.content.map((Y)=>{if(Y.type==="text")return{type:"text",text:Y.text};return{type:"image",image:Y.image_url.url}})};case"assistant":if(X.tool_calls&&X.tool_calls.length>0)return{role:"assistant",content:X.tool_calls.map((Y)=>({type:"tool-call",toolCallId:Y.id,toolName:Y.function.name,input:LN6(Y.function.arguments,Y.id,Y.function.name)}))};return{role:"assistant",content:X.content??""};case"tool":let Q=Z[X.tool_call_id]??"unknown";return{role:"tool",content:[{type:"tool-result",toolCallId:X.tool_call_id,toolName:Q,output:{type:"text",value:X.content}}]}}})}function jN6($){let Z=$.map((X)=>{let Q=X.function.parameters?pY(X.function.parameters):pY({type:"object",properties:{}});return[X.function.name,h$({description:X.function.description,inputSchema:Q})]});return Object.fromEntries(Z)}function zN6($){if(!$)return;return{openai:{response_format:$}}}function PN6(){return`chatcmpl-${crypto.randomUUID().replace(/-/g,"").substring(0,29)}`}function Ic$($,Z,X,Q,Y,G){let J={model:$,messages:Z,tools:X,temperature:Q.temperature,maxTokens:Q.max_tokens,topP:Q.top_p,frequencyPenalty:Q.frequency_penalty,presencePenalty:Q.presence_penalty,stopSequences:Q.stop?Array.isArray(Q.stop)?Q.stop:[Q.stop]:void 0,abortSignal:G};return Y?{...J,providerOptions:Y}:J}function qc$($){if($==="tool-calls")return"tool_calls";if($==="length")return"length";return"stop"}var WN6=256,KN6,FN6,HN6,NN6,UN6,BN6,ON6,DN6,Mc$,kc$,Vc$;var Sc$=D(()=>{m4();Z8();gu();TN();KN6=M1.object({type:M1.literal("function"),function:M1.object({name:M1.string(),description:M1.string().optional(),parameters:M1.record(M1.string(),M1.unknown()).optional()})}),FN6=M1.object({id:M1.string(),type:M1.literal("function"),function:M1.object({name:M1.string(),arguments:M1.string()})}),HN6=M1.discriminatedUnion("role",[M1.object({role:M1.literal("system"),content:M1.string(),name:M1.string().optional()}),M1.object({role:M1.literal("user"),content:M1.union([M1.string(),M1.array(M1.union([M1.object({type:M1.literal("text"),text:M1.string()}),M1.object({type:M1.literal("image_url"),image_url:M1.object({url:M1.string(),detail:M1.string().optional()})})]))]),name:M1.string().optional()}),M1.object({role:M1.literal("assistant"),content:M1.string().nullable().optional(),name:M1.string().optional(),tool_calls:M1.array(FN6).optional()}),M1.object({role:M1.literal("tool"),content:M1.string(),tool_call_id:M1.string()})]),NN6=M1.object({type:M1.literal("text")}),UN6=M1.object({type:M1.literal("json_object")}),BN6=M1.object({type:M1.literal("json_schema"),json_schema:M1.object({name:M1.string(),description:M1.string().optional(),schema:M1.record(M1.string(),M1.unknown()),strict:M1.boolean().optional()})}),ON6=M1.union([NN6,UN6,BN6]),DN6=M1.object({model:M1.string().describe("Format: 'model_id' or 'credential_id:model_id'"),messages:M1.array(HN6),stream:M1.boolean().optional().default(!1),temperature:M1.number().min(0).max(2).optional(),max_tokens:M1.number().positive().optional(),top_p:M1.number().min(0).max(1).optional(),frequency_penalty:M1.number().min(-2).max(2).optional(),presence_penalty:M1.number().min(-2).max(2).optional(),stop:M1.union([M1.string(),M1.array(M1.string())]).optional(),tools:M1.array(KN6).optional(),tool_choice:M1.union([M1.literal("auto"),M1.literal("none"),M1.literal("required"),M1.object({type:M1.literal("function"),function:M1.object({name:M1.string()})})]).optional(),response_format:ON6.optional(),user:M1.string().optional()});Mc$=class Mc$ extends Error{constructor($){super($);this.name="MessageConversionError"}};kc$=new K1;kc$.post("/:org/v1/chat/completions",async($)=>{let Z=$.get("studioContext"),X=$.req.param("org");try{if(!Z.auth.apiKey?.id)return $.json(AF("API key authentication required. Provide a valid API key via Authorization header.","authentication_error"),401);if(!Z.organization)return $.json(AF("Organization context is required. Ensure your API key has organization metadata.","invalid_request_error","organization"),400);if((Z.organization.slug??Z.organization.id)!==X)return $.json(AF("Organization mismatch. The API key's organization does not match the requested organization.","invalid_request_error","organization"),403);let Q=await $.req.json(),Y=DN6.safeParse(Q);if(!Y.success){let L=Y.error.issues[0]??{message:"Invalid request",path:[]};return $.json(AF(`Invalid request: ${L.message}`,"invalid_request_error",L.path.length>0?L.path.join("."):null),400)}let G=Y.data,J=wN6(G.model);if(!J)return $.json(AF("Invalid model format. Expected 'model_id' or 'credential_id:model_id' (e.g., 'claude-sonnet-4-6' or 'key_abc123:claude-sonnet-4-6')","invalid_request_error","model"),400);let{credentialId:W}=J,{modelId:K}=J;if(!W){let E=(await Z.storage.aiProviderKeys.list({organizationId:Z.organization.id})).find((j)=>GL(j.providerId));if(!E)return $.json(AF("No AI provider credentials configured for this organization. Add a credential in settings or specify one explicitly via 'credential_id:model_id'.","invalid_request_error","model"),400);W=E.id}let F;try{F=await Z.aiProviders.activate(W,Z.organization.id)}catch{return $.json(AF(`AI provider credential not found or inaccessible: ${W}`,"invalid_request_error","model"),404)}let H=F.aiSdk.languageModel(K),N=EN6(G.messages),U=G.tools?jN6(G.tools):void 0,B=zN6(G.response_format),O=PN6(),w=Math.floor(Date.now()/1000);if(G.stream)return iN($,async(L)=>{let E=Ic$(H,N,U,G,B,$.req.raw.signal);try{let j=AO(E),z=!1,P=0,A="",I=async()=>{if(A.length===0)return;let k=A;A="",await L.writeSSE({data:JSON.stringify({id:O,object:"chat.completion.chunk",created:w,model:G.model,choices:[{index:0,delta:{content:k},finish_reason:null}]})})};for await(let k of j.fullStream){if(!z&&(k.type==="text-delta"||k.type==="tool-call"))await L.writeSSE({data:JSON.stringify({id:O,object:"chat.completion.chunk",created:w,model:G.model,choices:[{index:0,delta:{role:"assistant",content:""},finish_reason:null}]})}),z=!0;if(k.type==="text-delta"){if(A+=k.text,A.length>=WN6)await I()}else if(k.type==="tool-call"){await I();let M=P++;await L.writeSSE({data:JSON.stringify({id:O,object:"chat.completion.chunk",created:w,model:G.model,choices:[{index:0,delta:{tool_calls:[{index:M,id:k.toolCallId,type:"function",function:{name:k.toolName,arguments:JSON.stringify(k.input)}}]},finish_reason:null}]})})}else if(k.type==="finish")await I(),await L.writeSSE({data:JSON.stringify({id:O,object:"chat.completion.chunk",created:w,model:G.model,choices:[{index:0,delta:{},finish_reason:qc$(k.finishReason)}],usage:k.totalUsage?{prompt_tokens:k.totalUsage.inputTokens??0,completion_tokens:k.totalUsage.outputTokens??0,total_tokens:k.totalUsage.totalTokens??0}:void 0})})}await I(),await L.writeSSE({data:"[DONE]"})}catch(j){let z=j;console.error("[openai-compat:stream] Error:",z.message),await L.writeSSE({data:JSON.stringify({error:{message:z.message,type:"server_error"}})})}});else{let L=Ic$(H,N,U,G,B,$.req.raw.signal),E=await zO(L),j={role:"assistant",content:E.text||null};if(E.toolCalls&&E.toolCalls.length>0)j.tool_calls=E.toolCalls.map((z)=>({id:z.toolCallId,type:"function",function:{name:z.toolName,arguments:JSON.stringify("input"in z?z.input:{})}})),j.content=null;return $.json({id:O,object:"chat.completion",created:w,model:G.model,choices:[{index:0,message:j,finish_reason:qc$(E.finishReason)}],usage:{prompt_tokens:E.usage?.inputTokens??0,completion_tokens:E.usage?.outputTokens??0,total_tokens:E.usage?.totalTokens??0}})}}catch(Q){let Y=Q;if(Y.name==="AbortError")return $.json(AF("Request aborted","invalid_request_error"),400);if(Y.name==="MessageConversionError")return $.json(AF(Y.message,"invalid_request_error","messages"),400);return console.error("[openai-compat] Error:",Y.message,Y.stack),$.json(AF(Y.message,"server_error"),500)}});Vc$=kc$});function AN6($){if(typeof $!=="object"||$===null)return!1;let X=$.githubRepo?.url;return typeof X==="string"&&X.length>0}function Cc$(){let $=new K1;return $.use("*",async(Z,X)=>{await X(),Z.header("Cache-Control","private, no-store"),Z.header("Vary","Cookie")}),$.get("/",async(Z)=>{let X=Z.get("studioContext"),Q=o0(X);if(!Q)return Z.json({error:"Authentication required"},401);let G=(Z.req.query("site")??"").trim().toLowerCase();if(!nX(G))return Z.json({error:"Invalid site slug"},400);let J=await X.db.selectFrom("member").innerJoin("organization","organization.id","member.organizationId").select(["organization.id as id","organization.slug as slug","organization.name as name","organization.metadata as metadata"]).where("member.userId","=",Q).execute(),W=[];for(let F of J){if(!F.slug||d9(F))continue;let H=await X.storage.virtualMcps.list(F.id);for(let N of H){if(ns1(N)!==G)continue;if(!AN6(N.metadata))continue;W.push({orgSlug:F.slug,orgName:F.name??F.slug,project:{id:N.id,title:N.title,icon:N.icon??null}})}}let K={matches:W};return Z.json(K)}),$}var _c$=D(()=>{Z8();VH()});var fc$;var vc$=D(()=>{fc$={name:"decocms",version:"4.321.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","db:migrate:dbos":"bun run ./dist/server/migrate-dbos.js",check:"tsc --noEmit",start:"bun run ./dist/server/server.js",migrate:"bun run src/database/migrate.ts","migrate:dbos":"bun run src/database/migrate-dbos.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","@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"}}});function IN6(){let $=process.env.POSTHOG_KEY;if(!$)return null;return{key:$,host:process.env.POSTHOG_HOST??RN6}}var bc$,RN6="https://ph.studio.decocms.com",xc$;var yc$=D(()=>{Z8();g50();yC();X9();L$();l51();vc$();bc$=new K1;bc$.get("/",($)=>{let Z={version:fc$.version,theme:Fi1(),...AH().logo&&{logo:AH().logo},...HN()&&{internalUrl:hC1()},..._0().enableDecoImport&&{enableDecoImport:!0},brandExtractEnabled:!!_0().firecrawlApiKey,hostingEnabled:!!_0().controlplaneRestUrl&&!!_0().controlplaneServiceToken,hostingControlPlaneGa:_0().hostingControlPlaneGa,monitorEnabled:!!_0().clickhouseAnalyticsUrl&&!!_0().clickhouseAnalyticsPassword,monitorGa:_0().monitorGa,auth:qx$(),posthog:IN6(),googleMapsApiKey:process.env.GOOGLE_MAPS_API_KEY?.trim()||null,runtime:{agentSandbox:zs()}};return $.header("Cache-Control","no-store"),$.json({success:!0,config:Z})});xc$=bc$});function pu($){let Z=($??"").trim().toLowerCase();return Z=Z.replace(/^https?:\/\//,""),Z=Z.replace(/^www\./,""),Z=Z.split(/[/?#]/)[0]??"",Z.replace(/\/+$/,"")}function N71($){return(pu($).split(".")[0]||$).replace(/[-_]/g," ").split(" ").filter(Boolean).map((X)=>X.charAt(0).toUpperCase()+X.slice(1)).join(" ")}function hc$($,Z=64){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(pu($))}&sz=${Z}`}function gc$($,Z){let X=$.trim();if(X.length<=Z)return X;let Q=X.slice(0,Z-1),Y=Q.lastIndexOf(" ");return`${(Y>Z*0.6?Q.slice(0,Y):Q).trimEnd()}\u2026`}function uc$($){let{brand:Z,domain:X,score:Q,verdict:Y}=$,G=typeof Q==="number"?`${Z} commerce report \u2014 ${Math.round(Q)}/100 \xB7 decocms`:`${Z} commerce report \xB7 decocms`,J=`See the full ${Z} scorecard \u2014 SEO, performance, conversion & AEO signals scored by decocms.`,W=Y?.trim()?gc$(`${Y.trim().replace(/\s+/g," ")} \u2014 ${J}`,200):gc$(`How does ${X} really perform? ${J}`,200);return{title:G,description:W}}import{z as c0}from"zod";var wv,qN6,MN6,kN6,VN6,lc$;var cc$=D(()=>{wv=c0.enum(["good","bad","neutral"]),qN6=c0.preprocess(($)=>{if(Array.isArray($))return{kind:"text",value:$.find((X)=>X!==null&&typeof X!=="object")??""};return $!==null&&typeof $==="object"?$:{kind:"text",value:$}},c0.object({kind:c0.enum(["text","number","sparkline","badge","score"]).catch("text"),value:c0.coerce.string().optional(),tone:wv.optional(),muted:c0.boolean().optional(),delta:c0.coerce.string().optional(),deltaDir:c0.enum(["up","down","neutral"]).optional(),points:c0.array(c0.coerce.number()).optional(),label:c0.coerce.string().optional()}).transform(($)=>{if($.kind==="badge"&&$.label==null)$.label=$.value??"";if($.kind==="score"){let Z=Number($.value);if(Number.isNaN(Z))return{...$,kind:"text"}}return $})),MN6=c0.preprocess(($)=>{let Z=$;if(Z&&typeof Z==="object"&&!Array.isArray(Z)&&Array.isArray(Z.cells))Z=Z.cells;if(Array.isArray(Z)&&Z.length===1&&Array.isArray(Z[0]))Z=Z[0];if(Array.isArray(Z))return Z;if(Z&&typeof Z==="object")return Object.values(Z);return Z},c0.array(qN6)),kN6={key:c0.coerce.string(),title:c0.coerce.string(),eyebrow:c0.coerce.string().optional(),headline:c0.coerce.string(),annotation:c0.coerce.string().optional(),methodology:c0.coerce.string().optional(),sources:c0.array(c0.object({name:c0.coerce.string(),logoUrl:c0.coerce.string()})).optional()},VN6=c0.discriminatedUnion("template",[c0.object({template:c0.literal("cover"),score:c0.object({value:c0.coerce.number(),max:c0.coerce.number().optional(),grade:c0.coerce.string().optional(),label:c0.coerce.string().optional()}).optional(),brandImage:c0.coerce.string().optional(),screenshot:c0.coerce.string().optional(),mobileScreenshot:c0.coerce.string().optional()}),c0.object({template:c0.literal("cta"),ctaUrl:c0.coerce.string().optional(),ctaLabel:c0.coerce.string().optional(),bullets:c0.array(c0.coerce.string()).optional()}),c0.object({template:c0.literal("series"),points:c0.array(c0.coerce.number()).min(2),xLabels:c0.array(c0.coerce.string()).min(1),unit:c0.coerce.string().optional(),callout:c0.object({index:c0.coerce.number(),value:c0.coerce.string(),tone:wv.optional()})}),c0.object({template:c0.literal("threshold"),value:c0.coerce.string().default(""),metricLabel:c0.coerce.string().optional(),ratio:c0.coerce.number(),thresholdRatio:c0.coerce.number().optional(),thresholdLabel:c0.coerce.string().default(""),tone:wv.optional()}),c0.object({template:c0.literal("stats"),stats:c0.array(c0.object({value:c0.coerce.string(),label:c0.coerce.string(),tone:wv.optional()})).min(1)}),c0.object({template:c0.literal("bars"),items:c0.array(c0.object({value:c0.coerce.string(),label:c0.coerce.string(),ratio:c0.coerce.number(),tone:wv.optional()})).min(1)}),c0.object({template:c0.literal("gauges"),gauges:c0.array(c0.object({label:c0.coerce.string(),value:c0.coerce.string(),status:c0.enum(["good","warn","bad"]).catch("warn"),caption:c0.coerce.string().optional(),ratio:c0.coerce.number().optional()})).min(1)}),c0.object({template:c0.literal("checklist"),checks:c0.array(c0.object({label:c0.coerce.string(),status:c0.enum(["pass","fail","warn"]).catch("fail"),value:c0.coerce.string().optional()})).min(1)}),c0.object({template:c0.literal("table"),columns:c0.array(c0.object({label:c0.coerce.string(),align:c0.enum(["left","right"]).optional()})).min(1),rows:c0.array(MN6).min(1),highlightRow:c0.coerce.number().optional()}),c0.object({template:c0.literal("products"),products:c0.array(c0.object({name:c0.coerce.string(),price:c0.coerce.string().optional(),image:c0.coerce.string().optional(),url:c0.coerce.string().optional()})).min(1)}),c0.object({template:c0.literal("list"),entries:c0.array(c0.object({label:c0.coerce.string(),severity:c0.enum(["error","warning","notice"]).catch("notice")})).min(1),moreCount:c0.coerce.number().optional()}),c0.object({template:c0.literal("keywords"),volumeLabel:c0.coerce.string().optional(),keywords:c0.array(c0.object({term:c0.coerce.string(),volume:c0.coerce.string(),position:c0.coerce.number().catch(0)})).min(1)}),c0.object({template:c0.literal("competitor"),metricLabel:c0.coerce.string().optional(),competitors:c0.array(c0.object({name:c0.coerce.string(),value:c0.coerce.string(),tone:wv.optional(),isYou:c0.boolean().optional()})).min(1)}),c0.object({template:c0.literal("scorecard"),rivalLabel:c0.coerce.string().optional(),dimensions:c0.array(c0.object({label:c0.coerce.string(),you:c0.coerce.string(),rival:c0.coerce.string().optional(),rivalName:c0.coerce.string().optional(),tone:wv.optional()})).min(1)})]),lc$=c0.object({...kN6,template:VN6})});function DT0($){let Z=[],X=[...$.sections].sort((Y,G)=>Y.position-G.position).map((Y)=>{let G=lc$.safeParse(Y.props);if(G.success)return G.data;let J=G.error.issues[0];return Z.push({section_type:Y.section_type,position:Y.position,reason:J?`${J.path.join(".")||"(root)"}: ${J.message}`:"contract violation"}),null}).filter((Y)=>Y!==null),Q=X.filter((Y)=>Y.template.template!=="cover"&&Y.template.template!=="cta").map((Y)=>({key:Y.key,title:Y.title}));return{deck:{meta:{...$.meta,scores:$.summary?.scores,scannedAt:$.scanned_at,toc:Q},slides:X},drops:Z}}var U71=D(()=>{cc$()});import{join as dc$}from"path";async function CN6($){try{let Z=await fetch(`${KK({})}/api/v2/public/diagnostics/${encodeURIComponent($)}`,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(SN6)});if(!Z.ok)return null;let X=await Z.json(),{deck:Q}=DT0(X);if(!Q.slides.length)return null;let Y=Q.slides.find((W)=>W.template.template==="cover"),G=Y?.template,J=G&&G.template==="cover"?G:void 0;return{brand:Q.meta.brand?.trim()||N71($),score:Q.meta.scores?.cover??J?.score?.value,verdict:Y?.annotation?.trim()||Y?.headline?.trim()||void 0}}catch{return null}}function EG($){return $.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;")}function _N6($,Z){let X=pu($),Q=Z?.brand?.trim()||N71(X),Y=hc$(X,128),J=`${(_0().baseUrl??"https://studio.decocms.com").replace(/\/+$/,"")}/report/${encodeURIComponent(X)}`,{title:W,description:K}=uc$({brand:Q,domain:X,score:Z?.score,verdict:Z?.verdict}),F=`${J}/og.png`,H=`${Q} commerce report by decocms`;return[`<title>${EG(W)}</title>`,`<meta name="description" content="${EG(K)}" />`,'<meta name="robots" content="noindex, follow" />','<meta property="og:type" content="website" />','<meta property="og:site_name" content="decocms" />',`<meta property="og:title" content="${EG(W)}" />`,`<meta property="og:description" content="${EG(K)}" />`,`<meta property="og:url" content="${EG(J)}" />`,`<meta property="og:image" content="${EG(F)}" />`,'<meta property="og:image:width" content="1200" />','<meta property="og:image:height" content="630" />',`<meta property="og:image:alt" content="${EG(H)}" />`,'<meta name="twitter:card" content="summary_large_image" />',`<meta name="twitter:title" content="${EG(W)}" />`,`<meta name="twitter:description" content="${EG(K)}" />`,`<meta name="twitter:image" content="${EG(F)}" />`,`<meta name="twitter:image:alt" content="${EG(H)}" />`,`<link rel="canonical" href="${EG(J)}" />`,`<link rel="icon" href="${EG(Y)}" sizes="any" />`].join(`
2950
+ `,j=await Z.createBlob(E);await pl$(Z.owner,Z.repo,j,E);let z=L[0]??`${WT0(Q)}/${sZ1(O)}.json`;F.push({path:z,mode:"100644",type:"blob",sha:j});let P=z.slice(z.lastIndexOf("/")+1,-5);H.set(z,{stem:P,sha:j,content:E});for(let A of L.slice(1))F.push({path:A,mode:"100644",type:"blob",sha:null}),H.delete(A)}for(let O of $.del)for(let w of Y71(K,O))F.push({path:w,mode:"100644",type:"blob",sha:null}),H.delete(w);if(F.length===0)return G;let N=Q?`${Q}/.deco/blocks.gen.json`:".deco/blocks.gen.json";if(W.some((O)=>O.type==="blob"&&O.path===N)){let O=await Promise.all([...H.values()].map(async(j)=>({stem:j.stem,content:j.content??await Z.getBlobText(j.sha)}))),{decofile:w,skipped:L}=Gs(O);if(L.length>0)console.warn("decofile gen: dropped blocks that were not valid JSON",{repo:`${Z.owner}/${Z.repo}`,branch:X,packagePath:Q,blocks:L.map((j)=>j.key)});let E=await Z.createBlob(w);F.push({path:N,mode:"100644",type:"blob",sha:E})}let U=await Z.createTree(J,F),B=await Z.createCommit({message:rH6($),treeSha:U,parentShas:[G]});try{return await Z.updateRef(X,B),B}catch(O){if(!(O instanceof l4&&O.status===422)||Y>=nH6-1)throw O;await w$(eZ(2000,200,Y,2,0.5))}}}function rH6($){let Z=(Y)=>{let G=Y.slice(0,3).join(", ");return Y.length>3?`${G} (+${Y.length-3} more)`:G},X=[];if($.set.size>0)X.push(`update ${Z([...$.set.keys()])}`);if($.del.size>0)X.push(`delete ${Z([...$.del])}`);let Q=`chore(decofile): ${X.join("; ")}`;return nm0(Q,$.deps.coAuthor)}var nH6=3,F71;var Fc$=D(()=>{hO0();$T0();X4();cD();KT0();F71=new Map});import{createHmac as Hc$,randomBytes as aH6,timingSafeEqual as sH6}from"crypto";function Nc$(){if(OT0)return OT0;let $;try{let Z=_0();$=Z.studioJwtSecret??Z.betterAuthSecret}catch{$=void 0}return OT0=$?Buffer.from($):aH6(32),OT0}function H71($){let Z=$.nowMs??Date.now(),X={o:$.organizationId,m:$.virtualMcpId,b:$.branch,e:Math.floor((Z+eH6)/1000)},Q=Buffer.from(JSON.stringify(X)).toString("base64url"),Y=Hc$("sha256",Nc$()).update(Q).digest("base64url");return`${Q}.${Y}`}function Uc$($,Z){let X=$.indexOf(".");if(X<0)return!1;let Q=$.slice(0,X),Y=Buffer.from($.slice(X+1)),G=Buffer.from(Hc$("sha256",Nc$()).update(Q).digest("base64url"));if(Y.length!==G.length||!sH6(Y,G))return!1;let J;try{J=JSON.parse(Buffer.from(Q,"base64url").toString())}catch{return!1}let W=Math.floor((Z.nowMs??Date.now())/1000);return J.o===Z.organizationId&&J.m===Z.virtualMcpId&&J.b===Z.branch&&typeof J.e==="number"&&J.e>=W}var eH6=21600000,OT0=null;var Bc$=D(()=>{L$()});import{z as iu}from"zod";function ZN6($){return $.length>0&&$.length<=255&&!$.includes("..")&&!$.endsWith("/")&&!$.endsWith(".lock")&&$N6.test($)}function Ec$($){return $.req.header("x-forwarded-host")??new URL($.req.url).host}async function Ns($){let Z=$.get("decofileScope");return sA0($.var.studioContext,Z.organizationId,Z.githubRepo)}function Us($,Z){if(Z instanceof l4){let Q=Z.status===404?404:Z.status===409?409:Z.status===422?409:502;return $.json({error:Z.message},Q)}let X=Z instanceof Error?Z.message:String(Z);return $.json({error:X},500)}function jc$(){let $=new K1;return $.use("/:virtualMcpId/:branch",Lc$),$.use("/:virtualMcpId/:branch/*",Lc$),$.get("/:virtualMcpId/:branch",async(Z)=>{let X=Z.get("decofileScope");try{let Q=await Ns(Z),Y=await nl$(Q,X.branch,X.packagePath,{createBranchIfMissing:!!X.userId}),G={ETag:`"${Y.sha}"`,"Cache-Control":"no-store","Access-Control-Allow-Origin":"*"};if(Z.req.header("if-none-match")===`"${Y.sha}"`)return Z.body(null,304,G);if(!X.userId)return Z.body(Y.decofile,200,{...G,"content-type":"application/json"});let J=H71({organizationId:X.organizationId,virtualMcpId:X.virtualMcpId,branch:X.branch});return Z.body(`{"version":${JSON.stringify(Y.sha)},"token":${JSON.stringify(J)},"apiHost":${JSON.stringify(Ec$(Z))},"decofile":${Y.decofile}}`,200,{...G,"content-type":"application/json"})}catch(Q){return Us(Z,Q)}}),$.get("/:virtualMcpId/:branch/meta",async(Z)=>{let X=Z.get("decofileScope"),Q=X.packagePath?`${X.packagePath}/.deco/meta.gen.json`:".deco/meta.gen.json";try{let Y=await Ns(Z),G=await Y.getFileTextAtRef(X.branch,Q);if(G===null){let J=await Y.getDefaultBranch();if(J!==X.branch)G=await Y.getFileTextAtRef(J,Q)}if(G===null)return Z.json({error:"meta.gen.json not committed"},404);return Z.body(G,200,{"content-type":"application/json","Cache-Control":"no-store","Access-Control-Allow-Origin":"*"})}catch(Y){return Us(Z,Y)}}),$.patch("/:virtualMcpId/:branch",QN6,async(Z)=>{let X=Z.get("decofileScope"),Q=Z.var.studioContext,Y=YN6.safeParse(await Z.req.json().catch(()=>null));if(!Y.success)return Z.json({error:"Invalid body",details:Y.error.issues},400);let G=Y.data;for(let J of[...Object.keys(G.set??{}),...G.delete??[]])try{eA0(J)}catch(W){let K=W instanceof Error?W.message:String(W);return Z.json({error:K},400)}for(let[J,W]of Object.entries(G.set??{})){if(typeof W!=="object"||W===null||Array.isArray(W))return Z.json({error:`Block "${J}" must be a JSON object`},400);if(aZ1(J))return Z.json({error:`Block key "${J}" collides with a framework resolver module and cannot be written`},400)}try{let J=await Ns(Z),W=await Kc$(`${X.organizationId}/${X.virtualMcpId}/${X.branch}`,{client:J,branch:X.branch,packagePath:X.packagePath,coAuthor:hu(Q)},G),K=H71({organizationId:X.organizationId,virtualMcpId:X.virtualMcpId,branch:X.branch});return Z.json({version:W,token:K,apiHost:Ec$(Z)})}catch(J){return Us(Z,J)}}),$.post("/:virtualMcpId/:branch/publish",async(Z)=>{let X=Z.get("decofileScope");try{let Q=await Ns(Z),Y=await Q.getDefaultBranch();if(Y===X.branch)return Z.json({error:"Branch is already the default branch"},400);let G=`chore(decofile): publish ${X.branch}`;try{let J;try{J=await Q.mergeBranch(Y,X.branch,G)}catch(W){if(!(W instanceof l4&&W.status===409))throw W;await NT0(Q,X.branch,Y),J=await Q.mergeBranch(Y,X.branch,G)}return J?Z.json({result:"merged",sha:J}):Z.json({result:"up-to-date"})}catch(J){if(J instanceof l4&&J.status===409)return Z.json({error:"merge-conflict"},409);if(J instanceof l4&&J.status===405){let K=await Q.findOpenPullRequest(Y,X.branch)??await Q.createPullRequest({base:Y,head:X.branch,title:`Publish ${X.branch}`});return Z.json({result:"pull-request",number:K.number,url:K.html_url})}throw J}}catch(Q){return Us(Z,Q)}}),$.get("/:virtualMcpId/:branch/status",async(Z)=>{let X=Z.get("decofileScope");try{let Q=await Ns(Z),Y=await Q.getDefaultBranch();if(Y===X.branch)return Z.json({baseBranch:Y,aheadBy:0,behindBy:0,lastCommitAt:null});try{let[{aheadBy:G,behindBy:J},W]=await Promise.all([Q.compare(Y,X.branch),Q.getBranchHead(X.branch)]);return Z.json({baseBranch:Y,aheadBy:G,behindBy:J,lastCommitAt:W.committedAt})}catch(G){if(G instanceof l4&&G.status===404)return Z.json({baseBranch:Y,aheadBy:0,behindBy:0,lastCommitAt:null});throw G}}catch(Q){return Us(Z,Q)}}),$}var $N6,Oc$=500,Dc$=1048576,wc$=1024,XN6=8388608,QN6,YN6,Lc$;var zc$=D(()=>{Sn0();$T0();Z8();yN();uZ1();aA0();W71();rZ1();Fc$();Bc$();J71();cD();KT0();$N6=/^[a-zA-Z0-9][a-zA-Z0-9/._-]*$/;QN6=_9({maxSize:XN6,onError:($)=>$.json({error:"Payload too large"},413)}),YN6=iu.object({set:iu.record(iu.string(),iu.unknown()).optional(),delete:iu.array(iu.string()).optional()}).refine(($)=>Object.keys($.set??{}).length>0||($.delete?.length??0)>0,{message:"Patch must set or delete at least one block"}).refine(($)=>Object.keys($.set??{}).length+($.delete?.length??0)<=Oc$,{message:`Patch cannot touch more than ${Oc$} blocks`}).refine(($)=>Object.values($.set??{}).every((Z)=>JSON.stringify(Z).length<=Dc$),{message:`Each block must be at most ${Dc$} bytes`}).refine(($)=>[...Object.keys($.set??{}),...$.delete??[]].every((Z)=>Z.length<=wc$),{message:`Each block key must be at most ${wc$} characters`}),Lc$=rA0(async($,Z)=>{let X=$.var.studioContext,Q=X.organization;if(!Q)return $.json({error:"Organization scope required"},500);let Y=$.req.param("virtualMcpId"),G=$.req.param("branch");if(!Y||!G)return $.json({error:"virtualMcpId and branch are required"},400);if(!ZN6(G))return $.json({error:`Invalid branch name: ${G}`},400);let J=X.auth?.user?.id??null;if(!J){let B=$.req.query("token");if(!($.req.method==="GET"&&!$.req.path.match(/\/(publish|status)$/)))return $.json({error:"Unauthorized"},401);if(!B||!Uc$(B,{organizationId:Q.id,virtualMcpId:Y,branch:G}))return $.json({error:"Unauthorized"},401)}let W=await X.storage.virtualMcps.findById(Y);if(!W||W.organization_id!==Q.id)return $.json({error:"Virtual MCP not found"},404);let K=W.metadata??null;if(!mO0(K))return $.json({error:"Project has no preview server configured"},404);let H=W.connections?.map((B)=>B.connection_id)??[],N=Fs(K,H);if(!N)return $.json({error:"Project has no GitHub repository"},404);let U=K?.runtime;return $.set("decofileScope",{organizationId:Q.id,virtualMcpId:Y,branch:G,packagePath:U?.path?.replace(/^\/+|\/+$/g,"")||null,githubRepo:N,userId:J}),Z()})});var Pc$=($)=>{let Z=new K1;if(Z.use("*",Zv),Z.route("/",HA0()),Z.route("/",yy$()),Z.route("/",du$()),Z.route("/",uu$()),Z.route("/",nA0()),Z.route("/tools",ru$()),Z.route("/",nu$()),Z.route("/",ju$({kvStorage:$.kvStorage})),Z.route("/",Lu$()),Z.route("/fs",vu$({getConnection:$.getNatsConnection})),Z.route("/sandbox",Jc$()),Z.route("/decofile",jc$()),Z.route("/",yu$()),Z.route("/deco-sites",UA0()),Z.route("/hosting",qy$()),Z.route("/monitor",vy$()),Z.route("/sso",YA0()),Z.route("/",tA0({tokenStorage:$.tokenStorage,automationEventDispatcher:$.automationEventDispatcher})),Z.route("/webhooks",Py$()),$.mountDevAssets)Z.route("/dev-assets",wA0({orgFromPath:!0}));return Z.use("/mcp/:connectionId?",$.mcpAuth),Z.use("/mcp/:connectionId/ui-resource",$.mcpAuth),Z.use("/mcp/gateway/:virtualMcpId?",$.mcpAuth),Z.use("/mcp/virtual-mcp/:virtualMcpId?",$.mcpAuth),Z.use("/mcp/self",$.mcpAuth),Z.use("/mcp/task-run/:threadId",$.mcpAuth),Z.route("/",pf$()),Z.get("/mcp/:gateway?/:connectionId/.well-known/oauth-protected-resource/*",$.betterAuthProtectedResourceHandler),Z.get("/mcp/.well-known/oauth-protected-resource",$.betterAuthProtectedResourceHandler),Z.route("/mcp/task-run",bu$()),Z.route("/mcp",FL0()),Z.route("/mcp/self",pA0()),Z.route("/mcp",UL0()),Z.all("/oauth-proxy/:connectionId/*",$.oauthProxyHandler),Z.get("/watch",$.watchHandler),Z};var Ac$=D(()=>{Z8();sP0();Ay$();H91();My$();fy$();LA0();Ca();G91();Eu$();zu$();fu$();vt();e51();BL0();vZ1();xu$();gu$();lu$();mu$();tu$();bZ1();au$();xZ1();HL0();Wc$();zc$()});function GN6($){return $.filter((Z)=>Z.vendors?.alias).map((Z)=>({name:Z.name,title:Z.title,description:Z.description,logo:Z.logo,category:Z.category,vendor:{alias:Z.vendors.alias,url:Z.vendors.url}}))}var JN6=async($,Z)=>{if(!$.get("studioContext").auth.user?.id)return $.json({error:"Unauthorized"},401);return Z()},Tc$=()=>{let $=new K1;return $.use("*",JN6),$.get("/",async(Z)=>{let X=_0(),Q=X.decoSupabaseUrl,Y=X.decoSupabaseServiceKey;if(!Q||!Y)return Z.json({apps:[]});try{let G=await DY(Q,Y,"apps?select=name,title,description,logo,category,vendors(alias,url)");return Z.json({apps:GN6(G)})}catch(G){return console.error("[deco-apps] GET error:",G),Z.json({error:"Failed to fetch apps"},502)}}),$};var Rc$=D(()=>{Z8();L$();QP0()});import{z as M1}from"zod";function AF($,Z="invalid_request_error",X=null,Q=null){return{error:{message:$,type:Z,param:X,code:Q}}}function wN6($){if(!$)return null;let Z=$.indexOf(":");if(Z===-1)return{credentialId:null,modelId:$};let X=$.substring(0,Z),Q=$.substring(Z+1);if(!X||!Q)return null;return{credentialId:X,modelId:Q}}function LN6($,Z,X){try{return JSON.parse($)}catch{throw new Mc$(`Invalid JSON in tool call arguments for function '${X}' (tool_call_id: ${Z}): ${$}`)}}function EN6($){let Z={};for(let X of $)if(X.role==="assistant"&&X.tool_calls)for(let Q of X.tool_calls)Z[Q.id]=Q.function.name;return $.map((X)=>{switch(X.role){case"system":return{role:"system",content:X.content};case"user":if(typeof X.content==="string")return{role:"user",content:X.content};return{role:"user",content:X.content.map((Y)=>{if(Y.type==="text")return{type:"text",text:Y.text};return{type:"image",image:Y.image_url.url}})};case"assistant":if(X.tool_calls&&X.tool_calls.length>0)return{role:"assistant",content:X.tool_calls.map((Y)=>({type:"tool-call",toolCallId:Y.id,toolName:Y.function.name,input:LN6(Y.function.arguments,Y.id,Y.function.name)}))};return{role:"assistant",content:X.content??""};case"tool":let Q=Z[X.tool_call_id]??"unknown";return{role:"tool",content:[{type:"tool-result",toolCallId:X.tool_call_id,toolName:Q,output:{type:"text",value:X.content}}]}}})}function jN6($){let Z=$.map((X)=>{let Q=X.function.parameters?pY(X.function.parameters):pY({type:"object",properties:{}});return[X.function.name,h$({description:X.function.description,inputSchema:Q})]});return Object.fromEntries(Z)}function zN6($){if(!$)return;return{openai:{response_format:$}}}function PN6(){return`chatcmpl-${crypto.randomUUID().replace(/-/g,"").substring(0,29)}`}function Ic$($,Z,X,Q,Y,G){let J={model:$,messages:Z,tools:X,temperature:Q.temperature,maxTokens:Q.max_tokens,topP:Q.top_p,frequencyPenalty:Q.frequency_penalty,presencePenalty:Q.presence_penalty,stopSequences:Q.stop?Array.isArray(Q.stop)?Q.stop:[Q.stop]:void 0,abortSignal:G};return Y?{...J,providerOptions:Y}:J}function qc$($){if($==="tool-calls")return"tool_calls";if($==="length")return"length";return"stop"}var WN6=256,KN6,FN6,HN6,NN6,UN6,BN6,ON6,DN6,Mc$,kc$,Vc$;var Sc$=D(()=>{m4();Z8();gu();TN();KN6=M1.object({type:M1.literal("function"),function:M1.object({name:M1.string(),description:M1.string().optional(),parameters:M1.record(M1.string(),M1.unknown()).optional()})}),FN6=M1.object({id:M1.string(),type:M1.literal("function"),function:M1.object({name:M1.string(),arguments:M1.string()})}),HN6=M1.discriminatedUnion("role",[M1.object({role:M1.literal("system"),content:M1.string(),name:M1.string().optional()}),M1.object({role:M1.literal("user"),content:M1.union([M1.string(),M1.array(M1.union([M1.object({type:M1.literal("text"),text:M1.string()}),M1.object({type:M1.literal("image_url"),image_url:M1.object({url:M1.string(),detail:M1.string().optional()})})]))]),name:M1.string().optional()}),M1.object({role:M1.literal("assistant"),content:M1.string().nullable().optional(),name:M1.string().optional(),tool_calls:M1.array(FN6).optional()}),M1.object({role:M1.literal("tool"),content:M1.string(),tool_call_id:M1.string()})]),NN6=M1.object({type:M1.literal("text")}),UN6=M1.object({type:M1.literal("json_object")}),BN6=M1.object({type:M1.literal("json_schema"),json_schema:M1.object({name:M1.string(),description:M1.string().optional(),schema:M1.record(M1.string(),M1.unknown()),strict:M1.boolean().optional()})}),ON6=M1.union([NN6,UN6,BN6]),DN6=M1.object({model:M1.string().describe("Format: 'model_id' or 'credential_id:model_id'"),messages:M1.array(HN6),stream:M1.boolean().optional().default(!1),temperature:M1.number().min(0).max(2).optional(),max_tokens:M1.number().positive().optional(),top_p:M1.number().min(0).max(1).optional(),frequency_penalty:M1.number().min(-2).max(2).optional(),presence_penalty:M1.number().min(-2).max(2).optional(),stop:M1.union([M1.string(),M1.array(M1.string())]).optional(),tools:M1.array(KN6).optional(),tool_choice:M1.union([M1.literal("auto"),M1.literal("none"),M1.literal("required"),M1.object({type:M1.literal("function"),function:M1.object({name:M1.string()})})]).optional(),response_format:ON6.optional(),user:M1.string().optional()});Mc$=class Mc$ extends Error{constructor($){super($);this.name="MessageConversionError"}};kc$=new K1;kc$.post("/:org/v1/chat/completions",async($)=>{let Z=$.get("studioContext"),X=$.req.param("org");try{if(!Z.auth.apiKey?.id)return $.json(AF("API key authentication required. Provide a valid API key via Authorization header.","authentication_error"),401);if(!Z.organization)return $.json(AF("Organization context is required. Ensure your API key has organization metadata.","invalid_request_error","organization"),400);if((Z.organization.slug??Z.organization.id)!==X)return $.json(AF("Organization mismatch. The API key's organization does not match the requested organization.","invalid_request_error","organization"),403);let Q=await $.req.json(),Y=DN6.safeParse(Q);if(!Y.success){let L=Y.error.issues[0]??{message:"Invalid request",path:[]};return $.json(AF(`Invalid request: ${L.message}`,"invalid_request_error",L.path.length>0?L.path.join("."):null),400)}let G=Y.data,J=wN6(G.model);if(!J)return $.json(AF("Invalid model format. Expected 'model_id' or 'credential_id:model_id' (e.g., 'claude-sonnet-4-6' or 'key_abc123:claude-sonnet-4-6')","invalid_request_error","model"),400);let{credentialId:W}=J,{modelId:K}=J;if(!W){let E=(await Z.storage.aiProviderKeys.list({organizationId:Z.organization.id})).find((j)=>GL(j.providerId));if(!E)return $.json(AF("No AI provider credentials configured for this organization. Add a credential in settings or specify one explicitly via 'credential_id:model_id'.","invalid_request_error","model"),400);W=E.id}let F;try{F=await Z.aiProviders.activate(W,Z.organization.id)}catch{return $.json(AF(`AI provider credential not found or inaccessible: ${W}`,"invalid_request_error","model"),404)}let H=F.aiSdk.languageModel(K),N=EN6(G.messages),U=G.tools?jN6(G.tools):void 0,B=zN6(G.response_format),O=PN6(),w=Math.floor(Date.now()/1000);if(G.stream)return iN($,async(L)=>{let E=Ic$(H,N,U,G,B,$.req.raw.signal);try{let j=AO(E),z=!1,P=0,A="",I=async()=>{if(A.length===0)return;let k=A;A="",await L.writeSSE({data:JSON.stringify({id:O,object:"chat.completion.chunk",created:w,model:G.model,choices:[{index:0,delta:{content:k},finish_reason:null}]})})};for await(let k of j.fullStream){if(!z&&(k.type==="text-delta"||k.type==="tool-call"))await L.writeSSE({data:JSON.stringify({id:O,object:"chat.completion.chunk",created:w,model:G.model,choices:[{index:0,delta:{role:"assistant",content:""},finish_reason:null}]})}),z=!0;if(k.type==="text-delta"){if(A+=k.text,A.length>=WN6)await I()}else if(k.type==="tool-call"){await I();let M=P++;await L.writeSSE({data:JSON.stringify({id:O,object:"chat.completion.chunk",created:w,model:G.model,choices:[{index:0,delta:{tool_calls:[{index:M,id:k.toolCallId,type:"function",function:{name:k.toolName,arguments:JSON.stringify(k.input)}}]},finish_reason:null}]})})}else if(k.type==="finish")await I(),await L.writeSSE({data:JSON.stringify({id:O,object:"chat.completion.chunk",created:w,model:G.model,choices:[{index:0,delta:{},finish_reason:qc$(k.finishReason)}],usage:k.totalUsage?{prompt_tokens:k.totalUsage.inputTokens??0,completion_tokens:k.totalUsage.outputTokens??0,total_tokens:k.totalUsage.totalTokens??0}:void 0})})}await I(),await L.writeSSE({data:"[DONE]"})}catch(j){let z=j;console.error("[openai-compat:stream] Error:",z.message),await L.writeSSE({data:JSON.stringify({error:{message:z.message,type:"server_error"}})})}});else{let L=Ic$(H,N,U,G,B,$.req.raw.signal),E=await zO(L),j={role:"assistant",content:E.text||null};if(E.toolCalls&&E.toolCalls.length>0)j.tool_calls=E.toolCalls.map((z)=>({id:z.toolCallId,type:"function",function:{name:z.toolName,arguments:JSON.stringify("input"in z?z.input:{})}})),j.content=null;return $.json({id:O,object:"chat.completion",created:w,model:G.model,choices:[{index:0,message:j,finish_reason:qc$(E.finishReason)}],usage:{prompt_tokens:E.usage?.inputTokens??0,completion_tokens:E.usage?.outputTokens??0,total_tokens:E.usage?.totalTokens??0}})}}catch(Q){let Y=Q;if(Y.name==="AbortError")return $.json(AF("Request aborted","invalid_request_error"),400);if(Y.name==="MessageConversionError")return $.json(AF(Y.message,"invalid_request_error","messages"),400);return console.error("[openai-compat] Error:",Y.message,Y.stack),$.json(AF(Y.message,"server_error"),500)}});Vc$=kc$});function AN6($){if(typeof $!=="object"||$===null)return!1;let X=$.githubRepo?.url;return typeof X==="string"&&X.length>0}function Cc$(){let $=new K1;return $.use("*",async(Z,X)=>{await X(),Z.header("Cache-Control","private, no-store"),Z.header("Vary","Cookie")}),$.get("/",async(Z)=>{let X=Z.get("studioContext"),Q=o0(X);if(!Q)return Z.json({error:"Authentication required"},401);let G=(Z.req.query("site")??"").trim().toLowerCase();if(!nX(G))return Z.json({error:"Invalid site slug"},400);let J=await X.db.selectFrom("member").innerJoin("organization","organization.id","member.organizationId").select(["organization.id as id","organization.slug as slug","organization.name as name","organization.metadata as metadata"]).where("member.userId","=",Q).execute(),W=[];for(let F of J){if(!F.slug||d9(F))continue;let H=await X.storage.virtualMcps.list(F.id);for(let N of H){if(ns1(N)!==G)continue;if(!AN6(N.metadata))continue;W.push({orgSlug:F.slug,orgName:F.name??F.slug,project:{id:N.id,title:N.title,icon:N.icon??null}})}}let K={matches:W};return Z.json(K)}),$}var _c$=D(()=>{Z8();VH()});var fc$;var vc$=D(()=>{fc$={name:"decocms",version:"4.321.4",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","db:migrate:dbos":"bun run ./dist/server/migrate-dbos.js",check:"tsc --noEmit",start:"bun run ./dist/server/server.js",migrate:"bun run src/database/migrate.ts","migrate:dbos":"bun run src/database/migrate-dbos.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","@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"}}});function IN6(){let $=process.env.POSTHOG_KEY;if(!$)return null;return{key:$,host:process.env.POSTHOG_HOST??RN6}}var bc$,RN6="https://ph.studio.decocms.com",xc$;var yc$=D(()=>{Z8();g50();yC();X9();L$();l51();vc$();bc$=new K1;bc$.get("/",($)=>{let Z={version:fc$.version,theme:Fi1(),...AH().logo&&{logo:AH().logo},...HN()&&{internalUrl:hC1()},..._0().enableDecoImport&&{enableDecoImport:!0},brandExtractEnabled:!!_0().firecrawlApiKey,hostingEnabled:!!_0().controlplaneRestUrl&&!!_0().controlplaneServiceToken,hostingControlPlaneGa:_0().hostingControlPlaneGa,monitorEnabled:!!_0().clickhouseAnalyticsUrl&&!!_0().clickhouseAnalyticsPassword,monitorGa:_0().monitorGa,auth:qx$(),posthog:IN6(),googleMapsApiKey:process.env.GOOGLE_MAPS_API_KEY?.trim()||null,runtime:{agentSandbox:zs()}};return $.header("Cache-Control","no-store"),$.json({success:!0,config:Z})});xc$=bc$});function pu($){let Z=($??"").trim().toLowerCase();return Z=Z.replace(/^https?:\/\//,""),Z=Z.replace(/^www\./,""),Z=Z.split(/[/?#]/)[0]??"",Z.replace(/\/+$/,"")}function N71($){return(pu($).split(".")[0]||$).replace(/[-_]/g," ").split(" ").filter(Boolean).map((X)=>X.charAt(0).toUpperCase()+X.slice(1)).join(" ")}function hc$($,Z=64){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(pu($))}&sz=${Z}`}function gc$($,Z){let X=$.trim();if(X.length<=Z)return X;let Q=X.slice(0,Z-1),Y=Q.lastIndexOf(" ");return`${(Y>Z*0.6?Q.slice(0,Y):Q).trimEnd()}\u2026`}function uc$($){let{brand:Z,domain:X,score:Q,verdict:Y}=$,G=typeof Q==="number"?`${Z} commerce report \u2014 ${Math.round(Q)}/100 \xB7 decocms`:`${Z} commerce report \xB7 decocms`,J=`See the full ${Z} scorecard \u2014 SEO, performance, conversion & AEO signals scored by decocms.`,W=Y?.trim()?gc$(`${Y.trim().replace(/\s+/g," ")} \u2014 ${J}`,200):gc$(`How does ${X} really perform? ${J}`,200);return{title:G,description:W}}import{z as c0}from"zod";var wv,qN6,MN6,kN6,VN6,lc$;var cc$=D(()=>{wv=c0.enum(["good","bad","neutral"]),qN6=c0.preprocess(($)=>{if(Array.isArray($))return{kind:"text",value:$.find((X)=>X!==null&&typeof X!=="object")??""};return $!==null&&typeof $==="object"?$:{kind:"text",value:$}},c0.object({kind:c0.enum(["text","number","sparkline","badge","score"]).catch("text"),value:c0.coerce.string().optional(),tone:wv.optional(),muted:c0.boolean().optional(),delta:c0.coerce.string().optional(),deltaDir:c0.enum(["up","down","neutral"]).optional(),points:c0.array(c0.coerce.number()).optional(),label:c0.coerce.string().optional()}).transform(($)=>{if($.kind==="badge"&&$.label==null)$.label=$.value??"";if($.kind==="score"){let Z=Number($.value);if(Number.isNaN(Z))return{...$,kind:"text"}}return $})),MN6=c0.preprocess(($)=>{let Z=$;if(Z&&typeof Z==="object"&&!Array.isArray(Z)&&Array.isArray(Z.cells))Z=Z.cells;if(Array.isArray(Z)&&Z.length===1&&Array.isArray(Z[0]))Z=Z[0];if(Array.isArray(Z))return Z;if(Z&&typeof Z==="object")return Object.values(Z);return Z},c0.array(qN6)),kN6={key:c0.coerce.string(),title:c0.coerce.string(),eyebrow:c0.coerce.string().optional(),headline:c0.coerce.string(),annotation:c0.coerce.string().optional(),methodology:c0.coerce.string().optional(),sources:c0.array(c0.object({name:c0.coerce.string(),logoUrl:c0.coerce.string()})).optional()},VN6=c0.discriminatedUnion("template",[c0.object({template:c0.literal("cover"),score:c0.object({value:c0.coerce.number(),max:c0.coerce.number().optional(),grade:c0.coerce.string().optional(),label:c0.coerce.string().optional()}).optional(),brandImage:c0.coerce.string().optional(),screenshot:c0.coerce.string().optional(),mobileScreenshot:c0.coerce.string().optional()}),c0.object({template:c0.literal("cta"),ctaUrl:c0.coerce.string().optional(),ctaLabel:c0.coerce.string().optional(),bullets:c0.array(c0.coerce.string()).optional()}),c0.object({template:c0.literal("series"),points:c0.array(c0.coerce.number()).min(2),xLabels:c0.array(c0.coerce.string()).min(1),unit:c0.coerce.string().optional(),callout:c0.object({index:c0.coerce.number(),value:c0.coerce.string(),tone:wv.optional()})}),c0.object({template:c0.literal("threshold"),value:c0.coerce.string().default(""),metricLabel:c0.coerce.string().optional(),ratio:c0.coerce.number(),thresholdRatio:c0.coerce.number().optional(),thresholdLabel:c0.coerce.string().default(""),tone:wv.optional()}),c0.object({template:c0.literal("stats"),stats:c0.array(c0.object({value:c0.coerce.string(),label:c0.coerce.string(),tone:wv.optional()})).min(1)}),c0.object({template:c0.literal("bars"),items:c0.array(c0.object({value:c0.coerce.string(),label:c0.coerce.string(),ratio:c0.coerce.number(),tone:wv.optional()})).min(1)}),c0.object({template:c0.literal("gauges"),gauges:c0.array(c0.object({label:c0.coerce.string(),value:c0.coerce.string(),status:c0.enum(["good","warn","bad"]).catch("warn"),caption:c0.coerce.string().optional(),ratio:c0.coerce.number().optional()})).min(1)}),c0.object({template:c0.literal("checklist"),checks:c0.array(c0.object({label:c0.coerce.string(),status:c0.enum(["pass","fail","warn"]).catch("fail"),value:c0.coerce.string().optional()})).min(1)}),c0.object({template:c0.literal("table"),columns:c0.array(c0.object({label:c0.coerce.string(),align:c0.enum(["left","right"]).optional()})).min(1),rows:c0.array(MN6).min(1),highlightRow:c0.coerce.number().optional()}),c0.object({template:c0.literal("products"),products:c0.array(c0.object({name:c0.coerce.string(),price:c0.coerce.string().optional(),image:c0.coerce.string().optional(),url:c0.coerce.string().optional()})).min(1)}),c0.object({template:c0.literal("list"),entries:c0.array(c0.object({label:c0.coerce.string(),severity:c0.enum(["error","warning","notice"]).catch("notice")})).min(1),moreCount:c0.coerce.number().optional()}),c0.object({template:c0.literal("keywords"),volumeLabel:c0.coerce.string().optional(),keywords:c0.array(c0.object({term:c0.coerce.string(),volume:c0.coerce.string(),position:c0.coerce.number().catch(0)})).min(1)}),c0.object({template:c0.literal("competitor"),metricLabel:c0.coerce.string().optional(),competitors:c0.array(c0.object({name:c0.coerce.string(),value:c0.coerce.string(),tone:wv.optional(),isYou:c0.boolean().optional()})).min(1)}),c0.object({template:c0.literal("scorecard"),rivalLabel:c0.coerce.string().optional(),dimensions:c0.array(c0.object({label:c0.coerce.string(),you:c0.coerce.string(),rival:c0.coerce.string().optional(),rivalName:c0.coerce.string().optional(),tone:wv.optional()})).min(1)})]),lc$=c0.object({...kN6,template:VN6})});function DT0($){let Z=[],X=[...$.sections].sort((Y,G)=>Y.position-G.position).map((Y)=>{let G=lc$.safeParse(Y.props);if(G.success)return G.data;let J=G.error.issues[0];return Z.push({section_type:Y.section_type,position:Y.position,reason:J?`${J.path.join(".")||"(root)"}: ${J.message}`:"contract violation"}),null}).filter((Y)=>Y!==null),Q=X.filter((Y)=>Y.template.template!=="cover"&&Y.template.template!=="cta").map((Y)=>({key:Y.key,title:Y.title}));return{deck:{meta:{...$.meta,scores:$.summary?.scores,scannedAt:$.scanned_at,toc:Q},slides:X},drops:Z}}var U71=D(()=>{cc$()});import{join as dc$}from"path";async function CN6($){try{let Z=await fetch(`${KK({})}/api/v2/public/diagnostics/${encodeURIComponent($)}`,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(SN6)});if(!Z.ok)return null;let X=await Z.json(),{deck:Q}=DT0(X);if(!Q.slides.length)return null;let Y=Q.slides.find((W)=>W.template.template==="cover"),G=Y?.template,J=G&&G.template==="cover"?G:void 0;return{brand:Q.meta.brand?.trim()||N71($),score:Q.meta.scores?.cover??J?.score?.value,verdict:Y?.annotation?.trim()||Y?.headline?.trim()||void 0}}catch{return null}}function EG($){return $.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;")}function _N6($,Z){let X=pu($),Q=Z?.brand?.trim()||N71(X),Y=hc$(X,128),J=`${(_0().baseUrl??"https://studio.decocms.com").replace(/\/+$/,"")}/report/${encodeURIComponent(X)}`,{title:W,description:K}=uc$({brand:Q,domain:X,score:Z?.score,verdict:Z?.verdict}),F=`${J}/og.png`,H=`${Q} commerce report by decocms`;return[`<title>${EG(W)}</title>`,`<meta name="description" content="${EG(K)}" />`,'<meta name="robots" content="noindex, follow" />','<meta property="og:type" content="website" />','<meta property="og:site_name" content="decocms" />',`<meta property="og:title" content="${EG(W)}" />`,`<meta property="og:description" content="${EG(K)}" />`,`<meta property="og:url" content="${EG(J)}" />`,`<meta property="og:image" content="${EG(F)}" />`,'<meta property="og:image:width" content="1200" />','<meta property="og:image:height" content="630" />',`<meta property="og:image:alt" content="${EG(H)}" />`,'<meta name="twitter:card" content="summary_large_image" />',`<meta name="twitter:title" content="${EG(W)}" />`,`<meta name="twitter:description" content="${EG(K)}" />`,`<meta name="twitter:image" content="${EG(F)}" />`,`<meta name="twitter:image:alt" content="${EG(H)}" />`,`<link rel="canonical" href="${EG(J)}" />`,`<link rel="icon" href="${EG(Y)}" sizes="any" />`].join(`
2951
2951
  `)}function vN6($,Z){return $.replace(/<title>[\s\S]*?<\/title>\s*/i,"").replace(/<meta\s+name="(?:description|twitter:[^"]*)"[^>]*>\s*/gi,"").replace(/<meta\s+property="og:[^"]*"[^>]*>\s*/gi,"").replace(/<link\s+rel="icon"[^>]*>\s*/gi,"").replace("</head>",` ${Z}
2952
2952
  </head>`)}function mc$($){let Z=new K1;return Z.get("/:domain/og.png",async(X)=>{let Q=pu(X.req.param("domain")),Y=async()=>{let G=$?Bun.file(dc$($,"report-og-fallback.png")):null;if(!G||!await G.exists())return X.notFound();return X.body(new Uint8Array(await G.arrayBuffer()),200,{"Content-Type":"image/png","Cache-Control":"public, max-age=0, s-maxage=3600"})};try{let G=await fetch(`${KK({})}/api/v2/public/diagnostics/${encodeURIComponent(Q)}/og.png`,{signal:AbortSignal.timeout(fN6)}),J=G.headers.get("content-type")??"";if(!G.ok||!J.startsWith("image/")||!G.body)return Y();return X.body(G.body,200,{"Content-Type":J,"Cache-Control":"public, max-age=0, s-maxage=604800"})}catch{return Y()}}),Z.get("/:domain",async(X)=>{let Q=X.req.param("domain"),Y=$?dc$($,"index.html"):null,G=Y?Bun.file(Y):null;if(!G||!await G.exists())return X.notFound();let J=await G.text();try{let W=await CN6(pu(Q)),K=_N6(Q,W);return X.html(vN6(J,K),200,{"Cache-Control":"public, max-age=0, s-maxage=300"})}catch{return X.html(J)}}),Z}var SN6=2500,fN6=1e4;var ic$=D(()=>{Z8();U71();HE();L$()});function Bs($,Z){return fetch(`${KK({})}${$}`,Z)}async function bN6($,Z,X){let Q=new URLSearchParams;if(Z)Q.set("pw",Z);if(X)Q.set("lang",X);let Y=Q.toString()?`?${Q.toString()}`:"",G=await Bs(`/api/v2/public/diagnostics/${encodeURIComponent($)}${Y}`,{headers:{Accept:"application/json"}});if(G.status===404)return{status:"not_found",deck:null,scanned_at:null,drops:[]};if(!G.ok)throw Error(`report read HTTP ${G.status}`);let J=await G.json(),{deck:W,drops:K}=DT0(J);return{status:W.slides.length?"ready":"empty",deck:W,scanned_at:J.scanned_at,drops:K}}var xN6,nN,pc$=async($,Z)=>{if(!$.get("reportUser"))return $.json({error:"Authentication required"},401);await Z();return},nc$;var tc$=D(()=>{Z8();cY();HE();U71();xN6=new Set(["complete","errored","terminated","unknown"]),nN=new K1;nN.use("*",async($,Z)=>{let X=await a$.api.getSession({headers:$.req.raw.headers});$.set("reportUser",X?.user?.id?{email:X.user.email}:void 0),await Z(),$.header("Cache-Control","private, no-store"),$.header("Vary","Cookie");return});nN.use("/link-token/*",pc$);nN.use("/suggest",pc$);nN.get("/site/:domain",async($)=>{let Z=$.req.param("domain").trim();if(!Z)return $.json({error:"domain is required"},400);let X=$.get("reportUser"),Q=$.req.query("key")?.trim()||void 0,Y=$.req.query("lang")?.trim()||void 0;try{let G=await bN6(Z,Q,Y);if($.header("Cache-Control","private, no-store"),X||!G.deck)return $.json(G);return $.json({...G,deck:{...G.deck,slides:G.deck.slides.slice(0,1)},truncated:G.status==="ready"})}catch{return $.json({error:"report read failed"},502)}});nN.post("/run",async($)=>{let Z=$.get("reportUser"),X;try{X=await $.req.json()}catch{return $.json({error:"invalid JSON"},400)}let Q=typeof X.domain==="string"?X.domain.trim():"";if(!Q)return $.json({error:"domain is required"},400);let Y=Z?.email,G=typeof X.distinctId==="string"&&X.distinctId.trim()&&X.distinctId.length<=200?X.distinctId.trim():void 0;try{let J=await Bs("/api/v2/diagnostics/run",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${FE({})}`},body:JSON.stringify({url:Q,...Y?{email:Y}:{},distinct_id:G})});if(!J.ok)return $.json({error:`run HTTP ${J.status}`},502);let W=await J.json(),K=W.blocked?{state:"blocked"}:W.status==="fresh"?{state:"fresh"}:W.mode==="sync"?{state:"sync"}:{state:"running",id:W.id??null};return $.json(K)}catch{return $.json({error:"run failed"},502)}});nN.get("/status",async($)=>{let Z=$.req.query("id");if(!Z)return $.json({error:"id is required"},400);try{let X=await Bs(`/api/v2/diagnostics/status?id=${encodeURIComponent(Z)}`,{headers:{Authorization:`Bearer ${FE({})}`}});if(!X.ok)return $.json({error:`status HTTP ${X.status}`},502);let Y=(await X.json()).status??"unknown",G={done:xN6.has(Y),status:Y};return $.json(G)}catch{return $.json({error:"status failed"},502)}});nN.get("/link-token/:id",async($)=>{let Z=$.req.param("id");try{let X=await Bs(`/api/v2/public/link-tokens/${encodeURIComponent(Z)}`,{headers:{Accept:"application/json"}});if(X.status===404)return $.json(null);if(!X.ok)return $.json({error:`link token HTTP ${X.status}`},502);return $.json(await X.json())}catch{return $.json({error:"link token resolve failed"},502)}});nN.get("/suggest",async($)=>{let Z=($.req.query("q")??"").trim().slice(0,64);if(Z.length<2)return $.json({suggestions:[]});try{let X=await Bs(`/api/v2/public/suggest?q=${encodeURIComponent(Z)}`,{headers:{Accept:"application/json"}});if(!X.ok)return $.json({suggestions:[]});let Q=await X.json();return $.json({suggestions:Array.isArray(Q.suggestions)?Q.suggestions:[]})}catch{return $.json({suggestions:[]})}});nc$=nN});import{createHmac as yN6,timingSafeEqual as gN6}from"crypto";function rc$($,Z,X,Q=Date.now()){if(!Z||!X)return!1;let Y,G=[];for(let F of Z.split(",")){let H=F.indexOf("=");if(H<=0)continue;let N=F.slice(0,H).trim(),U=F.slice(H+1).trim();if(N==="t")Y=U;else if(N==="v1")G.push(U)}if(!Y||G.length===0)return!1;let J=Number(Y);if(!Number.isFinite(J)||Math.abs(Q/1000-J)>hN6)return!1;let W=yN6("sha256",X).update(`${Y}.${$}`).digest("hex"),K=Buffer.from(W,"hex");return G.some((F)=>{let H=Buffer.from(F,"hex");return K.length===H.length&&gN6(K,H)})}function ac$($){let Z;try{Z=JSON.parse($)}catch{return null}let X=bJ(Z),Q=bJ(bJ(X?.data)?.object);if(!X||typeof X.type!=="string"||!Q)return null;return{id:TF(X.id),type:X.type,created:typeof X.created==="number"?X.created:void 0,livemode:typeof X.livemode==="boolean"?X.livemode:void 0,data:{object:Q}}}function sc$($){switch($){case"active":case"trialing":return"active";case"past_due":return"past_due";default:return"canceled"}}function TF($){return typeof $==="string"?$:void 0}function bJ($){return typeof $==="object"&&$!==null?$:void 0}function wT0($){return typeof $==="number"?new Date($*1000):null}function D71($){return TF($)??TF(bJ($)?.id)}function uN6($){return D71($.subscription)??TF(bJ(bJ($.parent)?.subscription_details)?.subscription)}function lN6($){let Z=wT0($.current_period_end);if(Z)return Z;let X=bJ($.items)?.data;if(!Array.isArray(X))return null;let Q=0;for(let Y of X){let G=bJ(Y)?.current_period_end;if(typeof G==="number"&&G>Q)Q=G}return Q>0?new Date(Q*1000):null}function B71($,Z){let X=wT0($.created);return!!X&&!!Z.lastStripeEventAt&&X<Z.lastStripeEventAt}function O71($,Z){let X=wT0($.created);if(!X)return;return Z.lastStripeEventAt&&Z.lastStripeEventAt>X?void 0:X}async function cN6($,Z){let X=Z.data.object;switch(Z.type){case"checkout.session.completed":case"checkout.session.async_payment_succeeded":{let Q=TF(bJ(X.metadata)?.orgId);if(!Q)return{handled:!1,reason:"no orgId"};if(TF(bJ(X.metadata)?.kind)==="topup"){if(X.mode!=="payment")return{handled:!1,reason:"topup with wrong mode"};if(TF(X.payment_status)!=="paid")return{handled:!1,reason:"payment not confirmed"};let J=TF(X.id);if(!J)return console.error("stripe webhook: topup session without id",{eventId:Z.id,organizationId:Q}),{handled:!1,reason:"topup session without id"};let W=Number(bJ(X.metadata)?.creditCents);if(!Number.isInteger(W)||W<=0)return console.error("stripe webhook: paid topup with bad metadata \u2014 credit NOT applied",{eventId:Z.id,organizationId:Q,creditCents:bJ(X.metadata)?.creditCents}),{handled:!1,reason:"bad topup metadata"};return{handled:!0,organizationId:Q,topUp:{creditCents:W,referenceId:`stripe-topup:${J}`}}}if(X.mode!=="subscription")return{handled:!1,reason:"not a subscription checkout"};if(TF(X.payment_status)!=="paid")return{handled:!1,reason:"payment not confirmed"};let Y=await $.getBilling(Q);if(!Y)return{handled:!1,reason:"unknown org"};let G=D71(X.subscription);if(Y.stripeSubscriptionId&&G&&Y.stripeSubscriptionId!==G)return console.error("stripe webhook: refused checkout rebind",{organizationId:Q,eventId:Z.id}),{handled:!1,reason:"org already bound to another subscription",orphanSubscriptionId:G};if(B71(Z,Y))return{handled:!1,reason:"stale event"};return await $.updateStripeState(Q,{stripeCustomerId:D71(X.customer),stripeSubscriptionId:G,status:"active",lastStripeEventAt:O71(Z,Y)}),{handled:!0,organizationId:Q}}case"customer.subscription.updated":case"customer.subscription.deleted":{let Q=TF(X.id);if(!Q)return{handled:!1,reason:"no sub id"};let Y=await $.getBillingByStripeSubscriptionId(Q);if(!Y)return{handled:!1,reason:"unknown subscription"};let G=Z.type==="customer.subscription.deleted";if(!G&&B71(Z,Y))return{handled:!1,reason:"stale event"};let J=G?"canceled":sc$(X.status);return await $.updateStripeState(Y.organizationId,{status:J,currentPeriodEnd:lN6(X),...G&&{stripeSubscriptionId:null},lastStripeEventAt:O71(Z,Y)}),{handled:!0,organizationId:Y.organizationId}}case"invoice.paid":{let Q=uN6(X);if(!Q)return{handled:!1,reason:"no sub id"};let Y=await $.getBillingByStripeSubscriptionId(Q);if(!Y)return{handled:!1,reason:"unknown subscription"};if(B71(Z,Y))return{handled:!1,reason:"stale event"};return await $.updateStripeState(Y.organizationId,{status:"active",currentPeriodEnd:wT0(X.period_end),lastStripeEventAt:O71(Z,Y)}),{handled:!0,organizationId:Y.organizationId}}default:return{handled:!1,reason:`unhandled event ${Z.type}`}}}function dN6($,Z){if(!Z.handled||$.livemode===!1)return null;let X=$.data.object;if(Z.topUp)return{name:"credits_topup_succeeded",organizationId:Z.organizationId,properties:{credit_cents:Z.topUp.creditCents}};switch($.type){case"checkout.session.completed":case"checkout.session.async_payment_succeeded":return{name:"subscription_started",organizationId:Z.organizationId,properties:{}};case"customer.subscription.deleted":return{name:"subscription_canceled",organizationId:Z.organizationId,properties:{}};case"customer.subscription.updated":return{name:"subscription_updated",organizationId:Z.organizationId,properties:{status:sc$(X.status),...typeof X.cancel_at_period_end==="boolean"?{cancel_at_period_end:X.cancel_at_period_end}:{}}};case"invoice.paid":if(X.billing_reason==="subscription_create")return null;return{name:"subscription_renewed",organizationId:Z.organizationId,properties:{}};default:return null}}function oc$($,Z){let X=dN6($,Z);if(!X)return;gY({event:X.name,organizationId:X.organizationId,...$.id?{uuid:Ln1(`stripe:${$.id}:${X.name}`)}:{},...$.created?{timestamp:new Date($.created*1000)}:{},properties:X.properties})}async function ec$($){let Z=new YK(U8().db),X=await cN6(Z,$);if(!(X.handled&&X.topUp))oc$($,X);if(X.handled&&X.topUp)await rL$({organizationId:X.organizationId,amountCents:X.topUp.creditCents,referenceId:X.topUp.referenceId}),oc$($,X);if(!X.handled&&X.orphanSubscriptionId)try{await ie1(X.orphanSubscriptionId),console.error("stripe webhook: canceled orphan subscription",{subscriptionId:X.orphanSubscriptionId,eventId:$.id})}catch(Q){if(!(Q instanceof dY&&(Q.status===400||Q.status===404)))throw Q}return X}var hN6=300;var $d$=D(()=>{mG();_4();L50();AE();O01()});var mN6=1048576,w71;var Zd$=D(()=>{Z8();yN();L$();$d$();w71=new K1;w71.post("/webhook",_9({maxSize:mN6,onError:($)=>$.json({error:"payload too large"},413)}),async($)=>{let Z=_0().stripeWebhookSecret;if(!Z)return $.json({error:"stripe billing not configured"},503);let X=await $.req.text();if(!rc$(X,$.req.header("stripe-signature"),Z))return $.json({error:"invalid signature"},400);let Y=ac$(X);if(!Y)return $.json({error:"invalid payload"},400);let G=await ec$(Y);return console.log("stripe webhook",{eventId:Y.id,type:Y.type,livemode:Y.livemode,...G}),$.json({received:!0})})});import{timingSafeEqual as iN6}from"crypto";function nN6($,Z,X){if(!Z?.startsWith("sha256="))return!1;let Q=new Bun.CryptoHasher("sha256",X).update($).digest("hex"),Y=Z.slice(7);if(Y.length!==Q.length)return!1;return iN6(Buffer.from(Y),Buffer.from(Q))}var pN6=5242880,L71;var Xd$=D(()=>{Z8();yN();m3();L71=new K1;L71.post("/webhook",_9({maxSize:pN6,onError:($)=>$.json({error:"payload too large"},413)}),async($)=>{let Z=process.env.GITHUB_WEBHOOK_SECRET;if(!Z)return $.json({error:"github webhook not configured"},503);let X=await $.req.text();if(!nN6(X,$.req.header("x-hub-signature-256"),Z))return $.json({error:"invalid signature"},400);if($.req.header("x-github-event")!=="push")return $.json({ok:!0,ignored:"event"});let Q;try{Q=JSON.parse(X)}catch{return $.json({error:"invalid payload"},400)}let Y=Q.ref,G=Q.repository?.full_name;if(!Y||!G)return $.json({ok:!0,ignored:"shape"});let W=(await kn0())?.markTenantPoolsDirty(G,Y)??[];return $.json({ok:!0,pools:W})})});function Qd$($,Z){if(Z.startsWith("text/html")||Z.startsWith("image/svg"))$.set("Content-Security-Policy","sandbox allow-scripts allow-modals allow-same-origin")}var Yd$,tN6,oN6,Gd$;var Jd$=D(()=>{Z8();P3();Bg();LE();Yd$=new K1,tN6=["range","if-none-match","if-modified-since"],oN6=["content-type","content-length","content-range","accept-ranges","etag","last-modified"];Yd$.get("/:org/files/*",async($)=>{let Z=$.get("studioContext"),X=Z.organization?.id;if(!Z.auth?.user?.id){if(Lu($))return $.redirect(`/login?next=${encodeURIComponent($.req.path)}`,302);throw new Z$(401,{message:"Authentication required"})}if(!X)throw new Z$(401,{message:"Organization context required"});let Q=$.req.path.replace(/^.*\/files\//,"");if(!Q)throw new Z$(400,{message:"Missing file key"});let Y=await Yt(Q,Z);if(!Y)throw new Z$(503,{message:"Object storage not configured"});if(Y.startsWith("data:")&&vQ()){let K=Y.match(/^data:([^;]+);base64,(.+)$/s);if(!K)throw new Z$(500,{message:"Invalid data URL from storage"});let[,F,H]=K,N=Buffer.from(H,"base64"),U=new Headers({"Content-Type":F,"Cache-Control":"private, max-age=86400"});return Qd$(U,F),new Response(N,{status:200,headers:U})}let G=new Headers;for(let K of tN6){let F=$.req.header(K);if(F)G.set(K,F)}let J=await fetch(Y,{headers:G});if(J.status===403||J.status===404)throw new Z$(404,{message:"File not found"});if(!J.ok&&J.status!==304&&J.status!==416)throw console.error(`[files] upstream storage error ${J.status} for key:`,Q),new Z$(502,{message:"Upstream storage error"});let W=new Headers;for(let K of oN6){let F=J.headers.get(K);if(F)W.set(K,F)}return W.set("Cache-Control","private, max-age=86400"),Qd$(W,W.get("content-type")??""),new Response(J.body,{status:J.status,headers:W})});Gd$=Yd$});var Os=_((Lv)=>{var rN6=Lv&&Lv.__createBinding||(Object.create?function($,Z,X,Q){if(Q===void 0)Q=X;var Y=Object.getOwnPropertyDescriptor(Z,X);if(!Y||("get"in Y?!Z.__esModule:Y.writable||Y.configurable))Y={enumerable:!0,get:function(){return Z[X]}};Object.defineProperty($,Q,Y)}:function($,Z,X,Q){if(Q===void 0)Q=X;$[Q]=Z[X]}),aN6=Lv&&Lv.__exportStar||function($,Z){for(var X in $)if(X!=="default"&&!Object.prototype.hasOwnProperty.call(Z,X))rN6(Z,$,X)};Object.defineProperty(Lv,"__esModule",{value:!0});aN6(RY(),Lv)});var Fd$=_((Wd$)=>{Object.defineProperty(Wd$,"__esModule",{value:!0});Wd$.version=void 0;Wd$.version="3.4.0"});var Ud$=_((RF)=>{var sN6=RF&&RF.__importDefault||function($){return $&&$.__esModule?$:{default:$}};Object.defineProperty(RF,"__esModule",{value:!0});RF.NodeTransport=RF.VERSION=void 0;RF.nodeResolveHost=YU6;var Z5=Os(),eN6=P0("net"),E71=P0("tls"),$U6=P0("path"),Hd$=P0("fs"),ZU6=sN6(P0("dns")),XU6=Fd$();RF.VERSION=XU6.version;var QU6="nats.js";class Nd${socket;version;lang;yields=[];signal=(0,Z5.deferred)();closedNotification=(0,Z5.deferred)();options;connected=!1;tlsName="";done=!1;closeError;constructor(){this.lang=QU6,this.version=RF.VERSION}async connect($,Z){this.tlsName=$.tlsName,this.options=Z;let{tls:X}=this.options,{handshakeFirst:Q}=X||{};try{if(Q===!0)this.socket=await this.tlsFirst($);else this.socket=await this.dial($);if(this.done)this.socket?.destroy();let Y=await this.peekInfo();(0,Z5.checkOptions)(Y,Z);let{tls_required:G,tls_available:J}=Y,W=J===!0&&Z.tls!==null;if(!Q&&(G||W))this.socket=await this.startTLS();if(this.done)this.socket?.destroy();if(G&&this.socket.encrypted!==!0)throw Z5.errors.InvalidArgumentError.format("tls","is not available on this server");return this.connected=!0,this.setupHandlers(),this.signal.resolve(),Promise.resolve()}catch(Y){let G=Y;if(!G)G=new Z5.errors.ConnectionError("error connecting - node provided an undefined error");let{code:J}=G,W=J==="ECONNREFUSED"?new Z5.errors.ConnectionError("connection refused",{cause:G}):G;throw this.socket?.destroy(),W}}dial($){let Z=(0,Z5.deferred)(),X,Q=(0,eN6.createConnection)($.port,$.hostname,()=>{Z.resolve(Q),Q.removeAllListeners()});return Q.on("error",(Y)=>{X=Y}),Q.on("close",()=>{Q.removeAllListeners(),Z.reject(X)}),Q.setNoDelay(!0),Z}get isClosed(){return this.done}close($){return this._closed($,!1)}peekInfo(){let $=(0,Z5.deferred)(),Z;return this.socket.on("data",(X)=>{this.yields.push(X);let Q=Z5.DataBuffer.concat(...this.yields),Y=(0,Z5.extractProtocolMessage)(Q);if(Y!=="")try{let G=Z5.INFO.exec(Y);if(!G)throw Error("unexpected response from server");let J=JSON.parse(G[1]);$.resolve(J)}catch(G){$.reject(G)}finally{this.socket.removeAllListeners()}}),this.socket.on("error",(X)=>{Z=X}),this.socket.on("close",()=>{this.socket.removeAllListeners(),$.reject(Z)}),$}loadFile($){if(!$)return Promise.resolve();let Z=(0,Z5.deferred)();try{if($=(0,$U6.resolve)($),!(0,Hd$.existsSync)($))Z.reject(Error(`${$} doesn't exist`));(0,Hd$.readFile)($,(X,Q)=>{if(X)return Z.reject(X);Z.resolve(Q)})}catch(X){Z.reject(X)}return Z}async loadClientCerts(){let $={},{certFile:Z,cert:X,caFile:Q,ca:Y,keyFile:G,key:J}=this.options.tls;try{if(Z){let W=await this.loadFile(Z);if(W)$.cert=W}else if(X)$.cert=X;if(G){let W=await this.loadFile(G);if(W)$.key=W}else if(J)$.key=J;if(Q){let W=await this.loadFile(Q);if(W)$.ca=[W]}else if(Y)$.ca=Y;return Promise.resolve($)}catch(W){return Promise.reject(W)}}async tlsFirst($){let Z,X={servername:this.tlsName,rejectUnauthorized:!0};if(this.socket)X.socket=this.socket;if(typeof this.options.tls==="object")try{let Y=await this.loadClientCerts()||{};X=(0,Z5.extend)(X,this.options.tls,Y)}catch(Y){return Promise.reject(new Z5.errors.ConnectionError(Y.message,{cause:Y}))}let Q=(0,Z5.deferred)();try{let Y=(0,E71.connect)($.port,$.hostname,X,()=>{Y.removeAllListeners(),Q.resolve(Y)});Y.on("error",(G)=>{Z=G}),Y.on("secureConnect",()=>{if(X.rejectUnauthorized===!1)return;if(!Y.authorized)throw Y.authorizationError}),Y.on("close",()=>{Q.reject(Z),Y.removeAllListeners()}),Y.setNoDelay(!0)}catch(Y){Q.reject(new Z5.errors.ConnectionError(Y.message,{cause:Y}))}return Q}async startTLS(){let $,Z={socket:this.socket,servername:this.tlsName,rejectUnauthorized:!0};if(typeof this.options.tls==="object")try{let Q=await this.loadClientCerts()||{};Z=(0,Z5.extend)(Z,this.options.tls,Q)}catch(Q){return Promise.reject(new Z5.errors.ConnectionError(Q.message,{cause:Q}))}let X=(0,Z5.deferred)();try{let Q=(0,E71.connect)(Z,()=>{Q.removeAllListeners(),X.resolve(Q)});Q.on("error",(Y)=>{$=Y}),Q.on("secureConnect",()=>{if(Z.rejectUnauthorized===!1)return;if(!Q.authorized)throw Q.authorizationError}),Q.on("close",()=>{X.reject($),Q.removeAllListeners()})}catch(Q){X.reject(new Z5.errors.ConnectionError(Q.message,{cause:Q}))}return X}setupHandlers(){let $;this.socket.on("data",(Z)=>{return this.yields.push(Z),this.signal.resolve()}),this.socket.on("error",(Z)=>{$=Z}),this.socket.on("end",()=>{if(this.socket?.destroyed)return;this.socket?.write(new Uint8Array(0),()=>{this.socket?.end()})}),this.socket.on("close",()=>{this._closed($,!1)})}[Symbol.asyncIterator](){return this.iterate()}async*iterate(){while(!0){if(this.yields.length===0)await this.signal;let $=this.yields;this.yields=[];for(let Z=0;Z<$.length;Z++){if(this.options.debug)console.info(`> ${(0,Z5.render)($[Z])}`);yield $[Z]}if(this.done)break;else if(this.yields.length===0)$.length=0,this.yields=$,this.signal=(0,Z5.deferred)()}}discard(){if(this.done=!0,this.socket)try{this.socket.removeAllListeners(),this.socket.destroy()}catch{}}disconnect(){this._closed(void 0,!0).then().catch()}isEncrypted(){return this.socket instanceof E71.TLSSocket}_send($){if(this.isClosed||this.socket===void 0)return Promise.resolve();if(this.options.debug)console.info(`< ${(0,Z5.render)($)}`);let Z=(0,Z5.deferred)();try{this.socket.write($,(X)=>{if(X){if(this.options.debug)console.error(`!!! ${(0,Z5.render)($)}: ${X}`);return Z.reject(X)}return Z.resolve()})}catch(X){if(this.options.debug)console.error(`!!! ${(0,Z5.render)($)}: ${X}`);Z.reject(X)}return Z}send($){this._send($).catch((X)=>{})}async _closed($,Z=!0){if(!this.connected)return;if(this.done){this.socket?.destroy();return}if(this.closeError=$,!$&&this.socket&&Z)try{await this._send(new TextEncoder().encode(""))}catch(X){if(this.options.debug)console.log("transport close terminated with an error",X)}try{if(this.socket)this.socket.removeAllListeners(),this.socket?.destroy(),this.socket=void 0}catch(X){console.log(X)}this.done=!0,this.closedNotification.resolve(this.closeError)}closed(){return this.closedNotification}}RF.NodeTransport=Nd$;function YU6($){let Z=(0,Z5.deferred)();return ZU6.default.lookup($,{all:!0},(X,Q)=>{if(X){Z.reject(X);return}let Y=[];for(let G of Q)Y.push(G.address);if(Y.length===0)Y.push($);Z.resolve(Y)}),Z}});var Ld$=_((wd$)=>{Object.defineProperty(wd$,"__esModule",{value:!0});wd$.connect=GU6;var Bd$=Ud$(),Od$=Os(),Dd$=Os();function GU6($={}){if((0,Dd$.hasWsProtocol)($))return Promise.reject(Dd$.errors.InvalidArgumentError.format("servers","node client doesn't support websockets, use the 'wsconnect' function instead"));return(0,Od$.setTransportFactory)({factory:()=>{return new Bd$.NodeTransport},dnsResolveFn:Bd$.nodeResolveHost}),Od$.NatsConnectionImpl.connect($)}});var Ed$=_((tN)=>{var WU6=tN&&tN.__createBinding||(Object.create?function($,Z,X,Q){if(Q===void 0)Q=X;var Y=Object.getOwnPropertyDescriptor(Z,X);if(!Y||("get"in Y?!Z.__esModule:Y.writable||Y.configurable))Y={enumerable:!0,get:function(){return Z[X]}};Object.defineProperty($,Q,Y)}:function($,Z,X,Q){if(Q===void 0)Q=X;$[Q]=Z[X]}),KU6=tN&&tN.__exportStar||function($,Z){for(var X in $)if(X!=="default"&&!Object.prototype.hasOwnProperty.call(Z,X))WU6(Z,$,X)};Object.defineProperty(tN,"__esModule",{value:!0});tN.connect=void 0;var FU6=Ld$();Object.defineProperty(tN,"connect",{enumerable:!0,get:function(){return FU6.connect}});KU6(Os(),tN)});function Ad$($){let Z=$?.connectFn??BU6,X=null,Q=null,Y=!1,G=!1,J=!1,W=[];function K(){return X!==null&&!X.isClosed()&&!X.isDraining()&&!J}function F(){console.log(`[NatsProvider] fireReady: ${W.length} callbacks`);for(let U of W)try{U()}catch{}}function H(U){(async()=>{for await(let B of U.status())if(B.type==="disconnect")console.log("[NatsProvider] Disconnected"),J=!0;else if(B.type==="reconnect")console.log("[NatsProvider] Reconnected, re-firing ready callbacks"),J=!1,Q=null,F()})().catch(()=>{})}async function N(U,B){let O=0;while(!G)try{X=await Z({servers:U,timeout:UU6,reconnect:!0,maxReconnectAttempts:-1,...B?{authenticator:B}:{}}),console.log(`[NatsProvider] Connected to ${X.getServer()} after ${O} attempt(s)`),Q=null,J=!1,H(X),F();return}catch{O++;let w=eZ(NU6,HU6,O-1,2,0.5);await w$(w)}}return{init(U,B){if(Y)return;Y=!0,G=!1;let O=B?.creds?jd$.credsAuthenticator(new TextEncoder().encode(B.creds)):void 0;N(U,O).catch(()=>{})},isConnected(){return K()},getConnection(){return K()?X:null},getJetStream(){if(!K())return null;if(!Q)Q=Pd$.jetstream(X);return Q},onReady(U){if(W.push(U),K())try{U()}catch{}},async drain(){if(G=!0,Y=!1,Q=null,J=!1,X){let U=X;X=null,await U.drain().catch(()=>{})}}}}function BU6($){return zd$.connect($)}var jd$,zd$,Pd$,HU6=100,NU6=3000,UU6=3000;var Td$=D(()=>{X4();jd$=V(Ll(),1),zd$=V(Ed$(),1),Pd$=V(YU(),1)});function j71($,Z){return`${$}.${Z}`}class z71{cache;constructor($){this.cache=$u({ttlMs:$?.ttlMs??OU6,maxSize:$?.maxSize??DU6})}async get($,Z){return this.cache.get(j71($,Z))??null}async set($,Z,X){this.cache.set(j71($,Z),X)}async invalidate($,Z){this.cache.delete(j71($,Z))}teardown(){this.cache.clear()}}var OU6=600000,DU6=5000;var Rd$=()=>{};function LT0($,Z){return`${$}:${Z}`}function P71($){let Z=$u({ttlMs:$?.ttlMs??wU6,maxSize:$?.maxSize??LU6}),X=$?.getConnection,Q=crypto.randomUUID(),Y=new TextEncoder,G=new TextDecoder,J=null;function W(K,F){let H=X?.();if(!H)return;try{H.publish(Id$,Y.encode(JSON.stringify({organizationId:K,keyId:F,originId:Q})))}catch(N){console.warn("[ProviderKeyCache] Publish failed (non-critical):",N)}}return{get(K,F){return Z.get(LT0(K,F))},set(K,F,H){Z.set(LT0(K,F),H)},invalidate(K,F){Z.delete(LT0(K,F)),W(K,F)},start(){if(J)return;let K=X?.();if(!K)return;J=K.subscribe(Id$),(async()=>{for await(let F of J)try{let H=JSON.parse(G.decode(F.data));if(H.originId===Q)continue;Z.delete(LT0(H.organizationId,H.keyId))}catch{}})().catch(console.error)},teardown(){J?.unsubscribe(),J=null,Z.clear()}}}var Id$="studio.ai-provider-keys.invalidate",wU6=30000,LU6=5000;var qd$=()=>{};class A71{options;subscription=null;onCancel=null;encoder=new TextEncoder;originId=crypto.randomUUID();constructor($){this.options=$}async start($){if($)this.onCancel=$;if(this.subscription)return;if(!this.onCancel)return;let Z=this.options.getConnection();if(!Z)return;let X=new TextDecoder,Q=Z.subscribe("studio.decopilot.cancel");this.subscription=Q,(async()=>{for await(let Y of Q)try{let G=JSON.parse(X.decode(Y.data));if(G.originId===this.originId)continue;this.onCancel?.(G.taskId)}catch{}})().catch(console.error)}broadcast($){if(/[.*>\s]/.test($)){console.warn("[NatsCancelBroadcast] Invalid threadId, skipping broadcast");return}this.onCancel?.($);try{let Z=this.options.getConnection();if(!Z)return;let X=this.encoder.encode(JSON.stringify({taskId:$,originId:this.originId}));Z.publish("studio.decopilot.cancel",X)}catch(Z){console.warn("[NatsCancelBroadcast] Publish failed (non-critical):",Z)}}async stop(){this.subscription?.unsubscribe(),this.subscription=null,this.onCancel=null}}var Md$=($)=>{let Z;return()=>Z??=$()},T71,R71;var kd$=D(()=>{W6();T71=Md$(()=>J$.createHistogram("decopilot.stream.encode_ms",{description:"Per-chunk JSON.stringify+encode time for decopilot stream",unit:"ms"})),R71=Md$(()=>J$.createCounter("decopilot.stream.published_chunks",{description:"Logical decopilot stream chunks published to JetStream",unit:"{chunks}"}))});function RU6($=Cd$){return{name:iK,subjects:[`${Ir0}.>`],storage:LW.StorageType.File,max_age:zU6,max_bytes:AU6,max_msgs_per_subject:TU6,discard:LW.DiscardPolicy.Old,retention:LW.RetentionPolicy.Limits,duplicate_window:PU6,num_replicas:$}}class _d${chunks=0;encodeMs=0;maxMs=0;bytes=0;windowStart=performance.now();constructor(){setInterval(()=>this.flush(),1e4).unref?.()}record($,Z){if(this.chunks++,this.encodeMs+=$,$>this.maxMs)this.maxMs=$;this.bytes+=Z}flush(){let $=performance.now(),Z=$-this.windowStart;if(this.chunks>0&&Z>0)console.warn(JSON.stringify({msg:"stream-encode-trace",windowMs:Math.round(Z),chunks:this.chunks,encodeMs:Math.round(this.encodeMs),pctOfLoop:+(this.encodeMs/Z*100).toFixed(1),maxChunkMs:+this.maxMs.toFixed(2),mbEncoded:+(this.bytes/1048576).toFixed(2)}));this.chunks=0,this.encodeMs=0,this.maxMs=0,this.bytes=0,this.windowStart=$}}function Vd$($){let Z=Sd$.headers();for(let[X,Q]of Object.entries($))Z.set(X,Q);return Z}function kU6($,Z){let X=0;return{publish(Q,Y,G,J){Q.publish(Y,G,J?{headers:J}:void 0).catch((W)=>{if(X++,jU6().add(1,{"org.id":Z??"unknown"}),X===1||X%100===0)console.warn(`[Decopilot] JetStream publish failed for thread ${$} (${X} total):`,W)})},get errorCount(){return X}}}function VU6($,Z){return $.info?.cluster?Z:1}function SU6($){if(!($ instanceof Error))return!1;if(/non-clustered/i.test($.message))return!0;return/replicas?\b/i.test($.message)&&/not supported|can ?not|exceed|insufficient|greater than/i.test($.message)}class I71{options;js=null;jsm=null;constructor($){this.options=$}async init(){let $=this.options.getConnection();if(!$){console.log("[Decopilot] StreamBuffer.init skipped: NATS not connected yet");return}let Z=async(Q,Y)=>{let G=RU6(Y);try{await Q.streams.info(iK),await Q.streams.update(iK,G)}catch(J){if(J instanceof Error&&J.message.includes("stream not found"))await Q.streams.add(G),await Q.streams.update(iK,G);else if(J instanceof Error&&/can ?not change.*storage|storage type/i.test(J.message))await Q.streams.delete(iK),await Q.streams.add(G);else throw J}},X=await w6(async()=>{let Q=this.options.getJetStreamManager?await this.options.getJetStreamManager():await LW.jetstreamManager($),Y=VU6($,Cd$);try{await Z(Q,Y)}catch(G){if(Y<=1||!SU6(G))throw G;console.warn(`[Decopilot] StreamBuffer: NATS rejected num_replicas=${Y} (${G.message}); falling back to an unreplicated stream`),await Z(Q,1)}return Q},{maxAttempts:5,minTimeout:250,maxTimeout:4000,jitter:0.5,isRetriable:Rg});this.js=this.options.getJetStream(),this.jsm=X,console.log(`[Decopilot] StreamBuffer.init ${this.js?"ready":"degraded (js=null)"}`)}pump($,Z,X,Q){let Y=this.js;if(!Y)return console.warn(`[Decopilot] pump: JetStream client unavailable for thread ${Z}; chunks NOT published to NATS`),Promise.resolve();let G=kU6(Z,Q),J=!1,W=()=>{if(J)return;J=!0;let F=yU$(Z);Y.publish(F.subject,F.data).catch(()=>{})};X.addEventListener("abort",W,{once:!0});let K=(F)=>{let H=performance.now(),N=Mr0(F,{runId:Z}),U=performance.now()-H;T71().record(U),R71().add(1,{"org.id":Q??"unknown"}),MU6?.record(U,N.reduce((B,O)=>B+O.data.length,0));for(let B of N)G.publish(Y,B.subject,B.data,B.headers?Vd$(B.headers):void 0)};return(async()=>{let F=$.getReader(),H=0,N=0,U;try{while(!0){let{done:B,value:O}=await F.read();if(B)break;if(K(O),N++,++H>=64)H=0,await new Promise((w)=>setImmediate(w))}}catch(B){U=B,console.warn(`[Decopilot] stream pump error for thread ${Z}:`,B?.message??B)}finally{if(F.releaseLock(),W(),qU6)console.warn(JSON.stringify({msg:"decopilot-stream-diag",event:"pump-done",taskId:Z,publishedChunks:N,publishErrors:G.errorCount}))}if(U!==void 0)throw U})()}async publishSerialized($,Z){try{return await w6(()=>$.publish(Z.subject,Z.data,{...Z.headers?{headers:Vd$(Z.headers)}:{},...Z.msgId?{msgID:Z.msgId}:{}}),{maxAttempts:6,minTimeout:250,maxTimeout:5000,jitter:0.5,isRetriable:Rg}),!0}catch(X){return console.error(`[Decopilot] publish failed after retries subject=${Z.subject}`,X),!1}}async publishRawChunk($,Z,X){let Q=this.js;if(!Q)return!1;let Y=performance.now(),G=Mr0(Z,{runId:$,dedup:X});T71().record(performance.now()-Y),R71().add(1);for(let J of G)if(!await this.publishSerialized(Q,J))return!1;return!0}async publishDone($,Z,X){let Q=this.js;if(!Q)return!1;let Y=xU$({runId:$,fenceToken:Z,finalSeq:X});return await this.publishSerialized(Q,Y)}async createTailStream($,Z,X){let Q=this.js;if(!Q)return console.warn(`[Decopilot] createTailStream: JetStream client unavailable for thread ${$}; no live tail`),null;let Y=X?.deliverPolicy==="new"?LW.DeliverPolicy.New:LW.DeliverPolicy.All,G=X?.closeOnDone??!1,J=YD($),W;try{W=await w6(async()=>{return(await Q.consumers.get(iK,{filter_subjects:J,deliver_policy:Y})).consume()},{maxAttempts:6,minTimeout:250,maxTimeout:5000,jitter:0.5,isRetriable:Rg})}catch(w){return console.warn("[Decopilot] JetStream tail unavailable (non-critical):",w?.message??w),null}let H=dw0({messages:async function*(){try{for await(let w of W)yield{subject:w.subject,data:w.data,headers:w.headers}}finally{W.stop()}}(),onCancel:()=>W.stop()}).pipeThrough(hw0()).pipeThrough(uw0()).getReader(),N=!1,U=()=>{if(N)return;N=!0;try{H.releaseLock()}catch{}},B=!1,O=()=>{if(B)return;B=!0,W.stop(),H.cancel().catch(()=>{}),U()};return Z?.addEventListener("abort",O,{once:!0}),new ReadableStream({async pull(w){for(;;){let{done:L,value:E}=await H.read();if(L){O(),w.close();return}let j=E;if(j.kind==="done"){if(G){O(),w.close();return}continue}w.enqueue(j.chunk);return}},cancel(){O()}})}purge($){if(!this.jsm)return;this.jsm.streams.purge(iK,{filter:YD($)}).catch(()=>{})}teardown(){this.js=null,this.jsm=null}}var LW,Sd$,EU6=($)=>{let Z;return()=>Z??=$()},jU6,zU6=86400000000000,PU6=120000000000,AU6=4294967296,Cd$,TU6=500000,IU6,qU6,MU6;var vd$=D(()=>{X4();kr0();mw0();lw0();W6();kd$();LW=V(YU(),1),Sd$=V(Ll(),1),jU6=EU6(()=>J$.createCounter("decopilot.stream.publish_errors",{description:"Number of JetStream publish failures for decopilot stream chunks",unit:"{errors}"})),Cd$=Math.max(1,Number(process.env.DECOPILOT_STREAM_REPLICAS??3)||3);IU6=process.env.STREAM_ENCODE_TRACE==="1",qU6=process.env.DECOPILOT_STREAM_TRACE==="1";MU6=IU6?new _d$:null});function ET0($,Z,X,Q){if(!Q)return!1;return $.emit(Z,lW(X,Q.status,{title:Q.title??void 0,virtualMcpId:Q.virtual_mcp_id??void 0,createdBy:Q.created_by??void 0,triggerId:Q.trigger_id??null,branch:Q.branch??null,harnessId:Q.harness_id??void 0,createdAt:Q.created_at,updatedAt:Q.updated_at})),!0}var fd$=D(()=>{R8()});class q71{storage;options;timer=null;constructor($,Z={}){this.storage=$;this.options=Z}start(){if(this.timer)return;let $=this.options.intervalMs??300000;this.timer=setInterval(()=>{this.runOnce()},$)}async runOnce(){let $=this.options.staleAfterMs??3600000;try{let Z=await this.storage.sweepAbandoned($);if(Z>0)console.log(`[async-research-sweeper] marked ${Z} stale jobs as abandoned`);return Z}catch(Z){return console.error("[async-research-sweeper] sweep failed",Z),0}}dispose(){if(this.timer)clearInterval(this.timer),this.timer=null}}async function bd$($,Z,X){let Q=Z.organizationId;if(!sQ(Z))return!1;if(!vC(X))return!1;if(await $.storage.taskBoard.hasHumanRejectedDone(Z.id,Q))return!1;let Y=await $.storage.organizationSettings.get(Q),G=EK(Y?.flags),J=await $.storage.taskBoard.update(Z.id,Q,{status:G},Z.updatedBy);return await R6($,{taskBoardItemId:Z.id,action:"status_changed",actorId:null,data:{from:Z.status,to:G,reason:"pr_merged"}}),Y8(Q,J),console.log(`[task-board-review-sweeper] ${Z.id}: linked PR already merged \u2014 moved to ${G}`),!0}var xd$=D(()=>{R4();KX();Fg();t3();f5()});function yU6($){return $ instanceof aX}function gU6($,Z){return Z-$>=bU6}class M71{taskBoard;contextFactory;billing;options;timer=null;running=!1;cursor=null;constructor($,Z,X,Q={}){this.taskBoard=$;this.contextFactory=Z;this.billing=X;this.options=Q}start(){if(this.timer)return;let $=this.options.intervalMs??CU6;this.timer=setInterval(()=>{this.runOnce()},$),this.timer.unref()}async runOnce(){if(this.running)return 0;this.running=!0;let $=0;try{let Z=this.options.batchSize??vU6,X=this.options.itemIntervalMs??_U6,Q=new Date(Date.now()-X),Y=await this.taskBoard.listItemsPendingReview(Z,this.cursor,Q),G=Y.at(-1);this.cursor=Y.length===Z&&G?{updatedAt:G.updatedAt,id:G.id}:null;for(let{id:J,organizationId:W}of Y)try{if(await this.reconcileItem(J,W,Q))$++}catch(K){console.error(`[task-board-review-sweeper] ${J} failed`,K)}await this.reapNeverStartedThreads(Z),$+=await this.dispatchDueRetries(Z),await this.reactToUnhandledFailures(Z)}catch(Z){console.error("[task-board-review-sweeper] sweep failed",Z)}finally{this.running=!1}return $}async reapNeverStartedThreads($){try{let Z=await this.taskBoard.failNeverStartedLinkedThreads($,new Date(Date.now()-jt0),pt0);for(let X of Z)console.warn(`[task-board-review-sweeper] failed never-started thread ${X.threadId} on ${X.itemId}`)}catch(Z){console.error("[task-board-review-sweeper] reaping failed",Z)}}async reactToUnhandledFailures($){let Z=await this.taskBoard.listItemsStuckAfterFailure($,new Date(Date.now()-xU6));for(let{id:X,organizationId:Q,threadId:Y}of Z)try{console.warn(`[task-board-review-sweeper] reacting to an unhandled failure on ${X}`),await dt0(this.taskBoard,Y,Q),await mt0(this.taskBoard,this.billing,Y,Q)}catch(G){console.error(`[task-board-review-sweeper] unhandled-failure reaction for ${X} failed`,G)}}async dispatchDueRetries($){let Z=0,X=await this.taskBoard.listItemsDueForRetry($,new Date);for(let{id:Q,organizationId:Y,attempts:G}of X)try{if(!await this.taskBoard.claimDueRetry(Q,Y,new Date))continue;let J=await this.taskBoard.getById(Q,Y);if(!J||J.status!==I$.progress||J.assigneeId!==X8)continue;let W=await this.contextFactory(Y,J.assignedBy??J.createdBy);if(!W)continue;await KN(W,J,{runClass:"retry"}),Z++,console.warn(`[task-board-review-sweeper] re-dispatched ${Q} after a failure (attempt ${G})`)}catch(J){if(console.error(`[task-board-review-sweeper] retry dispatch for ${Q} failed`,J),yU6(J)){await this.returnToTodo(Q,Y,J instanceof Error?J.message:String(J));continue}await this.taskBoard.scheduleRunRetry(Q,Y,G,new Date(Date.now()+fU6)).catch((W)=>console.error(`[task-board-review-sweeper] re-arming ${Q} failed`,W))}return Z}async returnToTodo($,Z,X){try{let Q=await this.taskBoard.getById($,Z);if(!Q||Q.status!==I$.progress)return;let Y=await this.taskBoard.returnToTodoAfterFailure($,Z,Q.updatedBy);if(!Y)return;await this.taskBoard.recordActivity({taskBoardItemId:$,action:"status_changed",actorId:null,data:{from:"in_progress",to:"todo",reason:X}}).catch(()=>{}),Y8(Z,Y)}catch(Q){console.error(`[task-board-review-sweeper] returning ${$} to todo failed`,Q)}}async handOffReviewWithoutPr($,Z){let X=await this.taskBoard.listActivity(Z.id,Z.organizationId);if(!gU6(vH(X,Z.reviewCycleStartedAt),Date.now()))return;await gK($,Z,"no pull request is linked to this task \u2014 there is nothing for a "+"reviewer to review")}async reconcileItem($,Z,X){if(!await this.taskBoard.claimSweep($,Z,X))return!1;let Q=await this.taskBoard.getById($,Z);if(!Q)return!1;if(!sQ(Q))return!1;let Y=Q.assigneeId===X8,G=await this.taskBoard.listPrs($,Z),J=await this.contextFactory(Z,Q.assignedBy??Q.createdBy);if(!J)return!1;if(G.length===0){if(Y)await this.handOffReviewWithoutPr(J,Q);return!1}let W=await Promise.all(G.map(async(K)=>({...K,...await Ug(Z,K)})));if(W.every((K)=>K.state===null))console.warn(`[task-board-review-sweeper] ${$}: no live PR state from GitHub (${W.length} PR(s)) \u2014 proceeding on unknown`);if(await bd$(J,Q,W))return!0;if(await MB$(J,Q))return!0;if(await this.resolveConflictFromSweep(J,Q,W))return!0;if(!Y)return!1;if(!No0(W))return!1;return await eD0(J,Q,{previewMatchesHead:Uo0(W)}),!0}async resolveConflictFromSweep($,Z,X){let Q=X.find((Y)=>Y.state!=="closed"&&Y.conflict===!0);if(!Q)return!1;return await oO($,Z.organizationId,Z,{pr:{number:Q.number,url:Q.url},conflict:!0}).catch((Y)=>{return console.error("[task-board-review-sweeper] conflict resolve failed",Y),!1})}dispose(){if(this.timer)clearInterval(this.timer),this.timer=null}}var CU6=60000,_U6=300000,vU6=50,fU6=60000,bU6=900000,xU6=120000;var yd$=D(()=>{R4();Qo0();WN();It();t3();xd$();f5();sG();nt0();QG();$t();Hg()});import{readdir as hU6,rm as jT0}from"fs/promises";import{join as zT0}from"path";async function PT0($){let Z=new Date;Z.setUTCDate(Z.getUTCDate()-uU6),Z.setUTCHours(0,0,0,0);let X=0;try{let Q=await Ev($);for(let Y of Q)if(/^\d{4}$/.test(Y))X+=await gd$($,Y,Z);else if(!Y.startsWith(".")){let G=zT0($,Y),J=await Ev(G);for(let K of J){if(!/^\d{4}$/.test(K))continue;X+=await gd$(G,K,Z)}if((await Ev(G)).length===0)await jT0(G,{recursive:!0,force:!0})}}catch(Q){console.warn("monitoring retention cleanup failed:",Q)}return X}async function gd$($,Z,X){let Q=0,Y=zT0($,Z),G=await Ev(Y);for(let W of G){if(!/^\d{2}$/.test(W))continue;let K=zT0(Y,W),F=await Ev(K);for(let N of F){if(!/^\d{2}$/.test(N))continue;let U=new Date(`${Z}-${W}-${N}T00:00:00Z`);if(isNaN(U.getTime()))continue;if(U<X){let B=zT0(K,N);await jT0(B,{recursive:!0,force:!0}),Q++}}if((await Ev(K)).length===0)await jT0(K,{recursive:!0,force:!0})}if((await Ev(Y)).length===0)await jT0(Y,{recursive:!0,force:!0});return Q}async function Ev($){try{return(await hU6($)).filter((X)=>!X.startsWith("."))}catch{return[]}}var uU6=30;var k71=()=>{};import{DBOS as V71,SchedulerMode as lU6}from"@dbos-inc/dbos-sdk";async function dU6(){let $=[gJ(),jv(),MF()],Z=0;for(let X of $)try{Z+=await PT0(X)}catch(Q){console.error("[monitoring-retention] cleanup failed:",Q)}return console.log(`[monitoring-retention] deleted ${Z} day-dir(s) across ${$.length} signal dir(s)`),{deleted:Z,dirs:$.length}}async function mU6($,Z){await V71.runStep(()=>dU6(),{name:"monitoringRetention"})}function ud$(){if(hd$)return;hd$=!0;let $=V71.registerWorkflow(mU6,{name:"monitoringRetentionWorkflow"});V71.registerScheduled($,{name:"monitoringRetentionWorkflow",crontab:cU6,mode:lU6.ExactlyOncePerIntervalWhenActive})}var cU6="23 4 * * *",hd$=!1;var ld$=D(()=>{zY();k71()});function cd$($){return async(Z,X)=>{let Q=await $.db.selectFrom("member").innerJoin("organization","organization.id","member.organizationId").select(["member.role","organization.id as orgId","organization.slug as orgSlug","organization.name as orgName"]).where("member.userId","=",X).where("member.organizationId","=",Z).executeTakeFirst();if(!Q)return console.warn(`[automationContextFactory] User ${X} not found in org ${Z} \u2014 returning null`),null;let Y=await HJ.create();Y.auth.user={id:X,role:Q.role},Y.organization={id:Q.orgId,slug:Q.orgSlug,name:Q.orgName};let G=await Kt($.db,Z,Q.role);return Y.boundAuth=R51({auth:Y.authInstance,headers:new Headers,role:Q.role,permissions:G,userId:X}),Y.access=new tL(X,void 0,Y.boundAuth,Q.role,"self"),rO(Y,{id:Q.orgId,slug:Q.orgSlug}),Y}}var dd$=D(()=>{fB();aO()});function iU6(){return[{name:"Postgres",status:"pending",port:0},{name:"NATS",status:"pending",port:0}]}function pU6(){return{services:iU6(),migrationsStatus:"pending",serverUrl:null,logs:[]}}function tU6(){for(let $ of nU6)$()}function md$($){let Z=[...S71.logs,$];S71={...S71,logs:Z.length>500?Z.slice(-500):Z},tU6()}function C71(){return oU6}var S71,nU6,oU6=!1;var _71=D(()=>{S71=pU6(),nU6=new Set});import{EventEmitter as rU6}from"events";var v71;var id$=D(()=>{_71();v71=new rU6;v71.on("request",($)=>{md$($)})});function pd$(){return async($,Z)=>{let X=Date.now(),Q=$.req.method,Y=$.req.path;if(Y==="/api/auth/get-session"||Y.includes("favicon")){await Z();return}let G="",J=!1;if(Y.startsWith("/mcp")&&Q==="POST"){J=!0;try{if($.req.header("Content-Type")?.includes("application/json")){let U=await $.req.raw.clone().json();if(U.method==="tools/call"&&U.params?.name){let B=nu(U.params.name),O=U.params.arguments||{},w=Object.keys(O).map((E)=>nu(E)),L=w.length>0?w.slice(0,3).join(",")+(w.length>3?"\u2026":""):"";G=`${F5.tool}${B}${F5.dim}(${L})${F5.reset}`}else if(U.method)G=`${F5.dim}${nu(U.method)}${F5.reset}`}}catch{}}let W=nu(Y);if(Y.startsWith("/mcp/conn_")){let H=Y.split("/")[2]??"";W=`/mcp/${F5.mcp}${nu(H.slice(0,12))}\u2026${F5.reset}`}else if(Y==="/mcp")W=`${F5.mcp}/mcp${F5.reset}`;else if(Y==="/mcp/registry")W=`${F5.mcp}/mcp/registry${F5.reset}`;let K=sU6(Q),F=J?"\u25C0":"\u2190";if(!C71())console.log(`${F5.dim}${F}${F5.reset} ${K}${Q}${F5.reset} ${W}${G?` ${G}`:""}`);try{await Z()}finally{let H=Date.now()-X,N=$.res.status,U=aU6(N),B=H<1000?`${H}ms`:`${(H/1000).toFixed(1)}s`,O=J?"\u25B6":"\u2192";if(!C71())console.log(`${F5.dim}${O}${F5.reset} ${K}${Q}${F5.reset} ${W}${G?` ${G}`:""} ${U}${N}${F5.reset} ${F5.duration}${B}${F5.reset}`);v71.emit("request",{method:Q,path:nu(Y),status:N,duration:H,timestamp:new Date})}}}var F5,aU6=($)=>{if($>=500)return F5.serverError;if($>=400)return F5.clientError;if($>=300)return F5.redirect;return F5.ok},sU6=($)=>{return F5[$]||F5.reset},nu=($)=>{return $.replace(/\r/g,"").replace(/\n/g,"").replace(/\x1b\[[0-9;]*m/g,"").replace(/[\x00-\x1f\x7f-\x9f]/g,"")};var nd$=D(()=>{_71();id$();F5={reset:"\x1B[0m",dim:"\x1B[2m",bold:"\x1B[1m",GET:"\x1B[36m",POST:"\x1B[33m",PUT:"\x1B[35m",DELETE:"\x1B[31m",ok:"\x1B[32m",redirect:"\x1B[36m",clientError:"\x1B[33m",serverError:"\x1B[31m",mcp:"\x1B[35m",tool:"\x1B[96m",duration:"\x1B[90m"}});import{createHmac as ad$}from"crypto";import{mkdir as eU6,readdir as $B6,rm as td$,stat as sd$}from"fs/promises";import{join as b71,relative as ZB6}from"path";import{z as A$}from"zod";function $m$($){let Z=$.replace(/[^a-zA-Z0-9_-]/g,"_");return b71(XB6,Z)}function Zm$($){return $.replace(/^\/+/,"").replace(/\.\./g,"")}function f71($,Z){let X=$m$($),Q=Zm$(Z);return b71(X,Q)}function QB6($,Z,X,Q){let Y=_0().encryptionKey||"dev-secret",G=`${$}:${Z}:${X}:${Q}`;return ad$("sha256",Y).update(G).digest("hex")}function rd$($,Z,X,Q,Y){let G=Math.floor(Date.now()/1000)+Q,J=QB6(Z,X,G,Y),W=new URL(`/api/dev-assets/${Z}/${Zm$(X)}`,$);return W.searchParams.set("expires",G.toString()),W.searchParams.set("signature",J),W.searchParams.set("method",Y),W.toString()}function Xm$($,Z,X){let Q=`${$}:${Z.getTime()}:${X}`;return`"${ad$("md5","etag").update(Q).digest("hex")}"`}async function Qm$($,Z,X,Q,Y){try{let G=await $B6($,{withFileTypes:!0});for(let J of G){let W=b71($,J.name),F=ZB6(Z,W).replace(/\\/g,"/");if(X&&!F.startsWith(X))continue;if(J.isDirectory())if(Q){let H=F+"/";if(!X||H.startsWith(X)){if(!(X?F.slice(X.length):F).includes("/"))Y.commonPrefixes.add(H)}}else await Qm$(W,Z,X,Q,Y);else if(J.isFile()){if(Q&&X){let H=F.slice(X.length);if(H.includes(Q)){let N=H.indexOf(Q),U=X+H.slice(0,N+1);Y.commonPrefixes.add(U);continue}}try{let H=await sd$(W);Y.objects.push({key:F,size:H.size,lastModified:H.mtime.toISOString(),etag:Xm$(W,H.mtime,H.size)})}catch{}}}}catch{}}function Ym$($,Z){let Q=n($).id;return[{name:"LIST_OBJECTS",description:"List objects in the local assets directory with pagination support",inputSchema:A$.object({prefix:A$.string().optional(),maxKeys:A$.number().optional().default(1000),continuationToken:A$.string().optional(),delimiter:A$.string().optional()}),outputSchema:A$.object({objects:A$.array(A$.object({key:A$.string(),size:A$.number(),lastModified:A$.string(),etag:A$.string()})),nextContinuationToken:A$.string().optional(),isTruncated:A$.boolean(),commonPrefixes:A$.array(A$.string()).optional()}),handler:async(Y)=>{let G=Y,J=G.prefix||"",W=G.maxKeys??1000,K=G.delimiter,F=G.continuationToken,H=$m$(Q);await eU6(H,{recursive:!0});let N={objects:[],commonPrefixes:new Set};await Qm$(H,H,J,K,N),N.objects.sort((L,E)=>L.key.localeCompare(E.key));let U=0;if(F){if(U=N.objects.findIndex((L)=>L.key>F),U===-1)U=N.objects.length}let B=N.objects.slice(U,U+W),O=U+W<N.objects.length,w=O?B[B.length-1]?.key:void 0;return{objects:B,isTruncated:O,nextContinuationToken:w,commonPrefixes:Array.from(N.commonPrefixes).sort()}}},{name:"GET_OBJECT_METADATA",description:"Get metadata for a file in the local assets directory",inputSchema:A$.object({key:A$.string()}),outputSchema:A$.object({contentType:A$.string().optional(),contentLength:A$.number(),lastModified:A$.string(),etag:A$.string(),metadata:A$.record(A$.string(),A$.string()).optional()}),handler:async(Y)=>{let G=Y,J=f71(Q,G.key),W=await sd$(J);return{contentType:O91(G.key),contentLength:W.size,lastModified:W.mtime.toISOString(),etag:Xm$(J,W.mtime,W.size)}}},{name:"GET_PRESIGNED_URL",description:"Generate a presigned URL for downloading a file from local storage",inputSchema:A$.object({key:A$.string(),expiresIn:A$.number().optional()}),outputSchema:A$.object({url:A$.string(),expiresIn:A$.number()}),handler:async(Y)=>{let G=Y,J=G.expiresIn??od$;return{url:rd$(Z,Q,G.key,J,"GET"),expiresIn:J}}},{name:"PUT_PRESIGNED_URL",description:"Generate a presigned URL for uploading a file to local storage",inputSchema:A$.object({key:A$.string(),expiresIn:A$.number().optional(),contentType:A$.string().optional()}),outputSchema:A$.object({url:A$.string(),expiresIn:A$.number()}),handler:async(Y)=>{let G=Y,J=G.expiresIn??od$;return{url:rd$(Z,Q,G.key,J,"PUT"),expiresIn:J}}},{name:"DELETE_OBJECT",description:"Delete a single file from local storage",inputSchema:A$.object({key:A$.string()}),outputSchema:A$.object({success:A$.boolean(),key:A$.string()}),handler:async(Y)=>{let G=Y,J=f71(Q,G.key);try{return await td$(J),{success:!0,key:G.key}}catch{return{success:!1,key:G.key}}}},{name:"DELETE_OBJECTS",description:"Delete multiple files from local storage",inputSchema:A$.object({keys:A$.array(A$.string()).max(1000)}),outputSchema:A$.object({deleted:A$.array(A$.string()),errors:A$.array(A$.object({key:A$.string(),message:A$.string()}))}),handler:async(Y)=>{let G=Y,J=[],W=[];return await Promise.all(G.keys.map(async(K)=>{let F=f71(Q,K);try{await td$(F),J.push(K)}catch(H){W.push({key:K,message:H instanceof Error?H.message:"Unknown error"})}})),{deleted:J,errors:W}}}]}async function x71($,Z,X){let Q=Ym$(Z,X),Y=new tW({name:"dev-assets-mcp",version:"1.0.0"},{capabilities:{tools:{}},jsonSchemaValidator:O5});for(let J of Q){let W="shape"in J.inputSchema?J.inputSchema.shape:A$.object({}).shape,K=J.outputSchema&&"shape"in J.outputSchema?J.outputSchema.shape:A$.object({}).shape;Y.registerTool(J.name,{description:J.description??"",inputSchema:W,outputSchema:K,annotations:J.annotations,_meta:J._meta},async(F)=>{try{let H=await J.handler(F);return{content:[{type:"text",text:JSON.stringify(H)}],structuredContent:H}}catch(H){return{content:[{type:"text",text:`Error: ${H.message}`}],isError:!0}}})}let G=new GQ({enableJsonResponse:$.headers.get("Accept")?.includes("application/json")??!1});return await Y.connect(G),EJ(Y,G,$,"mcp:dev-assets")}async function Gm$($,Z,X,Q){let G=Ym$(X,Q).find((J)=>J.name===$);if(!G)return{content:[{type:"text",text:`Tool not found: ${$}`}],isError:!0};try{let J=await G.handler(Z);return{content:[{type:"text",text:JSON.stringify(J)}]}}catch(J){return{content:[{type:"text",text:J instanceof Error?J.message:String(J)}],isError:!0}}}var XB6="./data/assets",od$=3600,ed$,Jm$;var Wm$=D(()=>{L$();Sg();Z8();ld();Z_();hX();LA0();ed$=new K1;ed$.all("/",async($)=>{let Z=$.get("studioContext"),X=new URL($.req.url),Q=`${X.protocol}//${X.host}`;return x71($.req.raw,Z,Q)});Jm$=ed$});var Km$={};L4(Km$,{mountDevRoutes:()=>YB6});function YB6($,Z){$.all("/mcp/:connectionId{.*_dev-assets$}",Z,async(Q)=>{let Y=Q.get("studioContext"),G=new URL(Q.req.url),J=`${G.protocol}//${G.host}`;return x71(Q.req.raw,Y,J)}),$.all("/mcp/:connectionId{.*_dev-assets$}/call-tool/:toolName",Z,async(Q)=>{let Y=Q.get("studioContext"),G=new URL(Q.req.url),J=`${G.protocol}//${G.host}`,W=Q.req.param("toolName");if(!W)return Q.json({error:"Missing tool name"},400);let K=await Q.req.json(),F=await Gm$(W,K,Y,J);if(F.isError)return Q.json(F.content,500);return Q.json(F.content)}),$.use("/mcp/dev-assets",Z),$.route("/mcp/dev-assets",Jm$);let X=new K1;X.use("*",DW({mountPath:"/api/dev-assets"})),X.route("/",wA0({orgFromPath:!1})),$.route("/api/dev-assets",X)}var Fm$=D(()=>{Z8();J91();LA0();Wm$()});import{sql as GB6}from"kysely";import{randomUUID as Hm$}from"crypto";import{z as JB6}from"zod";async function KB6($){let Z=new Date().toISOString(),X=Hm$(),Q=v8.SELF($.organizationId),Y="registry.publish_request.created",G={requestId:$.request.id,requestedId:$.request.requested_id,title:$.request.title,status:$.request.status,createdAt:$.request.created_at,requester:{name:$.request.requester_name,email:$.request.requester_email}};await $.db.insertInto("events").values({id:X,organization_id:$.organizationId,type:"registry.publish_request.created",source:Q,specversion:"1.0",subject:$.request.id,time:Z,datacontenttype:"application/json",dataschema:null,data:JSON.stringify(G),cron:null,status:"pending",attempts:0,last_error:null,next_retry_at:null,created_at:Z,updated_at:Z}).execute();let J=await $.db.selectFrom("event_subscriptions").select(["id"]).where("organization_id","=",$.organizationId).where("enabled","=",1).where("event_type","=","registry.publish_request.created").where((W)=>W.or([W("publisher","is",null),W("publisher","=",Q)])).execute();if(J.length>0)await $.db.insertInto("event_deliveries").values(J.map((W)=>({id:Hm$(),event_id:X,subscription_id:W.id,status:"pending",attempts:0,last_error:null,delivered_at:null,next_retry_at:null,created_at:Z}))).execute();try{await GB6`SELECT
2953
2953
  pg_notify('studio_events', ${X}),