@decocms/mesh 2.125.3 → 2.127.0

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 (212) hide show
  1. package/dist/client/assets/{AlertCircle-CAn1onHH.js → AlertCircle-DJ052zqS.js} +1 -1
  2. package/dist/client/assets/{AlertOctagon-ChcnKW7P.js → AlertOctagon-DCNCOxEl.js} +1 -1
  3. package/dist/client/assets/{AlertTriangle-Suhq71Ba.js → AlertTriangle-MQM19F_y.js} +1 -1
  4. package/dist/client/assets/{ArrowDown-BQn3fvf7.js → ArrowDown-Bn9Nw2BD.js} +1 -1
  5. package/dist/client/assets/{ArrowLeft-DkojAdWe.js → ArrowLeft-BSPqreiE.js} +1 -1
  6. package/dist/client/assets/{ArrowUp-CCTJ8tar.js → ArrowUp-BLFAP4Oh.js} +1 -1
  7. package/dist/client/assets/{Check-2BTd1528.js → Check-BXz-Aa3Y.js} +1 -1
  8. package/dist/client/assets/{CheckCircle-DUsP9qJl.js → CheckCircle-DmsV77x1.js} +1 -1
  9. package/dist/client/assets/{CheckDone01-Bs5yfbwu.js → CheckDone01-CQuFbmYi.js} +1 -1
  10. package/dist/client/assets/{CheckVerified02-D9LvEg4-.js → CheckVerified02-C2uVr9FW.js} +1 -1
  11. package/dist/client/assets/{ChevronDown-BK0Z-3ss.js → ChevronDown-CEb48ZDu.js} +1 -1
  12. package/dist/client/assets/{ChevronRight-CpFHeZ-k.js → ChevronRight-CQS5xbc3.js} +1 -1
  13. package/dist/client/assets/{Clock-DWLl74MU.js → Clock-X1ZnQ0e8.js} +1 -1
  14. package/dist/client/assets/{Code01-D7rt1C5k.js → Code01-CVF-mmmz.js} +1 -1
  15. package/dist/client/assets/{Container-Dkua_wx6.js → Container-D3N8SS-J.js} +1 -1
  16. package/dist/client/assets/{Copy01-CWD2XYkN.js → Copy01-CFXdI8SF.js} +1 -1
  17. package/dist/client/assets/{Dataflow03-dIUcYa_e.js → Dataflow03-BvFbR-2p.js} +1 -1
  18. package/dist/client/assets/{DotsHorizontal-R03fSXLm.js → DotsHorizontal-BlKZUIAr.js} +1 -1
  19. package/dist/client/assets/{DotsVertical-nJGFqnIJ.js → DotsVertical-CJJQe-sw.js} +1 -1
  20. package/dist/client/assets/{Download01-w53nljTi.js → Download01-BuGXWPUb.js} +1 -1
  21. package/dist/client/assets/{Edit01-Een9NeGa.js → Edit01-vxAH-tv6.js} +1 -1
  22. package/dist/client/assets/{Eye-cRMKwlob.js → Eye-Cqy0OQfO.js} +1 -1
  23. package/dist/client/assets/{File02-BiHbI-Bs.js → File02-CYWnFy5E.js} +1 -1
  24. package/dist/client/assets/{File06-DK6hozGp.js → File06-p-mGMfLu.js} +1 -1
  25. package/dist/client/assets/{FilterLines-DcFfiBYv.js → FilterLines-B-D6srZC.js} +1 -1
  26. package/dist/client/assets/{Globe01-zBSU4RrG.js → Globe01-Di6WS1d0.js} +1 -1
  27. package/dist/client/assets/{Globe02-BzI-D3XF.js → Globe02-CL5aTFno.js} +1 -1
  28. package/dist/client/assets/{Grid01-DtWTP079.js → Grid01-BGPoEeik.js} +1 -1
  29. package/dist/client/assets/{Hash02-B_cIkiva.js → Hash02-BWg3CKrn.js} +1 -1
  30. package/dist/client/assets/{Home02-B0J9-6Fj.js → Home02-Atzompjz.js} +1 -1
  31. package/dist/client/assets/{Image01-DuLPJrbP.js → Image01-B-9nWGvT.js} +1 -1
  32. package/dist/client/assets/{Inbox01-DkeOZ2C_.js → Inbox01-CWbCHIve.js} +1 -1
  33. package/dist/client/assets/{InfoCircle-v_Zi3ix-.js → InfoCircle-BxNpDB4f.js} +1 -1
  34. package/dist/client/assets/{Key01-FdWHEw6c.js → Key01-BBHw8-AF.js} +1 -1
  35. package/dist/client/assets/{LinkExternal01-BvWelMzx.js → LinkExternal01-BH7m2QmL.js} +1 -1
  36. package/dist/client/assets/{List-D1SXIq-Q.js → List-DZq_3WJK.js} +1 -1
  37. package/dist/client/assets/{Loading01-BntQXW3R.js → Loading01-Bm0RmGTq.js} +1 -1
  38. package/dist/client/assets/{Lock01-Ca25inpJ.js → Lock01-BY0MGONc.js} +1 -1
  39. package/dist/client/assets/{Pin01-D5SNXGno.js → Pin01-BQxfi8aj.js} +1 -1
  40. package/dist/client/assets/{Play-Dv6XoPC1.js → Play-CGUn4LDu.js} +1 -1
  41. package/dist/client/assets/{Plus-BpJ1F9ED.js → Plus-CfD4U7h2.js} +1 -1
  42. package/dist/client/assets/{RefreshCcw01-C6HpBrM2.js → RefreshCcw01-ClQUpEVA.js} +1 -1
  43. package/dist/client/assets/{RefreshCw01-BLvlqjIJ.js → RefreshCw01-DsYl6Nso.js} +1 -1
  44. package/dist/client/assets/{Rows03-Bw2KmPLF.js → Rows03-BmDCzA2B.js} +1 -1
  45. package/dist/client/assets/{Save01-C7Op6P3G.js → Save01-CVm8Nhi5.js} +1 -1
  46. package/dist/client/assets/{SearchMd-B22BWSrE.js → SearchMd-rBeGYVN8.js} +1 -1
  47. package/dist/client/assets/{Settings01-39eYdV1s.js → Settings01-BCU61Dg3.js} +1 -1
  48. package/dist/client/assets/{Shield01-D5vtlDrS.js → Shield01-D73wrcGm.js} +1 -1
  49. package/dist/client/assets/{Terminal-jwgZ8meH.js → Terminal-B7IR3GOF.js} +1 -1
  50. package/dist/client/assets/Tool01-D4p-h1gd.js +1 -0
  51. package/dist/client/assets/{Trash01-NHvYJiOw.js → Trash01-CNjhe6V_.js} +1 -1
  52. package/dist/client/assets/{Upload01-B7z0chWz.js → Upload01-KtFgXqwG.js} +1 -1
  53. package/dist/client/assets/{Users03-CfBv5uVc.js → Users03-DNxW_fja.js} +1 -1
  54. package/dist/client/assets/{X-nbY3n5YX.js → X-OID4YrAs.js} +1 -1
  55. package/dist/client/assets/{XCircle-CdrNrzcr.js → XCircle-LfPUm5IL.js} +1 -1
  56. package/dist/client/assets/{XClose-DHV8bqGR.js → XClose-CVjVP425.js} +1 -1
  57. package/dist/client/assets/{agent-connections-preview-D2nPeCg-.js → agent-connections-preview-BPhKy-Id.js} +1 -1
  58. package/dist/client/assets/agent-detail-HyuxH4Ve.js +2 -0
  59. package/dist/client/assets/agents-Bc9eRkDe.js +1 -0
  60. package/dist/client/assets/{alert-dialog-DIblcPQC.js → alert-dialog-9GjsXnzK.js} +1 -1
  61. package/dist/client/assets/{auth-catchall-lueUuNUs.js → auth-catchall-Bsy9nmf9.js} +1 -1
  62. package/dist/client/assets/{avatar-DAde4Coq.js → avatar-D7LZZNPu.js} +1 -1
  63. package/dist/client/assets/{badge-EvnzqGBM.js → badge-CQ9R9pkG.js} +1 -1
  64. package/dist/client/assets/{binder-DtqSnmtn.js → binder-BRFblyKj.js} +1 -1
  65. package/dist/client/assets/{breadcrumb-Dit0z7A7.js → breadcrumb-_jAneXHm.js} +1 -1
  66. package/dist/client/assets/{button-DDY6hri1.js → button-BjJbLzI1.js} +1 -1
  67. package/dist/client/assets/{card-CHcjH7V4.js → card-BiNPXwY7.js} +1 -1
  68. package/dist/client/assets/{chart-BEZIHLHA.js → chart-Cye540qd.js} +5 -5
  69. package/dist/client/assets/{checkbox-_pZquTsv.js → checkbox-ClNyXMEe.js} +1 -1
  70. package/dist/client/assets/{circle-alert-8my-DdYx.js → circle-alert-BwBTOPt2.js} +1 -1
  71. package/dist/client/assets/collection-detail-CgUzsg7m.js +26 -0
  72. package/dist/client/assets/collection-search-D9lLlfmK.js +1 -0
  73. package/dist/client/assets/collection-tab-CK-Q89lj.js +1 -0
  74. package/dist/client/assets/collection-table-wrapper-HJznMrYU.js +1 -0
  75. package/dist/client/assets/{collection-tabs-CMMj9apF.js → collection-tabs-D0BDRIQH.js} +1 -1
  76. package/dist/client/assets/{command-D0lPyqX9.js → command-CmCm6EpS.js} +1 -1
  77. package/dist/client/assets/{connect-jPJQySxH.js → connect-D_vBcyxr.js} +1 -1
  78. package/dist/client/assets/{connection-card-C36z_Zfo.js → connection-card-O78FPkKW.js} +1 -1
  79. package/dist/client/assets/connection-detail-CqECx5w9.js +1 -0
  80. package/dist/client/assets/connections-DcBskx9Y.js +1 -0
  81. package/dist/client/assets/{constants-BWuwqVaf.js → constants-Bz_J8k2h.js} +1 -1
  82. package/dist/client/assets/constants-CQfW12Qo.js +1 -0
  83. package/dist/client/assets/{context-BoqYBHof.js → context-DPw3JrfP.js} +1 -1
  84. package/dist/client/assets/{create-organization-dialog-DZ-29KA3.js → create-organization-dialog-ChDwEIL0.js} +1 -1
  85. package/dist/client/assets/{create-project-dialog-5JWgj7o1.js → create-project-dialog-D_pqfYAD.js} +1 -1
  86. package/dist/client/assets/{deco-constants-Lndb0_Fi.js → deco-constants-CGrimklY.js} +1 -1
  87. package/dist/client/assets/{dialog-AmArt43J.js → dialog-CsS26GNP.js} +1 -1
  88. package/dist/client/assets/{dropdown-menu-CMr4pVGd.js → dropdown-menu-Bx6HZEO6.js} +1 -1
  89. package/dist/client/assets/{dynamic-plugin-layout-B-RWLbim.js → dynamic-plugin-layout-ChDoP95P.js} +1 -1
  90. package/dist/client/assets/editable-thread-title-DG8vSbP7.js +16 -0
  91. package/dist/client/assets/{empty-state-BxqfhnZC.js → empty-state-BIKMZA4A.js} +1 -1
  92. package/dist/client/assets/{env-vars-editor-CeWJLU0d.js → env-vars-editor-Bu4z6L63.js} +1 -1
  93. package/dist/client/assets/{error-boundary-BbdoNwwk.js → error-boundary-BOjL_3iE.js} +1 -1
  94. package/dist/client/assets/{extract-connection-data-FghvIcuN.js → extract-connection-data-9qHOXLXC.js} +1 -1
  95. package/dist/client/assets/{file-browser-BRNDEG3O.js → file-browser-DlsvWnR4.js} +2 -2
  96. package/dist/client/assets/{form-Bsyh-cQj.js → form-BcYKMkAo.js} +1 -1
  97. package/dist/client/assets/{grid-view-BjxbyS3V.js → grid-view-DKE_LwVv.js} +1 -1
  98. package/dist/client/assets/{home-BqlHZV0D.js → home-CfX1o6Ev.js} +1 -1
  99. package/dist/client/assets/index-B7FUMscm.css +1 -0
  100. package/dist/client/assets/{index-ClGhCbA0.js → index-BFnklquP.js} +72 -62
  101. package/dist/client/assets/{index-IwkUYudi.js → index-BqwppNxk.js} +1 -1
  102. package/dist/client/assets/{index-CMIePc8v.js → index-CKXRhh0t.js} +37 -37
  103. package/dist/client/assets/{index-7GX9Z2_E.js → index-DbG6jisP.js} +1 -1
  104. package/dist/client/assets/{index-BwsTCLNe.js → index-Ds78Hq48.js} +1 -1
  105. package/dist/client/assets/index-LVMAuFW8.js +1 -0
  106. package/dist/client/assets/{index-_qbzL5MU.js → index-kQL4iCgd.js} +1 -1
  107. package/dist/client/assets/{index-Ck8tqNHK.js → index-lC9RbQEq.js} +1 -1
  108. package/dist/client/assets/{index-MmPZuevW.js → index-nl6bR4T8.js} +1 -1
  109. package/dist/client/assets/{infiniteQueryObserver-DuAdiH0n.js → infiniteQueryObserver-C_YVCa9u.js} +1 -1
  110. package/dist/client/assets/{input-Je9XV62u.js → input-BPPp7fkV.js} +1 -1
  111. package/dist/client/assets/{integration-icon-DeiJ75EP.js → integration-icon-CaUI1jG_.js} +1 -1
  112. package/dist/client/assets/{label-Ct-IE-k2.js → label-Ce-8MeXM.js} +1 -1
  113. package/dist/client/assets/{layout-BWtcS0Q2.js → layout-B_vm2aCi.js} +1 -1
  114. package/dist/client/assets/{localstorage-keys-B-4HWrAO.js → localstorage-keys-D7-2hl7K.js} +1 -1
  115. package/dist/client/assets/{login-swb3IsCw.js → login-BZjy-JZF.js} +1 -1
  116. package/dist/client/assets/{markdown-BshJmJUr.js → markdown-CL_nEHz6.js} +1 -1
  117. package/dist/client/assets/mcp-oauth-6gipdrl8.js +1 -0
  118. package/dist/client/assets/{mcp-server-card-DJ-C7iNn.js → mcp-server-card-k65UbfnQ.js} +1 -1
  119. package/dist/client/assets/mcp-server-detail-DOi3A41L.js +2 -0
  120. package/dist/client/assets/members-DyXednFN.js +3 -0
  121. package/dist/client/assets/{monitoring-Dkzs8zLr.js → monitoring-CbDWX7qw.js} +2 -2
  122. package/dist/client/assets/{monitoring-dashboard-edit-6Jd7ItfF.js → monitoring-dashboard-edit-Xu9WaY0f.js} +1 -1
  123. package/dist/client/assets/{monitoring-dashboard-view-NmZHmCWV.js → monitoring-dashboard-view-BnJZoOh6.js} +1 -1
  124. package/dist/client/assets/{oauth-callback-hu62EGGB.js → oauth-callback-CLQrXT_i.js} +1 -1
  125. package/dist/client/assets/page-NSWxyYqB.js +1 -0
  126. package/dist/client/assets/page-tLMAT584.js +1 -0
  127. package/dist/client/assets/{plugin-empty-state-BfDH4uPn.js → plugin-empty-state-D5Ff5dMm.js} +1 -1
  128. package/dist/client/assets/{plugin-empty-state-DRRVQKmb.js → plugin-empty-state-WLlCNcH0.js} +1 -1
  129. package/dist/client/assets/{plugin-header-BPNBXPjM.js → plugin-header-DBNmWz2Z.js} +1 -1
  130. package/dist/client/assets/{plugin-header-8kNYjC6n.js → plugin-header-D_CX7196.js} +1 -1
  131. package/dist/client/assets/{popover-CdPr2kUy.js → popover-Dz4mFPzW.js} +1 -1
  132. package/dist/client/assets/{project-layout-bgteQ5fY.js → project-layout-L7FdQtTW.js} +1 -1
  133. package/dist/client/assets/projects-list-DFLeaqhB.js +1 -0
  134. package/dist/client/assets/{ranking-layout-BxRgmZtS.js → ranking-layout-CLhL84_g.js} +1 -1
  135. package/dist/client/assets/{readme-viewer-ym80L_hw.js → readme-viewer-BAJaQnye.js} +1 -1
  136. package/dist/client/assets/{registry-layout-C8Ew4flr.js → registry-layout-CLL316VY.js} +1 -1
  137. package/dist/client/assets/{registry-utils-DBAgugDf.js → registry-utils-C_nLhlWN.js} +1 -1
  138. package/dist/client/assets/{reports-layout-BoIJWhiW.js → reports-layout-DnfAta3q.js} +2 -2
  139. package/dist/client/assets/{reset-password-DY5mUItc.js → reset-password-Cpx9ZUFt.js} +1 -1
  140. package/dist/client/assets/{resizable-8m39GKGn.js → resizable-TMJNEC5w.js} +1 -1
  141. package/dist/client/assets/{save-actions-DnxE-Bzm.js → save-actions-BYQZP6Sr.js} +1 -1
  142. package/dist/client/assets/{scroll-area-C-RNU2ZC.js → scroll-area-D6nBfX1Y.js} +4 -4
  143. package/dist/client/assets/{select-B9AjxT2Q.js → select-CwR5iwKr.js} +1 -1
  144. package/dist/client/assets/shell-layout-BnW-yUkb.js +3 -0
  145. package/dist/client/assets/{skeleton-BAWgWTH6.js → skeleton-DzMO4E_x.js} +1 -1
  146. package/dist/client/assets/{spinner-C5H8EOvR.js → spinner-B4HBT9r3.js} +1 -1
  147. package/dist/client/assets/{store-invite-BSP87zro.js → store-invite-DR-2VUII.js} +1 -1
  148. package/dist/client/assets/{switch-Bnxx_fFZ.js → switch-DkAfY5Xp.js} +1 -1
  149. package/dist/client/assets/{table-Bt31_DyV.js → table-BDxbk9kk.js} +1 -1
  150. package/dist/client/assets/tasks-JeX1dzU3.js +1 -0
  151. package/dist/client/assets/{textarea-Dfcf9iVI.js → textarea-C7R7dq5L.js} +1 -1
  152. package/dist/client/assets/{time-range-picker-VoxMdMGw.js → time-range-picker-CPtVWgsO.js} +1 -1
  153. package/dist/client/assets/{toggle-group-BYr6H2N2.js → toggle-group-BsC04HU0.js} +1 -1
  154. package/dist/client/assets/tools-list-C1FJexpR.js +1 -0
  155. package/dist/client/assets/{tooltip-Kun6OEqc.js → tooltip-C-TvyUPP.js} +1 -1
  156. package/dist/client/assets/{topbar-portal-BYkDxjeH.js → topbar-portal-BlsIm0Za.js} +1 -1
  157. package/dist/client/assets/types-DWiNuJXJ.js +155 -0
  158. package/dist/client/assets/{use-binding-Bt6opM01.js → use-binding-DtOyQ6H-.js} +1 -1
  159. package/dist/client/assets/{use-connection-CZeLlUDa.js → use-connection-CU1wdNM8.js} +1 -1
  160. package/dist/client/assets/{use-copy-BLt7-cw9.js → use-copy-C-xyAEAK.js} +1 -1
  161. package/dist/client/assets/{use-create-virtual-mcp-BWbRPuCZ.js → use-create-virtual-mcp-CdmTVIKM.js} +1 -1
  162. package/dist/client/assets/use-deco-chat-open-yra_c3Dw.js +1 -0
  163. package/dist/client/assets/{use-install-from-registry-BsUBgwfp.js → use-install-from-registry-Dpg6ludv.js} +1 -1
  164. package/dist/client/assets/{use-list-state-B_n0GZwG.js → use-list-state-DEj8YIwi.js} +1 -1
  165. package/dist/client/assets/{use-llm-CBsUcVLv.js → use-llm-Bjuj_MKF.js} +1 -1
  166. package/dist/client/assets/use-mcp-prompts-C2SxEfwc.js +1 -0
  167. package/dist/client/assets/{use-mcp-tools-BED8kPD7.js → use-mcp-tools-aLeNmzej.js} +1 -1
  168. package/dist/client/assets/{use-mobile-DLzBblnh.js → use-mobile-B6wwiLld.js} +1 -1
  169. package/dist/client/assets/{use-organization-settings-BTKBql6r.js → use-organization-settings-DdF3cHOT.js} +1 -1
  170. package/dist/client/assets/{use-project-Dgs5h9hm.js → use-project-Bmqhspht.js} +1 -1
  171. package/dist/client/assets/{use-settings-modal-CL7KNbwO.js → use-settings-modal-BQGLflyF.js} +1 -1
  172. package/dist/client/assets/{use-view-mode-Cm6MlS0B.js → use-view-mode-D5ZS-ZdB.js} +1 -1
  173. package/dist/client/assets/{use-virtual-mcp-chylq6BL.js → use-virtual-mcp-DqbEku8h.js} +1 -1
  174. package/dist/client/assets/useInfiniteQuery-DgzNofe0.js +1 -0
  175. package/dist/client/assets/{useMutation-CTU78J7M.js → useMutation-D2jNlXyR.js} +1 -1
  176. package/dist/client/assets/useQuery-6KDecjjg.js +1 -0
  177. package/dist/client/assets/useSuspenseInfiniteQuery-B2-Ew4j-.js +1 -0
  178. package/dist/client/assets/workflow-DJP52hJ3.js +1 -0
  179. package/dist/client/index.html +2 -2
  180. package/dist/server/cli.js +5 -5
  181. package/dist/server/migrate.js +2 -2
  182. package/dist/server/server.js +5 -5
  183. package/package.json +2 -1
  184. package/dist/client/assets/agent-detail-CAAcyNFf.js +0 -2
  185. package/dist/client/assets/agents-IxYsoQkx.js +0 -1
  186. package/dist/client/assets/collection-detail-BPjVfY9E.js +0 -26
  187. package/dist/client/assets/collection-search-BhyeAK8D.js +0 -1
  188. package/dist/client/assets/collection-tab-DYRZjIfR.js +0 -1
  189. package/dist/client/assets/collection-table-wrapper-DF0r5l64.js +0 -1
  190. package/dist/client/assets/connection-detail-D4fpJvP6.js +0 -1
  191. package/dist/client/assets/connections-Dd7R3YoP.js +0 -1
  192. package/dist/client/assets/constants-alL-orOw.js +0 -1
  193. package/dist/client/assets/empty-state-CUU2GnRG.js +0 -1
  194. package/dist/client/assets/index-D1eaSCBW.css +0 -1
  195. package/dist/client/assets/index-DFjHyz2s.js +0 -1
  196. package/dist/client/assets/mcp-oauth-DtHeHoWJ.js +0 -1
  197. package/dist/client/assets/mcp-server-detail-Du1aBWwk.js +0 -2
  198. package/dist/client/assets/members-BLWGtvj7.js +0 -3
  199. package/dist/client/assets/page-C-wJ53x_.js +0 -1
  200. package/dist/client/assets/page-Y1SYGnRN.js +0 -1
  201. package/dist/client/assets/projects-list-DngofdiO.js +0 -1
  202. package/dist/client/assets/shell-layout-DY2c6Efx.js +0 -3
  203. package/dist/client/assets/tasks-OIFCJv2K.js +0 -1
  204. package/dist/client/assets/tools-list-CMPsf87L.js +0 -1
  205. package/dist/client/assets/typewriter-title-ir44iZyu.js +0 -16
  206. package/dist/client/assets/use-deco-chat-open-DqF5WsjN.js +0 -1
  207. package/dist/client/assets/use-mcp-prompts-CTAKOvKB.js +0 -1
  208. package/dist/client/assets/useInfiniteQuery-B4zFsz_-.js +0 -1
  209. package/dist/client/assets/useQuery-CL8s1AaN.js +0 -1
  210. package/dist/client/assets/useSuspenseInfiniteQuery-CnNOZleg.js +0 -1
  211. package/dist/client/assets/view-mode-toggle-lRAyyRMm.js +0 -1
  212. package/dist/client/assets/workflow-CH4Jfjr7.js +0 -1
@@ -1469,7 +1469,7 @@ ${Y.stack}`;return Q}if(typeof Y==="object"&&Y!==null){let Q=Y,X="";if(typeof Q.
1469
1469
  ${Q.stack}`;return X}try{let G=JSON.stringify(Q,null,2);if(G!=="{}"&&G.length<1000){if(typeof Q.stack==="string"&&Q.stack&&Q.stack.length<2000)return`${G}
1470
1470
 
1471
1471
  Stack trace:
1472
- ${Q.stack}`;return G}}catch{}if(typeof Q.toString==="function")try{let G=Q.toString();if(G!=="[object Object]")return G}catch{}let J=Object.keys(Q);if(J.length>0)return`Object with keys: ${J.join(", ")}`;return"[object Object]"}if(typeof Y==="string")return Y;if(typeof Y==="number"||typeof Y==="boolean")return String(Y);if(typeof Y==="function")return`[Function: ${Y.name||"anon"}]`;if(typeof Y==="symbol")return Y.toString();if(typeof Y==="bigint")return Y.toString();try{return String(Y)}catch{return"Unknown value (could not convert to string)"}}function BO(Y,Q){switch(typeof Q){case"string":return Y.newString(Q);case"number":return Y.newNumber(Q);case"boolean":return Q?Y.true:Y.false;case"undefined":return Y.undefined;case"object":{if(Q===null)return Y.null;if(Array.isArray(Q)){let J=Y.newArray();return Q.forEach((G,K)=>{let W=BO(Y,G);try{Y.setProp(J,String(K),W)}finally{W.dispose?.()}}),J}let X=Y.newObject();for(let[J,G]of Object.entries(Q)){let K=BO(Y,G);try{Y.setProp(X,J,K)}finally{K.dispose?.()}}return X}case"function":{let X=`__hostFn_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return Y.newFunction(X,(...G)=>{try{let K=G.map((Z)=>Y.dump(Z)),W=Q(...K);if(W&&typeof W.then==="function"){let Z=Y.newPromise();return W.then((H)=>{try{let $=BO(Y,H);Z.resolve($),$.dispose()}catch($){let F=qO($),V=Y.newString(`Promise resolution error: ${F}`);Z.reject(V),V.dispose()}finally{Y.runtime.executePendingJobs()}}).catch((H)=>{let $=qO(H),F=Y.newString(`Promise rejection: ${$}`);Z.reject(F),F.dispose(),Y.runtime.executePendingJobs()}),Z.handle}return BO(Y,W)}catch(K){let W=qO(K);return Y.newString(`HostFunctionError: ${W}`)}finally{G.forEach((K)=>K.dispose())}})}case"bigint":return Y.newString(Q.toString());case"symbol":return Y.newString(Q.toString());default:try{return Y.newString(String(Q))}catch{return Y.undefined}}}var xc0=()=>{};function LO1(Y){let Q=Y.runtime.executePendingJobs(100);try{if("unwrap"in Q&&typeof Q.unwrap==="function")Q.unwrap()}finally{if("dispose"in Q&&typeof Q.dispose==="function")Q.dispose()}}async function Or(Y,Q,X){let J=Date.now(),G=Y.resolvePromise(Q);while(!0){LO1(Y);let K=await Promise.race([G,lm6(0).then(()=>null)]);if(K!==null)return K;if(Date.now()-J>X)throw Error(`Timed out after ${X}ms while awaiting a QuickJS promise`)}}async function Dv({tools:Y,code:Q,timeoutMs:X}){let W=[];try{const J=kB(W,await NO1({memoryLimitBytes:33554432,stackSizeBytes:524288}),0);const G=kB(W,J.newContext({interruptAfterMs:X}),0);const K=kB(W,OO1(G),0);try{let F=G.evalCode(Q,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult(F),B=BO(G,Y);G.setProp(G.global,"tools",B);let U=G.runtime.hasPendingJob()?G.unwrapResult(await Or(G,V,X)):V;if(U!==V)V.dispose();let D=G.getProp(U,"default"),z=G.typeof(D);if(z!=="function")return D.dispose(),U.dispose(),B.dispose(),{error:`Code must export default a function (tools). Got ${z}. Example: export default async (tools) => { /* ... */ }`,consoleLogs:K.logs};let L=G.callFunction(D,G.undefined,B);B.dispose(),D.dispose(),U.dispose();let w=G.unwrapResult(L),E=await Or(G,w,X);w.dispose();let T=G.unwrapResult(E);if(G.runtime.hasPendingJob())LO1(G);let C=G.dump(T);return T.dispose(),{returnValue:C,consoleLogs:K.logs}}catch(F){return console.log(F),{error:qO(F),consoleLogs:K.logs}}}catch(Z){var H=Z,$=1}finally{Ls(W,H,$)}}async function MO1({input:Y,code:Q,timeoutMs:X}){let W=[];try{const J=kB(W,await NO1({memoryLimitBytes:33554432,stackSizeBytes:524288}),0);const G=kB(W,J.newContext({interruptAfterMs:X}),0);const K=kB(W,OO1(G),0);try{let F=G.evalCode(Q,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult(F),B=BO(G,Y);G.setProp(G.global,"input",B);let U=G.runtime.hasPendingJob()?G.unwrapResult(await Or(G,V,X)):V;if(U!==V)V.dispose();let D=G.getProp(U,"default"),z=G.typeof(D);if(z!=="function")return D.dispose(),U.dispose(),B.dispose(),{error:`Code must export default a function (input). Got ${z}. Example: export default (input) => { return input.items.map(i => i.name); }`,consoleLogs:K.logs};let L=G.callFunction(D,G.undefined,B);B.dispose(),D.dispose(),U.dispose();let w=G.unwrapResult(L),E=await Or(G,w,X);w.dispose();let T=G.unwrapResult(E);if(G.runtime.hasPendingJob())LO1(G);let C=G.dump(T);return T.dispose(),{returnValue:C,consoleLogs:K.logs}}catch(F){return console.log(F),{error:qO(F),consoleLogs:K.logs}}}catch(Z){var H=Z,$=1}finally{Ls(W,H,$)}}var lm6=(Y)=>new Promise((Q)=>setTimeout(Q,Y));var gc0=j(()=>{hc0();xc0()});var Nr=j(()=>{gc0()});async function dm6(Y,Q){let X=Y.connections.map((K)=>K.connection_id),J=[];for(let K of X){let W=await Q.storage.connections.findById(K);if(W&&W.status==="active")J.push(W)}return J.map((K)=>{let W=Y.connections.find((Z)=>Z.connection_id===K.id);return{connection:K,selectedTools:W?.selected_tools??null,selectedResources:W?.selected_resources??null,selectedPrompts:W?.selected_prompts??null}})}async function uc0(Y,Q){return(await Q.storage.connections.list(Y)).filter((J)=>J.status==="active").map((J)=>({connection:J,selectedTools:null,selectedResources:null,selectedPrompts:null}))}async function pm6(Y,Q){let X=new Map;for(let B of Y)X.set(B.connection.id,B);let J=Y.map((B)=>B.connection),G=new Map,K=await Promise.allSettled(J.map(async(B)=>{try{let U=await Q.createMCPProxy(B);return{connection:B,proxy:U}}catch(U){return console.warn(`[code-execution] Failed to create proxy for connection ${B.id}:`,U),null}}));for(let B of K)if(B.status==="fulfilled"&&B.value)G.set(B.value.connection.id,B.value);let W=await Promise.allSettled(Array.from(G.entries()).map(async([B,U])=>{try{let z=(await U.proxy.listTools()).tools,L=X.get(B);if(L?.selectedTools&&L.selectedTools.length>0){let w=new Set(L.selectedTools);z=z.filter((E)=>w.has(E.name))}return{connectionId:B,connectionTitle:U.connection.title,tools:z}}catch(D){return console.error(`[code-execution] Failed to list tools for connection ${B}:`,D),null}})),Z=new Set,H=[],$=new Map;for(let B of W){if(B.status!=="fulfilled"||!B.value)continue;let{connectionId:U,connectionTitle:D,tools:z}=B.value;for(let L of z){if(Z.has(L.name))continue;Z.add(L.name),H.push({...L,_meta:{connectionId:U,connectionTitle:D}}),$.set(L.name,U)}}let F=async(B,U)=>{let D=$.get(B);if(!D)return{content:[{type:"text",text:`Tool not found: ${B}`}],isError:!0};let z=G.get(D);if(!z)return{content:[{type:"text",text:`Connection not found for tool: ${B}`}],isError:!0};return await z.proxy.callTool({name:B,arguments:U})},V=[];for(let[,B]of G)V.push(B.proxy.close().catch(()=>{}));return await Promise.all(V),{tools:H,callTool:F}}async function NP(Y){let Q=v0(Y),X;if(Y.connectionId){let J=await Y.storage.virtualMcps.findById(Y.connectionId,Y.organization?.id);if(J)X=await dm6(J,Y);else X=await uc0(Q.id,Y)}else X=await uc0(Q.id,Y);return pm6(X,Y)}function cm6(Y){return Y.toLowerCase().split(/[\s_\-./]+/).filter((Q)=>Q.length>=2)}function nm6(Y,Q){let X=0,J=Q.name.toLowerCase(),G=(Q.description??"").toLowerCase(),K=(Q._meta?.connectionTitle??"").toLowerCase();for(let W of Y){if(J===W)X+=10;else if(J.includes(W))X+=3;if(G.includes(W))X+=2;if(K.includes(W))X+=1}return X}function Lr(Y,Q,X){let J=cm6(Y);if(J.length===0)return Q.slice(0,X);return Q.map((G)=>({tool:G,score:nm6(J,G)})).filter((G)=>G.score>0).sort((G,K)=>K.score-G.score).slice(0,X).map((G)=>G.tool)}function Mr(Y,Q){let X=new Map(Q.map((G)=>[G.name,G]));return{tools:Y.map((G)=>X.get(G)).filter((G)=>G!==void 0).map((G)=>({name:G.name,description:G.description,connection:G._meta?.connectionTitle??"",inputSchema:G.inputSchema,outputSchema:G.outputSchema})),notFound:Y.filter((G)=>!X.has(G))}}async function wr(Y,Q,X){let J=Object.fromEntries(Q.tools.map((G)=>[G.name,async(K)=>{let W=await Q.callTool(G.name,K??{});if(W.structuredContent&&typeof W.structuredContent==="object")return W.structuredContent;let Z=W.content;if(Z?.[0]?.type==="text"&&Z[0].text)try{return JSON.parse(Z[0].text)}catch{return Z[0].text}return W}]));return Dv({code:Y,tools:J,timeoutMs:X})}function zv(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}]}}function qB(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}],isError:!0}}function zF(Y){let Q=new Set(im6);return Y.filter((X)=>!Q.has(X.name))}var im6;var UO=j(()=>{Nr();im6=["CODE_EXECUTION_SEARCH_TOOLS","CODE_EXECUTION_DESCRIBE_TOOLS","CODE_EXECUTION_RUN_CODE"]});var wO1;var mc0=j(()=>{F4();Uv();UO();wO1=t1({name:"CODE_EXECUTION_SEARCH_TOOLS",description:"Search for available tools by name or description. Returns tool names and brief descriptions without full schemas. Use this to discover tools before calling CODE_EXECUTION_DESCRIBE_TOOLS for detailed schemas.",annotations:{title:"Search Tools",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:Ic0,outputSchema:jc0,handler:async(Y,Q)=>{D0(Q),v0(Q),await Q.access.check();let X=await NP(Q),J=Lr(Y.query,X.tools,Y.limit);return{query:Y.query,results:J.map((G)=>({name:G.name,description:G.description,connection:G._meta?.connectionTitle??""})),totalAvailable:X.tools.length}}})});var AO1;var lc0=j(()=>{F4();Uv();UO();AO1=t1({name:"CODE_EXECUTION_DESCRIBE_TOOLS",description:"Get detailed schemas for specific tools. Call after CODE_EXECUTION_SEARCH_TOOLS to get full input/output schemas before executing code.",annotations:{title:"Describe Tools",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:Sc0,outputSchema:kc0,handler:async(Y,Q)=>{D0(Q),v0(Q),await Q.access.check();let X=await NP(Q);return Mr(Y.tools,X.tools)}})});var PO1;var dc0=j(()=>{F4();Uv();UO();PO1=t1({name:"CODE_EXECUTION_RUN_CODE",description:'Run JavaScript code in a sandbox. Code must be an ES module that `export default`s an async function that receives (tools) as its first parameter. Use CODE_EXECUTION_DESCRIBE_TOOLS to understand the input/output schemas for a tool before calling it. Use `await tools.toolName(args)` or `await tools["tool-name"](args)` to call tools.',annotations:{title:"Run Code",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},inputSchema:vc0,outputSchema:_c0,handler:async(Y,Q)=>{D0(Q),v0(Q),await Q.access.check();let X=await NP(Q);return await wr(Y.code,X,Y.timeoutMs)}})});var pc0=j(()=>{mc0();lc0();dc0();Uv()});var rm6,om6,EO1;var cc0=j(()=>{QY();n1();F4();rn();p$();rm6=q.object({data:_T.describe("Data for the new connection (id is auto-generated if not provided)")}),om6=q.object({item:Y5.describe("The created connection entity")}),EO1=t1({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",annotations:{title:"Create Connection",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:rm6,outputSchema:om6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=TY(Q);if(!J)throw Error("User ID required to create connection");let G={...Y.data,organization_id:X.id,created_by:J};if(G.connection_type==="VIRTUAL"){let $=AU(G.connection_url);if(!$)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let F=await Q.storage.virtualMcps.findById($);if(!F)throw Error(`Virtual MCP not found: ${$}`);if(F.organization_id!==X.id)throw Error("Virtual MCP does not belong to the current organization");G.connection_url=PU($)}let K=await EA({id:`pending-${Date.now()}`,title:G.title,connection_type:G.connection_type,connection_url:G.connection_url,connection_token:G.connection_token,connection_headers:G.connection_headers}).catch(()=>null),W=K?.tools?.length?K.tools:null,Z=K?.scopes?.length?K.scopes:null,H=await Q.storage.connections.create({...G,tools:W,configuration_scopes:Z});return await Q.eventBus.publish(X.id,IY.SELF(X.id),{type:"connection.created",data:H}),{item:H}}})});var sm6,tm6,nc0;var ic0=j(()=>{n1();MG();sm6=pH.extend({avatar:q.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:q.string().describe("System prompt that defines the assistant's behavior"),virtual_mcp_id:q.string().describe("Virtual MCP ID to use for this assistant"),model:q.object({id:q.string().describe("Model ID"),connectionId:q.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),tm6=cH("assistant",sm6),nc0=[...tm6]});var Ov,OF,rc0,em6,Yl6,oc0,Ql6,Xl6,Jl6,Gl6,Wl6,Zl6,sc0,Kl6,Hl6,$l6,Fl6,Vl6,ql6,Bl6,Ul6,Dl6,zl6,RV9,Ol6,IV9,ac0,Nl6,Ll6,TO1,Nv;var Ar=j(()=>{n1();xz();MG();Ov=q.lazy(()=>q.union([q.null(),q.string(),q.number(),q.boolean(),q.record(q.string(),Ov),q.array(Ov)])),OF=q.record(q.string(),q.record(q.string(),Ov)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),rc0=q.object({type:q.literal("text"),text:q.string().describe("The text content"),providerOptions:OF}),em6=q.object({type:q.literal("text"),text:q.string().describe("The text content"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),Yl6=q.string().describe("File data as URL string"),oc0=q.object({type:q.literal("file"),filename:q.string().optional().describe("Optional filename of the file"),data:Yl6,mediaType:q.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:OF}),Ql6=q.object({type:q.literal("file"),mediaType:q.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),data:q.string().describe("Generated file data as base64 encoded string")}),Xl6=q.object({type:q.literal("reasoning"),text:q.string().describe("The reasoning text"),providerOptions:OF}),Jl6=q.object({type:q.literal("reasoning"),text:q.string().describe("The reasoning text"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),Gl6=q.object({type:q.literal("tool-call"),toolCallId:q.string().describe("ID of the tool call, used to match with tool result"),toolName:q.string().describe("Name of the tool being called"),input:q.string().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:q.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:OF}),Wl6=q.object({type:q.literal("tool-call"),toolCallId:q.string().describe("ID of the tool call"),toolName:q.string().describe("Name of the tool being called"),input:q.string().describe("Stringified JSON object with the tool call arguments"),providerExecuted:q.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),Zl6=q.union([q.object({type:q.literal("text"),value:q.string()}),q.object({type:q.literal("json"),value:Ov}),q.object({type:q.literal("error-text"),value:q.string()}),q.object({type:q.literal("error-json"),value:Ov}),q.object({type:q.literal("content"),value:q.array(q.union([q.object({type:q.literal("text"),text:q.string().describe("Text content")}),q.object({type:q.literal("media"),data:q.string().describe("Base-64 encoded media data"),mediaType:q.string().describe("IANA media type")})]))}),q.object({type:q.literal("execution-denied"),reason:q.string().optional()}),q.string().describe("Raw or JSON-serialized output (e.g. from AI SDK mapToolResultOutput)")]),sc0=q.object({type:q.literal("tool-result"),toolCallId:q.string().describe("ID of the tool call that this result is associated with"),toolName:q.string().describe("Name of the tool that generated this result"),output:Zl6.describe("Result of the tool call"),result:q.unknown().describe("Unknown result of the tool call"),providerOptions:OF}),Kl6=q.object({type:q.literal("tool-result"),toolCallId:q.string().describe("ID of the tool call that this result is associated with"),toolName:q.string().describe("Name of the tool that generated this result"),result:q.any().describe("Result of the tool call (JSON-serializable)"),isError:q.boolean().optional().describe("Whether the result is an error or error message"),providerExecuted:q.boolean().optional().describe("Whether the tool result was generated by the provider"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),Hl6=q.union([q.object({type:q.literal("source"),sourceType:q.literal("url"),id:q.string().describe("The ID of the source"),url:q.string().describe("The URL of the source"),title:q.string().optional().describe("The title of the source"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),q.object({type:q.literal("source"),sourceType:q.literal("document"),id:q.string().describe("The ID of the source"),mediaType:q.string().describe("IANA media type of the document (e.g., application/pdf)"),title:q.string().describe("The title of the document"),filename:q.string().optional().describe("Optional filename of the document"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")})]),$l6=q.object({role:q.literal("system"),content:q.string().describe("System message content"),providerOptions:OF}),Fl6=q.object({role:q.literal("user"),content:q.array(q.union([rc0,oc0])).describe("User message content parts (text or file)"),providerOptions:OF}),Vl6=q.object({role:q.literal("assistant"),content:q.array(q.union([rc0,oc0,Xl6,Gl6,sc0])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:OF}),ql6=q.object({role:q.literal("tool"),content:q.array(sc0).describe("Tool message content (tool results)"),providerOptions:OF}),Bl6=q.union([$l6,Fl6,Vl6,ql6]),Ul6=q.array(Bl6).describe("A list of messages forming the prompt"),Dl6=q.object({prompt:Ul6.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:q.number().optional().describe("Maximum number of tokens to generate"),temperature:q.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:q.number().optional().describe("Nucleus sampling parameter"),topK:q.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:q.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:q.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:q.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:q.array(q.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:q.union([q.object({type:q.literal("text")}),q.object({type:q.literal("json"),schema:q.any().optional().describe("JSON schema that the generated output should conform to"),name:q.string().optional().describe("Name of output that should be generated"),description:q.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:q.array(q.any()).optional().describe("The tools that are available for the model"),toolChoice:q.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:q.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:q.any().optional().describe("Abort signal for cancelling the operation"),providerOptions:q.any().optional().describe("Additional provider-specific options")}),zl6=q.object({content:q.array(q.union([em6,Ql6,Jl6,Wl6,Kl6,Hl6])).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:q.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:q.looseObject({inputTokens:q.number().optional(),outputTokens:q.number().optional(),totalTokens:q.number().optional(),reasoningTokens:q.number().optional()}).describe("Usage information for the language model call"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata"),request:q.object({body:q.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:q.object({id:q.string().optional().describe("ID for the generated response"),timestamp:q.iso.datetime().optional().describe("Timestamp for the start of the generated response"),modelId:q.string().optional().describe("The ID of the response model that was used"),headers:q.record(q.string(),q.string()).optional().describe("Response headers"),body:q.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:q.array(q.any()).describe("Warnings for the call, e.g. unsupported settings")}),RV9=q.object({stream:q.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:q.object({body:q.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:q.object({headers:q.record(q.string(),q.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),Ol6=q.object({supportedUrls:q.record(q.string(),q.array(q.string())).describe("Supported URL patterns by media type for the provider")}),IV9=q.object({modelId:q.string().describe("The ID of the model"),logo:q.string().nullable(),description:q.string().nullable(),capabilities:q.array(q.string()),limits:q.object({contextWindow:q.number(),maxOutputTokens:q.number()}).nullable(),costs:q.object({input:q.number(),output:q.number()}).nullable(),provider:q.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),ac0=q.object({modelId:q.string().describe("The ID of the model"),callOptions:Dl6}),Nl6=pH.extend({logo:q.string().nullable(),description:q.string().nullable(),capabilities:q.array(q.string()),limits:q.object({contextWindow:q.number(),maxOutputTokens:q.number()}).nullable(),costs:q.object({input:q.number(),output:q.number()}).nullable(),provider:q.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),Ll6=cH("llm",Nl6,{readOnly:!0}),TO1=[{name:"LLM_METADATA",inputSchema:q.object({modelId:q.string().describe("The ID of the model")}),outputSchema:Ol6},{name:"LLM_DO_STREAM",inputSchema:ac0,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:ac0,outputSchema:zl6},...Ll6],Nv=lH(TO1)});function LP(){return!1}function Pr(Y,Q){return Y===IY.DEV_ASSETS(Q)}function MP(Y,Q){let X=W91(Q,Y),J=new Date().toISOString();return{id:X.id??IY.DEV_ASSETS(Y),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:Y,created_by:"system",created_at:J,updated_at:J,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:Ml6,bindings:["OBJECT_STORAGE"],status:"active"}}var Ml6;var Er=j(()=>{Wi();QY();n1();Ml6=tS.map((Y)=>({name:Y.name,description:`${Y.name} operation for local file storage`,inputSchema:q.toJSONSchema(Y.inputSchema),outputSchema:q.toJSONSchema(Y.outputSchema)}))});function Al6(Y){let Q=[],X=0;while(X<Y.length){let J=Y[X];if(J==="%")Q.push(".*");else if(J==="_")Q.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))Q.push("\\"+J);else Q.push(J);X++}return Q.join("")}function BB(Y){return typeof Y==="string"||typeof Y==="number"}function Tr(Y,Q){if("conditions"in Q){let{operator:Z,conditions:H}=Q;switch(Z){case"and":return H.every(($)=>Tr(Y,$));case"or":return H.some(($)=>Tr(Y,$));case"not":return!H.every(($)=>Tr(Y,$));default:return!0}}let{field:X,operator:J,value:G}=Q,K=X.join("."),W=CO1(Y,K);switch(J){case"eq":return W===G;case"gt":return BB(W)&&BB(G)&&W>G;case"gte":return BB(W)&&BB(G)&&W>=G;case"lt":return BB(W)&&BB(G)&&W<G;case"lte":return BB(W)&&BB(G)&&W<=G;case"in":return Array.isArray(G)&&G.includes(W);case"like":if(typeof W!=="string"||typeof G!=="string")return!1;if(G.length>100)return!1;let Z=Al6(G);return new RegExp(`^${Z}$`,"i").test(W);case"contains":if(typeof W!=="string"||typeof G!=="string")return!1;return W.toLowerCase().includes(G.toLowerCase());default:return!0}}function CO1(Y,Q){let X=Q.split("."),J=Y;for(let G of X){if(J==null||typeof J!=="object")return;J=J[G]}return J}function Pl6(Y,Q){return[...Y].sort((X,J)=>{for(let G of Q){let K=G.field.join("."),W=CO1(X,K),Z=CO1(J,K),H=0;if(W==null&&Z==null)continue;if(W==null)H=G.nulls==="first"?-1:1;else if(Z==null)H=G.nulls==="first"?1:-1;else if(typeof W==="string"&&typeof Z==="string")H=W.localeCompare(Z);else if(typeof W==="number"&&typeof Z==="number")H=W-Z;else H=String(W).localeCompare(String(Z));if(H!==0)return G.direction==="desc"?-H:H}return 0})}var wl6,El6,Tl6,RO1;var tc0=j(()=>{Yk();ic0();MG();Ar();Wi();QY();n1();F4();Er();p$();wl6={LLM:TO1,ASSISTANTS:nc0,OBJECT_STORAGE:tS};El6=lZ.extend({binding:q.union([q.object({}).passthrough(),q.string()]).optional(),include_virtual:q.boolean().optional().describe("Whether to include VIRTUAL connections in the results. Defaults to false.")}),Tl6=n$(Y5),RO1=t1({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:El6,outputSchema:Tl6,handler:async(Y,Q)=>{await Q.access.check();let X=v0(Q),J=Y.binding?typeof Y.binding==="string"?(()=>{let B=wl6[Y.binding.toUpperCase()];if(!B)throw Error(`Unknown binding: ${Y.binding}`);return B})():Y.binding:void 0,G=J?Qi(J):void 0,K=await Q.storage.connections.list(X.id,{includeVirtual:Y.include_virtual??!1});if(LP()){let B=X7(),U=IY.DEV_ASSETS(X.id);if(!K.some((D)=>D.id===U)){let D=MP(X.id,B);K.unshift(D)}}let W=G?await Promise.all(K.map(async(B)=>{if(!B.tools||B.tools.length===0)return null;return G.isImplementedBy(B.tools.map((D)=>({name:D.name,inputSchema:D.inputSchema,outputSchema:D.outputSchema})))?B:null})).then((B)=>B.filter((U)=>U!==null)):K;if(Y.where)W=W.filter((B)=>Tr(B,Y.where));if(Y.orderBy&&Y.orderBy.length>0)W=Pl6(W,Y.orderBy);let Z=W.length,H=Y.offset??0,$=Y.limit??100,F=W.slice(H,H+$),V=H+$<Z;return{items:F,totalCount:Z,hasMore:V}}})});var Cl6,IO1;var ec0=j(()=>{MG();F4();Er();p$();Cl6=hS(Y5),IO1=t1({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",annotations:{title:"Get Connection",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:bS,outputSchema:Cl6,handler:async(Y,Q)=>{let X=v0(Q);if(await Q.access.check(),LP()&&Pr(Y.id,X.id))return{item:MP(X.id,X7())};let J=await Q.storage.connections.findById(Y.id);if(!J||J.organization_id!==X.id)return{item:null};return{item:J}}})});var Cr=(Y,Q)=>{if(Q===null||Q===void 0)return;let X=Y.replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),J=Q;for(let G of X){if(J===null||J===void 0||typeof J!=="object")return;J=J[G]}return J};function Yn0(Y){let Q=Y.split("::");if(Q.length!==2||!Q[0]||!Q[1])throw Error(`Invalid scope format: ${Y}. Expected format: "KEY::SCOPE"`);return Q}function Rl6(Y){let Q=Y.split("::");if(Q.length!==2||!Q[0]||!Q[1])return null;return Q}function Il6(Y){if(typeof Y==="object"&&Y!==null&&"value"in Y){let Q=Y.value;if(typeof Q==="string")return Q}return null}function jO1(Y,Q){let X={};if(!Y||!Q)return X;for(let J of Q){if(J==="*"){X["*"]=["*"];continue}let G=Rl6(J);if(!G)continue;let[K,W]=G,Z=Cr(K,Y),H=Il6(Z);if(H){if(!X[H])X[H]=[];X[H].push(W)}}return X}function Qn0(Y,Q){let X=jO1(Y,Q);return new Set(Object.keys(X).filter((J)=>J!=="*"))}var SO1=()=>{};import{randomBytes as jl6}from"crypto";function Xn0(){if(Lv)return Lv;let Y=process.env.MESH_JWT_SECRET??p9.jwt?.secret??process.env.BETTER_AUTH_SECRET;if(Y)Lv=new TextEncoder().encode(Y);else console.warn("MESH_JWT_SECRET not set - generating random secret (not persistent)"),Lv=new Uint8Array(jl6(32));return Lv}async function Jn0(Y,Q="5m"){let X=Xn0();return await new s5(Y).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(Q).sign(X)}async function Gn0(Y){try{let Q=Xn0(),{payload:X}=await JY(Y,Q);return X}catch{return}}var Lv=null;var kO1=j(()=>{t5();wP()});async function Wn0(Y){if(!Y.refreshToken)return{success:!1,error:"No refresh token available"};if(!Y.tokenEndpoint)return{success:!1,error:"No token endpoint available"};if(!Y.clientId)return{success:!1,error:"No client ID available"};try{let Q=new URLSearchParams({grant_type:"refresh_token",refresh_token:Y.refreshToken,client_id:Y.clientId});if(Y.clientSecret)Q.set("client_secret",Y.clientSecret);if(Y.scope)Q.set("scope",Y.scope);let X=await fetch(Y.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Q.toString()});if(!X.ok){let G=await X.text();console.error(`[TokenRefresh] Failed to refresh token: ${X.status}`,G);try{let K=JSON.parse(G);return{success:!1,error:K.error_description||K.error||`Token refresh failed: ${X.status}`}}catch{return{success:!1,error:`Token refresh failed: ${X.status}`}}}let J=await X.json();return{success:!0,accessToken:J.access_token,refreshToken:J.refresh_token||Y.refreshToken,expiresIn:J.expires_in,scope:J.scope}}catch(Q){return console.error("[TokenRefresh] Error refreshing token:",Q),{success:!1,error:Q instanceof Error?Q.message:"Token refresh failed"}}}class NF{db;vault;constructor(Y,Q){this.db=Y;this.vault=Q}async get(Y){let Q=await this.db.selectFrom("downstream_tokens").selectAll().where("connectionId","=",Y).executeTakeFirst();if(!Q)return null;return this.decryptToken(Q)}async upsert(Y){let Q=new Date().toISOString(),X=await this.vault.encrypt(Y.accessToken),J=Y.refreshToken?await this.vault.encrypt(Y.refreshToken):null,G=Y.clientSecret?await this.vault.encrypt(Y.clientSecret):null;return await this.db.transaction().execute(async(K)=>{let W=await K.selectFrom("downstream_tokens").select(["id","createdAt"]).where("connectionId","=",Y.connectionId).executeTakeFirst();if(W)return await K.updateTable("downstream_tokens").set({accessToken:X,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,updatedAt:Q}).where("id","=",W.id).execute(),{id:W.id,connectionId:Y.connectionId,accessToken:Y.accessToken,refreshToken:Y.refreshToken,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:W.createdAt,updatedAt:Q,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint};let Z=J9("dtok");return await K.insertInto("downstream_tokens").values({id:Z,connectionId:Y.connectionId,accessToken:X,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,createdAt:Q,updatedAt:Q}).execute(),{id:Z,connectionId:Y.connectionId,accessToken:Y.accessToken,refreshToken:Y.refreshToken,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:Q,updatedAt:Q,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint}})}async delete(Y){await this.db.deleteFrom("downstream_tokens").where("connectionId","=",Y).execute()}isExpired(Y,Q=0){if(!Y.expiresAt)return!1;let J=(Y.expiresAt instanceof Date?Y.expiresAt:new Date(Y.expiresAt)).getTime();if(Number.isNaN(J))return!0;return J-Q<Date.now()}async decryptToken(Y){let Q=await this.vault.decrypt(Y.accessToken),X=Y.refreshToken?await this.vault.decrypt(Y.refreshToken):null,J=Y.clientSecret?await this.vault.decrypt(Y.clientSecret):null;return{id:Y.id,connectionId:Y.connectionId,accessToken:Q,refreshToken:X,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:Y.createdAt,updatedAt:Y.updatedAt,clientId:Y.clientId,clientSecret:J,tokenEndpoint:Y.tokenEndpoint}}}var Rr=j(()=>{F7()});async function Mv(Y,Q,X){let J=Y.id,G=jO1(Y.configuration_state,Y.configuration_scopes),K=Q.auth.user?.id??Q.auth.apiKey?.userId??(X?Y.created_by:void 0),[W,Z]=K?await Jn0({sub:K,user:{id:K},metadata:{state:Y.configuration_state??void 0,meshUrl:Q.baseUrl,connectionId:J,organizationId:Q.organization?.id},permissions:G}).then((U)=>[U,null]).catch((U)=>[null,U]):[null,Error("User ID required to issue configuration token")];if(Z)console.error("Failed to issue configuration token:",W);let H=Q.auth.user?.connectionId,$={...H?{"x-caller-id":H}:{},...Q.metadata.wellKnownForwardableHeaders??{},"x-request-id":Q.metadata.requestId},F=null,V=new NF(Q.db,Q.vault),B=await V.get(J);if(B){let U=!!B.refreshToken&&!!B.tokenEndpoint;if(V.isExpired(B,U?300000:0))if(U){console.log(`[Proxy] Token expired for ${J}, attempting refresh`);let z=await Wn0(B);if(z.success&&z.accessToken)await V.upsert({connectionId:J,accessToken:z.accessToken,refreshToken:z.refreshToken??B.refreshToken,scope:z.scope??B.scope,expiresAt:z.expiresIn?new Date(Date.now()+z.expiresIn*1000):null,clientId:B.clientId,clientSecret:B.clientSecret,tokenEndpoint:B.tokenEndpoint}),F=z.accessToken,console.log(`[Proxy] Token refreshed for ${J}`);else await V.delete(J),console.error(`[Proxy] Token refresh failed for ${J}: ${z.error}`)}else await V.delete(J),console.log(`[Proxy] Token expired without refresh capability for ${J}`);else F=B.accessToken}if(!F&&Y.connection_token)F=Y.connection_token;if(F)$.Authorization=`Bearer ${F}`;if(W)$["x-mesh-token"]=W;return $}var vO1=j(()=>{SO1();kO1();Rr()});function Ir(){let Y=new Map;function Q(J,G){let K=Y.get(G);if(K)return console.log(`[ClientPool] Reusing cached client for ${G}`),K;console.log(`[ClientPool] Creating new client for ${G}`);let W=new eJ({name:`outbound-client-${G}`,version:"1.0.0"},{capabilities:{tasks:{list:{},cancel:{},requests:{tool:{call:{}}}}}});W.onclose=()=>{Y.delete(G)};let Z=W.connect(J,{timeout:30000}).then(()=>W).catch((H)=>{throw Y.delete(G),H});return Y.set(G,Z),Z}return Object.assign(Q,{[Symbol.asyncDispose]:async()=>{let J=[];for(let[G,K]of Y)J.push(K.then((W)=>W.close()).catch((W)=>console.error(`[ClientPool] Error closing client ${G}:`,W)));await Promise.all(J),Y.clear()}})}var _O1=j(()=>{LU()});function Zn0(Y){let Q=new _S({command:Y.command,args:Y.args,env:Y.env,cwd:Y.cwd,stderr:"pipe"}),X=Y.name||Y.id,J="\x1B[2m",G="\x1B[0m";return Q.stderr?.on("data",(K)=>{let W=K.toString().trimEnd();if(W)console.error(`${W} \x1B[2m[${X}]\x1B[0m`)}),Q}var Kn0=j(()=>{dq1()});class wv{innerTransport;constructor(Y){this.innerTransport=Y}async start(){return this.innerTransport.onmessage=(Y)=>{this.handleIncomingMessage(Y)},this.innerTransport.onerror=(Y)=>{this.onerror?.(Y)},this.innerTransport.onclose=()=>{this.onclose?.()},this.innerTransport.start()}async send(Y){return this.handleOutgoingMessage(Y)}async close(){return this.innerTransport.close()}async handleOutgoingMessage(Y){return this.innerTransport.send(Y)}handleIncomingMessage(Y){this.onmessage?.(Y)}isRequest(Y){return"method"in Y&&Y.method!==void 0}isResponse(Y){return"result"in Y||"error"in Y&&!("method"in Y)}onmessage;onerror;onclose}function Av(Y,...Q){return Q.reduce((X,J)=>J(X),Y)}var Hn0="mcp.mesh";var $n0,yO1,LF;var Pv=j(()=>{$n0=class $n0 extends Error{constructor(Y){super(Y);this.name="UnauthorizedError"}};yO1=class yO1 extends Error{constructor(Y){super(Y);this.name="ForbiddenError"}};LF=class LF{userId;toolName;boundAuth;role;connectionId;getToolMeta;_granted=!1;constructor(Y,Q,X,J,G,K="self",W){this.userId=Q;this.toolName=X;this.boundAuth=J;this.role=G;this.connectionId=K;this.getToolMeta=W}[Symbol.dispose](){this._granted=!1}setToolName(Y){this.toolName=Y}grant(){return this._granted=!0,{[Symbol.dispose]:()=>{this._granted=!1}}}async check(...Y){if(this._granted)return;if(this.toolName?.startsWith("MESH_PUBLIC_")){this.grant();return}if(!this.userId&&!this.boundAuth){if(this.getToolMeta&&await this.isToolPublic()){this.grant();return}throw new $n0("Authentication required. Please provide a valid OAuth token or API key.")}let Q=Y.length>0?Y:this.toolName?[this.toolName]:[];if(Q.length===0)throw new yO1("No resources specified for access check");for(let X of Q)if(await this.checkResource(X)){this.grant();return}throw new yO1(`Access denied to: ${Q.join(", ")}`)}async checkResource(Y){if(!this.userId&&!this.boundAuth)return!1;if(this.role==="admin"||this.role==="owner")return!0;if(!this.boundAuth)return!1;let Q={};if(this.connectionId)Q[this.connectionId]=[Y];return this.boundAuth.hasPermission(Q)}async isToolPublic(){if(this.toolName?.startsWith("MESH_PUBLIC_"))return!0;if(!this.getToolMeta)return!1;try{let Y=await this.getToolMeta();if(!Y)return!1;let X=Y[Hn0]?.public_tool;return X===!0||X==="true"}catch{return!1}}granted(){return this._granted}}});var Sl6="mcp.mesh",AP;var Fn0=j(()=>{Pv();AP=class AP extends wv{options;cachedToolsMap=null;constructor(Y,Q){super(Y);this.options=Q;if(Q.connection.tools)this.cachedToolsMap=new Map(Q.connection.tools.map((X)=>[X.name,X]))}async handleOutgoingMessage(Y){if(!this.isRequest(Y))return this.innerTransport.send(Y);let Q=Y;if(Q.method==="tools/call")await this.authorizeToolCall(Q),this.stripMetaFromArguments(Q);return this.innerTransport.send(Y)}async authorizeToolCall(Y){if(this.options.superUser)return;let X=Y.params.name,{ctx:J,connection:G}=this.options;if(this.isPublicTool(X))return;if(!J.auth.user?.id&&!J.auth.apiKey?.id)throw Error("Authentication required. Please provide a valid OAuth token or API key.");let K=async()=>{return this.cachedToolsMap?.get(X)?._meta};await new LF(J.authInstance,J.auth.user?.id??J.auth.apiKey?.userId,X,J.boundAuth,J.auth.user?.role,G.id,K).check(X)}isPublicTool(Y){if(Y.startsWith("MESH_PUBLIC_"))return!0;if(!this.cachedToolsMap)return!1;let Q=this.cachedToolsMap.get(Y);if(!Q?._meta)return!1;return Q._meta[Sl6]?.public_tool===!0}stripMetaFromArguments(Y){let Q=Y.params;if(Q.arguments&&"_meta"in Q.arguments){let{_meta:X,...J}=Q.arguments;Q.arguments=J}}}});function qn0(Y){if(!Y.isError)return;let Q=Y.content;if(!Array.isArray(Q))return;for(let X of Q)if(X&&typeof X==="object"&&"type"in X&&X.type==="text"&&"text"in X&&typeof X.text==="string")return X.text;return}function bO1(Y){if(!Y)return;let Q=Y._meta;if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let X=Q.properties;if(!X||typeof X!=="object"||Array.isArray(X))return;let J={};for(let[G,K]of Object.entries(X))if(typeof K==="string")J[G]=K;return Object.keys(J).length>0?J:void 0}function hO1(Y,Q){if(!Y&&!Q)return;if(!Y)return Q;if(!Q)return Y;return{...Q,...Y}}function xO1(Y){if(Y&&typeof Y==="object"&&!Array.isArray(Y)){let Q=Y,X=Q.structuredContent;if(X&&typeof X==="object"&&!Array.isArray(X))return X;return Q}return{value:Y}}async function kl6(Y,Q){let X=Y.body;if(!X)return{text:"",truncated:!1};let J=X.getReader(),G=new TextDecoder,K=!1,W=0,Z=[];try{while(!0){let{value:H,done:$}=await J.read();if($)break;if(H){if(W+=H.byteLength,W>Q){K=!0;let F=Q-(W-H.byteLength);if(F>0)Z.push(G.decode(H.slice(0,F),{stream:!0}));break}Z.push(G.decode(H,{stream:!0}))}}}finally{J.releaseLock()}return Z.push(G.decode()),{text:Z.join(""),truncated:K}}function vl6(Y){if(!Y)return;let Q=Y.trimEnd().split(`
1472
+ ${Q.stack}`;return G}}catch{}if(typeof Q.toString==="function")try{let G=Q.toString();if(G!=="[object Object]")return G}catch{}let J=Object.keys(Q);if(J.length>0)return`Object with keys: ${J.join(", ")}`;return"[object Object]"}if(typeof Y==="string")return Y;if(typeof Y==="number"||typeof Y==="boolean")return String(Y);if(typeof Y==="function")return`[Function: ${Y.name||"anon"}]`;if(typeof Y==="symbol")return Y.toString();if(typeof Y==="bigint")return Y.toString();try{return String(Y)}catch{return"Unknown value (could not convert to string)"}}function BO(Y,Q){switch(typeof Q){case"string":return Y.newString(Q);case"number":return Y.newNumber(Q);case"boolean":return Q?Y.true:Y.false;case"undefined":return Y.undefined;case"object":{if(Q===null)return Y.null;if(Array.isArray(Q)){let J=Y.newArray();return Q.forEach((G,K)=>{let W=BO(Y,G);try{Y.setProp(J,String(K),W)}finally{W.dispose?.()}}),J}let X=Y.newObject();for(let[J,G]of Object.entries(Q)){let K=BO(Y,G);try{Y.setProp(X,J,K)}finally{K.dispose?.()}}return X}case"function":{let X=`__hostFn_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return Y.newFunction(X,(...G)=>{try{let K=G.map((Z)=>Y.dump(Z)),W=Q(...K);if(W&&typeof W.then==="function"){let Z=Y.newPromise();return W.then((H)=>{try{let $=BO(Y,H);Z.resolve($),$.dispose()}catch($){let F=qO($),V=Y.newString(`Promise resolution error: ${F}`);Z.reject(V),V.dispose()}finally{Y.runtime.executePendingJobs()}}).catch((H)=>{let $=qO(H),F=Y.newString(`Promise rejection: ${$}`);Z.reject(F),F.dispose(),Y.runtime.executePendingJobs()}),Z.handle}return BO(Y,W)}catch(K){let W=qO(K);return Y.newString(`HostFunctionError: ${W}`)}finally{G.forEach((K)=>K.dispose())}})}case"bigint":return Y.newString(Q.toString());case"symbol":return Y.newString(Q.toString());default:try{return Y.newString(String(Q))}catch{return Y.undefined}}}var xc0=()=>{};function LO1(Y){let Q=Y.runtime.executePendingJobs(100);try{if("unwrap"in Q&&typeof Q.unwrap==="function")Q.unwrap()}finally{if("dispose"in Q&&typeof Q.dispose==="function")Q.dispose()}}async function Or(Y,Q,X){let J=Date.now(),G=Y.resolvePromise(Q);while(!0){LO1(Y);let K=await Promise.race([G,lm6(0).then(()=>null)]);if(K!==null)return K;if(Date.now()-J>X)throw Error(`Timed out after ${X}ms while awaiting a QuickJS promise`)}}async function Dv({tools:Y,code:Q,timeoutMs:X}){let W=[];try{const J=kB(W,await NO1({memoryLimitBytes:33554432,stackSizeBytes:524288}),0);const G=kB(W,J.newContext({interruptAfterMs:X}),0);const K=kB(W,OO1(G),0);try{let F=G.evalCode(Q,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult(F),B=BO(G,Y);G.setProp(G.global,"tools",B);let U=G.runtime.hasPendingJob()?G.unwrapResult(await Or(G,V,X)):V;if(U!==V)V.dispose();let D=G.getProp(U,"default"),z=G.typeof(D);if(z!=="function")return D.dispose(),U.dispose(),B.dispose(),{error:`Code must export default a function (tools). Got ${z}. Example: export default async (tools) => { /* ... */ }`,consoleLogs:K.logs};let L=G.callFunction(D,G.undefined,B);B.dispose(),D.dispose(),U.dispose();let w=G.unwrapResult(L),E=await Or(G,w,X);w.dispose();let T=G.unwrapResult(E);if(G.runtime.hasPendingJob())LO1(G);let C=G.dump(T);return T.dispose(),{returnValue:C,consoleLogs:K.logs}}catch(F){return console.log(F),{error:qO(F),consoleLogs:K.logs}}}catch(Z){var H=Z,$=1}finally{Ls(W,H,$)}}async function MO1({input:Y,code:Q,timeoutMs:X}){let W=[];try{const J=kB(W,await NO1({memoryLimitBytes:33554432,stackSizeBytes:524288}),0);const G=kB(W,J.newContext({interruptAfterMs:X}),0);const K=kB(W,OO1(G),0);try{let F=G.evalCode(Q,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult(F),B=BO(G,Y);G.setProp(G.global,"input",B);let U=G.runtime.hasPendingJob()?G.unwrapResult(await Or(G,V,X)):V;if(U!==V)V.dispose();let D=G.getProp(U,"default"),z=G.typeof(D);if(z!=="function")return D.dispose(),U.dispose(),B.dispose(),{error:`Code must export default a function (input). Got ${z}. Example: export default (input) => { return input.items.map(i => i.name); }`,consoleLogs:K.logs};let L=G.callFunction(D,G.undefined,B);B.dispose(),D.dispose(),U.dispose();let w=G.unwrapResult(L),E=await Or(G,w,X);w.dispose();let T=G.unwrapResult(E);if(G.runtime.hasPendingJob())LO1(G);let C=G.dump(T);return T.dispose(),{returnValue:C,consoleLogs:K.logs}}catch(F){return console.log(F),{error:qO(F),consoleLogs:K.logs}}}catch(Z){var H=Z,$=1}finally{Ls(W,H,$)}}var lm6=(Y)=>new Promise((Q)=>setTimeout(Q,Y));var gc0=j(()=>{hc0();xc0()});var Nr=j(()=>{gc0()});async function dm6(Y,Q){let X=Y.connections.map((K)=>K.connection_id),J=[];for(let K of X){let W=await Q.storage.connections.findById(K);if(W&&W.status==="active")J.push(W)}return J.map((K)=>{let W=Y.connections.find((Z)=>Z.connection_id===K.id);return{connection:K,selectedTools:W?.selected_tools??null,selectedResources:W?.selected_resources??null,selectedPrompts:W?.selected_prompts??null}})}async function uc0(Y,Q){return(await Q.storage.connections.list(Y)).filter((J)=>J.status==="active").map((J)=>({connection:J,selectedTools:null,selectedResources:null,selectedPrompts:null}))}async function pm6(Y,Q){let X=new Map;for(let B of Y)X.set(B.connection.id,B);let J=Y.map((B)=>B.connection),G=new Map,K=await Promise.allSettled(J.map(async(B)=>{try{let U=await Q.createMCPProxy(B);return{connection:B,proxy:U}}catch(U){return console.warn(`[code-execution] Failed to create proxy for connection ${B.id}:`,U),null}}));for(let B of K)if(B.status==="fulfilled"&&B.value)G.set(B.value.connection.id,B.value);let W=await Promise.allSettled(Array.from(G.entries()).map(async([B,U])=>{try{let z=(await U.proxy.listTools()).tools,L=X.get(B);if(L?.selectedTools&&L.selectedTools.length>0){let w=new Set(L.selectedTools);z=z.filter((E)=>w.has(E.name))}return{connectionId:B,connectionTitle:U.connection.title,tools:z}}catch(D){return console.error(`[code-execution] Failed to list tools for connection ${B}:`,D),null}})),Z=new Set,H=[],$=new Map;for(let B of W){if(B.status!=="fulfilled"||!B.value)continue;let{connectionId:U,connectionTitle:D,tools:z}=B.value;for(let L of z){if(Z.has(L.name))continue;Z.add(L.name),H.push({...L,_meta:{...L._meta,connectionId:U,connectionTitle:D}}),$.set(L.name,U)}}let F=async(B,U)=>{let D=$.get(B);if(!D)return{content:[{type:"text",text:`Tool not found: ${B}`}],isError:!0};let z=G.get(D);if(!z)return{content:[{type:"text",text:`Connection not found for tool: ${B}`}],isError:!0};return await z.proxy.callTool({name:B,arguments:U})},V=[];for(let[,B]of G)V.push(B.proxy.close().catch(()=>{}));return await Promise.all(V),{tools:H,callTool:F}}async function NP(Y){let Q=v0(Y),X;if(Y.connectionId){let J=await Y.storage.virtualMcps.findById(Y.connectionId,Y.organization?.id);if(J)X=await dm6(J,Y);else X=await uc0(Q.id,Y)}else X=await uc0(Q.id,Y);return pm6(X,Y)}function cm6(Y){return Y.toLowerCase().split(/[\s_\-./]+/).filter((Q)=>Q.length>=2)}function nm6(Y,Q){let X=0,J=Q.name.toLowerCase(),G=(Q.description??"").toLowerCase(),K=(Q._meta?.connectionTitle??"").toLowerCase();for(let W of Y){if(J===W)X+=10;else if(J.includes(W))X+=3;if(G.includes(W))X+=2;if(K.includes(W))X+=1}return X}function Lr(Y,Q,X){let J=cm6(Y);if(J.length===0)return Q.slice(0,X);return Q.map((G)=>({tool:G,score:nm6(J,G)})).filter((G)=>G.score>0).sort((G,K)=>K.score-G.score).slice(0,X).map((G)=>G.tool)}function Mr(Y,Q){let X=new Map(Q.map((G)=>[G.name,G]));return{tools:Y.map((G)=>X.get(G)).filter((G)=>G!==void 0).map((G)=>({name:G.name,description:G.description,connection:G._meta?.connectionTitle??"",inputSchema:G.inputSchema,outputSchema:G.outputSchema})),notFound:Y.filter((G)=>!X.has(G))}}async function wr(Y,Q,X){let J=Object.fromEntries(Q.tools.map((G)=>[G.name,async(K)=>{let W=await Q.callTool(G.name,K??{});if(W.structuredContent&&typeof W.structuredContent==="object")return W.structuredContent;let Z=W.content;if(Z?.[0]?.type==="text"&&Z[0].text)try{return JSON.parse(Z[0].text)}catch{return Z[0].text}return W}]));return Dv({code:Y,tools:J,timeoutMs:X})}function zv(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}]}}function qB(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}],isError:!0}}function zF(Y){let Q=new Set(im6);return Y.filter((X)=>!Q.has(X.name))}var im6;var UO=j(()=>{Nr();im6=["CODE_EXECUTION_SEARCH_TOOLS","CODE_EXECUTION_DESCRIBE_TOOLS","CODE_EXECUTION_RUN_CODE"]});var wO1;var mc0=j(()=>{F4();Uv();UO();wO1=t1({name:"CODE_EXECUTION_SEARCH_TOOLS",description:"Search for available tools by name or description. Returns tool names and brief descriptions without full schemas. Use this to discover tools before calling CODE_EXECUTION_DESCRIBE_TOOLS for detailed schemas.",annotations:{title:"Search Tools",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:Ic0,outputSchema:jc0,handler:async(Y,Q)=>{D0(Q),v0(Q),await Q.access.check();let X=await NP(Q),J=Lr(Y.query,X.tools,Y.limit);return{query:Y.query,results:J.map((G)=>({name:G.name,description:G.description,connection:G._meta?.connectionTitle??""})),totalAvailable:X.tools.length}}})});var AO1;var lc0=j(()=>{F4();Uv();UO();AO1=t1({name:"CODE_EXECUTION_DESCRIBE_TOOLS",description:"Get detailed schemas for specific tools. Call after CODE_EXECUTION_SEARCH_TOOLS to get full input/output schemas before executing code.",annotations:{title:"Describe Tools",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:Sc0,outputSchema:kc0,handler:async(Y,Q)=>{D0(Q),v0(Q),await Q.access.check();let X=await NP(Q);return Mr(Y.tools,X.tools)}})});var PO1;var dc0=j(()=>{F4();Uv();UO();PO1=t1({name:"CODE_EXECUTION_RUN_CODE",description:'Run JavaScript code in a sandbox. Code must be an ES module that `export default`s an async function that receives (tools) as its first parameter. Use CODE_EXECUTION_DESCRIBE_TOOLS to understand the input/output schemas for a tool before calling it. Use `await tools.toolName(args)` or `await tools["tool-name"](args)` to call tools.',annotations:{title:"Run Code",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},inputSchema:vc0,outputSchema:_c0,handler:async(Y,Q)=>{D0(Q),v0(Q),await Q.access.check();let X=await NP(Q);return await wr(Y.code,X,Y.timeoutMs)}})});var pc0=j(()=>{mc0();lc0();dc0();Uv()});var rm6,om6,EO1;var cc0=j(()=>{QY();n1();F4();rn();p$();rm6=q.object({data:_T.describe("Data for the new connection (id is auto-generated if not provided)")}),om6=q.object({item:Y5.describe("The created connection entity")}),EO1=t1({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",annotations:{title:"Create Connection",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:rm6,outputSchema:om6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=TY(Q);if(!J)throw Error("User ID required to create connection");let G={...Y.data,organization_id:X.id,created_by:J};if(G.connection_type==="VIRTUAL"){let $=AU(G.connection_url);if(!$)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let F=await Q.storage.virtualMcps.findById($);if(!F)throw Error(`Virtual MCP not found: ${$}`);if(F.organization_id!==X.id)throw Error("Virtual MCP does not belong to the current organization");G.connection_url=PU($)}let K=await EA({id:`pending-${Date.now()}`,title:G.title,connection_type:G.connection_type,connection_url:G.connection_url,connection_token:G.connection_token,connection_headers:G.connection_headers}).catch(()=>null),W=K?.tools?.length?K.tools:null,Z=K?.scopes?.length?K.scopes:null,H=await Q.storage.connections.create({...G,tools:W,configuration_scopes:Z});return await Q.eventBus.publish(X.id,IY.SELF(X.id),{type:"connection.created",data:H}),{item:H}}})});var sm6,tm6,nc0;var ic0=j(()=>{n1();MG();sm6=pH.extend({avatar:q.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:q.string().describe("System prompt that defines the assistant's behavior"),virtual_mcp_id:q.string().describe("Virtual MCP ID to use for this assistant"),model:q.object({id:q.string().describe("Model ID"),connectionId:q.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),tm6=cH("assistant",sm6),nc0=[...tm6]});var Ov,OF,rc0,em6,Yl6,oc0,Ql6,Xl6,Jl6,Gl6,Wl6,Zl6,sc0,Kl6,Hl6,$l6,Fl6,Vl6,ql6,Bl6,Ul6,Dl6,zl6,RV9,Ol6,IV9,ac0,Nl6,Ll6,TO1,Nv;var Ar=j(()=>{n1();xz();MG();Ov=q.lazy(()=>q.union([q.null(),q.string(),q.number(),q.boolean(),q.record(q.string(),Ov),q.array(Ov)])),OF=q.record(q.string(),q.record(q.string(),Ov)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),rc0=q.object({type:q.literal("text"),text:q.string().describe("The text content"),providerOptions:OF}),em6=q.object({type:q.literal("text"),text:q.string().describe("The text content"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),Yl6=q.string().describe("File data as URL string"),oc0=q.object({type:q.literal("file"),filename:q.string().optional().describe("Optional filename of the file"),data:Yl6,mediaType:q.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:OF}),Ql6=q.object({type:q.literal("file"),mediaType:q.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),data:q.string().describe("Generated file data as base64 encoded string")}),Xl6=q.object({type:q.literal("reasoning"),text:q.string().describe("The reasoning text"),providerOptions:OF}),Jl6=q.object({type:q.literal("reasoning"),text:q.string().describe("The reasoning text"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),Gl6=q.object({type:q.literal("tool-call"),toolCallId:q.string().describe("ID of the tool call, used to match with tool result"),toolName:q.string().describe("Name of the tool being called"),input:q.string().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:q.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:OF}),Wl6=q.object({type:q.literal("tool-call"),toolCallId:q.string().describe("ID of the tool call"),toolName:q.string().describe("Name of the tool being called"),input:q.string().describe("Stringified JSON object with the tool call arguments"),providerExecuted:q.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),Zl6=q.union([q.object({type:q.literal("text"),value:q.string()}),q.object({type:q.literal("json"),value:Ov}),q.object({type:q.literal("error-text"),value:q.string()}),q.object({type:q.literal("error-json"),value:Ov}),q.object({type:q.literal("content"),value:q.array(q.union([q.object({type:q.literal("text"),text:q.string().describe("Text content")}),q.object({type:q.literal("media"),data:q.string().describe("Base-64 encoded media data"),mediaType:q.string().describe("IANA media type")})]))}),q.object({type:q.literal("execution-denied"),reason:q.string().optional()}),q.string().describe("Raw or JSON-serialized output (e.g. from AI SDK mapToolResultOutput)")]),sc0=q.object({type:q.literal("tool-result"),toolCallId:q.string().describe("ID of the tool call that this result is associated with"),toolName:q.string().describe("Name of the tool that generated this result"),output:Zl6.describe("Result of the tool call"),result:q.unknown().describe("Unknown result of the tool call"),providerOptions:OF}),Kl6=q.object({type:q.literal("tool-result"),toolCallId:q.string().describe("ID of the tool call that this result is associated with"),toolName:q.string().describe("Name of the tool that generated this result"),result:q.any().describe("Result of the tool call (JSON-serializable)"),isError:q.boolean().optional().describe("Whether the result is an error or error message"),providerExecuted:q.boolean().optional().describe("Whether the tool result was generated by the provider"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),Hl6=q.union([q.object({type:q.literal("source"),sourceType:q.literal("url"),id:q.string().describe("The ID of the source"),url:q.string().describe("The URL of the source"),title:q.string().optional().describe("The title of the source"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),q.object({type:q.literal("source"),sourceType:q.literal("document"),id:q.string().describe("The ID of the source"),mediaType:q.string().describe("IANA media type of the document (e.g., application/pdf)"),title:q.string().describe("The title of the document"),filename:q.string().optional().describe("Optional filename of the document"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")})]),$l6=q.object({role:q.literal("system"),content:q.string().describe("System message content"),providerOptions:OF}),Fl6=q.object({role:q.literal("user"),content:q.array(q.union([rc0,oc0])).describe("User message content parts (text or file)"),providerOptions:OF}),Vl6=q.object({role:q.literal("assistant"),content:q.array(q.union([rc0,oc0,Xl6,Gl6,sc0])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:OF}),ql6=q.object({role:q.literal("tool"),content:q.array(sc0).describe("Tool message content (tool results)"),providerOptions:OF}),Bl6=q.union([$l6,Fl6,Vl6,ql6]),Ul6=q.array(Bl6).describe("A list of messages forming the prompt"),Dl6=q.object({prompt:Ul6.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:q.number().optional().describe("Maximum number of tokens to generate"),temperature:q.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:q.number().optional().describe("Nucleus sampling parameter"),topK:q.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:q.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:q.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:q.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:q.array(q.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:q.union([q.object({type:q.literal("text")}),q.object({type:q.literal("json"),schema:q.any().optional().describe("JSON schema that the generated output should conform to"),name:q.string().optional().describe("Name of output that should be generated"),description:q.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:q.array(q.any()).optional().describe("The tools that are available for the model"),toolChoice:q.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:q.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:q.any().optional().describe("Abort signal for cancelling the operation"),providerOptions:q.any().optional().describe("Additional provider-specific options")}),zl6=q.object({content:q.array(q.union([em6,Ql6,Jl6,Wl6,Kl6,Hl6])).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:q.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:q.looseObject({inputTokens:q.number().optional(),outputTokens:q.number().optional(),totalTokens:q.number().optional(),reasoningTokens:q.number().optional()}).describe("Usage information for the language model call"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata"),request:q.object({body:q.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:q.object({id:q.string().optional().describe("ID for the generated response"),timestamp:q.iso.datetime().optional().describe("Timestamp for the start of the generated response"),modelId:q.string().optional().describe("The ID of the response model that was used"),headers:q.record(q.string(),q.string()).optional().describe("Response headers"),body:q.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:q.array(q.any()).describe("Warnings for the call, e.g. unsupported settings")}),RV9=q.object({stream:q.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:q.object({body:q.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:q.object({headers:q.record(q.string(),q.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),Ol6=q.object({supportedUrls:q.record(q.string(),q.array(q.string())).describe("Supported URL patterns by media type for the provider")}),IV9=q.object({modelId:q.string().describe("The ID of the model"),logo:q.string().nullable(),description:q.string().nullable(),capabilities:q.array(q.string()),limits:q.object({contextWindow:q.number(),maxOutputTokens:q.number()}).nullable(),costs:q.object({input:q.number(),output:q.number()}).nullable(),provider:q.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),ac0=q.object({modelId:q.string().describe("The ID of the model"),callOptions:Dl6}),Nl6=pH.extend({logo:q.string().nullable(),description:q.string().nullable(),capabilities:q.array(q.string()),limits:q.object({contextWindow:q.number(),maxOutputTokens:q.number()}).nullable(),costs:q.object({input:q.number(),output:q.number()}).nullable(),provider:q.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),Ll6=cH("llm",Nl6,{readOnly:!0}),TO1=[{name:"LLM_METADATA",inputSchema:q.object({modelId:q.string().describe("The ID of the model")}),outputSchema:Ol6},{name:"LLM_DO_STREAM",inputSchema:ac0,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:ac0,outputSchema:zl6},...Ll6],Nv=lH(TO1)});function LP(){return!1}function Pr(Y,Q){return Y===IY.DEV_ASSETS(Q)}function MP(Y,Q){let X=W91(Q,Y),J=new Date().toISOString();return{id:X.id??IY.DEV_ASSETS(Y),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:Y,created_by:"system",created_at:J,updated_at:J,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:Ml6,bindings:["OBJECT_STORAGE"],status:"active"}}var Ml6;var Er=j(()=>{Wi();QY();n1();Ml6=tS.map((Y)=>({name:Y.name,description:`${Y.name} operation for local file storage`,inputSchema:q.toJSONSchema(Y.inputSchema),outputSchema:q.toJSONSchema(Y.outputSchema)}))});function Al6(Y){let Q=[],X=0;while(X<Y.length){let J=Y[X];if(J==="%")Q.push(".*");else if(J==="_")Q.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))Q.push("\\"+J);else Q.push(J);X++}return Q.join("")}function BB(Y){return typeof Y==="string"||typeof Y==="number"}function Tr(Y,Q){if("conditions"in Q){let{operator:Z,conditions:H}=Q;switch(Z){case"and":return H.every(($)=>Tr(Y,$));case"or":return H.some(($)=>Tr(Y,$));case"not":return!H.every(($)=>Tr(Y,$));default:return!0}}let{field:X,operator:J,value:G}=Q,K=X.join("."),W=CO1(Y,K);switch(J){case"eq":return W===G;case"gt":return BB(W)&&BB(G)&&W>G;case"gte":return BB(W)&&BB(G)&&W>=G;case"lt":return BB(W)&&BB(G)&&W<G;case"lte":return BB(W)&&BB(G)&&W<=G;case"in":return Array.isArray(G)&&G.includes(W);case"like":if(typeof W!=="string"||typeof G!=="string")return!1;if(G.length>100)return!1;let Z=Al6(G);return new RegExp(`^${Z}$`,"i").test(W);case"contains":if(typeof W!=="string"||typeof G!=="string")return!1;return W.toLowerCase().includes(G.toLowerCase());default:return!0}}function CO1(Y,Q){let X=Q.split("."),J=Y;for(let G of X){if(J==null||typeof J!=="object")return;J=J[G]}return J}function Pl6(Y,Q){return[...Y].sort((X,J)=>{for(let G of Q){let K=G.field.join("."),W=CO1(X,K),Z=CO1(J,K),H=0;if(W==null&&Z==null)continue;if(W==null)H=G.nulls==="first"?-1:1;else if(Z==null)H=G.nulls==="first"?1:-1;else if(typeof W==="string"&&typeof Z==="string")H=W.localeCompare(Z);else if(typeof W==="number"&&typeof Z==="number")H=W-Z;else H=String(W).localeCompare(String(Z));if(H!==0)return G.direction==="desc"?-H:H}return 0})}var wl6,El6,Tl6,RO1;var tc0=j(()=>{Yk();ic0();MG();Ar();Wi();QY();n1();F4();Er();p$();wl6={LLM:TO1,ASSISTANTS:nc0,OBJECT_STORAGE:tS};El6=lZ.extend({binding:q.union([q.object({}).passthrough(),q.string()]).optional(),include_virtual:q.boolean().optional().describe("Whether to include VIRTUAL connections in the results. Defaults to false.")}),Tl6=n$(Y5),RO1=t1({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:El6,outputSchema:Tl6,handler:async(Y,Q)=>{await Q.access.check();let X=v0(Q),J=Y.binding?typeof Y.binding==="string"?(()=>{let B=wl6[Y.binding.toUpperCase()];if(!B)throw Error(`Unknown binding: ${Y.binding}`);return B})():Y.binding:void 0,G=J?Qi(J):void 0,K=await Q.storage.connections.list(X.id,{includeVirtual:Y.include_virtual??!1});if(LP()){let B=X7(),U=IY.DEV_ASSETS(X.id);if(!K.some((D)=>D.id===U)){let D=MP(X.id,B);K.unshift(D)}}let W=G?await Promise.all(K.map(async(B)=>{if(!B.tools||B.tools.length===0)return null;return G.isImplementedBy(B.tools.map((D)=>({name:D.name,inputSchema:D.inputSchema,outputSchema:D.outputSchema})))?B:null})).then((B)=>B.filter((U)=>U!==null)):K;if(Y.where)W=W.filter((B)=>Tr(B,Y.where));if(Y.orderBy&&Y.orderBy.length>0)W=Pl6(W,Y.orderBy);let Z=W.length,H=Y.offset??0,$=Y.limit??100,F=W.slice(H,H+$),V=H+$<Z;return{items:F,totalCount:Z,hasMore:V}}})});var Cl6,IO1;var ec0=j(()=>{MG();F4();Er();p$();Cl6=hS(Y5),IO1=t1({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",annotations:{title:"Get Connection",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:bS,outputSchema:Cl6,handler:async(Y,Q)=>{let X=v0(Q);if(await Q.access.check(),LP()&&Pr(Y.id,X.id))return{item:MP(X.id,X7())};let J=await Q.storage.connections.findById(Y.id);if(!J||J.organization_id!==X.id)return{item:null};return{item:J}}})});var Cr=(Y,Q)=>{if(Q===null||Q===void 0)return;let X=Y.replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),J=Q;for(let G of X){if(J===null||J===void 0||typeof J!=="object")return;J=J[G]}return J};function Yn0(Y){let Q=Y.split("::");if(Q.length!==2||!Q[0]||!Q[1])throw Error(`Invalid scope format: ${Y}. Expected format: "KEY::SCOPE"`);return Q}function Rl6(Y){let Q=Y.split("::");if(Q.length!==2||!Q[0]||!Q[1])return null;return Q}function Il6(Y){if(typeof Y==="object"&&Y!==null&&"value"in Y){let Q=Y.value;if(typeof Q==="string")return Q}return null}function jO1(Y,Q){let X={};if(!Y||!Q)return X;for(let J of Q){if(J==="*"){X["*"]=["*"];continue}let G=Rl6(J);if(!G)continue;let[K,W]=G,Z=Cr(K,Y),H=Il6(Z);if(H){if(!X[H])X[H]=[];X[H].push(W)}}return X}function Qn0(Y,Q){let X=jO1(Y,Q);return new Set(Object.keys(X).filter((J)=>J!=="*"))}var SO1=()=>{};import{randomBytes as jl6}from"crypto";function Xn0(){if(Lv)return Lv;let Y=process.env.MESH_JWT_SECRET??p9.jwt?.secret??process.env.BETTER_AUTH_SECRET;if(Y)Lv=new TextEncoder().encode(Y);else console.warn("MESH_JWT_SECRET not set - generating random secret (not persistent)"),Lv=new Uint8Array(jl6(32));return Lv}async function Jn0(Y,Q="5m"){let X=Xn0();return await new s5(Y).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(Q).sign(X)}async function Gn0(Y){try{let Q=Xn0(),{payload:X}=await JY(Y,Q);return X}catch{return}}var Lv=null;var kO1=j(()=>{t5();wP()});async function Wn0(Y){if(!Y.refreshToken)return{success:!1,error:"No refresh token available"};if(!Y.tokenEndpoint)return{success:!1,error:"No token endpoint available"};if(!Y.clientId)return{success:!1,error:"No client ID available"};try{let Q=new URLSearchParams({grant_type:"refresh_token",refresh_token:Y.refreshToken,client_id:Y.clientId});if(Y.clientSecret)Q.set("client_secret",Y.clientSecret);if(Y.scope)Q.set("scope",Y.scope);let X=await fetch(Y.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Q.toString()});if(!X.ok){let G=await X.text();console.error(`[TokenRefresh] Failed to refresh token: ${X.status}`,G);try{let K=JSON.parse(G);return{success:!1,error:K.error_description||K.error||`Token refresh failed: ${X.status}`}}catch{return{success:!1,error:`Token refresh failed: ${X.status}`}}}let J=await X.json();return{success:!0,accessToken:J.access_token,refreshToken:J.refresh_token||Y.refreshToken,expiresIn:J.expires_in,scope:J.scope}}catch(Q){return console.error("[TokenRefresh] Error refreshing token:",Q),{success:!1,error:Q instanceof Error?Q.message:"Token refresh failed"}}}class NF{db;vault;constructor(Y,Q){this.db=Y;this.vault=Q}async get(Y){let Q=await this.db.selectFrom("downstream_tokens").selectAll().where("connectionId","=",Y).executeTakeFirst();if(!Q)return null;return this.decryptToken(Q)}async upsert(Y){let Q=new Date().toISOString(),X=await this.vault.encrypt(Y.accessToken),J=Y.refreshToken?await this.vault.encrypt(Y.refreshToken):null,G=Y.clientSecret?await this.vault.encrypt(Y.clientSecret):null;return await this.db.transaction().execute(async(K)=>{let W=await K.selectFrom("downstream_tokens").select(["id","createdAt"]).where("connectionId","=",Y.connectionId).executeTakeFirst();if(W)return await K.updateTable("downstream_tokens").set({accessToken:X,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,updatedAt:Q}).where("id","=",W.id).execute(),{id:W.id,connectionId:Y.connectionId,accessToken:Y.accessToken,refreshToken:Y.refreshToken,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:W.createdAt,updatedAt:Q,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint};let Z=J9("dtok");return await K.insertInto("downstream_tokens").values({id:Z,connectionId:Y.connectionId,accessToken:X,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,createdAt:Q,updatedAt:Q}).execute(),{id:Z,connectionId:Y.connectionId,accessToken:Y.accessToken,refreshToken:Y.refreshToken,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:Q,updatedAt:Q,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint}})}async delete(Y){await this.db.deleteFrom("downstream_tokens").where("connectionId","=",Y).execute()}isExpired(Y,Q=0){if(!Y.expiresAt)return!1;let J=(Y.expiresAt instanceof Date?Y.expiresAt:new Date(Y.expiresAt)).getTime();if(Number.isNaN(J))return!0;return J-Q<Date.now()}async decryptToken(Y){let Q=await this.vault.decrypt(Y.accessToken),X=Y.refreshToken?await this.vault.decrypt(Y.refreshToken):null,J=Y.clientSecret?await this.vault.decrypt(Y.clientSecret):null;return{id:Y.id,connectionId:Y.connectionId,accessToken:Q,refreshToken:X,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:Y.createdAt,updatedAt:Y.updatedAt,clientId:Y.clientId,clientSecret:J,tokenEndpoint:Y.tokenEndpoint}}}var Rr=j(()=>{F7()});async function Mv(Y,Q,X){let J=Y.id,G=jO1(Y.configuration_state,Y.configuration_scopes),K=Q.auth.user?.id??Q.auth.apiKey?.userId??(X?Y.created_by:void 0),[W,Z]=K?await Jn0({sub:K,user:{id:K},metadata:{state:Y.configuration_state??void 0,meshUrl:Q.baseUrl,connectionId:J,organizationId:Q.organization?.id},permissions:G}).then((U)=>[U,null]).catch((U)=>[null,U]):[null,Error("User ID required to issue configuration token")];if(Z)console.error("Failed to issue configuration token:",W);let H=Q.auth.user?.connectionId,$={...H?{"x-caller-id":H}:{},...Q.metadata.wellKnownForwardableHeaders??{},"x-request-id":Q.metadata.requestId},F=null,V=new NF(Q.db,Q.vault),B=await V.get(J);if(B){let U=!!B.refreshToken&&!!B.tokenEndpoint;if(V.isExpired(B,U?300000:0))if(U){console.log(`[Proxy] Token expired for ${J}, attempting refresh`);let z=await Wn0(B);if(z.success&&z.accessToken)await V.upsert({connectionId:J,accessToken:z.accessToken,refreshToken:z.refreshToken??B.refreshToken,scope:z.scope??B.scope,expiresAt:z.expiresIn?new Date(Date.now()+z.expiresIn*1000):null,clientId:B.clientId,clientSecret:B.clientSecret,tokenEndpoint:B.tokenEndpoint}),F=z.accessToken,console.log(`[Proxy] Token refreshed for ${J}`);else await V.delete(J),console.error(`[Proxy] Token refresh failed for ${J}: ${z.error}`)}else await V.delete(J),console.log(`[Proxy] Token expired without refresh capability for ${J}`);else F=B.accessToken}if(!F&&Y.connection_token)F=Y.connection_token;if(F)$.Authorization=`Bearer ${F}`;if(W)$["x-mesh-token"]=W;return $}var vO1=j(()=>{SO1();kO1();Rr()});function Ir(){let Y=new Map;function Q(J,G){let K=Y.get(G);if(K)return console.log(`[ClientPool] Reusing cached client for ${G}`),K;console.log(`[ClientPool] Creating new client for ${G}`);let W=new eJ({name:`outbound-client-${G}`,version:"1.0.0"},{capabilities:{tasks:{list:{},cancel:{},requests:{tool:{call:{}}}}}});W.onclose=()=>{Y.delete(G)};let Z=W.connect(J,{timeout:30000}).then(()=>W).catch((H)=>{throw Y.delete(G),H});return Y.set(G,Z),Z}return Object.assign(Q,{[Symbol.asyncDispose]:async()=>{let J=[];for(let[G,K]of Y)J.push(K.then((W)=>W.close()).catch((W)=>console.error(`[ClientPool] Error closing client ${G}:`,W)));await Promise.all(J),Y.clear()}})}var _O1=j(()=>{LU()});function Zn0(Y){let Q=new _S({command:Y.command,args:Y.args,env:Y.env,cwd:Y.cwd,stderr:"pipe"}),X=Y.name||Y.id,J="\x1B[2m",G="\x1B[0m";return Q.stderr?.on("data",(K)=>{let W=K.toString().trimEnd();if(W)console.error(`${W} \x1B[2m[${X}]\x1B[0m`)}),Q}var Kn0=j(()=>{dq1()});class wv{innerTransport;constructor(Y){this.innerTransport=Y}async start(){return this.innerTransport.onmessage=(Y)=>{this.handleIncomingMessage(Y)},this.innerTransport.onerror=(Y)=>{this.onerror?.(Y)},this.innerTransport.onclose=()=>{this.onclose?.()},this.innerTransport.start()}async send(Y){return this.handleOutgoingMessage(Y)}async close(){return this.innerTransport.close()}async handleOutgoingMessage(Y){return this.innerTransport.send(Y)}handleIncomingMessage(Y){this.onmessage?.(Y)}isRequest(Y){return"method"in Y&&Y.method!==void 0}isResponse(Y){return"result"in Y||"error"in Y&&!("method"in Y)}onmessage;onerror;onclose}function Av(Y,...Q){return Q.reduce((X,J)=>J(X),Y)}var Hn0="mcp.mesh";var $n0,yO1,LF;var Pv=j(()=>{$n0=class $n0 extends Error{constructor(Y){super(Y);this.name="UnauthorizedError"}};yO1=class yO1 extends Error{constructor(Y){super(Y);this.name="ForbiddenError"}};LF=class LF{userId;toolName;boundAuth;role;connectionId;getToolMeta;_granted=!1;constructor(Y,Q,X,J,G,K="self",W){this.userId=Q;this.toolName=X;this.boundAuth=J;this.role=G;this.connectionId=K;this.getToolMeta=W}[Symbol.dispose](){this._granted=!1}setToolName(Y){this.toolName=Y}grant(){return this._granted=!0,{[Symbol.dispose]:()=>{this._granted=!1}}}async check(...Y){if(this._granted)return;if(this.toolName?.startsWith("MESH_PUBLIC_")){this.grant();return}if(!this.userId&&!this.boundAuth){if(this.getToolMeta&&await this.isToolPublic()){this.grant();return}throw new $n0("Authentication required. Please provide a valid OAuth token or API key.")}let Q=Y.length>0?Y:this.toolName?[this.toolName]:[];if(Q.length===0)throw new yO1("No resources specified for access check");for(let X of Q)if(await this.checkResource(X)){this.grant();return}throw new yO1(`Access denied to: ${Q.join(", ")}`)}async checkResource(Y){if(!this.userId&&!this.boundAuth)return!1;if(this.role==="admin"||this.role==="owner")return!0;if(!this.boundAuth)return!1;let Q={};if(this.connectionId)Q[this.connectionId]=[Y];return this.boundAuth.hasPermission(Q)}async isToolPublic(){if(this.toolName?.startsWith("MESH_PUBLIC_"))return!0;if(!this.getToolMeta)return!1;try{let Y=await this.getToolMeta();if(!Y)return!1;let X=Y[Hn0]?.public_tool;return X===!0||X==="true"}catch{return!1}}granted(){return this._granted}}});var Sl6="mcp.mesh",AP;var Fn0=j(()=>{Pv();AP=class AP extends wv{options;cachedToolsMap=null;constructor(Y,Q){super(Y);this.options=Q;if(Q.connection.tools)this.cachedToolsMap=new Map(Q.connection.tools.map((X)=>[X.name,X]))}async handleOutgoingMessage(Y){if(!this.isRequest(Y))return this.innerTransport.send(Y);let Q=Y;if(Q.method==="tools/call")await this.authorizeToolCall(Q),this.stripMetaFromArguments(Q);return this.innerTransport.send(Y)}async authorizeToolCall(Y){if(this.options.superUser)return;let X=Y.params.name,{ctx:J,connection:G}=this.options;if(this.isPublicTool(X))return;if(!J.auth.user?.id&&!J.auth.apiKey?.id)throw Error("Authentication required. Please provide a valid OAuth token or API key.");let K=async()=>{return this.cachedToolsMap?.get(X)?._meta};await new LF(J.authInstance,J.auth.user?.id??J.auth.apiKey?.userId,X,J.boundAuth,J.auth.user?.role,G.id,K).check(X)}isPublicTool(Y){if(Y.startsWith("MESH_PUBLIC_"))return!0;if(!this.cachedToolsMap)return!1;let Q=this.cachedToolsMap.get(Y);if(!Q?._meta)return!1;return Q._meta[Sl6]?.public_tool===!0}stripMetaFromArguments(Y){let Q=Y.params;if(Q.arguments&&"_meta"in Q.arguments){let{_meta:X,...J}=Q.arguments;Q.arguments=J}}}});function qn0(Y){if(!Y.isError)return;let Q=Y.content;if(!Array.isArray(Q))return;for(let X of Q)if(X&&typeof X==="object"&&"type"in X&&X.type==="text"&&"text"in X&&typeof X.text==="string")return X.text;return}function bO1(Y){if(!Y)return;let Q=Y._meta;if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let X=Q.properties;if(!X||typeof X!=="object"||Array.isArray(X))return;let J={};for(let[G,K]of Object.entries(X))if(typeof K==="string")J[G]=K;return Object.keys(J).length>0?J:void 0}function hO1(Y,Q){if(!Y&&!Q)return;if(!Y)return Q;if(!Q)return Y;return{...Q,...Y}}function xO1(Y){if(Y&&typeof Y==="object"&&!Array.isArray(Y)){let Q=Y,X=Q.structuredContent;if(X&&typeof X==="object"&&!Array.isArray(X))return X;return Q}return{value:Y}}async function kl6(Y,Q){let X=Y.body;if(!X)return{text:"",truncated:!1};let J=X.getReader(),G=new TextDecoder,K=!1,W=0,Z=[];try{while(!0){let{value:H,done:$}=await J.read();if($)break;if(H){if(W+=H.byteLength,W>Q){K=!0;let F=Q-(W-H.byteLength);if(F>0)Z.push(G.decode(H.slice(0,F),{stream:!0}));break}Z.push(G.decode(H,{stream:!0}))}}}finally{J.releaseLock()}return Z.push(G.decode()),{text:Z.join(""),truncated:K}}function vl6(Y){if(!Y)return;let Q=Y.trimEnd().split(`
1473
1473
  `);for(let X=Q.length-1;X>=0&&X>=Q.length-5;X--){let J=Q[X]?.trim();if(!J)continue;try{let G=JSON.parse(J);if(G&&typeof G==="object"&&G.type==="finish"){let K={};if(G.usage)K.usage=G.usage;if(G.providerMetadata)K.providerMetadata=G.providerMetadata;if(G.finishReason)K.finishReason=G.finishReason;return Object.keys(K).length>0?K:void 0}}catch{}}return}async function fO1(Y){let{ctx:Q,enabled:X}=Y,J=Y.organizationId??Q.organization?.id;if(!X||!J)return;if(f3(Y.connectionId))return;let G=bO1(Y.request.params.arguments),K=hO1(Q.metadata.properties,G),W=Q.auth.user?.id||Q.auth.apiKey?.userId;if(W)try{let Z=await Q.storage.tags.getUserTagsInOrg(W,J);if(Z.length>0){let H=Z.map(($)=>$.name).join(",");K={...K,user_tags:H}}}catch{}await Q.storage.monitoring.log({organizationId:J,connectionId:Y.connectionId,connectionTitle:Y.connectionTitle,toolName:Y.request.params.name,input:Y.request.params.arguments??{},output:Y.output,isError:Y.isError,errorMessage:Y.errorMessage,durationMs:Y.durationMs,timestamp:new Date,userId:Q.auth.user?.id||Q.auth.apiKey?.userId||null,requestId:Q.metadata.requestId,userAgent:Q.metadata.userAgent,virtualMcpId:Y.virtualMcpId,properties:K})}function Bn0(Y){let{ctx:Q,enabled:X,connectionId:J,connectionTitle:G,virtualMcpId:K}=Y;return async(W,Z)=>{let H=Date.now();try{let $=await Z(),F=Q.organization?.id;if(X&&F){let V=$.clone();(async()=>{try{let{text:B,truncated:U}=await kl6(V,Vn0),D=Date.now()-H,z=V.headers.get("content-type")??"",L=B;if(z.includes("application/json"))try{L=B.length?JSON.parse(B):null}catch{L=B}let w=$.status>=400,E=w&&L&&typeof L==="object"&&"error"in L?L.error:void 0,T=typeof E==="string"&&E?E:w&&typeof L==="string"&&L.trim()?L.slice(0,500):w?`HTTP ${$.status} ${$.statusText}`.trim():U?`Response body truncated to ${Vn0} bytes`:void 0,C=xO1(L),P=vl6(B);if(P)Object.assign(C,P);await fO1({ctx:Q,enabled:X,organizationId:F,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:C,isError:w,errorMessage:T,durationMs:D})}catch(B){let U=Date.now()-H;await fO1({ctx:Q,enabled:X,organizationId:F,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:{},isError:!0,errorMessage:`Failed to read streamable response body: ${B.message}`,durationMs:U})}})()}return $}catch($){let F=$,V=Date.now()-H;throw await fO1({ctx:Q,enabled:X,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:{},isError:!0,errorMessage:F.message,durationMs:V}),$}}}var Vn0=262144;var gO1=j(()=>{QY()});var PP;var Un0=j(()=>{WI();gO1();PP=class PP extends wv{options;inflightRequests=new Map;constructor(Y,Q){super(Y);this.options=Q}async handleOutgoingMessage(Y){if(this.isRequest(Y)){let Q=Y;this.onRequestStart(Q)}return this.innerTransport.send(Y)}handleIncomingMessage(Y){if(this.isResponse(Y)){let Q=Y;this.onResponseEnd(Q)}this.onmessage?.(Y)}onRequestStart(Y){let{ctx:Q,connectionId:X}=this.options,J,G;if(Y.method==="tools/call"&&Y.params){let W=Y.params;J=W.name,G=W.arguments}let K;if(Y.method==="tools/call"&&J)K=Q.tracer.startSpan("mcp.proxy.callTool",{attributes:{"connection.id":X,"tool.name":J,"request.id":Q.metadata.requestId,"jsonrpc.id":Y.id,"jsonrpc.method":Y.method}});if(Y.id!==null&&Y.id!==void 0)this.inflightRequests.set(Y.id,{startTime:Date.now(),method:Y.method,toolName:J,toolArguments:G,span:K})}onResponseEnd(Y){if(Y.id===null||Y.id===void 0)return;let Q=this.inflightRequests.get(Y.id);if(!Q)return;let{ctx:X,connectionId:J}=this.options,{startTime:G,method:K,toolName:W,toolArguments:Z,span:H}=Q,$=Date.now()-G;if(this.inflightRequests.delete(Y.id),K!=="tools/call"||!W)return;let F="error"in Y,V=F?Y.error:Y.result,B=F?{content:[{type:"text",text:Y.error?.message||"Unknown error"}],isError:!0}:V;if(X.meter.createHistogram("connection.proxy.duration").record($,{"connection.id":J,"tool.name":W,status:F?"error":"success"}),F)X.meter.createCounter("connection.proxy.errors").add(1,{"connection.id":J,"tool.name":W,error:Y.error?.message});else X.meter.createCounter("connection.proxy.requests").add(1,{"connection.id":J,"tool.name":W,status:"success"});if(H){if(F&&Y.error)H.recordException(Error(Y.error.message)),H.setAttributes({error:!0,"error.code":Y.error.code,"error.message":Y.error.message});H.end()}this.logToDatabase({toolName:W,toolArguments:Z,result:B,duration:$,isError:Boolean(F)})}async logToDatabase(Y){let{ctx:Q,connectionId:X,connectionTitle:J,virtualMcpId:G}=this.options,{toolName:K,toolArguments:W,result:Z,duration:H,isError:$}=Y;if(!ml().enabled)return;let V=Q.organization?.id;if(!V)return;let B=qn0(Z),U=xO1(Z),D=bO1(W),z=hO1(Q.metadata.properties,D);try{await Q.storage.monitoring.log({organizationId:V,connectionId:X,connectionTitle:J,toolName:K,input:W??{},output:U,isError:$,errorMessage:B,durationMs:H,timestamp:new Date,userId:Q.auth.user?.id||Q.auth.apiKey?.userId||null,requestId:Q.metadata.requestId,userAgent:Q.metadata.userAgent,virtualMcpId:G,properties:z})}catch(L){console.error("[MonitoringTransport] Failed to log to database:",L)}}async close(){for(let Y of this.inflightRequests.values())if(Y.span)Y.span.setAttributes({"transport.closed":!0}),Y.span.end();return this.inflightRequests.clear(),super.close()}}});var Dn0=j(()=>{Fn0();Un0()});async function zn0(Y,Q,X=!1){let J=Y.id,G=Q.connectionId&&Q.connectionId!==J?Q.connectionId:void 0;switch(Y.connection_type){case"STDIO":{if(process.env.UNSAFE_ALLOW_STDIO_TRANSPORT!=="true")throw Error("STDIO connections are disabled in production. Set UNSAFE_ALLOW_STDIO_TRANSPORT=true to enable.");let K=Y.connection_headers;if(!jK(K))throw Error("STDIO connection missing parameters");let W=Zn0({id:J,name:Y.title,command:K.command,args:K.args,env:K.envVars,cwd:K.cwd});return W=Av(W,(Z)=>new AP(Z,{ctx:Q,connection:Y,superUser:X}),(Z)=>new PP(Z,{ctx:Q,connectionId:J,connectionTitle:Y.title,virtualMcpId:G})),_l6(W,J)}case"HTTP":case"Websocket":{if(!Y.connection_url)throw Error(`${Y.connection_type} connection missing URL`);let K=await Mv(Y,Q,X),W=Y.connection_headers;if(W&&"headers"in W)Object.assign(K,W.headers);let Z=new qV(new URL(Y.connection_url),{requestInit:{headers:K}});return Z=Av(Z,(H)=>new AP(H,{ctx:Q,connection:Y,superUser:X}),(H)=>new PP(H,{ctx:Q,connectionId:J,connectionTitle:Y.title,virtualMcpId:G})),Q.getOrCreateClient(Z,J)}case"SSE":{if(!Y.connection_url)throw Error("SSE connection missing URL");let K=await Mv(Y,Q,X),W=Y.connection_headers;if(W&&"headers"in W)Object.assign(K,W.headers);let Z=new fz(new URL(Y.connection_url),{requestInit:{headers:K}});return Z=Av(Z,(H)=>new AP(H,{ctx:Q,connection:Y,superUser:X}),(H)=>new PP(H,{ctx:Q,connectionId:J,connectionTitle:Y.title,virtualMcpId:G})),Q.getOrCreateClient(Z,J)}default:throw Error(`Unknown connection type: ${Y.connection_type}`)}}var _l6;var On0=j(()=>{p$();cn();vT();vO1();_O1();Kn0();Dn0();_l6=Ir()});function UB(Y){if(!Y?._meta)return!1;return typeof Y._meta["mcp.mesh"]?.["tool.fn"]==="string"}function Mn0(Y){return Y._meta["mcp.mesh"]["tool.fn"]}function Ev(Y,Q,X,J){return{id:Y,name:Q.name,description:Q.description,inputSchema:Q.inputSchema,outputSchema:Q.outputSchema,annotations:Q.annotations,code:Q._meta["mcp.mesh"]["tool.fn"],connection_dependencies:Q._meta.connectionDependencies??[],created_at:X,updated_at:J}}var uO1,cq9,Q3,Nn0,Ln0;var MF=j(()=>{n1();uO1=q.object({title:q.string().optional(),readOnlyHint:q.boolean().optional(),destructiveHint:q.boolean().optional(),idempotentHint:q.boolean().optional(),openWorldHint:q.boolean().optional()}),cq9=q.object({"tool.fn":q.string().describe("JavaScript ES module code that exports a default async function")}),Q3=q.object({id:q.string().describe("Unique identifier for the virtual tool (auto-generated)"),name:q.string().min(1).max(255).describe("Tool name (must be unique within the Virtual MCP)"),description:q.string().optional().describe("Human-readable description of what the tool does"),inputSchema:q.record(q.string(),q.unknown()).describe("JSON Schema defining the tool's input parameters"),outputSchema:q.record(q.string(),q.unknown()).optional().describe("JSON Schema defining the tool's output (optional)"),annotations:uO1.optional().describe("MCP tool annotations"),code:q.string().describe("JavaScript ES module code. Must export default an async function: export default async (tools, args) => { ... }"),connection_dependencies:q.array(q.string()).describe("Connection IDs that this tool depends on (specified by the creator)"),created_at:q.string().describe("When the virtual tool was created"),updated_at:q.string().describe("When the virtual tool was last updated")}),Nn0=q.object({name:q.string().min(1).max(255).describe("Tool name (must be unique within the Virtual MCP)"),description:q.string().optional().describe("Human-readable description"),inputSchema:q.record(q.string(),q.unknown()).describe("JSON Schema defining the tool's input parameters"),outputSchema:q.record(q.string(),q.unknown()).optional().describe("JSON Schema for output"),annotations:uO1.optional().describe("MCP tool annotations"),code:q.string().describe("JavaScript ES module code. Must export default an async function: export default async (tools, args) => { ... }"),connection_dependencies:q.array(q.string()).optional().describe("Connection IDs that this tool depends on. Creates indirect aggregations to prevent deletion of referenced connections.")}),Ln0=q.object({name:q.string().min(1).max(255).optional().describe("New tool name"),description:q.string().nullable().optional().describe("New description (null to clear)"),inputSchema:q.record(q.string(),q.unknown()).optional().describe("New input schema"),outputSchema:q.record(q.string(),q.unknown()).nullable().optional().describe("New output schema (null to clear)"),annotations:uO1.nullable().optional().describe("New annotations (null to clear)"),code:q.string().optional().describe("New JavaScript code"),connection_dependencies:q.array(q.string()).optional().describe("Connection IDs that this tool depends on. Replaces existing dependencies if provided.")})});function DO(Y){return(Q)=>{if(Q instanceof u0&&Q.code===o0.MethodNotFound)return Y;throw Q}}var mO1=j(()=>{kQ()});class wn0{factory;promise=null;constructor(Y){this.factory=Y}getOrCreatePromise(){if(!this.promise)this.promise=this.factory();return this.promise}then(Y,Q){return this.getOrCreatePromise().then(Y,Q)}catch(Y){return this.getOrCreatePromise().catch(Y)}finally(Y){return this.getOrCreatePromise().finally(Y)}}function EP(Y){return new wn0(Y)}function yl6(Y,Q,X){let J=new eJ({name:`lazy-${Y.id}`,version:"1.0.0"},{capabilities:{}}),G=null;function K(){if(!G)G=y5(Y,Q,X).then((H)=>{if(Y.connection_type==="HTTP"||Y.connection_type==="SSE"||Y.connection_type==="Websocket")return zO(H,Y.id,Y,Q,{superUser:X});return H});return G}if(Y.connection_type!=="VIRTUAL"&&Array.isArray(Y.tools)&&Y.tools.length>0)J.listTools=async()=>({tools:Y.tools.map((H)=>({name:H.name,description:H.description,inputSchema:H.inputSchema,outputSchema:H.outputSchema,annotations:H.annotations,_meta:H._meta}))});else J.listTools=async()=>{return(await K()).listTools()};J.callTool=async(H,$,F)=>{return(await K()).callTool(H,$,F)},J.listResources=async()=>{return(await K()).listResources()},J.listPrompts=async()=>{return(await K()).listPrompts()},J.getPrompt=async(H,$)=>{return(await K()).getPrompt(H,$)},J.readResource=async(H,$)=>{return(await K()).readResource(H,$)},J.callStreamableTool=async(H,$)=>{let F=await K();if("callStreamableTool"in F&&typeof F.callStreamableTool==="function")return F.callStreamableTool(H,$);let V=await F.callTool({name:H,arguments:$});return new Response(JSON.stringify(V),{headers:{"Content-Type":"application/json"}})};let Z=J.close.bind(J);return J.close=async()=>{if(G){let H=await G.catch(()=>null);if(H)await H.close().catch(()=>{})}await Z()},J}function fl6(Y,Q,X=!1){let J=new Map;for(let G of Y)J.set(G.id,yl6(G,Q,X));return J}async function An0(Y){let Q=[];for(let[,X]of Y)Q.push(X.close().catch(()=>{}));await Promise.all(Q)}var TP;var lO1=j(()=>{CP();mO1();LU();Nr();MF();TP=class TP extends eJ{options;ctx;_cachedTools;_cachedResources;_cachedPrompts;_clients;_connections;_selectionMap;constructor(Y,Q){super({name:"virtual-mcp-passthrough",version:"1.0.0"},{capabilities:{tasks:{list:{},cancel:{},requests:{tool:{call:{}}}}}});this.options=Y;this.ctx=Q;this._selectionMap=new Map;for(let X of Y.virtualMcp.connections)this._selectionMap.set(X.connection_id,X);this._connections=new Map;for(let X of Y.connections)this._connections.set(X.id,X);this._clients=fl6(this.options.connections,this.ctx,this.options.superUser),this._cachedTools=EP(()=>this.loadToolsCache()),this._cachedResources=EP(()=>this.loadCache("resources")),this._cachedPrompts=EP(()=>this.loadCache("prompts"))}async loadToolsCache(){let Y=this._clients,Q=await Promise.all(Array.from(Y.entries()).map(async([W,Z])=>{try{let H=await Z.listTools().then((F)=>F.tools),$=this._selectionMap.get(W);if($?.selected_tools?.length){let F=new Set($.selected_tools);H=H.filter((V)=>F.has(V.name))}return{connectionId:W,data:H}}catch(H){return console.error(`[PassthroughClient] Failed to load tools for connection ${W}:`,H),null}})),X=[],J=new Map,G=new Map,K=this.options.virtualTools??[];for(let W of K){if(J.has(W.name))continue;let Z={name:W.name,description:W.description,inputSchema:W.inputSchema,outputSchema:W.outputSchema,annotations:W.annotations,_meta:{connectionId:this.options.virtualMcp.id??"__VIRTUAL__",connectionTitle:this.options.virtualMcp.title}};X.push(Z),J.set(W.name,"__VIRTUAL__"),G.set(W.name,W)}for(let W of Q){if(!W)continue;let{connectionId:Z,data:H}=W,F=this._connections.get(Z)?.title??"";for(let V of H){let B=V.name;if(J.has(B))continue;let U={...V,_meta:{connectionId:Z,connectionTitle:F,...V?._meta}};X.push(U),J.set(B,Z)}}return{data:X,mappings:J,virtualTools:G}}async loadCache(Y){let Q=this._clients,X=await Promise.all(Array.from(Q.entries()).map(async([K,W])=>{try{let Z=Y==="resources"?await W.listResources().catch(DO({resources:[]})).then((F)=>F.resources):await W.listPrompts().catch(DO({prompts:[]})).then((F)=>F.prompts),H=this._selectionMap.get(K),$=Y==="resources"?"selected_resources":"selected_prompts";if(H?.[$]?.length){let F=new Set(H[$]);return{connectionId:K,data:Z.filter((V)=>F.has(V.name))}}return{connectionId:K,data:Z}}catch(Z){return console.error(`[PassthroughClient] Failed to load cache for connection ${K}:`,Z),null}})),J=[],G=new Map;for(let K of X){if(!K)continue;let{connectionId:W,data:Z}=K,$=this._connections.get(W)?.title??"";for(let F of Z){let V=F.name??F.uri;if(G.has(V))continue;let B={...F,_meta:{connectionId:W,connectionTitle:$,...F?._meta}};J.push(B),G.set(V,W)}}return{data:J,mappings:G}}async listTools(){return{tools:(await this._cachedTools).data}}async callTool(Y){let Q=await this._cachedTools,X=this._clients,J=Q.mappings.get(Y.name);if(!J)return{content:[{type:"text",text:`Tool not found: ${Y.name}`}],isError:!0};if(J==="__VIRTUAL__")return this.executeVirtualTool(Y.name,Y.arguments??{},Q,X);let G=X.get(J);if(!G)return{content:[{type:"text",text:`Connection not found for tool: ${Y.name}`}],isError:!0};return await G.callTool({name:Y.name,arguments:Y.arguments??{}})}async executeVirtualTool(Y,Q,X,J){let G=X.virtualTools.get(Y);if(!G)return{content:[{type:"text",text:`Virtual tool not found: ${Y}`}],isError:!0};let K=Mn0(G),W={};for(let[Z,H]of X.mappings){if(H==="__VIRTUAL__")continue;let $=J.get(H);if(!$)continue;W[Z]=async(F)=>{let V=await $.callTool({name:Z,arguments:F});if(V.structuredContent&&typeof V.structuredContent==="object")return V.structuredContent;let B=V.content;if(B?.[0]?.type==="text"&&B[0].text)try{return JSON.parse(B[0].text)}catch{return B[0].text}return V}}try{let H=`
1474
1474
  const __virtualToolFn = ${K.replace(/^\s*export\s+default\s+/,"").trim()};
1475
1475
  export default async (tools) => {
@@ -1478,7 +1478,7 @@ ${Q.stack}`;return G}}catch{}if(typeof Q.toString==="function")try{let G=Q.toStr
1478
1478
  };
1479
1479
  `,$=await Dv({code:H,tools:W,timeoutMs:30000});if($.error)return{content:[{type:"text",text:`Virtual tool error: ${$.error}`}],isError:!0};return{content:[{type:"text",text:JSON.stringify($.returnValue??null)}]}}catch(Z){return{content:[{type:"text",text:`Virtual tool execution failed: ${Z instanceof Error?Z.message:String(Z)}`}],isError:!0}}}async listResources(){return{resources:(await this._cachedResources).data}}async readResource(Y){let Q=await this._cachedResources,X=this._clients,J=Q.mappings.get(Y.uri);if(!J)throw Error(`Resource not found: ${Y.uri}`);let G=X.get(J);if(!G)throw Error(`Connection not found for resource: ${Y.uri}`);return await G.readResource(Y)}async listPrompts(){return{prompts:(await this._cachedPrompts).data}}async getPrompt(Y){let Q=await this._cachedPrompts,X=this._clients,J=Q.mappings.get(Y.name);if(!J)throw Error(`Prompt not found: ${Y.name}`);let G=X.get(J);if(!G)throw Error(`Connection not found for prompt: ${Y.name}`);return await G.getPrompt(Y)}async callStreamableTool(Y,Q){let X=await this._cachedTools,J=this._clients,G=X.mappings.get(Y);if(G){let W=J.get(G);if(W&&"callStreamableTool"in W)return W.callStreamableTool(Y,Q)}let K=await this.callTool({name:Y,arguments:Q});return new Response(JSON.stringify(K),{headers:{"Content-Type":"application/json"}})}async[Symbol.asyncDispose](){await An0(this._clients)}async close(){await An0(this._clients),await super.close()}getInstructions(){return this.options.virtualMcp.metadata?.instructions??void 0}}});var Pn0,bl6,En0,hl6,Tv;var dO1=j(()=>{n1();UO();lO1();Pn0=q.object({query:q.string().min(1).describe("Search query to find tools by name or description"),limit:q.number().default(10).describe("Maximum number of results to return")}),bl6=q.toJSONSchema(Pn0),En0=q.object({tools:q.array(q.string()).min(1).describe("Array of tool names to get detailed schemas for")}),hl6=q.toJSONSchema(En0);Tv=class Tv extends TP{constructor(Y,Q){super(Y,Q)}getSearchTool(Y){return{name:"GATEWAY_SEARCH_TOOLS",description:`Search for available tools by name or description. Returns tool names and brief descriptions without full schemas. Use this to discover tools before calling GATEWAY_DESCRIBE_TOOLS for detailed schemas. Total tools: ${Y}.`,inputSchema:bl6,annotations:{title:"Search Tools",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}}}getDescribeTool(){return{name:"GATEWAY_DESCRIBE_TOOLS",description:"Get detailed schemas for specific tools. Call after GATEWAY_SEARCH_TOOLS to get full input/output schemas.",inputSchema:hl6,annotations:{title:"Describe Tools",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}}}async handleSearch(Y){let Q=Pn0.safeParse(Y);if(!Q.success)return qB({error:Q.error.flatten()});let X=await this._cachedTools,J=zF(X.data),G=Lr(Q.data.query,J,Q.data.limit);return zv({query:Q.data.query,results:G.map((K)=>({name:K.name,description:K.description,connection:K._meta.connectionTitle})),totalAvailable:J.length})}async handleDescribe(Y){let Q=En0.safeParse(Y);if(!Q.success)return qB({error:Q.error.flatten()});let X=await this._cachedTools,J=zF(X.data),G=Mr(Q.data.tools,J);return zv({tools:G.tools,notFound:G.notFound})}async listTools(){let Y=await this._cachedTools,Q=zF(Y.data);return{tools:[this.getSearchTool(Q.length),this.getDescribeTool()]}}async callTool(Y){if(Y.name==="GATEWAY_SEARCH_TOOLS")return this.handleSearch(Y.arguments??{});if(Y.name==="GATEWAY_DESCRIBE_TOOLS")return this.handleDescribe(Y.arguments??{});return{content:[{type:"text",text:`Unknown tool: ${Y.name}. Available: GATEWAY_SEARCH_TOOLS, GATEWAY_DESCRIBE_TOOLS`}],isError:!0}}async routeToolCall(Y){return TP.prototype.callTool.call(this,Y)}}});var Tn0,xl6,pO1;var Cn0=j(()=>{n1();UO();dO1();Tn0=q.object({code:q.string().min(1).describe("JavaScript code to execute. It runs as an async function body; you can use top-level `return` and `await`."),timeoutMs:q.number().default(3000).describe("Max execution time in milliseconds (default: 3000).")}),xl6=q.toJSONSchema(Tn0);pO1=class pO1 extends Tv{constructor(Y,Q){super(Y,Q)}getRunCodeTool(){return{name:"GATEWAY_RUN_CODE",description:'Run JavaScript code in a sandbox. Code must be an ES module that `export default`s an async function that receives (tools) as its first parameter. Use GATEWAY_DESCRIBE_TOOLS to understand the input/output schemas for a tool before calling it. Use `await tools.toolName(args)` or `await tools["tool-name"](args)` to call tools.',inputSchema:xl6,annotations:{title:"Run Code",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}}}async handleRunCode(Y){let Q=Tn0.safeParse(Y);if(!Q.success)return qB({error:Q.error.flatten()});let X=await this._cachedTools,G={tools:zF(X.data),callTool:async(W,Z)=>{return this.routeToolCall({name:W,arguments:Z})}},K=await wr(Q.data.code,G,Q.data.timeoutMs);if(K.error)return qB(K);return zv(K)}async listTools(){return{tools:[...(await super.listTools()).tools,this.getRunCodeTool()]}}async callTool(Y){if(Y.name==="GATEWAY_RUN_CODE")return this.handleRunCode(Y.arguments??{});return super.callTool(Y)}}});function In0(Y){let Q=Y.slice().sort().join(","),X=Rn0.get(Q);if(!X){let J=q.object({name:(Y.length>0?q.enum(Y):q.string()).describe("The name of the tool to execute"),arguments:q.record(q.string(),q.unknown()).default({}).describe("Arguments to pass to the tool")});X={schema:J,jsonSchema:q.toJSONSchema(J)},Rn0.set(Q,X)}return X}var Rn0,cO1;var jn0=j(()=>{n1();UO();dO1();Rn0=new Map;cO1=class cO1 extends Tv{constructor(Y,Q){super(Y,Q)}async getCallTool(){let Y=await this._cachedTools,X=zF(Y.data).map((G)=>G.name),{jsonSchema:J}=In0(X);return{name:"GATEWAY_CALL_TOOL",description:"Execute a tool by name. Use GATEWAY_DESCRIBE_TOOLS first to understand the input schema.",inputSchema:J,annotations:{title:"Call Tool",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}}}async handleCallTool(Y){let Q=await this._cachedTools,X=zF(Q.data),J=X.map(($)=>$.name),{schema:G}=In0(J),K=G.safeParse(Y);if(!K.success)return qB({error:K.error.flatten()});let{name:W,arguments:Z}=K.data;if(!new Map(X.map(($)=>[$.name,$])).has(W))return{content:[{type:"text",text:`Tool not found: ${W}. Use GATEWAY_SEARCH_TOOLS to find available tools.`}],isError:!0};return this.routeToolCall({name:W,arguments:Z})}async listTools(){let Y=await super.listTools(),Q=await this.getCallTool();return{tools:[...Y.tools,Q]}}async callTool(Y){if(Y.name==="GATEWAY_CALL_TOOL")return this.handleCallTool(Y.arguments??{});return super.callTool(Y)}}});function nO1(Y){switch(Y){case"smart_tool_selection":return"smart_tool_selection";case"code_execution":return"code_execution";case"passthrough":default:return"passthrough"}}function gl6(Y,Q){if(Y.connection_type!=="VIRTUAL")return!1;if(!Q||f3(Q))return!1;return Y.id===Q}async function Sn0(Y,Q,X=!1){let J=Y.id,G=await Q.storage.virtualMcps.findById(J);if(!G)throw Error(`Virtual MCP not found: ${J}`);return DB(G,Q,"passthrough",X)}async function DB(Y,Q,X,J=!1){let K=Y.connections.map((V)=>V.connection_id).map((V)=>Q.storage.connections.findById(V)),W=Y.id?await Q.storage.connections.findById(Y.id):null,Z=await Promise.all(K),H=[];if(W?.tools){for(let V of W.tools)if(UB(V))H.push(V)}let F={connections:Z.filter((V)=>V!==null&&V.status==="active"&&!gl6(V,Y.id)),virtualMcp:Y,virtualTools:H.length>0?H:void 0,superUser:J};return X==="smart_tool_selection"?new cO1(F,Q):X==="code_execution"?new pO1(F,Q):new TP(F,Q)}var Cv=j(()=>{QY();MF();Cn0();lO1();jn0()});async function y5(Y,Q,X=!1){if(Y.connection_type==="VIRTUAL")return Sn0(Y,Q,X);return zn0(Y,Q,X)}var iO1=j(()=>{On0();Cv()});async function aO1(Y,Q,X){let J=await y5(Y,Q,X),G=TU(J,{name:"mcp-mesh-enhanced",version:"1.0.0"},{capabilities:ul6,instructions:J.getInstructions()});return G.server.setRequestHandler(eF,async()=>{return await J.listResources().catch(DO({resources:[]}))}),G.server.setRequestHandler(YV,async()=>{return await J.listResourceTemplates().catch(DO({resourceTemplates:[]}))}),G.server.setRequestHandler(QV,async()=>{return await J.listPrompts().catch(DO({prompts:[]}))}),G}var ul6;var kn0=j(()=>{QY();kQ();iO1();mO1();ul6={tools:{},resources:{},prompts:{}}});function rO1(Y,Q){let X=Y.listTools.bind(Y),J=async()=>{if(Q.connection_type!=="VIRTUAL"&&Q.tools&&Q.tools.length>0)return{tools:Q.tools.map((K)=>({name:K.name,description:K.description,inputSchema:K.inputSchema,outputSchema:K.outputSchema,annotations:K.annotations,_meta:K._meta}))};return await X()};return Y.listTools=J,Y}function ml6(Y,Q,X){return async(J,G)=>{try{let K=J.params.name,W=async()=>{let{tools:H}=await X();return H.find((F)=>F.name===K)?._meta};return await new LF(Y.authInstance,Y.auth.user?.id??Y.auth.apiKey?.userId,K,Y.boundAuth,Y.auth.user?.role,Q,W).check(K),await G()}catch(K){return new Response(JSON.stringify({error:`Authorization failed: ${K.message}`}),{status:403,headers:{"Content-Type":"application/json"}})}}}function zO(Y,Q,X,J,G){let K=async(Z,H)=>{if(X.connection_type==="VIRTUAL"){let U=await Y.callTool({name:Z,arguments:H});return new Response(JSON.stringify(U),{headers:{"Content-Type":"application/json"}})}if(!X.connection_url)throw Error("Streamable tools require HTTP connection with URL");let $=X.connection_url,F={method:"tools/call",params:{name:Z,arguments:H}};if(!G.superUser){let D=await ml6(J,Q,Y.listTools.bind(Y))(F,async()=>{return new Response});if(!D.ok)return D}let V=J.connectionId&&J.connectionId!==Q?J.connectionId:void 0;return Bn0({ctx:J,enabled:ml().enabled,connectionId:Q,connectionTitle:X.title,virtualMcpId:V})(F,async()=>{let U=await Mv(X,J,G.superUser),D=X.connection_headers;if(D&&"headers"in D)Object.assign(U,D.headers);let z=new URL($);z.pathname=z.pathname.replace(/\/$/,"")+`/call-tool/${F.params.name}`;let L=JSON.parse(JSON.stringify(F.params.arguments,(E,T)=>{if(T instanceof AbortSignal)return;if(typeof T==="function"||typeof T==="symbol")return;if(T===void 0)return;return T})),w=JSON.stringify(L);return await J.tracer.startActiveSpan("mcp.proxy.callStreamableTool",{attributes:{"connection.id":Q,"tool.name":F.params.name,"request.id":J.metadata.requestId}},async(E)=>{let T=Date.now();try{let C=await fetch(z.toString(),{method:"POST",redirect:"manual",body:w,headers:{...U,"Content-Type":"application/json"}}),P=Date.now()-T;return J.meter.createHistogram("connection.proxy.streamable.duration").record(P,{"connection.id":Q,"tool.name":F.params.name,status:C.ok?"success":"error"}),J.meter.createCounter("connection.proxy.streamable.requests").add(1,{"connection.id":Q,"tool.name":F.params.name,status:C.ok?"success":"error"}),E.end(),C}catch(C){let P=C,R=Date.now()-T;throw console.error("[with-streaming-support] fetch error",{connectionId:Q,toolName:F.params.name,error:P.message,errorStack:P.stack,duration:R}),J.meter.createHistogram("connection.proxy.streamable.duration").record(R,{"connection.id":Q,"tool.name":F.params.name,status:"error"}),J.meter.createCounter("connection.proxy.streamable.errors").add(1,{"connection.id":Q,"tool.name":F.params.name,error:P.message}),E.recordException(P),E.end(),C}})})},W=Object.assign(Object.create(Object.getPrototypeOf(Y)),Y);return W.callStreamableTool=K,W}var vn0=j(()=>{vO1();Pv();WI();gO1()});var _n0=j(()=>{vn0()});var CP=j(()=>{iO1();kn0();_n0()});async function pl6(Y,Q,X,J){for(let K of Q){if(K==="*")continue;let[W]=Yn0(K),Z=Cr(W,Y);if(Z===void 0||Z===null)throw Error(`Scope references key "${W}" but it's not present in state`)}let G=Qn0(Y,Q);for(let K of G){if(K.endsWith("_self"))continue;let W=await J.storage.connections.findById(K);if(!W||W.organization_id!==X)throw Error(`Referenced connection not found: ${K}`);try{await J.access.check(K)}catch(Z){throw Error(`Access denied to referenced connection: ${K}. ${Z.message}`)}}}var ll6,dl6,oO1;var yn0=j(()=>{SO1();CP();Rr();n1();F4();rn();p$();ll6=q.object({id:q.string().describe("ID of the connection to update"),data:yT.describe("Partial connection data to update")}),dl6=q.object({item:Y5.describe("The updated connection entity")});oO1=t1({name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update an existing MCP connection in the organization",annotations:{title:"Update Connection",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:ll6,outputSchema:dl6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=TY(Q);if(!J)throw Error("User ID required to update connection");let{id:G,data:K}=Y,W=await Q.storage.connections.findById(G);if(!W||W.organization_id!==X.id)throw Error("Connection not found in organization");let Z=K.connection_type??W.connection_type,H=K.connection_url??W.connection_url;if(Z==="VIRTUAL"){let L=AU(H);if(!L)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let w=await Q.storage.virtualMcps.findById(L);if(!w)throw Error(`Virtual MCP not found: ${L}`);if(w.organization_id!==X.id)throw Error("Virtual MCP does not belong to the current organization");H=PU(L)}let $=K.configuration_state??W.configuration_state??{},F=K.configuration_scopes??W.configuration_scopes??[];if(K.configuration_state!==void 0||K.configuration_scopes!==void 0){if(K.configuration_state!==void 0)$=K.configuration_state??{};else if($===null||$===void 0)$={};if(K.configuration_scopes!==void 0)F=K.configuration_scopes??[];if(F.length>0)await pl6($,F,X.id,Q)}let V=K.connection_token??W.connection_token;if(!V)try{let w=await new NF(Q.db,Q.vault).get(G);if(w?.accessToken)V=w.accessToken}catch{}let B=await EA({id:W.id,title:K.title??W.title,connection_type:Z,connection_url:H,connection_token:V,connection_headers:K.connection_headers??W.connection_headers}).catch(()=>null),U=B?.tools?.length?B.tools:null;if(K.configuration_scopes===void 0&&B?.scopes?.length)F=B.scopes;let D={...K,connection_url:H,tools:U,configuration_state:$,configuration_scopes:F,updated_by:J},z=await Q.storage.connections.update(G,D);if((K.configuration_state!==void 0||K.configuration_scopes!==void 0)&&$&&F)try{await(await y5(z,Q,!1)).callTool({name:"ON_MCP_CONFIGURATION",arguments:{state:$,scopes:F}})}catch(L){console.error("Failed to invoke ON_MCP_CONFIGURATION callback",L)}return{item:z}}})});var cl6,sO1;var fn0=j(()=>{MG();n1();F4();p$();cl6=xS.extend({force:q.boolean().optional().describe("If true, removes this connection from all agents that reference it before deleting")}),sO1=t1({name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete a connection",annotations:{title:"Delete Connection",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:cl6,outputSchema:gS(Y5),handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=await Q.storage.connections.findById(Y.id);if(!J)throw Error(`Connection not found: ${Y.id}`);if(J.organization_id!==X.id)throw Error("Connection not found in organization");if(J.metadata?.isFixed===!0)throw Error("This connection is a fixed system connection and cannot be deleted");let K=await Q.storage.virtualMcps.listByConnectionId(X.id,Y.id);if(K.length>0)if(Y.force)await Q.storage.virtualMcps.removeConnectionReferences(Y.id);else throw Error(JSON.stringify({code:"CONNECTION_IN_USE",agentNames:K.map((W)=>W.title)}));return await Q.storage.connections.delete(Y.id),{item:J}}})});var tO1;var bn0=j(()=>{n1();F4();tO1=t1({name:"CONNECTION_TEST",description:"Test connection health and latency",annotations:{title:"Test Connection",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},inputSchema:q.object({id:q.string()}),outputSchema:q.object({id:q.string(),healthy:q.boolean(),latencyMs:q.number()}),handler:async(Y,Q)=>{let X=v0(Q);await Q.access.check();let J=await Q.storage.connections.findById(Y.id);if(!J||J.organization_id!==X.id)throw Error("Connection not found");let G=await Q.storage.connections.testConnection(Y.id);return{id:Y.id,...G}}})});var hn0=j(()=>{cc0();tc0();ec0();yn0();fn0();bn0()});import{sql as v8}from"kysely";function xn0(Y){if(Y===null||Y===void 0)return"NULL";if(typeof Y==="number")return String(Y);if(typeof Y==="boolean")return Y?"TRUE":"FALSE";if(typeof Y==="string")return`'${Y.replace(/'/g,"''")}'`;if(Y instanceof Date)return`'${Y.toISOString()}'`;return`'${JSON.stringify(Y).replace(/'/g,"''")}'`}function al6(Y,Q){let X=Y;for(let G=Q.length;G>=1;G--){let K=`$${G}`;if(X.includes(K))X=X.replaceAll(K,xn0(Q[G-1]))}let J=[];for(let G=0;G<X.length;G++)if(X[G]==="?")J.push(G);for(let G=Math.min(J.length,Q.length)-1;G>=0;G--){let K=J[G],W=xn0(Q[G]);X=X.slice(0,K)+W+X.slice(K+1)}return X}function gn0(Y){return Y.replace(/-/g,"_")}function ol6(Y){return`app_${gn0(Y)}`}function sl6(Y){return`app_role_${gn0(Y)}`}function tl6(Y){if(Y instanceof Error){let Q=Y.message.toLowerCase(),X=Y.code;return X==="3F000"||X==="42704"||X==="22023"||Q.includes("schema")&&Q.includes("does not exist")||Q.includes("role")&&Q.includes("does not exist")}return!1}async function el6(Y,Q,X){if(await v8`CREATE SCHEMA IF NOT EXISTS ${v8.id(Q)}`.execute(Y),!(await v8`
1480
1480
  SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${X}) as exists
1481
- `.execute(Y)).rows[0]?.exists)await v8`CREATE ROLE ${v8.id(X)} NOLOGIN`.execute(Y);await v8`GRANT ${v8.id(X)} TO CURRENT_USER`.execute(Y),await v8`GRANT USAGE, CREATE ON SCHEMA ${v8.id(Q)} TO ${v8.id(X)}`.execute(Y),await v8`GRANT ALL ON ALL TABLES IN SCHEMA ${v8.id(Q)} TO ${v8.id(X)}`.execute(Y),await v8`GRANT ALL ON ALL SEQUENCES IN SCHEMA ${v8.id(Q)} TO ${v8.id(X)}`.execute(Y),await v8`ALTER DEFAULT PRIVILEGES IN SCHEMA ${v8.id(Q)} GRANT ALL ON TABLES TO ${v8.id(X)}`.execute(Y),await v8`ALTER DEFAULT PRIVILEGES IN SCHEMA ${v8.id(Q)} GRANT ALL ON SEQUENCES TO ${v8.id(X)}`.execute(Y),await v8`REVOKE ALL ON SCHEMA public FROM ${v8.id(X)}`.execute(Y)}async function Yd6(Y,Q,X,J){try{return await Y.transaction().execute(async(G)=>{return await v8`SET LOCAL ROLE ${v8.id(X)}`.execute(G),await v8`SET LOCAL search_path TO ${v8.id(Q)}`.execute(G),await v8.raw(J).execute(G)})}catch(G){if(tl6(G))return await el6(Y,Q,X),await Y.transaction().execute(async(K)=>{return await v8`SET LOCAL ROLE ${v8.id(X)}`.execute(K),await v8`SET LOCAL search_path TO ${v8.id(Q)}`.execute(K),await v8.raw(J).execute(K)});throw G}}var il6,rl6,un0;var mn0=j(()=>{n1();F4();il6=q.object({results:q.array(q.unknown()).optional(),success:q.boolean().optional()});rl6=q.object({sql:q.string().describe("The SQL query to run"),params:q.array(q.any()).describe("The parameters to pass to the SQL query").optional()});un0=t1({name:"DATABASES_RUN_SQL",description:"Run a SQL query against the database",annotations:{title:"Run SQL Query",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:rl6,outputSchema:q.object({result:q.array(il6)}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=al6(Y.sql,Y.params||[]);if(!Q.connectionId)throw Error("Connection context required for database access");let J=ol6(Q.connectionId),G=sl6(Q.connectionId);return{result:[{results:(await Yd6(Q.db,J,G,X)).rows,success:!0}]}}})});var ln0,Xd6,dn0;var wF=j(()=>{n1();Yk();ln0=q.object({connectionId:q.string().optional().describe("Filter subscriptions by connection ID (optional)")}),Xd6=q.object({id:q.string().describe("Subscription ID"),connectionId:q.string().describe("Subscriber connection ID"),eventType:q.string().describe("Event type pattern"),publisher:q.string().nullable().describe("Publisher connection filter (null = all publishers)"),filter:q.string().nullable().describe("JSONPath filter expression"),enabled:q.boolean().describe("Whether subscription is enabled"),createdAt:q.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:q.string().datetime().describe("Updated timestamp (ISO 8601)")}),dn0=q.object({subscriptions:q.array(Xd6).describe("List of subscriptions")})});var eO1;var pn0=j(()=>{F4();wF();eO1=t1({name:"EVENT_PUBLISH",description:"Publish an event to the event bus. Supports immediate, scheduled (deliverAt), and recurring (cron) delivery. The source is automatically set to the caller's connection ID.",annotations:{title:"Publish Event",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},inputSchema:uS,outputSchema:mS,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=Q.connectionId;if(!J)throw Error("Connection ID required to publish events. Use a connection-scoped token.");let G=await Q.eventBus.publish(X.id,J,{type:Y.type,subject:Y.subject,data:Y.data,deliverAt:Y.deliverAt,cron:Y.cron});return{id:G.id,type:G.type,source:G.source,time:G.time}}})});var YN1;var cn0=j(()=>{F4();wF();YN1=t1({name:"EVENT_SUBSCRIBE",description:"Subscribe to events of a specific type. The subscriber is automatically set to the caller's connection.",annotations:{title:"Subscribe to Events",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:lS,outputSchema:dS,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=Q.connectionId;if(!J)throw Error("Connection ID required to subscribe. Use a connection-scoped token.");let G=await Q.eventBus.subscribe(X.id,{connectionId:J,eventType:Y.eventType,publisher:Y.publisher,filter:Y.filter});return{subscription:{id:G.id,connectionId:G.connectionId,eventType:G.eventType,publisher:G.publisher,filter:G.filter,enabled:G.enabled,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}}}})});var QN1;var nn0=j(()=>{F4();wF();QN1=t1({name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events by removing a subscription.",annotations:{title:"Unsubscribe from Events",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:nS,outputSchema:iS,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=Q.connectionId;if(!J)throw Error("Connection ID required to unsubscribe. Use a connection-scoped token.");let G=await Q.eventBus.getSubscription(X.id,Y.subscriptionId);if(!G)throw Error(`Subscription not found: ${Y.subscriptionId}`);if(G.connectionId!==J)throw Error("Cannot unsubscribe from a subscription owned by another connection");return{success:(await Q.eventBus.unsubscribe(X.id,Y.subscriptionId)).success,subscriptionId:Y.subscriptionId}}})});var XN1;var in0=j(()=>{F4();wF();XN1=t1({name:"EVENT_CANCEL",description:"Cancel a recurring event to stop future deliveries. Only the publisher can cancel their own events.",annotations:{title:"Cancel Recurring Event",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:aS,outputSchema:rS,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=Q.connectionId;if(!J)throw Error("Connection ID required to cancel events. Use a connection-scoped token.");if(!await Q.eventBus.getEvent(X.id,Y.eventId))throw Error(`Event not found: ${Y.eventId}`);if(!(await Q.eventBus.cancelEvent(X.id,Y.eventId,J)).success)throw Error("Failed to cancel event. Either the event is already completed/failed, or you are not the publisher.");return{success:!0,eventId:Y.eventId}}})});var JN1;var an0=j(()=>{F4();wF();JN1=t1({name:"EVENT_ACK",description:"Acknowledge delivery of an event. Call after successfully processing an event received via ON_EVENTS with retryAfter.",annotations:{title:"Acknowledge Event",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:oS,outputSchema:sS,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=Q.connectionId;if(!J)throw Error("Connection ID required to acknowledge events. Use a connection-scoped token.");if(!(await Q.eventBus.ackEvent(X.id,Y.eventId,J)).success)throw Error("Failed to acknowledge event. Either the event was not found, already delivered, or you are not a subscriber.");return{success:!0,eventId:Y.eventId}}})});var GN1;var rn0=j(()=>{F4();wF();GN1=t1({name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions, optionally filtered by connection ID.",annotations:{title:"List Event Subscriptions",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:ln0,outputSchema:dn0,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);return await Q.access.check(),{subscriptions:(await Q.eventBus.listSubscriptions(X.id,Y.connectionId)).map((G)=>({id:G.id,connectionId:G.connectionId,eventType:G.eventType,publisher:G.publisher,filter:G.filter,enabled:G.enabled,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}))}}})});var WN1;var on0=j(()=>{F4();wF();WN1=t1({name:"EVENT_SYNC_SUBSCRIPTIONS",description:"Sync subscriptions to desired state. Creates new, deletes removed, updates changed filters. Subscriptions are identified by (eventType, publisher).",annotations:{title:"Sync Event Subscriptions",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:pS,outputSchema:cS,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=Q.connectionId;if(!J)throw Error("Connection ID required to sync subscriptions. Use a connection-scoped token.");let G=await Q.eventBus.syncSubscriptions(X.id,{connectionId:J,subscriptions:Y.subscriptions});return{created:G.created,updated:G.updated,deleted:G.deleted,unchanged:G.unchanged,subscriptions:G.subscriptions.map((K)=>({id:K.id,connectionId:K.connectionId,eventType:K.eventType,publisher:K.publisher,filter:K.filter,enabled:K.enabled,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt,updatedAt:K.updatedAt instanceof Date?K.updatedAt.toISOString():K.updatedAt}))}}})});var sn0=j(()=>{pn0();cn0();nn0();in0();an0();rn0();on0();wF()});var RP=j(()=>{Ix()});function tn0(){return`/icons/capy-${Math.floor(Math.random()*39)+0}.png`}var Gd6,Wd6,ZN1;var en0=j(()=>{n1();F4();RP();Gd6=q.object({data:bT.describe("Data for the new virtual MCP")}),Wd6=q.object({item:bG.describe("The created virtual MCP entity")}),ZN1=t1({name:"COLLECTION_VIRTUAL_MCP_CREATE",description:"Create a new Virtual MCP",annotations:{title:"Create Virtual MCP",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:Gd6,outputSchema:Wd6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=TY(Q);if(!J)throw Error("User ID required to create virtual MCP");let G={...Y.data,icon:Y.data.icon??tn0()};return{item:await Q.storage.virtualMcps.create(X.id,J,G)}}})});function Zd6(Y){let Q=[],X=0;while(X<Y.length){let J=Y[X];if(J==="%")Q.push(".*");else if(J==="_")Q.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))Q.push("\\"+J);else Q.push(J);X++}return Q.join("")}function zB(Y){return typeof Y==="string"||typeof Y==="number"}function KN1(Y,Q){let X=Q.split("."),J=Y;for(let G of X){if(J==null||typeof J!=="object")return;J=J[G]}return J}function Kd6(Y,Q){return Y.connections.some((X)=>X.connection_id===Q)}function jr(Y,Q){if("conditions"in Q){let{operator:Z,conditions:H}=Q;switch(Z){case"and":return H.every(($)=>jr(Y,$));case"or":return H.some(($)=>jr(Y,$));case"not":return!H.every(($)=>jr(Y,$));default:return!0}}let{field:X,operator:J,value:G}=Q,K=X.join(".");if(K==="connection_id"){if(J!=="eq"||typeof G!=="string")return!1;return Kd6(Y,G)}let W=KN1(Y,K);switch(J){case"eq":return W===G;case"gt":return zB(W)&&zB(G)&&W>G;case"gte":return zB(W)&&zB(G)&&W>=G;case"lt":return zB(W)&&zB(G)&&W<G;case"lte":return zB(W)&&zB(G)&&W<=G;case"in":return Array.isArray(G)&&G.includes(W);case"like":if(typeof W!=="string"||typeof G!=="string")return!1;if(G.length>100)return!1;let Z=Zd6(G);return new RegExp(`^${Z}$`,"i").test(W);case"contains":if(typeof W!=="string"||typeof G!=="string")return!1;return W.toLowerCase().includes(G.toLowerCase());default:return!0}}function Hd6(Y,Q){return[...Y].sort((X,J)=>{for(let G of Q){let K=G.field.join("."),W=KN1(X,K),Z=KN1(J,K),H=0;if(W==null&&Z==null)continue;if(W==null)H=G.nulls==="first"?-1:1;else if(Z==null)H=G.nulls==="first"?1:-1;else if(typeof W==="string"&&typeof Z==="string")H=W.localeCompare(Z);else if(typeof W==="number"&&typeof Z==="number")H=W-Z;else H=String(W).localeCompare(String(Z));if(H!==0)return G.direction==="desc"?-H:H}return 0})}var $d6,Fd6,HN1;var Yi0=j(()=>{MG();F4();RP();$d6=lZ,Fd6=n$(bG),HN1=t1({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:$d6,outputSchema:Fd6,handler:async(Y,Q)=>{await Q.access.check();let X=v0(Q),J=Y.where&&!("conditions"in Y.where)&&Y.where.field.join(".")==="connection_id"&&Y.where.operator==="eq"&&typeof Y.where.value==="string"?Y.where.value:void 0,K=J?await Q.storage.virtualMcps.listByConnectionId(X.id,J):await Q.storage.virtualMcps.list(X.id);if(Y.where)K=K.filter((V)=>jr(V,Y.where));if(Y.orderBy&&Y.orderBy.length>0)K=Hd6(K,Y.orderBy);let W=K.length,Z=Y.offset??0,H=Y.limit??100,$=K.slice(Z,Z+H),F=Z+H<W;return{items:$,totalCount:W,hasMore:F}}})});var Vd6,qd6,$N1;var Qi0=j(()=>{n1();F4();RP();Vd6=q.object({id:q.string().describe("ID of the virtual MCP to retrieve")}),qd6=q.object({item:bG.nullable().describe("The retrieved virtual MCP, or null if not found")}),$N1=t1({name:"COLLECTION_VIRTUAL_MCP_GET",description:"Get an MCP virtual MCP by ID",annotations:{title:"Get Virtual MCP",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:Vd6,outputSchema:qd6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.id);if(J&&J.organization_id!==X.id)return{item:null};if(!J)return{item:null};return{item:J}}})});var Bd6,Ud6,FN1;var Xi0=j(()=>{n1();F4();RP();Bd6=q.object({id:q.string().describe("ID of the virtual MCP to update"),data:hT.describe("Partial virtual MCP data to update")}),Ud6=q.object({item:bG.describe("The updated virtual MCP entity")}),FN1=t1({name:"COLLECTION_VIRTUAL_MCP_UPDATE",description:"Update an MCP virtual MCP",annotations:{title:"Update Virtual MCP",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:Bd6,outputSchema:Ud6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=TY(Q);if(!J)throw Error("User ID required to update virtual MCP");let G=await Q.storage.virtualMcps.findById(Y.id);if(!G)throw Error(`Virtual MCP not found: ${Y.id}`);if(G.organization_id!==X.id)throw Error(`Virtual MCP not found: ${Y.id}`);return{item:await Q.storage.virtualMcps.update(Y.id,J,Y.data)}}})});var Dd6,zd6,VN1;var Ji0=j(()=>{n1();F4();RP();Dd6=q.object({id:q.string().describe("ID of the virtual MCP to delete")}),zd6=q.object({item:bG.describe("The deleted virtual MCP entity")}),VN1=t1({name:"COLLECTION_VIRTUAL_MCP_DELETE",description:"Delete an MCP virtual MCP",annotations:{title:"Delete Virtual MCP",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:Dd6,outputSchema:zd6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.id);if(!J)throw Error(`Virtual MCP not found: ${Y.id}`);if(J.organization_id!==X.id)throw Error(`Virtual MCP not found: ${Y.id}`);return await Q.storage.virtualMcps.delete(Y.id),{item:J}}})});var Gi0=j(()=>{en0();Yi0();Qi0();Xi0();Ji0()});var Nd6,Ld6,qN1;var Wi0=j(()=>{n1();F4();MF();Nd6=q.object({virtual_mcp_id:q.string().describe("ID of the Virtual MCP to add the tool to"),data:Nn0.describe("Virtual tool data")}),Ld6=q.object({item:Q3.describe("The created virtual tool")}),qN1=t1({name:"COLLECTION_VIRTUAL_TOOLS_CREATE",description:"Create a new virtual tool on a Virtual MCP. The tool code should be a JavaScript ES module that exports a default async function: export default async (tools, args) => { ... }. Specify connection_dependencies to indicate which connections this tool uses.",annotations:{title:"Create Virtual Tool",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:Nd6,outputSchema:Ld6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!J||J.organization_id!==X.id)throw Error(`Virtual MCP not found: ${Y.virtual_mcp_id}`);let G=Y.data.connection_dependencies??[];return{item:await Q.storage.virtualMcps.createVirtualTool(Y.virtual_mcp_id,Y.data,G)}}})});var Md6,wd6,BN1;var Zi0=j(()=>{n1();F4();MF();Md6=q.object({virtual_mcp_id:q.string().describe("ID of the Virtual MCP to list tools for"),limit:q.number().int().min(1).max(1000).optional().describe("Maximum number of items to return"),offset:q.number().int().min(0).optional().describe("Number of items to skip")}),wd6=q.object({items:q.array(Q3).describe("Array of virtual tools"),totalCount:q.number().int().min(0).optional().describe("Total number of virtual tools"),hasMore:q.boolean().optional().describe("Whether there are more items available")}),BN1=t1({name:"COLLECTION_VIRTUAL_TOOLS_LIST",description:"List all virtual tools for a Virtual MCP",annotations:{title:"List Virtual Tools",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:Md6,outputSchema:wd6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!J||J.organization_id!==X.id)return{items:[],totalCount:0,hasMore:!1};let G=await Q.storage.virtualMcps.listVirtualTools(Y.virtual_mcp_id),K=G.length,W=Y.offset??0,Z=Y.limit??100,H=G.slice(W,W+Z),$=W+Z<K;return{items:H,totalCount:K,hasMore:$}}})});var Ad6,Pd6,UN1;var Ki0=j(()=>{n1();F4();MF();Ad6=q.object({virtual_mcp_id:q.string().describe("ID of the Virtual MCP"),name:q.string().describe("Name of the virtual tool to retrieve")}),Pd6=q.object({item:Q3.nullable().describe("The retrieved virtual tool, or null if not found")}),UN1=t1({name:"COLLECTION_VIRTUAL_TOOLS_GET",description:"Get a virtual tool by name from a Virtual MCP",annotations:{title:"Get Virtual Tool",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:Ad6,outputSchema:Pd6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!J||J.organization_id!==X.id)return{item:null};return{item:await Q.storage.virtualMcps.getVirtualTool(Y.virtual_mcp_id,Y.name)}}})});var Ed6,Td6,DN1;var Hi0=j(()=>{n1();F4();MF();Ed6=q.object({virtual_mcp_id:q.string().describe("ID of the Virtual MCP"),name:q.string().describe("Current name of the virtual tool to update"),data:Ln0.describe("Partial virtual tool data to update")}),Td6=q.object({item:Q3.describe("The updated virtual tool")}),DN1=t1({name:"COLLECTION_VIRTUAL_TOOLS_UPDATE",description:"Update an existing virtual tool on a Virtual MCP. Specify connection_dependencies to update which connections this tool uses.",annotations:{title:"Update Virtual Tool",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:Ed6,outputSchema:Td6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!J||J.organization_id!==X.id)throw Error(`Virtual MCP not found: ${Y.virtual_mcp_id}`);if(!await Q.storage.virtualMcps.getVirtualTool(Y.virtual_mcp_id,Y.name))throw Error(`Virtual tool not found: ${Y.name}`);let K=Y.data.connection_dependencies;return{item:await Q.storage.virtualMcps.updateVirtualTool(Y.virtual_mcp_id,Y.name,Y.data,K)}}})});var Cd6,Rd6,zN1;var $i0=j(()=>{n1();F4();MF();Cd6=q.object({virtual_mcp_id:q.string().describe("ID of the Virtual MCP"),name:q.string().describe("Name of the virtual tool to delete")}),Rd6=q.object({item:Q3.describe("The deleted virtual tool")}),zN1=t1({name:"COLLECTION_VIRTUAL_TOOLS_DELETE",description:"Delete a virtual tool from a Virtual MCP",annotations:{title:"Delete Virtual Tool",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:Cd6,outputSchema:Rd6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!J||J.organization_id!==X.id)throw Error(`Virtual MCP not found: ${Y.virtual_mcp_id}`);let G=await Q.storage.virtualMcps.getVirtualTool(Y.virtual_mcp_id,Y.name);if(!G)throw Error(`Virtual tool not found: ${Y.name}`);return await Q.storage.virtualMcps.deleteVirtualTool(Y.virtual_mcp_id,Y.name),{item:G}}})});var Fi0=j(()=>{Wi0();Zi0();Ki0();Hi0();$i0()});var jd6,ON1;var Vi0=j(()=>{F4();n1();jd6=q.object({id:q.string().optional().describe("Unique log identifier"),organizationId:q.string().describe("Organization ID"),connectionId:q.string().describe("Connection ID"),connectionTitle:q.string().describe("Connection display name"),toolName:q.string().describe("Name of the tool that was called"),input:q.record(q.string(),q.unknown()).describe("Redacted tool input"),output:q.record(q.string(),q.unknown()).describe("Redacted tool output"),isError:q.boolean().describe("Whether the call resulted in an error"),errorMessage:q.string().nullish().describe("Error message if applicable"),durationMs:q.number().describe("Call duration in milliseconds"),timestamp:q.string().describe("ISO 8601 timestamp of the call"),userId:q.string().nullish().describe("User who triggered the call"),requestId:q.string().describe("Unique request identifier"),userAgent:q.string().nullish().describe("Client identifier (x-mesh-client header)"),virtualMcpId:q.string().nullish().describe("Virtual MCP (Agent) ID if routed through an agent"),properties:q.record(q.string(),q.string()).nullish().describe("Custom key-value metadata attached to the log")}),ON1=t1({name:"MONITORING_LOGS_LIST",description:"List monitoring logs for tool calls in the organization",annotations:{title:"List Monitoring Logs",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({connectionId:q.string().optional().describe("Filter by connection ID"),excludeConnectionIds:q.array(q.string()).optional().describe("Exclude logs from these connection IDs (e.g. system connections)"),virtualMcpId:q.string().optional().describe("Filter by Virtual MCP (Agent) ID"),toolName:q.string().optional().describe("Filter by tool name"),isError:q.boolean().optional().describe("Filter by error status"),startDate:q.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:q.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)"),limit:q.number().default(20).describe("Maximum number of results"),offset:q.number().default(0).describe("Offset for pagination"),properties:q.record(q.string(),q.string()).optional().describe("Filter by exact property key=value matches"),propertyKeys:q.array(q.string()).optional().describe("Filter by logs that have these property keys"),propertyPatterns:q.record(q.string(),q.string()).optional().describe("Filter by property value patterns (SQL LIKE, use % as wildcard)"),propertyInValues:q.record(q.string(),q.string()).optional().describe("Filter by exact match within comma-separated values (e.g., user_tags in 'Engineering')")}),outputSchema:q.object({logs:q.array(jd6).describe("Array of monitoring logs"),total:q.number().describe("Total number of logs matching filters"),offset:q.number().describe("Current offset for pagination"),limit:q.number().describe("Current limit for pagination")}),handler:async(Y,Q)=>{let X=v0(Q),G=Y.properties||Y.propertyKeys||Y.propertyPatterns||Y.propertyInValues?{properties:Y.properties,propertyKeys:Y.propertyKeys,propertyPatterns:Y.propertyPatterns,propertyInValues:Y.propertyInValues}:void 0,K={organizationId:X.id,connectionId:Y.connectionId,excludeConnectionIds:Y.excludeConnectionIds,virtualMcpId:Y.virtualMcpId,toolName:Y.toolName,isError:Y.isError,startDate:Y.startDate?new Date(Y.startDate):void 0,endDate:Y.endDate?new Date(Y.endDate):void 0,limit:Y.limit,offset:Y.offset,propertyFilters:G},W=await Q.storage.monitoring.query(K);return{logs:W.logs.map((Z)=>({...Z,timestamp:Z.timestamp instanceof Date?Z.timestamp.toISOString():Z.timestamp})),total:W.total,offset:Y.offset,limit:Y.limit}}})});var NN1;var qi0=j(()=>{F4();n1();NN1=t1({name:"MONITORING_STATS",description:"Get aggregated statistics for tool call monitoring",annotations:{title:"Get Monitoring Stats",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({startDate:q.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:q.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)")}),outputSchema:q.object({totalCalls:q.number().describe("Total number of tool calls"),errorRate:q.number().describe("Error rate as a decimal (0 to 1)"),avgDurationMs:q.number().describe("Average call duration in milliseconds"),errorRatePercent:q.string().describe("Error rate as a percentage string")}),handler:async(Y,Q)=>{let J={organizationId:v0(Q).id,startDate:Y.startDate?new Date(Y.startDate):void 0,endDate:Y.endDate?new Date(Y.endDate):void 0},G=await Q.storage.monitoring.getStats(J);return{...G,errorRatePercent:(G.errorRate*100).toFixed(2)}}})});var Bi0=j(()=>{Vi0();qi0()});var kd6,vd6,_d6,yd6,fd6,Rv,Iv,OB,bd6,hd6,Ui0;var IP=j(()=>{n1();kd6=q.enum(["sum","avg","min","max","count","last"]).describe("Aggregation function to apply"),vd6=q.enum(["metric","timeseries","table"]).describe("Widget display type"),_d6=q.object({path:q.string().describe("JSONPath to extract value, e.g., '$.usage.total_tokens'"),from:q.enum(["input","output"]).describe("Extract from tool call input or output")}),yd6=q.object({fn:kd6,groupBy:q.string().optional().describe("Optional JSONPath for grouping results"),interval:q.string().optional().describe("For timeseries widgets: interval like '1h', '1d', '15m'")}),fd6=q.object({connectionIds:q.array(q.string()).optional().describe("Filter to specific connections"),toolNames:q.array(q.string()).optional().describe("Filter to specific tools")}),Rv=q.object({id:q.string().describe("Unique widget identifier"),name:q.string().describe("Widget display name"),type:vd6,source:_d6,aggregation:yd6,filter:fd6.optional()}),Iv=q.object({connectionIds:q.array(q.string()).optional().describe("Filter to specific connections"),virtualMcpIds:q.array(q.string()).optional().describe("Filter to specific virtual MCPs/agents"),toolNames:q.array(q.string()).optional().describe("Filter to specific tools"),propertyFilters:q.record(q.string(),q.string()).optional().describe("Filter by exact metadata property key=value matches (e.g., { environment: 'production' })")}),OB=q.object({id:q.string().describe("Unique dashboard identifier"),organizationId:q.string().describe("Organization ID"),name:q.string().describe("Dashboard name"),description:q.string().nullable().describe("Dashboard description"),filters:Iv.nullable().describe("Global filters applied to all widgets"),widgets:q.array(Rv).describe("Widget definitions"),createdBy:q.string().describe("User ID who created the dashboard"),createdAt:q.string().describe("Creation timestamp"),updatedAt:q.string().describe("Last update timestamp")}),bd6=q.object({key:q.string().describe("Group key value"),value:q.number().describe("Aggregated value for this group")}),hd6=q.object({timestamp:q.string().describe("Time bucket timestamp"),value:q.number().describe("Aggregated value for this time bucket")}),Ui0=q.object({widgetId:q.string().describe("Widget ID this result is for"),value:q.number().nullable().describe("Aggregated value (for metric type)"),groups:q.array(bd6).optional().describe("Grouped results (when groupBy is specified)"),timeseries:q.array(hd6).optional().describe("Timeseries data (for timeseries type)")})});var LN1;var Di0=j(()=>{F4();n1();IP();LN1=t1({name:"MONITORING_DASHBOARD_CREATE",description:"Create a new monitoring dashboard with JSONPath widgets",annotations:{title:"Create Monitoring Dashboard",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:q.object({name:q.string().min(1).describe("Dashboard name"),description:q.string().optional().describe("Dashboard description"),filters:Iv.optional().describe("Global filters applied to all widgets"),widgets:q.array(Rv).min(1).describe("Widget definitions (at least one required)")}),outputSchema:OB,handler:async(Y,Q)=>{let X=v0(Q),J=Q.auth.user?.id;if(!J)throw Error("User authentication required");let G=await Q.storage.monitoringDashboards.create(X.id,J,{name:Y.name,description:Y.description,filters:Y.filters,widgets:Y.widgets});return{id:G.id,organizationId:G.organizationId,name:G.name,description:G.description,filters:G.filters,widgets:G.widgets,createdBy:G.createdBy,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}}})});var MN1;var zi0=j(()=>{F4();n1();IP();MN1=t1({name:"MONITORING_DASHBOARD_GET",description:"Get a monitoring dashboard by ID",annotations:{title:"Get Monitoring Dashboard",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({id:q.string().describe("Dashboard ID")}),outputSchema:OB.nullable(),handler:async(Y,Q)=>{let X=v0(Q),J=await Q.storage.monitoringDashboards.get(Y.id);if(!J||J.organizationId!==X.id)return null;return{id:J.id,organizationId:J.organizationId,name:J.name,description:J.description,filters:J.filters,widgets:J.widgets,createdBy:J.createdBy,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt,updatedAt:J.updatedAt instanceof Date?J.updatedAt.toISOString():J.updatedAt}}})});var wN1;var Oi0=j(()=>{F4();n1();IP();wN1=t1({name:"MONITORING_DASHBOARD_LIST",description:"List all monitoring dashboards for the organization",annotations:{title:"List Monitoring Dashboards",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({}),outputSchema:q.object({dashboards:q.array(OB).describe("List of dashboards"),total:q.number().describe("Total number of dashboards")}),handler:async(Y,Q)=>{let X=v0(Q),J=await Q.storage.monitoringDashboards.list(X.id);return{dashboards:J.map((G)=>({id:G.id,organizationId:G.organizationId,name:G.name,description:G.description,filters:G.filters,widgets:G.widgets,createdBy:G.createdBy,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt})),total:J.length}}})});var AN1;var Ni0=j(()=>{F4();n1();IP();AN1=t1({name:"MONITORING_DASHBOARD_UPDATE",description:"Update an existing monitoring dashboard",annotations:{title:"Update Monitoring Dashboard",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({id:q.string().describe("Dashboard ID to update"),name:q.string().optional().describe("New dashboard name"),description:q.string().nullable().optional().describe("New dashboard description"),filters:Iv.nullable().optional().describe("New global filters"),widgets:q.array(Rv).optional().describe("New widget definitions")}),outputSchema:OB,handler:async(Y,Q)=>{let X=v0(Q),J=await Q.storage.monitoringDashboards.get(Y.id);if(!J||J.organizationId!==X.id)throw Error(`Dashboard ${Y.id} not found`);let G={};if(Y.name!==void 0)G.name=Y.name;if(Y.description!==void 0)G.description=Y.description;if(Y.filters!==void 0)G.filters=Y.filters;if(Y.widgets!==void 0)G.widgets=Y.widgets;let K=await Q.storage.monitoringDashboards.update(Y.id,G);return{id:K.id,organizationId:K.organizationId,name:K.name,description:K.description,filters:K.filters,widgets:K.widgets,createdBy:K.createdBy,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt,updatedAt:K.updatedAt instanceof Date?K.updatedAt.toISOString():K.updatedAt}}})});var PN1;var Li0=j(()=>{F4();n1();PN1=t1({name:"MONITORING_DASHBOARD_DELETE",description:"Delete a monitoring dashboard",annotations:{title:"Delete Monitoring Dashboard",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({id:q.string().describe("Dashboard ID to delete")}),outputSchema:q.object({success:q.boolean().describe("Whether the deletion was successful")}),handler:async(Y,Q)=>{let X=v0(Q),J=await Q.storage.monitoringDashboards.get(Y.id);if(!J||J.organizationId!==X.id)throw Error(`Dashboard ${Y.id} not found`);return await Q.storage.monitoringDashboards.delete(Y.id),{success:!0}}})});var EN1;var Mi0=j(()=>{F4();n1();IP();EN1=t1({name:"MONITORING_DASHBOARD_QUERY",description:"Execute a dashboard's widgets and return aggregated monitoring data",annotations:{title:"Query Monitoring Dashboard",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({dashboardId:q.string().describe("Dashboard ID to query"),timeRange:q.object({startDate:q.string().datetime().describe("Start of time range (ISO 8601)"),endDate:q.string().datetime().describe("End of time range (ISO 8601)")}).optional().describe("Time range for the query (defaults to last 24 hours)"),propertyFilters:q.object({properties:q.record(q.string(),q.string()).optional().describe("Exact match: property key equals value"),propertyKeys:q.array(q.string()).optional().describe("Exists: filter logs that have these property keys"),propertyPatterns:q.record(q.string(),q.string()).optional().describe("Pattern match: property value matches pattern (SQL LIKE, use % as wildcard)"),propertyInValues:q.record(q.string(),q.string()).optional().describe("In match: exact match within comma-separated values")}).optional().describe("Runtime property filters applied to all widgets (merged with dashboard-level filters)")}),outputSchema:q.object({dashboardId:q.string().describe("Dashboard ID"),results:q.array(Ui0).describe("Widget query results"),timeRange:q.object({startDate:q.string(),endDate:q.string()}).describe("Time range used for the query")}),handler:async(Y,Q)=>{let X=v0(Q),J=await Q.storage.monitoringDashboards.get(Y.dashboardId);if(!J||J.organizationId!==X.id)throw Error(`Dashboard ${Y.dashboardId} not found`);let G=new Date,K=Y.timeRange?.startDate?new Date(Y.timeRange.startDate):new Date(G.getTime()-86400000),W=Y.timeRange?.endDate?new Date(Y.timeRange.endDate):G,Z=await Promise.all(J.widgets.map(async(H)=>{let $=J.filters?.propertyFilters,F=Y.propertyFilters,V=$||F?{properties:{...$,...F?.properties},propertyKeys:F?.propertyKeys,propertyPatterns:F?.propertyPatterns,propertyInValues:F?.propertyInValues}:void 0,B={connectionIds:H.filter?.connectionIds??J.filters?.connectionIds??void 0,virtualMcpIds:J.filters?.virtualMcpIds??void 0,toolNames:H.filter?.toolNames??J.filters?.toolNames??void 0,startDate:K,endDate:W,propertyFilters:V};try{let U=await Q.storage.monitoring.aggregate({organizationId:X.id,path:H.source.path,from:H.source.from,aggregation:H.aggregation.fn,groupBy:H.aggregation.groupBy,interval:H.aggregation.interval,filters:B});return{widgetId:H.id,value:U.value,groups:U.groups,timeseries:U.timeseries}}catch(U){return console.error(`Widget ${H.id} aggregation failed:`,U),{widgetId:H.id,value:null,groups:void 0,timeseries:void 0}}}));return{dashboardId:Y.dashboardId,results:Z,timeRange:{startDate:K.toISOString(),endDate:W.toISOString()}}}})});var xd6,TN1;var wi0=j(()=>{F4();n1();xd6=q.object({type:q.enum(["metric","timeseries","table"]),source:q.object({path:q.string().describe("JSONPath to extract value from"),from:q.enum(["input","output"]).describe("Extract from input or output")}),aggregation:q.object({fn:q.enum(["sum","avg","min","max","count","last"]).describe("Aggregation function"),groupBy:q.string().optional().describe("JSONPath for grouping (table)"),interval:q.string().optional().describe("Time interval for timeseries (15m, 1h, 1d)")}),filter:q.object({connectionIds:q.array(q.string()).optional(),toolNames:q.array(q.string()).optional()}).optional()}),TN1=t1({name:"MONITORING_WIDGET_PREVIEW",description:"Preview a widget aggregation without saving. Used to test queries in the dashboard editor.",annotations:{title:"Preview Monitoring Widget",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({widget:xd6.describe("Widget configuration to preview"),timeRange:q.object({startDate:q.string().datetime().describe("Start of time range (ISO 8601)"),endDate:q.string().datetime().describe("End of time range (ISO 8601)")}).optional().describe("Time range for the query (defaults to last 24 hours)"),propertyFilters:q.object({properties:q.record(q.string(),q.string()).optional().describe("Exact match: property key equals value"),propertyKeys:q.array(q.string()).optional().describe("Exists: filter logs that have these property keys"),propertyPatterns:q.record(q.string(),q.string()).optional().describe("Pattern match: property value matches pattern (SQL LIKE)"),propertyInValues:q.record(q.string(),q.string()).optional().describe("In match: exact match within comma-separated values")}).optional().describe("Property filters to apply")}),outputSchema:q.object({value:q.number().nullable().optional().describe("Aggregated value"),groups:q.array(q.object({key:q.string(),value:q.number()})).optional().describe("Grouped results for table widgets"),timeseries:q.array(q.object({timestamp:q.string(),value:q.number()})).optional().describe("Timeseries data points"),matchedRecords:q.number().describe("Number of records that matched"),timeRange:q.object({startDate:q.string(),endDate:q.string()}).describe("Time range used for the query")}),handler:async(Y,Q)=>{let X=v0(Q),{widget:J,timeRange:G}=Y,K=new Date,W=G?.startDate?new Date(G.startDate):new Date(K.getTime()-86400000),Z=G?.endDate?new Date(G.endDate):K,H={connectionIds:J.filter?.connectionIds,toolNames:J.filter?.toolNames,startDate:W,endDate:Z,propertyFilters:Y.propertyFilters};try{let $=await Q.storage.monitoring.countMatched({organizationId:X.id,path:J.source.path,from:J.source.from,filters:H}),F=await Q.storage.monitoring.aggregate({organizationId:X.id,path:J.source.path,from:J.source.from,aggregation:J.aggregation.fn,groupBy:J.aggregation.groupBy,interval:J.aggregation.interval,filters:H});return{value:F.value,groups:F.groups,timeseries:F.timeseries,matchedRecords:$,timeRange:{startDate:W.toISOString(),endDate:Z.toISOString()}}}catch($){return console.error("Widget preview aggregation failed:",$),{value:null,matchedRecords:0,timeRange:{startDate:W.toISOString(),endDate:Z.toISOString()}}}}})});var Ai0=j(()=>{Di0();zi0();Oi0();Ni0();Li0();Mi0();wi0()});var CN1;var Pi0=j(()=>{n1();F4();CN1=t1({name:"ORGANIZATION_CREATE",description:"Create a new organization",annotations:{title:"Create Organization",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:q.object({slug:q.string().min(1).max(50).regex(/^[a-z0-9-]+$/,"Slug must be lowercase alphanumeric with hyphens"),name:q.string().min(1).max(255),description:q.string().optional()}),outputSchema:q.object({id:q.string(),name:q.string(),slug:q.string(),logo:q.string().nullable().optional(),metadata:q.any().optional(),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),members:q.array(q.any()).optional()}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=TY(Q);if(!X)throw Error("User ID required to create organization");let J=await Q.boundAuth.organization.create({name:Y.name,slug:Y.slug,metadata:Y.description?{description:Y.description}:void 0,userId:X});if(!J)throw Error("Failed to create organization");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var RN1;var Ei0=j(()=>{n1();F4();RN1=t1({name:"ORGANIZATION_LIST",description:"List all organizations user has access to",annotations:{title:"List Organizations",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({userId:q.string().optional()}),outputSchema:q.object({organizations:q.array(q.object({id:q.string(),name:q.string(),slug:q.string(),logo:q.string().nullable().optional(),metadata:q.any().optional(),createdAt:q.string().datetime().describe("ISO 8601 timestamp")}))}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=TY(Q),J=Y.userId||X;if(!J)throw Error("User ID required to list organizations");return{organizations:(await Q.boundAuth.organization.list(J)).map((K)=>({...K,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt}))}}})});var IN1;var Ti0=j(()=>{n1();F4();IN1=t1({name:"ORGANIZATION_GET",description:"Get organization details by slug or ID",annotations:{title:"Get Organization",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({}),outputSchema:q.object({id:q.string(),name:q.string(),slug:q.string(),logo:q.string().nullable().optional(),metadata:q.any().optional(),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),members:q.array(q.any()).optional(),invitations:q.array(q.any()).optional()}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=await Q.boundAuth.organization.get();if(!X)throw Error("No active organization found");let J=new Date,G=X.invitations?.filter((K)=>new Date(K.expiresAt)>J);return{...X,invitations:G,createdAt:X.createdAt instanceof Date?X.createdAt.toISOString():X.createdAt}}})});var jN1;var Ci0=j(()=>{n1();F4();jN1=t1({name:"ORGANIZATION_UPDATE",description:"Update an existing organization",annotations:{title:"Update Organization",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({id:q.string(),slug:q.string().min(1).max(50).regex(/^[a-z0-9-]+$/).optional(),name:q.string().min(1).max(255).optional(),description:q.string().optional()}),outputSchema:q.object({id:q.string(),name:q.string(),slug:q.string(),logo:q.string().nullable().optional(),metadata:q.any().optional(),createdAt:q.string().datetime().describe("ISO 8601 timestamp")}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X={};if(Y.name)X.name=Y.name;if(Y.slug)X.slug=Y.slug;if(Y.description)X.metadata={description:Y.description};let J=await Q.boundAuth.organization.update({organizationId:Y.id,data:X});if(!J)throw Error("Failed to update organization");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var SN1;var Ri0=j(()=>{n1();F4();SN1=t1({name:"ORGANIZATION_DELETE",description:"Delete an organization",annotations:{title:"Delete Organization",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({id:q.string()}),outputSchema:q.object({success:q.boolean(),id:q.string()}),handler:async(Y,Q)=>{return D0(Q),await Q.access.check(),await Q.boundAuth.organization.delete(Y.id),{success:!0,id:Y.id}}})});var jv;var kN1=j(()=>{n1();jv=q.object({title:q.string(),url:q.string(),icon:q.string()})});var vN1;var Ii0=j(()=>{n1();F4();kN1();vN1=t1({name:"ORGANIZATION_SETTINGS_GET",description:"Get organization-level settings",annotations:{title:"Get Organization Settings",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({}),outputSchema:q.object({organizationId:q.string(),sidebar_items:q.array(jv).nullable().optional(),enabled_plugins:q.array(q.string()).nullable().optional(),createdAt:q.string().datetime().optional().describe("ISO 8601 timestamp"),updatedAt:q.string().datetime().optional().describe("ISO 8601 timestamp")}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=Q.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");let J=await Q.storage.organizationSettings.get(X);if(!J)return{organizationId:X};return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt,updatedAt:J.updatedAt instanceof Date?J.updatedAt.toISOString():J.updatedAt}}})});var _N1;var ji0=j(()=>{n1();F4();kN1();_N1=t1({name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization-level settings",annotations:{title:"Update Organization Settings",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({organizationId:q.string(),sidebar_items:q.array(jv).optional(),enabled_plugins:q.array(q.string()).optional()}),outputSchema:q.object({organizationId:q.string(),sidebar_items:q.array(jv).nullable().optional(),enabled_plugins:q.array(q.string()).nullable().optional(),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),updatedAt:q.string().datetime().describe("ISO 8601 timestamp")}),handler:async(Y,Q)=>{if(D0(Q),await Q.access.check(),Q.organization&&Q.organization.id!==Y.organizationId)throw Error("Cannot update settings for a different organization");let X=await Q.storage.organizationSettings.upsert(Y.organizationId,{sidebar_items:Y.sidebar_items,enabled_plugins:Y.enabled_plugins});return{...X,createdAt:X.createdAt instanceof Date?X.createdAt.toISOString():X.createdAt,updatedAt:X.updatedAt instanceof Date?X.updatedAt.toISOString():X.updatedAt}}})});var yN1;var Si0=j(()=>{n1();F4();yN1=t1({name:"ORGANIZATION_MEMBER_ADD",description:"Add a member to an organization",annotations:{title:"Add Organization Member",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({organizationId:q.string().optional(),userId:q.string(),role:q.array(q.string())}),outputSchema:q.object({id:q.string(),organizationId:q.string(),userId:q.string(),role:q.union([q.string(),q.array(q.string())]),createdAt:q.string().datetime().describe("ISO 8601 timestamp")}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=Y.organizationId||Q.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");if(X!==Q.organization?.id)throw Error("Organization ID does not match authenticated organization");let J=await Q.boundAuth.organization.addMember({organizationId:X,userId:Y.userId,role:Y.role});if(!J)throw Error("Failed to add member");return{...J,role:J.role,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var fN1;var ki0=j(()=>{n1();F4();fN1=t1({name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove a member from an organization",annotations:{title:"Remove Organization Member",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({organizationId:q.string().optional(),memberIdOrEmail:q.string()}),outputSchema:q.object({success:q.boolean(),memberIdOrEmail:q.string()}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=Y.organizationId||Q.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");return await Q.boundAuth.organization.removeMember({organizationId:X,memberIdOrEmail:Y.memberIdOrEmail}),{success:!0,memberIdOrEmail:Y.memberIdOrEmail}}})});var bN1;var vi0=j(()=>{n1();F4();bN1=t1({name:"ORGANIZATION_MEMBER_LIST",description:"List all members in an organization",annotations:{title:"List Organization Members",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({limit:q.number().optional(),offset:q.number().optional()}),outputSchema:q.object({members:q.array(q.object({id:q.string(),organizationId:q.string(),userId:q.string(),role:q.string(),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),user:q.object({id:q.string(),name:q.string(),email:q.string(),image:q.string().optional()}).optional()}))}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=Q.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");let J=await Q.boundAuth.organization.listMembers({organizationId:X,limit:Y.limit,offset:Y.offset});return{members:(Array.isArray(J)?J:[]).map((K)=>({...K,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt}))}}})});var hN1;var _i0=j(()=>{n1();F4();hN1=t1({name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Update a member's role in an organization",annotations:{title:"Update Member Role",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({organizationId:q.string().optional(),memberId:q.string(),role:q.array(q.string())}),outputSchema:q.object({id:q.string(),organizationId:q.string(),userId:q.string(),role:q.union([q.literal("admin"),q.literal("member"),q.literal("owner")]),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),user:q.object({email:q.string(),name:q.string(),image:q.string().optional()})}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=Y.organizationId||Q.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");let J=await Q.boundAuth.organization.updateMemberRole({organizationId:X,memberId:Y.memberId,role:Y.role});if(!J)throw Error("Failed to update member role");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var yi0=j(()=>{Pi0();Ei0();Ti0();Ci0();Ri0();Ii0();ji0();Si0();ki0();vi0();_i0()});var md6,Sr,ld6,OO,fi0,kr;var NO=j(()=>{n1();md6=q.object({banner:q.string().nullable(),bannerColor:q.string().nullable(),icon:q.string().nullable(),themeColor:q.string().nullable()}),Sr=q.object({banner:q.string().nullable().optional(),bannerColor:q.string().nullable().optional(),icon:q.string().nullable().optional(),themeColor:q.string().nullable().optional()}),ld6=q.object({id:q.string(),title:q.string(),icon:q.string().nullable()}),OO=q.object({id:q.string(),organizationId:q.string(),slug:q.string(),name:q.string(),description:q.string().nullable(),enabledPlugins:q.array(q.string()).nullable(),ui:md6.nullable(),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),updatedAt:q.string().datetime().describe("ISO 8601 timestamp")}),fi0=OO.omit({organizationId:!0}).extend({boundConnections:q.array(ld6)}),kr=q.object({id:q.string(),projectId:q.string(),pluginId:q.string(),connectionId:q.string().nullable(),settings:q.record(q.string(),q.unknown()).nullable(),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),updatedAt:q.string().datetime().describe("ISO 8601 timestamp")})});var xN1;var bi0=j(()=>{n1();F4();NO();xN1=t1({name:"PROJECT_LIST",description:"List all projects in an organization",annotations:{title:"List Projects",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({organizationId:q.string().describe("Organization ID to list projects for")}),outputSchema:q.object({projects:q.array(fi0)}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=await Q.storage.projects.list(Y.organizationId),J=X.map((K)=>K.id),G=await Q.storage.projectPluginConfigs.getBoundConnectionsForProjects(J);return{projects:X.map((K)=>({id:K.id,slug:K.slug,name:K.name,description:K.description,enabledPlugins:K.enabledPlugins,ui:K.ui,boundConnections:G.get(K.id)??[],createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt,updatedAt:K.updatedAt instanceof Date?K.updatedAt.toISOString():K.updatedAt}))}}})});var gN1;var hi0=j(()=>{n1();F4();NO();gN1=t1({name:"PROJECT_GET",description:"Get a project by ID or slug",annotations:{title:"Get Project",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({organizationId:q.string().describe("Organization ID"),projectId:q.string().optional().describe("Project ID (either this or slug required)"),slug:q.string().optional().describe("Project slug (either this or projectId required)")}).refine((Y)=>Y.projectId||Y.slug,{message:"Either projectId or slug must be provided"}),outputSchema:q.object({project:OO.nullable()}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=null;if(Y.projectId)X=await Q.storage.projects.get(Y.projectId);else if(Y.slug)X=await Q.storage.projects.getBySlug(Y.organizationId,Y.slug);if(!X)return{project:null};return{project:{id:X.id,organizationId:X.organizationId,slug:X.slug,name:X.name,description:X.description,enabledPlugins:X.enabledPlugins,ui:X.ui,createdAt:X.createdAt instanceof Date?X.createdAt.toISOString():X.createdAt,updatedAt:X.updatedAt instanceof Date?X.updatedAt.toISOString():X.updatedAt}}}})});var uN1;var xi0=j(()=>{n1();QY();F4();NO();uN1=t1({name:"PROJECT_CREATE",description:"Create a new project in an organization",annotations:{title:"Create Project",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:q.object({organizationId:q.string().describe("Organization ID"),slug:q.string().min(1).max(100).regex(/^[a-z0-9-]+$/,"Slug must be lowercase alphanumeric with hyphens").describe("URL-friendly identifier"),name:q.string().min(1).max(200).describe("Display name"),description:q.string().max(1000).nullable().optional().describe("Project description"),enabledPlugins:q.array(q.string()).nullable().optional().describe("Plugin IDs to enable"),ui:Sr.nullable().optional().describe("UI customization")}),outputSchema:q.object({project:OO}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let{organizationId:X,slug:J,name:G,description:K,enabledPlugins:W,ui:Z}=Y;if(J===nW)throw Error(`Slug "${nW}" is reserved`);if(await Q.storage.projects.getBySlug(X,J))throw Error(`Project with slug "${J}" already exists in this organization`);let $=Z?{banner:Z.banner??null,bannerColor:Z.bannerColor??null,icon:Z.icon??null,themeColor:Z.themeColor??null}:null,F=await Q.storage.projects.create({organizationId:X,slug:J,name:G,description:K??null,enabledPlugins:W??null,ui:$});return{project:{id:F.id,organizationId:F.organizationId,slug:F.slug,name:F.name,description:F.description,enabledPlugins:F.enabledPlugins,ui:F.ui,createdAt:F.createdAt instanceof Date?F.createdAt.toISOString():F.createdAt,updatedAt:F.updatedAt instanceof Date?F.updatedAt.toISOString():F.updatedAt}}}})});var mN1;var gi0=j(()=>{n1();F4();NO();mN1=t1({name:"PROJECT_UPDATE",description:"Update a project's details",annotations:{title:"Update Project",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({projectId:q.string().describe("Project ID to update"),name:q.string().min(1).max(200).optional().describe("New display name"),description:q.string().max(1000).nullable().optional().describe("New description"),enabledPlugins:q.array(q.string()).nullable().optional().describe("Updated plugin IDs"),ui:Sr.nullable().optional().describe("Updated UI customization")}),outputSchema:q.object({project:OO.nullable()}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let{projectId:X,name:J,description:G,enabledPlugins:K,ui:W}=Y,Z={};if(J!==void 0)Z.name=J;if(G!==void 0)Z.description=G;if(K!==void 0)Z.enabledPlugins=K;if(W!==void 0)Z.ui=W?{banner:W.banner??null,bannerColor:W.bannerColor??null,icon:W.icon??null,themeColor:W.themeColor??null}:null;let H=await Q.storage.projects.update(X,Z);if(!H)return{project:null};return{project:{id:H.id,organizationId:H.organizationId,slug:H.slug,name:H.name,description:H.description,enabledPlugins:H.enabledPlugins,ui:H.ui,createdAt:H.createdAt instanceof Date?H.createdAt.toISOString():H.createdAt,updatedAt:H.updatedAt instanceof Date?H.updatedAt.toISOString():H.updatedAt}}}})});var lN1;var ui0=j(()=>{n1();QY();F4();lN1=t1({name:"PROJECT_DELETE",description:"Delete a project (cannot delete org-admin)",annotations:{title:"Delete Project",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({projectId:q.string().describe("Project ID to delete")}),outputSchema:q.object({success:q.boolean(),message:q.string().optional()}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let{projectId:X}=Y,J=await Q.storage.projects.get(X);if(!J)return{success:!1,message:"Project not found"};if(J.slug===nW)return{success:!1,message:"Cannot delete the org-admin project"};return{success:await Q.storage.projects.delete(X)}}})});var dN1;var mi0=j(()=>{n1();F4();NO();dN1=t1({name:"PROJECT_PLUGIN_CONFIG_GET",description:"Get plugin configuration for a project",annotations:{title:"Get Project Plugin Config",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({projectId:q.string().describe("Project ID"),pluginId:q.string().describe("Plugin ID")}),outputSchema:q.object({config:kr.nullable()}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let{projectId:X,pluginId:J}=Y,G=await Q.storage.projectPluginConfigs.get(X,J);if(!G)return{config:null};return{config:{id:G.id,projectId:G.projectId,pluginId:G.pluginId,connectionId:G.connectionId,settings:G.settings,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}}}})});var pN1;var li0=j(()=>{n1();F4();NO();Er();pN1=t1({name:"PROJECT_PLUGIN_CONFIG_UPDATE",description:"Update or create plugin configuration for a project",annotations:{title:"Update Project Plugin Config",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({projectId:q.string().describe("Project ID"),pluginId:q.string().describe("Plugin ID"),connectionId:q.string().nullable().optional().describe("MCP connection to bind"),settings:q.record(q.string(),q.unknown()).nullable().optional().describe("Plugin-specific settings")}),outputSchema:q.object({config:kr}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let{projectId:X,pluginId:J,connectionId:G,settings:K}=Y,W=TY(Q),Z=await Q.storage.projects.get(X);if(!Z)throw Error(`Project not found: ${X}`);let H=G?await Q.storage.connections.findById(G):null;if(G&&Z.organizationId&&!H&&LP()){if(Pr(G,Z.organizationId)){if(!W)throw Error("User ID required to create dev-assets connection");let F=MP(Z.organizationId,X7());await Q.storage.connections.create({...F,organization_id:Z.organizationId,created_by:W})}}let $=await Q.storage.projectPluginConfigs.upsert(X,J,{connectionId:G,settings:K});return{config:{id:$.id,projectId:$.projectId,pluginId:$.pluginId,connectionId:$.connectionId,settings:$.settings,createdAt:$.createdAt instanceof Date?$.createdAt.toISOString():$.createdAt,updatedAt:$.updatedAt instanceof Date?$.updatedAt.toISOString():$.updatedAt}}}})});var di0=j(()=>{bi0();hi0();xi0();gi0();ui0();mi0();li0()});var cN1;var pi0=j(()=>{n1();F4();cN1=t1({name:"TAGS_LIST",description:"List all tags in an organization",annotations:{title:"List Tags",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({}),outputSchema:q.object({tags:q.array(q.object({id:q.string(),organizationId:q.string(),name:q.string(),createdAt:q.string().describe("ISO 8601 timestamp")}))}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=v0(Q);return{tags:(await Q.storage.tags.listOrgTags(X.id)).map((G)=>({...G,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():String(G.createdAt)}))}}})});var nN1;var ci0=j(()=>{n1();F4();nN1=t1({name:"TAGS_CREATE",description:"Create a new tag in an organization",annotations:{title:"Create Tag",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:q.object({name:q.string().min(1).max(50).describe("Tag name")}),outputSchema:q.object({tag:q.object({id:q.string(),organizationId:q.string(),name:q.string(),createdAt:q.string().describe("ISO 8601 timestamp")})}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=v0(Q),J=await Q.storage.tags.createTag(X.id,Y.name);return{tag:{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():String(J.createdAt)}}}})});var iN1;var ni0=j(()=>{n1();F4();iN1=t1({name:"TAGS_DELETE",description:"Delete a tag from an organization (removes from all members)",annotations:{title:"Delete Tag",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({tagId:q.string().describe("Tag ID to delete")}),outputSchema:q.object({success:q.boolean()}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=v0(Q),J=await Q.storage.tags.getTag(Y.tagId);if(!J)throw Error("Tag not found");if(J.organizationId!==X.id)throw Error("Tag does not belong to this organization");return await Q.storage.tags.deleteTag(Y.tagId),{success:!0}}})});var aN1;var ii0=j(()=>{n1();F4();aN1=t1({name:"MEMBER_TAGS_GET",description:"Get tags assigned to a member",annotations:{title:"Get Member Tags",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({memberId:q.string().describe("Member ID")}),outputSchema:q.object({tags:q.array(q.object({id:q.string(),organizationId:q.string(),name:q.string(),createdAt:q.string().describe("ISO 8601 timestamp")}))}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=v0(Q);if(!await Q.storage.tags.verifyMemberOrg(Y.memberId,X.id))throw Error(`Member not found in this organization: ${Y.memberId}`);return{tags:(await Q.storage.tags.getMemberTags(Y.memberId)).map((K)=>({...K,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():String(K.createdAt)}))}}})});var rN1;var ai0=j(()=>{n1();F4();rN1=t1({name:"MEMBER_TAGS_SET",description:"Set tags for a member (replaces all existing tags)",annotations:{title:"Set Member Tags",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({memberId:q.string().describe("Member ID"),tagIds:q.array(q.string()).describe("Array of tag IDs to assign")}),outputSchema:q.object({success:q.boolean(),tags:q.array(q.object({id:q.string(),organizationId:q.string(),name:q.string(),createdAt:q.string().describe("ISO 8601 timestamp")}))}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=v0(Q);if(!await Q.storage.tags.verifyMemberOrg(Y.memberId,X.id))throw Error(`Member not found in this organization: ${Y.memberId}`);for(let K of Y.tagIds){let W=await Q.storage.tags.getTag(K);if(!W)throw Error(`Tag not found: ${K}`);if(W.organizationId!==X.id)throw Error(`Tag does not belong to this organization: ${K}`)}return await Q.storage.tags.setMemberTags(Y.memberId,Y.tagIds),{success:!0,tags:(await Q.storage.tags.getMemberTags(Y.memberId)).map((K)=>({...K,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():String(K.createdAt)}))}}})});var ri0=j(()=>{pi0();ci0();ni0();ii0();ai0()});var oi0=j(()=>{QY()});var si0,X3,ti0,ei0;var LO=j(()=>{n1();oi0();si0=q.object({id:q.string().describe("Unique message ID"),thread_id:q.string().describe("ID of the parent thread"),metadata:q.unknown().optional().describe("Optional message metadata"),parts:q.array(q.record(q.string(),q.unknown())).describe("Message content parts (AI SDK UIMessagePart format)"),role:q.enum(["user","assistant","system"]).describe("Message role"),created_at:q.string().datetime().describe("Timestamp of creation"),updated_at:q.string().datetime().describe("Timestamp of last update")}),X3=q.object({id:q.string().describe("Unique thread ID"),organization_id:q.string().describe("Organization this thread belongs to"),title:q.string().describe("Thread title"),description:q.string().nullable().describe("Thread description"),created_at:q.string().datetime().describe("Timestamp of creation"),updated_at:q.string().datetime().describe("Timestamp of last update"),hidden:q.boolean().optional().describe("Whether the thread is hidden"),status:q.enum([...WL,"expired"]).describe("Thread execution status. 'expired' is virtual -- computed at read time for stale in_progress threads"),created_by:q.string().describe("User ID who created the thread"),updated_by:q.string().nullable().describe("User ID who last updated the thread")}),ti0=q.object({id:q.string().optional().describe("Optional custom ID for the thread"),title:q.string().describe("Thread title"),description:q.string().nullish().describe("Thread description")}),ei0=q.object({title:q.string().optional().describe("New thread title"),description:q.string().nullish().describe("New thread description"),hidden:q.boolean().optional().describe("Whether the thread is hidden")})});var cd6,nd6,oN1;var Ya0=j(()=>{n1();F4();LO();F7();cd6=q.object({data:ti0.describe("Data for the new thread (id is auto-generated if not provided)")}),nd6=q.object({item:X3.describe("The created thread entity")}),oN1=t1({name:"COLLECTION_THREADS_CREATE",description:"Create a new thread in the organization",annotations:{title:"Create Thread",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:cd6,outputSchema:nd6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=TY(Q);if(!J)throw Error("User ID required to create thread");let G=Y.data.id??J9("thrd"),K=await Q.storage.threads.create({id:G,organization_id:X.id,title:Y.data.title,description:Y.data.description,created_by:J});return{item:{...K,hidden:K.hidden??!1}}}})});function NB(Y,Q=Date.now()){let X=Y.status;if(X==="in_progress"){let J=new Date(Y.updated_at).getTime();if(!Number.isFinite(J)||Q-J>1800000)X="expired"}return{...Y,status:X,hidden:Y.hidden??!1}}var id6,ad6,sN1;var Qa0=j(()=>{MG();F4();LO();n1();id6=lZ.extend({where:q.object({created_by:q.string().optional()}).optional()}),ad6=n$(X3),sN1=t1({name:"COLLECTION_THREADS_LIST",description:"List all threads in the organization with filtering, sorting, and pagination",annotations:{title:"List Threads",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:id6,outputSchema:ad6,handler:async(Y,Q)=>{await Q.access.check();let X=Q.auth.user?.id;if(!X)throw Error("User ID required to list threads");let J=v0(Q),G=Y.offset??0,K=Y.limit??100,{threads:W,total:Z}=await Q.storage.threads.list(J.id,X,{limit:K,offset:G}),H=G+K<Z,$=Date.now();return{items:W.map((F)=>NB(F,$)),totalCount:Z,hasMore:H}}})});var rd6,tN1;var Xa0=j(()=>{MG();F4();LO();rd6=hS(X3),tN1=t1({name:"COLLECTION_THREADS_GET",description:"Get thread details by ID",annotations:{title:"Get Thread",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:bS,outputSchema:rd6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=await Q.storage.threads.get(Y.id);if(!J||J.organization_id!==X.id)return{item:null};return{item:NB(J)}}})});var od6,sd6,eN1;var Ja0=j(()=>{n1();F4();LO();od6=q.object({id:q.string().describe("ID of the thread to update"),data:ei0.describe("Partial thread data to update")}),sd6=q.object({item:X3.describe("The updated thread entity")}),eN1=t1({name:"COLLECTION_THREADS_UPDATE",description:"Update an existing thread in the organization",annotations:{title:"Update Thread",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:od6,outputSchema:sd6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=TY(Q);if(!J)throw Error("User ID required to update thread");let{id:G,data:K}=Y,W=await Q.storage.threads.get(G);if(!W||W.organization_id!==X.id)throw Error("Thread not found in organization");let Z=await Q.storage.threads.update(G,{title:K.title,description:K.description,hidden:K.hidden,updated_by:J});return{item:NB(Z)}}})});var YL1;var Ga0=j(()=>{MG();F4();LO();YL1=t1({name:"COLLECTION_THREADS_DELETE",description:"Delete a thread",annotations:{title:"Delete Thread",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:xS,outputSchema:gS(X3),handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=await Q.storage.threads.get(Y.id);if(!J)throw Error(`Thread not found: ${Y.id}`);if(J.organization_id!==X.id)throw Error(`Thread not found: ${Y.id}`);return await Q.storage.threads.delete(Y.id),{item:NB(J)}}})});function Wa0(Y){if(!Y)return null;if("field"in Y&&Y.field[0]==="thread_id"&&Y.operator==="eq")return String(Y.value);if("conditions"in Y)for(let Q of Y.conditions){let X=Wa0(Q);if(X)return X}return null}var td6,QL1;var Za0=j(()=>{MG();F4();LO();td6=n$(si0),QL1=t1({name:"COLLECTION_THREAD_MESSAGES_LIST",description:"List all messages for a specific thread",annotations:{title:"List Thread Messages",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:lZ,outputSchema:td6,handler:async(Y,Q)=>{let X=v0(Q);await Q.access.check();let J=Wa0(Y.where);if(!J)throw Error("thread_id filter is required in where clause");let G=await Q.storage.threads.get(J);if(!G||G.organization_id!==X.id)return{items:[],totalCount:0,hasMore:!1};let K=Y.offset??0,W=Y.limit??100,{messages:Z,total:H}=await Q.storage.threads.listMessages(J,{limit:W,offset:K}),$=K+W<H;return{items:Z,totalCount:H,hasMore:$}}})});var Ka0=j(()=>{Ya0();Qa0();Xa0();Ja0();Ga0();Za0()});var Yp6,Qp6,XL1;var Ha0=j(()=>{n1();F4();Yp6=q.object({id:q.string().min(1)}),Qp6=q.object({user:q.object({id:q.string(),name:q.string(),email:q.string(),image:q.string().nullable()}).nullable()}),XL1=t1({name:"USER_GET",description:"Get a user by id (restricted to shared organizations)",annotations:{title:"Get User",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:Yp6,outputSchema:Qp6,handler:async(Y,Q)=>{await Q.access.check(),D0(Q);let X=TY(Q);if(!X)throw Error("Authentication required");let J=await Q.storage.users.findById(Y.id,X);if(!J)return{user:null};return{user:{id:J.id,name:J.name,email:J.email,image:J.image??null}}}})});var $a0=j(()=>{Ha0()});var Va0={};R4(Va0,{managementMCP:()=>JL1,ALL_TOOLS:()=>Fa0});var Jp6,Gp6,Fa0,JL1=async(Y)=>{let Q=null;if(Y.organization){let G=await Y.storage.organizationSettings.get(Y.organization.id),K=await Y.storage.projects.list(Y.organization.id),W=new Set(G?.enabled_plugins??[]);for(let Z of K)if(Z.enabledPlugins)for(let H of Z.enabledPlugins)W.add(H);Q=W.size>0?[...W]:null}let X=Kc0(Fa0,Q),J=new EU({name:"mcp-mesh-management",version:"1.0.0"},{capabilities:{tools:{}}});for(let G of X){let K=G.inputSchema&&typeof G.inputSchema==="object"&&"shape"in G.inputSchema?G.inputSchema:q.object({}),W=G.outputSchema&&typeof G.outputSchema==="object"&&"shape"in G.outputSchema?G.outputSchema:void 0,Z=K.shape,H=W?.shape;J.registerTool(G.name,{description:G.description??"",inputSchema:Z,outputSchema:H,annotations:G.annotations},async($)=>{Y.access.setToolName(G.name);try{let F=await G.execute($,Y);return{content:[{type:"text",text:JSON.stringify(F)}],structuredContent:F}}catch(F){return{content:[{type:"text",text:`Error: ${F.message}`}],isError:!0}}})}return J};var GL1=j(()=>{Bv();kx();n1();Rc0();pc0();hn0();mn0();sn0();Gi0();Fi0();Bi0();Ai0();yi0();di0();ri0();Ka0();$a0();Jp6=[CN1,RN1,IN1,jN1,SN1,vN1,_N1,yN1,fN1,bN1,hN1,EO1,RO1,IO1,oO1,sO1,tO1,ZN1,HN1,$N1,FN1,VN1,qN1,BN1,UN1,DN1,zN1,un0,ON1,NN1,LN1,MN1,wN1,AN1,PN1,EN1,TN1,BO1,DO1,zO1,UO1,eO1,YN1,QN1,XN1,JN1,GN1,WN1,XL1,wO1,AO1,PO1,oN1,sN1,tN1,eN1,YL1,QL1,cN1,nN1,iN1,aN1,rN1,xN1,gN1,uN1,mN1,lN1,dN1,pN1],Gp6=Hc0(),Fa0=[...Jp6,...Gp6]});function Wp6(Y){return[{permissions:{self:["*"]},getTools:async()=>{let{ALL_TOOLS:Q}=await Promise.resolve().then(() => (GL1(),Va0));return Q.map((X)=>{return{name:X.name,inputSchema:q.toJSONSchema(X.inputSchema,{unrepresentable:"any"}),outputSchema:X.outputSchema?q.toJSONSchema(X.outputSchema,{unrepresentable:"any"}):void 0,description:X.description}})},data:G91(X7(),Y)},{data:J91()},{data:X91(Y)}]}async function qa0(Y,Q){try{let X=vz(),J=new _z(process.env.ENCRYPTION_KEY||""),G=new RS(X.db,J),K=new IS(X.db),W=Wp6(Y);try{await K.create({organizationId:Y,slug:nW,name:iO,description:"Organization administration and settings",enabledPlugins:null,ui:null})}catch(Z){console.warn("Could not create org-admin project (may already exist):",Z)}await Promise.all(W.map(async(Z)=>{let H=null;if(Z.permissions)H=(await XK.api.createApiKey({body:{name:`${Z.data.app_name??crypto.randomUUID()}-mcp`,userId:Q,permissions:Z.permissions,rateLimitEnabled:!1,metadata:{organization:{id:Y},purpose:"default-org-connections"}}}))?.key;let $=await EA({id:"pending",title:Z.data.title,connection_type:Z.data.connection_type,connection_url:Z.data.connection_url,connection_token:Z.data.connection_token,connection_headers:Z.data.connection_headers}).catch(()=>null),F=await Z.getTools?.()??$?.tools??null,V=$?.scopes?.length?$.scopes:null,B=Z.data.id?Z.data.id.startsWith(`${Y}_`)?Z.data.id:`${Y}_${Z.data.id}`:void 0;await G.create({...Z.data,id:B,tools:F,configuration_scopes:V,organization_id:Y,created_by:Q,connection_token:Z.data.connection_token??H})}))}catch(X){console.error("Error creating default MCP connections:",X)}}var Ba0=j(()=>{QY();PS();ln();Mq1();wq1();rn();n1();wP()});var WL1,vr;var _r=j(()=>{WL1=["owner","admin","user"],vr=["owner","admin"]});var Zp6=(Y)=>{return{defaultSSO:[{domain:Y.domain,providerId:Y.providerId,oidcConfig:{issuer:`https://login.microsoftonline.com/${Y.MS_TENANT_ID}/v2.0`,pkce:!0,clientId:Y.MS_CLIENT_ID,clientSecret:Y.MS_CLIENT_SECRET,discoveryEndpoint:`https://login.microsoftonline.com/${Y.MS_TENANT_ID}/v2.0/.well-known/openid-configuration`,authorizationEndpoint:`https://login.microsoftonline.com/${Y.MS_TENANT_ID}/oauth2/v2.0/authorize`,tokenEndpoint:`https://login.microsoftonline.com/${Y.MS_TENANT_ID}/oauth2/v2.0/token`,jwksEndpoint:`https://login.microsoftonline.com/${Y.MS_TENANT_ID}/discovery/v2.0/keys`,userInfoEndpoint:"https://graph.microsoft.com/oidc/userinfo",tokenEndpointAuthentication:"client_secret_post",scopes:Y.scopes,mapping:{id:"sub",email:"email",emailVerified:"email_verified",name:"name",image:"picture",extraFields:{emailVerified:"email_verified"}}}}]}},Ua0=(Y)=>{if(Y.providerId==="microsoft")return Zp6(Y);throw Error(`Unsupported provider: ${Y.providerId}`)};function Kp6(Y){return Y.toLowerCase().trim().replace(/[^a-z0-9\s_-]+/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function Hp6(){let Y=Math.floor(Math.random()*za0.length),Q=Math.floor(Math.random()*Da0.length),X=za0[Y]??"deco",J=Da0[Q]??"studio";return`${X}-${J}`}function Op6(){let Y=[Sv],Q=new URL(Sv);if(Q.hostname==="localhost")Y.push(Sv.replace("localhost","127.0.0.1"));else if(Q.hostname==="127.0.0.1")Y.push(Sv.replace("127.0.0.1","localhost"));return Y}var Da0,za0,$p6,Fp6,yr,Vp6,qp6,Bp6,Oa0,p9,Na0=void 0,ZL1=void 0,KL1=!1,Up6,Dp6,zp6,Sv,XK;var wP=j(()=>{YQ1();od1();bc1();m51();F71();In1();WI();fn1();PS();Lq1();Cj0();Ba0();_r();Da0=["labs","agent","studio","workspace","systems","core","cloud","works"],za0=["capybara","guarana","deco","samba","feijoada","capoeira","carnival"];$p6=Object.values(OC()).map((Y)=>Y.map((Q)=>Q.name)).flat(),Fp6={...Tl,self:["*",...$p6]},yr=DH(Fp6),Vp6=yr.newRole({self:["*"],...rR.statements}),qp6=yr.newRole({self:["*"],...rR.statements}),Bp6=yr.newRole({self:["*"],...rR.statements}),Oa0=Object.values(OC()).map((Y)=>Y.map((Q)=>`self:${Q.name}`)).flat(),p9=GI.auth;if(p9.inviteEmailProviderId&&p9.emailProviders&&p9.emailProviders.length>0){let Y=TS(p9.emailProviders,p9.inviteEmailProviderId);if(Y){let Q=ES(Y);Na0=async(X)=>{let J=X.inviter.user?.name||X.inviter.user?.email,G=`${X7()}/auth/accept-invitation?invitationId=${X.invitation.id}&redirectTo=/`;await Q({to:X.email,subject:`Invitation to join ${X.organization.name}`,html:`
1481
+ `.execute(Y)).rows[0]?.exists)await v8`CREATE ROLE ${v8.id(X)} NOLOGIN`.execute(Y);await v8`GRANT ${v8.id(X)} TO CURRENT_USER`.execute(Y),await v8`GRANT USAGE, CREATE ON SCHEMA ${v8.id(Q)} TO ${v8.id(X)}`.execute(Y),await v8`GRANT ALL ON ALL TABLES IN SCHEMA ${v8.id(Q)} TO ${v8.id(X)}`.execute(Y),await v8`GRANT ALL ON ALL SEQUENCES IN SCHEMA ${v8.id(Q)} TO ${v8.id(X)}`.execute(Y),await v8`ALTER DEFAULT PRIVILEGES IN SCHEMA ${v8.id(Q)} GRANT ALL ON TABLES TO ${v8.id(X)}`.execute(Y),await v8`ALTER DEFAULT PRIVILEGES IN SCHEMA ${v8.id(Q)} GRANT ALL ON SEQUENCES TO ${v8.id(X)}`.execute(Y),await v8`REVOKE ALL ON SCHEMA public FROM ${v8.id(X)}`.execute(Y)}async function Yd6(Y,Q,X,J){try{return await Y.transaction().execute(async(G)=>{return await v8`SET LOCAL ROLE ${v8.id(X)}`.execute(G),await v8`SET LOCAL search_path TO ${v8.id(Q)}`.execute(G),await v8.raw(J).execute(G)})}catch(G){if(tl6(G))return await el6(Y,Q,X),await Y.transaction().execute(async(K)=>{return await v8`SET LOCAL ROLE ${v8.id(X)}`.execute(K),await v8`SET LOCAL search_path TO ${v8.id(Q)}`.execute(K),await v8.raw(J).execute(K)});throw G}}var il6,rl6,un0;var mn0=j(()=>{n1();F4();il6=q.object({results:q.array(q.unknown()).optional(),success:q.boolean().optional()});rl6=q.object({sql:q.string().describe("The SQL query to run"),params:q.array(q.any()).describe("The parameters to pass to the SQL query").optional()});un0=t1({name:"DATABASES_RUN_SQL",description:"Run a SQL query against the database",annotations:{title:"Run SQL Query",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:rl6,outputSchema:q.object({result:q.array(il6)}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=al6(Y.sql,Y.params||[]);if(!Q.connectionId)throw Error("Connection context required for database access");let J=ol6(Q.connectionId),G=sl6(Q.connectionId);return{result:[{results:(await Yd6(Q.db,J,G,X)).rows,success:!0}]}}})});var ln0,Xd6,dn0;var wF=j(()=>{n1();Yk();ln0=q.object({connectionId:q.string().optional().describe("Filter subscriptions by connection ID (optional)")}),Xd6=q.object({id:q.string().describe("Subscription ID"),connectionId:q.string().describe("Subscriber connection ID"),eventType:q.string().describe("Event type pattern"),publisher:q.string().nullable().describe("Publisher connection filter (null = all publishers)"),filter:q.string().nullable().describe("JSONPath filter expression"),enabled:q.boolean().describe("Whether subscription is enabled"),createdAt:q.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:q.string().datetime().describe("Updated timestamp (ISO 8601)")}),dn0=q.object({subscriptions:q.array(Xd6).describe("List of subscriptions")})});var eO1;var pn0=j(()=>{F4();wF();eO1=t1({name:"EVENT_PUBLISH",description:"Publish an event to the event bus. Supports immediate, scheduled (deliverAt), and recurring (cron) delivery. The source is automatically set to the caller's connection ID.",annotations:{title:"Publish Event",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},inputSchema:uS,outputSchema:mS,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=Q.connectionId;if(!J)throw Error("Connection ID required to publish events. Use a connection-scoped token.");let G=await Q.eventBus.publish(X.id,J,{type:Y.type,subject:Y.subject,data:Y.data,deliverAt:Y.deliverAt,cron:Y.cron});return{id:G.id,type:G.type,source:G.source,time:G.time}}})});var YN1;var cn0=j(()=>{F4();wF();YN1=t1({name:"EVENT_SUBSCRIBE",description:"Subscribe to events of a specific type. The subscriber is automatically set to the caller's connection.",annotations:{title:"Subscribe to Events",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:lS,outputSchema:dS,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=Q.connectionId;if(!J)throw Error("Connection ID required to subscribe. Use a connection-scoped token.");let G=await Q.eventBus.subscribe(X.id,{connectionId:J,eventType:Y.eventType,publisher:Y.publisher,filter:Y.filter});return{subscription:{id:G.id,connectionId:G.connectionId,eventType:G.eventType,publisher:G.publisher,filter:G.filter,enabled:G.enabled,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}}}})});var QN1;var nn0=j(()=>{F4();wF();QN1=t1({name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events by removing a subscription.",annotations:{title:"Unsubscribe from Events",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:nS,outputSchema:iS,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=Q.connectionId;if(!J)throw Error("Connection ID required to unsubscribe. Use a connection-scoped token.");let G=await Q.eventBus.getSubscription(X.id,Y.subscriptionId);if(!G)throw Error(`Subscription not found: ${Y.subscriptionId}`);if(G.connectionId!==J)throw Error("Cannot unsubscribe from a subscription owned by another connection");return{success:(await Q.eventBus.unsubscribe(X.id,Y.subscriptionId)).success,subscriptionId:Y.subscriptionId}}})});var XN1;var in0=j(()=>{F4();wF();XN1=t1({name:"EVENT_CANCEL",description:"Cancel a recurring event to stop future deliveries. Only the publisher can cancel their own events.",annotations:{title:"Cancel Recurring Event",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:aS,outputSchema:rS,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=Q.connectionId;if(!J)throw Error("Connection ID required to cancel events. Use a connection-scoped token.");if(!await Q.eventBus.getEvent(X.id,Y.eventId))throw Error(`Event not found: ${Y.eventId}`);if(!(await Q.eventBus.cancelEvent(X.id,Y.eventId,J)).success)throw Error("Failed to cancel event. Either the event is already completed/failed, or you are not the publisher.");return{success:!0,eventId:Y.eventId}}})});var JN1;var an0=j(()=>{F4();wF();JN1=t1({name:"EVENT_ACK",description:"Acknowledge delivery of an event. Call after successfully processing an event received via ON_EVENTS with retryAfter.",annotations:{title:"Acknowledge Event",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:oS,outputSchema:sS,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=Q.connectionId;if(!J)throw Error("Connection ID required to acknowledge events. Use a connection-scoped token.");if(!(await Q.eventBus.ackEvent(X.id,Y.eventId,J)).success)throw Error("Failed to acknowledge event. Either the event was not found, already delivered, or you are not a subscriber.");return{success:!0,eventId:Y.eventId}}})});var GN1;var rn0=j(()=>{F4();wF();GN1=t1({name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions, optionally filtered by connection ID.",annotations:{title:"List Event Subscriptions",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:ln0,outputSchema:dn0,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);return await Q.access.check(),{subscriptions:(await Q.eventBus.listSubscriptions(X.id,Y.connectionId)).map((G)=>({id:G.id,connectionId:G.connectionId,eventType:G.eventType,publisher:G.publisher,filter:G.filter,enabled:G.enabled,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}))}}})});var WN1;var on0=j(()=>{F4();wF();WN1=t1({name:"EVENT_SYNC_SUBSCRIPTIONS",description:"Sync subscriptions to desired state. Creates new, deletes removed, updates changed filters. Subscriptions are identified by (eventType, publisher).",annotations:{title:"Sync Event Subscriptions",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:pS,outputSchema:cS,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=Q.connectionId;if(!J)throw Error("Connection ID required to sync subscriptions. Use a connection-scoped token.");let G=await Q.eventBus.syncSubscriptions(X.id,{connectionId:J,subscriptions:Y.subscriptions});return{created:G.created,updated:G.updated,deleted:G.deleted,unchanged:G.unchanged,subscriptions:G.subscriptions.map((K)=>({id:K.id,connectionId:K.connectionId,eventType:K.eventType,publisher:K.publisher,filter:K.filter,enabled:K.enabled,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt,updatedAt:K.updatedAt instanceof Date?K.updatedAt.toISOString():K.updatedAt}))}}})});var sn0=j(()=>{pn0();cn0();nn0();in0();an0();rn0();on0();wF()});var RP=j(()=>{Ix()});function tn0(){return`/icons/capy-${Math.floor(Math.random()*39)+0}.png`}var Gd6,Wd6,ZN1;var en0=j(()=>{n1();F4();RP();Gd6=q.object({data:bT.describe("Data for the new virtual MCP")}),Wd6=q.object({item:bG.describe("The created virtual MCP entity")}),ZN1=t1({name:"COLLECTION_VIRTUAL_MCP_CREATE",description:"Create a new Virtual MCP",annotations:{title:"Create Virtual MCP",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:Gd6,outputSchema:Wd6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=TY(Q);if(!J)throw Error("User ID required to create virtual MCP");let G={...Y.data,icon:Y.data.icon??tn0()};return{item:await Q.storage.virtualMcps.create(X.id,J,G)}}})});function Zd6(Y){let Q=[],X=0;while(X<Y.length){let J=Y[X];if(J==="%")Q.push(".*");else if(J==="_")Q.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))Q.push("\\"+J);else Q.push(J);X++}return Q.join("")}function zB(Y){return typeof Y==="string"||typeof Y==="number"}function KN1(Y,Q){let X=Q.split("."),J=Y;for(let G of X){if(J==null||typeof J!=="object")return;J=J[G]}return J}function Kd6(Y,Q){return Y.connections.some((X)=>X.connection_id===Q)}function jr(Y,Q){if("conditions"in Q){let{operator:Z,conditions:H}=Q;switch(Z){case"and":return H.every(($)=>jr(Y,$));case"or":return H.some(($)=>jr(Y,$));case"not":return!H.every(($)=>jr(Y,$));default:return!0}}let{field:X,operator:J,value:G}=Q,K=X.join(".");if(K==="connection_id"){if(J!=="eq"||typeof G!=="string")return!1;return Kd6(Y,G)}let W=KN1(Y,K);switch(J){case"eq":return W===G;case"gt":return zB(W)&&zB(G)&&W>G;case"gte":return zB(W)&&zB(G)&&W>=G;case"lt":return zB(W)&&zB(G)&&W<G;case"lte":return zB(W)&&zB(G)&&W<=G;case"in":return Array.isArray(G)&&G.includes(W);case"like":if(typeof W!=="string"||typeof G!=="string")return!1;if(G.length>100)return!1;let Z=Zd6(G);return new RegExp(`^${Z}$`,"i").test(W);case"contains":if(typeof W!=="string"||typeof G!=="string")return!1;return W.toLowerCase().includes(G.toLowerCase());default:return!0}}function Hd6(Y,Q){return[...Y].sort((X,J)=>{for(let G of Q){let K=G.field.join("."),W=KN1(X,K),Z=KN1(J,K),H=0;if(W==null&&Z==null)continue;if(W==null)H=G.nulls==="first"?-1:1;else if(Z==null)H=G.nulls==="first"?1:-1;else if(typeof W==="string"&&typeof Z==="string")H=W.localeCompare(Z);else if(typeof W==="number"&&typeof Z==="number")H=W-Z;else H=String(W).localeCompare(String(Z));if(H!==0)return G.direction==="desc"?-H:H}return 0})}var $d6,Fd6,HN1;var Yi0=j(()=>{MG();F4();RP();$d6=lZ,Fd6=n$(bG),HN1=t1({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:$d6,outputSchema:Fd6,handler:async(Y,Q)=>{await Q.access.check();let X=v0(Q),J=Y.where&&!("conditions"in Y.where)&&Y.where.field.join(".")==="connection_id"&&Y.where.operator==="eq"&&typeof Y.where.value==="string"?Y.where.value:void 0,K=J?await Q.storage.virtualMcps.listByConnectionId(X.id,J):await Q.storage.virtualMcps.list(X.id);if(Y.where)K=K.filter((V)=>jr(V,Y.where));if(Y.orderBy&&Y.orderBy.length>0)K=Hd6(K,Y.orderBy);let W=K.length,Z=Y.offset??0,H=Y.limit??100,$=K.slice(Z,Z+H),F=Z+H<W;return{items:$,totalCount:W,hasMore:F}}})});var Vd6,qd6,$N1;var Qi0=j(()=>{n1();F4();RP();Vd6=q.object({id:q.string().describe("ID of the virtual MCP to retrieve")}),qd6=q.object({item:bG.nullable().describe("The retrieved virtual MCP, or null if not found")}),$N1=t1({name:"COLLECTION_VIRTUAL_MCP_GET",description:"Get an MCP virtual MCP by ID",annotations:{title:"Get Virtual MCP",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:Vd6,outputSchema:qd6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.id);if(J&&J.organization_id!==X.id)return{item:null};if(!J)return{item:null};return{item:J}}})});var Bd6,Ud6,FN1;var Xi0=j(()=>{n1();F4();RP();Bd6=q.object({id:q.string().describe("ID of the virtual MCP to update"),data:hT.describe("Partial virtual MCP data to update")}),Ud6=q.object({item:bG.describe("The updated virtual MCP entity")}),FN1=t1({name:"COLLECTION_VIRTUAL_MCP_UPDATE",description:"Update an MCP virtual MCP",annotations:{title:"Update Virtual MCP",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:Bd6,outputSchema:Ud6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=TY(Q);if(!J)throw Error("User ID required to update virtual MCP");let G=await Q.storage.virtualMcps.findById(Y.id);if(!G)throw Error(`Virtual MCP not found: ${Y.id}`);if(G.organization_id!==X.id)throw Error(`Virtual MCP not found: ${Y.id}`);return{item:await Q.storage.virtualMcps.update(Y.id,J,Y.data)}}})});var Dd6,zd6,VN1;var Ji0=j(()=>{n1();F4();RP();Dd6=q.object({id:q.string().describe("ID of the virtual MCP to delete")}),zd6=q.object({item:bG.describe("The deleted virtual MCP entity")}),VN1=t1({name:"COLLECTION_VIRTUAL_MCP_DELETE",description:"Delete an MCP virtual MCP",annotations:{title:"Delete Virtual MCP",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:Dd6,outputSchema:zd6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.id);if(!J)throw Error(`Virtual MCP not found: ${Y.id}`);if(J.organization_id!==X.id)throw Error(`Virtual MCP not found: ${Y.id}`);return await Q.storage.virtualMcps.delete(Y.id),{item:J}}})});var Gi0=j(()=>{en0();Yi0();Qi0();Xi0();Ji0()});var Nd6,Ld6,qN1;var Wi0=j(()=>{n1();F4();MF();Nd6=q.object({virtual_mcp_id:q.string().describe("ID of the Virtual MCP to add the tool to"),data:Nn0.describe("Virtual tool data")}),Ld6=q.object({item:Q3.describe("The created virtual tool")}),qN1=t1({name:"COLLECTION_VIRTUAL_TOOLS_CREATE",description:"Create a new virtual tool on a Virtual MCP. The tool code should be a JavaScript ES module that exports a default async function: export default async (tools, args) => { ... }. Specify connection_dependencies to indicate which connections this tool uses.",annotations:{title:"Create Virtual Tool",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:Nd6,outputSchema:Ld6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!J||J.organization_id!==X.id)throw Error(`Virtual MCP not found: ${Y.virtual_mcp_id}`);let G=Y.data.connection_dependencies??[];return{item:await Q.storage.virtualMcps.createVirtualTool(Y.virtual_mcp_id,Y.data,G)}}})});var Md6,wd6,BN1;var Zi0=j(()=>{n1();F4();MF();Md6=q.object({virtual_mcp_id:q.string().describe("ID of the Virtual MCP to list tools for"),limit:q.number().int().min(1).max(1000).optional().describe("Maximum number of items to return"),offset:q.number().int().min(0).optional().describe("Number of items to skip")}),wd6=q.object({items:q.array(Q3).describe("Array of virtual tools"),totalCount:q.number().int().min(0).optional().describe("Total number of virtual tools"),hasMore:q.boolean().optional().describe("Whether there are more items available")}),BN1=t1({name:"COLLECTION_VIRTUAL_TOOLS_LIST",description:"List all virtual tools for a Virtual MCP",annotations:{title:"List Virtual Tools",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:Md6,outputSchema:wd6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!J||J.organization_id!==X.id)return{items:[],totalCount:0,hasMore:!1};let G=await Q.storage.virtualMcps.listVirtualTools(Y.virtual_mcp_id),K=G.length,W=Y.offset??0,Z=Y.limit??100,H=G.slice(W,W+Z),$=W+Z<K;return{items:H,totalCount:K,hasMore:$}}})});var Ad6,Pd6,UN1;var Ki0=j(()=>{n1();F4();MF();Ad6=q.object({virtual_mcp_id:q.string().describe("ID of the Virtual MCP"),name:q.string().describe("Name of the virtual tool to retrieve")}),Pd6=q.object({item:Q3.nullable().describe("The retrieved virtual tool, or null if not found")}),UN1=t1({name:"COLLECTION_VIRTUAL_TOOLS_GET",description:"Get a virtual tool by name from a Virtual MCP",annotations:{title:"Get Virtual Tool",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:Ad6,outputSchema:Pd6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!J||J.organization_id!==X.id)return{item:null};return{item:await Q.storage.virtualMcps.getVirtualTool(Y.virtual_mcp_id,Y.name)}}})});var Ed6,Td6,DN1;var Hi0=j(()=>{n1();F4();MF();Ed6=q.object({virtual_mcp_id:q.string().describe("ID of the Virtual MCP"),name:q.string().describe("Current name of the virtual tool to update"),data:Ln0.describe("Partial virtual tool data to update")}),Td6=q.object({item:Q3.describe("The updated virtual tool")}),DN1=t1({name:"COLLECTION_VIRTUAL_TOOLS_UPDATE",description:"Update an existing virtual tool on a Virtual MCP. Specify connection_dependencies to update which connections this tool uses.",annotations:{title:"Update Virtual Tool",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:Ed6,outputSchema:Td6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!J||J.organization_id!==X.id)throw Error(`Virtual MCP not found: ${Y.virtual_mcp_id}`);if(!await Q.storage.virtualMcps.getVirtualTool(Y.virtual_mcp_id,Y.name))throw Error(`Virtual tool not found: ${Y.name}`);let K=Y.data.connection_dependencies;return{item:await Q.storage.virtualMcps.updateVirtualTool(Y.virtual_mcp_id,Y.name,Y.data,K)}}})});var Cd6,Rd6,zN1;var $i0=j(()=>{n1();F4();MF();Cd6=q.object({virtual_mcp_id:q.string().describe("ID of the Virtual MCP"),name:q.string().describe("Name of the virtual tool to delete")}),Rd6=q.object({item:Q3.describe("The deleted virtual tool")}),zN1=t1({name:"COLLECTION_VIRTUAL_TOOLS_DELETE",description:"Delete a virtual tool from a Virtual MCP",annotations:{title:"Delete Virtual Tool",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:Cd6,outputSchema:Rd6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!J||J.organization_id!==X.id)throw Error(`Virtual MCP not found: ${Y.virtual_mcp_id}`);let G=await Q.storage.virtualMcps.getVirtualTool(Y.virtual_mcp_id,Y.name);if(!G)throw Error(`Virtual tool not found: ${Y.name}`);return await Q.storage.virtualMcps.deleteVirtualTool(Y.virtual_mcp_id,Y.name),{item:G}}})});var Fi0=j(()=>{Wi0();Zi0();Ki0();Hi0();$i0()});var jd6,ON1;var Vi0=j(()=>{F4();n1();jd6=q.object({id:q.string().optional().describe("Unique log identifier"),organizationId:q.string().describe("Organization ID"),connectionId:q.string().describe("Connection ID"),connectionTitle:q.string().describe("Connection display name"),toolName:q.string().describe("Name of the tool that was called"),input:q.record(q.string(),q.unknown()).describe("Redacted tool input"),output:q.record(q.string(),q.unknown()).describe("Redacted tool output"),isError:q.boolean().describe("Whether the call resulted in an error"),errorMessage:q.string().nullish().describe("Error message if applicable"),durationMs:q.number().describe("Call duration in milliseconds"),timestamp:q.string().describe("ISO 8601 timestamp of the call"),userId:q.string().nullish().describe("User who triggered the call"),requestId:q.string().describe("Unique request identifier"),userAgent:q.string().nullish().describe("Client identifier (x-mesh-client header)"),virtualMcpId:q.string().nullish().describe("Virtual MCP (Agent) ID if routed through an agent"),properties:q.record(q.string(),q.string()).nullish().describe("Custom key-value metadata attached to the log")}),ON1=t1({name:"MONITORING_LOGS_LIST",description:"List monitoring logs for tool calls in the organization",annotations:{title:"List Monitoring Logs",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({connectionId:q.string().optional().describe("Filter by connection ID"),excludeConnectionIds:q.array(q.string()).optional().describe("Exclude logs from these connection IDs (e.g. system connections)"),virtualMcpId:q.string().optional().describe("Filter by Virtual MCP (Agent) ID"),toolName:q.string().optional().describe("Filter by tool name"),isError:q.boolean().optional().describe("Filter by error status"),startDate:q.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:q.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)"),limit:q.number().default(20).describe("Maximum number of results"),offset:q.number().default(0).describe("Offset for pagination"),properties:q.record(q.string(),q.string()).optional().describe("Filter by exact property key=value matches"),propertyKeys:q.array(q.string()).optional().describe("Filter by logs that have these property keys"),propertyPatterns:q.record(q.string(),q.string()).optional().describe("Filter by property value patterns (SQL LIKE, use % as wildcard)"),propertyInValues:q.record(q.string(),q.string()).optional().describe("Filter by exact match within comma-separated values (e.g., user_tags in 'Engineering')")}),outputSchema:q.object({logs:q.array(jd6).describe("Array of monitoring logs"),total:q.number().describe("Total number of logs matching filters"),offset:q.number().describe("Current offset for pagination"),limit:q.number().describe("Current limit for pagination")}),handler:async(Y,Q)=>{let X=v0(Q),G=Y.properties||Y.propertyKeys||Y.propertyPatterns||Y.propertyInValues?{properties:Y.properties,propertyKeys:Y.propertyKeys,propertyPatterns:Y.propertyPatterns,propertyInValues:Y.propertyInValues}:void 0,K={organizationId:X.id,connectionId:Y.connectionId,excludeConnectionIds:Y.excludeConnectionIds,virtualMcpId:Y.virtualMcpId,toolName:Y.toolName,isError:Y.isError,startDate:Y.startDate?new Date(Y.startDate):void 0,endDate:Y.endDate?new Date(Y.endDate):void 0,limit:Y.limit,offset:Y.offset,propertyFilters:G},W=await Q.storage.monitoring.query(K);return{logs:W.logs.map((Z)=>({...Z,timestamp:Z.timestamp instanceof Date?Z.timestamp.toISOString():Z.timestamp})),total:W.total,offset:Y.offset,limit:Y.limit}}})});var NN1;var qi0=j(()=>{F4();n1();NN1=t1({name:"MONITORING_STATS",description:"Get aggregated statistics for tool call monitoring",annotations:{title:"Get Monitoring Stats",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({startDate:q.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:q.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)")}),outputSchema:q.object({totalCalls:q.number().describe("Total number of tool calls"),errorRate:q.number().describe("Error rate as a decimal (0 to 1)"),avgDurationMs:q.number().describe("Average call duration in milliseconds"),errorRatePercent:q.string().describe("Error rate as a percentage string")}),handler:async(Y,Q)=>{let J={organizationId:v0(Q).id,startDate:Y.startDate?new Date(Y.startDate):void 0,endDate:Y.endDate?new Date(Y.endDate):void 0},G=await Q.storage.monitoring.getStats(J);return{...G,errorRatePercent:(G.errorRate*100).toFixed(2)}}})});var Bi0=j(()=>{Vi0();qi0()});var kd6,vd6,_d6,yd6,fd6,Rv,Iv,OB,bd6,hd6,Ui0;var IP=j(()=>{n1();kd6=q.enum(["sum","avg","min","max","count","last"]).describe("Aggregation function to apply"),vd6=q.enum(["metric","timeseries","table"]).describe("Widget display type"),_d6=q.object({path:q.string().describe("JSONPath to extract value, e.g., '$.usage.total_tokens'"),from:q.enum(["input","output"]).describe("Extract from tool call input or output")}),yd6=q.object({fn:kd6,groupBy:q.string().optional().describe("Optional JSONPath for grouping results"),interval:q.string().optional().describe("For timeseries widgets: interval like '1h', '1d', '15m'")}),fd6=q.object({connectionIds:q.array(q.string()).optional().describe("Filter to specific connections"),toolNames:q.array(q.string()).optional().describe("Filter to specific tools")}),Rv=q.object({id:q.string().describe("Unique widget identifier"),name:q.string().describe("Widget display name"),type:vd6,source:_d6,aggregation:yd6,filter:fd6.optional()}),Iv=q.object({connectionIds:q.array(q.string()).optional().describe("Filter to specific connections"),virtualMcpIds:q.array(q.string()).optional().describe("Filter to specific virtual MCPs/agents"),toolNames:q.array(q.string()).optional().describe("Filter to specific tools"),propertyFilters:q.record(q.string(),q.string()).optional().describe("Filter by exact metadata property key=value matches (e.g., { environment: 'production' })")}),OB=q.object({id:q.string().describe("Unique dashboard identifier"),organizationId:q.string().describe("Organization ID"),name:q.string().describe("Dashboard name"),description:q.string().nullable().describe("Dashboard description"),filters:Iv.nullable().describe("Global filters applied to all widgets"),widgets:q.array(Rv).describe("Widget definitions"),createdBy:q.string().describe("User ID who created the dashboard"),createdAt:q.string().describe("Creation timestamp"),updatedAt:q.string().describe("Last update timestamp")}),bd6=q.object({key:q.string().describe("Group key value"),value:q.number().describe("Aggregated value for this group")}),hd6=q.object({timestamp:q.string().describe("Time bucket timestamp"),value:q.number().describe("Aggregated value for this time bucket")}),Ui0=q.object({widgetId:q.string().describe("Widget ID this result is for"),value:q.number().nullable().describe("Aggregated value (for metric type)"),groups:q.array(bd6).optional().describe("Grouped results (when groupBy is specified)"),timeseries:q.array(hd6).optional().describe("Timeseries data (for timeseries type)")})});var LN1;var Di0=j(()=>{F4();n1();IP();LN1=t1({name:"MONITORING_DASHBOARD_CREATE",description:"Create a new monitoring dashboard with JSONPath widgets",annotations:{title:"Create Monitoring Dashboard",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:q.object({name:q.string().min(1).describe("Dashboard name"),description:q.string().optional().describe("Dashboard description"),filters:Iv.optional().describe("Global filters applied to all widgets"),widgets:q.array(Rv).min(1).describe("Widget definitions (at least one required)")}),outputSchema:OB,handler:async(Y,Q)=>{let X=v0(Q),J=Q.auth.user?.id;if(!J)throw Error("User authentication required");let G=await Q.storage.monitoringDashboards.create(X.id,J,{name:Y.name,description:Y.description,filters:Y.filters,widgets:Y.widgets});return{id:G.id,organizationId:G.organizationId,name:G.name,description:G.description,filters:G.filters,widgets:G.widgets,createdBy:G.createdBy,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}}})});var MN1;var zi0=j(()=>{F4();n1();IP();MN1=t1({name:"MONITORING_DASHBOARD_GET",description:"Get a monitoring dashboard by ID",annotations:{title:"Get Monitoring Dashboard",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({id:q.string().describe("Dashboard ID")}),outputSchema:OB.nullable(),handler:async(Y,Q)=>{let X=v0(Q),J=await Q.storage.monitoringDashboards.get(Y.id);if(!J||J.organizationId!==X.id)return null;return{id:J.id,organizationId:J.organizationId,name:J.name,description:J.description,filters:J.filters,widgets:J.widgets,createdBy:J.createdBy,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt,updatedAt:J.updatedAt instanceof Date?J.updatedAt.toISOString():J.updatedAt}}})});var wN1;var Oi0=j(()=>{F4();n1();IP();wN1=t1({name:"MONITORING_DASHBOARD_LIST",description:"List all monitoring dashboards for the organization",annotations:{title:"List Monitoring Dashboards",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({}),outputSchema:q.object({dashboards:q.array(OB).describe("List of dashboards"),total:q.number().describe("Total number of dashboards")}),handler:async(Y,Q)=>{let X=v0(Q),J=await Q.storage.monitoringDashboards.list(X.id);return{dashboards:J.map((G)=>({id:G.id,organizationId:G.organizationId,name:G.name,description:G.description,filters:G.filters,widgets:G.widgets,createdBy:G.createdBy,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt})),total:J.length}}})});var AN1;var Ni0=j(()=>{F4();n1();IP();AN1=t1({name:"MONITORING_DASHBOARD_UPDATE",description:"Update an existing monitoring dashboard",annotations:{title:"Update Monitoring Dashboard",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({id:q.string().describe("Dashboard ID to update"),name:q.string().optional().describe("New dashboard name"),description:q.string().nullable().optional().describe("New dashboard description"),filters:Iv.nullable().optional().describe("New global filters"),widgets:q.array(Rv).optional().describe("New widget definitions")}),outputSchema:OB,handler:async(Y,Q)=>{let X=v0(Q),J=await Q.storage.monitoringDashboards.get(Y.id);if(!J||J.organizationId!==X.id)throw Error(`Dashboard ${Y.id} not found`);let G={};if(Y.name!==void 0)G.name=Y.name;if(Y.description!==void 0)G.description=Y.description;if(Y.filters!==void 0)G.filters=Y.filters;if(Y.widgets!==void 0)G.widgets=Y.widgets;let K=await Q.storage.monitoringDashboards.update(Y.id,G);return{id:K.id,organizationId:K.organizationId,name:K.name,description:K.description,filters:K.filters,widgets:K.widgets,createdBy:K.createdBy,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt,updatedAt:K.updatedAt instanceof Date?K.updatedAt.toISOString():K.updatedAt}}})});var PN1;var Li0=j(()=>{F4();n1();PN1=t1({name:"MONITORING_DASHBOARD_DELETE",description:"Delete a monitoring dashboard",annotations:{title:"Delete Monitoring Dashboard",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({id:q.string().describe("Dashboard ID to delete")}),outputSchema:q.object({success:q.boolean().describe("Whether the deletion was successful")}),handler:async(Y,Q)=>{let X=v0(Q),J=await Q.storage.monitoringDashboards.get(Y.id);if(!J||J.organizationId!==X.id)throw Error(`Dashboard ${Y.id} not found`);return await Q.storage.monitoringDashboards.delete(Y.id),{success:!0}}})});var EN1;var Mi0=j(()=>{F4();n1();IP();EN1=t1({name:"MONITORING_DASHBOARD_QUERY",description:"Execute a dashboard's widgets and return aggregated monitoring data",annotations:{title:"Query Monitoring Dashboard",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({dashboardId:q.string().describe("Dashboard ID to query"),timeRange:q.object({startDate:q.string().datetime().describe("Start of time range (ISO 8601)"),endDate:q.string().datetime().describe("End of time range (ISO 8601)")}).optional().describe("Time range for the query (defaults to last 24 hours)"),propertyFilters:q.object({properties:q.record(q.string(),q.string()).optional().describe("Exact match: property key equals value"),propertyKeys:q.array(q.string()).optional().describe("Exists: filter logs that have these property keys"),propertyPatterns:q.record(q.string(),q.string()).optional().describe("Pattern match: property value matches pattern (SQL LIKE, use % as wildcard)"),propertyInValues:q.record(q.string(),q.string()).optional().describe("In match: exact match within comma-separated values")}).optional().describe("Runtime property filters applied to all widgets (merged with dashboard-level filters)")}),outputSchema:q.object({dashboardId:q.string().describe("Dashboard ID"),results:q.array(Ui0).describe("Widget query results"),timeRange:q.object({startDate:q.string(),endDate:q.string()}).describe("Time range used for the query")}),handler:async(Y,Q)=>{let X=v0(Q),J=await Q.storage.monitoringDashboards.get(Y.dashboardId);if(!J||J.organizationId!==X.id)throw Error(`Dashboard ${Y.dashboardId} not found`);let G=new Date,K=Y.timeRange?.startDate?new Date(Y.timeRange.startDate):new Date(G.getTime()-86400000),W=Y.timeRange?.endDate?new Date(Y.timeRange.endDate):G,Z=await Promise.all(J.widgets.map(async(H)=>{let $=J.filters?.propertyFilters,F=Y.propertyFilters,V=$||F?{properties:{...$,...F?.properties},propertyKeys:F?.propertyKeys,propertyPatterns:F?.propertyPatterns,propertyInValues:F?.propertyInValues}:void 0,B={connectionIds:H.filter?.connectionIds??J.filters?.connectionIds??void 0,virtualMcpIds:J.filters?.virtualMcpIds??void 0,toolNames:H.filter?.toolNames??J.filters?.toolNames??void 0,startDate:K,endDate:W,propertyFilters:V};try{let U=await Q.storage.monitoring.aggregate({organizationId:X.id,path:H.source.path,from:H.source.from,aggregation:H.aggregation.fn,groupBy:H.aggregation.groupBy,interval:H.aggregation.interval,filters:B});return{widgetId:H.id,value:U.value,groups:U.groups,timeseries:U.timeseries}}catch(U){return console.error(`Widget ${H.id} aggregation failed:`,U),{widgetId:H.id,value:null,groups:void 0,timeseries:void 0}}}));return{dashboardId:Y.dashboardId,results:Z,timeRange:{startDate:K.toISOString(),endDate:W.toISOString()}}}})});var xd6,TN1;var wi0=j(()=>{F4();n1();xd6=q.object({type:q.enum(["metric","timeseries","table"]),source:q.object({path:q.string().describe("JSONPath to extract value from"),from:q.enum(["input","output"]).describe("Extract from input or output")}),aggregation:q.object({fn:q.enum(["sum","avg","min","max","count","last"]).describe("Aggregation function"),groupBy:q.string().optional().describe("JSONPath for grouping (table)"),interval:q.string().optional().describe("Time interval for timeseries (15m, 1h, 1d)")}),filter:q.object({connectionIds:q.array(q.string()).optional(),toolNames:q.array(q.string()).optional()}).optional()}),TN1=t1({name:"MONITORING_WIDGET_PREVIEW",description:"Preview a widget aggregation without saving. Used to test queries in the dashboard editor.",annotations:{title:"Preview Monitoring Widget",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({widget:xd6.describe("Widget configuration to preview"),timeRange:q.object({startDate:q.string().datetime().describe("Start of time range (ISO 8601)"),endDate:q.string().datetime().describe("End of time range (ISO 8601)")}).optional().describe("Time range for the query (defaults to last 24 hours)"),propertyFilters:q.object({properties:q.record(q.string(),q.string()).optional().describe("Exact match: property key equals value"),propertyKeys:q.array(q.string()).optional().describe("Exists: filter logs that have these property keys"),propertyPatterns:q.record(q.string(),q.string()).optional().describe("Pattern match: property value matches pattern (SQL LIKE)"),propertyInValues:q.record(q.string(),q.string()).optional().describe("In match: exact match within comma-separated values")}).optional().describe("Property filters to apply")}),outputSchema:q.object({value:q.number().nullable().optional().describe("Aggregated value"),groups:q.array(q.object({key:q.string(),value:q.number()})).optional().describe("Grouped results for table widgets"),timeseries:q.array(q.object({timestamp:q.string(),value:q.number()})).optional().describe("Timeseries data points"),matchedRecords:q.number().describe("Number of records that matched"),timeRange:q.object({startDate:q.string(),endDate:q.string()}).describe("Time range used for the query")}),handler:async(Y,Q)=>{let X=v0(Q),{widget:J,timeRange:G}=Y,K=new Date,W=G?.startDate?new Date(G.startDate):new Date(K.getTime()-86400000),Z=G?.endDate?new Date(G.endDate):K,H={connectionIds:J.filter?.connectionIds,toolNames:J.filter?.toolNames,startDate:W,endDate:Z,propertyFilters:Y.propertyFilters};try{let $=await Q.storage.monitoring.countMatched({organizationId:X.id,path:J.source.path,from:J.source.from,filters:H}),F=await Q.storage.monitoring.aggregate({organizationId:X.id,path:J.source.path,from:J.source.from,aggregation:J.aggregation.fn,groupBy:J.aggregation.groupBy,interval:J.aggregation.interval,filters:H});return{value:F.value,groups:F.groups,timeseries:F.timeseries,matchedRecords:$,timeRange:{startDate:W.toISOString(),endDate:Z.toISOString()}}}catch($){return console.error("Widget preview aggregation failed:",$),{value:null,matchedRecords:0,timeRange:{startDate:W.toISOString(),endDate:Z.toISOString()}}}}})});var Ai0=j(()=>{Di0();zi0();Oi0();Ni0();Li0();Mi0();wi0()});var CN1;var Pi0=j(()=>{n1();F4();CN1=t1({name:"ORGANIZATION_CREATE",description:"Create a new organization",annotations:{title:"Create Organization",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:q.object({slug:q.string().min(1).max(50).regex(/^[a-z0-9-]+$/,"Slug must be lowercase alphanumeric with hyphens"),name:q.string().min(1).max(255),description:q.string().optional()}),outputSchema:q.object({id:q.string(),name:q.string(),slug:q.string(),logo:q.string().nullable().optional(),metadata:q.any().optional(),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),members:q.array(q.any()).optional()}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=TY(Q);if(!X)throw Error("User ID required to create organization");let J=await Q.boundAuth.organization.create({name:Y.name,slug:Y.slug,metadata:Y.description?{description:Y.description}:void 0,userId:X});if(!J)throw Error("Failed to create organization");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var RN1;var Ei0=j(()=>{n1();F4();RN1=t1({name:"ORGANIZATION_LIST",description:"List all organizations user has access to",annotations:{title:"List Organizations",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({userId:q.string().optional()}),outputSchema:q.object({organizations:q.array(q.object({id:q.string(),name:q.string(),slug:q.string(),logo:q.string().nullable().optional(),metadata:q.any().optional(),createdAt:q.string().datetime().describe("ISO 8601 timestamp")}))}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=TY(Q),J=Y.userId||X;if(!J)throw Error("User ID required to list organizations");return{organizations:(await Q.boundAuth.organization.list(J)).map((K)=>({...K,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt}))}}})});var IN1;var Ti0=j(()=>{n1();F4();IN1=t1({name:"ORGANIZATION_GET",description:"Get organization details by slug or ID",annotations:{title:"Get Organization",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({}),outputSchema:q.object({id:q.string(),name:q.string(),slug:q.string(),logo:q.string().nullable().optional(),metadata:q.any().optional(),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),members:q.array(q.any()).optional(),invitations:q.array(q.any()).optional()}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=await Q.boundAuth.organization.get();if(!X)throw Error("No active organization found");let J=new Date,G=X.invitations?.filter((K)=>new Date(K.expiresAt)>J);return{...X,invitations:G,createdAt:X.createdAt instanceof Date?X.createdAt.toISOString():X.createdAt}}})});var jN1;var Ci0=j(()=>{n1();F4();jN1=t1({name:"ORGANIZATION_UPDATE",description:"Update an existing organization",annotations:{title:"Update Organization",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({id:q.string(),slug:q.string().min(1).max(50).regex(/^[a-z0-9-]+$/).optional(),name:q.string().min(1).max(255).optional(),description:q.string().optional()}),outputSchema:q.object({id:q.string(),name:q.string(),slug:q.string(),logo:q.string().nullable().optional(),metadata:q.any().optional(),createdAt:q.string().datetime().describe("ISO 8601 timestamp")}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X={};if(Y.name)X.name=Y.name;if(Y.slug)X.slug=Y.slug;if(Y.description)X.metadata={description:Y.description};let J=await Q.boundAuth.organization.update({organizationId:Y.id,data:X});if(!J)throw Error("Failed to update organization");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var SN1;var Ri0=j(()=>{n1();F4();SN1=t1({name:"ORGANIZATION_DELETE",description:"Delete an organization",annotations:{title:"Delete Organization",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({id:q.string()}),outputSchema:q.object({success:q.boolean(),id:q.string()}),handler:async(Y,Q)=>{return D0(Q),await Q.access.check(),await Q.boundAuth.organization.delete(Y.id),{success:!0,id:Y.id}}})});var jv;var kN1=j(()=>{n1();jv=q.object({title:q.string(),url:q.string(),icon:q.string()})});var vN1;var Ii0=j(()=>{n1();F4();kN1();vN1=t1({name:"ORGANIZATION_SETTINGS_GET",description:"Get organization-level settings",annotations:{title:"Get Organization Settings",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({}),outputSchema:q.object({organizationId:q.string(),sidebar_items:q.array(jv).nullable().optional(),enabled_plugins:q.array(q.string()).nullable().optional(),createdAt:q.string().datetime().optional().describe("ISO 8601 timestamp"),updatedAt:q.string().datetime().optional().describe("ISO 8601 timestamp")}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=Q.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");let J=await Q.storage.organizationSettings.get(X);if(!J)return{organizationId:X};return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt,updatedAt:J.updatedAt instanceof Date?J.updatedAt.toISOString():J.updatedAt}}})});var _N1;var ji0=j(()=>{n1();F4();kN1();_N1=t1({name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization-level settings",annotations:{title:"Update Organization Settings",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({organizationId:q.string(),sidebar_items:q.array(jv).optional(),enabled_plugins:q.array(q.string()).optional()}),outputSchema:q.object({organizationId:q.string(),sidebar_items:q.array(jv).nullable().optional(),enabled_plugins:q.array(q.string()).nullable().optional(),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),updatedAt:q.string().datetime().describe("ISO 8601 timestamp")}),handler:async(Y,Q)=>{if(D0(Q),await Q.access.check(),Q.organization&&Q.organization.id!==Y.organizationId)throw Error("Cannot update settings for a different organization");let X=await Q.storage.organizationSettings.upsert(Y.organizationId,{sidebar_items:Y.sidebar_items,enabled_plugins:Y.enabled_plugins});return{...X,createdAt:X.createdAt instanceof Date?X.createdAt.toISOString():X.createdAt,updatedAt:X.updatedAt instanceof Date?X.updatedAt.toISOString():X.updatedAt}}})});var yN1;var Si0=j(()=>{n1();F4();yN1=t1({name:"ORGANIZATION_MEMBER_ADD",description:"Add a member to an organization",annotations:{title:"Add Organization Member",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({organizationId:q.string().optional(),userId:q.string(),role:q.array(q.string())}),outputSchema:q.object({id:q.string(),organizationId:q.string(),userId:q.string(),role:q.union([q.string(),q.array(q.string())]),createdAt:q.string().datetime().describe("ISO 8601 timestamp")}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=Y.organizationId||Q.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");if(X!==Q.organization?.id)throw Error("Organization ID does not match authenticated organization");let J=await Q.boundAuth.organization.addMember({organizationId:X,userId:Y.userId,role:Y.role});if(!J)throw Error("Failed to add member");return{...J,role:J.role,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var fN1;var ki0=j(()=>{n1();F4();fN1=t1({name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove a member from an organization",annotations:{title:"Remove Organization Member",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({organizationId:q.string().optional(),memberIdOrEmail:q.string()}),outputSchema:q.object({success:q.boolean(),memberIdOrEmail:q.string()}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=Y.organizationId||Q.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");return await Q.boundAuth.organization.removeMember({organizationId:X,memberIdOrEmail:Y.memberIdOrEmail}),{success:!0,memberIdOrEmail:Y.memberIdOrEmail}}})});var bN1;var vi0=j(()=>{n1();F4();bN1=t1({name:"ORGANIZATION_MEMBER_LIST",description:"List all members in an organization",annotations:{title:"List Organization Members",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({limit:q.number().optional(),offset:q.number().optional()}),outputSchema:q.object({members:q.array(q.object({id:q.string(),organizationId:q.string(),userId:q.string(),role:q.string(),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),user:q.object({id:q.string(),name:q.string(),email:q.string(),image:q.string().optional()}).optional()}))}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=Q.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");let J=await Q.boundAuth.organization.listMembers({organizationId:X,limit:Y.limit,offset:Y.offset});return{members:(Array.isArray(J)?J:[]).map((K)=>({...K,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt}))}}})});var hN1;var _i0=j(()=>{n1();F4();hN1=t1({name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Update a member's role in an organization",annotations:{title:"Update Member Role",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({organizationId:q.string().optional(),memberId:q.string(),role:q.array(q.string())}),outputSchema:q.object({id:q.string(),organizationId:q.string(),userId:q.string(),role:q.union([q.literal("admin"),q.literal("member"),q.literal("owner")]),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),user:q.object({email:q.string(),name:q.string(),image:q.string().optional()})}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=Y.organizationId||Q.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");let J=await Q.boundAuth.organization.updateMemberRole({organizationId:X,memberId:Y.memberId,role:Y.role});if(!J)throw Error("Failed to update member role");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var yi0=j(()=>{Pi0();Ei0();Ti0();Ci0();Ri0();Ii0();ji0();Si0();ki0();vi0();_i0()});var md6,Sr,ld6,OO,fi0,kr;var NO=j(()=>{n1();md6=q.object({banner:q.string().nullable(),bannerColor:q.string().nullable(),icon:q.string().nullable(),themeColor:q.string().nullable()}),Sr=q.object({banner:q.string().nullable().optional(),bannerColor:q.string().nullable().optional(),icon:q.string().nullable().optional(),themeColor:q.string().nullable().optional()}),ld6=q.object({id:q.string(),title:q.string(),icon:q.string().nullable()}),OO=q.object({id:q.string(),organizationId:q.string(),slug:q.string(),name:q.string(),description:q.string().nullable(),enabledPlugins:q.array(q.string()).nullable(),ui:md6.nullable(),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),updatedAt:q.string().datetime().describe("ISO 8601 timestamp")}),fi0=OO.omit({organizationId:!0}).extend({boundConnections:q.array(ld6)}),kr=q.object({id:q.string(),projectId:q.string(),pluginId:q.string(),connectionId:q.string().nullable(),settings:q.record(q.string(),q.unknown()).nullable(),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),updatedAt:q.string().datetime().describe("ISO 8601 timestamp")})});var xN1;var bi0=j(()=>{n1();F4();NO();xN1=t1({name:"PROJECT_LIST",description:"List all projects in an organization",annotations:{title:"List Projects",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({organizationId:q.string().describe("Organization ID to list projects for")}),outputSchema:q.object({projects:q.array(fi0)}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=await Q.storage.projects.list(Y.organizationId),J=X.map((K)=>K.id),G=await Q.storage.projectPluginConfigs.getBoundConnectionsForProjects(J);return{projects:X.map((K)=>({id:K.id,slug:K.slug,name:K.name,description:K.description,enabledPlugins:K.enabledPlugins,ui:K.ui,boundConnections:G.get(K.id)??[],createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt,updatedAt:K.updatedAt instanceof Date?K.updatedAt.toISOString():K.updatedAt}))}}})});var gN1;var hi0=j(()=>{n1();F4();NO();gN1=t1({name:"PROJECT_GET",description:"Get a project by ID or slug",annotations:{title:"Get Project",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({organizationId:q.string().describe("Organization ID"),projectId:q.string().optional().describe("Project ID (either this or slug required)"),slug:q.string().optional().describe("Project slug (either this or projectId required)")}).refine((Y)=>Y.projectId||Y.slug,{message:"Either projectId or slug must be provided"}),outputSchema:q.object({project:OO.nullable()}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=null;if(Y.projectId)X=await Q.storage.projects.get(Y.projectId);else if(Y.slug)X=await Q.storage.projects.getBySlug(Y.organizationId,Y.slug);if(!X)return{project:null};return{project:{id:X.id,organizationId:X.organizationId,slug:X.slug,name:X.name,description:X.description,enabledPlugins:X.enabledPlugins,ui:X.ui,createdAt:X.createdAt instanceof Date?X.createdAt.toISOString():X.createdAt,updatedAt:X.updatedAt instanceof Date?X.updatedAt.toISOString():X.updatedAt}}}})});var uN1;var xi0=j(()=>{n1();QY();F4();NO();uN1=t1({name:"PROJECT_CREATE",description:"Create a new project in an organization",annotations:{title:"Create Project",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:q.object({organizationId:q.string().describe("Organization ID"),slug:q.string().min(1).max(100).regex(/^[a-z0-9-]+$/,"Slug must be lowercase alphanumeric with hyphens").describe("URL-friendly identifier"),name:q.string().min(1).max(200).describe("Display name"),description:q.string().max(1000).nullable().optional().describe("Project description"),enabledPlugins:q.array(q.string()).nullable().optional().describe("Plugin IDs to enable"),ui:Sr.nullable().optional().describe("UI customization")}),outputSchema:q.object({project:OO}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let{organizationId:X,slug:J,name:G,description:K,enabledPlugins:W,ui:Z}=Y;if(J===nW)throw Error(`Slug "${nW}" is reserved`);if(await Q.storage.projects.getBySlug(X,J))throw Error(`Project with slug "${J}" already exists in this organization`);let $=Z?{banner:Z.banner??null,bannerColor:Z.bannerColor??null,icon:Z.icon??null,themeColor:Z.themeColor??null}:null,F=await Q.storage.projects.create({organizationId:X,slug:J,name:G,description:K??null,enabledPlugins:W??null,ui:$});return{project:{id:F.id,organizationId:F.organizationId,slug:F.slug,name:F.name,description:F.description,enabledPlugins:F.enabledPlugins,ui:F.ui,createdAt:F.createdAt instanceof Date?F.createdAt.toISOString():F.createdAt,updatedAt:F.updatedAt instanceof Date?F.updatedAt.toISOString():F.updatedAt}}}})});var mN1;var gi0=j(()=>{n1();F4();NO();mN1=t1({name:"PROJECT_UPDATE",description:"Update a project's details",annotations:{title:"Update Project",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({projectId:q.string().describe("Project ID to update"),name:q.string().min(1).max(200).optional().describe("New display name"),description:q.string().max(1000).nullable().optional().describe("New description"),enabledPlugins:q.array(q.string()).nullable().optional().describe("Updated plugin IDs"),ui:Sr.nullable().optional().describe("Updated UI customization")}),outputSchema:q.object({project:OO.nullable()}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let{projectId:X,name:J,description:G,enabledPlugins:K,ui:W}=Y,Z={};if(J!==void 0)Z.name=J;if(G!==void 0)Z.description=G;if(K!==void 0)Z.enabledPlugins=K;if(W!==void 0)Z.ui=W?{banner:W.banner??null,bannerColor:W.bannerColor??null,icon:W.icon??null,themeColor:W.themeColor??null}:null;let H=await Q.storage.projects.update(X,Z);if(!H)return{project:null};return{project:{id:H.id,organizationId:H.organizationId,slug:H.slug,name:H.name,description:H.description,enabledPlugins:H.enabledPlugins,ui:H.ui,createdAt:H.createdAt instanceof Date?H.createdAt.toISOString():H.createdAt,updatedAt:H.updatedAt instanceof Date?H.updatedAt.toISOString():H.updatedAt}}}})});var lN1;var ui0=j(()=>{n1();QY();F4();lN1=t1({name:"PROJECT_DELETE",description:"Delete a project (cannot delete org-admin)",annotations:{title:"Delete Project",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({projectId:q.string().describe("Project ID to delete")}),outputSchema:q.object({success:q.boolean(),message:q.string().optional()}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let{projectId:X}=Y,J=await Q.storage.projects.get(X);if(!J)return{success:!1,message:"Project not found"};if(J.slug===nW)return{success:!1,message:"Cannot delete the org-admin project"};return{success:await Q.storage.projects.delete(X)}}})});var dN1;var mi0=j(()=>{n1();F4();NO();dN1=t1({name:"PROJECT_PLUGIN_CONFIG_GET",description:"Get plugin configuration for a project",annotations:{title:"Get Project Plugin Config",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({projectId:q.string().describe("Project ID"),pluginId:q.string().describe("Plugin ID")}),outputSchema:q.object({config:kr.nullable()}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let{projectId:X,pluginId:J}=Y,G=await Q.storage.projectPluginConfigs.get(X,J);if(!G)return{config:null};return{config:{id:G.id,projectId:G.projectId,pluginId:G.pluginId,connectionId:G.connectionId,settings:G.settings,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}}}})});var pN1;var li0=j(()=>{n1();F4();NO();Er();pN1=t1({name:"PROJECT_PLUGIN_CONFIG_UPDATE",description:"Update or create plugin configuration for a project",annotations:{title:"Update Project Plugin Config",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({projectId:q.string().describe("Project ID"),pluginId:q.string().describe("Plugin ID"),connectionId:q.string().nullable().optional().describe("MCP connection to bind"),settings:q.record(q.string(),q.unknown()).nullable().optional().describe("Plugin-specific settings")}),outputSchema:q.object({config:kr}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let{projectId:X,pluginId:J,connectionId:G,settings:K}=Y,W=TY(Q),Z=await Q.storage.projects.get(X);if(!Z)throw Error(`Project not found: ${X}`);let H=G?await Q.storage.connections.findById(G):null;if(G&&Z.organizationId&&!H&&LP()){if(Pr(G,Z.organizationId)){if(!W)throw Error("User ID required to create dev-assets connection");let F=MP(Z.organizationId,X7());await Q.storage.connections.create({...F,organization_id:Z.organizationId,created_by:W})}}let $=await Q.storage.projectPluginConfigs.upsert(X,J,{connectionId:G,settings:K});return{config:{id:$.id,projectId:$.projectId,pluginId:$.pluginId,connectionId:$.connectionId,settings:$.settings,createdAt:$.createdAt instanceof Date?$.createdAt.toISOString():$.createdAt,updatedAt:$.updatedAt instanceof Date?$.updatedAt.toISOString():$.updatedAt}}}})});var di0=j(()=>{bi0();hi0();xi0();gi0();ui0();mi0();li0()});var cN1;var pi0=j(()=>{n1();F4();cN1=t1({name:"TAGS_LIST",description:"List all tags in an organization",annotations:{title:"List Tags",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({}),outputSchema:q.object({tags:q.array(q.object({id:q.string(),organizationId:q.string(),name:q.string(),createdAt:q.string().describe("ISO 8601 timestamp")}))}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=v0(Q);return{tags:(await Q.storage.tags.listOrgTags(X.id)).map((G)=>({...G,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():String(G.createdAt)}))}}})});var nN1;var ci0=j(()=>{n1();F4();nN1=t1({name:"TAGS_CREATE",description:"Create a new tag in an organization",annotations:{title:"Create Tag",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:q.object({name:q.string().min(1).max(50).describe("Tag name")}),outputSchema:q.object({tag:q.object({id:q.string(),organizationId:q.string(),name:q.string(),createdAt:q.string().describe("ISO 8601 timestamp")})}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=v0(Q),J=await Q.storage.tags.createTag(X.id,Y.name);return{tag:{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():String(J.createdAt)}}}})});var iN1;var ni0=j(()=>{n1();F4();iN1=t1({name:"TAGS_DELETE",description:"Delete a tag from an organization (removes from all members)",annotations:{title:"Delete Tag",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({tagId:q.string().describe("Tag ID to delete")}),outputSchema:q.object({success:q.boolean()}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=v0(Q),J=await Q.storage.tags.getTag(Y.tagId);if(!J)throw Error("Tag not found");if(J.organizationId!==X.id)throw Error("Tag does not belong to this organization");return await Q.storage.tags.deleteTag(Y.tagId),{success:!0}}})});var aN1;var ii0=j(()=>{n1();F4();aN1=t1({name:"MEMBER_TAGS_GET",description:"Get tags assigned to a member",annotations:{title:"Get Member Tags",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({memberId:q.string().describe("Member ID")}),outputSchema:q.object({tags:q.array(q.object({id:q.string(),organizationId:q.string(),name:q.string(),createdAt:q.string().describe("ISO 8601 timestamp")}))}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=v0(Q);if(!await Q.storage.tags.verifyMemberOrg(Y.memberId,X.id))throw Error(`Member not found in this organization: ${Y.memberId}`);return{tags:(await Q.storage.tags.getMemberTags(Y.memberId)).map((K)=>({...K,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():String(K.createdAt)}))}}})});var rN1;var ai0=j(()=>{n1();F4();rN1=t1({name:"MEMBER_TAGS_SET",description:"Set tags for a member (replaces all existing tags)",annotations:{title:"Set Member Tags",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({memberId:q.string().describe("Member ID"),tagIds:q.array(q.string()).describe("Array of tag IDs to assign")}),outputSchema:q.object({success:q.boolean(),tags:q.array(q.object({id:q.string(),organizationId:q.string(),name:q.string(),createdAt:q.string().describe("ISO 8601 timestamp")}))}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=v0(Q);if(!await Q.storage.tags.verifyMemberOrg(Y.memberId,X.id))throw Error(`Member not found in this organization: ${Y.memberId}`);for(let K of Y.tagIds){let W=await Q.storage.tags.getTag(K);if(!W)throw Error(`Tag not found: ${K}`);if(W.organizationId!==X.id)throw Error(`Tag does not belong to this organization: ${K}`)}return await Q.storage.tags.setMemberTags(Y.memberId,Y.tagIds),{success:!0,tags:(await Q.storage.tags.getMemberTags(Y.memberId)).map((K)=>({...K,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():String(K.createdAt)}))}}})});var ri0=j(()=>{pi0();ci0();ni0();ii0();ai0()});var oi0=j(()=>{QY()});var si0,X3,ti0,ei0;var LO=j(()=>{n1();oi0();si0=q.object({id:q.string().describe("Unique message ID"),thread_id:q.string().describe("ID of the parent thread"),metadata:q.unknown().optional().describe("Optional message metadata"),parts:q.array(q.record(q.string(),q.unknown())).describe("Message content parts (AI SDK UIMessagePart format)"),role:q.enum(["user","assistant","system"]).describe("Message role"),created_at:q.string().datetime().describe("Timestamp of creation"),updated_at:q.string().datetime().describe("Timestamp of last update")}),X3=q.object({id:q.string().describe("Unique thread ID"),organization_id:q.string().describe("Organization this thread belongs to"),title:q.string().describe("Thread title"),description:q.string().nullable().describe("Thread description"),created_at:q.string().datetime().describe("Timestamp of creation"),updated_at:q.string().datetime().describe("Timestamp of last update"),hidden:q.boolean().optional().describe("Whether the thread is hidden"),status:q.enum([...WL,"expired"]).describe("Thread execution status. 'expired' is virtual -- computed at read time for stale in_progress threads"),created_by:q.string().describe("User ID who created the thread"),updated_by:q.string().nullable().describe("User ID who last updated the thread")}),ti0=q.object({id:q.string().optional().describe("Optional custom ID for the thread"),title:q.string().describe("Thread title"),description:q.string().nullish().describe("Thread description")}),ei0=q.object({title:q.string().optional().describe("New thread title"),description:q.string().nullish().describe("New thread description"),hidden:q.boolean().optional().describe("Whether the thread is hidden")})});var cd6,nd6,oN1;var Ya0=j(()=>{n1();F4();LO();F7();cd6=q.object({data:ti0.describe("Data for the new thread (id is auto-generated if not provided)")}),nd6=q.object({item:X3.describe("The created thread entity")}),oN1=t1({name:"COLLECTION_THREADS_CREATE",description:"Create a new thread in the organization",annotations:{title:"Create Thread",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:cd6,outputSchema:nd6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=TY(Q);if(!J)throw Error("User ID required to create thread");let G=Y.data.id??J9("thrd"),K=await Q.storage.threads.create({id:G,organization_id:X.id,title:Y.data.title,description:Y.data.description,created_by:J});return{item:{...K,hidden:K.hidden??!1}}}})});function NB(Y,Q=Date.now()){let X=Y.status;if(X==="in_progress"){let J=new Date(Y.updated_at).getTime();if(!Number.isFinite(J)||Q-J>1800000)X="expired"}return{...Y,status:X,hidden:Y.hidden??!1}}var id6,ad6,sN1;var Qa0=j(()=>{MG();F4();LO();n1();id6=lZ.extend({where:q.object({created_by:q.string().optional()}).optional()}),ad6=n$(X3),sN1=t1({name:"COLLECTION_THREADS_LIST",description:"List all threads in the organization with filtering, sorting, and pagination",annotations:{title:"List Threads",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:id6,outputSchema:ad6,handler:async(Y,Q)=>{await Q.access.check();let X=Q.auth.user?.id;if(!X)throw Error("User ID required to list threads");let J=v0(Q),G=Y.offset??0,K=Y.limit??100,{threads:W,total:Z}=await Q.storage.threads.list(J.id,X,{limit:K,offset:G}),H=G+K<Z,$=Date.now();return{items:W.map((F)=>NB(F,$)),totalCount:Z,hasMore:H}}})});var rd6,tN1;var Xa0=j(()=>{MG();F4();LO();rd6=hS(X3),tN1=t1({name:"COLLECTION_THREADS_GET",description:"Get thread details by ID",annotations:{title:"Get Thread",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:bS,outputSchema:rd6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=await Q.storage.threads.get(Y.id);if(!J||J.organization_id!==X.id)return{item:null};return{item:NB(J)}}})});var od6,sd6,eN1;var Ja0=j(()=>{n1();F4();LO();od6=q.object({id:q.string().describe("ID of the thread to update"),data:ei0.describe("Partial thread data to update")}),sd6=q.object({item:X3.describe("The updated thread entity")}),eN1=t1({name:"COLLECTION_THREADS_UPDATE",description:"Update an existing thread in the organization",annotations:{title:"Update Thread",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:od6,outputSchema:sd6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=TY(Q);if(!J)throw Error("User ID required to update thread");let{id:G,data:K}=Y,W=await Q.storage.threads.get(G);if(!W||W.organization_id!==X.id)throw Error("Thread not found in organization");let Z=await Q.storage.threads.update(G,{title:K.title,description:K.description,hidden:K.hidden,updated_by:J});return{item:NB(Z)}}})});var YL1;var Ga0=j(()=>{MG();F4();LO();YL1=t1({name:"COLLECTION_THREADS_DELETE",description:"Delete a thread",annotations:{title:"Delete Thread",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:xS,outputSchema:gS(X3),handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=await Q.storage.threads.get(Y.id);if(!J)throw Error(`Thread not found: ${Y.id}`);if(J.organization_id!==X.id)throw Error(`Thread not found: ${Y.id}`);return await Q.storage.threads.delete(Y.id),{item:NB(J)}}})});function Wa0(Y){if(!Y)return null;if("field"in Y&&Y.field[0]==="thread_id"&&Y.operator==="eq")return String(Y.value);if("conditions"in Y)for(let Q of Y.conditions){let X=Wa0(Q);if(X)return X}return null}var td6,QL1;var Za0=j(()=>{MG();F4();LO();td6=n$(si0),QL1=t1({name:"COLLECTION_THREAD_MESSAGES_LIST",description:"List all messages for a specific thread",annotations:{title:"List Thread Messages",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:lZ,outputSchema:td6,handler:async(Y,Q)=>{let X=v0(Q);await Q.access.check();let J=Wa0(Y.where);if(!J)throw Error("thread_id filter is required in where clause");let G=await Q.storage.threads.get(J);if(!G||G.organization_id!==X.id)return{items:[],totalCount:0,hasMore:!1};let K=Y.offset??0,W=Y.limit??100,{messages:Z,total:H}=await Q.storage.threads.listMessages(J,{limit:W,offset:K}),$=K+W<H;return{items:Z,totalCount:H,hasMore:$}}})});var Ka0=j(()=>{Ya0();Qa0();Xa0();Ja0();Ga0();Za0()});var Yp6,Qp6,XL1;var Ha0=j(()=>{n1();F4();Yp6=q.object({id:q.string().min(1)}),Qp6=q.object({user:q.object({id:q.string(),name:q.string(),email:q.string(),image:q.string().nullable()}).nullable()}),XL1=t1({name:"USER_GET",description:"Get a user by id (restricted to shared organizations)",annotations:{title:"Get User",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:Yp6,outputSchema:Qp6,handler:async(Y,Q)=>{await Q.access.check(),D0(Q);let X=TY(Q);if(!X)throw Error("Authentication required");let J=await Q.storage.users.findById(Y.id,X);if(!J)return{user:null};return{user:{id:J.id,name:J.name,email:J.email,image:J.image??null}}}})});var $a0=j(()=>{Ha0()});var Va0={};R4(Va0,{managementMCP:()=>JL1,ALL_TOOLS:()=>Fa0});var Jp6,Gp6,Fa0,JL1=async(Y)=>{let Q=null;if(Y.organization){let G=await Y.storage.organizationSettings.get(Y.organization.id),K=await Y.storage.projects.list(Y.organization.id),W=new Set(G?.enabled_plugins??[]);for(let Z of K)if(Z.enabledPlugins)for(let H of Z.enabledPlugins)W.add(H);Q=W.size>0?[...W]:null}let X=Kc0(Fa0,Q),J=new EU({name:"mcp-mesh-management",version:"1.0.0"},{capabilities:{tools:{}}});for(let G of X){let K=G.inputSchema&&typeof G.inputSchema==="object"&&"shape"in G.inputSchema?G.inputSchema:q.object({}),W=G.outputSchema&&typeof G.outputSchema==="object"&&"shape"in G.outputSchema?G.outputSchema:void 0,Z=K.shape,H=W?.shape;J.registerTool(G.name,{description:G.description??"",inputSchema:Z,outputSchema:H,annotations:G.annotations,_meta:G._meta},async($)=>{Y.access.setToolName(G.name);try{let F=await G.execute($,Y);return{content:[{type:"text",text:JSON.stringify(F)}],structuredContent:F}}catch(F){return{content:[{type:"text",text:`Error: ${F.message}`}],isError:!0}}})}return J};var GL1=j(()=>{Bv();kx();n1();Rc0();pc0();hn0();mn0();sn0();Gi0();Fi0();Bi0();Ai0();yi0();di0();ri0();Ka0();$a0();Jp6=[CN1,RN1,IN1,jN1,SN1,vN1,_N1,yN1,fN1,bN1,hN1,EO1,RO1,IO1,oO1,sO1,tO1,ZN1,HN1,$N1,FN1,VN1,qN1,BN1,UN1,DN1,zN1,un0,ON1,NN1,LN1,MN1,wN1,AN1,PN1,EN1,TN1,BO1,DO1,zO1,UO1,eO1,YN1,QN1,XN1,JN1,GN1,WN1,XL1,wO1,AO1,PO1,oN1,sN1,tN1,eN1,YL1,QL1,cN1,nN1,iN1,aN1,rN1,xN1,gN1,uN1,mN1,lN1,dN1,pN1],Gp6=Hc0(),Fa0=[...Jp6,...Gp6]});function Wp6(Y){return[{permissions:{self:["*"]},getTools:async()=>{let{ALL_TOOLS:Q}=await Promise.resolve().then(() => (GL1(),Va0));return Q.map((X)=>{return{name:X.name,inputSchema:q.toJSONSchema(X.inputSchema,{unrepresentable:"any"}),outputSchema:X.outputSchema?q.toJSONSchema(X.outputSchema,{unrepresentable:"any"}):void 0,description:X.description}})},data:G91(X7(),Y)},{data:J91()},{data:X91(Y)}]}async function qa0(Y,Q){try{let X=vz(),J=new _z(process.env.ENCRYPTION_KEY||""),G=new RS(X.db,J),K=new IS(X.db),W=Wp6(Y);try{await K.create({organizationId:Y,slug:nW,name:iO,description:"Organization administration and settings",enabledPlugins:null,ui:null})}catch(Z){console.warn("Could not create org-admin project (may already exist):",Z)}await Promise.all(W.map(async(Z)=>{let H=null;if(Z.permissions)H=(await XK.api.createApiKey({body:{name:`${Z.data.app_name??crypto.randomUUID()}-mcp`,userId:Q,permissions:Z.permissions,rateLimitEnabled:!1,metadata:{organization:{id:Y},purpose:"default-org-connections"}}}))?.key;let $=await EA({id:"pending",title:Z.data.title,connection_type:Z.data.connection_type,connection_url:Z.data.connection_url,connection_token:Z.data.connection_token,connection_headers:Z.data.connection_headers}).catch(()=>null),F=await Z.getTools?.()??$?.tools??null,V=$?.scopes?.length?$.scopes:null,B=Z.data.id?Z.data.id.startsWith(`${Y}_`)?Z.data.id:`${Y}_${Z.data.id}`:void 0;await G.create({...Z.data,id:B,tools:F,configuration_scopes:V,organization_id:Y,created_by:Q,connection_token:Z.data.connection_token??H})}))}catch(X){console.error("Error creating default MCP connections:",X)}}var Ba0=j(()=>{QY();PS();ln();Mq1();wq1();rn();n1();wP()});var WL1,vr;var _r=j(()=>{WL1=["owner","admin","user"],vr=["owner","admin"]});var Zp6=(Y)=>{return{defaultSSO:[{domain:Y.domain,providerId:Y.providerId,oidcConfig:{issuer:`https://login.microsoftonline.com/${Y.MS_TENANT_ID}/v2.0`,pkce:!0,clientId:Y.MS_CLIENT_ID,clientSecret:Y.MS_CLIENT_SECRET,discoveryEndpoint:`https://login.microsoftonline.com/${Y.MS_TENANT_ID}/v2.0/.well-known/openid-configuration`,authorizationEndpoint:`https://login.microsoftonline.com/${Y.MS_TENANT_ID}/oauth2/v2.0/authorize`,tokenEndpoint:`https://login.microsoftonline.com/${Y.MS_TENANT_ID}/oauth2/v2.0/token`,jwksEndpoint:`https://login.microsoftonline.com/${Y.MS_TENANT_ID}/discovery/v2.0/keys`,userInfoEndpoint:"https://graph.microsoft.com/oidc/userinfo",tokenEndpointAuthentication:"client_secret_post",scopes:Y.scopes,mapping:{id:"sub",email:"email",emailVerified:"email_verified",name:"name",image:"picture",extraFields:{emailVerified:"email_verified"}}}}]}},Ua0=(Y)=>{if(Y.providerId==="microsoft")return Zp6(Y);throw Error(`Unsupported provider: ${Y.providerId}`)};function Kp6(Y){return Y.toLowerCase().trim().replace(/[^a-z0-9\s_-]+/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function Hp6(){let Y=Math.floor(Math.random()*za0.length),Q=Math.floor(Math.random()*Da0.length),X=za0[Y]??"deco",J=Da0[Q]??"studio";return`${X}-${J}`}function Op6(){let Y=[Sv],Q=new URL(Sv);if(Q.hostname==="localhost")Y.push(Sv.replace("localhost","127.0.0.1"));else if(Q.hostname==="127.0.0.1")Y.push(Sv.replace("127.0.0.1","localhost"));return Y}var Da0,za0,$p6,Fp6,yr,Vp6,qp6,Bp6,Oa0,p9,Na0=void 0,ZL1=void 0,KL1=!1,Up6,Dp6,zp6,Sv,XK;var wP=j(()=>{YQ1();od1();bc1();m51();F71();In1();WI();fn1();PS();Lq1();Cj0();Ba0();_r();Da0=["labs","agent","studio","workspace","systems","core","cloud","works"],za0=["capybara","guarana","deco","samba","feijoada","capoeira","carnival"];$p6=Object.values(OC()).map((Y)=>Y.map((Q)=>Q.name)).flat(),Fp6={...Tl,self:["*",...$p6]},yr=DH(Fp6),Vp6=yr.newRole({self:["*"],...rR.statements}),qp6=yr.newRole({self:["*"],...rR.statements}),Bp6=yr.newRole({self:["*"],...rR.statements}),Oa0=Object.values(OC()).map((Y)=>Y.map((Q)=>`self:${Q.name}`)).flat(),p9=GI.auth;if(p9.inviteEmailProviderId&&p9.emailProviders&&p9.emailProviders.length>0){let Y=TS(p9.emailProviders,p9.inviteEmailProviderId);if(Y){let Q=ES(Y);Na0=async(X)=>{let J=X.inviter.user?.name||X.inviter.user?.email,G=`${X7()}/auth/accept-invitation?invitationId=${X.invitation.id}&redirectTo=/`;await Q({to:X.email,subject:`Invitation to join ${X.organization.name}`,html:`
1482
1482
  <h2>You've been invited!</h2>
1483
1483
  <p>${J} has invited you to join <strong>${X.organization.name}</strong>.</p>
1484
1484
  <p><a href="${G}">Click here to accept the invitation</a></p>
@@ -1536,8 +1536,8 @@ Example input: "How do I connect to a database?"
1536
1536
  Example output: Database Connection Setup
1537
1537
 
1538
1538
  Example input: "What tools are available?"
1539
- Example output: Available Tools Overview`;var _P=j(()=>{F7();er0=["user_ask","subtask"]});function er(Y){return typeof Y==="string"?Y:Y.toISOString()}class gv{db;constructor(Y){this.db=Y}async create(Y){let Q=Y.id??J9("thrd"),X=new Date().toISOString();if(!Y.organization_id)throw Error("organization_id is required");if(!Y.created_by)throw Error("created_by is required");if(!Y.title)Y.title=tr;let J={id:Q,organization_id:Y.organization_id,title:Y.title,description:Y.description??null,status:Y.status??"completed",created_at:X,updated_at:X,created_by:Y.created_by,updated_by:Y.updated_by??null},G=await this.db.insertInto("threads").values(J).returningAll().executeTakeFirstOrThrow();return this.threadFromDbRow(G)}async get(Y){let Q=await this.db.selectFrom("threads").selectAll().where("id","=",Y).executeTakeFirst();return Q?this.threadFromDbRow(Q):null}async update(Y,Q){let J={updated_at:new Date().toISOString()};if(Q.title!==void 0)J.title=Q.title;if(Q.description!==void 0)J.description=Q.description;if(Q.updated_by!==void 0)J.updated_by=Q.updated_by;if(Q.hidden!==void 0)J.hidden=Q.hidden;if(Q.status!==void 0)J.status=Q.status;await this.db.updateTable("threads").set(J).where("id","=",Y).execute();let G=await this.get(Y);if(!G)throw Error("Thread not found after update");return G}async delete(Y){await this.db.deleteFrom("threads").where("id","=",Y).execute()}async list(Y,Q,X){let J=this.db.selectFrom("threads").selectAll().where("organization_id","=",Y).where("hidden","=",!1).orderBy("updated_at","desc");if(Q)J=J.where("created_by","=",Q);let G=this.db.selectFrom("threads").select((Z)=>Z.fn.count("id").as("count")).where("organization_id","=",Y).where("hidden","=",!1);if(Q)G=G.where("created_by","=",Q);if(X?.limit)J=J.limit(X.limit);if(X?.offset)J=J.offset(X.offset);let[K,W]=await Promise.all([J.execute(),G.executeTakeFirst()]);return{threads:K.map((Z)=>this.threadFromDbRow(Z)),total:Number(W?.count||0)}}async saveMessages(Y){let Q=new Date().toISOString(),X=Y[0]?.thread_id;if(!X)throw Error("thread_id is required when creating multiple messages");let J=new Map;for(let Z of Y){let H=J.get(Z.id);if(H&&H.thread_id!==Z.thread_id)throw Error(`Duplicate message id "${Z.id}" with conflicting thread_ids: "${H.thread_id}" vs "${Z.thread_id}"`);J.set(Z.id,Z)}let G=[...J.values()],K=G.find((Z)=>Z.thread_id!==X);if(K)throw Error(`All messages must target the same thread. Expected thread_id "${X}", but message "${K.id}" has thread_id "${K.thread_id}"`);let W=G.map((Z)=>({id:Z.id,thread_id:X,metadata:Z.metadata?JSON.stringify(Z.metadata):null,parts:JSON.stringify(Z.parts),role:Z.role,created_at:Z.created_at??Q,updated_at:Q}));await this.db.transaction().execute(async(Z)=>{await Z.insertInto("thread_messages").values(W).onConflict((H)=>H.column("id").doUpdateSet(($)=>({metadata:$.ref("excluded.metadata"),parts:$.ref("excluded.parts"),role:$.ref("excluded.role"),updated_at:$.ref("excluded.updated_at")}))).execute(),await Z.updateTable("threads").set({updated_at:Q}).where("id","=",X).execute()})}async listMessages(Y,Q){let X=Q?.sort??"asc",J=this.db.selectFrom("thread_messages").selectAll().where("thread_id","=",Y).orderBy("created_at",X).orderBy("id",X),G=this.db.selectFrom("thread_messages").select((Z)=>Z.fn.count("id").as("count")).where("thread_id","=",Y);if(Q?.limit)J=J.limit(Q.limit);if(Q?.offset)J=J.offset(Q.offset);let[K,W]=await Promise.all([J.execute(),G.executeTakeFirst()]);return{messages:K.map((Z)=>this.messageFromDbRow(Z)),total:Number(W?.count||0)}}threadFromDbRow(Y){return{id:Y.id,organization_id:Y.organization_id,title:Y.title,description:Y.description,status:Y.status,created_at:er(Y.created_at),updated_at:er(Y.updated_at),created_by:Y.created_by,updated_by:Y.updated_by,hidden:!!Y.hidden}}messageFromDbRow(Y){let Q,X;try{Q=Y.metadata?JSON.parse(Y.metadata):void 0}catch(J){console.error(`Failed to parse metadata for message ${Y.id}:`,Y.metadata,J),Q=void 0}try{X=typeof Y.parts==="string"?JSON.parse(Y.parts):Y.parts}catch(J){console.error(`Failed to parse parts for message ${Y.id}:`,Y.parts,J),X=[]}return{id:Y.id,thread_id:Y.thread_id,metadata:Q,parts:X,role:Y.role,created_at:er(Y.created_at),updated_at:er(Y.updated_at)}}}var hL1=j(()=>{F7();_P()});function Gc6(Y){if(!Y)return;try{let Q=JSON.parse(Y);if(typeof Q!=="object"||Q===null||Array.isArray(Q))return;let X={};for(let[J,G]of Object.entries(Q))if(typeof G==="string")X[J]=G;return Object.keys(X).length>0?X:void 0}catch{return}}function Wc6(Y,Q){for(let[X,J]of Object.entries(Q)){let G=Y[X];if(!G||G.length===0){let K=Y["*"];if(!K||K.length===0)return!1;if(K.includes("*"))continue;for(let W of J)if(!K.includes(W))return!1;continue}if(G.includes("*"))continue;for(let K of J)if(!G.includes(K))return!1}return!0}function Zc6(Y){let{auth:Q,headers:X,role:J,permissions:G,userId:K}=Y,W=Q.api.hasPermission;return{hasPermission:async(Z)=>{if(J&&WL1.includes(J))return!0;if(G)return Wc6(G,Z);if(!W)return console.error("[Auth] hasPermission API not available"),!1;try{if((await W({headers:X,body:{permission:Z}}))?.success===!0)return!0;let $={};for(let V of Object.keys(Z))$[V]=["*"];return(await W({headers:X,body:{permission:$}}))?.success===!0}catch(H){return console.error("[Auth] Permission check failed:",H),!1}},organization:{create:async(Z)=>{return Q.api.createOrganization({headers:X,body:Z})},update:async(Z)=>{return Q.api.updateOrganization({headers:X,body:Z})},delete:async(Z)=>{await Q.api.deleteOrganization({headers:X,body:{organizationId:Z}})},get:async(Z)=>{return Q.api.getFullOrganization({headers:X,query:Z?{organizationId:Z}:void 0})},list:async(Z)=>{return Q.api.listOrganizations({headers:X,query:Z?{userId:Z}:void 0})},addMember:async(Z)=>{return Q.api.addMember({headers:X,body:Z})},removeMember:async(Z)=>{await Q.api.removeMember({headers:X,body:Z})},listMembers:async(Z)=>{return Q.api.listMembers({headers:X,query:Z?{organizationId:Z.organizationId,limit:Z.limit,offset:Z.offset}:void 0})},updateMemberRole:async(Z)=>{return Q.api.updateMemberRole({headers:X,body:Z})}},apiKey:{create:async(Z)=>{return Q.api.createApiKey({body:{...Z,userId:K}})},list:async()=>{return Q.api.listApiKeys({headers:X})},update:async(Z)=>{return Q.api.updateApiKey({body:{...Z,userId:K}})},delete:async(Z)=>{await Q.api.deleteApiKey({headers:X,body:{keyId:Z}})}}}}async function Kc6(Y,Q,X){if(WL1.includes(X))return;let J=await Y.selectFrom("organizationRole").select(["permission"]).where("organizationId","=",Q).where("role","=",X).executeTakeFirst();if(!J?.permission)return;try{return JSON.parse(J.permission)}catch{console.error(`[Auth] Failed to parse permissions for role: ${X}`);return}}async function Hc6(Y,Q,X,J=Xo0){let G=Y.headers.get("Authorization");try{let K=new Headers(Y.headers);K.set("X-MCP-Session-Auth","true");let W=await J.measure("auth_get_mcp_session",()=>Q.api.getMcpSession({headers:K}));if(W){let Z=W.userId,H=await J.measure("auth_query_membership",()=>X.selectFrom("member").innerJoin("organization","organization.id","member.organizationId").select(["member.role","member.organizationId","organization.id as orgId","organization.slug as orgSlug","organization.name as orgName"]).where("member.userId","=",Z).executeTakeFirst()),$=H?.role,F=H?{id:H.orgId,slug:H.orgSlug,name:H.orgName}:void 0,V;if(H&&$)V=await J.measure("auth_fetch_role_permissions",()=>Kc6(X,H.organizationId,$));return{user:{id:Z,role:$},role:$,permissions:V,organization:F}}}catch(K){console.error("[Auth] OAuth session check failed:",K)}if(G?.startsWith("Bearer ")){let K=G.replace("Bearer ","").trim();try{let W=await J.measure("auth_verify_mesh_jwt",()=>Gn0(K));if(W){let Z,H=W.metadata?.organizationId;if(W.sub&&H)Z=(await J.measure("auth_query_membership",()=>X.selectFrom("member").select(["member.role"]).where("member.userId","=",W.sub).where("member.organizationId","=",H).executeTakeFirst()))?.role;return{user:{id:W.sub,connectionId:W.metadata?.connectionId,role:Z},role:Z,permissions:W.permissions,organization:W.metadata?.organizationId?{id:W.metadata?.organizationId}:void 0}}}catch{}try{let W=await J.measure("auth_verify_api_key",()=>Q.api.verifyApiKey({body:{key:K}}));if(W?.valid&&W.key){let Z=W.key.metadata?.organization,H=W.key.permissions,$,F=W.key.userId;if(F&&Z?.id)$=(await J.measure("auth_query_membership",()=>X.selectFrom("member").select(["member.role"]).where("member.userId","=",F).where("member.organizationId","=",Z.id).executeTakeFirst()))?.role;return{apiKeyId:W.key.id,user:{id:W.key.userId,role:$},role:$,permissions:H,organization:Z?{id:Z.id,slug:Z.slug,name:Z.name}:void 0}}}catch(W){console.error("[Auth] API key check failed:",W)}}try{let K=new Headers(Y.headers);K.delete("Authorization");let W=await J.measure("auth_get_session",()=>Q.api.getSession({headers:K}));if(W){let Z,H;if(W.session.activeOrganizationId){let $=await J.measure("auth_get_full_organization",()=>Q.api.getFullOrganization({headers:K}).catch(()=>null));if($)Z={id:$.id,slug:$.slug,name:$.name},H=$.members?.find((V)=>V.userId===W.user.id)?.role;else Z={id:W.session.activeOrganizationId,slug:"",name:""}}return{user:{id:W.user.id,email:W.user.email,role:H},role:H,organization:Z}}}catch(K){let W=K;console.error("[Auth] Session check failed:",JSON.stringify({message:W.message,body:W.body,stack:W.stack},null,2))}return{user:void 0}}async function Jo0(Y){let Q=new _z(Y.encryption.key),X={connections:new RS(Y.db,Q),organizationSettings:new CL1(Y.db),monitoring:new EL1(Y.db,Y.databaseType),monitoringDashboards:new TL1(Y.db),virtualMcps:new AL1(Y.db),users:new jL1(Y.db),threads:new gv(Y.db),tags:new IL1(Y.db),projects:new IS(Y.db),projectPluginConfigs:new RL1(Y.db)};return async(J,G)=>{let K=G?.timings??Xo0,W=Ir(),Z=J?.headers.get("x-caller-id")??void 0,H=J?await Hc6(J,Y.auth,Y.db,K):{user:void 0},$=Zc6({auth:Y.auth,headers:J?.headers??new Headers,role:H.role,permissions:H.permissions,userId:H.user?.id}),F={user:H.user};if(H.apiKeyId)F.apiKey={id:H.apiKeyId,name:"",userId:""};let V=H.organization,B=J?process.env.BASE_URL??`${new URL(J.url).origin}`:X7(),U=new LF(Y.auth,F.user?.id,void 0,$,H.role,"self"),D={timings:K,auth:F,connectionId:Z,organization:V,storage:X,vault:Q,authInstance:Y.auth,boundAuth:$,access:U,db:Y.db,tracer:Y.observability.tracer,meter:Y.observability.meter,baseUrl:B,metadata:{requestId:crypto.randomUUID(),timestamp:new Date,wellKnownForwardableHeaders:Object.fromEntries($c6.map((z)=>[z,J?.headers.get(z)??null]).filter(([z,L])=>L!==null)),userAgent:J?.headers.get("x-mesh-client")||J?.headers.get("User-Agent")||void 0,ipAddress:(J?.headers.get("CF-Connecting-IP")||J?.headers.get("X-Forwarded-For"))??void 0,properties:Gc6(J?.headers.get("x-mesh-properties"))},eventBus:Y.eventBus,createMCPProxy:async(z)=>{return await ir0(z,D)},getOrCreateClient:W};return D}}var Qo0,PF,Xo0,$c6;var ir=j(()=>{kO1();ln();Mq1();vr0();_r0();yr0();wq1();fr0();br0();Pv();CO();_r();hL1();_O1();PF={set:(Y)=>{Qo0=Y},create:async(Y,Q)=>{return await Qo0(Y,Q)}},Xo0={measure:async(Y,Q)=>{return await Q()}},$c6=["x-hub-signature-256"]});class Go0{db;constructor(Y){this.db=Y}async publishEvent(Y){let Q=new Date().toISOString();return await this.db.insertInto("events").values({id:Y.id,organization_id:Y.organizationId,type:Y.type,source:Y.source,specversion:"1.0",subject:Y.subject??null,time:Y.time,datacontenttype:Y.datacontenttype??"application/json",dataschema:Y.dataschema??null,data:Y.data?JSON.stringify(Y.data):null,cron:Y.cron??null,status:"pending",attempts:0,last_error:null,next_retry_at:null,created_at:Q,updated_at:Q}).execute(),{id:Y.id,organizationId:Y.organizationId,type:Y.type,source:Y.source,specversion:"1.0",subject:Y.subject??null,time:Y.time,datacontenttype:Y.datacontenttype??"application/json",dataschema:Y.dataschema??null,data:Y.data??null,cron:Y.cron??null,status:"pending",attempts:0,lastError:null,nextRetryAt:null,createdAt:Q,updatedAt:Q}}async subscribe(Y){let Q=this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",Y.organizationId).where("connection_id","=",Y.connectionId).where("event_type","=",Y.eventType);if(Y.publisher)Q=Q.where("publisher","=",Y.publisher);else Q=Q.where("publisher","is",null);if(Y.filter)Q=Q.where("filter","=",Y.filter);else Q=Q.where("filter","is",null);let X=await Q.executeTakeFirst();if(X)return{id:X.id,organizationId:X.organization_id,connectionId:X.connection_id,publisher:X.publisher,eventType:X.event_type,filter:X.filter,enabled:X.enabled===1,createdAt:X.created_at,updatedAt:X.updated_at};let J=new Date().toISOString();return await this.db.insertInto("event_subscriptions").values({id:Y.id,organization_id:Y.organizationId,connection_id:Y.connectionId,publisher:Y.publisher??null,event_type:Y.eventType,filter:Y.filter??null,enabled:1,created_at:J,updated_at:J}).execute(),{id:Y.id,organizationId:Y.organizationId,connectionId:Y.connectionId,publisher:Y.publisher??null,eventType:Y.eventType,filter:Y.filter??null,enabled:!0,createdAt:J,updatedAt:J}}async unsubscribe(Y,Q){return{success:((await this.db.deleteFrom("event_subscriptions").where("id","=",Y).where("organization_id","=",Q).executeTakeFirst()).numDeletedRows??0n)>0n}}async listSubscriptions(Y,Q){let X=this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",Y);if(Q)X=X.where("connection_id","=",Q);return(await X.execute()).map((G)=>({id:G.id,organizationId:G.organization_id,connectionId:G.connection_id,publisher:G.publisher,eventType:G.event_type,filter:G.filter,enabled:G.enabled===1,createdAt:G.created_at,updatedAt:G.updated_at}))}async getSubscription(Y,Q){let X=await this.db.selectFrom("event_subscriptions").selectAll().where("id","=",Y).where("organization_id","=",Q).executeTakeFirst();if(!X)return null;return{id:X.id,organizationId:X.organization_id,connectionId:X.connection_id,publisher:X.publisher,eventType:X.event_type,filter:X.filter,enabled:X.enabled===1,createdAt:X.created_at,updatedAt:X.updated_at}}async getMatchingSubscriptions(Y){return(await this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",Y.organizationId).where("enabled","=",1).where("event_type","=",Y.type).where((X)=>X.or([X("publisher","is",null),X("publisher","=",Y.source)])).execute()).map((X)=>({id:X.id,organizationId:X.organization_id,connectionId:X.connection_id,publisher:X.publisher,eventType:X.event_type,filter:X.filter,enabled:X.enabled===1,createdAt:X.created_at,updatedAt:X.updated_at}))}async createDeliveries(Y,Q,X){if(Q.length===0)return;let J=new Date().toISOString(),G=X??null,K=Q.map((W)=>({id:crypto.randomUUID(),event_id:Y,subscription_id:W,status:"pending",attempts:0,last_error:null,delivered_at:null,next_retry_at:G,created_at:J}));await this.db.insertInto("event_deliveries").values(K).execute()}async claimPendingDeliveries(Y){let Q=new Date().toISOString(),X;try{X=(await this.db.updateTable("event_deliveries").set({status:"processing"}).where("id","in",(K)=>K.selectFrom("event_deliveries as d").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select("d.id").where("d.status","=","pending").where("s.enabled","=",1).where((W)=>W.or([W("d.next_retry_at","is",null),W("d.next_retry_at","<=",Q)])).orderBy("d.created_at","asc").limit(Y)).where("status","=","pending").returning(["id"]).execute()).map((K)=>K.id)}catch{let G=await this.db.selectFrom("event_deliveries as d").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select(["d.id"]).where("d.status","=","pending").where("s.enabled","=",1).where((K)=>K.or([K("d.next_retry_at","is",null),K("d.next_retry_at","<=",Q)])).orderBy("d.created_at","asc").limit(Y).execute();if(G.length===0)return[];X=G.map((K)=>K.id),await this.db.updateTable("event_deliveries").set({status:"processing"}).where("id","in",X).where("status","=","pending").execute()}if(X.length===0)return[];return(await this.db.selectFrom("event_deliveries as d").innerJoin("events as e","e.id","d.event_id").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select(["d.id as delivery_id","d.event_id","d.subscription_id","d.status as delivery_status","d.attempts as delivery_attempts","d.last_error as delivery_last_error","d.delivered_at","d.next_retry_at as delivery_next_retry_at","d.created_at as delivery_created_at","e.organization_id","e.type","e.source","e.specversion","e.subject","e.time","e.datacontenttype","e.dataschema","e.data","e.cron","e.status as event_status","e.attempts as event_attempts","e.last_error as event_last_error","e.next_retry_at","e.created_at as event_created_at","e.updated_at as event_updated_at","s.connection_id","s.publisher","s.event_type","s.filter","s.enabled","s.created_at as subscription_created_at","s.updated_at as subscription_updated_at"]).where("d.id","in",X).where("d.status","=","processing").execute()).map((G)=>({delivery:{id:G.delivery_id,eventId:G.event_id,subscriptionId:G.subscription_id,status:G.delivery_status,attempts:G.delivery_attempts,lastError:G.delivery_last_error,deliveredAt:G.delivered_at,nextRetryAt:G.delivery_next_retry_at,createdAt:G.delivery_created_at},event:{id:G.event_id,organizationId:G.organization_id,type:G.type,source:G.source,specversion:G.specversion,subject:G.subject,time:G.time,datacontenttype:G.datacontenttype,dataschema:G.dataschema,data:G.data?JSON.parse(G.data):null,cron:G.cron,status:G.event_status,attempts:G.event_attempts,lastError:G.event_last_error,nextRetryAt:G.next_retry_at,createdAt:G.event_created_at,updatedAt:G.event_updated_at},subscription:{id:G.subscription_id,organizationId:G.organization_id,connectionId:G.connection_id,publisher:G.publisher,eventType:G.event_type,filter:G.filter,enabled:G.enabled===1,createdAt:G.subscription_created_at,updatedAt:G.subscription_updated_at}}))}async markDeliveriesDelivered(Y){if(Y.length===0)return;let Q=new Date().toISOString();await this.db.updateTable("event_deliveries").set({status:"delivered",delivered_at:Q}).where("id","in",Y).execute()}async markDeliveriesFailed(Y,Q,X=20,J=1000,G=3600000){if(Y.length===0)return;for(let K of Y){let W=await this.db.selectFrom("event_deliveries").select(["attempts"]).where("id","=",K).executeTakeFirst();if(!W)continue;let Z=W.attempts+1;if(Z>=X)await this.db.updateTable("event_deliveries").set({attempts:Z,last_error:Q,status:"failed",next_retry_at:null}).where("id","=",K).execute();else{let H=Math.min(J*Math.pow(2,Z-1),G),$=new Date(Date.now()+H).toISOString();await this.db.updateTable("event_deliveries").set({attempts:Z,last_error:Q,status:"pending",next_retry_at:$}).where("id","=",K).execute()}}}async updateEventStatus(Y){let Q=await this.db.selectFrom("event_deliveries").select(["status"]).where("event_id","=",Y).execute();if(Q.length===0)return;let X=Q.every((K)=>K.status==="delivered"),J=Q.some((K)=>K.status==="failed"),G=Q.some((K)=>K.status==="pending"||K.status==="processing");if(X)await this.db.updateTable("events").set({status:"delivered",updated_at:new Date().toISOString()}).where("id","=",Y).execute();else if(J&&!G)await this.db.updateTable("events").set({status:"failed",updated_at:new Date().toISOString()}).where("id","=",Y).execute()}async resetStuckDeliveries(){let Y=await this.db.updateTable("event_deliveries").set({status:"pending"}).where("status","=","processing").executeTakeFirst();return Number(Y.numUpdatedRows??0)}async getEvent(Y,Q){let X=await this.db.selectFrom("events").selectAll().where("id","=",Y).where("organization_id","=",Q).executeTakeFirst();if(!X)return null;return{id:X.id,organizationId:X.organization_id,type:X.type,source:X.source,specversion:X.specversion,subject:X.subject,time:X.time,datacontenttype:X.datacontenttype,dataschema:X.dataschema,data:X.data?JSON.parse(X.data):null,cron:X.cron,status:X.status,attempts:X.attempts,lastError:X.last_error,nextRetryAt:X.next_retry_at,createdAt:X.created_at,updatedAt:X.updated_at}}async findActiveCronEvent(Y,Q,X,J){let G=await this.db.selectFrom("events").selectAll().where("organization_id","=",Y).where("type","=",Q).where("source","=",X).where("cron","=",J).where("status","in",["pending","processing","delivered"]).orderBy("created_at","desc").executeTakeFirst();if(!G)return null;return{id:G.id,organizationId:G.organization_id,type:G.type,source:G.source,specversion:G.specversion,subject:G.subject,time:G.time,datacontenttype:G.datacontenttype,dataschema:G.dataschema,data:G.data?JSON.parse(G.data):null,cron:G.cron,status:G.status,attempts:G.attempts,lastError:G.last_error,nextRetryAt:G.next_retry_at,createdAt:G.created_at,updatedAt:G.updated_at}}async cancelEvent(Y,Q,X){let J=await this.db.updateTable("events").set({status:"failed",last_error:"Cancelled by publisher",updated_at:new Date().toISOString()}).where("id","=",Y).where("organization_id","=",Q).where("source","=",X).where("status","in",["pending","processing"]).executeTakeFirst();if((J.numUpdatedRows??0n)>0n)await this.db.updateTable("event_deliveries").set({status:"failed",last_error:"Event cancelled by publisher"}).where("event_id","=",Y).where("status","in",["pending","processing"]).execute();return{success:(J.numUpdatedRows??0n)>0n}}async scheduleRetryWithoutAttemptIncrement(Y,Q){if(Y.length===0)return;let X=new Date(Date.now()+Q).toISOString();await this.db.updateTable("event_deliveries").set({status:"pending",next_retry_at:X}).where("id","in",Y).execute()}async ackDelivery(Y,Q,X){if(!await this.db.selectFrom("events").select(["id"]).where("id","=",Y).where("organization_id","=",Q).executeTakeFirst())return{success:!1};let K=((await this.db.updateTable("event_deliveries").set({status:"delivered",delivered_at:new Date().toISOString()}).where("event_id","=",Y).where("status","in",["pending","processing"]).where((W)=>W.exists(W.selectFrom("event_subscriptions").select("id").whereRef("event_subscriptions.id","=","event_deliveries.subscription_id").where("event_subscriptions.connection_id","=",X).where("event_subscriptions.organization_id","=",Q))).executeTakeFirst()).numUpdatedRows??0n)>0n;if(K)await this.updateEventStatus(Y);return{success:K}}async syncSubscriptions(Y){let{organizationId:Q,connectionId:X,subscriptions:J}=Y,G=(w,E)=>{return`${w}::${E??""}`},K=await this.listSubscriptions(Q,X),W=new Map;for(let w of K)W.set(G(w.eventType,w.publisher),w);let Z=new Map;for(let w of J)Z.set(G(w.eventType,w.publisher),w);let H=new Date().toISOString(),$=[],F=[],V=[],B=0;for(let[w,E]of Z){let T=W.get(w);if(!T)$.push({id:crypto.randomUUID(),organization_id:Q,connection_id:X,event_type:E.eventType,publisher:E.publisher??null,filter:E.filter??null,enabled:1,created_at:H,updated_at:H});else{let C=T.filter??null,P=E.filter??null;if(C!==P)F.push({id:T.id,filter:P});else B++}}for(let[w,E]of W)if(!Z.has(w))V.push(E.id);if($.length>0)await this.db.insertInto("event_subscriptions").values($).execute();if(F.length>0)await Promise.all(F.map((w)=>this.db.updateTable("event_subscriptions").set({filter:w.filter,updated_at:H}).where("id","=",w.id).execute()));if(V.length>0)await this.db.deleteFrom("event_subscriptions").where("id","in",V).execute();let U=$.length,D=F.length,z=V.length,L=await this.listSubscriptions(Q,X);return{created:U,updated:D,deleted:z,unchanged:B,subscriptions:L}}}function Wo0(Y){return new Go0(Y)}function gJ(Y,Q,X,J,G,K,W,Z){return gJ.fromTZ(gJ.tp(Y,Q,X,J,G,K,W),Z)}function xL1(Y,Q=new Date){let X=Q.toLocaleString("en-US",{timeZone:Y,timeZoneName:"shortOffset"}).split(" ").slice(-1)[0],J=Q.toLocaleString("en-US").replace(/[\u202f]/," ");return Date.parse(`${J} GMT`)-Date.parse(`${J} ${X}`)}function Fc6(Y,Q){let X=new Date(Date.parse(Y));if(isNaN(X))throw Error("minitz: Invalid ISO8601 passed to parser.");let J=Y.substring(9);return Y.includes("Z")||J.includes("-")||J.includes("+")?gJ.tp(X.getUTCFullYear(),X.getUTCMonth()+1,X.getUTCDate(),X.getUTCHours(),X.getUTCMinutes(),X.getUTCSeconds(),"Etc/UTC"):gJ.tp(X.getFullYear(),X.getMonth()+1,X.getDate(),X.getHours(),X.getMinutes(),X.getSeconds(),Q)}function Vc6(Y){if(Y===void 0&&(Y={}),delete Y.name,Y.legacyMode=Y.legacyMode===void 0?!0:Y.legacyMode,Y.paused=Y.paused===void 0?!1:Y.paused,Y.maxRuns=Y.maxRuns===void 0?1/0:Y.maxRuns,Y.catch=Y.catch===void 0?!1:Y.catch,Y.interval=Y.interval===void 0?0:parseInt(Y.interval.toString(),10),Y.utcOffset=Y.utcOffset===void 0?void 0:parseInt(Y.utcOffset.toString(),10),Y.unref=Y.unref===void 0?!1:Y.unref,Y.startAt&&(Y.startAt=new hW(Y.startAt,Y.timezone)),Y.stopAt&&(Y.stopAt=new hW(Y.stopAt,Y.timezone)),Y.interval!==null){if(isNaN(Y.interval))throw Error("CronOptions: Supplied value for interval is not a number");if(Y.interval<0)throw Error("CronOptions: Supplied value for interval can not be negative")}if(Y.utcOffset!==void 0){if(isNaN(Y.utcOffset))throw Error("CronOptions: Invalid value passed for utcOffset, should be number representing minutes offset from UTC.");if(Y.utcOffset<-870||Y.utcOffset>870)throw Error("CronOptions: utcOffset out of bounds.");if(Y.utcOffset!==void 0&&Y.timezone)throw Error("CronOptions: Combining 'utcOffset' with 'timezone' is not allowed.")}if(Y.unref!==!0&&Y.unref!==!1)throw Error("CronOptions: Unref should be either true, false or undefined(false).");return Y}function uv(Y){return Object.prototype.toString.call(Y)==="[object Function]"||typeof Y=="function"||Y instanceof Function}function qc6(Y){return uv(Y)}function Bc6(Y){typeof Deno<"u"&&typeof Deno.unrefTimer<"u"?Deno.unrefTimer(Y):Y&&typeof Y.unref<"u"&&Y.unref()}var gL1=32,mv,$o0,Zo0=class{pattern;timezone;second;minute;hour;day;month;dayOfWeek;lastDayOfMonth;starDOM;starDOW;constructor(Y,Q){this.pattern=Y,this.timezone=Q,this.second=Array(60).fill(0),this.minute=Array(60).fill(0),this.hour=Array(24).fill(0),this.day=Array(31).fill(0),this.month=Array(12).fill(0),this.dayOfWeek=Array(7).fill(0),this.lastDayOfMonth=!1,this.starDOM=!1,this.starDOW=!1,this.parse()}parse(){if(!(typeof this.pattern=="string"||this.pattern instanceof String))throw TypeError("CronPattern: Pattern has to be of type string.");this.pattern.indexOf("@")>=0&&(this.pattern=this.handleNicknames(this.pattern).trim());let Y=this.pattern.replace(/\s+/g," ").split(" ");if(Y.length<5||Y.length>6)throw TypeError("CronPattern: invalid configuration format ('"+this.pattern+"'), exactly five or six space separated parts are required.");if(Y.length===5&&Y.unshift("0"),Y[3].indexOf("L")>=0&&(Y[3]=Y[3].replace("L",""),this.lastDayOfMonth=!0),Y[3]=="*"&&(this.starDOM=!0),Y[4].length>=3&&(Y[4]=this.replaceAlphaMonths(Y[4])),Y[5].length>=3&&(Y[5]=this.replaceAlphaDays(Y[5])),Y[5]=="*"&&(this.starDOW=!0),this.pattern.indexOf("?")>=0){let Q=new hW(new Date,this.timezone).getDate(!0);Y[0]=Y[0].replace("?",Q.getSeconds().toString()),Y[1]=Y[1].replace("?",Q.getMinutes().toString()),Y[2]=Y[2].replace("?",Q.getHours().toString()),this.starDOM||(Y[3]=Y[3].replace("?",Q.getDate().toString())),Y[4]=Y[4].replace("?",(Q.getMonth()+1).toString()),this.starDOW||(Y[5]=Y[5].replace("?",Q.getDay().toString()))}this.throwAtIllegalCharacters(Y),this.partToArray("second",Y[0],0,1),this.partToArray("minute",Y[1],0,1),this.partToArray("hour",Y[2],0,1),this.partToArray("day",Y[3],-1,1),this.partToArray("month",Y[4],-1,1),this.partToArray("dayOfWeek",Y[5],0,mv),this.dayOfWeek[7]&&(this.dayOfWeek[0]=this.dayOfWeek[7])}partToArray(Y,Q,X,J){let G=this[Y],K=Y==="day"&&this.lastDayOfMonth;if(Q===""&&!K)throw TypeError("CronPattern: configuration entry "+Y+" ("+Q+") is empty, check for trailing spaces.");if(Q==="*")return G.fill(J);let W=Q.split(",");if(W.length>1)for(let Z=0;Z<W.length;Z++)this.partToArray(Y,W[Z],X,J);else Q.indexOf("-")!==-1&&Q.indexOf("/")!==-1?this.handleRangeWithStepping(Q,Y,X,J):Q.indexOf("-")!==-1?this.handleRange(Q,Y,X,J):Q.indexOf("/")!==-1?this.handleStepping(Q,Y,X,J):Q!==""&&this.handleNumber(Q,Y,X,J)}throwAtIllegalCharacters(Y){for(let Q=0;Q<Y.length;Q++)if((Q===5?/[^/*0-9,\-#L]+/:/[^/*0-9,-]+/).test(Y[Q]))throw TypeError("CronPattern: configuration entry "+Q+" ("+Y[Q]+") contains illegal characters.")}handleNumber(Y,Q,X,J){let G=this.extractNth(Y,Q),K=parseInt(G[0],10)+X;if(isNaN(K))throw TypeError("CronPattern: "+Q+" is not a number: '"+Y+"'");this.setPart(Q,K,G[1]||J)}setPart(Y,Q,X){if(!Object.prototype.hasOwnProperty.call(this,Y))throw TypeError("CronPattern: Invalid part specified: "+Y);if(Y==="dayOfWeek"){if(Q===7&&(Q=0),Q<0||Q>6)throw RangeError("CronPattern: Invalid value for dayOfWeek: "+Q);this.setNthWeekdayOfMonth(Q,X);return}if(Y==="second"||Y==="minute"){if(Q<0||Q>=60)throw RangeError("CronPattern: Invalid value for "+Y+": "+Q)}else if(Y==="hour"){if(Q<0||Q>=24)throw RangeError("CronPattern: Invalid value for "+Y+": "+Q)}else if(Y==="day"){if(Q<0||Q>=31)throw RangeError("CronPattern: Invalid value for "+Y+": "+Q)}else if(Y==="month"&&(Q<0||Q>=12))throw RangeError("CronPattern: Invalid value for "+Y+": "+Q);this[Y][Q]=X}handleRangeWithStepping(Y,Q,X,J){let G=this.extractNth(Y,Q),K=G[0].match(/^(\d+)-(\d+)\/(\d+)$/);if(K===null)throw TypeError("CronPattern: Syntax error, illegal range with stepping: '"+Y+"'");let[,W,Z,H]=K,$=parseInt(W,10)+X,F=parseInt(Z,10)+X,V=parseInt(H,10);if(isNaN($))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(F))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(isNaN(V))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(V===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(V>this[Q].length)throw TypeError("CronPattern: Syntax error, steps cannot be greater than maximum value of part ("+this[Q].length+")");if($>F)throw TypeError("CronPattern: From value is larger than to value: '"+Y+"'");for(let B=$;B<=F;B+=V)this.setPart(Q,B,G[1]||J)}extractNth(Y,Q){let X=Y,J;if(X.includes("#")){if(Q!=="dayOfWeek")throw Error("CronPattern: nth (#) only allowed in day-of-week field");J=X.split("#")[1],X=X.split("#")[0]}return[X,J]}handleRange(Y,Q,X,J){let G=this.extractNth(Y,Q),K=G[0].split("-");if(K.length!==2)throw TypeError("CronPattern: Syntax error, illegal range: '"+Y+"'");let W=parseInt(K[0],10)+X,Z=parseInt(K[1],10)+X;if(isNaN(W))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(Z))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(W>Z)throw TypeError("CronPattern: From value is larger than to value: '"+Y+"'");for(let H=W;H<=Z;H++)this.setPart(Q,H,G[1]||J)}handleStepping(Y,Q,X,J){let G=this.extractNth(Y,Q),K=G[0].split("/");if(K.length!==2)throw TypeError("CronPattern: Syntax error, illegal stepping: '"+Y+"'");K[0]===""&&(K[0]="*");let W=0;K[0]!=="*"&&(W=parseInt(K[0],10)+X);let Z=parseInt(K[1],10);if(isNaN(Z))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(Z===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(Z>this[Q].length)throw TypeError("CronPattern: Syntax error, max steps for part is ("+this[Q].length+")");for(let H=W;H<this[Q].length;H+=Z)this.setPart(Q,H,G[1]||J)}replaceAlphaDays(Y){return Y.replace(/-sun/gi,"-7").replace(/sun/gi,"0").replace(/mon/gi,"1").replace(/tue/gi,"2").replace(/wed/gi,"3").replace(/thu/gi,"4").replace(/fri/gi,"5").replace(/sat/gi,"6")}replaceAlphaMonths(Y){return Y.replace(/jan/gi,"1").replace(/feb/gi,"2").replace(/mar/gi,"3").replace(/apr/gi,"4").replace(/may/gi,"5").replace(/jun/gi,"6").replace(/jul/gi,"7").replace(/aug/gi,"8").replace(/sep/gi,"9").replace(/oct/gi,"10").replace(/nov/gi,"11").replace(/dec/gi,"12")}handleNicknames(Y){let Q=Y.trim().toLowerCase();return Q==="@yearly"||Q==="@annually"?"0 0 1 1 *":Q==="@monthly"?"0 0 1 * *":Q==="@weekly"?"0 0 * * 0":Q==="@daily"?"0 0 * * *":Q==="@hourly"?"0 * * * *":Y}setNthWeekdayOfMonth(Y,Q){if(typeof Q!="number"&&Q==="L")this.dayOfWeek[Y]=this.dayOfWeek[Y]|gL1;else if(Q===mv)this.dayOfWeek[Y]=mv;else if(Q<6&&Q>0)this.dayOfWeek[Y]=this.dayOfWeek[Y]|$o0[Q-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${Q}, Type: ${typeof Q}`)}},Ko0,EF,hW=class Y{tz;ms;second;minute;hour;day;month;year;constructor(Q,X){if(this.tz=X,Q&&Q instanceof Date)if(!isNaN(Q))this.fromDate(Q);else throw TypeError("CronDate: Invalid date passed to CronDate constructor");else if(Q===void 0)this.fromDate(new Date);else if(Q&&typeof Q=="string")this.fromString(Q);else if(Q instanceof Y)this.fromCronDate(Q);else throw TypeError("CronDate: Invalid type ("+typeof Q+") passed to CronDate constructor")}isNthWeekdayOfMonth(Q,X,J,G){let K=new Date(Date.UTC(Q,X,J)).getUTCDay(),W=0;for(let Z=1;Z<=J;Z++)new Date(Date.UTC(Q,X,Z)).getUTCDay()===K&&W++;if(G&mv&&$o0[W-1]&G)return!0;if(G&gL1){let Z=new Date(Date.UTC(Q,X+1,0)).getUTCDate();for(let H=J+1;H<=Z;H++)if(new Date(Date.UTC(Q,X,H)).getUTCDay()===K)return!1;return!0}return!1}fromDate(Q){if(this.tz!==void 0)if(typeof this.tz=="number")this.ms=Q.getUTCMilliseconds(),this.second=Q.getUTCSeconds(),this.minute=Q.getUTCMinutes()+this.tz,this.hour=Q.getUTCHours(),this.day=Q.getUTCDate(),this.month=Q.getUTCMonth(),this.year=Q.getUTCFullYear(),this.apply();else{let X=gJ.toTZ(Q,this.tz);this.ms=Q.getMilliseconds(),this.second=X.s,this.minute=X.i,this.hour=X.h,this.day=X.d,this.month=X.m-1,this.year=X.y}else this.ms=Q.getMilliseconds(),this.second=Q.getSeconds(),this.minute=Q.getMinutes(),this.hour=Q.getHours(),this.day=Q.getDate(),this.month=Q.getMonth(),this.year=Q.getFullYear()}fromCronDate(Q){this.tz=Q.tz,this.year=Q.year,this.month=Q.month,this.day=Q.day,this.hour=Q.hour,this.minute=Q.minute,this.second=Q.second,this.ms=Q.ms}apply(){if(this.month>11||this.day>Ko0[this.month]||this.hour>59||this.minute>59||this.second>59||this.hour<0||this.minute<0||this.second<0){let Q=new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms));return this.ms=Q.getUTCMilliseconds(),this.second=Q.getUTCSeconds(),this.minute=Q.getUTCMinutes(),this.hour=Q.getUTCHours(),this.day=Q.getUTCDate(),this.month=Q.getUTCMonth(),this.year=Q.getUTCFullYear(),!0}else return!1}fromString(Q){if(typeof this.tz=="number"){let X=gJ.fromTZISO(Q);this.ms=X.getUTCMilliseconds(),this.second=X.getUTCSeconds(),this.minute=X.getUTCMinutes(),this.hour=X.getUTCHours(),this.day=X.getUTCDate(),this.month=X.getUTCMonth(),this.year=X.getUTCFullYear(),this.apply()}else return this.fromDate(gJ.fromTZISO(Q,this.tz))}findNext(Q,X,J,G){let K=this[X],W;J.lastDayOfMonth&&(this.month!==1?W=Ko0[this.month]:W=new Date(Date.UTC(this.year,this.month+1,0,0,0,0,0)).getUTCDate());let Z=!J.starDOW&&X=="day"?new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay():void 0;for(let H=this[X]+G;H<J[X].length;H++){let $=J[X][H];if(X==="day"&&J.lastDayOfMonth&&H-G==W&&($=1),X==="day"&&!J.starDOW){let F=J.dayOfWeek[(Z+(H-G-1))%7];if(F&&F&mv)F=this.isNthWeekdayOfMonth(this.year,this.month,H-G,F)?1:0;else if(F)throw Error(`CronDate: Invalid value for dayOfWeek encountered. ${F}`);Q.legacyMode&&!J.starDOM?$=$||F:$=$&&F}if($)return this[X]=H-G,K!==this[X]?2:1}return 3}recurse(Q,X,J){let G=this.findNext(X,EF[J][0],Q,EF[J][2]);if(G>1){let K=J+1;for(;K<EF.length;)this[EF[K][0]]=-EF[K][2],K++;if(G===3)return this[EF[J][1]]++,this[EF[J][0]]=-EF[J][2],this.apply(),this.recurse(Q,X,0);if(this.apply())return this.recurse(Q,X,J-1)}return J+=1,J>=EF.length?this:this.year>=3000?null:this.recurse(Q,X,J)}increment(Q,X,J){return this.second+=X.interval!==void 0&&X.interval>1&&J?X.interval:1,this.ms=0,this.apply(),this.recurse(Q,X,0)}getDate(Q){return Q||this.tz===void 0?new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms):typeof this.tz=="number"?new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute-this.tz,this.second,this.ms)):gJ.fromTZ(gJ.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}},Ho0=30000,Yo,Qo=class{name;options;_states;fn;constructor(Y,Q,X){let J,G;if(uv(Q))G=Q;else if(typeof Q=="object")J=Q;else if(Q!==void 0)throw Error("Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).");if(uv(X))G=X;else if(typeof X=="object")J=X;else if(X!==void 0)throw Error("Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).");if(this.name=J?.name,this.options=Vc6(J),this._states={kill:!1,blocking:!1,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:J?J.maxRuns:void 0,paused:J?J.paused:!1,pattern:new Zo0("* * * * *")},Y&&(Y instanceof Date||typeof Y=="string"&&Y.indexOf(":")>0)?this._states.once=new hW(Y,this.options.timezone||this.options.utcOffset):this._states.pattern=new Zo0(Y,this.options.timezone),this.name){if(Yo.find((K)=>K.name===this.name))throw Error("Cron: Tried to initialize new named job '"+this.name+"', but name already taken.");Yo.push(this)}return G!==void 0&&qc6(G)&&(this.fn=G,this.schedule()),this}nextRun(Y){let Q=this._next(Y);return Q?Q.getDate(!1):null}nextRuns(Y,Q){this._states.maxRuns!==void 0&&Y>this._states.maxRuns&&(Y=this._states.maxRuns);let X=[],J=Q||this._states.currentRun||void 0;for(;Y--&&(J=this.nextRun(J));)X.push(J);return X}getPattern(){return this._states.pattern?this._states.pattern.pattern:void 0}isRunning(){let Y=this.nextRun(this._states.currentRun),Q=!this._states.paused,X=this.fn!==void 0,J=!this._states.kill;return Q&&X&&J&&Y!==null}isStopped(){return this._states.kill}isBusy(){return this._states.blocking}currentRun(){return this._states.currentRun?this._states.currentRun.getDate():null}previousRun(){return this._states.previousRun?this._states.previousRun.getDate():null}msToNext(Y){let Q=this._next(Y);return Q?Y instanceof hW||Y instanceof Date?Q.getTime()-Y.getTime():Q.getTime()-new hW(Y).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let Y=Yo.indexOf(this);Y>=0&&Yo.splice(Y,1)}pause(){return this._states.paused=!0,!this._states.kill}resume(){return this._states.paused=!1,!this._states.kill}schedule(Y){if(Y&&this.fn)throw Error("Cron: It is not allowed to schedule two functions using the same Croner instance.");Y&&(this.fn=Y);let Q=this.msToNext(),X=this.nextRun(this._states.currentRun);return Q==null||isNaN(Q)||X===null?this:(Q>Ho0&&(Q=Ho0),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(X),Q),this._states.currentTimeout&&this.options.unref&&Bc6(this._states.currentTimeout),this)}async _trigger(Y){if(this._states.blocking=!0,this._states.currentRun=new hW(void 0,this.options.timezone||this.options.utcOffset),this.options.catch)try{this.fn!==void 0&&await this.fn(this,this.options.context)}catch(Q){uv(this.options.catch)&&this.options.catch(Q,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new hW(Y,this.options.timezone||this.options.utcOffset),this._states.blocking=!1}async trigger(){await this._trigger()}runsLeft(){return this._states.maxRuns}_checkTrigger(Y){let Q=new Date,X=!this._states.paused&&Q.getTime()>=Y.getTime(),J=this._states.blocking&&this.options.protect;X&&!J?(this._states.maxRuns!==void 0&&this._states.maxRuns--,this._trigger()):X&&J&&uv(this.options.protect)&&setTimeout(()=>this.options.protect(this),0),this.schedule()}_next(Y){let Q=!!(Y||this._states.currentRun),X=!1;!Y&&this.options.startAt&&this.options.interval&&([Y,Q]=this._calculatePreviousRun(Y,Q),X=!Y),Y=new hW(Y,this.options.timezone||this.options.utcOffset),this.options.startAt&&Y&&Y.getTime()<this.options.startAt.getTime()&&(Y=this.options.startAt);let J=this._states.once||new hW(Y,this.options.timezone||this.options.utcOffset);return!X&&J!==this._states.once&&(J=J.increment(this._states.pattern,this.options,Q)),this._states.once&&this._states.once.getTime()<=Y.getTime()||J===null||this._states.maxRuns!==void 0&&this._states.maxRuns<=0||this._states.kill||this.options.stopAt&&J.getTime()>=this.options.stopAt.getTime()?null:J}_calculatePreviousRun(Y,Q){let X=new hW(void 0,this.options.timezone||this.options.utcOffset),J=Y;if(this.options.startAt.getTime()<=X.getTime()){J=this.options.startAt;let G=J.getTime()+this.options.interval*1000;for(;G<=X.getTime();)J=new hW(J,this.options.timezone||this.options.utcOffset).increment(this._states.pattern,this.options,!0),G=J.getTime()+this.options.interval*1000;Q=!0}return J===null&&(J=void 0),[J,Q]}};var uL1=j(()=>{gJ.fromTZISO=(Y,Q,X)=>gJ.fromTZ(Fc6(Y,Q),X);gJ.fromTZ=function(Y,Q){let X=new Date(Date.UTC(Y.y,Y.m-1,Y.d,Y.h,Y.i,Y.s)),J=xL1(Y.tz,X),G=new Date(X.getTime()-J),K=xL1(Y.tz,G);if(K-J===0)return G;{let W=new Date(X.getTime()-K),Z=xL1(Y.tz,W);if(Z-K===0)return W;if(!Q&&Z-K>0)return W;if(Q)throw Error("Invalid date passed to fromTZ()");return G}};gJ.toTZ=function(Y,Q){let X=Y.toLocaleString("en-US",{timeZone:Q}).replace(/[\u202f]/," "),J=new Date(X);return{y:J.getFullYear(),m:J.getMonth()+1,d:J.getDate(),h:J.getHours(),i:J.getMinutes(),s:J.getSeconds(),tz:Q}};gJ.tp=(Y,Q,X,J,G,K,W)=>({y:Y,m:Q,d:X,h:J,i:G,s:K,tz:W});gJ.minitz=gJ;mv=31|gL1,$o0=[1,2,4,8,16],Ko0=[31,28,31,30,31,30,31,31,30,31,30,31],EF=[["month","year",0],["day","month",-1],["hour","day",0],["minute","hour",0],["second","minute",0]];Yo=[]});class lv{localEmit=null;async start(Y){this.localEmit=Y}broadcast(Y,Q){this.localEmit?.(Y,Q)}async stop(){this.localEmit=null}}class qo0{listeners=new Map;totalCount=0;strategy=new lv;started=!1;async start(Y){if(this.started){if(!Y)return;await this.stop()}if(Y)this.strategy=Y;await this.strategy.start((Q,X)=>this.localEmit(Q,X)),this.started=!0}async stop(){if(!this.started)return;await this.strategy.stop(),this.started=!1}add(Y){if(this.totalCount>=Vo0)return console.warn(`[SSEHub] Total connection limit reached (${Vo0})`),null;let Q=this.listeners.get(Y.organizationId);if(!Q)Q=new Map,this.listeners.set(Y.organizationId,Q);if(Q.size>=Fo0)return console.warn(`[SSEHub] Per-org connection limit reached for ${Y.organizationId} (${Fo0})`),null;return Q.set(Y.id,Y),this.totalCount++,Y.id}remove(Y,Q){let X=this.listeners.get(Y);if(!X)return;if(X.delete(Q)){if(this.totalCount--,X.size===0)this.listeners.delete(Y)}}emit(Y,Q){this.strategy.broadcast(Y,Q)}countForOrg(Y){return this.listeners.get(Y)?.size??0}get count(){return this.totalCount}localEmit(Y,Q){let X=this.listeners.get(Y);if(!X||X.size===0)return;for(let J of X.values()){if(J.typePatterns&&!Uc6(Q.type,J.typePatterns))continue;try{J.push(Q)}catch{this.remove(Y,J.id)}}}}function Uc6(Y,Q){for(let X of Q){if(X===Y)return!0;if(X.endsWith(".*")){let J=X.slice(0,-1);if(Y.startsWith(J))return!0}}return!1}function Bo0(Y){return{id:Y.id,type:Y.type,source:Y.source,subject:Y.subject,data:Y.data?Dc6(Y.data):void 0,time:Y.time}}function Dc6(Y){if(typeof Y==="string")try{return JSON.parse(Y)}catch{return Y}return Y}var Fo0=50,Vo0=500,uJ;var Xo=j(()=>{uJ=new qo0});var Jo;var mL1=j(()=>{Jo={pollIntervalMs:5000,batchSize:100,maxAttempts:20,retryDelayMs:1000,maxDelayMs:3600000}});function zc6(Y){return Y.endsWith("_self")}function Oc6(Y){return Y.slice(0,-5)}function Uo0(){return async(Y,Q)=>{try{if(zc6(Y)&&VO1()){let W=Oc6(Y),Z=await PF.create();if(await qc0(Q,{organizationId:W,connectionId:Y,publish:async(F,V,B,U)=>{await Z.eventBus.publish(W,Y,{type:F,subject:V,data:B,deliverAt:U?.deliverAt})},createMCPProxy:async(F)=>{let V=await fL1(F,Z);return{callTool:async(B,U,D)=>{let z=await V.callTool(B,U,D);return{content:z.content,structuredContent:z.structuredContent,isError:z.isError}},close:()=>V.close()}}}))return{success:!0}}let X=await PF.create(),J=await fL1(Y,X),K=await tq1.forClient(TO(J)).ON_EVENTS({events:Q});return{success:K.success,error:K.error,retryAfter:K.retryAfter,results:K.results}}catch(X){let J=X instanceof Error?X.message:String(X);return console.error(`[EventBus] Failed to notify connection ${Y}:`,J),{success:!1,error:J}}}}var Do0=j(()=>{ir();Bv();Yk();CO()});function zo0(Y){return{specversion:"1.0",id:Y.id,source:Y.source,type:Y.type,time:Y.time,subject:Y.subject??void 0,datacontenttype:Y.datacontenttype,dataschema:Y.dataschema??void 0,data:Y.data??void 0}}function Nc6(Y){let Q=new Map;for(let J of Y){let G=J.subscription.connectionId,K=Q.get(G);if(K){if(K.deliveryIds.push(J.delivery.id),!K.seenEventIds.has(J.event.id))K.seenEventIds.add(J.event.id),K.events.push(zo0(J.event))}else Q.set(G,{connectionId:J.subscription.connectionId,deliveryIds:[J.delivery.id],events:[zo0(J.event)],seenEventIds:new Set([J.event.id])})}let X=new Map;for(let[J,G]of Q)X.set(J,{connectionId:G.connectionId,deliveryIds:G.deliveryIds,events:G.events});return X}class lL1{storage;notifySubscriber;running=!1;processing=!1;pendingNotify=!1;config;constructor(Y,Q){this.storage=Y;this.notifySubscriber=Uo0(),this.config={...Jo,...Q}}async start(){if(this.running)return;let Y=await this.storage.resetStuckDeliveries();if(Y>0)console.log(`[EventBus] Reset ${Y} stuck deliveries from previous shutdown`);this.running=!0}stop(){this.running=!1,console.log("[EventBus] Worker stopped")}isRunning(){return this.running}async processNow(){if(!this.running)return;if(this.processing){this.pendingNotify=!0;return}this.processing=!0;try{do this.pendingNotify=!1,await this.processEvents();while(this.pendingNotify)}catch(Y){console.error("[EventBus] Error processing events:",Y)}finally{this.processing=!1}}async processEvents(){let Y=await this.storage.claimPendingDeliveries(this.config.batchSize);if(Y.length===0)return;let Q=Nc6(Y),X=new Set;await Promise.allSettled(Array.from(Q.entries()).map(async([J,G])=>{try{let K=await this.notifySubscriber(G.connectionId,G.events);if(K.results&&Object.keys(K.results).length>0)await this.processPerEventResults(G,K);else if(K.success)await this.storage.markDeliveriesDelivered(G.deliveryIds);else if(K.retryAfter&&K.retryAfter>0)await this.storage.scheduleRetryWithoutAttemptIncrement(G.deliveryIds,K.retryAfter);else await this.storage.markDeliveriesFailed(G.deliveryIds,K.error||"Subscriber returned success=false",this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}catch(K){let W=K instanceof Error?K.message:String(K);console.error(`[EventBus] Failed to notify subscription ${J}:`,W),await this.storage.markDeliveriesFailed(G.deliveryIds,W,this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}for(let K of Y)if(G.deliveryIds.includes(K.delivery.id))X.add(K.event.id)}));for(let J of X)try{await this.storage.updateEventStatus(J);let G=Y.find((K)=>K.event.id===J)?.event;if(G?.cron)await this.scheduleNextCronDelivery(G)}catch(G){console.error(`[EventBus] Failed to update event status ${J}:`,G)}}async processPerEventResults(Y,Q){let X=[],J=new Map,G=[],K=new Map;for(let W=0;W<Y.events.length;W++){let Z=Y.events?.[W];if(!Z)continue;let H=Y.deliveryIds?.[W];if(!H)continue;K.set(Z.id,H)}for(let W of Y.events){let Z=K.get(W.id);if(!Z)continue;let H=Q.results?.[W.id];if(H)if(H.success)X.push(Z);else if(H.retryAfter&&H.retryAfter>0){let $=J.get(H.retryAfter)||[];$.push(Z),J.set(H.retryAfter,$)}else G.push({deliveryId:Z,error:H.error||"Event processing failed"});else if(Q.success)X.push(Z);else if(Q.retryAfter&&Q.retryAfter>0){let $=J.get(Q.retryAfter)||[];$.push(Z),J.set(Q.retryAfter,$)}else G.push({deliveryId:Z,error:Q.error||"Batch processing failed"})}if(X.length>0)await this.storage.markDeliveriesDelivered(X);for(let[W,Z]of J)await this.storage.scheduleRetryWithoutAttemptIncrement(Z,W);if(G.length>0){let W=new Map;for(let{deliveryId:Z,error:H}of G){let $=W.get(H)||[];$.push(Z),W.set(H,$)}for(let[Z,H]of W)await this.storage.markDeliveriesFailed(H,Z,this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}}async scheduleNextCronDelivery(Y){if(!Y.cron)return;try{let X=new Qo(Y.cron).nextRun();if(!X){console.log(`[EventBus] Cron expression for event ${Y.id} has no more runs`);return}let J=X.toISOString(),G=await this.storage.getMatchingSubscriptions(Y);if(G.length===0){console.log(`[EventBus] No subscriptions for cron event ${Y.id}, skipping next delivery`);return}await this.storage.createDeliveries(Y.id,G.map((K)=>K.id),J),console.log(`[EventBus] Scheduled next cron delivery for event ${Y.id} at ${J}`)}catch(Q){console.error(`[EventBus] Failed to schedule next cron delivery for event ${Y.id}:`,Q)}}}var Oo0=j(()=>{uL1();mL1();Do0()});class dL1{storage;worker;notifyStrategy;running=!1;constructor(Y){this.storage=Y.storage,this.notifyStrategy=Y.notifyStrategy,this.worker=new lL1(this.storage,Y.config)}async publish(Y,Q,X){if(X.deliverAt&&X.cron)throw Error("Cannot set both deliverAt and cron. Use one or the other.");let J;if(X.cron){try{let F=new Qo(X.cron).nextRun();if(!F)throw Error("Cron expression does not produce a next run time");J=F.toISOString()}catch($){throw Error(`Invalid cron expression: ${$ instanceof Error?$.message:String($)}`)}let H=await this.storage.findActiveCronEvent(Y,X.type,Q,X.cron);if(H)return H}let G=crypto.randomUUID(),K=new Date().toISOString(),W=await this.storage.publishEvent({id:G,organizationId:Y,type:X.type,source:Q,subject:X.subject,time:K,data:X.data,cron:X.cron});uJ.emit(Y,Bo0(W));let Z=await this.storage.getMatchingSubscriptions(W);if(Z.length>0){let H=X.deliverAt??J;if(await this.storage.createDeliveries(G,Z.map(($)=>$.id),H),this.notifyStrategy&&!H)await this.notifyStrategy.notify(G).catch(($)=>{console.warn("[EventBus] Notify failed (non-critical):",$)})}return W}async subscribe(Y,Q){return this.storage.subscribe({id:crypto.randomUUID(),organizationId:Y,connectionId:Q.connectionId,publisher:Q.publisher,eventType:Q.eventType,filter:Q.filter})}async unsubscribe(Y,Q){return this.storage.unsubscribe(Q,Y)}async listSubscriptions(Y,Q){return this.storage.listSubscriptions(Y,Q)}async getSubscription(Y,Q){return this.storage.getSubscription(Q,Y)}async getEvent(Y,Q){return this.storage.getEvent(Q,Y)}async cancelEvent(Y,Q,X){return this.storage.cancelEvent(Q,Y,X)}async ackEvent(Y,Q,X){return this.storage.ackDelivery(Q,Y,X)}async syncSubscriptions(Y,Q){return this.storage.syncSubscriptions({organizationId:Y,...Q})}async start(){if(this.running)return;if(this.running=!0,await this.worker.start(),this.notifyStrategy)await this.notifyStrategy.start(()=>{this.worker.processNow().catch((Y)=>{console.error("[EventBus] Error processing after notify:",Y)})});await this.worker.processNow().catch((Y)=>{console.error("[EventBus] Error processing pending events on startup:",Y)})}async stop(){if(!this.running)return;if(this.running=!1,this.worker.stop(),this.notifyStrategy)try{await this.notifyStrategy.stop()}catch(Y){console.error("[EventBus] Error stopping notify strategy:",Y)}console.log("[EventBus] Stopped")}isRunning(){return this.running}}var No0=j(()=>{uL1();Xo();Oo0()});class pL1{options;sub=null;onNotify=null;encoder=new TextEncoder;constructor(Y){this.options=Y}async start(Y){let Q=this.options.getConnection();if(!Q||this.sub)return;this.onNotify=Y,this.sub=Q.subscribe("mesh.events.notify"),(async()=>{for await(let X of this.sub)this.onNotify?.()})().catch((X)=>{console.error("[NatsNotify] Subscription error:",X)}),console.log("[NatsNotify] Started, subscribed to","mesh.events.notify")}async stop(){this.sub?.unsubscribe(),this.sub=null,this.onNotify=null,console.log("[NatsNotify] Stopped")}async notify(Y){let Q=this.options.getConnection();if(!Q)return;try{Q.publish("mesh.events.notify",this.encoder.encode(Y))}catch(X){console.warn("[NatsNotify] Publish failed (non-critical):",X)}}}class cL1{options;sub=null;localEmit=null;originId=crypto.randomUUID();encoder=new TextEncoder;constructor(Y){this.options=Y}async start(Y){this.localEmit=Y;let Q=this.options.getConnection();if(!Q||this.sub)return;this.sub=Q.subscribe("mesh.sse.broadcast");let X=new TextDecoder;(async()=>{for await(let J of this.sub)try{let G=JSON.parse(X.decode(J.data));if(typeof G?.originId!=="string"||typeof G?.organizationId!=="string"||typeof G?.event?.id!=="string"||typeof G?.event?.type!=="string")continue;if(G.originId===this.originId)continue;this.localEmit?.(G.organizationId,G.event)}catch{}})().catch((J)=>{console.error("[NatsSSEBroadcast] Subscription error:",J)}),console.log("[NatsSSEBroadcast] Started, subscribed to","mesh.sse.broadcast")}broadcast(Y,Q){this.localEmit?.(Y,Q);let X=this.options.getConnection();if(!X)return;let J={originId:this.originId,organizationId:Y,event:Q};try{X.publish("mesh.sse.broadcast",this.encoder.encode(JSON.stringify(J)))}catch(G){console.warn("[NatsSSEBroadcast] Publish failed (non-critical):",G)}}async stop(){this.sub?.unsubscribe(),this.sub=null,this.localEmit=null,console.log("[NatsSSEBroadcast] Stopped")}}function nL1(...Y){return{async start(Q){await Promise.all(Y.map((X)=>X.start(Q)))},async stop(){await Promise.all(Y.map((Q)=>Q.stop().catch((X)=>{console.error("[NotifyStrategy] Error stopping strategy:",X)})))},async notify(Q){await Promise.all(Y.map((X)=>X.notify(Q).catch((J)=>{console.warn("[NotifyStrategy] Notify failed (non-critical):",J)})))}}}class iL1{intervalMs;timer=null;onNotify=null;constructor(Y){this.intervalMs=Y}async start(Y){if(this.timer)return;this.onNotify=Y,this.scheduleNext(),console.log(`[Polling] Started polling every ${this.intervalMs}ms`)}async stop(){if(this.timer)clearTimeout(this.timer),this.timer=null,console.log("[Polling] Stopped polling");this.onNotify=null}async notify(Y){if(this.onNotify)this.onNotify()}scheduleNext(){this.timer=setTimeout(()=>{if(this.onNotify)this.onNotify();if(this.timer)this.scheduleNext()},this.intervalMs)}}import{sql as Lc6}from"kysely";class aL1{db;pool;listenClient=null;onNotify=null;constructor(Y,Q){this.db=Y;this.pool=Q}async start(Y){if(this.listenClient)return;this.onNotify=Y;try{this.listenClient=await this.pool.connect(),this.listenClient.on("notification",(Q)=>{if(Q.channel===yP&&this.onNotify)this.onNotify()}),this.listenClient.on("error",(Q)=>{console.error("[PostgresNotify] Connection error:",Q),this.cleanup()}),await this.listenClient.query(`LISTEN ${yP}`),console.log("[PostgresNotify] Started LISTEN on",yP)}catch(Q){console.error("[PostgresNotify] Failed to start LISTEN:",Q),this.cleanup()}}async stop(){if(this.listenClient){try{await this.listenClient.query(`UNLISTEN ${yP}`),console.log("[PostgresNotify] Stopped LISTEN on",yP)}catch{}this.cleanup()}}async notify(Y){try{await Lc6`SELECT pg_notify(${yP}, ${Y})`.execute(this.db)}catch(Q){console.warn("[PostgresNotify] Failed to send NOTIFY:",Q)}}cleanup(){if(this.listenClient)this.listenClient.release(),this.listenClient=null;this.onNotify=null}}var yP="mesh_events";var Lo0=()=>{};function Mc6(Y){let Q=process.env.NOTIFY_STRATEGY;if(Q==="nats"||Q==="postgres"||Q==="polling")return Q;if(process.env.NATS_URL)return"nats";if(Y.type==="postgres")return"postgres";return"polling"}function Mo0(Y,Q,X){let J=Wo0(Y.db),G=Q?.pollIntervalMs??Jo.pollIntervalMs,K=Mc6(Y),W=new iL1(G),Z=process.env.NATS_URL,H;switch(K){case"nats":{if(!Z)throw Error("[EventBus] NOTIFY_STRATEGY=nats requires NATS_URL to be set");let F=(()=>{try{return new URL(Z).host}catch{return"unknown"}})();if(!X){console.warn(`[EventBus] NATS unavailable (${F}), falling back to polling`),H=W;break}console.log(`[EventBus] Using NATS notify strategy (${F})`),H=nL1(W,new pL1({getConnection:()=>X.getConnection()}));break}case"postgres":{if(Y.type!=="postgres"){console.warn("[EventBus] NOTIFY_STRATEGY=postgres requires a PostgreSQL database, falling back to polling"),H=W;break}console.log("[EventBus] Using PostgreSQL LISTEN/NOTIFY strategy"),H=nL1(W,new aL1(Y.db,Y.pool));break}case"polling":default:console.log("[EventBus] Using polling notify strategy"),H=W}let $=Z&&X?new cL1({getConnection:()=>X.getConnection()}):new lv;if(uJ.start($).catch((F)=>{console.error("[SSEHub] Failed to start broadcast strategy:",F)}),Z&&X)console.log("[SSEHub] Using NATS SSE broadcast (cross-pod)");else console.log("[SSEHub] Using local SSE broadcast (single-pod)");return new dL1({storage:J,config:Q,notifyStrategy:H})}var Go=j(()=>{No0();mL1();Lo0();Xo();Xo()});var wo0;var Ao0=j(()=>{wo0={google:{name:"Google",icon:"https://assets.decocache.com/webdraw/eb7480aa-a68b-4ce4-98ff-36aa121762a7/google.svg"},github:{name:"GitHub",icon:"https://assets.decocache.com/webdraw/5f999dcb-c8a6-4572-948c-9996ef1d502f/github.svg"},microsoft:{name:"Microsoft",icon:"https://assets.decocache.com/mcp/aa6f6e1a-6526-4bca-99cc-82e2ec38b0e4/microsoft.png"}}});var Po0,Eo0;var To0=j(()=>{JK();wP();Ao0();Po0=new VQ;Po0.get("/config",async(Y)=>{try{let Q=Object.keys(p9.socialProviders??{}),X=Q.length>0,J=Q.map((W)=>({name:W,icon:wo0[W].icon})),G=process.env.UNSAFE_ALLOW_STDIO_TRANSPORT==="true",K={emailAndPassword:{enabled:p9.emailAndPassword?.enabled??!1},magicLink:{enabled:p9.magicLinkConfig?.enabled??!1},resetPassword:{enabled:KL1},socialProviders:{enabled:X,providers:J},sso:p9.ssoConfig?{enabled:!0,providerId:p9.ssoConfig.providerId}:{enabled:!1},stdioEnabled:G};return Y.json({success:!0,config:K})}catch(Q){let X=Q instanceof Error?Q.message:"Failed to load auth config";return Y.json({success:!1,error:X},500)}});Eo0=Po0});function Co0(Y){let{toolOutputMap:Q}=Y;return fJ({description:"The input is a string. Dont make assumptions about its format; prefer using regexes and string manipulation to extract the desired information. You may call this tool multiple times to extract the desired information.",inputExamples:[{input:{tool_call_id:"tool_call_id_1",code:"export default (input) => { return input.match(/[a-z]/g); }"}},{input:{tool_call_id:"tool_call_id_2",code:"export default (input) => { return input.split(' ').map(word => word.length); }"}}],inputSchema:l8(q.object({tool_call_id:q.string(),code:q.string().min(1).describe("JavaScript code to transform the tool output. The code must be an ES module: `export default (input) => { ... }`")})),execute:async({tool_call_id:X,code:J})=>{if(!Q.has(X))throw Error(`Tool output not found for tool call id: ${X}`);let G=Q.get(X),K=await MO1({input:G,code:J,timeoutMs:5000}),W=rL1({return:K.returnValue});if(W>4000)throw Error(`Tool call ${X} output is too long to display (${W} tokens), reduce or truncate the output`);return{result:K.returnValue,error:K.error,consoleLogs:K.consoleLogs}}})}function Pc6(Y){if(!Y)return 0;let Q=Y.match(Ac6)?.length??0,X=Y.length-Q;return Math.ceil(X/wc6)+Math.ceil(Q*1.5)}function rL1(Y){let Q=typeof Y==="string"?Y:JSON.stringify(Y);return Pc6(Q)}var wc6=4,Ac6;var oL1=j(()=>{sZ();n1();Nr();Ac6=/[\u3000-\u303f\u3040-\u309f\u30a0-\u30ff\u4e00-\u9fff\u3400-\u4dbf\uf900-\ufaff]/g});function Wo(Y,Q){if(Y==="yolo")return!1;if(Y==="none")return!0;return Q!==!0}function Zo(Y){let Q=Y.get("meshContext").organization;if(!Q)throw Error("Organization context is required");if((Q.slug??Q.id)!==Y.req.param("org"))throw Error("Organization mismatch");return Q}async function dv(Y,Q,X,J="none",G){let K=!G?.disableOutputTruncation,Z=(await Y.listTools()).tools.map((H)=>{let{name:$,title:F,description:V,inputSchema:B,annotations:U}=H;return[$,fJ({title:F??$,description:V,inputSchema:SW(B),outputSchema:void 0,needsApproval:Wo(J,U?.readOnlyHint),execute:async(D,z)=>{let L=performance.now();try{return await Y.callTool({name:H.name,arguments:D},EK,{signal:z.abortSignal,timeout:cr0})}finally{if(X){let w=performance.now()-L;X.write({type:"data-tool-metadata",id:z.toolCallId,data:{annotations:H.annotations,latencyMs:w}})}}},toModelOutput:async({output:D,toolCallId:z})=>{if(K){let w=rL1(D.structuredContent??D.content);if(w>4000)return Q.set(z,JSON.stringify(D.structuredContent??D.content)),{type:"text",value:`Tool call ${z} output is too long to display (${w} tokens), use the read_tool_output tool`}}if(D.isError)return{type:"error-text",value:D.content.map((E)=>E.type==="text"?E.text:null).filter(Boolean).join(`
1540
- `)||"Unknown error"};if("structuredContent"in D)return{type:"json",value:D.structuredContent};return{type:"text",value:D.content.map((w)=>{if(w.type==="text")return w.text;return JSON.stringify(w)}).join(`
1539
+ Example output: Available Tools Overview`;var _P=j(()=>{F7();er0=["user_ask","subtask"]});function er(Y){return typeof Y==="string"?Y:Y.toISOString()}class gv{db;constructor(Y){this.db=Y}async create(Y){let Q=Y.id??J9("thrd"),X=new Date().toISOString();if(!Y.organization_id)throw Error("organization_id is required");if(!Y.created_by)throw Error("created_by is required");if(!Y.title)Y.title=tr;let J={id:Q,organization_id:Y.organization_id,title:Y.title,description:Y.description??null,status:Y.status??"completed",created_at:X,updated_at:X,created_by:Y.created_by,updated_by:Y.updated_by??null},G=await this.db.insertInto("threads").values(J).returningAll().executeTakeFirstOrThrow();return this.threadFromDbRow(G)}async get(Y){let Q=await this.db.selectFrom("threads").selectAll().where("id","=",Y).executeTakeFirst();return Q?this.threadFromDbRow(Q):null}async update(Y,Q){let J={updated_at:new Date().toISOString()};if(Q.title!==void 0)J.title=Q.title;if(Q.description!==void 0)J.description=Q.description;if(Q.updated_by!==void 0)J.updated_by=Q.updated_by;if(Q.hidden!==void 0)J.hidden=Q.hidden;if(Q.status!==void 0)J.status=Q.status;await this.db.updateTable("threads").set(J).where("id","=",Y).execute();let G=await this.get(Y);if(!G)throw Error("Thread not found after update");return G}async delete(Y){await this.db.deleteFrom("threads").where("id","=",Y).execute()}async list(Y,Q,X){let J=this.db.selectFrom("threads").selectAll().where("organization_id","=",Y).where("hidden","=",!1).orderBy("updated_at","desc");if(Q)J=J.where("created_by","=",Q);let G=this.db.selectFrom("threads").select((Z)=>Z.fn.count("id").as("count")).where("organization_id","=",Y).where("hidden","=",!1);if(Q)G=G.where("created_by","=",Q);if(X?.limit)J=J.limit(X.limit);if(X?.offset)J=J.offset(X.offset);let[K,W]=await Promise.all([J.execute(),G.executeTakeFirst()]);return{threads:K.map((Z)=>this.threadFromDbRow(Z)),total:Number(W?.count||0)}}async saveMessages(Y){let Q=new Date().toISOString(),X=Y[0]?.thread_id;if(!X)throw Error("thread_id is required when creating multiple messages");let J=new Map;for(let Z of Y){let H=J.get(Z.id);if(H&&H.thread_id!==Z.thread_id)throw Error(`Duplicate message id "${Z.id}" with conflicting thread_ids: "${H.thread_id}" vs "${Z.thread_id}"`);J.set(Z.id,Z)}let G=[...J.values()],K=G.find((Z)=>Z.thread_id!==X);if(K)throw Error(`All messages must target the same thread. Expected thread_id "${X}", but message "${K.id}" has thread_id "${K.thread_id}"`);let W=G.map((Z)=>({id:Z.id,thread_id:X,metadata:Z.metadata?JSON.stringify(Z.metadata):null,parts:JSON.stringify(Z.parts),role:Z.role,created_at:Z.created_at??Q,updated_at:Q}));await this.db.transaction().execute(async(Z)=>{await Z.insertInto("thread_messages").values(W).onConflict((H)=>H.column("id").doUpdateSet(($)=>({metadata:$.ref("excluded.metadata"),parts:$.ref("excluded.parts"),role:$.ref("excluded.role"),updated_at:$.ref("excluded.updated_at")}))).execute(),await Z.updateTable("threads").set({updated_at:Q}).where("id","=",X).execute()})}async listMessages(Y,Q){let X=Q?.sort??"asc",J=this.db.selectFrom("thread_messages").selectAll().where("thread_id","=",Y).orderBy("created_at",X).orderBy("id",X),G=this.db.selectFrom("thread_messages").select((Z)=>Z.fn.count("id").as("count")).where("thread_id","=",Y);if(Q?.limit)J=J.limit(Q.limit);if(Q?.offset)J=J.offset(Q.offset);let[K,W]=await Promise.all([J.execute(),G.executeTakeFirst()]);return{messages:K.map((Z)=>this.messageFromDbRow(Z)),total:Number(W?.count||0)}}threadFromDbRow(Y){return{id:Y.id,organization_id:Y.organization_id,title:Y.title,description:Y.description,status:Y.status,created_at:er(Y.created_at),updated_at:er(Y.updated_at),created_by:Y.created_by,updated_by:Y.updated_by,hidden:!!Y.hidden}}messageFromDbRow(Y){let Q,X;try{Q=Y.metadata?JSON.parse(Y.metadata):void 0}catch(J){console.error(`Failed to parse metadata for message ${Y.id}:`,Y.metadata,J),Q=void 0}try{X=typeof Y.parts==="string"?JSON.parse(Y.parts):Y.parts}catch(J){console.error(`Failed to parse parts for message ${Y.id}:`,Y.parts,J),X=[]}return{id:Y.id,thread_id:Y.thread_id,metadata:Q,parts:X,role:Y.role,created_at:er(Y.created_at),updated_at:er(Y.updated_at)}}}var hL1=j(()=>{F7();_P()});function Gc6(Y){if(!Y)return;try{let Q=JSON.parse(Y);if(typeof Q!=="object"||Q===null||Array.isArray(Q))return;let X={};for(let[J,G]of Object.entries(Q))if(typeof G==="string")X[J]=G;return Object.keys(X).length>0?X:void 0}catch{return}}function Wc6(Y,Q){for(let[X,J]of Object.entries(Q)){let G=Y[X];if(!G||G.length===0){let K=Y["*"];if(!K||K.length===0)return!1;if(K.includes("*"))continue;for(let W of J)if(!K.includes(W))return!1;continue}if(G.includes("*"))continue;for(let K of J)if(!G.includes(K))return!1}return!0}function Zc6(Y){let{auth:Q,headers:X,role:J,permissions:G,userId:K}=Y,W=Q.api.hasPermission;return{hasPermission:async(Z)=>{if(J&&WL1.includes(J))return!0;if(G)return Wc6(G,Z);if(!W)return console.error("[Auth] hasPermission API not available"),!1;try{if((await W({headers:X,body:{permission:Z}}))?.success===!0)return!0;let $={};for(let V of Object.keys(Z))$[V]=["*"];return(await W({headers:X,body:{permission:$}}))?.success===!0}catch(H){return console.error("[Auth] Permission check failed:",H),!1}},organization:{create:async(Z)=>{return Q.api.createOrganization({headers:X,body:Z})},update:async(Z)=>{return Q.api.updateOrganization({headers:X,body:Z})},delete:async(Z)=>{await Q.api.deleteOrganization({headers:X,body:{organizationId:Z}})},get:async(Z)=>{return Q.api.getFullOrganization({headers:X,query:Z?{organizationId:Z}:void 0})},list:async(Z)=>{return Q.api.listOrganizations({headers:X,query:Z?{userId:Z}:void 0})},addMember:async(Z)=>{return Q.api.addMember({headers:X,body:Z})},removeMember:async(Z)=>{await Q.api.removeMember({headers:X,body:Z})},listMembers:async(Z)=>{return Q.api.listMembers({headers:X,query:Z?{organizationId:Z.organizationId,limit:Z.limit,offset:Z.offset}:void 0})},updateMemberRole:async(Z)=>{return Q.api.updateMemberRole({headers:X,body:Z})}},apiKey:{create:async(Z)=>{return Q.api.createApiKey({body:{...Z,userId:K}})},list:async()=>{return Q.api.listApiKeys({headers:X})},update:async(Z)=>{return Q.api.updateApiKey({body:{...Z,userId:K}})},delete:async(Z)=>{await Q.api.deleteApiKey({headers:X,body:{keyId:Z}})}}}}async function Kc6(Y,Q,X){if(WL1.includes(X))return;let J=await Y.selectFrom("organizationRole").select(["permission"]).where("organizationId","=",Q).where("role","=",X).executeTakeFirst();if(!J?.permission)return;try{return JSON.parse(J.permission)}catch{console.error(`[Auth] Failed to parse permissions for role: ${X}`);return}}async function Hc6(Y,Q,X,J=Xo0){let G=Y.headers.get("Authorization");try{let K=new Headers(Y.headers);K.set("X-MCP-Session-Auth","true");let W=await J.measure("auth_get_mcp_session",()=>Q.api.getMcpSession({headers:K}));if(W){let Z=W.userId,H=await J.measure("auth_query_membership",()=>X.selectFrom("member").innerJoin("organization","organization.id","member.organizationId").select(["member.role","member.organizationId","organization.id as orgId","organization.slug as orgSlug","organization.name as orgName"]).where("member.userId","=",Z).executeTakeFirst()),$=H?.role,F=H?{id:H.orgId,slug:H.orgSlug,name:H.orgName}:void 0,V;if(H&&$)V=await J.measure("auth_fetch_role_permissions",()=>Kc6(X,H.organizationId,$));return{user:{id:Z,role:$},role:$,permissions:V,organization:F}}}catch(K){console.error("[Auth] OAuth session check failed:",K)}if(G?.startsWith("Bearer ")){let K=G.replace("Bearer ","").trim();try{let W=await J.measure("auth_verify_mesh_jwt",()=>Gn0(K));if(W){let Z,H=W.metadata?.organizationId;if(W.sub&&H)Z=(await J.measure("auth_query_membership",()=>X.selectFrom("member").select(["member.role"]).where("member.userId","=",W.sub).where("member.organizationId","=",H).executeTakeFirst()))?.role;return{user:{id:W.sub,connectionId:W.metadata?.connectionId,role:Z},role:Z,permissions:W.permissions,organization:W.metadata?.organizationId?{id:W.metadata?.organizationId}:void 0}}}catch{}try{let W=await J.measure("auth_verify_api_key",()=>Q.api.verifyApiKey({body:{key:K}}));if(W?.valid&&W.key){let Z=W.key.metadata?.organization,H=W.key.permissions,$,F=W.key.userId;if(F&&Z?.id)$=(await J.measure("auth_query_membership",()=>X.selectFrom("member").select(["member.role"]).where("member.userId","=",F).where("member.organizationId","=",Z.id).executeTakeFirst()))?.role;return{apiKeyId:W.key.id,user:{id:W.key.userId,role:$},role:$,permissions:H,organization:Z?{id:Z.id,slug:Z.slug,name:Z.name}:void 0}}}catch(W){console.error("[Auth] API key check failed:",W)}}try{let K=new Headers(Y.headers);K.delete("Authorization");let W=await J.measure("auth_get_session",()=>Q.api.getSession({headers:K}));if(W){let Z,H;if(W.session.activeOrganizationId){let $=await J.measure("auth_get_full_organization",()=>Q.api.getFullOrganization({headers:K}).catch(()=>null));if($)Z={id:$.id,slug:$.slug,name:$.name},H=$.members?.find((V)=>V.userId===W.user.id)?.role;else Z={id:W.session.activeOrganizationId,slug:"",name:""}}return{user:{id:W.user.id,email:W.user.email,role:H},role:H,organization:Z}}}catch(K){let W=K;console.error("[Auth] Session check failed:",JSON.stringify({message:W.message,body:W.body,stack:W.stack},null,2))}return{user:void 0}}async function Jo0(Y){let Q=new _z(Y.encryption.key),X={connections:new RS(Y.db,Q),organizationSettings:new CL1(Y.db),monitoring:new EL1(Y.db,Y.databaseType),monitoringDashboards:new TL1(Y.db),virtualMcps:new AL1(Y.db),users:new jL1(Y.db),threads:new gv(Y.db),tags:new IL1(Y.db),projects:new IS(Y.db),projectPluginConfigs:new RL1(Y.db)};return async(J,G)=>{let K=G?.timings??Xo0,W=Ir(),Z=J?.headers.get("x-caller-id")??void 0,H=J?await Hc6(J,Y.auth,Y.db,K):{user:void 0},$=Zc6({auth:Y.auth,headers:J?.headers??new Headers,role:H.role,permissions:H.permissions,userId:H.user?.id}),F={user:H.user};if(H.apiKeyId)F.apiKey={id:H.apiKeyId,name:"",userId:""};let V=H.organization,B=J?process.env.BASE_URL??`${new URL(J.url).origin}`:X7(),U=new LF(Y.auth,F.user?.id,void 0,$,H.role,"self"),D={timings:K,auth:F,connectionId:Z,organization:V,storage:X,vault:Q,authInstance:Y.auth,boundAuth:$,access:U,db:Y.db,tracer:Y.observability.tracer,meter:Y.observability.meter,baseUrl:B,metadata:{requestId:crypto.randomUUID(),timestamp:new Date,wellKnownForwardableHeaders:Object.fromEntries($c6.map((z)=>[z,J?.headers.get(z)??null]).filter(([z,L])=>L!==null)),userAgent:J?.headers.get("x-mesh-client")||J?.headers.get("User-Agent")||void 0,ipAddress:(J?.headers.get("CF-Connecting-IP")||J?.headers.get("X-Forwarded-For"))??void 0,properties:Gc6(J?.headers.get("x-mesh-properties"))},eventBus:Y.eventBus,createMCPProxy:async(z)=>{return await ir0(z,D)},getOrCreateClient:W};return D}}var Qo0,PF,Xo0,$c6;var ir=j(()=>{kO1();ln();Mq1();vr0();_r0();yr0();wq1();fr0();br0();Pv();CO();_r();hL1();_O1();PF={set:(Y)=>{Qo0=Y},create:async(Y,Q)=>{return await Qo0(Y,Q)}},Xo0={measure:async(Y,Q)=>{return await Q()}},$c6=["x-hub-signature-256"]});class Go0{db;constructor(Y){this.db=Y}async publishEvent(Y){let Q=new Date().toISOString();return await this.db.insertInto("events").values({id:Y.id,organization_id:Y.organizationId,type:Y.type,source:Y.source,specversion:"1.0",subject:Y.subject??null,time:Y.time,datacontenttype:Y.datacontenttype??"application/json",dataschema:Y.dataschema??null,data:Y.data?JSON.stringify(Y.data):null,cron:Y.cron??null,status:"pending",attempts:0,last_error:null,next_retry_at:null,created_at:Q,updated_at:Q}).execute(),{id:Y.id,organizationId:Y.organizationId,type:Y.type,source:Y.source,specversion:"1.0",subject:Y.subject??null,time:Y.time,datacontenttype:Y.datacontenttype??"application/json",dataschema:Y.dataschema??null,data:Y.data??null,cron:Y.cron??null,status:"pending",attempts:0,lastError:null,nextRetryAt:null,createdAt:Q,updatedAt:Q}}async subscribe(Y){let Q=this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",Y.organizationId).where("connection_id","=",Y.connectionId).where("event_type","=",Y.eventType);if(Y.publisher)Q=Q.where("publisher","=",Y.publisher);else Q=Q.where("publisher","is",null);if(Y.filter)Q=Q.where("filter","=",Y.filter);else Q=Q.where("filter","is",null);let X=await Q.executeTakeFirst();if(X)return{id:X.id,organizationId:X.organization_id,connectionId:X.connection_id,publisher:X.publisher,eventType:X.event_type,filter:X.filter,enabled:X.enabled===1,createdAt:X.created_at,updatedAt:X.updated_at};let J=new Date().toISOString();return await this.db.insertInto("event_subscriptions").values({id:Y.id,organization_id:Y.organizationId,connection_id:Y.connectionId,publisher:Y.publisher??null,event_type:Y.eventType,filter:Y.filter??null,enabled:1,created_at:J,updated_at:J}).execute(),{id:Y.id,organizationId:Y.organizationId,connectionId:Y.connectionId,publisher:Y.publisher??null,eventType:Y.eventType,filter:Y.filter??null,enabled:!0,createdAt:J,updatedAt:J}}async unsubscribe(Y,Q){return{success:((await this.db.deleteFrom("event_subscriptions").where("id","=",Y).where("organization_id","=",Q).executeTakeFirst()).numDeletedRows??0n)>0n}}async listSubscriptions(Y,Q){let X=this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",Y);if(Q)X=X.where("connection_id","=",Q);return(await X.execute()).map((G)=>({id:G.id,organizationId:G.organization_id,connectionId:G.connection_id,publisher:G.publisher,eventType:G.event_type,filter:G.filter,enabled:G.enabled===1,createdAt:G.created_at,updatedAt:G.updated_at}))}async getSubscription(Y,Q){let X=await this.db.selectFrom("event_subscriptions").selectAll().where("id","=",Y).where("organization_id","=",Q).executeTakeFirst();if(!X)return null;return{id:X.id,organizationId:X.organization_id,connectionId:X.connection_id,publisher:X.publisher,eventType:X.event_type,filter:X.filter,enabled:X.enabled===1,createdAt:X.created_at,updatedAt:X.updated_at}}async getMatchingSubscriptions(Y){return(await this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",Y.organizationId).where("enabled","=",1).where("event_type","=",Y.type).where((X)=>X.or([X("publisher","is",null),X("publisher","=",Y.source)])).execute()).map((X)=>({id:X.id,organizationId:X.organization_id,connectionId:X.connection_id,publisher:X.publisher,eventType:X.event_type,filter:X.filter,enabled:X.enabled===1,createdAt:X.created_at,updatedAt:X.updated_at}))}async createDeliveries(Y,Q,X){if(Q.length===0)return;let J=new Date().toISOString(),G=X??null,K=Q.map((W)=>({id:crypto.randomUUID(),event_id:Y,subscription_id:W,status:"pending",attempts:0,last_error:null,delivered_at:null,next_retry_at:G,created_at:J}));await this.db.insertInto("event_deliveries").values(K).execute()}async claimPendingDeliveries(Y){let Q=new Date().toISOString(),X;try{X=(await this.db.updateTable("event_deliveries").set({status:"processing"}).where("id","in",(K)=>K.selectFrom("event_deliveries as d").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select("d.id").where("d.status","=","pending").where("s.enabled","=",1).where((W)=>W.or([W("d.next_retry_at","is",null),W("d.next_retry_at","<=",Q)])).orderBy("d.created_at","asc").limit(Y)).where("status","=","pending").returning(["id"]).execute()).map((K)=>K.id)}catch{let G=await this.db.selectFrom("event_deliveries as d").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select(["d.id"]).where("d.status","=","pending").where("s.enabled","=",1).where((K)=>K.or([K("d.next_retry_at","is",null),K("d.next_retry_at","<=",Q)])).orderBy("d.created_at","asc").limit(Y).execute();if(G.length===0)return[];X=G.map((K)=>K.id),await this.db.updateTable("event_deliveries").set({status:"processing"}).where("id","in",X).where("status","=","pending").execute()}if(X.length===0)return[];return(await this.db.selectFrom("event_deliveries as d").innerJoin("events as e","e.id","d.event_id").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select(["d.id as delivery_id","d.event_id","d.subscription_id","d.status as delivery_status","d.attempts as delivery_attempts","d.last_error as delivery_last_error","d.delivered_at","d.next_retry_at as delivery_next_retry_at","d.created_at as delivery_created_at","e.organization_id","e.type","e.source","e.specversion","e.subject","e.time","e.datacontenttype","e.dataschema","e.data","e.cron","e.status as event_status","e.attempts as event_attempts","e.last_error as event_last_error","e.next_retry_at","e.created_at as event_created_at","e.updated_at as event_updated_at","s.connection_id","s.publisher","s.event_type","s.filter","s.enabled","s.created_at as subscription_created_at","s.updated_at as subscription_updated_at"]).where("d.id","in",X).where("d.status","=","processing").execute()).map((G)=>({delivery:{id:G.delivery_id,eventId:G.event_id,subscriptionId:G.subscription_id,status:G.delivery_status,attempts:G.delivery_attempts,lastError:G.delivery_last_error,deliveredAt:G.delivered_at,nextRetryAt:G.delivery_next_retry_at,createdAt:G.delivery_created_at},event:{id:G.event_id,organizationId:G.organization_id,type:G.type,source:G.source,specversion:G.specversion,subject:G.subject,time:G.time,datacontenttype:G.datacontenttype,dataschema:G.dataschema,data:G.data?JSON.parse(G.data):null,cron:G.cron,status:G.event_status,attempts:G.event_attempts,lastError:G.event_last_error,nextRetryAt:G.next_retry_at,createdAt:G.event_created_at,updatedAt:G.event_updated_at},subscription:{id:G.subscription_id,organizationId:G.organization_id,connectionId:G.connection_id,publisher:G.publisher,eventType:G.event_type,filter:G.filter,enabled:G.enabled===1,createdAt:G.subscription_created_at,updatedAt:G.subscription_updated_at}}))}async markDeliveriesDelivered(Y){if(Y.length===0)return;let Q=new Date().toISOString();await this.db.updateTable("event_deliveries").set({status:"delivered",delivered_at:Q}).where("id","in",Y).execute()}async markDeliveriesFailed(Y,Q,X=20,J=1000,G=3600000){if(Y.length===0)return;for(let K of Y){let W=await this.db.selectFrom("event_deliveries").select(["attempts"]).where("id","=",K).executeTakeFirst();if(!W)continue;let Z=W.attempts+1;if(Z>=X)await this.db.updateTable("event_deliveries").set({attempts:Z,last_error:Q,status:"failed",next_retry_at:null}).where("id","=",K).execute();else{let H=Math.min(J*Math.pow(2,Z-1),G),$=new Date(Date.now()+H).toISOString();await this.db.updateTable("event_deliveries").set({attempts:Z,last_error:Q,status:"pending",next_retry_at:$}).where("id","=",K).execute()}}}async updateEventStatus(Y){let Q=await this.db.selectFrom("event_deliveries").select(["status"]).where("event_id","=",Y).execute();if(Q.length===0)return;let X=Q.every((K)=>K.status==="delivered"),J=Q.some((K)=>K.status==="failed"),G=Q.some((K)=>K.status==="pending"||K.status==="processing");if(X)await this.db.updateTable("events").set({status:"delivered",updated_at:new Date().toISOString()}).where("id","=",Y).execute();else if(J&&!G)await this.db.updateTable("events").set({status:"failed",updated_at:new Date().toISOString()}).where("id","=",Y).execute()}async resetStuckDeliveries(){let Y=await this.db.updateTable("event_deliveries").set({status:"pending"}).where("status","=","processing").executeTakeFirst();return Number(Y.numUpdatedRows??0)}async getEvent(Y,Q){let X=await this.db.selectFrom("events").selectAll().where("id","=",Y).where("organization_id","=",Q).executeTakeFirst();if(!X)return null;return{id:X.id,organizationId:X.organization_id,type:X.type,source:X.source,specversion:X.specversion,subject:X.subject,time:X.time,datacontenttype:X.datacontenttype,dataschema:X.dataschema,data:X.data?JSON.parse(X.data):null,cron:X.cron,status:X.status,attempts:X.attempts,lastError:X.last_error,nextRetryAt:X.next_retry_at,createdAt:X.created_at,updatedAt:X.updated_at}}async findActiveCronEvent(Y,Q,X,J){let G=await this.db.selectFrom("events").selectAll().where("organization_id","=",Y).where("type","=",Q).where("source","=",X).where("cron","=",J).where("status","in",["pending","processing","delivered"]).orderBy("created_at","desc").executeTakeFirst();if(!G)return null;return{id:G.id,organizationId:G.organization_id,type:G.type,source:G.source,specversion:G.specversion,subject:G.subject,time:G.time,datacontenttype:G.datacontenttype,dataschema:G.dataschema,data:G.data?JSON.parse(G.data):null,cron:G.cron,status:G.status,attempts:G.attempts,lastError:G.last_error,nextRetryAt:G.next_retry_at,createdAt:G.created_at,updatedAt:G.updated_at}}async cancelEvent(Y,Q,X){let J=await this.db.updateTable("events").set({status:"failed",last_error:"Cancelled by publisher",updated_at:new Date().toISOString()}).where("id","=",Y).where("organization_id","=",Q).where("source","=",X).where("status","in",["pending","processing"]).executeTakeFirst();if((J.numUpdatedRows??0n)>0n)await this.db.updateTable("event_deliveries").set({status:"failed",last_error:"Event cancelled by publisher"}).where("event_id","=",Y).where("status","in",["pending","processing"]).execute();return{success:(J.numUpdatedRows??0n)>0n}}async scheduleRetryWithoutAttemptIncrement(Y,Q){if(Y.length===0)return;let X=new Date(Date.now()+Q).toISOString();await this.db.updateTable("event_deliveries").set({status:"pending",next_retry_at:X}).where("id","in",Y).execute()}async ackDelivery(Y,Q,X){if(!await this.db.selectFrom("events").select(["id"]).where("id","=",Y).where("organization_id","=",Q).executeTakeFirst())return{success:!1};let K=((await this.db.updateTable("event_deliveries").set({status:"delivered",delivered_at:new Date().toISOString()}).where("event_id","=",Y).where("status","in",["pending","processing"]).where((W)=>W.exists(W.selectFrom("event_subscriptions").select("id").whereRef("event_subscriptions.id","=","event_deliveries.subscription_id").where("event_subscriptions.connection_id","=",X).where("event_subscriptions.organization_id","=",Q))).executeTakeFirst()).numUpdatedRows??0n)>0n;if(K)await this.updateEventStatus(Y);return{success:K}}async syncSubscriptions(Y){let{organizationId:Q,connectionId:X,subscriptions:J}=Y,G=(w,E)=>{return`${w}::${E??""}`},K=await this.listSubscriptions(Q,X),W=new Map;for(let w of K)W.set(G(w.eventType,w.publisher),w);let Z=new Map;for(let w of J)Z.set(G(w.eventType,w.publisher),w);let H=new Date().toISOString(),$=[],F=[],V=[],B=0;for(let[w,E]of Z){let T=W.get(w);if(!T)$.push({id:crypto.randomUUID(),organization_id:Q,connection_id:X,event_type:E.eventType,publisher:E.publisher??null,filter:E.filter??null,enabled:1,created_at:H,updated_at:H});else{let C=T.filter??null,P=E.filter??null;if(C!==P)F.push({id:T.id,filter:P});else B++}}for(let[w,E]of W)if(!Z.has(w))V.push(E.id);if($.length>0)await this.db.insertInto("event_subscriptions").values($).execute();if(F.length>0)await Promise.all(F.map((w)=>this.db.updateTable("event_subscriptions").set({filter:w.filter,updated_at:H}).where("id","=",w.id).execute()));if(V.length>0)await this.db.deleteFrom("event_subscriptions").where("id","in",V).execute();let U=$.length,D=F.length,z=V.length,L=await this.listSubscriptions(Q,X);return{created:U,updated:D,deleted:z,unchanged:B,subscriptions:L}}}function Wo0(Y){return new Go0(Y)}function gJ(Y,Q,X,J,G,K,W,Z){return gJ.fromTZ(gJ.tp(Y,Q,X,J,G,K,W),Z)}function xL1(Y,Q=new Date){let X=Q.toLocaleString("en-US",{timeZone:Y,timeZoneName:"shortOffset"}).split(" ").slice(-1)[0],J=Q.toLocaleString("en-US").replace(/[\u202f]/," ");return Date.parse(`${J} GMT`)-Date.parse(`${J} ${X}`)}function Fc6(Y,Q){let X=new Date(Date.parse(Y));if(isNaN(X))throw Error("minitz: Invalid ISO8601 passed to parser.");let J=Y.substring(9);return Y.includes("Z")||J.includes("-")||J.includes("+")?gJ.tp(X.getUTCFullYear(),X.getUTCMonth()+1,X.getUTCDate(),X.getUTCHours(),X.getUTCMinutes(),X.getUTCSeconds(),"Etc/UTC"):gJ.tp(X.getFullYear(),X.getMonth()+1,X.getDate(),X.getHours(),X.getMinutes(),X.getSeconds(),Q)}function Vc6(Y){if(Y===void 0&&(Y={}),delete Y.name,Y.legacyMode=Y.legacyMode===void 0?!0:Y.legacyMode,Y.paused=Y.paused===void 0?!1:Y.paused,Y.maxRuns=Y.maxRuns===void 0?1/0:Y.maxRuns,Y.catch=Y.catch===void 0?!1:Y.catch,Y.interval=Y.interval===void 0?0:parseInt(Y.interval.toString(),10),Y.utcOffset=Y.utcOffset===void 0?void 0:parseInt(Y.utcOffset.toString(),10),Y.unref=Y.unref===void 0?!1:Y.unref,Y.startAt&&(Y.startAt=new hW(Y.startAt,Y.timezone)),Y.stopAt&&(Y.stopAt=new hW(Y.stopAt,Y.timezone)),Y.interval!==null){if(isNaN(Y.interval))throw Error("CronOptions: Supplied value for interval is not a number");if(Y.interval<0)throw Error("CronOptions: Supplied value for interval can not be negative")}if(Y.utcOffset!==void 0){if(isNaN(Y.utcOffset))throw Error("CronOptions: Invalid value passed for utcOffset, should be number representing minutes offset from UTC.");if(Y.utcOffset<-870||Y.utcOffset>870)throw Error("CronOptions: utcOffset out of bounds.");if(Y.utcOffset!==void 0&&Y.timezone)throw Error("CronOptions: Combining 'utcOffset' with 'timezone' is not allowed.")}if(Y.unref!==!0&&Y.unref!==!1)throw Error("CronOptions: Unref should be either true, false or undefined(false).");return Y}function uv(Y){return Object.prototype.toString.call(Y)==="[object Function]"||typeof Y=="function"||Y instanceof Function}function qc6(Y){return uv(Y)}function Bc6(Y){typeof Deno<"u"&&typeof Deno.unrefTimer<"u"?Deno.unrefTimer(Y):Y&&typeof Y.unref<"u"&&Y.unref()}var gL1=32,mv,$o0,Zo0=class{pattern;timezone;second;minute;hour;day;month;dayOfWeek;lastDayOfMonth;starDOM;starDOW;constructor(Y,Q){this.pattern=Y,this.timezone=Q,this.second=Array(60).fill(0),this.minute=Array(60).fill(0),this.hour=Array(24).fill(0),this.day=Array(31).fill(0),this.month=Array(12).fill(0),this.dayOfWeek=Array(7).fill(0),this.lastDayOfMonth=!1,this.starDOM=!1,this.starDOW=!1,this.parse()}parse(){if(!(typeof this.pattern=="string"||this.pattern instanceof String))throw TypeError("CronPattern: Pattern has to be of type string.");this.pattern.indexOf("@")>=0&&(this.pattern=this.handleNicknames(this.pattern).trim());let Y=this.pattern.replace(/\s+/g," ").split(" ");if(Y.length<5||Y.length>6)throw TypeError("CronPattern: invalid configuration format ('"+this.pattern+"'), exactly five or six space separated parts are required.");if(Y.length===5&&Y.unshift("0"),Y[3].indexOf("L")>=0&&(Y[3]=Y[3].replace("L",""),this.lastDayOfMonth=!0),Y[3]=="*"&&(this.starDOM=!0),Y[4].length>=3&&(Y[4]=this.replaceAlphaMonths(Y[4])),Y[5].length>=3&&(Y[5]=this.replaceAlphaDays(Y[5])),Y[5]=="*"&&(this.starDOW=!0),this.pattern.indexOf("?")>=0){let Q=new hW(new Date,this.timezone).getDate(!0);Y[0]=Y[0].replace("?",Q.getSeconds().toString()),Y[1]=Y[1].replace("?",Q.getMinutes().toString()),Y[2]=Y[2].replace("?",Q.getHours().toString()),this.starDOM||(Y[3]=Y[3].replace("?",Q.getDate().toString())),Y[4]=Y[4].replace("?",(Q.getMonth()+1).toString()),this.starDOW||(Y[5]=Y[5].replace("?",Q.getDay().toString()))}this.throwAtIllegalCharacters(Y),this.partToArray("second",Y[0],0,1),this.partToArray("minute",Y[1],0,1),this.partToArray("hour",Y[2],0,1),this.partToArray("day",Y[3],-1,1),this.partToArray("month",Y[4],-1,1),this.partToArray("dayOfWeek",Y[5],0,mv),this.dayOfWeek[7]&&(this.dayOfWeek[0]=this.dayOfWeek[7])}partToArray(Y,Q,X,J){let G=this[Y],K=Y==="day"&&this.lastDayOfMonth;if(Q===""&&!K)throw TypeError("CronPattern: configuration entry "+Y+" ("+Q+") is empty, check for trailing spaces.");if(Q==="*")return G.fill(J);let W=Q.split(",");if(W.length>1)for(let Z=0;Z<W.length;Z++)this.partToArray(Y,W[Z],X,J);else Q.indexOf("-")!==-1&&Q.indexOf("/")!==-1?this.handleRangeWithStepping(Q,Y,X,J):Q.indexOf("-")!==-1?this.handleRange(Q,Y,X,J):Q.indexOf("/")!==-1?this.handleStepping(Q,Y,X,J):Q!==""&&this.handleNumber(Q,Y,X,J)}throwAtIllegalCharacters(Y){for(let Q=0;Q<Y.length;Q++)if((Q===5?/[^/*0-9,\-#L]+/:/[^/*0-9,-]+/).test(Y[Q]))throw TypeError("CronPattern: configuration entry "+Q+" ("+Y[Q]+") contains illegal characters.")}handleNumber(Y,Q,X,J){let G=this.extractNth(Y,Q),K=parseInt(G[0],10)+X;if(isNaN(K))throw TypeError("CronPattern: "+Q+" is not a number: '"+Y+"'");this.setPart(Q,K,G[1]||J)}setPart(Y,Q,X){if(!Object.prototype.hasOwnProperty.call(this,Y))throw TypeError("CronPattern: Invalid part specified: "+Y);if(Y==="dayOfWeek"){if(Q===7&&(Q=0),Q<0||Q>6)throw RangeError("CronPattern: Invalid value for dayOfWeek: "+Q);this.setNthWeekdayOfMonth(Q,X);return}if(Y==="second"||Y==="minute"){if(Q<0||Q>=60)throw RangeError("CronPattern: Invalid value for "+Y+": "+Q)}else if(Y==="hour"){if(Q<0||Q>=24)throw RangeError("CronPattern: Invalid value for "+Y+": "+Q)}else if(Y==="day"){if(Q<0||Q>=31)throw RangeError("CronPattern: Invalid value for "+Y+": "+Q)}else if(Y==="month"&&(Q<0||Q>=12))throw RangeError("CronPattern: Invalid value for "+Y+": "+Q);this[Y][Q]=X}handleRangeWithStepping(Y,Q,X,J){let G=this.extractNth(Y,Q),K=G[0].match(/^(\d+)-(\d+)\/(\d+)$/);if(K===null)throw TypeError("CronPattern: Syntax error, illegal range with stepping: '"+Y+"'");let[,W,Z,H]=K,$=parseInt(W,10)+X,F=parseInt(Z,10)+X,V=parseInt(H,10);if(isNaN($))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(F))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(isNaN(V))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(V===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(V>this[Q].length)throw TypeError("CronPattern: Syntax error, steps cannot be greater than maximum value of part ("+this[Q].length+")");if($>F)throw TypeError("CronPattern: From value is larger than to value: '"+Y+"'");for(let B=$;B<=F;B+=V)this.setPart(Q,B,G[1]||J)}extractNth(Y,Q){let X=Y,J;if(X.includes("#")){if(Q!=="dayOfWeek")throw Error("CronPattern: nth (#) only allowed in day-of-week field");J=X.split("#")[1],X=X.split("#")[0]}return[X,J]}handleRange(Y,Q,X,J){let G=this.extractNth(Y,Q),K=G[0].split("-");if(K.length!==2)throw TypeError("CronPattern: Syntax error, illegal range: '"+Y+"'");let W=parseInt(K[0],10)+X,Z=parseInt(K[1],10)+X;if(isNaN(W))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(Z))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(W>Z)throw TypeError("CronPattern: From value is larger than to value: '"+Y+"'");for(let H=W;H<=Z;H++)this.setPart(Q,H,G[1]||J)}handleStepping(Y,Q,X,J){let G=this.extractNth(Y,Q),K=G[0].split("/");if(K.length!==2)throw TypeError("CronPattern: Syntax error, illegal stepping: '"+Y+"'");K[0]===""&&(K[0]="*");let W=0;K[0]!=="*"&&(W=parseInt(K[0],10)+X);let Z=parseInt(K[1],10);if(isNaN(Z))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(Z===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(Z>this[Q].length)throw TypeError("CronPattern: Syntax error, max steps for part is ("+this[Q].length+")");for(let H=W;H<this[Q].length;H+=Z)this.setPart(Q,H,G[1]||J)}replaceAlphaDays(Y){return Y.replace(/-sun/gi,"-7").replace(/sun/gi,"0").replace(/mon/gi,"1").replace(/tue/gi,"2").replace(/wed/gi,"3").replace(/thu/gi,"4").replace(/fri/gi,"5").replace(/sat/gi,"6")}replaceAlphaMonths(Y){return Y.replace(/jan/gi,"1").replace(/feb/gi,"2").replace(/mar/gi,"3").replace(/apr/gi,"4").replace(/may/gi,"5").replace(/jun/gi,"6").replace(/jul/gi,"7").replace(/aug/gi,"8").replace(/sep/gi,"9").replace(/oct/gi,"10").replace(/nov/gi,"11").replace(/dec/gi,"12")}handleNicknames(Y){let Q=Y.trim().toLowerCase();return Q==="@yearly"||Q==="@annually"?"0 0 1 1 *":Q==="@monthly"?"0 0 1 * *":Q==="@weekly"?"0 0 * * 0":Q==="@daily"?"0 0 * * *":Q==="@hourly"?"0 * * * *":Y}setNthWeekdayOfMonth(Y,Q){if(typeof Q!="number"&&Q==="L")this.dayOfWeek[Y]=this.dayOfWeek[Y]|gL1;else if(Q===mv)this.dayOfWeek[Y]=mv;else if(Q<6&&Q>0)this.dayOfWeek[Y]=this.dayOfWeek[Y]|$o0[Q-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${Q}, Type: ${typeof Q}`)}},Ko0,EF,hW=class Y{tz;ms;second;minute;hour;day;month;year;constructor(Q,X){if(this.tz=X,Q&&Q instanceof Date)if(!isNaN(Q))this.fromDate(Q);else throw TypeError("CronDate: Invalid date passed to CronDate constructor");else if(Q===void 0)this.fromDate(new Date);else if(Q&&typeof Q=="string")this.fromString(Q);else if(Q instanceof Y)this.fromCronDate(Q);else throw TypeError("CronDate: Invalid type ("+typeof Q+") passed to CronDate constructor")}isNthWeekdayOfMonth(Q,X,J,G){let K=new Date(Date.UTC(Q,X,J)).getUTCDay(),W=0;for(let Z=1;Z<=J;Z++)new Date(Date.UTC(Q,X,Z)).getUTCDay()===K&&W++;if(G&mv&&$o0[W-1]&G)return!0;if(G&gL1){let Z=new Date(Date.UTC(Q,X+1,0)).getUTCDate();for(let H=J+1;H<=Z;H++)if(new Date(Date.UTC(Q,X,H)).getUTCDay()===K)return!1;return!0}return!1}fromDate(Q){if(this.tz!==void 0)if(typeof this.tz=="number")this.ms=Q.getUTCMilliseconds(),this.second=Q.getUTCSeconds(),this.minute=Q.getUTCMinutes()+this.tz,this.hour=Q.getUTCHours(),this.day=Q.getUTCDate(),this.month=Q.getUTCMonth(),this.year=Q.getUTCFullYear(),this.apply();else{let X=gJ.toTZ(Q,this.tz);this.ms=Q.getMilliseconds(),this.second=X.s,this.minute=X.i,this.hour=X.h,this.day=X.d,this.month=X.m-1,this.year=X.y}else this.ms=Q.getMilliseconds(),this.second=Q.getSeconds(),this.minute=Q.getMinutes(),this.hour=Q.getHours(),this.day=Q.getDate(),this.month=Q.getMonth(),this.year=Q.getFullYear()}fromCronDate(Q){this.tz=Q.tz,this.year=Q.year,this.month=Q.month,this.day=Q.day,this.hour=Q.hour,this.minute=Q.minute,this.second=Q.second,this.ms=Q.ms}apply(){if(this.month>11||this.day>Ko0[this.month]||this.hour>59||this.minute>59||this.second>59||this.hour<0||this.minute<0||this.second<0){let Q=new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms));return this.ms=Q.getUTCMilliseconds(),this.second=Q.getUTCSeconds(),this.minute=Q.getUTCMinutes(),this.hour=Q.getUTCHours(),this.day=Q.getUTCDate(),this.month=Q.getUTCMonth(),this.year=Q.getUTCFullYear(),!0}else return!1}fromString(Q){if(typeof this.tz=="number"){let X=gJ.fromTZISO(Q);this.ms=X.getUTCMilliseconds(),this.second=X.getUTCSeconds(),this.minute=X.getUTCMinutes(),this.hour=X.getUTCHours(),this.day=X.getUTCDate(),this.month=X.getUTCMonth(),this.year=X.getUTCFullYear(),this.apply()}else return this.fromDate(gJ.fromTZISO(Q,this.tz))}findNext(Q,X,J,G){let K=this[X],W;J.lastDayOfMonth&&(this.month!==1?W=Ko0[this.month]:W=new Date(Date.UTC(this.year,this.month+1,0,0,0,0,0)).getUTCDate());let Z=!J.starDOW&&X=="day"?new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay():void 0;for(let H=this[X]+G;H<J[X].length;H++){let $=J[X][H];if(X==="day"&&J.lastDayOfMonth&&H-G==W&&($=1),X==="day"&&!J.starDOW){let F=J.dayOfWeek[(Z+(H-G-1))%7];if(F&&F&mv)F=this.isNthWeekdayOfMonth(this.year,this.month,H-G,F)?1:0;else if(F)throw Error(`CronDate: Invalid value for dayOfWeek encountered. ${F}`);Q.legacyMode&&!J.starDOM?$=$||F:$=$&&F}if($)return this[X]=H-G,K!==this[X]?2:1}return 3}recurse(Q,X,J){let G=this.findNext(X,EF[J][0],Q,EF[J][2]);if(G>1){let K=J+1;for(;K<EF.length;)this[EF[K][0]]=-EF[K][2],K++;if(G===3)return this[EF[J][1]]++,this[EF[J][0]]=-EF[J][2],this.apply(),this.recurse(Q,X,0);if(this.apply())return this.recurse(Q,X,J-1)}return J+=1,J>=EF.length?this:this.year>=3000?null:this.recurse(Q,X,J)}increment(Q,X,J){return this.second+=X.interval!==void 0&&X.interval>1&&J?X.interval:1,this.ms=0,this.apply(),this.recurse(Q,X,0)}getDate(Q){return Q||this.tz===void 0?new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms):typeof this.tz=="number"?new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute-this.tz,this.second,this.ms)):gJ.fromTZ(gJ.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}},Ho0=30000,Yo,Qo=class{name;options;_states;fn;constructor(Y,Q,X){let J,G;if(uv(Q))G=Q;else if(typeof Q=="object")J=Q;else if(Q!==void 0)throw Error("Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).");if(uv(X))G=X;else if(typeof X=="object")J=X;else if(X!==void 0)throw Error("Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).");if(this.name=J?.name,this.options=Vc6(J),this._states={kill:!1,blocking:!1,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:J?J.maxRuns:void 0,paused:J?J.paused:!1,pattern:new Zo0("* * * * *")},Y&&(Y instanceof Date||typeof Y=="string"&&Y.indexOf(":")>0)?this._states.once=new hW(Y,this.options.timezone||this.options.utcOffset):this._states.pattern=new Zo0(Y,this.options.timezone),this.name){if(Yo.find((K)=>K.name===this.name))throw Error("Cron: Tried to initialize new named job '"+this.name+"', but name already taken.");Yo.push(this)}return G!==void 0&&qc6(G)&&(this.fn=G,this.schedule()),this}nextRun(Y){let Q=this._next(Y);return Q?Q.getDate(!1):null}nextRuns(Y,Q){this._states.maxRuns!==void 0&&Y>this._states.maxRuns&&(Y=this._states.maxRuns);let X=[],J=Q||this._states.currentRun||void 0;for(;Y--&&(J=this.nextRun(J));)X.push(J);return X}getPattern(){return this._states.pattern?this._states.pattern.pattern:void 0}isRunning(){let Y=this.nextRun(this._states.currentRun),Q=!this._states.paused,X=this.fn!==void 0,J=!this._states.kill;return Q&&X&&J&&Y!==null}isStopped(){return this._states.kill}isBusy(){return this._states.blocking}currentRun(){return this._states.currentRun?this._states.currentRun.getDate():null}previousRun(){return this._states.previousRun?this._states.previousRun.getDate():null}msToNext(Y){let Q=this._next(Y);return Q?Y instanceof hW||Y instanceof Date?Q.getTime()-Y.getTime():Q.getTime()-new hW(Y).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let Y=Yo.indexOf(this);Y>=0&&Yo.splice(Y,1)}pause(){return this._states.paused=!0,!this._states.kill}resume(){return this._states.paused=!1,!this._states.kill}schedule(Y){if(Y&&this.fn)throw Error("Cron: It is not allowed to schedule two functions using the same Croner instance.");Y&&(this.fn=Y);let Q=this.msToNext(),X=this.nextRun(this._states.currentRun);return Q==null||isNaN(Q)||X===null?this:(Q>Ho0&&(Q=Ho0),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(X),Q),this._states.currentTimeout&&this.options.unref&&Bc6(this._states.currentTimeout),this)}async _trigger(Y){if(this._states.blocking=!0,this._states.currentRun=new hW(void 0,this.options.timezone||this.options.utcOffset),this.options.catch)try{this.fn!==void 0&&await this.fn(this,this.options.context)}catch(Q){uv(this.options.catch)&&this.options.catch(Q,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new hW(Y,this.options.timezone||this.options.utcOffset),this._states.blocking=!1}async trigger(){await this._trigger()}runsLeft(){return this._states.maxRuns}_checkTrigger(Y){let Q=new Date,X=!this._states.paused&&Q.getTime()>=Y.getTime(),J=this._states.blocking&&this.options.protect;X&&!J?(this._states.maxRuns!==void 0&&this._states.maxRuns--,this._trigger()):X&&J&&uv(this.options.protect)&&setTimeout(()=>this.options.protect(this),0),this.schedule()}_next(Y){let Q=!!(Y||this._states.currentRun),X=!1;!Y&&this.options.startAt&&this.options.interval&&([Y,Q]=this._calculatePreviousRun(Y,Q),X=!Y),Y=new hW(Y,this.options.timezone||this.options.utcOffset),this.options.startAt&&Y&&Y.getTime()<this.options.startAt.getTime()&&(Y=this.options.startAt);let J=this._states.once||new hW(Y,this.options.timezone||this.options.utcOffset);return!X&&J!==this._states.once&&(J=J.increment(this._states.pattern,this.options,Q)),this._states.once&&this._states.once.getTime()<=Y.getTime()||J===null||this._states.maxRuns!==void 0&&this._states.maxRuns<=0||this._states.kill||this.options.stopAt&&J.getTime()>=this.options.stopAt.getTime()?null:J}_calculatePreviousRun(Y,Q){let X=new hW(void 0,this.options.timezone||this.options.utcOffset),J=Y;if(this.options.startAt.getTime()<=X.getTime()){J=this.options.startAt;let G=J.getTime()+this.options.interval*1000;for(;G<=X.getTime();)J=new hW(J,this.options.timezone||this.options.utcOffset).increment(this._states.pattern,this.options,!0),G=J.getTime()+this.options.interval*1000;Q=!0}return J===null&&(J=void 0),[J,Q]}};var uL1=j(()=>{gJ.fromTZISO=(Y,Q,X)=>gJ.fromTZ(Fc6(Y,Q),X);gJ.fromTZ=function(Y,Q){let X=new Date(Date.UTC(Y.y,Y.m-1,Y.d,Y.h,Y.i,Y.s)),J=xL1(Y.tz,X),G=new Date(X.getTime()-J),K=xL1(Y.tz,G);if(K-J===0)return G;{let W=new Date(X.getTime()-K),Z=xL1(Y.tz,W);if(Z-K===0)return W;if(!Q&&Z-K>0)return W;if(Q)throw Error("Invalid date passed to fromTZ()");return G}};gJ.toTZ=function(Y,Q){let X=Y.toLocaleString("en-US",{timeZone:Q}).replace(/[\u202f]/," "),J=new Date(X);return{y:J.getFullYear(),m:J.getMonth()+1,d:J.getDate(),h:J.getHours(),i:J.getMinutes(),s:J.getSeconds(),tz:Q}};gJ.tp=(Y,Q,X,J,G,K,W)=>({y:Y,m:Q,d:X,h:J,i:G,s:K,tz:W});gJ.minitz=gJ;mv=31|gL1,$o0=[1,2,4,8,16],Ko0=[31,28,31,30,31,30,31,31,30,31,30,31],EF=[["month","year",0],["day","month",-1],["hour","day",0],["minute","hour",0],["second","minute",0]];Yo=[]});class lv{localEmit=null;async start(Y){this.localEmit=Y}broadcast(Y,Q){this.localEmit?.(Y,Q)}async stop(){this.localEmit=null}}class qo0{listeners=new Map;totalCount=0;strategy=new lv;started=!1;async start(Y){if(this.started){if(!Y)return;await this.stop()}if(Y)this.strategy=Y;await this.strategy.start((Q,X)=>this.localEmit(Q,X)),this.started=!0}async stop(){if(!this.started)return;await this.strategy.stop(),this.started=!1}add(Y){if(this.totalCount>=Vo0)return console.warn(`[SSEHub] Total connection limit reached (${Vo0})`),null;let Q=this.listeners.get(Y.organizationId);if(!Q)Q=new Map,this.listeners.set(Y.organizationId,Q);if(Q.size>=Fo0)return console.warn(`[SSEHub] Per-org connection limit reached for ${Y.organizationId} (${Fo0})`),null;return Q.set(Y.id,Y),this.totalCount++,Y.id}remove(Y,Q){let X=this.listeners.get(Y);if(!X)return;if(X.delete(Q)){if(this.totalCount--,X.size===0)this.listeners.delete(Y)}}emit(Y,Q){this.strategy.broadcast(Y,Q)}countForOrg(Y){return this.listeners.get(Y)?.size??0}get count(){return this.totalCount}localEmit(Y,Q){let X=this.listeners.get(Y);if(!X||X.size===0)return;for(let J of X.values()){if(J.typePatterns&&!Uc6(Q.type,J.typePatterns))continue;try{J.push(Q)}catch{this.remove(Y,J.id)}}}}function Uc6(Y,Q){for(let X of Q){if(X===Y)return!0;if(X.endsWith(".*")){let J=X.slice(0,-1);if(Y.startsWith(J))return!0}}return!1}function Bo0(Y){return{id:Y.id,type:Y.type,source:Y.source,subject:Y.subject,data:Y.data?Dc6(Y.data):void 0,time:Y.time}}function Dc6(Y){if(typeof Y==="string")try{return JSON.parse(Y)}catch{return Y}return Y}var Fo0=50,Vo0=500,uJ;var Xo=j(()=>{uJ=new qo0});var Jo;var mL1=j(()=>{Jo={pollIntervalMs:5000,batchSize:100,maxAttempts:20,retryDelayMs:1000,maxDelayMs:3600000}});function zc6(Y){return Y.endsWith("_self")}function Oc6(Y){return Y.slice(0,-5)}function Uo0(){return async(Y,Q)=>{try{if(zc6(Y)&&VO1()){let W=Oc6(Y),Z=await PF.create();if(await qc0(Q,{organizationId:W,connectionId:Y,publish:async(F,V,B,U)=>{await Z.eventBus.publish(W,Y,{type:F,subject:V,data:B,deliverAt:U?.deliverAt})},createMCPProxy:async(F)=>{let V=await fL1(F,Z);return{callTool:async(B,U,D)=>{let z=await V.callTool(B,U,D);return{content:z.content,structuredContent:z.structuredContent,isError:z.isError}},close:()=>V.close()}}}))return{success:!0}}let X=await PF.create(),J=await fL1(Y,X),K=await tq1.forClient(TO(J)).ON_EVENTS({events:Q});return{success:K.success,error:K.error,retryAfter:K.retryAfter,results:K.results}}catch(X){let J=X instanceof Error?X.message:String(X);return console.error(`[EventBus] Failed to notify connection ${Y}:`,J),{success:!1,error:J}}}}var Do0=j(()=>{ir();Bv();Yk();CO()});function zo0(Y){return{specversion:"1.0",id:Y.id,source:Y.source,type:Y.type,time:Y.time,subject:Y.subject??void 0,datacontenttype:Y.datacontenttype,dataschema:Y.dataschema??void 0,data:Y.data??void 0}}function Nc6(Y){let Q=new Map;for(let J of Y){let G=J.subscription.connectionId,K=Q.get(G);if(K){if(K.deliveryIds.push(J.delivery.id),!K.seenEventIds.has(J.event.id))K.seenEventIds.add(J.event.id),K.events.push(zo0(J.event))}else Q.set(G,{connectionId:J.subscription.connectionId,deliveryIds:[J.delivery.id],events:[zo0(J.event)],seenEventIds:new Set([J.event.id])})}let X=new Map;for(let[J,G]of Q)X.set(J,{connectionId:G.connectionId,deliveryIds:G.deliveryIds,events:G.events});return X}class lL1{storage;notifySubscriber;running=!1;processing=!1;pendingNotify=!1;config;constructor(Y,Q){this.storage=Y;this.notifySubscriber=Uo0(),this.config={...Jo,...Q}}async start(){if(this.running)return;let Y=await this.storage.resetStuckDeliveries();if(Y>0)console.log(`[EventBus] Reset ${Y} stuck deliveries from previous shutdown`);this.running=!0}stop(){this.running=!1,console.log("[EventBus] Worker stopped")}isRunning(){return this.running}async processNow(){if(!this.running)return;if(this.processing){this.pendingNotify=!0;return}this.processing=!0;try{do this.pendingNotify=!1,await this.processEvents();while(this.pendingNotify)}catch(Y){console.error("[EventBus] Error processing events:",Y)}finally{this.processing=!1}}async processEvents(){let Y=await this.storage.claimPendingDeliveries(this.config.batchSize);if(Y.length===0)return;let Q=Nc6(Y),X=new Set;await Promise.allSettled(Array.from(Q.entries()).map(async([J,G])=>{try{let K=await this.notifySubscriber(G.connectionId,G.events);if(K.results&&Object.keys(K.results).length>0)await this.processPerEventResults(G,K);else if(K.success)await this.storage.markDeliveriesDelivered(G.deliveryIds);else if(K.retryAfter&&K.retryAfter>0)await this.storage.scheduleRetryWithoutAttemptIncrement(G.deliveryIds,K.retryAfter);else await this.storage.markDeliveriesFailed(G.deliveryIds,K.error||"Subscriber returned success=false",this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}catch(K){let W=K instanceof Error?K.message:String(K);console.error(`[EventBus] Failed to notify subscription ${J}:`,W),await this.storage.markDeliveriesFailed(G.deliveryIds,W,this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}for(let K of Y)if(G.deliveryIds.includes(K.delivery.id))X.add(K.event.id)}));for(let J of X)try{await this.storage.updateEventStatus(J);let G=Y.find((K)=>K.event.id===J)?.event;if(G?.cron)await this.scheduleNextCronDelivery(G)}catch(G){console.error(`[EventBus] Failed to update event status ${J}:`,G)}}async processPerEventResults(Y,Q){let X=[],J=new Map,G=[],K=new Map;for(let W=0;W<Y.events.length;W++){let Z=Y.events?.[W];if(!Z)continue;let H=Y.deliveryIds?.[W];if(!H)continue;K.set(Z.id,H)}for(let W of Y.events){let Z=K.get(W.id);if(!Z)continue;let H=Q.results?.[W.id];if(H)if(H.success)X.push(Z);else if(H.retryAfter&&H.retryAfter>0){let $=J.get(H.retryAfter)||[];$.push(Z),J.set(H.retryAfter,$)}else G.push({deliveryId:Z,error:H.error||"Event processing failed"});else if(Q.success)X.push(Z);else if(Q.retryAfter&&Q.retryAfter>0){let $=J.get(Q.retryAfter)||[];$.push(Z),J.set(Q.retryAfter,$)}else G.push({deliveryId:Z,error:Q.error||"Batch processing failed"})}if(X.length>0)await this.storage.markDeliveriesDelivered(X);for(let[W,Z]of J)await this.storage.scheduleRetryWithoutAttemptIncrement(Z,W);if(G.length>0){let W=new Map;for(let{deliveryId:Z,error:H}of G){let $=W.get(H)||[];$.push(Z),W.set(H,$)}for(let[Z,H]of W)await this.storage.markDeliveriesFailed(H,Z,this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}}async scheduleNextCronDelivery(Y){if(!Y.cron)return;try{let X=new Qo(Y.cron).nextRun();if(!X){console.log(`[EventBus] Cron expression for event ${Y.id} has no more runs`);return}let J=X.toISOString(),G=await this.storage.getMatchingSubscriptions(Y);if(G.length===0){console.log(`[EventBus] No subscriptions for cron event ${Y.id}, skipping next delivery`);return}await this.storage.createDeliveries(Y.id,G.map((K)=>K.id),J),console.log(`[EventBus] Scheduled next cron delivery for event ${Y.id} at ${J}`)}catch(Q){console.error(`[EventBus] Failed to schedule next cron delivery for event ${Y.id}:`,Q)}}}var Oo0=j(()=>{uL1();mL1();Do0()});class dL1{storage;worker;notifyStrategy;running=!1;constructor(Y){this.storage=Y.storage,this.notifyStrategy=Y.notifyStrategy,this.worker=new lL1(this.storage,Y.config)}async publish(Y,Q,X){if(X.deliverAt&&X.cron)throw Error("Cannot set both deliverAt and cron. Use one or the other.");let J;if(X.cron){try{let F=new Qo(X.cron).nextRun();if(!F)throw Error("Cron expression does not produce a next run time");J=F.toISOString()}catch($){throw Error(`Invalid cron expression: ${$ instanceof Error?$.message:String($)}`)}let H=await this.storage.findActiveCronEvent(Y,X.type,Q,X.cron);if(H)return H}let G=crypto.randomUUID(),K=new Date().toISOString(),W=await this.storage.publishEvent({id:G,organizationId:Y,type:X.type,source:Q,subject:X.subject,time:K,data:X.data,cron:X.cron});uJ.emit(Y,Bo0(W));let Z=await this.storage.getMatchingSubscriptions(W);if(Z.length>0){let H=X.deliverAt??J;if(await this.storage.createDeliveries(G,Z.map(($)=>$.id),H),this.notifyStrategy&&!H)await this.notifyStrategy.notify(G).catch(($)=>{console.warn("[EventBus] Notify failed (non-critical):",$)})}return W}async subscribe(Y,Q){return this.storage.subscribe({id:crypto.randomUUID(),organizationId:Y,connectionId:Q.connectionId,publisher:Q.publisher,eventType:Q.eventType,filter:Q.filter})}async unsubscribe(Y,Q){return this.storage.unsubscribe(Q,Y)}async listSubscriptions(Y,Q){return this.storage.listSubscriptions(Y,Q)}async getSubscription(Y,Q){return this.storage.getSubscription(Q,Y)}async getEvent(Y,Q){return this.storage.getEvent(Q,Y)}async cancelEvent(Y,Q,X){return this.storage.cancelEvent(Q,Y,X)}async ackEvent(Y,Q,X){return this.storage.ackDelivery(Q,Y,X)}async syncSubscriptions(Y,Q){return this.storage.syncSubscriptions({organizationId:Y,...Q})}async start(){if(this.running)return;if(this.running=!0,await this.worker.start(),this.notifyStrategy)await this.notifyStrategy.start(()=>{this.worker.processNow().catch((Y)=>{console.error("[EventBus] Error processing after notify:",Y)})});await this.worker.processNow().catch((Y)=>{console.error("[EventBus] Error processing pending events on startup:",Y)})}async stop(){if(!this.running)return;if(this.running=!1,this.worker.stop(),this.notifyStrategy)try{await this.notifyStrategy.stop()}catch(Y){console.error("[EventBus] Error stopping notify strategy:",Y)}console.log("[EventBus] Stopped")}isRunning(){return this.running}}var No0=j(()=>{uL1();Xo();Oo0()});class pL1{options;sub=null;onNotify=null;encoder=new TextEncoder;constructor(Y){this.options=Y}async start(Y){let Q=this.options.getConnection();if(!Q||this.sub)return;this.onNotify=Y,this.sub=Q.subscribe("mesh.events.notify"),(async()=>{for await(let X of this.sub)this.onNotify?.()})().catch((X)=>{console.error("[NatsNotify] Subscription error:",X)}),console.log("[NatsNotify] Started, subscribed to","mesh.events.notify")}async stop(){this.sub?.unsubscribe(),this.sub=null,this.onNotify=null,console.log("[NatsNotify] Stopped")}async notify(Y){let Q=this.options.getConnection();if(!Q)return;try{Q.publish("mesh.events.notify",this.encoder.encode(Y))}catch(X){console.warn("[NatsNotify] Publish failed (non-critical):",X)}}}class cL1{options;sub=null;localEmit=null;originId=crypto.randomUUID();encoder=new TextEncoder;constructor(Y){this.options=Y}async start(Y){this.localEmit=Y;let Q=this.options.getConnection();if(!Q||this.sub)return;this.sub=Q.subscribe("mesh.sse.broadcast");let X=new TextDecoder;(async()=>{for await(let J of this.sub)try{let G=JSON.parse(X.decode(J.data));if(typeof G?.originId!=="string"||typeof G?.organizationId!=="string"||typeof G?.event?.id!=="string"||typeof G?.event?.type!=="string")continue;if(G.originId===this.originId)continue;this.localEmit?.(G.organizationId,G.event)}catch{}})().catch((J)=>{console.error("[NatsSSEBroadcast] Subscription error:",J)}),console.log("[NatsSSEBroadcast] Started, subscribed to","mesh.sse.broadcast")}broadcast(Y,Q){this.localEmit?.(Y,Q);let X=this.options.getConnection();if(!X)return;let J={originId:this.originId,organizationId:Y,event:Q};try{X.publish("mesh.sse.broadcast",this.encoder.encode(JSON.stringify(J)))}catch(G){console.warn("[NatsSSEBroadcast] Publish failed (non-critical):",G)}}async stop(){this.sub?.unsubscribe(),this.sub=null,this.localEmit=null,console.log("[NatsSSEBroadcast] Stopped")}}function nL1(...Y){return{async start(Q){await Promise.all(Y.map((X)=>X.start(Q)))},async stop(){await Promise.all(Y.map((Q)=>Q.stop().catch((X)=>{console.error("[NotifyStrategy] Error stopping strategy:",X)})))},async notify(Q){await Promise.all(Y.map((X)=>X.notify(Q).catch((J)=>{console.warn("[NotifyStrategy] Notify failed (non-critical):",J)})))}}}class iL1{intervalMs;timer=null;onNotify=null;constructor(Y){this.intervalMs=Y}async start(Y){if(this.timer)return;this.onNotify=Y,this.scheduleNext(),console.log(`[Polling] Started polling every ${this.intervalMs}ms`)}async stop(){if(this.timer)clearTimeout(this.timer),this.timer=null,console.log("[Polling] Stopped polling");this.onNotify=null}async notify(Y){if(this.onNotify)this.onNotify()}scheduleNext(){this.timer=setTimeout(()=>{if(this.onNotify)this.onNotify();if(this.timer)this.scheduleNext()},this.intervalMs)}}import{sql as Lc6}from"kysely";class aL1{db;pool;listenClient=null;onNotify=null;constructor(Y,Q){this.db=Y;this.pool=Q}async start(Y){if(this.listenClient)return;this.onNotify=Y;try{this.listenClient=await this.pool.connect(),this.listenClient.on("notification",(Q)=>{if(Q.channel===yP&&this.onNotify)this.onNotify()}),this.listenClient.on("error",(Q)=>{console.error("[PostgresNotify] Connection error:",Q),this.cleanup()}),await this.listenClient.query(`LISTEN ${yP}`),console.log("[PostgresNotify] Started LISTEN on",yP)}catch(Q){console.error("[PostgresNotify] Failed to start LISTEN:",Q),this.cleanup()}}async stop(){if(this.listenClient){try{await this.listenClient.query(`UNLISTEN ${yP}`),console.log("[PostgresNotify] Stopped LISTEN on",yP)}catch{}this.cleanup()}}async notify(Y){try{await Lc6`SELECT pg_notify(${yP}, ${Y})`.execute(this.db)}catch(Q){console.warn("[PostgresNotify] Failed to send NOTIFY:",Q)}}cleanup(){if(this.listenClient)this.listenClient.release(),this.listenClient=null;this.onNotify=null}}var yP="mesh_events";var Lo0=()=>{};function Mc6(Y){let Q=process.env.NOTIFY_STRATEGY;if(Q==="nats"||Q==="postgres"||Q==="polling")return Q;if(process.env.NATS_URL)return"nats";if(Y.type==="postgres")return"postgres";return"polling"}function Mo0(Y,Q,X){let J=Wo0(Y.db),G=Q?.pollIntervalMs??Jo.pollIntervalMs,K=Mc6(Y),W=new iL1(G),Z=process.env.NATS_URL,H;switch(K){case"nats":{if(!Z)throw Error("[EventBus] NOTIFY_STRATEGY=nats requires NATS_URL to be set");let F=(()=>{try{return new URL(Z).host}catch{return"unknown"}})();if(!X){console.warn(`[EventBus] NATS unavailable (${F}), falling back to polling`),H=W;break}console.log(`[EventBus] Using NATS notify strategy (${F})`),H=nL1(W,new pL1({getConnection:()=>X.getConnection()}));break}case"postgres":{if(Y.type!=="postgres"){console.warn("[EventBus] NOTIFY_STRATEGY=postgres requires a PostgreSQL database, falling back to polling"),H=W;break}console.log("[EventBus] Using PostgreSQL LISTEN/NOTIFY strategy"),H=nL1(W,new aL1(Y.db,Y.pool));break}case"polling":default:console.log("[EventBus] Using polling notify strategy"),H=W}let $=Z&&X?new cL1({getConnection:()=>X.getConnection()}):new lv;if(uJ.start($).catch((F)=>{console.error("[SSEHub] Failed to start broadcast strategy:",F)}),Z&&X)console.log("[SSEHub] Using NATS SSE broadcast (cross-pod)");else console.log("[SSEHub] Using local SSE broadcast (single-pod)");return new dL1({storage:J,config:Q,notifyStrategy:H})}var Go=j(()=>{No0();mL1();Lo0();Xo();Xo()});var wo0;var Ao0=j(()=>{wo0={google:{name:"Google",icon:"https://assets.decocache.com/webdraw/eb7480aa-a68b-4ce4-98ff-36aa121762a7/google.svg"},github:{name:"GitHub",icon:"https://assets.decocache.com/webdraw/5f999dcb-c8a6-4572-948c-9996ef1d502f/github.svg"},microsoft:{name:"Microsoft",icon:"https://assets.decocache.com/mcp/aa6f6e1a-6526-4bca-99cc-82e2ec38b0e4/microsoft.png"}}});var Po0,Eo0;var To0=j(()=>{JK();wP();Ao0();Po0=new VQ;Po0.get("/config",async(Y)=>{try{let Q=Object.keys(p9.socialProviders??{}),X=Q.length>0,J=Q.map((W)=>({name:W,icon:wo0[W].icon})),G=process.env.UNSAFE_ALLOW_STDIO_TRANSPORT==="true",K={emailAndPassword:{enabled:p9.emailAndPassword?.enabled??!1},magicLink:{enabled:p9.magicLinkConfig?.enabled??!1},resetPassword:{enabled:KL1},socialProviders:{enabled:X,providers:J},sso:p9.ssoConfig?{enabled:!0,providerId:p9.ssoConfig.providerId}:{enabled:!1},stdioEnabled:G};return Y.json({success:!0,config:K})}catch(Q){let X=Q instanceof Error?Q.message:"Failed to load auth config";return Y.json({success:!1,error:X},500)}});Eo0=Po0});function Co0(Y){let{toolOutputMap:Q}=Y;return fJ({description:"The input is a string. Dont make assumptions about its format; prefer using regexes and string manipulation to extract the desired information. You may call this tool multiple times to extract the desired information.",inputExamples:[{input:{tool_call_id:"tool_call_id_1",code:"export default (input) => { return input.match(/[a-z]/g); }"}},{input:{tool_call_id:"tool_call_id_2",code:"export default (input) => { return input.split(' ').map(word => word.length); }"}}],inputSchema:l8(q.object({tool_call_id:q.string(),code:q.string().min(1).describe("JavaScript code to transform the tool output. The code must be an ES module: `export default (input) => { ... }`")})),execute:async({tool_call_id:X,code:J})=>{if(!Q.has(X))throw Error(`Tool output not found for tool call id: ${X}`);let G=Q.get(X),K=await MO1({input:G,code:J,timeoutMs:5000}),W=rL1({return:K.returnValue});if(W>4000)throw Error(`Tool call ${X} output is too long to display (${W} tokens), reduce or truncate the output`);return{result:K.returnValue,error:K.error,consoleLogs:K.consoleLogs}}})}function Pc6(Y){if(!Y)return 0;let Q=Y.match(Ac6)?.length??0,X=Y.length-Q;return Math.ceil(X/wc6)+Math.ceil(Q*1.5)}function rL1(Y){let Q=typeof Y==="string"?Y:JSON.stringify(Y);return Pc6(Q)}var wc6=4,Ac6;var oL1=j(()=>{sZ();n1();Nr();Ac6=/[\u3000-\u303f\u3040-\u309f\u30a0-\u30ff\u4e00-\u9fff\u3400-\u4dbf\uf900-\ufaff]/g});function Wo(Y,Q){if(Y==="yolo")return!1;if(Y==="none")return!0;return Q!==!0}function Zo(Y){let Q=Y.get("meshContext").organization;if(!Q)throw Error("Organization context is required");if((Q.slug??Q.id)!==Y.req.param("org"))throw Error("Organization mismatch");return Q}async function dv(Y,Q,X,J="none",G){let K=!G?.disableOutputTruncation,Z=(await Y.listTools()).tools.map((H)=>{let{name:$,title:F,description:V,inputSchema:B,annotations:U,_meta:D}=H;return[$,fJ({title:F??$,description:V,inputSchema:SW(B),outputSchema:void 0,needsApproval:Wo(J,U?.readOnlyHint),execute:async(z,L)=>{let w=performance.now();try{return await Y.callTool({name:H.name,arguments:z},EK,{signal:L.abortSignal,timeout:cr0})}finally{if(X){let E=performance.now()-w;X.write({type:"data-tool-metadata",id:L.toolCallId,data:{_meta:D,annotations:U,latencyMs:E}})}}},toModelOutput:async({output:z,toolCallId:L})=>{if(K){let E=rL1(z.structuredContent??z.content);if(E>4000)return Q.set(L,JSON.stringify(z.structuredContent??z.content)),{type:"text",value:`Tool call ${L} output is too long to display (${E} tokens), use the read_tool_output tool`}}if(z.isError)return{type:"error-text",value:z.content.map((T)=>T.type==="text"?T.text:null).filter(Boolean).join(`
1540
+ `)||"Unknown error"};if("structuredContent"in z)return{type:"json",value:z.structuredContent};return{type:"text",value:z.content.map((E)=>{if(E.type==="text")return E.text;return JSON.stringify(E)}).join(`
1541
1541
  `)}}})]});return Object.fromEntries(Z)}async function sL1(Y){let Q=Y.get("meshContext"),X=Q.auth?.user?.id;if(!X)throw new XJ(401,{message:"Unauthorized"});let J=Zo(Y),G=Y.req.param("threadId");if(/[.*>\s]/.test(G))throw new XJ(400,{message:"Invalid thread ID"});let K=await Q.storage.threads.get(G);if(!K||K.organization_id!==J.id)throw new XJ(404,{message:"Thread not found"});if(K.created_by!==X)throw new XJ(403,{message:"Not authorized"});return{ctx:Q,organization:J,thread:K,threadId:G,userId:X}}var Ko=j(()=>{kQ();sZ();jP();CO();oL1()});function Ro0(Y,Q,X){let{organization:J,needsApproval:G}=Q;return fJ({description:Cc6,inputSchema:l8(Ec6),outputSchema:l8(Tc6),needsApproval:G,execute:async({search_term:K},W)=>{let Z=performance.now();try{let $=(await X.storage.virtualMcps.list(J.id)).filter((V)=>V.status==="active");if(K&&K.trim().length>0){let V=K.toLowerCase();$=$.filter((B)=>{let U=B.title.toLowerCase().includes(V),D=B.description?.toLowerCase().includes(V)??!1;return U||D})}return{agents:$.map((V)=>({agent_id:V.id,name:V.title,purpose:V.description,capabilities:[]}))}}finally{let H=performance.now()-Z;Y.write({type:"data-tool-metadata",id:W.toolCallId,data:{annotations:Rc6,latencyMs:H}})}}})}var Ec6,Tc6,Cc6="Search for agents configured in the organization. Returns agent metadata including purpose and capabilities. Use this to discover specialized agents before delegating work with subtask_run.",Rc6;var Io0=j(()=>{sZ();n1();Ec6=q.object({search_term:q.string().optional().describe("Optional search term to filter agents by name, title, or description. Leave empty to return all available agents.")}),Tc6=q.object({agents:q.array(q.object({agent_id:q.string().describe("Unique identifier for the agent"),name:q.string().describe("Human-readable agent name"),purpose:q.string().nullable().describe("What the agent is designed to do"),capabilities:q.array(q.string()).describe("List of capabilities the agent has")}))}),Rc6={readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}});function kc6(Y){let Q=`You are a focused subtask agent delegated a specific task by a parent agent.
1542
1542
 
1543
1543
  ## Before Acting: Assess the Task
@@ -1568,7 +1568,7 @@ ${Y}`;return Q}function jo0(Y,Q,X){let{modelProvider:J,organization:G,models:K,n
1568
1568
  ${W}`)}return{stream:uc6(K),response:{headers:Object.fromEntries(K.headers?.entries()??[])}}}}}}};var eL1=()=>{};async function ro0(Y,Q){let X=Nv.forClient(TO(Y)),J=pv(X);return{thinkingModel:J.languageModel(Q.thinking.id),codingModel:Q.coding?J.languageModel(Q.coding.id):void 0,fastModel:Q.fast?J.languageModel(Q.fast.id):void 0,connectionId:Q.connectionId}}var oo0=j(()=>{Ar();eL1();CO()});var lc6,dc6,pc6,YM1,cc6,so0;var to0=j(()=>{n1();_P();lc6=q.looseObject({id:q.string().optional(),role:q.enum(["user","assistant","system"]),parts:q.array(q.record(q.string(),q.unknown())),metadata:q.unknown().optional()}),dc6=q.object({windowSize:q.number().default(sr),thread_id:q.string()}),pc6=q.enum(["openai","anthropic","google","xai","deepseek","openrouter","openai-compatible"]).optional().nullable(),YM1=q.object({id:q.string(),capabilities:q.object({vision:q.boolean().optional(),text:q.boolean().optional(),tools:q.boolean().optional()}).optional(),provider:pc6,limits:q.object({contextWindow:q.number().optional(),maxOutputTokens:q.number().optional()}).optional()}),cc6=q.object({connectionId:q.string(),thinking:YM1.describe("Backbone model for the agentic loop"),coding:YM1.optional().describe("Good coding model"),fast:YM1.optional().describe("Cheap model for simple tasks")}).loose(),so0=q.object({messages:q.array(lc6).min(1).refine((Y)=>Y.filter((Q)=>Q.role!=="system").length===1,{message:"Expected exactly one non-system message"}),memory:dc6.optional(),models:cc6,agent:q.object({id:q.string(),mode:q.enum(["passthrough","smart_tool_selection","code_execution"])}).loose(),stream:q.boolean().optional(),temperature:q.number().default(0.5),thread_id:q.string().optional(),toolApprovalLevel:q.enum(["none","readonly","yolo"]).default("none")})});function eo0(Y,Q=[]){if(Y==="stop")return"completed";if(Y==="tool-calls"){let X=Q.some((G)=>G.type==="tool-user_ask"&&G.state==="input-available"),J=Q.some((G)=>G.state==="approval-requested");return X||J?"requires_action":"completed"}return"failed"}async function Ys0(Y){let{abortSignal:Q,model:X,userMessage:J}=Y,G=new AbortController,K=()=>G.abort();Q.addEventListener("abort",K,{once:!0});let W=setTimeout(()=>{G.abort()},nc6);try{let H=(await oA({model:X,system:Yo0,messages:[{role:"user",content:J}],maxOutputTokens:60,temperature:0.2,abortSignal:G.signal})).text.trim();return(H.split(`
1569
1569
  `)[0]??H).replace(/^["']|["']$/g,"").replace(/^(Title:|title:)\s*/i,"").replace(/[.!?]$/,"").slice(0,60).trim()}catch(Z){let H=Z;if(H.name==="AbortError")console.warn("[decopilot:title] Title generation aborted (timeout or parent abort)");else console.error("[decopilot:title] \u274C Failed to generate title:",H.message);return null}finally{clearTimeout(W),Q.removeEventListener("abort",K)}}var nc6=2500;var Qs0=j(()=>{sZ();_P()});async function ic6(Y){let Q=Zo(Y),X=await Y.req.json(),J=so0.safeParse(X);if(!J.success)throw new XJ(400,{message:J.error.message});let{messages:G,...K}=J.data,W=G,{systemMessages:Z,requestMessage:H}=fo0(W);return{organization:Q,systemMessages:Z,requestMessage:H,...K}}function QM1(Y){let{cancelBroadcast:Q,streamBuffer:X,runRegistry:J}=Y,G=new VQ;return G.get("/:org/decopilot/allowed-models",async(K)=>{try{let W=K.get("meshContext"),Z=Zo(K),H=W.auth.user?.role,$=await tL1(W.db,Z.id,H);return K.json(co0($))}catch(W){if(console.error("[decopilot:allowed-models] Error",W),W instanceof XJ)return K.json({error:W.message},W.status);return K.json({error:W instanceof Error?W.message:"Internal error"},500)}}),G.post("/:org/decopilot/stream",async(K)=>{let W,Z;try{let H=K.get("meshContext"),{organization:$,models:F,agent:V,systemMessages:B,requestMessage:U,temperature:D,memory:z,thread_id:L,toolApprovalLevel:w}=await ic6(K),E=H.auth?.user?.id;if(!E)throw new XJ(401,{message:"User ID is required"});let T=await tL1(H.db,$.id,H.auth.user?.role);if(!po0(T,F.connectionId,F.thinking.id))throw new XJ(403,{message:"Model not allowed for your role"});let C=z?.windowSize??sr,P=L??z?.thread_id,[R,k,_]=await Promise.all([H.storage.virtualMcps.findById(V.id,$.id),H.storage.connections.findById(F.connectionId,$.id),uo0(H.storage.threads,{organization_id:$.id,thread_id:P,userId:E,defaultWindowSize:C})]),f=async(...L1)=>{let S1=Date.now(),m1=[...new Map(L1.filter(Boolean).map((Q0)=>[Q0.id,Q0])).values()].map((Q0,C1)=>({...Q0,thread_id:_.thread.id,created_at:new Date(S1+C1).toISOString(),updated_at:new Date(S1+C1).toISOString()}));if(m1.length===0)return;await _.save(m1).catch((Q0)=>{console.error("[decopilot:stream] Error saving messages",Q0)})},b=(L1)=>{H.storage.threads.update(_.thread.id,{status:L1}).catch((m1)=>{console.error("[decopilot:stream] Error updating thread status",m1)});let S1=L1==="completed"?"completed":"failed";J.finishRun(_.thread.id,S1,(m1)=>X.purge(m1)),uJ.emit($.id,xT(_.thread.id,L1)),uJ.emit($.id,Rx(_.thread.id,L1))};if(W=()=>b("failed"),!k)throw Error("Model connection not found");if(!R)throw Error("Agent not found");await H.storage.threads.update(_.thread.id,{status:"in_progress"}),uJ.emit($.id,xT(_.thread.id,"in_progress"));let r=J.startRun(_.thread.id,$.id,E).abortController.signal;X.purge(_.thread.id),await f(U),r.addEventListener("abort",()=>{Z?.(),W()});let m=V.mode!=="passthrough",h=F.thinking.limits?.maxOutputTokens??or,n=!1,$1=0,Q1=null,N1=await bo0(_,U,[bL1(),...B],C),j1=new Map,D1=rU1({originalMessages:N1,execute:async({writer:L1})=>{let[S1,m1,Q0]=await Promise.all([y5(k,H,!1),DB(R,H,"passthrough"),m?DB(R,H,V.mode):Promise.resolve(null)]);Z=()=>{S1.close().catch(()=>{}),m1.close().catch(()=>{}),Q0?.close().catch(()=>{})};let C1=zO(S1,F.connectionId,k,H,{superUser:!1}),A1=await ro0(C1,F),s1=m1.getInstructions(),B4=s1?.trim()?N1.map((h4)=>h4.id==="decopilot-system"?bL1(s1):h4):N1,K4=await dv(m1,j1,L1,w),q0=Q0?await dv(Q0,j1,L1,w):{},f1=await _o0(L1,{modelProvider:A1,organization:$,models:F,toolApprovalLevel:w,toolOutputMap:j1},H),w1={...K4,...q0,...f1},i1=Q0?[...Object.keys(q0),...Object.keys(f1)]:void 0,{systemMessages:R1,messages:y1,originalMessages:A0}=await ho0(B4,{windowSize:C,models:F,tools:w1});if(lo0(F,A0),_.thread.title===tr)Ys0({abortSignal:r,model:A1.fastModel??A1.thinkingModel,userMessage:JSON.stringify(y1[0]?.content)}).then(async(h4)=>{if(!h4)return;if(await H.storage.threads.update(_.thread.id,{title:h4}).catch((_0)=>{console.error("[decopilot:stream] Error updating thread title",_0)}),!n)L1.write({type:"data-thread-title",data:{title:h4},transient:!0})});let G0=null,x4,k6=sA({model:A1.thinkingModel,system:R1,messages:y1,tools:w1,activeTools:i1,temperature:D,maxOutputTokens:h,abortSignal:r,stopWhen:XB(sr0),onError:async(h4)=>{throw console.error("[decopilot:stream] Error",h4),h4}}).toUIMessageStream({originalMessages:A0,generateMessageId:or0,messageMetadata:({part:h4})=>{if(h4.type==="start")return{agent:{id:V.id??null,mode:V.mode},models:{connectionId:F.connectionId,thinking:F.thinking},created_at:new Date,thread_id:_.thread.id};if(h4.type==="reasoning-start"){if(G0===null)G0=new Date;return{reasoning_start_at:G0}}if(h4.type==="reasoning-end")return{reasoning_end_at:new Date};if(h4.type==="finish-step"){x4=h4.providerMetadata;return}if(h4.type==="finish"){let _0=F.thinking.provider,x1=h4.totalUsage,P0=x4??h4.providerMetadata,i4=x1?{inputTokens:x1.inputTokens??0,outputTokens:x1.outputTokens??0,reasoningTokens:x1.reasoningTokens??void 0,totalTokens:x1.totalTokens??0,providerMetadata:L91(_0&&P0?{...P0,[_0]:{...P0[_0]??{},reasoning_details:void 0}}:P0)}:void 0;return{...i4&&{usage:i4}}}return}});L1.merge(X.relay(k6,_.thread.id,r))},onFinish:async({responseMessage:L1,finishReason:S1})=>{if(n=!0,Z?.(),Q1)await Q1;if(await f(L1),r.aborted)return;let m1=eo0(S1,L1?.parts);b(m1)},onStepFinish:({responseMessage:L1})=>{if($1++,uJ.emit($.id,Cx(_.thread.id,$1)),$1%5===0)Q1=f(L1).finally(()=>{Q1=null})},onError:(L1)=>{if(n=!0,Z?.(),r.aborted)return L1 instanceof Error?L1.message:String(L1);if(console.error("[decopilot] stream error:",L1),_.thread.id)W();return L1 instanceof Error?L1.message:String(L1)}});return Ha({stream:D1,consumeSseStream:Rk})}catch(H){if(Z?.(),W)W();if(console.error("[decopilot:stream] Error",H),H instanceof XJ)return K.json({error:H.message},H.status);if(H instanceof Error&&H.name==="AbortError")return console.warn("[decopilot:stream] Aborted",{error:H.message}),K.json({error:"Request aborted"},400);return console.error("[decopilot:stream] Failed",{error:H instanceof Error?H.message:JSON.stringify(H),stack:H instanceof Error?H.stack:void 0}),K.json({error:H instanceof Error?H.message:JSON.stringify(H)},500)}}),G.post("/:org/decopilot/cancel/:threadId",async(K)=>{let{threadId:W}=await sL1(K);if(J.cancelLocal(W))return K.json({cancelled:!0});return Q.broadcast(W),K.json({cancelled:!0,async:!0},202)}),G.get("/:org/decopilot/attach/:threadId",async(K)=>{try{let{threadId:W}=await sL1(K),Z=J.getRun(W);if(!Z||Z.status!=="running")return K.body(null,204);let H=await X.createReplayStream(W);if(!H)return K.body(null,204);let $=rU1({execute:async({writer:F})=>{let V=H.getReader();try{while(!0){let{done:B,value:U}=await V.read();if(B)break;F.write(U)}}finally{V.releaseLock()}}});return Ha({stream:$,consumeSseStream:Rk})}catch(W){if(W instanceof XJ)throw W;return console.error("[decopilot:attach] Error",W),K.body(null,500)}}),G}var Xs0=j(()=>{CP();Cv();QY();sZ();JK();jP();yo0();_P();xo0();Ko();mo0();do0();Go();no0();oo0();to0();Qs0()});var Js0=j(()=>{Xs0()});var Ho,Gs0;var Ws0=j(()=>{JK();Rr();Ho=new VQ;Ho.post("/connections/:connectionId/oauth-token",async(Y)=>{let Q=Y.get("meshContext"),X=Y.req.param("connectionId");if(!(Q.auth.user?.id??Q.auth.apiKey?.userId??null))return Y.json({error:"Unauthorized"},401);if(!await Q.storage.connections.findById(X,Q.organization?.id))return Y.json({error:"Connection not found"},404);let K=await Y.req.json();if(!K.accessToken)return Y.json({error:"accessToken is required"},400);if(K.tokenEndpoint){let F;try{F=new URL(K.tokenEndpoint)}catch{return Y.json({error:"tokenEndpoint must be a valid URL"},400)}if(F.protocol!=="http:"&&F.protocol!=="https:")return Y.json({error:"tokenEndpoint must be an http(s) URL"},400)}let W=K.expiresIn?new Date(Date.now()+K.expiresIn*1000):null,Z=new NF(Q.db,Q.vault),H={connectionId:X,accessToken:K.accessToken,refreshToken:K.refreshToken??null,scope:K.scope??null,expiresAt:W,clientId:K.clientId??null,clientSecret:K.clientSecret??null,tokenEndpoint:K.tokenEndpoint??null},$=await Z.upsert(H);return Y.json({success:!0,expiresAt:$.expiresAt})});Ho.delete("/connections/:connectionId/oauth-token",async(Y)=>{let Q=Y.get("meshContext"),X=Y.req.param("connectionId");if(!(Q.auth.user?.id??Q.auth.apiKey?.userId??null))return Y.json({error:"Unauthorized"},401);return await new NF(Q.db,Q.vault).delete(X),Y.json({success:!0})});Ho.get("/connections/:connectionId/oauth-token/status",async(Y)=>{let Q=Y.get("meshContext"),X=Y.req.param("connectionId");if(!(Q.auth.user?.id??Q.auth.apiKey?.userId??null))return Y.json({error:"Unauthorized"},401);let G=new NF(Q.db,Q.vault),K=await G.get(X);if(!K)return Y.json({hasToken:!1,isExpired:!0,canRefresh:!1});let W=G.isExpired(K),Z=!!K.refreshToken&&!!K.tokenEndpoint;return Y.json({hasToken:!0,isExpired:W,canRefresh:Z,expiresAt:K.expiresAt})});Gs0=Ho});var XM1=class{writer;encoder;writable;abortSubscribers=[];responseReadable;aborted=!1;closed=!1;constructor(Y,Q){this.writable=Y,this.writer=Y.getWriter(),this.encoder=new TextEncoder;let X=Q.getReader();this.abortSubscribers.push(async()=>{await X.cancel()}),this.responseReadable=new ReadableStream({async pull(J){let{done:G,value:K}=await X.read();G?J.close():J.enqueue(K)},cancel:()=>{this.abort()}})}async write(Y){try{if(typeof Y==="string")Y=this.encoder.encode(Y);await this.writer.write(Y)}catch{}return this}async writeln(Y){return await this.write(Y+`
1570
1570
  `),this}sleep(Y){return new Promise((Q)=>setTimeout(Q,Y))}async close(){try{await this.writer.close()}catch{}this.closed=!0}async pipe(Y){this.writer.releaseLock(),await Y.pipeTo(this.writable,{preventClose:!0}),this.writer=this.writable.getWriter()}onAbort(Y){this.abortSubscribers.push(Y)}abort(){if(!this.aborted)this.aborted=!0,this.abortSubscribers.forEach((Y)=>Y())}};var JM1=()=>{};var $o=()=>{let Y=typeof Bun<"u"?Bun.version:void 0;if(Y===void 0)return!1;let Q=Y.startsWith("1.1")||Y.startsWith("1.0")||Y.startsWith("0.");return $o=()=>Q,Q};var GM1=()=>{};var Zs0=j(()=>{JM1();GM1()});var Ks0,ac6=async(Y,Q,X)=>{try{await Q(Y)}catch(J){if(J instanceof Error&&X)await X(J,Y),await Y.writeSSE({event:"error",data:J.message});else console.error(J)}finally{Y.close()}},rc6,cv=(Y,Q,X)=>{let{readable:J,writable:G}=new TransformStream,K=new Ks0(G,J);if($o())Y.req.raw.signal.addEventListener("abort",()=>{if(!K.closed)K.abort()});return rc6.set(K.responseReadable,Y),Y.header("Transfer-Encoding","chunked"),Y.header("Content-Type","text/event-stream"),Y.header("Cache-Control","no-cache"),Y.header("Connection","keep-alive"),ac6(K,Q,X),Y.newResponse(K.responseReadable)};var Hs0=j(()=>{BL1();JM1();GM1();Ks0=class extends XM1{constructor(Y,Q){super(Y,Q)}async writeSSE(Y){let X=(await _v(Y.data,xr.Stringify,!1,{})).split(/\r\n|\r|\n/).map((G)=>{return`data: ${G}`}).join(`
1571
- `),J=[Y.event&&`event: ${Y.event}`,X,Y.id&&`id: ${Y.id}`,Y.retry&&`retry: ${Y.retry}`].filter(Boolean).join(`
1571
+ `);for(let G of["event","id","retry"])if(Y[G]&&/[\r\n]/.test(Y[G]))throw Error(`${G} must not contain "\\r" or "\\n"`);let J=[Y.event&&`event: ${Y.event}`,X,Y.id&&`id: ${Y.id}`,Y.retry&&`retry: ${Y.retry}`].filter(Boolean).join(`
1572
1572
  `)+`
1573
1573
 
1574
1574
  `;await this.write(J)}},rc6=new WeakMap});var $s0=j(()=>{gr();Fo()});var Fo=j(()=>{Zs0();Hs0();$s0()});function J3(Y,Q="invalid_request_error",X=null,J=null){return{error:{message:Y,type:Q,param:X,code:J}}}function Wn6(Y){let Q=Y.indexOf(":");if(Q===-1)return null;let X=Y.substring(0,Q),J=Y.substring(Q+1);if(!X||!J)return null;return{connectionId:X,modelId:J}}function Zn6(Y,Q,X){try{return JSON.parse(Y)}catch{throw new qs0(`Invalid JSON in tool call arguments for function '${X}' (tool_call_id: ${Q}): ${Y}`)}}function Kn6(Y){let Q={};for(let X of Y)if(X.role==="assistant"&&X.tool_calls)for(let J of X.tool_calls)Q[J.id]=J.function.name;return Y.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((G)=>{if(G.type==="text")return{type:"text",text:G.text};return{type:"image",image:G.image_url.url}})};case"assistant":if(X.tool_calls&&X.tool_calls.length>0)return{role:"assistant",content:X.tool_calls.map((G)=>({type:"tool-call",toolCallId:G.id,toolName:G.function.name,input:Zn6(G.function.arguments,G.id,G.function.name)}))};return{role:"assistant",content:X.content??""};case"tool":let J=Q[X.tool_call_id]??"unknown";return{role:"tool",content:[{type:"tool-result",toolCallId:X.tool_call_id,toolName:J,output:{type:"text",value:X.content}}]}}})}function Hn6(Y){let Q=Y.map((X)=>{let J=X.function.parameters?SW(X.function.parameters):SW({type:"object",properties:{}});return[X.function.name,fJ({description:X.function.description,inputSchema:J})]});return Object.fromEntries(Q)}function $n6(Y){if(!Y)return;return{openai:{response_format:Y}}}function Fn6(){return`chatcmpl-${crypto.randomUUID().replace(/-/g,"").substring(0,29)}`}async function Vn6(Y,Q,X){let J=await Y.storage.connections.findById(X);if(!J)return null;if(J.organization_id!==Q)return null;if(J.status!=="active")return null;return J}async function qn6(Y,Q){await new LF(Y.authInstance,Y.auth.user?.id??Y.auth.apiKey?.userId,"*",Y.boundAuth,Y.auth.user?.role,Q).check("*")}function Fs0(Y,Q,X,J,G,K){let W={model:Y,messages:Q,tools:X,temperature:J.temperature,maxTokens:J.max_tokens,topP:J.top_p,frequencyPenalty:J.frequency_penalty,presencePenalty:J.presence_penalty,stopSequences:J.stop?Array.isArray(J.stop)?J.stop:[J.stop]:void 0,abortSignal:K};return G?{...W,providerOptions:G}:W}function Vs0(Y){if(Y==="tool-calls")return"tool_calls";if(Y==="length")return"length";return"stop"}var sc6,tc6,ec6,Yn6,Qn6,Xn6,Jn6,Gn6,qs0,Bs0,Us0;var Ds0=j(()=>{Ar();CP();CO();sZ();JK();Fo();n1();Pv();eL1();sc6=q.object({type:q.literal("function"),function:q.object({name:q.string(),description:q.string().optional(),parameters:q.record(q.string(),q.unknown()).optional()})}),tc6=q.object({id:q.string(),type:q.literal("function"),function:q.object({name:q.string(),arguments:q.string()})}),ec6=q.discriminatedUnion("role",[q.object({role:q.literal("system"),content:q.string(),name:q.string().optional()}),q.object({role:q.literal("user"),content:q.union([q.string(),q.array(q.union([q.object({type:q.literal("text"),text:q.string()}),q.object({type:q.literal("image_url"),image_url:q.object({url:q.string(),detail:q.string().optional()})})]))]),name:q.string().optional()}),q.object({role:q.literal("assistant"),content:q.string().nullable().optional(),name:q.string().optional(),tool_calls:q.array(tc6).optional()}),q.object({role:q.literal("tool"),content:q.string(),tool_call_id:q.string()})]),Yn6=q.object({type:q.literal("text")}),Qn6=q.object({type:q.literal("json_object")}),Xn6=q.object({type:q.literal("json_schema"),json_schema:q.object({name:q.string(),description:q.string().optional(),schema:q.record(q.string(),q.unknown()),strict:q.boolean().optional()})}),Jn6=q.union([Yn6,Qn6,Xn6]),Gn6=q.object({model:q.string().describe("Format: connection_id:model_id"),messages:q.array(ec6),stream:q.boolean().optional().default(!1),temperature:q.number().min(0).max(2).optional(),max_tokens:q.number().positive().optional(),top_p:q.number().min(0).max(1).optional(),frequency_penalty:q.number().min(-2).max(2).optional(),presence_penalty:q.number().min(-2).max(2).optional(),stop:q.union([q.string(),q.array(q.string())]).optional(),tools:q.array(sc6).optional(),tool_choice:q.union([q.literal("auto"),q.literal("none"),q.literal("required"),q.object({type:q.literal("function"),function:q.object({name:q.string()})})]).optional(),response_format:Jn6.optional(),user:q.string().optional()});qs0=class qs0 extends Error{constructor(Y){super(Y);this.name="MessageConversionError"}};Bs0=new VQ;Bs0.post("/:org/v1/chat/completions",async(Y)=>{let Q=Y.get("meshContext"),X=Y.req.param("org");try{if(!Q.auth.apiKey?.id)return Y.json(J3("API key authentication required. Provide a valid API key via Authorization header.","authentication_error"),401);if(!Q.organization)return Y.json(J3("Organization context is required. Ensure your API key has organization metadata.","invalid_request_error","organization"),400);if((Q.organization.slug??Q.organization.id)!==X)return Y.json(J3("Organization mismatch. The API key's organization does not match the requested organization.","invalid_request_error","organization"),403);let J=await Y.req.json(),G=Gn6.safeParse(J);if(!G.success){let z=G.error.issues[0]??{message:"Invalid request",path:[]};return Y.json(J3(`Invalid request: ${z.message}`,"invalid_request_error",z.path.length>0?z.path.join("."):null),400)}let K=G.data,W=Wn6(K.model);if(!W)return Y.json(J3("Invalid model format. Expected 'connection_id:model_id' (e.g., 'conn_abc123:gpt-4')","invalid_request_error","model"),400);let{connectionId:Z,modelId:H}=W;try{await qn6(Q,Z)}catch{return Y.json(J3(`Access denied to connection: ${Z}`,"permission_error","model"),403)}let $=await Vn6(Q,Q.organization.id,Z);if(!$)return Y.json(J3(`Connection not found or inactive: ${Z}`,"invalid_request_error","model"),404);let F=Kn6(K.messages),V=K.tools?Hn6(K.tools):void 0,B=$n6(K.response_format),U=Fn6(),D=Math.floor(Date.now()/1000);if(K.stream)return cv(Y,async(z)=>{let L=await y5($,Q,!1),w=zO(L,Z,$,Q,{superUser:!1}),E=Nv.forClient(TO(w)),T=pv(E).languageModel(H),C=Fs0(T,F,V,K,B,Y.req.raw.signal);try{let P=sA(C),R=!1,k=0;for await(let _ of P.fullStream){if(!R&&(_.type==="text-delta"||_.type==="tool-call"))await z.writeSSE({data:JSON.stringify({id:U,object:"chat.completion.chunk",created:D,model:K.model,choices:[{index:0,delta:{role:"assistant",content:""},finish_reason:null}]})}),R=!0;if(_.type==="text-delta")await z.writeSSE({data:JSON.stringify({id:U,object:"chat.completion.chunk",created:D,model:K.model,choices:[{index:0,delta:{content:_.text},finish_reason:null}]})});else if(_.type==="tool-call"){let f=k++;await z.writeSSE({data:JSON.stringify({id:U,object:"chat.completion.chunk",created:D,model:K.model,choices:[{index:0,delta:{tool_calls:[{index:f,id:_.toolCallId,type:"function",function:{name:_.toolName,arguments:JSON.stringify(_.input)}}]},finish_reason:null}]})})}else if(_.type==="finish")await z.writeSSE({data:JSON.stringify({id:U,object:"chat.completion.chunk",created:D,model:K.model,choices:[{index:0,delta:{},finish_reason:Vs0(_.finishReason)}],usage:_.totalUsage?{prompt_tokens:_.totalUsage.inputTokens??0,completion_tokens:_.totalUsage.outputTokens??0,total_tokens:_.totalUsage.totalTokens??0}:void 0})})}await z.writeSSE({data:"[DONE]"})}catch(P){let R=P;console.error("[openai-compat:stream] Error:",R.message),await z.writeSSE({data:JSON.stringify({error:{message:R.message,type:"server_error"}})})}});else{let z=await y5($,Q,!1),L=Nv.forClient(TO(z)),w=pv(L).languageModel(H),E=Fs0(w,F,V,K,B,Y.req.raw.signal),T=await oA(E),C={role:"assistant",content:T.text||null};if(T.toolCalls&&T.toolCalls.length>0)C.tool_calls=T.toolCalls.map((P)=>({id:P.toolCallId,type:"function",function:{name:P.toolName,arguments:JSON.stringify("input"in P?P.input:{})}})),C.content=null;return Y.json({id:U,object:"chat.completion",created:D,model:K.model,choices:[{index:0,message:C,finish_reason:Vs0(T.finishReason)}],usage:{prompt_tokens:T.usage?.inputTokens??0,completion_tokens:T.usage?.outputTokens??0,total_tokens:T.usage?.totalTokens??0}})}}catch(J){let G=J;if(G.name==="AbortError")return Y.json(J3("Request aborted","invalid_request_error"),400);if(G.name==="MessageConversionError")return Y.json(J3(G.message,"invalid_request_error","messages"),400);return console.error("[openai-compat] Error:",G.message,G.stack),Y.json(J3(G.message,"server_error"),500)}});Us0=Bs0});var zs0,Os0;var Ns0=j(()=>{JK();WI();zs0=new VQ;zs0.get("/",(Y)=>{let Q={theme:yn1()};return Y.json({success:!0,config:Q})});Os0=zs0});var Ls0,Ms0;var ws0=j(()=>{JK();Qk();GL1();Ls0=new VQ;Ls0.all("/",async(Y)=>{let Q=await JL1(Y.get("meshContext")),X=new i$({enableJsonResponse:Y.req.raw.headers.get("Accept")?.includes("application/json")??!1});return await Q.connect(X),X.handleRequest(Y.req.raw)});Ms0=Ls0});function As0(Y){return Y===nv.HEALTH||Y===nv.METRICS||Y.startsWith(fP.WELL_KNOWN)}function Un6(Y){return Y.startsWith(fP.API)}function Dn6(Y){return Y==="/mcp"||Y.startsWith(fP.MCP)}function zn6(Y){return Y.startsWith(fP.OAUTH_PROXY)}function On6(Y){return Bn6.test(Y)}function Nn6(Y){return Y.startsWith(fP.ORG)}function Ps0(Y){return Un6(Y)||Dn6(Y)||zn6(Y)||Nn6(Y)||As0(Y)}function Es0(Y){return Y==="/"||Y.startsWith(fP.API_AUTH)||As0(Y)||On6(Y)}var nv,fP,Bn6;var WM1=j(()=>{nv={HEALTH:"/health",METRICS:"/metrics"},fP={API:"/api/",API_AUTH:"/api/auth/",MCP:"/mcp/",OAUTH_PROXY:"/oauth-proxy/",WELL_KNOWN:"/.well-known",ORG:"/org/"},Bn6=/\.(html|css|js|ico|svg|png|jpg|jpeg|gif|webp|woff|woff2)$/});class ZM1{onCancel=null;async start(Y){this.onCancel=Y}broadcast(Y){this.onCancel?.(Y)}async stop(){this.onCancel=null}}var qQ=I((Ts0)=>{Object.defineProperty(Ts0,"__esModule",{value:!0});Ts0.TD=Ts0.TE=Ts0.Empty=void 0;Ts0.encode=Mn6;Ts0.decode=wn6;Ts0.Empty=new Uint8Array(0);Ts0.TE=new TextEncoder;Ts0.TD=new TextDecoder;function Ln6(...Y){let Q=0;for(let G=0;G<Y.length;G++)Q+=Y[G].length;let X=new Uint8Array(Q),J=0;for(let G=0;G<Y.length;G++)X.set(Y[G],J),J+=Y[G].length;return X}function Mn6(...Y){let Q=[];for(let X=0;X<Y.length;X++)Q.push(Ts0.TE.encode(Y[X]));if(Q.length===0)return Ts0.Empty;if(Q.length===1)return Q[0];return Ln6(...Q)}function wn6(Y){if(!Y||Y.length===0)return"";return Ts0.TD.decode(Y)}});var G3=I((vs0)=>{Object.defineProperty(vs0,"__esModule",{value:!0});vs0.nuid=vs0.Nuid=void 0;var Is0="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",HM1=36,Vo=12,En6=10,js0=3656158440062976,Ss0=33,Tn6=333,ks0=Vo+En6;function Cn6(Y){for(let Q=0;Q<Y.length;Q++)Y[Q]=Math.floor(Math.random()*255)}function Rn6(Y){var Q;if((Q=globalThis===null||globalThis===void 0?void 0:globalThis.crypto)===null||Q===void 0?void 0:Q.getRandomValues)globalThis.crypto.getRandomValues(Y);else Cn6(Y)}class $M1{constructor(){this.buf=new Uint8Array(ks0),this.inited=!1}init(){this.inited=!0,this.setPre(),this.initSeqAndInc(),this.fillSeq()}initSeqAndInc(){this.seq=Math.floor(Math.random()*js0),this.inc=Math.floor(Math.random()*(Tn6-Ss0)+Ss0)}setPre(){let Y=new Uint8Array(Vo);Rn6(Y);for(let Q=0;Q<Vo;Q++){let X=Y[Q]%HM1;this.buf[Q]=Is0.charCodeAt(X)}}fillSeq(){let Y=this.seq;for(let Q=ks0-1;Q>=Vo;Q--)this.buf[Q]=Is0.charCodeAt(Y%HM1),Y=Math.floor(Y/HM1)}next(){if(!this.inited)this.init();if(this.seq+=this.inc,this.seq>js0)this.setPre(),this.initSeqAndInc();return this.fillSeq(),String.fromCharCode.apply(String,this.buf)}reset(){this.init()}}vs0.Nuid=$M1;vs0.nuid=new $M1});var E9=I((W8)=>{var jn6=W8&&W8.__awaiter||function(Y,Q,X,J){function G(K){return K instanceof X?K:new X(function(W){W(K)})}return new(X||(X=Promise))(function(K,W){function Z(F){try{$(J.next(F))}catch(V){W(V)}}function H(F){try{$(J.throw(F))}catch(V){W(V)}}function $(F){F.done?K(F.value):G(F.value).then(Z,H)}$((J=J.apply(Y,Q||[])).next())})};Object.defineProperty(W8,"__esModule",{value:!0});W8.ServiceVerb=W8.DEFAULT_HOST=W8.DEFAULT_PORT=W8.ServiceError=W8.ServiceErrorCodeHeader=W8.ServiceErrorHeader=W8.ServiceResponseType=W8.RequestStrategy=W8.Match=W8.NatsError=W8.Messages=W8.ErrorCode=W8.DebugEvents=W8.Events=void 0;W8.isNatsError=kn6;W8.syncIterator=_n6;W8.createInbox=yn6;var Sn6=G3(),ys0;(function(Y){Y.Disconnect="disconnect",Y.Reconnect="reconnect",Y.Update="update",Y.LDM="ldm",Y.Error="error"})(ys0||(W8.Events=ys0={}));var fs0;(function(Y){Y.Reconnecting="reconnecting",Y.PingTimer="pingTimer",Y.StaleConnection="staleConnection",Y.ClientInitiatedReconnect="client initiated reconnect"})(fs0||(W8.DebugEvents=fs0={}));var GK;(function(Y){Y.ApiError="BAD API",Y.BadAuthentication="BAD_AUTHENTICATION",Y.BadCreds="BAD_CREDS",Y.BadHeader="BAD_HEADER",Y.BadJson="BAD_JSON",Y.BadPayload="BAD_PAYLOAD",Y.BadSubject="BAD_SUBJECT",Y.Cancelled="CANCELLED",Y.ConnectionClosed="CONNECTION_CLOSED",Y.ConnectionDraining="CONNECTION_DRAINING",Y.ConnectionRefused="CONNECTION_REFUSED",Y.ConnectionTimeout="CONNECTION_TIMEOUT",Y.Disconnect="DISCONNECT",Y.InvalidOption="INVALID_OPTION",Y.InvalidPayload="INVALID_PAYLOAD",Y.MaxPayloadExceeded="MAX_PAYLOAD_EXCEEDED",Y.NoResponders="503",Y.NotFunction="NOT_FUNC",Y.RequestError="REQUEST_ERROR",Y.ServerOptionNotAvailable="SERVER_OPT_NA",Y.SubClosed="SUB_CLOSED",Y.SubDraining="SUB_DRAINING",Y.Timeout="TIMEOUT",Y.Tls="TLS",Y.Unknown="UNKNOWN_ERROR",Y.WssRequired="WSS_REQUIRED",Y.JetStreamInvalidAck="JESTREAM_INVALID_ACK",Y.JetStream404NoMessages="404",Y.JetStream408RequestTimeout="408",Y.JetStream409MaxAckPendingExceeded="409",Y.JetStream409="409",Y.JetStreamNotEnabled="503",Y.JetStreamIdleHeartBeat="IDLE_HEARTBEAT",Y.AuthorizationViolation="AUTHORIZATION_VIOLATION",Y.AuthenticationExpired="AUTHENTICATION_EXPIRED",Y.ProtocolError="NATS_PROTOCOL_ERR",Y.PermissionsViolation="PERMISSIONS_VIOLATION",Y.AuthenticationTimeout="AUTHENTICATION_TIMEOUT",Y.AccountExpired="ACCOUNT_EXPIRED"})(GK||(W8.ErrorCode=GK={}));function kn6(Y){return typeof Y.code==="string"}class Bo{constructor(){this.messages=new Map,this.messages.set(GK.InvalidPayload,"Invalid payload type - payloads can be 'binary', 'string', or 'json'"),this.messages.set(GK.BadJson,"Bad JSON"),this.messages.set(GK.WssRequired,"TLS is required, therefore a secure websocket connection is also required")}static getMessage(Y){return vn6.getMessage(Y)}getMessage(Y){return this.messages.get(Y)||Y}}W8.Messages=Bo;var vn6=new Bo;class FM1 extends Error{constructor(Y,Q,X){super(Y);this.name="NatsError",this.message=Y,this.code=Q,this.chainedError=X}static errorForCode(Y,Q){let X=Bo.getMessage(Y);return new FM1(X,Y,Q)}isAuthError(){return this.code===GK.AuthenticationExpired||this.code===GK.AuthorizationViolation||this.code===GK.AccountExpired}isAuthTimeout(){return this.code===GK.AuthenticationTimeout}isPermissionError(){return this.code===GK.PermissionsViolation}isProtocolError(){return this.code===GK.ProtocolError}isJetStreamError(){return this.api_error!==void 0}jsError(){return this.api_error?this.api_error:null}}W8.NatsError=FM1;var bs0;(function(Y){Y[Y.Exact=0]="Exact",Y[Y.CanonicalMIME=1]="CanonicalMIME",Y[Y.IgnoreCase=2]="IgnoreCase"})(bs0||(W8.Match=bs0={}));var hs0;(function(Y){Y.Timer="timer",Y.Count="count",Y.JitterTimer="jitterTimer",Y.SentinelMsg="sentinelMsg"})(hs0||(W8.RequestStrategy=hs0={}));function _n6(Y){let Q=Y[Symbol.asyncIterator]();return{next(){return jn6(this,void 0,void 0,function*(){let X=yield Q.next();if(X.done)return Promise.resolve(null);return Promise.resolve(X.value)})}}}var xs0;(function(Y){Y.STATS="io.nats.micro.v1.stats_response",Y.INFO="io.nats.micro.v1.info_response",Y.PING="io.nats.micro.v1.ping_response"})(xs0||(W8.ServiceResponseType=xs0={}));W8.ServiceErrorHeader="Nats-Service-Error";W8.ServiceErrorCodeHeader="Nats-Service-Error-Code";class qo extends Error{constructor(Y,Q){super(Q);this.code=Y}static isServiceError(Y){return qo.toServiceError(Y)!==null}static toServiceError(Y){var Q,X;let J=((Q=Y===null||Y===void 0?void 0:Y.headers)===null||Q===void 0?void 0:Q.get(W8.ServiceErrorCodeHeader))||"";if(J!==""){let G=parseInt(J)||400,K=((X=Y===null||Y===void 0?void 0:Y.headers)===null||X===void 0?void 0:X.get(W8.ServiceErrorHeader))||"";return new qo(G,K.length?K:J)}return null}}W8.ServiceError=qo;function yn6(Y=""){if(Y=Y||"_INBOX",typeof Y!=="string")throw Error("prefix must be a string");return Y.split(".").forEach((Q)=>{if(Q==="*"||Q===">")throw Error(`inbox prefixes cannot have wildcards '${Y}'`)}),`${Y}.${Sn6.nuid.next()}`}W8.DEFAULT_PORT=4222;W8.DEFAULT_HOST="127.0.0.1";var gs0;(function(Y){Y.PING="PING",Y.STATS="STATS",Y.INFO="INFO"})(gs0||(W8.ServiceVerb=gs0={}))});var BQ=I((CY)=>{var fn6=CY&&CY.__awaiter||function(Y,Q,X,J){function G(K){return K instanceof X?K:new X(function(W){W(K)})}return new(X||(X=Promise))(function(K,W){function Z(F){try{$(J.next(F))}catch(V){W(V)}}function H(F){try{$(J.throw(F))}catch(V){W(V)}}function $(F){F.done?K(F.value):G(F.value).then(Z,H)}$((J=J.apply(Y,Q||[])).next())})},bn6=CY&&CY.__asyncValues||function(Y){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var Q=Y[Symbol.asyncIterator],X;return Q?Q.call(Y):(Y=typeof __values==="function"?__values(Y):Y[Symbol.iterator](),X={},J("next"),J("throw"),J("return"),X[Symbol.asyncIterator]=function(){return this},X);function J(K){X[K]=Y[K]&&function(W){return new Promise(function(Z,H){W=Y[K](W),G(Z,H,W.done,W.value)})}}function G(K,W,Z,H){Promise.resolve(H).then(function($){K({value:$,done:Z})},W)}};Object.defineProperty(CY,"__esModule",{value:!0});CY.SimpleMutex=CY.Perf=void 0;CY.extend=xn6;CY.render=gn6;CY.timeout=un6;CY.delay=mn6;CY.deadline=ln6;CY.deferred=VM1;CY.debugDeferred=dn6;CY.shuffle=pn6;CY.collect=cn6;CY.jitter=ls0;CY.backoffWithMax=nn6;CY.backoff=ds0;CY.nanos=in6;CY.millis=an6;var hn6=qQ(),Uo=E9();function xn6(Y,...Q){for(let X=0;X<Q.length;X++){let J=Q[X];Object.keys(J).forEach(function(G){Y[G]=J[G]})}return Y}function gn6(Y){return hn6.TD.decode(Y).replace(/\n/g,"\u240A").replace(/\r/g,"\u240D")}function un6(Y,Q=!0){let X=Q?Uo.NatsError.errorForCode(Uo.ErrorCode.Timeout):null,J,G,K=new Promise((W,Z)=>{J={cancel:()=>{if(G)clearTimeout(G)}},G=setTimeout(()=>{if(X===null)Z(Uo.NatsError.errorForCode(Uo.ErrorCode.Timeout));else Z(X)},Y)});return Object.assign(K,J)}function mn6(Y=0){let Q,X=new Promise((J)=>{let G=setTimeout(()=>{J()},Y);Q={cancel:()=>{if(G)clearTimeout(G)}}});return Object.assign(X,Q)}function ln6(Y,Q=1000){let X=Error("deadline exceeded"),J=VM1(),G=setTimeout(()=>J.reject(X),Q);return Promise.race([Y,J]).finally(()=>clearTimeout(G))}function VM1(){let Y={},Q=new Promise((X,J)=>{Y={resolve:X,reject:J}});return Object.assign(Q,Y)}function dn6(){let Y={},Q=new Promise((X,J)=>{Y={resolve:(G)=>{console.trace("resolve",G),X(G)},reject:(G)=>{console.trace("reject"),J(G)}}});return Object.assign(Q,Y)}function pn6(Y){for(let Q=Y.length-1;Q>0;Q--){let X=Math.floor(Math.random()*(Q+1));[Y[Q],Y[X]]=[Y[X],Y[Q]]}return Y}function cn6(Y){return fn6(this,void 0,void 0,function*(){var Q,X,J,G,K,W,Z;let H=[];try{for(Q=!0,X=bn6(Y);J=yield X.next(),G=J.done,!G;Q=!0){Z=J.value,Q=!1;let $=Z;H.push($)}}catch($){K={error:$}}finally{try{if(!Q&&!G&&(W=X.return))yield W.call(X)}finally{if(K)throw K.error}}return H})}class us0{constructor(){this.timers=new Map,this.measures=new Map}mark(Y){this.timers.set(Y,performance.now())}measure(Y,Q,X){let J=this.timers.get(Q);if(J===void 0)throw Error(`${Q} is not defined`);let G=this.timers.get(X);if(G===void 0)throw Error(`${X} is not defined`);this.measures.set(Y,G-J)}getEntries(){let Y=[];return this.measures.forEach((Q,X)=>{Y.push({name:X,duration:Q})}),Y}}CY.Perf=us0;class ms0{constructor(Y=1){this.max=Y,this.current=0,this.waiting=[]}lock(){if(this.current++,this.current<=this.max)return Promise.resolve();let Y=VM1();return this.waiting.push(Y),Y}unlock(){this.current--;let Y=this.waiting.pop();Y===null||Y===void 0||Y.resolve()}}CY.SimpleMutex=ms0;function ls0(Y){if(Y===0)return 0;return Math.floor(Y/2+Math.random()*Y)}function nn6(Y=30000){let Q=[Y];while(!0){let X=Math.floor(Y/2);if(X<100){Q.unshift(0);break}Q.unshift(X),Y=X}return ds0(Q)}function ds0(Y=[0,250,250,500,500,3000,5000]){if(!Array.isArray(Y))Y=[0,250,250,500,500,3000,5000];let Q=Y.length-1;return{backoff(X){return ls0(X>Q?Y[Q]:Y[X])}}}function in6(Y){return Y*1e6}function an6(Y){return Math.floor(Y/1e6)}});var bP=I((ns0)=>{Object.defineProperty(ns0,"__esModule",{value:!0});ns0.DataBuffer=void 0;var ps0=qQ();class cs0{constructor(){this.buffers=[],this.byteLength=0}static concat(...Y){let Q=0;for(let G=0;G<Y.length;G++)Q+=Y[G].length;let X=new Uint8Array(Q),J=0;for(let G=0;G<Y.length;G++)X.set(Y[G],J),J+=Y[G].length;return X}static fromAscii(Y){if(!Y)Y="";return ps0.TE.encode(Y)}static toAscii(Y){return ps0.TD.decode(Y)}reset(){this.buffers.length=0,this.byteLength=0}pack(){if(this.buffers.length>1){let Y=new Uint8Array(this.byteLength),Q=0;for(let X=0;X<this.buffers.length;X++)Y.set(this.buffers[X],Q),Q+=this.buffers[X].length;this.buffers.length=0,this.buffers.push(Y)}}shift(){if(this.buffers.length){let Y=this.buffers.shift();if(Y)return this.byteLength-=Y.length,Y}return new Uint8Array(0)}drain(Y){if(this.buffers.length){this.pack();let Q=this.buffers.pop();if(Q){let X=this.byteLength;if(Y===void 0||Y>X)Y=X;let J=Q.subarray(0,Y);if(X>Y)this.buffers.push(Q.subarray(Y));return this.byteLength=X-Y,J}}return new Uint8Array(0)}fill(Y,...Q){if(Y)this.buffers.push(Y),this.byteLength+=Y.length;for(let X=0;X<Q.length;X++)if(Q[X]&&Q[X].length)this.buffers.push(Q[X]),this.byteLength+=Q[X].length}peek(){if(this.buffers.length)return this.pack(),this.buffers[0];return new Uint8Array(0)}size(){return this.byteLength}length(){return this.buffers.length}}ns0.DataBuffer=cs0});var hP=I((rs0)=>{Object.defineProperty(rs0,"__esModule",{value:!0});rs0.LF=rs0.CR=rs0.CRLF=rs0.CR_LF_LEN=rs0.CR_LF=void 0;rs0.setTransportFactory=tn6;rs0.defaultPort=en6;rs0.getUrlParseFn=Yi6;rs0.newTransport=Qi6;rs0.getResolveFn=Xi6;rs0.protoLen=as0;rs0.extractProtocolMessage=Ji6;var rn6=qQ(),on6=E9(),sn6=bP(),L7;function tn6(Y){L7=Y}function en6(){return L7!==void 0&&L7.defaultPort!==void 0?L7.defaultPort:on6.DEFAULT_PORT}function Yi6(){return L7!==void 0&&L7.urlParseFn?L7.urlParseFn:void 0}function Qi6(){if(!L7||typeof L7.factory!=="function")throw Error("transport fn is not set");return L7.factory()}function Xi6(){return L7!==void 0&&L7.dnsResolveFn?L7.dnsResolveFn:void 0}rs0.CR_LF=`\r