@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/cli.js
CHANGED
|
@@ -1179,9 +1179,9 @@ ${X.stack}`;return Y}if(typeof X==="object"&&X!==null){let Y=X,Q="";if(typeof Y.
|
|
|
1179
1179
|
${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}
|
|
1180
1180
|
|
|
1181
1181
|
Stack trace:
|
|
1182
|
-
${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 yB(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,W)=>{let Z=yB(X,G);try{X.setProp(J,String(W),Z)}finally{Z.dispose?.()}}),J}let Q=X.newObject();for(let[J,G]of Object.entries(Y)){let W=yB(X,G);try{X.setProp(Q,J,W)}finally{W.dispose?.()}}return Q}case"function":{let Q=`__hostFn_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return X.newFunction(Q,(...G)=>{try{let W=G.map(($)=>X.dump($)),Z=Y(...W);if(Z&&typeof Z.then==="function"){let $=X.newPromise();return Z.then((K)=>{try{let H=yB(X,K);$.resolve(H),H.dispose(),X.runtime.executePendingJobs()}catch(H){let F=_B(H),V=X.newString(`Promise resolution error: ${F}`);$.reject(V),V.dispose(),X.runtime.executePendingJobs()}}).catch((K)=>{let H=_B(K),F=X.newString(`Promise rejection: ${H}`);$.reject(F),F.dispose(),X.runtime.executePendingJobs()}),$.handle}return yB(X,Z)}catch(W){let Z=_B(W);return X.newString(`HostFunctionError: ${Z}`)}finally{G.forEach((W)=>W.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 VW1=()=>{};function UW1(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 qW1(X,Y,Q){let J=Date.now(),G=X.resolvePromise(Y);while(!0){UW1(X);let W=await Promise.race([G,wu6(0).then(()=>null)]);if(W!==null)return W;if(Date.now()-J>Q)throw Error(`Timed out after ${Q}ms while awaiting a QuickJS promise`)}}async function tY0({tools:X,code:Y,timeoutMs:Q}){let Z=[];try{let J=await HW1({memoryLimitBytes:33554432,stackSizeBytes:524288});const G=Eh(Z,J.newContext({interruptAfterMs:Q}),0);const W=Eh(Z,f71(G),0);try{let F=G.evalCode(Y,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult(F),q=yB(G,X);G.setProp(G.global,"tools",q);let z=G.runtime.hasPendingJob()?G.unwrapResult(await qW1(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:W.logs};let L=G.callFunction(D,G.undefined,q),w=G.unwrapResult(L),C=await qW1(G,w,Q),T=G.unwrapResult(C);if(G.runtime.hasPendingJob())UW1(G);return{returnValue:G.dump(T),consoleLogs:W.logs}}catch(F){return console.log(F),{error:_B(F),consoleLogs:W.logs}}}catch($){var K=$,H=1}finally{uJ0(Z,K,H)}}var wu6=(X)=>new Promise((Y)=>setTimeout(Y,X));var zW1=S(()=>{FW1();VW1()});var BW1=S(()=>{zW1()});async function Mu6(X,Y){let Q;if(X.tool_selection_mode==="exclusion"){let G=(await Y.storage.connections.list(X.organization_id)).filter((Z)=>Z.status==="active"),W=new Map;for(let Z of X.connections)W.set(Z.connection_id,{selectedTools:Z.selected_tools,selectedResources:Z.selected_resources,selectedPrompts:Z.selected_prompts});Q=[];for(let Z of G){let $=W.get(Z.id);if($===void 0)Q.push({connection:Z,selectedTools:null,selectedResources:null,selectedPrompts:null});else if(($.selectedTools===null||$.selectedTools.length===0)&&($.selectedResources===null||$.selectedResources.length===0)&&($.selectedPrompts===null||$.selectedPrompts.length===0));else Q.push({connection:Z,selectedTools:$.selectedTools,selectedResources:$.selectedResources,selectedPrompts:$.selectedPrompts})}}else{let J=X.connections.map((W)=>W.connection_id),G=[];for(let W of J){let Z=await Y.storage.connections.findById(W);if(Z&&Z.status==="active")G.push(Z)}Q=G.map((W)=>{let Z=X.connections.find(($)=>$.connection_id===W.id);return{connection:W,selectedTools:Z?.selected_tools??null,selectedResources:Z?.selected_resources??null,selectedPrompts:Z?.selected_prompts??null}})}return Q}async function DW1(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 Pu6(X,Y,Q){let J=await kB.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}}),W=new Set,Z=[],$=new Map,K=new Set;for(let F of G){if(F.status!=="fulfilled"||!F.value)continue;let{connectionId:V,connectionTitle:q,tools:z}=F.value;K.add(q);for(let D of z){if(W.has(D.name))continue;W.add(D.name),Z.push({...D,_meta:{connectionId:V,connectionTitle:q}}),$.set(D.name,{connectionId:V,originalName:D.name})}}return{tools:Z,callTool:async(F,V)=>{let q=$.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(K).sort()}}async function bB(X){let Y=_1(X),Q,J="inclusion";if(X.connectionId){let G=await X.storage.virtualMcps.findById(X.connectionId);if(G)Q=await Mu6(G,X),J=G.tool_selection_mode;else Q=await DW1(Y.id,X)}else Q=await DW1(Y.id,X);return Pu6(Q,J,X)}function Au6(X){return X.toLowerCase().split(/[\s_\-./]+/).filter((Y)=>Y.length>=2)}function Tu6(X,Y){let Q=0,J=Y.name.toLowerCase(),G=(Y.description??"").toLowerCase(),W=Y._meta.connectionTitle.toLowerCase();for(let Z of X){if(J===Z)Q+=10;else if(J.includes(Z))Q+=3;if(G.includes(Z))Q+=2;if(W.includes(Z))Q+=1}return Q}function Uf(X,Y,Q){let J=Au6(X);if(J.length===0)return Y.slice(0,Q);return Y.map((G)=>({tool:G,score:Tu6(J,G)})).filter((G)=>G.score>0).sort((G,W)=>W.score-G.score).slice(0,Q).map((G)=>G.tool)}function zf(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 Bf(X,Y,Q){let J=Object.fromEntries(Y.tools.map((G)=>[G.name,async(W)=>Y.callTool(G.name,W??{})]));return tY0({code:X,tools:J,timeoutMs:Q})}function Df(X){return{content:[{type:"text",text:JSON.stringify(X,null,2)}]}}function fB(X){return{content:[{type:"text",text:JSON.stringify(X,null,2)}],isError:!0}}function zA(X){let Y=new Set(Eu6);return X.filter((Q)=>!Y.has(Q.name))}var Eu6;var BA=S(()=>{BW1();Eu6=["CODE_EXECUTION_SEARCH_TOOLS","CODE_EXECUTION_DESCRIBE_TOOLS","CODE_EXECUTION_RUN_CODE"]});var eY0;var NW1=S(()=>{$6();qA();BA();eY0=e0({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:S71,outputSchema:k71,handler:async(X,Y)=>{z1(Y),_1(Y),await Y.access.check();let Q=await bB(Y),J=Uf(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 X90;var OW1=S(()=>{$6();qA();BA();X90=e0({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:v71,outputSchema:_71,handler:async(X,Y)=>{z1(Y),_1(Y),await Y.access.check();let Q=await bB(Y);return zf(X.tools,Q.tools)}})});var Y90;var LW1=S(()=>{$6();qA();BA();Y90=e0({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:y71,outputSchema:b71,handler:async(X,Y)=>{z1(Y),_1(Y),await Y.access.check();let Q=await bB(Y);return await Bf(X.code,Q,X.timeoutMs)}})});var wW1=S(()=>{NW1();OW1();LW1();qA()});var Cu6,Iu6,Q90;var MW1=S(()=>{YA();r0();$6();Zf();g7();Cu6=U.object({data:QG1.describe("Data for the new connection (id is auto-generated if not provided)")}),Iu6=U.object({item:F5.describe("The created connection entity")}),Q90=e0({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",inputSchema:Cu6,outputSchema:Iu6,handler:async(X,Y)=>{z1(Y);let Q=_1(Y);await Y.access.check();let J=d8(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 K=fK(G.connection_url);if(!K)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let H=await Y.storage.virtualMcps.findById(K);if(!H)throw Error(`Virtual MCP not found: ${K}`);if(H.organization_id!==Q.id)throw Error("Virtual MCP does not belong to the current organization");G.connection_url=Xf(K)}let W=await RB({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),Z=W?.length?W:null,$=await Y.storage.connections.create({...G,tools:Z});return await Y.eventBus.publish(Q.id,LZ.SELF(Q.id),{type:"connection.created",data:$}),{item:$}}})});function DA(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)=>DA(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)&&DA(X[G],Y[G]))}return!1}function su6(){return(X)=>{if(!Array.isArray(X))return!0;let Y=[];return X.every((Q)=>{if(Y.some((G)=>DA(Q,G)))return!1;return Y.push(Q),!0})}}function Nf(X,Y){return X.safeParse(Y).success}function bY(X){if(typeof X==="boolean")return X?U.any():U.never();let Y={};for(let G of Vm6)G.apply(Y,X);let Q=[];if(Y.string!==!1)Q.push(Y.string||U.string());if(Y.number!==!1)Q.push(Y.number||U.number());if(Y.boolean!==!1)Q.push(Y.boolean||U.boolean());if(Y.null!==!1)Q.push(Y.null||U.null());if(Y.array!==!1)Q.push(Y.array||U.array(U.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=U.custom((W)=>{return typeof W==="object"&&W!==null&&!Array.isArray(W)},"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=U.never();else if(Q.length===1)J=Q[0];else if(!Object.keys(X).some((W)=>W!=="$schema"&&W!=="title"&&W!=="description"))J=U.any();else J=U.union(Q);for(let G of qm6)J=G.apply(J,X);return J}var Ru6=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||U.number();if(G instanceof U.ZodNumber)X.number=G.int()}}},Su6=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=U.literal(Q);else if(typeof Q==="number")X.number=U.literal(Q);else if(typeof Q==="boolean")X.boolean=U.literal(Q);else if(Q===null)X.null=U.null();else if(Array.isArray(Q))X.array=void 0;else if(typeof Q==="object")X.object=void 0}},ku6=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?U.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 U.literal(X[0]);if(Y==="string")return U.enum(X);if(Y==="number"){let[Q,J,...G]=X;return U.union([U.literal(Q),U.literal(J),...G.map((W)=>U.literal(W))])}if(Y==="boolean")return U.union([U.literal(!0),U.literal(!1)]);return!1}},vu6=class{apply(X,Y){let Q=Y;if(Q.type==="string"&&Q.format==="binary"&&Q.contentEncoding==="binary"){let J=U.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}}},_u6=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=U.string()}}},yu6=class{apply(X,Y){let Q=Y;if(Q.minLength===void 0)return;if(X.string!==!1){let J=X.string||U.string();if(J instanceof U.ZodString)X.string=J.refine((G)=>{return Array.from(G).length>=Q.minLength},{message:`String must be at least ${Q.minLength} characters long`})}}},bu6=class{apply(X,Y){let Q=Y;if(Q.maxLength===void 0)return;if(X.string!==!1){let J=X.string||U.string();if(J instanceof U.ZodString)X.string=J.refine((G)=>{return Array.from(G).length<=Q.maxLength},{message:`String must be at most ${Q.maxLength} characters long`})}}},fu6=class{apply(X,Y){let Q=Y;if(!Q.pattern)return;if(X.string!==!1){let J=X.string||U.string();if(J instanceof U.ZodString){let G=new RegExp(Q.pattern);X.string=J.regex(G)}}}},hu6=class{apply(X,Y){let Q=Y;if(Q.minimum===void 0)return;if(X.number!==!1){let J=X.number||U.number();if(J instanceof U.ZodNumber)X.number=J.min(Q.minimum)}}},xu6=class{apply(X,Y){let Q=Y;if(Q.maximum===void 0)return;if(X.number!==!1){let J=X.number||U.number();if(J instanceof U.ZodNumber)X.number=J.max(Q.maximum)}}},gu6=class{apply(X,Y){let Q=Y;if(Q.exclusiveMinimum===void 0)return;if(X.number!==!1){let J=X.number||U.number();if(J instanceof U.ZodNumber)if(typeof Q.exclusiveMinimum==="number")X.number=J.gt(Q.exclusiveMinimum);else X.number=!1}}},uu6=class{apply(X,Y){let Q=Y;if(Q.exclusiveMaximum===void 0)return;if(X.number!==!1){let J=X.number||U.number();if(J instanceof U.ZodNumber)if(typeof Q.exclusiveMaximum==="number")X.number=J.lt(Q.exclusiveMaximum);else X.number=!1}}},mu6=class{apply(X,Y){let Q=Y;if(Q.multipleOf===void 0)return;if(X.number!==!1){let J=X.number||U.number();if(J instanceof U.ZodNumber)X.number=J.refine((G)=>{if(Q.multipleOf===0)return!1;let W=G/Q.multipleOf,Z=Math.round(W),$=Math.min(Math.abs(G)*Number.EPSILON*10,Math.abs(Q.multipleOf)*Number.EPSILON*10);return Math.abs(W-Z)<=$/Math.abs(Q.multipleOf)},{message:`Must be a multiple of ${Q.multipleOf}`})}}},lu6=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=U.array(U.any())}}},du6=class{apply(X,Y){let Q=Y;if(Q.minItems===void 0)return;if(X.array!==!1)X.array=(X.array||U.array(U.any())).min(Q.minItems)}},pu6=class{apply(X,Y){let Q=Y;if(Q.maxItems===void 0)return;if(X.array!==!1)X.array=(X.array||U.array(U.any())).max(Q.maxItems)}},cu6=class{apply(X,Y){let Q=Y;if(X.array===!1)return;if(Array.isArray(Q.items))X.array=X.array||U.array(U.any());else if(Q.items&&typeof Q.items!=="boolean"&&!Q.prefixItems){let J=bY(Q.items),G=U.array(J);if(X.array&&X.array instanceof U.ZodArray){let W=X.array._def;if(W.checks)W.checks.forEach((Z)=>{if(Z._zod&&Z._zod.def){let $=Z._zod.def;if($.check==="min_length"&&$.minimum!==void 0)G=G.min($.minimum);else if($.check==="max_length"&&$.maximum!==void 0)G=G.max($.maximum)}})}X.array=G}else if(typeof Q.items==="boolean"&&Q.items===!1)if(!Q.prefixItems)X.array=U.array(U.any()).max(0);else X.array=X.array||U.array(U.any());else if(typeof Q.items==="boolean"&&Q.items===!0)X.array=X.array||U.array(U.any());else if(Q.prefixItems)X.array=X.array||U.array(U.any())}},nu6=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((W)=>bY(W)),G;if(J.length===0)G=U.tuple([]);else G=U.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}},iu6=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||U.object({}).passthrough()}},au6=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=U.object({}).passthrough()}}},ru6=class{apply(X,Y){let Q=Y;if(Q.maxProperties===void 0)return;if(X.object!==!1){let J=X.object||U.object({}).passthrough();X.object=J.refine((G)=>Object.keys(G).length<=Q.maxProperties,{message:`Object must have at most ${Q.maxProperties} properties`})}}},ou6=class{apply(X,Y){let Q=Y;if(Q.minProperties===void 0)return;if(X.object!==!1){let J=X.object||U.object({}).passthrough();X.object=J.refine((G)=>Object.keys(G).length>=Q.minProperties,{message:`Object must have at least ${Q.minProperties} properties`})}}},tu6=class{apply(X,Y){if(!Y.not)return X;let Q=bY(Y.not);return X.refine((J)=>!Nf(Q,J),{message:"Value must not match the 'not' schema"})}},eu6=class{apply(X,Y){if(Y.uniqueItems!==!0)return X;return X.refine(su6(),{message:"Array items must be unique"})}},Xm6=class{apply(X,Y){if(!Y.allOf||Y.allOf.length===0)return X;return Y.allOf.map((J)=>bY(J)).reduce((J,G)=>U.intersection(J,G),X)}},Ym6=class{apply(X,Y){if(!Y.anyOf||Y.anyOf.length===0)return X;let Q=Y.anyOf.length===1?bY(Y.anyOf[0]):U.union([bY(Y.anyOf[0]),bY(Y.anyOf[1]),...Y.anyOf.slice(2).map((J)=>bY(J))]);return U.intersection(X,Q)}},Qm6=class{apply(X,Y){if(!Y.oneOf||Y.oneOf.length===0)return X;let Q=Y.oneOf.map((J)=>bY(J));return X.refine((J)=>{let G=0;for(let W of Q)if(W.safeParse(J).success){if(G++,G>1)return!1}return G===1},{message:"Value must match exactly one of the oneOf schemas"})}},Jm6=class{apply(X,Y){let Q=Y;if(Q.prefixItems&&Array.isArray(Q.prefixItems)){let G=Q.prefixItems.map((W)=>bY(W));return X.refine((W)=>{if(!Array.isArray(W))return!0;for(let Z=0;Z<Math.min(W.length,G.length);Z++)if(!Nf(G[Z],W[Z]))return!1;if(W.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 Z=bY(Q.items);for(let $=G.length;$<W.length;$++)if(!Nf(Z,W[$]))return!1}}return!0},{message:"Array does not match prefixItems schema"})}return X}},Gm6=class{apply(X,Y){let Q=Y;if(!Q.properties&&!Q.required&&Q.additionalProperties!==!1)return X;if(X instanceof U.ZodObject||X instanceof U.ZodRecord){let J={};if(Q.properties){for(let[G,W]of Object.entries(Q.properties))if(W!==void 0)J[G]=bY(W)}if(Q.required&&Array.isArray(Q.required)){let G=new Set(Q.required);for(let W of Object.keys(J))if(!G.has(W))J[W]=J[W].optional()}else for(let G of Object.keys(J))J[G]=J[G].optional();if(Q.additionalProperties===!1)return U.object(J);else return U.object(J).passthrough()}return X.refine((J)=>{if(typeof J!=="object"||J===null||Array.isArray(J))return!0;if(Q.properties){for(let[G,W]of Object.entries(Q.properties))if(W!==void 0){if(Object.getOwnPropertyDescriptor(J,G)!==void 0){if(!bY(W).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 W in J)if(!G.has(W))return!1}return!0},{message:"Object constraints validation failed"})}},Wm6=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)=>DA(J,G))},{message:"Value must match one of the enum values"})}},Zm6=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)=>DA(J,Q),{message:"Value must equal the const value"})}},$m6=class{apply(X,Y){if(Y.description)X=X.describe(Y.description);return X}},Km6=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 U.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))}},Hm6=class{apply(X,Y){var Q;let J=Y;if(J.contains===void 0)return X;let G=bY(J.contains),W=(Q=J.minContains)!=null?Q:1,Z=J.maxContains;return X.refine(($)=>{if(!Array.isArray($))return!0;let K=0;for(let H of $)if(Nf(G,H))K++;if(K<W)return!1;if(Z!==void 0&&K>Z)return!1;return!0},{message:"Array must contain required items matching the schema"})}},Fm6=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)}},Vm6,qm6;var PW1=S(()=>{r6();r6();r6();r6();r6();r6();r6();r6();r6();r6();r6();r6();r6();r6();Vm6=[new Su6,new ku6,new Ru6,new vu6,new _u6,new lu6,new au6,new yu6,new bu6,new fu6,new hu6,new xu6,new gu6,new uu6,new mu6,new nu6,new du6,new pu6,new cu6,new ru6,new ou6,new iu6],qm6=[new Km6,new Wm6,new Zm6,new Xm6,new Ym6,new Qm6,new Jm6,new Gm6,new Hm6,new tu6,new eu6,new Fm6,new $m6]});class J90{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,Um6),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=ZJ.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 Um6="mcp";var AW1=S(()=>{RX()});function zm6(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 G90;var TW1=S(()=>{LB();G90=class G90 extends x7{constructor(X,Y){super(X,Y)}send(X,Y){let Q=zm6(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 EW1,jW1=async(X,Y,Q)=>{let J=Bm6(X.connection,Y,Q);if(!J)throw Error("Unknown MCP connection type");let G=new EW1({name:X?.name??"MCP Client",version:"1.0.0"});return await G.connect(J),{client:G,callStreamableTool:(W,Z,$)=>{if(X.connection.type!=="HTTP")throw Error("HTTP connection required");let K=new Headers(Q);if(!K.has("Authorization"))K.set("Authorization",`Bearer ${X.connection.token}`);for(let[V,q]of Object.entries(X.connection.headers??{}))K.set(V,q);let H=new URL(X.connection.url),F=H.pathname.replace(/\/+$/,"")||"/";return H.pathname=`${F}/call-tool/${encodeURIComponent(W)}`,fetch(H.href,{method:"POST",redirect:"manual",body:JSON.stringify(Z),headers:K,signal:$})}}},Bm6=(X,Y,Q)=>{if(X.type==="Websocket")return new J90(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 W={requestInit:{headers:G,signal:Y}};if(X.token)W.eventSourceInit={fetch:(Z,$)=>{return fetch(Z,{...$,headers:{...G,Accept:"text/event-stream"},signal:Y})}};return new gF(new URL(X.url),W)}return new G90(new URL(X.url),{requestInit:{headers:G,signal:Y,credentials:"include"}})};var CW1=S(()=>{yF();Jf();AW1();RX();TW1();EW1=class EW1 extends PQ{constructor(X,Y){super(X,Y)}async listTools(X,Y){return await this.request({method:"tools/list",params:X},EP,Y)}}});function RW1(X){let Y=(Q)=>{if("connection"in X)return jW1({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 $;async function G(K,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),K,V?.signal??void 0);let{structuredContent:L,isError:w,content:C}=await D.callTool({name:String(F),arguments:K},void 0,{signal:V?.signal??void 0});if(w){let T=C?.[0]?.text,A=typeof T==="string"?Dm6(T):null,P=A?.code&&typeof X?.getErrorByStatusCode==="function"?X.getErrorByStatusCode(A.code,A.message,A.traceId):null;if(P)throw P;throw Error(`Tool ${String(F)} returned an error: ${JSON.stringify(L??C)}`)}return L}async function W(){let{client:K}=await Y(),{tools:H}=await K.listTools();return H}async function Z(){if(!("connection"in X))return W();let K=X.connection,H=JSON.stringify(K);try{if(!Of.has(H))Of.set(H,W());return await Of.get(H)}catch(F){console.error("Failed to list tools",F),Of.delete(H);return}}async function $(){return(await Z()??[]).map((H)=>IW1(H,G))}return G.asTool=async()=>{let H=(await Z()??[]).find((F)=>F.name===J);if(!H)throw Error(`Tool ${J} not found`);return IW1(H,G)},G}})}var Dm6=(X)=>{try{return JSON.parse(X)}catch{return X}},Of,IW1=(X,Y)=>{return{...X,id:X.name,inputSchema:X.inputSchema?bY(X.inputSchema):void 0,outputSchema:X.outputSchema?bY(X.outputSchema):void 0,execute:(Q)=>{return Y(Q.context,X.name)}}};var SW1=S(()=>{PW1();CW1();Of=new Map});function Lf(X){return RW1(X)}var Ea4;var kW1=S(()=>{SW1();Ea4=new Proxy({},{get(X,Y){if(Y==="toJSON")return null;if(Y==="forConnection")return(Q)=>Lf({connection:Q});return global[Y]}})});function wf(X){return{isImplementedBy:(Y)=>{for(let Q of X){let J=typeof Q.name==="string"?new RegExp(`^${Q.name}$`):Q.name,G=Y.find((W)=>J.test(W.name));if(!G&&Q.opt)continue;if(!G)return!1}return!0}}}var cF=(X)=>{return{...wf(X),forClient:(Y)=>{return Lf({client:Y,streamable:X.reduce((Q,J)=>{return Q[J.name]=J.streamable===!0,Q},{})})},forConnection:(Y)=>{return Lf({connection:Y,streamable:X.reduce((Q,J)=>{return Q[J.name]=J.streamable===!0,Q},{})})}}};var NA=S(()=>{kW1()});var W90,Sa4;var vW1=S(()=>{XP();W90=w6(eM(),1),Sa4=W90.createContext(null)});function iF(X){return U.object({items:U.array(X).describe("Array of collection items"),totalCount:U.number().int().min(0).optional().describe("Total number of matching items (if available)"),hasMore:U.boolean().optional().describe("Whether there are more items available")})}function LA(X){return U.object({item:X.nullable().describe("The retrieved item, or null if not found")})}function Lm6(X){return U.object({data:X.partial().describe("Data for the new entity (id may be auto-generated)")})}function wm6(X){return U.object({item:X.describe("The created entity with generated id")})}function Mm6(X){return U.object({id:U.string().describe("ID of the entity to update"),data:X.partial().describe("Partial entity data to update")})}function Pm6(X){return U.object({item:X.describe("The updated entity")})}function MA(X){return U.object({item:X.describe("The deleted entity")})}function xB(X,Y,Q){let J=X.toUpperCase(),G=Q?.readOnly??!1,W=[{name:`COLLECTION_${J}_LIST`,inputSchema:nF,outputSchema:iF(Y)},{name:`COLLECTION_${J}_GET`,inputSchema:OA,outputSchema:LA(Y)}];if(!G)W.push({name:`COLLECTION_${J}_CREATE`,inputSchema:Lm6(Y),outputSchema:wm6(Y),opt:!0},{name:`COLLECTION_${J}_UPDATE`,inputSchema:Mm6(Y),outputSchema:Pm6(Y),opt:!0},{name:`COLLECTION_${J}_DELETE`,inputSchema:wA,outputSchema:MA(Y),opt:!0});return W}var hB,Nm6,_W1,Om6,nF,OA,wA;var GG=S(()=>{r0();hB=U.object({id:U.string().describe("Unique identifier for the entity"),title:U.string().describe("Human-readable title for the entity"),description:U.string().nullish().describe("Description of the entity"),created_at:U.string().datetime(),updated_at:U.string().datetime(),created_by:U.string().optional(),updated_by:U.string().optional()}),Nm6=U.object({field:U.array(U.string()),operator:U.enum(["eq","gt","gte","lt","lte","in","like","contains"]),value:U.unknown()}),_W1=U.lazy(()=>U.union([Nm6,U.object({operator:U.enum(["and","or","not"]),conditions:U.array(_W1)})])),Om6=U.object({field:U.array(U.string()),direction:U.enum(["asc","desc"]),nulls:U.enum(["first","last"]).optional()}),nF=U.object({where:_W1.optional().describe("Filter expression"),orderBy:U.array(Om6).optional().describe("Sort expressions"),limit:U.number().int().min(1).max(1000).optional().describe("Maximum number of items to return"),offset:U.number().int().min(0).optional().describe("Number of items to skip")});OA=U.object({id:U.string().describe("ID of the entity to retrieve")});wA=U.object({id:U.string().describe("ID of the entity to delete")})});var Am6,yW1,ha4;var bW1=S(()=>{r0();GG();Am6=U.object({id:U.string(),name:U.string(),description:U.string().optional(),inputSchema:U.record(U.string(),U.unknown()),outputSchema:U.record(U.string(),U.unknown()).optional()}),yW1=hB.extend({_meta:U.object({"io.decocms":U.object({id:U.string(),verified:U.boolean(),scopeName:U.string(),appName:U.string(),friendlyName:U.string().nullable().optional(),metadata:U.record(U.string(),U.unknown()).nullable().optional(),publishedAt:U.string().datetime().optional(),updatedAt:U.string().datetime().optional(),tools:U.array(Am6).nullable().optional().describe("Available tools exposed by this app")}).optional()}).optional(),server:U.object({$schema:U.string().optional(),_meta:U.record(U.string(),U.unknown()).optional(),name:U.string().describe("The server name (scope/app)"),title:U.string().optional().describe("User-friendly title"),description:U.string().optional().describe("Server description"),icons:U.array(U.object({src:U.string(),mimeType:U.string().optional(),sizes:U.array(U.string()).optional(),theme:U.enum(["light","dark"]).optional()})).optional(),remotes:U.array(U.object({type:U.enum(["http","stdio","sse"]),url:U.string().optional(),headers:U.array(U.unknown()).optional()})).optional(),packages:U.array(U.unknown()).optional(),repository:U.object({url:U.string(),source:U.string().optional(),subfolder:U.string().optional()}).optional(),version:U.string().optional(),websiteUrl:U.string().optional()})}),ha4=xB("registry_app",yW1,{readOnly:!0})});var fW1,hW1,xW1,gW1,uW1,Z90;var mW1=S(()=>{r0();NA();fW1=U.object({specversion:U.literal("1.0").describe("CloudEvents specification version"),id:U.string().describe("Unique identifier for this event (UUID recommended)"),source:U.string().describe("Connection ID of the event publisher"),type:U.string().describe("Event type (e.g., 'order.created', 'user.signup')"),time:U.string().datetime().optional().describe("Timestamp of when the event occurred (ISO 8601)"),subject:U.string().optional().describe("Subject/resource identifier (e.g., order ID, user ID)"),datacontenttype:U.string().optional().default("application/json").describe("Content type of the data attribute"),dataschema:U.string().url().optional().describe("URI to the schema for the data attribute"),data:U.unknown().optional().describe("Event payload (any JSON value)")}),hW1=U.object({events:U.array(fW1).min(1).describe("Batch of CloudEvents to process")}),xW1=U.object({success:U.boolean().optional().describe("Whether this event was processed successfully"),error:U.string().optional().describe("Error message for this event"),retryAfter:U.number().int().positive().optional().describe("Re-deliver this event after this many ms")}),gW1=U.object({success:U.boolean().optional().describe("Batch success - applies to events not in results"),error:U.string().optional().describe("Batch error message - applies to events not in results"),processedCount:U.number().int().min(0).optional().describe("Number of events successfully processed"),retryAfter:U.number().int().positive().optional().describe("Batch retryAfter - applies to events not in results"),results:U.record(U.string(),xW1).optional().describe("Per-event results keyed by event ID")}),uW1=[{name:"ON_EVENTS",inputSchema:hW1,outputSchema:gW1}],Z90=cF(uW1)});var PA,AA,TA,EA,lW1,dW1,jA,CA,IA,RA,SA,kA,vA,_A,pW1,Tm6;var cW1=S(()=>{r0();NA();PA=U.object({type:U.string().min(1).max(255).describe("Event type identifier"),subject:U.string().max(255).optional().describe("Subject/resource identifier (e.g., order ID)"),data:U.unknown().optional().describe("Event payload"),deliverAt:U.string().datetime().optional().describe("Scheduled delivery time (ISO 8601). Omit for immediate delivery."),cron:U.string().max(100).optional().describe("Cron expression for recurring delivery. Use EVENT_CANCEL to stop.")}),AA=U.object({id:U.string().describe("Unique event ID"),type:U.string().describe("Event type"),source:U.string().describe("Source connection ID"),time:U.string().describe("Event timestamp")}),TA=U.object({eventType:U.string().min(1).max(255).describe("Event type to subscribe to"),publisher:U.string().optional().describe("Filter events by publisher connection ID"),filter:U.string().max(1000).optional().describe("JSONPath filter expression on event data")}),EA=U.object({subscription:U.object({id:U.string().describe("Subscription ID"),connectionId:U.string().describe("Subscriber connection ID"),eventType:U.string().describe("Event type pattern"),publisher:U.string().nullable().describe("Publisher connection filter"),filter:U.string().nullable().describe("JSONPath filter expression"),enabled:U.boolean().describe("Whether subscription is enabled"),createdAt:U.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:U.string().datetime().describe("Updated timestamp (ISO 8601)")})}),lW1=U.object({eventType:U.string().min(1).max(255).describe("Event type to subscribe to"),publisher:U.string().optional().describe("Filter events by publisher connection ID"),filter:U.string().max(1000).optional().describe("JSONPath filter expression on event data")}),dW1=U.object({id:U.string().describe("Subscription ID"),connectionId:U.string().describe("Subscriber connection ID"),eventType:U.string().describe("Event type pattern"),publisher:U.string().nullable().describe("Publisher connection filter"),filter:U.string().nullable().describe("JSONPath filter expression"),enabled:U.boolean().describe("Whether subscription is enabled"),createdAt:U.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:U.string().datetime().describe("Updated timestamp (ISO 8601)")}),jA=U.object({subscriptions:U.array(lW1).describe("Desired subscriptions - system will create/update/delete to match")}),CA=U.object({created:U.number().int().min(0).describe("Number of subscriptions created"),updated:U.number().int().min(0).describe("Number of subscriptions with filter updated"),deleted:U.number().int().min(0).describe("Number of subscriptions removed"),unchanged:U.number().int().min(0).describe("Number of subscriptions unchanged"),subscriptions:U.array(dW1).describe("Current subscriptions after sync")}),IA=U.object({subscriptionId:U.string().describe("Subscription ID to remove")}),RA=U.object({success:U.boolean().describe("Whether unsubscribe was successful"),subscriptionId:U.string().describe("Subscription ID that was removed")}),SA=U.object({eventId:U.string().describe("Event ID to cancel")}),kA=U.object({success:U.boolean().describe("Whether cancellation was successful"),eventId:U.string().describe("Event ID that was cancelled")}),vA=U.object({eventId:U.string().describe("Event ID to acknowledge")}),_A=U.object({success:U.boolean().describe("Whether ACK was successful"),eventId:U.string().describe("Event ID that was acknowledged")}),pW1=[{name:"EVENT_PUBLISH",inputSchema:PA,outputSchema:AA},{name:"EVENT_SUBSCRIBE",inputSchema:TA,outputSchema:EA},{name:"EVENT_UNSUBSCRIBE",inputSchema:IA,outputSchema:RA},{name:"EVENT_CANCEL",inputSchema:SA,outputSchema:kA},{name:"EVENT_ACK",inputSchema:vA,outputSchema:_A},{name:"EVENT_SYNC_SUBSCRIPTIONS",inputSchema:jA,outputSchema:CA}],Tm6=cF(pW1)});var na4,ia4,aa4,ra4,oa4,sa4,ta4,ea4,Xr4,Yr4,Qr4,Jr4;var nW1=S(()=>{r0();na4=U.object({prefix:U.string().optional().describe("Filter objects by prefix (e.g., 'folder/' for folder contents)"),maxKeys:U.number().optional().default(1000).describe("Maximum number of keys to return (default: 1000)"),continuationToken:U.string().optional().describe("Token for pagination from previous response"),delimiter:U.string().optional().describe("Delimiter for grouping keys (typically '/'). When set, commonPrefixes returns folder paths.")}),ia4=U.object({objects:U.array(U.object({key:U.string().describe("Object key/path"),size:U.number().describe("Object size in bytes"),lastModified:U.string().describe("Last modified timestamp"),etag:U.string().describe("Entity tag for the object")})),nextContinuationToken:U.string().optional().describe("Token for fetching next page of results"),isTruncated:U.boolean().describe("Whether there are more results available"),commonPrefixes:U.array(U.string()).optional().describe("Folder paths when delimiter is used (e.g., ['photos/2024/', 'photos/2025/'])")}),aa4=U.object({key:U.string().describe("Object key/path to get metadata for")}),ra4=U.object({contentType:U.string().optional().describe("MIME type of the object"),contentLength:U.number().describe("Size of the object in bytes"),lastModified:U.string().describe("Last modified timestamp"),etag:U.string().describe("Entity tag for the object"),metadata:U.record(U.string(),U.string()).optional().describe("Custom metadata key-value pairs")}),oa4=U.object({key:U.string().describe("Object key/path to generate URL for"),expiresIn:U.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)")}),sa4=U.object({url:U.string().describe("Presigned URL for downloading the object"),expiresIn:U.number().describe("Expiration time in seconds that was used")}),ta4=U.object({key:U.string().describe("Object key/path for the upload"),expiresIn:U.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)"),contentType:U.string().optional().describe("MIME type for the object being uploaded")}),ea4=U.object({url:U.string().describe("Presigned URL for uploading the object"),expiresIn:U.number().describe("Expiration time in seconds that was used")}),Xr4=U.object({key:U.string().describe("Object key/path to delete")}),Yr4=U.object({success:U.boolean().describe("Whether the deletion was successful"),key:U.string().describe("The key that was deleted")}),Qr4=U.object({keys:U.array(U.string()).max(1000).describe("Array of object keys/paths to delete (max 1000)")}),Jr4=U.object({deleted:U.array(U.string()).describe("Array of successfully deleted keys"),errors:U.array(U.object({key:U.string(),message:U.string()})).describe("Array of errors for failed deletions")})});var Mf=S(()=>{NA();vW1();bW1();mW1();cW1();nW1()});var Em6,jm6,iW1;var aW1=S(()=>{r0();GG();Em6=hB.extend({avatar:U.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:U.string().describe("System prompt that defines the assistant's behavior"),virtual_mcp_id:U.string().describe("Virtual MCP ID to use for this assistant"),model:U.object({id:U.string().describe("Model ID"),connectionId:U.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),jm6=xB("assistant",Em6),iW1=[...jm6]});var yA,AZ,oW1,Cm6,Im6,sW1,Rm6,Sm6,km6,vm6,_m6,ym6,tW1,bm6,fm6,hm6,xm6,gm6,um6,mm6,lm6,dm6,pm6,Ar4,cm6,Tr4,rW1,nm6,im6,$90,Pf;var Af=S(()=>{r0();NA();GG();yA=U.lazy(()=>U.union([U.null(),U.string(),U.number(),U.boolean(),U.record(U.string(),yA),U.array(yA)])),AZ=U.record(U.string(),U.record(U.string(),yA)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),oW1=U.object({type:U.literal("text"),text:U.string().describe("The text content"),providerOptions:AZ}),Cm6=U.object({type:U.literal("text"),text:U.string().describe("The text content"),providerMetadata:U.any().optional().describe("Additional provider-specific metadata")}),Im6=U.string().describe("File data as URL string"),sW1=U.object({type:U.literal("file"),filename:U.string().optional().describe("Optional filename of the file"),data:Im6,mediaType:U.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:AZ}),Rm6=U.object({type:U.literal("file"),mediaType:U.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),data:U.string().describe("Generated file data as base64 encoded string")}),Sm6=U.object({type:U.literal("reasoning"),text:U.string().describe("The reasoning text"),providerOptions:AZ}),km6=U.object({type:U.literal("reasoning"),text:U.string().describe("The reasoning text"),providerMetadata:U.any().optional().describe("Additional provider-specific metadata")}),vm6=U.object({type:U.literal("tool-call"),toolCallId:U.string().describe("ID of the tool call, used to match with tool result"),toolName:U.string().describe("Name of the tool being called"),input:U.string().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:U.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:AZ}),_m6=U.object({type:U.literal("tool-call"),toolCallId:U.string().describe("ID of the tool call"),toolName:U.string().describe("Name of the tool being called"),input:U.string().describe("Stringified JSON object with the tool call arguments"),providerExecuted:U.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerMetadata:U.any().optional().describe("Additional provider-specific metadata")}),ym6=U.union([U.object({type:U.literal("text"),value:U.string()}),U.object({type:U.literal("json"),value:yA}),U.object({type:U.literal("error-text"),value:U.string()}),U.object({type:U.literal("error-json"),value:yA}),U.object({type:U.literal("content"),value:U.array(U.union([U.object({type:U.literal("text"),text:U.string().describe("Text content")}),U.object({type:U.literal("media"),data:U.string().describe("Base-64 encoded media data"),mediaType:U.string().describe("IANA media type")})]))})]),tW1=U.object({type:U.literal("tool-result"),toolCallId:U.string().describe("ID of the tool call that this result is associated with"),toolName:U.string().describe("Name of the tool that generated this result"),output:ym6.describe("Result of the tool call"),result:U.unknown().describe("Unknown result of the tool call"),providerOptions:AZ}),bm6=U.object({type:U.literal("tool-result"),toolCallId:U.string().describe("ID of the tool call that this result is associated with"),toolName:U.string().describe("Name of the tool that generated this result"),result:U.any().describe("Result of the tool call (JSON-serializable)"),isError:U.boolean().optional().describe("Whether the result is an error or error message"),providerExecuted:U.boolean().optional().describe("Whether the tool result was generated by the provider"),providerMetadata:U.any().optional().describe("Additional provider-specific metadata")}),fm6=U.union([U.object({type:U.literal("source"),sourceType:U.literal("url"),id:U.string().describe("The ID of the source"),url:U.string().describe("The URL of the source"),title:U.string().optional().describe("The title of the source"),providerMetadata:U.any().optional().describe("Additional provider-specific metadata")}),U.object({type:U.literal("source"),sourceType:U.literal("document"),id:U.string().describe("The ID of the source"),mediaType:U.string().describe("IANA media type of the document (e.g., application/pdf)"),title:U.string().describe("The title of the document"),filename:U.string().optional().describe("Optional filename of the document"),providerMetadata:U.any().optional().describe("Additional provider-specific metadata")})]),hm6=U.object({role:U.literal("system"),content:U.string().describe("System message content"),providerOptions:AZ}),xm6=U.object({role:U.literal("user"),content:U.array(U.union([oW1,sW1])).describe("User message content parts (text or file)"),providerOptions:AZ}),gm6=U.object({role:U.literal("assistant"),content:U.array(U.union([oW1,sW1,Sm6,vm6,tW1])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:AZ}),um6=U.object({role:U.literal("tool"),content:U.array(tW1).describe("Tool message content (tool results)"),providerOptions:AZ}),mm6=U.union([hm6,xm6,gm6,um6]),lm6=U.array(mm6).describe("A list of messages forming the prompt"),dm6=U.object({prompt:lm6.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:U.number().optional().describe("Maximum number of tokens to generate"),temperature:U.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:U.number().optional().describe("Nucleus sampling parameter"),topK:U.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:U.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:U.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:U.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:U.array(U.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:U.union([U.object({type:U.literal("text")}),U.object({type:U.literal("json"),schema:U.any().optional().describe("JSON schema that the generated output should conform to"),name:U.string().optional().describe("Name of output that should be generated"),description:U.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:U.array(U.any()).optional().describe("The tools that are available for the model"),toolChoice:U.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:U.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:U.any().optional().describe("Abort signal for cancelling the operation"),providerOptions:U.any().optional().describe("Additional provider-specific options")}),pm6=U.object({content:U.array(U.union([Cm6,Rm6,km6,_m6,bm6,fm6])).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:U.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:U.looseObject({inputTokens:U.number().optional(),outputTokens:U.number().optional(),totalTokens:U.number().optional(),reasoningTokens:U.number().optional()}).describe("Usage information for the language model call"),providerMetadata:U.any().optional().describe("Additional provider-specific metadata"),request:U.object({body:U.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:U.object({id:U.string().optional().describe("ID for the generated response"),timestamp:U.iso.datetime().optional().describe("Timestamp for the start of the generated response"),modelId:U.string().optional().describe("The ID of the response model that was used"),headers:U.record(U.string(),U.string()).optional().describe("Response headers"),body:U.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:U.array(U.any()).describe("Warnings for the call, e.g. unsupported settings")}),Ar4=U.object({stream:U.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:U.object({body:U.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:U.object({headers:U.record(U.string(),U.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),cm6=U.object({supportedUrls:U.record(U.string(),U.array(U.string())).describe("Supported URL patterns by media type for the provider")}),Tr4=U.object({modelId:U.string().describe("The ID of the model"),logo:U.string().nullable(),description:U.string().nullable(),capabilities:U.array(U.string()),limits:U.object({contextWindow:U.number(),maxOutputTokens:U.number()}).nullable(),costs:U.object({input:U.number(),output:U.number()}).nullable(),provider:U.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),rW1=U.object({modelId:U.string().describe("The ID of the model"),callOptions:dm6}),nm6=hB.extend({logo:U.string().nullable(),description:U.string().nullable(),capabilities:U.array(U.string()),limits:U.object({contextWindow:U.number(),maxOutputTokens:U.number()}).nullable(),costs:U.object({input:U.number(),output:U.number()}).nullable(),provider:U.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),im6=xB("llm",nm6,{readOnly:!0}),$90=[{name:"LLM_METADATA",inputSchema:U.object({modelId:U.string().describe("The ID of the model")}),outputSchema:cm6},{name:"LLM_DO_STREAM",inputSchema:rW1,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:rW1,outputSchema:pm6},...im6],Pf=cF($90)});function rm6(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 uK(X){return typeof X==="string"||typeof X==="number"}function Tf(X,Y){if("conditions"in Y){let{operator:$,conditions:K}=Y;switch($){case"and":return K.every((H)=>Tf(X,H));case"or":return K.some((H)=>Tf(X,H));case"not":return!K.every((H)=>Tf(X,H));default:return!0}}let{field:Q,operator:J,value:G}=Y,W=Q.join("."),Z=K90(X,W);switch(J){case"eq":return Z===G;case"gt":return uK(Z)&&uK(G)&&Z>G;case"gte":return uK(Z)&&uK(G)&&Z>=G;case"lt":return uK(Z)&&uK(G)&&Z<G;case"lte":return uK(Z)&&uK(G)&&Z<=G;case"in":return Array.isArray(G)&&G.includes(Z);case"like":if(typeof Z!=="string"||typeof G!=="string")return!1;if(G.length>100)return!1;let $=rm6(G);return new RegExp(`^${$}$`,"i").test(Z);case"contains":if(typeof Z!=="string"||typeof G!=="string")return!1;return Z.toLowerCase().includes(G.toLowerCase());default:return!0}}function K90(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 om6(X,Y){return[...X].sort((Q,J)=>{for(let G of Y){let W=G.field.join("."),Z=K90(Q,W),$=K90(J,W),K=0;if(Z==null&&$==null)continue;if(Z==null)K=G.nulls==="first"?-1:1;else if($==null)K=G.nulls==="first"?1:-1;else if(typeof Z==="string"&&typeof $==="string")K=Z.localeCompare($);else if(typeof Z==="number"&&typeof $==="number")K=Z-$;else K=String(Z).localeCompare(String($));if(K!==0)return G.direction==="desc"?-K:K}return 0})}var am6,sm6,tm6,H90;var eW1=S(()=>{Mf();aW1();GG();Af();r0();$6();g7();am6={LLM:$90,ASSISTANTS:iW1};sm6=nF.extend({binding:U.union([U.object({}).passthrough(),U.string()]).optional()}),tm6=iF(F5),H90=e0({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",inputSchema:sm6,outputSchema:tm6,handler:async(X,Y)=>{await Y.access.check();let Q=_1(Y),J=X.binding?typeof X.binding==="string"?(()=>{let z=am6[X.binding.toUpperCase()];if(!z)throw Error(`Unknown binding: ${X.binding}`);return z})():X.binding:void 0,G=J?wf(J):void 0,Z=(await Y.storage.connections.list(Q.id)).filter((z)=>z.connection_type!=="VIRTUAL"),$=G?await Promise.all(Z.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)):Z;if(X.where)$=$.filter((z)=>Tf(z,X.where));if(X.orderBy&&X.orderBy.length>0)$=om6($,X.orderBy);let K=$.length,H=X.offset??0,F=X.limit??100,V=$.slice(H,H+F),q=H+F<K;return{items:V,totalCount:K,hasMore:q}}})});var em6,F90;var XZ1=S(()=>{GG();$6();g7();em6=LA(F5),F90=e0({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",inputSchema:OA,outputSchema:em6,handler:async(X,Y)=>{let Q=_1(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 Ef=(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 YZ1(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 Xl6(X){let Y=X.split("::");if(Y.length!==2||!Y[0]||!Y[1])return null;return Y}function Yl6(X){if(typeof X==="object"&&X!==null&&"value"in X){let Y=X.value;if(typeof Y==="string")return Y}return null}function V90(X,Y){let Q={};if(!X||!Y)return Q;for(let J of Y){if(J==="*"){Q["*"]=["*"];continue}let G=Xl6(J);if(!G)continue;let[W,Z]=G,$=Ef(W,X),K=Yl6($);if(K){if(!Q[K])Q[K]=[];Q[K].push(Z)}}return Q}function QZ1(X,Y){let Q=V90(X,Y);return new Set(Object.keys(Q).filter((J)=>J!=="*"))}var q90=()=>{};class TZ{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(W)=>{let Z=await W.selectFrom("downstream_tokens").select(["id","createdAt"]).where("connectionId","=",X.connectionId).executeTakeFirst();if(Z)return await W.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","=",Z.id).execute(),{id:Z.id,connectionId:X.connectionId,accessToken:X.accessToken,refreshToken:X.refreshToken,scope:X.scope,expiresAt:X.expiresAt,createdAt:Z.createdAt,updatedAt:Y,clientId:X.clientId,clientSecret:X.clientSecret,tokenEndpoint:X.tokenEndpoint};let $=GX("dtok");return await W.insertInto("downstream_tokens").values({id:$,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:$,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 jf=S(()=>{wZ()});async function Gl6(X,Y,Q,J){for(let W of Y){if(W==="*")continue;let[Z]=YZ1(W),$=Ef(Z,X);if($===void 0||$===null)throw Error(`Scope references key "${Z}" but it's not present in state`)}let G=QZ1(X,Y);for(let W of G){if(W.endsWith("_self"))continue;let Z=await J.storage.connections.findById(W);if(!Z||Z.organization_id!==Q)throw Error(`Referenced connection not found: ${W}`);try{await J.access.check(W)}catch($){throw Error(`Access denied to referenced connection: ${W}. ${$.message}`)}}}var Ql6,Jl6,U90;var JZ1=S(()=>{q90();jf();r0();$6();Zf();g7();Ql6=U.object({id:U.string().describe("ID of the connection to update"),data:JG1.describe("Partial connection data to update")}),Jl6=U.object({item:F5.describe("The updated connection entity")});U90=e0({name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update an existing MCP connection in the organization",inputSchema:Ql6,outputSchema:Jl6,handler:async(X,Y)=>{z1(Y);let Q=_1(Y);if(await Y.access.check(),!d8(Y))throw Error("User ID required to update connection");let{id:G,data:W}=X,Z=await Y.storage.connections.findById(G);if(!Z||Z.organization_id!==Q.id)throw Error("Connection not found in organization");let $=W.connection_type??Z.connection_type,K=W.connection_url??Z.connection_url;if($==="VIRTUAL"){let L=fK(K);if(!L)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let w=await Y.storage.virtualMcps.findById(L);if(!w)throw Error(`Virtual MCP not found: ${L}`);if(w.organization_id!==Q.id)throw Error("Virtual MCP does not belong to the current organization");K=Xf(L)}let H=W.configuration_state??Z.configuration_state,F=W.configuration_scopes??Z.configuration_scopes??[];if(W.configuration_state!==void 0||W.configuration_scopes!==void 0){if(W.configuration_state!==void 0)H=W.configuration_state;else if(H===null)H={};if(W.configuration_scopes!==void 0)F=W.configuration_scopes??[];if(F.length>0&&H)await Gl6(H,F,Q.id,Y)}let V=W.connection_token??Z.connection_token;if(!V)try{let w=await new TZ(Y.db,Y.vault).get(G);if(w?.accessToken)V=w.accessToken}catch{}let q=await RB({id:Z.id,title:W.title??Z.title,connection_type:$,connection_url:K,connection_token:V,connection_headers:W.connection_headers??Z.connection_headers}).catch(()=>null),z=q?.length?q:null,D={...W,connection_url:K,tools:z,configuration_state:H,configuration_scopes:F},N=await Y.storage.connections.update(G,D);if((W.configuration_state!==void 0||W.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(L){console.error("Failed to invoke ON_MCP_CONFIGURATION callback",L)}return{item:N}}})});var z90;var GZ1=S(()=>{GG();$6();g7();z90=e0({name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete a connection",inputSchema:wA,outputSchema:MA(F5),handler:async(X,Y)=>{z1(Y);let Q=_1(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 B90;var WZ1=S(()=>{r0();$6();B90=e0({name:"CONNECTION_TEST",description:"Test connection health and latency",inputSchema:U.object({id:U.string()}),outputSchema:U.object({id:U.string(),healthy:U.boolean(),latencyMs:U.number()}),handler:async(X,Y)=>{let Q=_1(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 ZZ1=S(()=>{MW1();eW1();XZ1();JZ1();GZ1();WZ1()});import{sql as X4}from"kysely";function $Z1(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 $l6(X,Y){let Q=X;for(let G=Y.length;G>=1;G--){let W=`$${G}`;if(Q.includes(W))Q=Q.replaceAll(W,$Z1(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 W=J[G],Z=$Z1(Y[G]);Q=Q.slice(0,W)+Z+Q.slice(W+1)}return Q}function KZ1(X){return X.replace(/-/g,"_")}function Hl6(X){return`app_${KZ1(X)}`}function Fl6(X){return`app_role_${KZ1(X)}`}function Vl6(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 ql6(X,Y,Q){if(await X4`CREATE SCHEMA IF NOT EXISTS ${X4.id(Y)}`.execute(X),!(await X4`
|
|
1182
|
+
${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 yB(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,W)=>{let Z=yB(X,G);try{X.setProp(J,String(W),Z)}finally{Z.dispose?.()}}),J}let Q=X.newObject();for(let[J,G]of Object.entries(Y)){let W=yB(X,G);try{X.setProp(Q,J,W)}finally{W.dispose?.()}}return Q}case"function":{let Q=`__hostFn_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return X.newFunction(Q,(...G)=>{try{let W=G.map(($)=>X.dump($)),Z=Y(...W);if(Z&&typeof Z.then==="function"){let $=X.newPromise();return Z.then((K)=>{try{let H=yB(X,K);$.resolve(H),H.dispose(),X.runtime.executePendingJobs()}catch(H){let F=_B(H),V=X.newString(`Promise resolution error: ${F}`);$.reject(V),V.dispose(),X.runtime.executePendingJobs()}}).catch((K)=>{let H=_B(K),F=X.newString(`Promise rejection: ${H}`);$.reject(F),F.dispose(),X.runtime.executePendingJobs()}),$.handle}return yB(X,Z)}catch(W){let Z=_B(W);return X.newString(`HostFunctionError: ${Z}`)}finally{G.forEach((W)=>W.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 VW1=()=>{};function UW1(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 qW1(X,Y,Q){let J=Date.now(),G=X.resolvePromise(Y);while(!0){UW1(X);let W=await Promise.race([G,wu6(0).then(()=>null)]);if(W!==null)return W;if(Date.now()-J>Q)throw Error(`Timed out after ${Q}ms while awaiting a QuickJS promise`)}}async function tY0({tools:X,code:Y,timeoutMs:Q}){let Z=[];try{let J=await HW1({memoryLimitBytes:33554432,stackSizeBytes:524288});const G=Eh(Z,J.newContext({interruptAfterMs:Q}),0);const W=Eh(Z,f71(G),0);try{let F=G.evalCode(Y,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult(F),q=yB(G,X);G.setProp(G.global,"tools",q);let z=G.runtime.hasPendingJob()?G.unwrapResult(await qW1(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:W.logs};let L=G.callFunction(D,G.undefined,q),w=G.unwrapResult(L),C=await qW1(G,w,Q),T=G.unwrapResult(C);if(G.runtime.hasPendingJob())UW1(G);return{returnValue:G.dump(T),consoleLogs:W.logs}}catch(F){return console.log(F),{error:_B(F),consoleLogs:W.logs}}}catch($){var K=$,H=1}finally{uJ0(Z,K,H)}}var wu6=(X)=>new Promise((Y)=>setTimeout(Y,X));var zW1=S(()=>{FW1();VW1()});var BW1=S(()=>{zW1()});async function Mu6(X,Y){let Q;if(X.tool_selection_mode==="exclusion"){let G=(await Y.storage.connections.list(X.organization_id)).filter((Z)=>Z.status==="active"),W=new Map;for(let Z of X.connections)W.set(Z.connection_id,{selectedTools:Z.selected_tools,selectedResources:Z.selected_resources,selectedPrompts:Z.selected_prompts});Q=[];for(let Z of G){let $=W.get(Z.id);if($===void 0)Q.push({connection:Z,selectedTools:null,selectedResources:null,selectedPrompts:null});else if(($.selectedTools===null||$.selectedTools.length===0)&&($.selectedResources===null||$.selectedResources.length===0)&&($.selectedPrompts===null||$.selectedPrompts.length===0));else Q.push({connection:Z,selectedTools:$.selectedTools,selectedResources:$.selectedResources,selectedPrompts:$.selectedPrompts})}}else{let J=X.connections.map((W)=>W.connection_id),G=[];for(let W of J){let Z=await Y.storage.connections.findById(W);if(Z&&Z.status==="active")G.push(Z)}Q=G.map((W)=>{let Z=X.connections.find(($)=>$.connection_id===W.id);return{connection:W,selectedTools:Z?.selected_tools??null,selectedResources:Z?.selected_resources??null,selectedPrompts:Z?.selected_prompts??null}})}return Q}async function DW1(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 Pu6(X,Y,Q){let J=await kB.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}}),W=new Set,Z=[],$=new Map,K=new Set;for(let F of G){if(F.status!=="fulfilled"||!F.value)continue;let{connectionId:V,connectionTitle:q,tools:z}=F.value;K.add(q);for(let D of z){if(W.has(D.name))continue;W.add(D.name),Z.push({...D,_meta:{connectionId:V,connectionTitle:q}}),$.set(D.name,{connectionId:V,originalName:D.name})}}return{tools:Z,callTool:async(F,V)=>{let q=$.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(K).sort()}}async function bB(X){let Y=_1(X),Q,J="inclusion";if(X.connectionId){let G=await X.storage.virtualMcps.findById(X.connectionId);if(G)Q=await Mu6(G,X),J=G.tool_selection_mode;else Q=await DW1(Y.id,X)}else Q=await DW1(Y.id,X);return Pu6(Q,J,X)}function Au6(X){return X.toLowerCase().split(/[\s_\-./]+/).filter((Y)=>Y.length>=2)}function Tu6(X,Y){let Q=0,J=Y.name.toLowerCase(),G=(Y.description??"").toLowerCase(),W=Y._meta.connectionTitle.toLowerCase();for(let Z of X){if(J===Z)Q+=10;else if(J.includes(Z))Q+=3;if(G.includes(Z))Q+=2;if(W.includes(Z))Q+=1}return Q}function Uf(X,Y,Q){let J=Au6(X);if(J.length===0)return Y.slice(0,Q);return Y.map((G)=>({tool:G,score:Tu6(J,G)})).filter((G)=>G.score>0).sort((G,W)=>W.score-G.score).slice(0,Q).map((G)=>G.tool)}function zf(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 Bf(X,Y,Q){let J=Object.fromEntries(Y.tools.map((G)=>[G.name,async(W)=>Y.callTool(G.name,W??{})]));return tY0({code:X,tools:J,timeoutMs:Q})}function Df(X){return{content:[{type:"text",text:JSON.stringify(X,null,2)}]}}function fB(X){return{content:[{type:"text",text:JSON.stringify(X,null,2)}],isError:!0}}function zA(X){let Y=new Set(Eu6);return X.filter((Q)=>!Y.has(Q.name))}var Eu6;var BA=S(()=>{BW1();Eu6=["CODE_EXECUTION_SEARCH_TOOLS","CODE_EXECUTION_DESCRIBE_TOOLS","CODE_EXECUTION_RUN_CODE"]});var eY0;var NW1=S(()=>{$6();qA();BA();eY0=e0({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:S71,outputSchema:k71,handler:async(X,Y)=>{z1(Y),_1(Y),await Y.access.check();let Q=await bB(Y),J=Uf(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 X90;var OW1=S(()=>{$6();qA();BA();X90=e0({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:v71,outputSchema:_71,handler:async(X,Y)=>{z1(Y),_1(Y),await Y.access.check();let Q=await bB(Y);return zf(X.tools,Q.tools)}})});var Y90;var LW1=S(()=>{$6();qA();BA();Y90=e0({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:y71,outputSchema:b71,handler:async(X,Y)=>{z1(Y),_1(Y),await Y.access.check();let Q=await bB(Y);return await Bf(X.code,Q,X.timeoutMs)}})});var wW1=S(()=>{NW1();OW1();LW1();qA()});var Cu6,Iu6,Q90;var MW1=S(()=>{YA();r0();$6();Zf();g7();Cu6=U.object({data:QG1.describe("Data for the new connection (id is auto-generated if not provided)")}),Iu6=U.object({item:F5.describe("The created connection entity")}),Q90=e0({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",inputSchema:Cu6,outputSchema:Iu6,handler:async(X,Y)=>{z1(Y);let Q=_1(Y);await Y.access.check();let J=d8(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 K=fK(G.connection_url);if(!K)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let H=await Y.storage.virtualMcps.findById(K);if(!H)throw Error(`Virtual MCP not found: ${K}`);if(H.organization_id!==Q.id)throw Error("Virtual MCP does not belong to the current organization");G.connection_url=Xf(K)}let W=await RB({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),Z=W?.length?W:null,$=await Y.storage.connections.create({...G,tools:Z});return await Y.eventBus.publish(Q.id,LZ.SELF(Q.id),{type:"connection.created",data:$}),{item:$}}})});function DA(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)=>DA(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)&&DA(X[G],Y[G]))}return!1}function su6(){return(X)=>{if(!Array.isArray(X))return!0;let Y=[];return X.every((Q)=>{if(Y.some((G)=>DA(Q,G)))return!1;return Y.push(Q),!0})}}function Nf(X,Y){return X.safeParse(Y).success}function bY(X){if(typeof X==="boolean")return X?U.any():U.never();let Y={};for(let G of Vm6)G.apply(Y,X);let Q=[];if(Y.string!==!1)Q.push(Y.string||U.string());if(Y.number!==!1)Q.push(Y.number||U.number());if(Y.boolean!==!1)Q.push(Y.boolean||U.boolean());if(Y.null!==!1)Q.push(Y.null||U.null());if(Y.array!==!1)Q.push(Y.array||U.array(U.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=U.custom((W)=>{return typeof W==="object"&&W!==null&&!Array.isArray(W)},"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=U.never();else if(Q.length===1)J=Q[0];else if(!Object.keys(X).some((W)=>W!=="$schema"&&W!=="title"&&W!=="description"))J=U.any();else J=U.union(Q);for(let G of qm6)J=G.apply(J,X);return J}var Ru6=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||U.number();if(G instanceof U.ZodNumber)X.number=G.int()}}},Su6=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=U.literal(Q);else if(typeof Q==="number")X.number=U.literal(Q);else if(typeof Q==="boolean")X.boolean=U.literal(Q);else if(Q===null)X.null=U.null();else if(Array.isArray(Q))X.array=void 0;else if(typeof Q==="object")X.object=void 0}},ku6=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?U.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 U.literal(X[0]);if(Y==="string")return U.enum(X);if(Y==="number"){let[Q,J,...G]=X;return U.union([U.literal(Q),U.literal(J),...G.map((W)=>U.literal(W))])}if(Y==="boolean")return U.union([U.literal(!0),U.literal(!1)]);return!1}},vu6=class{apply(X,Y){let Q=Y;if(Q.type==="string"&&Q.format==="binary"&&Q.contentEncoding==="binary"){let J=U.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}}},_u6=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=U.string()}}},yu6=class{apply(X,Y){let Q=Y;if(Q.minLength===void 0)return;if(X.string!==!1){let J=X.string||U.string();if(J instanceof U.ZodString)X.string=J.refine((G)=>{return Array.from(G).length>=Q.minLength},{message:`String must be at least ${Q.minLength} characters long`})}}},bu6=class{apply(X,Y){let Q=Y;if(Q.maxLength===void 0)return;if(X.string!==!1){let J=X.string||U.string();if(J instanceof U.ZodString)X.string=J.refine((G)=>{return Array.from(G).length<=Q.maxLength},{message:`String must be at most ${Q.maxLength} characters long`})}}},fu6=class{apply(X,Y){let Q=Y;if(!Q.pattern)return;if(X.string!==!1){let J=X.string||U.string();if(J instanceof U.ZodString){let G=new RegExp(Q.pattern);X.string=J.regex(G)}}}},hu6=class{apply(X,Y){let Q=Y;if(Q.minimum===void 0)return;if(X.number!==!1){let J=X.number||U.number();if(J instanceof U.ZodNumber)X.number=J.min(Q.minimum)}}},xu6=class{apply(X,Y){let Q=Y;if(Q.maximum===void 0)return;if(X.number!==!1){let J=X.number||U.number();if(J instanceof U.ZodNumber)X.number=J.max(Q.maximum)}}},gu6=class{apply(X,Y){let Q=Y;if(Q.exclusiveMinimum===void 0)return;if(X.number!==!1){let J=X.number||U.number();if(J instanceof U.ZodNumber)if(typeof Q.exclusiveMinimum==="number")X.number=J.gt(Q.exclusiveMinimum);else X.number=!1}}},uu6=class{apply(X,Y){let Q=Y;if(Q.exclusiveMaximum===void 0)return;if(X.number!==!1){let J=X.number||U.number();if(J instanceof U.ZodNumber)if(typeof Q.exclusiveMaximum==="number")X.number=J.lt(Q.exclusiveMaximum);else X.number=!1}}},mu6=class{apply(X,Y){let Q=Y;if(Q.multipleOf===void 0)return;if(X.number!==!1){let J=X.number||U.number();if(J instanceof U.ZodNumber)X.number=J.refine((G)=>{if(Q.multipleOf===0)return!1;let W=G/Q.multipleOf,Z=Math.round(W),$=Math.min(Math.abs(G)*Number.EPSILON*10,Math.abs(Q.multipleOf)*Number.EPSILON*10);return Math.abs(W-Z)<=$/Math.abs(Q.multipleOf)},{message:`Must be a multiple of ${Q.multipleOf}`})}}},lu6=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=U.array(U.any())}}},du6=class{apply(X,Y){let Q=Y;if(Q.minItems===void 0)return;if(X.array!==!1)X.array=(X.array||U.array(U.any())).min(Q.minItems)}},pu6=class{apply(X,Y){let Q=Y;if(Q.maxItems===void 0)return;if(X.array!==!1)X.array=(X.array||U.array(U.any())).max(Q.maxItems)}},cu6=class{apply(X,Y){let Q=Y;if(X.array===!1)return;if(Array.isArray(Q.items))X.array=X.array||U.array(U.any());else if(Q.items&&typeof Q.items!=="boolean"&&!Q.prefixItems){let J=bY(Q.items),G=U.array(J);if(X.array&&X.array instanceof U.ZodArray){let W=X.array._def;if(W.checks)W.checks.forEach((Z)=>{if(Z._zod&&Z._zod.def){let $=Z._zod.def;if($.check==="min_length"&&$.minimum!==void 0)G=G.min($.minimum);else if($.check==="max_length"&&$.maximum!==void 0)G=G.max($.maximum)}})}X.array=G}else if(typeof Q.items==="boolean"&&Q.items===!1)if(!Q.prefixItems)X.array=U.array(U.any()).max(0);else X.array=X.array||U.array(U.any());else if(typeof Q.items==="boolean"&&Q.items===!0)X.array=X.array||U.array(U.any());else if(Q.prefixItems)X.array=X.array||U.array(U.any())}},nu6=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((W)=>bY(W)),G;if(J.length===0)G=U.tuple([]);else G=U.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}},iu6=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||U.object({}).passthrough()}},au6=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=U.object({}).passthrough()}}},ru6=class{apply(X,Y){let Q=Y;if(Q.maxProperties===void 0)return;if(X.object!==!1){let J=X.object||U.object({}).passthrough();X.object=J.refine((G)=>Object.keys(G).length<=Q.maxProperties,{message:`Object must have at most ${Q.maxProperties} properties`})}}},ou6=class{apply(X,Y){let Q=Y;if(Q.minProperties===void 0)return;if(X.object!==!1){let J=X.object||U.object({}).passthrough();X.object=J.refine((G)=>Object.keys(G).length>=Q.minProperties,{message:`Object must have at least ${Q.minProperties} properties`})}}},tu6=class{apply(X,Y){if(!Y.not)return X;let Q=bY(Y.not);return X.refine((J)=>!Nf(Q,J),{message:"Value must not match the 'not' schema"})}},eu6=class{apply(X,Y){if(Y.uniqueItems!==!0)return X;return X.refine(su6(),{message:"Array items must be unique"})}},Xm6=class{apply(X,Y){if(!Y.allOf||Y.allOf.length===0)return X;return Y.allOf.map((J)=>bY(J)).reduce((J,G)=>U.intersection(J,G),X)}},Ym6=class{apply(X,Y){if(!Y.anyOf||Y.anyOf.length===0)return X;let Q=Y.anyOf.length===1?bY(Y.anyOf[0]):U.union([bY(Y.anyOf[0]),bY(Y.anyOf[1]),...Y.anyOf.slice(2).map((J)=>bY(J))]);return U.intersection(X,Q)}},Qm6=class{apply(X,Y){if(!Y.oneOf||Y.oneOf.length===0)return X;let Q=Y.oneOf.map((J)=>bY(J));return X.refine((J)=>{let G=0;for(let W of Q)if(W.safeParse(J).success){if(G++,G>1)return!1}return G===1},{message:"Value must match exactly one of the oneOf schemas"})}},Jm6=class{apply(X,Y){let Q=Y;if(Q.prefixItems&&Array.isArray(Q.prefixItems)){let G=Q.prefixItems.map((W)=>bY(W));return X.refine((W)=>{if(!Array.isArray(W))return!0;for(let Z=0;Z<Math.min(W.length,G.length);Z++)if(!Nf(G[Z],W[Z]))return!1;if(W.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 Z=bY(Q.items);for(let $=G.length;$<W.length;$++)if(!Nf(Z,W[$]))return!1}}return!0},{message:"Array does not match prefixItems schema"})}return X}},Gm6=class{apply(X,Y){let Q=Y;if(!Q.properties&&!Q.required&&Q.additionalProperties!==!1)return X;if(X instanceof U.ZodObject||X instanceof U.ZodRecord){let J={};if(Q.properties){for(let[G,W]of Object.entries(Q.properties))if(W!==void 0)J[G]=bY(W)}if(Q.required&&Array.isArray(Q.required)){let G=new Set(Q.required);for(let W of Object.keys(J))if(!G.has(W))J[W]=J[W].optional()}else for(let G of Object.keys(J))J[G]=J[G].optional();if(Q.additionalProperties===!1)return U.object(J);else return U.object(J).passthrough()}return X.refine((J)=>{if(typeof J!=="object"||J===null||Array.isArray(J))return!0;if(Q.properties){for(let[G,W]of Object.entries(Q.properties))if(W!==void 0){if(Object.getOwnPropertyDescriptor(J,G)!==void 0){if(!bY(W).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 W in J)if(!G.has(W))return!1}return!0},{message:"Object constraints validation failed"})}},Wm6=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)=>DA(J,G))},{message:"Value must match one of the enum values"})}},Zm6=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)=>DA(J,Q),{message:"Value must equal the const value"})}},$m6=class{apply(X,Y){if(Y.description)X=X.describe(Y.description);return X}},Km6=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 U.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))}},Hm6=class{apply(X,Y){var Q;let J=Y;if(J.contains===void 0)return X;let G=bY(J.contains),W=(Q=J.minContains)!=null?Q:1,Z=J.maxContains;return X.refine(($)=>{if(!Array.isArray($))return!0;let K=0;for(let H of $)if(Nf(G,H))K++;if(K<W)return!1;if(Z!==void 0&&K>Z)return!1;return!0},{message:"Array must contain required items matching the schema"})}},Fm6=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)}},Vm6,qm6;var PW1=S(()=>{r6();r6();r6();r6();r6();r6();r6();r6();r6();r6();r6();r6();r6();r6();Vm6=[new Su6,new ku6,new Ru6,new vu6,new _u6,new lu6,new au6,new yu6,new bu6,new fu6,new hu6,new xu6,new gu6,new uu6,new mu6,new nu6,new du6,new pu6,new cu6,new ru6,new ou6,new iu6],qm6=[new Km6,new Wm6,new Zm6,new Xm6,new Ym6,new Qm6,new Jm6,new Gm6,new Hm6,new tu6,new eu6,new Fm6,new $m6]});class J90{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,Um6),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=ZJ.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 Um6="mcp";var AW1=S(()=>{RX()});function zm6(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 G90;var TW1=S(()=>{LB();G90=class G90 extends x7{constructor(X,Y){super(X,Y)}send(X,Y){let Q=zm6(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 EW1,jW1=async(X,Y,Q)=>{let J=Bm6(X.connection,Y,Q);if(!J)throw Error("Unknown MCP connection type");let G=new EW1({name:X?.name??"MCP Client",version:"1.0.0"});return await G.connect(J),{client:G,callStreamableTool:(W,Z,$)=>{if(X.connection.type!=="HTTP")throw Error("HTTP connection required");let K=new Headers(Q);if(!K.has("Authorization"))K.set("Authorization",`Bearer ${X.connection.token}`);for(let[V,q]of Object.entries(X.connection.headers??{}))K.set(V,q);let H=new URL(X.connection.url),F=H.pathname.replace(/\/+$/,"")||"/";return H.pathname=`${F}/call-tool/${encodeURIComponent(W)}`,fetch(H.href,{method:"POST",redirect:"manual",body:JSON.stringify(Z),headers:K,signal:$})}}},Bm6=(X,Y,Q)=>{if(X.type==="Websocket")return new J90(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 W={requestInit:{headers:G,signal:Y}};if(X.token)W.eventSourceInit={fetch:(Z,$)=>{return fetch(Z,{...$,headers:{...G,Accept:"text/event-stream"},signal:Y})}};return new gF(new URL(X.url),W)}return new G90(new URL(X.url),{requestInit:{headers:G,signal:Y,credentials:"include"}})};var CW1=S(()=>{yF();Jf();AW1();RX();TW1();EW1=class EW1 extends PQ{constructor(X,Y){super(X,Y)}async listTools(X,Y){return await this.request({method:"tools/list",params:X},EP,Y)}}});function RW1(X){let Y=(Q)=>{if("connection"in X)return jW1({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 $;async function G(K,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),K);let{structuredContent:D,isError:N,content:L}=await q.callTool({name:String(H),arguments:K});if(N){let w=L?.[0]?.text,C=typeof w==="string"?Dm6(w):null,T=C?.code&&typeof X?.getErrorByStatusCode==="function"?X.getErrorByStatusCode(C.code,C.message,C.traceId):null;if(T)throw T;throw Error(`Tool ${String(H)} returned an error: ${JSON.stringify(D??L)}`)}return D}async function W(){let{client:K}=await Y(),{tools:H}=await K.listTools();return H}async function Z(){if(!("connection"in X))return W();let K=X.connection,H=JSON.stringify(K);try{if(!Of.has(H))Of.set(H,W());return await Of.get(H)}catch(F){console.error("Failed to list tools",F),Of.delete(H);return}}async function $(){return(await Z()??[]).map((H)=>IW1(H,G))}return G.asTool=async()=>{let H=(await Z()??[]).find((F)=>F.name===J);if(!H)throw Error(`Tool ${J} not found`);return IW1(H,G)},G}})}var Dm6=(X)=>{try{return JSON.parse(X)}catch{return X}},Of,IW1=(X,Y)=>{return{...X,id:X.name,inputSchema:X.inputSchema?bY(X.inputSchema):void 0,outputSchema:X.outputSchema?bY(X.outputSchema):void 0,execute:(Q)=>{return Y(Q.context,X.name)}}};var SW1=S(()=>{PW1();CW1();Of=new Map});function Lf(X){return RW1(X)}var Ea4;var kW1=S(()=>{SW1();Ea4=new Proxy({},{get(X,Y){if(Y==="toJSON")return null;if(Y==="forConnection")return(Q)=>Lf({connection:Q});return global[Y]}})});function wf(X){return{isImplementedBy:(Y)=>{for(let Q of X){let J=typeof Q.name==="string"?new RegExp(`^${Q.name}$`):Q.name,G=Y.find((W)=>J.test(W.name));if(!G&&Q.opt)continue;if(!G)return!1}return!0}}}var cF=(X)=>{return{...wf(X),forClient:(Y)=>{return Lf({client:Y,streamable:X.reduce((Q,J)=>{return Q[J.name]=J.streamable===!0,Q},{})})},forConnection:(Y)=>{return Lf({connection:Y,streamable:X.reduce((Q,J)=>{return Q[J.name]=J.streamable===!0,Q},{})})}}};var NA=S(()=>{kW1()});var W90,Sa4;var vW1=S(()=>{XP();W90=w6(eM(),1),Sa4=W90.createContext(null)});function iF(X){return U.object({items:U.array(X).describe("Array of collection items"),totalCount:U.number().int().min(0).optional().describe("Total number of matching items (if available)"),hasMore:U.boolean().optional().describe("Whether there are more items available")})}function LA(X){return U.object({item:X.nullable().describe("The retrieved item, or null if not found")})}function Lm6(X){return U.object({data:X.partial().describe("Data for the new entity (id may be auto-generated)")})}function wm6(X){return U.object({item:X.describe("The created entity with generated id")})}function Mm6(X){return U.object({id:U.string().describe("ID of the entity to update"),data:X.partial().describe("Partial entity data to update")})}function Pm6(X){return U.object({item:X.describe("The updated entity")})}function MA(X){return U.object({item:X.describe("The deleted entity")})}function xB(X,Y,Q){let J=X.toUpperCase(),G=Q?.readOnly??!1,W=[{name:`COLLECTION_${J}_LIST`,inputSchema:nF,outputSchema:iF(Y)},{name:`COLLECTION_${J}_GET`,inputSchema:OA,outputSchema:LA(Y)}];if(!G)W.push({name:`COLLECTION_${J}_CREATE`,inputSchema:Lm6(Y),outputSchema:wm6(Y),opt:!0},{name:`COLLECTION_${J}_UPDATE`,inputSchema:Mm6(Y),outputSchema:Pm6(Y),opt:!0},{name:`COLLECTION_${J}_DELETE`,inputSchema:wA,outputSchema:MA(Y),opt:!0});return W}var hB,Nm6,_W1,Om6,nF,OA,wA;var GG=S(()=>{r0();hB=U.object({id:U.string().describe("Unique identifier for the entity"),title:U.string().describe("Human-readable title for the entity"),description:U.string().nullish().describe("Description of the entity"),created_at:U.string().datetime(),updated_at:U.string().datetime(),created_by:U.string().optional(),updated_by:U.string().optional()}),Nm6=U.object({field:U.array(U.string()),operator:U.enum(["eq","gt","gte","lt","lte","in","like","contains"]),value:U.unknown()}),_W1=U.lazy(()=>U.union([Nm6,U.object({operator:U.enum(["and","or","not"]),conditions:U.array(_W1)})])),Om6=U.object({field:U.array(U.string()),direction:U.enum(["asc","desc"]),nulls:U.enum(["first","last"]).optional()}),nF=U.object({where:_W1.optional().describe("Filter expression"),orderBy:U.array(Om6).optional().describe("Sort expressions"),limit:U.number().int().min(1).max(1000).optional().describe("Maximum number of items to return"),offset:U.number().int().min(0).optional().describe("Number of items to skip")});OA=U.object({id:U.string().describe("ID of the entity to retrieve")});wA=U.object({id:U.string().describe("ID of the entity to delete")})});var Am6,yW1,ha4;var bW1=S(()=>{r0();GG();Am6=U.object({id:U.string(),name:U.string(),description:U.string().optional(),inputSchema:U.record(U.string(),U.unknown()),outputSchema:U.record(U.string(),U.unknown()).optional()}),yW1=hB.extend({_meta:U.object({"io.decocms":U.object({id:U.string(),verified:U.boolean(),scopeName:U.string(),appName:U.string(),friendlyName:U.string().nullable().optional(),metadata:U.record(U.string(),U.unknown()).nullable().optional(),publishedAt:U.string().datetime().optional(),updatedAt:U.string().datetime().optional(),tools:U.array(Am6).nullable().optional().describe("Available tools exposed by this app")}).optional()}).optional(),server:U.object({$schema:U.string().optional(),_meta:U.record(U.string(),U.unknown()).optional(),name:U.string().describe("The server name (scope/app)"),title:U.string().optional().describe("User-friendly title"),description:U.string().optional().describe("Server description"),icons:U.array(U.object({src:U.string(),mimeType:U.string().optional(),sizes:U.array(U.string()).optional(),theme:U.enum(["light","dark"]).optional()})).optional(),remotes:U.array(U.object({type:U.enum(["http","stdio","sse"]),url:U.string().optional(),headers:U.array(U.unknown()).optional()})).optional(),packages:U.array(U.unknown()).optional(),repository:U.object({url:U.string(),source:U.string().optional(),subfolder:U.string().optional()}).optional(),version:U.string().optional(),websiteUrl:U.string().optional()})}),ha4=xB("registry_app",yW1,{readOnly:!0})});var fW1,hW1,xW1,gW1,uW1,Z90;var mW1=S(()=>{r0();NA();fW1=U.object({specversion:U.literal("1.0").describe("CloudEvents specification version"),id:U.string().describe("Unique identifier for this event (UUID recommended)"),source:U.string().describe("Connection ID of the event publisher"),type:U.string().describe("Event type (e.g., 'order.created', 'user.signup')"),time:U.string().datetime().optional().describe("Timestamp of when the event occurred (ISO 8601)"),subject:U.string().optional().describe("Subject/resource identifier (e.g., order ID, user ID)"),datacontenttype:U.string().optional().default("application/json").describe("Content type of the data attribute"),dataschema:U.string().url().optional().describe("URI to the schema for the data attribute"),data:U.unknown().optional().describe("Event payload (any JSON value)")}),hW1=U.object({events:U.array(fW1).min(1).describe("Batch of CloudEvents to process")}),xW1=U.object({success:U.boolean().optional().describe("Whether this event was processed successfully"),error:U.string().optional().describe("Error message for this event"),retryAfter:U.number().int().positive().optional().describe("Re-deliver this event after this many ms")}),gW1=U.object({success:U.boolean().optional().describe("Batch success - applies to events not in results"),error:U.string().optional().describe("Batch error message - applies to events not in results"),processedCount:U.number().int().min(0).optional().describe("Number of events successfully processed"),retryAfter:U.number().int().positive().optional().describe("Batch retryAfter - applies to events not in results"),results:U.record(U.string(),xW1).optional().describe("Per-event results keyed by event ID")}),uW1=[{name:"ON_EVENTS",inputSchema:hW1,outputSchema:gW1}],Z90=cF(uW1)});var PA,AA,TA,EA,lW1,dW1,jA,CA,IA,RA,SA,kA,vA,_A,pW1,Tm6;var cW1=S(()=>{r0();NA();PA=U.object({type:U.string().min(1).max(255).describe("Event type identifier"),subject:U.string().max(255).optional().describe("Subject/resource identifier (e.g., order ID)"),data:U.unknown().optional().describe("Event payload"),deliverAt:U.string().datetime().optional().describe("Scheduled delivery time (ISO 8601). Omit for immediate delivery."),cron:U.string().max(100).optional().describe("Cron expression for recurring delivery. Use EVENT_CANCEL to stop.")}),AA=U.object({id:U.string().describe("Unique event ID"),type:U.string().describe("Event type"),source:U.string().describe("Source connection ID"),time:U.string().describe("Event timestamp")}),TA=U.object({eventType:U.string().min(1).max(255).describe("Event type to subscribe to"),publisher:U.string().optional().describe("Filter events by publisher connection ID"),filter:U.string().max(1000).optional().describe("JSONPath filter expression on event data")}),EA=U.object({subscription:U.object({id:U.string().describe("Subscription ID"),connectionId:U.string().describe("Subscriber connection ID"),eventType:U.string().describe("Event type pattern"),publisher:U.string().nullable().describe("Publisher connection filter"),filter:U.string().nullable().describe("JSONPath filter expression"),enabled:U.boolean().describe("Whether subscription is enabled"),createdAt:U.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:U.string().datetime().describe("Updated timestamp (ISO 8601)")})}),lW1=U.object({eventType:U.string().min(1).max(255).describe("Event type to subscribe to"),publisher:U.string().optional().describe("Filter events by publisher connection ID"),filter:U.string().max(1000).optional().describe("JSONPath filter expression on event data")}),dW1=U.object({id:U.string().describe("Subscription ID"),connectionId:U.string().describe("Subscriber connection ID"),eventType:U.string().describe("Event type pattern"),publisher:U.string().nullable().describe("Publisher connection filter"),filter:U.string().nullable().describe("JSONPath filter expression"),enabled:U.boolean().describe("Whether subscription is enabled"),createdAt:U.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:U.string().datetime().describe("Updated timestamp (ISO 8601)")}),jA=U.object({subscriptions:U.array(lW1).describe("Desired subscriptions - system will create/update/delete to match")}),CA=U.object({created:U.number().int().min(0).describe("Number of subscriptions created"),updated:U.number().int().min(0).describe("Number of subscriptions with filter updated"),deleted:U.number().int().min(0).describe("Number of subscriptions removed"),unchanged:U.number().int().min(0).describe("Number of subscriptions unchanged"),subscriptions:U.array(dW1).describe("Current subscriptions after sync")}),IA=U.object({subscriptionId:U.string().describe("Subscription ID to remove")}),RA=U.object({success:U.boolean().describe("Whether unsubscribe was successful"),subscriptionId:U.string().describe("Subscription ID that was removed")}),SA=U.object({eventId:U.string().describe("Event ID to cancel")}),kA=U.object({success:U.boolean().describe("Whether cancellation was successful"),eventId:U.string().describe("Event ID that was cancelled")}),vA=U.object({eventId:U.string().describe("Event ID to acknowledge")}),_A=U.object({success:U.boolean().describe("Whether ACK was successful"),eventId:U.string().describe("Event ID that was acknowledged")}),pW1=[{name:"EVENT_PUBLISH",inputSchema:PA,outputSchema:AA},{name:"EVENT_SUBSCRIBE",inputSchema:TA,outputSchema:EA},{name:"EVENT_UNSUBSCRIBE",inputSchema:IA,outputSchema:RA},{name:"EVENT_CANCEL",inputSchema:SA,outputSchema:kA},{name:"EVENT_ACK",inputSchema:vA,outputSchema:_A},{name:"EVENT_SYNC_SUBSCRIPTIONS",inputSchema:jA,outputSchema:CA}],Tm6=cF(pW1)});var na4,ia4,aa4,ra4,oa4,sa4,ta4,ea4,Xr4,Yr4,Qr4,Jr4;var nW1=S(()=>{r0();na4=U.object({prefix:U.string().optional().describe("Filter objects by prefix (e.g., 'folder/' for folder contents)"),maxKeys:U.number().optional().default(1000).describe("Maximum number of keys to return (default: 1000)"),continuationToken:U.string().optional().describe("Token for pagination from previous response"),delimiter:U.string().optional().describe("Delimiter for grouping keys (typically '/'). When set, commonPrefixes returns folder paths.")}),ia4=U.object({objects:U.array(U.object({key:U.string().describe("Object key/path"),size:U.number().describe("Object size in bytes"),lastModified:U.string().describe("Last modified timestamp"),etag:U.string().describe("Entity tag for the object")})),nextContinuationToken:U.string().optional().describe("Token for fetching next page of results"),isTruncated:U.boolean().describe("Whether there are more results available"),commonPrefixes:U.array(U.string()).optional().describe("Folder paths when delimiter is used (e.g., ['photos/2024/', 'photos/2025/'])")}),aa4=U.object({key:U.string().describe("Object key/path to get metadata for")}),ra4=U.object({contentType:U.string().optional().describe("MIME type of the object"),contentLength:U.number().describe("Size of the object in bytes"),lastModified:U.string().describe("Last modified timestamp"),etag:U.string().describe("Entity tag for the object"),metadata:U.record(U.string(),U.string()).optional().describe("Custom metadata key-value pairs")}),oa4=U.object({key:U.string().describe("Object key/path to generate URL for"),expiresIn:U.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)")}),sa4=U.object({url:U.string().describe("Presigned URL for downloading the object"),expiresIn:U.number().describe("Expiration time in seconds that was used")}),ta4=U.object({key:U.string().describe("Object key/path for the upload"),expiresIn:U.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)"),contentType:U.string().optional().describe("MIME type for the object being uploaded")}),ea4=U.object({url:U.string().describe("Presigned URL for uploading the object"),expiresIn:U.number().describe("Expiration time in seconds that was used")}),Xr4=U.object({key:U.string().describe("Object key/path to delete")}),Yr4=U.object({success:U.boolean().describe("Whether the deletion was successful"),key:U.string().describe("The key that was deleted")}),Qr4=U.object({keys:U.array(U.string()).max(1000).describe("Array of object keys/paths to delete (max 1000)")}),Jr4=U.object({deleted:U.array(U.string()).describe("Array of successfully deleted keys"),errors:U.array(U.object({key:U.string(),message:U.string()})).describe("Array of errors for failed deletions")})});var Mf=S(()=>{NA();vW1();bW1();mW1();cW1();nW1()});var Em6,jm6,iW1;var aW1=S(()=>{r0();GG();Em6=hB.extend({avatar:U.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:U.string().describe("System prompt that defines the assistant's behavior"),virtual_mcp_id:U.string().describe("Virtual MCP ID to use for this assistant"),model:U.object({id:U.string().describe("Model ID"),connectionId:U.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),jm6=xB("assistant",Em6),iW1=[...jm6]});var yA,AZ,oW1,Cm6,Im6,sW1,Rm6,Sm6,km6,vm6,_m6,ym6,tW1,bm6,fm6,hm6,xm6,gm6,um6,mm6,lm6,dm6,pm6,Ar4,cm6,Tr4,rW1,nm6,im6,$90,Pf;var Af=S(()=>{r0();NA();GG();yA=U.lazy(()=>U.union([U.null(),U.string(),U.number(),U.boolean(),U.record(U.string(),yA),U.array(yA)])),AZ=U.record(U.string(),U.record(U.string(),yA)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),oW1=U.object({type:U.literal("text"),text:U.string().describe("The text content"),providerOptions:AZ}),Cm6=U.object({type:U.literal("text"),text:U.string().describe("The text content"),providerMetadata:U.any().optional().describe("Additional provider-specific metadata")}),Im6=U.string().describe("File data as URL string"),sW1=U.object({type:U.literal("file"),filename:U.string().optional().describe("Optional filename of the file"),data:Im6,mediaType:U.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:AZ}),Rm6=U.object({type:U.literal("file"),mediaType:U.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),data:U.string().describe("Generated file data as base64 encoded string")}),Sm6=U.object({type:U.literal("reasoning"),text:U.string().describe("The reasoning text"),providerOptions:AZ}),km6=U.object({type:U.literal("reasoning"),text:U.string().describe("The reasoning text"),providerMetadata:U.any().optional().describe("Additional provider-specific metadata")}),vm6=U.object({type:U.literal("tool-call"),toolCallId:U.string().describe("ID of the tool call, used to match with tool result"),toolName:U.string().describe("Name of the tool being called"),input:U.string().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:U.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:AZ}),_m6=U.object({type:U.literal("tool-call"),toolCallId:U.string().describe("ID of the tool call"),toolName:U.string().describe("Name of the tool being called"),input:U.string().describe("Stringified JSON object with the tool call arguments"),providerExecuted:U.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerMetadata:U.any().optional().describe("Additional provider-specific metadata")}),ym6=U.union([U.object({type:U.literal("text"),value:U.string()}),U.object({type:U.literal("json"),value:yA}),U.object({type:U.literal("error-text"),value:U.string()}),U.object({type:U.literal("error-json"),value:yA}),U.object({type:U.literal("content"),value:U.array(U.union([U.object({type:U.literal("text"),text:U.string().describe("Text content")}),U.object({type:U.literal("media"),data:U.string().describe("Base-64 encoded media data"),mediaType:U.string().describe("IANA media type")})]))})]),tW1=U.object({type:U.literal("tool-result"),toolCallId:U.string().describe("ID of the tool call that this result is associated with"),toolName:U.string().describe("Name of the tool that generated this result"),output:ym6.describe("Result of the tool call"),result:U.unknown().describe("Unknown result of the tool call"),providerOptions:AZ}),bm6=U.object({type:U.literal("tool-result"),toolCallId:U.string().describe("ID of the tool call that this result is associated with"),toolName:U.string().describe("Name of the tool that generated this result"),result:U.any().describe("Result of the tool call (JSON-serializable)"),isError:U.boolean().optional().describe("Whether the result is an error or error message"),providerExecuted:U.boolean().optional().describe("Whether the tool result was generated by the provider"),providerMetadata:U.any().optional().describe("Additional provider-specific metadata")}),fm6=U.union([U.object({type:U.literal("source"),sourceType:U.literal("url"),id:U.string().describe("The ID of the source"),url:U.string().describe("The URL of the source"),title:U.string().optional().describe("The title of the source"),providerMetadata:U.any().optional().describe("Additional provider-specific metadata")}),U.object({type:U.literal("source"),sourceType:U.literal("document"),id:U.string().describe("The ID of the source"),mediaType:U.string().describe("IANA media type of the document (e.g., application/pdf)"),title:U.string().describe("The title of the document"),filename:U.string().optional().describe("Optional filename of the document"),providerMetadata:U.any().optional().describe("Additional provider-specific metadata")})]),hm6=U.object({role:U.literal("system"),content:U.string().describe("System message content"),providerOptions:AZ}),xm6=U.object({role:U.literal("user"),content:U.array(U.union([oW1,sW1])).describe("User message content parts (text or file)"),providerOptions:AZ}),gm6=U.object({role:U.literal("assistant"),content:U.array(U.union([oW1,sW1,Sm6,vm6,tW1])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:AZ}),um6=U.object({role:U.literal("tool"),content:U.array(tW1).describe("Tool message content (tool results)"),providerOptions:AZ}),mm6=U.union([hm6,xm6,gm6,um6]),lm6=U.array(mm6).describe("A list of messages forming the prompt"),dm6=U.object({prompt:lm6.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:U.number().optional().describe("Maximum number of tokens to generate"),temperature:U.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:U.number().optional().describe("Nucleus sampling parameter"),topK:U.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:U.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:U.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:U.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:U.array(U.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:U.union([U.object({type:U.literal("text")}),U.object({type:U.literal("json"),schema:U.any().optional().describe("JSON schema that the generated output should conform to"),name:U.string().optional().describe("Name of output that should be generated"),description:U.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:U.array(U.any()).optional().describe("The tools that are available for the model"),toolChoice:U.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:U.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:U.any().optional().describe("Abort signal for cancelling the operation"),providerOptions:U.any().optional().describe("Additional provider-specific options")}),pm6=U.object({content:U.array(U.union([Cm6,Rm6,km6,_m6,bm6,fm6])).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:U.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:U.looseObject({inputTokens:U.number().optional(),outputTokens:U.number().optional(),totalTokens:U.number().optional(),reasoningTokens:U.number().optional()}).describe("Usage information for the language model call"),providerMetadata:U.any().optional().describe("Additional provider-specific metadata"),request:U.object({body:U.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:U.object({id:U.string().optional().describe("ID for the generated response"),timestamp:U.iso.datetime().optional().describe("Timestamp for the start of the generated response"),modelId:U.string().optional().describe("The ID of the response model that was used"),headers:U.record(U.string(),U.string()).optional().describe("Response headers"),body:U.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:U.array(U.any()).describe("Warnings for the call, e.g. unsupported settings")}),Ar4=U.object({stream:U.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:U.object({body:U.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:U.object({headers:U.record(U.string(),U.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),cm6=U.object({supportedUrls:U.record(U.string(),U.array(U.string())).describe("Supported URL patterns by media type for the provider")}),Tr4=U.object({modelId:U.string().describe("The ID of the model"),logo:U.string().nullable(),description:U.string().nullable(),capabilities:U.array(U.string()),limits:U.object({contextWindow:U.number(),maxOutputTokens:U.number()}).nullable(),costs:U.object({input:U.number(),output:U.number()}).nullable(),provider:U.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),rW1=U.object({modelId:U.string().describe("The ID of the model"),callOptions:dm6}),nm6=hB.extend({logo:U.string().nullable(),description:U.string().nullable(),capabilities:U.array(U.string()),limits:U.object({contextWindow:U.number(),maxOutputTokens:U.number()}).nullable(),costs:U.object({input:U.number(),output:U.number()}).nullable(),provider:U.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),im6=xB("llm",nm6,{readOnly:!0}),$90=[{name:"LLM_METADATA",inputSchema:U.object({modelId:U.string().describe("The ID of the model")}),outputSchema:cm6},{name:"LLM_DO_STREAM",inputSchema:rW1,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:rW1,outputSchema:pm6},...im6],Pf=cF($90)});function rm6(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 uK(X){return typeof X==="string"||typeof X==="number"}function Tf(X,Y){if("conditions"in Y){let{operator:$,conditions:K}=Y;switch($){case"and":return K.every((H)=>Tf(X,H));case"or":return K.some((H)=>Tf(X,H));case"not":return!K.every((H)=>Tf(X,H));default:return!0}}let{field:Q,operator:J,value:G}=Y,W=Q.join("."),Z=K90(X,W);switch(J){case"eq":return Z===G;case"gt":return uK(Z)&&uK(G)&&Z>G;case"gte":return uK(Z)&&uK(G)&&Z>=G;case"lt":return uK(Z)&&uK(G)&&Z<G;case"lte":return uK(Z)&&uK(G)&&Z<=G;case"in":return Array.isArray(G)&&G.includes(Z);case"like":if(typeof Z!=="string"||typeof G!=="string")return!1;if(G.length>100)return!1;let $=rm6(G);return new RegExp(`^${$}$`,"i").test(Z);case"contains":if(typeof Z!=="string"||typeof G!=="string")return!1;return Z.toLowerCase().includes(G.toLowerCase());default:return!0}}function K90(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 om6(X,Y){return[...X].sort((Q,J)=>{for(let G of Y){let W=G.field.join("."),Z=K90(Q,W),$=K90(J,W),K=0;if(Z==null&&$==null)continue;if(Z==null)K=G.nulls==="first"?-1:1;else if($==null)K=G.nulls==="first"?1:-1;else if(typeof Z==="string"&&typeof $==="string")K=Z.localeCompare($);else if(typeof Z==="number"&&typeof $==="number")K=Z-$;else K=String(Z).localeCompare(String($));if(K!==0)return G.direction==="desc"?-K:K}return 0})}var am6,sm6,tm6,H90;var eW1=S(()=>{Mf();aW1();GG();Af();r0();$6();g7();am6={LLM:$90,ASSISTANTS:iW1};sm6=nF.extend({binding:U.union([U.object({}).passthrough(),U.string()]).optional()}),tm6=iF(F5),H90=e0({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",inputSchema:sm6,outputSchema:tm6,handler:async(X,Y)=>{await Y.access.check();let Q=_1(Y),J=X.binding?typeof X.binding==="string"?(()=>{let z=am6[X.binding.toUpperCase()];if(!z)throw Error(`Unknown binding: ${X.binding}`);return z})():X.binding:void 0,G=J?wf(J):void 0,Z=(await Y.storage.connections.list(Q.id)).filter((z)=>z.connection_type!=="VIRTUAL"),$=G?await Promise.all(Z.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)):Z;if(X.where)$=$.filter((z)=>Tf(z,X.where));if(X.orderBy&&X.orderBy.length>0)$=om6($,X.orderBy);let K=$.length,H=X.offset??0,F=X.limit??100,V=$.slice(H,H+F),q=H+F<K;return{items:V,totalCount:K,hasMore:q}}})});var em6,F90;var XZ1=S(()=>{GG();$6();g7();em6=LA(F5),F90=e0({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",inputSchema:OA,outputSchema:em6,handler:async(X,Y)=>{let Q=_1(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 Ef=(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 YZ1(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 Xl6(X){let Y=X.split("::");if(Y.length!==2||!Y[0]||!Y[1])return null;return Y}function Yl6(X){if(typeof X==="object"&&X!==null&&"value"in X){let Y=X.value;if(typeof Y==="string")return Y}return null}function V90(X,Y){let Q={};if(!X||!Y)return Q;for(let J of Y){if(J==="*"){Q["*"]=["*"];continue}let G=Xl6(J);if(!G)continue;let[W,Z]=G,$=Ef(W,X),K=Yl6($);if(K){if(!Q[K])Q[K]=[];Q[K].push(Z)}}return Q}function QZ1(X,Y){let Q=V90(X,Y);return new Set(Object.keys(Q).filter((J)=>J!=="*"))}var q90=()=>{};class TZ{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(W)=>{let Z=await W.selectFrom("downstream_tokens").select(["id","createdAt"]).where("connectionId","=",X.connectionId).executeTakeFirst();if(Z)return await W.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","=",Z.id).execute(),{id:Z.id,connectionId:X.connectionId,accessToken:X.accessToken,refreshToken:X.refreshToken,scope:X.scope,expiresAt:X.expiresAt,createdAt:Z.createdAt,updatedAt:Y,clientId:X.clientId,clientSecret:X.clientSecret,tokenEndpoint:X.tokenEndpoint};let $=GX("dtok");return await W.insertInto("downstream_tokens").values({id:$,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:$,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 jf=S(()=>{wZ()});async function Gl6(X,Y,Q,J){for(let W of Y){if(W==="*")continue;let[Z]=YZ1(W),$=Ef(Z,X);if($===void 0||$===null)throw Error(`Scope references key "${Z}" but it's not present in state`)}let G=QZ1(X,Y);for(let W of G){if(W.endsWith("_self"))continue;let Z=await J.storage.connections.findById(W);if(!Z||Z.organization_id!==Q)throw Error(`Referenced connection not found: ${W}`);try{await J.access.check(W)}catch($){throw Error(`Access denied to referenced connection: ${W}. ${$.message}`)}}}var Ql6,Jl6,U90;var JZ1=S(()=>{q90();jf();r0();$6();Zf();g7();Ql6=U.object({id:U.string().describe("ID of the connection to update"),data:JG1.describe("Partial connection data to update")}),Jl6=U.object({item:F5.describe("The updated connection entity")});U90=e0({name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update an existing MCP connection in the organization",inputSchema:Ql6,outputSchema:Jl6,handler:async(X,Y)=>{z1(Y);let Q=_1(Y);if(await Y.access.check(),!d8(Y))throw Error("User ID required to update connection");let{id:G,data:W}=X,Z=await Y.storage.connections.findById(G);if(!Z||Z.organization_id!==Q.id)throw Error("Connection not found in organization");let $=W.connection_type??Z.connection_type,K=W.connection_url??Z.connection_url;if($==="VIRTUAL"){let L=fK(K);if(!L)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let w=await Y.storage.virtualMcps.findById(L);if(!w)throw Error(`Virtual MCP not found: ${L}`);if(w.organization_id!==Q.id)throw Error("Virtual MCP does not belong to the current organization");K=Xf(L)}let H=W.configuration_state??Z.configuration_state,F=W.configuration_scopes??Z.configuration_scopes??[];if(W.configuration_state!==void 0||W.configuration_scopes!==void 0){if(W.configuration_state!==void 0)H=W.configuration_state;else if(H===null)H={};if(W.configuration_scopes!==void 0)F=W.configuration_scopes??[];if(F.length>0&&H)await Gl6(H,F,Q.id,Y)}let V=W.connection_token??Z.connection_token;if(!V)try{let w=await new TZ(Y.db,Y.vault).get(G);if(w?.accessToken)V=w.accessToken}catch{}let q=await RB({id:Z.id,title:W.title??Z.title,connection_type:$,connection_url:K,connection_token:V,connection_headers:W.connection_headers??Z.connection_headers}).catch(()=>null),z=q?.length?q:null,D={...W,connection_url:K,tools:z,configuration_state:H,configuration_scopes:F},N=await Y.storage.connections.update(G,D);if((W.configuration_state!==void 0||W.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(L){console.error("Failed to invoke ON_MCP_CONFIGURATION callback",L)}return{item:N}}})});var z90;var GZ1=S(()=>{GG();$6();g7();z90=e0({name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete a connection",inputSchema:wA,outputSchema:MA(F5),handler:async(X,Y)=>{z1(Y);let Q=_1(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 B90;var WZ1=S(()=>{r0();$6();B90=e0({name:"CONNECTION_TEST",description:"Test connection health and latency",inputSchema:U.object({id:U.string()}),outputSchema:U.object({id:U.string(),healthy:U.boolean(),latencyMs:U.number()}),handler:async(X,Y)=>{let Q=_1(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 ZZ1=S(()=>{MW1();eW1();XZ1();JZ1();GZ1();WZ1()});import{sql as X4}from"kysely";function $Z1(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 $l6(X,Y){let Q=X;for(let G=Y.length;G>=1;G--){let W=`$${G}`;if(Q.includes(W))Q=Q.replaceAll(W,$Z1(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 W=J[G],Z=$Z1(Y[G]);Q=Q.slice(0,W)+Z+Q.slice(W+1)}return Q}function KZ1(X){return X.replace(/-/g,"_")}function Hl6(X){return`app_${KZ1(X)}`}function Fl6(X){return`app_role_${KZ1(X)}`}function Vl6(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 ql6(X,Y,Q){if(await X4`CREATE SCHEMA IF NOT EXISTS ${X4.id(Y)}`.execute(X),!(await X4`
|
|
1183
1183
|
SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${Q}) as exists
|
|
1184
|
-
`.execute(X)).rows[0]?.exists)await X4`CREATE ROLE ${X4.id(Q)} NOLOGIN`.execute(X);await X4`GRANT ${X4.id(Q)} TO CURRENT_USER`.execute(X),await X4`GRANT USAGE, CREATE ON SCHEMA ${X4.id(Y)} TO ${X4.id(Q)}`.execute(X),await X4`GRANT ALL ON ALL TABLES IN SCHEMA ${X4.id(Y)} TO ${X4.id(Q)}`.execute(X),await X4`GRANT ALL ON ALL SEQUENCES IN SCHEMA ${X4.id(Y)} TO ${X4.id(Q)}`.execute(X),await X4`ALTER DEFAULT PRIVILEGES IN SCHEMA ${X4.id(Y)} GRANT ALL ON TABLES TO ${X4.id(Q)}`.execute(X),await X4`ALTER DEFAULT PRIVILEGES IN SCHEMA ${X4.id(Y)} GRANT ALL ON SEQUENCES TO ${X4.id(Q)}`.execute(X),await X4`REVOKE ALL ON SCHEMA public FROM ${X4.id(Q)}`.execute(X)}async function Ul6(X,Y,Q,J){try{return await X.transaction().execute(async(G)=>{return await X4`SET LOCAL ROLE ${X4.id(Q)}`.execute(G),await X4`SET LOCAL search_path TO ${X4.id(Y)}`.execute(G),await X4.raw(J).execute(G)})}catch(G){if(Vl6(G))return await ql6(X,Y,Q),await X.transaction().execute(async(W)=>{return await X4`SET LOCAL ROLE ${X4.id(Q)}`.execute(W),await X4`SET LOCAL search_path TO ${X4.id(Y)}`.execute(W),await X4.raw(J).execute(W)});throw G}}var Zl6,Kl6,HZ1;var FZ1=S(()=>{r0();$6();Zl6=U.object({results:U.array(U.unknown()).optional(),success:U.boolean().optional()});Kl6=U.object({sql:U.string().describe("The SQL query to run"),params:U.array(U.any()).describe("The parameters to pass to the SQL query").optional()});HZ1=e0({name:"DATABASES_RUN_SQL",description:"Run a SQL query against the database",inputSchema:Kl6,outputSchema:U.object({result:U.array(Zl6)}),handler:async(X,Y)=>{z1(Y),await Y.access.check();let Q=$l6(X.sql,X.params||[]);if(!Y.connectionId)throw Error("Connection context required for database access");let J=Hl6(Y.connectionId),G=Fl6(Y.connectionId);return{result:[{results:(await Ul6(Y.db,J,G,Q)).rows,success:!0}]}}})});var VZ1,Bl6,qZ1;var EZ=S(()=>{r0();Mf();VZ1=U.object({connectionId:U.string().optional().describe("Filter subscriptions by connection ID (optional)")}),Bl6=U.object({id:U.string().describe("Subscription ID"),connectionId:U.string().describe("Subscriber connection ID"),eventType:U.string().describe("Event type pattern"),publisher:U.string().nullable().describe("Publisher connection filter (null = all publishers)"),filter:U.string().nullable().describe("JSONPath filter expression"),enabled:U.boolean().describe("Whether subscription is enabled"),createdAt:U.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:U.string().datetime().describe("Updated timestamp (ISO 8601)")}),qZ1=U.object({subscriptions:U.array(Bl6).describe("List of subscriptions")})});var D90;var UZ1=S(()=>{$6();EZ();D90=e0({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:PA,outputSchema:AA,handler:async(X,Y)=>{z1(Y);let Q=_1(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 N90;var zZ1=S(()=>{$6();EZ();N90=e0({name:"EVENT_SUBSCRIBE",description:"Subscribe to events of a specific type. The subscriber is automatically set to the caller's connection.",inputSchema:TA,outputSchema:EA,handler:async(X,Y)=>{z1(Y);let Q=_1(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 O90;var BZ1=S(()=>{$6();EZ();O90=e0({name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events by removing a subscription.",inputSchema:IA,outputSchema:RA,handler:async(X,Y)=>{z1(Y);let Q=_1(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 L90;var DZ1=S(()=>{$6();EZ();L90=e0({name:"EVENT_CANCEL",description:"Cancel a recurring event to stop future deliveries. Only the publisher can cancel their own events.",inputSchema:SA,outputSchema:kA,handler:async(X,Y)=>{z1(Y);let Q=_1(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 w90;var NZ1=S(()=>{$6();EZ();w90=e0({name:"EVENT_ACK",description:"Acknowledge delivery of an event. Call after successfully processing an event received via ON_EVENTS with retryAfter.",inputSchema:vA,outputSchema:_A,handler:async(X,Y)=>{z1(Y);let Q=_1(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 M90;var OZ1=S(()=>{$6();EZ();M90=e0({name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions, optionally filtered by connection ID.",inputSchema:VZ1,outputSchema:qZ1,handler:async(X,Y)=>{z1(Y);let Q=_1(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 P90;var LZ1=S(()=>{$6();EZ();P90=e0({name:"EVENT_SYNC_SUBSCRIPTIONS",description:"Sync subscriptions to desired state. Creates new, deletes removed, updates changed filters. Subscriptions are identified by (eventType, publisher).",inputSchema:jA,outputSchema:CA,handler:async(X,Y)=>{z1(Y);let Q=_1(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((W)=>({id:W.id,connectionId:W.connectionId,eventType:W.eventType,publisher:W.publisher,filter:W.filter,enabled:W.enabled,createdAt:W.createdAt instanceof Date?W.createdAt.toISOString():W.createdAt,updatedAt:W.updatedAt instanceof Date?W.updatedAt.toISOString():W.updatedAt}))}}})});var wZ1=S(()=>{UZ1();zZ1();BZ1();DZ1();NZ1();OZ1();LZ1();EZ()});var A90,Nl6,u7,MZ1,PZ1;var gB=S(()=>{r0();A90=U.enum(["inclusion","exclusion"]).describe("Tool selection mode: 'inclusion' = include selected (default), 'exclusion' = exclude selected"),Nl6=U.object({connection_id:U.string().describe("Connection ID"),selected_tools:U.array(U.string()).nullable().describe("Selected tool names. With 'inclusion' mode: null = all tools included. With 'exclusion' mode: null = entire connection excluded"),selected_resources:U.array(U.string()).nullable().describe("Selected resource URIs or patterns. Supports * and ** wildcards for pattern matching. With 'inclusion' mode: null = all resources included."),selected_prompts:U.array(U.string()).nullable().describe("Selected prompt names. With 'inclusion' mode: null = all prompts included. With 'exclusion' mode: null = entire connection excluded.")}),u7=U.object({id:U.string().describe("Unique identifier for the virtual MCP"),title:U.string().describe("Human-readable name for the virtual MCP"),description:U.string().nullable().describe("Description of the virtual MCP"),icon:U.string().nullable().optional().describe("Icon URL for the virtual MCP"),created_at:U.string().describe("When the virtual MCP was created"),updated_at:U.string().describe("When the virtual MCP was last updated"),created_by:U.string().describe("User ID who created the virtual MCP"),updated_by:U.string().optional().describe("User ID who last updated the virtual MCP"),organization_id:U.string().describe("Organization ID this virtual MCP belongs to"),tool_selection_mode:A90.describe("Tool selection mode: 'inclusion' = include selected, 'exclusion' = exclude selected"),status:U.enum(["active","inactive"]).describe("Current status"),metadata:U.object({instructions:U.string().optional().describe("MCP server instructions")}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:U.array(Nl6).describe("Connections with their selected tools (behavior depends on tool_selection_mode)")}),MZ1=U.object({title:U.string().min(1).max(255).describe("Name for the virtual MCP"),description:U.string().nullable().optional().describe("Optional description"),tool_selection_mode:A90.optional().default("inclusion").describe("Tool selection mode (defaults to 'inclusion')"),icon:U.string().nullable().optional().describe("Optional icon URL"),status:U.enum(["active","inactive"]).optional().default("active").describe("Initial status"),metadata:U.object({instructions:U.string().optional().describe("MCP server instructions")}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:U.array(U.object({connection_id:U.string().describe("Connection ID"),selected_tools:U.array(U.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools or full exclusion)"),selected_resources:U.array(U.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources)"),selected_prompts:U.array(U.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)")}),PZ1=U.object({title:U.string().min(1).max(255).optional().describe("New name"),description:U.string().nullable().optional().describe("New description (null to clear)"),tool_selection_mode:A90.optional().describe("New tool selection mode"),icon:U.string().nullable().optional().describe("New icon URL (null to clear)"),status:U.enum(["active","inactive"]).optional().describe("New status"),metadata:U.object({instructions:U.string().optional().describe("MCP server instructions")}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:U.array(U.object({connection_id:U.string().describe("Connection ID"),selected_tools:U.array(U.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools or full exclusion)"),selected_resources:U.array(U.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources)"),selected_prompts:U.array(U.string()).nullable().optional().describe("Selected prompt names (null/undefined = all prompts or full exclusion)")})).optional().describe("New connections (replaces existing)")})});var Ol6,Ll6,T90;var AZ1=S(()=>{r0();$6();gB();Ol6=U.object({data:MZ1.describe("Data for the new virtual MCP")}),Ll6=U.object({item:u7.describe("The created virtual MCP entity")}),T90=e0({name:"COLLECTION_VIRTUAL_MCP_CREATE",description:"Create a new MCP virtual MCP in the organization",inputSchema:Ol6,outputSchema:Ll6,handler:async(X,Y)=>{z1(Y);let Q=_1(Y);await Y.access.check();let J=d8(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 wl6(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 mK(X){return typeof X==="string"||typeof X==="number"}function E90(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 Ml6(X,Y){return X.connections.some((Q)=>Q.connection_id===Y)}function Cf(X,Y){if("conditions"in Y){let{operator:$,conditions:K}=Y;switch($){case"and":return K.every((H)=>Cf(X,H));case"or":return K.some((H)=>Cf(X,H));case"not":return!K.every((H)=>Cf(X,H));default:return!0}}let{field:Q,operator:J,value:G}=Y,W=Q.join(".");if(W==="connection_id"){if(J!=="eq"||typeof G!=="string")return!1;return Ml6(X,G)}let Z=E90(X,W);switch(J){case"eq":return Z===G;case"gt":return mK(Z)&&mK(G)&&Z>G;case"gte":return mK(Z)&&mK(G)&&Z>=G;case"lt":return mK(Z)&&mK(G)&&Z<G;case"lte":return mK(Z)&&mK(G)&&Z<=G;case"in":return Array.isArray(G)&&G.includes(Z);case"like":if(typeof Z!=="string"||typeof G!=="string")return!1;if(G.length>100)return!1;let $=wl6(G);return new RegExp(`^${$}$`,"i").test(Z);case"contains":if(typeof Z!=="string"||typeof G!=="string")return!1;return Z.toLowerCase().includes(G.toLowerCase());default:return!0}}function Pl6(X,Y){return[...X].sort((Q,J)=>{for(let G of Y){let W=G.field.join("."),Z=E90(Q,W),$=E90(J,W),K=0;if(Z==null&&$==null)continue;if(Z==null)K=G.nulls==="first"?-1:1;else if($==null)K=G.nulls==="first"?1:-1;else if(typeof Z==="string"&&typeof $==="string")K=Z.localeCompare($);else if(typeof Z==="number"&&typeof $==="number")K=Z-$;else K=String(Z).localeCompare(String($));if(K!==0)return G.direction==="desc"?-K:K}return 0})}var Al6,Tl6,j90;var TZ1=S(()=>{GG();$6();gB();Al6=nF,Tl6=iF(u7),j90=e0({name:"COLLECTION_VIRTUAL_MCP_LIST",description:"List all MCP virtual MCPs in the organization",inputSchema:Al6,outputSchema:Tl6,handler:async(X,Y)=>{await Y.access.check();let Q=_1(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,W=J?await Y.storage.virtualMcps.listByConnectionId(Q.id,J):await Y.storage.virtualMcps.list(Q.id);if(X.where)W=W.filter((V)=>Cf(V,X.where));if(X.orderBy&&X.orderBy.length>0)W=Pl6(W,X.orderBy);let Z=W.length,$=X.offset??0,K=X.limit??100,H=W.slice($,$+K),F=$+K<Z;return{items:H,totalCount:Z,hasMore:F}}})});var El6,jl6,C90;var EZ1=S(()=>{r0();$6();gB();El6=U.object({id:U.string().describe("ID of the virtual MCP to retrieve")}),jl6=U.object({item:u7.nullable().describe("The retrieved virtual MCP, or null if not found")}),C90=e0({name:"COLLECTION_VIRTUAL_MCP_GET",description:"Get an MCP virtual MCP by ID",inputSchema:El6,outputSchema:jl6,handler:async(X,Y)=>{z1(Y);let Q=_1(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 Cl6,Il6,I90;var jZ1=S(()=>{r0();$6();gB();Cl6=U.object({id:U.string().describe("ID of the virtual MCP to update"),data:PZ1.describe("Partial virtual MCP data to update")}),Il6=U.object({item:u7.describe("The updated virtual MCP entity")}),I90=e0({name:"COLLECTION_VIRTUAL_MCP_UPDATE",description:"Update an MCP virtual MCP",inputSchema:Cl6,outputSchema:Il6,handler:async(X,Y)=>{z1(Y);let Q=_1(Y);await Y.access.check();let J=d8(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 Rl6,Sl6,R90;var CZ1=S(()=>{r0();$6();gB();Rl6=U.object({id:U.string().describe("ID of the virtual MCP to delete")}),Sl6=U.object({item:u7.describe("The deleted virtual MCP entity")}),R90=e0({name:"COLLECTION_VIRTUAL_MCP_DELETE",description:"Delete an MCP virtual MCP",inputSchema:Rl6,outputSchema:Sl6,handler:async(X,Y)=>{z1(Y);let Q=_1(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 IZ1=S(()=>{AZ1();TZ1();EZ1();jZ1();CZ1()});var vl6,S90;var RZ1=S(()=>{$6();r0();vl6=U.object({id:U.string().optional().describe("Unique log identifier"),organizationId:U.string().describe("Organization ID"),connectionId:U.string().describe("Connection ID"),connectionTitle:U.string().describe("Connection display name"),toolName:U.string().describe("Name of the tool that was called"),input:U.record(U.string(),U.unknown()).describe("Redacted tool input"),output:U.record(U.string(),U.unknown()).describe("Redacted tool output"),isError:U.boolean().describe("Whether the call resulted in an error"),errorMessage:U.string().nullish().describe("Error message if applicable"),durationMs:U.number().describe("Call duration in milliseconds"),timestamp:U.string().describe("ISO 8601 timestamp of the call"),userId:U.string().nullish().describe("User who triggered the call"),requestId:U.string().describe("Unique request identifier"),userAgent:U.string().nullish().describe("Client identifier (x-mesh-client header)"),virtualMcpId:U.string().nullish().describe("Virtual MCP (Agent) ID if routed through an agent"),properties:U.record(U.string(),U.string()).nullish().describe("Custom key-value metadata attached to the log")}),S90=e0({name:"MONITORING_LOGS_LIST",description:"List monitoring logs for tool calls in the organization",inputSchema:U.object({connectionId:U.string().optional().describe("Filter by connection ID"),virtualMcpId:U.string().optional().describe("Filter by Virtual MCP (Agent) ID"),toolName:U.string().optional().describe("Filter by tool name"),isError:U.boolean().optional().describe("Filter by error status"),startDate:U.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:U.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)"),limit:U.number().default(100).describe("Maximum number of results"),offset:U.number().default(0).describe("Offset for pagination"),properties:U.record(U.string(),U.string()).optional().describe("Filter by exact property key=value matches"),propertyKeys:U.array(U.string()).optional().describe("Filter by logs that have these property keys"),propertyPatterns:U.record(U.string(),U.string()).optional().describe("Filter by property value patterns (SQL LIKE, use % as wildcard)")}),outputSchema:U.object({logs:U.array(vl6).describe("Array of monitoring logs"),total:U.number().describe("Total number of logs matching filters"),offset:U.number().describe("Current offset for pagination"),limit:U.number().describe("Current limit for pagination")}),handler:async(X,Y)=>{let Q=_1(Y),G=X.properties||X.propertyKeys||X.propertyPatterns?{properties:X.properties,propertyKeys:X.propertyKeys,propertyPatterns:X.propertyPatterns}:void 0,W={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},Z=await Y.storage.monitoring.query(W);return{logs:Z.logs.map(($)=>({...$,timestamp:$.timestamp instanceof Date?$.timestamp.toISOString():$.timestamp})),total:Z.total,offset:X.offset,limit:X.limit}}})});var k90;var SZ1=S(()=>{$6();r0();k90=e0({name:"MONITORING_STATS",description:"Get aggregated statistics for tool call monitoring",inputSchema:U.object({startDate:U.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:U.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)")}),outputSchema:U.object({totalCalls:U.number().describe("Total number of tool calls"),errorRate:U.number().describe("Error rate as a decimal (0 to 1)"),avgDurationMs:U.number().describe("Average call duration in milliseconds"),errorRatePercent:U.string().describe("Error rate as a percentage string")}),handler:async(X,Y)=>{let J={organizationId:_1(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 kZ1=S(()=>{RZ1();SZ1()});var v90;var vZ1=S(()=>{r0();$6();v90=e0({name:"ORGANIZATION_CREATE",description:"Create a new organization",inputSchema:U.object({slug:U.string().min(1).max(50).regex(/^[a-z0-9-]+$/,"Slug must be lowercase alphanumeric with hyphens"),name:U.string().min(1).max(255),description:U.string().optional()}),outputSchema:U.object({id:U.string(),name:U.string(),slug:U.string(),logo:U.string().nullable().optional(),metadata:U.any().optional(),createdAt:U.string().datetime().describe("ISO 8601 timestamp"),members:U.array(U.any()).optional()}),handler:async(X,Y)=>{z1(Y),await Y.access.check();let Q=d8(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 _90;var _Z1=S(()=>{r0();$6();_90=e0({name:"ORGANIZATION_LIST",description:"List all organizations user has access to",inputSchema:U.object({userId:U.string().optional()}),outputSchema:U.object({organizations:U.array(U.object({id:U.string(),name:U.string(),slug:U.string(),logo:U.string().nullable().optional(),metadata:U.any().optional(),createdAt:U.string().datetime().describe("ISO 8601 timestamp")}))}),handler:async(X,Y)=>{z1(Y),await Y.access.check();let Q=d8(Y),J=X.userId||Q;if(!J)throw Error("User ID required to list organizations");return{organizations:(await Y.boundAuth.organization.list(J)).map((W)=>({...W,createdAt:W.createdAt instanceof Date?W.createdAt.toISOString():W.createdAt}))}}})});var y90;var yZ1=S(()=>{r0();$6();y90=e0({name:"ORGANIZATION_GET",description:"Get organization details by slug or ID",inputSchema:U.object({}),outputSchema:U.object({id:U.string(),name:U.string(),slug:U.string(),logo:U.string().nullable().optional(),metadata:U.any().optional(),createdAt:U.string().datetime().describe("ISO 8601 timestamp"),members:U.array(U.any()).optional(),invitations:U.array(U.any()).optional()}),handler:async(X,Y)=>{z1(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((W)=>new Date(W.expiresAt)>J);return{...Q,invitations:G,createdAt:Q.createdAt instanceof Date?Q.createdAt.toISOString():Q.createdAt}}})});var b90;var bZ1=S(()=>{r0();$6();b90=e0({name:"ORGANIZATION_UPDATE",description:"Update an existing organization",inputSchema:U.object({id:U.string(),slug:U.string().min(1).max(50).regex(/^[a-z0-9-]+$/).optional(),name:U.string().min(1).max(255).optional(),description:U.string().optional()}),outputSchema:U.object({id:U.string(),name:U.string(),slug:U.string(),logo:U.string().nullable().optional(),metadata:U.any().optional(),createdAt:U.string().datetime().describe("ISO 8601 timestamp")}),handler:async(X,Y)=>{z1(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 f90;var fZ1=S(()=>{r0();$6();f90=e0({name:"ORGANIZATION_DELETE",description:"Delete an organization",inputSchema:U.object({id:U.string()}),outputSchema:U.object({success:U.boolean(),id:U.string()}),handler:async(X,Y)=>{return z1(Y),await Y.access.check(),await Y.boundAuth.organization.delete(X.id),{success:!0,id:X.id}}})});var bA;var h90=S(()=>{r0();bA=U.object({title:U.string(),url:U.string(),icon:U.string()})});var x90;var hZ1=S(()=>{r0();$6();h90();x90=e0({name:"ORGANIZATION_SETTINGS_GET",description:"Get organization-level settings",inputSchema:U.object({}),outputSchema:U.object({organizationId:U.string(),sidebar_items:U.array(bA).nullable().optional(),enabled_plugins:U.array(U.string()).nullable().optional(),createdAt:U.string().datetime().optional().describe("ISO 8601 timestamp"),updatedAt:U.string().datetime().optional().describe("ISO 8601 timestamp")}),handler:async(X,Y)=>{z1(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 g90;var xZ1=S(()=>{r0();$6();h90();g90=e0({name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization-level settings",inputSchema:U.object({organizationId:U.string(),sidebar_items:U.array(bA).optional(),enabled_plugins:U.array(U.string()).optional()}),outputSchema:U.object({organizationId:U.string(),sidebar_items:U.array(bA).nullable().optional(),enabled_plugins:U.array(U.string()).nullable().optional(),createdAt:U.string().datetime().describe("ISO 8601 timestamp"),updatedAt:U.string().datetime().describe("ISO 8601 timestamp")}),handler:async(X,Y)=>{if(z1(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 u90;var gZ1=S(()=>{r0();$6();u90=e0({name:"ORGANIZATION_MEMBER_ADD",description:"Add a member to an organization",inputSchema:U.object({organizationId:U.string().optional(),userId:U.string(),role:U.array(U.string())}),outputSchema:U.object({id:U.string(),organizationId:U.string(),userId:U.string(),role:U.union([U.string(),U.array(U.string())]),createdAt:U.string().datetime().describe("ISO 8601 timestamp")}),handler:async(X,Y)=>{z1(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 m90;var uZ1=S(()=>{r0();$6();m90=e0({name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove a member from an organization",inputSchema:U.object({organizationId:U.string().optional(),memberIdOrEmail:U.string()}),outputSchema:U.object({success:U.boolean(),memberIdOrEmail:U.string()}),handler:async(X,Y)=>{z1(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 l90;var mZ1=S(()=>{r0();$6();l90=e0({name:"ORGANIZATION_MEMBER_LIST",description:"List all members in an organization",inputSchema:U.object({limit:U.number().optional(),offset:U.number().optional()}),outputSchema:U.object({members:U.array(U.object({id:U.string(),organizationId:U.string(),userId:U.string(),role:U.string(),createdAt:U.string().datetime().describe("ISO 8601 timestamp"),user:U.object({id:U.string(),name:U.string(),email:U.string(),image:U.string().optional()}).optional()}))}),handler:async(X,Y)=>{z1(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((W)=>({...W,createdAt:W.createdAt instanceof Date?W.createdAt.toISOString():W.createdAt}))}}})});var d90;var lZ1=S(()=>{r0();$6();d90=e0({name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Update a member's role in an organization",inputSchema:U.object({organizationId:U.string().optional(),memberId:U.string(),role:U.array(U.string())}),outputSchema:U.object({id:U.string(),organizationId:U.string(),userId:U.string(),role:U.union([U.literal("admin"),U.literal("member"),U.literal("owner")]),createdAt:U.string().datetime().describe("ISO 8601 timestamp"),user:U.object({email:U.string(),name:U.string(),image:U.string().optional()})}),handler:async(X,Y)=>{z1(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 dZ1=S(()=>{vZ1();_Z1();yZ1();bZ1();fZ1();hZ1();xZ1();gZ1();uZ1();mZ1();lZ1()});var pZ1,m7,cZ1,nZ1;var aF=S(()=>{r0();pZ1=U.object({id:U.string().describe("Unique message ID"),threadId:U.string().describe("ID of the parent thread"),metadata:U.unknown().optional().describe("Optional message metadata"),parts:U.array(U.record(U.string(),U.unknown())).describe("Message content parts (AI SDK UIMessagePart format)"),role:U.enum(["user","assistant","system"]).describe("Message role"),createdAt:U.string().datetime().describe("Timestamp of creation"),updatedAt:U.string().datetime().describe("Timestamp of last update")}),m7=U.object({id:U.string().describe("Unique thread ID"),organizationId:U.string().describe("Organization this thread belongs to"),title:U.string().describe("Thread title"),description:U.string().nullable().describe("Thread description"),createdAt:U.string().datetime().describe("Timestamp of creation"),updatedAt:U.string().datetime().describe("Timestamp of last update"),hidden:U.boolean().optional().describe("Whether the thread is hidden"),createdBy:U.string().describe("User ID who created the thread"),updatedBy:U.string().nullable().describe("User ID who last updated the thread")}),cZ1=U.object({id:U.string().optional().describe("Optional custom ID for the thread"),title:U.string().describe("Thread title"),description:U.string().nullish().describe("Thread description")}),nZ1=U.object({title:U.string().optional().describe("New thread title"),description:U.string().nullish().describe("New thread description"),hidden:U.boolean().optional().describe("Whether the thread is hidden")})});var bl6,fl6,p90;var iZ1=S(()=>{r0();$6();aF();wZ();bl6=U.object({data:cZ1.describe("Data for the new thread (id is auto-generated if not provided)")}),fl6=U.object({item:m7.describe("The created thread entity")}),p90=e0({name:"COLLECTION_THREADS_CREATE",description:"Create a new thread in the organization",inputSchema:bl6,outputSchema:fl6,handler:async(X,Y)=>{z1(Y);let Q=_1(Y);await Y.access.check();let J=d8(Y);if(!J)throw Error("User ID required to create thread");let G=X.data.id??GX("thrd"),W=await Y.storage.threads.create({id:G,organizationId:Q.id,title:X.data.title,description:X.data.description,createdBy:J});return{item:{...W,hidden:W.hidden??!1}}}})});var hl6,xl6,c90;var aZ1=S(()=>{GG();$6();aF();r0();hl6=nF.extend({where:U.object({created_by:U.string().optional()}).optional()}),xl6=iF(m7),c90=e0({name:"COLLECTION_THREADS_LIST",description:"List all threads in the organization with filtering, sorting, and pagination",inputSchema:hl6,outputSchema:xl6,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=_1(Y),G=X.offset??0,W=X.limit??100,{threads:Z,total:$}=await Y.storage.threads.list(J.id,Q,{limit:W,offset:G}),K=G+W<$;return{items:Z.map((H)=>({...H,hidden:H.hidden??!1})),totalCount:$,hasMore:K}}})});var gl6,n90;var rZ1=S(()=>{GG();$6();aF();gl6=LA(m7),n90=e0({name:"COLLECTION_THREADS_GET",description:"Get thread details by ID",inputSchema:OA,outputSchema:gl6,handler:async(X,Y)=>{z1(Y);let Q=_1(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 ul6,ml6,i90;var oZ1=S(()=>{r0();$6();aF();ul6=U.object({id:U.string().describe("ID of the thread to update"),data:nZ1.describe("Partial thread data to update")}),ml6=U.object({item:m7.describe("The updated thread entity")}),i90=e0({name:"COLLECTION_THREADS_UPDATE",description:"Update an existing thread in the organization",inputSchema:ul6,outputSchema:ml6,handler:async(X,Y)=>{z1(Y);let Q=_1(Y);await Y.access.check();let J=d8(Y);if(!J)throw Error("User ID required to update thread");let{id:G,data:W}=X,Z=await Y.storage.threads.get(G);if(!Z||Z.organizationId!==Q.id)throw Error("Thread not found in organization");let $=await Y.storage.threads.update(G,{title:W.title,description:W.description,hidden:W.hidden,updatedBy:J});return{item:{...$,hidden:$.hidden??!1}}}})});var a90;var sZ1=S(()=>{GG();$6();aF();a90=e0({name:"COLLECTION_THREADS_DELETE",description:"Delete a thread",inputSchema:wA,outputSchema:MA(m7),handler:async(X,Y)=>{z1(Y);let Q=_1(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 ll6,dl6,r90;var tZ1=S(()=>{r0();$6();aF();ll6=U.object({threadId:U.string().describe("ID of the thread to list messages for"),limit:U.number().optional().describe("Maximum number of messages to return"),offset:U.number().optional().describe("Number of messages to skip")}),dl6=U.object({items:U.array(pZ1).describe("List of thread messages"),totalCount:U.number().describe("Total number of messages in the thread"),hasMore:U.boolean().describe("Whether there are more messages available")}),r90=e0({name:"COLLECTION_THREAD_MESSAGES_LIST",description:"List all messages for a specific thread",inputSchema:ll6,outputSchema:dl6,handler:async(X,Y)=>{let Q=_1(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,W=X.limit??100,{messages:Z,total:$}=await Y.storage.threads.listMessages(X.threadId,{limit:W,offset:G}),K=G+W<$;return{items:Z,totalCount:$,hasMore:K}}})});var eZ1=S(()=>{iZ1();aZ1();rZ1();oZ1();sZ1();tZ1()});var cl6,nl6,o90;var X$1=S(()=>{r0();$6();cl6=U.object({id:U.string().min(1)}),nl6=U.object({user:U.object({id:U.string(),name:U.string(),email:U.string(),image:U.string().nullable()}).nullable()}),o90=e0({name:"USER_GET",description:"Get a user by id (restricted to shared organizations)",inputSchema:cl6,outputSchema:nl6,handler:async(X,Y)=>{await Y.access.check(),z1(Y);let Q=d8(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 Y$1=S(()=>{X$1()});var J$1={};c1(J$1,{managementMCP:()=>s90,ALL_TOOLS:()=>Q$1});var Q$1,s90=(X)=>{let Y=Q$1.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 z71({name:"mcp-mesh-management",version:"1.0.0"}).withTools(Y).build()};var t90=S(()=>{B71();R71();wW1();ZZ1();FZ1();wZ1();IZ1();kZ1();dZ1();eZ1();Y$1();Q$1=[v90,_90,y90,b90,f90,x90,g90,u90,m90,l90,d90,Q90,H90,F90,U90,z90,B90,T90,j90,C90,I90,R90,HZ1,S90,k90,SY0,vY0,_Y0,kY0,D90,N90,O90,L90,w90,M90,P90,o90,eY0,X90,Y90,p90,c90,n90,i90,a90,r90]});function al6(X){return[{permissions:{self:["*"]},getTools:async()=>{let{ALL_TOOLS:Y}=await Promise.resolve().then(() => (t90(),J$1));return Y.map((Q)=>{return{name:Q.name,inputSchema:U.toJSONSchema(Q.inputSchema,{unrepresentable:"any"}),outputSchema:Q.outputSchema?U.toJSONSchema(Q.outputSchema,{unrepresentable:"any"}):void 0,description:Q.description}})},data:iX0(process.env.BASE_URL||"http://localhost:3000",X)},{data:nX0()},{data:cX0(X)}]}async function G$1(X,Y){try{let Q=MF(),J=new JA(process.env.ENCRYPTION_KEY||""),G=new GA(Q.db,J),W=al6(X);await Promise.all(W.map(async(Z)=>{let $=null;if(Z.permissions)$=(await WG.api.createApiKey({body:{name:`${Z.data.app_name??crypto.randomUUID()}-mcp`,userId:Y,permissions:Z.permissions,rateLimitEnabled:!1,metadata:{organization:{id:X},purpose:"default-org-connections"}}}))?.key;let K=await Z.getTools?.()??await RB({id:"pending",title:Z.data.title,connection_type:Z.data.connection_type,connection_url:Z.data.connection_url,connection_token:Z.data.connection_token,connection_headers:Z.data.connection_headers}).catch(()=>null),H=Z.data.id?Z.data.id.startsWith(`${X}_`)?Z.data.id:`${X}_${Z.data.id}`:void 0;await G.create({...Z.data,id:H,tools:K,organization_id:X,created_by:Y,connection_token:Z.data.connection_token??$})}))}catch(Q){console.error("Error creating default MCP connections:",Q)}}var W$1=S(()=>{YA();tM();XY0();YY0();Zf();r0();uB()});var e90,Z$1;var XQ0=S(()=>{e90=["owner","admin","user"],Z$1=["owner","admin"]});var rl6=(X)=>{return{defaultSSO:[{domain:X.domain,providerId:X.providerId,oidcConfig:{issuer:`https://login.microsoftonline.com/${X.MS_TENANT_ID}/v2.0`,pkce:!0,clientId:X.MS_CLIENT_ID,clientSecret:X.MS_CLIENT_SECRET,discoveryEndpoint:`https://login.microsoftonline.com/${X.MS_TENANT_ID}/v2.0/.well-known/openid-configuration`,authorizationEndpoint:`https://login.microsoftonline.com/${X.MS_TENANT_ID}/oauth2/v2.0/authorize`,tokenEndpoint:`https://login.microsoftonline.com/${X.MS_TENANT_ID}/oauth2/v2.0/token`,jwksEndpoint:`https://login.microsoftonline.com/${X.MS_TENANT_ID}/discovery/v2.0/keys`,userInfoEndpoint:"https://graph.microsoft.com/oidc/userinfo",tokenEndpointAuthentication:"client_secret_post",scopes:X.scopes,mapping:{id:"sub",email:"email",emailVerified:"email_verified",name:"name",image:"picture",extraFields:{emailVerified:"email_verified"}}}}]}},$$1=(X)=>{if(X.providerId==="microsoft")return rl6(X);throw Error(`Unsupported provider: ${X.providerId}`)};function ol6(X){return X.toLowerCase().trim().replace(/[^a-z0-9\s_-]+/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function sl6(){let X=Math.floor(Math.random()*H$1.length),Y=Math.floor(Math.random()*K$1.length),Q=H$1[X]??"deco",J=K$1[Y]??"studio";return`${Q}-${J}`}var K$1,H$1,tl6,el6,If,Xd6,Yd6,Qd6,F$1,WX,V$1=void 0,Jd6,Gd6,Wd6,WG;var uB=S(()=>{md();DD0();QO0();Si();ea();aO0();fS();QL0();tM();r60();a41();W$1();XQ0();K$1=["labs","agent","studio","workspace","systems","core","cloud","works"],H$1=["capybara","guarana","deco","samba","feijoada","capoeira","carnival"];tl6=Object.values(HO()).map((X)=>X.map((Y)=>Y.name)).flat(),el6={...wS,self:["*",...tl6]},If=W7(el6),Xd6=If.newRole({self:["*"],...mL.statements}),Yd6=If.newRole({self:["*"],...mL.statements}),Qd6=If.newRole({self:["*"],...mL.statements}),F$1=Object.values(HO()).map((X)=>X.map((Y)=>`self:${Y.name}`)).flat(),WX=oL.auth;if(WX.inviteEmailProviderId&&WX.emailProviders&&WX.emailProviders.length>0){let X=$y(WX.emailProviders,WX.inviteEmailProviderId);if(X){let Y=Zy(X);V$1=async(Q)=>{let J=Q.inviter.user?.name||Q.inviter.user?.email,G=`${process.env.BASE_URL||"http://localhost:3000"}/auth/accept-invitation?invitationId=${Q.invitation.id}`;await Y({to:Q.email,subject:`Invitation to join ${Q.organization.name}`,html:`
|
|
1184
|
+
`.execute(X)).rows[0]?.exists)await X4`CREATE ROLE ${X4.id(Q)} NOLOGIN`.execute(X);await X4`GRANT ${X4.id(Q)} TO CURRENT_USER`.execute(X),await X4`GRANT USAGE, CREATE ON SCHEMA ${X4.id(Y)} TO ${X4.id(Q)}`.execute(X),await X4`GRANT ALL ON ALL TABLES IN SCHEMA ${X4.id(Y)} TO ${X4.id(Q)}`.execute(X),await X4`GRANT ALL ON ALL SEQUENCES IN SCHEMA ${X4.id(Y)} TO ${X4.id(Q)}`.execute(X),await X4`ALTER DEFAULT PRIVILEGES IN SCHEMA ${X4.id(Y)} GRANT ALL ON TABLES TO ${X4.id(Q)}`.execute(X),await X4`ALTER DEFAULT PRIVILEGES IN SCHEMA ${X4.id(Y)} GRANT ALL ON SEQUENCES TO ${X4.id(Q)}`.execute(X),await X4`REVOKE ALL ON SCHEMA public FROM ${X4.id(Q)}`.execute(X)}async function Ul6(X,Y,Q,J){try{return await X.transaction().execute(async(G)=>{return await X4`SET LOCAL ROLE ${X4.id(Q)}`.execute(G),await X4`SET LOCAL search_path TO ${X4.id(Y)}`.execute(G),await X4.raw(J).execute(G)})}catch(G){if(Vl6(G))return await ql6(X,Y,Q),await X.transaction().execute(async(W)=>{return await X4`SET LOCAL ROLE ${X4.id(Q)}`.execute(W),await X4`SET LOCAL search_path TO ${X4.id(Y)}`.execute(W),await X4.raw(J).execute(W)});throw G}}var Zl6,Kl6,HZ1;var FZ1=S(()=>{r0();$6();Zl6=U.object({results:U.array(U.unknown()).optional(),success:U.boolean().optional()});Kl6=U.object({sql:U.string().describe("The SQL query to run"),params:U.array(U.any()).describe("The parameters to pass to the SQL query").optional()});HZ1=e0({name:"DATABASES_RUN_SQL",description:"Run a SQL query against the database",inputSchema:Kl6,outputSchema:U.object({result:U.array(Zl6)}),handler:async(X,Y)=>{z1(Y),await Y.access.check();let Q=$l6(X.sql,X.params||[]);if(!Y.connectionId)throw Error("Connection context required for database access");let J=Hl6(Y.connectionId),G=Fl6(Y.connectionId);return{result:[{results:(await Ul6(Y.db,J,G,Q)).rows,success:!0}]}}})});var VZ1,Bl6,qZ1;var EZ=S(()=>{r0();Mf();VZ1=U.object({connectionId:U.string().optional().describe("Filter subscriptions by connection ID (optional)")}),Bl6=U.object({id:U.string().describe("Subscription ID"),connectionId:U.string().describe("Subscriber connection ID"),eventType:U.string().describe("Event type pattern"),publisher:U.string().nullable().describe("Publisher connection filter (null = all publishers)"),filter:U.string().nullable().describe("JSONPath filter expression"),enabled:U.boolean().describe("Whether subscription is enabled"),createdAt:U.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:U.string().datetime().describe("Updated timestamp (ISO 8601)")}),qZ1=U.object({subscriptions:U.array(Bl6).describe("List of subscriptions")})});var D90;var UZ1=S(()=>{$6();EZ();D90=e0({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:PA,outputSchema:AA,handler:async(X,Y)=>{z1(Y);let Q=_1(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 N90;var zZ1=S(()=>{$6();EZ();N90=e0({name:"EVENT_SUBSCRIBE",description:"Subscribe to events of a specific type. The subscriber is automatically set to the caller's connection.",inputSchema:TA,outputSchema:EA,handler:async(X,Y)=>{z1(Y);let Q=_1(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 O90;var BZ1=S(()=>{$6();EZ();O90=e0({name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events by removing a subscription.",inputSchema:IA,outputSchema:RA,handler:async(X,Y)=>{z1(Y);let Q=_1(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 L90;var DZ1=S(()=>{$6();EZ();L90=e0({name:"EVENT_CANCEL",description:"Cancel a recurring event to stop future deliveries. Only the publisher can cancel their own events.",inputSchema:SA,outputSchema:kA,handler:async(X,Y)=>{z1(Y);let Q=_1(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 w90;var NZ1=S(()=>{$6();EZ();w90=e0({name:"EVENT_ACK",description:"Acknowledge delivery of an event. Call after successfully processing an event received via ON_EVENTS with retryAfter.",inputSchema:vA,outputSchema:_A,handler:async(X,Y)=>{z1(Y);let Q=_1(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 M90;var OZ1=S(()=>{$6();EZ();M90=e0({name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions, optionally filtered by connection ID.",inputSchema:VZ1,outputSchema:qZ1,handler:async(X,Y)=>{z1(Y);let Q=_1(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 P90;var LZ1=S(()=>{$6();EZ();P90=e0({name:"EVENT_SYNC_SUBSCRIPTIONS",description:"Sync subscriptions to desired state. Creates new, deletes removed, updates changed filters. Subscriptions are identified by (eventType, publisher).",inputSchema:jA,outputSchema:CA,handler:async(X,Y)=>{z1(Y);let Q=_1(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((W)=>({id:W.id,connectionId:W.connectionId,eventType:W.eventType,publisher:W.publisher,filter:W.filter,enabled:W.enabled,createdAt:W.createdAt instanceof Date?W.createdAt.toISOString():W.createdAt,updatedAt:W.updatedAt instanceof Date?W.updatedAt.toISOString():W.updatedAt}))}}})});var wZ1=S(()=>{UZ1();zZ1();BZ1();DZ1();NZ1();OZ1();LZ1();EZ()});var A90,Nl6,u7,MZ1,PZ1;var gB=S(()=>{r0();A90=U.enum(["inclusion","exclusion"]).describe("Tool selection mode: 'inclusion' = include selected (default), 'exclusion' = exclude selected"),Nl6=U.object({connection_id:U.string().describe("Connection ID"),selected_tools:U.array(U.string()).nullable().describe("Selected tool names. With 'inclusion' mode: null = all tools included. With 'exclusion' mode: null = entire connection excluded"),selected_resources:U.array(U.string()).nullable().describe("Selected resource URIs or patterns. Supports * and ** wildcards for pattern matching. With 'inclusion' mode: null = all resources included."),selected_prompts:U.array(U.string()).nullable().describe("Selected prompt names. With 'inclusion' mode: null = all prompts included. With 'exclusion' mode: null = entire connection excluded.")}),u7=U.object({id:U.string().describe("Unique identifier for the virtual MCP"),title:U.string().describe("Human-readable name for the virtual MCP"),description:U.string().nullable().describe("Description of the virtual MCP"),icon:U.string().nullable().optional().describe("Icon URL for the virtual MCP"),created_at:U.string().describe("When the virtual MCP was created"),updated_at:U.string().describe("When the virtual MCP was last updated"),created_by:U.string().describe("User ID who created the virtual MCP"),updated_by:U.string().optional().describe("User ID who last updated the virtual MCP"),organization_id:U.string().describe("Organization ID this virtual MCP belongs to"),tool_selection_mode:A90.describe("Tool selection mode: 'inclusion' = include selected, 'exclusion' = exclude selected"),status:U.enum(["active","inactive"]).describe("Current status"),metadata:U.object({instructions:U.string().optional().describe("MCP server instructions")}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:U.array(Nl6).describe("Connections with their selected tools (behavior depends on tool_selection_mode)")}),MZ1=U.object({title:U.string().min(1).max(255).describe("Name for the virtual MCP"),description:U.string().nullable().optional().describe("Optional description"),tool_selection_mode:A90.optional().default("inclusion").describe("Tool selection mode (defaults to 'inclusion')"),icon:U.string().nullable().optional().describe("Optional icon URL"),status:U.enum(["active","inactive"]).optional().default("active").describe("Initial status"),metadata:U.object({instructions:U.string().optional().describe("MCP server instructions")}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:U.array(U.object({connection_id:U.string().describe("Connection ID"),selected_tools:U.array(U.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools or full exclusion)"),selected_resources:U.array(U.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources)"),selected_prompts:U.array(U.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)")}),PZ1=U.object({title:U.string().min(1).max(255).optional().describe("New name"),description:U.string().nullable().optional().describe("New description (null to clear)"),tool_selection_mode:A90.optional().describe("New tool selection mode"),icon:U.string().nullable().optional().describe("New icon URL (null to clear)"),status:U.enum(["active","inactive"]).optional().describe("New status"),metadata:U.object({instructions:U.string().optional().describe("MCP server instructions")}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:U.array(U.object({connection_id:U.string().describe("Connection ID"),selected_tools:U.array(U.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools or full exclusion)"),selected_resources:U.array(U.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources)"),selected_prompts:U.array(U.string()).nullable().optional().describe("Selected prompt names (null/undefined = all prompts or full exclusion)")})).optional().describe("New connections (replaces existing)")})});var Ol6,Ll6,T90;var AZ1=S(()=>{r0();$6();gB();Ol6=U.object({data:MZ1.describe("Data for the new virtual MCP")}),Ll6=U.object({item:u7.describe("The created virtual MCP entity")}),T90=e0({name:"COLLECTION_VIRTUAL_MCP_CREATE",description:"Create a new MCP virtual MCP in the organization",inputSchema:Ol6,outputSchema:Ll6,handler:async(X,Y)=>{z1(Y);let Q=_1(Y);await Y.access.check();let J=d8(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 wl6(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 mK(X){return typeof X==="string"||typeof X==="number"}function E90(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 Ml6(X,Y){return X.connections.some((Q)=>Q.connection_id===Y)}function Cf(X,Y){if("conditions"in Y){let{operator:$,conditions:K}=Y;switch($){case"and":return K.every((H)=>Cf(X,H));case"or":return K.some((H)=>Cf(X,H));case"not":return!K.every((H)=>Cf(X,H));default:return!0}}let{field:Q,operator:J,value:G}=Y,W=Q.join(".");if(W==="connection_id"){if(J!=="eq"||typeof G!=="string")return!1;return Ml6(X,G)}let Z=E90(X,W);switch(J){case"eq":return Z===G;case"gt":return mK(Z)&&mK(G)&&Z>G;case"gte":return mK(Z)&&mK(G)&&Z>=G;case"lt":return mK(Z)&&mK(G)&&Z<G;case"lte":return mK(Z)&&mK(G)&&Z<=G;case"in":return Array.isArray(G)&&G.includes(Z);case"like":if(typeof Z!=="string"||typeof G!=="string")return!1;if(G.length>100)return!1;let $=wl6(G);return new RegExp(`^${$}$`,"i").test(Z);case"contains":if(typeof Z!=="string"||typeof G!=="string")return!1;return Z.toLowerCase().includes(G.toLowerCase());default:return!0}}function Pl6(X,Y){return[...X].sort((Q,J)=>{for(let G of Y){let W=G.field.join("."),Z=E90(Q,W),$=E90(J,W),K=0;if(Z==null&&$==null)continue;if(Z==null)K=G.nulls==="first"?-1:1;else if($==null)K=G.nulls==="first"?1:-1;else if(typeof Z==="string"&&typeof $==="string")K=Z.localeCompare($);else if(typeof Z==="number"&&typeof $==="number")K=Z-$;else K=String(Z).localeCompare(String($));if(K!==0)return G.direction==="desc"?-K:K}return 0})}var Al6,Tl6,j90;var TZ1=S(()=>{GG();$6();gB();Al6=nF,Tl6=iF(u7),j90=e0({name:"COLLECTION_VIRTUAL_MCP_LIST",description:"List all MCP virtual MCPs in the organization",inputSchema:Al6,outputSchema:Tl6,handler:async(X,Y)=>{await Y.access.check();let Q=_1(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,W=J?await Y.storage.virtualMcps.listByConnectionId(Q.id,J):await Y.storage.virtualMcps.list(Q.id);if(X.where)W=W.filter((V)=>Cf(V,X.where));if(X.orderBy&&X.orderBy.length>0)W=Pl6(W,X.orderBy);let Z=W.length,$=X.offset??0,K=X.limit??100,H=W.slice($,$+K),F=$+K<Z;return{items:H,totalCount:Z,hasMore:F}}})});var El6,jl6,C90;var EZ1=S(()=>{r0();$6();gB();El6=U.object({id:U.string().describe("ID of the virtual MCP to retrieve")}),jl6=U.object({item:u7.nullable().describe("The retrieved virtual MCP, or null if not found")}),C90=e0({name:"COLLECTION_VIRTUAL_MCP_GET",description:"Get an MCP virtual MCP by ID",inputSchema:El6,outputSchema:jl6,handler:async(X,Y)=>{z1(Y);let Q=_1(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 Cl6,Il6,I90;var jZ1=S(()=>{r0();$6();gB();Cl6=U.object({id:U.string().describe("ID of the virtual MCP to update"),data:PZ1.describe("Partial virtual MCP data to update")}),Il6=U.object({item:u7.describe("The updated virtual MCP entity")}),I90=e0({name:"COLLECTION_VIRTUAL_MCP_UPDATE",description:"Update an MCP virtual MCP",inputSchema:Cl6,outputSchema:Il6,handler:async(X,Y)=>{z1(Y);let Q=_1(Y);await Y.access.check();let J=d8(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 Rl6,Sl6,R90;var CZ1=S(()=>{r0();$6();gB();Rl6=U.object({id:U.string().describe("ID of the virtual MCP to delete")}),Sl6=U.object({item:u7.describe("The deleted virtual MCP entity")}),R90=e0({name:"COLLECTION_VIRTUAL_MCP_DELETE",description:"Delete an MCP virtual MCP",inputSchema:Rl6,outputSchema:Sl6,handler:async(X,Y)=>{z1(Y);let Q=_1(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 IZ1=S(()=>{AZ1();TZ1();EZ1();jZ1();CZ1()});var vl6,S90;var RZ1=S(()=>{$6();r0();vl6=U.object({id:U.string().optional().describe("Unique log identifier"),organizationId:U.string().describe("Organization ID"),connectionId:U.string().describe("Connection ID"),connectionTitle:U.string().describe("Connection display name"),toolName:U.string().describe("Name of the tool that was called"),input:U.record(U.string(),U.unknown()).describe("Redacted tool input"),output:U.record(U.string(),U.unknown()).describe("Redacted tool output"),isError:U.boolean().describe("Whether the call resulted in an error"),errorMessage:U.string().nullish().describe("Error message if applicable"),durationMs:U.number().describe("Call duration in milliseconds"),timestamp:U.string().describe("ISO 8601 timestamp of the call"),userId:U.string().nullish().describe("User who triggered the call"),requestId:U.string().describe("Unique request identifier"),userAgent:U.string().nullish().describe("Client identifier (x-mesh-client header)"),virtualMcpId:U.string().nullish().describe("Virtual MCP (Agent) ID if routed through an agent"),properties:U.record(U.string(),U.string()).nullish().describe("Custom key-value metadata attached to the log")}),S90=e0({name:"MONITORING_LOGS_LIST",description:"List monitoring logs for tool calls in the organization",inputSchema:U.object({connectionId:U.string().optional().describe("Filter by connection ID"),virtualMcpId:U.string().optional().describe("Filter by Virtual MCP (Agent) ID"),toolName:U.string().optional().describe("Filter by tool name"),isError:U.boolean().optional().describe("Filter by error status"),startDate:U.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:U.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)"),limit:U.number().default(10).describe("Maximum number of results"),offset:U.number().default(0).describe("Offset for pagination"),properties:U.record(U.string(),U.string()).optional().describe("Filter by exact property key=value matches"),propertyKeys:U.array(U.string()).optional().describe("Filter by logs that have these property keys"),propertyPatterns:U.record(U.string(),U.string()).optional().describe("Filter by property value patterns (SQL LIKE, use % as wildcard)")}),outputSchema:U.object({logs:U.array(vl6).describe("Array of monitoring logs"),total:U.number().describe("Total number of logs matching filters"),offset:U.number().describe("Current offset for pagination"),limit:U.number().describe("Current limit for pagination")}),handler:async(X,Y)=>{let Q=_1(Y),G=X.properties||X.propertyKeys||X.propertyPatterns?{properties:X.properties,propertyKeys:X.propertyKeys,propertyPatterns:X.propertyPatterns}:void 0,W={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},Z=await Y.storage.monitoring.query(W);return{logs:Z.logs.map(($)=>({...$,timestamp:$.timestamp instanceof Date?$.timestamp.toISOString():$.timestamp})),total:Z.total,offset:X.offset,limit:X.limit}}})});var k90;var SZ1=S(()=>{$6();r0();k90=e0({name:"MONITORING_STATS",description:"Get aggregated statistics for tool call monitoring",inputSchema:U.object({startDate:U.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:U.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)")}),outputSchema:U.object({totalCalls:U.number().describe("Total number of tool calls"),errorRate:U.number().describe("Error rate as a decimal (0 to 1)"),avgDurationMs:U.number().describe("Average call duration in milliseconds"),errorRatePercent:U.string().describe("Error rate as a percentage string")}),handler:async(X,Y)=>{let J={organizationId:_1(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 kZ1=S(()=>{RZ1();SZ1()});var v90;var vZ1=S(()=>{r0();$6();v90=e0({name:"ORGANIZATION_CREATE",description:"Create a new organization",inputSchema:U.object({slug:U.string().min(1).max(50).regex(/^[a-z0-9-]+$/,"Slug must be lowercase alphanumeric with hyphens"),name:U.string().min(1).max(255),description:U.string().optional()}),outputSchema:U.object({id:U.string(),name:U.string(),slug:U.string(),logo:U.string().nullable().optional(),metadata:U.any().optional(),createdAt:U.string().datetime().describe("ISO 8601 timestamp"),members:U.array(U.any()).optional()}),handler:async(X,Y)=>{z1(Y),await Y.access.check();let Q=d8(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 _90;var _Z1=S(()=>{r0();$6();_90=e0({name:"ORGANIZATION_LIST",description:"List all organizations user has access to",inputSchema:U.object({userId:U.string().optional()}),outputSchema:U.object({organizations:U.array(U.object({id:U.string(),name:U.string(),slug:U.string(),logo:U.string().nullable().optional(),metadata:U.any().optional(),createdAt:U.string().datetime().describe("ISO 8601 timestamp")}))}),handler:async(X,Y)=>{z1(Y),await Y.access.check();let Q=d8(Y),J=X.userId||Q;if(!J)throw Error("User ID required to list organizations");return{organizations:(await Y.boundAuth.organization.list(J)).map((W)=>({...W,createdAt:W.createdAt instanceof Date?W.createdAt.toISOString():W.createdAt}))}}})});var y90;var yZ1=S(()=>{r0();$6();y90=e0({name:"ORGANIZATION_GET",description:"Get organization details by slug or ID",inputSchema:U.object({}),outputSchema:U.object({id:U.string(),name:U.string(),slug:U.string(),logo:U.string().nullable().optional(),metadata:U.any().optional(),createdAt:U.string().datetime().describe("ISO 8601 timestamp"),members:U.array(U.any()).optional(),invitations:U.array(U.any()).optional()}),handler:async(X,Y)=>{z1(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((W)=>new Date(W.expiresAt)>J);return{...Q,invitations:G,createdAt:Q.createdAt instanceof Date?Q.createdAt.toISOString():Q.createdAt}}})});var b90;var bZ1=S(()=>{r0();$6();b90=e0({name:"ORGANIZATION_UPDATE",description:"Update an existing organization",inputSchema:U.object({id:U.string(),slug:U.string().min(1).max(50).regex(/^[a-z0-9-]+$/).optional(),name:U.string().min(1).max(255).optional(),description:U.string().optional()}),outputSchema:U.object({id:U.string(),name:U.string(),slug:U.string(),logo:U.string().nullable().optional(),metadata:U.any().optional(),createdAt:U.string().datetime().describe("ISO 8601 timestamp")}),handler:async(X,Y)=>{z1(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 f90;var fZ1=S(()=>{r0();$6();f90=e0({name:"ORGANIZATION_DELETE",description:"Delete an organization",inputSchema:U.object({id:U.string()}),outputSchema:U.object({success:U.boolean(),id:U.string()}),handler:async(X,Y)=>{return z1(Y),await Y.access.check(),await Y.boundAuth.organization.delete(X.id),{success:!0,id:X.id}}})});var bA;var h90=S(()=>{r0();bA=U.object({title:U.string(),url:U.string(),icon:U.string()})});var x90;var hZ1=S(()=>{r0();$6();h90();x90=e0({name:"ORGANIZATION_SETTINGS_GET",description:"Get organization-level settings",inputSchema:U.object({}),outputSchema:U.object({organizationId:U.string(),sidebar_items:U.array(bA).nullable().optional(),enabled_plugins:U.array(U.string()).nullable().optional(),createdAt:U.string().datetime().optional().describe("ISO 8601 timestamp"),updatedAt:U.string().datetime().optional().describe("ISO 8601 timestamp")}),handler:async(X,Y)=>{z1(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 g90;var xZ1=S(()=>{r0();$6();h90();g90=e0({name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization-level settings",inputSchema:U.object({organizationId:U.string(),sidebar_items:U.array(bA).optional(),enabled_plugins:U.array(U.string()).optional()}),outputSchema:U.object({organizationId:U.string(),sidebar_items:U.array(bA).nullable().optional(),enabled_plugins:U.array(U.string()).nullable().optional(),createdAt:U.string().datetime().describe("ISO 8601 timestamp"),updatedAt:U.string().datetime().describe("ISO 8601 timestamp")}),handler:async(X,Y)=>{if(z1(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 u90;var gZ1=S(()=>{r0();$6();u90=e0({name:"ORGANIZATION_MEMBER_ADD",description:"Add a member to an organization",inputSchema:U.object({organizationId:U.string().optional(),userId:U.string(),role:U.array(U.string())}),outputSchema:U.object({id:U.string(),organizationId:U.string(),userId:U.string(),role:U.union([U.string(),U.array(U.string())]),createdAt:U.string().datetime().describe("ISO 8601 timestamp")}),handler:async(X,Y)=>{z1(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 m90;var uZ1=S(()=>{r0();$6();m90=e0({name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove a member from an organization",inputSchema:U.object({organizationId:U.string().optional(),memberIdOrEmail:U.string()}),outputSchema:U.object({success:U.boolean(),memberIdOrEmail:U.string()}),handler:async(X,Y)=>{z1(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 l90;var mZ1=S(()=>{r0();$6();l90=e0({name:"ORGANIZATION_MEMBER_LIST",description:"List all members in an organization",inputSchema:U.object({limit:U.number().optional(),offset:U.number().optional()}),outputSchema:U.object({members:U.array(U.object({id:U.string(),organizationId:U.string(),userId:U.string(),role:U.string(),createdAt:U.string().datetime().describe("ISO 8601 timestamp"),user:U.object({id:U.string(),name:U.string(),email:U.string(),image:U.string().optional()}).optional()}))}),handler:async(X,Y)=>{z1(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((W)=>({...W,createdAt:W.createdAt instanceof Date?W.createdAt.toISOString():W.createdAt}))}}})});var d90;var lZ1=S(()=>{r0();$6();d90=e0({name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Update a member's role in an organization",inputSchema:U.object({organizationId:U.string().optional(),memberId:U.string(),role:U.array(U.string())}),outputSchema:U.object({id:U.string(),organizationId:U.string(),userId:U.string(),role:U.union([U.literal("admin"),U.literal("member"),U.literal("owner")]),createdAt:U.string().datetime().describe("ISO 8601 timestamp"),user:U.object({email:U.string(),name:U.string(),image:U.string().optional()})}),handler:async(X,Y)=>{z1(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 dZ1=S(()=>{vZ1();_Z1();yZ1();bZ1();fZ1();hZ1();xZ1();gZ1();uZ1();mZ1();lZ1()});var pZ1,m7,cZ1,nZ1;var aF=S(()=>{r0();pZ1=U.object({id:U.string().describe("Unique message ID"),threadId:U.string().describe("ID of the parent thread"),metadata:U.unknown().optional().describe("Optional message metadata"),parts:U.array(U.record(U.string(),U.unknown())).describe("Message content parts (AI SDK UIMessagePart format)"),role:U.enum(["user","assistant","system"]).describe("Message role"),createdAt:U.string().datetime().describe("Timestamp of creation"),updatedAt:U.string().datetime().describe("Timestamp of last update")}),m7=U.object({id:U.string().describe("Unique thread ID"),organizationId:U.string().describe("Organization this thread belongs to"),title:U.string().describe("Thread title"),description:U.string().nullable().describe("Thread description"),createdAt:U.string().datetime().describe("Timestamp of creation"),updatedAt:U.string().datetime().describe("Timestamp of last update"),hidden:U.boolean().optional().describe("Whether the thread is hidden"),createdBy:U.string().describe("User ID who created the thread"),updatedBy:U.string().nullable().describe("User ID who last updated the thread")}),cZ1=U.object({id:U.string().optional().describe("Optional custom ID for the thread"),title:U.string().describe("Thread title"),description:U.string().nullish().describe("Thread description")}),nZ1=U.object({title:U.string().optional().describe("New thread title"),description:U.string().nullish().describe("New thread description"),hidden:U.boolean().optional().describe("Whether the thread is hidden")})});var bl6,fl6,p90;var iZ1=S(()=>{r0();$6();aF();wZ();bl6=U.object({data:cZ1.describe("Data for the new thread (id is auto-generated if not provided)")}),fl6=U.object({item:m7.describe("The created thread entity")}),p90=e0({name:"COLLECTION_THREADS_CREATE",description:"Create a new thread in the organization",inputSchema:bl6,outputSchema:fl6,handler:async(X,Y)=>{z1(Y);let Q=_1(Y);await Y.access.check();let J=d8(Y);if(!J)throw Error("User ID required to create thread");let G=X.data.id??GX("thrd"),W=await Y.storage.threads.create({id:G,organizationId:Q.id,title:X.data.title,description:X.data.description,createdBy:J});return{item:{...W,hidden:W.hidden??!1}}}})});var hl6,xl6,c90;var aZ1=S(()=>{GG();$6();aF();r0();hl6=nF.extend({where:U.object({created_by:U.string().optional()}).optional()}),xl6=iF(m7),c90=e0({name:"COLLECTION_THREADS_LIST",description:"List all threads in the organization with filtering, sorting, and pagination",inputSchema:hl6,outputSchema:xl6,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=_1(Y),G=X.offset??0,W=X.limit??100,{threads:Z,total:$}=await Y.storage.threads.list(J.id,Q,{limit:W,offset:G}),K=G+W<$;return{items:Z.map((H)=>({...H,hidden:H.hidden??!1})),totalCount:$,hasMore:K}}})});var gl6,n90;var rZ1=S(()=>{GG();$6();aF();gl6=LA(m7),n90=e0({name:"COLLECTION_THREADS_GET",description:"Get thread details by ID",inputSchema:OA,outputSchema:gl6,handler:async(X,Y)=>{z1(Y);let Q=_1(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 ul6,ml6,i90;var oZ1=S(()=>{r0();$6();aF();ul6=U.object({id:U.string().describe("ID of the thread to update"),data:nZ1.describe("Partial thread data to update")}),ml6=U.object({item:m7.describe("The updated thread entity")}),i90=e0({name:"COLLECTION_THREADS_UPDATE",description:"Update an existing thread in the organization",inputSchema:ul6,outputSchema:ml6,handler:async(X,Y)=>{z1(Y);let Q=_1(Y);await Y.access.check();let J=d8(Y);if(!J)throw Error("User ID required to update thread");let{id:G,data:W}=X,Z=await Y.storage.threads.get(G);if(!Z||Z.organizationId!==Q.id)throw Error("Thread not found in organization");let $=await Y.storage.threads.update(G,{title:W.title,description:W.description,hidden:W.hidden,updatedBy:J});return{item:{...$,hidden:$.hidden??!1}}}})});var a90;var sZ1=S(()=>{GG();$6();aF();a90=e0({name:"COLLECTION_THREADS_DELETE",description:"Delete a thread",inputSchema:wA,outputSchema:MA(m7),handler:async(X,Y)=>{z1(Y);let Q=_1(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 ll6,dl6,r90;var tZ1=S(()=>{r0();$6();aF();ll6=U.object({threadId:U.string().describe("ID of the thread to list messages for"),limit:U.number().optional().describe("Maximum number of messages to return"),offset:U.number().optional().describe("Number of messages to skip")}),dl6=U.object({items:U.array(pZ1).describe("List of thread messages"),totalCount:U.number().describe("Total number of messages in the thread"),hasMore:U.boolean().describe("Whether there are more messages available")}),r90=e0({name:"COLLECTION_THREAD_MESSAGES_LIST",description:"List all messages for a specific thread",inputSchema:ll6,outputSchema:dl6,handler:async(X,Y)=>{let Q=_1(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,W=X.limit??100,{messages:Z,total:$}=await Y.storage.threads.listMessages(X.threadId,{limit:W,offset:G}),K=G+W<$;return{items:Z,totalCount:$,hasMore:K}}})});var eZ1=S(()=>{iZ1();aZ1();rZ1();oZ1();sZ1();tZ1()});var cl6,nl6,o90;var X$1=S(()=>{r0();$6();cl6=U.object({id:U.string().min(1)}),nl6=U.object({user:U.object({id:U.string(),name:U.string(),email:U.string(),image:U.string().nullable()}).nullable()}),o90=e0({name:"USER_GET",description:"Get a user by id (restricted to shared organizations)",inputSchema:cl6,outputSchema:nl6,handler:async(X,Y)=>{await Y.access.check(),z1(Y);let Q=d8(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 Y$1=S(()=>{X$1()});var J$1={};c1(J$1,{managementMCP:()=>s90,ALL_TOOLS:()=>Q$1});var Q$1,s90=(X)=>{let Y=Q$1.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 z71({name:"mcp-mesh-management",version:"1.0.0"}).withTools(Y).build()};var t90=S(()=>{B71();R71();wW1();ZZ1();FZ1();wZ1();IZ1();kZ1();dZ1();eZ1();Y$1();Q$1=[v90,_90,y90,b90,f90,x90,g90,u90,m90,l90,d90,Q90,H90,F90,U90,z90,B90,T90,j90,C90,I90,R90,HZ1,S90,k90,SY0,vY0,_Y0,kY0,D90,N90,O90,L90,w90,M90,P90,o90,eY0,X90,Y90,p90,c90,n90,i90,a90,r90]});function al6(X){return[{permissions:{self:["*"]},getTools:async()=>{let{ALL_TOOLS:Y}=await Promise.resolve().then(() => (t90(),J$1));return Y.map((Q)=>{return{name:Q.name,inputSchema:U.toJSONSchema(Q.inputSchema,{unrepresentable:"any"}),outputSchema:Q.outputSchema?U.toJSONSchema(Q.outputSchema,{unrepresentable:"any"}):void 0,description:Q.description}})},data:iX0(process.env.BASE_URL||"http://localhost:3000",X)},{data:nX0()},{data:cX0(X)}]}async function G$1(X,Y){try{let Q=MF(),J=new JA(process.env.ENCRYPTION_KEY||""),G=new GA(Q.db,J),W=al6(X);await Promise.all(W.map(async(Z)=>{let $=null;if(Z.permissions)$=(await WG.api.createApiKey({body:{name:`${Z.data.app_name??crypto.randomUUID()}-mcp`,userId:Y,permissions:Z.permissions,rateLimitEnabled:!1,metadata:{organization:{id:X},purpose:"default-org-connections"}}}))?.key;let K=await Z.getTools?.()??await RB({id:"pending",title:Z.data.title,connection_type:Z.data.connection_type,connection_url:Z.data.connection_url,connection_token:Z.data.connection_token,connection_headers:Z.data.connection_headers}).catch(()=>null),H=Z.data.id?Z.data.id.startsWith(`${X}_`)?Z.data.id:`${X}_${Z.data.id}`:void 0;await G.create({...Z.data,id:H,tools:K,organization_id:X,created_by:Y,connection_token:Z.data.connection_token??$})}))}catch(Q){console.error("Error creating default MCP connections:",Q)}}var W$1=S(()=>{YA();tM();XY0();YY0();Zf();r0();uB()});var e90,Z$1;var XQ0=S(()=>{e90=["owner","admin","user"],Z$1=["owner","admin"]});var rl6=(X)=>{return{defaultSSO:[{domain:X.domain,providerId:X.providerId,oidcConfig:{issuer:`https://login.microsoftonline.com/${X.MS_TENANT_ID}/v2.0`,pkce:!0,clientId:X.MS_CLIENT_ID,clientSecret:X.MS_CLIENT_SECRET,discoveryEndpoint:`https://login.microsoftonline.com/${X.MS_TENANT_ID}/v2.0/.well-known/openid-configuration`,authorizationEndpoint:`https://login.microsoftonline.com/${X.MS_TENANT_ID}/oauth2/v2.0/authorize`,tokenEndpoint:`https://login.microsoftonline.com/${X.MS_TENANT_ID}/oauth2/v2.0/token`,jwksEndpoint:`https://login.microsoftonline.com/${X.MS_TENANT_ID}/discovery/v2.0/keys`,userInfoEndpoint:"https://graph.microsoft.com/oidc/userinfo",tokenEndpointAuthentication:"client_secret_post",scopes:X.scopes,mapping:{id:"sub",email:"email",emailVerified:"email_verified",name:"name",image:"picture",extraFields:{emailVerified:"email_verified"}}}}]}},$$1=(X)=>{if(X.providerId==="microsoft")return rl6(X);throw Error(`Unsupported provider: ${X.providerId}`)};function ol6(X){return X.toLowerCase().trim().replace(/[^a-z0-9\s_-]+/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function sl6(){let X=Math.floor(Math.random()*H$1.length),Y=Math.floor(Math.random()*K$1.length),Q=H$1[X]??"deco",J=K$1[Y]??"studio";return`${Q}-${J}`}var K$1,H$1,tl6,el6,If,Xd6,Yd6,Qd6,F$1,WX,V$1=void 0,Jd6,Gd6,Wd6,WG;var uB=S(()=>{md();DD0();QO0();Si();ea();aO0();fS();QL0();tM();r60();a41();W$1();XQ0();K$1=["labs","agent","studio","workspace","systems","core","cloud","works"],H$1=["capybara","guarana","deco","samba","feijoada","capoeira","carnival"];tl6=Object.values(HO()).map((X)=>X.map((Y)=>Y.name)).flat(),el6={...wS,self:["*",...tl6]},If=W7(el6),Xd6=If.newRole({self:["*"],...mL.statements}),Yd6=If.newRole({self:["*"],...mL.statements}),Qd6=If.newRole({self:["*"],...mL.statements}),F$1=Object.values(HO()).map((X)=>X.map((Y)=>`self:${Y.name}`)).flat(),WX=oL.auth;if(WX.inviteEmailProviderId&&WX.emailProviders&&WX.emailProviders.length>0){let X=$y(WX.emailProviders,WX.inviteEmailProviderId);if(X){let Y=Zy(X);V$1=async(Q)=>{let J=Q.inviter.user?.name||Q.inviter.user?.email,G=`${process.env.BASE_URL||"http://localhost:3000"}/auth/accept-invitation?invitationId=${Q.invitation.id}`;await Y({to:Q.email,subject:`Invitation to join ${Q.organization.name}`,html:`
|
|
1185
1185
|
<h2>You've been invited!</h2>
|
|
1186
1186
|
<p>${J} has invited you to join <strong>${Q.organization.name}</strong>.</p>
|
|
1187
1187
|
<p><a href="${G}">Click here to accept the invitation</a></p>
|