@decocms/mesh 2.38.2 → 2.38.3
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-z3xwiUwg.js → AlertCircle-DwLOjdfH.js} +1 -1
- package/dist/client/assets/{ArrowLeft-BkoJglZy.js → ArrowLeft-kGx3Y-zX.js} +1 -1
- package/dist/client/assets/{ArrowUp-BAMBJKzk.js → ArrowUp-DWcXOBpz.js} +1 -1
- package/dist/client/assets/{Check-BK9-0hKa.js → Check-B2vj72U5.js} +1 -1
- package/dist/client/assets/{ChevronDown-PIP2u0bO.js → ChevronDown-Vb06lc-B.js} +1 -1
- package/dist/client/assets/{Code01-Bur40qHc.js → Code01-DwHTWnoR.js} +1 -1
- package/dist/client/assets/{Copy01-BOhF0ZEB.js → Copy01-BAk05E9H.js} +1 -1
- package/dist/client/assets/{CpuChip02-BTAUjBs1.js → CpuChip02-DbAeAdPe.js} +1 -1
- package/dist/client/assets/{DotsHorizontal-DxGrUc9a.js → DotsHorizontal-Cj7CLHDn.js} +1 -1
- package/dist/client/assets/{DotsVertical-D61roAg3.js → DotsVertical-XYYRNoTX.js} +1 -1
- package/dist/client/assets/{Download01-DH0bL3Nt.js → Download01-CHXxU49K.js} +1 -1
- package/dist/client/assets/{Edit01-DINJ246_.js → Edit01-B9xu7jSw.js} +1 -1
- package/dist/client/assets/{File06-DVkrNas0.js → File06-D7bjpxHc.js} +1 -1
- package/dist/client/assets/{FilterLines-so_Nzmiv.js → FilterLines-CIEdE4Wb.js} +1 -1
- package/dist/client/assets/{FlipBackward-iQ8t51Yv.js → FlipBackward-CRoccaVQ.js} +1 -1
- package/dist/client/assets/{GitBranch01-T4MUtqYK.js → GitBranch01-B_LsZRsF.js} +1 -1
- package/dist/client/assets/{Grid01-CN_8958k.js → Grid01-DvrY1gt1.js} +1 -1
- package/dist/client/assets/{Home02-DuEnlN2j.js → Home02-_JdnGU0Y.js} +1 -1
- package/dist/client/assets/{Image01-CAZIUcM5.js → Image01-WlrQGekP.js} +1 -1
- package/dist/client/assets/{Inbox01-CM3kHNUT.js → Inbox01-Cx7mk7qN.js} +1 -1
- package/dist/client/assets/{InfoCircle-yeMjcoma.js → InfoCircle-BV74k_Yn.js} +1 -1
- package/dist/client/assets/{Key01-9yBwokED.js → Key01-CRs4BGmx.js} +1 -1
- package/dist/client/assets/{LinkExternal01-DVQPzyFK.js → LinkExternal01-H-oJkxYN.js} +1 -1
- package/dist/client/assets/{List-BuWxjuK8.js → List-BCcNlZrf.js} +1 -1
- package/dist/client/assets/{Loading01-D1yLQLik.js → Loading01-Dul6ue0E.js} +1 -1
- package/dist/client/assets/{Lock01-RqyglEYd.js → Lock01-Cy1pPqT8.js} +1 -1
- package/dist/client/assets/{Play-DVdw4qV-.js → Play-BpLCryum.js} +1 -1
- package/dist/client/assets/{Plus-Je-soon7.js → Plus-BVDMzeyp.js} +1 -1
- package/dist/client/assets/{SearchMd-CbtolPap.js → SearchMd-jGEmiNrX.js} +1 -1
- package/dist/client/assets/{Terminal-DYGeKWvi.js → Terminal-CE84-sCv.js} +1 -1
- package/dist/client/assets/{Trash01-CZvA_s0Y.js → Trash01-B0ak1X_N.js} +1 -1
- package/dist/client/assets/{Upload01-DhaDMFFD.js → Upload01-C0kHDVw4.js} +1 -1
- package/dist/client/assets/{X-sxVQmAsr.js → X-BLWQxpEf.js} +1 -1
- package/dist/client/assets/{XClose-zzu-jidq.js → XClose-DB-yTUBg.js} +1 -1
- package/dist/client/assets/{agent-detail-BlRpinmR.js → agent-detail-DmNNNO27.js} +1 -1
- package/dist/client/assets/{agents-DknJreAQ.js → agents-Cc3M23qv.js} +1 -1
- package/dist/client/assets/{alert-dialog-CVkwkecf.js → alert-dialog-djFlPxmw.js} +1 -1
- package/dist/client/assets/{auth-catchall-w4I8mOfz.js → auth-catchall-BJHCOfwt.js} +1 -1
- package/dist/client/assets/{avatar-C9tVSVlv.js → avatar-B5p9MTms.js} +1 -1
- package/dist/client/assets/{badge-C7J4I2Hj.js → badge-BSYGnPtt.js} +1 -1
- package/dist/client/assets/{binder-CbjhFDGc.js → binder-DWCHeQZ9.js} +1 -1
- package/dist/client/assets/{button-CceSuFKi.js → button-AdEzXtPt.js} +1 -1
- package/dist/client/assets/{card-BGHb8OmC.js → card-CQNrgAR3.js} +1 -1
- package/dist/client/assets/{checkbox-Cu04V43g.js → checkbox-3cM8_JBb.js} +1 -1
- package/dist/client/assets/{collection-detail-D2oIsKq-.js → collection-detail-BOnOtOYD.js} +1 -1
- package/dist/client/assets/{collection-display-button-Df_9WgFb.js → collection-display-button-DpjzbbIn.js} +1 -1
- package/dist/client/assets/{collection-header-COgMCOx8.js → collection-header-B4-DpfAL.js} +1 -1
- package/dist/client/assets/{collection-page-DVakSZpa.js → collection-page-b5lRP5ne.js} +1 -1
- package/dist/client/assets/{collection-search-Fe3W5Myr.js → collection-search-DqVEDOqS.js} +1 -1
- package/dist/client/assets/{collection-tab-_C4vj95J.js → collection-tab-BQhJW6AS.js} +1 -1
- package/dist/client/assets/{collection-table-wrapper-VkF3O5dC.js → collection-table-wrapper-B8ubC3Sh.js} +1 -1
- package/dist/client/assets/{connection-card-Bq9AH0T5.js → connection-card-C7f1dOrX.js} +1 -1
- package/dist/client/assets/{connection-detail-CbrkwDLO.js → connection-detail-RVxHc67u.js} +1 -1
- package/dist/client/assets/{connections-unSJ25xy.js → connections-Bv_34Usi.js} +1 -1
- package/dist/client/assets/{constants-DqnLzZpL.js → constants-BEKdbCo6.js} +1 -1
- package/dist/client/assets/constants-C88aG7V1.js +1 -0
- package/dist/client/assets/{create-organization-dialog-DCA75BPi.js → create-organization-dialog-BW4DOW5y.js} +1 -1
- package/dist/client/assets/{dialog-CL6M-Xmi.js → dialog-DLbo5T8N.js} +1 -1
- package/dist/client/assets/{dropdown-menu-BMu3zBVo.js → dropdown-menu-CM0mCcd3.js} +1 -1
- package/dist/client/assets/{dynamic-plugin-layout-CKzehx9R.js → dynamic-plugin-layout-DQFkQzWH.js} +1 -1
- package/dist/client/assets/{empty-state-BHdJzPJs.js → empty-state-BrUv9lsZ.js} +1 -1
- package/dist/client/assets/{empty-state-B0xeJKH5.js → empty-state-DZFeepnb.js} +1 -1
- package/dist/client/assets/{env-vars-editor-CtvDpSON.js → env-vars-editor-BAOHiLu2.js} +1 -1
- package/dist/client/assets/{error-boundary-vgLVbtql.js → error-boundary-DaCO9OCg.js} +1 -1
- package/dist/client/assets/{extract-connection-data-w2VKbBVM.js → extract-connection-data-C1X2zeqi.js} +1 -1
- package/dist/client/assets/{file-browser-C_o-XRN_.js → file-browser-DW6TJdZX.js} +2 -2
- package/dist/client/assets/{form-DWBp_92q.js → form-D8bvI4tc.js} +1 -1
- package/dist/client/assets/{grid-view-D4uG2rz_.js → grid-view-BLOYnzFT.js} +1 -1
- package/dist/client/assets/{home-tcH3yRYZ.js → home-DlKoJ54P.js} +1 -1
- package/dist/client/assets/{index-CQ6L3uZi.js → index-By7Mca_U.js} +1 -1
- package/dist/client/assets/{index-DimTMp-G.js → index-Ck_HNGGd.js} +2 -2
- package/dist/client/assets/{index-CUpy3pKS.js → index-CtrgR5Sj.js} +1 -1
- package/dist/client/assets/{index-D4QmV-sc.js → index-DSyGEqnv.js} +1 -1
- package/dist/client/assets/{index-D1MpJYf1.js → index-Dpe1Ly1c.js} +1 -1
- package/dist/client/assets/{index-BfBspZNA.js → index-I1CjKwfa.js} +1 -1
- package/dist/client/assets/{infiniteQueryObserver-DeWE7Mv6.js → infiniteQueryObserver-yBeVIl9y.js} +1 -1
- package/dist/client/assets/{input-BzZt5UMQ.js → input-BD07TV73.js} +1 -1
- package/dist/client/assets/{layout-DqvUpliw.js → layout-CtPQmm1R.js} +1 -1
- package/dist/client/assets/{localstorage-keys-Pb1bSOSH.js → localstorage-keys-bIhPsHqu.js} +1 -1
- package/dist/client/assets/{login-Bw3mNwou.js → login-DsME5Q78.js} +1 -1
- package/dist/client/assets/{mcp-oauth-DVTAVhIy.js → mcp-oauth-nsjatGUX.js} +1 -1
- package/dist/client/assets/{mcp-server-card-BOsrfsoy.js → mcp-server-card-Bhmbue9c.js} +1 -1
- package/dist/client/assets/{mcp-server-detail-DL4a0l-I.js → mcp-server-detail-B4am-5Te.js} +2 -2
- package/dist/client/assets/{members-CaWwLwBY.js → members-BB0T9TqV.js} +1 -1
- package/dist/client/assets/{monaco-editor-C3l8YLnM.js → monaco-editor-CP1tDtbL.js} +1 -1
- package/dist/client/assets/{monitoring-BXzU__Q2.js → monitoring-PT-sW85P.js} +2 -2
- package/dist/client/assets/{oauth-callback-C29sykPI.js → oauth-callback-B-DW0xRP.js} +1 -1
- package/dist/client/assets/{page-D9f3s0Zn.js → page-Cc8e_HoP.js} +1 -1
- package/dist/client/assets/{page-DFTluz6T.js → page-rhO8Ndm_.js} +2 -2
- package/dist/client/assets/{pin-to-sidebar-button-a3_Q5PIg.js → pin-to-sidebar-button-C0LI8OyX.js} +1 -1
- package/dist/client/assets/{plugin-empty-state-gioOq0db.js → plugin-empty-state-Snmmscpf.js} +1 -1
- package/dist/client/assets/{plugin-header-OS_VhXuY.js → plugin-header-CQUxkpkP.js} +1 -1
- package/dist/client/assets/{plugins-6jaAX9OI.js → plugins-Z6bDUs1U.js} +1 -1
- package/dist/client/assets/{popover-DCXtR4UV.js → popover-C2dO17KJ.js} +1 -1
- package/dist/client/assets/{registry-utils-B1EtgBkU.js → registry-utils-BE0ZphJL.js} +1 -1
- package/dist/client/assets/{resizable-C5jfRumR.js → resizable-C65jXR9m.js} +1 -1
- package/dist/client/assets/{resource-tabs-BNBJ-3ue.js → resource-tabs-CMKv9MLy.js} +1 -1
- package/dist/client/assets/{select-DVxy4dZt.js → select-DjQ5i8qH.js} +1 -1
- package/dist/client/assets/{settings-DlMrUAFl.js → settings-B6WkV5Xi.js} +1 -1
- package/dist/client/assets/{shell-layout-C02QmtDM.js → shell-layout-BAq9UL-m.js} +1 -1
- package/dist/client/assets/{spinner-BK_gptNQ.js → spinner-D1jlVRw-.js} +1 -1
- package/dist/client/assets/{switch-BEUY1ZkG.js → switch-VxY_iYFv.js} +1 -1
- package/dist/client/assets/{textarea-Dok2BUMd.js → textarea-Ca9yvCmH.js} +1 -1
- package/dist/client/assets/{tool-set-selector-BPpD_gne.js → tool-set-selector-Gam2FuD6.js} +1 -1
- package/dist/client/assets/{tools-list-eucrhDw_.js → tools-list-NAnIcc4C.js} +1 -1
- package/dist/client/assets/{tooltip-BotDoy6T.js → tooltip-CXbR3les.js} +1 -1
- package/dist/client/assets/{typewriter-title-C0AyXxMG.js → typewriter-title-C-fZ8H0Y.js} +1 -1
- package/dist/client/assets/{use-binding-Dj1HVNst.js → use-binding-Bio_IG23.js} +1 -1
- package/dist/client/assets/{use-collections-Vpvt2q4e.js → use-collections-BtupqZP_.js} +1 -1
- package/dist/client/assets/{use-connection-DTjI_RtQ.js → use-connection-Dd7Yvjif.js} +1 -1
- package/dist/client/assets/{use-create-virtual-mcp-Jf2xsGTe.js → use-create-virtual-mcp-fvY3FmjO.js} +1 -1
- package/dist/client/assets/{use-list-state-Bzarl2oM.js → use-list-state-D5d2Dsd0.js} +1 -1
- package/dist/client/assets/{use-members-BtNqo2oh.js → use-members-fszl9icN.js} +1 -1
- package/dist/client/assets/{use-mobile-CcOC6HBd.js → use-mobile-jDYVRPrZ.js} +1 -1
- package/dist/client/assets/{use-organization-settings-CwiS3zFY.js → use-organization-settings-DjIJdwlh.js} +1 -1
- package/dist/client/assets/{use-virtual-mcp-hN6G5B_j.js → use-virtual-mcp-wPhrZ9RR.js} +1 -1
- package/dist/client/assets/useInfiniteQuery-BVNnXO_N.js +1 -0
- package/dist/client/assets/{useMutation-d4_WWA7-.js → useMutation-BucpIOAt.js} +1 -1
- package/dist/client/assets/useQuery-Zp-sAZMS.js +1 -0
- package/dist/client/assets/{value-BHid2kuo.js → value-E9Fqy7St.js} +1 -1
- package/dist/client/assets/{view-mode-toggle-DhWV5fbM.js → view-mode-toggle-CR_cIdX-.js} +1 -1
- package/dist/client/assets/{virtual-mcp-Dyh0Ag7o.js → virtual-mcp-CLFdFi_E.js} +1 -1
- package/dist/client/assets/{workflow-Bw7jESqY.js → workflow-DJOiUaHZ.js} +1 -1
- package/dist/client/index.html +1 -1
- package/dist/server/cli.js +2 -2
- package/dist/server/migrate.js +2 -2
- package/dist/server/server.js +2 -2
- package/package.json +1 -1
- package/dist/client/assets/constants-CrS7edVE.js +0 -1
- package/dist/client/assets/useInfiniteQuery-B-B7Ix7h.js +0 -1
- package/dist/client/assets/useQuery-BMYUlGUP.js +0 -1
package/dist/server/migrate.js
CHANGED
|
@@ -404,9 +404,9 @@ ${X.stack}`;return Y}if(typeof X==="object"&&X!==null){let Y=X,Q="";if(typeof Y.
|
|
|
404
404
|
${Y.stack}`;return Q}try{let G=JSON.stringify(Y,null,2);if(G!=="{}"&&G.length<1000){if(typeof Y.stack==="string"&&Y.stack&&Y.stack.length<2000)return`${G}
|
|
405
405
|
|
|
406
406
|
Stack trace:
|
|
407
|
-
${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 IU(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=IU(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=IU(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=IU(X,$);K.resolve(H),H.dispose(),X.runtime.executePendingJobs()}catch(H){let F=jU(H),V=X.newString(`Promise resolution error: ${F}`);K.reject(V),V.dispose(),X.runtime.executePendingJobs()}}).catch(($)=>{let H=jU($),F=X.newString(`Promise rejection: ${H}`);K.reject(F),F.dispose(),X.runtime.executePendingJobs()}),K.handle}return IU(X,W)}catch(Z){let W=jU(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 C94=()=>{};function S94(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 R94(X,Y,Q){let J=Date.now(),G=X.resolvePromise(Y);while(!0){S94(X);let Z=await Promise.race([G,aE6(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 U60({tools:X,code:Y,timeoutMs:Q}){let W=[];try{let J=await j94({memoryLimitBytes:33554432,stackSizeBytes:524288});const G=$_(W,J.newContext({interruptAfterMs:Q}),0);const Z=$_(W,e84(G),0);try{let F=G.evalCode(Y,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult(F),q=IU(G,X);G.setProp(G.global,"tools",q);let z=G.runtime.hasPendingJob()?G.unwrapResult(await R94(G,V,Q)):V;if(z!==V)V.dispose();let D=G.getProp(z,"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,q),w=G.unwrapResult(O),E=await R94(G,w,Q),C=G.unwrapResult(E);if(G.runtime.hasPendingJob())S94(G);return{returnValue:G.dump(C),consoleLogs:Z.logs}}catch(F){return console.log(F),{error:jU(F),consoleLogs:Z.logs}}}catch(K){var $=K,H=1}finally{V10(W,$,H)}}var aE6=(X)=>new Promise((Y)=>setTimeout(Y,X));var v94=g(()=>{I94();C94()});var k94=g(()=>{v94()});async function rE6(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 _94(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 oE6(X,Y,Q){let J=await ik.create(X,Q),G=await J.mapSettled(async(F,V)=>{try{let z=(await F.proxy.client.listTools()).tools;if(Y==="exclusion"){if(F.selectedTools&&F.selectedTools.length>0){let D=new Set(F.selectedTools);z=z.filter((N)=>!D.has(N.name))}}else if(F.selectedTools&&F.selectedTools.length>0){let D=new Set(F.selectedTools);z=z.filter((N)=>D.has(N.name))}return{connectionId:V,connectionTitle:F.connection.title,tools:z}}catch(q){return console.error(`[code-execution] Failed to list tools for connection ${V}:`,q),null}}),Z=new Set,W=[],K=new Map,$=new Set;for(let F of G){if(F.status!=="fulfilled"||!F.value)continue;let{connectionId:V,connectionTitle:q,tools:z}=F.value;$.add(q);for(let D of z){if(Z.has(D.name))continue;Z.add(D.name),W.push({...D,_meta:{connectionId:V,connectionTitle:q}}),K.set(D.name,{connectionId:V,originalName:D.name})}}return{tools:W,callTool:async(F,V)=>{let q=K.get(F);if(!q)return{content:[{type:"text",text:`Tool not found: ${F}`}],isError:!0};let z=J.get(q.connectionId);if(!z)return{content:[{type:"text",text:`Connection not found for tool: ${F}`}],isError:!0};return await z.proxy.client.callTool({name:q.originalName,arguments:V})},categories:Array.from($).sort()}}async function CU(X){let Y=j4(X),Q,J="inclusion";if(X.connectionId){let G=await X.storage.virtualMcps.findById(X.connectionId);if(G)Q=await rE6(G,X),J=G.tool_selection_mode;else Q=await _94(Y.id,X)}else Q=await _94(Y.id,X);return oE6(Q,J,X)}function sE6(X){return X.toLowerCase().split(/[\s_\-./]+/).filter((Y)=>Y.length>=2)}function tE6(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 y94(X,Y,Q){let J=sE6(X);if(J.length===0)return Y.slice(0,Q);return Y.map((G)=>({tool:G,score:tE6(J,G)})).filter((G)=>G.score>0).sort((G,Z)=>Z.score-G.score).slice(0,Q).map((G)=>G.tool)}function f94(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 b94(X,Y,Q){let J=Object.fromEntries(Y.tools.map((G)=>[G.name,async(Z)=>Y.callTool(G.name,Z??{})]));return U60({code:X,tools:J,timeoutMs:Q})}var sk=g(()=>{k94()});var z60;var h94=g(()=>{s4();Cw();sk();z60=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:i84,outputSchema:a84,handler:async(X,Y)=>{H4(Y),j4(Y),await Y.access.check();let Q=await CU(Y),J=y94(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 B60;var x94=g(()=>{s4();Cw();sk();B60=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:r84,outputSchema:o84,handler:async(X,Y)=>{H4(Y),j4(Y),await Y.access.check();let Q=await CU(Y);return f94(X.tools,Q.tools)}})});var D60;var g94=g(()=>{s4();Cw();sk();D60=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:s84,outputSchema:t84,handler:async(X,Y)=>{H4(Y),j4(Y),await Y.access.check();let Q=await CU(Y);return await b94(X.code,Q,X.timeoutMs)}})});var u94=g(()=>{h94();x94();g94();Cw()});var Xj6,Yj6,N60;var m94=g(()=>{V40();o0();s4();ck();ZK();Xj6=L.object({data:B14.describe("Data for the new connection (id is auto-generated if not provided)")}),Yj6=L.object({item:NJ.describe("The created connection entity")}),N60=r0({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",inputSchema:Xj6,outputSchema:Yj6,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);await Y.access.check();let J=E8(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 $=xk(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=gk($)}let Z=await TU({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,s3.SELF(Q.id),{type:"connection.created",data:K}),{item:K}}})});function Sw(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)=>Sw(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)&&Sw(X[G],Y[G]))}return!1}function Aj6(){return(X)=>{if(!Array.isArray(X))return!0;let Y=[];return X.every((Q)=>{if(Y.some((G)=>Sw(Q,G)))return!1;return Y.push(Q),!0})}}function tk(X,Y){return X.safeParse(Y).success}function XX(X){if(typeof X==="boolean")return X?L.any():L.never();let Y={};for(let G of xj6)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 gj6)J=G.apply(J,X);return J}var Qj6=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()}}},Jj6=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}},Gj6=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}},Wj6=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}}},Zj6=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()}}},Kj6=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`})}}},$j6=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`})}}},Hj6=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)}}}},Fj6=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)}}},Vj6=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)}}},qj6=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}}},Uj6=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}}},zj6=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}`})}}},Bj6=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())}}},Dj6=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)}},Nj6=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)}},Oj6=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=XX(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())}},Lj6=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)=>XX(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}},wj6=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()}},Mj6=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()}}},Pj6=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`})}}},Tj6=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`})}}},Ej6=class{apply(X,Y){if(!Y.not)return X;let Q=XX(Y.not);return X.refine((J)=>!tk(Q,J),{message:"Value must not match the 'not' schema"})}},jj6=class{apply(X,Y){if(Y.uniqueItems!==!0)return X;return X.refine(Aj6(),{message:"Array items must be unique"})}},Ij6=class{apply(X,Y){if(!Y.allOf||Y.allOf.length===0)return X;return Y.allOf.map((J)=>XX(J)).reduce((J,G)=>L.intersection(J,G),X)}},Cj6=class{apply(X,Y){if(!Y.anyOf||Y.anyOf.length===0)return X;let Q=Y.anyOf.length===1?XX(Y.anyOf[0]):L.union([XX(Y.anyOf[0]),XX(Y.anyOf[1]),...Y.anyOf.slice(2).map((J)=>XX(J))]);return L.intersection(X,Q)}},Rj6=class{apply(X,Y){if(!Y.oneOf||Y.oneOf.length===0)return X;let Q=Y.oneOf.map((J)=>XX(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"})}},Sj6=class{apply(X,Y){let Q=Y;if(Q.prefixItems&&Array.isArray(Q.prefixItems)){let G=Q.prefixItems.map((Z)=>XX(Z));return X.refine((Z)=>{if(!Array.isArray(Z))return!0;for(let W=0;W<Math.min(Z.length,G.length);W++)if(!tk(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=XX(Q.items);for(let K=G.length;K<Z.length;K++)if(!tk(W,Z[K]))return!1}}return!0},{message:"Array does not match prefixItems schema"})}return X}},vj6=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]=XX(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(!XX(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"})}},kj6=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)=>Sw(J,G))},{message:"Value must match one of the enum values"})}},_j6=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)=>Sw(J,Q),{message:"Value must equal the const value"})}},yj6=class{apply(X,Y){if(Y.description)X=X.describe(Y.description);return X}},fj6=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))}},bj6=class{apply(X,Y){var Q;let J=Y;if(J.contains===void 0)return X;let G=XX(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(tk(G,H))$++;if($<Z)return!1;if(W!==void 0&&$>W)return!1;return!0},{message:"Array must contain required items matching the schema"})}},hj6=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)}},xj6,gj6;var l94=g(()=>{O9();O9();O9();O9();O9();O9();O9();O9();O9();O9();O9();O9();O9();O9();xj6=[new Jj6,new Gj6,new Qj6,new Wj6,new Zj6,new Bj6,new Mj6,new Kj6,new $j6,new Hj6,new Fj6,new Vj6,new qj6,new Uj6,new zj6,new Lj6,new Dj6,new Nj6,new Oj6,new Pj6,new Tj6,new wj6],gj6=[new fj6,new kj6,new _j6,new Ij6,new Cj6,new Rj6,new Sj6,new vj6,new bj6,new Ej6,new jj6,new hj6,new yj6]});class O60{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,uj6),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=UQ.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 uj6="mcp";var d94=g(()=>{zQ()});function mj6(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 L60;var p94=g(()=>{yk();L60=class L60 extends qU{constructor(X,Y){super(X,Y)}send(X,Y){let Q=mj6(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 c94,n94=async(X,Y,Q)=>{let J=lj6(X.connection,Y,Q);if(!J)throw Error("Unknown MCP connection type");let G=new c94({name:X?.name??"MCP Client",version:"1.0.0"});return await G.connect(J),{client:G,callStreamableTool:(Z,W,K)=>{if(X.connection.type!=="HTTP")throw Error("HTTP connection required");let $=new Headers(Q);if(!$.has("Authorization"))$.set("Authorization",`Bearer ${X.connection.token}`);for(let[V,q]of Object.entries(X.connection.headers??{}))$.set(V,q);let H=new URL(X.connection.url),F=H.pathname.replace(/\/+$/,"")||"/";return H.pathname=`${F}/call-tool/${encodeURIComponent(Z)}`,fetch(H.href,{method:"POST",redirect:"manual",body:JSON.stringify(W),headers:$,signal:K})}}},lj6=(X,Y,Q)=>{if(X.type==="Websocket")return new O60(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 jw(new URL(X.url),Z)}return new L60(new URL(X.url),{requestInit:{headers:G,signal:Y,credentials:"include"}})};var i94=g(()=>{Lk();A40();d94();zQ();p94();c94=class c94 extends GK{constructor(X,Y){super(X,Y)}async listTools(X,Y){return await this.request({method:"tools/list",params:X},cL,Y)}}});function r94(X){let Y=(Q)=>{if("connection"in X)return n94({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){let F,V;if(typeof H==="object")F=J,V=H;else F??=J;let q=X?.debugId?.(),z=q?{"x-trace-debug-id":q}:void 0,{client:D,callStreamableTool:N}=await Y(z);if(X?.streamable?.[String(F)])return N(String(F),$,V?.signal??void 0);let{structuredContent:O,isError:w,content:E}=await D.callTool({name:String(F),arguments:$},void 0,{signal:V?.signal??void 0});if(w){let C=E?.[0]?.text,A=typeof C==="string"?dj6(C):null,T=A?.code&&typeof X?.getErrorByStatusCode==="function"?X.getErrorByStatusCode(A.code,A.message,A.traceId):null;if(T)throw T;throw Error(`Tool ${String(F)} returned an error: ${JSON.stringify(O??E)}`)}return O}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(!ek.has(H))ek.set(H,Z());return await ek.get(H)}catch(F){console.error("Failed to list tools",F),ek.delete(H);return}}async function K(){return(await W()??[]).map((H)=>a94(H,G))}return G.asTool=async()=>{let H=(await W()??[]).find((F)=>F.name===J);if(!H)throw Error(`Tool ${J} not found`);return a94(H,G)},G}})}var dj6=(X)=>{try{return JSON.parse(X)}catch{return X}},ek,a94=(X,Y)=>{return{...X,id:X.name,inputSchema:X.inputSchema?XX(X.inputSchema):void 0,outputSchema:X.outputSchema?XX(X.outputSchema):void 0,execute:(Q)=>{return Y(Q.context,X.name)}}};var o94=g(()=>{l94();i94();ek=new Map});function X_(X){return r94(X)}var kj1;var s94=g(()=>{o94();kj1=new Proxy({},{get(X,Y){if(Y==="toJSON")return null;if(Y==="forConnection")return(Q)=>X_({connection:Q});return global[Y]}})});function Y_(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 JH=(X)=>{return{...Y_(X),forClient:(Y)=>{return X_({client:Y,streamable:X.reduce((Q,J)=>{return Q[J.name]=J.streamable===!0,Q},{})})},forConnection:(Y)=>{return X_({connection:Y,streamable:X.reduce((Q,J)=>{return Q[J.name]=J.streamable===!0,Q},{})})}}};var vw=g(()=>{s94()});var w60,hj1;var t94=g(()=>{LL();w60=U1(OL(),1),hj1=w60.createContext(null)});function WH(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 _w(X){return L.object({item:X.nullable().describe("The retrieved item, or null if not found")})}function nj6(X){return L.object({data:X.partial().describe("Data for the new entity (id may be auto-generated)")})}function ij6(X){return L.object({item:X.describe("The created entity with generated id")})}function aj6(X){return L.object({id:L.string().describe("ID of the entity to update"),data:X.partial().describe("Partial entity data to update")})}function rj6(X){return L.object({item:X.describe("The updated entity")})}function fw(X){return L.object({item:X.describe("The deleted entity")})}function SU(X,Y,Q){let J=X.toUpperCase(),G=Q?.readOnly??!1,Z=[{name:`COLLECTION_${J}_LIST`,inputSchema:GH,outputSchema:WH(Y)},{name:`COLLECTION_${J}_GET`,inputSchema:kw,outputSchema:_w(Y)}];if(!G)Z.push({name:`COLLECTION_${J}_CREATE`,inputSchema:nj6(Y),outputSchema:ij6(Y),opt:!0},{name:`COLLECTION_${J}_UPDATE`,inputSchema:aj6(Y),outputSchema:rj6(Y),opt:!0},{name:`COLLECTION_${J}_DELETE`,inputSchema:yw,outputSchema:fw(Y),opt:!0});return Z}var RU,pj6,e94,cj6,GH,kw,yw;var F5=g(()=>{o0();RU=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()}),pj6=L.object({field:L.array(L.string()),operator:L.enum(["eq","gt","gte","lt","lte","in","like","contains"]),value:L.unknown()}),e94=L.lazy(()=>L.union([pj6,L.object({operator:L.enum(["and","or","not"]),conditions:L.array(e94)})])),cj6=L.object({field:L.array(L.string()),direction:L.enum(["asc","desc"]),nulls:L.enum(["first","last"]).optional()}),GH=L.object({where:e94.optional().describe("Filter expression"),orderBy:L.array(cj6).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")});kw=L.object({id:L.string().describe("ID of the entity to retrieve")});yw=L.object({id:L.string().describe("ID of the entity to delete")})});var oj6,XX4,pj1;var YX4=g(()=>{o0();F5();oj6=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()}),XX4=RU.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(oj6).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()})}),pj1=SU("registry_app",XX4,{readOnly:!0})});var QX4,JX4,GX4,WX4,ZX4,sj6;var KX4=g(()=>{o0();vw();QX4=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)")}),JX4=L.object({events:L.array(QX4).min(1).describe("Batch of CloudEvents to process")}),GX4=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")}),WX4=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(),GX4).optional().describe("Per-event results keyed by event ID")}),ZX4=[{name:"ON_EVENTS",inputSchema:JX4,outputSchema:WX4}],sj6=JH(ZX4)});var bw,hw,xw,gw,$X4,HX4,uw,mw,lw,dw,pw,cw,nw,iw,FX4,tj6;var VX4=g(()=>{o0();vw();bw=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.")}),hw=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")}),xw=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")}),gw=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)")})}),$X4=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")}),HX4=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)")}),uw=L.object({subscriptions:L.array($X4).describe("Desired subscriptions - system will create/update/delete to match")}),mw=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(HX4).describe("Current subscriptions after sync")}),lw=L.object({subscriptionId:L.string().describe("Subscription ID to remove")}),dw=L.object({success:L.boolean().describe("Whether unsubscribe was successful"),subscriptionId:L.string().describe("Subscription ID that was removed")}),pw=L.object({eventId:L.string().describe("Event ID to cancel")}),cw=L.object({success:L.boolean().describe("Whether cancellation was successful"),eventId:L.string().describe("Event ID that was cancelled")}),nw=L.object({eventId:L.string().describe("Event ID to acknowledge")}),iw=L.object({success:L.boolean().describe("Whether ACK was successful"),eventId:L.string().describe("Event ID that was acknowledged")}),FX4=[{name:"EVENT_PUBLISH",inputSchema:bw,outputSchema:hw},{name:"EVENT_SUBSCRIBE",inputSchema:xw,outputSchema:gw},{name:"EVENT_UNSUBSCRIBE",inputSchema:lw,outputSchema:dw},{name:"EVENT_CANCEL",inputSchema:pw,outputSchema:cw},{name:"EVENT_ACK",inputSchema:nw,outputSchema:iw},{name:"EVENT_SYNC_SUBSCRIPTIONS",inputSchema:uw,outputSchema:mw}],tj6=JH(FX4)});var ej1,XI1,YI1,QI1,JI1,GI1,WI1,ZI1,KI1,$I1,HI1,FI1;var qX4=g(()=>{o0();ej1=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.")}),XI1=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/'])")}),YI1=L.object({key:L.string().describe("Object key/path to get metadata for")}),QI1=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")}),JI1=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)")}),GI1=L.object({url:L.string().describe("Presigned URL for downloading the object"),expiresIn:L.number().describe("Expiration time in seconds that was used")}),WI1=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")}),ZI1=L.object({url:L.string().describe("Presigned URL for uploading the object"),expiresIn:L.number().describe("Expiration time in seconds that was used")}),KI1=L.object({key:L.string().describe("Object key/path to delete")}),$I1=L.object({success:L.boolean().describe("Whether the deletion was successful"),key:L.string().describe("The key that was deleted")}),HI1=L.object({keys:L.array(L.string()).max(1000).describe("Array of object keys/paths to delete (max 1000)")}),FI1=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 M60=g(()=>{vw();t94();YX4();KX4();VX4();qX4()});var ej6,XI6,UX4;var zX4=g(()=>{o0();F5();ej6=RU.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")}),XI6=SU("assistant",ej6),UX4=[...XI6]});var aw,JW,DX4,YI6,QI6,NX4,JI6,GI6,WI6,ZI6,KI6,$I6,OX4,HI6,FI6,VI6,qI6,UI6,zI6,BI6,DI6,NI6,OI6,SI1,LI6,vI1,BX4,wI6,MI6,P60,kI1;var LX4=g(()=>{o0();vw();F5();aw=L.lazy(()=>L.union([L.null(),L.string(),L.number(),L.boolean(),L.record(L.string(),aw),L.array(aw)])),JW=L.record(L.string(),L.record(L.string(),aw)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),DX4=L.object({type:L.literal("text"),text:L.string().describe("The text content"),providerOptions:JW}),YI6=L.object({type:L.literal("text"),text:L.string().describe("The text content"),providerMetadata:L.any().optional().describe("Additional provider-specific metadata")}),QI6=L.string().describe("File data as URL string"),NX4=L.object({type:L.literal("file"),filename:L.string().optional().describe("Optional filename of the file"),data:QI6,mediaType:L.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:JW}),JI6=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")}),GI6=L.object({type:L.literal("reasoning"),text:L.string().describe("The reasoning text"),providerOptions:JW}),WI6=L.object({type:L.literal("reasoning"),text:L.string().describe("The reasoning text"),providerMetadata:L.any().optional().describe("Additional provider-specific metadata")}),ZI6=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:JW}),KI6=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")}),$I6=L.union([L.object({type:L.literal("text"),value:L.string()}),L.object({type:L.literal("json"),value:aw}),L.object({type:L.literal("error-text"),value:L.string()}),L.object({type:L.literal("error-json"),value:aw}),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")})]))})]),OX4=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:$I6.describe("Result of the tool call"),result:L.unknown().describe("Unknown result of the tool call"),providerOptions:JW}),HI6=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")}),FI6=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")})]),VI6=L.object({role:L.literal("system"),content:L.string().describe("System message content"),providerOptions:JW}),qI6=L.object({role:L.literal("user"),content:L.array(L.union([DX4,NX4])).describe("User message content parts (text or file)"),providerOptions:JW}),UI6=L.object({role:L.literal("assistant"),content:L.array(L.union([DX4,NX4,GI6,ZI6,OX4])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:JW}),zI6=L.object({role:L.literal("tool"),content:L.array(OX4).describe("Tool message content (tool results)"),providerOptions:JW}),BI6=L.union([VI6,qI6,UI6,zI6]),DI6=L.array(BI6).describe("A list of messages forming the prompt"),NI6=L.object({prompt:DI6.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")}),OI6=L.object({content:L.array(L.union([YI6,JI6,WI6,KI6,HI6,FI6])).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")}),SI1=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")}),LI6=L.object({supportedUrls:L.record(L.string(),L.array(L.string())).describe("Supported URL patterns by media type for the provider")}),vI1=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()}),BX4=L.object({modelId:L.string().describe("The ID of the model"),callOptions:NI6}),wI6=RU.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()}),MI6=SU("llm",wI6,{readOnly:!0}),P60=[{name:"LLM_METADATA",inputSchema:L.object({modelId:L.string().describe("The ID of the model")}),outputSchema:LI6},{name:"LLM_DO_STREAM",inputSchema:BX4,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:BX4,outputSchema:OI6},...MI6],kI1=JH(P60)});function TI6(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 FK(X){return typeof X==="string"||typeof X==="number"}function Q_(X,Y){if("conditions"in Y){let{operator:K,conditions:$}=Y;switch(K){case"and":return $.every((H)=>Q_(X,H));case"or":return $.some((H)=>Q_(X,H));case"not":return!$.every((H)=>Q_(X,H));default:return!0}}let{field:Q,operator:J,value:G}=Y,Z=Q.join("."),W=T60(X,Z);switch(J){case"eq":return W===G;case"gt":return FK(W)&&FK(G)&&W>G;case"gte":return FK(W)&&FK(G)&&W>=G;case"lt":return FK(W)&&FK(G)&&W<G;case"lte":return FK(W)&&FK(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=TI6(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 T60(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 AI6(X,Y){return[...X].sort((Q,J)=>{for(let G of Y){let Z=G.field.join("."),W=T60(Q,Z),K=T60(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 PI6,EI6,jI6,A60;var wX4=g(()=>{M60();zX4();F5();LX4();o0();s4();ZK();PI6={LLM:P60,ASSISTANTS:UX4};EI6=GH.extend({binding:L.union([L.object({}).passthrough(),L.string()]).optional()}),jI6=WH(NJ),A60=r0({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",inputSchema:EI6,outputSchema:jI6,handler:async(X,Y)=>{await Y.access.check();let Q=j4(Y),J=X.binding?typeof X.binding==="string"?(()=>{let z=PI6[X.binding.toUpperCase()];if(!z)throw Error(`Unknown binding: ${X.binding}`);return z})():X.binding:void 0,G=J?Y_(J):void 0,W=(await Y.storage.connections.list(Q.id)).filter((z)=>z.connection_type!=="VIRTUAL"),K=G?await Promise.all(W.map(async(z)=>{if(!z.tools||z.tools.length===0)return null;return G.isImplementedBy(z.tools.map((N)=>({name:N.name,inputSchema:N.inputSchema,outputSchema:N.outputSchema})))?z:null})).then((z)=>z.filter((D)=>D!==null)):W;if(X.where)K=K.filter((z)=>Q_(z,X.where));if(X.orderBy&&X.orderBy.length>0)K=AI6(K,X.orderBy);let $=K.length,H=X.offset??0,F=X.limit??100,V=K.slice(H,H+F),q=H+F<$;return{items:V,totalCount:$,hasMore:q}}})});var II6,E60;var MX4=g(()=>{F5();s4();ZK();II6=_w(NJ),E60=r0({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",inputSchema:kw,outputSchema:II6,handler:async(X,Y)=>{let Q=j4(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 J_=(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 PX4(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 CI6(X){let Y=X.split("::");if(Y.length!==2||!Y[0]||!Y[1])return null;return Y}function RI6(X){if(typeof X==="object"&&X!==null&&"value"in X){let Y=X.value;if(typeof Y==="string")return Y}return null}function SI6(X,Y){let Q={};if(!X||!Y)return Q;for(let J of Y){if(J==="*"){Q["*"]=["*"];continue}let G=CI6(J);if(!G)continue;let[Z,W]=G,K=J_(Z,X),$=RI6(K);if($){if(!Q[$])Q[$]=[];Q[$].push(W)}}return Q}function TX4(X,Y){let Q=SI6(X,Y);return new Set(Object.keys(Q).filter((J)=>J!=="*"))}var AX4=()=>{};class j60{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=zU("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 EX4=g(()=>{uk()});async function _I6(X,Y,Q,J){for(let Z of Y){if(Z==="*")continue;let[W]=PX4(Z),K=J_(W,X);if(K===void 0||K===null)throw Error(`Scope references key "${W}" but it's not present in state`)}let G=TX4(X,Y);for(let Z of G){if(Z.endsWith("_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 vI6,kI6,I60;var jX4=g(()=>{AX4();EX4();o0();s4();ck();ZK();vI6=L.object({id:L.string().describe("ID of the connection to update"),data:D14.describe("Partial connection data to update")}),kI6=L.object({item:NJ.describe("The updated connection entity")});I60=r0({name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update an existing MCP connection in the organization",inputSchema:vI6,outputSchema:kI6,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);if(await Y.access.check(),!E8(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=xk($);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");$=gk(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 _I6(H,F,Q.id,Y)}let V=Z.connection_token??W.connection_token;if(!V)try{let w=await new j60(Y.db,Y.vault).get(G);if(w?.accessToken)V=w.accessToken}catch{}let q=await TU({id:W.id,title:Z.title??W.title,connection_type:K,connection_url:$,connection_token:V,connection_headers:Z.connection_headers??W.connection_headers}).catch(()=>null),z=q?.length?q:null,D={...Z,connection_url:$,tools:z,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 C60;var IX4=g(()=>{F5();s4();ZK();C60=r0({name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete a connection",inputSchema:yw,outputSchema:fw(NJ),handler:async(X,Y)=>{H4(Y);let Q=j4(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 R60;var CX4=g(()=>{o0();s4();R60=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=j4(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 RX4=g(()=>{m94();wX4();MX4();jX4();IX4();CX4()});import{sql as p6}from"kysely";function SX4(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 bI6(X,Y){let Q=X;for(let G=Y.length;G>=1;G--){let Z=`$${G}`;if(Q.includes(Z))Q=Q.replaceAll(Z,SX4(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=SX4(Y[G]);Q=Q.slice(0,Z)+W+Q.slice(Z+1)}return Q}function vX4(X){return X.replace(/-/g,"_")}function xI6(X){return`app_${vX4(X)}`}function gI6(X){return`app_role_${vX4(X)}`}function uI6(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 mI6(X,Y,Q){if(await p6`CREATE SCHEMA IF NOT EXISTS ${p6.id(Y)}`.execute(X),!(await p6`
|
|
407
|
+
${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 IU(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=IU(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=IU(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=IU(X,$);K.resolve(H),H.dispose(),X.runtime.executePendingJobs()}catch(H){let F=jU(H),V=X.newString(`Promise resolution error: ${F}`);K.reject(V),V.dispose(),X.runtime.executePendingJobs()}}).catch(($)=>{let H=jU($),F=X.newString(`Promise rejection: ${H}`);K.reject(F),F.dispose(),X.runtime.executePendingJobs()}),K.handle}return IU(X,W)}catch(Z){let W=jU(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 C94=()=>{};function S94(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 R94(X,Y,Q){let J=Date.now(),G=X.resolvePromise(Y);while(!0){S94(X);let Z=await Promise.race([G,aE6(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 U60({tools:X,code:Y,timeoutMs:Q}){let W=[];try{let J=await j94({memoryLimitBytes:33554432,stackSizeBytes:524288});const G=$_(W,J.newContext({interruptAfterMs:Q}),0);const Z=$_(W,e84(G),0);try{let F=G.evalCode(Y,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult(F),q=IU(G,X);G.setProp(G.global,"tools",q);let z=G.runtime.hasPendingJob()?G.unwrapResult(await R94(G,V,Q)):V;if(z!==V)V.dispose();let D=G.getProp(z,"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,q),w=G.unwrapResult(O),E=await R94(G,w,Q),C=G.unwrapResult(E);if(G.runtime.hasPendingJob())S94(G);return{returnValue:G.dump(C),consoleLogs:Z.logs}}catch(F){return console.log(F),{error:jU(F),consoleLogs:Z.logs}}}catch(K){var $=K,H=1}finally{V10(W,$,H)}}var aE6=(X)=>new Promise((Y)=>setTimeout(Y,X));var v94=g(()=>{I94();C94()});var k94=g(()=>{v94()});async function rE6(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 _94(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 oE6(X,Y,Q){let J=await ik.create(X,Q),G=await J.mapSettled(async(F,V)=>{try{let z=(await F.proxy.client.listTools()).tools;if(Y==="exclusion"){if(F.selectedTools&&F.selectedTools.length>0){let D=new Set(F.selectedTools);z=z.filter((N)=>!D.has(N.name))}}else if(F.selectedTools&&F.selectedTools.length>0){let D=new Set(F.selectedTools);z=z.filter((N)=>D.has(N.name))}return{connectionId:V,connectionTitle:F.connection.title,tools:z}}catch(q){return console.error(`[code-execution] Failed to list tools for connection ${V}:`,q),null}}),Z=new Set,W=[],K=new Map,$=new Set;for(let F of G){if(F.status!=="fulfilled"||!F.value)continue;let{connectionId:V,connectionTitle:q,tools:z}=F.value;$.add(q);for(let D of z){if(Z.has(D.name))continue;Z.add(D.name),W.push({...D,_meta:{connectionId:V,connectionTitle:q}}),K.set(D.name,{connectionId:V,originalName:D.name})}}return{tools:W,callTool:async(F,V)=>{let q=K.get(F);if(!q)return{content:[{type:"text",text:`Tool not found: ${F}`}],isError:!0};let z=J.get(q.connectionId);if(!z)return{content:[{type:"text",text:`Connection not found for tool: ${F}`}],isError:!0};return await z.proxy.client.callTool({name:q.originalName,arguments:V})},categories:Array.from($).sort()}}async function CU(X){let Y=j4(X),Q,J="inclusion";if(X.connectionId){let G=await X.storage.virtualMcps.findById(X.connectionId);if(G)Q=await rE6(G,X),J=G.tool_selection_mode;else Q=await _94(Y.id,X)}else Q=await _94(Y.id,X);return oE6(Q,J,X)}function sE6(X){return X.toLowerCase().split(/[\s_\-./]+/).filter((Y)=>Y.length>=2)}function tE6(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 y94(X,Y,Q){let J=sE6(X);if(J.length===0)return Y.slice(0,Q);return Y.map((G)=>({tool:G,score:tE6(J,G)})).filter((G)=>G.score>0).sort((G,Z)=>Z.score-G.score).slice(0,Q).map((G)=>G.tool)}function f94(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 b94(X,Y,Q){let J=Object.fromEntries(Y.tools.map((G)=>[G.name,async(Z)=>Y.callTool(G.name,Z??{})]));return U60({code:X,tools:J,timeoutMs:Q})}var sk=g(()=>{k94()});var z60;var h94=g(()=>{s4();Cw();sk();z60=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:i84,outputSchema:a84,handler:async(X,Y)=>{H4(Y),j4(Y),await Y.access.check();let Q=await CU(Y),J=y94(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 B60;var x94=g(()=>{s4();Cw();sk();B60=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:r84,outputSchema:o84,handler:async(X,Y)=>{H4(Y),j4(Y),await Y.access.check();let Q=await CU(Y);return f94(X.tools,Q.tools)}})});var D60;var g94=g(()=>{s4();Cw();sk();D60=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:s84,outputSchema:t84,handler:async(X,Y)=>{H4(Y),j4(Y),await Y.access.check();let Q=await CU(Y);return await b94(X.code,Q,X.timeoutMs)}})});var u94=g(()=>{h94();x94();g94();Cw()});var Xj6,Yj6,N60;var m94=g(()=>{V40();o0();s4();ck();ZK();Xj6=L.object({data:B14.describe("Data for the new connection (id is auto-generated if not provided)")}),Yj6=L.object({item:NJ.describe("The created connection entity")}),N60=r0({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",inputSchema:Xj6,outputSchema:Yj6,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);await Y.access.check();let J=E8(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 $=xk(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=gk($)}let Z=await TU({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,s3.SELF(Q.id),{type:"connection.created",data:K}),{item:K}}})});function Sw(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)=>Sw(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)&&Sw(X[G],Y[G]))}return!1}function Aj6(){return(X)=>{if(!Array.isArray(X))return!0;let Y=[];return X.every((Q)=>{if(Y.some((G)=>Sw(Q,G)))return!1;return Y.push(Q),!0})}}function tk(X,Y){return X.safeParse(Y).success}function XX(X){if(typeof X==="boolean")return X?L.any():L.never();let Y={};for(let G of xj6)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 gj6)J=G.apply(J,X);return J}var Qj6=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()}}},Jj6=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}},Gj6=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}},Wj6=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}}},Zj6=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()}}},Kj6=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`})}}},$j6=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`})}}},Hj6=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)}}}},Fj6=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)}}},Vj6=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)}}},qj6=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}}},Uj6=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}}},zj6=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}`})}}},Bj6=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())}}},Dj6=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)}},Nj6=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)}},Oj6=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=XX(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())}},Lj6=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)=>XX(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}},wj6=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()}},Mj6=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()}}},Pj6=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`})}}},Tj6=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`})}}},Ej6=class{apply(X,Y){if(!Y.not)return X;let Q=XX(Y.not);return X.refine((J)=>!tk(Q,J),{message:"Value must not match the 'not' schema"})}},jj6=class{apply(X,Y){if(Y.uniqueItems!==!0)return X;return X.refine(Aj6(),{message:"Array items must be unique"})}},Ij6=class{apply(X,Y){if(!Y.allOf||Y.allOf.length===0)return X;return Y.allOf.map((J)=>XX(J)).reduce((J,G)=>L.intersection(J,G),X)}},Cj6=class{apply(X,Y){if(!Y.anyOf||Y.anyOf.length===0)return X;let Q=Y.anyOf.length===1?XX(Y.anyOf[0]):L.union([XX(Y.anyOf[0]),XX(Y.anyOf[1]),...Y.anyOf.slice(2).map((J)=>XX(J))]);return L.intersection(X,Q)}},Rj6=class{apply(X,Y){if(!Y.oneOf||Y.oneOf.length===0)return X;let Q=Y.oneOf.map((J)=>XX(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"})}},Sj6=class{apply(X,Y){let Q=Y;if(Q.prefixItems&&Array.isArray(Q.prefixItems)){let G=Q.prefixItems.map((Z)=>XX(Z));return X.refine((Z)=>{if(!Array.isArray(Z))return!0;for(let W=0;W<Math.min(Z.length,G.length);W++)if(!tk(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=XX(Q.items);for(let K=G.length;K<Z.length;K++)if(!tk(W,Z[K]))return!1}}return!0},{message:"Array does not match prefixItems schema"})}return X}},vj6=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]=XX(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(!XX(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"})}},kj6=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)=>Sw(J,G))},{message:"Value must match one of the enum values"})}},_j6=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)=>Sw(J,Q),{message:"Value must equal the const value"})}},yj6=class{apply(X,Y){if(Y.description)X=X.describe(Y.description);return X}},fj6=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))}},bj6=class{apply(X,Y){var Q;let J=Y;if(J.contains===void 0)return X;let G=XX(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(tk(G,H))$++;if($<Z)return!1;if(W!==void 0&&$>W)return!1;return!0},{message:"Array must contain required items matching the schema"})}},hj6=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)}},xj6,gj6;var l94=g(()=>{O9();O9();O9();O9();O9();O9();O9();O9();O9();O9();O9();O9();O9();O9();xj6=[new Jj6,new Gj6,new Qj6,new Wj6,new Zj6,new Bj6,new Mj6,new Kj6,new $j6,new Hj6,new Fj6,new Vj6,new qj6,new Uj6,new zj6,new Lj6,new Dj6,new Nj6,new Oj6,new Pj6,new Tj6,new wj6],gj6=[new fj6,new kj6,new _j6,new Ij6,new Cj6,new Rj6,new Sj6,new vj6,new bj6,new Ej6,new jj6,new hj6,new yj6]});class O60{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,uj6),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=UQ.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 uj6="mcp";var d94=g(()=>{zQ()});function mj6(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 L60;var p94=g(()=>{yk();L60=class L60 extends qU{constructor(X,Y){super(X,Y)}send(X,Y){let Q=mj6(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 c94,n94=async(X,Y,Q)=>{let J=lj6(X.connection,Y,Q);if(!J)throw Error("Unknown MCP connection type");let G=new c94({name:X?.name??"MCP Client",version:"1.0.0"});return await G.connect(J),{client:G,callStreamableTool:(Z,W,K)=>{if(X.connection.type!=="HTTP")throw Error("HTTP connection required");let $=new Headers(Q);if(!$.has("Authorization"))$.set("Authorization",`Bearer ${X.connection.token}`);for(let[V,q]of Object.entries(X.connection.headers??{}))$.set(V,q);let H=new URL(X.connection.url),F=H.pathname.replace(/\/+$/,"")||"/";return H.pathname=`${F}/call-tool/${encodeURIComponent(Z)}`,fetch(H.href,{method:"POST",redirect:"manual",body:JSON.stringify(W),headers:$,signal:K})}}},lj6=(X,Y,Q)=>{if(X.type==="Websocket")return new O60(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 jw(new URL(X.url),Z)}return new L60(new URL(X.url),{requestInit:{headers:G,signal:Y,credentials:"include"}})};var i94=g(()=>{Lk();A40();d94();zQ();p94();c94=class c94 extends GK{constructor(X,Y){super(X,Y)}async listTools(X,Y){return await this.request({method:"tools/list",params:X},cL,Y)}}});function r94(X){let Y=(Q)=>{if("connection"in X)return n94({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?.(),V=F?{"x-trace-debug-id":F}:void 0,{client:q,callStreamableTool:z}=await Y(V);if(X?.streamable?.[String(H)])return z(String(H),$);let{structuredContent:D,isError:N,content:O}=await q.callTool({name:String(H),arguments:$});if(N){let w=O?.[0]?.text,E=typeof w==="string"?dj6(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(!ek.has(H))ek.set(H,Z());return await ek.get(H)}catch(F){console.error("Failed to list tools",F),ek.delete(H);return}}async function K(){return(await W()??[]).map((H)=>a94(H,G))}return G.asTool=async()=>{let H=(await W()??[]).find((F)=>F.name===J);if(!H)throw Error(`Tool ${J} not found`);return a94(H,G)},G}})}var dj6=(X)=>{try{return JSON.parse(X)}catch{return X}},ek,a94=(X,Y)=>{return{...X,id:X.name,inputSchema:X.inputSchema?XX(X.inputSchema):void 0,outputSchema:X.outputSchema?XX(X.outputSchema):void 0,execute:(Q)=>{return Y(Q.context,X.name)}}};var o94=g(()=>{l94();i94();ek=new Map});function X_(X){return r94(X)}var kj1;var s94=g(()=>{o94();kj1=new Proxy({},{get(X,Y){if(Y==="toJSON")return null;if(Y==="forConnection")return(Q)=>X_({connection:Q});return global[Y]}})});function Y_(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 JH=(X)=>{return{...Y_(X),forClient:(Y)=>{return X_({client:Y,streamable:X.reduce((Q,J)=>{return Q[J.name]=J.streamable===!0,Q},{})})},forConnection:(Y)=>{return X_({connection:Y,streamable:X.reduce((Q,J)=>{return Q[J.name]=J.streamable===!0,Q},{})})}}};var vw=g(()=>{s94()});var w60,hj1;var t94=g(()=>{LL();w60=U1(OL(),1),hj1=w60.createContext(null)});function WH(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 _w(X){return L.object({item:X.nullable().describe("The retrieved item, or null if not found")})}function nj6(X){return L.object({data:X.partial().describe("Data for the new entity (id may be auto-generated)")})}function ij6(X){return L.object({item:X.describe("The created entity with generated id")})}function aj6(X){return L.object({id:L.string().describe("ID of the entity to update"),data:X.partial().describe("Partial entity data to update")})}function rj6(X){return L.object({item:X.describe("The updated entity")})}function fw(X){return L.object({item:X.describe("The deleted entity")})}function SU(X,Y,Q){let J=X.toUpperCase(),G=Q?.readOnly??!1,Z=[{name:`COLLECTION_${J}_LIST`,inputSchema:GH,outputSchema:WH(Y)},{name:`COLLECTION_${J}_GET`,inputSchema:kw,outputSchema:_w(Y)}];if(!G)Z.push({name:`COLLECTION_${J}_CREATE`,inputSchema:nj6(Y),outputSchema:ij6(Y),opt:!0},{name:`COLLECTION_${J}_UPDATE`,inputSchema:aj6(Y),outputSchema:rj6(Y),opt:!0},{name:`COLLECTION_${J}_DELETE`,inputSchema:yw,outputSchema:fw(Y),opt:!0});return Z}var RU,pj6,e94,cj6,GH,kw,yw;var F5=g(()=>{o0();RU=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()}),pj6=L.object({field:L.array(L.string()),operator:L.enum(["eq","gt","gte","lt","lte","in","like","contains"]),value:L.unknown()}),e94=L.lazy(()=>L.union([pj6,L.object({operator:L.enum(["and","or","not"]),conditions:L.array(e94)})])),cj6=L.object({field:L.array(L.string()),direction:L.enum(["asc","desc"]),nulls:L.enum(["first","last"]).optional()}),GH=L.object({where:e94.optional().describe("Filter expression"),orderBy:L.array(cj6).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")});kw=L.object({id:L.string().describe("ID of the entity to retrieve")});yw=L.object({id:L.string().describe("ID of the entity to delete")})});var oj6,XX4,pj1;var YX4=g(()=>{o0();F5();oj6=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()}),XX4=RU.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(oj6).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()})}),pj1=SU("registry_app",XX4,{readOnly:!0})});var QX4,JX4,GX4,WX4,ZX4,sj6;var KX4=g(()=>{o0();vw();QX4=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)")}),JX4=L.object({events:L.array(QX4).min(1).describe("Batch of CloudEvents to process")}),GX4=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")}),WX4=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(),GX4).optional().describe("Per-event results keyed by event ID")}),ZX4=[{name:"ON_EVENTS",inputSchema:JX4,outputSchema:WX4}],sj6=JH(ZX4)});var bw,hw,xw,gw,$X4,HX4,uw,mw,lw,dw,pw,cw,nw,iw,FX4,tj6;var VX4=g(()=>{o0();vw();bw=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.")}),hw=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")}),xw=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")}),gw=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)")})}),$X4=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")}),HX4=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)")}),uw=L.object({subscriptions:L.array($X4).describe("Desired subscriptions - system will create/update/delete to match")}),mw=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(HX4).describe("Current subscriptions after sync")}),lw=L.object({subscriptionId:L.string().describe("Subscription ID to remove")}),dw=L.object({success:L.boolean().describe("Whether unsubscribe was successful"),subscriptionId:L.string().describe("Subscription ID that was removed")}),pw=L.object({eventId:L.string().describe("Event ID to cancel")}),cw=L.object({success:L.boolean().describe("Whether cancellation was successful"),eventId:L.string().describe("Event ID that was cancelled")}),nw=L.object({eventId:L.string().describe("Event ID to acknowledge")}),iw=L.object({success:L.boolean().describe("Whether ACK was successful"),eventId:L.string().describe("Event ID that was acknowledged")}),FX4=[{name:"EVENT_PUBLISH",inputSchema:bw,outputSchema:hw},{name:"EVENT_SUBSCRIBE",inputSchema:xw,outputSchema:gw},{name:"EVENT_UNSUBSCRIBE",inputSchema:lw,outputSchema:dw},{name:"EVENT_CANCEL",inputSchema:pw,outputSchema:cw},{name:"EVENT_ACK",inputSchema:nw,outputSchema:iw},{name:"EVENT_SYNC_SUBSCRIPTIONS",inputSchema:uw,outputSchema:mw}],tj6=JH(FX4)});var ej1,XI1,YI1,QI1,JI1,GI1,WI1,ZI1,KI1,$I1,HI1,FI1;var qX4=g(()=>{o0();ej1=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.")}),XI1=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/'])")}),YI1=L.object({key:L.string().describe("Object key/path to get metadata for")}),QI1=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")}),JI1=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)")}),GI1=L.object({url:L.string().describe("Presigned URL for downloading the object"),expiresIn:L.number().describe("Expiration time in seconds that was used")}),WI1=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")}),ZI1=L.object({url:L.string().describe("Presigned URL for uploading the object"),expiresIn:L.number().describe("Expiration time in seconds that was used")}),KI1=L.object({key:L.string().describe("Object key/path to delete")}),$I1=L.object({success:L.boolean().describe("Whether the deletion was successful"),key:L.string().describe("The key that was deleted")}),HI1=L.object({keys:L.array(L.string()).max(1000).describe("Array of object keys/paths to delete (max 1000)")}),FI1=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 M60=g(()=>{vw();t94();YX4();KX4();VX4();qX4()});var ej6,XI6,UX4;var zX4=g(()=>{o0();F5();ej6=RU.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")}),XI6=SU("assistant",ej6),UX4=[...XI6]});var aw,JW,DX4,YI6,QI6,NX4,JI6,GI6,WI6,ZI6,KI6,$I6,OX4,HI6,FI6,VI6,qI6,UI6,zI6,BI6,DI6,NI6,OI6,SI1,LI6,vI1,BX4,wI6,MI6,P60,kI1;var LX4=g(()=>{o0();vw();F5();aw=L.lazy(()=>L.union([L.null(),L.string(),L.number(),L.boolean(),L.record(L.string(),aw),L.array(aw)])),JW=L.record(L.string(),L.record(L.string(),aw)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),DX4=L.object({type:L.literal("text"),text:L.string().describe("The text content"),providerOptions:JW}),YI6=L.object({type:L.literal("text"),text:L.string().describe("The text content"),providerMetadata:L.any().optional().describe("Additional provider-specific metadata")}),QI6=L.string().describe("File data as URL string"),NX4=L.object({type:L.literal("file"),filename:L.string().optional().describe("Optional filename of the file"),data:QI6,mediaType:L.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:JW}),JI6=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")}),GI6=L.object({type:L.literal("reasoning"),text:L.string().describe("The reasoning text"),providerOptions:JW}),WI6=L.object({type:L.literal("reasoning"),text:L.string().describe("The reasoning text"),providerMetadata:L.any().optional().describe("Additional provider-specific metadata")}),ZI6=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:JW}),KI6=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")}),$I6=L.union([L.object({type:L.literal("text"),value:L.string()}),L.object({type:L.literal("json"),value:aw}),L.object({type:L.literal("error-text"),value:L.string()}),L.object({type:L.literal("error-json"),value:aw}),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")})]))})]),OX4=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:$I6.describe("Result of the tool call"),result:L.unknown().describe("Unknown result of the tool call"),providerOptions:JW}),HI6=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")}),FI6=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")})]),VI6=L.object({role:L.literal("system"),content:L.string().describe("System message content"),providerOptions:JW}),qI6=L.object({role:L.literal("user"),content:L.array(L.union([DX4,NX4])).describe("User message content parts (text or file)"),providerOptions:JW}),UI6=L.object({role:L.literal("assistant"),content:L.array(L.union([DX4,NX4,GI6,ZI6,OX4])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:JW}),zI6=L.object({role:L.literal("tool"),content:L.array(OX4).describe("Tool message content (tool results)"),providerOptions:JW}),BI6=L.union([VI6,qI6,UI6,zI6]),DI6=L.array(BI6).describe("A list of messages forming the prompt"),NI6=L.object({prompt:DI6.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")}),OI6=L.object({content:L.array(L.union([YI6,JI6,WI6,KI6,HI6,FI6])).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")}),SI1=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")}),LI6=L.object({supportedUrls:L.record(L.string(),L.array(L.string())).describe("Supported URL patterns by media type for the provider")}),vI1=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()}),BX4=L.object({modelId:L.string().describe("The ID of the model"),callOptions:NI6}),wI6=RU.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()}),MI6=SU("llm",wI6,{readOnly:!0}),P60=[{name:"LLM_METADATA",inputSchema:L.object({modelId:L.string().describe("The ID of the model")}),outputSchema:LI6},{name:"LLM_DO_STREAM",inputSchema:BX4,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:BX4,outputSchema:OI6},...MI6],kI1=JH(P60)});function TI6(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 FK(X){return typeof X==="string"||typeof X==="number"}function Q_(X,Y){if("conditions"in Y){let{operator:K,conditions:$}=Y;switch(K){case"and":return $.every((H)=>Q_(X,H));case"or":return $.some((H)=>Q_(X,H));case"not":return!$.every((H)=>Q_(X,H));default:return!0}}let{field:Q,operator:J,value:G}=Y,Z=Q.join("."),W=T60(X,Z);switch(J){case"eq":return W===G;case"gt":return FK(W)&&FK(G)&&W>G;case"gte":return FK(W)&&FK(G)&&W>=G;case"lt":return FK(W)&&FK(G)&&W<G;case"lte":return FK(W)&&FK(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=TI6(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 T60(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 AI6(X,Y){return[...X].sort((Q,J)=>{for(let G of Y){let Z=G.field.join("."),W=T60(Q,Z),K=T60(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 PI6,EI6,jI6,A60;var wX4=g(()=>{M60();zX4();F5();LX4();o0();s4();ZK();PI6={LLM:P60,ASSISTANTS:UX4};EI6=GH.extend({binding:L.union([L.object({}).passthrough(),L.string()]).optional()}),jI6=WH(NJ),A60=r0({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",inputSchema:EI6,outputSchema:jI6,handler:async(X,Y)=>{await Y.access.check();let Q=j4(Y),J=X.binding?typeof X.binding==="string"?(()=>{let z=PI6[X.binding.toUpperCase()];if(!z)throw Error(`Unknown binding: ${X.binding}`);return z})():X.binding:void 0,G=J?Y_(J):void 0,W=(await Y.storage.connections.list(Q.id)).filter((z)=>z.connection_type!=="VIRTUAL"),K=G?await Promise.all(W.map(async(z)=>{if(!z.tools||z.tools.length===0)return null;return G.isImplementedBy(z.tools.map((N)=>({name:N.name,inputSchema:N.inputSchema,outputSchema:N.outputSchema})))?z:null})).then((z)=>z.filter((D)=>D!==null)):W;if(X.where)K=K.filter((z)=>Q_(z,X.where));if(X.orderBy&&X.orderBy.length>0)K=AI6(K,X.orderBy);let $=K.length,H=X.offset??0,F=X.limit??100,V=K.slice(H,H+F),q=H+F<$;return{items:V,totalCount:$,hasMore:q}}})});var II6,E60;var MX4=g(()=>{F5();s4();ZK();II6=_w(NJ),E60=r0({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",inputSchema:kw,outputSchema:II6,handler:async(X,Y)=>{let Q=j4(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 J_=(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 PX4(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 CI6(X){let Y=X.split("::");if(Y.length!==2||!Y[0]||!Y[1])return null;return Y}function RI6(X){if(typeof X==="object"&&X!==null&&"value"in X){let Y=X.value;if(typeof Y==="string")return Y}return null}function SI6(X,Y){let Q={};if(!X||!Y)return Q;for(let J of Y){if(J==="*"){Q["*"]=["*"];continue}let G=CI6(J);if(!G)continue;let[Z,W]=G,K=J_(Z,X),$=RI6(K);if($){if(!Q[$])Q[$]=[];Q[$].push(W)}}return Q}function TX4(X,Y){let Q=SI6(X,Y);return new Set(Object.keys(Q).filter((J)=>J!=="*"))}var AX4=()=>{};class j60{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=zU("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 EX4=g(()=>{uk()});async function _I6(X,Y,Q,J){for(let Z of Y){if(Z==="*")continue;let[W]=PX4(Z),K=J_(W,X);if(K===void 0||K===null)throw Error(`Scope references key "${W}" but it's not present in state`)}let G=TX4(X,Y);for(let Z of G){if(Z.endsWith("_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 vI6,kI6,I60;var jX4=g(()=>{AX4();EX4();o0();s4();ck();ZK();vI6=L.object({id:L.string().describe("ID of the connection to update"),data:D14.describe("Partial connection data to update")}),kI6=L.object({item:NJ.describe("The updated connection entity")});I60=r0({name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update an existing MCP connection in the organization",inputSchema:vI6,outputSchema:kI6,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);if(await Y.access.check(),!E8(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=xk($);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");$=gk(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 _I6(H,F,Q.id,Y)}let V=Z.connection_token??W.connection_token;if(!V)try{let w=await new j60(Y.db,Y.vault).get(G);if(w?.accessToken)V=w.accessToken}catch{}let q=await TU({id:W.id,title:Z.title??W.title,connection_type:K,connection_url:$,connection_token:V,connection_headers:Z.connection_headers??W.connection_headers}).catch(()=>null),z=q?.length?q:null,D={...Z,connection_url:$,tools:z,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 C60;var IX4=g(()=>{F5();s4();ZK();C60=r0({name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete a connection",inputSchema:yw,outputSchema:fw(NJ),handler:async(X,Y)=>{H4(Y);let Q=j4(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 R60;var CX4=g(()=>{o0();s4();R60=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=j4(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 RX4=g(()=>{m94();wX4();MX4();jX4();IX4();CX4()});import{sql as p6}from"kysely";function SX4(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 bI6(X,Y){let Q=X;for(let G=Y.length;G>=1;G--){let Z=`$${G}`;if(Q.includes(Z))Q=Q.replaceAll(Z,SX4(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=SX4(Y[G]);Q=Q.slice(0,Z)+W+Q.slice(Z+1)}return Q}function vX4(X){return X.replace(/-/g,"_")}function xI6(X){return`app_${vX4(X)}`}function gI6(X){return`app_role_${vX4(X)}`}function uI6(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 mI6(X,Y,Q){if(await p6`CREATE SCHEMA IF NOT EXISTS ${p6.id(Y)}`.execute(X),!(await p6`
|
|
408
408
|
SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${Q}) as exists
|
|
409
|
-
`.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 lI6(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(uI6(G))return await mI6(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 fI6,hI6,kX4;var _X4=g(()=>{o0();s4();fI6=L.object({results:L.array(L.unknown()).optional(),success:L.boolean().optional()});hI6=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()});kX4=r0({name:"DATABASES_RUN_SQL",description:"Run a SQL query against the database",inputSchema:hI6,outputSchema:L.object({result:L.array(fI6)}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=bI6(X.sql,X.params||[]);if(!Y.connectionId)throw Error("Connection context required for database access");let J=xI6(Y.connectionId),G=gI6(Y.connectionId);return{result:[{results:(await lI6(Y.db,J,G,Q)).rows,success:!0}]}}})});var yX4,pI6,fX4;var GW=g(()=>{o0();M60();yX4=L.object({connectionId:L.string().optional().describe("Filter subscriptions by connection ID (optional)")}),pI6=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)")}),fX4=L.object({subscriptions:L.array(pI6).describe("List of subscriptions")})});var S60;var bX4=g(()=>{s4();GW();S60=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:bw,outputSchema:hw,handler:async(X,Y)=>{H4(Y);let Q=j4(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 v60;var hX4=g(()=>{s4();GW();v60=r0({name:"EVENT_SUBSCRIBE",description:"Subscribe to events of a specific type. The subscriber is automatically set to the caller's connection.",inputSchema:xw,outputSchema:gw,handler:async(X,Y)=>{H4(Y);let Q=j4(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 k60;var xX4=g(()=>{s4();GW();k60=r0({name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events by removing a subscription.",inputSchema:lw,outputSchema:dw,handler:async(X,Y)=>{H4(Y);let Q=j4(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 _60;var gX4=g(()=>{s4();GW();_60=r0({name:"EVENT_CANCEL",description:"Cancel a recurring event to stop future deliveries. Only the publisher can cancel their own events.",inputSchema:pw,outputSchema:cw,handler:async(X,Y)=>{H4(Y);let Q=j4(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 y60;var uX4=g(()=>{s4();GW();y60=r0({name:"EVENT_ACK",description:"Acknowledge delivery of an event. Call after successfully processing an event received via ON_EVENTS with retryAfter.",inputSchema:nw,outputSchema:iw,handler:async(X,Y)=>{H4(Y);let Q=j4(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 f60;var mX4=g(()=>{s4();GW();f60=r0({name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions, optionally filtered by connection ID.",inputSchema:yX4,outputSchema:fX4,handler:async(X,Y)=>{H4(Y);let Q=j4(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 b60;var lX4=g(()=>{s4();GW();b60=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:uw,outputSchema:mw,handler:async(X,Y)=>{H4(Y);let Q=j4(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 dX4=g(()=>{bX4();hX4();xX4();gX4();uX4();mX4();lX4();GW()});var h60,nI6,vG,pX4,cX4;var vU=g(()=>{o0();h60=L.enum(["inclusion","exclusion"]).describe("Tool selection mode: 'inclusion' = include selected (default), 'exclusion' = exclude selected"),nI6=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.")}),vG=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:h60.describe("Tool selection mode: 'inclusion' = include selected, 'exclusion' = exclude selected"),status:L.enum(["active","inactive"]).describe("Current status"),metadata:L.object({instructions:L.string().optional().describe("MCP server instructions")}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:L.array(nI6).describe("Connections with their selected tools (behavior depends on tool_selection_mode)")}),pX4=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:h60.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"),metadata:L.object({instructions:L.string().optional().describe("MCP server instructions")}).nullable().optional().describe("Additional metadata including MCP server instructions"),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)")}),cX4=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:h60.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"),metadata:L.object({instructions:L.string().optional().describe("MCP server instructions")}).nullable().optional().describe("Additional metadata including MCP server instructions"),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 iI6,aI6,x60;var nX4=g(()=>{o0();s4();vU();iI6=L.object({data:pX4.describe("Data for the new virtual MCP")}),aI6=L.object({item:vG.describe("The created virtual MCP entity")}),x60=r0({name:"COLLECTION_VIRTUAL_MCP_CREATE",description:"Create a new MCP virtual MCP in the organization",inputSchema:iI6,outputSchema:aI6,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);await Y.access.check();let J=E8(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 rI6(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 VK(X){return typeof X==="string"||typeof X==="number"}function g60(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 oI6(X,Y){return X.connections.some((Q)=>Q.connection_id===Y)}function G_(X,Y){if("conditions"in Y){let{operator:K,conditions:$}=Y;switch(K){case"and":return $.every((H)=>G_(X,H));case"or":return $.some((H)=>G_(X,H));case"not":return!$.every((H)=>G_(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 oI6(X,G)}let W=g60(X,Z);switch(J){case"eq":return W===G;case"gt":return VK(W)&&VK(G)&&W>G;case"gte":return VK(W)&&VK(G)&&W>=G;case"lt":return VK(W)&&VK(G)&&W<G;case"lte":return VK(W)&&VK(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=rI6(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 sI6(X,Y){return[...X].sort((Q,J)=>{for(let G of Y){let Z=G.field.join("."),W=g60(Q,Z),K=g60(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 tI6,eI6,u60;var iX4=g(()=>{F5();s4();vU();tI6=GH,eI6=WH(vG),u60=r0({name:"COLLECTION_VIRTUAL_MCP_LIST",description:"List all MCP virtual MCPs in the organization",inputSchema:tI6,outputSchema:eI6,handler:async(X,Y)=>{await Y.access.check();let Q=j4(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((V)=>G_(V,X.where));if(X.orderBy&&X.orderBy.length>0)Z=sI6(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 XC6,YC6,m60;var aX4=g(()=>{o0();s4();vU();XC6=L.object({id:L.string().describe("ID of the virtual MCP to retrieve")}),YC6=L.object({item:vG.nullable().describe("The retrieved virtual MCP, or null if not found")}),m60=r0({name:"COLLECTION_VIRTUAL_MCP_GET",description:"Get an MCP virtual MCP by ID",inputSchema:XC6,outputSchema:YC6,handler:async(X,Y)=>{H4(Y);let Q=j4(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 QC6,JC6,l60;var rX4=g(()=>{o0();s4();vU();QC6=L.object({id:L.string().describe("ID of the virtual MCP to update"),data:cX4.describe("Partial virtual MCP data to update")}),JC6=L.object({item:vG.describe("The updated virtual MCP entity")}),l60=r0({name:"COLLECTION_VIRTUAL_MCP_UPDATE",description:"Update an MCP virtual MCP",inputSchema:QC6,outputSchema:JC6,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);await Y.access.check();let J=E8(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 GC6,WC6,d60;var oX4=g(()=>{o0();s4();vU();GC6=L.object({id:L.string().describe("ID of the virtual MCP to delete")}),WC6=L.object({item:vG.describe("The deleted virtual MCP entity")}),d60=r0({name:"COLLECTION_VIRTUAL_MCP_DELETE",description:"Delete an MCP virtual MCP",inputSchema:GC6,outputSchema:WC6,handler:async(X,Y)=>{H4(Y);let Q=j4(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 sX4=g(()=>{nX4();iX4();aX4();rX4();oX4()});var KC6,p60;var tX4=g(()=>{s4();o0();KC6=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")}),p60=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(KC6).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=j4(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 c60;var eX4=g(()=>{s4();o0();c60=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:j4(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 XY4=g(()=>{tX4();eX4()});var n60;var YY4=g(()=>{o0();s4();n60=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=E8(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 i60;var QY4=g(()=>{o0();s4();i60=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=E8(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 a60;var JY4=g(()=>{o0();s4();a60=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 r60;var GY4=g(()=>{o0();s4();r60=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 o60;var WY4=g(()=>{o0();s4();o60=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 rw;var s60=g(()=>{o0();rw=L.object({title:L.string(),url:L.string(),icon:L.string()})});var t60;var ZY4=g(()=>{o0();s4();s60();t60=r0({name:"ORGANIZATION_SETTINGS_GET",description:"Get organization-level settings",inputSchema:L.object({}),outputSchema:L.object({organizationId:L.string(),sidebar_items:L.array(rw).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 e60;var KY4=g(()=>{o0();s4();s60();e60=r0({name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization-level settings",inputSchema:L.object({organizationId:L.string(),sidebar_items:L.array(rw).optional(),enabled_plugins:L.array(L.string()).optional()}),outputSchema:L.object({organizationId:L.string(),sidebar_items:L.array(rw).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 X10;var $Y4=g(()=>{o0();s4();X10=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 Y10;var HY4=g(()=>{o0();s4();Y10=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 Q10;var FY4=g(()=>{o0();s4();Q10=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 J10;var VY4=g(()=>{o0();s4();J10=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 qY4=g(()=>{YY4();QY4();JY4();GY4();WY4();ZY4();KY4();$Y4();HY4();FY4();VY4()});var UY4,kG,zY4,BY4;var ZH=g(()=>{o0();UY4=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")}),kG=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")}),zY4=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")}),BY4=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 FC6,VC6,G10;var DY4=g(()=>{o0();s4();ZH();uk();FC6=L.object({data:zY4.describe("Data for the new thread (id is auto-generated if not provided)")}),VC6=L.object({item:kG.describe("The created thread entity")}),G10=r0({name:"COLLECTION_THREADS_CREATE",description:"Create a new thread in the organization",inputSchema:FC6,outputSchema:VC6,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);await Y.access.check();let J=E8(Y);if(!J)throw Error("User ID required to create thread");let G=X.data.id??zU("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 qC6,UC6,W10;var NY4=g(()=>{F5();s4();ZH();o0();qC6=GH.extend({where:L.object({created_by:L.string().optional()}).optional()}),UC6=WH(kG),W10=r0({name:"COLLECTION_THREADS_LIST",description:"List all threads in the organization with filtering, sorting, and pagination",inputSchema:qC6,outputSchema:UC6,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=j4(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 zC6,Z10;var OY4=g(()=>{F5();s4();ZH();zC6=_w(kG),Z10=r0({name:"COLLECTION_THREADS_GET",description:"Get thread details by ID",inputSchema:kw,outputSchema:zC6,handler:async(X,Y)=>{H4(Y);let Q=j4(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 BC6,DC6,K10;var LY4=g(()=>{o0();s4();ZH();BC6=L.object({id:L.string().describe("ID of the thread to update"),data:BY4.describe("Partial thread data to update")}),DC6=L.object({item:kG.describe("The updated thread entity")}),K10=r0({name:"COLLECTION_THREADS_UPDATE",description:"Update an existing thread in the organization",inputSchema:BC6,outputSchema:DC6,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);await Y.access.check();let J=E8(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 $10;var wY4=g(()=>{F5();s4();ZH();$10=r0({name:"COLLECTION_THREADS_DELETE",description:"Delete a thread",inputSchema:yw,outputSchema:fw(kG),handler:async(X,Y)=>{H4(Y);let Q=j4(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 NC6,OC6,H10;var MY4=g(()=>{o0();s4();ZH();NC6=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")}),OC6=L.object({items:L.array(UY4).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")}),H10=r0({name:"COLLECTION_THREAD_MESSAGES_LIST",description:"List all messages for a specific thread",inputSchema:NC6,outputSchema:OC6,handler:async(X,Y)=>{let Q=j4(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 PY4=g(()=>{DY4();NY4();OY4();LY4();wY4();MY4()});var wC6,MC6,F10;var TY4=g(()=>{o0();s4();wC6=L.object({id:L.string().min(1)}),MC6=L.object({user:L.object({id:L.string(),name:L.string(),email:L.string(),image:L.string().nullable()}).nullable()}),F10=r0({name:"USER_GET",description:"Get a user by id (restricted to shared organizations)",inputSchema:wC6,outputSchema:MC6,handler:async(X,Y)=>{await Y.access.check(),H4(Y);let Q=E8(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 AY4=g(()=>{TY4()});var jY4={};h4(jY4,{managementMCP:()=>TC6,ALL_TOOLS:()=>EY4});var EY4,TC6=(X)=>{let Y=EY4.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 v84({name:"mcp-mesh-management",version:"1.0.0"}).withTools(Y).build()};var IY4=g(()=>{k84();n84();u94();RX4();_X4();dX4();sX4();XY4();qY4();PY4();AY4();EY4=[n60,i60,a60,r60,o60,t60,e60,X10,Y10,Q10,J10,N60,A60,E60,I60,C60,R60,x60,u60,m60,l60,d60,kX4,p60,c60,c40,i40,a40,n40,S60,v60,k60,_60,y60,f60,b60,F10,z60,B60,D60,G10,W10,Z10,K10,$10,H10]});g_();import{Migrator as bY4}from"kysely";var k10={benchmark:()=>Promise.resolve().then(() => (v10(),S10)).then((X)=>X.seed)};async function _10(X,Y){let Q=k10[Y];if(!Q)throw Error(`Unknown seed: ${Y}. Available: ${Object.keys(k10).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}_G();NQ();_G();NQ();FX();H9();var z8=(X,Y="ms")=>{return new Date(Date.now()+(Y==="sec"?X*1000:X))},YE=new WeakMap;function HQ0(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 QE(X,Y){if(!YE.has(X))YE.set(X,new Map);let Q=YE.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 YE.get(X).set(Y,J),J}function F9(X,Y){return{...HQ0(Y,{fields:QE(X,"user")}),id:Y.id}}function j5(X,Y){return HQ0(Y,{fields:QE(X,"session")})}function zg(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 JE(X,Y={},Q){return zg(Y,{fields:QE(X,"user"),action:Q})}function Bg(X,Y){return zg(Y,{fields:QE(X,"session")})}function SX(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}HY();o0();var RW4="127.0.0.1";function fW(X,Y){if(Y.advanced?.ipAddress?.disableIpTracking)return null;if(iG()||JF())return RW4;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(SW4(W))return W}}return null}function SW4(X){if(cK().safeParse(X).success)return!0;if(nK().safeParse(X).success)return!0;return!1}VX();P5();HY();j8();import{sql as C5}from"kysely";async function zQ0(X,Y){let Q;if(!X.database){let J=xY(X),G=Object.keys(J).reduce((W,K)=>{return W[K]=[],W},{}),{memoryAdapter:Z}=await Promise.resolve().then(() => (UQ0(),qQ0));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 Mg(X){return zQ0(X,async(Y)=>{let{createKyselyAdapter:Q}=await Promise.resolve().then(() => (wg(),Lg)),{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(() => (wg(),Lg));return W(J,{type:G||"sqlite",debugLogs:Y.database&&"debugLogs"in Y.database?Y.database.debugLogs:!1,transaction:Z})(Y)})}function BQ0(X,Y){let Q=Y.hooks;async function J($,H,F){let V=await gY(),q=$;for(let N of Q||[]){let O=N[H]?.create?.before;if(O){let w=await O(q,V);if(w===!1)return null;if(typeof w==="object"&&"data"in w)q={...q,...w.data}}}let z=F?await F.fn(q):null,D=!F||F.executeMainFn?await(await K1(X)).create({model:H,data:q,forceAllowId:!0}):z;for(let N of Q||[]){let O=N[H]?.create?.after;if(O)await O(D,V)}return D}async function G($,H,F,V){let q=await gY(),z=$;for(let O of Q||[]){let w=O[F]?.update?.before;if(w){let E=await w($,q);if(E===!1)return null;if(typeof E==="object"&&"data"in E)z={...z,...E.data}}}let D=V?await V.fn(z):null,N=!V||V.executeMainFn?await(await K1(X)).update({model:F,update:z,where:H}):D;for(let O of Q||[]){let w=O[F]?.update?.after;if(w)await w(N,q)}return N}async function Z($,H,F,V){let q=await gY(),z=$;for(let O of Q||[]){let w=O[F]?.update?.before;if(w){let E=await w($,q);if(E===!1)return null;if(typeof E==="object"&&"data"in E)z={...z,...E.data}}}let D=V?await V.fn(z):null,N=!V||V.executeMainFn?await(await K1(X)).updateMany({model:F,update:z,where:H}):D;for(let O of Q||[]){let w=O[F]?.update?.after;if(w)await w(N,q)}return N}async function W($,H,F){let V=await gY(),q=null;try{q=(await(await K1(X)).findMany({model:H,where:$,limit:1}))[0]||null}catch(N){}if(q)for(let N of Q||[]){let O=N[H]?.delete?.before;if(O){if(await O(q,V)===!1)return null}}let z=F?await F.fn($):null,D=!F||F.executeMainFn?await(await K1(X)).delete({model:H,where:$}):z;if(q)for(let N of Q||[]){let O=N[H]?.delete?.after;if(O)await O(q,V)}return D}async function K($,H,F){let V=await gY(),q=[];try{q=await(await K1(X)).findMany({model:H,where:$})}catch(N){}for(let N of q)for(let O of Q||[]){let w=O[H]?.delete?.before;if(w){if(await w(N,V)===!1)return null}}let z=F?await F.fn($):null,D=!F||F.executeMainFn?await(await K1(X)).deleteMany({model:H,where:$}):z;for(let N of q)for(let O of Q||[]){let w=O[H]?.delete?.after;if(w)await w(N,V)}return D}return{createWithHooks:J,updateWithHooks:G,updateManyWithHooks:Z,deleteWithHooks:W,deleteManyWithHooks:K}}var FE=(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}=BQ0(X,Y);async function V(q){if(!G)return;let z=await G.get(`active-sessions-${q.id}`);if(!z)return;let D=Date.now(),N=(D1(z)||[]).filter((O)=>O.expiresAt>D);await Promise.all(N.map(async({token:O})=>{let w=await G.get(O);if(!w)return;let E=D1(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:q}),Math.floor(C))}))}return{createOAuthUser:async(q,z)=>{return Wz(X,async()=>{let D=await W({createdAt:new Date,updatedAt:new Date,...q},"user",void 0);return{user:D,account:await W({...z,userId:D.id,createdAt:new Date,updatedAt:new Date},"account",void 0)}})},createUser:async(q)=>{return await W({createdAt:new Date,updatedAt:new Date,...q,email:q.email?.toLowerCase()},"user",void 0)},createAccount:async(q)=>{return await W({createdAt:new Date,updatedAt:new Date,...q},"account",void 0)},listSessions:async(q)=>{if(G){let z=await G.get(`active-sessions-${q}`);if(!z)return[];let D=D1(z)||[],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=D1(C);if(!A)return[];let T=j5(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:q}]})},listUsers:async(q,z,D,N)=>{return await(await K1(X)).findMany({model:"user",limit:q,offset:z,sortBy:D,where:N})},countTotalUsers:async(q)=>{let z=await(await K1(X)).count({model:"user",where:q});if(typeof z==="string")return parseInt(z);return z},deleteUser:async(q)=>{if(G)await G.delete(`active-sessions-${q}`);if(!G||J.session?.storeSessionInDatabase)await F([{field:"userId",value:q}],"session",void 0);await F([{field:"userId",value:q}],"account",void 0),await H([{field:"id",value:q}],"user",void 0)},createSession:async(q,z,D,N)=>{let O=await gY().catch(()=>null),w=O?.headers||O?.request?.headers,{id:E,...C}=D||{},A=Bg(O?.context.options??J,{}),T={ipAddress:O?.request||O?.headers?fW(O?.request||O?.headers,O?.context.options)||"":"",userAgent:w?.get("user-agent")||"",...C,expiresAt:z?z8(86400,"sec"):z8(Z,"sec"),userId:q,token:g8(32),createdAt:new Date,updatedAt:new Date,...A,...N?C:{}};return await W(T,"session",G?{fn:async(I)=>{let R=await G.get(`active-sessions-${q}`),v=[],_=Date.now();if(R)v=D1(R)||[],v=v.filter((m)=>m.expiresAt>_);let y=v.sort((m,t)=>m.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-${q}`,JSON.stringify(y),a);let x=await X.findOne({model:"user",where:[{field:"id",value:q}]}),k=Math.max(Math.floor((T.expiresAt.getTime()-_)/1000),0);if(k>0)await G.set(T.token,JSON.stringify({session:I,user:x}),k);return I},executeMainFn:J.session?.storeSessionInDatabase}:void 0)},findSession:async(q)=>{if(G){let O=await G.get(q);if(!O&&!J.session?.storeSessionInDatabase)return null;if(O){let w=D1(O);if(!w)return null;return{session:j5(Y.options,{...w.session,expiresAt:new Date(w.session.expiresAt),createdAt:new Date(w.session.createdAt),updatedAt:new Date(w.session.updatedAt)}),user:F9(Y.options,{...w.user,createdAt:new Date(w.user.createdAt),updatedAt:new Date(w.user.updatedAt)})}}}let z=await(await K1(X)).findOne({model:"session",where:[{value:q,field:"token"}],join:{user:!0}});if(!z)return null;let{user:D,...N}=z;if(!D)return null;return{session:j5(Y.options,N),user:F9(Y.options,D)}},findSessions:async(q)=>{if(G){let D=[];for(let N of q){let O=await G.get(N);if(O){let w=D1(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 z=await(await K1(X)).findMany({model:"session",where:[{field:"token",value:q,operator:"in"}],join:{user:!0}});if(!z.length)return[];if(z.some((D)=>!D.user))return[];return z.map((D)=>{let{user:N,...O}=D;return{session:O,user:N}})},updateSession:async(q,z)=>{return await K(z,[{field:"token",value:q}],"session",G?{async fn(D){let N=await G.get(q),O=null;if(N){let w=D1(N);if(!w)return null;return O={...w.session,...D},O}else return null},executeMainFn:J.session?.storeSessionInDatabase}:void 0)},deleteSession:async(q)=>{if(G){let z=await G.get(q);if(z){let{session:D}=D1(z)??{};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=D1(O)||[],E=Date.now(),C=w.filter((T)=>T.expiresAt>E&&T.token!==q),A=C.sort((T,I)=>T.expiresAt-I.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(q),!J.session?.storeSessionInDatabase||Y.options.session?.preserveSessionInDatabase)return}await(await K1(X)).delete({model:"session",where:[{field:"token",value:q}]})},deleteAccounts:async(q)=>{await F([{field:"userId",value:q}],"account",void 0)},deleteAccount:async(q)=>{await H([{field:"id",value:q}],"account",void 0)},deleteSessions:async(q)=>{if(G){if(typeof q==="string"){let z=await G.get(`active-sessions-${q}`),D=z?D1(z):[];if(!D)return;for(let N of D)await G.delete(N.token)}else for(let z of q)if(await G.get(z))await G.delete(z);if(!J.session?.storeSessionInDatabase||Y.options.session?.preserveSessionInDatabase)return}await F([{field:Array.isArray(q)?"token":"userId",value:q,operator:Array.isArray(q)?"in":void 0}],"session",void 0)},findOAuthUser:async(q,z,D)=>{let N=await(await K1(X)).findMany({model:"account",where:[{value:z,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:q.toLowerCase(),field:"email"}]});if(O)return{user:O,accounts:[N]};return null}else{let O=await(await K1(X)).findOne({model:"user",where:[{value:q.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(q,z)=>{let D=await(await K1(X)).findOne({model:"user",where:[{value:q.toLowerCase(),field:"email"}],join:{...z?.includeAccounts?{account:!0}:{}}});if(!D)return null;let{account:N,...O}=D;return{user:O,accounts:N??[]}},findUserById:async(q)=>{if(!q)return null;return await(await K1(X)).findOne({model:"user",where:[{field:"id",value:q}]})},linkAccount:async(q)=>{return await W({createdAt:new Date,updatedAt:new Date,...q},"account",void 0)},updateUser:async(q,z)=>{let D=await K(z,[{field:"id",value:q}],"user",void 0);return await V(D),await V(D),D},updateUserByEmail:async(q,z)=>{let D=await K(z,[{field:"email",value:q.toLowerCase()}],"user",void 0);return await V(D),await V(D),D},updatePassword:async(q,z)=>{await $({password:z},[{field:"userId",value:q},{field:"providerId",value:"credential"}],"account",void 0)},findAccounts:async(q)=>{return await(await K1(X)).findMany({model:"account",where:[{field:"userId",value:q}]})},findAccount:async(q)=>{return await(await K1(X)).findOne({model:"account",where:[{field:"accountId",value:q}]})},findAccountByProviderId:async(q,z)=>{return await(await K1(X)).findOne({model:"account",where:[{field:"accountId",value:q},{field:"providerId",value:z}]})},findAccountByUserId:async(q)=>{return await(await K1(X)).findMany({model:"account",where:[{field:"userId",value:q}]})},updateAccount:async(q,z)=>{return await K(z,[{field:"id",value:q}],"account",void 0)},createVerificationValue:async(q)=>{return await W({createdAt:new Date,updatedAt:new Date,...q},"verification",void 0)},findVerificationValue:async(q)=>{let z=await(await K1(X)).findMany({model:"verification",where:[{field:"identifier",value:q}],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 z[0]},deleteVerificationValue:async(q)=>{await(await K1(X)).delete({model:"verification",where:[{field:"id",value:q}]})},deleteVerificationByIdentifier:async(q)=>{await(await K1(X)).delete({model:"verification",where:[{field:"identifier",value:q}]})},updateVerificationValue:async(q,z)=>{return await K(z,[{field:"id",value:q}],"verification",void 0)}}};function DQ0(X){let Y=xY(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 bW4={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 NQ0(X,Y,Q){function J(Z){return Z.toLowerCase().split("(")[0].trim()}if(Y==="string[]"||Y==="number[]")return X.toLowerCase().includes("json");let G=bW4[Q];return(Array.isArray(Y)?G.string.map((Z)=>Z.toLowerCase()):G[Y].map((Z)=>Z.toLowerCase())).includes(J(X))}async function hW4(X){try{let Y=await C5`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 hB(X){let Y=DQ0(X),Q=WF(X.logger),{kysely:J,databaseType:G}=await QM(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 hW4(J),Q.debug(`PostgreSQL migration: Using schema '${Z}' (from search_path)`);try{if(!(await C5`
|
|
409
|
+
`.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 lI6(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(uI6(G))return await mI6(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 fI6,hI6,kX4;var _X4=g(()=>{o0();s4();fI6=L.object({results:L.array(L.unknown()).optional(),success:L.boolean().optional()});hI6=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()});kX4=r0({name:"DATABASES_RUN_SQL",description:"Run a SQL query against the database",inputSchema:hI6,outputSchema:L.object({result:L.array(fI6)}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=bI6(X.sql,X.params||[]);if(!Y.connectionId)throw Error("Connection context required for database access");let J=xI6(Y.connectionId),G=gI6(Y.connectionId);return{result:[{results:(await lI6(Y.db,J,G,Q)).rows,success:!0}]}}})});var yX4,pI6,fX4;var GW=g(()=>{o0();M60();yX4=L.object({connectionId:L.string().optional().describe("Filter subscriptions by connection ID (optional)")}),pI6=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)")}),fX4=L.object({subscriptions:L.array(pI6).describe("List of subscriptions")})});var S60;var bX4=g(()=>{s4();GW();S60=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:bw,outputSchema:hw,handler:async(X,Y)=>{H4(Y);let Q=j4(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 v60;var hX4=g(()=>{s4();GW();v60=r0({name:"EVENT_SUBSCRIBE",description:"Subscribe to events of a specific type. The subscriber is automatically set to the caller's connection.",inputSchema:xw,outputSchema:gw,handler:async(X,Y)=>{H4(Y);let Q=j4(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 k60;var xX4=g(()=>{s4();GW();k60=r0({name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events by removing a subscription.",inputSchema:lw,outputSchema:dw,handler:async(X,Y)=>{H4(Y);let Q=j4(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 _60;var gX4=g(()=>{s4();GW();_60=r0({name:"EVENT_CANCEL",description:"Cancel a recurring event to stop future deliveries. Only the publisher can cancel their own events.",inputSchema:pw,outputSchema:cw,handler:async(X,Y)=>{H4(Y);let Q=j4(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 y60;var uX4=g(()=>{s4();GW();y60=r0({name:"EVENT_ACK",description:"Acknowledge delivery of an event. Call after successfully processing an event received via ON_EVENTS with retryAfter.",inputSchema:nw,outputSchema:iw,handler:async(X,Y)=>{H4(Y);let Q=j4(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 f60;var mX4=g(()=>{s4();GW();f60=r0({name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions, optionally filtered by connection ID.",inputSchema:yX4,outputSchema:fX4,handler:async(X,Y)=>{H4(Y);let Q=j4(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 b60;var lX4=g(()=>{s4();GW();b60=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:uw,outputSchema:mw,handler:async(X,Y)=>{H4(Y);let Q=j4(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 dX4=g(()=>{bX4();hX4();xX4();gX4();uX4();mX4();lX4();GW()});var h60,nI6,vG,pX4,cX4;var vU=g(()=>{o0();h60=L.enum(["inclusion","exclusion"]).describe("Tool selection mode: 'inclusion' = include selected (default), 'exclusion' = exclude selected"),nI6=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.")}),vG=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:h60.describe("Tool selection mode: 'inclusion' = include selected, 'exclusion' = exclude selected"),status:L.enum(["active","inactive"]).describe("Current status"),metadata:L.object({instructions:L.string().optional().describe("MCP server instructions")}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:L.array(nI6).describe("Connections with their selected tools (behavior depends on tool_selection_mode)")}),pX4=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:h60.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"),metadata:L.object({instructions:L.string().optional().describe("MCP server instructions")}).nullable().optional().describe("Additional metadata including MCP server instructions"),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)")}),cX4=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:h60.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"),metadata:L.object({instructions:L.string().optional().describe("MCP server instructions")}).nullable().optional().describe("Additional metadata including MCP server instructions"),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 iI6,aI6,x60;var nX4=g(()=>{o0();s4();vU();iI6=L.object({data:pX4.describe("Data for the new virtual MCP")}),aI6=L.object({item:vG.describe("The created virtual MCP entity")}),x60=r0({name:"COLLECTION_VIRTUAL_MCP_CREATE",description:"Create a new MCP virtual MCP in the organization",inputSchema:iI6,outputSchema:aI6,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);await Y.access.check();let J=E8(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 rI6(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 VK(X){return typeof X==="string"||typeof X==="number"}function g60(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 oI6(X,Y){return X.connections.some((Q)=>Q.connection_id===Y)}function G_(X,Y){if("conditions"in Y){let{operator:K,conditions:$}=Y;switch(K){case"and":return $.every((H)=>G_(X,H));case"or":return $.some((H)=>G_(X,H));case"not":return!$.every((H)=>G_(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 oI6(X,G)}let W=g60(X,Z);switch(J){case"eq":return W===G;case"gt":return VK(W)&&VK(G)&&W>G;case"gte":return VK(W)&&VK(G)&&W>=G;case"lt":return VK(W)&&VK(G)&&W<G;case"lte":return VK(W)&&VK(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=rI6(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 sI6(X,Y){return[...X].sort((Q,J)=>{for(let G of Y){let Z=G.field.join("."),W=g60(Q,Z),K=g60(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 tI6,eI6,u60;var iX4=g(()=>{F5();s4();vU();tI6=GH,eI6=WH(vG),u60=r0({name:"COLLECTION_VIRTUAL_MCP_LIST",description:"List all MCP virtual MCPs in the organization",inputSchema:tI6,outputSchema:eI6,handler:async(X,Y)=>{await Y.access.check();let Q=j4(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((V)=>G_(V,X.where));if(X.orderBy&&X.orderBy.length>0)Z=sI6(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 XC6,YC6,m60;var aX4=g(()=>{o0();s4();vU();XC6=L.object({id:L.string().describe("ID of the virtual MCP to retrieve")}),YC6=L.object({item:vG.nullable().describe("The retrieved virtual MCP, or null if not found")}),m60=r0({name:"COLLECTION_VIRTUAL_MCP_GET",description:"Get an MCP virtual MCP by ID",inputSchema:XC6,outputSchema:YC6,handler:async(X,Y)=>{H4(Y);let Q=j4(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 QC6,JC6,l60;var rX4=g(()=>{o0();s4();vU();QC6=L.object({id:L.string().describe("ID of the virtual MCP to update"),data:cX4.describe("Partial virtual MCP data to update")}),JC6=L.object({item:vG.describe("The updated virtual MCP entity")}),l60=r0({name:"COLLECTION_VIRTUAL_MCP_UPDATE",description:"Update an MCP virtual MCP",inputSchema:QC6,outputSchema:JC6,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);await Y.access.check();let J=E8(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 GC6,WC6,d60;var oX4=g(()=>{o0();s4();vU();GC6=L.object({id:L.string().describe("ID of the virtual MCP to delete")}),WC6=L.object({item:vG.describe("The deleted virtual MCP entity")}),d60=r0({name:"COLLECTION_VIRTUAL_MCP_DELETE",description:"Delete an MCP virtual MCP",inputSchema:GC6,outputSchema:WC6,handler:async(X,Y)=>{H4(Y);let Q=j4(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 sX4=g(()=>{nX4();iX4();aX4();rX4();oX4()});var KC6,p60;var tX4=g(()=>{s4();o0();KC6=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")}),p60=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(10).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(KC6).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=j4(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 c60;var eX4=g(()=>{s4();o0();c60=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:j4(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 XY4=g(()=>{tX4();eX4()});var n60;var YY4=g(()=>{o0();s4();n60=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=E8(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 i60;var QY4=g(()=>{o0();s4();i60=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=E8(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 a60;var JY4=g(()=>{o0();s4();a60=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 r60;var GY4=g(()=>{o0();s4();r60=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 o60;var WY4=g(()=>{o0();s4();o60=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 rw;var s60=g(()=>{o0();rw=L.object({title:L.string(),url:L.string(),icon:L.string()})});var t60;var ZY4=g(()=>{o0();s4();s60();t60=r0({name:"ORGANIZATION_SETTINGS_GET",description:"Get organization-level settings",inputSchema:L.object({}),outputSchema:L.object({organizationId:L.string(),sidebar_items:L.array(rw).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 e60;var KY4=g(()=>{o0();s4();s60();e60=r0({name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization-level settings",inputSchema:L.object({organizationId:L.string(),sidebar_items:L.array(rw).optional(),enabled_plugins:L.array(L.string()).optional()}),outputSchema:L.object({organizationId:L.string(),sidebar_items:L.array(rw).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 X10;var $Y4=g(()=>{o0();s4();X10=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 Y10;var HY4=g(()=>{o0();s4();Y10=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 Q10;var FY4=g(()=>{o0();s4();Q10=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 J10;var VY4=g(()=>{o0();s4();J10=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 qY4=g(()=>{YY4();QY4();JY4();GY4();WY4();ZY4();KY4();$Y4();HY4();FY4();VY4()});var UY4,kG,zY4,BY4;var ZH=g(()=>{o0();UY4=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")}),kG=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")}),zY4=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")}),BY4=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 FC6,VC6,G10;var DY4=g(()=>{o0();s4();ZH();uk();FC6=L.object({data:zY4.describe("Data for the new thread (id is auto-generated if not provided)")}),VC6=L.object({item:kG.describe("The created thread entity")}),G10=r0({name:"COLLECTION_THREADS_CREATE",description:"Create a new thread in the organization",inputSchema:FC6,outputSchema:VC6,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);await Y.access.check();let J=E8(Y);if(!J)throw Error("User ID required to create thread");let G=X.data.id??zU("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 qC6,UC6,W10;var NY4=g(()=>{F5();s4();ZH();o0();qC6=GH.extend({where:L.object({created_by:L.string().optional()}).optional()}),UC6=WH(kG),W10=r0({name:"COLLECTION_THREADS_LIST",description:"List all threads in the organization with filtering, sorting, and pagination",inputSchema:qC6,outputSchema:UC6,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=j4(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 zC6,Z10;var OY4=g(()=>{F5();s4();ZH();zC6=_w(kG),Z10=r0({name:"COLLECTION_THREADS_GET",description:"Get thread details by ID",inputSchema:kw,outputSchema:zC6,handler:async(X,Y)=>{H4(Y);let Q=j4(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 BC6,DC6,K10;var LY4=g(()=>{o0();s4();ZH();BC6=L.object({id:L.string().describe("ID of the thread to update"),data:BY4.describe("Partial thread data to update")}),DC6=L.object({item:kG.describe("The updated thread entity")}),K10=r0({name:"COLLECTION_THREADS_UPDATE",description:"Update an existing thread in the organization",inputSchema:BC6,outputSchema:DC6,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);await Y.access.check();let J=E8(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 $10;var wY4=g(()=>{F5();s4();ZH();$10=r0({name:"COLLECTION_THREADS_DELETE",description:"Delete a thread",inputSchema:yw,outputSchema:fw(kG),handler:async(X,Y)=>{H4(Y);let Q=j4(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 NC6,OC6,H10;var MY4=g(()=>{o0();s4();ZH();NC6=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")}),OC6=L.object({items:L.array(UY4).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")}),H10=r0({name:"COLLECTION_THREAD_MESSAGES_LIST",description:"List all messages for a specific thread",inputSchema:NC6,outputSchema:OC6,handler:async(X,Y)=>{let Q=j4(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 PY4=g(()=>{DY4();NY4();OY4();LY4();wY4();MY4()});var wC6,MC6,F10;var TY4=g(()=>{o0();s4();wC6=L.object({id:L.string().min(1)}),MC6=L.object({user:L.object({id:L.string(),name:L.string(),email:L.string(),image:L.string().nullable()}).nullable()}),F10=r0({name:"USER_GET",description:"Get a user by id (restricted to shared organizations)",inputSchema:wC6,outputSchema:MC6,handler:async(X,Y)=>{await Y.access.check(),H4(Y);let Q=E8(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 AY4=g(()=>{TY4()});var jY4={};h4(jY4,{managementMCP:()=>TC6,ALL_TOOLS:()=>EY4});var EY4,TC6=(X)=>{let Y=EY4.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 v84({name:"mcp-mesh-management",version:"1.0.0"}).withTools(Y).build()};var IY4=g(()=>{k84();n84();u94();RX4();_X4();dX4();sX4();XY4();qY4();PY4();AY4();EY4=[n60,i60,a60,r60,o60,t60,e60,X10,Y10,Q10,J10,N60,A60,E60,I60,C60,R60,x60,u60,m60,l60,d60,kX4,p60,c60,c40,i40,a40,n40,S60,v60,k60,_60,y60,f60,b60,F10,z60,B60,D60,G10,W10,Z10,K10,$10,H10]});g_();import{Migrator as bY4}from"kysely";var k10={benchmark:()=>Promise.resolve().then(() => (v10(),S10)).then((X)=>X.seed)};async function _10(X,Y){let Q=k10[Y];if(!Q)throw Error(`Unknown seed: ${Y}. Available: ${Object.keys(k10).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}_G();NQ();_G();NQ();FX();H9();var z8=(X,Y="ms")=>{return new Date(Date.now()+(Y==="sec"?X*1000:X))},YE=new WeakMap;function HQ0(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 QE(X,Y){if(!YE.has(X))YE.set(X,new Map);let Q=YE.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 YE.get(X).set(Y,J),J}function F9(X,Y){return{...HQ0(Y,{fields:QE(X,"user")}),id:Y.id}}function j5(X,Y){return HQ0(Y,{fields:QE(X,"session")})}function zg(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 JE(X,Y={},Q){return zg(Y,{fields:QE(X,"user"),action:Q})}function Bg(X,Y){return zg(Y,{fields:QE(X,"session")})}function SX(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}HY();o0();var RW4="127.0.0.1";function fW(X,Y){if(Y.advanced?.ipAddress?.disableIpTracking)return null;if(iG()||JF())return RW4;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(SW4(W))return W}}return null}function SW4(X){if(cK().safeParse(X).success)return!0;if(nK().safeParse(X).success)return!0;return!1}VX();P5();HY();j8();import{sql as C5}from"kysely";async function zQ0(X,Y){let Q;if(!X.database){let J=xY(X),G=Object.keys(J).reduce((W,K)=>{return W[K]=[],W},{}),{memoryAdapter:Z}=await Promise.resolve().then(() => (UQ0(),qQ0));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 Mg(X){return zQ0(X,async(Y)=>{let{createKyselyAdapter:Q}=await Promise.resolve().then(() => (wg(),Lg)),{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(() => (wg(),Lg));return W(J,{type:G||"sqlite",debugLogs:Y.database&&"debugLogs"in Y.database?Y.database.debugLogs:!1,transaction:Z})(Y)})}function BQ0(X,Y){let Q=Y.hooks;async function J($,H,F){let V=await gY(),q=$;for(let N of Q||[]){let O=N[H]?.create?.before;if(O){let w=await O(q,V);if(w===!1)return null;if(typeof w==="object"&&"data"in w)q={...q,...w.data}}}let z=F?await F.fn(q):null,D=!F||F.executeMainFn?await(await K1(X)).create({model:H,data:q,forceAllowId:!0}):z;for(let N of Q||[]){let O=N[H]?.create?.after;if(O)await O(D,V)}return D}async function G($,H,F,V){let q=await gY(),z=$;for(let O of Q||[]){let w=O[F]?.update?.before;if(w){let E=await w($,q);if(E===!1)return null;if(typeof E==="object"&&"data"in E)z={...z,...E.data}}}let D=V?await V.fn(z):null,N=!V||V.executeMainFn?await(await K1(X)).update({model:F,update:z,where:H}):D;for(let O of Q||[]){let w=O[F]?.update?.after;if(w)await w(N,q)}return N}async function Z($,H,F,V){let q=await gY(),z=$;for(let O of Q||[]){let w=O[F]?.update?.before;if(w){let E=await w($,q);if(E===!1)return null;if(typeof E==="object"&&"data"in E)z={...z,...E.data}}}let D=V?await V.fn(z):null,N=!V||V.executeMainFn?await(await K1(X)).updateMany({model:F,update:z,where:H}):D;for(let O of Q||[]){let w=O[F]?.update?.after;if(w)await w(N,q)}return N}async function W($,H,F){let V=await gY(),q=null;try{q=(await(await K1(X)).findMany({model:H,where:$,limit:1}))[0]||null}catch(N){}if(q)for(let N of Q||[]){let O=N[H]?.delete?.before;if(O){if(await O(q,V)===!1)return null}}let z=F?await F.fn($):null,D=!F||F.executeMainFn?await(await K1(X)).delete({model:H,where:$}):z;if(q)for(let N of Q||[]){let O=N[H]?.delete?.after;if(O)await O(q,V)}return D}async function K($,H,F){let V=await gY(),q=[];try{q=await(await K1(X)).findMany({model:H,where:$})}catch(N){}for(let N of q)for(let O of Q||[]){let w=O[H]?.delete?.before;if(w){if(await w(N,V)===!1)return null}}let z=F?await F.fn($):null,D=!F||F.executeMainFn?await(await K1(X)).deleteMany({model:H,where:$}):z;for(let N of q)for(let O of Q||[]){let w=O[H]?.delete?.after;if(w)await w(N,V)}return D}return{createWithHooks:J,updateWithHooks:G,updateManyWithHooks:Z,deleteWithHooks:W,deleteManyWithHooks:K}}var FE=(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}=BQ0(X,Y);async function V(q){if(!G)return;let z=await G.get(`active-sessions-${q.id}`);if(!z)return;let D=Date.now(),N=(D1(z)||[]).filter((O)=>O.expiresAt>D);await Promise.all(N.map(async({token:O})=>{let w=await G.get(O);if(!w)return;let E=D1(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:q}),Math.floor(C))}))}return{createOAuthUser:async(q,z)=>{return Wz(X,async()=>{let D=await W({createdAt:new Date,updatedAt:new Date,...q},"user",void 0);return{user:D,account:await W({...z,userId:D.id,createdAt:new Date,updatedAt:new Date},"account",void 0)}})},createUser:async(q)=>{return await W({createdAt:new Date,updatedAt:new Date,...q,email:q.email?.toLowerCase()},"user",void 0)},createAccount:async(q)=>{return await W({createdAt:new Date,updatedAt:new Date,...q},"account",void 0)},listSessions:async(q)=>{if(G){let z=await G.get(`active-sessions-${q}`);if(!z)return[];let D=D1(z)||[],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=D1(C);if(!A)return[];let T=j5(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:q}]})},listUsers:async(q,z,D,N)=>{return await(await K1(X)).findMany({model:"user",limit:q,offset:z,sortBy:D,where:N})},countTotalUsers:async(q)=>{let z=await(await K1(X)).count({model:"user",where:q});if(typeof z==="string")return parseInt(z);return z},deleteUser:async(q)=>{if(G)await G.delete(`active-sessions-${q}`);if(!G||J.session?.storeSessionInDatabase)await F([{field:"userId",value:q}],"session",void 0);await F([{field:"userId",value:q}],"account",void 0),await H([{field:"id",value:q}],"user",void 0)},createSession:async(q,z,D,N)=>{let O=await gY().catch(()=>null),w=O?.headers||O?.request?.headers,{id:E,...C}=D||{},A=Bg(O?.context.options??J,{}),T={ipAddress:O?.request||O?.headers?fW(O?.request||O?.headers,O?.context.options)||"":"",userAgent:w?.get("user-agent")||"",...C,expiresAt:z?z8(86400,"sec"):z8(Z,"sec"),userId:q,token:g8(32),createdAt:new Date,updatedAt:new Date,...A,...N?C:{}};return await W(T,"session",G?{fn:async(I)=>{let R=await G.get(`active-sessions-${q}`),v=[],_=Date.now();if(R)v=D1(R)||[],v=v.filter((m)=>m.expiresAt>_);let y=v.sort((m,t)=>m.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-${q}`,JSON.stringify(y),a);let x=await X.findOne({model:"user",where:[{field:"id",value:q}]}),k=Math.max(Math.floor((T.expiresAt.getTime()-_)/1000),0);if(k>0)await G.set(T.token,JSON.stringify({session:I,user:x}),k);return I},executeMainFn:J.session?.storeSessionInDatabase}:void 0)},findSession:async(q)=>{if(G){let O=await G.get(q);if(!O&&!J.session?.storeSessionInDatabase)return null;if(O){let w=D1(O);if(!w)return null;return{session:j5(Y.options,{...w.session,expiresAt:new Date(w.session.expiresAt),createdAt:new Date(w.session.createdAt),updatedAt:new Date(w.session.updatedAt)}),user:F9(Y.options,{...w.user,createdAt:new Date(w.user.createdAt),updatedAt:new Date(w.user.updatedAt)})}}}let z=await(await K1(X)).findOne({model:"session",where:[{value:q,field:"token"}],join:{user:!0}});if(!z)return null;let{user:D,...N}=z;if(!D)return null;return{session:j5(Y.options,N),user:F9(Y.options,D)}},findSessions:async(q)=>{if(G){let D=[];for(let N of q){let O=await G.get(N);if(O){let w=D1(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 z=await(await K1(X)).findMany({model:"session",where:[{field:"token",value:q,operator:"in"}],join:{user:!0}});if(!z.length)return[];if(z.some((D)=>!D.user))return[];return z.map((D)=>{let{user:N,...O}=D;return{session:O,user:N}})},updateSession:async(q,z)=>{return await K(z,[{field:"token",value:q}],"session",G?{async fn(D){let N=await G.get(q),O=null;if(N){let w=D1(N);if(!w)return null;return O={...w.session,...D},O}else return null},executeMainFn:J.session?.storeSessionInDatabase}:void 0)},deleteSession:async(q)=>{if(G){let z=await G.get(q);if(z){let{session:D}=D1(z)??{};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=D1(O)||[],E=Date.now(),C=w.filter((T)=>T.expiresAt>E&&T.token!==q),A=C.sort((T,I)=>T.expiresAt-I.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(q),!J.session?.storeSessionInDatabase||Y.options.session?.preserveSessionInDatabase)return}await(await K1(X)).delete({model:"session",where:[{field:"token",value:q}]})},deleteAccounts:async(q)=>{await F([{field:"userId",value:q}],"account",void 0)},deleteAccount:async(q)=>{await H([{field:"id",value:q}],"account",void 0)},deleteSessions:async(q)=>{if(G){if(typeof q==="string"){let z=await G.get(`active-sessions-${q}`),D=z?D1(z):[];if(!D)return;for(let N of D)await G.delete(N.token)}else for(let z of q)if(await G.get(z))await G.delete(z);if(!J.session?.storeSessionInDatabase||Y.options.session?.preserveSessionInDatabase)return}await F([{field:Array.isArray(q)?"token":"userId",value:q,operator:Array.isArray(q)?"in":void 0}],"session",void 0)},findOAuthUser:async(q,z,D)=>{let N=await(await K1(X)).findMany({model:"account",where:[{value:z,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:q.toLowerCase(),field:"email"}]});if(O)return{user:O,accounts:[N]};return null}else{let O=await(await K1(X)).findOne({model:"user",where:[{value:q.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(q,z)=>{let D=await(await K1(X)).findOne({model:"user",where:[{value:q.toLowerCase(),field:"email"}],join:{...z?.includeAccounts?{account:!0}:{}}});if(!D)return null;let{account:N,...O}=D;return{user:O,accounts:N??[]}},findUserById:async(q)=>{if(!q)return null;return await(await K1(X)).findOne({model:"user",where:[{field:"id",value:q}]})},linkAccount:async(q)=>{return await W({createdAt:new Date,updatedAt:new Date,...q},"account",void 0)},updateUser:async(q,z)=>{let D=await K(z,[{field:"id",value:q}],"user",void 0);return await V(D),await V(D),D},updateUserByEmail:async(q,z)=>{let D=await K(z,[{field:"email",value:q.toLowerCase()}],"user",void 0);return await V(D),await V(D),D},updatePassword:async(q,z)=>{await $({password:z},[{field:"userId",value:q},{field:"providerId",value:"credential"}],"account",void 0)},findAccounts:async(q)=>{return await(await K1(X)).findMany({model:"account",where:[{field:"userId",value:q}]})},findAccount:async(q)=>{return await(await K1(X)).findOne({model:"account",where:[{field:"accountId",value:q}]})},findAccountByProviderId:async(q,z)=>{return await(await K1(X)).findOne({model:"account",where:[{field:"accountId",value:q},{field:"providerId",value:z}]})},findAccountByUserId:async(q)=>{return await(await K1(X)).findMany({model:"account",where:[{field:"userId",value:q}]})},updateAccount:async(q,z)=>{return await K(z,[{field:"id",value:q}],"account",void 0)},createVerificationValue:async(q)=>{return await W({createdAt:new Date,updatedAt:new Date,...q},"verification",void 0)},findVerificationValue:async(q)=>{let z=await(await K1(X)).findMany({model:"verification",where:[{field:"identifier",value:q}],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 z[0]},deleteVerificationValue:async(q)=>{await(await K1(X)).delete({model:"verification",where:[{field:"id",value:q}]})},deleteVerificationByIdentifier:async(q)=>{await(await K1(X)).delete({model:"verification",where:[{field:"identifier",value:q}]})},updateVerificationValue:async(q,z)=>{return await K(z,[{field:"id",value:q}],"verification",void 0)}}};function DQ0(X){let Y=xY(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 bW4={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 NQ0(X,Y,Q){function J(Z){return Z.toLowerCase().split("(")[0].trim()}if(Y==="string[]"||Y==="number[]")return X.toLowerCase().includes("json");let G=bW4[Q];return(Array.isArray(Y)?G.string.map((Z)=>Z.toLowerCase()):G[Y].map((Z)=>Z.toLowerCase())).includes(J(X))}async function hW4(X){try{let Y=await C5`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 hB(X){let Y=DQ0(X),Q=WF(X.logger),{kysely:J,databaseType:G}=await QM(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 hW4(J),Q.debug(`PostgreSQL migration: Using schema '${Z}' (from search_path)`);try{if(!(await C5`
|
|
410
410
|
SELECT schema_name
|
|
411
411
|
FROM information_schema.schemata
|
|
412
412
|
WHERE schema_name = ${Z}
|