@decocms/mesh 2.29.1 → 2.29.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/assets/{AlertCircle-B2wU6D_n.js → AlertCircle-BjDAjYli.js} +1 -1
- package/dist/client/assets/{ArrowLeft-NyHGzvbe.js → ArrowLeft-C3b0kZkv.js} +1 -1
- package/dist/client/assets/{ArrowUp-C6Sqn9AG.js → ArrowUp-UuyzMrp7.js} +1 -1
- package/dist/client/assets/{Check-D3xuSVGj.js → Check-BBlt8nj4.js} +1 -1
- package/dist/client/assets/{ChevronDown-C-3EfjEP.js → ChevronDown-C2nnNiko.js} +1 -1
- package/dist/client/assets/{Code01-DfyMLaC-.js → Code01-BkX8PbNA.js} +1 -1
- package/dist/client/assets/{Copy01-Dc1RdJpq.js → Copy01-eVnag3mk.js} +1 -1
- package/dist/client/assets/{DotsHorizontal-B2UMMt8A.js → DotsHorizontal-D8Oa-FB4.js} +1 -1
- package/dist/client/assets/{DotsVertical-DvDijuvP.js → DotsVertical-Cl1hRwhg.js} +1 -1
- package/dist/client/assets/{Download01-CkMxNb0B.js → Download01-BW7f1rv9.js} +1 -1
- package/dist/client/assets/{Edit01-L4Nnr0QQ.js → Edit01-C2f_e3xp.js} +1 -1
- package/dist/client/assets/{File06-CBX_wyuh.js → File06-D5XMLdKt.js} +1 -1
- package/dist/client/assets/{FilterLines-CDH3HxTZ.js → FilterLines-ZY2ZET-V.js} +1 -1
- package/dist/client/assets/{FlipBackward-BEzqS8y7.js → FlipBackward-BX_e7PV2.js} +1 -1
- package/dist/client/assets/{GitBranch01-XjgV7Utb.js → GitBranch01-BBkuZ0g6.js} +1 -1
- package/dist/client/assets/{Grid01-Bdr8TdFN.js → Grid01-uChhmLMS.js} +1 -1
- package/dist/client/assets/{Home02-DCkHxmzr.js → Home02-C3AGNyGt.js} +1 -1
- package/dist/client/assets/{Image01-Cz2WeHIZ.js → Image01-Ca9fCk1g.js} +1 -1
- package/dist/client/assets/{Inbox01-Bl63CjOF.js → Inbox01-7yaEdhih.js} +1 -1
- package/dist/client/assets/{InfoCircle-nAODGDfn.js → InfoCircle-ZFVXEe-o.js} +1 -1
- package/dist/client/assets/{Key01-CohHKaNI.js → Key01-BVzZzDXG.js} +1 -1
- package/dist/client/assets/{LinkExternal01-BVGqLQdf.js → LinkExternal01-DYbIdjWG.js} +1 -1
- package/dist/client/assets/{List-BiMBtc9h.js → List-DTNJ5e_Z.js} +1 -1
- package/dist/client/assets/{Loading01-BGMvClGA.js → Loading01-CVbOjnPi.js} +1 -1
- package/dist/client/assets/{Lock01-DkDYnCig.js → Lock01-Irv7dEl1.js} +1 -1
- package/dist/client/assets/{Play-D6WkVhCH.js → Play-el8E8avm.js} +1 -1
- package/dist/client/assets/{Plus-DOLhHKPS.js → Plus-jsBXu2Jm.js} +1 -1
- package/dist/client/assets/{SearchMd-wW0y4rSg.js → SearchMd-CDx95UHX.js} +1 -1
- package/dist/client/assets/{Terminal-wdncdOY3.js → Terminal-C4vz1dQ0.js} +1 -1
- package/dist/client/assets/{Trash01-uBQo4R5K.js → Trash01-hrLLpuYX.js} +1 -1
- package/dist/client/assets/{Upload01-DrOTJQud.js → Upload01-CdFUIAAb.js} +1 -1
- package/dist/client/assets/{X-BsuyfM7l.js → X-Bp6jT_CT.js} +1 -1
- package/dist/client/assets/{XClose-D2cxj93b.js → XClose-ChfIwjbU.js} +1 -1
- package/dist/client/assets/{agent-detail-VQXvW-QJ.js → agent-detail-BvL0RN-C.js} +1 -1
- package/dist/client/assets/{agents-D6fLoeau.js → agents-CDU0paf2.js} +1 -1
- package/dist/client/assets/{alert-dialog-njkM7m-D.js → alert-dialog-5F29h7ch.js} +1 -1
- package/dist/client/assets/{auth-catchall-BgrOMedF.js → auth-catchall-BnUTAkiU.js} +1 -1
- package/dist/client/assets/{avatar-DN0XBse5.js → avatar-_fJCi1jf.js} +1 -1
- package/dist/client/assets/{badge-C4NA8Y3o.js → badge-DIpSEo79.js} +1 -1
- package/dist/client/assets/{binder-Kl7aT5vq.js → binder-QE3BUq_4.js} +1 -1
- package/dist/client/assets/{button-BvR2W8G4.js → button-BID2CMhP.js} +1 -1
- package/dist/client/assets/{card-COq6R1Ol.js → card-6juGo41K.js} +1 -1
- package/dist/client/assets/{checkbox-eVOKaait.js → checkbox-BR6ZWQcp.js} +1 -1
- package/dist/client/assets/{collection-detail-BIHW3g46.js → collection-detail-DdU0S4bC.js} +1 -1
- package/dist/client/assets/{collection-display-button-BCRnx64a.js → collection-display-button-CES97i9G.js} +1 -1
- package/dist/client/assets/{collection-header-BfyNoDrz.js → collection-header-C2jCnQ0V.js} +1 -1
- package/dist/client/assets/{collection-page-DGdU_exK.js → collection-page-DQBRHwuf.js} +1 -1
- package/dist/client/assets/{collection-search-DqgXXQWv.js → collection-search-CYQ70Hoa.js} +1 -1
- package/dist/client/assets/{collection-tab-WUfWVMgI.js → collection-tab-5E9Q1B_9.js} +1 -1
- package/dist/client/assets/{collection-table-wrapper-bSjbJgfa.js → collection-table-wrapper-CVkp-9hJ.js} +1 -1
- package/dist/client/assets/{connection-sopQjWTN.js → connection-CzagOXhI.js} +1 -1
- package/dist/client/assets/{connection-card-D5GbzeyC.js → connection-card-De1P7KUX.js} +1 -1
- package/dist/client/assets/{connection-detail-DzUcsbPz.js → connection-detail-C6yPmWnc.js} +1 -1
- package/dist/client/assets/{connections-DmmC3rw3.js → connections-JU4CGCz5.js} +1 -1
- package/dist/client/assets/constants-VQyKSexs.js +1 -0
- package/dist/client/assets/{create-organization-dialog-nASMtJST.js → create-organization-dialog-DjIYezTr.js} +1 -1
- package/dist/client/assets/{dialog-B904z6ZY.js → dialog-N6lD2G23.js} +1 -1
- package/dist/client/assets/{dropdown-menu-BnIr5Jx8.js → dropdown-menu-CZuHPcK3.js} +1 -1
- package/dist/client/assets/{dynamic-plugin-layout-DahJzuQA.js → dynamic-plugin-layout-D2QU16mz.js} +1 -1
- package/dist/client/assets/{empty-state-CVynnCY5.js → empty-state-B2MmEXSc.js} +1 -1
- package/dist/client/assets/{empty-state-Dw5rHePk.js → empty-state-aph8hymo.js} +1 -1
- package/dist/client/assets/{env-vars-editor-C4fVY6WB.js → env-vars-editor-Bw5ArpUL.js} +1 -1
- package/dist/client/assets/{error-boundary-BQAARcQ8.js → error-boundary-BSc3aikh.js} +1 -1
- package/dist/client/assets/{extract-connection-data-BOG_2a3a.js → extract-connection-data-DsBhcJbM.js} +1 -1
- package/dist/client/assets/{file-browser-DW8BOHM2.js → file-browser-C7oCWAQD.js} +2 -2
- package/dist/client/assets/{form-SKjUzorv.js → form-R15NVDAL.js} +1 -1
- package/dist/client/assets/{grid-view-CEUpbNrR.js → grid-view-CW_NhGu9.js} +1 -1
- package/dist/client/assets/{home-Cqfqey-F.js → home-QfrULyzV.js} +1 -1
- package/dist/client/assets/{index-sI-UsvfH.js → index-BfX1PMhV.js} +1 -1
- package/dist/client/assets/{index-DEnww9gD.js → index-C0cxXUhv.js} +2 -2
- package/dist/client/assets/{index-BGkDS5MK.js → index-DJuj6s5W.js} +1 -1
- package/dist/client/assets/{index-DSRGhYN3.js → index-kNWs-Kaj.js} +1 -1
- package/dist/client/assets/{index-D4KRNGOL.js → index-wl-vFw7b.js} +1 -1
- package/dist/client/assets/{infiniteQueryObserver-CGYWk_ac.js → infiniteQueryObserver-CzQcKMvF.js} +1 -1
- package/dist/client/assets/{input-DgTGe31P.js → input-DHdPZHvh.js} +1 -1
- package/dist/client/assets/{layout-BIa7Ww4X.js → layout-DVqtFrGe.js} +1 -1
- package/dist/client/assets/{localstorage-keys-D17OGozQ.js → localstorage-keys-CySryjw_.js} +1 -1
- package/dist/client/assets/{login-B5xXqMPx.js → login-DK-wLmSi.js} +1 -1
- package/dist/client/assets/{mcp-oauth-dZd55Tzg.js → mcp-oauth-C_uVzdje.js} +1 -1
- package/dist/client/assets/{mcp-server-card-DJM3hj-p.js → mcp-server-card-utdZ5S32.js} +1 -1
- package/dist/client/assets/{mcp-server-detail-DLyr08JI.js → mcp-server-detail-MhY6fdyG.js} +1 -1
- package/dist/client/assets/{members-CyhMUe46.js → members-BM4vbqXY.js} +1 -1
- package/dist/client/assets/{monaco-editor-DqozmIOD.js → monaco-editor-Bvv8L85C.js} +1 -1
- package/dist/client/assets/{monitoring-CnFXHSqu.js → monitoring-CaEhdIcr.js} +1 -1
- package/dist/client/assets/{oauth-callback-CubY7ZAH.js → oauth-callback-HFODG9C4.js} +1 -1
- package/dist/client/assets/{page-DFKun2Tu.js → page-0IgoQPj0.js} +1 -1
- package/dist/client/assets/{page-u6lkgihQ.js → page-BbtKYCEh.js} +1 -1
- package/dist/client/assets/{pin-to-sidebar-button-BGiKx435.js → pin-to-sidebar-button-BTWnJIgz.js} +1 -1
- package/dist/client/assets/{plugin-empty-state-C6RQEnQT.js → plugin-empty-state-LAcvmaUO.js} +1 -1
- package/dist/client/assets/{plugin-header-BIVYVkxH.js → plugin-header-CIa7SNC1.js} +1 -1
- package/dist/client/assets/{plugins-CgIotr1d.js → plugins-Zgv-qqyu.js} +1 -1
- package/dist/client/assets/{popover-Dn4ivO-8.js → popover-ffhxj7L9.js} +1 -1
- package/dist/client/assets/{project-context-provider-D72115Hk.js → project-context-provider-CG5Jt9jX.js} +1 -1
- package/dist/client/assets/{registry-utils-BP4AlvoC.js → registry-utils-Cqqa8TSE.js} +1 -1
- package/dist/client/assets/{resizable-CvvIJMA2.js → resizable-e7LRtN-0.js} +1 -1
- package/dist/client/assets/{resource-tabs-BIg7eAtK.js → resource-tabs-B6SPH4Q6.js} +1 -1
- package/dist/client/assets/{schema-uDdRhKGN.js → schema-BesiDnBO.js} +1 -1
- package/dist/client/assets/{select-B9MrHEQV.js → select-Cd19OBy8.js} +1 -1
- package/dist/client/assets/{settings-Q3YU3dT_.js → settings-DgjJ7rwy.js} +1 -1
- package/dist/client/assets/shell-layout-C4m50Amb.js +3 -0
- package/dist/client/assets/{spinner-D65UOVx5.js → spinner-B3XPkxOB.js} +1 -1
- package/dist/client/assets/{switch-CRRx7Ihv.js → switch-rXNPyRWr.js} +1 -1
- package/dist/client/assets/{textarea-CPHR6Kxa.js → textarea-B0dfI4Xu.js} +1 -1
- package/dist/client/assets/{tool-set-selector-CCX0O6mj.js → tool-set-selector-DCV0H2hh.js} +1 -1
- package/dist/client/assets/{tools-list-CXNtlBT4.js → tools-list-DcCgeTm7.js} +1 -1
- package/dist/client/assets/{tooltip-D08WG2Dp.js → tooltip-BpIeWmG3.js} +1 -1
- package/dist/client/assets/{typewriter-title-CwCkt48S.js → typewriter-title-vmu3HKS1.js} +1 -1
- package/dist/client/assets/{use-binding-B3nCylWG.js → use-binding-CmWOKG-X.js} +1 -1
- package/dist/client/assets/{use-collections-GcxvTgiJ.js → use-collections-BRVu5nwP.js} +1 -1
- package/dist/client/assets/{use-connection-CkN55J_1.js → use-connection-D__nfNf6.js} +1 -1
- package/dist/client/assets/{use-connection-resources-D2edaHva.js → use-connection-resources-CaArMBqO.js} +1 -1
- package/dist/client/assets/{use-create-virtual-mcp-D-dhpSeW.js → use-create-virtual-mcp-CULFY9tZ.js} +1 -1
- package/dist/client/assets/{use-list-state-BRnheB8y.js → use-list-state-D7wpG1Rh.js} +1 -1
- package/dist/client/assets/{use-mcp-BQQPfGWJ.js → use-mcp-DsR0-4yM.js} +1 -1
- package/dist/client/assets/{use-members-DYIVgUcO.js → use-members-BTTcGaAb.js} +1 -1
- package/dist/client/assets/{use-mobile-CfOQmwhW.js → use-mobile-Bw0zGvKx.js} +1 -1
- package/dist/client/assets/{use-organization-settings-XdMGyJnx.js → use-organization-settings-DYYG9Qqm.js} +1 -1
- package/dist/client/assets/{use-tool-call-PpVkvWqr.js → use-tool-call-DdCnWg9K.js} +1 -1
- package/dist/client/assets/{use-virtual-mcp-BjvB4zxw.js → use-virtual-mcp-aCxo16E3.js} +1 -1
- package/dist/client/assets/{use-virtual-mcp-system-prompt-nay7WZGK.js → use-virtual-mcp-system-prompt-Be4EZZHh.js} +1 -1
- package/dist/client/assets/useInfiniteQuery-Dee7xpCM.js +1 -0
- package/dist/client/assets/{useMutation-BwDH9xn6.js → useMutation-DujnxbMG.js} +1 -1
- package/dist/client/assets/useQuery-CENoGrPp.js +1 -0
- package/dist/client/assets/{value-ClLnPq5S.js → value-BpSoQ0Q3.js} +1 -1
- package/dist/client/assets/{view-mode-toggle-DO5T8Hqo.js → view-mode-toggle--WEYRZgf.js} +1 -1
- package/dist/client/assets/{workflow-CfVwecJB.js → workflow-DtxWy1GI.js} +1 -1
- package/dist/client/index.html +1 -1
- package/dist/server/cli.js +1 -1
- package/dist/server/migrate.js +1 -1
- package/dist/server/server.js +1 -1
- package/package.json +1 -1
- package/dist/client/assets/constants-hDYh8bMu.js +0 -1
- package/dist/client/assets/shell-layout-BHlunMbQ.js +0 -3
- package/dist/client/assets/useInfiniteQuery-ft5Nm7Gb.js +0 -1
- package/dist/client/assets/useQuery-DqDScg2z.js +0 -1
package/dist/server/migrate.js
CHANGED
|
@@ -366,7 +366,7 @@ ${Y.stack}`;return Q}try{let G=JSON.stringify(Y,null,2);if(G!=="{}"&&G.length<10
|
|
|
366
366
|
Stack trace:
|
|
367
367
|
${Y.stack}`;return G}}catch{}if(typeof Y.toString==="function")try{let G=Y.toString();if(G!=="[object Object]")return G}catch{}let J=Object.keys(Y);if(J.length>0)return`Object with keys: ${J.join(", ")}`;return"[object Object]"}if(typeof X==="string")return X;if(typeof X==="number"||typeof X==="boolean")return String(X);if(typeof X==="function")return`[Function: ${X.name||"anon"}]`;if(typeof X==="symbol")return X.toString();if(typeof X==="bigint")return X.toString();try{return String(X)}catch{return"Unknown value (could not convert to string)"}}function Oz(X,Y){switch(typeof Y){case"string":return X.newString(Y);case"number":return X.newNumber(Y);case"boolean":return Y?X.true:X.false;case"undefined":return X.undefined;case"object":{if(Y===null)return X.null;if(Array.isArray(Y)){let J=X.newArray();return Y.forEach((G,Z)=>{let W=Oz(X,G);try{X.setProp(J,String(Z),W)}finally{W.dispose?.()}}),J}let Q=X.newObject();for(let[J,G]of Object.entries(Y)){let Z=Oz(X,G);try{X.setProp(Q,J,Z)}finally{Z.dispose?.()}}return Q}case"function":{let Q=`__hostFn_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return X.newFunction(Q,(...G)=>{try{let Z=G.map((K)=>X.dump(K)),W=Y(...Z);if(W&&typeof W.then==="function"){let K=X.newPromise();return W.then(($)=>{try{let H=Oz(X,$);K.resolve(H),H.dispose(),X.runtime.executePendingJobs()}catch(H){let F=Nz(H),q=X.newString(`Promise resolution error: ${F}`);K.reject(q),q.dispose(),X.runtime.executePendingJobs()}}).catch(($)=>{let H=Nz($),F=X.newString(`Promise rejection: ${H}`);K.reject(F),F.dispose(),X.runtime.executePendingJobs()}),K.handle}return Oz(X,W)}catch(Z){let W=Nz(Z);return X.newString(`HostFunctionError: ${W}`)}finally{G.forEach((Z)=>Z.dispose())}})}case"bigint":return X.newString(Y.toString());case"symbol":return X.newString(Y.toString());default:try{return X.newString(String(Y))}catch{return X.undefined}}}var s14=()=>{};function e14(X){let Y=X.runtime.executePendingJobs(100);try{if("unwrap"in Y&&typeof Y.unwrap==="function")Y.unwrap()}finally{if("dispose"in Y&&typeof Y.dispose==="function")Y.dispose()}}async function t14(X,Y,Q){let J=Date.now(),G=X.resolvePromise(Y);while(!0){e14(X);let Z=await Promise.race([G,TP6(0).then(()=>null)]);if(Z!==null)return Z;if(Date.now()-J>Q)throw Error(`Timed out after ${Q}ms while awaiting a QuickJS promise`)}}async function A40({tools:X,code:Y,timeoutMs:Q}){let W=[];try{let J=await r14({memoryLimitBytes:33554432,stackSizeBytes:524288});const G=ck(W,J.newContext({interruptAfterMs:Q}),0);const Z=ck(W,P14(G),0);try{let F=G.evalCode(Y,"index.mjs",{strip:!0,strict:!0,type:"module"}),q=G.unwrapResult(F),V=Oz(G,X);G.setProp(G.global,"tools",V);let U=G.runtime.hasPendingJob()?G.unwrapResult(await t14(G,q,Q)):q;if(U!==q)q.dispose();let D=G.getProp(U,"default"),N=G.typeof(D);if(N!=="function")return{error:`Code must export default a function (tools). Got ${N}. Example: export default async (tools) => { /* ... */ }`,consoleLogs:Z.logs};let O=G.callFunction(D,G.undefined,V),w=G.unwrapResult(O),E=await t14(G,w,Q),C=G.unwrapResult(E);if(G.runtime.hasPendingJob())e14(G);return{returnValue:G.dump(C),consoleLogs:Z.logs}}catch(F){return console.log(F),{error:Nz(F),consoleLogs:Z.logs}}}catch(K){var $=K,H=1}finally{A60(W,$,H)}}var TP6=(X)=>new Promise((Y)=>setTimeout(Y,X));var X84=d(()=>{o14();s14()});var Y84=d(()=>{X84()});async function AP6(X,Y){let Q;if(X.tool_selection_mode==="exclusion"){let G=(await Y.storage.connections.list(X.organization_id)).filter((W)=>W.status==="active"),Z=new Map;for(let W of X.connections)Z.set(W.connection_id,{selectedTools:W.selected_tools,selectedResources:W.selected_resources,selectedPrompts:W.selected_prompts});Q=[];for(let W of G){let K=Z.get(W.id);if(K===void 0)Q.push({connection:W,selectedTools:null,selectedResources:null,selectedPrompts:null});else if((K.selectedTools===null||K.selectedTools.length===0)&&(K.selectedResources===null||K.selectedResources.length===0)&&(K.selectedPrompts===null||K.selectedPrompts.length===0));else Q.push({connection:W,selectedTools:K.selectedTools,selectedResources:K.selectedResources,selectedPrompts:K.selectedPrompts})}}else{let J=X.connections.map((Z)=>Z.connection_id),G=[];for(let Z of J){let W=await Y.storage.connections.findById(Z);if(W&&W.status==="active")G.push(W)}Q=G.map((Z)=>{let W=X.connections.find((K)=>K.connection_id===Z.id);return{connection:Z,selectedTools:W?.selected_tools??null,selectedResources:W?.selected_resources??null,selectedPrompts:W?.selected_prompts??null}})}return Q}async function Q84(X,Y){return(await Y.storage.connections.list(X)).filter((J)=>J.status==="active").map((J)=>({connection:J,selectedTools:null,selectedResources:null,selectedPrompts:null}))}async function EP6(X,Y,Q){let J=await Sk.create(X,Q),G=await J.mapSettled(async(F,q)=>{try{let U=(await F.proxy.client.listTools()).tools;if(Y==="exclusion"){if(F.selectedTools&&F.selectedTools.length>0){let D=new Set(F.selectedTools);U=U.filter((N)=>!D.has(N.name))}}else if(F.selectedTools&&F.selectedTools.length>0){let D=new Set(F.selectedTools);U=U.filter((N)=>D.has(N.name))}return{connectionId:q,connectionTitle:F.connection.title,tools:U}}catch(V){return console.error(`[code-execution] Failed to list tools for connection ${q}:`,V),null}}),Z=new Set,W=[],K=new Map,$=new Set;for(let F of G){if(F.status!=="fulfilled"||!F.value)continue;let{connectionId:q,connectionTitle:V,tools:U}=F.value;$.add(V);for(let D of U){if(Z.has(D.name))continue;Z.add(D.name),W.push({...D,_meta:{connectionId:q,connectionTitle:V}}),K.set(D.name,{connectionId:q,originalName:D.name})}}return{tools:W,callTool:async(F,q)=>{let V=K.get(F);if(!V)return{content:[{type:"text",text:`Tool not found: ${F}`}],isError:!0};let U=J.get(V.connectionId);if(!U)return{content:[{type:"text",text:`Connection not found for tool: ${F}`}],isError:!0};return await U.proxy.client.callTool({name:V.originalName,arguments:q})},categories:Array.from($).sort()}}async function Lz(X){let Y=I4(X),Q,J="inclusion";if(X.connectionId){let G=await X.storage.virtualMcps.findById(X.connectionId);if(G)Q=await AP6(G,X),J=G.tool_selection_mode;else Q=await Q84(Y.id,X)}else Q=await Q84(Y.id,X);return EP6(Q,J,X)}function IP6(X){return X.toLowerCase().split(/[\s_\-./]+/).filter((Y)=>Y.length>=2)}function jP6(X,Y){let Q=0,J=Y.name.toLowerCase(),G=(Y.description??"").toLowerCase(),Z=Y._meta.connectionTitle.toLowerCase();for(let W of X){if(J===W)Q+=10;else if(J.includes(W))Q+=3;if(G.includes(W))Q+=2;if(Z.includes(W))Q+=1}return Q}function J84(X,Y,Q){let J=IP6(X);if(J.length===0)return Y.slice(0,Q);return Y.map((G)=>({tool:G,score:jP6(J,G)})).filter((G)=>G.score>0).sort((G,Z)=>Z.score-G.score).slice(0,Q).map((G)=>G.tool)}function G84(X,Y){let Q=new Map(Y.map((G)=>[G.name,G]));return{tools:X.map((G)=>Q.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:X.filter((G)=>!Q.has(G))}}async function W84(X,Y,Q){let J=Object.fromEntries(Y.tools.map((G)=>[G.name,async(Z)=>Y.callTool(G.name,Z??{})]));return A40({code:X,tools:J,timeoutMs:Q})}var yk=d(()=>{Y84()});var E40;var Z84=d(()=>{s4();Dw();yk();E40=r0({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.",inputSchema:D14,outputSchema:N14,handler:async(X,Y)=>{H4(Y),I4(Y),await Y.access.check();let Q=await Lz(Y),J=J84(X.query,Q.tools,X.limit);return{query:X.query,results:J.map((G)=>({name:G.name,description:G.description,connection:G._meta.connectionTitle})),totalAvailable:Q.tools.length}}})});var I40;var K84=d(()=>{s4();Dw();yk();I40=r0({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.",inputSchema:O14,outputSchema:L14,handler:async(X,Y)=>{H4(Y),I4(Y),await Y.access.check();let Q=await Lz(Y);return G84(X.tools,Q.tools)}})});var j40;var $84=d(()=>{s4();Dw();yk();j40=r0({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.',inputSchema:w14,outputSchema:M14,handler:async(X,Y)=>{H4(Y),I4(Y),await Y.access.check();let Q=await Lz(Y);return await W84(X.code,Q,X.timeoutMs)}})});var H84=d(()=>{Z84();K84();$84();Dw()});var RP6,SP6,C40;var F84=d(()=>{CS();s0();s4();Ck();uZ();RP6=L.object({data:Er0.describe("Data for the new connection (id is auto-generated if not provided)")}),SP6=L.object({item:HJ.describe("The created connection entity")}),C40=r0({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",inputSchema:RP6,outputSchema:SP6,handler:async(X,Y)=>{H4(Y);let Q=I4(Y);await Y.access.check();let J=A8(Y);if(!J)throw Error("User ID required to create connection");let G={...X.data,organization_id:Q.id,created_by:J};if(G.connection_type==="VIRTUAL"){let $=RS(G.connection_url);if(!$)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let H=await Y.storage.virtualMcps.findById($);if(!H)throw Error(`Virtual MCP not found: ${$}`);if(H.organization_id!==Q.id)throw Error("Virtual MCP does not belong to the current organization");G.connection_url=SS($)}let Z=await Uz({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=Z?.length?Z:null,K=await Y.storage.connections.create({...G,tools:W});return await Y.eventBus.publish(Q.id,jS.SELF(Q.id),{type:"connection.created",data:K}),{item:K}}})});function Ow(X,Y){if(X===Y)return!0;if(X==null||Y==null)return X===Y;if(typeof X!==typeof Y)return!1;if(Array.isArray(X)&&Array.isArray(Y)){if(X.length!==Y.length)return!1;return X.every((Q,J)=>Ow(Q,Y[J]))}if(typeof X==="object"&&typeof Y==="object"){let Q=Object.keys(X),J=Object.keys(Y);if(Q.length!==J.length)return!1;return Q.every((G)=>J.includes(G)&&Ow(X[G],Y[G]))}return!1}function eP6(){return(X)=>{if(!Array.isArray(X))return!0;let Y=[];return X.every((Q)=>{if(Y.some((G)=>Ow(Q,G)))return!1;return Y.push(Q),!0})}}function fk(X,Y){return X.safeParse(Y).success}function e9(X){if(typeof X==="boolean")return X?L.any():L.never();let Y={};for(let G of zT6)G.apply(Y,X);let Q=[];if(Y.string!==!1)Q.push(Y.string||L.string());if(Y.number!==!1)Q.push(Y.number||L.number());if(Y.boolean!==!1)Q.push(Y.boolean||L.boolean());if(Y.null!==!1)Q.push(Y.null||L.null());if(Y.array!==!1)Q.push(Y.array||L.array(L.any()));if(Y.tuple!==!1&&Y.tuple!==void 0)Q.push(Y.tuple);if(Y.object!==!1)if(Y.object)Q.push(Y.object);else{let G=L.custom((Z)=>{return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)},"Must be an object, not an array");Q.push(G)}if(Y.file!==!1&&Y.file!==void 0)Q.push(Y.file);let J;if(Q.length===0)J=L.never();else if(Q.length===1)J=Q[0];else if(!Object.keys(X).some((Z)=>Z!=="$schema"&&Z!=="title"&&Z!=="description"))J=L.any();else J=L.union(Q);for(let G of UT6)J=G.apply(J,X);return J}var vP6=class{apply(X,Y){if(!Y.type)return;let Q=Array.isArray(Y.type)?Y.type:[Y.type],J=new Set(Q);if(!J.has("string"))X.string=!1;if(!J.has("number")&&!J.has("integer"))X.number=!1;if(!J.has("boolean"))X.boolean=!1;if(!J.has("null"))X.null=!1;if(!J.has("array"))X.array=!1;if(!J.has("object"))X.object=!1;if(J.has("integer")&&X.number!==!1){let G=X.number||L.number();if(G instanceof L.ZodNumber)X.number=G.int()}}},kP6=class{apply(X,Y){if(Y.const===void 0)return;let Q=Y.const;if(X.string=!1,X.number=!1,X.boolean=!1,X.null=!1,X.array=!1,X.object=!1,typeof Q==="string")X.string=L.literal(Q);else if(typeof Q==="number")X.number=L.literal(Q);else if(typeof Q==="boolean")X.boolean=L.literal(Q);else if(Q===null)X.null=L.null();else if(Array.isArray(Q))X.array=void 0;else if(typeof Q==="object")X.object=void 0}},_P6=class{apply(X,Y){if(!Y.enum)return;if(Y.enum.length===0){if(!Y.type)X.string=!1,X.number=!1,X.boolean=!1,X.null=!1,X.array=!1,X.object=!1;return}let Q={string:Y.enum.filter((J)=>typeof J==="string"),number:Y.enum.filter((J)=>typeof J==="number"),boolean:Y.enum.filter((J)=>typeof J==="boolean"),null:Y.enum.filter((J)=>J===null),array:Y.enum.filter((J)=>Array.isArray(J)),object:Y.enum.filter((J)=>typeof J==="object"&&J!==null&&!Array.isArray(J))};X.string=this.createTypeSchema(Q.string,"string"),X.number=this.createTypeSchema(Q.number,"number"),X.boolean=this.createTypeSchema(Q.boolean,"boolean"),X.null=Q.null.length>0?L.null():!1,X.array=Q.array.length>0?void 0:!1,X.object=Q.object.length>0?void 0:!1}createTypeSchema(X,Y){if(X.length===0)return!1;if(X.length===1)return L.literal(X[0]);if(Y==="string")return L.enum(X);if(Y==="number"){let[Q,J,...G]=X;return L.union([L.literal(Q),L.literal(J),...G.map((Z)=>L.literal(Z))])}if(Y==="boolean")return L.union([L.literal(!0),L.literal(!1)]);return!1}},yP6=class{apply(X,Y){let Q=Y;if(Q.type==="string"&&Q.format==="binary"&&Q.contentEncoding==="binary"){let J=L.file();if(Q.minLength!==void 0)J=J.min(Q.minLength);if(Q.maxLength!==void 0)J=J.max(Q.maxLength);if(Q.contentMediaType!==void 0)J=J.mime(Q.contentMediaType);X.file=J,X.string=!1}}},fP6=class{apply(X,Y){let Q=Y;if(Y.type===void 0&&(Q.minLength!==void 0||Q.maxLength!==void 0||Q.pattern!==void 0)){if(X.string===void 0)X.string=L.string()}}},bP6=class{apply(X,Y){let Q=Y;if(Q.minLength===void 0)return;if(X.string!==!1){let J=X.string||L.string();if(J instanceof L.ZodString)X.string=J.refine((G)=>{return Array.from(G).length>=Q.minLength},{message:`String must be at least ${Q.minLength} characters long`})}}},hP6=class{apply(X,Y){let Q=Y;if(Q.maxLength===void 0)return;if(X.string!==!1){let J=X.string||L.string();if(J instanceof L.ZodString)X.string=J.refine((G)=>{return Array.from(G).length<=Q.maxLength},{message:`String must be at most ${Q.maxLength} characters long`})}}},xP6=class{apply(X,Y){let Q=Y;if(!Q.pattern)return;if(X.string!==!1){let J=X.string||L.string();if(J instanceof L.ZodString){let G=new RegExp(Q.pattern);X.string=J.regex(G)}}}},gP6=class{apply(X,Y){let Q=Y;if(Q.minimum===void 0)return;if(X.number!==!1){let J=X.number||L.number();if(J instanceof L.ZodNumber)X.number=J.min(Q.minimum)}}},uP6=class{apply(X,Y){let Q=Y;if(Q.maximum===void 0)return;if(X.number!==!1){let J=X.number||L.number();if(J instanceof L.ZodNumber)X.number=J.max(Q.maximum)}}},mP6=class{apply(X,Y){let Q=Y;if(Q.exclusiveMinimum===void 0)return;if(X.number!==!1){let J=X.number||L.number();if(J instanceof L.ZodNumber)if(typeof Q.exclusiveMinimum==="number")X.number=J.gt(Q.exclusiveMinimum);else X.number=!1}}},lP6=class{apply(X,Y){let Q=Y;if(Q.exclusiveMaximum===void 0)return;if(X.number!==!1){let J=X.number||L.number();if(J instanceof L.ZodNumber)if(typeof Q.exclusiveMaximum==="number")X.number=J.lt(Q.exclusiveMaximum);else X.number=!1}}},dP6=class{apply(X,Y){let Q=Y;if(Q.multipleOf===void 0)return;if(X.number!==!1){let J=X.number||L.number();if(J instanceof L.ZodNumber)X.number=J.refine((G)=>{if(Q.multipleOf===0)return!1;let Z=G/Q.multipleOf,W=Math.round(Z),K=Math.min(Math.abs(G)*Number.EPSILON*10,Math.abs(Q.multipleOf)*Number.EPSILON*10);return Math.abs(Z-W)<=K/Math.abs(Q.multipleOf)},{message:`Must be a multiple of ${Q.multipleOf}`})}}},pP6=class{apply(X,Y){let Q=Y;if(Y.type===void 0&&(Q.minItems!==void 0||Q.maxItems!==void 0||Q.items!==void 0||Q.prefixItems!==void 0)){if(X.array===void 0)X.array=L.array(L.any())}}},cP6=class{apply(X,Y){let Q=Y;if(Q.minItems===void 0)return;if(X.array!==!1)X.array=(X.array||L.array(L.any())).min(Q.minItems)}},nP6=class{apply(X,Y){let Q=Y;if(Q.maxItems===void 0)return;if(X.array!==!1)X.array=(X.array||L.array(L.any())).max(Q.maxItems)}},iP6=class{apply(X,Y){let Q=Y;if(X.array===!1)return;if(Array.isArray(Q.items))X.array=X.array||L.array(L.any());else if(Q.items&&typeof Q.items!=="boolean"&&!Q.prefixItems){let J=e9(Q.items),G=L.array(J);if(X.array&&X.array instanceof L.ZodArray){let Z=X.array._def;if(Z.checks)Z.checks.forEach((W)=>{if(W._zod&&W._zod.def){let K=W._zod.def;if(K.check==="min_length"&&K.minimum!==void 0)G=G.min(K.minimum);else if(K.check==="max_length"&&K.maximum!==void 0)G=G.max(K.maximum)}})}X.array=G}else if(typeof Q.items==="boolean"&&Q.items===!1)if(!Q.prefixItems)X.array=L.array(L.any()).max(0);else X.array=X.array||L.array(L.any());else if(typeof Q.items==="boolean"&&Q.items===!0)X.array=X.array||L.array(L.any());else if(Q.prefixItems)X.array=X.array||L.array(L.any())}},aP6=class{apply(X,Y){if(Y.type!=="array")return;let Q=Y;if(!Array.isArray(Q.items))return;if(X.array===!1)return;let J=Q.items.map((Z)=>e9(Z)),G;if(J.length===0)G=L.tuple([]);else G=L.tuple(J);if(Q.minItems!==void 0&&Q.minItems>J.length)G=!1;if(Q.maxItems!==void 0&&Q.maxItems<J.length)G=!1;X.tuple=G,X.array=!1}},rP6=class{apply(X,Y){let Q=Y;if(X.object===!1)return;if(Q.properties||Q.required||Q.additionalProperties!==void 0)X.object=X.object||L.object({}).passthrough()}},oP6=class{apply(X,Y){let Q=Y;if(Y.type===void 0&&(Q.maxProperties!==void 0||Q.minProperties!==void 0)){if(X.object===void 0)X.object=L.object({}).passthrough()}}},sP6=class{apply(X,Y){let Q=Y;if(Q.maxProperties===void 0)return;if(X.object!==!1){let J=X.object||L.object({}).passthrough();X.object=J.refine((G)=>Object.keys(G).length<=Q.maxProperties,{message:`Object must have at most ${Q.maxProperties} properties`})}}},tP6=class{apply(X,Y){let Q=Y;if(Q.minProperties===void 0)return;if(X.object!==!1){let J=X.object||L.object({}).passthrough();X.object=J.refine((G)=>Object.keys(G).length>=Q.minProperties,{message:`Object must have at least ${Q.minProperties} properties`})}}},XT6=class{apply(X,Y){if(!Y.not)return X;let Q=e9(Y.not);return X.refine((J)=>!fk(Q,J),{message:"Value must not match the 'not' schema"})}},YT6=class{apply(X,Y){if(Y.uniqueItems!==!0)return X;return X.refine(eP6(),{message:"Array items must be unique"})}},QT6=class{apply(X,Y){if(!Y.allOf||Y.allOf.length===0)return X;return Y.allOf.map((J)=>e9(J)).reduce((J,G)=>L.intersection(J,G),X)}},JT6=class{apply(X,Y){if(!Y.anyOf||Y.anyOf.length===0)return X;let Q=Y.anyOf.length===1?e9(Y.anyOf[0]):L.union([e9(Y.anyOf[0]),e9(Y.anyOf[1]),...Y.anyOf.slice(2).map((J)=>e9(J))]);return L.intersection(X,Q)}},GT6=class{apply(X,Y){if(!Y.oneOf||Y.oneOf.length===0)return X;let Q=Y.oneOf.map((J)=>e9(J));return X.refine((J)=>{let G=0;for(let Z of Q)if(Z.safeParse(J).success){if(G++,G>1)return!1}return G===1},{message:"Value must match exactly one of the oneOf schemas"})}},WT6=class{apply(X,Y){let Q=Y;if(Q.prefixItems&&Array.isArray(Q.prefixItems)){let G=Q.prefixItems.map((Z)=>e9(Z));return X.refine((Z)=>{if(!Array.isArray(Z))return!0;for(let W=0;W<Math.min(Z.length,G.length);W++)if(!fk(G[W],Z[W]))return!1;if(Z.length>G.length){if(typeof Q.items==="boolean"&&Q.items===!1)return!1;else if(Q.items&&typeof Q.items==="object"&&!Array.isArray(Q.items)){let W=e9(Q.items);for(let K=G.length;K<Z.length;K++)if(!fk(W,Z[K]))return!1}}return!0},{message:"Array does not match prefixItems schema"})}return X}},ZT6=class{apply(X,Y){let Q=Y;if(!Q.properties&&!Q.required&&Q.additionalProperties!==!1)return X;if(X instanceof L.ZodObject||X instanceof L.ZodRecord){let J={};if(Q.properties){for(let[G,Z]of Object.entries(Q.properties))if(Z!==void 0)J[G]=e9(Z)}if(Q.required&&Array.isArray(Q.required)){let G=new Set(Q.required);for(let Z of Object.keys(J))if(!G.has(Z))J[Z]=J[Z].optional()}else for(let G of Object.keys(J))J[G]=J[G].optional();if(Q.additionalProperties===!1)return L.object(J);else return L.object(J).passthrough()}return X.refine((J)=>{if(typeof J!=="object"||J===null||Array.isArray(J))return!0;if(Q.properties){for(let[G,Z]of Object.entries(Q.properties))if(Z!==void 0){if(Object.getOwnPropertyDescriptor(J,G)!==void 0){if(!e9(Z).safeParse(J[G]).success)return!1}}}if(Q.required&&Array.isArray(Q.required)){for(let G of Q.required)if(Object.getOwnPropertyDescriptor(J,G)===void 0)return!1}if(Q.additionalProperties===!1&&Q.properties){let G=new Set(Object.keys(Q.properties));for(let Z in J)if(!G.has(Z))return!1}return!0},{message:"Object constraints validation failed"})}},KT6=class{apply(X,Y){if(!Y.enum||Y.enum.length===0)return X;let Q=Y.enum.filter((J)=>Array.isArray(J)||typeof J==="object"&&J!==null);if(Q.length===0)return X;return X.refine((J)=>{if(typeof J!=="object"||J===null)return!0;return Q.some((G)=>Ow(J,G))},{message:"Value must match one of the enum values"})}},$T6=class{apply(X,Y){if(Y.const===void 0)return X;let Q=Y.const;if(typeof Q!=="object"||Q===null)return X;return X.refine((J)=>Ow(J,Q),{message:"Value must equal the const value"})}},HT6=class{apply(X,Y){if(Y.description)X=X.describe(Y.description);return X}},FT6=class{apply(X,Y){var Q;let J=Y;if(!((Q=J.required)==null?void 0:Q.includes("__proto__"))||Y.type!==void 0)return X;return L.any().refine((G)=>this.validateRequired(G,J.required),{message:"Missing required properties"})}validateRequired(X,Y){if(typeof X!=="object"||X===null||Array.isArray(X))return!0;return Y.every((Q)=>Object.prototype.hasOwnProperty.call(X,Q))}},qT6=class{apply(X,Y){var Q;let J=Y;if(J.contains===void 0)return X;let G=e9(J.contains),Z=(Q=J.minContains)!=null?Q:1,W=J.maxContains;return X.refine((K)=>{if(!Array.isArray(K))return!0;let $=0;for(let H of K)if(fk(G,H))$++;if($<Z)return!1;if(W!==void 0&&$>W)return!1;return!0},{message:"Array must contain required items matching the schema"})}},VT6=class{apply(X,Y){let{default:Q}=Y;if(Q===void 0)return X;if(!X.safeParse(Q).success)return X;return X.default(Q)}},zT6,UT6;var q84=d(()=>{N9();N9();N9();N9();N9();N9();N9();N9();N9();N9();N9();N9();N9();N9();zT6=[new kP6,new _P6,new vP6,new yP6,new fP6,new pP6,new oP6,new bP6,new hP6,new xP6,new gP6,new uP6,new mP6,new lP6,new dP6,new aP6,new cP6,new nP6,new iP6,new sP6,new tP6,new rP6],UT6=[new FT6,new KT6,new $T6,new QT6,new JT6,new GT6,new WT6,new ZT6,new qT6,new XT6,new YT6,new VT6,new HT6]});class R40{constructor(X){this._url=X}start(){if(this._socket)throw Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((X,Y)=>{this._socket=new WebSocket(this._url,BT6),this._socket.onerror=(Q)=>{let J="error"in Q?Q.error:Error(`WebSocket error: ${JSON.stringify(Q)}`);Y(J),this.onerror?.(J)},this._socket.onopen=()=>{X()},this._socket.onclose=()=>{this.onclose?.()},this._socket.onmessage=(Q)=>{let J;try{J=qQ.parse(JSON.parse(Q.data))}catch(G){this.onerror?.(G);return}this.onmessage?.(J)}})}async close(){this._socket?.close()}send(X){return new Promise((Y,Q)=>{if(!this._socket){Q(Error("Not connected"));return}this._socket?.send(JSON.stringify(X)),Y()})}}var BT6="mcp";var V84=d(()=>{VQ()});function DT6(X){let Y=X;if(!Y||typeof Y!=="object"||!("method"in Y))return null;switch(Y.method){case"initialize":{let Q=Y?.params?.protocolVersion;if(!Q)return null;return{type:"emit",message:{result:{protocolVersion:Q,capabilities:{tools:{}},serverInfo:{name:"deco-chat-server",version:"1.0.0"}},jsonrpc:Y.jsonrpc??"2.0",id:Y.id}}}case"notifications/roots/list_changed":case"notifications/initialized":case"notifications/cancelled":case"notifications/progress":return{type:"suppress"};default:return null}}var S40;var z84=d(()=>{n00();S40=class S40 extends Uw{constructor(X,Y){super(X,Y)}send(X,Y){let Q=DT6(X);if(Q?.type==="emit")return this.onmessage?.(Q.message),Promise.resolve();if(Q?.type==="suppress")return Promise.resolve();return super.send(X,Y)}}});var U84,B84=async(X,Y,Q)=>{let J=NT6(X.connection,Y,Q);if(!J)throw Error("Unknown MCP connection type");let G=new U84({name:X?.name??"MCP Client",version:"1.0.0"});return await G.connect(J),{client:G,callStreamableTool:(Z,W)=>{if(X.connection.type!=="HTTP")throw Error("HTTP connection required");let K=new Headers(Q);if(!K.has("Authorization"))K.set("Authorization",`Bearer ${X.connection.token}`);for(let[F,q]of Object.entries(X.connection.headers??{}))K.set(F,q);let $=new URL(X.connection.url),H=$.pathname.replace(/\/+$/,"")||"/";return $.pathname=`${H}/call-tool/${encodeURIComponent(Z)}`,fetch($.href,{method:"POST",redirect:"manual",body:JSON.stringify(W),headers:K})}}},NT6=(X,Y,Q)=>{if(X.type==="Websocket")return new R40(new URL(X.url));if(X.type!=="SSE"&&X.type!=="HTTP")return null;let G={...X.token?{authorization:`Bearer ${X.token}`}:{},...Q??{},..."headers"in X?X.headers||{}:{}};if(X.type==="SSE"){let Z={requestInit:{headers:G,signal:Y}};if(X.token)Z.eventSourceInit={fetch:(W,K)=>{return fetch(W,{...K,headers:{...G,Accept:"text/event-stream"},signal:Y})}};return new zw(new URL(X.url),Z)}return new S40(new URL(X.url),{requestInit:{headers:G,signal:Y,credentials:"include"}})};var D84=d(()=>{H00();_00();V84();VQ();z84();U84=class U84 extends c3{constructor(X,Y){super(X,Y)}async listTools(X,Y){return await this.request({method:"tools/list",params:X},yL,Y)}}});function O84(X){let Y=(Q)=>{if("connection"in X)return B84({connection:X.connection},void 0,Q);return X.client};return new Proxy({},{get(Q,J){if(J==="toJSON")return null;if(typeof J!=="string")throw Error("Name must be a string");if(J==="listTools")return K;async function G($,H=J){let F=X?.debugId?.(),q=F?{"x-trace-debug-id":F}:void 0,{client:V,callStreamableTool:U}=await Y(q);if(X?.streamable?.[String(H)])return U(String(H),$);let{structuredContent:D,isError:N,content:O}=await V.callTool({name:String(H),arguments:$});if(N){let w=O?.[0]?.text,E=typeof w==="string"?OT6(w):null,C=E?.code&&typeof X?.getErrorByStatusCode==="function"?X.getErrorByStatusCode(E.code,E.message,E.traceId):null;if(C)throw C;throw Error(`Tool ${String(H)} returned an error: ${JSON.stringify(D??O)}`)}return D}async function Z(){let{client:$}=await Y(),{tools:H}=await $.listTools();return H}async function W(){if(!("connection"in X))return Z();let $=X.connection,H=JSON.stringify($);try{if(!bk.has(H))bk.set(H,Z());return await bk.get(H)}catch(F){console.error("Failed to list tools",F),bk.delete(H);return}}async function K(){return(await W()??[]).map((H)=>N84(H,G))}return G.asTool=async()=>{let H=(await W()??[]).find((F)=>F.name===J);if(!H)throw Error(`Tool ${J} not found`);return N84(H,G)},G}})}var OT6=(X)=>{try{return JSON.parse(X)}catch{return X}},bk,N84=(X,Y)=>{return{...X,id:X.name,inputSchema:X.inputSchema?e9(X.inputSchema):void 0,outputSchema:X.outputSchema?e9(X.outputSchema):void 0,execute:(Q)=>{return Y(Q.context,X.name)}}};var L84=d(()=>{q84();D84();bk=new Map});function hk(X){return O84(X)}var JP1;var w84=d(()=>{L84();JP1=new Proxy({},{get(X,Y){if(Y==="toJSON")return null;if(Y==="forConnection")return(Q)=>hk({connection:Q});return global[Y]}})});function xk(X){return{isImplementedBy:(Y)=>{for(let Q of X){let J=typeof Q.name==="string"?new RegExp(`^${Q.name}$`):Q.name,G=Y.find((Z)=>J.test(Z.name));if(!G&&Q.opt)continue;if(!G)return!1}return!0}}}var s3=(X)=>{return{...xk(X),forClient:(Y)=>{return hk({client:Y,streamable:X.reduce((Q,J)=>{return Q[J.name]=J.streamable===!0,Q},{})})},forConnection:(Y)=>{return hk({connection:Y,streamable:X.reduce((Q,J)=>{return Q[J.name]=J.streamable===!0,Q},{})})}}};var Lw=d(()=>{w84()});function ww(X,Y,Q){this.props=X,this.context=Y,this.refs=P84,this.updater=Q||M84}function T84(){}function A84(X,Y,Q){this.props=X,this.context=Y,this.refs=P84,this.updater=Q||M84}var LT6,wT6,M84,MT6,P84,v40,k40=function(X){return X={$$typeof:wT6,_currentValue:X,_currentValue2:X,_threadCount:0,Provider:null,Consumer:null},X.Provider=X,X.Consumer={$$typeof:LT6,_context:X},X};var E84=d(()=>{LT6=Symbol.for("react.consumer"),wT6=Symbol.for("react.context"),M84={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},MT6=Object.assign,P84={};ww.prototype.isReactComponent={};ww.prototype.setState=function(X,Y){if(typeof X!=="object"&&typeof X!=="function"&&X!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,X,Y,"setState")};ww.prototype.forceUpdate=function(X){this.updater.enqueueForceUpdate(this,X,"forceUpdate")};T84.prototype=ww.prototype;v40=A84.prototype=new T84;v40.constructor=A84;MT6(v40,ww.prototype);v40.isPureReactComponent=!0});var _40=()=>{};var zP1;var I84=d(()=>{E84();_40();zP1=k40(null)});function e3(X){return L.object({items:L.array(X).describe("Array of collection items"),totalCount:L.number().int().min(0).optional().describe("Total number of matching items (if available)"),hasMore:L.boolean().optional().describe("Whether there are more items available")})}function Pw(X){return L.object({item:X.nullable().describe("The retrieved item, or null if not found")})}function AT6(X){return L.object({data:X.partial().describe("Data for the new entity (id may be auto-generated)")})}function ET6(X){return L.object({item:X.describe("The created entity with generated id")})}function IT6(X){return L.object({id:L.string().describe("ID of the entity to update"),data:X.partial().describe("Partial entity data to update")})}function jT6(X){return L.object({item:X.describe("The updated entity")})}function Aw(X){return L.object({item:X.describe("The deleted entity")})}function Mz(X,Y,Q){let J=X.toUpperCase(),G=Q?.readOnly??!1,Z=[{name:`COLLECTION_${J}_LIST`,inputSchema:t3,outputSchema:e3(Y)},{name:`COLLECTION_${J}_GET`,inputSchema:Mw,outputSchema:Pw(Y)}];if(!G)Z.push({name:`COLLECTION_${J}_CREATE`,inputSchema:AT6(Y),outputSchema:ET6(Y),opt:!0},{name:`COLLECTION_${J}_UPDATE`,inputSchema:IT6(Y),outputSchema:jT6(Y),opt:!0},{name:`COLLECTION_${J}_DELETE`,inputSchema:Tw,outputSchema:Aw(Y),opt:!0});return Z}var wz,PT6,j84,TT6,t3,Mw,Tw;var K5=d(()=>{s0();wz=L.object({id:L.string().describe("Unique identifier for the entity"),title:L.string().describe("Human-readable title for the entity"),description:L.string().nullish().describe("Description of the entity"),created_at:L.string().datetime(),updated_at:L.string().datetime(),created_by:L.string().optional(),updated_by:L.string().optional()}),PT6=L.object({field:L.array(L.string()),operator:L.enum(["eq","gt","gte","lt","lte","in","like","contains"]),value:L.unknown()}),j84=L.lazy(()=>L.union([PT6,L.object({operator:L.enum(["and","or","not"]),conditions:L.array(j84)})])),TT6=L.object({field:L.array(L.string()),direction:L.enum(["asc","desc"]),nulls:L.enum(["first","last"]).optional()}),t3=L.object({where:j84.optional().describe("Filter expression"),orderBy:L.array(TT6).optional().describe("Sort expressions"),limit:L.number().int().min(1).max(1000).optional().describe("Maximum number of items to return"),offset:L.number().int().min(0).optional().describe("Number of items to skip")});Mw=L.object({id:L.string().describe("ID of the entity to retrieve")});Tw=L.object({id:L.string().describe("ID of the entity to delete")})});var CT6,C84,wP1;var R84=d(()=>{s0();K5();CT6=L.object({id:L.string(),name:L.string(),description:L.string().optional(),inputSchema:L.record(L.string(),L.unknown()),outputSchema:L.record(L.string(),L.unknown()).optional()}),C84=wz.extend({_meta:L.object({"io.decocms":L.object({id:L.string(),verified:L.boolean(),scopeName:L.string(),appName:L.string(),friendlyName:L.string().nullable().optional(),metadata:L.record(L.string(),L.unknown()).nullable().optional(),publishedAt:L.string().datetime().optional(),updatedAt:L.string().datetime().optional(),tools:L.array(CT6).nullable().optional().describe("Available tools exposed by this app")}).optional()}).optional(),server:L.object({$schema:L.string().optional(),_meta:L.record(L.string(),L.unknown()).optional(),name:L.string().describe("The server name (scope/app)"),title:L.string().optional().describe("User-friendly title"),description:L.string().optional().describe("Server description"),icons:L.array(L.object({src:L.string(),mimeType:L.string().optional(),sizes:L.array(L.string()).optional(),theme:L.enum(["light","dark"]).optional()})).optional(),remotes:L.array(L.object({type:L.enum(["http","stdio","sse"]),url:L.string().optional(),headers:L.array(L.unknown()).optional()})).optional(),packages:L.array(L.unknown()).optional(),repository:L.object({url:L.string(),source:L.string().optional(),subfolder:L.string().optional()}).optional(),version:L.string().optional(),websiteUrl:L.string().optional()})}),wP1=Mz("registry_app",C84,{readOnly:!0})});var S84,v84,k84,_84,y84,RT6;var f84=d(()=>{s0();Lw();S84=L.object({specversion:L.literal("1.0").describe("CloudEvents specification version"),id:L.string().describe("Unique identifier for this event (UUID recommended)"),source:L.string().describe("Connection ID of the event publisher"),type:L.string().describe("Event type (e.g., 'order.created', 'user.signup')"),time:L.string().datetime().optional().describe("Timestamp of when the event occurred (ISO 8601)"),subject:L.string().optional().describe("Subject/resource identifier (e.g., order ID, user ID)"),datacontenttype:L.string().optional().default("application/json").describe("Content type of the data attribute"),dataschema:L.string().url().optional().describe("URI to the schema for the data attribute"),data:L.unknown().optional().describe("Event payload (any JSON value)")}),v84=L.object({events:L.array(S84).min(1).describe("Batch of CloudEvents to process")}),k84=L.object({success:L.boolean().optional().describe("Whether this event was processed successfully"),error:L.string().optional().describe("Error message for this event"),retryAfter:L.number().int().positive().optional().describe("Re-deliver this event after this many ms")}),_84=L.object({success:L.boolean().optional().describe("Batch success - applies to events not in results"),error:L.string().optional().describe("Batch error message - applies to events not in results"),processedCount:L.number().int().min(0).optional().describe("Number of events successfully processed"),retryAfter:L.number().int().positive().optional().describe("Batch retryAfter - applies to events not in results"),results:L.record(L.string(),k84).optional().describe("Per-event results keyed by event ID")}),y84=[{name:"ON_EVENTS",inputSchema:v84,outputSchema:_84}],RT6=s3(y84)});var Ew,Iw,jw,Cw,b84,h84,Rw,Sw,vw,kw,_w,yw,fw,bw,x84,ST6;var g84=d(()=>{s0();Lw();Ew=L.object({type:L.string().min(1).max(255).describe("Event type identifier"),subject:L.string().max(255).optional().describe("Subject/resource identifier (e.g., order ID)"),data:L.unknown().optional().describe("Event payload"),deliverAt:L.string().datetime().optional().describe("Scheduled delivery time (ISO 8601). Omit for immediate delivery."),cron:L.string().max(100).optional().describe("Cron expression for recurring delivery. Use EVENT_CANCEL to stop.")}),Iw=L.object({id:L.string().describe("Unique event ID"),type:L.string().describe("Event type"),source:L.string().describe("Source connection ID"),time:L.string().describe("Event timestamp")}),jw=L.object({eventType:L.string().min(1).max(255).describe("Event type to subscribe to"),publisher:L.string().optional().describe("Filter events by publisher connection ID"),filter:L.string().max(1000).optional().describe("JSONPath filter expression on event data")}),Cw=L.object({subscription:L.object({id:L.string().describe("Subscription ID"),connectionId:L.string().describe("Subscriber connection ID"),eventType:L.string().describe("Event type pattern"),publisher:L.string().nullable().describe("Publisher connection filter"),filter:L.string().nullable().describe("JSONPath filter expression"),enabled:L.boolean().describe("Whether subscription is enabled"),createdAt:L.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:L.string().datetime().describe("Updated timestamp (ISO 8601)")})}),b84=L.object({eventType:L.string().min(1).max(255).describe("Event type to subscribe to"),publisher:L.string().optional().describe("Filter events by publisher connection ID"),filter:L.string().max(1000).optional().describe("JSONPath filter expression on event data")}),h84=L.object({id:L.string().describe("Subscription ID"),connectionId:L.string().describe("Subscriber connection ID"),eventType:L.string().describe("Event type pattern"),publisher:L.string().nullable().describe("Publisher connection filter"),filter:L.string().nullable().describe("JSONPath filter expression"),enabled:L.boolean().describe("Whether subscription is enabled"),createdAt:L.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:L.string().datetime().describe("Updated timestamp (ISO 8601)")}),Rw=L.object({subscriptions:L.array(b84).describe("Desired subscriptions - system will create/update/delete to match")}),Sw=L.object({created:L.number().int().min(0).describe("Number of subscriptions created"),updated:L.number().int().min(0).describe("Number of subscriptions with filter updated"),deleted:L.number().int().min(0).describe("Number of subscriptions removed"),unchanged:L.number().int().min(0).describe("Number of subscriptions unchanged"),subscriptions:L.array(h84).describe("Current subscriptions after sync")}),vw=L.object({subscriptionId:L.string().describe("Subscription ID to remove")}),kw=L.object({success:L.boolean().describe("Whether unsubscribe was successful"),subscriptionId:L.string().describe("Subscription ID that was removed")}),_w=L.object({eventId:L.string().describe("Event ID to cancel")}),yw=L.object({success:L.boolean().describe("Whether cancellation was successful"),eventId:L.string().describe("Event ID that was cancelled")}),fw=L.object({eventId:L.string().describe("Event ID to acknowledge")}),bw=L.object({success:L.boolean().describe("Whether ACK was successful"),eventId:L.string().describe("Event ID that was acknowledged")}),x84=[{name:"EVENT_PUBLISH",inputSchema:Ew,outputSchema:Iw},{name:"EVENT_SUBSCRIBE",inputSchema:jw,outputSchema:Cw},{name:"EVENT_UNSUBSCRIBE",inputSchema:vw,outputSchema:kw},{name:"EVENT_CANCEL",inputSchema:_w,outputSchema:yw},{name:"EVENT_ACK",inputSchema:fw,outputSchema:bw},{name:"EVENT_SYNC_SUBSCRIPTIONS",inputSchema:Rw,outputSchema:Sw}],ST6=s3(x84)});var RP1,SP1,vP1,kP1,_P1,yP1,fP1,bP1,hP1,xP1,gP1,uP1;var u84=d(()=>{s0();RP1=L.object({prefix:L.string().optional().describe("Filter objects by prefix (e.g., 'folder/' for folder contents)"),maxKeys:L.number().optional().default(1000).describe("Maximum number of keys to return (default: 1000)"),continuationToken:L.string().optional().describe("Token for pagination from previous response"),delimiter:L.string().optional().describe("Delimiter for grouping keys (typically '/'). When set, commonPrefixes returns folder paths.")}),SP1=L.object({objects:L.array(L.object({key:L.string().describe("Object key/path"),size:L.number().describe("Object size in bytes"),lastModified:L.string().describe("Last modified timestamp"),etag:L.string().describe("Entity tag for the object")})),nextContinuationToken:L.string().optional().describe("Token for fetching next page of results"),isTruncated:L.boolean().describe("Whether there are more results available"),commonPrefixes:L.array(L.string()).optional().describe("Folder paths when delimiter is used (e.g., ['photos/2024/', 'photos/2025/'])")}),vP1=L.object({key:L.string().describe("Object key/path to get metadata for")}),kP1=L.object({contentType:L.string().optional().describe("MIME type of the object"),contentLength:L.number().describe("Size of the object in bytes"),lastModified:L.string().describe("Last modified timestamp"),etag:L.string().describe("Entity tag for the object"),metadata:L.record(L.string(),L.string()).optional().describe("Custom metadata key-value pairs")}),_P1=L.object({key:L.string().describe("Object key/path to generate URL for"),expiresIn:L.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)")}),yP1=L.object({url:L.string().describe("Presigned URL for downloading the object"),expiresIn:L.number().describe("Expiration time in seconds that was used")}),fP1=L.object({key:L.string().describe("Object key/path for the upload"),expiresIn:L.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)"),contentType:L.string().optional().describe("MIME type for the object being uploaded")}),bP1=L.object({url:L.string().describe("Presigned URL for uploading the object"),expiresIn:L.number().describe("Expiration time in seconds that was used")}),hP1=L.object({key:L.string().describe("Object key/path to delete")}),xP1=L.object({success:L.boolean().describe("Whether the deletion was successful"),key:L.string().describe("The key that was deleted")}),gP1=L.object({keys:L.array(L.string()).max(1000).describe("Array of object keys/paths to delete (max 1000)")}),uP1=L.object({deleted:L.array(L.string()).describe("Array of successfully deleted keys"),errors:L.array(L.object({key:L.string(),message:L.string()})).describe("Array of errors for failed deletions")})});var y40=d(()=>{Lw();I84();R84();f84();g84();u84()});var vT6,kT6,m84;var l84=d(()=>{s0();K5();vT6=wz.extend({avatar:L.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:L.string().describe("System prompt that defines the assistant's behavior"),virtual_mcp_id:L.string().describe("Virtual MCP ID to use for this assistant"),model:L.object({id:L.string().describe("Model ID"),connectionId:L.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),kT6=Mz("assistant",vT6),m84=[...kT6]});var hw,e7,p84,_T6,yT6,c84,fT6,bT6,hT6,xT6,gT6,uT6,n84,mT6,lT6,dT6,pT6,cT6,nT6,iT6,aT6,rT6,oT6,ZT1,sT6,KT1,d84,tT6,eT6,f40,$T1;var i84=d(()=>{s0();Lw();K5();hw=L.lazy(()=>L.union([L.null(),L.string(),L.number(),L.boolean(),L.record(L.string(),hw),L.array(hw)])),e7=L.record(L.string(),L.record(L.string(),hw)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),p84=L.object({type:L.literal("text"),text:L.string().describe("The text content"),providerOptions:e7}),_T6=L.object({type:L.literal("text"),text:L.string().describe("The text content"),providerMetadata:L.any().optional().describe("Additional provider-specific metadata")}),yT6=L.string().describe("File data as URL string"),c84=L.object({type:L.literal("file"),filename:L.string().optional().describe("Optional filename of the file"),data:yT6,mediaType:L.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:e7}),fT6=L.object({type:L.literal("file"),mediaType:L.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),data:L.string().describe("Generated file data as base64 encoded string")}),bT6=L.object({type:L.literal("reasoning"),text:L.string().describe("The reasoning text"),providerOptions:e7}),hT6=L.object({type:L.literal("reasoning"),text:L.string().describe("The reasoning text"),providerMetadata:L.any().optional().describe("Additional provider-specific metadata")}),xT6=L.object({type:L.literal("tool-call"),toolCallId:L.string().describe("ID of the tool call, used to match with tool result"),toolName:L.string().describe("Name of the tool being called"),input:L.string().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:L.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:e7}),gT6=L.object({type:L.literal("tool-call"),toolCallId:L.string().describe("ID of the tool call"),toolName:L.string().describe("Name of the tool being called"),input:L.string().describe("Stringified JSON object with the tool call arguments"),providerExecuted:L.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerMetadata:L.any().optional().describe("Additional provider-specific metadata")}),uT6=L.union([L.object({type:L.literal("text"),value:L.string()}),L.object({type:L.literal("json"),value:hw}),L.object({type:L.literal("error-text"),value:L.string()}),L.object({type:L.literal("error-json"),value:hw}),L.object({type:L.literal("content"),value:L.array(L.union([L.object({type:L.literal("text"),text:L.string().describe("Text content")}),L.object({type:L.literal("media"),data:L.string().describe("Base-64 encoded media data"),mediaType:L.string().describe("IANA media type")})]))})]),n84=L.object({type:L.literal("tool-result"),toolCallId:L.string().describe("ID of the tool call that this result is associated with"),toolName:L.string().describe("Name of the tool that generated this result"),output:uT6.describe("Result of the tool call"),result:L.unknown().describe("Unknown result of the tool call"),providerOptions:e7}),mT6=L.object({type:L.literal("tool-result"),toolCallId:L.string().describe("ID of the tool call that this result is associated with"),toolName:L.string().describe("Name of the tool that generated this result"),result:L.any().describe("Result of the tool call (JSON-serializable)"),isError:L.boolean().optional().describe("Whether the result is an error or error message"),providerExecuted:L.boolean().optional().describe("Whether the tool result was generated by the provider"),providerMetadata:L.any().optional().describe("Additional provider-specific metadata")}),lT6=L.union([L.object({type:L.literal("source"),sourceType:L.literal("url"),id:L.string().describe("The ID of the source"),url:L.string().describe("The URL of the source"),title:L.string().optional().describe("The title of the source"),providerMetadata:L.any().optional().describe("Additional provider-specific metadata")}),L.object({type:L.literal("source"),sourceType:L.literal("document"),id:L.string().describe("The ID of the source"),mediaType:L.string().describe("IANA media type of the document (e.g., application/pdf)"),title:L.string().describe("The title of the document"),filename:L.string().optional().describe("Optional filename of the document"),providerMetadata:L.any().optional().describe("Additional provider-specific metadata")})]),dT6=L.object({role:L.literal("system"),content:L.string().describe("System message content"),providerOptions:e7}),pT6=L.object({role:L.literal("user"),content:L.array(L.union([p84,c84])).describe("User message content parts (text or file)"),providerOptions:e7}),cT6=L.object({role:L.literal("assistant"),content:L.array(L.union([p84,c84,bT6,xT6,n84])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:e7}),nT6=L.object({role:L.literal("tool"),content:L.array(n84).describe("Tool message content (tool results)"),providerOptions:e7}),iT6=L.union([dT6,pT6,cT6,nT6]),aT6=L.array(iT6).describe("A list of messages forming the prompt"),rT6=L.object({prompt:aT6.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:L.number().optional().describe("Maximum number of tokens to generate"),temperature:L.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:L.number().optional().describe("Nucleus sampling parameter"),topK:L.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:L.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:L.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:L.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:L.array(L.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:L.union([L.object({type:L.literal("text")}),L.object({type:L.literal("json"),schema:L.any().optional().describe("JSON schema that the generated output should conform to"),name:L.string().optional().describe("Name of output that should be generated"),description:L.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:L.array(L.any()).optional().describe("The tools that are available for the model"),toolChoice:L.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:L.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:L.any().optional().describe("Abort signal for cancelling the operation"),providerOptions:L.any().optional().describe("Additional provider-specific options")}),oT6=L.object({content:L.array(L.union([_T6,fT6,hT6,gT6,mT6,lT6])).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:L.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:L.looseObject({inputTokens:L.number().optional(),outputTokens:L.number().optional(),totalTokens:L.number().optional(),reasoningTokens:L.number().optional()}).describe("Usage information for the language model call"),providerMetadata:L.any().optional().describe("Additional provider-specific metadata"),request:L.object({body:L.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:L.object({id:L.string().optional().describe("ID for the generated response"),timestamp:L.iso.datetime().optional().describe("Timestamp for the start of the generated response"),modelId:L.string().optional().describe("The ID of the response model that was used"),headers:L.record(L.string(),L.string()).optional().describe("Response headers"),body:L.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:L.array(L.any()).describe("Warnings for the call, e.g. unsupported settings")}),ZT1=L.object({stream:L.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:L.object({body:L.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:L.object({headers:L.record(L.string(),L.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),sT6=L.object({supportedUrls:L.record(L.string(),L.array(L.string())).describe("Supported URL patterns by media type for the provider")}),KT1=L.object({modelId:L.string().describe("The ID of the model"),logo:L.string().nullable(),description:L.string().nullable(),capabilities:L.array(L.string()),limits:L.object({contextWindow:L.number(),maxOutputTokens:L.number()}).nullable(),costs:L.object({input:L.number(),output:L.number()}).nullable(),provider:L.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),d84=L.object({modelId:L.string().describe("The ID of the model"),callOptions:rT6}),tT6=wz.extend({logo:L.string().nullable(),description:L.string().nullable(),capabilities:L.array(L.string()),limits:L.object({contextWindow:L.number(),maxOutputTokens:L.number()}).nullable(),costs:L.object({input:L.number(),output:L.number()}).nullable(),provider:L.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),eT6=Mz("llm",tT6,{readOnly:!0}),f40=[{name:"LLM_METADATA",inputSchema:L.object({modelId:L.string().describe("The ID of the model")}),outputSchema:sT6},{name:"LLM_DO_STREAM",inputSchema:d84,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:d84,outputSchema:oT6},...eT6],$T1=s3(f40)});function YA6(X){let Y=[],Q=0;while(Q<X.length){let J=X[Q];if(J==="%")Y.push(".*");else if(J==="_")Y.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))Y.push("\\"+J);else Y.push(J);Q++}return Y.join("")}function GK(X){return typeof X==="string"||typeof X==="number"}function gk(X,Y){if("conditions"in Y){let{operator:K,conditions:$}=Y;switch(K){case"and":return $.every((H)=>gk(X,H));case"or":return $.some((H)=>gk(X,H));case"not":return!$.every((H)=>gk(X,H));default:return!0}}let{field:Q,operator:J,value:G}=Y,Z=Q.join("."),W=b40(X,Z);switch(J){case"eq":return W===G;case"gt":return GK(W)&&GK(G)&&W>G;case"gte":return GK(W)&&GK(G)&&W>=G;case"lt":return GK(W)&&GK(G)&&W<G;case"lte":return GK(W)&&GK(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 K=YA6(G);return new RegExp(`^${K}$`,"i").test(W);case"contains":if(typeof W!=="string"||typeof G!=="string")return!1;return W.toLowerCase().includes(G.toLowerCase());default:return!0}}function b40(X,Y){let Q=Y.split("."),J=X;for(let G of Q){if(J==null||typeof J!=="object")return;J=J[G]}return J}function QA6(X,Y){return[...X].sort((Q,J)=>{for(let G of Y){let Z=G.field.join("."),W=b40(Q,Z),K=b40(J,Z),$=0;if(W==null&&K==null)continue;if(W==null)$=G.nulls==="first"?-1:1;else if(K==null)$=G.nulls==="first"?1:-1;else if(typeof W==="string"&&typeof K==="string")$=W.localeCompare(K);else if(typeof W==="number"&&typeof K==="number")$=W-K;else $=String(W).localeCompare(String(K));if($!==0)return G.direction==="desc"?-$:$}return 0})}var XA6,JA6,GA6,h40;var a84=d(()=>{y40();l84();K5();i84();s0();s4();uZ();XA6={LLM:f40,ASSISTANTS:m84};JA6=t3.extend({binding:L.union([L.object({}).passthrough(),L.string()]).optional()}),GA6=e3(HJ),h40=r0({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",inputSchema:JA6,outputSchema:GA6,handler:async(X,Y)=>{await Y.access.check();let Q=I4(Y),J=X.binding?typeof X.binding==="string"?(()=>{let U=XA6[X.binding.toUpperCase()];if(!U)throw Error(`Unknown binding: ${X.binding}`);return U})():X.binding:void 0,G=J?xk(J):void 0,W=(await Y.storage.connections.list(Q.id)).filter((U)=>U.connection_type!=="VIRTUAL"),K=G?await Promise.all(W.map(async(U)=>{if(!U.tools||U.tools.length===0)return null;return G.isImplementedBy(U.tools.map((N)=>({name:N.name,inputSchema:N.inputSchema,outputSchema:N.outputSchema})))?U:null})).then((U)=>U.filter((D)=>D!==null)):W;if(X.where)K=K.filter((U)=>gk(U,X.where));if(X.orderBy&&X.orderBy.length>0)K=QA6(K,X.orderBy);let $=K.length,H=X.offset??0,F=X.limit??100,q=K.slice(H,H+F),V=H+F<$;return{items:q,totalCount:$,hasMore:V}}})});var WA6,x40;var r84=d(()=>{K5();s4();uZ();WA6=Pw(HJ),x40=r0({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",inputSchema:Mw,outputSchema:WA6,handler:async(X,Y)=>{let Q=I4(Y);await Y.access.check();let J=await Y.storage.connections.findById(X.id);if(!J||J.organization_id!==Q.id)return{item:null};return{item:J}}})});var uk=(X,Y)=>{if(Y===null||Y===void 0)return;let Q=X.replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),J=Y;for(let G of Q){if(J===null||J===void 0||typeof J!=="object")return;J=J[G]}return J};function o84(X){let Y=X.split("::");if(Y.length!==2||!Y[0]||!Y[1])throw Error(`Invalid scope format: ${X}. Expected format: "KEY::SCOPE"`);return Y}function ZA6(X){let Y=X.split("::");if(Y.length!==2||!Y[0]||!Y[1])return null;return Y}function KA6(X){if(typeof X==="object"&&X!==null&&"value"in X){let Y=X.value;if(typeof Y==="string")return Y}return null}function $A6(X,Y){let Q={};if(!X||!Y)return Q;for(let J of Y){if(J==="*"){Q["*"]=["*"];continue}let G=ZA6(J);if(!G)continue;let[Z,W]=G,K=uk(Z,X),$=KA6(K);if($){if(!Q[$])Q[$]=[];Q[$].push(W)}}return Q}function s84(X,Y){let Q=$A6(X,Y);return new Set(Object.keys(Q).filter((J)=>J!=="*"))}var t84=()=>{};class g40{db;vault;constructor(X,Y){this.db=X;this.vault=Y}async get(X){let Y=await this.db.selectFrom("downstream_tokens").selectAll().where("connectionId","=",X).executeTakeFirst();if(!Y)return null;return this.decryptToken(Y)}async upsert(X){let Y=new Date().toISOString(),Q=await this.vault.encrypt(X.accessToken),J=X.refreshToken?await this.vault.encrypt(X.refreshToken):null,G=X.clientSecret?await this.vault.encrypt(X.clientSecret):null;return await this.db.transaction().execute(async(Z)=>{let W=await Z.selectFrom("downstream_tokens").select(["id","createdAt"]).where("connectionId","=",X.connectionId).executeTakeFirst();if(W)return await Z.updateTable("downstream_tokens").set({accessToken:Q,refreshToken:J,scope:X.scope,expiresAt:X.expiresAt?.toISOString()??null,clientId:X.clientId,clientSecret:G,tokenEndpoint:X.tokenEndpoint,updatedAt:Y}).where("id","=",W.id).execute(),{id:W.id,connectionId:X.connectionId,accessToken:X.accessToken,refreshToken:X.refreshToken,scope:X.scope,expiresAt:X.expiresAt,createdAt:W.createdAt,updatedAt:Y,clientId:X.clientId,clientSecret:X.clientSecret,tokenEndpoint:X.tokenEndpoint};let K=RV("dtok");return await Z.insertInto("downstream_tokens").values({id:K,connectionId:X.connectionId,accessToken:Q,refreshToken:J,scope:X.scope,expiresAt:X.expiresAt?.toISOString()??null,clientId:X.clientId,clientSecret:G,tokenEndpoint:X.tokenEndpoint,createdAt:Y,updatedAt:Y}).execute(),{id:K,connectionId:X.connectionId,accessToken:X.accessToken,refreshToken:X.refreshToken,scope:X.scope,expiresAt:X.expiresAt,createdAt:Y,updatedAt:Y,clientId:X.clientId,clientSecret:X.clientSecret,tokenEndpoint:X.tokenEndpoint}})}async delete(X){await this.db.deleteFrom("downstream_tokens").where("connectionId","=",X).execute()}isExpired(X,Y=0){if(!X.expiresAt)return!1;let J=(X.expiresAt instanceof Date?X.expiresAt:new Date(X.expiresAt)).getTime();if(Number.isNaN(J))return!0;return J-Y<Date.now()}async decryptToken(X){let Y=await this.vault.decrypt(X.accessToken),Q=X.refreshToken?await this.vault.decrypt(X.refreshToken):null,J=X.clientSecret?await this.vault.decrypt(X.clientSecret):null;return{id:X.id,connectionId:X.connectionId,accessToken:Y,refreshToken:Q,scope:X.scope,expiresAt:X.expiresAt,createdAt:X.createdAt,updatedAt:X.updatedAt,clientId:X.clientId,clientSecret:J,tokenEndpoint:X.tokenEndpoint}}}var e84=d(()=>{vS()});async function qA6(X,Y,Q,J){for(let Z of Y){if(Z==="*")continue;let[W]=o84(Z),K=uk(W,X);if(K===void 0||K===null)throw Error(`Scope references key "${W}" but it's not present in state`)}let G=s84(X,Y);for(let Z of G){if(Z===k3.SELF)continue;let W=await J.storage.connections.findById(Z);if(!W||W.organization_id!==Q)throw Error(`Referenced connection not found: ${Z}`);try{await J.access.check(Z)}catch(K){throw Error(`Access denied to referenced connection: ${Z}. ${K.message}`)}}}var HA6,FA6,u40;var X94=d(()=>{t84();CS();e84();s0();s4();Ck();uZ();HA6=L.object({id:L.string().describe("ID of the connection to update"),data:Ir0.describe("Partial connection data to update")}),FA6=L.object({item:HJ.describe("The updated connection entity")});u40=r0({name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update an existing MCP connection in the organization",inputSchema:HA6,outputSchema:FA6,handler:async(X,Y)=>{H4(Y);let Q=I4(Y);if(await Y.access.check(),!A8(Y))throw Error("User ID required to update connection");let{id:G,data:Z}=X,W=await Y.storage.connections.findById(G);if(!W||W.organization_id!==Q.id)throw Error("Connection not found in organization");let K=Z.connection_type??W.connection_type,$=Z.connection_url??W.connection_url;if(K==="VIRTUAL"){let O=RS($);if(!O)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let w=await Y.storage.virtualMcps.findById(O);if(!w)throw Error(`Virtual MCP not found: ${O}`);if(w.organization_id!==Q.id)throw Error("Virtual MCP does not belong to the current organization");$=SS(O)}let H=Z.configuration_state??W.configuration_state,F=Z.configuration_scopes??W.configuration_scopes??[];if(Z.configuration_state!==void 0||Z.configuration_scopes!==void 0){if(Z.configuration_state!==void 0)H=Z.configuration_state;else if(H===null)H={};if(Z.configuration_scopes!==void 0)F=Z.configuration_scopes??[];if(F.length>0&&H)await qA6(H,F,Q.id,Y)}let q=Z.connection_token??W.connection_token;if(!q)try{let w=await new g40(Y.db,Y.vault).get(G);if(w?.accessToken)q=w.accessToken}catch{}let V=await Uz({id:W.id,title:Z.title??W.title,connection_type:K,connection_url:$,connection_token:q,connection_headers:Z.connection_headers??W.connection_headers}).catch(()=>null),U=V?.length?V:null,D={...Z,connection_url:$,tools:U,configuration_state:H,configuration_scopes:F},N=await Y.storage.connections.update(G,D);if((Z.configuration_state!==void 0||Z.configuration_scopes!==void 0)&&H&&F.length>0)try{await(await Y.createMCPProxy(G)).client.callTool({name:"ON_MCP_CONFIGURATION",arguments:{state:H,scopes:F}})}catch(O){console.error("Failed to invoke ON_MCP_CONFIGURATION callback",O)}return{item:N}}})});var m40;var Y94=d(()=>{K5();s4();uZ();m40=r0({name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete a connection",inputSchema:Tw,outputSchema:Aw(HJ),handler:async(X,Y)=>{H4(Y);let Q=I4(Y);await Y.access.check();let J=await Y.storage.connections.findById(X.id);if(!J)throw Error(`Connection not found: ${X.id}`);if(J.organization_id!==Q.id)throw Error("Connection not found in organization");return await Y.storage.connections.delete(X.id),{item:J}}})});var l40;var Q94=d(()=>{s0();s4();l40=r0({name:"CONNECTION_TEST",description:"Test connection health and latency",inputSchema:L.object({id:L.string()}),outputSchema:L.object({id:L.string(),healthy:L.boolean(),latencyMs:L.number()}),handler:async(X,Y)=>{let Q=I4(Y);await Y.access.check();let J=await Y.storage.connections.findById(X.id);if(!J||J.organization_id!==Q.id)throw Error("Connection not found");let G=await Y.storage.connections.testConnection(X.id);return{id:X.id,...G}}})});var J94=d(()=>{F84();a84();r84();X94();Y94();Q94()});import{sql as p6}from"kysely";function G94(X){if(X===null||X===void 0)return"NULL";if(typeof X==="number")return String(X);if(typeof X==="boolean")return X?"TRUE":"FALSE";if(typeof X==="string")return`'${X.replace(/'/g,"''")}'`;if(X instanceof Date)return`'${X.toISOString()}'`;return`'${JSON.stringify(X).replace(/'/g,"''")}'`}function UA6(X,Y){let Q=X;for(let G=Y.length;G>=1;G--){let Z=`$${G}`;if(Q.includes(Z))Q=Q.replaceAll(Z,G94(Y[G-1]))}let J=[];for(let G=0;G<Q.length;G++)if(Q[G]==="?")J.push(G);for(let G=Math.min(J.length,Y.length)-1;G>=0;G--){let Z=J[G],W=G94(Y[G]);Q=Q.slice(0,Z)+W+Q.slice(Z+1)}return Q}function W94(X){return X.replace(/-/g,"_")}function DA6(X){return`app_${W94(X)}`}function NA6(X){return`app_role_${W94(X)}`}function OA6(X){if(X instanceof Error){let Y=X.message.toLowerCase(),Q=X.code;return Q==="3F000"||Q==="42704"||Y.includes("schema")&&Y.includes("does not exist")||Y.includes("role")&&Y.includes("does not exist")}return!1}async function LA6(X,Y,Q){if(await p6`CREATE SCHEMA IF NOT EXISTS ${p6.id(Y)}`.execute(X),!(await p6`
|
|
368
368
|
SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${Q}) as exists
|
|
369
|
-
`.execute(X)).rows[0]?.exists)await p6`CREATE ROLE ${p6.id(Q)} NOLOGIN`.execute(X);await p6`GRANT ${p6.id(Q)} TO CURRENT_USER`.execute(X),await p6`GRANT USAGE, CREATE ON SCHEMA ${p6.id(Y)} TO ${p6.id(Q)}`.execute(X),await p6`GRANT ALL ON ALL TABLES IN SCHEMA ${p6.id(Y)} TO ${p6.id(Q)}`.execute(X),await p6`GRANT ALL ON ALL SEQUENCES IN SCHEMA ${p6.id(Y)} TO ${p6.id(Q)}`.execute(X),await p6`ALTER DEFAULT PRIVILEGES IN SCHEMA ${p6.id(Y)} GRANT ALL ON TABLES TO ${p6.id(Q)}`.execute(X),await p6`ALTER DEFAULT PRIVILEGES IN SCHEMA ${p6.id(Y)} GRANT ALL ON SEQUENCES TO ${p6.id(Q)}`.execute(X),await p6`REVOKE ALL ON SCHEMA public FROM ${p6.id(Q)}`.execute(X)}async function wA6(X,Y,Q,J){try{return await X.transaction().execute(async(G)=>{return await p6`SET LOCAL ROLE ${p6.id(Q)}`.execute(G),await p6`SET LOCAL search_path TO ${p6.id(Y)}`.execute(G),await p6.raw(J).execute(G)})}catch(G){if(OA6(G))return await LA6(X,Y,Q),await X.transaction().execute(async(Z)=>{return await p6`SET LOCAL ROLE ${p6.id(Q)}`.execute(Z),await p6`SET LOCAL search_path TO ${p6.id(Y)}`.execute(Z),await p6.raw(J).execute(Z)});throw G}}var zA6,BA6,Z94;var K94=d(()=>{s0();s4();zA6=L.object({results:L.array(L.unknown()).optional(),success:L.boolean().optional()});BA6=L.object({sql:L.string().describe("The SQL query to run"),params:L.array(L.any()).describe("The parameters to pass to the SQL query").optional()});Z94=r0({name:"DATABASES_RUN_SQL",description:"Run a SQL query against the database",inputSchema:BA6,outputSchema:L.object({result:L.array(zA6)}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=UA6(X.sql,X.params||[]);if(!Y.connectionId)throw Error("Connection context required for database access");let J=DA6(Y.connectionId),G=NA6(Y.connectionId);return{result:[{results:(await wA6(Y.db,J,G,Q)).rows,success:!0}]}}})});var $94,PA6,H94;var XW=d(()=>{s0();y40();$94=L.object({connectionId:L.string().optional().describe("Filter subscriptions by connection ID (optional)")}),PA6=L.object({id:L.string().describe("Subscription ID"),connectionId:L.string().describe("Subscriber connection ID"),eventType:L.string().describe("Event type pattern"),publisher:L.string().nullable().describe("Publisher connection filter (null = all publishers)"),filter:L.string().nullable().describe("JSONPath filter expression"),enabled:L.boolean().describe("Whether subscription is enabled"),createdAt:L.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:L.string().datetime().describe("Updated timestamp (ISO 8601)")}),H94=L.object({subscriptions:L.array(PA6).describe("List of subscriptions")})});var d40;var F94=d(()=>{s4();XW();d40=r0({name:"EVENT_PUBLISH",description:"Publish an event to the event bus. Supports immediate, scheduled (deliverAt), and recurring (cron) delivery. The source is automatically set to the caller's connection ID.",inputSchema:Ew,outputSchema:Iw,handler:async(X,Y)=>{H4(Y);let Q=I4(Y);await Y.access.check();let J=Y.connectionId;if(!J)throw Error("Connection ID required to publish events. Use a connection-scoped token.");let G=await Y.eventBus.publish(Q.id,J,{type:X.type,subject:X.subject,data:X.data,deliverAt:X.deliverAt,cron:X.cron});return{id:G.id,type:G.type,source:G.source,time:G.time}}})});var p40;var q94=d(()=>{s4();XW();p40=r0({name:"EVENT_SUBSCRIBE",description:"Subscribe to events of a specific type. The subscriber is automatically set to the caller's connection.",inputSchema:jw,outputSchema:Cw,handler:async(X,Y)=>{H4(Y);let Q=I4(Y);await Y.access.check();let J=Y.connectionId;if(!J)throw Error("Connection ID required to subscribe. Use a connection-scoped token.");let G=await Y.eventBus.subscribe(Q.id,{connectionId:J,eventType:X.eventType,publisher:X.publisher,filter:X.filter});return{subscription:{id:G.id,connectionId:G.connectionId,eventType:G.eventType,publisher:G.publisher,filter:G.filter,enabled:G.enabled,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}}}})});var c40;var V94=d(()=>{s4();XW();c40=r0({name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events by removing a subscription.",inputSchema:vw,outputSchema:kw,handler:async(X,Y)=>{H4(Y);let Q=I4(Y);await Y.access.check();let J=Y.connectionId;if(!J)throw Error("Connection ID required to unsubscribe. Use a connection-scoped token.");let G=await Y.eventBus.getSubscription(Q.id,X.subscriptionId);if(!G)throw Error(`Subscription not found: ${X.subscriptionId}`);if(G.connectionId!==J)throw Error("Cannot unsubscribe from a subscription owned by another connection");return{success:(await Y.eventBus.unsubscribe(Q.id,X.subscriptionId)).success,subscriptionId:X.subscriptionId}}})});var n40;var z94=d(()=>{s4();XW();n40=r0({name:"EVENT_CANCEL",description:"Cancel a recurring event to stop future deliveries. Only the publisher can cancel their own events.",inputSchema:_w,outputSchema:yw,handler:async(X,Y)=>{H4(Y);let Q=I4(Y);await Y.access.check();let J=Y.connectionId;if(!J)throw Error("Connection ID required to cancel events. Use a connection-scoped token.");if(!await Y.eventBus.getEvent(Q.id,X.eventId))throw Error(`Event not found: ${X.eventId}`);if(!(await Y.eventBus.cancelEvent(Q.id,X.eventId,J)).success)throw Error("Failed to cancel event. Either the event is already completed/failed, or you are not the publisher.");return{success:!0,eventId:X.eventId}}})});var i40;var U94=d(()=>{s4();XW();i40=r0({name:"EVENT_ACK",description:"Acknowledge delivery of an event. Call after successfully processing an event received via ON_EVENTS with retryAfter.",inputSchema:fw,outputSchema:bw,handler:async(X,Y)=>{H4(Y);let Q=I4(Y);await Y.access.check();let J=Y.connectionId;if(!J)throw Error("Connection ID required to acknowledge events. Use a connection-scoped token.");if(!(await Y.eventBus.ackEvent(Q.id,X.eventId,J)).success)throw Error("Failed to acknowledge event. Either the event was not found, already delivered, or you are not a subscriber.");return{success:!0,eventId:X.eventId}}})});var a40;var B94=d(()=>{s4();XW();a40=r0({name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions, optionally filtered by connection ID.",inputSchema:$94,outputSchema:H94,handler:async(X,Y)=>{H4(Y);let Q=I4(Y);return await Y.access.check(),{subscriptions:(await Y.eventBus.listSubscriptions(Q.id,X.connectionId)).map((G)=>({id:G.id,connectionId:G.connectionId,eventType:G.eventType,publisher:G.publisher,filter:G.filter,enabled:G.enabled,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}))}}})});var r40;var D94=d(()=>{s4();XW();r40=r0({name:"EVENT_SYNC_SUBSCRIPTIONS",description:"Sync subscriptions to desired state. Creates new, deletes removed, updates changed filters. Subscriptions are identified by (eventType, publisher).",inputSchema:Rw,outputSchema:Sw,handler:async(X,Y)=>{H4(Y);let Q=I4(Y);await Y.access.check();let J=Y.connectionId;if(!J)throw Error("Connection ID required to sync subscriptions. Use a connection-scoped token.");let G=await Y.eventBus.syncSubscriptions(Q.id,{connectionId:J,subscriptions:X.subscriptions});return{created:G.created,updated:G.updated,deleted:G.deleted,unchanged:G.unchanged,subscriptions:G.subscriptions.map((Z)=>({id:Z.id,connectionId:Z.connectionId,eventType:Z.eventType,publisher:Z.publisher,filter:Z.filter,enabled:Z.enabled,createdAt:Z.createdAt instanceof Date?Z.createdAt.toISOString():Z.createdAt,updatedAt:Z.updatedAt instanceof Date?Z.updatedAt.toISOString():Z.updatedAt}))}}})});var N94=d(()=>{F94();q94();V94();z94();U94();B94();D94();XW()});var o40,AA6,jG,O94,L94;var Pz=d(()=>{s0();o40=L.enum(["inclusion","exclusion"]).describe("Tool selection mode: 'inclusion' = include selected (default), 'exclusion' = exclude selected"),AA6=L.object({connection_id:L.string().describe("Connection ID"),selected_tools:L.array(L.string()).nullable().describe("Selected tool names. With 'inclusion' mode: null = all tools included. With 'exclusion' mode: null = entire connection excluded"),selected_resources:L.array(L.string()).nullable().describe("Selected resource URIs or patterns. Supports * and ** wildcards for pattern matching. With 'inclusion' mode: null = all resources included."),selected_prompts:L.array(L.string()).nullable().describe("Selected prompt names. With 'inclusion' mode: null = all prompts included. With 'exclusion' mode: null = entire connection excluded.")}),jG=L.object({id:L.string().describe("Unique identifier for the virtual MCP"),title:L.string().describe("Human-readable name for the virtual MCP"),description:L.string().nullable().describe("Description of the virtual MCP"),icon:L.string().nullable().optional().describe("Icon URL for the virtual MCP"),created_at:L.string().describe("When the virtual MCP was created"),updated_at:L.string().describe("When the virtual MCP was last updated"),created_by:L.string().describe("User ID who created the virtual MCP"),updated_by:L.string().optional().describe("User ID who last updated the virtual MCP"),organization_id:L.string().describe("Organization ID this virtual MCP belongs to"),tool_selection_mode:o40.describe("Tool selection mode: 'inclusion' = include selected, 'exclusion' = exclude selected"),status:L.enum(["active","inactive"]).describe("Current status"),connections:L.array(AA6).describe("Connections with their selected tools (behavior depends on tool_selection_mode)")}),O94=L.object({title:L.string().min(1).max(255).describe("Name for the virtual MCP"),description:L.string().nullable().optional().describe("Optional description"),tool_selection_mode:o40.optional().default("inclusion").describe("Tool selection mode (defaults to 'inclusion')"),icon:L.string().nullable().optional().describe("Optional icon URL"),status:L.enum(["active","inactive"]).optional().default("active").describe("Initial status"),connections:L.array(L.object({connection_id:L.string().describe("Connection ID"),selected_tools:L.array(L.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools or full exclusion)"),selected_resources:L.array(L.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources)"),selected_prompts:L.array(L.string()).nullable().optional().describe("Selected prompt names (null/undefined = all prompts or full exclusion)")})).describe("Connections to include/exclude (can be empty for exclusion mode)")}),L94=L.object({title:L.string().min(1).max(255).optional().describe("New name"),description:L.string().nullable().optional().describe("New description (null to clear)"),tool_selection_mode:o40.optional().describe("New tool selection mode"),icon:L.string().nullable().optional().describe("New icon URL (null to clear)"),status:L.enum(["active","inactive"]).optional().describe("New status"),connections:L.array(L.object({connection_id:L.string().describe("Connection ID"),selected_tools:L.array(L.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools or full exclusion)"),selected_resources:L.array(L.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources)"),selected_prompts:L.array(L.string()).nullable().optional().describe("Selected prompt names (null/undefined = all prompts or full exclusion)")})).optional().describe("New connections (replaces existing)")})});var EA6,IA6,s40;var w94=d(()=>{s0();s4();Pz();EA6=L.object({data:O94.describe("Data for the new virtual MCP")}),IA6=L.object({item:jG.describe("The created virtual MCP entity")}),s40=r0({name:"COLLECTION_VIRTUAL_MCP_CREATE",description:"Create a new MCP virtual MCP in the organization",inputSchema:EA6,outputSchema:IA6,handler:async(X,Y)=>{H4(Y);let Q=I4(Y);await Y.access.check();let J=A8(Y);if(!J)throw Error("User ID required to create virtual MCP");return{item:await Y.storage.virtualMcps.create(Q.id,J,X.data)}}})});function jA6(X){let Y=[],Q=0;while(Q<X.length){let J=X[Q];if(J==="%")Y.push(".*");else if(J==="_")Y.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))Y.push("\\"+J);else Y.push(J);Q++}return Y.join("")}function WK(X){return typeof X==="string"||typeof X==="number"}function t40(X,Y){let Q=Y.split("."),J=X;for(let G of Q){if(J==null||typeof J!=="object")return;J=J[G]}return J}function CA6(X,Y){return X.connections.some((Q)=>Q.connection_id===Y)}function mk(X,Y){if("conditions"in Y){let{operator:K,conditions:$}=Y;switch(K){case"and":return $.every((H)=>mk(X,H));case"or":return $.some((H)=>mk(X,H));case"not":return!$.every((H)=>mk(X,H));default:return!0}}let{field:Q,operator:J,value:G}=Y,Z=Q.join(".");if(Z==="connection_id"){if(J!=="eq"||typeof G!=="string")return!1;return CA6(X,G)}let W=t40(X,Z);switch(J){case"eq":return W===G;case"gt":return WK(W)&&WK(G)&&W>G;case"gte":return WK(W)&&WK(G)&&W>=G;case"lt":return WK(W)&&WK(G)&&W<G;case"lte":return WK(W)&&WK(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 K=jA6(G);return new RegExp(`^${K}$`,"i").test(W);case"contains":if(typeof W!=="string"||typeof G!=="string")return!1;return W.toLowerCase().includes(G.toLowerCase());default:return!0}}function RA6(X,Y){return[...X].sort((Q,J)=>{for(let G of Y){let Z=G.field.join("."),W=t40(Q,Z),K=t40(J,Z),$=0;if(W==null&&K==null)continue;if(W==null)$=G.nulls==="first"?-1:1;else if(K==null)$=G.nulls==="first"?1:-1;else if(typeof W==="string"&&typeof K==="string")$=W.localeCompare(K);else if(typeof W==="number"&&typeof K==="number")$=W-K;else $=String(W).localeCompare(String(K));if($!==0)return G.direction==="desc"?-$:$}return 0})}var SA6,vA6,e40;var M94=d(()=>{K5();s4();Pz();SA6=t3,vA6=e3(jG),e40=r0({name:"COLLECTION_VIRTUAL_MCP_LIST",description:"List all MCP virtual MCPs in the organization",inputSchema:SA6,outputSchema:vA6,handler:async(X,Y)=>{await Y.access.check();let Q=I4(Y),J=X.where&&!("conditions"in X.where)&&X.where.field.join(".")==="connection_id"&&X.where.operator==="eq"&&typeof X.where.value==="string"?X.where.value:void 0,Z=J?await Y.storage.virtualMcps.listByConnectionId(Q.id,J):await Y.storage.virtualMcps.list(Q.id);if(X.where)Z=Z.filter((q)=>mk(q,X.where));if(X.orderBy&&X.orderBy.length>0)Z=RA6(Z,X.orderBy);let W=Z.length,K=X.offset??0,$=X.limit??100,H=Z.slice(K,K+$),F=K+$<W;return{items:H,totalCount:W,hasMore:F}}})});var kA6,_A6,X60;var P94=d(()=>{s0();s4();Pz();kA6=L.object({id:L.string().describe("ID of the virtual MCP to retrieve")}),_A6=L.object({item:jG.nullable().describe("The retrieved virtual MCP, or null if not found")}),X60=r0({name:"COLLECTION_VIRTUAL_MCP_GET",description:"Get an MCP virtual MCP by ID",inputSchema:kA6,outputSchema:_A6,handler:async(X,Y)=>{H4(Y);let Q=I4(Y);await Y.access.check();let J=await Y.storage.virtualMcps.findById(X.id);if(J&&J.organization_id!==Q.id)return{item:null};if(!J)return{item:null};return{item:J}}})});var yA6,fA6,Y60;var T94=d(()=>{s0();s4();Pz();yA6=L.object({id:L.string().describe("ID of the virtual MCP to update"),data:L94.describe("Partial virtual MCP data to update")}),fA6=L.object({item:jG.describe("The updated virtual MCP entity")}),Y60=r0({name:"COLLECTION_VIRTUAL_MCP_UPDATE",description:"Update an MCP virtual MCP",inputSchema:yA6,outputSchema:fA6,handler:async(X,Y)=>{H4(Y);let Q=I4(Y);await Y.access.check();let J=A8(Y);if(!J)throw Error("User ID required to update virtual MCP");let G=await Y.storage.virtualMcps.findById(X.id);if(!G)throw Error(`Virtual MCP not found: ${X.id}`);if(G.organization_id!==Q.id)throw Error(`Virtual MCP not found: ${X.id}`);return{item:await Y.storage.virtualMcps.update(X.id,J,X.data)}}})});var bA6,hA6,Q60;var A94=d(()=>{s0();s4();Pz();bA6=L.object({id:L.string().describe("ID of the virtual MCP to delete")}),hA6=L.object({item:jG.describe("The deleted virtual MCP entity")}),Q60=r0({name:"COLLECTION_VIRTUAL_MCP_DELETE",description:"Delete an MCP virtual MCP",inputSchema:bA6,outputSchema:hA6,handler:async(X,Y)=>{H4(Y);let Q=I4(Y);await Y.access.check();let J=await Y.storage.virtualMcps.findById(X.id);if(!J)throw Error(`Virtual MCP not found: ${X.id}`);if(J.organization_id!==Q.id)throw Error(`Virtual MCP not found: ${X.id}`);return await Y.storage.virtualMcps.delete(X.id),{item:J}}})});var E94=d(()=>{w94();M94();P94();T94();A94()});var gA6,J60;var I94=d(()=>{s4();s0();gA6=L.object({id:L.string().optional().describe("Unique log identifier"),organizationId:L.string().describe("Organization ID"),connectionId:L.string().describe("Connection ID"),connectionTitle:L.string().describe("Connection display name"),toolName:L.string().describe("Name of the tool that was called"),input:L.record(L.string(),L.unknown()).describe("Redacted tool input"),output:L.record(L.string(),L.unknown()).describe("Redacted tool output"),isError:L.boolean().describe("Whether the call resulted in an error"),errorMessage:L.string().nullish().describe("Error message if applicable"),durationMs:L.number().describe("Call duration in milliseconds"),timestamp:L.string().describe("ISO 8601 timestamp of the call"),userId:L.string().nullish().describe("User who triggered the call"),requestId:L.string().describe("Unique request identifier"),userAgent:L.string().nullish().describe("Client identifier (x-mesh-client header)"),virtualMcpId:L.string().nullish().describe("Virtual MCP (Agent) ID if routed through an agent"),properties:L.record(L.string(),L.string()).nullish().describe("Custom key-value metadata attached to the log")}),J60=r0({name:"MONITORING_LOGS_LIST",description:"List monitoring logs for tool calls in the organization",inputSchema:L.object({connectionId:L.string().optional().describe("Filter by connection ID"),virtualMcpId:L.string().optional().describe("Filter by Virtual MCP (Agent) ID"),toolName:L.string().optional().describe("Filter by tool name"),isError:L.boolean().optional().describe("Filter by error status"),startDate:L.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:L.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)"),limit:L.number().default(100).describe("Maximum number of results"),offset:L.number().default(0).describe("Offset for pagination"),properties:L.record(L.string(),L.string()).optional().describe("Filter by exact property key=value matches"),propertyKeys:L.array(L.string()).optional().describe("Filter by logs that have these property keys"),propertyPatterns:L.record(L.string(),L.string()).optional().describe("Filter by property value patterns (SQL LIKE, use % as wildcard)")}),outputSchema:L.object({logs:L.array(gA6).describe("Array of monitoring logs"),total:L.number().describe("Total number of logs matching filters"),offset:L.number().describe("Current offset for pagination"),limit:L.number().describe("Current limit for pagination")}),handler:async(X,Y)=>{let Q=I4(Y),G=X.properties||X.propertyKeys||X.propertyPatterns?{properties:X.properties,propertyKeys:X.propertyKeys,propertyPatterns:X.propertyPatterns}:void 0,Z={organizationId:Q.id,connectionId:X.connectionId,virtualMcpId:X.virtualMcpId,toolName:X.toolName,isError:X.isError,startDate:X.startDate?new Date(X.startDate):void 0,endDate:X.endDate?new Date(X.endDate):void 0,limit:X.limit,offset:X.offset,propertyFilters:G},W=await Y.storage.monitoring.query(Z);return{logs:W.logs.map((K)=>({...K,timestamp:K.timestamp instanceof Date?K.timestamp.toISOString():K.timestamp})),total:W.total,offset:X.offset,limit:X.limit}}})});var G60;var j94=d(()=>{s4();s0();G60=r0({name:"MONITORING_STATS",description:"Get aggregated statistics for tool call monitoring",inputSchema:L.object({startDate:L.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:L.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)")}),outputSchema:L.object({totalCalls:L.number().describe("Total number of tool calls"),errorRate:L.number().describe("Error rate as a decimal (0 to 1)"),avgDurationMs:L.number().describe("Average call duration in milliseconds"),errorRatePercent:L.string().describe("Error rate as a percentage string")}),handler:async(X,Y)=>{let J={organizationId:I4(Y).id,startDate:X.startDate?new Date(X.startDate):void 0,endDate:X.endDate?new Date(X.endDate):void 0},G=await Y.storage.monitoring.getStats(J);return{...G,errorRatePercent:(G.errorRate*100).toFixed(2)}}})});var C94=d(()=>{I94();j94()});var W60;var R94=d(()=>{s0();s4();W60=r0({name:"ORGANIZATION_CREATE",description:"Create a new organization",inputSchema:L.object({slug:L.string().min(1).max(50).regex(/^[a-z0-9-]+$/,"Slug must be lowercase alphanumeric with hyphens"),name:L.string().min(1).max(255),description:L.string().optional()}),outputSchema:L.object({id:L.string(),name:L.string(),slug:L.string(),logo:L.string().nullable().optional(),metadata:L.any().optional(),createdAt:L.string().datetime().describe("ISO 8601 timestamp"),members:L.array(L.any()).optional()}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=A8(Y);if(!Q)throw Error("User ID required to create organization");let J=await Y.boundAuth.organization.create({name:X.name,slug:X.slug,metadata:X.description?{description:X.description}:void 0,userId:Q});if(!J)throw Error("Failed to create organization");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var Z60;var S94=d(()=>{s0();s4();Z60=r0({name:"ORGANIZATION_LIST",description:"List all organizations user has access to",inputSchema:L.object({userId:L.string().optional()}),outputSchema:L.object({organizations:L.array(L.object({id:L.string(),name:L.string(),slug:L.string(),logo:L.string().nullable().optional(),metadata:L.any().optional(),createdAt:L.string().datetime().describe("ISO 8601 timestamp")}))}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=A8(Y),J=X.userId||Q;if(!J)throw Error("User ID required to list organizations");return{organizations:(await Y.boundAuth.organization.list(J)).map((Z)=>({...Z,createdAt:Z.createdAt instanceof Date?Z.createdAt.toISOString():Z.createdAt}))}}})});var K60;var v94=d(()=>{s0();s4();K60=r0({name:"ORGANIZATION_GET",description:"Get organization details by slug or ID",inputSchema:L.object({}),outputSchema:L.object({id:L.string(),name:L.string(),slug:L.string(),logo:L.string().nullable().optional(),metadata:L.any().optional(),createdAt:L.string().datetime().describe("ISO 8601 timestamp"),members:L.array(L.any()).optional(),invitations:L.array(L.any()).optional()}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=await Y.boundAuth.organization.get();if(!Q)throw Error("No active organization found");return{...Q,createdAt:Q.createdAt instanceof Date?Q.createdAt.toISOString():Q.createdAt}}})});var $60;var k94=d(()=>{s0();s4();$60=r0({name:"ORGANIZATION_UPDATE",description:"Update an existing organization",inputSchema:L.object({id:L.string(),slug:L.string().min(1).max(50).regex(/^[a-z0-9-]+$/).optional(),name:L.string().min(1).max(255).optional(),description:L.string().optional()}),outputSchema:L.object({id:L.string(),name:L.string(),slug:L.string(),logo:L.string().nullable().optional(),metadata:L.any().optional(),createdAt:L.string().datetime().describe("ISO 8601 timestamp")}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q={};if(X.name)Q.name=X.name;if(X.slug)Q.slug=X.slug;if(X.description)Q.metadata={description:X.description};let J=await Y.boundAuth.organization.update({organizationId:X.id,data:Q});if(!J)throw Error("Failed to update organization");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var H60;var _94=d(()=>{s0();s4();H60=r0({name:"ORGANIZATION_DELETE",description:"Delete an organization",inputSchema:L.object({id:L.string()}),outputSchema:L.object({success:L.boolean(),id:L.string()}),handler:async(X,Y)=>{return H4(Y),await Y.access.check(),await Y.boundAuth.organization.delete(X.id),{success:!0,id:X.id}}})});var xw;var F60=d(()=>{s0();xw=L.object({title:L.string(),url:L.string(),icon:L.string()})});var q60;var y94=d(()=>{s0();s4();F60();q60=r0({name:"ORGANIZATION_SETTINGS_GET",description:"Get organization-level settings",inputSchema:L.object({}),outputSchema:L.object({organizationId:L.string(),sidebar_items:L.array(xw).nullable().optional(),enabled_plugins:L.array(L.string()).nullable().optional(),createdAt:L.string().datetime().optional().describe("ISO 8601 timestamp"),updatedAt:L.string().datetime().optional().describe("ISO 8601 timestamp")}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=Y.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let J=await Y.storage.organizationSettings.get(Q);if(!J)return{organizationId:Q};return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt,updatedAt:J.updatedAt instanceof Date?J.updatedAt.toISOString():J.updatedAt}}})});var V60;var f94=d(()=>{s0();s4();F60();V60=r0({name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization-level settings",inputSchema:L.object({organizationId:L.string(),sidebar_items:L.array(xw).optional(),enabled_plugins:L.array(L.string()).optional()}),outputSchema:L.object({organizationId:L.string(),sidebar_items:L.array(xw).nullable().optional(),enabled_plugins:L.array(L.string()).nullable().optional(),createdAt:L.string().datetime().describe("ISO 8601 timestamp"),updatedAt:L.string().datetime().describe("ISO 8601 timestamp")}),handler:async(X,Y)=>{if(H4(Y),await Y.access.check(),Y.organization&&Y.organization.id!==X.organizationId)throw Error("Cannot update settings for a different organization");let Q=await Y.storage.organizationSettings.upsert(X.organizationId,{sidebar_items:X.sidebar_items,enabled_plugins:X.enabled_plugins});return{...Q,createdAt:Q.createdAt instanceof Date?Q.createdAt.toISOString():Q.createdAt,updatedAt:Q.updatedAt instanceof Date?Q.updatedAt.toISOString():Q.updatedAt}}})});var z60;var b94=d(()=>{s0();s4();z60=r0({name:"ORGANIZATION_MEMBER_ADD",description:"Add a member to an organization",inputSchema:L.object({organizationId:L.string().optional(),userId:L.string(),role:L.array(L.string())}),outputSchema:L.object({id:L.string(),organizationId:L.string(),userId:L.string(),role:L.union([L.string(),L.array(L.string())]),createdAt:L.string().datetime().describe("ISO 8601 timestamp")}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=X.organizationId||Y.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let J=await Y.boundAuth.organization.addMember({organizationId:Q,userId:X.userId,role:X.role});if(!J)throw Error("Failed to add member");return{...J,role:J.role,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var U60;var h94=d(()=>{s0();s4();U60=r0({name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove a member from an organization",inputSchema:L.object({organizationId:L.string().optional(),memberIdOrEmail:L.string()}),outputSchema:L.object({success:L.boolean(),memberIdOrEmail:L.string()}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=X.organizationId||Y.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");return await Y.boundAuth.organization.removeMember({organizationId:Q,memberIdOrEmail:X.memberIdOrEmail}),{success:!0,memberIdOrEmail:X.memberIdOrEmail}}})});var B60;var x94=d(()=>{s0();s4();B60=r0({name:"ORGANIZATION_MEMBER_LIST",description:"List all members in an organization",inputSchema:L.object({limit:L.number().optional(),offset:L.number().optional()}),outputSchema:L.object({members:L.array(L.object({id:L.string(),organizationId:L.string(),userId:L.string(),role:L.string(),createdAt:L.string().datetime().describe("ISO 8601 timestamp"),user:L.object({id:L.string(),name:L.string(),email:L.string(),image:L.string().optional()}).optional()}))}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=Y.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let J=await Y.boundAuth.organization.listMembers({organizationId:Q,limit:X.limit,offset:X.offset});return{members:(Array.isArray(J)?J:[]).map((Z)=>({...Z,createdAt:Z.createdAt instanceof Date?Z.createdAt.toISOString():Z.createdAt}))}}})});var D60;var g94=d(()=>{s0();s4();D60=r0({name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Update a member's role in an organization",inputSchema:L.object({organizationId:L.string().optional(),memberId:L.string(),role:L.array(L.string())}),outputSchema:L.object({id:L.string(),organizationId:L.string(),userId:L.string(),role:L.union([L.literal("admin"),L.literal("member"),L.literal("owner")]),createdAt:L.string().datetime().describe("ISO 8601 timestamp"),user:L.object({email:L.string(),name:L.string(),image:L.string().optional()})}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=X.organizationId||Y.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let J=await Y.boundAuth.organization.updateMemberRole({organizationId:Q,memberId:X.memberId,role:X.role});if(!J)throw Error("Failed to update member role");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var u94=d(()=>{R94();S94();v94();k94();_94();y94();f94();b94();h94();x94();g94()});var m94,CG,l94,d94;var XH=d(()=>{s0();m94=L.object({id:L.string().describe("Unique message ID"),threadId:L.string().describe("ID of the parent thread"),metadata:L.unknown().optional().describe("Optional message metadata"),parts:L.array(L.record(L.string(),L.unknown())).describe("Message content parts (AI SDK UIMessagePart format)"),role:L.enum(["user","assistant","system"]).describe("Message role"),createdAt:L.string().datetime().describe("Timestamp of creation"),updatedAt:L.string().datetime().describe("Timestamp of last update")}),CG=L.object({id:L.string().describe("Unique thread ID"),organizationId:L.string().describe("Organization this thread belongs to"),title:L.string().describe("Thread title"),description:L.string().nullable().describe("Thread description"),createdAt:L.string().datetime().describe("Timestamp of creation"),updatedAt:L.string().datetime().describe("Timestamp of last update"),hidden:L.boolean().optional().describe("Whether the thread is hidden"),createdBy:L.string().describe("User ID who created the thread"),updatedBy:L.string().nullable().describe("User ID who last updated the thread")}),l94=L.object({id:L.string().optional().describe("Optional custom ID for the thread"),title:L.string().describe("Thread title"),description:L.string().nullish().describe("Thread description")}),d94=L.object({title:L.string().optional().describe("New thread title"),description:L.string().nullish().describe("New thread description"),hidden:L.boolean().optional().describe("Whether the thread is hidden")})});var lA6,dA6,N60;var p94=d(()=>{s0();s4();XH();vS();lA6=L.object({data:l94.describe("Data for the new thread (id is auto-generated if not provided)")}),dA6=L.object({item:CG.describe("The created thread entity")}),N60=r0({name:"COLLECTION_THREADS_CREATE",description:"Create a new thread in the organization",inputSchema:lA6,outputSchema:dA6,handler:async(X,Y)=>{H4(Y);let Q=I4(Y);await Y.access.check();let J=A8(Y);if(!J)throw Error("User ID required to create thread");let G=X.data.id??RV("thrd"),Z=await Y.storage.threads.create({id:G,organizationId:Q.id,title:X.data.title,description:X.data.description,createdBy:J});return{item:{...Z,hidden:Z.hidden??!1}}}})});var pA6,cA6,O60;var c94=d(()=>{K5();s4();XH();s0();pA6=t3.extend({where:L.object({created_by:L.string().optional()}).optional()}),cA6=e3(CG),O60=r0({name:"COLLECTION_THREADS_LIST",description:"List all threads in the organization with filtering, sorting, and pagination",inputSchema:pA6,outputSchema:cA6,handler:async(X,Y)=>{await Y.access.check();let Q=Y.auth.user?.id;if(!Q)throw Error("User ID required to list threads");let J=I4(Y),G=X.offset??0,Z=X.limit??100,{threads:W,total:K}=await Y.storage.threads.list(J.id,Q,{limit:Z,offset:G}),$=G+Z<K;return{items:W.map((H)=>({...H,hidden:H.hidden??!1})),totalCount:K,hasMore:$}}})});var nA6,L60;var n94=d(()=>{K5();s4();XH();nA6=Pw(CG),L60=r0({name:"COLLECTION_THREADS_GET",description:"Get thread details by ID",inputSchema:Mw,outputSchema:nA6,handler:async(X,Y)=>{H4(Y);let Q=I4(Y);await Y.access.check();let J=await Y.storage.threads.get(X.id);if(!J||J.organizationId!==Q.id)return{item:null};return{item:{...J,hidden:J.hidden??!1}}}})});var iA6,aA6,w60;var i94=d(()=>{s0();s4();XH();iA6=L.object({id:L.string().describe("ID of the thread to update"),data:d94.describe("Partial thread data to update")}),aA6=L.object({item:CG.describe("The updated thread entity")}),w60=r0({name:"COLLECTION_THREADS_UPDATE",description:"Update an existing thread in the organization",inputSchema:iA6,outputSchema:aA6,handler:async(X,Y)=>{H4(Y);let Q=I4(Y);await Y.access.check();let J=A8(Y);if(!J)throw Error("User ID required to update thread");let{id:G,data:Z}=X,W=await Y.storage.threads.get(G);if(!W||W.organizationId!==Q.id)throw Error("Thread not found in organization");let K=await Y.storage.threads.update(G,{title:Z.title,description:Z.description,hidden:Z.hidden,updatedBy:J});return{item:{...K,hidden:K.hidden??!1}}}})});var M60;var a94=d(()=>{K5();s4();XH();M60=r0({name:"COLLECTION_THREADS_DELETE",description:"Delete a thread",inputSchema:Tw,outputSchema:Aw(CG),handler:async(X,Y)=>{H4(Y);let Q=I4(Y);await Y.access.check();let J=await Y.storage.threads.get(X.id);if(!J)throw Error(`Thread not found: ${X.id}`);if(J.organizationId!==Q.id)throw Error(`Thread not found: ${X.id}`);return await Y.storage.threads.delete(X.id),{item:{...J,hidden:J.hidden??!1}}}})});var rA6,oA6,P60;var r94=d(()=>{s0();s4();XH();rA6=L.object({threadId:L.string().describe("ID of the thread to list messages for"),limit:L.number().optional().describe("Maximum number of messages to return"),offset:L.number().optional().describe("Number of messages to skip")}),oA6=L.object({items:L.array(m94).describe("List of thread messages"),totalCount:L.number().describe("Total number of messages in the thread"),hasMore:L.boolean().describe("Whether there are more messages available")}),P60=r0({name:"COLLECTION_THREAD_MESSAGES_LIST",description:"List all messages for a specific thread",inputSchema:rA6,outputSchema:oA6,handler:async(X,Y)=>{let Q=I4(Y);await Y.access.check();let J=await Y.storage.threads.get(X.threadId);if(!J||J.organizationId!==Q.id)throw Error("Thread not found in organization");let G=X.offset??0,Z=X.limit??100,{messages:W,total:K}=await Y.storage.threads.listMessages(X.threadId,{limit:Z,offset:G}),$=G+Z<K;return{items:W,totalCount:K,hasMore:$}}})});var o94=d(()=>{p94();c94();n94();i94();a94();r94()});var tA6,eA6,T60;var s94=d(()=>{s0();s4();tA6=L.object({id:L.string().min(1)}),eA6=L.object({user:L.object({id:L.string(),name:L.string(),email:L.string(),image:L.string().nullable()}).nullable()}),T60=r0({name:"USER_GET",description:"Get a user by id (restricted to shared organizations)",inputSchema:tA6,outputSchema:eA6,handler:async(X,Y)=>{await Y.access.check(),H4(Y);let Q=A8(Y);if(!Q)throw Error("Authentication required");let J=await Y.storage.users.findById(X.id,Q);if(!J)return{user:null};return{user:{id:J.id,name:J.name,email:J.email,image:J.image??null}}}})});var t94=d(()=>{s94()});var XX4={};m4(XX4,{managementMCP:()=>YE6,ALL_TOOLS:()=>e94});var e94,YE6=(X)=>{let Y=e94.map((J)=>({name:J.name,description:J.description,inputSchema:J.inputSchema,outputSchema:J.outputSchema,handler:async(G)=>{return X.access.setToolName(J.name),await J.execute(G,X)}}));return X14({name:"mcp-mesh-management",version:"1.0.0"}).withTools(Y).build()};var YX4=d(()=>{Y14();B14();H84();J94();K94();N94();E94();C94();u94();o94();t94();e94=[W60,Z60,K60,$60,H60,q60,V60,z60,U60,B60,D60,C40,h40,x40,u40,m40,l40,s40,e40,X60,Y60,Q60,Z94,J60,G60,Q40,G40,W40,J40,d40,p40,c40,n40,i40,a40,r40,T60,E40,I40,j40,N60,O60,L60,w60,M60,P60]});O_();import{Migrator as FX4}from"kysely";var d60={benchmark:()=>Promise.resolve().then(() => (l60(),m60)).then((X)=>X.seed)};async function p60(X,Y){let Q=d60[Y];if(!Q)throw Error(`Unknown seed: ${Y}. Available: ${Object.keys(d60).join(", ")}`);let J=await Q();console.log(`\uD83C\uDF31 Running seed: ${Y}`);let G=await J(X);return console.log(`\u2705 Seed "${Y}" completed`),G}RG();BQ();RG();BQ();HX();$9();var z8=(X,Y="ms")=>{return new Date(Date.now()+(Y==="sec"?X*1000:X))},pA=new WeakMap;function wY0(X,Y){let Q=Y.fields,J={};for(let G in X){let Z=Q[G];if(!Z){J[G]=X[G];continue}if(Z.returned===!1)continue;J[G]=X[G]}return J}function cA(X,Y){if(!pA.has(X))pA.set(X,new Map);let Q=pA.get(X);if(Q.has(Y))return Q.get(Y);let J={...Y==="user"?X.user?.additionalFields:{},...Y==="session"?X.session?.additionalFields:{}};for(let G of X.plugins||[])if(G.schema&&G.schema[Y])J={...J,...G.schema[Y].fields};return pA.get(X).set(Y,J),J}function H9(X,Y){return{...wY0(Y,{fields:cA(X,"user")}),id:Y.id}}function T5(X,Y){return wY0(Y,{fields:cA(X,"session")})}function ix(X,Y){let Q=Y.action||"create",J=Y.fields,G=Object.assign(Object.create(null),null);for(let Z in J){if(Z in X){if(J[Z].input===!1){if(J[Z].defaultValue!==void 0){if(Q!=="update"){G[Z]=J[Z].defaultValue;continue}}if(X[Z])throw new c("BAD_REQUEST",{message:`${Z} is not allowed to be set`});continue}if(J[Z].validator?.input&&X[Z]!==void 0){G[Z]=J[Z].validator.input["~standard"].validate(X[Z]);continue}if(J[Z].transform?.input&&X[Z]!==void 0){G[Z]=J[Z].transform?.input(X[Z]);continue}G[Z]=X[Z];continue}if(J[Z].defaultValue!==void 0&&Q==="create"){if(typeof J[Z].defaultValue==="function"){G[Z]=J[Z].defaultValue();continue}G[Z]=J[Z].defaultValue;continue}if(J[Z].required&&Q==="create")throw new c("BAD_REQUEST",{message:`${Z} is required`})}return G}function nA(X,Y={},Q){return ix(Y,{fields:cA(X,"user"),action:Q})}function ax(X,Y){return ix(Y,{fields:cA(X,"session")})}function RX(X,Y){if(!Y)return X;for(let Q in Y){let J=Y[Q]?.modelName;if(J)X[Q].modelName=J;for(let G in X[Q].fields){let Z=Y[Q]?.fields?.[G];if(!Z)continue;X[Q].fields[G].fieldName=Z}}return X}KY();s0();var eG4="127.0.0.1";function vW(X,Y){if(Y.advanced?.ipAddress?.disableIpTracking)return null;if(dG()||sH())return eG4;let Q="headers"in X?X.headers:X,J=Y.advanced?.ipAddress?.ipAddressHeaders||["x-forwarded-for"];for(let G of J){let Z="get"in Q?Q.get(G):Q[G];if(typeof Z==="string"){let W=Z.split(",")[0].trim();if(X74(W))return W}}return null}function X74(X){if(gK().safeParse(X).success)return!0;if(uK().safeParse(X).success)return!0;return!1}FX();L5();KY();E8();import{sql as E5}from"kysely";async function EY0(X,Y){let Q;if(!X.database){let J=bY(X),G=Object.keys(J).reduce((W,K)=>{return W[K]=[],W},{}),{memoryAdapter:Z}=await Promise.resolve().then(() => (AY0(),TY0));Q=Z(G)(X)}else if(typeof X.database==="function")Q=X.database(X);else Q=await Y(X);if(!Q.transaction)v4.warn("Adapter does not correctly implement transaction function, patching it automatically. Please update your adapter implementation."),Q.transaction=async(J)=>{return J(Q)};return Q}async function Xg(X){return EY0(X,async(Y)=>{let{createKyselyAdapter:Q}=await Promise.resolve().then(() => (ex(),tx)),{kysely:J,databaseType:G,transaction:Z}=await Q(Y);if(!J)throw new T4("Failed to initialize database adapter");let{kyselyAdapter:W}=await Promise.resolve().then(() => (ex(),tx));return W(J,{type:G||"sqlite",debugLogs:Y.database&&"debugLogs"in Y.database?Y.database.debugLogs:!1,transaction:Z})(Y)})}function IY0(X,Y){let Q=Y.hooks;async function J($,H,F){let q=await hY(),V=$;for(let N of Q||[]){let O=N[H]?.create?.before;if(O){let w=await O(V,q);if(w===!1)return null;if(typeof w==="object"&&"data"in w)V={...V,...w.data}}}let U=F?await F.fn(V):null,D=!F||F.executeMainFn?await(await K1(X)).create({model:H,data:V,forceAllowId:!0}):U;for(let N of Q||[]){let O=N[H]?.create?.after;if(O)await O(D,q)}return D}async function G($,H,F,q){let V=await hY(),U=$;for(let O of Q||[]){let w=O[F]?.update?.before;if(w){let E=await w($,V);if(E===!1)return null;if(typeof E==="object"&&"data"in E)U={...U,...E.data}}}let D=q?await q.fn(U):null,N=!q||q.executeMainFn?await(await K1(X)).update({model:F,update:U,where:H}):D;for(let O of Q||[]){let w=O[F]?.update?.after;if(w)await w(N,V)}return N}async function Z($,H,F,q){let V=await hY(),U=$;for(let O of Q||[]){let w=O[F]?.update?.before;if(w){let E=await w($,V);if(E===!1)return null;if(typeof E==="object"&&"data"in E)U={...U,...E.data}}}let D=q?await q.fn(U):null,N=!q||q.executeMainFn?await(await K1(X)).updateMany({model:F,update:U,where:H}):D;for(let O of Q||[]){let w=O[F]?.update?.after;if(w)await w(N,V)}return N}async function W($,H,F){let q=await hY(),V=null;try{V=(await(await K1(X)).findMany({model:H,where:$,limit:1}))[0]||null}catch(N){}if(V)for(let N of Q||[]){let O=N[H]?.delete?.before;if(O){if(await O(V,q)===!1)return null}}let U=F?await F.fn($):null,D=!F||F.executeMainFn?await(await K1(X)).delete({model:H,where:$}):U;if(V)for(let N of Q||[]){let O=N[H]?.delete?.after;if(O)await O(V,q)}return D}async function K($,H,F){let q=await hY(),V=[];try{V=await(await K1(X)).findMany({model:H,where:$})}catch(N){}for(let N of V)for(let O of Q||[]){let w=O[H]?.delete?.before;if(w){if(await w(N,q)===!1)return null}}let U=F?await F.fn($):null,D=!F||F.executeMainFn?await(await K1(X)).deleteMany({model:H,where:$}):U;for(let N of V)for(let O of Q||[]){let w=O[H]?.delete?.after;if(w)await w(N,q)}return D}return{createWithHooks:J,updateWithHooks:G,updateManyWithHooks:Z,deleteWithHooks:W,deleteManyWithHooks:K}}var eA=(X,Y)=>{let{logger:Q,options:J}=Y,G=J.secondaryStorage,Z=J.session?.expiresIn||604800,{createWithHooks:W,updateWithHooks:K,updateManyWithHooks:$,deleteWithHooks:H,deleteManyWithHooks:F}=IY0(X,Y);async function q(V){if(!G)return;let U=await G.get(`active-sessions-${V.id}`);if(!U)return;let D=Date.now(),N=(B1(U)||[]).filter((O)=>O.expiresAt>D);await Promise.all(N.map(async({token:O})=>{let w=await G.get(O);if(!w)return;let E=B1(w);if(!E)return;let C=Math.max(Math.floor(new Date(E.session.expiresAt).getTime()-D)/1000,0);await G.set(O,JSON.stringify({session:E.session,user:V}),Math.floor(C))}))}return{createOAuthUser:async(V,U)=>{return oz(X,async()=>{let D=await W({createdAt:new Date,updatedAt:new Date,...V},"user",void 0);return{user:D,account:await W({...U,userId:D.id,createdAt:new Date,updatedAt:new Date},"account",void 0)}})},createUser:async(V)=>{return await W({createdAt:new Date,updatedAt:new Date,...V,email:V.email?.toLowerCase()},"user",void 0)},createAccount:async(V)=>{return await W({createdAt:new Date,updatedAt:new Date,...V},"account",void 0)},listSessions:async(V)=>{if(G){let U=await G.get(`active-sessions-${V}`);if(!U)return[];let D=B1(U)||[],N=Date.now(),O=D.filter((E)=>E.expiresAt>N),w=[];for(let E of O){let C=await G.get(E.token);if(C){let A=B1(C);if(!A)return[];let T=T5(Y.options,{...A.session,expiresAt:new Date(A.session.expiresAt)});w.push(T)}}return w}return await(await K1(X)).findMany({model:"session",where:[{field:"userId",value:V}]})},listUsers:async(V,U,D,N)=>{return await(await K1(X)).findMany({model:"user",limit:V,offset:U,sortBy:D,where:N})},countTotalUsers:async(V)=>{let U=await(await K1(X)).count({model:"user",where:V});if(typeof U==="string")return parseInt(U);return U},deleteUser:async(V)=>{if(G)await G.delete(`active-sessions-${V}`);if(!G||J.session?.storeSessionInDatabase)await F([{field:"userId",value:V}],"session",void 0);await F([{field:"userId",value:V}],"account",void 0),await H([{field:"id",value:V}],"user",void 0)},createSession:async(V,U,D,N)=>{let O=await hY().catch(()=>null),w=O?.headers||O?.request?.headers,{id:E,...C}=D||{},A=ax(O?.context.options??J,{}),T={ipAddress:O?.request||O?.headers?vW(O?.request||O?.headers,O?.context.options)||"":"",userAgent:w?.get("user-agent")||"",...C,expiresAt:U?z8(86400,"sec"):z8(Z,"sec"),userId:V,token:x8(32),createdAt:new Date,updatedAt:new Date,...A,...N?C:{}};return await W(T,"session",G?{fn:async(j)=>{let R=await G.get(`active-sessions-${V}`),v=[],_=Date.now();if(R)v=B1(R)||[],v=v.filter((u)=>u.expiresAt>_);let y=v.sort((u,t)=>u.expiresAt-t.expiresAt),f=y.at(-1)?.expiresAt;if(y.push({token:T.token,expiresAt:T.expiresAt.getTime()}),!f||f<T.expiresAt.getTime())f=T.expiresAt.getTime();let a=Math.max(Math.floor((f-_)/1000),0);if(a>0)await G.set(`active-sessions-${V}`,JSON.stringify(y),a);let x=await X.findOne({model:"user",where:[{field:"id",value:V}]}),k=Math.max(Math.floor((T.expiresAt.getTime()-_)/1000),0);if(k>0)await G.set(T.token,JSON.stringify({session:j,user:x}),k);return j},executeMainFn:J.session?.storeSessionInDatabase}:void 0)},findSession:async(V)=>{if(G){let O=await G.get(V);if(!O&&!J.session?.storeSessionInDatabase)return null;if(O){let w=B1(O);if(!w)return null;return{session:T5(Y.options,{...w.session,expiresAt:new Date(w.session.expiresAt),createdAt:new Date(w.session.createdAt),updatedAt:new Date(w.session.updatedAt)}),user:H9(Y.options,{...w.user,createdAt:new Date(w.user.createdAt),updatedAt:new Date(w.user.updatedAt)})}}}let U=await(await K1(X)).findOne({model:"session",where:[{value:V,field:"token"}],join:{user:!0}});if(!U)return null;let{user:D,...N}=U;if(!D)return null;return{session:T5(Y.options,N),user:H9(Y.options,D)}},findSessions:async(V)=>{if(G){let D=[];for(let N of V){let O=await G.get(N);if(O){let w=B1(O);if(!w)return[];let E={session:{...w.session,expiresAt:new Date(w.session.expiresAt)},user:{...w.user,createdAt:new Date(w.user.createdAt),updatedAt:new Date(w.user.updatedAt)}};D.push(E)}}return D}let U=await(await K1(X)).findMany({model:"session",where:[{field:"token",value:V,operator:"in"}],join:{user:!0}});if(!U.length)return[];if(U.some((D)=>!D.user))return[];return U.map((D)=>{let{user:N,...O}=D;return{session:O,user:N}})},updateSession:async(V,U)=>{return await K(U,[{field:"token",value:V}],"session",G?{async fn(D){let N=await G.get(V),O=null;if(N){let w=B1(N);if(!w)return null;return O={...w.session,...D},O}else return null},executeMainFn:J.session?.storeSessionInDatabase}:void 0)},deleteSession:async(V)=>{if(G){let U=await G.get(V);if(U){let{session:D}=B1(U)??{};if(!D){Q.error("Session not found in secondary storage");return}let N=D.userId,O=await G.get(`active-sessions-${N}`);if(O){let w=B1(O)||[],E=Date.now(),C=w.filter((T)=>T.expiresAt>E&&T.token!==V),A=C.sort((T,j)=>T.expiresAt-j.expiresAt).at(-1)?.expiresAt;if(C.length>0&&A&&A>Date.now())await G.set(`active-sessions-${N}`,JSON.stringify(C),Math.floor((A-E)/1000));else await G.delete(`active-sessions-${N}`)}else Q.error("Active sessions list not found in secondary storage")}if(await G.delete(V),!J.session?.storeSessionInDatabase||Y.options.session?.preserveSessionInDatabase)return}await(await K1(X)).delete({model:"session",where:[{field:"token",value:V}]})},deleteAccounts:async(V)=>{await F([{field:"userId",value:V}],"account",void 0)},deleteAccount:async(V)=>{await H([{field:"id",value:V}],"account",void 0)},deleteSessions:async(V)=>{if(G){if(typeof V==="string"){let U=await G.get(`active-sessions-${V}`),D=U?B1(U):[];if(!D)return;for(let N of D)await G.delete(N.token)}else for(let U of V)if(await G.get(U))await G.delete(U);if(!J.session?.storeSessionInDatabase||Y.options.session?.preserveSessionInDatabase)return}await F([{field:Array.isArray(V)?"token":"userId",value:V,operator:Array.isArray(V)?"in":void 0}],"session",void 0)},findOAuthUser:async(V,U,D)=>{let N=await(await K1(X)).findMany({model:"account",where:[{value:U,field:"accountId"}],join:{user:!0}}).then((O)=>{return O.find((w)=>w.providerId===D)});if(N)if(N.user)return{user:N.user,accounts:[N]};else{let O=await(await K1(X)).findOne({model:"user",where:[{value:V.toLowerCase(),field:"email"}]});if(O)return{user:O,accounts:[N]};return null}else{let O=await(await K1(X)).findOne({model:"user",where:[{value:V.toLowerCase(),field:"email"}]});if(O)return{user:O,accounts:await(await K1(X)).findMany({model:"account",where:[{value:O.id,field:"userId"}]})||[]};else return null}},findUserByEmail:async(V,U)=>{let D=await(await K1(X)).findOne({model:"user",where:[{value:V.toLowerCase(),field:"email"}],join:{...U?.includeAccounts?{account:!0}:{}}});if(!D)return null;let{account:N,...O}=D;return{user:O,accounts:N??[]}},findUserById:async(V)=>{if(!V)return null;return await(await K1(X)).findOne({model:"user",where:[{field:"id",value:V}]})},linkAccount:async(V)=>{return await W({createdAt:new Date,updatedAt:new Date,...V},"account",void 0)},updateUser:async(V,U)=>{let D=await K(U,[{field:"id",value:V}],"user",void 0);return await q(D),await q(D),D},updateUserByEmail:async(V,U)=>{let D=await K(U,[{field:"email",value:V.toLowerCase()}],"user",void 0);return await q(D),await q(D),D},updatePassword:async(V,U)=>{await $({password:U},[{field:"userId",value:V},{field:"providerId",value:"credential"}],"account",void 0)},findAccounts:async(V)=>{return await(await K1(X)).findMany({model:"account",where:[{field:"userId",value:V}]})},findAccount:async(V)=>{return await(await K1(X)).findOne({model:"account",where:[{field:"accountId",value:V}]})},findAccountByProviderId:async(V,U)=>{return await(await K1(X)).findOne({model:"account",where:[{field:"accountId",value:V},{field:"providerId",value:U}]})},findAccountByUserId:async(V)=>{return await(await K1(X)).findMany({model:"account",where:[{field:"userId",value:V}]})},updateAccount:async(V,U)=>{return await K(U,[{field:"id",value:V}],"account",void 0)},createVerificationValue:async(V)=>{return await W({createdAt:new Date,updatedAt:new Date,...V},"verification",void 0)},findVerificationValue:async(V)=>{let U=await(await K1(X)).findMany({model:"verification",where:[{field:"identifier",value:V}],sortBy:{field:"createdAt",direction:"desc"},limit:1});if(!J.verification?.disableCleanup)await(await K1(X)).deleteMany({model:"verification",where:[{field:"expiresAt",value:new Date,operator:"lt"}]});return U[0]},deleteVerificationValue:async(V)=>{await(await K1(X)).delete({model:"verification",where:[{field:"id",value:V}]})},deleteVerificationByIdentifier:async(V)=>{await(await K1(X)).delete({model:"verification",where:[{field:"identifier",value:V}]})},updateVerificationValue:async(V,U)=>{return await K(U,[{field:"id",value:V}],"verification",void 0)}}};function jY0(X){let Y=bY(X),Q={};for(let J in Y){let G=Y[J],Z=G.fields,W={};if(Object.entries(Z).forEach(([K,$])=>{if(W[$.fieldName||K]=$,$.references){let H=Y[$.references.model];if(H)W[$.fieldName||K].references={...$.references,model:H.modelName,field:$.references.field}}}),Q[G.modelName]){Q[G.modelName].fields={...Q[G.modelName].fields,...W};continue}Q[G.modelName]={fields:W,order:G.order||1/0}}return Q}var Z74={postgres:{string:["character varying","varchar","text","uuid"],number:["int4","integer","bigint","smallint","numeric","real","double precision"],boolean:["bool","boolean"],date:["timestamptz","timestamp","date"],json:["json","jsonb"]},mysql:{string:["varchar","text","uuid"],number:["integer","int","bigint","smallint","decimal","float","double"],boolean:["boolean","tinyint"],date:["timestamp","datetime","date"],json:["json"]},sqlite:{string:["TEXT"],number:["INTEGER","REAL"],boolean:["INTEGER","BOOLEAN"],date:["DATE","INTEGER"],json:["TEXT"]},mssql:{string:["varchar","nvarchar","uniqueidentifier"],number:["int","bigint","smallint","decimal","float","double"],boolean:["bit","smallint"],date:["datetime2","date","datetime"],json:["varchar","nvarchar"]}};function CY0(X,Y,Q){function J(Z){return Z.toLowerCase().split("(")[0].trim()}if(Y==="string[]"||Y==="number[]")return X.toLowerCase().includes("json");let G=Z74[Q];return(Array.isArray(Y)?G.string.map((Z)=>Z.toLowerCase()):G[Y].map((Z)=>Z.toLowerCase())).includes(J(X))}async function K74(X){try{let Y=await E5`SHOW search_path`.execute(X);if(Y.rows[0]?.search_path)return Y.rows[0].search_path.split(",").map((Q)=>Q.trim()).map((Q)=>Q.replace(/^["']|["']$/g,"")).filter((Q)=>!Q.startsWith("$"))[0]||"public"}catch(Y){}return"public"}async function CB(X){let Y=jY0(X),Q=eH(X.logger),{kysely:J,databaseType:G}=await cw(X);if(!G)Q.warn("Could not determine database type, defaulting to sqlite. Please provide a type in the database options to avoid this."),G="sqlite";if(!J)Q.error("Only kysely adapter is supported for migrations. You can use `generate` command to generate the schema, if you're using a different adapter."),process.exit(1);let Z="public";if(G==="postgres"){Z=await K74(J),Q.debug(`PostgreSQL migration: Using schema '${Z}' (from search_path)`);try{if(!(await E5`
|
|
369
|
+
`.execute(X)).rows[0]?.exists)await p6`CREATE ROLE ${p6.id(Q)} NOLOGIN`.execute(X);await p6`GRANT ${p6.id(Q)} TO CURRENT_USER`.execute(X),await p6`GRANT USAGE, CREATE ON SCHEMA ${p6.id(Y)} TO ${p6.id(Q)}`.execute(X),await p6`GRANT ALL ON ALL TABLES IN SCHEMA ${p6.id(Y)} TO ${p6.id(Q)}`.execute(X),await p6`GRANT ALL ON ALL SEQUENCES IN SCHEMA ${p6.id(Y)} TO ${p6.id(Q)}`.execute(X),await p6`ALTER DEFAULT PRIVILEGES IN SCHEMA ${p6.id(Y)} GRANT ALL ON TABLES TO ${p6.id(Q)}`.execute(X),await p6`ALTER DEFAULT PRIVILEGES IN SCHEMA ${p6.id(Y)} GRANT ALL ON SEQUENCES TO ${p6.id(Q)}`.execute(X),await p6`REVOKE ALL ON SCHEMA public FROM ${p6.id(Q)}`.execute(X)}async function wA6(X,Y,Q,J){try{return await X.transaction().execute(async(G)=>{return await p6`SET LOCAL ROLE ${p6.id(Q)}`.execute(G),await p6`SET LOCAL search_path TO ${p6.id(Y)}`.execute(G),await p6.raw(J).execute(G)})}catch(G){if(OA6(G))return await LA6(X,Y,Q),await X.transaction().execute(async(Z)=>{return await p6`SET LOCAL ROLE ${p6.id(Q)}`.execute(Z),await p6`SET LOCAL search_path TO ${p6.id(Y)}`.execute(Z),await p6.raw(J).execute(Z)});throw G}}var zA6,BA6,Z94;var K94=d(()=>{s0();s4();zA6=L.object({results:L.array(L.unknown()).optional(),success:L.boolean().optional()});BA6=L.object({sql:L.string().describe("The SQL query to run"),params:L.array(L.any()).describe("The parameters to pass to the SQL query").optional()});Z94=r0({name:"DATABASES_RUN_SQL",description:"Run a SQL query against the database",inputSchema:BA6,outputSchema:L.object({result:L.array(zA6)}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=UA6(X.sql,X.params||[]);if(!Y.connectionId)throw Error("Connection context required for database access");let J=DA6(Y.connectionId),G=NA6(Y.connectionId);return{result:[{results:(await wA6(Y.db,J,G,Q)).rows,success:!0}]}}})});var $94,PA6,H94;var XW=d(()=>{s0();y40();$94=L.object({connectionId:L.string().optional().describe("Filter subscriptions by connection ID (optional)")}),PA6=L.object({id:L.string().describe("Subscription ID"),connectionId:L.string().describe("Subscriber connection ID"),eventType:L.string().describe("Event type pattern"),publisher:L.string().nullable().describe("Publisher connection filter (null = all publishers)"),filter:L.string().nullable().describe("JSONPath filter expression"),enabled:L.boolean().describe("Whether subscription is enabled"),createdAt:L.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:L.string().datetime().describe("Updated timestamp (ISO 8601)")}),H94=L.object({subscriptions:L.array(PA6).describe("List of subscriptions")})});var d40;var F94=d(()=>{s4();XW();d40=r0({name:"EVENT_PUBLISH",description:"Publish an event to the event bus. Supports immediate, scheduled (deliverAt), and recurring (cron) delivery. The source is automatically set to the caller's connection ID.",inputSchema:Ew,outputSchema:Iw,handler:async(X,Y)=>{H4(Y);let Q=I4(Y);await Y.access.check();let J=Y.connectionId;if(!J)throw Error("Connection ID required to publish events. Use a connection-scoped token.");let G=await Y.eventBus.publish(Q.id,J,{type:X.type,subject:X.subject,data:X.data,deliverAt:X.deliverAt,cron:X.cron});return{id:G.id,type:G.type,source:G.source,time:G.time}}})});var p40;var q94=d(()=>{s4();XW();p40=r0({name:"EVENT_SUBSCRIBE",description:"Subscribe to events of a specific type. The subscriber is automatically set to the caller's connection.",inputSchema:jw,outputSchema:Cw,handler:async(X,Y)=>{H4(Y);let Q=I4(Y);await Y.access.check();let J=Y.connectionId;if(!J)throw Error("Connection ID required to subscribe. Use a connection-scoped token.");let G=await Y.eventBus.subscribe(Q.id,{connectionId:J,eventType:X.eventType,publisher:X.publisher,filter:X.filter});return{subscription:{id:G.id,connectionId:G.connectionId,eventType:G.eventType,publisher:G.publisher,filter:G.filter,enabled:G.enabled,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}}}})});var c40;var V94=d(()=>{s4();XW();c40=r0({name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events by removing a subscription.",inputSchema:vw,outputSchema:kw,handler:async(X,Y)=>{H4(Y);let Q=I4(Y);await Y.access.check();let J=Y.connectionId;if(!J)throw Error("Connection ID required to unsubscribe. Use a connection-scoped token.");let G=await Y.eventBus.getSubscription(Q.id,X.subscriptionId);if(!G)throw Error(`Subscription not found: ${X.subscriptionId}`);if(G.connectionId!==J)throw Error("Cannot unsubscribe from a subscription owned by another connection");return{success:(await Y.eventBus.unsubscribe(Q.id,X.subscriptionId)).success,subscriptionId:X.subscriptionId}}})});var n40;var z94=d(()=>{s4();XW();n40=r0({name:"EVENT_CANCEL",description:"Cancel a recurring event to stop future deliveries. Only the publisher can cancel their own events.",inputSchema:_w,outputSchema:yw,handler:async(X,Y)=>{H4(Y);let Q=I4(Y);await Y.access.check();let J=Y.connectionId;if(!J)throw Error("Connection ID required to cancel events. Use a connection-scoped token.");if(!await Y.eventBus.getEvent(Q.id,X.eventId))throw Error(`Event not found: ${X.eventId}`);if(!(await Y.eventBus.cancelEvent(Q.id,X.eventId,J)).success)throw Error("Failed to cancel event. Either the event is already completed/failed, or you are not the publisher.");return{success:!0,eventId:X.eventId}}})});var i40;var U94=d(()=>{s4();XW();i40=r0({name:"EVENT_ACK",description:"Acknowledge delivery of an event. Call after successfully processing an event received via ON_EVENTS with retryAfter.",inputSchema:fw,outputSchema:bw,handler:async(X,Y)=>{H4(Y);let Q=I4(Y);await Y.access.check();let J=Y.connectionId;if(!J)throw Error("Connection ID required to acknowledge events. Use a connection-scoped token.");if(!(await Y.eventBus.ackEvent(Q.id,X.eventId,J)).success)throw Error("Failed to acknowledge event. Either the event was not found, already delivered, or you are not a subscriber.");return{success:!0,eventId:X.eventId}}})});var a40;var B94=d(()=>{s4();XW();a40=r0({name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions, optionally filtered by connection ID.",inputSchema:$94,outputSchema:H94,handler:async(X,Y)=>{H4(Y);let Q=I4(Y);return await Y.access.check(),{subscriptions:(await Y.eventBus.listSubscriptions(Q.id,X.connectionId)).map((G)=>({id:G.id,connectionId:G.connectionId,eventType:G.eventType,publisher:G.publisher,filter:G.filter,enabled:G.enabled,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}))}}})});var r40;var D94=d(()=>{s4();XW();r40=r0({name:"EVENT_SYNC_SUBSCRIPTIONS",description:"Sync subscriptions to desired state. Creates new, deletes removed, updates changed filters. Subscriptions are identified by (eventType, publisher).",inputSchema:Rw,outputSchema:Sw,handler:async(X,Y)=>{H4(Y);let Q=I4(Y);await Y.access.check();let J=Y.connectionId;if(!J)throw Error("Connection ID required to sync subscriptions. Use a connection-scoped token.");let G=await Y.eventBus.syncSubscriptions(Q.id,{connectionId:J,subscriptions:X.subscriptions});return{created:G.created,updated:G.updated,deleted:G.deleted,unchanged:G.unchanged,subscriptions:G.subscriptions.map((Z)=>({id:Z.id,connectionId:Z.connectionId,eventType:Z.eventType,publisher:Z.publisher,filter:Z.filter,enabled:Z.enabled,createdAt:Z.createdAt instanceof Date?Z.createdAt.toISOString():Z.createdAt,updatedAt:Z.updatedAt instanceof Date?Z.updatedAt.toISOString():Z.updatedAt}))}}})});var N94=d(()=>{F94();q94();V94();z94();U94();B94();D94();XW()});var o40,AA6,jG,O94,L94;var Pz=d(()=>{s0();o40=L.enum(["inclusion","exclusion"]).describe("Tool selection mode: 'inclusion' = include selected (default), 'exclusion' = exclude selected"),AA6=L.object({connection_id:L.string().describe("Connection ID"),selected_tools:L.array(L.string()).nullable().describe("Selected tool names. With 'inclusion' mode: null = all tools included. With 'exclusion' mode: null = entire connection excluded"),selected_resources:L.array(L.string()).nullable().describe("Selected resource URIs or patterns. Supports * and ** wildcards for pattern matching. With 'inclusion' mode: null = all resources included."),selected_prompts:L.array(L.string()).nullable().describe("Selected prompt names. With 'inclusion' mode: null = all prompts included. With 'exclusion' mode: null = entire connection excluded.")}),jG=L.object({id:L.string().describe("Unique identifier for the virtual MCP"),title:L.string().describe("Human-readable name for the virtual MCP"),description:L.string().nullable().describe("Description of the virtual MCP"),icon:L.string().nullable().optional().describe("Icon URL for the virtual MCP"),created_at:L.string().describe("When the virtual MCP was created"),updated_at:L.string().describe("When the virtual MCP was last updated"),created_by:L.string().describe("User ID who created the virtual MCP"),updated_by:L.string().optional().describe("User ID who last updated the virtual MCP"),organization_id:L.string().describe("Organization ID this virtual MCP belongs to"),tool_selection_mode:o40.describe("Tool selection mode: 'inclusion' = include selected, 'exclusion' = exclude selected"),status:L.enum(["active","inactive"]).describe("Current status"),connections:L.array(AA6).describe("Connections with their selected tools (behavior depends on tool_selection_mode)")}),O94=L.object({title:L.string().min(1).max(255).describe("Name for the virtual MCP"),description:L.string().nullable().optional().describe("Optional description"),tool_selection_mode:o40.optional().default("inclusion").describe("Tool selection mode (defaults to 'inclusion')"),icon:L.string().nullable().optional().describe("Optional icon URL"),status:L.enum(["active","inactive"]).optional().default("active").describe("Initial status"),connections:L.array(L.object({connection_id:L.string().describe("Connection ID"),selected_tools:L.array(L.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools or full exclusion)"),selected_resources:L.array(L.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources)"),selected_prompts:L.array(L.string()).nullable().optional().describe("Selected prompt names (null/undefined = all prompts or full exclusion)")})).describe("Connections to include/exclude (can be empty for exclusion mode)")}),L94=L.object({title:L.string().min(1).max(255).optional().describe("New name"),description:L.string().nullable().optional().describe("New description (null to clear)"),tool_selection_mode:o40.optional().describe("New tool selection mode"),icon:L.string().nullable().optional().describe("New icon URL (null to clear)"),status:L.enum(["active","inactive"]).optional().describe("New status"),connections:L.array(L.object({connection_id:L.string().describe("Connection ID"),selected_tools:L.array(L.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools or full exclusion)"),selected_resources:L.array(L.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources)"),selected_prompts:L.array(L.string()).nullable().optional().describe("Selected prompt names (null/undefined = all prompts or full exclusion)")})).optional().describe("New connections (replaces existing)")})});var EA6,IA6,s40;var w94=d(()=>{s0();s4();Pz();EA6=L.object({data:O94.describe("Data for the new virtual MCP")}),IA6=L.object({item:jG.describe("The created virtual MCP entity")}),s40=r0({name:"COLLECTION_VIRTUAL_MCP_CREATE",description:"Create a new MCP virtual MCP in the organization",inputSchema:EA6,outputSchema:IA6,handler:async(X,Y)=>{H4(Y);let Q=I4(Y);await Y.access.check();let J=A8(Y);if(!J)throw Error("User ID required to create virtual MCP");return{item:await Y.storage.virtualMcps.create(Q.id,J,X.data)}}})});function jA6(X){let Y=[],Q=0;while(Q<X.length){let J=X[Q];if(J==="%")Y.push(".*");else if(J==="_")Y.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))Y.push("\\"+J);else Y.push(J);Q++}return Y.join("")}function WK(X){return typeof X==="string"||typeof X==="number"}function t40(X,Y){let Q=Y.split("."),J=X;for(let G of Q){if(J==null||typeof J!=="object")return;J=J[G]}return J}function CA6(X,Y){return X.connections.some((Q)=>Q.connection_id===Y)}function mk(X,Y){if("conditions"in Y){let{operator:K,conditions:$}=Y;switch(K){case"and":return $.every((H)=>mk(X,H));case"or":return $.some((H)=>mk(X,H));case"not":return!$.every((H)=>mk(X,H));default:return!0}}let{field:Q,operator:J,value:G}=Y,Z=Q.join(".");if(Z==="connection_id"){if(J!=="eq"||typeof G!=="string")return!1;return CA6(X,G)}let W=t40(X,Z);switch(J){case"eq":return W===G;case"gt":return WK(W)&&WK(G)&&W>G;case"gte":return WK(W)&&WK(G)&&W>=G;case"lt":return WK(W)&&WK(G)&&W<G;case"lte":return WK(W)&&WK(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 K=jA6(G);return new RegExp(`^${K}$`,"i").test(W);case"contains":if(typeof W!=="string"||typeof G!=="string")return!1;return W.toLowerCase().includes(G.toLowerCase());default:return!0}}function RA6(X,Y){return[...X].sort((Q,J)=>{for(let G of Y){let Z=G.field.join("."),W=t40(Q,Z),K=t40(J,Z),$=0;if(W==null&&K==null)continue;if(W==null)$=G.nulls==="first"?-1:1;else if(K==null)$=G.nulls==="first"?1:-1;else if(typeof W==="string"&&typeof K==="string")$=W.localeCompare(K);else if(typeof W==="number"&&typeof K==="number")$=W-K;else $=String(W).localeCompare(String(K));if($!==0)return G.direction==="desc"?-$:$}return 0})}var SA6,vA6,e40;var M94=d(()=>{K5();s4();Pz();SA6=t3,vA6=e3(jG),e40=r0({name:"COLLECTION_VIRTUAL_MCP_LIST",description:"List all MCP virtual MCPs in the organization",inputSchema:SA6,outputSchema:vA6,handler:async(X,Y)=>{await Y.access.check();let Q=I4(Y),J=X.where&&!("conditions"in X.where)&&X.where.field.join(".")==="connection_id"&&X.where.operator==="eq"&&typeof X.where.value==="string"?X.where.value:void 0,Z=J?await Y.storage.virtualMcps.listByConnectionId(Q.id,J):await Y.storage.virtualMcps.list(Q.id);if(X.where)Z=Z.filter((q)=>mk(q,X.where));if(X.orderBy&&X.orderBy.length>0)Z=RA6(Z,X.orderBy);let W=Z.length,K=X.offset??0,$=X.limit??100,H=Z.slice(K,K+$),F=K+$<W;return{items:H,totalCount:W,hasMore:F}}})});var kA6,_A6,X60;var P94=d(()=>{s0();s4();Pz();kA6=L.object({id:L.string().describe("ID of the virtual MCP to retrieve")}),_A6=L.object({item:jG.nullable().describe("The retrieved virtual MCP, or null if not found")}),X60=r0({name:"COLLECTION_VIRTUAL_MCP_GET",description:"Get an MCP virtual MCP by ID",inputSchema:kA6,outputSchema:_A6,handler:async(X,Y)=>{H4(Y);let Q=I4(Y);await Y.access.check();let J=await Y.storage.virtualMcps.findById(X.id);if(J&&J.organization_id!==Q.id)return{item:null};if(!J)return{item:null};return{item:J}}})});var yA6,fA6,Y60;var T94=d(()=>{s0();s4();Pz();yA6=L.object({id:L.string().describe("ID of the virtual MCP to update"),data:L94.describe("Partial virtual MCP data to update")}),fA6=L.object({item:jG.describe("The updated virtual MCP entity")}),Y60=r0({name:"COLLECTION_VIRTUAL_MCP_UPDATE",description:"Update an MCP virtual MCP",inputSchema:yA6,outputSchema:fA6,handler:async(X,Y)=>{H4(Y);let Q=I4(Y);await Y.access.check();let J=A8(Y);if(!J)throw Error("User ID required to update virtual MCP");let G=await Y.storage.virtualMcps.findById(X.id);if(!G)throw Error(`Virtual MCP not found: ${X.id}`);if(G.organization_id!==Q.id)throw Error(`Virtual MCP not found: ${X.id}`);return{item:await Y.storage.virtualMcps.update(X.id,J,X.data)}}})});var bA6,hA6,Q60;var A94=d(()=>{s0();s4();Pz();bA6=L.object({id:L.string().describe("ID of the virtual MCP to delete")}),hA6=L.object({item:jG.describe("The deleted virtual MCP entity")}),Q60=r0({name:"COLLECTION_VIRTUAL_MCP_DELETE",description:"Delete an MCP virtual MCP",inputSchema:bA6,outputSchema:hA6,handler:async(X,Y)=>{H4(Y);let Q=I4(Y);await Y.access.check();let J=await Y.storage.virtualMcps.findById(X.id);if(!J)throw Error(`Virtual MCP not found: ${X.id}`);if(J.organization_id!==Q.id)throw Error(`Virtual MCP not found: ${X.id}`);return await Y.storage.virtualMcps.delete(X.id),{item:J}}})});var E94=d(()=>{w94();M94();P94();T94();A94()});var gA6,J60;var I94=d(()=>{s4();s0();gA6=L.object({id:L.string().optional().describe("Unique log identifier"),organizationId:L.string().describe("Organization ID"),connectionId:L.string().describe("Connection ID"),connectionTitle:L.string().describe("Connection display name"),toolName:L.string().describe("Name of the tool that was called"),input:L.record(L.string(),L.unknown()).describe("Redacted tool input"),output:L.record(L.string(),L.unknown()).describe("Redacted tool output"),isError:L.boolean().describe("Whether the call resulted in an error"),errorMessage:L.string().nullish().describe("Error message if applicable"),durationMs:L.number().describe("Call duration in milliseconds"),timestamp:L.string().describe("ISO 8601 timestamp of the call"),userId:L.string().nullish().describe("User who triggered the call"),requestId:L.string().describe("Unique request identifier"),userAgent:L.string().nullish().describe("Client identifier (x-mesh-client header)"),virtualMcpId:L.string().nullish().describe("Virtual MCP (Agent) ID if routed through an agent"),properties:L.record(L.string(),L.string()).nullish().describe("Custom key-value metadata attached to the log")}),J60=r0({name:"MONITORING_LOGS_LIST",description:"List monitoring logs for tool calls in the organization",inputSchema:L.object({connectionId:L.string().optional().describe("Filter by connection ID"),virtualMcpId:L.string().optional().describe("Filter by Virtual MCP (Agent) ID"),toolName:L.string().optional().describe("Filter by tool name"),isError:L.boolean().optional().describe("Filter by error status"),startDate:L.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:L.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)"),limit:L.number().default(100).describe("Maximum number of results"),offset:L.number().default(0).describe("Offset for pagination"),properties:L.record(L.string(),L.string()).optional().describe("Filter by exact property key=value matches"),propertyKeys:L.array(L.string()).optional().describe("Filter by logs that have these property keys"),propertyPatterns:L.record(L.string(),L.string()).optional().describe("Filter by property value patterns (SQL LIKE, use % as wildcard)")}),outputSchema:L.object({logs:L.array(gA6).describe("Array of monitoring logs"),total:L.number().describe("Total number of logs matching filters"),offset:L.number().describe("Current offset for pagination"),limit:L.number().describe("Current limit for pagination")}),handler:async(X,Y)=>{let Q=I4(Y),G=X.properties||X.propertyKeys||X.propertyPatterns?{properties:X.properties,propertyKeys:X.propertyKeys,propertyPatterns:X.propertyPatterns}:void 0,Z={organizationId:Q.id,connectionId:X.connectionId,virtualMcpId:X.virtualMcpId,toolName:X.toolName,isError:X.isError,startDate:X.startDate?new Date(X.startDate):void 0,endDate:X.endDate?new Date(X.endDate):void 0,limit:X.limit,offset:X.offset,propertyFilters:G},W=await Y.storage.monitoring.query(Z);return{logs:W.logs.map((K)=>({...K,timestamp:K.timestamp instanceof Date?K.timestamp.toISOString():K.timestamp})),total:W.total,offset:X.offset,limit:X.limit}}})});var G60;var j94=d(()=>{s4();s0();G60=r0({name:"MONITORING_STATS",description:"Get aggregated statistics for tool call monitoring",inputSchema:L.object({startDate:L.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:L.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)")}),outputSchema:L.object({totalCalls:L.number().describe("Total number of tool calls"),errorRate:L.number().describe("Error rate as a decimal (0 to 1)"),avgDurationMs:L.number().describe("Average call duration in milliseconds"),errorRatePercent:L.string().describe("Error rate as a percentage string")}),handler:async(X,Y)=>{let J={organizationId:I4(Y).id,startDate:X.startDate?new Date(X.startDate):void 0,endDate:X.endDate?new Date(X.endDate):void 0},G=await Y.storage.monitoring.getStats(J);return{...G,errorRatePercent:(G.errorRate*100).toFixed(2)}}})});var C94=d(()=>{I94();j94()});var W60;var R94=d(()=>{s0();s4();W60=r0({name:"ORGANIZATION_CREATE",description:"Create a new organization",inputSchema:L.object({slug:L.string().min(1).max(50).regex(/^[a-z0-9-]+$/,"Slug must be lowercase alphanumeric with hyphens"),name:L.string().min(1).max(255),description:L.string().optional()}),outputSchema:L.object({id:L.string(),name:L.string(),slug:L.string(),logo:L.string().nullable().optional(),metadata:L.any().optional(),createdAt:L.string().datetime().describe("ISO 8601 timestamp"),members:L.array(L.any()).optional()}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=A8(Y);if(!Q)throw Error("User ID required to create organization");let J=await Y.boundAuth.organization.create({name:X.name,slug:X.slug,metadata:X.description?{description:X.description}:void 0,userId:Q});if(!J)throw Error("Failed to create organization");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var Z60;var S94=d(()=>{s0();s4();Z60=r0({name:"ORGANIZATION_LIST",description:"List all organizations user has access to",inputSchema:L.object({userId:L.string().optional()}),outputSchema:L.object({organizations:L.array(L.object({id:L.string(),name:L.string(),slug:L.string(),logo:L.string().nullable().optional(),metadata:L.any().optional(),createdAt:L.string().datetime().describe("ISO 8601 timestamp")}))}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=A8(Y),J=X.userId||Q;if(!J)throw Error("User ID required to list organizations");return{organizations:(await Y.boundAuth.organization.list(J)).map((Z)=>({...Z,createdAt:Z.createdAt instanceof Date?Z.createdAt.toISOString():Z.createdAt}))}}})});var K60;var v94=d(()=>{s0();s4();K60=r0({name:"ORGANIZATION_GET",description:"Get organization details by slug or ID",inputSchema:L.object({}),outputSchema:L.object({id:L.string(),name:L.string(),slug:L.string(),logo:L.string().nullable().optional(),metadata:L.any().optional(),createdAt:L.string().datetime().describe("ISO 8601 timestamp"),members:L.array(L.any()).optional(),invitations:L.array(L.any()).optional()}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=await Y.boundAuth.organization.get();if(!Q)throw Error("No active organization found");let J=new Date,G=Q.invitations?.filter((Z)=>new Date(Z.expiresAt)>J);return{...Q,invitations:G,createdAt:Q.createdAt instanceof Date?Q.createdAt.toISOString():Q.createdAt}}})});var $60;var k94=d(()=>{s0();s4();$60=r0({name:"ORGANIZATION_UPDATE",description:"Update an existing organization",inputSchema:L.object({id:L.string(),slug:L.string().min(1).max(50).regex(/^[a-z0-9-]+$/).optional(),name:L.string().min(1).max(255).optional(),description:L.string().optional()}),outputSchema:L.object({id:L.string(),name:L.string(),slug:L.string(),logo:L.string().nullable().optional(),metadata:L.any().optional(),createdAt:L.string().datetime().describe("ISO 8601 timestamp")}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q={};if(X.name)Q.name=X.name;if(X.slug)Q.slug=X.slug;if(X.description)Q.metadata={description:X.description};let J=await Y.boundAuth.organization.update({organizationId:X.id,data:Q});if(!J)throw Error("Failed to update organization");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var H60;var _94=d(()=>{s0();s4();H60=r0({name:"ORGANIZATION_DELETE",description:"Delete an organization",inputSchema:L.object({id:L.string()}),outputSchema:L.object({success:L.boolean(),id:L.string()}),handler:async(X,Y)=>{return H4(Y),await Y.access.check(),await Y.boundAuth.organization.delete(X.id),{success:!0,id:X.id}}})});var xw;var F60=d(()=>{s0();xw=L.object({title:L.string(),url:L.string(),icon:L.string()})});var q60;var y94=d(()=>{s0();s4();F60();q60=r0({name:"ORGANIZATION_SETTINGS_GET",description:"Get organization-level settings",inputSchema:L.object({}),outputSchema:L.object({organizationId:L.string(),sidebar_items:L.array(xw).nullable().optional(),enabled_plugins:L.array(L.string()).nullable().optional(),createdAt:L.string().datetime().optional().describe("ISO 8601 timestamp"),updatedAt:L.string().datetime().optional().describe("ISO 8601 timestamp")}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=Y.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let J=await Y.storage.organizationSettings.get(Q);if(!J)return{organizationId:Q};return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt,updatedAt:J.updatedAt instanceof Date?J.updatedAt.toISOString():J.updatedAt}}})});var V60;var f94=d(()=>{s0();s4();F60();V60=r0({name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization-level settings",inputSchema:L.object({organizationId:L.string(),sidebar_items:L.array(xw).optional(),enabled_plugins:L.array(L.string()).optional()}),outputSchema:L.object({organizationId:L.string(),sidebar_items:L.array(xw).nullable().optional(),enabled_plugins:L.array(L.string()).nullable().optional(),createdAt:L.string().datetime().describe("ISO 8601 timestamp"),updatedAt:L.string().datetime().describe("ISO 8601 timestamp")}),handler:async(X,Y)=>{if(H4(Y),await Y.access.check(),Y.organization&&Y.organization.id!==X.organizationId)throw Error("Cannot update settings for a different organization");let Q=await Y.storage.organizationSettings.upsert(X.organizationId,{sidebar_items:X.sidebar_items,enabled_plugins:X.enabled_plugins});return{...Q,createdAt:Q.createdAt instanceof Date?Q.createdAt.toISOString():Q.createdAt,updatedAt:Q.updatedAt instanceof Date?Q.updatedAt.toISOString():Q.updatedAt}}})});var z60;var b94=d(()=>{s0();s4();z60=r0({name:"ORGANIZATION_MEMBER_ADD",description:"Add a member to an organization",inputSchema:L.object({organizationId:L.string().optional(),userId:L.string(),role:L.array(L.string())}),outputSchema:L.object({id:L.string(),organizationId:L.string(),userId:L.string(),role:L.union([L.string(),L.array(L.string())]),createdAt:L.string().datetime().describe("ISO 8601 timestamp")}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=X.organizationId||Y.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let J=await Y.boundAuth.organization.addMember({organizationId:Q,userId:X.userId,role:X.role});if(!J)throw Error("Failed to add member");return{...J,role:J.role,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var U60;var h94=d(()=>{s0();s4();U60=r0({name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove a member from an organization",inputSchema:L.object({organizationId:L.string().optional(),memberIdOrEmail:L.string()}),outputSchema:L.object({success:L.boolean(),memberIdOrEmail:L.string()}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=X.organizationId||Y.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");return await Y.boundAuth.organization.removeMember({organizationId:Q,memberIdOrEmail:X.memberIdOrEmail}),{success:!0,memberIdOrEmail:X.memberIdOrEmail}}})});var B60;var x94=d(()=>{s0();s4();B60=r0({name:"ORGANIZATION_MEMBER_LIST",description:"List all members in an organization",inputSchema:L.object({limit:L.number().optional(),offset:L.number().optional()}),outputSchema:L.object({members:L.array(L.object({id:L.string(),organizationId:L.string(),userId:L.string(),role:L.string(),createdAt:L.string().datetime().describe("ISO 8601 timestamp"),user:L.object({id:L.string(),name:L.string(),email:L.string(),image:L.string().optional()}).optional()}))}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=Y.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let J=await Y.boundAuth.organization.listMembers({organizationId:Q,limit:X.limit,offset:X.offset});return{members:(Array.isArray(J)?J:[]).map((Z)=>({...Z,createdAt:Z.createdAt instanceof Date?Z.createdAt.toISOString():Z.createdAt}))}}})});var D60;var g94=d(()=>{s0();s4();D60=r0({name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Update a member's role in an organization",inputSchema:L.object({organizationId:L.string().optional(),memberId:L.string(),role:L.array(L.string())}),outputSchema:L.object({id:L.string(),organizationId:L.string(),userId:L.string(),role:L.union([L.literal("admin"),L.literal("member"),L.literal("owner")]),createdAt:L.string().datetime().describe("ISO 8601 timestamp"),user:L.object({email:L.string(),name:L.string(),image:L.string().optional()})}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=X.organizationId||Y.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let J=await Y.boundAuth.organization.updateMemberRole({organizationId:Q,memberId:X.memberId,role:X.role});if(!J)throw Error("Failed to update member role");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var u94=d(()=>{R94();S94();v94();k94();_94();y94();f94();b94();h94();x94();g94()});var m94,CG,l94,d94;var XH=d(()=>{s0();m94=L.object({id:L.string().describe("Unique message ID"),threadId:L.string().describe("ID of the parent thread"),metadata:L.unknown().optional().describe("Optional message metadata"),parts:L.array(L.record(L.string(),L.unknown())).describe("Message content parts (AI SDK UIMessagePart format)"),role:L.enum(["user","assistant","system"]).describe("Message role"),createdAt:L.string().datetime().describe("Timestamp of creation"),updatedAt:L.string().datetime().describe("Timestamp of last update")}),CG=L.object({id:L.string().describe("Unique thread ID"),organizationId:L.string().describe("Organization this thread belongs to"),title:L.string().describe("Thread title"),description:L.string().nullable().describe("Thread description"),createdAt:L.string().datetime().describe("Timestamp of creation"),updatedAt:L.string().datetime().describe("Timestamp of last update"),hidden:L.boolean().optional().describe("Whether the thread is hidden"),createdBy:L.string().describe("User ID who created the thread"),updatedBy:L.string().nullable().describe("User ID who last updated the thread")}),l94=L.object({id:L.string().optional().describe("Optional custom ID for the thread"),title:L.string().describe("Thread title"),description:L.string().nullish().describe("Thread description")}),d94=L.object({title:L.string().optional().describe("New thread title"),description:L.string().nullish().describe("New thread description"),hidden:L.boolean().optional().describe("Whether the thread is hidden")})});var lA6,dA6,N60;var p94=d(()=>{s0();s4();XH();vS();lA6=L.object({data:l94.describe("Data for the new thread (id is auto-generated if not provided)")}),dA6=L.object({item:CG.describe("The created thread entity")}),N60=r0({name:"COLLECTION_THREADS_CREATE",description:"Create a new thread in the organization",inputSchema:lA6,outputSchema:dA6,handler:async(X,Y)=>{H4(Y);let Q=I4(Y);await Y.access.check();let J=A8(Y);if(!J)throw Error("User ID required to create thread");let G=X.data.id??RV("thrd"),Z=await Y.storage.threads.create({id:G,organizationId:Q.id,title:X.data.title,description:X.data.description,createdBy:J});return{item:{...Z,hidden:Z.hidden??!1}}}})});var pA6,cA6,O60;var c94=d(()=>{K5();s4();XH();s0();pA6=t3.extend({where:L.object({created_by:L.string().optional()}).optional()}),cA6=e3(CG),O60=r0({name:"COLLECTION_THREADS_LIST",description:"List all threads in the organization with filtering, sorting, and pagination",inputSchema:pA6,outputSchema:cA6,handler:async(X,Y)=>{await Y.access.check();let Q=Y.auth.user?.id;if(!Q)throw Error("User ID required to list threads");let J=I4(Y),G=X.offset??0,Z=X.limit??100,{threads:W,total:K}=await Y.storage.threads.list(J.id,Q,{limit:Z,offset:G}),$=G+Z<K;return{items:W.map((H)=>({...H,hidden:H.hidden??!1})),totalCount:K,hasMore:$}}})});var nA6,L60;var n94=d(()=>{K5();s4();XH();nA6=Pw(CG),L60=r0({name:"COLLECTION_THREADS_GET",description:"Get thread details by ID",inputSchema:Mw,outputSchema:nA6,handler:async(X,Y)=>{H4(Y);let Q=I4(Y);await Y.access.check();let J=await Y.storage.threads.get(X.id);if(!J||J.organizationId!==Q.id)return{item:null};return{item:{...J,hidden:J.hidden??!1}}}})});var iA6,aA6,w60;var i94=d(()=>{s0();s4();XH();iA6=L.object({id:L.string().describe("ID of the thread to update"),data:d94.describe("Partial thread data to update")}),aA6=L.object({item:CG.describe("The updated thread entity")}),w60=r0({name:"COLLECTION_THREADS_UPDATE",description:"Update an existing thread in the organization",inputSchema:iA6,outputSchema:aA6,handler:async(X,Y)=>{H4(Y);let Q=I4(Y);await Y.access.check();let J=A8(Y);if(!J)throw Error("User ID required to update thread");let{id:G,data:Z}=X,W=await Y.storage.threads.get(G);if(!W||W.organizationId!==Q.id)throw Error("Thread not found in organization");let K=await Y.storage.threads.update(G,{title:Z.title,description:Z.description,hidden:Z.hidden,updatedBy:J});return{item:{...K,hidden:K.hidden??!1}}}})});var M60;var a94=d(()=>{K5();s4();XH();M60=r0({name:"COLLECTION_THREADS_DELETE",description:"Delete a thread",inputSchema:Tw,outputSchema:Aw(CG),handler:async(X,Y)=>{H4(Y);let Q=I4(Y);await Y.access.check();let J=await Y.storage.threads.get(X.id);if(!J)throw Error(`Thread not found: ${X.id}`);if(J.organizationId!==Q.id)throw Error(`Thread not found: ${X.id}`);return await Y.storage.threads.delete(X.id),{item:{...J,hidden:J.hidden??!1}}}})});var rA6,oA6,P60;var r94=d(()=>{s0();s4();XH();rA6=L.object({threadId:L.string().describe("ID of the thread to list messages for"),limit:L.number().optional().describe("Maximum number of messages to return"),offset:L.number().optional().describe("Number of messages to skip")}),oA6=L.object({items:L.array(m94).describe("List of thread messages"),totalCount:L.number().describe("Total number of messages in the thread"),hasMore:L.boolean().describe("Whether there are more messages available")}),P60=r0({name:"COLLECTION_THREAD_MESSAGES_LIST",description:"List all messages for a specific thread",inputSchema:rA6,outputSchema:oA6,handler:async(X,Y)=>{let Q=I4(Y);await Y.access.check();let J=await Y.storage.threads.get(X.threadId);if(!J||J.organizationId!==Q.id)throw Error("Thread not found in organization");let G=X.offset??0,Z=X.limit??100,{messages:W,total:K}=await Y.storage.threads.listMessages(X.threadId,{limit:Z,offset:G}),$=G+Z<K;return{items:W,totalCount:K,hasMore:$}}})});var o94=d(()=>{p94();c94();n94();i94();a94();r94()});var tA6,eA6,T60;var s94=d(()=>{s0();s4();tA6=L.object({id:L.string().min(1)}),eA6=L.object({user:L.object({id:L.string(),name:L.string(),email:L.string(),image:L.string().nullable()}).nullable()}),T60=r0({name:"USER_GET",description:"Get a user by id (restricted to shared organizations)",inputSchema:tA6,outputSchema:eA6,handler:async(X,Y)=>{await Y.access.check(),H4(Y);let Q=A8(Y);if(!Q)throw Error("Authentication required");let J=await Y.storage.users.findById(X.id,Q);if(!J)return{user:null};return{user:{id:J.id,name:J.name,email:J.email,image:J.image??null}}}})});var t94=d(()=>{s94()});var XX4={};m4(XX4,{managementMCP:()=>YE6,ALL_TOOLS:()=>e94});var e94,YE6=(X)=>{let Y=e94.map((J)=>({name:J.name,description:J.description,inputSchema:J.inputSchema,outputSchema:J.outputSchema,handler:async(G)=>{return X.access.setToolName(J.name),await J.execute(G,X)}}));return X14({name:"mcp-mesh-management",version:"1.0.0"}).withTools(Y).build()};var YX4=d(()=>{Y14();B14();H84();J94();K94();N94();E94();C94();u94();o94();t94();e94=[W60,Z60,K60,$60,H60,q60,V60,z60,U60,B60,D60,C40,h40,x40,u40,m40,l40,s40,e40,X60,Y60,Q60,Z94,J60,G60,Q40,G40,W40,J40,d40,p40,c40,n40,i40,a40,r40,T60,E40,I40,j40,N60,O60,L60,w60,M60,P60]});O_();import{Migrator as FX4}from"kysely";var d60={benchmark:()=>Promise.resolve().then(() => (l60(),m60)).then((X)=>X.seed)};async function p60(X,Y){let Q=d60[Y];if(!Q)throw Error(`Unknown seed: ${Y}. Available: ${Object.keys(d60).join(", ")}`);let J=await Q();console.log(`\uD83C\uDF31 Running seed: ${Y}`);let G=await J(X);return console.log(`\u2705 Seed "${Y}" completed`),G}RG();BQ();RG();BQ();HX();$9();var z8=(X,Y="ms")=>{return new Date(Date.now()+(Y==="sec"?X*1000:X))},pA=new WeakMap;function wY0(X,Y){let Q=Y.fields,J={};for(let G in X){let Z=Q[G];if(!Z){J[G]=X[G];continue}if(Z.returned===!1)continue;J[G]=X[G]}return J}function cA(X,Y){if(!pA.has(X))pA.set(X,new Map);let Q=pA.get(X);if(Q.has(Y))return Q.get(Y);let J={...Y==="user"?X.user?.additionalFields:{},...Y==="session"?X.session?.additionalFields:{}};for(let G of X.plugins||[])if(G.schema&&G.schema[Y])J={...J,...G.schema[Y].fields};return pA.get(X).set(Y,J),J}function H9(X,Y){return{...wY0(Y,{fields:cA(X,"user")}),id:Y.id}}function T5(X,Y){return wY0(Y,{fields:cA(X,"session")})}function ix(X,Y){let Q=Y.action||"create",J=Y.fields,G=Object.assign(Object.create(null),null);for(let Z in J){if(Z in X){if(J[Z].input===!1){if(J[Z].defaultValue!==void 0){if(Q!=="update"){G[Z]=J[Z].defaultValue;continue}}if(X[Z])throw new c("BAD_REQUEST",{message:`${Z} is not allowed to be set`});continue}if(J[Z].validator?.input&&X[Z]!==void 0){G[Z]=J[Z].validator.input["~standard"].validate(X[Z]);continue}if(J[Z].transform?.input&&X[Z]!==void 0){G[Z]=J[Z].transform?.input(X[Z]);continue}G[Z]=X[Z];continue}if(J[Z].defaultValue!==void 0&&Q==="create"){if(typeof J[Z].defaultValue==="function"){G[Z]=J[Z].defaultValue();continue}G[Z]=J[Z].defaultValue;continue}if(J[Z].required&&Q==="create")throw new c("BAD_REQUEST",{message:`${Z} is required`})}return G}function nA(X,Y={},Q){return ix(Y,{fields:cA(X,"user"),action:Q})}function ax(X,Y){return ix(Y,{fields:cA(X,"session")})}function RX(X,Y){if(!Y)return X;for(let Q in Y){let J=Y[Q]?.modelName;if(J)X[Q].modelName=J;for(let G in X[Q].fields){let Z=Y[Q]?.fields?.[G];if(!Z)continue;X[Q].fields[G].fieldName=Z}}return X}KY();s0();var eG4="127.0.0.1";function vW(X,Y){if(Y.advanced?.ipAddress?.disableIpTracking)return null;if(dG()||sH())return eG4;let Q="headers"in X?X.headers:X,J=Y.advanced?.ipAddress?.ipAddressHeaders||["x-forwarded-for"];for(let G of J){let Z="get"in Q?Q.get(G):Q[G];if(typeof Z==="string"){let W=Z.split(",")[0].trim();if(X74(W))return W}}return null}function X74(X){if(gK().safeParse(X).success)return!0;if(uK().safeParse(X).success)return!0;return!1}FX();L5();KY();E8();import{sql as E5}from"kysely";async function EY0(X,Y){let Q;if(!X.database){let J=bY(X),G=Object.keys(J).reduce((W,K)=>{return W[K]=[],W},{}),{memoryAdapter:Z}=await Promise.resolve().then(() => (AY0(),TY0));Q=Z(G)(X)}else if(typeof X.database==="function")Q=X.database(X);else Q=await Y(X);if(!Q.transaction)v4.warn("Adapter does not correctly implement transaction function, patching it automatically. Please update your adapter implementation."),Q.transaction=async(J)=>{return J(Q)};return Q}async function Xg(X){return EY0(X,async(Y)=>{let{createKyselyAdapter:Q}=await Promise.resolve().then(() => (ex(),tx)),{kysely:J,databaseType:G,transaction:Z}=await Q(Y);if(!J)throw new T4("Failed to initialize database adapter");let{kyselyAdapter:W}=await Promise.resolve().then(() => (ex(),tx));return W(J,{type:G||"sqlite",debugLogs:Y.database&&"debugLogs"in Y.database?Y.database.debugLogs:!1,transaction:Z})(Y)})}function IY0(X,Y){let Q=Y.hooks;async function J($,H,F){let q=await hY(),V=$;for(let N of Q||[]){let O=N[H]?.create?.before;if(O){let w=await O(V,q);if(w===!1)return null;if(typeof w==="object"&&"data"in w)V={...V,...w.data}}}let U=F?await F.fn(V):null,D=!F||F.executeMainFn?await(await K1(X)).create({model:H,data:V,forceAllowId:!0}):U;for(let N of Q||[]){let O=N[H]?.create?.after;if(O)await O(D,q)}return D}async function G($,H,F,q){let V=await hY(),U=$;for(let O of Q||[]){let w=O[F]?.update?.before;if(w){let E=await w($,V);if(E===!1)return null;if(typeof E==="object"&&"data"in E)U={...U,...E.data}}}let D=q?await q.fn(U):null,N=!q||q.executeMainFn?await(await K1(X)).update({model:F,update:U,where:H}):D;for(let O of Q||[]){let w=O[F]?.update?.after;if(w)await w(N,V)}return N}async function Z($,H,F,q){let V=await hY(),U=$;for(let O of Q||[]){let w=O[F]?.update?.before;if(w){let E=await w($,V);if(E===!1)return null;if(typeof E==="object"&&"data"in E)U={...U,...E.data}}}let D=q?await q.fn(U):null,N=!q||q.executeMainFn?await(await K1(X)).updateMany({model:F,update:U,where:H}):D;for(let O of Q||[]){let w=O[F]?.update?.after;if(w)await w(N,V)}return N}async function W($,H,F){let q=await hY(),V=null;try{V=(await(await K1(X)).findMany({model:H,where:$,limit:1}))[0]||null}catch(N){}if(V)for(let N of Q||[]){let O=N[H]?.delete?.before;if(O){if(await O(V,q)===!1)return null}}let U=F?await F.fn($):null,D=!F||F.executeMainFn?await(await K1(X)).delete({model:H,where:$}):U;if(V)for(let N of Q||[]){let O=N[H]?.delete?.after;if(O)await O(V,q)}return D}async function K($,H,F){let q=await hY(),V=[];try{V=await(await K1(X)).findMany({model:H,where:$})}catch(N){}for(let N of V)for(let O of Q||[]){let w=O[H]?.delete?.before;if(w){if(await w(N,q)===!1)return null}}let U=F?await F.fn($):null,D=!F||F.executeMainFn?await(await K1(X)).deleteMany({model:H,where:$}):U;for(let N of V)for(let O of Q||[]){let w=O[H]?.delete?.after;if(w)await w(N,q)}return D}return{createWithHooks:J,updateWithHooks:G,updateManyWithHooks:Z,deleteWithHooks:W,deleteManyWithHooks:K}}var eA=(X,Y)=>{let{logger:Q,options:J}=Y,G=J.secondaryStorage,Z=J.session?.expiresIn||604800,{createWithHooks:W,updateWithHooks:K,updateManyWithHooks:$,deleteWithHooks:H,deleteManyWithHooks:F}=IY0(X,Y);async function q(V){if(!G)return;let U=await G.get(`active-sessions-${V.id}`);if(!U)return;let D=Date.now(),N=(B1(U)||[]).filter((O)=>O.expiresAt>D);await Promise.all(N.map(async({token:O})=>{let w=await G.get(O);if(!w)return;let E=B1(w);if(!E)return;let C=Math.max(Math.floor(new Date(E.session.expiresAt).getTime()-D)/1000,0);await G.set(O,JSON.stringify({session:E.session,user:V}),Math.floor(C))}))}return{createOAuthUser:async(V,U)=>{return oz(X,async()=>{let D=await W({createdAt:new Date,updatedAt:new Date,...V},"user",void 0);return{user:D,account:await W({...U,userId:D.id,createdAt:new Date,updatedAt:new Date},"account",void 0)}})},createUser:async(V)=>{return await W({createdAt:new Date,updatedAt:new Date,...V,email:V.email?.toLowerCase()},"user",void 0)},createAccount:async(V)=>{return await W({createdAt:new Date,updatedAt:new Date,...V},"account",void 0)},listSessions:async(V)=>{if(G){let U=await G.get(`active-sessions-${V}`);if(!U)return[];let D=B1(U)||[],N=Date.now(),O=D.filter((E)=>E.expiresAt>N),w=[];for(let E of O){let C=await G.get(E.token);if(C){let A=B1(C);if(!A)return[];let T=T5(Y.options,{...A.session,expiresAt:new Date(A.session.expiresAt)});w.push(T)}}return w}return await(await K1(X)).findMany({model:"session",where:[{field:"userId",value:V}]})},listUsers:async(V,U,D,N)=>{return await(await K1(X)).findMany({model:"user",limit:V,offset:U,sortBy:D,where:N})},countTotalUsers:async(V)=>{let U=await(await K1(X)).count({model:"user",where:V});if(typeof U==="string")return parseInt(U);return U},deleteUser:async(V)=>{if(G)await G.delete(`active-sessions-${V}`);if(!G||J.session?.storeSessionInDatabase)await F([{field:"userId",value:V}],"session",void 0);await F([{field:"userId",value:V}],"account",void 0),await H([{field:"id",value:V}],"user",void 0)},createSession:async(V,U,D,N)=>{let O=await hY().catch(()=>null),w=O?.headers||O?.request?.headers,{id:E,...C}=D||{},A=ax(O?.context.options??J,{}),T={ipAddress:O?.request||O?.headers?vW(O?.request||O?.headers,O?.context.options)||"":"",userAgent:w?.get("user-agent")||"",...C,expiresAt:U?z8(86400,"sec"):z8(Z,"sec"),userId:V,token:x8(32),createdAt:new Date,updatedAt:new Date,...A,...N?C:{}};return await W(T,"session",G?{fn:async(j)=>{let R=await G.get(`active-sessions-${V}`),v=[],_=Date.now();if(R)v=B1(R)||[],v=v.filter((u)=>u.expiresAt>_);let y=v.sort((u,t)=>u.expiresAt-t.expiresAt),f=y.at(-1)?.expiresAt;if(y.push({token:T.token,expiresAt:T.expiresAt.getTime()}),!f||f<T.expiresAt.getTime())f=T.expiresAt.getTime();let a=Math.max(Math.floor((f-_)/1000),0);if(a>0)await G.set(`active-sessions-${V}`,JSON.stringify(y),a);let x=await X.findOne({model:"user",where:[{field:"id",value:V}]}),k=Math.max(Math.floor((T.expiresAt.getTime()-_)/1000),0);if(k>0)await G.set(T.token,JSON.stringify({session:j,user:x}),k);return j},executeMainFn:J.session?.storeSessionInDatabase}:void 0)},findSession:async(V)=>{if(G){let O=await G.get(V);if(!O&&!J.session?.storeSessionInDatabase)return null;if(O){let w=B1(O);if(!w)return null;return{session:T5(Y.options,{...w.session,expiresAt:new Date(w.session.expiresAt),createdAt:new Date(w.session.createdAt),updatedAt:new Date(w.session.updatedAt)}),user:H9(Y.options,{...w.user,createdAt:new Date(w.user.createdAt),updatedAt:new Date(w.user.updatedAt)})}}}let U=await(await K1(X)).findOne({model:"session",where:[{value:V,field:"token"}],join:{user:!0}});if(!U)return null;let{user:D,...N}=U;if(!D)return null;return{session:T5(Y.options,N),user:H9(Y.options,D)}},findSessions:async(V)=>{if(G){let D=[];for(let N of V){let O=await G.get(N);if(O){let w=B1(O);if(!w)return[];let E={session:{...w.session,expiresAt:new Date(w.session.expiresAt)},user:{...w.user,createdAt:new Date(w.user.createdAt),updatedAt:new Date(w.user.updatedAt)}};D.push(E)}}return D}let U=await(await K1(X)).findMany({model:"session",where:[{field:"token",value:V,operator:"in"}],join:{user:!0}});if(!U.length)return[];if(U.some((D)=>!D.user))return[];return U.map((D)=>{let{user:N,...O}=D;return{session:O,user:N}})},updateSession:async(V,U)=>{return await K(U,[{field:"token",value:V}],"session",G?{async fn(D){let N=await G.get(V),O=null;if(N){let w=B1(N);if(!w)return null;return O={...w.session,...D},O}else return null},executeMainFn:J.session?.storeSessionInDatabase}:void 0)},deleteSession:async(V)=>{if(G){let U=await G.get(V);if(U){let{session:D}=B1(U)??{};if(!D){Q.error("Session not found in secondary storage");return}let N=D.userId,O=await G.get(`active-sessions-${N}`);if(O){let w=B1(O)||[],E=Date.now(),C=w.filter((T)=>T.expiresAt>E&&T.token!==V),A=C.sort((T,j)=>T.expiresAt-j.expiresAt).at(-1)?.expiresAt;if(C.length>0&&A&&A>Date.now())await G.set(`active-sessions-${N}`,JSON.stringify(C),Math.floor((A-E)/1000));else await G.delete(`active-sessions-${N}`)}else Q.error("Active sessions list not found in secondary storage")}if(await G.delete(V),!J.session?.storeSessionInDatabase||Y.options.session?.preserveSessionInDatabase)return}await(await K1(X)).delete({model:"session",where:[{field:"token",value:V}]})},deleteAccounts:async(V)=>{await F([{field:"userId",value:V}],"account",void 0)},deleteAccount:async(V)=>{await H([{field:"id",value:V}],"account",void 0)},deleteSessions:async(V)=>{if(G){if(typeof V==="string"){let U=await G.get(`active-sessions-${V}`),D=U?B1(U):[];if(!D)return;for(let N of D)await G.delete(N.token)}else for(let U of V)if(await G.get(U))await G.delete(U);if(!J.session?.storeSessionInDatabase||Y.options.session?.preserveSessionInDatabase)return}await F([{field:Array.isArray(V)?"token":"userId",value:V,operator:Array.isArray(V)?"in":void 0}],"session",void 0)},findOAuthUser:async(V,U,D)=>{let N=await(await K1(X)).findMany({model:"account",where:[{value:U,field:"accountId"}],join:{user:!0}}).then((O)=>{return O.find((w)=>w.providerId===D)});if(N)if(N.user)return{user:N.user,accounts:[N]};else{let O=await(await K1(X)).findOne({model:"user",where:[{value:V.toLowerCase(),field:"email"}]});if(O)return{user:O,accounts:[N]};return null}else{let O=await(await K1(X)).findOne({model:"user",where:[{value:V.toLowerCase(),field:"email"}]});if(O)return{user:O,accounts:await(await K1(X)).findMany({model:"account",where:[{value:O.id,field:"userId"}]})||[]};else return null}},findUserByEmail:async(V,U)=>{let D=await(await K1(X)).findOne({model:"user",where:[{value:V.toLowerCase(),field:"email"}],join:{...U?.includeAccounts?{account:!0}:{}}});if(!D)return null;let{account:N,...O}=D;return{user:O,accounts:N??[]}},findUserById:async(V)=>{if(!V)return null;return await(await K1(X)).findOne({model:"user",where:[{field:"id",value:V}]})},linkAccount:async(V)=>{return await W({createdAt:new Date,updatedAt:new Date,...V},"account",void 0)},updateUser:async(V,U)=>{let D=await K(U,[{field:"id",value:V}],"user",void 0);return await q(D),await q(D),D},updateUserByEmail:async(V,U)=>{let D=await K(U,[{field:"email",value:V.toLowerCase()}],"user",void 0);return await q(D),await q(D),D},updatePassword:async(V,U)=>{await $({password:U},[{field:"userId",value:V},{field:"providerId",value:"credential"}],"account",void 0)},findAccounts:async(V)=>{return await(await K1(X)).findMany({model:"account",where:[{field:"userId",value:V}]})},findAccount:async(V)=>{return await(await K1(X)).findOne({model:"account",where:[{field:"accountId",value:V}]})},findAccountByProviderId:async(V,U)=>{return await(await K1(X)).findOne({model:"account",where:[{field:"accountId",value:V},{field:"providerId",value:U}]})},findAccountByUserId:async(V)=>{return await(await K1(X)).findMany({model:"account",where:[{field:"userId",value:V}]})},updateAccount:async(V,U)=>{return await K(U,[{field:"id",value:V}],"account",void 0)},createVerificationValue:async(V)=>{return await W({createdAt:new Date,updatedAt:new Date,...V},"verification",void 0)},findVerificationValue:async(V)=>{let U=await(await K1(X)).findMany({model:"verification",where:[{field:"identifier",value:V}],sortBy:{field:"createdAt",direction:"desc"},limit:1});if(!J.verification?.disableCleanup)await(await K1(X)).deleteMany({model:"verification",where:[{field:"expiresAt",value:new Date,operator:"lt"}]});return U[0]},deleteVerificationValue:async(V)=>{await(await K1(X)).delete({model:"verification",where:[{field:"id",value:V}]})},deleteVerificationByIdentifier:async(V)=>{await(await K1(X)).delete({model:"verification",where:[{field:"identifier",value:V}]})},updateVerificationValue:async(V,U)=>{return await K(U,[{field:"id",value:V}],"verification",void 0)}}};function jY0(X){let Y=bY(X),Q={};for(let J in Y){let G=Y[J],Z=G.fields,W={};if(Object.entries(Z).forEach(([K,$])=>{if(W[$.fieldName||K]=$,$.references){let H=Y[$.references.model];if(H)W[$.fieldName||K].references={...$.references,model:H.modelName,field:$.references.field}}}),Q[G.modelName]){Q[G.modelName].fields={...Q[G.modelName].fields,...W};continue}Q[G.modelName]={fields:W,order:G.order||1/0}}return Q}var Z74={postgres:{string:["character varying","varchar","text","uuid"],number:["int4","integer","bigint","smallint","numeric","real","double precision"],boolean:["bool","boolean"],date:["timestamptz","timestamp","date"],json:["json","jsonb"]},mysql:{string:["varchar","text","uuid"],number:["integer","int","bigint","smallint","decimal","float","double"],boolean:["boolean","tinyint"],date:["timestamp","datetime","date"],json:["json"]},sqlite:{string:["TEXT"],number:["INTEGER","REAL"],boolean:["INTEGER","BOOLEAN"],date:["DATE","INTEGER"],json:["TEXT"]},mssql:{string:["varchar","nvarchar","uniqueidentifier"],number:["int","bigint","smallint","decimal","float","double"],boolean:["bit","smallint"],date:["datetime2","date","datetime"],json:["varchar","nvarchar"]}};function CY0(X,Y,Q){function J(Z){return Z.toLowerCase().split("(")[0].trim()}if(Y==="string[]"||Y==="number[]")return X.toLowerCase().includes("json");let G=Z74[Q];return(Array.isArray(Y)?G.string.map((Z)=>Z.toLowerCase()):G[Y].map((Z)=>Z.toLowerCase())).includes(J(X))}async function K74(X){try{let Y=await E5`SHOW search_path`.execute(X);if(Y.rows[0]?.search_path)return Y.rows[0].search_path.split(",").map((Q)=>Q.trim()).map((Q)=>Q.replace(/^["']|["']$/g,"")).filter((Q)=>!Q.startsWith("$"))[0]||"public"}catch(Y){}return"public"}async function CB(X){let Y=jY0(X),Q=eH(X.logger),{kysely:J,databaseType:G}=await cw(X);if(!G)Q.warn("Could not determine database type, defaulting to sqlite. Please provide a type in the database options to avoid this."),G="sqlite";if(!J)Q.error("Only kysely adapter is supported for migrations. You can use `generate` command to generate the schema, if you're using a different adapter."),process.exit(1);let Z="public";if(G==="postgres"){Z=await K74(J),Q.debug(`PostgreSQL migration: Using schema '${Z}' (from search_path)`);try{if(!(await E5`
|
|
370
370
|
SELECT schema_name
|
|
371
371
|
FROM information_schema.schemata
|
|
372
372
|
WHERE schema_name = ${Z}
|