@decocms/mesh 2.109.1 → 2.111.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-BNHu4U_w.js → AlertCircle-bEWTGYQE.js} +1 -1
- package/dist/client/assets/{AlertOctagon-B_77zMvV.js → AlertOctagon-jm8CcrPk.js} +1 -1
- package/dist/client/assets/{AlertTriangle-B3iutOXb.js → AlertTriangle-eAB-0ieE.js} +1 -1
- package/dist/client/assets/{ArrowLeft-BCoINK1a.js → ArrowLeft-D7uAItRc.js} +1 -1
- package/dist/client/assets/{ArrowUp-BfLZrH4Z.js → ArrowUp-CkcaWCpU.js} +1 -1
- package/dist/client/assets/{Check-DG5LOfHE.js → Check-Cde7RTNZ.js} +1 -1
- package/dist/client/assets/{CheckCircle-DXUyPLGJ.js → CheckCircle-Br3rkknf.js} +1 -1
- package/dist/client/assets/{CheckDone01-BVECQ061.js → CheckDone01-CpbJnE_m.js} +1 -1
- package/dist/client/assets/{ChevronDown-P4XeJ9w5.js → ChevronDown-BHLkCRfV.js} +1 -1
- package/dist/client/assets/{ChevronRight-CHS1psX7.js → ChevronRight-Dto52yQm.js} +1 -1
- package/dist/client/assets/{Clock-DbrHehdf.js → Clock-oB8PnqIX.js} +1 -1
- package/dist/client/assets/{Code01-Dte9rLPH.js → Code01-CO57rkhh.js} +1 -1
- package/dist/client/assets/{Container-DZJok7qt.js → Container-CuEVA9z5.js} +1 -1
- package/dist/client/assets/{Copy01-CBdgbqFW.js → Copy01-D6cA5Bao.js} +1 -1
- package/dist/client/assets/{Dataflow03-WvCvIAmM.js → Dataflow03-DQnu0GHc.js} +1 -1
- package/dist/client/assets/{DotsHorizontal-x234Trom.js → DotsHorizontal-CAUuRIsX.js} +1 -1
- package/dist/client/assets/{DotsVertical-BAfOGQhL.js → DotsVertical-4-6MpG1x.js} +1 -1
- package/dist/client/assets/{Download01-B_ClGnf8.js → Download01-BpooYyea.js} +1 -1
- package/dist/client/assets/{Edit01-BtQjuTbw.js → Edit01-D_He0Qcx.js} +1 -1
- package/dist/client/assets/{Eye-HNj86q6R.js → Eye-sS8C8lhQ.js} +1 -1
- package/dist/client/assets/{File02-D7uMen2N.js → File02-Cd2nxs7e.js} +1 -1
- package/dist/client/assets/{File06-CqEjxUxt.js → File06-BbX0X3RW.js} +1 -1
- package/dist/client/assets/{FilterLines-bS8_Yh-E.js → FilterLines-D1Wq_oLr.js} +1 -1
- package/dist/client/assets/{Globe01-BijbXV_r.js → Globe01-BMYxDRJg.js} +1 -1
- package/dist/client/assets/{Globe02-DKIs5RjV.js → Globe02-DdJralrq.js} +1 -1
- package/dist/client/assets/{Grid01-CgP_l9be.js → Grid01-c14CcfGv.js} +1 -1
- package/dist/client/assets/{Home02-SUAjW3nz.js → Home02-BqhNdrz1.js} +1 -1
- package/dist/client/assets/{Image01-CTxAUEpv.js → Image01-4UI6PMDR.js} +1 -1
- package/dist/client/assets/{Inbox01-IqJkaMzy.js → Inbox01-CWLqt9Yb.js} +1 -1
- package/dist/client/assets/{InfoCircle-Bb5NzZd-.js → InfoCircle-DURjpgB8.js} +1 -1
- package/dist/client/assets/{Key01-BB3q5OcJ.js → Key01-bjXfeM33.js} +1 -1
- package/dist/client/assets/{LinkExternal01-BTGVW1Qi.js → LinkExternal01-14dslzCC.js} +1 -1
- package/dist/client/assets/{List-RSBUWz52.js → List-Bz-HqB2A.js} +1 -1
- package/dist/client/assets/{Loading01-D-iQ3x6B.js → Loading01-Ch2k_cO0.js} +1 -1
- package/dist/client/assets/{Lock01-BCf2m01i.js → Lock01-CekSmM4P.js} +1 -1
- package/dist/client/assets/{Pin01-I9LdYIlC.js → Pin01-BuY2xAOk.js} +1 -1
- package/dist/client/assets/{Play-DqomGUHs.js → Play-B_rcTUes.js} +1 -1
- package/dist/client/assets/{Plus-B8rm50Ox.js → Plus-UwL8F8N3.js} +1 -1
- package/dist/client/assets/{RefreshCcw01-ByoHxPlX.js → RefreshCcw01-CZU5hF6U.js} +1 -1
- package/dist/client/assets/{RefreshCw01-D5lhZ8mX.js → RefreshCw01-V0SIJl2n.js} +1 -1
- package/dist/client/assets/{Save01-9tV2ohjl.js → Save01-CA4PXZOb.js} +1 -1
- package/dist/client/assets/{SearchMd-DWE3UxU2.js → SearchMd-DjhJ-jXf.js} +1 -1
- package/dist/client/assets/{Settings01-DKrG7yMR.js → Settings01-dX8zcRzd.js} +1 -1
- package/dist/client/assets/{Settings02-OMvHwhZ2.js → Settings02-UBagZMD9.js} +1 -1
- package/dist/client/assets/{Share07-DK8c-5Z6.js → Share07-DjzTAxVa.js} +1 -1
- package/dist/client/assets/{Terminal-DKHY5zjy.js → Terminal-C0dbAH7y.js} +1 -1
- package/dist/client/assets/{Tool01-BAR4Pm87.js → Tool01-udXArWal.js} +1 -1
- package/dist/client/assets/{Trash01-DOoBIHb_.js → Trash01-DS8Nec2-.js} +1 -1
- package/dist/client/assets/{Upload01-DCltlStQ.js → Upload01-t6HaYGdn.js} +1 -1
- package/dist/client/assets/{Users03-Bf7uxoC5.js → Users03-hdIubEDI.js} +1 -1
- package/dist/client/assets/{X-DA2sDUV2.js → X-BqxbJGqL.js} +1 -1
- package/dist/client/assets/{XCircle-D6Zk67At.js → XCircle-BgwNOOZJ.js} +1 -1
- package/dist/client/assets/{XClose-D-0Eqw-_.js → XClose-Bprl3cRT.js} +1 -1
- package/dist/client/assets/{agent-connections-preview-N_Bygs3y.js → agent-connections-preview-lJfk_RJm.js} +1 -1
- package/dist/client/assets/{agent-detail-B6enUst-.js → agent-detail-Bhc0r91L.js} +1 -1
- package/dist/client/assets/{agents-CF1_nQU-.js → agents-CE6JDpYA.js} +1 -1
- package/dist/client/assets/{alert-dialog-Bow6SDVm.js → alert-dialog-gWwSFFbG.js} +1 -1
- package/dist/client/assets/{auth-catchall-D97a-l8D.js → auth-catchall-BFiMZMS8.js} +1 -1
- package/dist/client/assets/{avatar-B37qTwXF.js → avatar-IuwJgub4.js} +1 -1
- package/dist/client/assets/{badge-CbuZxOhE.js → badge-Bd9ds4H4.js} +1 -1
- package/dist/client/assets/{binder-BzuI_xjk.js → binder-DmSKEcn-.js} +1 -1
- package/dist/client/assets/{breadcrumb-B9K_bdts.js → breadcrumb-C6MfuXzl.js} +1 -1
- package/dist/client/assets/{button-KbFW4XuN.js → button-D5BNc8dp.js} +1 -1
- package/dist/client/assets/{card-CIHNFHDM.js → card-Cgc78Uht.js} +1 -1
- package/dist/client/assets/{checkbox-BgvZYkw3.js → checkbox-SFEz6K4_.js} +1 -1
- package/dist/client/assets/{circle-alert-Ccks-MAu.js → circle-alert-C2beg3p1.js} +1 -1
- package/dist/client/assets/{collection-detail-C_N0geWQ.js → collection-detail-z9D01Or4.js} +1 -1
- package/dist/client/assets/{collection-tab-C-RG3I-p.js → collection-tab-D3tlAngj.js} +1 -1
- package/dist/client/assets/{collection-table-wrapper-CTALYkV9.js → collection-table-wrapper-CsEhs8YK.js} +1 -1
- package/dist/client/assets/{collection-tabs-DRICSlCe.js → collection-tabs-B2eW2C84.js} +1 -1
- package/dist/client/assets/{command-TRqwLhQ_.js → command-Dq7w6ynt.js} +1 -1
- package/dist/client/assets/{connect-DWSDNHqf.js → connect-BFutdXGM.js} +1 -1
- package/dist/client/assets/{connection-card-BBZJ8W3M.js → connection-card-DoCZrTVq.js} +1 -1
- package/dist/client/assets/{connection-detail-BL7CKfM7.js → connection-detail-BcxUiwIW.js} +1 -1
- package/dist/client/assets/{connections-CTHmnJaG.js → connections-BB4IuRF4.js} +1 -1
- package/dist/client/assets/constants-B0PTmP5X.js +1 -0
- package/dist/client/assets/{constants-C56FepeM.js → constants-BDmh-5yq.js} +1 -1
- package/dist/client/assets/{create-organization-dialog-BOVQgbie.js → create-organization-dialog-DqUIdZF5.js} +1 -1
- package/dist/client/assets/{create-project-dialog-Cbp27b9r.js → create-project-dialog-DyPUq5zk.js} +1 -1
- package/dist/client/assets/{dialog-CTzYyOCo.js → dialog-CG-MxlwQ.js} +1 -1
- package/dist/client/assets/{dropdown-menu-COB17A0Z.js → dropdown-menu-DIfkZHca.js} +1 -1
- package/dist/client/assets/{dynamic-plugin-layout-CU_9kBh0.js → dynamic-plugin-layout-CiI0chwE.js} +1 -1
- package/dist/client/assets/{empty-state-DbrAwFcx.js → empty-state-Dmo1TSMW.js} +1 -1
- package/dist/client/assets/{empty-state-DYt7iyWe.js → empty-state-GVjUPx0I.js} +1 -1
- package/dist/client/assets/{env-vars-editor-Dy_wYHf8.js → env-vars-editor-8mXm1o_h.js} +1 -1
- package/dist/client/assets/{error-boundary-CNsxzBU5.js → error-boundary-B6Gf4fgG.js} +1 -1
- package/dist/client/assets/{extract-connection-data-JqSd5LuK.js → extract-connection-data-gZ1JZJmA.js} +1 -1
- package/dist/client/assets/{file-browser-ZLEw2qLV.js → file-browser-BQ0mYskp.js} +2 -2
- package/dist/client/assets/{form-3k69lugl.js → form-DvnhpLXs.js} +1 -1
- package/dist/client/assets/{grid-view-D__vcP1M.js → grid-view-DlZbmvf-.js} +1 -1
- package/dist/client/assets/{home-BOWI6wWW.js → home-Bjl27M0K.js} +1 -1
- package/dist/client/assets/{index-BaKw5S62.js → index-BlXwEQ9V.js} +1 -1
- package/dist/client/assets/{index-CuIrPKu9.js → index-BvhQiadW.js} +3 -3
- package/dist/client/assets/{index-Db6r-OFW.js → index-CyL8KErr.js} +1 -1
- package/dist/client/assets/{index-52ezqwYc.js → index-D-6JKh3p.js} +1 -1
- package/dist/client/assets/{index-CEBU5ikU.js → index-DRXes33a.js} +1 -1
- package/dist/client/assets/{index-Bs7FV238.js → index-DbcJt8XX.js} +1 -1
- package/dist/client/assets/{index-m3V673uZ.js → index-QzN6MLN4.js} +1 -1
- package/dist/client/assets/{index-BhWwwe4k.js → index-WXQ5eAXl.js} +1 -1
- package/dist/client/assets/{index-1ZfnT2oW.js → index-ta9cE60F.js} +1 -1
- package/dist/client/assets/{infiniteQueryObserver-60Pvs7lk.js → infiniteQueryObserver-DptHeBQv.js} +1 -1
- package/dist/client/assets/{input-g5LrnBay.js → input-2Z65TF1A.js} +1 -1
- package/dist/client/assets/{integration-icon-CgM-an9b.js → integration-icon-8s4NHKIN.js} +1 -1
- package/dist/client/assets/{label-BRqnACHD.js → label-CKUxsWQ-.js} +1 -1
- package/dist/client/assets/{layout-veX2bHTO.js → layout-DLBZsl0p.js} +1 -1
- package/dist/client/assets/{localstorage-keys-DVialVZJ.js → localstorage-keys-ZSpnvEZj.js} +1 -1
- package/dist/client/assets/{login-Bo_vv91H.js → login-BkOZREWM.js} +1 -1
- package/dist/client/assets/{markdown-B9MVxSX8.js → markdown-xMtZt85F.js} +1 -1
- package/dist/client/assets/{mcp-oauth-CqxFiNor.js → mcp-oauth-DtO03_dC.js} +1 -1
- package/dist/client/assets/{mcp-server-card-B7R2dxPn.js → mcp-server-card-CgYOdmzv.js} +1 -1
- package/dist/client/assets/{mcp-server-detail-CgW9CI19.js → mcp-server-detail-fMqJHIia.js} +2 -2
- package/dist/client/assets/{members-R5hOA6Ln.js → members-CYvMiKld.js} +1 -1
- package/dist/client/assets/{monitoring-C0HiMyW6.js → monitoring-DzuawcVe.js} +1 -1
- package/dist/client/assets/{monitoring-dashboard-edit-CXDrAMd6.js → monitoring-dashboard-edit-DvF-f_Px.js} +1 -1
- package/dist/client/assets/{monitoring-dashboard-view-DIquPtHE.js → monitoring-dashboard-view-CZV350XG.js} +1 -1
- package/dist/client/assets/{oauth-callback-C7CG4TvZ.js → oauth-callback-CfmRg_0A.js} +1 -1
- package/dist/client/assets/{page-BBuPAnYW.js → page-CgDKBWsq.js} +1 -1
- package/dist/client/assets/{page-CmdabCF-.js → page-Dv3oR7oA.js} +1 -1
- package/dist/client/assets/{plugin-empty-state-BjravhmS.js → plugin-empty-state-BReduRlu.js} +1 -1
- package/dist/client/assets/{plugin-empty-state-DB5GFJQB.js → plugin-empty-state-DIEznBxY.js} +1 -1
- package/dist/client/assets/{plugin-header-D4-3EhvX.js → plugin-header-BxoyjVUE.js} +1 -1
- package/dist/client/assets/{plugin-header-BoBMp38h.js → plugin-header-DfwEpjUS.js} +1 -1
- package/dist/client/assets/{popover-VJKeuwbC.js → popover-BAxEdUnc.js} +1 -1
- package/dist/client/assets/{project-layout-B-2nzLyc.js → project-layout-BbukR4Wk.js} +1 -1
- package/dist/client/assets/{project-settings-Cv631PiB.js → project-settings-CPbKOYMT.js} +1 -1
- package/dist/client/assets/{projects-list-VqhVqmHW.js → projects-list-vAE-kMW-.js} +1 -1
- package/dist/client/assets/{readme-viewer-CYxESlX8.js → readme-viewer-a-OyYWiD.js} +1 -1
- package/dist/client/assets/{registry-layout-DSELVp8O.js → registry-layout-ljhRSRf0.js} +1 -1
- package/dist/client/assets/{registry-utils-BDP3t_m0.js → registry-utils-B-vEnp7V.js} +1 -1
- package/dist/client/assets/{reports-layout-chWgOVY4.js → reports-layout-BW9aOA_j.js} +1 -1
- package/dist/client/assets/{reset-password-BepKS7QP.js → reset-password-DHzE-PHg.js} +1 -1
- package/dist/client/assets/{resizable-DzVs9cF1.js → resizable-B-LtqXP7.js} +1 -1
- package/dist/client/assets/{save-actions-C432uq2M.js → save-actions-BzE06WE0.js} +1 -1
- package/dist/client/assets/{scroll-area-BppB61vI.js → scroll-area-BFpjaQ0Z.js} +1 -1
- package/dist/client/assets/{select-CjbCdlbs.js → select-RhE9YjyI.js} +1 -1
- package/dist/client/assets/{shell-layout-BNTceB-j.js → shell-layout-BcqBvgig.js} +3 -3
- package/dist/client/assets/{spinner-Ys0MZVWU.js → spinner-_rC9EVa-.js} +1 -1
- package/dist/client/assets/{store-invite-wi4-CXmp.js → store-invite-C6_aoRYc.js} +1 -1
- package/dist/client/assets/{switch-mZQ9VTrI.js → switch-DDYhCtLF.js} +1 -1
- package/dist/client/assets/{table-50O0LiWw.js → table-_ch5ZreO.js} +1 -1
- package/dist/client/assets/{tasks-Knr19XiW.js → tasks-T50v_FuI.js} +1 -1
- package/dist/client/assets/{textarea-CaReVd_T.js → textarea-DMg0QASM.js} +1 -1
- package/dist/client/assets/{time-range-picker-CmEKwRJx.js → time-range-picker--odqKeol.js} +1 -1
- package/dist/client/assets/{toggle-group-igEKa_l0.js → toggle-group-F2kH_XG3.js} +1 -1
- package/dist/client/assets/{tools-list-DXmYEuhW.js → tools-list-DVtkXKlT.js} +1 -1
- package/dist/client/assets/{tooltip-0WAr9Tnd.js → tooltip-DJtJQVyb.js} +1 -1
- package/dist/client/assets/{topbar-portal-A-r6dcXk.js → topbar-portal-D8XQac0n.js} +1 -1
- package/dist/client/assets/{typewriter-title-0Ps8bNiF.js → typewriter-title-BV0w42ZY.js} +1 -1
- package/dist/client/assets/{use-binding-DHUPD73-.js → use-binding-Dhp8gek5.js} +1 -1
- package/dist/client/assets/{use-connection-h_6wlDvG.js → use-connection-DKKMhiye.js} +1 -1
- package/dist/client/assets/{use-copy-DzbutdJX.js → use-copy-BoeWTlCp.js} +1 -1
- package/dist/client/assets/{use-create-virtual-mcp-BEYGEKPm.js → use-create-virtual-mcp-qsfLujLC.js} +1 -1
- package/dist/client/assets/{use-deco-chat-open-QCitD2jP.js → use-deco-chat-open-794DEjbq.js} +1 -1
- package/dist/client/assets/{use-install-from-registry-CKNWgTjl.js → use-install-from-registry-CgNh3nC2.js} +1 -1
- package/dist/client/assets/{use-list-state-QuR-uYrt.js → use-list-state-DfiBe_-7.js} +1 -1
- package/dist/client/assets/{use-llm-BiV3ohz2.js → use-llm-D4M8og3H.js} +1 -1
- package/dist/client/assets/{use-mcp-prompts-BfBaVKeH.js → use-mcp-prompts-BD7tCF_J.js} +1 -1
- package/dist/client/assets/{use-mcp-tools-9-0ktUQU.js → use-mcp-tools-CruvlSzs.js} +1 -1
- package/dist/client/assets/{use-mobile-DBbPwq5K.js → use-mobile-BAZFYSo6.js} +1 -1
- package/dist/client/assets/{use-organization-settings-Di-WJ99L.js → use-organization-settings-BcYQXMAp.js} +1 -1
- package/dist/client/assets/{use-project-CQC3Fx2l.js → use-project-CnPDQWv2.js} +1 -1
- package/dist/client/assets/{use-view-mode-C4TZAKDl.js → use-view-mode-CYTOa6eI.js} +1 -1
- package/dist/client/assets/{use-virtual-mcp-B5taJWCy.js → use-virtual-mcp-B8Rn3cO8.js} +1 -1
- package/dist/client/assets/useInfiniteQuery-B9rccKQ_.js +1 -0
- package/dist/client/assets/{useMutation-Zw-bAGx2.js → useMutation-u4c8C_eX.js} +1 -1
- package/dist/client/assets/useQuery-C_EWSF-i.js +1 -0
- package/dist/client/assets/useSuspenseInfiniteQuery-DLq-AweJ.js +1 -0
- package/dist/client/assets/{workflow-BrwP_xN6.js → workflow-ySdJVZPl.js} +1 -1
- package/dist/client/index.html +1 -1
- package/dist/server/cli.js +265 -235
- package/dist/server/migrate.js +3 -3
- package/dist/server/server.js +238 -208
- package/package.json +2 -1
- package/dist/client/assets/constants-C6KVRSAR.js +0 -1
- package/dist/client/assets/useInfiniteQuery-CGBDp2t8.js +0 -1
- package/dist/client/assets/useQuery-eogqvd42.js +0 -1
- package/dist/client/assets/useSuspenseInfiniteQuery-DAyAVWU_.js +0 -1
package/dist/server/migrate.js
CHANGED
|
@@ -1467,8 +1467,8 @@ ${Y.stack}`;return Q}if(typeof Y==="object"&&Y!==null){let Q=Y,X="";if(typeof Q.
|
|
|
1467
1467
|
${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}
|
|
1468
1468
|
|
|
1469
1469
|
Stack trace:
|
|
1470
|
-
${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 yN(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=yN(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=yN(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 F=yN(Y,H);Z.resolve(F),F.dispose()}catch(F){let $=kN(F),V=Y.newString(`Promise resolution error: ${$}`);Z.reject(V),V.dispose()}finally{Y.runtime.executePendingJobs()}}).catch((H)=>{let F=kN(H),$=Y.newString(`Promise rejection: ${F}`);Z.reject($),$.dispose(),Y.runtime.executePendingJobs()}),Z.handle}return yN(Y,W)}catch(K){let W=kN(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 ky0=()=>{};function fy0(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 yy0(Y,Q,X){let J=Date.now(),G=Y.resolvePromise(Q);while(!0){fy0(Y);let K=await Promise.race([G,B24(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 iR({tools:Y,code:Q,timeoutMs:X}){let W=[];try{const J=ZI(W,await _y0({memoryLimitBytes:33554432,stackSizeBytes:524288}),0);const G=ZI(W,J.newContext({interruptAfterMs:X}),0);const K=ZI(W,Ry0(G),0);try{let $=G.evalCode(Q,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult($),B=yN(G,Y);G.setProp(G.global,"tools",B);let U=G.runtime.hasPendingJob()?G.unwrapResult(await yy0(G,V,X)):V;if(U!==V)V.dispose();let z=G.getProp(U,"default"),D=G.typeof(z);if(D!=="function")return z.dispose(),U.dispose(),B.dispose(),{error:`Code must export default a function (tools). Got ${D}. Example: export default async (tools) => { /* ... */ }`,consoleLogs:K.logs};let M=G.callFunction(z,G.undefined,B);B.dispose(),z.dispose(),U.dispose();let w=G.unwrapResult(M),P=await yy0(G,w,X);w.dispose();let j=G.unwrapResult(P);if(G.runtime.hasPendingJob())fy0(G);let T=G.dump(j);return j.dispose(),{returnValue:T,consoleLogs:K.logs}}catch($){return console.log($),{error:kN($),consoleLogs:K.logs}}}catch(Z){var H=Z,F=1}finally{kV1(W,H,F)}}var B24=(Y)=>new Promise((Q)=>setTimeout(Q,Y));var by0=S(()=>{vy0();ky0()});var oF1=S(()=>{by0()});async function U24(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 hy0(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 z24(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 D=(await U.proxy.listTools()).tools,M=X.get(B);if(M?.selectedTools&&M.selectedTools.length>0){let w=new Set(M.selectedTools);D=D.filter((P)=>w.has(P.name))}return{connectionId:B,connectionTitle:U.connection.title,tools:D}}catch(z){return console.error(`[code-execution] Failed to list tools for connection ${B}:`,z),null}})),Z=new Set,H=[],F=new Map;for(let B of W){if(B.status!=="fulfilled"||!B.value)continue;let{connectionId:U,connectionTitle:z,tools:D}=B.value;for(let M of D){if(Z.has(M.name))continue;Z.add(M.name),H.push({...M,_meta:{connectionId:U,connectionTitle:z}}),F.set(M.name,U)}}let $=async(B,U)=>{let z=F.get(B);if(!z)return{content:[{type:"text",text:`Tool not found: ${B}`}],isError:!0};let D=G.get(z);if(!D)return{content:[{type:"text",text:`Connection not found for tool: ${B}`}],isError:!0};return await D.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:$}}async function fN(Y){let Q=q0(Y),X;if(Y.connectionId){let J=await Y.storage.virtualMcps.findById(Y.connectionId,Y.organization?.id);if(J)X=await U24(J,Y);else X=await hy0(Q.id,Y)}else X=await hy0(Q.id,Y);return z24(X,Y)}function D24(Y){return Y.toLowerCase().split(/[\s_\-./]+/).filter((Q)=>Q.length>=2)}function O24(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 Gp(Y,Q,X){let J=D24(Y);if(J.length===0)return Q.slice(0,X);return Q.map((G)=>({tool:G,score:O24(J,G)})).filter((G)=>G.score>0).sort((G,K)=>K.score-G.score).slice(0,X).map((G)=>G.tool)}function Wp(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 Zp(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 iR({code:Y,tools:J,timeoutMs:X})}function aR(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}]}}function M$(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}],isError:!0}}function m3(Y){let Q=new Set(L24);return Y.filter((X)=>!Q.has(X.name))}var L24;var WU=S(()=>{oF1();L24=["CODE_EXECUTION_SEARCH_TOOLS","CODE_EXECUTION_DESCRIBE_TOOLS","CODE_EXECUTION_RUN_CODE"]});var sF1;var xy0=S(()=>{k0();nR();WU();sF1=v1({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:wy0,outputSchema:Ay0,handler:async(Y,Q)=>{o1(Q),q0(Q),await Q.access.check();let X=await fN(Q),J=Gp(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 tF1;var gy0=S(()=>{k0();nR();WU();tF1=v1({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:Py0,outputSchema:Ey0,handler:async(Y,Q)=>{o1(Q),q0(Q),await Q.access.check();let X=await fN(Q);return Wp(Y.tools,X.tools)}})});var eF1;var uy0=S(()=>{k0();nR();WU();eF1=v1({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:Ty0,outputSchema:Cy0,handler:async(Y,Q)=>{o1(Q),q0(Q),await Q.access.check();let X=await fN(Q);return await Zp(Y.code,X,Y.timeoutMs)}})});var my0=S(()=>{xy0();gy0();uy0();nR()});var M24,w24,Y$1;var ly0=S(()=>{jY();y1();k0();gm();L3();M24=q.object({data:PA.describe("Data for the new connection (id is auto-generated if not provided)")}),w24=q.object({item:E5.describe("The created connection entity")}),Y$1=v1({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:M24,outputSchema:w24,handler:async(Y,Q)=>{o1(Q);let X=q0(Q);await Q.access.check();let J=L9(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 H=LV(G.connection_url);if(!H)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let F=await Q.storage.virtualMcps.findById(H);if(!F)throw Error(`Virtual MCP not found: ${H}`);if(F.organization_id!==X.id)throw Error("Virtual MCP does not belong to the current organization");G.connection_url=NV(H)}let K=await cL({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?.length?K:null,Z=await Q.storage.connections.create({...G,tools:W});return await Q.eventBus.publish(X.id,g9.SELF(X.id),{type:"connection.created",data:Z}),{item:Z}}})});var A24,P24,dy0;var py0=S(()=>{y1();gX();A24=yZ.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")}),P24=fZ("assistant",A24),dy0=[...P24]});var rR,l3,ny0,E24,T24,iy0,C24,R24,I24,j24,S24,_24,ay0,v24,k24,y24,f24,b24,h24,x24,g24,u24,m24,kc8,l24,yc8,cy0,d24,p24,Q$1,fc8;var ry0=S(()=>{y1();_B();gX();rR=q.lazy(()=>q.union([q.null(),q.string(),q.number(),q.boolean(),q.record(q.string(),rR),q.array(rR)])),l3=q.record(q.string(),q.record(q.string(),rR)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),ny0=q.object({type:q.literal("text"),text:q.string().describe("The text content"),providerOptions:l3}),E24=q.object({type:q.literal("text"),text:q.string().describe("The text content"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),T24=q.string().describe("File data as URL string"),iy0=q.object({type:q.literal("file"),filename:q.string().optional().describe("Optional filename of the file"),data:T24,mediaType:q.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:l3}),C24=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")}),R24=q.object({type:q.literal("reasoning"),text:q.string().describe("The reasoning text"),providerOptions:l3}),I24=q.object({type:q.literal("reasoning"),text:q.string().describe("The reasoning text"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),j24=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:l3}),S24=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")}),_24=q.union([q.object({type:q.literal("text"),value:q.string()}),q.object({type:q.literal("json"),value:rR}),q.object({type:q.literal("error-text"),value:q.string()}),q.object({type:q.literal("error-json"),value:rR}),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)")]),ay0=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:_24.describe("Result of the tool call"),result:q.unknown().describe("Unknown result of the tool call"),providerOptions:l3}),v24=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")}),k24=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")})]),y24=q.object({role:q.literal("system"),content:q.string().describe("System message content"),providerOptions:l3}),f24=q.object({role:q.literal("user"),content:q.array(q.union([ny0,iy0])).describe("User message content parts (text or file)"),providerOptions:l3}),b24=q.object({role:q.literal("assistant"),content:q.array(q.union([ny0,iy0,R24,j24,ay0])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:l3}),h24=q.object({role:q.literal("tool"),content:q.array(ay0).describe("Tool message content (tool results)"),providerOptions:l3}),x24=q.union([y24,f24,b24,h24]),g24=q.array(x24).describe("A list of messages forming the prompt"),u24=q.object({prompt:g24.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")}),m24=q.object({content:q.array(q.union([E24,C24,I24,S24,v24,k24])).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")}),kc8=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")}),l24=q.object({supportedUrls:q.record(q.string(),q.array(q.string())).describe("Supported URL patterns by media type for the provider")}),yc8=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()}),cy0=q.object({modelId:q.string().describe("The ID of the model"),callOptions:u24}),d24=yZ.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()}),p24=fZ("llm",d24,{readOnly:!0}),Q$1=[{name:"LLM_METADATA",inputSchema:q.object({modelId:q.string().describe("The ID of the model")}),outputSchema:l24},{name:"LLM_DO_STREAM",inputSchema:cy0,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:cy0,outputSchema:m24},...p24],fc8=vZ(Q$1)});function bN(){return!1}function Kp(Y,Q){return Y===g9.DEV_ASSETS(Q)}function hN(Y,Q){let X=Kt(Q,Y),J=new Date().toISOString();return{id:X.id??g9.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:c24,bindings:["OBJECT_STORAGE"],status:"active"}}var c24;var Hp=S(()=>{rm();jY();y1();c24=bC.map((Y)=>({name:Y.name,description:`${Y.name} operation for local file storage`,inputSchema:q.toJSONSchema(Y.inputSchema),outputSchema:q.toJSONSchema(Y.outputSchema)}))});function i24(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 w$(Y){return typeof Y==="string"||typeof Y==="number"}function Fp(Y,Q){if("conditions"in Q){let{operator:Z,conditions:H}=Q;switch(Z){case"and":return H.every((F)=>Fp(Y,F));case"or":return H.some((F)=>Fp(Y,F));case"not":return!H.every((F)=>Fp(Y,F));default:return!0}}let{field:X,operator:J,value:G}=Q,K=X.join("."),W=X$1(Y,K);switch(J){case"eq":return W===G;case"gt":return w$(W)&&w$(G)&&W>G;case"gte":return w$(W)&&w$(G)&&W>=G;case"lt":return w$(W)&&w$(G)&&W<G;case"lte":return w$(W)&&w$(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=i24(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 X$1(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 a24(Y,Q){return[...Y].sort((X,J)=>{for(let G of Q){let K=G.field.join("."),W=X$1(X,K),Z=X$1(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 n24,r24,o24,J$1;var oy0=S(()=>{sm();py0();gX();ry0();rm();jY();y1();k0();Hp();L3();n24={LLM:Q$1,ASSISTANTS:dy0,OBJECT_STORAGE:bC};r24=mG.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.")}),o24=M3(E5),J$1=v1({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:r24,outputSchema:o24,handler:async(Y,Q)=>{await Q.access.check();let X=q0(Q),J=Y.binding?typeof Y.binding==="string"?(()=>{let B=n24[Y.binding.toUpperCase()];if(!B)throw Error(`Unknown binding: ${Y.binding}`);return B})():Y.binding:void 0,G=J?cm(J):void 0,K=await Q.storage.connections.list(X.id,{includeVirtual:Y.include_virtual??!1});if(bN()){let B=MG(),U=g9.DEV_ASSETS(X.id);if(!K.some((z)=>z.id===U)){let z=hN(X.id,B);K.unshift(z)}}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((z)=>({name:z.name,inputSchema:z.inputSchema,outputSchema:z.outputSchema})))?B:null})).then((B)=>B.filter((U)=>U!==null)):K;if(Y.where)W=W.filter((B)=>Fp(B,Y.where));if(Y.orderBy&&Y.orderBy.length>0)W=a24(W,Y.orderBy);let Z=W.length,H=Y.offset??0,F=Y.limit??100,$=W.slice(H,H+F),V=H+F<Z;return{items:$,totalCount:Z,hasMore:V}}})});var s24,G$1;var sy0=S(()=>{gX();k0();Hp();L3();s24=wC(E5),G$1=v1({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",annotations:{title:"Get Connection",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:MC,outputSchema:s24,handler:async(Y,Q)=>{let X=q0(Q);if(await Q.access.check(),bN()&&Kp(Y.id,X.id))return{item:hN(X.id,MG())};let J=await Q.storage.connections.findById(Y.id);if(!J||J.organization_id!==X.id)return{item:null};return{item:J}}})});var $p=(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 ty0(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 t24(Y){let Q=Y.split("::");if(Q.length!==2||!Q[0]||!Q[1])return null;return Q}function e24(Y){if(typeof Y==="object"&&Y!==null&&"value"in Y){let Q=Y.value;if(typeof Q==="string")return Q}return null}function W$1(Y,Q){let X={};if(!Y||!Q)return X;for(let J of Q){if(J==="*"){X["*"]=["*"];continue}let G=t24(J);if(!G)continue;let[K,W]=G,Z=$p(K,Y),H=e24(Z);if(H){if(!X[H])X[H]=[];X[H].push(W)}}return X}function ey0(Y,Q){let X=W$1(Y,Q);return new Set(Object.keys(X).filter((J)=>J!=="*"))}var Z$1=()=>{};import{randomBytes as YE4}from"crypto";function QE4(){if(oR)return oR;let Y=process.env.MESH_JWT_SECRET??YY.jwt?.secret??process.env.BETTER_AUTH_SECRET;if(Y)oR=new TextEncoder().encode(Y);else console.warn("MESH_JWT_SECRET not set - generating random secret (not persistent)"),oR=new Uint8Array(YE4(32));return oR}async function Yf0(Y,Q="5m"){let X=QE4();return await new zX(Y).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(Q).sign(X)}var oR=null;var Qf0=S(()=>{DX();Vp()});async function Xf0(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 sR{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=Y$("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 K$1=S(()=>{qC()});async function tR(Y,Q,X){let J=Y.id,G=W$1(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 Yf0({sub:K,user:{id:K},metadata:{state:Y.configuration_state??void 0,meshUrl:process.env.MESH_URL??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,F={...H?{"x-caller-id":H}:{},...Q.metadata.wellKnownForwardableHeaders??{},"x-request-id":Q.metadata.requestId},$=null,V=new sR(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 D=await Xf0(B);if(D.success&&D.accessToken)await V.upsert({connectionId:J,accessToken:D.accessToken,refreshToken:D.refreshToken??B.refreshToken,scope:D.scope??B.scope,expiresAt:D.expiresIn?new Date(Date.now()+D.expiresIn*1000):null,clientId:B.clientId,clientSecret:B.clientSecret,tokenEndpoint:B.tokenEndpoint}),$=D.accessToken,console.log(`[Proxy] Token refreshed for ${J}`);else await V.delete(J),console.error(`[Proxy] Token refresh failed for ${J}: ${D.error}`)}else await V.delete(J),console.log(`[Proxy] Token expired without refresh capability for ${J}`);else $=B.accessToken}if(!$&&Y.connection_token)$=Y.connection_token;if($)F.Authorization=`Bearer ${$}`;if(W)F["x-mesh-token"]=W;return F}var H$1=S(()=>{Z$1();Qf0();K$1()});function Jf0(){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 sX({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 Gf0=S(()=>{Az()});function Wf0(Y){let Q=new OC({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 Zf0=S(()=>{kZ1()});class eR{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 YI(Y,...Q){return Q.reduce((X,J)=>J(X),Y)}var Kf0="mcp.mesh";var Hf0,F$1,QI;var $$1=S(()=>{Hf0=class Hf0 extends Error{constructor(Y){super(Y);this.name="UnauthorizedError"}};F$1=class F$1 extends Error{constructor(Y){super(Y);this.name="ForbiddenError"}};QI=class QI{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 Hf0("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 F$1("No resources specified for access check");for(let X of Q)if(await this.checkResource(X)){this.grant();return}throw new F$1(`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[Kf0]?.public_tool;return X===!0||X==="true"}catch{return!1}}granted(){return this._granted}}});var XE4="mcp.mesh",xN;var Ff0=S(()=>{$$1();xN=class xN extends eR{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 QI(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[XE4]?.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 Vf0(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 q$1(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 B$1(Y,Q){if(!Y&&!Q)return;if(!Y)return Q;if(!Q)return Y;return{...Q,...Y}}function U$1(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 JE4(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:F}=await J.read();if(F)break;if(H){if(W+=H.byteLength,W>Q){K=!0;let $=Q-(W-H.byteLength);if($>0)Z.push(G.decode(H.slice(0,$),{stream:!0}));break}Z.push(G.decode(H,{stream:!0}))}}}finally{J.releaseLock()}return Z.push(G.decode()),{text:Z.join(""),truncated:K}}function GE4(Y){if(!Y)return;let Q=Y.trimEnd().split(`
|
|
1471
|
-
`);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 V$1(Y){let{ctx:Q,enabled:X}=Y,J=Y.organizationId??Q.organization?.id;if(!X||!J)return;if(OV(Y.connectionId))return;let G=q$1(Y.request.params.arguments),K=B$1(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((F)=>F.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 qf0(Y){let{ctx:Q,enabled:X,connectionId:J,connectionTitle:G,virtualMcpId:K}=Y;return async(W,Z)=>{let H=Date.now();try{let F=await Z(),$=Q.organization?.id;if(X&&$){let V=F.clone();(async()=>{try{let{text:B,truncated:U}=await JE4(V,$f0),z=Date.now()-H,D=V.headers.get("content-type")??"",M=B;if(D.includes("application/json"))try{M=B.length?JSON.parse(B):null}catch{M=B}let w=F.status>=400,P=w&&M&&typeof M==="object"&&"error"in M?M.error:void 0,j=typeof P==="string"&&P?P:w&&typeof M==="string"&&M.trim()?M.slice(0,500):w?`HTTP ${F.status} ${F.statusText}`.trim():U?`Response body truncated to ${$f0} bytes`:void 0,T=U$1(M),E=GE4(B);if(E)Object.assign(T,E);await V$1({ctx:Q,enabled:X,organizationId:$,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:T,isError:w,errorMessage:j,durationMs:z})}catch(B){let U=Date.now()-H;await V$1({ctx:Q,enabled:X,organizationId:$,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:{},isError:!0,errorMessage:`Failed to read streamable response body: ${B.message}`,durationMs:U})}})()}return F}catch(F){let $=F,V=Date.now()-H;throw await V$1({ctx:Q,enabled:X,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:{},isError:!0,errorMessage:$.message,durationMs:V}),F}}}var $f0=262144;var z$1=S(()=>{jY()});var gN;var Bf0=S(()=>{kh();z$1();gN=class gN extends eR{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,F=Date.now()-G;if(this.inflightRequests.delete(Y.id),K!=="tools/call"||!W)return;let $="error"in Y,V=$?Y.error:Y.result,B=$?{content:[{type:"text",text:Y.error?.message||"Unknown error"}],isError:!0}:V;if(X.meter.createHistogram("connection.proxy.duration").record(F,{"connection.id":J,"tool.name":W,status:$?"error":"success"}),$)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($&&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:F,isError:Boolean($)})}async logToDatabase(Y){let{ctx:Q,connectionId:X,connectionTitle:J,virtualMcpId:G}=this.options,{toolName:K,toolArguments:W,result:Z,duration:H,isError:F}=Y;if(!vh().enabled)return;let V=Q.organization?.id;if(!V)return;let B=Vf0(Z),U=U$1(Z),z=q$1(W),D=B$1(Q.metadata.properties,z);try{await Q.storage.monitoring.log({organizationId:V,connectionId:X,connectionTitle:J,toolName:K,input:W??{},output:U,isError:F,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:D})}catch(M){console.error("[MonitoringTransport] Failed to log to database:",M)}}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 Uf0=S(()=>{Ff0();Bf0()});async function zf0(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(!NW(K))throw Error("STDIO connection missing parameters");let W=Wf0({id:J,name:Y.title,command:K.command,args:K.args,env:K.envVars,cwd:K.cwd});return W=YI(W,(Z)=>new xN(Z,{ctx:Q,connection:Y,superUser:X}),(Z)=>new gN(Z,{ctx:Q,connectionId:J,connectionTitle:Y.title,virtualMcpId:G})),WE4(W,J)}case"HTTP":case"Websocket":{if(!Y.connection_url)throw Error(`${Y.connection_type} connection missing URL`);let K=await tR(Y,Q,X),W=Y.connection_headers;if(W&&"headers"in W)Object.assign(K,W.headers);let Z=new wH(new URL(Y.connection_url),{requestInit:{headers:K}});return Z=YI(Z,(H)=>new xN(H,{ctx:Q,connection:Y,superUser:X}),(H)=>new gN(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 tR(Y,Q,X),W=Y.connection_headers;if(W&&"headers"in W)Object.assign(K,W.headers);let Z=new IB(new URL(Y.connection_url),{requestInit:{headers:K}});return Z=YI(Z,(H)=>new xN(H,{ctx:Q,connection:Y,superUser:X}),(H)=>new gN(H,{ctx:Q,connectionId:J,connectionTitle:Y.title,virtualMcpId:G})),Q.getOrCreateClient(Z,J)}default:throw Error(`Unknown connection type: ${Y.connection_type}`)}}var WE4;var Df0=S(()=>{L3();bm();AA();H$1();Gf0();Zf0();Uf0();WE4=Jf0()});function Nf0(Y){if(!Y?._meta)return!1;return typeof Y._meta["mcp.mesh"]?.["tool.fn"]==="string"}function Mf0(Y){return Y._meta["mcp.mesh"]["tool.fn"]}var D$1,tn8,pZ,Of0,Lf0;var A$=S(()=>{y1();D$1=q.object({title:q.string().optional(),readOnlyHint:q.boolean().optional(),destructiveHint:q.boolean().optional(),idempotentHint:q.boolean().optional(),openWorldHint:q.boolean().optional()}),tn8=q.object({"tool.fn":q.string().describe("JavaScript ES module code that exports a default async function")}),pZ=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:D$1.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")}),Of0=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:D$1.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.")}),Lf0=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:D$1.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 qp(Y){return(Q)=>{if(Q instanceof w0&&Q.code===C0.MethodNotFound)return Y;throw Q}}var O$1=S(()=>{IY()});class wf0{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 Bp(Y){return new wf0(Y)}function ZE4(Y,Q,X){let J=new sX({name:`lazy-${Y.id}`,version:"1.0.0"},{capabilities:{}}),G=null;function K(){if(!G)G=mN(Y,Q,X).then((H)=>{if(Y.connection_type==="HTTP"||Y.connection_type==="SSE"||Y.connection_type==="Websocket")return N$1(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,F)=>{return(await K()).getPrompt(H,F)},J.readResource=async(H,F)=>{return(await K()).readResource(H,F)},J.callStreamableTool=async(H,F)=>{let $=await K();if("callStreamableTool"in $&&typeof $.callStreamableTool==="function")return $.callStreamableTool(H,F);let V=await $.callTool({name:H,arguments:F});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 KE4(Y,Q,X=!1){let J=new Map;for(let G of Y)J.set(G.id,ZE4(G,Q,X));return J}async function Af0(Y){let Q=[];for(let[,X]of Y)Q.push(X.close().catch(()=>{}));await Promise.all(Q)}var uN;var L$1=S(()=>{M$1();O$1();Az();oF1();A$();uN=class uN extends sX{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=KE4(this.options.connections,this.ctx,this.options.superUser),this._cachedTools=Bp(()=>this.loadToolsCache()),this._cachedResources=Bp(()=>this.loadCache("resources")),this._cachedPrompts=Bp(()=>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(($)=>$.tools),F=this._selectionMap.get(W);if(F?.selected_tools?.length){let $=new Set(F.selected_tools);H=H.filter((V)=>$.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,$=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:$,...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(qp({resources:[]})).then(($)=>$.resources):await W.listPrompts().catch(qp({prompts:[]})).then(($)=>$.prompts),H=this._selectionMap.get(K),F=Y==="resources"?"selected_resources":"selected_prompts";if(H?.[F]?.length){let $=new Set(H[F]);return{connectionId:K,data:Z.filter((V)=>$.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,F=this._connections.get(W)?.title??"";for(let $ of Z){let V=$.name??$.uri;if(G.has(V))continue;let B={...$,_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=Mf0(G),W={};for(let[Z,H]of X.mappings){if(H==="__VIRTUAL__")continue;let F=J.get(H);if(!F)continue;W[Z]=async($)=>{let V=await F.callTool({name:Z,arguments:$});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=`
|
|
1470
|
+
${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 yN(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=yN(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=yN(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 F=yN(Y,H);Z.resolve(F),F.dispose()}catch(F){let $=kN(F),V=Y.newString(`Promise resolution error: ${$}`);Z.reject(V),V.dispose()}finally{Y.runtime.executePendingJobs()}}).catch((H)=>{let F=kN(H),$=Y.newString(`Promise rejection: ${F}`);Z.reject($),$.dispose(),Y.runtime.executePendingJobs()}),Z.handle}return yN(Y,W)}catch(K){let W=kN(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 ky0=()=>{};function fy0(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 yy0(Y,Q,X){let J=Date.now(),G=Y.resolvePromise(Q);while(!0){fy0(Y);let K=await Promise.race([G,B24(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 iR({tools:Y,code:Q,timeoutMs:X}){let W=[];try{const J=ZI(W,await _y0({memoryLimitBytes:33554432,stackSizeBytes:524288}),0);const G=ZI(W,J.newContext({interruptAfterMs:X}),0);const K=ZI(W,Ry0(G),0);try{let $=G.evalCode(Q,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult($),B=yN(G,Y);G.setProp(G.global,"tools",B);let U=G.runtime.hasPendingJob()?G.unwrapResult(await yy0(G,V,X)):V;if(U!==V)V.dispose();let z=G.getProp(U,"default"),D=G.typeof(z);if(D!=="function")return z.dispose(),U.dispose(),B.dispose(),{error:`Code must export default a function (tools). Got ${D}. Example: export default async (tools) => { /* ... */ }`,consoleLogs:K.logs};let M=G.callFunction(z,G.undefined,B);B.dispose(),z.dispose(),U.dispose();let w=G.unwrapResult(M),P=await yy0(G,w,X);w.dispose();let j=G.unwrapResult(P);if(G.runtime.hasPendingJob())fy0(G);let T=G.dump(j);return j.dispose(),{returnValue:T,consoleLogs:K.logs}}catch($){return console.log($),{error:kN($),consoleLogs:K.logs}}}catch(Z){var H=Z,F=1}finally{kV1(W,H,F)}}var B24=(Y)=>new Promise((Q)=>setTimeout(Q,Y));var by0=S(()=>{vy0();ky0()});var oF1=S(()=>{by0()});async function U24(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 hy0(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 z24(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 D=(await U.proxy.listTools()).tools,M=X.get(B);if(M?.selectedTools&&M.selectedTools.length>0){let w=new Set(M.selectedTools);D=D.filter((P)=>w.has(P.name))}return{connectionId:B,connectionTitle:U.connection.title,tools:D}}catch(z){return console.error(`[code-execution] Failed to list tools for connection ${B}:`,z),null}})),Z=new Set,H=[],F=new Map;for(let B of W){if(B.status!=="fulfilled"||!B.value)continue;let{connectionId:U,connectionTitle:z,tools:D}=B.value;for(let M of D){if(Z.has(M.name))continue;Z.add(M.name),H.push({...M,_meta:{connectionId:U,connectionTitle:z}}),F.set(M.name,U)}}let $=async(B,U)=>{let z=F.get(B);if(!z)return{content:[{type:"text",text:`Tool not found: ${B}`}],isError:!0};let D=G.get(z);if(!D)return{content:[{type:"text",text:`Connection not found for tool: ${B}`}],isError:!0};return await D.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:$}}async function fN(Y){let Q=q0(Y),X;if(Y.connectionId){let J=await Y.storage.virtualMcps.findById(Y.connectionId,Y.organization?.id);if(J)X=await U24(J,Y);else X=await hy0(Q.id,Y)}else X=await hy0(Q.id,Y);return z24(X,Y)}function D24(Y){return Y.toLowerCase().split(/[\s_\-./]+/).filter((Q)=>Q.length>=2)}function O24(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 Gp(Y,Q,X){let J=D24(Y);if(J.length===0)return Q.slice(0,X);return Q.map((G)=>({tool:G,score:O24(J,G)})).filter((G)=>G.score>0).sort((G,K)=>K.score-G.score).slice(0,X).map((G)=>G.tool)}function Wp(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 Zp(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 iR({code:Y,tools:J,timeoutMs:X})}function aR(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}]}}function M$(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}],isError:!0}}function m3(Y){let Q=new Set(L24);return Y.filter((X)=>!Q.has(X.name))}var L24;var WU=S(()=>{oF1();L24=["CODE_EXECUTION_SEARCH_TOOLS","CODE_EXECUTION_DESCRIBE_TOOLS","CODE_EXECUTION_RUN_CODE"]});var sF1;var xy0=S(()=>{k0();nR();WU();sF1=v1({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:wy0,outputSchema:Ay0,handler:async(Y,Q)=>{o1(Q),q0(Q),await Q.access.check();let X=await fN(Q),J=Gp(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 tF1;var gy0=S(()=>{k0();nR();WU();tF1=v1({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:Py0,outputSchema:Ey0,handler:async(Y,Q)=>{o1(Q),q0(Q),await Q.access.check();let X=await fN(Q);return Wp(Y.tools,X.tools)}})});var eF1;var uy0=S(()=>{k0();nR();WU();eF1=v1({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:Ty0,outputSchema:Cy0,handler:async(Y,Q)=>{o1(Q),q0(Q),await Q.access.check();let X=await fN(Q);return await Zp(Y.code,X,Y.timeoutMs)}})});var my0=S(()=>{xy0();gy0();uy0();nR()});var M24,w24,Y$1;var ly0=S(()=>{jY();y1();k0();gm();L3();M24=q.object({data:PA.describe("Data for the new connection (id is auto-generated if not provided)")}),w24=q.object({item:E5.describe("The created connection entity")}),Y$1=v1({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:M24,outputSchema:w24,handler:async(Y,Q)=>{o1(Q);let X=q0(Q);await Q.access.check();let J=L9(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 H=LV(G.connection_url);if(!H)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let F=await Q.storage.virtualMcps.findById(H);if(!F)throw Error(`Virtual MCP not found: ${H}`);if(F.organization_id!==X.id)throw Error("Virtual MCP does not belong to the current organization");G.connection_url=NV(H)}let K=await cL({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?.length?K:null,Z=await Q.storage.connections.create({...G,tools:W});return await Q.eventBus.publish(X.id,g9.SELF(X.id),{type:"connection.created",data:Z}),{item:Z}}})});var A24,P24,dy0;var py0=S(()=>{y1();gX();A24=yZ.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")}),P24=fZ("assistant",A24),dy0=[...P24]});var rR,l3,ny0,E24,T24,iy0,C24,R24,I24,j24,S24,_24,ay0,v24,k24,y24,f24,b24,h24,x24,g24,u24,m24,yc8,l24,fc8,cy0,d24,p24,Q$1,bc8;var ry0=S(()=>{y1();_B();gX();rR=q.lazy(()=>q.union([q.null(),q.string(),q.number(),q.boolean(),q.record(q.string(),rR),q.array(rR)])),l3=q.record(q.string(),q.record(q.string(),rR)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),ny0=q.object({type:q.literal("text"),text:q.string().describe("The text content"),providerOptions:l3}),E24=q.object({type:q.literal("text"),text:q.string().describe("The text content"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),T24=q.string().describe("File data as URL string"),iy0=q.object({type:q.literal("file"),filename:q.string().optional().describe("Optional filename of the file"),data:T24,mediaType:q.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:l3}),C24=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")}),R24=q.object({type:q.literal("reasoning"),text:q.string().describe("The reasoning text"),providerOptions:l3}),I24=q.object({type:q.literal("reasoning"),text:q.string().describe("The reasoning text"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),j24=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:l3}),S24=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")}),_24=q.union([q.object({type:q.literal("text"),value:q.string()}),q.object({type:q.literal("json"),value:rR}),q.object({type:q.literal("error-text"),value:q.string()}),q.object({type:q.literal("error-json"),value:rR}),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)")]),ay0=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:_24.describe("Result of the tool call"),result:q.unknown().describe("Unknown result of the tool call"),providerOptions:l3}),v24=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")}),k24=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")})]),y24=q.object({role:q.literal("system"),content:q.string().describe("System message content"),providerOptions:l3}),f24=q.object({role:q.literal("user"),content:q.array(q.union([ny0,iy0])).describe("User message content parts (text or file)"),providerOptions:l3}),b24=q.object({role:q.literal("assistant"),content:q.array(q.union([ny0,iy0,R24,j24,ay0])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:l3}),h24=q.object({role:q.literal("tool"),content:q.array(ay0).describe("Tool message content (tool results)"),providerOptions:l3}),x24=q.union([y24,f24,b24,h24]),g24=q.array(x24).describe("A list of messages forming the prompt"),u24=q.object({prompt:g24.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")}),m24=q.object({content:q.array(q.union([E24,C24,I24,S24,v24,k24])).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")}),yc8=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")}),l24=q.object({supportedUrls:q.record(q.string(),q.array(q.string())).describe("Supported URL patterns by media type for the provider")}),fc8=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()}),cy0=q.object({modelId:q.string().describe("The ID of the model"),callOptions:u24}),d24=yZ.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()}),p24=fZ("llm",d24,{readOnly:!0}),Q$1=[{name:"LLM_METADATA",inputSchema:q.object({modelId:q.string().describe("The ID of the model")}),outputSchema:l24},{name:"LLM_DO_STREAM",inputSchema:cy0,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:cy0,outputSchema:m24},...p24],bc8=vZ(Q$1)});function bN(){return!1}function Kp(Y,Q){return Y===g9.DEV_ASSETS(Q)}function hN(Y,Q){let X=Kt(Q,Y),J=new Date().toISOString();return{id:X.id??g9.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:c24,bindings:["OBJECT_STORAGE"],status:"active"}}var c24;var Hp=S(()=>{rm();jY();y1();c24=bC.map((Y)=>({name:Y.name,description:`${Y.name} operation for local file storage`,inputSchema:q.toJSONSchema(Y.inputSchema),outputSchema:q.toJSONSchema(Y.outputSchema)}))});function i24(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 w$(Y){return typeof Y==="string"||typeof Y==="number"}function Fp(Y,Q){if("conditions"in Q){let{operator:Z,conditions:H}=Q;switch(Z){case"and":return H.every((F)=>Fp(Y,F));case"or":return H.some((F)=>Fp(Y,F));case"not":return!H.every((F)=>Fp(Y,F));default:return!0}}let{field:X,operator:J,value:G}=Q,K=X.join("."),W=X$1(Y,K);switch(J){case"eq":return W===G;case"gt":return w$(W)&&w$(G)&&W>G;case"gte":return w$(W)&&w$(G)&&W>=G;case"lt":return w$(W)&&w$(G)&&W<G;case"lte":return w$(W)&&w$(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=i24(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 X$1(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 a24(Y,Q){return[...Y].sort((X,J)=>{for(let G of Q){let K=G.field.join("."),W=X$1(X,K),Z=X$1(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 n24,r24,o24,J$1;var oy0=S(()=>{sm();py0();gX();ry0();rm();jY();y1();k0();Hp();L3();n24={LLM:Q$1,ASSISTANTS:dy0,OBJECT_STORAGE:bC};r24=mG.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.")}),o24=M3(E5),J$1=v1({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:r24,outputSchema:o24,handler:async(Y,Q)=>{await Q.access.check();let X=q0(Q),J=Y.binding?typeof Y.binding==="string"?(()=>{let B=n24[Y.binding.toUpperCase()];if(!B)throw Error(`Unknown binding: ${Y.binding}`);return B})():Y.binding:void 0,G=J?cm(J):void 0,K=await Q.storage.connections.list(X.id,{includeVirtual:Y.include_virtual??!1});if(bN()){let B=MG(),U=g9.DEV_ASSETS(X.id);if(!K.some((z)=>z.id===U)){let z=hN(X.id,B);K.unshift(z)}}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((z)=>({name:z.name,inputSchema:z.inputSchema,outputSchema:z.outputSchema})))?B:null})).then((B)=>B.filter((U)=>U!==null)):K;if(Y.where)W=W.filter((B)=>Fp(B,Y.where));if(Y.orderBy&&Y.orderBy.length>0)W=a24(W,Y.orderBy);let Z=W.length,H=Y.offset??0,F=Y.limit??100,$=W.slice(H,H+F),V=H+F<Z;return{items:$,totalCount:Z,hasMore:V}}})});var s24,G$1;var sy0=S(()=>{gX();k0();Hp();L3();s24=wC(E5),G$1=v1({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",annotations:{title:"Get Connection",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:MC,outputSchema:s24,handler:async(Y,Q)=>{let X=q0(Q);if(await Q.access.check(),bN()&&Kp(Y.id,X.id))return{item:hN(X.id,MG())};let J=await Q.storage.connections.findById(Y.id);if(!J||J.organization_id!==X.id)return{item:null};return{item:J}}})});var $p=(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 ty0(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 t24(Y){let Q=Y.split("::");if(Q.length!==2||!Q[0]||!Q[1])return null;return Q}function e24(Y){if(typeof Y==="object"&&Y!==null&&"value"in Y){let Q=Y.value;if(typeof Q==="string")return Q}return null}function W$1(Y,Q){let X={};if(!Y||!Q)return X;for(let J of Q){if(J==="*"){X["*"]=["*"];continue}let G=t24(J);if(!G)continue;let[K,W]=G,Z=$p(K,Y),H=e24(Z);if(H){if(!X[H])X[H]=[];X[H].push(W)}}return X}function ey0(Y,Q){let X=W$1(Y,Q);return new Set(Object.keys(X).filter((J)=>J!=="*"))}var Z$1=()=>{};import{randomBytes as YE4}from"crypto";function QE4(){if(oR)return oR;let Y=process.env.MESH_JWT_SECRET??YY.jwt?.secret??process.env.BETTER_AUTH_SECRET;if(Y)oR=new TextEncoder().encode(Y);else console.warn("MESH_JWT_SECRET not set - generating random secret (not persistent)"),oR=new Uint8Array(YE4(32));return oR}async function Yf0(Y,Q="5m"){let X=QE4();return await new zX(Y).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(Q).sign(X)}var oR=null;var Qf0=S(()=>{DX();Vp()});async function Xf0(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 sR{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=Y$("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 K$1=S(()=>{qC()});async function tR(Y,Q,X){let J=Y.id,G=W$1(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 Yf0({sub:K,user:{id:K},metadata:{state:Y.configuration_state??void 0,meshUrl:process.env.MESH_URL??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,F={...H?{"x-caller-id":H}:{},...Q.metadata.wellKnownForwardableHeaders??{},"x-request-id":Q.metadata.requestId},$=null,V=new sR(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 D=await Xf0(B);if(D.success&&D.accessToken)await V.upsert({connectionId:J,accessToken:D.accessToken,refreshToken:D.refreshToken??B.refreshToken,scope:D.scope??B.scope,expiresAt:D.expiresIn?new Date(Date.now()+D.expiresIn*1000):null,clientId:B.clientId,clientSecret:B.clientSecret,tokenEndpoint:B.tokenEndpoint}),$=D.accessToken,console.log(`[Proxy] Token refreshed for ${J}`);else await V.delete(J),console.error(`[Proxy] Token refresh failed for ${J}: ${D.error}`)}else await V.delete(J),console.log(`[Proxy] Token expired without refresh capability for ${J}`);else $=B.accessToken}if(!$&&Y.connection_token)$=Y.connection_token;if($)F.Authorization=`Bearer ${$}`;if(W)F["x-mesh-token"]=W;return F}var H$1=S(()=>{Z$1();Qf0();K$1()});function Jf0(){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 sX({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 Gf0=S(()=>{Az()});function Wf0(Y){let Q=new OC({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 Zf0=S(()=>{kZ1()});class eR{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 YI(Y,...Q){return Q.reduce((X,J)=>J(X),Y)}var Kf0="mcp.mesh";var Hf0,F$1,QI;var $$1=S(()=>{Hf0=class Hf0 extends Error{constructor(Y){super(Y);this.name="UnauthorizedError"}};F$1=class F$1 extends Error{constructor(Y){super(Y);this.name="ForbiddenError"}};QI=class QI{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 Hf0("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 F$1("No resources specified for access check");for(let X of Q)if(await this.checkResource(X)){this.grant();return}throw new F$1(`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[Kf0]?.public_tool;return X===!0||X==="true"}catch{return!1}}granted(){return this._granted}}});var XE4="mcp.mesh",xN;var Ff0=S(()=>{$$1();xN=class xN extends eR{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 QI(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[XE4]?.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 Vf0(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 q$1(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 B$1(Y,Q){if(!Y&&!Q)return;if(!Y)return Q;if(!Q)return Y;return{...Q,...Y}}function U$1(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 JE4(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:F}=await J.read();if(F)break;if(H){if(W+=H.byteLength,W>Q){K=!0;let $=Q-(W-H.byteLength);if($>0)Z.push(G.decode(H.slice(0,$),{stream:!0}));break}Z.push(G.decode(H,{stream:!0}))}}}finally{J.releaseLock()}return Z.push(G.decode()),{text:Z.join(""),truncated:K}}function GE4(Y){if(!Y)return;let Q=Y.trimEnd().split(`
|
|
1471
|
+
`);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 V$1(Y){let{ctx:Q,enabled:X}=Y,J=Y.organizationId??Q.organization?.id;if(!X||!J)return;if(OV(Y.connectionId))return;let G=q$1(Y.request.params.arguments),K=B$1(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((F)=>F.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 qf0(Y){let{ctx:Q,enabled:X,connectionId:J,connectionTitle:G,virtualMcpId:K}=Y;return async(W,Z)=>{let H=Date.now();try{let F=await Z(),$=Q.organization?.id;if(X&&$){let V=F.clone();(async()=>{try{let{text:B,truncated:U}=await JE4(V,$f0),z=Date.now()-H,D=V.headers.get("content-type")??"",M=B;if(D.includes("application/json"))try{M=B.length?JSON.parse(B):null}catch{M=B}let w=F.status>=400,P=w&&M&&typeof M==="object"&&"error"in M?M.error:void 0,j=typeof P==="string"&&P?P:w&&typeof M==="string"&&M.trim()?M.slice(0,500):w?`HTTP ${F.status} ${F.statusText}`.trim():U?`Response body truncated to ${$f0} bytes`:void 0,T=U$1(M),E=GE4(B);if(E)Object.assign(T,E);await V$1({ctx:Q,enabled:X,organizationId:$,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:T,isError:w,errorMessage:j,durationMs:z})}catch(B){let U=Date.now()-H;await V$1({ctx:Q,enabled:X,organizationId:$,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:{},isError:!0,errorMessage:`Failed to read streamable response body: ${B.message}`,durationMs:U})}})()}return F}catch(F){let $=F,V=Date.now()-H;throw await V$1({ctx:Q,enabled:X,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:{},isError:!0,errorMessage:$.message,durationMs:V}),F}}}var $f0=262144;var z$1=S(()=>{jY()});var gN;var Bf0=S(()=>{kh();z$1();gN=class gN extends eR{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,F=Date.now()-G;if(this.inflightRequests.delete(Y.id),K!=="tools/call"||!W)return;let $="error"in Y,V=$?Y.error:Y.result,B=$?{content:[{type:"text",text:Y.error?.message||"Unknown error"}],isError:!0}:V;if(X.meter.createHistogram("connection.proxy.duration").record(F,{"connection.id":J,"tool.name":W,status:$?"error":"success"}),$)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($&&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:F,isError:Boolean($)})}async logToDatabase(Y){let{ctx:Q,connectionId:X,connectionTitle:J,virtualMcpId:G}=this.options,{toolName:K,toolArguments:W,result:Z,duration:H,isError:F}=Y;if(!vh().enabled)return;let V=Q.organization?.id;if(!V)return;let B=Vf0(Z),U=U$1(Z),z=q$1(W),D=B$1(Q.metadata.properties,z);try{await Q.storage.monitoring.log({organizationId:V,connectionId:X,connectionTitle:J,toolName:K,input:W??{},output:U,isError:F,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:D})}catch(M){console.error("[MonitoringTransport] Failed to log to database:",M)}}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 Uf0=S(()=>{Ff0();Bf0()});async function zf0(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(!NW(K))throw Error("STDIO connection missing parameters");let W=Wf0({id:J,name:Y.title,command:K.command,args:K.args,env:K.envVars,cwd:K.cwd});return W=YI(W,(Z)=>new xN(Z,{ctx:Q,connection:Y,superUser:X}),(Z)=>new gN(Z,{ctx:Q,connectionId:J,connectionTitle:Y.title,virtualMcpId:G})),WE4(W,J)}case"HTTP":case"Websocket":{if(!Y.connection_url)throw Error(`${Y.connection_type} connection missing URL`);let K=await tR(Y,Q,X),W=Y.connection_headers;if(W&&"headers"in W)Object.assign(K,W.headers);let Z=new wH(new URL(Y.connection_url),{requestInit:{headers:K}});return Z=YI(Z,(H)=>new xN(H,{ctx:Q,connection:Y,superUser:X}),(H)=>new gN(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 tR(Y,Q,X),W=Y.connection_headers;if(W&&"headers"in W)Object.assign(K,W.headers);let Z=new IB(new URL(Y.connection_url),{requestInit:{headers:K}});return Z=YI(Z,(H)=>new xN(H,{ctx:Q,connection:Y,superUser:X}),(H)=>new gN(H,{ctx:Q,connectionId:J,connectionTitle:Y.title,virtualMcpId:G})),Q.getOrCreateClient(Z,J)}default:throw Error(`Unknown connection type: ${Y.connection_type}`)}}var WE4;var Df0=S(()=>{L3();bm();AA();H$1();Gf0();Zf0();Uf0();WE4=Jf0()});function Nf0(Y){if(!Y?._meta)return!1;return typeof Y._meta["mcp.mesh"]?.["tool.fn"]==="string"}function Mf0(Y){return Y._meta["mcp.mesh"]["tool.fn"]}var D$1,en8,pZ,Of0,Lf0;var A$=S(()=>{y1();D$1=q.object({title:q.string().optional(),readOnlyHint:q.boolean().optional(),destructiveHint:q.boolean().optional(),idempotentHint:q.boolean().optional(),openWorldHint:q.boolean().optional()}),en8=q.object({"tool.fn":q.string().describe("JavaScript ES module code that exports a default async function")}),pZ=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:D$1.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")}),Of0=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:D$1.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.")}),Lf0=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:D$1.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 qp(Y){return(Q)=>{if(Q instanceof w0&&Q.code===C0.MethodNotFound)return Y;throw Q}}var O$1=S(()=>{IY()});class wf0{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 Bp(Y){return new wf0(Y)}function ZE4(Y,Q,X){let J=new sX({name:`lazy-${Y.id}`,version:"1.0.0"},{capabilities:{}}),G=null;function K(){if(!G)G=mN(Y,Q,X).then((H)=>{if(Y.connection_type==="HTTP"||Y.connection_type==="SSE"||Y.connection_type==="Websocket")return N$1(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,F)=>{return(await K()).getPrompt(H,F)},J.readResource=async(H,F)=>{return(await K()).readResource(H,F)},J.callStreamableTool=async(H,F)=>{let $=await K();if("callStreamableTool"in $&&typeof $.callStreamableTool==="function")return $.callStreamableTool(H,F);let V=await $.callTool({name:H,arguments:F});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 KE4(Y,Q,X=!1){let J=new Map;for(let G of Y)J.set(G.id,ZE4(G,Q,X));return J}async function Af0(Y){let Q=[];for(let[,X]of Y)Q.push(X.close().catch(()=>{}));await Promise.all(Q)}var uN;var L$1=S(()=>{M$1();O$1();Az();oF1();A$();uN=class uN extends sX{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=KE4(this.options.connections,this.ctx,this.options.superUser),this._cachedTools=Bp(()=>this.loadToolsCache()),this._cachedResources=Bp(()=>this.loadCache("resources")),this._cachedPrompts=Bp(()=>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(($)=>$.tools),F=this._selectionMap.get(W);if(F?.selected_tools?.length){let $=new Set(F.selected_tools);H=H.filter((V)=>$.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,$=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:$,...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(qp({resources:[]})).then(($)=>$.resources):await W.listPrompts().catch(qp({prompts:[]})).then(($)=>$.prompts),H=this._selectionMap.get(K),F=Y==="resources"?"selected_resources":"selected_prompts";if(H?.[F]?.length){let $=new Set(H[F]);return{connectionId:K,data:Z.filter((V)=>$.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,F=this._connections.get(W)?.title??"";for(let $ of Z){let V=$.name??$.uri;if(G.has(V))continue;let B={...$,_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=Mf0(G),W={};for(let[Z,H]of X.mappings){if(H==="__VIRTUAL__")continue;let F=J.get(H);if(!F)continue;W[Z]=async($)=>{let V=await F.callTool({name:Z,arguments:$});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=`
|
|
1472
1472
|
const __virtualToolFn = ${K.replace(/^\s*export\s+default\s+/,"").trim()};
|
|
1473
1473
|
export default async (tools) => {
|
|
1474
1474
|
const args = ${JSON.stringify(Q)};
|
|
@@ -1514,4 +1514,4 @@ ${Q.stack}`;return G}}catch{}if(typeof Q.toString==="function")try{let G=Q.toStr
|
|
|
1514
1514
|
`.execute(Y),J=new Set(X.rows.map((W)=>`${W.plugin_id}/${W.name}`)),G=new Map;for(let{pluginId:W,migration:Z}of Q){if(!G.has(W))G.set(W,[]);G.get(W).push({name:Z.name,up:Z.up})}let K=0;for(let[W,Z]of G){Z.sort((H,F)=>H.name.localeCompare(F.name));for(let H of Z){let F=`${W}/${H.name}`;if(J.has(F))continue;if(K===0)console.log("\uD83D\uDD0C Running plugin migrations...");K++,console.log(` Running: ${F}`),await H.up(Y);let $=new Date().toISOString();await p3`
|
|
1515
1515
|
INSERT INTO plugin_migrations (plugin_id, name, timestamp)
|
|
1516
1516
|
VALUES (${W}, ${H.name}, ${$})
|
|
1517
|
-
`.execute(Y)}}if(K>0)console.log(`\u2705 ${K} plugin migration(s) completed`)}async function aT4(Y,Q){await cT4(Y,Q),await nT4(Y,Q);let X=new Th0({db:Y,provider:{getMigrations:()=>Promise.resolve(wk)}}),{error:J,results:G}=await X.migrateToLatest();if(G?.forEach((K)=>{if(K.status==="Success")console.log(`\u2705 Migration "${K.migrationName}" executed successfully`);else if(K.status==="Error")console.error(`\u274C Failed to execute migration "${K.migrationName}"`)}),J)throw console.error("Failed to migrate"),console.error(J),J}async function rT4(Y){let{keepOpen:Q=!1,database:X,skipBetterAuth:J=!1,seed:G}=Y??{};if(!J&&!X)await Eh0();let K=X??HC(),W=async()=>{if(!Q&&!X)console.log("\uD83D\uDD12 Closing database connection..."),await YM0(K).catch((Z)=>{console.warn("Warning: Error closing database:",Z)})};try{console.log("\uD83D\uDCCA Running Kysely migrations..."),await aT4(K.db,K.type),console.log("\uD83C\uDF89 Core migrations completed successfully"),await iT4(K.db);let Z;if(G)Z=await Dw1(K.db,G);return await W(),{seedResult:Z}}catch(Z){throw await W(),Z}}async function
|
|
1517
|
+
`.execute(Y)}}if(K>0)console.log(`\u2705 ${K} plugin migration(s) completed`)}async function aT4(Y,Q){await cT4(Y,Q),await nT4(Y,Q);let X=new Th0({db:Y,provider:{getMigrations:()=>Promise.resolve(wk)}}),{error:J,results:G}=await X.migrateToLatest();if(G?.forEach((K)=>{if(K.status==="Success")console.log(`\u2705 Migration "${K.migrationName}" executed successfully`);else if(K.status==="Error")console.error(`\u274C Failed to execute migration "${K.migrationName}"`)}),J)throw console.error("Failed to migrate"),console.error(J),J}async function rT4(Y){let{keepOpen:Q=!1,database:X,skipBetterAuth:J=!1,seed:G}=Y??{};if(!J&&!X)await Eh0();let K=X??HC(),W=async()=>{if(!Q&&!X)console.log("\uD83D\uDD12 Closing database connection..."),await YM0(K).catch((Z)=>{console.warn("Warning: Error closing database:",Z)})};try{console.log("\uD83D\uDCCA Running Kysely migrations..."),await aT4(K.db,K.type),console.log("\uD83C\uDF89 Core migrations completed successfully"),await iT4(K.db);let Z;if(G)Z=await Dw1(K.db,G);return await W(),{seedResult:Z}}catch(Z){throw await W(),Z}}async function y09(){let Y=HC(),Q=new Th0({db:Y.db,provider:{getMigrations:()=>Promise.resolve(wk)}}),{error:X,results:J}=await Q.migrateDown();if(J?.forEach((G)=>{if(G.status==="Success")console.log(`\u2705 Migration "${G.migrationName}" rolled back successfully`);else if(G.status==="Error")console.error(`\u274C Failed to rollback migration "${G.migrationName}"`)}),X)throw console.error("Failed to rollback migration"),console.error(X),X}if(import.meta.main)console.log("\uD83D\uDE80 Migration script starting..."),console.log("\uD83D\uDCE6 Imported migrateToLatest function"),(async()=>{console.log("\uD83C\uDFC3 Executing migration function...");try{await rT4(),console.log("\u2705 All migrations completed. Exiting..."),process.exit(0)}catch(Y){console.error("\u274C Migration failed:",Y),process.exit(1)}})();export{Dw1 as runSeed,aT4 as runKyselyMigrations,rT4 as migrateToLatest,y09 as migrateDown};
|