@decocms/mesh 2.125.3 → 2.127.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/assets/{AlertCircle-CAn1onHH.js → AlertCircle-DJ052zqS.js} +1 -1
- package/dist/client/assets/{AlertOctagon-ChcnKW7P.js → AlertOctagon-DCNCOxEl.js} +1 -1
- package/dist/client/assets/{AlertTriangle-Suhq71Ba.js → AlertTriangle-MQM19F_y.js} +1 -1
- package/dist/client/assets/{ArrowDown-BQn3fvf7.js → ArrowDown-Bn9Nw2BD.js} +1 -1
- package/dist/client/assets/{ArrowLeft-DkojAdWe.js → ArrowLeft-BSPqreiE.js} +1 -1
- package/dist/client/assets/{ArrowUp-CCTJ8tar.js → ArrowUp-BLFAP4Oh.js} +1 -1
- package/dist/client/assets/{Check-2BTd1528.js → Check-BXz-Aa3Y.js} +1 -1
- package/dist/client/assets/{CheckCircle-DUsP9qJl.js → CheckCircle-DmsV77x1.js} +1 -1
- package/dist/client/assets/{CheckDone01-Bs5yfbwu.js → CheckDone01-CQuFbmYi.js} +1 -1
- package/dist/client/assets/{CheckVerified02-D9LvEg4-.js → CheckVerified02-C2uVr9FW.js} +1 -1
- package/dist/client/assets/{ChevronDown-BK0Z-3ss.js → ChevronDown-CEb48ZDu.js} +1 -1
- package/dist/client/assets/{ChevronRight-CpFHeZ-k.js → ChevronRight-CQS5xbc3.js} +1 -1
- package/dist/client/assets/{Clock-DWLl74MU.js → Clock-X1ZnQ0e8.js} +1 -1
- package/dist/client/assets/{Code01-D7rt1C5k.js → Code01-CVF-mmmz.js} +1 -1
- package/dist/client/assets/{Container-Dkua_wx6.js → Container-D3N8SS-J.js} +1 -1
- package/dist/client/assets/{Copy01-CWD2XYkN.js → Copy01-CFXdI8SF.js} +1 -1
- package/dist/client/assets/{Dataflow03-dIUcYa_e.js → Dataflow03-BvFbR-2p.js} +1 -1
- package/dist/client/assets/{DotsHorizontal-R03fSXLm.js → DotsHorizontal-BlKZUIAr.js} +1 -1
- package/dist/client/assets/{DotsVertical-nJGFqnIJ.js → DotsVertical-CJJQe-sw.js} +1 -1
- package/dist/client/assets/{Download01-w53nljTi.js → Download01-BuGXWPUb.js} +1 -1
- package/dist/client/assets/{Edit01-Een9NeGa.js → Edit01-vxAH-tv6.js} +1 -1
- package/dist/client/assets/{Eye-cRMKwlob.js → Eye-Cqy0OQfO.js} +1 -1
- package/dist/client/assets/{File02-BiHbI-Bs.js → File02-CYWnFy5E.js} +1 -1
- package/dist/client/assets/{File06-DK6hozGp.js → File06-p-mGMfLu.js} +1 -1
- package/dist/client/assets/{FilterLines-DcFfiBYv.js → FilterLines-B-D6srZC.js} +1 -1
- package/dist/client/assets/{Globe01-zBSU4RrG.js → Globe01-Di6WS1d0.js} +1 -1
- package/dist/client/assets/{Globe02-BzI-D3XF.js → Globe02-CL5aTFno.js} +1 -1
- package/dist/client/assets/{Grid01-DtWTP079.js → Grid01-BGPoEeik.js} +1 -1
- package/dist/client/assets/{Hash02-B_cIkiva.js → Hash02-BWg3CKrn.js} +1 -1
- package/dist/client/assets/{Home02-B0J9-6Fj.js → Home02-Atzompjz.js} +1 -1
- package/dist/client/assets/{Image01-DuLPJrbP.js → Image01-B-9nWGvT.js} +1 -1
- package/dist/client/assets/{Inbox01-DkeOZ2C_.js → Inbox01-CWbCHIve.js} +1 -1
- package/dist/client/assets/{InfoCircle-v_Zi3ix-.js → InfoCircle-BxNpDB4f.js} +1 -1
- package/dist/client/assets/{Key01-FdWHEw6c.js → Key01-BBHw8-AF.js} +1 -1
- package/dist/client/assets/{LinkExternal01-BvWelMzx.js → LinkExternal01-BH7m2QmL.js} +1 -1
- package/dist/client/assets/{List-D1SXIq-Q.js → List-DZq_3WJK.js} +1 -1
- package/dist/client/assets/{Loading01-BntQXW3R.js → Loading01-Bm0RmGTq.js} +1 -1
- package/dist/client/assets/{Lock01-Ca25inpJ.js → Lock01-BY0MGONc.js} +1 -1
- package/dist/client/assets/{Pin01-D5SNXGno.js → Pin01-BQxfi8aj.js} +1 -1
- package/dist/client/assets/{Play-Dv6XoPC1.js → Play-CGUn4LDu.js} +1 -1
- package/dist/client/assets/{Plus-BpJ1F9ED.js → Plus-CfD4U7h2.js} +1 -1
- package/dist/client/assets/{RefreshCcw01-C6HpBrM2.js → RefreshCcw01-ClQUpEVA.js} +1 -1
- package/dist/client/assets/{RefreshCw01-BLvlqjIJ.js → RefreshCw01-DsYl6Nso.js} +1 -1
- package/dist/client/assets/{Rows03-Bw2KmPLF.js → Rows03-BmDCzA2B.js} +1 -1
- package/dist/client/assets/{Save01-C7Op6P3G.js → Save01-CVm8Nhi5.js} +1 -1
- package/dist/client/assets/{SearchMd-B22BWSrE.js → SearchMd-rBeGYVN8.js} +1 -1
- package/dist/client/assets/{Settings01-39eYdV1s.js → Settings01-BCU61Dg3.js} +1 -1
- package/dist/client/assets/{Shield01-D5vtlDrS.js → Shield01-D73wrcGm.js} +1 -1
- package/dist/client/assets/{Terminal-jwgZ8meH.js → Terminal-B7IR3GOF.js} +1 -1
- package/dist/client/assets/Tool01-D4p-h1gd.js +1 -0
- package/dist/client/assets/{Trash01-NHvYJiOw.js → Trash01-CNjhe6V_.js} +1 -1
- package/dist/client/assets/{Upload01-B7z0chWz.js → Upload01-KtFgXqwG.js} +1 -1
- package/dist/client/assets/{Users03-CfBv5uVc.js → Users03-DNxW_fja.js} +1 -1
- package/dist/client/assets/{X-nbY3n5YX.js → X-OID4YrAs.js} +1 -1
- package/dist/client/assets/{XCircle-CdrNrzcr.js → XCircle-LfPUm5IL.js} +1 -1
- package/dist/client/assets/{XClose-DHV8bqGR.js → XClose-CVjVP425.js} +1 -1
- package/dist/client/assets/{agent-connections-preview-D2nPeCg-.js → agent-connections-preview-BPhKy-Id.js} +1 -1
- package/dist/client/assets/agent-detail-HyuxH4Ve.js +2 -0
- package/dist/client/assets/agents-Bc9eRkDe.js +1 -0
- package/dist/client/assets/{alert-dialog-DIblcPQC.js → alert-dialog-9GjsXnzK.js} +1 -1
- package/dist/client/assets/{auth-catchall-lueUuNUs.js → auth-catchall-Bsy9nmf9.js} +1 -1
- package/dist/client/assets/{avatar-DAde4Coq.js → avatar-D7LZZNPu.js} +1 -1
- package/dist/client/assets/{badge-EvnzqGBM.js → badge-CQ9R9pkG.js} +1 -1
- package/dist/client/assets/{binder-DtqSnmtn.js → binder-BRFblyKj.js} +1 -1
- package/dist/client/assets/{breadcrumb-Dit0z7A7.js → breadcrumb-_jAneXHm.js} +1 -1
- package/dist/client/assets/{button-DDY6hri1.js → button-BjJbLzI1.js} +1 -1
- package/dist/client/assets/{card-CHcjH7V4.js → card-BiNPXwY7.js} +1 -1
- package/dist/client/assets/{chart-BEZIHLHA.js → chart-Cye540qd.js} +5 -5
- package/dist/client/assets/{checkbox-_pZquTsv.js → checkbox-ClNyXMEe.js} +1 -1
- package/dist/client/assets/{circle-alert-8my-DdYx.js → circle-alert-BwBTOPt2.js} +1 -1
- package/dist/client/assets/collection-detail-CgUzsg7m.js +26 -0
- package/dist/client/assets/collection-search-D9lLlfmK.js +1 -0
- package/dist/client/assets/collection-tab-CK-Q89lj.js +1 -0
- package/dist/client/assets/collection-table-wrapper-HJznMrYU.js +1 -0
- package/dist/client/assets/{collection-tabs-CMMj9apF.js → collection-tabs-D0BDRIQH.js} +1 -1
- package/dist/client/assets/{command-D0lPyqX9.js → command-CmCm6EpS.js} +1 -1
- package/dist/client/assets/{connect-jPJQySxH.js → connect-D_vBcyxr.js} +1 -1
- package/dist/client/assets/{connection-card-C36z_Zfo.js → connection-card-O78FPkKW.js} +1 -1
- package/dist/client/assets/connection-detail-CqECx5w9.js +1 -0
- package/dist/client/assets/connections-DcBskx9Y.js +1 -0
- package/dist/client/assets/{constants-BWuwqVaf.js → constants-Bz_J8k2h.js} +1 -1
- package/dist/client/assets/constants-CQfW12Qo.js +1 -0
- package/dist/client/assets/{context-BoqYBHof.js → context-DPw3JrfP.js} +1 -1
- package/dist/client/assets/{create-organization-dialog-DZ-29KA3.js → create-organization-dialog-ChDwEIL0.js} +1 -1
- package/dist/client/assets/{create-project-dialog-5JWgj7o1.js → create-project-dialog-D_pqfYAD.js} +1 -1
- package/dist/client/assets/{deco-constants-Lndb0_Fi.js → deco-constants-CGrimklY.js} +1 -1
- package/dist/client/assets/{dialog-AmArt43J.js → dialog-CsS26GNP.js} +1 -1
- package/dist/client/assets/{dropdown-menu-CMr4pVGd.js → dropdown-menu-Bx6HZEO6.js} +1 -1
- package/dist/client/assets/{dynamic-plugin-layout-B-RWLbim.js → dynamic-plugin-layout-ChDoP95P.js} +1 -1
- package/dist/client/assets/editable-thread-title-DG8vSbP7.js +16 -0
- package/dist/client/assets/{empty-state-BxqfhnZC.js → empty-state-BIKMZA4A.js} +1 -1
- package/dist/client/assets/{env-vars-editor-CeWJLU0d.js → env-vars-editor-Bu4z6L63.js} +1 -1
- package/dist/client/assets/{error-boundary-BbdoNwwk.js → error-boundary-BOjL_3iE.js} +1 -1
- package/dist/client/assets/{extract-connection-data-FghvIcuN.js → extract-connection-data-9qHOXLXC.js} +1 -1
- package/dist/client/assets/{file-browser-BRNDEG3O.js → file-browser-DlsvWnR4.js} +2 -2
- package/dist/client/assets/{form-Bsyh-cQj.js → form-BcYKMkAo.js} +1 -1
- package/dist/client/assets/{grid-view-BjxbyS3V.js → grid-view-DKE_LwVv.js} +1 -1
- package/dist/client/assets/{home-BqlHZV0D.js → home-CfX1o6Ev.js} +1 -1
- package/dist/client/assets/index-B7FUMscm.css +1 -0
- package/dist/client/assets/{index-ClGhCbA0.js → index-BFnklquP.js} +72 -62
- package/dist/client/assets/{index-IwkUYudi.js → index-BqwppNxk.js} +1 -1
- package/dist/client/assets/{index-CMIePc8v.js → index-CKXRhh0t.js} +37 -37
- package/dist/client/assets/{index-7GX9Z2_E.js → index-DbG6jisP.js} +1 -1
- package/dist/client/assets/{index-BwsTCLNe.js → index-Ds78Hq48.js} +1 -1
- package/dist/client/assets/index-LVMAuFW8.js +1 -0
- package/dist/client/assets/{index-_qbzL5MU.js → index-kQL4iCgd.js} +1 -1
- package/dist/client/assets/{index-Ck8tqNHK.js → index-lC9RbQEq.js} +1 -1
- package/dist/client/assets/{index-MmPZuevW.js → index-nl6bR4T8.js} +1 -1
- package/dist/client/assets/{infiniteQueryObserver-DuAdiH0n.js → infiniteQueryObserver-C_YVCa9u.js} +1 -1
- package/dist/client/assets/{input-Je9XV62u.js → input-BPPp7fkV.js} +1 -1
- package/dist/client/assets/{integration-icon-DeiJ75EP.js → integration-icon-CaUI1jG_.js} +1 -1
- package/dist/client/assets/{label-Ct-IE-k2.js → label-Ce-8MeXM.js} +1 -1
- package/dist/client/assets/{layout-BWtcS0Q2.js → layout-B_vm2aCi.js} +1 -1
- package/dist/client/assets/{localstorage-keys-B-4HWrAO.js → localstorage-keys-D7-2hl7K.js} +1 -1
- package/dist/client/assets/{login-swb3IsCw.js → login-BZjy-JZF.js} +1 -1
- package/dist/client/assets/{markdown-BshJmJUr.js → markdown-CL_nEHz6.js} +1 -1
- package/dist/client/assets/mcp-oauth-6gipdrl8.js +1 -0
- package/dist/client/assets/{mcp-server-card-DJ-C7iNn.js → mcp-server-card-k65UbfnQ.js} +1 -1
- package/dist/client/assets/mcp-server-detail-DOi3A41L.js +2 -0
- package/dist/client/assets/members-DyXednFN.js +3 -0
- package/dist/client/assets/{monitoring-Dkzs8zLr.js → monitoring-CbDWX7qw.js} +2 -2
- package/dist/client/assets/{monitoring-dashboard-edit-6Jd7ItfF.js → monitoring-dashboard-edit-Xu9WaY0f.js} +1 -1
- package/dist/client/assets/{monitoring-dashboard-view-NmZHmCWV.js → monitoring-dashboard-view-BnJZoOh6.js} +1 -1
- package/dist/client/assets/{oauth-callback-hu62EGGB.js → oauth-callback-CLQrXT_i.js} +1 -1
- package/dist/client/assets/page-NSWxyYqB.js +1 -0
- package/dist/client/assets/page-tLMAT584.js +1 -0
- package/dist/client/assets/{plugin-empty-state-BfDH4uPn.js → plugin-empty-state-D5Ff5dMm.js} +1 -1
- package/dist/client/assets/{plugin-empty-state-DRRVQKmb.js → plugin-empty-state-WLlCNcH0.js} +1 -1
- package/dist/client/assets/{plugin-header-BPNBXPjM.js → plugin-header-DBNmWz2Z.js} +1 -1
- package/dist/client/assets/{plugin-header-8kNYjC6n.js → plugin-header-D_CX7196.js} +1 -1
- package/dist/client/assets/{popover-CdPr2kUy.js → popover-Dz4mFPzW.js} +1 -1
- package/dist/client/assets/{project-layout-bgteQ5fY.js → project-layout-L7FdQtTW.js} +1 -1
- package/dist/client/assets/projects-list-DFLeaqhB.js +1 -0
- package/dist/client/assets/{ranking-layout-BxRgmZtS.js → ranking-layout-CLhL84_g.js} +1 -1
- package/dist/client/assets/{readme-viewer-ym80L_hw.js → readme-viewer-BAJaQnye.js} +1 -1
- package/dist/client/assets/{registry-layout-C8Ew4flr.js → registry-layout-CLL316VY.js} +1 -1
- package/dist/client/assets/{registry-utils-DBAgugDf.js → registry-utils-C_nLhlWN.js} +1 -1
- package/dist/client/assets/{reports-layout-BoIJWhiW.js → reports-layout-DnfAta3q.js} +2 -2
- package/dist/client/assets/{reset-password-DY5mUItc.js → reset-password-Cpx9ZUFt.js} +1 -1
- package/dist/client/assets/{resizable-8m39GKGn.js → resizable-TMJNEC5w.js} +1 -1
- package/dist/client/assets/{save-actions-DnxE-Bzm.js → save-actions-BYQZP6Sr.js} +1 -1
- package/dist/client/assets/{scroll-area-C-RNU2ZC.js → scroll-area-D6nBfX1Y.js} +4 -4
- package/dist/client/assets/{select-B9AjxT2Q.js → select-CwR5iwKr.js} +1 -1
- package/dist/client/assets/shell-layout-BnW-yUkb.js +3 -0
- package/dist/client/assets/{skeleton-BAWgWTH6.js → skeleton-DzMO4E_x.js} +1 -1
- package/dist/client/assets/{spinner-C5H8EOvR.js → spinner-B4HBT9r3.js} +1 -1
- package/dist/client/assets/{store-invite-BSP87zro.js → store-invite-DR-2VUII.js} +1 -1
- package/dist/client/assets/{switch-Bnxx_fFZ.js → switch-DkAfY5Xp.js} +1 -1
- package/dist/client/assets/{table-Bt31_DyV.js → table-BDxbk9kk.js} +1 -1
- package/dist/client/assets/tasks-JeX1dzU3.js +1 -0
- package/dist/client/assets/{textarea-Dfcf9iVI.js → textarea-C7R7dq5L.js} +1 -1
- package/dist/client/assets/{time-range-picker-VoxMdMGw.js → time-range-picker-CPtVWgsO.js} +1 -1
- package/dist/client/assets/{toggle-group-BYr6H2N2.js → toggle-group-BsC04HU0.js} +1 -1
- package/dist/client/assets/tools-list-C1FJexpR.js +1 -0
- package/dist/client/assets/{tooltip-Kun6OEqc.js → tooltip-C-TvyUPP.js} +1 -1
- package/dist/client/assets/{topbar-portal-BYkDxjeH.js → topbar-portal-BlsIm0Za.js} +1 -1
- package/dist/client/assets/types-DWiNuJXJ.js +155 -0
- package/dist/client/assets/{use-binding-Bt6opM01.js → use-binding-DtOyQ6H-.js} +1 -1
- package/dist/client/assets/{use-connection-CZeLlUDa.js → use-connection-CU1wdNM8.js} +1 -1
- package/dist/client/assets/{use-copy-BLt7-cw9.js → use-copy-C-xyAEAK.js} +1 -1
- package/dist/client/assets/{use-create-virtual-mcp-BWbRPuCZ.js → use-create-virtual-mcp-CdmTVIKM.js} +1 -1
- package/dist/client/assets/use-deco-chat-open-yra_c3Dw.js +1 -0
- package/dist/client/assets/{use-install-from-registry-BsUBgwfp.js → use-install-from-registry-Dpg6ludv.js} +1 -1
- package/dist/client/assets/{use-list-state-B_n0GZwG.js → use-list-state-DEj8YIwi.js} +1 -1
- package/dist/client/assets/{use-llm-CBsUcVLv.js → use-llm-Bjuj_MKF.js} +1 -1
- package/dist/client/assets/use-mcp-prompts-C2SxEfwc.js +1 -0
- package/dist/client/assets/{use-mcp-tools-BED8kPD7.js → use-mcp-tools-aLeNmzej.js} +1 -1
- package/dist/client/assets/{use-mobile-DLzBblnh.js → use-mobile-B6wwiLld.js} +1 -1
- package/dist/client/assets/{use-organization-settings-BTKBql6r.js → use-organization-settings-DdF3cHOT.js} +1 -1
- package/dist/client/assets/{use-project-Dgs5h9hm.js → use-project-Bmqhspht.js} +1 -1
- package/dist/client/assets/{use-settings-modal-CL7KNbwO.js → use-settings-modal-BQGLflyF.js} +1 -1
- package/dist/client/assets/{use-view-mode-Cm6MlS0B.js → use-view-mode-D5ZS-ZdB.js} +1 -1
- package/dist/client/assets/{use-virtual-mcp-chylq6BL.js → use-virtual-mcp-DqbEku8h.js} +1 -1
- package/dist/client/assets/useInfiniteQuery-DgzNofe0.js +1 -0
- package/dist/client/assets/{useMutation-CTU78J7M.js → useMutation-D2jNlXyR.js} +1 -1
- package/dist/client/assets/useQuery-6KDecjjg.js +1 -0
- package/dist/client/assets/useSuspenseInfiniteQuery-B2-Ew4j-.js +1 -0
- package/dist/client/assets/workflow-DJP52hJ3.js +1 -0
- package/dist/client/index.html +2 -2
- package/dist/server/cli.js +5 -5
- package/dist/server/migrate.js +2 -2
- package/dist/server/server.js +5 -5
- package/package.json +2 -1
- package/dist/client/assets/agent-detail-CAAcyNFf.js +0 -2
- package/dist/client/assets/agents-IxYsoQkx.js +0 -1
- package/dist/client/assets/collection-detail-BPjVfY9E.js +0 -26
- package/dist/client/assets/collection-search-BhyeAK8D.js +0 -1
- package/dist/client/assets/collection-tab-DYRZjIfR.js +0 -1
- package/dist/client/assets/collection-table-wrapper-DF0r5l64.js +0 -1
- package/dist/client/assets/connection-detail-D4fpJvP6.js +0 -1
- package/dist/client/assets/connections-Dd7R3YoP.js +0 -1
- package/dist/client/assets/constants-alL-orOw.js +0 -1
- package/dist/client/assets/empty-state-CUU2GnRG.js +0 -1
- package/dist/client/assets/index-D1eaSCBW.css +0 -1
- package/dist/client/assets/index-DFjHyz2s.js +0 -1
- package/dist/client/assets/mcp-oauth-DtHeHoWJ.js +0 -1
- package/dist/client/assets/mcp-server-detail-Du1aBWwk.js +0 -2
- package/dist/client/assets/members-BLWGtvj7.js +0 -3
- package/dist/client/assets/page-C-wJ53x_.js +0 -1
- package/dist/client/assets/page-Y1SYGnRN.js +0 -1
- package/dist/client/assets/projects-list-DngofdiO.js +0 -1
- package/dist/client/assets/shell-layout-DY2c6Efx.js +0 -3
- package/dist/client/assets/tasks-OIFCJv2K.js +0 -1
- package/dist/client/assets/tools-list-CMPsf87L.js +0 -1
- package/dist/client/assets/typewriter-title-ir44iZyu.js +0 -16
- package/dist/client/assets/use-deco-chat-open-DqF5WsjN.js +0 -1
- package/dist/client/assets/use-mcp-prompts-CTAKOvKB.js +0 -1
- package/dist/client/assets/useInfiniteQuery-B4zFsz_-.js +0 -1
- package/dist/client/assets/useQuery-CL8s1AaN.js +0 -1
- package/dist/client/assets/useSuspenseInfiniteQuery-CnNOZleg.js +0 -1
- package/dist/client/assets/view-mode-toggle-lRAyyRMm.js +0 -1
- package/dist/client/assets/workflow-CH4Jfjr7.js +0 -1
package/dist/server/server.js
CHANGED
|
@@ -1319,7 +1319,7 @@ ${Y.stack}`;return Q}if(typeof Y==="object"&&Y!==null){let Q=Y,X="";if(typeof Q.
|
|
|
1319
1319
|
${Q.stack}`;return X}try{let G=JSON.stringify(Q,null,2);if(G!=="{}"&&G.length<1000){if(typeof Q.stack==="string"&&Q.stack&&Q.stack.length<2000)return`${G}
|
|
1320
1320
|
|
|
1321
1321
|
Stack trace:
|
|
1322
|
-
${Q.stack}`;return G}}catch{}if(typeof Q.toString==="function")try{let G=Q.toString();if(G!=="[object Object]")return G}catch{}let J=Object.keys(Q);if(J.length>0)return`Object with keys: ${J.join(", ")}`;return"[object Object]"}if(typeof Y==="string")return Y;if(typeof Y==="number"||typeof Y==="boolean")return String(Y);if(typeof Y==="function")return`[Function: ${Y.name||"anon"}]`;if(typeof Y==="symbol")return Y.toString();if(typeof Y==="bigint")return Y.toString();try{return String(Y)}catch{return"Unknown value (could not convert to string)"}}function HO(Y,Q){switch(typeof Q){case"string":return Y.newString(Q);case"number":return Y.newNumber(Q);case"boolean":return Q?Y.true:Y.false;case"undefined":return Y.undefined;case"object":{if(Q===null)return Y.null;if(Array.isArray(Q)){let J=Y.newArray();return Q.forEach((G,K)=>{let W=HO(Y,G);try{Y.setProp(J,String(K),W)}finally{W.dispose?.()}}),J}let X=Y.newObject();for(let[J,G]of Object.entries(Q)){let K=HO(Y,G);try{Y.setProp(X,J,K)}finally{K.dispose?.()}}return X}case"function":{let X=`__hostFn_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return Y.newFunction(X,(...G)=>{try{let K=G.map((Z)=>Y.dump(Z)),W=Q(...K);if(W&&typeof W.then==="function"){let Z=Y.newPromise();return W.then((H)=>{try{let $=HO(Y,H);Z.resolve($),$.dispose()}catch($){let F=KO($),V=Y.newString(`Promise resolution error: ${F}`);Z.reject(V),V.dispose()}finally{Y.runtime.executePendingJobs()}}).catch((H)=>{let $=KO(H),F=Y.newString(`Promise rejection: ${$}`);Z.reject(F),F.dispose(),Y.runtime.executePendingJobs()}),Z.handle}return HO(Y,W)}catch(K){let W=KO(K);return Y.newString(`HostFunctionError: ${W}`)}finally{G.forEach((K)=>K.dispose())}})}case"bigint":return Y.newString(Q.toString());case"symbol":return Y.newString(Q.toString());default:try{return Y.newString(String(Q))}catch{return Y.undefined}}}var Fp0=()=>{};function Fz1(Y){let Q=Y.runtime.executePendingJobs(100);try{if("unwrap"in Q&&typeof Q.unwrap==="function")Q.unwrap()}finally{if("dispose"in Q&&typeof Q.dispose==="function")Q.dispose()}}async function Xr(Y,Q,X){let J=Date.now(),G=Y.resolvePromise(Q);while(!0){Fz1(Y);let K=await Promise.race([G,_h6(0).then(()=>null)]);if(K!==null)return K;if(Date.now()-J>X)throw Error(`Timed out after ${X}ms while awaiting a QuickJS promise`)}}async function Xv({tools:Y,code:Q,timeoutMs:X}){let W=[];try{const J=PB(W,await $z1({memoryLimitBytes:33554432,stackSizeBytes:524288}),0);const G=PB(W,J.newContext({interruptAfterMs:X}),0);const K=PB(W,Hz1(G),0);try{let F=G.evalCode(Q,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult(F),B=HO(G,Y);G.setProp(G.global,"tools",B);let U=G.runtime.hasPendingJob()?G.unwrapResult(await Xr(G,V,X)):V;if(U!==V)V.dispose();let D=G.getProp(U,"default"),z=G.typeof(D);if(z!=="function")return D.dispose(),U.dispose(),B.dispose(),{error:`Code must export default a function (tools). Got ${z}. Example: export default async (tools) => { /* ... */ }`,consoleLogs:K.logs};let L=G.callFunction(D,G.undefined,B);B.dispose(),D.dispose(),U.dispose();let w=G.unwrapResult(L),E=await Xr(G,w,X);w.dispose();let T=G.unwrapResult(E);if(G.runtime.hasPendingJob())Fz1(G);let C=G.dump(T);return T.dispose(),{returnValue:C,consoleLogs:K.logs}}catch(F){return console.log(F),{error:KO(F),consoleLogs:K.logs}}}catch(Z){var H=Z,$=1}finally{mo(W,H,$)}}async function Vz1({input:Y,code:Q,timeoutMs:X}){let W=[];try{const J=PB(W,await $z1({memoryLimitBytes:33554432,stackSizeBytes:524288}),0);const G=PB(W,J.newContext({interruptAfterMs:X}),0);const K=PB(W,Hz1(G),0);try{let F=G.evalCode(Q,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult(F),B=HO(G,Y);G.setProp(G.global,"input",B);let U=G.runtime.hasPendingJob()?G.unwrapResult(await Xr(G,V,X)):V;if(U!==V)V.dispose();let D=G.getProp(U,"default"),z=G.typeof(D);if(z!=="function")return D.dispose(),U.dispose(),B.dispose(),{error:`Code must export default a function (input). Got ${z}. Example: export default (input) => { return input.items.map(i => i.name); }`,consoleLogs:K.logs};let L=G.callFunction(D,G.undefined,B);B.dispose(),D.dispose(),U.dispose();let w=G.unwrapResult(L),E=await Xr(G,w,X);w.dispose();let T=G.unwrapResult(E);if(G.runtime.hasPendingJob())Fz1(G);let C=G.dump(T);return T.dispose(),{returnValue:C,consoleLogs:K.logs}}catch(F){return console.log(F),{error:KO(F),consoleLogs:K.logs}}}catch(Z){var H=Z,$=1}finally{mo(W,H,$)}}var _h6=(Y)=>new Promise((Q)=>setTimeout(Q,Y));var Vp0=k(()=>{$p0();Fp0()});var Jr=k(()=>{Vp0()});async function yh6(Y,Q){let X=Y.connections.map((K)=>K.connection_id),J=[];for(let K of X){let W=await Q.storage.connections.findById(K);if(W&&W.status==="active")J.push(W)}return J.map((K)=>{let W=Y.connections.find((Z)=>Z.connection_id===K.id);return{connection:K,selectedTools:W?.selected_tools??null,selectedResources:W?.selected_resources??null,selectedPrompts:W?.selected_prompts??null}})}async function qp0(Y,Q){return(await Q.storage.connections.list(Y)).filter((J)=>J.status==="active").map((J)=>({connection:J,selectedTools:null,selectedResources:null,selectedPrompts:null}))}async function fh6(Y,Q){let X=new Map;for(let B of Y)X.set(B.connection.id,B);let J=Y.map((B)=>B.connection),G=new Map,K=await Promise.allSettled(J.map(async(B)=>{try{let U=await Q.createMCPProxy(B);return{connection:B,proxy:U}}catch(U){return console.warn(`[code-execution] Failed to create proxy for connection ${B.id}:`,U),null}}));for(let B of K)if(B.status==="fulfilled"&&B.value)G.set(B.value.connection.id,B.value);let W=await Promise.allSettled(Array.from(G.entries()).map(async([B,U])=>{try{let z=(await U.proxy.listTools()).tools,L=X.get(B);if(L?.selectedTools&&L.selectedTools.length>0){let w=new Set(L.selectedTools);z=z.filter((E)=>w.has(E.name))}return{connectionId:B,connectionTitle:U.connection.title,tools:z}}catch(D){return console.error(`[code-execution] Failed to list tools for connection ${B}:`,D),null}})),Z=new Set,H=[],$=new Map;for(let B of W){if(B.status!=="fulfilled"||!B.value)continue;let{connectionId:U,connectionTitle:D,tools:z}=B.value;for(let L of z){if(Z.has(L.name))continue;Z.add(L.name),H.push({...L,_meta:{connectionId:U,connectionTitle:D}}),$.set(L.name,U)}}let F=async(B,U)=>{let D=$.get(B);if(!D)return{content:[{type:"text",text:`Tool not found: ${B}`}],isError:!0};let z=G.get(D);if(!z)return{content:[{type:"text",text:`Connection not found for tool: ${B}`}],isError:!0};return await z.proxy.callTool({name:B,arguments:U})},V=[];for(let[,B]of G)V.push(B.proxy.close().catch(()=>{}));return await Promise.all(V),{tools:H,callTool:F}}async function $P(Y){let Q=v0(Y),X;if(Y.connectionId){let J=await Y.storage.virtualMcps.findById(Y.connectionId,Y.organization?.id);if(J)X=await yh6(J,Y);else X=await qp0(Q.id,Y)}else X=await qp0(Q.id,Y);return fh6(X,Y)}function bh6(Y){return Y.toLowerCase().split(/[\s_\-./]+/).filter((Q)=>Q.length>=2)}function hh6(Y,Q){let X=0,J=Q.name.toLowerCase(),G=(Q.description??"").toLowerCase(),K=(Q._meta?.connectionTitle??"").toLowerCase();for(let W of Y){if(J===W)X+=10;else if(J.includes(W))X+=3;if(G.includes(W))X+=2;if(K.includes(W))X+=1}return X}function Gr(Y,Q,X){let J=bh6(Y);if(J.length===0)return Q.slice(0,X);return Q.map((G)=>({tool:G,score:hh6(J,G)})).filter((G)=>G.score>0).sort((G,K)=>K.score-G.score).slice(0,X).map((G)=>G.tool)}function Wr(Y,Q){let X=new Map(Q.map((G)=>[G.name,G]));return{tools:Y.map((G)=>X.get(G)).filter((G)=>G!==void 0).map((G)=>({name:G.name,description:G.description,connection:G._meta?.connectionTitle??"",inputSchema:G.inputSchema,outputSchema:G.outputSchema})),notFound:Y.filter((G)=>!X.has(G))}}async function Zr(Y,Q,X){let J=Object.fromEntries(Q.tools.map((G)=>[G.name,async(K)=>{let W=await Q.callTool(G.name,K??{});if(W.structuredContent&&typeof W.structuredContent==="object")return W.structuredContent;let Z=W.content;if(Z?.[0]?.type==="text"&&Z[0].text)try{return JSON.parse(Z[0].text)}catch{return Z[0].text}return W}]));return Xv({code:Y,tools:J,timeoutMs:X})}function Jv(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}]}}function GB(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}],isError:!0}}function KF(Y){let Q=new Set(xh6);return Y.filter((X)=>!Q.has(X.name))}var xh6;var $O=k(()=>{Jr();xh6=["CODE_EXECUTION_SEARCH_TOOLS","CODE_EXECUTION_DESCRIBE_TOOLS","CODE_EXECUTION_RUN_CODE"]});var qz1;var Bp0=k(()=>{F4();Qv();$O();qz1=s1({name:"CODE_EXECUTION_SEARCH_TOOLS",description:"Search for available tools by name or description. Returns tool names and brief descriptions without full schemas. Use this to discover tools before calling CODE_EXECUTION_DESCRIBE_TOOLS for detailed schemas.",annotations:{title:"Search Tools",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:Yp0,outputSchema:Qp0,handler:async(Y,Q)=>{D0(Q),v0(Q),await Q.access.check();let X=await $P(Q),J=Gr(Y.query,X.tools,Y.limit);return{query:Y.query,results:J.map((G)=>({name:G.name,description:G.description,connection:G._meta?.connectionTitle??""})),totalAvailable:X.tools.length}}})});var Bz1;var Up0=k(()=>{F4();Qv();$O();Bz1=s1({name:"CODE_EXECUTION_DESCRIBE_TOOLS",description:"Get detailed schemas for specific tools. Call after CODE_EXECUTION_SEARCH_TOOLS to get full input/output schemas before executing code.",annotations:{title:"Describe Tools",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:Xp0,outputSchema:Jp0,handler:async(Y,Q)=>{D0(Q),v0(Q),await Q.access.check();let X=await $P(Q);return Wr(Y.tools,X.tools)}})});var Uz1;var Dp0=k(()=>{F4();Qv();$O();Uz1=s1({name:"CODE_EXECUTION_RUN_CODE",description:'Run JavaScript code in a sandbox. Code must be an ES module that `export default`s an async function that receives (tools) as its first parameter. Use CODE_EXECUTION_DESCRIBE_TOOLS to understand the input/output schemas for a tool before calling it. Use `await tools.toolName(args)` or `await tools["tool-name"](args)` to call tools.',annotations:{title:"Run Code",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},inputSchema:Gp0,outputSchema:Wp0,handler:async(Y,Q)=>{D0(Q),v0(Q),await Q.access.check();let X=await $P(Q);return await Zr(Y.code,X,Y.timeoutMs)}})});var zp0=k(()=>{Bp0();Up0();Dp0();Qv()});var uh6,mh6,Dz1;var Op0=k(()=>{KY();c1();F4();kn();b$();uh6=q.object({data:PR.describe("Data for the new connection (id is auto-generated if not provided)")}),mh6=q.object({item:W5.describe("The created connection entity")}),Dz1=s1({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",annotations:{title:"Create Connection",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:uh6,outputSchema:mh6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=EY(Q);if(!J)throw Error("User ID required to create connection");let G={...Y.data,organization_id:X.id,created_by:J};if(G.connection_type==="VIRTUAL"){let $=DD(G.connection_url);if(!$)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let F=await Q.storage.virtualMcps.findById($);if(!F)throw Error(`Virtual MCP not found: ${$}`);if(F.organization_id!==X.id)throw Error("Virtual MCP does not belong to the current organization");G.connection_url=zD($)}let K=await DA({id:`pending-${Date.now()}`,title:G.title,connection_type:G.connection_type,connection_url:G.connection_url,connection_token:G.connection_token,connection_headers:G.connection_headers}).catch(()=>null),W=K?.tools?.length?K.tools:null,Z=K?.scopes?.length?K.scopes:null,H=await Q.storage.connections.create({...G,tools:W,configuration_scopes:Z});return await Q.eventBus.publish(X.id,IY.SELF(X.id),{type:"connection.created",data:H}),{item:H}}})});var lh6,dh6,Np0;var Lp0=k(()=>{c1();MG();lh6=bH.extend({avatar:q.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:q.string().describe("System prompt that defines the assistant's behavior"),virtual_mcp_id:q.string().describe("Virtual MCP ID to use for this assistant"),model:q.object({id:q.string().describe("Model ID"),connectionId:q.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),dh6=hH("assistant",lh6),Np0=[...dh6]});var Gv,HF,wp0,ph6,ch6,Ap0,nh6,ih6,ah6,rh6,oh6,sh6,Pp0,th6,eh6,Yx6,Qx6,Xx6,Jx6,Gx6,Wx6,Zx6,Kx6,MH9,Hx6,wH9,Mp0,$x6,Fx6,zz1,Wv;var Kr=k(()=>{c1();_z();MG();Gv=q.lazy(()=>q.union([q.null(),q.string(),q.number(),q.boolean(),q.record(q.string(),Gv),q.array(Gv)])),HF=q.record(q.string(),q.record(q.string(),Gv)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),wp0=q.object({type:q.literal("text"),text:q.string().describe("The text content"),providerOptions:HF}),ph6=q.object({type:q.literal("text"),text:q.string().describe("The text content"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),ch6=q.string().describe("File data as URL string"),Ap0=q.object({type:q.literal("file"),filename:q.string().optional().describe("Optional filename of the file"),data:ch6,mediaType:q.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:HF}),nh6=q.object({type:q.literal("file"),mediaType:q.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),data:q.string().describe("Generated file data as base64 encoded string")}),ih6=q.object({type:q.literal("reasoning"),text:q.string().describe("The reasoning text"),providerOptions:HF}),ah6=q.object({type:q.literal("reasoning"),text:q.string().describe("The reasoning text"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),rh6=q.object({type:q.literal("tool-call"),toolCallId:q.string().describe("ID of the tool call, used to match with tool result"),toolName:q.string().describe("Name of the tool being called"),input:q.string().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:q.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:HF}),oh6=q.object({type:q.literal("tool-call"),toolCallId:q.string().describe("ID of the tool call"),toolName:q.string().describe("Name of the tool being called"),input:q.string().describe("Stringified JSON object with the tool call arguments"),providerExecuted:q.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),sh6=q.union([q.object({type:q.literal("text"),value:q.string()}),q.object({type:q.literal("json"),value:Gv}),q.object({type:q.literal("error-text"),value:q.string()}),q.object({type:q.literal("error-json"),value:Gv}),q.object({type:q.literal("content"),value:q.array(q.union([q.object({type:q.literal("text"),text:q.string().describe("Text content")}),q.object({type:q.literal("media"),data:q.string().describe("Base-64 encoded media data"),mediaType:q.string().describe("IANA media type")})]))}),q.object({type:q.literal("execution-denied"),reason:q.string().optional()}),q.string().describe("Raw or JSON-serialized output (e.g. from AI SDK mapToolResultOutput)")]),Pp0=q.object({type:q.literal("tool-result"),toolCallId:q.string().describe("ID of the tool call that this result is associated with"),toolName:q.string().describe("Name of the tool that generated this result"),output:sh6.describe("Result of the tool call"),result:q.unknown().describe("Unknown result of the tool call"),providerOptions:HF}),th6=q.object({type:q.literal("tool-result"),toolCallId:q.string().describe("ID of the tool call that this result is associated with"),toolName:q.string().describe("Name of the tool that generated this result"),result:q.any().describe("Result of the tool call (JSON-serializable)"),isError:q.boolean().optional().describe("Whether the result is an error or error message"),providerExecuted:q.boolean().optional().describe("Whether the tool result was generated by the provider"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),eh6=q.union([q.object({type:q.literal("source"),sourceType:q.literal("url"),id:q.string().describe("The ID of the source"),url:q.string().describe("The URL of the source"),title:q.string().optional().describe("The title of the source"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),q.object({type:q.literal("source"),sourceType:q.literal("document"),id:q.string().describe("The ID of the source"),mediaType:q.string().describe("IANA media type of the document (e.g., application/pdf)"),title:q.string().describe("The title of the document"),filename:q.string().optional().describe("Optional filename of the document"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")})]),Yx6=q.object({role:q.literal("system"),content:q.string().describe("System message content"),providerOptions:HF}),Qx6=q.object({role:q.literal("user"),content:q.array(q.union([wp0,Ap0])).describe("User message content parts (text or file)"),providerOptions:HF}),Xx6=q.object({role:q.literal("assistant"),content:q.array(q.union([wp0,Ap0,ih6,rh6,Pp0])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:HF}),Jx6=q.object({role:q.literal("tool"),content:q.array(Pp0).describe("Tool message content (tool results)"),providerOptions:HF}),Gx6=q.union([Yx6,Qx6,Xx6,Jx6]),Wx6=q.array(Gx6).describe("A list of messages forming the prompt"),Zx6=q.object({prompt:Wx6.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:q.number().optional().describe("Maximum number of tokens to generate"),temperature:q.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:q.number().optional().describe("Nucleus sampling parameter"),topK:q.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:q.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:q.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:q.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:q.array(q.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:q.union([q.object({type:q.literal("text")}),q.object({type:q.literal("json"),schema:q.any().optional().describe("JSON schema that the generated output should conform to"),name:q.string().optional().describe("Name of output that should be generated"),description:q.string().optional().describe("Description of the output that should be generated")})]).optional().describe("Response format. The output can either be text or JSON. Default is text"),tools:q.array(q.any()).optional().describe("The tools that are available for the model"),toolChoice:q.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:q.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:q.any().optional().describe("Abort signal for cancelling the operation"),providerOptions:q.any().optional().describe("Additional provider-specific options")}),Kx6=q.object({content:q.array(q.union([ph6,nh6,ah6,oh6,th6,eh6])).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:q.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:q.looseObject({inputTokens:q.number().optional(),outputTokens:q.number().optional(),totalTokens:q.number().optional(),reasoningTokens:q.number().optional()}).describe("Usage information for the language model call"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata"),request:q.object({body:q.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:q.object({id:q.string().optional().describe("ID for the generated response"),timestamp:q.iso.datetime().optional().describe("Timestamp for the start of the generated response"),modelId:q.string().optional().describe("The ID of the response model that was used"),headers:q.record(q.string(),q.string()).optional().describe("Response headers"),body:q.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:q.array(q.any()).describe("Warnings for the call, e.g. unsupported settings")}),MH9=q.object({stream:q.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:q.object({body:q.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:q.object({headers:q.record(q.string(),q.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),Hx6=q.object({supportedUrls:q.record(q.string(),q.array(q.string())).describe("Supported URL patterns by media type for the provider")}),wH9=q.object({modelId:q.string().describe("The ID of the model"),logo:q.string().nullable(),description:q.string().nullable(),capabilities:q.array(q.string()),limits:q.object({contextWindow:q.number(),maxOutputTokens:q.number()}).nullable(),costs:q.object({input:q.number(),output:q.number()}).nullable(),provider:q.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),Mp0=q.object({modelId:q.string().describe("The ID of the model"),callOptions:Zx6}),$x6=bH.extend({logo:q.string().nullable(),description:q.string().nullable(),capabilities:q.array(q.string()),limits:q.object({contextWindow:q.number(),maxOutputTokens:q.number()}).nullable(),costs:q.object({input:q.number(),output:q.number()}).nullable(),provider:q.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),Fx6=hH("llm",$x6,{readOnly:!0}),zz1=[{name:"LLM_METADATA",inputSchema:q.object({modelId:q.string().describe("The ID of the model")}),outputSchema:Hx6},{name:"LLM_DO_STREAM",inputSchema:Mp0,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:Mp0,outputSchema:Kx6},...Fx6],Wv=yH(zz1)});function FP(){return!1}function Hr(Y,Q){return Y===IY.DEV_ASSETS(Q)}function VP(Y,Q){let X=D71(Q,Y),J=new Date().toISOString();return{id:X.id??IY.DEV_ASSETS(Y),title:X.title,description:X.description??null,icon:X.icon??null,app_name:X.app_name??null,app_id:X.app_id??null,organization_id:Y,created_by:"system",created_at:J,updated_at:J,connection_type:X.connection_type,connection_url:X.connection_url??null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:X.metadata??null,tools:Vx6,bindings:["OBJECT_STORAGE"],status:"active"}}var Vx6;var $r=k(()=>{ln();KY();c1();Vx6=uS.map((Y)=>({name:Y.name,description:`${Y.name} operation for local file storage`,inputSchema:q.toJSONSchema(Y.inputSchema),outputSchema:q.toJSONSchema(Y.outputSchema)}))});function Bx6(Y){let Q=[],X=0;while(X<Y.length){let J=Y[X];if(J==="%")Q.push(".*");else if(J==="_")Q.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))Q.push("\\"+J);else Q.push(J);X++}return Q.join("")}function WB(Y){return typeof Y==="string"||typeof Y==="number"}function Fr(Y,Q){if("conditions"in Q){let{operator:Z,conditions:H}=Q;switch(Z){case"and":return H.every(($)=>Fr(Y,$));case"or":return H.some(($)=>Fr(Y,$));case"not":return!H.every(($)=>Fr(Y,$));default:return!0}}let{field:X,operator:J,value:G}=Q,K=X.join("."),W=Oz1(Y,K);switch(J){case"eq":return W===G;case"gt":return WB(W)&&WB(G)&&W>G;case"gte":return WB(W)&&WB(G)&&W>=G;case"lt":return WB(W)&&WB(G)&&W<G;case"lte":return WB(W)&&WB(G)&&W<=G;case"in":return Array.isArray(G)&&G.includes(W);case"like":if(typeof W!=="string"||typeof G!=="string")return!1;if(G.length>100)return!1;let Z=Bx6(G);return new RegExp(`^${Z}$`,"i").test(W);case"contains":if(typeof W!=="string"||typeof G!=="string")return!1;return W.toLowerCase().includes(G.toLowerCase());default:return!0}}function Oz1(Y,Q){let X=Q.split("."),J=Y;for(let G of X){if(J==null||typeof J!=="object")return;J=J[G]}return J}function Ux6(Y,Q){return[...Y].sort((X,J)=>{for(let G of Q){let K=G.field.join("."),W=Oz1(X,K),Z=Oz1(J,K),H=0;if(W==null&&Z==null)continue;if(W==null)H=G.nulls==="first"?-1:1;else if(Z==null)H=G.nulls==="first"?1:-1;else if(typeof W==="string"&&typeof Z==="string")H=W.localeCompare(Z);else if(typeof W==="number"&&typeof Z==="number")H=W-Z;else H=String(W).localeCompare(String(Z));if(H!==0)return G.direction==="desc"?-H:H}return 0})}var qx6,Dx6,zx6,Nz1;var Ep0=k(()=>{lS();Lp0();MG();Kr();ln();KY();c1();F4();$r();b$();qx6={LLM:zz1,ASSISTANTS:Np0,OBJECT_STORAGE:uS};Dx6=uZ.extend({binding:q.union([q.object({}).passthrough(),q.string()]).optional(),include_virtual:q.boolean().optional().describe("Whether to include VIRTUAL connections in the results. Defaults to false.")}),zx6=x$(W5),Nz1=s1({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",annotations:{title:"List Connections",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:Dx6,outputSchema:zx6,handler:async(Y,Q)=>{await Q.access.check();let X=v0(Q),J=Y.binding?typeof Y.binding==="string"?(()=>{let B=qx6[Y.binding.toUpperCase()];if(!B)throw Error(`Unknown binding: ${Y.binding}`);return B})():Y.binding:void 0,G=J?xn(J):void 0,K=await Q.storage.connections.list(X.id,{includeVirtual:Y.include_virtual??!1});if(FP()){let B=K7(),U=IY.DEV_ASSETS(X.id);if(!K.some((D)=>D.id===U)){let D=VP(X.id,B);K.unshift(D)}}let W=G?await Promise.all(K.map(async(B)=>{if(!B.tools||B.tools.length===0)return null;return G.isImplementedBy(B.tools.map((D)=>({name:D.name,inputSchema:D.inputSchema,outputSchema:D.outputSchema})))?B:null})).then((B)=>B.filter((U)=>U!==null)):K;if(Y.where)W=W.filter((B)=>Fr(B,Y.where));if(Y.orderBy&&Y.orderBy.length>0)W=Ux6(W,Y.orderBy);let Z=W.length,H=Y.offset??0,$=Y.limit??100,F=W.slice(H,H+$),V=H+$<Z;return{items:F,totalCount:Z,hasMore:V}}})});var Ox6,Lz1;var Tp0=k(()=>{MG();F4();$r();b$();Ox6=TS(W5),Lz1=s1({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",annotations:{title:"Get Connection",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:ES,outputSchema:Ox6,handler:async(Y,Q)=>{let X=v0(Q);if(await Q.access.check(),FP()&&Hr(Y.id,X.id))return{item:VP(X.id,K7())};let J=await Q.storage.connections.findById(Y.id);if(!J||J.organization_id!==X.id)return{item:null};return{item:J}}})});var Vr=(Y,Q)=>{if(Q===null||Q===void 0)return;let X=Y.replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),J=Q;for(let G of X){if(J===null||J===void 0||typeof J!=="object")return;J=J[G]}return J};function Cp0(Y){let Q=Y.split("::");if(Q.length!==2||!Q[0]||!Q[1])throw Error(`Invalid scope format: ${Y}. Expected format: "KEY::SCOPE"`);return Q}function Nx6(Y){let Q=Y.split("::");if(Q.length!==2||!Q[0]||!Q[1])return null;return Q}function Lx6(Y){if(typeof Y==="object"&&Y!==null&&"value"in Y){let Q=Y.value;if(typeof Q==="string")return Q}return null}function Mz1(Y,Q){let X={};if(!Y||!Q)return X;for(let J of Q){if(J==="*"){X["*"]=["*"];continue}let G=Nx6(J);if(!G)continue;let[K,W]=G,Z=Vr(K,Y),H=Lx6(Z);if(H){if(!X[H])X[H]=[];X[H].push(W)}}return X}function Rp0(Y,Q){let X=Mz1(Y,Q);return new Set(Object.keys(X).filter((J)=>J!=="*"))}var wz1=()=>{};import{randomBytes as Mx6}from"crypto";function Ip0(){if(Zv)return Zv;let Y=process.env.MESH_JWT_SECRET??p9.jwt?.secret??process.env.BETTER_AUTH_SECRET;if(Y)Zv=new TextEncoder().encode(Y);else console.warn("MESH_JWT_SECRET not set - generating random secret (not persistent)"),Zv=new Uint8Array(Mx6(32));return Zv}async function jp0(Y,Q="5m"){let X=Ip0();return await new BG(Y).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(Q).sign(X)}async function Sp0(Y){try{let Q=Ip0(),{payload:X}=await JY(Y,Q);return X}catch{return}}var Zv=null;var Az1=k(()=>{UG();Kv()});async function kp0(Y){if(!Y.refreshToken)return{success:!1,error:"No refresh token available"};if(!Y.tokenEndpoint)return{success:!1,error:"No token endpoint available"};if(!Y.clientId)return{success:!1,error:"No client ID available"};try{let Q=new URLSearchParams({grant_type:"refresh_token",refresh_token:Y.refreshToken,client_id:Y.clientId});if(Y.clientSecret)Q.set("client_secret",Y.clientSecret);if(Y.scope)Q.set("scope",Y.scope);let X=await fetch(Y.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Q.toString()});if(!X.ok){let G=await X.text();console.error(`[TokenRefresh] Failed to refresh token: ${X.status}`,G);try{let K=JSON.parse(G);return{success:!1,error:K.error_description||K.error||`Token refresh failed: ${X.status}`}}catch{return{success:!1,error:`Token refresh failed: ${X.status}`}}}let J=await X.json();return{success:!0,accessToken:J.access_token,refreshToken:J.refresh_token||Y.refreshToken,expiresIn:J.expires_in,scope:J.scope}}catch(Q){return console.error("[TokenRefresh] Error refreshing token:",Q),{success:!1,error:Q instanceof Error?Q.message:"Token refresh failed"}}}class $F{db;vault;constructor(Y,Q){this.db=Y;this.vault=Q}async get(Y){let Q=await this.db.selectFrom("downstream_tokens").selectAll().where("connectionId","=",Y).executeTakeFirst();if(!Q)return null;return this.decryptToken(Q)}async upsert(Y){let Q=new Date().toISOString(),X=await this.vault.encrypt(Y.accessToken),J=Y.refreshToken?await this.vault.encrypt(Y.refreshToken):null,G=Y.clientSecret?await this.vault.encrypt(Y.clientSecret):null;return await this.db.transaction().execute(async(K)=>{let W=await K.selectFrom("downstream_tokens").select(["id","createdAt"]).where("connectionId","=",Y.connectionId).executeTakeFirst();if(W)return await K.updateTable("downstream_tokens").set({accessToken:X,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,updatedAt:Q}).where("id","=",W.id).execute(),{id:W.id,connectionId:Y.connectionId,accessToken:Y.accessToken,refreshToken:Y.refreshToken,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:W.createdAt,updatedAt:Q,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint};let Z=X9("dtok");return await K.insertInto("downstream_tokens").values({id:Z,connectionId:Y.connectionId,accessToken:X,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,createdAt:Q,updatedAt:Q}).execute(),{id:Z,connectionId:Y.connectionId,accessToken:Y.accessToken,refreshToken:Y.refreshToken,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:Q,updatedAt:Q,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint}})}async delete(Y){await this.db.deleteFrom("downstream_tokens").where("connectionId","=",Y).execute()}isExpired(Y,Q=0){if(!Y.expiresAt)return!1;let J=(Y.expiresAt instanceof Date?Y.expiresAt:new Date(Y.expiresAt)).getTime();if(Number.isNaN(J))return!0;return J-Q<Date.now()}async decryptToken(Y){let Q=await this.vault.decrypt(Y.accessToken),X=Y.refreshToken?await this.vault.decrypt(Y.refreshToken):null,J=Y.clientSecret?await this.vault.decrypt(Y.clientSecret):null;return{id:Y.id,connectionId:Y.connectionId,accessToken:Q,refreshToken:X,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:Y.createdAt,updatedAt:Y.updatedAt,clientId:Y.clientId,clientSecret:J,tokenEndpoint:Y.tokenEndpoint}}}var qr=k(()=>{$7()});async function Hv(Y,Q,X){let J=Y.id,G=Mz1(Y.configuration_state,Y.configuration_scopes),K=Q.auth.user?.id??Q.auth.apiKey?.userId??(X?Y.created_by:void 0),[W,Z]=K?await jp0({sub:K,user:{id:K},metadata:{state:Y.configuration_state??void 0,meshUrl:Q.baseUrl,connectionId:J,organizationId:Q.organization?.id},permissions:G}).then((U)=>[U,null]).catch((U)=>[null,U]):[null,Error("User ID required to issue configuration token")];if(Z)console.error("Failed to issue configuration token:",W);let H=Q.auth.user?.connectionId,$={...H?{"x-caller-id":H}:{},...Q.metadata.wellKnownForwardableHeaders??{},"x-request-id":Q.metadata.requestId},F=null,V=new $F(Q.db,Q.vault),B=await V.get(J);if(B){let U=!!B.refreshToken&&!!B.tokenEndpoint;if(V.isExpired(B,U?300000:0))if(U){console.log(`[Proxy] Token expired for ${J}, attempting refresh`);let z=await kp0(B);if(z.success&&z.accessToken)await V.upsert({connectionId:J,accessToken:z.accessToken,refreshToken:z.refreshToken??B.refreshToken,scope:z.scope??B.scope,expiresAt:z.expiresIn?new Date(Date.now()+z.expiresIn*1000):null,clientId:B.clientId,clientSecret:B.clientSecret,tokenEndpoint:B.tokenEndpoint}),F=z.accessToken,console.log(`[Proxy] Token refreshed for ${J}`);else await V.delete(J),console.error(`[Proxy] Token refresh failed for ${J}: ${z.error}`)}else await V.delete(J),console.log(`[Proxy] Token expired without refresh capability for ${J}`);else F=B.accessToken}if(!F&&Y.connection_token)F=Y.connection_token;if(F)$.Authorization=`Bearer ${F}`;if(W)$["x-mesh-token"]=W;return $}var Pz1=k(()=>{wz1();Az1();qr()});function Br(){let Y=new Map;function Q(J,G){let K=Y.get(G);if(K)return console.log(`[ClientPool] Reusing cached client for ${G}`),K;console.log(`[ClientPool] Creating new client for ${G}`);let W=new G5({name:`outbound-client-${G}`,version:"1.0.0"},{capabilities:{tasks:{list:{},cancel:{},requests:{tool:{call:{}}}}}});W.onclose=()=>{Y.delete(G)};let Z=W.connect(J,{timeout:30000}).then(()=>W).catch((H)=>{throw Y.delete(G),H});return Y.set(G,Z),Z}return Object.assign(Q,{[Symbol.asyncDispose]:async()=>{let J=[];for(let[G,K]of Y)J.push(K.then((W)=>W.close()).catch((W)=>console.error(`[ClientPool] Error closing client ${G}:`,W)));await Promise.all(J),Y.clear()}})}var Ez1=k(()=>{qD()});function vp0(Y){let Q=new wS({command:Y.command,args:Y.args,env:Y.env,cwd:Y.cwd,stderr:"pipe"}),X=Y.name||Y.id,J="\x1B[2m",G="\x1B[0m";return Q.stderr?.on("data",(K)=>{let W=K.toString().trimEnd();if(W)console.error(`${W} \x1B[2m[${X}]\x1B[0m`)}),Q}var _p0=k(()=>{yV1()});class $v{innerTransport;constructor(Y){this.innerTransport=Y}async start(){return this.innerTransport.onmessage=(Y)=>{this.handleIncomingMessage(Y)},this.innerTransport.onerror=(Y)=>{this.onerror?.(Y)},this.innerTransport.onclose=()=>{this.onclose?.()},this.innerTransport.start()}async send(Y){return this.handleOutgoingMessage(Y)}async close(){return this.innerTransport.close()}async handleOutgoingMessage(Y){return this.innerTransport.send(Y)}handleIncomingMessage(Y){this.onmessage?.(Y)}isRequest(Y){return"method"in Y&&Y.method!==void 0}isResponse(Y){return"result"in Y||"error"in Y&&!("method"in Y)}onmessage;onerror;onclose}function Fv(Y,...Q){return Q.reduce((X,J)=>J(X),Y)}var yp0="mcp.mesh";var fp0,Tz1,FF;var Vv=k(()=>{fp0=class fp0 extends Error{constructor(Y){super(Y);this.name="UnauthorizedError"}};Tz1=class Tz1 extends Error{constructor(Y){super(Y);this.name="ForbiddenError"}};FF=class FF{userId;toolName;boundAuth;role;connectionId;getToolMeta;_granted=!1;constructor(Y,Q,X,J,G,K="self",W){this.userId=Q;this.toolName=X;this.boundAuth=J;this.role=G;this.connectionId=K;this.getToolMeta=W}[Symbol.dispose](){this._granted=!1}setToolName(Y){this.toolName=Y}grant(){return this._granted=!0,{[Symbol.dispose]:()=>{this._granted=!1}}}async check(...Y){if(this._granted)return;if(this.toolName?.startsWith("MESH_PUBLIC_")){this.grant();return}if(!this.userId&&!this.boundAuth){if(this.getToolMeta&&await this.isToolPublic()){this.grant();return}throw new fp0("Authentication required. Please provide a valid OAuth token or API key.")}let Q=Y.length>0?Y:this.toolName?[this.toolName]:[];if(Q.length===0)throw new Tz1("No resources specified for access check");for(let X of Q)if(await this.checkResource(X)){this.grant();return}throw new Tz1(`Access denied to: ${Q.join(", ")}`)}async checkResource(Y){if(!this.userId&&!this.boundAuth)return!1;if(this.role==="admin"||this.role==="owner")return!0;if(!this.boundAuth)return!1;let Q={};if(this.connectionId)Q[this.connectionId]=[Y];return this.boundAuth.hasPermission(Q)}async isToolPublic(){if(this.toolName?.startsWith("MESH_PUBLIC_"))return!0;if(!this.getToolMeta)return!1;try{let Y=await this.getToolMeta();if(!Y)return!1;let X=Y[yp0]?.public_tool;return X===!0||X==="true"}catch{return!1}}granted(){return this._granted}}});var wx6="mcp.mesh",qP;var bp0=k(()=>{Vv();qP=class qP extends $v{options;cachedToolsMap=null;constructor(Y,Q){super(Y);this.options=Q;if(Q.connection.tools)this.cachedToolsMap=new Map(Q.connection.tools.map((X)=>[X.name,X]))}async handleOutgoingMessage(Y){if(!this.isRequest(Y))return this.innerTransport.send(Y);let Q=Y;if(Q.method==="tools/call")await this.authorizeToolCall(Q),this.stripMetaFromArguments(Q);return this.innerTransport.send(Y)}async authorizeToolCall(Y){if(this.options.superUser)return;let X=Y.params.name,{ctx:J,connection:G}=this.options;if(this.isPublicTool(X))return;if(!J.auth.user?.id&&!J.auth.apiKey?.id)throw Error("Authentication required. Please provide a valid OAuth token or API key.");let K=async()=>{return this.cachedToolsMap?.get(X)?._meta};await new FF(J.authInstance,J.auth.user?.id??J.auth.apiKey?.userId,X,J.boundAuth,J.auth.user?.role,G.id,K).check(X)}isPublicTool(Y){if(Y.startsWith("MESH_PUBLIC_"))return!0;if(!this.cachedToolsMap)return!1;let Q=this.cachedToolsMap.get(Y);if(!Q?._meta)return!1;return Q._meta[wx6]?.public_tool===!0}stripMetaFromArguments(Y){let Q=Y.params;if(Q.arguments&&"_meta"in Q.arguments){let{_meta:X,...J}=Q.arguments;Q.arguments=J}}}});function xp0(Y){if(!Y.isError)return;let Q=Y.content;if(!Array.isArray(Q))return;for(let X of Q)if(X&&typeof X==="object"&&"type"in X&&X.type==="text"&&"text"in X&&typeof X.text==="string")return X.text;return}function Rz1(Y){if(!Y)return;let Q=Y._meta;if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let X=Q.properties;if(!X||typeof X!=="object"||Array.isArray(X))return;let J={};for(let[G,K]of Object.entries(X))if(typeof K==="string")J[G]=K;return Object.keys(J).length>0?J:void 0}function Iz1(Y,Q){if(!Y&&!Q)return;if(!Y)return Q;if(!Q)return Y;return{...Q,...Y}}function jz1(Y){if(Y&&typeof Y==="object"&&!Array.isArray(Y)){let Q=Y,X=Q.structuredContent;if(X&&typeof X==="object"&&!Array.isArray(X))return X;return Q}return{value:Y}}async function Ax6(Y,Q){let X=Y.body;if(!X)return{text:"",truncated:!1};let J=X.getReader(),G=new TextDecoder,K=!1,W=0,Z=[];try{while(!0){let{value:H,done:$}=await J.read();if($)break;if(H){if(W+=H.byteLength,W>Q){K=!0;let F=Q-(W-H.byteLength);if(F>0)Z.push(G.decode(H.slice(0,F),{stream:!0}));break}Z.push(G.decode(H,{stream:!0}))}}}finally{J.releaseLock()}return Z.push(G.decode()),{text:Z.join(""),truncated:K}}function Px6(Y){if(!Y)return;let Q=Y.trimEnd().split(`
|
|
1322
|
+
${Q.stack}`;return G}}catch{}if(typeof Q.toString==="function")try{let G=Q.toString();if(G!=="[object Object]")return G}catch{}let J=Object.keys(Q);if(J.length>0)return`Object with keys: ${J.join(", ")}`;return"[object Object]"}if(typeof Y==="string")return Y;if(typeof Y==="number"||typeof Y==="boolean")return String(Y);if(typeof Y==="function")return`[Function: ${Y.name||"anon"}]`;if(typeof Y==="symbol")return Y.toString();if(typeof Y==="bigint")return Y.toString();try{return String(Y)}catch{return"Unknown value (could not convert to string)"}}function HO(Y,Q){switch(typeof Q){case"string":return Y.newString(Q);case"number":return Y.newNumber(Q);case"boolean":return Q?Y.true:Y.false;case"undefined":return Y.undefined;case"object":{if(Q===null)return Y.null;if(Array.isArray(Q)){let J=Y.newArray();return Q.forEach((G,K)=>{let W=HO(Y,G);try{Y.setProp(J,String(K),W)}finally{W.dispose?.()}}),J}let X=Y.newObject();for(let[J,G]of Object.entries(Q)){let K=HO(Y,G);try{Y.setProp(X,J,K)}finally{K.dispose?.()}}return X}case"function":{let X=`__hostFn_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return Y.newFunction(X,(...G)=>{try{let K=G.map((Z)=>Y.dump(Z)),W=Q(...K);if(W&&typeof W.then==="function"){let Z=Y.newPromise();return W.then((H)=>{try{let $=HO(Y,H);Z.resolve($),$.dispose()}catch($){let F=KO($),V=Y.newString(`Promise resolution error: ${F}`);Z.reject(V),V.dispose()}finally{Y.runtime.executePendingJobs()}}).catch((H)=>{let $=KO(H),F=Y.newString(`Promise rejection: ${$}`);Z.reject(F),F.dispose(),Y.runtime.executePendingJobs()}),Z.handle}return HO(Y,W)}catch(K){let W=KO(K);return Y.newString(`HostFunctionError: ${W}`)}finally{G.forEach((K)=>K.dispose())}})}case"bigint":return Y.newString(Q.toString());case"symbol":return Y.newString(Q.toString());default:try{return Y.newString(String(Q))}catch{return Y.undefined}}}var Fp0=()=>{};function Fz1(Y){let Q=Y.runtime.executePendingJobs(100);try{if("unwrap"in Q&&typeof Q.unwrap==="function")Q.unwrap()}finally{if("dispose"in Q&&typeof Q.dispose==="function")Q.dispose()}}async function Xr(Y,Q,X){let J=Date.now(),G=Y.resolvePromise(Q);while(!0){Fz1(Y);let K=await Promise.race([G,_h6(0).then(()=>null)]);if(K!==null)return K;if(Date.now()-J>X)throw Error(`Timed out after ${X}ms while awaiting a QuickJS promise`)}}async function Xv({tools:Y,code:Q,timeoutMs:X}){let W=[];try{const J=PB(W,await $z1({memoryLimitBytes:33554432,stackSizeBytes:524288}),0);const G=PB(W,J.newContext({interruptAfterMs:X}),0);const K=PB(W,Hz1(G),0);try{let F=G.evalCode(Q,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult(F),B=HO(G,Y);G.setProp(G.global,"tools",B);let U=G.runtime.hasPendingJob()?G.unwrapResult(await Xr(G,V,X)):V;if(U!==V)V.dispose();let D=G.getProp(U,"default"),z=G.typeof(D);if(z!=="function")return D.dispose(),U.dispose(),B.dispose(),{error:`Code must export default a function (tools). Got ${z}. Example: export default async (tools) => { /* ... */ }`,consoleLogs:K.logs};let L=G.callFunction(D,G.undefined,B);B.dispose(),D.dispose(),U.dispose();let w=G.unwrapResult(L),E=await Xr(G,w,X);w.dispose();let T=G.unwrapResult(E);if(G.runtime.hasPendingJob())Fz1(G);let C=G.dump(T);return T.dispose(),{returnValue:C,consoleLogs:K.logs}}catch(F){return console.log(F),{error:KO(F),consoleLogs:K.logs}}}catch(Z){var H=Z,$=1}finally{mo(W,H,$)}}async function Vz1({input:Y,code:Q,timeoutMs:X}){let W=[];try{const J=PB(W,await $z1({memoryLimitBytes:33554432,stackSizeBytes:524288}),0);const G=PB(W,J.newContext({interruptAfterMs:X}),0);const K=PB(W,Hz1(G),0);try{let F=G.evalCode(Q,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult(F),B=HO(G,Y);G.setProp(G.global,"input",B);let U=G.runtime.hasPendingJob()?G.unwrapResult(await Xr(G,V,X)):V;if(U!==V)V.dispose();let D=G.getProp(U,"default"),z=G.typeof(D);if(z!=="function")return D.dispose(),U.dispose(),B.dispose(),{error:`Code must export default a function (input). Got ${z}. Example: export default (input) => { return input.items.map(i => i.name); }`,consoleLogs:K.logs};let L=G.callFunction(D,G.undefined,B);B.dispose(),D.dispose(),U.dispose();let w=G.unwrapResult(L),E=await Xr(G,w,X);w.dispose();let T=G.unwrapResult(E);if(G.runtime.hasPendingJob())Fz1(G);let C=G.dump(T);return T.dispose(),{returnValue:C,consoleLogs:K.logs}}catch(F){return console.log(F),{error:KO(F),consoleLogs:K.logs}}}catch(Z){var H=Z,$=1}finally{mo(W,H,$)}}var _h6=(Y)=>new Promise((Q)=>setTimeout(Q,Y));var Vp0=k(()=>{$p0();Fp0()});var Jr=k(()=>{Vp0()});async function yh6(Y,Q){let X=Y.connections.map((K)=>K.connection_id),J=[];for(let K of X){let W=await Q.storage.connections.findById(K);if(W&&W.status==="active")J.push(W)}return J.map((K)=>{let W=Y.connections.find((Z)=>Z.connection_id===K.id);return{connection:K,selectedTools:W?.selected_tools??null,selectedResources:W?.selected_resources??null,selectedPrompts:W?.selected_prompts??null}})}async function qp0(Y,Q){return(await Q.storage.connections.list(Y)).filter((J)=>J.status==="active").map((J)=>({connection:J,selectedTools:null,selectedResources:null,selectedPrompts:null}))}async function fh6(Y,Q){let X=new Map;for(let B of Y)X.set(B.connection.id,B);let J=Y.map((B)=>B.connection),G=new Map,K=await Promise.allSettled(J.map(async(B)=>{try{let U=await Q.createMCPProxy(B);return{connection:B,proxy:U}}catch(U){return console.warn(`[code-execution] Failed to create proxy for connection ${B.id}:`,U),null}}));for(let B of K)if(B.status==="fulfilled"&&B.value)G.set(B.value.connection.id,B.value);let W=await Promise.allSettled(Array.from(G.entries()).map(async([B,U])=>{try{let z=(await U.proxy.listTools()).tools,L=X.get(B);if(L?.selectedTools&&L.selectedTools.length>0){let w=new Set(L.selectedTools);z=z.filter((E)=>w.has(E.name))}return{connectionId:B,connectionTitle:U.connection.title,tools:z}}catch(D){return console.error(`[code-execution] Failed to list tools for connection ${B}:`,D),null}})),Z=new Set,H=[],$=new Map;for(let B of W){if(B.status!=="fulfilled"||!B.value)continue;let{connectionId:U,connectionTitle:D,tools:z}=B.value;for(let L of z){if(Z.has(L.name))continue;Z.add(L.name),H.push({...L,_meta:{...L._meta,connectionId:U,connectionTitle:D}}),$.set(L.name,U)}}let F=async(B,U)=>{let D=$.get(B);if(!D)return{content:[{type:"text",text:`Tool not found: ${B}`}],isError:!0};let z=G.get(D);if(!z)return{content:[{type:"text",text:`Connection not found for tool: ${B}`}],isError:!0};return await z.proxy.callTool({name:B,arguments:U})},V=[];for(let[,B]of G)V.push(B.proxy.close().catch(()=>{}));return await Promise.all(V),{tools:H,callTool:F}}async function $P(Y){let Q=v0(Y),X;if(Y.connectionId){let J=await Y.storage.virtualMcps.findById(Y.connectionId,Y.organization?.id);if(J)X=await yh6(J,Y);else X=await qp0(Q.id,Y)}else X=await qp0(Q.id,Y);return fh6(X,Y)}function bh6(Y){return Y.toLowerCase().split(/[\s_\-./]+/).filter((Q)=>Q.length>=2)}function hh6(Y,Q){let X=0,J=Q.name.toLowerCase(),G=(Q.description??"").toLowerCase(),K=(Q._meta?.connectionTitle??"").toLowerCase();for(let W of Y){if(J===W)X+=10;else if(J.includes(W))X+=3;if(G.includes(W))X+=2;if(K.includes(W))X+=1}return X}function Gr(Y,Q,X){let J=bh6(Y);if(J.length===0)return Q.slice(0,X);return Q.map((G)=>({tool:G,score:hh6(J,G)})).filter((G)=>G.score>0).sort((G,K)=>K.score-G.score).slice(0,X).map((G)=>G.tool)}function Wr(Y,Q){let X=new Map(Q.map((G)=>[G.name,G]));return{tools:Y.map((G)=>X.get(G)).filter((G)=>G!==void 0).map((G)=>({name:G.name,description:G.description,connection:G._meta?.connectionTitle??"",inputSchema:G.inputSchema,outputSchema:G.outputSchema})),notFound:Y.filter((G)=>!X.has(G))}}async function Zr(Y,Q,X){let J=Object.fromEntries(Q.tools.map((G)=>[G.name,async(K)=>{let W=await Q.callTool(G.name,K??{});if(W.structuredContent&&typeof W.structuredContent==="object")return W.structuredContent;let Z=W.content;if(Z?.[0]?.type==="text"&&Z[0].text)try{return JSON.parse(Z[0].text)}catch{return Z[0].text}return W}]));return Xv({code:Y,tools:J,timeoutMs:X})}function Jv(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}]}}function GB(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}],isError:!0}}function KF(Y){let Q=new Set(xh6);return Y.filter((X)=>!Q.has(X.name))}var xh6;var $O=k(()=>{Jr();xh6=["CODE_EXECUTION_SEARCH_TOOLS","CODE_EXECUTION_DESCRIBE_TOOLS","CODE_EXECUTION_RUN_CODE"]});var qz1;var Bp0=k(()=>{F4();Qv();$O();qz1=s1({name:"CODE_EXECUTION_SEARCH_TOOLS",description:"Search for available tools by name or description. Returns tool names and brief descriptions without full schemas. Use this to discover tools before calling CODE_EXECUTION_DESCRIBE_TOOLS for detailed schemas.",annotations:{title:"Search Tools",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:Yp0,outputSchema:Qp0,handler:async(Y,Q)=>{D0(Q),v0(Q),await Q.access.check();let X=await $P(Q),J=Gr(Y.query,X.tools,Y.limit);return{query:Y.query,results:J.map((G)=>({name:G.name,description:G.description,connection:G._meta?.connectionTitle??""})),totalAvailable:X.tools.length}}})});var Bz1;var Up0=k(()=>{F4();Qv();$O();Bz1=s1({name:"CODE_EXECUTION_DESCRIBE_TOOLS",description:"Get detailed schemas for specific tools. Call after CODE_EXECUTION_SEARCH_TOOLS to get full input/output schemas before executing code.",annotations:{title:"Describe Tools",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:Xp0,outputSchema:Jp0,handler:async(Y,Q)=>{D0(Q),v0(Q),await Q.access.check();let X=await $P(Q);return Wr(Y.tools,X.tools)}})});var Uz1;var Dp0=k(()=>{F4();Qv();$O();Uz1=s1({name:"CODE_EXECUTION_RUN_CODE",description:'Run JavaScript code in a sandbox. Code must be an ES module that `export default`s an async function that receives (tools) as its first parameter. Use CODE_EXECUTION_DESCRIBE_TOOLS to understand the input/output schemas for a tool before calling it. Use `await tools.toolName(args)` or `await tools["tool-name"](args)` to call tools.',annotations:{title:"Run Code",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},inputSchema:Gp0,outputSchema:Wp0,handler:async(Y,Q)=>{D0(Q),v0(Q),await Q.access.check();let X=await $P(Q);return await Zr(Y.code,X,Y.timeoutMs)}})});var zp0=k(()=>{Bp0();Up0();Dp0();Qv()});var uh6,mh6,Dz1;var Op0=k(()=>{KY();c1();F4();kn();b$();uh6=q.object({data:PR.describe("Data for the new connection (id is auto-generated if not provided)")}),mh6=q.object({item:W5.describe("The created connection entity")}),Dz1=s1({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",annotations:{title:"Create Connection",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:uh6,outputSchema:mh6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=EY(Q);if(!J)throw Error("User ID required to create connection");let G={...Y.data,organization_id:X.id,created_by:J};if(G.connection_type==="VIRTUAL"){let $=DD(G.connection_url);if(!$)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let F=await Q.storage.virtualMcps.findById($);if(!F)throw Error(`Virtual MCP not found: ${$}`);if(F.organization_id!==X.id)throw Error("Virtual MCP does not belong to the current organization");G.connection_url=zD($)}let K=await DA({id:`pending-${Date.now()}`,title:G.title,connection_type:G.connection_type,connection_url:G.connection_url,connection_token:G.connection_token,connection_headers:G.connection_headers}).catch(()=>null),W=K?.tools?.length?K.tools:null,Z=K?.scopes?.length?K.scopes:null,H=await Q.storage.connections.create({...G,tools:W,configuration_scopes:Z});return await Q.eventBus.publish(X.id,IY.SELF(X.id),{type:"connection.created",data:H}),{item:H}}})});var lh6,dh6,Np0;var Lp0=k(()=>{c1();MG();lh6=bH.extend({avatar:q.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:q.string().describe("System prompt that defines the assistant's behavior"),virtual_mcp_id:q.string().describe("Virtual MCP ID to use for this assistant"),model:q.object({id:q.string().describe("Model ID"),connectionId:q.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),dh6=hH("assistant",lh6),Np0=[...dh6]});var Gv,HF,wp0,ph6,ch6,Ap0,nh6,ih6,ah6,rh6,oh6,sh6,Pp0,th6,eh6,Yx6,Qx6,Xx6,Jx6,Gx6,Wx6,Zx6,Kx6,MH9,Hx6,wH9,Mp0,$x6,Fx6,zz1,Wv;var Kr=k(()=>{c1();_z();MG();Gv=q.lazy(()=>q.union([q.null(),q.string(),q.number(),q.boolean(),q.record(q.string(),Gv),q.array(Gv)])),HF=q.record(q.string(),q.record(q.string(),Gv)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),wp0=q.object({type:q.literal("text"),text:q.string().describe("The text content"),providerOptions:HF}),ph6=q.object({type:q.literal("text"),text:q.string().describe("The text content"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),ch6=q.string().describe("File data as URL string"),Ap0=q.object({type:q.literal("file"),filename:q.string().optional().describe("Optional filename of the file"),data:ch6,mediaType:q.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:HF}),nh6=q.object({type:q.literal("file"),mediaType:q.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),data:q.string().describe("Generated file data as base64 encoded string")}),ih6=q.object({type:q.literal("reasoning"),text:q.string().describe("The reasoning text"),providerOptions:HF}),ah6=q.object({type:q.literal("reasoning"),text:q.string().describe("The reasoning text"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),rh6=q.object({type:q.literal("tool-call"),toolCallId:q.string().describe("ID of the tool call, used to match with tool result"),toolName:q.string().describe("Name of the tool being called"),input:q.string().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:q.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:HF}),oh6=q.object({type:q.literal("tool-call"),toolCallId:q.string().describe("ID of the tool call"),toolName:q.string().describe("Name of the tool being called"),input:q.string().describe("Stringified JSON object with the tool call arguments"),providerExecuted:q.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),sh6=q.union([q.object({type:q.literal("text"),value:q.string()}),q.object({type:q.literal("json"),value:Gv}),q.object({type:q.literal("error-text"),value:q.string()}),q.object({type:q.literal("error-json"),value:Gv}),q.object({type:q.literal("content"),value:q.array(q.union([q.object({type:q.literal("text"),text:q.string().describe("Text content")}),q.object({type:q.literal("media"),data:q.string().describe("Base-64 encoded media data"),mediaType:q.string().describe("IANA media type")})]))}),q.object({type:q.literal("execution-denied"),reason:q.string().optional()}),q.string().describe("Raw or JSON-serialized output (e.g. from AI SDK mapToolResultOutput)")]),Pp0=q.object({type:q.literal("tool-result"),toolCallId:q.string().describe("ID of the tool call that this result is associated with"),toolName:q.string().describe("Name of the tool that generated this result"),output:sh6.describe("Result of the tool call"),result:q.unknown().describe("Unknown result of the tool call"),providerOptions:HF}),th6=q.object({type:q.literal("tool-result"),toolCallId:q.string().describe("ID of the tool call that this result is associated with"),toolName:q.string().describe("Name of the tool that generated this result"),result:q.any().describe("Result of the tool call (JSON-serializable)"),isError:q.boolean().optional().describe("Whether the result is an error or error message"),providerExecuted:q.boolean().optional().describe("Whether the tool result was generated by the provider"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),eh6=q.union([q.object({type:q.literal("source"),sourceType:q.literal("url"),id:q.string().describe("The ID of the source"),url:q.string().describe("The URL of the source"),title:q.string().optional().describe("The title of the source"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),q.object({type:q.literal("source"),sourceType:q.literal("document"),id:q.string().describe("The ID of the source"),mediaType:q.string().describe("IANA media type of the document (e.g., application/pdf)"),title:q.string().describe("The title of the document"),filename:q.string().optional().describe("Optional filename of the document"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")})]),Yx6=q.object({role:q.literal("system"),content:q.string().describe("System message content"),providerOptions:HF}),Qx6=q.object({role:q.literal("user"),content:q.array(q.union([wp0,Ap0])).describe("User message content parts (text or file)"),providerOptions:HF}),Xx6=q.object({role:q.literal("assistant"),content:q.array(q.union([wp0,Ap0,ih6,rh6,Pp0])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:HF}),Jx6=q.object({role:q.literal("tool"),content:q.array(Pp0).describe("Tool message content (tool results)"),providerOptions:HF}),Gx6=q.union([Yx6,Qx6,Xx6,Jx6]),Wx6=q.array(Gx6).describe("A list of messages forming the prompt"),Zx6=q.object({prompt:Wx6.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:q.number().optional().describe("Maximum number of tokens to generate"),temperature:q.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:q.number().optional().describe("Nucleus sampling parameter"),topK:q.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:q.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:q.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:q.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:q.array(q.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:q.union([q.object({type:q.literal("text")}),q.object({type:q.literal("json"),schema:q.any().optional().describe("JSON schema that the generated output should conform to"),name:q.string().optional().describe("Name of output that should be generated"),description:q.string().optional().describe("Description of the output that should be generated")})]).optional().describe("Response format. The output can either be text or JSON. Default is text"),tools:q.array(q.any()).optional().describe("The tools that are available for the model"),toolChoice:q.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:q.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:q.any().optional().describe("Abort signal for cancelling the operation"),providerOptions:q.any().optional().describe("Additional provider-specific options")}),Kx6=q.object({content:q.array(q.union([ph6,nh6,ah6,oh6,th6,eh6])).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:q.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:q.looseObject({inputTokens:q.number().optional(),outputTokens:q.number().optional(),totalTokens:q.number().optional(),reasoningTokens:q.number().optional()}).describe("Usage information for the language model call"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata"),request:q.object({body:q.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:q.object({id:q.string().optional().describe("ID for the generated response"),timestamp:q.iso.datetime().optional().describe("Timestamp for the start of the generated response"),modelId:q.string().optional().describe("The ID of the response model that was used"),headers:q.record(q.string(),q.string()).optional().describe("Response headers"),body:q.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:q.array(q.any()).describe("Warnings for the call, e.g. unsupported settings")}),MH9=q.object({stream:q.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:q.object({body:q.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:q.object({headers:q.record(q.string(),q.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),Hx6=q.object({supportedUrls:q.record(q.string(),q.array(q.string())).describe("Supported URL patterns by media type for the provider")}),wH9=q.object({modelId:q.string().describe("The ID of the model"),logo:q.string().nullable(),description:q.string().nullable(),capabilities:q.array(q.string()),limits:q.object({contextWindow:q.number(),maxOutputTokens:q.number()}).nullable(),costs:q.object({input:q.number(),output:q.number()}).nullable(),provider:q.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),Mp0=q.object({modelId:q.string().describe("The ID of the model"),callOptions:Zx6}),$x6=bH.extend({logo:q.string().nullable(),description:q.string().nullable(),capabilities:q.array(q.string()),limits:q.object({contextWindow:q.number(),maxOutputTokens:q.number()}).nullable(),costs:q.object({input:q.number(),output:q.number()}).nullable(),provider:q.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),Fx6=hH("llm",$x6,{readOnly:!0}),zz1=[{name:"LLM_METADATA",inputSchema:q.object({modelId:q.string().describe("The ID of the model")}),outputSchema:Hx6},{name:"LLM_DO_STREAM",inputSchema:Mp0,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:Mp0,outputSchema:Kx6},...Fx6],Wv=yH(zz1)});function FP(){return!1}function Hr(Y,Q){return Y===IY.DEV_ASSETS(Q)}function VP(Y,Q){let X=D71(Q,Y),J=new Date().toISOString();return{id:X.id??IY.DEV_ASSETS(Y),title:X.title,description:X.description??null,icon:X.icon??null,app_name:X.app_name??null,app_id:X.app_id??null,organization_id:Y,created_by:"system",created_at:J,updated_at:J,connection_type:X.connection_type,connection_url:X.connection_url??null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:X.metadata??null,tools:Vx6,bindings:["OBJECT_STORAGE"],status:"active"}}var Vx6;var $r=k(()=>{ln();KY();c1();Vx6=uS.map((Y)=>({name:Y.name,description:`${Y.name} operation for local file storage`,inputSchema:q.toJSONSchema(Y.inputSchema),outputSchema:q.toJSONSchema(Y.outputSchema)}))});function Bx6(Y){let Q=[],X=0;while(X<Y.length){let J=Y[X];if(J==="%")Q.push(".*");else if(J==="_")Q.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))Q.push("\\"+J);else Q.push(J);X++}return Q.join("")}function WB(Y){return typeof Y==="string"||typeof Y==="number"}function Fr(Y,Q){if("conditions"in Q){let{operator:Z,conditions:H}=Q;switch(Z){case"and":return H.every(($)=>Fr(Y,$));case"or":return H.some(($)=>Fr(Y,$));case"not":return!H.every(($)=>Fr(Y,$));default:return!0}}let{field:X,operator:J,value:G}=Q,K=X.join("."),W=Oz1(Y,K);switch(J){case"eq":return W===G;case"gt":return WB(W)&&WB(G)&&W>G;case"gte":return WB(W)&&WB(G)&&W>=G;case"lt":return WB(W)&&WB(G)&&W<G;case"lte":return WB(W)&&WB(G)&&W<=G;case"in":return Array.isArray(G)&&G.includes(W);case"like":if(typeof W!=="string"||typeof G!=="string")return!1;if(G.length>100)return!1;let Z=Bx6(G);return new RegExp(`^${Z}$`,"i").test(W);case"contains":if(typeof W!=="string"||typeof G!=="string")return!1;return W.toLowerCase().includes(G.toLowerCase());default:return!0}}function Oz1(Y,Q){let X=Q.split("."),J=Y;for(let G of X){if(J==null||typeof J!=="object")return;J=J[G]}return J}function Ux6(Y,Q){return[...Y].sort((X,J)=>{for(let G of Q){let K=G.field.join("."),W=Oz1(X,K),Z=Oz1(J,K),H=0;if(W==null&&Z==null)continue;if(W==null)H=G.nulls==="first"?-1:1;else if(Z==null)H=G.nulls==="first"?1:-1;else if(typeof W==="string"&&typeof Z==="string")H=W.localeCompare(Z);else if(typeof W==="number"&&typeof Z==="number")H=W-Z;else H=String(W).localeCompare(String(Z));if(H!==0)return G.direction==="desc"?-H:H}return 0})}var qx6,Dx6,zx6,Nz1;var Ep0=k(()=>{lS();Lp0();MG();Kr();ln();KY();c1();F4();$r();b$();qx6={LLM:zz1,ASSISTANTS:Np0,OBJECT_STORAGE:uS};Dx6=uZ.extend({binding:q.union([q.object({}).passthrough(),q.string()]).optional(),include_virtual:q.boolean().optional().describe("Whether to include VIRTUAL connections in the results. Defaults to false.")}),zx6=x$(W5),Nz1=s1({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",annotations:{title:"List Connections",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:Dx6,outputSchema:zx6,handler:async(Y,Q)=>{await Q.access.check();let X=v0(Q),J=Y.binding?typeof Y.binding==="string"?(()=>{let B=qx6[Y.binding.toUpperCase()];if(!B)throw Error(`Unknown binding: ${Y.binding}`);return B})():Y.binding:void 0,G=J?xn(J):void 0,K=await Q.storage.connections.list(X.id,{includeVirtual:Y.include_virtual??!1});if(FP()){let B=K7(),U=IY.DEV_ASSETS(X.id);if(!K.some((D)=>D.id===U)){let D=VP(X.id,B);K.unshift(D)}}let W=G?await Promise.all(K.map(async(B)=>{if(!B.tools||B.tools.length===0)return null;return G.isImplementedBy(B.tools.map((D)=>({name:D.name,inputSchema:D.inputSchema,outputSchema:D.outputSchema})))?B:null})).then((B)=>B.filter((U)=>U!==null)):K;if(Y.where)W=W.filter((B)=>Fr(B,Y.where));if(Y.orderBy&&Y.orderBy.length>0)W=Ux6(W,Y.orderBy);let Z=W.length,H=Y.offset??0,$=Y.limit??100,F=W.slice(H,H+$),V=H+$<Z;return{items:F,totalCount:Z,hasMore:V}}})});var Ox6,Lz1;var Tp0=k(()=>{MG();F4();$r();b$();Ox6=TS(W5),Lz1=s1({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",annotations:{title:"Get Connection",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:ES,outputSchema:Ox6,handler:async(Y,Q)=>{let X=v0(Q);if(await Q.access.check(),FP()&&Hr(Y.id,X.id))return{item:VP(X.id,K7())};let J=await Q.storage.connections.findById(Y.id);if(!J||J.organization_id!==X.id)return{item:null};return{item:J}}})});var Vr=(Y,Q)=>{if(Q===null||Q===void 0)return;let X=Y.replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),J=Q;for(let G of X){if(J===null||J===void 0||typeof J!=="object")return;J=J[G]}return J};function Cp0(Y){let Q=Y.split("::");if(Q.length!==2||!Q[0]||!Q[1])throw Error(`Invalid scope format: ${Y}. Expected format: "KEY::SCOPE"`);return Q}function Nx6(Y){let Q=Y.split("::");if(Q.length!==2||!Q[0]||!Q[1])return null;return Q}function Lx6(Y){if(typeof Y==="object"&&Y!==null&&"value"in Y){let Q=Y.value;if(typeof Q==="string")return Q}return null}function Mz1(Y,Q){let X={};if(!Y||!Q)return X;for(let J of Q){if(J==="*"){X["*"]=["*"];continue}let G=Nx6(J);if(!G)continue;let[K,W]=G,Z=Vr(K,Y),H=Lx6(Z);if(H){if(!X[H])X[H]=[];X[H].push(W)}}return X}function Rp0(Y,Q){let X=Mz1(Y,Q);return new Set(Object.keys(X).filter((J)=>J!=="*"))}var wz1=()=>{};import{randomBytes as Mx6}from"crypto";function Ip0(){if(Zv)return Zv;let Y=process.env.MESH_JWT_SECRET??p9.jwt?.secret??process.env.BETTER_AUTH_SECRET;if(Y)Zv=new TextEncoder().encode(Y);else console.warn("MESH_JWT_SECRET not set - generating random secret (not persistent)"),Zv=new Uint8Array(Mx6(32));return Zv}async function jp0(Y,Q="5m"){let X=Ip0();return await new BG(Y).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(Q).sign(X)}async function Sp0(Y){try{let Q=Ip0(),{payload:X}=await JY(Y,Q);return X}catch{return}}var Zv=null;var Az1=k(()=>{UG();Kv()});async function kp0(Y){if(!Y.refreshToken)return{success:!1,error:"No refresh token available"};if(!Y.tokenEndpoint)return{success:!1,error:"No token endpoint available"};if(!Y.clientId)return{success:!1,error:"No client ID available"};try{let Q=new URLSearchParams({grant_type:"refresh_token",refresh_token:Y.refreshToken,client_id:Y.clientId});if(Y.clientSecret)Q.set("client_secret",Y.clientSecret);if(Y.scope)Q.set("scope",Y.scope);let X=await fetch(Y.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Q.toString()});if(!X.ok){let G=await X.text();console.error(`[TokenRefresh] Failed to refresh token: ${X.status}`,G);try{let K=JSON.parse(G);return{success:!1,error:K.error_description||K.error||`Token refresh failed: ${X.status}`}}catch{return{success:!1,error:`Token refresh failed: ${X.status}`}}}let J=await X.json();return{success:!0,accessToken:J.access_token,refreshToken:J.refresh_token||Y.refreshToken,expiresIn:J.expires_in,scope:J.scope}}catch(Q){return console.error("[TokenRefresh] Error refreshing token:",Q),{success:!1,error:Q instanceof Error?Q.message:"Token refresh failed"}}}class $F{db;vault;constructor(Y,Q){this.db=Y;this.vault=Q}async get(Y){let Q=await this.db.selectFrom("downstream_tokens").selectAll().where("connectionId","=",Y).executeTakeFirst();if(!Q)return null;return this.decryptToken(Q)}async upsert(Y){let Q=new Date().toISOString(),X=await this.vault.encrypt(Y.accessToken),J=Y.refreshToken?await this.vault.encrypt(Y.refreshToken):null,G=Y.clientSecret?await this.vault.encrypt(Y.clientSecret):null;return await this.db.transaction().execute(async(K)=>{let W=await K.selectFrom("downstream_tokens").select(["id","createdAt"]).where("connectionId","=",Y.connectionId).executeTakeFirst();if(W)return await K.updateTable("downstream_tokens").set({accessToken:X,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,updatedAt:Q}).where("id","=",W.id).execute(),{id:W.id,connectionId:Y.connectionId,accessToken:Y.accessToken,refreshToken:Y.refreshToken,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:W.createdAt,updatedAt:Q,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint};let Z=X9("dtok");return await K.insertInto("downstream_tokens").values({id:Z,connectionId:Y.connectionId,accessToken:X,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,createdAt:Q,updatedAt:Q}).execute(),{id:Z,connectionId:Y.connectionId,accessToken:Y.accessToken,refreshToken:Y.refreshToken,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:Q,updatedAt:Q,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint}})}async delete(Y){await this.db.deleteFrom("downstream_tokens").where("connectionId","=",Y).execute()}isExpired(Y,Q=0){if(!Y.expiresAt)return!1;let J=(Y.expiresAt instanceof Date?Y.expiresAt:new Date(Y.expiresAt)).getTime();if(Number.isNaN(J))return!0;return J-Q<Date.now()}async decryptToken(Y){let Q=await this.vault.decrypt(Y.accessToken),X=Y.refreshToken?await this.vault.decrypt(Y.refreshToken):null,J=Y.clientSecret?await this.vault.decrypt(Y.clientSecret):null;return{id:Y.id,connectionId:Y.connectionId,accessToken:Q,refreshToken:X,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:Y.createdAt,updatedAt:Y.updatedAt,clientId:Y.clientId,clientSecret:J,tokenEndpoint:Y.tokenEndpoint}}}var qr=k(()=>{$7()});async function Hv(Y,Q,X){let J=Y.id,G=Mz1(Y.configuration_state,Y.configuration_scopes),K=Q.auth.user?.id??Q.auth.apiKey?.userId??(X?Y.created_by:void 0),[W,Z]=K?await jp0({sub:K,user:{id:K},metadata:{state:Y.configuration_state??void 0,meshUrl:Q.baseUrl,connectionId:J,organizationId:Q.organization?.id},permissions:G}).then((U)=>[U,null]).catch((U)=>[null,U]):[null,Error("User ID required to issue configuration token")];if(Z)console.error("Failed to issue configuration token:",W);let H=Q.auth.user?.connectionId,$={...H?{"x-caller-id":H}:{},...Q.metadata.wellKnownForwardableHeaders??{},"x-request-id":Q.metadata.requestId},F=null,V=new $F(Q.db,Q.vault),B=await V.get(J);if(B){let U=!!B.refreshToken&&!!B.tokenEndpoint;if(V.isExpired(B,U?300000:0))if(U){console.log(`[Proxy] Token expired for ${J}, attempting refresh`);let z=await kp0(B);if(z.success&&z.accessToken)await V.upsert({connectionId:J,accessToken:z.accessToken,refreshToken:z.refreshToken??B.refreshToken,scope:z.scope??B.scope,expiresAt:z.expiresIn?new Date(Date.now()+z.expiresIn*1000):null,clientId:B.clientId,clientSecret:B.clientSecret,tokenEndpoint:B.tokenEndpoint}),F=z.accessToken,console.log(`[Proxy] Token refreshed for ${J}`);else await V.delete(J),console.error(`[Proxy] Token refresh failed for ${J}: ${z.error}`)}else await V.delete(J),console.log(`[Proxy] Token expired without refresh capability for ${J}`);else F=B.accessToken}if(!F&&Y.connection_token)F=Y.connection_token;if(F)$.Authorization=`Bearer ${F}`;if(W)$["x-mesh-token"]=W;return $}var Pz1=k(()=>{wz1();Az1();qr()});function Br(){let Y=new Map;function Q(J,G){let K=Y.get(G);if(K)return console.log(`[ClientPool] Reusing cached client for ${G}`),K;console.log(`[ClientPool] Creating new client for ${G}`);let W=new G5({name:`outbound-client-${G}`,version:"1.0.0"},{capabilities:{tasks:{list:{},cancel:{},requests:{tool:{call:{}}}}}});W.onclose=()=>{Y.delete(G)};let Z=W.connect(J,{timeout:30000}).then(()=>W).catch((H)=>{throw Y.delete(G),H});return Y.set(G,Z),Z}return Object.assign(Q,{[Symbol.asyncDispose]:async()=>{let J=[];for(let[G,K]of Y)J.push(K.then((W)=>W.close()).catch((W)=>console.error(`[ClientPool] Error closing client ${G}:`,W)));await Promise.all(J),Y.clear()}})}var Ez1=k(()=>{qD()});function vp0(Y){let Q=new wS({command:Y.command,args:Y.args,env:Y.env,cwd:Y.cwd,stderr:"pipe"}),X=Y.name||Y.id,J="\x1B[2m",G="\x1B[0m";return Q.stderr?.on("data",(K)=>{let W=K.toString().trimEnd();if(W)console.error(`${W} \x1B[2m[${X}]\x1B[0m`)}),Q}var _p0=k(()=>{yV1()});class $v{innerTransport;constructor(Y){this.innerTransport=Y}async start(){return this.innerTransport.onmessage=(Y)=>{this.handleIncomingMessage(Y)},this.innerTransport.onerror=(Y)=>{this.onerror?.(Y)},this.innerTransport.onclose=()=>{this.onclose?.()},this.innerTransport.start()}async send(Y){return this.handleOutgoingMessage(Y)}async close(){return this.innerTransport.close()}async handleOutgoingMessage(Y){return this.innerTransport.send(Y)}handleIncomingMessage(Y){this.onmessage?.(Y)}isRequest(Y){return"method"in Y&&Y.method!==void 0}isResponse(Y){return"result"in Y||"error"in Y&&!("method"in Y)}onmessage;onerror;onclose}function Fv(Y,...Q){return Q.reduce((X,J)=>J(X),Y)}var yp0="mcp.mesh";var fp0,Tz1,FF;var Vv=k(()=>{fp0=class fp0 extends Error{constructor(Y){super(Y);this.name="UnauthorizedError"}};Tz1=class Tz1 extends Error{constructor(Y){super(Y);this.name="ForbiddenError"}};FF=class FF{userId;toolName;boundAuth;role;connectionId;getToolMeta;_granted=!1;constructor(Y,Q,X,J,G,K="self",W){this.userId=Q;this.toolName=X;this.boundAuth=J;this.role=G;this.connectionId=K;this.getToolMeta=W}[Symbol.dispose](){this._granted=!1}setToolName(Y){this.toolName=Y}grant(){return this._granted=!0,{[Symbol.dispose]:()=>{this._granted=!1}}}async check(...Y){if(this._granted)return;if(this.toolName?.startsWith("MESH_PUBLIC_")){this.grant();return}if(!this.userId&&!this.boundAuth){if(this.getToolMeta&&await this.isToolPublic()){this.grant();return}throw new fp0("Authentication required. Please provide a valid OAuth token or API key.")}let Q=Y.length>0?Y:this.toolName?[this.toolName]:[];if(Q.length===0)throw new Tz1("No resources specified for access check");for(let X of Q)if(await this.checkResource(X)){this.grant();return}throw new Tz1(`Access denied to: ${Q.join(", ")}`)}async checkResource(Y){if(!this.userId&&!this.boundAuth)return!1;if(this.role==="admin"||this.role==="owner")return!0;if(!this.boundAuth)return!1;let Q={};if(this.connectionId)Q[this.connectionId]=[Y];return this.boundAuth.hasPermission(Q)}async isToolPublic(){if(this.toolName?.startsWith("MESH_PUBLIC_"))return!0;if(!this.getToolMeta)return!1;try{let Y=await this.getToolMeta();if(!Y)return!1;let X=Y[yp0]?.public_tool;return X===!0||X==="true"}catch{return!1}}granted(){return this._granted}}});var wx6="mcp.mesh",qP;var bp0=k(()=>{Vv();qP=class qP extends $v{options;cachedToolsMap=null;constructor(Y,Q){super(Y);this.options=Q;if(Q.connection.tools)this.cachedToolsMap=new Map(Q.connection.tools.map((X)=>[X.name,X]))}async handleOutgoingMessage(Y){if(!this.isRequest(Y))return this.innerTransport.send(Y);let Q=Y;if(Q.method==="tools/call")await this.authorizeToolCall(Q),this.stripMetaFromArguments(Q);return this.innerTransport.send(Y)}async authorizeToolCall(Y){if(this.options.superUser)return;let X=Y.params.name,{ctx:J,connection:G}=this.options;if(this.isPublicTool(X))return;if(!J.auth.user?.id&&!J.auth.apiKey?.id)throw Error("Authentication required. Please provide a valid OAuth token or API key.");let K=async()=>{return this.cachedToolsMap?.get(X)?._meta};await new FF(J.authInstance,J.auth.user?.id??J.auth.apiKey?.userId,X,J.boundAuth,J.auth.user?.role,G.id,K).check(X)}isPublicTool(Y){if(Y.startsWith("MESH_PUBLIC_"))return!0;if(!this.cachedToolsMap)return!1;let Q=this.cachedToolsMap.get(Y);if(!Q?._meta)return!1;return Q._meta[wx6]?.public_tool===!0}stripMetaFromArguments(Y){let Q=Y.params;if(Q.arguments&&"_meta"in Q.arguments){let{_meta:X,...J}=Q.arguments;Q.arguments=J}}}});function xp0(Y){if(!Y.isError)return;let Q=Y.content;if(!Array.isArray(Q))return;for(let X of Q)if(X&&typeof X==="object"&&"type"in X&&X.type==="text"&&"text"in X&&typeof X.text==="string")return X.text;return}function Rz1(Y){if(!Y)return;let Q=Y._meta;if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let X=Q.properties;if(!X||typeof X!=="object"||Array.isArray(X))return;let J={};for(let[G,K]of Object.entries(X))if(typeof K==="string")J[G]=K;return Object.keys(J).length>0?J:void 0}function Iz1(Y,Q){if(!Y&&!Q)return;if(!Y)return Q;if(!Q)return Y;return{...Q,...Y}}function jz1(Y){if(Y&&typeof Y==="object"&&!Array.isArray(Y)){let Q=Y,X=Q.structuredContent;if(X&&typeof X==="object"&&!Array.isArray(X))return X;return Q}return{value:Y}}async function Ax6(Y,Q){let X=Y.body;if(!X)return{text:"",truncated:!1};let J=X.getReader(),G=new TextDecoder,K=!1,W=0,Z=[];try{while(!0){let{value:H,done:$}=await J.read();if($)break;if(H){if(W+=H.byteLength,W>Q){K=!0;let F=Q-(W-H.byteLength);if(F>0)Z.push(G.decode(H.slice(0,F),{stream:!0}));break}Z.push(G.decode(H,{stream:!0}))}}}finally{J.releaseLock()}return Z.push(G.decode()),{text:Z.join(""),truncated:K}}function Px6(Y){if(!Y)return;let Q=Y.trimEnd().split(`
|
|
1323
1323
|
`);for(let X=Q.length-1;X>=0&&X>=Q.length-5;X--){let J=Q[X]?.trim();if(!J)continue;try{let G=JSON.parse(J);if(G&&typeof G==="object"&&G.type==="finish"){let K={};if(G.usage)K.usage=G.usage;if(G.providerMetadata)K.providerMetadata=G.providerMetadata;if(G.finishReason)K.finishReason=G.finishReason;return Object.keys(K).length>0?K:void 0}}catch{}}return}async function Cz1(Y){let{ctx:Q,enabled:X}=Y,J=Y.organizationId??Q.organization?.id;if(!X||!J)return;if(o3(Y.connectionId))return;let G=Rz1(Y.request.params.arguments),K=Iz1(Q.metadata.properties,G),W=Q.auth.user?.id||Q.auth.apiKey?.userId;if(W)try{let Z=await Q.storage.tags.getUserTagsInOrg(W,J);if(Z.length>0){let H=Z.map(($)=>$.name).join(",");K={...K,user_tags:H}}}catch{}await Q.storage.monitoring.log({organizationId:J,connectionId:Y.connectionId,connectionTitle:Y.connectionTitle,toolName:Y.request.params.name,input:Y.request.params.arguments??{},output:Y.output,isError:Y.isError,errorMessage:Y.errorMessage,durationMs:Y.durationMs,timestamp:new Date,userId:Q.auth.user?.id||Q.auth.apiKey?.userId||null,requestId:Q.metadata.requestId,userAgent:Q.metadata.userAgent,virtualMcpId:Y.virtualMcpId,properties:K})}function gp0(Y){let{ctx:Q,enabled:X,connectionId:J,connectionTitle:G,virtualMcpId:K}=Y;return async(W,Z)=>{let H=Date.now();try{let $=await Z(),F=Q.organization?.id;if(X&&F){let V=$.clone();(async()=>{try{let{text:B,truncated:U}=await Ax6(V,hp0),D=Date.now()-H,z=V.headers.get("content-type")??"",L=B;if(z.includes("application/json"))try{L=B.length?JSON.parse(B):null}catch{L=B}let w=$.status>=400,E=w&&L&&typeof L==="object"&&"error"in L?L.error:void 0,T=typeof E==="string"&&E?E:w&&typeof L==="string"&&L.trim()?L.slice(0,500):w?`HTTP ${$.status} ${$.statusText}`.trim():U?`Response body truncated to ${hp0} bytes`:void 0,C=jz1(L),P=Px6(B);if(P)Object.assign(C,P);await Cz1({ctx:Q,enabled:X,organizationId:F,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:C,isError:w,errorMessage:T,durationMs:D})}catch(B){let U=Date.now()-H;await Cz1({ctx:Q,enabled:X,organizationId:F,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:{},isError:!0,errorMessage:`Failed to read streamable response body: ${B.message}`,durationMs:U})}})()}return $}catch($){let F=$,V=Date.now()-H;throw await Cz1({ctx:Q,enabled:X,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:{},isError:!0,errorMessage:F.message,durationMs:V}),$}}}var hp0=262144;var Sz1=k(()=>{KY()});var BP;var up0=k(()=>{QS();Sz1();BP=class BP extends $v{options;inflightRequests=new Map;constructor(Y,Q){super(Y);this.options=Q}async handleOutgoingMessage(Y){if(this.isRequest(Y)){let Q=Y;this.onRequestStart(Q)}return this.innerTransport.send(Y)}handleIncomingMessage(Y){if(this.isResponse(Y)){let Q=Y;this.onResponseEnd(Q)}this.onmessage?.(Y)}onRequestStart(Y){let{ctx:Q,connectionId:X}=this.options,J,G;if(Y.method==="tools/call"&&Y.params){let W=Y.params;J=W.name,G=W.arguments}let K;if(Y.method==="tools/call"&&J)K=Q.tracer.startSpan("mcp.proxy.callTool",{attributes:{"connection.id":X,"tool.name":J,"request.id":Q.metadata.requestId,"jsonrpc.id":Y.id,"jsonrpc.method":Y.method}});if(Y.id!==null&&Y.id!==void 0)this.inflightRequests.set(Y.id,{startTime:Date.now(),method:Y.method,toolName:J,toolArguments:G,span:K})}onResponseEnd(Y){if(Y.id===null||Y.id===void 0)return;let Q=this.inflightRequests.get(Y.id);if(!Q)return;let{ctx:X,connectionId:J}=this.options,{startTime:G,method:K,toolName:W,toolArguments:Z,span:H}=Q,$=Date.now()-G;if(this.inflightRequests.delete(Y.id),K!=="tools/call"||!W)return;let F="error"in Y,V=F?Y.error:Y.result,B=F?{content:[{type:"text",text:Y.error?.message||"Unknown error"}],isError:!0}:V;if(X.meter.createHistogram("connection.proxy.duration").record($,{"connection.id":J,"tool.name":W,status:F?"error":"success"}),F)X.meter.createCounter("connection.proxy.errors").add(1,{"connection.id":J,"tool.name":W,error:Y.error?.message});else X.meter.createCounter("connection.proxy.requests").add(1,{"connection.id":J,"tool.name":W,status:"success"});if(H){if(F&&Y.error)H.recordException(Error(Y.error.message)),H.setAttributes({error:!0,"error.code":Y.error.code,"error.message":Y.error.message});H.end()}this.logToDatabase({toolName:W,toolArguments:Z,result:B,duration:$,isError:Boolean(F)})}async logToDatabase(Y){let{ctx:Q,connectionId:X,connectionTitle:J,virtualMcpId:G}=this.options,{toolName:K,toolArguments:W,result:Z,duration:H,isError:$}=Y;if(!Fn().enabled)return;let V=Q.organization?.id;if(!V)return;let B=xp0(Z),U=jz1(Z),D=Rz1(W),z=Iz1(Q.metadata.properties,D);try{await Q.storage.monitoring.log({organizationId:V,connectionId:X,connectionTitle:J,toolName:K,input:W??{},output:U,isError:$,errorMessage:B,durationMs:H,timestamp:new Date,userId:Q.auth.user?.id||Q.auth.apiKey?.userId||null,requestId:Q.metadata.requestId,userAgent:Q.metadata.userAgent,virtualMcpId:G,properties:z})}catch(L){console.error("[MonitoringTransport] Failed to log to database:",L)}}async close(){for(let Y of this.inflightRequests.values())if(Y.span)Y.span.setAttributes({"transport.closed":!0}),Y.span.end();return this.inflightRequests.clear(),super.close()}}});var mp0=k(()=>{bp0();up0()});async function lp0(Y,Q,X=!1){let J=Y.id,G=Q.connectionId&&Q.connectionId!==J?Q.connectionId:void 0;switch(Y.connection_type){case"STDIO":{if(process.env.UNSAFE_ALLOW_STDIO_TRANSPORT!=="true")throw Error("STDIO connections are disabled in production. Set UNSAFE_ALLOW_STDIO_TRANSPORT=true to enable.");let K=Y.connection_headers;if(!aK(K))throw Error("STDIO connection missing parameters");let W=vp0({id:J,name:Y.title,command:K.command,args:K.args,env:K.envVars,cwd:K.cwd});return W=Fv(W,(Z)=>new qP(Z,{ctx:Q,connection:Y,superUser:X}),(Z)=>new BP(Z,{ctx:Q,connectionId:J,connectionTitle:Y.title,virtualMcpId:G})),Ex6(W,J)}case"HTTP":case"Websocket":{if(!Y.connection_url)throw Error(`${Y.connection_type} connection missing URL`);let K=await Hv(Y,Q,X),W=Y.connection_headers;if(W&&"headers"in W)Object.assign(K,W.headers);let Z=new bV(new URL(Y.connection_url),{requestInit:{headers:K}});return Z=Fv(Z,(H)=>new qP(H,{ctx:Q,connection:Y,superUser:X}),(H)=>new BP(H,{ctx:Q,connectionId:J,connectionTitle:Y.title,virtualMcpId:G})),Q.getOrCreateClient(Z,J)}case"SSE":{if(!Y.connection_url)throw Error("SSE connection missing URL");let K=await Hv(Y,Q,X),W=Y.connection_headers;if(W&&"headers"in W)Object.assign(K,W.headers);let Z=new Sz(new URL(Y.connection_url),{requestInit:{headers:K}});return Z=Fv(Z,(H)=>new qP(H,{ctx:Q,connection:Y,superUser:X}),(H)=>new BP(H,{ctx:Q,connectionId:J,connectionTitle:Y.title,virtualMcpId:G})),Q.getOrCreateClient(Z,J)}default:throw Error(`Unknown connection type: ${Y.connection_type}`)}}var Ex6;var dp0=k(()=>{b$();In();AR();Pz1();Ez1();_p0();mp0();Ex6=Br()});function ZB(Y){if(!Y?._meta)return!1;return typeof Y._meta["mcp.mesh"]?.["tool.fn"]==="string"}function np0(Y){return Y._meta["mcp.mesh"]["tool.fn"]}function qv(Y,Q,X,J){return{id:Y,name:Q.name,description:Q.description,inputSchema:Q.inputSchema,outputSchema:Q.outputSchema,annotations:Q.annotations,code:Q._meta["mcp.mesh"]["tool.fn"],connection_dependencies:Q._meta.connectionDependencies??[],created_at:X,updated_at:J}}var kz1,x39,iH,pp0,cp0;var VF=k(()=>{c1();kz1=q.object({title:q.string().optional(),readOnlyHint:q.boolean().optional(),destructiveHint:q.boolean().optional(),idempotentHint:q.boolean().optional(),openWorldHint:q.boolean().optional()}),x39=q.object({"tool.fn":q.string().describe("JavaScript ES module code that exports a default async function")}),iH=q.object({id:q.string().describe("Unique identifier for the virtual tool (auto-generated)"),name:q.string().min(1).max(255).describe("Tool name (must be unique within the Virtual MCP)"),description:q.string().optional().describe("Human-readable description of what the tool does"),inputSchema:q.record(q.string(),q.unknown()).describe("JSON Schema defining the tool's input parameters"),outputSchema:q.record(q.string(),q.unknown()).optional().describe("JSON Schema defining the tool's output (optional)"),annotations:kz1.optional().describe("MCP tool annotations"),code:q.string().describe("JavaScript ES module code. Must export default an async function: export default async (tools, args) => { ... }"),connection_dependencies:q.array(q.string()).describe("Connection IDs that this tool depends on (specified by the creator)"),created_at:q.string().describe("When the virtual tool was created"),updated_at:q.string().describe("When the virtual tool was last updated")}),pp0=q.object({name:q.string().min(1).max(255).describe("Tool name (must be unique within the Virtual MCP)"),description:q.string().optional().describe("Human-readable description"),inputSchema:q.record(q.string(),q.unknown()).describe("JSON Schema defining the tool's input parameters"),outputSchema:q.record(q.string(),q.unknown()).optional().describe("JSON Schema for output"),annotations:kz1.optional().describe("MCP tool annotations"),code:q.string().describe("JavaScript ES module code. Must export default an async function: export default async (tools, args) => { ... }"),connection_dependencies:q.array(q.string()).optional().describe("Connection IDs that this tool depends on. Creates indirect aggregations to prevent deletion of referenced connections.")}),cp0=q.object({name:q.string().min(1).max(255).optional().describe("New tool name"),description:q.string().nullable().optional().describe("New description (null to clear)"),inputSchema:q.record(q.string(),q.unknown()).optional().describe("New input schema"),outputSchema:q.record(q.string(),q.unknown()).nullable().optional().describe("New output schema (null to clear)"),annotations:kz1.nullable().optional().describe("New annotations (null to clear)"),code:q.string().optional().describe("New JavaScript code"),connection_dependencies:q.array(q.string()).optional().describe("Connection IDs that this tool depends on. Replaces existing dependencies if provided.")})});function FO(Y){return(Q)=>{if(Q instanceof u0&&Q.code===o0.MethodNotFound)return Y;throw Q}}var vz1=k(()=>{vQ()});class ip0{factory;promise=null;constructor(Y){this.factory=Y}getOrCreatePromise(){if(!this.promise)this.promise=this.factory();return this.promise}then(Y,Q){return this.getOrCreatePromise().then(Y,Q)}catch(Y){return this.getOrCreatePromise().catch(Y)}finally(Y){return this.getOrCreatePromise().finally(Y)}}function UP(Y){return new ip0(Y)}function Tx6(Y,Q,X){let J=new G5({name:`lazy-${Y.id}`,version:"1.0.0"},{capabilities:{}}),G=null;function K(){if(!G)G=_5(Y,Q,X).then((H)=>{if(Y.connection_type==="HTTP"||Y.connection_type==="SSE"||Y.connection_type==="Websocket")return VO(H,Y.id,Y,Q,{superUser:X});return H});return G}if(Y.connection_type!=="VIRTUAL"&&Array.isArray(Y.tools)&&Y.tools.length>0)J.listTools=async()=>({tools:Y.tools.map((H)=>({name:H.name,description:H.description,inputSchema:H.inputSchema,outputSchema:H.outputSchema,annotations:H.annotations,_meta:H._meta}))});else J.listTools=async()=>{return(await K()).listTools()};J.callTool=async(H,$,F)=>{return(await K()).callTool(H,$,F)},J.listResources=async()=>{return(await K()).listResources()},J.listPrompts=async()=>{return(await K()).listPrompts()},J.getPrompt=async(H,$)=>{return(await K()).getPrompt(H,$)},J.readResource=async(H,$)=>{return(await K()).readResource(H,$)},J.callStreamableTool=async(H,$)=>{let F=await K();if("callStreamableTool"in F&&typeof F.callStreamableTool==="function")return F.callStreamableTool(H,$);let V=await F.callTool({name:H,arguments:$});return new Response(JSON.stringify(V),{headers:{"Content-Type":"application/json"}})};let Z=J.close.bind(J);return J.close=async()=>{if(G){let H=await G.catch(()=>null);if(H)await H.close().catch(()=>{})}await Z()},J}function Cx6(Y,Q,X=!1){let J=new Map;for(let G of Y)J.set(G.id,Tx6(G,Q,X));return J}async function ap0(Y){let Q=[];for(let[,X]of Y)Q.push(X.close().catch(()=>{}));await Promise.all(Q)}var DP;var _z1=k(()=>{zP();vz1();qD();Jr();VF();DP=class DP extends G5{options;ctx;_cachedTools;_cachedResources;_cachedPrompts;_clients;_connections;_selectionMap;constructor(Y,Q){super({name:"virtual-mcp-passthrough",version:"1.0.0"},{capabilities:{tasks:{list:{},cancel:{},requests:{tool:{call:{}}}}}});this.options=Y;this.ctx=Q;this._selectionMap=new Map;for(let X of Y.virtualMcp.connections)this._selectionMap.set(X.connection_id,X);this._connections=new Map;for(let X of Y.connections)this._connections.set(X.id,X);this._clients=Cx6(this.options.connections,this.ctx,this.options.superUser),this._cachedTools=UP(()=>this.loadToolsCache()),this._cachedResources=UP(()=>this.loadCache("resources")),this._cachedPrompts=UP(()=>this.loadCache("prompts"))}async loadToolsCache(){let Y=this._clients,Q=await Promise.all(Array.from(Y.entries()).map(async([W,Z])=>{try{let H=await Z.listTools().then((F)=>F.tools),$=this._selectionMap.get(W);if($?.selected_tools?.length){let F=new Set($.selected_tools);H=H.filter((V)=>F.has(V.name))}return{connectionId:W,data:H}}catch(H){return console.error(`[PassthroughClient] Failed to load tools for connection ${W}:`,H),null}})),X=[],J=new Map,G=new Map,K=this.options.virtualTools??[];for(let W of K){if(J.has(W.name))continue;let Z={name:W.name,description:W.description,inputSchema:W.inputSchema,outputSchema:W.outputSchema,annotations:W.annotations,_meta:{connectionId:this.options.virtualMcp.id??"__VIRTUAL__",connectionTitle:this.options.virtualMcp.title}};X.push(Z),J.set(W.name,"__VIRTUAL__"),G.set(W.name,W)}for(let W of Q){if(!W)continue;let{connectionId:Z,data:H}=W,F=this._connections.get(Z)?.title??"";for(let V of H){let B=V.name;if(J.has(B))continue;let U={...V,_meta:{connectionId:Z,connectionTitle:F,...V?._meta}};X.push(U),J.set(B,Z)}}return{data:X,mappings:J,virtualTools:G}}async loadCache(Y){let Q=this._clients,X=await Promise.all(Array.from(Q.entries()).map(async([K,W])=>{try{let Z=Y==="resources"?await W.listResources().catch(FO({resources:[]})).then((F)=>F.resources):await W.listPrompts().catch(FO({prompts:[]})).then((F)=>F.prompts),H=this._selectionMap.get(K),$=Y==="resources"?"selected_resources":"selected_prompts";if(H?.[$]?.length){let F=new Set(H[$]);return{connectionId:K,data:Z.filter((V)=>F.has(V.name))}}return{connectionId:K,data:Z}}catch(Z){return console.error(`[PassthroughClient] Failed to load cache for connection ${K}:`,Z),null}})),J=[],G=new Map;for(let K of X){if(!K)continue;let{connectionId:W,data:Z}=K,$=this._connections.get(W)?.title??"";for(let F of Z){let V=F.name??F.uri;if(G.has(V))continue;let B={...F,_meta:{connectionId:W,connectionTitle:$,...F?._meta}};J.push(B),G.set(V,W)}}return{data:J,mappings:G}}async listTools(){return{tools:(await this._cachedTools).data}}async callTool(Y){let Q=await this._cachedTools,X=this._clients,J=Q.mappings.get(Y.name);if(!J)return{content:[{type:"text",text:`Tool not found: ${Y.name}`}],isError:!0};if(J==="__VIRTUAL__")return this.executeVirtualTool(Y.name,Y.arguments??{},Q,X);let G=X.get(J);if(!G)return{content:[{type:"text",text:`Connection not found for tool: ${Y.name}`}],isError:!0};return await G.callTool({name:Y.name,arguments:Y.arguments??{}})}async executeVirtualTool(Y,Q,X,J){let G=X.virtualTools.get(Y);if(!G)return{content:[{type:"text",text:`Virtual tool not found: ${Y}`}],isError:!0};let K=np0(G),W={};for(let[Z,H]of X.mappings){if(H==="__VIRTUAL__")continue;let $=J.get(H);if(!$)continue;W[Z]=async(F)=>{let V=await $.callTool({name:Z,arguments:F});if(V.structuredContent&&typeof V.structuredContent==="object")return V.structuredContent;let B=V.content;if(B?.[0]?.type==="text"&&B[0].text)try{return JSON.parse(B[0].text)}catch{return B[0].text}return V}}try{let H=`
|
|
1324
1324
|
const __virtualToolFn = ${K.replace(/^\s*export\s+default\s+/,"").trim()};
|
|
1325
1325
|
export default async (tools) => {
|
|
@@ -1328,7 +1328,7 @@ ${Q.stack}`;return G}}catch{}if(typeof Q.toString==="function")try{let G=Q.toStr
|
|
|
1328
1328
|
};
|
|
1329
1329
|
`,$=await Xv({code:H,tools:W,timeoutMs:30000});if($.error)return{content:[{type:"text",text:`Virtual tool error: ${$.error}`}],isError:!0};return{content:[{type:"text",text:JSON.stringify($.returnValue??null)}]}}catch(Z){return{content:[{type:"text",text:`Virtual tool execution failed: ${Z instanceof Error?Z.message:String(Z)}`}],isError:!0}}}async listResources(){return{resources:(await this._cachedResources).data}}async readResource(Y){let Q=await this._cachedResources,X=this._clients,J=Q.mappings.get(Y.uri);if(!J)throw Error(`Resource not found: ${Y.uri}`);let G=X.get(J);if(!G)throw Error(`Connection not found for resource: ${Y.uri}`);return await G.readResource(Y)}async listPrompts(){return{prompts:(await this._cachedPrompts).data}}async getPrompt(Y){let Q=await this._cachedPrompts,X=this._clients,J=Q.mappings.get(Y.name);if(!J)throw Error(`Prompt not found: ${Y.name}`);let G=X.get(J);if(!G)throw Error(`Connection not found for prompt: ${Y.name}`);return await G.getPrompt(Y)}async callStreamableTool(Y,Q){let X=await this._cachedTools,J=this._clients,G=X.mappings.get(Y);if(G){let W=J.get(G);if(W&&"callStreamableTool"in W)return W.callStreamableTool(Y,Q)}let K=await this.callTool({name:Y,arguments:Q});return new Response(JSON.stringify(K),{headers:{"Content-Type":"application/json"}})}async[Symbol.asyncDispose](){await ap0(this._clients)}async close(){await ap0(this._clients),await super.close()}getInstructions(){return this.options.virtualMcp.metadata?.instructions??void 0}}});var rp0,Rx6,op0,Ix6,Bv;var yz1=k(()=>{c1();$O();_z1();rp0=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")}),Rx6=q.toJSONSchema(rp0),op0=q.object({tools:q.array(q.string()).min(1).describe("Array of tool names to get detailed schemas for")}),Ix6=q.toJSONSchema(op0);Bv=class Bv extends DP{constructor(Y,Q){super(Y,Q)}getSearchTool(Y){return{name:"GATEWAY_SEARCH_TOOLS",description:`Search for available tools by name or description. Returns tool names and brief descriptions without full schemas. Use this to discover tools before calling GATEWAY_DESCRIBE_TOOLS for detailed schemas. Total tools: ${Y}.`,inputSchema:Rx6,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:Ix6,annotations:{title:"Describe Tools",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}}}async handleSearch(Y){let Q=rp0.safeParse(Y);if(!Q.success)return GB({error:Q.error.flatten()});let X=await this._cachedTools,J=KF(X.data),G=Gr(Q.data.query,J,Q.data.limit);return Jv({query:Q.data.query,results:G.map((K)=>({name:K.name,description:K.description,connection:K._meta.connectionTitle})),totalAvailable:J.length})}async handleDescribe(Y){let Q=op0.safeParse(Y);if(!Q.success)return GB({error:Q.error.flatten()});let X=await this._cachedTools,J=KF(X.data),G=Wr(Q.data.tools,J);return Jv({tools:G.tools,notFound:G.notFound})}async listTools(){let Y=await this._cachedTools,Q=KF(Y.data);return{tools:[this.getSearchTool(Q.length),this.getDescribeTool()]}}async callTool(Y){if(Y.name==="GATEWAY_SEARCH_TOOLS")return this.handleSearch(Y.arguments??{});if(Y.name==="GATEWAY_DESCRIBE_TOOLS")return this.handleDescribe(Y.arguments??{});return{content:[{type:"text",text:`Unknown tool: ${Y.name}. Available: GATEWAY_SEARCH_TOOLS, GATEWAY_DESCRIBE_TOOLS`}],isError:!0}}async routeToolCall(Y){return DP.prototype.callTool.call(this,Y)}}});var sp0,jx6,fz1;var tp0=k(()=>{c1();$O();yz1();sp0=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).")}),jx6=q.toJSONSchema(sp0);fz1=class fz1 extends Bv{constructor(Y,Q){super(Y,Q)}getRunCodeTool(){return{name:"GATEWAY_RUN_CODE",description:'Run JavaScript code in a sandbox. Code must be an ES module that `export default`s an async function that receives (tools) as its first parameter. Use GATEWAY_DESCRIBE_TOOLS to understand the input/output schemas for a tool before calling it. Use `await tools.toolName(args)` or `await tools["tool-name"](args)` to call tools.',inputSchema:jx6,annotations:{title:"Run Code",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}}}async handleRunCode(Y){let Q=sp0.safeParse(Y);if(!Q.success)return GB({error:Q.error.flatten()});let X=await this._cachedTools,G={tools:KF(X.data),callTool:async(W,Z)=>{return this.routeToolCall({name:W,arguments:Z})}},K=await Zr(Q.data.code,G,Q.data.timeoutMs);if(K.error)return GB(K);return Jv(K)}async listTools(){return{tools:[...(await super.listTools()).tools,this.getRunCodeTool()]}}async callTool(Y){if(Y.name==="GATEWAY_RUN_CODE")return this.handleRunCode(Y.arguments??{});return super.callTool(Y)}}});function Yc0(Y){let Q=Y.slice().sort().join(","),X=ep0.get(Q);if(!X){let J=q.object({name:(Y.length>0?q.enum(Y):q.string()).describe("The name of the tool to execute"),arguments:q.record(q.string(),q.unknown()).default({}).describe("Arguments to pass to the tool")});X={schema:J,jsonSchema:q.toJSONSchema(J)},ep0.set(Q,X)}return X}var ep0,bz1;var Qc0=k(()=>{c1();$O();yz1();ep0=new Map;bz1=class bz1 extends Bv{constructor(Y,Q){super(Y,Q)}async getCallTool(){let Y=await this._cachedTools,X=KF(Y.data).map((G)=>G.name),{jsonSchema:J}=Yc0(X);return{name:"GATEWAY_CALL_TOOL",description:"Execute a tool by name. Use GATEWAY_DESCRIBE_TOOLS first to understand the input schema.",inputSchema:J,annotations:{title:"Call Tool",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}}}async handleCallTool(Y){let Q=await this._cachedTools,X=KF(Q.data),J=X.map(($)=>$.name),{schema:G}=Yc0(J),K=G.safeParse(Y);if(!K.success)return GB({error:K.error.flatten()});let{name:W,arguments:Z}=K.data;if(!new Map(X.map(($)=>[$.name,$])).has(W))return{content:[{type:"text",text:`Tool not found: ${W}. Use GATEWAY_SEARCH_TOOLS to find available tools.`}],isError:!0};return this.routeToolCall({name:W,arguments:Z})}async listTools(){let Y=await super.listTools(),Q=await this.getCallTool();return{tools:[...Y.tools,Q]}}async callTool(Y){if(Y.name==="GATEWAY_CALL_TOOL")return this.handleCallTool(Y.arguments??{});return super.callTool(Y)}}});function hz1(Y){switch(Y){case"smart_tool_selection":return"smart_tool_selection";case"code_execution":return"code_execution";case"passthrough":default:return"passthrough"}}function Sx6(Y,Q){if(Y.connection_type!=="VIRTUAL")return!1;if(!Q||o3(Q))return!1;return Y.id===Q}async function Xc0(Y,Q,X=!1){let J=Y.id,G=await Q.storage.virtualMcps.findById(J);if(!G)throw Error(`Virtual MCP not found: ${J}`);return KB(G,Q,"passthrough",X)}async function KB(Y,Q,X,J=!1){let K=Y.connections.map((V)=>V.connection_id).map((V)=>Q.storage.connections.findById(V)),W=Y.id?await Q.storage.connections.findById(Y.id):null,Z=await Promise.all(K),H=[];if(W?.tools){for(let V of W.tools)if(ZB(V))H.push(V)}let F={connections:Z.filter((V)=>V!==null&&V.status==="active"&&!Sx6(V,Y.id)),virtualMcp:Y,virtualTools:H.length>0?H:void 0,superUser:J};return X==="smart_tool_selection"?new bz1(F,Q):X==="code_execution"?new fz1(F,Q):new DP(F,Q)}var Uv=k(()=>{KY();VF();tp0();_z1();Qc0()});async function _5(Y,Q,X=!1){if(Y.connection_type==="VIRTUAL")return Xc0(Y,Q,X);return lp0(Y,Q,X)}var xz1=k(()=>{dp0();Uv()});async function gz1(Y,Q,X){let J=await _5(Y,Q,X),G=ND(J,{name:"mcp-mesh-enhanced",version:"1.0.0"},{capabilities:kx6,instructions:J.getInstructions()});return G.server.setRequestHandler(PV,async()=>{return await J.listResources().catch(FO({resources:[]}))}),G.server.setRequestHandler(EV,async()=>{return await J.listResourceTemplates().catch(FO({resourceTemplates:[]}))}),G.server.setRequestHandler(TV,async()=>{return await J.listPrompts().catch(FO({prompts:[]}))}),G}var kx6;var Jc0=k(()=>{KY();vQ();xz1();vz1();kx6={tools:{},resources:{},prompts:{}}});function uz1(Y,Q){let X=Y.listTools.bind(Y),J=async()=>{if(Q.connection_type!=="VIRTUAL"&&Q.tools&&Q.tools.length>0)return{tools:Q.tools.map((K)=>({name:K.name,description:K.description,inputSchema:K.inputSchema,outputSchema:K.outputSchema,annotations:K.annotations,_meta:K._meta}))};return await X()};return Y.listTools=J,Y}function vx6(Y,Q,X){return async(J,G)=>{try{let K=J.params.name,W=async()=>{let{tools:H}=await X();return H.find((F)=>F.name===K)?._meta};return await new FF(Y.authInstance,Y.auth.user?.id??Y.auth.apiKey?.userId,K,Y.boundAuth,Y.auth.user?.role,Q,W).check(K),await G()}catch(K){return new Response(JSON.stringify({error:`Authorization failed: ${K.message}`}),{status:403,headers:{"Content-Type":"application/json"}})}}}function VO(Y,Q,X,J,G){let K=async(Z,H)=>{if(X.connection_type==="VIRTUAL"){let U=await Y.callTool({name:Z,arguments:H});return new Response(JSON.stringify(U),{headers:{"Content-Type":"application/json"}})}if(!X.connection_url)throw Error("Streamable tools require HTTP connection with URL");let $=X.connection_url,F={method:"tools/call",params:{name:Z,arguments:H}};if(!G.superUser){let D=await vx6(J,Q,Y.listTools.bind(Y))(F,async()=>{return new Response});if(!D.ok)return D}let V=J.connectionId&&J.connectionId!==Q?J.connectionId:void 0;return gp0({ctx:J,enabled:Fn().enabled,connectionId:Q,connectionTitle:X.title,virtualMcpId:V})(F,async()=>{let U=await Hv(X,J,G.superUser),D=X.connection_headers;if(D&&"headers"in D)Object.assign(U,D.headers);let z=new URL($);z.pathname=z.pathname.replace(/\/$/,"")+`/call-tool/${F.params.name}`;let L=JSON.parse(JSON.stringify(F.params.arguments,(E,T)=>{if(T instanceof AbortSignal)return;if(typeof T==="function"||typeof T==="symbol")return;if(T===void 0)return;return T})),w=JSON.stringify(L);return await J.tracer.startActiveSpan("mcp.proxy.callStreamableTool",{attributes:{"connection.id":Q,"tool.name":F.params.name,"request.id":J.metadata.requestId}},async(E)=>{let T=Date.now();try{let C=await fetch(z.toString(),{method:"POST",redirect:"manual",body:w,headers:{...U,"Content-Type":"application/json"}}),P=Date.now()-T;return J.meter.createHistogram("connection.proxy.streamable.duration").record(P,{"connection.id":Q,"tool.name":F.params.name,status:C.ok?"success":"error"}),J.meter.createCounter("connection.proxy.streamable.requests").add(1,{"connection.id":Q,"tool.name":F.params.name,status:C.ok?"success":"error"}),E.end(),C}catch(C){let P=C,R=Date.now()-T;throw console.error("[with-streaming-support] fetch error",{connectionId:Q,toolName:F.params.name,error:P.message,errorStack:P.stack,duration:R}),J.meter.createHistogram("connection.proxy.streamable.duration").record(R,{"connection.id":Q,"tool.name":F.params.name,status:"error"}),J.meter.createCounter("connection.proxy.streamable.errors").add(1,{"connection.id":Q,"tool.name":F.params.name,error:P.message}),E.recordException(P),E.end(),C}})})},W=Object.assign(Object.create(Object.getPrototypeOf(Y)),Y);return W.callStreamableTool=K,W}var Gc0=k(()=>{Pz1();Vv();QS();Sz1()});var Wc0=k(()=>{Gc0()});var zP=k(()=>{xz1();Jc0();Wc0()});async function fx6(Y,Q,X,J){for(let K of Q){if(K==="*")continue;let[W]=Cp0(K),Z=Vr(W,Y);if(Z===void 0||Z===null)throw Error(`Scope references key "${W}" but it's not present in state`)}let G=Rp0(Y,Q);for(let K of G){if(K.endsWith("_self"))continue;let W=await J.storage.connections.findById(K);if(!W||W.organization_id!==X)throw Error(`Referenced connection not found: ${K}`);try{await J.access.check(K)}catch(Z){throw Error(`Access denied to referenced connection: ${K}. ${Z.message}`)}}}var _x6,yx6,mz1;var Zc0=k(()=>{wz1();zP();qr();c1();F4();kn();b$();_x6=q.object({id:q.string().describe("ID of the connection to update"),data:ER.describe("Partial connection data to update")}),yx6=q.object({item:W5.describe("The updated connection entity")});mz1=s1({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:_x6,outputSchema:yx6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=EY(Q);if(!J)throw Error("User ID required to update connection");let{id:G,data:K}=Y,W=await Q.storage.connections.findById(G);if(!W||W.organization_id!==X.id)throw Error("Connection not found in organization");let Z=K.connection_type??W.connection_type,H=K.connection_url??W.connection_url;if(Z==="VIRTUAL"){let L=DD(H);if(!L)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let w=await Q.storage.virtualMcps.findById(L);if(!w)throw Error(`Virtual MCP not found: ${L}`);if(w.organization_id!==X.id)throw Error("Virtual MCP does not belong to the current organization");H=zD(L)}let $=K.configuration_state??W.configuration_state??{},F=K.configuration_scopes??W.configuration_scopes??[];if(K.configuration_state!==void 0||K.configuration_scopes!==void 0){if(K.configuration_state!==void 0)$=K.configuration_state??{};else if($===null||$===void 0)$={};if(K.configuration_scopes!==void 0)F=K.configuration_scopes??[];if(F.length>0)await fx6($,F,X.id,Q)}let V=K.connection_token??W.connection_token;if(!V)try{let w=await new $F(Q.db,Q.vault).get(G);if(w?.accessToken)V=w.accessToken}catch{}let B=await DA({id:W.id,title:K.title??W.title,connection_type:Z,connection_url:H,connection_token:V,connection_headers:K.connection_headers??W.connection_headers}).catch(()=>null),U=B?.tools?.length?B.tools:null;if(K.configuration_scopes===void 0&&B?.scopes?.length)F=B.scopes;let D={...K,connection_url:H,tools:U,configuration_state:$,configuration_scopes:F,updated_by:J},z=await Q.storage.connections.update(G,D);if((K.configuration_state!==void 0||K.configuration_scopes!==void 0)&&$&&F)try{await(await _5(z,Q,!1)).callTool({name:"ON_MCP_CONFIGURATION",arguments:{state:$,scopes:F}})}catch(L){console.error("Failed to invoke ON_MCP_CONFIGURATION callback",L)}return{item:z}}})});var bx6,lz1;var Kc0=k(()=>{MG();c1();F4();b$();bx6=CS.extend({force:q.boolean().optional().describe("If true, removes this connection from all agents that reference it before deleting")}),lz1=s1({name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete a connection",annotations:{title:"Delete Connection",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:bx6,outputSchema:RS(W5),handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=await Q.storage.connections.findById(Y.id);if(!J)throw Error(`Connection not found: ${Y.id}`);if(J.organization_id!==X.id)throw Error("Connection not found in organization");if(J.metadata?.isFixed===!0)throw Error("This connection is a fixed system connection and cannot be deleted");let K=await Q.storage.virtualMcps.listByConnectionId(X.id,Y.id);if(K.length>0)if(Y.force)await Q.storage.virtualMcps.removeConnectionReferences(Y.id);else throw Error(JSON.stringify({code:"CONNECTION_IN_USE",agentNames:K.map((W)=>W.title)}));return await Q.storage.connections.delete(Y.id),{item:J}}})});var dz1;var Hc0=k(()=>{c1();F4();dz1=s1({name:"CONNECTION_TEST",description:"Test connection health and latency",annotations:{title:"Test Connection",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},inputSchema:q.object({id:q.string()}),outputSchema:q.object({id:q.string(),healthy:q.boolean(),latencyMs:q.number()}),handler:async(Y,Q)=>{let X=v0(Q);await Q.access.check();let J=await Q.storage.connections.findById(Y.id);if(!J||J.organization_id!==X.id)throw Error("Connection not found");let G=await Q.storage.connections.testConnection(Y.id);return{id:Y.id,...G}}})});var $c0=k(()=>{Op0();Ep0();Tp0();Zc0();Kc0();Hc0()});import{sql as k8}from"kysely";function Fc0(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 gx6(Y,Q){let X=Y;for(let G=Q.length;G>=1;G--){let K=`$${G}`;if(X.includes(K))X=X.replaceAll(K,Fc0(Q[G-1]))}let J=[];for(let G=0;G<X.length;G++)if(X[G]==="?")J.push(G);for(let G=Math.min(J.length,Q.length)-1;G>=0;G--){let K=J[G],W=Fc0(Q[G]);X=X.slice(0,K)+W+X.slice(K+1)}return X}function Vc0(Y){return Y.replace(/-/g,"_")}function mx6(Y){return`app_${Vc0(Y)}`}function lx6(Y){return`app_role_${Vc0(Y)}`}function dx6(Y){if(Y instanceof Error){let Q=Y.message.toLowerCase(),X=Y.code;return X==="3F000"||X==="42704"||X==="22023"||Q.includes("schema")&&Q.includes("does not exist")||Q.includes("role")&&Q.includes("does not exist")}return!1}async function px6(Y,Q,X){if(await k8`CREATE SCHEMA IF NOT EXISTS ${k8.id(Q)}`.execute(Y),!(await k8`
|
|
1330
1330
|
SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${X}) as exists
|
|
1331
|
-
`.execute(Y)).rows[0]?.exists)await k8`CREATE ROLE ${k8.id(X)} NOLOGIN`.execute(Y);await k8`GRANT ${k8.id(X)} TO CURRENT_USER`.execute(Y),await k8`GRANT USAGE, CREATE ON SCHEMA ${k8.id(Q)} TO ${k8.id(X)}`.execute(Y),await k8`GRANT ALL ON ALL TABLES IN SCHEMA ${k8.id(Q)} TO ${k8.id(X)}`.execute(Y),await k8`GRANT ALL ON ALL SEQUENCES IN SCHEMA ${k8.id(Q)} TO ${k8.id(X)}`.execute(Y),await k8`ALTER DEFAULT PRIVILEGES IN SCHEMA ${k8.id(Q)} GRANT ALL ON TABLES TO ${k8.id(X)}`.execute(Y),await k8`ALTER DEFAULT PRIVILEGES IN SCHEMA ${k8.id(Q)} GRANT ALL ON SEQUENCES TO ${k8.id(X)}`.execute(Y),await k8`REVOKE ALL ON SCHEMA public FROM ${k8.id(X)}`.execute(Y)}async function cx6(Y,Q,X,J){try{return await Y.transaction().execute(async(G)=>{return await k8`SET LOCAL ROLE ${k8.id(X)}`.execute(G),await k8`SET LOCAL search_path TO ${k8.id(Q)}`.execute(G),await k8.raw(J).execute(G)})}catch(G){if(dx6(G))return await px6(Y,Q,X),await Y.transaction().execute(async(K)=>{return await k8`SET LOCAL ROLE ${k8.id(X)}`.execute(K),await k8`SET LOCAL search_path TO ${k8.id(Q)}`.execute(K),await k8.raw(J).execute(K)});throw G}}var xx6,ux6,qc0;var Bc0=k(()=>{c1();F4();xx6=q.object({results:q.array(q.unknown()).optional(),success:q.boolean().optional()});ux6=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()});qc0=s1({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:ux6,outputSchema:q.object({result:q.array(xx6)}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=gx6(Y.sql,Y.params||[]);if(!Q.connectionId)throw Error("Connection context required for database access");let J=mx6(Q.connectionId),G=lx6(Q.connectionId);return{result:[{results:(await cx6(Q.db,J,G,X)).rows,success:!0}]}}})});var Uc0,ix6,Dc0;var qF=k(()=>{c1();lS();Uc0=q.object({connectionId:q.string().optional().describe("Filter subscriptions by connection ID (optional)")}),ix6=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)")}),Dc0=q.object({subscriptions:q.array(ix6).describe("List of subscriptions")})});var pz1;var zc0=k(()=>{F4();qF();pz1=s1({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:IS,outputSchema:jS,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=Q.connectionId;if(!J)throw Error("Connection ID required to publish events. Use a connection-scoped token.");let G=await Q.eventBus.publish(X.id,J,{type:Y.type,subject:Y.subject,data:Y.data,deliverAt:Y.deliverAt,cron:Y.cron});return{id:G.id,type:G.type,source:G.source,time:G.time}}})});var cz1;var Oc0=k(()=>{F4();qF();cz1=s1({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:SS,outputSchema:kS,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=Q.connectionId;if(!J)throw Error("Connection ID required to subscribe. Use a connection-scoped token.");let G=await Q.eventBus.subscribe(X.id,{connectionId:J,eventType:Y.eventType,publisher:Y.publisher,filter:Y.filter});return{subscription:{id:G.id,connectionId:G.connectionId,eventType:G.eventType,publisher:G.publisher,filter:G.filter,enabled:G.enabled,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}}}})});var nz1;var Nc0=k(()=>{F4();qF();nz1=s1({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:yS,outputSchema:fS,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=Q.connectionId;if(!J)throw Error("Connection ID required to unsubscribe. Use a connection-scoped token.");let G=await Q.eventBus.getSubscription(X.id,Y.subscriptionId);if(!G)throw Error(`Subscription not found: ${Y.subscriptionId}`);if(G.connectionId!==J)throw Error("Cannot unsubscribe from a subscription owned by another connection");return{success:(await Q.eventBus.unsubscribe(X.id,Y.subscriptionId)).success,subscriptionId:Y.subscriptionId}}})});var iz1;var Lc0=k(()=>{F4();qF();iz1=s1({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:bS,outputSchema:hS,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=Q.connectionId;if(!J)throw Error("Connection ID required to cancel events. Use a connection-scoped token.");if(!await Q.eventBus.getEvent(X.id,Y.eventId))throw Error(`Event not found: ${Y.eventId}`);if(!(await Q.eventBus.cancelEvent(X.id,Y.eventId,J)).success)throw Error("Failed to cancel event. Either the event is already completed/failed, or you are not the publisher.");return{success:!0,eventId:Y.eventId}}})});var az1;var Mc0=k(()=>{F4();qF();az1=s1({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:xS,outputSchema:gS,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=Q.connectionId;if(!J)throw Error("Connection ID required to acknowledge events. Use a connection-scoped token.");if(!(await Q.eventBus.ackEvent(X.id,Y.eventId,J)).success)throw Error("Failed to acknowledge event. Either the event was not found, already delivered, or you are not a subscriber.");return{success:!0,eventId:Y.eventId}}})});var rz1;var wc0=k(()=>{F4();qF();rz1=s1({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:Uc0,outputSchema:Dc0,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);return await Q.access.check(),{subscriptions:(await Q.eventBus.listSubscriptions(X.id,Y.connectionId)).map((G)=>({id:G.id,connectionId:G.connectionId,eventType:G.eventType,publisher:G.publisher,filter:G.filter,enabled:G.enabled,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}))}}})});var oz1;var Ac0=k(()=>{F4();qF();oz1=s1({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:vS,outputSchema:_S,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=Q.connectionId;if(!J)throw Error("Connection ID required to sync subscriptions. Use a connection-scoped token.");let G=await Q.eventBus.syncSubscriptions(X.id,{connectionId:J,subscriptions:Y.subscriptions});return{created:G.created,updated:G.updated,deleted:G.deleted,unchanged:G.unchanged,subscriptions:G.subscriptions.map((K)=>({id:K.id,connectionId:K.connectionId,eventType:K.eventType,publisher:K.publisher,filter:K.filter,enabled:K.enabled,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt,updatedAt:K.updatedAt instanceof Date?K.updatedAt.toISOString():K.updatedAt}))}}})});var Pc0=k(()=>{zc0();Oc0();Nc0();Lc0();Mc0();wc0();Ac0();qF()});var OP=k(()=>{nm()});function Ec0(){return`/icons/capy-${Math.floor(Math.random()*39)+0}.png`}var rx6,ox6,sz1;var Tc0=k(()=>{c1();F4();OP();rx6=q.object({data:CR.describe("Data for the new virtual MCP")}),ox6=q.object({item:lG.describe("The created virtual MCP entity")}),sz1=s1({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:rx6,outputSchema:ox6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=EY(Q);if(!J)throw Error("User ID required to create virtual MCP");let G={...Y.data,icon:Y.data.icon??Ec0()};return{item:await Q.storage.virtualMcps.create(X.id,J,G)}}})});function sx6(Y){let Q=[],X=0;while(X<Y.length){let J=Y[X];if(J==="%")Q.push(".*");else if(J==="_")Q.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))Q.push("\\"+J);else Q.push(J);X++}return Q.join("")}function HB(Y){return typeof Y==="string"||typeof Y==="number"}function tz1(Y,Q){let X=Q.split("."),J=Y;for(let G of X){if(J==null||typeof J!=="object")return;J=J[G]}return J}function tx6(Y,Q){return Y.connections.some((X)=>X.connection_id===Q)}function Ur(Y,Q){if("conditions"in Q){let{operator:Z,conditions:H}=Q;switch(Z){case"and":return H.every(($)=>Ur(Y,$));case"or":return H.some(($)=>Ur(Y,$));case"not":return!H.every(($)=>Ur(Y,$));default:return!0}}let{field:X,operator:J,value:G}=Q,K=X.join(".");if(K==="connection_id"){if(J!=="eq"||typeof G!=="string")return!1;return tx6(Y,G)}let W=tz1(Y,K);switch(J){case"eq":return W===G;case"gt":return HB(W)&&HB(G)&&W>G;case"gte":return HB(W)&&HB(G)&&W>=G;case"lt":return HB(W)&&HB(G)&&W<G;case"lte":return HB(W)&&HB(G)&&W<=G;case"in":return Array.isArray(G)&&G.includes(W);case"like":if(typeof W!=="string"||typeof G!=="string")return!1;if(G.length>100)return!1;let Z=sx6(G);return new RegExp(`^${Z}$`,"i").test(W);case"contains":if(typeof W!=="string"||typeof G!=="string")return!1;return W.toLowerCase().includes(G.toLowerCase());default:return!0}}function ex6(Y,Q){return[...Y].sort((X,J)=>{for(let G of Q){let K=G.field.join("."),W=tz1(X,K),Z=tz1(J,K),H=0;if(W==null&&Z==null)continue;if(W==null)H=G.nulls==="first"?-1:1;else if(Z==null)H=G.nulls==="first"?1:-1;else if(typeof W==="string"&&typeof Z==="string")H=W.localeCompare(Z);else if(typeof W==="number"&&typeof Z==="number")H=W-Z;else H=String(W).localeCompare(String(Z));if(H!==0)return G.direction==="desc"?-H:H}return 0})}var Yg6,Qg6,ez1;var Cc0=k(()=>{MG();F4();OP();Yg6=uZ,Qg6=x$(lG),ez1=s1({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:Yg6,outputSchema:Qg6,handler:async(Y,Q)=>{await Q.access.check();let X=v0(Q),J=Y.where&&!("conditions"in Y.where)&&Y.where.field.join(".")==="connection_id"&&Y.where.operator==="eq"&&typeof Y.where.value==="string"?Y.where.value:void 0,K=J?await Q.storage.virtualMcps.listByConnectionId(X.id,J):await Q.storage.virtualMcps.list(X.id);if(Y.where)K=K.filter((V)=>Ur(V,Y.where));if(Y.orderBy&&Y.orderBy.length>0)K=ex6(K,Y.orderBy);let W=K.length,Z=Y.offset??0,H=Y.limit??100,$=K.slice(Z,Z+H),F=Z+H<W;return{items:$,totalCount:W,hasMore:F}}})});var Xg6,Jg6,YO1;var Rc0=k(()=>{c1();F4();OP();Xg6=q.object({id:q.string().describe("ID of the virtual MCP to retrieve")}),Jg6=q.object({item:lG.nullable().describe("The retrieved virtual MCP, or null if not found")}),YO1=s1({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:Xg6,outputSchema:Jg6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.id);if(J&&J.organization_id!==X.id)return{item:null};if(!J)return{item:null};return{item:J}}})});var Gg6,Wg6,QO1;var Ic0=k(()=>{c1();F4();OP();Gg6=q.object({id:q.string().describe("ID of the virtual MCP to update"),data:RR.describe("Partial virtual MCP data to update")}),Wg6=q.object({item:lG.describe("The updated virtual MCP entity")}),QO1=s1({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:Gg6,outputSchema:Wg6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=EY(Q);if(!J)throw Error("User ID required to update virtual MCP");let G=await Q.storage.virtualMcps.findById(Y.id);if(!G)throw Error(`Virtual MCP not found: ${Y.id}`);if(G.organization_id!==X.id)throw Error(`Virtual MCP not found: ${Y.id}`);return{item:await Q.storage.virtualMcps.update(Y.id,J,Y.data)}}})});var Zg6,Kg6,XO1;var jc0=k(()=>{c1();F4();OP();Zg6=q.object({id:q.string().describe("ID of the virtual MCP to delete")}),Kg6=q.object({item:lG.describe("The deleted virtual MCP entity")}),XO1=s1({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:Zg6,outputSchema:Kg6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.id);if(!J)throw Error(`Virtual MCP not found: ${Y.id}`);if(J.organization_id!==X.id)throw Error(`Virtual MCP not found: ${Y.id}`);return await Q.storage.virtualMcps.delete(Y.id),{item:J}}})});var Sc0=k(()=>{Tc0();Cc0();Rc0();Ic0();jc0()});var $g6,Fg6,JO1;var kc0=k(()=>{c1();F4();VF();$g6=q.object({virtual_mcp_id:q.string().describe("ID of the Virtual MCP to add the tool to"),data:pp0.describe("Virtual tool data")}),Fg6=q.object({item:iH.describe("The created virtual tool")}),JO1=s1({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:$g6,outputSchema:Fg6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!J||J.organization_id!==X.id)throw Error(`Virtual MCP not found: ${Y.virtual_mcp_id}`);let G=Y.data.connection_dependencies??[];return{item:await Q.storage.virtualMcps.createVirtualTool(Y.virtual_mcp_id,Y.data,G)}}})});var Vg6,qg6,GO1;var vc0=k(()=>{c1();F4();VF();Vg6=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")}),qg6=q.object({items:q.array(iH).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")}),GO1=s1({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:Vg6,outputSchema:qg6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!J||J.organization_id!==X.id)return{items:[],totalCount:0,hasMore:!1};let G=await Q.storage.virtualMcps.listVirtualTools(Y.virtual_mcp_id),K=G.length,W=Y.offset??0,Z=Y.limit??100,H=G.slice(W,W+Z),$=W+Z<K;return{items:H,totalCount:K,hasMore:$}}})});var Bg6,Ug6,WO1;var _c0=k(()=>{c1();F4();VF();Bg6=q.object({virtual_mcp_id:q.string().describe("ID of the Virtual MCP"),name:q.string().describe("Name of the virtual tool to retrieve")}),Ug6=q.object({item:iH.nullable().describe("The retrieved virtual tool, or null if not found")}),WO1=s1({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:Bg6,outputSchema:Ug6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!J||J.organization_id!==X.id)return{item:null};return{item:await Q.storage.virtualMcps.getVirtualTool(Y.virtual_mcp_id,Y.name)}}})});var Dg6,zg6,ZO1;var yc0=k(()=>{c1();F4();VF();Dg6=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:cp0.describe("Partial virtual tool data to update")}),zg6=q.object({item:iH.describe("The updated virtual tool")}),ZO1=s1({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:Dg6,outputSchema:zg6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!J||J.organization_id!==X.id)throw Error(`Virtual MCP not found: ${Y.virtual_mcp_id}`);if(!await Q.storage.virtualMcps.getVirtualTool(Y.virtual_mcp_id,Y.name))throw Error(`Virtual tool not found: ${Y.name}`);let K=Y.data.connection_dependencies;return{item:await Q.storage.virtualMcps.updateVirtualTool(Y.virtual_mcp_id,Y.name,Y.data,K)}}})});var Og6,Ng6,KO1;var fc0=k(()=>{c1();F4();VF();Og6=q.object({virtual_mcp_id:q.string().describe("ID of the Virtual MCP"),name:q.string().describe("Name of the virtual tool to delete")}),Ng6=q.object({item:iH.describe("The deleted virtual tool")}),KO1=s1({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:Og6,outputSchema:Ng6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!J||J.organization_id!==X.id)throw Error(`Virtual MCP not found: ${Y.virtual_mcp_id}`);let G=await Q.storage.virtualMcps.getVirtualTool(Y.virtual_mcp_id,Y.name);if(!G)throw Error(`Virtual tool not found: ${Y.name}`);return await Q.storage.virtualMcps.deleteVirtualTool(Y.virtual_mcp_id,Y.name),{item:G}}})});var bc0=k(()=>{kc0();vc0();_c0();yc0();fc0()});var Mg6,HO1;var hc0=k(()=>{F4();c1();Mg6=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")}),HO1=s1({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(Mg6).describe("Array of monitoring logs"),total:q.number().describe("Total number of logs matching filters"),offset:q.number().describe("Current offset for pagination"),limit:q.number().describe("Current limit for pagination")}),handler:async(Y,Q)=>{let X=v0(Q),G=Y.properties||Y.propertyKeys||Y.propertyPatterns||Y.propertyInValues?{properties:Y.properties,propertyKeys:Y.propertyKeys,propertyPatterns:Y.propertyPatterns,propertyInValues:Y.propertyInValues}:void 0,K={organizationId:X.id,connectionId:Y.connectionId,excludeConnectionIds:Y.excludeConnectionIds,virtualMcpId:Y.virtualMcpId,toolName:Y.toolName,isError:Y.isError,startDate:Y.startDate?new Date(Y.startDate):void 0,endDate:Y.endDate?new Date(Y.endDate):void 0,limit:Y.limit,offset:Y.offset,propertyFilters:G},W=await Q.storage.monitoring.query(K);return{logs:W.logs.map((Z)=>({...Z,timestamp:Z.timestamp instanceof Date?Z.timestamp.toISOString():Z.timestamp})),total:W.total,offset:Y.offset,limit:Y.limit}}})});var $O1;var xc0=k(()=>{F4();c1();$O1=s1({name:"MONITORING_STATS",description:"Get aggregated statistics for tool call monitoring",annotations:{title:"Get Monitoring Stats",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({startDate:q.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:q.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)")}),outputSchema:q.object({totalCalls:q.number().describe("Total number of tool calls"),errorRate:q.number().describe("Error rate as a decimal (0 to 1)"),avgDurationMs:q.number().describe("Average call duration in milliseconds"),errorRatePercent:q.string().describe("Error rate as a percentage string")}),handler:async(Y,Q)=>{let J={organizationId:v0(Q).id,startDate:Y.startDate?new Date(Y.startDate):void 0,endDate:Y.endDate?new Date(Y.endDate):void 0},G=await Q.storage.monitoring.getStats(J);return{...G,errorRatePercent:(G.errorRate*100).toFixed(2)}}})});var gc0=k(()=>{hc0();xc0()});var Ag6,Pg6,Eg6,Tg6,Cg6,Dv,zv,$B,Rg6,Ig6,uc0;var NP=k(()=>{c1();Ag6=q.enum(["sum","avg","min","max","count","last"]).describe("Aggregation function to apply"),Pg6=q.enum(["metric","timeseries","table"]).describe("Widget display type"),Eg6=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")}),Tg6=q.object({fn:Ag6,groupBy:q.string().optional().describe("Optional JSONPath for grouping results"),interval:q.string().optional().describe("For timeseries widgets: interval like '1h', '1d', '15m'")}),Cg6=q.object({connectionIds:q.array(q.string()).optional().describe("Filter to specific connections"),toolNames:q.array(q.string()).optional().describe("Filter to specific tools")}),Dv=q.object({id:q.string().describe("Unique widget identifier"),name:q.string().describe("Widget display name"),type:Pg6,source:Eg6,aggregation:Tg6,filter:Cg6.optional()}),zv=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' })")}),$B=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:zv.nullable().describe("Global filters applied to all widgets"),widgets:q.array(Dv).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")}),Rg6=q.object({key:q.string().describe("Group key value"),value:q.number().describe("Aggregated value for this group")}),Ig6=q.object({timestamp:q.string().describe("Time bucket timestamp"),value:q.number().describe("Aggregated value for this time bucket")}),uc0=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(Rg6).optional().describe("Grouped results (when groupBy is specified)"),timeseries:q.array(Ig6).optional().describe("Timeseries data (for timeseries type)")})});var FO1;var mc0=k(()=>{F4();c1();NP();FO1=s1({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:zv.optional().describe("Global filters applied to all widgets"),widgets:q.array(Dv).min(1).describe("Widget definitions (at least one required)")}),outputSchema:$B,handler:async(Y,Q)=>{let X=v0(Q),J=Q.auth.user?.id;if(!J)throw Error("User authentication required");let G=await Q.storage.monitoringDashboards.create(X.id,J,{name:Y.name,description:Y.description,filters:Y.filters,widgets:Y.widgets});return{id:G.id,organizationId:G.organizationId,name:G.name,description:G.description,filters:G.filters,widgets:G.widgets,createdBy:G.createdBy,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}}})});var VO1;var lc0=k(()=>{F4();c1();NP();VO1=s1({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:$B.nullable(),handler:async(Y,Q)=>{let X=v0(Q),J=await Q.storage.monitoringDashboards.get(Y.id);if(!J||J.organizationId!==X.id)return null;return{id:J.id,organizationId:J.organizationId,name:J.name,description:J.description,filters:J.filters,widgets:J.widgets,createdBy:J.createdBy,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt,updatedAt:J.updatedAt instanceof Date?J.updatedAt.toISOString():J.updatedAt}}})});var qO1;var dc0=k(()=>{F4();c1();NP();qO1=s1({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($B).describe("List of dashboards"),total:q.number().describe("Total number of dashboards")}),handler:async(Y,Q)=>{let X=v0(Q),J=await Q.storage.monitoringDashboards.list(X.id);return{dashboards:J.map((G)=>({id:G.id,organizationId:G.organizationId,name:G.name,description:G.description,filters:G.filters,widgets:G.widgets,createdBy:G.createdBy,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt})),total:J.length}}})});var BO1;var pc0=k(()=>{F4();c1();NP();BO1=s1({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:zv.nullable().optional().describe("New global filters"),widgets:q.array(Dv).optional().describe("New widget definitions")}),outputSchema:$B,handler:async(Y,Q)=>{let X=v0(Q),J=await Q.storage.monitoringDashboards.get(Y.id);if(!J||J.organizationId!==X.id)throw Error(`Dashboard ${Y.id} not found`);let G={};if(Y.name!==void 0)G.name=Y.name;if(Y.description!==void 0)G.description=Y.description;if(Y.filters!==void 0)G.filters=Y.filters;if(Y.widgets!==void 0)G.widgets=Y.widgets;let K=await Q.storage.monitoringDashboards.update(Y.id,G);return{id:K.id,organizationId:K.organizationId,name:K.name,description:K.description,filters:K.filters,widgets:K.widgets,createdBy:K.createdBy,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt,updatedAt:K.updatedAt instanceof Date?K.updatedAt.toISOString():K.updatedAt}}})});var UO1;var cc0=k(()=>{F4();c1();UO1=s1({name:"MONITORING_DASHBOARD_DELETE",description:"Delete a monitoring dashboard",annotations:{title:"Delete Monitoring Dashboard",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({id:q.string().describe("Dashboard ID to delete")}),outputSchema:q.object({success:q.boolean().describe("Whether the deletion was successful")}),handler:async(Y,Q)=>{let X=v0(Q),J=await Q.storage.monitoringDashboards.get(Y.id);if(!J||J.organizationId!==X.id)throw Error(`Dashboard ${Y.id} not found`);return await Q.storage.monitoringDashboards.delete(Y.id),{success:!0}}})});var DO1;var nc0=k(()=>{F4();c1();NP();DO1=s1({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(uc0).describe("Widget query results"),timeRange:q.object({startDate:q.string(),endDate:q.string()}).describe("Time range used for the query")}),handler:async(Y,Q)=>{let X=v0(Q),J=await Q.storage.monitoringDashboards.get(Y.dashboardId);if(!J||J.organizationId!==X.id)throw Error(`Dashboard ${Y.dashboardId} not found`);let G=new Date,K=Y.timeRange?.startDate?new Date(Y.timeRange.startDate):new Date(G.getTime()-86400000),W=Y.timeRange?.endDate?new Date(Y.timeRange.endDate):G,Z=await Promise.all(J.widgets.map(async(H)=>{let $=J.filters?.propertyFilters,F=Y.propertyFilters,V=$||F?{properties:{...$,...F?.properties},propertyKeys:F?.propertyKeys,propertyPatterns:F?.propertyPatterns,propertyInValues:F?.propertyInValues}:void 0,B={connectionIds:H.filter?.connectionIds??J.filters?.connectionIds??void 0,virtualMcpIds:J.filters?.virtualMcpIds??void 0,toolNames:H.filter?.toolNames??J.filters?.toolNames??void 0,startDate:K,endDate:W,propertyFilters:V};try{let U=await Q.storage.monitoring.aggregate({organizationId:X.id,path:H.source.path,from:H.source.from,aggregation:H.aggregation.fn,groupBy:H.aggregation.groupBy,interval:H.aggregation.interval,filters:B});return{widgetId:H.id,value:U.value,groups:U.groups,timeseries:U.timeseries}}catch(U){return console.error(`Widget ${H.id} aggregation failed:`,U),{widgetId:H.id,value:null,groups:void 0,timeseries:void 0}}}));return{dashboardId:Y.dashboardId,results:Z,timeRange:{startDate:K.toISOString(),endDate:W.toISOString()}}}})});var jg6,zO1;var ic0=k(()=>{F4();c1();jg6=q.object({type:q.enum(["metric","timeseries","table"]),source:q.object({path:q.string().describe("JSONPath to extract value from"),from:q.enum(["input","output"]).describe("Extract from input or output")}),aggregation:q.object({fn:q.enum(["sum","avg","min","max","count","last"]).describe("Aggregation function"),groupBy:q.string().optional().describe("JSONPath for grouping (table)"),interval:q.string().optional().describe("Time interval for timeseries (15m, 1h, 1d)")}),filter:q.object({connectionIds:q.array(q.string()).optional(),toolNames:q.array(q.string()).optional()}).optional()}),zO1=s1({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:jg6.describe("Widget configuration to preview"),timeRange:q.object({startDate:q.string().datetime().describe("Start of time range (ISO 8601)"),endDate:q.string().datetime().describe("End of time range (ISO 8601)")}).optional().describe("Time range for the query (defaults to last 24 hours)"),propertyFilters:q.object({properties:q.record(q.string(),q.string()).optional().describe("Exact match: property key equals value"),propertyKeys:q.array(q.string()).optional().describe("Exists: filter logs that have these property keys"),propertyPatterns:q.record(q.string(),q.string()).optional().describe("Pattern match: property value matches pattern (SQL LIKE)"),propertyInValues:q.record(q.string(),q.string()).optional().describe("In match: exact match within comma-separated values")}).optional().describe("Property filters to apply")}),outputSchema:q.object({value:q.number().nullable().optional().describe("Aggregated value"),groups:q.array(q.object({key:q.string(),value:q.number()})).optional().describe("Grouped results for table widgets"),timeseries:q.array(q.object({timestamp:q.string(),value:q.number()})).optional().describe("Timeseries data points"),matchedRecords:q.number().describe("Number of records that matched"),timeRange:q.object({startDate:q.string(),endDate:q.string()}).describe("Time range used for the query")}),handler:async(Y,Q)=>{let X=v0(Q),{widget:J,timeRange:G}=Y,K=new Date,W=G?.startDate?new Date(G.startDate):new Date(K.getTime()-86400000),Z=G?.endDate?new Date(G.endDate):K,H={connectionIds:J.filter?.connectionIds,toolNames:J.filter?.toolNames,startDate:W,endDate:Z,propertyFilters:Y.propertyFilters};try{let $=await Q.storage.monitoring.countMatched({organizationId:X.id,path:J.source.path,from:J.source.from,filters:H}),F=await Q.storage.monitoring.aggregate({organizationId:X.id,path:J.source.path,from:J.source.from,aggregation:J.aggregation.fn,groupBy:J.aggregation.groupBy,interval:J.aggregation.interval,filters:H});return{value:F.value,groups:F.groups,timeseries:F.timeseries,matchedRecords:$,timeRange:{startDate:W.toISOString(),endDate:Z.toISOString()}}}catch($){return console.error("Widget preview aggregation failed:",$),{value:null,matchedRecords:0,timeRange:{startDate:W.toISOString(),endDate:Z.toISOString()}}}}})});var ac0=k(()=>{mc0();lc0();dc0();pc0();cc0();nc0();ic0()});var OO1;var rc0=k(()=>{c1();F4();OO1=s1({name:"ORGANIZATION_CREATE",description:"Create a new organization",annotations:{title:"Create Organization",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:q.object({slug:q.string().min(1).max(50).regex(/^[a-z0-9-]+$/,"Slug must be lowercase alphanumeric with hyphens"),name:q.string().min(1).max(255),description:q.string().optional()}),outputSchema:q.object({id:q.string(),name:q.string(),slug:q.string(),logo:q.string().nullable().optional(),metadata:q.any().optional(),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),members:q.array(q.any()).optional()}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=EY(Q);if(!X)throw Error("User ID required to create organization");let J=await Q.boundAuth.organization.create({name:Y.name,slug:Y.slug,metadata:Y.description?{description:Y.description}:void 0,userId:X});if(!J)throw Error("Failed to create organization");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var NO1;var oc0=k(()=>{c1();F4();NO1=s1({name:"ORGANIZATION_LIST",description:"List all organizations user has access to",annotations:{title:"List Organizations",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({userId:q.string().optional()}),outputSchema:q.object({organizations:q.array(q.object({id:q.string(),name:q.string(),slug:q.string(),logo:q.string().nullable().optional(),metadata:q.any().optional(),createdAt:q.string().datetime().describe("ISO 8601 timestamp")}))}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=EY(Q),J=Y.userId||X;if(!J)throw Error("User ID required to list organizations");return{organizations:(await Q.boundAuth.organization.list(J)).map((K)=>({...K,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt}))}}})});var LO1;var sc0=k(()=>{c1();F4();LO1=s1({name:"ORGANIZATION_GET",description:"Get organization details by slug or ID",annotations:{title:"Get Organization",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({}),outputSchema:q.object({id:q.string(),name:q.string(),slug:q.string(),logo:q.string().nullable().optional(),metadata:q.any().optional(),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),members:q.array(q.any()).optional(),invitations:q.array(q.any()).optional()}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=await Q.boundAuth.organization.get();if(!X)throw Error("No active organization found");let J=new Date,G=X.invitations?.filter((K)=>new Date(K.expiresAt)>J);return{...X,invitations:G,createdAt:X.createdAt instanceof Date?X.createdAt.toISOString():X.createdAt}}})});var MO1;var tc0=k(()=>{c1();F4();MO1=s1({name:"ORGANIZATION_UPDATE",description:"Update an existing organization",annotations:{title:"Update Organization",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({id:q.string(),slug:q.string().min(1).max(50).regex(/^[a-z0-9-]+$/).optional(),name:q.string().min(1).max(255).optional(),description:q.string().optional()}),outputSchema:q.object({id:q.string(),name:q.string(),slug:q.string(),logo:q.string().nullable().optional(),metadata:q.any().optional(),createdAt:q.string().datetime().describe("ISO 8601 timestamp")}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X={};if(Y.name)X.name=Y.name;if(Y.slug)X.slug=Y.slug;if(Y.description)X.metadata={description:Y.description};let J=await Q.boundAuth.organization.update({organizationId:Y.id,data:X});if(!J)throw Error("Failed to update organization");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var wO1;var ec0=k(()=>{c1();F4();wO1=s1({name:"ORGANIZATION_DELETE",description:"Delete an organization",annotations:{title:"Delete Organization",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({id:q.string()}),outputSchema:q.object({success:q.boolean(),id:q.string()}),handler:async(Y,Q)=>{return D0(Q),await Q.access.check(),await Q.boundAuth.organization.delete(Y.id),{success:!0,id:Y.id}}})});var Ov;var AO1=k(()=>{c1();Ov=q.object({title:q.string(),url:q.string(),icon:q.string()})});var PO1;var Yn0=k(()=>{c1();F4();AO1();PO1=s1({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(Ov).nullable().optional(),enabled_plugins:q.array(q.string()).nullable().optional(),createdAt:q.string().datetime().optional().describe("ISO 8601 timestamp"),updatedAt:q.string().datetime().optional().describe("ISO 8601 timestamp")}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=Q.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");let J=await Q.storage.organizationSettings.get(X);if(!J)return{organizationId:X};return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt,updatedAt:J.updatedAt instanceof Date?J.updatedAt.toISOString():J.updatedAt}}})});var EO1;var Qn0=k(()=>{c1();F4();AO1();EO1=s1({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(Ov).optional(),enabled_plugins:q.array(q.string()).optional()}),outputSchema:q.object({organizationId:q.string(),sidebar_items:q.array(Ov).nullable().optional(),enabled_plugins:q.array(q.string()).nullable().optional(),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),updatedAt:q.string().datetime().describe("ISO 8601 timestamp")}),handler:async(Y,Q)=>{if(D0(Q),await Q.access.check(),Q.organization&&Q.organization.id!==Y.organizationId)throw Error("Cannot update settings for a different organization");let X=await Q.storage.organizationSettings.upsert(Y.organizationId,{sidebar_items:Y.sidebar_items,enabled_plugins:Y.enabled_plugins});return{...X,createdAt:X.createdAt instanceof Date?X.createdAt.toISOString():X.createdAt,updatedAt:X.updatedAt instanceof Date?X.updatedAt.toISOString():X.updatedAt}}})});var TO1;var Xn0=k(()=>{c1();F4();TO1=s1({name:"ORGANIZATION_MEMBER_ADD",description:"Add a member to an organization",annotations:{title:"Add Organization Member",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({organizationId:q.string().optional(),userId:q.string(),role:q.array(q.string())}),outputSchema:q.object({id:q.string(),organizationId:q.string(),userId:q.string(),role:q.union([q.string(),q.array(q.string())]),createdAt:q.string().datetime().describe("ISO 8601 timestamp")}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=Y.organizationId||Q.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");if(X!==Q.organization?.id)throw Error("Organization ID does not match authenticated organization");let J=await Q.boundAuth.organization.addMember({organizationId:X,userId:Y.userId,role:Y.role});if(!J)throw Error("Failed to add member");return{...J,role:J.role,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var CO1;var Jn0=k(()=>{c1();F4();CO1=s1({name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove a member from an organization",annotations:{title:"Remove Organization Member",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({organizationId:q.string().optional(),memberIdOrEmail:q.string()}),outputSchema:q.object({success:q.boolean(),memberIdOrEmail:q.string()}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=Y.organizationId||Q.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");return await Q.boundAuth.organization.removeMember({organizationId:X,memberIdOrEmail:Y.memberIdOrEmail}),{success:!0,memberIdOrEmail:Y.memberIdOrEmail}}})});var RO1;var Gn0=k(()=>{c1();F4();RO1=s1({name:"ORGANIZATION_MEMBER_LIST",description:"List all members in an organization",annotations:{title:"List Organization Members",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({limit:q.number().optional(),offset:q.number().optional()}),outputSchema:q.object({members:q.array(q.object({id:q.string(),organizationId:q.string(),userId:q.string(),role:q.string(),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),user:q.object({id:q.string(),name:q.string(),email:q.string(),image:q.string().optional()}).optional()}))}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=Q.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");let J=await Q.boundAuth.organization.listMembers({organizationId:X,limit:Y.limit,offset:Y.offset});return{members:(Array.isArray(J)?J:[]).map((K)=>({...K,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt}))}}})});var IO1;var Wn0=k(()=>{c1();F4();IO1=s1({name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Update a member's role in an organization",annotations:{title:"Update Member Role",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({organizationId:q.string().optional(),memberId:q.string(),role:q.array(q.string())}),outputSchema:q.object({id:q.string(),organizationId:q.string(),userId:q.string(),role:q.union([q.literal("admin"),q.literal("member"),q.literal("owner")]),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),user:q.object({email:q.string(),name:q.string(),image:q.string().optional()})}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=Y.organizationId||Q.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");let J=await Q.boundAuth.organization.updateMemberRole({organizationId:X,memberId:Y.memberId,role:Y.role});if(!J)throw Error("Failed to update member role");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var Zn0=k(()=>{rc0();oc0();sc0();tc0();ec0();Yn0();Qn0();Xn0();Jn0();Gn0();Wn0()});var vg6,Dr,_g6,qO,Kn0,zr;var BO=k(()=>{c1();vg6=q.object({banner:q.string().nullable(),bannerColor:q.string().nullable(),icon:q.string().nullable(),themeColor:q.string().nullable()}),Dr=q.object({banner:q.string().nullable().optional(),bannerColor:q.string().nullable().optional(),icon:q.string().nullable().optional(),themeColor:q.string().nullable().optional()}),_g6=q.object({id:q.string(),title:q.string(),icon:q.string().nullable()}),qO=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:vg6.nullable(),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),updatedAt:q.string().datetime().describe("ISO 8601 timestamp")}),Kn0=qO.omit({organizationId:!0}).extend({boundConnections:q.array(_g6)}),zr=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 jO1;var Hn0=k(()=>{c1();F4();BO();jO1=s1({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(Kn0)}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=await Q.storage.projects.list(Y.organizationId),J=X.map((K)=>K.id),G=await Q.storage.projectPluginConfigs.getBoundConnectionsForProjects(J);return{projects:X.map((K)=>({id:K.id,slug:K.slug,name:K.name,description:K.description,enabledPlugins:K.enabledPlugins,ui:K.ui,boundConnections:G.get(K.id)??[],createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt,updatedAt:K.updatedAt instanceof Date?K.updatedAt.toISOString():K.updatedAt}))}}})});var SO1;var $n0=k(()=>{c1();F4();BO();SO1=s1({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:qO.nullable()}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=null;if(Y.projectId)X=await Q.storage.projects.get(Y.projectId);else if(Y.slug)X=await Q.storage.projects.getBySlug(Y.organizationId,Y.slug);if(!X)return{project:null};return{project:{id:X.id,organizationId:X.organizationId,slug:X.slug,name:X.name,description:X.description,enabledPlugins:X.enabledPlugins,ui:X.ui,createdAt:X.createdAt instanceof Date?X.createdAt.toISOString():X.createdAt,updatedAt:X.updatedAt instanceof Date?X.updatedAt.toISOString():X.updatedAt}}}})});var kO1;var Fn0=k(()=>{c1();KY();F4();BO();kO1=s1({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:Dr.nullable().optional().describe("UI customization")}),outputSchema:q.object({project:qO}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let{organizationId:X,slug:J,name:G,description:K,enabledPlugins:W,ui:Z}=Y;if(J===k3)throw Error(`Slug "${k3}" is reserved`);if(await Q.storage.projects.getBySlug(X,J))throw Error(`Project with slug "${J}" already exists in this organization`);let $=Z?{banner:Z.banner??null,bannerColor:Z.bannerColor??null,icon:Z.icon??null,themeColor:Z.themeColor??null}:null,F=await Q.storage.projects.create({organizationId:X,slug:J,name:G,description:K??null,enabledPlugins:W??null,ui:$});return{project:{id:F.id,organizationId:F.organizationId,slug:F.slug,name:F.name,description:F.description,enabledPlugins:F.enabledPlugins,ui:F.ui,createdAt:F.createdAt instanceof Date?F.createdAt.toISOString():F.createdAt,updatedAt:F.updatedAt instanceof Date?F.updatedAt.toISOString():F.updatedAt}}}})});var vO1;var Vn0=k(()=>{c1();F4();BO();vO1=s1({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:Dr.nullable().optional().describe("Updated UI customization")}),outputSchema:q.object({project:qO.nullable()}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let{projectId:X,name:J,description:G,enabledPlugins:K,ui:W}=Y,Z={};if(J!==void 0)Z.name=J;if(G!==void 0)Z.description=G;if(K!==void 0)Z.enabledPlugins=K;if(W!==void 0)Z.ui=W?{banner:W.banner??null,bannerColor:W.bannerColor??null,icon:W.icon??null,themeColor:W.themeColor??null}:null;let H=await Q.storage.projects.update(X,Z);if(!H)return{project:null};return{project:{id:H.id,organizationId:H.organizationId,slug:H.slug,name:H.name,description:H.description,enabledPlugins:H.enabledPlugins,ui:H.ui,createdAt:H.createdAt instanceof Date?H.createdAt.toISOString():H.createdAt,updatedAt:H.updatedAt instanceof Date?H.updatedAt.toISOString():H.updatedAt}}}})});var _O1;var qn0=k(()=>{c1();KY();F4();_O1=s1({name:"PROJECT_DELETE",description:"Delete a project (cannot delete org-admin)",annotations:{title:"Delete Project",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({projectId:q.string().describe("Project ID to delete")}),outputSchema:q.object({success:q.boolean(),message:q.string().optional()}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let{projectId:X}=Y,J=await Q.storage.projects.get(X);if(!J)return{success:!1,message:"Project not found"};if(J.slug===k3)return{success:!1,message:"Cannot delete the org-admin project"};return{success:await Q.storage.projects.delete(X)}}})});var yO1;var Bn0=k(()=>{c1();F4();BO();yO1=s1({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:zr.nullable()}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let{projectId:X,pluginId:J}=Y,G=await Q.storage.projectPluginConfigs.get(X,J);if(!G)return{config:null};return{config:{id:G.id,projectId:G.projectId,pluginId:G.pluginId,connectionId:G.connectionId,settings:G.settings,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}}}})});var fO1;var Un0=k(()=>{c1();F4();BO();$r();fO1=s1({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:zr}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let{projectId:X,pluginId:J,connectionId:G,settings:K}=Y,W=EY(Q),Z=await Q.storage.projects.get(X);if(!Z)throw Error(`Project not found: ${X}`);let H=G?await Q.storage.connections.findById(G):null;if(G&&Z.organizationId&&!H&&FP()){if(Hr(G,Z.organizationId)){if(!W)throw Error("User ID required to create dev-assets connection");let F=VP(Z.organizationId,K7());await Q.storage.connections.create({...F,organization_id:Z.organizationId,created_by:W})}}let $=await Q.storage.projectPluginConfigs.upsert(X,J,{connectionId:G,settings:K});return{config:{id:$.id,projectId:$.projectId,pluginId:$.pluginId,connectionId:$.connectionId,settings:$.settings,createdAt:$.createdAt instanceof Date?$.createdAt.toISOString():$.createdAt,updatedAt:$.updatedAt instanceof Date?$.updatedAt.toISOString():$.updatedAt}}}})});var Dn0=k(()=>{Hn0();$n0();Fn0();Vn0();qn0();Bn0();Un0()});var bO1;var zn0=k(()=>{c1();F4();bO1=s1({name:"TAGS_LIST",description:"List all tags in an organization",annotations:{title:"List Tags",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({}),outputSchema:q.object({tags:q.array(q.object({id:q.string(),organizationId:q.string(),name:q.string(),createdAt:q.string().describe("ISO 8601 timestamp")}))}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=v0(Q);return{tags:(await Q.storage.tags.listOrgTags(X.id)).map((G)=>({...G,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():String(G.createdAt)}))}}})});var hO1;var On0=k(()=>{c1();F4();hO1=s1({name:"TAGS_CREATE",description:"Create a new tag in an organization",annotations:{title:"Create Tag",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:q.object({name:q.string().min(1).max(50).describe("Tag name")}),outputSchema:q.object({tag:q.object({id:q.string(),organizationId:q.string(),name:q.string(),createdAt:q.string().describe("ISO 8601 timestamp")})}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=v0(Q),J=await Q.storage.tags.createTag(X.id,Y.name);return{tag:{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():String(J.createdAt)}}}})});var xO1;var Nn0=k(()=>{c1();F4();xO1=s1({name:"TAGS_DELETE",description:"Delete a tag from an organization (removes from all members)",annotations:{title:"Delete Tag",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({tagId:q.string().describe("Tag ID to delete")}),outputSchema:q.object({success:q.boolean()}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=v0(Q),J=await Q.storage.tags.getTag(Y.tagId);if(!J)throw Error("Tag not found");if(J.organizationId!==X.id)throw Error("Tag does not belong to this organization");return await Q.storage.tags.deleteTag(Y.tagId),{success:!0}}})});var gO1;var Ln0=k(()=>{c1();F4();gO1=s1({name:"MEMBER_TAGS_GET",description:"Get tags assigned to a member",annotations:{title:"Get Member Tags",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({memberId:q.string().describe("Member ID")}),outputSchema:q.object({tags:q.array(q.object({id:q.string(),organizationId:q.string(),name:q.string(),createdAt:q.string().describe("ISO 8601 timestamp")}))}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=v0(Q);if(!await Q.storage.tags.verifyMemberOrg(Y.memberId,X.id))throw Error(`Member not found in this organization: ${Y.memberId}`);return{tags:(await Q.storage.tags.getMemberTags(Y.memberId)).map((K)=>({...K,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():String(K.createdAt)}))}}})});var uO1;var Mn0=k(()=>{c1();F4();uO1=s1({name:"MEMBER_TAGS_SET",description:"Set tags for a member (replaces all existing tags)",annotations:{title:"Set Member Tags",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({memberId:q.string().describe("Member ID"),tagIds:q.array(q.string()).describe("Array of tag IDs to assign")}),outputSchema:q.object({success:q.boolean(),tags:q.array(q.object({id:q.string(),organizationId:q.string(),name:q.string(),createdAt:q.string().describe("ISO 8601 timestamp")}))}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=v0(Q);if(!await Q.storage.tags.verifyMemberOrg(Y.memberId,X.id))throw Error(`Member not found in this organization: ${Y.memberId}`);for(let K of Y.tagIds){let W=await Q.storage.tags.getTag(K);if(!W)throw Error(`Tag not found: ${K}`);if(W.organizationId!==X.id)throw Error(`Tag does not belong to this organization: ${K}`)}return await Q.storage.tags.setMemberTags(Y.memberId,Y.tagIds),{success:!0,tags:(await Q.storage.tags.getMemberTags(Y.memberId)).map((K)=>({...K,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():String(K.createdAt)}))}}})});var wn0=k(()=>{zn0();On0();Nn0();Ln0();Mn0()});var An0=k(()=>{KY()});var Pn0,aH,En0,Tn0;var UO=k(()=>{c1();An0();Pn0=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")}),aH=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([...qM,"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")}),En0=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")}),Tn0=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 bg6,hg6,mO1;var Cn0=k(()=>{c1();F4();UO();$7();bg6=q.object({data:En0.describe("Data for the new thread (id is auto-generated if not provided)")}),hg6=q.object({item:aH.describe("The created thread entity")}),mO1=s1({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:bg6,outputSchema:hg6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=EY(Q);if(!J)throw Error("User ID required to create thread");let G=Y.data.id??X9("thrd"),K=await Q.storage.threads.create({id:G,organization_id:X.id,title:Y.data.title,description:Y.data.description,created_by:J});return{item:{...K,hidden:K.hidden??!1}}}})});function FB(Y,Q=Date.now()){let X=Y.status;if(X==="in_progress"){let J=new Date(Y.updated_at).getTime();if(!Number.isFinite(J)||Q-J>1800000)X="expired"}return{...Y,status:X,hidden:Y.hidden??!1}}var xg6,gg6,lO1;var Rn0=k(()=>{MG();F4();UO();c1();xg6=uZ.extend({where:q.object({created_by:q.string().optional()}).optional()}),gg6=x$(aH),lO1=s1({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:xg6,outputSchema:gg6,handler:async(Y,Q)=>{await Q.access.check();let X=Q.auth.user?.id;if(!X)throw Error("User ID required to list threads");let J=v0(Q),G=Y.offset??0,K=Y.limit??100,{threads:W,total:Z}=await Q.storage.threads.list(J.id,X,{limit:K,offset:G}),H=G+K<Z,$=Date.now();return{items:W.map((F)=>FB(F,$)),totalCount:Z,hasMore:H}}})});var ug6,dO1;var In0=k(()=>{MG();F4();UO();ug6=TS(aH),dO1=s1({name:"COLLECTION_THREADS_GET",description:"Get thread details by ID",annotations:{title:"Get Thread",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:ES,outputSchema:ug6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=await Q.storage.threads.get(Y.id);if(!J||J.organization_id!==X.id)return{item:null};return{item:FB(J)}}})});var mg6,lg6,pO1;var jn0=k(()=>{c1();F4();UO();mg6=q.object({id:q.string().describe("ID of the thread to update"),data:Tn0.describe("Partial thread data to update")}),lg6=q.object({item:aH.describe("The updated thread entity")}),pO1=s1({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:mg6,outputSchema:lg6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=EY(Q);if(!J)throw Error("User ID required to update thread");let{id:G,data:K}=Y,W=await Q.storage.threads.get(G);if(!W||W.organization_id!==X.id)throw Error("Thread not found in organization");let Z=await Q.storage.threads.update(G,{title:K.title,description:K.description,hidden:K.hidden,updated_by:J});return{item:FB(Z)}}})});var cO1;var Sn0=k(()=>{MG();F4();UO();cO1=s1({name:"COLLECTION_THREADS_DELETE",description:"Delete a thread",annotations:{title:"Delete Thread",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:CS,outputSchema:RS(aH),handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=await Q.storage.threads.get(Y.id);if(!J)throw Error(`Thread not found: ${Y.id}`);if(J.organization_id!==X.id)throw Error(`Thread not found: ${Y.id}`);return await Q.storage.threads.delete(Y.id),{item:FB(J)}}})});function kn0(Y){if(!Y)return null;if("field"in Y&&Y.field[0]==="thread_id"&&Y.operator==="eq")return String(Y.value);if("conditions"in Y)for(let Q of Y.conditions){let X=kn0(Q);if(X)return X}return null}var dg6,nO1;var vn0=k(()=>{MG();F4();UO();dg6=x$(Pn0),nO1=s1({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:uZ,outputSchema:dg6,handler:async(Y,Q)=>{let X=v0(Q);await Q.access.check();let J=kn0(Y.where);if(!J)throw Error("thread_id filter is required in where clause");let G=await Q.storage.threads.get(J);if(!G||G.organization_id!==X.id)return{items:[],totalCount:0,hasMore:!1};let K=Y.offset??0,W=Y.limit??100,{messages:Z,total:H}=await Q.storage.threads.listMessages(J,{limit:W,offset:K}),$=K+W<H;return{items:Z,totalCount:H,hasMore:$}}})});var _n0=k(()=>{Cn0();Rn0();In0();jn0();Sn0();vn0()});var cg6,ng6,iO1;var yn0=k(()=>{c1();F4();cg6=q.object({id:q.string().min(1)}),ng6=q.object({user:q.object({id:q.string(),name:q.string(),email:q.string(),image:q.string().nullable()}).nullable()}),iO1=s1({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:cg6,outputSchema:ng6,handler:async(Y,Q)=>{await Q.access.check(),D0(Q);let X=EY(Q);if(!X)throw Error("Authentication required");let J=await Q.storage.users.findById(Y.id,X);if(!J)return{user:null};return{user:{id:J.id,name:J.name,email:J.email,image:J.image??null}}}})});var fn0=k(()=>{yn0()});var hn0={};RY(hn0,{managementMCP:()=>aO1,ALL_TOOLS:()=>bn0});var ag6,rg6,bn0,aO1=async(Y)=>{let Q=null;if(Y.organization){let G=await Y.storage.organizationSettings.get(Y.organization.id),K=await Y.storage.projects.list(Y.organization.id),W=new Set(G?.enabled_plugins??[]);for(let Z of K)if(Z.enabledPlugins)for(let H of Z.enabledPlugins)W.add(H);Q=W.size>0?[...W]:null}let X=yd0(bn0,Q),J=new OD({name:"mcp-mesh-management",version:"1.0.0"},{capabilities:{tools:{}}});for(let G of X){let K=G.inputSchema&&typeof G.inputSchema==="object"&&"shape"in G.inputSchema?G.inputSchema:q.object({}),W=G.outputSchema&&typeof G.outputSchema==="object"&&"shape"in G.outputSchema?G.outputSchema:void 0,Z=K.shape,H=W?.shape;J.registerTool(G.name,{description:G.description??"",inputSchema:Z,outputSchema:H,annotations:G.annotations},async($)=>{Y.access.setToolName(G.name);try{let F=await G.execute($,Y);return{content:[{type:"text",text:JSON.stringify(F)}],structuredContent:F}}catch(F){return{content:[{type:"text",text:`Error: ${F.message}`}],isError:!0}}})}return J};var rO1=k(()=>{Yr();rm();c1();ed0();zp0();$c0();Bc0();Pc0();Sc0();bc0();gc0();ac0();Zn0();Dn0();wn0();_n0();fn0();ag6=[OO1,NO1,LO1,MO1,wO1,PO1,EO1,TO1,CO1,RO1,IO1,Dz1,Nz1,Lz1,mz1,lz1,dz1,sz1,ez1,YO1,QO1,XO1,JO1,GO1,WO1,ZO1,KO1,qc0,HO1,$O1,FO1,VO1,qO1,BO1,UO1,DO1,zO1,Gz1,Zz1,Kz1,Wz1,pz1,cz1,nz1,iz1,az1,rz1,oz1,iO1,qz1,Bz1,Uz1,mO1,lO1,dO1,pO1,cO1,nO1,bO1,hO1,xO1,gO1,uO1,jO1,SO1,kO1,vO1,_O1,yO1,fO1],rg6=fd0(),bn0=[...ag6,...rg6]});function og6(Y){return[{permissions:{self:["*"]},getTools:async()=>{let{ALL_TOOLS:Q}=await Promise.resolve().then(() => (rO1(),hn0));return Q.map((X)=>{return{name:X.name,inputSchema:q.toJSONSchema(X.inputSchema,{unrepresentable:"any"}),outputSchema:X.outputSchema?q.toJSONSchema(X.outputSchema,{unrepresentable:"any"}):void 0,description:X.description}})},data:U71(K7(),Y)},{data:B71()},{data:q71(Y)}]}async function xn0(Y,Q){try{let X=Pn(),J=new Rz(process.env.ENCRYPTION_KEY||""),G=new DS(X.db,J),K=new zS(X.db),W=og6(Y);try{await K.create({organizationId:Y,slug:k3,name:hb,description:"Organization administration and settings",enabledPlugins:null,ui:null})}catch(Z){console.warn("Could not create org-admin project (may already exist):",Z)}await Promise.all(W.map(async(Z)=>{let H=null;if(Z.permissions)H=(await BF.api.createApiKey({body:{name:`${Z.data.app_name??crypto.randomUUID()}-mcp`,userId:Q,permissions:Z.permissions,rateLimitEnabled:!1,metadata:{organization:{id:Y},purpose:"default-org-connections"}}}))?.key;let $=await DA({id:"pending",title:Z.data.title,connection_type:Z.data.connection_type,connection_url:Z.data.connection_url,connection_token:Z.data.connection_token,connection_headers:Z.data.connection_headers}).catch(()=>null),F=await Z.getTools?.()??$?.tools??null,V=$?.scopes?.length?$.scopes:null,B=Z.data.id?Z.data.id.startsWith(`${Y}_`)?Z.data.id:`${Y}_${Z.data.id}`:void 0;await G.create({...Z.data,id:B,tools:F,configuration_scopes:V,organization_id:Y,created_by:Q,connection_token:Z.data.connection_token??H})}))}catch(X){console.error("Error creating default MCP connections:",X)}}var gn0=k(()=>{KY();En();Tn();VV1();qV1();kn();c1();Kv()});var oO1,Or;var Nr=k(()=>{oO1=["owner","admin","user"],Or=["owner","admin"]});var sg6=(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"}}}}]}},un0=(Y)=>{if(Y.providerId==="microsoft")return sg6(Y);throw Error(`Unsupported provider: ${Y.providerId}`)};function tg6(Y){return Y.toLowerCase().trim().replace(/[^a-z0-9\s_-]+/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function eg6(){let Y=Math.floor(Math.random()*ln0.length),Q=Math.floor(Math.random()*mn0.length),X=ln0[Y]??"deco",J=mn0[Q]??"studio";return`${X}-${J}`}function Hu6(){let Y=[Nv],Q=new URL(Nv);if(Q.hostname==="localhost")Y.push(Nv.replace("localhost","127.0.0.1"));else if(Q.hostname==="127.0.0.1")Y.push(Nv.replace("127.0.0.1","localhost"));return Y}var mn0,ln0,Yu6,Qu6,Lr,Xu6,Ju6,Gu6,dn0,p9,pn0=void 0,sO1=void 0,tO1=!1,Wu6,Zu6,Ku6,Nv,BF;var Kv=k(()=>{l71();CP0();q20();e31();AF1();GT0();QS();VT0();En();FV1();rR0();gn0();Nr();mn0=["labs","agent","studio","workspace","systems","core","cloud","works"],ln0=["capybara","guarana","deco","samba","feijoada","capoeira","carnival"];Yu6=Object.values(hR()).map((Y)=>Y.map((Q)=>Q.name)).flat(),Qu6={...ac,self:["*",...Yu6]},Lr=vH(Qu6),Xu6=Lr.newRole({self:["*"],...cj.statements}),Ju6=Lr.newRole({self:["*"],...cj.statements}),Gu6=Lr.newRole({self:["*"],...cj.statements}),dn0=Object.values(hR()).map((Y)=>Y.map((Q)=>`self:${Q.name}`)).flat(),p9=YS.auth;if(p9.inviteEmailProviderId&&p9.emailProviders&&p9.emailProviders.length>0){let Y=BS(p9.emailProviders,p9.inviteEmailProviderId);if(Y){let Q=qS(Y);pn0=async(X)=>{let J=X.inviter.user?.name||X.inviter.user?.email,G=`${K7()}/auth/accept-invitation?invitationId=${X.invitation.id}&redirectTo=/`;await Q({to:X.email,subject:`Invitation to join ${X.organization.name}`,html:`
|
|
1331
|
+
`.execute(Y)).rows[0]?.exists)await k8`CREATE ROLE ${k8.id(X)} NOLOGIN`.execute(Y);await k8`GRANT ${k8.id(X)} TO CURRENT_USER`.execute(Y),await k8`GRANT USAGE, CREATE ON SCHEMA ${k8.id(Q)} TO ${k8.id(X)}`.execute(Y),await k8`GRANT ALL ON ALL TABLES IN SCHEMA ${k8.id(Q)} TO ${k8.id(X)}`.execute(Y),await k8`GRANT ALL ON ALL SEQUENCES IN SCHEMA ${k8.id(Q)} TO ${k8.id(X)}`.execute(Y),await k8`ALTER DEFAULT PRIVILEGES IN SCHEMA ${k8.id(Q)} GRANT ALL ON TABLES TO ${k8.id(X)}`.execute(Y),await k8`ALTER DEFAULT PRIVILEGES IN SCHEMA ${k8.id(Q)} GRANT ALL ON SEQUENCES TO ${k8.id(X)}`.execute(Y),await k8`REVOKE ALL ON SCHEMA public FROM ${k8.id(X)}`.execute(Y)}async function cx6(Y,Q,X,J){try{return await Y.transaction().execute(async(G)=>{return await k8`SET LOCAL ROLE ${k8.id(X)}`.execute(G),await k8`SET LOCAL search_path TO ${k8.id(Q)}`.execute(G),await k8.raw(J).execute(G)})}catch(G){if(dx6(G))return await px6(Y,Q,X),await Y.transaction().execute(async(K)=>{return await k8`SET LOCAL ROLE ${k8.id(X)}`.execute(K),await k8`SET LOCAL search_path TO ${k8.id(Q)}`.execute(K),await k8.raw(J).execute(K)});throw G}}var xx6,ux6,qc0;var Bc0=k(()=>{c1();F4();xx6=q.object({results:q.array(q.unknown()).optional(),success:q.boolean().optional()});ux6=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()});qc0=s1({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:ux6,outputSchema:q.object({result:q.array(xx6)}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=gx6(Y.sql,Y.params||[]);if(!Q.connectionId)throw Error("Connection context required for database access");let J=mx6(Q.connectionId),G=lx6(Q.connectionId);return{result:[{results:(await cx6(Q.db,J,G,X)).rows,success:!0}]}}})});var Uc0,ix6,Dc0;var qF=k(()=>{c1();lS();Uc0=q.object({connectionId:q.string().optional().describe("Filter subscriptions by connection ID (optional)")}),ix6=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)")}),Dc0=q.object({subscriptions:q.array(ix6).describe("List of subscriptions")})});var pz1;var zc0=k(()=>{F4();qF();pz1=s1({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:IS,outputSchema:jS,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=Q.connectionId;if(!J)throw Error("Connection ID required to publish events. Use a connection-scoped token.");let G=await Q.eventBus.publish(X.id,J,{type:Y.type,subject:Y.subject,data:Y.data,deliverAt:Y.deliverAt,cron:Y.cron});return{id:G.id,type:G.type,source:G.source,time:G.time}}})});var cz1;var Oc0=k(()=>{F4();qF();cz1=s1({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:SS,outputSchema:kS,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=Q.connectionId;if(!J)throw Error("Connection ID required to subscribe. Use a connection-scoped token.");let G=await Q.eventBus.subscribe(X.id,{connectionId:J,eventType:Y.eventType,publisher:Y.publisher,filter:Y.filter});return{subscription:{id:G.id,connectionId:G.connectionId,eventType:G.eventType,publisher:G.publisher,filter:G.filter,enabled:G.enabled,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}}}})});var nz1;var Nc0=k(()=>{F4();qF();nz1=s1({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:yS,outputSchema:fS,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=Q.connectionId;if(!J)throw Error("Connection ID required to unsubscribe. Use a connection-scoped token.");let G=await Q.eventBus.getSubscription(X.id,Y.subscriptionId);if(!G)throw Error(`Subscription not found: ${Y.subscriptionId}`);if(G.connectionId!==J)throw Error("Cannot unsubscribe from a subscription owned by another connection");return{success:(await Q.eventBus.unsubscribe(X.id,Y.subscriptionId)).success,subscriptionId:Y.subscriptionId}}})});var iz1;var Lc0=k(()=>{F4();qF();iz1=s1({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:bS,outputSchema:hS,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=Q.connectionId;if(!J)throw Error("Connection ID required to cancel events. Use a connection-scoped token.");if(!await Q.eventBus.getEvent(X.id,Y.eventId))throw Error(`Event not found: ${Y.eventId}`);if(!(await Q.eventBus.cancelEvent(X.id,Y.eventId,J)).success)throw Error("Failed to cancel event. Either the event is already completed/failed, or you are not the publisher.");return{success:!0,eventId:Y.eventId}}})});var az1;var Mc0=k(()=>{F4();qF();az1=s1({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:xS,outputSchema:gS,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=Q.connectionId;if(!J)throw Error("Connection ID required to acknowledge events. Use a connection-scoped token.");if(!(await Q.eventBus.ackEvent(X.id,Y.eventId,J)).success)throw Error("Failed to acknowledge event. Either the event was not found, already delivered, or you are not a subscriber.");return{success:!0,eventId:Y.eventId}}})});var rz1;var wc0=k(()=>{F4();qF();rz1=s1({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:Uc0,outputSchema:Dc0,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);return await Q.access.check(),{subscriptions:(await Q.eventBus.listSubscriptions(X.id,Y.connectionId)).map((G)=>({id:G.id,connectionId:G.connectionId,eventType:G.eventType,publisher:G.publisher,filter:G.filter,enabled:G.enabled,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}))}}})});var oz1;var Ac0=k(()=>{F4();qF();oz1=s1({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:vS,outputSchema:_S,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=Q.connectionId;if(!J)throw Error("Connection ID required to sync subscriptions. Use a connection-scoped token.");let G=await Q.eventBus.syncSubscriptions(X.id,{connectionId:J,subscriptions:Y.subscriptions});return{created:G.created,updated:G.updated,deleted:G.deleted,unchanged:G.unchanged,subscriptions:G.subscriptions.map((K)=>({id:K.id,connectionId:K.connectionId,eventType:K.eventType,publisher:K.publisher,filter:K.filter,enabled:K.enabled,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt,updatedAt:K.updatedAt instanceof Date?K.updatedAt.toISOString():K.updatedAt}))}}})});var Pc0=k(()=>{zc0();Oc0();Nc0();Lc0();Mc0();wc0();Ac0();qF()});var OP=k(()=>{nm()});function Ec0(){return`/icons/capy-${Math.floor(Math.random()*39)+0}.png`}var rx6,ox6,sz1;var Tc0=k(()=>{c1();F4();OP();rx6=q.object({data:CR.describe("Data for the new virtual MCP")}),ox6=q.object({item:lG.describe("The created virtual MCP entity")}),sz1=s1({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:rx6,outputSchema:ox6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=EY(Q);if(!J)throw Error("User ID required to create virtual MCP");let G={...Y.data,icon:Y.data.icon??Ec0()};return{item:await Q.storage.virtualMcps.create(X.id,J,G)}}})});function sx6(Y){let Q=[],X=0;while(X<Y.length){let J=Y[X];if(J==="%")Q.push(".*");else if(J==="_")Q.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))Q.push("\\"+J);else Q.push(J);X++}return Q.join("")}function HB(Y){return typeof Y==="string"||typeof Y==="number"}function tz1(Y,Q){let X=Q.split("."),J=Y;for(let G of X){if(J==null||typeof J!=="object")return;J=J[G]}return J}function tx6(Y,Q){return Y.connections.some((X)=>X.connection_id===Q)}function Ur(Y,Q){if("conditions"in Q){let{operator:Z,conditions:H}=Q;switch(Z){case"and":return H.every(($)=>Ur(Y,$));case"or":return H.some(($)=>Ur(Y,$));case"not":return!H.every(($)=>Ur(Y,$));default:return!0}}let{field:X,operator:J,value:G}=Q,K=X.join(".");if(K==="connection_id"){if(J!=="eq"||typeof G!=="string")return!1;return tx6(Y,G)}let W=tz1(Y,K);switch(J){case"eq":return W===G;case"gt":return HB(W)&&HB(G)&&W>G;case"gte":return HB(W)&&HB(G)&&W>=G;case"lt":return HB(W)&&HB(G)&&W<G;case"lte":return HB(W)&&HB(G)&&W<=G;case"in":return Array.isArray(G)&&G.includes(W);case"like":if(typeof W!=="string"||typeof G!=="string")return!1;if(G.length>100)return!1;let Z=sx6(G);return new RegExp(`^${Z}$`,"i").test(W);case"contains":if(typeof W!=="string"||typeof G!=="string")return!1;return W.toLowerCase().includes(G.toLowerCase());default:return!0}}function ex6(Y,Q){return[...Y].sort((X,J)=>{for(let G of Q){let K=G.field.join("."),W=tz1(X,K),Z=tz1(J,K),H=0;if(W==null&&Z==null)continue;if(W==null)H=G.nulls==="first"?-1:1;else if(Z==null)H=G.nulls==="first"?1:-1;else if(typeof W==="string"&&typeof Z==="string")H=W.localeCompare(Z);else if(typeof W==="number"&&typeof Z==="number")H=W-Z;else H=String(W).localeCompare(String(Z));if(H!==0)return G.direction==="desc"?-H:H}return 0})}var Yg6,Qg6,ez1;var Cc0=k(()=>{MG();F4();OP();Yg6=uZ,Qg6=x$(lG),ez1=s1({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:Yg6,outputSchema:Qg6,handler:async(Y,Q)=>{await Q.access.check();let X=v0(Q),J=Y.where&&!("conditions"in Y.where)&&Y.where.field.join(".")==="connection_id"&&Y.where.operator==="eq"&&typeof Y.where.value==="string"?Y.where.value:void 0,K=J?await Q.storage.virtualMcps.listByConnectionId(X.id,J):await Q.storage.virtualMcps.list(X.id);if(Y.where)K=K.filter((V)=>Ur(V,Y.where));if(Y.orderBy&&Y.orderBy.length>0)K=ex6(K,Y.orderBy);let W=K.length,Z=Y.offset??0,H=Y.limit??100,$=K.slice(Z,Z+H),F=Z+H<W;return{items:$,totalCount:W,hasMore:F}}})});var Xg6,Jg6,YO1;var Rc0=k(()=>{c1();F4();OP();Xg6=q.object({id:q.string().describe("ID of the virtual MCP to retrieve")}),Jg6=q.object({item:lG.nullable().describe("The retrieved virtual MCP, or null if not found")}),YO1=s1({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:Xg6,outputSchema:Jg6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.id);if(J&&J.organization_id!==X.id)return{item:null};if(!J)return{item:null};return{item:J}}})});var Gg6,Wg6,QO1;var Ic0=k(()=>{c1();F4();OP();Gg6=q.object({id:q.string().describe("ID of the virtual MCP to update"),data:RR.describe("Partial virtual MCP data to update")}),Wg6=q.object({item:lG.describe("The updated virtual MCP entity")}),QO1=s1({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:Gg6,outputSchema:Wg6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=EY(Q);if(!J)throw Error("User ID required to update virtual MCP");let G=await Q.storage.virtualMcps.findById(Y.id);if(!G)throw Error(`Virtual MCP not found: ${Y.id}`);if(G.organization_id!==X.id)throw Error(`Virtual MCP not found: ${Y.id}`);return{item:await Q.storage.virtualMcps.update(Y.id,J,Y.data)}}})});var Zg6,Kg6,XO1;var jc0=k(()=>{c1();F4();OP();Zg6=q.object({id:q.string().describe("ID of the virtual MCP to delete")}),Kg6=q.object({item:lG.describe("The deleted virtual MCP entity")}),XO1=s1({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:Zg6,outputSchema:Kg6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.id);if(!J)throw Error(`Virtual MCP not found: ${Y.id}`);if(J.organization_id!==X.id)throw Error(`Virtual MCP not found: ${Y.id}`);return await Q.storage.virtualMcps.delete(Y.id),{item:J}}})});var Sc0=k(()=>{Tc0();Cc0();Rc0();Ic0();jc0()});var $g6,Fg6,JO1;var kc0=k(()=>{c1();F4();VF();$g6=q.object({virtual_mcp_id:q.string().describe("ID of the Virtual MCP to add the tool to"),data:pp0.describe("Virtual tool data")}),Fg6=q.object({item:iH.describe("The created virtual tool")}),JO1=s1({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:$g6,outputSchema:Fg6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!J||J.organization_id!==X.id)throw Error(`Virtual MCP not found: ${Y.virtual_mcp_id}`);let G=Y.data.connection_dependencies??[];return{item:await Q.storage.virtualMcps.createVirtualTool(Y.virtual_mcp_id,Y.data,G)}}})});var Vg6,qg6,GO1;var vc0=k(()=>{c1();F4();VF();Vg6=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")}),qg6=q.object({items:q.array(iH).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")}),GO1=s1({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:Vg6,outputSchema:qg6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!J||J.organization_id!==X.id)return{items:[],totalCount:0,hasMore:!1};let G=await Q.storage.virtualMcps.listVirtualTools(Y.virtual_mcp_id),K=G.length,W=Y.offset??0,Z=Y.limit??100,H=G.slice(W,W+Z),$=W+Z<K;return{items:H,totalCount:K,hasMore:$}}})});var Bg6,Ug6,WO1;var _c0=k(()=>{c1();F4();VF();Bg6=q.object({virtual_mcp_id:q.string().describe("ID of the Virtual MCP"),name:q.string().describe("Name of the virtual tool to retrieve")}),Ug6=q.object({item:iH.nullable().describe("The retrieved virtual tool, or null if not found")}),WO1=s1({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:Bg6,outputSchema:Ug6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!J||J.organization_id!==X.id)return{item:null};return{item:await Q.storage.virtualMcps.getVirtualTool(Y.virtual_mcp_id,Y.name)}}})});var Dg6,zg6,ZO1;var yc0=k(()=>{c1();F4();VF();Dg6=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:cp0.describe("Partial virtual tool data to update")}),zg6=q.object({item:iH.describe("The updated virtual tool")}),ZO1=s1({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:Dg6,outputSchema:zg6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!J||J.organization_id!==X.id)throw Error(`Virtual MCP not found: ${Y.virtual_mcp_id}`);if(!await Q.storage.virtualMcps.getVirtualTool(Y.virtual_mcp_id,Y.name))throw Error(`Virtual tool not found: ${Y.name}`);let K=Y.data.connection_dependencies;return{item:await Q.storage.virtualMcps.updateVirtualTool(Y.virtual_mcp_id,Y.name,Y.data,K)}}})});var Og6,Ng6,KO1;var fc0=k(()=>{c1();F4();VF();Og6=q.object({virtual_mcp_id:q.string().describe("ID of the Virtual MCP"),name:q.string().describe("Name of the virtual tool to delete")}),Ng6=q.object({item:iH.describe("The deleted virtual tool")}),KO1=s1({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:Og6,outputSchema:Ng6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!J||J.organization_id!==X.id)throw Error(`Virtual MCP not found: ${Y.virtual_mcp_id}`);let G=await Q.storage.virtualMcps.getVirtualTool(Y.virtual_mcp_id,Y.name);if(!G)throw Error(`Virtual tool not found: ${Y.name}`);return await Q.storage.virtualMcps.deleteVirtualTool(Y.virtual_mcp_id,Y.name),{item:G}}})});var bc0=k(()=>{kc0();vc0();_c0();yc0();fc0()});var Mg6,HO1;var hc0=k(()=>{F4();c1();Mg6=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")}),HO1=s1({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(Mg6).describe("Array of monitoring logs"),total:q.number().describe("Total number of logs matching filters"),offset:q.number().describe("Current offset for pagination"),limit:q.number().describe("Current limit for pagination")}),handler:async(Y,Q)=>{let X=v0(Q),G=Y.properties||Y.propertyKeys||Y.propertyPatterns||Y.propertyInValues?{properties:Y.properties,propertyKeys:Y.propertyKeys,propertyPatterns:Y.propertyPatterns,propertyInValues:Y.propertyInValues}:void 0,K={organizationId:X.id,connectionId:Y.connectionId,excludeConnectionIds:Y.excludeConnectionIds,virtualMcpId:Y.virtualMcpId,toolName:Y.toolName,isError:Y.isError,startDate:Y.startDate?new Date(Y.startDate):void 0,endDate:Y.endDate?new Date(Y.endDate):void 0,limit:Y.limit,offset:Y.offset,propertyFilters:G},W=await Q.storage.monitoring.query(K);return{logs:W.logs.map((Z)=>({...Z,timestamp:Z.timestamp instanceof Date?Z.timestamp.toISOString():Z.timestamp})),total:W.total,offset:Y.offset,limit:Y.limit}}})});var $O1;var xc0=k(()=>{F4();c1();$O1=s1({name:"MONITORING_STATS",description:"Get aggregated statistics for tool call monitoring",annotations:{title:"Get Monitoring Stats",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({startDate:q.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:q.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)")}),outputSchema:q.object({totalCalls:q.number().describe("Total number of tool calls"),errorRate:q.number().describe("Error rate as a decimal (0 to 1)"),avgDurationMs:q.number().describe("Average call duration in milliseconds"),errorRatePercent:q.string().describe("Error rate as a percentage string")}),handler:async(Y,Q)=>{let J={organizationId:v0(Q).id,startDate:Y.startDate?new Date(Y.startDate):void 0,endDate:Y.endDate?new Date(Y.endDate):void 0},G=await Q.storage.monitoring.getStats(J);return{...G,errorRatePercent:(G.errorRate*100).toFixed(2)}}})});var gc0=k(()=>{hc0();xc0()});var Ag6,Pg6,Eg6,Tg6,Cg6,Dv,zv,$B,Rg6,Ig6,uc0;var NP=k(()=>{c1();Ag6=q.enum(["sum","avg","min","max","count","last"]).describe("Aggregation function to apply"),Pg6=q.enum(["metric","timeseries","table"]).describe("Widget display type"),Eg6=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")}),Tg6=q.object({fn:Ag6,groupBy:q.string().optional().describe("Optional JSONPath for grouping results"),interval:q.string().optional().describe("For timeseries widgets: interval like '1h', '1d', '15m'")}),Cg6=q.object({connectionIds:q.array(q.string()).optional().describe("Filter to specific connections"),toolNames:q.array(q.string()).optional().describe("Filter to specific tools")}),Dv=q.object({id:q.string().describe("Unique widget identifier"),name:q.string().describe("Widget display name"),type:Pg6,source:Eg6,aggregation:Tg6,filter:Cg6.optional()}),zv=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' })")}),$B=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:zv.nullable().describe("Global filters applied to all widgets"),widgets:q.array(Dv).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")}),Rg6=q.object({key:q.string().describe("Group key value"),value:q.number().describe("Aggregated value for this group")}),Ig6=q.object({timestamp:q.string().describe("Time bucket timestamp"),value:q.number().describe("Aggregated value for this time bucket")}),uc0=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(Rg6).optional().describe("Grouped results (when groupBy is specified)"),timeseries:q.array(Ig6).optional().describe("Timeseries data (for timeseries type)")})});var FO1;var mc0=k(()=>{F4();c1();NP();FO1=s1({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:zv.optional().describe("Global filters applied to all widgets"),widgets:q.array(Dv).min(1).describe("Widget definitions (at least one required)")}),outputSchema:$B,handler:async(Y,Q)=>{let X=v0(Q),J=Q.auth.user?.id;if(!J)throw Error("User authentication required");let G=await Q.storage.monitoringDashboards.create(X.id,J,{name:Y.name,description:Y.description,filters:Y.filters,widgets:Y.widgets});return{id:G.id,organizationId:G.organizationId,name:G.name,description:G.description,filters:G.filters,widgets:G.widgets,createdBy:G.createdBy,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}}})});var VO1;var lc0=k(()=>{F4();c1();NP();VO1=s1({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:$B.nullable(),handler:async(Y,Q)=>{let X=v0(Q),J=await Q.storage.monitoringDashboards.get(Y.id);if(!J||J.organizationId!==X.id)return null;return{id:J.id,organizationId:J.organizationId,name:J.name,description:J.description,filters:J.filters,widgets:J.widgets,createdBy:J.createdBy,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt,updatedAt:J.updatedAt instanceof Date?J.updatedAt.toISOString():J.updatedAt}}})});var qO1;var dc0=k(()=>{F4();c1();NP();qO1=s1({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($B).describe("List of dashboards"),total:q.number().describe("Total number of dashboards")}),handler:async(Y,Q)=>{let X=v0(Q),J=await Q.storage.monitoringDashboards.list(X.id);return{dashboards:J.map((G)=>({id:G.id,organizationId:G.organizationId,name:G.name,description:G.description,filters:G.filters,widgets:G.widgets,createdBy:G.createdBy,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt})),total:J.length}}})});var BO1;var pc0=k(()=>{F4();c1();NP();BO1=s1({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:zv.nullable().optional().describe("New global filters"),widgets:q.array(Dv).optional().describe("New widget definitions")}),outputSchema:$B,handler:async(Y,Q)=>{let X=v0(Q),J=await Q.storage.monitoringDashboards.get(Y.id);if(!J||J.organizationId!==X.id)throw Error(`Dashboard ${Y.id} not found`);let G={};if(Y.name!==void 0)G.name=Y.name;if(Y.description!==void 0)G.description=Y.description;if(Y.filters!==void 0)G.filters=Y.filters;if(Y.widgets!==void 0)G.widgets=Y.widgets;let K=await Q.storage.monitoringDashboards.update(Y.id,G);return{id:K.id,organizationId:K.organizationId,name:K.name,description:K.description,filters:K.filters,widgets:K.widgets,createdBy:K.createdBy,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt,updatedAt:K.updatedAt instanceof Date?K.updatedAt.toISOString():K.updatedAt}}})});var UO1;var cc0=k(()=>{F4();c1();UO1=s1({name:"MONITORING_DASHBOARD_DELETE",description:"Delete a monitoring dashboard",annotations:{title:"Delete Monitoring Dashboard",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({id:q.string().describe("Dashboard ID to delete")}),outputSchema:q.object({success:q.boolean().describe("Whether the deletion was successful")}),handler:async(Y,Q)=>{let X=v0(Q),J=await Q.storage.monitoringDashboards.get(Y.id);if(!J||J.organizationId!==X.id)throw Error(`Dashboard ${Y.id} not found`);return await Q.storage.monitoringDashboards.delete(Y.id),{success:!0}}})});var DO1;var nc0=k(()=>{F4();c1();NP();DO1=s1({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(uc0).describe("Widget query results"),timeRange:q.object({startDate:q.string(),endDate:q.string()}).describe("Time range used for the query")}),handler:async(Y,Q)=>{let X=v0(Q),J=await Q.storage.monitoringDashboards.get(Y.dashboardId);if(!J||J.organizationId!==X.id)throw Error(`Dashboard ${Y.dashboardId} not found`);let G=new Date,K=Y.timeRange?.startDate?new Date(Y.timeRange.startDate):new Date(G.getTime()-86400000),W=Y.timeRange?.endDate?new Date(Y.timeRange.endDate):G,Z=await Promise.all(J.widgets.map(async(H)=>{let $=J.filters?.propertyFilters,F=Y.propertyFilters,V=$||F?{properties:{...$,...F?.properties},propertyKeys:F?.propertyKeys,propertyPatterns:F?.propertyPatterns,propertyInValues:F?.propertyInValues}:void 0,B={connectionIds:H.filter?.connectionIds??J.filters?.connectionIds??void 0,virtualMcpIds:J.filters?.virtualMcpIds??void 0,toolNames:H.filter?.toolNames??J.filters?.toolNames??void 0,startDate:K,endDate:W,propertyFilters:V};try{let U=await Q.storage.monitoring.aggregate({organizationId:X.id,path:H.source.path,from:H.source.from,aggregation:H.aggregation.fn,groupBy:H.aggregation.groupBy,interval:H.aggregation.interval,filters:B});return{widgetId:H.id,value:U.value,groups:U.groups,timeseries:U.timeseries}}catch(U){return console.error(`Widget ${H.id} aggregation failed:`,U),{widgetId:H.id,value:null,groups:void 0,timeseries:void 0}}}));return{dashboardId:Y.dashboardId,results:Z,timeRange:{startDate:K.toISOString(),endDate:W.toISOString()}}}})});var jg6,zO1;var ic0=k(()=>{F4();c1();jg6=q.object({type:q.enum(["metric","timeseries","table"]),source:q.object({path:q.string().describe("JSONPath to extract value from"),from:q.enum(["input","output"]).describe("Extract from input or output")}),aggregation:q.object({fn:q.enum(["sum","avg","min","max","count","last"]).describe("Aggregation function"),groupBy:q.string().optional().describe("JSONPath for grouping (table)"),interval:q.string().optional().describe("Time interval for timeseries (15m, 1h, 1d)")}),filter:q.object({connectionIds:q.array(q.string()).optional(),toolNames:q.array(q.string()).optional()}).optional()}),zO1=s1({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:jg6.describe("Widget configuration to preview"),timeRange:q.object({startDate:q.string().datetime().describe("Start of time range (ISO 8601)"),endDate:q.string().datetime().describe("End of time range (ISO 8601)")}).optional().describe("Time range for the query (defaults to last 24 hours)"),propertyFilters:q.object({properties:q.record(q.string(),q.string()).optional().describe("Exact match: property key equals value"),propertyKeys:q.array(q.string()).optional().describe("Exists: filter logs that have these property keys"),propertyPatterns:q.record(q.string(),q.string()).optional().describe("Pattern match: property value matches pattern (SQL LIKE)"),propertyInValues:q.record(q.string(),q.string()).optional().describe("In match: exact match within comma-separated values")}).optional().describe("Property filters to apply")}),outputSchema:q.object({value:q.number().nullable().optional().describe("Aggregated value"),groups:q.array(q.object({key:q.string(),value:q.number()})).optional().describe("Grouped results for table widgets"),timeseries:q.array(q.object({timestamp:q.string(),value:q.number()})).optional().describe("Timeseries data points"),matchedRecords:q.number().describe("Number of records that matched"),timeRange:q.object({startDate:q.string(),endDate:q.string()}).describe("Time range used for the query")}),handler:async(Y,Q)=>{let X=v0(Q),{widget:J,timeRange:G}=Y,K=new Date,W=G?.startDate?new Date(G.startDate):new Date(K.getTime()-86400000),Z=G?.endDate?new Date(G.endDate):K,H={connectionIds:J.filter?.connectionIds,toolNames:J.filter?.toolNames,startDate:W,endDate:Z,propertyFilters:Y.propertyFilters};try{let $=await Q.storage.monitoring.countMatched({organizationId:X.id,path:J.source.path,from:J.source.from,filters:H}),F=await Q.storage.monitoring.aggregate({organizationId:X.id,path:J.source.path,from:J.source.from,aggregation:J.aggregation.fn,groupBy:J.aggregation.groupBy,interval:J.aggregation.interval,filters:H});return{value:F.value,groups:F.groups,timeseries:F.timeseries,matchedRecords:$,timeRange:{startDate:W.toISOString(),endDate:Z.toISOString()}}}catch($){return console.error("Widget preview aggregation failed:",$),{value:null,matchedRecords:0,timeRange:{startDate:W.toISOString(),endDate:Z.toISOString()}}}}})});var ac0=k(()=>{mc0();lc0();dc0();pc0();cc0();nc0();ic0()});var OO1;var rc0=k(()=>{c1();F4();OO1=s1({name:"ORGANIZATION_CREATE",description:"Create a new organization",annotations:{title:"Create Organization",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:q.object({slug:q.string().min(1).max(50).regex(/^[a-z0-9-]+$/,"Slug must be lowercase alphanumeric with hyphens"),name:q.string().min(1).max(255),description:q.string().optional()}),outputSchema:q.object({id:q.string(),name:q.string(),slug:q.string(),logo:q.string().nullable().optional(),metadata:q.any().optional(),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),members:q.array(q.any()).optional()}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=EY(Q);if(!X)throw Error("User ID required to create organization");let J=await Q.boundAuth.organization.create({name:Y.name,slug:Y.slug,metadata:Y.description?{description:Y.description}:void 0,userId:X});if(!J)throw Error("Failed to create organization");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var NO1;var oc0=k(()=>{c1();F4();NO1=s1({name:"ORGANIZATION_LIST",description:"List all organizations user has access to",annotations:{title:"List Organizations",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({userId:q.string().optional()}),outputSchema:q.object({organizations:q.array(q.object({id:q.string(),name:q.string(),slug:q.string(),logo:q.string().nullable().optional(),metadata:q.any().optional(),createdAt:q.string().datetime().describe("ISO 8601 timestamp")}))}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=EY(Q),J=Y.userId||X;if(!J)throw Error("User ID required to list organizations");return{organizations:(await Q.boundAuth.organization.list(J)).map((K)=>({...K,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt}))}}})});var LO1;var sc0=k(()=>{c1();F4();LO1=s1({name:"ORGANIZATION_GET",description:"Get organization details by slug or ID",annotations:{title:"Get Organization",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({}),outputSchema:q.object({id:q.string(),name:q.string(),slug:q.string(),logo:q.string().nullable().optional(),metadata:q.any().optional(),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),members:q.array(q.any()).optional(),invitations:q.array(q.any()).optional()}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=await Q.boundAuth.organization.get();if(!X)throw Error("No active organization found");let J=new Date,G=X.invitations?.filter((K)=>new Date(K.expiresAt)>J);return{...X,invitations:G,createdAt:X.createdAt instanceof Date?X.createdAt.toISOString():X.createdAt}}})});var MO1;var tc0=k(()=>{c1();F4();MO1=s1({name:"ORGANIZATION_UPDATE",description:"Update an existing organization",annotations:{title:"Update Organization",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({id:q.string(),slug:q.string().min(1).max(50).regex(/^[a-z0-9-]+$/).optional(),name:q.string().min(1).max(255).optional(),description:q.string().optional()}),outputSchema:q.object({id:q.string(),name:q.string(),slug:q.string(),logo:q.string().nullable().optional(),metadata:q.any().optional(),createdAt:q.string().datetime().describe("ISO 8601 timestamp")}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X={};if(Y.name)X.name=Y.name;if(Y.slug)X.slug=Y.slug;if(Y.description)X.metadata={description:Y.description};let J=await Q.boundAuth.organization.update({organizationId:Y.id,data:X});if(!J)throw Error("Failed to update organization");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var wO1;var ec0=k(()=>{c1();F4();wO1=s1({name:"ORGANIZATION_DELETE",description:"Delete an organization",annotations:{title:"Delete Organization",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({id:q.string()}),outputSchema:q.object({success:q.boolean(),id:q.string()}),handler:async(Y,Q)=>{return D0(Q),await Q.access.check(),await Q.boundAuth.organization.delete(Y.id),{success:!0,id:Y.id}}})});var Ov;var AO1=k(()=>{c1();Ov=q.object({title:q.string(),url:q.string(),icon:q.string()})});var PO1;var Yn0=k(()=>{c1();F4();AO1();PO1=s1({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(Ov).nullable().optional(),enabled_plugins:q.array(q.string()).nullable().optional(),createdAt:q.string().datetime().optional().describe("ISO 8601 timestamp"),updatedAt:q.string().datetime().optional().describe("ISO 8601 timestamp")}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=Q.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");let J=await Q.storage.organizationSettings.get(X);if(!J)return{organizationId:X};return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt,updatedAt:J.updatedAt instanceof Date?J.updatedAt.toISOString():J.updatedAt}}})});var EO1;var Qn0=k(()=>{c1();F4();AO1();EO1=s1({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(Ov).optional(),enabled_plugins:q.array(q.string()).optional()}),outputSchema:q.object({organizationId:q.string(),sidebar_items:q.array(Ov).nullable().optional(),enabled_plugins:q.array(q.string()).nullable().optional(),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),updatedAt:q.string().datetime().describe("ISO 8601 timestamp")}),handler:async(Y,Q)=>{if(D0(Q),await Q.access.check(),Q.organization&&Q.organization.id!==Y.organizationId)throw Error("Cannot update settings for a different organization");let X=await Q.storage.organizationSettings.upsert(Y.organizationId,{sidebar_items:Y.sidebar_items,enabled_plugins:Y.enabled_plugins});return{...X,createdAt:X.createdAt instanceof Date?X.createdAt.toISOString():X.createdAt,updatedAt:X.updatedAt instanceof Date?X.updatedAt.toISOString():X.updatedAt}}})});var TO1;var Xn0=k(()=>{c1();F4();TO1=s1({name:"ORGANIZATION_MEMBER_ADD",description:"Add a member to an organization",annotations:{title:"Add Organization Member",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({organizationId:q.string().optional(),userId:q.string(),role:q.array(q.string())}),outputSchema:q.object({id:q.string(),organizationId:q.string(),userId:q.string(),role:q.union([q.string(),q.array(q.string())]),createdAt:q.string().datetime().describe("ISO 8601 timestamp")}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=Y.organizationId||Q.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");if(X!==Q.organization?.id)throw Error("Organization ID does not match authenticated organization");let J=await Q.boundAuth.organization.addMember({organizationId:X,userId:Y.userId,role:Y.role});if(!J)throw Error("Failed to add member");return{...J,role:J.role,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var CO1;var Jn0=k(()=>{c1();F4();CO1=s1({name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove a member from an organization",annotations:{title:"Remove Organization Member",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({organizationId:q.string().optional(),memberIdOrEmail:q.string()}),outputSchema:q.object({success:q.boolean(),memberIdOrEmail:q.string()}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=Y.organizationId||Q.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");return await Q.boundAuth.organization.removeMember({organizationId:X,memberIdOrEmail:Y.memberIdOrEmail}),{success:!0,memberIdOrEmail:Y.memberIdOrEmail}}})});var RO1;var Gn0=k(()=>{c1();F4();RO1=s1({name:"ORGANIZATION_MEMBER_LIST",description:"List all members in an organization",annotations:{title:"List Organization Members",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({limit:q.number().optional(),offset:q.number().optional()}),outputSchema:q.object({members:q.array(q.object({id:q.string(),organizationId:q.string(),userId:q.string(),role:q.string(),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),user:q.object({id:q.string(),name:q.string(),email:q.string(),image:q.string().optional()}).optional()}))}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=Q.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");let J=await Q.boundAuth.organization.listMembers({organizationId:X,limit:Y.limit,offset:Y.offset});return{members:(Array.isArray(J)?J:[]).map((K)=>({...K,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt}))}}})});var IO1;var Wn0=k(()=>{c1();F4();IO1=s1({name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Update a member's role in an organization",annotations:{title:"Update Member Role",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({organizationId:q.string().optional(),memberId:q.string(),role:q.array(q.string())}),outputSchema:q.object({id:q.string(),organizationId:q.string(),userId:q.string(),role:q.union([q.literal("admin"),q.literal("member"),q.literal("owner")]),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),user:q.object({email:q.string(),name:q.string(),image:q.string().optional()})}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=Y.organizationId||Q.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");let J=await Q.boundAuth.organization.updateMemberRole({organizationId:X,memberId:Y.memberId,role:Y.role});if(!J)throw Error("Failed to update member role");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var Zn0=k(()=>{rc0();oc0();sc0();tc0();ec0();Yn0();Qn0();Xn0();Jn0();Gn0();Wn0()});var vg6,Dr,_g6,qO,Kn0,zr;var BO=k(()=>{c1();vg6=q.object({banner:q.string().nullable(),bannerColor:q.string().nullable(),icon:q.string().nullable(),themeColor:q.string().nullable()}),Dr=q.object({banner:q.string().nullable().optional(),bannerColor:q.string().nullable().optional(),icon:q.string().nullable().optional(),themeColor:q.string().nullable().optional()}),_g6=q.object({id:q.string(),title:q.string(),icon:q.string().nullable()}),qO=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:vg6.nullable(),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),updatedAt:q.string().datetime().describe("ISO 8601 timestamp")}),Kn0=qO.omit({organizationId:!0}).extend({boundConnections:q.array(_g6)}),zr=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 jO1;var Hn0=k(()=>{c1();F4();BO();jO1=s1({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(Kn0)}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=await Q.storage.projects.list(Y.organizationId),J=X.map((K)=>K.id),G=await Q.storage.projectPluginConfigs.getBoundConnectionsForProjects(J);return{projects:X.map((K)=>({id:K.id,slug:K.slug,name:K.name,description:K.description,enabledPlugins:K.enabledPlugins,ui:K.ui,boundConnections:G.get(K.id)??[],createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt,updatedAt:K.updatedAt instanceof Date?K.updatedAt.toISOString():K.updatedAt}))}}})});var SO1;var $n0=k(()=>{c1();F4();BO();SO1=s1({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:qO.nullable()}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=null;if(Y.projectId)X=await Q.storage.projects.get(Y.projectId);else if(Y.slug)X=await Q.storage.projects.getBySlug(Y.organizationId,Y.slug);if(!X)return{project:null};return{project:{id:X.id,organizationId:X.organizationId,slug:X.slug,name:X.name,description:X.description,enabledPlugins:X.enabledPlugins,ui:X.ui,createdAt:X.createdAt instanceof Date?X.createdAt.toISOString():X.createdAt,updatedAt:X.updatedAt instanceof Date?X.updatedAt.toISOString():X.updatedAt}}}})});var kO1;var Fn0=k(()=>{c1();KY();F4();BO();kO1=s1({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:Dr.nullable().optional().describe("UI customization")}),outputSchema:q.object({project:qO}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let{organizationId:X,slug:J,name:G,description:K,enabledPlugins:W,ui:Z}=Y;if(J===k3)throw Error(`Slug "${k3}" is reserved`);if(await Q.storage.projects.getBySlug(X,J))throw Error(`Project with slug "${J}" already exists in this organization`);let $=Z?{banner:Z.banner??null,bannerColor:Z.bannerColor??null,icon:Z.icon??null,themeColor:Z.themeColor??null}:null,F=await Q.storage.projects.create({organizationId:X,slug:J,name:G,description:K??null,enabledPlugins:W??null,ui:$});return{project:{id:F.id,organizationId:F.organizationId,slug:F.slug,name:F.name,description:F.description,enabledPlugins:F.enabledPlugins,ui:F.ui,createdAt:F.createdAt instanceof Date?F.createdAt.toISOString():F.createdAt,updatedAt:F.updatedAt instanceof Date?F.updatedAt.toISOString():F.updatedAt}}}})});var vO1;var Vn0=k(()=>{c1();F4();BO();vO1=s1({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:Dr.nullable().optional().describe("Updated UI customization")}),outputSchema:q.object({project:qO.nullable()}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let{projectId:X,name:J,description:G,enabledPlugins:K,ui:W}=Y,Z={};if(J!==void 0)Z.name=J;if(G!==void 0)Z.description=G;if(K!==void 0)Z.enabledPlugins=K;if(W!==void 0)Z.ui=W?{banner:W.banner??null,bannerColor:W.bannerColor??null,icon:W.icon??null,themeColor:W.themeColor??null}:null;let H=await Q.storage.projects.update(X,Z);if(!H)return{project:null};return{project:{id:H.id,organizationId:H.organizationId,slug:H.slug,name:H.name,description:H.description,enabledPlugins:H.enabledPlugins,ui:H.ui,createdAt:H.createdAt instanceof Date?H.createdAt.toISOString():H.createdAt,updatedAt:H.updatedAt instanceof Date?H.updatedAt.toISOString():H.updatedAt}}}})});var _O1;var qn0=k(()=>{c1();KY();F4();_O1=s1({name:"PROJECT_DELETE",description:"Delete a project (cannot delete org-admin)",annotations:{title:"Delete Project",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({projectId:q.string().describe("Project ID to delete")}),outputSchema:q.object({success:q.boolean(),message:q.string().optional()}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let{projectId:X}=Y,J=await Q.storage.projects.get(X);if(!J)return{success:!1,message:"Project not found"};if(J.slug===k3)return{success:!1,message:"Cannot delete the org-admin project"};return{success:await Q.storage.projects.delete(X)}}})});var yO1;var Bn0=k(()=>{c1();F4();BO();yO1=s1({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:zr.nullable()}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let{projectId:X,pluginId:J}=Y,G=await Q.storage.projectPluginConfigs.get(X,J);if(!G)return{config:null};return{config:{id:G.id,projectId:G.projectId,pluginId:G.pluginId,connectionId:G.connectionId,settings:G.settings,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}}}})});var fO1;var Un0=k(()=>{c1();F4();BO();$r();fO1=s1({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:zr}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let{projectId:X,pluginId:J,connectionId:G,settings:K}=Y,W=EY(Q),Z=await Q.storage.projects.get(X);if(!Z)throw Error(`Project not found: ${X}`);let H=G?await Q.storage.connections.findById(G):null;if(G&&Z.organizationId&&!H&&FP()){if(Hr(G,Z.organizationId)){if(!W)throw Error("User ID required to create dev-assets connection");let F=VP(Z.organizationId,K7());await Q.storage.connections.create({...F,organization_id:Z.organizationId,created_by:W})}}let $=await Q.storage.projectPluginConfigs.upsert(X,J,{connectionId:G,settings:K});return{config:{id:$.id,projectId:$.projectId,pluginId:$.pluginId,connectionId:$.connectionId,settings:$.settings,createdAt:$.createdAt instanceof Date?$.createdAt.toISOString():$.createdAt,updatedAt:$.updatedAt instanceof Date?$.updatedAt.toISOString():$.updatedAt}}}})});var Dn0=k(()=>{Hn0();$n0();Fn0();Vn0();qn0();Bn0();Un0()});var bO1;var zn0=k(()=>{c1();F4();bO1=s1({name:"TAGS_LIST",description:"List all tags in an organization",annotations:{title:"List Tags",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({}),outputSchema:q.object({tags:q.array(q.object({id:q.string(),organizationId:q.string(),name:q.string(),createdAt:q.string().describe("ISO 8601 timestamp")}))}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=v0(Q);return{tags:(await Q.storage.tags.listOrgTags(X.id)).map((G)=>({...G,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():String(G.createdAt)}))}}})});var hO1;var On0=k(()=>{c1();F4();hO1=s1({name:"TAGS_CREATE",description:"Create a new tag in an organization",annotations:{title:"Create Tag",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:q.object({name:q.string().min(1).max(50).describe("Tag name")}),outputSchema:q.object({tag:q.object({id:q.string(),organizationId:q.string(),name:q.string(),createdAt:q.string().describe("ISO 8601 timestamp")})}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=v0(Q),J=await Q.storage.tags.createTag(X.id,Y.name);return{tag:{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():String(J.createdAt)}}}})});var xO1;var Nn0=k(()=>{c1();F4();xO1=s1({name:"TAGS_DELETE",description:"Delete a tag from an organization (removes from all members)",annotations:{title:"Delete Tag",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({tagId:q.string().describe("Tag ID to delete")}),outputSchema:q.object({success:q.boolean()}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=v0(Q),J=await Q.storage.tags.getTag(Y.tagId);if(!J)throw Error("Tag not found");if(J.organizationId!==X.id)throw Error("Tag does not belong to this organization");return await Q.storage.tags.deleteTag(Y.tagId),{success:!0}}})});var gO1;var Ln0=k(()=>{c1();F4();gO1=s1({name:"MEMBER_TAGS_GET",description:"Get tags assigned to a member",annotations:{title:"Get Member Tags",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({memberId:q.string().describe("Member ID")}),outputSchema:q.object({tags:q.array(q.object({id:q.string(),organizationId:q.string(),name:q.string(),createdAt:q.string().describe("ISO 8601 timestamp")}))}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=v0(Q);if(!await Q.storage.tags.verifyMemberOrg(Y.memberId,X.id))throw Error(`Member not found in this organization: ${Y.memberId}`);return{tags:(await Q.storage.tags.getMemberTags(Y.memberId)).map((K)=>({...K,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():String(K.createdAt)}))}}})});var uO1;var Mn0=k(()=>{c1();F4();uO1=s1({name:"MEMBER_TAGS_SET",description:"Set tags for a member (replaces all existing tags)",annotations:{title:"Set Member Tags",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({memberId:q.string().describe("Member ID"),tagIds:q.array(q.string()).describe("Array of tag IDs to assign")}),outputSchema:q.object({success:q.boolean(),tags:q.array(q.object({id:q.string(),organizationId:q.string(),name:q.string(),createdAt:q.string().describe("ISO 8601 timestamp")}))}),handler:async(Y,Q)=>{D0(Q),await Q.access.check();let X=v0(Q);if(!await Q.storage.tags.verifyMemberOrg(Y.memberId,X.id))throw Error(`Member not found in this organization: ${Y.memberId}`);for(let K of Y.tagIds){let W=await Q.storage.tags.getTag(K);if(!W)throw Error(`Tag not found: ${K}`);if(W.organizationId!==X.id)throw Error(`Tag does not belong to this organization: ${K}`)}return await Q.storage.tags.setMemberTags(Y.memberId,Y.tagIds),{success:!0,tags:(await Q.storage.tags.getMemberTags(Y.memberId)).map((K)=>({...K,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():String(K.createdAt)}))}}})});var wn0=k(()=>{zn0();On0();Nn0();Ln0();Mn0()});var An0=k(()=>{KY()});var Pn0,aH,En0,Tn0;var UO=k(()=>{c1();An0();Pn0=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")}),aH=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([...qM,"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")}),En0=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")}),Tn0=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 bg6,hg6,mO1;var Cn0=k(()=>{c1();F4();UO();$7();bg6=q.object({data:En0.describe("Data for the new thread (id is auto-generated if not provided)")}),hg6=q.object({item:aH.describe("The created thread entity")}),mO1=s1({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:bg6,outputSchema:hg6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=EY(Q);if(!J)throw Error("User ID required to create thread");let G=Y.data.id??X9("thrd"),K=await Q.storage.threads.create({id:G,organization_id:X.id,title:Y.data.title,description:Y.data.description,created_by:J});return{item:{...K,hidden:K.hidden??!1}}}})});function FB(Y,Q=Date.now()){let X=Y.status;if(X==="in_progress"){let J=new Date(Y.updated_at).getTime();if(!Number.isFinite(J)||Q-J>1800000)X="expired"}return{...Y,status:X,hidden:Y.hidden??!1}}var xg6,gg6,lO1;var Rn0=k(()=>{MG();F4();UO();c1();xg6=uZ.extend({where:q.object({created_by:q.string().optional()}).optional()}),gg6=x$(aH),lO1=s1({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:xg6,outputSchema:gg6,handler:async(Y,Q)=>{await Q.access.check();let X=Q.auth.user?.id;if(!X)throw Error("User ID required to list threads");let J=v0(Q),G=Y.offset??0,K=Y.limit??100,{threads:W,total:Z}=await Q.storage.threads.list(J.id,X,{limit:K,offset:G}),H=G+K<Z,$=Date.now();return{items:W.map((F)=>FB(F,$)),totalCount:Z,hasMore:H}}})});var ug6,dO1;var In0=k(()=>{MG();F4();UO();ug6=TS(aH),dO1=s1({name:"COLLECTION_THREADS_GET",description:"Get thread details by ID",annotations:{title:"Get Thread",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:ES,outputSchema:ug6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=await Q.storage.threads.get(Y.id);if(!J||J.organization_id!==X.id)return{item:null};return{item:FB(J)}}})});var mg6,lg6,pO1;var jn0=k(()=>{c1();F4();UO();mg6=q.object({id:q.string().describe("ID of the thread to update"),data:Tn0.describe("Partial thread data to update")}),lg6=q.object({item:aH.describe("The updated thread entity")}),pO1=s1({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:mg6,outputSchema:lg6,handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=EY(Q);if(!J)throw Error("User ID required to update thread");let{id:G,data:K}=Y,W=await Q.storage.threads.get(G);if(!W||W.organization_id!==X.id)throw Error("Thread not found in organization");let Z=await Q.storage.threads.update(G,{title:K.title,description:K.description,hidden:K.hidden,updated_by:J});return{item:FB(Z)}}})});var cO1;var Sn0=k(()=>{MG();F4();UO();cO1=s1({name:"COLLECTION_THREADS_DELETE",description:"Delete a thread",annotations:{title:"Delete Thread",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:CS,outputSchema:RS(aH),handler:async(Y,Q)=>{D0(Q);let X=v0(Q);await Q.access.check();let J=await Q.storage.threads.get(Y.id);if(!J)throw Error(`Thread not found: ${Y.id}`);if(J.organization_id!==X.id)throw Error(`Thread not found: ${Y.id}`);return await Q.storage.threads.delete(Y.id),{item:FB(J)}}})});function kn0(Y){if(!Y)return null;if("field"in Y&&Y.field[0]==="thread_id"&&Y.operator==="eq")return String(Y.value);if("conditions"in Y)for(let Q of Y.conditions){let X=kn0(Q);if(X)return X}return null}var dg6,nO1;var vn0=k(()=>{MG();F4();UO();dg6=x$(Pn0),nO1=s1({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:uZ,outputSchema:dg6,handler:async(Y,Q)=>{let X=v0(Q);await Q.access.check();let J=kn0(Y.where);if(!J)throw Error("thread_id filter is required in where clause");let G=await Q.storage.threads.get(J);if(!G||G.organization_id!==X.id)return{items:[],totalCount:0,hasMore:!1};let K=Y.offset??0,W=Y.limit??100,{messages:Z,total:H}=await Q.storage.threads.listMessages(J,{limit:W,offset:K}),$=K+W<H;return{items:Z,totalCount:H,hasMore:$}}})});var _n0=k(()=>{Cn0();Rn0();In0();jn0();Sn0();vn0()});var cg6,ng6,iO1;var yn0=k(()=>{c1();F4();cg6=q.object({id:q.string().min(1)}),ng6=q.object({user:q.object({id:q.string(),name:q.string(),email:q.string(),image:q.string().nullable()}).nullable()}),iO1=s1({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:cg6,outputSchema:ng6,handler:async(Y,Q)=>{await Q.access.check(),D0(Q);let X=EY(Q);if(!X)throw Error("Authentication required");let J=await Q.storage.users.findById(Y.id,X);if(!J)return{user:null};return{user:{id:J.id,name:J.name,email:J.email,image:J.image??null}}}})});var fn0=k(()=>{yn0()});var hn0={};RY(hn0,{managementMCP:()=>aO1,ALL_TOOLS:()=>bn0});var ag6,rg6,bn0,aO1=async(Y)=>{let Q=null;if(Y.organization){let G=await Y.storage.organizationSettings.get(Y.organization.id),K=await Y.storage.projects.list(Y.organization.id),W=new Set(G?.enabled_plugins??[]);for(let Z of K)if(Z.enabledPlugins)for(let H of Z.enabledPlugins)W.add(H);Q=W.size>0?[...W]:null}let X=yd0(bn0,Q),J=new OD({name:"mcp-mesh-management",version:"1.0.0"},{capabilities:{tools:{}}});for(let G of X){let K=G.inputSchema&&typeof G.inputSchema==="object"&&"shape"in G.inputSchema?G.inputSchema:q.object({}),W=G.outputSchema&&typeof G.outputSchema==="object"&&"shape"in G.outputSchema?G.outputSchema:void 0,Z=K.shape,H=W?.shape;J.registerTool(G.name,{description:G.description??"",inputSchema:Z,outputSchema:H,annotations:G.annotations,_meta:G._meta},async($)=>{Y.access.setToolName(G.name);try{let F=await G.execute($,Y);return{content:[{type:"text",text:JSON.stringify(F)}],structuredContent:F}}catch(F){return{content:[{type:"text",text:`Error: ${F.message}`}],isError:!0}}})}return J};var rO1=k(()=>{Yr();rm();c1();ed0();zp0();$c0();Bc0();Pc0();Sc0();bc0();gc0();ac0();Zn0();Dn0();wn0();_n0();fn0();ag6=[OO1,NO1,LO1,MO1,wO1,PO1,EO1,TO1,CO1,RO1,IO1,Dz1,Nz1,Lz1,mz1,lz1,dz1,sz1,ez1,YO1,QO1,XO1,JO1,GO1,WO1,ZO1,KO1,qc0,HO1,$O1,FO1,VO1,qO1,BO1,UO1,DO1,zO1,Gz1,Zz1,Kz1,Wz1,pz1,cz1,nz1,iz1,az1,rz1,oz1,iO1,qz1,Bz1,Uz1,mO1,lO1,dO1,pO1,cO1,nO1,bO1,hO1,xO1,gO1,uO1,jO1,SO1,kO1,vO1,_O1,yO1,fO1],rg6=fd0(),bn0=[...ag6,...rg6]});function og6(Y){return[{permissions:{self:["*"]},getTools:async()=>{let{ALL_TOOLS:Q}=await Promise.resolve().then(() => (rO1(),hn0));return Q.map((X)=>{return{name:X.name,inputSchema:q.toJSONSchema(X.inputSchema,{unrepresentable:"any"}),outputSchema:X.outputSchema?q.toJSONSchema(X.outputSchema,{unrepresentable:"any"}):void 0,description:X.description}})},data:U71(K7(),Y)},{data:B71()},{data:q71(Y)}]}async function xn0(Y,Q){try{let X=Pn(),J=new Rz(process.env.ENCRYPTION_KEY||""),G=new DS(X.db,J),K=new zS(X.db),W=og6(Y);try{await K.create({organizationId:Y,slug:k3,name:hb,description:"Organization administration and settings",enabledPlugins:null,ui:null})}catch(Z){console.warn("Could not create org-admin project (may already exist):",Z)}await Promise.all(W.map(async(Z)=>{let H=null;if(Z.permissions)H=(await BF.api.createApiKey({body:{name:`${Z.data.app_name??crypto.randomUUID()}-mcp`,userId:Q,permissions:Z.permissions,rateLimitEnabled:!1,metadata:{organization:{id:Y},purpose:"default-org-connections"}}}))?.key;let $=await DA({id:"pending",title:Z.data.title,connection_type:Z.data.connection_type,connection_url:Z.data.connection_url,connection_token:Z.data.connection_token,connection_headers:Z.data.connection_headers}).catch(()=>null),F=await Z.getTools?.()??$?.tools??null,V=$?.scopes?.length?$.scopes:null,B=Z.data.id?Z.data.id.startsWith(`${Y}_`)?Z.data.id:`${Y}_${Z.data.id}`:void 0;await G.create({...Z.data,id:B,tools:F,configuration_scopes:V,organization_id:Y,created_by:Q,connection_token:Z.data.connection_token??H})}))}catch(X){console.error("Error creating default MCP connections:",X)}}var gn0=k(()=>{KY();En();Tn();VV1();qV1();kn();c1();Kv()});var oO1,Or;var Nr=k(()=>{oO1=["owner","admin","user"],Or=["owner","admin"]});var sg6=(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"}}}}]}},un0=(Y)=>{if(Y.providerId==="microsoft")return sg6(Y);throw Error(`Unsupported provider: ${Y.providerId}`)};function tg6(Y){return Y.toLowerCase().trim().replace(/[^a-z0-9\s_-]+/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function eg6(){let Y=Math.floor(Math.random()*ln0.length),Q=Math.floor(Math.random()*mn0.length),X=ln0[Y]??"deco",J=mn0[Q]??"studio";return`${X}-${J}`}function Hu6(){let Y=[Nv],Q=new URL(Nv);if(Q.hostname==="localhost")Y.push(Nv.replace("localhost","127.0.0.1"));else if(Q.hostname==="127.0.0.1")Y.push(Nv.replace("127.0.0.1","localhost"));return Y}var mn0,ln0,Yu6,Qu6,Lr,Xu6,Ju6,Gu6,dn0,p9,pn0=void 0,sO1=void 0,tO1=!1,Wu6,Zu6,Ku6,Nv,BF;var Kv=k(()=>{l71();CP0();q20();e31();AF1();GT0();QS();VT0();En();FV1();rR0();gn0();Nr();mn0=["labs","agent","studio","workspace","systems","core","cloud","works"],ln0=["capybara","guarana","deco","samba","feijoada","capoeira","carnival"];Yu6=Object.values(hR()).map((Y)=>Y.map((Q)=>Q.name)).flat(),Qu6={...ac,self:["*",...Yu6]},Lr=vH(Qu6),Xu6=Lr.newRole({self:["*"],...cj.statements}),Ju6=Lr.newRole({self:["*"],...cj.statements}),Gu6=Lr.newRole({self:["*"],...cj.statements}),dn0=Object.values(hR()).map((Y)=>Y.map((Q)=>`self:${Q.name}`)).flat(),p9=YS.auth;if(p9.inviteEmailProviderId&&p9.emailProviders&&p9.emailProviders.length>0){let Y=BS(p9.emailProviders,p9.inviteEmailProviderId);if(Y){let Q=qS(Y);pn0=async(X)=>{let J=X.inviter.user?.name||X.inviter.user?.email,G=`${K7()}/auth/accept-invitation?invitationId=${X.invitation.id}&redirectTo=/`;await Q({to:X.email,subject:`Invitation to join ${X.organization.name}`,html:`
|
|
1332
1332
|
<h2>You've been invited!</h2>
|
|
1333
1333
|
<p>${J} has invited you to join <strong>${X.organization.name}</strong>.</p>
|
|
1334
1334
|
<p><a href="${G}">Click here to accept the invitation</a></p>
|
|
@@ -1387,8 +1387,8 @@ Example input: "How do I connect to a database?"
|
|
|
1387
1387
|
Example output: Database Connection Setup
|
|
1388
1388
|
|
|
1389
1389
|
Example input: "What tools are available?"
|
|
1390
|
-
Example output: Available Tools Overview`;function Rr(Y){return typeof Y==="string"?Y:Y.toISOString()}class Lv{db;constructor(Y){this.db=Y}async create(Y){let Q=Y.id??X9("thrd"),X=new Date().toISOString();if(!Y.organization_id)throw Error("organization_id is required");if(!Y.created_by)throw Error("created_by is required");if(!Y.title)Y.title=Cr;let J={id:Q,organization_id:Y.organization_id,title:Y.title,description:Y.description??null,status:Y.status??"completed",created_at:X,updated_at:X,created_by:Y.created_by,updated_by:Y.updated_by??null},G=await this.db.insertInto("threads").values(J).returningAll().executeTakeFirstOrThrow();return this.threadFromDbRow(G)}async get(Y){let Q=await this.db.selectFrom("threads").selectAll().where("id","=",Y).executeTakeFirst();return Q?this.threadFromDbRow(Q):null}async update(Y,Q){let J={updated_at:new Date().toISOString()};if(Q.title!==void 0)J.title=Q.title;if(Q.description!==void 0)J.description=Q.description;if(Q.updated_by!==void 0)J.updated_by=Q.updated_by;if(Q.hidden!==void 0)J.hidden=Q.hidden;if(Q.status!==void 0)J.status=Q.status;await this.db.updateTable("threads").set(J).where("id","=",Y).execute();let G=await this.get(Y);if(!G)throw Error("Thread not found after update");return G}async delete(Y){await this.db.deleteFrom("threads").where("id","=",Y).execute()}async list(Y,Q,X){let J=this.db.selectFrom("threads").selectAll().where("organization_id","=",Y).where("hidden","=",!1).orderBy("updated_at","desc");if(Q)J=J.where("created_by","=",Q);let G=this.db.selectFrom("threads").select((Z)=>Z.fn.count("id").as("count")).where("organization_id","=",Y).where("hidden","=",!1);if(Q)G=G.where("created_by","=",Q);if(X?.limit)J=J.limit(X.limit);if(X?.offset)J=J.offset(X.offset);let[K,W]=await Promise.all([J.execute(),G.executeTakeFirst()]);return{threads:K.map((Z)=>this.threadFromDbRow(Z)),total:Number(W?.count||0)}}async saveMessages(Y){let Q=new Date().toISOString(),X=Y[0]?.thread_id;if(!X)throw Error("thread_id is required when creating multiple messages");let J=new Map;for(let Z of Y){let H=J.get(Z.id);if(H&&H.thread_id!==Z.thread_id)throw Error(`Duplicate message id "${Z.id}" with conflicting thread_ids: "${H.thread_id}" vs "${Z.thread_id}"`);J.set(Z.id,Z)}let G=[...J.values()],K=G.find((Z)=>Z.thread_id!==X);if(K)throw Error(`All messages must target the same thread. Expected thread_id "${X}", but message "${K.id}" has thread_id "${K.thread_id}"`);let W=G.map((Z)=>({id:Z.id,thread_id:X,metadata:Z.metadata?JSON.stringify(Z.metadata):null,parts:JSON.stringify(Z.parts),role:Z.role,created_at:Z.created_at??Q,updated_at:Q}));await this.db.transaction().execute(async(Z)=>{await Z.insertInto("thread_messages").values(W).onConflict((H)=>H.column("id").doUpdateSet(($)=>({metadata:$.ref("excluded.metadata"),parts:$.ref("excluded.parts"),role:$.ref("excluded.role"),updated_at:$.ref("excluded.updated_at")}))).execute(),await Z.updateTable("threads").set({updated_at:Q}).where("id","=",X).execute()})}async listMessages(Y,Q){let X=Q?.sort??"asc",J=this.db.selectFrom("thread_messages").selectAll().where("thread_id","=",Y).orderBy("created_at",X).orderBy("id",X),G=this.db.selectFrom("thread_messages").select((Z)=>Z.fn.count("id").as("count")).where("thread_id","=",Y);if(Q?.limit)J=J.limit(Q.limit);if(Q?.offset)J=J.offset(Q.offset);let[K,W]=await Promise.all([J.execute(),G.executeTakeFirst()]);return{messages:K.map((Z)=>this.messageFromDbRow(Z)),total:Number(W?.count||0)}}threadFromDbRow(Y){return{id:Y.id,organization_id:Y.organization_id,title:Y.title,description:Y.description,status:Y.status,created_at:Rr(Y.created_at),updated_at:Rr(Y.updated_at),created_by:Y.created_by,updated_by:Y.updated_by,hidden:!!Y.hidden}}messageFromDbRow(Y){let Q,X;try{Q=Y.metadata?JSON.parse(Y.metadata):void 0}catch(J){console.error(`Failed to parse metadata for message ${Y.id}:`,Y.metadata,J),Q=void 0}try{X=typeof Y.parts==="string"?JSON.parse(Y.parts):Y.parts}catch(J){console.error(`Failed to parse parts for message ${Y.id}:`,Y.parts,J),X=[]}return{id:Y.id,thread_id:Y.thread_id,metadata:Q,parts:X,role:Y.role,created_at:Rr(Y.created_at),updated_at:Rr(Y.updated_at)}}}Ez1();function qu6(Y){if(!Y)return;try{let Q=JSON.parse(Y);if(typeof Q!=="object"||Q===null||Array.isArray(Q))return;let X={};for(let[J,G]of Object.entries(Q))if(typeof G==="string")X[J]=G;return Object.keys(X).length>0?X:void 0}catch{return}}function Bu6(Y,Q){for(let[X,J]of Object.entries(Q)){let G=Y[X];if(!G||G.length===0){let K=Y["*"];if(!K||K.length===0)return!1;if(K.includes("*"))continue;for(let W of J)if(!K.includes(W))return!1;continue}if(G.includes("*"))continue;for(let K of J)if(!G.includes(K))return!1}return!0}function Uu6(Y){let{auth:Q,headers:X,role:J,permissions:G,userId:K}=Y,W=Q.api.hasPermission;return{hasPermission:async(Z)=>{if(J&&oO1.includes(J))return!0;if(G)return Bu6(G,Z);if(!W)return console.error("[Auth] hasPermission API not available"),!1;try{if((await W({headers:X,body:{permission:Z}}))?.success===!0)return!0;let $={};for(let V of Object.keys(Z))$[V]=["*"];return(await W({headers:X,body:{permission:$}}))?.success===!0}catch(H){return console.error("[Auth] Permission check failed:",H),!1}},organization:{create:async(Z)=>{return Q.api.createOrganization({headers:X,body:Z})},update:async(Z)=>{return Q.api.updateOrganization({headers:X,body:Z})},delete:async(Z)=>{await Q.api.deleteOrganization({headers:X,body:{organizationId:Z}})},get:async(Z)=>{return Q.api.getFullOrganization({headers:X,query:Z?{organizationId:Z}:void 0})},list:async(Z)=>{return Q.api.listOrganizations({headers:X,query:Z?{userId:Z}:void 0})},addMember:async(Z)=>{return Q.api.addMember({headers:X,body:Z})},removeMember:async(Z)=>{await Q.api.removeMember({headers:X,body:Z})},listMembers:async(Z)=>{return Q.api.listMembers({headers:X,query:Z?{organizationId:Z.organizationId,limit:Z.limit,offset:Z.offset}:void 0})},updateMemberRole:async(Z)=>{return Q.api.updateMemberRole({headers:X,body:Z})}},apiKey:{create:async(Z)=>{return Q.api.createApiKey({body:{...Z,userId:K}})},list:async()=>{return Q.api.listApiKeys({headers:X})},update:async(Z)=>{return Q.api.updateApiKey({body:{...Z,userId:K}})},delete:async(Z)=>{await Q.api.deleteApiKey({headers:X,body:{keyId:Z}})}}}}async function Du6(Y,Q,X){if(oO1.includes(X))return;let J=await Y.selectFrom("organizationRole").select(["permission"]).where("organizationId","=",Q).where("role","=",X).executeTakeFirst();if(!J?.permission)return;try{return JSON.parse(J.permission)}catch{console.error(`[Auth] Failed to parse permissions for role: ${X}`);return}}async function zu6(Y,Q,X,J=Fi0){let G=Y.headers.get("Authorization");try{let K=new Headers(Y.headers);K.set("X-MCP-Session-Auth","true");let W=await J.measure("auth_get_mcp_session",()=>Q.api.getMcpSession({headers:K}));if(W){let Z=W.userId,H=await J.measure("auth_query_membership",()=>X.selectFrom("member").innerJoin("organization","organization.id","member.organizationId").select(["member.role","member.organizationId","organization.id as orgId","organization.slug as orgSlug","organization.name as orgName"]).where("member.userId","=",Z).executeTakeFirst()),$=H?.role,F=H?{id:H.orgId,slug:H.orgSlug,name:H.orgName}:void 0,V;if(H&&$)V=await J.measure("auth_fetch_role_permissions",()=>Du6(X,H.organizationId,$));return{user:{id:Z,role:$},role:$,permissions:V,organization:F}}}catch(K){console.error("[Auth] OAuth session check failed:",K)}if(G?.startsWith("Bearer ")){let K=G.replace("Bearer ","").trim();try{let W=await J.measure("auth_verify_mesh_jwt",()=>Sp0(K));if(W){let Z,H=W.metadata?.organizationId;if(W.sub&&H)Z=(await J.measure("auth_query_membership",()=>X.selectFrom("member").select(["member.role"]).where("member.userId","=",W.sub).where("member.organizationId","=",H).executeTakeFirst()))?.role;return{user:{id:W.sub,connectionId:W.metadata?.connectionId,role:Z},role:Z,permissions:W.permissions,organization:W.metadata?.organizationId?{id:W.metadata?.organizationId}:void 0}}}catch{}try{let W=await J.measure("auth_verify_api_key",()=>Q.api.verifyApiKey({body:{key:K}}));if(W?.valid&&W.key){let Z=W.key.metadata?.organization,H=W.key.permissions,$,F=W.key.userId;if(F&&Z?.id)$=(await J.measure("auth_query_membership",()=>X.selectFrom("member").select(["member.role"]).where("member.userId","=",F).where("member.organizationId","=",Z.id).executeTakeFirst()))?.role;return{apiKeyId:W.key.id,user:{id:W.key.userId,role:$},role:$,permissions:H,organization:Z?{id:Z.id,slug:Z.slug,name:Z.name}:void 0}}}catch(W){console.error("[Auth] API key check failed:",W)}}try{let K=new Headers(Y.headers);K.delete("Authorization");let W=await J.measure("auth_get_session",()=>Q.api.getSession({headers:K}));if(W){let Z,H;if(W.session.activeOrganizationId){let $=await J.measure("auth_get_full_organization",()=>Q.api.getFullOrganization({headers:K}).catch(()=>null));if($)Z={id:$.id,slug:$.slug,name:$.name},H=$.members?.find((V)=>V.userId===W.user.id)?.role;else Z={id:W.session.activeOrganizationId,slug:"",name:""}}return{user:{id:W.user.id,email:W.user.email,role:H},role:H,organization:Z}}}catch(K){let W=K;console.error("[Auth] Session check failed:",JSON.stringify({message:W.message,body:W.body,stack:W.stack},null,2))}return{user:void 0}}var $i0,UF={set:(Y)=>{$i0=Y},create:async(Y,Q)=>{return await $i0(Y,Q)}},Fi0={measure:async(Y,Q)=>{return await Q()}},Ou6=["x-hub-signature-256"];async function Vi0(Y){let Q=new Rz(Y.encryption.key),X={connections:new DS(Y.db,Q),organizationSettings:new JN1(Y.db),monitoring:new QN1(Y.db,Y.databaseType),monitoringDashboards:new XN1(Y.db),virtualMcps:new eO1(Y.db),users:new ZN1(Y.db),threads:new Lv(Y.db),tags:new WN1(Y.db),projects:new zS(Y.db),projectPluginConfigs:new GN1(Y.db)};return async(J,G)=>{let K=G?.timings??Fi0,W=Br(),Z=J?.headers.get("x-caller-id")??void 0,H=J?await zu6(J,Y.auth,Y.db,K):{user:void 0},$=Uu6({auth:Y.auth,headers:J?.headers??new Headers,role:H.role,permissions:H.permissions,userId:H.user?.id}),F={user:H.user};if(H.apiKeyId)F.apiKey={id:H.apiKeyId,name:"",userId:""};let V=H.organization,B=J?process.env.BASE_URL??`${new URL(J.url).origin}`:K7(),U=new FF(Y.auth,F.user?.id,void 0,$,H.role,"self"),D={timings:K,auth:F,connectionId:Z,organization:V,storage:X,vault:Q,authInstance:Y.auth,boundAuth:$,access:U,db:Y.db,tracer:Y.observability.tracer,meter:Y.observability.meter,baseUrl:B,metadata:{requestId:crypto.randomUUID(),timestamp:new Date,wellKnownForwardableHeaders:Object.fromEntries(Ou6.map((z)=>[z,J?.headers.get(z)??null]).filter(([z,L])=>L!==null)),userAgent:J?.headers.get("x-mesh-client")||J?.headers.get("User-Agent")||void 0,ipAddress:(J?.headers.get("CF-Connecting-IP")||J?.headers.get("X-Forwarded-For"))??void 0,properties:qu6(J?.headers.get("x-mesh-properties"))},eventBus:Y.eventBus,createMCPProxy:async(z)=>{return await Qi0(z,D)},getOrCreateClient:W};return D}}En();class qi0{db;constructor(Y){this.db=Y}async publishEvent(Y){let Q=new Date().toISOString();return await this.db.insertInto("events").values({id:Y.id,organization_id:Y.organizationId,type:Y.type,source:Y.source,specversion:"1.0",subject:Y.subject??null,time:Y.time,datacontenttype:Y.datacontenttype??"application/json",dataschema:Y.dataschema??null,data:Y.data?JSON.stringify(Y.data):null,cron:Y.cron??null,status:"pending",attempts:0,last_error:null,next_retry_at:null,created_at:Q,updated_at:Q}).execute(),{id:Y.id,organizationId:Y.organizationId,type:Y.type,source:Y.source,specversion:"1.0",subject:Y.subject??null,time:Y.time,datacontenttype:Y.datacontenttype??"application/json",dataschema:Y.dataschema??null,data:Y.data??null,cron:Y.cron??null,status:"pending",attempts:0,lastError:null,nextRetryAt:null,createdAt:Q,updatedAt:Q}}async subscribe(Y){let Q=this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",Y.organizationId).where("connection_id","=",Y.connectionId).where("event_type","=",Y.eventType);if(Y.publisher)Q=Q.where("publisher","=",Y.publisher);else Q=Q.where("publisher","is",null);if(Y.filter)Q=Q.where("filter","=",Y.filter);else Q=Q.where("filter","is",null);let X=await Q.executeTakeFirst();if(X)return{id:X.id,organizationId:X.organization_id,connectionId:X.connection_id,publisher:X.publisher,eventType:X.event_type,filter:X.filter,enabled:X.enabled===1,createdAt:X.created_at,updatedAt:X.updated_at};let J=new Date().toISOString();return await this.db.insertInto("event_subscriptions").values({id:Y.id,organization_id:Y.organizationId,connection_id:Y.connectionId,publisher:Y.publisher??null,event_type:Y.eventType,filter:Y.filter??null,enabled:1,created_at:J,updated_at:J}).execute(),{id:Y.id,organizationId:Y.organizationId,connectionId:Y.connectionId,publisher:Y.publisher??null,eventType:Y.eventType,filter:Y.filter??null,enabled:!0,createdAt:J,updatedAt:J}}async unsubscribe(Y,Q){return{success:((await this.db.deleteFrom("event_subscriptions").where("id","=",Y).where("organization_id","=",Q).executeTakeFirst()).numDeletedRows??0n)>0n}}async listSubscriptions(Y,Q){let X=this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",Y);if(Q)X=X.where("connection_id","=",Q);return(await X.execute()).map((G)=>({id:G.id,organizationId:G.organization_id,connectionId:G.connection_id,publisher:G.publisher,eventType:G.event_type,filter:G.filter,enabled:G.enabled===1,createdAt:G.created_at,updatedAt:G.updated_at}))}async getSubscription(Y,Q){let X=await this.db.selectFrom("event_subscriptions").selectAll().where("id","=",Y).where("organization_id","=",Q).executeTakeFirst();if(!X)return null;return{id:X.id,organizationId:X.organization_id,connectionId:X.connection_id,publisher:X.publisher,eventType:X.event_type,filter:X.filter,enabled:X.enabled===1,createdAt:X.created_at,updatedAt:X.updated_at}}async getMatchingSubscriptions(Y){return(await this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",Y.organizationId).where("enabled","=",1).where("event_type","=",Y.type).where((X)=>X.or([X("publisher","is",null),X("publisher","=",Y.source)])).execute()).map((X)=>({id:X.id,organizationId:X.organization_id,connectionId:X.connection_id,publisher:X.publisher,eventType:X.event_type,filter:X.filter,enabled:X.enabled===1,createdAt:X.created_at,updatedAt:X.updated_at}))}async createDeliveries(Y,Q,X){if(Q.length===0)return;let J=new Date().toISOString(),G=X??null,K=Q.map((W)=>({id:crypto.randomUUID(),event_id:Y,subscription_id:W,status:"pending",attempts:0,last_error:null,delivered_at:null,next_retry_at:G,created_at:J}));await this.db.insertInto("event_deliveries").values(K).execute()}async claimPendingDeliveries(Y){let Q=new Date().toISOString(),X;try{X=(await this.db.updateTable("event_deliveries").set({status:"processing"}).where("id","in",(K)=>K.selectFrom("event_deliveries as d").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select("d.id").where("d.status","=","pending").where("s.enabled","=",1).where((W)=>W.or([W("d.next_retry_at","is",null),W("d.next_retry_at","<=",Q)])).orderBy("d.created_at","asc").limit(Y)).where("status","=","pending").returning(["id"]).execute()).map((K)=>K.id)}catch{let G=await this.db.selectFrom("event_deliveries as d").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select(["d.id"]).where("d.status","=","pending").where("s.enabled","=",1).where((K)=>K.or([K("d.next_retry_at","is",null),K("d.next_retry_at","<=",Q)])).orderBy("d.created_at","asc").limit(Y).execute();if(G.length===0)return[];X=G.map((K)=>K.id),await this.db.updateTable("event_deliveries").set({status:"processing"}).where("id","in",X).where("status","=","pending").execute()}if(X.length===0)return[];return(await this.db.selectFrom("event_deliveries as d").innerJoin("events as e","e.id","d.event_id").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select(["d.id as delivery_id","d.event_id","d.subscription_id","d.status as delivery_status","d.attempts as delivery_attempts","d.last_error as delivery_last_error","d.delivered_at","d.next_retry_at as delivery_next_retry_at","d.created_at as delivery_created_at","e.organization_id","e.type","e.source","e.specversion","e.subject","e.time","e.datacontenttype","e.dataschema","e.data","e.cron","e.status as event_status","e.attempts as event_attempts","e.last_error as event_last_error","e.next_retry_at","e.created_at as event_created_at","e.updated_at as event_updated_at","s.connection_id","s.publisher","s.event_type","s.filter","s.enabled","s.created_at as subscription_created_at","s.updated_at as subscription_updated_at"]).where("d.id","in",X).where("d.status","=","processing").execute()).map((G)=>({delivery:{id:G.delivery_id,eventId:G.event_id,subscriptionId:G.subscription_id,status:G.delivery_status,attempts:G.delivery_attempts,lastError:G.delivery_last_error,deliveredAt:G.delivered_at,nextRetryAt:G.delivery_next_retry_at,createdAt:G.delivery_created_at},event:{id:G.event_id,organizationId:G.organization_id,type:G.type,source:G.source,specversion:G.specversion,subject:G.subject,time:G.time,datacontenttype:G.datacontenttype,dataschema:G.dataschema,data:G.data?JSON.parse(G.data):null,cron:G.cron,status:G.event_status,attempts:G.event_attempts,lastError:G.event_last_error,nextRetryAt:G.next_retry_at,createdAt:G.event_created_at,updatedAt:G.event_updated_at},subscription:{id:G.subscription_id,organizationId:G.organization_id,connectionId:G.connection_id,publisher:G.publisher,eventType:G.event_type,filter:G.filter,enabled:G.enabled===1,createdAt:G.subscription_created_at,updatedAt:G.subscription_updated_at}}))}async markDeliveriesDelivered(Y){if(Y.length===0)return;let Q=new Date().toISOString();await this.db.updateTable("event_deliveries").set({status:"delivered",delivered_at:Q}).where("id","in",Y).execute()}async markDeliveriesFailed(Y,Q,X=20,J=1000,G=3600000){if(Y.length===0)return;for(let K of Y){let W=await this.db.selectFrom("event_deliveries").select(["attempts"]).where("id","=",K).executeTakeFirst();if(!W)continue;let Z=W.attempts+1;if(Z>=X)await this.db.updateTable("event_deliveries").set({attempts:Z,last_error:Q,status:"failed",next_retry_at:null}).where("id","=",K).execute();else{let H=Math.min(J*Math.pow(2,Z-1),G),$=new Date(Date.now()+H).toISOString();await this.db.updateTable("event_deliveries").set({attempts:Z,last_error:Q,status:"pending",next_retry_at:$}).where("id","=",K).execute()}}}async updateEventStatus(Y){let Q=await this.db.selectFrom("event_deliveries").select(["status"]).where("event_id","=",Y).execute();if(Q.length===0)return;let X=Q.every((K)=>K.status==="delivered"),J=Q.some((K)=>K.status==="failed"),G=Q.some((K)=>K.status==="pending"||K.status==="processing");if(X)await this.db.updateTable("events").set({status:"delivered",updated_at:new Date().toISOString()}).where("id","=",Y).execute();else if(J&&!G)await this.db.updateTable("events").set({status:"failed",updated_at:new Date().toISOString()}).where("id","=",Y).execute()}async resetStuckDeliveries(){let Y=await this.db.updateTable("event_deliveries").set({status:"pending"}).where("status","=","processing").executeTakeFirst();return Number(Y.numUpdatedRows??0)}async getEvent(Y,Q){let X=await this.db.selectFrom("events").selectAll().where("id","=",Y).where("organization_id","=",Q).executeTakeFirst();if(!X)return null;return{id:X.id,organizationId:X.organization_id,type:X.type,source:X.source,specversion:X.specversion,subject:X.subject,time:X.time,datacontenttype:X.datacontenttype,dataschema:X.dataschema,data:X.data?JSON.parse(X.data):null,cron:X.cron,status:X.status,attempts:X.attempts,lastError:X.last_error,nextRetryAt:X.next_retry_at,createdAt:X.created_at,updatedAt:X.updated_at}}async findActiveCronEvent(Y,Q,X,J){let G=await this.db.selectFrom("events").selectAll().where("organization_id","=",Y).where("type","=",Q).where("source","=",X).where("cron","=",J).where("status","in",["pending","processing","delivered"]).orderBy("created_at","desc").executeTakeFirst();if(!G)return null;return{id:G.id,organizationId:G.organization_id,type:G.type,source:G.source,specversion:G.specversion,subject:G.subject,time:G.time,datacontenttype:G.datacontenttype,dataschema:G.dataschema,data:G.data?JSON.parse(G.data):null,cron:G.cron,status:G.status,attempts:G.attempts,lastError:G.last_error,nextRetryAt:G.next_retry_at,createdAt:G.created_at,updatedAt:G.updated_at}}async cancelEvent(Y,Q,X){let J=await this.db.updateTable("events").set({status:"failed",last_error:"Cancelled by publisher",updated_at:new Date().toISOString()}).where("id","=",Y).where("organization_id","=",Q).where("source","=",X).where("status","in",["pending","processing"]).executeTakeFirst();if((J.numUpdatedRows??0n)>0n)await this.db.updateTable("event_deliveries").set({status:"failed",last_error:"Event cancelled by publisher"}).where("event_id","=",Y).where("status","in",["pending","processing"]).execute();return{success:(J.numUpdatedRows??0n)>0n}}async scheduleRetryWithoutAttemptIncrement(Y,Q){if(Y.length===0)return;let X=new Date(Date.now()+Q).toISOString();await this.db.updateTable("event_deliveries").set({status:"pending",next_retry_at:X}).where("id","in",Y).execute()}async ackDelivery(Y,Q,X){if(!await this.db.selectFrom("events").select(["id"]).where("id","=",Y).where("organization_id","=",Q).executeTakeFirst())return{success:!1};let K=((await this.db.updateTable("event_deliveries").set({status:"delivered",delivered_at:new Date().toISOString()}).where("event_id","=",Y).where("status","in",["pending","processing"]).where((W)=>W.exists(W.selectFrom("event_subscriptions").select("id").whereRef("event_subscriptions.id","=","event_deliveries.subscription_id").where("event_subscriptions.connection_id","=",X).where("event_subscriptions.organization_id","=",Q))).executeTakeFirst()).numUpdatedRows??0n)>0n;if(K)await this.updateEventStatus(Y);return{success:K}}async syncSubscriptions(Y){let{organizationId:Q,connectionId:X,subscriptions:J}=Y,G=(w,E)=>{return`${w}::${E??""}`},K=await this.listSubscriptions(Q,X),W=new Map;for(let w of K)W.set(G(w.eventType,w.publisher),w);let Z=new Map;for(let w of J)Z.set(G(w.eventType,w.publisher),w);let H=new Date().toISOString(),$=[],F=[],V=[],B=0;for(let[w,E]of Z){let T=W.get(w);if(!T)$.push({id:crypto.randomUUID(),organization_id:Q,connection_id:X,event_type:E.eventType,publisher:E.publisher??null,filter:E.filter??null,enabled:1,created_at:H,updated_at:H});else{let C=T.filter??null,P=E.filter??null;if(C!==P)F.push({id:T.id,filter:P});else B++}}for(let[w,E]of W)if(!Z.has(w))V.push(E.id);if($.length>0)await this.db.insertInto("event_subscriptions").values($).execute();if(F.length>0)await Promise.all(F.map((w)=>this.db.updateTable("event_subscriptions").set({filter:w.filter,updated_at:H}).where("id","=",w.id).execute()));if(V.length>0)await this.db.deleteFrom("event_subscriptions").where("id","in",V).execute();let U=$.length,D=F.length,z=V.length,L=await this.listSubscriptions(Q,X);return{created:U,updated:D,deleted:z,unchanged:B,subscriptions:L}}}function Bi0(Y){return new qi0(Y)}function hJ(Y,Q,X,J,G,K,W,Z){return hJ.fromTZ(hJ.tp(Y,Q,X,J,G,K,W),Z)}hJ.fromTZISO=(Y,Q,X)=>hJ.fromTZ(Nu6(Y,Q),X);hJ.fromTZ=function(Y,Q){let X=new Date(Date.UTC(Y.y,Y.m-1,Y.d,Y.h,Y.i,Y.s)),J=qN1(Y.tz,X),G=new Date(X.getTime()-J),K=qN1(Y.tz,G);if(K-J===0)return G;{let W=new Date(X.getTime()-K),Z=qN1(Y.tz,W);if(Z-K===0)return W;if(!Q&&Z-K>0)return W;if(Q)throw Error("Invalid date passed to fromTZ()");return G}};hJ.toTZ=function(Y,Q){let X=Y.toLocaleString("en-US",{timeZone:Q}).replace(/[\u202f]/," "),J=new Date(X);return{y:J.getFullYear(),m:J.getMonth()+1,d:J.getDate(),h:J.getHours(),i:J.getMinutes(),s:J.getSeconds(),tz:Q}};hJ.tp=(Y,Q,X,J,G,K,W)=>({y:Y,m:Q,d:X,h:J,i:G,s:K,tz:W});function qN1(Y,Q=new Date){let X=Q.toLocaleString("en-US",{timeZone:Y,timeZoneName:"shortOffset"}).split(" ").slice(-1)[0],J=Q.toLocaleString("en-US").replace(/[\u202f]/," ");return Date.parse(`${J} GMT`)-Date.parse(`${J} ${X}`)}function Nu6(Y,Q){let X=new Date(Date.parse(Y));if(isNaN(X))throw Error("minitz: Invalid ISO8601 passed to parser.");let J=Y.substring(9);return Y.includes("Z")||J.includes("-")||J.includes("+")?hJ.tp(X.getUTCFullYear(),X.getUTCMonth()+1,X.getUTCDate(),X.getUTCHours(),X.getUTCMinutes(),X.getUTCSeconds(),"Etc/UTC"):hJ.tp(X.getFullYear(),X.getMonth()+1,X.getDate(),X.getHours(),X.getMinutes(),X.getSeconds(),Q)}hJ.minitz=hJ;var BN1=32,wv=31|BN1,Oi0=[1,2,4,8,16],Ui0=class{pattern;timezone;second;minute;hour;day;month;dayOfWeek;lastDayOfMonth;starDOM;starDOW;constructor(Y,Q){this.pattern=Y,this.timezone=Q,this.second=Array(60).fill(0),this.minute=Array(60).fill(0),this.hour=Array(24).fill(0),this.day=Array(31).fill(0),this.month=Array(12).fill(0),this.dayOfWeek=Array(7).fill(0),this.lastDayOfMonth=!1,this.starDOM=!1,this.starDOW=!1,this.parse()}parse(){if(!(typeof this.pattern=="string"||this.pattern instanceof String))throw TypeError("CronPattern: Pattern has to be of type string.");this.pattern.indexOf("@")>=0&&(this.pattern=this.handleNicknames(this.pattern).trim());let Y=this.pattern.replace(/\s+/g," ").split(" ");if(Y.length<5||Y.length>6)throw TypeError("CronPattern: invalid configuration format ('"+this.pattern+"'), exactly five or six space separated parts are required.");if(Y.length===5&&Y.unshift("0"),Y[3].indexOf("L")>=0&&(Y[3]=Y[3].replace("L",""),this.lastDayOfMonth=!0),Y[3]=="*"&&(this.starDOM=!0),Y[4].length>=3&&(Y[4]=this.replaceAlphaMonths(Y[4])),Y[5].length>=3&&(Y[5]=this.replaceAlphaDays(Y[5])),Y[5]=="*"&&(this.starDOW=!0),this.pattern.indexOf("?")>=0){let Q=new fW(new Date,this.timezone).getDate(!0);Y[0]=Y[0].replace("?",Q.getSeconds().toString()),Y[1]=Y[1].replace("?",Q.getMinutes().toString()),Y[2]=Y[2].replace("?",Q.getHours().toString()),this.starDOM||(Y[3]=Y[3].replace("?",Q.getDate().toString())),Y[4]=Y[4].replace("?",(Q.getMonth()+1).toString()),this.starDOW||(Y[5]=Y[5].replace("?",Q.getDay().toString()))}this.throwAtIllegalCharacters(Y),this.partToArray("second",Y[0],0,1),this.partToArray("minute",Y[1],0,1),this.partToArray("hour",Y[2],0,1),this.partToArray("day",Y[3],-1,1),this.partToArray("month",Y[4],-1,1),this.partToArray("dayOfWeek",Y[5],0,wv),this.dayOfWeek[7]&&(this.dayOfWeek[0]=this.dayOfWeek[7])}partToArray(Y,Q,X,J){let G=this[Y],K=Y==="day"&&this.lastDayOfMonth;if(Q===""&&!K)throw TypeError("CronPattern: configuration entry "+Y+" ("+Q+") is empty, check for trailing spaces.");if(Q==="*")return G.fill(J);let W=Q.split(",");if(W.length>1)for(let Z=0;Z<W.length;Z++)this.partToArray(Y,W[Z],X,J);else Q.indexOf("-")!==-1&&Q.indexOf("/")!==-1?this.handleRangeWithStepping(Q,Y,X,J):Q.indexOf("-")!==-1?this.handleRange(Q,Y,X,J):Q.indexOf("/")!==-1?this.handleStepping(Q,Y,X,J):Q!==""&&this.handleNumber(Q,Y,X,J)}throwAtIllegalCharacters(Y){for(let Q=0;Q<Y.length;Q++)if((Q===5?/[^/*0-9,\-#L]+/:/[^/*0-9,-]+/).test(Y[Q]))throw TypeError("CronPattern: configuration entry "+Q+" ("+Y[Q]+") contains illegal characters.")}handleNumber(Y,Q,X,J){let G=this.extractNth(Y,Q),K=parseInt(G[0],10)+X;if(isNaN(K))throw TypeError("CronPattern: "+Q+" is not a number: '"+Y+"'");this.setPart(Q,K,G[1]||J)}setPart(Y,Q,X){if(!Object.prototype.hasOwnProperty.call(this,Y))throw TypeError("CronPattern: Invalid part specified: "+Y);if(Y==="dayOfWeek"){if(Q===7&&(Q=0),Q<0||Q>6)throw RangeError("CronPattern: Invalid value for dayOfWeek: "+Q);this.setNthWeekdayOfMonth(Q,X);return}if(Y==="second"||Y==="minute"){if(Q<0||Q>=60)throw RangeError("CronPattern: Invalid value for "+Y+": "+Q)}else if(Y==="hour"){if(Q<0||Q>=24)throw RangeError("CronPattern: Invalid value for "+Y+": "+Q)}else if(Y==="day"){if(Q<0||Q>=31)throw RangeError("CronPattern: Invalid value for "+Y+": "+Q)}else if(Y==="month"&&(Q<0||Q>=12))throw RangeError("CronPattern: Invalid value for "+Y+": "+Q);this[Y][Q]=X}handleRangeWithStepping(Y,Q,X,J){let G=this.extractNth(Y,Q),K=G[0].match(/^(\d+)-(\d+)\/(\d+)$/);if(K===null)throw TypeError("CronPattern: Syntax error, illegal range with stepping: '"+Y+"'");let[,W,Z,H]=K,$=parseInt(W,10)+X,F=parseInt(Z,10)+X,V=parseInt(H,10);if(isNaN($))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(F))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(isNaN(V))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(V===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(V>this[Q].length)throw TypeError("CronPattern: Syntax error, steps cannot be greater than maximum value of part ("+this[Q].length+")");if($>F)throw TypeError("CronPattern: From value is larger than to value: '"+Y+"'");for(let B=$;B<=F;B+=V)this.setPart(Q,B,G[1]||J)}extractNth(Y,Q){let X=Y,J;if(X.includes("#")){if(Q!=="dayOfWeek")throw Error("CronPattern: nth (#) only allowed in day-of-week field");J=X.split("#")[1],X=X.split("#")[0]}return[X,J]}handleRange(Y,Q,X,J){let G=this.extractNth(Y,Q),K=G[0].split("-");if(K.length!==2)throw TypeError("CronPattern: Syntax error, illegal range: '"+Y+"'");let W=parseInt(K[0],10)+X,Z=parseInt(K[1],10)+X;if(isNaN(W))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(Z))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(W>Z)throw TypeError("CronPattern: From value is larger than to value: '"+Y+"'");for(let H=W;H<=Z;H++)this.setPart(Q,H,G[1]||J)}handleStepping(Y,Q,X,J){let G=this.extractNth(Y,Q),K=G[0].split("/");if(K.length!==2)throw TypeError("CronPattern: Syntax error, illegal stepping: '"+Y+"'");K[0]===""&&(K[0]="*");let W=0;K[0]!=="*"&&(W=parseInt(K[0],10)+X);let Z=parseInt(K[1],10);if(isNaN(Z))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(Z===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(Z>this[Q].length)throw TypeError("CronPattern: Syntax error, max steps for part is ("+this[Q].length+")");for(let H=W;H<this[Q].length;H+=Z)this.setPart(Q,H,G[1]||J)}replaceAlphaDays(Y){return Y.replace(/-sun/gi,"-7").replace(/sun/gi,"0").replace(/mon/gi,"1").replace(/tue/gi,"2").replace(/wed/gi,"3").replace(/thu/gi,"4").replace(/fri/gi,"5").replace(/sat/gi,"6")}replaceAlphaMonths(Y){return Y.replace(/jan/gi,"1").replace(/feb/gi,"2").replace(/mar/gi,"3").replace(/apr/gi,"4").replace(/may/gi,"5").replace(/jun/gi,"6").replace(/jul/gi,"7").replace(/aug/gi,"8").replace(/sep/gi,"9").replace(/oct/gi,"10").replace(/nov/gi,"11").replace(/dec/gi,"12")}handleNicknames(Y){let Q=Y.trim().toLowerCase();return Q==="@yearly"||Q==="@annually"?"0 0 1 1 *":Q==="@monthly"?"0 0 1 * *":Q==="@weekly"?"0 0 * * 0":Q==="@daily"?"0 0 * * *":Q==="@hourly"?"0 * * * *":Y}setNthWeekdayOfMonth(Y,Q){if(typeof Q!="number"&&Q==="L")this.dayOfWeek[Y]=this.dayOfWeek[Y]|BN1;else if(Q===wv)this.dayOfWeek[Y]=wv;else if(Q<6&&Q>0)this.dayOfWeek[Y]=this.dayOfWeek[Y]|Oi0[Q-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${Q}, Type: ${typeof Q}`)}},Di0=[31,28,31,30,31,30,31,31,30,31,30,31],DF=[["month","year",0],["day","month",-1],["hour","day",0],["minute","hour",0],["second","minute",0]],fW=class Y{tz;ms;second;minute;hour;day;month;year;constructor(Q,X){if(this.tz=X,Q&&Q instanceof Date)if(!isNaN(Q))this.fromDate(Q);else throw TypeError("CronDate: Invalid date passed to CronDate constructor");else if(Q===void 0)this.fromDate(new Date);else if(Q&&typeof Q=="string")this.fromString(Q);else if(Q instanceof Y)this.fromCronDate(Q);else throw TypeError("CronDate: Invalid type ("+typeof Q+") passed to CronDate constructor")}isNthWeekdayOfMonth(Q,X,J,G){let K=new Date(Date.UTC(Q,X,J)).getUTCDay(),W=0;for(let Z=1;Z<=J;Z++)new Date(Date.UTC(Q,X,Z)).getUTCDay()===K&&W++;if(G&wv&&Oi0[W-1]&G)return!0;if(G&BN1){let Z=new Date(Date.UTC(Q,X+1,0)).getUTCDate();for(let H=J+1;H<=Z;H++)if(new Date(Date.UTC(Q,X,H)).getUTCDay()===K)return!1;return!0}return!1}fromDate(Q){if(this.tz!==void 0)if(typeof this.tz=="number")this.ms=Q.getUTCMilliseconds(),this.second=Q.getUTCSeconds(),this.minute=Q.getUTCMinutes()+this.tz,this.hour=Q.getUTCHours(),this.day=Q.getUTCDate(),this.month=Q.getUTCMonth(),this.year=Q.getUTCFullYear(),this.apply();else{let X=hJ.toTZ(Q,this.tz);this.ms=Q.getMilliseconds(),this.second=X.s,this.minute=X.i,this.hour=X.h,this.day=X.d,this.month=X.m-1,this.year=X.y}else this.ms=Q.getMilliseconds(),this.second=Q.getSeconds(),this.minute=Q.getMinutes(),this.hour=Q.getHours(),this.day=Q.getDate(),this.month=Q.getMonth(),this.year=Q.getFullYear()}fromCronDate(Q){this.tz=Q.tz,this.year=Q.year,this.month=Q.month,this.day=Q.day,this.hour=Q.hour,this.minute=Q.minute,this.second=Q.second,this.ms=Q.ms}apply(){if(this.month>11||this.day>Di0[this.month]||this.hour>59||this.minute>59||this.second>59||this.hour<0||this.minute<0||this.second<0){let Q=new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms));return this.ms=Q.getUTCMilliseconds(),this.second=Q.getUTCSeconds(),this.minute=Q.getUTCMinutes(),this.hour=Q.getUTCHours(),this.day=Q.getUTCDate(),this.month=Q.getUTCMonth(),this.year=Q.getUTCFullYear(),!0}else return!1}fromString(Q){if(typeof this.tz=="number"){let X=hJ.fromTZISO(Q);this.ms=X.getUTCMilliseconds(),this.second=X.getUTCSeconds(),this.minute=X.getUTCMinutes(),this.hour=X.getUTCHours(),this.day=X.getUTCDate(),this.month=X.getUTCMonth(),this.year=X.getUTCFullYear(),this.apply()}else return this.fromDate(hJ.fromTZISO(Q,this.tz))}findNext(Q,X,J,G){let K=this[X],W;J.lastDayOfMonth&&(this.month!==1?W=Di0[this.month]:W=new Date(Date.UTC(this.year,this.month+1,0,0,0,0,0)).getUTCDate());let Z=!J.starDOW&&X=="day"?new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay():void 0;for(let H=this[X]+G;H<J[X].length;H++){let $=J[X][H];if(X==="day"&&J.lastDayOfMonth&&H-G==W&&($=1),X==="day"&&!J.starDOW){let F=J.dayOfWeek[(Z+(H-G-1))%7];if(F&&F&wv)F=this.isNthWeekdayOfMonth(this.year,this.month,H-G,F)?1:0;else if(F)throw Error(`CronDate: Invalid value for dayOfWeek encountered. ${F}`);Q.legacyMode&&!J.starDOM?$=$||F:$=$&&F}if($)return this[X]=H-G,K!==this[X]?2:1}return 3}recurse(Q,X,J){let G=this.findNext(X,DF[J][0],Q,DF[J][2]);if(G>1){let K=J+1;for(;K<DF.length;)this[DF[K][0]]=-DF[K][2],K++;if(G===3)return this[DF[J][1]]++,this[DF[J][0]]=-DF[J][2],this.apply(),this.recurse(Q,X,0);if(this.apply())return this.recurse(Q,X,J-1)}return J+=1,J>=DF.length?this:this.year>=3000?null:this.recurse(Q,X,J)}increment(Q,X,J){return this.second+=X.interval!==void 0&&X.interval>1&&J?X.interval:1,this.ms=0,this.apply(),this.recurse(Q,X,0)}getDate(Q){return Q||this.tz===void 0?new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms):typeof this.tz=="number"?new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute-this.tz,this.second,this.ms)):hJ.fromTZ(hJ.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}};function Lu6(Y){if(Y===void 0&&(Y={}),delete Y.name,Y.legacyMode=Y.legacyMode===void 0?!0:Y.legacyMode,Y.paused=Y.paused===void 0?!1:Y.paused,Y.maxRuns=Y.maxRuns===void 0?1/0:Y.maxRuns,Y.catch=Y.catch===void 0?!1:Y.catch,Y.interval=Y.interval===void 0?0:parseInt(Y.interval.toString(),10),Y.utcOffset=Y.utcOffset===void 0?void 0:parseInt(Y.utcOffset.toString(),10),Y.unref=Y.unref===void 0?!1:Y.unref,Y.startAt&&(Y.startAt=new fW(Y.startAt,Y.timezone)),Y.stopAt&&(Y.stopAt=new fW(Y.stopAt,Y.timezone)),Y.interval!==null){if(isNaN(Y.interval))throw Error("CronOptions: Supplied value for interval is not a number");if(Y.interval<0)throw Error("CronOptions: Supplied value for interval can not be negative")}if(Y.utcOffset!==void 0){if(isNaN(Y.utcOffset))throw Error("CronOptions: Invalid value passed for utcOffset, should be number representing minutes offset from UTC.");if(Y.utcOffset<-870||Y.utcOffset>870)throw Error("CronOptions: utcOffset out of bounds.");if(Y.utcOffset!==void 0&&Y.timezone)throw Error("CronOptions: Combining 'utcOffset' with 'timezone' is not allowed.")}if(Y.unref!==!0&&Y.unref!==!1)throw Error("CronOptions: Unref should be either true, false or undefined(false).");return Y}function Mv(Y){return Object.prototype.toString.call(Y)==="[object Function]"||typeof Y=="function"||Y instanceof Function}function Mu6(Y){return Mv(Y)}function wu6(Y){typeof Deno<"u"&&typeof Deno.unrefTimer<"u"?Deno.unrefTimer(Y):Y&&typeof Y.unref<"u"&&Y.unref()}var zi0=30000,Ir=[],jr=class{name;options;_states;fn;constructor(Y,Q,X){let J,G;if(Mv(Q))G=Q;else if(typeof Q=="object")J=Q;else if(Q!==void 0)throw Error("Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).");if(Mv(X))G=X;else if(typeof X=="object")J=X;else if(X!==void 0)throw Error("Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).");if(this.name=J?.name,this.options=Lu6(J),this._states={kill:!1,blocking:!1,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:J?J.maxRuns:void 0,paused:J?J.paused:!1,pattern:new Ui0("* * * * *")},Y&&(Y instanceof Date||typeof Y=="string"&&Y.indexOf(":")>0)?this._states.once=new fW(Y,this.options.timezone||this.options.utcOffset):this._states.pattern=new Ui0(Y,this.options.timezone),this.name){if(Ir.find((K)=>K.name===this.name))throw Error("Cron: Tried to initialize new named job '"+this.name+"', but name already taken.");Ir.push(this)}return G!==void 0&&Mu6(G)&&(this.fn=G,this.schedule()),this}nextRun(Y){let Q=this._next(Y);return Q?Q.getDate(!1):null}nextRuns(Y,Q){this._states.maxRuns!==void 0&&Y>this._states.maxRuns&&(Y=this._states.maxRuns);let X=[],J=Q||this._states.currentRun||void 0;for(;Y--&&(J=this.nextRun(J));)X.push(J);return X}getPattern(){return this._states.pattern?this._states.pattern.pattern:void 0}isRunning(){let Y=this.nextRun(this._states.currentRun),Q=!this._states.paused,X=this.fn!==void 0,J=!this._states.kill;return Q&&X&&J&&Y!==null}isStopped(){return this._states.kill}isBusy(){return this._states.blocking}currentRun(){return this._states.currentRun?this._states.currentRun.getDate():null}previousRun(){return this._states.previousRun?this._states.previousRun.getDate():null}msToNext(Y){let Q=this._next(Y);return Q?Y instanceof fW||Y instanceof Date?Q.getTime()-Y.getTime():Q.getTime()-new fW(Y).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let Y=Ir.indexOf(this);Y>=0&&Ir.splice(Y,1)}pause(){return this._states.paused=!0,!this._states.kill}resume(){return this._states.paused=!1,!this._states.kill}schedule(Y){if(Y&&this.fn)throw Error("Cron: It is not allowed to schedule two functions using the same Croner instance.");Y&&(this.fn=Y);let Q=this.msToNext(),X=this.nextRun(this._states.currentRun);return Q==null||isNaN(Q)||X===null?this:(Q>zi0&&(Q=zi0),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(X),Q),this._states.currentTimeout&&this.options.unref&&wu6(this._states.currentTimeout),this)}async _trigger(Y){if(this._states.blocking=!0,this._states.currentRun=new fW(void 0,this.options.timezone||this.options.utcOffset),this.options.catch)try{this.fn!==void 0&&await this.fn(this,this.options.context)}catch(Q){Mv(this.options.catch)&&this.options.catch(Q,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new fW(Y,this.options.timezone||this.options.utcOffset),this._states.blocking=!1}async trigger(){await this._trigger()}runsLeft(){return this._states.maxRuns}_checkTrigger(Y){let Q=new Date,X=!this._states.paused&&Q.getTime()>=Y.getTime(),J=this._states.blocking&&this.options.protect;X&&!J?(this._states.maxRuns!==void 0&&this._states.maxRuns--,this._trigger()):X&&J&&Mv(this.options.protect)&&setTimeout(()=>this.options.protect(this),0),this.schedule()}_next(Y){let Q=!!(Y||this._states.currentRun),X=!1;!Y&&this.options.startAt&&this.options.interval&&([Y,Q]=this._calculatePreviousRun(Y,Q),X=!Y),Y=new fW(Y,this.options.timezone||this.options.utcOffset),this.options.startAt&&Y&&Y.getTime()<this.options.startAt.getTime()&&(Y=this.options.startAt);let J=this._states.once||new fW(Y,this.options.timezone||this.options.utcOffset);return!X&&J!==this._states.once&&(J=J.increment(this._states.pattern,this.options,Q)),this._states.once&&this._states.once.getTime()<=Y.getTime()||J===null||this._states.maxRuns!==void 0&&this._states.maxRuns<=0||this._states.kill||this.options.stopAt&&J.getTime()>=this.options.stopAt.getTime()?null:J}_calculatePreviousRun(Y,Q){let X=new fW(void 0,this.options.timezone||this.options.utcOffset),J=Y;if(this.options.startAt.getTime()<=X.getTime()){J=this.options.startAt;let G=J.getTime()+this.options.interval*1000;for(;G<=X.getTime();)J=new fW(J,this.options.timezone||this.options.utcOffset).increment(this._states.pattern,this.options,!0),G=J.getTime()+this.options.interval*1000;Q=!0}return J===null&&(J=void 0),[J,Q]}};class Av{localEmit=null;async start(Y){this.localEmit=Y}broadcast(Y,Q){this.localEmit?.(Y,Q)}async stop(){this.localEmit=null}}var Ni0=50,Li0=500;class Mi0{listeners=new Map;totalCount=0;strategy=new Av;started=!1;async start(Y){if(this.started){if(!Y)return;await this.stop()}if(Y)this.strategy=Y;await this.strategy.start((Q,X)=>this.localEmit(Q,X)),this.started=!0}async stop(){if(!this.started)return;await this.strategy.stop(),this.started=!1}add(Y){if(this.totalCount>=Li0)return console.warn(`[SSEHub] Total connection limit reached (${Li0})`),null;let Q=this.listeners.get(Y.organizationId);if(!Q)Q=new Map,this.listeners.set(Y.organizationId,Q);if(Q.size>=Ni0)return console.warn(`[SSEHub] Per-org connection limit reached for ${Y.organizationId} (${Ni0})`),null;return Q.set(Y.id,Y),this.totalCount++,Y.id}remove(Y,Q){let X=this.listeners.get(Y);if(!X)return;if(X.delete(Q)){if(this.totalCount--,X.size===0)this.listeners.delete(Y)}}emit(Y,Q){this.strategy.broadcast(Y,Q)}countForOrg(Y){return this.listeners.get(Y)?.size??0}get count(){return this.totalCount}localEmit(Y,Q){let X=this.listeners.get(Y);if(!X||X.size===0)return;for(let J of X.values()){if(J.typePatterns&&!Au6(Q.type,J.typePatterns))continue;try{J.push(Q)}catch{this.remove(Y,J.id)}}}}function Au6(Y,Q){for(let X of Q){if(X===Y)return!0;if(X.endsWith(".*")){let J=X.slice(0,-1);if(Y.startsWith(J))return!0}}return!1}var xJ=new Mi0;function wi0(Y){return{id:Y.id,type:Y.type,source:Y.source,subject:Y.subject,data:Y.data?Pu6(Y.data):void 0,time:Y.time}}function Pu6(Y){if(typeof Y==="string")try{return JSON.parse(Y)}catch{return Y}return Y}var Sr={pollIntervalMs:5000,batchSize:100,maxAttempts:20,retryDelayMs:1000,maxDelayMs:3600000};Yr();lS();function Eu6(Y){return Y.endsWith("_self")}function Tu6(Y){return Y.slice(0,-5)}function Ai0(){return async(Y,Q)=>{try{if(Eu6(Y)&&Xz1()){let W=Tu6(Y),Z=await UF.create();if(await xd0(Q,{organizationId:W,connectionId:Y,publish:async(F,V,B,U)=>{await Z.eventBus.publish(W,Y,{type:F,subject:V,data:B,deliverAt:U?.deliverAt})},createMCPProxy:async(F)=>{let V=await FN1(F,Z);return{callTool:async(B,U,D)=>{let z=await V.callTool(B,U,D);return{content:z.content,structuredContent:z.structuredContent,isError:z.isError}},close:()=>V.close()}}}))return{success:!0}}let X=await UF.create(),J=await FN1(Y,X),K=await dV1.forClient(DO(J)).ON_EVENTS({events:Q});return{success:K.success,error:K.error,retryAfter:K.retryAfter,results:K.results}}catch(X){let J=X instanceof Error?X.message:String(X);return console.error(`[EventBus] Failed to notify connection ${Y}:`,J),{success:!1,error:J}}}}function Pi0(Y){return{specversion:"1.0",id:Y.id,source:Y.source,type:Y.type,time:Y.time,subject:Y.subject??void 0,datacontenttype:Y.datacontenttype,dataschema:Y.dataschema??void 0,data:Y.data??void 0}}function Cu6(Y){let Q=new Map;for(let J of Y){let G=J.subscription.connectionId,K=Q.get(G);if(K){if(K.deliveryIds.push(J.delivery.id),!K.seenEventIds.has(J.event.id))K.seenEventIds.add(J.event.id),K.events.push(Pi0(J.event))}else Q.set(G,{connectionId:J.subscription.connectionId,deliveryIds:[J.delivery.id],events:[Pi0(J.event)],seenEventIds:new Set([J.event.id])})}let X=new Map;for(let[J,G]of Q)X.set(J,{connectionId:G.connectionId,deliveryIds:G.deliveryIds,events:G.events});return X}class UN1{storage;notifySubscriber;running=!1;processing=!1;pendingNotify=!1;config;constructor(Y,Q){this.storage=Y;this.notifySubscriber=Ai0(),this.config={...Sr,...Q}}async start(){if(this.running)return;let Y=await this.storage.resetStuckDeliveries();if(Y>0)console.log(`[EventBus] Reset ${Y} stuck deliveries from previous shutdown`);this.running=!0}stop(){this.running=!1,console.log("[EventBus] Worker stopped")}isRunning(){return this.running}async processNow(){if(!this.running)return;if(this.processing){this.pendingNotify=!0;return}this.processing=!0;try{do this.pendingNotify=!1,await this.processEvents();while(this.pendingNotify)}catch(Y){console.error("[EventBus] Error processing events:",Y)}finally{this.processing=!1}}async processEvents(){let Y=await this.storage.claimPendingDeliveries(this.config.batchSize);if(Y.length===0)return;let Q=Cu6(Y),X=new Set;await Promise.allSettled(Array.from(Q.entries()).map(async([J,G])=>{try{let K=await this.notifySubscriber(G.connectionId,G.events);if(K.results&&Object.keys(K.results).length>0)await this.processPerEventResults(G,K);else if(K.success)await this.storage.markDeliveriesDelivered(G.deliveryIds);else if(K.retryAfter&&K.retryAfter>0)await this.storage.scheduleRetryWithoutAttemptIncrement(G.deliveryIds,K.retryAfter);else await this.storage.markDeliveriesFailed(G.deliveryIds,K.error||"Subscriber returned success=false",this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}catch(K){let W=K instanceof Error?K.message:String(K);console.error(`[EventBus] Failed to notify subscription ${J}:`,W),await this.storage.markDeliveriesFailed(G.deliveryIds,W,this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}for(let K of Y)if(G.deliveryIds.includes(K.delivery.id))X.add(K.event.id)}));for(let J of X)try{await this.storage.updateEventStatus(J);let G=Y.find((K)=>K.event.id===J)?.event;if(G?.cron)await this.scheduleNextCronDelivery(G)}catch(G){console.error(`[EventBus] Failed to update event status ${J}:`,G)}}async processPerEventResults(Y,Q){let X=[],J=new Map,G=[],K=new Map;for(let W=0;W<Y.events.length;W++){let Z=Y.events?.[W];if(!Z)continue;let H=Y.deliveryIds?.[W];if(!H)continue;K.set(Z.id,H)}for(let W of Y.events){let Z=K.get(W.id);if(!Z)continue;let H=Q.results?.[W.id];if(H)if(H.success)X.push(Z);else if(H.retryAfter&&H.retryAfter>0){let $=J.get(H.retryAfter)||[];$.push(Z),J.set(H.retryAfter,$)}else G.push({deliveryId:Z,error:H.error||"Event processing failed"});else if(Q.success)X.push(Z);else if(Q.retryAfter&&Q.retryAfter>0){let $=J.get(Q.retryAfter)||[];$.push(Z),J.set(Q.retryAfter,$)}else G.push({deliveryId:Z,error:Q.error||"Batch processing failed"})}if(X.length>0)await this.storage.markDeliveriesDelivered(X);for(let[W,Z]of J)await this.storage.scheduleRetryWithoutAttemptIncrement(Z,W);if(G.length>0){let W=new Map;for(let{deliveryId:Z,error:H}of G){let $=W.get(H)||[];$.push(Z),W.set(H,$)}for(let[Z,H]of W)await this.storage.markDeliveriesFailed(H,Z,this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}}async scheduleNextCronDelivery(Y){if(!Y.cron)return;try{let X=new jr(Y.cron).nextRun();if(!X){console.log(`[EventBus] Cron expression for event ${Y.id} has no more runs`);return}let J=X.toISOString(),G=await this.storage.getMatchingSubscriptions(Y);if(G.length===0){console.log(`[EventBus] No subscriptions for cron event ${Y.id}, skipping next delivery`);return}await this.storage.createDeliveries(Y.id,G.map((K)=>K.id),J),console.log(`[EventBus] Scheduled next cron delivery for event ${Y.id} at ${J}`)}catch(Q){console.error(`[EventBus] Failed to schedule next cron delivery for event ${Y.id}:`,Q)}}}class DN1{storage;worker;notifyStrategy;running=!1;constructor(Y){this.storage=Y.storage,this.notifyStrategy=Y.notifyStrategy,this.worker=new UN1(this.storage,Y.config)}async publish(Y,Q,X){if(X.deliverAt&&X.cron)throw Error("Cannot set both deliverAt and cron. Use one or the other.");let J;if(X.cron){try{let F=new jr(X.cron).nextRun();if(!F)throw Error("Cron expression does not produce a next run time");J=F.toISOString()}catch($){throw Error(`Invalid cron expression: ${$ instanceof Error?$.message:String($)}`)}let H=await this.storage.findActiveCronEvent(Y,X.type,Q,X.cron);if(H)return H}let G=crypto.randomUUID(),K=new Date().toISOString(),W=await this.storage.publishEvent({id:G,organizationId:Y,type:X.type,source:Q,subject:X.subject,time:K,data:X.data,cron:X.cron});xJ.emit(Y,wi0(W));let Z=await this.storage.getMatchingSubscriptions(W);if(Z.length>0){let H=X.deliverAt??J;if(await this.storage.createDeliveries(G,Z.map(($)=>$.id),H),this.notifyStrategy&&!H)await this.notifyStrategy.notify(G).catch(($)=>{console.warn("[EventBus] Notify failed (non-critical):",$)})}return W}async subscribe(Y,Q){return this.storage.subscribe({id:crypto.randomUUID(),organizationId:Y,connectionId:Q.connectionId,publisher:Q.publisher,eventType:Q.eventType,filter:Q.filter})}async unsubscribe(Y,Q){return this.storage.unsubscribe(Q,Y)}async listSubscriptions(Y,Q){return this.storage.listSubscriptions(Y,Q)}async getSubscription(Y,Q){return this.storage.getSubscription(Q,Y)}async getEvent(Y,Q){return this.storage.getEvent(Q,Y)}async cancelEvent(Y,Q,X){return this.storage.cancelEvent(Q,Y,X)}async ackEvent(Y,Q,X){return this.storage.ackDelivery(Q,Y,X)}async syncSubscriptions(Y,Q){return this.storage.syncSubscriptions({organizationId:Y,...Q})}async start(){if(this.running)return;if(this.running=!0,await this.worker.start(),this.notifyStrategy)await this.notifyStrategy.start(()=>{this.worker.processNow().catch((Y)=>{console.error("[EventBus] Error processing after notify:",Y)})});await this.worker.processNow().catch((Y)=>{console.error("[EventBus] Error processing pending events on startup:",Y)})}async stop(){if(!this.running)return;if(this.running=!1,this.worker.stop(),this.notifyStrategy)try{await this.notifyStrategy.stop()}catch(Y){console.error("[EventBus] Error stopping notify strategy:",Y)}console.log("[EventBus] Stopped")}isRunning(){return this.running}}class zN1{options;sub=null;onNotify=null;encoder=new TextEncoder;constructor(Y){this.options=Y}async start(Y){let Q=this.options.getConnection();if(!Q||this.sub)return;this.onNotify=Y,this.sub=Q.subscribe("mesh.events.notify"),(async()=>{for await(let X of this.sub)this.onNotify?.()})().catch((X)=>{console.error("[NatsNotify] Subscription error:",X)}),console.log("[NatsNotify] Started, subscribed to","mesh.events.notify")}async stop(){this.sub?.unsubscribe(),this.sub=null,this.onNotify=null,console.log("[NatsNotify] Stopped")}async notify(Y){let Q=this.options.getConnection();if(!Q)return;try{Q.publish("mesh.events.notify",this.encoder.encode(Y))}catch(X){console.warn("[NatsNotify] Publish failed (non-critical):",X)}}}class ON1{options;sub=null;localEmit=null;originId=crypto.randomUUID();encoder=new TextEncoder;constructor(Y){this.options=Y}async start(Y){this.localEmit=Y;let Q=this.options.getConnection();if(!Q||this.sub)return;this.sub=Q.subscribe("mesh.sse.broadcast");let X=new TextDecoder;(async()=>{for await(let J of this.sub)try{let G=JSON.parse(X.decode(J.data));if(typeof G?.originId!=="string"||typeof G?.organizationId!=="string"||typeof G?.event?.id!=="string"||typeof G?.event?.type!=="string")continue;if(G.originId===this.originId)continue;this.localEmit?.(G.organizationId,G.event)}catch{}})().catch((J)=>{console.error("[NatsSSEBroadcast] Subscription error:",J)}),console.log("[NatsSSEBroadcast] Started, subscribed to","mesh.sse.broadcast")}broadcast(Y,Q){this.localEmit?.(Y,Q);let X=this.options.getConnection();if(!X)return;let J={originId:this.originId,organizationId:Y,event:Q};try{X.publish("mesh.sse.broadcast",this.encoder.encode(JSON.stringify(J)))}catch(G){console.warn("[NatsSSEBroadcast] Publish failed (non-critical):",G)}}async stop(){this.sub?.unsubscribe(),this.sub=null,this.localEmit=null,console.log("[NatsSSEBroadcast] Stopped")}}function NN1(...Y){return{async start(Q){await Promise.all(Y.map((X)=>X.start(Q)))},async stop(){await Promise.all(Y.map((Q)=>Q.stop().catch((X)=>{console.error("[NotifyStrategy] Error stopping strategy:",X)})))},async notify(Q){await Promise.all(Y.map((X)=>X.notify(Q).catch((J)=>{console.warn("[NotifyStrategy] Notify failed (non-critical):",J)})))}}}class LN1{intervalMs;timer=null;onNotify=null;constructor(Y){this.intervalMs=Y}async start(Y){if(this.timer)return;this.onNotify=Y,this.scheduleNext(),console.log(`[Polling] Started polling every ${this.intervalMs}ms`)}async stop(){if(this.timer)clearTimeout(this.timer),this.timer=null,console.log("[Polling] Stopped polling");this.onNotify=null}async notify(Y){if(this.onNotify)this.onNotify()}scheduleNext(){this.timer=setTimeout(()=>{if(this.onNotify)this.onNotify();if(this.timer)this.scheduleNext()},this.intervalMs)}}import{sql as Ru6}from"kysely";var LP="mesh_events";class MN1{db;pool;listenClient=null;onNotify=null;constructor(Y,Q){this.db=Y;this.pool=Q}async start(Y){if(this.listenClient)return;this.onNotify=Y;try{this.listenClient=await this.pool.connect(),this.listenClient.on("notification",(Q)=>{if(Q.channel===LP&&this.onNotify)this.onNotify()}),this.listenClient.on("error",(Q)=>{console.error("[PostgresNotify] Connection error:",Q),this.cleanup()}),await this.listenClient.query(`LISTEN ${LP}`),console.log("[PostgresNotify] Started LISTEN on",LP)}catch(Q){console.error("[PostgresNotify] Failed to start LISTEN:",Q),this.cleanup()}}async stop(){if(this.listenClient){try{await this.listenClient.query(`UNLISTEN ${LP}`),console.log("[PostgresNotify] Stopped LISTEN on",LP)}catch{}this.cleanup()}}async notify(Y){try{await Ru6`SELECT pg_notify(${LP}, ${Y})`.execute(this.db)}catch(Q){console.warn("[PostgresNotify] Failed to send NOTIFY:",Q)}}cleanup(){if(this.listenClient)this.listenClient.release(),this.listenClient=null;this.onNotify=null}}function Iu6(Y){let Q=process.env.NOTIFY_STRATEGY;if(Q==="nats"||Q==="postgres"||Q==="polling")return Q;if(process.env.NATS_URL)return"nats";if(Y.type==="postgres")return"postgres";return"polling"}function Ei0(Y,Q,X){let J=Bi0(Y.db),G=Q?.pollIntervalMs??Sr.pollIntervalMs,K=Iu6(Y),W=new LN1(G),Z=process.env.NATS_URL,H;switch(K){case"nats":{if(!Z)throw Error("[EventBus] NOTIFY_STRATEGY=nats requires NATS_URL to be set");let F=(()=>{try{return new URL(Z).host}catch{return"unknown"}})();if(!X){console.warn(`[EventBus] NATS unavailable (${F}), falling back to polling`),H=W;break}console.log(`[EventBus] Using NATS notify strategy (${F})`),H=NN1(W,new zN1({getConnection:()=>X.getConnection()}));break}case"postgres":{if(Y.type!=="postgres"){console.warn("[EventBus] NOTIFY_STRATEGY=postgres requires a PostgreSQL database, falling back to polling"),H=W;break}console.log("[EventBus] Using PostgreSQL LISTEN/NOTIFY strategy"),H=NN1(W,new MN1(Y.db,Y.pool));break}case"polling":default:console.log("[EventBus] Using polling notify strategy"),H=W}let $=Z&&X?new ON1({getConnection:()=>X.getConnection()}):new Av;if(xJ.start($).catch((F)=>{console.error("[SSEHub] Failed to start broadcast strategy:",F)}),Z&&X)console.log("[SSEHub] Using NATS SSE broadcast (cross-pod)");else console.log("[SSEHub] Using local SSE broadcast (single-pod)");return new DN1({storage:J,config:Q,notifyStrategy:H})}FN();Kv();var Ti0={google:{name:"Google",icon:"https://assets.decocache.com/webdraw/eb7480aa-a68b-4ce4-98ff-36aa121762a7/google.svg"},github:{name:"GitHub",icon:"https://assets.decocache.com/webdraw/5f999dcb-c8a6-4572-948c-9996ef1d502f/github.svg"},microsoft:{name:"Microsoft",icon:"https://assets.decocache.com/mcp/aa6f6e1a-6526-4bca-99cc-82e2ec38b0e4/microsoft.png"}};var Ci0=new JQ;Ci0.get("/config",async(Y)=>{try{let Q=Object.keys(p9.socialProviders??{}),X=Q.length>0,J=Q.map((W)=>({name:W,icon:Ti0[W].icon})),G=process.env.UNSAFE_ALLOW_STDIO_TRANSPORT==="true",K={emailAndPassword:{enabled:p9.emailAndPassword?.enabled??!1},magicLink:{enabled:p9.magicLinkConfig?.enabled??!1},resetPassword:{enabled:tO1},socialProviders:{enabled:X,providers:J},sso:p9.ssoConfig?{enabled:!0,providerId:p9.ssoConfig.providerId}:{enabled:!1},stdioEnabled:G};return Y.json({success:!0,config:K})}catch(Q){let X=Q instanceof Error?Q.message:"Failed to load auth config";return Y.json({success:!1,error:X},500)}});var Ri0=Ci0;zP();Uv();KY();rZ();vQ();rZ();rZ();c1();Jr();function Ii0(Y){let{toolOutputMap:Q}=Y;return _J({description:"The input is a string. Dont make assumptions about its format; prefer using regexes and string manipulation to extract the desired information. You may call this tool multiple times to extract the desired information.",inputExamples:[{input:{tool_call_id:"tool_call_id_1",code:"export default (input) => { return input.match(/[a-z]/g); }"}},{input:{tool_call_id:"tool_call_id_2",code:"export default (input) => { return input.split(' ').map(word => word.length); }"}}],inputSchema:m8(q.object({tool_call_id:q.string(),code:q.string().min(1).describe("JavaScript code to transform the tool output. The code must be an ES module: `export default (input) => { ... }`")})),execute:async({tool_call_id:X,code:J})=>{if(!Q.has(X))throw Error(`Tool output not found for tool call id: ${X}`);let G=Q.get(X),K=await Vz1({input:G,code:J,timeoutMs:5000}),W=wN1({return:K.returnValue});if(W>4000)throw Error(`Tool call ${X} output is too long to display (${W} tokens), reduce or truncate the output`);return{result:K.returnValue,error:K.error,consoleLogs:K.consoleLogs}}})}var ju6=4,Su6=/[\u3000-\u303f\u3040-\u309f\u30a0-\u30ff\u4e00-\u9fff\u3400-\u4dbf\uf900-\ufaff]/g;function ku6(Y){if(!Y)return 0;let Q=Y.match(Su6)?.length??0,X=Y.length-Q;return Math.ceil(X/ju6)+Math.ceil(Q*1.5)}function wN1(Y){let Q=typeof Y==="string"?Y:JSON.stringify(Y);return ku6(Q)}function kr(Y,Q){if(Y==="yolo")return!1;if(Y==="none")return!0;return Q!==!0}function vr(Y){let Q=Y.get("meshContext").organization;if(!Q)throw Error("Organization context is required");if((Q.slug??Q.id)!==Y.req.param("org"))throw Error("Organization mismatch");return Q}async function Pv(Y,Q,X,J="none",G){let K=!G?.disableOutputTruncation,Z=(await Y.listTools()).tools.map((H)=>{let{name:$,title:F,description:V,inputSchema:B,annotations:U}=H;return[$,_J({title:F??$,description:V,inputSchema:IW(B),outputSchema:void 0,needsApproval:kr(J,U?.readOnlyHint),execute:async(D,z)=>{let L=performance.now();try{return await Y.callTool({name:H.name,arguments:D},dK,{signal:z.abortSignal,timeout:en0})}finally{if(X){let w=performance.now()-L;X.write({type:"data-tool-metadata",id:z.toolCallId,data:{annotations:H.annotations,latencyMs:w}})}}},toModelOutput:async({output:D,toolCallId:z})=>{if(K){let w=wN1(D.structuredContent??D.content);if(w>4000)return Q.set(z,JSON.stringify(D.structuredContent??D.content)),{type:"text",value:`Tool call ${z} output is too long to display (${w} tokens), use the read_tool_output tool`}}if(D.isError)return{type:"error-text",value:D.content.map((E)=>E.type==="text"?E.text:null).filter(Boolean).join(`
|
|
1391
|
-
`)||"Unknown error"};if("structuredContent"in
|
|
1390
|
+
Example output: Available Tools Overview`;function Rr(Y){return typeof Y==="string"?Y:Y.toISOString()}class Lv{db;constructor(Y){this.db=Y}async create(Y){let Q=Y.id??X9("thrd"),X=new Date().toISOString();if(!Y.organization_id)throw Error("organization_id is required");if(!Y.created_by)throw Error("created_by is required");if(!Y.title)Y.title=Cr;let J={id:Q,organization_id:Y.organization_id,title:Y.title,description:Y.description??null,status:Y.status??"completed",created_at:X,updated_at:X,created_by:Y.created_by,updated_by:Y.updated_by??null},G=await this.db.insertInto("threads").values(J).returningAll().executeTakeFirstOrThrow();return this.threadFromDbRow(G)}async get(Y){let Q=await this.db.selectFrom("threads").selectAll().where("id","=",Y).executeTakeFirst();return Q?this.threadFromDbRow(Q):null}async update(Y,Q){let J={updated_at:new Date().toISOString()};if(Q.title!==void 0)J.title=Q.title;if(Q.description!==void 0)J.description=Q.description;if(Q.updated_by!==void 0)J.updated_by=Q.updated_by;if(Q.hidden!==void 0)J.hidden=Q.hidden;if(Q.status!==void 0)J.status=Q.status;await this.db.updateTable("threads").set(J).where("id","=",Y).execute();let G=await this.get(Y);if(!G)throw Error("Thread not found after update");return G}async delete(Y){await this.db.deleteFrom("threads").where("id","=",Y).execute()}async list(Y,Q,X){let J=this.db.selectFrom("threads").selectAll().where("organization_id","=",Y).where("hidden","=",!1).orderBy("updated_at","desc");if(Q)J=J.where("created_by","=",Q);let G=this.db.selectFrom("threads").select((Z)=>Z.fn.count("id").as("count")).where("organization_id","=",Y).where("hidden","=",!1);if(Q)G=G.where("created_by","=",Q);if(X?.limit)J=J.limit(X.limit);if(X?.offset)J=J.offset(X.offset);let[K,W]=await Promise.all([J.execute(),G.executeTakeFirst()]);return{threads:K.map((Z)=>this.threadFromDbRow(Z)),total:Number(W?.count||0)}}async saveMessages(Y){let Q=new Date().toISOString(),X=Y[0]?.thread_id;if(!X)throw Error("thread_id is required when creating multiple messages");let J=new Map;for(let Z of Y){let H=J.get(Z.id);if(H&&H.thread_id!==Z.thread_id)throw Error(`Duplicate message id "${Z.id}" with conflicting thread_ids: "${H.thread_id}" vs "${Z.thread_id}"`);J.set(Z.id,Z)}let G=[...J.values()],K=G.find((Z)=>Z.thread_id!==X);if(K)throw Error(`All messages must target the same thread. Expected thread_id "${X}", but message "${K.id}" has thread_id "${K.thread_id}"`);let W=G.map((Z)=>({id:Z.id,thread_id:X,metadata:Z.metadata?JSON.stringify(Z.metadata):null,parts:JSON.stringify(Z.parts),role:Z.role,created_at:Z.created_at??Q,updated_at:Q}));await this.db.transaction().execute(async(Z)=>{await Z.insertInto("thread_messages").values(W).onConflict((H)=>H.column("id").doUpdateSet(($)=>({metadata:$.ref("excluded.metadata"),parts:$.ref("excluded.parts"),role:$.ref("excluded.role"),updated_at:$.ref("excluded.updated_at")}))).execute(),await Z.updateTable("threads").set({updated_at:Q}).where("id","=",X).execute()})}async listMessages(Y,Q){let X=Q?.sort??"asc",J=this.db.selectFrom("thread_messages").selectAll().where("thread_id","=",Y).orderBy("created_at",X).orderBy("id",X),G=this.db.selectFrom("thread_messages").select((Z)=>Z.fn.count("id").as("count")).where("thread_id","=",Y);if(Q?.limit)J=J.limit(Q.limit);if(Q?.offset)J=J.offset(Q.offset);let[K,W]=await Promise.all([J.execute(),G.executeTakeFirst()]);return{messages:K.map((Z)=>this.messageFromDbRow(Z)),total:Number(W?.count||0)}}threadFromDbRow(Y){return{id:Y.id,organization_id:Y.organization_id,title:Y.title,description:Y.description,status:Y.status,created_at:Rr(Y.created_at),updated_at:Rr(Y.updated_at),created_by:Y.created_by,updated_by:Y.updated_by,hidden:!!Y.hidden}}messageFromDbRow(Y){let Q,X;try{Q=Y.metadata?JSON.parse(Y.metadata):void 0}catch(J){console.error(`Failed to parse metadata for message ${Y.id}:`,Y.metadata,J),Q=void 0}try{X=typeof Y.parts==="string"?JSON.parse(Y.parts):Y.parts}catch(J){console.error(`Failed to parse parts for message ${Y.id}:`,Y.parts,J),X=[]}return{id:Y.id,thread_id:Y.thread_id,metadata:Q,parts:X,role:Y.role,created_at:Rr(Y.created_at),updated_at:Rr(Y.updated_at)}}}Ez1();function qu6(Y){if(!Y)return;try{let Q=JSON.parse(Y);if(typeof Q!=="object"||Q===null||Array.isArray(Q))return;let X={};for(let[J,G]of Object.entries(Q))if(typeof G==="string")X[J]=G;return Object.keys(X).length>0?X:void 0}catch{return}}function Bu6(Y,Q){for(let[X,J]of Object.entries(Q)){let G=Y[X];if(!G||G.length===0){let K=Y["*"];if(!K||K.length===0)return!1;if(K.includes("*"))continue;for(let W of J)if(!K.includes(W))return!1;continue}if(G.includes("*"))continue;for(let K of J)if(!G.includes(K))return!1}return!0}function Uu6(Y){let{auth:Q,headers:X,role:J,permissions:G,userId:K}=Y,W=Q.api.hasPermission;return{hasPermission:async(Z)=>{if(J&&oO1.includes(J))return!0;if(G)return Bu6(G,Z);if(!W)return console.error("[Auth] hasPermission API not available"),!1;try{if((await W({headers:X,body:{permission:Z}}))?.success===!0)return!0;let $={};for(let V of Object.keys(Z))$[V]=["*"];return(await W({headers:X,body:{permission:$}}))?.success===!0}catch(H){return console.error("[Auth] Permission check failed:",H),!1}},organization:{create:async(Z)=>{return Q.api.createOrganization({headers:X,body:Z})},update:async(Z)=>{return Q.api.updateOrganization({headers:X,body:Z})},delete:async(Z)=>{await Q.api.deleteOrganization({headers:X,body:{organizationId:Z}})},get:async(Z)=>{return Q.api.getFullOrganization({headers:X,query:Z?{organizationId:Z}:void 0})},list:async(Z)=>{return Q.api.listOrganizations({headers:X,query:Z?{userId:Z}:void 0})},addMember:async(Z)=>{return Q.api.addMember({headers:X,body:Z})},removeMember:async(Z)=>{await Q.api.removeMember({headers:X,body:Z})},listMembers:async(Z)=>{return Q.api.listMembers({headers:X,query:Z?{organizationId:Z.organizationId,limit:Z.limit,offset:Z.offset}:void 0})},updateMemberRole:async(Z)=>{return Q.api.updateMemberRole({headers:X,body:Z})}},apiKey:{create:async(Z)=>{return Q.api.createApiKey({body:{...Z,userId:K}})},list:async()=>{return Q.api.listApiKeys({headers:X})},update:async(Z)=>{return Q.api.updateApiKey({body:{...Z,userId:K}})},delete:async(Z)=>{await Q.api.deleteApiKey({headers:X,body:{keyId:Z}})}}}}async function Du6(Y,Q,X){if(oO1.includes(X))return;let J=await Y.selectFrom("organizationRole").select(["permission"]).where("organizationId","=",Q).where("role","=",X).executeTakeFirst();if(!J?.permission)return;try{return JSON.parse(J.permission)}catch{console.error(`[Auth] Failed to parse permissions for role: ${X}`);return}}async function zu6(Y,Q,X,J=Fi0){let G=Y.headers.get("Authorization");try{let K=new Headers(Y.headers);K.set("X-MCP-Session-Auth","true");let W=await J.measure("auth_get_mcp_session",()=>Q.api.getMcpSession({headers:K}));if(W){let Z=W.userId,H=await J.measure("auth_query_membership",()=>X.selectFrom("member").innerJoin("organization","organization.id","member.organizationId").select(["member.role","member.organizationId","organization.id as orgId","organization.slug as orgSlug","organization.name as orgName"]).where("member.userId","=",Z).executeTakeFirst()),$=H?.role,F=H?{id:H.orgId,slug:H.orgSlug,name:H.orgName}:void 0,V;if(H&&$)V=await J.measure("auth_fetch_role_permissions",()=>Du6(X,H.organizationId,$));return{user:{id:Z,role:$},role:$,permissions:V,organization:F}}}catch(K){console.error("[Auth] OAuth session check failed:",K)}if(G?.startsWith("Bearer ")){let K=G.replace("Bearer ","").trim();try{let W=await J.measure("auth_verify_mesh_jwt",()=>Sp0(K));if(W){let Z,H=W.metadata?.organizationId;if(W.sub&&H)Z=(await J.measure("auth_query_membership",()=>X.selectFrom("member").select(["member.role"]).where("member.userId","=",W.sub).where("member.organizationId","=",H).executeTakeFirst()))?.role;return{user:{id:W.sub,connectionId:W.metadata?.connectionId,role:Z},role:Z,permissions:W.permissions,organization:W.metadata?.organizationId?{id:W.metadata?.organizationId}:void 0}}}catch{}try{let W=await J.measure("auth_verify_api_key",()=>Q.api.verifyApiKey({body:{key:K}}));if(W?.valid&&W.key){let Z=W.key.metadata?.organization,H=W.key.permissions,$,F=W.key.userId;if(F&&Z?.id)$=(await J.measure("auth_query_membership",()=>X.selectFrom("member").select(["member.role"]).where("member.userId","=",F).where("member.organizationId","=",Z.id).executeTakeFirst()))?.role;return{apiKeyId:W.key.id,user:{id:W.key.userId,role:$},role:$,permissions:H,organization:Z?{id:Z.id,slug:Z.slug,name:Z.name}:void 0}}}catch(W){console.error("[Auth] API key check failed:",W)}}try{let K=new Headers(Y.headers);K.delete("Authorization");let W=await J.measure("auth_get_session",()=>Q.api.getSession({headers:K}));if(W){let Z,H;if(W.session.activeOrganizationId){let $=await J.measure("auth_get_full_organization",()=>Q.api.getFullOrganization({headers:K}).catch(()=>null));if($)Z={id:$.id,slug:$.slug,name:$.name},H=$.members?.find((V)=>V.userId===W.user.id)?.role;else Z={id:W.session.activeOrganizationId,slug:"",name:""}}return{user:{id:W.user.id,email:W.user.email,role:H},role:H,organization:Z}}}catch(K){let W=K;console.error("[Auth] Session check failed:",JSON.stringify({message:W.message,body:W.body,stack:W.stack},null,2))}return{user:void 0}}var $i0,UF={set:(Y)=>{$i0=Y},create:async(Y,Q)=>{return await $i0(Y,Q)}},Fi0={measure:async(Y,Q)=>{return await Q()}},Ou6=["x-hub-signature-256"];async function Vi0(Y){let Q=new Rz(Y.encryption.key),X={connections:new DS(Y.db,Q),organizationSettings:new JN1(Y.db),monitoring:new QN1(Y.db,Y.databaseType),monitoringDashboards:new XN1(Y.db),virtualMcps:new eO1(Y.db),users:new ZN1(Y.db),threads:new Lv(Y.db),tags:new WN1(Y.db),projects:new zS(Y.db),projectPluginConfigs:new GN1(Y.db)};return async(J,G)=>{let K=G?.timings??Fi0,W=Br(),Z=J?.headers.get("x-caller-id")??void 0,H=J?await zu6(J,Y.auth,Y.db,K):{user:void 0},$=Uu6({auth:Y.auth,headers:J?.headers??new Headers,role:H.role,permissions:H.permissions,userId:H.user?.id}),F={user:H.user};if(H.apiKeyId)F.apiKey={id:H.apiKeyId,name:"",userId:""};let V=H.organization,B=J?process.env.BASE_URL??`${new URL(J.url).origin}`:K7(),U=new FF(Y.auth,F.user?.id,void 0,$,H.role,"self"),D={timings:K,auth:F,connectionId:Z,organization:V,storage:X,vault:Q,authInstance:Y.auth,boundAuth:$,access:U,db:Y.db,tracer:Y.observability.tracer,meter:Y.observability.meter,baseUrl:B,metadata:{requestId:crypto.randomUUID(),timestamp:new Date,wellKnownForwardableHeaders:Object.fromEntries(Ou6.map((z)=>[z,J?.headers.get(z)??null]).filter(([z,L])=>L!==null)),userAgent:J?.headers.get("x-mesh-client")||J?.headers.get("User-Agent")||void 0,ipAddress:(J?.headers.get("CF-Connecting-IP")||J?.headers.get("X-Forwarded-For"))??void 0,properties:qu6(J?.headers.get("x-mesh-properties"))},eventBus:Y.eventBus,createMCPProxy:async(z)=>{return await Qi0(z,D)},getOrCreateClient:W};return D}}En();class qi0{db;constructor(Y){this.db=Y}async publishEvent(Y){let Q=new Date().toISOString();return await this.db.insertInto("events").values({id:Y.id,organization_id:Y.organizationId,type:Y.type,source:Y.source,specversion:"1.0",subject:Y.subject??null,time:Y.time,datacontenttype:Y.datacontenttype??"application/json",dataschema:Y.dataschema??null,data:Y.data?JSON.stringify(Y.data):null,cron:Y.cron??null,status:"pending",attempts:0,last_error:null,next_retry_at:null,created_at:Q,updated_at:Q}).execute(),{id:Y.id,organizationId:Y.organizationId,type:Y.type,source:Y.source,specversion:"1.0",subject:Y.subject??null,time:Y.time,datacontenttype:Y.datacontenttype??"application/json",dataschema:Y.dataschema??null,data:Y.data??null,cron:Y.cron??null,status:"pending",attempts:0,lastError:null,nextRetryAt:null,createdAt:Q,updatedAt:Q}}async subscribe(Y){let Q=this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",Y.organizationId).where("connection_id","=",Y.connectionId).where("event_type","=",Y.eventType);if(Y.publisher)Q=Q.where("publisher","=",Y.publisher);else Q=Q.where("publisher","is",null);if(Y.filter)Q=Q.where("filter","=",Y.filter);else Q=Q.where("filter","is",null);let X=await Q.executeTakeFirst();if(X)return{id:X.id,organizationId:X.organization_id,connectionId:X.connection_id,publisher:X.publisher,eventType:X.event_type,filter:X.filter,enabled:X.enabled===1,createdAt:X.created_at,updatedAt:X.updated_at};let J=new Date().toISOString();return await this.db.insertInto("event_subscriptions").values({id:Y.id,organization_id:Y.organizationId,connection_id:Y.connectionId,publisher:Y.publisher??null,event_type:Y.eventType,filter:Y.filter??null,enabled:1,created_at:J,updated_at:J}).execute(),{id:Y.id,organizationId:Y.organizationId,connectionId:Y.connectionId,publisher:Y.publisher??null,eventType:Y.eventType,filter:Y.filter??null,enabled:!0,createdAt:J,updatedAt:J}}async unsubscribe(Y,Q){return{success:((await this.db.deleteFrom("event_subscriptions").where("id","=",Y).where("organization_id","=",Q).executeTakeFirst()).numDeletedRows??0n)>0n}}async listSubscriptions(Y,Q){let X=this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",Y);if(Q)X=X.where("connection_id","=",Q);return(await X.execute()).map((G)=>({id:G.id,organizationId:G.organization_id,connectionId:G.connection_id,publisher:G.publisher,eventType:G.event_type,filter:G.filter,enabled:G.enabled===1,createdAt:G.created_at,updatedAt:G.updated_at}))}async getSubscription(Y,Q){let X=await this.db.selectFrom("event_subscriptions").selectAll().where("id","=",Y).where("organization_id","=",Q).executeTakeFirst();if(!X)return null;return{id:X.id,organizationId:X.organization_id,connectionId:X.connection_id,publisher:X.publisher,eventType:X.event_type,filter:X.filter,enabled:X.enabled===1,createdAt:X.created_at,updatedAt:X.updated_at}}async getMatchingSubscriptions(Y){return(await this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",Y.organizationId).where("enabled","=",1).where("event_type","=",Y.type).where((X)=>X.or([X("publisher","is",null),X("publisher","=",Y.source)])).execute()).map((X)=>({id:X.id,organizationId:X.organization_id,connectionId:X.connection_id,publisher:X.publisher,eventType:X.event_type,filter:X.filter,enabled:X.enabled===1,createdAt:X.created_at,updatedAt:X.updated_at}))}async createDeliveries(Y,Q,X){if(Q.length===0)return;let J=new Date().toISOString(),G=X??null,K=Q.map((W)=>({id:crypto.randomUUID(),event_id:Y,subscription_id:W,status:"pending",attempts:0,last_error:null,delivered_at:null,next_retry_at:G,created_at:J}));await this.db.insertInto("event_deliveries").values(K).execute()}async claimPendingDeliveries(Y){let Q=new Date().toISOString(),X;try{X=(await this.db.updateTable("event_deliveries").set({status:"processing"}).where("id","in",(K)=>K.selectFrom("event_deliveries as d").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select("d.id").where("d.status","=","pending").where("s.enabled","=",1).where((W)=>W.or([W("d.next_retry_at","is",null),W("d.next_retry_at","<=",Q)])).orderBy("d.created_at","asc").limit(Y)).where("status","=","pending").returning(["id"]).execute()).map((K)=>K.id)}catch{let G=await this.db.selectFrom("event_deliveries as d").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select(["d.id"]).where("d.status","=","pending").where("s.enabled","=",1).where((K)=>K.or([K("d.next_retry_at","is",null),K("d.next_retry_at","<=",Q)])).orderBy("d.created_at","asc").limit(Y).execute();if(G.length===0)return[];X=G.map((K)=>K.id),await this.db.updateTable("event_deliveries").set({status:"processing"}).where("id","in",X).where("status","=","pending").execute()}if(X.length===0)return[];return(await this.db.selectFrom("event_deliveries as d").innerJoin("events as e","e.id","d.event_id").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select(["d.id as delivery_id","d.event_id","d.subscription_id","d.status as delivery_status","d.attempts as delivery_attempts","d.last_error as delivery_last_error","d.delivered_at","d.next_retry_at as delivery_next_retry_at","d.created_at as delivery_created_at","e.organization_id","e.type","e.source","e.specversion","e.subject","e.time","e.datacontenttype","e.dataschema","e.data","e.cron","e.status as event_status","e.attempts as event_attempts","e.last_error as event_last_error","e.next_retry_at","e.created_at as event_created_at","e.updated_at as event_updated_at","s.connection_id","s.publisher","s.event_type","s.filter","s.enabled","s.created_at as subscription_created_at","s.updated_at as subscription_updated_at"]).where("d.id","in",X).where("d.status","=","processing").execute()).map((G)=>({delivery:{id:G.delivery_id,eventId:G.event_id,subscriptionId:G.subscription_id,status:G.delivery_status,attempts:G.delivery_attempts,lastError:G.delivery_last_error,deliveredAt:G.delivered_at,nextRetryAt:G.delivery_next_retry_at,createdAt:G.delivery_created_at},event:{id:G.event_id,organizationId:G.organization_id,type:G.type,source:G.source,specversion:G.specversion,subject:G.subject,time:G.time,datacontenttype:G.datacontenttype,dataschema:G.dataschema,data:G.data?JSON.parse(G.data):null,cron:G.cron,status:G.event_status,attempts:G.event_attempts,lastError:G.event_last_error,nextRetryAt:G.next_retry_at,createdAt:G.event_created_at,updatedAt:G.event_updated_at},subscription:{id:G.subscription_id,organizationId:G.organization_id,connectionId:G.connection_id,publisher:G.publisher,eventType:G.event_type,filter:G.filter,enabled:G.enabled===1,createdAt:G.subscription_created_at,updatedAt:G.subscription_updated_at}}))}async markDeliveriesDelivered(Y){if(Y.length===0)return;let Q=new Date().toISOString();await this.db.updateTable("event_deliveries").set({status:"delivered",delivered_at:Q}).where("id","in",Y).execute()}async markDeliveriesFailed(Y,Q,X=20,J=1000,G=3600000){if(Y.length===0)return;for(let K of Y){let W=await this.db.selectFrom("event_deliveries").select(["attempts"]).where("id","=",K).executeTakeFirst();if(!W)continue;let Z=W.attempts+1;if(Z>=X)await this.db.updateTable("event_deliveries").set({attempts:Z,last_error:Q,status:"failed",next_retry_at:null}).where("id","=",K).execute();else{let H=Math.min(J*Math.pow(2,Z-1),G),$=new Date(Date.now()+H).toISOString();await this.db.updateTable("event_deliveries").set({attempts:Z,last_error:Q,status:"pending",next_retry_at:$}).where("id","=",K).execute()}}}async updateEventStatus(Y){let Q=await this.db.selectFrom("event_deliveries").select(["status"]).where("event_id","=",Y).execute();if(Q.length===0)return;let X=Q.every((K)=>K.status==="delivered"),J=Q.some((K)=>K.status==="failed"),G=Q.some((K)=>K.status==="pending"||K.status==="processing");if(X)await this.db.updateTable("events").set({status:"delivered",updated_at:new Date().toISOString()}).where("id","=",Y).execute();else if(J&&!G)await this.db.updateTable("events").set({status:"failed",updated_at:new Date().toISOString()}).where("id","=",Y).execute()}async resetStuckDeliveries(){let Y=await this.db.updateTable("event_deliveries").set({status:"pending"}).where("status","=","processing").executeTakeFirst();return Number(Y.numUpdatedRows??0)}async getEvent(Y,Q){let X=await this.db.selectFrom("events").selectAll().where("id","=",Y).where("organization_id","=",Q).executeTakeFirst();if(!X)return null;return{id:X.id,organizationId:X.organization_id,type:X.type,source:X.source,specversion:X.specversion,subject:X.subject,time:X.time,datacontenttype:X.datacontenttype,dataschema:X.dataschema,data:X.data?JSON.parse(X.data):null,cron:X.cron,status:X.status,attempts:X.attempts,lastError:X.last_error,nextRetryAt:X.next_retry_at,createdAt:X.created_at,updatedAt:X.updated_at}}async findActiveCronEvent(Y,Q,X,J){let G=await this.db.selectFrom("events").selectAll().where("organization_id","=",Y).where("type","=",Q).where("source","=",X).where("cron","=",J).where("status","in",["pending","processing","delivered"]).orderBy("created_at","desc").executeTakeFirst();if(!G)return null;return{id:G.id,organizationId:G.organization_id,type:G.type,source:G.source,specversion:G.specversion,subject:G.subject,time:G.time,datacontenttype:G.datacontenttype,dataschema:G.dataschema,data:G.data?JSON.parse(G.data):null,cron:G.cron,status:G.status,attempts:G.attempts,lastError:G.last_error,nextRetryAt:G.next_retry_at,createdAt:G.created_at,updatedAt:G.updated_at}}async cancelEvent(Y,Q,X){let J=await this.db.updateTable("events").set({status:"failed",last_error:"Cancelled by publisher",updated_at:new Date().toISOString()}).where("id","=",Y).where("organization_id","=",Q).where("source","=",X).where("status","in",["pending","processing"]).executeTakeFirst();if((J.numUpdatedRows??0n)>0n)await this.db.updateTable("event_deliveries").set({status:"failed",last_error:"Event cancelled by publisher"}).where("event_id","=",Y).where("status","in",["pending","processing"]).execute();return{success:(J.numUpdatedRows??0n)>0n}}async scheduleRetryWithoutAttemptIncrement(Y,Q){if(Y.length===0)return;let X=new Date(Date.now()+Q).toISOString();await this.db.updateTable("event_deliveries").set({status:"pending",next_retry_at:X}).where("id","in",Y).execute()}async ackDelivery(Y,Q,X){if(!await this.db.selectFrom("events").select(["id"]).where("id","=",Y).where("organization_id","=",Q).executeTakeFirst())return{success:!1};let K=((await this.db.updateTable("event_deliveries").set({status:"delivered",delivered_at:new Date().toISOString()}).where("event_id","=",Y).where("status","in",["pending","processing"]).where((W)=>W.exists(W.selectFrom("event_subscriptions").select("id").whereRef("event_subscriptions.id","=","event_deliveries.subscription_id").where("event_subscriptions.connection_id","=",X).where("event_subscriptions.organization_id","=",Q))).executeTakeFirst()).numUpdatedRows??0n)>0n;if(K)await this.updateEventStatus(Y);return{success:K}}async syncSubscriptions(Y){let{organizationId:Q,connectionId:X,subscriptions:J}=Y,G=(w,E)=>{return`${w}::${E??""}`},K=await this.listSubscriptions(Q,X),W=new Map;for(let w of K)W.set(G(w.eventType,w.publisher),w);let Z=new Map;for(let w of J)Z.set(G(w.eventType,w.publisher),w);let H=new Date().toISOString(),$=[],F=[],V=[],B=0;for(let[w,E]of Z){let T=W.get(w);if(!T)$.push({id:crypto.randomUUID(),organization_id:Q,connection_id:X,event_type:E.eventType,publisher:E.publisher??null,filter:E.filter??null,enabled:1,created_at:H,updated_at:H});else{let C=T.filter??null,P=E.filter??null;if(C!==P)F.push({id:T.id,filter:P});else B++}}for(let[w,E]of W)if(!Z.has(w))V.push(E.id);if($.length>0)await this.db.insertInto("event_subscriptions").values($).execute();if(F.length>0)await Promise.all(F.map((w)=>this.db.updateTable("event_subscriptions").set({filter:w.filter,updated_at:H}).where("id","=",w.id).execute()));if(V.length>0)await this.db.deleteFrom("event_subscriptions").where("id","in",V).execute();let U=$.length,D=F.length,z=V.length,L=await this.listSubscriptions(Q,X);return{created:U,updated:D,deleted:z,unchanged:B,subscriptions:L}}}function Bi0(Y){return new qi0(Y)}function hJ(Y,Q,X,J,G,K,W,Z){return hJ.fromTZ(hJ.tp(Y,Q,X,J,G,K,W),Z)}hJ.fromTZISO=(Y,Q,X)=>hJ.fromTZ(Nu6(Y,Q),X);hJ.fromTZ=function(Y,Q){let X=new Date(Date.UTC(Y.y,Y.m-1,Y.d,Y.h,Y.i,Y.s)),J=qN1(Y.tz,X),G=new Date(X.getTime()-J),K=qN1(Y.tz,G);if(K-J===0)return G;{let W=new Date(X.getTime()-K),Z=qN1(Y.tz,W);if(Z-K===0)return W;if(!Q&&Z-K>0)return W;if(Q)throw Error("Invalid date passed to fromTZ()");return G}};hJ.toTZ=function(Y,Q){let X=Y.toLocaleString("en-US",{timeZone:Q}).replace(/[\u202f]/," "),J=new Date(X);return{y:J.getFullYear(),m:J.getMonth()+1,d:J.getDate(),h:J.getHours(),i:J.getMinutes(),s:J.getSeconds(),tz:Q}};hJ.tp=(Y,Q,X,J,G,K,W)=>({y:Y,m:Q,d:X,h:J,i:G,s:K,tz:W});function qN1(Y,Q=new Date){let X=Q.toLocaleString("en-US",{timeZone:Y,timeZoneName:"shortOffset"}).split(" ").slice(-1)[0],J=Q.toLocaleString("en-US").replace(/[\u202f]/," ");return Date.parse(`${J} GMT`)-Date.parse(`${J} ${X}`)}function Nu6(Y,Q){let X=new Date(Date.parse(Y));if(isNaN(X))throw Error("minitz: Invalid ISO8601 passed to parser.");let J=Y.substring(9);return Y.includes("Z")||J.includes("-")||J.includes("+")?hJ.tp(X.getUTCFullYear(),X.getUTCMonth()+1,X.getUTCDate(),X.getUTCHours(),X.getUTCMinutes(),X.getUTCSeconds(),"Etc/UTC"):hJ.tp(X.getFullYear(),X.getMonth()+1,X.getDate(),X.getHours(),X.getMinutes(),X.getSeconds(),Q)}hJ.minitz=hJ;var BN1=32,wv=31|BN1,Oi0=[1,2,4,8,16],Ui0=class{pattern;timezone;second;minute;hour;day;month;dayOfWeek;lastDayOfMonth;starDOM;starDOW;constructor(Y,Q){this.pattern=Y,this.timezone=Q,this.second=Array(60).fill(0),this.minute=Array(60).fill(0),this.hour=Array(24).fill(0),this.day=Array(31).fill(0),this.month=Array(12).fill(0),this.dayOfWeek=Array(7).fill(0),this.lastDayOfMonth=!1,this.starDOM=!1,this.starDOW=!1,this.parse()}parse(){if(!(typeof this.pattern=="string"||this.pattern instanceof String))throw TypeError("CronPattern: Pattern has to be of type string.");this.pattern.indexOf("@")>=0&&(this.pattern=this.handleNicknames(this.pattern).trim());let Y=this.pattern.replace(/\s+/g," ").split(" ");if(Y.length<5||Y.length>6)throw TypeError("CronPattern: invalid configuration format ('"+this.pattern+"'), exactly five or six space separated parts are required.");if(Y.length===5&&Y.unshift("0"),Y[3].indexOf("L")>=0&&(Y[3]=Y[3].replace("L",""),this.lastDayOfMonth=!0),Y[3]=="*"&&(this.starDOM=!0),Y[4].length>=3&&(Y[4]=this.replaceAlphaMonths(Y[4])),Y[5].length>=3&&(Y[5]=this.replaceAlphaDays(Y[5])),Y[5]=="*"&&(this.starDOW=!0),this.pattern.indexOf("?")>=0){let Q=new fW(new Date,this.timezone).getDate(!0);Y[0]=Y[0].replace("?",Q.getSeconds().toString()),Y[1]=Y[1].replace("?",Q.getMinutes().toString()),Y[2]=Y[2].replace("?",Q.getHours().toString()),this.starDOM||(Y[3]=Y[3].replace("?",Q.getDate().toString())),Y[4]=Y[4].replace("?",(Q.getMonth()+1).toString()),this.starDOW||(Y[5]=Y[5].replace("?",Q.getDay().toString()))}this.throwAtIllegalCharacters(Y),this.partToArray("second",Y[0],0,1),this.partToArray("minute",Y[1],0,1),this.partToArray("hour",Y[2],0,1),this.partToArray("day",Y[3],-1,1),this.partToArray("month",Y[4],-1,1),this.partToArray("dayOfWeek",Y[5],0,wv),this.dayOfWeek[7]&&(this.dayOfWeek[0]=this.dayOfWeek[7])}partToArray(Y,Q,X,J){let G=this[Y],K=Y==="day"&&this.lastDayOfMonth;if(Q===""&&!K)throw TypeError("CronPattern: configuration entry "+Y+" ("+Q+") is empty, check for trailing spaces.");if(Q==="*")return G.fill(J);let W=Q.split(",");if(W.length>1)for(let Z=0;Z<W.length;Z++)this.partToArray(Y,W[Z],X,J);else Q.indexOf("-")!==-1&&Q.indexOf("/")!==-1?this.handleRangeWithStepping(Q,Y,X,J):Q.indexOf("-")!==-1?this.handleRange(Q,Y,X,J):Q.indexOf("/")!==-1?this.handleStepping(Q,Y,X,J):Q!==""&&this.handleNumber(Q,Y,X,J)}throwAtIllegalCharacters(Y){for(let Q=0;Q<Y.length;Q++)if((Q===5?/[^/*0-9,\-#L]+/:/[^/*0-9,-]+/).test(Y[Q]))throw TypeError("CronPattern: configuration entry "+Q+" ("+Y[Q]+") contains illegal characters.")}handleNumber(Y,Q,X,J){let G=this.extractNth(Y,Q),K=parseInt(G[0],10)+X;if(isNaN(K))throw TypeError("CronPattern: "+Q+" is not a number: '"+Y+"'");this.setPart(Q,K,G[1]||J)}setPart(Y,Q,X){if(!Object.prototype.hasOwnProperty.call(this,Y))throw TypeError("CronPattern: Invalid part specified: "+Y);if(Y==="dayOfWeek"){if(Q===7&&(Q=0),Q<0||Q>6)throw RangeError("CronPattern: Invalid value for dayOfWeek: "+Q);this.setNthWeekdayOfMonth(Q,X);return}if(Y==="second"||Y==="minute"){if(Q<0||Q>=60)throw RangeError("CronPattern: Invalid value for "+Y+": "+Q)}else if(Y==="hour"){if(Q<0||Q>=24)throw RangeError("CronPattern: Invalid value for "+Y+": "+Q)}else if(Y==="day"){if(Q<0||Q>=31)throw RangeError("CronPattern: Invalid value for "+Y+": "+Q)}else if(Y==="month"&&(Q<0||Q>=12))throw RangeError("CronPattern: Invalid value for "+Y+": "+Q);this[Y][Q]=X}handleRangeWithStepping(Y,Q,X,J){let G=this.extractNth(Y,Q),K=G[0].match(/^(\d+)-(\d+)\/(\d+)$/);if(K===null)throw TypeError("CronPattern: Syntax error, illegal range with stepping: '"+Y+"'");let[,W,Z,H]=K,$=parseInt(W,10)+X,F=parseInt(Z,10)+X,V=parseInt(H,10);if(isNaN($))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(F))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(isNaN(V))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(V===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(V>this[Q].length)throw TypeError("CronPattern: Syntax error, steps cannot be greater than maximum value of part ("+this[Q].length+")");if($>F)throw TypeError("CronPattern: From value is larger than to value: '"+Y+"'");for(let B=$;B<=F;B+=V)this.setPart(Q,B,G[1]||J)}extractNth(Y,Q){let X=Y,J;if(X.includes("#")){if(Q!=="dayOfWeek")throw Error("CronPattern: nth (#) only allowed in day-of-week field");J=X.split("#")[1],X=X.split("#")[0]}return[X,J]}handleRange(Y,Q,X,J){let G=this.extractNth(Y,Q),K=G[0].split("-");if(K.length!==2)throw TypeError("CronPattern: Syntax error, illegal range: '"+Y+"'");let W=parseInt(K[0],10)+X,Z=parseInt(K[1],10)+X;if(isNaN(W))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(Z))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(W>Z)throw TypeError("CronPattern: From value is larger than to value: '"+Y+"'");for(let H=W;H<=Z;H++)this.setPart(Q,H,G[1]||J)}handleStepping(Y,Q,X,J){let G=this.extractNth(Y,Q),K=G[0].split("/");if(K.length!==2)throw TypeError("CronPattern: Syntax error, illegal stepping: '"+Y+"'");K[0]===""&&(K[0]="*");let W=0;K[0]!=="*"&&(W=parseInt(K[0],10)+X);let Z=parseInt(K[1],10);if(isNaN(Z))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(Z===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(Z>this[Q].length)throw TypeError("CronPattern: Syntax error, max steps for part is ("+this[Q].length+")");for(let H=W;H<this[Q].length;H+=Z)this.setPart(Q,H,G[1]||J)}replaceAlphaDays(Y){return Y.replace(/-sun/gi,"-7").replace(/sun/gi,"0").replace(/mon/gi,"1").replace(/tue/gi,"2").replace(/wed/gi,"3").replace(/thu/gi,"4").replace(/fri/gi,"5").replace(/sat/gi,"6")}replaceAlphaMonths(Y){return Y.replace(/jan/gi,"1").replace(/feb/gi,"2").replace(/mar/gi,"3").replace(/apr/gi,"4").replace(/may/gi,"5").replace(/jun/gi,"6").replace(/jul/gi,"7").replace(/aug/gi,"8").replace(/sep/gi,"9").replace(/oct/gi,"10").replace(/nov/gi,"11").replace(/dec/gi,"12")}handleNicknames(Y){let Q=Y.trim().toLowerCase();return Q==="@yearly"||Q==="@annually"?"0 0 1 1 *":Q==="@monthly"?"0 0 1 * *":Q==="@weekly"?"0 0 * * 0":Q==="@daily"?"0 0 * * *":Q==="@hourly"?"0 * * * *":Y}setNthWeekdayOfMonth(Y,Q){if(typeof Q!="number"&&Q==="L")this.dayOfWeek[Y]=this.dayOfWeek[Y]|BN1;else if(Q===wv)this.dayOfWeek[Y]=wv;else if(Q<6&&Q>0)this.dayOfWeek[Y]=this.dayOfWeek[Y]|Oi0[Q-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${Q}, Type: ${typeof Q}`)}},Di0=[31,28,31,30,31,30,31,31,30,31,30,31],DF=[["month","year",0],["day","month",-1],["hour","day",0],["minute","hour",0],["second","minute",0]],fW=class Y{tz;ms;second;minute;hour;day;month;year;constructor(Q,X){if(this.tz=X,Q&&Q instanceof Date)if(!isNaN(Q))this.fromDate(Q);else throw TypeError("CronDate: Invalid date passed to CronDate constructor");else if(Q===void 0)this.fromDate(new Date);else if(Q&&typeof Q=="string")this.fromString(Q);else if(Q instanceof Y)this.fromCronDate(Q);else throw TypeError("CronDate: Invalid type ("+typeof Q+") passed to CronDate constructor")}isNthWeekdayOfMonth(Q,X,J,G){let K=new Date(Date.UTC(Q,X,J)).getUTCDay(),W=0;for(let Z=1;Z<=J;Z++)new Date(Date.UTC(Q,X,Z)).getUTCDay()===K&&W++;if(G&wv&&Oi0[W-1]&G)return!0;if(G&BN1){let Z=new Date(Date.UTC(Q,X+1,0)).getUTCDate();for(let H=J+1;H<=Z;H++)if(new Date(Date.UTC(Q,X,H)).getUTCDay()===K)return!1;return!0}return!1}fromDate(Q){if(this.tz!==void 0)if(typeof this.tz=="number")this.ms=Q.getUTCMilliseconds(),this.second=Q.getUTCSeconds(),this.minute=Q.getUTCMinutes()+this.tz,this.hour=Q.getUTCHours(),this.day=Q.getUTCDate(),this.month=Q.getUTCMonth(),this.year=Q.getUTCFullYear(),this.apply();else{let X=hJ.toTZ(Q,this.tz);this.ms=Q.getMilliseconds(),this.second=X.s,this.minute=X.i,this.hour=X.h,this.day=X.d,this.month=X.m-1,this.year=X.y}else this.ms=Q.getMilliseconds(),this.second=Q.getSeconds(),this.minute=Q.getMinutes(),this.hour=Q.getHours(),this.day=Q.getDate(),this.month=Q.getMonth(),this.year=Q.getFullYear()}fromCronDate(Q){this.tz=Q.tz,this.year=Q.year,this.month=Q.month,this.day=Q.day,this.hour=Q.hour,this.minute=Q.minute,this.second=Q.second,this.ms=Q.ms}apply(){if(this.month>11||this.day>Di0[this.month]||this.hour>59||this.minute>59||this.second>59||this.hour<0||this.minute<0||this.second<0){let Q=new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms));return this.ms=Q.getUTCMilliseconds(),this.second=Q.getUTCSeconds(),this.minute=Q.getUTCMinutes(),this.hour=Q.getUTCHours(),this.day=Q.getUTCDate(),this.month=Q.getUTCMonth(),this.year=Q.getUTCFullYear(),!0}else return!1}fromString(Q){if(typeof this.tz=="number"){let X=hJ.fromTZISO(Q);this.ms=X.getUTCMilliseconds(),this.second=X.getUTCSeconds(),this.minute=X.getUTCMinutes(),this.hour=X.getUTCHours(),this.day=X.getUTCDate(),this.month=X.getUTCMonth(),this.year=X.getUTCFullYear(),this.apply()}else return this.fromDate(hJ.fromTZISO(Q,this.tz))}findNext(Q,X,J,G){let K=this[X],W;J.lastDayOfMonth&&(this.month!==1?W=Di0[this.month]:W=new Date(Date.UTC(this.year,this.month+1,0,0,0,0,0)).getUTCDate());let Z=!J.starDOW&&X=="day"?new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay():void 0;for(let H=this[X]+G;H<J[X].length;H++){let $=J[X][H];if(X==="day"&&J.lastDayOfMonth&&H-G==W&&($=1),X==="day"&&!J.starDOW){let F=J.dayOfWeek[(Z+(H-G-1))%7];if(F&&F&wv)F=this.isNthWeekdayOfMonth(this.year,this.month,H-G,F)?1:0;else if(F)throw Error(`CronDate: Invalid value for dayOfWeek encountered. ${F}`);Q.legacyMode&&!J.starDOM?$=$||F:$=$&&F}if($)return this[X]=H-G,K!==this[X]?2:1}return 3}recurse(Q,X,J){let G=this.findNext(X,DF[J][0],Q,DF[J][2]);if(G>1){let K=J+1;for(;K<DF.length;)this[DF[K][0]]=-DF[K][2],K++;if(G===3)return this[DF[J][1]]++,this[DF[J][0]]=-DF[J][2],this.apply(),this.recurse(Q,X,0);if(this.apply())return this.recurse(Q,X,J-1)}return J+=1,J>=DF.length?this:this.year>=3000?null:this.recurse(Q,X,J)}increment(Q,X,J){return this.second+=X.interval!==void 0&&X.interval>1&&J?X.interval:1,this.ms=0,this.apply(),this.recurse(Q,X,0)}getDate(Q){return Q||this.tz===void 0?new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms):typeof this.tz=="number"?new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute-this.tz,this.second,this.ms)):hJ.fromTZ(hJ.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}};function Lu6(Y){if(Y===void 0&&(Y={}),delete Y.name,Y.legacyMode=Y.legacyMode===void 0?!0:Y.legacyMode,Y.paused=Y.paused===void 0?!1:Y.paused,Y.maxRuns=Y.maxRuns===void 0?1/0:Y.maxRuns,Y.catch=Y.catch===void 0?!1:Y.catch,Y.interval=Y.interval===void 0?0:parseInt(Y.interval.toString(),10),Y.utcOffset=Y.utcOffset===void 0?void 0:parseInt(Y.utcOffset.toString(),10),Y.unref=Y.unref===void 0?!1:Y.unref,Y.startAt&&(Y.startAt=new fW(Y.startAt,Y.timezone)),Y.stopAt&&(Y.stopAt=new fW(Y.stopAt,Y.timezone)),Y.interval!==null){if(isNaN(Y.interval))throw Error("CronOptions: Supplied value for interval is not a number");if(Y.interval<0)throw Error("CronOptions: Supplied value for interval can not be negative")}if(Y.utcOffset!==void 0){if(isNaN(Y.utcOffset))throw Error("CronOptions: Invalid value passed for utcOffset, should be number representing minutes offset from UTC.");if(Y.utcOffset<-870||Y.utcOffset>870)throw Error("CronOptions: utcOffset out of bounds.");if(Y.utcOffset!==void 0&&Y.timezone)throw Error("CronOptions: Combining 'utcOffset' with 'timezone' is not allowed.")}if(Y.unref!==!0&&Y.unref!==!1)throw Error("CronOptions: Unref should be either true, false or undefined(false).");return Y}function Mv(Y){return Object.prototype.toString.call(Y)==="[object Function]"||typeof Y=="function"||Y instanceof Function}function Mu6(Y){return Mv(Y)}function wu6(Y){typeof Deno<"u"&&typeof Deno.unrefTimer<"u"?Deno.unrefTimer(Y):Y&&typeof Y.unref<"u"&&Y.unref()}var zi0=30000,Ir=[],jr=class{name;options;_states;fn;constructor(Y,Q,X){let J,G;if(Mv(Q))G=Q;else if(typeof Q=="object")J=Q;else if(Q!==void 0)throw Error("Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).");if(Mv(X))G=X;else if(typeof X=="object")J=X;else if(X!==void 0)throw Error("Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).");if(this.name=J?.name,this.options=Lu6(J),this._states={kill:!1,blocking:!1,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:J?J.maxRuns:void 0,paused:J?J.paused:!1,pattern:new Ui0("* * * * *")},Y&&(Y instanceof Date||typeof Y=="string"&&Y.indexOf(":")>0)?this._states.once=new fW(Y,this.options.timezone||this.options.utcOffset):this._states.pattern=new Ui0(Y,this.options.timezone),this.name){if(Ir.find((K)=>K.name===this.name))throw Error("Cron: Tried to initialize new named job '"+this.name+"', but name already taken.");Ir.push(this)}return G!==void 0&&Mu6(G)&&(this.fn=G,this.schedule()),this}nextRun(Y){let Q=this._next(Y);return Q?Q.getDate(!1):null}nextRuns(Y,Q){this._states.maxRuns!==void 0&&Y>this._states.maxRuns&&(Y=this._states.maxRuns);let X=[],J=Q||this._states.currentRun||void 0;for(;Y--&&(J=this.nextRun(J));)X.push(J);return X}getPattern(){return this._states.pattern?this._states.pattern.pattern:void 0}isRunning(){let Y=this.nextRun(this._states.currentRun),Q=!this._states.paused,X=this.fn!==void 0,J=!this._states.kill;return Q&&X&&J&&Y!==null}isStopped(){return this._states.kill}isBusy(){return this._states.blocking}currentRun(){return this._states.currentRun?this._states.currentRun.getDate():null}previousRun(){return this._states.previousRun?this._states.previousRun.getDate():null}msToNext(Y){let Q=this._next(Y);return Q?Y instanceof fW||Y instanceof Date?Q.getTime()-Y.getTime():Q.getTime()-new fW(Y).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let Y=Ir.indexOf(this);Y>=0&&Ir.splice(Y,1)}pause(){return this._states.paused=!0,!this._states.kill}resume(){return this._states.paused=!1,!this._states.kill}schedule(Y){if(Y&&this.fn)throw Error("Cron: It is not allowed to schedule two functions using the same Croner instance.");Y&&(this.fn=Y);let Q=this.msToNext(),X=this.nextRun(this._states.currentRun);return Q==null||isNaN(Q)||X===null?this:(Q>zi0&&(Q=zi0),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(X),Q),this._states.currentTimeout&&this.options.unref&&wu6(this._states.currentTimeout),this)}async _trigger(Y){if(this._states.blocking=!0,this._states.currentRun=new fW(void 0,this.options.timezone||this.options.utcOffset),this.options.catch)try{this.fn!==void 0&&await this.fn(this,this.options.context)}catch(Q){Mv(this.options.catch)&&this.options.catch(Q,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new fW(Y,this.options.timezone||this.options.utcOffset),this._states.blocking=!1}async trigger(){await this._trigger()}runsLeft(){return this._states.maxRuns}_checkTrigger(Y){let Q=new Date,X=!this._states.paused&&Q.getTime()>=Y.getTime(),J=this._states.blocking&&this.options.protect;X&&!J?(this._states.maxRuns!==void 0&&this._states.maxRuns--,this._trigger()):X&&J&&Mv(this.options.protect)&&setTimeout(()=>this.options.protect(this),0),this.schedule()}_next(Y){let Q=!!(Y||this._states.currentRun),X=!1;!Y&&this.options.startAt&&this.options.interval&&([Y,Q]=this._calculatePreviousRun(Y,Q),X=!Y),Y=new fW(Y,this.options.timezone||this.options.utcOffset),this.options.startAt&&Y&&Y.getTime()<this.options.startAt.getTime()&&(Y=this.options.startAt);let J=this._states.once||new fW(Y,this.options.timezone||this.options.utcOffset);return!X&&J!==this._states.once&&(J=J.increment(this._states.pattern,this.options,Q)),this._states.once&&this._states.once.getTime()<=Y.getTime()||J===null||this._states.maxRuns!==void 0&&this._states.maxRuns<=0||this._states.kill||this.options.stopAt&&J.getTime()>=this.options.stopAt.getTime()?null:J}_calculatePreviousRun(Y,Q){let X=new fW(void 0,this.options.timezone||this.options.utcOffset),J=Y;if(this.options.startAt.getTime()<=X.getTime()){J=this.options.startAt;let G=J.getTime()+this.options.interval*1000;for(;G<=X.getTime();)J=new fW(J,this.options.timezone||this.options.utcOffset).increment(this._states.pattern,this.options,!0),G=J.getTime()+this.options.interval*1000;Q=!0}return J===null&&(J=void 0),[J,Q]}};class Av{localEmit=null;async start(Y){this.localEmit=Y}broadcast(Y,Q){this.localEmit?.(Y,Q)}async stop(){this.localEmit=null}}var Ni0=50,Li0=500;class Mi0{listeners=new Map;totalCount=0;strategy=new Av;started=!1;async start(Y){if(this.started){if(!Y)return;await this.stop()}if(Y)this.strategy=Y;await this.strategy.start((Q,X)=>this.localEmit(Q,X)),this.started=!0}async stop(){if(!this.started)return;await this.strategy.stop(),this.started=!1}add(Y){if(this.totalCount>=Li0)return console.warn(`[SSEHub] Total connection limit reached (${Li0})`),null;let Q=this.listeners.get(Y.organizationId);if(!Q)Q=new Map,this.listeners.set(Y.organizationId,Q);if(Q.size>=Ni0)return console.warn(`[SSEHub] Per-org connection limit reached for ${Y.organizationId} (${Ni0})`),null;return Q.set(Y.id,Y),this.totalCount++,Y.id}remove(Y,Q){let X=this.listeners.get(Y);if(!X)return;if(X.delete(Q)){if(this.totalCount--,X.size===0)this.listeners.delete(Y)}}emit(Y,Q){this.strategy.broadcast(Y,Q)}countForOrg(Y){return this.listeners.get(Y)?.size??0}get count(){return this.totalCount}localEmit(Y,Q){let X=this.listeners.get(Y);if(!X||X.size===0)return;for(let J of X.values()){if(J.typePatterns&&!Au6(Q.type,J.typePatterns))continue;try{J.push(Q)}catch{this.remove(Y,J.id)}}}}function Au6(Y,Q){for(let X of Q){if(X===Y)return!0;if(X.endsWith(".*")){let J=X.slice(0,-1);if(Y.startsWith(J))return!0}}return!1}var xJ=new Mi0;function wi0(Y){return{id:Y.id,type:Y.type,source:Y.source,subject:Y.subject,data:Y.data?Pu6(Y.data):void 0,time:Y.time}}function Pu6(Y){if(typeof Y==="string")try{return JSON.parse(Y)}catch{return Y}return Y}var Sr={pollIntervalMs:5000,batchSize:100,maxAttempts:20,retryDelayMs:1000,maxDelayMs:3600000};Yr();lS();function Eu6(Y){return Y.endsWith("_self")}function Tu6(Y){return Y.slice(0,-5)}function Ai0(){return async(Y,Q)=>{try{if(Eu6(Y)&&Xz1()){let W=Tu6(Y),Z=await UF.create();if(await xd0(Q,{organizationId:W,connectionId:Y,publish:async(F,V,B,U)=>{await Z.eventBus.publish(W,Y,{type:F,subject:V,data:B,deliverAt:U?.deliverAt})},createMCPProxy:async(F)=>{let V=await FN1(F,Z);return{callTool:async(B,U,D)=>{let z=await V.callTool(B,U,D);return{content:z.content,structuredContent:z.structuredContent,isError:z.isError}},close:()=>V.close()}}}))return{success:!0}}let X=await UF.create(),J=await FN1(Y,X),K=await dV1.forClient(DO(J)).ON_EVENTS({events:Q});return{success:K.success,error:K.error,retryAfter:K.retryAfter,results:K.results}}catch(X){let J=X instanceof Error?X.message:String(X);return console.error(`[EventBus] Failed to notify connection ${Y}:`,J),{success:!1,error:J}}}}function Pi0(Y){return{specversion:"1.0",id:Y.id,source:Y.source,type:Y.type,time:Y.time,subject:Y.subject??void 0,datacontenttype:Y.datacontenttype,dataschema:Y.dataschema??void 0,data:Y.data??void 0}}function Cu6(Y){let Q=new Map;for(let J of Y){let G=J.subscription.connectionId,K=Q.get(G);if(K){if(K.deliveryIds.push(J.delivery.id),!K.seenEventIds.has(J.event.id))K.seenEventIds.add(J.event.id),K.events.push(Pi0(J.event))}else Q.set(G,{connectionId:J.subscription.connectionId,deliveryIds:[J.delivery.id],events:[Pi0(J.event)],seenEventIds:new Set([J.event.id])})}let X=new Map;for(let[J,G]of Q)X.set(J,{connectionId:G.connectionId,deliveryIds:G.deliveryIds,events:G.events});return X}class UN1{storage;notifySubscriber;running=!1;processing=!1;pendingNotify=!1;config;constructor(Y,Q){this.storage=Y;this.notifySubscriber=Ai0(),this.config={...Sr,...Q}}async start(){if(this.running)return;let Y=await this.storage.resetStuckDeliveries();if(Y>0)console.log(`[EventBus] Reset ${Y} stuck deliveries from previous shutdown`);this.running=!0}stop(){this.running=!1,console.log("[EventBus] Worker stopped")}isRunning(){return this.running}async processNow(){if(!this.running)return;if(this.processing){this.pendingNotify=!0;return}this.processing=!0;try{do this.pendingNotify=!1,await this.processEvents();while(this.pendingNotify)}catch(Y){console.error("[EventBus] Error processing events:",Y)}finally{this.processing=!1}}async processEvents(){let Y=await this.storage.claimPendingDeliveries(this.config.batchSize);if(Y.length===0)return;let Q=Cu6(Y),X=new Set;await Promise.allSettled(Array.from(Q.entries()).map(async([J,G])=>{try{let K=await this.notifySubscriber(G.connectionId,G.events);if(K.results&&Object.keys(K.results).length>0)await this.processPerEventResults(G,K);else if(K.success)await this.storage.markDeliveriesDelivered(G.deliveryIds);else if(K.retryAfter&&K.retryAfter>0)await this.storage.scheduleRetryWithoutAttemptIncrement(G.deliveryIds,K.retryAfter);else await this.storage.markDeliveriesFailed(G.deliveryIds,K.error||"Subscriber returned success=false",this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}catch(K){let W=K instanceof Error?K.message:String(K);console.error(`[EventBus] Failed to notify subscription ${J}:`,W),await this.storage.markDeliveriesFailed(G.deliveryIds,W,this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}for(let K of Y)if(G.deliveryIds.includes(K.delivery.id))X.add(K.event.id)}));for(let J of X)try{await this.storage.updateEventStatus(J);let G=Y.find((K)=>K.event.id===J)?.event;if(G?.cron)await this.scheduleNextCronDelivery(G)}catch(G){console.error(`[EventBus] Failed to update event status ${J}:`,G)}}async processPerEventResults(Y,Q){let X=[],J=new Map,G=[],K=new Map;for(let W=0;W<Y.events.length;W++){let Z=Y.events?.[W];if(!Z)continue;let H=Y.deliveryIds?.[W];if(!H)continue;K.set(Z.id,H)}for(let W of Y.events){let Z=K.get(W.id);if(!Z)continue;let H=Q.results?.[W.id];if(H)if(H.success)X.push(Z);else if(H.retryAfter&&H.retryAfter>0){let $=J.get(H.retryAfter)||[];$.push(Z),J.set(H.retryAfter,$)}else G.push({deliveryId:Z,error:H.error||"Event processing failed"});else if(Q.success)X.push(Z);else if(Q.retryAfter&&Q.retryAfter>0){let $=J.get(Q.retryAfter)||[];$.push(Z),J.set(Q.retryAfter,$)}else G.push({deliveryId:Z,error:Q.error||"Batch processing failed"})}if(X.length>0)await this.storage.markDeliveriesDelivered(X);for(let[W,Z]of J)await this.storage.scheduleRetryWithoutAttemptIncrement(Z,W);if(G.length>0){let W=new Map;for(let{deliveryId:Z,error:H}of G){let $=W.get(H)||[];$.push(Z),W.set(H,$)}for(let[Z,H]of W)await this.storage.markDeliveriesFailed(H,Z,this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}}async scheduleNextCronDelivery(Y){if(!Y.cron)return;try{let X=new jr(Y.cron).nextRun();if(!X){console.log(`[EventBus] Cron expression for event ${Y.id} has no more runs`);return}let J=X.toISOString(),G=await this.storage.getMatchingSubscriptions(Y);if(G.length===0){console.log(`[EventBus] No subscriptions for cron event ${Y.id}, skipping next delivery`);return}await this.storage.createDeliveries(Y.id,G.map((K)=>K.id),J),console.log(`[EventBus] Scheduled next cron delivery for event ${Y.id} at ${J}`)}catch(Q){console.error(`[EventBus] Failed to schedule next cron delivery for event ${Y.id}:`,Q)}}}class DN1{storage;worker;notifyStrategy;running=!1;constructor(Y){this.storage=Y.storage,this.notifyStrategy=Y.notifyStrategy,this.worker=new UN1(this.storage,Y.config)}async publish(Y,Q,X){if(X.deliverAt&&X.cron)throw Error("Cannot set both deliverAt and cron. Use one or the other.");let J;if(X.cron){try{let F=new jr(X.cron).nextRun();if(!F)throw Error("Cron expression does not produce a next run time");J=F.toISOString()}catch($){throw Error(`Invalid cron expression: ${$ instanceof Error?$.message:String($)}`)}let H=await this.storage.findActiveCronEvent(Y,X.type,Q,X.cron);if(H)return H}let G=crypto.randomUUID(),K=new Date().toISOString(),W=await this.storage.publishEvent({id:G,organizationId:Y,type:X.type,source:Q,subject:X.subject,time:K,data:X.data,cron:X.cron});xJ.emit(Y,wi0(W));let Z=await this.storage.getMatchingSubscriptions(W);if(Z.length>0){let H=X.deliverAt??J;if(await this.storage.createDeliveries(G,Z.map(($)=>$.id),H),this.notifyStrategy&&!H)await this.notifyStrategy.notify(G).catch(($)=>{console.warn("[EventBus] Notify failed (non-critical):",$)})}return W}async subscribe(Y,Q){return this.storage.subscribe({id:crypto.randomUUID(),organizationId:Y,connectionId:Q.connectionId,publisher:Q.publisher,eventType:Q.eventType,filter:Q.filter})}async unsubscribe(Y,Q){return this.storage.unsubscribe(Q,Y)}async listSubscriptions(Y,Q){return this.storage.listSubscriptions(Y,Q)}async getSubscription(Y,Q){return this.storage.getSubscription(Q,Y)}async getEvent(Y,Q){return this.storage.getEvent(Q,Y)}async cancelEvent(Y,Q,X){return this.storage.cancelEvent(Q,Y,X)}async ackEvent(Y,Q,X){return this.storage.ackDelivery(Q,Y,X)}async syncSubscriptions(Y,Q){return this.storage.syncSubscriptions({organizationId:Y,...Q})}async start(){if(this.running)return;if(this.running=!0,await this.worker.start(),this.notifyStrategy)await this.notifyStrategy.start(()=>{this.worker.processNow().catch((Y)=>{console.error("[EventBus] Error processing after notify:",Y)})});await this.worker.processNow().catch((Y)=>{console.error("[EventBus] Error processing pending events on startup:",Y)})}async stop(){if(!this.running)return;if(this.running=!1,this.worker.stop(),this.notifyStrategy)try{await this.notifyStrategy.stop()}catch(Y){console.error("[EventBus] Error stopping notify strategy:",Y)}console.log("[EventBus] Stopped")}isRunning(){return this.running}}class zN1{options;sub=null;onNotify=null;encoder=new TextEncoder;constructor(Y){this.options=Y}async start(Y){let Q=this.options.getConnection();if(!Q||this.sub)return;this.onNotify=Y,this.sub=Q.subscribe("mesh.events.notify"),(async()=>{for await(let X of this.sub)this.onNotify?.()})().catch((X)=>{console.error("[NatsNotify] Subscription error:",X)}),console.log("[NatsNotify] Started, subscribed to","mesh.events.notify")}async stop(){this.sub?.unsubscribe(),this.sub=null,this.onNotify=null,console.log("[NatsNotify] Stopped")}async notify(Y){let Q=this.options.getConnection();if(!Q)return;try{Q.publish("mesh.events.notify",this.encoder.encode(Y))}catch(X){console.warn("[NatsNotify] Publish failed (non-critical):",X)}}}class ON1{options;sub=null;localEmit=null;originId=crypto.randomUUID();encoder=new TextEncoder;constructor(Y){this.options=Y}async start(Y){this.localEmit=Y;let Q=this.options.getConnection();if(!Q||this.sub)return;this.sub=Q.subscribe("mesh.sse.broadcast");let X=new TextDecoder;(async()=>{for await(let J of this.sub)try{let G=JSON.parse(X.decode(J.data));if(typeof G?.originId!=="string"||typeof G?.organizationId!=="string"||typeof G?.event?.id!=="string"||typeof G?.event?.type!=="string")continue;if(G.originId===this.originId)continue;this.localEmit?.(G.organizationId,G.event)}catch{}})().catch((J)=>{console.error("[NatsSSEBroadcast] Subscription error:",J)}),console.log("[NatsSSEBroadcast] Started, subscribed to","mesh.sse.broadcast")}broadcast(Y,Q){this.localEmit?.(Y,Q);let X=this.options.getConnection();if(!X)return;let J={originId:this.originId,organizationId:Y,event:Q};try{X.publish("mesh.sse.broadcast",this.encoder.encode(JSON.stringify(J)))}catch(G){console.warn("[NatsSSEBroadcast] Publish failed (non-critical):",G)}}async stop(){this.sub?.unsubscribe(),this.sub=null,this.localEmit=null,console.log("[NatsSSEBroadcast] Stopped")}}function NN1(...Y){return{async start(Q){await Promise.all(Y.map((X)=>X.start(Q)))},async stop(){await Promise.all(Y.map((Q)=>Q.stop().catch((X)=>{console.error("[NotifyStrategy] Error stopping strategy:",X)})))},async notify(Q){await Promise.all(Y.map((X)=>X.notify(Q).catch((J)=>{console.warn("[NotifyStrategy] Notify failed (non-critical):",J)})))}}}class LN1{intervalMs;timer=null;onNotify=null;constructor(Y){this.intervalMs=Y}async start(Y){if(this.timer)return;this.onNotify=Y,this.scheduleNext(),console.log(`[Polling] Started polling every ${this.intervalMs}ms`)}async stop(){if(this.timer)clearTimeout(this.timer),this.timer=null,console.log("[Polling] Stopped polling");this.onNotify=null}async notify(Y){if(this.onNotify)this.onNotify()}scheduleNext(){this.timer=setTimeout(()=>{if(this.onNotify)this.onNotify();if(this.timer)this.scheduleNext()},this.intervalMs)}}import{sql as Ru6}from"kysely";var LP="mesh_events";class MN1{db;pool;listenClient=null;onNotify=null;constructor(Y,Q){this.db=Y;this.pool=Q}async start(Y){if(this.listenClient)return;this.onNotify=Y;try{this.listenClient=await this.pool.connect(),this.listenClient.on("notification",(Q)=>{if(Q.channel===LP&&this.onNotify)this.onNotify()}),this.listenClient.on("error",(Q)=>{console.error("[PostgresNotify] Connection error:",Q),this.cleanup()}),await this.listenClient.query(`LISTEN ${LP}`),console.log("[PostgresNotify] Started LISTEN on",LP)}catch(Q){console.error("[PostgresNotify] Failed to start LISTEN:",Q),this.cleanup()}}async stop(){if(this.listenClient){try{await this.listenClient.query(`UNLISTEN ${LP}`),console.log("[PostgresNotify] Stopped LISTEN on",LP)}catch{}this.cleanup()}}async notify(Y){try{await Ru6`SELECT pg_notify(${LP}, ${Y})`.execute(this.db)}catch(Q){console.warn("[PostgresNotify] Failed to send NOTIFY:",Q)}}cleanup(){if(this.listenClient)this.listenClient.release(),this.listenClient=null;this.onNotify=null}}function Iu6(Y){let Q=process.env.NOTIFY_STRATEGY;if(Q==="nats"||Q==="postgres"||Q==="polling")return Q;if(process.env.NATS_URL)return"nats";if(Y.type==="postgres")return"postgres";return"polling"}function Ei0(Y,Q,X){let J=Bi0(Y.db),G=Q?.pollIntervalMs??Sr.pollIntervalMs,K=Iu6(Y),W=new LN1(G),Z=process.env.NATS_URL,H;switch(K){case"nats":{if(!Z)throw Error("[EventBus] NOTIFY_STRATEGY=nats requires NATS_URL to be set");let F=(()=>{try{return new URL(Z).host}catch{return"unknown"}})();if(!X){console.warn(`[EventBus] NATS unavailable (${F}), falling back to polling`),H=W;break}console.log(`[EventBus] Using NATS notify strategy (${F})`),H=NN1(W,new zN1({getConnection:()=>X.getConnection()}));break}case"postgres":{if(Y.type!=="postgres"){console.warn("[EventBus] NOTIFY_STRATEGY=postgres requires a PostgreSQL database, falling back to polling"),H=W;break}console.log("[EventBus] Using PostgreSQL LISTEN/NOTIFY strategy"),H=NN1(W,new MN1(Y.db,Y.pool));break}case"polling":default:console.log("[EventBus] Using polling notify strategy"),H=W}let $=Z&&X?new ON1({getConnection:()=>X.getConnection()}):new Av;if(xJ.start($).catch((F)=>{console.error("[SSEHub] Failed to start broadcast strategy:",F)}),Z&&X)console.log("[SSEHub] Using NATS SSE broadcast (cross-pod)");else console.log("[SSEHub] Using local SSE broadcast (single-pod)");return new DN1({storage:J,config:Q,notifyStrategy:H})}FN();Kv();var Ti0={google:{name:"Google",icon:"https://assets.decocache.com/webdraw/eb7480aa-a68b-4ce4-98ff-36aa121762a7/google.svg"},github:{name:"GitHub",icon:"https://assets.decocache.com/webdraw/5f999dcb-c8a6-4572-948c-9996ef1d502f/github.svg"},microsoft:{name:"Microsoft",icon:"https://assets.decocache.com/mcp/aa6f6e1a-6526-4bca-99cc-82e2ec38b0e4/microsoft.png"}};var Ci0=new JQ;Ci0.get("/config",async(Y)=>{try{let Q=Object.keys(p9.socialProviders??{}),X=Q.length>0,J=Q.map((W)=>({name:W,icon:Ti0[W].icon})),G=process.env.UNSAFE_ALLOW_STDIO_TRANSPORT==="true",K={emailAndPassword:{enabled:p9.emailAndPassword?.enabled??!1},magicLink:{enabled:p9.magicLinkConfig?.enabled??!1},resetPassword:{enabled:tO1},socialProviders:{enabled:X,providers:J},sso:p9.ssoConfig?{enabled:!0,providerId:p9.ssoConfig.providerId}:{enabled:!1},stdioEnabled:G};return Y.json({success:!0,config:K})}catch(Q){let X=Q instanceof Error?Q.message:"Failed to load auth config";return Y.json({success:!1,error:X},500)}});var Ri0=Ci0;zP();Uv();KY();rZ();vQ();rZ();rZ();c1();Jr();function Ii0(Y){let{toolOutputMap:Q}=Y;return _J({description:"The input is a string. Dont make assumptions about its format; prefer using regexes and string manipulation to extract the desired information. You may call this tool multiple times to extract the desired information.",inputExamples:[{input:{tool_call_id:"tool_call_id_1",code:"export default (input) => { return input.match(/[a-z]/g); }"}},{input:{tool_call_id:"tool_call_id_2",code:"export default (input) => { return input.split(' ').map(word => word.length); }"}}],inputSchema:m8(q.object({tool_call_id:q.string(),code:q.string().min(1).describe("JavaScript code to transform the tool output. The code must be an ES module: `export default (input) => { ... }`")})),execute:async({tool_call_id:X,code:J})=>{if(!Q.has(X))throw Error(`Tool output not found for tool call id: ${X}`);let G=Q.get(X),K=await Vz1({input:G,code:J,timeoutMs:5000}),W=wN1({return:K.returnValue});if(W>4000)throw Error(`Tool call ${X} output is too long to display (${W} tokens), reduce or truncate the output`);return{result:K.returnValue,error:K.error,consoleLogs:K.consoleLogs}}})}var ju6=4,Su6=/[\u3000-\u303f\u3040-\u309f\u30a0-\u30ff\u4e00-\u9fff\u3400-\u4dbf\uf900-\ufaff]/g;function ku6(Y){if(!Y)return 0;let Q=Y.match(Su6)?.length??0,X=Y.length-Q;return Math.ceil(X/ju6)+Math.ceil(Q*1.5)}function wN1(Y){let Q=typeof Y==="string"?Y:JSON.stringify(Y);return ku6(Q)}function kr(Y,Q){if(Y==="yolo")return!1;if(Y==="none")return!0;return Q!==!0}function vr(Y){let Q=Y.get("meshContext").organization;if(!Q)throw Error("Organization context is required");if((Q.slug??Q.id)!==Y.req.param("org"))throw Error("Organization mismatch");return Q}async function Pv(Y,Q,X,J="none",G){let K=!G?.disableOutputTruncation,Z=(await Y.listTools()).tools.map((H)=>{let{name:$,title:F,description:V,inputSchema:B,annotations:U,_meta:D}=H;return[$,_J({title:F??$,description:V,inputSchema:IW(B),outputSchema:void 0,needsApproval:kr(J,U?.readOnlyHint),execute:async(z,L)=>{let w=performance.now();try{return await Y.callTool({name:H.name,arguments:z},dK,{signal:L.abortSignal,timeout:en0})}finally{if(X){let E=performance.now()-w;X.write({type:"data-tool-metadata",id:L.toolCallId,data:{_meta:D,annotations:U,latencyMs:E}})}}},toModelOutput:async({output:z,toolCallId:L})=>{if(K){let E=wN1(z.structuredContent??z.content);if(E>4000)return Q.set(L,JSON.stringify(z.structuredContent??z.content)),{type:"text",value:`Tool call ${L} output is too long to display (${E} tokens), use the read_tool_output tool`}}if(z.isError)return{type:"error-text",value:z.content.map((T)=>T.type==="text"?T.text:null).filter(Boolean).join(`
|
|
1391
|
+
`)||"Unknown error"};if("structuredContent"in z)return{type:"json",value:z.structuredContent};return{type:"text",value:z.content.map((E)=>{if(E.type==="text")return E.text;return JSON.stringify(E)}).join(`
|
|
1392
1392
|
`)}}})]});return Object.fromEntries(Z)}async function AN1(Y){let Q=Y.get("meshContext"),X=Q.auth?.user?.id;if(!X)throw new TX(401,{message:"Unauthorized"});let J=vr(Y),G=Y.req.param("threadId");if(/[.*>\s]/.test(G))throw new TX(400,{message:"Invalid thread ID"});let K=await Q.storage.threads.get(G);if(!K||K.organization_id!==J.id)throw new TX(404,{message:"Thread not found"});if(K.created_by!==X)throw new TX(403,{message:"Not authorized"});return{ctx:Q,organization:J,thread:K,threadId:G,userId:X}}rZ();c1();var vu6=q.object({search_term:q.string().optional().describe("Optional search term to filter agents by name, title, or description. Leave empty to return all available agents.")}),_u6=q.object({agents:q.array(q.object({agent_id:q.string().describe("Unique identifier for the agent"),name:q.string().describe("Human-readable agent name"),purpose:q.string().nullable().describe("What the agent is designed to do"),capabilities:q.array(q.string()).describe("List of capabilities the agent has")}))}),yu6="Search for agents configured in the organization. Returns agent metadata including purpose and capabilities. Use this to discover specialized agents before delegating work with subtask_run.",fu6={readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1};function ji0(Y,Q,X){let{organization:J,needsApproval:G}=Q;return _J({description:yu6,inputSchema:m8(vu6),outputSchema:m8(_u6),needsApproval:G,execute:async({search_term:K},W)=>{let Z=performance.now();try{let $=(await X.storage.virtualMcps.list(J.id)).filter((V)=>V.status==="active");if(K&&K.trim().length>0){let V=K.toLowerCase();$=$.filter((B)=>{let U=B.title.toLowerCase().includes(V),D=B.description?.toLowerCase().includes(V)??!1;return U||D})}return{agents:$.map((V)=>({agent_id:V.id,name:V.title,purpose:V.description,capabilities:[]}))}}finally{let H=performance.now()-Z;Y.write({type:"data-tool-metadata",id:W.toolCallId,data:{annotations:fu6,latencyMs:H}})}}})}Uv();KY();rZ();c1();var bu6=q.object({prompt:q.string().min(1).max(50000).describe("The task to delegate to the subagent. Be specific and self-contained \u2014 "+"the subagent has no access to the parent conversation history."),agent_id:q.string().min(1).max(128).describe("The ID of the agent (Virtual MCP) to delegate to. This agent must exist and be active in the current organization.")}),hu6=`Delegate a self-contained task to another agent. The subagent runs independently with its own tools and returns results when complete. Use this when a task is better handled by a specialized agent, or to parallelize work across agents.
|
|
1393
1393
|
|
|
1394
1394
|
`+"IMPORTANT: Every subtask call starts FRESH \u2014 no conversation history, no prior runs. Even if you call it multiple times, each run is isolated. Always include full context in the prompt; never use continuation phrases like 'continue' or 'as before'.",xu6={readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0};function gu6(Y){let Q=`You are a focused subtask agent delegated a specific task by a parent agent.
|
|
@@ -1419,7 +1419,7 @@ ${Y}`;return Q}function Si0(Y,Q,X){let{modelProvider:J,organization:G,models:K,n
|
|
|
1419
1419
|
${W}`)}return{stream:au6(K),response:{headers:Object.fromEntries(K.headers?.entries()??[])}}}}}}};async function di0(Y,Q){let X=Wv.forClient(DO(Y)),J=Ev(X);return{thinkingModel:J.languageModel(Q.thinking.id),codingModel:Q.coding?J.languageModel(Q.coding.id):void 0,fastModel:Q.fast?J.languageModel(Q.fast.id):void 0,connectionId:Q.connectionId}}c1();var ou6=q.looseObject({id:q.string().optional(),role:q.enum(["user","assistant","system"]),parts:q.array(q.record(q.string(),q.unknown())),metadata:q.unknown().optional()}),su6=q.object({windowSize:q.number().default(Tr),thread_id:q.string()}),tu6=q.enum(["openai","anthropic","google","xai","deepseek","openrouter","openai-compatible"]).optional().nullable(),EN1=q.object({id:q.string(),capabilities:q.object({vision:q.boolean().optional(),text:q.boolean().optional(),tools:q.boolean().optional()}).optional(),provider:tu6,limits:q.object({contextWindow:q.number().optional(),maxOutputTokens:q.number().optional()}).optional()}),eu6=q.object({connectionId:q.string(),thinking:EN1.describe("Backbone model for the agentic loop"),coding:EN1.optional().describe("Good coding model"),fast:EN1.optional().describe("Cheap model for simple tasks")}).loose(),pi0=q.object({messages:q.array(ou6).min(1).refine((Y)=>Y.filter((Q)=>Q.role!=="system").length===1,{message:"Expected exactly one non-system message"}),memory:su6.optional(),models:eu6,agent:q.object({id:q.string(),mode:q.enum(["passthrough","smart_tool_selection","code_execution"])}).loose(),stream:q.boolean().optional(),temperature:q.number().default(0.5),thread_id:q.string().optional(),toolApprovalLevel:q.enum(["none","readonly","yolo"]).default("none")});function ci0(Y,Q=[]){if(Y==="stop")return"completed";if(Y==="tool-calls"){let X=Q.some((G)=>G.type==="tool-user_ask"&&G.state==="input-available"),J=Q.some((G)=>G.state==="approval-requested");return X||J?"requires_action":"completed"}return"failed"}rZ();var Ym6=2500;async function ni0(Y){let{abortSignal:Q,model:X,userMessage:J}=Y,G=new AbortController,K=()=>G.abort();Q.addEventListener("abort",K,{once:!0});let W=setTimeout(()=>{G.abort()},Ym6);try{let H=(await mA({model:X,system:Hi0,messages:[{role:"user",content:J}],maxOutputTokens:60,temperature:0.2,abortSignal:G.signal})).text.trim();return(H.split(`
|
|
1420
1420
|
`)[0]??H).replace(/^["']|["']$/g,"").replace(/^(Title:|title:)\s*/i,"").replace(/[.!?]$/,"").slice(0,60).trim()}catch(Z){let H=Z;if(H.name==="AbortError")console.warn("[decopilot:title] Title generation aborted (timeout or parent abort)");else console.error("[decopilot:title] \u274C Failed to generate title:",H.message);return null}finally{clearTimeout(W),Q.removeEventListener("abort",K)}}async function Qm6(Y){let Q=vr(Y),X=await Y.req.json(),J=pi0.safeParse(X);if(!J.success)throw new TX(400,{message:J.error.message});let{messages:G,...K}=J.data,W=G,{systemMessages:Z,requestMessage:H}=_i0(W);return{organization:Q,systemMessages:Z,requestMessage:H,...K}}function TN1(Y){let{cancelBroadcast:Q,streamBuffer:X,runRegistry:J}=Y,G=new JQ;return G.get("/:org/decopilot/allowed-models",async(K)=>{try{let W=K.get("meshContext"),Z=vr(K),H=W.auth.user?.role,$=await PN1(W.db,Z.id,H);return K.json(ui0($))}catch(W){if(console.error("[decopilot:allowed-models] Error",W),W instanceof TX)return K.json({error:W.message},W.status);return K.json({error:W instanceof Error?W.message:"Internal error"},500)}}),G.post("/:org/decopilot/stream",async(K)=>{let W,Z;try{let H=K.get("meshContext"),{organization:$,models:F,agent:V,systemMessages:B,requestMessage:U,temperature:D,memory:z,thread_id:L,toolApprovalLevel:w}=await Qm6(K),E=H.auth?.user?.id;if(!E)throw new TX(401,{message:"User ID is required"});let T=await PN1(H.db,$.id,H.auth.user?.role);if(!gi0(T,F.connectionId,F.thinking.id))throw new TX(403,{message:"Model not allowed for your role"});let C=z?.windowSize??Tr,P=L??z?.thread_id,[R,S,_]=await Promise.all([H.storage.virtualMcps.findById(V.id,$.id),H.storage.connections.findById(F.connectionId,$.id),hi0(H.storage.threads,{organization_id:$.id,thread_id:P,userId:E,defaultWindowSize:C})]),f=async(...L1)=>{let S1=Date.now(),u1=[...new Map(L1.filter(Boolean).map((Y0)=>[Y0.id,Y0])).values()].map((Y0,C1)=>({...Y0,thread_id:_.thread.id,created_at:new Date(S1+C1).toISOString(),updated_at:new Date(S1+C1).toISOString()}));if(u1.length===0)return;await _.save(u1).catch((Y0)=>{console.error("[decopilot:stream] Error saving messages",Y0)})},b=(L1)=>{H.storage.threads.update(_.thread.id,{status:L1}).catch((u1)=>{console.error("[decopilot:stream] Error updating thread status",u1)});let S1=L1==="completed"?"completed":"failed";J.finishRun(_.thread.id,S1,(u1)=>X.purge(u1)),xJ.emit($.id,IR(_.thread.id,L1)),xJ.emit($.id,cm(_.thread.id,L1))};if(W=()=>b("failed"),!S)throw Error("Model connection not found");if(!R)throw Error("Agent not found");await H.storage.threads.update(_.thread.id,{status:"in_progress"}),xJ.emit($.id,IR(_.thread.id,"in_progress"));let r=J.startRun(_.thread.id,$.id,E).abortController.signal;X.purge(_.thread.id),await f(U),r.addEventListener("abort",()=>{Z?.(),W()});let m=V.mode!=="passthrough",h=F.thinking.limits?.maxOutputTokens??Er,n=!1,$1=0,Q1=null,N1=await yi0(_,U,[VN1(),...B],C),j1=new Map,D1=uB1({originalMessages:N1,execute:async({writer:L1})=>{let[S1,u1,Y0]=await Promise.all([_5(S,H,!1),KB(R,H,"passthrough"),m?KB(R,H,V.mode):Promise.resolve(null)]);Z=()=>{S1.close().catch(()=>{}),u1.close().catch(()=>{}),Y0?.close().catch(()=>{})};let C1=VO(S1,F.connectionId,S,H,{superUser:!1}),A1=await di0(C1,F),o1=u1.getInstructions(),B4=o1?.trim()?N1.map((b4)=>b4.id==="decopilot-system"?VN1(o1):b4):N1,K4=await Pv(u1,j1,L1,w),V0=Y0?await Pv(Y0,j1,L1,w):{},y1=await vi0(L1,{modelProvider:A1,organization:$,models:F,toolApprovalLevel:w,toolOutputMap:j1},H),w1={...K4,...V0,...y1},n1=Y0?[...Object.keys(V0),...Object.keys(y1)]:void 0,{systemMessages:R1,messages:_1,originalMessages:A0}=await fi0(B4,{windowSize:C,models:F,tools:w1});if(xi0(F,A0),_.thread.title===Cr)ni0({abortSignal:r,model:A1.fastModel??A1.thinkingModel,userMessage:JSON.stringify(_1[0]?.content)}).then(async(b4)=>{if(!b4)return;if(await H.storage.threads.update(_.thread.id,{title:b4}).catch((_0)=>{console.error("[decopilot:stream] Error updating thread title",_0)}),!n)L1.write({type:"data-thread-title",data:{title:b4},transient:!0})});let J0=null,h4,S6=lA({model:A1.thinkingModel,system:R1,messages:_1,tools:w1,activeTools:n1,temperature:D,maxOutputTokens:h,abortSignal:r,stopWhen:iq(Wi0),onError:async(b4)=>{throw console.error("[decopilot:stream] Error",b4),b4}}).toUIMessageStream({originalMessages:A0,generateMessageId:Gi0,messageMetadata:({part:b4})=>{if(b4.type==="start")return{agent:{id:V.id??null,mode:V.mode},models:{connectionId:F.connectionId,thinking:F.thinking},created_at:new Date,thread_id:_.thread.id};if(b4.type==="reasoning-start"){if(J0===null)J0=new Date;return{reasoning_start_at:J0}}if(b4.type==="reasoning-end")return{reasoning_end_at:new Date};if(b4.type==="finish-step"){h4=b4.providerMetadata;return}if(b4.type==="finish"){let _0=F.thinking.provider,h1=b4.totalUsage,P0=h4??b4.providerMetadata,n4=h1?{inputTokens:h1.inputTokens??0,outputTokens:h1.outputTokens??0,reasoningTokens:h1.reasoningTokens??void 0,totalTokens:h1.totalTokens??0,providerMetadata:j71(_0&&P0?{...P0,[_0]:{...P0[_0]??{},reasoning_details:void 0}}:P0)}:void 0;return{...n4&&{usage:n4}}}return}});L1.merge(X.relay(S6,_.thread.id,r))},onFinish:async({responseMessage:L1,finishReason:S1})=>{if(n=!0,Z?.(),Q1)await Q1;if(await f(L1),r.aborted)return;let u1=ci0(S1,L1?.parts);b(u1)},onStepFinish:({responseMessage:L1})=>{if($1++,xJ.emit($.id,pm(_.thread.id,$1)),$1%5===0)Q1=f(L1).finally(()=>{Q1=null})},onError:(L1)=>{if(n=!0,Z?.(),r.aborted)return L1 instanceof Error?L1.message:String(L1);if(console.error("[decopilot] stream error:",L1),_.thread.id)W();return L1 instanceof Error?L1.message:String(L1)}});return ni({stream:D1,consumeSseStream:Dk})}catch(H){if(Z?.(),W)W();if(console.error("[decopilot:stream] Error",H),H instanceof TX)return K.json({error:H.message},H.status);if(H instanceof Error&&H.name==="AbortError")return console.warn("[decopilot:stream] Aborted",{error:H.message}),K.json({error:"Request aborted"},400);return console.error("[decopilot:stream] Failed",{error:H instanceof Error?H.message:JSON.stringify(H),stack:H instanceof Error?H.stack:void 0}),K.json({error:H instanceof Error?H.message:JSON.stringify(H)},500)}}),G.post("/:org/decopilot/cancel/:threadId",async(K)=>{let{threadId:W}=await AN1(K);if(J.cancelLocal(W))return K.json({cancelled:!0});return Q.broadcast(W),K.json({cancelled:!0,async:!0},202)}),G.get("/:org/decopilot/attach/:threadId",async(K)=>{try{let{threadId:W}=await AN1(K),Z=J.getRun(W);if(!Z||Z.status!=="running")return K.body(null,204);let H=await X.createReplayStream(W);if(!H)return K.body(null,204);let $=uB1({execute:async({writer:F})=>{let V=H.getReader();try{while(!0){let{done:B,value:U}=await V.read();if(B)break;F.write(U)}}finally{V.releaseLock()}}});return ni({stream:$,consumeSseStream:Dk})}catch(W){if(W instanceof TX)throw W;return console.error("[decopilot:attach] Error",W),K.body(null,500)}}),G}qr();var _r=new JQ;_r.post("/connections/:connectionId/oauth-token",async(Y)=>{let Q=Y.get("meshContext"),X=Y.req.param("connectionId");if(!(Q.auth.user?.id??Q.auth.apiKey?.userId??null))return Y.json({error:"Unauthorized"},401);if(!await Q.storage.connections.findById(X,Q.organization?.id))return Y.json({error:"Connection not found"},404);let K=await Y.req.json();if(!K.accessToken)return Y.json({error:"accessToken is required"},400);if(K.tokenEndpoint){let F;try{F=new URL(K.tokenEndpoint)}catch{return Y.json({error:"tokenEndpoint must be a valid URL"},400)}if(F.protocol!=="http:"&&F.protocol!=="https:")return Y.json({error:"tokenEndpoint must be an http(s) URL"},400)}let W=K.expiresIn?new Date(Date.now()+K.expiresIn*1000):null,Z=new $F(Q.db,Q.vault),H={connectionId:X,accessToken:K.accessToken,refreshToken:K.refreshToken??null,scope:K.scope??null,expiresAt:W,clientId:K.clientId??null,clientSecret:K.clientSecret??null,tokenEndpoint:K.tokenEndpoint??null},$=await Z.upsert(H);return Y.json({success:!0,expiresAt:$.expiresAt})});_r.delete("/connections/:connectionId/oauth-token",async(Y)=>{let Q=Y.get("meshContext"),X=Y.req.param("connectionId");if(!(Q.auth.user?.id??Q.auth.apiKey?.userId??null))return Y.json({error:"Unauthorized"},401);return await new $F(Q.db,Q.vault).delete(X),Y.json({success:!0})});_r.get("/connections/:connectionId/oauth-token/status",async(Y)=>{let Q=Y.get("meshContext"),X=Y.req.param("connectionId");if(!(Q.auth.user?.id??Q.auth.apiKey?.userId??null))return Y.json({error:"Unauthorized"},401);let G=new $F(Q.db,Q.vault),K=await G.get(X);if(!K)return Y.json({hasToken:!1,isExpired:!0,canRefresh:!1});let W=G.isExpired(K),Z=!!K.refreshToken&&!!K.tokenEndpoint;return Y.json({hasToken:!0,isExpired:W,canRefresh:Z,expiresAt:K.expiresAt})});var ii0=_r;Kr();zP();rZ();var CN1=class{writer;encoder;writable;abortSubscribers=[];responseReadable;aborted=!1;closed=!1;constructor(Y,Q){this.writable=Y,this.writer=Y.getWriter(),this.encoder=new TextEncoder;let X=Q.getReader();this.abortSubscribers.push(async()=>{await X.cancel()}),this.responseReadable=new ReadableStream({async pull(J){let{done:G,value:K}=await X.read();G?J.close():J.enqueue(K)},cancel:()=>{this.abort()}})}async write(Y){try{if(typeof Y==="string")Y=this.encoder.encode(Y);await this.writer.write(Y)}catch{}return this}async writeln(Y){return await this.write(Y+`
|
|
1421
1421
|
`),this}sleep(Y){return new Promise((Q)=>setTimeout(Q,Y))}async close(){try{await this.writer.close()}catch{}this.closed=!0}async pipe(Y){this.writer.releaseLock(),await Y.pipeTo(this.writable,{preventClose:!0}),this.writer=this.writable.getWriter()}onAbort(Y){this.abortSubscribers.push(Y)}abort(){if(!this.aborted)this.aborted=!0,this.abortSubscribers.forEach((Y)=>Y())}};var yr=()=>{let Y=typeof Bun<"u"?Bun.version:void 0;if(Y===void 0)return!1;let Q=Y.startsWith("1.1")||Y.startsWith("1.0")||Y.startsWith("0.");return yr=()=>Q,Q};var ai0=class extends CN1{constructor(Y,Q){super(Y,Q)}async writeSSE(Y){let X=(await kR(Y.data,em.Stringify,!1,{})).split(/\r\n|\r|\n/).map((G)=>{return`data: ${G}`}).join(`
|
|
1422
|
-
`),J=[Y.event&&`event: ${Y.event}`,X,Y.id&&`id: ${Y.id}`,Y.retry&&`retry: ${Y.retry}`].filter(Boolean).join(`
|
|
1422
|
+
`);for(let G of["event","id","retry"])if(Y[G]&&/[\r\n]/.test(Y[G]))throw Error(`${G} must not contain "\\r" or "\\n"`);let J=[Y.event&&`event: ${Y.event}`,X,Y.id&&`id: ${Y.id}`,Y.retry&&`retry: ${Y.retry}`].filter(Boolean).join(`
|
|
1423
1423
|
`)+`
|
|
1424
1424
|
|
|
1425
1425
|
`;await this.write(J)}},Xm6=async(Y,Q,X)=>{try{await Q(Y)}catch(J){if(J instanceof Error&&X)await X(J,Y),await Y.writeSSE({event:"error",data:J.message});else console.error(J)}finally{Y.close()}},Jm6=new WeakMap,Tv=(Y,Q,X)=>{let{readable:J,writable:G}=new TransformStream,K=new ai0(G,J);if(yr())Y.req.raw.signal.addEventListener("abort",()=>{if(!K.closed)K.abort()});return Jm6.set(K.responseReadable,Y),Y.header("Transfer-Encoding","chunked"),Y.header("Content-Type","text/event-stream"),Y.header("Cache-Control","no-cache"),Y.header("Connection","keep-alive"),Xm6(K,Q,X),Y.newResponse(K.responseReadable)};c1();Vv();var Wm6=q.object({type:q.literal("function"),function:q.object({name:q.string(),description:q.string().optional(),parameters:q.record(q.string(),q.unknown()).optional()})}),Zm6=q.object({id:q.string(),type:q.literal("function"),function:q.object({name:q.string(),arguments:q.string()})}),Km6=q.discriminatedUnion("role",[q.object({role:q.literal("system"),content:q.string(),name:q.string().optional()}),q.object({role:q.literal("user"),content:q.union([q.string(),q.array(q.union([q.object({type:q.literal("text"),text:q.string()}),q.object({type:q.literal("image_url"),image_url:q.object({url:q.string(),detail:q.string().optional()})})]))]),name:q.string().optional()}),q.object({role:q.literal("assistant"),content:q.string().nullable().optional(),name:q.string().optional(),tool_calls:q.array(Zm6).optional()}),q.object({role:q.literal("tool"),content:q.string(),tool_call_id:q.string()})]),Hm6=q.object({type:q.literal("text")}),$m6=q.object({type:q.literal("json_object")}),Fm6=q.object({type:q.literal("json_schema"),json_schema:q.object({name:q.string(),description:q.string().optional(),schema:q.record(q.string(),q.unknown()),strict:q.boolean().optional()})}),Vm6=q.union([Hm6,$m6,Fm6]),qm6=q.object({model:q.string().describe("Format: connection_id:model_id"),messages:q.array(Km6),stream:q.boolean().optional().default(!1),temperature:q.number().min(0).max(2).optional(),max_tokens:q.number().positive().optional(),top_p:q.number().min(0).max(1).optional(),frequency_penalty:q.number().min(-2).max(2).optional(),presence_penalty:q.number().min(-2).max(2).optional(),stop:q.union([q.string(),q.array(q.string())]).optional(),tools:q.array(Wm6).optional(),tool_choice:q.union([q.literal("auto"),q.literal("none"),q.literal("required"),q.object({type:q.literal("function"),function:q.object({name:q.string()})})]).optional(),response_format:Vm6.optional(),user:q.string().optional()});function rH(Y,Q="invalid_request_error",X=null,J=null){return{error:{message:Y,type:Q,param:X,code:J}}}function Bm6(Y){let Q=Y.indexOf(":");if(Q===-1)return null;let X=Y.substring(0,Q),J=Y.substring(Q+1);if(!X||!J)return null;return{connectionId:X,modelId:J}}class si0 extends Error{constructor(Y){super(Y);this.name="MessageConversionError"}}function Um6(Y,Q,X){try{return JSON.parse(Y)}catch{throw new si0(`Invalid JSON in tool call arguments for function '${X}' (tool_call_id: ${Q}): ${Y}`)}}function Dm6(Y){let Q={};for(let X of Y)if(X.role==="assistant"&&X.tool_calls)for(let J of X.tool_calls)Q[J.id]=J.function.name;return Y.map((X)=>{switch(X.role){case"system":return{role:"system",content:X.content};case"user":if(typeof X.content==="string")return{role:"user",content:X.content};return{role:"user",content:X.content.map((G)=>{if(G.type==="text")return{type:"text",text:G.text};return{type:"image",image:G.image_url.url}})};case"assistant":if(X.tool_calls&&X.tool_calls.length>0)return{role:"assistant",content:X.tool_calls.map((G)=>({type:"tool-call",toolCallId:G.id,toolName:G.function.name,input:Um6(G.function.arguments,G.id,G.function.name)}))};return{role:"assistant",content:X.content??""};case"tool":let J=Q[X.tool_call_id]??"unknown";return{role:"tool",content:[{type:"tool-result",toolCallId:X.tool_call_id,toolName:J,output:{type:"text",value:X.content}}]}}})}function zm6(Y){let Q=Y.map((X)=>{let J=X.function.parameters?IW(X.function.parameters):IW({type:"object",properties:{}});return[X.function.name,_J({description:X.function.description,inputSchema:J})]});return Object.fromEntries(Q)}function Om6(Y){if(!Y)return;return{openai:{response_format:Y}}}function Nm6(){return`chatcmpl-${crypto.randomUUID().replace(/-/g,"").substring(0,29)}`}async function Lm6(Y,Q,X){let J=await Y.storage.connections.findById(X);if(!J)return null;if(J.organization_id!==Q)return null;if(J.status!=="active")return null;return J}async function Mm6(Y,Q){await new FF(Y.authInstance,Y.auth.user?.id??Y.auth.apiKey?.userId,"*",Y.boundAuth,Y.auth.user?.role,Q).check("*")}function ri0(Y,Q,X,J,G,K){let W={model:Y,messages:Q,tools:X,temperature:J.temperature,maxTokens:J.max_tokens,topP:J.top_p,frequencyPenalty:J.frequency_penalty,presencePenalty:J.presence_penalty,stopSequences:J.stop?Array.isArray(J.stop)?J.stop:[J.stop]:void 0,abortSignal:K};return G?{...W,providerOptions:G}:W}function oi0(Y){if(Y==="tool-calls")return"tool_calls";if(Y==="length")return"length";return"stop"}var ti0=new JQ;ti0.post("/:org/v1/chat/completions",async(Y)=>{let Q=Y.get("meshContext"),X=Y.req.param("org");try{if(!Q.auth.apiKey?.id)return Y.json(rH("API key authentication required. Provide a valid API key via Authorization header.","authentication_error"),401);if(!Q.organization)return Y.json(rH("Organization context is required. Ensure your API key has organization metadata.","invalid_request_error","organization"),400);if((Q.organization.slug??Q.organization.id)!==X)return Y.json(rH("Organization mismatch. The API key's organization does not match the requested organization.","invalid_request_error","organization"),403);let J=await Y.req.json(),G=qm6.safeParse(J);if(!G.success){let z=G.error.issues[0]??{message:"Invalid request",path:[]};return Y.json(rH(`Invalid request: ${z.message}`,"invalid_request_error",z.path.length>0?z.path.join("."):null),400)}let K=G.data,W=Bm6(K.model);if(!W)return Y.json(rH("Invalid model format. Expected 'connection_id:model_id' (e.g., 'conn_abc123:gpt-4')","invalid_request_error","model"),400);let{connectionId:Z,modelId:H}=W;try{await Mm6(Q,Z)}catch{return Y.json(rH(`Access denied to connection: ${Z}`,"permission_error","model"),403)}let $=await Lm6(Q,Q.organization.id,Z);if(!$)return Y.json(rH(`Connection not found or inactive: ${Z}`,"invalid_request_error","model"),404);let F=Dm6(K.messages),V=K.tools?zm6(K.tools):void 0,B=Om6(K.response_format),U=Nm6(),D=Math.floor(Date.now()/1000);if(K.stream)return Tv(Y,async(z)=>{let L=await _5($,Q,!1),w=VO(L,Z,$,Q,{superUser:!1}),E=Wv.forClient(DO(w)),T=Ev(E).languageModel(H),C=ri0(T,F,V,K,B,Y.req.raw.signal);try{let P=lA(C),R=!1,S=0;for await(let _ of P.fullStream){if(!R&&(_.type==="text-delta"||_.type==="tool-call"))await z.writeSSE({data:JSON.stringify({id:U,object:"chat.completion.chunk",created:D,model:K.model,choices:[{index:0,delta:{role:"assistant",content:""},finish_reason:null}]})}),R=!0;if(_.type==="text-delta")await z.writeSSE({data:JSON.stringify({id:U,object:"chat.completion.chunk",created:D,model:K.model,choices:[{index:0,delta:{content:_.text},finish_reason:null}]})});else if(_.type==="tool-call"){let f=S++;await z.writeSSE({data:JSON.stringify({id:U,object:"chat.completion.chunk",created:D,model:K.model,choices:[{index:0,delta:{tool_calls:[{index:f,id:_.toolCallId,type:"function",function:{name:_.toolName,arguments:JSON.stringify(_.input)}}]},finish_reason:null}]})})}else if(_.type==="finish")await z.writeSSE({data:JSON.stringify({id:U,object:"chat.completion.chunk",created:D,model:K.model,choices:[{index:0,delta:{},finish_reason:oi0(_.finishReason)}],usage:_.totalUsage?{prompt_tokens:_.totalUsage.inputTokens??0,completion_tokens:_.totalUsage.outputTokens??0,total_tokens:_.totalUsage.totalTokens??0}:void 0})})}await z.writeSSE({data:"[DONE]"})}catch(P){let R=P;console.error("[openai-compat:stream] Error:",R.message),await z.writeSSE({data:JSON.stringify({error:{message:R.message,type:"server_error"}})})}});else{let z=await _5($,Q,!1),L=Wv.forClient(DO(z)),w=Ev(L).languageModel(H),E=ri0(w,F,V,K,B,Y.req.raw.signal),T=await mA(E),C={role:"assistant",content:T.text||null};if(T.toolCalls&&T.toolCalls.length>0)C.tool_calls=T.toolCalls.map((P)=>({id:P.toolCallId,type:"function",function:{name:P.toolName,arguments:JSON.stringify("input"in P?P.input:{})}})),C.content=null;return Y.json({id:U,object:"chat.completion",created:D,model:K.model,choices:[{index:0,message:C,finish_reason:oi0(T.finishReason)}],usage:{prompt_tokens:T.usage?.inputTokens??0,completion_tokens:T.usage?.outputTokens??0,total_tokens:T.usage?.totalTokens??0}})}}catch(J){let G=J;if(G.name==="AbortError")return Y.json(rH("Request aborted","invalid_request_error"),400);if(G.name==="MessageConversionError")return Y.json(rH(G.message,"invalid_request_error","messages"),400);return console.error("[openai-compat] Error:",G.message,G.stack),Y.json(rH(G.message,"server_error"),500)}});var ei0=ti0;QS();var Ya0=new JQ;Ya0.get("/",(Y)=>{let Q={theme:FT0()};return Y.json({success:!0,config:Q})});var Qa0=Ya0;dS();rO1();var Xa0=new JQ;Xa0.all("/",async(Y)=>{let Q=await aO1(Y.get("meshContext")),X=new g$({enableJsonResponse:Y.req.raw.headers.get("Accept")?.includes("application/json")??!1});return await Q.connect(X),X.handleRequest(Y.req.raw)});var Ja0=Xa0;var Cv={HEALTH:"/health",METRICS:"/metrics"},MP={API:"/api/",API_AUTH:"/api/auth/",MCP:"/mcp/",OAUTH_PROXY:"/oauth-proxy/",WELL_KNOWN:"/.well-known",ORG:"/org/"},wm6=/\.(html|css|js|ico|svg|png|jpg|jpeg|gif|webp|woff|woff2)$/;function Ga0(Y){return Y===Cv.HEALTH||Y===Cv.METRICS||Y.startsWith(MP.WELL_KNOWN)}function Am6(Y){return Y.startsWith(MP.API)}function Pm6(Y){return Y==="/mcp"||Y.startsWith(MP.MCP)}function Em6(Y){return Y.startsWith(MP.OAUTH_PROXY)}function Tm6(Y){return wm6.test(Y)}function Cm6(Y){return Y.startsWith(MP.ORG)}function Wa0(Y){return Am6(Y)||Pm6(Y)||Em6(Y)||Cm6(Y)||Ga0(Y)}function Za0(Y){return Y==="/"||Y.startsWith(MP.API_AUTH)||Ga0(Y)||Tm6(Y)}Yr();Tn();class RN1{onCancel=null;async start(Y){this.onCancel=Y}broadcast(Y){this.onCancel?.(Y)}async stop(){this.onCancel=null}}var vt0=E6(FM1(),1);function _t0(){let Y=null,Q=null;return{async init(X){if(Y)return;Y=await vt0.connect({servers:X}),console.log("[NATS] Connected")},getConnection(){return Y},getJetStream(){if(!Y)return null;if(!Q)Q=Y.jetstream();return Q},async drain(){if(Q=null,Y){let X=Y;Y=null,await X.drain().catch(()=>{}),console.log("[NATS] Connection drained")}}}}class VM1{options;sub=null;onCancel=null;encoder=new TextEncoder;originId=crypto.randomUUID();constructor(Y){this.options=Y}async start(Y){this.onCancel=Y;let Q=this.options.getConnection();if(!Q||this.sub)return;this.sub=Q.subscribe("mesh.decopilot.cancel");let X=new TextDecoder;(async()=>{for await(let J of this.sub)try{let G=JSON.parse(X.decode(J.data));if(G.originId===this.originId)continue;this.onCancel?.(G.threadId)}catch{}})().catch(console.error),console.log("[NatsCancelBroadcast] Started, subscribed to","mesh.decopilot.cancel")}broadcast(Y){if(/[.*>\s]/.test(Y)){console.warn("[NatsCancelBroadcast] Invalid threadId, skipping broadcast");return}this.onCancel?.(Y);let Q=this.options.getConnection();if(!Q)return;try{Q.publish("mesh.decopilot.cancel",this.encoder.encode(JSON.stringify({threadId:Y,originId:this.originId})))}catch(X){console.warn("[NatsCancelBroadcast] Publish failed (non-critical):",X)}}async stop(){this.sub?.unsubscribe(),this.sub=null,this.onCancel=null,console.log("[NatsCancelBroadcast] Stopped")}}class qM1{async init(){}relay(Y){return Y}async createReplayStream(){return null}purge(){}teardown(){}}var AB=E6(FM1(),1),xo="DECOPILOT_STREAMS",yt0="decopilot.stream",Ka6=300000000000,Ha6=524288000,$a6=20000,Fa6=30000;function Va6(Y){if(/[.*>\s]/.test(Y))throw Error("Invalid NATS subject token")}function BM1(Y){return Va6(Y),`${yt0}.${Y}`}function qa6(Y){let Q=0;return{publish(X,J,G){X.publish(J,G).catch((K)=>{if(Q++,Q===1||Q%100===0)console.warn(`[Decopilot] JetStream publish failed for thread ${Y} (${Q} total):`,K)})},get errorCount(){return Q}}}class UM1{options;js=null;jsm=null;encoder=new TextEncoder;constructor(Y){this.options=Y}async init(){let Y=this.options.getConnection();if(!Y)return;let Q=await Y.jetstreamManager(),X={name:xo,subjects:[`${yt0}.>`],storage:AB.StorageType.Memory,max_age:Ka6,max_bytes:Ha6,max_msgs_per_subject:$a6,discard:AB.DiscardPolicy.Old,retention:AB.RetentionPolicy.Limits,num_replicas:1};try{await Q.streams.info(xo),await Q.streams.update(xo,X)}catch(J){if(J instanceof Error&&J.message.includes("stream not found"))await Q.streams.add(X);else throw J}this.js=this.options.getJetStream(),this.jsm=Q,console.log("[Decopilot] JetStream stream buffer ready (memory storage, 5min TTL, 20K msgs/subject)")}relay(Y,Q,X){let J=this.js;if(!J)return Y;let G=BM1(Q),K=qa6(Q),W=this.encoder,Z=!1,H=()=>{if(Z)return;Z=!0,J.publish(G,W.encode(JSON.stringify({done:!0}))).catch(()=>{})};return X?.addEventListener("abort",H),Y.pipeThrough(new TransformStream({transform($,F){F.enqueue($),K.publish(J,G,W.encode(JSON.stringify({p:$})))},flush(){X?.removeEventListener("abort",H),H()}}))}async createReplayStream(Y){let Q=this.js;if(!Q)return null;let X=BM1(Y),J;try{J=await Q.subscribe(X,{ordered:!0,config:{filter_subject:X,ack_policy:AB.AckPolicy.None}})}catch(W){return console.warn("[Decopilot] JetStream replay unavailable (non-critical):",W?.message??W),null}let G=new TextDecoder,K=async function*(){for await(let W of J)yield W}();return new ReadableStream({async pull(W){while(!0){let Z,H=await Promise.race([K.next(),new Promise((F)=>{Z=setTimeout(()=>F({done:!0,value:void 0}),Fa6)})]);if(clearTimeout(Z),H.done){J.unsubscribe(),W.close();return}let $=H.value;try{let F=JSON.parse(G.decode($.data));if(F.done){J.unsubscribe(),W.close();return}if(F.p){W.enqueue(F.p);return}}catch{}}},cancel(){J.unsubscribe()}})}purge(Y){if(!this.jsm)return;this.jsm.streams.purge(xo,{filter:BM1(Y)}).catch(()=>{})}teardown(){this.js=null,this.jsm=null,console.log("[Decopilot] JetStream stream buffer torn down")}}class DM1{runs=new Map;reaperTimer=null;constructor(){this.reaperTimer=setInterval(()=>this.reapStaleRuns(),300000)}reapStaleRuns(){let Y=Date.now();for(let[Q,X]of this.runs)if(X.status==="running"&&Y-X.startedAt.getTime()>1800000)console.warn(`[RunRegistry] Reaping stale run for thread ${Q} (age: ${Math.round((Y-X.startedAt.getTime())/60000)}min)`),X.status="failed",X.abortController.abort(),this.runs.delete(Q)}startRun(Y,Q,X){let J=this.runs.get(Y);if(J){if(J.status==="running")J.abortController.abort();J.status="failed",this.runs.delete(Y)}let G={threadId:Y,orgId:Q,userId:X,abortController:new AbortController,status:"running",startedAt:new Date};return this.runs.set(Y,G),G}getRun(Y){return this.runs.get(Y)}cancelLocal(Y){let Q=this.runs.get(Y);if(!Q||Q.status!=="running")return!1;return Q.status="failed",Q.abortController.abort(),!0}completeRun(Y,Q){let X=this.runs.get(Y);if(X)X.status=Q,this.runs.delete(Y)}finishRun(Y,Q,X){this.completeRun(Y,Q),X?.(Y)}stopAll(Y){for(let[Q,X]of this.runs)if(X.status==="running")X.abortController.abort(),Y.update(Q,{status:"failed"}).catch(()=>{});this.runs.clear()}dispose(){if(this.reaperTimer)clearInterval(this.reaperTimer),this.reaperTimer=null}}AF1();l71();var go=null,zM1=null;async function Ba6(Y,Q){let J=(await Y.storage.connections.list(Q)).find((G)=>G.connection_url?.startsWith(IJ0));if(!J?.configuration_state)return null;return J.configuration_state.project_locator}function Ua6(Y){let Q=new URLSearchParams;if(Y){let[X,J]=Y.split("/");if(X)Q.set("workspace_hint",X);if(J)Q.set("project_hint",J)}else Q.set("auto_personal","true");return Q.set("force_new","true"),Q}var Da6=new ft0.PrometheusSerializer,za6=()=>LF1(BF),Oa6=()=>NF1(BF);async function bt0(Y={}){let Q=Y.database??Pn();if(go&&go.isRunning())console.log("[EventBus] Stopping previous worker (HMR cleanup)"),Promise.resolve(go.stop()).catch((z)=>{console.error("[EventBus] Error stopping previous worker:",z)}),xJ.stop().catch((z)=>{console.error("[SSEHub] Error stopping previous broadcast (HMR cleanup):",z)});let X=process.env.NATS_URL,J=X?_t0():null;if(J)try{await J.init(X)}catch(z){console.warn("[NATS] Connection failed, falling back to local-only mode:",z),J=null}let G;if(Y.eventBus)G=Y.eventBus,xJ.start().catch((z)=>{console.error("[SSEHub] Error starting broadcast (custom eventBus):",z)});else G=Ei0(Q,void 0,J);if(go=G,zM1)zM1();let K=new Lv(Q.db),W=new DM1,Z=J?new VM1({getConnection:()=>J.getConnection()}):new RN1,H=J?new UM1({getConnection:()=>J.getConnection(),getJetStream:()=>J.getJetStream()}):new qM1;Z.start((z)=>W.cancelLocal(z)).catch((z)=>{console.error("[Decopilot] CancelBroadcast start failed:",z)}),H.init().catch((z)=>{console.warn("[Decopilot] StreamBuffer init failed, attach/late-join disabled:",z)}),zM1=()=>{W.stopAll(K),W.dispose(),Z.stop().catch(()=>{}),H.teardown(),J?.drain().catch(()=>{})};let $=new JQ;$.use("*",u71({enabled:(z)=>FF0(z,"debug")==="1"})),$.use("*",W91),$.use("/*",VF0({origin:(z)=>{if(z.includes("localhost")||z.includes("127.0.0.1"))return z;return z},credentials:!0,allowMethods:["GET","POST","PUT","DELETE","OPTIONS"],allowHeaders:["Content-Type","Authorization","mcp-protocol-version"],exposeHeaders:["WWW-Authenticate"]})),$.use("*",UF0()),$.use("*",async(z,L)=>{if(await L(),z.res.status>=500){let E=await z.res.clone().text();console.error(`[5xx Response] ${z.req.method} ${z.req.path} - ${z.res.status}:`,E)}}),$.get(Cv.HEALTH,(z)=>{return z.json({status:"ok",timestamp:new Date().toISOString(),version:"1.0.0"})}),$.get(Cv.METRICS,async(z)=>{try{let L=await K91.collect(),w=Da6.serialize(L.resourceMetrics);return z.text(w,200,{"Content-Type":"text/plain; version=0.0.4; charset=utf-8"})}catch(L){return console.error("Failed to collect metrics:",L),z.text("# Error collecting metrics",500)}}),$.route("/api/config",Qa0),$.route("/api/auth/custom",Ri0),$.all("/api/auth/*",async(z)=>{return await BF.handler(z.req.raw)}),$.route("/",sn0),$.all("/oauth-proxy/:connectionId/*",async(z)=>{let L=z.req.param("connectionId"),w=z.req.path.split("/").filter(Boolean),E=w[w.length-1],T=z.get("meshContext");if(!T)T=await UF.create(z.req.raw),z.set("meshContext",T);let C=await T.storage.connections.findById(L);if(!C?.connection_url)return z.json({error:"Connection not found"},404);let P=await wr(C.connection_url),R,S=new URL(C.connection_url);if(P.ok)R=(await P.json()).authorization_servers?.[0];if(!R)R=S.origin;let _=await HN1(R);if(!_.ok)return z.json({error:"Failed to get auth server metadata"},502);let f=await _.json(),b;if(E==="authorize")b=f.authorization_endpoint;else if(E==="token")b=f.token_endpoint;else if(E==="register")b=f.registration_endpoint;if(!b)return z.json({error:`Unknown OAuth endpoint: ${E}`},404);let g=new URL(b),r=new URL(z.req.url);if(g.search=r.search,E==="authorize"){if(g.searchParams.has("resource"))g.searchParams.set("resource",C.connection_url);if(jJ0(C.connection_url))try{let D1=await Ba6(T,C.organization_id),L1=Ua6(D1);for(let[S1,u1]of L1)g.searchParams.set(S1,u1)}catch(D1){console.warn("[oauth-proxy] Failed to get smart OAuth params, proceeding without:",D1)}return z.redirect(g.toString(),302)}let m={Accept:z.req.header("Accept")||"application/json"},h=z.req.header("Content-Type");if(h)m["Content-Type"]=h;let n=z.req.header("Authorization");if(n)m.Authorization=n;let $1;if(z.req.method!=="GET"&&z.req.method!=="HEAD")if(E==="token"&&h?.includes("application/x-www-form-urlencoded")){let D1=await z.req.formData();if(D1.has("resource"))D1.set("resource",C.connection_url);let L1=new URLSearchParams;for(let[S1,u1]of D1.entries())L1.append(S1,u1.toString());$1=L1.toString()}else $1=z.req.raw.body??void 0;let Q1=await fetch(g.toString(),{method:z.req.method,headers:m,body:$1,duplex:"half",redirect:"manual"}),N1=new Headers,j1=["connection","keep-alive","transfer-encoding","content-encoding","content-length"];for(let[D1,L1]of Q1.headers.entries())if(!j1.includes(D1.toLowerCase()))N1.set(D1,L1);return new Response(Q1.body,{status:Q1.status,statusText:Q1.statusText,headers:N1})}),$.get("/mcp/:gateway?/:connectionId/.well-known/oauth-protected-resource/*",async(z)=>{let w=await za6()(z.req.raw),E=await w.json();return Response.json(E,w)});let F=async(z)=>{let w=await Oa6()(z.req.raw),E=await w.json();return Response.json(E,w)};$.get("/.well-known/oauth-authorization-server/*/:gateway?/:connectionId?",F);let V=await Vi0({db:Q.db,databaseType:Q.type,auth:BF,encryption:{key:process.env.ENCRYPTION_KEY||""},observability:{tracer:$N,meter:yb},eventBus:G});UF.set(V),Promise.resolve(G.start()).then(()=>{return console.log("[EventBus] Worker started"),gd0({db:Q.db,publish:async(z,L)=>{await G.publish(z,"",L)}})}).catch((z)=>{console.error("[EventBus] Error during startup:",z)}),$.use("*",async(z,L)=>{if(Za0(z.req.path))return L();let w={measure:async(T,C)=>{zM(z,T);try{return await C()}finally{wD(z,T)}}},E=await UF.create(z.req.raw,{timings:w});return z.set("meshContext",E),L()}),$.get("/api/tools/management",(z)=>{return z.json({tools:m71,grouped:hR()})}),$.use("/mcp/*",async(z,L)=>{zM(z,"mcp");try{return await L()}finally{wD(z,"mcp")}});let B=async(z,L)=>{let w=z.var.meshContext;if(!w.auth.user?.id&&!w.auth.apiKey?.id){let E=new URL(z.req.url);return z.res=new Response(null,{status:401,headers:{"WWW-Authenticate":`Bearer realm="mcp",resource_metadata="${E.origin}${E.pathname}/.well-known/oauth-protected-resource"`}})}return await L()};$.use("/mcp/:connectionId?",B),$.use("/mcp/gateway/:virtualMcpId?",B),$.use("/mcp/virtual-mcp/:virtualMcpId?",B),$.use("/mcp/self",B),$.route("/mcp",tn0),$.route("/mcp/self",Ja0),$.route("/mcp",Ji0),$.use("/api/:org/models/*",async(z,L)=>{zM(z,"llm_models");try{return await L()}finally{wD(z,"llm_models")}});let U=TN1({cancelBroadcast:Z,streamBuffer:H,runRegistry:W});$.route("/api",U),$.route("/api",ei0),$.post("/org/:organizationId/events/:type",async(z)=>{let L=z.req.param("organizationId");return await z.var.meshContext.eventBus.publish(L,IY.SELF(L),{data:await z.req.json(),type:`public:${z.req.param("type")}`,subject:z.req.query("subject"),deliverAt:z.req.query("deliverAt"),cron:z.req.query("cron")}),z.json({success:!0})}),$.get("/org/:organizationId/watch",async(z)=>{let L=z.var.meshContext;if(!(L.auth.user?.id??L.auth.apiKey?.userId))return z.json({error:"Unauthorized"},401);let E=z.req.param("organizationId");if(E!==L.organization?.id)return z.json({error:"Forbidden access to organization"},403);let T=z.req.query("types"),C=T?T.split(",").map((R)=>R.trim()).filter(Boolean):null,P=crypto.randomUUID();return Tv(z,async(R)=>{if(await R.writeSSE({event:"connected",data:JSON.stringify({listenerId:P,organizationId:E,typePatterns:C,connectedAt:new Date().toISOString()})}),!xJ.add({id:P,organizationId:E,typePatterns:C?.length?C:null,push:(f)=>{R.writeSSE({id:f.id,event:f.type,data:JSON.stringify(f)}).catch(()=>{})}})){await R.writeSSE({event:"error",data:JSON.stringify({error:"Too many connections",message:"SSE connection limit reached. Try again later."})});return}let _=setInterval(()=>{R.writeSSE({event:"keepalive",data:""}).catch(()=>{clearInterval(_)})},30000);R.onAbort(()=>{clearInterval(_),xJ.remove(E,P)}),await new Promise((f)=>{R.onAbort(()=>f())})})}),$.route("/api",ii0);let D=new Rz(process.env.ENCRYPTION_KEY||"");return hd0(Q.db,D),bd0($,{db:Q.db,vault:D}),$.notFound((z)=>{return z.json({error:"Not Found",path:z.req.path},404)}),$.onError((z,L)=>{console.error("Server error :",z);let w=z instanceof Error?z.message:"Unknown error";return L.json({error:"Internal Server Error",message:w},500)}),$}import ht0 from"v8";import{rename as Na6,mkdir as La6}from"fs/promises";import{join as Ma6}from"path";function xt0(Y){let{port:Q,hostname:X="0.0.0.0"}=Y;return Bun.serve({port:Q,hostname:X,fetch:async(J)=>{let G=new URL(J.url);if(G.pathname==="/health")return Response.json({status:"ok",uptime:process.uptime()});if(G.pathname==="/memory")return Response.json({...process.memoryUsage(),uptimeSeconds:process.uptime()});if(G.pathname==="/heap-snapshot"){let K=Date.now();try{let W=ht0.writeHeapSnapshot(),Z=Bun.file(W);return new Response(Z,{headers:{"Content-Type":"application/octet-stream","Content-Disposition":`attachment; filename="heap-${K}.heapsnapshot"`}})}catch(W){return Response.json({error:String(W)},{status:500})}}if(G.pathname==="/gc"){if(typeof Bun.gc==="function")return Bun.gc(!0),Response.json({status:"gc triggered"});return Response.json({status:"gc not available"},{status:501})}if(G.pathname==="/prestop-hook"){let K=process.env.PRESTOP_HEAP_SNAPSHOT_DIR;if(!K)return Response.json({status:"skipped",reason:"PRESTOP_HEAP_SNAPSHOT_DIR not set"});try{await La6(K,{recursive:!0});let W=ht0.writeHeapSnapshot(),Z=process.env.HOSTNAME??process.env.POD_NAME??"unknown",H=new Date().toISOString().replace(/[:.]/g,"-"),$=`${Z}-${H}.heapsnapshot`,F=Ma6(K,$);await Na6(W,F);let V=process.memoryUsage();return console.log("[prestop-hook] Heap snapshot saved:",F),Response.json({status:"saved",path:F,memory:{rss:V.rss,heapUsed:V.heapUsed,external:V.external}})}catch(W){return console.error("[prestop-hook] Failed to save heap snapshot:",W),Response.json({error:String(W)},{status:500})}}return Response.json({error:"Not found"},{status:404})}})}var ut0=parseInt(process.env.PORT||"3000",10),gt0=parseInt(process.env.DEBUG_PORT||"9090",10),wa6=process.env.ENABLE_DEBUG_SERVER==="true",mP="\x1B[0m",Aa6="\x1B[1m",mt0="\x1B[2m",Pa6="\x1B[32m",lt0="\x1B[36m",dt0="\x1B[4m",Ea6=`http://localhost:${ut0}`,Ta6=RJ0({clientDir:CJ0(import.meta.url,"../client"),isServerPath:Wa0}),Ca6=await bt0();console.log("");console.log(`${Pa6}\u2713${mP} ${Aa6}Ready${mP}`);console.log("");console.log(` ${mt0}Open in browser:${mP} ${lt0}${dt0}${Ea6}${mP}`);console.log("");Bun.serve({idleTimeout:0,port:ut0,hostname:"0.0.0.0",fetch:async(Y)=>{return await Ta6(Y)??Ca6.fetch(Y)},development:!1});if(wa6)xt0({port:gt0}),console.log(` ${mt0}Debug server:${mP} ${lt0}${dt0}http://localhost:${gt0}${mP}`),console.log("");
|