decocms 4.242.8 → 4.242.10

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 (238) hide show
  1. package/dist/client/assets/{AlertCircle-BoTQlFfh.js → AlertCircle-DPj0TT5W.js} +1 -1
  2. package/dist/client/assets/{AreaChart-T2OyonCK.js → AreaChart-DsfQVE3P.js} +1 -1
  3. package/dist/client/assets/{ArrowLeft-CLe5Qvl7.js → ArrowLeft--mXelsby.js} +1 -1
  4. package/dist/client/assets/{ArrowUp-DHH91psC.js → ArrowUp-W3X0jAF0.js} +1 -1
  5. package/dist/client/assets/{ArrowUpRight-BPplqZgs.js → ArrowUpRight-DOAvXudj.js} +1 -1
  6. package/dist/client/assets/{Check-CDFz4AjT.js → Check-BAWZfjr5.js} +1 -1
  7. package/dist/client/assets/{CheckCircle-nI2pZ3Kf.js → CheckCircle-eUP1HtEW.js} +1 -1
  8. package/dist/client/assets/{ChevronDown-nAecbmVW.js → ChevronDown-BISzat6M.js} +1 -1
  9. package/dist/client/assets/{ChevronRight-qkZFnoAz.js → ChevronRight-DnzpCIMU.js} +1 -1
  10. package/dist/client/assets/{ChevronSelectorVertical-BfGyxCCr.js → ChevronSelectorVertical-CCYOv6Za.js} +1 -1
  11. package/dist/client/assets/{ChevronUp-CrdQT8QJ.js → ChevronUp-DEmpBxyN.js} +1 -1
  12. package/dist/client/assets/{Copy01-Ca9EpaeI.js → Copy01-C-PIl4iG.js} +1 -1
  13. package/dist/client/assets/{CreditCard01-B9aN1Ui2.js → CreditCard01-CyDwjCn7.js} +1 -1
  14. package/dist/client/assets/{DotsVertical-BAknAFtO.js → DotsVertical-Eg6GaY5s.js} +1 -1
  15. package/dist/client/assets/{Download01-Bm3fUxw2.js → Download01-BRq337Wk.js} +1 -1
  16. package/dist/client/assets/{Eye-CZ1lkQZi.js → Eye-BMH6Y9P8.js} +1 -1
  17. package/dist/client/assets/{FilterLines-15AxvKle.js → FilterLines-mjIFanlg.js} +1 -1
  18. package/dist/client/assets/{Globe01-D7eaLSZi.js → Globe01-CCHhrECw.js} +1 -1
  19. package/dist/client/assets/{Globe04-FqhO4Hgt.js → Globe04-DgxgXdVa.js} +1 -1
  20. package/dist/client/assets/{HardDrive-DD_Yzh-d.js → HardDrive-B_L1Kp36.js} +1 -1
  21. package/dist/client/assets/{Key01-CZx41HY4.js → Key01-BhPdhwGh.js} +1 -1
  22. package/dist/client/assets/{LayoutLeft-BpXv7oEx.js → LayoutLeft-DdSr18Wt.js} +1 -1
  23. package/dist/client/assets/{LinkExternal01-C8ScgZrs.js → LinkExternal01-DJzJfXFI.js} +1 -1
  24. package/dist/client/assets/{LockUnlocked01-DKKD_Ok5.js → LockUnlocked01-BhcVkmae.js} +1 -1
  25. package/dist/client/assets/{LogOut01-THLMLsl3.js → LogOut01-COY7cWij.js} +1 -1
  26. package/dist/client/assets/{Monitor01-BBWSaMsJ.js → Monitor01-B6hueFPX.js} +1 -1
  27. package/dist/client/assets/{Palette-BdNH3l-N.js → Palette-C2YsoqB9.js} +1 -1
  28. package/dist/client/assets/{Play-BkCtwszA.js → Play-DxU4X3z0.js} +1 -1
  29. package/dist/client/assets/{Plus-BU2lhptn.js → Plus-B0wAX0d2.js} +1 -1
  30. package/dist/client/assets/{SearchLg-DY-7dxSc.js → SearchLg-CqVQxhTC.js} +1 -1
  31. package/dist/client/assets/{SearchMd-DDzdMVOp.js → SearchMd-CVxZKDL2.js} +1 -1
  32. package/dist/client/assets/{Settings02-Gbxpyx4Q.js → Settings02-DUEfEBLC.js} +1 -1
  33. package/dist/client/assets/{Share07-B2wLINGb.js → Share07-BQeXkwc5.js} +1 -1
  34. package/dist/client/assets/{Shield01-vXLr1mr5.js → Shield01-EEfait41.js} +1 -1
  35. package/dist/client/assets/{Stars01-DDcyuzvc.js → Stars01-Bxu-zmv-.js} +1 -1
  36. package/dist/client/assets/{Stars02-atggWcu2.js → Stars02-BoAAvUu_.js} +1 -1
  37. package/dist/client/assets/{Sun-BS55qMsk.js → Sun-DImtkqHD.js} +1 -1
  38. package/dist/client/assets/{SwitchHorizontal01-BmFQo3OE.js → SwitchHorizontal01-DV7LXpuC.js} +1 -1
  39. package/dist/client/assets/{Tool01-Cj5KnqgJ.js → Tool01-B7i0WMht.js} +1 -1
  40. package/dist/client/assets/{Tool02-Cy5KJ2T2.js → Tool02-COXthdcT.js} +1 -1
  41. package/dist/client/assets/{Trash01-hDvKHPoK.js → Trash01-Bh8I-rom.js} +1 -1
  42. package/dist/client/assets/{TrendUp01-DJpajRd_.js → TrendUp01-gf6bY9Ll.js} +1 -1
  43. package/dist/client/assets/{Upload01-jgZfErqT.js → Upload01-PsrIiVlI.js} +1 -1
  44. package/dist/client/assets/{User01-BgbUKPiK.js → User01-DLUrqydl.js} +1 -1
  45. package/dist/client/assets/{Users01-CkJKhpVc.js → Users01-DyYZFYjp.js} +1 -1
  46. package/dist/client/assets/{Users03-Dv3_fZad.js → Users03-Cnyxfwux.js} +1 -1
  47. package/dist/client/assets/{X-C6E8GzfL.js → X-DeVnVCsw.js} +1 -1
  48. package/dist/client/assets/{XCircle-DH2jOoBq.js → XCircle-CsXPFJDC.js} +1 -1
  49. package/dist/client/assets/{XClose-D2UGSKyk.js → XClose-Dbp-AMIR.js} +1 -1
  50. package/dist/client/assets/{YAxis-B480boDG.js → YAxis-B5Uzpck2.js} +1 -1
  51. package/dist/client/assets/{Zap-mwiynZmR.js → Zap-C4uk703x.js} +1 -1
  52. package/dist/client/assets/{ZapSquare-DlhxOYuh.js → ZapSquare-CGfipewK.js} +1 -1
  53. package/dist/client/assets/{access-gate-pt14iFbc.js → access-gate-DYKcaB-m.js} +1 -1
  54. package/dist/client/assets/{agent-icon-CdAzwt7J.js → agent-icon-DKDDr6LX.js} +1 -1
  55. package/dist/client/assets/{agents-list-9BtWGPLX.js → agents-list-BgesIp_D.js} +1 -1
  56. package/dist/client/assets/{ai-providers-C5xCfu1Y.js → ai-providers-fzOldjD4.js} +1 -1
  57. package/dist/client/assets/{alert-dialog-C-cZlNMV.js → alert-dialog-D6Xiv1th.js} +1 -1
  58. package/dist/client/assets/{alert-BVIJuHm7.js → alert-lJEBGonb.js} +1 -1
  59. package/dist/client/assets/{api-keys-iGr2jYCA.js → api-keys-B51dfm24.js} +1 -1
  60. package/dist/client/assets/{app-editor-CniWqGdb.js → app-editor-AidVerAP.js} +1 -1
  61. package/dist/client/assets/{auth-catchall-CCtGRN8I.js → auth-catchall-M9c2hOiZ.js} +1 -1
  62. package/dist/client/assets/{auth-entry-B8_ipjg9.js → auth-entry-CjKfa59U.js} +1 -1
  63. package/dist/client/assets/{auth-split-layout-b_jjaEti.js → auth-split-layout-DWIu4cZc.js} +1 -1
  64. package/dist/client/assets/{auth-Br4KUJ_D.js → auth-wXaWfFkt.js} +1 -1
  65. package/dist/client/assets/{authenticate-and-persist-oauth-DhuGhqU0.js → authenticate-and-persist-oauth-Cys_xhUc.js} +1 -1
  66. package/dist/client/assets/{automation-list-row-ChQj_d8M.js → automation-list-row-WDjapWGl.js} +1 -1
  67. package/dist/client/assets/{automation-runs-C8ijWgiW.js → automation-runs-DI0wW3HR.js} +1 -1
  68. package/dist/client/assets/{automations-Cn8bxCYo.js → automations-D5_hh9gc.js} +1 -1
  69. package/dist/client/assets/{avatar-BcYKO37a.js → avatar-BTV4Qfqg.js} +1 -1
  70. package/dist/client/assets/{badge-WQNJCKcw.js → badge-rdgmpGaw.js} +1 -1
  71. package/dist/client/assets/{billing-DoiNzskc.js → billing-Cx-a1tN3.js} +1 -1
  72. package/dist/client/assets/{block-document-CX5b_YrK.js → block-document-kHgzmyXx.js} +1 -1
  73. package/dist/client/assets/{buckets-YNdLWugq.js → buckets-DqW4i9rI.js} +1 -1
  74. package/dist/client/assets/{bulk-category-panel-BdRz9at_.js → bulk-category-panel-Emz3xi9j.js} +1 -1
  75. package/dist/client/assets/{capability-load-error-LbhhkHcE.js → capability-load-error-DohLqsdZ.js} +1 -1
  76. package/dist/client/assets/{card-BJU3ICwF.js → card-DkMLLs3X.js} +1 -1
  77. package/dist/client/assets/{cards-CtYDK4ef.js → cards-B3jJW5lu.js} +1 -1
  78. package/dist/client/assets/{category-editor-BkAMV04h.js → category-editor-Cu9jjvOg.js} +1 -1
  79. package/dist/client/assets/{chart-BeyRG261.js → chart-Cpa4A7Tu.js} +1 -1
  80. package/dist/client/assets/{chat-context-DRswam-n.js → chat-context-BF2RCi05.js} +1 -1
  81. package/dist/client/assets/{checkbox-Bs8phTrR.js → checkbox-CaVApT67.js} +1 -1
  82. package/dist/client/assets/{choose-editor-VlsT214a.js → choose-editor-B-VCsfM3.js} +1 -1
  83. package/dist/client/assets/{cli-auth-success-DBhYeOy-.js → cli-auth-success-DSiJCWEu.js} +1 -1
  84. package/dist/client/assets/{collection-detail-Dcx57D-C.js → collection-detail-Bub4UoR4.js} +1 -1
  85. package/dist/client/assets/{collection-display-button-DJjS0aZn.js → collection-display-button-CNnES-dT.js} +1 -1
  86. package/dist/client/assets/{collection-search-3PtmZ2TT.js → collection-search-DT_JimIl.js} +1 -1
  87. package/dist/client/assets/{collection-table-wrapper-RtnOd8bF.js → collection-table-wrapper-DuleZYgZ.js} +1 -1
  88. package/dist/client/assets/{collection-tabs-FkQlO5iz.js → collection-tabs-BksolnC6.js} +1 -1
  89. package/dist/client/assets/{command-C5iwTZOo.js → command-CGXNHhZH.js} +1 -1
  90. package/dist/client/assets/{commerce-onboarding-6yH6xV87.js → commerce-onboarding-DSIILXD4.js} +1 -1
  91. package/dist/client/assets/{connect-CpkSS2rm.js → connect-DUxffXRl.js} +1 -1
  92. package/dist/client/assets/{connection-CdQeuUbf.js → connection-C8lE0tDj.js} +1 -1
  93. package/dist/client/assets/{connection-card-CHvixVXW.js → connection-card-DcfZkEa8.js} +1 -1
  94. package/dist/client/assets/{connection-detail-A5faCN3P.js → connection-detail-U_qgx_iG.js} +1 -1
  95. package/dist/client/assets/{connection-form-helpers-Df4Ue4Ix.js → connection-form-helpers-NuK_m8Pl.js} +1 -1
  96. package/dist/client/assets/{connections-ConL6zk4.js → connections-C4QSRNtA.js} +1 -1
  97. package/dist/client/assets/{decopilot-sse-pool-Bt-N4qla.js → decopilot-sse-pool-ClNmIN2K.js} +1 -1
  98. package/dist/client/assets/{dialog-D5yd4-0t.js → dialog-B9QT_4we.js} +1 -1
  99. package/dist/client/assets/{domain-settings-BwdgISpN.js → domain-settings-BbpAktH4.js} +1 -1
  100. package/dist/client/assets/{drawer-HIHWp3gG.js → drawer-B9CdaPxO.js} +1 -1
  101. package/dist/client/assets/{dropdown-menu-DYoLFcve.js → dropdown-menu-CDGy5N9-.js} +1 -1
  102. package/dist/client/assets/{empty-state-BHJXrO2t.js → empty-state-sbb1v6cn.js} +1 -1
  103. package/dist/client/assets/{extract-connection-data-jzPmfmjm.js → extract-connection-data-C96UDA-l.js} +1 -1
  104. package/dist/client/assets/{file-explorer-C1lAmDdt.js → file-explorer-PxWQvAnd.js} +1 -1
  105. package/dist/client/assets/{file-type-icon-Q8n4QLXy.js → file-type-icon-CwWxajMP.js} +1 -1
  106. package/dist/client/assets/{form-789bkDdv.js → form-ChEZ0zqM.js} +1 -1
  107. package/dist/client/assets/{general-5uxBADza.js → general-B1UscCa5.js} +1 -1
  108. package/dist/client/assets/{github-repo-picker-C9rLdFTg.js → github-repo-picker-BDWadEgD.js} +1 -1
  109. package/dist/client/assets/{hooks-n8Ss1WVk.js → hooks-Dgzoz6KV.js} +1 -1
  110. package/dist/client/assets/{index-C71Kq6yz.js → index-7ZNKcEjn.js} +5 -5
  111. package/dist/client/assets/{index-DBqB5deL.js → index-BPo9WF4Q.js} +1 -1
  112. package/dist/client/assets/{index-BRMmCy_p.js → index-CK52UFJP.js} +1 -1
  113. package/dist/client/assets/{index-D8jNAo2W.js → index-Ce5n4s3x.js} +1 -1
  114. package/dist/client/assets/index-D2n5z3jR.js +1 -0
  115. package/dist/client/assets/{index-GwvevJ5e.js → index-Dlwi6abY.js} +1 -1
  116. package/dist/client/assets/{index-DOX5DH3-.js → index-Do0Dh-VN.js} +1 -1
  117. package/dist/client/assets/{index-BBYMMwr3.js → index-TVxJmanj.js} +3 -3
  118. package/dist/client/assets/{index-DOm-v_tR.js → index-XSxLrzIP.js} +1 -1
  119. package/dist/client/assets/{index-redirect-D9Z66Mz5.js → index-redirect-DtMKg6ZI.js} +1 -1
  120. package/dist/client/assets/{index-h0oQmXLZ.js → index-zh3mGEbF.js} +1 -1
  121. package/dist/client/assets/{infra-billing-Bwz2gt_p.js → infra-billing-C5DK3FnQ.js} +1 -1
  122. package/dist/client/assets/{input-CqVjACZq.js → input-BtNRi-g2.js} +1 -1
  123. package/dist/client/assets/{integration-icon-D96vAHD-.js → integration-icon-CXijUwhk.js} +1 -1
  124. package/dist/client/assets/{invite-member-dialog-Ctdea6OY.js → invite-member-dialog-CoFJLobO.js} +1 -1
  125. package/dist/client/assets/{label-B8C6pCoD.js → label-B0Ccc7LL.js} +1 -1
  126. package/dist/client/assets/{layout-CU-GGyLd.js → layout-C6JjAVjC.js} +1 -1
  127. package/dist/client/assets/{login-mb2jdVFW.js → login-Bz-HPqqW.js} +1 -1
  128. package/dist/client/assets/{mcp-oauth-Dl3OcyHS.js → mcp-oauth-CS_U5MWt.js} +1 -1
  129. package/dist/client/assets/{members-CVcFRwzJ.js → members-Kb56DrWn.js} +1 -1
  130. package/dist/client/assets/{monaco-editor-6oF1_5Rv.js → monaco-editor-B_qDBcRJ.js} +1 -1
  131. package/dist/client/assets/{monitoring-stats-row-oHGWv6_N.js → monitoring-stats-row-DLAUs5tg.js} +1 -1
  132. package/dist/client/assets/{multi-select-Q7j5A2MT.js → multi-select-HXdaTxqa.js} +1 -1
  133. package/dist/client/assets/{oauth-callback-PoL_-HnY.js → oauth-callback-Ccnd2k4R.js} +1 -1
  134. package/dist/client/assets/{oauth-callback-ai-provider-DGeAIKGB.js → oauth-callback-ai-provider-C7Db36xR.js} +1 -1
  135. package/dist/client/assets/{onboarding-CD6h0MoQ.js → onboarding-C1rbCP2W.js} +1 -1
  136. package/dist/client/assets/{org-layout-CzPlRRs3.js → org-layout-CxBs98Ar.js} +1 -1
  137. package/dist/client/assets/{organization-choice-B1bFqmcL.js → organization-choice-DrLLxSoz.js} +1 -1
  138. package/dist/client/assets/{orgs-CbweUhRf.js → orgs-BbTz6TNL.js} +1 -1
  139. package/dist/client/assets/{page-seo-form-CNV9kfDu.js → page-seo-form-xJRGv7un.js} +1 -1
  140. package/dist/client/assets/{popover-D5GiNAyY.js → popover-DMqZhiHF.js} +1 -1
  141. package/dist/client/assets/{post-editor-CQpbHb80.js → post-editor-rVhLCZ0c.js} +1 -1
  142. package/dist/client/assets/{primitives-I-hRROi8.js → primitives-BHeOttUZ.js} +1 -1
  143. package/dist/client/assets/{profile-Ds5Ix8in.js → profile-Dv4y6bNR.js} +1 -1
  144. package/dist/client/assets/{project-app-view-VKBwhaaV.js → project-app-view-s7Fj8WgP.js} +1 -1
  145. package/dist/client/assets/record-editor-CWQh5FOd.js +1 -0
  146. package/dist/client/assets/{redirect-editor-C8PXnLEF.js → redirect-editor-CDWNokFL.js} +1 -1
  147. package/dist/client/assets/registry-CWnO2FJF.js +2 -0
  148. package/dist/client/assets/{registry-layout-PTzlEEOK.js → registry-layout-DjY8N_Hs.js} +1 -1
  149. package/dist/client/assets/{reports-CMpxAqPJ.js → reports-C1pgHtUC.js} +1 -1
  150. package/dist/client/assets/{require-capability-CRHirOp0.js → require-capability-CdOZJUDV.js} +1 -1
  151. package/dist/client/assets/{required-auth-layout-IJ5KMaV7.js → required-auth-layout-DUdjg8n8.js} +1 -1
  152. package/dist/client/assets/{reset-password-ulCP3mtK.js → reset-password-DD3DJpy6.js} +1 -1
  153. package/dist/client/assets/{roles-CXbDye5u.js → roles-Bme4JUNj.js} +1 -1
  154. package/dist/client/assets/{search-input-wz_3YmOf.js → search-input-CdI8Pgbj.js} +1 -1
  155. package/dist/client/assets/{secrets-Bmb_mWwh.js → secrets-CUofQaQ9.js} +1 -1
  156. package/dist/client/assets/{sections-editor-BhBP7Ob2.js → sections-editor-D0894X5D.js} +1 -1
  157. package/dist/client/assets/{select-DxLnud9a.js → select-kCMdjGDf.js} +1 -1
  158. package/dist/client/assets/{select-model-BdG4GQ81.js → select-model-B5SrHIQX.js} +1 -1
  159. package/dist/client/assets/{self-tool-result-BA7oGPeT.js → self-tool-result-DM5TjbUm.js} +1 -1
  160. package/dist/client/assets/{seo-editor-DDg9ydQ3.js → seo-editor-D_rUf9LC.js} +1 -1
  161. package/dist/client/assets/{settings-layout-Dg51K4Kh.js → settings-layout-C-QdPrwB.js} +1 -1
  162. package/dist/client/assets/{settings-section-sNSyfM9A.js → settings-section-BGx9mSWJ.js} +1 -1
  163. package/dist/client/assets/{settings-subnav-Ded1qddZ.js → settings-subnav-BfbIdXjG.js} +1 -1
  164. package/dist/client/assets/{shell-controls-CUcNY7Fr.js → shell-controls-BYkZeAbj.js} +1 -1
  165. package/dist/client/assets/{shell-layout-B_utdrsX.js → shell-layout-dgcctxP3.js} +1 -1
  166. package/dist/client/assets/{sidebar-hMS-Do1_.js → sidebar-s_g3bu-j.js} +1 -1
  167. package/dist/client/assets/{skeleton-_qZfcijY.js → skeleton-CI-9lXWg.js} +1 -1
  168. package/dist/client/assets/{spinner-DL7S_Tg-.js → spinner-B_HRFF3R.js} +1 -1
  169. package/dist/client/assets/{sso-CBuqzByo.js → sso-DaVcHVch.js} +1 -1
  170. package/dist/client/assets/{store-DUDLKkAB.js → store-f11wu41J.js} +1 -1
  171. package/dist/client/assets/store-registry-CE30Vn3X.js +2 -0
  172. package/dist/client/assets/{studio-tools-Cy9wsd4y.js → studio-tools-7jhyyEEa.js} +1 -1
  173. package/dist/client/assets/{switch-sXtR6oTo.js → switch-BDRsP0YE.js} +1 -1
  174. package/dist/client/assets/{synced-repos-D8XHKICV.js → synced-repos-DLA2z7V6.js} +1 -1
  175. package/dist/client/assets/tab-id-DNSBg1pI.js +1 -0
  176. package/dist/client/assets/{table-DD3qCk9X.js → table-Dgri0mcO.js} +1 -1
  177. package/dist/client/assets/{tabs-DZ5h0Fcm.js → tabs-2HjAqTx_.js} +1 -1
  178. package/dist/client/assets/{tasks-CD8H7e_s.js → tasks-BqzklBEA.js} +1 -1
  179. package/dist/client/assets/{textarea-CSgZI08j.js → textarea-BzAP5ul5.js} +1 -1
  180. package/dist/client/assets/{toggle-group-CvoJjpIe.js → toggle-group-DD5v2h7j.js} +1 -1
  181. package/dist/client/assets/{toolbar-DdebAnOR.js → toolbar-CwCNgNPL.js} +1 -1
  182. package/dist/client/assets/{tooltip-CWQrULJe.js → tooltip-CGYtF0CM.js} +1 -1
  183. package/dist/client/assets/{track-C5-1AYRb.js → track-iQ1N9A_G.js} +1 -1
  184. package/dist/client/assets/{types-BQWJxfW4.js → types-OJhKLG7b.js} +1 -1
  185. package/dist/client/assets/{use-ai-providers-DxDfGFw1.js → use-ai-providers-CAEIb15z.js} +1 -1
  186. package/dist/client/assets/{use-api-keys-BJ1hlP35.js → use-api-keys-DPUWR3Ad.js} +1 -1
  187. package/dist/client/assets/{use-automations-g5In83DG.js → use-automations-DY1t-c_g.js} +1 -1
  188. package/dist/client/assets/{use-autosave-CgGiRTZK.js → use-autosave-BfaxcSH9.js} +1 -1
  189. package/dist/client/assets/{use-capability-B0eEIIUn.js → use-capability-CMCOM-Ob.js} +1 -1
  190. package/dist/client/assets/{use-clock-tick-tQ6drAyu.js → use-clock-tick-BQ6X3lcG.js} +1 -1
  191. package/dist/client/assets/{use-commerce-diagnostic-D6HtRduN.js → use-commerce-diagnostic-luqE31Vl.js} +1 -1
  192. package/dist/client/assets/{use-connection-C-HVDfiy.js → use-connection-CCf0X_Vv.js} +1 -1
  193. package/dist/client/assets/{use-copy-D8PMebN0.js → use-copy-vWayLSpc.js} +1 -1
  194. package/dist/client/assets/{use-create-virtual-mcp-ttdO-ylP.js → use-create-virtual-mcp-CtrHqVF8.js} +1 -1
  195. package/dist/client/assets/{use-debounced-autosave-z_CWuHw8.js → use-debounced-autosave-cUsJaezi.js} +1 -1
  196. package/dist/client/assets/{use-debounced-value-CbVjJFET.js → use-debounced-value-COMgyEvN.js} +1 -1
  197. package/dist/client/assets/{use-decopilot-events-Bbpy6flz.js → use-decopilot-events-sgrSIiUJ.js} +1 -1
  198. package/dist/client/assets/{use-delete-connection-nWKSlMgi.js → use-delete-connection-BE019k7d.js} +1 -1
  199. package/dist/client/assets/{use-deployment-admin-CRNylnbv.js → use-deployment-admin-BTlj-zaN.js} +1 -1
  200. package/dist/client/assets/{use-file-configs-XiD5eAWL.js → use-file-configs-D2J5Sdhy.js} +1 -1
  201. package/dist/client/assets/{use-infinite-scroll-D6t-LMo5.js → use-infinite-scroll-Dbhyc-ys.js} +1 -1
  202. package/dist/client/assets/{use-join-requests-C09IfXhk.js → use-join-requests-CcwaNXwF.js} +1 -1
  203. package/dist/client/assets/{use-mcp-client-C-fMgszX.js → use-mcp-client-Dnsh6rr5.js} +1 -1
  204. package/dist/client/assets/{use-mcp-tools-CbbSPUy6.js → use-mcp-tools-BCzsZfdg.js} +1 -1
  205. package/dist/client/assets/{use-members-QekAqTvh.js → use-members-BScdoLaR.js} +1 -1
  206. package/dist/client/assets/{use-mobile-B10O0pZ7.js → use-mobile-BeYJ6MTB.js} +1 -1
  207. package/dist/client/assets/{use-navigate-to-agent-yk7cNjBx.js → use-navigate-to-agent-BmHo3Xvh.js} +1 -1
  208. package/dist/client/assets/{use-open-billing-url-BE6h4LOJ.js → use-open-billing-url-BKnHMwK7.js} +1 -1
  209. package/dist/client/assets/{use-org-auth-client-BQH-9lL0.js → use-org-auth-client-BUNP4eIU.js} +1 -1
  210. package/dist/client/assets/{use-org-repo-syncs-w8LFOrjq.js → use-org-repo-syncs-X7aknvvW.js} +1 -1
  211. package/dist/client/assets/{use-org-sso-oXX1uPBw.js → use-org-sso-DMJb8Ec2.js} +1 -1
  212. package/dist/client/assets/{use-organization-roles-DMHC71DF.js → use-organization-roles-BDF7Lm4s.js} +1 -1
  213. package/dist/client/assets/{use-organization-settings-D2zIP7wS.js → use-organization-settings-ezMtvH2D.js} +1 -1
  214. package/dist/client/assets/{use-registry-connections-BzsP92GY.js → use-registry-connections-D9SiW2ic.js} +1 -1
  215. package/dist/client/assets/{use-secrets-JrIeyUm9.js → use-secrets-DgvAGPLP.js} +1 -1
  216. package/dist/client/assets/{use-section-preview-base-C_MekoyS.js → use-section-preview-base-Co0O08zb.js} +1 -1
  217. package/dist/client/assets/{use-settings-tabs-C6hz5k04.js → use-settings-tabs-DBGBXz4S.js} +1 -1
  218. package/dist/client/assets/{use-status-sounds-CIAplBkm.js → use-status-sounds-050voMNC.js} +1 -1
  219. package/dist/client/assets/{use-tags-BRSc5FVx.js → use-tags-CYjObMAD.js} +1 -1
  220. package/dist/client/assets/{use-view-mode-BdPSyg0i.js → use-view-mode-8Tl-R4_x.js} +1 -1
  221. package/dist/client/assets/{use-virtual-mcp-BJMxUE1F.js → use-virtual-mcp-DC0yZKcn.js} +1 -1
  222. package/dist/client/assets/useInfiniteQuery-uKPP5SNM.js +1 -0
  223. package/dist/client/assets/{useRouterState-CKyWwcy8.js → useRouterState-BOB0p_oR.js} +1 -1
  224. package/dist/client/assets/useSuspenseInfiniteQuery-veDaNj0T.js +1 -0
  225. package/dist/client/assets/{users-Bh9cgiYJ.js → users--_NSodGI.js} +1 -1
  226. package/dist/client/assets/{variant-calendar-BhSX6y6r.js → variant-calendar-DuhbWJ29.js} +1 -1
  227. package/dist/client/assets/{view-mode-toggle-Col-XvVC.js → view-mode-toggle-CGD7TU-t.js} +1 -1
  228. package/dist/client/index.html +1 -1
  229. package/dist/server/cli.js +2 -2
  230. package/dist/server/server.js +2 -2
  231. package/package.json +1 -1
  232. package/dist/client/assets/index-BAN-evsd.js +0 -1
  233. package/dist/client/assets/record-editor-K34bBJD4.js +0 -1
  234. package/dist/client/assets/registry-aIa5F6SF.js +0 -2
  235. package/dist/client/assets/store-registry-0DDzIaYB.js +0 -2
  236. package/dist/client/assets/tab-id-zrZ__KZh.js +0 -1
  237. package/dist/client/assets/useInfiniteQuery-CaQ1BLm9.js +0 -1
  238. package/dist/client/assets/useSuspenseInfiniteQuery-BBFpWAvP.js +0 -1
@@ -944,7 +944,7 @@ You are the Usage Manager. You analyze how this workspace is actually used \u201
944
944
  b. MONITORING_LOGS_LIST with isError true (plus connectionId/toolName/virtualMcpId filters) \u2192 failing calls.
945
945
  c. MONITORING_LOG_GET on specific log ids for full input/output when the error message isn't enough.
946
946
  d. Report the failing tool/connection, error pattern, and suggest the fix or owner.
947
- </workflows>`,Vt1={id:"studio-usage-manager",title:"Usage Manager",icon:"icon://BarChart10?color=blue",description:"Analyze usage, costs, and clean up idle agents and connections",selectedTools:["MONITORING_STATS","MONITORING_LOGS_LIST","MONITORING_LOG_GET","MONITORING_THREAD_USAGE","COLLECTION_VIRTUAL_MCP_LIST","COLLECTION_VIRTUAL_MCP_GET","COLLECTION_VIRTUAL_MCP_DELETE","VIRTUAL_MCP_LAST_USED_LIST","COLLECTION_CONNECTIONS_LIST","COLLECTION_CONNECTIONS_GET","COLLECTION_CONNECTIONS_DELETE","ORGANIZATION_MEMBER_LIST"],selectedConnections:null,selectedPrompts:[],instructions:Lp8,getId:h7.USAGE_MANAGER}});function Pu0($){return CL.find((Z)=>$.startsWith(`${Z.id}_`))??null}async function Ep8($,Z){if("resolveRuntime"in $)return $.resolveRuntime(Z);return{instructions:$.instructions,selectedTools:$.selectedTools}}async function H50({virtualMcp:$,agentId:Z=$.id,organizationId:X,ctx:Q}){let Y=Pu0(Z);if(!Y)return $;let G=await Ep8(Y,{orgId:X,ctx:Q}),J=G.selectedTools?[...G.selectedTools]:null;return{...$,metadata:{...$.metadata??{},instructions:G.instructions},connections:$.connections.map((W)=>({...W,selected_tools:J}))}}async function F50($,Z){if(!("checklist"in $))return[];return Promise.all($.checklist.map(async(X)=>({label:X.label,activeForm:X.activeForm,action:X.action,completed:await X.isCompleted(Z),alwaysSuggest:X.alwaysSuggest})))}async function Ct1($,Z,X){let Q={self:l4.SELF($),registry:l4.REGISTRY($),"community-registry":l4.COMMUNITY_REGISTRY($)};await Promise.all(CL.map(async(Y)=>{let G=Y.getId($),J=await X.findById(G,$),K=(Y.selectedConnections??["self"]).map((H)=>Q[H]);if(J){await X.update(G,Z,{metadata:{...J.metadata??{},instructions:Y.instructions},connections:K.map((H)=>{let F=J.connections.find((N)=>N.connection_id===H);return{connection_id:H,selected_tools:Y.selectedTools?[...Y.selectedTools]:null,selected_resources:F?.selected_resources??null,selected_prompts:F?.selected_prompts??null}})});return}await X.create($,Z,{title:Y.title,description:Y.description,icon:Y.icon,status:"active",pinned:!1,metadata:{instructions:Y.instructions},connections:K.map((H)=>({connection_id:H,selected_tools:Y.selectedTools?[...Y.selectedTools]:null,selected_resources:null,selected_prompts:Y.selectedPrompts?[...Y.selectedPrompts]:null}))},{id:G})}))}var CL;var Nx=w(()=>{U8();Ot1();wt1();Lt1();At1();Rt1();qt1();kt1();St1();CL=[Pt1,Ut1,Dt1,Tt1,Bt1,It1,Mt1,Vt1]});import{DBOS as N50}from"@dbos-inc/dbos-sdk";async function jp8($){let Z=p8(),X=new tf(Z.db);await Ct1($.orgId,$.createdBy,X)}async function zp8($){let Z=p8(),X=new tf(Z.db);for(let Q of CL){let Y=Q.getId($.orgId),G=await X.findById(Y,$.orgId);if(!G)continue;let J=Q.selectedPrompts?[...Q.selectedPrompts]:null;if(G.connections.every((K)=>{let H=K.selected_prompts;if(J===null)return H===null;if(H===null)return!1;if(H.length!==J.length)return!1;return H.every((F,N)=>F===J[N])}))continue;await X.update(Y,$.createdBy,{connections:G.connections.map((K)=>({connection_id:K.connection_id,selected_tools:K.selected_tools,selected_resources:K.selected_resources,selected_prompts:J}))})}}async function Pp8($){await N50.runStep(()=>jp8($),{name:"installStudioPack"}),await N50.runStep(()=>zp8($),{name:"backfillSelectedPrompts"})}async function Au0($){await N50.startWorkflow(Ap8,{workflowID:`install-studio-pack:${Tp8}:${$.orgId}`})($)}async function _t1(){let Z=await p8().db.selectFrom("member").select(["organizationId","userId"]).orderBy("createdAt","asc").execute(),X=new Map;for(let Q of Z)if(!X.has(Q.organizationId))X.set(Q.organizationId,Q.userId);await Promise.all(Array.from(X).map(async([Q,Y])=>{try{await Au0({orgId:Q,createdBy:Y})}catch(G){console.error("[studio-pack-backfill] enqueue failed",{orgId:Q},G)}}))}var Ap8,Tp8="v5";var U50=w(()=>{_G();bx0();Nx();Ap8=N50.registerWorkflow(Pp8,{name:"installStudioPackWorkflow"})});class nm{constructor(){this._messageQueue=[]}static createLinkedPair(){let $=new nm,Z=new nm;return $._otherTransport=Z,Z._otherTransport=$,[$,Z]}async start(){while(this._messageQueue.length>0){let $=this._messageQueue.shift();this.onmessage?.($.message,$.extra)}}async close(){let $=this._otherTransport;this._otherTransport=void 0,await $?.close(),this.onclose?.()}async send($,Z){if(!this._otherTransport)throw Error("Not connected");if(this._otherTransport.onmessage)this._otherTransport.onmessage($,{authInfo:Z?.authInfo});else this._otherTransport._messageQueue.push({message:$,extra:{authInfo:Z?.authInfo}})}}import{z as $4}from"zod";var O50,vt1,ft1,bt1,xt1,yt1,gt1,ht1,ut1,ct1;var Ux=w(()=>{O50=$4.record($4.string(),$4.array($4.string())),vt1=$4.object({id:$4.string().describe("Unique identifier for the API key"),name:$4.string().describe("Human-readable name for the API key"),userId:$4.string().describe("ID of the user who owns this API key"),permissions:O50.describe('Permissions granted to this API key. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Example: { "self": ["API_KEY_CREATE"], "conn_abc123": ["SEND_MESSAGE"] }'),expiresAt:$4.string().datetime().nullable().optional().describe("Expiration date of the API key (ISO 8601)"),createdAt:$4.string().datetime().describe("When the API key was created (ISO 8601)")}),ft1=$4.object({name:$4.string().min(1).max(64).describe("Human-readable name for the API key"),permissions:O50.describe(`Permissions to grant (REQUIRED \u2014 there is no implicit default). Format: { resource: [actions] }. Resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Actions are tool names (e.g., ["ORGANIZATION_GET"]) or ["*"] for all. Example: { "self": ["ORGANIZATION_GET", "COLLECTION_CONNECTIONS_LIST"] }. The key is authorized solely by this allowlist; the creator's role does not widen it.`),expiresIn:$4.number().positive().optional().describe("Expiration time in seconds. If not provided, key never expires."),metadata:$4.record($4.string(),$4.unknown()).optional().describe("Additional metadata to store with the API key")}),bt1=$4.object({id:$4.string().describe("Unique identifier for the API key"),name:$4.string().describe("Human-readable name for the API key"),key:$4.string().describe("The actual API key value. STORE THIS SECURELY - it will not be shown again!"),permissions:O50.describe('Permissions granted to this API key. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools'),expiresAt:$4.string().datetime().nullable().optional().describe("Expiration date of the API key (ISO 8601)"),createdAt:$4.string().datetime().describe("When the API key was created (ISO 8601)")}),xt1=$4.object({}),yt1=$4.object({items:$4.array(vt1).describe("List of API keys (without key values)")}),gt1=$4.object({keyId:$4.string().describe("ID of the API key to update"),name:$4.string().min(1).max(64).optional().describe("New name for the API key"),permissions:O50.optional().describe('New permissions. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Actions are tool names or "*" for all. Example: { "self": ["API_KEY_CREATE"] }. Replaces existing permissions.'),metadata:$4.record($4.string(),$4.unknown()).optional().describe("New metadata. Replaces existing metadata.")}),ht1=$4.object({item:vt1.describe("The updated API key (without key value)")}),ut1=$4.object({keyId:$4.string().describe("ID of the API key to delete")}),ct1=$4.object({success:$4.boolean().describe("Whether the deletion was successful"),keyId:$4.string().describe("ID of the deleted API key")})});var Tu0;var lt1=w(()=>{M4();C0();Ux();Tu0=c({name:"API_KEY_CREATE",description:"Create an API key with scoped permissions. The key value is returned only once \u2014 store it immediately.",annotations:{title:"Create API Key",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:ft1,outputSchema:bt1,handler:async($,Z)=>{r(Z),await Z.access.check();let X=await Z.boundAuth.apiKey.create({name:$.name,permissions:$.permissions,expiresIn:$.expiresIn,metadata:{...$.metadata,organization:Z.organization}}),Q=X.expiresAt?X.expiresAt instanceof Date?X.expiresAt.toISOString():X.expiresAt:null,Y=X.createdAt instanceof Date?X.createdAt.toISOString():X.createdAt,G=G1(Z);if(G)y1.capture({distinctId:G,event:"api_key_created",...Z.organization?.id?{groups:{organization:Z.organization.id}}:{},properties:{key_id:X.id,key_name:X.name??$.name,organization_id:Z.organization?.id,has_expiry:!!Q}});return{id:X.id,name:X.name??$.name,key:X.key,permissions:X.permissions??{},expiresAt:Q,createdAt:Y}}})});var Ru0;var dt1=w(()=>{M4();C0();Ux();Ru0=c({name:"API_KEY_DELETE",description:"Delete and instantly revoke an API key. Cannot be undone.",annotations:{title:"Delete API Key",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:ut1,outputSchema:ct1,handler:async($,Z)=>{r(Z),await Z.access.check();let X=G1(Z);if(!X)throw Error("User ID required to delete API key");let Y=(await Z.boundAuth.apiKey.list())?.find((K)=>K.id===$.keyId);if(!Y)throw Error("API key not found");let J=Y.metadata?.organization?.id,W=Z.organization?.id;if(J!==W)throw Error("Cannot delete API key from another organization");if(await Z.boundAuth.apiKey.delete($.keyId),W)y1.capture({distinctId:X,event:"api_key_deleted",groups:{organization:W},properties:{key_id:$.keyId,organization_id:W}});return{success:!0,keyId:$.keyId}}})});var Iu0;var mt1=w(()=>{C0();Ux();Iu0=c({name:"API_KEY_LIST",description:"List API keys for the current user in the current organization. Returns metadata only \u2014 key values are never shown after creation.",annotations:{title:"List API Keys",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:xt1,outputSchema:yt1,handler:async($,Z)=>{r(Z),await Z.access.check();let X=await Z.boundAuth.apiKey.list(),Q=Z.organization?.id;return{items:(X??[]).filter((G)=>{return G.metadata?.organization?.id===Q}).map((G)=>({id:G.id,name:G.name??"Unnamed Key",userId:G.userId,permissions:G.permissions??{},expiresAt:G.expiresAt?G.expiresAt instanceof Date?G.expiresAt.toISOString():G.expiresAt:null,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt}))}}})});var qu0;var it1=w(()=>{C0();Ux();qu0=c({name:"API_KEY_UPDATE",description:"Update an API key's name, permissions, or metadata. The key value cannot be changed or retrieved.",annotations:{title:"Update API Key",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:gt1,outputSchema:ht1,handler:async($,Z)=>{if(r(Z),await Z.access.check(),!G1(Z))throw Error("User ID required to update API key");let Y=(await Z.boundAuth.apiKey.list())?.find((H)=>H.id===$.keyId);if(!Y)throw Error(`API key not found: ${$.keyId}`);let J=Y.metadata?.organization?.id,W=Z.organization?.id;if(J!==W)throw Error("Cannot update API key from another organization");let K=await Z.boundAuth.apiKey.update({keyId:$.keyId,name:$.name,permissions:$.permissions,metadata:{...$.metadata,organization:Z.organization}});if(!K)throw Error(`Failed to update API key: ${$.keyId}`);return{item:{id:K.id,name:K.name??$.name??"Unnamed Key",userId:K.userId,permissions:K.permissions??{},expiresAt:K.expiresAt?K.expiresAt instanceof Date?K.expiresAt.toISOString():K.expiresAt:null,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt}}}})});var pt1=w(()=>{lt1();dt1();mt1();it1();Ux()});function zO($){let Z=$.trim();if(!Z)return{ok:!1,error:"Enter a website URL."};let X=Ip8.test(Z),Q=qp8.test(Z),Y=Mp8.test(Z);if(X&&!Q&&!Y)return{ok:!1,error:"Use an HTTP or HTTPS website URL."};let G=Q?Z:`https://${Z}`,J;try{J=new URL(G)}catch{return{ok:!1,error:"Enter a valid website URL."}}if(J.protocol!=="http:"&&J.protocol!=="https:")return{ok:!1,error:"Use an HTTP or HTTPS website URL."};let W=J.hostname.split(".");if(W.length<2||W.some((K)=>!K||!kp8.test(K)))return{ok:!1,error:"Enter a valid website URL."};return J.protocol="https:",{ok:!0,value:J.origin}}var Ip8,qp8,Mp8,kp8;var tm=w(()=>{Ip8=/^[a-zA-Z][a-zA-Z\d+.-]*:/,qp8=/^[a-zA-Z][a-zA-Z\d+.-]*:\/\//,Mp8=/^[^\s/:?#]+\.[^\s/:?#]+:\d+(?:[/?#]|$)/,kp8=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i});import{z as hX}from"zod";function oW($){if($.baseUrl)return $.baseUrl.replace(/\/+$/,"");return(($.settings??b0()).reportsInternalApiUrl??Vp8).replace(/\/+$/,"")}function tt1($={}){return`${oW($)}/api/v2/mcp`}function _L($){let Z=$.apiKey??($.settings??b0()).reportsInternalApiKey;if(!Z)throw Error("REPORTS_INTERNAL_API_KEY (or the legacy COMMERCE_DISCOVERY_INTERNAL_API_KEY) is required to set up reports.");return Z}function w50($){return new URL($).hostname}function Cp8($){return $==="ownership_unverified"||$==="already_claimed_by_other_org"}function _p8($,Z={}){switch($){case"ownership_unverified":{let X=Z.email?`O e-mail ${Z.email}`:"Este e-mail",Q=Z.domain?` ${Z.domain}`:" este site";return`${X} n\xE3o tem permiss\xE3o para reivindicar${Q}. Use um e-mail do dom\xEDnio do site ou pe\xE7a ao suporte para autorizar seu dom\xEDnio.`}case"already_claimed_by_other_org":return"Este site j\xE1 pertence a outra organiza\xE7\xE3o. Fale com o suporte para transferir o acesso.";case"unknown":return"N\xE3o foi poss\xEDvel configurar o Commerce Discovery. Tente novamente ou fale com o suporte.";default:return $}}async function vp8($){let Z=await $.text().catch(()=>"");if(!Z)return"unknown";try{let X=JSON.parse(Z);return Cp8(X.error)?X.error:"unknown"}catch{return"unknown"}}async function B50($){let Z=await $.text().catch(()=>"");if(!Z)return;try{return JSON.parse(Z)}catch{return}}async function Mu0($){let Z=`Commerce Discovery auth failed with status ${$.status}.`,X=await $.text().catch(()=>"");if(!X)return Z;try{let Q=JSON.parse(X),Y=typeof Q.error==="string"?Q.error:typeof Q.message==="string"?Q.message:null;return Y?`Commerce Discovery auth failed: ${Y}.`:Z}catch{return Z}}async function rt1($,Z={}){let X=oW(Z),Q=_L(Z),Y=Z.fetchImpl??fetch,G=w50($.siteUrl),J=`${X}/api/v2/internal/diagnostics/${encodeURIComponent(G)}/upgrade`,W=await Y(J,{method:"POST",headers:{Authorization:`Bearer ${Q}`,"Content-Type":"application/json"},body:JSON.stringify({org_id:$.orgId,...$.orgName?{name:$.orgName}:{},...$.email?{email:$.email}:{},...$.reportUrl?{report_url:$.reportUrl}:{}})});if(!W.ok){let H=await vp8(W);throw new ot1(H,{email:$.email,domain:G})}let K=Sp8.safeParse(await B50(W));if(!K.success)throw Error("Commerce Discovery auth response did not include a token.");return{authorizationToken:K.data.token}}async function at1($,Z={}){let X=oW(Z),Q=_L(Z),Y=Z.fetchImpl??fetch,G=w50($.siteUrl),J=`${X}/api/v2/internal/diagnostics/${encodeURIComponent(G)}/bindings`,W=await Y(J,{method:"POST",headers:{Authorization:`Bearer ${Q}`,"Content-Type":"application/json"},body:JSON.stringify({org_id:$.orgId,provider:$.provider,resource_id:$.resourceId})});if(W.status===409)return{ok:!1,reason:"resource_already_bound",detail:"Este recurso j\xE1 est\xE1 vinculado a outra loja. Se ele \xE9 seu, fale com o suporte para revis\xE3o manual."};if(W.status===422){let H=nt1.safeParse(await B50(W));return{ok:!1,reason:H.success?H.data.reason??"verification_failed":"verification_failed",detail:(H.success?H.data.detail:void 0)??"N\xE3o foi poss\xEDvel verificar o acesso a este recurso."}}if(!W.ok)throw Error(await Mu0(W));let K=nt1.safeParse(await B50(W));if(!K.success||!K.data.binding)throw Error("Commerce Discovery bind response did not include a binding.");return{ok:!0,resourceId:K.data.binding.resource_id,evidence:K.data.binding.evidence}}async function st1($,Z={}){let X=oW(Z),Q=_L(Z),Y=Z.fetchImpl??fetch,G=w50($.siteUrl),J=`${X}/api/v2/internal/diagnostics/${encodeURIComponent(G)}/run`,W=await Y(J,{method:"POST",headers:{Authorization:`Bearer ${Q}`,"Content-Type":"application/json"},body:JSON.stringify({org_id:$.orgId,...$.githubRepo?{github_repo:$.githubRepo}:{}})});if(W.status===409)return{triggered:!1,reason:"not_upgraded"};if(!W.ok)throw Error(await Mu0(W));return{triggered:!0}}async function et1($,Z={}){let X=oW(Z),Q=_L(Z),Y=Z.fetchImpl??fetch,G=w50($.siteUrl),J=`${X}/api/v2/internal/diagnostics/${encodeURIComponent(G)}/connections/status?org_id=${encodeURIComponent($.orgId)}`,W=await Y(J,{method:"GET",headers:{Authorization:`Bearer ${Q}`}});if(W.status===404||W.status===409)return{providers:{},claimed:!1};if(!W.ok)throw Error(await Mu0(W));let K=fp8.safeParse(await B50(W));return{providers:K.success?K.data.providers:{},claimed:!0}}var Vp8,Sp8,nt1,ot1,fp8;var vL=w(()=>{U8();T$();Vp8=new URL(Sx1).origin,Sp8=hX.object({token:hX.string().min(1)}),nt1=hX.object({binding:hX.object({resource_id:hX.string(),evidence:hX.string()}).optional(),reason:hX.string().optional(),detail:hX.string().optional()});ot1=class ot1 extends Error{code;constructor($,Z={}){super(_p8($,Z));this.name="CommerceDiscoveryClaimError",this.code=$}};fp8=hX.object({providers:hX.record(hX.string(),hX.object({connected:hX.boolean(),via:hX.enum(["oauth","sa"]).nullable(),resource:hX.string().nullable()}))})});import{z as kY}from"zod";var bp8,xp8,ku0;var $o1=w(()=>{tm();C0();vL();bp8=kY.object({siteUrl:kY.string().min(1).describe("Website URL of the store being bound."),provider:kY.enum(["ga4","gsc"]).describe("Which Google source to bind: ga4 (Analytics) or gsc (Search Console)."),resourceId:kY.string().min(1).describe("The resource id the client typed: GA4 numeric property id, or GSC site (sc-domain:example.com or https://example.com/).")}),xp8=kY.discriminatedUnion("ok",[kY.object({ok:kY.literal(!0),resourceId:kY.string(),evidence:kY.string()}),kY.object({ok:kY.literal(!1),reason:kY.string(),detail:kY.string()})]),ku0=c({name:"COMMERCE_DISCOVERY_BIND",description:"Bind a GA4 property or GSC site to the org's store via the shared service account (consent-free lane). The client grants deco-reader@\u2026 access to the resource and provides its id; Commerce Discovery verifies the resource belongs to this domain before persisting. Returns ok:false with an actionable pt-BR detail when verification fails or the resource is already bound elsewhere.",annotations:{title:"Bind Commerce Discovery Data Source",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},inputSchema:bp8,outputSchema:xp8,handler:async($,Z)=>{r(Z);let X=t(Z);await Z.access.check();let Q=zO($.siteUrl);if(!Q.ok)throw Error(Q.error);return at1({siteUrl:Q.value,orgId:X.id,provider:$.provider,resourceId:$.resourceId.trim()})}})});import{z as rW}from"zod";var yp8,gp8,Vu0;var Zo1=w(()=>{tm();C0();vL();yp8=rW.object({siteUrl:rW.string().min(1).describe("Website URL of the store to inspect.")}),gp8=rW.object({providers:rW.record(rW.string(),rW.object({connected:rW.boolean(),via:rW.enum(["oauth","sa"]).nullable(),resource:rW.string().nullable()})),claimed:rW.boolean().describe("False when the site isn't claimed/upgraded for this org \u2014 providers is then empty because the status is unreadable, NOT because nothing is connected. The UI must warn instead of rendering existing bindings as disconnected.")}),Vu0=c({name:"COMMERCE_DISCOVERY_CONNECTION_STATUS",description:"Read per-provider connection status (ga4/gsc/vtex) for the org's store \u2014 { connected, via: oauth|sa, resource }. The single source of truth for whether a data source is connected, unifying the OAuth (Studio vault) and shared-SA binding lanes. Read-only.",annotations:{title:"Commerce Discovery Connection Status",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},inputSchema:yp8,outputSchema:gp8,handler:async($,Z)=>{r(Z);let X=t(Z);await Z.access.check();let Q=zO($.siteUrl);if(!Q.ok)throw Error(Q.error);return et1({siteUrl:Q.value,orgId:X.id})}})});import{z as om}from"zod";var hp8,up8,Su0;var Xo1=w(()=>{U8();tm();C0();vL();hp8=om.object({siteUrl:om.string().min(1).describe("Website URL to run the diagnostic for.")}),up8=om.object({triggered:om.boolean(),reason:om.string().optional()}),Su0=c({name:"COMMERCE_DISCOVERY_RUN",description:"Trigger the Commerce Discovery diagnostic run for the current organization's store. Call once the data sources (GA4/GSC/VTEX) are connected \u2014 this run resolves credentials and produces the enriched report.",annotations:{title:"Run Commerce Discovery",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},inputSchema:hp8,outputSchema:up8,handler:async($,Z)=>{r(Z);let X=t(Z);await Z.access.check();let Q=zO($.siteUrl);if(!Q.ok)throw Error(Q.error);let Y=l4.COMMERCE_DISCOVERY(X.id),J=(await Z.storage.connections.findById(Y,X.id))?.configuration_state,W=J&&typeof J==="object"&&typeof J.github_repo==="string"&&J.github_repo.length>0?J.github_repo:void 0;return st1({siteUrl:Q.value,orgId:X.id,githubRepo:W})}})});var PO=w(()=>{E$0()});import{z as aW}from"zod";async function mp8($,Z,X,Q){let Y=await $.storage.connections.findById(Z,X);if(Y)return Y;throw Q}async function ip8($,Z,X,Q){let Y=await $.storage.virtualMcps.findById(Z,X);if(Y)return Y;throw Q}var Cu0,cp8=3600000,lp8,dp8,_u0;var Qo1=w(()=>{U8();tm();C0();VW();PO();vL();Cu0=g80,lp8=aW.object({siteUrl:aW.string().min(1).describe("Website URL to configure.")}),dp8=aW.object({connection:b7,virtualMcp:x7,reportApp:aW.object({connectionId:aW.string(),virtualMcpId:aW.string(),toolName:aW.literal(Cu0)}),created:aW.object({connection:aW.boolean(),virtualMcp:aW.boolean()})});_u0=c({name:"COMMERCE_DISCOVERY_SETUP",description:"Create or return the Commerce Discovery connection and virtual MCP for the current organization.",annotations:{title:"Set Up Commerce Discovery",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:lp8,outputSchema:dp8,handler:async($,Z)=>{r(Z);let X=t(Z);await Z.access.check("COLLECTION_CONNECTIONS_CREATE");let Q=G1(Z);if(!Q)throw Error("User ID required to set up Commerce Discovery");let Y=zO($.siteUrl);if(!Y.ok)throw Error(Y.error);let G=l4.COMMERCE_DISCOVERY(X.id),J=u80(X.id),W=new URLSearchParams({virtualmcpid:J,main:`app:${G}:${Cu0}`}),K={email:Z.auth.user?.email,reportUrl:`${Z.baseUrl}/${encodeURIComponent(X.slug??X.id)}/${crypto.randomUUID()}?${W.toString()}`},H=await Z.storage.connections.findById(G,X.id),F={connection:!1,virtualMcp:!1},N=await rt1({siteUrl:Y.value,orgId:X.id,orgName:X.name,...K}),U=tt1();if(H)console.log("[commerce-discovery] syncing connection to claimed site",{orgId:X.id,siteUrl:Y.value,connectionId:G}),H=await Z.storage.connections.update(H.id,{connection_url:U,connection_token:N.authorizationToken,metadata:{...H.metadata??{},siteUrl:Y.value}});else{console.log("[commerce-discovery] creating connection",{orgId:X.id,siteUrl:Y.value,connectionId:G});try{let L=dx1(X.id,N.authorizationToken,U);H=await Z.storage.connections.create({...L,metadata:{...L.metadata??{},siteUrl:Y.value},organization_id:X.id,created_by:Q}),F.connection=!0}catch(L){H=await mp8(Z,G,X.id,L)}}let O=await Z.storage.virtualMcps.findById(J,X.id);if(!O){console.log("[commerce-discovery] creating virtual MCP",{orgId:X.id,siteUrl:Y.value,connectionId:H.id,virtualMcpId:J});try{O=await Z.storage.virtualMcps.create(X.id,Q,mx1(X.id,H.id),{id:J}),F.virtualMcp=!0}catch(L){O=await ip8(Z,J,X.id,L)}}if(!O.pinned)O=await Z.storage.virtualMcps.update(O.id,Q,{pinned:!0});let B=await Z.db.selectFrom("organization").select(["createdAt"]).where("id","=",X.id).executeTakeFirst();if((B?Date.now()-new Date(B.createdAt).getTime():Number.POSITIVE_INFINITY)<cp8){let E=(await Z.storage.organizationSettings.get(X.id))?.flags,j={};if(E?.reports_only==null)j.reports_only=!0;if(Object.keys(j).length>0)await Z.storage.organizationSettings.upsert(X.id,{flags:j})}return{connection:H,virtualMcp:O,reportApp:{connectionId:H.id,virtualMcpId:O.id,toolName:Cu0},created:F}}})});var Yo1=w(()=>{$o1();Zo1();Xo1();Qo1()});var vu0=_((Go1)=>{Object.defineProperty(Go1,"__esModule",{value:!0});Go1.kvPrefix=Go1.KvWatchInclude=void 0;Go1.KvWatchInclude={LastValue:"",AllHistory:"history",UpdatesOnly:"updates"};Go1.kvPrefix="KV_"});var Lo1=_((wo1)=>{Object.defineProperty(wo1,"__esModule",{value:!0});wo1.KvStatusImpl=wo1.Bucket=wo1.Kvm=wo1.kvOperationHdr=void 0;wo1.Base64KeyCodec=tp8;wo1.NoopKvCodecs=fu0;wo1.defaultBucketOpts=Ko1;wo1.validateKey=Ho1;wo1.validateSearchKey=Fo1;wo1.hasWildcards=No1;wo1.validateBucket=D50;var _5=HY(),$5=Ws(),C5=vu0();function tp8(){let $=(Z,X)=>{let Q=[];for(let Y of Z.split("."))switch(Y){case">":case"*":Q.push(Y);break;default:Q.push(X(Y));break}return Q.join(".")};return{encode(Z){return $(Z,btoa)},decode(Z){return $(Z,atob)}}}function fu0(){return{key:{encode($){return $},decode($){return $}},value:{encode($){return typeof $==="string"?new TextEncoder().encode($):$},decode($){return $}}}}function Ko1(){return{replicas:1,history:1,timeout:2000,max_bytes:-1,maxValueSize:-1,codec:fu0(),storage:$5.StorageType.File}}wo1.kvOperationHdr="KV-Operation";var Wo1="$KV",op8=/^[-/=.\w]+$/,rp8=/^[-/=.>*\w]+$/,ap8=/^[-\w]+$/;function Ho1($){if($.startsWith(".")||$.endsWith(".")||!op8.test($))throw Error(`invalid key: ${$}`)}function Fo1($){if($.startsWith(".")||$.endsWith(".")||$.includes("..")||!rp8.test($))throw Error(`invalid key: ${$}`)}function No1($){if($.startsWith(".")||$.endsWith("."))throw Error(`invalid key: ${$}`);let Z=$.split("."),X=!1;for(let Q=0;Q<Z.length;Q++)switch(Z[Q]){case"*":X=!0;break;case">":if(Q!==Z.length-1)throw Error(`invalid key: ${$}`);X=!0;break;default:}return X}function D50($){if(!ap8.test($))throw Error(`invalid bucket name: ${$}`)}class Uo1{js;constructor($){this.js=(0,$5.toJetStreamClient)($)}create($,Z={}){return this.#$($,Z)}open($,Z={}){return Z.bindOnly=!0,this.#$($,Z)}#$($,Z={}){let{ok:X,min:Q}=this.js.nc.features.get(_5.Feature.JS_KV);if(!X)return Promise.reject(Error(`kv is only supported on servers ${Q} or better`));if(Z.bindOnly)return Ox.bind(this.js,$,Z);return Ox.create(this.js,$,Z)}list(){let $=(X)=>{let Y=X.streams.filter((J)=>{return J.config.name.startsWith(C5.kvPrefix)});Y.forEach((J)=>{J.config.sealed=J.config.sealed||!1,J.config.deny_delete=J.config.deny_delete||!1,J.config.deny_purge=J.config.deny_purge||!1,J.config.allow_rollup_hdrs=J.config.allow_rollup_hdrs||!1});let G="";if(Y.length)G=this.js.nc.info?.cluster??"";return Y.map((J)=>{return new L50(J,G)})},Z=`${this.js.prefix}.STREAM.LIST`;return new $5.ListerImpl(Z,$,this.js)}}wo1.Kvm=Uo1;class Ox{js;jsm;stream;bucket;direct;codec;prefix;editPrefix;useJsPrefix;_prefixLen;constructor($,Z,X){D50($),this.js=Z,this.jsm=X,this.bucket=$,this.prefix=Wo1,this.editPrefix="",this.useJsPrefix=!1,this._prefixLen=0}static async create($,Z,X={}){D50(Z);let Q=await $.jetstreamManager(),Y=new Ox(Z,$,Q);return await Y.init(X),Y}static async bind($,Z,X={}){let Q=$.getOptions()?.checkAPI||X.bindOnly===!1,Y=await $.jetstreamManager(Q),G={config:{allow_direct:X.allow_direct}};D50(Z);let J=new Ox(Z,$,Y);return G.config.name=X.streamName??J.bucketName(),Object.assign(J,G),J.stream=G.config.name,J.codec=X.codec||fu0(),J.direct=G.config.allow_direct??!1,J.initializePrefixes(G),J}async init($={}){let Z=Object.assign(Ko1(),$);this.codec=Z.codec;let X={};if(this.stream=X.name=$.streamName??this.bucketName(),X.retention=$5.RetentionPolicy.Limits,X.max_msgs_per_subject=Z.history,Z.max_bytes)X.max_bytes=Z.max_bytes;if(X.max_msg_size=Z.maxValueSize,X.storage=Z.storage,$.placement)X.placement=$.placement;if($.republish)X.republish=$.republish;if($.description)X.description=$.description;if($.markerTTL)X.allow_msg_ttl=!0,X.subject_delete_marker_ttl=(0,_5.nanos)(Z.markerTTL);if($.mirror){let H=Object.assign({},$.mirror);if(!H.name.startsWith(C5.kvPrefix))H.name=`${C5.kvPrefix}${H.name}`;X.mirror=H,X.mirror_direct=!0}else if($.sources){let H=$.sources.map((F)=>{let N=Object.assign({},F),U=N.name.startsWith(C5.kvPrefix)?N.name.substring(C5.kvPrefix.length):N.name;if(!N.name.startsWith(C5.kvPrefix))N.name=`${C5.kvPrefix}${N.name}`;if(!F.external&&U!==this.bucket)N.subject_transforms=[{src:`$KV.${U}.>`,dest:`$KV.${this.bucket}.>`}];return N});X.sources=H,X.subjects=[this.subjectForBucket()]}else X.subjects=[this.subjectForBucket()];if($.metadata)X.metadata=$.metadata;if(typeof $.compression==="boolean")X.compression=$.compression?$5.StoreCompression.S2:$5.StoreCompression.None;let Q=this.js.nc,Y=Q.getServerVersion(),G=Y?(0,_5.compare)(Y,(0,_5.parseSemVer)("2.7.2"))>=0:!1;X.discard=G?$5.DiscardPolicy.New:$5.DiscardPolicy.Old;let{ok:J,min:W}=Q.features.get(_5.Feature.JS_ALLOW_DIRECT);if(!J&&$.allow_direct===!0){let H=Y?`${Y.major}.${Y.minor}.${Y.micro}`:"unknown";return Promise.reject(Error(`allow_direct is not available on server version ${H} - requires ${W}`))}if($.allow_direct=typeof $.allow_direct==="boolean"?$.allow_direct:J,X.allow_direct=$.allow_direct,this.direct=X.allow_direct,X.num_replicas=Z.replicas,Z.ttl)X.max_age=(0,_5.nanos)(Z.ttl);X.allow_rollup_hdrs=!0;let K;try{if(K=await this.jsm.streams.info(X.name),!K.config.allow_direct&&this.direct===!0)this.direct=!1}catch(H){if(H.message==="stream not found")K=await this.jsm.streams.add(X);else throw H}this.initializePrefixes(K)}initializePrefixes($){this._prefixLen=0,this.prefix=`$KV.${this.bucket}`,this.useJsPrefix=this.js.apiPrefix!=="$JS.API";let{mirror:Z}=$.config;if(Z){let X=Z.name;if(X.startsWith(C5.kvPrefix))X=X.substring(C5.kvPrefix.length);if(Z.external&&Z.external.api!==""){let Q=Z.name.substring(C5.kvPrefix.length);this.useJsPrefix=!1,this.prefix=`$KV.${Q}`,this.editPrefix=`${Z.external.api}.$KV.${X}`}else this.editPrefix=this.prefix}}bucketName(){return this.stream??`${C5.kvPrefix}${this.bucket}`}subjectForBucket(){return`${this.prefix}.${this.bucket}.>`}subjectForKey($,Z=!1){let X=[];if(Z){if(this.useJsPrefix)X.push(this.js.apiPrefix);if(this.editPrefix!=="")X.push(this.editPrefix);else X.push(this.prefix)}else if(this.prefix)X.push(this.prefix);return X.push($),X.join(".")}fullKeyName($){if(this.prefix!=="")return`${this.prefix}.${$}`;return`${Wo1}.${this.bucket}.${$}`}get prefixLen(){if(this._prefixLen===0)this._prefixLen=this.prefix.length+1;return this._prefixLen}encodeKey($){let Z=[];for(let X of $.split("."))switch(X){case">":case"*":Z.push(X);break;default:Z.push(this.codec.key.encode(X));break}return Z.join(".")}decodeKey($){let Z=[];for(let X of $.split("."))switch(X){case">":case"*":Z.push(X);break;default:Z.push(this.codec.key.decode(X));break}return Z.join(".")}validateKey=Ho1;validateSearchKey=Fo1;hasWildcards=No1;close(){return Promise.resolve()}dataLen($,Z){let X=Z?Z.get($5.JsHeaders.MessageSizeHdr)||"":"";if(X!=="")return parseInt(X,10);return $.length}smToEntry($){return new Oo1(this.bucket,this.prefixLen,$,this.codec)}jmToWatchEntry($,Z){return new Bo1(this.bucket,this.prefixLen,$,Z,this.codec)}async create($,Z,X){let Q;try{let G={previousSeq:0},J=await this._put($,Z,G,X);return Promise.resolve(J)}catch(G){if(Q=G,G instanceof $5.JetStreamApiError){let J=G;if(J.code!==$5.JetStreamApiCodes.StreamWrongLastSequence&&J.code!==$5.JetStreamApiCodes.StreamWrongLastSequenceUnknown)return Promise.reject(G)}}let Y=0;try{let G=await this.get($);if(G?.operation==="DEL"||G?.operation==="PURGE")return Y=G!==null?G.revision:0,this._put($,Z,{previousSeq:Y},X);else return Promise.reject(Q)}catch(G){return Promise.reject(G)}}update($,Z,X,Q){if(X<=0)throw Error("version must be greater than 0");return this.put($,Z,{previousSeq:X,timeout:Q})}async _put($,Z,X={},Q){let Y=this.encodeKey($);this.validateKey(Y),Z=this.codec.value.encode(Z);let G={timeout:X?.timeout};if(X.previousSeq!==void 0){let J=(0,_5.headers)();G.headers=J,J.set($5.PubHeaders.ExpectedLastSubjectSequenceHdr,`${X.previousSeq}`)}if(Q)(G.headers||(0,_5.headers)()).set($5.PubHeaders.MessageTTL,Q);try{return(await this.js.publish(this.subjectForKey(Y,!0),Z,G)).seq}catch(J){return Promise.reject(J)}}put($,Z,X={}){return this._put($,Z,X)}async get($,Z){let X=this.encodeKey($);this.validateKey(X);let Q={last_by_subj:this.subjectForKey(X)};if(Z&&Z.revision>0)Q={seq:Z.revision};let Y=null;try{if(this.direct)Y=await this.jsm.direct.getMessage(this.bucketName(),Q);else Y=await this.jsm.streams.getMessage(this.bucketName(),Q);if(Y===null)return null;let G=this.smToEntry(Y);if(G.rawKey!==X)return null;return G}catch(G){throw G}}purge($,Z){return this._deleteOrPurge($,"PURGE",Z)}delete($,Z){return this._deleteOrPurge($,"DEL",Z)}async purgeDeletes($=1800000){let Z=[],X=await this.history({key:">"});await(async()=>{for await(let J of X)if(J.operation==="DEL"||J.operation==="PURGE")Z.push(J)})().then(),X.stop();let Q=Date.now()-$,Y=Z.map((J)=>{let W=this.subjectForKey(J.key);if(J.created.getTime()>=Q)return this.jsm.streams.purge(this.stream,{filter:W,keep:1});else return this.jsm.streams.purge(this.stream,{filter:W,keep:0})}),G=await Promise.all(Y);return G.unshift({success:!0,purged:0}),G.reduce((J,W)=>{return J.purged+=W.purged,J})}async _deleteOrPurge($,Z,X){if(!this.hasWildcards($))return this._doDeleteOrPurge($,Z,X);let Q=await this.keys($),Y=[];for await(let G of Q)if(Y.push(this._doDeleteOrPurge(G,Z)),Y.length===100)await Promise.all(Y),Y.length=0;if(Y.length>0)await Promise.all(Y)}async _doDeleteOrPurge($,Z,X){let Q=this.encodeKey($);this.validateKey(Q);let Y=(0,_5.headers)();if(Y.set(wo1.kvOperationHdr,Z),Z==="PURGE"){let G=X;if(Y.set($5.JsHeaders.RollupHdr,$5.JsHeaders.RollupValueSubject),typeof G?.ttl==="string"&&G.ttl!=="")Y.set($5.PubHeaders.MessageTTL,`${G.ttl}`)}if(X?.previousSeq)Y.set($5.PubHeaders.ExpectedLastSubjectSequenceHdr,`${X.previousSeq}`);await this.js.publish(this.subjectForKey(Q,!0),_5.Empty,{headers:Y})}_buildCC($,Z,X={}){let Y=(!Array.isArray($)?[$]:$).map((W)=>{let K=this.encodeKey(W);return this.validateSearchKey(W),this.fullKeyName(K)}),G=$5.DeliverPolicy.LastPerSubject;if(Z===C5.KvWatchInclude.AllHistory)G=$5.DeliverPolicy.All;if(Z===C5.KvWatchInclude.UpdatesOnly)G=$5.DeliverPolicy.New;let J=void 0;if(Y.length===1)J=Y[0],Y=void 0;return Object.assign({deliver_policy:G,ack_policy:$5.AckPolicy.None,filter_subjects:Y,filter_subject:J,flow_control:!0,idle_heartbeat:(0,_5.nanos)(5000)},X)}remove($){return this.purge($)}async history($={}){let Z=$.key??">",X={};X.headers_only=$.headers_only||!1;let Q=new _5.QueuedIteratorImpl,Y=()=>{Q.stop()},G=this._buildCC(Z,C5.KvWatchInclude.AllHistory,X),J=await this.js.consumers.getPushConsumer(this.stream,G);if(Q._data=J,(await J.info(!0)).num_pending===0)return Q.push(Y),Q;let K=await J.consume({callback:(H)=>{let F=this.jmToWatchEntry(H,!1);if(Q.push(F),Q.received++,H.info.pending===0)Q.push(Y)}});return K.closed().then(()=>{Q.push(Y)}),(async()=>{for await(let H of K.status())switch(H.type){case"heartbeat":Q.push(()=>{Q.stop()});break}})().then(),Q.iterClosed.then(()=>{K.stop()}),Q}canSetWatcherName(){let $=this.js.nc,{ok:Z}=$.features.get(_5.Feature.JS_NEW_CONSUMER_CREATE_API);return Z}async watch($={}){let Z=$.key??">",X=new _5.QueuedIteratorImpl,Q={};Q.headers_only=$.headers_only||!1;let Y=C5.KvWatchInclude.LastValue;if($.include===C5.KvWatchInclude.AllHistory)Y=C5.KvWatchInclude.AllHistory;else if($.include===C5.KvWatchInclude.UpdatesOnly)Y=C5.KvWatchInclude.UpdatesOnly;let G=$.ignoreDeletes===!0,J=this._buildCC(Z,Y,Q);if(J.name=`KV_WATCHER_${_5.nuid.next()}`,$.resumeFromRevision&&$.resumeFromRevision>0)J.deliver_policy=$5.DeliverPolicy.StartSequence,J.opt_start_seq=$.resumeFromRevision;let W=await this.js.consumers.getPushConsumer(this.stream,J),H=(await W.info(!0)).num_pending,F=Y===C5.KvWatchInclude.UpdatesOnly||H===0;X._data=W;let N=0,U=await W.consume({callback:(O)=>{if(!F)N++,F=N>=H;let B=this.jmToWatchEntry(O,F);if(G&&B.operation==="DEL")return;X.push(B),X.received++}});return X.iterClosed.then(()=>{U.stop()}),U.closed().then(()=>{X.push(()=>{X.stop()})}),X}async keys($=">"){let Z=new _5.QueuedIteratorImpl,X=this._buildCC($,C5.KvWatchInclude.LastValue,{headers_only:!0}),Q=await this.js.consumers.getPushConsumer(this.stream,X);if((await Q.info()).num_pending===0)return Z.stop(),Z;Z._data=Q;let G=await Q.consume({callback:(J)=>{let W=J.headers?.get(wo1.kvOperationHdr);if(W!=="DEL"&&W!=="PURGE"){let K=this.decodeKey(J.subject.substring(this.prefixLen));Z.push(K)}if(J.info.pending===0)G.stop()}});return(async()=>{for await(let J of G.status())switch(J.type){case"heartbeat":Z.push(()=>{Z.stop()});break}})().then(),G.closed().then(()=>{Z.push(()=>{Z.stop()})}),Z.iterClosed.then(()=>{G.stop()}),Z}purgeBucket($){return this.jsm.streams.purge(this.bucketName(),$)}destroy(){return this.jsm.streams.delete(this.bucketName())}async status(){let Z=this.js.nc.info?.cluster??"",X=this.bucketName(),Q=await this.jsm.streams.info(X);return new L50(Q,Z)}}wo1.Bucket=Ox;class L50{si;cluster;constructor($,Z=""){this.si=$,this.cluster=Z}get bucket(){return this.si.config.name.startsWith(C5.kvPrefix)?this.si.config.name.substring(C5.kvPrefix.length):this.si.config.name}get values(){return this.si.state.messages}get history(){return this.si.config.max_msgs_per_subject}get ttl(){return(0,_5.millis)(this.si.config.max_age)}get markerTTL(){if(typeof this.si.config.subject_delete_marker_ttl==="number")return(0,_5.millis)(this.si.config.subject_delete_marker_ttl);return 0}get bucket_location(){return this.cluster}get backingStore(){return this.si.config.storage}get storage(){return this.si.config.storage}get replicas(){return this.si.config.num_replicas}get description(){return this.si.config.description??""}get maxBucketSize(){return this.si.config.max_bytes}get maxValueSize(){return this.si.config.max_msg_size}get max_bytes(){return this.si.config.max_bytes}get placement(){return this.si.config.placement||{cluster:"",tags:[]}}get placementCluster(){return this.si.config.placement?.cluster??""}get republish(){return this.si.config.republish??{src:"",dest:""}}get streamInfo(){return this.si}get size(){return this.si.state.bytes}get metadata(){return this.si.config.metadata??{}}get compression(){if(this.si.config.compression)return this.si.config.compression!==$5.StoreCompression.None;return!1}}wo1.KvStatusImpl=L50;class Oo1{bucket;sm;prefixLen;codec;constructor($,Z,X,Q){this.bucket=$,this.prefixLen=Z,this.sm=X,this.codec=Q}get rawKey(){return this.sm.subject.substring(this.prefixLen)}get key(){return this.codec.key.decode(this.rawKey)}get value(){return this.codec.value.decode(this.sm.data)}get delta(){return 0}get created(){return this.sm.time}get revision(){return this.sm.seq}get operation(){if(this.sm.header?.has("Nats-Marker-Reason")){if(this.sm.header?.get("Nats-Marker-Reason")==="MaxAge")return"PURGE"}return this.sm.header?.get(wo1.kvOperationHdr)||"PUT"}get length(){let $=this.sm.header.get($5.JsHeaders.MessageSizeHdr)||"";if($!=="")return parseInt($,10);return this.sm.data.length}json($){return JSON.parse(_5.TD.decode(this.value),$)}string(){return _5.TD.decode(this.value)}}class Bo1{bucket;sm;prefixLen;update;codec;constructor($,Z,X,Q,Y){this.bucket=$,this.prefixLen=Z,this.sm=X,this.update=Q,this.codec=Y}get rawKey(){return this.sm.subject.substring(this.prefixLen)}get key(){return this.codec.key.decode(this.rawKey)}get value(){return this.codec.value.decode(this.sm.data)}get created(){return new Date((0,_5.millis)(this.sm.info.timestampNanos))}get revision(){return this.sm.seq}get operation(){if(this.sm.headers?.has("Nats-Marker-Reason")){if(this.sm.headers?.get("Nats-Marker-Reason")==="MaxAge")return"PURGE"}return this.sm.headers?.get(wo1.kvOperationHdr)||"PUT"}get delta(){return this.sm.info.pending}get length(){let $=this.sm.headers?.get($5.JsHeaders.MessageSizeHdr)||"";if($!=="")return parseInt($,10);return this.sm.data.length}get isUpdate(){return this.update}json($){return JSON.parse(_5.TD.decode(this.value),$)}string(){return _5.TD.decode(this.value)}}});var bu0=_((N3)=>{Object.defineProperty(N3,"__esModule",{value:!0});N3.validateKey=N3.validateBucket=N3.NoopKvCodecs=N3.Kvm=N3.defaultBucketOpts=N3.Bucket=N3.Base64KeyCodec=N3.KvWatchInclude=N3.kvPrefix=void 0;var Eo1=vu0();Object.defineProperty(N3,"kvPrefix",{enumerable:!0,get:function(){return Eo1.kvPrefix}});Object.defineProperty(N3,"KvWatchInclude",{enumerable:!0,get:function(){return Eo1.KvWatchInclude}});var fL=Lo1();Object.defineProperty(N3,"Base64KeyCodec",{enumerable:!0,get:function(){return fL.Base64KeyCodec}});Object.defineProperty(N3,"Bucket",{enumerable:!0,get:function(){return fL.Bucket}});Object.defineProperty(N3,"defaultBucketOpts",{enumerable:!0,get:function(){return fL.defaultBucketOpts}});Object.defineProperty(N3,"Kvm",{enumerable:!0,get:function(){return fL.Kvm}});Object.defineProperty(N3,"NoopKvCodecs",{enumerable:!0,get:function(){return fL.NoopKvCodecs}});Object.defineProperty(N3,"validateBucket",{enumerable:!0,get:function(){return fL.validateBucket}});Object.defineProperty(N3,"validateKey",{enumerable:!0,get:function(){return fL.validateKey}})});var xu0=_((AO)=>{Object.defineProperty(AO,"__esModule",{value:!0});AO.NoopKvCodecs=AO.Kvm=AO.defaultBucketOpts=AO.Bucket=AO.Base64KeyCodec=AO.KvWatchInclude=void 0;var Kn8=bu0();Object.defineProperty(AO,"KvWatchInclude",{enumerable:!0,get:function(){return Kn8.KvWatchInclude}});var am=bu0();Object.defineProperty(AO,"Base64KeyCodec",{enumerable:!0,get:function(){return am.Base64KeyCodec}});Object.defineProperty(AO,"Bucket",{enumerable:!0,get:function(){return am.Bucket}});Object.defineProperty(AO,"defaultBucketOpts",{enumerable:!0,get:function(){return am.defaultBucketOpts}});Object.defineProperty(AO,"Kvm",{enumerable:!0,get:function(){return am.Kvm}});Object.defineProperty(AO,"NoopKvCodecs",{enumerable:!0,get:function(){return am.NoopKvCodecs}})});function E50(){let $=new TextEncoder,Z=new TextDecoder;return{encode:(X)=>$.encode(JSON.stringify(X)),decode:(X)=>JSON.parse(Z.decode(X))}}class gu0{options;kv=null;codec=E50();constructor($){this.options=$}async init(){let $=this.options.getJetStream();if(!$)return;this.kv=await new zo1.Kvm($).create(Fn8,{storage:jo1.StorageType.Memory})}async get($,Z){if(!this.kv)return null;try{let X=await this.kv.get(`${$}.${Z}`);if(!X?.value?.length)return null;if(X.operation==="DEL"||X.operation==="PURGE")return null;return this.codec.decode(X.value)}catch{return null}}async set($,Z,X){if(!this.kv)return;try{await this.kv.put(`${$}.${Z}`,this.codec.encode(X))}catch{}}async invalidate($){if(!this.kv)return;await Promise.all(["tools","resources","prompts"].map(async(X)=>{try{await this.kv.delete(`${X}.${$}`)}catch{}}))}teardown(){this.kv=null}}function Nn8($,Z,X){if(X<=0)return!0;if($===void 0)return!0;return Z-$>=X}function j50($){return $ instanceof D1&&$.code===I1.MethodNotFound}function Un8($){return $ instanceof D1&&$.code===-32000&&/connection closed/i.test($.message)}async function RO($,Z,X,Q,Y,G=0){if(!Q)try{return await X()}catch(H){if(j50(H))return[];return sm.add(1,{type:$,outcome:"error",stage:"no_cache"}),null}let J=`${$}:${Z}`,W=await Q.get($,Z);if(W===null)try{let H=await X();return Q.set($,Z,H).catch(()=>{}),yu0.set(J,Date.now()),sm.add(1,{type:$,outcome:"miss",stage:"miss"}),H}catch(H){if(j50(H))return Q.set($,Z,[]).catch(()=>{}),[];return sm.add(1,{type:$,outcome:"error",stage:"miss"}),null}if(sm.add(1,{type:$,outcome:"hit",stage:"hit"}),Nn8(yu0.get(J),Date.now(),G)&&!z50.has(J)){z50.add(J),yu0.set(J,Date.now());let H=X().then((F)=>Q.set($,Z,F)).catch((F)=>{if(j50(F)||Un8(F)){if(j50(F))Q.set($,Z,[]).catch(()=>{});return}sm.add(1,{type:$,outcome:"error",stage:"revalidation"})}).finally(()=>z50.delete(J));Y?.(H)}return W}function hu0($){Po1=$}function s5(){return Po1}var jo1,zo1,sm,Fn8="DECOCMS_MCP_LISTS",z50,yu0,TO=30000,Po1=null;var VY=w(()=>{r5();f6();jo1=V(bw(),1),zo1=V(xu0(),1),sm=S$.createCounter("mcp_list_cache.fetches",{description:"MCP list cache fetch outcomes (hit, miss, error)",unit:"{fetches}"});z50=new Set;S$.createObservableGauge("mcp_list_cache.pending_revalidations",{description:"In-flight background MCP list revalidations on this pod",unit:"{revalidations}"}).addCallback(($)=>$.observe(z50.size));yu0=new Map});async function uu0($,Z,X){let Q=new AbortController,Y,G=new Promise((W,K)=>{Y=setTimeout(()=>{Q.abort(),K(new Ao1($.id,X))},X)}),J=(async()=>{let W=await F5($,Z,!0);try{return(await W.listTools(void 0,{timeout:X,signal:Q.signal})).tools}finally{await W.close().catch(()=>{})}})();J.catch(()=>{});try{return await Promise.race([J,G])}finally{if(Y)clearTimeout(Y)}}var Ao1;var To1=w(()=>{em();Ao1=class Ao1 extends Error{constructor($,Z){super(`listTools timed out after ${Z}ms for connection ${$}`);this.name="ListToolsTimeoutError"}}});function P50($){return(Z)=>{if(Z instanceof D1&&Z.code===I1.MethodNotFound)return $;throw Z}}var Ro1=w(()=>{r5()});function A50($,Z,X){let Q=IO($,Z,X,s5()??void 0),Y=gD(Q,{name:"studio-mcp-server",version:"1.0.0"},{capabilities:On8,toolCallTimeoutMs:pf});Y.server.setRequestHandler(jU,async()=>{return await Q.listResources().catch(P50({resources:[]}))}),Y.server.setRequestHandler(zU,async()=>{return await Q.listResourceTemplates().catch(P50({resourceTemplates:[]}))}),Y.server.setRequestHandler(PU,async()=>{return await Q.listPrompts().catch(P50({prompts:[]}))});let G=Y.close.bind(Y);return Y.close=async()=>{await G(),await Q.close().catch(()=>{})},Y}var On8;var Io1=w(()=>{_X();r5();$i();VY();Ro1();On8={tools:{},resources:{},prompts:{}}});var HF=w(()=>{em();To1();Io1()});function Zi($,Z,X){if(Z.some((Q)=>Q!=="*"&&Q.startsWith("SELF::"))&&$.SELF===void 0)$.SELF={value:`${X}_self`}}function Xi($,Z){let X=new Map;for(let Q of Z){if(Q==="*")continue;let[Y,G]=O60(Q);if(!Bn8.has(G))continue;let J=Lm(Y,$);if(typeof J!=="object"||J===null||!("value"in J))continue;let W=J.value;if(typeof W!=="string")continue;X.set(`${W}:${G}`,{targetConnectionId:W,scope:G})}return[...X.values()]}async function Qi($,Z,X,Q){for(let G of Z){if(G==="*")continue;let[J]=O60(G),W=Lm(J,$);if(W===void 0||W===null)throw Error(`Scope references key "${J}" but it's not present in state`)}let Y=ql1($,Z);for(let G of Y){if(G.endsWith("_self"))continue;let J=await Q.storage.connections.findById(G);if(!J||J.organization_id!==X)throw Error(`Referenced connection not found: ${G}`);try{await Q.access.check(G)}catch(W){throw Error(`Access denied to referenced connection: ${G}. ${W.message}`)}}}var Bn8;var cu0=w(()=>{dg0();t80();Bn8=new Set([p80,n80])});import{z as qo1}from"zod";var wn8,Dn8,lu0;var Mo1=w(()=>{M4();C0();T$();VY();HF();cu0();pm();VW();wn8=qo1.object({data:F$0.describe("Data for the new connection (id is auto-generated if not provided)")}),Dn8=qo1.object({item:b7.describe("The created connection entity")}),lu0=c({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection. Auto-fetches and caches the server's tool list.",annotations:{title:"Create Connection",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:wn8,outputSchema:Dn8,handler:async($,Z)=>{r(Z);let X=t(Z);await Z.access.check();let Q=G1(Z);if(!Q)throw Error("User ID required to create connection");let Y={...$.data,organization_id:X.id,created_by:Q};if(Y.id){if((await Z.storage.connections.findById(Y.id))?.organization_id===X.id)throw Error("Connection already exists in organization")}if(Y.connection_type==="VIRTUAL"){let N=Ff(Y.connection_url);if(!N)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let U=await Z.storage.virtualMcps.findById(N);if(!U)throw Error(`Virtual MCP not found: ${N}`);if(U.organization_id!==X.id)throw Error("Virtual MCP does not belong to the current organization");Y.connection_url=Nf(N)}if(Y.connection_type==="STDIO"&&!b0().localMode)throw Error("STDIO connections are only available in local mode (--local-mode).");let G=await jO({id:`pending-${Date.now()}`,title:Y.title,connection_type:Y.connection_type,connection_url:Y.connection_url,connection_token:Y.connection_token,connection_headers:Y.connection_headers}).catch(()=>null),J=G?.tools?.length?G.tools:null,W=G?.scopes?.length?G.scopes:Y.configuration_scopes??null,K=Y.configuration_state??null;if(K&&W?.length)Zi(K,W,X.id),await Qi(K,W,X.id,Z);let H=await Z.storage.connections.createNew({...Y,tools:null,configuration_state:K,configuration_scopes:W}),F=K&&W?.length?Xi(K,W):[];if(F.length>0){let N;try{await Z.storage.connectionCredentialVault.replaceGrantsForSubject({organizationId:X.id,subjectConnectionId:H.id,createdBy:Q,grants:F});let{plaintextToken:U,record:O}=await Z.storage.connectionCredentialVault.createOrRotateWorkloadToken({organizationId:X.id,subjectConnectionId:H.id});N=O.id,await(await F5(H,Z,!1)).callTool({name:"ON_MCP_CONFIGURATION",arguments:{state:K,scopes:W,firstRun:!0,vault:{baseUrl:Z.baseUrl,org:X.slug??X.id,subjectConnectionId:H.id,token:U}}})}catch(U){if(N)await Z.storage.connectionCredentialVault.revokeWorkloadToken({organizationId:X.id,subjectConnectionId:H.id,tokenId:N});throw await Z.storage.connections.delete(H.id),U}}if(J)s5()?.set("tools",H.id,J).catch(()=>{});return y1.capture({distinctId:Q,event:"connection_created",groups:{organization:X.id},properties:{connection_id:H.id,connection_type:H.connection_type,app_name:H.app_name??null,organization_id:X.id,tools_count:J?.length??0}}),{item:H}}})});import{z as fG}from"zod/v4";import{z as ko1}from"zod/v4";import{z as T50}from"zod/v4";import{z as sW}from"zod/v4";import{z as zn8}from"zod/v4";import{z as bL}from"zod/v4";import{z as eW}from"zod/v4";import{z as CZ}from"zod/v4";import{z as Vo1}from"zod/v4";import{z as q50}from"zod/v4";import{z as dn8}from"zod/v4";import{z as So1}from"zod/v4";import{z as R50}from"zod/v4";import{z as sn8}from"zod/v4";function Yi($,Z){if($===Z)return!0;if($==null||Z==null)return $===Z;if(typeof $!==typeof Z)return!1;if(Array.isArray($)&&Array.isArray(Z)){if($.length!==Z.length)return!1;return $.every((X,Q)=>Yi(X,Z[Q]))}if(typeof $==="object"&&typeof Z==="object"){let X=Object.keys($),Q=Object.keys(Z);if(X.length!==Q.length)return!1;return X.every((Y)=>Q.includes(Y)&&Yi($[Y],Z[Y]))}return!1}function un8(){return($)=>{if(!Array.isArray($))return!0;let Z=[];return $.every((X)=>{if(Z.some((Y)=>Yi(X,Y)))return!1;return Z.push(X),!0})}}function I50($,Z){return $.safeParse(Z).success}function H7($){if(typeof $==="boolean")return $?fG.any():fG.never();let Z={};for(let Y of Xt8)Y.apply(Z,$);let X=[];if(Z.string!==!1)X.push(Z.string||fG.string());if(Z.number!==!1)X.push(Z.number||fG.number());if(Z.boolean!==!1)X.push(Z.boolean||fG.boolean());if(Z.null!==!1)X.push(Z.null||fG.null());if(Z.array!==!1)X.push(Z.array||fG.array(fG.any()));if(Z.tuple!==!1&&Z.tuple!==void 0)X.push(Z.tuple);if(Z.object!==!1)if(Z.object)X.push(Z.object);else{let Y=fG.custom((G)=>{return typeof G==="object"&&G!==null&&!Array.isArray(G)},"Must be an object, not an array");X.push(Y)}if(Z.file!==!1&&Z.file!==void 0)X.push(Z.file);let Q;if(X.length===0)Q=fG.never();else if(X.length===1)Q=X[0];else if(!Object.keys($).some((G)=>G!=="$schema"&&G!=="title"&&G!=="description"))Q=fG.any();else Q=fG.union(X);for(let Y of Qt8)Q=Y.apply(Q,$);return Q}var Ln8=class{apply($,Z){if(!Z.type)return;let X=Array.isArray(Z.type)?Z.type:[Z.type],Q=new Set(X);if(!Q.has("string"))$.string=!1;if(!Q.has("number")&&!Q.has("integer"))$.number=!1;if(!Q.has("boolean"))$.boolean=!1;if(!Q.has("null"))$.null=!1;if(!Q.has("array"))$.array=!1;if(!Q.has("object"))$.object=!1;if(Q.has("integer")&&$.number!==!1){let Y=$.number||ko1.number();if(Y instanceof ko1.ZodNumber)$.number=Y.int()}}},En8=class{apply($,Z){if(Z.const===void 0)return;let X=Z.const;if($.string=!1,$.number=!1,$.boolean=!1,$.null=!1,$.array=!1,$.object=!1,typeof X==="string")$.string=T50.literal(X);else if(typeof X==="number")$.number=T50.literal(X);else if(typeof X==="boolean")$.boolean=T50.literal(X);else if(X===null)$.null=T50.null();else if(Array.isArray(X))$.array=void 0;else if(typeof X==="object")$.object=void 0}},jn8=class{apply($,Z){if(!Z.enum)return;if(Z.enum.length===0){if(!Z.type)$.string=!1,$.number=!1,$.boolean=!1,$.null=!1,$.array=!1,$.object=!1;return}let X={string:Z.enum.filter((Q)=>typeof Q==="string"),number:Z.enum.filter((Q)=>typeof Q==="number"),boolean:Z.enum.filter((Q)=>typeof Q==="boolean"),null:Z.enum.filter((Q)=>Q===null),array:Z.enum.filter((Q)=>Array.isArray(Q)),object:Z.enum.filter((Q)=>typeof Q==="object"&&Q!==null&&!Array.isArray(Q))};$.string=this.createTypeSchema(X.string,"string"),$.number=this.createTypeSchema(X.number,"number"),$.boolean=this.createTypeSchema(X.boolean,"boolean"),$.null=X.null.length>0?sW.null():!1,$.array=X.array.length>0?void 0:!1,$.object=X.object.length>0?void 0:!1}createTypeSchema($,Z){if($.length===0)return!1;if($.length===1)return sW.literal($[0]);if(Z==="string")return sW.enum($);if(Z==="number"){let[X,Q,...Y]=$;return sW.union([sW.literal(X),sW.literal(Q),...Y.map((G)=>sW.literal(G))])}if(Z==="boolean")return sW.union([sW.literal(!0),sW.literal(!1)]);return!1}},Pn8=class{apply($,Z){let X=Z;if(X.type==="string"&&X.format==="binary"&&X.contentEncoding==="binary"){let Q=zn8.file();if(X.minLength!==void 0)Q=Q.min(X.minLength);if(X.maxLength!==void 0)Q=Q.max(X.maxLength);if(X.contentMediaType!==void 0)Q=Q.mime(X.contentMediaType);$.file=Q,$.string=!1}}},An8=class{apply($,Z){let X=Z;if(Z.type===void 0&&(X.minLength!==void 0||X.maxLength!==void 0||X.pattern!==void 0)){if($.string===void 0)$.string=bL.string()}}},Tn8=class{apply($,Z){let X=Z;if(X.minLength===void 0)return;if($.string!==!1){let Q=$.string||bL.string();if(Q instanceof bL.ZodString)$.string=Q.refine((Y)=>{return Array.from(Y).length>=X.minLength},{message:`String must be at least ${X.minLength} characters long`})}}},Rn8=class{apply($,Z){let X=Z;if(X.maxLength===void 0)return;if($.string!==!1){let Q=$.string||bL.string();if(Q instanceof bL.ZodString)$.string=Q.refine((Y)=>{return Array.from(Y).length<=X.maxLength},{message:`String must be at most ${X.maxLength} characters long`})}}},In8=class{apply($,Z){let X=Z;if(!X.pattern)return;if($.string!==!1){let Q=$.string||bL.string();if(Q instanceof bL.ZodString){let Y=new RegExp(X.pattern);$.string=Q.regex(Y)}}}},qn8=class{apply($,Z){let X=Z;if(X.minimum===void 0)return;if($.number!==!1){let Q=$.number||eW.number();if(Q instanceof eW.ZodNumber)$.number=Q.min(X.minimum)}}},Mn8=class{apply($,Z){let X=Z;if(X.maximum===void 0)return;if($.number!==!1){let Q=$.number||eW.number();if(Q instanceof eW.ZodNumber)$.number=Q.max(X.maximum)}}},kn8=class{apply($,Z){let X=Z;if(X.exclusiveMinimum===void 0)return;if($.number!==!1){let Q=$.number||eW.number();if(Q instanceof eW.ZodNumber)if(typeof X.exclusiveMinimum==="number")$.number=Q.gt(X.exclusiveMinimum);else $.number=!1}}},Vn8=class{apply($,Z){let X=Z;if(X.exclusiveMaximum===void 0)return;if($.number!==!1){let Q=$.number||eW.number();if(Q instanceof eW.ZodNumber)if(typeof X.exclusiveMaximum==="number")$.number=Q.lt(X.exclusiveMaximum);else $.number=!1}}},Sn8=class{apply($,Z){let X=Z;if(X.multipleOf===void 0)return;if($.number!==!1){let Q=$.number||eW.number();if(Q instanceof eW.ZodNumber)$.number=Q.refine((Y)=>{if(X.multipleOf===0)return!1;let G=Y/X.multipleOf,J=Math.round(G),W=Math.min(Math.abs(Y)*Number.EPSILON*10,Math.abs(X.multipleOf)*Number.EPSILON*10);return Math.abs(G-J)<=W/Math.abs(X.multipleOf)},{message:`Must be a multiple of ${X.multipleOf}`})}}},Cn8=class{apply($,Z){let X=Z;if(Z.type===void 0&&(X.minItems!==void 0||X.maxItems!==void 0||X.items!==void 0||X.prefixItems!==void 0)){if($.array===void 0)$.array=CZ.array(CZ.any())}}},_n8=class{apply($,Z){let X=Z;if(X.minItems===void 0)return;if($.array!==!1)$.array=($.array||CZ.array(CZ.any())).min(X.minItems)}},vn8=class{apply($,Z){let X=Z;if(X.maxItems===void 0)return;if($.array!==!1)$.array=($.array||CZ.array(CZ.any())).max(X.maxItems)}},fn8=class{apply($,Z){let X=Z;if($.array===!1)return;if(Array.isArray(X.items))$.array=$.array||CZ.array(CZ.any());else if(X.items&&typeof X.items!=="boolean"&&!X.prefixItems){let Q=H7(X.items),Y=CZ.array(Q);if($.array&&$.array instanceof CZ.ZodArray){let G=$.array._def;if(G.checks)G.checks.forEach((J)=>{if(J._zod&&J._zod.def){let W=J._zod.def;if(W.check==="min_length"&&W.minimum!==void 0)Y=Y.min(W.minimum);else if(W.check==="max_length"&&W.maximum!==void 0)Y=Y.max(W.maximum)}})}$.array=Y}else if(typeof X.items==="boolean"&&X.items===!1)if(!X.prefixItems)$.array=CZ.array(CZ.any()).max(0);else $.array=$.array||CZ.array(CZ.any());else if(typeof X.items==="boolean"&&X.items===!0)$.array=$.array||CZ.array(CZ.any());else if(X.prefixItems)$.array=$.array||CZ.array(CZ.any())}},bn8=class{apply($,Z){if(Z.type!=="array")return;let X=Z;if(!Array.isArray(X.items))return;if($.array===!1)return;let Q=X.items.map((G)=>H7(G)),Y;if(Q.length===0)Y=Vo1.tuple([]);else Y=Vo1.tuple(Q);if(X.minItems!==void 0&&X.minItems>Q.length)Y=!1;if(X.maxItems!==void 0&&X.maxItems<Q.length)Y=!1;$.tuple=Y,$.array=!1}},xn8=class{apply($,Z){let X=Z;if($.object===!1)return;if(X.properties||X.required||X.additionalProperties!==void 0)$.object=$.object||q50.object({}).passthrough()}},yn8=class{apply($,Z){let X=Z;if(Z.type===void 0&&(X.maxProperties!==void 0||X.minProperties!==void 0)){if($.object===void 0)$.object=q50.object({}).passthrough()}}},gn8=class{apply($,Z){let X=Z;if(X.maxProperties===void 0)return;if($.object!==!1){let Q=$.object||q50.object({}).passthrough();$.object=Q.refine((Y)=>Object.keys(Y).length<=X.maxProperties,{message:`Object must have at most ${X.maxProperties} properties`})}}},hn8=class{apply($,Z){let X=Z;if(X.minProperties===void 0)return;if($.object!==!1){let Q=$.object||q50.object({}).passthrough();$.object=Q.refine((Y)=>Object.keys(Y).length>=X.minProperties,{message:`Object must have at least ${X.minProperties} properties`})}}},cn8=class{apply($,Z){if(!Z.not)return $;let X=H7(Z.not);return $.refine((Q)=>!I50(X,Q),{message:"Value must not match the 'not' schema"})}},ln8=class{apply($,Z){if(Z.uniqueItems!==!0)return $;return $.refine(un8(),{message:"Array items must be unique"})}},mn8=class{apply($,Z){if(!Z.allOf||Z.allOf.length===0)return $;return Z.allOf.map((Q)=>H7(Q)).reduce((Q,Y)=>dn8.intersection(Q,Y),$)}},in8=class{apply($,Z){if(!Z.anyOf||Z.anyOf.length===0)return $;let X=Z.anyOf.length===1?H7(Z.anyOf[0]):So1.union([H7(Z.anyOf[0]),H7(Z.anyOf[1]),...Z.anyOf.slice(2).map((Q)=>H7(Q))]);return So1.intersection($,X)}},pn8=class{apply($,Z){if(!Z.oneOf||Z.oneOf.length===0)return $;let X=Z.oneOf.map((Q)=>H7(Q));return $.refine((Q)=>{let Y=0;for(let G of X)if(G.safeParse(Q).success){if(Y++,Y>1)return!1}return Y===1},{message:"Value must match exactly one of the oneOf schemas"})}},nn8=class{apply($,Z){let X=Z;if(X.prefixItems&&Array.isArray(X.prefixItems)){let Y=X.prefixItems.map((G)=>H7(G));return $.refine((G)=>{if(!Array.isArray(G))return!0;for(let J=0;J<Math.min(G.length,Y.length);J++)if(!I50(Y[J],G[J]))return!1;if(G.length>Y.length){if(typeof X.items==="boolean"&&X.items===!1)return!1;else if(X.items&&typeof X.items==="object"&&!Array.isArray(X.items)){let J=H7(X.items);for(let W=Y.length;W<G.length;W++)if(!I50(J,G[W]))return!1}}return!0},{message:"Array does not match prefixItems schema"})}return $}},tn8=class{apply($,Z){let X=Z;if(!X.properties&&!X.required&&X.additionalProperties!==!1)return $;if($ instanceof R50.ZodObject||$ instanceof R50.ZodRecord){let Q={};if(X.properties){for(let[Y,G]of Object.entries(X.properties))if(G!==void 0)Q[Y]=H7(G)}if(X.required&&Array.isArray(X.required)){let Y=new Set(X.required);for(let G of Object.keys(Q))if(!Y.has(G))Q[G]=Q[G].optional()}else for(let Y of Object.keys(Q))Q[Y]=Q[Y].optional();if(X.additionalProperties===!1)return R50.object(Q);else return R50.object(Q).passthrough()}return $.refine((Q)=>{if(typeof Q!=="object"||Q===null||Array.isArray(Q))return!0;if(X.properties){for(let[Y,G]of Object.entries(X.properties))if(G!==void 0){if(Object.getOwnPropertyDescriptor(Q,Y)!==void 0){if(!H7(G).safeParse(Q[Y]).success)return!1}}}if(X.required&&Array.isArray(X.required)){for(let Y of X.required)if(Object.getOwnPropertyDescriptor(Q,Y)===void 0)return!1}if(X.additionalProperties===!1&&X.properties){let Y=new Set(Object.keys(X.properties));for(let G in Q)if(!Y.has(G))return!1}return!0},{message:"Object constraints validation failed"})}},on8=class{apply($,Z){if(!Z.enum||Z.enum.length===0)return $;let X=Z.enum.filter((Q)=>Array.isArray(Q)||typeof Q==="object"&&Q!==null);if(X.length===0)return $;return $.refine((Q)=>{if(typeof Q!=="object"||Q===null)return!0;return X.some((Y)=>Yi(Q,Y))},{message:"Value must match one of the enum values"})}},rn8=class{apply($,Z){if(Z.const===void 0)return $;let X=Z.const;if(typeof X!=="object"||X===null)return $;return $.refine((Q)=>Yi(Q,X),{message:"Value must equal the const value"})}},an8=class{apply($,Z){if(Z.description)$=$.describe(Z.description);return $}},en8=class{apply($,Z){var X;let Q=Z;if(!((X=Q.required)==null?void 0:X.includes("__proto__"))||Z.type!==void 0)return $;return sn8.any().refine((Y)=>this.validateRequired(Y,Q.required),{message:"Missing required properties"})}validateRequired($,Z){if(typeof $!=="object"||$===null||Array.isArray($))return!0;return Z.every((X)=>Object.prototype.hasOwnProperty.call($,X))}},$t8=class{apply($,Z){var X;let Q=Z;if(Q.contains===void 0)return $;let Y=H7(Q.contains),G=(X=Q.minContains)!=null?X:1,J=Q.maxContains;return $.refine((W)=>{if(!Array.isArray(W))return!0;let K=0;for(let H of W)if(I50(Y,H))K++;if(K<G)return!1;if(J!==void 0&&K>J)return!1;return!0},{message:"Array must contain required items matching the schema"})}},Zt8=class{apply($,Z){let{default:X}=Z;if(X===void 0)return $;if(!$.safeParse(X).success)return $;return $.default(X)}},Xt8,Qt8;var Co1=w(()=>{Xt8=[new En8,new jn8,new Ln8,new Pn8,new An8,new Cn8,new yn8,new Tn8,new Rn8,new In8,new qn8,new Mn8,new kn8,new Vn8,new Sn8,new bn8,new _n8,new vn8,new fn8,new gn8,new hn8,new xn8],Qt8=[new en8,new on8,new rn8,new mn8,new in8,new pn8,new nn8,new tn8,new $t8,new cn8,new ln8,new Zt8,new an8]});class du0{constructor($){this._url=$}start(){if(this._socket)throw Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise(($,Z)=>{this._socket=new WebSocket(this._url,Yt8),this._socket.onerror=(X)=>{let Q="error"in X?X.error:Error(`WebSocket error: ${JSON.stringify(X)}`);Z(Q),this.onerror?.(Q)},this._socket.onopen=()=>{$()},this._socket.onclose=()=>{this.onclose?.()},this._socket.onmessage=(X)=>{let Q;try{Q=zY.parse(JSON.parse(X.data))}catch(Y){this.onerror?.(Y);return}this.onmessage?.(Q)}})}async close(){this._socket?.close()}send($){return new Promise((Z,X)=>{if(!this._socket){X(Error("Not connected"));return}this._socket?.send(JSON.stringify($)),Z()})}}var Yt8="mcp";var _o1=w(()=>{r5()});function Gt8($){let Z=$;if(!Z||typeof Z!=="object"||!("method"in Z))return null;switch(Z.method){case"initialize":{let X=Z?.params?.protocolVersion;if(!X)return null;return{type:"emit",message:{result:{protocolVersion:X,capabilities:{tools:{}},serverInfo:{name:"deco-chat-server",version:"1.0.0"}},jsonrpc:Z.jsonrpc??"2.0",id:Z.id}}}case"notifications/roots/list_changed":case"notifications/initialized":case"notifications/cancelled":case"notifications/progress":return{type:"suppress"};default:return null}}var M50;var mu0=w(()=>{ff();M50=class M50 extends xW{constructor($,Z){super($,Z)}send($,Z){let X=Gt8($);if(X?.type==="emit")return this.onmessage?.(X.message),Promise.resolve();if(X?.type==="suppress")return Promise.resolve();return super.send($,Z)}}});var vo1,fo1=async($,Z,X)=>{let Q=Jt8($.connection,Z,X);if(!Q)throw Error("Unknown MCP connection type");let Y=new vo1({name:$?.name??"MCP Client",version:"1.0.0"});return await Y.connect(Q),{client:Y}},Jt8=($,Z,X)=>{if($.type==="Websocket")return new du0(new URL($.url));if($.type!=="SSE"&&$.type!=="HTTP")return null;let Y={...$.token?{authorization:`Bearer ${$.token}`}:{},...X??{},..."headers"in $?$.headers||{}:{}};if($.type==="SSE"){let G={requestInit:{headers:Y,signal:Z}};if($.token)G.eventSourceInit={fetch:(J,W)=>{return fetch(J,{...W,headers:{...Y,Accept:"text/event-stream"},signal:Z})}};return new aH(new URL($.url),G)}return new M50(new URL($.url),{requestInit:{headers:Y,signal:Z,credentials:"include"}})};var bo1=w(()=>{fW();tl();_o1();r5();_X();mu0();vo1=class vo1 extends b9{constructor($,Z){super($,{jsonSchemaValidator:H5,...Z})}async listTools($,Z){return await this.request({method:"tools/list",params:$},Hl,Z)}}});function Kt8($,Z){if(xL.set($,Z),xL.size>Wt8){let X=xL.keys().next().value;if(X!==void 0)xL.delete(X)}}function go1($){let Z=(X)=>{if("connection"in $)return fo1({connection:$.connection},void 0,X);return $.client};return new Proxy({},{get(X,Q){if(Q==="toJSON")return null;if(typeof Q!=="string")throw Error("Name must be a string");if(Q==="listTools")return W;async function Y(K,H=Q){let F=$?.debugId?.(),N=F?{"x-trace-debug-id":F}:void 0,{client:U}=await Z(N),{structuredContent:O,isError:B,content:D}=await U.callTool({name:String(H),arguments:K});if(B){let E=D?.[0]?.text,j=typeof E==="string"?xo1(E):null,z=j?.code&&typeof $?.getErrorByStatusCode==="function"?$.getErrorByStatusCode(j.code,j.message,j.traceId):null;if(z)throw z;throw Error(`Tool ${String(H)} returned an error: ${JSON.stringify(O??D)}`)}if(O!==void 0)return O;let L=D?.[0]?.text;return typeof L==="string"?xo1(L):void 0}async function G(){let{client:K}=await Z(),{tools:H}=await K.listTools();return H}async function J(){if(!("connection"in $))return G();let K=$.connection,H=JSON.stringify(K);try{if(!xL.has(H))Kt8(H,G());return await xL.get(H)}catch(F){console.error("Failed to list tools",F),xL.delete(H);return}}async function W(){return(await J()??[]).map((H)=>yo1(H,Y))}return Y.asTool=async()=>{let H=(await J()??[]).find((F)=>F.name===Q);if(!H)throw Error(`Tool ${Q} not found`);return yo1(H,Y)},Y}})}var xo1=($)=>{try{return JSON.parse($)}catch{return $}},Wt8=500,xL,yo1=($,Z)=>{return{...$,id:$.name,inputSchema:$.inputSchema?H7($.inputSchema):void 0,outputSchema:$.outputSchema?H7($.outputSchema):void 0,execute:(X)=>{return Z(X.context,$.name)}}};var ho1=w(()=>{Co1();bo1();xL=new Map});function qO($){return go1($)}var Bx;var iu0=w(()=>{ho1();Bx=new Proxy({},{get($,Z){if(Z==="toJSON")return null;if(Z==="forConnection")return(X)=>qO({connection:X});if(Z==="forClient")return(X)=>qO({client:X});return globalThis[Z]}})});function k50($){return{isImplementedBy:(Z)=>{for(let X of $){let Q=typeof X.name==="string"?new RegExp(`^${X.name}$`):X.name,Y=Z.find((G)=>Q.test(G.name));if(!Y&&X.opt)continue;if(!Y)return!1}return!0}}}var $K=($)=>{return{...k50($),forClient:(Z)=>{return qO({client:Z})},forConnection:(Z)=>{return qO({connection:Z})}}};var yL=w(()=>{iu0()});import{z as v5}from"zod";var uo1,V50,co1,S50,lo1,Ht8;var do1=w(()=>{yL();uo1=v5.object({specversion:v5.literal("1.0").describe("CloudEvents specification version"),id:v5.string().describe("Unique identifier for this event (UUID recommended)"),source:v5.string().describe("Connection ID of the event publisher"),type:v5.string().describe("Event type (e.g., 'order.created', 'user.signup')"),time:v5.string().datetime().optional().describe("Timestamp of when the event occurred (ISO 8601)"),subject:v5.string().optional().describe("Subject/resource identifier (e.g., order ID, user ID)"),datacontenttype:v5.string().optional().default("application/json").describe("Content type of the data attribute"),dataschema:v5.string().url().optional().describe("URI to the schema for the data attribute"),data:v5.unknown().optional().describe("Event payload (any JSON value)")}),V50=v5.object({events:v5.array(uo1).min(1).describe("Batch of CloudEvents to process")}),co1=v5.object({success:v5.boolean().optional().describe("Whether this event was processed successfully"),error:v5.string().optional().describe("Error message for this event"),retryAfter:v5.number().int().positive().optional().describe("Re-deliver this event after this many ms")}),S50=v5.object({success:v5.boolean().optional().describe("Batch success - applies to events not in results"),error:v5.string().optional().describe("Batch error message - applies to events not in results"),processedCount:v5.number().int().min(0).optional().describe("Number of events successfully processed"),retryAfter:v5.number().int().positive().optional().describe("Batch retryAfter - applies to events not in results"),results:v5.record(v5.string(),co1).optional().describe("Per-event results keyed by event ID")}),lo1=[{name:"ON_EVENTS",inputSchema:V50,outputSchema:S50}],Ht8=$K(lo1)});import{z as f5}from"zod";var mo1,io1,po1,no1,to1,oo1,C50,pu0;var nu0=w(()=>{yL();mo1=f5.object({type:f5.literal("string"),enum:f5.array(f5.string()).optional(),description:f5.string().optional()}),io1=f5.object({type:f5.string(),description:f5.string(),paramsSchema:f5.record(f5.string(),mo1)}),po1=f5.object({}),no1=f5.object({triggers:f5.array(io1)}),to1=f5.object({type:f5.string(),params:f5.record(f5.string(),f5.string()),enabled:f5.boolean(),callbackUrl:f5.url().optional(),callbackToken:f5.string().min(1).optional()}),oo1=f5.object({success:f5.boolean()}),C50=[{name:"TRIGGER_LIST",inputSchema:po1,outputSchema:no1},{name:"TRIGGER_CONFIGURE",inputSchema:to1,outputSchema:oo1}],pu0=$K(C50)});import{z as I$}from"zod";var Ft8,Nt8,Ut8,Ot8,Bt8,wt8,Dt8,Lt8,Et8,jt8,zt8,Pt8,gL;var Gi=w(()=>{Ft8=I$.object({prefix:I$.string().optional().describe("Filter objects by prefix (e.g., 'folder/' for folder contents)"),maxKeys:I$.number().optional().default(1000).describe("Maximum number of keys to return (default: 1000)"),continuationToken:I$.string().optional().describe("Token for pagination from previous response"),delimiter:I$.string().optional().describe("Delimiter for grouping keys (typically '/'). When set, commonPrefixes returns folder paths.")}),Nt8=I$.object({objects:I$.array(I$.object({key:I$.string().describe("Object key/path"),size:I$.number().describe("Object size in bytes"),lastModified:I$.string().describe("Last modified timestamp"),etag:I$.string().describe("Entity tag for the object")})),nextContinuationToken:I$.string().optional().describe("Token for fetching next page of results"),isTruncated:I$.boolean().describe("Whether there are more results available"),commonPrefixes:I$.array(I$.string()).optional().describe("Folder paths when delimiter is used (e.g., ['photos/2024/', 'photos/2025/'])")}),Ut8=I$.object({key:I$.string().describe("Object key/path to get metadata for")}),Ot8=I$.object({contentType:I$.string().optional().describe("MIME type of the object"),contentLength:I$.number().describe("Size of the object in bytes"),lastModified:I$.string().describe("Last modified timestamp"),etag:I$.string().describe("Entity tag for the object"),metadata:I$.record(I$.string(),I$.string()).optional().describe("Custom metadata key-value pairs")}),Bt8=I$.object({key:I$.string().describe("Object key/path to generate URL for"),expiresIn:I$.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)")}),wt8=I$.object({url:I$.string().describe("Presigned URL for downloading the object"),expiresIn:I$.number().describe("Expiration time in seconds that was used")}),Dt8=I$.object({key:I$.string().describe("Object key/path for the upload"),expiresIn:I$.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)"),contentType:I$.string().optional().describe("MIME type for the object being uploaded")}),Lt8=I$.object({url:I$.string().describe("Presigned URL for uploading the object"),expiresIn:I$.number().describe("Expiration time in seconds that was used")}),Et8=I$.object({key:I$.string().describe("Object key/path to delete")}),jt8=I$.object({success:I$.boolean().describe("Whether the deletion was successful"),key:I$.string().describe("The key that was deleted")}),zt8=I$.object({keys:I$.array(I$.string()).max(1000).describe("Array of object keys/paths to delete (max 1000)")}),Pt8=I$.object({deleted:I$.array(I$.string()).describe("Array of successfully deleted keys"),errors:I$.array(I$.object({key:I$.string(),message:I$.string()})).describe("Array of errors for failed deletions")}),gL=[{name:"LIST_OBJECTS",inputSchema:Ft8,outputSchema:Nt8},{name:"GET_OBJECT_METADATA",inputSchema:Ut8,outputSchema:Ot8},{name:"GET_PRESIGNED_URL",inputSchema:Bt8,outputSchema:wt8},{name:"PUT_PRESIGNED_URL",inputSchema:Dt8,outputSchema:Lt8},{name:"DELETE_OBJECT",inputSchema:Et8,outputSchema:jt8},{name:"DELETE_OBJECTS",inputSchema:zt8,outputSchema:Pt8}]});import{z as D6}from"zod";var ro1,ao1,so1,Ji,_50,v50,f50,b50,At8;var tu0=w(()=>{yL();ro1=D6.object({primary:D6.string().optional().describe("Primary brand color (hex)"),secondary:D6.string().optional().describe("Secondary brand color (hex)"),accent:D6.string().optional().describe("Accent / highlight color (hex)"),background:D6.string().optional().describe("Background color (hex)"),foreground:D6.string().optional().describe("Foreground / text color (hex)")}),ao1=D6.object({heading:D6.string().optional().describe("Font family for headings"),body:D6.string().optional().describe("Font family for body text"),code:D6.string().optional().describe("Font family for code / monospace")}),so1=D6.object({logo:D6.string().optional().describe("Logo URL"),favicon:D6.string().optional().describe("Favicon URL"),ogImage:D6.string().optional().describe("Open Graph image URL")}),Ji=D6.object({id:D6.string(),name:D6.string().describe("Brand / company name"),domain:D6.string().optional().describe("Company domain (e.g. example.com)"),colors:ro1.optional().describe("Semantic color palette"),fonts:ao1.optional().describe("Font families by role"),assets:so1.optional().describe("Visual identity assets"),overview:D6.string().optional().describe("Company overview / description"),tagline:D6.string().optional().describe("Brand tagline"),tone:D6.string().optional().describe("Tone of voice description"),metadata:D6.record(D6.string(),D6.unknown()).optional().describe("Extra design tokens and metadata")}),_50=D6.object({id:D6.string().optional().describe("Brand ID. Omit to get the default brand.")}),v50=D6.object({}),f50=D6.object({items:D6.array(Ji)}),b50=[{name:"BRAND_GET",inputSchema:_50,outputSchema:Ji},{name:"BRAND_LIST",inputSchema:v50,outputSchema:f50,opt:!0}],At8=$K(b50)});var ou0=w(()=>{yL();do1();nu0();Gi();tu0()});import{z as D8}from"zod";function FF($){return D8.object({items:D8.array($).describe("Array of collection items"),totalCount:D8.number().int().min(0).optional().describe("Total number of matching items (if available)"),hasMore:D8.boolean().optional().describe("Whether there are more items available")})}function Ki($){return D8.object({item:$.nullable().describe("The retrieved item, or null if not found")})}function It8($){return D8.object({data:$.partial().describe("Data for the new entity (id may be auto-generated)")})}function qt8($){return D8.object({item:$.describe("The created entity with generated id")})}function Mt8($){return D8.object({id:D8.string().describe("ID of the entity to update"),data:$.partial().describe("Partial entity data to update")})}function kt8($){return D8.object({item:$.describe("The updated entity")})}function Fi($){return D8.object({item:$.describe("The deleted entity")})}function y50($,Z,X){let Q=$.toUpperCase(),Y=X?.readOnly??!1,G=[{name:`COLLECTION_${Q}_LIST`,inputSchema:U3,outputSchema:FF(Z)},{name:`COLLECTION_${Q}_GET`,inputSchema:Wi,outputSchema:Ki(Z)}];if(!Y)G.push({name:`COLLECTION_${Q}_CREATE`,inputSchema:It8(Z),outputSchema:qt8(Z),opt:!0},{name:`COLLECTION_${Q}_UPDATE`,inputSchema:Mt8(Z),outputSchema:kt8(Z),opt:!0},{name:`COLLECTION_${Q}_DELETE`,inputSchema:Hi,outputSchema:Fi(Z),opt:!0});return G}var x50,Tt8,eo1,Rt8,U3,Wi,Hi;var bG=w(()=>{x50=D8.object({id:D8.string().describe("Unique identifier for the entity"),title:D8.string().describe("Human-readable title for the entity"),description:D8.string().nullish().describe("Description of the entity"),created_at:D8.string().datetime(),updated_at:D8.string().datetime(),created_by:D8.string().optional(),updated_by:D8.string().optional()}),Tt8=D8.object({field:D8.array(D8.string()),operator:D8.enum(["eq","gt","gte","lt","lte","in","like","contains"]),value:D8.unknown()}),eo1=D8.lazy(()=>D8.union([Tt8,D8.object({operator:D8.enum(["and","or","not"]),conditions:D8.array(eo1)})])),Rt8=D8.object({field:D8.array(D8.string()),direction:D8.enum(["asc","desc"]),nulls:D8.enum(["first","last"]).optional()}),U3=D8.object({where:eo1.optional().describe("Filter expression"),orderBy:D8.array(Rt8).optional().describe("Sort expressions"),limit:D8.number().int().min(1).max(1000).optional().describe("Maximum number of items to return"),offset:D8.number().int().min(0).optional().describe("Number of items to skip")});Wi=D8.object({id:D8.string().describe("ID of the entity to retrieve")});Hi=D8.object({id:D8.string().describe("ID of the entity to delete")})});import{z as wx}from"zod";var Vt8,St8,$r1;var Zr1=w(()=>{bG();Vt8=x50.extend({avatar:wx.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:wx.string().describe("System prompt that defines the assistant's behavior"),virtual_mcp_id:wx.string().describe("Virtual MCP ID to use for this assistant"),model:wx.object({id:wx.string().describe("Model ID"),connectionId:wx.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),St8=y50("assistant",Vt8),$r1=[...St8]});import{z as H0}from"zod";var Ni,NF,Qr1,Ct8,_t8,Yr1,vt8,ft8,bt8,xt8,yt8,gt8,Gr1,ht8,ut8,ct8,lt8,dt8,mt8,it8,pt8,nt8,tt8,Q45,ot8,Y45,Xr1,rt8,at8,g50,G45;var Jr1=w(()=>{yL();bG();Ni=H0.lazy(()=>H0.union([H0.null(),H0.string(),H0.number(),H0.boolean(),H0.record(H0.string(),Ni),H0.array(Ni)])),NF=H0.record(H0.string(),H0.record(H0.string(),Ni)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),Qr1=H0.object({type:H0.literal("text"),text:H0.string().describe("The text content"),providerOptions:NF}),Ct8=H0.object({type:H0.literal("text"),text:H0.string().describe("The text content"),providerMetadata:H0.any().optional().describe("Additional provider-specific metadata")}),_t8=H0.string().describe("File data as URL string"),Yr1=H0.object({type:H0.literal("file"),filename:H0.string().optional().describe("Optional filename of the file"),data:_t8,mediaType:H0.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:NF}),vt8=H0.object({type:H0.literal("file"),mediaType:H0.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),data:H0.string().describe("Generated file data as base64 encoded string")}),ft8=H0.object({type:H0.literal("reasoning"),text:H0.string().describe("The reasoning text"),providerOptions:NF}),bt8=H0.object({type:H0.literal("reasoning"),text:H0.string().describe("The reasoning text"),providerMetadata:H0.any().optional().describe("Additional provider-specific metadata")}),xt8=H0.object({type:H0.literal("tool-call"),toolCallId:H0.string().describe("ID of the tool call, used to match with tool result"),toolName:H0.string().describe("Name of the tool being called"),input:H0.string().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:H0.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:NF}),yt8=H0.object({type:H0.literal("tool-call"),toolCallId:H0.string().describe("ID of the tool call"),toolName:H0.string().describe("Name of the tool being called"),input:H0.string().describe("Stringified JSON object with the tool call arguments"),providerExecuted:H0.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerMetadata:H0.any().optional().describe("Additional provider-specific metadata")}),gt8=H0.union([H0.object({type:H0.literal("text"),value:H0.string()}),H0.object({type:H0.literal("json"),value:Ni}),H0.object({type:H0.literal("error-text"),value:H0.string()}),H0.object({type:H0.literal("error-json"),value:Ni}),H0.object({type:H0.literal("content"),value:H0.array(H0.union([H0.object({type:H0.literal("text"),text:H0.string().describe("Text content")}),H0.object({type:H0.literal("media"),data:H0.string().describe("Base-64 encoded media data"),mediaType:H0.string().describe("IANA media type")})]))}),H0.object({type:H0.literal("execution-denied"),reason:H0.string().optional()}),H0.string().describe("Raw or JSON-serialized output (e.g. from AI SDK mapToolResultOutput)")]),Gr1=H0.object({type:H0.literal("tool-result"),toolCallId:H0.string().describe("ID of the tool call that this result is associated with"),toolName:H0.string().describe("Name of the tool that generated this result"),output:gt8.describe("Result of the tool call"),result:H0.unknown().describe("Unknown result of the tool call"),providerOptions:NF}),ht8=H0.object({type:H0.literal("tool-result"),toolCallId:H0.string().describe("ID of the tool call that this result is associated with"),toolName:H0.string().describe("Name of the tool that generated this result"),result:H0.any().describe("Result of the tool call (JSON-serializable)"),isError:H0.boolean().optional().describe("Whether the result is an error or error message"),providerExecuted:H0.boolean().optional().describe("Whether the tool result was generated by the provider"),providerMetadata:H0.any().optional().describe("Additional provider-specific metadata")}),ut8=H0.union([H0.object({type:H0.literal("source"),sourceType:H0.literal("url"),id:H0.string().describe("The ID of the source"),url:H0.string().describe("The URL of the source"),title:H0.string().optional().describe("The title of the source"),providerMetadata:H0.any().optional().describe("Additional provider-specific metadata")}),H0.object({type:H0.literal("source"),sourceType:H0.literal("document"),id:H0.string().describe("The ID of the source"),mediaType:H0.string().describe("IANA media type of the document (e.g., application/pdf)"),title:H0.string().describe("The title of the document"),filename:H0.string().optional().describe("Optional filename of the document"),providerMetadata:H0.any().optional().describe("Additional provider-specific metadata")})]),ct8=H0.object({role:H0.literal("system"),content:H0.string().describe("System message content"),providerOptions:NF}),lt8=H0.object({role:H0.literal("user"),content:H0.array(H0.union([Qr1,Yr1])).describe("User message content parts (text or file)"),providerOptions:NF}),dt8=H0.object({role:H0.literal("assistant"),content:H0.array(H0.union([Qr1,Yr1,ft8,xt8,Gr1])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:NF}),mt8=H0.object({role:H0.literal("tool"),content:H0.array(Gr1).describe("Tool message content (tool results)"),providerOptions:NF}),it8=H0.union([ct8,lt8,dt8,mt8]),pt8=H0.array(it8).describe("A list of messages forming the prompt"),nt8=H0.object({prompt:pt8.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:H0.number().optional().describe("Maximum number of tokens to generate"),temperature:H0.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:H0.number().optional().describe("Nucleus sampling parameter"),topK:H0.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:H0.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:H0.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:H0.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:H0.array(H0.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:H0.union([H0.object({type:H0.literal("text")}),H0.object({type:H0.literal("json"),schema:H0.any().optional().describe("JSON schema that the generated output should conform to"),name:H0.string().optional().describe("Name of output that should be generated"),description:H0.string().optional().describe("Description of the output that should be generated")})]).optional().describe("Response format. The output can either be text or JSON. Default is text"),tools:H0.array(H0.any()).optional().describe("The tools that are available for the model"),toolChoice:H0.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:H0.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:H0.any().optional().describe("Abort signal for cancelling the operation"),providerOptions:H0.any().optional().describe("Additional provider-specific options")}),tt8=H0.object({content:H0.array(H0.union([Ct8,vt8,bt8,yt8,ht8,ut8])).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:H0.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:H0.looseObject({inputTokens:H0.number().optional(),outputTokens:H0.number().optional(),totalTokens:H0.number().optional(),reasoningTokens:H0.number().optional()}).describe("Usage information for the language model call"),providerMetadata:H0.any().optional().describe("Additional provider-specific metadata"),request:H0.object({body:H0.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:H0.object({id:H0.string().optional().describe("ID for the generated response"),timestamp:H0.iso.datetime().optional().describe("Timestamp for the start of the generated response"),modelId:H0.string().optional().describe("The ID of the response model that was used"),headers:H0.record(H0.string(),H0.string()).optional().describe("Response headers"),body:H0.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:H0.array(H0.any()).describe("Warnings for the call, e.g. unsupported settings")}),Q45=H0.object({stream:H0.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:H0.object({body:H0.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:H0.object({headers:H0.record(H0.string(),H0.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),ot8=H0.object({supportedUrls:H0.record(H0.string(),H0.array(H0.string())).describe("Supported URL patterns by media type for the provider")}),Y45=H0.object({modelId:H0.string().describe("The ID of the model"),logo:H0.string().nullable(),description:H0.string().nullable(),capabilities:H0.array(H0.string()),limits:H0.object({contextWindow:H0.number(),maxOutputTokens:H0.number()}).nullable(),costs:H0.object({input:H0.number(),output:H0.number()}).nullable(),provider:H0.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),Xr1=H0.object({modelId:H0.string().describe("The ID of the model"),callOptions:nt8}),rt8=x50.extend({logo:H0.string().nullable(),description:H0.string().nullable(),capabilities:H0.array(H0.string()),limits:H0.object({contextWindow:H0.number(),maxOutputTokens:H0.number()}).nullable(),costs:H0.object({input:H0.number(),output:H0.number()}).nullable(),provider:H0.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),at8=y50("llm",rt8,{readOnly:!0}),g50=[{name:"LLM_METADATA",inputSchema:H0.object({modelId:H0.string().describe("The ID of the model")}),outputSchema:ot8},{name:"LLM_DO_STREAM",inputSchema:Xr1},{name:"LLM_DO_GENERATE",inputSchema:Xr1,outputSchema:tt8},...at8],G45=$K(g50)});import{z as hL}from"zod";var st8,Wr1;var Kr1=w(()=>{st8=hL.object({scopes:hL.array(hL.string()).describe("List of scopes available"),stateSchema:hL.record(hL.string(),hL.unknown()).describe("JSON Schema (draft-07) defining the state structure")}),Wr1=[{name:"MCP_CONFIGURATION",inputSchema:hL.object({}),outputSchema:st8}]});import{z as b5}from"zod";var et8,$o8,Hr1;var Fr1=w(()=>{et8=b5.object({}).strict(),$o8=b5.object({billing:b5.object({mode:b5.enum(["prepaid","postpaid"]),limitPeriod:b5.enum(["daily","weekly","monthly"]).nullable()}),limit:b5.object({total:b5.number().nullable(),remaining:b5.number().nullable(),reset:b5.string().nullable()}),usage:b5.object({total:b5.number(),daily:b5.number(),weekly:b5.number(),monthly:b5.number()}),alert:b5.object({enabled:b5.boolean(),threshold_usd:b5.number(),email:b5.string().nullable()}),connectionId:b5.string()}),Hr1=[{name:"GATEWAY_USAGE",inputSchema:et8,outputSchema:$o8},{name:"GATEWAY_SET_LIMIT",inputSchema:b5.object({}),outputSchema:b5.object({}),opt:!0},{name:"GATEWAY_SET_ALERT",inputSchema:b5.object({}),outputSchema:b5.object({}),opt:!0}]});import{z as Nr1}from"zod";function O3(){return LY()===null}function h50($,Z){return $===l4.DEV_ASSETS(Z)}function Dx($,Z){let X=fx1(Z,$),Q=new Date().toISOString();return{id:X.id??l4.DEV_ASSETS($),title:X.title,description:X.description??null,icon:X.icon??null,app_name:X.app_name??null,app_id:X.app_id??null,organization_id:$,created_by:"system",created_at:Q,updated_at:Q,connection_type:X.connection_type,connection_url:X.connection_url??null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:X.metadata??null,tools:Zo8,bindings:["OBJECT_STORAGE"],status:"active"}}var Zo8;var Lx=w(()=>{TD();Gi();U8();Zo8=gL.map(($)=>({name:$.name,description:`${$.name} operation for local file storage`,inputSchema:Nr1.toJSONSchema($.inputSchema),outputSchema:Nr1.toJSONSchema($.outputSchema)}))});function Ur1($,Z){return $||Z===0}function Or1($,Z,X,Q,Y){let G=Z?Y+1:Y,J=Z?$.slice(0,X):$,W=Q+X<G;return{items:J,totalCount:G,hasMore:W}}function Xo8($,Z){if(Z.length===0)return;let[X,...Q]=Z,Y=X==="slug"?bU($):$[X];for(let G of Q){if(Y===null||typeof Y!=="object")return;Y=Y[G]}return Y}function Qo8($){let X=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/%/g,".*").replace(/_/g,".");return new RegExp(`^${X}$`,"i")}function Yo8($,Z,X){if($===void 0)return!0;switch(Z){case"eq":return X===null?$===null:$===X;case"gt":return $>X;case"gte":return $>=X;case"lt":return $<X;case"lte":return $<=X;case"in":return Array.isArray(X)&&X.includes($);case"like":return typeof $==="string"&&Qo8(String(X)).test($);case"contains":return String($).toLowerCase().includes(String(X).toLowerCase());default:return!0}}function Ui($,Z){if(!Z)return!0;if("conditions"in Z){let{operator:Q,conditions:Y}=Z;if(Y.length===0)return!0;switch(Q){case"and":return Y.every((G)=>Ui($,G));case"or":return Y.some((G)=>Ui($,G));case"not":return!Y.every((G)=>Ui($,G));default:return!0}}let X=Xo8($,Z.field);return Yo8(X,Z.operator,Z.value)}var Br1=w(()=>{d80()});async function wr1($,Z,X){if($.length===0)return;let Q=0;async function Y(){while(Q<$.length){let G=Q++;await X($[G])}}await Promise.all(Array.from({length:Math.min(Z,$.length)},()=>Y()))}import{z as MO}from"zod";var Go8=8,Jo8,Wo8,Ko8,Ho8,ru0;var Dr1=w(()=>{ou0();Zr1();bG();Jr1();Kr1();Gi();Fr1();U8();C0();v9();VY();HF();Lx();VW();d80();Br1();Jo8=[{name:/^(COLLECTION_REGISTRY_APP_LIST|REGISTRY_ITEM_LIST)$/,inputSchema:MO.object({})}],Wo8={LLM:g50,LLMS:g50,ASSISTANTS:$r1,MCP:Wr1,OBJECT_STORAGE:gL,AI_GATEWAY_BILLING:Hr1,TRIGGER:C50,REGISTRY:Jo8,BRAND:b50},Ko8=U3.extend({binding:MO.union([MO.array(MO.object({}).passthrough()),MO.object({}).passthrough(),MO.string()]).optional(),include_virtual:MO.boolean().optional().describe("Whether to include VIRTUAL connections in the results. Defaults to false."),slug:MO.string().optional().describe("Filter by connection slug. Matches against app_name, or a slug derived from connection_url or title.")}),Ho8=FF(b7),ru0=c({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",annotations:{title:"List Connections",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:Ko8,outputSchema:Ho8,handler:async($,Z)=>{await Z.access.check();let X=t(Z),Q=$.binding?typeof $.binding==="string"?(()=>{let N=Wo8[$.binding.toUpperCase()];if(!N)throw Error(`Unknown binding: ${$.binding}`);return N})():$.binding:void 0,Y=Q?k50(Q):void 0,G=!!Y,J=$.limit??100,W=$.offset??0,{items:K,totalCount:H}=await Z.storage.connections.list(X.id,{includeVirtual:$.include_virtual??!1,slug:$.slug,where:$.where,orderBy:$.orderBy,limit:G?void 0:J,offset:G?void 0:W});if(Y){let N=s5(),U=l4.SELF(X.id);await wr1(K,Go8,async(O)=>{if(O.tools!==null)return;let B=O.id===U?async()=>{let{listManagementTools:L}=await Promise.resolve().then(() => (kO(),u50));return L(Z)}:()=>uu0(O,Z,m80),D=await RO("tools",O.id,B,N,(L)=>Z.pendingRevalidations.push(L),TO);if(D!==null)O.tools=D})}let F=!1;if(O3()&&Ur1(G,W)){let N=_9(),U=l4.DEV_ASSETS(X.id);if(!K.some((O)=>O.id===U)){let O=Dx(X.id,N),B=!$.slug||bU(O)===$.slug,D=Ui(O,$.where);if(B&&D)K.unshift(O),F=!0}}if(G){let N=(await Promise.all(K.map(async(D)=>{if(!D.tools||D.tools.length===0)return null;return Y.isImplementedBy(D.tools.map((E)=>({name:E.name,inputSchema:E.inputSchema,outputSchema:E.outputSchema})))?D:null}))).filter((D)=>D!==null),U=N.length,O=N.slice(W,W+J),B=W+J<U;return{items:O,totalCount:U,hasMore:B}}return Or1(K,F,J,W,H)}})});var Fo8,au0;var Lr1=w(()=>{bG();U8();C0();v9();VY();HF();Lx();VW();Fo8=Ki(b7),au0=c({name:"COLLECTION_CONNECTIONS_GET",description:"Get a connection's configuration, tools list, and status by ID.",annotations:{title:"Get Connection",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},_meta:{ui:{visibility:["app"]}},inputSchema:Wi,outputSchema:Fo8,handler:async($,Z)=>{let X=t(Z);if(await Z.access.check(),O3()&&h50($.id,X.id))return{item:Dx(X.id,_9())};let Q=await Z.storage.connections.findById($.id);if(!Q||Q.organization_id!==X.id)return{item:null};if(Q.tools===null){let Y=l4.SELF(X.id),G=Q.id===Y?async()=>{let{listManagementTools:W}=await Promise.resolve().then(() => (kO(),u50));return W(Z)}:async()=>{let W=await F5(Q,Z,!0);try{return(await W.listTools()).tools}finally{await W.close().catch(()=>{})}},J=await RO("tools",Q.id,G,s5(),(W)=>Z.pendingRevalidations.push(W),TO);if(J!==null)Q.tools=J}return{item:Q}}})});class u6{db;vault;constructor($,Z){this.db=$;this.vault=Z}async get($){let Z=await this.db.selectFrom("downstream_tokens").selectAll().where("connectionId","=",$).executeTakeFirst();if(!Z)return null;return this.decryptToken(Z)}async upsert($){let Z=new Date().toISOString(),X=await this.vault.encrypt($.accessToken),Q=$.refreshToken?await this.vault.encrypt($.refreshToken):null,Y=$.clientSecret?await this.vault.encrypt($.clientSecret):null;return await this.db.transaction().execute(async(G)=>{let J=await G.selectFrom("downstream_tokens").select(["id","createdAt"]).where("connectionId","=",$.connectionId).executeTakeFirst();if(J)return await G.updateTable("downstream_tokens").set({accessToken:X,refreshToken:Q,scope:$.scope,expiresAt:$.expiresAt?.toISOString()??null,clientId:$.clientId,clientSecret:Y,tokenEndpoint:$.tokenEndpoint,updatedAt:Z}).where("id","=",J.id).execute(),{id:J.id,connectionId:$.connectionId,accessToken:$.accessToken,refreshToken:$.refreshToken,scope:$.scope,expiresAt:$.expiresAt,createdAt:J.createdAt,updatedAt:Z,clientId:$.clientId,clientSecret:$.clientSecret,tokenEndpoint:$.tokenEndpoint};let W=m8("dtok");return await G.insertInto("downstream_tokens").values({id:W,connectionId:$.connectionId,accessToken:X,refreshToken:Q,scope:$.scope,expiresAt:$.expiresAt?.toISOString()??null,clientId:$.clientId,clientSecret:Y,tokenEndpoint:$.tokenEndpoint,createdAt:Z,updatedAt:Z}).execute(),{id:W,connectionId:$.connectionId,accessToken:$.accessToken,refreshToken:$.refreshToken,scope:$.scope,expiresAt:$.expiresAt,createdAt:Z,updatedAt:Z,clientId:$.clientId,clientSecret:$.clientSecret,tokenEndpoint:$.tokenEndpoint}})}async delete($){await this.db.deleteFrom("downstream_tokens").where("connectionId","=",$).execute()}isExpired($,Z=0){if(!$.expiresAt)return!1;let Q=($.expiresAt instanceof Date?$.expiresAt:new Date($.expiresAt)).getTime();if(Number.isNaN(Q))return!0;return Q-Z<Date.now()}async decryptToken($){let Z=await this.vault.decrypt($.accessToken),X=$.refreshToken?await this.vault.decrypt($.refreshToken):null,Q=$.clientSecret?await this.vault.decrypt($.clientSecret):null;return{id:$.id,connectionId:$.connectionId,accessToken:Z,refreshToken:X,scope:$.scope,expiresAt:$.expiresAt,createdAt:$.createdAt,updatedAt:$.updatedAt,clientId:$.clientId,clientSecret:Q,tokenEndpoint:$.tokenEndpoint}}}var xG=w(()=>{vX()});function Ex(...$){if(Bo8)console.log("[mcp-read-cache]",...$)}function wo8($){return $.kind==="org"?"org":`u:${$.userId}`}function su0($){if($===null||typeof $!=="object")return JSON.stringify($)??"null";if(Array.isArray($))return`[${$.map(su0).join(",")}]`;return`{${Object.keys($).sort().map((X)=>`${JSON.stringify(X)}:${su0($[X])}`).join(",")}}`}class d50{config;maxEntries;now;maxTotalBytes;store=new Map;revalidating=new Set;totalBytes=0;constructor($=No8,Z=Uo8,X=()=>Date.now(),Q=Oo8){this.config=$;this.maxEntries=Z;this.now=X;this.maxTotalBytes=Q}stats(){return{entries:this.store.size,bytes:this.totalBytes}}deleteKey($){let Z=this.store.get($);if(Z)this.store.delete($),this.totalBytes-=Z.bytes}key($,Z,X,Q){return`${Z}:${wo8(X)}:${$}:${su0(Q)}`}storeSet($,Z,X,Q){let Y;try{Y=JSON.stringify(Z).length}catch{Ex("SKIP non-serializable",$);return}if(Y>Q){Ex("SKIP oversize",$,`${Y}b > cap ${Q}b`);return}this.deleteKey($);while(this.store.size>0&&(this.store.size>=this.maxEntries||this.totalBytes+Y>this.maxTotalBytes)){let G=this.store.keys().next().value;if(G===void 0)break;this.deleteKey(G)}this.store.set($,{value:Z,storedAt:X,bytes:Y}),this.totalBytes+=Y}async fetch($){let{type:Z,connectionId:X,scope:Q,params:Y,fetchLive:G,shouldCache:J,onRevalidation:W}=$,K=this.config[Z],H=this.key(Z,X,Q,Y),F=this.now(),N=this.store.get(H),U=N?F-N.storedAt:1/0;if(!N||U>K.maxStaleMs){c50.add(1,{type:Z,outcome:"miss"}),Ex(N?"EXPIRED":"MISS",H);let O=await G();if(J?.(O)??!0)this.storeSet(H,O,this.now(),K.maxValueBytes);else Ex("NOT-CACHED (shouldCache=false)",H);return O}if(this.store.delete(H),this.store.set(H,N),U>K.revalidateAfterMs&&!this.revalidating.has(H)){c50.add(1,{type:Z,outcome:"stale"}),Ex("STALE \u2192 serve + revalidate",H,`age=${U}ms`),this.revalidating.add(H);let O=G().then((B)=>{if(J?.(B)??!0)this.storeSet(H,B,this.now(),K.maxValueBytes)}).catch(()=>{c50.add(1,{type:Z,outcome:"error"})}).finally(()=>this.revalidating.delete(H));W?.(O)}else c50.add(1,{type:Z,outcome:"hit"}),Ex("HIT",H,`age=${U}ms`);return N.value}invalidate($){let Z=`${$}:`;for(let X of[...this.store.keys()])if(X.startsWith(Z))this.deleteKey(X)}}function $c0(){return b0().mcpCacheEnabled}function m50(){return $c0()?eu0:null}var c50,l50=1024,Er1,No8,Uo8=2000,Oo8,Bo8,eu0;var Oi=w(()=>{f6();T$();c50=S$.createCounter("mcp_read_cache.fetches",{description:"MCP read cache outcomes (hit, stale, miss, error)",unit:"{fetches}"}),Er1=l50*l50,No8={"tools/call":{revalidateAfterMs:30000,maxStaleMs:300000,maxValueBytes:512*l50},"resources/read":{revalidateAfterMs:60000,maxStaleMs:300000,maxValueBytes:4*Er1},"prompts/get":{revalidateAfterMs:60000,maxStaleMs:300000,maxValueBytes:512*l50}},Oo8=256*Er1,Bo8=typeof process<"u"&&!!process.env?.MCP_CACHE_DEBUG;eu0=new d50;S$.createObservableGauge("mcp_read_cache.entries",{description:"Current entry count in the per-pod MCP read cache",unit:"{entries}"}).addCallback(($)=>$.observe(eu0.stats().entries));S$.createObservableGauge("mcp_read_cache.bytes",{description:"Approximate total bytes held in the per-pod MCP read cache",unit:"By"}).addCallback(($)=>$.observe(eu0.stats().bytes))});function Pr1($){m50()?.invalidate($)}function jx($){Pr1($);let Z=Zc0?.();if(!Z)return;try{Z.publish(jr1,Do8.encode(JSON.stringify({connectionId:$,originId:zr1})))}catch(X){console.warn("[McpCacheInvalidation] publish failed (non-critical):",X)}}function Ar1($){if(Zc0=$,Bi)return;let Z=$();if(!Z)return;Bi=Z.subscribe(jr1),(async()=>{for await(let X of Bi)try{let Q=JSON.parse(Lo8.decode(X.data));if(Q.originId===zr1)continue;Pr1(Q.connectionId)}catch{}})().catch(console.error)}function Tr1(){Bi?.unsubscribe(),Bi=null,Zc0=void 0}var jr1="studio.mcp-cache.invalidate",zr1,Do8,Lo8,Zc0,Bi=null;var wi=w(()=>{Oi();zr1=crypto.randomUUID(),Do8=new TextEncoder,Lo8=new TextDecoder});import{z as Xc0}from"zod";function jo8($){let Z={...$};for(let X of Eo8)delete Z[X];return Z}function zo8($,Z){return $.connection_url!==void 0?$.connection_url:Z}function To8($,Z){return $.length===Z.length&&$.every((X,Q)=>X===Z[Q])}var Eo8,Po8,Ao8,Qc0;var Rr1=w(()=>{HF();xG();C0();T$();VY();wi();cu0();pm();VW();Eo8=["id","organization_id","created_by","created_at"];Po8=Xc0.object({id:Xc0.string().describe("ID of the connection to update"),data:N$0.describe("Partial connection data to update")}),Ao8=Xc0.object({item:b7.describe("The updated connection entity")});Qc0=c({name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update a connection's configuration. Re-fetches tools from the server on URL change.",annotations:{title:"Update Connection",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:Po8,outputSchema:Ao8,handler:async($,Z)=>{r(Z);let X=t(Z);await Z.access.check();let Q=G1(Z);if(!Q)throw Error("User ID required to update connection");let{id:Y}=$,G=jo8($.data),J=G.configuration_state!==void 0||G.configuration_scopes!==void 0,W=await Z.storage.connections.findById(Y);if(!W||W.organization_id!==X.id)throw Error("Connection not found in organization");let K=G.connection_type??W.connection_type,H=zo8(G,W.connection_url);if(K==="VIRTUAL"){let f=Ff(H);if(!f)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let x=await Z.storage.virtualMcps.findById(f);if(!x)throw Error(`Virtual MCP not found: ${f}`);if(x.organization_id!==X.id)throw Error("Virtual MCP does not belong to the current organization");H=Nf(f)}let F=G.configuration_state??W.configuration_state??{},N=G.configuration_scopes??W.configuration_scopes??[];if(J){if(G.configuration_state!==void 0)F=G.configuration_state??{};else if(F===null||F===void 0)F={};if(G.configuration_scopes!==void 0)N=G.configuration_scopes??[];if(N.length>0){let f=F;Zi(f,N,X.id),await Qi(f,N,X.id,Z)}}if(K==="STDIO"&&!b0().localMode)throw Error("STDIO connections are only available in local mode (--local-mode).");let U=G.connection_token??W.connection_token;if(!U)try{let x=await new u6(Z.db,Z.vault).get(Y);if(x?.accessToken)U=x.accessToken}catch{}let O=await jO({id:W.id,title:G.title??W.title,connection_type:K,connection_url:H,connection_token:U,connection_headers:G.connection_headers??W.connection_headers}).catch(()=>null),B=O?.tools?.length?O.tools:null,D=!1;if(G.configuration_scopes===void 0&&O?.scopes?.length)D=!To8(N,O.scopes),N=O.scopes;if(Zi(F,N,X.id),D&&N.length>0)await Qi(F,N,X.id,Z);let L=J||D,E=L?Xi(F,N):[],j=L?Xi(W.configuration_state??{},W.configuration_scopes??[]):[],z=W.configuration_state,A=z==null||Object.keys(z).length===0,P,M,q=async()=>{try{await Z.storage.connectionCredentialVault.replaceGrantsForSubject({organizationId:X.id,subjectConnectionId:Y,createdBy:Q,grants:j})}catch(f){console.error("Failed to restore credential grants after credential vault mutation failed",f)}},k={...G,connection_url:H,tools:null,configuration_state:F,configuration_scopes:N,updated_by:Q},C={...W,...k};if(L)try{if(await Z.storage.connectionCredentialVault.replaceGrantsForSubject({organizationId:X.id,subjectConnectionId:Y,createdBy:Q,grants:E}),E.length>0){if(!await Z.storage.connectionCredentialVault.findActiveWorkloadToken({organizationId:X.id,subjectConnectionId:Y})){let{plaintextToken:x,record:n}=await Z.storage.connectionCredentialVault.createOrRotateWorkloadToken({organizationId:X.id,subjectConnectionId:Y});M=n.id,P={baseUrl:Z.baseUrl,org:X.slug??X.id,subjectConnectionId:Y,token:x}}}}catch(f){if(M)await Z.storage.connectionCredentialVault.revokeWorkloadToken({organizationId:X.id,subjectConnectionId:Y,tokenId:M});throw await q(),f}if(L&&F&&N)try{await(await F5(C,Z,!1)).callTool({name:"ON_MCP_CONFIGURATION",arguments:{state:F,scopes:N,firstRun:A,...P?{vault:P}:{}}})}catch(f){if(console.error("Failed to invoke ON_MCP_CONFIGURATION callback",f),M)throw await Z.storage.connectionCredentialVault.revokeWorkloadToken({organizationId:X.id,subjectConnectionId:Y,tokenId:M}),await q(),f}let l;try{l=await Z.storage.connections.update(Y,k)}catch(f){if(L){if(M)await Z.storage.connectionCredentialVault.revokeWorkloadToken({organizationId:X.id,subjectConnectionId:Y,tokenId:M});await q()}throw f}if(B)s5()?.set("tools",Y,B).catch(()=>{});return jx(Y),{item:l}}})});import{z as Ro8}from"zod";var Io8,Yc0;var Ir1=w(()=>{bG();M4();C0();VY();wi();VW();Io8=Hi.extend({force:Ro8.boolean().optional().describe("If true, removes this connection from all agents that reference it before deleting")}),Yc0=c({name:"COLLECTION_CONNECTIONS_DELETE",description:"Permanently delete a connection. Set force=true to auto-remove from referencing Virtual MCPs.",annotations:{title:"Delete Connection",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:Io8,outputSchema:Fi(b7),handler:async($,Z)=>{r(Z);let X=t(Z);await Z.access.check();let Q=await Z.storage.connections.findById($.id);if(!Q)throw Error(`Connection not found: ${$.id}`);if(Q.organization_id!==X.id)throw Error("Connection not found in organization");if(Q.metadata?.isFixed===!0)throw Error("This connection is a fixed system connection and cannot be deleted");let G=await Z.storage.virtualMcps.listByConnectionId(X.id,$.id);if(G.length>0)if($.force)await Z.storage.virtualMcps.removeConnectionReferences($.id);else throw Error(JSON.stringify({code:"CONNECTION_IN_USE",agentNames:G.map((K)=>K.title)}));await Z.storage.connections.delete($.id);let J=await Z.storage.organizationSettings.get(X.id);if(J?.registry_config){let{registries:K,blockedMcps:H}=J.registry_config;if($.id in K){let{[$.id]:F,...N}=K;await Z.storage.organizationSettings.upsert(X.id,{registry_config:{registries:N,blockedMcps:H}})}}s5()?.invalidate($.id).catch(()=>{}),jx($.id);let W=G1(Z);if(W)y1.capture({distinctId:W,event:"connection_deleted",groups:{organization:X.id},properties:{connection_id:Q.id,connection_type:Q.connection_type,app_name:Q.app_name??null,organization_id:X.id,forced:$.force??!1}});return{item:Q}}})});import{z as zx}from"zod";var Gc0;var qr1=w(()=>{C0();Gc0=c({name:"CONNECTION_TEST",description:"Test connection health and latency",annotations:{title:"Test Connection",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},inputSchema:zx.object({id:zx.string()}),outputSchema:zx.object({id:zx.string(),healthy:zx.boolean(),latencyMs:zx.number()}),handler:async($,Z)=>{let X=t(Z);await Z.access.check();let Q=await Z.storage.connections.findById($.id);if(!Q||Q.organization_id!==X.id)throw Error("Connection not found");let Y=await Z.storage.connections.testConnection($.id);return{id:$.id,...Y}}})});var Mr1=w(()=>{Mo1();Dr1();Lr1();Rr1();Ir1();qr1()});import{sql as k4}from"kysely";import{z as ZK}from"zod";function kr1($){if($===null||$===void 0)return"NULL";if(typeof $==="number")return String($);if(typeof $==="boolean")return $?"TRUE":"FALSE";if(typeof $==="string")return`'${$.replace(/'/g,"''")}'`;if($ instanceof Date)return`'${$.toISOString()}'`;return`'${JSON.stringify($).replace(/'/g,"''")}'`}function ko8($,Z){let X=$;for(let Y=Z.length;Y>=1;Y--){let G=`$${Y}`;if(X.includes(G))X=X.replaceAll(G,kr1(Z[Y-1]))}let Q=[];for(let Y=0;Y<X.length;Y++)if(X[Y]==="?")Q.push(Y);for(let Y=Math.min(Q.length,Z.length)-1;Y>=0;Y--){let G=Q[Y],J=kr1(Z[Y]);X=X.slice(0,G)+J+X.slice(G+1)}return X}function Vr1($){return $.replace(/-/g,"_")}function So8($){return`app_${Vr1($)}`}function Co8($){return`app_role_${Vr1($)}`}function _o8($){if($ instanceof Error){let Z=$.message.toLowerCase(),X=$.code;return X==="3F000"||X==="42704"||X==="22023"||Z.includes("schema")&&Z.includes("does not exist")||Z.includes("role")&&Z.includes("does not exist")}return!1}async function vo8($,Z,X){if(await k4`CREATE SCHEMA IF NOT EXISTS ${k4.id(Z)}`.execute($),!(await k4`
947
+ </workflows>`,Vt1={id:"studio-usage-manager",title:"Usage Manager",icon:"icon://BarChart10?color=blue",description:"Analyze usage, costs, and clean up idle agents and connections",selectedTools:["MONITORING_STATS","MONITORING_LOGS_LIST","MONITORING_LOG_GET","MONITORING_THREAD_USAGE","COLLECTION_VIRTUAL_MCP_LIST","COLLECTION_VIRTUAL_MCP_GET","COLLECTION_VIRTUAL_MCP_DELETE","VIRTUAL_MCP_LAST_USED_LIST","COLLECTION_CONNECTIONS_LIST","COLLECTION_CONNECTIONS_GET","COLLECTION_CONNECTIONS_DELETE","ORGANIZATION_MEMBER_LIST"],selectedConnections:null,selectedPrompts:[],instructions:Lp8,getId:h7.USAGE_MANAGER}});function Pu0($){return CL.find((Z)=>$.startsWith(`${Z.id}_`))??null}async function Ep8($,Z){if("resolveRuntime"in $)return $.resolveRuntime(Z);return{instructions:$.instructions,selectedTools:$.selectedTools}}async function H50({virtualMcp:$,agentId:Z=$.id,organizationId:X,ctx:Q}){let Y=Pu0(Z);if(!Y)return $;let G=await Ep8(Y,{orgId:X,ctx:Q}),J=G.selectedTools?[...G.selectedTools]:null;return{...$,metadata:{...$.metadata??{},instructions:G.instructions},connections:$.connections.map((W)=>({...W,selected_tools:J}))}}async function F50($,Z){if(!("checklist"in $))return[];return Promise.all($.checklist.map(async(X)=>({label:X.label,activeForm:X.activeForm,action:X.action,completed:await X.isCompleted(Z),alwaysSuggest:X.alwaysSuggest})))}async function Ct1($,Z,X){let Q={self:l4.SELF($),registry:l4.REGISTRY($),"community-registry":l4.COMMUNITY_REGISTRY($)};await Promise.all(CL.map(async(Y)=>{let G=Y.getId($),J=await X.findById(G,$),K=(Y.selectedConnections??["self"]).map((H)=>Q[H]);if(J){await X.update(G,Z,{metadata:{...J.metadata??{},instructions:Y.instructions},connections:K.map((H)=>{let F=J.connections.find((N)=>N.connection_id===H);return{connection_id:H,selected_tools:Y.selectedTools?[...Y.selectedTools]:null,selected_resources:F?.selected_resources??null,selected_prompts:F?.selected_prompts??null}})});return}await X.create($,Z,{title:Y.title,description:Y.description,icon:Y.icon,status:"active",pinned:!1,metadata:{instructions:Y.instructions},connections:K.map((H)=>({connection_id:H,selected_tools:Y.selectedTools?[...Y.selectedTools]:null,selected_resources:null,selected_prompts:Y.selectedPrompts?[...Y.selectedPrompts]:null}))},{id:G})}))}var CL;var Nx=w(()=>{U8();Ot1();wt1();Lt1();At1();Rt1();qt1();kt1();St1();CL=[Pt1,Ut1,Dt1,Tt1,Bt1,It1,Mt1,Vt1]});import{DBOS as N50}from"@dbos-inc/dbos-sdk";async function jp8($){let Z=p8(),X=new tf(Z.db);await Ct1($.orgId,$.createdBy,X)}async function zp8($){let Z=p8(),X=new tf(Z.db);for(let Q of CL){let Y=Q.getId($.orgId),G=await X.findById(Y,$.orgId);if(!G)continue;let J=Q.selectedPrompts?[...Q.selectedPrompts]:null;if(G.connections.every((K)=>{let H=K.selected_prompts;if(J===null)return H===null;if(H===null)return!1;if(H.length!==J.length)return!1;return H.every((F,N)=>F===J[N])}))continue;await X.update(Y,$.createdBy,{connections:G.connections.map((K)=>({connection_id:K.connection_id,selected_tools:K.selected_tools,selected_resources:K.selected_resources,selected_prompts:J}))})}}async function Pp8($){await N50.runStep(()=>jp8($),{name:"installStudioPack"}),await N50.runStep(()=>zp8($),{name:"backfillSelectedPrompts"})}async function Au0($){await N50.startWorkflow(Ap8,{workflowID:`install-studio-pack:${Tp8}:${$.orgId}`})($)}async function _t1(){let Z=await p8().db.selectFrom("member").select(["organizationId","userId"]).orderBy("createdAt","asc").execute(),X=new Map;for(let Q of Z)if(!X.has(Q.organizationId))X.set(Q.organizationId,Q.userId);await Promise.all(Array.from(X).map(async([Q,Y])=>{try{await Au0({orgId:Q,createdBy:Y})}catch(G){console.error("[studio-pack-backfill] enqueue failed",{orgId:Q},G)}}))}var Ap8,Tp8="v5";var U50=w(()=>{_G();bx0();Nx();Ap8=N50.registerWorkflow(Pp8,{name:"installStudioPackWorkflow"})});class nm{constructor(){this._messageQueue=[]}static createLinkedPair(){let $=new nm,Z=new nm;return $._otherTransport=Z,Z._otherTransport=$,[$,Z]}async start(){while(this._messageQueue.length>0){let $=this._messageQueue.shift();this.onmessage?.($.message,$.extra)}}async close(){let $=this._otherTransport;this._otherTransport=void 0,await $?.close(),this.onclose?.()}async send($,Z){if(!this._otherTransport)throw Error("Not connected");if(this._otherTransport.onmessage)this._otherTransport.onmessage($,{authInfo:Z?.authInfo});else this._otherTransport._messageQueue.push({message:$,extra:{authInfo:Z?.authInfo}})}}import{z as $4}from"zod";var O50,vt1,ft1,bt1,xt1,yt1,gt1,ht1,ut1,ct1;var Ux=w(()=>{O50=$4.record($4.string(),$4.array($4.string())),vt1=$4.object({id:$4.string().describe("Unique identifier for the API key"),name:$4.string().describe("Human-readable name for the API key"),userId:$4.string().describe("ID of the user who owns this API key"),permissions:O50.describe('Permissions granted to this API key. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Example: { "self": ["API_KEY_CREATE"], "conn_abc123": ["SEND_MESSAGE"] }'),expiresAt:$4.string().datetime().nullable().optional().describe("Expiration date of the API key (ISO 8601)"),createdAt:$4.string().datetime().describe("When the API key was created (ISO 8601)")}),ft1=$4.object({name:$4.string().min(1).max(64).describe("Human-readable name for the API key"),permissions:O50.describe(`Permissions to grant (REQUIRED \u2014 there is no implicit default). Format: { resource: [actions] }. Resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Actions are tool names (e.g., ["ORGANIZATION_GET"]) or ["*"] for all. Example: { "self": ["ORGANIZATION_GET", "COLLECTION_CONNECTIONS_LIST"] }. The key is authorized solely by this allowlist; the creator's role does not widen it.`),expiresIn:$4.number().positive().optional().describe("Expiration time in seconds. If not provided, key never expires."),metadata:$4.record($4.string(),$4.unknown()).optional().describe("Additional metadata to store with the API key")}),bt1=$4.object({id:$4.string().describe("Unique identifier for the API key"),name:$4.string().describe("Human-readable name for the API key"),key:$4.string().describe("The actual API key value. STORE THIS SECURELY - it will not be shown again!"),permissions:O50.describe('Permissions granted to this API key. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools'),expiresAt:$4.string().datetime().nullable().optional().describe("Expiration date of the API key (ISO 8601)"),createdAt:$4.string().datetime().describe("When the API key was created (ISO 8601)")}),xt1=$4.object({}),yt1=$4.object({items:$4.array(vt1).describe("List of API keys (without key values)")}),gt1=$4.object({keyId:$4.string().describe("ID of the API key to update"),name:$4.string().min(1).max(64).optional().describe("New name for the API key"),permissions:O50.optional().describe('New permissions. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Actions are tool names or "*" for all. Example: { "self": ["API_KEY_CREATE"] }. Replaces existing permissions.'),metadata:$4.record($4.string(),$4.unknown()).optional().describe("New metadata. Replaces existing metadata.")}),ht1=$4.object({item:vt1.describe("The updated API key (without key value)")}),ut1=$4.object({keyId:$4.string().describe("ID of the API key to delete")}),ct1=$4.object({success:$4.boolean().describe("Whether the deletion was successful"),keyId:$4.string().describe("ID of the deleted API key")})});var Tu0;var lt1=w(()=>{M4();C0();Ux();Tu0=c({name:"API_KEY_CREATE",description:"Create an API key with scoped permissions. The key value is returned only once \u2014 store it immediately.",annotations:{title:"Create API Key",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:ft1,outputSchema:bt1,handler:async($,Z)=>{r(Z),await Z.access.check();let X=await Z.boundAuth.apiKey.create({name:$.name,permissions:$.permissions,expiresIn:$.expiresIn,metadata:{...$.metadata,organization:Z.organization}}),Q=X.expiresAt?X.expiresAt instanceof Date?X.expiresAt.toISOString():X.expiresAt:null,Y=X.createdAt instanceof Date?X.createdAt.toISOString():X.createdAt,G=G1(Z);if(G)y1.capture({distinctId:G,event:"api_key_created",...Z.organization?.id?{groups:{organization:Z.organization.id}}:{},properties:{key_id:X.id,key_name:X.name??$.name,organization_id:Z.organization?.id,has_expiry:!!Q}});return{id:X.id,name:X.name??$.name,key:X.key,permissions:X.permissions??{},expiresAt:Q,createdAt:Y}}})});var Ru0;var dt1=w(()=>{M4();C0();Ux();Ru0=c({name:"API_KEY_DELETE",description:"Delete and instantly revoke an API key. Cannot be undone.",annotations:{title:"Delete API Key",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:ut1,outputSchema:ct1,handler:async($,Z)=>{r(Z),await Z.access.check();let X=G1(Z);if(!X)throw Error("User ID required to delete API key");let Y=(await Z.boundAuth.apiKey.list())?.find((K)=>K.id===$.keyId);if(!Y)throw Error("API key not found");let J=Y.metadata?.organization?.id,W=Z.organization?.id;if(J!==W)throw Error("Cannot delete API key from another organization");if(await Z.boundAuth.apiKey.delete($.keyId),W)y1.capture({distinctId:X,event:"api_key_deleted",groups:{organization:W},properties:{key_id:$.keyId,organization_id:W}});return{success:!0,keyId:$.keyId}}})});var Iu0;var mt1=w(()=>{C0();Ux();Iu0=c({name:"API_KEY_LIST",description:"List API keys for the current user in the current organization. Returns metadata only \u2014 key values are never shown after creation.",annotations:{title:"List API Keys",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:xt1,outputSchema:yt1,handler:async($,Z)=>{r(Z),await Z.access.check();let X=await Z.boundAuth.apiKey.list(),Q=Z.organization?.id;return{items:(X??[]).filter((G)=>{return G.metadata?.organization?.id===Q}).map((G)=>({id:G.id,name:G.name??"Unnamed Key",userId:G.userId,permissions:G.permissions??{},expiresAt:G.expiresAt?G.expiresAt instanceof Date?G.expiresAt.toISOString():G.expiresAt:null,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt}))}}})});var qu0;var it1=w(()=>{C0();Ux();qu0=c({name:"API_KEY_UPDATE",description:"Update an API key's name, permissions, or metadata. The key value cannot be changed or retrieved.",annotations:{title:"Update API Key",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:gt1,outputSchema:ht1,handler:async($,Z)=>{if(r(Z),await Z.access.check(),!G1(Z))throw Error("User ID required to update API key");let Y=(await Z.boundAuth.apiKey.list())?.find((H)=>H.id===$.keyId);if(!Y)throw Error(`API key not found: ${$.keyId}`);let J=Y.metadata?.organization?.id,W=Z.organization?.id;if(J!==W)throw Error("Cannot update API key from another organization");let K=await Z.boundAuth.apiKey.update({keyId:$.keyId,name:$.name,permissions:$.permissions,metadata:{...$.metadata,organization:Z.organization}});if(!K)throw Error(`Failed to update API key: ${$.keyId}`);return{item:{id:K.id,name:K.name??$.name??"Unnamed Key",userId:K.userId,permissions:K.permissions??{},expiresAt:K.expiresAt?K.expiresAt instanceof Date?K.expiresAt.toISOString():K.expiresAt:null,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt}}}})});var pt1=w(()=>{lt1();dt1();mt1();it1();Ux()});function zO($){let Z=$.trim();if(!Z)return{ok:!1,error:"Enter a website URL."};let X=Ip8.test(Z),Q=qp8.test(Z),Y=Mp8.test(Z);if(X&&!Q&&!Y)return{ok:!1,error:"Use an HTTP or HTTPS website URL."};let G=Q?Z:`https://${Z}`,J;try{J=new URL(G)}catch{return{ok:!1,error:"Enter a valid website URL."}}if(J.protocol!=="http:"&&J.protocol!=="https:")return{ok:!1,error:"Use an HTTP or HTTPS website URL."};let W=J.hostname.split(".");if(W.length<2||W.some((K)=>!K||!kp8.test(K)))return{ok:!1,error:"Enter a valid website URL."};return J.protocol="https:",{ok:!0,value:J.origin}}var Ip8,qp8,Mp8,kp8;var tm=w(()=>{Ip8=/^[a-zA-Z][a-zA-Z\d+.-]*:/,qp8=/^[a-zA-Z][a-zA-Z\d+.-]*:\/\//,Mp8=/^[^\s/:?#]+\.[^\s/:?#]+:\d+(?:[/?#]|$)/,kp8=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i});import{z as hX}from"zod";function oW($){if($.baseUrl)return $.baseUrl.replace(/\/+$/,"");return(($.settings??b0()).reportsInternalApiUrl??Vp8).replace(/\/+$/,"")}function tt1($={}){return`${oW($)}/api/v2/mcp`}function _L($){let Z=$.apiKey??($.settings??b0()).reportsInternalApiKey;if(!Z)throw Error("REPORTS_INTERNAL_API_KEY (or the legacy COMMERCE_DISCOVERY_INTERNAL_API_KEY) is required to set up reports.");return Z}function w50($){return new URL($).hostname}function Cp8($){return $==="ownership_unverified"||$==="already_claimed_by_other_org"}function _p8($,Z={}){switch($){case"ownership_unverified":{let X=Z.email?`O e-mail ${Z.email}`:"Este e-mail",Q=Z.domain?` ${Z.domain}`:" este site";return`${X} n\xE3o tem permiss\xE3o para reivindicar${Q}. Use um e-mail do dom\xEDnio do site ou pe\xE7a ao suporte para autorizar seu dom\xEDnio.`}case"already_claimed_by_other_org":return"Este site j\xE1 pertence a outra organiza\xE7\xE3o. Fale com o suporte para transferir o acesso.";case"unknown":return"N\xE3o foi poss\xEDvel configurar o Commerce Discovery. Tente novamente ou fale com o suporte.";default:return $}}async function vp8($){let Z=await $.text().catch(()=>"");if(!Z)return"unknown";try{let X=JSON.parse(Z);return Cp8(X.error)?X.error:"unknown"}catch{return"unknown"}}async function B50($){let Z=await $.text().catch(()=>"");if(!Z)return;try{return JSON.parse(Z)}catch{return}}async function Mu0($){let Z=`Commerce Discovery auth failed with status ${$.status}.`,X=await $.text().catch(()=>"");if(!X)return Z;try{let Q=JSON.parse(X),Y=typeof Q.error==="string"?Q.error:typeof Q.message==="string"?Q.message:null;return Y?`Commerce Discovery auth failed: ${Y}.`:Z}catch{return Z}}async function rt1($,Z={}){let X=oW(Z),Q=_L(Z),Y=Z.fetchImpl??fetch,G=w50($.siteUrl),J=`${X}/api/v2/internal/diagnostics/${encodeURIComponent(G)}/upgrade`,W=await Y(J,{method:"POST",headers:{Authorization:`Bearer ${Q}`,"Content-Type":"application/json"},body:JSON.stringify({org_id:$.orgId,...$.orgName?{name:$.orgName}:{},...$.email?{email:$.email}:{},...$.reportUrl?{report_url:$.reportUrl}:{}})});if(!W.ok){let H=await vp8(W);throw new ot1(H,{email:$.email,domain:G})}let K=Sp8.safeParse(await B50(W));if(!K.success)throw Error("Commerce Discovery auth response did not include a token.");return{authorizationToken:K.data.token}}async function at1($,Z={}){let X=oW(Z),Q=_L(Z),Y=Z.fetchImpl??fetch,G=w50($.siteUrl),J=`${X}/api/v2/internal/diagnostics/${encodeURIComponent(G)}/bindings`,W=await Y(J,{method:"POST",headers:{Authorization:`Bearer ${Q}`,"Content-Type":"application/json"},body:JSON.stringify({org_id:$.orgId,provider:$.provider,resource_id:$.resourceId})});if(W.status===409)return{ok:!1,reason:"resource_already_bound",detail:"Este recurso j\xE1 est\xE1 vinculado a outra loja. Se ele \xE9 seu, fale com o suporte para revis\xE3o manual."};if(W.status===422){let H=nt1.safeParse(await B50(W));return{ok:!1,reason:H.success?H.data.reason??"verification_failed":"verification_failed",detail:(H.success?H.data.detail:void 0)??"N\xE3o foi poss\xEDvel verificar o acesso a este recurso."}}if(!W.ok)throw Error(await Mu0(W));let K=nt1.safeParse(await B50(W));if(!K.success||!K.data.binding)throw Error("Commerce Discovery bind response did not include a binding.");return{ok:!0,resourceId:K.data.binding.resource_id,evidence:K.data.binding.evidence}}async function st1($,Z={}){let X=oW(Z),Q=_L(Z),Y=Z.fetchImpl??fetch,G=w50($.siteUrl),J=`${X}/api/v2/internal/diagnostics/${encodeURIComponent(G)}/run`,W=await Y(J,{method:"POST",headers:{Authorization:`Bearer ${Q}`,"Content-Type":"application/json"},body:JSON.stringify({org_id:$.orgId,...$.githubRepo?{github_repo:$.githubRepo}:{}})});if(W.status===409)return{triggered:!1,reason:"not_upgraded"};if(!W.ok)throw Error(await Mu0(W));return{triggered:!0}}async function et1($,Z={}){let X=oW(Z),Q=_L(Z),Y=Z.fetchImpl??fetch,G=w50($.siteUrl),J=`${X}/api/v2/internal/diagnostics/${encodeURIComponent(G)}/connections/status?org_id=${encodeURIComponent($.orgId)}`,W=await Y(J,{method:"GET",headers:{Authorization:`Bearer ${Q}`}});if(W.status===404||W.status===409)return{providers:{},claimed:!1};if(!W.ok)throw Error(await Mu0(W));let K=fp8.safeParse(await B50(W));return{providers:K.success?K.data.providers:{},claimed:!0}}var Vp8,Sp8,nt1,ot1,fp8;var vL=w(()=>{U8();T$();Vp8=new URL(Sx1).origin,Sp8=hX.object({token:hX.string().min(1)}),nt1=hX.object({binding:hX.object({resource_id:hX.string(),evidence:hX.string()}).optional(),reason:hX.string().optional(),detail:hX.string().optional()});ot1=class ot1 extends Error{code;constructor($,Z={}){super(_p8($,Z));this.name="CommerceDiscoveryClaimError",this.code=$}};fp8=hX.object({providers:hX.record(hX.string(),hX.object({connected:hX.boolean(),via:hX.enum(["oauth","sa"]).nullable(),resource:hX.string().nullable()}))})});import{z as kY}from"zod";var bp8,xp8,ku0;var $o1=w(()=>{tm();C0();vL();bp8=kY.object({siteUrl:kY.string().min(1).describe("Website URL of the store being bound."),provider:kY.enum(["ga4","gsc"]).describe("Which Google source to bind: ga4 (Analytics) or gsc (Search Console)."),resourceId:kY.string().min(1).describe("The resource id the client typed: GA4 numeric property id, or GSC site (sc-domain:example.com or https://example.com/).")}),xp8=kY.discriminatedUnion("ok",[kY.object({ok:kY.literal(!0),resourceId:kY.string(),evidence:kY.string()}),kY.object({ok:kY.literal(!1),reason:kY.string(),detail:kY.string()})]),ku0=c({name:"COMMERCE_DISCOVERY_BIND",description:"Bind a GA4 property or GSC site to the org's store via the shared service account (consent-free lane). The client grants deco-reader@\u2026 access to the resource and provides its id; Commerce Discovery verifies the resource belongs to this domain before persisting. Returns ok:false with an actionable pt-BR detail when verification fails or the resource is already bound elsewhere.",annotations:{title:"Bind Commerce Discovery Data Source",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},inputSchema:bp8,outputSchema:xp8,handler:async($,Z)=>{r(Z);let X=t(Z);await Z.access.check();let Q=zO($.siteUrl);if(!Q.ok)throw Error(Q.error);return at1({siteUrl:Q.value,orgId:X.id,provider:$.provider,resourceId:$.resourceId.trim()})}})});import{z as rW}from"zod";var yp8,gp8,Vu0;var Zo1=w(()=>{tm();C0();vL();yp8=rW.object({siteUrl:rW.string().min(1).describe("Website URL of the store to inspect.")}),gp8=rW.object({providers:rW.record(rW.string(),rW.object({connected:rW.boolean(),via:rW.enum(["oauth","sa"]).nullable(),resource:rW.string().nullable()})),claimed:rW.boolean().describe("False when the site isn't claimed/upgraded for this org \u2014 providers is then empty because the status is unreadable, NOT because nothing is connected. The UI must warn instead of rendering existing bindings as disconnected.")}),Vu0=c({name:"COMMERCE_DISCOVERY_CONNECTION_STATUS",description:"Read per-provider connection status (ga4/gsc/vtex) for the org's store \u2014 { connected, via: oauth|sa, resource }. The single source of truth for whether a data source is connected, unifying the OAuth (Studio vault) and shared-SA binding lanes. Read-only.",annotations:{title:"Commerce Discovery Connection Status",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},inputSchema:yp8,outputSchema:gp8,handler:async($,Z)=>{r(Z);let X=t(Z);await Z.access.check();let Q=zO($.siteUrl);if(!Q.ok)throw Error(Q.error);return et1({siteUrl:Q.value,orgId:X.id})}})});import{z as om}from"zod";var hp8,up8,Su0;var Xo1=w(()=>{U8();tm();C0();vL();hp8=om.object({siteUrl:om.string().min(1).describe("Website URL to run the diagnostic for.")}),up8=om.object({triggered:om.boolean(),reason:om.string().optional()}),Su0=c({name:"COMMERCE_DISCOVERY_RUN",description:"Trigger the Commerce Discovery diagnostic run for the current organization's store. Call once the data sources (GA4/GSC/VTEX) are connected \u2014 this run resolves credentials and produces the enriched report.",annotations:{title:"Run Commerce Discovery",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},inputSchema:hp8,outputSchema:up8,handler:async($,Z)=>{r(Z);let X=t(Z);await Z.access.check();let Q=zO($.siteUrl);if(!Q.ok)throw Error(Q.error);let Y=l4.COMMERCE_DISCOVERY(X.id),J=(await Z.storage.connections.findById(Y,X.id))?.configuration_state,W=J&&typeof J==="object"&&typeof J.github_repo==="string"&&J.github_repo.length>0?J.github_repo:void 0;return st1({siteUrl:Q.value,orgId:X.id,githubRepo:W})}})});var PO=w(()=>{E$0()});import{z as aW}from"zod";async function mp8($,Z,X,Q){let Y=await $.storage.connections.findById(Z,X);if(Y)return Y;throw Q}async function ip8($,Z,X,Q){let Y=await $.storage.virtualMcps.findById(Z,X);if(Y)return Y;throw Q}var Cu0,cp8=3600000,lp8,dp8,_u0;var Qo1=w(()=>{U8();tm();C0();VW();PO();vL();Cu0=g80,lp8=aW.object({siteUrl:aW.string().min(1).describe("Website URL to configure.")}),dp8=aW.object({connection:b7,virtualMcp:x7,reportApp:aW.object({connectionId:aW.string(),virtualMcpId:aW.string(),toolName:aW.literal(Cu0)}),created:aW.object({connection:aW.boolean(),virtualMcp:aW.boolean()})});_u0=c({name:"COMMERCE_DISCOVERY_SETUP",description:"Create or return the Commerce Discovery connection and virtual MCP for the current organization.",annotations:{title:"Set Up Commerce Discovery",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:lp8,outputSchema:dp8,handler:async($,Z)=>{r(Z);let X=t(Z);await Z.access.check("COLLECTION_CONNECTIONS_CREATE");let Q=G1(Z);if(!Q)throw Error("User ID required to set up Commerce Discovery");let Y=zO($.siteUrl);if(!Y.ok)throw Error(Y.error);let G=l4.COMMERCE_DISCOVERY(X.id),J=u80(X.id),W=new URLSearchParams({virtualmcpid:J,main:`app:${G}:${Cu0}`}),K={email:Z.auth.user?.email,reportUrl:`${Z.baseUrl}/${encodeURIComponent(X.slug??X.id)}/${crypto.randomUUID()}?${W.toString()}`},H=await Z.storage.connections.findById(G,X.id),F={connection:!1,virtualMcp:!1},N=await rt1({siteUrl:Y.value,orgId:X.id,orgName:X.name,...K}),U=tt1();if(H)console.log("[commerce-discovery] syncing connection to claimed site",{orgId:X.id,siteUrl:Y.value,connectionId:G}),H=await Z.storage.connections.update(H.id,{connection_url:U,connection_token:N.authorizationToken,metadata:{...H.metadata??{},siteUrl:Y.value}});else{console.log("[commerce-discovery] creating connection",{orgId:X.id,siteUrl:Y.value,connectionId:G});try{let L=dx1(X.id,N.authorizationToken,U);H=await Z.storage.connections.create({...L,metadata:{...L.metadata??{},siteUrl:Y.value},organization_id:X.id,created_by:Q}),F.connection=!0}catch(L){H=await mp8(Z,G,X.id,L)}}let O=await Z.storage.virtualMcps.findById(J,X.id);if(!O){console.log("[commerce-discovery] creating virtual MCP",{orgId:X.id,siteUrl:Y.value,connectionId:H.id,virtualMcpId:J});try{O=await Z.storage.virtualMcps.create(X.id,Q,mx1(X.id,H.id),{id:J}),F.virtualMcp=!0}catch(L){O=await ip8(Z,J,X.id,L)}}if(!O.pinned)O=await Z.storage.virtualMcps.update(O.id,Q,{pinned:!0});let B=await Z.db.selectFrom("organization").select(["createdAt"]).where("id","=",X.id).executeTakeFirst();if((B?Date.now()-new Date(B.createdAt).getTime():Number.POSITIVE_INFINITY)<cp8){let E=(await Z.storage.organizationSettings.get(X.id))?.flags,j={};if(E?.reports_only==null)j.reports_only=!0;if(Object.keys(j).length>0)await Z.storage.organizationSettings.upsert(X.id,{flags:j})}return{connection:H,virtualMcp:O,reportApp:{connectionId:H.id,virtualMcpId:O.id,toolName:Cu0},created:F}}})});var Yo1=w(()=>{$o1();Zo1();Xo1();Qo1()});var vu0=_((Go1)=>{Object.defineProperty(Go1,"__esModule",{value:!0});Go1.kvPrefix=Go1.KvWatchInclude=void 0;Go1.KvWatchInclude={LastValue:"",AllHistory:"history",UpdatesOnly:"updates"};Go1.kvPrefix="KV_"});var Lo1=_((wo1)=>{Object.defineProperty(wo1,"__esModule",{value:!0});wo1.KvStatusImpl=wo1.Bucket=wo1.Kvm=wo1.kvOperationHdr=void 0;wo1.Base64KeyCodec=tp8;wo1.NoopKvCodecs=fu0;wo1.defaultBucketOpts=Ko1;wo1.validateKey=Ho1;wo1.validateSearchKey=Fo1;wo1.hasWildcards=No1;wo1.validateBucket=D50;var _5=HY(),$5=Ws(),C5=vu0();function tp8(){let $=(Z,X)=>{let Q=[];for(let Y of Z.split("."))switch(Y){case">":case"*":Q.push(Y);break;default:Q.push(X(Y));break}return Q.join(".")};return{encode(Z){return $(Z,btoa)},decode(Z){return $(Z,atob)}}}function fu0(){return{key:{encode($){return $},decode($){return $}},value:{encode($){return typeof $==="string"?new TextEncoder().encode($):$},decode($){return $}}}}function Ko1(){return{replicas:1,history:1,timeout:2000,max_bytes:-1,maxValueSize:-1,codec:fu0(),storage:$5.StorageType.File}}wo1.kvOperationHdr="KV-Operation";var Wo1="$KV",op8=/^[-/=.\w]+$/,rp8=/^[-/=.>*\w]+$/,ap8=/^[-\w]+$/;function Ho1($){if($.startsWith(".")||$.endsWith(".")||!op8.test($))throw Error(`invalid key: ${$}`)}function Fo1($){if($.startsWith(".")||$.endsWith(".")||$.includes("..")||!rp8.test($))throw Error(`invalid key: ${$}`)}function No1($){if($.startsWith(".")||$.endsWith("."))throw Error(`invalid key: ${$}`);let Z=$.split("."),X=!1;for(let Q=0;Q<Z.length;Q++)switch(Z[Q]){case"*":X=!0;break;case">":if(Q!==Z.length-1)throw Error(`invalid key: ${$}`);X=!0;break;default:}return X}function D50($){if(!ap8.test($))throw Error(`invalid bucket name: ${$}`)}class Uo1{js;constructor($){this.js=(0,$5.toJetStreamClient)($)}create($,Z={}){return this.#$($,Z)}open($,Z={}){return Z.bindOnly=!0,this.#$($,Z)}#$($,Z={}){let{ok:X,min:Q}=this.js.nc.features.get(_5.Feature.JS_KV);if(!X)return Promise.reject(Error(`kv is only supported on servers ${Q} or better`));if(Z.bindOnly)return Ox.bind(this.js,$,Z);return Ox.create(this.js,$,Z)}list(){let $=(X)=>{let Y=X.streams.filter((J)=>{return J.config.name.startsWith(C5.kvPrefix)});Y.forEach((J)=>{J.config.sealed=J.config.sealed||!1,J.config.deny_delete=J.config.deny_delete||!1,J.config.deny_purge=J.config.deny_purge||!1,J.config.allow_rollup_hdrs=J.config.allow_rollup_hdrs||!1});let G="";if(Y.length)G=this.js.nc.info?.cluster??"";return Y.map((J)=>{return new L50(J,G)})},Z=`${this.js.prefix}.STREAM.LIST`;return new $5.ListerImpl(Z,$,this.js)}}wo1.Kvm=Uo1;class Ox{js;jsm;stream;bucket;direct;codec;prefix;editPrefix;useJsPrefix;_prefixLen;constructor($,Z,X){D50($),this.js=Z,this.jsm=X,this.bucket=$,this.prefix=Wo1,this.editPrefix="",this.useJsPrefix=!1,this._prefixLen=0}static async create($,Z,X={}){D50(Z);let Q=await $.jetstreamManager(),Y=new Ox(Z,$,Q);return await Y.init(X),Y}static async bind($,Z,X={}){let Q=$.getOptions()?.checkAPI||X.bindOnly===!1,Y=await $.jetstreamManager(Q),G={config:{allow_direct:X.allow_direct}};D50(Z);let J=new Ox(Z,$,Y);return G.config.name=X.streamName??J.bucketName(),Object.assign(J,G),J.stream=G.config.name,J.codec=X.codec||fu0(),J.direct=G.config.allow_direct??!1,J.initializePrefixes(G),J}async init($={}){let Z=Object.assign(Ko1(),$);this.codec=Z.codec;let X={};if(this.stream=X.name=$.streamName??this.bucketName(),X.retention=$5.RetentionPolicy.Limits,X.max_msgs_per_subject=Z.history,Z.max_bytes)X.max_bytes=Z.max_bytes;if(X.max_msg_size=Z.maxValueSize,X.storage=Z.storage,$.placement)X.placement=$.placement;if($.republish)X.republish=$.republish;if($.description)X.description=$.description;if($.markerTTL)X.allow_msg_ttl=!0,X.subject_delete_marker_ttl=(0,_5.nanos)(Z.markerTTL);if($.mirror){let H=Object.assign({},$.mirror);if(!H.name.startsWith(C5.kvPrefix))H.name=`${C5.kvPrefix}${H.name}`;X.mirror=H,X.mirror_direct=!0}else if($.sources){let H=$.sources.map((F)=>{let N=Object.assign({},F),U=N.name.startsWith(C5.kvPrefix)?N.name.substring(C5.kvPrefix.length):N.name;if(!N.name.startsWith(C5.kvPrefix))N.name=`${C5.kvPrefix}${N.name}`;if(!F.external&&U!==this.bucket)N.subject_transforms=[{src:`$KV.${U}.>`,dest:`$KV.${this.bucket}.>`}];return N});X.sources=H,X.subjects=[this.subjectForBucket()]}else X.subjects=[this.subjectForBucket()];if($.metadata)X.metadata=$.metadata;if(typeof $.compression==="boolean")X.compression=$.compression?$5.StoreCompression.S2:$5.StoreCompression.None;let Q=this.js.nc,Y=Q.getServerVersion(),G=Y?(0,_5.compare)(Y,(0,_5.parseSemVer)("2.7.2"))>=0:!1;X.discard=G?$5.DiscardPolicy.New:$5.DiscardPolicy.Old;let{ok:J,min:W}=Q.features.get(_5.Feature.JS_ALLOW_DIRECT);if(!J&&$.allow_direct===!0){let H=Y?`${Y.major}.${Y.minor}.${Y.micro}`:"unknown";return Promise.reject(Error(`allow_direct is not available on server version ${H} - requires ${W}`))}if($.allow_direct=typeof $.allow_direct==="boolean"?$.allow_direct:J,X.allow_direct=$.allow_direct,this.direct=X.allow_direct,X.num_replicas=Z.replicas,Z.ttl)X.max_age=(0,_5.nanos)(Z.ttl);X.allow_rollup_hdrs=!0;let K;try{if(K=await this.jsm.streams.info(X.name),!K.config.allow_direct&&this.direct===!0)this.direct=!1}catch(H){if(H.message==="stream not found")K=await this.jsm.streams.add(X);else throw H}this.initializePrefixes(K)}initializePrefixes($){this._prefixLen=0,this.prefix=`$KV.${this.bucket}`,this.useJsPrefix=this.js.apiPrefix!=="$JS.API";let{mirror:Z}=$.config;if(Z){let X=Z.name;if(X.startsWith(C5.kvPrefix))X=X.substring(C5.kvPrefix.length);if(Z.external&&Z.external.api!==""){let Q=Z.name.substring(C5.kvPrefix.length);this.useJsPrefix=!1,this.prefix=`$KV.${Q}`,this.editPrefix=`${Z.external.api}.$KV.${X}`}else this.editPrefix=this.prefix}}bucketName(){return this.stream??`${C5.kvPrefix}${this.bucket}`}subjectForBucket(){return`${this.prefix}.${this.bucket}.>`}subjectForKey($,Z=!1){let X=[];if(Z){if(this.useJsPrefix)X.push(this.js.apiPrefix);if(this.editPrefix!=="")X.push(this.editPrefix);else X.push(this.prefix)}else if(this.prefix)X.push(this.prefix);return X.push($),X.join(".")}fullKeyName($){if(this.prefix!=="")return`${this.prefix}.${$}`;return`${Wo1}.${this.bucket}.${$}`}get prefixLen(){if(this._prefixLen===0)this._prefixLen=this.prefix.length+1;return this._prefixLen}encodeKey($){let Z=[];for(let X of $.split("."))switch(X){case">":case"*":Z.push(X);break;default:Z.push(this.codec.key.encode(X));break}return Z.join(".")}decodeKey($){let Z=[];for(let X of $.split("."))switch(X){case">":case"*":Z.push(X);break;default:Z.push(this.codec.key.decode(X));break}return Z.join(".")}validateKey=Ho1;validateSearchKey=Fo1;hasWildcards=No1;close(){return Promise.resolve()}dataLen($,Z){let X=Z?Z.get($5.JsHeaders.MessageSizeHdr)||"":"";if(X!=="")return parseInt(X,10);return $.length}smToEntry($){return new Oo1(this.bucket,this.prefixLen,$,this.codec)}jmToWatchEntry($,Z){return new Bo1(this.bucket,this.prefixLen,$,Z,this.codec)}async create($,Z,X){let Q;try{let G={previousSeq:0},J=await this._put($,Z,G,X);return Promise.resolve(J)}catch(G){if(Q=G,G instanceof $5.JetStreamApiError){let J=G;if(J.code!==$5.JetStreamApiCodes.StreamWrongLastSequence&&J.code!==$5.JetStreamApiCodes.StreamWrongLastSequenceUnknown)return Promise.reject(G)}}let Y=0;try{let G=await this.get($);if(G?.operation==="DEL"||G?.operation==="PURGE")return Y=G!==null?G.revision:0,this._put($,Z,{previousSeq:Y},X);else return Promise.reject(Q)}catch(G){return Promise.reject(G)}}update($,Z,X,Q){if(X<=0)throw Error("version must be greater than 0");return this.put($,Z,{previousSeq:X,timeout:Q})}async _put($,Z,X={},Q){let Y=this.encodeKey($);this.validateKey(Y),Z=this.codec.value.encode(Z);let G={timeout:X?.timeout};if(X.previousSeq!==void 0){let J=(0,_5.headers)();G.headers=J,J.set($5.PubHeaders.ExpectedLastSubjectSequenceHdr,`${X.previousSeq}`)}if(Q)(G.headers||(0,_5.headers)()).set($5.PubHeaders.MessageTTL,Q);try{return(await this.js.publish(this.subjectForKey(Y,!0),Z,G)).seq}catch(J){return Promise.reject(J)}}put($,Z,X={}){return this._put($,Z,X)}async get($,Z){let X=this.encodeKey($);this.validateKey(X);let Q={last_by_subj:this.subjectForKey(X)};if(Z&&Z.revision>0)Q={seq:Z.revision};let Y=null;try{if(this.direct)Y=await this.jsm.direct.getMessage(this.bucketName(),Q);else Y=await this.jsm.streams.getMessage(this.bucketName(),Q);if(Y===null)return null;let G=this.smToEntry(Y);if(G.rawKey!==X)return null;return G}catch(G){throw G}}purge($,Z){return this._deleteOrPurge($,"PURGE",Z)}delete($,Z){return this._deleteOrPurge($,"DEL",Z)}async purgeDeletes($=1800000){let Z=[],X=await this.history({key:">"});await(async()=>{for await(let J of X)if(J.operation==="DEL"||J.operation==="PURGE")Z.push(J)})().then(),X.stop();let Q=Date.now()-$,Y=Z.map((J)=>{let W=this.subjectForKey(J.key);if(J.created.getTime()>=Q)return this.jsm.streams.purge(this.stream,{filter:W,keep:1});else return this.jsm.streams.purge(this.stream,{filter:W,keep:0})}),G=await Promise.all(Y);return G.unshift({success:!0,purged:0}),G.reduce((J,W)=>{return J.purged+=W.purged,J})}async _deleteOrPurge($,Z,X){if(!this.hasWildcards($))return this._doDeleteOrPurge($,Z,X);let Q=await this.keys($),Y=[];for await(let G of Q)if(Y.push(this._doDeleteOrPurge(G,Z)),Y.length===100)await Promise.all(Y),Y.length=0;if(Y.length>0)await Promise.all(Y)}async _doDeleteOrPurge($,Z,X){let Q=this.encodeKey($);this.validateKey(Q);let Y=(0,_5.headers)();if(Y.set(wo1.kvOperationHdr,Z),Z==="PURGE"){let G=X;if(Y.set($5.JsHeaders.RollupHdr,$5.JsHeaders.RollupValueSubject),typeof G?.ttl==="string"&&G.ttl!=="")Y.set($5.PubHeaders.MessageTTL,`${G.ttl}`)}if(X?.previousSeq)Y.set($5.PubHeaders.ExpectedLastSubjectSequenceHdr,`${X.previousSeq}`);await this.js.publish(this.subjectForKey(Q,!0),_5.Empty,{headers:Y})}_buildCC($,Z,X={}){let Y=(!Array.isArray($)?[$]:$).map((W)=>{let K=this.encodeKey(W);return this.validateSearchKey(W),this.fullKeyName(K)}),G=$5.DeliverPolicy.LastPerSubject;if(Z===C5.KvWatchInclude.AllHistory)G=$5.DeliverPolicy.All;if(Z===C5.KvWatchInclude.UpdatesOnly)G=$5.DeliverPolicy.New;let J=void 0;if(Y.length===1)J=Y[0],Y=void 0;return Object.assign({deliver_policy:G,ack_policy:$5.AckPolicy.None,filter_subjects:Y,filter_subject:J,flow_control:!0,idle_heartbeat:(0,_5.nanos)(5000)},X)}remove($){return this.purge($)}async history($={}){let Z=$.key??">",X={};X.headers_only=$.headers_only||!1;let Q=new _5.QueuedIteratorImpl,Y=()=>{Q.stop()},G=this._buildCC(Z,C5.KvWatchInclude.AllHistory,X),J=await this.js.consumers.getPushConsumer(this.stream,G);if(Q._data=J,(await J.info(!0)).num_pending===0)return Q.push(Y),Q;let K=await J.consume({callback:(H)=>{let F=this.jmToWatchEntry(H,!1);if(Q.push(F),Q.received++,H.info.pending===0)Q.push(Y)}});return K.closed().then(()=>{Q.push(Y)}),(async()=>{for await(let H of K.status())switch(H.type){case"heartbeat":Q.push(()=>{Q.stop()});break}})().then(),Q.iterClosed.then(()=>{K.stop()}),Q}canSetWatcherName(){let $=this.js.nc,{ok:Z}=$.features.get(_5.Feature.JS_NEW_CONSUMER_CREATE_API);return Z}async watch($={}){let Z=$.key??">",X=new _5.QueuedIteratorImpl,Q={};Q.headers_only=$.headers_only||!1;let Y=C5.KvWatchInclude.LastValue;if($.include===C5.KvWatchInclude.AllHistory)Y=C5.KvWatchInclude.AllHistory;else if($.include===C5.KvWatchInclude.UpdatesOnly)Y=C5.KvWatchInclude.UpdatesOnly;let G=$.ignoreDeletes===!0,J=this._buildCC(Z,Y,Q);if(J.name=`KV_WATCHER_${_5.nuid.next()}`,$.resumeFromRevision&&$.resumeFromRevision>0)J.deliver_policy=$5.DeliverPolicy.StartSequence,J.opt_start_seq=$.resumeFromRevision;let W=await this.js.consumers.getPushConsumer(this.stream,J),H=(await W.info(!0)).num_pending,F=Y===C5.KvWatchInclude.UpdatesOnly||H===0;X._data=W;let N=0,U=await W.consume({callback:(O)=>{if(!F)N++,F=N>=H;let B=this.jmToWatchEntry(O,F);if(G&&B.operation==="DEL")return;X.push(B),X.received++}});return X.iterClosed.then(()=>{U.stop()}),U.closed().then(()=>{X.push(()=>{X.stop()})}),X}async keys($=">"){let Z=new _5.QueuedIteratorImpl,X=this._buildCC($,C5.KvWatchInclude.LastValue,{headers_only:!0}),Q=await this.js.consumers.getPushConsumer(this.stream,X);if((await Q.info()).num_pending===0)return Z.stop(),Z;Z._data=Q;let G=await Q.consume({callback:(J)=>{let W=J.headers?.get(wo1.kvOperationHdr);if(W!=="DEL"&&W!=="PURGE"){let K=this.decodeKey(J.subject.substring(this.prefixLen));Z.push(K)}if(J.info.pending===0)G.stop()}});return(async()=>{for await(let J of G.status())switch(J.type){case"heartbeat":Z.push(()=>{Z.stop()});break}})().then(),G.closed().then(()=>{Z.push(()=>{Z.stop()})}),Z.iterClosed.then(()=>{G.stop()}),Z}purgeBucket($){return this.jsm.streams.purge(this.bucketName(),$)}destroy(){return this.jsm.streams.delete(this.bucketName())}async status(){let Z=this.js.nc.info?.cluster??"",X=this.bucketName(),Q=await this.jsm.streams.info(X);return new L50(Q,Z)}}wo1.Bucket=Ox;class L50{si;cluster;constructor($,Z=""){this.si=$,this.cluster=Z}get bucket(){return this.si.config.name.startsWith(C5.kvPrefix)?this.si.config.name.substring(C5.kvPrefix.length):this.si.config.name}get values(){return this.si.state.messages}get history(){return this.si.config.max_msgs_per_subject}get ttl(){return(0,_5.millis)(this.si.config.max_age)}get markerTTL(){if(typeof this.si.config.subject_delete_marker_ttl==="number")return(0,_5.millis)(this.si.config.subject_delete_marker_ttl);return 0}get bucket_location(){return this.cluster}get backingStore(){return this.si.config.storage}get storage(){return this.si.config.storage}get replicas(){return this.si.config.num_replicas}get description(){return this.si.config.description??""}get maxBucketSize(){return this.si.config.max_bytes}get maxValueSize(){return this.si.config.max_msg_size}get max_bytes(){return this.si.config.max_bytes}get placement(){return this.si.config.placement||{cluster:"",tags:[]}}get placementCluster(){return this.si.config.placement?.cluster??""}get republish(){return this.si.config.republish??{src:"",dest:""}}get streamInfo(){return this.si}get size(){return this.si.state.bytes}get metadata(){return this.si.config.metadata??{}}get compression(){if(this.si.config.compression)return this.si.config.compression!==$5.StoreCompression.None;return!1}}wo1.KvStatusImpl=L50;class Oo1{bucket;sm;prefixLen;codec;constructor($,Z,X,Q){this.bucket=$,this.prefixLen=Z,this.sm=X,this.codec=Q}get rawKey(){return this.sm.subject.substring(this.prefixLen)}get key(){return this.codec.key.decode(this.rawKey)}get value(){return this.codec.value.decode(this.sm.data)}get delta(){return 0}get created(){return this.sm.time}get revision(){return this.sm.seq}get operation(){if(this.sm.header?.has("Nats-Marker-Reason")){if(this.sm.header?.get("Nats-Marker-Reason")==="MaxAge")return"PURGE"}return this.sm.header?.get(wo1.kvOperationHdr)||"PUT"}get length(){let $=this.sm.header.get($5.JsHeaders.MessageSizeHdr)||"";if($!=="")return parseInt($,10);return this.sm.data.length}json($){return JSON.parse(_5.TD.decode(this.value),$)}string(){return _5.TD.decode(this.value)}}class Bo1{bucket;sm;prefixLen;update;codec;constructor($,Z,X,Q,Y){this.bucket=$,this.prefixLen=Z,this.sm=X,this.update=Q,this.codec=Y}get rawKey(){return this.sm.subject.substring(this.prefixLen)}get key(){return this.codec.key.decode(this.rawKey)}get value(){return this.codec.value.decode(this.sm.data)}get created(){return new Date((0,_5.millis)(this.sm.info.timestampNanos))}get revision(){return this.sm.seq}get operation(){if(this.sm.headers?.has("Nats-Marker-Reason")){if(this.sm.headers?.get("Nats-Marker-Reason")==="MaxAge")return"PURGE"}return this.sm.headers?.get(wo1.kvOperationHdr)||"PUT"}get delta(){return this.sm.info.pending}get length(){let $=this.sm.headers?.get($5.JsHeaders.MessageSizeHdr)||"";if($!=="")return parseInt($,10);return this.sm.data.length}get isUpdate(){return this.update}json($){return JSON.parse(_5.TD.decode(this.value),$)}string(){return _5.TD.decode(this.value)}}});var bu0=_((N3)=>{Object.defineProperty(N3,"__esModule",{value:!0});N3.validateKey=N3.validateBucket=N3.NoopKvCodecs=N3.Kvm=N3.defaultBucketOpts=N3.Bucket=N3.Base64KeyCodec=N3.KvWatchInclude=N3.kvPrefix=void 0;var Eo1=vu0();Object.defineProperty(N3,"kvPrefix",{enumerable:!0,get:function(){return Eo1.kvPrefix}});Object.defineProperty(N3,"KvWatchInclude",{enumerable:!0,get:function(){return Eo1.KvWatchInclude}});var fL=Lo1();Object.defineProperty(N3,"Base64KeyCodec",{enumerable:!0,get:function(){return fL.Base64KeyCodec}});Object.defineProperty(N3,"Bucket",{enumerable:!0,get:function(){return fL.Bucket}});Object.defineProperty(N3,"defaultBucketOpts",{enumerable:!0,get:function(){return fL.defaultBucketOpts}});Object.defineProperty(N3,"Kvm",{enumerable:!0,get:function(){return fL.Kvm}});Object.defineProperty(N3,"NoopKvCodecs",{enumerable:!0,get:function(){return fL.NoopKvCodecs}});Object.defineProperty(N3,"validateBucket",{enumerable:!0,get:function(){return fL.validateBucket}});Object.defineProperty(N3,"validateKey",{enumerable:!0,get:function(){return fL.validateKey}})});var xu0=_((AO)=>{Object.defineProperty(AO,"__esModule",{value:!0});AO.NoopKvCodecs=AO.Kvm=AO.defaultBucketOpts=AO.Bucket=AO.Base64KeyCodec=AO.KvWatchInclude=void 0;var Kn8=bu0();Object.defineProperty(AO,"KvWatchInclude",{enumerable:!0,get:function(){return Kn8.KvWatchInclude}});var am=bu0();Object.defineProperty(AO,"Base64KeyCodec",{enumerable:!0,get:function(){return am.Base64KeyCodec}});Object.defineProperty(AO,"Bucket",{enumerable:!0,get:function(){return am.Bucket}});Object.defineProperty(AO,"defaultBucketOpts",{enumerable:!0,get:function(){return am.defaultBucketOpts}});Object.defineProperty(AO,"Kvm",{enumerable:!0,get:function(){return am.Kvm}});Object.defineProperty(AO,"NoopKvCodecs",{enumerable:!0,get:function(){return am.NoopKvCodecs}})});function E50(){let $=new TextEncoder,Z=new TextDecoder;return{encode:(X)=>$.encode(JSON.stringify(X)),decode:(X)=>JSON.parse(Z.decode(X))}}class gu0{options;kv=null;codec=E50();constructor($){this.options=$}async init(){let $=this.options.getJetStream();if(!$)return;this.kv=await new zo1.Kvm($).create(Fn8,{storage:jo1.StorageType.Memory})}async get($,Z){if(!this.kv)return null;try{let X=await this.kv.get(`${$}.${Z}`);if(!X?.value?.length)return null;if(X.operation==="DEL"||X.operation==="PURGE")return null;return this.codec.decode(X.value)}catch{return null}}async set($,Z,X){if(!this.kv)return;try{await this.kv.put(`${$}.${Z}`,this.codec.encode(X))}catch{}}async invalidate($){if(!this.kv)return;await Promise.all(["tools","resources","prompts"].map(async(X)=>{try{await this.kv.delete(`${X}.${$}`)}catch{}}))}teardown(){this.kv=null}}function Nn8($,Z,X){if(X<=0)return!0;if($===void 0)return!0;return Z-$>=X}function j50($){return $ instanceof D1&&$.code===I1.MethodNotFound}function Un8($){return $ instanceof D1&&$.code===-32000&&/connection closed/i.test($.message)}async function RO($,Z,X,Q,Y,G=0){if(!Q)try{return await X()}catch(H){if(j50(H))return[];return sm.add(1,{type:$,outcome:"error",stage:"no_cache"}),null}let J=`${$}:${Z}`,W=await Q.get($,Z);if(W===null)try{let H=await X();return Q.set($,Z,H).catch(()=>{}),yu0.set(J,Date.now()),sm.add(1,{type:$,outcome:"miss",stage:"miss"}),H}catch(H){if(j50(H))return Q.set($,Z,[]).catch(()=>{}),[];return sm.add(1,{type:$,outcome:"error",stage:"miss"}),null}if(sm.add(1,{type:$,outcome:"hit",stage:"hit"}),Nn8(yu0.get(J),Date.now(),G)&&!z50.has(J)){z50.add(J),yu0.set(J,Date.now());let H=X().then((F)=>Q.set($,Z,F)).catch((F)=>{if(j50(F)||Un8(F)){if(j50(F))Q.set($,Z,[]).catch(()=>{});return}sm.add(1,{type:$,outcome:"error",stage:"revalidation"})}).finally(()=>z50.delete(J));Y?.(H)}return W}function hu0($){Po1=$}function s5(){return Po1}var jo1,zo1,sm,Fn8="DECOCMS_MCP_LISTS",z50,yu0,TO=30000,Po1=null;var VY=w(()=>{r5();f6();jo1=V(bw(),1),zo1=V(xu0(),1),sm=S$.createCounter("mcp_list_cache.fetches",{description:"MCP list cache fetch outcomes (hit, miss, error)",unit:"{fetches}"});z50=new Set;S$.createObservableGauge("mcp_list_cache.pending_revalidations",{description:"In-flight background MCP list revalidations on this pod",unit:"{revalidations}"}).addCallback(($)=>$.observe(z50.size));yu0=new Map});async function uu0($,Z,X){let Q=new AbortController,Y,G=new Promise((W,K)=>{Y=setTimeout(()=>{Q.abort(),K(new Ao1($.id,X))},X)}),J=(async()=>{let W=await F5($,Z,!0);try{return(await W.listTools(void 0,{timeout:X,signal:Q.signal})).tools}finally{await W.close().catch(()=>{})}})();J.catch(()=>{});try{return await Promise.race([J,G])}finally{if(Y)clearTimeout(Y)}}var Ao1;var To1=w(()=>{em();Ao1=class Ao1 extends Error{constructor($,Z){super(`listTools timed out after ${Z}ms for connection ${$}`);this.name="ListToolsTimeoutError"}}});function P50($){return(Z)=>{if(Z instanceof D1&&Z.code===I1.MethodNotFound)return $;throw Z}}var Ro1=w(()=>{r5()});function A50($,Z,X){let Q=IO($,Z,X,s5()??void 0),Y=gD(Q,{name:"studio-mcp-server",version:"1.0.0"},{capabilities:On8,toolCallTimeoutMs:pf});Y.server.setRequestHandler(jU,async()=>{return await Q.listResources().catch(P50({resources:[]}))}),Y.server.setRequestHandler(zU,async()=>{return await Q.listResourceTemplates().catch(P50({resourceTemplates:[]}))}),Y.server.setRequestHandler(PU,async()=>{return await Q.listPrompts().catch(P50({prompts:[]}))});let G=Y.close.bind(Y);return Y.close=async()=>{await G(),await Q.close().catch(()=>{})},Y}var On8;var Io1=w(()=>{_X();r5();$i();VY();Ro1();On8={tools:{},resources:{},prompts:{}}});var HF=w(()=>{em();To1();Io1()});function Zi($,Z,X){if(Z.some((Q)=>Q!=="*"&&Q.startsWith("SELF::"))&&$.SELF===void 0)$.SELF={value:`${X}_self`}}function Xi($,Z){let X=new Map;for(let Q of Z){if(Q==="*")continue;let[Y,G]=O60(Q);if(!Bn8.has(G))continue;let J=Lm(Y,$);if(typeof J!=="object"||J===null||!("value"in J))continue;let W=J.value;if(typeof W!=="string")continue;X.set(`${W}:${G}`,{targetConnectionId:W,scope:G})}return[...X.values()]}async function Qi($,Z,X,Q){for(let G of Z){if(G==="*")continue;let[J]=O60(G),W=Lm(J,$);if(W===void 0||W===null)throw Error(`Scope references key "${J}" but it's not present in state`)}let Y=ql1($,Z);for(let G of Y){if(G.endsWith("_self"))continue;let J=await Q.storage.connections.findById(G);if(!J||J.organization_id!==X)throw Error(`Referenced connection not found: ${G}`);try{await Q.access.check(G)}catch(W){throw Error(`Access denied to referenced connection: ${G}. ${W.message}`)}}}var Bn8;var cu0=w(()=>{dg0();t80();Bn8=new Set([p80,n80])});import{z as qo1}from"zod";var wn8,Dn8,lu0;var Mo1=w(()=>{M4();C0();T$();VY();HF();cu0();pm();VW();wn8=qo1.object({data:F$0.describe("Data for the new connection (id is auto-generated if not provided)")}),Dn8=qo1.object({item:b7.describe("The created connection entity")}),lu0=c({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection. Auto-fetches and caches the server's tool list.",annotations:{title:"Create Connection",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:wn8,outputSchema:Dn8,handler:async($,Z)=>{r(Z);let X=t(Z);await Z.access.check();let Q=G1(Z);if(!Q)throw Error("User ID required to create connection");let Y={...$.data,organization_id:X.id,created_by:Q};if(Y.id){if((await Z.storage.connections.findById(Y.id))?.organization_id===X.id)throw Error("Connection already exists in organization")}if(Y.connection_type==="VIRTUAL"){let N=Ff(Y.connection_url);if(!N)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let U=await Z.storage.virtualMcps.findById(N);if(!U)throw Error(`Virtual MCP not found: ${N}`);if(U.organization_id!==X.id)throw Error("Virtual MCP does not belong to the current organization");Y.connection_url=Nf(N)}if(Y.connection_type==="STDIO"&&!b0().localMode)throw Error("STDIO connections are only available in local mode (--local-mode).");let G=await jO({id:`pending-${Date.now()}`,title:Y.title,connection_type:Y.connection_type,connection_url:Y.connection_url,connection_token:Y.connection_token,connection_headers:Y.connection_headers}).catch(()=>null),J=G?.tools?.length?G.tools:null,W=G?.scopes?.length?G.scopes:Y.configuration_scopes??null,K=Y.configuration_state??null;if(K&&W?.length)Zi(K,W,X.id),await Qi(K,W,X.id,Z);let H=await Z.storage.connections.createNew({...Y,tools:null,configuration_state:K,configuration_scopes:W}),F=K&&W?.length?Xi(K,W):[];if(F.length>0){let N;try{await Z.storage.connectionCredentialVault.replaceGrantsForSubject({organizationId:X.id,subjectConnectionId:H.id,createdBy:Q,grants:F});let{plaintextToken:U,record:O}=await Z.storage.connectionCredentialVault.createOrRotateWorkloadToken({organizationId:X.id,subjectConnectionId:H.id});N=O.id,await(await F5(H,Z,!1)).callTool({name:"ON_MCP_CONFIGURATION",arguments:{state:K,scopes:W,firstRun:!0,vault:{baseUrl:Z.baseUrl,org:X.slug??X.id,subjectConnectionId:H.id,token:U}}})}catch(U){if(N)await Z.storage.connectionCredentialVault.revokeWorkloadToken({organizationId:X.id,subjectConnectionId:H.id,tokenId:N});throw await Z.storage.connections.delete(H.id),U}}if(J)s5()?.set("tools",H.id,J).catch(()=>{});return y1.capture({distinctId:Q,event:"connection_created",groups:{organization:X.id},properties:{connection_id:H.id,connection_type:H.connection_type,app_name:H.app_name??null,organization_id:X.id,tools_count:J?.length??0}}),{item:H}}})});import{z as fG}from"zod/v4";import{z as ko1}from"zod/v4";import{z as T50}from"zod/v4";import{z as sW}from"zod/v4";import{z as zn8}from"zod/v4";import{z as bL}from"zod/v4";import{z as eW}from"zod/v4";import{z as CZ}from"zod/v4";import{z as Vo1}from"zod/v4";import{z as q50}from"zod/v4";import{z as dn8}from"zod/v4";import{z as So1}from"zod/v4";import{z as R50}from"zod/v4";import{z as sn8}from"zod/v4";function Yi($,Z){if($===Z)return!0;if($==null||Z==null)return $===Z;if(typeof $!==typeof Z)return!1;if(Array.isArray($)&&Array.isArray(Z)){if($.length!==Z.length)return!1;return $.every((X,Q)=>Yi(X,Z[Q]))}if(typeof $==="object"&&typeof Z==="object"){let X=Object.keys($),Q=Object.keys(Z);if(X.length!==Q.length)return!1;return X.every((Y)=>Q.includes(Y)&&Yi($[Y],Z[Y]))}return!1}function un8(){return($)=>{if(!Array.isArray($))return!0;let Z=[];return $.every((X)=>{if(Z.some((Y)=>Yi(X,Y)))return!1;return Z.push(X),!0})}}function I50($,Z){return $.safeParse(Z).success}function H7($){if(typeof $==="boolean")return $?fG.any():fG.never();let Z={};for(let Y of Xt8)Y.apply(Z,$);let X=[];if(Z.string!==!1)X.push(Z.string||fG.string());if(Z.number!==!1)X.push(Z.number||fG.number());if(Z.boolean!==!1)X.push(Z.boolean||fG.boolean());if(Z.null!==!1)X.push(Z.null||fG.null());if(Z.array!==!1)X.push(Z.array||fG.array(fG.any()));if(Z.tuple!==!1&&Z.tuple!==void 0)X.push(Z.tuple);if(Z.object!==!1)if(Z.object)X.push(Z.object);else{let Y=fG.custom((G)=>{return typeof G==="object"&&G!==null&&!Array.isArray(G)},"Must be an object, not an array");X.push(Y)}if(Z.file!==!1&&Z.file!==void 0)X.push(Z.file);let Q;if(X.length===0)Q=fG.never();else if(X.length===1)Q=X[0];else if(!Object.keys($).some((G)=>G!=="$schema"&&G!=="title"&&G!=="description"))Q=fG.any();else Q=fG.union(X);for(let Y of Qt8)Q=Y.apply(Q,$);return Q}var Ln8=class{apply($,Z){if(!Z.type)return;let X=Array.isArray(Z.type)?Z.type:[Z.type],Q=new Set(X);if(!Q.has("string"))$.string=!1;if(!Q.has("number")&&!Q.has("integer"))$.number=!1;if(!Q.has("boolean"))$.boolean=!1;if(!Q.has("null"))$.null=!1;if(!Q.has("array"))$.array=!1;if(!Q.has("object"))$.object=!1;if(Q.has("integer")&&$.number!==!1){let Y=$.number||ko1.number();if(Y instanceof ko1.ZodNumber)$.number=Y.int()}}},En8=class{apply($,Z){if(Z.const===void 0)return;let X=Z.const;if($.string=!1,$.number=!1,$.boolean=!1,$.null=!1,$.array=!1,$.object=!1,typeof X==="string")$.string=T50.literal(X);else if(typeof X==="number")$.number=T50.literal(X);else if(typeof X==="boolean")$.boolean=T50.literal(X);else if(X===null)$.null=T50.null();else if(Array.isArray(X))$.array=void 0;else if(typeof X==="object")$.object=void 0}},jn8=class{apply($,Z){if(!Z.enum)return;if(Z.enum.length===0){if(!Z.type)$.string=!1,$.number=!1,$.boolean=!1,$.null=!1,$.array=!1,$.object=!1;return}let X={string:Z.enum.filter((Q)=>typeof Q==="string"),number:Z.enum.filter((Q)=>typeof Q==="number"),boolean:Z.enum.filter((Q)=>typeof Q==="boolean"),null:Z.enum.filter((Q)=>Q===null),array:Z.enum.filter((Q)=>Array.isArray(Q)),object:Z.enum.filter((Q)=>typeof Q==="object"&&Q!==null&&!Array.isArray(Q))};$.string=this.createTypeSchema(X.string,"string"),$.number=this.createTypeSchema(X.number,"number"),$.boolean=this.createTypeSchema(X.boolean,"boolean"),$.null=X.null.length>0?sW.null():!1,$.array=X.array.length>0?void 0:!1,$.object=X.object.length>0?void 0:!1}createTypeSchema($,Z){if($.length===0)return!1;if($.length===1)return sW.literal($[0]);if(Z==="string")return sW.enum($);if(Z==="number"){let[X,Q,...Y]=$;return sW.union([sW.literal(X),sW.literal(Q),...Y.map((G)=>sW.literal(G))])}if(Z==="boolean")return sW.union([sW.literal(!0),sW.literal(!1)]);return!1}},Pn8=class{apply($,Z){let X=Z;if(X.type==="string"&&X.format==="binary"&&X.contentEncoding==="binary"){let Q=zn8.file();if(X.minLength!==void 0)Q=Q.min(X.minLength);if(X.maxLength!==void 0)Q=Q.max(X.maxLength);if(X.contentMediaType!==void 0)Q=Q.mime(X.contentMediaType);$.file=Q,$.string=!1}}},An8=class{apply($,Z){let X=Z;if(Z.type===void 0&&(X.minLength!==void 0||X.maxLength!==void 0||X.pattern!==void 0)){if($.string===void 0)$.string=bL.string()}}},Tn8=class{apply($,Z){let X=Z;if(X.minLength===void 0)return;if($.string!==!1){let Q=$.string||bL.string();if(Q instanceof bL.ZodString)$.string=Q.refine((Y)=>{return Array.from(Y).length>=X.minLength},{message:`String must be at least ${X.minLength} characters long`})}}},Rn8=class{apply($,Z){let X=Z;if(X.maxLength===void 0)return;if($.string!==!1){let Q=$.string||bL.string();if(Q instanceof bL.ZodString)$.string=Q.refine((Y)=>{return Array.from(Y).length<=X.maxLength},{message:`String must be at most ${X.maxLength} characters long`})}}},In8=class{apply($,Z){let X=Z;if(!X.pattern)return;if($.string!==!1){let Q=$.string||bL.string();if(Q instanceof bL.ZodString){let Y=new RegExp(X.pattern);$.string=Q.regex(Y)}}}},qn8=class{apply($,Z){let X=Z;if(X.minimum===void 0)return;if($.number!==!1){let Q=$.number||eW.number();if(Q instanceof eW.ZodNumber)$.number=Q.min(X.minimum)}}},Mn8=class{apply($,Z){let X=Z;if(X.maximum===void 0)return;if($.number!==!1){let Q=$.number||eW.number();if(Q instanceof eW.ZodNumber)$.number=Q.max(X.maximum)}}},kn8=class{apply($,Z){let X=Z;if(X.exclusiveMinimum===void 0)return;if($.number!==!1){let Q=$.number||eW.number();if(Q instanceof eW.ZodNumber)if(typeof X.exclusiveMinimum==="number")$.number=Q.gt(X.exclusiveMinimum);else $.number=!1}}},Vn8=class{apply($,Z){let X=Z;if(X.exclusiveMaximum===void 0)return;if($.number!==!1){let Q=$.number||eW.number();if(Q instanceof eW.ZodNumber)if(typeof X.exclusiveMaximum==="number")$.number=Q.lt(X.exclusiveMaximum);else $.number=!1}}},Sn8=class{apply($,Z){let X=Z;if(X.multipleOf===void 0)return;if($.number!==!1){let Q=$.number||eW.number();if(Q instanceof eW.ZodNumber)$.number=Q.refine((Y)=>{if(X.multipleOf===0)return!1;let G=Y/X.multipleOf,J=Math.round(G),W=Math.min(Math.abs(Y)*Number.EPSILON*10,Math.abs(X.multipleOf)*Number.EPSILON*10);return Math.abs(G-J)<=W/Math.abs(X.multipleOf)},{message:`Must be a multiple of ${X.multipleOf}`})}}},Cn8=class{apply($,Z){let X=Z;if(Z.type===void 0&&(X.minItems!==void 0||X.maxItems!==void 0||X.items!==void 0||X.prefixItems!==void 0)){if($.array===void 0)$.array=CZ.array(CZ.any())}}},_n8=class{apply($,Z){let X=Z;if(X.minItems===void 0)return;if($.array!==!1)$.array=($.array||CZ.array(CZ.any())).min(X.minItems)}},vn8=class{apply($,Z){let X=Z;if(X.maxItems===void 0)return;if($.array!==!1)$.array=($.array||CZ.array(CZ.any())).max(X.maxItems)}},fn8=class{apply($,Z){let X=Z;if($.array===!1)return;if(Array.isArray(X.items))$.array=$.array||CZ.array(CZ.any());else if(X.items&&typeof X.items!=="boolean"&&!X.prefixItems){let Q=H7(X.items),Y=CZ.array(Q);if($.array&&$.array instanceof CZ.ZodArray){let G=$.array._def;if(G.checks)G.checks.forEach((J)=>{if(J._zod&&J._zod.def){let W=J._zod.def;if(W.check==="min_length"&&W.minimum!==void 0)Y=Y.min(W.minimum);else if(W.check==="max_length"&&W.maximum!==void 0)Y=Y.max(W.maximum)}})}$.array=Y}else if(typeof X.items==="boolean"&&X.items===!1)if(!X.prefixItems)$.array=CZ.array(CZ.any()).max(0);else $.array=$.array||CZ.array(CZ.any());else if(typeof X.items==="boolean"&&X.items===!0)$.array=$.array||CZ.array(CZ.any());else if(X.prefixItems)$.array=$.array||CZ.array(CZ.any())}},bn8=class{apply($,Z){if(Z.type!=="array")return;let X=Z;if(!Array.isArray(X.items))return;if($.array===!1)return;let Q=X.items.map((G)=>H7(G)),Y;if(Q.length===0)Y=Vo1.tuple([]);else Y=Vo1.tuple(Q);if(X.minItems!==void 0&&X.minItems>Q.length)Y=!1;if(X.maxItems!==void 0&&X.maxItems<Q.length)Y=!1;$.tuple=Y,$.array=!1}},xn8=class{apply($,Z){let X=Z;if($.object===!1)return;if(X.properties||X.required||X.additionalProperties!==void 0)$.object=$.object||q50.object({}).passthrough()}},yn8=class{apply($,Z){let X=Z;if(Z.type===void 0&&(X.maxProperties!==void 0||X.minProperties!==void 0)){if($.object===void 0)$.object=q50.object({}).passthrough()}}},gn8=class{apply($,Z){let X=Z;if(X.maxProperties===void 0)return;if($.object!==!1){let Q=$.object||q50.object({}).passthrough();$.object=Q.refine((Y)=>Object.keys(Y).length<=X.maxProperties,{message:`Object must have at most ${X.maxProperties} properties`})}}},hn8=class{apply($,Z){let X=Z;if(X.minProperties===void 0)return;if($.object!==!1){let Q=$.object||q50.object({}).passthrough();$.object=Q.refine((Y)=>Object.keys(Y).length>=X.minProperties,{message:`Object must have at least ${X.minProperties} properties`})}}},cn8=class{apply($,Z){if(!Z.not)return $;let X=H7(Z.not);return $.refine((Q)=>!I50(X,Q),{message:"Value must not match the 'not' schema"})}},ln8=class{apply($,Z){if(Z.uniqueItems!==!0)return $;return $.refine(un8(),{message:"Array items must be unique"})}},mn8=class{apply($,Z){if(!Z.allOf||Z.allOf.length===0)return $;return Z.allOf.map((Q)=>H7(Q)).reduce((Q,Y)=>dn8.intersection(Q,Y),$)}},in8=class{apply($,Z){if(!Z.anyOf||Z.anyOf.length===0)return $;let X=Z.anyOf.length===1?H7(Z.anyOf[0]):So1.union([H7(Z.anyOf[0]),H7(Z.anyOf[1]),...Z.anyOf.slice(2).map((Q)=>H7(Q))]);return So1.intersection($,X)}},pn8=class{apply($,Z){if(!Z.oneOf||Z.oneOf.length===0)return $;let X=Z.oneOf.map((Q)=>H7(Q));return $.refine((Q)=>{let Y=0;for(let G of X)if(G.safeParse(Q).success){if(Y++,Y>1)return!1}return Y===1},{message:"Value must match exactly one of the oneOf schemas"})}},nn8=class{apply($,Z){let X=Z;if(X.prefixItems&&Array.isArray(X.prefixItems)){let Y=X.prefixItems.map((G)=>H7(G));return $.refine((G)=>{if(!Array.isArray(G))return!0;for(let J=0;J<Math.min(G.length,Y.length);J++)if(!I50(Y[J],G[J]))return!1;if(G.length>Y.length){if(typeof X.items==="boolean"&&X.items===!1)return!1;else if(X.items&&typeof X.items==="object"&&!Array.isArray(X.items)){let J=H7(X.items);for(let W=Y.length;W<G.length;W++)if(!I50(J,G[W]))return!1}}return!0},{message:"Array does not match prefixItems schema"})}return $}},tn8=class{apply($,Z){let X=Z;if(!X.properties&&!X.required&&X.additionalProperties!==!1)return $;if($ instanceof R50.ZodObject||$ instanceof R50.ZodRecord){let Q={};if(X.properties){for(let[Y,G]of Object.entries(X.properties))if(G!==void 0)Q[Y]=H7(G)}if(X.required&&Array.isArray(X.required)){let Y=new Set(X.required);for(let G of Object.keys(Q))if(!Y.has(G))Q[G]=Q[G].optional()}else for(let Y of Object.keys(Q))Q[Y]=Q[Y].optional();if(X.additionalProperties===!1)return R50.object(Q);else return R50.object(Q).passthrough()}return $.refine((Q)=>{if(typeof Q!=="object"||Q===null||Array.isArray(Q))return!0;if(X.properties){for(let[Y,G]of Object.entries(X.properties))if(G!==void 0){if(Object.getOwnPropertyDescriptor(Q,Y)!==void 0){if(!H7(G).safeParse(Q[Y]).success)return!1}}}if(X.required&&Array.isArray(X.required)){for(let Y of X.required)if(Object.getOwnPropertyDescriptor(Q,Y)===void 0)return!1}if(X.additionalProperties===!1&&X.properties){let Y=new Set(Object.keys(X.properties));for(let G in Q)if(!Y.has(G))return!1}return!0},{message:"Object constraints validation failed"})}},on8=class{apply($,Z){if(!Z.enum||Z.enum.length===0)return $;let X=Z.enum.filter((Q)=>Array.isArray(Q)||typeof Q==="object"&&Q!==null);if(X.length===0)return $;return $.refine((Q)=>{if(typeof Q!=="object"||Q===null)return!0;return X.some((Y)=>Yi(Q,Y))},{message:"Value must match one of the enum values"})}},rn8=class{apply($,Z){if(Z.const===void 0)return $;let X=Z.const;if(typeof X!=="object"||X===null)return $;return $.refine((Q)=>Yi(Q,X),{message:"Value must equal the const value"})}},an8=class{apply($,Z){if(Z.description)$=$.describe(Z.description);return $}},en8=class{apply($,Z){var X;let Q=Z;if(!((X=Q.required)==null?void 0:X.includes("__proto__"))||Z.type!==void 0)return $;return sn8.any().refine((Y)=>this.validateRequired(Y,Q.required),{message:"Missing required properties"})}validateRequired($,Z){if(typeof $!=="object"||$===null||Array.isArray($))return!0;return Z.every((X)=>Object.prototype.hasOwnProperty.call($,X))}},$t8=class{apply($,Z){var X;let Q=Z;if(Q.contains===void 0)return $;let Y=H7(Q.contains),G=(X=Q.minContains)!=null?X:1,J=Q.maxContains;return $.refine((W)=>{if(!Array.isArray(W))return!0;let K=0;for(let H of W)if(I50(Y,H))K++;if(K<G)return!1;if(J!==void 0&&K>J)return!1;return!0},{message:"Array must contain required items matching the schema"})}},Zt8=class{apply($,Z){let{default:X}=Z;if(X===void 0)return $;if(!$.safeParse(X).success)return $;return $.default(X)}},Xt8,Qt8;var Co1=w(()=>{Xt8=[new En8,new jn8,new Ln8,new Pn8,new An8,new Cn8,new yn8,new Tn8,new Rn8,new In8,new qn8,new Mn8,new kn8,new Vn8,new Sn8,new bn8,new _n8,new vn8,new fn8,new gn8,new hn8,new xn8],Qt8=[new en8,new on8,new rn8,new mn8,new in8,new pn8,new nn8,new tn8,new $t8,new cn8,new ln8,new Zt8,new an8]});class du0{constructor($){this._url=$}start(){if(this._socket)throw Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise(($,Z)=>{this._socket=new WebSocket(this._url,Yt8),this._socket.onerror=(X)=>{let Q="error"in X?X.error:Error(`WebSocket error: ${JSON.stringify(X)}`);Z(Q),this.onerror?.(Q)},this._socket.onopen=()=>{$()},this._socket.onclose=()=>{this.onclose?.()},this._socket.onmessage=(X)=>{let Q;try{Q=zY.parse(JSON.parse(X.data))}catch(Y){this.onerror?.(Y);return}this.onmessage?.(Q)}})}async close(){this._socket?.close()}send($){return new Promise((Z,X)=>{if(!this._socket){X(Error("Not connected"));return}this._socket?.send(JSON.stringify($)),Z()})}}var Yt8="mcp";var _o1=w(()=>{r5()});function Gt8($){let Z=$;if(!Z||typeof Z!=="object"||!("method"in Z))return null;switch(Z.method){case"initialize":{let X=Z?.params?.protocolVersion;if(!X)return null;return{type:"emit",message:{result:{protocolVersion:X,capabilities:{tools:{}},serverInfo:{name:"deco-chat-server",version:"1.0.0"}},jsonrpc:Z.jsonrpc??"2.0",id:Z.id}}}case"notifications/roots/list_changed":case"notifications/initialized":case"notifications/cancelled":case"notifications/progress":return{type:"suppress"};default:return null}}var M50;var mu0=w(()=>{ff();M50=class M50 extends xW{constructor($,Z){super($,Z)}send($,Z){let X=Gt8($);if(X?.type==="emit")return this.onmessage?.(X.message),Promise.resolve();if(X?.type==="suppress")return Promise.resolve();return super.send($,Z)}}});var vo1,fo1=async($,Z,X)=>{let Q=Jt8($.connection,Z,X);if(!Q)throw Error("Unknown MCP connection type");let Y=new vo1({name:$?.name??"MCP Client",version:"1.0.0"});return await Y.connect(Q),{client:Y}},Jt8=($,Z,X)=>{if($.type==="Websocket")return new du0(new URL($.url));if($.type!=="SSE"&&$.type!=="HTTP")return null;let Y={...$.token?{authorization:`Bearer ${$.token}`}:{},...X??{},..."headers"in $?$.headers||{}:{}};if($.type==="SSE"){let G={requestInit:{headers:Y,signal:Z}};if($.token)G.eventSourceInit={fetch:(J,W)=>{return fetch(J,{...W,headers:{...Y,Accept:"text/event-stream"},signal:Z})}};return new aH(new URL($.url),G)}return new M50(new URL($.url),{requestInit:{headers:Y,signal:Z,credentials:"include"}})};var bo1=w(()=>{fW();tl();_o1();r5();_X();mu0();vo1=class vo1 extends b9{constructor($,Z){super($,{jsonSchemaValidator:H5,...Z})}async listTools($,Z){return await this.request({method:"tools/list",params:$},Hl,Z)}}});function Kt8($,Z){if(xL.set($,Z),xL.size>Wt8){let X=xL.keys().next().value;if(X!==void 0)xL.delete(X)}}function go1($){let Z=(X)=>{if("connection"in $)return fo1({connection:$.connection},void 0,X);return $.client};return new Proxy({},{get(X,Q){if(Q==="toJSON")return null;if(typeof Q!=="string")throw Error("Name must be a string");if(Q==="listTools")return W;async function Y(K,H=Q){let F=$?.debugId?.(),N=F?{"x-trace-debug-id":F}:void 0,{client:U}=await Z(N),{structuredContent:O,isError:B,content:D}=await U.callTool({name:String(H),arguments:K});if(B){let E=D?.[0]?.text,j=typeof E==="string"?xo1(E):null,z=j?.code&&typeof $?.getErrorByStatusCode==="function"?$.getErrorByStatusCode(j.code,j.message,j.traceId):null;if(z)throw z;throw Error(`Tool ${String(H)} returned an error: ${JSON.stringify(O??D)}`)}if(O!==void 0)return O;let L=D?.[0]?.text;return typeof L==="string"?xo1(L):void 0}async function G(){let{client:K}=await Z(),{tools:H}=await K.listTools();return H}async function J(){if(!("connection"in $))return G();let K=$.connection,H=JSON.stringify(K);try{if(!xL.has(H))Kt8(H,G());return await xL.get(H)}catch(F){console.error("Failed to list tools",F),xL.delete(H);return}}async function W(){return(await J()??[]).map((H)=>yo1(H,Y))}return Y.asTool=async()=>{let H=(await J()??[]).find((F)=>F.name===Q);if(!H)throw Error(`Tool ${Q} not found`);return yo1(H,Y)},Y}})}var xo1=($)=>{try{return JSON.parse($)}catch{return $}},Wt8=500,xL,yo1=($,Z)=>{return{...$,id:$.name,inputSchema:$.inputSchema?H7($.inputSchema):void 0,outputSchema:$.outputSchema?H7($.outputSchema):void 0,execute:(X)=>{return Z(X.context,$.name)}}};var ho1=w(()=>{Co1();bo1();xL=new Map});function qO($){return go1($)}var Bx;var iu0=w(()=>{ho1();Bx=new Proxy({},{get($,Z){if(Z==="toJSON")return null;if(Z==="forConnection")return(X)=>qO({connection:X});if(Z==="forClient")return(X)=>qO({client:X});return globalThis[Z]}})});function k50($){return{isImplementedBy:(Z)=>{for(let X of $){let Q=typeof X.name==="string"?new RegExp(`^${X.name}$`):X.name,Y=Z.find((G)=>Q.test(G.name));if(!Y&&X.opt)continue;if(!Y)return!1}return!0}}}var $K=($)=>{return{...k50($),forClient:(Z)=>{return qO({client:Z})},forConnection:(Z)=>{return qO({connection:Z})}}};var yL=w(()=>{iu0()});import{z as v5}from"zod";var uo1,V50,co1,S50,lo1,Ht8;var do1=w(()=>{yL();uo1=v5.object({specversion:v5.literal("1.0").describe("CloudEvents specification version"),id:v5.string().describe("Unique identifier for this event (UUID recommended)"),source:v5.string().describe("Connection ID of the event publisher"),type:v5.string().describe("Event type (e.g., 'order.created', 'user.signup')"),time:v5.string().datetime().optional().describe("Timestamp of when the event occurred (ISO 8601)"),subject:v5.string().optional().describe("Subject/resource identifier (e.g., order ID, user ID)"),datacontenttype:v5.string().optional().default("application/json").describe("Content type of the data attribute"),dataschema:v5.string().url().optional().describe("URI to the schema for the data attribute"),data:v5.unknown().optional().describe("Event payload (any JSON value)")}),V50=v5.object({events:v5.array(uo1).min(1).describe("Batch of CloudEvents to process")}),co1=v5.object({success:v5.boolean().optional().describe("Whether this event was processed successfully"),error:v5.string().optional().describe("Error message for this event"),retryAfter:v5.number().int().positive().optional().describe("Re-deliver this event after this many ms")}),S50=v5.object({success:v5.boolean().optional().describe("Batch success - applies to events not in results"),error:v5.string().optional().describe("Batch error message - applies to events not in results"),processedCount:v5.number().int().min(0).optional().describe("Number of events successfully processed"),retryAfter:v5.number().int().positive().optional().describe("Batch retryAfter - applies to events not in results"),results:v5.record(v5.string(),co1).optional().describe("Per-event results keyed by event ID")}),lo1=[{name:"ON_EVENTS",inputSchema:V50,outputSchema:S50}],Ht8=$K(lo1)});import{z as f5}from"zod";var mo1,io1,po1,no1,to1,oo1,C50,pu0;var nu0=w(()=>{yL();mo1=f5.object({type:f5.literal("string"),enum:f5.array(f5.string()).optional(),description:f5.string().optional()}),io1=f5.object({type:f5.string(),description:f5.string(),paramsSchema:f5.record(f5.string(),mo1)}),po1=f5.object({}),no1=f5.object({triggers:f5.array(io1)}),to1=f5.object({type:f5.string(),params:f5.record(f5.string(),f5.string()),enabled:f5.boolean(),callbackUrl:f5.url().optional(),callbackToken:f5.string().min(1).optional()}),oo1=f5.object({success:f5.boolean()}),C50=[{name:"TRIGGER_LIST",inputSchema:po1,outputSchema:no1},{name:"TRIGGER_CONFIGURE",inputSchema:to1,outputSchema:oo1}],pu0=$K(C50)});import{z as I$}from"zod";var Ft8,Nt8,Ut8,Ot8,Bt8,wt8,Dt8,Lt8,Et8,jt8,zt8,Pt8,gL;var Gi=w(()=>{Ft8=I$.object({prefix:I$.string().optional().describe("Filter objects by prefix (e.g., 'folder/' for folder contents)"),maxKeys:I$.number().optional().default(1000).describe("Maximum number of keys to return (default: 1000)"),continuationToken:I$.string().optional().describe("Token for pagination from previous response"),delimiter:I$.string().optional().describe("Delimiter for grouping keys (typically '/'). When set, commonPrefixes returns folder paths.")}),Nt8=I$.object({objects:I$.array(I$.object({key:I$.string().describe("Object key/path"),size:I$.number().describe("Object size in bytes"),lastModified:I$.string().describe("Last modified timestamp"),etag:I$.string().describe("Entity tag for the object")})),nextContinuationToken:I$.string().optional().describe("Token for fetching next page of results"),isTruncated:I$.boolean().describe("Whether there are more results available"),commonPrefixes:I$.array(I$.string()).optional().describe("Folder paths when delimiter is used (e.g., ['photos/2024/', 'photos/2025/'])")}),Ut8=I$.object({key:I$.string().describe("Object key/path to get metadata for")}),Ot8=I$.object({contentType:I$.string().optional().describe("MIME type of the object"),contentLength:I$.number().describe("Size of the object in bytes"),lastModified:I$.string().describe("Last modified timestamp"),etag:I$.string().describe("Entity tag for the object"),metadata:I$.record(I$.string(),I$.string()).optional().describe("Custom metadata key-value pairs")}),Bt8=I$.object({key:I$.string().describe("Object key/path to generate URL for"),expiresIn:I$.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)")}),wt8=I$.object({url:I$.string().describe("Presigned URL for downloading the object"),expiresIn:I$.number().describe("Expiration time in seconds that was used")}),Dt8=I$.object({key:I$.string().describe("Object key/path for the upload"),expiresIn:I$.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)"),contentType:I$.string().optional().describe("MIME type for the object being uploaded")}),Lt8=I$.object({url:I$.string().describe("Presigned URL for uploading the object"),expiresIn:I$.number().describe("Expiration time in seconds that was used")}),Et8=I$.object({key:I$.string().describe("Object key/path to delete")}),jt8=I$.object({success:I$.boolean().describe("Whether the deletion was successful"),key:I$.string().describe("The key that was deleted")}),zt8=I$.object({keys:I$.array(I$.string()).max(1000).describe("Array of object keys/paths to delete (max 1000)")}),Pt8=I$.object({deleted:I$.array(I$.string()).describe("Array of successfully deleted keys"),errors:I$.array(I$.object({key:I$.string(),message:I$.string()})).describe("Array of errors for failed deletions")}),gL=[{name:"LIST_OBJECTS",inputSchema:Ft8,outputSchema:Nt8},{name:"GET_OBJECT_METADATA",inputSchema:Ut8,outputSchema:Ot8},{name:"GET_PRESIGNED_URL",inputSchema:Bt8,outputSchema:wt8},{name:"PUT_PRESIGNED_URL",inputSchema:Dt8,outputSchema:Lt8},{name:"DELETE_OBJECT",inputSchema:Et8,outputSchema:jt8},{name:"DELETE_OBJECTS",inputSchema:zt8,outputSchema:Pt8}]});import{z as D6}from"zod";var ro1,ao1,so1,Ji,_50,v50,f50,b50,At8;var tu0=w(()=>{yL();ro1=D6.object({primary:D6.string().optional().describe("Primary brand color (hex)"),secondary:D6.string().optional().describe("Secondary brand color (hex)"),accent:D6.string().optional().describe("Accent / highlight color (hex)"),background:D6.string().optional().describe("Background color (hex)"),foreground:D6.string().optional().describe("Foreground / text color (hex)")}),ao1=D6.object({heading:D6.string().optional().describe("Font family for headings"),body:D6.string().optional().describe("Font family for body text"),code:D6.string().optional().describe("Font family for code / monospace")}),so1=D6.object({logo:D6.string().optional().describe("Logo URL"),favicon:D6.string().optional().describe("Favicon URL"),ogImage:D6.string().optional().describe("Open Graph image URL")}),Ji=D6.object({id:D6.string(),name:D6.string().describe("Brand / company name"),domain:D6.string().optional().describe("Company domain (e.g. example.com)"),colors:ro1.optional().describe("Semantic color palette"),fonts:ao1.optional().describe("Font families by role"),assets:so1.optional().describe("Visual identity assets"),overview:D6.string().optional().describe("Company overview / description"),tagline:D6.string().optional().describe("Brand tagline"),tone:D6.string().optional().describe("Tone of voice description"),metadata:D6.record(D6.string(),D6.unknown()).optional().describe("Extra design tokens and metadata")}),_50=D6.object({id:D6.string().optional().describe("Brand ID. Omit to get the default brand.")}),v50=D6.object({}),f50=D6.object({items:D6.array(Ji)}),b50=[{name:"BRAND_GET",inputSchema:_50,outputSchema:Ji},{name:"BRAND_LIST",inputSchema:v50,outputSchema:f50,opt:!0}],At8=$K(b50)});var ou0=w(()=>{yL();do1();nu0();Gi();tu0()});import{z as D8}from"zod";function FF($){return D8.object({items:D8.array($).describe("Array of collection items"),totalCount:D8.number().int().min(0).optional().describe("Total number of matching items (if available)"),hasMore:D8.boolean().optional().describe("Whether there are more items available")})}function Ki($){return D8.object({item:$.nullable().describe("The retrieved item, or null if not found")})}function It8($){return D8.object({data:$.partial().describe("Data for the new entity (id may be auto-generated)")})}function qt8($){return D8.object({item:$.describe("The created entity with generated id")})}function Mt8($){return D8.object({id:D8.string().describe("ID of the entity to update"),data:$.partial().describe("Partial entity data to update")})}function kt8($){return D8.object({item:$.describe("The updated entity")})}function Fi($){return D8.object({item:$.describe("The deleted entity")})}function y50($,Z,X){let Q=$.toUpperCase(),Y=X?.readOnly??!1,G=[{name:`COLLECTION_${Q}_LIST`,inputSchema:U3,outputSchema:FF(Z)},{name:`COLLECTION_${Q}_GET`,inputSchema:Wi,outputSchema:Ki(Z)}];if(!Y)G.push({name:`COLLECTION_${Q}_CREATE`,inputSchema:It8(Z),outputSchema:qt8(Z),opt:!0},{name:`COLLECTION_${Q}_UPDATE`,inputSchema:Mt8(Z),outputSchema:kt8(Z),opt:!0},{name:`COLLECTION_${Q}_DELETE`,inputSchema:Hi,outputSchema:Fi(Z),opt:!0});return G}var x50,Tt8,eo1,Rt8,U3,Wi,Hi;var bG=w(()=>{x50=D8.object({id:D8.string().describe("Unique identifier for the entity"),title:D8.string().describe("Human-readable title for the entity"),description:D8.string().nullish().describe("Description of the entity"),created_at:D8.string().datetime(),updated_at:D8.string().datetime(),created_by:D8.string().optional(),updated_by:D8.string().optional()}),Tt8=D8.object({field:D8.array(D8.string()),operator:D8.enum(["eq","gt","gte","lt","lte","in","like","contains"]),value:D8.unknown()}),eo1=D8.lazy(()=>D8.union([Tt8,D8.object({operator:D8.enum(["and","or","not"]),conditions:D8.array(eo1)})])),Rt8=D8.object({field:D8.array(D8.string()),direction:D8.enum(["asc","desc"]),nulls:D8.enum(["first","last"]).optional()}),U3=D8.object({where:eo1.optional().describe("Filter expression"),orderBy:D8.array(Rt8).optional().describe("Sort expressions"),limit:D8.number().int().min(1).max(1000).optional().describe("Maximum number of items to return"),offset:D8.number().int().min(0).optional().describe("Number of items to skip")});Wi=D8.object({id:D8.string().describe("ID of the entity to retrieve")});Hi=D8.object({id:D8.string().describe("ID of the entity to delete")})});import{z as wx}from"zod";var Vt8,St8,$r1;var Zr1=w(()=>{bG();Vt8=x50.extend({avatar:wx.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:wx.string().describe("System prompt that defines the assistant's behavior"),virtual_mcp_id:wx.string().describe("Virtual MCP ID to use for this assistant"),model:wx.object({id:wx.string().describe("Model ID"),connectionId:wx.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),St8=y50("assistant",Vt8),$r1=[...St8]});import{z as H0}from"zod";var Ni,NF,Qr1,Ct8,_t8,Yr1,vt8,ft8,bt8,xt8,yt8,gt8,Gr1,ht8,ut8,ct8,lt8,dt8,mt8,it8,pt8,nt8,tt8,Q45,ot8,Y45,Xr1,rt8,at8,g50,G45;var Jr1=w(()=>{yL();bG();Ni=H0.lazy(()=>H0.union([H0.null(),H0.string(),H0.number(),H0.boolean(),H0.record(H0.string(),Ni),H0.array(Ni)])),NF=H0.record(H0.string(),H0.record(H0.string(),Ni)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),Qr1=H0.object({type:H0.literal("text"),text:H0.string().describe("The text content"),providerOptions:NF}),Ct8=H0.object({type:H0.literal("text"),text:H0.string().describe("The text content"),providerMetadata:H0.any().optional().describe("Additional provider-specific metadata")}),_t8=H0.string().describe("File data as URL string"),Yr1=H0.object({type:H0.literal("file"),filename:H0.string().optional().describe("Optional filename of the file"),data:_t8,mediaType:H0.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:NF}),vt8=H0.object({type:H0.literal("file"),mediaType:H0.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),data:H0.string().describe("Generated file data as base64 encoded string")}),ft8=H0.object({type:H0.literal("reasoning"),text:H0.string().describe("The reasoning text"),providerOptions:NF}),bt8=H0.object({type:H0.literal("reasoning"),text:H0.string().describe("The reasoning text"),providerMetadata:H0.any().optional().describe("Additional provider-specific metadata")}),xt8=H0.object({type:H0.literal("tool-call"),toolCallId:H0.string().describe("ID of the tool call, used to match with tool result"),toolName:H0.string().describe("Name of the tool being called"),input:H0.string().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:H0.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:NF}),yt8=H0.object({type:H0.literal("tool-call"),toolCallId:H0.string().describe("ID of the tool call"),toolName:H0.string().describe("Name of the tool being called"),input:H0.string().describe("Stringified JSON object with the tool call arguments"),providerExecuted:H0.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerMetadata:H0.any().optional().describe("Additional provider-specific metadata")}),gt8=H0.union([H0.object({type:H0.literal("text"),value:H0.string()}),H0.object({type:H0.literal("json"),value:Ni}),H0.object({type:H0.literal("error-text"),value:H0.string()}),H0.object({type:H0.literal("error-json"),value:Ni}),H0.object({type:H0.literal("content"),value:H0.array(H0.union([H0.object({type:H0.literal("text"),text:H0.string().describe("Text content")}),H0.object({type:H0.literal("media"),data:H0.string().describe("Base-64 encoded media data"),mediaType:H0.string().describe("IANA media type")})]))}),H0.object({type:H0.literal("execution-denied"),reason:H0.string().optional()}),H0.string().describe("Raw or JSON-serialized output (e.g. from AI SDK mapToolResultOutput)")]),Gr1=H0.object({type:H0.literal("tool-result"),toolCallId:H0.string().describe("ID of the tool call that this result is associated with"),toolName:H0.string().describe("Name of the tool that generated this result"),output:gt8.describe("Result of the tool call"),result:H0.unknown().describe("Unknown result of the tool call"),providerOptions:NF}),ht8=H0.object({type:H0.literal("tool-result"),toolCallId:H0.string().describe("ID of the tool call that this result is associated with"),toolName:H0.string().describe("Name of the tool that generated this result"),result:H0.any().describe("Result of the tool call (JSON-serializable)"),isError:H0.boolean().optional().describe("Whether the result is an error or error message"),providerExecuted:H0.boolean().optional().describe("Whether the tool result was generated by the provider"),providerMetadata:H0.any().optional().describe("Additional provider-specific metadata")}),ut8=H0.union([H0.object({type:H0.literal("source"),sourceType:H0.literal("url"),id:H0.string().describe("The ID of the source"),url:H0.string().describe("The URL of the source"),title:H0.string().optional().describe("The title of the source"),providerMetadata:H0.any().optional().describe("Additional provider-specific metadata")}),H0.object({type:H0.literal("source"),sourceType:H0.literal("document"),id:H0.string().describe("The ID of the source"),mediaType:H0.string().describe("IANA media type of the document (e.g., application/pdf)"),title:H0.string().describe("The title of the document"),filename:H0.string().optional().describe("Optional filename of the document"),providerMetadata:H0.any().optional().describe("Additional provider-specific metadata")})]),ct8=H0.object({role:H0.literal("system"),content:H0.string().describe("System message content"),providerOptions:NF}),lt8=H0.object({role:H0.literal("user"),content:H0.array(H0.union([Qr1,Yr1])).describe("User message content parts (text or file)"),providerOptions:NF}),dt8=H0.object({role:H0.literal("assistant"),content:H0.array(H0.union([Qr1,Yr1,ft8,xt8,Gr1])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:NF}),mt8=H0.object({role:H0.literal("tool"),content:H0.array(Gr1).describe("Tool message content (tool results)"),providerOptions:NF}),it8=H0.union([ct8,lt8,dt8,mt8]),pt8=H0.array(it8).describe("A list of messages forming the prompt"),nt8=H0.object({prompt:pt8.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:H0.number().optional().describe("Maximum number of tokens to generate"),temperature:H0.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:H0.number().optional().describe("Nucleus sampling parameter"),topK:H0.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:H0.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:H0.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:H0.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:H0.array(H0.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:H0.union([H0.object({type:H0.literal("text")}),H0.object({type:H0.literal("json"),schema:H0.any().optional().describe("JSON schema that the generated output should conform to"),name:H0.string().optional().describe("Name of output that should be generated"),description:H0.string().optional().describe("Description of the output that should be generated")})]).optional().describe("Response format. The output can either be text or JSON. Default is text"),tools:H0.array(H0.any()).optional().describe("The tools that are available for the model"),toolChoice:H0.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:H0.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:H0.any().optional().describe("Abort signal for cancelling the operation"),providerOptions:H0.any().optional().describe("Additional provider-specific options")}),tt8=H0.object({content:H0.array(H0.union([Ct8,vt8,bt8,yt8,ht8,ut8])).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:H0.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:H0.looseObject({inputTokens:H0.number().optional(),outputTokens:H0.number().optional(),totalTokens:H0.number().optional(),reasoningTokens:H0.number().optional()}).describe("Usage information for the language model call"),providerMetadata:H0.any().optional().describe("Additional provider-specific metadata"),request:H0.object({body:H0.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:H0.object({id:H0.string().optional().describe("ID for the generated response"),timestamp:H0.iso.datetime().optional().describe("Timestamp for the start of the generated response"),modelId:H0.string().optional().describe("The ID of the response model that was used"),headers:H0.record(H0.string(),H0.string()).optional().describe("Response headers"),body:H0.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:H0.array(H0.any()).describe("Warnings for the call, e.g. unsupported settings")}),Q45=H0.object({stream:H0.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:H0.object({body:H0.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:H0.object({headers:H0.record(H0.string(),H0.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),ot8=H0.object({supportedUrls:H0.record(H0.string(),H0.array(H0.string())).describe("Supported URL patterns by media type for the provider")}),Y45=H0.object({modelId:H0.string().describe("The ID of the model"),logo:H0.string().nullable(),description:H0.string().nullable(),capabilities:H0.array(H0.string()),limits:H0.object({contextWindow:H0.number(),maxOutputTokens:H0.number()}).nullable(),costs:H0.object({input:H0.number(),output:H0.number()}).nullable(),provider:H0.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),Xr1=H0.object({modelId:H0.string().describe("The ID of the model"),callOptions:nt8}),rt8=x50.extend({logo:H0.string().nullable(),description:H0.string().nullable(),capabilities:H0.array(H0.string()),limits:H0.object({contextWindow:H0.number(),maxOutputTokens:H0.number()}).nullable(),costs:H0.object({input:H0.number(),output:H0.number()}).nullable(),provider:H0.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),at8=y50("llm",rt8,{readOnly:!0}),g50=[{name:"LLM_METADATA",inputSchema:H0.object({modelId:H0.string().describe("The ID of the model")}),outputSchema:ot8},{name:"LLM_DO_STREAM",inputSchema:Xr1},{name:"LLM_DO_GENERATE",inputSchema:Xr1,outputSchema:tt8},...at8],G45=$K(g50)});import{z as hL}from"zod";var st8,Wr1;var Kr1=w(()=>{st8=hL.object({scopes:hL.array(hL.string()).describe("List of scopes available"),stateSchema:hL.record(hL.string(),hL.unknown()).describe("JSON Schema (draft-07) defining the state structure")}),Wr1=[{name:"MCP_CONFIGURATION",inputSchema:hL.object({}),outputSchema:st8}]});import{z as b5}from"zod";var et8,$o8,Hr1;var Fr1=w(()=>{et8=b5.object({}).strict(),$o8=b5.object({billing:b5.object({mode:b5.enum(["prepaid","postpaid"]),limitPeriod:b5.enum(["daily","weekly","monthly"]).nullable()}),limit:b5.object({total:b5.number().nullable(),remaining:b5.number().nullable(),reset:b5.string().nullable()}),usage:b5.object({total:b5.number(),daily:b5.number(),weekly:b5.number(),monthly:b5.number()}),alert:b5.object({enabled:b5.boolean(),threshold_usd:b5.number(),email:b5.string().nullable()}),connectionId:b5.string()}),Hr1=[{name:"GATEWAY_USAGE",inputSchema:et8,outputSchema:$o8},{name:"GATEWAY_SET_LIMIT",inputSchema:b5.object({}),outputSchema:b5.object({}),opt:!0},{name:"GATEWAY_SET_ALERT",inputSchema:b5.object({}),outputSchema:b5.object({}),opt:!0}]});import{z as Nr1}from"zod";function O3(){return LY()===null}function h50($,Z){return $===l4.DEV_ASSETS(Z)}function Dx($,Z){let X=fx1(Z,$),Q=new Date().toISOString();return{id:X.id??l4.DEV_ASSETS($),title:X.title,description:X.description??null,icon:X.icon??null,app_name:X.app_name??null,app_id:X.app_id??null,organization_id:$,created_by:"system",created_at:Q,updated_at:Q,connection_type:X.connection_type,connection_url:X.connection_url??null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:X.metadata??null,tools:Zo8,bindings:["OBJECT_STORAGE"],status:"active"}}var Zo8;var Lx=w(()=>{TD();Gi();U8();Zo8=gL.map(($)=>({name:$.name,description:`${$.name} operation for local file storage`,inputSchema:Nr1.toJSONSchema($.inputSchema),outputSchema:Nr1.toJSONSchema($.outputSchema)}))});function Ur1($,Z){return $||Z===0}function Or1($,Z,X,Q,Y){let G=Z?Y+1:Y,J=Z?$.slice(0,X):$,W=Q+X<G;return{items:J,totalCount:G,hasMore:W}}function Xo8($,Z){if(Z.length===0)return;let[X,...Q]=Z,Y=X==="slug"?bU($):$[X];for(let G of Q){if(Y===null||typeof Y!=="object")return;Y=Y[G]}return Y}function Qo8($){let X=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/%/g,".*").replace(/_/g,".");return new RegExp(`^${X}$`,"i")}function Yo8($,Z,X){if($===void 0)return!0;switch(Z){case"eq":return X===null?$===null:$===X;case"gt":return $>X;case"gte":return $>=X;case"lt":return $<X;case"lte":return $<=X;case"in":return Array.isArray(X)&&X.includes($);case"like":return typeof $==="string"&&Qo8(String(X)).test($);case"contains":return String($).toLowerCase().includes(String(X).toLowerCase());default:return!0}}function Ui($,Z){if(!Z)return!0;if("conditions"in Z){let{operator:Q,conditions:Y}=Z;if(Y.length===0)return!0;switch(Q){case"and":return Y.every((G)=>Ui($,G));case"or":return Y.some((G)=>Ui($,G));case"not":return!Y.every((G)=>Ui($,G));default:return!0}}let X=Xo8($,Z.field);return Yo8(X,Z.operator,Z.value)}var Br1=w(()=>{d80()});async function wr1($,Z,X){if($.length===0)return;let Q=0;async function Y(){while(Q<$.length){let G=Q++;await X($[G])}}await Promise.all(Array.from({length:Math.min(Z,$.length)},()=>Y()))}import{z as MO}from"zod";var Go8=8,Jo8,Wo8,Ko8,Ho8,ru0;var Dr1=w(()=>{ou0();Zr1();bG();Jr1();Kr1();Gi();Fr1();U8();C0();v9();VY();HF();Lx();VW();d80();Br1();Jo8=[{name:/^(COLLECTION_REGISTRY_APP_LIST|REGISTRY_ITEM_LIST)$/,inputSchema:MO.object({})}],Wo8={LLM:g50,LLMS:g50,ASSISTANTS:$r1,MCP:Wr1,OBJECT_STORAGE:gL,AI_GATEWAY_BILLING:Hr1,TRIGGER:C50,REGISTRY:Jo8,BRAND:b50},Ko8=U3.extend({binding:MO.union([MO.array(MO.object({}).passthrough()),MO.object({}).passthrough(),MO.string()]).optional(),include_virtual:MO.boolean().optional().describe("Whether to include VIRTUAL connections in the results. Defaults to false."),slug:MO.string().optional().describe("Filter by connection slug. Matches against app_name, or a slug derived from connection_url or title.")}),Ho8=FF(b7),ru0=c({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",annotations:{title:"List Connections",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:Ko8,outputSchema:Ho8,handler:async($,Z)=>{await Z.access.check();let X=t(Z),Q=$.binding?typeof $.binding==="string"?(()=>{let N=Wo8[$.binding.toUpperCase()];if(!N)throw Error(`Unknown binding: ${$.binding}`);return N})():$.binding:void 0,Y=Q?k50(Q):void 0,G=!!Y,J=$.limit??100,W=$.offset??0,{items:K,totalCount:H}=await Z.storage.connections.list(X.id,{includeVirtual:$.include_virtual??!1,slug:$.slug,where:$.where,orderBy:$.orderBy,limit:G?void 0:J,offset:G?void 0:W});if(Y){let N=s5(),U=l4.SELF(X.id);await wr1(K,Go8,async(O)=>{if(O.tools!==null)return;let B=O.id===U?async()=>{let{listManagementTools:L}=await Promise.resolve().then(() => (kO(),u50));return L(Z)}:()=>uu0(O,Z,m80),D=await RO("tools",O.id,B,N,(L)=>Z.pendingRevalidations.push(L),TO);if(D!==null)O.tools=D})}let F=!1;if(O3()&&Ur1(G,W)){let N=_9(),U=l4.DEV_ASSETS(X.id);if(!K.some((O)=>O.id===U)){let O=Dx(X.id,N),B=!$.slug||bU(O)===$.slug,D=Ui(O,$.where);if(B&&D)K.unshift(O),F=!0}}if(G){let N=(await Promise.all(K.map(async(D)=>{if(!D.tools||D.tools.length===0)return null;return Y.isImplementedBy(D.tools.map((E)=>({name:E.name,inputSchema:E.inputSchema,outputSchema:E.outputSchema})))?D:null}))).filter((D)=>D!==null),U=N.length,O=N.slice(W,W+J),B=W+J<U;return{items:O,totalCount:U,hasMore:B}}return Or1(K,F,J,W,H)}})});var Fo8,au0;var Lr1=w(()=>{bG();U8();C0();v9();VY();HF();Lx();VW();Fo8=Ki(b7),au0=c({name:"COLLECTION_CONNECTIONS_GET",description:"Get a connection's configuration, tools list, and status by ID.",annotations:{title:"Get Connection",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},_meta:{ui:{visibility:["app"]}},inputSchema:Wi,outputSchema:Fo8,handler:async($,Z)=>{let X=t(Z);if(await Z.access.check(),O3()&&h50($.id,X.id))return{item:Dx(X.id,_9())};let Q=await Z.storage.connections.findById($.id);if(!Q||Q.organization_id!==X.id)return{item:null};if(Q.tools===null){let Y=l4.SELF(X.id),G=Q.id===Y?async()=>{let{listManagementTools:W}=await Promise.resolve().then(() => (kO(),u50));return W(Z)}:async()=>{let W=await F5(Q,Z,!0);try{return(await W.listTools()).tools}finally{await W.close().catch(()=>{})}},J=await RO("tools",Q.id,G,s5(),(W)=>Z.pendingRevalidations.push(W),TO);if(J!==null)Q.tools=J}return{item:Q}}})});class u6{db;vault;constructor($,Z){this.db=$;this.vault=Z}async get($){let Z=await this.db.selectFrom("downstream_tokens").selectAll().where("connectionId","=",$).executeTakeFirst();if(!Z)return null;return this.decryptToken(Z)}async upsert($){let Z=new Date().toISOString(),X=await this.vault.encrypt($.accessToken),Q=$.refreshToken?await this.vault.encrypt($.refreshToken):null,Y=$.clientSecret?await this.vault.encrypt($.clientSecret):null,G=$.expiresAt?.toISOString()??null,J=await this.db.insertInto("downstream_tokens").values({id:m8("dtok"),connectionId:$.connectionId,accessToken:X,refreshToken:Q,scope:$.scope,expiresAt:G,clientId:$.clientId,clientSecret:Y,tokenEndpoint:$.tokenEndpoint,createdAt:Z,updatedAt:Z}).onConflict((W)=>W.column("connectionId").doUpdateSet({accessToken:X,refreshToken:Q,scope:$.scope,expiresAt:G,clientId:$.clientId,clientSecret:Y,tokenEndpoint:$.tokenEndpoint,updatedAt:Z})).returning(["id","createdAt"]).executeTakeFirstOrThrow();return{id:J.id,connectionId:$.connectionId,accessToken:$.accessToken,refreshToken:$.refreshToken,scope:$.scope,expiresAt:$.expiresAt,createdAt:J.createdAt,updatedAt:Z,clientId:$.clientId,clientSecret:$.clientSecret,tokenEndpoint:$.tokenEndpoint}}async delete($){await this.db.deleteFrom("downstream_tokens").where("connectionId","=",$).execute()}isExpired($,Z=0){if(!$.expiresAt)return!1;let Q=($.expiresAt instanceof Date?$.expiresAt:new Date($.expiresAt)).getTime();if(Number.isNaN(Q))return!0;return Q-Z<Date.now()}async decryptToken($){let Z=await this.vault.decrypt($.accessToken),X=$.refreshToken?await this.vault.decrypt($.refreshToken):null,Q=$.clientSecret?await this.vault.decrypt($.clientSecret):null;return{id:$.id,connectionId:$.connectionId,accessToken:Z,refreshToken:X,scope:$.scope,expiresAt:$.expiresAt,createdAt:$.createdAt,updatedAt:$.updatedAt,clientId:$.clientId,clientSecret:Q,tokenEndpoint:$.tokenEndpoint}}}var xG=w(()=>{vX()});function Ex(...$){if(Bo8)console.log("[mcp-read-cache]",...$)}function wo8($){return $.kind==="org"?"org":`u:${$.userId}`}function su0($){if($===null||typeof $!=="object")return JSON.stringify($)??"null";if(Array.isArray($))return`[${$.map(su0).join(",")}]`;return`{${Object.keys($).sort().map((X)=>`${JSON.stringify(X)}:${su0($[X])}`).join(",")}}`}class d50{config;maxEntries;now;maxTotalBytes;store=new Map;revalidating=new Set;totalBytes=0;constructor($=No8,Z=Uo8,X=()=>Date.now(),Q=Oo8){this.config=$;this.maxEntries=Z;this.now=X;this.maxTotalBytes=Q}stats(){return{entries:this.store.size,bytes:this.totalBytes}}deleteKey($){let Z=this.store.get($);if(Z)this.store.delete($),this.totalBytes-=Z.bytes}key($,Z,X,Q){return`${Z}:${wo8(X)}:${$}:${su0(Q)}`}storeSet($,Z,X,Q){let Y;try{Y=JSON.stringify(Z).length}catch{Ex("SKIP non-serializable",$);return}if(Y>Q){Ex("SKIP oversize",$,`${Y}b > cap ${Q}b`);return}this.deleteKey($);while(this.store.size>0&&(this.store.size>=this.maxEntries||this.totalBytes+Y>this.maxTotalBytes)){let G=this.store.keys().next().value;if(G===void 0)break;this.deleteKey(G)}this.store.set($,{value:Z,storedAt:X,bytes:Y}),this.totalBytes+=Y}async fetch($){let{type:Z,connectionId:X,scope:Q,params:Y,fetchLive:G,shouldCache:J,onRevalidation:W}=$,K=this.config[Z],H=this.key(Z,X,Q,Y),F=this.now(),N=this.store.get(H),U=N?F-N.storedAt:1/0;if(!N||U>K.maxStaleMs){c50.add(1,{type:Z,outcome:"miss"}),Ex(N?"EXPIRED":"MISS",H);let O=await G();if(J?.(O)??!0)this.storeSet(H,O,this.now(),K.maxValueBytes);else Ex("NOT-CACHED (shouldCache=false)",H);return O}if(this.store.delete(H),this.store.set(H,N),U>K.revalidateAfterMs&&!this.revalidating.has(H)){c50.add(1,{type:Z,outcome:"stale"}),Ex("STALE \u2192 serve + revalidate",H,`age=${U}ms`),this.revalidating.add(H);let O=G().then((B)=>{if(J?.(B)??!0)this.storeSet(H,B,this.now(),K.maxValueBytes)}).catch(()=>{c50.add(1,{type:Z,outcome:"error"})}).finally(()=>this.revalidating.delete(H));W?.(O)}else c50.add(1,{type:Z,outcome:"hit"}),Ex("HIT",H,`age=${U}ms`);return N.value}invalidate($){let Z=`${$}:`;for(let X of[...this.store.keys()])if(X.startsWith(Z))this.deleteKey(X)}}function $c0(){return b0().mcpCacheEnabled}function m50(){return $c0()?eu0:null}var c50,l50=1024,Er1,No8,Uo8=2000,Oo8,Bo8,eu0;var Oi=w(()=>{f6();T$();c50=S$.createCounter("mcp_read_cache.fetches",{description:"MCP read cache outcomes (hit, stale, miss, error)",unit:"{fetches}"}),Er1=l50*l50,No8={"tools/call":{revalidateAfterMs:30000,maxStaleMs:300000,maxValueBytes:512*l50},"resources/read":{revalidateAfterMs:60000,maxStaleMs:300000,maxValueBytes:4*Er1},"prompts/get":{revalidateAfterMs:60000,maxStaleMs:300000,maxValueBytes:512*l50}},Oo8=256*Er1,Bo8=typeof process<"u"&&!!process.env?.MCP_CACHE_DEBUG;eu0=new d50;S$.createObservableGauge("mcp_read_cache.entries",{description:"Current entry count in the per-pod MCP read cache",unit:"{entries}"}).addCallback(($)=>$.observe(eu0.stats().entries));S$.createObservableGauge("mcp_read_cache.bytes",{description:"Approximate total bytes held in the per-pod MCP read cache",unit:"By"}).addCallback(($)=>$.observe(eu0.stats().bytes))});function Pr1($){m50()?.invalidate($)}function jx($){Pr1($);let Z=Zc0?.();if(!Z)return;try{Z.publish(jr1,Do8.encode(JSON.stringify({connectionId:$,originId:zr1})))}catch(X){console.warn("[McpCacheInvalidation] publish failed (non-critical):",X)}}function Ar1($){if(Zc0=$,Bi)return;let Z=$();if(!Z)return;Bi=Z.subscribe(jr1),(async()=>{for await(let X of Bi)try{let Q=JSON.parse(Lo8.decode(X.data));if(Q.originId===zr1)continue;Pr1(Q.connectionId)}catch{}})().catch(console.error)}function Tr1(){Bi?.unsubscribe(),Bi=null,Zc0=void 0}var jr1="studio.mcp-cache.invalidate",zr1,Do8,Lo8,Zc0,Bi=null;var wi=w(()=>{Oi();zr1=crypto.randomUUID(),Do8=new TextEncoder,Lo8=new TextDecoder});import{z as Xc0}from"zod";function jo8($){let Z={...$};for(let X of Eo8)delete Z[X];return Z}function zo8($,Z){return $.connection_url!==void 0?$.connection_url:Z}function To8($,Z){return $.length===Z.length&&$.every((X,Q)=>X===Z[Q])}var Eo8,Po8,Ao8,Qc0;var Rr1=w(()=>{HF();xG();C0();T$();VY();wi();cu0();pm();VW();Eo8=["id","organization_id","created_by","created_at"];Po8=Xc0.object({id:Xc0.string().describe("ID of the connection to update"),data:N$0.describe("Partial connection data to update")}),Ao8=Xc0.object({item:b7.describe("The updated connection entity")});Qc0=c({name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update a connection's configuration. Re-fetches tools from the server on URL change.",annotations:{title:"Update Connection",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:Po8,outputSchema:Ao8,handler:async($,Z)=>{r(Z);let X=t(Z);await Z.access.check();let Q=G1(Z);if(!Q)throw Error("User ID required to update connection");let{id:Y}=$,G=jo8($.data),J=G.configuration_state!==void 0||G.configuration_scopes!==void 0,W=await Z.storage.connections.findById(Y);if(!W||W.organization_id!==X.id)throw Error("Connection not found in organization");let K=G.connection_type??W.connection_type,H=zo8(G,W.connection_url);if(K==="VIRTUAL"){let f=Ff(H);if(!f)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let x=await Z.storage.virtualMcps.findById(f);if(!x)throw Error(`Virtual MCP not found: ${f}`);if(x.organization_id!==X.id)throw Error("Virtual MCP does not belong to the current organization");H=Nf(f)}let F=G.configuration_state??W.configuration_state??{},N=G.configuration_scopes??W.configuration_scopes??[];if(J){if(G.configuration_state!==void 0)F=G.configuration_state??{};else if(F===null||F===void 0)F={};if(G.configuration_scopes!==void 0)N=G.configuration_scopes??[];if(N.length>0){let f=F;Zi(f,N,X.id),await Qi(f,N,X.id,Z)}}if(K==="STDIO"&&!b0().localMode)throw Error("STDIO connections are only available in local mode (--local-mode).");let U=G.connection_token??W.connection_token;if(!U)try{let x=await new u6(Z.db,Z.vault).get(Y);if(x?.accessToken)U=x.accessToken}catch{}let O=await jO({id:W.id,title:G.title??W.title,connection_type:K,connection_url:H,connection_token:U,connection_headers:G.connection_headers??W.connection_headers}).catch(()=>null),B=O?.tools?.length?O.tools:null,D=!1;if(G.configuration_scopes===void 0&&O?.scopes?.length)D=!To8(N,O.scopes),N=O.scopes;if(Zi(F,N,X.id),D&&N.length>0)await Qi(F,N,X.id,Z);let L=J||D,E=L?Xi(F,N):[],j=L?Xi(W.configuration_state??{},W.configuration_scopes??[]):[],z=W.configuration_state,A=z==null||Object.keys(z).length===0,P,M,q=async()=>{try{await Z.storage.connectionCredentialVault.replaceGrantsForSubject({organizationId:X.id,subjectConnectionId:Y,createdBy:Q,grants:j})}catch(f){console.error("Failed to restore credential grants after credential vault mutation failed",f)}},k={...G,connection_url:H,tools:null,configuration_state:F,configuration_scopes:N,updated_by:Q},C={...W,...k};if(L)try{if(await Z.storage.connectionCredentialVault.replaceGrantsForSubject({organizationId:X.id,subjectConnectionId:Y,createdBy:Q,grants:E}),E.length>0){if(!await Z.storage.connectionCredentialVault.findActiveWorkloadToken({organizationId:X.id,subjectConnectionId:Y})){let{plaintextToken:x,record:n}=await Z.storage.connectionCredentialVault.createOrRotateWorkloadToken({organizationId:X.id,subjectConnectionId:Y});M=n.id,P={baseUrl:Z.baseUrl,org:X.slug??X.id,subjectConnectionId:Y,token:x}}}}catch(f){if(M)await Z.storage.connectionCredentialVault.revokeWorkloadToken({organizationId:X.id,subjectConnectionId:Y,tokenId:M});throw await q(),f}if(L&&F&&N)try{await(await F5(C,Z,!1)).callTool({name:"ON_MCP_CONFIGURATION",arguments:{state:F,scopes:N,firstRun:A,...P?{vault:P}:{}}})}catch(f){if(console.error("Failed to invoke ON_MCP_CONFIGURATION callback",f),M)throw await Z.storage.connectionCredentialVault.revokeWorkloadToken({organizationId:X.id,subjectConnectionId:Y,tokenId:M}),await q(),f}let l;try{l=await Z.storage.connections.update(Y,k)}catch(f){if(L){if(M)await Z.storage.connectionCredentialVault.revokeWorkloadToken({organizationId:X.id,subjectConnectionId:Y,tokenId:M});await q()}throw f}if(B)s5()?.set("tools",Y,B).catch(()=>{});return jx(Y),{item:l}}})});import{z as Ro8}from"zod";var Io8,Yc0;var Ir1=w(()=>{bG();M4();C0();VY();wi();VW();Io8=Hi.extend({force:Ro8.boolean().optional().describe("If true, removes this connection from all agents that reference it before deleting")}),Yc0=c({name:"COLLECTION_CONNECTIONS_DELETE",description:"Permanently delete a connection. Set force=true to auto-remove from referencing Virtual MCPs.",annotations:{title:"Delete Connection",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:Io8,outputSchema:Fi(b7),handler:async($,Z)=>{r(Z);let X=t(Z);await Z.access.check();let Q=await Z.storage.connections.findById($.id);if(!Q)throw Error(`Connection not found: ${$.id}`);if(Q.organization_id!==X.id)throw Error("Connection not found in organization");if(Q.metadata?.isFixed===!0)throw Error("This connection is a fixed system connection and cannot be deleted");let G=await Z.storage.virtualMcps.listByConnectionId(X.id,$.id);if(G.length>0)if($.force)await Z.storage.virtualMcps.removeConnectionReferences($.id);else throw Error(JSON.stringify({code:"CONNECTION_IN_USE",agentNames:G.map((K)=>K.title)}));await Z.storage.connections.delete($.id);let J=await Z.storage.organizationSettings.get(X.id);if(J?.registry_config){let{registries:K,blockedMcps:H}=J.registry_config;if($.id in K){let{[$.id]:F,...N}=K;await Z.storage.organizationSettings.upsert(X.id,{registry_config:{registries:N,blockedMcps:H}})}}s5()?.invalidate($.id).catch(()=>{}),jx($.id);let W=G1(Z);if(W)y1.capture({distinctId:W,event:"connection_deleted",groups:{organization:X.id},properties:{connection_id:Q.id,connection_type:Q.connection_type,app_name:Q.app_name??null,organization_id:X.id,forced:$.force??!1}});return{item:Q}}})});import{z as zx}from"zod";var Gc0;var qr1=w(()=>{C0();Gc0=c({name:"CONNECTION_TEST",description:"Test connection health and latency",annotations:{title:"Test Connection",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},inputSchema:zx.object({id:zx.string()}),outputSchema:zx.object({id:zx.string(),healthy:zx.boolean(),latencyMs:zx.number()}),handler:async($,Z)=>{let X=t(Z);await Z.access.check();let Q=await Z.storage.connections.findById($.id);if(!Q||Q.organization_id!==X.id)throw Error("Connection not found");let Y=await Z.storage.connections.testConnection($.id);return{id:$.id,...Y}}})});var Mr1=w(()=>{Mo1();Dr1();Lr1();Rr1();Ir1();qr1()});import{sql as k4}from"kysely";import{z as ZK}from"zod";function kr1($){if($===null||$===void 0)return"NULL";if(typeof $==="number")return String($);if(typeof $==="boolean")return $?"TRUE":"FALSE";if(typeof $==="string")return`'${$.replace(/'/g,"''")}'`;if($ instanceof Date)return`'${$.toISOString()}'`;return`'${JSON.stringify($).replace(/'/g,"''")}'`}function ko8($,Z){let X=$;for(let Y=Z.length;Y>=1;Y--){let G=`$${Y}`;if(X.includes(G))X=X.replaceAll(G,kr1(Z[Y-1]))}let Q=[];for(let Y=0;Y<X.length;Y++)if(X[Y]==="?")Q.push(Y);for(let Y=Math.min(Q.length,Z.length)-1;Y>=0;Y--){let G=Q[Y],J=kr1(Z[Y]);X=X.slice(0,G)+J+X.slice(G+1)}return X}function Vr1($){return $.replace(/-/g,"_")}function So8($){return`app_${Vr1($)}`}function Co8($){return`app_role_${Vr1($)}`}function _o8($){if($ instanceof Error){let Z=$.message.toLowerCase(),X=$.code;return X==="3F000"||X==="42704"||X==="22023"||Z.includes("schema")&&Z.includes("does not exist")||Z.includes("role")&&Z.includes("does not exist")}return!1}async function vo8($,Z,X){if(await k4`CREATE SCHEMA IF NOT EXISTS ${k4.id(Z)}`.execute($),!(await k4`
948
948
  SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${X}) as exists
949
949
  `.execute($)).rows[0]?.exists)await k4`CREATE ROLE ${k4.id(X)} NOLOGIN`.execute($);await k4`GRANT ${k4.id(X)} TO CURRENT_USER`.execute($),await k4`GRANT USAGE, CREATE ON SCHEMA ${k4.id(Z)} TO ${k4.id(X)}`.execute($),await k4`GRANT ALL ON ALL TABLES IN SCHEMA ${k4.id(Z)} TO ${k4.id(X)}`.execute($),await k4`GRANT ALL ON ALL SEQUENCES IN SCHEMA ${k4.id(Z)} TO ${k4.id(X)}`.execute($),await k4`ALTER DEFAULT PRIVILEGES IN SCHEMA ${k4.id(Z)} GRANT ALL ON TABLES TO ${k4.id(X)}`.execute($),await k4`ALTER DEFAULT PRIVILEGES IN SCHEMA ${k4.id(Z)} GRANT ALL ON SEQUENCES TO ${k4.id(X)}`.execute($),await k4`REVOKE ALL ON SCHEMA public FROM ${k4.id(X)}`.execute($)}async function fo8($,Z,X,Q){try{return await $.transaction().execute(async(Y)=>{return await k4`SET LOCAL ROLE ${k4.id(X)}`.execute(Y),await k4`SET LOCAL search_path TO ${k4.id(Z)}`.execute(Y),await k4.raw(Q).execute(Y)})}catch(Y){if(_o8(Y))return await vo8($,Z,X),await $.transaction().execute(async(G)=>{return await k4`SET LOCAL ROLE ${k4.id(X)}`.execute(G),await k4`SET LOCAL search_path TO ${k4.id(Z)}`.execute(G),await k4.raw(Q).execute(G)});throw Y}}var Mo8,Vo8,Sr1;var Cr1=w(()=>{C0();Mo8=ZK.object({results:ZK.array(ZK.unknown()).optional(),success:ZK.boolean().optional()});Vo8=ZK.object({sql:ZK.string().describe("The SQL query to run"),params:ZK.array(ZK.any()).describe("The parameters to pass to the SQL query").optional()});Sr1=c({name:"DATABASES_RUN_SQL",description:"Run a SQL query in a connection-scoped isolated schema. Supports SELECT, DDL, and DML.",annotations:{title:"Run SQL Query",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:Vo8,outputSchema:ZK.object({result:ZK.array(Mo8)}),handler:async($,Z)=>{r(Z),await Z.access.check();let X=ko8($.sql,$.params||[]);if(!Z.connectionId)throw Error("Connection context required for database access");console.warn("DATABASES_RUN_SQL invoked",{"tool.deprecation_probe":"DATABASES_RUN_SQL","connection.id":Z.connectionId,"organization.id":Z.organization?.id??null,"user.id":Z.auth.user?.id??null});let Q=So8(Z.connectionId),Y=Co8(Z.connectionId);return{result:[{results:(await fo8(Z.db,Q,Y,X)).rows,success:!0}]}}})});function i50($){let Z=$.access.getRole();if(!kG(Z))throw new QF("Only organization owners and admins can change org-wide pin status")}var Jc0=w(()=>{VG();DL()});async function p50($,Z,X){let Q=[...new Set(X)],Y=await Promise.all(Q.map((J)=>$.storage.connections.findById(J,Z))),G=Q.filter((J,W)=>!Y[W]);if(G.length>0)throw Error(`Connection not found: ${G.join(", ")}`)}function UF($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function n50($){let Z=2166136261;for(let X=0;X<$.length;X++)Z=Math.imul(Z^$.charCodeAt(X),16777619);return`a${(Z>>>0).toString(36).padStart(6,"0").slice(-6)}`}function Di($){if($&&typeof $==="object"&&"gatewayClientId"in $&&typeof $.gatewayClientId==="string")return $.gatewayClientId;return}function Li($,Z){if(!Z)return $;let X=`${n50(Z)}_`;return $.startsWith(X)?$.slice(X.length):$}function xo8($){return $.split(/[-_]/).map((Z)=>Z?Z.charAt(0).toUpperCase()+Z.slice(1):Z).join(" ")}var Px;var _r1=w(()=>{fW();Px=class Px extends b9{static MAX_PAGES_PER_CLIENT=1000;clients;slugToKey=new Map;resolvedClients=new Map;toolsCache=null;resourcesCache=null;resourceTemplatesCache=null;promptsCache=null;resourceRouteMap=new Map;constructor($,Z){super(Z?.clientInfo??{name:"gateway-client",version:"1.0.0"},{capabilities:Z?.capabilities});this.clients=$;for(let X of Object.keys($)){let Q=n50(X);if(this.slugToKey.has(Q))throw Error(`GatewayClient: duplicate namespace code "${Q}" from keys "${this.slugToKey.get(Q)}" and "${X}"`);this.slugToKey.set(Q,X)}}namespace($,Z){return`${n50($)}_${Z}`}async resolveToolTarget($){let Z=$.indexOf("_");if(Z!==-1){let Q=$.slice(0,Z),Y=this.slugToKey.get(Q);if(Y)return[Y,$.slice(Z+1)]}let{tools:X}=await this.listTools();for(let Q of X){let Y=Di(Q._meta);if(!Y)continue;if(Li(Q.name,Y)===$)return[Y,$]}if(Z===-1)throw Error(`GatewayClient: could not resolve tool "${$}" \u2014 no namespace prefix and not found in any client`);throw Error(`GatewayClient: unknown namespace "${$.slice(0,Z)}" in "${$}" and not found by original name in any client`)}async resolvePromptTarget($){let Z=$.indexOf("_");if(Z!==-1){let Q=$.slice(0,Z),Y=this.slugToKey.get(Q);if(Y)return[Y,$.slice(Z+1)]}let{prompts:X}=await this.listPrompts();for(let Q of X){let Y=Di(Q._meta);if(!Y)continue;if(Li(Q.name,Y)===$)return[Y,$]}if(Z===-1)throw Error(`GatewayClient: could not resolve prompt "${$}" \u2014 no namespace prefix and not found in any client`);throw Error(`GatewayClient: unknown namespace "${$.slice(0,Z)}" in "${$}" and not found by original name in any client`)}resolveClient($){let Z=this.resolvedClients.get($);if(Z)return Z;let X=this.clients[$];if(!X)return Promise.reject(Error(`GatewayClient: unknown client key "${$}"`));let Q=X.client,Y;try{Y=typeof Q==="function"?Promise.resolve(Q()):Promise.resolve(Q)}catch(J){return Promise.reject(J)}let G=Y.catch((J)=>{throw this.resolvedClients.delete($),J});return this.resolvedClients.set($,G),G}getResolvedClient($){return this.resolveClient($)}async listFromClient($,Z,X){try{let Q=await this.resolveClient($);return await Z(Q)}catch(Q){return console.warn(`GatewayClient: skipping ${X} from client "${$}" \u2014 ${Q?.message??Q}`),[]}}async paginate($,Z,X){let Q=[],Y,G=0;do{let J=await X(Y);Q.push(...J.items),Y=J.nextCursor,G++}while(Y&&G<Px.MAX_PAGES_PER_CLIENT);if(Y)console.warn(`GatewayClient: client "${$}" exceeded ${Px.MAX_PAGES_PER_CLIENT} pages listing ${Z} \u2014 truncating`);return Q}fetchAllTools($,Z){return this.paginate(Z,"tools",async(X)=>{let Q=await $.listTools(X?{cursor:X}:void 0);return{items:Q.tools,nextCursor:Q.nextCursor}})}fetchAllResources($,Z){return this.paginate(Z,"resources",async(X)=>{let Q=await $.listResources(X?{cursor:X}:void 0);return{items:Q.resources,nextCursor:Q.nextCursor}})}fetchAllResourceTemplates($,Z){return this.paginate(Z,"resource templates",async(X)=>{let Q=await $.listResourceTemplates(X?{cursor:X}:void 0);return{items:Q.resourceTemplates,nextCursor:Q.nextCursor}})}fetchAllPrompts($,Z){return this.paginate(Z,"prompts",async(X)=>{let Q=await $.listPrompts(X?{cursor:X}:void 0);return{items:Q.prompts,nextCursor:Q.nextCursor}})}listTools($,Z){if(!this.toolsCache)this.toolsCache=this.aggregateTools();return this.toolsCache}async aggregateTools(){let $=[];for(let[Z,X]of Object.entries(this.clients)){let Q=await this.listFromClient(Z,(J)=>this.fetchAllTools(J,Z),"tools"),Y=X.tools,G=Y?new Set(Y):null;for(let J of Q){if(G&&!G.has(J.name))continue;$.push({...J,name:this.namespace(Z,J.name),_meta:{...J._meta??{},gatewayClientId:Z}})}}return{tools:$}}listResources($,Z){if(!this.resourcesCache)this.resourcesCache=this.aggregateResources();return this.resourcesCache}async aggregateResources(){let $=new Set,Z=[],X=new Map;for(let[Q,Y]of Object.entries(this.clients)){let G=await this.listFromClient(Q,(K)=>this.fetchAllResources(K,Q),"resources"),J=Y.resources,W=J?new Set(J):null;for(let K of G){if(W&&!W.has(K.uri)&&!(K.name&&W.has(K.name)))continue;if($.has(K.uri)){console.warn(`GatewayClient: duplicate resource "${K.uri}" from client "${Q}" \u2014 skipping`);continue}$.add(K.uri),X.set(K.uri,Q),Z.push({...K,_meta:{...K._meta??{},gatewayClientId:Q}})}}return this.resourceRouteMap=X,{resources:Z}}listResourceTemplates($,Z){if(!this.resourceTemplatesCache)this.resourceTemplatesCache=this.aggregateResourceTemplates();return this.resourceTemplatesCache}async aggregateResourceTemplates(){let $=new Set,Z=[];for(let[X,Q]of Object.entries(this.clients)){let Y=await this.listFromClient(X,(G)=>this.fetchAllResourceTemplates(G,X),"resource templates");for(let G of Y){if($.has(G.uriTemplate)){console.warn(`GatewayClient: duplicate resource template "${G.uriTemplate}" from client "${X}" \u2014 skipping`);continue}$.add(G.uriTemplate),Z.push({...G,_meta:{...G._meta??{},gatewayClientId:X}})}}return{resourceTemplates:Z}}listPrompts($,Z){if(!this.promptsCache)this.promptsCache=this.aggregatePrompts();return this.promptsCache}async aggregatePrompts(){let $=[];for(let[Z,X]of Object.entries(this.clients)){let Q=await this.listFromClient(Z,(J)=>this.fetchAllPrompts(J,Z),"prompts"),Y=X.prompts,G=Y?new Set(Y):null;for(let J of Q){if(G&&!G.has(J.name))continue;$.push({...J,name:this.namespace(Z,J.name),title:J.title??xo8(J.name),_meta:{...J._meta??{},gatewayClientId:Z}})}}return{prompts:$}}async callTool($,Z,X){let[Q,Y]=await this.resolveToolTarget($.name);return(await this.resolveClient(Q)).callTool({...$,name:Y},Z,X)}async readResource($,Z){let X=await this.resolveResourceRoute($.uri);return(await this.resolveClient(X)).readResource($)}async getPrompt($,Z){let[X,Q]=await this.resolvePromptTarget($.name);return(await this.resolveClient(X)).getPrompt({...$,name:Q})}async resolveResourceRoute($){let Z=this.resourceRouteMap.get($);if(Z)return Z;if(this.resourcesCache=null,await this.listResources(),Z=this.resourceRouteMap.get($),Z)return Z;throw Error(`GatewayClient: resource "${$}" not found in any upstream client`)}getServerCapabilities(){return{tools:{},resources:{},prompts:{}}}getInstructions(){return}refresh(){this.toolsCache=null,this.resourcesCache=null,this.resourceTemplatesCache=null,this.promptsCache=null}async close(){let $=[...this.resolvedClients.values()].map((Z)=>Z.then((X)=>X.close()).catch(()=>{}));await Promise.allSettled($),await super.close()}}});var t50=w(()=>{_r1()});function Kc0($){return UF($)}function go8($,Z){let X=UF(Z)||"prompt";return`${String($).padStart(yo8,"0")}-${X}`}async function Hc0($,Z,X){try{await $.delete(o50,Kc0(Z),{actor:X})}catch(Q){console.error("[agent-prompts] failed to delete prompts",{agentId:Z,err:Q})}}async function r50($,Z,X,Q){let Y=Kc0(Z);await Hc0($,Z,X),await Promise.all(Q.slice(0,Wc0).map(async(G,J)=>{let W=go8(J,G.title),K={name:W,title:G.title,description:G.description,text:G.text};try{await $.write(o50,`${Y}/${W}.json`,JSON.stringify(K),{actor:X,contentType:"application/json"})}catch(H){console.error("[agent-prompts] failed to seed prompt",{agentId:Z,name:W,err:H})}}))}async function vr1($,Z){let X=Kc0(Z),Q;try{Q=await $.listDir(o50,X)}catch{return[]}let Y=Q.filter((J)=>J.kind==="file"&&J.path.endsWith(".json")).slice(0,Wc0),G=[];for(let J of Y)try{let W=await $.read(o50,J.path),K=JSON.parse(new TextDecoder().decode(W));if(K&&typeof K.name==="string"&&typeof K.title==="string"&&typeof K.text==="string")G.push(K)}catch{}return G}var o50="agent-prompts",Wc0=20,yo8;var Ei=w(()=>{t50();yo8=String(Wc0-1).length});import{z as xr1}from"zod";function ho8(){let $=fr1[Math.floor(Math.random()*fr1.length)];return`icon://${br1[Math.floor(Math.random()*br1.length)]}?color=${$}`}var fr1,br1,uo8,co8,Fc0;var yr1=w(()=>{C0();PO();Jc0();Ei();fr1=["red","orange","amber","yellow","lime","green","emerald","cyan","sky","blue","indigo","violet","purple","fuchsia","pink","rose"],br1=["Star01","Zap","Heart","Globe01","Compass03","Lightbulb02","Rocket01","Flag01","BookOpen01","Shield01","Key01","Diamond01","Cube01","Target04","Award01","Briefcase01","Coffee","Feather","Hexagon01","Layers3_01","Map01","Palette","Package","Terminal"];uo8=xr1.object({data:B$0.describe("Data for the new virtual MCP")}),co8=xr1.object({item:x7.describe("The created virtual MCP entity")}),Fc0=c({name:"COLLECTION_VIRTUAL_MCP_CREATE",description:"Create a Virtual MCP (agent) that aggregates tools from multiple connections into one endpoint. Pass `prompts` to seed the agent with kickstart prompts (conversation starters shown as icebreakers). Author them from the agent's role/instructions and the descriptions of the tools it will have, so the starters are coherent and immediately useful.",annotations:{title:"Create Virtual MCP",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:uo8,outputSchema:co8,handler:async($,Z)=>{r(Z);let X=t(Z);await Z.access.check();let Q=G1(Z);if(!Q)throw Error("User ID required to create virtual MCP");if($.data.pinned===!0)i50(Z);let{prompts:Y,...G}=$.data;if(G.connections.length>0)await p50(Z,X.id,G.connections.map((K)=>K.connection_id));let J={...G,icon:G.icon??ho8()},W=await Z.storage.virtualMcps.create(X.id,Q,J);if(Y?.length&&Z.orgFs&&W.id)await r50(Z.orgFs,W.id,Q,Y);return{item:W}}})});function lo8($){let Z=[],X=0;while(X<$.length){let Q=$[X];if(Q==="%")Z.push(".*");else if(Q==="_")Z.push(".");else if(/[.*+?^${}()|[\]\\]/.test(Q))Z.push("\\"+Q);else Z.push(Q);X++}return Z.join("")}function VO($){return typeof $==="string"||typeof $==="number"}function Nc0($,Z){let X=Z.split("."),Q=$;for(let Y of X){if(Q==null||typeof Q!=="object")return;Q=Q[Y]}return Q}function do8($,Z){return $.connections.some((X)=>X.connection_id===Z)}function a50($,Z){if("conditions"in Z){let{operator:W,conditions:K}=Z;switch(W){case"and":return K.every((H)=>a50($,H));case"or":return K.some((H)=>a50($,H));case"not":return!K.every((H)=>a50($,H));default:return!0}}let{field:X,operator:Q,value:Y}=Z,G=X.join(".");if(G==="connection_id"){if(Q!=="eq"||typeof Y!=="string")return!1;return do8($,Y)}let J=Nc0($,G);switch(Q){case"eq":return J===Y;case"gt":return VO(J)&&VO(Y)&&J>Y;case"gte":return VO(J)&&VO(Y)&&J>=Y;case"lt":return VO(J)&&VO(Y)&&J<Y;case"lte":return VO(J)&&VO(Y)&&J<=Y;case"in":return Array.isArray(Y)&&Y.includes(J);case"like":if(typeof J!=="string"||typeof Y!=="string")return!1;if(Y.length>100)return!1;let W=lo8(Y);return new RegExp(`^${W}$`,"i").test(J);case"contains":if(typeof J!=="string"||typeof Y!=="string")return!1;return J.toLowerCase().includes(Y.toLowerCase());default:return!0}}function mo8($,Z){return[...$].sort((X,Q)=>{for(let Y of Z){let G=Y.field.join("."),J=Nc0(X,G),W=Nc0(Q,G),K=0;if(J==null&&W==null)continue;if(J==null)K=Y.nulls==="first"?-1:1;else if(W==null)K=Y.nulls==="first"?1:-1;else if(typeof J==="string"&&typeof W==="string")K=J.localeCompare(W);else if(typeof J==="number"&&typeof W==="number")K=J-W;else K=String(J).localeCompare(String(W));if(K!==0)return Y.direction==="desc"?-K:K}return 0})}var io8,po8,Uc0;var gr1=w(()=>{bG();C0();PO();io8=U3,po8=FF(x7),Uc0=c({name:"COLLECTION_VIRTUAL_MCP_LIST",description:"List all MCP virtual MCPs in the organization",annotations:{title:"List Virtual MCPs",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:io8,outputSchema:po8,handler:async($,Z)=>{await Z.access.check();let X=t(Z),Q=$.where&&!("conditions"in $.where)&&$.where.field.join(".")==="connection_id"&&$.where.operator==="eq"&&typeof $.where.value==="string"?$.where.value:void 0,Y=$.where&&!("conditions"in $.where)&&$.where.field.join(".")==="pinned"&&$.where.operator==="eq"&&typeof $.where.value==="boolean"?$.where.value:void 0,J=Q?await Z.storage.virtualMcps.listByConnectionId(X.id,Q):await Z.storage.virtualMcps.list(X.id,Y!==void 0?{pinnedOnly:Y}:void 0);if($.where)J=J.filter((U)=>a50(U,$.where));if($.orderBy&&$.orderBy.length>0)J=mo8(J,$.orderBy);let W=J.length,K=$.offset??0,H=$.limit??100,F=J.slice(K,K+H),N=K+H<W;return{items:F,totalCount:W,hasMore:N}}})});import{z as Oc0}from"zod";var no8,to8,Bc0;var hr1=w(()=>{C0();PO();no8=Oc0.object({id:Oc0.string().describe("ID of the virtual MCP to retrieve")}),to8=Oc0.object({item:x7.nullable().describe("The retrieved virtual MCP, or null if not found")}),Bc0=c({name:"COLLECTION_VIRTUAL_MCP_GET",description:"Get a Virtual MCP's configuration, connections, and virtual tools by ID.",annotations:{title:"Get Virtual MCP",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:no8,outputSchema:to8,handler:async($,Z)=>{r(Z);let X=t(Z);await Z.access.check();let Q=await Z.storage.virtualMcps.findById($.id);if(Q&&Q.organization_id!==X.id)return{item:null};if(!Q)return{item:null};return{item:Q}}})});import{z as wc0}from"zod";var oo8,ro8,Dc0;var ur1=w(()=>{C0();Ei();PO();Jc0();oo8=wc0.object({id:wc0.string().describe("ID of the virtual MCP to update"),data:w$0.describe("Partial virtual MCP data to update")}),ro8=wc0.object({item:x7.describe("The updated virtual MCP entity")}),Dc0=c({name:"COLLECTION_VIRTUAL_MCP_UPDATE",description:"Update a Virtual MCP's name, slug, connection list, or kickstart prompts. Pass `prompts` to replace the agent's conversation starters (full set; empty array clears them).",annotations:{title:"Update Virtual MCP",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:oo8,outputSchema:ro8,handler:async($,Z)=>{r(Z);let X=t(Z);await Z.access.check();let Q=G1(Z);if(!Q)throw Error("User ID required to update virtual MCP");let Y=await Z.storage.virtualMcps.findById($.id);if(!Y)throw Error(`Virtual MCP not found: ${$.id}`);if(Y.organization_id!==X.id)throw Error(`Virtual MCP not found: ${$.id}`);let{prompts:G,...J}=$.data;if(J.metadata&&Y.metadata)J.metadata={...Y.metadata,...J.metadata};if(J.pinned!==void 0&&J.pinned!==Y.pinned)i50(Z);if(J.connections?.length)await p50(Z,X.id,J.connections.map((K)=>K.connection_id));let W=await Z.storage.virtualMcps.update($.id,Q,J);if(G!==void 0&&Z.orgFs)await r50(Z.orgFs,$.id,Q,G);return{item:W}}})});function ao8($){if(!$)return!1;return/permission\s+"?checks"?\s+is not allowed/i.test($)||/permissions exceed what the github app/i.test($)}function so8($){let{checks:Z,...X}=$;return X}async function dr1($,Z){let X={...Z,checks:"read"},Q=await $(X);if(Q.isError&&ao8(Q.content?.find((Y)=>Y.type==="text")?.text)){let Y=so8(Z);return{result:await $(Y),grantedPermissions:Y}}return{result:Q,grantedPermissions:X}}function eo8($){if(!$||typeof $!=="object"||Array.isArray($))return cr1;let Z=$;if(Object.values(Z).some((X)=>typeof X!=="string"))return cr1;return Z}function $r8($){if(typeof $!=="number"||!Number.isFinite($)||!Number.isInteger($)||$<=0)return;return $}function x5($){let Z=$.metadata?.repoScope;if(!Z||typeof Z.installationId!=="number"||!Number.isFinite(Z.installationId)||!Number.isInteger(Z.installationId)||Z.installationId<=0||typeof Z.owner!=="string"||typeof Z.repo!=="string"||Z.owner.length===0||Z.repo.length===0)return null;let X=$r8(Z.repositoryId);return{sourceConnectionId:typeof Z.sourceConnectionId==="string"?Z.sourceConnectionId:void 0,installationId:Z.installationId,repositoryId:X,owner:Z.owner,repo:Z.repo,permissions:eo8(Z.permissions),grantProvider:Z.grantProvider==="github-mcp"?"github-mcp":void 0}}function uL($){return $.metadata?.orgShared===!0}function s50($,Z,X){let Q=lr1(Z,X),Y=($??[]).filter((G)=>{if(G.status&&G.status!=="active")return!1;let J=x5(G);return J!==null&&lr1(J.owner,J.repo)===Q});return Y.find(uL)??Y[0]??null}var cr1,lr1=($,Z)=>`${$}/${Z}`.toLowerCase();var SY=w(()=>{cr1={contents:"write",metadata:"read",pull_requests:"write",issues:"write",checks:"read"}});function mr1($){return TG($)!==null||h80($)!==null}var ir1=w(()=>{U8()});import{z as Lc0}from"zod";var Zr8,Xr8,Ec0;var pr1=w(()=>{SY();xG();C0();Ei();PO();ir1();Zr8=Lc0.object({id:Lc0.string().describe("ID of the virtual MCP to delete")}),Xr8=Lc0.object({item:x7.describe("The deleted virtual MCP entity")}),Ec0=c({name:"COLLECTION_VIRTUAL_MCP_DELETE",description:"Permanently delete a Virtual MCP and its virtual tools.",annotations:{title:"Delete Virtual MCP",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:Zr8,outputSchema:Xr8,handler:async($,Z)=>{r(Z);let X=t(Z);if(await Z.access.check(),mr1($.id))throw Error(`Virtual MCP not found: ${$.id}`);let Q=await Z.storage.virtualMcps.findById($.id);if(!Q)throw Error(`Virtual MCP not found: ${$.id}`);if(Q.organization_id!==X.id)throw Error(`Virtual MCP not found: ${$.id}`);await Z.storage.virtualMcps.delete($.id);try{if((await Z.storage.organizationSettings.get(X.id))?.main_agent_id===$.id)await Z.storage.organizationSettings.upsert(X.id,{main_agent_id:null})}catch(G){console.error("[VIRTUAL_MCP_DELETE] failed to clear main agent pointer",{id:$.id,error:G.message})}if(Z.orgFs)await Hc0(Z.orgFs,$.id,G1(Z)??"system");let Y=Q.metadata?.githubRepo?.connectionId;if(Y)try{let G=await Z.storage.connections.findById(Y,X.id),J=G&&(uL(G)||(await Z.storage.virtualMcps.listByConnectionId(X.id,Y)).length>0||await Z.storage.connections.isReferencedByThread(Y));if(G&&x5(G)&&!J){let K=await new u6(Z.db,Z.vault).get(Y);if(K?.accessToken)try{await fetch("https://api.github.com/installation/token",{method:"DELETE",headers:{Authorization:`Bearer ${K.accessToken}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"},signal:AbortSignal.timeout(5000)})}catch{}await Z.storage.connections.delete(Y)}}catch(G){console.error("[VIRTUAL_MCP_DELETE] failed to tear down repo-scoped connection",{childConnectionId:Y,error:G.message})}return{item:Q}}})});import{z as AQ}from"zod";var Qr8,jc0;var nr1=w(()=>{C0();Qr8=AQ.object({id:AQ.string(),virtualMcpId:AQ.string(),pluginId:AQ.string(),connectionId:AQ.string().nullable(),settings:AQ.record(AQ.string(),AQ.unknown()).nullable(),createdAt:AQ.string(),updatedAt:AQ.string()}),jc0=c({name:"VIRTUAL_MCP_PLUGIN_CONFIG_GET",description:"Get a plugin's current configuration for a specific virtual MCP.",annotations:{title:"Get Virtual MCP Plugin Config",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:AQ.object({virtualMcpId:AQ.string().describe("Virtual MCP ID"),pluginId:AQ.string().describe("Plugin ID")}),outputSchema:AQ.object({config:Qr8.nullable()}),handler:async($,Z)=>{r(Z);let X=t(Z);await Z.access.check();let{virtualMcpId:Q,pluginId:Y}=$,G=await Z.storage.connections.findById(Q);if(!G||G.organization_id!==X.id)return{config:null};if(G.connection_type!=="VIRTUAL")return{config:null};let J=await Z.storage.virtualMcpPluginConfigs.get(Q,Y);if(!J)return{config:null};return{config:{id:J.id,virtualMcpId:J.virtualMcpId,pluginId:J.pluginId,connectionId:J.connectionId,settings:J.settings,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt,updatedAt:J.updatedAt instanceof Date?J.updatedAt.toISOString():J.updatedAt}}}})});import{z as _Z}from"zod";var Yr8,zc0;var tr1=w(()=>{C0();Lx();v9();Yr8=_Z.object({id:_Z.string(),virtualMcpId:_Z.string(),pluginId:_Z.string(),connectionId:_Z.string().nullable(),settings:_Z.record(_Z.string(),_Z.unknown()).nullable(),createdAt:_Z.string(),updatedAt:_Z.string()}),zc0=c({name:"VIRTUAL_MCP_PLUGIN_CONFIG_UPDATE",description:"Set or update a plugin's configuration for a specific virtual MCP.",annotations:{title:"Update Virtual MCP Plugin Config",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:_Z.object({virtualMcpId:_Z.string().describe("Virtual MCP ID"),pluginId:_Z.string().describe("Plugin ID"),connectionId:_Z.string().nullable().optional().describe("MCP connection to bind"),settings:_Z.record(_Z.string(),_Z.unknown()).nullable().optional().describe("Plugin-specific settings")}),outputSchema:_Z.object({config:Yr8}),handler:async($,Z)=>{r(Z);let X=t(Z);await Z.access.check();let{virtualMcpId:Q,pluginId:Y,connectionId:G,settings:J}=$,W=G1(Z),K=await Z.storage.connections.findById(Q);if(!K)throw Error(`Connection not found: ${Q}`);if(K.organization_id!==X.id)throw Error(`Connection not found: ${Q}`);if(K.connection_type!=="VIRTUAL")throw Error(`Connection not found: ${Q}`);let H=G?await Z.storage.connections.findById(G):null;if(G&&H&&H.organization_id!==X.id)throw Error(`Connection not found: ${G}`);if(G&&K.organization_id&&!H&&O3()&&h50(G,K.organization_id)){if(!W)throw Error("User ID required to create dev-assets connection");let N=Dx(K.organization_id,_9());await Z.storage.connections.create({...N,organization_id:K.organization_id,created_by:W})}else if(G&&!H)throw Error(`Connection not found: ${G}`);let F=await Z.storage.virtualMcpPluginConfigs.upsert(Q,Y,{connectionId:G,settings:J});return{config:{id:F.id,virtualMcpId:F.virtualMcpId,pluginId:F.pluginId,connectionId:F.connectionId,settings:F.settings,createdAt:F.createdAt instanceof Date?F.createdAt.toISOString():F.createdAt,updatedAt:F.updatedAt instanceof Date?F.updatedAt.toISOString():F.updatedAt}}}})});import{z as uX}from"zod";var Gr8,Pc0;var or1=w(()=>{C0();PO();Gr8=uX.object({connectionId:uX.string(),toolName:uX.string(),label:uX.string(),icon:uX.string().nullable().optional()}),Pc0=c({name:"VIRTUAL_MCP_PINNED_VIEWS_UPDATE",description:"Update the pinned sidebar views for a virtual MCP. Replaces all current pins.",annotations:{title:"Update Pinned Views",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:uX.object({virtualMcpId:uX.string().describe("Virtual MCP ID"),pinnedViews:uX.array(Gr8).describe("Pinned views to set for the virtual MCP sidebar"),layout:uX.object({defaultMainView:uX.object({type:uX.string(),id:uX.string().optional(),toolName:uX.string().optional()}).nullable().optional(),chatDefaultOpen:uX.boolean().nullable().optional()}).optional()}),outputSchema:uX.object({item:x7.nullable()}),handler:async($,Z)=>{r(Z);let X=t(Z);await Z.access.check();let{virtualMcpId:Q,pinnedViews:Y,layout:G}=$,J=G1(Z),W=await Z.storage.virtualMcps.findById(Q);if(!W)throw Error(`Virtual MCP not found: ${Q}`);if(W.organization_id!==X.id)throw Error(`Virtual MCP not found: ${Q}`);let K=W.metadata?.ui??{},H={...K,pinnedViews:Y.length>0?Y:null,layout:G??K.layout??null};return{item:await Z.storage.virtualMcps.update(Q,J??"system",{metadata:{...W.metadata,ui:H}})}}})});import{z as OF}from"zod";var Jr8,Wr8,Ac0;var rr1=w(()=>{C0();Jr8=OF.object({ids:OF.array(OF.string()).describe("Virtual MCP ids to look up")}),Wr8=OF.object({items:OF.array(OF.object({id:OF.string(),last_used_at:OF.string().optional(),last_used_by:OF.string().optional()}))}),Ac0=c({name:"VIRTUAL_MCP_LAST_USED_LIST",description:"Get last-used info (timestamp + user) for one or more virtual MCPs, derived from the most recent thread per agent.",annotations:{title:"List Virtual MCP Last Used",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:Jr8,outputSchema:Wr8,handler:async($,Z)=>{r(Z),t(Z),await Z.access.check();let X=await Z.storage.threads.findLastUsedByVirtualMcpIds($.ids);return{items:$.ids.map((Q)=>({id:Q,last_used_at:X.get(Q)?.last_used_at,last_used_by:X.get(Q)?.last_used_by}))}}})});var ar1=w(()=>{yr1();gr1();hr1();ur1();pr1();nr1();tr1();or1();rr1()});import{z as i7}from"zod";var Tc0;var sr1=w(()=>{f6();C0();Tc0=c({name:"MONITORING_HEATMAP",description:"Get tool-call volume broken down by agent and tool name, for spotting heavily-used tools per agent.",annotations:{title:"Get Tool-Call Heatmap",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:i7.object({startDate:i7.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:i7.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)"),virtualMcpIds:i7.array(i7.string()).max(100).optional().describe("Filter by specific agent (Virtual MCP) IDs"),excludeConnectionIds:i7.array(i7.string()).max(100).optional().describe("Exclude tool calls from these connection IDs"),limit:i7.number().int().min(1).max(1000).optional().describe("Max number of (agent, tool) cells to return")}),outputSchema:i7.object({cells:i7.array(i7.object({virtualMcpId:i7.string().nullable(),toolName:i7.string(),calls:i7.number(),errors:i7.number(),outputSize:i7.number().describe("Sum of tool-output character length \u2014 a proxy for context weight, not LLM token count")}))}),handler:async($,Z)=>{let X=t(Z);return await Z.access.check(),await XQ(),Z.storage.monitoring.queryToolCallHeatmap({organizationId:X.id,startDate:$.startDate?new Date($.startDate):void 0,endDate:$.endDate?new Date($.endDate):void 0,filters:{virtualMcpIds:$.virtualMcpIds,excludeConnectionIds:$.excludeConnectionIds},limit:$.limit})}})});import{z as N5}from"zod";var Rc0;var er1=w(()=>{f6();C0();Rc0=c({name:"MONITORING_LOG_GET",description:"Get a single monitoring log by ID with full input and output data.",annotations:{title:"Get Monitoring Log",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:N5.object({id:N5.string().describe("Log ID to fetch")}),outputSchema:N5.object({log:N5.object({id:N5.string().optional(),organizationId:N5.string(),connectionId:N5.string(),toolName:N5.string(),input:N5.record(N5.string(),N5.unknown()),output:N5.record(N5.string(),N5.unknown()),isError:N5.boolean(),errorMessage:N5.string().nullish(),durationMs:N5.number(),timestamp:N5.string(),userId:N5.string().nullish(),requestId:N5.string(),userAgent:N5.string().nullish(),virtualMcpId:N5.string().nullish(),properties:N5.record(N5.string(),N5.string()).nullish()}).nullable().describe("The monitoring log, or null if not found")}),handler:async($,Z)=>{await Z.access.check(),await XQ();let X=t(Z),Q=await Z.storage.monitoring.getById(X.id,$.id);if(!Q)return{log:null};return{log:{...Q,timestamp:Q.timestamp instanceof Date?Q.timestamp.toISOString():Q.timestamp}}}})});import{z as W8}from"zod";var Hr8,Ic0;var $a1=w(()=>{f6();C0();Hr8=W8.object({id:W8.string().optional().describe("Unique log identifier"),organizationId:W8.string().describe("Organization ID"),connectionId:W8.string().describe("Connection ID"),toolName:W8.string().describe("Name of the tool that was called"),isError:W8.boolean().describe("Whether the call resulted in an error"),errorMessage:W8.string().nullish().describe("Error message if applicable"),durationMs:W8.number().describe("Call duration in milliseconds"),timestamp:W8.string().describe("ISO 8601 timestamp of the call"),userId:W8.string().nullish().describe("User who triggered the call"),requestId:W8.string().describe("Unique request identifier"),userAgent:W8.string().nullish().describe("Client identifier (x-studio-client header)"),virtualMcpId:W8.string().nullish().describe("Virtual MCP (Agent) ID if routed through an agent"),properties:W8.record(W8.string(),W8.string()).nullish().describe("Custom key-value metadata attached to the log")}),Ic0=c({name:"MONITORING_LOGS_LIST",description:"List monitoring logs for tool calls with filtering and pagination.",annotations:{title:"List Monitoring Logs",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:W8.object({connectionId:W8.string().optional().describe("Filter by connection ID"),excludeConnectionIds:W8.array(W8.string()).optional().describe("Exclude logs from these connection IDs (e.g. system connections)"),virtualMcpId:W8.string().optional().describe("Filter by Virtual MCP (Agent) ID"),toolName:W8.string().optional().describe("Filter by tool name"),isError:W8.boolean().optional().describe("Filter by error status"),startDate:W8.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:W8.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)"),limit:W8.number().default(20).describe("Maximum number of results"),offset:W8.number().default(0).describe("Offset for pagination"),properties:W8.record(W8.string(),W8.string()).optional().describe("Filter by exact property key=value matches"),propertyKeys:W8.array(W8.string()).optional().describe("Filter by logs that have these property keys"),propertyPatterns:W8.record(W8.string(),W8.string()).optional().describe("Filter by property value patterns (SQL LIKE, use % as wildcard)"),propertyInValues:W8.record(W8.string(),W8.string()).optional().describe("Filter by exact match within comma-separated values (e.g., user_tags in 'Engineering')")}),outputSchema:W8.object({logs:W8.array(Hr8).describe("Array of monitoring logs"),total:W8.number().describe("Total number of logs matching filters"),offset:W8.number().describe("Current offset for pagination"),limit:W8.number().describe("Current limit for pagination")}),handler:async($,Z)=>{await XQ();let X=t(Z),Y=$.properties||$.propertyKeys||$.propertyPatterns||$.propertyInValues?{properties:$.properties,propertyKeys:$.propertyKeys,propertyPatterns:$.propertyPatterns,propertyInValues:$.propertyInValues}:void 0,G={organizationId:X.id,connectionId:$.connectionId,excludeConnectionIds:$.excludeConnectionIds,virtualMcpId:$.virtualMcpId,toolName:$.toolName,isError:$.isError,startDate:$.startDate?new Date($.startDate):void 0,endDate:$.endDate?new Date($.endDate):void 0,limit:$.limit,offset:$.offset,propertyFilters:Y},J=await Z.storage.monitoring.query(G);return{logs:J.logs.map(({input:W,output:K,...H})=>({...H,timestamp:H.timestamp instanceof Date?H.timestamp.toISOString():H.timestamp})),total:J.total,offset:$.offset,limit:$.limit}}})});import{z as G$}from"zod";var qc0;var Za1=w(()=>{f6();C0();qc0=c({name:"MONITORING_STATS",description:"Get aggregated statistics (counts, latency, error rates) for tool call monitoring.",annotations:{title:"Get Monitoring Stats",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:G$.object({startDate:G$.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:G$.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)"),interval:G$.string().regex(/^\d+[mhd]$/).optional().describe("Bucket interval for timeseries data (e.g. 1m, 5m, 2h, 1d). When provided, returns timeseries array."),connectionIds:G$.array(G$.string()).max(100).optional().describe("Filter by specific connection IDs (max 100)"),excludeConnectionIds:G$.array(G$.string()).max(100).optional().describe("Exclude specific connection IDs (max 100)"),toolNames:G$.array(G$.string()).max(100).optional().describe("Filter by specific tool names (max 100)"),status:G$.enum(["success","error"]).optional().describe("Filter metrics by execution status"),topN:G$.number().int().min(1).max(20).optional().describe("When provided with interval, also return top tools and their timeseries"),userIds:G$.array(G$.string()).max(100).optional().describe("Filter LLM usage by user IDs (only applied when llmUsage is true)"),llmUsage:G$.boolean().optional().describe("Aggregate LLM-call usage (tokens + USD cost) from raw log rows for the given connection. Returns token/cost totals and timeseries. Requires interval.")}),outputSchema:G$.object({totalCalls:G$.number().describe("Total number of tool calls"),errorRate:G$.number().optional().describe("Error rate as a decimal (0 to 1)"),avgDurationMs:G$.number().describe("Average call duration in milliseconds"),errorRatePercent:G$.string().optional().describe("Error rate as a percentage string"),totalErrors:G$.number().optional().describe("Total number of errors"),p50DurationMs:G$.number().optional().describe("50th percentile duration in milliseconds"),p95DurationMs:G$.number().optional().describe("95th percentile duration in milliseconds"),connectionBreakdown:G$.array(G$.object({connectionId:G$.string(),calls:G$.number(),errors:G$.number(),errorRate:G$.number(),avgDurationMs:G$.number()})).optional().describe("Per-connection metric breakdown"),totalInputTokens:G$.number().optional().describe("Total input tokens (LLM usage mode)"),totalOutputTokens:G$.number().optional().describe("Total output tokens (LLM usage mode)"),totalTokens:G$.number().optional().describe("Total tokens (LLM usage mode)"),totalCostUsd:G$.number().optional().describe("Total USD cost (LLM usage mode; only non-zero for providers that report cost)"),topTools:G$.array(G$.object({toolName:G$.string(),connectionId:G$.string().nullable(),calls:G$.number(),inputTokens:G$.number().optional(),outputTokens:G$.number().optional(),costUsd:G$.number().optional()})).optional().describe("Top tools ranked by calls"),topToolsTimeseries:G$.array(G$.object({timestamp:G$.string(),toolName:G$.string(),calls:G$.number(),errors:G$.number(),avg:G$.number(),p95:G$.number()})).optional().describe("Per-tool metric timeseries for the top tools"),timeseries:G$.array(G$.object({timestamp:G$.string(),calls:G$.number(),errors:G$.number(),errorRate:G$.number(),avg:G$.number(),p50:G$.number(),p95:G$.number(),inputTokens:G$.number().optional(),outputTokens:G$.number().optional(),totalTokens:G$.number().optional(),costUsd:G$.number().optional()})).optional().describe("Timeseries data points bucketed by interval")}),handler:async($,Z)=>{let X=t(Z);if(await Z.access.check(),await XQ(),$.interval&&$.llmUsage)return Z.storage.monitoring.queryLlmUsageStats({organizationId:X.id,interval:$.interval,connectionId:$.connectionIds?.[0]??"decopilot",startDate:$.startDate?new Date($.startDate):void 0,endDate:$.endDate?new Date($.endDate):void 0,userIds:$.userIds,topN:$.topN});if($.interval){let Y=await Z.storage.monitoring.queryMetricTimeseries({organizationId:X.id,interval:$.interval,startDate:$.startDate?new Date($.startDate):void 0,endDate:$.endDate?new Date($.endDate):void 0,filters:{connectionIds:$.connectionIds,excludeConnectionIds:$.excludeConnectionIds,toolNames:$.toolNames,status:$.status}});if(!$.topN)return Y;let G=await Z.storage.monitoring.queryMetricTopToolsTimeseries({organizationId:X.id,interval:$.interval,startDate:$.startDate?new Date($.startDate):void 0,endDate:$.endDate?new Date($.endDate):void 0,topN:$.topN,filters:{connectionIds:$.connectionIds,excludeConnectionIds:$.excludeConnectionIds,toolNames:$.toolNames,status:$.status}});return{...Y,topTools:G.topTools,topToolsTimeseries:G.timeseries}}let Q=await Z.storage.monitoring.getStats({organizationId:X.id,startDate:$.startDate?new Date($.startDate):void 0,endDate:$.endDate?new Date($.endDate):void 0});return{...Q,errorRatePercent:(Q.errorRate*100).toFixed(2)}}})});import{z as cX}from"zod";var Mc0;var Xa1=w(()=>{f6();C0();Mc0=c({name:"MONITORING_THREAD_USAGE",description:"Aggregate LLM token usage and USD cost per thread for the given thread IDs.",annotations:{title:"Get Thread Usage",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:cX.object({threadIds:cX.array(cX.string()).min(1).max(500).describe("Thread IDs to aggregate usage for (max 500)"),connectionId:cX.string().optional().describe("LLM connection ID (defaults to 'decopilot')"),startDate:cX.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:cX.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)")}),outputSchema:cX.object({items:cX.array(cX.object({threadId:cX.string(),calls:cX.number(),inputTokens:cX.number(),outputTokens:cX.number(),totalTokens:cX.number(),costUsd:cX.number()}))}),handler:async($,Z)=>{let X=t(Z);return await Z.access.check(),await XQ(),{items:await Z.storage.monitoring.queryThreadUsage({organizationId:X.id,connectionId:$.connectionId??"decopilot",threadIds:$.threadIds,startDate:$.startDate?new Date($.startDate):void 0,endDate:$.endDate?new Date($.endDate):void 0})}}})});var Qa1=w(()=>{sr1();er1();$a1();Za1();Xa1()});function e50($){return typeof $==="string"&&Nr8.has($.trim().toLowerCase())}var Nr8;var kc0=w(()=>{Nr8=new Set([".well-known","_admin","api","auth","cli","commerce-onboarding","dbos-queue-depth","health","hosted-run-pending","login","mcp","metrics","oauth","oauth-proxy","onboarding","org","report","reset-password"])});import{z as CY}from"zod";var Vc0;var Ya1=w(()=>{C0();kc0();Vc0=c({name:"ORGANIZATION_CREATE",description:"Create a new organization. The caller becomes the owner automatically.",annotations:{title:"Create Organization",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:CY.object({slug:CY.string().min(1).max(50).regex(/^[a-z0-9-]+$/,"Slug must be lowercase alphanumeric with hyphens").refine(($)=>!e50($),"Slug is reserved by Studio"),name:CY.string().min(1).max(255),description:CY.string().optional()}),outputSchema:CY.object({id:CY.string(),name:CY.string(),slug:CY.string(),logo:CY.string().nullable().optional(),metadata:CY.any().optional(),createdAt:CY.string().datetime().describe("ISO 8601 timestamp"),members:CY.array(CY.any()).optional()}),handler:async($,Z)=>{r(Z),await Z.access.check();let X=G1(Z);if(!X)throw Error("User ID required to create organization");let Q=await Z.boundAuth.organization.create({name:$.name,slug:$.slug,metadata:$.description?{description:$.description}:void 0,userId:X});if(!Q)throw Error("Failed to create organization");return{...Q,createdAt:Q.createdAt instanceof Date?Q.createdAt.toISOString():Q.createdAt}}})});import{z as B3}from"zod";var Sc0;var Ga1=w(()=>{C0();Sc0=c({name:"ORGANIZATION_LIST",description:"List organizations the current user belongs to.",annotations:{title:"List Organizations",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},_meta:{ui:{visibility:"app"}},inputSchema:B3.object({userId:B3.string().optional()}),outputSchema:B3.object({organizations:B3.array(B3.object({id:B3.string(),name:B3.string(),slug:B3.string(),logo:B3.string().nullable().optional(),metadata:B3.any().optional(),createdAt:B3.string().datetime().describe("ISO 8601 timestamp")}))}),handler:async($,Z)=>{r(Z),await Z.access.check();let X=G1(Z),Q=$.userId||X;if(!Q)throw Error("User ID required to list organizations");return{organizations:(await Z.boundAuth.organization.list(Q)).map((G)=>({...G,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt}))}}})});import{z as yG}from"zod";var Cc0;var Ja1=w(()=>{C0();Cc0=c({name:"ORGANIZATION_GET",description:"Get an organization's details, members, and settings by slug or ID.",annotations:{title:"Get Organization",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:yG.object({}),outputSchema:yG.object({id:yG.string(),name:yG.string(),slug:yG.string(),logo:yG.string().nullable().optional(),metadata:yG.any().optional(),createdAt:yG.string().datetime().describe("ISO 8601 timestamp"),members:yG.array(yG.any()).optional(),invitations:yG.array(yG.any()).optional()}),handler:async($,Z)=>{r(Z),await Z.access.check();let X=Z.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");let Q=await Z.boundAuth.organization.get(X);if(!Q)throw Error("No active organization found");let Y=new Date,G=Q.invitations?.filter((J)=>new Date(J.expiresAt)>Y);return{...Q,invitations:G,createdAt:Q.createdAt instanceof Date?Q.createdAt.toISOString():Q.createdAt}}})});import{z as w3}from"zod";var _c0;var Wa1=w(()=>{C0();_c0=c({name:"ORGANIZATION_UPDATE",description:"Update an organization's name or description.",annotations:{title:"Update Organization",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:w3.object({id:w3.string(),name:w3.string().min(1).max(255).optional(),description:w3.string().optional()}),outputSchema:w3.object({id:w3.string(),name:w3.string(),slug:w3.string(),logo:w3.string().nullable().optional(),metadata:w3.any().optional(),createdAt:w3.string().datetime().describe("ISO 8601 timestamp")}),handler:async($,Z)=>{r(Z),await Z.access.check();let X={};if($.name)X.name=$.name;if($.description)X.metadata={description:$.description};let Q=await Z.boundAuth.organization.update({organizationId:$.id,data:X});if(!Q)throw Error("Failed to update organization");return{...Q,createdAt:Q.createdAt instanceof Date?Q.createdAt.toISOString():Q.createdAt}}})});import{z as ji}from"zod";var vc0;var Ka1=w(()=>{C0();vc0=c({name:"ORGANIZATION_DELETE",description:"Archive an organization (soft delete).",annotations:{title:"Delete Organization",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:ji.object({id:ji.string()}),outputSchema:ji.object({success:ji.boolean(),id:ji.string()}),handler:async($,Z)=>{return r(Z),await Z.access.check(),await Z.boundAuth.organization.update({organizationId:$.id,data:{metadata:{archived:!0,archivedAt:new Date().toISOString()}}}),{success:!0,id:$.id}}})});import{z as K$}from"zod";function $90($,Z){let X=$?.[Z];return Ur8.has(Z)?X!==!1:X===!0}var zi,Pi,BF,Ha1,SO,Ai,Ti,Ri,Ii,Ur8,CO;var TQ=w(()=>{zi=K$.object({title:K$.string(),url:K$.string(),icon:K$.string()}),Pi=K$.object({registries:K$.record(K$.string(),K$.object({enabled:K$.boolean()})).describe("Per-registry enabled/disabled state. Key is connection ID. Absent registries are treated as enabled."),blockedMcps:K$.array(K$.string()).describe("List of MCP app_name or app_id values to hide from the store.")}),BF=K$.object({keyId:K$.string(),modelId:K$.string(),title:K$.string().optional()}).nullable(),Ha1=K$.enum(["fast","smart","thinking","image","web_search","deep_research"]),SO=K$.enum(["fast","smart","thinking"]),Ai=K$.object({tiers:K$.object({fast:BF,smart:BF,thinking:BF,image:BF,web_search:BF,deep_research:BF})}),Ti=K$.object({tiers:K$.object({fast:BF.optional(),smart:BF.optional(),thinking:BF.optional()})}),Ri=K$.object({ids:K$.array(K$.string()).describe("Ordered list of custom virtual MCP agent ids to show on the home view.")}),Ii=K$.object({demo_mode:K$.boolean().optional().describe("Curated demo org: the commerce connect modal proceeds without a configured required data source."),reports_only:K$.boolean().optional().describe("Curated commerce (reports) look: hides agent navigation, the home Customize button, and the Settings/Automations tabs. Defaulted on for orgs created by commerce onboarding."),nav_v2:K$.boolean().optional().describe("First-class navigation: the sidebar lists destinations (Reports, Library, Tasks) instead of chat threads, and the thread list moves into a menu at the top of the chat panel. Always on for reports_only orgs."),qa_agent_enabled:K$.boolean().optional().describe("Run the QA Agent on a task's pull request once it's In Review \u2014 it verifies the task actually solved the problem (exercises the feature, not just the diff)."),code_reviewer_enabled:K$.boolean().optional().describe("Run the Code Reviewer on a task's pull request once it's In Review \u2014 it reviews the code using the repo's stack-appropriate review skills."),auto_merge:K$.boolean().optional().describe("When every enabled reviewer (QA Agent / Code Reviewer) approves a task's pull request, merge it automatically instead of leaving the merge to a human. If the merge is blocked by a conflict with the base branch, hand the PR back to the Super Agent to resolve the conflict (check out the branch, merge the base, push) so it can then merge."),cheap_reviewer_model:K$.boolean().optional().describe("Run the QA Agent and Code Reviewer on a cheaper model than the Super Agent. A review reads a diff and reaches a verdict; it does not need the model that wrote the code. Off by default \u2014 turning it on trades some review depth for cost."),auto_assign_report_tasks_to_super_agent:K$.boolean().optional().describe("When a report import creates a task board item without an assignee, delegate it to the Super Agent automatically instead of leaving it unassigned.")}),Ur8=new Set(["qa_agent_enabled","code_reviewer_enabled"]);CO=K$.object({id:K$.string().describe("Brand context ID"),name:K$.string().describe("Company name"),domain:K$.string().describe("Company domain (e.g. example.com)"),overview:K$.string().describe("Company overview / description"),logo:K$.string().nullable().optional().describe("Logo URL"),favicon:K$.string().nullable().optional().describe("Favicon URL"),ogImage:K$.string().nullable().optional().describe("OG image URL"),fonts:K$.object({heading:K$.string().optional().describe("Font family for headings"),body:K$.string().optional().describe("Font family for body text"),code:K$.string().optional().describe("Font family for code / monospace")}).nullable().optional().describe("Font families by semantic role"),colors:K$.object({primary:K$.string().optional().describe("Primary brand color (hex)"),secondary:K$.string().optional().describe("Secondary brand color (hex)"),accent:K$.string().optional().describe("Accent / highlight color (hex)"),background:K$.string().optional().describe("Background color (hex)"),foreground:K$.string().optional().describe("Foreground / text color (hex)")}).nullable().optional().describe("Semantic color palette"),images:K$.array(K$.record(K$.string(),K$.unknown())).nullable().optional().describe("Brand images"),metadata:K$.record(K$.string(),K$.unknown()).nullable().optional().describe("Extra design tokens (typography, components, spacing, layout, tone, etc.)"),archivedAt:K$.string().nullable().optional().describe("Archive timestamp (null to unarchive)"),isDefault:K$.boolean().optional().describe("Whether this is the default brand for the organization")})});import{z as wF}from"zod";var fc0;var Fa1=w(()=>{C0();TQ();fc0=c({name:"ORGANIZATION_SETTINGS_GET",description:"Get organization-level settings including sidebar configuration, store registry settings, simple model mode, and default home agents.",annotations:{title:"Get Organization Settings",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:wF.object({}),outputSchema:wF.object({organizationId:wF.string(),sidebar_items:wF.array(zi).nullable().optional(),enabled_plugins:wF.array(wF.string()).nullable().optional(),registry_config:Pi.nullable().optional(),simple_mode:Ai.nullable().optional(),default_home_agents:Ri.nullable().optional(),flags:Ii.nullable().optional(),main_agent_id:wF.string().nullable().optional(),createdAt:wF.string().datetime().optional().describe("ISO 8601 timestamp"),updatedAt:wF.string().datetime().optional().describe("ISO 8601 timestamp")}),handler:async($,Z)=>{r(Z),await Z.access.check();let X=Z.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");let Q=await Z.storage.organizationSettings.get(X);if(!Q)return{organizationId:X};return{...Q,createdAt:Q.createdAt instanceof Date?Q.createdAt.toISOString():Q.createdAt,updatedAt:Q.updatedAt instanceof Date?Q.updatedAt.toISOString():Q.updatedAt}}})});import{z as RQ}from"zod";var bc0;var Na1=w(()=>{C0();TQ();bc0=c({name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization-level settings such as sidebar configuration, store registry settings, simple model mode, and default home agents.",annotations:{title:"Update Organization Settings",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:RQ.object({organizationId:RQ.string(),sidebar_items:RQ.array(zi).optional(),enabled_plugins:RQ.array(RQ.string()).optional(),registry_config:Pi.optional(),simple_mode:Ai.optional(),default_home_agents:Ri.optional(),flags:Ii.strict().optional().describe("Org boolean toggles. Shallow-merged into the stored flags: keys you pass win (explicit false persists), omitted keys keep their value."),main_agent_id:RQ.string().nullable().optional().describe("Virtual MCP id the org lands on instead of the Super Agent. Pass null to clear.")}),outputSchema:RQ.object({organizationId:RQ.string(),sidebar_items:RQ.array(zi).nullable().optional(),enabled_plugins:RQ.array(RQ.string()).nullable().optional(),registry_config:Pi.nullable().optional(),simple_mode:Ai.nullable().optional(),default_home_agents:Ri.nullable().optional(),flags:Ii.nullable().optional(),main_agent_id:RQ.string().nullable().optional(),createdAt:RQ.string().datetime().describe("ISO 8601 timestamp"),updatedAt:RQ.string().datetime().describe("ISO 8601 timestamp")}),handler:async($,Z)=>{if(r(Z),await Z.access.check(),t(Z).id!==$.organizationId)throw Error("Cannot update settings for a different organization");let Q=await Z.storage.organizationSettings.upsert($.organizationId,{sidebar_items:$.sidebar_items,enabled_plugins:$.enabled_plugins,registry_config:$.registry_config,simple_mode:$.simple_mode,default_home_agents:$.default_home_agents,flags:$.flags,main_agent_id:$.main_agent_id});return{...Q,createdAt:Q.createdAt instanceof Date?Q.createdAt.toISOString():Q.createdAt,updatedAt:Q.updatedAt instanceof Date?Q.updatedAt.toISOString():Q.updatedAt}}})});import{z as D3}from"zod";var Ua1,xc0,yc0;var Oa1=w(()=>{C0();TQ();Ua1=CO.extend({organizationId:D3.string(),archivedAt:D3.string().nullable().optional().describe("ISO 8601 timestamp"),createdAt:D3.string().describe("ISO 8601 timestamp"),updatedAt:D3.string().describe("ISO 8601 timestamp")}),xc0=c({name:"BRAND_CONTEXT_LIST",description:"List all brand contexts (company profiles) for the current organization.",annotations:{title:"List Brand Contexts",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:D3.object({includeArchived:D3.boolean().optional().describe("Include archived brands in the list")}),outputSchema:D3.object({items:D3.array(Ua1)}),handler:async($,Z)=>{r(Z),await Z.access.check();let X=Z.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");return{items:(await Z.storage.brandContext.list(X,{includeArchived:$.includeArchived})).map((Y)=>({...Y,archivedAt:Y.archivedAt instanceof Date?Y.archivedAt.toISOString():Y.archivedAt,createdAt:Y.createdAt instanceof Date?Y.createdAt.toISOString():Y.createdAt,updatedAt:Y.updatedAt instanceof Date?Y.updatedAt.toISOString():Y.updatedAt}))}}}),yc0=c({name:"BRAND_CONTEXT_GET",description:"Get a specific brand context by ID.",annotations:{title:"Get Brand Context",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:D3.object({id:D3.string().describe("Brand context ID")}),outputSchema:Ua1.extend({organizationId:D3.string()}),handler:async($,Z)=>{r(Z),await Z.access.check();let X=Z.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");let Q=await Z.storage.brandContext.get($.id,X);if(!Q)throw Error("Brand context not found");return{...Q,archivedAt:Q.archivedAt instanceof Date?Q.archivedAt.toISOString():Q.archivedAt,createdAt:Q.createdAt instanceof Date?Q.createdAt.toISOString():Q.createdAt,updatedAt:Q.updatedAt instanceof Date?Q.updatedAt.toISOString():Q.updatedAt}}})});import{z as cL}from"zod";var Ba1,gc0,hc0,uc0;var wa1=w(()=>{C0();TQ();Ba1=CO.extend({organizationId:cL.string(),createdAt:cL.string().describe("ISO 8601 timestamp"),updatedAt:cL.string().describe("ISO 8601 timestamp")}),gc0=c({name:"BRAND_CONTEXT_CREATE",description:"Create a new brand context (company profile) for the current organization.",annotations:{title:"Create Brand Context",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},inputSchema:CO.omit({id:!0}),outputSchema:Ba1,handler:async($,Z)=>{r(Z),await Z.access.check();let X=Z.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");let Q=await Z.storage.brandContext.create(X,{name:$.name,domain:$.domain,overview:$.overview,logo:$.logo??null,favicon:$.favicon??null,ogImage:$.ogImage??null,fonts:$.fonts??null,colors:$.colors??null,images:$.images??null,metadata:$.metadata??null});return{...Q,archivedAt:Q.archivedAt instanceof Date?Q.archivedAt.toISOString():Q.archivedAt,createdAt:Q.createdAt instanceof Date?Q.createdAt.toISOString():Q.createdAt,updatedAt:Q.updatedAt instanceof Date?Q.updatedAt.toISOString():Q.updatedAt}}}),hc0=c({name:"BRAND_CONTEXT_UPDATE",description:"Update an existing brand context by ID.",annotations:{title:"Update Brand Context",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:CO.partial().required({id:!0}),outputSchema:Ba1,handler:async($,Z)=>{r(Z),await Z.access.check();let X=Z.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");if(!await Z.storage.brandContext.get($.id,X))throw Error("Brand context not found");let{id:Y,...G}=$;if(G.isDefault===!0)await Z.storage.brandContext.setDefault(Y,X);let J=await Z.storage.brandContext.update(Y,X,{name:G.name,domain:G.domain,overview:G.overview,logo:G.logo!==void 0?G.logo??null:void 0,favicon:G.favicon!==void 0?G.favicon??null:void 0,ogImage:G.ogImage!==void 0?G.ogImage??null:void 0,fonts:G.fonts!==void 0?G.fonts??null:void 0,colors:G.colors!==void 0?G.colors??null:void 0,images:G.images!==void 0?G.images??null:void 0,metadata:G.metadata!==void 0?G.metadata??null:void 0,archivedAt:G.archivedAt!==void 0?G.archivedAt??null:void 0,isDefault:G.isDefault===!1?!1:void 0});return{...J,archivedAt:J.archivedAt instanceof Date?J.archivedAt.toISOString():J.archivedAt,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt,updatedAt:J.updatedAt instanceof Date?J.updatedAt.toISOString():J.updatedAt}}}),uc0=c({name:"BRAND_CONTEXT_DELETE",description:"Archive a brand context by ID (soft delete).",annotations:{title:"Archive Brand Context",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:cL.object({id:cL.string().describe("Brand context ID")}),outputSchema:cL.object({success:cL.boolean()}),handler:async($,Z)=>{r(Z),await Z.access.check();let X=Z.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");if(!await Z.storage.brandContext.get($.id,X))throw Error("Brand context not found");return await Z.storage.brandContext.update($.id,X,{archivedAt:new Date().toISOString(),isDefault:!1}),{success:!0}}})});async function Z90($,Z,X){let Q=$.trim();if(!Q.startsWith("http"))Q=`https://${Q}`;let Y=await fetch("https://api.firecrawl.dev/v1/scrape",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Z}`},body:JSON.stringify({url:Q,formats:["branding"]})});if(!Y.ok){let U=await Y.text().catch(()=>"");throw Error(`Firecrawl API error: ${Y.status} ${U.slice(0,200)}`)}let G=await Y.json();if(!G.success||!G.data?.branding)return null;let J=G.data.branding,W=G.data.metadata??{},K=wr8(J,W);return{name:W.title?.split(/[|\u2013\u2014]|\s+-\s+/).map((U)=>U.trim()).filter(Boolean)?.slice().sort((U,O)=>U.length-O.length)[0]??W.ogSiteName??X??$,domain:$,overview:W.description??"",logo:K.logo,favicon:K.favicon,ogImage:K.ogImage,fonts:K.fonts,colors:K.colors,images:null,metadata:Object.keys(K.metadata).length>0?K.metadata:null}}function wr8($,Z){let X=$.images??{},Q=$.colors??{},Y={};for(let[F,N]of Object.entries(Q))if(typeof N==="string"&&N&&Or8.has(F))Y[F]=N;let G={},W=($.typography??{}).fontFamilies??{};for(let[F,N]of Object.entries(W))if(typeof N==="string"&&N){let U=Br8[F.toLowerCase()];if(U&&!G[U])G[U]=N}let K=$.fonts;if(Array.isArray(K))for(let F of K){let N=F.family;if(typeof N==="string"&&N&&!G.body)G.body=N}let H={};for(let F of["typography","components","spacing","layout","animations","icons","tone","personality","colorScheme"])if($[F]!==void 0)H[F]=$[F];return{logo:X.logo??null,favicon:X.favicon??null,ogImage:X.ogImage??Z.ogImage??null,fonts:Object.keys(G).length>0?G:null,colors:Object.keys(Y).length>0?Y:null,metadata:H}}var Or8,Br8;var cc0=w(()=>{Or8=new Set(["primary","secondary","accent","background","foreground"]),Br8={heading:"heading",headings:"heading",head:"heading",title:"heading",body:"body",primary:"body",text:"body",code:"code",monospace:"code",mono:"code"}});import{z as X90}from"zod";var Dr8,lc0;var Da1=w(()=>{C0();cc0();TQ();Dr8=CO.pick({id:!0,name:!0,domain:!0,overview:!0,logo:!0,favicon:!0,ogImage:!0,fonts:!0,colors:!0}).extend({success:X90.boolean()}),lc0=c({name:"BRAND_CONTEXT_EXTRACT",description:"Extract brand context (colors, fonts, logos) from a website URL using Firecrawl.",annotations:{title:"Extract Brand Context",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},inputSchema:X90.object({domain:X90.string().describe("Website domain to extract brand from"),brandId:X90.string().optional().describe("Existing brand context ID to update (creates new if omitted)")}),outputSchema:Dr8,modelSummary:($)=>$.success?`Brand saved (id=${$.id}, name=${$.name}, domain=${$.domain}). The UI rendered the logo, colors, fonts, and overview.`:"Brand extraction failed.",handler:async($,Z)=>{r(Z),await Z.access.check();let X=Z.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");let Q=Z.firecrawlApiKey;if(!Q)throw Error("FIRECRAWL_API_KEY is not configured. Set the environment variable to enable brand extraction.");let Y=await Z90($.domain,Q,$.domain);if(!Y)throw Error("Firecrawl did not return branding data for this URL");let G={name:Y.name,domain:Y.domain,overview:Y.overview,logo:Y.logo,favicon:Y.favicon,ogImage:Y.ogImage,fonts:Y.fonts,colors:Y.colors,images:Y.images,metadata:Y.metadata},J=$.brandId?await(async()=>{if(!await Z.storage.brandContext.get($.brandId,X))throw Error("Brand context not found");return Z.storage.brandContext.update($.brandId,X,G)})():await Z.storage.brandContext.create(X,G);return{id:J.id,name:J.name,domain:J.domain,overview:J.overview,logo:J.logo,favicon:J.favicon,ogImage:J.ogImage,fonts:J.fonts,colors:J.colors,success:!0}}})});function La1($){let Z=$.metadata??{};return{id:$.id,name:$.name,domain:$.domain||void 0,colors:$.colors??void 0,fonts:$.fonts??void 0,assets:$.logo||$.favicon||$.ogImage?{logo:$.logo??void 0,favicon:$.favicon??void 0,ogImage:$.ogImage??void 0}:void 0,overview:$.overview||void 0,tagline:typeof Z.tagline==="string"?Z.tagline:void 0,tone:typeof Z.tone==="string"?Z.tone:void 0,metadata:(()=>{let X=Object.fromEntries(Object.entries(Z).filter(([Q])=>Q!=="tagline"&&Q!=="tone"));return Object.keys(X).length>0?X:void 0})()}}var dc0,mc0;var Ea1=w(()=>{tu0();C0();dc0=c({name:"BRAND_GET",description:"Get a brand context by ID. Omit the ID to get the default brand for the organization.",annotations:{title:"Get Brand",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:_50,outputSchema:Ji,handler:async($,Z)=>{r(Z),await Z.access.check();let X=Z.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");let Q=$.id?await Z.storage.brandContext.get($.id,X):await Z.storage.brandContext.getDefault(X);if(!Q)throw Error($.id?"Brand not found":"No default brand configured");return La1(Q)}}),mc0=c({name:"BRAND_LIST",description:"List all active brands for the current organization.",annotations:{title:"List Brands",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:v50,outputSchema:f50,handler:async($,Z)=>{r(Z),await Z.access.check();let X=Z.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");return{items:(await Z.storage.brandContext.list(X)).map(La1)}}})});import{resolveTxt as Lr8}from"dns/promises";function ic0($){return`${Er8}.${$.toLowerCase()}`}function ja1(){return`deco-verify-${crypto.randomUUID().replace(/-/g,"")}`}async function za1($,Z,X=Lr8){if(!Z)return!1;try{return(await X(ic0($))).some((Y)=>Y.join("").trim()===Z)}catch{return!1}}var Er8="_deco-verify";var Pa1=()=>{};import{z as R5}from"zod";function _O($){let Z=$.verificationStatus==="pending"&&Boolean($.verificationToken);return{id:$.id,domain:$.domain,joinMode:$.joinMode,verificationStatus:$.verificationStatus,verificationMethod:$.verificationMethod,verifiedAt:$.verifiedAt?new Date($.verifiedAt).toISOString():null,recordName:Z?ic0($.domain):null,recordValue:Z?$.verificationToken:null}}function zr8($){let Z=$.toLowerCase().trim();if(!jr8.test(Z))throw Error(`Invalid domain format: "${Z}". Must be a valid domain like "acme.com"`);if(L3.has(Z))throw Error(`Cannot claim generic email domain "${Z}". Only corporate domains are allowed.`);return Z}var jr8,pc0,Q90,nc0,tc0,oc0,rc0,ac0;var Aa1=w(()=>{_Y();Pa1();C0();jr8=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/,pc0=R5.enum(["off","auto","request"]),Q90=R5.object({id:R5.string(),domain:R5.string(),joinMode:pc0,verificationStatus:R5.enum(["pending","verified"]),verificationMethod:R5.enum(["email","dns"]).nullable(),verifiedAt:R5.string().nullable(),recordName:R5.string().nullable(),recordValue:R5.string().nullable()});nc0=c({name:"ORGANIZATION_DOMAIN_LIST",description:"List the email domains claimed by an organization.",annotations:{title:"List Organization Domains",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:R5.object({}),outputSchema:R5.object({domains:R5.array(Q90)}),handler:async($,Z)=>{r(Z),await Z.access.check();let X=t(Z);return{domains:(await Z.storage.organizationDomains.listByOrganizationId(X.id)).map(_O)}}}),tc0=c({name:"ORGANIZATION_DOMAIN_ADD",description:"Claim an email domain for an organization. If the caller's verified email matches the domain it is trusted immediately; otherwise it requires DNS verification.",annotations:{title:"Add Organization Domain",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:R5.object({domain:R5.string().min(1).max(255).describe("Domain to claim, e.g. acme.com"),joinMode:pc0.optional().describe("Initial join mode (only applied when the domain is trusted immediately via email match).")}),outputSchema:Q90,handler:async($,Z)=>{r(Z),await Z.access.check();let X=t(Z),Q=zr8($.domain),G=Z.auth.user?.email?.split("@")[1]?.toLowerCase(),J=Boolean(Z.auth.user?.emailVerified)&&G===Q,W=await Z.storage.organizationDomains.getByOrgAndDomain(X.id,Q);if(W){if(W.verificationStatus!=="verified"&&J){let H=await Z.storage.organizationDomains.markVerified(W.id,"email");return _O(H)}return _O(W)}let K=J?await Z.storage.organizationDomains.add(X.id,Q,{joinMode:$.joinMode??"off",verificationStatus:"verified",verificationMethod:"email"}):await Z.storage.organizationDomains.add(X.id,Q,{joinMode:"off",verificationStatus:"pending",verificationToken:ja1()});return _O(K)}}),oc0=c({name:"ORGANIZATION_DOMAIN_UPDATE",description:"Set the join mode for a claimed domain. Discoverable modes (auto/request) require the domain to be verified.",annotations:{title:"Update Organization Domain",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:R5.object({id:R5.string(),joinMode:pc0}),outputSchema:Q90,handler:async($,Z)=>{r(Z),await Z.access.check();let X=t(Z),Q=await Z.storage.organizationDomains.getById($.id);if(!Q||Q.organizationId!==X.id)throw Error("Domain not found");if($.joinMode!=="off"&&Q.verificationStatus!=="verified")throw Error("Verify the domain before enabling auto-join or requests.");let Y=await Z.storage.organizationDomains.updateJoinMode($.id,$.joinMode);return _O(Y)}}),rc0=c({name:"ORGANIZATION_DOMAIN_VERIFY",description:"Check the DNS TXT record for a pending domain and mark it verified if present.",annotations:{title:"Verify Organization Domain",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},inputSchema:R5.object({id:R5.string()}),outputSchema:R5.object({verified:R5.boolean(),domain:Q90}),handler:async($,Z)=>{r(Z),await Z.access.check();let X=t(Z),Q=await Z.storage.organizationDomains.getById($.id);if(!Q||Q.organizationId!==X.id)throw Error("Domain not found");if(Q.verificationStatus==="verified")return{verified:!0,domain:_O(Q)};if(!Q.verificationToken)throw Error("Domain has no pending DNS verification.");if(!await za1(Q.domain,Q.verificationToken))return{verified:!1,domain:_O(Q)};let G=await Z.storage.organizationDomains.markVerified($.id,"dns");return{verified:!0,domain:_O(G)}}}),ac0=c({name:"ORGANIZATION_DOMAIN_REMOVE",description:"Remove a claimed domain from an organization.",annotations:{title:"Remove Organization Domain",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:R5.object({id:R5.string()}),outputSchema:R5.object({success:R5.boolean()}),handler:async($,Z)=>{r(Z),await Z.access.check();let X=t(Z),Q=await Z.storage.organizationDomains.getById($.id);if(!Q||Q.organizationId!==X.id)throw Error("Domain not found");return await Z.storage.organizationDomains.removeById($.id),{success:!0}}})});function vO($){return($ instanceof Error?$.message.toLowerCase():"").includes("already a member")}import{z as L9}from"zod";var Pr8,sc0,ec0,$l0;var Ta1=w(()=>{C0();M4();Pr8=L9.object({id:L9.string(),userId:L9.string(),status:L9.enum(["pending","approved","denied"]),createdAt:L9.string(),user:L9.object({id:L9.string(),name:L9.string(),email:L9.string(),image:L9.string().nullable()}).nullable()}),sc0=c({name:"ORGANIZATION_JOIN_REQUEST_LIST",description:"List pending requests to join the organization.",annotations:{title:"List Join Requests",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:L9.object({}),outputSchema:L9.object({requests:L9.array(Pr8)}),handler:async($,Z)=>{r(Z),await Z.access.check();let X=t(Z);return{requests:(await Z.storage.organizationJoinRequests.listPendingWithUser(X.id)).map((Y)=>({id:Y.id,userId:Y.userId,status:Y.status,createdAt:new Date(Y.createdAt).toISOString(),user:Y.user}))}}}),ec0=c({name:"ORGANIZATION_JOIN_REQUEST_APPROVE",description:"Approve a pending join request, adding the user as a member.",annotations:{title:"Approve Join Request",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:L9.object({requestId:L9.string()}),outputSchema:L9.object({success:L9.boolean()}),handler:async($,Z)=>{r(Z),await Z.access.check();let X=t(Z),Q=await Z.storage.organizationJoinRequests.getById($.requestId);if(!Q||Q.organizationId!==X.id)throw Error("Join request not found");if(Q.status!=="pending")throw Error("Join request has already been decided");let Y=G1(Z);if(!await Z.storage.organizationJoinRequests.decide(Q.id,"approved",Y??Q.userId))return{success:!0};try{await Z.boundAuth.organization.addMember({organizationId:X.id,userId:Q.userId,role:["user"]})}catch(J){if(!vO(J))throw J}if(Y)y1.capture({distinctId:Y,event:"organization_join_request_approved",groups:{organization:X.id},properties:{organization_id:X.id,user_id:Q.userId}});return{success:!0}}}),$l0=c({name:"ORGANIZATION_JOIN_REQUEST_DENY",description:"Deny a pending join request.",annotations:{title:"Deny Join Request",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:L9.object({requestId:L9.string()}),outputSchema:L9.object({success:L9.boolean()}),handler:async($,Z)=>{r(Z),await Z.access.check();let X=t(Z),Q=await Z.storage.organizationJoinRequests.getById($.requestId);if(!Q||Q.organizationId!==X.id)throw Error("Join request not found");if(Q.status!=="pending")throw Error("Join request has already been decided");let Y=G1(Z);if(await Z.storage.organizationJoinRequests.decide(Q.id,"denied",Y??Q.userId)&&Y)y1.capture({distinctId:Y,event:"organization_join_request_denied",groups:{organization:X.id},properties:{organization_id:X.id,user_id:Q.userId}});return{success:!0}}})});import{z as IQ}from"zod";var Zl0;var Ra1=w(()=>{M4();C0();VG();Zl0=c({name:"ORGANIZATION_MEMBER_ADD",description:"Invite a member to the organization by email with an assigned role.",annotations:{title:"Add Organization Member",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:IQ.object({organizationId:IQ.string().optional(),userId:IQ.string(),role:IQ.array(IQ.string())}),outputSchema:IQ.object({id:IQ.string(),organizationId:IQ.string(),userId:IQ.string(),role:IQ.union([IQ.string(),IQ.array(IQ.string())]),createdAt:IQ.string().datetime().describe("ISO 8601 timestamp")}),handler:async($,Z)=>{r(Z),await Z.access.check();let X=$.organizationId||Z.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");if(X!==Z.organization?.id)throw Error("Organization ID does not match authenticated organization");let Q=await Z.db.selectFrom("member").select(["role"]).where("userId","=",G1(Z)??"").where("organizationId","=",X).executeTakeFirst();if(!K60(Q?.role,$.role))throw Error(`Insufficient privileges to assign role "${$.role.join(",")}"`);let Y=await Z.boundAuth.organization.addMember({organizationId:X,userId:$.userId,role:$.role});if(!Y)throw Error("Failed to add member");let G=G1(Z);if(G)y1.capture({distinctId:G,event:"organization_member_added",groups:{organization:X},properties:{organization_id:X,added_user_id:$.userId,role:$.role}});return{...Y,role:Y.role,createdAt:Y.createdAt instanceof Date?Y.createdAt.toISOString():Y.createdAt}}})});import{z as Ax}from"zod";var Xl0;var Ia1=w(()=>{M4();C0();Xl0=c({name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove a member from the organization. Revokes all their access immediately.",annotations:{title:"Remove Organization Member",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:Ax.object({organizationId:Ax.string().optional(),memberIdOrEmail:Ax.string()}),outputSchema:Ax.object({success:Ax.boolean(),memberIdOrEmail:Ax.string()}),handler:async($,Z)=>{r(Z),await Z.access.check();let X=$.organizationId||Z.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");if(X!==Z.organization?.id)throw Error("Organization ID does not match authenticated organization");let Q=await Z.boundAuth.organization.removeMember({organizationId:X,memberIdOrEmail:$.memberIdOrEmail});Z.invalidateMemberRole?.(Q.member.userId,X);let Y=G1(Z);if(Y)y1.capture({distinctId:Y,event:"organization_member_removed",groups:{organization:X},properties:{organization_id:X,member_id_or_email:$.memberIdOrEmail}});return{success:!0,memberIdOrEmail:$.memberIdOrEmail}}})});import{z as p7}from"zod";var Ql0;var qa1=w(()=>{C0();Ql0=c({name:"ORGANIZATION_MEMBER_LIST",description:"List all members in the organization with their roles.",annotations:{title:"List Organization Members",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:p7.object({limit:p7.number().optional(),offset:p7.number().optional()}),outputSchema:p7.object({members:p7.array(p7.object({id:p7.string(),organizationId:p7.string(),userId:p7.string(),role:p7.string(),createdAt:p7.string().datetime().describe("ISO 8601 timestamp"),user:p7.object({id:p7.string(),name:p7.string(),email:p7.string(),image:p7.string().optional()}).optional()}))}),handler:async($,Z)=>{r(Z),await Z.access.check();let X=Z.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");let Q=await Z.boundAuth.organization.listMembers({organizationId:X,limit:$.limit,offset:$.offset});return{members:(Array.isArray(Q)?Q:[]).map((G)=>({...G,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt}))}}})});import{z as vZ}from"zod";var Yl0;var Ma1=w(()=>{M4();C0();VG();Yl0=c({name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Change a member's role (e.g., admin, member) within the organization.",annotations:{title:"Update Member Role",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:vZ.object({organizationId:vZ.string().optional(),memberId:vZ.string(),role:vZ.array(vZ.string())}),outputSchema:vZ.object({id:vZ.string(),organizationId:vZ.string(),userId:vZ.string(),role:vZ.union([vZ.string(),vZ.array(vZ.string())]),createdAt:vZ.string().datetime().describe("ISO 8601 timestamp"),user:vZ.object({email:vZ.string(),name:vZ.string(),image:vZ.string().optional()})}),handler:async($,Z)=>{r(Z),await Z.access.check();let X=$.organizationId||Z.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");let Q=await Z.db.selectFrom("member").select(["role"]).where("userId","=",G1(Z)??"").where("organizationId","=",X).executeTakeFirst();if(!K60(Q?.role,$.role))throw Error(`Insufficient privileges to assign role "${$.role.join(",")}"`);let Y=await Z.boundAuth.organization.updateMemberRole({organizationId:X,memberId:$.memberId,role:$.role});if(!Y)throw Error("Failed to update member role");Z.invalidateMemberRole?.(Y.userId,X);let G=G1(Z);if(G)y1.capture({distinctId:G,event:"organization_member_role_updated",groups:{organization:X},properties:{organization_id:X,member_id:$.memberId,target_user_id:Y.userId,new_role:Array.isArray($.role)?$.role.join(","):$.role}});return{...Y,createdAt:Y.createdAt instanceof Date?Y.createdAt.toISOString():Y.createdAt}}})});async function ka1(){if(qi&&Date.now()-qi.fetchedAt<600000)return qi.rate;try{let Z=await(await fetch("https://economia.awesomeapi.com.br/json/last/USD-BRL",{signal:AbortSignal.timeout(5000)})).json(),X=parseFloat(Z.USDBRL?.bid??"");if(Number.isNaN(X)||X<=0)throw Error("Invalid rate");return qi={rate:X,fetchedAt:Date.now()},X}catch{return qi?.rate??5.5}}function Va1($,Z,X){if(Z==="brl")return Math.round($/X);return $}var qi=null;function Gl0($,Z="",X=new URLSearchParams){for(let[Q,Y]of Object.entries($)){if(Y===void 0||Y===null)continue;let G=Z?`${Z}[${Q}]`:Q;if(Array.isArray(Y))Y.forEach((J,W)=>{if(typeof J==="object"&&J!==null)Gl0(J,`${G}[${W}]`,X);else X.append(`${G}[${W}]`,String(J))});else if(typeof Y==="object")Gl0(Y,G,X);else X.append(G,String(Y))}return X}async function Mi($,Z){let X=b0().stripeSecretKey;if(!X)throw new vY(503,"billing is not configured");let Q=Z?.params?Gl0(Z.params).toString():void 0,Y=await fetch(`${Ar8}${$}`,{method:Z?.method??(Q?"POST":"GET"),headers:{Authorization:`Bearer ${X}`,...Q&&{"Content-Type":"application/x-www-form-urlencoded"}},body:Q,signal:AbortSignal.timeout(Tr8)}),G=await Y.json().catch(()=>({}));if(!Y.ok){let J=G.error?.message??`HTTP ${Y.status}`;throw new vY(Y.status,J)}return G}function Sa1($){return{billing_address_collection:"required",tax_id_collection:{enabled:!0},...$&&{customer_update:{address:"auto",name:"auto"}}}}async function Ca1($){let Z=b0().stripeOrgPriceId;if(!Z)throw new vY(503,"billing is not configured");let X=await Mi("/checkout/sessions",{params:{mode:"subscription",...Sa1(null),line_items:[{price:Z,quantity:1}],success_url:$.successUrl,cancel_url:$.cancelUrl,metadata:{orgId:$.organizationId},subscription_data:{metadata:{orgId:$.organizationId}}}});if(!X.url)throw new vY(500,"checkout session lacks url");return{url:X.url}}function Rr8($,Z){return Math.round($*(1+Z/100))}async function _a1($){let Z=Rr8($.amountCents,$.feePercent),X=Va1($.amountCents,$.currency,await ka1()),Q=b0().stripeTopupProductId,Y={kind:"topup",orgId:$.organizationId,creditCents:X},G=$.currency==="brl"?`Studio AI credits (R$ ${($.amountCents/100).toFixed(2)})`:`Studio AI credits ($${($.amountCents/100).toFixed(2)})`,J=await Mi("/checkout/sessions",{params:{mode:"payment",...$.customerId&&{customer:$.customerId},...Sa1($.customerId),line_items:[{quantity:1,price_data:{currency:$.currency,unit_amount:Z,...Q?{product:Q}:{product_data:{name:G}}}}],success_url:$.successUrl,cancel_url:$.cancelUrl,metadata:Y,payment_intent_data:{metadata:Y}}});if(!J.url)throw new vY(500,"checkout session lacks url");return{url:J.url}}async function Y90($){let Z=await Mi("/billing_portal/sessions",{params:{customer:$.customerId,return_url:$.returnUrl}});if(!Z.url)throw new vY(500,"portal session lacks url");return{url:Z.url}}async function G90($){return Mi(`/subscriptions/${encodeURIComponent($)}`)}async function va1($){await Mi(`/subscriptions/${encodeURIComponent($)}`,{method:"DELETE"})}var Ar8="https://api.stripe.com/v1",vY,Tr8=15000;var lL=w(()=>{T$();vY=class vY extends Error{status;constructor($,Z){super(`Stripe API ${$}: ${Z}`);this.status=$;this.name="StripeApiError"}}});import{z as Jl0}from"zod";var Wl0;var fa1=w(()=>{lL();v9();C0();M4();Wl0=c({name:"ORGANIZATION_BILLING_CHECKOUT_START",description:"Start the organization's subscription: creates a Stripe Checkout session and returns its URL.",annotations:{title:"Start Billing Checkout",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0},inputSchema:Jl0.object({}),outputSchema:Jl0.object({url:Jl0.string()}),handler:async($,Z)=>{r(Z),await Z.access.check();let X=Z.organization?.id,Q=Z.organization?.slug;if(!X||!Q)throw Error("Organization context required");let Y=await Z.storage.organizationBilling.getBilling(X);if(Y?.status==="active")throw Error("This organization already has an active subscription.");if(Y?.stripeSubscriptionId)throw Error("This organization still has a subscription on file \u2014 settle or cancel it before starting a new checkout.");let G=`${MZ()}/${encodeURIComponent(Q)}/members`,{url:J}=await Ca1({organizationId:X,successUrl:`${G}?checkout=success`,cancelUrl:`${G}?checkout=canceled`});return qY({event:"subscription_checkout_started",organizationId:X,...Z.auth?.user?.id?{userId:Z.auth.user.id}:{}}),{url:J}}})});import{z as Kl0}from"zod";var Hl0;var ba1=w(()=>{lL();v9();C0();Hl0=c({name:"ORGANIZATION_BILLING_PORTAL",description:"Open the organization's Stripe billing portal (manage card, invoices, cancellation). Returns the portal URL.",annotations:{title:"Open Billing Portal",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0},inputSchema:Kl0.object({}),outputSchema:Kl0.object({url:Kl0.string()}),handler:async($,Z)=>{r(Z),await Z.access.check();let X=t(Z);if(!X.slug)throw Error("Organization context required");let Q=await Z.storage.organizationBilling.getBilling(X.id);if(!Q?.stripeCustomerId)throw Error("This organization has no billing account yet \u2014 subscribe first.");try{return await Y90({customerId:Q.stripeCustomerId,returnUrl:`${MZ()}/${encodeURIComponent(X.slug)}/members`})}catch(Y){if(Y instanceof vY)throw Error(Y.message);throw Y}}})});function J90($){return Fl0[$%Fl0.length]??Ir8}function qQ($){return $.createdBy==="system"}function DF($){return K90.filter((Z)=>$90($,qr8[Z]))}function ki($,Z){return $?.startsWith(`${Tx[Z]}:`)??!1}function LF($){let Z=0;for(let X of $){if(X.action!=="status_changed")continue;if(X.data?.to!=="in_review")continue;Z=Math.max(Z,new Date(X.occurredAt).getTime())}return Z}function Nl0($,Z){let X=LF($),Q=new Map;for(let Y of $){if(Y.action!=="review_approved"&&Y.action!=="review_changes_requested")continue;if(new Date(Y.occurredAt).getTime()<X)continue;let G=Y.data??{};if(G.reviewer!=="qa"&&G.reviewer!=="code_review")continue;if(Y.action==="review_approved"){if(Z?.verifiedOnly&&G.verified!==!0)continue;Q.set(G.reviewer,"approved")}else Q.set(G.reviewer,"changes_requested")}return Q}function fO($,Z,X){if(Z.length===0)return!1;let Q=Nl0($,X);return Z.every((Y)=>Q.get(Y)==="approved")}function xa1($,Z){return fO($,Z)&&!fO($,Z,{verifiedOnly:!0})}function ya1($){let Z=null;for(let X of $){if(X.action!=="review_approved"&&X.action!=="review_changes_requested")continue;let Q=new Date(X.occurredAt).getTime();if(Z&&Q<Z.at)continue;let Y=X.data?.notes;Z={at:Q,notes:X.action==="review_changes_requested"&&typeof Y==="string"?Y:null}}return Z?.notes??null}function Mr8($){let Z=0;for(let X of $){if(X.action!=="assignee_changed")continue;if(X.data?.to!==n8)continue;Z=Math.max(Z,new Date(X.occurredAt).getTime())}return Z}function ga1($,Z=Ul0){let X=Mr8($),Q=new Set,Y=0;for(let G of[...$].sort((J,W)=>J.occurredAt.localeCompare(W.occurredAt))){let J=new Date(G.occurredAt).getTime();if(G.action==="status_changed"){if(G.data?.to==="in_review")Y=J;continue}if(G.action==="review_changes_requested"&&J>=X)Q.add(Y)}return Q.size+1>=Z}var n8="super-agent",Fl0,Ir8,W90='Your checkout is SHALLOW (`git clone --depth 1`), so it has no merge base and `git diff main...HEAD` (three dots) fails with "fatal: main...HEAD: no merge base". To see a branch diff, either use the two-dot form against the fetched remote ref (`git fetch origin <base> && git diff origin/<base> HEAD`), or deepen first with `git fetch --deepen=100`. Same for `git log main..HEAD` and anything else that needs shared history.',K90,Tx,qr8,Ul0=5,ha1="task-board.item.updated",ua1="task-board.item.deleted";var E9=w(()=>{TQ();Fl0=["#9ca3af","#ef4444","#f97316","#f59e0b","#22c55e","#3b82f6","#a855f7","#ec4899"],Ir8=Fl0[0];K90=["qa","code_review"],Tx={qa:"QA Agent",code_review:"Code Reviewer"},qr8={qa:"qa_agent_enabled",code_review:"code_reviewer_enabled"}});function Ol0($){return $==="trial"?"trial":"subscription"}function Vi($,Z,X,Q={}){qY({event:Z,organizationId:X.organizationId,...$.auth?.user?.id?{userId:$.auth.user.id}:{},properties:{task_id:X.id,...Q}})}function Bl0($){return $?.status==="active"||$?.status==="past_due"}function H90($,Z){if(Bl0($))return{periodKey:$?.currentPeriodEnd?`sub:${$.currentPeriodEnd.toISOString()}`:"sub:pending",limit:$?.monthlyTaskExecutions??Z.monthlyTaskExecutions,exhaustedReason:"monthly_exhausted"};return{periodKey:"trial",limit:$?.freeTaskExecutions??Z.freeTaskExecutions,exhaustedReason:"trial_exhausted"}}function Si(){let $=b0();return{enforced:$.taskQuotaEnforced,freeTaskExecutions:$.freeTaskExecutions,monthlyTaskExecutions:$.monthlyTaskExecutions,maxRunsPerTask:$.maxRunsPerTask}}function Rx(){return{...Si(),maxRunsPerTask:Number.POSITIVE_INFINITY}}async function F90($,Z,X=Si()){if(!X.enforced||!qQ(Z))return;let Q=await $.storage.organizationBilling.taskClaim(Z.id);if(Q&&Q.runCount>=X.maxRunsPerTask)throw Vi($,"task_quota_blocked",Z,{phase:"precheck",reason:"runs_exhausted"}),new n7("runs_exhausted");if(Q&&Q.state!=="released")return;let Y=await $.storage.organizationBilling.getBilling(Z.organizationId),G=H90(Y,X);if(await $.storage.organizationBilling.countTaskClaims(Z.organizationId,G.periodKey)>=G.limit)throw Vi($,"task_quota_blocked",Z,{phase:"precheck",reason:G.exhaustedReason,billing_mode:Ol0(G.periodKey),limit:G.limit}),new n7(G.exhaustedReason)}async function ca1($,Z,X=Si()){if(!X.enforced||!qQ(Z))return"skipped";let Q=await $.storage.organizationBilling.getBilling(Z.organizationId),Y=H90(Q,X),G=await $.storage.organizationBilling.claimTaskUnderLimit(Z.organizationId,Z.id,Y.periodKey,Y.limit,X.maxRunsPerTask);if(G==="exhausted")throw Vi($,"task_quota_blocked",Z,{phase:"claim",reason:Y.exhaustedReason,billing_mode:Ol0(Y.periodKey),limit:Y.limit}),new n7(Y.exhaustedReason);if(G==="runs_exhausted")throw Vi($,"task_quota_blocked",Z,{phase:"claim",reason:"runs_exhausted"}),new n7("runs_exhausted");if(G==="claimed")Vi($,"task_quota_claimed",Z,{billing_mode:Ol0(Y.periodKey),period_key:Y.periodKey,limit:Y.limit});return G}async function la1($,Z,X,Q){if(Q==="skipped")return;await $.rollbackTaskClaim(Z,X,{releaseSlot:Q==="claimed"}).catch((Y)=>console.error("[task-quota] rollback failed (stays charged)",Y))}async function da1($,Z){let X=await $.storage.organizationBilling.taskClaim(Z);return!!X&&X.state!=="released"}async function ma1($,Z,X){if(await $.releaseTaskClaim(Z,X).catch((Y)=>{return console.error("[task-quota] refund failed (stays charged)",Y),!1}))qY({event:"task_quota_refunded",organizationId:Z,properties:{task_id:X}})}var kr8="[SUBSCRIPTION_REQUIRED]",Vr8,n7;var E3=w(()=>{E9();M4();T$();Vr8={trial_exhausted:"this organization used its free task executions \u2014 subscribe to keep running tasks",monthly_exhausted:"this organization used its monthly task executions \u2014 more become available next billing cycle",runs_exhausted:"this task reached its execution limit \u2014 create a new task to keep going"};n7=class n7 extends Error{reason;constructor($){super(`${kr8} ${Vr8[$]}`);this.reason=$;this.name="TaskQuotaError"}}});import{z as EF}from"zod";var wl0;var ia1=w(()=>{C0();E3();wl0=c({name:"ORGANIZATION_TASK_QUOTA_GET",description:"Get the organization's auto-task quota: how many runs are used in the current period, the limit, and the subscription's billing status.",annotations:{title:"Get Task Quota",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:EF.object({}),outputSchema:EF.object({enforced:EF.boolean(),billingStatus:EF.string(),subscribed:EF.boolean(),hasBillingAccount:EF.boolean(),used:EF.number(),limit:EF.number(),currentPeriodEnd:EF.string().datetime().nullable()}),handler:async($,Z)=>{r(Z),await Z.access.check();let X=t(Z),Q=Si(),Y=await Z.storage.organizationBilling.getBilling(X.id),G=H90(Y,Q),J=await Z.storage.organizationBilling.countTaskClaims(X.id,G.periodKey);return{enforced:Q.enforced,billingStatus:Y?.status??"none",subscribed:Bl0(Y),hasBillingAccount:!!Y?.stripeCustomerId,used:J,limit:G.limit,currentPeriodEnd:Y?.currentPeriodEnd?.toISOString()??null}}})});var pa1=w(()=>{Ya1();Ga1();Ja1();Wa1();Ka1();Fa1();Na1();Oa1();wa1();Da1();Ea1();Aa1();Ta1();Ra1();Ia1();qa1();Ma1();fa1();ba1();ia1()});function XK($){if($==null)return"unknown error";if(typeof $==="string")return $;if($ instanceof Error)return $.message;return JSON.stringify($)}function N90($){if($===null||typeof $==="string"||typeof $==="number"||typeof $==="boolean")return!0;if(Array.isArray($))return $.every(N90);if(typeof $==="object")return Object.entries($).every(([Z,X])=>typeof Z==="string"&&(X===void 0||N90(X)));return!1}function Dl0($){return Array.isArray($)&&$.every(N90)}function Ci($){return $!=null&&typeof $==="object"&&Object.entries($).every(([Z,X])=>typeof Z==="string"&&(X===void 0||N90(X)))}var Ps1="vercel.ai.error",Cr8,na1,ta1,J1,As1="AI_APICallError",Ts1,_r8,oa1,ra1,Z4,Rs1="AI_EmptyResponseBodyError",Is1,vr8,aa1,sa1,U90,qs1="AI_InvalidArgumentError",Ms1,fr8,ea1,$s1,bO,ks1="AI_InvalidPromptError",Vs1,br8,Zs1,Xs1,gG,Ss1="AI_InvalidResponseDataError",Cs1,xr8,Qs1,Ys1,Ix,_s1="AI_JSONParseError",vs1,yr8,Gs1,Js1,jF,fs1="AI_LoadAPIKeyError",bs1,gr8,Ws1,Ks1,dL,xs1="AI_LoadSettingError",ys1,hr8,Hs1,Fs1,gs1,hs1="AI_NoContentGeneratedError",us1,ur8,Ns1,Us1,cs1,ls1="AI_NoSuchModelError",ds1,cr8,Os1,Bs1,y5,ms1="AI_TooManyEmbeddingValuesForCallError",is1,lr8,ws1,Ds1,qx,ps1="AI_TypeValidationError",ns1,dr8,Ls1,Es1,U5,ts1="AI_UnsupportedFunctionalityError",os1,mr8,js1,zs1,V4;var a1=w(()=>{Cr8=Symbol.for(Ps1),J1=class $ extends(ta1=Error,na1=Cr8,ta1){constructor({name:Z,message:X,cause:Q}){super(X);this[na1]=!0,this.name=Z,this.cause=Q}static isInstance(Z){return $.hasMarker(Z,Ps1)}static hasMarker(Z,X){let Q=Symbol.for(X);return Z!=null&&typeof Z==="object"&&Q in Z&&typeof Z[Q]==="boolean"&&Z[Q]===!0}},Ts1=`vercel.ai.error.${As1}`,_r8=Symbol.for(Ts1),Z4=class extends(ra1=J1,oa1=_r8,ra1){constructor({message:$,url:Z,requestBodyValues:X,statusCode:Q,responseHeaders:Y,responseBody:G,cause:J,isRetryable:W=Q!=null&&(Q===408||Q===409||Q===429||Q>=500),data:K}){super({name:As1,message:$,cause:J});this[oa1]=!0,this.url=Z,this.requestBodyValues=X,this.statusCode=Q,this.responseHeaders=Y,this.responseBody=G,this.isRetryable=W,this.data=K}static isInstance($){return J1.hasMarker($,Ts1)}},Is1=`vercel.ai.error.${Rs1}`,vr8=Symbol.for(Is1),U90=class extends(sa1=J1,aa1=vr8,sa1){constructor({message:$="Empty response body"}={}){super({name:Rs1,message:$});this[aa1]=!0}static isInstance($){return J1.hasMarker($,Is1)}};Ms1=`vercel.ai.error.${qs1}`,fr8=Symbol.for(Ms1),bO=class extends($s1=J1,ea1=fr8,$s1){constructor({message:$,cause:Z,argument:X}){super({name:qs1,message:$,cause:Z});this[ea1]=!0,this.argument=X}static isInstance($){return J1.hasMarker($,Ms1)}},Vs1=`vercel.ai.error.${ks1}`,br8=Symbol.for(Vs1),gG=class extends(Xs1=J1,Zs1=br8,Xs1){constructor({prompt:$,message:Z,cause:X}){super({name:ks1,message:`Invalid prompt: ${Z}`,cause:X});this[Zs1]=!0,this.prompt=$}static isInstance($){return J1.hasMarker($,Vs1)}},Cs1=`vercel.ai.error.${Ss1}`,xr8=Symbol.for(Cs1),Ix=class extends(Ys1=J1,Qs1=xr8,Ys1){constructor({data:$,message:Z=`Invalid response data: ${JSON.stringify($)}.`}){super({name:Ss1,message:Z});this[Qs1]=!0,this.data=$}static isInstance($){return J1.hasMarker($,Cs1)}},vs1=`vercel.ai.error.${_s1}`,yr8=Symbol.for(vs1),jF=class extends(Js1=J1,Gs1=yr8,Js1){constructor({text:$,cause:Z}){super({name:_s1,message:`JSON parsing failed: Text: ${$}.
950
950
  Error message: ${XK(Z)}`,cause:Z});this[Gs1]=!0,this.text=$}static isInstance($){return J1.hasMarker($,vs1)}},bs1=`vercel.ai.error.${fs1}`,gr8=Symbol.for(bs1),dL=class extends(Ks1=J1,Ws1=gr8,Ks1){constructor({message:$}){super({name:fs1,message:$});this[Ws1]=!0}static isInstance($){return J1.hasMarker($,bs1)}},ys1=`vercel.ai.error.${xs1}`,hr8=Symbol.for(ys1),gs1=class extends(Fs1=J1,Hs1=hr8,Fs1){constructor({message:$}){super({name:xs1,message:$});this[Hs1]=!0}static isInstance($){return J1.hasMarker($,ys1)}},us1=`vercel.ai.error.${hs1}`,ur8=Symbol.for(us1),cs1=class extends(Us1=J1,Ns1=ur8,Us1){constructor({message:$="No content generated."}={}){super({name:hs1,message:$});this[Ns1]=!0}static isInstance($){return J1.hasMarker($,us1)}},ds1=`vercel.ai.error.${ls1}`,cr8=Symbol.for(ds1),y5=class extends(Bs1=J1,Os1=cr8,Bs1){constructor({errorName:$=ls1,modelId:Z,modelType:X,message:Q=`No such ${X}: ${Z}`}){super({name:$,message:Q});this[Os1]=!0,this.modelId=Z,this.modelType=X}static isInstance($){return J1.hasMarker($,ds1)}},is1=`vercel.ai.error.${ms1}`,lr8=Symbol.for(is1),qx=class extends(Ds1=J1,ws1=lr8,Ds1){constructor($){super({name:ms1,message:`Too many values for a single embedding call. The ${$.provider} model "${$.modelId}" can only embed up to ${$.maxEmbeddingsPerCall} values per call, but ${$.values.length} values were provided.`});this[ws1]=!0,this.provider=$.provider,this.modelId=$.modelId,this.maxEmbeddingsPerCall=$.maxEmbeddingsPerCall,this.values=$.values}static isInstance($){return J1.hasMarker($,is1)}},ns1=`vercel.ai.error.${ps1}`,dr8=Symbol.for(ns1),U5=class $ extends(Es1=J1,Ls1=dr8,Es1){constructor({value:Z,cause:X,context:Q}){let Y="Type validation failed";if(Q==null?void 0:Q.field)Y+=` for ${Q.field}`;if((Q==null?void 0:Q.entityName)||(Q==null?void 0:Q.entityId)){Y+=" (";let G=[];if(Q.entityName)G.push(Q.entityName);if(Q.entityId)G.push(`id: "${Q.entityId}"`);Y+=G.join(", "),Y+=")"}super({name:ps1,message:`${Y}: Value: ${JSON.stringify(Z)}.
@@ -2803,7 +2803,7 @@ Respond with the structured verdict and a short reason.`,Dy$;var Ey$=w(()=>{_4()
2803
2803
  ${G.join(`
2804
2804
  `)}`:Y}function sY6($){let Z=new Set;for(let X of $)for(let Q of X.split(`
2805
2805
  `)){let Y=Q.trim();if(/^Co-authored-by:\s/i.test(Y))Z.add(Y)}return[...Z]}var iY6=200,pY6=12,nY6=300,F91=3;var N91=w(()=>{q_();fP0()});function $G6($){if(!$||$.includes(".."))return!1;return eY6.test($)}function Qg$($){let Z=typeof $.__resolveType==="string"?$.__resolveType:null;if(!Z||!$G6(Z))return null;let{__resolveType:X,...Q}=$;return{resolveType:Z,payload:Q}}function Yg$($,Z){return`${$.replace(/\/+$/,"")}/deco/invoke/${Z}`}var eY6;var Gg$=w(()=>{eY6=/^[\w./@-]+$/});function U91($){let Z;try{Z=new URL($)}catch{return null}if(!Z.hostname.endsWith(".localhost"))return null;let X=Z.host;return Z.hostname="127.0.0.1",{url:Z.toString(),hostHeader:X}}function Za($,Z){let X=$?.githubRepo;if(!X?.owner||!X?.name)return null;if(!X.connectionId)return X;if(!Z.includes(X.connectionId))return null;return X}async function Jg$($,Z,X,Q){if(!Q.connectionId)throw new k_("Push requires a connected GitHub account. Connect mcp-github for this project and restart the sandbox.");let Y=$.organization?.id;if(!Y)throw new k_($9);await nO({ctx:$,connectionId:Q.connectionId,organizationId:Y,forceRefresh:!0,onLegacyMintError:(F)=>{let N=F instanceof Error?F.message:$9;throw new k_(N)}});let{cloneUrl:G,gitUserName:J,gitUserEmail:W}=await tO(Q.connectionId,Q.owner,Q.name,$.db,$.vault).catch((F)=>{let{code:N,message:U}=t8$(F instanceof Error?F.message:String(F));throw N?new k_(U):F}),K=ch($),H=await Z.proxyDaemonRequest(X,"/_sandbox/config",{method:"PUT",headers:new Headers({"content-type":"application/json"}),body:JSON.stringify({git:{repository:{cloneUrl:G},identity:{userName:J,userEmail:W}},...K?{operator:K}:{}})});if(!H.ok){let F=await UB(H,ZG6).catch(()=>H.statusText);throw Error(`Failed to refresh sandbox git credentials (${H.status}): ${F}`)}}var ZG6=10485760,k_;var O91=w(()=>{uG();TP0();xp();bd0();hx();k_=class k_ extends Error{constructor($){super($);this.name="GitPushAuthError"}}});function QG6($){let Z=$.startsWith("thread:")?$.slice(7):$;if(!Z||Z.length>255||Z.includes("..")||Z.startsWith("/")||Z.endsWith("/")||Z.endsWith(".lock")||!XG6.test(Z))throw Error(`Invalid branch name: ${$}`)}function V_($){return AbortSignal.any([$.req.raw.signal,AbortSignal.timeout(GG6)])}function JG6($,Z,X){let Q=B5($)[Z]?.[X];return!!Q&&Object.keys(PY(Q)).length>0}function S_($){let{runner:Z}=$.get("vmClaim");if(!Z)return $.json({error:"No sandbox runner configured"},503);return Z}async function ph($){let{virtualMcpMetadata:Z,connectionIds:X}=$.get("vmClaim"),Q=$.var.studioContext,Y=Za(Z,X);if(!Y)throw new Q6(404,"AUTH","repo","Project has no GitHub repository");let G=t(Q);return RP0(Q,G.id,Y)}function B91($,Z){if(Z instanceof Q6){let Q=Z.status===404?404:Z.status===409||Z.status===422?409:502;return $.json({error:Z.message},Q,m5)}let X=Z instanceof Error?Z.message:String(Z);return $.json({error:X},502,m5)}async function Hg$($){try{let Z=await ph($),X=await bP0(Z,$.get("vmClaim").branch);return $.json(X,200,m5)}catch(Z){return B91($,Z)}}function Xa($,Z){let Q=(gP0.get($)??Promise.resolve()).catch(()=>{}).then(Z),Y=Q.catch(()=>{});return gP0.set($,Y),Y.finally(()=>{if(gP0.get($)===Y)gP0.delete($)}),Q}async function dZ($,Z,X){if($.get("vmClaim").fastPreview)return $.json({error:"sandbox not found: Fast Preview projects are sandbox-less"},404,m5);let Q=S_($);if(Q instanceof Response)return Q;let{claimName:Y,userId:G,projectRef:J}=$.get("vmClaim"),W=X?.method??"POST",K=null,H=new Headers;if(X?.jsonBody!==void 0)K=X.jsonBody,H.set("content-type","application/json");else if(X?.forwardJsonBody)K=await $.req.text(),H.set("content-type","application/json");let F=X?.signal,N={method:W,headers:H,body:K,...F?{signal:F}:{}},U=async()=>{let O=await Q.proxyDaemonRequest(Y,Z,N);if(X?.map404to410&&O.status===404){try{await O.body?.cancel()}catch{}if(await Q.adoptLiveClaim?.({userId:G,projectRef:J},Y))O=await Q.proxyDaemonRequest(Y,Z,N);if(O.status===404){try{await O.body?.cancel()}catch{}return new Response(JSON.stringify({error:"Sandbox handle is gone. The sandbox needs to be re-provisioned."}),{status:410,headers:{"content-type":"application/json",...m5}})}}let B=await O.text(),D=X?.redactRepoDirUnlessDesktop&&Q.kind!=="user-desktop"?KG6(B):B,L=O.headers.get("content-type")??"application/json";return new Response(D,{status:O.status,headers:{"content-type":L,...m5}})};try{if(F){let O=U();return O.catch(()=>{}),await Promise.race([O,new Promise((D,L)=>{if(F.aborted)return L(F.reason);F.addEventListener("abort",()=>L(F.reason),{once:!0})})])}return await U()}catch(O){let B=O instanceof Error?O.message:String(O);return $.json({error:`Daemon unreachable: ${B}`},502)}}function KG6($){try{let Z=JSON.parse($);if(Z&&typeof Z==="object"&&!Array.isArray(Z)&&"repoDir"in Z)return JSON.stringify({...Z,repoDir:null})}catch{}return $}async function hP0($,Z,X,Q="GET",Y){let G=await $.proxyDaemonRequest(Z,X,{method:Q,headers:new Headers,body:null});if(G.status===404&&Y){try{await G.body?.cancel()}catch{}if(await $.adoptLiveClaim?.(Y,Z))G=await $.proxyDaemonRequest(Z,X,{method:Q,headers:new Headers,body:null})}if(G.status===404){try{await G.body?.cancel()}catch{}throw Error("SANDBOX_GONE")}let J=await G.text();if(!G.ok){let W=`Daemon error (${G.status})`;try{W=JSON.parse(J).error??W}catch{}throw Error(W)}return JSON.parse(J)}function HG6($){return Fg$.includes($)}var XG6,Wg$=524288,YG6=65536,GG6=1e4,Kg$=2000,WG6,gP0,m5,Fg$,Ng$=()=>{let $=new F1;$.use("/:virtualMcpId/:branch/*",WG6),$.post("/:virtualMcpId/:branch/write",(X)=>dZ(X,"/_sandbox/write",{forwardJsonBody:!0,signal:V_(X)})),$.post("/:virtualMcpId/:branch/unlink",(X)=>dZ(X,"/_sandbox/unlink",{forwardJsonBody:!0,signal:V_(X)})),$.post("/:virtualMcpId/:branch/mkdir",(X)=>dZ(X,"/_sandbox/mkdir",{forwardJsonBody:!0,signal:V_(X)})),$.post("/:virtualMcpId/:branch/rename",(X)=>dZ(X,"/_sandbox/rename",{forwardJsonBody:!0,signal:V_(X)})),$.post("/:virtualMcpId/:branch/read",(X)=>dZ(X,"/_sandbox/read",{forwardJsonBody:!0,signal:V_(X)})),$.post("/:virtualMcpId/:branch/glob",(X)=>dZ(X,"/_sandbox/glob",{forwardJsonBody:!0,signal:V_(X)})),$.post("/:virtualMcpId/:branch/grep",(X)=>dZ(X,"/_sandbox/grep",{forwardJsonBody:!0,signal:V_(X)})),$.post("/:virtualMcpId/:branch/exec/:script",async(X)=>{let Q=X.req.param("script");if(!Q)return X.json({error:"missing script name"},400);return dZ(X,`/_sandbox/exec/${encodeURIComponent(Q)}`)}),$.post("/:virtualMcpId/:branch/exec/:script/kill",async(X)=>{let Q=X.req.param("script");if(!Q)return X.json({error:"missing script name"},400);return dZ(X,`/_sandbox/exec/${encodeURIComponent(Q)}/kill`)}),$.get("/:virtualMcpId/:branch/config",(X)=>dZ(X,"/_sandbox/config",{method:"GET",map404to410:!0,redactRepoDirUnlessDesktop:!0})),$.put("/:virtualMcpId/:branch/config",(X)=>dZ(X,"/_sandbox/config",{method:"PUT",forwardJsonBody:!0,map404to410:!0})),$.post("/:virtualMcpId/:branch/setup/:step",async(X)=>{let Q=X.req.param("step");if(!Q||!HG6(Q))return X.json({error:`step must be one of: ${Fg$.join(", ")}`},400);if(Q==="start"){let Y=X.get("vmClaim");if(Y.runner){let G=t(X.var.studioContext),J=Qy(Y.virtualMcpMetadata);try{await SO0({ctx:X.var.studioContext,runner:Y.runner,handle:Y.claimName,orgId:G.id,userId:Y.callerUserId,entries:J})}catch(W){let K=W instanceof Error?W.message:String(W);return X.json({error:`Failed to push env to daemon: ${K}`},502)}}}return dZ(X,`/_sandbox/setup/${Q}`,{signal:X.req.raw.signal,map404to410:!0})}),$.get("/:virtualMcpId/:branch/events",(X)=>{let Q=X.get("vmClaim");if(!Q.runner)return TN(X,async(Y)=>{await Y.writeSSE({event:"phase",data:JSON.stringify({kind:"failed",reason:"unknown",message:"No sandbox runner configured on this studio instance."})})});return Fy$(X,{ctx:X.var.studioContext,claimName:Q.claimName,runner:Q.runner,virtualMcpId:Q.virtualMcpId,branch:Q.branch,userId:Q.userId,projectRef:Q.projectRef,virtualMcpMetadata:Q.virtualMcpMetadata})}),$.get("/:virtualMcpId/:branch/git/status",(X)=>{if(X.get("vmClaim").fastPreview)return Hg$(X);return Z(X)});let Z=(X)=>dZ(X,"/_sandbox/git/status",{method:"GET",map404to410:!0,signal:AbortSignal.any([X.req.raw.signal,AbortSignal.timeout(Kg$)])});return $.post("/:virtualMcpId/:branch/git/status",(X)=>{if(X.get("vmClaim").fastPreview)return Hg$(X);return dZ(X,"/_sandbox/git/status",{map404to410:!0,signal:AbortSignal.any([X.req.raw.signal,AbortSignal.timeout(Kg$)])})}),$.post("/:virtualMcpId/:branch/git/diff",async(X)=>{let Q=X.get("vmClaim");if(Q.fastPreview)try{let Y=await X.req.json().catch(()=>({})),G=await ph(X),J=await xP0(G,Q.branch,Y.base);return X.json(J,200,m5)}catch(Y){return B91(X,Y)}return dZ(X,"/_sandbox/git/diff",{forwardJsonBody:!0,map404to410:!0})}),$.post("/:virtualMcpId/:branch/git/publish",async(X)=>{if(X.get("vmClaim").fastPreview)return X.json({ok:!0},200,m5);let Q=S_(X);if(Q instanceof Response)return Q;let{claimName:Y,virtualMcpMetadata:G,connectionIds:J}=X.get("vmClaim"),W=X.var.studioContext;return Xa(Y,async()=>{try{await n51(W,Q,Y);let K=Za(G,J);if(K)await Jg$(W,Q,Y,K)}catch(K){if(K instanceof k_)return X.json({error:K.message},403,m5);let H=K instanceof Error?K.message:String(K);return X.json({error:H},502,m5)}return dZ(X,"/_sandbox/git/publish",{forwardJsonBody:!0,map404to410:!0})})}),$.post("/:virtualMcpId/:branch/git/discard",async(X)=>{let Q=X.get("vmClaim");if(Q.fastPreview)return Xa(Q.claimName,async()=>{let Y=await X.req.json().catch(()=>({})),G=Array.isArray(Y.filepaths)?Y.filepaths.filter((J)=>typeof J==="string"):[];if(G.length===0)return X.json({error:"filepaths is required"},400,m5);try{let J=await ph(X);return await Xg$(J,Q.branch,G),X.json({ok:!0},200,m5)}catch(J){let W=J instanceof Q6&&J.status===409?409:502,K=J instanceof Error?J.message:String(J);return X.json({error:K},W,m5)}});return Xa(Q.claimName,()=>dZ(X,"/_sandbox/git/discard",{forwardJsonBody:!0,map404to410:!0}))}),$.post("/:virtualMcpId/:branch/git/rebase",async(X)=>{let Q=X.get("vmClaim");if(Q.fastPreview)return Xa(Q.claimName,async()=>{try{let W=await X.req.json().catch(()=>({})),K=await ph(X),H=W.base??await K.getDefaultBranch();return await yP0(K,Q.branch,H),X.json({ok:!0},200,m5)}catch(W){return B91(X,W)}});let Y=S_(X);if(Y instanceof Response)return Y;let{claimName:G}=X.get("vmClaim"),J=X.var.studioContext;return Xa(G,async()=>{try{await n51(J,Y,G)}catch(W){let K=W instanceof Error?W.message:String(W);return X.json({error:K},502,m5)}return dZ(X,"/_sandbox/git/rebase",{forwardJsonBody:!0,map404to410:!0})})}),$.post("/:virtualMcpId/:branch/git/suggest-commit",M9({maxSize:Wg$,onError:(X)=>X.json({error:"Payload too large"},413,m5)}),async(X)=>{let Q=X.get("vmClaim"),Y=null;if(!Q.fastPreview){let H=S_(X);if(H instanceof Response)return H;Y=H}let{claimName:G,userId:J,projectRef:W}=Q,K=X.var.studioContext;try{let H=await X.req.json().catch(()=>({})),F=H.status,N=H.diff,U=N!=null&&typeof N.diffs==="object"&&N.diffs!==null,[O,B]=r51(F)&&U?[F,N]:Y?await Promise.all([hP0(Y,G,"/_sandbox/git/status","GET",{userId:J,projectRef:W}),hP0(Y,G,"/_sandbox/git/diff","GET",{userId:J,projectRef:W})]):await(async()=>{let L=await ph(X);return Promise.all([bP0(L,Q.branch),xP0(L,Q.branch)])})(),D=await wy$(K,O,B);return X.json(D,200,m5)}catch(H){let F=H instanceof Error?H.message:String(H);if(F==="SANDBOX_GONE")return X.json({error:"Sandbox handle is gone. The sandbox needs to be re-provisioned."},410,m5);return X.json({error:F},502,m5)}}),$.post("/:virtualMcpId/:branch/git/judge-review",M9({maxSize:Wg$,onError:(X)=>X.json({error:"Payload too large"},413,m5)}),async(X)=>{let Q=X.get("vmClaim"),Y=null;if(!Q.fastPreview){let H=S_(X);if(H instanceof Response)return H;Y=H}let{claimName:G,userId:J,projectRef:W}=Q,K=X.var.studioContext;try{let H=await X.req.json().catch(()=>({})),F=H.status,N=H.diff,U=N!=null&&typeof N.diffs==="object"&&N.diffs!==null,[O,B]=r51(F)&&U?[F,N]:Y?await Promise.all([hP0(Y,G,"/_sandbox/git/status","GET",{userId:J,projectRef:W}),hP0(Y,G,"/_sandbox/git/diff","GET",{userId:J,projectRef:W})]):await(async()=>{let L=await ph(X);return Promise.all([bP0(L,Q.branch),xP0(L,Q.branch)])})(),D=await Ly$(K,O,B,typeof H.language==="string"?H.language:void 0);return X.json(D,200,m5)}catch(H){let F=H instanceof Error?H.message:String(H);if(F==="SANDBOX_GONE")return X.json({error:"Sandbox handle is gone. The sandbox needs to be re-provisioned."},410,m5);return X.json({error:F},502,m5)}}),$.get("/:virtualMcpId/:branch/preview-fetch",async(X)=>{let Q=S_(X);if(Q instanceof Response)return Q;let{claimName:Y}=X.get("vmClaim"),G=X.req.query("path");if(!G||!G.startsWith("/")||G.startsWith("//")||G.includes("..")||G.includes("\\"))return X.json({error:"Path not allowed"},403);let J;try{J=await Q.getPreviewUrl(Y)}catch{return X.json({error:"Preview not available"},502)}if(!J)return X.json({error:"Preview not available"},502);let W=J.replace(/\/+$/,""),K=U91(`${W}${G}`),H;try{H=await fetch(K?.url??`${W}${G}`,{...K?{headers:{host:K.hostHeader}}:{}})}catch{return X.json({error:"Preview unreachable"},502)}let F;try{F=await H.text()}catch{return X.json({error:"Preview unreachable"},502)}return new Response(F,{status:H.status,headers:{"content-type":H.headers.get("content-type")??"application/json"}})}),$.post("/:virtualMcpId/:branch/preview-invoke",M9({maxSize:YG6,onError:(X)=>X.json({error:"Payload too large"},413)}),async(X)=>{let Q=S_(X);if(Q instanceof Response)return Q;let{claimName:Y}=X.get("vmClaim"),G;try{G=await Q.getPreviewUrl(Y)}catch{return X.json({error:"Preview not available"},502)}if(!G)return X.json({error:"Preview not available"},502);let J;try{J=await X.req.json()}catch{return X.json({error:"Invalid JSON body"},400)}if(!J||typeof J!=="object"||Array.isArray(J))return X.json({error:"Invalid JSON body"},400);let W=Qg$(J);if(!W)return X.json({error:"Invalid or missing __resolveType"},400);let K=Yg$(G,W.resolveType),H=U91(K),F;try{F=await fetch(H?.url??K,{method:"POST",headers:{"content-type":"application/json",...H?{host:H.hostHeader}:{}},body:JSON.stringify(W.payload),signal:AbortSignal.timeout(30000)})}catch{return X.json({error:"Preview unreachable"},502)}let N;try{N=await F.text()}catch{return X.json({error:"Preview unreachable"},502)}return new Response(N,{status:F.status,headers:{"content-type":F.headers.get("content-type")??"application/json"}})}),$};var Ug$=w(()=>{w8();BN();uh();p51();TF();Ky$();S3();dX();U8();SB0();KB();Hy$();Ny$();Qp0();fp();e51();Ey$();X91();q_();N91();Gg$();O91();XG6=/^[a-zA-Z0-9][a-zA-Z0-9/._-]*$/;WG6=AP0(async($,Z)=>{let X=$.var.studioContext;try{r(X)}catch{return $.json({error:"Unauthorized"},401)}let Q=G1(X);if(!Q)return $.json({error:"Unauthorized"},401);let Y;try{Y=t(X)}catch{return $.json({error:"Organization scope required"},403)}let G=$.req.param("virtualMcpId"),J=$.req.param("branch");if(!G||!J)return $.json({error:"virtualMcpId and branch are required"},400);try{QG6(J)}catch(O){let B=O instanceof Error?O.message:String(O);return $.json({error:B},400)}let W=await X.storage.virtualMcps.findById(G);if(!W||W.organization_id!==Y.id)return $.json({error:"Virtual MCP not found"},404);let K=ai({orgId:Y.id,virtualMcpId:G,branch:J}),H=await vF(X,J,Q),F=Wy$({userId:H,projectRef:K}),N=W.metadata??null;if(FW$(N).fastPreviewCapability&&!JG6(N,H,J))return $.set("vmClaim",{claimName:F,callerUserId:Q,runner:null,virtualMcpId:G,branch:J,userId:H,projectRef:K,virtualMcpMetadata:N,connectionIds:W.connections?.map((O)=>O.connection_id)??[],fastPreview:!0}),Z();let U;try{U=(await oX(X,{userId:H,branch:J,virtualMcpMetadata:N})).provider}catch{U=null}if(!U)return $.json({error:"No sandbox runner found"},404);return $.set("vmClaim",{claimName:F,callerUserId:Q,runner:U,virtualMcpId:G,branch:J,userId:H,projectRef:K,virtualMcpMetadata:N,connectionIds:W.connections?.map((O)=>O.connection_id)??[]}),Z()});gP0=new Map;m5={"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache"};Fg$=["clone","install","start"]});function Og$($,Z,X){let Q=w91.get($);if(!Q)Q={pending:null,running:!1},w91.set($,Q);if(!Q.pending)Q.pending={set:new Map,del:new Set,deps:Z,resolvers:[],rejecters:[]};let Y=Q.pending;Y.deps=Z;for(let[J,W]of Object.entries(X.set??{}))Y.set.set(J,W),Y.del.delete(J);for(let J of X.delete??[])Y.del.add(J),Y.set.delete(J);let G=new Promise((J,W)=>{Y.resolvers.push(J),Y.rejecters.push(W)});if(!Q.running)NG6($,Q);return G}async function NG6($,Z){Z.running=!0;try{while(Z.pending){let X=Z.pending;Z.pending=null;try{let Q=await UG6(X);for(let Y of X.resolvers)Y(Q)}catch(Q){for(let Y of X.rejecters)Y(Q)}}}finally{if(Z.running=!1,!Z.pending)w91.delete($)}}async function UG6($){let{client:Z,branch:X,packagePath:Q}=$.deps;for(let Y=0;;Y++){let G=await $a(Z,X),J=await Z.getCommitTreeSha(G),W=await Z.getTreeRecursive(J),K=K91(W,Q),H=[],F=new Map(K.map((B)=>[B.path,{stem:B.stem,sha:B.sha}]));for(let[B,D]of $.set){let L=H91(K,B),E=`${JSON.stringify(D,null,2)}
2806
- `,j=await Z.createBlob(E);await $g$(Z.owner,Z.repo,j,E);let z=L[0]??`${vP0(Q)}/${Q91(B)}.json`;H.push({path:z,mode:"100644",type:"blob",sha:j});let A=z.slice(z.lastIndexOf("/")+1,-5);F.set(z,{stem:A,sha:j,content:E});for(let P of L.slice(1))H.push({path:P,mode:"100644",type:"blob",sha:null}),F.delete(P)}for(let B of $.del)for(let D of H91(K,B))H.push({path:D,mode:"100644",type:"blob",sha:null}),F.delete(D);if(H.length===0)return G;let N=Q?`${Q}/.deco/blocks.gen.json`:".deco/blocks.gen.json";if(W.some((B)=>B.type==="blob"&&B.path===N)){let B=await Promise.all([...F.values()].map(async(j)=>({stem:j.stem,content:j.content??await Z.getBlobText(j.sha)}))),{decofile:D,skipped:L}=rr(B);if(L.length>0)console.warn("decofile gen: dropped blocks that were not valid JSON",{repo:`${Z.owner}/${Z.repo}`,branch:X,packagePath:Q,blocks:L.map((j)=>j.key)});let E=await Z.createBlob(D);H.push({path:N,mode:"100644",type:"blob",sha:E})}let U=await Z.createTree(J,H),O=await Z.createCommit({message:OG6($),treeSha:U,parentShas:[G]});try{return await Z.updateRef(X,O),O}catch(B){if(!(B instanceof Q6&&B.status===422)||Y>=FG6-1)throw B;await q$(pZ(2000,200,Y,2,0.5))}}}function OG6($){let Z=(Y)=>{let G=Y.slice(0,3).join(", ");return Y.length>3?`${G} (+${Y.length-3} more)`:G},X=[];if($.set.size>0)X.push(`update ${Z([...$.set.keys()])}`);if($.del.size>0)X.push(`delete ${Z([...$.del])}`);let Q=`chore(decofile): ${X.join("; ")}`;return qd0(Q,$.deps.coAuthor)}var FG6=3,w91;var Bg$=w(()=>{AO0();qP0();u4();q_();fP0();w91=new Map});import{createHmac as wg$,randomBytes as BG6,timingSafeEqual as wG6}from"crypto";function Dg$(){if(uP0)return uP0;let $;try{let Z=b0();$=Z.studioJwtSecret??Z.betterAuthSecret}catch{$=void 0}return uP0=$?Buffer.from($):BG6(32),uP0}function D91($){let Z=$.nowMs??Date.now(),X={o:$.organizationId,m:$.virtualMcpId,b:$.branch,e:Math.floor((Z+DG6)/1000)},Q=Buffer.from(JSON.stringify(X)).toString("base64url"),Y=wg$("sha256",Dg$()).update(Q).digest("base64url");return`${Q}.${Y}`}function Lg$($,Z){let X=$.indexOf(".");if(X<0)return!1;let Q=$.slice(0,X),Y=Buffer.from($.slice(X+1)),G=Buffer.from(wg$("sha256",Dg$()).update(Q).digest("base64url"));if(Y.length!==G.length||!wG6(Y,G))return!1;let J;try{J=JSON.parse(Buffer.from(Q,"base64url").toString())}catch{return!1}let W=Math.floor((Z.nowMs??Date.now())/1000);return J.o===Z.organizationId&&J.m===Z.virtualMcpId&&J.b===Z.branch&&typeof J.e==="number"&&J.e>=W}var DG6=21600000,uP0=null;var Eg$=w(()=>{T$()});import{z as nh}from"zod";function EG6($){return $.length>0&&$.length<=255&&!$.includes("..")&&!$.endsWith("/")&&!$.endsWith(".lock")&&LG6.test($)}function zg$($){return $.req.header("x-forwarded-host")??new URL($.req.url).host}async function cP0($){let Z=$.get("decofileScope");return RP0($.var.studioContext,Z.organizationId,Z.githubRepo)}function lP0($,Z){if(Z instanceof Q6){let Q=Z.status===404?404:Z.status===409?409:Z.status===422?409:502;return $.json({error:Z.message},Q)}let X=Z instanceof Error?Z.message:String(Z);return $.json({error:X},500)}function Pg$(){let $=new F1;return $.use("/:virtualMcpId/:branch",jg$),$.use("/:virtualMcpId/:branch/*",jg$),$.get("/:virtualMcpId/:branch",async(Z)=>{let X=Z.get("decofileScope");try{let Q=await cP0(Z),Y=await Zg$(Q,X.branch,X.packagePath,{createBranchIfMissing:!!X.userId}),G={ETag:`"${Y.sha}"`,"Cache-Control":"no-store","Access-Control-Allow-Origin":"*"};if(Z.req.header("if-none-match")===`"${Y.sha}"`)return Z.body(null,304,G);if(!X.userId)return Z.body(Y.decofile,200,{...G,"content-type":"application/json"});let J=D91({organizationId:X.organizationId,virtualMcpId:X.virtualMcpId,branch:X.branch});return Z.body(`{"version":${JSON.stringify(Y.sha)},"token":${JSON.stringify(J)},"apiHost":${JSON.stringify(zg$(Z))},"decofile":${Y.decofile}}`,200,{...G,"content-type":"application/json"})}catch(Q){return lP0(Z,Q)}}),$.patch("/:virtualMcpId/:branch",async(Z)=>{let X=Z.get("decofileScope"),Q=Z.var.studioContext,Y=jG6.safeParse(await Z.req.json().catch(()=>null));if(!Y.success)return Z.json({error:"Invalid body",details:Y.error.issues},400);let G=Y.data;for(let J of[...Object.keys(G.set??{}),...G.delete??[]])try{IP0(J)}catch(W){let K=W instanceof Error?W.message:String(W);return Z.json({error:K},400)}for(let[J,W]of Object.entries(G.set??{}))if(typeof W!=="object"||W===null||Array.isArray(W))return Z.json({error:`Block "${J}" must be a JSON object`},400);try{let J=await cP0(Z),W=await Og$(`${X.organizationId}/${X.virtualMcpId}/${X.branch}`,{client:J,branch:X.branch,packagePath:X.packagePath,coAuthor:ch(Q)},G),K=D91({organizationId:X.organizationId,virtualMcpId:X.virtualMcpId,branch:X.branch});return Z.json({version:W,token:K,apiHost:zg$(Z)})}catch(J){return lP0(Z,J)}}),$.post("/:virtualMcpId/:branch/publish",async(Z)=>{let X=Z.get("decofileScope");try{let Q=await cP0(Z),Y=await Q.getDefaultBranch();if(Y===X.branch)return Z.json({error:"Branch is already the default branch"},400);let G=`chore(decofile): publish ${X.branch}`;try{let J;try{J=await Q.mergeBranch(Y,X.branch,G)}catch(W){if(!(W instanceof Q6&&W.status===409))throw W;await yP0(Q,X.branch,Y),J=await Q.mergeBranch(Y,X.branch,G)}return J?Z.json({result:"merged",sha:J}):Z.json({result:"up-to-date"})}catch(J){if(J instanceof Q6&&J.status===409)return Z.json({error:"merge-conflict"},409);if(J instanceof Q6&&J.status===405){let K=await Q.findOpenPullRequest(Y,X.branch)??await Q.createPullRequest({base:Y,head:X.branch,title:`Publish ${X.branch}`});return Z.json({result:"pull-request",number:K.number,url:K.html_url})}throw J}}catch(Q){return lP0(Z,Q)}}),$.get("/:virtualMcpId/:branch/status",async(Z)=>{let X=Z.get("decofileScope");try{let Q=await cP0(Z),Y=await Q.getDefaultBranch();if(Y===X.branch)return Z.json({baseBranch:Y,aheadBy:0,behindBy:0});try{let{aheadBy:G,behindBy:J}=await Q.compare(Y,X.branch);return Z.json({baseBranch:Y,aheadBy:G,behindBy:J})}catch(G){if(G instanceof Q6&&G.status===404)return Z.json({baseBranch:Y,aheadBy:0,behindBy:0});throw G}}catch(Q){return lP0(Z,Q)}}),$}var LG6,jG6,jg$;var Ag$=w(()=>{qP0();w8();p51();TP0();O91();X91();Bg$();Eg$();N91();q_();fP0();LG6=/^[a-zA-Z0-9][a-zA-Z0-9/._-]*$/;jG6=nh.object({set:nh.record(nh.string(),nh.unknown()).optional(),delete:nh.array(nh.string()).optional()}).refine(($)=>Object.keys($.set??{}).length>0||($.delete?.length??0)>0,{message:"Patch must set or delete at least one block"}),jg$=AP0(async($,Z)=>{let X=$.var.studioContext,Q=X.organization;if(!Q)return $.json({error:"Organization scope required"},500);let Y=$.req.param("virtualMcpId"),G=$.req.param("branch");if(!Y||!G)return $.json({error:"virtualMcpId and branch are required"},400);if(!EG6(G))return $.json({error:`Invalid branch name: ${G}`},400);let J=X.auth?.user?.id??null;if(!J){let O=$.req.query("token");if(!($.req.method==="GET"&&!$.req.path.match(/\/(publish|status)$/)))return $.json({error:"Unauthorized"},401);if(!O||!Lg$(O,{organizationId:Q.id,virtualMcpId:Y,branch:G}))return $.json({error:"Unauthorized"},401)}let W=await X.storage.virtualMcps.findById(Y);if(!W||W.organization_id!==Q.id)return $.json({error:"Virtual MCP not found"},404);let K=W.metadata??null;if(!VB0(K)||K?.fastPreview!==!0)return $.json({error:"Fast Preview is not enabled for this project"},404);let F=W.connections?.map((O)=>O.connection_id)??[],N=Za(K,F);if(!N)return $.json({error:"Project has no GitHub repository"},404);let U=K?.runtime;return $.set("decofileScope",{organizationId:Q.id,virtualMcpId:Y,branch:G,packagePath:U?.path?.replace(/^\/+|\/+$/g,"")||null,githubRepo:N,userId:J}),Z()})});var Tg$=($)=>{let Z=new F1;if(Z.use("*",D_),Z.route("/",hz0()),Z.route("/",iv$()),Z.route("/",tx$()),Z.route("/",ix$()),Z.route("/",jP0()),Z.route("/tools",Zy$()),Z.route("/",sx$()),Z.route("/",Mx$({kvStorage:$.kvStorage})),Z.route("/",Ix$()),Z.route("/fs",gx$({getConnection:$.getNatsConnection})),Z.route("/sandbox",Ng$()),Z.route("/decofile",Pg$()),Z.route("/",lx$()),Z.route("/deco-sites",cz0()),Z.route("/sso",vz0()),Z.route("/",zP0({tokenStorage:$.tokenStorage,automationEventDispatcher:$.automationEventDispatcher})),Z.route("/webhooks",yv$()),$.mountDevAssets)Z.route("/dev-assets",lz0({orgFromPath:!0}));return Z.use("/mcp/:connectionId?",$.mcpAuth),Z.use("/mcp/:connectionId/ui-resource",$.mcpAuth),Z.use("/mcp/gateway/:virtualMcpId?",$.mcpAuth),Z.use("/mcp/virtual-mcp/:virtualMcpId?",$.mcpAuth),Z.use("/mcp/self",$.mcpAuth),Z.use("/mcp/task-run/:threadId",$.mcpAuth),Z.route("/",jC$()),Z.get("/mcp/:gateway?/:connectionId/.well-known/oauth-protected-resource/*",$.betterAuthProtectedResourceHandler),Z.get("/mcp/.well-known/oauth-protected-resource",$.betterAuthProtectedResourceHandler),Z.route("/mcp/task-run",ux$()),Z.route("/mcp",nw0()),Z.route("/mcp/self",EP0()),Z.route("/mcp",rw0()),Z.all("/oauth-proxy/:connectionId/*",$.oauthProxyHandler),Z.get("/watch",$.watchHandler),Z};var Rg$=w(()=>{w8();B61();gv$();E61();dz0();Ar();U61();qx$();kx$();hx$();_n();Y61();aw0();h51();cx$();dx$();px$();ox$();ex$();c51();Xy$();l51();tw0();Ug$();Ag$()});function zG6($){return $.filter((Z)=>Z.vendors?.alias).map((Z)=>({name:Z.name,title:Z.title,description:Z.description,logo:Z.logo,category:Z.category,vendor:{alias:Z.vendors.alias,url:Z.vendors.url}}))}var PG6=async($,Z)=>{if(!$.get("studioContext").auth.user?.id)return $.json({error:"Unauthorized"},401);return Z()},Ig$=()=>{let $=new F1;return $.use("*",PG6),$.get("/",async(Z)=>{let X=b0(),Q=X.decoSupabaseUrl,Y=X.decoSupabaseServiceKey;if(!Q||!Y)return Z.json({apps:[]});try{let G=await lZ(Q,Y,"apps?select=name,title,description,logo,category,vendors(alias,url)");return Z.json({apps:zG6(G)})}catch(G){return console.error("[deco-apps] GET error:",G),Z.json({error:"Failed to fetch apps"},502)}}),$};var qg$=w(()=>{w8();T$();cj0()});import{z as M1}from"zod";function QH($,Z="invalid_request_error",X=null,Q=null){return{error:{message:$,type:Z,param:X,code:Q}}}function CG6($){if(!$)return null;let Z=$.indexOf(":");if(Z===-1)return{credentialId:null,modelId:$};let X=$.substring(0,Z),Q=$.substring(Z+1);if(!X||!Q)return null;return{credentialId:X,modelId:Q}}function _G6($,Z,X){try{return JSON.parse($)}catch{throw new Vg$(`Invalid JSON in tool call arguments for function '${X}' (tool_call_id: ${Z}): ${$}`)}}function vG6($){let Z={};for(let X of $)if(X.role==="assistant"&&X.tool_calls)for(let Q of X.tool_calls)Z[Q.id]=Q.function.name;return $.map((X)=>{switch(X.role){case"system":return{role:"system",content:X.content};case"user":if(typeof X.content==="string")return{role:"user",content:X.content};return{role:"user",content:X.content.map((Y)=>{if(Y.type==="text")return{type:"text",text:Y.text};return{type:"image",image:Y.image_url.url}})};case"assistant":if(X.tool_calls&&X.tool_calls.length>0)return{role:"assistant",content:X.tool_calls.map((Y)=>({type:"tool-call",toolCallId:Y.id,toolName:Y.function.name,input:_G6(Y.function.arguments,Y.id,Y.function.name)}))};return{role:"assistant",content:X.content??""};case"tool":let Q=Z[X.tool_call_id]??"unknown";return{role:"tool",content:[{type:"tool-result",toolCallId:X.tool_call_id,toolName:Q,output:{type:"text",value:X.content}}]}}})}function fG6($){let Z=$.map((X)=>{let Q=X.function.parameters?xY(X.function.parameters):xY({type:"object",properties:{}});return[X.function.name,b$({description:X.function.description,inputSchema:Q})]});return Object.fromEntries(Z)}function bG6($){if(!$)return;return{openai:{response_format:$}}}function xG6(){return`chatcmpl-${crypto.randomUUID().replace(/-/g,"").substring(0,29)}`}function Mg$($,Z,X,Q,Y,G){let J={model:$,messages:Z,tools:X,temperature:Q.temperature,maxTokens:Q.max_tokens,topP:Q.top_p,frequencyPenalty:Q.frequency_penalty,presencePenalty:Q.presence_penalty,stopSequences:Q.stop?Array.isArray(Q.stop)?Q.stop:[Q.stop]:void 0,abortSignal:G};return Y?{...J,providerOptions:Y}:J}function kg$($){if($==="tool-calls")return"tool_calls";if($==="length")return"length";return"stop"}var AG6=256,TG6,RG6,IG6,qG6,MG6,kG6,VG6,SG6,Vg$,Sg$,Cg$;var _g$=w(()=>{_4();w8();uh();XN();TG6=M1.object({type:M1.literal("function"),function:M1.object({name:M1.string(),description:M1.string().optional(),parameters:M1.record(M1.string(),M1.unknown()).optional()})}),RG6=M1.object({id:M1.string(),type:M1.literal("function"),function:M1.object({name:M1.string(),arguments:M1.string()})}),IG6=M1.discriminatedUnion("role",[M1.object({role:M1.literal("system"),content:M1.string(),name:M1.string().optional()}),M1.object({role:M1.literal("user"),content:M1.union([M1.string(),M1.array(M1.union([M1.object({type:M1.literal("text"),text:M1.string()}),M1.object({type:M1.literal("image_url"),image_url:M1.object({url:M1.string(),detail:M1.string().optional()})})]))]),name:M1.string().optional()}),M1.object({role:M1.literal("assistant"),content:M1.string().nullable().optional(),name:M1.string().optional(),tool_calls:M1.array(RG6).optional()}),M1.object({role:M1.literal("tool"),content:M1.string(),tool_call_id:M1.string()})]),qG6=M1.object({type:M1.literal("text")}),MG6=M1.object({type:M1.literal("json_object")}),kG6=M1.object({type:M1.literal("json_schema"),json_schema:M1.object({name:M1.string(),description:M1.string().optional(),schema:M1.record(M1.string(),M1.unknown()),strict:M1.boolean().optional()})}),VG6=M1.union([qG6,MG6,kG6]),SG6=M1.object({model:M1.string().describe("Format: 'model_id' or 'credential_id:model_id'"),messages:M1.array(IG6),stream:M1.boolean().optional().default(!1),temperature:M1.number().min(0).max(2).optional(),max_tokens:M1.number().positive().optional(),top_p:M1.number().min(0).max(1).optional(),frequency_penalty:M1.number().min(-2).max(2).optional(),presence_penalty:M1.number().min(-2).max(2).optional(),stop:M1.union([M1.string(),M1.array(M1.string())]).optional(),tools:M1.array(TG6).optional(),tool_choice:M1.union([M1.literal("auto"),M1.literal("none"),M1.literal("required"),M1.object({type:M1.literal("function"),function:M1.object({name:M1.string()})})]).optional(),response_format:VG6.optional(),user:M1.string().optional()});Vg$=class Vg$ extends Error{constructor($){super($);this.name="MessageConversionError"}};Sg$=new F1;Sg$.post("/:org/v1/chat/completions",async($)=>{let Z=$.get("studioContext"),X=$.req.param("org");try{if(!Z.auth.apiKey?.id)return $.json(QH("API key authentication required. Provide a valid API key via Authorization header.","authentication_error"),401);if(!Z.organization)return $.json(QH("Organization context is required. Ensure your API key has organization metadata.","invalid_request_error","organization"),400);if((Z.organization.slug??Z.organization.id)!==X)return $.json(QH("Organization mismatch. The API key's organization does not match the requested organization.","invalid_request_error","organization"),403);let Q=await $.req.json(),Y=SG6.safeParse(Q);if(!Y.success){let L=Y.error.issues[0]??{message:"Invalid request",path:[]};return $.json(QH(`Invalid request: ${L.message}`,"invalid_request_error",L.path.length>0?L.path.join("."):null),400)}let G=Y.data,J=CG6(G.model);if(!J)return $.json(QH("Invalid model format. Expected 'model_id' or 'credential_id:model_id' (e.g., 'claude-sonnet-4-6' or 'key_abc123:claude-sonnet-4-6')","invalid_request_error","model"),400);let{credentialId:W}=J,{modelId:K}=J;if(!W){let E=(await Z.storage.aiProviderKeys.list({organizationId:Z.organization.id})).find((j)=>VD(j.providerId));if(!E)return $.json(QH("No AI provider credentials configured for this organization. Add a credential in settings or specify one explicitly via 'credential_id:model_id'.","invalid_request_error","model"),400);W=E.id}let H;try{H=await Z.aiProviders.activate(W,Z.organization.id)}catch{return $.json(QH(`AI provider credential not found or inaccessible: ${W}`,"invalid_request_error","model"),404)}let F=H.aiSdk.languageModel(K),N=vG6(G.messages),U=G.tools?fG6(G.tools):void 0,O=bG6(G.response_format),B=xG6(),D=Math.floor(Date.now()/1000);if(G.stream)return TN($,async(L)=>{let E=Mg$(F,N,U,G,O,$.req.raw.signal);try{let j=iO(E),z=!1,A=0,P="",M=async()=>{if(P.length===0)return;let q=P;P="",await L.writeSSE({data:JSON.stringify({id:B,object:"chat.completion.chunk",created:D,model:G.model,choices:[{index:0,delta:{content:q},finish_reason:null}]})})};for await(let q of j.fullStream){if(!z&&(q.type==="text-delta"||q.type==="tool-call"))await L.writeSSE({data:JSON.stringify({id:B,object:"chat.completion.chunk",created:D,model:G.model,choices:[{index:0,delta:{role:"assistant",content:""},finish_reason:null}]})}),z=!0;if(q.type==="text-delta"){if(P+=q.text,P.length>=AG6)await M()}else if(q.type==="tool-call"){await M();let k=A++;await L.writeSSE({data:JSON.stringify({id:B,object:"chat.completion.chunk",created:D,model:G.model,choices:[{index:0,delta:{tool_calls:[{index:k,id:q.toolCallId,type:"function",function:{name:q.toolName,arguments:JSON.stringify(q.input)}}]},finish_reason:null}]})})}else if(q.type==="finish")await M(),await L.writeSSE({data:JSON.stringify({id:B,object:"chat.completion.chunk",created:D,model:G.model,choices:[{index:0,delta:{},finish_reason:kg$(q.finishReason)}],usage:q.totalUsage?{prompt_tokens:q.totalUsage.inputTokens??0,completion_tokens:q.totalUsage.outputTokens??0,total_tokens:q.totalUsage.totalTokens??0}:void 0})})}await M(),await L.writeSSE({data:"[DONE]"})}catch(j){let z=j;console.error("[openai-compat:stream] Error:",z.message),await L.writeSSE({data:JSON.stringify({error:{message:z.message,type:"server_error"}})})}});else{let L=Mg$(F,N,U,G,O,$.req.raw.signal),E=await dO(L),j={role:"assistant",content:E.text||null};if(E.toolCalls&&E.toolCalls.length>0)j.tool_calls=E.toolCalls.map((z)=>({id:z.toolCallId,type:"function",function:{name:z.toolName,arguments:JSON.stringify("input"in z?z.input:{})}})),j.content=null;return $.json({id:B,object:"chat.completion",created:D,model:G.model,choices:[{index:0,message:j,finish_reason:kg$(E.finishReason)}],usage:{prompt_tokens:E.usage?.inputTokens??0,completion_tokens:E.usage?.outputTokens??0,total_tokens:E.usage?.totalTokens??0}})}}catch(Q){let Y=Q;if(Y.name==="AbortError")return $.json(QH("Request aborted","invalid_request_error"),400);if(Y.name==="MessageConversionError")return $.json(QH(Y.message,"invalid_request_error","messages"),400);return console.error("[openai-compat] Error:",Y.message,Y.stack),$.json(QH(Y.message,"server_error"),500)}});Cg$=Sg$});function vg$(){let $=new F1;return $.use("*",async(Z,X)=>{await X(),Z.header("Cache-Control","private, no-store"),Z.header("Vary","Cookie")}),$.get("/",async(Z)=>{let X=Z.get("studioContext"),Q=G1(X);if(!Q)return Z.json({error:"Authentication required"},401);let G=(Z.req.query("site")??"").trim().toLowerCase();if(!oK(G))return Z.json({error:"Invalid site slug"},400);let J=await X.db.selectFrom("member").innerJoin("organization","organization.id","member.organizationId").select(["organization.id as id","organization.slug as slug","organization.name as name","organization.metadata as metadata"]).where("member.userId","=",Q).execute(),W=[];for(let H of J){if(!H.slug||J7(H))continue;let F=await X.storage.virtualMcps.list(H.id);for(let N of F){if(N.title.toLowerCase()!==G)continue;W.push({orgSlug:H.slug,orgName:H.name??H.slug,project:{id:N.id,title:N.title,icon:N.icon??null}})}}let K={matches:W};return Z.json(K)}),$}var fg$=w(()=>{w8();W_()});var xg$;var bg$=w(()=>{xg$={name:"decocms",version:"4.242.8",description:"Deco CMS \u2014 Self-hostable MCP Gateway for managing AI connections and tools",author:"Deco team",repository:{type:"git",url:"git+https://github.com/decocms/studio.git",directory:"apps/api"},bugs:{url:"https://github.com/decocms/studio/issues"},type:"module",bin:{deco:"./dist/server/cli.js"},files:["dist/**/*"],scripts:{dev:"bun run migrate && bun run dev:server","dev:server":"bun run --cwd=../../packages/sandbox build && NODE_ENV=development bun --env-file=.env --hot run src/index.ts",build:"bun run build:server","build:server":"bun run scripts/bundle-server-script.ts --dist ./dist/server","generate:tool-contracts":"bun run scripts/generate-tool-contracts.ts","db:migrate":"bun run ./dist/server/migrate.js","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","@nats-io/jwt":"0.0.10-5","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.211.0","@opentelemetry/exporter-logs-otlp-proto":"^0.211.0","@opentelemetry/exporter-prometheus":"^0.208.0","@opentelemetry/exporter-trace-otlp-proto":"^0.207.0","@opentelemetry/instrumentation-runtime-node":"^0.24.0","@opentelemetry/resources":"^2.6.0","@opentelemetry/sdk-logs":"^0.211.0","@opentelemetry/sdk-metrics":"^2.2.0","@opentelemetry/sdk-node":"^0.207.0","@opentelemetry/sdk-trace-base":"^2.5.0","@types/bun":"^1.3.1","@types/google.maps":"^3.65.2","@types/pg":"^8.15.6","@types/react-syntax-highlighter":"^15.5.13","@vercel/nft":"^1.1.1",ai:"^6.0.208","better-auth":"1.4.22",croner:"^9.1.0",degit:"^2.8.4",hono:"^4.10.7",jose:"^6.0.11",nanoid:"^5.1.6",pg:"^8.16.3",typescript:"^7.0.2",typescript5:"npm:typescript@^5.9.3",zod:"4.3.6"},homepage:"https://github.com/decocms/studio",keywords:["mcp","model-context-protocol","ai","gateway","self-hosted","tools"],license:"MIT",publishConfig:{access:"public"}}});function hG6(){let $=process.env.POSTHOG_KEY;if(!$)return null;return{key:$,host:process.env.POSTHOG_HOST??gG6}}var yg$,gG6="https://ph.studio.decocms.com",gg$;var hg$=w(()=>{w8();Jh0();QC();v9();T$();e41();bg$();yg$=new F1;yg$.get("/",($)=>{let Z={version:xg$.version,theme:Ud1(),...jL().logo&&{logo:jL().logo},...TK()&&{internalUrl:lV1()},...b0().enableDecoImport&&{enableDecoImport:!0},brandExtractEnabled:!!b0().firecrawlApiKey,auth:Xv$(),posthog:hG6(),googleMapsApiKey:process.env.GOOGLE_MAPS_API_KEY?.trim()||null,runtime:{agentSandbox:!TK()&&b0().sandboxProviderKind==="agent-sandbox"}};return $.header("Cache-Control","no-store"),$.json({success:!0,config:Z})});gg$=yg$});function th($){let Z=($??"").trim().toLowerCase();return Z=Z.replace(/^https?:\/\//,""),Z=Z.replace(/^www\./,""),Z=Z.split(/[/?#]/)[0]??"",Z.replace(/\/+$/,"")}function L91($){return(th($).split(".")[0]||$).replace(/[-_]/g," ").split(" ").filter(Boolean).map((X)=>X.charAt(0).toUpperCase()+X.slice(1)).join(" ")}function cg$($,Z=64){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(th($))}&sz=${Z}`}function ug$($,Z){let X=$.trim();if(X.length<=Z)return X;let Q=X.slice(0,Z-1),Y=Q.lastIndexOf(" ");return`${(Y>Z*0.6?Q.slice(0,Y):Q).trimEnd()}\u2026`}function lg$($){let{brand:Z,domain:X,score:Q,verdict:Y}=$,G=typeof Q==="number"?`${Z} commerce report \u2014 ${Math.round(Q)}/100 \xB7 decocms`:`${Z} commerce report \xB7 decocms`,J=`See the full ${Z} scorecard \u2014 SEO, performance, conversion & AEO signals scored by decocms.`,W=Y?.trim()?ug$(`${Y.trim().replace(/\s+/g," ")} \u2014 ${J}`,200):ug$(`How does ${X} really perform? ${J}`,200);return{title:G,description:W}}import{z as l0}from"zod";var C_,uG6,cG6,lG6,dG6,dg$;var mg$=w(()=>{C_=l0.enum(["good","bad","neutral"]),uG6=l0.preprocess(($)=>{if(Array.isArray($))return{kind:"text",value:$.find((X)=>X!==null&&typeof X!=="object")??""};return $!==null&&typeof $==="object"?$:{kind:"text",value:$}},l0.object({kind:l0.enum(["text","number","sparkline","badge","score"]).catch("text"),value:l0.coerce.string().optional(),tone:C_.optional(),muted:l0.boolean().optional(),delta:l0.coerce.string().optional(),deltaDir:l0.enum(["up","down","neutral"]).optional(),points:l0.array(l0.coerce.number()).optional(),label:l0.coerce.string().optional()}).transform(($)=>{if($.kind==="badge"&&$.label==null)$.label=$.value??"";if($.kind==="score"){let Z=Number($.value);if(Number.isNaN(Z))return{...$,kind:"text"}}return $})),cG6=l0.preprocess(($)=>{let Z=$;if(Z&&typeof Z==="object"&&!Array.isArray(Z)&&Array.isArray(Z.cells))Z=Z.cells;if(Array.isArray(Z)&&Z.length===1&&Array.isArray(Z[0]))Z=Z[0];if(Array.isArray(Z))return Z;if(Z&&typeof Z==="object")return Object.values(Z);return Z},l0.array(uG6)),lG6={key:l0.coerce.string(),title:l0.coerce.string(),eyebrow:l0.coerce.string().optional(),headline:l0.coerce.string(),annotation:l0.coerce.string().optional(),methodology:l0.coerce.string().optional(),sources:l0.array(l0.object({name:l0.coerce.string(),logoUrl:l0.coerce.string()})).optional()},dG6=l0.discriminatedUnion("template",[l0.object({template:l0.literal("cover"),score:l0.object({value:l0.coerce.number(),max:l0.coerce.number().optional(),grade:l0.coerce.string().optional(),label:l0.coerce.string().optional()}).optional(),brandImage:l0.coerce.string().optional(),screenshot:l0.coerce.string().optional(),mobileScreenshot:l0.coerce.string().optional()}),l0.object({template:l0.literal("cta"),ctaUrl:l0.coerce.string().optional(),ctaLabel:l0.coerce.string().optional(),bullets:l0.array(l0.coerce.string()).optional()}),l0.object({template:l0.literal("series"),points:l0.array(l0.coerce.number()).min(2),xLabels:l0.array(l0.coerce.string()).min(1),unit:l0.coerce.string().optional(),callout:l0.object({index:l0.coerce.number(),value:l0.coerce.string(),tone:C_.optional()})}),l0.object({template:l0.literal("threshold"),value:l0.coerce.string().default(""),metricLabel:l0.coerce.string().optional(),ratio:l0.coerce.number(),thresholdRatio:l0.coerce.number().optional(),thresholdLabel:l0.coerce.string().default(""),tone:C_.optional()}),l0.object({template:l0.literal("stats"),stats:l0.array(l0.object({value:l0.coerce.string(),label:l0.coerce.string(),tone:C_.optional()})).min(1)}),l0.object({template:l0.literal("bars"),items:l0.array(l0.object({value:l0.coerce.string(),label:l0.coerce.string(),ratio:l0.coerce.number(),tone:C_.optional()})).min(1)}),l0.object({template:l0.literal("gauges"),gauges:l0.array(l0.object({label:l0.coerce.string(),value:l0.coerce.string(),status:l0.enum(["good","warn","bad"]).catch("warn"),caption:l0.coerce.string().optional(),ratio:l0.coerce.number().optional()})).min(1)}),l0.object({template:l0.literal("checklist"),checks:l0.array(l0.object({label:l0.coerce.string(),status:l0.enum(["pass","fail","warn"]).catch("fail"),value:l0.coerce.string().optional()})).min(1)}),l0.object({template:l0.literal("table"),columns:l0.array(l0.object({label:l0.coerce.string(),align:l0.enum(["left","right"]).optional()})).min(1),rows:l0.array(cG6).min(1),highlightRow:l0.coerce.number().optional()}),l0.object({template:l0.literal("products"),products:l0.array(l0.object({name:l0.coerce.string(),price:l0.coerce.string().optional(),image:l0.coerce.string().optional(),url:l0.coerce.string().optional()})).min(1)}),l0.object({template:l0.literal("list"),entries:l0.array(l0.object({label:l0.coerce.string(),severity:l0.enum(["error","warning","notice"]).catch("notice")})).min(1),moreCount:l0.coerce.number().optional()}),l0.object({template:l0.literal("keywords"),volumeLabel:l0.coerce.string().optional(),keywords:l0.array(l0.object({term:l0.coerce.string(),volume:l0.coerce.string(),position:l0.coerce.number().catch(0)})).min(1)}),l0.object({template:l0.literal("competitor"),metricLabel:l0.coerce.string().optional(),competitors:l0.array(l0.object({name:l0.coerce.string(),value:l0.coerce.string(),tone:C_.optional(),isYou:l0.boolean().optional()})).min(1)}),l0.object({template:l0.literal("scorecard"),rivalLabel:l0.coerce.string().optional(),dimensions:l0.array(l0.object({label:l0.coerce.string(),you:l0.coerce.string(),rival:l0.coerce.string().optional(),rivalName:l0.coerce.string().optional(),tone:C_.optional()})).min(1)})]),dg$=l0.object({...lG6,template:dG6})});function dP0($){let Z=[],X=[...$.sections].sort((Y,G)=>Y.position-G.position).map((Y)=>{let G=dg$.safeParse(Y.props);if(G.success)return G.data;let J=G.error.issues[0];return Z.push({section_type:Y.section_type,position:Y.position,reason:J?`${J.path.join(".")||"(root)"}: ${J.message}`:"contract violation"}),null}).filter((Y)=>Y!==null),Q=X.filter((Y)=>Y.template.template!=="cover"&&Y.template.template!=="cta").map((Y)=>({key:Y.key,title:Y.title}));return{deck:{meta:{...$.meta,scores:$.summary?.scores,scannedAt:$.scanned_at,toc:Q},slides:X},drops:Z}}var E91=w(()=>{mg$()});import{join as ig$}from"path";async function iG6($){try{let Z=await fetch(`${oW({})}/api/v2/public/diagnostics/${encodeURIComponent($)}`,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(mG6)});if(!Z.ok)return null;let X=await Z.json(),{deck:Q}=dP0(X);if(!Q.slides.length)return null;let Y=Q.slides.find((W)=>W.template.template==="cover"),G=Y?.template,J=G&&G.template==="cover"?G:void 0;return{brand:Q.meta.brand?.trim()||L91($),score:Q.meta.scores?.cover??J?.score?.value,verdict:Y?.annotation?.trim()||Y?.headline?.trim()||void 0}}catch{return null}}function YG($){return $.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;")}function pG6($,Z){let X=th($),Q=Z?.brand?.trim()||L91(X),Y=cg$(X,128),J=`${(b0().baseUrl??"https://studio.decocms.com").replace(/\/+$/,"")}/report/${encodeURIComponent(X)}`,{title:W,description:K}=lg$({brand:Q,domain:X,score:Z?.score,verdict:Z?.verdict}),H=`${J}/og.png`,F=`${Q} commerce report by decocms`;return[`<title>${YG(W)}</title>`,`<meta name="description" content="${YG(K)}" />`,'<meta name="robots" content="noindex, follow" />','<meta property="og:type" content="website" />','<meta property="og:site_name" content="decocms" />',`<meta property="og:title" content="${YG(W)}" />`,`<meta property="og:description" content="${YG(K)}" />`,`<meta property="og:url" content="${YG(J)}" />`,`<meta property="og:image" content="${YG(H)}" />`,'<meta property="og:image:width" content="1200" />','<meta property="og:image:height" content="630" />',`<meta property="og:image:alt" content="${YG(F)}" />`,'<meta name="twitter:card" content="summary_large_image" />',`<meta name="twitter:title" content="${YG(W)}" />`,`<meta name="twitter:description" content="${YG(K)}" />`,`<meta name="twitter:image" content="${YG(H)}" />`,`<meta name="twitter:image:alt" content="${YG(F)}" />`,`<link rel="canonical" href="${YG(J)}" />`,`<link rel="icon" href="${YG(Y)}" sizes="any" />`].join(`
2806
+ `,j=await Z.createBlob(E);await $g$(Z.owner,Z.repo,j,E);let z=L[0]??`${vP0(Q)}/${Q91(B)}.json`;H.push({path:z,mode:"100644",type:"blob",sha:j});let A=z.slice(z.lastIndexOf("/")+1,-5);F.set(z,{stem:A,sha:j,content:E});for(let P of L.slice(1))H.push({path:P,mode:"100644",type:"blob",sha:null}),F.delete(P)}for(let B of $.del)for(let D of H91(K,B))H.push({path:D,mode:"100644",type:"blob",sha:null}),F.delete(D);if(H.length===0)return G;let N=Q?`${Q}/.deco/blocks.gen.json`:".deco/blocks.gen.json";if(W.some((B)=>B.type==="blob"&&B.path===N)){let B=await Promise.all([...F.values()].map(async(j)=>({stem:j.stem,content:j.content??await Z.getBlobText(j.sha)}))),{decofile:D,skipped:L}=rr(B);if(L.length>0)console.warn("decofile gen: dropped blocks that were not valid JSON",{repo:`${Z.owner}/${Z.repo}`,branch:X,packagePath:Q,blocks:L.map((j)=>j.key)});let E=await Z.createBlob(D);H.push({path:N,mode:"100644",type:"blob",sha:E})}let U=await Z.createTree(J,H),O=await Z.createCommit({message:OG6($),treeSha:U,parentShas:[G]});try{return await Z.updateRef(X,O),O}catch(B){if(!(B instanceof Q6&&B.status===422)||Y>=FG6-1)throw B;await q$(pZ(2000,200,Y,2,0.5))}}}function OG6($){let Z=(Y)=>{let G=Y.slice(0,3).join(", ");return Y.length>3?`${G} (+${Y.length-3} more)`:G},X=[];if($.set.size>0)X.push(`update ${Z([...$.set.keys()])}`);if($.del.size>0)X.push(`delete ${Z([...$.del])}`);let Q=`chore(decofile): ${X.join("; ")}`;return qd0(Q,$.deps.coAuthor)}var FG6=3,w91;var Bg$=w(()=>{AO0();qP0();u4();q_();fP0();w91=new Map});import{createHmac as wg$,randomBytes as BG6,timingSafeEqual as wG6}from"crypto";function Dg$(){if(uP0)return uP0;let $;try{let Z=b0();$=Z.studioJwtSecret??Z.betterAuthSecret}catch{$=void 0}return uP0=$?Buffer.from($):BG6(32),uP0}function D91($){let Z=$.nowMs??Date.now(),X={o:$.organizationId,m:$.virtualMcpId,b:$.branch,e:Math.floor((Z+DG6)/1000)},Q=Buffer.from(JSON.stringify(X)).toString("base64url"),Y=wg$("sha256",Dg$()).update(Q).digest("base64url");return`${Q}.${Y}`}function Lg$($,Z){let X=$.indexOf(".");if(X<0)return!1;let Q=$.slice(0,X),Y=Buffer.from($.slice(X+1)),G=Buffer.from(wg$("sha256",Dg$()).update(Q).digest("base64url"));if(Y.length!==G.length||!wG6(Y,G))return!1;let J;try{J=JSON.parse(Buffer.from(Q,"base64url").toString())}catch{return!1}let W=Math.floor((Z.nowMs??Date.now())/1000);return J.o===Z.organizationId&&J.m===Z.virtualMcpId&&J.b===Z.branch&&typeof J.e==="number"&&J.e>=W}var DG6=21600000,uP0=null;var Eg$=w(()=>{T$()});import{z as nh}from"zod";function EG6($){return $.length>0&&$.length<=255&&!$.includes("..")&&!$.endsWith("/")&&!$.endsWith(".lock")&&LG6.test($)}function zg$($){return $.req.header("x-forwarded-host")??new URL($.req.url).host}async function cP0($){let Z=$.get("decofileScope");return RP0($.var.studioContext,Z.organizationId,Z.githubRepo)}function lP0($,Z){if(Z instanceof Q6){let Q=Z.status===404?404:Z.status===409?409:Z.status===422?409:502;return $.json({error:Z.message},Q)}let X=Z instanceof Error?Z.message:String(Z);return $.json({error:X},500)}function Pg$(){let $=new F1;return $.use("/:virtualMcpId/:branch",jg$),$.use("/:virtualMcpId/:branch/*",jg$),$.get("/:virtualMcpId/:branch",async(Z)=>{let X=Z.get("decofileScope");try{let Q=await cP0(Z),Y=await Zg$(Q,X.branch,X.packagePath,{createBranchIfMissing:!!X.userId}),G={ETag:`"${Y.sha}"`,"Cache-Control":"no-store","Access-Control-Allow-Origin":"*"};if(Z.req.header("if-none-match")===`"${Y.sha}"`)return Z.body(null,304,G);if(!X.userId)return Z.body(Y.decofile,200,{...G,"content-type":"application/json"});let J=D91({organizationId:X.organizationId,virtualMcpId:X.virtualMcpId,branch:X.branch});return Z.body(`{"version":${JSON.stringify(Y.sha)},"token":${JSON.stringify(J)},"apiHost":${JSON.stringify(zg$(Z))},"decofile":${Y.decofile}}`,200,{...G,"content-type":"application/json"})}catch(Q){return lP0(Z,Q)}}),$.patch("/:virtualMcpId/:branch",async(Z)=>{let X=Z.get("decofileScope"),Q=Z.var.studioContext,Y=jG6.safeParse(await Z.req.json().catch(()=>null));if(!Y.success)return Z.json({error:"Invalid body",details:Y.error.issues},400);let G=Y.data;for(let J of[...Object.keys(G.set??{}),...G.delete??[]])try{IP0(J)}catch(W){let K=W instanceof Error?W.message:String(W);return Z.json({error:K},400)}for(let[J,W]of Object.entries(G.set??{}))if(typeof W!=="object"||W===null||Array.isArray(W))return Z.json({error:`Block "${J}" must be a JSON object`},400);try{let J=await cP0(Z),W=await Og$(`${X.organizationId}/${X.virtualMcpId}/${X.branch}`,{client:J,branch:X.branch,packagePath:X.packagePath,coAuthor:ch(Q)},G),K=D91({organizationId:X.organizationId,virtualMcpId:X.virtualMcpId,branch:X.branch});return Z.json({version:W,token:K,apiHost:zg$(Z)})}catch(J){return lP0(Z,J)}}),$.post("/:virtualMcpId/:branch/publish",async(Z)=>{let X=Z.get("decofileScope");try{let Q=await cP0(Z),Y=await Q.getDefaultBranch();if(Y===X.branch)return Z.json({error:"Branch is already the default branch"},400);let G=`chore(decofile): publish ${X.branch}`;try{let J;try{J=await Q.mergeBranch(Y,X.branch,G)}catch(W){if(!(W instanceof Q6&&W.status===409))throw W;await yP0(Q,X.branch,Y),J=await Q.mergeBranch(Y,X.branch,G)}return J?Z.json({result:"merged",sha:J}):Z.json({result:"up-to-date"})}catch(J){if(J instanceof Q6&&J.status===409)return Z.json({error:"merge-conflict"},409);if(J instanceof Q6&&J.status===405){let K=await Q.findOpenPullRequest(Y,X.branch)??await Q.createPullRequest({base:Y,head:X.branch,title:`Publish ${X.branch}`});return Z.json({result:"pull-request",number:K.number,url:K.html_url})}throw J}}catch(Q){return lP0(Z,Q)}}),$.get("/:virtualMcpId/:branch/status",async(Z)=>{let X=Z.get("decofileScope");try{let Q=await cP0(Z),Y=await Q.getDefaultBranch();if(Y===X.branch)return Z.json({baseBranch:Y,aheadBy:0,behindBy:0});try{let{aheadBy:G,behindBy:J}=await Q.compare(Y,X.branch);return Z.json({baseBranch:Y,aheadBy:G,behindBy:J})}catch(G){if(G instanceof Q6&&G.status===404)return Z.json({baseBranch:Y,aheadBy:0,behindBy:0});throw G}}catch(Q){return lP0(Z,Q)}}),$}var LG6,jG6,jg$;var Ag$=w(()=>{qP0();w8();p51();TP0();O91();X91();Bg$();Eg$();N91();q_();fP0();LG6=/^[a-zA-Z0-9][a-zA-Z0-9/._-]*$/;jG6=nh.object({set:nh.record(nh.string(),nh.unknown()).optional(),delete:nh.array(nh.string()).optional()}).refine(($)=>Object.keys($.set??{}).length>0||($.delete?.length??0)>0,{message:"Patch must set or delete at least one block"}),jg$=AP0(async($,Z)=>{let X=$.var.studioContext,Q=X.organization;if(!Q)return $.json({error:"Organization scope required"},500);let Y=$.req.param("virtualMcpId"),G=$.req.param("branch");if(!Y||!G)return $.json({error:"virtualMcpId and branch are required"},400);if(!EG6(G))return $.json({error:`Invalid branch name: ${G}`},400);let J=X.auth?.user?.id??null;if(!J){let O=$.req.query("token");if(!($.req.method==="GET"&&!$.req.path.match(/\/(publish|status)$/)))return $.json({error:"Unauthorized"},401);if(!O||!Lg$(O,{organizationId:Q.id,virtualMcpId:Y,branch:G}))return $.json({error:"Unauthorized"},401)}let W=await X.storage.virtualMcps.findById(Y);if(!W||W.organization_id!==Q.id)return $.json({error:"Virtual MCP not found"},404);let K=W.metadata??null;if(!VB0(K)||K?.fastPreview!==!0)return $.json({error:"Fast Preview is not enabled for this project"},404);let F=W.connections?.map((O)=>O.connection_id)??[],N=Za(K,F);if(!N)return $.json({error:"Project has no GitHub repository"},404);let U=K?.runtime;return $.set("decofileScope",{organizationId:Q.id,virtualMcpId:Y,branch:G,packagePath:U?.path?.replace(/^\/+|\/+$/g,"")||null,githubRepo:N,userId:J}),Z()})});var Tg$=($)=>{let Z=new F1;if(Z.use("*",D_),Z.route("/",hz0()),Z.route("/",iv$()),Z.route("/",tx$()),Z.route("/",ix$()),Z.route("/",jP0()),Z.route("/tools",Zy$()),Z.route("/",sx$()),Z.route("/",Mx$({kvStorage:$.kvStorage})),Z.route("/",Ix$()),Z.route("/fs",gx$({getConnection:$.getNatsConnection})),Z.route("/sandbox",Ng$()),Z.route("/decofile",Pg$()),Z.route("/",lx$()),Z.route("/deco-sites",cz0()),Z.route("/sso",vz0()),Z.route("/",zP0({tokenStorage:$.tokenStorage,automationEventDispatcher:$.automationEventDispatcher})),Z.route("/webhooks",yv$()),$.mountDevAssets)Z.route("/dev-assets",lz0({orgFromPath:!0}));return Z.use("/mcp/:connectionId?",$.mcpAuth),Z.use("/mcp/:connectionId/ui-resource",$.mcpAuth),Z.use("/mcp/gateway/:virtualMcpId?",$.mcpAuth),Z.use("/mcp/virtual-mcp/:virtualMcpId?",$.mcpAuth),Z.use("/mcp/self",$.mcpAuth),Z.use("/mcp/task-run/:threadId",$.mcpAuth),Z.route("/",jC$()),Z.get("/mcp/:gateway?/:connectionId/.well-known/oauth-protected-resource/*",$.betterAuthProtectedResourceHandler),Z.get("/mcp/.well-known/oauth-protected-resource",$.betterAuthProtectedResourceHandler),Z.route("/mcp/task-run",ux$()),Z.route("/mcp",nw0()),Z.route("/mcp/self",EP0()),Z.route("/mcp",rw0()),Z.all("/oauth-proxy/:connectionId/*",$.oauthProxyHandler),Z.get("/watch",$.watchHandler),Z};var Rg$=w(()=>{w8();B61();gv$();E61();dz0();Ar();U61();qx$();kx$();hx$();_n();Y61();aw0();h51();cx$();dx$();px$();ox$();ex$();c51();Xy$();l51();tw0();Ug$();Ag$()});function zG6($){return $.filter((Z)=>Z.vendors?.alias).map((Z)=>({name:Z.name,title:Z.title,description:Z.description,logo:Z.logo,category:Z.category,vendor:{alias:Z.vendors.alias,url:Z.vendors.url}}))}var PG6=async($,Z)=>{if(!$.get("studioContext").auth.user?.id)return $.json({error:"Unauthorized"},401);return Z()},Ig$=()=>{let $=new F1;return $.use("*",PG6),$.get("/",async(Z)=>{let X=b0(),Q=X.decoSupabaseUrl,Y=X.decoSupabaseServiceKey;if(!Q||!Y)return Z.json({apps:[]});try{let G=await lZ(Q,Y,"apps?select=name,title,description,logo,category,vendors(alias,url)");return Z.json({apps:zG6(G)})}catch(G){return console.error("[deco-apps] GET error:",G),Z.json({error:"Failed to fetch apps"},502)}}),$};var qg$=w(()=>{w8();T$();cj0()});import{z as M1}from"zod";function QH($,Z="invalid_request_error",X=null,Q=null){return{error:{message:$,type:Z,param:X,code:Q}}}function CG6($){if(!$)return null;let Z=$.indexOf(":");if(Z===-1)return{credentialId:null,modelId:$};let X=$.substring(0,Z),Q=$.substring(Z+1);if(!X||!Q)return null;return{credentialId:X,modelId:Q}}function _G6($,Z,X){try{return JSON.parse($)}catch{throw new Vg$(`Invalid JSON in tool call arguments for function '${X}' (tool_call_id: ${Z}): ${$}`)}}function vG6($){let Z={};for(let X of $)if(X.role==="assistant"&&X.tool_calls)for(let Q of X.tool_calls)Z[Q.id]=Q.function.name;return $.map((X)=>{switch(X.role){case"system":return{role:"system",content:X.content};case"user":if(typeof X.content==="string")return{role:"user",content:X.content};return{role:"user",content:X.content.map((Y)=>{if(Y.type==="text")return{type:"text",text:Y.text};return{type:"image",image:Y.image_url.url}})};case"assistant":if(X.tool_calls&&X.tool_calls.length>0)return{role:"assistant",content:X.tool_calls.map((Y)=>({type:"tool-call",toolCallId:Y.id,toolName:Y.function.name,input:_G6(Y.function.arguments,Y.id,Y.function.name)}))};return{role:"assistant",content:X.content??""};case"tool":let Q=Z[X.tool_call_id]??"unknown";return{role:"tool",content:[{type:"tool-result",toolCallId:X.tool_call_id,toolName:Q,output:{type:"text",value:X.content}}]}}})}function fG6($){let Z=$.map((X)=>{let Q=X.function.parameters?xY(X.function.parameters):xY({type:"object",properties:{}});return[X.function.name,b$({description:X.function.description,inputSchema:Q})]});return Object.fromEntries(Z)}function bG6($){if(!$)return;return{openai:{response_format:$}}}function xG6(){return`chatcmpl-${crypto.randomUUID().replace(/-/g,"").substring(0,29)}`}function Mg$($,Z,X,Q,Y,G){let J={model:$,messages:Z,tools:X,temperature:Q.temperature,maxTokens:Q.max_tokens,topP:Q.top_p,frequencyPenalty:Q.frequency_penalty,presencePenalty:Q.presence_penalty,stopSequences:Q.stop?Array.isArray(Q.stop)?Q.stop:[Q.stop]:void 0,abortSignal:G};return Y?{...J,providerOptions:Y}:J}function kg$($){if($==="tool-calls")return"tool_calls";if($==="length")return"length";return"stop"}var AG6=256,TG6,RG6,IG6,qG6,MG6,kG6,VG6,SG6,Vg$,Sg$,Cg$;var _g$=w(()=>{_4();w8();uh();XN();TG6=M1.object({type:M1.literal("function"),function:M1.object({name:M1.string(),description:M1.string().optional(),parameters:M1.record(M1.string(),M1.unknown()).optional()})}),RG6=M1.object({id:M1.string(),type:M1.literal("function"),function:M1.object({name:M1.string(),arguments:M1.string()})}),IG6=M1.discriminatedUnion("role",[M1.object({role:M1.literal("system"),content:M1.string(),name:M1.string().optional()}),M1.object({role:M1.literal("user"),content:M1.union([M1.string(),M1.array(M1.union([M1.object({type:M1.literal("text"),text:M1.string()}),M1.object({type:M1.literal("image_url"),image_url:M1.object({url:M1.string(),detail:M1.string().optional()})})]))]),name:M1.string().optional()}),M1.object({role:M1.literal("assistant"),content:M1.string().nullable().optional(),name:M1.string().optional(),tool_calls:M1.array(RG6).optional()}),M1.object({role:M1.literal("tool"),content:M1.string(),tool_call_id:M1.string()})]),qG6=M1.object({type:M1.literal("text")}),MG6=M1.object({type:M1.literal("json_object")}),kG6=M1.object({type:M1.literal("json_schema"),json_schema:M1.object({name:M1.string(),description:M1.string().optional(),schema:M1.record(M1.string(),M1.unknown()),strict:M1.boolean().optional()})}),VG6=M1.union([qG6,MG6,kG6]),SG6=M1.object({model:M1.string().describe("Format: 'model_id' or 'credential_id:model_id'"),messages:M1.array(IG6),stream:M1.boolean().optional().default(!1),temperature:M1.number().min(0).max(2).optional(),max_tokens:M1.number().positive().optional(),top_p:M1.number().min(0).max(1).optional(),frequency_penalty:M1.number().min(-2).max(2).optional(),presence_penalty:M1.number().min(-2).max(2).optional(),stop:M1.union([M1.string(),M1.array(M1.string())]).optional(),tools:M1.array(TG6).optional(),tool_choice:M1.union([M1.literal("auto"),M1.literal("none"),M1.literal("required"),M1.object({type:M1.literal("function"),function:M1.object({name:M1.string()})})]).optional(),response_format:VG6.optional(),user:M1.string().optional()});Vg$=class Vg$ extends Error{constructor($){super($);this.name="MessageConversionError"}};Sg$=new F1;Sg$.post("/:org/v1/chat/completions",async($)=>{let Z=$.get("studioContext"),X=$.req.param("org");try{if(!Z.auth.apiKey?.id)return $.json(QH("API key authentication required. Provide a valid API key via Authorization header.","authentication_error"),401);if(!Z.organization)return $.json(QH("Organization context is required. Ensure your API key has organization metadata.","invalid_request_error","organization"),400);if((Z.organization.slug??Z.organization.id)!==X)return $.json(QH("Organization mismatch. The API key's organization does not match the requested organization.","invalid_request_error","organization"),403);let Q=await $.req.json(),Y=SG6.safeParse(Q);if(!Y.success){let L=Y.error.issues[0]??{message:"Invalid request",path:[]};return $.json(QH(`Invalid request: ${L.message}`,"invalid_request_error",L.path.length>0?L.path.join("."):null),400)}let G=Y.data,J=CG6(G.model);if(!J)return $.json(QH("Invalid model format. Expected 'model_id' or 'credential_id:model_id' (e.g., 'claude-sonnet-4-6' or 'key_abc123:claude-sonnet-4-6')","invalid_request_error","model"),400);let{credentialId:W}=J,{modelId:K}=J;if(!W){let E=(await Z.storage.aiProviderKeys.list({organizationId:Z.organization.id})).find((j)=>VD(j.providerId));if(!E)return $.json(QH("No AI provider credentials configured for this organization. Add a credential in settings or specify one explicitly via 'credential_id:model_id'.","invalid_request_error","model"),400);W=E.id}let H;try{H=await Z.aiProviders.activate(W,Z.organization.id)}catch{return $.json(QH(`AI provider credential not found or inaccessible: ${W}`,"invalid_request_error","model"),404)}let F=H.aiSdk.languageModel(K),N=vG6(G.messages),U=G.tools?fG6(G.tools):void 0,O=bG6(G.response_format),B=xG6(),D=Math.floor(Date.now()/1000);if(G.stream)return TN($,async(L)=>{let E=Mg$(F,N,U,G,O,$.req.raw.signal);try{let j=iO(E),z=!1,A=0,P="",M=async()=>{if(P.length===0)return;let q=P;P="",await L.writeSSE({data:JSON.stringify({id:B,object:"chat.completion.chunk",created:D,model:G.model,choices:[{index:0,delta:{content:q},finish_reason:null}]})})};for await(let q of j.fullStream){if(!z&&(q.type==="text-delta"||q.type==="tool-call"))await L.writeSSE({data:JSON.stringify({id:B,object:"chat.completion.chunk",created:D,model:G.model,choices:[{index:0,delta:{role:"assistant",content:""},finish_reason:null}]})}),z=!0;if(q.type==="text-delta"){if(P+=q.text,P.length>=AG6)await M()}else if(q.type==="tool-call"){await M();let k=A++;await L.writeSSE({data:JSON.stringify({id:B,object:"chat.completion.chunk",created:D,model:G.model,choices:[{index:0,delta:{tool_calls:[{index:k,id:q.toolCallId,type:"function",function:{name:q.toolName,arguments:JSON.stringify(q.input)}}]},finish_reason:null}]})})}else if(q.type==="finish")await M(),await L.writeSSE({data:JSON.stringify({id:B,object:"chat.completion.chunk",created:D,model:G.model,choices:[{index:0,delta:{},finish_reason:kg$(q.finishReason)}],usage:q.totalUsage?{prompt_tokens:q.totalUsage.inputTokens??0,completion_tokens:q.totalUsage.outputTokens??0,total_tokens:q.totalUsage.totalTokens??0}:void 0})})}await M(),await L.writeSSE({data:"[DONE]"})}catch(j){let z=j;console.error("[openai-compat:stream] Error:",z.message),await L.writeSSE({data:JSON.stringify({error:{message:z.message,type:"server_error"}})})}});else{let L=Mg$(F,N,U,G,O,$.req.raw.signal),E=await dO(L),j={role:"assistant",content:E.text||null};if(E.toolCalls&&E.toolCalls.length>0)j.tool_calls=E.toolCalls.map((z)=>({id:z.toolCallId,type:"function",function:{name:z.toolName,arguments:JSON.stringify("input"in z?z.input:{})}})),j.content=null;return $.json({id:B,object:"chat.completion",created:D,model:G.model,choices:[{index:0,message:j,finish_reason:kg$(E.finishReason)}],usage:{prompt_tokens:E.usage?.inputTokens??0,completion_tokens:E.usage?.outputTokens??0,total_tokens:E.usage?.totalTokens??0}})}}catch(Q){let Y=Q;if(Y.name==="AbortError")return $.json(QH("Request aborted","invalid_request_error"),400);if(Y.name==="MessageConversionError")return $.json(QH(Y.message,"invalid_request_error","messages"),400);return console.error("[openai-compat] Error:",Y.message,Y.stack),$.json(QH(Y.message,"server_error"),500)}});Cg$=Sg$});function vg$(){let $=new F1;return $.use("*",async(Z,X)=>{await X(),Z.header("Cache-Control","private, no-store"),Z.header("Vary","Cookie")}),$.get("/",async(Z)=>{let X=Z.get("studioContext"),Q=G1(X);if(!Q)return Z.json({error:"Authentication required"},401);let G=(Z.req.query("site")??"").trim().toLowerCase();if(!oK(G))return Z.json({error:"Invalid site slug"},400);let J=await X.db.selectFrom("member").innerJoin("organization","organization.id","member.organizationId").select(["organization.id as id","organization.slug as slug","organization.name as name","organization.metadata as metadata"]).where("member.userId","=",Q).execute(),W=[];for(let H of J){if(!H.slug||J7(H))continue;let F=await X.storage.virtualMcps.list(H.id);for(let N of F){if(N.title.toLowerCase()!==G)continue;W.push({orgSlug:H.slug,orgName:H.name??H.slug,project:{id:N.id,title:N.title,icon:N.icon??null}})}}let K={matches:W};return Z.json(K)}),$}var fg$=w(()=>{w8();W_()});var xg$;var bg$=w(()=>{xg$={name:"decocms",version:"4.242.10",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","@nats-io/jwt":"0.0.10-5","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.211.0","@opentelemetry/exporter-logs-otlp-proto":"^0.211.0","@opentelemetry/exporter-prometheus":"^0.208.0","@opentelemetry/exporter-trace-otlp-proto":"^0.207.0","@opentelemetry/instrumentation-runtime-node":"^0.24.0","@opentelemetry/resources":"^2.6.0","@opentelemetry/sdk-logs":"^0.211.0","@opentelemetry/sdk-metrics":"^2.2.0","@opentelemetry/sdk-node":"^0.207.0","@opentelemetry/sdk-trace-base":"^2.5.0","@types/bun":"^1.3.1","@types/google.maps":"^3.65.2","@types/pg":"^8.15.6","@types/react-syntax-highlighter":"^15.5.13","@vercel/nft":"^1.1.1",ai:"^6.0.208","better-auth":"1.4.22",croner:"^9.1.0",degit:"^2.8.4",hono:"^4.10.7",jose:"^6.0.11",nanoid:"^5.1.6",pg:"^8.16.3",typescript:"^7.0.2",typescript5:"npm:typescript@^5.9.3",zod:"4.3.6"},homepage:"https://github.com/decocms/studio",keywords:["mcp","model-context-protocol","ai","gateway","self-hosted","tools"],license:"MIT",publishConfig:{access:"public"}}});function hG6(){let $=process.env.POSTHOG_KEY;if(!$)return null;return{key:$,host:process.env.POSTHOG_HOST??gG6}}var yg$,gG6="https://ph.studio.decocms.com",gg$;var hg$=w(()=>{w8();Jh0();QC();v9();T$();e41();bg$();yg$=new F1;yg$.get("/",($)=>{let Z={version:xg$.version,theme:Ud1(),...jL().logo&&{logo:jL().logo},...TK()&&{internalUrl:lV1()},...b0().enableDecoImport&&{enableDecoImport:!0},brandExtractEnabled:!!b0().firecrawlApiKey,auth:Xv$(),posthog:hG6(),googleMapsApiKey:process.env.GOOGLE_MAPS_API_KEY?.trim()||null,runtime:{agentSandbox:!TK()&&b0().sandboxProviderKind==="agent-sandbox"}};return $.header("Cache-Control","no-store"),$.json({success:!0,config:Z})});gg$=yg$});function th($){let Z=($??"").trim().toLowerCase();return Z=Z.replace(/^https?:\/\//,""),Z=Z.replace(/^www\./,""),Z=Z.split(/[/?#]/)[0]??"",Z.replace(/\/+$/,"")}function L91($){return(th($).split(".")[0]||$).replace(/[-_]/g," ").split(" ").filter(Boolean).map((X)=>X.charAt(0).toUpperCase()+X.slice(1)).join(" ")}function cg$($,Z=64){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(th($))}&sz=${Z}`}function ug$($,Z){let X=$.trim();if(X.length<=Z)return X;let Q=X.slice(0,Z-1),Y=Q.lastIndexOf(" ");return`${(Y>Z*0.6?Q.slice(0,Y):Q).trimEnd()}\u2026`}function lg$($){let{brand:Z,domain:X,score:Q,verdict:Y}=$,G=typeof Q==="number"?`${Z} commerce report \u2014 ${Math.round(Q)}/100 \xB7 decocms`:`${Z} commerce report \xB7 decocms`,J=`See the full ${Z} scorecard \u2014 SEO, performance, conversion & AEO signals scored by decocms.`,W=Y?.trim()?ug$(`${Y.trim().replace(/\s+/g," ")} \u2014 ${J}`,200):ug$(`How does ${X} really perform? ${J}`,200);return{title:G,description:W}}import{z as l0}from"zod";var C_,uG6,cG6,lG6,dG6,dg$;var mg$=w(()=>{C_=l0.enum(["good","bad","neutral"]),uG6=l0.preprocess(($)=>{if(Array.isArray($))return{kind:"text",value:$.find((X)=>X!==null&&typeof X!=="object")??""};return $!==null&&typeof $==="object"?$:{kind:"text",value:$}},l0.object({kind:l0.enum(["text","number","sparkline","badge","score"]).catch("text"),value:l0.coerce.string().optional(),tone:C_.optional(),muted:l0.boolean().optional(),delta:l0.coerce.string().optional(),deltaDir:l0.enum(["up","down","neutral"]).optional(),points:l0.array(l0.coerce.number()).optional(),label:l0.coerce.string().optional()}).transform(($)=>{if($.kind==="badge"&&$.label==null)$.label=$.value??"";if($.kind==="score"){let Z=Number($.value);if(Number.isNaN(Z))return{...$,kind:"text"}}return $})),cG6=l0.preprocess(($)=>{let Z=$;if(Z&&typeof Z==="object"&&!Array.isArray(Z)&&Array.isArray(Z.cells))Z=Z.cells;if(Array.isArray(Z)&&Z.length===1&&Array.isArray(Z[0]))Z=Z[0];if(Array.isArray(Z))return Z;if(Z&&typeof Z==="object")return Object.values(Z);return Z},l0.array(uG6)),lG6={key:l0.coerce.string(),title:l0.coerce.string(),eyebrow:l0.coerce.string().optional(),headline:l0.coerce.string(),annotation:l0.coerce.string().optional(),methodology:l0.coerce.string().optional(),sources:l0.array(l0.object({name:l0.coerce.string(),logoUrl:l0.coerce.string()})).optional()},dG6=l0.discriminatedUnion("template",[l0.object({template:l0.literal("cover"),score:l0.object({value:l0.coerce.number(),max:l0.coerce.number().optional(),grade:l0.coerce.string().optional(),label:l0.coerce.string().optional()}).optional(),brandImage:l0.coerce.string().optional(),screenshot:l0.coerce.string().optional(),mobileScreenshot:l0.coerce.string().optional()}),l0.object({template:l0.literal("cta"),ctaUrl:l0.coerce.string().optional(),ctaLabel:l0.coerce.string().optional(),bullets:l0.array(l0.coerce.string()).optional()}),l0.object({template:l0.literal("series"),points:l0.array(l0.coerce.number()).min(2),xLabels:l0.array(l0.coerce.string()).min(1),unit:l0.coerce.string().optional(),callout:l0.object({index:l0.coerce.number(),value:l0.coerce.string(),tone:C_.optional()})}),l0.object({template:l0.literal("threshold"),value:l0.coerce.string().default(""),metricLabel:l0.coerce.string().optional(),ratio:l0.coerce.number(),thresholdRatio:l0.coerce.number().optional(),thresholdLabel:l0.coerce.string().default(""),tone:C_.optional()}),l0.object({template:l0.literal("stats"),stats:l0.array(l0.object({value:l0.coerce.string(),label:l0.coerce.string(),tone:C_.optional()})).min(1)}),l0.object({template:l0.literal("bars"),items:l0.array(l0.object({value:l0.coerce.string(),label:l0.coerce.string(),ratio:l0.coerce.number(),tone:C_.optional()})).min(1)}),l0.object({template:l0.literal("gauges"),gauges:l0.array(l0.object({label:l0.coerce.string(),value:l0.coerce.string(),status:l0.enum(["good","warn","bad"]).catch("warn"),caption:l0.coerce.string().optional(),ratio:l0.coerce.number().optional()})).min(1)}),l0.object({template:l0.literal("checklist"),checks:l0.array(l0.object({label:l0.coerce.string(),status:l0.enum(["pass","fail","warn"]).catch("fail"),value:l0.coerce.string().optional()})).min(1)}),l0.object({template:l0.literal("table"),columns:l0.array(l0.object({label:l0.coerce.string(),align:l0.enum(["left","right"]).optional()})).min(1),rows:l0.array(cG6).min(1),highlightRow:l0.coerce.number().optional()}),l0.object({template:l0.literal("products"),products:l0.array(l0.object({name:l0.coerce.string(),price:l0.coerce.string().optional(),image:l0.coerce.string().optional(),url:l0.coerce.string().optional()})).min(1)}),l0.object({template:l0.literal("list"),entries:l0.array(l0.object({label:l0.coerce.string(),severity:l0.enum(["error","warning","notice"]).catch("notice")})).min(1),moreCount:l0.coerce.number().optional()}),l0.object({template:l0.literal("keywords"),volumeLabel:l0.coerce.string().optional(),keywords:l0.array(l0.object({term:l0.coerce.string(),volume:l0.coerce.string(),position:l0.coerce.number().catch(0)})).min(1)}),l0.object({template:l0.literal("competitor"),metricLabel:l0.coerce.string().optional(),competitors:l0.array(l0.object({name:l0.coerce.string(),value:l0.coerce.string(),tone:C_.optional(),isYou:l0.boolean().optional()})).min(1)}),l0.object({template:l0.literal("scorecard"),rivalLabel:l0.coerce.string().optional(),dimensions:l0.array(l0.object({label:l0.coerce.string(),you:l0.coerce.string(),rival:l0.coerce.string().optional(),rivalName:l0.coerce.string().optional(),tone:C_.optional()})).min(1)})]),dg$=l0.object({...lG6,template:dG6})});function dP0($){let Z=[],X=[...$.sections].sort((Y,G)=>Y.position-G.position).map((Y)=>{let G=dg$.safeParse(Y.props);if(G.success)return G.data;let J=G.error.issues[0];return Z.push({section_type:Y.section_type,position:Y.position,reason:J?`${J.path.join(".")||"(root)"}: ${J.message}`:"contract violation"}),null}).filter((Y)=>Y!==null),Q=X.filter((Y)=>Y.template.template!=="cover"&&Y.template.template!=="cta").map((Y)=>({key:Y.key,title:Y.title}));return{deck:{meta:{...$.meta,scores:$.summary?.scores,scannedAt:$.scanned_at,toc:Q},slides:X},drops:Z}}var E91=w(()=>{mg$()});import{join as ig$}from"path";async function iG6($){try{let Z=await fetch(`${oW({})}/api/v2/public/diagnostics/${encodeURIComponent($)}`,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(mG6)});if(!Z.ok)return null;let X=await Z.json(),{deck:Q}=dP0(X);if(!Q.slides.length)return null;let Y=Q.slides.find((W)=>W.template.template==="cover"),G=Y?.template,J=G&&G.template==="cover"?G:void 0;return{brand:Q.meta.brand?.trim()||L91($),score:Q.meta.scores?.cover??J?.score?.value,verdict:Y?.annotation?.trim()||Y?.headline?.trim()||void 0}}catch{return null}}function YG($){return $.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;")}function pG6($,Z){let X=th($),Q=Z?.brand?.trim()||L91(X),Y=cg$(X,128),J=`${(b0().baseUrl??"https://studio.decocms.com").replace(/\/+$/,"")}/report/${encodeURIComponent(X)}`,{title:W,description:K}=lg$({brand:Q,domain:X,score:Z?.score,verdict:Z?.verdict}),H=`${J}/og.png`,F=`${Q} commerce report by decocms`;return[`<title>${YG(W)}</title>`,`<meta name="description" content="${YG(K)}" />`,'<meta name="robots" content="noindex, follow" />','<meta property="og:type" content="website" />','<meta property="og:site_name" content="decocms" />',`<meta property="og:title" content="${YG(W)}" />`,`<meta property="og:description" content="${YG(K)}" />`,`<meta property="og:url" content="${YG(J)}" />`,`<meta property="og:image" content="${YG(H)}" />`,'<meta property="og:image:width" content="1200" />','<meta property="og:image:height" content="630" />',`<meta property="og:image:alt" content="${YG(F)}" />`,'<meta name="twitter:card" content="summary_large_image" />',`<meta name="twitter:title" content="${YG(W)}" />`,`<meta name="twitter:description" content="${YG(K)}" />`,`<meta name="twitter:image" content="${YG(H)}" />`,`<meta name="twitter:image:alt" content="${YG(F)}" />`,`<link rel="canonical" href="${YG(J)}" />`,`<link rel="icon" href="${YG(Y)}" sizes="any" />`].join(`
2807
2807
  `)}function nG6($,Z){return $.replace(/<title>[\s\S]*?<\/title>\s*/i,"").replace(/<meta\s+name="(?:description|twitter:[^"]*)"[^>]*>\s*/gi,"").replace(/<meta\s+property="og:[^"]*"[^>]*>\s*/gi,"").replace(/<link\s+rel="icon"[^>]*>\s*/gi,"").replace("</head>",` ${Z}
2808
2808
  </head>`)}function pg$($){let Z=new F1;return Z.get("/:domain/og.png",async(X)=>{let Q=th(X.req.param("domain")),Y=async()=>{let G=$?Bun.file(ig$($,"report-og-fallback.png")):null;if(!G||!await G.exists())return X.notFound();return X.body(new Uint8Array(await G.arrayBuffer()),200,{"Content-Type":"image/png","Cache-Control":"public, max-age=0, s-maxage=3600"})};try{let G=await fetch(`${oW({})}/api/v2/public/diagnostics/${encodeURIComponent(Q)}/og.png`,{signal:AbortSignal.timeout(tG6)}),J=G.headers.get("content-type")??"";if(!G.ok||!J.startsWith("image/")||!G.body)return Y();return X.body(G.body,200,{"Content-Type":J,"Cache-Control":"public, max-age=0, s-maxage=604800"})}catch{return Y()}}),Z.get("/:domain",async(X)=>{let Q=X.req.param("domain"),Y=$?ig$($,"index.html"):null,G=Y?Bun.file(Y):null;if(!G||!await G.exists())return X.notFound();let J=await G.text();try{let W=await iG6(th(Q)),K=pG6(Q,W);return X.html(nG6(J,K),200,{"Cache-Control":"public, max-age=0, s-maxage=300"})}catch{return X.html(J)}}),Z}var mG6=2500,tG6=1e4;var ng$=w(()=>{w8();E91();vL();T$()});function Qa($,Z){return fetch(`${oW({})}${$}`,Z)}async function oG6($,Z,X){let Q=new URLSearchParams;if(Z)Q.set("pw",Z);if(X)Q.set("lang",X);let Y=Q.toString()?`?${Q.toString()}`:"",G=await Qa(`/api/v2/public/diagnostics/${encodeURIComponent($)}${Y}`,{headers:{Accept:"application/json"}});if(G.status===404)return{status:"not_found",deck:null,scanned_at:null,drops:[]};if(!G.ok)throw Error(`report read HTTP ${G.status}`);let J=await G.json(),{deck:W,drops:K}=dP0(J);return{status:W.slides.length?"ready":"empty",deck:W,scanned_at:J.scanned_at,drops:K}}var rG6,IN,tg$=async($,Z)=>{if(!$.get("reportUser"))return $.json({error:"Authentication required"},401);await Z();return},og$;var rg$=w(()=>{w8();_Y();vL();E91();rG6=new Set(["complete","errored","terminated","unknown"]),IN=new F1;IN.use("*",async($,Z)=>{let X=await H8.api.getSession({headers:$.req.raw.headers});$.set("reportUser",X?.user?.id?{email:X.user.email}:void 0),await Z(),$.header("Cache-Control","private, no-store"),$.header("Vary","Cookie");return});IN.use("/link-token/*",tg$);IN.use("/suggest",tg$);IN.get("/site/:domain",async($)=>{let Z=$.req.param("domain").trim();if(!Z)return $.json({error:"domain is required"},400);let X=$.get("reportUser"),Q=$.req.query("key")?.trim()||void 0,Y=$.req.query("lang")?.trim()||void 0;try{let G=await oG6(Z,Q,Y);if($.header("Cache-Control","private, no-store"),X||!G.deck)return $.json(G);return $.json({...G,deck:{...G.deck,slides:G.deck.slides.slice(0,1)},truncated:G.status==="ready"})}catch{return $.json({error:"report read failed"},502)}});IN.post("/run",async($)=>{let Z=$.get("reportUser"),X;try{X=await $.req.json()}catch{return $.json({error:"invalid JSON"},400)}let Q=typeof X.domain==="string"?X.domain.trim():"";if(!Q)return $.json({error:"domain is required"},400);let Y=Z?.email,G=typeof X.distinctId==="string"&&X.distinctId.trim()&&X.distinctId.length<=200?X.distinctId.trim():void 0;try{let J=await Qa("/api/v2/diagnostics/run",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${_L({})}`},body:JSON.stringify({url:Q,...Y?{email:Y}:{},distinct_id:G})});if(!J.ok)return $.json({error:`run HTTP ${J.status}`},502);let W=await J.json(),K=W.blocked?{state:"blocked"}:W.status==="fresh"?{state:"fresh"}:W.mode==="sync"?{state:"sync"}:{state:"running",id:W.id??null};return $.json(K)}catch{return $.json({error:"run failed"},502)}});IN.get("/status",async($)=>{let Z=$.req.query("id");if(!Z)return $.json({error:"id is required"},400);try{let X=await Qa(`/api/v2/diagnostics/status?id=${encodeURIComponent(Z)}`,{headers:{Authorization:`Bearer ${_L({})}`}});if(!X.ok)return $.json({error:`status HTTP ${X.status}`},502);let Y=(await X.json()).status??"unknown",G={done:rG6.has(Y),status:Y};return $.json(G)}catch{return $.json({error:"status failed"},502)}});IN.get("/link-token/:id",async($)=>{let Z=$.req.param("id");try{let X=await Qa(`/api/v2/public/link-tokens/${encodeURIComponent(Z)}`,{headers:{Accept:"application/json"}});if(X.status===404)return $.json(null);if(!X.ok)return $.json({error:`link token HTTP ${X.status}`},502);return $.json(await X.json())}catch{return $.json({error:"link token resolve failed"},502)}});IN.get("/suggest",async($)=>{let Z=($.req.query("q")??"").trim().slice(0,64);if(Z.length<2)return $.json({suggestions:[]});try{let X=await Qa(`/api/v2/public/suggest?q=${encodeURIComponent(Z)}`,{headers:{Accept:"application/json"}});if(!X.ok)return $.json({suggestions:[]});let Q=await X.json();return $.json({suggestions:Array.isArray(Q.suggestions)?Q.suggestions:[]})}catch{return $.json({suggestions:[]})}});og$=IN});import{createHmac as aG6,timingSafeEqual as sG6}from"crypto";function sg$($,Z,X,Q=Date.now()){if(!Z||!X)return!1;let Y,G=[];for(let H of Z.split(",")){let F=H.indexOf("=");if(F<=0)continue;let N=H.slice(0,F).trim(),U=H.slice(F+1).trim();if(N==="t")Y=U;else if(N==="v1")G.push(U)}if(!Y||G.length===0)return!1;let J=Number(Y);if(!Number.isFinite(J)||Math.abs(Q/1000-J)>eG6)return!1;let W=aG6("sha256",X).update(`${Y}.${$}`).digest("hex"),K=Buffer.from(W,"hex");return G.some((H)=>{let F=Buffer.from(H,"hex");return K.length===F.length&&sG6(K,F)})}function eg$($){let Z;try{Z=JSON.parse($)}catch{return null}let X=PJ(Z),Q=PJ(PJ(X?.data)?.object);if(!X||typeof X.type!=="string"||!Q)return null;return{id:YH(X.id),type:X.type,created:typeof X.created==="number"?X.created:void 0,livemode:typeof X.livemode==="boolean"?X.livemode:void 0,data:{object:Q}}}function $h$($){switch($){case"active":case"trialing":return"active";case"past_due":return"past_due";default:return"canceled"}}function YH($){return typeof $==="string"?$:void 0}function PJ($){return typeof $==="object"&&$!==null?$:void 0}function mP0($){return typeof $==="number"?new Date($*1000):null}function P91($){return YH($)??YH(PJ($)?.id)}function $J6($){return P91($.subscription)??YH(PJ(PJ($.parent)?.subscription_details)?.subscription)}function ZJ6($){let Z=mP0($.current_period_end);if(Z)return Z;let X=PJ($.items)?.data;if(!Array.isArray(X))return null;let Q=0;for(let Y of X){let G=PJ(Y)?.current_period_end;if(typeof G==="number"&&G>Q)Q=G}return Q>0?new Date(Q*1000):null}function j91($,Z){let X=mP0($.created);return!!X&&!!Z.lastStripeEventAt&&X<Z.lastStripeEventAt}function z91($,Z){let X=mP0($.created);if(!X)return;return Z.lastStripeEventAt&&Z.lastStripeEventAt>X?void 0:X}async function XJ6($,Z){let X=Z.data.object;switch(Z.type){case"checkout.session.completed":case"checkout.session.async_payment_succeeded":{let Q=YH(PJ(X.metadata)?.orgId);if(!Q)return{handled:!1,reason:"no orgId"};if(YH(PJ(X.metadata)?.kind)==="topup"){if(X.mode!=="payment")return{handled:!1,reason:"topup with wrong mode"};if(YH(X.payment_status)!=="paid")return{handled:!1,reason:"payment not confirmed"};let J=YH(X.id);if(!J)return console.error("stripe webhook: topup session without id",{eventId:Z.id,organizationId:Q}),{handled:!1,reason:"topup session without id"};let W=Number(PJ(X.metadata)?.creditCents);if(!Number.isInteger(W)||W<=0)return console.error("stripe webhook: paid topup with bad metadata \u2014 credit NOT applied",{eventId:Z.id,organizationId:Q,creditCents:PJ(X.metadata)?.creditCents}),{handled:!1,reason:"bad topup metadata"};return{handled:!0,organizationId:Q,topUp:{creditCents:W,referenceId:`stripe-topup:${J}`}}}if(X.mode!=="subscription")return{handled:!1,reason:"not a subscription checkout"};if(YH(X.payment_status)!=="paid")return{handled:!1,reason:"payment not confirmed"};let Y=await $.getBilling(Q);if(!Y)return{handled:!1,reason:"unknown org"};let G=P91(X.subscription);if(Y.stripeSubscriptionId&&G&&Y.stripeSubscriptionId!==G)return console.error("stripe webhook: refused checkout rebind",{organizationId:Q,eventId:Z.id}),{handled:!1,reason:"org already bound to another subscription",orphanSubscriptionId:G};if(j91(Z,Y))return{handled:!1,reason:"stale event"};return await $.updateStripeState(Q,{stripeCustomerId:P91(X.customer),stripeSubscriptionId:G,status:"active",lastStripeEventAt:z91(Z,Y)}),{handled:!0,organizationId:Q}}case"customer.subscription.updated":case"customer.subscription.deleted":{let Q=YH(X.id);if(!Q)return{handled:!1,reason:"no sub id"};let Y=await $.getBillingByStripeSubscriptionId(Q);if(!Y)return{handled:!1,reason:"unknown subscription"};let G=Z.type==="customer.subscription.deleted";if(!G&&j91(Z,Y))return{handled:!1,reason:"stale event"};let J=G?"canceled":$h$(X.status);return await $.updateStripeState(Y.organizationId,{status:J,currentPeriodEnd:ZJ6(X),...G&&{stripeSubscriptionId:null},lastStripeEventAt:z91(Z,Y)}),{handled:!0,organizationId:Y.organizationId}}case"invoice.paid":{let Q=$J6(X);if(!Q)return{handled:!1,reason:"no sub id"};let Y=await $.getBillingByStripeSubscriptionId(Q);if(!Y)return{handled:!1,reason:"unknown subscription"};if(j91(Z,Y))return{handled:!1,reason:"stale event"};return await $.updateStripeState(Y.organizationId,{status:"active",currentPeriodEnd:mP0(X.period_end),lastStripeEventAt:z91(Z,Y)}),{handled:!0,organizationId:Y.organizationId}}default:return{handled:!1,reason:`unhandled event ${Z.type}`}}}function QJ6($,Z){if(!Z.handled||$.livemode===!1)return null;let X=$.data.object;if(Z.topUp)return{name:"credits_topup_succeeded",organizationId:Z.organizationId,properties:{credit_cents:Z.topUp.creditCents}};switch($.type){case"checkout.session.completed":case"checkout.session.async_payment_succeeded":return{name:"subscription_started",organizationId:Z.organizationId,properties:{}};case"customer.subscription.deleted":return{name:"subscription_canceled",organizationId:Z.organizationId,properties:{}};case"customer.subscription.updated":return{name:"subscription_updated",organizationId:Z.organizationId,properties:{status:$h$(X.status),...typeof X.cancel_at_period_end==="boolean"?{cancel_at_period_end:X.cancel_at_period_end}:{}}};case"invoice.paid":if(X.billing_reason==="subscription_create")return null;return{name:"subscription_renewed",organizationId:Z.organizationId,properties:{}};default:return null}}function ag$($,Z){let X=QJ6($,Z);if(!X)return;qY({event:X.name,organizationId:X.organizationId,...$.id?{uuid:zi1(`stripe:${$.id}:${X.name}`)}:{},...$.created?{timestamp:new Date($.created*1000)}:{},properties:X.properties})}async function Zh$($){let Z=new iW(p8().db),X=await XJ6(Z,$);if(!(X.handled&&X.topUp))ag$($,X);if(X.handled&&X.topUp)await sB$({organizationId:X.organizationId,amountCents:X.topUp.creditCents,referenceId:X.topUp.referenceId}),ag$($,X);if(!X.handled&&X.orphanSubscriptionId)try{await va1(X.orphanSubscriptionId),console.error("stripe webhook: canceled orphan subscription",{subscriptionId:X.orphanSubscriptionId,eventId:$.id})}catch(Q){if(!(Q instanceof vY&&(Q.status===400||Q.status===404)))throw Q}return X}var eG6=300;var Xh$=w(()=>{_G();M4();G60();lL();xs0()});var YJ6=1048576,A91;var Qh$=w(()=>{w8();BN();T$();Xh$();A91=new F1;A91.post("/webhook",M9({maxSize:YJ6,onError:($)=>$.json({error:"payload too large"},413)}),async($)=>{let Z=b0().stripeWebhookSecret;if(!Z)return $.json({error:"stripe billing not configured"},503);let X=await $.req.text();if(!sg$(X,$.req.header("stripe-signature"),Z))return $.json({error:"invalid signature"},400);let Y=eg$(X);if(!Y)return $.json({error:"invalid payload"},400);let G=await Zh$(Y);return console.log("stripe webhook",{eventId:Y.id,type:Y.type,livemode:Y.livemode,...G}),$.json({received:!0})})});import{timingSafeEqual as GJ6}from"crypto";function WJ6($,Z,X){if(!Z?.startsWith("sha256="))return!1;let Q=new Bun.CryptoHasher("sha256",X).update($).digest("hex"),Y=Z.slice(7);if(Y.length!==Q.length)return!1;return GJ6(Buffer.from(Y),Buffer.from(Q))}var JJ6=5242880,T91;var Yh$=w(()=>{w8();BN();Cp();T91=new F1;T91.post("/webhook",M9({maxSize:JJ6,onError:($)=>$.json({error:"payload too large"},413)}),async($)=>{let Z=process.env.GITHUB_WEBHOOK_SECRET;if(!Z)return $.json({error:"github webhook not configured"},503);let X=await $.req.text();if(!WJ6(X,$.req.header("x-hub-signature-256"),Z))return $.json({error:"invalid signature"},400);if($.req.header("x-github-event")!=="push")return $.json({ok:!0,ignored:"event"});let Q;try{Q=JSON.parse(X)}catch{return $.json({error:"invalid payload"},400)}let Y=Q.ref,G=Q.repository?.full_name;if(!Y||!G)return $.json({ok:!0,ignored:"shape"});let W=(await ai0())?.markTenantPoolsDirty(G,Y)??[];return $.json({ok:!0,pools:W})})});function Gh$($,Z){if(Z.startsWith("text/html")||Z.startsWith("image/svg"))$.set("Content-Security-Policy","sandbox allow-scripts allow-modals allow-same-origin")}var Jh$,KJ6,HJ6,Wh$;var Kh$=w(()=>{w8();K3();jy();Lx();Jh$=new F1,KJ6=["range","if-none-match","if-modified-since"],HJ6=["content-type","content-length","content-range","accept-ranges","etag","last-modified"];Jh$.get("/:org/files/*",async($)=>{let Z=$.get("studioContext"),X=Z.organization?.id;if(!Z.auth?.user?.id){if(Ah($))return $.redirect(`/login?next=${encodeURIComponent($.req.path)}`,302);throw new $$(401,{message:"Authentication required"})}if(!X)throw new $$(401,{message:"Organization context required"});let Q=$.req.path.replace(/^.*\/files\//,"");if(!Q)throw new $$(400,{message:"Missing file key"});let Y=await Wn(Q,Z);if(!Y)throw new $$(503,{message:"Object storage not configured"});if(Y.startsWith("data:")&&O3()){let K=Y.match(/^data:([^;]+);base64,(.+)$/s);if(!K)throw new $$(500,{message:"Invalid data URL from storage"});let[,H,F]=K,N=Buffer.from(F,"base64"),U=new Headers({"Content-Type":H,"Cache-Control":"private, max-age=86400"});return Gh$(U,H),new Response(N,{status:200,headers:U})}let G=new Headers;for(let K of KJ6){let H=$.req.header(K);if(H)G.set(K,H)}let J=await fetch(Y,{headers:G});if(J.status===403||J.status===404)throw new $$(404,{message:"File not found"});if(!J.ok&&J.status!==304&&J.status!==416)throw console.error(`[files] upstream storage error ${J.status} for key:`,Q),new $$(502,{message:"Upstream storage error"});let W=new Headers;for(let K of HJ6){let H=J.headers.get(K);if(H)W.set(K,H)}return W.set("Cache-Control","private, max-age=86400"),Gh$(W,W.get("content-type")??""),new Response(J.body,{status:J.status,headers:W})});Wh$=Jh$});var Ya=_((__)=>{var FJ6=__&&__.__createBinding||(Object.create?function($,Z,X,Q){if(Q===void 0)Q=X;var Y=Object.getOwnPropertyDescriptor(Z,X);if(!Y||("get"in Y?!Z.__esModule:Y.writable||Y.configurable))Y={enumerable:!0,get:function(){return Z[X]}};Object.defineProperty($,Q,Y)}:function($,Z,X,Q){if(Q===void 0)Q=X;$[Q]=Z[X]}),NJ6=__&&__.__exportStar||function($,Z){for(var X in $)if(X!=="default"&&!Object.prototype.hasOwnProperty.call(Z,X))FJ6(Z,$,X)};Object.defineProperty(__,"__esModule",{value:!0});NJ6(HY(),__)});var Nh$=_((Hh$)=>{Object.defineProperty(Hh$,"__esModule",{value:!0});Hh$.version=void 0;Hh$.version="3.4.0"});var Bh$=_((GH)=>{var UJ6=GH&&GH.__importDefault||function($){return $&&$.__esModule?$:{default:$}};Object.defineProperty(GH,"__esModule",{value:!0});GH.NodeTransport=GH.VERSION=void 0;GH.nodeResolveHost=EJ6;var t6=Ya(),OJ6=z0("net"),R91=z0("tls"),BJ6=z0("path"),Uh$=z0("fs"),wJ6=UJ6(z0("dns")),DJ6=Nh$();GH.VERSION=DJ6.version;var LJ6="nats.js";class Oh${socket;version;lang;yields=[];signal=(0,t6.deferred)();closedNotification=(0,t6.deferred)();options;connected=!1;tlsName="";done=!1;closeError;constructor(){this.lang=LJ6,this.version=GH.VERSION}async connect($,Z){this.tlsName=$.tlsName,this.options=Z;let{tls:X}=this.options,{handshakeFirst:Q}=X||{};try{if(Q===!0)this.socket=await this.tlsFirst($);else this.socket=await this.dial($);if(this.done)this.socket?.destroy();let Y=await this.peekInfo();(0,t6.checkOptions)(Y,Z);let{tls_required:G,tls_available:J}=Y,W=J===!0&&Z.tls!==null;if(!Q&&(G||W))this.socket=await this.startTLS();if(this.done)this.socket?.destroy();if(G&&this.socket.encrypted!==!0)throw t6.errors.InvalidArgumentError.format("tls","is not available on this server");return this.connected=!0,this.setupHandlers(),this.signal.resolve(),Promise.resolve()}catch(Y){let G=Y;if(!G)G=new t6.errors.ConnectionError("error connecting - node provided an undefined error");let{code:J}=G,W=J==="ECONNREFUSED"?new t6.errors.ConnectionError("connection refused",{cause:G}):G;throw this.socket?.destroy(),W}}dial($){let Z=(0,t6.deferred)(),X,Q=(0,OJ6.createConnection)($.port,$.hostname,()=>{Z.resolve(Q),Q.removeAllListeners()});return Q.on("error",(Y)=>{X=Y}),Q.on("close",()=>{Q.removeAllListeners(),Z.reject(X)}),Q.setNoDelay(!0),Z}get isClosed(){return this.done}close($){return this._closed($,!1)}peekInfo(){let $=(0,t6.deferred)(),Z;return this.socket.on("data",(X)=>{this.yields.push(X);let Q=t6.DataBuffer.concat(...this.yields),Y=(0,t6.extractProtocolMessage)(Q);if(Y!=="")try{let G=t6.INFO.exec(Y);if(!G)throw Error("unexpected response from server");let J=JSON.parse(G[1]);$.resolve(J)}catch(G){$.reject(G)}finally{this.socket.removeAllListeners()}}),this.socket.on("error",(X)=>{Z=X}),this.socket.on("close",()=>{this.socket.removeAllListeners(),$.reject(Z)}),$}loadFile($){if(!$)return Promise.resolve();let Z=(0,t6.deferred)();try{if($=(0,BJ6.resolve)($),!(0,Uh$.existsSync)($))Z.reject(Error(`${$} doesn't exist`));(0,Uh$.readFile)($,(X,Q)=>{if(X)return Z.reject(X);Z.resolve(Q)})}catch(X){Z.reject(X)}return Z}async loadClientCerts(){let $={},{certFile:Z,cert:X,caFile:Q,ca:Y,keyFile:G,key:J}=this.options.tls;try{if(Z){let W=await this.loadFile(Z);if(W)$.cert=W}else if(X)$.cert=X;if(G){let W=await this.loadFile(G);if(W)$.key=W}else if(J)$.key=J;if(Q){let W=await this.loadFile(Q);if(W)$.ca=[W]}else if(Y)$.ca=Y;return Promise.resolve($)}catch(W){return Promise.reject(W)}}async tlsFirst($){let Z,X={servername:this.tlsName,rejectUnauthorized:!0};if(this.socket)X.socket=this.socket;if(typeof this.options.tls==="object")try{let Y=await this.loadClientCerts()||{};X=(0,t6.extend)(X,this.options.tls,Y)}catch(Y){return Promise.reject(new t6.errors.ConnectionError(Y.message,{cause:Y}))}let Q=(0,t6.deferred)();try{let Y=(0,R91.connect)($.port,$.hostname,X,()=>{Y.removeAllListeners(),Q.resolve(Y)});Y.on("error",(G)=>{Z=G}),Y.on("secureConnect",()=>{if(X.rejectUnauthorized===!1)return;if(!Y.authorized)throw Y.authorizationError}),Y.on("close",()=>{Q.reject(Z),Y.removeAllListeners()}),Y.setNoDelay(!0)}catch(Y){Q.reject(new t6.errors.ConnectionError(Y.message,{cause:Y}))}return Q}async startTLS(){let $,Z={socket:this.socket,servername:this.tlsName,rejectUnauthorized:!0};if(typeof this.options.tls==="object")try{let Q=await this.loadClientCerts()||{};Z=(0,t6.extend)(Z,this.options.tls,Q)}catch(Q){return Promise.reject(new t6.errors.ConnectionError(Q.message,{cause:Q}))}let X=(0,t6.deferred)();try{let Q=(0,R91.connect)(Z,()=>{Q.removeAllListeners(),X.resolve(Q)});Q.on("error",(Y)=>{$=Y}),Q.on("secureConnect",()=>{if(Z.rejectUnauthorized===!1)return;if(!Q.authorized)throw Q.authorizationError}),Q.on("close",()=>{X.reject($),Q.removeAllListeners()})}catch(Q){X.reject(new t6.errors.ConnectionError(Q.message,{cause:Q}))}return X}setupHandlers(){let $;this.socket.on("data",(Z)=>{return this.yields.push(Z),this.signal.resolve()}),this.socket.on("error",(Z)=>{$=Z}),this.socket.on("end",()=>{if(this.socket?.destroyed)return;this.socket?.write(new Uint8Array(0),()=>{this.socket?.end()})}),this.socket.on("close",()=>{this._closed($,!1)})}[Symbol.asyncIterator](){return this.iterate()}async*iterate(){while(!0){if(this.yields.length===0)await this.signal;let $=this.yields;this.yields=[];for(let Z=0;Z<$.length;Z++){if(this.options.debug)console.info(`> ${(0,t6.render)($[Z])}`);yield $[Z]}if(this.done)break;else if(this.yields.length===0)$.length=0,this.yields=$,this.signal=(0,t6.deferred)()}}discard(){if(this.done=!0,this.socket)try{this.socket.removeAllListeners(),this.socket.destroy()}catch{}}disconnect(){this._closed(void 0,!0).then().catch()}isEncrypted(){return this.socket instanceof R91.TLSSocket}_send($){if(this.isClosed||this.socket===void 0)return Promise.resolve();if(this.options.debug)console.info(`< ${(0,t6.render)($)}`);let Z=(0,t6.deferred)();try{this.socket.write($,(X)=>{if(X){if(this.options.debug)console.error(`!!! ${(0,t6.render)($)}: ${X}`);return Z.reject(X)}return Z.resolve()})}catch(X){if(this.options.debug)console.error(`!!! ${(0,t6.render)($)}: ${X}`);Z.reject(X)}return Z}send($){this._send($).catch((X)=>{})}async _closed($,Z=!0){if(!this.connected)return;if(this.done){this.socket?.destroy();return}if(this.closeError=$,!$&&this.socket&&Z)try{await this._send(new TextEncoder().encode(""))}catch(X){if(this.options.debug)console.log("transport close terminated with an error",X)}try{if(this.socket)this.socket.removeAllListeners(),this.socket?.destroy(),this.socket=void 0}catch(X){console.log(X)}this.done=!0,this.closedNotification.resolve(this.closeError)}closed(){return this.closedNotification}}GH.NodeTransport=Oh$;function EJ6($){let Z=(0,t6.deferred)();return wJ6.default.lookup($,{all:!0},(X,Q)=>{if(X){Z.reject(X);return}let Y=[];for(let G of Q)Y.push(G.address);if(Y.length===0)Y.push($);Z.resolve(Y)}),Z}});var jh$=_((Eh$)=>{Object.defineProperty(Eh$,"__esModule",{value:!0});Eh$.connect=jJ6;var wh$=Bh$(),Dh$=Ya(),Lh$=Ya();function jJ6($={}){if((0,Lh$.hasWsProtocol)($))return Promise.reject(Lh$.errors.InvalidArgumentError.format("servers","node client doesn't support websockets, use the 'wsconnect' function instead"));return(0,Dh$.setTransportFactory)({factory:()=>{return new wh$.NodeTransport},dnsResolveFn:wh$.nodeResolveHost}),Dh$.NatsConnectionImpl.connect($)}});var zh$=_((qN)=>{var PJ6=qN&&qN.__createBinding||(Object.create?function($,Z,X,Q){if(Q===void 0)Q=X;var Y=Object.getOwnPropertyDescriptor(Z,X);if(!Y||("get"in Y?!Z.__esModule:Y.writable||Y.configurable))Y={enumerable:!0,get:function(){return Z[X]}};Object.defineProperty($,Q,Y)}:function($,Z,X,Q){if(Q===void 0)Q=X;$[Q]=Z[X]}),AJ6=qN&&qN.__exportStar||function($,Z){for(var X in $)if(X!=="default"&&!Object.prototype.hasOwnProperty.call(Z,X))PJ6(Z,$,X)};Object.defineProperty(qN,"__esModule",{value:!0});qN.connect=void 0;var TJ6=jh$();Object.defineProperty(qN,"connect",{enumerable:!0,get:function(){return TJ6.connect}});AJ6(Ya(),qN)});function Rh$($){let Z=$?.connectFn??MJ6,X=null,Q=null,Y=!1,G=!1,J=!1,W=[];function K(){return X!==null&&!X.isClosed()&&!X.isDraining()&&!J}function H(){console.log(`[NatsProvider] fireReady: ${W.length} callbacks`);for(let U of W)try{U()}catch{}}function F(U){(async()=>{for await(let O of U.status())if(O.type==="disconnect")console.log("[NatsProvider] Disconnected"),J=!0;else if(O.type==="reconnect")console.log("[NatsProvider] Reconnected, re-firing ready callbacks"),J=!1,Q=null,H()})().catch(()=>{})}async function N(U,O){let B=0;while(!G)try{X=await Z({servers:U,timeout:qJ6,reconnect:!0,maxReconnectAttempts:-1,...O?{authenticator:O}:{}}),console.log(`[NatsProvider] Connected to ${X.getServer()} after ${B} attempt(s)`),Q=null,J=!1,F(X),H();return}catch{B++;let D=pZ(IJ6,RJ6,B-1,2,0.5);await q$(D)}}return{init(U,O){if(Y)return;Y=!0,G=!1;let B=O?.creds?Ph$.credsAuthenticator(new TextEncoder().encode(O.creds)):void 0;N(U,B).catch(()=>{})},isConnected(){return K()},getConnection(){return K()?X:null},getJetStream(){if(!K())return null;if(!Q)Q=Th$.jetstream(X);return Q},onReady(U){if(W.push(U),K())try{U()}catch{}},async drain(){if(G=!0,Y=!1,Q=null,J=!1,X){let U=X;X=null,await U.drain().catch(()=>{})}}}}function MJ6($){return Ah$.connect($)}var Ph$,Ah$,Th$,RJ6=100,IJ6=3000,qJ6=3000;var Ih$=w(()=>{u4();Ph$=V(ju(),1),Ah$=V(zh$(),1),Th$=V(bw(),1)});function I91($,Z){return`${$}.${Z}`}class q91{cache;constructor($){this.cache=Hh({ttlMs:$?.ttlMs??kJ6,maxSize:$?.maxSize??VJ6})}async get($,Z){return this.cache.get(I91($,Z))??null}async set($,Z,X){this.cache.set(I91($,Z),X)}async invalidate($,Z){this.cache.delete(I91($,Z))}teardown(){this.cache.clear()}}var kJ6=600000,VJ6=5000;var qh$=()=>{};function iP0($,Z){return`${$}:${Z}`}function M91($){let Z=Hh({ttlMs:$?.ttlMs??SJ6,maxSize:$?.maxSize??CJ6}),X=$?.getConnection,Q=crypto.randomUUID(),Y=new TextEncoder,G=new TextDecoder,J=null;function W(K,H){let F=X?.();if(!F)return;try{F.publish(Mh$,Y.encode(JSON.stringify({organizationId:K,keyId:H,originId:Q})))}catch(N){console.warn("[ProviderKeyCache] Publish failed (non-critical):",N)}}return{get(K,H){return Z.get(iP0(K,H))},set(K,H,F){Z.set(iP0(K,H),F)},invalidate(K,H){Z.delete(iP0(K,H)),W(K,H)},start(){if(J)return;let K=X?.();if(!K)return;J=K.subscribe(Mh$),(async()=>{for await(let H of J)try{let F=JSON.parse(G.decode(H.data));if(F.originId===Q)continue;Z.delete(iP0(F.organizationId,F.keyId))}catch{}})().catch(console.error)},teardown(){J?.unsubscribe(),J=null,Z.clear()}}}var Mh$="studio.ai-provider-keys.invalidate",SJ6=30000,CJ6=5000;var kh$=()=>{};class k91{options;subscriptions=[];onCancel=null;encoder=new TextEncoder;originId=crypto.randomUUID();seenMessageIds=new Set;constructor($){this.options=$}async start($){if($)this.onCancel=$;if(this.subscriptions.length>0)return;if(!this.onCancel)return;let Z=this.options.getConnection();if(!Z)return;let X=new TextDecoder;this.subscriptions=Vh$.map((Q)=>Z.subscribe(Q));for(let Q of this.subscriptions)(async()=>{for await(let Y of Q)try{let G=JSON.parse(X.decode(Y.data));if(G.originId===this.originId)continue;if(G.messageId&&this.hasSeen(G.messageId))continue;this.onCancel?.(G.taskId)}catch{}})().catch(console.error)}broadcast($){if(/[.*>\s]/.test($)){console.warn("[NatsCancelBroadcast] Invalid threadId, skipping broadcast");return}this.onCancel?.($);try{let Z=this.options.getConnection();if(!Z)return;let X=this.encoder.encode(JSON.stringify({taskId:$,originId:this.originId,messageId:crypto.randomUUID()}));for(let Q of Vh$)Z.publish(Q,X)}catch(Z){console.warn("[NatsCancelBroadcast] Publish failed (non-critical):",Z)}}publishControlFrame($,Z){}async stop(){for(let $ of this.subscriptions)$.unsubscribe();this.subscriptions=[],this.seenMessageIds.clear(),this.onCancel=null}hasSeen($){if(this.seenMessageIds.has($))return!0;if(this.seenMessageIds.add($),this.seenMessageIds.size>1000){let Z=this.seenMessageIds.values().next().value;if(Z)this.seenMessageIds.delete(Z)}return!1}}var Vh$;var Sh$=w(()=>{Vh$=["studio.decopilot.cancel","mesh.decopilot.cancel"]});var Ch$=($)=>{let Z;return()=>Z??=$()},V91,S91;var _h$=w(()=>{f6();V91=Ch$(()=>S$.createHistogram("decopilot.stream.encode_ms",{description:"Per-chunk JSON.stringify+encode time for decopilot stream",unit:"ms"})),S91=Ch$(()=>S$.createCounter("decopilot.stream.published_chunks",{description:"Logical decopilot stream chunks published to JetStream",unit:"{chunks}"}))});function gJ6(){return{name:mF,subjects:[`${Uw0}.>`],storage:GW.StorageType.File,max_age:fJ6,max_bytes:xJ6,max_msgs_per_subject:yJ6,discard:GW.DiscardPolicy.Old,retention:GW.RetentionPolicy.Limits,duplicate_window:bJ6,num_replicas:1}}class bh${chunks=0;encodeMs=0;maxMs=0;bytes=0;windowStart=performance.now();constructor(){setInterval(()=>this.flush(),1e4).unref?.()}record($,Z){if(this.chunks++,this.encodeMs+=$,$>this.maxMs)this.maxMs=$;this.bytes+=Z}flush(){let $=performance.now(),Z=$-this.windowStart;if(this.chunks>0&&Z>0)console.warn(JSON.stringify({msg:"stream-encode-trace",windowMs:Math.round(Z),chunks:this.chunks,encodeMs:Math.round(this.encodeMs),pctOfLoop:+(this.encodeMs/Z*100).toFixed(1),maxChunkMs:+this.maxMs.toFixed(2),mbEncoded:+(this.bytes/1048576).toFixed(2)}));this.chunks=0,this.encodeMs=0,this.maxMs=0,this.bytes=0,this.windowStart=$}}function vh$($){let Z=fh$.headers();for(let[X,Q]of Object.entries($))Z.set(X,Q);return Z}function lJ6($,Z){let X=0;return{publish(Q,Y,G,J){Q.publish(Y,G,J?{headers:J}:void 0).catch((W)=>{if(X++,vJ6().add(1,{"org.id":Z??"unknown"}),X===1||X%100===0)console.warn(`[Decopilot] JetStream publish failed for thread ${$} (${X} total):`,W)})},get errorCount(){return X}}}function dJ6($){if(!($ instanceof Error))return!1;if($.name==="TimeoutError")return!0;return/timeout|no responders|503/i.test($.message)}class C91{options;js=null;jsm=null;constructor($){this.options=$}async init(){let $=this.options.getConnection();if(!$){console.log("[Decopilot] StreamBuffer.init skipped: NATS not connected yet");return}let Z=gJ6(),X=await N9(async()=>{let Q=this.options.getJetStreamManager?await this.options.getJetStreamManager():await GW.jetstreamManager($);try{await Q.streams.info(mF),await Q.streams.update(mF,Z)}catch(Y){if(Y instanceof Error&&Y.message.includes("stream not found"))await Q.streams.add(Z);else if(Y instanceof Error&&/can ?not change.*storage|storage type/i.test(Y.message))await Q.streams.delete(mF),await Q.streams.add(Z);else throw Y}return Q},{maxAttempts:5,minTimeout:250,maxTimeout:4000,jitter:0.5,isRetriable:dJ6});this.js=this.options.getJetStream(),this.jsm=X,console.log(`[Decopilot] StreamBuffer.init ${this.js?"ready":"degraded (js=null)"}`)}pump($,Z,X,Q){let Y=this.js;if(!Y)return console.warn(`[Decopilot] pump: JetStream client unavailable for thread ${Z}; chunks NOT published to NATS`),Promise.resolve();let G=lJ6(Z,Q),J=!1,W=()=>{if(J)return;J=!0;let H=SH$(Z);Y.publish(H.subject,H.data).catch(()=>{})};X.addEventListener("abort",W,{once:!0});let K=(H)=>{let F=performance.now(),N=vt0(H,{runId:Z}),U=performance.now()-F;if(V91().record(U),S91().add(1,{"org.id":Q??"unknown"}),cJ6?.record(U,N.reduce((O,B)=>O+B.data.length,0)),N.length===0){console.warn(`[Decopilot] dropping oversized stream chunk for thread ${Z}`);return}for(let O of N)G.publish(Y,O.subject,O.data,O.headers?vh$(O.headers):void 0)};return(async()=>{let H=$.getReader(),F=0,N=0,U;try{while(!0){let{done:O,value:B}=await H.read();if(O)break;if(K(B),N++,++F>=64)F=0,await new Promise((D)=>setImmediate(D))}}catch(O){U=O,console.warn(`[Decopilot] stream pump error for thread ${Z}:`,O?.message??O)}finally{if(H.releaseLock(),W(),uJ6)console.warn(JSON.stringify({msg:"decopilot-stream-diag",event:"pump-done",taskId:Z,publishedChunks:N,publishErrors:G.errorCount}))}if(U!==void 0)throw U})()}async publishRawChunk($,Z,X){let Q=this.js;if(!Q)return!1;let Y=performance.now(),G=vt0(Z,{runId:$,dedup:X});if(V91().record(performance.now()-Y),S91().add(1),G.length===0)return console.warn(`[Decopilot] dropping oversized raw chunk for thread ${$} (> MAX_CHUNKED_BYTES)`),!0;for(let J of G)await Q.publish(J.subject,J.data,{...J.headers?{headers:vh$(J.headers)}:{},...J.msgId?{msgID:J.msgId}:{}});return!0}async publishDone($,Z,X){let Q=this.js;if(!Q)return!1;let Y=VH$({runId:$,fenceToken:Z,finalSeq:X});return await Q.publish(Y.subject,Y.data,{msgID:Y.msgId}),!0}async createTailStream($,Z,X){let Q=this.js;if(!Q)return console.warn(`[Decopilot] createTailStream: JetStream client unavailable for thread ${$}; no live tail`),null;let Y=X?.deliverPolicy==="new"?GW.DeliverPolicy.New:GW.DeliverPolicy.All,G=X?.closeOnDone??!1,J=MB($),W;try{W=await(await Q.consumers.get(mF,{filter_subjects:J,deliver_policy:Y})).consume()}catch(D){return console.warn("[Decopilot] JetStream tail unavailable (non-critical):",D?.message??D),null}let F=Lw0({messages:async function*(){try{for await(let D of W)yield{subject:D.subject,data:D.data,headers:D.headers}}finally{W.stop()}}(),onCancel:()=>W.stop()}).pipeThrough(Ow0()).pipeThrough(Bw0()).getReader(),N=!1,U=()=>{if(N)return;N=!0;try{F.releaseLock()}catch{}},O=!1,B=()=>{if(O)return;O=!0,W.stop(),F.cancel().catch(()=>{}),U()};return Z?.addEventListener("abort",B,{once:!0}),new ReadableStream({async pull(D){for(;;){let{done:L,value:E}=await F.read();if(L){B(),D.close();return}let j=E;if(j.kind==="done"){if(G){B(),D.close();return}continue}D.enqueue(j.chunk);return}},cancel(){B()}})}purge($){if(!this.jsm)return;this.jsm.streams.purge(mF,{filter:MB($)}).catch(()=>{})}teardown(){this.js=null,this.jsm=null}}var GW,fh$,_J6=($)=>{let Z;return()=>Z??=$()},vJ6,fJ6=86400000000000,bJ6=120000000000,xJ6=4294967296,yJ6=500000,hJ6,uJ6,cJ6;var xh$=w(()=>{u4();ft0();Ew0();ww0();f6();_h$();GW=V(bw(),1),fh$=V(ju(),1),vJ6=_J6(()=>S$.createCounter("decopilot.stream.publish_errors",{description:"Number of JetStream publish failures for decopilot stream chunks",unit:"{errors}"}));hJ6=process.env.STREAM_ENCODE_TRACE==="1",uJ6=process.env.DECOPILOT_STREAM_TRACE==="1";cJ6=hJ6?new bh$:null});function pP0($,Z,X,Q){if(!Q)return!1;return $.emit(Z,kW(X,Q.status,{title:Q.title??void 0,virtualMcpId:Q.virtual_mcp_id??void 0,createdBy:Q.created_by??void 0,triggerId:Q.trigger_id??null,branch:Q.branch??null,harnessId:Q.harness_id??void 0,createdAt:Q.created_at,updatedAt:Q.updated_at})),!0}var yh$=w(()=>{U8()});class _91{storage;options;timer=null;constructor($,Z={}){this.storage=$;this.options=Z}start(){if(this.timer)return;let $=this.options.intervalMs??300000;this.timer=setInterval(()=>{this.runOnce()},$)}async runOnce(){let $=this.options.staleAfterMs??3600000;try{let Z=await this.storage.sweepAbandoned($);if(Z>0)console.log(`[async-research-sweeper] marked ${Z} stale jobs as abandoned`);return Z}catch(Z){return console.error("[async-research-sweeper] sweep failed",Z),0}}dispose(){if(this.timer)clearInterval(this.timer),this.timer=null}}function rJ6($){return $ instanceof n7}function aJ6($,Z){return Z-$>=tJ6}class v91{taskBoard;contextFactory;billing;options;timer=null;running=!1;cursor=null;constructor($,Z,X,Q={}){this.taskBoard=$;this.contextFactory=Z;this.billing=X;this.options=Q}start(){if(this.timer)return;let $=this.options.intervalMs??mJ6;this.timer=setInterval(()=>{this.runOnce()},$),this.timer.unref()}async runOnce(){if(this.running)return 0;this.running=!0;let $=0;try{let Z=this.options.batchSize??pJ6,X=this.options.itemIntervalMs??iJ6,Q=new Date(Date.now()-X),Y=await this.taskBoard.listItemsPendingReview(Z,this.cursor,Q),G=Y.at(-1);this.cursor=Y.length===Z&&G?{updatedAt:G.updatedAt,id:G.id}:null;for(let{id:J,organizationId:W}of Y)try{if(await this.reconcileItem(J,W,Q))$++}catch(K){console.error(`[task-board-review-sweeper] ${J} failed`,K)}await this.reapNeverStartedThreads(Z),$+=await this.dispatchDueRetries(Z),await this.reactToUnhandledFailures(Z)}catch(Z){console.error("[task-board-review-sweeper] sweep failed",Z)}finally{this.running=!1}return $}async reapNeverStartedThreads($){try{let Z=await this.taskBoard.failNeverStartedLinkedThreads($,new Date(Date.now()-In0),Do0);for(let X of Z)console.warn(`[task-board-review-sweeper] failed never-started thread ${X.threadId} on ${X.itemId}`)}catch(Z){console.error("[task-board-review-sweeper] reaping failed",Z)}}async reactToUnhandledFailures($){let Z=await this.taskBoard.listItemsStuckAfterFailure($,new Date(Date.now()-oJ6));for(let{id:X,organizationId:Q,threadId:Y}of Z)try{console.warn(`[task-board-review-sweeper] reacting to an unhandled failure on ${X}`),await Xt0(this.taskBoard,Y,Q),await Qt0(this.taskBoard,this.billing,Y,Q)}catch(G){console.error(`[task-board-review-sweeper] unhandled-failure reaction for ${X} failed`,G)}}async dispatchDueRetries($){let Z=0,X=await this.taskBoard.listItemsDueForRetry($,new Date);for(let{id:Q,organizationId:Y,attempts:G}of X)try{if(!await this.taskBoard.claimDueRetry(Q,Y,new Date))continue;let J=await this.taskBoard.getById(Q,Y);if(!J||J.status!=="in_progress"||J.assigneeId!==n8)continue;let W=await this.contextFactory(Y,J.assignedBy??J.createdBy);if(!W)continue;await iF(W,J,{runClass:"retry"}),Z++,console.warn(`[task-board-review-sweeper] re-dispatched ${Q} after a failure (attempt ${G})`)}catch(J){if(console.error(`[task-board-review-sweeper] retry dispatch for ${Q} failed`,J),rJ6(J)){await this.returnToTodo(Q,Y,J instanceof Error?J.message:String(J));continue}await this.taskBoard.scheduleRunRetry(Q,Y,G,new Date(Date.now()+nJ6)).catch((W)=>console.error(`[task-board-review-sweeper] re-arming ${Q} failed`,W))}return Z}async returnToTodo($,Z,X){try{let Q=await this.taskBoard.getById($,Z);if(!Q||Q.status!=="in_progress")return;let Y=await this.taskBoard.returnToTodoAfterFailure($,Z,Q.updatedBy);if(!Y)return;await this.taskBoard.recordActivity({taskBoardItemId:$,action:"status_changed",actorId:null,data:{from:"in_progress",to:"todo",reason:X}}).catch(()=>{}),A8(Z,Y)}catch(Q){console.error(`[task-board-review-sweeper] returning ${$} to todo failed`,Q)}}async handOffReviewWithoutPr($,Z){let X=await this.taskBoard.listActivity(Z.id,Z.organizationId);if(!aJ6(LF(X),Date.now()))return;await qK($,Z,"no pull request is linked to this task \u2014 there is nothing for a "+"reviewer to review")}async reconcileItem($,Z,X){if(!await this.taskBoard.claimSweep($,Z,X))return!1;let Q=await this.taskBoard.getById($,Z);if(!Q)return!1;if(Q.status!=="in_review")return!1;let Y=Q.assigneeId===n8,G=await this.taskBoard.listPrs($,Z),J=await this.contextFactory(Z,Q.assignedBy??Q.createdBy);if(!J)return!1;if(G.length===0){if(Y)await this.handOffReviewWithoutPr(J,Q);return!1}if(await lF$(J,Q))return!0;if(!Y)return!1;let W=await Promise.all(G.map(async(K)=>({...K,...await vy(Z,K)})));if(W.every((K)=>K.state===null))console.warn(`[task-board-review-sweeper] ${$}: no live PR state from GitHub (${W.length} PR(s)) \u2014 proceeding on unknown`);if(!Uo0(W))return!1;return await Rw0(J,Q,{previewMatchesHead:Oo0(W)}),!0}dispose(){if(this.timer)clearInterval(this.timer),this.timer=null}}var mJ6=60000,iJ6=300000,pJ6=50,nJ6=60000,tJ6=900000,oJ6=120000;var gh$=w(()=>{E9();Yo0();cF();Mn();G9();E3();Lo0();kK();Pn()});import{readdir as sJ6,rm as nP0}from"fs/promises";import{join as tP0}from"path";async function oP0($){let Z=new Date;Z.setUTCDate(Z.getUTCDate()-eJ6),Z.setUTCHours(0,0,0,0);let X=0;try{let Q=await v_($);for(let Y of Q)if(/^\d{4}$/.test(Y))X+=await hh$($,Y,Z);else if(!Y.startsWith(".")){let G=tP0($,Y),J=await v_(G);for(let K of J){if(!/^\d{4}$/.test(K))continue;X+=await hh$(G,K,Z)}if((await v_(G)).length===0)await nP0(G,{recursive:!0,force:!0})}}catch(Q){console.warn("monitoring retention cleanup failed:",Q)}return X}async function hh$($,Z,X){let Q=0,Y=tP0($,Z),G=await v_(Y);for(let W of G){if(!/^\d{2}$/.test(W))continue;let K=tP0(Y,W),H=await v_(K);for(let N of H){if(!/^\d{2}$/.test(N))continue;let U=new Date(`${Z}-${W}-${N}T00:00:00Z`);if(isNaN(U.getTime()))continue;if(U<X){let O=tP0(K,N);await nP0(O,{recursive:!0,force:!0}),Q++}}if((await v_(K)).length===0)await nP0(K,{recursive:!0,force:!0})}if((await v_(Y)).length===0)await nP0(Y,{recursive:!0,force:!0});return Q}async function v_($){try{return(await sJ6($)).filter((X)=>!X.startsWith("."))}catch{return[]}}var eJ6=30;var f91=()=>{};import{DBOS as b91,SchedulerMode as $36}from"@dbos-inc/dbos-sdk";async function X36(){let $=[qJ(),f_(),HH()],Z=0;for(let X of $)try{Z+=await oP0(X)}catch(Q){console.error("[monitoring-retention] cleanup failed:",Q)}return console.log(`[monitoring-retention] deleted ${Z} day-dir(s) across ${$.length} signal dir(s)`),{deleted:Z,dirs:$.length}}async function Q36($,Z){await b91.runStep(()=>X36(),{name:"monitoringRetention"})}function ch$(){if(uh$)return;uh$=!0;let $=b91.registerWorkflow(Q36,{name:"monitoringRetentionWorkflow"});b91.registerScheduled($,{name:"monitoringRetentionWorkflow",crontab:Z36,mode:$36.ExactlyOncePerIntervalWhenActive})}var Z36="23 4 * * *",uh$=!1;var lh$=w(()=>{GY();f91()});function dh$($){return async(Z,X)=>{let Q=await $.db.selectFrom("member").innerJoin("organization","organization.id","member.organizationId").select(["member.role","organization.id as orgId","organization.slug as orgSlug","organization.name as orgName"]).where("member.userId","=",X).where("member.organizationId","=",Z).executeTakeFirst();if(!Q)return console.warn(`[automationContextFactory] User ${X} not found in org ${Z} \u2014 returning null`),null;let Y=await sG.create();Y.auth.user={id:X,role:Q.role},Y.organization={id:Q.orgId,slug:Q.orgSlug,name:Q.orgName};let G=await b41($.db,Z,Q.role);return Y.boundAuth=f41({auth:Y.authInstance,headers:new Headers,role:Q.role,permissions:G,userId:X}),Y.access=new wL(X,void 0,Y.boundAuth,Q.role,"self"),AB(Y,{id:Q.orgId,slug:Q.orgSlug}),Y}}var mh$=w(()=>{DL();YC()});function Y36(){return{services:[{name:"Postgres",status:"pending",port:0},{name:"NATS",status:"pending",port:0}],migrationsStatus:"pending",serverUrl:null,logs:[]}}function J36(){for(let $ of G36)$()}function ih$($){let Z=[...x91.logs,$];x91={...x91,logs:Z.length>500?Z.slice(-500):Z},J36()}function y91(){return W36}var x91,G36,W36=!1;var g91=w(()=>{x91=Y36(),G36=new Set});import{EventEmitter as K36}from"events";var h91;var ph$=w(()=>{g91();h91=new K36;h91.on("request",($)=>{ih$($)})});function nh$(){return async($,Z)=>{let X=Date.now(),Q=$.req.method,Y=$.req.path;if(Y==="/api/auth/get-session"||Y.includes("favicon")){await Z();return}let G="",J=!1;if(Y.startsWith("/mcp")&&Q==="POST"){J=!0;try{if($.req.header("Content-Type")?.includes("application/json")){let U=await $.req.raw.clone().json();if(U.method==="tools/call"&&U.params?.name){let O=oh(U.params.name),B=U.params.arguments||{},D=Object.keys(B).map((E)=>oh(E)),L=D.length>0?D.slice(0,3).join(",")+(D.length>3?"\u2026":""):"";G=`${Y5.tool}${O}${Y5.dim}(${L})${Y5.reset}`}else if(U.method)G=`${Y5.dim}${oh(U.method)}${Y5.reset}`}}catch{}}let W=oh(Y);if(Y.startsWith("/mcp/conn_")){let F=Y.split("/")[2]??"";W=`/mcp/${Y5.mcp}${oh(F.slice(0,12))}\u2026${Y5.reset}`}else if(Y==="/mcp")W=`${Y5.mcp}/mcp${Y5.reset}`;else if(Y==="/mcp/registry")W=`${Y5.mcp}/mcp/registry${Y5.reset}`;let K=F36(Q),H=J?"\u25C0":"\u2190";if(!y91())console.log(`${Y5.dim}${H}${Y5.reset} ${K}${Q}${Y5.reset} ${W}${G?` ${G}`:""}`);try{await Z()}finally{let F=Date.now()-X,N=$.res.status,U=H36(N),O=F<1000?`${F}ms`:`${(F/1000).toFixed(1)}s`,B=J?"\u25B6":"\u2192";if(!y91())console.log(`${Y5.dim}${B}${Y5.reset} ${K}${Q}${Y5.reset} ${W}${G?` ${G}`:""} ${U}${N}${Y5.reset} ${Y5.duration}${O}${Y5.reset}`);h91.emit("request",{method:Q,path:oh(Y),status:N,duration:F,timestamp:new Date})}}}var Y5,H36=($)=>{if($>=500)return Y5.serverError;if($>=400)return Y5.clientError;if($>=300)return Y5.redirect;return Y5.ok},F36=($)=>{return Y5[$]||Y5.reset},oh=($)=>{return $.replace(/\r/g,"").replace(/\n/g,"").replace(/\x1b\[[0-9;]*m/g,"").replace(/[\x00-\x1f\x7f-\x9f]/g,"")};var th$=w(()=>{g91();ph$();Y5={reset:"\x1B[0m",dim:"\x1B[2m",bold:"\x1B[1m",GET:"\x1B[36m",POST:"\x1B[33m",PUT:"\x1B[35m",DELETE:"\x1B[31m",ok:"\x1B[32m",redirect:"\x1B[36m",clientError:"\x1B[33m",serverError:"\x1B[31m",mcp:"\x1B[35m",tool:"\x1B[96m",duration:"\x1B[90m"}});import{createHmac as sh$}from"crypto";import{mkdir as N36,readdir as U36,rm as oh$,stat as eh$}from"fs/promises";import{join as c91,relative as O36}from"path";import{z as z$}from"zod";function Zu$($){let Z=$.replace(/[^a-zA-Z0-9_-]/g,"_");return c91(B36,Z)}function Xu$($){return $.replace(/^\/+/,"").replace(/\.\./g,"")}function u91($,Z){let X=Zu$($),Q=Xu$(Z);return c91(X,Q)}function w36($,Z,X,Q){let Y=b0().encryptionKey||"dev-secret",G=`${$}:${Z}:${X}:${Q}`;return sh$("sha256",Y).update(G).digest("hex")}function ah$($,Z,X,Q,Y){let G=Math.floor(Date.now()/1000)+Q,J=w36(Z,X,G,Y),W=new URL(`/api/dev-assets/${Z}/${Xu$(X)}`,$);return W.searchParams.set("expires",G.toString()),W.searchParams.set("signature",J),W.searchParams.set("method",Y),W.toString()}function Qu$($,Z,X){let Q=`${$}:${Z.getTime()}:${X}`;return`"${sh$("md5","etag").update(Q).digest("hex")}"`}async function Yu$($,Z,X,Q,Y){try{let G=await U36($,{withFileTypes:!0});for(let J of G){let W=c91($,J.name),H=O36(Z,W).replace(/\\/g,"/");if(X&&!H.startsWith(X))continue;if(J.isDirectory())if(Q){let F=H+"/";if(!X||F.startsWith(X)){if(!(X?H.slice(X.length):H).includes("/"))Y.commonPrefixes.add(F)}}else await Yu$(W,Z,X,Q,Y);else if(J.isFile()){if(Q&&X){let F=H.slice(X.length);if(F.includes(Q)){let N=F.indexOf(Q),U=X+F.slice(0,N+1);Y.commonPrefixes.add(U);continue}}try{let F=await eh$(W);Y.objects.push({key:H,size:F.size,lastModified:F.mtime.toISOString(),etag:Qu$(W,F.mtime,F.size)})}catch{}}}}catch{}}function Gu$($,Z){let Q=t($).id;return[{name:"LIST_OBJECTS",description:"List objects in the local assets directory with pagination support",inputSchema:z$.object({prefix:z$.string().optional(),maxKeys:z$.number().optional().default(1000),continuationToken:z$.string().optional(),delimiter:z$.string().optional()}),outputSchema:z$.object({objects:z$.array(z$.object({key:z$.string(),size:z$.number(),lastModified:z$.string(),etag:z$.string()})),nextContinuationToken:z$.string().optional(),isTruncated:z$.boolean(),commonPrefixes:z$.array(z$.string()).optional()}),handler:async(Y)=>{let G=Y,J=G.prefix||"",W=G.maxKeys??1000,K=G.delimiter,H=G.continuationToken,F=Zu$(Q);await N36(F,{recursive:!0});let N={objects:[],commonPrefixes:new Set};await Yu$(F,F,J,K,N),N.objects.sort((L,E)=>L.key.localeCompare(E.key));let U=0;if(H){if(U=N.objects.findIndex((L)=>L.key>H),U===-1)U=N.objects.length}let O=N.objects.slice(U,U+W),B=U+W<N.objects.length,D=B?O[O.length-1]?.key:void 0;return{objects:O,isTruncated:B,nextContinuationToken:D,commonPrefixes:Array.from(N.commonPrefixes).sort()}}},{name:"GET_OBJECT_METADATA",description:"Get metadata for a file in the local assets directory",inputSchema:z$.object({key:z$.string()}),outputSchema:z$.object({contentType:z$.string().optional(),contentLength:z$.number(),lastModified:z$.string(),etag:z$.string(),metadata:z$.record(z$.string(),z$.string()).optional()}),handler:async(Y)=>{let G=Y,J=u91(Q,G.key),W=await eh$(J);return{contentType:z61(G.key),contentLength:W.size,lastModified:W.mtime.toISOString(),etag:Qu$(J,W.mtime,W.size)}}},{name:"GET_PRESIGNED_URL",description:"Generate a presigned URL for downloading a file from local storage",inputSchema:z$.object({key:z$.string(),expiresIn:z$.number().optional()}),outputSchema:z$.object({url:z$.string(),expiresIn:z$.number()}),handler:async(Y)=>{let G=Y,J=G.expiresIn??rh$;return{url:ah$(Z,Q,G.key,J,"GET"),expiresIn:J}}},{name:"PUT_PRESIGNED_URL",description:"Generate a presigned URL for uploading a file to local storage",inputSchema:z$.object({key:z$.string(),expiresIn:z$.number().optional(),contentType:z$.string().optional()}),outputSchema:z$.object({url:z$.string(),expiresIn:z$.number()}),handler:async(Y)=>{let G=Y,J=G.expiresIn??rh$;return{url:ah$(Z,Q,G.key,J,"PUT"),expiresIn:J}}},{name:"DELETE_OBJECT",description:"Delete a single file from local storage",inputSchema:z$.object({key:z$.string()}),outputSchema:z$.object({success:z$.boolean(),key:z$.string()}),handler:async(Y)=>{let G=Y,J=u91(Q,G.key);try{return await oh$(J),{success:!0,key:G.key}}catch{return{success:!1,key:G.key}}}},{name:"DELETE_OBJECTS",description:"Delete multiple files from local storage",inputSchema:z$.object({keys:z$.array(z$.string()).max(1000)}),outputSchema:z$.object({deleted:z$.array(z$.string()),errors:z$.array(z$.object({key:z$.string(),message:z$.string()}))}),handler:async(Y)=>{let G=Y,J=[],W=[];return await Promise.all(G.keys.map(async(K)=>{let H=u91(Q,K);try{await oh$(H),J.push(K)}catch(F){W.push({key:K,message:F instanceof Error?F.message:"Unknown error"})}})),{deleted:J,errors:W}}}]}async function l91($,Z,X){let Q=Gu$(Z,X),Y=new bW({name:"dev-assets-mcp",version:"1.0.0"},{capabilities:{tools:{}},jsonSchemaValidator:H5});for(let J of Q){let W="shape"in J.inputSchema?J.inputSchema.shape:z$.object({}).shape,K=J.outputSchema&&"shape"in J.outputSchema?J.outputSchema.shape:z$.object({}).shape;Y.registerTool(J.name,{description:J.description??"",inputSchema:W,outputSchema:K,annotations:J.annotations,_meta:J._meta},async(H)=>{try{let F=await J.handler(H);return{content:[{type:"text",text:JSON.stringify(F)}],structuredContent:F}}catch(F){return{content:[{type:"text",text:`Error: ${F.message}`}],isError:!0}}})}let G=new sX({enableJsonResponse:$.headers.get("Accept")?.includes("application/json")??!1});return await Y.connect(G),GJ(Y,G,$,"mcp:dev-assets")}async function Ju$($,Z,X,Q){let G=Gu$(X,Q).find((J)=>J.name===$);if(!G)return{content:[{type:"text",text:`Tool not found: ${$}`}],isError:!0};try{let J=await G.handler(Z);return{content:[{type:"text",text:JSON.stringify(J)}]}}catch(J){return{content:[{type:"text",text:J instanceof Error?J.message:String(J)}],isError:!0}}}var B36="./data/assets",rh$=3600,$u$,Wu$;var Ku$=w(()=>{T$();hy();w8();ll();wC();_X();dz0();$u$=new F1;$u$.all("/",async($)=>{let Z=$.get("studioContext"),X=new URL($.req.url),Q=`${X.protocol}//${X.host}`;return l91($.req.raw,Z,Q)});Wu$=$u$});var Hu$={};Y4(Hu$,{mountDevRoutes:()=>D36});function D36($,Z){$.all("/mcp/:connectionId{.*_dev-assets$}",Z,async(Q)=>{let Y=Q.get("studioContext"),G=new URL(Q.req.url),J=`${G.protocol}//${G.host}`;return l91(Q.req.raw,Y,J)}),$.all("/mcp/:connectionId{.*_dev-assets$}/call-tool/:toolName",Z,async(Q)=>{let Y=Q.get("studioContext"),G=new URL(Q.req.url),J=`${G.protocol}//${G.host}`,W=Q.req.param("toolName");if(!W)return Q.json({error:"Missing tool name"},400);let K=await Q.req.json(),H=await Ju$(W,K,Y,J);if(H.isError)return Q.json(H.content,500);return Q.json(H.content)}),$.use("/mcp/dev-assets",Z),$.route("/mcp/dev-assets",Wu$);let X=new F1;X.use("*",QW({mountPath:"/api/dev-assets"})),X.route("/",lz0({orgFromPath:!1})),$.route("/api/dev-assets",X)}var Fu$=w(()=>{w8();O61();dz0();Ku$()});import{sql as L36}from"kysely";import{randomUUID as Nu$}from"crypto";import{z as E36}from"zod";async function z36($){let Z=new Date().toISOString(),X=Nu$(),Q=l4.SELF($.organizationId),Y="registry.publish_request.created",G={requestId:$.request.id,requestedId:$.request.requested_id,title:$.request.title,status:$.request.status,createdAt:$.request.created_at,requester:{name:$.request.requester_name,email:$.request.requester_email}};await $.db.insertInto("events").values({id:X,organization_id:$.organizationId,type:"registry.publish_request.created",source:Q,specversion:"1.0",subject:$.request.id,time:Z,datacontenttype:"application/json",dataschema:null,data:JSON.stringify(G),cron:null,status:"pending",attempts:0,last_error:null,next_retry_at:null,created_at:Z,updated_at:Z}).execute();let J=await $.db.selectFrom("event_subscriptions").select(["id"]).where("organization_id","=",$.organizationId).where("enabled","=",1).where("event_type","=","registry.publish_request.created").where((W)=>W.or([W("publisher","is",null),W("publisher","=",Q)])).execute();if(J.length>0)await $.db.insertInto("event_deliveries").values(J.map((W)=>({id:Nu$(),event_id:X,subscription_id:W.id,status:"pending",attempts:0,last_error:null,delivered_at:null,next_retry_at:null,created_at:Z}))).execute();try{await L36`SELECT
2809
2809
  pg_notify('studio_events', ${X}),