decocms 4.344.1 → 4.344.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (255) hide show
  1. package/dist/client/assets/{AlertCircle-BjMuYxmi.js → AlertCircle-C0qny1px.js} +1 -1
  2. package/dist/client/assets/{AreaChart-P5pArksK.js → AreaChart-BNxcydhF.js} +1 -1
  3. package/dist/client/assets/{ArrowLeft-BwC_u33Q.js → ArrowLeft-B2XPOt0B.js} +1 -1
  4. package/dist/client/assets/{ArrowUp-B8VhBtFx.js → ArrowUp-Bhh1sF6B.js} +1 -1
  5. package/dist/client/assets/{Check-DxQeYFcE.js → Check-CmQ2oLwV.js} +1 -1
  6. package/dist/client/assets/{CheckCircle-C_IlU8js.js → CheckCircle-5VIyydf8.js} +1 -1
  7. package/dist/client/assets/{ChevronRight-DPUKyX3B.js → ChevronRight-B27Hv5xi.js} +1 -1
  8. package/dist/client/assets/{ChevronSelectorVertical-YzQi0PQX.js → ChevronSelectorVertical-C16IZ1zE.js} +1 -1
  9. package/dist/client/assets/{ChevronUp-C9LCQ5Al.js → ChevronUp-DjhaEVdT.js} +1 -1
  10. package/dist/client/assets/{Copy01-MwHtzLVF.js → Copy01-hpwMZEjO.js} +1 -1
  11. package/dist/client/assets/{CreditCard01-Bi3-77w1.js → CreditCard01-_mA3pKi1.js} +1 -1
  12. package/dist/client/assets/{DotsVertical-B1I-mCuU.js → DotsVertical-BdoeS7iv.js} +1 -1
  13. package/dist/client/assets/{Download01-DGJEMDLc.js → Download01-LaiEzG3K.js} +1 -1
  14. package/dist/client/assets/{ErrorBarContext-DJ1fmyx8.js → ErrorBarContext-GHNxgIhL.js} +1 -1
  15. package/dist/client/assets/{Eye-D5g3w0j_.js → Eye-Dv6k5qFi.js} +1 -1
  16. package/dist/client/assets/{GitBranch01-CnlwY1P_.js → GitBranch01--7681EQG.js} +1 -1
  17. package/dist/client/assets/{Globe01-BLWkbDkc.js → Globe01-DbmZ0o2m.js} +1 -1
  18. package/dist/client/assets/{HardDrive-DQDOqSUK.js → HardDrive-DhrO38sr.js} +1 -1
  19. package/dist/client/assets/{Image01-vgxUXrTy.js → Image01-B__pNkrA.js} +1 -1
  20. package/dist/client/assets/{Key01-BmgHvr4E.js → Key01-B99AObCK.js} +1 -1
  21. package/dist/client/assets/{Link01-tJAsKN4V.js → Link01-BqiRcefs.js} +1 -1
  22. package/dist/client/assets/{LinkExternal01-DhLc5AVD.js → LinkExternal01-uMPfzQw5.js} +1 -1
  23. package/dist/client/assets/{Monitor01-BC_tYrvH.js → Monitor01-meoYyhOW.js} +1 -1
  24. package/dist/client/assets/{Package-gYdvPjZu.js → Package-Cz3ieF2n.js} +1 -1
  25. package/dist/client/assets/{Palette-CqySYNVO.js → Palette-CYkdSv-c.js} +1 -1
  26. package/dist/client/assets/{Play-Un8C-mAg.js → Play-CYQqcuRA.js} +1 -1
  27. package/dist/client/assets/{Plus-D6AiOZHV.js → Plus-C93pYF67.js} +1 -1
  28. package/dist/client/assets/{SearchMd-By0JhV4t.js → SearchMd-BgrahhLJ.js} +1 -1
  29. package/dist/client/assets/{Sector-DHsJol83.js → Sector-DA4aDIUa.js} +1 -1
  30. package/dist/client/assets/{Settings02-ClicUXGp.js → Settings02-CF6_FXnL.js} +1 -1
  31. package/dist/client/assets/{Share07-J9Tcg72Q.js → Share07-DNrUoDK2.js} +1 -1
  32. package/dist/client/assets/{Shield01-CRcKuFYE.js → Shield01-BK6WsY_Q.js} +1 -1
  33. package/dist/client/assets/{Stars01-Dmq72XcE.js → Stars01-CMlFN1iY.js} +1 -1
  34. package/dist/client/assets/{Sun-BXZfuBXP.js → Sun-DcyZD3fZ.js} +1 -1
  35. package/dist/client/assets/{Tool01-DJvWUPsn.js → Tool01-CJk3kST-.js} +1 -1
  36. package/dist/client/assets/{Tool02-eg3_S9Ak.js → Tool02-C5AbXwYZ.js} +1 -1
  37. package/dist/client/assets/{Trash01-C8iWkF21.js → Trash01-DXUyyosw.js} +1 -1
  38. package/dist/client/assets/{TrendUp01-vUbGui7n.js → TrendUp01-BpraasBt.js} +1 -1
  39. package/dist/client/assets/{Upload01-iR-rddab.js → Upload01-CAEKyOZy.js} +1 -1
  40. package/dist/client/assets/{User01-B5-Ys5vY.js → User01-By3UU9_0.js} +1 -1
  41. package/dist/client/assets/{UserSquare-gcGLnQoD.js → UserSquare-C9Yj5vKH.js} +1 -1
  42. package/dist/client/assets/{Users01-BVSUwlTI.js → Users01-BnSJOwH_.js} +1 -1
  43. package/dist/client/assets/{Users03-B9pTZPgz.js → Users03-Br54yZny.js} +1 -1
  44. package/dist/client/assets/{XCircle-4-8Jmfe4.js → XCircle-xCNpg4_3.js} +1 -1
  45. package/dist/client/assets/{XClose-COktzEMg.js → XClose-D6CVjuQD.js} +1 -1
  46. package/dist/client/assets/{Zap-g0qt0BwC.js → Zap-B9B8yhi7.js} +1 -1
  47. package/dist/client/assets/{ZoomOut-B_R5roqc.js → ZoomOut-C6ZLfLr7.js} +1 -1
  48. package/dist/client/assets/{access-gate-DLbpI8LF.js → access-gate-BqfCjr72.js} +1 -1
  49. package/dist/client/assets/{agent-icon-CCMiedCg.js → agent-icon-Sokr2wRV.js} +1 -1
  50. package/dist/client/assets/{agents-list-BQlnHJ-C.js → agents-list-ClI3IQyW.js} +1 -1
  51. package/dist/client/assets/{ai-providers-C8Gfn0sX.js → ai-providers-BiPyBRlR.js} +1 -1
  52. package/dist/client/assets/{alert-C6LsdoJV.js → alert-CFcbNqtp.js} +1 -1
  53. package/dist/client/assets/{alert-dialog-CJkXwWO9.js → alert-dialog-CNldqZsO.js} +1 -1
  54. package/dist/client/assets/{analytics-tab-C9SAGUgS.js → analytics-tab-BQJ-onyb.js} +1 -1
  55. package/dist/client/assets/api-keys-ChG3M8Mw.js +1 -0
  56. package/dist/client/assets/{api-keys-Cfd6NXQe.js → api-keys-WzJqP8Kj.js} +1 -1
  57. package/dist/client/assets/app-editor-8aYF0SAd.js +1 -0
  58. package/dist/client/assets/{auth-BPPezCXD.js → auth-DwMcGIkW.js} +1 -1
  59. package/dist/client/assets/{auth-catchall-BdTMMjlD.js → auth-catchall-DhQ_dsU6.js} +1 -1
  60. package/dist/client/assets/{auth-entry-B9uhggZP.js → auth-entry-H_tkAl6r.js} +1 -1
  61. package/dist/client/assets/{auth-split-layout-CN54sM56.js → auth-split-layout-DDvsORYF.js} +1 -1
  62. package/dist/client/assets/{authenticate-and-persist-oauth-Cu9y6SFV.js → authenticate-and-persist-oauth-CUqRnEoc.js} +1 -1
  63. package/dist/client/assets/{automation-list-row-BfHNI8Ry.js → automation-list-row-czAKSqCd.js} +1 -1
  64. package/dist/client/assets/{automation-runs-xfHBNYfm.js → automation-runs-B1sDggeq.js} +1 -1
  65. package/dist/client/assets/{automations-BG7aFgC9.js → automations-mh1wCA2E.js} +1 -1
  66. package/dist/client/assets/{autosend-CzXMxIBc.js → autosend-C2M3oMWg.js} +1 -1
  67. package/dist/client/assets/{avatar-cGgzX6Q8.js → avatar-E3Ku78Qr.js} +1 -1
  68. package/dist/client/assets/{badge-BOpZ6PkI.js → badge-C1plUCvU.js} +1 -1
  69. package/dist/client/assets/{block-document-Cx3WrG1X.js → block-document-DnS9PwNb.js} +1 -1
  70. package/dist/client/assets/{breadcrumb-KhPwJDYK.js → breadcrumb-CEOyoxxM.js} +1 -1
  71. package/dist/client/assets/{buckets-oJeZKYCe.js → buckets-C25mccgP.js} +1 -1
  72. package/dist/client/assets/{bulk-category-panel-B3zkGj5A.js → bulk-category-panel-6WLeyrzh.js} +1 -1
  73. package/dist/client/assets/{capability-load-error-D4HyCPBw.js → capability-load-error-DaASiLKE.js} +1 -1
  74. package/dist/client/assets/{cards-7EkyDZYV.js → cards-DrEtEuSA.js} +1 -1
  75. package/dist/client/assets/{category-editor-6SA3LNZv.js → category-editor-B09JH3m-.js} +1 -1
  76. package/dist/client/assets/{cdn-tab-DnbzvYlD.js → cdn-tab-CZ1Rz28V.js} +1 -1
  77. package/dist/client/assets/{chart-D3GNpA8E.js → chart-DLN94Yuh.js} +1 -1
  78. package/dist/client/assets/{chat-context-CXRs08s6.js → chat-context-Cj5PFaOM.js} +1 -1
  79. package/dist/client/assets/{checkbox-CpzwVXNS.js → checkbox-CVnXYBps.js} +1 -1
  80. package/dist/client/assets/{choose-editor-B4YWcnMg.js → choose-editor-BE92k8jI.js} +1 -1
  81. package/dist/client/assets/{cli-auth-success-CgbANE02.js → cli-auth-success-BMGCM_8X.js} +1 -1
  82. package/dist/client/assets/{client-icons-rTmmY4Qu.js → client-icons-C2e6COqB.js} +1 -1
  83. package/dist/client/assets/{collection-detail-5_RmbhhY.js → collection-detail-x7ykT2Ry.js} +1 -1
  84. package/dist/client/assets/{collection-display-button-CxDVHK3I.js → collection-display-button-CfIQymG1.js} +1 -1
  85. package/dist/client/assets/{collection-search-l1m_ppUw.js → collection-search-DxOane-0.js} +1 -1
  86. package/dist/client/assets/{collection-table-wrapper-Cnb9LKHS.js → collection-table-wrapper-CpVYdRK4.js} +1 -1
  87. package/dist/client/assets/{collection-tabs-CwMFKn1n.js → collection-tabs-CyauGvwq.js} +1 -1
  88. package/dist/client/assets/{command-BYlxLxTL.js → command-Hj_raW8k.js} +1 -1
  89. package/dist/client/assets/{commerce-onboarding-DjThyQh0.js → commerce-onboarding-CuLqtbcy.js} +1 -1
  90. package/dist/client/assets/{connect-Bkm3_g-O.js → connect-Xz6c3641.js} +1 -1
  91. package/dist/client/assets/{connect-layout-COVIZNxi.js → connect-layout-K-hZ0_ym.js} +1 -1
  92. package/dist/client/assets/{connection-C7aOtOZ9.js → connection-BmloY6wm.js} +1 -1
  93. package/dist/client/assets/{connection-card-FoQxvuJf.js → connection-card-DkeFitC9.js} +1 -1
  94. package/dist/client/assets/{connection-detail-DKMftkhe.js → connection-detail-DsNeFFvP.js} +1 -1
  95. package/dist/client/assets/{connection-form-helpers-BuJtasnZ.js → connection-form-helpers-BqIKeSnw.js} +1 -1
  96. package/dist/client/assets/{connections-FZxsmgMU.js → connections-aykt3abn.js} +1 -1
  97. package/dist/client/assets/{create-organization-dialog-G4OcSS8l.js → create-organization-dialog-BX0CUO0j.js} +1 -1
  98. package/dist/client/assets/{decopilot-sse-pool-L93pnfSs.js → decopilot-sse-pool-DZr2L-JD.js} +1 -1
  99. package/dist/client/assets/{dialog-OBxzAzom.js → dialog-DQfbJCC6.js} +1 -1
  100. package/dist/client/assets/{domain-settings-BRznnLr6.js → domain-settings-A8c7ke5N.js} +1 -1
  101. package/dist/client/assets/{drawer-C2xrNU8r.js → drawer-B9bDs4Ls.js} +1 -1
  102. package/dist/client/assets/{dropdown-menu-D7LCoNMq.js → dropdown-menu-DOECFeLR.js} +1 -1
  103. package/dist/client/assets/{e2e-tab-ntnPl-ca.js → e2e-tab-Blf2Ap_9.js} +1 -1
  104. package/dist/client/assets/{editor-CCRpAUKq.js → editor-fUuz2MTe.js} +1 -1
  105. package/dist/client/assets/{empty-state-DHwnQMV_.js → empty-state-13O4lRlk.js} +1 -1
  106. package/dist/client/assets/{empty-state-ADGxJSqy.js → empty-state-DB7HW5VU.js} +1 -1
  107. package/dist/client/assets/{extract-connection-data-BbqgTPgH.js → extract-connection-data-B45ll6gx.js} +1 -1
  108. package/dist/client/assets/{file-explorer-Bw3GSfQk.js → file-explorer-rIcSF1Wr.js} +1 -1
  109. package/dist/client/assets/{file-type-icon-CAW_viSw.js → file-type-icon-GIi5lUDa.js} +1 -1
  110. package/dist/client/assets/{folder-icon-SMGV3EMO.js → folder-icon-1B7OaZuC.js} +1 -1
  111. package/dist/client/assets/{form-S1ZESyeH.js → form-D1uCY5P6.js} +1 -1
  112. package/dist/client/assets/{general-SIMm3O8G.js → general-Co5dzuX-.js} +1 -1
  113. package/dist/client/assets/{github-icon-DbAmZ8nk.js → github-icon-BCHup1mY.js} +1 -1
  114. package/dist/client/assets/{hooks-B2R9sLxn.js → hooks-Bp1NdkLZ.js} +1 -1
  115. package/dist/client/assets/{hosting-tab-Ijx0TIC2.js → hosting-tab-WhehOhV2.js} +1 -1
  116. package/dist/client/assets/{index-7sFGYlJb.js → index-B-SFzwQ0.js} +1 -1
  117. package/dist/client/assets/{index-BchAOKlj.js → index-BQcoMXia.js} +2 -2
  118. package/dist/client/assets/{index-Buw64iTd.js → index-BqWHsoZ7.js} +1 -1
  119. package/dist/client/assets/{index-DPgRZdG6.js → index-Bwb7o3GW.js} +1 -1
  120. package/dist/client/assets/{index-Un5MjpBc.js → index-BxhlSimQ.js} +1 -1
  121. package/dist/client/assets/{index-CY2FHft8.js → index-CvfUTEg1.js} +1 -1
  122. package/dist/client/assets/{index-BPhWztnJ.js → index-D7qUeb84.js} +6 -6
  123. package/dist/client/assets/{index-lO6vP97d.js → index-DF7KW54C.js} +1 -1
  124. package/dist/client/assets/{index-Dhhe2yhg.js → index-DgzjHRte.js} +1 -1
  125. package/dist/client/assets/{index-DhTvONYT.js → index-DppZ6Cuh.js} +1 -1
  126. package/dist/client/assets/{index-redirect-BK-AVO2r.js → index-redirect-CHqT86li.js} +1 -1
  127. package/dist/client/assets/{infiniteQueryObserver-DdVambif.js → infiniteQueryObserver-B6kEjjrG.js} +1 -1
  128. package/dist/client/assets/{infra-billing-C3sspPa6.js → infra-billing-DZmmt6zX.js} +1 -1
  129. package/dist/client/assets/{input-DHP0RHlp.js → input-CMpXoJQQ.js} +1 -1
  130. package/dist/client/assets/{integration-icon-W2Q5PIck.js → integration-icon-KBoNAUV5.js} +1 -1
  131. package/dist/client/assets/{invite-member-dialog-CtEorK5c.js → invite-member-dialog-DzmoZ7z0.js} +1 -1
  132. package/dist/client/assets/{label-C7PK-lHw.js → label-DodRSPBl.js} +1 -1
  133. package/dist/client/assets/{layout-BnKlqv03.js → layout-p84CPw_W.js} +1 -1
  134. package/dist/client/assets/{login-BgsirZAt.js → login-qaDZ6pfK.js} +1 -1
  135. package/dist/client/assets/{markdown-BsIXLS3b.js → markdown-CXIAcTBJ.js} +1 -1
  136. package/dist/client/assets/{mcp-app-renderer-BTHF0AHF.js → mcp-app-renderer-iVlibFiT.js} +1 -1
  137. package/dist/client/assets/{mcp-oauth-DEWFOPkn.js → mcp-oauth-Cahsr_xA.js} +1 -1
  138. package/dist/client/assets/{members-jBFFi-vT.js → members-CVoitCGA.js} +1 -1
  139. package/dist/client/assets/{monaco-editor-DZADfW6r.js → monaco-editor-Dlrh6WT0.js} +1 -1
  140. package/dist/client/assets/{monitoring-stats-row-hKlWAt04.js → monitoring-stats-row-UUJjSC2L.js} +1 -1
  141. package/dist/client/assets/{multi-select-BLvZSTa1.js → multi-select-C9FaGgMm.js} +1 -1
  142. package/dist/client/assets/{oauth-callback-C51UB2D9.js → oauth-callback-BrsfA7zh.js} +1 -1
  143. package/dist/client/assets/{oauth-callback-ai-provider-Dsv963Ta.js → oauth-callback-ai-provider-CijU2vJE.js} +1 -1
  144. package/dist/client/assets/{onboarding-BYN-WZdf.js → onboarding-CkcuLiZT.js} +1 -1
  145. package/dist/client/assets/{org-layout-p6eqD620.js → org-layout-C1jBywh4.js} +1 -1
  146. package/dist/client/assets/{organization-choice-BLk1I6v9.js → organization-choice-CpltQ7-f.js} +1 -1
  147. package/dist/client/assets/{orgs-D_gvdKOu.js → orgs-WhkmcxJ0.js} +1 -1
  148. package/dist/client/assets/{page-seo-form-BDlAG2ny.js → page-seo-form-DCTcv1uv.js} +1 -1
  149. package/dist/client/assets/{popover-DkmR2lA6.js → popover-1HuPDlq4.js} +1 -1
  150. package/dist/client/assets/{post-calendar-CZISCbTj.js → post-calendar-MP1XEDcJ.js} +1 -1
  151. package/dist/client/assets/{post-editor-CYhhN1_z.js → post-editor-U0U-5c0E.js} +1 -1
  152. package/dist/client/assets/{primitives-CdRr57q-.js → primitives-KfqX5TVa.js} +1 -1
  153. package/dist/client/assets/{profile-CBONxCiy.js → profile-v9KeCx-y.js} +1 -1
  154. package/dist/client/assets/{project-app-view-BhoARCjd.js → project-app-view-BwZk6Udn.js} +1 -1
  155. package/dist/client/assets/{project-icon-DamXOjp8.js → project-icon-DMd26Pls.js} +1 -1
  156. package/dist/client/assets/{prompts-B6rAIvaw.js → prompts-CBgpH6_D.js} +1 -1
  157. package/dist/client/assets/record-editor-COIIYg4K.js +1 -0
  158. package/dist/client/assets/redirect-editor-CsEXUbgi.js +1 -0
  159. package/dist/client/assets/registry-C8XSrdWL.js +2 -0
  160. package/dist/client/assets/{registry-layout-DXwkRZOQ.js → registry-layout-CzT3YaK7.js} +1 -1
  161. package/dist/client/assets/{reports-BdxqpCo4.js → reports-DjQdnDXe.js} +1 -1
  162. package/dist/client/assets/{repositories-CGubii5t.js → repositories-AYkI0R1m.js} +1 -1
  163. package/dist/client/assets/{repository-import-picker-BJ-zN9Ij.js → repository-import-picker-C4ReqfSZ.js} +1 -1
  164. package/dist/client/assets/{repository-picker-BX_XSV19.js → repository-picker-D40DSLJP.js} +1 -1
  165. package/dist/client/assets/{require-capability--DOt2ERE.js → require-capability-BiJ9J6gK.js} +1 -1
  166. package/dist/client/assets/{required-auth-layout-Dy1_df_6.js → required-auth-layout-CCzrqs7a.js} +1 -1
  167. package/dist/client/assets/{reset-password-98jWo32P.js → reset-password-DzD5F-bQ.js} +1 -1
  168. package/dist/client/assets/{review-settings-CMYzZWK1.js → review-settings-ChCihbTS.js} +1 -1
  169. package/dist/client/assets/{roles-CPs9PioP.js → roles-DkR-RRyj.js} +1 -1
  170. package/dist/client/assets/{schema-C65nFTu4.js → schema-DM4fDgzo.js} +1 -1
  171. package/dist/client/assets/{scroll-area-TfVnAKMc.js → scroll-area-DWyWk7Jv.js} +1 -1
  172. package/dist/client/assets/{search-input-BQUFx9US.js → search-input-BrPxku06.js} +1 -1
  173. package/dist/client/assets/{secrets-C2HdSGM-.js → secrets-hNPljrJ4.js} +1 -1
  174. package/dist/client/assets/{sections-editor-BkMJ_oh_.js → sections-editor-DnGZRBS3.js} +1 -1
  175. package/dist/client/assets/{select-DrxveWhw.js → select-Biz9Nswo.js} +1 -1
  176. package/dist/client/assets/{select-model-Chu6b8mZ.js → select-model-BgSq1LgM.js} +1 -1
  177. package/dist/client/assets/{self-tool-result-DTVcCRcK.js → self-tool-result-klr6v5UO.js} +1 -1
  178. package/dist/client/assets/{seo-editor-CuepF3pb.js → seo-editor-DfcoS9MP.js} +1 -1
  179. package/dist/client/assets/settings-layout-BxIBM9qK.js +1 -0
  180. package/dist/client/assets/{settings-sidebar-DLrns6Fj.js → settings-sidebar-BeUFOMYU.js} +1 -1
  181. package/dist/client/assets/{shell-controls-CQiUgtRO.js → shell-controls-DUYrjBrP.js} +1 -1
  182. package/dist/client/assets/{shell-layout-BqV6fEBV.js → shell-layout-DedSudP1.js} +1 -1
  183. package/dist/client/assets/{skill-preview-CllyAILl.js → skill-preview-KNzIWmHY.js} +1 -1
  184. package/dist/client/assets/{skills-CFONQWW-.js → skills-SswbLa5T.js} +1 -1
  185. package/dist/client/assets/{sso-0n7r8-x_.js → sso-CXJr0VQP.js} +1 -1
  186. package/dist/client/assets/{store-B9HWO6cb.js → store-Dfdc4PHh.js} +1 -1
  187. package/dist/client/assets/store-registry-7tXK9BjC.js +2 -0
  188. package/dist/client/assets/{switch-D_cjCTgk.js → switch-vGB5Iw30.js} +1 -1
  189. package/dist/client/assets/{synced-repos-CoVXAmDk.js → synced-repos-CUidyAWL.js} +1 -1
  190. package/dist/client/assets/{table-Cf1yQntK.js → table-DSdoGDbv.js} +1 -1
  191. package/dist/client/assets/{tabs-od0SPK7S.js → tabs-B-iSBwwB.js} +1 -1
  192. package/dist/client/assets/{task-board-BnIBnE9V.js → task-board-YGgzMS53.js} +1 -1
  193. package/dist/client/assets/{task-route-C8eS62da.js → task-route-Ce5mQ3Za.js} +1 -1
  194. package/dist/client/assets/{tasks-Bd3sMm2P.js → tasks-Bse92t-v.js} +1 -1
  195. package/dist/client/assets/{textarea-CtTIh5eo.js → textarea-BHyVakeU.js} +1 -1
  196. package/dist/client/assets/{thread-intent-BUdj1oNO.js → thread-intent-Du1_x4Jo.js} +1 -1
  197. package/dist/client/assets/{thread-route-BuMLLPC9.js → thread-route-FbwK7fgk.js} +1 -1
  198. package/dist/client/assets/{toggle-group-CRdE5vQF.js → toggle-group-Dax2ER5x.js} +1 -1
  199. package/dist/client/assets/{toolbar-CsP7VfFt.js → toolbar-BwnpNgw5.js} +1 -1
  200. package/dist/client/assets/{toolbar-icon-button-BuEXzagv.js → toolbar-icon-button-MI8EHgxl.js} +1 -1
  201. package/dist/client/assets/{track-0QXSC0aR.js → track-BHRpjdS1.js} +1 -1
  202. package/dist/client/assets/{types-KEdMbDrR.js → types-CksA11PS.js} +1 -1
  203. package/dist/client/assets/{use-ai-providers-BdW_wf1z.js → use-ai-providers-CR5aXXx9.js} +1 -1
  204. package/dist/client/assets/{use-automations-DKOxPPAq.js → use-automations-CR3y-cno.js} +1 -1
  205. package/dist/client/assets/{use-autosave-BFL8sOAH.js → use-autosave-DZ8ozoxR.js} +1 -1
  206. package/dist/client/assets/{use-connection-BRPceU75.js → use-connection-DevEmQgx.js} +1 -1
  207. package/dist/client/assets/{use-copy-BeP1DGCD.js → use-copy-BwhkoVWT.js} +1 -1
  208. package/dist/client/assets/{use-create-virtual-mcp-DhSsOf3L.js → use-create-virtual-mcp-DSbrYl04.js} +1 -1
  209. package/dist/client/assets/{use-date-fns-locale-CqGJGe22.js → use-date-fns-locale-CsR-muSU.js} +1 -1
  210. package/dist/client/assets/{use-debounced-autosave-ORs7hX9x.js → use-debounced-autosave-DKLFJ5dE.js} +1 -1
  211. package/dist/client/assets/{use-debounced-value-8ClMD96D.js → use-debounced-value-HSbVg15K.js} +1 -1
  212. package/dist/client/assets/{use-decopilot-events-kIL4-9J-.js → use-decopilot-events-BjUmeoBW.js} +1 -1
  213. package/dist/client/assets/{use-delete-connection-DtqNWOLX.js → use-delete-connection-Cwrx1UQB.js} +1 -1
  214. package/dist/client/assets/{use-deployment-admin-Cm6pk0-i.js → use-deployment-admin-cCGiEL7u.js} +1 -1
  215. package/dist/client/assets/{use-destination-route-DSB7ygJ3.js → use-destination-route-Cy6Wb0tP.js} +1 -1
  216. package/dist/client/assets/{use-file-configs-CI0rcz5W.js → use-file-configs-BvYm0UJv.js} +1 -1
  217. package/dist/client/assets/{use-infinite-scroll-c0yQIbtU.js → use-infinite-scroll-DltgLysD.js} +1 -1
  218. package/dist/client/assets/{use-join-requests-Dpj6-Adj.js → use-join-requests-DDT_8QXv.js} +1 -1
  219. package/dist/client/assets/{use-mcp-auth-status-DhNUxu5f.js → use-mcp-auth-status-DEs88obf.js} +1 -1
  220. package/dist/client/assets/{use-mcp-client-dKCIRAKY.js → use-mcp-client-Bcw5zCo1.js} +1 -1
  221. package/dist/client/assets/{use-mcp-prompts-W9hu3OsJ.js → use-mcp-prompts-ShaK7Sn1.js} +1 -1
  222. package/dist/client/assets/{use-mcp-tools-Ci7UuYIf.js → use-mcp-tools-BbuyA-nn.js} +1 -1
  223. package/dist/client/assets/{use-members-DfzsBCnJ.js → use-members-DWHm6J5E.js} +1 -1
  224. package/dist/client/assets/{use-navigate-to-agent-DsVT2aJv.js → use-navigate-to-agent-C5VUtvNR.js} +1 -1
  225. package/dist/client/assets/{use-org-auth-client-C1YRjV3w.js → use-org-auth-client-U6rTeVug.js} +1 -1
  226. package/dist/client/assets/{use-org-notice-Cpu85Ukm.js → use-org-notice-D-KSDtqd.js} +1 -1
  227. package/dist/client/assets/{use-org-sso-C2KOoYeA.js → use-org-sso-DRZKsxoE.js} +1 -1
  228. package/dist/client/assets/{use-organization-roles-t96LTPe2.js → use-organization-roles-Bc3vsckc.js} +1 -1
  229. package/dist/client/assets/{use-organization-settings-ux6449Xl.js → use-organization-settings-CvNxIv-E.js} +1 -1
  230. package/dist/client/assets/{use-panel-navigate-BvI2J3ls.js → use-panel-navigate-ByHiKiT-.js} +1 -1
  231. package/dist/client/assets/{use-registry-connections-D8Shk9Ny.js → use-registry-connections-esc0qiTG.js} +1 -1
  232. package/dist/client/assets/{use-secrets-DFHzz6hG.js → use-secrets-DsTKtQMN.js} +1 -1
  233. package/dist/client/assets/{use-section-preview-base-jzmCaiCf.js → use-section-preview-base-DcluO2Ni.js} +1 -1
  234. package/dist/client/assets/{use-status-sounds-DudWi0tR.js → use-status-sounds-kmyo4ncc.js} +1 -1
  235. package/dist/client/assets/{use-tags-BN2t59T_.js → use-tags-dH77QWAi.js} +1 -1
  236. package/dist/client/assets/{use-view-mode-DXxOuUTm.js → use-view-mode-CWAbp_M4.js} +1 -1
  237. package/dist/client/assets/{use-virtual-mcp-CE2lvrwN.js → use-virtual-mcp-DQRWXbcv.js} +1 -1
  238. package/dist/client/assets/useInfiniteQuery-D4aaR12K.js +1 -0
  239. package/dist/client/assets/useSuspenseInfiniteQuery-FTKrOF08.js +1 -0
  240. package/dist/client/assets/{users-COCvGep8.js → users-CQ9RsvIu.js} +1 -1
  241. package/dist/client/assets/{variant-calendar-NUEWKCfJ.js → variant-calendar-Cm-vJHJd.js} +1 -1
  242. package/dist/client/assets/{view-mode-toggle-uxtdvGkq.js → view-mode-toggle-BAznsDzK.js} +1 -1
  243. package/dist/client/index.html +1 -1
  244. package/dist/server/cli.js +3 -3
  245. package/dist/server/server.js +3 -3
  246. package/package.json +1 -1
  247. package/dist/client/assets/api-keys-D7hTNuqp.js +0 -1
  248. package/dist/client/assets/app-editor-CnMywu3-.js +0 -1
  249. package/dist/client/assets/record-editor-BGBP-klp.js +0 -1
  250. package/dist/client/assets/redirect-editor-BwCGTNSS.js +0 -1
  251. package/dist/client/assets/registry-XT_AT1wH.js +0 -2
  252. package/dist/client/assets/settings-layout-7f7HAulD.js +0 -1
  253. package/dist/client/assets/store-registry-tVyVxLd9.js +0 -2
  254. package/dist/client/assets/useInfiniteQuery-rTw2vfoi.js +0 -1
  255. package/dist/client/assets/useSuspenseInfiniteQuery-C9r2I39H.js +0 -1
@@ -1939,7 +1939,7 @@ Usage: deco services <up|down|status>`),process.exit(1)}}var qr1=D(()=>{Fy()});f
1939
1939
  `.execute($);if(Number(W.rows[0]?.cnt)===0){console.warn(`Failed to migrate ${G}/${K}, keeping in old table`);continue}}await bg`
1940
1940
  DELETE FROM kysely_migration WHERE name = ${Q}
1941
1941
  `.execute($)}}async function h1$($){await W64($),await H64($);let Z=new y1$({db:$,provider:{getMigrations:()=>Promise.resolve(Mo0)}}),{error:Q,results:X}=await Z.migrateToLatest(),Y=0;if(X?.forEach((J)=>{if(J.status==="Success")Y++;else if(J.status==="Error")console.error(`Failed to execute migration "${J.migrationName}"`)}),Q)throw console.error("Failed to migrate"),console.error(Q),Q;return Y}async function F64($){let{keepOpen:Z=!1,database:Q,skipBetterAuth:X=!1}=$??{},Y="skipped";if(!X&&!Q)Y=await Xi0();let J=Q??u$(),G=async()=>{if(!Z&&!Q)await uO(J).catch((K)=>{console.warn("Warning: Error closing database:",K)})};try{let K=await h1$(J.db);return await G(),{betterAuth:Y,kysely:K}}catch(K){throw await G(),K}}async function U64(){let $=u$(),Z=new y1$({db:$.db,provider:{getMigrations:()=>Promise.resolve(Mo0)}}),{error:Q,results:X}=await Z.migrateDown();if(X?.forEach((Y)=>{if(Y.status==="Success")console.log(`\u2705 Migration "${Y.migrationName}" rolled back successfully`);else if(Y.status==="Error")console.error(`\u274C Failed to rollback migration "${Y.migrationName}"`)}),Q)throw console.error("Failed to rollback migration"),console.error(Q),Q}var c1$=D(()=>{b1$();Yi0();wQ()});async function BX0($){let Z={...process.env},Q=X60($,Z);console.log(VP1(Q.settings.encryptionKey));let X=Q.settings.betterAuthSecret||(Q.settings.localMode?Ys1(Q.settings.dataDir):""),{ensureServices:Y}=await Promise.resolve().then(() => (DQ0(),OQ0)),{outputs:J,services:G}=await Y({home:Q.settings.dataDir,externalDatabaseUrl:Q.externalDatabaseUrl,externalNatsUrl:Q.externalNatsUrl});if(!Q.skipMigrations){let{migrateBetterAuth:W}=await Promise.resolve().then(() => (Yi0(),Gs1));await W(J.databaseUrl);let{createDatabase:H}=await Promise.resolve().then(() => (wQ(),Aa1)),{migrateToLatest:F}=await Promise.resolve().then(() => (c1$(),u1$)),U=H(J.databaseUrl);await F({keepOpen:!0,database:U,skipBetterAuth:!0})}let K={...Q.settings,betterAuthSecret:X,databaseUrl:J.databaseUrl,natsUrls:J.natsUrls,...J.s3?{s3Endpoint:J.s3.endpoint,s3Bucket:J.s3.bucket,s3AccessKeyId:J.s3.accessKeyId,s3SecretAccessKey:J.s3.secretAccessKey,s3ForcePathStyle:J.s3.forcePathStyle}:{}};return Mr1(K),{settings:K,services:G.map((W)=>({name:W.name==="PostgreSQL"?"Postgres":W.name,port:W.port})),managedServiceNames:G.filter((W)=>W.owner==="managed").map((W)=>W.name)}}var Vo0=D(()=>{Fy();Js1();A$()});var i1$={};e(i1$,{updateService:()=>bE,subscribeCliState:()=>Co0,setTuiConsoleIntercepted:()=>OX0,setServerUrl:()=>hn,setMigrationsDone:()=>gn,setDevMode:()=>B64,resetCliStateForTests:()=>N64,isTuiConsoleIntercepted:()=>DX0,getCliState:()=>So0,addLogEntry:()=>nO});function l1$(){return[{name:"Postgres",status:"pending",port:0},{name:"NATS",status:"pending",port:0}]}function m1$(){return{services:l1$(),migrationsStatus:"pending",serverUrl:null,logs:[]}}function N64(){KY=m1$()}function yn(){for(let $ of ko0)$()}function So0(){return KY}function Co0($){return ko0.add($),()=>ko0.delete($)}function bE($){KY={...KY,services:KY.services.map((Z)=>Z.name===$.name?$:Z)},yn()}function gn(){KY={...KY,migrationsStatus:"done"},yn()}function hn($){KY={...KY,serverUrl:$},yn()}function nO($){let Z=[...KY.logs,$];KY={...KY,logs:Z.length>500?Z.slice(-500):Z},yn()}function B64(){KY={...KY,services:[...l1$(),{name:"API",status:"pending",port:0},{name:"Vite",status:"pending",port:0}]},yn()}function OX0($){d1$=$}function DX0(){return d1$}var KY,ko0,d1$=!1;var yE=D(()=>{KY=m1$();ko0=new Set});import{createServer as p1$}from"net";function O64($){return new Promise((Z)=>{let Q=p1$();Q.once("error",()=>Z(!1)),Q.listen($,"0.0.0.0",()=>{Q.close(()=>Z(!0))})})}async function un($){if(await O64($))return $;let Z=await new Promise((Q,X)=>{let Y=p1$();Y.once("error",X),Y.listen(0,"0.0.0.0",()=>{let J=Y.address(),G=typeof J==="object"&&J?J.port:0;Y.close(()=>Q(G))})});return console.warn(`Port ${$} is in use, using port ${Z} instead.`),Z}var _o0=()=>{};var xo0={};e(xo0,{startDevServer:()=>L64,pipeToLogStore:()=>vo0});import{join as D64}from"path";function vo0($){let Z=$.getReader(),Q=new TextDecoder,X="";function Y(){let J=X.split(`
1942
- `);X=J.pop()??"";for(let G of J){let K=Bun.stripANSI(G).replace(/^\[\d+\]\s*/,"").trim();if(!K)continue;nO({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:K})}}(async()=>{try{for(;;){let{done:J,value:G}=await Z.read();if(J)break;X+=Q.decode(G,{stream:!0}),Y()}}catch{}if(X.trim()){let J=Bun.stripANSI(X).replace(/^\[\d+\]\s*/,"").trim();if(J)nO({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:J})}})()}async function L64($){let{baseUrl:Z,noTui:Q}=$,X=process.env.HOST==="0.0.0.0"&&Boolean(process.env.PORT),Y=X?process.env.PORT:$.vitePort,J=Z||`http://localhost:${Y}`,G=X?await un(Number(Y)+1):await un(Number($.port)),{settings:K,services:W,managedServiceNames:H}=await BX0({port:String(G),home:$.home,baseUrl:$.baseUrl,localMode:$.localMode,skipMigrations:$.skipMigrations,noTui:$.noTui,vitePort:$.vitePort});for(let L of W)bE({name:L.name,status:"ready",port:L.port});gn();let F=D64(import.meta.dir,"..","..","..","..",".."),U=Q===!0,N=Bun.spawn(["bun","run","dev:servers"],{cwd:F,env:{...process.env,PORT:String(K.port),VITE_PORT:String(Y),DATABASE_URL:K.databaseUrl,NATS_URL:K.natsUrls.join(","),NODE_ENV:K.nodeEnv,BASE_URL:J,DECOCMS_LOCAL_MODE:String(K.localMode),DECOCMS_HOME:K.dataDir,DATA_DIR:K.dataDir,DECO_CLI:"1",...K.betterAuthSecret?{BETTER_AUTH_SECRET:K.betterAuthSecret}:{},...K.s3Endpoint?{S3_ENDPOINT:K.s3Endpoint,S3_BUCKET:K.s3Bucket??"",S3_ACCESS_KEY_ID:K.s3AccessKeyId??"",S3_SECRET_ACCESS_KEY:K.s3SecretAccessKey??"",S3_FORCE_PATH_STYLE:String(K.s3ForcePathStyle)}:{},...K.natsCredsPath?{NATS_CREDS:K.natsCredsPath}:{}},stdio:["inherit",U?"inherit":"pipe",U?"inherit":"pipe"]});if(!U)vo0(N.stdout),vo0(N.stderr);hn(J),bE({name:"Vite",status:"ready",port:Number(Y)}),bE({name:"API",status:"ready",port:Number(K.port)});let O=async(L)=>{if(N.kill(L),await N.exited,H.length>0){let{stopServices:w}=await Promise.resolve().then(() => (DQ0(),OQ0));await w(K.dataDir)}};return process.on("SIGINT",()=>O("SIGINT")),process.on("SIGTERM",()=>O("SIGTERM")),{port:Number(Y),process:N}}var fo0=D(()=>{Vo0();yE();_o0()});var LX0;var bo0=D(()=>{LX0={name:"decocms",version:"4.344.1",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"}}});import{Box as j64,Text as n1$}from"ink";import{jsx as E64,jsxs as t1$}from"react/jsx-runtime";function o1$({version:$}){return t1$(j64,{flexDirection:"column",marginTop:1,children:[gQ0.map((Z,Q)=>E64(n1$,{color:hQ0[Q],children:Z},Q)),t1$(n1$,{dimColor:!0,children:[" v",$]})]})}var r1$=D(()=>{Rn()});import{Box as gE,Text as tO}from"ink";import{Spinner as z64}from"@inkjs/ui";import{jsx as TJ,jsxs as yg}from"react/jsx-runtime";function a1$({status:$}){if($==="pending")return TJ(z64,{label:""});return TJ(tO,{color:"green",children:"\u2713"})}function P64($){return`${$.name}: ${$.port||"...."}`}function s1$({services:$,migrationsStatus:Z,home:Q,serverUrl:X}){return yg(gE,{flexDirection:"column",paddingBottom:1,children:[TJ(o1$,{version:LX0.version}),TJ(gE,{marginBottom:1,children:TJ(tO,{dimColor:!0,children:"\u2500".repeat(80)})}),TJ(gE,{children:yg(tO,{dimColor:!0,children:["Home: ",Q]})}),yg(gE,{gap:2,children:[$.map((Y)=>yg(gE,{gap:1,children:[TJ(tO,{children:P64(Y)}),TJ(a1$,{status:Y.status})]},Y.name)),yg(gE,{gap:1,children:[TJ(tO,{children:"Migrations"}),TJ(a1$,{status:Z})]})]}),TJ(gE,{children:X?yg(tO,{children:["Open in browser: ",TJ(tO,{color:"cyan",children:X})]}):TJ(tO,{dimColor:!0,children:"Starting..."})})]})}var e1$=D(()=>{bo0();r1$()});import{Box as A64,Text as cn}from"ink";import{jsx as yo0,jsxs as go0}from"react/jsx-runtime";function T64($){if($>=500)return"red";if($>=400)return"yellow";if($>=300)return"cyan";return"green"}function $$$({logs:$}){return yo0(A64,{flexDirection:"column",children:$.map((Z,Q)=>{if(Z.rawLine)return yo0(cn,{dimColor:!0,children:Z.rawLine},Q);let X=Z.duration<1000?`${Z.duration}ms`:`${(Z.duration/1000).toFixed(1)}s`;return go0(cn,{children:[go0(cn,{dimColor:!0,children:[Z.method.padEnd(6)," ",Z.path.padEnd(30)," "]}),yo0(cn,{color:T64(Z.status),children:Z.status}),go0(cn,{dimColor:!0,children:[" ",X.padStart(8)]})]},Q)})})}var Z$$=()=>{};var ho0={};e(ho0,{App:()=>q64});import{Box as R64}from"ink";import{useSyncExternalStore as I64}from"react";import{jsx as Q$$,jsxs as M64}from"react/jsx-runtime";function q64({home:$}){let Z=I64(Co0,So0);return M64(R64,{flexDirection:"column",children:[Q$$(s1$,{services:Z.services,migrationsStatus:Z.migrationsStatus,home:$,serverUrl:Z.serverUrl}),Q$$($$$,{logs:Z.logs})]})}var uo0=D(()=>{e1$();Z$$();yE()});var OK="thread-gate",nU="decopilot-hosted-harness",tU="decopilot-hosted-harness-sandboxed",lG="automations",oO="background-tools",hE="task-board-github-reads";var X$$="11";function Y$$($){return{name:"decocms",systemDatabaseUrl:$.systemDatabaseUrl,systemDatabaseSchemaName:"dbos",systemDatabasePoolSize:$.poolSize,runAdminServer:!1,executorID:$.executorID,applicationVersion:X$$,...$.listenQueues!==void 0?{listenQueues:$.listenQueues}:{}}}var J$$=()=>{};import V64 from"pg";async function K$$($,Z){let{databaseUrl:Q,lockTimeoutMs:X=k64}=$,Y=$.log??((W)=>console.log(W)),J=new V64.Client({connectionString:Q});await J.connect();let G=Date.now(),K=!1;try{while(!K){if(K=(await J.query("SELECT pg_try_advisory_lock($1) AS locked",[G$$.toString()])).rows[0]?.locked===!0,K)break;if(Date.now()-G>=X)throw Error(`Timed out after ${X}ms waiting for the DBOS migration lock. Another process is still migrating the dbos schema; this pod will restart and retry.`);await B$(S64)}let W=Date.now()-G;if(W>1000)Y(`[dbos] waited ${W}ms for the migration lock; another process migrated first`);return await Z()}finally{if(K)try{await J.query("SELECT pg_advisory_unlock($1)",[G$$.toString()])}catch{}await J.end().catch(()=>{})}}var G$$=8314027461559302n,k64=600000,S64=500;var W$$=D(()=>{C8()});function C64(){let $=(process.env.BUN_OPTIONS??"").split(/\s+/).filter(Boolean);return[...process.argv.slice(1),...$]}function co0($,Z){for(let Q=0;Q<$.length;Q++){let X=$[Q];if(X===void 0)continue;if(X===Z)return $[Q+1];if(X.startsWith(`${Z}=`))return X.slice(Z.length+1)}return}function H$$(){let $=C64();if($.includes("--cpu-prof")){console.log(JSON.stringify({msg:"cpu-profiling-active",dir:co0($,"--cpu-prof-dir")??process.cwd(),name:co0($,"--cpu-prof-name"),markdown:$.includes("--cpu-prof-md"),intervalUs:Number(co0($,"--cpu-prof-interval")??1000),note:"profile is written on process exit"}));return}if(process.env.CPU_PROFILE)console.warn(JSON.stringify({msg:"cpu-profiling-requested-but-inactive",hint:'CPU profiling is a Bun launch flag. Set BUN_OPTIONS="--cpu-prof --cpu-prof-md --cpu-prof-dir=/tmp" before starting the process.'}))}function F$$(){if(process.env.HEAP_WATCH!=="1")return()=>{};let $=Number(process.env.HEAP_WATCH_INTERVAL_MS??60000),Z=async()=>{let Q=_E();if(!Q)return;let X={};try{let{heapStats:Y}=await import("bun:jsc"),J=Y(),G=Object.entries(J.objectTypeCounts).sort((K,W)=>W[1]-K[1]).slice(0,20);X={objectCount:J.objectCount,heapSize:J.heapSize,top:Object.fromEntries(G)}}catch{}console.log(JSON.stringify({msg:"heap-watch",ts:new Date().toISOString(),uptimeS:Math.round(process.uptime()),rss:Q.rss,heapUsed:Q.heapUsed,heapTotal:Q.heapTotal,external:Q.external,arrayBuffers:Q.arrayBuffers,...X}))};return Z().catch(()=>{}),wX0=setInterval(()=>void Z().catch(()=>{}),$),wX0.unref?.(),process.on("SIGUSR2",()=>{try{let Q=Bun.generateHeapSnapshot("v8"),X=typeof Q==="string"?Q:JSON.stringify(Q),Y=`/tmp/heap-${process.pid}-${Date.now()}.heapsnapshot`;Bun.write(Y,X),console.log(JSON.stringify({msg:"heap-snapshot-written",path:Y}))}catch(Q){console.error("[heap-watch] snapshot failed:",Q)}}),()=>{if(wX0)clearInterval(wX0)}}var wX0;var U$$=()=>{};import*as _64 from"bun:jsc";function N$$(){if(process.env.STALL_WATCHDOG!=="1")return()=>{};let $=Number(process.env.STALL_WATCHDOG_MS??100),Z=Number(process.env.STALL_WATCHDOG_TICK_MS??50);try{v64()}catch(J){return console.error("[stall-watchdog] failed to start sampling profiler:",J),()=>{}}let Q,X=performance.now()+Z,Y=()=>{let J=performance.now(),G=J-X;X=J+Z;let K=[];try{K=x64()?.traces??[]}catch{}if(G>$&&K.length>0){let W=new Map;for(let F of K){let U=F.frames.find((O)=>O.sourceURL&&!/Unknown Executable/.test(O.category??""))??F.frames[0];if(!U)continue;let N=(U.sourceURL??"?").replace(/^.*\/node_modules\//,"node_modules/"),B=`${U.name??"?"} @ ${N}:${U.line??"?"}`;W.set(B,(W.get(B)??0)+1)}let H=[...W.entries()].sort((F,U)=>U[1]-F[1]).slice(0,8).map(([F,U])=>({frame:F,count:U}));console.warn(JSON.stringify({msg:"stall-stack",ts:new Date().toISOString(),lagMs:Math.round(G),samplesInWindow:K.length,top:H}))}Q=setTimeout(Y,Z),Q.unref?.()};return Q=setTimeout(Y,Z),Q.unref?.(),()=>{if(Q)clearTimeout(Q)}}var v64,x64;var B$$=D(()=>{({startSamplingProfiler:v64,samplingProfilerStackTraces:x64}=_64)});function O$$(){H$$();let $=[F$$(),Oa1(),N$$()];return()=>{for(let Z of $)Z()}}var D$$=D(()=>{td0();U$$();B$$()});var uE=v((L$$)=>{Object.defineProperty(L$$,"__esModule",{value:!0});L$$.RepublishHeaders=L$$.DirectMsgHeaders=L$$.JsHeaders=L$$.AdvisoryKind=void 0;L$$.isOrderedPushConsumerOptions=f64;L$$.isPullConsumer=b64;L$$.isPushConsumer=y64;L$$.isBoundPushConsumerOptions=g64;function f64($){if($&&typeof $==="object")return"name_prefix"in $||"deliver_subject_prefix"in $||"filter_subjects"in $||"filter_subject"in $||"deliver_policy"in $||"opt_start_seq"in $||"opt_start_time"in $||"replay_policy"in $||"inactive_threshold"in $||"headers_only"in $||"deliver_prefix"in $;return!1}function b64($){return $.isPullConsumer()}function y64($){return $.isPushConsumer()}function g64($){if($&&typeof $==="object")return"deliver_subject"in $||"deliver_group"in $||"idle_heartbeat"in $;return!1}L$$.AdvisoryKind={API:"api_audit",StreamAction:"stream_action",ConsumerAction:"consumer_action",SnapshotCreate:"snapshot_create",SnapshotComplete:"snapshot_complete",RestoreCreate:"restore_create",RestoreComplete:"restore_complete",MaxDeliver:"max_deliver",Terminated:"terminated",Ack:"consumer_ack",StreamLeaderElected:"stream_leader_elected",StreamQuorumLost:"stream_quorum_lost",ConsumerLeaderElected:"consumer_leader_elected",ConsumerQuorumLost:"consumer_quorum_lost"};L$$.JsHeaders={StreamSourceHdr:"Nats-Stream-Source",LastConsumerSeqHdr:"Nats-Last-Consumer",LastStreamSeqHdr:"Nats-Last-Stream",ConsumerStalledHdr:"Nats-Consumer-Stalled",MessageSizeHdr:"Nats-Msg-Size",RollupHdr:"Nats-Rollup",RollupValueSubject:"sub",RollupValueAll:"all",PendingMessagesHdr:"Nats-Pending-Messages",PendingBytesHdr:"Nats-Pending-Bytes",RequiredApiLevel:"Nats-Required-Api-Level"};L$$.DirectMsgHeaders={Stream:"Nats-Stream",Sequence:"Nats-Sequence",TimeStamp:"Nats-Time-Stamp",Subject:"Nats-Subject",LastSequence:"Nats-Last-Sequence",NumPending:"Nats-Num-Pending"};L$$.RepublishHeaders={Stream:"Nats-Stream",Subject:"Nats-Subject",Sequence:"Nats-Sequence",LastSequence:"Nats-Last-Sequence",Size:"Nats-Msg-Size"}});var RJ=v((j$$)=>{Object.defineProperty(j$$,"__esModule",{value:!0});j$$.TD=j$$.TE=j$$.Empty=void 0;j$$.encode=n64;j$$.decode=t64;j$$.Empty=new Uint8Array(0);j$$.TE=new TextEncoder;j$$.TD=new TextDecoder;function p64(...$){let Z=0;for(let Y=0;Y<$.length;Y++)Z+=$[Y].length;let Q=new Uint8Array(Z),X=0;for(let Y=0;Y<$.length;Y++)Q.set($[Y],X),X+=$[Y].length;return Q}function n64(...$){let Z=[];for(let Q=0;Q<$.length;Q++)Z.push(j$$.TE.encode($[Q]));if(Z.length===0)return j$$.Empty;if(Z.length===1)return Z[0];return p64(...Z)}function t64($){if(!$||$.length===0)return"";return j$$.TD.decode($)}});var IJ=v((P$$)=>{Object.defineProperty(P$$,"__esModule",{value:!0});P$$.errors=P$$.PermissionViolationError=P$$.NoRespondersError=P$$.TimeoutError=P$$.RequestError=P$$.ProtocolError=P$$.ConnectionError=P$$.DrainingConnectionError=P$$.ClosedConnectionError=P$$.AuthorizationError=P$$.UserAuthenticationExpiredError=P$$.InvalidOperationError=P$$.InvalidArgumentError=P$$.InvalidSubjectError=void 0;class mo0 extends Error{constructor($,Z){super(`illegal subject: '${$}'`,Z);this.name="InvalidSubjectError"}}P$$.InvalidSubjectError=mo0;class jX0 extends Error{constructor($,Z){super($,Z);this.name="InvalidArgumentError"}static format($,Z,Q){if(Array.isArray(Z)&&Z.length>1)Z=Z[0];if(Array.isArray($))$=$.map((X)=>`'${X}'`),$=$.join(",");else $=`'${$}'`;return new jX0(`${$} ${Z}`,Q)}}P$$.InvalidArgumentError=jX0;class do0 extends Error{constructor($,Z){super($,Z);this.name="InvalidOperationError"}}P$$.InvalidOperationError=do0;class EX0 extends Error{constructor($,Z){super($,Z);this.name="UserAuthenticationExpiredError"}static parse($){if($.toLowerCase().indexOf("user authentication expired")!==-1)return new EX0($);return null}}P$$.UserAuthenticationExpiredError=EX0;class zX0 extends Error{constructor($,Z){super($,Z);this.name="AuthorizationError"}static parse($){let Z=["authorization violation","account authentication expired","authentication timeout"],Q=$.toLowerCase();for(let X=0;X<Z.length;X++)if(Q.indexOf(Z[X])!==-1)return new zX0($);return null}}P$$.AuthorizationError=zX0;class io0 extends Error{constructor(){super("closed connection");this.name="ClosedConnectionError"}}P$$.ClosedConnectionError=io0;class po0 extends Error{constructor(){super("connection draining");this.name="DrainingConnectionError"}}P$$.DrainingConnectionError=po0;class no0 extends Error{constructor($,Z){super($,Z);this.name="ConnectionError"}}P$$.ConnectionError=no0;class to0 extends Error{constructor($,Z){super($,Z);this.name="ProtocolError"}}P$$.ProtocolError=to0;class oo0 extends Error{constructor($="",Z){super($,Z);this.name="RequestError"}isNoResponders(){return this.cause instanceof PX0}}P$$.RequestError=oo0;class ro0 extends Error{constructor($){super("timeout",$);this.name="TimeoutError"}}P$$.TimeoutError=ro0;class PX0 extends Error{subject;constructor($,Z){super(`no responders: '${$}'`,Z);this.subject=$,this.name="NoResponders"}}P$$.NoRespondersError=PX0;class AX0 extends Error{operation;subject;queue;constructor($,Z,Q,X,Y){super($,Y);this.name="PermissionViolationError",this.operation=Z,this.subject=Q,this.queue=X}static parse($){if(($?$.toLowerCase():"").indexOf("permissions violation")===-1)return null;let Q="publish",X="",Y=void 0,J=$.match(/(Publish|Subscription) to "(\S+)"/);if(J){if(Q=J[1].toLowerCase(),X=J[2],Q==="subscription"){let G=$.match(/using queue "(\S+)"/);if(G)Y=G[1]}}return new AX0($,Q,X,Y)}}P$$.PermissionViolationError=AX0;P$$.errors={AuthorizationError:zX0,ClosedConnectionError:io0,ConnectionError:no0,DrainingConnectionError:po0,InvalidArgumentError:jX0,InvalidOperationError:do0,InvalidSubjectError:mo0,NoRespondersError:PX0,PermissionViolationError:AX0,ProtocolError:to0,RequestError:oo0,TimeoutError:ro0,UserAuthenticationExpiredError:EX0}});var DK=v((q$$)=>{Object.defineProperty(q$$,"__esModule",{value:!0});q$$.SimpleMutex=q$$.Perf=void 0;q$$.extend=U54;q$$.render=N54;q$$.timeout=B54;q$$.delay=O54;q$$.deadline=D54;q$$.deferred=so0;q$$.debugDeferred=L54;q$$.shuffle=w54;q$$.collect=j54;q$$.jitter=I$$;q$$.backoff=E54;q$$.nanos=z54;q$$.millis=P54;q$$.randomToken=R54;var F54=RJ(),ao0=IJ();function U54($,...Z){for(let Q=0;Q<Z.length;Q++){let X=Z[Q];Object.keys(X).forEach(function(Y){$[Y]=X[Y]})}return $}function N54($){return F54.TD.decode($).replace(/\n/g,"\u240A").replace(/\r/g,"\u240D")}function B54($,Z=!0){let Q=Z?new ao0.TimeoutError:null,X,Y,J=new Promise((G,K)=>{X={cancel:()=>{if(Y)clearTimeout(Y)}},Y=setTimeout(()=>{if(Q===null)K(new ao0.TimeoutError);else K(Q)},$)});return Object.assign(J,X)}function O54($=0){let Z,Q=new Promise((X)=>{let Y=setTimeout(()=>{X()},$);Z={cancel:()=>{if(Y)clearTimeout(Y),X()}}});return Object.assign(Q,Z)}async function D54($,Z=1000){let Q=so0(),X=setTimeout(()=>{Q.reject(new ao0.TimeoutError)},Z);try{return await Promise.race([$,Q])}finally{clearTimeout(X)}}function so0(){let $={},Z=new Promise((Q,X)=>{$={resolve:Q,reject:X}});return Object.assign(Z,$)}function L54(){let $={},Z=new Promise((Q,X)=>{$={resolve:(Y)=>{console.trace("resolve",Y),Q(Y)},reject:(Y)=>{console.trace("reject"),X(Y)}}});return Object.assign(Z,$)}function w54($){for(let Z=$.length-1;Z>0;Z--){let Q=Math.floor(Math.random()*(Z+1));[$[Z],$[Q]]=[$[Q],$[Z]]}return $}async function j54($){let Z=[];for await(let Q of $)Z.push(Q);return Z}class T$${timers;measures;constructor(){this.timers=new Map,this.measures=new Map}mark($){this.timers.set($,performance.now())}measure($,Z,Q){let X=this.timers.get(Z);if(X===void 0)throw Error(`${Z} is not defined`);let Y=this.timers.get(Q);if(Y===void 0)throw Error(`${Q} is not defined`);this.measures.set($,Y-X)}getEntries(){let $=[];return this.measures.forEach((Z,Q)=>{$.push({name:Q,duration:Z})}),$}}q$$.Perf=T$$;class R$${max;current;waiting;constructor($=1){this.max=$,this.current=0,this.waiting=[]}lock(){if(this.current++,this.current<=this.max)return Promise.resolve();let $=so0();return this.waiting.push($),$}unlock(){this.current--,this.waiting.pop()?.resolve()}}q$$.SimpleMutex=R$$;function I$$($){if($===0)return 0;return Math.floor($/2+Math.random()*$)}function E54($=[0,250,250,500,500,3000,5000]){if(!Array.isArray($))$=[0,250,250,500,500,3000,5000];let Z=$.length-1;return{backoff(Q){return I$$(Q>Z?$[Z]:$[Q])}}}function z54($){return $*1e6}function P54($){return Math.floor($/1e6)}var A54="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",oU=new Uint8Array(62);for(let $=0;$<62;$++)oU[$]=A54.charCodeAt($);var T54=218340105584896;function R54(){let $=Math.floor(Math.random()*T54),Z=$%62,Q=oU[Z];$=($-Z)/62,Z=$%62;let X=oU[Z];$=($-Z)/62,Z=$%62;let Y=oU[Z];$=($-Z)/62,Z=$%62;let J=oU[Z];$=($-Z)/62,Z=$%62;let G=oU[Z];$=($-Z)/62,Z=$%62;let K=oU[Z];$=($-Z)/62,Z=$%62;let W=oU[Z];$=($-Z)/62;let H=oU[$];return String.fromCharCode(Q,X,Y,J,G,K,W,H)}});var x$$=v((_$$)=>{Object.defineProperty(_$$,"__esModule",{value:!0});_$$.nuid=_$$.NuidImpl=void 0;var u54="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",rO=62,RX0=12,S$$=10,V$$=33,c54=333,k$$=RX0+S$$,$r0=new Uint8Array(rO);for(let $=0;$<rO;$++)$r0[$]=u54.charCodeAt($);var TX0=4294967296,C$$=BigInt(rO)**BigInt(S$$),ln=Number(C$$/(1n<<32n)),eo0=Number(C$$%(1n<<32n));function l54($){for(let Z=0;Z<$.length;Z++)$[Z]=Math.floor(Math.random()*256)}function m54($){if(globalThis?.crypto?.getRandomValues)globalThis.crypto.getRandomValues($);else l54($)}class Zr0{buf;cbuf;seqHi;seqLo;inc;inited;constructor(){this.buf=new Uint8Array(k$$),this.cbuf=new Uint8Array(RX0),this.inited=!1}init(){this.inited=!0,this.setPre(),this.initSeqAndInc(),this.fillSeq()}initSeqAndInc(){let $=0;do this.seqHi=Math.floor(Math.random()*(ln+1)),this.seqLo=Math.floor(Math.random()*TX0);while($++<8&&this.seqHi===ln&&this.seqLo>=eo0);if(this.seqHi===ln&&this.seqLo>=eo0)this.seqLo=0;this.inc=Math.random()*(c54-V$$)+V$$|0}setPre(){m54(this.cbuf);for(let $=0;$<RX0;$++)this.buf[$]=$r0[this.cbuf[$]%rO]}fillSeq(){let $=this.seqHi,Z=this.seqLo;for(let Q=k$$-1;Q>=RX0;Q--){let X=Math.floor($/rO),J=($-X*rO)*TX0+Z,G=Math.floor(J/rO),K=J-G*rO;this.buf[Q]=$r0[K],$=X,Z=G}}next(){if(!this.inited)this.init();if(this.seqLo+=this.inc,this.seqLo>=TX0)this.seqLo-=TX0,this.seqHi+=1;if(this.seqHi>ln||this.seqHi===ln&&this.seqLo>=eo0)this.setPre(),this.initSeqAndInc();this.fillSeq();let $=this.buf;return String.fromCharCode($[0],$[1],$[2],$[3],$[4],$[5],$[6],$[7],$[8],$[9],$[10],$[11],$[12],$[13],$[14],$[15],$[16],$[17],$[18],$[19],$[20],$[21])}reset(){this.init()}}_$$.NuidImpl=Zr0;_$$.nuid=new Zr0});var g$$=v((b$$)=>{Object.defineProperty(b$$,"__esModule",{value:!0});b$$.nuid=b$$.Nuid=void 0;var f$$=x$$();b$$.Nuid=f$$.NuidImpl;b$$.nuid=f$$.nuid});var qX0=v((IX0)=>{Object.defineProperty(IX0,"__esModule",{value:!0});IX0.nuid=IX0.Nuid=void 0;var h$$=g$$();Object.defineProperty(IX0,"Nuid",{enumerable:!0,get:function(){return h$$.Nuid}});Object.defineProperty(IX0,"nuid",{enumerable:!0,get:function(){return h$$.nuid}})});var aO=v((u$$)=>{Object.defineProperty(u$$,"__esModule",{value:!0});u$$.DEFAULT_HOST=u$$.DEFAULT_PORT=u$$.Match=void 0;u$$.syncIterator=o54;u$$.createInbox=r54;var n54=qX0(),t54=IJ();u$$.Match={Exact:"exact",CanonicalMIME:"canonical",IgnoreCase:"insensitive"};function o54($){let Z=$[Symbol.asyncIterator]();return{async next(){let Q=await Z.next();if(Q.done)return Promise.resolve(null);return Promise.resolve(Q.value)}}}function r54($=""){if($=$||"_INBOX",typeof $!=="string")throw TypeError("prefix must be a string");return $.split(".").forEach((Z)=>{if(Z==="*"||Z===">")throw t54.InvalidArgumentError.format("prefix",`cannot have wildcards ('${$}')`)}),`${$}.${n54.nuid.next()}`}u$$.DEFAULT_PORT=4222;u$$.DEFAULT_HOST="127.0.0.1"});var mn=v((d$$)=>{Object.defineProperty(d$$,"__esModule",{value:!0});d$$.DataBuffer=void 0;var l$$=RJ();class m$${buffers;byteLength;constructor(){this.buffers=[],this.byteLength=0}static concat(...$){let Z=0;for(let Y=0;Y<$.length;Y++)Z+=$[Y].length;let Q=new Uint8Array(Z),X=0;for(let Y=0;Y<$.length;Y++)Q.set($[Y],X),X+=$[Y].length;return Q}static fromAscii($){if(!$)$="";return l$$.TE.encode($)}static toAscii($){return l$$.TD.decode($)}reset(){this.buffers.length=0,this.byteLength=0}pack(){if(this.buffers.length>1){let $=new Uint8Array(this.byteLength),Z=0;for(let Q=0;Q<this.buffers.length;Q++)$.set(this.buffers[Q],Z),Z+=this.buffers[Q].length;this.buffers.length=0,this.buffers.push($)}}shift(){if(this.buffers.length){let $=this.buffers.shift();if($)return this.byteLength-=$.length,$}return new Uint8Array(0)}drain($){if(this.buffers.length){this.pack();let Z=this.buffers.pop();if(Z){let Q=this.byteLength;if($===void 0||$>Q)$=Q;let X=Z.subarray(0,$);if(Q>$)this.buffers.push(Z.subarray($));return this.byteLength=Q-$,X}}return new Uint8Array(0)}fill($,...Z){if($)this.buffers.push($),this.byteLength+=$.length;for(let Q=0;Q<Z.length;Q++)if(Z[Q]&&Z[Q].length)this.buffers.push(Z[Q]),this.byteLength+=Z[Q].length}peek(){if(this.buffers.length)return this.pack(),this.buffers[0];return new Uint8Array(0)}size(){return this.byteLength}length(){return this.buffers.length}}d$$.DataBuffer=m$$});var cE=v((n$$)=>{Object.defineProperty(n$$,"__esModule",{value:!0});n$$.LF=n$$.CR=n$$.CRLF=n$$.CR_LF_LEN=n$$.CR_LF=void 0;n$$.setTransportFactory=Y94;n$$.defaultPort=J94;n$$.getUrlParseFn=G94;n$$.newTransport=K94;n$$.getResolveFn=W94;n$$.protoLen=p$$;n$$.extractProtocolMessage=H94;var Z94=RJ(),Q94=aO(),X94=mn(),qJ;function Y94($){qJ=$}function J94(){return qJ!==void 0&&qJ.defaultPort!==void 0?qJ.defaultPort:Q94.DEFAULT_PORT}function G94(){return qJ!==void 0&&qJ.urlParseFn?qJ.urlParseFn:void 0}function K94(){if(!qJ||typeof qJ.factory!=="function")throw Error("transport fn is not set");return qJ.factory()}function W94(){return qJ!==void 0&&qJ.dnsResolveFn?qJ.dnsResolveFn:void 0}n$$.CR_LF=`\r
1942
+ `);X=J.pop()??"";for(let G of J){let K=Bun.stripANSI(G).replace(/^\[\d+\]\s*/,"").trim();if(!K)continue;nO({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:K})}}(async()=>{try{for(;;){let{done:J,value:G}=await Z.read();if(J)break;X+=Q.decode(G,{stream:!0}),Y()}}catch{}if(X.trim()){let J=Bun.stripANSI(X).replace(/^\[\d+\]\s*/,"").trim();if(J)nO({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:J})}})()}async function L64($){let{baseUrl:Z,noTui:Q}=$,X=process.env.HOST==="0.0.0.0"&&Boolean(process.env.PORT),Y=X?process.env.PORT:$.vitePort,J=Z||`http://localhost:${Y}`,G=X?await un(Number(Y)+1):await un(Number($.port)),{settings:K,services:W,managedServiceNames:H}=await BX0({port:String(G),home:$.home,baseUrl:$.baseUrl,localMode:$.localMode,skipMigrations:$.skipMigrations,noTui:$.noTui,vitePort:$.vitePort});for(let L of W)bE({name:L.name,status:"ready",port:L.port});gn();let F=D64(import.meta.dir,"..","..","..","..",".."),U=Q===!0,N=Bun.spawn(["bun","run","dev:servers"],{cwd:F,env:{...process.env,PORT:String(K.port),VITE_PORT:String(Y),DATABASE_URL:K.databaseUrl,NATS_URL:K.natsUrls.join(","),NODE_ENV:K.nodeEnv,BASE_URL:J,DECOCMS_LOCAL_MODE:String(K.localMode),DECOCMS_HOME:K.dataDir,DATA_DIR:K.dataDir,DECO_CLI:"1",...K.betterAuthSecret?{BETTER_AUTH_SECRET:K.betterAuthSecret}:{},...K.s3Endpoint?{S3_ENDPOINT:K.s3Endpoint,S3_BUCKET:K.s3Bucket??"",S3_ACCESS_KEY_ID:K.s3AccessKeyId??"",S3_SECRET_ACCESS_KEY:K.s3SecretAccessKey??"",S3_FORCE_PATH_STYLE:String(K.s3ForcePathStyle)}:{},...K.natsCredsPath?{NATS_CREDS:K.natsCredsPath}:{}},stdio:["inherit",U?"inherit":"pipe",U?"inherit":"pipe"]});if(!U)vo0(N.stdout),vo0(N.stderr);hn(J),bE({name:"Vite",status:"ready",port:Number(Y)}),bE({name:"API",status:"ready",port:Number(K.port)});let O=async(L)=>{if(N.kill(L),await N.exited,H.length>0){let{stopServices:w}=await Promise.resolve().then(() => (DQ0(),OQ0));await w(K.dataDir)}};return process.on("SIGINT",()=>O("SIGINT")),process.on("SIGTERM",()=>O("SIGTERM")),{port:Number(Y),process:N}}var fo0=D(()=>{Vo0();yE();_o0()});var LX0;var bo0=D(()=>{LX0={name:"decocms",version:"4.344.2",description:"Deco CMS \u2014 Self-hostable MCP Gateway for managing AI connections and tools",author:"Deco team",repository:{type:"git",url:"git+https://github.com/decocms/studio.git",directory:"apps/api"},bugs:{url:"https://github.com/decocms/studio/issues"},type:"module",bin:{deco:"./dist/server/cli.js"},files:["dist/**/*"],scripts:{dev:"bun run migrate && bun run dev:server","dev:server":"bun run --cwd=../../packages/sandbox build && NODE_ENV=development bun --env-file=.env --hot run src/index.ts",build:"bun run build:server","build:server":"bun run scripts/bundle-server-script.ts --dist ./dist/server","generate:tool-contracts":"bun run scripts/generate-tool-contracts.ts","db:migrate":"bun run ./dist/server/migrate.js","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"}}});import{Box as j64,Text as n1$}from"ink";import{jsx as E64,jsxs as t1$}from"react/jsx-runtime";function o1$({version:$}){return t1$(j64,{flexDirection:"column",marginTop:1,children:[gQ0.map((Z,Q)=>E64(n1$,{color:hQ0[Q],children:Z},Q)),t1$(n1$,{dimColor:!0,children:[" v",$]})]})}var r1$=D(()=>{Rn()});import{Box as gE,Text as tO}from"ink";import{Spinner as z64}from"@inkjs/ui";import{jsx as TJ,jsxs as yg}from"react/jsx-runtime";function a1$({status:$}){if($==="pending")return TJ(z64,{label:""});return TJ(tO,{color:"green",children:"\u2713"})}function P64($){return`${$.name}: ${$.port||"...."}`}function s1$({services:$,migrationsStatus:Z,home:Q,serverUrl:X}){return yg(gE,{flexDirection:"column",paddingBottom:1,children:[TJ(o1$,{version:LX0.version}),TJ(gE,{marginBottom:1,children:TJ(tO,{dimColor:!0,children:"\u2500".repeat(80)})}),TJ(gE,{children:yg(tO,{dimColor:!0,children:["Home: ",Q]})}),yg(gE,{gap:2,children:[$.map((Y)=>yg(gE,{gap:1,children:[TJ(tO,{children:P64(Y)}),TJ(a1$,{status:Y.status})]},Y.name)),yg(gE,{gap:1,children:[TJ(tO,{children:"Migrations"}),TJ(a1$,{status:Z})]})]}),TJ(gE,{children:X?yg(tO,{children:["Open in browser: ",TJ(tO,{color:"cyan",children:X})]}):TJ(tO,{dimColor:!0,children:"Starting..."})})]})}var e1$=D(()=>{bo0();r1$()});import{Box as A64,Text as cn}from"ink";import{jsx as yo0,jsxs as go0}from"react/jsx-runtime";function T64($){if($>=500)return"red";if($>=400)return"yellow";if($>=300)return"cyan";return"green"}function $$$({logs:$}){return yo0(A64,{flexDirection:"column",children:$.map((Z,Q)=>{if(Z.rawLine)return yo0(cn,{dimColor:!0,children:Z.rawLine},Q);let X=Z.duration<1000?`${Z.duration}ms`:`${(Z.duration/1000).toFixed(1)}s`;return go0(cn,{children:[go0(cn,{dimColor:!0,children:[Z.method.padEnd(6)," ",Z.path.padEnd(30)," "]}),yo0(cn,{color:T64(Z.status),children:Z.status}),go0(cn,{dimColor:!0,children:[" ",X.padStart(8)]})]},Q)})})}var Z$$=()=>{};var ho0={};e(ho0,{App:()=>q64});import{Box as R64}from"ink";import{useSyncExternalStore as I64}from"react";import{jsx as Q$$,jsxs as M64}from"react/jsx-runtime";function q64({home:$}){let Z=I64(Co0,So0);return M64(R64,{flexDirection:"column",children:[Q$$(s1$,{services:Z.services,migrationsStatus:Z.migrationsStatus,home:$,serverUrl:Z.serverUrl}),Q$$($$$,{logs:Z.logs})]})}var uo0=D(()=>{e1$();Z$$();yE()});var OK="thread-gate",nU="decopilot-hosted-harness",tU="decopilot-hosted-harness-sandboxed",lG="automations",oO="background-tools",hE="task-board-github-reads";var X$$="11";function Y$$($){return{name:"decocms",systemDatabaseUrl:$.systemDatabaseUrl,systemDatabaseSchemaName:"dbos",systemDatabasePoolSize:$.poolSize,runAdminServer:!1,executorID:$.executorID,applicationVersion:X$$,...$.listenQueues!==void 0?{listenQueues:$.listenQueues}:{}}}var J$$=()=>{};import V64 from"pg";async function K$$($,Z){let{databaseUrl:Q,lockTimeoutMs:X=k64}=$,Y=$.log??((W)=>console.log(W)),J=new V64.Client({connectionString:Q});await J.connect();let G=Date.now(),K=!1;try{while(!K){if(K=(await J.query("SELECT pg_try_advisory_lock($1) AS locked",[G$$.toString()])).rows[0]?.locked===!0,K)break;if(Date.now()-G>=X)throw Error(`Timed out after ${X}ms waiting for the DBOS migration lock. Another process is still migrating the dbos schema; this pod will restart and retry.`);await B$(S64)}let W=Date.now()-G;if(W>1000)Y(`[dbos] waited ${W}ms for the migration lock; another process migrated first`);return await Z()}finally{if(K)try{await J.query("SELECT pg_advisory_unlock($1)",[G$$.toString()])}catch{}await J.end().catch(()=>{})}}var G$$=8314027461559302n,k64=600000,S64=500;var W$$=D(()=>{C8()});function C64(){let $=(process.env.BUN_OPTIONS??"").split(/\s+/).filter(Boolean);return[...process.argv.slice(1),...$]}function co0($,Z){for(let Q=0;Q<$.length;Q++){let X=$[Q];if(X===void 0)continue;if(X===Z)return $[Q+1];if(X.startsWith(`${Z}=`))return X.slice(Z.length+1)}return}function H$$(){let $=C64();if($.includes("--cpu-prof")){console.log(JSON.stringify({msg:"cpu-profiling-active",dir:co0($,"--cpu-prof-dir")??process.cwd(),name:co0($,"--cpu-prof-name"),markdown:$.includes("--cpu-prof-md"),intervalUs:Number(co0($,"--cpu-prof-interval")??1000),note:"profile is written on process exit"}));return}if(process.env.CPU_PROFILE)console.warn(JSON.stringify({msg:"cpu-profiling-requested-but-inactive",hint:'CPU profiling is a Bun launch flag. Set BUN_OPTIONS="--cpu-prof --cpu-prof-md --cpu-prof-dir=/tmp" before starting the process.'}))}function F$$(){if(process.env.HEAP_WATCH!=="1")return()=>{};let $=Number(process.env.HEAP_WATCH_INTERVAL_MS??60000),Z=async()=>{let Q=_E();if(!Q)return;let X={};try{let{heapStats:Y}=await import("bun:jsc"),J=Y(),G=Object.entries(J.objectTypeCounts).sort((K,W)=>W[1]-K[1]).slice(0,20);X={objectCount:J.objectCount,heapSize:J.heapSize,top:Object.fromEntries(G)}}catch{}console.log(JSON.stringify({msg:"heap-watch",ts:new Date().toISOString(),uptimeS:Math.round(process.uptime()),rss:Q.rss,heapUsed:Q.heapUsed,heapTotal:Q.heapTotal,external:Q.external,arrayBuffers:Q.arrayBuffers,...X}))};return Z().catch(()=>{}),wX0=setInterval(()=>void Z().catch(()=>{}),$),wX0.unref?.(),process.on("SIGUSR2",()=>{try{let Q=Bun.generateHeapSnapshot("v8"),X=typeof Q==="string"?Q:JSON.stringify(Q),Y=`/tmp/heap-${process.pid}-${Date.now()}.heapsnapshot`;Bun.write(Y,X),console.log(JSON.stringify({msg:"heap-snapshot-written",path:Y}))}catch(Q){console.error("[heap-watch] snapshot failed:",Q)}}),()=>{if(wX0)clearInterval(wX0)}}var wX0;var U$$=()=>{};import*as _64 from"bun:jsc";function N$$(){if(process.env.STALL_WATCHDOG!=="1")return()=>{};let $=Number(process.env.STALL_WATCHDOG_MS??100),Z=Number(process.env.STALL_WATCHDOG_TICK_MS??50);try{v64()}catch(J){return console.error("[stall-watchdog] failed to start sampling profiler:",J),()=>{}}let Q,X=performance.now()+Z,Y=()=>{let J=performance.now(),G=J-X;X=J+Z;let K=[];try{K=x64()?.traces??[]}catch{}if(G>$&&K.length>0){let W=new Map;for(let F of K){let U=F.frames.find((O)=>O.sourceURL&&!/Unknown Executable/.test(O.category??""))??F.frames[0];if(!U)continue;let N=(U.sourceURL??"?").replace(/^.*\/node_modules\//,"node_modules/"),B=`${U.name??"?"} @ ${N}:${U.line??"?"}`;W.set(B,(W.get(B)??0)+1)}let H=[...W.entries()].sort((F,U)=>U[1]-F[1]).slice(0,8).map(([F,U])=>({frame:F,count:U}));console.warn(JSON.stringify({msg:"stall-stack",ts:new Date().toISOString(),lagMs:Math.round(G),samplesInWindow:K.length,top:H}))}Q=setTimeout(Y,Z),Q.unref?.()};return Q=setTimeout(Y,Z),Q.unref?.(),()=>{if(Q)clearTimeout(Q)}}var v64,x64;var B$$=D(()=>{({startSamplingProfiler:v64,samplingProfilerStackTraces:x64}=_64)});function O$$(){H$$();let $=[F$$(),Oa1(),N$$()];return()=>{for(let Z of $)Z()}}var D$$=D(()=>{td0();U$$();B$$()});var uE=v((L$$)=>{Object.defineProperty(L$$,"__esModule",{value:!0});L$$.RepublishHeaders=L$$.DirectMsgHeaders=L$$.JsHeaders=L$$.AdvisoryKind=void 0;L$$.isOrderedPushConsumerOptions=f64;L$$.isPullConsumer=b64;L$$.isPushConsumer=y64;L$$.isBoundPushConsumerOptions=g64;function f64($){if($&&typeof $==="object")return"name_prefix"in $||"deliver_subject_prefix"in $||"filter_subjects"in $||"filter_subject"in $||"deliver_policy"in $||"opt_start_seq"in $||"opt_start_time"in $||"replay_policy"in $||"inactive_threshold"in $||"headers_only"in $||"deliver_prefix"in $;return!1}function b64($){return $.isPullConsumer()}function y64($){return $.isPushConsumer()}function g64($){if($&&typeof $==="object")return"deliver_subject"in $||"deliver_group"in $||"idle_heartbeat"in $;return!1}L$$.AdvisoryKind={API:"api_audit",StreamAction:"stream_action",ConsumerAction:"consumer_action",SnapshotCreate:"snapshot_create",SnapshotComplete:"snapshot_complete",RestoreCreate:"restore_create",RestoreComplete:"restore_complete",MaxDeliver:"max_deliver",Terminated:"terminated",Ack:"consumer_ack",StreamLeaderElected:"stream_leader_elected",StreamQuorumLost:"stream_quorum_lost",ConsumerLeaderElected:"consumer_leader_elected",ConsumerQuorumLost:"consumer_quorum_lost"};L$$.JsHeaders={StreamSourceHdr:"Nats-Stream-Source",LastConsumerSeqHdr:"Nats-Last-Consumer",LastStreamSeqHdr:"Nats-Last-Stream",ConsumerStalledHdr:"Nats-Consumer-Stalled",MessageSizeHdr:"Nats-Msg-Size",RollupHdr:"Nats-Rollup",RollupValueSubject:"sub",RollupValueAll:"all",PendingMessagesHdr:"Nats-Pending-Messages",PendingBytesHdr:"Nats-Pending-Bytes",RequiredApiLevel:"Nats-Required-Api-Level"};L$$.DirectMsgHeaders={Stream:"Nats-Stream",Sequence:"Nats-Sequence",TimeStamp:"Nats-Time-Stamp",Subject:"Nats-Subject",LastSequence:"Nats-Last-Sequence",NumPending:"Nats-Num-Pending"};L$$.RepublishHeaders={Stream:"Nats-Stream",Subject:"Nats-Subject",Sequence:"Nats-Sequence",LastSequence:"Nats-Last-Sequence",Size:"Nats-Msg-Size"}});var RJ=v((j$$)=>{Object.defineProperty(j$$,"__esModule",{value:!0});j$$.TD=j$$.TE=j$$.Empty=void 0;j$$.encode=n64;j$$.decode=t64;j$$.Empty=new Uint8Array(0);j$$.TE=new TextEncoder;j$$.TD=new TextDecoder;function p64(...$){let Z=0;for(let Y=0;Y<$.length;Y++)Z+=$[Y].length;let Q=new Uint8Array(Z),X=0;for(let Y=0;Y<$.length;Y++)Q.set($[Y],X),X+=$[Y].length;return Q}function n64(...$){let Z=[];for(let Q=0;Q<$.length;Q++)Z.push(j$$.TE.encode($[Q]));if(Z.length===0)return j$$.Empty;if(Z.length===1)return Z[0];return p64(...Z)}function t64($){if(!$||$.length===0)return"";return j$$.TD.decode($)}});var IJ=v((P$$)=>{Object.defineProperty(P$$,"__esModule",{value:!0});P$$.errors=P$$.PermissionViolationError=P$$.NoRespondersError=P$$.TimeoutError=P$$.RequestError=P$$.ProtocolError=P$$.ConnectionError=P$$.DrainingConnectionError=P$$.ClosedConnectionError=P$$.AuthorizationError=P$$.UserAuthenticationExpiredError=P$$.InvalidOperationError=P$$.InvalidArgumentError=P$$.InvalidSubjectError=void 0;class mo0 extends Error{constructor($,Z){super(`illegal subject: '${$}'`,Z);this.name="InvalidSubjectError"}}P$$.InvalidSubjectError=mo0;class jX0 extends Error{constructor($,Z){super($,Z);this.name="InvalidArgumentError"}static format($,Z,Q){if(Array.isArray(Z)&&Z.length>1)Z=Z[0];if(Array.isArray($))$=$.map((X)=>`'${X}'`),$=$.join(",");else $=`'${$}'`;return new jX0(`${$} ${Z}`,Q)}}P$$.InvalidArgumentError=jX0;class do0 extends Error{constructor($,Z){super($,Z);this.name="InvalidOperationError"}}P$$.InvalidOperationError=do0;class EX0 extends Error{constructor($,Z){super($,Z);this.name="UserAuthenticationExpiredError"}static parse($){if($.toLowerCase().indexOf("user authentication expired")!==-1)return new EX0($);return null}}P$$.UserAuthenticationExpiredError=EX0;class zX0 extends Error{constructor($,Z){super($,Z);this.name="AuthorizationError"}static parse($){let Z=["authorization violation","account authentication expired","authentication timeout"],Q=$.toLowerCase();for(let X=0;X<Z.length;X++)if(Q.indexOf(Z[X])!==-1)return new zX0($);return null}}P$$.AuthorizationError=zX0;class io0 extends Error{constructor(){super("closed connection");this.name="ClosedConnectionError"}}P$$.ClosedConnectionError=io0;class po0 extends Error{constructor(){super("connection draining");this.name="DrainingConnectionError"}}P$$.DrainingConnectionError=po0;class no0 extends Error{constructor($,Z){super($,Z);this.name="ConnectionError"}}P$$.ConnectionError=no0;class to0 extends Error{constructor($,Z){super($,Z);this.name="ProtocolError"}}P$$.ProtocolError=to0;class oo0 extends Error{constructor($="",Z){super($,Z);this.name="RequestError"}isNoResponders(){return this.cause instanceof PX0}}P$$.RequestError=oo0;class ro0 extends Error{constructor($){super("timeout",$);this.name="TimeoutError"}}P$$.TimeoutError=ro0;class PX0 extends Error{subject;constructor($,Z){super(`no responders: '${$}'`,Z);this.subject=$,this.name="NoResponders"}}P$$.NoRespondersError=PX0;class AX0 extends Error{operation;subject;queue;constructor($,Z,Q,X,Y){super($,Y);this.name="PermissionViolationError",this.operation=Z,this.subject=Q,this.queue=X}static parse($){if(($?$.toLowerCase():"").indexOf("permissions violation")===-1)return null;let Q="publish",X="",Y=void 0,J=$.match(/(Publish|Subscription) to "(\S+)"/);if(J){if(Q=J[1].toLowerCase(),X=J[2],Q==="subscription"){let G=$.match(/using queue "(\S+)"/);if(G)Y=G[1]}}return new AX0($,Q,X,Y)}}P$$.PermissionViolationError=AX0;P$$.errors={AuthorizationError:zX0,ClosedConnectionError:io0,ConnectionError:no0,DrainingConnectionError:po0,InvalidArgumentError:jX0,InvalidOperationError:do0,InvalidSubjectError:mo0,NoRespondersError:PX0,PermissionViolationError:AX0,ProtocolError:to0,RequestError:oo0,TimeoutError:ro0,UserAuthenticationExpiredError:EX0}});var DK=v((q$$)=>{Object.defineProperty(q$$,"__esModule",{value:!0});q$$.SimpleMutex=q$$.Perf=void 0;q$$.extend=U54;q$$.render=N54;q$$.timeout=B54;q$$.delay=O54;q$$.deadline=D54;q$$.deferred=so0;q$$.debugDeferred=L54;q$$.shuffle=w54;q$$.collect=j54;q$$.jitter=I$$;q$$.backoff=E54;q$$.nanos=z54;q$$.millis=P54;q$$.randomToken=R54;var F54=RJ(),ao0=IJ();function U54($,...Z){for(let Q=0;Q<Z.length;Q++){let X=Z[Q];Object.keys(X).forEach(function(Y){$[Y]=X[Y]})}return $}function N54($){return F54.TD.decode($).replace(/\n/g,"\u240A").replace(/\r/g,"\u240D")}function B54($,Z=!0){let Q=Z?new ao0.TimeoutError:null,X,Y,J=new Promise((G,K)=>{X={cancel:()=>{if(Y)clearTimeout(Y)}},Y=setTimeout(()=>{if(Q===null)K(new ao0.TimeoutError);else K(Q)},$)});return Object.assign(J,X)}function O54($=0){let Z,Q=new Promise((X)=>{let Y=setTimeout(()=>{X()},$);Z={cancel:()=>{if(Y)clearTimeout(Y),X()}}});return Object.assign(Q,Z)}async function D54($,Z=1000){let Q=so0(),X=setTimeout(()=>{Q.reject(new ao0.TimeoutError)},Z);try{return await Promise.race([$,Q])}finally{clearTimeout(X)}}function so0(){let $={},Z=new Promise((Q,X)=>{$={resolve:Q,reject:X}});return Object.assign(Z,$)}function L54(){let $={},Z=new Promise((Q,X)=>{$={resolve:(Y)=>{console.trace("resolve",Y),Q(Y)},reject:(Y)=>{console.trace("reject"),X(Y)}}});return Object.assign(Z,$)}function w54($){for(let Z=$.length-1;Z>0;Z--){let Q=Math.floor(Math.random()*(Z+1));[$[Z],$[Q]]=[$[Q],$[Z]]}return $}async function j54($){let Z=[];for await(let Q of $)Z.push(Q);return Z}class T$${timers;measures;constructor(){this.timers=new Map,this.measures=new Map}mark($){this.timers.set($,performance.now())}measure($,Z,Q){let X=this.timers.get(Z);if(X===void 0)throw Error(`${Z} is not defined`);let Y=this.timers.get(Q);if(Y===void 0)throw Error(`${Q} is not defined`);this.measures.set($,Y-X)}getEntries(){let $=[];return this.measures.forEach((Z,Q)=>{$.push({name:Q,duration:Z})}),$}}q$$.Perf=T$$;class R$${max;current;waiting;constructor($=1){this.max=$,this.current=0,this.waiting=[]}lock(){if(this.current++,this.current<=this.max)return Promise.resolve();let $=so0();return this.waiting.push($),$}unlock(){this.current--,this.waiting.pop()?.resolve()}}q$$.SimpleMutex=R$$;function I$$($){if($===0)return 0;return Math.floor($/2+Math.random()*$)}function E54($=[0,250,250,500,500,3000,5000]){if(!Array.isArray($))$=[0,250,250,500,500,3000,5000];let Z=$.length-1;return{backoff(Q){return I$$(Q>Z?$[Z]:$[Q])}}}function z54($){return $*1e6}function P54($){return Math.floor($/1e6)}var A54="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",oU=new Uint8Array(62);for(let $=0;$<62;$++)oU[$]=A54.charCodeAt($);var T54=218340105584896;function R54(){let $=Math.floor(Math.random()*T54),Z=$%62,Q=oU[Z];$=($-Z)/62,Z=$%62;let X=oU[Z];$=($-Z)/62,Z=$%62;let Y=oU[Z];$=($-Z)/62,Z=$%62;let J=oU[Z];$=($-Z)/62,Z=$%62;let G=oU[Z];$=($-Z)/62,Z=$%62;let K=oU[Z];$=($-Z)/62,Z=$%62;let W=oU[Z];$=($-Z)/62;let H=oU[$];return String.fromCharCode(Q,X,Y,J,G,K,W,H)}});var x$$=v((_$$)=>{Object.defineProperty(_$$,"__esModule",{value:!0});_$$.nuid=_$$.NuidImpl=void 0;var u54="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",rO=62,RX0=12,S$$=10,V$$=33,c54=333,k$$=RX0+S$$,$r0=new Uint8Array(rO);for(let $=0;$<rO;$++)$r0[$]=u54.charCodeAt($);var TX0=4294967296,C$$=BigInt(rO)**BigInt(S$$),ln=Number(C$$/(1n<<32n)),eo0=Number(C$$%(1n<<32n));function l54($){for(let Z=0;Z<$.length;Z++)$[Z]=Math.floor(Math.random()*256)}function m54($){if(globalThis?.crypto?.getRandomValues)globalThis.crypto.getRandomValues($);else l54($)}class Zr0{buf;cbuf;seqHi;seqLo;inc;inited;constructor(){this.buf=new Uint8Array(k$$),this.cbuf=new Uint8Array(RX0),this.inited=!1}init(){this.inited=!0,this.setPre(),this.initSeqAndInc(),this.fillSeq()}initSeqAndInc(){let $=0;do this.seqHi=Math.floor(Math.random()*(ln+1)),this.seqLo=Math.floor(Math.random()*TX0);while($++<8&&this.seqHi===ln&&this.seqLo>=eo0);if(this.seqHi===ln&&this.seqLo>=eo0)this.seqLo=0;this.inc=Math.random()*(c54-V$$)+V$$|0}setPre(){m54(this.cbuf);for(let $=0;$<RX0;$++)this.buf[$]=$r0[this.cbuf[$]%rO]}fillSeq(){let $=this.seqHi,Z=this.seqLo;for(let Q=k$$-1;Q>=RX0;Q--){let X=Math.floor($/rO),J=($-X*rO)*TX0+Z,G=Math.floor(J/rO),K=J-G*rO;this.buf[Q]=$r0[K],$=X,Z=G}}next(){if(!this.inited)this.init();if(this.seqLo+=this.inc,this.seqLo>=TX0)this.seqLo-=TX0,this.seqHi+=1;if(this.seqHi>ln||this.seqHi===ln&&this.seqLo>=eo0)this.setPre(),this.initSeqAndInc();this.fillSeq();let $=this.buf;return String.fromCharCode($[0],$[1],$[2],$[3],$[4],$[5],$[6],$[7],$[8],$[9],$[10],$[11],$[12],$[13],$[14],$[15],$[16],$[17],$[18],$[19],$[20],$[21])}reset(){this.init()}}_$$.NuidImpl=Zr0;_$$.nuid=new Zr0});var g$$=v((b$$)=>{Object.defineProperty(b$$,"__esModule",{value:!0});b$$.nuid=b$$.Nuid=void 0;var f$$=x$$();b$$.Nuid=f$$.NuidImpl;b$$.nuid=f$$.nuid});var qX0=v((IX0)=>{Object.defineProperty(IX0,"__esModule",{value:!0});IX0.nuid=IX0.Nuid=void 0;var h$$=g$$();Object.defineProperty(IX0,"Nuid",{enumerable:!0,get:function(){return h$$.Nuid}});Object.defineProperty(IX0,"nuid",{enumerable:!0,get:function(){return h$$.nuid}})});var aO=v((u$$)=>{Object.defineProperty(u$$,"__esModule",{value:!0});u$$.DEFAULT_HOST=u$$.DEFAULT_PORT=u$$.Match=void 0;u$$.syncIterator=o54;u$$.createInbox=r54;var n54=qX0(),t54=IJ();u$$.Match={Exact:"exact",CanonicalMIME:"canonical",IgnoreCase:"insensitive"};function o54($){let Z=$[Symbol.asyncIterator]();return{async next(){let Q=await Z.next();if(Q.done)return Promise.resolve(null);return Promise.resolve(Q.value)}}}function r54($=""){if($=$||"_INBOX",typeof $!=="string")throw TypeError("prefix must be a string");return $.split(".").forEach((Z)=>{if(Z==="*"||Z===">")throw t54.InvalidArgumentError.format("prefix",`cannot have wildcards ('${$}')`)}),`${$}.${n54.nuid.next()}`}u$$.DEFAULT_PORT=4222;u$$.DEFAULT_HOST="127.0.0.1"});var mn=v((d$$)=>{Object.defineProperty(d$$,"__esModule",{value:!0});d$$.DataBuffer=void 0;var l$$=RJ();class m$${buffers;byteLength;constructor(){this.buffers=[],this.byteLength=0}static concat(...$){let Z=0;for(let Y=0;Y<$.length;Y++)Z+=$[Y].length;let Q=new Uint8Array(Z),X=0;for(let Y=0;Y<$.length;Y++)Q.set($[Y],X),X+=$[Y].length;return Q}static fromAscii($){if(!$)$="";return l$$.TE.encode($)}static toAscii($){return l$$.TD.decode($)}reset(){this.buffers.length=0,this.byteLength=0}pack(){if(this.buffers.length>1){let $=new Uint8Array(this.byteLength),Z=0;for(let Q=0;Q<this.buffers.length;Q++)$.set(this.buffers[Q],Z),Z+=this.buffers[Q].length;this.buffers.length=0,this.buffers.push($)}}shift(){if(this.buffers.length){let $=this.buffers.shift();if($)return this.byteLength-=$.length,$}return new Uint8Array(0)}drain($){if(this.buffers.length){this.pack();let Z=this.buffers.pop();if(Z){let Q=this.byteLength;if($===void 0||$>Q)$=Q;let X=Z.subarray(0,$);if(Q>$)this.buffers.push(Z.subarray($));return this.byteLength=Q-$,X}}return new Uint8Array(0)}fill($,...Z){if($)this.buffers.push($),this.byteLength+=$.length;for(let Q=0;Q<Z.length;Q++)if(Z[Q]&&Z[Q].length)this.buffers.push(Z[Q]),this.byteLength+=Z[Q].length}peek(){if(this.buffers.length)return this.pack(),this.buffers[0];return new Uint8Array(0)}size(){return this.byteLength}length(){return this.buffers.length}}d$$.DataBuffer=m$$});var cE=v((n$$)=>{Object.defineProperty(n$$,"__esModule",{value:!0});n$$.LF=n$$.CR=n$$.CRLF=n$$.CR_LF_LEN=n$$.CR_LF=void 0;n$$.setTransportFactory=Y94;n$$.defaultPort=J94;n$$.getUrlParseFn=G94;n$$.newTransport=K94;n$$.getResolveFn=W94;n$$.protoLen=p$$;n$$.extractProtocolMessage=H94;var Z94=RJ(),Q94=aO(),X94=mn(),qJ;function Y94($){qJ=$}function J94(){return qJ!==void 0&&qJ.defaultPort!==void 0?qJ.defaultPort:Q94.DEFAULT_PORT}function G94(){return qJ!==void 0&&qJ.urlParseFn?qJ.urlParseFn:void 0}function K94(){if(!qJ||typeof qJ.factory!=="function")throw Error("transport fn is not set");return qJ.factory()}function W94(){return qJ!==void 0&&qJ.dnsResolveFn?qJ.dnsResolveFn:void 0}n$$.CR_LF=`\r
1943
1943
  `;n$$.CR_LF_LEN=n$$.CR_LF.length;n$$.CRLF=X94.DataBuffer.fromAscii(n$$.CR_LF);n$$.CR=new Uint8Array(n$$.CRLF)[0];n$$.LF=new Uint8Array(n$$.CRLF)[1];function p$$($){for(let Z=0;Z<$.length;Z++){let Q=Z+1;if($.byteLength>Q&&$[Z]===n$$.CR&&$[Q]===n$$.LF)return Q+1}return 0}function H94($){let Z=p$$($);if(Z>0){let X=new Uint8Array($).slice(0,Z);return Z94.TD.decode(X)}return""}});var Gr0=v((Z8$)=>{Object.defineProperty(Z8$,"__esModule",{value:!0});Z8$.ipV4=s$$;Z8$.isIP=z94;Z8$.parseIP=e$$;var dn=4,lE=16,MX0=48,a$$=57,o$$=65,j94=70,r$$=97,E94=102,Jr0=16777215;function s$$($,Z,Q,X){let Y=new Uint8Array(lE);return[0,0,0,0,0,0,0,0,0,0,255,255].forEach((G,K)=>{Y[K]=G}),Y[12]=$,Y[13]=Z,Y[14]=Q,Y[15]=X,Y}function z94($){return e$$($)!==void 0}function e$$($){for(let Z=0;Z<$.length;Z++)switch($[Z]){case".":return $8$($);case":":return P94($)}return}function $8$($){let Z=new Uint8Array(dn);for(let Q=0;Q<dn;Q++){if($.length===0)return;if(Q>0){if($[0]!==".")return;$=$.substring(1)}let{n:X,c:Y,ok:J}=A94($);if(!J||X>255)return;$=$.substring(Y),Z[Q]=X}return s$$(Z[0],Z[1],Z[2],Z[3])}function P94($){let Z=new Uint8Array(lE),Q=-1;if($.length>=2&&$[0]===":"&&$[1]===":"){if(Q=0,$=$.substring(2),$.length===0)return Z}let X=0;while(X<lE){let{n:Y,c:J,ok:G}=T94($);if(!G||Y>65535)return;if(J<$.length&&$[J]==="."){if(Q<0&&X!=lE-dn)return;if(X+dn>lE)return;let K=$8$($);if(K===void 0)return;Z[X]=K[12],Z[X+1]=K[13],Z[X+2]=K[14],Z[X+3]=K[15],$="",X+=dn;break}if(Z[X]=Y>>8,Z[X+1]=Y,X+=2,$=$.substring(J),$.length===0)break;if($[0]!==":"||$.length==1)return;if($=$.substring(1),$[0]===":"){if(Q>=0)return;if(Q=X,$=$.substring(1),$.length===0)break}}if($.length!==0)return;if(X<lE){if(Q<0)return;let Y=lE-X;for(let J=X-1;J>=Q;J--)Z[J+Y]=Z[J];for(let J=Q+Y-1;J>=Q;J--)Z[J]=0}else if(Q>=0)return;return Z}function A94($){let Z=0,Q=0;for(Z=0;Z<$.length&&MX0<=$.charCodeAt(Z)&&$.charCodeAt(Z)<=a$$;Z++)if(Q=Q*10+($.charCodeAt(Z)-MX0),Q>=Jr0)return{n:Jr0,c:Z,ok:!1};if(Z===0)return{n:0,c:0,ok:!1};return{n:Q,c:Z,ok:!0}}function T94($){let Z=0,Q=0;for(Q=0;Q<$.length;Q++){if(MX0<=$.charCodeAt(Q)&&$.charCodeAt(Q)<=a$$)Z*=16,Z+=$.charCodeAt(Q)-MX0;else if(r$$<=$.charCodeAt(Q)&&$.charCodeAt(Q)<=E94)Z*=16,Z+=$.charCodeAt(Q)-r$$+10;else if(o$$<=$.charCodeAt(Q)&&$.charCodeAt(Q)<=j94)Z*=16,Z+=$.charCodeAt(Q)-o$$+10;else break;if(Z>=Jr0)return{n:0,c:Q,ok:!1}}if(Q===0)return{n:0,c:Q,ok:!1};return{n:Z,c:Q,ok:!0}}});var Nr0=v((X8$)=>{Object.defineProperty(X8$,"__esModule",{value:!0});X8$.Servers=X8$.ServerImpl=void 0;X8$.isIPV4OrHostname=Q8$;X8$.hostPort=Ur0;var Kr0=cE(),Wr0=DK(),Hr0=Gr0(),M94=aO(),V94=IJ();function Q8$($){if($.indexOf("[")!==-1||$.indexOf("::")!==-1)return!1;if($.indexOf(".")!==-1)return!0;if($.split(":").length<=2)return!0;return!1}function Fr0($){return!Q8$($)}function k94($){let Q=$.toUpperCase().indexOf("::FFFF:");if(Q!==-1&&$.indexOf(".")!==-1){let X=$.substring(Q+7);return X=X.replace("[",""),X.replace("]","")}return $}function Ur0($){if($=$.trim(),$.match(/^(.*:\/\/)(.*)/m))$=$.replace(/^(.*:\/\/)(.*)/gm,"$2");if($=k94($),Fr0($)&&$.indexOf("[")===-1)$=`[${$}]`;let Z=Fr0($)?$.match(/(]:)(\d+)/):$.match(/(:)(\d+)/),Q=Z&&Z.length===3&&Z[1]&&Z[2]?parseInt(Z[2]):M94.DEFAULT_PORT,Y=new URL(`${Q===80?"https":"http"}://${$}`);Y.port=`${Q}`;let J=Y.hostname;if(J.charAt(0)==="[")J=J.substring(1,J.length-1);return{listen:Y.host,hostname:J,port:Q}}class gg{src;listen;hostname;port;didConnect;reconnects;lastConnect;gossiped;tlsName;resolves;constructor($,Z=!1){this.src=$,this.tlsName="";let Q=Ur0($);this.listen=Q.listen,this.hostname=Q.hostname,this.port=Q.port,this.didConnect=!1,this.reconnects=0,this.lastConnect=0,this.gossiped=Z}toString(){return this.listen}async resolve($){if(!$.fn||$.resolve===!1)return[this];let Z=[];if((0,Hr0.isIP)(this.hostname))return[this];else{let Q=await $.fn(this.hostname);if($.debug)console.log(`resolve ${this.hostname} = ${Q.join(",")}`);for(let X of Q){let Y=this.port===80?"https":"http",J=new URL(`${Y}://${Fr0(X)?"["+X+"]":X}`);J.port=`${this.port}`;let G=new gg(J.host,!1);G.tlsName=this.hostname,Z.push(G)}}if($.randomize)(0,Wr0.shuffle)(Z);return this.resolves=Z,Z}}X8$.ServerImpl=gg;class VX0{firstSelect;servers;currentServer;tlsName;randomize;constructor($={}){this.firstSelect=!0,this.servers=[],this.tlsName="",this.randomize=$.randomize||!1}setServers($){if(!Array.isArray($)||$.length===0)throw V94.InvalidArgumentError.format("servers","cannot be empty");let Z=(0,Kr0.getUrlParseFn)(),Q=new Map;for(let Y of this.servers)Q.set(Y.listen,Y);let X=[];for(let Y of $){Y=Z?Z(Y):Y;let{listen:J}=Ur0(Y),G=Q.get(J);if(G)G.gossiped=!1,X.push(G);else X.push(new gg(Y))}if(this.randomize)(0,Wr0.shuffle)(X);if(this.servers=X,this.currentServer===void 0||!X.includes(this.currentServer))this.currentServer=X[0],this.firstSelect=!0}clear(){this.servers.length=0}updateTLSName(){let $=this.getCurrentServer();if(!(0,Hr0.isIP)($.hostname))this.tlsName=$.hostname,this.servers.forEach((Z)=>{if(Z.gossiped)Z.tlsName=this.tlsName})}getCurrentServer(){return this.currentServer}addServer($,Z=!1){let Q=(0,Kr0.getUrlParseFn)();$=Q?Q($):$;let X=new gg($,Z);if((0,Hr0.isIP)(X.hostname))X.tlsName=this.tlsName;this.servers.push(X)}selectServer(){if(this.firstSelect)return this.firstSelect=!1,this.currentServer;let $=this.servers.shift();if($)this.servers.push($),this.currentServer=$;return $}removeCurrentServer(){this.removeServer(this.currentServer)}removeServer($){if($){let Z=this.servers.indexOf($);this.servers.splice(Z,1)}}snapshot(){return VX0.freezeAll(this.servers)}snapshotForHandler(){let $=this.currentServer;if(!$)return this.snapshot();let Z=this.servers.indexOf($);if(Z<=0)return this.snapshot();return VX0.freezeAll([$,...this.servers.slice(0,Z),...this.servers.slice(Z+1)])}static freezeAll($){return $.map((Z)=>Object.freeze({hostname:Z.hostname,port:Z.port,listen:Z.listen,src:Z.src,tlsName:Z.tlsName,reconnects:Z.reconnects,lastConnect:Z.lastConnect,gossiped:Z.gossiped,didConnect:Z.didConnect}))}find($){return this.servers.find((Z)=>Z.listen===$.listen)}setCurrent($){this.currentServer=$}length(){return this.servers.length}next(){return this.servers.length?this.servers[0]:void 0}getServers(){return this.servers}update($,Z){let Q=[],X=[],Y=(0,Kr0.getUrlParseFn)(),J=new Map;if($.connect_urls&&$.connect_urls.length>0)$.connect_urls.forEach((K)=>{K=Y?Y(K,Z):K;let W=new gg(K,!0);J.set(K,W)});let G=[];if(this.servers.forEach((K,W)=>{let H=K.listen;if(K.gossiped&&this.currentServer.listen!==H&&J.get(H)===void 0)G.push(W);J.delete(H)}),G.reverse(),G.forEach((K)=>{let W=this.servers.splice(K,1);X=X.concat(W[0].listen)}),J.forEach((K,W)=>{this.servers.push(K),Q.push(W)}),this.randomize&&Q.length>0){let K=this.currentServer,W=this.servers.filter((H)=>H!==K);(0,Wr0.shuffle)(W),this.servers=K?[K,...W]:W}return{added:Q,deleted:X}}}X8$.Servers=VX0});var kX0=v((K8$)=>{Object.defineProperty(K8$,"__esModule",{value:!0});K8$.QueuedIteratorImpl=void 0;var Br0=DK(),J8$=IJ();class G8${inflight;processed;received;noIterator;iterClosed;done;signal;yields;filtered;pendingFiltered;ctx;_data;err;time;profile;yielding;didBreak;constructor(){this.inflight=0,this.filtered=0,this.pendingFiltered=0,this.processed=0,this.received=0,this.noIterator=!1,this.done=!1,this.signal=(0,Br0.deferred)(),this.yields=[],this.iterClosed=(0,Br0.deferred)(),this.time=0,this.yielding=!1,this.didBreak=!1,this.profile=!1}[Symbol.asyncIterator](){return this.iterate()}push($){if(this.done)return;if(this.didBreak){if(typeof $==="function"){let Z=$;try{Z()}catch(Q){}}return}if(typeof $==="function")this.pendingFiltered++;this.yields.push($),this.signal.resolve()}async*iterate(){if(this.noIterator)throw new J8$.InvalidOperationError("iterator cannot be used when a callback is registered");if(this.yielding)throw new J8$.InvalidOperationError("iterator is already yielding");this.yielding=!0;try{while(!0){if(this.yields.length===0)await this.signal;if(this.err)throw this.err;let $=this.yields;this.inflight=$.length,this.yields=[];for(let Z=0;Z<$.length;Z++){if(typeof $[Z]==="function"){this.pendingFiltered--;let X=$[Z];try{X()}catch(Y){throw Y}if(this.err)throw this.err;continue}this.processed++,this.inflight--;let Q=this.profile?Date.now():0;yield $[Z],this.time=this.profile?Date.now()-Q:0}if(this.done)break;else if(this.yields.length===0)$.length=0,this.yields=$,this.signal=(0,Br0.deferred)()}}finally{this.didBreak=!0,this.stop()}}stop($){if(this.done)return;this.err=$,this.done=!0,this.signal.resolve(),this.iterClosed.resolve($)}getProcessed(){return this.noIterator?this.received:this.processed}getPending(){return this.yields.length+this.inflight-this.pendingFiltered}getReceived(){return this.received-this.filtered}}K8$.QueuedIteratorImpl=G8$});var Or0=v((U8$)=>{Object.defineProperty(U8$,"__esModule",{value:!0});U8$.MuxSubscription=void 0;var v94=aO(),H8$=IJ();class F8${baseInbox;reqs;constructor(){this.reqs=new Map}size(){return this.reqs.size}init($){return this.baseInbox=`${(0,v94.createInbox)($)}.`,this.baseInbox}add($){if(!isNaN($.received))$.received=0;this.reqs.set($.token,$)}get($){return this.reqs.get($)}cancel($){this.reqs.delete($.token)}getToken($){let Z=$.subject||"";if(Z.indexOf(this.baseInbox)===0)return Z.substring(this.baseInbox.length);return null}all(){return Array.from(this.reqs.values())}handleError($,Z){if($)return this.all().forEach((Q)=>{Q.resolver(Z,{})}),!0;if(Z.operation==="publish"){let Q=this.all().find((X)=>{return X.requestSubject===Z.subject});if(Q)return Q.resolver(Z,{}),!0}return!1}dispatcher(){return($,Z)=>{let Q=this.getToken(Z);if(Q){let X=this.get(Q);if(X){if($===null)$=Z?.data?.length===0&&Z.headers?.code===503?new H8$.NoRespondersError(X.requestSubject):null;X.resolver($,Z)}}}}close(){let $=new H8$.RequestError("connection closed");this.reqs.forEach((Z)=>{Z.resolver($,{})})}}U8$.MuxSubscription=F8$});var Dr0=v((O8$)=>{Object.defineProperty(O8$,"__esModule",{value:!0});O8$.Heartbeat=void 0;var x94=DK();class B8${ph;interval;maxOut;timer;pendings;constructor($,Z,Q){this.ph=$,this.interval=Z,this.maxOut=Q,this.pendings=[]}start(){this.cancel(),this._schedule()}cancel($){if(this.timer)clearTimeout(this.timer),this.timer=void 0;if(this._reset(),$)this.ph.disconnect()}_schedule(){this.timer=setTimeout(()=>{if(this.ph.dispatchStatus({type:"ping",pendingPings:this.pendings.length+1}),this.pendings.length===this.maxOut){this.cancel(!0);return}let $=(0,x94.deferred)();this.ph.flush($).then(()=>{this._reset()}).catch(()=>{this.cancel()}),this.pendings.push($),this._schedule()},this.interval)}_reset(){this.pendings=this.pendings.filter(($)=>{return $.resolve(),!1})}}O8$.Heartbeat=B8$});var jr0=v((E8$)=>{Object.defineProperty(E8$,"__esModule",{value:!0});E8$.DenoBuffer=E8$.MAX_SIZE=E8$.AssertionError=void 0;E8$.assert=w8$;E8$.concat=j8$;E8$.append=b94;E8$.readAll=y94;E8$.writeAll=g94;var f94=RJ();class Lr0 extends Error{constructor($){super($);this.name="AssertionError"}}E8$.AssertionError=Lr0;function w8$($,Z="Assertion failed."){if(!$)throw new Lr0(Z)}var L8$=32768;E8$.MAX_SIZE=4294967294;function SX0($,Z,Q=0){let X=Z.byteLength-Q;if($.byteLength>X)$=$.subarray(0,X);return Z.set($,Q),$.byteLength}function j8$($,Z){if($===void 0&&Z===void 0)return new Uint8Array(0);if($===void 0)return Z;if(Z===void 0)return $;let Q=new Uint8Array($.length+Z.length);return Q.set($,0),Q.set(Z,$.length),Q}function b94($,Z){return j8$($,Uint8Array.of(Z))}class wr0{_buf;_off;constructor($){if(this._off=0,$==null){this._buf=new Uint8Array(0);return}this._buf=new Uint8Array($)}bytes($={copy:!0}){if($.copy===!1)return this._buf.subarray(this._off);return this._buf.slice(this._off)}empty(){return this._buf.byteLength<=this._off}get length(){return this._buf.byteLength-this._off}get capacity(){return this._buf.buffer.byteLength}truncate($){if($===0){this.reset();return}if($<0||$>this.length)throw Error("bytes.Buffer: truncation out of range");this._reslice(this._off+$)}reset(){this._reslice(0),this._off=0}_tryGrowByReslice($){let Z=this._buf.byteLength;if($<=this.capacity-Z)return this._reslice(Z+$),Z;return-1}_reslice($){w8$($<=this._buf.buffer.byteLength),this._buf=new Uint8Array(this._buf.buffer,0,$)}readByte(){let $=new Uint8Array(1);if(this.read($))return $[0];return null}read($){if(this.empty()){if(this.reset(),$.byteLength===0)return 0;return null}let Z=SX0(this._buf.subarray(this._off),$);return this._off+=Z,Z}writeByte($){return this.write(Uint8Array.of($))}writeString($){return this.write(f94.TE.encode($))}write($){let Z=this._grow($.byteLength);return SX0($,this._buf,Z)}_grow($){let Z=this.length;if(Z===0&&this._off!==0)this.reset();let Q=this._tryGrowByReslice($);if(Q>=0)return Q;let X=this.capacity;if($<=Math.floor(X/2)-Z)SX0(this._buf.subarray(this._off),this._buf);else if(X+$>E8$.MAX_SIZE)throw Error("The buffer cannot be grown beyond the maximum size.");else{let Y=new Uint8Array(Math.min(2*X+$,E8$.MAX_SIZE));SX0(this._buf.subarray(this._off),Y),this._buf=Y}return this._off=0,this._reslice(Math.min(Z+$,E8$.MAX_SIZE)),Z}grow($){if($<0)throw Error("Buffer._grow: negative count");let Z=this._grow($);this._reslice(Z)}readFrom($){let Z=0,Q=new Uint8Array(L8$);while(!0){let X=this.capacity-this.length<L8$,Y=X?Q:new Uint8Array(this._buf.buffer,this.length),J=$.read(Y);if(J===null)return Z;if(X)this.write(Y.subarray(0,J));else this._reslice(this.length+J);Z+=J}}}E8$.DenoBuffer=wr0;function y94($){let Z=new wr0;return Z.readFrom($),Z.bytes()}function g94($,Z){let Q=0;while(Q<Z.length)Q+=$.write(Z.subarray(Q))}});var Pr0=v((R8$)=>{Object.defineProperty(R8$,"__esModule",{value:!0});R8$.cc=R8$.State=R8$.Parser=R8$.Kind=void 0;R8$.describe=i94;var Er0=jr0(),zr0=RJ();R8$.Kind={OK:0,ERR:1,MSG:2,INFO:3,PING:4,PONG:5};function i94($){let Z,Q="";switch($.kind){case R8$.Kind.MSG:Z="MSG";break;case R8$.Kind.OK:Z="OK";break;case R8$.Kind.ERR:Z="ERR",Q=zr0.TD.decode($.data);break;case R8$.Kind.PING:Z="PING";break;case R8$.Kind.PONG:Z="PONG";break;case R8$.Kind.INFO:Z="INFO",Q=zr0.TD.decode($.data)}return`${Z}: ${Q}`}function P8$(){let $={};return $.sid=-1,$.hdr=-1,$.size=-1,$}var A8$=48,p94=57,hg=67108864;class T8${dispatcher;state;as;drop;hdr;ma;argBuf;msgBuf;constructor($){this.dispatcher=$,this.state=R8$.State.OP_START,this.as=0,this.drop=0,this.hdr=0}parse($){let Z;for(Z=0;Z<$.length;Z++){let Q=$[Z];switch(this.state){case R8$.State.OP_START:switch(Q){case R8$.cc.M:case R8$.cc.m:this.state=R8$.State.OP_M,this.hdr=-1,this.ma=P8$();break;case R8$.cc.H:case R8$.cc.h:this.state=R8$.State.OP_H,this.hdr=0,this.ma=P8$();break;case R8$.cc.P:case R8$.cc.p:this.state=R8$.State.OP_P;break;case R8$.cc.PLUS:this.state=R8$.State.OP_PLUS;break;case R8$.cc.MINUS:this.state=R8$.State.OP_MINUS;break;case R8$.cc.I:case R8$.cc.i:this.state=R8$.State.OP_I;break;default:throw this.fail($.subarray(Z))}break;case R8$.State.OP_H:switch(Q){case R8$.cc.M:case R8$.cc.m:this.state=R8$.State.OP_M;break;default:throw this.fail($.subarray(Z))}break;case R8$.State.OP_M:switch(Q){case R8$.cc.S:case R8$.cc.s:this.state=R8$.State.OP_MS;break;default:throw this.fail($.subarray(Z))}break;case R8$.State.OP_MS:switch(Q){case R8$.cc.G:case R8$.cc.g:this.state=R8$.State.OP_MSG;break;default:throw this.fail($.subarray(Z))}break;case R8$.State.OP_MSG:switch(Q){case R8$.cc.SPACE:case R8$.cc.TAB:this.state=R8$.State.OP_MSG_SPC;break;default:throw this.fail($.subarray(Z))}break;case R8$.State.OP_MSG_SPC:switch(Q){case R8$.cc.SPACE:case R8$.cc.TAB:continue;default:this.state=R8$.State.MSG_ARG,this.as=Z}break;case R8$.State.MSG_ARG:switch(Q){case R8$.cc.CR:this.drop=1;break;case R8$.cc.NL:{let X=this.argBuf?this.argBuf.bytes():$.subarray(this.as,Z-this.drop);this.processMsgArgs(X),this.drop=0,this.as=Z+1,this.state=R8$.State.MSG_PAYLOAD,Z=this.as+this.ma.size-1;break}default:if(this.argBuf)this.argBuf.writeByte(Q)}break;case R8$.State.MSG_PAYLOAD:if(this.msgBuf)if(this.msgBuf.length>=this.ma.size){let X=this.msgBuf.bytes({copy:!1});this.dispatcher.push({kind:R8$.Kind.MSG,msg:this.ma,data:X}),this.argBuf=void 0,this.msgBuf=void 0,this.state=R8$.State.MSG_END}else{let X=this.ma.size-this.msgBuf.length,Y=$.length-Z;if(Y<X)X=Y;if(X>0)this.msgBuf.write($.subarray(Z,Z+X)),Z=Z+X-1;else this.msgBuf.writeByte(Q)}else if(Z-this.as>=this.ma.size)this.dispatcher.push({kind:R8$.Kind.MSG,msg:this.ma,data:$.subarray(this.as,Z)}),this.argBuf=void 0,this.msgBuf=void 0,this.state=R8$.State.MSG_END;break;case R8$.State.MSG_END:switch(Q){case R8$.cc.NL:this.drop=0,this.as=Z+1,this.state=R8$.State.OP_START;break;default:continue}break;case R8$.State.OP_PLUS:switch(Q){case R8$.cc.O:case R8$.cc.o:this.state=R8$.State.OP_PLUS_O;break;default:throw this.fail($.subarray(Z))}break;case R8$.State.OP_PLUS_O:switch(Q){case R8$.cc.K:case R8$.cc.k:this.state=R8$.State.OP_PLUS_OK;break;default:throw this.fail($.subarray(Z))}break;case R8$.State.OP_PLUS_OK:switch(Q){case R8$.cc.NL:this.dispatcher.push({kind:R8$.Kind.OK}),this.drop=0,this.state=R8$.State.OP_START;break}break;case R8$.State.OP_MINUS:switch(Q){case R8$.cc.E:case R8$.cc.e:this.state=R8$.State.OP_MINUS_E;break;default:throw this.fail($.subarray(Z))}break;case R8$.State.OP_MINUS_E:switch(Q){case R8$.cc.R:case R8$.cc.r:this.state=R8$.State.OP_MINUS_ER;break;default:throw this.fail($.subarray(Z))}break;case R8$.State.OP_MINUS_ER:switch(Q){case R8$.cc.R:case R8$.cc.r:this.state=R8$.State.OP_MINUS_ERR;break;default:throw this.fail($.subarray(Z))}break;case R8$.State.OP_MINUS_ERR:switch(Q){case R8$.cc.SPACE:case R8$.cc.TAB:this.state=R8$.State.OP_MINUS_ERR_SPC;break;default:throw this.fail($.subarray(Z))}break;case R8$.State.OP_MINUS_ERR_SPC:switch(Q){case R8$.cc.SPACE:case R8$.cc.TAB:continue;default:this.state=R8$.State.MINUS_ERR_ARG,this.as=Z}break;case R8$.State.MINUS_ERR_ARG:switch(Q){case R8$.cc.CR:this.drop=1;break;case R8$.cc.NL:{let X;if(this.argBuf)X=this.argBuf.bytes(),this.argBuf=void 0;else X=$.subarray(this.as,Z-this.drop);this.dispatcher.push({kind:R8$.Kind.ERR,data:X}),this.drop=0,this.as=Z+1,this.state=R8$.State.OP_START;break}default:if(this.argBuf)this.argBuf.write(Uint8Array.of(Q))}break;case R8$.State.OP_P:switch(Q){case R8$.cc.I:case R8$.cc.i:this.state=R8$.State.OP_PI;break;case R8$.cc.O:case R8$.cc.o:this.state=R8$.State.OP_PO;break;default:throw this.fail($.subarray(Z))}break;case R8$.State.OP_PO:switch(Q){case R8$.cc.N:case R8$.cc.n:this.state=R8$.State.OP_PON;break;default:throw this.fail($.subarray(Z))}break;case R8$.State.OP_PON:switch(Q){case R8$.cc.G:case R8$.cc.g:this.state=R8$.State.OP_PONG;break;default:throw this.fail($.subarray(Z))}break;case R8$.State.OP_PONG:switch(Q){case R8$.cc.NL:this.dispatcher.push({kind:R8$.Kind.PONG}),this.drop=0,this.state=R8$.State.OP_START;break}break;case R8$.State.OP_PI:switch(Q){case R8$.cc.N:case R8$.cc.n:this.state=R8$.State.OP_PIN;break;default:throw this.fail($.subarray(Z))}break;case R8$.State.OP_PIN:switch(Q){case R8$.cc.G:case R8$.cc.g:this.state=R8$.State.OP_PING;break;default:throw this.fail($.subarray(Z))}break;case R8$.State.OP_PING:switch(Q){case R8$.cc.NL:this.dispatcher.push({kind:R8$.Kind.PING}),this.drop=0,this.state=R8$.State.OP_START;break}break;case R8$.State.OP_I:switch(Q){case R8$.cc.N:case R8$.cc.n:this.state=R8$.State.OP_IN;break;default:throw this.fail($.subarray(Z))}break;case R8$.State.OP_IN:switch(Q){case R8$.cc.F:case R8$.cc.f:this.state=R8$.State.OP_INF;break;default:throw this.fail($.subarray(Z))}break;case R8$.State.OP_INF:switch(Q){case R8$.cc.O:case R8$.cc.o:this.state=R8$.State.OP_INFO;break;default:throw this.fail($.subarray(Z))}break;case R8$.State.OP_INFO:switch(Q){case R8$.cc.SPACE:case R8$.cc.TAB:this.state=R8$.State.OP_INFO_SPC;break;default:throw this.fail($.subarray(Z))}break;case R8$.State.OP_INFO_SPC:switch(Q){case R8$.cc.SPACE:case R8$.cc.TAB:continue;default:this.state=R8$.State.INFO_ARG,this.as=Z}break;case R8$.State.INFO_ARG:switch(Q){case R8$.cc.CR:this.drop=1;break;case R8$.cc.NL:{let X;if(this.argBuf)X=this.argBuf.bytes(),this.argBuf=void 0;else X=$.subarray(this.as,Z-this.drop);this.dispatcher.push({kind:R8$.Kind.INFO,data:X}),this.drop=0,this.as=Z+1,this.state=R8$.State.OP_START;break}default:if(this.argBuf)this.argBuf.writeByte(Q)}break;default:throw this.fail($.subarray(Z))}}if((this.state===R8$.State.MSG_ARG||this.state===R8$.State.MINUS_ERR_ARG||this.state===R8$.State.INFO_ARG)&&!this.argBuf)this.argBuf=new Er0.DenoBuffer($.subarray(this.as,Z-this.drop));if(this.state===R8$.State.MSG_PAYLOAD&&!this.msgBuf){if(!this.argBuf)this.cloneMsgArg();this.msgBuf=new Er0.DenoBuffer($.subarray(this.as))}}cloneMsgArg(){let $=this.ma.subject.length,Z=this.ma.reply?this.ma.reply.length:0,Q=new Uint8Array($+Z);if(Q.set(this.ma.subject),this.ma.reply)Q.set(this.ma.reply,$);if(this.argBuf=new Er0.DenoBuffer(Q),this.ma.subject=Q.subarray(0,$),this.ma.reply)this.ma.reply=Q.subarray($)}processMsgArgs($){if(this.hdr>=0)return this.processHeaderMsgArgs($);let Z=[],Q=-1;for(let X=0;X<$.length;X++)switch($[X]){case R8$.cc.SPACE:case R8$.cc.TAB:case R8$.cc.CR:case R8$.cc.NL:if(Q>=0)Z.push($.subarray(Q,X)),Q=-1;break;default:if(Q<0)Q=X}if(Q>=0)Z.push($.subarray(Q));switch(Z.length){case 3:this.ma.subject=Z[0],this.ma.sid=this.protoParseInt(Z[1]),this.ma.reply=void 0,this.ma.size=this.protoParseInt(Z[2],hg);break;case 4:this.ma.subject=Z[0],this.ma.sid=this.protoParseInt(Z[1]),this.ma.reply=Z[2],this.ma.size=this.protoParseInt(Z[3],hg);break;default:throw this.fail($,"processMsgArgs Parse Error")}if(this.ma.sid<0)throw this.fail($,"processMsgArgs Bad or Missing Sid Error");if(this.ma.size<0)throw this.fail($,"processMsgArgs Bad or Missing Size Error")}fail($,Z=""){if(!Z)Z=`parse error [${this.state}]`;else Z=`${Z} [${this.state}]`;return Error(`${Z}: ${zr0.TD.decode($)}`)}processHeaderMsgArgs($){let Z=[],Q=-1;for(let X=0;X<$.length;X++)switch($[X]){case R8$.cc.SPACE:case R8$.cc.TAB:case R8$.cc.CR:case R8$.cc.NL:if(Q>=0)Z.push($.subarray(Q,X)),Q=-1;break;default:if(Q<0)Q=X}if(Q>=0)Z.push($.subarray(Q));switch(Z.length){case 4:this.ma.subject=Z[0],this.ma.sid=this.protoParseInt(Z[1]),this.ma.reply=void 0,this.ma.hdr=this.protoParseInt(Z[2],hg),this.ma.size=this.protoParseInt(Z[3],hg);break;case 5:this.ma.subject=Z[0],this.ma.sid=this.protoParseInt(Z[1]),this.ma.reply=Z[2],this.ma.hdr=this.protoParseInt(Z[3],hg),this.ma.size=this.protoParseInt(Z[4],hg);break;default:throw this.fail($,"processHeaderMsgArgs Parse Error")}if(this.ma.sid<0)throw this.fail($,"processHeaderMsgArgs Bad or Missing Sid Error");if(this.ma.hdr<0||this.ma.hdr>this.ma.size)throw this.fail($,"processHeaderMsgArgs Bad or Missing Header Size Error");if(this.ma.size<0)throw this.fail($,"processHeaderMsgArgs Bad or Missing Size Error")}protoParseInt($,Z){if($.length===0||$.length>15)return-1;let Q=0;for(let X=0;X<$.length;X++){if($[X]<A8$||$[X]>p94)return-1;Q=Q*10+($[X]-A8$)}return Z!==void 0&&Q>Z?-1:Q}}R8$.Parser=T8$;R8$.State={OP_START:0,OP_PLUS:1,OP_PLUS_O:2,OP_PLUS_OK:3,OP_MINUS:4,OP_MINUS_E:5,OP_MINUS_ER:6,OP_MINUS_ERR:7,OP_MINUS_ERR_SPC:8,MINUS_ERR_ARG:9,OP_M:10,OP_MS:11,OP_MSG:12,OP_MSG_SPC:13,MSG_ARG:14,MSG_PAYLOAD:15,MSG_END:16,OP_H:17,OP_P:18,OP_PI:19,OP_PIN:20,OP_PING:21,OP_PO:22,OP_PON:23,OP_PONG:24,OP_I:25,OP_IN:26,OP_INF:27,OP_INFO:28,OP_INFO_SPC:29,INFO_ARG:30};R8$.cc={CR:13,E:69,e:101,F:70,f:102,G:71,g:103,H:72,h:104,I:73,i:105,K:75,k:107,M:77,m:109,MINUS:45,N:78,n:110,NL:10,O:79,o:111,P:80,p:112,PLUS:43,R:82,r:114,S:83,s:115,SPACE:32,TAB:9}});var vX0=v((q8$)=>{Object.defineProperty(q8$,"__esModule",{value:!0});q8$.MsgHdrsImpl=void 0;q8$.canonicalMIMEHeaderKey=Tr0;q8$.headers=o94;var I8$=RJ(),LK=aO(),_X0=IJ();function Tr0($){let F=!0,U=Array($.length);for(let N=0;N<$.length;N++){let B=$.charCodeAt(N);if(B===58||B<33||B>126)throw _X0.InvalidArgumentError.format("header",`'${$[N]}' is not a valid character in a header name`);if(F&&97<=B&&B<=122)B-=32;else if(!F&&65<=B&&B<=90)B+=32;U[N]=B,F=B==45}return String.fromCharCode(...U)}function o94($=0,Z=""){if($===0&&Z!=="")throw _X0.InvalidArgumentError.format("code","is required");else if($>0&&Z==="")throw _X0.InvalidArgumentError.format("description","is required");return new ug($,Z)}var Ar0="NATS/1.0";class ug{_code;headers;_description;constructor($=0,Z=""){this._code=$,this._description=Z,this.headers=new Map}[Symbol.iterator](){return this.headers.entries()}size(){return this.headers.size}equals($){if($&&this.headers.size===$.headers.size&&this._code===$._code){for(let[Z,Q]of this.headers){let X=$.values(Z);if(Q.length!==X.length)return!1;let Y=[...Q].sort(),J=[...X].sort();for(let G=0;G<Y.length;G++)if(Y[G]!==J[G])return!1}return!0}return!1}static decode($){let Z=new ug,X=I8$.TD.decode($).split(`\r
1944
1944
  `),Y=X[0];if(Y!==Ar0){let J=Y.replace(Ar0,"").trim();if(J.length>0){if(Z._code=parseInt(J,10),isNaN(Z._code))Z._code=0;let G=Z._code.toString();J=J.replace(G,""),Z._description=J.trim()}}if(X.length>=1)X.slice(1).map((J)=>{if(J){let G=J.indexOf(":");if(G>-1){let K=J.slice(0,G),W=J.slice(G+1).trim();Z.append(K,W)}}});return Z}toString(){if(this.headers.size===0&&this._code===0)return"";let $=Ar0;if(this._code>0&&this._description!=="")$+=` ${this._code} ${this._description}`;for(let[Z,Q]of this.headers)for(let X=0;X<Q.length;X++)$=`${$}\r
1945
1945
  ${Z}: ${Q[X]}`;return`${$}\r
@@ -1993,7 +1993,7 @@ You are running the brand-context onboarding for the user's organization. Your o
1993
1993
  4. Do NOT call any other tools in this thread. Do NOT call \`brand_context_setup\` more than once.
1994
1994
 
1995
1995
  If the tool returns an error, surface the error message to the user and ask whether they want to try a different URL.
1996
- `.trim();dJ$=oG("site-diagnostics_"),rv5=dJ$.is,av5=dJ$.get,iJ$=oG("commerce-discovery_"),sv5=iJ$.is,WG0=iJ$.get;jz={AUTOMATION_MANAGER:oG("studio-automation-manager_"),CONNECTION_MANAGER:oG("studio-connection-manager_"),API_KEY_MANAGER:oG("studio-api-key-manager_"),STORE_MANAGER:oG("studio-store-manager_"),BRAND_MANAGER:oG("studio-brand-manager_"),USAGE_MANAGER:oG("studio-usage-manager_")},rG={AUTOMATION_MANAGER:jz.AUTOMATION_MANAGER.get,CONNECTION_MANAGER:jz.CONNECTION_MANAGER.get,API_KEY_MANAGER:jz.API_KEY_MANAGER.get,STORE_MANAGER:jz.STORE_MANAGER.get,BRAND_MANAGER:jz.BRAND_MANAGER.get,USAGE_MANAGER:jz.USAGE_MANAGER.get};t01=["studio-agent-manager_","studio-task-manager_"],ev5=t01.map(oG)});function aJ$($){return $.toLowerCase().replace(/[^a-z0-9]/g,"")}function oO4($){return aJ$($).includes("deepresearch")}function sJ$($){let Z=aJ$($);if(Z.includes("deepresearch"))return!1;return rO4.some((Q)=>Z.includes(Q))}function aO4($){return $.asyncResearch!==!0&&sJ$($.modelId)}function sO4($){return $.asyncResearch===!0||oO4($.modelId)||sJ$($.modelId)}function hh($,Z,Q,X){for(let Y of Q){let J=$.find((G)=>G.modelId===Y);if(J)return{keyId:Z,modelId:J.modelId,title:J.title}}for(let Y of Q){let J=$.find((G)=>G.modelId.includes(Y));if(J)return{keyId:Z,modelId:J.modelId,title:J.title}}if(X){let Y=$.find(X);if(Y)return{keyId:Z,modelId:Y.modelId,title:Y.title}}return null}function eJ$($,Z){let Q={chat:{fast:null,smart:null,thinking:null},image:null,webSearch:null,deepResearch:null};for(let X of $){let Y=Z[X.id]??[],J=X.providerId;if(!Q.chat.fast)Q.chat.fast=hh(Y,X.id,mO4[J]??[]);if(!Q.chat.smart)Q.chat.smart=hh(Y,X.id,dO4[J]??[]);if(!Q.chat.thinking)Q.chat.thinking=hh(Y,X.id,iO4[J]??[]);if(!Q.image)Q.image=hh(Y,X.id,pO4[J]??[],(G)=>G.capabilities?.includes("image")===!0);if(!Q.webSearch)Q.webSearch=hh(Y,X.id,nO4[J]??[],aO4);if(!Q.deepResearch)Q.deepResearch=hh(Y,X.id,tO4[J]??[],sO4)}return Q}var mO4,dO4,iO4,pO4,nO4,tO4,rO4;var $G$=D(()=>{mO4={anthropic:["claude-haiku-4-5","claude-haiku"],openrouter:["qwen/qwen3.5-flash","anthropic/claude-haiku-4.5","anthropic/claude-haiku","google/gemini-3-flash"],deco:["qwen/qwen3.5-flash","anthropic/claude-haiku"],llmapi:["claude-haiku-4-5","claude-haiku","gpt-4o-mini"],google:["gemini-2.5-flash","gemini-3-flash"]},dO4={anthropic:["claude-sonnet-5","claude-sonnet"],openrouter:["anthropic/claude-sonnet-5","anthropic/claude-sonnet","anthropic/claude-opus-4.8","google/gemini-3-pro"],deco:["anthropic/claude-sonnet-5","anthropic/claude-sonnet","anthropic/claude"],llmapi:["claude-sonnet-4-6","claude-sonnet"],google:["gemini-3-pro","gemini-3-flash"]},iO4={anthropic:["claude-opus-4-8","claude-sonnet-5","claude-sonnet","claude-fable-5"],openrouter:["anthropic/claude-opus-4.8:extended","anthropic/claude-opus-4.8","anthropic/claude-sonnet-5:extended","anthropic/claude-sonnet-5","google/gemini-3-pro","anthropic/claude-fable-5"],deco:["anthropic/claude-opus","anthropic/claude-sonnet-4.6","anthropic/claude-sonnet","anthropic/claude-fable"],llmapi:["claude-opus-4-8","claude-opus","claude-sonnet-4-6"],google:["gemini-3-pro"]},pO4={openrouter:["openai/gpt-image-1","google/gemini-2.0-flash-image"],deco:["openai/gpt-image-1","google/gemini-2.0-flash-image"],llmapi:["gemini-2.5-flash-image","gpt-image-1"],google:["gemini-2.0-flash-image"]},nO4={openrouter:["perplexity/sonar","perplexity/sonar-pro"],deco:["perplexity/sonar","perplexity/sonar-pro"]},tO4={openrouter:["perplexity/deep-research","perplexity/sonar-pro"],deco:["perplexity/deep-research","perplexity/sonar-pro"]};rO4=["sonar","searchpreview","online"]});function HG0($){if(!$)return;let Z={};for(let Q in $){let X=$[Q];if(typeof X==="object"&&X!==null){let Y={};for(let J of eO4)if(J in X)Y[J]=X[J];Z[Q]=Y}}return Object.keys(Z).length>0?Z:void 0}var eO4;var ZG$=D(()=>{eO4=["usage","cost","model"]});var x8=D(()=>{bY0();rJ$();$G$();ZG$()});function FG0($){return $.toLowerCase().trim().replace(/\//g,"-").replace(/[^a-z0-9\s_-]+/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function SD($){if($.app_name)return $.app_name;if($.connection_url)try{let Z=new URL($.connection_url),X=((Z.port?`${Z.hostname}-${Z.port}`:Z.hostname)+Z.pathname).replace(/\/+$/,"");return FG0(X)}catch{return FG0($.connection_url)}if($.title)return FG0($.title);return $.id??"unknown"}var UG0=()=>{};var uh=300000,NG0=5000,BG0=1e4,o01=3,r01=30000,QG$=65000,OG0=1000,ch=3,XG$=5,YG$=60000,JG$=300000,a01=60000;function GG$(){if(DN.size<OG0)return;let $=null,Z=1/0;for(let[Q,X]of DN)if(X.lastFailureAt<Z)Z=X.lastFailureAt,$=Q;if($)DN.delete($)}function KG$($){let Z=DN.get($);if(!Z)return GG$(),DN.set($,{consecutiveFailures:1,disabled:!1,lastFailureAt:Date.now()}),{consecutiveFailures:1,thresholdCrossed:1>=ch};return Z.consecutiveFailures++,Z.lastFailureAt=Date.now(),{consecutiveFailures:Z.consecutiveFailures,thresholdCrossed:Z.consecutiveFailures>=ch}}function s01($){let Z=DN.get($);if(Z){Z.disabled=!0;return}GG$(),DN.set($,{consecutiveFailures:ch,disabled:!0,lastFailureAt:Date.now()})}function WG$($){return DN.get($)?.disabled??!1}function HG$($){DN.delete($)}var DN;var FG$=D(()=>{DN=new Map});import{sql as a$}from"kysely";function NG$($){if($.length===0)return null;let Z=$[0];if($.length===1&&ZD4.has(Z))return a$.ref(Z);if($.length===2&&UG$.has(Z)){let Q=$[1];return a$`${a$.ref(Z)}->>${a$.lit(Q)}`}if($.length>2&&UG$.has(Z)){let Q=`{${$.slice(1).join(",")}}`;return a$`${a$.ref(Z)}#>>${a$.lit(Q)}`}return null}function BG$($){if("conditions"in $){let{operator:J,conditions:G}=$;if(G.length===0)return a$`true`;let K=G.map((W)=>BG$(W));switch(J){case"and":return a$`(${a$.join(K,a$` AND `)})`;case"or":return a$`(${a$.join(K,a$` OR `)})`;case"not":return a$`NOT (${a$.join(K,a$` AND `)})`;default:return a$`true`}}let{field:Z,operator:Q,value:X}=$,Y=NG$(Z);if(!Y)return a$`true`;switch(Q){case"eq":return X===null?a$`${Y} IS NULL`:a$`${Y} = ${a$.val(X)}`;case"gt":return a$`${Y} > ${a$.val(X)}`;case"gte":return a$`${Y} >= ${a$.val(X)}`;case"lt":return a$`${Y} < ${a$.val(X)}`;case"lte":return a$`${Y} <= ${a$.val(X)}`;case"in":if(!Array.isArray(X)||X.length===0)return a$`false`;return a$`${Y} IN (${a$.join(X.map((J)=>a$.val(J)))})`;case"like":return a$`${Y} ILIKE ${a$.val(X)}`;case"contains":{let J=String(X).replace(/[%_\\]/g,"\\$&");return a$`${Y} ILIKE ${a$.val(`%${J}%`)}`}default:return a$`true`}}class wo{db;vault;constructor($,Z){this.db=$;this.vault=Z}async create($){let Z=$.id??v8("conn"),Q=new Date().toISOString(),X=await this.db.selectFrom("connections").select("organization_id").where("id","=",Z).executeTakeFirst();if(X){if(X.organization_id!==$.organization_id)throw Error("Connection ID already exists");return this.update(Z,$)}let Y=SD($),J=await this.serializeConnection({...$,id:$.id??Z,slug:Y,status:"active",created_at:Q,updated_at:Q}),G;try{G=await this.db.insertInto("connections").values(J).returningAll().executeTakeFirst()}catch(K){if(K instanceof Error&&(K.message.includes("duplicate key")||K.message.includes("unique constraint")))throw Error("Connection ID already exists");throw K}if(!G)throw Error(`Failed to create connection with id: ${Z}`);return this.deserializeConnection(G)}async createNew($){let Z=$.id??v8("conn"),Q=new Date().toISOString(),X=SD($),Y=await this.serializeConnection({...$,id:Z,slug:X,status:"active",created_at:Q,updated_at:Q}),J;try{J=await this.db.insertInto("connections").values(Y).returningAll().executeTakeFirst()}catch(G){if(G instanceof Error&&(G.message.includes("duplicate key")||G.message.includes("unique constraint")))throw Error("Connection ID already exists");throw G}if(!J)throw Error(`Failed to create connection with id: ${Z}`);return this.deserializeConnection(J)}async findById($,Z){let Q=IQ($);if(Q)return oJ$(Z??Q);let X=this.db.selectFrom("connections").selectAll().where("id","=",$);if(Z)X=X.where("organization_id","=",Z);let Y=await X.executeTakeFirst();return Y?this.deserializeConnection(Y):null}async findBySanitizedId($){let Z=$.replace(/-/g,"_"),Q=await this.db.selectFrom("connections").selectAll().where(a$`replace(id, '-', '_')`,"=",Z).where("id","!=",$).executeTakeFirst();return Q?this.deserializeConnection(Q):null}async list($,Z){let Q=this.db.selectFrom("connections").selectAll().where("organization_id","=",$);if(!Z?.includeVirtual)Q=Q.where("connection_type","!=","VIRTUAL");if(Z?.slug)Q=Q.where("slug","=",Z.slug);if(Z?.where)Q=Q.where(BG$(Z.where));let J=(await this.db.selectFrom(Q.as("filtered")).select(a$`count(*)::int`.as("count")).executeTakeFirst())?.count??0;if(Z?.orderBy&&Z.orderBy.length>0)for(let W of Z.orderBy){let H=NG$(W.field);if(!H)continue;let F=W.direction==="desc"?a$`desc`:a$`asc`,U=W.nulls==="first"?a$`nulls first`:a$`nulls last`;Q=Q.orderBy(a$`${H} ${F} ${U}`)}if(Z?.limit!==void 0)Q=Q.limit(Z.limit);if(Z?.offset)Q=Q.offset(Z.offset);let G=await Q.execute();return{items:await Promise.all(G.map((W)=>this.deserializeConnection(W))),totalCount:J}}async update($,Z){let{id:Q,organization_id:X,created_by:Y,created_at:J,...G}=Z;if(Z=G,Object.keys(Z).length===0){let U=await this.findById($);if(!U)throw Error("Connection not found");return U}let K={...Z},W=await this.db.selectFrom("connections").select(["app_name","connection_url","title"]).where("id","=",$).executeTakeFirst();if(W){let U=(N)=>Z[N]===void 0?W[N]:Z[N];K.slug=SD({app_name:U("app_name"),connection_url:U("connection_url"),title:U("title"),id:$})}let H=await this.serializeConnection({...K,updated_at:new Date().toISOString()}),F=await this.db.updateTable("connections").set(H).where("id","=",$).returningAll().executeTakeFirst();if(!F)throw Error("Connection not found after update");return this.deserializeConnection(F)}async isReferencedByThread($){return await this.db.selectFrom("threads").select("id").where(a$`metadata -> 'githubRepo' ->> 'connectionId' = ${$}`).limit(1).executeTakeFirst()!==void 0}async delete($){await this.db.deleteFrom("connections").where("id","=",$).execute()}async testConnection($,Z){let Q=await this.findById($);if(!Q)throw Error("Connection not found");let X=Date.now();if(Q.connection_type==="STDIO")return{healthy:!0,latencyMs:Date.now()-X};if(!Q.connection_url)return{healthy:!1,latencyMs:Date.now()-X};try{if(await gh(Q.connection_url))return{healthy:!1,latencyMs:Date.now()-X};let J=Q.connection_headers,G=await kD()(Q.connection_url,{method:"POST",signal:AbortSignal.timeout(1e4),headers:{"Content-Type":"application/json",...Q.connection_token&&{Authorization:`Bearer ${Q.connection_token}`},...J?.headers,...Z},body:JSON.stringify({jsonrpc:"2.0",method:"ping",id:1})});return{healthy:G.ok||G.status===404,latencyMs:Date.now()-X}}catch{return{healthy:!1,latencyMs:Date.now()-X}}}async serializeConnection($){let Z={};for(let[Q,X]of Object.entries($)){if(X===void 0)continue;if(Q==="tools")continue;if(Q==="connection_token"&&X)Z[Q]=await this.vault.encrypt(X);else if(Q==="configuration_state"&&X){let Y=JSON.stringify(X);Z[Q]=await this.vault.encrypt(Y)}else if(Q==="oauth_config"&&X)Z[Q]=await this.vault.encrypt(JSON.stringify(X));else if(Q==="connection_headers"&&X){let Y=X;if(PH(Y)&&Y.envVars){let J={};for(let[G,K]of Object.entries(Y.envVars))J[G]=await this.vault.encrypt(K);Z[Q]=JSON.stringify({...Y,envVars:J})}else Z[Q]=JSON.stringify(Y)}else if($D4.includes(Q))Z[Q]=X?JSON.stringify(X):null;else Z[Q]=X}return Z}async handleDecryptFailures($,Z){let Q=`connection ${$.id} (org: ${$.organization_id}, type: ${$.connection_type}, title: ${$.title})`;if(WG$($.id))return;if($.status!=="active"){s01($.id);return}let{thresholdCrossed:X}=KG$($.id);if(!X){for(let{label:Y,error:J}of Z)console.error(`Failed to decrypt ${Y} for ${Q}:`,J);return}try{await this.db.updateTable("connections").set({status:"error"}).where("id","=",$.id).execute(),s01($.id),console.error(`Disabled ${Q} after ${ch} consecutive decryption failures.`,Z[0]?.error)}catch(Y){console.error(`Failed to disable ${Q} after decryption failures:`,Y)}}async deserializeConnection($){let Z=[],Q=null;if($.connection_token)try{Q=await this.vault.decrypt($.connection_token)}catch(K){Z.push({label:"connection token",error:K})}let X=null;if($.configuration_state)try{let K=await this.vault.decrypt($.configuration_state);X=JSON.parse(K)}catch(K){Z.push({label:"configuration state",error:K})}let Y=null;if(typeof $.oauth_config==="string")try{Y=JSON.parse(await this.vault.decrypt($.oauth_config))}catch{try{Y=JSON.parse($.oauth_config)}catch(K){Z.push({label:"oauth config",error:K})}}else Y=$.oauth_config;if(Z.length>0)await this.handleDecryptFailures($,Z);else if($.connection_token||$.configuration_state||$.oauth_config)HG$($.id);let J=null;if($.connection_headers)try{let K=JSON.parse($.connection_headers);if(PH(K)&&K.envVars){let W={};for(let[H,F]of Object.entries(K.envVars))try{W[H]=await this.vault.decrypt(F)}catch{W[H]=F}J={...K,envVars:W}}else J=K}catch(K){console.error(`Failed to parse connection_headers for connection ${$.id} (org: ${$.organization_id}, type: ${$.connection_type}, title: ${$.title}):`,K)}let G=(K)=>{if(K===null)return null;if(typeof K==="string")try{return JSON.parse(K)}catch{return null}return K};return{id:$.id,organization_id:$.organization_id,created_by:$.created_by,updated_by:$.updated_by??void 0,title:$.title,description:$.description,icon:$.icon,app_name:$.app_name,app_id:$.app_id,slug:$.slug,connection_type:$.connection_type,connection_url:$.connection_url,connection_token:Q,connection_headers:J,oauth_config:Y,configuration_state:X,configuration_scopes:G($.configuration_scopes),metadata:G($.metadata),tools:null,bindings:G($.bindings),status:$.status,created_at:$.created_at,updated_at:$.updated_at}}}var $D4,ZD4,UG$;var e01=D(()=>{TH();wz();RQ();x8();UG0();FG$();$D4=["connection_headers","configuration_scopes","metadata","bindings"],ZD4=new Set(["id","organization_id","created_by","updated_by","title","description","icon","app_name","app_id","slug","connection_type","connection_url","status","created_at","updated_at"]),UG$=new Set(["metadata","configuration_scopes","bindings"])});import{createHash as QD4,randomBytes as XD4,timingSafeEqual as Rx5}from"crypto";function JD4($){return $.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function Z11($){return QD4("sha256").update($).digest("hex")}function LG$($){let Z=$11.length+1,Q=Z+DG$;if(!$.startsWith(`${$11}_`)||$.length<=Q+1||$[Q]!=="_")return null;let X=$.slice(Z,Q),Y=$.slice(Q+1);if(!OG$.test(X)||!OG$.test(Y))return null;return X}function wG$(){let $=JD4(XD4(YD4)),Z=$.slice(0,DG$),Q=`${$11}_${Z}_${$}`;return{plaintext:Q,prefix:Z,hash:Z11(Q)}}var $11="stv",YD4=32,DG$=12,OG$;var jG$=D(()=>{OG$=/^[A-Za-z0-9_-]+$/});function EG$($){return{id:$.id,organizationId:$.organization_id,subjectConnectionId:$.subject_connection_id,tokenHash:$.token_hash,tokenPrefix:$.token_prefix,name:$.name,revokedAt:$.revoked_at,lastUsedAt:$.last_used_at,createdAt:$.created_at,updatedAt:$.updated_at}}class Q11{db;constructor($){this.db=$}async createOrRotateWorkloadToken($){let Z=$.name??"default";return await this.db.transaction().execute(async(X)=>{if(!await X.selectFrom("connections").select("id").where("id","=",$.subjectConnectionId).where("organization_id","=",$.organizationId).executeTakeFirst())throw Error("Subject connection not found in organization");let J=wG$(),G=new Date().toISOString();await X.updateTable("connection_workload_tokens").set({revoked_at:G,updated_at:G}).where("organization_id","=",$.organizationId).where("subject_connection_id","=",$.subjectConnectionId).where("name","=",Z).where("revoked_at","is",null).execute();let K=await X.insertInto("connection_workload_tokens").values({id:v8("cwt"),organization_id:$.organizationId,subject_connection_id:$.subjectConnectionId,token_hash:J.hash,token_prefix:J.prefix,name:Z,revoked_at:null,last_used_at:null,created_at:G,updated_at:G}).returningAll().executeTakeFirstOrThrow();return{plaintextToken:J.plaintext,record:EG$(K)}})}async findActiveWorkloadToken($){let Z=await this.db.selectFrom("connection_workload_tokens").selectAll().where("organization_id","=",$.organizationId).where("subject_connection_id","=",$.subjectConnectionId).where("name","=",$.name??"default").where("revoked_at","is",null).executeTakeFirst();return Z?EG$(Z):null}async revokeWorkloadToken($){let Z=new Date().toISOString();await this.db.updateTable("connection_workload_tokens").set({revoked_at:Z,updated_at:Z}).where("id","=",$.tokenId).where("organization_id","=",$.organizationId).where("subject_connection_id","=",$.subjectConnectionId).where("revoked_at","is",null).execute()}async authenticateWorkloadToken($){let Z=LG$($);if(!Z)return null;let Q=Z11($),X=await this.db.selectFrom("connection_workload_tokens").select(["id","organization_id","subject_connection_id","token_prefix"]).where("token_prefix","=",Z).where("token_hash","=",Q).where("revoked_at","is",null).executeTakeFirst();if(!X)return null;let Y=new Date().toISOString();return await this.db.updateTable("connection_workload_tokens").set({last_used_at:Y,updated_at:Y}).where("id","=",X.id).execute(),{tokenId:X.id,tokenPrefix:X.token_prefix,organizationId:X.organization_id,subjectConnectionId:X.subject_connection_id}}async replaceGrantsForSubject($){await this.db.transaction().execute(async(Z)=>{if(!await Z.selectFrom("connections").select("id").where("id","=",$.subjectConnectionId).where("organization_id","=",$.organizationId).executeTakeFirst())throw Error("Referenced connection not found in organization");let X=[...new Set($.grants.map((G)=>G.targetConnectionId))];if(X.length>0){if((await Z.selectFrom("connections").select("id").where("organization_id","=",$.organizationId).where("id","in",X).execute()).length!==X.length)throw Error("Referenced connection not found in organization")}if(await Z.deleteFrom("connection_credential_grants").where("organization_id","=",$.organizationId).where("subject_connection_id","=",$.subjectConnectionId).execute(),$.grants.length===0)return;let Y=new Date().toISOString(),J=$.grants.map((G)=>({id:v8("ccg"),organization_id:$.organizationId,subject_connection_id:$.subjectConnectionId,target_connection_id:G.targetConnectionId,scope:G.scope,created_by:$.createdBy,created_at:Y,updated_at:Y}));await Z.insertInto("connection_credential_grants").values(J).execute()})}async hasGrant($){return!!await this.db.selectFrom("connection_credential_grants").select("id").where("organization_id","=",$.organizationId).where("subject_connection_id","=",$.subjectConnectionId).where("target_connection_id","=",$.targetConnectionId).where("scope","=",$.scope).executeTakeFirst()}}var DG0="credential:access-token:read",LG0="credential:configuration:read";var wG0=D(()=>{RQ();jG$()});function zG$($,Z){let Q=!1,X={...$},Y=$.pinnedViews;if(Array.isArray(Y)){let K=Y.filter((W)=>W.connectionId!==Z);if(K.length!==Y.length)Q=!0,X.pinnedViews=K.length>0?K:null}let J=$.homeTile;if(J&&J.connectionId===Z)Q=!0,X.homeTile=null;let G=$.homeTiles;if(Array.isArray(G)){let K=G.filter((W)=>W.connectionId!==Z);if(K.length!==G.length)Q=!0,X.homeTiles=K.length>0?K:null}return{ui:X,changed:Q}}function GD4($){return $.replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_")}function PG$($){let Z=$?.githubRepo?.repositoryId;return typeof Z==="string"&&Z.length>0?Z:null}class lh{db;constructor($){this.db=$}async create($,Z,Q,X){let Y=X?.id??v8("vir"),J=new Date().toISOString();await this.db.transaction().execute(async(K)=>{if(await K.insertInto("connections").values({id:Y,organization_id:$,created_by:Z,updated_by:Z,title:Q.title,description:Q.description??null,icon:Q.icon??null,app_name:null,app_id:null,connection_type:"VIRTUAL",pinned:Q.pinned??!1,connection_url:`virtual://${Y}`,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:Q.metadata?JSON.stringify(Q.metadata):null,repository_id:PG$(Q.metadata),bindings:null,status:Q.status??"active",created_at:J,updated_at:J}).execute(),Q.connections.length>0)await K.insertInto("connection_aggregations").values(Q.connections.map((W)=>({id:v8("agg"),parent_connection_id:Y,child_connection_id:W.connection_id,selected_tools:W.selected_tools?JSON.stringify(W.selected_tools):null,selected_resources:W.selected_resources?JSON.stringify(W.selected_resources):null,selected_prompts:W.selected_prompts?JSON.stringify(W.selected_prompts):null,dependency_mode:"direct",created_at:J}))).execute()});let G=await this.findById(Y);if(!G)throw Error(`Failed to create virtual MCP with id: ${Y}`);return G}async findById($,Z){let Q=IQ($);if(Q)return{...n01(Z??Q),pinned:!1,connections:[]};let X=KG0($);if(X)return{...mJ$(Z??X),pinned:!1,connections:[]};return this.findByIdInternal(this.db,$)}async findByIdInternal($,Z){let Q=await $.selectFrom("connections").selectAll().where("id","=",Z).where("connection_type","=","VIRTUAL").executeTakeFirst();if(!Q)return null;let X=await $.selectFrom("connection_aggregations").selectAll().where("parent_connection_id","=",Z).where("dependency_mode","=","direct").execute();return this.deserializeVirtualMCPEntity(Q,X)}async searchAcrossMemberships($){let{userId:Z,term:Q,limit:X,offset:Y=0,organizationId:J}=$,G=`%${GD4(Q)}%`,K=this.db.selectFrom("connections").innerJoin("member",(H)=>H.onRef("member.organizationId","=","connections.organization_id").on("member.userId","=",Z)).innerJoin("organization","organization.id","connections.organization_id").where("connections.connection_type","=","VIRTUAL").where((H)=>H.or([H("connections.title","ilike",G),H("connections.description","ilike",G)]));if(J)K=K.where("connections.organization_id","=",J);return(await K.select(["connections.id as id","connections.title as title","connections.icon as icon","connections.metadata as metadata","connections.organization_id as organization_id","organization.name as organization_name","organization.slug as organization_slug","organization.metadata as organization_metadata"]).orderBy("connections.updated_at","desc").orderBy("connections.id","asc").limit(X).offset(Y).execute()).map((H)=>({id:H.id,title:H.title,icon:H.icon,metadata:this.parseJson(H.metadata),organization_id:H.organization_id,organization_name:H.organization_name,organization_slug:H.organization_slug,organization_metadata:H.organization_metadata}))}async list($,Z){let Q=this.db.selectFrom("connections").selectAll().where("organization_id","=",$).where("connection_type","=","VIRTUAL");if(Z?.pinnedOnly)Q=Q.where("pinned","=",!0);let X=await Q.orderBy("created_at","asc").orderBy("id","asc").execute(),Y=X.map((K)=>K.id);if(Y.length===0)return[];let J=await this.db.selectFrom("connection_aggregations").selectAll().where("parent_connection_id","in",Y).where("dependency_mode","=","direct").execute(),G=new Map;for(let K of J){let W=G.get(K.parent_connection_id)??[];W.push(K),G.set(K.parent_connection_id,W)}return X.map((K)=>this.deserializeVirtualMCPEntity(K,G.get(K.id)??[]))}async listByIds($,Z){if(Z.length===0)return[];let Q=await this.db.selectFrom("connections").selectAll().where("id","in",Z).where("organization_id","=",$).where("connection_type","=","VIRTUAL").execute();if(Q.length===0)return[];let X=Q.map((G)=>G.id),Y=await this.db.selectFrom("connection_aggregations").selectAll().where("parent_connection_id","in",X).where("dependency_mode","=","direct").execute(),J=new Map;for(let G of Y){let K=J.get(G.parent_connection_id)??[];K.push(G),J.set(G.parent_connection_id,K)}return Q.map((G)=>this.deserializeVirtualMCPEntity(G,J.get(G.id)??[]))}async listByConnectionId($,Z){let X=(await this.db.selectFrom("connection_aggregations").select("parent_connection_id").where("child_connection_id","=",Z).execute()).map((W)=>W.parent_connection_id);if(X.length===0)return[];let Y=await this.db.selectFrom("connections").selectAll().where("id","in",X).where("organization_id","=",$).where("connection_type","=","VIRTUAL").execute();if(Y.length===0)return[];let J=Y.map((W)=>W.id),G=await this.db.selectFrom("connection_aggregations").selectAll().where("parent_connection_id","in",J).where("dependency_mode","=","direct").execute(),K=new Map;for(let W of G){let H=K.get(W.parent_connection_id)??[];H.push(W),K.set(W.parent_connection_id,H)}return Y.map((W)=>this.deserializeVirtualMCPEntity(W,K.get(W.id)??[]))}async update($,Z,Q){let X=new Date().toISOString(),Y={updated_at:X,updated_by:Z};if(Q.title!==void 0)Y.title=Q.title;if(Q.description!==void 0)Y.description=Q.description;if(Q.icon!==void 0)Y.icon=Q.icon;if(Q.status!==void 0)Y.status=Q.status;if(Q.pinned!==void 0)Y.pinned=Q.pinned;if(Q.metadata!==void 0)Y.repository_id=PG$(Q.metadata),Y.metadata=Q.metadata?JSON.stringify(Q.metadata):null;let J=[];await this.db.transaction().execute(async(K)=>{if(await K.updateTable("connections").set(Y).where("id","=",$).where("connection_type","=","VIRTUAL").execute(),Q.connections!==void 0){let W=await K.selectFrom("connection_aggregations").select("child_connection_id").where("parent_connection_id","=",$).where("dependency_mode","=","direct").execute(),H=new Set(W.map((U)=>U.child_connection_id));if(await K.deleteFrom("connection_aggregations").where("parent_connection_id","=",$).where("dependency_mode","=","direct").execute(),Q.connections.length>0)await K.insertInto("connection_aggregations").values(Q.connections.map((U)=>({id:v8("agg"),parent_connection_id:$,child_connection_id:U.connection_id,selected_tools:U.selected_tools?JSON.stringify(U.selected_tools):null,selected_resources:U.selected_resources?JSON.stringify(U.selected_resources):null,selected_prompts:U.selected_prompts?JSON.stringify(U.selected_prompts):null,dependency_mode:"direct",created_at:X}))).execute();let F=new Set(Q.connections.map((U)=>U.connection_id));for(let U of H)if(!F.has(U))J.push(U)}});for(let K of J)await this.cleanOrphanedPinnedViews([$],K);let G=await this.findById($);if(!G)throw Error("Virtual MCP not found after update");return G}async delete($){await this.db.transaction().execute(async(Z)=>{await Z.deleteFrom("threads").where("virtual_mcp_id","=",$).execute(),await Z.deleteFrom("connection_aggregations").where("parent_connection_id","=",$).execute(),await Z.deleteFrom("connections").where("id","=",$).where("connection_type","=","VIRTUAL").execute()})}async removeConnectionReferences($){let Z=await this.db.selectFrom("connection_aggregations").select("parent_connection_id").where("child_connection_id","=",$).execute();await this.db.deleteFrom("connection_aggregations").where("child_connection_id","=",$).execute(),await this.cleanOrphanedPinnedViews(Z.map((Q)=>Q.parent_connection_id),$)}async cleanOrphanedPinnedViews($,Z){for(let Q of $){let X=await this.db.selectFrom("connections").select("metadata").where("id","=",Q).executeTakeFirst();if(!X?.metadata)continue;let Y;try{Y=typeof X.metadata==="string"?JSON.parse(X.metadata):X.metadata}catch{continue}let J=Y.ui??null;if(!J)continue;let{ui:G,changed:K}=zG$(J,Z);if(!K)continue;let W={...Y,ui:G};await this.db.updateTable("connections").set({metadata:JSON.stringify(W)}).where("id","=",Q).execute()}}deserializeVirtualMCPEntity($,Z){let Q=$.created_at instanceof Date?$.created_at.toISOString():$.created_at,X=$.updated_at instanceof Date?$.updated_at.toISOString():$.updated_at,Y=$.status==="active"?"active":"inactive",J=this.parseJson($.metadata),{sandboxMap:G,...K}=J??{},W=G!==void 0?Bs0(G):void 0;return{id:$.id,organization_id:$.organization_id,title:$.title,description:$.description,icon:$.icon,status:Y,pinned:$.pinned,created_at:Q,updated_at:X,created_by:$.created_by,updated_by:$.updated_by??void 0,metadata:{...K,instructions:J?.instructions??null,...W!==void 0?{sandboxMap:W}:{}},connections:Z.map((H)=>({connection_id:H.child_connection_id,selected_tools:this.parseJson(H.selected_tools),selected_resources:this.parseJson(H.selected_resources),selected_prompts:this.parseJson(H.selected_prompts)}))}}parseJson($){if($===null)return null;if(typeof $==="string")try{return JSON.parse($)}catch{return null}return $}}function AG$($){let Z=new Map,Q=(X,Y)=>{let J=Z.get(X);if(J)return J;let G=Y();return Z.set(X,G),G};return new Proxy($,{get(X,Y,J){if(Y==="list")return(G,K)=>Q(`list:${G}:${K?.pinnedOnly?1:0}`,()=>X.list(G,K));if(Y==="create"||Y==="update"||Y==="delete"||Y==="removeConnectionReferences")return(...G)=>{return Z.clear(),X[Y](...G)};return Reflect.get(X,Y,J)}})}var X11=D(()=>{RQ();x8()});function zz($){let Z=String($??"");if(Z&&!Z.includes("T"))return Z.replace(" ","T")+"Z";return Z}function I$($){return $.replace(/\0/g,"").replace(/\\/g,"\\\\").replace(/'/g,"''")}function s8($){let Z=Number($??0);return Number.isFinite(Z)?Z:0}function WD4($){if(!KD4.has($))throw Error(`Invalid groupByColumn: ${$}`);return $}function Y11($){if(!HD4.test($))throw Error(`Invalid JSONPath: ${$}`);if($.startsWith("$."))return $;if($.startsWith("."))return`$${$}`;return`$.${$}`}function W11($){return $.replace(/^\$\./,"").split(".").map((Q)=>`'${I$(Q)}'`).join(", ")}function ND4($){let Z=FD4.exec($);if(!Z||!Z[1]||!Z[2])throw Error(`Invalid interval: ${$}`);let Q=parseInt(Z[1],10),X=Z[2],Y=UD4[X];if(Q<1||Q>Y)throw Error(`Invalid interval amount: ${Q}${X} (max ${Y}${X})`);return{amount:Q,unit:X}}function CD($,Z,Q="timestamp"){let{amount:X,unit:Y}=ND4($),G={m:"MINUTE",h:"HOUR",d:"DAY"}[Y];if(Z==="duckdb")return`time_bucket(INTERVAL '${X} ${G}', CAST(${Q} AS TIMESTAMP))`;return`toStartOfInterval(${Q}, INTERVAL ${X} ${G})`}function jo($,Z,Q){if(Q==="duckdb")return`json_extract_string(${$}, '${Z}')`;let X=W11(Z);return`JSONExtractString(${$}, ${X})`}function BD4($,Z,Q){if(Q==="duckdb")return`CAST(json_extract_string(${$}, '${Z}') AS DOUBLE)`;let X=W11(Z);return`JSONExtractFloat(${$}, ${X})`}function TG$($,Z,Q){if(Q==="duckdb")return`TRY_CAST(json_extract_string(${$}, '${Z}') AS DOUBLE)`;let X=W11(Z);return`toFloat64OrZero(JSONExtractString(${$}, ${X}))`}function J11($){if($===null||$===void 0)return{};if(typeof $==="object")return $;let Z=String($);try{return JSON.parse(Z)}catch{return{_decocms_truncated:Z}}}function G11($){return{id:String($.id??""),organizationId:String($.organization_id??""),connectionId:String($.connection_id??""),toolName:String($.tool_name??""),input:J11($.input),output:J11($.output),isError:$.is_error===1||$.is_error===!0||$.is_error==="1"||typeof $.is_error==="bigint"&&$.is_error===1n,errorMessage:$.error_message!=null?String($.error_message):null,durationMs:Number($.duration_ms??0),timestamp:(()=>{if($.timestamp instanceof Date)return $.timestamp.toISOString();let Z=String($.timestamp??""),Q=new Date(Z.includes("T")?Z:Z.replace(" ","T")+"Z");return Number.isNaN(Q.getTime())?Z:Q.toISOString()})(),userId:$.user_id!=null?String($.user_id):null,requestId:String($.request_id??""),userAgent:$.user_agent!=null?String($.user_agent):null,virtualMcpId:$.virtual_mcp_id!=null?String($.virtual_mcp_id):null,properties:$.properties?J11($.properties):null}}function MG$($,Z){let Q=[];if($.properties)for(let[X,Y]of Object.entries($.properties)){let J=I$(X),G=I$(Y);if(Z==="duckdb")Q.push(`json_extract_string(properties, '$.${J}') = '${G}'`);else Q.push(`JSONExtractString(properties, '${J}') = '${G}'`)}if($.propertyKeys)for(let X of $.propertyKeys){let Y=I$(X);if(Z==="duckdb")Q.push(`json_extract_string(properties, '$.${Y}') IS NOT NULL AND json_extract_string(properties, '$.${Y}') != ''`);else Q.push(`JSONExtractString(properties, '${Y}') IS NOT NULL AND JSONExtractString(properties, '${Y}') != ''`)}if($.propertyPatterns)for(let[X,Y]of Object.entries($.propertyPatterns)){let J=I$(X),G=I$(Y);if(Z==="duckdb")Q.push(`json_extract_string(properties, '$.${J}') ILIKE '${G}'`);else Q.push(`JSONExtractString(properties, '${J}') ILIKE '${G}'`)}if($.propertyInValues)for(let[X,Y]of Object.entries($.propertyInValues)){let J=I$(X),G=I$(Y);if(Z==="duckdb")Q.push(`list_contains(string_split(json_extract_string(properties, '$.${J}'), ','), '${G}')`);else Q.push(`has(splitByChar(',', JSONExtractString(properties, '${J}')), '${G}')`)}return Q}function IG$($,Z){let Q=[];if(sG(Q,Z?.startDate,$),!Z)return Q;if(Z.connectionIds?.length){let X=Z.connectionIds.map((Y)=>`'${I$(Y)}'`).join(",");Q.push(`connection_id IN (${X})`)}if(Z.toolNames?.length){let X=Z.toolNames.map((Y)=>`'${I$(Y)}'`).join(",");Q.push(`tool_name IN (${X})`)}if(Z.virtualMcpIds?.length){let X=Z.virtualMcpIds.map((Y)=>`'${I$(Y)}'`).join(",");Q.push(`virtual_mcp_id IN (${X})`)}if(Z.endDate)Q.push(aG(Z.endDate,$));if(Z.propertyFilters)Q.push(...MG$(Z.propertyFilters,$));return Q}function qG$($,Z,Q="timestamp"){if(Z==="duckdb")return`CAST(${Q} AS TIMESTAMP) >= TIMESTAMP '${$.toISOString()}'`;if(Q==="bucket")return`${Q} >= parseDateTimeBestEffort('${$.toISOString()}')`;return`${Q} >= parseDateTime64BestEffort('${$.toISOString()}', 9)`}function aG($,Z,Q="timestamp"){if(Z==="duckdb")return`CAST(${Q} AS TIMESTAMP) <= TIMESTAMP '${$.toISOString()}'`;if(Q==="bucket")return`${Q} <= parseDateTimeBestEffort('${$.toISOString()}')`;return`${Q} <= parseDateTime64BestEffort('${$.toISOString()}', 9)`}function sG($,Z,Q,X="timestamp"){if(Z)$.push(qG$(Z,Q,X));else if(Q==="clickhouse")$.push(qG$(new Date(Date.now()-OD4),Q,X))}class H11{engine;sourceFactory;metricEngine;metricSourceFactory;dialect;metricsFromLogs;constructor($,Z,Q,X,Y="clickhouse",J=!1){this.engine=$;this.sourceFactory=Z;this.metricEngine=Q;this.metricSourceFactory=X;this.dialect=Y;this.metricsFromLogs=J}async query($){if(!$.organizationId)throw Error("organizationId is required");let Z=this.sourceFactory($.organizationId,{startDate:$.startDate,endDate:$.endDate}),Q=[`organization_id = '${I$($.organizationId)}'`];if($.connectionId)Q.push(`connection_id = '${I$($.connectionId)}'`);if($.excludeConnectionIds?.length){let N=$.excludeConnectionIds.map((B)=>`'${I$(B)}'`).join(",");Q.push(`connection_id NOT IN (${N})`)}if($.virtualMcpId)Q.push(`virtual_mcp_id = '${I$($.virtualMcpId)}'`);if($.toolName)Q.push(`tool_name = '${I$($.toolName)}'`);if($.isError!==void 0)Q.push(`is_error = ${$.isError?1:0}`);if(sG(Q,$.startDate,this.dialect),$.endDate)Q.push(aG($.endDate,this.dialect));if($.propertyFilters)Q.push(...MG$($.propertyFilters,this.dialect));let X=1000,Y=Math.min(Math.max(1,Math.floor($.limit??50)),X),J=Math.max(0,Math.floor($.offset??0)),G=Q.join(" AND ");if(this.dialect==="duckdb"){let N=`SELECT ${RG$}, count(*) OVER () AS _total FROM ${Z} WHERE ${G} ORDER BY timestamp DESC LIMIT ${Y} OFFSET ${J}`,B=await this.engine.query(N);if(B.length===0)return{logs:[],total:0};let O=Number(B[0]._total??0);return{logs:B.map(G11),total:O}}let K=`SELECT count(*) AS total FROM ${Z} WHERE ${G}`,W=`SELECT ${RG$} FROM ${Z} WHERE ${G} ORDER BY timestamp DESC LIMIT ${Y} OFFSET ${J}`,[H,F]=await Promise.all([this.engine.query(K),this.engine.query(W)]),U=Number(H[0]?.total??0);return{logs:F.map(G11),total:U}}async getById($,Z){if(!$||!Z)return null;let X=`SELECT * FROM ${this.sourceFactory($)} WHERE organization_id = '${I$($)}' AND id = '${I$(Z)}' LIMIT 1`,Y=await this.engine.query(X);if(Y.length===0)return null;return G11(Y[0])}async getStats($){if(!$.organizationId)throw Error("organizationId is required");let Z=this.sourceFactory($.organizationId,{startDate:$.startDate,endDate:$.endDate}),Q=[`organization_id = '${I$($.organizationId)}'`];if(sG(Q,$.startDate,this.dialect),$.endDate)Q.push(aG($.endDate,this.dialect));let X=`SELECT count(*) AS total_calls, coalesce(sum(CASE WHEN is_error = 1 THEN 1.0 ELSE 0.0 END) / NULLIF(count(*), 0), 0) AS error_rate, coalesce(avg(duration_ms), 0) AS avg_duration_ms FROM ${Z} WHERE ${Q.join(" AND ")}`,J=(await this.engine.query(X))[0]??{};return{totalCalls:Number(J.total_calls??0),errorRate:Number(J.error_rate??0),avgDurationMs:Number(J.avg_duration_ms??0)}}async queryToolCallHeatmap($){if(!$.organizationId)throw Error("organizationId is required");let Z=this.sourceFactory($.organizationId,{startDate:$.startDate,endDate:$.endDate}),Q=[`organization_id = '${I$($.organizationId)}'`,"type = 'tool_call'"];if($.filters?.virtualMcpIds?.length){let G=$.filters.virtualMcpIds.map((K)=>`'${I$(K)}'`).join(",");Q.push(`virtual_mcp_id IN (${G})`)}if($.filters?.excludeConnectionIds?.length){let G=$.filters.excludeConnectionIds.map((K)=>`'${I$(K)}'`).join(",");Q.push(`connection_id NOT IN (${G})`)}if(sG(Q,$.startDate,this.dialect),$.endDate)Q.push(aG($.endDate,this.dialect));let X=Math.min(Math.max(1,Math.floor($.limit??500)),1000),Y=`SELECT virtual_mcp_id, tool_name, count(*) AS calls, coalesce(sum(CASE WHEN is_error = 1 THEN 1 ELSE 0 END), 0) AS errors, coalesce(sum(length(output)), 0) AS output_size FROM ${Z} WHERE ${Q.join(" AND ")} GROUP BY virtual_mcp_id, tool_name ORDER BY calls DESC LIMIT ${X}`;return{cells:(await this.engine.query(Y)).map((G)=>({virtualMcpId:G.virtual_mcp_id?String(G.virtual_mcp_id):null,toolName:String(G.tool_name??""),calls:Number(G.calls??0),errors:Number(G.errors??0),outputSize:Number(G.output_size??0)}))}}async queryLlmUsageStats($){let Z={totalCalls:0,totalErrors:0,avgDurationMs:0,p50DurationMs:0,p95DurationMs:0,totalInputTokens:0,totalOutputTokens:0,totalTokens:0,totalCostUsd:0,topTools:[],timeseries:[]};if(!$.organizationId||!$.connectionId)return Z;let Q=this.dialect,X=Q==="clickhouse",Y=this.sourceFactory($.organizationId,{startDate:$.startDate,endDate:$.endDate}),J=CD($.interval,Q,"timestamp"),G=(j)=>`coalesce(${TG$("properties",`$.${j}`,Q)}, 0)`,K=X?"count()":"count(*)",W=X?"countIf(is_error = 1)":"count(*) FILTER (WHERE is_error = 1)",H=(j)=>X?`quantile(${j})(duration_ms)`:`quantile_cont(duration_ms, ${j})`,F=[`organization_id = '${I$($.organizationId)}'`,`connection_id = '${I$($.connectionId)}'`];if(sG(F,$.startDate,Q),$.endDate)F.push(aG($.endDate,Q));if($.userIds?.length){let j=$.userIds.slice(0,100).map((E)=>`'${I$(E)}'`).join(",");F.push(`user_id IN (${j})`)}let U=F.join(" AND "),N=Math.min(Math.max(1,Math.floor($.topN??5)),20),B=`${K} AS calls,
1996
+ `.trim();dJ$=oG("site-diagnostics_"),rv5=dJ$.is,av5=dJ$.get,iJ$=oG("commerce-discovery_"),sv5=iJ$.is,WG0=iJ$.get;jz={AUTOMATION_MANAGER:oG("studio-automation-manager_"),CONNECTION_MANAGER:oG("studio-connection-manager_"),API_KEY_MANAGER:oG("studio-api-key-manager_"),STORE_MANAGER:oG("studio-store-manager_"),BRAND_MANAGER:oG("studio-brand-manager_"),USAGE_MANAGER:oG("studio-usage-manager_")},rG={AUTOMATION_MANAGER:jz.AUTOMATION_MANAGER.get,CONNECTION_MANAGER:jz.CONNECTION_MANAGER.get,API_KEY_MANAGER:jz.API_KEY_MANAGER.get,STORE_MANAGER:jz.STORE_MANAGER.get,BRAND_MANAGER:jz.BRAND_MANAGER.get,USAGE_MANAGER:jz.USAGE_MANAGER.get};t01=["studio-agent-manager_","studio-task-manager_"],ev5=t01.map(oG)});function aJ$($){return $.toLowerCase().replace(/[^a-z0-9]/g,"")}function oO4($){return aJ$($).includes("deepresearch")}function sJ$($){let Z=aJ$($);if(Z.includes("deepresearch"))return!1;return rO4.some((Q)=>Z.includes(Q))}function aO4($){return $.asyncResearch!==!0&&sJ$($.modelId)}function sO4($){return $.asyncResearch===!0||oO4($.modelId)||sJ$($.modelId)}function hh($,Z,Q,X){for(let Y of Q){let J=$.find((G)=>G.modelId===Y);if(J)return{keyId:Z,modelId:J.modelId,title:J.title}}for(let Y of Q){let J=$.find((G)=>G.modelId.includes(Y));if(J)return{keyId:Z,modelId:J.modelId,title:J.title}}if(X){let Y=$.find(X);if(Y)return{keyId:Z,modelId:Y.modelId,title:Y.title}}return null}function eJ$($,Z){let Q={chat:{fast:null,smart:null,thinking:null},image:null,webSearch:null,deepResearch:null};for(let X of $){let Y=Z[X.id]??[],J=X.providerId;if(!Q.chat.fast)Q.chat.fast=hh(Y,X.id,mO4[J]??[]);if(!Q.chat.smart)Q.chat.smart=hh(Y,X.id,dO4[J]??[]);if(!Q.chat.thinking)Q.chat.thinking=hh(Y,X.id,iO4[J]??[]);if(!Q.image)Q.image=hh(Y,X.id,pO4[J]??[],(G)=>G.capabilities?.includes("image")===!0);if(!Q.webSearch)Q.webSearch=hh(Y,X.id,nO4[J]??[],aO4);if(!Q.deepResearch)Q.deepResearch=hh(Y,X.id,tO4[J]??[],sO4)}return Q}var mO4,dO4,iO4,pO4,nO4,tO4,rO4;var $G$=D(()=>{mO4={anthropic:["claude-haiku-4-5","claude-haiku"],openrouter:["qwen/qwen3.5-flash","anthropic/claude-haiku-4.5","anthropic/claude-haiku","google/gemini-3-flash"],deco:["qwen/qwen3.5-flash","anthropic/claude-haiku"],llmapi:["claude-haiku-4-5","claude-haiku","gpt-4o-mini"],google:["gemini-2.5-flash","gemini-3-flash"]},dO4={anthropic:["claude-sonnet-5","claude-sonnet"],openrouter:["anthropic/claude-sonnet-5","anthropic/claude-sonnet","anthropic/claude-opus-4.8","google/gemini-3-pro"],deco:["anthropic/claude-sonnet-5","anthropic/claude-sonnet","anthropic/claude"],llmapi:["claude-sonnet-4-6","claude-sonnet"],google:["gemini-3-pro","gemini-3-flash"]},iO4={anthropic:["claude-opus-4-8","claude-sonnet-5","claude-sonnet","claude-fable-5"],openrouter:["anthropic/claude-opus-4.8:extended","anthropic/claude-opus-4.8","anthropic/claude-sonnet-5:extended","anthropic/claude-sonnet-5","google/gemini-3-pro","anthropic/claude-fable-5"],deco:["anthropic/claude-opus","anthropic/claude-sonnet-4.6","anthropic/claude-sonnet","anthropic/claude-fable"],llmapi:["claude-opus-4-8","claude-opus","claude-sonnet-4-6"],google:["gemini-3-pro"]},pO4={openrouter:["openai/gpt-image-1","google/gemini-2.0-flash-image"],deco:["openai/gpt-image-1","google/gemini-2.0-flash-image"],llmapi:["gemini-2.5-flash-image","gpt-image-1"],google:["gemini-2.0-flash-image"]},nO4={openrouter:["perplexity/sonar","perplexity/sonar-pro"],deco:["perplexity/sonar","perplexity/sonar-pro"]},tO4={openrouter:["perplexity/deep-research","perplexity/sonar-pro"],deco:["perplexity/deep-research","perplexity/sonar-pro"]};rO4=["sonar","searchpreview","online"]});function HG0($){if(!$)return;let Z={};for(let Q in $){let X=$[Q];if(typeof X==="object"&&X!==null){let Y={};for(let J of eO4)if(J in X)Y[J]=X[J];Z[Q]=Y}}return Object.keys(Z).length>0?Z:void 0}var eO4;var ZG$=D(()=>{eO4=["usage","cost","model"]});var x8=D(()=>{bY0();rJ$();$G$();ZG$()});function FG0($){return $.toLowerCase().trim().replace(/\//g,"-").replace(/[^a-z0-9\s_-]+/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function SD($){if($.app_name)return $.app_name;if($.connection_url)try{let Z=new URL($.connection_url),X=((Z.port?`${Z.hostname}-${Z.port}`:Z.hostname)+Z.pathname).replace(/\/+$/,"");return FG0(X)}catch{return FG0($.connection_url)}if($.title)return FG0($.title);return $.id??"unknown"}var UG0=()=>{};var uh=300000,NG0=5000,BG0=1e4,o01=3,r01=30000,QG$=65000,OG0=1000,ch=3,XG$=5,YG$=60000,JG$=300000,a01=60000;function GG$(){if(DN.size<OG0)return;let $=null,Z=1/0;for(let[Q,X]of DN)if(X.lastFailureAt<Z)Z=X.lastFailureAt,$=Q;if($)DN.delete($)}function KG$($){let Z=DN.get($);if(!Z)return GG$(),DN.set($,{consecutiveFailures:1,disabled:!1,lastFailureAt:Date.now()}),{consecutiveFailures:1,thresholdCrossed:1>=ch};return Z.consecutiveFailures++,Z.lastFailureAt=Date.now(),{consecutiveFailures:Z.consecutiveFailures,thresholdCrossed:Z.consecutiveFailures>=ch}}function s01($){let Z=DN.get($);if(Z){Z.disabled=!0;return}GG$(),DN.set($,{consecutiveFailures:ch,disabled:!0,lastFailureAt:Date.now()})}function WG$($){return DN.get($)?.disabled??!1}function HG$($){DN.delete($)}var DN;var FG$=D(()=>{DN=new Map});import{sql as a$}from"kysely";function NG$($){if($.length===0)return null;let Z=$[0];if($.length===1&&ZD4.has(Z))return a$.ref(Z);if($.length===2&&UG$.has(Z)){let Q=$[1];return a$`${a$.ref(Z)}->>${a$.lit(Q)}`}if($.length>2&&UG$.has(Z)){let Q=`{${$.slice(1).join(",")}}`;return a$`${a$.ref(Z)}#>>${a$.lit(Q)}`}return null}function BG$($){if("conditions"in $){let{operator:J,conditions:G}=$;if(G.length===0)return a$`true`;let K=G.map((W)=>BG$(W));switch(J){case"and":return a$`(${a$.join(K,a$` AND `)})`;case"or":return a$`(${a$.join(K,a$` OR `)})`;case"not":return a$`NOT (${a$.join(K,a$` AND `)})`;default:return a$`true`}}let{field:Z,operator:Q,value:X}=$,Y=NG$(Z);if(!Y)return a$`true`;switch(Q){case"eq":return X===null?a$`${Y} IS NULL`:a$`${Y} = ${a$.val(X)}`;case"gt":return a$`${Y} > ${a$.val(X)}`;case"gte":return a$`${Y} >= ${a$.val(X)}`;case"lt":return a$`${Y} < ${a$.val(X)}`;case"lte":return a$`${Y} <= ${a$.val(X)}`;case"in":if(!Array.isArray(X)||X.length===0)return a$`false`;return a$`${Y} IN (${a$.join(X.map((J)=>a$.val(J)))})`;case"like":return a$`${Y} ILIKE ${a$.val(X)}`;case"contains":{let J=String(X).replace(/[%_\\]/g,"\\$&");return a$`${Y} ILIKE ${a$.val(`%${J}%`)}`}default:return a$`true`}}class wo{db;vault;constructor($,Z){this.db=$;this.vault=Z}async create($){let Z=$.id??v8("conn"),Q=new Date().toISOString(),X=await this.db.selectFrom("connections").select("organization_id").where("id","=",Z).executeTakeFirst();if(X){if(X.organization_id!==$.organization_id)throw Error("Connection ID already exists");return this.update(Z,$)}let Y=SD($),J=await this.serializeConnection({...$,id:$.id??Z,slug:Y,status:"active",created_at:Q,updated_at:Q}),G;try{G=await this.db.insertInto("connections").values(J).returningAll().executeTakeFirst()}catch(K){if(K instanceof Error&&(K.message.includes("duplicate key")||K.message.includes("unique constraint")))throw Error("Connection ID already exists");throw K}if(!G)throw Error(`Failed to create connection with id: ${Z}`);return this.deserializeConnection(G)}async createNew($){let Z=$.id??v8("conn"),Q=new Date().toISOString(),X=SD($),Y=await this.serializeConnection({...$,id:Z,slug:X,status:"active",created_at:Q,updated_at:Q}),J;try{J=await this.db.insertInto("connections").values(Y).returningAll().executeTakeFirst()}catch(G){if(G instanceof Error&&(G.message.includes("duplicate key")||G.message.includes("unique constraint")))throw Error("Connection ID already exists");throw G}if(!J)throw Error(`Failed to create connection with id: ${Z}`);return this.deserializeConnection(J)}async findById($,Z){let Q=IQ($);if(Q)return oJ$(Z??Q);let X=this.db.selectFrom("connections").selectAll().where("id","=",$);if(Z)X=X.where("organization_id","=",Z);let Y=await X.executeTakeFirst();return Y?this.deserializeConnection(Y):null}async findBySanitizedId($){let Z=$.replace(/-/g,"_"),Q=await this.db.selectFrom("connections").selectAll().where(a$`replace(id, '-', '_')`,"=",Z).where("id","!=",$).executeTakeFirst();return Q?this.deserializeConnection(Q):null}async list($,Z){let Q=this.db.selectFrom("connections").selectAll().where("organization_id","=",$);if(!Z?.includeVirtual)Q=Q.where("connection_type","!=","VIRTUAL");if(Z?.slug)Q=Q.where("slug","=",Z.slug);if(Z?.where)Q=Q.where(BG$(Z.where));let J=(await this.db.selectFrom(Q.as("filtered")).select(a$`count(*)::int`.as("count")).executeTakeFirst())?.count??0;if(Z?.orderBy&&Z.orderBy.length>0)for(let W of Z.orderBy){let H=NG$(W.field);if(!H)continue;let F=W.direction==="desc"?a$`desc`:a$`asc`,U=W.nulls==="first"?a$`nulls first`:a$`nulls last`;Q=Q.orderBy(a$`${H} ${F} ${U}`)}if(Z?.limit!==void 0)Q=Q.limit(Z.limit);if(Z?.offset)Q=Q.offset(Z.offset);let G=await Q.execute();return{items:await Promise.all(G.map((W)=>this.deserializeConnection(W))),totalCount:J}}async update($,Z){let{id:Q,organization_id:X,created_by:Y,created_at:J,...G}=Z;if(Z=G,Object.keys(Z).length===0){let U=await this.findById($);if(!U)throw Error("Connection not found");return U}let K={...Z},W=await this.db.selectFrom("connections").select(["app_name","connection_url","title"]).where("id","=",$).executeTakeFirst();if(W){let U=(N)=>Z[N]===void 0?W[N]:Z[N];K.slug=SD({app_name:U("app_name"),connection_url:U("connection_url"),title:U("title"),id:$})}let H=await this.serializeConnection({...K,updated_at:new Date().toISOString()}),F=await this.db.updateTable("connections").set(H).where("id","=",$).returningAll().executeTakeFirst();if(!F)throw Error("Connection not found after update");return this.deserializeConnection(F)}async isReferencedByThread($){return await this.db.selectFrom("threads").select("id").where(a$`metadata -> 'githubRepo' ->> 'connectionId' = ${$}`).limit(1).executeTakeFirst()!==void 0}async delete($){await this.db.deleteFrom("connections").where("id","=",$).execute()}async testConnection($,Z){let Q=await this.findById($);if(!Q)throw Error("Connection not found");let X=Date.now();if(Q.connection_type==="STDIO")return{healthy:!0,latencyMs:Date.now()-X};if(!Q.connection_url)return{healthy:!1,latencyMs:Date.now()-X};try{if(await gh(Q.connection_url))return{healthy:!1,latencyMs:Date.now()-X};let J=Q.connection_headers,G=await kD()(Q.connection_url,{method:"POST",signal:AbortSignal.timeout(1e4),headers:{"Content-Type":"application/json",...Q.connection_token&&{Authorization:`Bearer ${Q.connection_token}`},...J?.headers,...Z},body:JSON.stringify({jsonrpc:"2.0",method:"ping",id:1})});return{healthy:G.ok||G.status===404,latencyMs:Date.now()-X}}catch{return{healthy:!1,latencyMs:Date.now()-X}}}async serializeConnection($){let Z={};for(let[Q,X]of Object.entries($)){if(X===void 0)continue;if(Q==="tools")continue;if(Q==="connection_token"&&X)Z[Q]=await this.vault.encrypt(X);else if(Q==="configuration_state"&&X){let Y=JSON.stringify(X);Z[Q]=await this.vault.encrypt(Y)}else if(Q==="oauth_config"&&X)Z[Q]=await this.vault.encrypt(JSON.stringify(X));else if(Q==="connection_headers"&&X){let Y=X;if(PH(Y)&&Y.envVars){let J={};for(let[G,K]of Object.entries(Y.envVars))J[G]=await this.vault.encrypt(K);Z[Q]=JSON.stringify({...Y,envVars:J})}else Z[Q]=JSON.stringify(Y)}else if($D4.includes(Q))Z[Q]=X?JSON.stringify(X):null;else Z[Q]=X}return Z}async handleDecryptFailures($,Z){let Q=`connection ${$.id} (org: ${$.organization_id}, type: ${$.connection_type}, title: ${$.title})`;if(WG$($.id))return;if($.status!=="active"){s01($.id);return}let{thresholdCrossed:X}=KG$($.id);if(!X){for(let{label:Y,error:J}of Z)console.error(`Failed to decrypt ${Y} for ${Q}:`,J);return}try{await this.db.updateTable("connections").set({status:"error"}).where("id","=",$.id).execute(),s01($.id),console.error(`Disabled ${Q} after ${ch} consecutive decryption failures.`,Z[0]?.error)}catch(Y){console.error(`Failed to disable ${Q} after decryption failures:`,Y)}}async deserializeConnection($){let Z=[],Q=null;if($.connection_token)try{Q=await this.vault.decrypt($.connection_token)}catch(W){Z.push({label:"connection token",error:W})}let X=null;if($.configuration_state)try{let W=await this.vault.decrypt($.configuration_state);X=JSON.parse(W)}catch(W){Z.push({label:"configuration state",error:W})}let Y=null;if(typeof $.oauth_config==="string")try{Y=JSON.parse(await this.vault.decrypt($.oauth_config))}catch{try{Y=JSON.parse($.oauth_config)}catch(W){Z.push({label:"oauth config",error:W})}}else Y=$.oauth_config;let J=null,G=!1;if($.connection_headers)try{let W=JSON.parse($.connection_headers);if(PH(W)&&W.envVars){G=!0;let H={};for(let[F,U]of Object.entries(W.envVars))try{H[F]=await this.vault.decrypt(U)}catch(N){H[F]="",Z.push({label:`env var "${F}"`,error:N})}J={...W,envVars:H}}else J=W}catch(W){console.error(`Failed to parse connection_headers for connection ${$.id} (org: ${$.organization_id}, type: ${$.connection_type}, title: ${$.title}):`,W)}if(Z.length>0)await this.handleDecryptFailures($,Z);else if($.connection_token||$.configuration_state||$.oauth_config||G)HG$($.id);let K=(W)=>{if(W===null)return null;if(typeof W==="string")try{return JSON.parse(W)}catch{return null}return W};return{id:$.id,organization_id:$.organization_id,created_by:$.created_by,updated_by:$.updated_by??void 0,title:$.title,description:$.description,icon:$.icon,app_name:$.app_name,app_id:$.app_id,slug:$.slug,connection_type:$.connection_type,connection_url:$.connection_url,connection_token:Q,connection_headers:J,oauth_config:Y,configuration_state:X,configuration_scopes:K($.configuration_scopes),metadata:K($.metadata),tools:null,bindings:K($.bindings),status:$.status,created_at:$.created_at,updated_at:$.updated_at}}}var $D4,ZD4,UG$;var e01=D(()=>{TH();wz();RQ();x8();UG0();FG$();$D4=["connection_headers","configuration_scopes","metadata","bindings"],ZD4=new Set(["id","organization_id","created_by","updated_by","title","description","icon","app_name","app_id","slug","connection_type","connection_url","status","created_at","updated_at"]),UG$=new Set(["metadata","configuration_scopes","bindings"])});import{createHash as QD4,randomBytes as XD4,timingSafeEqual as Rx5}from"crypto";function JD4($){return $.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function Z11($){return QD4("sha256").update($).digest("hex")}function LG$($){let Z=$11.length+1,Q=Z+DG$;if(!$.startsWith(`${$11}_`)||$.length<=Q+1||$[Q]!=="_")return null;let X=$.slice(Z,Q),Y=$.slice(Q+1);if(!OG$.test(X)||!OG$.test(Y))return null;return X}function wG$(){let $=JD4(XD4(YD4)),Z=$.slice(0,DG$),Q=`${$11}_${Z}_${$}`;return{plaintext:Q,prefix:Z,hash:Z11(Q)}}var $11="stv",YD4=32,DG$=12,OG$;var jG$=D(()=>{OG$=/^[A-Za-z0-9_-]+$/});function EG$($){return{id:$.id,organizationId:$.organization_id,subjectConnectionId:$.subject_connection_id,tokenHash:$.token_hash,tokenPrefix:$.token_prefix,name:$.name,revokedAt:$.revoked_at,lastUsedAt:$.last_used_at,createdAt:$.created_at,updatedAt:$.updated_at}}class Q11{db;constructor($){this.db=$}async createOrRotateWorkloadToken($){let Z=$.name??"default";return await this.db.transaction().execute(async(X)=>{if(!await X.selectFrom("connections").select("id").where("id","=",$.subjectConnectionId).where("organization_id","=",$.organizationId).executeTakeFirst())throw Error("Subject connection not found in organization");let J=wG$(),G=new Date().toISOString();await X.updateTable("connection_workload_tokens").set({revoked_at:G,updated_at:G}).where("organization_id","=",$.organizationId).where("subject_connection_id","=",$.subjectConnectionId).where("name","=",Z).where("revoked_at","is",null).execute();let K=await X.insertInto("connection_workload_tokens").values({id:v8("cwt"),organization_id:$.organizationId,subject_connection_id:$.subjectConnectionId,token_hash:J.hash,token_prefix:J.prefix,name:Z,revoked_at:null,last_used_at:null,created_at:G,updated_at:G}).returningAll().executeTakeFirstOrThrow();return{plaintextToken:J.plaintext,record:EG$(K)}})}async findActiveWorkloadToken($){let Z=await this.db.selectFrom("connection_workload_tokens").selectAll().where("organization_id","=",$.organizationId).where("subject_connection_id","=",$.subjectConnectionId).where("name","=",$.name??"default").where("revoked_at","is",null).executeTakeFirst();return Z?EG$(Z):null}async revokeWorkloadToken($){let Z=new Date().toISOString();await this.db.updateTable("connection_workload_tokens").set({revoked_at:Z,updated_at:Z}).where("id","=",$.tokenId).where("organization_id","=",$.organizationId).where("subject_connection_id","=",$.subjectConnectionId).where("revoked_at","is",null).execute()}async authenticateWorkloadToken($){let Z=LG$($);if(!Z)return null;let Q=Z11($),X=await this.db.selectFrom("connection_workload_tokens").select(["id","organization_id","subject_connection_id","token_prefix"]).where("token_prefix","=",Z).where("token_hash","=",Q).where("revoked_at","is",null).executeTakeFirst();if(!X)return null;let Y=new Date().toISOString();return await this.db.updateTable("connection_workload_tokens").set({last_used_at:Y,updated_at:Y}).where("id","=",X.id).execute(),{tokenId:X.id,tokenPrefix:X.token_prefix,organizationId:X.organization_id,subjectConnectionId:X.subject_connection_id}}async replaceGrantsForSubject($){await this.db.transaction().execute(async(Z)=>{if(!await Z.selectFrom("connections").select("id").where("id","=",$.subjectConnectionId).where("organization_id","=",$.organizationId).executeTakeFirst())throw Error("Referenced connection not found in organization");let X=[...new Set($.grants.map((G)=>G.targetConnectionId))];if(X.length>0){if((await Z.selectFrom("connections").select("id").where("organization_id","=",$.organizationId).where("id","in",X).execute()).length!==X.length)throw Error("Referenced connection not found in organization")}if(await Z.deleteFrom("connection_credential_grants").where("organization_id","=",$.organizationId).where("subject_connection_id","=",$.subjectConnectionId).execute(),$.grants.length===0)return;let Y=new Date().toISOString(),J=$.grants.map((G)=>({id:v8("ccg"),organization_id:$.organizationId,subject_connection_id:$.subjectConnectionId,target_connection_id:G.targetConnectionId,scope:G.scope,created_by:$.createdBy,created_at:Y,updated_at:Y}));await Z.insertInto("connection_credential_grants").values(J).execute()})}async hasGrant($){return!!await this.db.selectFrom("connection_credential_grants").select("id").where("organization_id","=",$.organizationId).where("subject_connection_id","=",$.subjectConnectionId).where("target_connection_id","=",$.targetConnectionId).where("scope","=",$.scope).executeTakeFirst()}}var DG0="credential:access-token:read",LG0="credential:configuration:read";var wG0=D(()=>{RQ();jG$()});function zG$($,Z){let Q=!1,X={...$},Y=$.pinnedViews;if(Array.isArray(Y)){let K=Y.filter((W)=>W.connectionId!==Z);if(K.length!==Y.length)Q=!0,X.pinnedViews=K.length>0?K:null}let J=$.homeTile;if(J&&J.connectionId===Z)Q=!0,X.homeTile=null;let G=$.homeTiles;if(Array.isArray(G)){let K=G.filter((W)=>W.connectionId!==Z);if(K.length!==G.length)Q=!0,X.homeTiles=K.length>0?K:null}return{ui:X,changed:Q}}function GD4($){return $.replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_")}function PG$($){let Z=$?.githubRepo?.repositoryId;return typeof Z==="string"&&Z.length>0?Z:null}class lh{db;constructor($){this.db=$}async create($,Z,Q,X){let Y=X?.id??v8("vir"),J=new Date().toISOString();await this.db.transaction().execute(async(K)=>{if(await K.insertInto("connections").values({id:Y,organization_id:$,created_by:Z,updated_by:Z,title:Q.title,description:Q.description??null,icon:Q.icon??null,app_name:null,app_id:null,connection_type:"VIRTUAL",pinned:Q.pinned??!1,connection_url:`virtual://${Y}`,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:Q.metadata?JSON.stringify(Q.metadata):null,repository_id:PG$(Q.metadata),bindings:null,status:Q.status??"active",created_at:J,updated_at:J}).execute(),Q.connections.length>0)await K.insertInto("connection_aggregations").values(Q.connections.map((W)=>({id:v8("agg"),parent_connection_id:Y,child_connection_id:W.connection_id,selected_tools:W.selected_tools?JSON.stringify(W.selected_tools):null,selected_resources:W.selected_resources?JSON.stringify(W.selected_resources):null,selected_prompts:W.selected_prompts?JSON.stringify(W.selected_prompts):null,dependency_mode:"direct",created_at:J}))).execute()});let G=await this.findById(Y);if(!G)throw Error(`Failed to create virtual MCP with id: ${Y}`);return G}async findById($,Z){let Q=IQ($);if(Q)return{...n01(Z??Q),pinned:!1,connections:[]};let X=KG0($);if(X)return{...mJ$(Z??X),pinned:!1,connections:[]};return this.findByIdInternal(this.db,$)}async findByIdInternal($,Z){let Q=await $.selectFrom("connections").selectAll().where("id","=",Z).where("connection_type","=","VIRTUAL").executeTakeFirst();if(!Q)return null;let X=await $.selectFrom("connection_aggregations").selectAll().where("parent_connection_id","=",Z).where("dependency_mode","=","direct").execute();return this.deserializeVirtualMCPEntity(Q,X)}async searchAcrossMemberships($){let{userId:Z,term:Q,limit:X,offset:Y=0,organizationId:J}=$,G=`%${GD4(Q)}%`,K=this.db.selectFrom("connections").innerJoin("member",(H)=>H.onRef("member.organizationId","=","connections.organization_id").on("member.userId","=",Z)).innerJoin("organization","organization.id","connections.organization_id").where("connections.connection_type","=","VIRTUAL").where((H)=>H.or([H("connections.title","ilike",G),H("connections.description","ilike",G)]));if(J)K=K.where("connections.organization_id","=",J);return(await K.select(["connections.id as id","connections.title as title","connections.icon as icon","connections.metadata as metadata","connections.organization_id as organization_id","organization.name as organization_name","organization.slug as organization_slug","organization.metadata as organization_metadata"]).orderBy("connections.updated_at","desc").orderBy("connections.id","asc").limit(X).offset(Y).execute()).map((H)=>({id:H.id,title:H.title,icon:H.icon,metadata:this.parseJson(H.metadata),organization_id:H.organization_id,organization_name:H.organization_name,organization_slug:H.organization_slug,organization_metadata:H.organization_metadata}))}async list($,Z){let Q=this.db.selectFrom("connections").selectAll().where("organization_id","=",$).where("connection_type","=","VIRTUAL");if(Z?.pinnedOnly)Q=Q.where("pinned","=",!0);let X=await Q.orderBy("created_at","asc").orderBy("id","asc").execute(),Y=X.map((K)=>K.id);if(Y.length===0)return[];let J=await this.db.selectFrom("connection_aggregations").selectAll().where("parent_connection_id","in",Y).where("dependency_mode","=","direct").execute(),G=new Map;for(let K of J){let W=G.get(K.parent_connection_id)??[];W.push(K),G.set(K.parent_connection_id,W)}return X.map((K)=>this.deserializeVirtualMCPEntity(K,G.get(K.id)??[]))}async listByIds($,Z){if(Z.length===0)return[];let Q=await this.db.selectFrom("connections").selectAll().where("id","in",Z).where("organization_id","=",$).where("connection_type","=","VIRTUAL").execute();if(Q.length===0)return[];let X=Q.map((G)=>G.id),Y=await this.db.selectFrom("connection_aggregations").selectAll().where("parent_connection_id","in",X).where("dependency_mode","=","direct").execute(),J=new Map;for(let G of Y){let K=J.get(G.parent_connection_id)??[];K.push(G),J.set(G.parent_connection_id,K)}return Q.map((G)=>this.deserializeVirtualMCPEntity(G,J.get(G.id)??[]))}async listByConnectionId($,Z){let X=(await this.db.selectFrom("connection_aggregations").select("parent_connection_id").where("child_connection_id","=",Z).execute()).map((W)=>W.parent_connection_id);if(X.length===0)return[];let Y=await this.db.selectFrom("connections").selectAll().where("id","in",X).where("organization_id","=",$).where("connection_type","=","VIRTUAL").execute();if(Y.length===0)return[];let J=Y.map((W)=>W.id),G=await this.db.selectFrom("connection_aggregations").selectAll().where("parent_connection_id","in",J).where("dependency_mode","=","direct").execute(),K=new Map;for(let W of G){let H=K.get(W.parent_connection_id)??[];H.push(W),K.set(W.parent_connection_id,H)}return Y.map((W)=>this.deserializeVirtualMCPEntity(W,K.get(W.id)??[]))}async update($,Z,Q){let X=new Date().toISOString(),Y={updated_at:X,updated_by:Z};if(Q.title!==void 0)Y.title=Q.title;if(Q.description!==void 0)Y.description=Q.description;if(Q.icon!==void 0)Y.icon=Q.icon;if(Q.status!==void 0)Y.status=Q.status;if(Q.pinned!==void 0)Y.pinned=Q.pinned;if(Q.metadata!==void 0)Y.repository_id=PG$(Q.metadata),Y.metadata=Q.metadata?JSON.stringify(Q.metadata):null;let J=[];await this.db.transaction().execute(async(K)=>{if(await K.updateTable("connections").set(Y).where("id","=",$).where("connection_type","=","VIRTUAL").execute(),Q.connections!==void 0){let W=await K.selectFrom("connection_aggregations").select("child_connection_id").where("parent_connection_id","=",$).where("dependency_mode","=","direct").execute(),H=new Set(W.map((U)=>U.child_connection_id));if(await K.deleteFrom("connection_aggregations").where("parent_connection_id","=",$).where("dependency_mode","=","direct").execute(),Q.connections.length>0)await K.insertInto("connection_aggregations").values(Q.connections.map((U)=>({id:v8("agg"),parent_connection_id:$,child_connection_id:U.connection_id,selected_tools:U.selected_tools?JSON.stringify(U.selected_tools):null,selected_resources:U.selected_resources?JSON.stringify(U.selected_resources):null,selected_prompts:U.selected_prompts?JSON.stringify(U.selected_prompts):null,dependency_mode:"direct",created_at:X}))).execute();let F=new Set(Q.connections.map((U)=>U.connection_id));for(let U of H)if(!F.has(U))J.push(U)}});for(let K of J)await this.cleanOrphanedPinnedViews([$],K);let G=await this.findById($);if(!G)throw Error("Virtual MCP not found after update");return G}async delete($){await this.db.transaction().execute(async(Z)=>{await Z.deleteFrom("threads").where("virtual_mcp_id","=",$).execute(),await Z.deleteFrom("connection_aggregations").where("parent_connection_id","=",$).execute(),await Z.deleteFrom("connections").where("id","=",$).where("connection_type","=","VIRTUAL").execute()})}async removeConnectionReferences($){let Z=await this.db.selectFrom("connection_aggregations").select("parent_connection_id").where("child_connection_id","=",$).execute();await this.db.deleteFrom("connection_aggregations").where("child_connection_id","=",$).execute(),await this.cleanOrphanedPinnedViews(Z.map((Q)=>Q.parent_connection_id),$)}async cleanOrphanedPinnedViews($,Z){for(let Q of $){let X=await this.db.selectFrom("connections").select("metadata").where("id","=",Q).executeTakeFirst();if(!X?.metadata)continue;let Y;try{Y=typeof X.metadata==="string"?JSON.parse(X.metadata):X.metadata}catch{continue}let J=Y.ui??null;if(!J)continue;let{ui:G,changed:K}=zG$(J,Z);if(!K)continue;let W={...Y,ui:G};await this.db.updateTable("connections").set({metadata:JSON.stringify(W)}).where("id","=",Q).execute()}}deserializeVirtualMCPEntity($,Z){let Q=$.created_at instanceof Date?$.created_at.toISOString():$.created_at,X=$.updated_at instanceof Date?$.updated_at.toISOString():$.updated_at,Y=$.status==="active"?"active":"inactive",J=this.parseJson($.metadata),{sandboxMap:G,...K}=J??{},W=G!==void 0?Bs0(G):void 0;return{id:$.id,organization_id:$.organization_id,title:$.title,description:$.description,icon:$.icon,status:Y,pinned:$.pinned,created_at:Q,updated_at:X,created_by:$.created_by,updated_by:$.updated_by??void 0,metadata:{...K,instructions:J?.instructions??null,...W!==void 0?{sandboxMap:W}:{}},connections:Z.map((H)=>({connection_id:H.child_connection_id,selected_tools:this.parseJson(H.selected_tools),selected_resources:this.parseJson(H.selected_resources),selected_prompts:this.parseJson(H.selected_prompts)}))}}parseJson($){if($===null)return null;if(typeof $==="string")try{return JSON.parse($)}catch{return null}return $}}function AG$($){let Z=new Map,Q=(X,Y)=>{let J=Z.get(X);if(J)return J;let G=Y();return Z.set(X,G),G};return new Proxy($,{get(X,Y,J){if(Y==="list")return(G,K)=>Q(`list:${G}:${K?.pinnedOnly?1:0}`,()=>X.list(G,K));if(Y==="create"||Y==="update"||Y==="delete"||Y==="removeConnectionReferences")return(...G)=>{return Z.clear(),X[Y](...G)};return Reflect.get(X,Y,J)}})}var X11=D(()=>{RQ();x8()});function zz($){let Z=String($??"");if(Z&&!Z.includes("T"))return Z.replace(" ","T")+"Z";return Z}function I$($){return $.replace(/\0/g,"").replace(/\\/g,"\\\\").replace(/'/g,"''")}function s8($){let Z=Number($??0);return Number.isFinite(Z)?Z:0}function WD4($){if(!KD4.has($))throw Error(`Invalid groupByColumn: ${$}`);return $}function Y11($){if(!HD4.test($))throw Error(`Invalid JSONPath: ${$}`);if($.startsWith("$."))return $;if($.startsWith("."))return`$${$}`;return`$.${$}`}function W11($){return $.replace(/^\$\./,"").split(".").map((Q)=>`'${I$(Q)}'`).join(", ")}function ND4($){let Z=FD4.exec($);if(!Z||!Z[1]||!Z[2])throw Error(`Invalid interval: ${$}`);let Q=parseInt(Z[1],10),X=Z[2],Y=UD4[X];if(Q<1||Q>Y)throw Error(`Invalid interval amount: ${Q}${X} (max ${Y}${X})`);return{amount:Q,unit:X}}function CD($,Z,Q="timestamp"){let{amount:X,unit:Y}=ND4($),G={m:"MINUTE",h:"HOUR",d:"DAY"}[Y];if(Z==="duckdb")return`time_bucket(INTERVAL '${X} ${G}', CAST(${Q} AS TIMESTAMP))`;return`toStartOfInterval(${Q}, INTERVAL ${X} ${G})`}function jo($,Z,Q){if(Q==="duckdb")return`json_extract_string(${$}, '${Z}')`;let X=W11(Z);return`JSONExtractString(${$}, ${X})`}function BD4($,Z,Q){if(Q==="duckdb")return`CAST(json_extract_string(${$}, '${Z}') AS DOUBLE)`;let X=W11(Z);return`JSONExtractFloat(${$}, ${X})`}function TG$($,Z,Q){if(Q==="duckdb")return`TRY_CAST(json_extract_string(${$}, '${Z}') AS DOUBLE)`;let X=W11(Z);return`toFloat64OrZero(JSONExtractString(${$}, ${X}))`}function J11($){if($===null||$===void 0)return{};if(typeof $==="object")return $;let Z=String($);try{return JSON.parse(Z)}catch{return{_decocms_truncated:Z}}}function G11($){return{id:String($.id??""),organizationId:String($.organization_id??""),connectionId:String($.connection_id??""),toolName:String($.tool_name??""),input:J11($.input),output:J11($.output),isError:$.is_error===1||$.is_error===!0||$.is_error==="1"||typeof $.is_error==="bigint"&&$.is_error===1n,errorMessage:$.error_message!=null?String($.error_message):null,durationMs:Number($.duration_ms??0),timestamp:(()=>{if($.timestamp instanceof Date)return $.timestamp.toISOString();let Z=String($.timestamp??""),Q=new Date(Z.includes("T")?Z:Z.replace(" ","T")+"Z");return Number.isNaN(Q.getTime())?Z:Q.toISOString()})(),userId:$.user_id!=null?String($.user_id):null,requestId:String($.request_id??""),userAgent:$.user_agent!=null?String($.user_agent):null,virtualMcpId:$.virtual_mcp_id!=null?String($.virtual_mcp_id):null,properties:$.properties?J11($.properties):null}}function MG$($,Z){let Q=[];if($.properties)for(let[X,Y]of Object.entries($.properties)){let J=I$(X),G=I$(Y);if(Z==="duckdb")Q.push(`json_extract_string(properties, '$.${J}') = '${G}'`);else Q.push(`JSONExtractString(properties, '${J}') = '${G}'`)}if($.propertyKeys)for(let X of $.propertyKeys){let Y=I$(X);if(Z==="duckdb")Q.push(`json_extract_string(properties, '$.${Y}') IS NOT NULL AND json_extract_string(properties, '$.${Y}') != ''`);else Q.push(`JSONExtractString(properties, '${Y}') IS NOT NULL AND JSONExtractString(properties, '${Y}') != ''`)}if($.propertyPatterns)for(let[X,Y]of Object.entries($.propertyPatterns)){let J=I$(X),G=I$(Y);if(Z==="duckdb")Q.push(`json_extract_string(properties, '$.${J}') ILIKE '${G}'`);else Q.push(`JSONExtractString(properties, '${J}') ILIKE '${G}'`)}if($.propertyInValues)for(let[X,Y]of Object.entries($.propertyInValues)){let J=I$(X),G=I$(Y);if(Z==="duckdb")Q.push(`list_contains(string_split(json_extract_string(properties, '$.${J}'), ','), '${G}')`);else Q.push(`has(splitByChar(',', JSONExtractString(properties, '${J}')), '${G}')`)}return Q}function IG$($,Z){let Q=[];if(sG(Q,Z?.startDate,$),!Z)return Q;if(Z.connectionIds?.length){let X=Z.connectionIds.map((Y)=>`'${I$(Y)}'`).join(",");Q.push(`connection_id IN (${X})`)}if(Z.toolNames?.length){let X=Z.toolNames.map((Y)=>`'${I$(Y)}'`).join(",");Q.push(`tool_name IN (${X})`)}if(Z.virtualMcpIds?.length){let X=Z.virtualMcpIds.map((Y)=>`'${I$(Y)}'`).join(",");Q.push(`virtual_mcp_id IN (${X})`)}if(Z.endDate)Q.push(aG(Z.endDate,$));if(Z.propertyFilters)Q.push(...MG$(Z.propertyFilters,$));return Q}function qG$($,Z,Q="timestamp"){if(Z==="duckdb")return`CAST(${Q} AS TIMESTAMP) >= TIMESTAMP '${$.toISOString()}'`;if(Q==="bucket")return`${Q} >= parseDateTimeBestEffort('${$.toISOString()}')`;return`${Q} >= parseDateTime64BestEffort('${$.toISOString()}', 9)`}function aG($,Z,Q="timestamp"){if(Z==="duckdb")return`CAST(${Q} AS TIMESTAMP) <= TIMESTAMP '${$.toISOString()}'`;if(Q==="bucket")return`${Q} <= parseDateTimeBestEffort('${$.toISOString()}')`;return`${Q} <= parseDateTime64BestEffort('${$.toISOString()}', 9)`}function sG($,Z,Q,X="timestamp"){if(Z)$.push(qG$(Z,Q,X));else if(Q==="clickhouse")$.push(qG$(new Date(Date.now()-OD4),Q,X))}class H11{engine;sourceFactory;metricEngine;metricSourceFactory;dialect;metricsFromLogs;constructor($,Z,Q,X,Y="clickhouse",J=!1){this.engine=$;this.sourceFactory=Z;this.metricEngine=Q;this.metricSourceFactory=X;this.dialect=Y;this.metricsFromLogs=J}async query($){if(!$.organizationId)throw Error("organizationId is required");let Z=this.sourceFactory($.organizationId,{startDate:$.startDate,endDate:$.endDate}),Q=[`organization_id = '${I$($.organizationId)}'`];if($.connectionId)Q.push(`connection_id = '${I$($.connectionId)}'`);if($.excludeConnectionIds?.length){let N=$.excludeConnectionIds.map((B)=>`'${I$(B)}'`).join(",");Q.push(`connection_id NOT IN (${N})`)}if($.virtualMcpId)Q.push(`virtual_mcp_id = '${I$($.virtualMcpId)}'`);if($.toolName)Q.push(`tool_name = '${I$($.toolName)}'`);if($.isError!==void 0)Q.push(`is_error = ${$.isError?1:0}`);if(sG(Q,$.startDate,this.dialect),$.endDate)Q.push(aG($.endDate,this.dialect));if($.propertyFilters)Q.push(...MG$($.propertyFilters,this.dialect));let X=1000,Y=Math.min(Math.max(1,Math.floor($.limit??50)),X),J=Math.max(0,Math.floor($.offset??0)),G=Q.join(" AND ");if(this.dialect==="duckdb"){let N=`SELECT ${RG$}, count(*) OVER () AS _total FROM ${Z} WHERE ${G} ORDER BY timestamp DESC LIMIT ${Y} OFFSET ${J}`,B=await this.engine.query(N);if(B.length===0)return{logs:[],total:0};let O=Number(B[0]._total??0);return{logs:B.map(G11),total:O}}let K=`SELECT count(*) AS total FROM ${Z} WHERE ${G}`,W=`SELECT ${RG$} FROM ${Z} WHERE ${G} ORDER BY timestamp DESC LIMIT ${Y} OFFSET ${J}`,[H,F]=await Promise.all([this.engine.query(K),this.engine.query(W)]),U=Number(H[0]?.total??0);return{logs:F.map(G11),total:U}}async getById($,Z){if(!$||!Z)return null;let X=`SELECT * FROM ${this.sourceFactory($)} WHERE organization_id = '${I$($)}' AND id = '${I$(Z)}' LIMIT 1`,Y=await this.engine.query(X);if(Y.length===0)return null;return G11(Y[0])}async getStats($){if(!$.organizationId)throw Error("organizationId is required");let Z=this.sourceFactory($.organizationId,{startDate:$.startDate,endDate:$.endDate}),Q=[`organization_id = '${I$($.organizationId)}'`];if(sG(Q,$.startDate,this.dialect),$.endDate)Q.push(aG($.endDate,this.dialect));let X=`SELECT count(*) AS total_calls, coalesce(sum(CASE WHEN is_error = 1 THEN 1.0 ELSE 0.0 END) / NULLIF(count(*), 0), 0) AS error_rate, coalesce(avg(duration_ms), 0) AS avg_duration_ms FROM ${Z} WHERE ${Q.join(" AND ")}`,J=(await this.engine.query(X))[0]??{};return{totalCalls:Number(J.total_calls??0),errorRate:Number(J.error_rate??0),avgDurationMs:Number(J.avg_duration_ms??0)}}async queryToolCallHeatmap($){if(!$.organizationId)throw Error("organizationId is required");let Z=this.sourceFactory($.organizationId,{startDate:$.startDate,endDate:$.endDate}),Q=[`organization_id = '${I$($.organizationId)}'`,"type = 'tool_call'"];if($.filters?.virtualMcpIds?.length){let G=$.filters.virtualMcpIds.map((K)=>`'${I$(K)}'`).join(",");Q.push(`virtual_mcp_id IN (${G})`)}if($.filters?.excludeConnectionIds?.length){let G=$.filters.excludeConnectionIds.map((K)=>`'${I$(K)}'`).join(",");Q.push(`connection_id NOT IN (${G})`)}if(sG(Q,$.startDate,this.dialect),$.endDate)Q.push(aG($.endDate,this.dialect));let X=Math.min(Math.max(1,Math.floor($.limit??500)),1000),Y=`SELECT virtual_mcp_id, tool_name, count(*) AS calls, coalesce(sum(CASE WHEN is_error = 1 THEN 1 ELSE 0 END), 0) AS errors, coalesce(sum(length(output)), 0) AS output_size FROM ${Z} WHERE ${Q.join(" AND ")} GROUP BY virtual_mcp_id, tool_name ORDER BY calls DESC LIMIT ${X}`;return{cells:(await this.engine.query(Y)).map((G)=>({virtualMcpId:G.virtual_mcp_id?String(G.virtual_mcp_id):null,toolName:String(G.tool_name??""),calls:Number(G.calls??0),errors:Number(G.errors??0),outputSize:Number(G.output_size??0)}))}}async queryLlmUsageStats($){let Z={totalCalls:0,totalErrors:0,avgDurationMs:0,p50DurationMs:0,p95DurationMs:0,totalInputTokens:0,totalOutputTokens:0,totalTokens:0,totalCostUsd:0,topTools:[],timeseries:[]};if(!$.organizationId||!$.connectionId)return Z;let Q=this.dialect,X=Q==="clickhouse",Y=this.sourceFactory($.organizationId,{startDate:$.startDate,endDate:$.endDate}),J=CD($.interval,Q,"timestamp"),G=(j)=>`coalesce(${TG$("properties",`$.${j}`,Q)}, 0)`,K=X?"count()":"count(*)",W=X?"countIf(is_error = 1)":"count(*) FILTER (WHERE is_error = 1)",H=(j)=>X?`quantile(${j})(duration_ms)`:`quantile_cont(duration_ms, ${j})`,F=[`organization_id = '${I$($.organizationId)}'`,`connection_id = '${I$($.connectionId)}'`];if(sG(F,$.startDate,Q),$.endDate)F.push(aG($.endDate,Q));if($.userIds?.length){let j=$.userIds.slice(0,100).map((E)=>`'${I$(E)}'`).join(",");F.push(`user_id IN (${j})`)}let U=F.join(" AND "),N=Math.min(Math.max(1,Math.floor($.topN??5)),20),B=`${K} AS calls,
1997
1997
  ${W} AS errors,
1998
1998
  avg(duration_ms) AS avg,
1999
1999
  sum(${G("input_tokens")}) AS in_tok,
@@ -4565,7 +4565,7 @@ Hint: Configure a valid Google account email in Monitor Configuration > Contexto
4565
4565
 
4566
4566
  `).trim(),N=F.length>0?`Not executed tools (${F.length}/${$.tools.length}): ${F.join(", ")}`:"",B=[U,N].filter((O)=>O.length>0).join(`
4567
4567
 
4568
- `);return{toolResults:W,agentSummary:B.length>0?B:null,unexecutedTools:F}}finally{await Z.close?.().catch(()=>{})}}async function EO1($,Z){let Q=$.storage.registry,X=$.organization.id,Y=await Q.monitorConnections.findByItemId(X,Z.id);if(Y){if(await $.storage.connections.findById(Y.connection_id,X))return Y.connection_id}let J=Tg6(Z);if(!J)throw Error(`Registry item ${Z.id} has no remote URL`);if(VD(J))throw Error(`Registry item ${Z.id} targets a private network URL, refusing to create a monitor connection`);let G=Pg6($),K=Ag6(Z),W=await $.storage.connections.create({organization_id:X,created_by:G,title:`[MCP Tester] ${Z.title}`,description:`Auto-created monitor connection for ${Z.id}`,app_name:"private-registry-monitor",app_id:`${Lb}:monitor`,connection_type:K,connection_url:J,metadata:{monitorConnection:!0,registryItemId:Z.id,pluginId:Lb}});return await Q.monitorConnections.upsert({organization_id:X,item_id:Z.id,connection_id:W.id,auth_status:"none"}),W.id}async function vg6($){let Z=$.ctx.storage.registry;switch($.action){case"unlisted":return await Z.items.update($.organizationId,$.item.id,{is_unlisted:!0}),"unlisted";case"remove_public":return await Z.items.update($.organizationId,$.item.id,{is_public:!1}),"removed_public";case"remove_private":case"remove_all":return await Z.items.delete($.organizationId,$.item.id),$.action==="remove_all"?"removed_all":"removed_private";default:return"none"}}async function xg6($){let Z=Date.now();if($.signal.aborted)throw Error("Run cancelled");let Q="passed",X=!1,Y=!1,J=null,G="none",K=null,W=[],H=null,F=async()=>{await $.onProgress?.({status:Q,connectionOk:X,toolsListed:Y,toolResults:[...W],agentSummary:K,errorMessage:J,actionTaken:G,durationMs:Date.now()-Z})};try{let U=await EO1($.ctx,$.item);H=await $.ctx.createMCPProxy(U),X=!0;let B=(await a$0(H.listTools?H.listTools():Promise.resolve({tools:[]}),$.monitorConfig.perMcpTimeoutMs,`listTools ${$.item.id}`)).tools??[];if(Y=!0,$.monitorConfig.monitorMode!=="health_check")W.push(...B.map((O)=>jO1(O.name))),await F();if($.monitorConfig.monitorMode==="full_agent"){let O=await _g6({ctx:$.ctx,monitorConfig:$.monitorConfig,item:$.item,proxy:H,tools:B,signal:$.signal,onProgress:async(L)=>{W.length=0,W.push(...W78({discoveredTools:B,executedResults:L})),Q=L.some((w)=>!w.success)?"failed":"passed",await F()}});if(W.length=0,W.push(...W78({discoveredTools:B,executedResults:O.toolResults})),K=O.agentSummary,O.toolResults.some((L)=>!L.success))Q="failed";if(O.unexecutedTools.length>0){if(Q="failed",!J)J=`Agent skipped ${O.unexecutedTools.length} tool(s): ${O.unexecutedTools.join(", ")}`}}else if($.monitorConfig.monitorMode!=="health_check"){for(let O=0;O<B.length;O++){let L=B[O];if(!L||$.signal.aborted)throw Error("Run cancelled");let w=Date.now();try{let j={},E=await a$0(H.callTool({name:L.name,arguments:j}),$.monitorConfig.perToolTimeoutMs,`tool ${L.name}`),z=!E.isError,P=Date.now()-w;H78(W,{toolName:L.name,success:z,input:j,durationMs:P,outputPreview:B78(E.structuredContent??E.content),error:z?null:sk0(E.content?.find((A)=>A.type==="text")?.text?.slice(0,300)??"Tool returned error")}),await F()}catch(j){let E=Date.now()-w,z=j instanceof Error?j.message:String(j);H78(W,{toolName:L.name,success:!1,durationMs:E,error:sk0(z)}),await F()}}if(W.some((O)=>!O.success))Q="failed"}else for(let O of B)W.push(jO1(O.name));if($.canApplyFailureAction&&Q==="failed"&&$.monitorConfig.onFailure!=="none")G=await vg6({ctx:$.ctx,organizationId:$.organizationId,item:$.item,action:$.monitorConfig.onFailure})}catch(U){if(J=U instanceof Error?U.message:String(U),Rg6(U))Q="needs_auth",await $.ctx.storage.registry.monitorConnections.updateAuthStatus($.organizationId,$.item.id,"needs_auth");else Q="error"}finally{await H?.close?.().catch(()=>{})}return{status:Q,connectionOk:X,toolsListed:Y,toolResults:W,agentSummary:K,errorMessage:J,actionTaken:G,durationMs:Date.now()-Z}}async function fg6($){let Z=$.ctx.storage.registry,X=(await Z.items.list($.organizationId,{includeUnlisted:!0})).items.filter((F)=>{if($.monitorConfig.testPublicOnly&&!F.is_public)return!1;if($.monitorConfig.testPrivateOnly&&F.is_public)return!1;return!0}),Y=$.monitorConfig.includePendingRequests?(await Z.publishRequests.list($.organizationId,{status:"pending",limit:500})).items.map((F)=>bg6(F)):[],J=[...X.map((F)=>({item:F,source:"registry_item"})),...Y.map((F)=>({item:F,source:"publish_request"}))];if(J.length===0){await Z.monitorRuns.update($.organizationId,$.runId,{total_items:0,status:"completed",started_at:new Date().toISOString(),finished_at:new Date().toISOString()});return}await Z.monitorRuns.update($.organizationId,$.runId,{total_items:J.length,status:"running",started_at:new Date().toISOString()});let G=0,K=0,W=0,H=0;for(let F=0;F<J.length;F++){let U=J[F],N=U?.item;if(!N||$.signal.aborted){await Z.monitorRuns.update($.organizationId,$.runId,{status:"cancelled",current_item_id:null,finished_at:new Date().toISOString()});return}await Z.monitorRuns.update($.organizationId,$.runId,{current_item_id:N.id});let B=null,O=async(w)=>{if(!B){B=(await Z.monitorResults.create({run_id:$.runId,organization_id:$.organizationId,item_id:N.id,item_title:N.title,status:w.status,error_message:w.errorMessage,connection_ok:w.connectionOk,tools_listed:w.toolsListed,tool_results:w.toolResults,agent_summary:w.agentSummary,duration_ms:w.durationMs,action_taken:w.actionTaken})).id;return}await Z.monitorResults.update($.organizationId,B,{status:w.status,error_message:w.errorMessage,connection_ok:w.connectionOk,tools_listed:w.toolsListed,tool_results:w.toolResults,agent_summary:w.agentSummary,duration_ms:w.durationMs,action_taken:w.actionTaken})},L=await xg6({ctx:$.ctx,organizationId:$.organizationId,item:N,monitorConfig:$.monitorConfig,signal:$.signal,canApplyFailureAction:U.source==="registry_item",onProgress:O});if(await O({status:L.status,connectionOk:L.connectionOk,toolsListed:L.toolsListed,toolResults:L.toolResults,agentSummary:L.agentSummary,errorMessage:L.errorMessage,actionTaken:L.actionTaken,durationMs:L.durationMs}),G+=1,L.status==="passed")K+=1;else if(L.status==="failed"||L.status==="error")W+=1;else H+=1;await Z.monitorRuns.update($.organizationId,$.runId,{tested_items:G,passed_items:K,failed_items:W,skipped_items:H})}await Z.monitorRuns.update($.organizationId,$.runId,{status:"completed",current_item_id:null,finished_at:new Date().toISOString()})}function bg6($){return{id:`${jj}${$.id}`,title:$.title,description:$.description,_meta:$._meta,server:$.server,is_public:!1,is_unlisted:!0,created_at:$.created_at,updated_at:$.updated_at}}async function yg6($,Z){let Q=zg6($);await Q.access.check();let X=Q.storage.registry,Y=await X.monitorRuns.create({organization_id:Q.organization.id,status:"pending",config_snapshot:Z,started_at:null}),J=new AbortController;return ak0.set(Y.id,J),fg6({ctx:Q,runId:Y.id,organizationId:Q.organization.id,monitorConfig:Z,signal:J.signal}).catch(async(G)=>{await X.monitorRuns.update(Q.organization.id,Y.id,{status:"failed",current_item_id:null,finished_at:new Date().toISOString()}).catch(()=>{}),Eg6(`Run ${Y.id} failed with uncaught error:`,G)}).finally(()=>{ak0.delete(Y.id)}),{run:{id:Y.id}}}var ak0,Lg6="[MONITOR-AGENT]",wg6,jg6="health_check: not called",L78;var ek0=D(()=>{M0();x4();wz();Pd();CB();ak0=new Map,wg6=uZ8;L78=h({name:"REGISTRY_MONITOR_RUN_START",description:"Start an MCP registry monitor run with an isolated set of monitor connections.",inputSchema:pZ8,outputSchema:nZ8,handler:async($,Z)=>{let Q=t(Z);await Z.access.check();let X=iZ8($.config??{}),{run:Y}=await yg6(Z,X),G=await Z.storage.registry.monitorRuns.findById(Q.id,Y.id);if(!G)throw Error(`Failed to load monitor run ${Y.id}`);return{run:G}}})});var w78;var j78=D(()=>{M0();CB();w78=h({name:"REGISTRY_MONITOR_RUN_LIST",description:"List MCP registry monitor runs",inputSchema:rZ8,outputSchema:aZ8,handler:async($,Z)=>{let Q=t(Z);return await Z.access.check(),Z.storage.registry.monitorRuns.list(Q.id,$)}})});var E78;var z78=D(()=>{M0();CB();E78=h({name:"REGISTRY_MONITOR_RUN_GET",description:"Get details for one MCP registry monitor run",inputSchema:sZ8,outputSchema:eZ8,handler:async($,Z)=>{let Q=t(Z);return await Z.access.check(),{run:await Z.storage.registry.monitorRuns.findById(Q.id,$.runId)}}})});var P78;var A78=D(()=>{M0();CB();ek0();P78=h({name:"REGISTRY_MONITOR_RUN_CANCEL",description:"Cancel a running MCP registry monitor run",inputSchema:tZ8,outputSchema:oZ8,handler:async($,Z)=>{let Q=t(Z);await Z.access.check();let X=Z.storage.registry;if(!await X.monitorRuns.findById(Q.id,$.runId))throw Error(`Monitor run not found: ${$.runId}`);return N78($.runId),{run:await X.monitorRuns.update(Q.id,$.runId,{status:"cancelled",current_item_id:null,finished_at:new Date().toISOString()})}}})});var T78;var R78=D(()=>{M0();CB();T78=h({name:"REGISTRY_MONITOR_RESULT_LIST",description:"List results for a given MCP registry monitor run",inputSchema:$78,outputSchema:Z78,handler:async($,Z)=>{let Q=t(Z);return await Z.access.check(),Z.storage.registry.monitorResults.listByRun(Q.id,$.runId,{status:$.status,limit:$.limit,offset:$.offset})}})});var I78;var q78=D(()=>{M0();CB();Pd();I78=h({name:"REGISTRY_MONITOR_CONNECTION_LIST",description:"List monitor connection mappings for private registry MCP monitor runs, including auth status",inputSchema:Q78,outputSchema:X78,handler:async($,Z)=>{let Q=t(Z);await Z.access.check();let X=Z.storage.registry,Y=await X.monitorConnections.list(Q.id);return{items:await Promise.all(Y.map(async(G)=>{let K=await X.items.findById(Q.id,G.item_id);if(!K&&G.item_id.startsWith(jj)){let F=G.item_id.slice(jj.length),U=await X.publishRequests.findById(Q.id,F);if(U)K={id:G.item_id,title:U.title,description:U.description,_meta:U._meta,server:U.server,is_public:!1,is_unlisted:!0,created_at:U.created_at,updated_at:U.updated_at}}let W=K?.server.remotes?.find((F)=>F.url)?.url??null,H=G.item_id.startsWith(jj)?"request":"store";return{mapping:G,item:K,remoteUrl:W,source:H}}))}}})});function gg6($){return{id:`${jj}${$.id}`,title:$.title,description:$.description,_meta:$._meta,server:$.server,is_public:!1,is_unlisted:!0,created_at:$.created_at,updated_at:$.updated_at}}var M78;var V78=D(()=>{M0();CB();ek0();Pd();M78=h({name:"REGISTRY_MONITOR_CONNECTION_SYNC",description:"Ensure every registry item has a dedicated monitor connection mapping for MCP monitors",inputSchema:Y78,outputSchema:J78,handler:async($,Z)=>{let Q=t(Z);await Z.access.check();let X=Z.storage.registry,Y=(await X.items.list(Q.id,{includeUnlisted:!0})).items,G=(await X.publishRequests.list(Q.id,{status:"pending",limit:500})).items.map(gg6),K=[...Y,...G],W=await X.monitorConnections.list(Q.id),H=new Set(W.map((U)=>U.item_id)),F=0;for(let U of K){if(!U.server.remotes?.some((N)=>N.url))continue;try{await EO1(Z,U)}catch(N){console.warn(`[REGISTRY_MONITOR_CONNECTION_SYNC] Skipping ${U.id}:`,N instanceof Error?N.message:N);continue}if(!H.has(U.id))F+=1}return{created:F,updated:Math.max(K.length-F,0)}}})});var k78;var S78=D(()=>{M0();CB();k78=h({name:"REGISTRY_MONITOR_CONNECTION_UPDATE_AUTH",description:"Update the auth_status of a monitor connection mapping (by core connection ID)",inputSchema:G78,outputSchema:K78,handler:async({connectionId:$,authStatus:Z},Q)=>{let X=t(Q);await Q.access.check();let Y=Q.storage.registry,J=X.id,G=await Y.monitorConnections.findByConnectionId(J,$);if(!G)throw Error(`No monitor connection mapping found for connection ${$}`);return await Y.monitorConnections.updateAuthStatus(J,G.item_id,Z),{success:!0}}})});function hg6($){if(!$)return{};if(typeof $==="string")try{return JSON.parse($)}catch{return{}}if(typeof $==="object")return $;return{}}async function s$0($,Z){let X=(await $.db.selectFrom("virtual_mcp_plugin_configs").innerJoin("connections","connections.id","virtual_mcp_plugin_configs.virtual_mcp_id").select(["virtual_mcp_plugin_configs.settings as settings"]).where("connections.organization_id","=",Z).where("virtual_mcp_plugin_configs.plugin_id","=",Lb).execute()).map((J)=>hg6(J.settings)),Y={acceptPublishRequests:X.some((J)=>J.acceptPublishRequests===!0),requireApiToken:X.some((J)=>J.requireApiToken===!0),storePrivateOnly:X.some((J)=>J.storePrivateOnly===!0)};if(Y.acceptPublishRequests||Y.requireApiToken||Y.storePrivateOnly)return Y;for(let J of X)if(Object.keys(J).length>0)return J;return{}}var C78=D(()=>{Pd()});import{z as zO1}from"zod";function ug6($,Z){if(!Z)return $;let Q={field:["is_public"],operator:"eq",value:!1};if(!$)return Q;return{operator:"and",conditions:[$,Q]}}function cg6($){let Z=new Map,Q=new Map;for(let Y of $){let J=RH(Y._meta);for(let G of J?.tags??[])Z.set(G,(Z.get(G)??0)+1);for(let G of J?.categories??[])Q.set(G,(Q.get(G)??0)+1)}let X=(Y)=>Array.from(Y.entries()).map(([J,G])=>({value:J,count:G})).sort((J,G)=>J.value.localeCompare(G.value));return{tags:X(Z),categories:X(Q)}}var _78,v78,x78,f78;var b78=D(()=>{M0();v9();C78();_78=h({name:"COLLECTION_REGISTRY_APP_LIST",description:"List registry items for Store discovery. Supports private-only mode from plugin settings.",inputSchema:Ld,outputSchema:wd,handler:async($,Z)=>{let Q=t(Z);await Z.access.check();let X=Z.storage.registry,Y=await s$0(Z,Q.id);return X.items.list(Q.id,{...$,where:ug6($.where,Y.storePrivateOnly===!0)})}}),v78=h({name:"COLLECTION_REGISTRY_APP_GET",description:"Get a registry item for Store details. Respects private-only mode from plugin settings.",inputSchema:QU,outputSchema:Db,handler:async($,Z)=>{let Q=t(Z);await Z.access.check();let X=Z.storage.registry,Y=await s$0(Z,Q.id),J=$.id??$.name;if(!J)return{item:null};let G=await X.items.findByIdOrName(Q.id,J);if(!G)return{item:null};if(Y.storePrivateOnly&&G.is_public)return{item:null};return{item:G}}}),x78=h({name:"COLLECTION_REGISTRY_APP_VERSIONS",description:"Get registry item versions for Store details. Respects private-only mode from plugin settings.",inputSchema:QU,outputSchema:zO1.object({versions:zO1.array(uW)}),handler:async($,Z)=>{let Q=t(Z);await Z.access.check();let X=Z.storage.registry,Y=await s$0(Z,Q.id),J=$.id??$.name;if(!J)return{versions:[]};let G=await X.items.findByIdOrName(Q.id,J);if(!G)return{versions:[]};if(Y.storePrivateOnly&&G.is_public)return{versions:[]};return{versions:[G]}}}),f78=h({name:"COLLECTION_REGISTRY_APP_FILTERS",description:"List Store filter facets for registry items. Respects private-only mode from plugin settings.",inputSchema:zO1.object({}),outputSchema:jd,handler:async($,Z)=>{let Q=t(Z);await Z.access.check();let X=Z.storage.registry;if(!(await s$0(Z,Q.id)).storePrivateOnly)return X.items.getFilters(Q.id);let J=await X.items.list(Q.id,{limit:1e4,where:{field:["is_public"],operator:"eq",value:!1}});return cg6(J.items)}})});var y78;var g78=D(()=>{GZ8();WZ8();FZ8();NZ8();wz();OZ8();LZ8();jZ8();zZ8();AZ8();IZ8();MZ8();kZ8();CZ8();vZ8();fZ8();yZ8();hZ8();ek0();j78();z78();A78();R78();q78();V78();S78();b78();y78=[_78,v78,x78,f78,wZ8,EZ8,DZ8,RZ8,HZ8,JZ8,PZ8,UZ8,BZ8,_J$,KZ8,qZ8,VZ8,SZ8,_Z8,xZ8,bZ8,gZ8,L78,w78,E78,P78,T78,I78,M78,k78]});import{z as Ad}from"zod";var PO1;var h78=D(()=>{M0();KW();we();xY();PO1=h({name:"SANDBOX_DELETE",description:"Delete a sandbox.",annotations:{title:"Delete VM Preview",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!0},_meta:{ui:{visibility:"app"}},inputSchema:Ad.object({virtualMcpId:Ad.string().describe("Virtual MCP ID that owns this VM"),branch:Ad.string().min(1).describe("Branch whose vm should be deleted (sandboxMap[userId][branch])"),removeWorktree:Ad.boolean().optional().default(!1).describe("Also reclaim the sandbox's workspace (local worktree + disk). Ignored by hosted teardown, whose filesystem is already destroyed.")}),outputSchema:Ad.object({success:Ad.boolean()}),handler:async($,Z)=>{let Q;try{Q=await lx$($,Z)}catch(K){if(K instanceof Error&&K.message==="Virtual MCP not found")return{success:!0};throw K}let{entry:X,userId:Y,sandboxUserId:J}=Q;if(!X)return{success:!0};let G=await m71(Z);return await Yw(Z.storage.virtualMcps,$.virtualMcpId,Y,J,$.branch),await G.delete(X.sandboxHandle).catch((K)=>console.error(`[SANDBOX_DELETE] ${d7} ${X.sandboxHandle}: ${K instanceof Error?K.message:String(K)}`)),{success:!0}}})});var u78=D(()=>{Pe();h78()});import{z as _B}from"zod";function pg6($){try{return JSON.parse($)}catch(Z){throw Error(`GitHub /user/installations returned invalid JSON: ${$.slice(0,300)}`,{cause:Z})}}var dg6="https://api.github.com",ig6=15000,AO1;var c78=D(()=>{M0();K3();TY();tK();Zs();qc();AO1=h({name:"GITHUB_LIST_USER_ORGS",description:"List GitHub App installations (orgs/accounts) accessible to the authenticated user.",annotations:{title:"List GitHub User Orgs",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},_meta:{ui:{visibility:"app"}},inputSchema:_B.object({connectionId:_B.string().describe("ID of the mcp-github connection to use")}),outputSchema:_B.object({installations:_B.array(_B.object({installationId:_B.number(),login:_B.string(),avatarUrl:_B.string(),type:_B.string()}))}),handler:async($,Z)=>{await Z.access.check();let Q=Z.organization?.id;if(!Q)throw Error("Organization context required");let X=await Z.storage.connections.findById($.connectionId,Q);if(!X)throw Error("Connection not found");if(J9(X))throw Error("Repo-scoped connections cannot list installations \u2014 use an org-level mcp-github connection");let Y=new C5(Z.db,Z.vault),J=await Y.get($.connectionId);if(!J)throw Error("No GitHub token found. Ensure the mcp-github connection is authenticated.");let G=J.accessToken;if(mL(J)&&Y.isExpired(J,Ws)){let U=await $S0(J,Y);if(!U)throw Error(VZ);G=U,J=await Y.get($.connectionId)??J}let K=[],W=1,H=100,F=async(U)=>fetch(`${dg6}/user/installations?per_page=${H}&page=${W}`,{headers:{Authorization:`Bearer ${U}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"},signal:AbortSignal.timeout(ig6)});while(!0){let U=await F(G);if(U.status===401){let B=await Y.get($.connectionId);if(!B||!mL(B))throw Error(VZ);let O=await $S0(B,Y);if(!O)throw Error(VZ);if(G=O,U=await F(G),U.status===401)throw Error(VZ)}if(uL(U.headers,{lane:"rest",operation:"list_user_installations",installation:i51}),gL(U)){let B=U.headers.get("retry-after")!==null?"secondary":"primary";cL({lane:"rest",operation:"list_user_installations",installation:i51,kind:B});let O=hL(U.headers);throw Error(`GitHub ${B} rate limit reached${O===null?"":`; retry in ${Math.ceil(O/1000)}s`}`)}if(!U.ok)throw Error(`GitHub /user/installations failed: ${U.status}`);let N=pg6(await U.text());for(let B of N.installations)K.push({installationId:B.id,login:B.account.login,avatarUrl:B.account.avatar_url,type:B.account.type});if(N.installations.length<H)break;W++}return{installations:K}}})});var l78=D(()=>{c78()});import{z as TO1}from"zod";function ZS0($){return{repositoryId:$.repositoryId,ref:$.repoUrl?eK($.repoUrl):null,connectionId:$.connectionId}}var vB,m78="No credential for this repository \u2014 link it in Settings \u2192 Repositories";var RO1=D(()=>{t5();vB={repositoryId:TO1.string().optional().describe("Connected repository (REPOSITORY_LINK) to act on"),repoUrl:TO1.string().optional().describe("Any URL of the repository \u2014 its provider and host are read from it"),connectionId:TO1.string().optional().describe("Legacy: a repo-scoped mcp-github connection in this org")}});import{z as cW}from"zod";var IO1;var d78=D(()=>{M0();H7();RO1();IO1=h({name:"REPOSITORY_SEARCH_BRANCHES",description:"Search a repository's branches by a case-insensitive substring of the branch name, filtered server-side by the provider.",annotations:{title:"Search Repository Branches",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},_meta:{ui:{visibility:"app"}},inputSchema:cW.object({...vB,query:cW.string().describe("Substring to match against branch names. Empty returns the first branches alphabetically."),limit:cW.number().int().min(1).max(100).default(30),cursor:cW.string().nullish().describe("Opaque cursor from a previous call's `nextCursor`, to read the next window")}),outputSchema:cW.object({branches:cW.array(cW.object({name:cW.string(),author:cW.string().nullable()})),totalCount:cW.number(),nextCursor:cW.string().nullable()}),handler:async($,Z)=>{await Z.access.check();let Q=Z.organization?.id;if(!Q)throw Error("Organization context required");return(await w91(Z,Q,ZS0($))).searchBranches({query:$.query,limit:$.limit,cursor:$.cursor})}})});import{z as m$}from"zod";function p78($){let{credentialConnectionId:Z,...Q}=$;return{...Q,servable:Js($)}}function qO1($){let{legacyConnectionId:Z,...Q}=$;return Q}async function n78($,Z,Q){let X=await $.storage.gitProviderAccounts.get(Q,Z);if(!X)throw Error("Git account not found");return X}var tg6,i78,t78,o78,r78,a78,s78,e78,$Q8,ZQ8;var QQ8=D(()=>{Fs();t5();M0();H7();d78();tg6=m$.object({ref:oE$,externalId:m$.string(),defaultBranch:m$.string().nullable(),webUrl:m$.string(),visibility:m$.enum(["public","private","internal"]),description:m$.string().nullable(),updatedAt:m$.string().nullable()}),i78=rE$.extend({servable:m$.boolean()});t78=h({name:"GIT_PROVIDER_CAPABILITIES",description:"Which git providers this deployment can connect through Studio-owned credentials, and the URLs that start each connect flow.",annotations:{title:"Git provider capabilities",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},_meta:{ui:{visibility:"app"}},inputSchema:m$.object({}),outputSchema:m$.object({github:m$.object({configured:m$.boolean(),connectPath:m$.string().nullable(),installPath:m$.string().nullable()}),gitlab:m$.object({oauthHosts:m$.array(m$.string()),connectPath:m$.string().nullable()})}),handler:async($,Z)=>{r(Z);let Q=t(Z),X=`/api/${Q.slug??Q.id}/git-providers`,Y=az$(),J=Y.github.configured;return{github:{configured:J,connectPath:J?`${X}/github/connect`:null,installPath:J?`${X}/github/install`:null},gitlab:{oauthHosts:Y.gitlab.hosts,connectPath:Y.gitlab.configured?`${X}/gitlab/connect`:null}}}}),o78=h({name:"GIT_ACCOUNT_LIST",description:"List the git provider accounts connected to this organization.",annotations:{title:"List git accounts",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},_meta:{ui:{visibility:"app"}},inputSchema:m$.object({}),outputSchema:m$.object({accounts:m$.array(i78)}),handler:async($,Z)=>{r(Z),await Z.access.check();let Q=t(Z);return{accounts:(await Z.storage.gitProviderAccounts.listByOrg(Q.id)).map(p78)}}}),r78=h({name:"GIT_ACCOUNT_CONNECT_TOKEN",description:"Connect a git provider account with a personal, project or group access token. Validates the token against the provider before storing it encrypted. Use this for self-managed GitLab instances (no OAuth application) or when OAuth is not wanted.",annotations:{title:"Connect git account with a token",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},_meta:{ui:{visibility:"app"}},inputSchema:m$.object({type:ra.describe("Provider; only gitlab accepts tokens today"),host:m$.string().min(1).describe("Provider host, e.g. gitlab.com or gitlab.acme.com"),token:m$.string().min(1).describe("Access token with api scope")}),outputSchema:m$.object({account:i78}),handler:async($,Z)=>{r(Z),await Z.access.check();let Q=t(Z),X=$.host.trim().toLowerCase();if(!/^[a-z0-9.-]+(:[0-9]+)?$/.test(X))throw Error("host must be a bare hostname, optionally with a port");let Y=await nz$($.type,X,$.token),J=await Z.storage.gitProviderAccounts.upsert({organizationId:Q.id,type:$.type,host:X,authKind:"token",externalAccountId:Y.externalAccountId,login:Y.login,avatarUrl:Y.avatarUrl,createdBy:o0(Z)??null});return await Z.storage.gitProviderAccountCredentials.upsert({connectionId:J.id,accessToken:$.token,refreshToken:null,scope:null,expiresAt:null,clientId:null,clientSecret:null,tokenEndpoint:null}),{account:p78(J)}}}),a78=h({name:"GIT_ACCOUNT_DELETE",description:"Disconnect a git provider account. Its repositories stay linked but lose credentials (they become anonymous clones) until linked to another account.",annotations:{title:"Disconnect git account",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},_meta:{ui:{visibility:"app"}},inputSchema:m$.object({id:m$.string()}),outputSchema:m$.object({deleted:m$.boolean()}),handler:async($,Z)=>{r(Z),await Z.access.check();let Q=t(Z);return{deleted:await Z.storage.gitProviderAccounts.delete($.id,Q.id)}}}),s78=h({name:"REPOSITORY_LIST",description:"List the repositories linked to this organization.",annotations:{title:"List repositories",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},_meta:{ui:{visibility:"app"}},inputSchema:m$.object({accountId:m$.string().optional().describe("Only repositories of this account")}),outputSchema:m$.object({repositories:m$.array(h51.extend({usable:m$.boolean()}))}),handler:async($,Z)=>{r(Z),await Z.access.check();let Q=t(Z),X=await Z.storage.repositories.listByOrg(Q.id,{accountId:$.accountId}),Y=await pL(Z,Q.id),J=new Set(Y.map((G)=>G.webUrl.toLowerCase()));return{repositories:X.map((G)=>({...qO1(G),usable:J.has(G.webUrl.toLowerCase())}))}}}),e78=h({name:"REPOSITORY_SEARCH",description:"Search the repositories an account can reach on its provider (not yet linked). Feeds the repository picker.",annotations:{title:"Search provider repositories",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},_meta:{ui:{visibility:"app"}},inputSchema:m$.object({accountId:m$.string(),query:m$.string().optional(),page:m$.number().int().min(1).optional(),perPage:m$.number().int().min(1).max(100).optional()}),outputSchema:m$.object({repositories:m$.array(tg6),hasMore:m$.boolean()}),handler:async($,Z)=>{r(Z),await Z.access.check();let Q=t(Z),X=await n78(Z,Q.id,$.accountId);return CP({db:Z.db,vault:Z.vault},X).listRepos({query:$.query,page:$.page,perPage:$.perPage})}}),$Q8=h({name:"REPOSITORY_LINK",description:"Link a repository to the organization. With an account, the repository is verified against the provider and its facts (id, default branch, visibility) recorded; without one it is linked as an anonymous public clone.",annotations:{title:"Link repository",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},_meta:{ui:{visibility:"app"}},inputSchema:m$.object({url:m$.string().min(1).describe("Repository URL (https or ssh), or a bare path like owner/name when accountId is given"),accountId:m$.string().optional().describe("Account whose credentials access the repository")}),outputSchema:m$.object({repository:h51}),handler:async($,Z)=>{r(Z),await Z.access.check();let Q=t(Z),X=o0(Z)??null;if(!$.accountId){let H=eK($.url);if(!H)throw Error("Could not recognise the repository URL. Use a full https URL from GitHub or GitLab.");let F=await Z.storage.repositories.upsert({organizationId:Q.id,ref:H,createdBy:X});return{repository:qO1(F)}}let Y=await n78(Z,Q.id,$.accountId),J=eK($.url,{provider:Y.type,host:Y.host});if(!J)throw Error("Could not recognise the repository URL or path");if(J.host!==Y.host)throw Error(`Repository is on ${J.host} but the account is on ${Y.host}`);let K=await CP({db:Z.db,vault:Z.vault},Y).getRepo(J);if(!K)throw Error(`${J.path} was not found on ${J.host} or the account cannot access it`);let W=await Z.storage.repositories.upsert({organizationId:Q.id,ref:K.ref,accountId:Y.id,externalId:K.externalId,defaultBranch:K.defaultBranch,visibility:K.visibility,createdBy:X});return{repository:qO1(W)}}}),ZQ8=h({name:"REPOSITORY_DELETE",description:"Unlink a repository from the organization. Agents, tasks and syncs that referenced it keep working off their legacy metadata until relinked.",annotations:{title:"Unlink repository",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},_meta:{ui:{visibility:"app"}},inputSchema:m$.object({id:m$.string()}),outputSchema:m$.object({deleted:m$.boolean()}),handler:async($,Z)=>{r(Z),await Z.access.check();let Q=t(Z);return{deleted:await Z.storage.repositories.delete($.id,Q.id)}}})});import{z as J$}from"zod";async function Td($,Z){let Q=$.organization?.id;if(!Q)throw Error("Organization context required");let X=await Hs($,Q,ZS0(Z));if(!X)throw Error(m78);return X}var rg6,ag6,QS0,sg6,XQ8,YQ8,JQ8,GQ8,KQ8,WQ8;var HQ8=D(()=>{M0();H7();RO1();rg6=J$.object({id:J$.string().nullable(),name:J$.string(),state:J$.enum(["queued","running","completed"]),conclusion:J$.enum(["success","failure","neutral","cancelled","skipped","timed_out","action_required"]).nullable(),url:J$.string().nullable(),durationMs:J$.number().nullable(),summary:J$.string().nullable()}),ag6=J$.object({id:J$.string(),author:J$.string(),body:J$.string(),createdAt:J$.string(),updatedAt:J$.string(),url:J$.string()}),QS0=J$.object({number:J$.number(),url:J$.string(),title:J$.string(),body:J$.string(),state:J$.enum(["open","closed","merged"]),draft:J$.boolean(),mergedAt:J$.string().nullable(),base:J$.string(),head:J$.string(),headSha:J$.string(),headRepoPath:J$.string().nullable(),author:J$.string(),conflicting:J$.boolean().nullable(),checks:J$.enum(["pending","passing","failing"]).nullable(),changedFiles:J$.number().nullable()}),sg6=QS0.extend({checkRuns:J$.array(rg6),comments:J$.array(ag6),unresolvedConversations:J$.number(),reviewBlocked:J$.boolean()}),XQ8=h({name:"CHANGE_REQUEST_STATE",description:"Read a branch's change request with its CI runs, review state and comments.",annotations:{title:"Read Change Request State",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},_meta:{ui:{visibility:"app"}},inputSchema:J$.object({...vB,branch:J$.string().describe("Head branch of the change request to read")}),outputSchema:J$.object({changeRequest:sg6.nullable()}),handler:async($,Z)=>{return await Z.access.check(),{changeRequest:await(await Td(Z,$)).readDetailed({branch:$.branch})}}}),YQ8=h({name:"CHANGE_REQUEST_LAST_MERGED",description:"Read the most recently merged change request into a base branch \u2014 in Fast Preview, the last publish.",annotations:{title:"Read Last Merged Change Request",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},_meta:{ui:{visibility:"app"}},inputSchema:J$.object({...vB,base:J$.string().describe("Branch it was merged into")}),outputSchema:J$.object({changeRequest:QS0.nullable()}),handler:async($,Z)=>{return await Z.access.check(),{changeRequest:await(await Td(Z,$)).lastMergedInto($.base)}}}),JQ8=h({name:"CHANGE_REQUEST_LIST_OPEN",description:"List a repository's open change requests, most recently updated first.",annotations:{title:"List Open Change Requests",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},_meta:{ui:{visibility:"app"}},inputSchema:J$.object({...vB,limit:J$.number().int().min(1).max(100).default(50)}),outputSchema:J$.object({changeRequests:J$.array(QS0)}),handler:async($,Z)=>{return await Z.access.check(),{changeRequests:await(await Td(Z,$)).listOpen($.limit)}}}),GQ8=h({name:"CHANGE_REQUEST_CHECK_LOG",description:"Read one CI run's report \u2014 a GitHub check run's output markdown, or the tail of a GitLab job's trace.",annotations:{title:"Read CI Run Report",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},_meta:{ui:{visibility:"app"}},inputSchema:J$.object({...vB,checkId:J$.string().describe("Provider id of the run, from its listing")}),outputSchema:J$.object({report:J$.string().nullable()}),handler:async($,Z)=>{return await Z.access.check(),{report:await(await Td(Z,$)).readCheckLog($.checkId)}}}),KQ8=h({name:"CHANGE_REQUEST_OPEN",description:"Propose a branch onto another. Returns the branch's existing change request instead of failing when it already has one.",annotations:{title:"Open Change Request",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},_meta:{ui:{visibility:"app"}},inputSchema:J$.object({...vB,head:J$.string().describe("Branch being proposed"),base:J$.string().describe("Branch it should land on"),title:J$.string(),body:J$.string().optional()}),outputSchema:J$.object({changeRequest:QS0,existed:J$.boolean()}),handler:async($,Z)=>{await Z.access.check();let Q=await Td(Z,$),X=await Q.readForBranch($.head);if(X&&X.state==="open"){if($.body&&$.body!==X.body)await Q.describe(X.number,$.body);return{changeRequest:$.body?{...X,body:$.body}:X,existed:!0}}return{changeRequest:await Q.open({head:$.head,base:$.base,title:$.title,body:$.body}),existed:!1}}}),WQ8=h({name:"CHANGE_REQUEST_MERGE",description:"Land a change request. Reports why it could not merge rather than throwing.",annotations:{title:"Merge Change Request",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0},_meta:{ui:{visibility:"app"}},inputSchema:J$.object({...vB,number:J$.number().int().positive(),strategy:J$.enum(["any","squash"]).default("any").describe("`squash` when the result must be one commit; `any` uses whatever the repository allows"),commitTitle:J$.string().optional(),commitMessage:J$.string().optional()}),outputSchema:J$.object({merged:J$.boolean(),reason:J$.enum(["conflict","blocked","rate_limited","not_found","error"]).optional(),detail:J$.string().optional()}),handler:async($,Z)=>{await Z.access.check();let X=await(await Td(Z,$)).merge($.number,{strategy:$.strategy,commitTitle:$.commitTitle,commitMessage:$.commitMessage});return X.merged?{merged:!0}:{merged:!1,reason:X.reason,detail:X.detail}}})});import{z as h6}from"zod";function XS0($){if(!$)return"";return typeof $==="string"?$:$.toISOString()}function FQ8($){let Z=$.trim();return Z.length>0?Z:void 0}function UQ8($,Z){return $===void 0||$.includes(Z)}var $h6,Zh6,Qh6,Xh6,Yh6,Jh6,MO1;var NQ8=D(()=>{M0();kY1();$h6=["thread","task"],Zh6=h6.object({type:h6.literal("thread"),id:h6.string(),title:h6.string(),created_at:h6.string(),updated_at:h6.string(),virtual_mcp_id:h6.string().nullable(),run_config:h6.record(h6.string(),h6.unknown()).nullable(),status:h6.string().nullable()}),Qh6=h6.object({type:h6.literal("task"),id:h6.string(),title:h6.string(),created_at:h6.string(),updated_at:h6.string(),key:h6.string().nullable(),status:h6.string().nullable(),repo:h6.string().nullable()}),Xh6=h6.discriminatedUnion("type",[Zh6,Qh6]),Yh6=h6.object({query:h6.string().max(256).describe("Free-text search query. Empty string returns the most recently updated resources."),limit:h6.number().int().min(1).max(50).optional().describe("Maximum results per resource type (default: 20)."),types:h6.array(h6.enum($h6)).optional().describe("Restrict the search to specific resource types. Omit to search across all available types.")}),Jh6=h6.object({items:h6.array(Xh6),totalCount:h6.number()});MO1=h({name:"GLOBAL_SEARCH",description:"Search across organization resources by free-text query. Returns a typed union of matches (currently: threads and task-board cards). New resource types may be added over time without changes to the call shape.",annotations:{title:"Global Search",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:Yh6,outputSchema:Jh6,handler:async($,Z)=>{await Z.access.check();let Q=t(Z),X=$.limit??20,Y=UQ8($.types,"thread"),J=UQ8($.types,"task"),G=[],K=0;if(Y){let{threads:W,total:H}=await Z.storage.threads.list(void 0,{limit:X,offset:0,search:FQ8($.query),includeArchived:!1});K+=H;for(let F of W)G.push({type:"thread",id:F.id,title:F.title??"",created_at:XS0(F.created_at),updated_at:XS0(F.updated_at),virtual_mcp_id:F.virtual_mcp_id??null,run_config:F.run_config??null,status:P3(F).status})}if(J){let W=await Z.storage.taskBoard.searchByTitle(Q.id,FQ8($.query)??"",X);K+=W.length;for(let H of W)G.push({type:"task",id:H.id,title:H.title??"",created_at:XS0(H.createdAt),updated_at:XS0(H.updatedAt),key:Q.slug?NR0(Q.slug,H.keySeq):null,status:H.status??null,repo:H.repo??null})}return{items:G,totalCount:K}}})});var BQ8=D(()=>{NQ8()});var JW0={};e(JW0,{toolSubsetMCP:()=>VO1,managementMCP:()=>rl,managementContextStore:()=>OB,listManagementTools:()=>Kh6,TOOL_BY_NAME:()=>Rd,CORE_TOOLS:()=>DQ8});import{z as OQ8}from"zod";async function Kh6($){let Z=await rl($),[Q,X]=Ha.createLinkedPair();await Z.connect(X);let Y=new $Z({name:"tools-hydration",version:"1.0.0"},{jsonSchemaValidator:S5});try{return await Y.connect(Q),(await Y.listTools()).tools}finally{await Y.close().catch(()=>{}),await Z.close().catch(()=>{})}}var DQ8,Rd,VO1=($,Z)=>{let Q=new SH({name:$,version:"1.0.0"},{capabilities:{tools:{}},jsonSchemaValidator:S5});for(let X of Z){let Y=Rd.get(X);if(!Y){console.warn(`[${$}] unknown tool "${X}" \u2014 not registered`);continue}let{config:J,handler:G}=d$0(Y);Q.registerTool(Y.name,J,G)}return Q},rl=async($)=>{let Z=new SH({name:"mcp-cms-management",version:"1.0.0"},{capabilities:{tools:{},prompts:{},resources:{}},jsonSchemaValidator:S5});for(let Y of Rd.values()){let{config:J,handler:G}=d$0(Y);Z.registerTool(Y.name,J,G)}let Q=bk0();for(let Y of Q){let J=Y.arguments?.length?Object.fromEntries(Y.arguments.map((G)=>{let K=G.required?OQ8.string():OQ8.string().optional();return[G.name,G.description?K.describe(G.description):K]})):void 0;Z.registerPrompt(Y.name,{title:Y.title,description:Y.description,...J?{argsSchema:J}:{}},(G)=>{return{messages:[{role:"user",content:{type:"text",text:typeof Y.text==="function"?Y.text(G??{}):Y.text}}]}})}if($.organization?.id){let Y=await $.storage.brandContext.list($.organization.id),J=new Set;for(let G of Y){let K=G.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),W=K?`brand-${K}`:`brand-${G.id}`;if(J.has(W))W=`${W}-${G.id.slice(0,8)}`;J.add(W);let H=[`# Brand: ${G.name}`,"",`**Domain:** ${G.domain}`,"","## Overview",G.overview];if(G.colors){let U=Object.entries(G.colors).filter(([,N])=>N);if(U.length>0){H.push("","## Colors");for(let[N,B]of U)H.push(`- **${N}:** ${B}`)}}if(G.fonts){let U=Object.entries(G.fonts).filter(([,N])=>N);if(U.length>0){H.push("","## Fonts");for(let[N,B]of U)H.push(`- ${B} (${N})`)}}if(G.logo)H.push("",`**Logo:** ${G.logo}`);if(G.favicon)H.push(`**Favicon:** ${G.favicon}`);if(G.ogImage)H.push(`**OG Image:** ${G.ogImage}`);if(G.images&&G.images.length>0){H.push("","## Images");for(let U of G.images){let N=Object.entries(U).map(([B,O])=>`${B}: ${O}`).join(", ");H.push(`- ${N}`)}}let F=H.join(`
4568
+ `);return{toolResults:W,agentSummary:B.length>0?B:null,unexecutedTools:F}}finally{await Z.close?.().catch(()=>{})}}async function EO1($,Z){let Q=$.storage.registry,X=$.organization.id,Y=await Q.monitorConnections.findByItemId(X,Z.id);if(Y){if(await $.storage.connections.findById(Y.connection_id,X))return Y.connection_id}let J=Tg6(Z);if(!J)throw Error(`Registry item ${Z.id} has no remote URL`);if(VD(J))throw Error(`Registry item ${Z.id} targets a private network URL, refusing to create a monitor connection`);let G=Pg6($),K=Ag6(Z),W=await $.storage.connections.create({organization_id:X,created_by:G,title:`[MCP Tester] ${Z.title}`,description:`Auto-created monitor connection for ${Z.id}`,app_name:"private-registry-monitor",app_id:`${Lb}:monitor`,connection_type:K,connection_url:J,metadata:{monitorConnection:!0,registryItemId:Z.id,pluginId:Lb}});return await Q.monitorConnections.upsert({organization_id:X,item_id:Z.id,connection_id:W.id,auth_status:"none"}),W.id}async function vg6($){let Z=$.ctx.storage.registry;switch($.action){case"unlisted":return await Z.items.update($.organizationId,$.item.id,{is_unlisted:!0}),"unlisted";case"remove_public":return await Z.items.update($.organizationId,$.item.id,{is_public:!1}),"removed_public";case"remove_private":case"remove_all":return await Z.items.delete($.organizationId,$.item.id),$.action==="remove_all"?"removed_all":"removed_private";default:return"none"}}async function xg6($){let Z=Date.now();if($.signal.aborted)throw Error("Run cancelled");let Q="passed",X=!1,Y=!1,J=null,G="none",K=null,W=[],H=null,F=async()=>{await $.onProgress?.({status:Q,connectionOk:X,toolsListed:Y,toolResults:[...W],agentSummary:K,errorMessage:J,actionTaken:G,durationMs:Date.now()-Z})};try{let U=await EO1($.ctx,$.item);H=await $.ctx.createMCPProxy(U),X=!0;let B=(await a$0(H.listTools?H.listTools():Promise.resolve({tools:[]}),$.monitorConfig.perMcpTimeoutMs,`listTools ${$.item.id}`)).tools??[];if(Y=!0,$.monitorConfig.monitorMode!=="health_check")W.push(...B.map((O)=>jO1(O.name))),await F();if($.monitorConfig.monitorMode==="full_agent"){let O=await _g6({ctx:$.ctx,monitorConfig:$.monitorConfig,item:$.item,proxy:H,tools:B,signal:$.signal,onProgress:async(L)=>{W.length=0,W.push(...W78({discoveredTools:B,executedResults:L})),Q=L.some((w)=>!w.success)?"failed":"passed",await F()}});if(W.length=0,W.push(...W78({discoveredTools:B,executedResults:O.toolResults})),K=O.agentSummary,O.toolResults.some((L)=>!L.success))Q="failed";if(O.unexecutedTools.length>0){if(Q="failed",!J)J=`Agent skipped ${O.unexecutedTools.length} tool(s): ${O.unexecutedTools.join(", ")}`}}else if($.monitorConfig.monitorMode!=="health_check"){for(let O=0;O<B.length;O++){let L=B[O];if(!L||$.signal.aborted)throw Error("Run cancelled");let w=Date.now();try{let j={},E=await a$0(H.callTool({name:L.name,arguments:j}),$.monitorConfig.perToolTimeoutMs,`tool ${L.name}`),z=!E.isError,P=Date.now()-w;H78(W,{toolName:L.name,success:z,input:j,durationMs:P,outputPreview:B78(E.structuredContent??E.content),error:z?null:sk0(E.content?.find((A)=>A.type==="text")?.text?.slice(0,300)??"Tool returned error")}),await F()}catch(j){let E=Date.now()-w,z=j instanceof Error?j.message:String(j);H78(W,{toolName:L.name,success:!1,durationMs:E,error:sk0(z)}),await F()}}if(W.some((O)=>!O.success))Q="failed"}else for(let O of B)W.push(jO1(O.name));if($.canApplyFailureAction&&Q==="failed"&&$.monitorConfig.onFailure!=="none")G=await vg6({ctx:$.ctx,organizationId:$.organizationId,item:$.item,action:$.monitorConfig.onFailure})}catch(U){if(J=U instanceof Error?U.message:String(U),Rg6(U))Q="needs_auth",await $.ctx.storage.registry.monitorConnections.updateAuthStatus($.organizationId,$.item.id,"needs_auth");else Q="error"}finally{await H?.close?.().catch(()=>{})}return{status:Q,connectionOk:X,toolsListed:Y,toolResults:W,agentSummary:K,errorMessage:J,actionTaken:G,durationMs:Date.now()-Z}}async function fg6($){let Z=$.ctx.storage.registry,X=(await Z.items.list($.organizationId,{includeUnlisted:!0})).items.filter((F)=>{if($.monitorConfig.testPublicOnly&&!F.is_public)return!1;if($.monitorConfig.testPrivateOnly&&F.is_public)return!1;return!0}),Y=$.monitorConfig.includePendingRequests?(await Z.publishRequests.list($.organizationId,{status:"pending",limit:500})).items.map((F)=>bg6(F)):[],J=[...X.map((F)=>({item:F,source:"registry_item"})),...Y.map((F)=>({item:F,source:"publish_request"}))];if(J.length===0){await Z.monitorRuns.update($.organizationId,$.runId,{total_items:0,status:"completed",started_at:new Date().toISOString(),finished_at:new Date().toISOString()});return}await Z.monitorRuns.update($.organizationId,$.runId,{total_items:J.length,status:"running",started_at:new Date().toISOString()});let G=0,K=0,W=0,H=0;for(let F=0;F<J.length;F++){let U=J[F],N=U?.item;if(!N||$.signal.aborted){await Z.monitorRuns.update($.organizationId,$.runId,{status:"cancelled",current_item_id:null,finished_at:new Date().toISOString()});return}await Z.monitorRuns.update($.organizationId,$.runId,{current_item_id:N.id});let B=null,O=async(w)=>{if(!B){B=(await Z.monitorResults.create({run_id:$.runId,organization_id:$.organizationId,item_id:N.id,item_title:N.title,status:w.status,error_message:w.errorMessage,connection_ok:w.connectionOk,tools_listed:w.toolsListed,tool_results:w.toolResults,agent_summary:w.agentSummary,duration_ms:w.durationMs,action_taken:w.actionTaken})).id;return}await Z.monitorResults.update($.organizationId,B,{status:w.status,error_message:w.errorMessage,connection_ok:w.connectionOk,tools_listed:w.toolsListed,tool_results:w.toolResults,agent_summary:w.agentSummary,duration_ms:w.durationMs,action_taken:w.actionTaken})},L=await xg6({ctx:$.ctx,organizationId:$.organizationId,item:N,monitorConfig:$.monitorConfig,signal:$.signal,canApplyFailureAction:U.source==="registry_item",onProgress:O});if(await O({status:L.status,connectionOk:L.connectionOk,toolsListed:L.toolsListed,toolResults:L.toolResults,agentSummary:L.agentSummary,errorMessage:L.errorMessage,actionTaken:L.actionTaken,durationMs:L.durationMs}),G+=1,L.status==="passed")K+=1;else if(L.status==="failed"||L.status==="error")W+=1;else H+=1;await Z.monitorRuns.update($.organizationId,$.runId,{tested_items:G,passed_items:K,failed_items:W,skipped_items:H})}await Z.monitorRuns.update($.organizationId,$.runId,{status:"completed",current_item_id:null,finished_at:new Date().toISOString()})}function bg6($){return{id:`${jj}${$.id}`,title:$.title,description:$.description,_meta:$._meta,server:$.server,is_public:!1,is_unlisted:!0,created_at:$.created_at,updated_at:$.updated_at}}async function yg6($,Z){let Q=zg6($);await Q.access.check();let X=Q.storage.registry,Y=await X.monitorRuns.create({organization_id:Q.organization.id,status:"pending",config_snapshot:Z,started_at:null}),J=new AbortController;return ak0.set(Y.id,J),fg6({ctx:Q,runId:Y.id,organizationId:Q.organization.id,monitorConfig:Z,signal:J.signal}).catch(async(G)=>{await X.monitorRuns.update(Q.organization.id,Y.id,{status:"failed",current_item_id:null,finished_at:new Date().toISOString()}).catch(()=>{}),Eg6(`Run ${Y.id} failed with uncaught error:`,G)}).finally(()=>{ak0.delete(Y.id)}),{run:{id:Y.id}}}var ak0,Lg6="[MONITOR-AGENT]",wg6,jg6="health_check: not called",L78;var ek0=D(()=>{M0();x4();wz();Pd();CB();ak0=new Map,wg6=uZ8;L78=h({name:"REGISTRY_MONITOR_RUN_START",description:"Start an MCP registry monitor run with an isolated set of monitor connections.",inputSchema:pZ8,outputSchema:nZ8,handler:async($,Z)=>{let Q=t(Z);await Z.access.check();let X=iZ8($.config??{}),{run:Y}=await yg6(Z,X),G=await Z.storage.registry.monitorRuns.findById(Q.id,Y.id);if(!G)throw Error(`Failed to load monitor run ${Y.id}`);return{run:G}}})});var w78;var j78=D(()=>{M0();CB();w78=h({name:"REGISTRY_MONITOR_RUN_LIST",description:"List MCP registry monitor runs",inputSchema:rZ8,outputSchema:aZ8,handler:async($,Z)=>{let Q=t(Z);return await Z.access.check(),Z.storage.registry.monitorRuns.list(Q.id,$)}})});var E78;var z78=D(()=>{M0();CB();E78=h({name:"REGISTRY_MONITOR_RUN_GET",description:"Get details for one MCP registry monitor run",inputSchema:sZ8,outputSchema:eZ8,handler:async($,Z)=>{let Q=t(Z);return await Z.access.check(),{run:await Z.storage.registry.monitorRuns.findById(Q.id,$.runId)}}})});var P78;var A78=D(()=>{M0();CB();ek0();P78=h({name:"REGISTRY_MONITOR_RUN_CANCEL",description:"Cancel a running MCP registry monitor run",inputSchema:tZ8,outputSchema:oZ8,handler:async($,Z)=>{let Q=t(Z);await Z.access.check();let X=Z.storage.registry;if(!await X.monitorRuns.findById(Q.id,$.runId))throw Error(`Monitor run not found: ${$.runId}`);return N78($.runId),{run:await X.monitorRuns.update(Q.id,$.runId,{status:"cancelled",current_item_id:null,finished_at:new Date().toISOString()})}}})});var T78;var R78=D(()=>{M0();CB();T78=h({name:"REGISTRY_MONITOR_RESULT_LIST",description:"List results for a given MCP registry monitor run",inputSchema:$78,outputSchema:Z78,handler:async($,Z)=>{let Q=t(Z);return await Z.access.check(),Z.storage.registry.monitorResults.listByRun(Q.id,$.runId,{status:$.status,limit:$.limit,offset:$.offset})}})});var I78;var q78=D(()=>{M0();CB();Pd();I78=h({name:"REGISTRY_MONITOR_CONNECTION_LIST",description:"List monitor connection mappings for private registry MCP monitor runs, including auth status",inputSchema:Q78,outputSchema:X78,handler:async($,Z)=>{let Q=t(Z);await Z.access.check();let X=Z.storage.registry,Y=await X.monitorConnections.list(Q.id);return{items:await Promise.all(Y.map(async(G)=>{let K=await X.items.findById(Q.id,G.item_id);if(!K&&G.item_id.startsWith(jj)){let F=G.item_id.slice(jj.length),U=await X.publishRequests.findById(Q.id,F);if(U)K={id:G.item_id,title:U.title,description:U.description,_meta:U._meta,server:U.server,is_public:!1,is_unlisted:!0,created_at:U.created_at,updated_at:U.updated_at}}let W=K?.server.remotes?.find((F)=>F.url)?.url??null,H=G.item_id.startsWith(jj)?"request":"store";return{mapping:G,item:K,remoteUrl:W,source:H}}))}}})});function gg6($){return{id:`${jj}${$.id}`,title:$.title,description:$.description,_meta:$._meta,server:$.server,is_public:!1,is_unlisted:!0,created_at:$.created_at,updated_at:$.updated_at}}var M78;var V78=D(()=>{M0();CB();ek0();Pd();M78=h({name:"REGISTRY_MONITOR_CONNECTION_SYNC",description:"Ensure every registry item has a dedicated monitor connection mapping for MCP monitors",inputSchema:Y78,outputSchema:J78,handler:async($,Z)=>{let Q=t(Z);await Z.access.check();let X=Z.storage.registry,Y=(await X.items.list(Q.id,{includeUnlisted:!0})).items,G=(await X.publishRequests.list(Q.id,{status:"pending",limit:500})).items.map(gg6),K=[...Y,...G],W=await X.monitorConnections.list(Q.id),H=new Set(W.map((U)=>U.item_id)),F=0;for(let U of K){if(!U.server.remotes?.some((N)=>N.url))continue;try{await EO1(Z,U)}catch(N){console.warn(`[REGISTRY_MONITOR_CONNECTION_SYNC] Skipping ${U.id}:`,N instanceof Error?N.message:N);continue}if(!H.has(U.id))F+=1}return{created:F,updated:Math.max(K.length-F,0)}}})});var k78;var S78=D(()=>{M0();CB();k78=h({name:"REGISTRY_MONITOR_CONNECTION_UPDATE_AUTH",description:"Update the auth_status of a monitor connection mapping (by core connection ID)",inputSchema:G78,outputSchema:K78,handler:async({connectionId:$,authStatus:Z},Q)=>{let X=t(Q);await Q.access.check();let Y=Q.storage.registry,J=X.id,G=await Y.monitorConnections.findByConnectionId(J,$);if(!G)throw Error(`No monitor connection mapping found for connection ${$}`);return await Y.monitorConnections.updateAuthStatus(J,G.item_id,Z),{success:!0}}})});function hg6($){if(!$)return{};if(typeof $==="string")try{return JSON.parse($)}catch{return{}}if(typeof $==="object")return $;return{}}async function s$0($,Z){let X=(await $.db.selectFrom("virtual_mcp_plugin_configs").innerJoin("connections","connections.id","virtual_mcp_plugin_configs.virtual_mcp_id").select(["virtual_mcp_plugin_configs.settings as settings"]).where("connections.organization_id","=",Z).where("virtual_mcp_plugin_configs.plugin_id","=",Lb).execute()).map((J)=>hg6(J.settings)),Y={acceptPublishRequests:X.some((J)=>J.acceptPublishRequests===!0),requireApiToken:X.some((J)=>J.requireApiToken===!0),storePrivateOnly:X.some((J)=>J.storePrivateOnly===!0)};if(Y.acceptPublishRequests||Y.requireApiToken||Y.storePrivateOnly)return Y;for(let J of X)if(Object.keys(J).length>0)return J;return{}}var C78=D(()=>{Pd()});import{z as zO1}from"zod";function ug6($,Z){if(!Z)return $;let Q={field:["is_public"],operator:"eq",value:!1};if(!$)return Q;return{operator:"and",conditions:[$,Q]}}function cg6($){let Z=new Map,Q=new Map;for(let Y of $){let J=RH(Y._meta);for(let G of J?.tags??[])Z.set(G,(Z.get(G)??0)+1);for(let G of J?.categories??[])Q.set(G,(Q.get(G)??0)+1)}let X=(Y)=>Array.from(Y.entries()).map(([J,G])=>({value:J,count:G})).sort((J,G)=>J.value.localeCompare(G.value));return{tags:X(Z),categories:X(Q)}}var _78,v78,x78,f78;var b78=D(()=>{M0();v9();C78();_78=h({name:"COLLECTION_REGISTRY_APP_LIST",description:"List registry items for Store discovery. Supports private-only mode from plugin settings.",inputSchema:Ld,outputSchema:wd,handler:async($,Z)=>{let Q=t(Z);await Z.access.check();let X=Z.storage.registry,Y=await s$0(Z,Q.id);return X.items.list(Q.id,{...$,where:ug6($.where,Y.storePrivateOnly===!0)})}}),v78=h({name:"COLLECTION_REGISTRY_APP_GET",description:"Get a registry item for Store details. Respects private-only mode from plugin settings.",inputSchema:QU,outputSchema:Db,handler:async($,Z)=>{let Q=t(Z);await Z.access.check();let X=Z.storage.registry,Y=await s$0(Z,Q.id),J=$.id??$.name;if(!J)return{item:null};let G=await X.items.findByIdOrName(Q.id,J);if(!G)return{item:null};if(Y.storePrivateOnly&&G.is_public)return{item:null};return{item:G}}}),x78=h({name:"COLLECTION_REGISTRY_APP_VERSIONS",description:"Get registry item versions for Store details. Respects private-only mode from plugin settings.",inputSchema:QU,outputSchema:zO1.object({versions:zO1.array(uW)}),handler:async($,Z)=>{let Q=t(Z);await Z.access.check();let X=Z.storage.registry,Y=await s$0(Z,Q.id),J=$.id??$.name;if(!J)return{versions:[]};let G=await X.items.findByIdOrName(Q.id,J);if(!G)return{versions:[]};if(Y.storePrivateOnly&&G.is_public)return{versions:[]};return{versions:[G]}}}),f78=h({name:"COLLECTION_REGISTRY_APP_FILTERS",description:"List Store filter facets for registry items. Respects private-only mode from plugin settings.",inputSchema:zO1.object({}),outputSchema:jd,handler:async($,Z)=>{let Q=t(Z);await Z.access.check();let X=Z.storage.registry;if(!(await s$0(Z,Q.id)).storePrivateOnly)return X.items.getFilters(Q.id);let J=await X.items.list(Q.id,{limit:1e4,where:{field:["is_public"],operator:"eq",value:!1}});return cg6(J.items)}})});var y78;var g78=D(()=>{GZ8();WZ8();FZ8();NZ8();wz();OZ8();LZ8();jZ8();zZ8();AZ8();IZ8();MZ8();kZ8();CZ8();vZ8();fZ8();yZ8();hZ8();ek0();j78();z78();A78();R78();q78();V78();S78();b78();y78=[_78,v78,x78,f78,wZ8,EZ8,DZ8,RZ8,HZ8,JZ8,PZ8,UZ8,BZ8,_J$,KZ8,qZ8,VZ8,SZ8,_Z8,xZ8,bZ8,gZ8,L78,w78,E78,P78,T78,I78,M78,k78]});import{z as Ad}from"zod";var PO1;var h78=D(()=>{M0();KW();we();xY();PO1=h({name:"SANDBOX_DELETE",description:"Delete a sandbox.",annotations:{title:"Delete VM Preview",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!0},_meta:{ui:{visibility:"app"}},inputSchema:Ad.object({virtualMcpId:Ad.string().describe("Virtual MCP ID that owns this VM"),branch:Ad.string().min(1).describe("Branch whose vm should be deleted (sandboxMap[userId][branch])"),removeWorktree:Ad.boolean().optional().default(!1).describe("Also reclaim the sandbox's workspace (local worktree + disk). Ignored by hosted teardown, whose filesystem is already destroyed.")}),outputSchema:Ad.object({success:Ad.boolean()}),handler:async($,Z)=>{let Q;try{Q=await lx$($,Z)}catch(K){if(K instanceof Error&&K.message==="Virtual MCP not found")return{success:!0};throw K}let{entry:X,userId:Y,sandboxUserId:J}=Q;if(!X)return{success:!0};let G=await m71(Z);return await Yw(Z.storage.virtualMcps,$.virtualMcpId,Y,J,$.branch),await G.delete(X.sandboxHandle).catch((K)=>console.error(`[SANDBOX_DELETE] ${d7} ${X.sandboxHandle}: ${K instanceof Error?K.message:String(K)}`)),{success:!0}}})});var u78=D(()=>{Pe();h78()});import{z as _B}from"zod";function pg6($){try{return JSON.parse($)}catch(Z){throw Error(`GitHub /user/installations returned invalid JSON: ${$.slice(0,300)}`,{cause:Z})}}var dg6="https://api.github.com",ig6=15000,AO1;var c78=D(()=>{M0();K3();TY();tK();Zs();qc();AO1=h({name:"GITHUB_LIST_USER_ORGS",description:"List GitHub App installations (orgs/accounts) accessible to the authenticated user.",annotations:{title:"List GitHub User Orgs",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},_meta:{ui:{visibility:"app"}},inputSchema:_B.object({connectionId:_B.string().describe("ID of the mcp-github connection to use")}),outputSchema:_B.object({installations:_B.array(_B.object({installationId:_B.number(),login:_B.string(),avatarUrl:_B.string(),type:_B.string()}))}),handler:async($,Z)=>{await Z.access.check();let Q=Z.organization?.id;if(!Q)throw Error("Organization context required");let X=await Z.storage.connections.findById($.connectionId,Q);if(!X)throw Error("Connection not found");if(J9(X))throw Error("Repo-scoped connections cannot list installations \u2014 use an org-level mcp-github connection");let Y=new C5(Z.db,Z.vault),J=await Y.get($.connectionId);if(!J)throw Error("No GitHub token found. Ensure the mcp-github connection is authenticated.");let G=J.accessToken;if(mL(J)&&Y.isExpired(J,Ws)){let U=await $S0(J,Y);if(!U)throw Error(VZ);G=U,J=await Y.get($.connectionId)??J}let K=[],W=1,H=100,F=async(U)=>fetch(`${dg6}/user/installations?per_page=${H}&page=${W}`,{headers:{Authorization:`Bearer ${U}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"},signal:AbortSignal.timeout(ig6)});while(!0){let U=await F(G);if(U.status===401){let B=await Y.get($.connectionId);if(!B||!mL(B))throw Error(VZ);let O=await $S0(B,Y);if(!O)throw Error(VZ);if(G=O,U=await F(G),U.status===401)throw Error(VZ)}if(uL(U.headers,{lane:"rest",operation:"list_user_installations",installation:i51}),gL(U)){await U.body?.cancel().catch(()=>{});let B=U.headers.get("retry-after")!==null?"secondary":"primary";cL({lane:"rest",operation:"list_user_installations",installation:i51,kind:B});let O=hL(U.headers);throw Error(`GitHub ${B} rate limit reached${O===null?"":`; retry in ${Math.ceil(O/1000)}s`}`)}if(!U.ok)throw await U.body?.cancel().catch(()=>{}),Error(`GitHub /user/installations failed: ${U.status}`);let N=pg6(await U.text());for(let B of N.installations)K.push({installationId:B.id,login:B.account.login,avatarUrl:B.account.avatar_url,type:B.account.type});if(N.installations.length<H)break;W++}return{installations:K}}})});var l78=D(()=>{c78()});import{z as TO1}from"zod";function ZS0($){return{repositoryId:$.repositoryId,ref:$.repoUrl?eK($.repoUrl):null,connectionId:$.connectionId}}var vB,m78="No credential for this repository \u2014 link it in Settings \u2192 Repositories";var RO1=D(()=>{t5();vB={repositoryId:TO1.string().optional().describe("Connected repository (REPOSITORY_LINK) to act on"),repoUrl:TO1.string().optional().describe("Any URL of the repository \u2014 its provider and host are read from it"),connectionId:TO1.string().optional().describe("Legacy: a repo-scoped mcp-github connection in this org")}});import{z as cW}from"zod";var IO1;var d78=D(()=>{M0();H7();RO1();IO1=h({name:"REPOSITORY_SEARCH_BRANCHES",description:"Search a repository's branches by a case-insensitive substring of the branch name, filtered server-side by the provider.",annotations:{title:"Search Repository Branches",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},_meta:{ui:{visibility:"app"}},inputSchema:cW.object({...vB,query:cW.string().describe("Substring to match against branch names. Empty returns the first branches alphabetically."),limit:cW.number().int().min(1).max(100).default(30),cursor:cW.string().nullish().describe("Opaque cursor from a previous call's `nextCursor`, to read the next window")}),outputSchema:cW.object({branches:cW.array(cW.object({name:cW.string(),author:cW.string().nullable()})),totalCount:cW.number(),nextCursor:cW.string().nullable()}),handler:async($,Z)=>{await Z.access.check();let Q=Z.organization?.id;if(!Q)throw Error("Organization context required");return(await w91(Z,Q,ZS0($))).searchBranches({query:$.query,limit:$.limit,cursor:$.cursor})}})});import{z as m$}from"zod";function p78($){let{credentialConnectionId:Z,...Q}=$;return{...Q,servable:Js($)}}function qO1($){let{legacyConnectionId:Z,...Q}=$;return Q}async function n78($,Z,Q){let X=await $.storage.gitProviderAccounts.get(Q,Z);if(!X)throw Error("Git account not found");return X}var tg6,i78,t78,o78,r78,a78,s78,e78,$Q8,ZQ8;var QQ8=D(()=>{Fs();t5();M0();H7();d78();tg6=m$.object({ref:oE$,externalId:m$.string(),defaultBranch:m$.string().nullable(),webUrl:m$.string(),visibility:m$.enum(["public","private","internal"]),description:m$.string().nullable(),updatedAt:m$.string().nullable()}),i78=rE$.extend({servable:m$.boolean()});t78=h({name:"GIT_PROVIDER_CAPABILITIES",description:"Which git providers this deployment can connect through Studio-owned credentials, and the URLs that start each connect flow.",annotations:{title:"Git provider capabilities",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},_meta:{ui:{visibility:"app"}},inputSchema:m$.object({}),outputSchema:m$.object({github:m$.object({configured:m$.boolean(),connectPath:m$.string().nullable(),installPath:m$.string().nullable()}),gitlab:m$.object({oauthHosts:m$.array(m$.string()),connectPath:m$.string().nullable()})}),handler:async($,Z)=>{r(Z);let Q=t(Z),X=`/api/${Q.slug??Q.id}/git-providers`,Y=az$(),J=Y.github.configured;return{github:{configured:J,connectPath:J?`${X}/github/connect`:null,installPath:J?`${X}/github/install`:null},gitlab:{oauthHosts:Y.gitlab.hosts,connectPath:Y.gitlab.configured?`${X}/gitlab/connect`:null}}}}),o78=h({name:"GIT_ACCOUNT_LIST",description:"List the git provider accounts connected to this organization.",annotations:{title:"List git accounts",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},_meta:{ui:{visibility:"app"}},inputSchema:m$.object({}),outputSchema:m$.object({accounts:m$.array(i78)}),handler:async($,Z)=>{r(Z),await Z.access.check();let Q=t(Z);return{accounts:(await Z.storage.gitProviderAccounts.listByOrg(Q.id)).map(p78)}}}),r78=h({name:"GIT_ACCOUNT_CONNECT_TOKEN",description:"Connect a git provider account with a personal, project or group access token. Validates the token against the provider before storing it encrypted. Use this for self-managed GitLab instances (no OAuth application) or when OAuth is not wanted.",annotations:{title:"Connect git account with a token",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},_meta:{ui:{visibility:"app"}},inputSchema:m$.object({type:ra.describe("Provider; only gitlab accepts tokens today"),host:m$.string().min(1).describe("Provider host, e.g. gitlab.com or gitlab.acme.com"),token:m$.string().min(1).describe("Access token with api scope")}),outputSchema:m$.object({account:i78}),handler:async($,Z)=>{r(Z),await Z.access.check();let Q=t(Z),X=$.host.trim().toLowerCase();if(!/^[a-z0-9.-]+(:[0-9]+)?$/.test(X))throw Error("host must be a bare hostname, optionally with a port");let Y=await nz$($.type,X,$.token),J=await Z.storage.gitProviderAccounts.upsert({organizationId:Q.id,type:$.type,host:X,authKind:"token",externalAccountId:Y.externalAccountId,login:Y.login,avatarUrl:Y.avatarUrl,createdBy:o0(Z)??null});return await Z.storage.gitProviderAccountCredentials.upsert({connectionId:J.id,accessToken:$.token,refreshToken:null,scope:null,expiresAt:null,clientId:null,clientSecret:null,tokenEndpoint:null}),{account:p78(J)}}}),a78=h({name:"GIT_ACCOUNT_DELETE",description:"Disconnect a git provider account. Its repositories stay linked but lose credentials (they become anonymous clones) until linked to another account.",annotations:{title:"Disconnect git account",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},_meta:{ui:{visibility:"app"}},inputSchema:m$.object({id:m$.string()}),outputSchema:m$.object({deleted:m$.boolean()}),handler:async($,Z)=>{r(Z),await Z.access.check();let Q=t(Z);return{deleted:await Z.storage.gitProviderAccounts.delete($.id,Q.id)}}}),s78=h({name:"REPOSITORY_LIST",description:"List the repositories linked to this organization.",annotations:{title:"List repositories",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},_meta:{ui:{visibility:"app"}},inputSchema:m$.object({accountId:m$.string().optional().describe("Only repositories of this account")}),outputSchema:m$.object({repositories:m$.array(h51.extend({usable:m$.boolean()}))}),handler:async($,Z)=>{r(Z),await Z.access.check();let Q=t(Z),X=await Z.storage.repositories.listByOrg(Q.id,{accountId:$.accountId}),Y=await pL(Z,Q.id),J=new Set(Y.map((G)=>G.webUrl.toLowerCase()));return{repositories:X.map((G)=>({...qO1(G),usable:J.has(G.webUrl.toLowerCase())}))}}}),e78=h({name:"REPOSITORY_SEARCH",description:"Search the repositories an account can reach on its provider (not yet linked). Feeds the repository picker.",annotations:{title:"Search provider repositories",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},_meta:{ui:{visibility:"app"}},inputSchema:m$.object({accountId:m$.string(),query:m$.string().optional(),page:m$.number().int().min(1).optional(),perPage:m$.number().int().min(1).max(100).optional()}),outputSchema:m$.object({repositories:m$.array(tg6),hasMore:m$.boolean()}),handler:async($,Z)=>{r(Z),await Z.access.check();let Q=t(Z),X=await n78(Z,Q.id,$.accountId);return CP({db:Z.db,vault:Z.vault},X).listRepos({query:$.query,page:$.page,perPage:$.perPage})}}),$Q8=h({name:"REPOSITORY_LINK",description:"Link a repository to the organization. With an account, the repository is verified against the provider and its facts (id, default branch, visibility) recorded; without one it is linked as an anonymous public clone.",annotations:{title:"Link repository",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},_meta:{ui:{visibility:"app"}},inputSchema:m$.object({url:m$.string().min(1).describe("Repository URL (https or ssh), or a bare path like owner/name when accountId is given"),accountId:m$.string().optional().describe("Account whose credentials access the repository")}),outputSchema:m$.object({repository:h51}),handler:async($,Z)=>{r(Z),await Z.access.check();let Q=t(Z),X=o0(Z)??null;if(!$.accountId){let H=eK($.url);if(!H)throw Error("Could not recognise the repository URL. Use a full https URL from GitHub or GitLab.");let F=await Z.storage.repositories.upsert({organizationId:Q.id,ref:H,createdBy:X});return{repository:qO1(F)}}let Y=await n78(Z,Q.id,$.accountId),J=eK($.url,{provider:Y.type,host:Y.host});if(!J)throw Error("Could not recognise the repository URL or path");if(J.host!==Y.host)throw Error(`Repository is on ${J.host} but the account is on ${Y.host}`);let K=await CP({db:Z.db,vault:Z.vault},Y).getRepo(J);if(!K)throw Error(`${J.path} was not found on ${J.host} or the account cannot access it`);let W=await Z.storage.repositories.upsert({organizationId:Q.id,ref:K.ref,accountId:Y.id,externalId:K.externalId,defaultBranch:K.defaultBranch,visibility:K.visibility,createdBy:X});return{repository:qO1(W)}}}),ZQ8=h({name:"REPOSITORY_DELETE",description:"Unlink a repository from the organization. Agents, tasks and syncs that referenced it keep working off their legacy metadata until relinked.",annotations:{title:"Unlink repository",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},_meta:{ui:{visibility:"app"}},inputSchema:m$.object({id:m$.string()}),outputSchema:m$.object({deleted:m$.boolean()}),handler:async($,Z)=>{r(Z),await Z.access.check();let Q=t(Z);return{deleted:await Z.storage.repositories.delete($.id,Q.id)}}})});import{z as J$}from"zod";async function Td($,Z){let Q=$.organization?.id;if(!Q)throw Error("Organization context required");let X=await Hs($,Q,ZS0(Z));if(!X)throw Error(m78);return X}var rg6,ag6,QS0,sg6,XQ8,YQ8,JQ8,GQ8,KQ8,WQ8;var HQ8=D(()=>{M0();H7();RO1();rg6=J$.object({id:J$.string().nullable(),name:J$.string(),state:J$.enum(["queued","running","completed"]),conclusion:J$.enum(["success","failure","neutral","cancelled","skipped","timed_out","action_required"]).nullable(),url:J$.string().nullable(),durationMs:J$.number().nullable(),summary:J$.string().nullable()}),ag6=J$.object({id:J$.string(),author:J$.string(),body:J$.string(),createdAt:J$.string(),updatedAt:J$.string(),url:J$.string()}),QS0=J$.object({number:J$.number(),url:J$.string(),title:J$.string(),body:J$.string(),state:J$.enum(["open","closed","merged"]),draft:J$.boolean(),mergedAt:J$.string().nullable(),base:J$.string(),head:J$.string(),headSha:J$.string(),headRepoPath:J$.string().nullable(),author:J$.string(),conflicting:J$.boolean().nullable(),checks:J$.enum(["pending","passing","failing"]).nullable(),changedFiles:J$.number().nullable()}),sg6=QS0.extend({checkRuns:J$.array(rg6),comments:J$.array(ag6),unresolvedConversations:J$.number(),reviewBlocked:J$.boolean()}),XQ8=h({name:"CHANGE_REQUEST_STATE",description:"Read a branch's change request with its CI runs, review state and comments.",annotations:{title:"Read Change Request State",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},_meta:{ui:{visibility:"app"}},inputSchema:J$.object({...vB,branch:J$.string().describe("Head branch of the change request to read")}),outputSchema:J$.object({changeRequest:sg6.nullable()}),handler:async($,Z)=>{return await Z.access.check(),{changeRequest:await(await Td(Z,$)).readDetailed({branch:$.branch})}}}),YQ8=h({name:"CHANGE_REQUEST_LAST_MERGED",description:"Read the most recently merged change request into a base branch \u2014 in Fast Preview, the last publish.",annotations:{title:"Read Last Merged Change Request",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},_meta:{ui:{visibility:"app"}},inputSchema:J$.object({...vB,base:J$.string().describe("Branch it was merged into")}),outputSchema:J$.object({changeRequest:QS0.nullable()}),handler:async($,Z)=>{return await Z.access.check(),{changeRequest:await(await Td(Z,$)).lastMergedInto($.base)}}}),JQ8=h({name:"CHANGE_REQUEST_LIST_OPEN",description:"List a repository's open change requests, most recently updated first.",annotations:{title:"List Open Change Requests",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},_meta:{ui:{visibility:"app"}},inputSchema:J$.object({...vB,limit:J$.number().int().min(1).max(100).default(50)}),outputSchema:J$.object({changeRequests:J$.array(QS0)}),handler:async($,Z)=>{return await Z.access.check(),{changeRequests:await(await Td(Z,$)).listOpen($.limit)}}}),GQ8=h({name:"CHANGE_REQUEST_CHECK_LOG",description:"Read one CI run's report \u2014 a GitHub check run's output markdown, or the tail of a GitLab job's trace.",annotations:{title:"Read CI Run Report",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},_meta:{ui:{visibility:"app"}},inputSchema:J$.object({...vB,checkId:J$.string().describe("Provider id of the run, from its listing")}),outputSchema:J$.object({report:J$.string().nullable()}),handler:async($,Z)=>{return await Z.access.check(),{report:await(await Td(Z,$)).readCheckLog($.checkId)}}}),KQ8=h({name:"CHANGE_REQUEST_OPEN",description:"Propose a branch onto another. Returns the branch's existing change request instead of failing when it already has one.",annotations:{title:"Open Change Request",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},_meta:{ui:{visibility:"app"}},inputSchema:J$.object({...vB,head:J$.string().describe("Branch being proposed"),base:J$.string().describe("Branch it should land on"),title:J$.string(),body:J$.string().optional()}),outputSchema:J$.object({changeRequest:QS0,existed:J$.boolean()}),handler:async($,Z)=>{await Z.access.check();let Q=await Td(Z,$),X=await Q.readForBranch($.head);if(X&&X.state==="open"){if($.body&&$.body!==X.body)await Q.describe(X.number,$.body);return{changeRequest:$.body?{...X,body:$.body}:X,existed:!0}}return{changeRequest:await Q.open({head:$.head,base:$.base,title:$.title,body:$.body}),existed:!1}}}),WQ8=h({name:"CHANGE_REQUEST_MERGE",description:"Land a change request. Reports why it could not merge rather than throwing.",annotations:{title:"Merge Change Request",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0},_meta:{ui:{visibility:"app"}},inputSchema:J$.object({...vB,number:J$.number().int().positive(),strategy:J$.enum(["any","squash"]).default("any").describe("`squash` when the result must be one commit; `any` uses whatever the repository allows"),commitTitle:J$.string().optional(),commitMessage:J$.string().optional()}),outputSchema:J$.object({merged:J$.boolean(),reason:J$.enum(["conflict","blocked","rate_limited","not_found","error"]).optional(),detail:J$.string().optional()}),handler:async($,Z)=>{await Z.access.check();let X=await(await Td(Z,$)).merge($.number,{strategy:$.strategy,commitTitle:$.commitTitle,commitMessage:$.commitMessage});return X.merged?{merged:!0}:{merged:!1,reason:X.reason,detail:X.detail}}})});import{z as h6}from"zod";function XS0($){if(!$)return"";return typeof $==="string"?$:$.toISOString()}function FQ8($){let Z=$.trim();return Z.length>0?Z:void 0}function UQ8($,Z){return $===void 0||$.includes(Z)}var $h6,Zh6,Qh6,Xh6,Yh6,Jh6,MO1;var NQ8=D(()=>{M0();kY1();$h6=["thread","task"],Zh6=h6.object({type:h6.literal("thread"),id:h6.string(),title:h6.string(),created_at:h6.string(),updated_at:h6.string(),virtual_mcp_id:h6.string().nullable(),run_config:h6.record(h6.string(),h6.unknown()).nullable(),status:h6.string().nullable()}),Qh6=h6.object({type:h6.literal("task"),id:h6.string(),title:h6.string(),created_at:h6.string(),updated_at:h6.string(),key:h6.string().nullable(),status:h6.string().nullable(),repo:h6.string().nullable()}),Xh6=h6.discriminatedUnion("type",[Zh6,Qh6]),Yh6=h6.object({query:h6.string().max(256).describe("Free-text search query. Empty string returns the most recently updated resources."),limit:h6.number().int().min(1).max(50).optional().describe("Maximum results per resource type (default: 20)."),types:h6.array(h6.enum($h6)).optional().describe("Restrict the search to specific resource types. Omit to search across all available types.")}),Jh6=h6.object({items:h6.array(Xh6),totalCount:h6.number()});MO1=h({name:"GLOBAL_SEARCH",description:"Search across organization resources by free-text query. Returns a typed union of matches (currently: threads and task-board cards). New resource types may be added over time without changes to the call shape.",annotations:{title:"Global Search",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:Yh6,outputSchema:Jh6,handler:async($,Z)=>{await Z.access.check();let Q=t(Z),X=$.limit??20,Y=UQ8($.types,"thread"),J=UQ8($.types,"task"),G=[],K=0;if(Y){let{threads:W,total:H}=await Z.storage.threads.list(void 0,{limit:X,offset:0,search:FQ8($.query),includeArchived:!1});K+=H;for(let F of W)G.push({type:"thread",id:F.id,title:F.title??"",created_at:XS0(F.created_at),updated_at:XS0(F.updated_at),virtual_mcp_id:F.virtual_mcp_id??null,run_config:F.run_config??null,status:P3(F).status})}if(J){let W=await Z.storage.taskBoard.searchByTitle(Q.id,FQ8($.query)??"",X);K+=W.length;for(let H of W)G.push({type:"task",id:H.id,title:H.title??"",created_at:XS0(H.createdAt),updated_at:XS0(H.updatedAt),key:Q.slug?NR0(Q.slug,H.keySeq):null,status:H.status??null,repo:H.repo??null})}return{items:G,totalCount:K}}})});var BQ8=D(()=>{NQ8()});var JW0={};e(JW0,{toolSubsetMCP:()=>VO1,managementMCP:()=>rl,managementContextStore:()=>OB,listManagementTools:()=>Kh6,TOOL_BY_NAME:()=>Rd,CORE_TOOLS:()=>DQ8});import{z as OQ8}from"zod";async function Kh6($){let Z=await rl($),[Q,X]=Ha.createLinkedPair();await Z.connect(X);let Y=new $Z({name:"tools-hydration",version:"1.0.0"},{jsonSchemaValidator:S5});try{return await Y.connect(Q),(await Y.listTools()).tools}finally{await Y.close().catch(()=>{}),await Z.close().catch(()=>{})}}var DQ8,Rd,VO1=($,Z)=>{let Q=new SH({name:$,version:"1.0.0"},{capabilities:{tools:{}},jsonSchemaValidator:S5});for(let X of Z){let Y=Rd.get(X);if(!Y){console.warn(`[${$}] unknown tool "${X}" \u2014 not registered`);continue}let{config:J,handler:G}=d$0(Y);Q.registerTool(Y.name,J,G)}return Q},rl=async($)=>{let Z=new SH({name:"mcp-cms-management",version:"1.0.0"},{capabilities:{tools:{},prompts:{},resources:{}},jsonSchemaValidator:S5});for(let Y of Rd.values()){let{config:J,handler:G}=d$0(Y);Z.registerTool(Y.name,J,G)}let Q=bk0();for(let Y of Q){let J=Y.arguments?.length?Object.fromEntries(Y.arguments.map((G)=>{let K=G.required?OQ8.string():OQ8.string().optional();return[G.name,G.description?K.describe(G.description):K]})):void 0;Z.registerPrompt(Y.name,{title:Y.title,description:Y.description,...J?{argsSchema:J}:{}},(G)=>{return{messages:[{role:"user",content:{type:"text",text:typeof Y.text==="function"?Y.text(G??{}):Y.text}}]}})}if($.organization?.id){let Y=await $.storage.brandContext.list($.organization.id),J=new Set;for(let G of Y){let K=G.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),W=K?`brand-${K}`:`brand-${G.id}`;if(J.has(W))W=`${W}-${G.id.slice(0,8)}`;J.add(W);let H=[`# Brand: ${G.name}`,"",`**Domain:** ${G.domain}`,"","## Overview",G.overview];if(G.colors){let U=Object.entries(G.colors).filter(([,N])=>N);if(U.length>0){H.push("","## Colors");for(let[N,B]of U)H.push(`- **${N}:** ${B}`)}}if(G.fonts){let U=Object.entries(G.fonts).filter(([,N])=>N);if(U.length>0){H.push("","## Fonts");for(let[N,B]of U)H.push(`- ${B} (${N})`)}}if(G.logo)H.push("",`**Logo:** ${G.logo}`);if(G.favicon)H.push(`**Favicon:** ${G.favicon}`);if(G.ogImage)H.push(`**OG Image:** ${G.ogImage}`);if(G.images&&G.images.length>0){H.push("","## Images");for(let U of G.images){let N=Object.entries(U).map(([B,O])=>`${B}: ${O}`).join(", ");H.push(`- ${N}`)}}let F=H.join(`
4569
4569
  `);Z.prompt(W,`Brand context for ${G.name}`,()=>({messages:[{role:"user",content:{type:"text",text:F}}]}))}}let X=S58();for(let Y of X)Z.resource(Y.name,Y.uri,{description:Y.description,mimeType:Y.mimeType??"text/markdown"},async(J)=>{return{contents:[{uri:typeof J==="string"?J:J.href,mimeType:Y.mimeType??"text/markdown",text:Y.text}]}});return Z};var RL=D(()=>{kH();Ho();TQ();yL$();oL$();qj$();Sj$();pj$();sj$();nE$();Hm$();wm$();Tm$();Vm$();Dd$();Ed$();Tn$();Mn$();Sn$();_68();u68();l68();t68();J58();eB1();yk0();yk0();Q98();g78();u78();l78();QQ8();HQ8();BQ8();DQ8=[e61,$51,Z51,Q51,X51,Y51,J51,Fm$,Nm$,Om$,Dm$,Zf,sx,ex,$f,oG1,rG1,aG1,eG1,$31,Z31,ax,Q31,J31,G31,K31,W31,uY1,N31,B31,O31,D31,H31,F31,e71,G51,K51,W51,H51,F51,N51,B51,O51,w51,j51,E51,z51,P51,A51,T51,R51,I51,q51,M51,V51,C51,v51,g51,gB1,iB1,pB1,G61,OP,DP,R61,I61,q61,s41,r41,t41,o41,wP,jP,EP,zP,PP,kj$,n61,t61,o61,r61,a61,m41,i41,p41,d41,JK1,GK1,KK1,A31,xx,fx,R31,I31,bx,w31,j31,E31,z31,P31,q31,M31,V31,s31,e31,$K1,ZK1,QK1,XK1,YK1,AP,TP,RP,p61,GH1,KH1,WH1,HH1,FH1,UH1,NH1,BH1,OH1,DH1,LH1,EH1,zH1,Rn$,In$,qn$,TH1,RH1,CB1,vB1,xB1,fB1,bB1,yB1,c68,m68,d68,i68,p68,n68,$58,Z58,Q58,X58,Y58,rB1,aB1,sB1,ux,cx,lx,mx,$O1,ZO1,QO1,XO1,YO1,JO1,...y78,fX1,PO1,AO1,t78,o78,r78,a78,s78,e78,$Q8,ZQ8,IO1,XQ8,YQ8,JQ8,GQ8,KQ8,WQ8,MO1],Rd=new Map(DQ8.map(($)=>[$.name,$]))});import{z as LQ8}from"zod";function Wh6($){return[{permissions:{self:["*"]},getTools:async()=>{let{CORE_TOOLS:Z}=await Promise.resolve().then(() => (RL(),JW0));return Z.map((Q)=>{return{name:Q.name,inputSchema:LQ8.toJSONSchema(Q.inputSchema,{unrepresentable:"any"}),outputSchema:Q.outputSchema?LQ8.toJSONSchema(Q.outputSchema,{unrepresentable:"any"}):void 0,description:Q.description}})},data:bJ$(l5(),$)},{data:fJ$()},{data:xJ$($)}]}async function wQ8($,Z){try{let Q=u$(),X=k0();await Q.db.insertInto("organization_billing").values({organization_id:$}).onConflict((K)=>K.column("organization_id").doNothing()).execute();let Y=new EX(X.encryptionKey),J=new wo(Q.db,Y),G=Wh6($);await Promise.all(G.map(async(K)=>{let W=null;if(K.permissions)W=(await G8.api.createApiKey({body:{name:`${K.data.app_name??crypto.randomUUID()}-mcp`,userId:Z,permissions:K.permissions,rateLimitEnabled:!1,metadata:{organization:{id:$},purpose:"default-org-connections"}}}))?.key;let H=await Jc({id:"pending",title:K.data.title,connection_type:K.data.connection_type,connection_url:K.data.connection_url,connection_token:K.data.connection_token??W,connection_headers:K.data.connection_headers}).catch(()=>null),F=await K.getTools?.()??H?.tools??null,U=H?.scopes?.length?H.scopes:null,N=K.data.id?K.data.id.startsWith(`${$}_`)?K.data.id:`${$}_${K.data.id}`:void 0;await J.create({...K.data,id:N,tools:F,configuration_scopes:U,organization_id:$,created_by:Z,connection_token:K.data.connection_token??W})}));try{await l41({orgId:$,createdBy:Z})}catch(K){console.error("Failed to enqueue studio pack install:",K)}if(X.aiGatewayEnabled&&X.studioProvisionSecretKey&&BL.provisionKey)try{let K=await jH(Z),W=await BL.provisionKey(K,$);await new Ka(Q.db,Y).upsert({providerId:"deco",label:"Auto-provisioned",apiKey:W,organizationId:$,createdBy:Z})}catch(K){console.error("Failed to auto-provision Deco AI Gateway key:",K)}}catch(Q){console.error("Error creating default MCP connections:",Q)}}var jQ8=D(()=>{x8();qK0();V5();wQ();GD();q41();e01();VK0();A$();uJ();_K0();JD()});async function EQ8($,Z){let Q=OX();if(!Q)return Z;let X=await u$().db.selectFrom("organization").select("slug").where("id","=",$).executeTakeFirst();if(!X?.slug)return Z;return await An({objectStorage:AJ(Q,$),baseUrl:l5(),orgSlug:X.slug,prefix:"org-logos"})(Z)??Z}var zQ8=D(()=>{wQ();lO();_Q0();V5()});function Hh6($,Z){let Q=$.email.split("@")[1]?.toLowerCase()??null;return{distinctId:$.id,properties:{$set:{email:$.email,name:$.name,email_verified:$.emailVerified},$set_once:{first_seen_at:Z.toISOString(),signup_email_domain:Q}}}}function kO1($){_1.identify(Hh6($,new Date))}var PQ8=D(()=>{l4()});import{adminAc as AQ8,memberAc as Fh6}from"@decocms/better-auth/plugins/organization/access";function CO1($){let Z=["*",...$];return{user:{self:[...hY0],...Fh6.statements},admin:{self:Z,...AQ8.statements},owner:{self:Z,...AQ8.statements}}}function Uh6($,Z){for(let[Q,X]of Object.entries(Z)){let Y=$[Q];if(!Y)return!1;for(let J of X)if(!Y.includes(J)&&!Y.includes("*"))return!1}return!0}function TQ8($,Z,Q){if(!$)return"fallback";if($.includes(","))return"fallback";if(!Wh.includes($))return"fallback";let X=Q[$];if(!X)return"fallback";return Uh6(X,Z)?"grant":"deny"}function RQ8(){if(!SO1){let $=Object.values(Qz()).flatMap((Z)=>Z.map((Q)=>Q.name));SO1=CO1($)}return SO1}var SO1;var _O1=D(()=>{Kh();zX()});import{decodeJwt as Nh6}from"jose";import{sql as e$0}from"kysely";async function Dh6($){let{user:Z,token:Q}=$;if(!Q?.idToken)return;let X;try{X=Nh6(Q.idToken)}catch{return}let{preferred_username:Y,upn:J}=X,G=[Y,J].filter((H)=>typeof H==="string"&&H.length>0&&H.toLowerCase()!==Z.email.toLowerCase()).map((H)=>H.toLowerCase());if(G.length===0)return;let{db:K}=u$(),W=await K.selectFrom("user").selectAll().where("email","in",G).where("id","!=",Z.id).executeTakeFirst();if(!W)return;try{await K.transaction().execute(async(H)=>{await e$0`UPDATE "account" SET "userId" = ${W.id} WHERE "userId" = ${Z.id}`.execute(H),await e$0`UPDATE "session" SET "userId" = ${W.id} WHERE "userId" = ${Z.id}`.execute(H),await e$0`
4570
4570
  UPDATE "member" SET "userId" = ${W.id}
4571
4571
  WHERE "userId" = ${Z.id}