decocms 2.162.1 → 2.162.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/assets/{AlertCircle-7lB7fro0.js → AlertCircle-CLSQ0NLi.js} +1 -1
- package/dist/client/assets/{AlignLeft-CWbftioK.js → AlignLeft-DGT5YesK.js} +1 -1
- package/dist/client/assets/{ArrowDown-Ce-Md5NR.js → ArrowDown-BeNMpJ4E.js} +1 -1
- package/dist/client/assets/{ArrowLeft-DNGwlp4M.js → ArrowLeft-ZgtBxTyN.js} +1 -1
- package/dist/client/assets/{ArrowUp-B9ucqKIV.js → ArrowUp-WkRPF3Cl.js} +1 -1
- package/dist/client/assets/{Check-Cvo-Mj0S.js → Check-D30Nw_2C.js} +1 -1
- package/dist/client/assets/{CheckCircle-BhnUN_-o.js → CheckCircle-4PmUxEXj.js} +1 -1
- package/dist/client/assets/{CheckDone01-Dh2K_VwC.js → CheckDone01-BYS-dKbQ.js} +1 -1
- package/dist/client/assets/{CheckVerified02-B23tFeT2.js → CheckVerified02-C_5D8neO.js} +1 -1
- package/dist/client/assets/{ChevronDown-DYWNve60.js → ChevronDown-C7zTxlHE.js} +1 -1
- package/dist/client/assets/{ChevronLeft-CIJS6SFa.js → ChevronLeft-Ov3NE9c_.js} +1 -1
- package/dist/client/assets/{ChevronRight-B4xXvXUl.js → ChevronRight-BJe7e-X2.js} +1 -1
- package/dist/client/assets/{Clock-Di0Vpv60.js → Clock--mEiDXe5.js} +1 -1
- package/dist/client/assets/{Code01-CeoOPe4L.js → Code01-BOUu51ck.js} +1 -1
- package/dist/client/assets/{Container-BvytClvz.js → Container-BXYdiT-J.js} +1 -1
- package/dist/client/assets/{Copy01-DEyL4hmF.js → Copy01-xLxETA4z.js} +1 -1
- package/dist/client/assets/{Dataflow03-BwgEkxHj.js → Dataflow03-FtQ0Yhj_.js} +1 -1
- package/dist/client/assets/{DotsHorizontal-BdKjLiyh.js → DotsHorizontal-Dprv0d9t.js} +1 -1
- package/dist/client/assets/{DotsVertical-BOqBGvRn.js → DotsVertical-C9TpfjSq.js} +1 -1
- package/dist/client/assets/{Download01-D8lTpA1-.js → Download01-TaBKKGTy.js} +1 -1
- package/dist/client/assets/{Edit01-olXvAtAZ.js → Edit01-BE5Wu5ID.js} +1 -1
- package/dist/client/assets/{Edit05-vNRWQV-M.js → Edit05-CHAqfRrN.js} +1 -1
- package/dist/client/assets/{Eye-DQ2cNQ7_.js → Eye-CmzbjCht.js} +1 -1
- package/dist/client/assets/{File02-o3tqw3TU.js → File02-DDGW2KdF.js} +1 -1
- package/dist/client/assets/{File06-CHaNuqmq.js → File06-u0e892jj.js} +1 -1
- package/dist/client/assets/{FilterLines-hoXV8gL3.js → FilterLines-peoUm3Kp.js} +1 -1
- package/dist/client/assets/{Globe01-DGfi10DG.js → Globe01-CttWHoLh.js} +1 -1
- package/dist/client/assets/{Globe02-2YlWazS5.js → Globe02-BaK8gLi7.js} +1 -1
- package/dist/client/assets/{Grid01-41ZWwZ8C.js → Grid01-MfVmgqVA.js} +1 -1
- package/dist/client/assets/{Hash02-CY2safPs.js → Hash02-BBdDXKgB.js} +1 -1
- package/dist/client/assets/{Home02-3xprgDGx.js → Home02-CD_MJrmZ.js} +1 -1
- package/dist/client/assets/{Image01-D8nsgOa4.js → Image01-NW_uhHHO.js} +1 -1
- package/dist/client/assets/{Inbox01-DreXa4ow.js → Inbox01-DUegC4zX.js} +1 -1
- package/dist/client/assets/{InfoCircle-DWkOumoB.js → InfoCircle-BdKgGvOW.js} +1 -1
- package/dist/client/assets/{Key01-DsUMZZb4.js → Key01-VhvVpwde.js} +1 -1
- package/dist/client/assets/{LayersTwo01-CozGeYpA.js → LayersTwo01-DY3gWhYo.js} +1 -1
- package/dist/client/assets/{LayoutLeft-BxnBHF6O.js → LayoutLeft-CTT2u70-.js} +1 -1
- package/dist/client/assets/{Link01-BW7OJP9H.js → Link01-Bm8fkbw8.js} +1 -1
- package/dist/client/assets/{LinkExternal01-B9scdF6U.js → LinkExternal01-D38J8WFf.js} +1 -1
- package/dist/client/assets/{List-BWlMAKKi.js → List-DBox7Fud.js} +1 -1
- package/dist/client/assets/{Loading01-DwU5xHXm.js → Loading01-DoI38kJv.js} +1 -1
- package/dist/client/assets/{Lock01-Culpb3mN.js → Lock01-BpzLUKPy.js} +1 -1
- package/dist/client/assets/{Play-DuD9KGGY.js → Play-Cff6s-Do.js} +1 -1
- package/dist/client/assets/{Plus-Dhm20gcZ.js → Plus-vjPXrbll.js} +1 -1
- package/dist/client/assets/{RefreshCcw01-CKrNRsn6.js → RefreshCcw01-C1dtrtd7.js} +1 -1
- package/dist/client/assets/{Save01-CSAj2bS1.js → Save01-DrnHDSfN.js} +1 -1
- package/dist/client/assets/{SearchMd-DwqVVEmk.js → SearchMd-BpeHWO8y.js} +1 -1
- package/dist/client/assets/{Settings01-DL_2jKIF.js → Settings01-C_OWZaLW.js} +1 -1
- package/dist/client/assets/{Shield01-BNl_AxVr.js → Shield01-Blnh5_zF.js} +1 -1
- package/dist/client/assets/{Terminal-BxC2jtAF.js → Terminal-CUOLHPPn.js} +1 -1
- package/dist/client/assets/{Trash01-CleP0qGT.js → Trash01-Bfnjcg6w.js} +1 -1
- package/dist/client/assets/{Upload01-Bpm7zuzQ.js → Upload01-DA4ZJJnb.js} +1 -1
- package/dist/client/assets/{Users03-BKRGqc64.js → Users03-CiI7Y2pI.js} +1 -1
- package/dist/client/assets/{X-BkXzJkvJ.js → X-LrH2dki2.js} +1 -1
- package/dist/client/assets/{XCircle-CQ0cwRmR.js → XCircle-KlbMEvQq.js} +1 -1
- package/dist/client/assets/{XClose-d8Jjie9z.js → XClose-T4dQr9IP.js} +1 -1
- package/dist/client/assets/{Zap-BTobxj-V.js → Zap-Cx7CJpzQ.js} +1 -1
- package/dist/client/assets/{agent-connections-preview-DAX-YxCn.js → agent-connections-preview-99IZ2JVi.js} +1 -1
- package/dist/client/assets/{agent-detail-Dd9g04cA.js → agent-detail-CQafIKIf.js} +1 -1
- package/dist/client/assets/{agents-BFg1anO6.js → agents-BBhRTRP7.js} +1 -1
- package/dist/client/assets/{alert-dialog-CR2Y_gWg.js → alert-dialog-ZI_d17Kf.js} +1 -1
- package/dist/client/assets/{auth-catchall-3qDVsVQ3.js → auth-catchall-B_kUtzsk.js} +1 -1
- package/dist/client/assets/{avatar-D_V-3wap.js → avatar-DMHAVN2G.js} +1 -1
- package/dist/client/assets/{badge-BsrlHJ_x.js → badge-ChDtoe7k.js} +1 -1
- package/dist/client/assets/{binder-B2J3jrRf.js → binder-BSp18fmP.js} +1 -1
- package/dist/client/assets/{breadcrumb-oFROyAn_.js → breadcrumb-DBcowLTl.js} +1 -1
- package/dist/client/assets/{card-EygHFK51.js → card-ChLHZaFH.js} +1 -1
- package/dist/client/assets/{chart-Bmnx76NN.js → chart-DOQ1KDh7.js} +1 -1
- package/dist/client/assets/{checkbox-CvzFKjZ3.js → checkbox-D_aK0Mdh.js} +1 -1
- package/dist/client/assets/{circle-alert-jB_R9VIQ.js → circle-alert-BHkFRl9i.js} +1 -1
- package/dist/client/assets/{collapsible-lu3Iy-S0.js → collapsible-CtdNMvGE.js} +1 -1
- package/dist/client/assets/{collection-detail-Bt1GArvb.js → collection-detail-CmmN6I8A.js} +1 -1
- package/dist/client/assets/{collection-display-button-YC_aXzYK.js → collection-display-button-Bv7DhR9w.js} +1 -1
- package/dist/client/assets/{collection-search-BdCpnSfc.js → collection-search-DnArRJMW.js} +1 -1
- package/dist/client/assets/{collection-tab-C2v1k0qS.js → collection-tab-CC0q_OnK.js} +1 -1
- package/dist/client/assets/{collection-table-wrapper-DhJA7hQ9.js → collection-table-wrapper-CEwU2e2W.js} +1 -1
- package/dist/client/assets/{collection-tabs-CioUgcWn.js → collection-tabs-CZLvOfkH.js} +1 -1
- package/dist/client/assets/{command-Dr9ELOIm.js → command-DLB128Pb.js} +1 -1
- package/dist/client/assets/{connect-DvWhgY7R.js → connect-CI9IzyBL.js} +1 -1
- package/dist/client/assets/{connection-card-uFTSOaWH.js → connection-card-ByscPAIj.js} +1 -1
- package/dist/client/assets/{connection-detail-C1eD5ISP.js → connection-detail-uL7h2miw.js} +1 -1
- package/dist/client/assets/{connection-status-CUgTWSPZ.js → connection-status-BLpLQzSg.js} +1 -1
- package/dist/client/assets/{connections-Da_AzXLe.js → connections-DMFM3gUy.js} +1 -1
- package/dist/client/assets/constants-CUyJcaN8.js +1 -0
- package/dist/client/assets/{constants-CJKNcVO0.js → constants-OpiJAgZI.js} +1 -1
- package/dist/client/assets/{context-iluKjV89.js → context-7Kd5bp6X.js} +1 -1
- package/dist/client/assets/{create-organization-dialog-BiPFmP0t.js → create-organization-dialog-BneQWVKs.js} +1 -1
- package/dist/client/assets/{create-project-dialog-CZRaXDOF.js → create-project-dialog-DcUDVcZj.js} +1 -1
- package/dist/client/assets/{danger-CS7q8T7g.js → danger-DbvicEY-.js} +1 -1
- package/dist/client/assets/{danger-zone-Arlo0D2G.js → danger-zone-CsqhCbO1.js} +1 -1
- package/dist/client/assets/{decopilot-events-C1rn4nxl.js → decopilot-events-BAhRgxLp.js} +1 -1
- package/dist/client/assets/{dependencies-C1u7sWiw.js → dependencies-Ds_GH7yM.js} +1 -1
- package/dist/client/assets/{dialog-De2kjp-7.js → dialog-DXMtLbOt.js} +1 -1
- package/dist/client/assets/{dropdown-menu-CBXVfpi8.js → dropdown-menu-Bv41z45k.js} +1 -1
- package/dist/client/assets/{dynamic-plugin-layout-D7aWriCh.js → dynamic-plugin-layout-CA3PBJG1.js} +1 -1
- package/dist/client/assets/{editable-task-title-Dw21XHnW.js → editable-task-title-BUHTazHh.js} +1 -1
- package/dist/client/assets/{empty-state-CCFoZ2I0.js → empty-state-D2gP2QeK.js} +1 -1
- package/dist/client/assets/{env-vars-editor-QlY_vLwo.js → env-vars-editor-DXU1-vnq.js} +1 -1
- package/dist/client/assets/{extract-connection-data-Drlb76Zi.js → extract-connection-data-CYsp_UMA.js} +1 -1
- package/dist/client/assets/{file-browser-CgJoRnNX.js → file-browser-DkGVcDoL.js} +2 -2
- package/dist/client/assets/{form-Do17Zmtj.js → form-Ndm9rRCe.js} +1 -1
- package/dist/client/assets/{general-BNTVDu8S.js → general-opBI2uJ9.js} +1 -1
- package/dist/client/assets/{grid-view-C25yp3XL.js → grid-view-CSu6RixN.js} +1 -1
- package/dist/client/assets/{home-CugPrCQk.js → home-B8vvircu.js} +1 -1
- package/dist/client/assets/{icon-picker-BRAO_6f7.js → icon-picker-8kNIyP1o.js} +1 -1
- package/dist/client/assets/{index-BWWyL373.js → index-BUZqKnhc.js} +1 -1
- package/dist/client/assets/{index-CWkZVTaB.js → index-C_qyq-0C.js} +1 -1
- package/dist/client/assets/{index-CkH3mWvs.js → index-CzhqcVNy.js} +3 -3
- package/dist/client/assets/{index-Bd2o7ApL.js → index-D0IWyB7F.js} +1 -1
- package/dist/client/assets/{index-BcCLyj5B.js → index-Dq7847Un.js} +1 -1
- package/dist/client/assets/{index-DYwRYhsj.js → index-DvM0KkHv.js} +1 -1
- package/dist/client/assets/{index-DJbhPUvH.js → index-NVV58uyB.js} +1 -1
- package/dist/client/assets/{index-DJaJOTT1.js → index-reo4wb4o.js} +1 -1
- package/dist/client/assets/{index-B-OdNlE7.js → index-u3QgiiTa.js} +1 -1
- package/dist/client/assets/{infiniteQueryObserver-DAaNXBsl.js → infiniteQueryObserver-B0sfe0Pc.js} +1 -1
- package/dist/client/assets/{input-Byroc8t4.js → input-CaHgq6JC.js} +1 -1
- package/dist/client/assets/{integration-icon-mwS0bnEH.js → integration-icon-C_O5yvdg.js} +1 -1
- package/dist/client/assets/{label-D4oI89DS.js → label-ZRpbI7Sm.js} +1 -1
- package/dist/client/assets/{layout-DoVjZIrn.js → layout-Di7S7mGF.js} +1 -1
- package/dist/client/assets/{layout-DDl2Bvjj.js → layout-_gy6ZrEk.js} +1 -1
- package/dist/client/assets/{localstorage-keys-DueMZIFu.js → localstorage-keys-CL6qU9e5.js} +1 -1
- package/dist/client/assets/{login-l7LPfl41.js → login-DzHv8Qa0.js} +1 -1
- package/dist/client/assets/{markdown-C5HDJBhu.js → markdown-CjmEcbPS.js} +1 -1
- package/dist/client/assets/{mcp-app-renderer-CcbaBTO3.js → mcp-app-renderer-DjshzOV0.js} +1 -1
- package/dist/client/assets/{mcp-server-card-DMYKZy5B.js → mcp-server-card-CbhtCiCR.js} +1 -1
- package/dist/client/assets/{mcp-server-detail-CaijVFsh.js → mcp-server-detail-Dm6C4rJd.js} +2 -2
- package/dist/client/assets/{members-DHOUb6ci.js → members-D0WpzrAD.js} +1 -1
- package/dist/client/assets/{monaco-editor-BQLItIWK.js → monaco-editor-860lh9IG.js} +1 -1
- package/dist/client/assets/{monitoring-Dts7enDX.js → monitoring-B8ASHaBh.js} +1 -1
- package/dist/client/assets/{monitoring-dashboard-edit-BpdxPDCL.js → monitoring-dashboard-edit-CKffDTQw.js} +1 -1
- package/dist/client/assets/{monitoring-dashboard-view-9-ODb2Fv.js → monitoring-dashboard-view-C1XkuilW.js} +1 -1
- package/dist/client/assets/{oauth-callback-Dz0IDrwc.js → oauth-callback-CsPyZ3bv.js} +1 -1
- package/dist/client/assets/{page-B20oyWAL.js → page-BGclLydc.js} +1 -1
- package/dist/client/assets/{page-COrqn5gB.js → page-BWVa1qSI.js} +1 -1
- package/dist/client/assets/{plugin-empty-state-BFvuO_ih.js → plugin-empty-state-BXMB-ve6.js} +1 -1
- package/dist/client/assets/{plugin-empty-state-amtzTfj5.js → plugin-empty-state-aV5T7nJZ.js} +1 -1
- package/dist/client/assets/{plugin-header-Ck-AR7F4.js → plugin-header-CMg87EDN.js} +1 -1
- package/dist/client/assets/{plugin-header-BBKvfeNU.js → plugin-header-DorQWEZ4.js} +1 -1
- package/dist/client/assets/plugins-BYjlWQ4G.js +1 -0
- package/dist/client/assets/{popover-abKtRKyZ.js → popover-DMD8_Cbp.js} +1 -1
- package/dist/client/assets/{project-app-view-4HfAYNAZ.js → project-app-view-BucEC3T-.js} +1 -1
- package/dist/client/assets/{project-layout-CabGF5OL.js → project-layout-DdxzQdxw.js} +1 -1
- package/dist/client/assets/{project-plugins-Cj7LCQq3.js → project-plugins-FyEUKPb1.js} +1 -1
- package/dist/client/assets/{projects-list-BGSS1A6G.js → projects-list-lWISZLY6.js} +1 -1
- package/dist/client/assets/{readme-viewer-CZC-Af79.js → readme-viewer-BRyijqWE.js} +1 -1
- package/dist/client/assets/{registry-layout-1no55Xfs.js → registry-layout-A5khdaYw.js} +1 -1
- package/dist/client/assets/{registry-utils-BKh1htsU.js → registry-utils-sGbNqghw.js} +1 -1
- package/dist/client/assets/{reports-layout-ClnQzTBD.js → reports-layout-Ds-X2DgZ.js} +1 -1
- package/dist/client/assets/{reset-password-_UXSoKqO.js → reset-password-DUyo7dJf.js} +1 -1
- package/dist/client/assets/{resizable-CRr1U4c3.js → resizable-DLaWW8z1.js} +1 -1
- package/dist/client/assets/{save-actions-DIgvk5ux.js → save-actions-KKLUna-U.js} +1 -1
- package/dist/client/assets/{scroll-area-CW7MZrxV.js → scroll-area-uvPGOSmX.js} +1 -1
- package/dist/client/assets/{select-CHbDIpjW.js → select-DhCocnGM.js} +1 -1
- package/dist/client/assets/{shell-layout-BcxWQVeI.js → shell-layout-CUgayftW.js} +2 -2
- package/dist/client/assets/{sidebar-settings-Bcsu8-RD.js → sidebar-settings-DWw0y5k_.js} +1 -1
- package/dist/client/assets/{skeleton-BnHZ2SKu.js → skeleton-LSt15V1C.js} +1 -1
- package/dist/client/assets/{spinner-BA1OKCJn.js → spinner-CI9QBd79.js} +1 -1
- package/dist/client/assets/{store-invite-igZB1w5t.js → store-invite-CFRAOscU.js} +1 -1
- package/dist/client/assets/{switch-CEp85hk1.js → switch-CsOlnIJv.js} +1 -1
- package/dist/client/assets/{table-FycIVL0n.js → table-xcvICYfC.js} +1 -1
- package/dist/client/assets/{tabs-eovXpXHz.js → tabs-d2vBhIp6.js} +1 -1
- package/dist/client/assets/tasks-CoQZ2sIy.js +1 -0
- package/dist/client/assets/{tasks-panel-BvevXbhl.js → tasks-panel-bZwhdQBY.js} +1 -1
- package/dist/client/assets/{textarea-xLi2sLqg.js → textarea-CqsgYI_z.js} +1 -1
- package/dist/client/assets/{time-range-picker-BlOSKVgs.js → time-range-picker-CnM7cuGo.js} +1 -1
- package/dist/client/assets/{toggle-group-CaTS_Qlx.js → toggle-group-BrCJ8OSl.js} +1 -1
- package/dist/client/assets/{tools-list-DtBpx3vZ.js → tools-list-BJgQvAAh.js} +1 -1
- package/dist/client/assets/{tooltip-BgxYg-1x.js → tooltip-B-2Ty_iR.js} +1 -1
- package/dist/client/assets/{topbar-portal-CSUXfJuZ.js → topbar-portal-CVzUAi-D.js} +1 -1
- package/dist/client/assets/{types-DtFKQumZ.js → types-DiJR_Oxi.js} +1 -1
- package/dist/client/assets/{use-binding-BakZcpgb.js → use-binding-CHcWA4CU.js} +1 -1
- package/dist/client/assets/{use-collections-Dn1-4HmN.js → use-collections-C8v6HwyA.js} +1 -1
- package/dist/client/assets/{use-connection-lSmwmnH7.js → use-connection-CkLGBugg.js} +1 -1
- package/dist/client/assets/{use-copy-Bomw0PO-.js → use-copy-BNKFNH2y.js} +1 -1
- package/dist/client/assets/{use-create-virtual-mcp-BCc2b51u.js → use-create-virtual-mcp-BvTxfE8g.js} +1 -1
- package/dist/client/assets/{use-install-from-registry-DNLztiY9.js → use-install-from-registry-rEwcMxvA.js} +1 -1
- package/dist/client/assets/{use-list-state-DsP3P__2.js → use-list-state-Dt9uCsOl.js} +1 -1
- package/dist/client/assets/{use-llm-CaWI-EbM.js → use-llm-CfPWCeJ7.js} +1 -1
- package/dist/client/assets/{use-mcp-prompts-DgbJlfFv.js → use-mcp-prompts-DJolbe2G.js} +1 -1
- package/dist/client/assets/{use-mcp-tools-DnT4wYwM.js → use-mcp-tools-_SrEx2Yc.js} +1 -1
- package/dist/client/assets/{use-members-BeqtA6Mf.js → use-members-Bg7suFno.js} +1 -1
- package/dist/client/assets/{use-mobile-DvJypPyV.js → use-mobile-Ccj9Yl8E.js} +1 -1
- package/dist/client/assets/{use-preferences-BtbUN2Ab.js → use-preferences-CBTWTfUK.js} +1 -1
- package/dist/client/assets/{use-project-C6Plluwk.js → use-project-O2tBNyfQ.js} +1 -1
- package/dist/client/assets/{use-settings-modal-BYuaItl2.js → use-settings-modal-Cb5fjZOk.js} +1 -1
- package/dist/client/assets/{use-view-mode-DlkH6B2z.js → use-view-mode-DltmabmA.js} +1 -1
- package/dist/client/assets/{use-virtual-mcp-Cd9Q7Ljj.js → use-virtual-mcp-CelTUOdD.js} +1 -1
- package/dist/client/assets/useInfiniteQuery-7fuF9QDV.js +1 -0
- package/dist/client/assets/{useMutation-T3cHavFN.js → useMutation-BLMqKfMt.js} +1 -1
- package/dist/client/assets/useQuery-BtUsJRrm.js +1 -0
- package/dist/client/assets/useSuspenseInfiniteQuery-BB0K0DXv.js +1 -0
- package/dist/client/assets/{user-CVY-7wwJ.js → user-BIDniHYV.js} +1 -1
- package/dist/client/assets/{workflow-JfVjNsvD.js → workflow-BPBBOx7S.js} +1 -1
- package/dist/client/index.html +1 -1
- package/dist/server/cli.js +2 -2
- package/dist/server/migrate.js +1 -1
- package/dist/server/server.js +2 -2
- package/package.json +1 -1
- package/dist/client/assets/constants-8yG-REbY.js +0 -1
- package/dist/client/assets/plugins-BL4zfVGs.js +0 -1
- package/dist/client/assets/tasks-zO_D9agi.js +0 -1
- package/dist/client/assets/useInfiniteQuery-DlMqKbZ8.js +0 -1
- package/dist/client/assets/useQuery-CrhfJFci.js +0 -1
- package/dist/client/assets/useSuspenseInfiniteQuery-D7mXok6B.js +0 -1
package/dist/server/cli.js
CHANGED
|
@@ -1955,7 +1955,7 @@ ${X.stack}`;return W}}catch{}if(typeof X.toString==="function")try{let W=X.toStr
|
|
|
1955
1955
|
};
|
|
1956
1956
|
`,$=await Eu({code:H,tools:K,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(Q){return{content:[{type:"text",text:`Virtual tool execution failed: ${Q instanceof Error?Q.message:String(Q)}`}],isError:!0}}}async listResources(){return{resources:(await this._cachedResources).data}}async readResource(Y){let X=await this._cachedResources,J=this._clients,G=X.mappings.get(Y.uri);if(!G)throw Error(`Resource not found: ${Y.uri}`);let W=J.get(G);if(!W)throw Error(`Connection not found for resource: ${Y.uri}`);return await W.readResource(Y)}async listPrompts(){return{prompts:(await this._cachedPrompts).data}}async getPrompt(Y){let X=await this._cachedPrompts,J=this._clients,G=X.mappings.get(Y.name);if(!G)throw Error(`Prompt not found: ${Y.name}`);let W=J.get(G);if(!W)throw Error(`Connection not found for prompt: ${Y.name}`);return await W.getPrompt(Y)}async callStreamableTool(Y,X){let J=await this._cachedTools,G=this._clients,W=J.mappings.get(Y);if(W){let K=G.get(W);if(K&&"callStreamableTool"in K)return K.callStreamableTool(Y,X)}let Z=await this.callTool({name:Y,arguments:X});return new Response(JSON.stringify(Z),{headers:{"Content-Type":"application/json"}})}async[Symbol.asyncDispose](){await jW6(this._clients)}async close(){await jW6(this._clients),await super.close()}getInstructions(){return this.options.virtualMcp.metadata?.instructions??void 0}}});var IW6,EG8,SW6,RG8,yu;var $k1=y(()=>{c0();qA();Hk1();IW6=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")}),EG8=q.toJSONSchema(IW6),SW6=q.object({tools:q.array(q.string()).min(1).describe("Array of tool names to get detailed schemas for")}),RG8=q.toJSONSchema(SW6);yu=class yu extends XI{constructor(Y,X){super(Y,X)}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:EG8,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:RG8,annotations:{title:"Describe Tools",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}}}async handleSearch(Y){let X=IW6.safeParse(Y);if(!X.success)return MO({error:X.error.flatten()});let J=await this._cachedTools,G=rU(J.data),W=v91(X.data.query,G,X.data.limit);return Ru({query:X.data.query,results:W.map((Z)=>({name:Z.name,description:Z.description,connection:Z._meta.connectionTitle})),totalAvailable:G.length})}async handleDescribe(Y){let X=SW6.safeParse(Y);if(!X.success)return MO({error:X.error.flatten()});let J=await this._cachedTools,G=rU(J.data),W=f91(X.data.tools,G);return Ru({tools:W.tools,notFound:W.notFound})}async listTools(){let Y=await this._cachedTools,X=rU(Y.data);return{tools:[this.getSearchTool(X.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 XI.prototype.callTool.call(this,Y)}}});var _W6,TG8,Fk1;var kW6=y(()=>{c0();qA();$k1();_W6=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).")}),TG8=q.toJSONSchema(_W6);Fk1=class Fk1 extends yu{constructor(Y,X){super(Y,X)}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:TG8,annotations:{title:"Run Code",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}}}async handleRunCode(Y){let X=_W6.safeParse(Y);if(!X.success)return MO({error:X.error.flatten()});let J=await this._cachedTools,W={tools:rU(J.data),callTool:async(K,Q)=>{return this.routeToolCall({name:K,arguments:Q})}},Z=await y91(X.data.code,W,X.data.timeoutMs);if(Z.error)return MO(Z);return Ru(Z)}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 fW6(Y){let X=Y.slice().sort().join(","),J=vW6.get(X);if(!J){let G=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")});J={schema:G,jsonSchema:q.toJSONSchema(G)},vW6.set(X,J)}return J}var vW6,Vk1;var yW6=y(()=>{c0();qA();$k1();vW6=new Map;Vk1=class Vk1 extends yu{constructor(Y,X){super(Y,X)}async getCallTool(){let Y=await this._cachedTools,J=rU(Y.data).map((W)=>W.name),{jsonSchema:G}=fW6(J);return{name:"GATEWAY_CALL_TOOL",description:"Execute a tool by name. Use GATEWAY_DESCRIBE_TOOLS first to understand the input schema.",inputSchema:G,annotations:{title:"Call Tool",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}}}async handleCallTool(Y){let X=await this._cachedTools,J=rU(X.data),G=J.map(($)=>$.name),{schema:W}=fW6(G),Z=W.safeParse(Y);if(!Z.success)return MO({error:Z.error.flatten()});let{name:K,arguments:Q}=Z.data;if(!new Map(J.map(($)=>[$.name,$])).has(K))return{content:[{type:"text",text:`Tool not found: ${K}. Use GATEWAY_SEARCH_TOOLS to find available tools.`}],isError:!0};return this.routeToolCall({name:K,arguments:Q})}async listTools(){let Y=await super.listTools(),X=await this.getCallTool();return{tools:[...Y.tools,X]}}async callTool(Y){if(Y.name==="GATEWAY_CALL_TOOL")return this.handleCallTool(Y.arguments??{});return super.callTool(Y)}}});function zk1(Y){switch(Y){case"smart_tool_selection":return"smart_tool_selection";case"code_execution":return"code_execution";case"passthrough":default:return"passthrough"}}function CG8(Y,X){if(Y.connection_type!=="VIRTUAL")return!1;if(!X||Gz(X))return!1;return Y.id===X}async function bW6(Y,X,J=!1){let G=Y.id,W=await X.storage.virtualMcps.findById(G);if(!W)throw Error(`Virtual MCP not found: ${G}`);return EO(W,X,"passthrough",J)}async function EO(Y,X,J,G=!1){let Z=Y.connections.map((V)=>V.connection_id).map((V)=>X.storage.connections.findById(V)),K=Y.id?await X.storage.connections.findById(Y.id):null,Q=await Promise.all(Z),H=[];if(K?.tools){for(let V of K.tools)if(PO(V))H.push(V)}let F={connections:Q.filter((V)=>V!==null&&V.status==="active"&&!CG8(V,Y.id)),virtualMcp:Y,virtualTools:H.length>0?H:void 0,superUser:G};return J==="smart_tool_selection"?new Vk1(F,X):J==="code_execution"?new Fk1(F,X):new XI(F,X)}var bu=y(()=>{cY();eU();kW6();Hk1();yW6()});async function EW(Y,X,J=!1){if(Y.connection_type==="VIRTUAL")return bW6(Y,X,J);return AW6(Y,X,J)}var Uk1=y(()=>{PW6();bu()});async function Bk1(Y,X,J){let G=await EW(Y,X,J),W=zN(G,{name:"mcp-mesh-enhanced",version:"1.0.0"},{capabilities:jG8,instructions:G.getInstructions()});return W.server.setRequestHandler(tB,async()=>{return await G.listResources().catch(DA({resources:[]}))}),W.server.setRequestHandler(eB,async()=>{return await G.listResourceTemplates().catch(DA({resourceTemplates:[]}))}),W.server.setRequestHandler(Yq,async()=>{return await G.listPrompts().catch(DA({prompts:[]}))}),W}var jG8;var hW6=y(()=>{cY();l5();Uk1();Kk1();jG8={tools:{},resources:{},prompts:{}}});function qk1(Y,X,J){let G=Y.listTools.bind(Y),W=async()=>{let Z=X.connection_type==="VIRTUAL";if(!Z&&X.tools&&X.tools.length>0)return{tools:X.tools.map((Q)=>({name:Q.name,description:Q.description,inputSchema:Q.inputSchema,outputSchema:Q.outputSchema,annotations:Q.annotations,_meta:Q._meta}))};if(!Z&&J){let Q=await J.get(X.id);if(Q)return{tools:Q}}let K=await G();if(!Z&&J&&K.tools.length>0)J.set(X.id,K.tools).catch(()=>{});return K};return Y.listTools=W,Y}function IG8(Y,X,J){return async(G,W)=>{try{let Z=G.params.name,K=async()=>{let{tools:H}=await J();return H.find((F)=>F.name===Z)?._meta};return await new tU(Y.authInstance,Y.auth.user?.id??Y.auth.apiKey?.userId,Z,Y.boundAuth,Y.auth.user?.role,X,K).check(Z),await W()}catch(Z){return new Response(JSON.stringify({error:`Authorization failed: ${Z.message}`}),{status:403,headers:{"Content-Type":"application/json"}})}}}function OA(Y,X,J,G,W){let Z=async(Q,H)=>{if(J.connection_type==="VIRTUAL"){let U=await Y.callTool({name:Q,arguments:H});return new Response(JSON.stringify(U),{headers:{"Content-Type":"application/json"}})}if(!J.connection_url)throw Error("Streamable tools require HTTP connection with URL");let $=J.connection_url,F={method:"tools/call",params:{name:Q,arguments:H}};if(!W.superUser){let B=await IG8(G,X,Y.listTools.bind(Y))(F,async()=>{return new Response});if(!B.ok)return B}let V=G.connectionId&&G.connectionId!==X?G.connectionId:void 0;return NW6({ctx:G,enabled:AL0().enabled,connectionId:X,connectionTitle:J.title,virtualMcpId:V})(F,async()=>{let U=await Iu(J,G,W.superUser),B=J.connection_headers;if(B&&"headers"in B)Object.assign(U,B.headers);let D=new URL($);D.pathname=D.pathname.replace(/\/$/,"")+`/call-tool/${F.params.name}`;let L=JSON.parse(JSON.stringify(F.params.arguments,(N,R)=>{if(R instanceof AbortSignal)return;if(typeof R==="function"||typeof R==="symbol")return;if(R===void 0)return;return R})),w=JSON.stringify(L);return await G.tracer.startActiveSpan("mcp.proxy.callStreamableTool",{attributes:{"connection.id":X,"tool.name":F.params.name,"request.id":G.metadata.requestId}},async(N)=>{let R=Date.now();try{let P=await fetch(D.toString(),{method:"POST",redirect:"manual",body:w,headers:{...U,"Content-Type":"application/json"}}),A=Date.now()-R;return G.meter.createHistogram("connection.proxy.streamable.duration").record(A,{"connection.id":X,"tool.name":F.params.name,status:P.ok?"success":"error"}),G.meter.createCounter("connection.proxy.streamable.requests").add(1,{"connection.id":X,"tool.name":F.params.name,status:P.ok?"success":"error"}),N.end(),P}catch(P){let A=P,E=Date.now()-R;throw console.error("[with-streaming-support] fetch error",{connectionId:X,toolName:F.params.name,error:A.message,errorStack:A.stack,duration:E}),G.meter.createHistogram("connection.proxy.streamable.duration").record(E,{"connection.id":X,"tool.name":F.params.name,status:"error"}),G.meter.createCounter("connection.proxy.streamable.errors").add(1,{"connection.id":X,"tool.name":F.params.name,error:A.message}),N.recordException(A),N.end(),P}})})},K=Object.assign(Object.create(Object.getPrototypeOf(Y)),Y);return K.callStreamableTool=Z,K}var xW6=y(()=>{s_1();ku();K01();Zk1()});var gW6=y(()=>{xW6()});var JI=y(()=>{Uk1();hW6();gW6()});function uW6(Y,X,J){if(X.some((G)=>G!=="*"&&G.startsWith("SELF::"))&&Y.SELF===void 0)Y.SELF={value:`${J}_self`}}async function kG8(Y,X,J,G){for(let Z of X){if(Z==="*")continue;let[K]=QW6(Z),Q=u91(K,Y);if(Q===void 0||Q===null)throw Error(`Scope references key "${K}" but it's not present in state`)}let W=KW6(Y,X);for(let Z of W){if(Z.endsWith("_self"))continue;let K=await G.storage.connections.findById(Z);if(!K||K.organization_id!==J)throw Error(`Referenced connection not found: ${Z}`);try{await G.access.check(Z)}catch(Q){throw Error(`Access denied to referenced connection: ${Z}. ${Q.message}`)}}}var SG8,_G8,Dk1;var mW6=y(()=>{r_1();JI();m91();c0();J4();I91();aU();SG8=q.object({id:q.string().describe("ID of the connection to update"),data:Ov.describe("Partial connection data to update")}),_G8=q.object({item:gG.describe("The updated connection entity")});Dk1=i0({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:SG8,outputSchema:_G8,handler:async(Y,X)=>{$6(X);let J=D6(X);await X.access.check();let G=fX(X);if(!G)throw Error("User ID required to update connection");let{id:W,data:Z}=Y,K=await X.storage.connections.findById(W);if(!K||K.organization_id!==J.id)throw Error("Connection not found in organization");let Q=Z.connection_type??K.connection_type,H=Z.connection_url??K.connection_url;if(Q==="VIRTUAL"){let L=FN(H);if(!L)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let w=await X.storage.virtualMcps.findById(L);if(!w)throw Error(`Virtual MCP not found: ${L}`);if(w.organization_id!==J.id)throw Error("Virtual MCP does not belong to the current organization");H=VN(L)}let $=Z.configuration_state??K.configuration_state??{},F=Z.configuration_scopes??K.configuration_scopes??[];if(Z.configuration_state!==void 0||Z.configuration_scopes!==void 0){if(Z.configuration_state!==void 0)$=Z.configuration_state??{};else if($===null||$===void 0)$={};if(Z.configuration_scopes!==void 0)F=Z.configuration_scopes??[];if(F.length>0){let L=$;uW6(L,F,J.id),await kG8(L,F,J.id,X)}}let V=Z.connection_token??K.connection_token;if(!V)try{let w=await new sU(X.db,X.vault).get(W);if(w?.accessToken)V=w.accessToken}catch{}let z=await nj({id:K.id,title:Z.title??K.title,connection_type:Q,connection_url:H,connection_token:V,connection_headers:Z.connection_headers??K.connection_headers}).catch(()=>null),U=z?.tools?.length?z.tools:null;if(Z.configuration_scopes===void 0&&z?.scopes?.length)F=z.scopes;uW6($,F,J.id);let B={...Z,connection_url:H,tools:U,configuration_state:$,configuration_scopes:F,updated_by:G},D=await X.storage.connections.update(W,B);if((Z.configuration_state!==void 0||Z.configuration_scopes!==void 0)&&$&&F)try{await(await EW(D,X,!1)).callTool({name:"ON_MCP_CONFIGURATION",arguments:{state:$,scopes:F}})}catch(L){console.error("Failed to invoke ON_MCP_CONFIGURATION callback",L)}return{item:D}}})});var vG8,Ok1;var lW6=y(()=>{YZ();c0();J4();aU();vG8=_f.extend({force:q.boolean().optional().describe("If true, removes this connection from all agents that reference it before deleting")}),Ok1=i0({name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete a connection",annotations:{title:"Delete Connection",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:vG8,outputSchema:kf(gG),handler:async(Y,X)=>{$6(X);let J=D6(X);await X.access.check();let G=await X.storage.connections.findById(Y.id);if(!G)throw Error(`Connection not found: ${Y.id}`);if(G.organization_id!==J.id)throw Error("Connection not found in organization");if(G.metadata?.isFixed===!0)throw Error("This connection is a fixed system connection and cannot be deleted");let Z=await X.storage.virtualMcps.listByConnectionId(J.id,Y.id);if(Z.length>0)if(Y.force)await X.storage.virtualMcps.removeConnectionReferences(Y.id);else throw Error(JSON.stringify({code:"CONNECTION_IN_USE",agentNames:Z.map((K)=>K.title)}));return await X.storage.connections.delete(Y.id),{item:G}}})});var Lk1;var dW6=y(()=>{c0();J4();Lk1=i0({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,X)=>{let J=D6(X);await X.access.check();let G=await X.storage.connections.findById(Y.id);if(!G||G.organization_id!==J.id)throw Error("Connection not found");let W=await X.storage.connections.testConnection(Y.id);return{id:Y.id,...W}}})});var cW6=y(()=>{sG6();WW6();ZW6();mW6();lW6();dW6()});function pW6(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 bG8(Y,X){let J=Y;for(let W=X.length;W>=1;W--){let Z=`$${W}`;if(J.includes(Z))J=J.replaceAll(Z,pW6(X[W-1]))}let G=[];for(let W=0;W<J.length;W++)if(J[W]==="?")G.push(W);for(let W=Math.min(G.length,X.length)-1;W>=0;W--){let Z=G[W],K=pW6(X[W]);J=J.slice(0,Z)+K+J.slice(Z+1)}return J}function nW6(Y){return Y.replace(/-/g,"_")}function xG8(Y){return`app_${nW6(Y)}`}function gG8(Y){return`app_role_${nW6(Y)}`}function uG8(Y){if(Y instanceof Error){let X=Y.message.toLowerCase(),J=Y.code;return J==="3F000"||J==="42704"||J==="22023"||X.includes("schema")&&X.includes("does not exist")||X.includes("role")&&X.includes("does not exist")}return!1}async function mG8(Y,X,J){if(await E0`CREATE SCHEMA IF NOT EXISTS ${E0.id(X)}`.execute(Y),!(await E0`
|
|
1957
1957
|
SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${J}) as exists
|
|
1958
|
-
`.execute(Y)).rows[0]?.exists)await E0`CREATE ROLE ${E0.id(J)} NOLOGIN`.execute(Y);await E0`GRANT ${E0.id(J)} TO CURRENT_USER`.execute(Y),await E0`GRANT USAGE, CREATE ON SCHEMA ${E0.id(X)} TO ${E0.id(J)}`.execute(Y),await E0`GRANT ALL ON ALL TABLES IN SCHEMA ${E0.id(X)} TO ${E0.id(J)}`.execute(Y),await E0`GRANT ALL ON ALL SEQUENCES IN SCHEMA ${E0.id(X)} TO ${E0.id(J)}`.execute(Y),await E0`ALTER DEFAULT PRIVILEGES IN SCHEMA ${E0.id(X)} GRANT ALL ON TABLES TO ${E0.id(J)}`.execute(Y),await E0`ALTER DEFAULT PRIVILEGES IN SCHEMA ${E0.id(X)} GRANT ALL ON SEQUENCES TO ${E0.id(J)}`.execute(Y),await E0`REVOKE ALL ON SCHEMA public FROM ${E0.id(J)}`.execute(Y)}async function lG8(Y,X,J,G){try{return await Y.transaction().execute(async(W)=>{return await E0`SET LOCAL ROLE ${E0.id(J)}`.execute(W),await E0`SET LOCAL search_path TO ${E0.id(X)}`.execute(W),await E0.raw(G).execute(W)})}catch(W){if(uG8(W))return await mG8(Y,X,J),await Y.transaction().execute(async(Z)=>{return await E0`SET LOCAL ROLE ${E0.id(J)}`.execute(Z),await E0`SET LOCAL search_path TO ${E0.id(X)}`.execute(Z),await E0.raw(G).execute(Z)});throw W}}var yG8,hG8,iW6;var aW6=y(()=>{F9();c0();J4();yG8=q.object({results:q.array(q.unknown()).optional(),success:q.boolean().optional()});hG8=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()});iW6=i0({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:hG8,outputSchema:q.object({result:q.array(yG8)}),handler:async(Y,X)=>{$6(X),await X.access.check();let J=bG8(Y.sql,Y.params||[]);if(!X.connectionId)throw Error("Connection context required for database access");let G=xG8(X.connectionId),W=gG8(X.connectionId);return{result:[{results:(await lG8(X.db,G,W,J)).rows,success:!0}]}}})});var rW6,cG8,oW6;var YB=y(()=>{c0();af();rW6=q.object({connectionId:q.string().optional().describe("Filter subscriptions by connection ID (optional)")}),cG8=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)")}),oW6=q.object({subscriptions:q.array(cG8).describe("List of subscriptions")})});var Nk1;var sW6=y(()=>{J4();YB();Nk1=i0({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:vf,outputSchema:ff,handler:async(Y,X)=>{$6(X);let J=D6(X);await X.access.check();let G=X.connectionId;if(!G)throw Error("Connection ID required to publish events. Use a connection-scoped token.");let W=await X.eventBus.publish(J.id,G,{type:Y.type,subject:Y.subject,data:Y.data,deliverAt:Y.deliverAt,cron:Y.cron});return{id:W.id,type:W.type,source:W.source,time:W.time}}})});var Mk1;var tW6=y(()=>{J4();YB();Mk1=i0({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:yf,outputSchema:bf,handler:async(Y,X)=>{$6(X);let J=D6(X);await X.access.check();let G=X.connectionId;if(!G)throw Error("Connection ID required to subscribe. Use a connection-scoped token.");let W=await X.eventBus.subscribe(J.id,{connectionId:G,eventType:Y.eventType,publisher:Y.publisher,filter:Y.filter});return{subscription:{id:W.id,connectionId:W.connectionId,eventType:W.eventType,publisher:W.publisher,filter:W.filter,enabled:W.enabled,createdAt:W.createdAt instanceof Date?W.createdAt.toISOString():W.createdAt,updatedAt:W.updatedAt instanceof Date?W.updatedAt.toISOString():W.updatedAt}}}})});var wk1;var eW6=y(()=>{J4();YB();wk1=i0({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:gf,outputSchema:uf,handler:async(Y,X)=>{$6(X);let J=D6(X);await X.access.check();let G=X.connectionId;if(!G)throw Error("Connection ID required to unsubscribe. Use a connection-scoped token.");let W=await X.eventBus.getSubscription(J.id,Y.subscriptionId);if(!W)throw Error(`Subscription not found: ${Y.subscriptionId}`);if(W.connectionId!==G)throw Error("Cannot unsubscribe from a subscription owned by another connection");return{success:(await X.eventBus.unsubscribe(J.id,Y.subscriptionId)).success,subscriptionId:Y.subscriptionId}}})});var Ak1;var YZ6=y(()=>{J4();YB();Ak1=i0({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:mf,outputSchema:lf,handler:async(Y,X)=>{$6(X);let J=D6(X);await X.access.check();let G=X.connectionId;if(!G)throw Error("Connection ID required to cancel events. Use a connection-scoped token.");if(!await X.eventBus.getEvent(J.id,Y.eventId))throw Error(`Event not found: ${Y.eventId}`);if(!(await X.eventBus.cancelEvent(J.id,Y.eventId,G)).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 Pk1;var XZ6=y(()=>{J4();YB();Pk1=i0({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:df,outputSchema:cf,handler:async(Y,X)=>{$6(X);let J=D6(X);await X.access.check();let G=X.connectionId;if(!G)throw Error("Connection ID required to acknowledge events. Use a connection-scoped token.");if(!(await X.eventBus.ackEvent(J.id,Y.eventId,G)).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 Ek1;var JZ6=y(()=>{J4();YB();Ek1=i0({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:rW6,outputSchema:oW6,handler:async(Y,X)=>{$6(X);let J=D6(X);return await X.access.check(),{subscriptions:(await X.eventBus.listSubscriptions(J.id,Y.connectionId)).map((W)=>({id:W.id,connectionId:W.connectionId,eventType:W.eventType,publisher:W.publisher,filter:W.filter,enabled:W.enabled,createdAt:W.createdAt instanceof Date?W.createdAt.toISOString():W.createdAt,updatedAt:W.updatedAt instanceof Date?W.updatedAt.toISOString():W.updatedAt}))}}})});var Rk1;var GZ6=y(()=>{J4();YB();Rk1=i0({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:hf,outputSchema:xf,handler:async(Y,X)=>{$6(X);let J=D6(X);await X.access.check();let G=X.connectionId;if(!G)throw Error("Connection ID required to sync subscriptions. Use a connection-scoped token.");let W=await X.eventBus.syncSubscriptions(J.id,{connectionId:G,subscriptions:Y.subscriptions});return{created:W.created,updated:W.updated,deleted:W.deleted,unchanged:W.unchanged,subscriptions:W.subscriptions.map((Z)=>({id:Z.id,connectionId:Z.connectionId,eventType:Z.eventType,publisher:Z.publisher,filter:Z.filter,enabled:Z.enabled,createdAt:Z.createdAt instanceof Date?Z.createdAt.toISOString():Z.createdAt,updatedAt:Z.updatedAt instanceof Date?Z.updatedAt.toISOString():Z.updatedAt}))}}})});var WZ6=y(()=>{sW6();tW6();eW6();YZ6();XZ6();JZ6();GZ6();YB()});var GI=y(()=>{Da()});function ZZ6(){return`/icons/capy-${Math.floor(Math.random()*39)+0}.png`}var nG8,iG8,Tk1;var QZ6=y(()=>{c0();J4();GI();nG8=q.object({data:Nv.describe("Data for the new virtual MCP")}),iG8=q.object({item:nZ.describe("The created virtual MCP entity")}),Tk1=i0({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:nG8,outputSchema:iG8,handler:async(Y,X)=>{$6(X);let J=D6(X);await X.access.check();let G=fX(X);if(!G)throw Error("User ID required to create virtual MCP");let W={...Y.data,icon:Y.data.icon??ZZ6()};return{item:await X.storage.virtualMcps.create(J.id,G,W)}}})});function aG8(Y){let X=[],J=0;while(J<Y.length){let G=Y[J];if(G==="%")X.push(".*");else if(G==="_")X.push(".");else if(/[.*+?^${}()|[\]\\]/.test(G))X.push("\\"+G);else X.push(G);J++}return X.join("")}function RO(Y){return typeof Y==="string"||typeof Y==="number"}function Ck1(Y,X){let J=X.split("."),G=Y;for(let W of J){if(G==null||typeof G!=="object")return;G=G[W]}return G}function rG8(Y,X){return Y.connections.some((J)=>J.connection_id===X)}function n91(Y,X){if("conditions"in X){let{operator:Q,conditions:H}=X;switch(Q){case"and":return H.every(($)=>n91(Y,$));case"or":return H.some(($)=>n91(Y,$));case"not":return!H.every(($)=>n91(Y,$));default:return!0}}let{field:J,operator:G,value:W}=X,Z=J.join(".");if(Z==="connection_id"){if(G!=="eq"||typeof W!=="string")return!1;return rG8(Y,W)}let K=Ck1(Y,Z);switch(G){case"eq":return K===W;case"gt":return RO(K)&&RO(W)&&K>W;case"gte":return RO(K)&&RO(W)&&K>=W;case"lt":return RO(K)&&RO(W)&&K<W;case"lte":return RO(K)&&RO(W)&&K<=W;case"in":return Array.isArray(W)&&W.includes(K);case"like":if(typeof K!=="string"||typeof W!=="string")return!1;if(W.length>100)return!1;let Q=aG8(W);return new RegExp(`^${Q}$`,"i").test(K);case"contains":if(typeof K!=="string"||typeof W!=="string")return!1;return K.toLowerCase().includes(W.toLowerCase());default:return!0}}function oG8(Y,X){return[...Y].sort((J,G)=>{for(let W of X){let Z=W.field.join("."),K=Ck1(J,Z),Q=Ck1(G,Z),H=0;if(K==null&&Q==null)continue;if(K==null)H=W.nulls==="first"?-1:1;else if(Q==null)H=W.nulls==="first"?1:-1;else if(typeof K==="string"&&typeof Q==="string")H=K.localeCompare(Q);else if(typeof K==="number"&&typeof Q==="number")H=K-Q;else H=String(K).localeCompare(String(Q));if(H!==0)return W.direction==="desc"?-H:H}return 0})}var sG8,tG8,jk1;var KZ6=y(()=>{YZ();J4();GI();sG8=W3,tG8=wz(nZ),jk1=i0({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:sG8,outputSchema:tG8,handler:async(Y,X)=>{await X.access.check();let J=D6(X),G=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,Z=G?await X.storage.virtualMcps.listByConnectionId(J.id,G):await X.storage.virtualMcps.list(J.id);if(Y.where)Z=Z.filter((V)=>n91(V,Y.where));if(Y.orderBy&&Y.orderBy.length>0)Z=oG8(Z,Y.orderBy);let K=Z.length,Q=Y.offset??0,H=Y.limit??100,$=Z.slice(Q,Q+H),F=Q+H<K;return{items:$,totalCount:K,hasMore:F}}})});var eG8,YW8,Ik1;var HZ6=y(()=>{c0();J4();GI();eG8=q.object({id:q.string().describe("ID of the virtual MCP to retrieve")}),YW8=q.object({item:nZ.nullable().describe("The retrieved virtual MCP, or null if not found")}),Ik1=i0({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:eG8,outputSchema:YW8,handler:async(Y,X)=>{$6(X);let J=D6(X);await X.access.check();let G=await X.storage.virtualMcps.findById(Y.id);if(G&&G.organization_id!==J.id)return{item:null};if(!G)return{item:null};return{item:G}}})});var XW8,JW8,Sk1;var $Z6=y(()=>{c0();J4();GI();XW8=q.object({id:q.string().describe("ID of the virtual MCP to update"),data:Mv.describe("Partial virtual MCP data to update")}),JW8=q.object({item:nZ.describe("The updated virtual MCP entity")}),Sk1=i0({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:XW8,outputSchema:JW8,handler:async(Y,X)=>{$6(X);let J=D6(X);await X.access.check();let G=fX(X);if(!G)throw Error("User ID required to update virtual MCP");let W=await X.storage.virtualMcps.findById(Y.id);if(!W)throw Error(`Virtual MCP not found: ${Y.id}`);if(W.organization_id!==J.id)throw Error(`Virtual MCP not found: ${Y.id}`);return{item:await X.storage.virtualMcps.update(Y.id,G,Y.data)}}})});var GW8,WW8,_k1;var FZ6=y(()=>{c0();J4();GI();GW8=q.object({id:q.string().describe("ID of the virtual MCP to delete")}),WW8=q.object({item:nZ.describe("The deleted virtual MCP entity")}),_k1=i0({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:GW8,outputSchema:WW8,handler:async(Y,X)=>{$6(X);let J=D6(X);await X.access.check();let G=await X.storage.virtualMcps.findById(Y.id);if(!G)throw Error(`Virtual MCP not found: ${Y.id}`);if(G.organization_id!==J.id)throw Error(`Virtual MCP not found: ${Y.id}`);return await X.storage.virtualMcps.delete(Y.id),{item:G}}})});var VZ6=y(()=>{QZ6();KZ6();HZ6();$Z6();FZ6()});var QW8,KW8,kk1;var zZ6=y(()=>{c0();J4();eU();QW8=q.object({virtual_mcp_id:q.string().describe("ID of the Virtual MCP to add the tool to"),data:EW6.describe("Virtual tool data")}),KW8=q.object({item:GV.describe("The created virtual tool")}),kk1=i0({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:QW8,outputSchema:KW8,handler:async(Y,X)=>{$6(X);let J=D6(X);await X.access.check();let G=await X.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!G||G.organization_id!==J.id)throw Error(`Virtual MCP not found: ${Y.virtual_mcp_id}`);let W=Y.data.connection_dependencies??[];return{item:await X.storage.virtualMcps.createVirtualTool(Y.virtual_mcp_id,Y.data,W)}}})});var HW8,$W8,vk1;var UZ6=y(()=>{c0();J4();eU();HW8=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")}),$W8=q.object({items:q.array(GV).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")}),vk1=i0({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:HW8,outputSchema:$W8,handler:async(Y,X)=>{$6(X);let J=D6(X);await X.access.check();let G=await X.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!G||G.organization_id!==J.id)return{items:[],totalCount:0,hasMore:!1};let W=await X.storage.virtualMcps.listVirtualTools(Y.virtual_mcp_id),Z=W.length,K=Y.offset??0,Q=Y.limit??100,H=W.slice(K,K+Q),$=K+Q<Z;return{items:H,totalCount:Z,hasMore:$}}})});var FW8,VW8,fk1;var BZ6=y(()=>{c0();J4();eU();FW8=q.object({virtual_mcp_id:q.string().describe("ID of the Virtual MCP"),name:q.string().describe("Name of the virtual tool to retrieve")}),VW8=q.object({item:GV.nullable().describe("The retrieved virtual tool, or null if not found")}),fk1=i0({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:FW8,outputSchema:VW8,handler:async(Y,X)=>{$6(X);let J=D6(X);await X.access.check();let G=await X.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!G||G.organization_id!==J.id)return{item:null};return{item:await X.storage.virtualMcps.getVirtualTool(Y.virtual_mcp_id,Y.name)}}})});var zW8,UW8,yk1;var qZ6=y(()=>{c0();J4();eU();zW8=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:RW6.describe("Partial virtual tool data to update")}),UW8=q.object({item:GV.describe("The updated virtual tool")}),yk1=i0({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:zW8,outputSchema:UW8,handler:async(Y,X)=>{$6(X);let J=D6(X);await X.access.check();let G=await X.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!G||G.organization_id!==J.id)throw Error(`Virtual MCP not found: ${Y.virtual_mcp_id}`);if(!await X.storage.virtualMcps.getVirtualTool(Y.virtual_mcp_id,Y.name))throw Error(`Virtual tool not found: ${Y.name}`);let Z=Y.data.connection_dependencies;return{item:await X.storage.virtualMcps.updateVirtualTool(Y.virtual_mcp_id,Y.name,Y.data,Z)}}})});var BW8,qW8,bk1;var DZ6=y(()=>{c0();J4();eU();BW8=q.object({virtual_mcp_id:q.string().describe("ID of the Virtual MCP"),name:q.string().describe("Name of the virtual tool to delete")}),qW8=q.object({item:GV.describe("The deleted virtual tool")}),bk1=i0({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:BW8,outputSchema:qW8,handler:async(Y,X)=>{$6(X);let J=D6(X);await X.access.check();let G=await X.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!G||G.organization_id!==J.id)throw Error(`Virtual MCP not found: ${Y.virtual_mcp_id}`);let W=await X.storage.virtualMcps.getVirtualTool(Y.virtual_mcp_id,Y.name);if(!W)throw Error(`Virtual tool not found: ${Y.name}`);return await X.storage.virtualMcps.deleteVirtualTool(Y.virtual_mcp_id,Y.name),{item:W}}})});var OZ6=y(()=>{zZ6();UZ6();BZ6();qZ6();DZ6()});var OW8,hk1;var LZ6=y(()=>{lw();J4();c0();OW8=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")}),hk1=i0({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(OW8).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,X)=>{await L76();let J=D6(X),W=Y.properties||Y.propertyKeys||Y.propertyPatterns||Y.propertyInValues?{properties:Y.properties,propertyKeys:Y.propertyKeys,propertyPatterns:Y.propertyPatterns,propertyInValues:Y.propertyInValues}:void 0,Z={organizationId:J.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:W},K=await X.storage.monitoring.query(Z);return{logs:K.logs.map((Q)=>({...Q,timestamp:Q.timestamp instanceof Date?Q.timestamp.toISOString():Q.timestamp})),total:K.total,offset:Y.offset,limit:Y.limit}}})});var xk1;var NZ6=y(()=>{J4();c0();xk1=i0({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,X)=>{let G={organizationId:D6(X).id,startDate:Y.startDate?new Date(Y.startDate):void 0,endDate:Y.endDate?new Date(Y.endDate):void 0},W=await X.storage.monitoring.getStats(G);return{...W,errorRatePercent:(W.errorRate*100).toFixed(2)}}})});var MZ6=y(()=>{LZ6();NZ6()});var NW8,MW8,wW8,gk1,AW8,PW8,hu,xu,TO,EW8,RW8,wZ6;var LA=y(()=>{c0();NW8=q.enum(["sum","avg","min","max","count","count_all","last"]).describe("Aggregation function to apply"),MW8=q.enum(["metric","timeseries","table"]).describe("Widget display type"),wW8=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")}),gk1=q.enum(["connection_id","connection_title","user_id","tool_name","virtual_mcp_id"]).describe("Table column to group by (takes priority over JSONPath groupBy)"),AW8=q.object({fn:NW8,groupBy:q.string().optional().describe("Optional JSONPath for grouping results"),groupByColumn:gk1.optional(),interval:q.string().optional().describe("For timeseries widgets: interval like '1h', '1d', '15m'")}),PW8=q.object({connectionIds:q.array(q.string()).optional().describe("Filter to specific connections"),toolNames:q.array(q.string()).optional().describe("Filter to specific tools")}),hu=q.object({id:q.string().describe("Unique widget identifier"),name:q.string().describe("Widget display name"),type:MW8,source:wW8,aggregation:AW8,filter:PW8.optional()}),xu=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' })")}),TO=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:xu.nullable().describe("Global filters applied to all widgets"),widgets:q.array(hu).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")}),EW8=q.object({key:q.string().describe("Group key value"),value:q.number().describe("Aggregated value for this group")}),RW8=q.object({timestamp:q.string().describe("Time bucket timestamp"),value:q.number().describe("Aggregated value for this time bucket")}),wZ6=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(EW8).optional().describe("Grouped results (when groupBy is specified)"),timeseries:q.array(RW8).optional().describe("Timeseries data (for timeseries type)")})});var uk1;var AZ6=y(()=>{J4();c0();LA();uk1=i0({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:xu.optional().describe("Global filters applied to all widgets"),widgets:q.array(hu).min(1).describe("Widget definitions (at least one required)")}),outputSchema:TO,handler:async(Y,X)=>{let J=D6(X),G=X.auth.user?.id;if(!G)throw Error("User authentication required");let W=await X.storage.monitoringDashboards.create(J.id,G,{name:Y.name,description:Y.description,filters:Y.filters,widgets:Y.widgets});return{id:W.id,organizationId:W.organizationId,name:W.name,description:W.description,filters:W.filters,widgets:W.widgets,createdBy:W.createdBy,createdAt:W.createdAt instanceof Date?W.createdAt.toISOString():W.createdAt,updatedAt:W.updatedAt instanceof Date?W.updatedAt.toISOString():W.updatedAt}}})});var mk1;var PZ6=y(()=>{J4();c0();LA();mk1=i0({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:TO.nullable(),handler:async(Y,X)=>{let J=D6(X),G=await X.storage.monitoringDashboards.get(Y.id);if(!G||G.organizationId!==J.id)return null;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 lk1;var EZ6=y(()=>{J4();c0();LA();lk1=i0({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(TO).describe("List of dashboards"),total:q.number().describe("Total number of dashboards")}),handler:async(Y,X)=>{let J=D6(X),G=await X.storage.monitoringDashboards.list(J.id);return{dashboards:G.map((W)=>({id:W.id,organizationId:W.organizationId,name:W.name,description:W.description,filters:W.filters,widgets:W.widgets,createdBy:W.createdBy,createdAt:W.createdAt instanceof Date?W.createdAt.toISOString():W.createdAt,updatedAt:W.updatedAt instanceof Date?W.updatedAt.toISOString():W.updatedAt})),total:G.length}}})});var dk1;var RZ6=y(()=>{J4();c0();LA();dk1=i0({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:xu.nullable().optional().describe("New global filters"),widgets:q.array(hu).optional().describe("New widget definitions")}),outputSchema:TO,handler:async(Y,X)=>{let J=D6(X),G=await X.storage.monitoringDashboards.get(Y.id);if(!G||G.organizationId!==J.id)throw Error(`Dashboard ${Y.id} not found`);let W={};if(Y.name!==void 0)W.name=Y.name;if(Y.description!==void 0)W.description=Y.description;if(Y.filters!==void 0)W.filters=Y.filters;if(Y.widgets!==void 0)W.widgets=Y.widgets;let Z=await X.storage.monitoringDashboards.update(Y.id,W);return{id:Z.id,organizationId:Z.organizationId,name:Z.name,description:Z.description,filters:Z.filters,widgets:Z.widgets,createdBy:Z.createdBy,createdAt:Z.createdAt instanceof Date?Z.createdAt.toISOString():Z.createdAt,updatedAt:Z.updatedAt instanceof Date?Z.updatedAt.toISOString():Z.updatedAt}}})});var ck1;var TZ6=y(()=>{J4();c0();ck1=i0({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,X)=>{let J=D6(X),G=await X.storage.monitoringDashboards.get(Y.id);if(!G||G.organizationId!==J.id)throw Error(`Dashboard ${Y.id} not found`);return await X.storage.monitoringDashboards.delete(Y.id),{success:!0}}})});var pk1;var CZ6=y(()=>{J4();c0();LA();pk1=i0({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(wZ6).describe("Widget query results"),timeRange:q.object({startDate:q.string(),endDate:q.string()}).describe("Time range used for the query")}),handler:async(Y,X)=>{let J=D6(X),G=await X.storage.monitoringDashboards.get(Y.dashboardId);if(!G||G.organizationId!==J.id)throw Error(`Dashboard ${Y.dashboardId} not found`);let W=new Date,Z=Y.timeRange?.startDate?new Date(Y.timeRange.startDate):new Date(W.getTime()-86400000),K=Y.timeRange?.endDate?new Date(Y.timeRange.endDate):W,Q=await Promise.all(G.widgets.map(async(H)=>{let $=G.filters?.propertyFilters,F=Y.propertyFilters,V=$||F?{properties:{...$,...F?.properties},propertyKeys:F?.propertyKeys,propertyPatterns:F?.propertyPatterns,propertyInValues:F?.propertyInValues}:void 0,z={connectionIds:H.filter?.connectionIds??G.filters?.connectionIds??void 0,virtualMcpIds:G.filters?.virtualMcpIds??void 0,toolNames:H.filter?.toolNames??G.filters?.toolNames??void 0,startDate:Z,endDate:K,propertyFilters:V};try{let U=await X.storage.monitoring.aggregate({organizationId:J.id,path:H.source.path,from:H.source.from,aggregation:H.aggregation.fn,groupBy:H.aggregation.groupBy,groupByColumn:H.aggregation.groupByColumn,interval:H.aggregation.interval,filters:z});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:Q,timeRange:{startDate:Z.toISOString(),endDate:K.toISOString()}}}})});var TW8,nk1;var jZ6=y(()=>{J4();c0();LA();TW8=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","count_all","last"]).describe("Aggregation function"),groupBy:q.string().optional().describe("JSONPath for grouping (table)"),groupByColumn:gk1.optional(),interval:q.string().optional().describe("Time interval for timeseries (15m, 1h, 1d)"),limit:q.number().int().positive().optional().describe("Max number of groups to return (applies to groupBy/groupByColumn, ordered by value desc)")}),filter:q.object({connectionIds:q.array(q.string()).optional(),toolNames:q.array(q.string()).optional()}).optional()}),nk1=i0({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:TW8.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"),skipCount:q.boolean().optional().describe("Skip the countMatched query to reduce database load when the count is not needed")}),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().optional().describe("Number of records that matched (omitted when skipCount is true)"),timeRange:q.object({startDate:q.string(),endDate:q.string()}).describe("Time range used for the query")}),handler:async(Y,X)=>{let J=D6(X),{widget:G,timeRange:W}=Y,Z=new Date,K=W?.startDate?new Date(W.startDate):new Date(Z.getTime()-86400000),Q=W?.endDate?new Date(W.endDate):Z,H={connectionIds:G.filter?.connectionIds,toolNames:G.filter?.toolNames,startDate:K,endDate:Q,propertyFilters:Y.propertyFilters};try{let $=Y.skipCount?void 0:await X.storage.monitoring.countMatched({organizationId:J.id,path:G.source.path,from:G.source.from,filters:H}),F=await X.storage.monitoring.aggregate({organizationId:J.id,path:G.source.path,from:G.source.from,aggregation:G.aggregation.fn,groupBy:G.aggregation.groupBy,groupByColumn:G.aggregation.groupByColumn,interval:G.aggregation.interval,limit:G.aggregation.limit,filters:H});return{value:F.value,groups:F.groups,timeseries:F.timeseries,matchedRecords:$,timeRange:{startDate:K.toISOString(),endDate:Q.toISOString()}}}catch($){return console.error("Widget preview aggregation failed:",$),{value:null,matchedRecords:void 0,timeRange:{startDate:K.toISOString(),endDate:Q.toISOString()}}}}})});var IZ6=y(()=>{AZ6();PZ6();EZ6();RZ6();TZ6();CZ6();jZ6()});var ik1;var SZ6=y(()=>{c0();J4();ik1=i0({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,X)=>{$6(X),await X.access.check();let J=fX(X);if(!J)throw Error("User ID required to create organization");let G=await X.boundAuth.organization.create({name:Y.name,slug:Y.slug,metadata:Y.description?{description:Y.description}:void 0,userId:J});if(!G)throw Error("Failed to create organization");return{...G,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt}}})});var ak1;var _Z6=y(()=>{c0();J4();ak1=i0({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,X)=>{$6(X),await X.access.check();let J=fX(X),G=Y.userId||J;if(!G)throw Error("User ID required to list organizations");return{organizations:(await X.boundAuth.organization.list(G)).map((Z)=>({...Z,createdAt:Z.createdAt instanceof Date?Z.createdAt.toISOString():Z.createdAt}))}}})});var rk1;var kZ6=y(()=>{c0();J4();rk1=i0({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,X)=>{$6(X),await X.access.check();let J=await X.boundAuth.organization.get();if(!J)throw Error("No active organization found");let G=new Date,W=J.invitations?.filter((Z)=>new Date(Z.expiresAt)>G);return{...J,invitations:W,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var ok1;var vZ6=y(()=>{c0();J4();ok1=i0({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,X)=>{$6(X),await X.access.check();let J={};if(Y.name)J.name=Y.name;if(Y.slug)J.slug=Y.slug;if(Y.description)J.metadata={description:Y.description};let G=await X.boundAuth.organization.update({organizationId:Y.id,data:J});if(!G)throw Error("Failed to update organization");return{...G,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt}}})});var sk1;var fZ6=y(()=>{c0();J4();sk1=i0({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,X)=>{return $6(X),await X.access.check(),await X.boundAuth.organization.delete(Y.id),{success:!0,id:Y.id}}})});var gu;var tk1=y(()=>{c0();gu=q.object({title:q.string(),url:q.string(),icon:q.string()})});var ek1;var yZ6=y(()=>{c0();J4();tk1();ek1=i0({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(gu).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,X)=>{$6(X),await X.access.check();let J=X.organization?.id;if(!J)throw Error("Organization ID required (no active organization in context)");let G=await X.storage.organizationSettings.get(J);if(!G)return{organizationId:J};return{...G,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}}})});var Yv1;var bZ6=y(()=>{c0();J4();tk1();Yv1=i0({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(gu).optional(),enabled_plugins:q.array(q.string()).optional()}),outputSchema:q.object({organizationId:q.string(),sidebar_items:q.array(gu).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,X)=>{if($6(X),await X.access.check(),X.organization&&X.organization.id!==Y.organizationId)throw Error("Cannot update settings for a different organization");let J=await X.storage.organizationSettings.upsert(Y.organizationId,{sidebar_items:Y.sidebar_items,enabled_plugins:Y.enabled_plugins});return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt,updatedAt:J.updatedAt instanceof Date?J.updatedAt.toISOString():J.updatedAt}}})});var Xv1;var hZ6=y(()=>{c0();J4();Xv1=i0({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,X)=>{$6(X),await X.access.check();let J=Y.organizationId||X.organization?.id;if(!J)throw Error("Organization ID required (no active organization in context)");if(J!==X.organization?.id)throw Error("Organization ID does not match authenticated organization");let G=await X.boundAuth.organization.addMember({organizationId:J,userId:Y.userId,role:Y.role});if(!G)throw Error("Failed to add member");return{...G,role:G.role,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt}}})});var Jv1;var xZ6=y(()=>{c0();J4();Jv1=i0({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,X)=>{$6(X),await X.access.check();let J=Y.organizationId||X.organization?.id;if(!J)throw Error("Organization ID required (no active organization in context)");return await X.boundAuth.organization.removeMember({organizationId:J,memberIdOrEmail:Y.memberIdOrEmail}),{success:!0,memberIdOrEmail:Y.memberIdOrEmail}}})});var Gv1;var gZ6=y(()=>{c0();J4();Gv1=i0({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,X)=>{$6(X),await X.access.check();let J=X.organization?.id;if(!J)throw Error("Organization ID required (no active organization in context)");let G=await X.boundAuth.organization.listMembers({organizationId:J,limit:Y.limit,offset:Y.offset});return{members:(Array.isArray(G)?G:[]).map((Z)=>({...Z,createdAt:Z.createdAt instanceof Date?Z.createdAt.toISOString():Z.createdAt}))}}})});var Wv1;var uZ6=y(()=>{c0();J4();Wv1=i0({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,X)=>{$6(X),await X.access.check();let J=Y.organizationId||X.organization?.id;if(!J)throw Error("Organization ID required (no active organization in context)");let G=await X.boundAuth.organization.updateMemberRole({organizationId:J,memberId:Y.memberId,role:Y.role});if(!G)throw Error("Failed to update member role");return{...G,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt}}})});var mZ6=y(()=>{SZ6();_Z6();kZ6();vZ6();fZ6();yZ6();bZ6();hZ6();xZ6();gZ6();uZ6()});var IW8,i91,SW8,XB,lZ6,a91;var CO=y(()=>{c0();IW8=q.object({banner:q.string().nullable(),bannerColor:q.string().nullable(),icon:q.string().nullable(),themeColor:q.string().nullable()}),i91=q.object({banner:q.string().nullable().optional(),bannerColor:q.string().nullable().optional(),icon:q.string().nullable().optional(),themeColor:q.string().nullable().optional()}),SW8=q.object({id:q.string(),title:q.string(),icon:q.string().nullable()}),XB=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:IW8.nullable(),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),updatedAt:q.string().datetime().describe("ISO 8601 timestamp")}),lZ6=XB.omit({organizationId:!0}).extend({boundConnections:q.array(SW8)}),a91=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 Zv1;var dZ6=y(()=>{c0();J4();CO();Zv1=i0({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(lZ6)}),handler:async(Y,X)=>{$6(X),await X.access.check();let J=await X.storage.projects.list(Y.organizationId),G=J.map((Z)=>Z.id),W=await X.storage.projectPluginConfigs.getBoundConnectionsForProjects(G);return{projects:J.map((Z)=>({id:Z.id,slug:Z.slug,name:Z.name,description:Z.description,enabledPlugins:Z.enabledPlugins,ui:Z.ui,boundConnections:W.get(Z.id)??[],createdAt:Z.createdAt instanceof Date?Z.createdAt.toISOString():Z.createdAt,updatedAt:Z.updatedAt instanceof Date?Z.updatedAt.toISOString():Z.updatedAt}))}}})});var Qv1;var cZ6=y(()=>{c0();J4();CO();Qv1=i0({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:XB.nullable()}),handler:async(Y,X)=>{$6(X),await X.access.check();let J=null;if(Y.projectId)J=await X.storage.projects.get(Y.projectId);else if(Y.slug)J=await X.storage.projects.getBySlug(Y.organizationId,Y.slug);if(!J)return{project:null};return{project:{id:J.id,organizationId:J.organizationId,slug:J.slug,name:J.name,description:J.description,enabledPlugins:J.enabledPlugins,ui:J.ui,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt,updatedAt:J.updatedAt instanceof Date?J.updatedAt.toISOString():J.updatedAt}}}})});var Kv1;var pZ6=y(()=>{c0();cY();J4();CO();Kv1=i0({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:i91.nullable().optional().describe("UI customization")}),outputSchema:q.object({project:XB}),handler:async(Y,X)=>{$6(X),await X.access.check();let{organizationId:J,slug:G,name:W,description:Z,enabledPlugins:K,ui:Q}=Y;if(G===SH)throw Error(`Slug "${SH}" is reserved`);if(await X.storage.projects.getBySlug(J,G))throw Error(`Project with slug "${G}" already exists in this organization`);let $=Q?{banner:Q.banner??null,bannerColor:Q.bannerColor??null,icon:Q.icon??null,themeColor:Q.themeColor??null}:null,F=await X.storage.projects.create({organizationId:J,slug:G,name:W,description:Z??null,enabledPlugins:K??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 Hv1;var nZ6=y(()=>{c0();J4();CO();Hv1=i0({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:i91.nullable().optional().describe("Updated UI customization")}),outputSchema:q.object({project:XB.nullable()}),handler:async(Y,X)=>{$6(X),await X.access.check();let{projectId:J,name:G,description:W,enabledPlugins:Z,ui:K}=Y,Q={};if(G!==void 0)Q.name=G;if(W!==void 0)Q.description=W;if(Z!==void 0)Q.enabledPlugins=Z;if(K!==void 0)Q.ui=K?{banner:K.banner??null,bannerColor:K.bannerColor??null,icon:K.icon??null,themeColor:K.themeColor??null}:null;let H=await X.storage.projects.update(J,Q);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 $v1;var iZ6=y(()=>{c0();cY();J4();$v1=i0({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,X)=>{$6(X),await X.access.check();let{projectId:J}=Y,G=await X.storage.projects.get(J);if(!G)return{success:!1,message:"Project not found"};if(G.slug===SH)return{success:!1,message:"Cannot delete the org-admin project"};return{success:await X.storage.projects.delete(J)}}})});var Fv1;var aZ6=y(()=>{c0();J4();CO();Fv1=i0({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:a91.nullable()}),handler:async(Y,X)=>{$6(X),await X.access.check();let{projectId:J,pluginId:G}=Y,W=await X.storage.projectPluginConfigs.get(J,G);if(!W)return{config:null};return{config:{id:W.id,projectId:W.projectId,pluginId:W.pluginId,connectionId:W.connectionId,settings:W.settings,createdAt:W.createdAt instanceof Date?W.createdAt.toISOString():W.createdAt,updatedAt:W.updatedAt instanceof Date?W.updatedAt.toISOString():W.updatedAt}}}})});var Vv1;var rZ6=y(()=>{c0();J4();CO();x91();SD();Vv1=i0({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:a91}),handler:async(Y,X)=>{$6(X),await X.access.check();let{projectId:J,pluginId:G,connectionId:W,settings:Z}=Y,K=fX(X),Q=await X.storage.projects.get(J);if(!Q)throw Error(`Project not found: ${J}`);let H=W?await X.storage.connections.findById(W):null;if(W&&Q.organizationId&&!H&&rj()){if(h91(W,Q.organizationId)){if(!K)throw Error("User ID required to create dev-assets connection");let F=oj(Q.organizationId,TQ());await X.storage.connections.create({...F,organization_id:Q.organizationId,created_by:K})}}let $=await X.storage.projectPluginConfigs.upsert(J,G,{connectionId:W,settings:Z});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 _W8,zv1;var oZ6=y(()=>{c0();J4();_W8=q.object({id:q.string(),title:q.string(),icon:q.string().nullable(),connectionType:q.string(),status:q.string()}),zv1=i0({name:"PROJECT_CONNECTION_LIST",description:"List connections associated with a project",annotations:{title:"List Project Connections",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({projectId:q.string().describe("Project ID")}),outputSchema:q.object({connections:q.array(_W8)}),handler:async(Y,X)=>{$6(X);let J=D6(X);await X.access.check();let{projectId:G}=Y,W=await X.storage.projects.get(G);if(!W||W.organizationId!==J.id)throw Error(`Project not found: ${G}`);let Z=await X.storage.projectConnections.list(G);return{connections:(await Promise.all(Z.map((H)=>X.storage.connections.findById(H.connectionId)))).filter((H)=>H!=null).map((H)=>({id:H.id,title:H.title,icon:H.icon??null,connectionType:H.connection_type,status:H.status}))}}})});var Uv1;var sZ6=y(()=>{c0();J4();Uv1=i0({name:"PROJECT_CONNECTION_ADD",description:"Associate a connection with a project",annotations:{title:"Add Project Connection",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({projectId:q.string().describe("Project ID"),connectionId:q.string().describe("Connection ID to associate")}),outputSchema:q.object({success:q.boolean(),projectConnectionId:q.string()}),handler:async(Y,X)=>{$6(X);let J=D6(X);await X.access.check();let{projectId:G,connectionId:W}=Y,Z=await X.storage.projects.get(G);if(!Z||Z.organizationId!==J.id)throw Error(`Project not found: ${G}`);let K=await X.storage.connections.findById(W);if(!K||K.organization_id!==J.id)throw Error(`Connection not found: ${W}`);return{success:!0,projectConnectionId:(await X.storage.projectConnections.add(G,W)).id}}})});var Bv1;var tZ6=y(()=>{c0();J4();Bv1=i0({name:"PROJECT_CONNECTION_REMOVE",description:"Remove a connection association from a project",annotations:{title:"Remove Project Connection",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({projectId:q.string().describe("Project ID"),connectionId:q.string().describe("Connection ID to disassociate")}),outputSchema:q.object({success:q.boolean()}),handler:async(Y,X)=>{$6(X);let J=D6(X);await X.access.check();let{projectId:G,connectionId:W}=Y,Z=await X.storage.projects.get(G);if(!Z||Z.organizationId!==J.id)throw Error(`Project not found: ${G}`);let K=await X.storage.connections.findById(W);if(!K||K.organization_id!==J.id)throw Error(`Connection not found: ${W}`);let Q=await X.storage.projectConnections.remove(G,W);if(Z?.ui?.pinnedViews?.length){let H=Z.ui.pinnedViews.filter(($)=>$.connectionId!==W);if(H.length!==Z.ui.pinnedViews.length){let $={...Z.ui,pinnedViews:H.length>0?H:null};await X.storage.projects.update(G,{ui:$})}}return{success:Q}}})});var kW8,qv1;var eZ6=y(()=>{c0();J4();CO();kW8=q.object({connectionId:q.string(),toolName:q.string(),label:q.string(),icon:q.string().nullable()}),qv1=i0({name:"PROJECT_PINNED_VIEWS_UPDATE",description:"Update the pinned sidebar views for a project",annotations:{title:"Update Pinned Views",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({projectId:q.string().describe("Project ID"),pinnedViews:q.array(kW8).describe("Pinned views to set for the project sidebar")}),outputSchema:q.object({project:XB.nullable()}),handler:async(Y,X)=>{$6(X),await X.access.check();let{projectId:J,pinnedViews:G}=Y,W=await X.storage.projects.get(J);if(!W)throw Error(`Project not found: ${J}`);let K={...W.ui??{banner:null,bannerColor:null,icon:null,themeColor:null},pinnedViews:G.length>0?G:null},Q=await X.storage.projects.update(J,{ui:K});if(!Q)return{project:null};return{project:{id:Q.id,organizationId:Q.organizationId,slug:Q.slug,name:Q.name,description:Q.description,enabledPlugins:Q.enabledPlugins,ui:Q.ui,createdAt:Q.createdAt instanceof Date?Q.createdAt.toISOString():Q.createdAt,updatedAt:Q.updatedAt instanceof Date?Q.updatedAt.toISOString():Q.updatedAt}}}})});var YQ6=y(()=>{dZ6();cZ6();pZ6();nZ6();iZ6();aZ6();rZ6();oZ6();sZ6();tZ6();eZ6()});var Dv1;var XQ6=y(()=>{c0();J4();Dv1=i0({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,X)=>{$6(X),await X.access.check();let J=D6(X);return{tags:(await X.storage.tags.listOrgTags(J.id)).map((W)=>({...W,createdAt:W.createdAt instanceof Date?W.createdAt.toISOString():String(W.createdAt)}))}}})});var Ov1;var JQ6=y(()=>{c0();J4();Ov1=i0({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,X)=>{$6(X),await X.access.check();let J=D6(X),G=await X.storage.tags.createTag(J.id,Y.name);return{tag:{...G,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():String(G.createdAt)}}}})});var Lv1;var GQ6=y(()=>{c0();J4();Lv1=i0({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,X)=>{$6(X),await X.access.check();let J=D6(X),G=await X.storage.tags.getTag(Y.tagId);if(!G)throw Error("Tag not found");if(G.organizationId!==J.id)throw Error("Tag does not belong to this organization");return await X.storage.tags.deleteTag(Y.tagId),{success:!0}}})});var Nv1;var WQ6=y(()=>{c0();J4();Nv1=i0({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,X)=>{$6(X),await X.access.check();let J=D6(X);if(!await X.storage.tags.verifyMemberOrg(Y.memberId,J.id))throw Error(`Member not found in this organization: ${Y.memberId}`);return{tags:(await X.storage.tags.getMemberTags(Y.memberId)).map((Z)=>({...Z,createdAt:Z.createdAt instanceof Date?Z.createdAt.toISOString():String(Z.createdAt)}))}}})});var Mv1;var ZQ6=y(()=>{c0();J4();Mv1=i0({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,X)=>{$6(X),await X.access.check();let J=D6(X);if(!await X.storage.tags.verifyMemberOrg(Y.memberId,J.id))throw Error(`Member not found in this organization: ${Y.memberId}`);for(let Z of Y.tagIds){let K=await X.storage.tags.getTag(Z);if(!K)throw Error(`Tag not found: ${Z}`);if(K.organizationId!==J.id)throw Error(`Tag does not belong to this organization: ${Z}`)}return await X.storage.tags.setMemberTags(Y.memberId,Y.tagIds),{success:!0,tags:(await X.storage.tags.getMemberTags(Y.memberId)).map((Z)=>({...Z,createdAt:Z.createdAt instanceof Date?Z.createdAt.toISOString():String(Z.createdAt)}))}}})});var QQ6=y(()=>{XQ6();JQ6();GQ6();WQ6();ZQ6()});var KQ6=y(()=>{cY()});var HQ6,WV,$Q6,FQ6;var NA=y(()=>{c0();KQ6();HQ6=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")}),WV=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([...YE,"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")}),$Q6=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")}),FQ6=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 yW8,bW8,wv1;var VQ6=y(()=>{c0();J4();NA();fQ();yW8=q.object({data:$Q6.describe("Data for the new thread (id is auto-generated if not provided)")}),bW8=q.object({item:WV.describe("The created thread entity")}),wv1=i0({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:yW8,outputSchema:bW8,handler:async(Y,X)=>{$6(X);let J=D6(X);await X.access.check();let G=fX(X);if(!G)throw Error("User ID required to create thread");let W=Y.data.id??e9("thrd"),Z=await X.storage.threads.create({id:W,organization_id:J.id,title:Y.data.title,description:Y.data.description,created_by:G});return{item:{...Z,hidden:Z.hidden??!1}}}})});function jO(Y,X=Date.now()){let J=Y.status;if(J==="in_progress"){let G=new Date(Y.updated_at).getTime();if(!Number.isFinite(G)||X-G>1800000)J="expired"}return{...Y,status:J,hidden:Y.hidden??!1}}var hW8,xW8,Av1;var zQ6=y(()=>{YZ();J4();NA();c0();hW8=W3.extend({where:q.object({created_by:q.string().optional()}).optional()}),xW8=wz(WV),Av1=i0({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:hW8,outputSchema:xW8,handler:async(Y,X)=>{if(await X.access.check(),!X.auth.user?.id)throw Error("User ID required to list threads");D6(X);let G=Y.offset??0,W=Y.limit??100,Z=Y.where?.created_by,{threads:K,total:Q}=await X.storage.threads.list(Z,{limit:W,offset:G}),H=G+W<Q,$=Date.now();return{items:K.map((F)=>jO(F,$)),totalCount:Q,hasMore:H}}})});var gW8,Pv1;var UQ6=y(()=>{YZ();J4();NA();gW8=Sf(WV),Pv1=i0({name:"COLLECTION_THREADS_GET",description:"Get thread details by ID",annotations:{title:"Get Thread",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:If,outputSchema:gW8,handler:async(Y,X)=>{$6(X),D6(X),await X.access.check();let J=await X.storage.threads.get(Y.id);if(!J)return{item:null};return{item:jO(J)}}})});var uW8,mW8,Ev1;var BQ6=y(()=>{c0();J4();NA();uW8=q.object({id:q.string().describe("ID of the thread to update"),data:FQ6.describe("Partial thread data to update")}),mW8=q.object({item:WV.describe("The updated thread entity")}),Ev1=i0({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:uW8,outputSchema:mW8,handler:async(Y,X)=>{$6(X),D6(X),await X.access.check();let J=fX(X);if(!J)throw Error("User ID required to update thread");let{id:G,data:W}=Y;if(!await X.storage.threads.get(G))throw Error("Thread not found in organization");let K=await X.storage.threads.update(G,{title:W.title,description:W.description,hidden:W.hidden,updated_by:J});return{item:jO(K)}}})});var Rv1;var qQ6=y(()=>{YZ();J4();NA();Rv1=i0({name:"COLLECTION_THREADS_DELETE",description:"Delete a thread",annotations:{title:"Delete Thread",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:_f,outputSchema:kf(WV),handler:async(Y,X)=>{$6(X),D6(X),await X.access.check();let J=await X.storage.threads.get(Y.id);if(!J)throw Error(`Thread not found: ${Y.id}`);return await X.storage.threads.delete(Y.id),{item:jO(J)}}})});function DQ6(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 X of Y.conditions){let J=DQ6(X);if(J)return J}return null}var lW8,Tv1;var OQ6=y(()=>{YZ();J4();NA();lW8=wz(HQ6),Tv1=i0({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:W3,outputSchema:lW8,handler:async(Y,X)=>{D6(X),await X.access.check();let J=DQ6(Y.where);if(!J)throw Error("thread_id filter is required in where clause");let G=Y.offset??0,W=Y.limit??100,{messages:Z,total:K}=await X.storage.threads.listMessages(J,{limit:W,offset:G}),Q=G+W<K;return{items:Z,totalCount:K,hasMore:Q}}})});var LQ6=y(()=>{VQ6();zQ6();UQ6();BQ6();qQ6();OQ6()});var cW8,pW8,Cv1;var NQ6=y(()=>{c0();J4();cW8=q.object({id:q.string().min(1)}),pW8=q.object({user:q.object({id:q.string(),name:q.string(),email:q.string(),image:q.string().nullable()}).nullable()}),Cv1=i0({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:cW8,outputSchema:pW8,handler:async(Y,X)=>{await X.access.check(),$6(X);let J=fX(X);if(!J)throw Error("Authentication required");let G=await X.storage.users.findById(Y.id,J);if(!G)return{user:null};return{user:{id:G.id,name:G.name,email:G.email,image:G.image??null}}}})});var MQ6=y(()=>{NQ6()});var AQ6={};L4(AQ6,{managementMCP:()=>jv1,ALL_TOOLS:()=>wQ6});var iW8,aW8,wQ6,jv1=async(Y)=>{let X=null;if(Y.organization){let W=await Y.storage.organizationSettings.get(Y.organization.id),Z=await Y.storage.projects.list(Y.organization.id),K=new Set(W?.enabled_plugins??[]);for(let Q of Z)if(Q.enabledPlugins)for(let H of Q.enabledPlugins)K.add(H);X=K.size>0?[...K]:null}let J=R30(wQ6,X),G=new Wz({name:"mcp-mesh-management",version:"1.0.0"},{capabilities:{tools:{}}});for(let W of J){let Z=W.inputSchema&&typeof W.inputSchema==="object"&&"shape"in W.inputSchema?W.inputSchema:q.object({}),K=W.outputSchema&&typeof W.outputSchema==="object"&&"shape"in W.outputSchema?W.outputSchema:void 0,Q=Z.shape,H=K?.shape;G.registerTool(W.name,{description:W.description??"",inputSchema:Q,outputSchema:H,annotations:W.annotations,_meta:W._meta},async($)=>{Y.access.setToolName(W.name);try{let F=await W.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 G};var Iv1=y(()=>{ZT();Pv();c0();vG6();oG6();cW6();aW6();WZ6();VZ6();OZ6();MZ6();IZ6();mZ6();YQ6();QQ6();LQ6();MQ6();iW8=[ik1,ak1,rk1,ok1,sk1,ek1,Yv1,Xv1,Jv1,Gv1,Wv1,d_1,n_1,i_1,Dk1,Ok1,Lk1,Tk1,jk1,Ik1,Sk1,_k1,kk1,vk1,fk1,yk1,bk1,iW6,hk1,xk1,uk1,mk1,lk1,dk1,ck1,pk1,nk1,k_1,f_1,y_1,v_1,Nk1,Mk1,wk1,Ak1,Pk1,Ek1,Rk1,Cv1,u_1,m_1,l_1,wv1,Av1,Pv1,Ev1,Rv1,Tv1,Dv1,Ov1,Lv1,Nv1,Mv1,Zv1,Qv1,Kv1,Hv1,$v1,Fv1,Vv1,zv1,Uv1,Bv1,qv1],aW8=T30(),wQ6=[...iW8,...aW8]});function rW8(Y){return[{permissions:{self:["*"]},getTools:async()=>{let{ALL_TOOLS:X}=await Promise.resolve().then(() => (Iv1(),AQ6));return X.map((J)=>{return{name:J.name,inputSchema:q.toJSONSchema(J.inputSchema,{unrepresentable:"any"}),outputSchema:J.outputSchema?q.toJSONSchema(J.outputSchema,{unrepresentable:"any"}):void 0,description:J.description}})},data:p$1(TQ(),Y)},{data:c$1()},{data:d$1(Y)}]}async function PQ6(Y,X){try{let J=sK(),G=new zA(Q4.ENCRYPTION_KEY),W=new Mu(J.db,G),Z=new wu(J.db),K=rW8(Y);try{await Z.create({organizationId:Y,slug:SH,name:d2,description:"Organization administration and settings",enabledPlugins:null,ui:null})}catch(Q){console.warn("Could not create org-admin project (may already exist):",Q)}await Promise.all(K.map(async(Q)=>{let H=null;if(Q.permissions)H=(await jZ.api.createApiKey({body:{name:`${Q.data.app_name??crypto.randomUUID()}-mcp`,userId:X,permissions:Q.permissions,rateLimitEnabled:!1,metadata:{organization:{id:Y},purpose:"default-org-connections"}}}))?.key;let $=await nj({id:"pending",title:Q.data.title,connection_type:Q.data.connection_type,connection_url:Q.data.connection_url,connection_token:Q.data.connection_token,connection_headers:Q.data.connection_headers}).catch(()=>null),F=await Q.getTools?.()??$?.tools??null,V=$?.scopes?.length?$.scopes:null,z=Q.data.id?Q.data.id.startsWith(`${Y}_`)?Q.data.id:`${Y}_${Q.data.id}`:void 0;await W.create({...Q.data,id:z,tools:F,configuration_scopes:V,organization_id:Y,created_by:X,connection_token:Q.data.connection_token??H})}))}catch(J){console.error("Error creating default MCP connections:",J)}}var EQ6=y(()=>{cY();SD();dj();T91();O_1();L_1();I91();c0();_5();AO()});var Sv1,r91;var o91=y(()=>{Sv1=["owner","admin","user"],r91=["owner","admin"]});var oW8=(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"}}}}]}},RQ6=(Y)=>{if(Y.providerId==="microsoft")return oW8(Y);throw Error(`Unsupported provider: ${Y.providerId}`)};var SQ6={};L4(SQ6,{resetPasswordEnabled:()=>t91,authConfig:()=>bY,auth:()=>jZ});function sW8(Y){return Y.toLowerCase().trim().replace(/[^a-z0-9\s_-]+/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function tW8(){let Y=Math.floor(Math.random()*CQ6.length),X=Math.floor(Math.random()*TQ6.length),J=CQ6[Y]??"deco",G=TQ6[X]??"studio";return`${J}-${G}`}function KZ8(){let Y=[uu],X=new URL(uu);if(X.hostname==="localhost")Y.push(uu.replace("localhost","127.0.0.1"));else if(X.hostname==="127.0.0.1")Y.push(uu.replace("127.0.0.1","localhost"));return Y}var TQ6,CQ6,eW8,YZ8,s91,XZ8,JZ8,GZ8,jQ6,bY,IQ6=void 0,_v1=void 0,t91=!1,WZ8,ZZ8,QZ8,uu,jZ;var AO=y(()=>{_5();XM1();lq0();EO0();ew1();M21();DL0();K01();SD();RL0();dj();D_1();E76();EQ6();o91();TQ6=["labs","agent","studio","workspace","systems","core","cloud","works"],CQ6=["capybara","guarana","deco","samba","feijoada","capoeira","carnival"];eW8=Object.values(Cb()).map((Y)=>Y.map((X)=>X.name)).flat(),YZ8={...p11,self:["*",...eW8]},s91=_F(YZ8),XZ8=s91.newRole({self:["*"],..._h.statements}),JZ8=s91.newRole({self:["*"],..._h.statements}),GZ8=s91.newRole({self:["*"],..._h.statements}),jQ6=Object.values(Cb()).map((Y)=>Y.map((X)=>`self:${X.name}`)).flat(),bY=uh.auth;if(bY.inviteEmailProviderId&&bY.emailProviders&&bY.emailProviders.length>0){let Y=Lu(bY.emailProviders,bY.inviteEmailProviderId);if(Y){let X=Ou(Y);IQ6=async(J)=>{let G=J.inviter.user?.name||J.inviter.user?.email,W=`${TQ()}/auth/accept-invitation?invitationId=${J.invitation.id}&redirectTo=/`;await X({to:J.email,subject:`Invitation to join ${J.organization.name}`,html:`
|
|
1958
|
+
`.execute(Y)).rows[0]?.exists)await E0`CREATE ROLE ${E0.id(J)} NOLOGIN`.execute(Y);await E0`GRANT ${E0.id(J)} TO CURRENT_USER`.execute(Y),await E0`GRANT USAGE, CREATE ON SCHEMA ${E0.id(X)} TO ${E0.id(J)}`.execute(Y),await E0`GRANT ALL ON ALL TABLES IN SCHEMA ${E0.id(X)} TO ${E0.id(J)}`.execute(Y),await E0`GRANT ALL ON ALL SEQUENCES IN SCHEMA ${E0.id(X)} TO ${E0.id(J)}`.execute(Y),await E0`ALTER DEFAULT PRIVILEGES IN SCHEMA ${E0.id(X)} GRANT ALL ON TABLES TO ${E0.id(J)}`.execute(Y),await E0`ALTER DEFAULT PRIVILEGES IN SCHEMA ${E0.id(X)} GRANT ALL ON SEQUENCES TO ${E0.id(J)}`.execute(Y),await E0`REVOKE ALL ON SCHEMA public FROM ${E0.id(J)}`.execute(Y)}async function lG8(Y,X,J,G){try{return await Y.transaction().execute(async(W)=>{return await E0`SET LOCAL ROLE ${E0.id(J)}`.execute(W),await E0`SET LOCAL search_path TO ${E0.id(X)}`.execute(W),await E0.raw(G).execute(W)})}catch(W){if(uG8(W))return await mG8(Y,X,J),await Y.transaction().execute(async(Z)=>{return await E0`SET LOCAL ROLE ${E0.id(J)}`.execute(Z),await E0`SET LOCAL search_path TO ${E0.id(X)}`.execute(Z),await E0.raw(G).execute(Z)});throw W}}var yG8,hG8,iW6;var aW6=y(()=>{F9();c0();J4();yG8=q.object({results:q.array(q.unknown()).optional(),success:q.boolean().optional()});hG8=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()});iW6=i0({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:hG8,outputSchema:q.object({result:q.array(yG8)}),handler:async(Y,X)=>{$6(X),await X.access.check();let J=bG8(Y.sql,Y.params||[]);if(!X.connectionId)throw Error("Connection context required for database access");let G=xG8(X.connectionId),W=gG8(X.connectionId);return{result:[{results:(await lG8(X.db,G,W,J)).rows,success:!0}]}}})});var rW6,cG8,oW6;var YB=y(()=>{c0();af();rW6=q.object({connectionId:q.string().optional().describe("Filter subscriptions by connection ID (optional)")}),cG8=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)")}),oW6=q.object({subscriptions:q.array(cG8).describe("List of subscriptions")})});var Nk1;var sW6=y(()=>{J4();YB();Nk1=i0({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:vf,outputSchema:ff,handler:async(Y,X)=>{$6(X);let J=D6(X);await X.access.check();let G=X.connectionId;if(!G)throw Error("Connection ID required to publish events. Use a connection-scoped token.");let W=await X.eventBus.publish(J.id,G,{type:Y.type,subject:Y.subject,data:Y.data,deliverAt:Y.deliverAt,cron:Y.cron});return{id:W.id,type:W.type,source:W.source,time:W.time}}})});var Mk1;var tW6=y(()=>{J4();YB();Mk1=i0({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:yf,outputSchema:bf,handler:async(Y,X)=>{$6(X);let J=D6(X);await X.access.check();let G=X.connectionId;if(!G)throw Error("Connection ID required to subscribe. Use a connection-scoped token.");let W=await X.eventBus.subscribe(J.id,{connectionId:G,eventType:Y.eventType,publisher:Y.publisher,filter:Y.filter});return{subscription:{id:W.id,connectionId:W.connectionId,eventType:W.eventType,publisher:W.publisher,filter:W.filter,enabled:W.enabled,createdAt:W.createdAt instanceof Date?W.createdAt.toISOString():W.createdAt,updatedAt:W.updatedAt instanceof Date?W.updatedAt.toISOString():W.updatedAt}}}})});var wk1;var eW6=y(()=>{J4();YB();wk1=i0({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:gf,outputSchema:uf,handler:async(Y,X)=>{$6(X);let J=D6(X);await X.access.check();let G=X.connectionId;if(!G)throw Error("Connection ID required to unsubscribe. Use a connection-scoped token.");let W=await X.eventBus.getSubscription(J.id,Y.subscriptionId);if(!W)throw Error(`Subscription not found: ${Y.subscriptionId}`);if(W.connectionId!==G)throw Error("Cannot unsubscribe from a subscription owned by another connection");return{success:(await X.eventBus.unsubscribe(J.id,Y.subscriptionId)).success,subscriptionId:Y.subscriptionId}}})});var Ak1;var YZ6=y(()=>{J4();YB();Ak1=i0({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:mf,outputSchema:lf,handler:async(Y,X)=>{$6(X);let J=D6(X);await X.access.check();let G=X.connectionId;if(!G)throw Error("Connection ID required to cancel events. Use a connection-scoped token.");if(!await X.eventBus.getEvent(J.id,Y.eventId))throw Error(`Event not found: ${Y.eventId}`);if(!(await X.eventBus.cancelEvent(J.id,Y.eventId,G)).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 Pk1;var XZ6=y(()=>{J4();YB();Pk1=i0({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:df,outputSchema:cf,handler:async(Y,X)=>{$6(X);let J=D6(X);await X.access.check();let G=X.connectionId;if(!G)throw Error("Connection ID required to acknowledge events. Use a connection-scoped token.");if(!(await X.eventBus.ackEvent(J.id,Y.eventId,G)).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 Ek1;var JZ6=y(()=>{J4();YB();Ek1=i0({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:rW6,outputSchema:oW6,handler:async(Y,X)=>{$6(X);let J=D6(X);return await X.access.check(),{subscriptions:(await X.eventBus.listSubscriptions(J.id,Y.connectionId)).map((W)=>({id:W.id,connectionId:W.connectionId,eventType:W.eventType,publisher:W.publisher,filter:W.filter,enabled:W.enabled,createdAt:W.createdAt instanceof Date?W.createdAt.toISOString():W.createdAt,updatedAt:W.updatedAt instanceof Date?W.updatedAt.toISOString():W.updatedAt}))}}})});var Rk1;var GZ6=y(()=>{J4();YB();Rk1=i0({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:hf,outputSchema:xf,handler:async(Y,X)=>{$6(X);let J=D6(X);await X.access.check();let G=X.connectionId;if(!G)throw Error("Connection ID required to sync subscriptions. Use a connection-scoped token.");let W=await X.eventBus.syncSubscriptions(J.id,{connectionId:G,subscriptions:Y.subscriptions});return{created:W.created,updated:W.updated,deleted:W.deleted,unchanged:W.unchanged,subscriptions:W.subscriptions.map((Z)=>({id:Z.id,connectionId:Z.connectionId,eventType:Z.eventType,publisher:Z.publisher,filter:Z.filter,enabled:Z.enabled,createdAt:Z.createdAt instanceof Date?Z.createdAt.toISOString():Z.createdAt,updatedAt:Z.updatedAt instanceof Date?Z.updatedAt.toISOString():Z.updatedAt}))}}})});var WZ6=y(()=>{sW6();tW6();eW6();YZ6();XZ6();JZ6();GZ6();YB()});var GI=y(()=>{Da()});function ZZ6(){return`/icons/capy-${Math.floor(Math.random()*39)+0}.png`}var nG8,iG8,Tk1;var QZ6=y(()=>{c0();J4();GI();nG8=q.object({data:Nv.describe("Data for the new virtual MCP")}),iG8=q.object({item:nZ.describe("The created virtual MCP entity")}),Tk1=i0({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:nG8,outputSchema:iG8,handler:async(Y,X)=>{$6(X);let J=D6(X);await X.access.check();let G=fX(X);if(!G)throw Error("User ID required to create virtual MCP");let W={...Y.data,icon:Y.data.icon??ZZ6()};return{item:await X.storage.virtualMcps.create(J.id,G,W)}}})});function aG8(Y){let X=[],J=0;while(J<Y.length){let G=Y[J];if(G==="%")X.push(".*");else if(G==="_")X.push(".");else if(/[.*+?^${}()|[\]\\]/.test(G))X.push("\\"+G);else X.push(G);J++}return X.join("")}function RO(Y){return typeof Y==="string"||typeof Y==="number"}function Ck1(Y,X){let J=X.split("."),G=Y;for(let W of J){if(G==null||typeof G!=="object")return;G=G[W]}return G}function rG8(Y,X){return Y.connections.some((J)=>J.connection_id===X)}function n91(Y,X){if("conditions"in X){let{operator:Q,conditions:H}=X;switch(Q){case"and":return H.every(($)=>n91(Y,$));case"or":return H.some(($)=>n91(Y,$));case"not":return!H.every(($)=>n91(Y,$));default:return!0}}let{field:J,operator:G,value:W}=X,Z=J.join(".");if(Z==="connection_id"){if(G!=="eq"||typeof W!=="string")return!1;return rG8(Y,W)}let K=Ck1(Y,Z);switch(G){case"eq":return K===W;case"gt":return RO(K)&&RO(W)&&K>W;case"gte":return RO(K)&&RO(W)&&K>=W;case"lt":return RO(K)&&RO(W)&&K<W;case"lte":return RO(K)&&RO(W)&&K<=W;case"in":return Array.isArray(W)&&W.includes(K);case"like":if(typeof K!=="string"||typeof W!=="string")return!1;if(W.length>100)return!1;let Q=aG8(W);return new RegExp(`^${Q}$`,"i").test(K);case"contains":if(typeof K!=="string"||typeof W!=="string")return!1;return K.toLowerCase().includes(W.toLowerCase());default:return!0}}function oG8(Y,X){return[...Y].sort((J,G)=>{for(let W of X){let Z=W.field.join("."),K=Ck1(J,Z),Q=Ck1(G,Z),H=0;if(K==null&&Q==null)continue;if(K==null)H=W.nulls==="first"?-1:1;else if(Q==null)H=W.nulls==="first"?1:-1;else if(typeof K==="string"&&typeof Q==="string")H=K.localeCompare(Q);else if(typeof K==="number"&&typeof Q==="number")H=K-Q;else H=String(K).localeCompare(String(Q));if(H!==0)return W.direction==="desc"?-H:H}return 0})}var sG8,tG8,jk1;var KZ6=y(()=>{YZ();J4();GI();sG8=W3,tG8=wz(nZ),jk1=i0({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:sG8,outputSchema:tG8,handler:async(Y,X)=>{await X.access.check();let J=D6(X),G=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,Z=G?await X.storage.virtualMcps.listByConnectionId(J.id,G):await X.storage.virtualMcps.list(J.id);if(Y.where)Z=Z.filter((V)=>n91(V,Y.where));if(Y.orderBy&&Y.orderBy.length>0)Z=oG8(Z,Y.orderBy);let K=Z.length,Q=Y.offset??0,H=Y.limit??100,$=Z.slice(Q,Q+H),F=Q+H<K;return{items:$,totalCount:K,hasMore:F}}})});var eG8,YW8,Ik1;var HZ6=y(()=>{c0();J4();GI();eG8=q.object({id:q.string().describe("ID of the virtual MCP to retrieve")}),YW8=q.object({item:nZ.nullable().describe("The retrieved virtual MCP, or null if not found")}),Ik1=i0({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:eG8,outputSchema:YW8,handler:async(Y,X)=>{$6(X);let J=D6(X);await X.access.check();let G=await X.storage.virtualMcps.findById(Y.id);if(G&&G.organization_id!==J.id)return{item:null};if(!G)return{item:null};return{item:G}}})});var XW8,JW8,Sk1;var $Z6=y(()=>{c0();J4();GI();XW8=q.object({id:q.string().describe("ID of the virtual MCP to update"),data:Mv.describe("Partial virtual MCP data to update")}),JW8=q.object({item:nZ.describe("The updated virtual MCP entity")}),Sk1=i0({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:XW8,outputSchema:JW8,handler:async(Y,X)=>{$6(X);let J=D6(X);await X.access.check();let G=fX(X);if(!G)throw Error("User ID required to update virtual MCP");let W=await X.storage.virtualMcps.findById(Y.id);if(!W)throw Error(`Virtual MCP not found: ${Y.id}`);if(W.organization_id!==J.id)throw Error(`Virtual MCP not found: ${Y.id}`);return{item:await X.storage.virtualMcps.update(Y.id,G,Y.data)}}})});var GW8,WW8,_k1;var FZ6=y(()=>{c0();J4();GI();GW8=q.object({id:q.string().describe("ID of the virtual MCP to delete")}),WW8=q.object({item:nZ.describe("The deleted virtual MCP entity")}),_k1=i0({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:GW8,outputSchema:WW8,handler:async(Y,X)=>{$6(X);let J=D6(X);await X.access.check();let G=await X.storage.virtualMcps.findById(Y.id);if(!G)throw Error(`Virtual MCP not found: ${Y.id}`);if(G.organization_id!==J.id)throw Error(`Virtual MCP not found: ${Y.id}`);return await X.storage.virtualMcps.delete(Y.id),{item:G}}})});var VZ6=y(()=>{QZ6();KZ6();HZ6();$Z6();FZ6()});var QW8,KW8,kk1;var zZ6=y(()=>{c0();J4();eU();QW8=q.object({virtual_mcp_id:q.string().describe("ID of the Virtual MCP to add the tool to"),data:EW6.describe("Virtual tool data")}),KW8=q.object({item:GV.describe("The created virtual tool")}),kk1=i0({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:QW8,outputSchema:KW8,handler:async(Y,X)=>{$6(X);let J=D6(X);await X.access.check();let G=await X.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!G||G.organization_id!==J.id)throw Error(`Virtual MCP not found: ${Y.virtual_mcp_id}`);let W=Y.data.connection_dependencies??[];return{item:await X.storage.virtualMcps.createVirtualTool(Y.virtual_mcp_id,Y.data,W)}}})});var HW8,$W8,vk1;var UZ6=y(()=>{c0();J4();eU();HW8=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")}),$W8=q.object({items:q.array(GV).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")}),vk1=i0({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:HW8,outputSchema:$W8,handler:async(Y,X)=>{$6(X);let J=D6(X);await X.access.check();let G=await X.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!G||G.organization_id!==J.id)return{items:[],totalCount:0,hasMore:!1};let W=await X.storage.virtualMcps.listVirtualTools(Y.virtual_mcp_id),Z=W.length,K=Y.offset??0,Q=Y.limit??100,H=W.slice(K,K+Q),$=K+Q<Z;return{items:H,totalCount:Z,hasMore:$}}})});var FW8,VW8,fk1;var BZ6=y(()=>{c0();J4();eU();FW8=q.object({virtual_mcp_id:q.string().describe("ID of the Virtual MCP"),name:q.string().describe("Name of the virtual tool to retrieve")}),VW8=q.object({item:GV.nullable().describe("The retrieved virtual tool, or null if not found")}),fk1=i0({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:FW8,outputSchema:VW8,handler:async(Y,X)=>{$6(X);let J=D6(X);await X.access.check();let G=await X.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!G||G.organization_id!==J.id)return{item:null};return{item:await X.storage.virtualMcps.getVirtualTool(Y.virtual_mcp_id,Y.name)}}})});var zW8,UW8,yk1;var qZ6=y(()=>{c0();J4();eU();zW8=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:RW6.describe("Partial virtual tool data to update")}),UW8=q.object({item:GV.describe("The updated virtual tool")}),yk1=i0({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:zW8,outputSchema:UW8,handler:async(Y,X)=>{$6(X);let J=D6(X);await X.access.check();let G=await X.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!G||G.organization_id!==J.id)throw Error(`Virtual MCP not found: ${Y.virtual_mcp_id}`);if(!await X.storage.virtualMcps.getVirtualTool(Y.virtual_mcp_id,Y.name))throw Error(`Virtual tool not found: ${Y.name}`);let Z=Y.data.connection_dependencies;return{item:await X.storage.virtualMcps.updateVirtualTool(Y.virtual_mcp_id,Y.name,Y.data,Z)}}})});var BW8,qW8,bk1;var DZ6=y(()=>{c0();J4();eU();BW8=q.object({virtual_mcp_id:q.string().describe("ID of the Virtual MCP"),name:q.string().describe("Name of the virtual tool to delete")}),qW8=q.object({item:GV.describe("The deleted virtual tool")}),bk1=i0({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:BW8,outputSchema:qW8,handler:async(Y,X)=>{$6(X);let J=D6(X);await X.access.check();let G=await X.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!G||G.organization_id!==J.id)throw Error(`Virtual MCP not found: ${Y.virtual_mcp_id}`);let W=await X.storage.virtualMcps.getVirtualTool(Y.virtual_mcp_id,Y.name);if(!W)throw Error(`Virtual tool not found: ${Y.name}`);return await X.storage.virtualMcps.deleteVirtualTool(Y.virtual_mcp_id,Y.name),{item:W}}})});var OZ6=y(()=>{zZ6();UZ6();BZ6();qZ6();DZ6()});var OW8,hk1;var LZ6=y(()=>{lw();J4();c0();OW8=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")}),hk1=i0({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(OW8).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,X)=>{await L76();let J=D6(X),W=Y.properties||Y.propertyKeys||Y.propertyPatterns||Y.propertyInValues?{properties:Y.properties,propertyKeys:Y.propertyKeys,propertyPatterns:Y.propertyPatterns,propertyInValues:Y.propertyInValues}:void 0,Z={organizationId:J.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:W},K=await X.storage.monitoring.query(Z);return{logs:K.logs.map((Q)=>{let H=Q.output,$=H;if(H&&typeof H==="object"&&"structuredContent"in H){let{content:F,...V}=H;$=V}else if(H&&typeof H==="object"&&"content"in H&&Array.isArray(H.content)){let{content:F,...V}=H;$=Object.keys(V).length>0?V:H}return{...Q,output:$,timestamp:Q.timestamp instanceof Date?Q.timestamp.toISOString():Q.timestamp}}),total:K.total,offset:Y.offset,limit:Y.limit}}})});var xk1;var NZ6=y(()=>{J4();c0();xk1=i0({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,X)=>{let G={organizationId:D6(X).id,startDate:Y.startDate?new Date(Y.startDate):void 0,endDate:Y.endDate?new Date(Y.endDate):void 0},W=await X.storage.monitoring.getStats(G);return{...W,errorRatePercent:(W.errorRate*100).toFixed(2)}}})});var MZ6=y(()=>{LZ6();NZ6()});var NW8,MW8,wW8,gk1,AW8,PW8,hu,xu,TO,EW8,RW8,wZ6;var LA=y(()=>{c0();NW8=q.enum(["sum","avg","min","max","count","count_all","last"]).describe("Aggregation function to apply"),MW8=q.enum(["metric","timeseries","table"]).describe("Widget display type"),wW8=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")}),gk1=q.enum(["connection_id","connection_title","user_id","tool_name","virtual_mcp_id"]).describe("Table column to group by (takes priority over JSONPath groupBy)"),AW8=q.object({fn:NW8,groupBy:q.string().optional().describe("Optional JSONPath for grouping results"),groupByColumn:gk1.optional(),interval:q.string().optional().describe("For timeseries widgets: interval like '1h', '1d', '15m'")}),PW8=q.object({connectionIds:q.array(q.string()).optional().describe("Filter to specific connections"),toolNames:q.array(q.string()).optional().describe("Filter to specific tools")}),hu=q.object({id:q.string().describe("Unique widget identifier"),name:q.string().describe("Widget display name"),type:MW8,source:wW8,aggregation:AW8,filter:PW8.optional()}),xu=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' })")}),TO=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:xu.nullable().describe("Global filters applied to all widgets"),widgets:q.array(hu).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")}),EW8=q.object({key:q.string().describe("Group key value"),value:q.number().describe("Aggregated value for this group")}),RW8=q.object({timestamp:q.string().describe("Time bucket timestamp"),value:q.number().describe("Aggregated value for this time bucket")}),wZ6=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(EW8).optional().describe("Grouped results (when groupBy is specified)"),timeseries:q.array(RW8).optional().describe("Timeseries data (for timeseries type)")})});var uk1;var AZ6=y(()=>{J4();c0();LA();uk1=i0({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:xu.optional().describe("Global filters applied to all widgets"),widgets:q.array(hu).min(1).describe("Widget definitions (at least one required)")}),outputSchema:TO,handler:async(Y,X)=>{let J=D6(X),G=X.auth.user?.id;if(!G)throw Error("User authentication required");let W=await X.storage.monitoringDashboards.create(J.id,G,{name:Y.name,description:Y.description,filters:Y.filters,widgets:Y.widgets});return{id:W.id,organizationId:W.organizationId,name:W.name,description:W.description,filters:W.filters,widgets:W.widgets,createdBy:W.createdBy,createdAt:W.createdAt instanceof Date?W.createdAt.toISOString():W.createdAt,updatedAt:W.updatedAt instanceof Date?W.updatedAt.toISOString():W.updatedAt}}})});var mk1;var PZ6=y(()=>{J4();c0();LA();mk1=i0({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:TO.nullable(),handler:async(Y,X)=>{let J=D6(X),G=await X.storage.monitoringDashboards.get(Y.id);if(!G||G.organizationId!==J.id)return null;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 lk1;var EZ6=y(()=>{J4();c0();LA();lk1=i0({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(TO).describe("List of dashboards"),total:q.number().describe("Total number of dashboards")}),handler:async(Y,X)=>{let J=D6(X),G=await X.storage.monitoringDashboards.list(J.id);return{dashboards:G.map((W)=>({id:W.id,organizationId:W.organizationId,name:W.name,description:W.description,filters:W.filters,widgets:W.widgets,createdBy:W.createdBy,createdAt:W.createdAt instanceof Date?W.createdAt.toISOString():W.createdAt,updatedAt:W.updatedAt instanceof Date?W.updatedAt.toISOString():W.updatedAt})),total:G.length}}})});var dk1;var RZ6=y(()=>{J4();c0();LA();dk1=i0({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:xu.nullable().optional().describe("New global filters"),widgets:q.array(hu).optional().describe("New widget definitions")}),outputSchema:TO,handler:async(Y,X)=>{let J=D6(X),G=await X.storage.monitoringDashboards.get(Y.id);if(!G||G.organizationId!==J.id)throw Error(`Dashboard ${Y.id} not found`);let W={};if(Y.name!==void 0)W.name=Y.name;if(Y.description!==void 0)W.description=Y.description;if(Y.filters!==void 0)W.filters=Y.filters;if(Y.widgets!==void 0)W.widgets=Y.widgets;let Z=await X.storage.monitoringDashboards.update(Y.id,W);return{id:Z.id,organizationId:Z.organizationId,name:Z.name,description:Z.description,filters:Z.filters,widgets:Z.widgets,createdBy:Z.createdBy,createdAt:Z.createdAt instanceof Date?Z.createdAt.toISOString():Z.createdAt,updatedAt:Z.updatedAt instanceof Date?Z.updatedAt.toISOString():Z.updatedAt}}})});var ck1;var TZ6=y(()=>{J4();c0();ck1=i0({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,X)=>{let J=D6(X),G=await X.storage.monitoringDashboards.get(Y.id);if(!G||G.organizationId!==J.id)throw Error(`Dashboard ${Y.id} not found`);return await X.storage.monitoringDashboards.delete(Y.id),{success:!0}}})});var pk1;var CZ6=y(()=>{J4();c0();LA();pk1=i0({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(wZ6).describe("Widget query results"),timeRange:q.object({startDate:q.string(),endDate:q.string()}).describe("Time range used for the query")}),handler:async(Y,X)=>{let J=D6(X),G=await X.storage.monitoringDashboards.get(Y.dashboardId);if(!G||G.organizationId!==J.id)throw Error(`Dashboard ${Y.dashboardId} not found`);let W=new Date,Z=Y.timeRange?.startDate?new Date(Y.timeRange.startDate):new Date(W.getTime()-86400000),K=Y.timeRange?.endDate?new Date(Y.timeRange.endDate):W,Q=await Promise.all(G.widgets.map(async(H)=>{let $=G.filters?.propertyFilters,F=Y.propertyFilters,V=$||F?{properties:{...$,...F?.properties},propertyKeys:F?.propertyKeys,propertyPatterns:F?.propertyPatterns,propertyInValues:F?.propertyInValues}:void 0,z={connectionIds:H.filter?.connectionIds??G.filters?.connectionIds??void 0,virtualMcpIds:G.filters?.virtualMcpIds??void 0,toolNames:H.filter?.toolNames??G.filters?.toolNames??void 0,startDate:Z,endDate:K,propertyFilters:V};try{let U=await X.storage.monitoring.aggregate({organizationId:J.id,path:H.source.path,from:H.source.from,aggregation:H.aggregation.fn,groupBy:H.aggregation.groupBy,groupByColumn:H.aggregation.groupByColumn,interval:H.aggregation.interval,filters:z});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:Q,timeRange:{startDate:Z.toISOString(),endDate:K.toISOString()}}}})});var TW8,nk1;var jZ6=y(()=>{J4();c0();LA();TW8=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","count_all","last"]).describe("Aggregation function"),groupBy:q.string().optional().describe("JSONPath for grouping (table)"),groupByColumn:gk1.optional(),interval:q.string().optional().describe("Time interval for timeseries (15m, 1h, 1d)"),limit:q.number().int().positive().optional().describe("Max number of groups to return (applies to groupBy/groupByColumn, ordered by value desc)")}),filter:q.object({connectionIds:q.array(q.string()).optional(),toolNames:q.array(q.string()).optional()}).optional()}),nk1=i0({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:TW8.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"),skipCount:q.boolean().optional().describe("Skip the countMatched query to reduce database load when the count is not needed")}),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().optional().describe("Number of records that matched (omitted when skipCount is true)"),timeRange:q.object({startDate:q.string(),endDate:q.string()}).describe("Time range used for the query")}),handler:async(Y,X)=>{let J=D6(X),{widget:G,timeRange:W}=Y,Z=new Date,K=W?.startDate?new Date(W.startDate):new Date(Z.getTime()-86400000),Q=W?.endDate?new Date(W.endDate):Z,H={connectionIds:G.filter?.connectionIds,toolNames:G.filter?.toolNames,startDate:K,endDate:Q,propertyFilters:Y.propertyFilters};try{let $=Y.skipCount?void 0:await X.storage.monitoring.countMatched({organizationId:J.id,path:G.source.path,from:G.source.from,filters:H}),F=await X.storage.monitoring.aggregate({organizationId:J.id,path:G.source.path,from:G.source.from,aggregation:G.aggregation.fn,groupBy:G.aggregation.groupBy,groupByColumn:G.aggregation.groupByColumn,interval:G.aggregation.interval,limit:G.aggregation.limit,filters:H});return{value:F.value,groups:F.groups,timeseries:F.timeseries,matchedRecords:$,timeRange:{startDate:K.toISOString(),endDate:Q.toISOString()}}}catch($){return console.error("Widget preview aggregation failed:",$),{value:null,matchedRecords:void 0,timeRange:{startDate:K.toISOString(),endDate:Q.toISOString()}}}}})});var IZ6=y(()=>{AZ6();PZ6();EZ6();RZ6();TZ6();CZ6();jZ6()});var ik1;var SZ6=y(()=>{c0();J4();ik1=i0({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,X)=>{$6(X),await X.access.check();let J=fX(X);if(!J)throw Error("User ID required to create organization");let G=await X.boundAuth.organization.create({name:Y.name,slug:Y.slug,metadata:Y.description?{description:Y.description}:void 0,userId:J});if(!G)throw Error("Failed to create organization");return{...G,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt}}})});var ak1;var _Z6=y(()=>{c0();J4();ak1=i0({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,X)=>{$6(X),await X.access.check();let J=fX(X),G=Y.userId||J;if(!G)throw Error("User ID required to list organizations");return{organizations:(await X.boundAuth.organization.list(G)).map((Z)=>({...Z,createdAt:Z.createdAt instanceof Date?Z.createdAt.toISOString():Z.createdAt}))}}})});var rk1;var kZ6=y(()=>{c0();J4();rk1=i0({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,X)=>{$6(X),await X.access.check();let J=await X.boundAuth.organization.get();if(!J)throw Error("No active organization found");let G=new Date,W=J.invitations?.filter((Z)=>new Date(Z.expiresAt)>G);return{...J,invitations:W,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var ok1;var vZ6=y(()=>{c0();J4();ok1=i0({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,X)=>{$6(X),await X.access.check();let J={};if(Y.name)J.name=Y.name;if(Y.slug)J.slug=Y.slug;if(Y.description)J.metadata={description:Y.description};let G=await X.boundAuth.organization.update({organizationId:Y.id,data:J});if(!G)throw Error("Failed to update organization");return{...G,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt}}})});var sk1;var fZ6=y(()=>{c0();J4();sk1=i0({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,X)=>{return $6(X),await X.access.check(),await X.boundAuth.organization.delete(Y.id),{success:!0,id:Y.id}}})});var gu;var tk1=y(()=>{c0();gu=q.object({title:q.string(),url:q.string(),icon:q.string()})});var ek1;var yZ6=y(()=>{c0();J4();tk1();ek1=i0({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(gu).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,X)=>{$6(X),await X.access.check();let J=X.organization?.id;if(!J)throw Error("Organization ID required (no active organization in context)");let G=await X.storage.organizationSettings.get(J);if(!G)return{organizationId:J};return{...G,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}}})});var Yv1;var bZ6=y(()=>{c0();J4();tk1();Yv1=i0({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(gu).optional(),enabled_plugins:q.array(q.string()).optional()}),outputSchema:q.object({organizationId:q.string(),sidebar_items:q.array(gu).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,X)=>{if($6(X),await X.access.check(),X.organization&&X.organization.id!==Y.organizationId)throw Error("Cannot update settings for a different organization");let J=await X.storage.organizationSettings.upsert(Y.organizationId,{sidebar_items:Y.sidebar_items,enabled_plugins:Y.enabled_plugins});return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt,updatedAt:J.updatedAt instanceof Date?J.updatedAt.toISOString():J.updatedAt}}})});var Xv1;var hZ6=y(()=>{c0();J4();Xv1=i0({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,X)=>{$6(X),await X.access.check();let J=Y.organizationId||X.organization?.id;if(!J)throw Error("Organization ID required (no active organization in context)");if(J!==X.organization?.id)throw Error("Organization ID does not match authenticated organization");let G=await X.boundAuth.organization.addMember({organizationId:J,userId:Y.userId,role:Y.role});if(!G)throw Error("Failed to add member");return{...G,role:G.role,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt}}})});var Jv1;var xZ6=y(()=>{c0();J4();Jv1=i0({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,X)=>{$6(X),await X.access.check();let J=Y.organizationId||X.organization?.id;if(!J)throw Error("Organization ID required (no active organization in context)");return await X.boundAuth.organization.removeMember({organizationId:J,memberIdOrEmail:Y.memberIdOrEmail}),{success:!0,memberIdOrEmail:Y.memberIdOrEmail}}})});var Gv1;var gZ6=y(()=>{c0();J4();Gv1=i0({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,X)=>{$6(X),await X.access.check();let J=X.organization?.id;if(!J)throw Error("Organization ID required (no active organization in context)");let G=await X.boundAuth.organization.listMembers({organizationId:J,limit:Y.limit,offset:Y.offset});return{members:(Array.isArray(G)?G:[]).map((Z)=>({...Z,createdAt:Z.createdAt instanceof Date?Z.createdAt.toISOString():Z.createdAt}))}}})});var Wv1;var uZ6=y(()=>{c0();J4();Wv1=i0({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,X)=>{$6(X),await X.access.check();let J=Y.organizationId||X.organization?.id;if(!J)throw Error("Organization ID required (no active organization in context)");let G=await X.boundAuth.organization.updateMemberRole({organizationId:J,memberId:Y.memberId,role:Y.role});if(!G)throw Error("Failed to update member role");return{...G,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt}}})});var mZ6=y(()=>{SZ6();_Z6();kZ6();vZ6();fZ6();yZ6();bZ6();hZ6();xZ6();gZ6();uZ6()});var IW8,i91,SW8,XB,lZ6,a91;var CO=y(()=>{c0();IW8=q.object({banner:q.string().nullable(),bannerColor:q.string().nullable(),icon:q.string().nullable(),themeColor:q.string().nullable()}),i91=q.object({banner:q.string().nullable().optional(),bannerColor:q.string().nullable().optional(),icon:q.string().nullable().optional(),themeColor:q.string().nullable().optional()}),SW8=q.object({id:q.string(),title:q.string(),icon:q.string().nullable()}),XB=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:IW8.nullable(),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),updatedAt:q.string().datetime().describe("ISO 8601 timestamp")}),lZ6=XB.omit({organizationId:!0}).extend({boundConnections:q.array(SW8)}),a91=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 Zv1;var dZ6=y(()=>{c0();J4();CO();Zv1=i0({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(lZ6)}),handler:async(Y,X)=>{$6(X),await X.access.check();let J=await X.storage.projects.list(Y.organizationId),G=J.map((Z)=>Z.id),W=await X.storage.projectPluginConfigs.getBoundConnectionsForProjects(G);return{projects:J.map((Z)=>({id:Z.id,slug:Z.slug,name:Z.name,description:Z.description,enabledPlugins:Z.enabledPlugins,ui:Z.ui,boundConnections:W.get(Z.id)??[],createdAt:Z.createdAt instanceof Date?Z.createdAt.toISOString():Z.createdAt,updatedAt:Z.updatedAt instanceof Date?Z.updatedAt.toISOString():Z.updatedAt}))}}})});var Qv1;var cZ6=y(()=>{c0();J4();CO();Qv1=i0({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:XB.nullable()}),handler:async(Y,X)=>{$6(X),await X.access.check();let J=null;if(Y.projectId)J=await X.storage.projects.get(Y.projectId);else if(Y.slug)J=await X.storage.projects.getBySlug(Y.organizationId,Y.slug);if(!J)return{project:null};return{project:{id:J.id,organizationId:J.organizationId,slug:J.slug,name:J.name,description:J.description,enabledPlugins:J.enabledPlugins,ui:J.ui,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt,updatedAt:J.updatedAt instanceof Date?J.updatedAt.toISOString():J.updatedAt}}}})});var Kv1;var pZ6=y(()=>{c0();cY();J4();CO();Kv1=i0({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:i91.nullable().optional().describe("UI customization")}),outputSchema:q.object({project:XB}),handler:async(Y,X)=>{$6(X),await X.access.check();let{organizationId:J,slug:G,name:W,description:Z,enabledPlugins:K,ui:Q}=Y;if(G===SH)throw Error(`Slug "${SH}" is reserved`);if(await X.storage.projects.getBySlug(J,G))throw Error(`Project with slug "${G}" already exists in this organization`);let $=Q?{banner:Q.banner??null,bannerColor:Q.bannerColor??null,icon:Q.icon??null,themeColor:Q.themeColor??null}:null,F=await X.storage.projects.create({organizationId:J,slug:G,name:W,description:Z??null,enabledPlugins:K??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 Hv1;var nZ6=y(()=>{c0();J4();CO();Hv1=i0({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:i91.nullable().optional().describe("Updated UI customization")}),outputSchema:q.object({project:XB.nullable()}),handler:async(Y,X)=>{$6(X),await X.access.check();let{projectId:J,name:G,description:W,enabledPlugins:Z,ui:K}=Y,Q={};if(G!==void 0)Q.name=G;if(W!==void 0)Q.description=W;if(Z!==void 0)Q.enabledPlugins=Z;if(K!==void 0)Q.ui=K?{banner:K.banner??null,bannerColor:K.bannerColor??null,icon:K.icon??null,themeColor:K.themeColor??null}:null;let H=await X.storage.projects.update(J,Q);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 $v1;var iZ6=y(()=>{c0();cY();J4();$v1=i0({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,X)=>{$6(X),await X.access.check();let{projectId:J}=Y,G=await X.storage.projects.get(J);if(!G)return{success:!1,message:"Project not found"};if(G.slug===SH)return{success:!1,message:"Cannot delete the org-admin project"};return{success:await X.storage.projects.delete(J)}}})});var Fv1;var aZ6=y(()=>{c0();J4();CO();Fv1=i0({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:a91.nullable()}),handler:async(Y,X)=>{$6(X),await X.access.check();let{projectId:J,pluginId:G}=Y,W=await X.storage.projectPluginConfigs.get(J,G);if(!W)return{config:null};return{config:{id:W.id,projectId:W.projectId,pluginId:W.pluginId,connectionId:W.connectionId,settings:W.settings,createdAt:W.createdAt instanceof Date?W.createdAt.toISOString():W.createdAt,updatedAt:W.updatedAt instanceof Date?W.updatedAt.toISOString():W.updatedAt}}}})});var Vv1;var rZ6=y(()=>{c0();J4();CO();x91();SD();Vv1=i0({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:a91}),handler:async(Y,X)=>{$6(X),await X.access.check();let{projectId:J,pluginId:G,connectionId:W,settings:Z}=Y,K=fX(X),Q=await X.storage.projects.get(J);if(!Q)throw Error(`Project not found: ${J}`);let H=W?await X.storage.connections.findById(W):null;if(W&&Q.organizationId&&!H&&rj()){if(h91(W,Q.organizationId)){if(!K)throw Error("User ID required to create dev-assets connection");let F=oj(Q.organizationId,TQ());await X.storage.connections.create({...F,organization_id:Q.organizationId,created_by:K})}}let $=await X.storage.projectPluginConfigs.upsert(J,G,{connectionId:W,settings:Z});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 _W8,zv1;var oZ6=y(()=>{c0();J4();_W8=q.object({id:q.string(),title:q.string(),icon:q.string().nullable(),connectionType:q.string(),status:q.string()}),zv1=i0({name:"PROJECT_CONNECTION_LIST",description:"List connections associated with a project",annotations:{title:"List Project Connections",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({projectId:q.string().describe("Project ID")}),outputSchema:q.object({connections:q.array(_W8)}),handler:async(Y,X)=>{$6(X);let J=D6(X);await X.access.check();let{projectId:G}=Y,W=await X.storage.projects.get(G);if(!W||W.organizationId!==J.id)throw Error(`Project not found: ${G}`);let Z=await X.storage.projectConnections.list(G);return{connections:(await Promise.all(Z.map((H)=>X.storage.connections.findById(H.connectionId)))).filter((H)=>H!=null).map((H)=>({id:H.id,title:H.title,icon:H.icon??null,connectionType:H.connection_type,status:H.status}))}}})});var Uv1;var sZ6=y(()=>{c0();J4();Uv1=i0({name:"PROJECT_CONNECTION_ADD",description:"Associate a connection with a project",annotations:{title:"Add Project Connection",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({projectId:q.string().describe("Project ID"),connectionId:q.string().describe("Connection ID to associate")}),outputSchema:q.object({success:q.boolean(),projectConnectionId:q.string()}),handler:async(Y,X)=>{$6(X);let J=D6(X);await X.access.check();let{projectId:G,connectionId:W}=Y,Z=await X.storage.projects.get(G);if(!Z||Z.organizationId!==J.id)throw Error(`Project not found: ${G}`);let K=await X.storage.connections.findById(W);if(!K||K.organization_id!==J.id)throw Error(`Connection not found: ${W}`);return{success:!0,projectConnectionId:(await X.storage.projectConnections.add(G,W)).id}}})});var Bv1;var tZ6=y(()=>{c0();J4();Bv1=i0({name:"PROJECT_CONNECTION_REMOVE",description:"Remove a connection association from a project",annotations:{title:"Remove Project Connection",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({projectId:q.string().describe("Project ID"),connectionId:q.string().describe("Connection ID to disassociate")}),outputSchema:q.object({success:q.boolean()}),handler:async(Y,X)=>{$6(X);let J=D6(X);await X.access.check();let{projectId:G,connectionId:W}=Y,Z=await X.storage.projects.get(G);if(!Z||Z.organizationId!==J.id)throw Error(`Project not found: ${G}`);let K=await X.storage.connections.findById(W);if(!K||K.organization_id!==J.id)throw Error(`Connection not found: ${W}`);let Q=await X.storage.projectConnections.remove(G,W);if(Z?.ui?.pinnedViews?.length){let H=Z.ui.pinnedViews.filter(($)=>$.connectionId!==W);if(H.length!==Z.ui.pinnedViews.length){let $={...Z.ui,pinnedViews:H.length>0?H:null};await X.storage.projects.update(G,{ui:$})}}return{success:Q}}})});var kW8,qv1;var eZ6=y(()=>{c0();J4();CO();kW8=q.object({connectionId:q.string(),toolName:q.string(),label:q.string(),icon:q.string().nullable()}),qv1=i0({name:"PROJECT_PINNED_VIEWS_UPDATE",description:"Update the pinned sidebar views for a project",annotations:{title:"Update Pinned Views",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({projectId:q.string().describe("Project ID"),pinnedViews:q.array(kW8).describe("Pinned views to set for the project sidebar")}),outputSchema:q.object({project:XB.nullable()}),handler:async(Y,X)=>{$6(X),await X.access.check();let{projectId:J,pinnedViews:G}=Y,W=await X.storage.projects.get(J);if(!W)throw Error(`Project not found: ${J}`);let K={...W.ui??{banner:null,bannerColor:null,icon:null,themeColor:null},pinnedViews:G.length>0?G:null},Q=await X.storage.projects.update(J,{ui:K});if(!Q)return{project:null};return{project:{id:Q.id,organizationId:Q.organizationId,slug:Q.slug,name:Q.name,description:Q.description,enabledPlugins:Q.enabledPlugins,ui:Q.ui,createdAt:Q.createdAt instanceof Date?Q.createdAt.toISOString():Q.createdAt,updatedAt:Q.updatedAt instanceof Date?Q.updatedAt.toISOString():Q.updatedAt}}}})});var YQ6=y(()=>{dZ6();cZ6();pZ6();nZ6();iZ6();aZ6();rZ6();oZ6();sZ6();tZ6();eZ6()});var Dv1;var XQ6=y(()=>{c0();J4();Dv1=i0({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,X)=>{$6(X),await X.access.check();let J=D6(X);return{tags:(await X.storage.tags.listOrgTags(J.id)).map((W)=>({...W,createdAt:W.createdAt instanceof Date?W.createdAt.toISOString():String(W.createdAt)}))}}})});var Ov1;var JQ6=y(()=>{c0();J4();Ov1=i0({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,X)=>{$6(X),await X.access.check();let J=D6(X),G=await X.storage.tags.createTag(J.id,Y.name);return{tag:{...G,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():String(G.createdAt)}}}})});var Lv1;var GQ6=y(()=>{c0();J4();Lv1=i0({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,X)=>{$6(X),await X.access.check();let J=D6(X),G=await X.storage.tags.getTag(Y.tagId);if(!G)throw Error("Tag not found");if(G.organizationId!==J.id)throw Error("Tag does not belong to this organization");return await X.storage.tags.deleteTag(Y.tagId),{success:!0}}})});var Nv1;var WQ6=y(()=>{c0();J4();Nv1=i0({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,X)=>{$6(X),await X.access.check();let J=D6(X);if(!await X.storage.tags.verifyMemberOrg(Y.memberId,J.id))throw Error(`Member not found in this organization: ${Y.memberId}`);return{tags:(await X.storage.tags.getMemberTags(Y.memberId)).map((Z)=>({...Z,createdAt:Z.createdAt instanceof Date?Z.createdAt.toISOString():String(Z.createdAt)}))}}})});var Mv1;var ZQ6=y(()=>{c0();J4();Mv1=i0({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,X)=>{$6(X),await X.access.check();let J=D6(X);if(!await X.storage.tags.verifyMemberOrg(Y.memberId,J.id))throw Error(`Member not found in this organization: ${Y.memberId}`);for(let Z of Y.tagIds){let K=await X.storage.tags.getTag(Z);if(!K)throw Error(`Tag not found: ${Z}`);if(K.organizationId!==J.id)throw Error(`Tag does not belong to this organization: ${Z}`)}return await X.storage.tags.setMemberTags(Y.memberId,Y.tagIds),{success:!0,tags:(await X.storage.tags.getMemberTags(Y.memberId)).map((Z)=>({...Z,createdAt:Z.createdAt instanceof Date?Z.createdAt.toISOString():String(Z.createdAt)}))}}})});var QQ6=y(()=>{XQ6();JQ6();GQ6();WQ6();ZQ6()});var KQ6=y(()=>{cY()});var HQ6,WV,$Q6,FQ6;var NA=y(()=>{c0();KQ6();HQ6=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")}),WV=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([...YE,"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")}),$Q6=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")}),FQ6=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 yW8,bW8,wv1;var VQ6=y(()=>{c0();J4();NA();fQ();yW8=q.object({data:$Q6.describe("Data for the new thread (id is auto-generated if not provided)")}),bW8=q.object({item:WV.describe("The created thread entity")}),wv1=i0({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:yW8,outputSchema:bW8,handler:async(Y,X)=>{$6(X);let J=D6(X);await X.access.check();let G=fX(X);if(!G)throw Error("User ID required to create thread");let W=Y.data.id??e9("thrd"),Z=await X.storage.threads.create({id:W,organization_id:J.id,title:Y.data.title,description:Y.data.description,created_by:G});return{item:{...Z,hidden:Z.hidden??!1}}}})});function jO(Y,X=Date.now()){let J=Y.status;if(J==="in_progress"){let G=new Date(Y.updated_at).getTime();if(!Number.isFinite(G)||X-G>1800000)J="expired"}return{...Y,status:J,hidden:Y.hidden??!1}}var hW8,xW8,Av1;var zQ6=y(()=>{YZ();J4();NA();c0();hW8=W3.extend({where:q.object({created_by:q.string().optional()}).optional()}),xW8=wz(WV),Av1=i0({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:hW8,outputSchema:xW8,handler:async(Y,X)=>{if(await X.access.check(),!X.auth.user?.id)throw Error("User ID required to list threads");D6(X);let G=Y.offset??0,W=Y.limit??100,Z=Y.where?.created_by,{threads:K,total:Q}=await X.storage.threads.list(Z,{limit:W,offset:G}),H=G+W<Q,$=Date.now();return{items:K.map((F)=>jO(F,$)),totalCount:Q,hasMore:H}}})});var gW8,Pv1;var UQ6=y(()=>{YZ();J4();NA();gW8=Sf(WV),Pv1=i0({name:"COLLECTION_THREADS_GET",description:"Get thread details by ID",annotations:{title:"Get Thread",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:If,outputSchema:gW8,handler:async(Y,X)=>{$6(X),D6(X),await X.access.check();let J=await X.storage.threads.get(Y.id);if(!J)return{item:null};return{item:jO(J)}}})});var uW8,mW8,Ev1;var BQ6=y(()=>{c0();J4();NA();uW8=q.object({id:q.string().describe("ID of the thread to update"),data:FQ6.describe("Partial thread data to update")}),mW8=q.object({item:WV.describe("The updated thread entity")}),Ev1=i0({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:uW8,outputSchema:mW8,handler:async(Y,X)=>{$6(X),D6(X),await X.access.check();let J=fX(X);if(!J)throw Error("User ID required to update thread");let{id:G,data:W}=Y;if(!await X.storage.threads.get(G))throw Error("Thread not found in organization");let K=await X.storage.threads.update(G,{title:W.title,description:W.description,hidden:W.hidden,updated_by:J});return{item:jO(K)}}})});var Rv1;var qQ6=y(()=>{YZ();J4();NA();Rv1=i0({name:"COLLECTION_THREADS_DELETE",description:"Delete a thread",annotations:{title:"Delete Thread",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:_f,outputSchema:kf(WV),handler:async(Y,X)=>{$6(X),D6(X),await X.access.check();let J=await X.storage.threads.get(Y.id);if(!J)throw Error(`Thread not found: ${Y.id}`);return await X.storage.threads.delete(Y.id),{item:jO(J)}}})});function DQ6(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 X of Y.conditions){let J=DQ6(X);if(J)return J}return null}var lW8,Tv1;var OQ6=y(()=>{YZ();J4();NA();lW8=wz(HQ6),Tv1=i0({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:W3,outputSchema:lW8,handler:async(Y,X)=>{D6(X),await X.access.check();let J=DQ6(Y.where);if(!J)throw Error("thread_id filter is required in where clause");let G=Y.offset??0,W=Y.limit??100,{messages:Z,total:K}=await X.storage.threads.listMessages(J,{limit:W,offset:G}),Q=G+W<K;return{items:Z,totalCount:K,hasMore:Q}}})});var LQ6=y(()=>{VQ6();zQ6();UQ6();BQ6();qQ6();OQ6()});var cW8,pW8,Cv1;var NQ6=y(()=>{c0();J4();cW8=q.object({id:q.string().min(1)}),pW8=q.object({user:q.object({id:q.string(),name:q.string(),email:q.string(),image:q.string().nullable()}).nullable()}),Cv1=i0({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:cW8,outputSchema:pW8,handler:async(Y,X)=>{await X.access.check(),$6(X);let J=fX(X);if(!J)throw Error("Authentication required");let G=await X.storage.users.findById(Y.id,J);if(!G)return{user:null};return{user:{id:G.id,name:G.name,email:G.email,image:G.image??null}}}})});var MQ6=y(()=>{NQ6()});var AQ6={};L4(AQ6,{managementMCP:()=>jv1,ALL_TOOLS:()=>wQ6});var iW8,aW8,wQ6,jv1=async(Y)=>{let X=null;if(Y.organization){let W=await Y.storage.organizationSettings.get(Y.organization.id),Z=await Y.storage.projects.list(Y.organization.id),K=new Set(W?.enabled_plugins??[]);for(let Q of Z)if(Q.enabledPlugins)for(let H of Q.enabledPlugins)K.add(H);X=K.size>0?[...K]:null}let J=R30(wQ6,X),G=new Wz({name:"mcp-mesh-management",version:"1.0.0"},{capabilities:{tools:{}}});for(let W of J){let Z=W.inputSchema&&typeof W.inputSchema==="object"&&"shape"in W.inputSchema?W.inputSchema:q.object({}),K=W.outputSchema&&typeof W.outputSchema==="object"&&"shape"in W.outputSchema?W.outputSchema:void 0,Q=Z.shape,H=K?.shape;G.registerTool(W.name,{description:W.description??"",inputSchema:Q,outputSchema:H,annotations:W.annotations,_meta:W._meta},async($)=>{Y.access.setToolName(W.name);try{let F=await W.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 G};var Iv1=y(()=>{ZT();Pv();c0();vG6();oG6();cW6();aW6();WZ6();VZ6();OZ6();MZ6();IZ6();mZ6();YQ6();QQ6();LQ6();MQ6();iW8=[ik1,ak1,rk1,ok1,sk1,ek1,Yv1,Xv1,Jv1,Gv1,Wv1,d_1,n_1,i_1,Dk1,Ok1,Lk1,Tk1,jk1,Ik1,Sk1,_k1,kk1,vk1,fk1,yk1,bk1,iW6,hk1,xk1,uk1,mk1,lk1,dk1,ck1,pk1,nk1,k_1,f_1,y_1,v_1,Nk1,Mk1,wk1,Ak1,Pk1,Ek1,Rk1,Cv1,u_1,m_1,l_1,wv1,Av1,Pv1,Ev1,Rv1,Tv1,Dv1,Ov1,Lv1,Nv1,Mv1,Zv1,Qv1,Kv1,Hv1,$v1,Fv1,Vv1,zv1,Uv1,Bv1,qv1],aW8=T30(),wQ6=[...iW8,...aW8]});function rW8(Y){return[{permissions:{self:["*"]},getTools:async()=>{let{ALL_TOOLS:X}=await Promise.resolve().then(() => (Iv1(),AQ6));return X.map((J)=>{return{name:J.name,inputSchema:q.toJSONSchema(J.inputSchema,{unrepresentable:"any"}),outputSchema:J.outputSchema?q.toJSONSchema(J.outputSchema,{unrepresentable:"any"}):void 0,description:J.description}})},data:p$1(TQ(),Y)},{data:c$1()},{data:d$1(Y)}]}async function PQ6(Y,X){try{let J=sK(),G=new zA(Q4.ENCRYPTION_KEY),W=new Mu(J.db,G),Z=new wu(J.db),K=rW8(Y);try{await Z.create({organizationId:Y,slug:SH,name:d2,description:"Organization administration and settings",enabledPlugins:null,ui:null})}catch(Q){console.warn("Could not create org-admin project (may already exist):",Q)}await Promise.all(K.map(async(Q)=>{let H=null;if(Q.permissions)H=(await jZ.api.createApiKey({body:{name:`${Q.data.app_name??crypto.randomUUID()}-mcp`,userId:X,permissions:Q.permissions,rateLimitEnabled:!1,metadata:{organization:{id:Y},purpose:"default-org-connections"}}}))?.key;let $=await nj({id:"pending",title:Q.data.title,connection_type:Q.data.connection_type,connection_url:Q.data.connection_url,connection_token:Q.data.connection_token,connection_headers:Q.data.connection_headers}).catch(()=>null),F=await Q.getTools?.()??$?.tools??null,V=$?.scopes?.length?$.scopes:null,z=Q.data.id?Q.data.id.startsWith(`${Y}_`)?Q.data.id:`${Y}_${Q.data.id}`:void 0;await W.create({...Q.data,id:z,tools:F,configuration_scopes:V,organization_id:Y,created_by:X,connection_token:Q.data.connection_token??H})}))}catch(J){console.error("Error creating default MCP connections:",J)}}var EQ6=y(()=>{cY();SD();dj();T91();O_1();L_1();I91();c0();_5();AO()});var Sv1,r91;var o91=y(()=>{Sv1=["owner","admin","user"],r91=["owner","admin"]});var oW8=(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"}}}}]}},RQ6=(Y)=>{if(Y.providerId==="microsoft")return oW8(Y);throw Error(`Unsupported provider: ${Y.providerId}`)};var SQ6={};L4(SQ6,{resetPasswordEnabled:()=>t91,authConfig:()=>bY,auth:()=>jZ});function sW8(Y){return Y.toLowerCase().trim().replace(/[^a-z0-9\s_-]+/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function tW8(){let Y=Math.floor(Math.random()*CQ6.length),X=Math.floor(Math.random()*TQ6.length),J=CQ6[Y]??"deco",G=TQ6[X]??"studio";return`${J}-${G}`}function KZ8(){let Y=[uu],X=new URL(uu);if(X.hostname==="localhost")Y.push(uu.replace("localhost","127.0.0.1"));else if(X.hostname==="127.0.0.1")Y.push(uu.replace("127.0.0.1","localhost"));return Y}var TQ6,CQ6,eW8,YZ8,s91,XZ8,JZ8,GZ8,jQ6,bY,IQ6=void 0,_v1=void 0,t91=!1,WZ8,ZZ8,QZ8,uu,jZ;var AO=y(()=>{_5();XM1();lq0();EO0();ew1();M21();DL0();K01();SD();RL0();dj();D_1();E76();EQ6();o91();TQ6=["labs","agent","studio","workspace","systems","core","cloud","works"],CQ6=["capybara","guarana","deco","samba","feijoada","capoeira","carnival"];eW8=Object.values(Cb()).map((Y)=>Y.map((X)=>X.name)).flat(),YZ8={...p11,self:["*",...eW8]},s91=_F(YZ8),XZ8=s91.newRole({self:["*"],..._h.statements}),JZ8=s91.newRole({self:["*"],..._h.statements}),GZ8=s91.newRole({self:["*"],..._h.statements}),jQ6=Object.values(Cb()).map((Y)=>Y.map((X)=>`self:${X.name}`)).flat(),bY=uh.auth;if(bY.inviteEmailProviderId&&bY.emailProviders&&bY.emailProviders.length>0){let Y=Lu(bY.emailProviders,bY.inviteEmailProviderId);if(Y){let X=Ou(Y);IQ6=async(J)=>{let G=J.inviter.user?.name||J.inviter.user?.email,W=`${TQ()}/auth/accept-invitation?invitationId=${J.invitation.id}&redirectTo=/`;await X({to:J.email,subject:`Invitation to join ${J.organization.name}`,html:`
|
|
1959
1959
|
<h2>You've been invited!</h2>
|
|
1960
1960
|
<p>${G} has invited you to join <strong>${J.organization.name}</strong>.</p>
|
|
1961
1961
|
<p><a href="${W}">Click here to accept the invitation</a></p>
|
|
@@ -1990,7 +1990,7 @@ ${X.stack}`;return W}}catch{}if(typeof X.toString==="function")try{let W=X.toStr
|
|
|
1990
1990
|
`.execute(Y),G=new Set(J.rows.map((K)=>`${K.plugin_id}/${K.name}`)),W=new Map;for(let{pluginId:K,migration:Q}of X){if(!W.has(K))W.set(K,[]);W.get(K).push({name:Q.name,up:Q.up})}let Z=0;for(let[K,Q]of W){Q.sort((H,$)=>H.name.localeCompare($.name));for(let H of Q){let $=`${K}/${H.name}`;if(G.has($))continue;if(Z===0)console.log("\uD83D\uDD0C Running plugin migrations...");Z++,console.log(` Running: ${$}`),await H.up(Y);let F=new Date().toISOString();await E0`
|
|
1991
1991
|
INSERT INTO plugin_migrations (plugin_id, name, timestamp)
|
|
1992
1992
|
VALUES (${K}, ${H.name}, ${F})
|
|
1993
|
-
`.execute(Y)}}if(Z>0)console.log(`\u2705 ${Z} plugin migration(s) completed`)}async function fQ6(Y){await HZ8(Y),await $Z8(Y);let X=new Xd({db:Y,provider:{getMigrations:()=>Promise.resolve(Na)}}),{error:J,results:G}=await X.migrateToLatest();if(G?.forEach((W)=>{if(W.status==="Success")console.log(`\u2705 Migration "${W.migrationName}" executed successfully`);else if(W.status==="Error")console.error(`\u274C Failed to execute migration "${W.migrationName}"`)}),J)throw console.error("Failed to migrate"),console.error(J),J}async function VZ8(Y){let{keepOpen:X=!1,database:J,skipBetterAuth:G=!1,seed:W}=Y??{};if(!G&&!J)await _Q6();let Z=J??sK(),K=async()=>{if(!X&&!J)console.log("\uD83D\uDD12 Closing database connection..."),await A76(Z).catch((Q)=>{console.warn("Warning: Error closing database:",Q)})};try{console.log("\uD83D\uDCCA Running Kysely migrations..."),await fQ6(Z.db),console.log("\uD83C\uDF89 Core migrations completed successfully"),await FZ8(Z.db);let Q;if(W)Q=await ZN1(Z.db,W);return await K(),{seedResult:Q}}catch(Q){throw await K(),Q}}async function zZ8(){let Y=sK(),X=new Xd({db:Y.db,provider:{getMigrations:()=>Promise.resolve(Na)}}),{error:J,results:G}=await X.migrateDown();if(G?.forEach((W)=>{if(W.status==="Success")console.log(`\u2705 Migration "${W.migrationName}" rolled back successfully`);else if(W.status==="Error")console.error(`\u274C Failed to rollback migration "${W.migrationName}"`)}),J)throw console.error("Failed to rollback migration"),console.error(J),J}var bQ6=y(()=>{F9();BF1();b30();kQ6();ZT();dj()});var b5;var WI=y(()=>{b5=class extends Error{res;status;constructor(Y=500,X){super(X?.message,{cause:X?.cause});this.res=X?.res,this.status=Y}getResponse(){if(this.res)return new Response(this.res.body,{status:this.status,headers:this.res.headers});return new Response(this.message,{status:this.status})}}});var hQ6,UZ8,BZ8=(Y,X)=>{if(!Y)return{};let J=new Headers(Y.headers);if(X){let G=J.get("connection");if(G){let W=G.split(",").map((K)=>K.trim()),Z=W.filter((K)=>!UZ8.test(K));if(Z.length>0)throw new b5(400,{message:`Invalid Connection header value: ${Z.join(", ")}`});W.forEach((K)=>{J.delete(K)})}}return hQ6.forEach((G)=>{J.delete(G)}),{method:Y.method,body:Y.body,duplex:Y.body?"half":void 0,headers:J,signal:Y.signal}},qZ8=(Y)=>{if(!Y.headers||Array.isArray(Y.headers)||Y.headers instanceof Headers)return Y;let X=new Headers;for(let[J,G]of Object.entries(Y.headers))if(G==null)X.delete(J);else X.set(J,G);return Y.headers=X,Y},xQ6=async(Y,X)=>{let{raw:J,customFetch:G,strictConnectionProcessing:W=!1,...Z}=X instanceof Request?{raw:X}:X??{},K=new Request(Y,{...BZ8(J,W),...qZ8(Z)});K.headers.delete("accept-encoding");let Q=await(G||fetch)(K),H=new Headers(Q.headers);if(hQ6.forEach(($)=>{H.delete($)}),H.has("content-encoding"))H.delete("content-encoding"),H.delete("content-length");return new Response(Q.body,{status:Q.status,statusText:Q.statusText,headers:H})};var gQ6=y(()=>{WI();hQ6=["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"],UZ8=/^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/});var uQ6=(Y)=>(X)=>{let J=new URL(X.req.raw.url),G=new URL(Y);return G.pathname=J.pathname,G.search=J.search,xQ6(G,{raw:X.req.raw,headers:{...X.req.raw.headers}})};var mQ6=y(()=>{gQ6()});import{resolve as mu,dirname as DZ8,join as OZ8,extname as LZ8,basename as NZ8,sep as lQ6}from"path";function MZ8(Y,X){if(Y===X||NZ8(Y)==="index.html")return{"Cache-Control":"no-cache"};if(Y.includes(`${lQ6}assets${lQ6}`))return{"Cache-Control":"public, max-age=31536000, immutable"};return{}}function PZ8(Y,X){let J=mu(X),G=mu(Y);return G===J||G.startsWith(J+"/")}function EZ8({requestPath:Y,clientDir:X}){let J=Y.startsWith("/")?Y.slice(1):Y,G=mu(X,J);if(!PZ8(G,X))return null;return G}function kv1(Y,X="../client"){let J=new URL(Y),G=DZ8(J.pathname);return mu(G,X)}function dQ6(Y={}){let{env:X="production",devServerUrl:J=wZ8,clientDir:G=AZ8,isServerPath:W=()=>!1}=Y;if(X==="development"){let Z=uQ6(J);return async function(Q){let H=new URL(Q.url);if(W(H.pathname))return null;let $={req:{raw:Q,url:Q.url}};return Z($)}}return async function(K){if(K.method!=="GET")return null;let Q=new URL(K.url),H;try{H=decodeURIComponent(Q.pathname)}catch{return null}if(W(H))return null;let $=EZ8({requestPath:H,clientDir:G});if(!$)return null;let F=OZ8($,"index.html"),V=mu(G,"index.html"),z=K.headers.get("accept"),B=z?.includes("text/html")||z?.includes("*/*")&&["",".html"].includes(LZ8($))?[F,V]:[];for(let D of[$,...B])try{let L=Bun.file(D);if(await L.exists())return new Response(L,{headers:MZ8(D,V)})}catch{}if(H.includes("/assets/"))return new Response("Not Found",{status:404,headers:{"Cache-Control":"no-store"}});return null}}var wZ8,AZ8="./dist/client";var cQ6=y(()=>{mQ6();wZ8=`http://localhost:${process.env.VITE_PORT||"4000"}`});function nQ6(Y){if(!Y)return!1;try{return new URL(Y).host==="api.decocms.com"&&Y!=="https://studio.decocms.com/org/deco/registry/mcp"}catch{return!1}}var pQ6="https://studio.decocms.com/org/deco/registry/mcp";var vv1=(Y,X,J)=>{return(G,W)=>{let Z=-1;return K(0);async function K(Q){if(Q<=Z)throw Error("next() called multiple times");Z=Q;let H,$=!1,F;if(Y[Q])F=Y[Q][0][0],G.req.routeIndex=Q;else F=Q===Y.length&&W||void 0;if(F)try{H=await F(G,()=>K(Q+1))}catch(V){if(V instanceof Error&&X)G.error=V,H=await X(V,G),$=!0;else throw V}else if(G.finalized===!1&&J)H=await J(G);if(H&&(G.finalized===!1||$))G.res=H;return G}}};var iQ6=()=>{};var aQ6;var rQ6=y(()=>{aQ6=Symbol()});async function RZ8(Y,X){let J=await Y.formData();if(J)return TZ8(J,X);return{}}function TZ8(Y,X){let J=Object.create(null);if(Y.forEach((G,W)=>{if(!(X.all||W.endsWith("[]")))J[W]=G;else CZ8(J,W,G)}),X.dot)Object.entries(J).forEach(([G,W])=>{if(G.includes("."))jZ8(J,G,W),delete J[G]});return J}var oQ6=async(Y,X=Object.create(null))=>{let{all:J=!1,dot:G=!1}=X,Z=(Y instanceof e91?Y.raw.headers:Y.headers).get("Content-Type");if(Z?.startsWith("multipart/form-data")||Z?.startsWith("application/x-www-form-urlencoded"))return RZ8(Y,{all:J,dot:G});return{}},CZ8=(Y,X,J)=>{if(Y[X]!==void 0)if(Array.isArray(Y[X]))Y[X].push(J);else Y[X]=[Y[X],J];else if(!X.endsWith("[]"))Y[X]=J;else Y[X]=[J]},jZ8=(Y,X,J)=>{if(/(?:^|\.)__proto__\./.test(X))return;let G=Y,W=X.split(".");W.forEach((Z,K)=>{if(K===W.length-1)G[Z]=J;else{if(!G[Z]||typeof G[Z]!=="object"||Array.isArray(G[Z])||G[Z]instanceof File)G[Z]=Object.create(null);G=G[Z]}})};var sQ6=y(()=>{fv1()});var bv1=(Y)=>{let X=Y.split("/");if(X[0]==="")X.shift();return X},tQ6=(Y)=>{let{groups:X,path:J}=IZ8(Y),G=bv1(J);return SZ8(G,X)},IZ8=(Y)=>{let X=[];return Y=Y.replace(/\{[^}]+\}/g,(J,G)=>{let W=`@${G}`;return X.push([W,J]),W}),{groups:X,path:Y}},SZ8=(Y,X)=>{for(let J=X.length-1;J>=0;J--){let[G]=X[J];for(let W=Y.length-1;W>=0;W--)if(Y[W].includes(G)){Y[W]=Y[W].replace(G,X[J][1]);break}}return Y},YY1,eQ6=(Y,X)=>{if(Y==="*")return"*";let J=Y.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(J){let G=`${Y}#${X}`;if(!YY1[G])if(J[2])YY1[G]=X&&X[0]!==":"&&X[0]!=="*"?[G,J[1],new RegExp(`^${J[2]}(?=/${X})`)]:[Y,J[1],new RegExp(`^${J[2]}$`)];else YY1[G]=[Y,J[1],!0];return YY1[G]}return null},ZI=(Y,X)=>{try{return X(Y)}catch{return Y.replace(/(?:%[0-9A-Fa-f]{2})+/g,(J)=>{try{return X(J)}catch{return J}})}},YK6=(Y)=>ZI(Y,decodeURI),hv1=(Y)=>{let X=Y.url,J=X.indexOf("/",X.indexOf(":")+4),G=J;for(;G<X.length;G++){let W=X.charCodeAt(G);if(W===37){let Z=X.indexOf("?",G),K=X.indexOf("#",G),Q=Z===-1?K===-1?void 0:K:K===-1?Z:Math.min(Z,K),H=X.slice(J,Q);return YK6(H.includes("%25")?H.replace(/%25/g,"%2525"):H)}else if(W===63||W===35)break}return X.slice(J,G)},XK6=(Y)=>{let X=hv1(Y);return X.length>1&&X.at(-1)==="/"?X.slice(0,-1):X},MA=(Y,X,...J)=>{if(J.length)X=MA(X,...J);return`${Y?.[0]==="/"?"":"/"}${Y}${X==="/"?"":`${Y?.at(-1)==="/"?"":"/"}${X?.[0]==="/"?X.slice(1):X}`}`},XY1=(Y)=>{if(Y.charCodeAt(Y.length-1)!==63||!Y.includes(":"))return null;let X=Y.split("/"),J=[],G="";return X.forEach((W)=>{if(W!==""&&!/\:/.test(W))G+="/"+W;else if(/\:/.test(W))if(/\?/.test(W)){if(J.length===0&&G==="")J.push("/");else J.push(G);let Z=W.replace("?","");G+="/"+Z,J.push(G)}else G+="/"+W}),J.filter((W,Z,K)=>K.indexOf(W)===Z)},yv1=(Y)=>{if(!/[%+]/.test(Y))return Y;if(Y.indexOf("+")!==-1)Y=Y.replace(/\+/g," ");return Y.indexOf("%")!==-1?ZI(Y,lu):Y},JK6=(Y,X,J)=>{let G;if(!J&&X&&!/[%+]/.test(X)){let K=Y.indexOf("?",8);if(K===-1)return;if(!Y.startsWith(X,K+1))K=Y.indexOf(`&${X}`,K+1);while(K!==-1){let Q=Y.charCodeAt(K+X.length+1);if(Q===61){let H=K+X.length+2,$=Y.indexOf("&",H);return yv1(Y.slice(H,$===-1?void 0:$))}else if(Q==38||isNaN(Q))return"";K=Y.indexOf(`&${X}`,K+1)}if(G=/[%+]/.test(Y),!G)return}let W={};G??=/[%+]/.test(Y);let Z=Y.indexOf("?",8);while(Z!==-1){let K=Y.indexOf("&",Z+1),Q=Y.indexOf("=",Z);if(Q>K&&K!==-1)Q=-1;let H=Y.slice(Z+1,Q===-1?K===-1?void 0:K:Q);if(G)H=yv1(H);if(Z=K,H==="")continue;let $;if(Q===-1)$="";else if($=Y.slice(Q+1,K===-1?void 0:K),G)$=yv1($);if(J){if(!(W[H]&&Array.isArray(W[H])))W[H]=[];W[H].push($)}else W[H]??=$}return X?W[X]:W},GK6,WK6=(Y,X)=>{return JK6(Y,X,!0)},lu;var IO=y(()=>{YY1={},GK6=JK6,lu=decodeURIComponent});var ZK6=(Y)=>ZI(Y,lu),e91;var fv1=y(()=>{WI();rQ6();sQ6();IO();e91=class{raw;#Y;#X;routeIndex=0;path;bodyCache={};constructor(Y,X="/",J=[[]]){this.raw=Y,this.path=X,this.#X=J,this.#Y={}}param(Y){return Y?this.#J(Y):this.#G()}#J(Y){let X=this.#X[0][this.routeIndex][1][Y],J=this.#W(X);return J&&/\%/.test(J)?ZK6(J):J}#G(){let Y={},X=Object.keys(this.#X[0][this.routeIndex][1]);for(let J of X){let G=this.#W(this.#X[0][this.routeIndex][1][J]);if(G!==void 0)Y[J]=/\%/.test(G)?ZK6(G):G}return Y}#W(Y){return this.#X[1]?this.#X[1][Y]:Y}query(Y){return GK6(this.url,Y)}queries(Y){return WK6(this.url,Y)}header(Y){if(Y)return this.raw.headers.get(Y)??void 0;let X={};return this.raw.headers.forEach((J,G)=>{X[G]=J}),X}async parseBody(Y){return this.bodyCache.parsedBody??=await oQ6(this,Y)}#Z=(Y)=>{let{bodyCache:X,raw:J}=this,G=X[Y];if(G)return G;let W=Object.keys(X)[0];if(W)return X[W].then((Z)=>{if(W==="json")Z=JSON.stringify(Z);return new Response(Z)[Y]()});return X[Y]=J[Y]()};json(){return this.#Z("text").then((Y)=>JSON.parse(Y))}text(){return this.#Z("text")}arrayBuffer(){return this.#Z("arrayBuffer")}blob(){return this.#Z("blob")}formData(){return this.#Z("formData")}addValidatedData(Y,X){this.#Y[Y]=X}valid(Y){return this.#Y[Y]}get url(){return this.raw.url}get method(){return this.raw.method}get[aQ6](){return this.#X}get matchedRoutes(){return this.#X[0].map(([[,Y]])=>Y)}get routePath(){return this.#X[0].map(([[,Y]])=>Y)[this.routeIndex].path}}});var JY1,QK6=(Y,X)=>{let J=new String(Y);return J.isEscaped=!0,J.callbacks=X,J},du=async(Y,X,J,G,W)=>{if(typeof Y==="object"&&!(Y instanceof String)){if(!(Y instanceof Promise))Y=Y.toString();if(Y instanceof Promise)Y=await Y}let Z=Y.callbacks;if(!Z?.length)return Promise.resolve(Y);if(W)W[0]+=Y;else W=[Y];let K=Promise.all(Z.map((Q)=>Q({phase:X,buffer:W,context:G}))).then((Q)=>Promise.all(Q.filter(Boolean).map((H)=>du(H,X,!1,G,W))).then(()=>W[0]));if(J)return QK6(await K,Z);else return K};var GY1=y(()=>{JY1={Stringify:1,BeforeStream:2,Stream:3}});var KK6="text/plain; charset=UTF-8",xv1=(Y,X)=>{return{"Content-Type":Y,...X}},cu=(Y,X)=>new Response(Y,X),HK6=class{#Y;#X;env={};#J;finalized=!1;error;#G;#W;#Z;#K;#Q;#H;#$;#V;#U;constructor(Y,X){if(this.#Y=Y,X)this.#W=X.executionCtx,this.env=X.env,this.#H=X.notFoundHandler,this.#U=X.path,this.#V=X.matchResult}get req(){return this.#X??=new e91(this.#Y,this.#U,this.#V),this.#X}get event(){if(this.#W&&"respondWith"in this.#W)return this.#W;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#W)return this.#W;else throw Error("This context has no ExecutionContext")}get res(){return this.#Z||=cu(null,{headers:this.#$??=new Headers})}set res(Y){if(this.#Z&&Y){Y=cu(Y.body,Y);for(let[X,J]of this.#Z.headers.entries()){if(X==="content-type")continue;if(X==="set-cookie"){let G=this.#Z.headers.getSetCookie();Y.headers.delete("set-cookie");for(let W of G)Y.headers.append("set-cookie",W)}else Y.headers.set(X,J)}}this.#Z=Y,this.finalized=!0}render=(...Y)=>{return this.#Q??=(X)=>this.html(X),this.#Q(...Y)};setLayout=(Y)=>this.#K=Y;getLayout=()=>this.#K;setRenderer=(Y)=>{this.#Q=Y};header=(Y,X,J)=>{if(this.finalized)this.#Z=cu(this.#Z.body,this.#Z);let G=this.#Z?this.#Z.headers:this.#$??=new Headers;if(X===void 0)G.delete(Y);else if(J?.append)G.append(Y,X);else G.set(Y,X)};status=(Y)=>{this.#G=Y};set=(Y,X)=>{this.#J??=new Map,this.#J.set(Y,X)};get=(Y)=>{return this.#J?this.#J.get(Y):void 0};get var(){if(!this.#J)return{};return Object.fromEntries(this.#J)}#F(Y,X,J){let G=this.#Z?new Headers(this.#Z.headers):this.#$??new Headers;if(typeof X==="object"&&"headers"in X){let Z=X.headers instanceof Headers?X.headers:new Headers(X.headers);for(let[K,Q]of Z)if(K.toLowerCase()==="set-cookie")G.append(K,Q);else G.set(K,Q)}if(J)for(let[Z,K]of Object.entries(J))if(typeof K==="string")G.set(Z,K);else{G.delete(Z);for(let Q of K)G.append(Z,Q)}let W=typeof X==="number"?X:X?.status??this.#G;return cu(Y,{status:W,headers:G})}newResponse=(...Y)=>this.#F(...Y);body=(Y,X,J)=>this.#F(Y,X,J);text=(Y,X,J)=>{return!this.#$&&!this.#G&&!X&&!J&&!this.finalized?new Response(Y):this.#F(Y,X,xv1(KK6,J))};json=(Y,X,J)=>{return this.#F(JSON.stringify(Y),X,xv1("application/json",J))};html=(Y,X,J)=>{let G=(W)=>this.#F(W,X,xv1("text/html; charset=UTF-8",J));return typeof Y==="object"?du(Y,JY1.Stringify,!1,{}).then(G):G(Y)};redirect=(Y,X)=>{let J=String(Y);return this.header("Location",!/[^\x00-\xFF]/.test(J)?J:encodeURI(J)),this.newResponse(null,X??302)};notFound=()=>{return this.#H??=()=>cu(),this.#H(this)}};var WY1=y(()=>{fv1();GY1()});var hY="ALL",$K6="all",FK6,ZY1="Can not add a route since the matcher is already built.",QY1;var SO=y(()=>{FK6=["get","post","put","delete","options","patch"],QY1=class extends Error{}});var gv1="__COMPOSED_HANDLER";var uv1=()=>{};var _Z8=(Y)=>{return Y.text("404 Not Found",404)},VK6=(Y,X)=>{if("getResponse"in Y){let J=Y.getResponse();return X.newResponse(J.body,J)}return console.error(Y),X.text("Internal Server Error",500)},zK6=class Y{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#Y="/";routes=[];constructor(X={}){[...FK6,$K6].forEach((Z)=>{this[Z]=(K,...Q)=>{if(typeof K==="string")this.#Y=K;else this.#G(Z,this.#Y,K);return Q.forEach((H)=>{this.#G(Z,this.#Y,H)}),this}}),this.on=(Z,K,...Q)=>{for(let H of[K].flat()){this.#Y=H;for(let $ of[Z].flat())Q.map((F)=>{this.#G($.toUpperCase(),this.#Y,F)})}return this},this.use=(Z,...K)=>{if(typeof Z==="string")this.#Y=Z;else this.#Y="*",K.unshift(Z);return K.forEach((Q)=>{this.#G(hY,this.#Y,Q)}),this};let{strict:G,...W}=X;Object.assign(this,W),this.getPath=G??!0?X.getPath??hv1:XK6}#X(){let X=new Y({router:this.router,getPath:this.getPath});return X.errorHandler=this.errorHandler,X.#J=this.#J,X.routes=this.routes,X}#J=_Z8;errorHandler=VK6;route(X,J){let G=this.basePath(X);return J.routes.map((W)=>{let Z;if(J.errorHandler===VK6)Z=W.handler;else Z=async(K,Q)=>(await vv1([],J.errorHandler)(K,()=>W.handler(K,Q))).res,Z[gv1]=W.handler;G.#G(W.method,W.path,Z)}),this}basePath(X){let J=this.#X();return J._basePath=MA(this._basePath,X),J}onError=(X)=>{return this.errorHandler=X,this};notFound=(X)=>{return this.#J=X,this};mount(X,J,G){let W,Z;if(G)if(typeof G==="function")Z=G;else if(Z=G.optionHandler,G.replaceRequest===!1)W=(H)=>H;else W=G.replaceRequest;let K=Z?(H)=>{let $=Z(H);return Array.isArray($)?$:[$]}:(H)=>{let $=void 0;try{$=H.executionCtx}catch{}return[H.env,$]};W||=(()=>{let H=MA(this._basePath,X),$=H==="/"?0:H.length;return(F)=>{let V=new URL(F.url);return V.pathname=V.pathname.slice($)||"/",new Request(V,F)}})();let Q=async(H,$)=>{let F=await J(W(H.req.raw),...K(H));if(F)return F;await $()};return this.#G(hY,MA(X,"*"),Q),this}#G(X,J,G){X=X.toUpperCase(),J=MA(this._basePath,J);let W={basePath:this._basePath,path:J,method:X,handler:G};this.router.add(X,J,[G,W]),this.routes.push(W)}#W(X,J){if(X instanceof Error)return this.errorHandler(X,J);throw X}#Z(X,J,G,W){if(W==="HEAD")return(async()=>new Response(null,await this.#Z(X,J,G,"GET")))();let Z=this.getPath(X,{env:G}),K=this.router.match(W,Z),Q=new HK6(X,{path:Z,matchResult:K,env:G,executionCtx:J,notFoundHandler:this.#J});if(K[0].length===1){let $;try{$=K[0][0][0][0](Q,async()=>{Q.res=await this.#J(Q)})}catch(F){return this.#W(F,Q)}return $ instanceof Promise?$.then((F)=>F||(Q.finalized?Q.res:this.#J(Q))).catch((F)=>this.#W(F,Q)):$??this.#J(Q)}let H=vv1(K[0],this.errorHandler,this.#J);return(async()=>{try{let $=await H(Q);if(!$.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return $.res}catch($){return this.#W($,Q)}})()}fetch=(X,...J)=>{return this.#Z(X,J[1],J[0],X.method)};request=(X,J,G,W)=>{if(X instanceof Request)return this.fetch(J?new Request(X,J):X,G,W);return X=X.toString(),this.fetch(new Request(/^https?:\/\//.test(X)?X:`http://localhost${MA("/",X)}`,J),G,W)};fire=()=>{addEventListener("fetch",(X)=>{X.respondWith(this.#Z(X.request,X,void 0,X.request.method))})}};var UK6=y(()=>{iQ6();WY1();SO();uv1();IO()});function KY1(Y,X){let J=this.buildAllMatchers(),G=(W,Z)=>{let K=J[W]||J[hY],Q=K[2][Z];if(Q)return Q;let H=Z.match(K[0]);if(!H)return[[],pu];let $=H.indexOf("",1);return[K[1][$],H]};return this.match=G,G(Y,X)}var pu;var mv1=y(()=>{SO();pu=[]});function vZ8(Y,X){if(Y.length===1)return X.length===1?Y<X?-1:1:-1;if(X.length===1)return 1;if(Y===nu||Y===iu)return 1;else if(X===nu||X===iu)return-1;if(Y===HY1)return 1;else if(X===HY1)return-1;return Y.length===X.length?Y<X?-1:1:X.length-Y.length}var HY1="[^/]+",nu=".*",iu="(?:|/.*)",wA,kZ8,BK6=class Y{#Y;#X;#J=Object.create(null);insert(X,J,G,W,Z){if(X.length===0){if(this.#Y!==void 0)throw wA;if(Z)return;this.#Y=J;return}let[K,...Q]=X,H=K==="*"?Q.length===0?["","",nu]:["","",HY1]:K==="/*"?["","",iu]:K.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),$;if(H){let F=H[1],V=H[2]||HY1;if(F&&H[2]){if(V===".*")throw wA;if(V=V.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(V))throw wA}if($=this.#J[V],!$){if(Object.keys(this.#J).some((z)=>z!==nu&&z!==iu))throw wA;if(Z)return;if($=this.#J[V]=new Y,F!=="")$.#X=W.varIndex++}if(!Z&&F!=="")G.push([F,$.#X])}else if($=this.#J[K],!$){if(Object.keys(this.#J).some((F)=>F.length>1&&F!==nu&&F!==iu))throw wA;if(Z)return;$=this.#J[K]=new Y}$.insert(Q,J,G,W,Z)}buildRegExpStr(){let J=Object.keys(this.#J).sort(vZ8).map((G)=>{let W=this.#J[G];return(typeof W.#X==="number"?`(${G})@${W.#X}`:kZ8.has(G)?`\\${G}`:G)+W.buildRegExpStr()});if(typeof this.#Y==="number")J.unshift(`#${this.#Y}`);if(J.length===0)return"";if(J.length===1)return J[0];return"(?:"+J.join("|")+")"}};var lv1=y(()=>{wA=Symbol(),kZ8=new Set(".\\+*[^]$()")});var qK6=class{#Y={varIndex:0};#X=new BK6;insert(Y,X,J){let G=[],W=[];for(let K=0;;){let Q=!1;if(Y=Y.replace(/\{[^}]+\}/g,(H)=>{let $=`@\\${K}`;return W[K]=[$,H],K++,Q=!0,$}),!Q)break}let Z=Y.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let K=W.length-1;K>=0;K--){let[Q]=W[K];for(let H=Z.length-1;H>=0;H--)if(Z[H].indexOf(Q)!==-1){Z[H]=Z[H].replace(Q,W[K][1]);break}}return this.#X.insert(Z,X,G,this.#Y,J),G}buildRegExp(){let Y=this.#X.buildRegExpStr();if(Y==="")return[/^$/,[],[]];let X=0,J=[],G=[];return Y=Y.replace(/#(\d+)|@(\d+)|\.\*\$/g,(W,Z,K)=>{if(Z!==void 0)return J[++X]=Number(Z),"$()";if(K!==void 0)return G[Number(K)]=++X,"";return""}),[new RegExp(`^${Y}`),J,G]}};var DK6=y(()=>{lv1()});function LK6(Y){return OK6[Y]??=new RegExp(Y==="*"?"":`^${Y.replace(/\/\*$|([.\\+*[^\]$()])/g,(X,J)=>J?`\\${J}`:"(?:|/.*)")}$`)}function yZ8(){OK6=Object.create(null)}function bZ8(Y){let X=new qK6,J=[];if(Y.length===0)return fZ8;let G=Y.map(($)=>[!/\*|\/:/.test($[0]),...$]).sort(([$,F],[V,z])=>$?1:V?-1:F.length-z.length),W=Object.create(null);for(let $=0,F=-1,V=G.length;$<V;$++){let[z,U,B]=G[$];if(z)W[U]=[B.map(([L])=>[L,Object.create(null)]),pu];else F++;let D;try{D=X.insert(U,F,z)}catch(L){throw L===wA?new QY1(U):L}if(z)continue;J[F]=B.map(([L,w])=>{let N=Object.create(null);w-=1;for(;w>=0;w--){let[R,P]=D[w];N[R]=P}return[L,N]})}let[Z,K,Q]=X.buildRegExp();for(let $=0,F=J.length;$<F;$++)for(let V=0,z=J[$].length;V<z;V++){let U=J[$][V]?.[1];if(!U)continue;let B=Object.keys(U);for(let D=0,L=B.length;D<L;D++)U[B[D]]=Q[U[B[D]]]}let H=[];for(let $ in K)H[$]=J[K[$]];return[Z,H,W]}function QI(Y,X){if(!Y)return;for(let J of Object.keys(Y).sort((G,W)=>W.length-G.length))if(LK6(J).test(X))return[...Y[J]];return}var fZ8,OK6,$Y1=class{name="RegExpRouter";#Y;#X;constructor(){this.#Y={[hY]:Object.create(null)},this.#X={[hY]:Object.create(null)}}add(Y,X,J){let G=this.#Y,W=this.#X;if(!G||!W)throw Error(ZY1);if(!G[Y])[G,W].forEach((Q)=>{Q[Y]=Object.create(null),Object.keys(Q[hY]).forEach((H)=>{Q[Y][H]=[...Q[hY][H]]})});if(X==="/*")X="*";let Z=(X.match(/\/:/g)||[]).length;if(/\*$/.test(X)){let Q=LK6(X);if(Y===hY)Object.keys(G).forEach((H)=>{G[H][X]||=QI(G[H],X)||QI(G[hY],X)||[]});else G[Y][X]||=QI(G[Y],X)||QI(G[hY],X)||[];Object.keys(G).forEach((H)=>{if(Y===hY||Y===H)Object.keys(G[H]).forEach(($)=>{Q.test($)&&G[H][$].push([J,Z])})}),Object.keys(W).forEach((H)=>{if(Y===hY||Y===H)Object.keys(W[H]).forEach(($)=>Q.test($)&&W[H][$].push([J,Z]))});return}let K=XY1(X)||[X];for(let Q=0,H=K.length;Q<H;Q++){let $=K[Q];Object.keys(W).forEach((F)=>{if(Y===hY||Y===F)W[F][$]||=[...QI(G[F],$)||QI(G[hY],$)||[]],W[F][$].push([J,Z-H+Q+1])})}}match=KY1;buildAllMatchers(){let Y=Object.create(null);return Object.keys(this.#X).concat(Object.keys(this.#Y)).forEach((X)=>{Y[X]||=this.#J(X)}),this.#Y=this.#X=void 0,yZ8(),Y}#J(Y){let X=[],J=Y===hY;if([this.#Y,this.#X].forEach((G)=>{let W=G[Y]?Object.keys(G[Y]).map((Z)=>[Z,G[Y][Z]]):[];if(W.length!==0)J||=!0,X.push(...W);else if(Y!==hY)X.push(...Object.keys(G[hY]).map((Z)=>[Z,G[hY][Z]]))}),!J)return null;else return bZ8(X)}};var dv1=y(()=>{SO();IO();mv1();lv1();DK6();fZ8=[/^$/,[],Object.create(null)],OK6=Object.create(null)});var hZ8=class{name="PreparedRegExpRouter";#Y;#X;constructor(Y,X){this.#Y=Y,this.#X=X}#J(Y,X){let J=this.#Y[Y];J[1].forEach((G)=>G&&G.push(X)),Object.values(J[2]).forEach((G)=>G[0].push(X))}#G(Y,X,J,G,W){let Z=this.#Y[Y];if(!W)Z[2][X][0].push([J,{}]);else G.forEach((K)=>{if(typeof K==="number")Z[1][K].push([J,W]);else Z[2][K||X][0].push([J,W])})}add(Y,X,J){if(!this.#Y[Y]){let W=this.#Y[hY],Z={};for(let K in W[2])Z[K]=[W[2][K][0].slice(),pu];this.#Y[Y]=[W[0],W[1].map((K)=>Array.isArray(K)?K.slice():0),Z]}if(X==="/*"||X==="*"){let W=[J,{}];if(Y===hY)for(let Z in this.#Y)this.#J(Z,W);else this.#J(Y,W);return}let G=this.#X[X];if(!G)throw Error(`Path ${X} is not registered`);for(let[W,Z]of G)if(Y===hY)for(let K in this.#Y)this.#G(K,X,J,W,Z);else this.#G(Y,X,J,W,Z)}buildAllMatchers(){return this.#Y}match=KY1};var NK6=y(()=>{SO();mv1();dv1()});var MK6=y(()=>{dv1();NK6()});var cv1=class{name="SmartRouter";#Y=[];#X=[];constructor(Y){this.#Y=Y.routers}add(Y,X,J){if(!this.#X)throw Error(ZY1);this.#X.push([Y,X,J])}match(Y,X){if(!this.#X)throw Error("Fatal error");let J=this.#Y,G=this.#X,W=J.length,Z=0,K;for(;Z<W;Z++){let Q=J[Z];try{for(let H=0,$=G.length;H<$;H++)Q.add(...G[H]);K=Q.match(Y,X)}catch(H){if(H instanceof QY1)continue;throw H}this.match=Q.match.bind(Q),this.#Y=[Q],this.#X=void 0;break}if(Z===W)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,K}get activeRouter(){if(this.#X||this.#Y.length!==1)throw Error("No active router has been determined yet.");return this.#Y[0]}};var wK6=y(()=>{SO()});var AK6=y(()=>{wK6()});var au,xZ8=(Y)=>{for(let X in Y)return!0;return!1},PK6=class Y{#Y;#X;#J;#G=0;#W=au;constructor(X,J,G){if(this.#X=G||Object.create(null),this.#Y=[],X&&J){let W=Object.create(null);W[X]={handler:J,possibleKeys:[],score:0},this.#Y=[W]}this.#J=[]}insert(X,J,G){this.#G=++this.#G;let W=this,Z=tQ6(J),K=[];for(let Q=0,H=Z.length;Q<H;Q++){let $=Z[Q],F=Z[Q+1],V=eQ6($,F),z=Array.isArray(V)?V[0]:$;if(z in W.#X){if(W=W.#X[z],V)K.push(V[1]);continue}if(W.#X[z]=new Y,V)W.#J.push(V),K.push(V[1]);W=W.#X[z]}return W.#Y.push({[X]:{handler:G,possibleKeys:K.filter((Q,H,$)=>$.indexOf(Q)===H),score:this.#G}}),W}#Z(X,J,G,W,Z){for(let K=0,Q=J.#Y.length;K<Q;K++){let H=J.#Y[K],$=H[G]||H[hY],F={};if($!==void 0){if($.params=Object.create(null),X.push($),W!==au||Z&&Z!==au)for(let V=0,z=$.possibleKeys.length;V<z;V++){let U=$.possibleKeys[V],B=F[$.score];$.params[U]=Z?.[U]&&!B?Z[U]:W[U]??Z?.[U],F[$.score]=!0}}}}search(X,J){let G=[];this.#W=au;let Z=[this],K=bv1(J),Q=[],H=K.length,$=null;for(let F=0;F<H;F++){let V=K[F],z=F===H-1,U=[];for(let D=0,L=Z.length;D<L;D++){let w=Z[D],N=w.#X[V];if(N)if(N.#W=w.#W,z){if(N.#X["*"])this.#Z(G,N.#X["*"],X,w.#W);this.#Z(G,N,X,w.#W)}else U.push(N);for(let R=0,P=w.#J.length;R<P;R++){let A=w.#J[R],E=w.#W===au?{}:{...w.#W};if(A==="*"){let h=w.#X["*"];if(h)this.#Z(G,h,X,w.#W),h.#W=E,U.push(h);continue}let[C,v,f]=A;if(!V&&!(f instanceof RegExp))continue;let b=w.#X[C];if(f instanceof RegExp){if($===null){$=Array(H);let c=J[0]==="/"?1:0;for(let m=0;m<H;m++)$[m]=c,c+=K[m].length+1}let h=J.substring($[F]),p=f.exec(h);if(p){if(E[v]=p[0],this.#Z(G,b,X,w.#W,E),xZ8(b.#X)){b.#W=E;let c=p[0].match(/\//)?.length??0;(Q[c]||=[]).push(b)}continue}}if(f===!0||f.test(V))if(E[v]=V,z){if(this.#Z(G,b,X,E,w.#W),b.#X["*"])this.#Z(G,b.#X["*"],X,E,w.#W)}else b.#W=E,U.push(b)}}let B=Q.shift();Z=B?U.concat(B):U}if(G.length>1)G.sort((F,V)=>{return F.score-V.score});return[G.map(({handler:F,params:V})=>[F,V])]}};var EK6=y(()=>{SO();IO();au=Object.create(null)});var pv1=class{name="TrieRouter";#Y;constructor(){this.#Y=new PK6}add(Y,X,J){let G=XY1(X);if(G){for(let W=0,Z=G.length;W<Z;W++)this.#Y.insert(Y,G[W],J);return}this.#Y.insert(Y,X,J)}match(Y,X){return this.#Y.search(Y,X)}};var RK6=y(()=>{IO();EK6()});var TK6=y(()=>{RK6()});var qX;var CK6=y(()=>{UK6();MK6();AK6();TK6();qX=class extends zK6{constructor(Y={}){super(Y);this.router=Y.router??new cv1({routers:[new $Y1,new pv1]})}}});var yQ=y(()=>{CK6()});var gZ8,uZ8,nv1=(Y,X)=>{if(X&&Y.indexOf(X)===-1)return{};let J=Y.trim().split(";"),G={};for(let W of J){W=W.trim();let Z=W.indexOf("=");if(Z===-1)continue;let K=W.substring(0,Z).trim();if(X&&X!==K||!gZ8.test(K))continue;let Q=W.substring(Z+1).trim();if(Q.startsWith('"')&&Q.endsWith('"'))Q=Q.slice(1,-1);if(uZ8.test(Q)){if(G[K]=Q.indexOf("%")!==-1?ZI(Q,lu):Q,X)break}}return G};var jK6=y(()=>{IO();gZ8=/^[\w!#$%&'*.^`|~+-]+$/,uZ8=/^[ !#-:<-[\]-~]*$/});var IK6=(Y,X,J)=>{let G=Y.req.raw.headers.get("Cookie");if(typeof X==="string"){if(!G)return;let Z=X;if(J==="secure")Z="__Secure-"+X;else if(J==="host")Z="__Host-"+X;return nv1(G,Z)[Z]}if(!G)return{};return nv1(G)};var SK6=y(()=>{jK6()});var _K6=(Y)=>{let J={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...Y},G=((Z)=>{if(typeof Z==="string")if(Z==="*")return()=>Z;else return(K)=>Z===K?K:null;else if(typeof Z==="function")return Z;else return(K)=>Z.includes(K)?K:null})(J.origin),W=((Z)=>{if(typeof Z==="function")return Z;else if(Array.isArray(Z))return()=>Z;else return()=>[]})(J.allowMethods);return async function(K,Q){function H(F,V){K.res.headers.set(F,V)}let $=await G(K.req.header("origin")||"",K);if($)H("Access-Control-Allow-Origin",$);if(J.credentials)H("Access-Control-Allow-Credentials","true");if(J.exposeHeaders?.length)H("Access-Control-Expose-Headers",J.exposeHeaders.join(","));if(K.req.method==="OPTIONS"){if(J.origin!=="*")H("Vary","Origin");if(J.maxAge!=null)H("Access-Control-Max-Age",J.maxAge.toString());let F=await W(K.req.header("origin")||"",K);if(F.length)H("Access-Control-Allow-Methods",F.join(","));let V=J.allowHeaders;if(!V?.length){let z=K.req.header("Access-Control-Request-Headers");if(z)V=z.split(/\s*,\s*/)}if(V?.length)H("Access-Control-Allow-Headers",V.join(",")),K.res.headers.append("Vary","Access-Control-Request-Headers");return K.res.headers.delete("Content-Length"),K.res.headers.delete("Content-Type"),new Response(null,{headers:K.res.headers,status:204,statusText:"No Content"})}if(await Q(),J.origin!=="*")K.header("Vary","Origin",{append:!0})}};var kK6=()=>{};function mZ8(){let{process:Y,Deno:X}=globalThis;return!(typeof X?.noColor==="boolean"?X.noColor:Y!==void 0?"NO_COLOR"in Y?.env:!1)}async function vK6(){let{navigator:Y}=globalThis,X="cloudflare:workers";return!(Y!==void 0&&Y.userAgent==="Cloudflare-Workers"?await(async()=>{try{return"NO_COLOR"in((await import("cloudflare:workers")).env??{})}catch{return!1}})():!mZ8())}var fK6=()=>{};async function yK6(Y,X,J,G,W=0,Z){let K=X==="<--"?`${X} ${J} ${G}`:`${X} ${J} ${G} ${await cZ8(W)} ${Z}`;Y(K)}var lZ8=(Y)=>{let[X,J]=[",","."];return Y.map((W)=>W.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+X)).join(J)},dZ8=(Y)=>{let X=Date.now()-Y;return lZ8([X<1000?X+"ms":Math.round(X/1000)+"s"])},cZ8=async(Y)=>{if(await vK6())switch(Y/100|0){case 5:return`\x1B[31m${Y}\x1B[0m`;case 4:return`\x1B[33m${Y}\x1B[0m`;case 3:return`\x1B[36m${Y}\x1B[0m`;case 2:return`\x1B[32m${Y}\x1B[0m`}return`${Y}`},bK6=(Y=console.log)=>{return async function(J,G){let{method:W,url:Z}=J.req,K=Z.slice(Z.indexOf("/",8));await yK6(Y,"<--",W,K);let Q=Date.now();await G(),await yK6(Y,"-->",W,K,J.res.status,dZ8(Q))}};var hK6=y(()=>{fK6()});var xK6=()=>{try{return performance.now()}catch{}return Date.now()},iv1=(Y)=>{let X={total:!0,enabled:!0,totalDescription:"Total Response Time",autoEnd:!0,crossOrigin:!1,...Y};return async function(G,W){let Z=[],K=new Map;if(G.get("metric"))return await W();if(G.set("metric",{headers:Z,timers:K}),X.total)KI(G,"total",X.totalDescription);if(await W(),X.total)AA(G,"total");if(X.autoEnd)K.forEach((H,$)=>AA(G,$));if(typeof X.enabled==="function"?X.enabled(G):X.enabled){G.res.headers.append("Server-Timing",Z.join(","));let H=typeof X.crossOrigin==="function"?X.crossOrigin(G):X.crossOrigin;if(H)G.res.headers.append("Timing-Allow-Origin",typeof H==="string"?H:"*")}}},gK6=(Y,X,J,G,W)=>{let Z=Y.get("metric");if(!Z){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}if(typeof J==="number"){let K=J.toFixed(W||1),Q=G?`${X};dur=${K};desc="${G}"`:`${X};dur=${K}`;Z.headers.push(Q)}else{let K=J?`${X};desc="${J}"`:`${X}`;Z.headers.push(K)}},KI=(Y,X,J)=>{let G=Y.get("metric");if(!G){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}G.timers.set(X,{description:J,start:xK6()})},AA=(Y,X,J)=>{let G=Y.get("metric");if(!G){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}let W=G.timers.get(X);if(!W){console.warn(`Timer "${X}" does not exist!`);return}let{description:Z,start:K}=W,Q=xK6()-K;gK6(Y,X,Q,Z,J),G.timers.delete(X)};var uK6=y(()=>{WY1()});var mK6=y(()=>{uK6()});class av1{db;constructor(Y){this.db=Y}async create(Y,X,J){let G=e9("vir"),W=new Date().toISOString();if(await this.db.insertInto("connections").values({id:G,organization_id:Y,created_by:X,title:J.title,description:J.description??null,icon:J.icon??null,app_name:null,app_id:null,connection_type:"VIRTUAL",connection_url:`virtual://${G}`,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:J.metadata?JSON.stringify(J.metadata):null,tools:null,bindings:null,status:J.status??"active",created_at:W,updated_at:W}).execute(),J.connections.length>0)await this.db.insertInto("connection_aggregations").values(J.connections.map((K)=>({id:e9("agg"),parent_connection_id:G,child_connection_id:K.connection_id,selected_tools:K.selected_tools?JSON.stringify(K.selected_tools):null,selected_resources:K.selected_resources?JSON.stringify(K.selected_resources):null,selected_prompts:K.selected_prompts?JSON.stringify(K.selected_prompts):null,dependency_mode:"direct",created_at:W}))).execute();let Z=await this.findById(G);if(!Z)throw Error(`Failed to create virtual MCP with id: ${G}`);return Z}async findById(Y,X){let J=Gz(Y);if(J){let G=X??J,W=await this.db.selectFrom("connections").selectAll().where("organization_id","=",G).where("status","!=","inactive").where("status","!=","error").execute();return{...Ua(G),connections:W.map((Z)=>({connection_id:Z.id,selected_tools:null,selected_resources:null,selected_prompts:null}))}}return this.findByIdInternal(this.db,Y)}async findByIdInternal(Y,X){let J=await Y.selectFrom("connections").selectAll().where("id","=",X).where("connection_type","=","VIRTUAL").executeTakeFirst();if(!J)return null;let G=await Y.selectFrom("connection_aggregations").selectAll().where("parent_connection_id","=",X).where("dependency_mode","=","direct").execute();return this.deserializeVirtualMCPEntity(J,G)}async list(Y){let X=await this.db.selectFrom("connections").selectAll().where("organization_id","=",Y).where("connection_type","=","VIRTUAL").execute(),J=X.map((Z)=>Z.id);if(J.length===0)return[];let G=await this.db.selectFrom("connection_aggregations").selectAll().where("parent_connection_id","in",J).where("dependency_mode","=","direct").execute(),W=new Map;for(let Z of G){let K=W.get(Z.parent_connection_id)??[];K.push(Z),W.set(Z.parent_connection_id,K)}return X.map((Z)=>this.deserializeVirtualMCPEntity(Z,W.get(Z.id)??[]))}async listByConnectionId(Y,X){let G=(await this.db.selectFrom("connection_aggregations").select("parent_connection_id").where("child_connection_id","=",X).execute()).map((H)=>H.parent_connection_id);if(G.length===0)return[];let W=await this.db.selectFrom("connections").selectAll().where("id","in",G).where("organization_id","=",Y).where("connection_type","=","VIRTUAL").execute();if(W.length===0)return[];let Z=W.map((H)=>H.id),K=await this.db.selectFrom("connection_aggregations").selectAll().where("parent_connection_id","in",Z).where("dependency_mode","=","direct").execute(),Q=new Map;for(let H of K){let $=Q.get(H.parent_connection_id)??[];$.push(H),Q.set(H.parent_connection_id,$)}return W.map((H)=>this.deserializeVirtualMCPEntity(H,Q.get(H.id)??[]))}async update(Y,X,J){let G=new Date().toISOString(),W={updated_at:G,updated_by:X};if(J.title!==void 0)W.title=J.title;if(J.description!==void 0)W.description=J.description;if(J.icon!==void 0)W.icon=J.icon;if(J.status!==void 0)W.status=J.status;if(J.metadata!==void 0)W.metadata=J.metadata?JSON.stringify(J.metadata):null;if(await this.db.updateTable("connections").set(W).where("id","=",Y).where("connection_type","=","VIRTUAL").execute(),J.connections!==void 0){if(await this.db.deleteFrom("connection_aggregations").where("parent_connection_id","=",Y).where("dependency_mode","=","direct").execute(),J.connections.length>0)await this.db.insertInto("connection_aggregations").values(J.connections.map((K)=>({id:e9("agg"),parent_connection_id:Y,child_connection_id:K.connection_id,selected_tools:K.selected_tools?JSON.stringify(K.selected_tools):null,selected_resources:K.selected_resources?JSON.stringify(K.selected_resources):null,selected_prompts:K.selected_prompts?JSON.stringify(K.selected_prompts):null,dependency_mode:"direct",created_at:G}))).execute()}let Z=await this.findById(Y);if(!Z)throw Error("Virtual MCP not found after update");return Z}async delete(Y){await this.db.deleteFrom("connection_aggregations").where("parent_connection_id","=",Y).execute(),await this.db.deleteFrom("connections").where("id","=",Y).where("connection_type","=","VIRTUAL").execute()}async removeConnectionReferences(Y){await this.db.deleteFrom("connection_aggregations").where("child_connection_id","=",Y).execute()}deserializeVirtualMCPEntity(Y,X){let J=Y.created_at instanceof Date?Y.created_at.toISOString():Y.created_at,G=Y.updated_at instanceof Date?Y.updated_at.toISOString():Y.updated_at,W=Y.status==="active"?"active":"inactive",Z=this.parseJson(Y.metadata);return{id:Y.id,organization_id:Y.organization_id,title:Y.title,description:Y.description,icon:Y.icon,status:W,created_at:J,updated_at:G,created_by:Y.created_by,updated_by:Y.updated_by??void 0,metadata:{...Z,instructions:Z?.instructions??null},connections:X.map((K)=>({connection_id:K.child_connection_id,selected_tools:this.parseJson(K.selected_tools),selected_resources:this.parseJson(K.selected_resources),selected_prompts:this.parseJson(K.selected_prompts)}))}}parseJson(Y){if(Y===null)return null;if(typeof Y==="string")try{return JSON.parse(Y)}catch{return null}return Y}async listVirtualTools(Y){let X=await this.db.selectFrom("connections").select(["tools","created_at","updated_at"]).where("id","=",Y).where("connection_type","=","VIRTUAL").executeTakeFirst();if(!X)return[];let J=this.parseJson(X.tools);if(!J)return[];let G=X.created_at instanceof Date?X.created_at.toISOString():X.created_at,W=X.updated_at instanceof Date?X.updated_at.toISOString():X.updated_at;return J.map((Z,K)=>({tool:Z,originalIndex:K})).filter(({tool:Z})=>PO(Z)).map(({tool:Z,originalIndex:K})=>fu(`${Y}:${Z.name}:${K}`,Z,G,W))}async getVirtualTool(Y,X){let J=await this.db.selectFrom("connections").select(["tools","created_at","updated_at"]).where("id","=",Y).where("connection_type","=","VIRTUAL").executeTakeFirst();if(!J)return null;let G=this.parseJson(J.tools);if(!G)return null;let W=G.findIndex((H)=>H.name===X&&PO(H));if(W===-1)return null;let Z=G[W],K=J.created_at instanceof Date?J.created_at.toISOString():J.created_at,Q=J.updated_at instanceof Date?J.updated_at.toISOString():J.updated_at;return fu(`${Y}:${Z.name}:${W}`,Z,K,Q)}async createVirtualTool(Y,X,J){let G=new Date().toISOString(),W=await this.db.selectFrom("connections").select(["tools"]).where("id","=",Y).where("connection_type","=","VIRTUAL").executeTakeFirst();if(!W)throw Error(`Virtual MCP not found: ${Y}`);let Z=this.parseJson(W.tools)??[];if(Z.some((Q)=>Q.name===X.name))throw Error(`Tool with name "${X.name}" already exists`);let K={name:X.name,description:X.description,inputSchema:X.inputSchema,outputSchema:X.outputSchema,annotations:X.annotations,_meta:{"mcp.mesh":{"tool.fn":X.code},connectionDependencies:J}};return Z.push(K),await this.db.updateTable("connections").set({tools:JSON.stringify(Z),updated_at:G}).where("id","=",Y).execute(),await this.syncIndirectDependencies(Y,J),fu(`${Y}:${X.name}:${Z.length-1}`,K,G,G)}async updateVirtualTool(Y,X,J,G){let W=new Date().toISOString(),Z=await this.db.selectFrom("connections").select(["tools","created_at"]).where("id","=",Y).where("connection_type","=","VIRTUAL").executeTakeFirst();if(!Z)throw Error(`Virtual MCP not found: ${Y}`);let K=this.parseJson(Z.tools)??[],Q=K.findIndex((z)=>z.name===X&&PO(z));if(Q===-1)throw Error(`Virtual tool not found: ${X}`);let H=K[Q];if(J.name&&J.name!==X){if(K.some((z)=>z.name===J.name))throw Error(`Tool with name "${J.name}" already exists`)}let $=G??H._meta.connectionDependencies??[],F={name:J.name??H.name,description:J.description!==void 0?J.description??void 0:H.description,inputSchema:J.inputSchema??H.inputSchema,outputSchema:J.outputSchema!==void 0?J.outputSchema??void 0:H.outputSchema,annotations:J.annotations!==void 0?J.annotations??void 0:H.annotations,_meta:{"mcp.mesh":{"tool.fn":J.code??H._meta["mcp.mesh"]["tool.fn"]},connectionDependencies:$}};if(K[Q]=F,await this.db.updateTable("connections").set({tools:JSON.stringify(K),updated_at:W}).where("id","=",Y).execute(),G!==void 0)await this.recalculateIndirectDependencies(Y,K);let V=Z.created_at instanceof Date?Z.created_at.toISOString():Z.created_at;return fu(`${Y}:${F.name}:${Q}`,F,V,W)}async deleteVirtualTool(Y,X){let J=new Date().toISOString(),G=await this.db.selectFrom("connections").select(["tools"]).where("id","=",Y).where("connection_type","=","VIRTUAL").executeTakeFirst();if(!G)throw Error(`Virtual MCP not found: ${Y}`);let W=this.parseJson(G.tools)??[],Z=W.findIndex((K)=>K.name===X&&PO(K));if(Z===-1)throw Error(`Virtual tool not found: ${X}`);W.splice(Z,1),await this.db.updateTable("connections").set({tools:W.length>0?JSON.stringify(W):null,updated_at:J}).where("id","=",Y).execute(),await this.recalculateIndirectDependencies(Y,W)}async syncIndirectDependencies(Y,X){if(X.length===0)return;let J=new Date().toISOString(),G=await this.db.selectFrom("connection_aggregations").select(["child_connection_id","dependency_mode"]).where("parent_connection_id","=",Y).execute(),W=new Set(G.map((K)=>K.child_connection_id)),Z=X.filter((K)=>!W.has(K));if(Z.length>0)await this.db.insertInto("connection_aggregations").values(Z.map((K)=>({id:e9("agg"),parent_connection_id:Y,child_connection_id:K,selected_tools:null,selected_resources:null,selected_prompts:null,dependency_mode:"indirect",created_at:J}))).execute()}async recalculateIndirectDependencies(Y,X){let J=new Set;for(let Q of X)if(PO(Q)){let H=Q._meta.connectionDependencies??[];for(let $ of H)J.add($)}let G=await this.db.selectFrom("connection_aggregations").select(["id","child_connection_id","dependency_mode"]).where("parent_connection_id","=",Y).execute(),W=G.filter((Q)=>Q.dependency_mode==="indirect"&&!J.has(Q.child_connection_id)).map((Q)=>Q.id);if(W.length>0)await this.db.deleteFrom("connection_aggregations").where("id","in",W).execute();let Z=new Set(G.map((Q)=>Q.child_connection_id)),K=Array.from(J).filter((Q)=>!Z.has(Q));if(K.length>0){let Q=new Date().toISOString();await this.db.insertInto("connection_aggregations").values(K.map((H)=>({id:e9("agg"),parent_connection_id:Y,child_connection_id:H,selected_tools:null,selected_resources:null,selected_prompts:null,dependency_mode:"indirect",created_at:Q}))).execute()}}}var lK6=y(()=>{fQ();cY();eU()});function JJ(Y){return Y.replace(/\0/g,"").replace(/\\/g,"\\\\").replace(/'/g,"''")}function nZ8(Y){if(!pZ8.has(Y))throw Error(`Invalid groupByColumn: ${Y}`);return Y}function rv1(Y){if(!iZ8.test(Y))throw Error(`Invalid JSONPath: ${Y}`);if(Y.startsWith("$."))return Y;if(Y.startsWith("."))return`$${Y}`;return`$.${Y}`}function ov1(Y){return Y.replace(/^\$\./,"").split(".").map((J)=>`'${JJ(J)}'`).join(", ")}function oZ8(Y){let X=aZ8.exec(Y);if(!X||!X[1]||!X[2])throw Error(`Invalid interval: ${Y}`);let J=parseInt(X[1],10),G=X[2],W=rZ8[G];if(J<1||J>W)throw Error(`Invalid interval amount: ${J}${G} (max ${W}${G})`);return{amount:J,unit:G}}function sZ8(Y){let{amount:X,unit:J}=oZ8(Y),W={m:"MINUTE",h:"HOUR",d:"DAY"}[J];return`toStartOfInterval(parseDateTime64BestEffort(toString(timestamp)), INTERVAL ${X} ${W})`}function sv1(Y){if(Y===null||Y===void 0)return{};if(typeof Y==="object")return Y;try{return JSON.parse(String(Y))}catch{return{}}}function tZ8(Y){return{id:String(Y.id??""),organizationId:String(Y.organization_id??""),connectionId:String(Y.connection_id??""),connectionTitle:String(Y.connection_title??""),toolName:String(Y.tool_name??""),input:sv1(Y.input),output:sv1(Y.output),isError:Y.is_error===1||Y.is_error===!0||Y.is_error==="1",errorMessage:Y.error_message!=null?String(Y.error_message):null,durationMs:Number(Y.duration_ms??0),timestamp:Y.timestamp instanceof Date?Y.timestamp.toISOString():String(Y.timestamp??""),userId:Y.user_id!=null?String(Y.user_id):null,requestId:String(Y.request_id??""),userAgent:Y.user_agent!=null?String(Y.user_agent):null,virtualMcpId:Y.virtual_mcp_id!=null?String(Y.virtual_mcp_id):null,properties:Y.properties?sv1(Y.properties):null}}function cK6(Y){let X=[];if(Y.properties)for(let[J,G]of Object.entries(Y.properties)){let W=JJ(J),Z=JJ(G);X.push(`JSONExtractString(properties, '${W}') = '${Z}'`)}if(Y.propertyKeys)for(let J of Y.propertyKeys){let G=JJ(J);X.push(`JSONExtractString(properties, '${G}') IS NOT NULL AND JSONExtractString(properties, '${G}') != ''`)}if(Y.propertyPatterns)for(let[J,G]of Object.entries(Y.propertyPatterns)){let W=JJ(J),Z=JJ(G);X.push(`JSONExtractString(properties, '${W}') ILIKE '${Z}'`)}if(Y.propertyInValues)for(let[J,G]of Object.entries(Y.propertyInValues)){let W=JJ(J),Z=JJ(G);X.push(`has(splitByChar(',', JSONExtractString(properties, '${W}')), '${Z}')`)}return X}function dK6(Y){if(!Y)return[];let X=[];if(Y.connectionIds?.length){let J=Y.connectionIds.map((G)=>`'${JJ(G)}'`).join(",");X.push(`connection_id IN (${J})`)}if(Y.toolNames?.length){let J=Y.toolNames.map((G)=>`'${JJ(G)}'`).join(",");X.push(`tool_name IN (${J})`)}if(Y.virtualMcpIds?.length){let J=Y.virtualMcpIds.map((G)=>`'${JJ(G)}'`).join(",");X.push(`virtual_mcp_id IN (${J})`)}if(Y.startDate)X.push(tv1(Y.startDate));if(Y.endDate)X.push(ev1(Y.endDate));if(Y.propertyFilters)X.push(...cK6(Y.propertyFilters));return X}function tv1(Y){return`parseDateTime64BestEffort(toString(timestamp)) >= parseDateTime64BestEffort('${Y.toISOString()}')`}function ev1(Y){return`parseDateTime64BestEffort(toString(timestamp)) <= parseDateTime64BestEffort('${Y.toISOString()}')`}class Yf1{engine;source;constructor(Y,X){this.engine=Y;this.source=X}async query(Y){if(!Y.organizationId)throw Error("organizationId is required");let X=[`organization_id = '${JJ(Y.organizationId)}'`];if(Y.connectionId)X.push(`connection_id = '${JJ(Y.connectionId)}'`);if(Y.excludeConnectionIds?.length){let $=Y.excludeConnectionIds.map((F)=>`'${JJ(F)}'`).join(",");X.push(`connection_id NOT IN (${$})`)}if(Y.virtualMcpId)X.push(`virtual_mcp_id = '${JJ(Y.virtualMcpId)}'`);if(Y.toolName)X.push(`tool_name = '${JJ(Y.toolName)}'`);if(Y.isError!==void 0)X.push(`is_error = ${Y.isError?1:0}`);if(Y.startDate)X.push(tv1(Y.startDate));if(Y.endDate)X.push(ev1(Y.endDate));if(Y.propertyFilters)X.push(...cK6(Y.propertyFilters));let J=1000,G=Math.min(Math.max(1,Math.floor(Y.limit??50)),J),W=Math.max(0,Math.floor(Y.offset??0)),Z=`SELECT *, count(*) OVER () AS _total FROM ${this.source} WHERE ${X.join(" AND ")} ORDER BY timestamp DESC LIMIT ${G} OFFSET ${W}`,K=await this.engine.query(Z);if(K.length===0)return{logs:[],total:0};let Q=Number(K[0]._total??0);return{logs:K.map(tZ8),total:Q}}async getStats(Y){if(!Y.organizationId)throw Error("organizationId is required");let X=[`organization_id = '${JJ(Y.organizationId)}'`];if(Y.startDate)X.push(tv1(Y.startDate));if(Y.endDate)X.push(ev1(Y.endDate));let J=`SELECT count(*) AS total_calls, coalesce(sum(CASE WHEN is_error = 1 THEN 1.0 ELSE 0.0 END) / NULLIF(count(*), 0), 0) AS error_rate, coalesce(avg(duration_ms), 0) AS avg_duration_ms FROM ${this.source} WHERE ${X.join(" AND ")}`,W=(await this.engine.query(J))[0]??{};return{totalCalls:Number(W.total_calls??0),errorRate:Number(W.error_rate??0),avgDurationMs:Number(W.avg_duration_ms??0)}}async aggregate(Y){if(!Y.organizationId)throw Error("organizationId is required");let X=rv1(Y.path),J=Y.from==="input"?"input":"output",G=ov1(X),W=Y.aggregation==="count"||Y.aggregation==="count_all"?"1":`JSONExtractFloat(${J}, ${G})`,Z=eZ8(Y.aggregation,W),K=[`organization_id = '${JJ(Y.organizationId)}'`];if(Y.aggregation==="count")K.push(`JSONExtractString(${J}, ${G}) IS NOT NULL`),K.push(`JSONExtractString(${J}, ${G}) != ''`);if(Y.aggregation!=="count"&&Y.aggregation!=="count_all")K.push(`JSONExtractString(${J}, ${G}) IS NOT NULL`),K.push(`JSONExtractString(${J}, ${G}) != ''`);K.push(...dK6(Y.filters));let Q=K.join(" AND "),H=Math.min(Math.max(1,Math.floor(Y.limit??1e4)),1e4);if(Y.groupByColumn){let V=nZ8(Y.groupByColumn),z=`SELECT ${V} AS group_key, ${Z} AS value FROM ${this.source} WHERE ${Q} GROUP BY ${V} ORDER BY value DESC LIMIT ${H}`;return{value:null,groups:(await this.engine.query(z)).map((B)=>({key:String(B.group_key??""),value:Number(B.value??0)}))}}if(Y.groupBy){let V=rv1(Y.groupBy),z=Y.from==="input"?"input":"output",U=ov1(V),B=`JSONExtractString(${z}, ${U})`,D=`SELECT ${B} AS group_key, ${Z} AS value FROM ${this.source} WHERE ${Q} AND ${B} != '' GROUP BY ${B} ORDER BY value DESC LIMIT ${H}`;return{value:null,groups:(await this.engine.query(D)).map((w)=>({key:String(w.group_key??""),value:Number(w.value??0)}))}}if(Y.interval){let z=`SELECT ${sZ8(Y.interval)} AS bucket, ${Z} AS value FROM ${this.source} WHERE ${Q} GROUP BY bucket ORDER BY bucket ASC LIMIT ${H}`;return{value:null,timeseries:(await this.engine.query(z)).map((B)=>({timestamp:String(B.bucket??""),value:Number(B.value??0)}))}}let $=`SELECT ${Z} AS value FROM ${this.source} WHERE ${Q}`,F=await this.engine.query($);return{value:Number(F[0]?.value??0)}}async countMatched(Y){if(!Y.organizationId)throw Error("organizationId is required");let X=rv1(Y.path),J=Y.from==="input"?"input":"output",G=ov1(X),W=[`organization_id = '${JJ(Y.organizationId)}'`,`JSONExtractString(${J}, ${G}) IS NOT NULL`,`JSONExtractString(${J}, ${G}) != ''`];W.push(...dK6(Y.filters));let Z=`SELECT count(*) AS cnt FROM ${this.source} WHERE ${W.join(" AND ")}`,K=await this.engine.query(Z);return Number(K[0]?.cnt??0)}}function eZ8(Y,X){switch(Y){case"sum":return`coalesce(sum(${X}), 0)`;case"avg":return`coalesce(avg(${X}), 0)`;case"min":return`min(${X})`;case"max":return`max(${X})`;case"count":return"count(*)";case"count_all":return"count(*)";case"last":return`argMax(${X}, timestamp)`;default:throw Error(`Unknown aggregation function: ${Y}`)}}var pZ8,iZ8,aZ8,rZ8;var pK6=y(()=>{pZ8=new Set(["connection_id","connection_title","user_id","tool_name","virtual_mcp_id"]);iZ8=/^(\$\.)?[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*$/;aZ8=/^(\d+)([mhd])$/,rZ8={m:525960,h:8760,d:365}});var aK6=n((ASY,iK6)=>{var __dirname="/home/runner/work/studio/studio/node_modules/.bun/chdb@1.6.0/node_modules/chdb",YQ8=V0("path"),ru=V0(YQ8.join(__dirname,"build","Release","chdb_node.node")),{mkdtempSync:XQ8,rmSync:JQ8}=V0("fs"),{join:GQ8}=V0("path"),WQ8=V0("os");function ZQ8(Y,X="CSV"){if(!Y)return"";return ru.Query(Y,X)}function QQ8(Y,X={},J="CSV"){if(!Y)return"";return ru.QueryBindSession(Y,X,J)}class nK6{constructor(Y=""){if(Y==="")this.path=XQ8(GQ8(WQ8.tmpdir(),"tmp-chdb-node")),this.isTemp=!0;else this.path=Y,this.isTemp=!1;if(this.connection=ru.CreateConnection(this.path),!this.connection)throw Error("Failed to create connection")}query(Y,X="CSV"){if(!Y)return"";if(!this.connection)throw Error("No active connection available");return ru.QueryWithConnection(this.connection,Y,X)}queryBind(Y,X={},J="CSV"){throw Error("QueryBind is not supported with connection-based sessions. Please use the standalone queryBind function instead.")}cleanup(){if(this.connection)ru.CloseConnection(this.connection),this.connection=null;if(this.isTemp)JQ8(this.path,{recursive:!0})}}iK6.exports={query:ZQ8,queryBind:QQ8,Session:nK6}});var FY1=n((sK6)=>{Object.defineProperty(sK6,"__esModule",{value:!0});sK6.ClickHouseLogLevel=sK6.LogWriter=sK6.DefaultLogger=void 0;class rK6{trace({module:Y,message:X,args:J}){let G=[ou({module:Y,message:X,level:"TRACE"})];if(J)G.push(`
|
|
1993
|
+
`.execute(Y)}}if(Z>0)console.log(`\u2705 ${Z} plugin migration(s) completed`)}async function fQ6(Y){await HZ8(Y),await $Z8(Y);let X=new Xd({db:Y,provider:{getMigrations:()=>Promise.resolve(Na)}}),{error:J,results:G}=await X.migrateToLatest();if(G?.forEach((W)=>{if(W.status==="Success")console.log(`\u2705 Migration "${W.migrationName}" executed successfully`);else if(W.status==="Error")console.error(`\u274C Failed to execute migration "${W.migrationName}"`)}),J)throw console.error("Failed to migrate"),console.error(J),J}async function VZ8(Y){let{keepOpen:X=!1,database:J,skipBetterAuth:G=!1,seed:W}=Y??{};if(!G&&!J)await _Q6();let Z=J??sK(),K=async()=>{if(!X&&!J)console.log("\uD83D\uDD12 Closing database connection..."),await A76(Z).catch((Q)=>{console.warn("Warning: Error closing database:",Q)})};try{console.log("\uD83D\uDCCA Running Kysely migrations..."),await fQ6(Z.db),console.log("\uD83C\uDF89 Core migrations completed successfully"),await FZ8(Z.db);let Q;if(W)Q=await ZN1(Z.db,W);return await K(),{seedResult:Q}}catch(Q){throw await K(),Q}}async function zZ8(){let Y=sK(),X=new Xd({db:Y.db,provider:{getMigrations:()=>Promise.resolve(Na)}}),{error:J,results:G}=await X.migrateDown();if(G?.forEach((W)=>{if(W.status==="Success")console.log(`\u2705 Migration "${W.migrationName}" rolled back successfully`);else if(W.status==="Error")console.error(`\u274C Failed to rollback migration "${W.migrationName}"`)}),J)throw console.error("Failed to rollback migration"),console.error(J),J}var bQ6=y(()=>{F9();BF1();b30();kQ6();ZT();dj()});var b5;var WI=y(()=>{b5=class extends Error{res;status;constructor(Y=500,X){super(X?.message,{cause:X?.cause});this.res=X?.res,this.status=Y}getResponse(){if(this.res)return new Response(this.res.body,{status:this.status,headers:this.res.headers});return new Response(this.message,{status:this.status})}}});var hQ6,UZ8,BZ8=(Y,X)=>{if(!Y)return{};let J=new Headers(Y.headers);if(X){let G=J.get("connection");if(G){let W=G.split(",").map((K)=>K.trim()),Z=W.filter((K)=>!UZ8.test(K));if(Z.length>0)throw new b5(400,{message:`Invalid Connection header value: ${Z.join(", ")}`});W.forEach((K)=>{J.delete(K)})}}return hQ6.forEach((G)=>{J.delete(G)}),{method:Y.method,body:Y.body,duplex:Y.body?"half":void 0,headers:J,signal:Y.signal}},qZ8=(Y)=>{if(!Y.headers||Array.isArray(Y.headers)||Y.headers instanceof Headers)return Y;let X=new Headers;for(let[J,G]of Object.entries(Y.headers))if(G==null)X.delete(J);else X.set(J,G);return Y.headers=X,Y},xQ6=async(Y,X)=>{let{raw:J,customFetch:G,strictConnectionProcessing:W=!1,...Z}=X instanceof Request?{raw:X}:X??{},K=new Request(Y,{...BZ8(J,W),...qZ8(Z)});K.headers.delete("accept-encoding");let Q=await(G||fetch)(K),H=new Headers(Q.headers);if(hQ6.forEach(($)=>{H.delete($)}),H.has("content-encoding"))H.delete("content-encoding"),H.delete("content-length");return new Response(Q.body,{status:Q.status,statusText:Q.statusText,headers:H})};var gQ6=y(()=>{WI();hQ6=["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"],UZ8=/^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/});var uQ6=(Y)=>(X)=>{let J=new URL(X.req.raw.url),G=new URL(Y);return G.pathname=J.pathname,G.search=J.search,xQ6(G,{raw:X.req.raw,headers:{...X.req.raw.headers}})};var mQ6=y(()=>{gQ6()});import{resolve as mu,dirname as DZ8,join as OZ8,extname as LZ8,basename as NZ8,sep as lQ6}from"path";function MZ8(Y,X){if(Y===X||NZ8(Y)==="index.html")return{"Cache-Control":"no-cache"};if(Y.includes(`${lQ6}assets${lQ6}`))return{"Cache-Control":"public, max-age=31536000, immutable"};return{}}function PZ8(Y,X){let J=mu(X),G=mu(Y);return G===J||G.startsWith(J+"/")}function EZ8({requestPath:Y,clientDir:X}){let J=Y.startsWith("/")?Y.slice(1):Y,G=mu(X,J);if(!PZ8(G,X))return null;return G}function kv1(Y,X="../client"){let J=new URL(Y),G=DZ8(J.pathname);return mu(G,X)}function dQ6(Y={}){let{env:X="production",devServerUrl:J=wZ8,clientDir:G=AZ8,isServerPath:W=()=>!1}=Y;if(X==="development"){let Z=uQ6(J);return async function(Q){let H=new URL(Q.url);if(W(H.pathname))return null;let $={req:{raw:Q,url:Q.url}};return Z($)}}return async function(K){if(K.method!=="GET")return null;let Q=new URL(K.url),H;try{H=decodeURIComponent(Q.pathname)}catch{return null}if(W(H))return null;let $=EZ8({requestPath:H,clientDir:G});if(!$)return null;let F=OZ8($,"index.html"),V=mu(G,"index.html"),z=K.headers.get("accept"),B=z?.includes("text/html")||z?.includes("*/*")&&["",".html"].includes(LZ8($))?[F,V]:[];for(let D of[$,...B])try{let L=Bun.file(D);if(await L.exists())return new Response(L,{headers:MZ8(D,V)})}catch{}if(H.includes("/assets/"))return new Response("Not Found",{status:404,headers:{"Cache-Control":"no-store"}});return null}}var wZ8,AZ8="./dist/client";var cQ6=y(()=>{mQ6();wZ8=`http://localhost:${process.env.VITE_PORT||"4000"}`});function nQ6(Y){if(!Y)return!1;try{return new URL(Y).host==="api.decocms.com"&&Y!=="https://studio.decocms.com/org/deco/registry/mcp"}catch{return!1}}var pQ6="https://studio.decocms.com/org/deco/registry/mcp";var vv1=(Y,X,J)=>{return(G,W)=>{let Z=-1;return K(0);async function K(Q){if(Q<=Z)throw Error("next() called multiple times");Z=Q;let H,$=!1,F;if(Y[Q])F=Y[Q][0][0],G.req.routeIndex=Q;else F=Q===Y.length&&W||void 0;if(F)try{H=await F(G,()=>K(Q+1))}catch(V){if(V instanceof Error&&X)G.error=V,H=await X(V,G),$=!0;else throw V}else if(G.finalized===!1&&J)H=await J(G);if(H&&(G.finalized===!1||$))G.res=H;return G}}};var iQ6=()=>{};var aQ6;var rQ6=y(()=>{aQ6=Symbol()});async function RZ8(Y,X){let J=await Y.formData();if(J)return TZ8(J,X);return{}}function TZ8(Y,X){let J=Object.create(null);if(Y.forEach((G,W)=>{if(!(X.all||W.endsWith("[]")))J[W]=G;else CZ8(J,W,G)}),X.dot)Object.entries(J).forEach(([G,W])=>{if(G.includes("."))jZ8(J,G,W),delete J[G]});return J}var oQ6=async(Y,X=Object.create(null))=>{let{all:J=!1,dot:G=!1}=X,Z=(Y instanceof e91?Y.raw.headers:Y.headers).get("Content-Type");if(Z?.startsWith("multipart/form-data")||Z?.startsWith("application/x-www-form-urlencoded"))return RZ8(Y,{all:J,dot:G});return{}},CZ8=(Y,X,J)=>{if(Y[X]!==void 0)if(Array.isArray(Y[X]))Y[X].push(J);else Y[X]=[Y[X],J];else if(!X.endsWith("[]"))Y[X]=J;else Y[X]=[J]},jZ8=(Y,X,J)=>{if(/(?:^|\.)__proto__\./.test(X))return;let G=Y,W=X.split(".");W.forEach((Z,K)=>{if(K===W.length-1)G[Z]=J;else{if(!G[Z]||typeof G[Z]!=="object"||Array.isArray(G[Z])||G[Z]instanceof File)G[Z]=Object.create(null);G=G[Z]}})};var sQ6=y(()=>{fv1()});var bv1=(Y)=>{let X=Y.split("/");if(X[0]==="")X.shift();return X},tQ6=(Y)=>{let{groups:X,path:J}=IZ8(Y),G=bv1(J);return SZ8(G,X)},IZ8=(Y)=>{let X=[];return Y=Y.replace(/\{[^}]+\}/g,(J,G)=>{let W=`@${G}`;return X.push([W,J]),W}),{groups:X,path:Y}},SZ8=(Y,X)=>{for(let J=X.length-1;J>=0;J--){let[G]=X[J];for(let W=Y.length-1;W>=0;W--)if(Y[W].includes(G)){Y[W]=Y[W].replace(G,X[J][1]);break}}return Y},YY1,eQ6=(Y,X)=>{if(Y==="*")return"*";let J=Y.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(J){let G=`${Y}#${X}`;if(!YY1[G])if(J[2])YY1[G]=X&&X[0]!==":"&&X[0]!=="*"?[G,J[1],new RegExp(`^${J[2]}(?=/${X})`)]:[Y,J[1],new RegExp(`^${J[2]}$`)];else YY1[G]=[Y,J[1],!0];return YY1[G]}return null},ZI=(Y,X)=>{try{return X(Y)}catch{return Y.replace(/(?:%[0-9A-Fa-f]{2})+/g,(J)=>{try{return X(J)}catch{return J}})}},YK6=(Y)=>ZI(Y,decodeURI),hv1=(Y)=>{let X=Y.url,J=X.indexOf("/",X.indexOf(":")+4),G=J;for(;G<X.length;G++){let W=X.charCodeAt(G);if(W===37){let Z=X.indexOf("?",G),K=X.indexOf("#",G),Q=Z===-1?K===-1?void 0:K:K===-1?Z:Math.min(Z,K),H=X.slice(J,Q);return YK6(H.includes("%25")?H.replace(/%25/g,"%2525"):H)}else if(W===63||W===35)break}return X.slice(J,G)},XK6=(Y)=>{let X=hv1(Y);return X.length>1&&X.at(-1)==="/"?X.slice(0,-1):X},MA=(Y,X,...J)=>{if(J.length)X=MA(X,...J);return`${Y?.[0]==="/"?"":"/"}${Y}${X==="/"?"":`${Y?.at(-1)==="/"?"":"/"}${X?.[0]==="/"?X.slice(1):X}`}`},XY1=(Y)=>{if(Y.charCodeAt(Y.length-1)!==63||!Y.includes(":"))return null;let X=Y.split("/"),J=[],G="";return X.forEach((W)=>{if(W!==""&&!/\:/.test(W))G+="/"+W;else if(/\:/.test(W))if(/\?/.test(W)){if(J.length===0&&G==="")J.push("/");else J.push(G);let Z=W.replace("?","");G+="/"+Z,J.push(G)}else G+="/"+W}),J.filter((W,Z,K)=>K.indexOf(W)===Z)},yv1=(Y)=>{if(!/[%+]/.test(Y))return Y;if(Y.indexOf("+")!==-1)Y=Y.replace(/\+/g," ");return Y.indexOf("%")!==-1?ZI(Y,lu):Y},JK6=(Y,X,J)=>{let G;if(!J&&X&&!/[%+]/.test(X)){let K=Y.indexOf("?",8);if(K===-1)return;if(!Y.startsWith(X,K+1))K=Y.indexOf(`&${X}`,K+1);while(K!==-1){let Q=Y.charCodeAt(K+X.length+1);if(Q===61){let H=K+X.length+2,$=Y.indexOf("&",H);return yv1(Y.slice(H,$===-1?void 0:$))}else if(Q==38||isNaN(Q))return"";K=Y.indexOf(`&${X}`,K+1)}if(G=/[%+]/.test(Y),!G)return}let W={};G??=/[%+]/.test(Y);let Z=Y.indexOf("?",8);while(Z!==-1){let K=Y.indexOf("&",Z+1),Q=Y.indexOf("=",Z);if(Q>K&&K!==-1)Q=-1;let H=Y.slice(Z+1,Q===-1?K===-1?void 0:K:Q);if(G)H=yv1(H);if(Z=K,H==="")continue;let $;if(Q===-1)$="";else if($=Y.slice(Q+1,K===-1?void 0:K),G)$=yv1($);if(J){if(!(W[H]&&Array.isArray(W[H])))W[H]=[];W[H].push($)}else W[H]??=$}return X?W[X]:W},GK6,WK6=(Y,X)=>{return JK6(Y,X,!0)},lu;var IO=y(()=>{YY1={},GK6=JK6,lu=decodeURIComponent});var ZK6=(Y)=>ZI(Y,lu),e91;var fv1=y(()=>{WI();rQ6();sQ6();IO();e91=class{raw;#Y;#X;routeIndex=0;path;bodyCache={};constructor(Y,X="/",J=[[]]){this.raw=Y,this.path=X,this.#X=J,this.#Y={}}param(Y){return Y?this.#J(Y):this.#G()}#J(Y){let X=this.#X[0][this.routeIndex][1][Y],J=this.#W(X);return J&&/\%/.test(J)?ZK6(J):J}#G(){let Y={},X=Object.keys(this.#X[0][this.routeIndex][1]);for(let J of X){let G=this.#W(this.#X[0][this.routeIndex][1][J]);if(G!==void 0)Y[J]=/\%/.test(G)?ZK6(G):G}return Y}#W(Y){return this.#X[1]?this.#X[1][Y]:Y}query(Y){return GK6(this.url,Y)}queries(Y){return WK6(this.url,Y)}header(Y){if(Y)return this.raw.headers.get(Y)??void 0;let X={};return this.raw.headers.forEach((J,G)=>{X[G]=J}),X}async parseBody(Y){return this.bodyCache.parsedBody??=await oQ6(this,Y)}#Z=(Y)=>{let{bodyCache:X,raw:J}=this,G=X[Y];if(G)return G;let W=Object.keys(X)[0];if(W)return X[W].then((Z)=>{if(W==="json")Z=JSON.stringify(Z);return new Response(Z)[Y]()});return X[Y]=J[Y]()};json(){return this.#Z("text").then((Y)=>JSON.parse(Y))}text(){return this.#Z("text")}arrayBuffer(){return this.#Z("arrayBuffer")}blob(){return this.#Z("blob")}formData(){return this.#Z("formData")}addValidatedData(Y,X){this.#Y[Y]=X}valid(Y){return this.#Y[Y]}get url(){return this.raw.url}get method(){return this.raw.method}get[aQ6](){return this.#X}get matchedRoutes(){return this.#X[0].map(([[,Y]])=>Y)}get routePath(){return this.#X[0].map(([[,Y]])=>Y)[this.routeIndex].path}}});var JY1,QK6=(Y,X)=>{let J=new String(Y);return J.isEscaped=!0,J.callbacks=X,J},du=async(Y,X,J,G,W)=>{if(typeof Y==="object"&&!(Y instanceof String)){if(!(Y instanceof Promise))Y=Y.toString();if(Y instanceof Promise)Y=await Y}let Z=Y.callbacks;if(!Z?.length)return Promise.resolve(Y);if(W)W[0]+=Y;else W=[Y];let K=Promise.all(Z.map((Q)=>Q({phase:X,buffer:W,context:G}))).then((Q)=>Promise.all(Q.filter(Boolean).map((H)=>du(H,X,!1,G,W))).then(()=>W[0]));if(J)return QK6(await K,Z);else return K};var GY1=y(()=>{JY1={Stringify:1,BeforeStream:2,Stream:3}});var KK6="text/plain; charset=UTF-8",xv1=(Y,X)=>{return{"Content-Type":Y,...X}},cu=(Y,X)=>new Response(Y,X),HK6=class{#Y;#X;env={};#J;finalized=!1;error;#G;#W;#Z;#K;#Q;#H;#$;#V;#U;constructor(Y,X){if(this.#Y=Y,X)this.#W=X.executionCtx,this.env=X.env,this.#H=X.notFoundHandler,this.#U=X.path,this.#V=X.matchResult}get req(){return this.#X??=new e91(this.#Y,this.#U,this.#V),this.#X}get event(){if(this.#W&&"respondWith"in this.#W)return this.#W;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#W)return this.#W;else throw Error("This context has no ExecutionContext")}get res(){return this.#Z||=cu(null,{headers:this.#$??=new Headers})}set res(Y){if(this.#Z&&Y){Y=cu(Y.body,Y);for(let[X,J]of this.#Z.headers.entries()){if(X==="content-type")continue;if(X==="set-cookie"){let G=this.#Z.headers.getSetCookie();Y.headers.delete("set-cookie");for(let W of G)Y.headers.append("set-cookie",W)}else Y.headers.set(X,J)}}this.#Z=Y,this.finalized=!0}render=(...Y)=>{return this.#Q??=(X)=>this.html(X),this.#Q(...Y)};setLayout=(Y)=>this.#K=Y;getLayout=()=>this.#K;setRenderer=(Y)=>{this.#Q=Y};header=(Y,X,J)=>{if(this.finalized)this.#Z=cu(this.#Z.body,this.#Z);let G=this.#Z?this.#Z.headers:this.#$??=new Headers;if(X===void 0)G.delete(Y);else if(J?.append)G.append(Y,X);else G.set(Y,X)};status=(Y)=>{this.#G=Y};set=(Y,X)=>{this.#J??=new Map,this.#J.set(Y,X)};get=(Y)=>{return this.#J?this.#J.get(Y):void 0};get var(){if(!this.#J)return{};return Object.fromEntries(this.#J)}#F(Y,X,J){let G=this.#Z?new Headers(this.#Z.headers):this.#$??new Headers;if(typeof X==="object"&&"headers"in X){let Z=X.headers instanceof Headers?X.headers:new Headers(X.headers);for(let[K,Q]of Z)if(K.toLowerCase()==="set-cookie")G.append(K,Q);else G.set(K,Q)}if(J)for(let[Z,K]of Object.entries(J))if(typeof K==="string")G.set(Z,K);else{G.delete(Z);for(let Q of K)G.append(Z,Q)}let W=typeof X==="number"?X:X?.status??this.#G;return cu(Y,{status:W,headers:G})}newResponse=(...Y)=>this.#F(...Y);body=(Y,X,J)=>this.#F(Y,X,J);text=(Y,X,J)=>{return!this.#$&&!this.#G&&!X&&!J&&!this.finalized?new Response(Y):this.#F(Y,X,xv1(KK6,J))};json=(Y,X,J)=>{return this.#F(JSON.stringify(Y),X,xv1("application/json",J))};html=(Y,X,J)=>{let G=(W)=>this.#F(W,X,xv1("text/html; charset=UTF-8",J));return typeof Y==="object"?du(Y,JY1.Stringify,!1,{}).then(G):G(Y)};redirect=(Y,X)=>{let J=String(Y);return this.header("Location",!/[^\x00-\xFF]/.test(J)?J:encodeURI(J)),this.newResponse(null,X??302)};notFound=()=>{return this.#H??=()=>cu(),this.#H(this)}};var WY1=y(()=>{fv1();GY1()});var hY="ALL",$K6="all",FK6,ZY1="Can not add a route since the matcher is already built.",QY1;var SO=y(()=>{FK6=["get","post","put","delete","options","patch"],QY1=class extends Error{}});var gv1="__COMPOSED_HANDLER";var uv1=()=>{};var _Z8=(Y)=>{return Y.text("404 Not Found",404)},VK6=(Y,X)=>{if("getResponse"in Y){let J=Y.getResponse();return X.newResponse(J.body,J)}return console.error(Y),X.text("Internal Server Error",500)},zK6=class Y{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#Y="/";routes=[];constructor(X={}){[...FK6,$K6].forEach((Z)=>{this[Z]=(K,...Q)=>{if(typeof K==="string")this.#Y=K;else this.#G(Z,this.#Y,K);return Q.forEach((H)=>{this.#G(Z,this.#Y,H)}),this}}),this.on=(Z,K,...Q)=>{for(let H of[K].flat()){this.#Y=H;for(let $ of[Z].flat())Q.map((F)=>{this.#G($.toUpperCase(),this.#Y,F)})}return this},this.use=(Z,...K)=>{if(typeof Z==="string")this.#Y=Z;else this.#Y="*",K.unshift(Z);return K.forEach((Q)=>{this.#G(hY,this.#Y,Q)}),this};let{strict:G,...W}=X;Object.assign(this,W),this.getPath=G??!0?X.getPath??hv1:XK6}#X(){let X=new Y({router:this.router,getPath:this.getPath});return X.errorHandler=this.errorHandler,X.#J=this.#J,X.routes=this.routes,X}#J=_Z8;errorHandler=VK6;route(X,J){let G=this.basePath(X);return J.routes.map((W)=>{let Z;if(J.errorHandler===VK6)Z=W.handler;else Z=async(K,Q)=>(await vv1([],J.errorHandler)(K,()=>W.handler(K,Q))).res,Z[gv1]=W.handler;G.#G(W.method,W.path,Z)}),this}basePath(X){let J=this.#X();return J._basePath=MA(this._basePath,X),J}onError=(X)=>{return this.errorHandler=X,this};notFound=(X)=>{return this.#J=X,this};mount(X,J,G){let W,Z;if(G)if(typeof G==="function")Z=G;else if(Z=G.optionHandler,G.replaceRequest===!1)W=(H)=>H;else W=G.replaceRequest;let K=Z?(H)=>{let $=Z(H);return Array.isArray($)?$:[$]}:(H)=>{let $=void 0;try{$=H.executionCtx}catch{}return[H.env,$]};W||=(()=>{let H=MA(this._basePath,X),$=H==="/"?0:H.length;return(F)=>{let V=new URL(F.url);return V.pathname=V.pathname.slice($)||"/",new Request(V,F)}})();let Q=async(H,$)=>{let F=await J(W(H.req.raw),...K(H));if(F)return F;await $()};return this.#G(hY,MA(X,"*"),Q),this}#G(X,J,G){X=X.toUpperCase(),J=MA(this._basePath,J);let W={basePath:this._basePath,path:J,method:X,handler:G};this.router.add(X,J,[G,W]),this.routes.push(W)}#W(X,J){if(X instanceof Error)return this.errorHandler(X,J);throw X}#Z(X,J,G,W){if(W==="HEAD")return(async()=>new Response(null,await this.#Z(X,J,G,"GET")))();let Z=this.getPath(X,{env:G}),K=this.router.match(W,Z),Q=new HK6(X,{path:Z,matchResult:K,env:G,executionCtx:J,notFoundHandler:this.#J});if(K[0].length===1){let $;try{$=K[0][0][0][0](Q,async()=>{Q.res=await this.#J(Q)})}catch(F){return this.#W(F,Q)}return $ instanceof Promise?$.then((F)=>F||(Q.finalized?Q.res:this.#J(Q))).catch((F)=>this.#W(F,Q)):$??this.#J(Q)}let H=vv1(K[0],this.errorHandler,this.#J);return(async()=>{try{let $=await H(Q);if(!$.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return $.res}catch($){return this.#W($,Q)}})()}fetch=(X,...J)=>{return this.#Z(X,J[1],J[0],X.method)};request=(X,J,G,W)=>{if(X instanceof Request)return this.fetch(J?new Request(X,J):X,G,W);return X=X.toString(),this.fetch(new Request(/^https?:\/\//.test(X)?X:`http://localhost${MA("/",X)}`,J),G,W)};fire=()=>{addEventListener("fetch",(X)=>{X.respondWith(this.#Z(X.request,X,void 0,X.request.method))})}};var UK6=y(()=>{iQ6();WY1();SO();uv1();IO()});function KY1(Y,X){let J=this.buildAllMatchers(),G=(W,Z)=>{let K=J[W]||J[hY],Q=K[2][Z];if(Q)return Q;let H=Z.match(K[0]);if(!H)return[[],pu];let $=H.indexOf("",1);return[K[1][$],H]};return this.match=G,G(Y,X)}var pu;var mv1=y(()=>{SO();pu=[]});function vZ8(Y,X){if(Y.length===1)return X.length===1?Y<X?-1:1:-1;if(X.length===1)return 1;if(Y===nu||Y===iu)return 1;else if(X===nu||X===iu)return-1;if(Y===HY1)return 1;else if(X===HY1)return-1;return Y.length===X.length?Y<X?-1:1:X.length-Y.length}var HY1="[^/]+",nu=".*",iu="(?:|/.*)",wA,kZ8,BK6=class Y{#Y;#X;#J=Object.create(null);insert(X,J,G,W,Z){if(X.length===0){if(this.#Y!==void 0)throw wA;if(Z)return;this.#Y=J;return}let[K,...Q]=X,H=K==="*"?Q.length===0?["","",nu]:["","",HY1]:K==="/*"?["","",iu]:K.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),$;if(H){let F=H[1],V=H[2]||HY1;if(F&&H[2]){if(V===".*")throw wA;if(V=V.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(V))throw wA}if($=this.#J[V],!$){if(Object.keys(this.#J).some((z)=>z!==nu&&z!==iu))throw wA;if(Z)return;if($=this.#J[V]=new Y,F!=="")$.#X=W.varIndex++}if(!Z&&F!=="")G.push([F,$.#X])}else if($=this.#J[K],!$){if(Object.keys(this.#J).some((F)=>F.length>1&&F!==nu&&F!==iu))throw wA;if(Z)return;$=this.#J[K]=new Y}$.insert(Q,J,G,W,Z)}buildRegExpStr(){let J=Object.keys(this.#J).sort(vZ8).map((G)=>{let W=this.#J[G];return(typeof W.#X==="number"?`(${G})@${W.#X}`:kZ8.has(G)?`\\${G}`:G)+W.buildRegExpStr()});if(typeof this.#Y==="number")J.unshift(`#${this.#Y}`);if(J.length===0)return"";if(J.length===1)return J[0];return"(?:"+J.join("|")+")"}};var lv1=y(()=>{wA=Symbol(),kZ8=new Set(".\\+*[^]$()")});var qK6=class{#Y={varIndex:0};#X=new BK6;insert(Y,X,J){let G=[],W=[];for(let K=0;;){let Q=!1;if(Y=Y.replace(/\{[^}]+\}/g,(H)=>{let $=`@\\${K}`;return W[K]=[$,H],K++,Q=!0,$}),!Q)break}let Z=Y.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let K=W.length-1;K>=0;K--){let[Q]=W[K];for(let H=Z.length-1;H>=0;H--)if(Z[H].indexOf(Q)!==-1){Z[H]=Z[H].replace(Q,W[K][1]);break}}return this.#X.insert(Z,X,G,this.#Y,J),G}buildRegExp(){let Y=this.#X.buildRegExpStr();if(Y==="")return[/^$/,[],[]];let X=0,J=[],G=[];return Y=Y.replace(/#(\d+)|@(\d+)|\.\*\$/g,(W,Z,K)=>{if(Z!==void 0)return J[++X]=Number(Z),"$()";if(K!==void 0)return G[Number(K)]=++X,"";return""}),[new RegExp(`^${Y}`),J,G]}};var DK6=y(()=>{lv1()});function LK6(Y){return OK6[Y]??=new RegExp(Y==="*"?"":`^${Y.replace(/\/\*$|([.\\+*[^\]$()])/g,(X,J)=>J?`\\${J}`:"(?:|/.*)")}$`)}function yZ8(){OK6=Object.create(null)}function bZ8(Y){let X=new qK6,J=[];if(Y.length===0)return fZ8;let G=Y.map(($)=>[!/\*|\/:/.test($[0]),...$]).sort(([$,F],[V,z])=>$?1:V?-1:F.length-z.length),W=Object.create(null);for(let $=0,F=-1,V=G.length;$<V;$++){let[z,U,B]=G[$];if(z)W[U]=[B.map(([L])=>[L,Object.create(null)]),pu];else F++;let D;try{D=X.insert(U,F,z)}catch(L){throw L===wA?new QY1(U):L}if(z)continue;J[F]=B.map(([L,w])=>{let N=Object.create(null);w-=1;for(;w>=0;w--){let[R,P]=D[w];N[R]=P}return[L,N]})}let[Z,K,Q]=X.buildRegExp();for(let $=0,F=J.length;$<F;$++)for(let V=0,z=J[$].length;V<z;V++){let U=J[$][V]?.[1];if(!U)continue;let B=Object.keys(U);for(let D=0,L=B.length;D<L;D++)U[B[D]]=Q[U[B[D]]]}let H=[];for(let $ in K)H[$]=J[K[$]];return[Z,H,W]}function QI(Y,X){if(!Y)return;for(let J of Object.keys(Y).sort((G,W)=>W.length-G.length))if(LK6(J).test(X))return[...Y[J]];return}var fZ8,OK6,$Y1=class{name="RegExpRouter";#Y;#X;constructor(){this.#Y={[hY]:Object.create(null)},this.#X={[hY]:Object.create(null)}}add(Y,X,J){let G=this.#Y,W=this.#X;if(!G||!W)throw Error(ZY1);if(!G[Y])[G,W].forEach((Q)=>{Q[Y]=Object.create(null),Object.keys(Q[hY]).forEach((H)=>{Q[Y][H]=[...Q[hY][H]]})});if(X==="/*")X="*";let Z=(X.match(/\/:/g)||[]).length;if(/\*$/.test(X)){let Q=LK6(X);if(Y===hY)Object.keys(G).forEach((H)=>{G[H][X]||=QI(G[H],X)||QI(G[hY],X)||[]});else G[Y][X]||=QI(G[Y],X)||QI(G[hY],X)||[];Object.keys(G).forEach((H)=>{if(Y===hY||Y===H)Object.keys(G[H]).forEach(($)=>{Q.test($)&&G[H][$].push([J,Z])})}),Object.keys(W).forEach((H)=>{if(Y===hY||Y===H)Object.keys(W[H]).forEach(($)=>Q.test($)&&W[H][$].push([J,Z]))});return}let K=XY1(X)||[X];for(let Q=0,H=K.length;Q<H;Q++){let $=K[Q];Object.keys(W).forEach((F)=>{if(Y===hY||Y===F)W[F][$]||=[...QI(G[F],$)||QI(G[hY],$)||[]],W[F][$].push([J,Z-H+Q+1])})}}match=KY1;buildAllMatchers(){let Y=Object.create(null);return Object.keys(this.#X).concat(Object.keys(this.#Y)).forEach((X)=>{Y[X]||=this.#J(X)}),this.#Y=this.#X=void 0,yZ8(),Y}#J(Y){let X=[],J=Y===hY;if([this.#Y,this.#X].forEach((G)=>{let W=G[Y]?Object.keys(G[Y]).map((Z)=>[Z,G[Y][Z]]):[];if(W.length!==0)J||=!0,X.push(...W);else if(Y!==hY)X.push(...Object.keys(G[hY]).map((Z)=>[Z,G[hY][Z]]))}),!J)return null;else return bZ8(X)}};var dv1=y(()=>{SO();IO();mv1();lv1();DK6();fZ8=[/^$/,[],Object.create(null)],OK6=Object.create(null)});var hZ8=class{name="PreparedRegExpRouter";#Y;#X;constructor(Y,X){this.#Y=Y,this.#X=X}#J(Y,X){let J=this.#Y[Y];J[1].forEach((G)=>G&&G.push(X)),Object.values(J[2]).forEach((G)=>G[0].push(X))}#G(Y,X,J,G,W){let Z=this.#Y[Y];if(!W)Z[2][X][0].push([J,{}]);else G.forEach((K)=>{if(typeof K==="number")Z[1][K].push([J,W]);else Z[2][K||X][0].push([J,W])})}add(Y,X,J){if(!this.#Y[Y]){let W=this.#Y[hY],Z={};for(let K in W[2])Z[K]=[W[2][K][0].slice(),pu];this.#Y[Y]=[W[0],W[1].map((K)=>Array.isArray(K)?K.slice():0),Z]}if(X==="/*"||X==="*"){let W=[J,{}];if(Y===hY)for(let Z in this.#Y)this.#J(Z,W);else this.#J(Y,W);return}let G=this.#X[X];if(!G)throw Error(`Path ${X} is not registered`);for(let[W,Z]of G)if(Y===hY)for(let K in this.#Y)this.#G(K,X,J,W,Z);else this.#G(Y,X,J,W,Z)}buildAllMatchers(){return this.#Y}match=KY1};var NK6=y(()=>{SO();mv1();dv1()});var MK6=y(()=>{dv1();NK6()});var cv1=class{name="SmartRouter";#Y=[];#X=[];constructor(Y){this.#Y=Y.routers}add(Y,X,J){if(!this.#X)throw Error(ZY1);this.#X.push([Y,X,J])}match(Y,X){if(!this.#X)throw Error("Fatal error");let J=this.#Y,G=this.#X,W=J.length,Z=0,K;for(;Z<W;Z++){let Q=J[Z];try{for(let H=0,$=G.length;H<$;H++)Q.add(...G[H]);K=Q.match(Y,X)}catch(H){if(H instanceof QY1)continue;throw H}this.match=Q.match.bind(Q),this.#Y=[Q],this.#X=void 0;break}if(Z===W)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,K}get activeRouter(){if(this.#X||this.#Y.length!==1)throw Error("No active router has been determined yet.");return this.#Y[0]}};var wK6=y(()=>{SO()});var AK6=y(()=>{wK6()});var au,xZ8=(Y)=>{for(let X in Y)return!0;return!1},PK6=class Y{#Y;#X;#J;#G=0;#W=au;constructor(X,J,G){if(this.#X=G||Object.create(null),this.#Y=[],X&&J){let W=Object.create(null);W[X]={handler:J,possibleKeys:[],score:0},this.#Y=[W]}this.#J=[]}insert(X,J,G){this.#G=++this.#G;let W=this,Z=tQ6(J),K=[];for(let Q=0,H=Z.length;Q<H;Q++){let $=Z[Q],F=Z[Q+1],V=eQ6($,F),z=Array.isArray(V)?V[0]:$;if(z in W.#X){if(W=W.#X[z],V)K.push(V[1]);continue}if(W.#X[z]=new Y,V)W.#J.push(V),K.push(V[1]);W=W.#X[z]}return W.#Y.push({[X]:{handler:G,possibleKeys:K.filter((Q,H,$)=>$.indexOf(Q)===H),score:this.#G}}),W}#Z(X,J,G,W,Z){for(let K=0,Q=J.#Y.length;K<Q;K++){let H=J.#Y[K],$=H[G]||H[hY],F={};if($!==void 0){if($.params=Object.create(null),X.push($),W!==au||Z&&Z!==au)for(let V=0,z=$.possibleKeys.length;V<z;V++){let U=$.possibleKeys[V],B=F[$.score];$.params[U]=Z?.[U]&&!B?Z[U]:W[U]??Z?.[U],F[$.score]=!0}}}}search(X,J){let G=[];this.#W=au;let Z=[this],K=bv1(J),Q=[],H=K.length,$=null;for(let F=0;F<H;F++){let V=K[F],z=F===H-1,U=[];for(let D=0,L=Z.length;D<L;D++){let w=Z[D],N=w.#X[V];if(N)if(N.#W=w.#W,z){if(N.#X["*"])this.#Z(G,N.#X["*"],X,w.#W);this.#Z(G,N,X,w.#W)}else U.push(N);for(let R=0,P=w.#J.length;R<P;R++){let A=w.#J[R],E=w.#W===au?{}:{...w.#W};if(A==="*"){let h=w.#X["*"];if(h)this.#Z(G,h,X,w.#W),h.#W=E,U.push(h);continue}let[C,v,f]=A;if(!V&&!(f instanceof RegExp))continue;let b=w.#X[C];if(f instanceof RegExp){if($===null){$=Array(H);let c=J[0]==="/"?1:0;for(let m=0;m<H;m++)$[m]=c,c+=K[m].length+1}let h=J.substring($[F]),p=f.exec(h);if(p){if(E[v]=p[0],this.#Z(G,b,X,w.#W,E),xZ8(b.#X)){b.#W=E;let c=p[0].match(/\//)?.length??0;(Q[c]||=[]).push(b)}continue}}if(f===!0||f.test(V))if(E[v]=V,z){if(this.#Z(G,b,X,E,w.#W),b.#X["*"])this.#Z(G,b.#X["*"],X,E,w.#W)}else b.#W=E,U.push(b)}}let B=Q.shift();Z=B?U.concat(B):U}if(G.length>1)G.sort((F,V)=>{return F.score-V.score});return[G.map(({handler:F,params:V})=>[F,V])]}};var EK6=y(()=>{SO();IO();au=Object.create(null)});var pv1=class{name="TrieRouter";#Y;constructor(){this.#Y=new PK6}add(Y,X,J){let G=XY1(X);if(G){for(let W=0,Z=G.length;W<Z;W++)this.#Y.insert(Y,G[W],J);return}this.#Y.insert(Y,X,J)}match(Y,X){return this.#Y.search(Y,X)}};var RK6=y(()=>{IO();EK6()});var TK6=y(()=>{RK6()});var qX;var CK6=y(()=>{UK6();MK6();AK6();TK6();qX=class extends zK6{constructor(Y={}){super(Y);this.router=Y.router??new cv1({routers:[new $Y1,new pv1]})}}});var yQ=y(()=>{CK6()});var gZ8,uZ8,nv1=(Y,X)=>{if(X&&Y.indexOf(X)===-1)return{};let J=Y.trim().split(";"),G={};for(let W of J){W=W.trim();let Z=W.indexOf("=");if(Z===-1)continue;let K=W.substring(0,Z).trim();if(X&&X!==K||!gZ8.test(K))continue;let Q=W.substring(Z+1).trim();if(Q.startsWith('"')&&Q.endsWith('"'))Q=Q.slice(1,-1);if(uZ8.test(Q)){if(G[K]=Q.indexOf("%")!==-1?ZI(Q,lu):Q,X)break}}return G};var jK6=y(()=>{IO();gZ8=/^[\w!#$%&'*.^`|~+-]+$/,uZ8=/^[ !#-:<-[\]-~]*$/});var IK6=(Y,X,J)=>{let G=Y.req.raw.headers.get("Cookie");if(typeof X==="string"){if(!G)return;let Z=X;if(J==="secure")Z="__Secure-"+X;else if(J==="host")Z="__Host-"+X;return nv1(G,Z)[Z]}if(!G)return{};return nv1(G)};var SK6=y(()=>{jK6()});var _K6=(Y)=>{let J={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...Y},G=((Z)=>{if(typeof Z==="string")if(Z==="*")return()=>Z;else return(K)=>Z===K?K:null;else if(typeof Z==="function")return Z;else return(K)=>Z.includes(K)?K:null})(J.origin),W=((Z)=>{if(typeof Z==="function")return Z;else if(Array.isArray(Z))return()=>Z;else return()=>[]})(J.allowMethods);return async function(K,Q){function H(F,V){K.res.headers.set(F,V)}let $=await G(K.req.header("origin")||"",K);if($)H("Access-Control-Allow-Origin",$);if(J.credentials)H("Access-Control-Allow-Credentials","true");if(J.exposeHeaders?.length)H("Access-Control-Expose-Headers",J.exposeHeaders.join(","));if(K.req.method==="OPTIONS"){if(J.origin!=="*")H("Vary","Origin");if(J.maxAge!=null)H("Access-Control-Max-Age",J.maxAge.toString());let F=await W(K.req.header("origin")||"",K);if(F.length)H("Access-Control-Allow-Methods",F.join(","));let V=J.allowHeaders;if(!V?.length){let z=K.req.header("Access-Control-Request-Headers");if(z)V=z.split(/\s*,\s*/)}if(V?.length)H("Access-Control-Allow-Headers",V.join(",")),K.res.headers.append("Vary","Access-Control-Request-Headers");return K.res.headers.delete("Content-Length"),K.res.headers.delete("Content-Type"),new Response(null,{headers:K.res.headers,status:204,statusText:"No Content"})}if(await Q(),J.origin!=="*")K.header("Vary","Origin",{append:!0})}};var kK6=()=>{};function mZ8(){let{process:Y,Deno:X}=globalThis;return!(typeof X?.noColor==="boolean"?X.noColor:Y!==void 0?"NO_COLOR"in Y?.env:!1)}async function vK6(){let{navigator:Y}=globalThis,X="cloudflare:workers";return!(Y!==void 0&&Y.userAgent==="Cloudflare-Workers"?await(async()=>{try{return"NO_COLOR"in((await import("cloudflare:workers")).env??{})}catch{return!1}})():!mZ8())}var fK6=()=>{};async function yK6(Y,X,J,G,W=0,Z){let K=X==="<--"?`${X} ${J} ${G}`:`${X} ${J} ${G} ${await cZ8(W)} ${Z}`;Y(K)}var lZ8=(Y)=>{let[X,J]=[",","."];return Y.map((W)=>W.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+X)).join(J)},dZ8=(Y)=>{let X=Date.now()-Y;return lZ8([X<1000?X+"ms":Math.round(X/1000)+"s"])},cZ8=async(Y)=>{if(await vK6())switch(Y/100|0){case 5:return`\x1B[31m${Y}\x1B[0m`;case 4:return`\x1B[33m${Y}\x1B[0m`;case 3:return`\x1B[36m${Y}\x1B[0m`;case 2:return`\x1B[32m${Y}\x1B[0m`}return`${Y}`},bK6=(Y=console.log)=>{return async function(J,G){let{method:W,url:Z}=J.req,K=Z.slice(Z.indexOf("/",8));await yK6(Y,"<--",W,K);let Q=Date.now();await G(),await yK6(Y,"-->",W,K,J.res.status,dZ8(Q))}};var hK6=y(()=>{fK6()});var xK6=()=>{try{return performance.now()}catch{}return Date.now()},iv1=(Y)=>{let X={total:!0,enabled:!0,totalDescription:"Total Response Time",autoEnd:!0,crossOrigin:!1,...Y};return async function(G,W){let Z=[],K=new Map;if(G.get("metric"))return await W();if(G.set("metric",{headers:Z,timers:K}),X.total)KI(G,"total",X.totalDescription);if(await W(),X.total)AA(G,"total");if(X.autoEnd)K.forEach((H,$)=>AA(G,$));if(typeof X.enabled==="function"?X.enabled(G):X.enabled){G.res.headers.append("Server-Timing",Z.join(","));let H=typeof X.crossOrigin==="function"?X.crossOrigin(G):X.crossOrigin;if(H)G.res.headers.append("Timing-Allow-Origin",typeof H==="string"?H:"*")}}},gK6=(Y,X,J,G,W)=>{let Z=Y.get("metric");if(!Z){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}if(typeof J==="number"){let K=J.toFixed(W||1),Q=G?`${X};dur=${K};desc="${G}"`:`${X};dur=${K}`;Z.headers.push(Q)}else{let K=J?`${X};desc="${J}"`:`${X}`;Z.headers.push(K)}},KI=(Y,X,J)=>{let G=Y.get("metric");if(!G){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}G.timers.set(X,{description:J,start:xK6()})},AA=(Y,X,J)=>{let G=Y.get("metric");if(!G){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}let W=G.timers.get(X);if(!W){console.warn(`Timer "${X}" does not exist!`);return}let{description:Z,start:K}=W,Q=xK6()-K;gK6(Y,X,Q,Z,J),G.timers.delete(X)};var uK6=y(()=>{WY1()});var mK6=y(()=>{uK6()});class av1{db;constructor(Y){this.db=Y}async create(Y,X,J){let G=e9("vir"),W=new Date().toISOString();if(await this.db.insertInto("connections").values({id:G,organization_id:Y,created_by:X,title:J.title,description:J.description??null,icon:J.icon??null,app_name:null,app_id:null,connection_type:"VIRTUAL",connection_url:`virtual://${G}`,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:J.metadata?JSON.stringify(J.metadata):null,tools:null,bindings:null,status:J.status??"active",created_at:W,updated_at:W}).execute(),J.connections.length>0)await this.db.insertInto("connection_aggregations").values(J.connections.map((K)=>({id:e9("agg"),parent_connection_id:G,child_connection_id:K.connection_id,selected_tools:K.selected_tools?JSON.stringify(K.selected_tools):null,selected_resources:K.selected_resources?JSON.stringify(K.selected_resources):null,selected_prompts:K.selected_prompts?JSON.stringify(K.selected_prompts):null,dependency_mode:"direct",created_at:W}))).execute();let Z=await this.findById(G);if(!Z)throw Error(`Failed to create virtual MCP with id: ${G}`);return Z}async findById(Y,X){let J=Gz(Y);if(J){let G=X??J,W=await this.db.selectFrom("connections").selectAll().where("organization_id","=",G).where("status","!=","inactive").where("status","!=","error").execute();return{...Ua(G),connections:W.map((Z)=>({connection_id:Z.id,selected_tools:null,selected_resources:null,selected_prompts:null}))}}return this.findByIdInternal(this.db,Y)}async findByIdInternal(Y,X){let J=await Y.selectFrom("connections").selectAll().where("id","=",X).where("connection_type","=","VIRTUAL").executeTakeFirst();if(!J)return null;let G=await Y.selectFrom("connection_aggregations").selectAll().where("parent_connection_id","=",X).where("dependency_mode","=","direct").execute();return this.deserializeVirtualMCPEntity(J,G)}async list(Y){let X=await this.db.selectFrom("connections").selectAll().where("organization_id","=",Y).where("connection_type","=","VIRTUAL").execute(),J=X.map((Z)=>Z.id);if(J.length===0)return[];let G=await this.db.selectFrom("connection_aggregations").selectAll().where("parent_connection_id","in",J).where("dependency_mode","=","direct").execute(),W=new Map;for(let Z of G){let K=W.get(Z.parent_connection_id)??[];K.push(Z),W.set(Z.parent_connection_id,K)}return X.map((Z)=>this.deserializeVirtualMCPEntity(Z,W.get(Z.id)??[]))}async listByConnectionId(Y,X){let G=(await this.db.selectFrom("connection_aggregations").select("parent_connection_id").where("child_connection_id","=",X).execute()).map((H)=>H.parent_connection_id);if(G.length===0)return[];let W=await this.db.selectFrom("connections").selectAll().where("id","in",G).where("organization_id","=",Y).where("connection_type","=","VIRTUAL").execute();if(W.length===0)return[];let Z=W.map((H)=>H.id),K=await this.db.selectFrom("connection_aggregations").selectAll().where("parent_connection_id","in",Z).where("dependency_mode","=","direct").execute(),Q=new Map;for(let H of K){let $=Q.get(H.parent_connection_id)??[];$.push(H),Q.set(H.parent_connection_id,$)}return W.map((H)=>this.deserializeVirtualMCPEntity(H,Q.get(H.id)??[]))}async update(Y,X,J){let G=new Date().toISOString(),W={updated_at:G,updated_by:X};if(J.title!==void 0)W.title=J.title;if(J.description!==void 0)W.description=J.description;if(J.icon!==void 0)W.icon=J.icon;if(J.status!==void 0)W.status=J.status;if(J.metadata!==void 0)W.metadata=J.metadata?JSON.stringify(J.metadata):null;if(await this.db.updateTable("connections").set(W).where("id","=",Y).where("connection_type","=","VIRTUAL").execute(),J.connections!==void 0){if(await this.db.deleteFrom("connection_aggregations").where("parent_connection_id","=",Y).where("dependency_mode","=","direct").execute(),J.connections.length>0)await this.db.insertInto("connection_aggregations").values(J.connections.map((K)=>({id:e9("agg"),parent_connection_id:Y,child_connection_id:K.connection_id,selected_tools:K.selected_tools?JSON.stringify(K.selected_tools):null,selected_resources:K.selected_resources?JSON.stringify(K.selected_resources):null,selected_prompts:K.selected_prompts?JSON.stringify(K.selected_prompts):null,dependency_mode:"direct",created_at:G}))).execute()}let Z=await this.findById(Y);if(!Z)throw Error("Virtual MCP not found after update");return Z}async delete(Y){await this.db.deleteFrom("connection_aggregations").where("parent_connection_id","=",Y).execute(),await this.db.deleteFrom("connections").where("id","=",Y).where("connection_type","=","VIRTUAL").execute()}async removeConnectionReferences(Y){await this.db.deleteFrom("connection_aggregations").where("child_connection_id","=",Y).execute()}deserializeVirtualMCPEntity(Y,X){let J=Y.created_at instanceof Date?Y.created_at.toISOString():Y.created_at,G=Y.updated_at instanceof Date?Y.updated_at.toISOString():Y.updated_at,W=Y.status==="active"?"active":"inactive",Z=this.parseJson(Y.metadata);return{id:Y.id,organization_id:Y.organization_id,title:Y.title,description:Y.description,icon:Y.icon,status:W,created_at:J,updated_at:G,created_by:Y.created_by,updated_by:Y.updated_by??void 0,metadata:{...Z,instructions:Z?.instructions??null},connections:X.map((K)=>({connection_id:K.child_connection_id,selected_tools:this.parseJson(K.selected_tools),selected_resources:this.parseJson(K.selected_resources),selected_prompts:this.parseJson(K.selected_prompts)}))}}parseJson(Y){if(Y===null)return null;if(typeof Y==="string")try{return JSON.parse(Y)}catch{return null}return Y}async listVirtualTools(Y){let X=await this.db.selectFrom("connections").select(["tools","created_at","updated_at"]).where("id","=",Y).where("connection_type","=","VIRTUAL").executeTakeFirst();if(!X)return[];let J=this.parseJson(X.tools);if(!J)return[];let G=X.created_at instanceof Date?X.created_at.toISOString():X.created_at,W=X.updated_at instanceof Date?X.updated_at.toISOString():X.updated_at;return J.map((Z,K)=>({tool:Z,originalIndex:K})).filter(({tool:Z})=>PO(Z)).map(({tool:Z,originalIndex:K})=>fu(`${Y}:${Z.name}:${K}`,Z,G,W))}async getVirtualTool(Y,X){let J=await this.db.selectFrom("connections").select(["tools","created_at","updated_at"]).where("id","=",Y).where("connection_type","=","VIRTUAL").executeTakeFirst();if(!J)return null;let G=this.parseJson(J.tools);if(!G)return null;let W=G.findIndex((H)=>H.name===X&&PO(H));if(W===-1)return null;let Z=G[W],K=J.created_at instanceof Date?J.created_at.toISOString():J.created_at,Q=J.updated_at instanceof Date?J.updated_at.toISOString():J.updated_at;return fu(`${Y}:${Z.name}:${W}`,Z,K,Q)}async createVirtualTool(Y,X,J){let G=new Date().toISOString(),W=await this.db.selectFrom("connections").select(["tools"]).where("id","=",Y).where("connection_type","=","VIRTUAL").executeTakeFirst();if(!W)throw Error(`Virtual MCP not found: ${Y}`);let Z=this.parseJson(W.tools)??[];if(Z.some((Q)=>Q.name===X.name))throw Error(`Tool with name "${X.name}" already exists`);let K={name:X.name,description:X.description,inputSchema:X.inputSchema,outputSchema:X.outputSchema,annotations:X.annotations,_meta:{"mcp.mesh":{"tool.fn":X.code},connectionDependencies:J}};return Z.push(K),await this.db.updateTable("connections").set({tools:JSON.stringify(Z),updated_at:G}).where("id","=",Y).execute(),await this.syncIndirectDependencies(Y,J),fu(`${Y}:${X.name}:${Z.length-1}`,K,G,G)}async updateVirtualTool(Y,X,J,G){let W=new Date().toISOString(),Z=await this.db.selectFrom("connections").select(["tools","created_at"]).where("id","=",Y).where("connection_type","=","VIRTUAL").executeTakeFirst();if(!Z)throw Error(`Virtual MCP not found: ${Y}`);let K=this.parseJson(Z.tools)??[],Q=K.findIndex((z)=>z.name===X&&PO(z));if(Q===-1)throw Error(`Virtual tool not found: ${X}`);let H=K[Q];if(J.name&&J.name!==X){if(K.some((z)=>z.name===J.name))throw Error(`Tool with name "${J.name}" already exists`)}let $=G??H._meta.connectionDependencies??[],F={name:J.name??H.name,description:J.description!==void 0?J.description??void 0:H.description,inputSchema:J.inputSchema??H.inputSchema,outputSchema:J.outputSchema!==void 0?J.outputSchema??void 0:H.outputSchema,annotations:J.annotations!==void 0?J.annotations??void 0:H.annotations,_meta:{"mcp.mesh":{"tool.fn":J.code??H._meta["mcp.mesh"]["tool.fn"]},connectionDependencies:$}};if(K[Q]=F,await this.db.updateTable("connections").set({tools:JSON.stringify(K),updated_at:W}).where("id","=",Y).execute(),G!==void 0)await this.recalculateIndirectDependencies(Y,K);let V=Z.created_at instanceof Date?Z.created_at.toISOString():Z.created_at;return fu(`${Y}:${F.name}:${Q}`,F,V,W)}async deleteVirtualTool(Y,X){let J=new Date().toISOString(),G=await this.db.selectFrom("connections").select(["tools"]).where("id","=",Y).where("connection_type","=","VIRTUAL").executeTakeFirst();if(!G)throw Error(`Virtual MCP not found: ${Y}`);let W=this.parseJson(G.tools)??[],Z=W.findIndex((K)=>K.name===X&&PO(K));if(Z===-1)throw Error(`Virtual tool not found: ${X}`);W.splice(Z,1),await this.db.updateTable("connections").set({tools:W.length>0?JSON.stringify(W):null,updated_at:J}).where("id","=",Y).execute(),await this.recalculateIndirectDependencies(Y,W)}async syncIndirectDependencies(Y,X){if(X.length===0)return;let J=new Date().toISOString(),G=await this.db.selectFrom("connection_aggregations").select(["child_connection_id","dependency_mode"]).where("parent_connection_id","=",Y).execute(),W=new Set(G.map((K)=>K.child_connection_id)),Z=X.filter((K)=>!W.has(K));if(Z.length>0)await this.db.insertInto("connection_aggregations").values(Z.map((K)=>({id:e9("agg"),parent_connection_id:Y,child_connection_id:K,selected_tools:null,selected_resources:null,selected_prompts:null,dependency_mode:"indirect",created_at:J}))).execute()}async recalculateIndirectDependencies(Y,X){let J=new Set;for(let Q of X)if(PO(Q)){let H=Q._meta.connectionDependencies??[];for(let $ of H)J.add($)}let G=await this.db.selectFrom("connection_aggregations").select(["id","child_connection_id","dependency_mode"]).where("parent_connection_id","=",Y).execute(),W=G.filter((Q)=>Q.dependency_mode==="indirect"&&!J.has(Q.child_connection_id)).map((Q)=>Q.id);if(W.length>0)await this.db.deleteFrom("connection_aggregations").where("id","in",W).execute();let Z=new Set(G.map((Q)=>Q.child_connection_id)),K=Array.from(J).filter((Q)=>!Z.has(Q));if(K.length>0){let Q=new Date().toISOString();await this.db.insertInto("connection_aggregations").values(K.map((H)=>({id:e9("agg"),parent_connection_id:Y,child_connection_id:H,selected_tools:null,selected_resources:null,selected_prompts:null,dependency_mode:"indirect",created_at:Q}))).execute()}}}var lK6=y(()=>{fQ();cY();eU()});function JJ(Y){return Y.replace(/\0/g,"").replace(/\\/g,"\\\\").replace(/'/g,"''")}function nZ8(Y){if(!pZ8.has(Y))throw Error(`Invalid groupByColumn: ${Y}`);return Y}function rv1(Y){if(!iZ8.test(Y))throw Error(`Invalid JSONPath: ${Y}`);if(Y.startsWith("$."))return Y;if(Y.startsWith("."))return`$${Y}`;return`$.${Y}`}function ov1(Y){return Y.replace(/^\$\./,"").split(".").map((J)=>`'${JJ(J)}'`).join(", ")}function oZ8(Y){let X=aZ8.exec(Y);if(!X||!X[1]||!X[2])throw Error(`Invalid interval: ${Y}`);let J=parseInt(X[1],10),G=X[2],W=rZ8[G];if(J<1||J>W)throw Error(`Invalid interval amount: ${J}${G} (max ${W}${G})`);return{amount:J,unit:G}}function sZ8(Y){let{amount:X,unit:J}=oZ8(Y),W={m:"MINUTE",h:"HOUR",d:"DAY"}[J];return`toStartOfInterval(parseDateTime64BestEffort(toString(timestamp)), INTERVAL ${X} ${W})`}function sv1(Y){if(Y===null||Y===void 0)return{};if(typeof Y==="object")return Y;try{return JSON.parse(String(Y))}catch{return{}}}function tZ8(Y){return{id:String(Y.id??""),organizationId:String(Y.organization_id??""),connectionId:String(Y.connection_id??""),connectionTitle:String(Y.connection_title??""),toolName:String(Y.tool_name??""),input:sv1(Y.input),output:sv1(Y.output),isError:Y.is_error===1||Y.is_error===!0||Y.is_error==="1",errorMessage:Y.error_message!=null?String(Y.error_message):null,durationMs:Number(Y.duration_ms??0),timestamp:(()=>{if(Y.timestamp instanceof Date)return Y.timestamp.toISOString();let X=String(Y.timestamp??""),J=new Date(X.includes("T")?X:X.replace(" ","T")+"Z");return Number.isNaN(J.getTime())?X:J.toISOString()})(),userId:Y.user_id!=null?String(Y.user_id):null,requestId:String(Y.request_id??""),userAgent:Y.user_agent!=null?String(Y.user_agent):null,virtualMcpId:Y.virtual_mcp_id!=null?String(Y.virtual_mcp_id):null,properties:Y.properties?sv1(Y.properties):null}}function cK6(Y){let X=[];if(Y.properties)for(let[J,G]of Object.entries(Y.properties)){let W=JJ(J),Z=JJ(G);X.push(`JSONExtractString(properties, '${W}') = '${Z}'`)}if(Y.propertyKeys)for(let J of Y.propertyKeys){let G=JJ(J);X.push(`JSONExtractString(properties, '${G}') IS NOT NULL AND JSONExtractString(properties, '${G}') != ''`)}if(Y.propertyPatterns)for(let[J,G]of Object.entries(Y.propertyPatterns)){let W=JJ(J),Z=JJ(G);X.push(`JSONExtractString(properties, '${W}') ILIKE '${Z}'`)}if(Y.propertyInValues)for(let[J,G]of Object.entries(Y.propertyInValues)){let W=JJ(J),Z=JJ(G);X.push(`has(splitByChar(',', JSONExtractString(properties, '${W}')), '${Z}')`)}return X}function dK6(Y){if(!Y)return[];let X=[];if(Y.connectionIds?.length){let J=Y.connectionIds.map((G)=>`'${JJ(G)}'`).join(",");X.push(`connection_id IN (${J})`)}if(Y.toolNames?.length){let J=Y.toolNames.map((G)=>`'${JJ(G)}'`).join(",");X.push(`tool_name IN (${J})`)}if(Y.virtualMcpIds?.length){let J=Y.virtualMcpIds.map((G)=>`'${JJ(G)}'`).join(",");X.push(`virtual_mcp_id IN (${J})`)}if(Y.startDate)X.push(tv1(Y.startDate));if(Y.endDate)X.push(ev1(Y.endDate));if(Y.propertyFilters)X.push(...cK6(Y.propertyFilters));return X}function tv1(Y){return`parseDateTime64BestEffort(toString(timestamp)) >= parseDateTime64BestEffort('${Y.toISOString()}')`}function ev1(Y){return`parseDateTime64BestEffort(toString(timestamp)) <= parseDateTime64BestEffort('${Y.toISOString()}')`}class Yf1{engine;source;constructor(Y,X){this.engine=Y;this.source=X}async query(Y){if(!Y.organizationId)throw Error("organizationId is required");let X=[`organization_id = '${JJ(Y.organizationId)}'`];if(Y.connectionId)X.push(`connection_id = '${JJ(Y.connectionId)}'`);if(Y.excludeConnectionIds?.length){let $=Y.excludeConnectionIds.map((F)=>`'${JJ(F)}'`).join(",");X.push(`connection_id NOT IN (${$})`)}if(Y.virtualMcpId)X.push(`virtual_mcp_id = '${JJ(Y.virtualMcpId)}'`);if(Y.toolName)X.push(`tool_name = '${JJ(Y.toolName)}'`);if(Y.isError!==void 0)X.push(`is_error = ${Y.isError?1:0}`);if(Y.startDate)X.push(tv1(Y.startDate));if(Y.endDate)X.push(ev1(Y.endDate));if(Y.propertyFilters)X.push(...cK6(Y.propertyFilters));let J=1000,G=Math.min(Math.max(1,Math.floor(Y.limit??50)),J),W=Math.max(0,Math.floor(Y.offset??0)),Z=`SELECT *, count(*) OVER () AS _total FROM ${this.source} WHERE ${X.join(" AND ")} ORDER BY timestamp DESC LIMIT ${G} OFFSET ${W}`,K=await this.engine.query(Z);if(K.length===0)return{logs:[],total:0};let Q=Number(K[0]._total??0);return{logs:K.map(tZ8),total:Q}}async getStats(Y){if(!Y.organizationId)throw Error("organizationId is required");let X=[`organization_id = '${JJ(Y.organizationId)}'`];if(Y.startDate)X.push(tv1(Y.startDate));if(Y.endDate)X.push(ev1(Y.endDate));let J=`SELECT count(*) AS total_calls, coalesce(sum(CASE WHEN is_error = 1 THEN 1.0 ELSE 0.0 END) / NULLIF(count(*), 0), 0) AS error_rate, coalesce(avg(duration_ms), 0) AS avg_duration_ms FROM ${this.source} WHERE ${X.join(" AND ")}`,W=(await this.engine.query(J))[0]??{};return{totalCalls:Number(W.total_calls??0),errorRate:Number(W.error_rate??0),avgDurationMs:Number(W.avg_duration_ms??0)}}async aggregate(Y){if(!Y.organizationId)throw Error("organizationId is required");let X=rv1(Y.path),J=Y.from==="input"?"input":"output",G=ov1(X),W=Y.aggregation==="count"||Y.aggregation==="count_all"?"1":`JSONExtractFloat(${J}, ${G})`,Z=eZ8(Y.aggregation,W),K=[`organization_id = '${JJ(Y.organizationId)}'`];if(Y.aggregation==="count")K.push(`JSONExtractString(${J}, ${G}) IS NOT NULL`),K.push(`JSONExtractString(${J}, ${G}) != ''`);if(Y.aggregation!=="count"&&Y.aggregation!=="count_all")K.push(`JSONExtractString(${J}, ${G}) IS NOT NULL`),K.push(`JSONExtractString(${J}, ${G}) != ''`);K.push(...dK6(Y.filters));let Q=K.join(" AND "),H=Math.min(Math.max(1,Math.floor(Y.limit??1e4)),1e4);if(Y.groupByColumn){let V=nZ8(Y.groupByColumn),z=`SELECT ${V} AS group_key, ${Z} AS value FROM ${this.source} WHERE ${Q} GROUP BY ${V} ORDER BY value DESC LIMIT ${H}`;return{value:null,groups:(await this.engine.query(z)).map((B)=>({key:String(B.group_key??""),value:Number(B.value??0)}))}}if(Y.groupBy){let V=rv1(Y.groupBy),z=Y.from==="input"?"input":"output",U=ov1(V),B=`JSONExtractString(${z}, ${U})`,D=`SELECT ${B} AS group_key, ${Z} AS value FROM ${this.source} WHERE ${Q} AND ${B} != '' GROUP BY ${B} ORDER BY value DESC LIMIT ${H}`;return{value:null,groups:(await this.engine.query(D)).map((w)=>({key:String(w.group_key??""),value:Number(w.value??0)}))}}if(Y.interval){let z=`SELECT ${sZ8(Y.interval)} AS bucket, ${Z} AS value FROM ${this.source} WHERE ${Q} GROUP BY bucket ORDER BY bucket ASC LIMIT ${H}`;return{value:null,timeseries:(await this.engine.query(z)).map((B)=>({timestamp:String(B.bucket??""),value:Number(B.value??0)}))}}let $=`SELECT ${Z} AS value FROM ${this.source} WHERE ${Q}`,F=await this.engine.query($);return{value:Number(F[0]?.value??0)}}async countMatched(Y){if(!Y.organizationId)throw Error("organizationId is required");let X=rv1(Y.path),J=Y.from==="input"?"input":"output",G=ov1(X),W=[`organization_id = '${JJ(Y.organizationId)}'`,`JSONExtractString(${J}, ${G}) IS NOT NULL`,`JSONExtractString(${J}, ${G}) != ''`];W.push(...dK6(Y.filters));let Z=`SELECT count(*) AS cnt FROM ${this.source} WHERE ${W.join(" AND ")}`,K=await this.engine.query(Z);return Number(K[0]?.cnt??0)}}function eZ8(Y,X){switch(Y){case"sum":return`coalesce(sum(${X}), 0)`;case"avg":return`coalesce(avg(${X}), 0)`;case"min":return`min(${X})`;case"max":return`max(${X})`;case"count":return"count(*)";case"count_all":return"count(*)";case"last":return`argMax(${X}, timestamp)`;default:throw Error(`Unknown aggregation function: ${Y}`)}}var pZ8,iZ8,aZ8,rZ8;var pK6=y(()=>{pZ8=new Set(["connection_id","connection_title","user_id","tool_name","virtual_mcp_id"]);iZ8=/^(\$\.)?[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*$/;aZ8=/^(\d+)([mhd])$/,rZ8={m:525960,h:8760,d:365}});var aK6=n((ASY,iK6)=>{var __dirname="/home/runner/work/studio/studio/node_modules/.bun/chdb@1.6.0/node_modules/chdb",YQ8=V0("path"),ru=V0(YQ8.join(__dirname,"build","Release","chdb_node.node")),{mkdtempSync:XQ8,rmSync:JQ8}=V0("fs"),{join:GQ8}=V0("path"),WQ8=V0("os");function ZQ8(Y,X="CSV"){if(!Y)return"";return ru.Query(Y,X)}function QQ8(Y,X={},J="CSV"){if(!Y)return"";return ru.QueryBindSession(Y,X,J)}class nK6{constructor(Y=""){if(Y==="")this.path=XQ8(GQ8(WQ8.tmpdir(),"tmp-chdb-node")),this.isTemp=!0;else this.path=Y,this.isTemp=!1;if(this.connection=ru.CreateConnection(this.path),!this.connection)throw Error("Failed to create connection")}query(Y,X="CSV"){if(!Y)return"";if(!this.connection)throw Error("No active connection available");return ru.QueryWithConnection(this.connection,Y,X)}queryBind(Y,X={},J="CSV"){throw Error("QueryBind is not supported with connection-based sessions. Please use the standalone queryBind function instead.")}cleanup(){if(this.connection)ru.CloseConnection(this.connection),this.connection=null;if(this.isTemp)JQ8(this.path,{recursive:!0})}}iK6.exports={query:ZQ8,queryBind:QQ8,Session:nK6}});var FY1=n((sK6)=>{Object.defineProperty(sK6,"__esModule",{value:!0});sK6.ClickHouseLogLevel=sK6.LogWriter=sK6.DefaultLogger=void 0;class rK6{trace({module:Y,message:X,args:J}){let G=[ou({module:Y,message:X,level:"TRACE"})];if(J)G.push(`
|
|
1994
1994
|
Arguments:`,J);console.debug(...G)}debug({module:Y,message:X,args:J}){let G=[ou({module:Y,message:X,level:"DEBUG"})];if(J)G.push(`
|
|
1995
1995
|
Arguments:`,J);console.debug(...G)}info({module:Y,message:X,args:J}){let G=[ou({module:Y,message:X,level:"INFO"})];if(J)G.push(`
|
|
1996
1996
|
Arguments:`,J);console.info(...G)}warn({module:Y,message:X,args:J,err:G}){let W=[ou({module:Y,message:X,level:"WARN"})];if(J)W.push(`
|