@decocms/mesh 1.4.4 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/dist/client/assets/{AlertCircle-B6rEUVLf.js → AlertCircle-BIlMffS8.js} +1 -1
  2. package/dist/client/assets/{ArrowLeft-DC_Ebc-m.js → ArrowLeft-CJ-eKoid.js} +1 -1
  3. package/dist/client/assets/{ChevronDown-rNVX3ifZ.js → ChevronDown-atiP0m-F.js} +1 -1
  4. package/dist/client/assets/{Clock-DS2iGkSJ.js → Clock-BD2gknBV.js} +1 -1
  5. package/dist/client/assets/{Code01-CoFYqM8q.js → Code01-BEefaaXC.js} +1 -1
  6. package/dist/client/assets/{Copy01-CCVZH6f1.js → Copy01-DhXqtugg.js} +1 -1
  7. package/dist/client/assets/{CpuChip02-DwHhz9CA.js → CpuChip02-BtgBI59l.js} +1 -1
  8. package/dist/client/assets/{DotsVertical-8kkJJG9R.js → DotsVertical-roys0n6e.js} +1 -1
  9. package/dist/client/assets/{File06-DxUGl7Wc.js → File06-MlW8n69V.js} +1 -1
  10. package/dist/client/assets/{FlipBackward-D9qJVjU9.js → FlipBackward-BSnTMMYy.js} +1 -1
  11. package/dist/client/assets/{GitBranch01-DLNdjhEu.js → GitBranch01-CEvRlFly.js} +1 -1
  12. package/dist/client/assets/{Grid01-BTunGha4.js → Grid01-CkwdbRed.js} +1 -1
  13. package/dist/client/assets/{Inbox01-BoV8p7IN.js → Inbox01-D66dNA_K.js} +1 -1
  14. package/dist/client/assets/{Key01-Bqzm5f6K.js → Key01-BXlD7hmS.js} +1 -1
  15. package/dist/client/assets/{LinkExternal01-WcFL8RpQ.js → LinkExternal01-O4xnNCff.js} +1 -1
  16. package/dist/client/assets/{Loading01-B0vdyVbH.js → Loading01-EiDV-2FW.js} +1 -1
  17. package/dist/client/assets/{Lock01-B0PVK-yI.js → Lock01-DpRDCI3P.js} +1 -1
  18. package/dist/client/assets/{Play-KfJ8X6ky.js → Play-FKw7EqPO.js} +1 -1
  19. package/dist/client/assets/{Plus-nu8-Nz8b.js → Plus-CwB-Rc8B.js} +1 -1
  20. package/dist/client/assets/{SearchMd-BFumDfkS.js → SearchMd-C6P9P1wF.js} +1 -1
  21. package/dist/client/assets/{Terminal-CDIp_seB.js → Terminal-Dv6w41J8.js} +1 -1
  22. package/dist/client/assets/{Trash01-1tKgR7uh.js → Trash01-Ctk7srex.js} +1 -1
  23. package/dist/client/assets/{X-hEo9Za23.js → X-Da4xsL05.js} +1 -1
  24. package/dist/client/assets/{XClose-BIthQxae.js → XClose-OUZ04LEo.js} +1 -1
  25. package/dist/client/assets/{alert-dialog-_VCwcCen.js → alert-dialog-D6UjYOUP.js} +1 -1
  26. package/dist/client/assets/{auth-BpfHzPVh.js → auth-CZR9mNdb.js} +1 -1
  27. package/dist/client/assets/{auth-catchall-D-D94naG.js → auth-catchall-BZWl_BRK.js} +1 -1
  28. package/dist/client/assets/{avatar-DHKqC-IM.js → avatar-BHE7lL4M.js} +1 -1
  29. package/dist/client/assets/{badge-Dkhmn9Qj.js → badge-B-u7R38I.js} +1 -1
  30. package/dist/client/assets/{button-BSXU4L7C.js → button-B13xcF6W.js} +1 -1
  31. package/dist/client/assets/{card-CXFRieEW.js → card-7VW-xSd-.js} +1 -1
  32. package/dist/client/assets/{checkbox-C-t_-9ku.js → checkbox-BMd2Z-WT.js} +1 -1
  33. package/dist/client/assets/{collection-detail-P20CfY5q.js → collection-detail-7eGCexqR.js} +3 -3
  34. package/dist/client/assets/{collection-display-button-BAoFTB4b.js → collection-display-button-D4VM0KQx.js} +1 -1
  35. package/dist/client/assets/{collection-header-B--7sWbR.js → collection-header-od14k6u3.js} +1 -1
  36. package/dist/client/assets/{collection-page-B71dz4fa.js → collection-page-BNuNM--s.js} +1 -1
  37. package/dist/client/assets/{collection-search-CrC01K4Z.js → collection-search-LnYLnFH8.js} +1 -1
  38. package/dist/client/assets/{collection-tab-dwp9LGxi.js → collection-tab-bg_gmLyh.js} +1 -1
  39. package/dist/client/assets/{collection-table-wrapper-CFoaxah9.js → collection-table-wrapper-B0AFEn1d.js} +1 -1
  40. package/dist/client/assets/{connection-card-eAyda1Mu.js → connection-card-r2tH19aR.js} +1 -1
  41. package/dist/client/assets/{connection-detail-Bn-jl6HG.js → connection-detail-Dm1s8Dj2.js} +1 -1
  42. package/dist/client/assets/connections-CWHukeOK.js +1 -0
  43. package/dist/client/assets/constants-CN4QOiqe.js +1 -0
  44. package/dist/client/assets/{core-C9AbX0ks.js → core-BqWxized.js} +1 -1
  45. package/dist/client/assets/{create-organization-dialog-DhHOFwW5.js → create-organization-dialog-CjneLhKn.js} +1 -1
  46. package/dist/client/assets/{dialog-Cj2udzC-.js → dialog-DoN4ORnY.js} +1 -1
  47. package/dist/client/assets/{dropdown-menu-ClBJUvd8.js → dropdown-menu-uXj8nKiT.js} +1 -1
  48. package/dist/client/assets/{empty-state-CYnIzDhF.js → empty-state-N07FE0YG.js} +1 -1
  49. package/dist/client/assets/{env-vars-editor-nU4IPD2j.js → env-vars-editor-B7JL_p-V.js} +1 -1
  50. package/dist/client/assets/{error-boundary-D5hb-PLt.js → error-boundary-Ce0_dLsG.js} +1 -1
  51. package/dist/client/assets/{extract-connection-data-BWB54H7f.js → extract-connection-data-CeT4F9gU.js} +1 -1
  52. package/dist/client/assets/{form-Dn7fy5O5.js → form-BQIYj24w.js} +1 -1
  53. package/dist/client/assets/{formatDistanceToNow-km7E2wF1.js → formatDistanceToNow-CArtWgcP.js} +1 -1
  54. package/dist/client/assets/gateway-detail-VCb3jL84.js +1 -0
  55. package/dist/client/assets/gateways-9p2LLkTK.js +1 -0
  56. package/dist/client/assets/{home-dep1g9Zf.js → home-DgfprghT.js} +1 -1
  57. package/dist/client/assets/{index-gqIvEQSH.js → index-CVgkE3Gv.js} +2 -2
  58. package/dist/client/assets/{index-tz4gB72W.js → index-DEMNtulg.js} +2 -2
  59. package/dist/client/assets/{index-DX5d9vx1.js → index-DcMa5gDs.js} +1 -1
  60. package/dist/client/assets/{index-CcNvI65p.js → index-DcvTq0xJ.js} +1 -1
  61. package/dist/client/assets/{input-Cb7MaM0d.js → input-YdP8mwrf.js} +1 -1
  62. package/dist/client/assets/json-Bz08jZIq.js +1 -0
  63. package/dist/client/assets/{json-syntax-highlighter-CCgbux_M.js → json-syntax-highlighter-Bif-CDya.js} +2 -2
  64. package/dist/client/assets/{layout-DtfNegCp.js → layout-BNxxrCBw.js} +1 -1
  65. package/dist/client/assets/{lazy-highlighter-CaGtIE-R.js → lazy-highlighter-C0vzyJy5.js} +1 -1
  66. package/dist/client/assets/{localstorage-keys-DIkWdWYS.js → localstorage-keys-DwKN3_Ky.js} +1 -1
  67. package/dist/client/assets/{login-DSSk45pi.js → login-UWyl_cxx.js} +1 -1
  68. package/dist/client/assets/{mcp-oauth-BOAcAnr_.js → mcp-oauth-Dqr97r2H.js} +1 -1
  69. package/dist/client/assets/{members-D4I8qlnr.js → members-C3UV37Kw.js} +1 -1
  70. package/dist/client/assets/{monitoring-CvcerPLg.js → monitoring-Ds52TSSS.js} +2 -2
  71. package/dist/client/assets/{oauth-callback-CY5bCrs6.js → oauth-callback-D4M9mHyH.js} +1 -1
  72. package/dist/client/assets/{page-Du4118GJ.js → page-B7ia0_lh.js} +2 -2
  73. package/dist/client/assets/{pin-to-sidebar-button-CwlJToUG.js → pin-to-sidebar-button-BKotT_Nc.js} +1 -1
  74. package/dist/client/assets/{popover-BPqLZ76M.js → popover-7jr0PuXV.js} +1 -1
  75. package/dist/client/assets/prism-light-CHE2alug.js +1 -0
  76. package/dist/client/assets/resizable-qkPSJ31g.js +1 -0
  77. package/dist/client/assets/{resource-tabs-CmUpRVKA.js → resource-tabs-qR3NhTLd.js} +1 -1
  78. package/dist/client/assets/{responsive-select-DwsIwS1V.js → responsive-select-CJQwNPPj.js} +1 -1
  79. package/dist/client/assets/{select-HGITgxwS.js → select-L_OjJ9sW.js} +1 -1
  80. package/dist/client/assets/{settings-sSoOIGWg.js → settings-BapAo6i2.js} +1 -1
  81. package/dist/client/assets/shell-layout-DqUuQ9gz.js +19 -0
  82. package/dist/client/assets/{spinner-BUVePO6d.js → spinner-CAJeeq5B.js} +1 -1
  83. package/dist/client/assets/{store-H6vucsd1.js → store-DTMoxgob.js} +1 -1
  84. package/dist/client/assets/{store-app-detail-aULJzMOJ.js → store-app-detail-CbGg2GlI.js} +1 -1
  85. package/dist/client/assets/{switch-BwTlw9qL.js → switch-DlwEQXd2.js} +1 -1
  86. package/dist/client/assets/{textarea-BAs6HmBZ.js → textarea-IOVeLZOt.js} +1 -1
  87. package/dist/client/assets/{thread-history-popover-DbEl1KJu.js → thread-history-popover-COjpShBU.js} +3 -3
  88. package/dist/client/assets/{tools-list-thZyoBrU.js → tools-list-l6xtSgWR.js} +1 -1
  89. package/dist/client/assets/{tooltip-Bzy1O5cq.js → tooltip-C7B84lYF.js} +1 -1
  90. package/dist/client/assets/{types-BVTsq_OW.js → types-BmKCUQAI.js} +1 -1
  91. package/dist/client/assets/{use-binding-jUI3xZmp.js → use-binding-Ce8NG0MO.js} +1 -1
  92. package/dist/client/assets/{use-connection-DRZbGk_A.js → use-connection-D-LWel3A.js} +1 -1
  93. package/dist/client/assets/{use-connection-resources-B3tDNT6E.js → use-connection-resources-CJzk5_Wj.js} +1 -1
  94. package/dist/client/assets/{use-gateway-CUxuCVmJ.js → use-gateway-eXp_1iQc.js} +1 -1
  95. package/dist/client/assets/{use-list-state-CkGBL95Z.js → use-list-state-CmxR0QRn.js} +1 -1
  96. package/dist/client/assets/{use-mcp-CMt9Wy3X.js → use-mcp-Cmlg9h6L.js} +1 -1
  97. package/dist/client/assets/{use-members-cyA2aC2q.js → use-members-Drex2zGi.js} +1 -1
  98. package/dist/client/assets/{use-mobile-B8xlavN6.js → use-mobile-B-R7B7Hp.js} +1 -1
  99. package/dist/client/assets/{use-organization-settings-C7IdFOTo.js → use-organization-settings-B_G_DBCR.js} +1 -1
  100. package/dist/client/assets/{use-tool-call-CsOSZ1pI.js → use-tool-call-BN3WED_Z.js} +1 -1
  101. package/dist/client/assets/useQuery-DLJrS2VC.js +1 -0
  102. package/dist/client/assets/{useSuspenseInfiniteQuery-DqCwXIKB.js → useSuspenseInfiniteQuery-DFaXtjFO.js} +1 -1
  103. package/dist/client/assets/{view-mode-toggle-COcukfhX.js → view-mode-toggle-BpRlpgBn.js} +1 -1
  104. package/dist/client/assets/workflow-CBeu3WB4.js +1 -0
  105. package/dist/client/index.html +1 -1
  106. package/dist/server/cli.js +2 -2
  107. package/dist/server/migrate.js +2 -2
  108. package/dist/server/server.js +3 -3
  109. package/package.json +1 -1
  110. package/dist/client/assets/connections-CDl5cKXc.js +0 -1
  111. package/dist/client/assets/constants-C-5m3xCJ.js +0 -1
  112. package/dist/client/assets/gateway-detail-BEimKnAa.js +0 -1
  113. package/dist/client/assets/gateways-1GR6BIbg.js +0 -1
  114. package/dist/client/assets/json-CevIphLA.js +0 -1
  115. package/dist/client/assets/prism-light-bnbWF_0X.js +0 -1
  116. package/dist/client/assets/resizable-Ck5ltOjh.js +0 -1
  117. package/dist/client/assets/shell-layout-BCUXUEeW.js +0 -19
  118. package/dist/client/assets/useQuery-Bl78N6vT.js +0 -1
  119. package/dist/client/assets/workflow-CaCjE8aO.js +0 -1
@@ -252,7 +252,7 @@ data:
252
252
 
253
253
  `,Q.enqueue(X.encode(G)),!0}catch{return!1}}handleUnsupportedRequest(){return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32000,message:"Method not allowed."},id:null}),{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(Q,X){try{let Y=Q.headers.get("accept");if(!Y?.includes("application/json")||!Y.includes("text/event-stream"))return this.createJsonErrorResponse(406,-32000,"Not Acceptable: Client must accept both application/json and text/event-stream");let J=Q.headers.get("content-type");if(!J||!J.includes("application/json"))return this.createJsonErrorResponse(415,-32000,"Unsupported Media Type: Content-Type must be application/json");let G={headers:Object.fromEntries(Q.headers.entries())},W;if(X?.parsedBody!==void 0)W=X.parsedBody;else try{W=await Q.json()}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}let Z;try{if(Array.isArray(W))Z=W.map((L)=>vY.parse(L));else Z=[vY.parse(W)]}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}let $=Z.some(ge);if($){if(this._initialized&&this.sessionId!==void 0)return this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(Z.length>1)return this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");if(this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized)await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!$){let L=this.validateSession(Q);if(L)return L;let M=this.validateProtocolVersion(Q);if(M)return M}if(!Z.some(iG)){for(let L of Z)this.onmessage?.(L,{authInfo:X?.authInfo,requestInfo:G});return new Response(null,{status:202})}let H=crypto.randomUUID(),F=Z.find((L)=>ge(L)),V=F?F.params.protocolVersion:Q.headers.get("mcp-protocol-version")??Pt0;if(this._enableJsonResponse)return new Promise((L)=>{this._streamMapping.set(H,{resolveJson:L,cleanup:()=>{this._streamMapping.delete(H)}});for(let M of Z)if(iG(M))this._requestToStreamMapping.set(M.id,H);for(let M of Z)this.onmessage?.(M,{authInfo:X?.authInfo,requestInfo:G})});let q=new TextEncoder,U,D=new ReadableStream({start:(L)=>{U=L},cancel:()=>{this._streamMapping.delete(H)}}),B={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};if(this.sessionId!==void 0)B["mcp-session-id"]=this.sessionId;for(let L of Z)if(iG(L))this._streamMapping.set(H,{controller:U,encoder:q,cleanup:()=>{this._streamMapping.delete(H);try{U.close()}catch{}}}),this._requestToStreamMapping.set(L.id,H);await this.writePrimingEvent(U,q,H,V);for(let L of Z){let M,C;if(iG(L)&&this._eventStore&&V>="2025-11-25")M=()=>{this.closeSSEStream(L.id)},C=()=>{this.closeStandaloneSSEStream()};this.onmessage?.(L,{authInfo:X?.authInfo,requestInfo:G,closeSSEStream:M,closeStandaloneSSEStream:C})}return new Response(D,{status:200,headers:B})}catch(Y){return this.onerror?.(Y),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(Y)})}}async handleDeleteRequest(Q){let X=this.validateSession(Q);if(X)return X;let Y=this.validateProtocolVersion(Q);if(Y)return Y;return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200})}validateSession(Q){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.createJsonErrorResponse(400,-32000,"Bad Request: Server not initialized");let X=Q.headers.get("mcp-session-id");if(!X)return this.createJsonErrorResponse(400,-32000,"Bad Request: Mcp-Session-Id header is required");if(X!==this.sessionId)return this.createJsonErrorResponse(404,-32001,"Session not found");return}validateProtocolVersion(Q){let X=Q.headers.get("mcp-protocol-version");if(X!==null&&!f3.includes(X))return this.createJsonErrorResponse(400,-32000,`Bad Request: Unsupported protocol version: ${X} (supported versions: ${f3.join(", ")})`);return}async close(){this._streamMapping.forEach(({cleanup:Q})=>{Q()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(Q){let X=this._requestToStreamMapping.get(Q);if(!X)return;let Y=this._streamMapping.get(X);if(Y)Y.cleanup()}closeStandaloneSSEStream(){let Q=this._streamMapping.get(this._standaloneSseStreamId);if(Q)Q.cleanup()}async send(Q,X){let Y=X?.relatedRequestId;if(O5(Q)||pz(Q))Y=Q.id;if(Y===void 0){if(O5(Q)||pz(Q))throw Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let W;if(this._eventStore)W=await this._eventStore.storeEvent(this._standaloneSseStreamId,Q);let Z=this._streamMapping.get(this._standaloneSseStreamId);if(Z===void 0)return;if(Z.controller&&Z.encoder)this.writeSSEEvent(Z.controller,Z.encoder,Q,W);return}let J=this._requestToStreamMapping.get(Y);if(!J)throw Error(`No connection established for request ID: ${String(Y)}`);let G=this._streamMapping.get(J);if(!this._enableJsonResponse&&G?.controller&&G?.encoder){let W;if(this._eventStore)W=await this._eventStore.storeEvent(J,Q);this.writeSSEEvent(G.controller,G.encoder,Q,W)}if(O5(Q)||pz(Q)){this._requestResponseMap.set(Y,Q);let W=Array.from(this._requestToStreamMapping.entries()).filter(([$,K])=>K===J).map(([$])=>$);if(W.every(($)=>this._requestResponseMap.has($))){if(!G)throw Error(`No connection established for request ID: ${String(Y)}`);if(this._enableJsonResponse&&G.resolveJson){let $={"Content-Type":"application/json"};if(this.sessionId!==void 0)$["mcp-session-id"]=this.sessionId;let K=W.map((H)=>this._requestResponseMap.get(H));if(K.length===1)G.resolveJson(new Response(JSON.stringify(K[0]),{status:200,headers:$}));else G.resolveJson(new Response(JSON.stringify(K),{status:200,headers:$}))}else G.cleanup();for(let $ of W)this._requestResponseMap.delete($),this._requestToStreamMapping.delete($)}}}}var Xy=o(()=>{_9()});var kM=(...Q)=>{return function(Y,J){let G=(W)=>{let Z=Q[W];if(!Z)return J();return Z(Y,()=>G(W+1))};return G(0)}};class BQ1{config;tools=[];callToolMiddlewares=[];constructor(Q){this.config={...Q,capabilities:Q.capabilities??{tools:{}}}}withTool(Q){return this.tools.push(Q),this}withTools(Q){return this.tools.push(...Q),this}callToolMiddleware(...Q){return this.callToolMiddlewares.push(...Q),this}build(){let Q=this.callToolMiddlewares.length>0?kM(...this.callToolMiddlewares):null,X=()=>{let Y=new p3({name:this.config.name,version:this.config.version},{capabilities:this.config.capabilities});for(let J of this.tools){let G=async(K)=>{try{let H=await J.handler(K);return{content:[{type:"text",text:JSON.stringify(H)}],structuredContent:H}}catch(H){return{content:[{type:"text",text:`Error: ${H.message}`}],isError:!0}}},W=Q?async(K)=>{let H={method:"tools/call",params:{name:J.name,arguments:K}};return await Q(H,()=>G(K))}:G,Z="shape"in J.inputSchema?J.inputSchema.shape:N.object({}).shape,$=J.outputSchema&&"shape"in J.outputSchema?J.outputSchema.shape:N.object({}).shape;Y.registerTool(J.name,{annotations:J.annotations,description:J.description??"",inputSchema:Z,outputSchema:$},W)}return Y};return{callStreamableTool:async(Y,J)=>{let G=this.tools.find((Z)=>Z.name===Y);if(!G)throw Error(`Tool ${Y} not found`);let W=await G.handler(J);if(!(W instanceof Response))throw Error(`Tool ${Y} returned a non-response`);return W},client:{listTools:async()=>{return{tools:this.tools.map((Y)=>({name:Y.name,description:Y.description??"",inputSchema:N.toJSONSchema(Y.inputSchema),outputSchema:Y.outputSchema?N.toJSONSchema(Y.outputSchema):void 0}))}},callTool:async(Y)=>{let J=this.tools.find((G)=>G.name===Y.name);if(!J)return{content:[{type:"text",text:"Tool not found"}]};try{let G=await J?.handler(Y.arguments??{});return{content:[{type:"text",text:JSON.stringify(G)}],structuredContent:G}}catch(G){return{content:[{type:"text",text:`Error: ${G.message}`}]}}}},fetch:async(Y)=>{let J=new c3({enableJsonResponse:Y.headers.get("Accept")?.includes("application/json")??!1});return await X().connect(J),await J.handleRequest(Y)}}}}function DQ1(Q){return new BQ1(Q)}var NQ1=o(()=>{Qy();Xy();W1()});function N1(Q){return{...Q,execute:async(X,Y)=>{let J=Date.now();return await Y.tracer.startActiveSpan(`tool.${Q.name}`,{attributes:{"tool.name":Q.name,"organization.id":Y.organization?.id??"system","user.id":Y.auth.user?.id??Y.auth.apiKey?.userId??"anonymous"}},async(G)=>{try{Y.toolName=Q.name,Y.access.setToolName?.(Q.name);let W=await Q.handler(X,Y),Z=Date.now()-J;return Y.meter.createHistogram("tool.execution.duration",{description:"Duration of tool executions in milliseconds",unit:"ms"}).record(Z,{"tool.name":Q.name,"organization.id":Y.organization?.id??"system",status:"success"}),Y.meter.createCounter("tool.execution.count",{description:"Number of tool executions"}).add(1,{"tool.name":Q.name,status:"success"}),G.setStatus({code:P60.SpanStatusCode.OK}),W}catch(W){throw Y.meter.createCounter("tool.execution.errors",{description:"Number of tool execution errors"}).add(1,{"tool.name":Q.name,"error.type":W.constructor.name}),G.setStatus({code:P60.SpanStatusCode.ERROR,message:W.message}),G.recordException(W),W}finally{G.end()}})}}}var P60;var P6=o(()=>{P60=m6($1(),1)});function O6(Q){if(!Q.organization)throw Error("This operation requires organization scope");return Q.organization}function b9(Q){return Q.auth.user?.id??Q.auth.apiKey?.userId}function o26(Q){return!!(Q.auth.user||Q.auth.apiKey)}function S1(Q){if(!o26(Q))throw Error("Authentication required")}var Yy,OQ1,LQ1,wQ1,MQ1,PQ1,TQ1,AQ1,EQ1,jQ1;var UU=o(()=>{W1();Yy=N.record(N.string(),N.array(N.string())),OQ1=N.object({id:N.string().describe("Unique identifier for the API key"),name:N.string().describe("Human-readable name for the API key"),userId:N.string().describe("ID of the user who owns this API key"),permissions:Yy.describe('Permissions granted to this API key. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Example: { "self": ["API_KEY_CREATE"], "conn_abc123": ["SEND_MESSAGE"] }'),expiresAt:N.union([N.string(),N.date()]).nullable().optional().describe("Expiration date of the API key"),createdAt:N.union([N.string(),N.date()]).describe("When the API key was created")}),LQ1=N.object({name:N.string().min(1).max(64).describe("Human-readable name for the API key"),permissions:Yy.optional().describe('Permissions to grant. Format: { resource: [actions] }. Resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Actions are tool names (e.g., ["API_KEY_CREATE"]) or ["*"] for all. Example: { "self": ["API_KEY_CREATE", "COLLECTION_CONNECTIONS_LIST"] }. Defaults to read-only permissions.'),expiresIn:N.number().positive().optional().describe("Expiration time in seconds. If not provided, key never expires."),metadata:N.record(N.string(),N.unknown()).optional().describe("Additional metadata to store with the API key")}),wQ1=N.object({id:N.string().describe("Unique identifier for the API key"),name:N.string().describe("Human-readable name for the API key"),key:N.string().describe("The actual API key value. STORE THIS SECURELY - it will not be shown again!"),permissions:Yy.describe('Permissions granted to this API key. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools'),expiresAt:N.union([N.string(),N.date()]).nullable().optional().describe("Expiration date of the API key"),createdAt:N.union([N.string(),N.date()]).describe("When the API key was created")}),MQ1=N.object({}),PQ1=N.object({items:N.array(OQ1).describe("List of API keys (without key values)")}),TQ1=N.object({keyId:N.string().describe("ID of the API key to update"),name:N.string().min(1).max(64).optional().describe("New name for the API key"),permissions:Yy.optional().describe('New permissions. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Actions are tool names or "*" for all. Example: { "self": ["API_KEY_CREATE"] }. Replaces existing permissions.'),metadata:N.record(N.string(),N.unknown()).optional().describe("New metadata. Replaces existing metadata.")}),AQ1=N.object({item:OQ1.describe("The updated API key (without key value)")}),EQ1=N.object({keyId:N.string().describe("ID of the API key to delete")}),jQ1=N.object({success:N.boolean().describe("Whether the deletion was successful"),keyId:N.string().describe("ID of the deleted API key")})});var T60;var CQ1=o(()=>{P6();UU();T60=N1({name:"API_KEY_CREATE",description:"Create a new API key with specified permissions. The key value is only returned once - store it securely!",inputSchema:LQ1,outputSchema:wQ1,handler:async(Q,X)=>{S1(X),await X.access.check();let Y=await X.boundAuth.apiKey.create({name:Q.name,permissions:Q.permissions,expiresIn:Q.expiresIn,metadata:{...Q.metadata,organization:X.organization}});return{id:Y.id,name:Y.name??Q.name,key:Y.key,permissions:Y.permissions??{},expiresAt:Y.expiresAt??null,createdAt:Y.createdAt}}})});var A60;var IQ1=o(()=>{P6();UU();A60=N1({name:"API_KEY_DELETE",description:"Delete an API key. This instantly revokes the key - it can no longer be used for authentication.",inputSchema:EQ1,outputSchema:jQ1,handler:async(Q,X)=>{if(S1(X),await X.access.check(),!b9(X))throw Error("User ID required to delete API key");let G=(await X.boundAuth.apiKey.list())?.find((K)=>K.id===Q.keyId);if(!G)throw Error("API key not found");let Z=G.metadata?.organization?.id,$=X.organization?.id;if(Z!==$)throw Error("Cannot delete API key from another organization");return await X.boundAuth.apiKey.delete(Q.keyId),{success:!0,keyId:Q.keyId}}})});var E60;var RQ1=o(()=>{P6();UU();E60=N1({name:"API_KEY_LIST",description:"List all API keys for the current user in the current organization. Returns metadata only - key values are never shown after creation.",inputSchema:MQ1,outputSchema:PQ1,handler:async(Q,X)=>{S1(X),await X.access.check();let Y=await X.boundAuth.apiKey.list(),J=X.organization?.id;return{items:(Y??[]).filter((W)=>{return W.metadata?.organization?.id===J}).map((W)=>({id:W.id,name:W.name??"Unnamed Key",userId:W.userId,permissions:W.permissions??{},expiresAt:W.expiresAt??null,createdAt:W.createdAt}))}}})});var j60;var SQ1=o(()=>{P6();UU();j60=N1({name:"API_KEY_UPDATE",description:"Update an existing API key's name, permissions, or metadata. Note: Key value cannot be changed or retrieved.",inputSchema:TQ1,outputSchema:AQ1,handler:async(Q,X)=>{if(S1(X),await X.access.check(),!b9(X))throw Error("User ID required to update API key");let G=(await X.boundAuth.apiKey.list())?.find((H)=>H.id===Q.keyId);if(!G)throw Error(`API key not found: ${Q.keyId}`);let Z=G.metadata?.organization?.id,$=X.organization?.id;if(Z!==$)throw Error("Cannot update API key from another organization");let K=await X.boundAuth.apiKey.update({keyId:Q.keyId,name:Q.name,permissions:Q.permissions,metadata:{...Q.metadata,organization:X.organization}});if(!K)throw Error(`Failed to update API key: ${Q.keyId}`);return{item:{id:K.id,name:K.name??Q.name??"Unnamed Key",userId:K.userId,permissions:K.permissions??{},expiresAt:K.expiresAt??null,createdAt:K.createdAt}}}})});var kQ1=o(()=>{CQ1();IQ1();RQ1();SQ1();UU()});var t26,e26,C60;var vQ1=o(()=>{R3();W1();P6();e_();U7();t26=N.object({data:ts0.describe("Data for the new connection (id is auto-generated if not provided)")}),e26=N.object({item:CJ.describe("The created connection entity")}),C60=N1({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",inputSchema:t26,outputSchema:e26,handler:async(Q,X)=>{S1(X);let Y=O6(X);await X.access.check();let J=b9(X);if(!J)throw Error("User ID required to create connection");let G={...Q.data,organization_id:Y.id,created_by:J},W=await zU({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 X.storage.connections.create({...G,tools:Z});return await X.eventBus.publish(Y.id,Ew.SELF(Y.id),{type:"connection.created",data:$}),{item:$}}})});function vM(Q,X){if(Q===X)return!0;if(Q==null||X==null)return Q===X;if(typeof Q!==typeof X)return!1;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;return Q.every((Y,J)=>vM(Y,X[J]))}if(typeof Q==="object"&&typeof X==="object"){let Y=Object.keys(Q),J=Object.keys(X);if(Y.length!==J.length)return!1;return Y.every((G)=>J.includes(G)&&vM(Q[G],X[G]))}return!1}function PC6(){return(Q)=>{if(!Array.isArray(Q))return!0;let X=[];return Q.every((Y)=>{if(X.some((G)=>vM(Y,G)))return!1;return X.push(Y),!0})}}function Jy(Q,X){return Q.safeParse(X).success}function q9(Q){if(typeof Q==="boolean")return Q?N.any():N.never();let X={};for(let G of fC6)G.apply(X,Q);let Y=[];if(X.string!==!1)Y.push(X.string||N.string());if(X.number!==!1)Y.push(X.number||N.number());if(X.boolean!==!1)Y.push(X.boolean||N.boolean());if(X.null!==!1)Y.push(X.null||N.null());if(X.array!==!1)Y.push(X.array||N.array(N.any()));if(X.tuple!==!1&&X.tuple!==void 0)Y.push(X.tuple);if(X.object!==!1)if(X.object)Y.push(X.object);else{let G=N.custom((W)=>{return typeof W==="object"&&W!==null&&!Array.isArray(W)},"Must be an object, not an array");Y.push(G)}if(X.file!==!1&&X.file!==void 0)Y.push(X.file);let J;if(Y.length===0)J=N.never();else if(Y.length===1)J=Y[0];else if(!Object.keys(Q).some((W)=>W!=="$schema"&&W!=="title"&&W!=="description"))J=N.any();else J=N.union(Y);for(let G of hC6)J=G.apply(J,Q);return J}var QC6=class{apply(Q,X){if(!X.type)return;let Y=Array.isArray(X.type)?X.type:[X.type],J=new Set(Y);if(!J.has("string"))Q.string=!1;if(!J.has("number")&&!J.has("integer"))Q.number=!1;if(!J.has("boolean"))Q.boolean=!1;if(!J.has("null"))Q.null=!1;if(!J.has("array"))Q.array=!1;if(!J.has("object"))Q.object=!1;if(J.has("integer")&&Q.number!==!1){let G=Q.number||N.number();if(G instanceof N.ZodNumber)Q.number=G.int()}}},XC6=class{apply(Q,X){if(X.const===void 0)return;let Y=X.const;if(Q.string=!1,Q.number=!1,Q.boolean=!1,Q.null=!1,Q.array=!1,Q.object=!1,typeof Y==="string")Q.string=N.literal(Y);else if(typeof Y==="number")Q.number=N.literal(Y);else if(typeof Y==="boolean")Q.boolean=N.literal(Y);else if(Y===null)Q.null=N.null();else if(Array.isArray(Y))Q.array=void 0;else if(typeof Y==="object")Q.object=void 0}},YC6=class{apply(Q,X){if(!X.enum)return;if(X.enum.length===0){if(!X.type)Q.string=!1,Q.number=!1,Q.boolean=!1,Q.null=!1,Q.array=!1,Q.object=!1;return}let Y={string:X.enum.filter((J)=>typeof J==="string"),number:X.enum.filter((J)=>typeof J==="number"),boolean:X.enum.filter((J)=>typeof J==="boolean"),null:X.enum.filter((J)=>J===null),array:X.enum.filter((J)=>Array.isArray(J)),object:X.enum.filter((J)=>typeof J==="object"&&J!==null&&!Array.isArray(J))};Q.string=this.createTypeSchema(Y.string,"string"),Q.number=this.createTypeSchema(Y.number,"number"),Q.boolean=this.createTypeSchema(Y.boolean,"boolean"),Q.null=Y.null.length>0?N.null():!1,Q.array=Y.array.length>0?void 0:!1,Q.object=Y.object.length>0?void 0:!1}createTypeSchema(Q,X){if(Q.length===0)return!1;if(Q.length===1)return N.literal(Q[0]);if(X==="string")return N.enum(Q);if(X==="number"){let[Y,J,...G]=Q;return N.union([N.literal(Y),N.literal(J),...G.map((W)=>N.literal(W))])}if(X==="boolean")return N.union([N.literal(!0),N.literal(!1)]);return!1}},JC6=class{apply(Q,X){let Y=X;if(Y.type==="string"&&Y.format==="binary"&&Y.contentEncoding==="binary"){let J=N.file();if(Y.minLength!==void 0)J=J.min(Y.minLength);if(Y.maxLength!==void 0)J=J.max(Y.maxLength);if(Y.contentMediaType!==void 0)J=J.mime(Y.contentMediaType);Q.file=J,Q.string=!1}}},GC6=class{apply(Q,X){let Y=X;if(X.type===void 0&&(Y.minLength!==void 0||Y.maxLength!==void 0||Y.pattern!==void 0)){if(Q.string===void 0)Q.string=N.string()}}},WC6=class{apply(Q,X){let Y=X;if(Y.minLength===void 0)return;if(Q.string!==!1){let J=Q.string||N.string();if(J instanceof N.ZodString)Q.string=J.refine((G)=>{return Array.from(G).length>=Y.minLength},{message:`String must be at least ${Y.minLength} characters long`})}}},ZC6=class{apply(Q,X){let Y=X;if(Y.maxLength===void 0)return;if(Q.string!==!1){let J=Q.string||N.string();if(J instanceof N.ZodString)Q.string=J.refine((G)=>{return Array.from(G).length<=Y.maxLength},{message:`String must be at most ${Y.maxLength} characters long`})}}},$C6=class{apply(Q,X){let Y=X;if(!Y.pattern)return;if(Q.string!==!1){let J=Q.string||N.string();if(J instanceof N.ZodString){let G=new RegExp(Y.pattern);Q.string=J.regex(G)}}}},KC6=class{apply(Q,X){let Y=X;if(Y.minimum===void 0)return;if(Q.number!==!1){let J=Q.number||N.number();if(J instanceof N.ZodNumber)Q.number=J.min(Y.minimum)}}},HC6=class{apply(Q,X){let Y=X;if(Y.maximum===void 0)return;if(Q.number!==!1){let J=Q.number||N.number();if(J instanceof N.ZodNumber)Q.number=J.max(Y.maximum)}}},FC6=class{apply(Q,X){let Y=X;if(Y.exclusiveMinimum===void 0)return;if(Q.number!==!1){let J=Q.number||N.number();if(J instanceof N.ZodNumber)if(typeof Y.exclusiveMinimum==="number")Q.number=J.gt(Y.exclusiveMinimum);else Q.number=!1}}},VC6=class{apply(Q,X){let Y=X;if(Y.exclusiveMaximum===void 0)return;if(Q.number!==!1){let J=Q.number||N.number();if(J instanceof N.ZodNumber)if(typeof Y.exclusiveMaximum==="number")Q.number=J.lt(Y.exclusiveMaximum);else Q.number=!1}}},qC6=class{apply(Q,X){let Y=X;if(Y.multipleOf===void 0)return;if(Q.number!==!1){let J=Q.number||N.number();if(J instanceof N.ZodNumber)Q.number=J.refine((G)=>{if(Y.multipleOf===0)return!1;let W=G/Y.multipleOf,Z=Math.round(W),$=Math.min(Math.abs(G)*Number.EPSILON*10,Math.abs(Y.multipleOf)*Number.EPSILON*10);return Math.abs(W-Z)<=$/Math.abs(Y.multipleOf)},{message:`Must be a multiple of ${Y.multipleOf}`})}}},zC6=class{apply(Q,X){let Y=X;if(X.type===void 0&&(Y.minItems!==void 0||Y.maxItems!==void 0||Y.items!==void 0||Y.prefixItems!==void 0)){if(Q.array===void 0)Q.array=N.array(N.any())}}},UC6=class{apply(Q,X){let Y=X;if(Y.minItems===void 0)return;if(Q.array!==!1)Q.array=(Q.array||N.array(N.any())).min(Y.minItems)}},BC6=class{apply(Q,X){let Y=X;if(Y.maxItems===void 0)return;if(Q.array!==!1)Q.array=(Q.array||N.array(N.any())).max(Y.maxItems)}},DC6=class{apply(Q,X){let Y=X;if(Q.array===!1)return;if(Array.isArray(Y.items))Q.array=Q.array||N.array(N.any());else if(Y.items&&typeof Y.items!=="boolean"&&!Y.prefixItems){let J=q9(Y.items),G=N.array(J);if(Q.array&&Q.array instanceof N.ZodArray){let W=Q.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)}})}Q.array=G}else if(typeof Y.items==="boolean"&&Y.items===!1)if(!Y.prefixItems)Q.array=N.array(N.any()).max(0);else Q.array=Q.array||N.array(N.any());else if(typeof Y.items==="boolean"&&Y.items===!0)Q.array=Q.array||N.array(N.any());else if(Y.prefixItems)Q.array=Q.array||N.array(N.any())}},NC6=class{apply(Q,X){if(X.type!=="array")return;let Y=X;if(!Array.isArray(Y.items))return;if(Q.array===!1)return;let J=Y.items.map((W)=>q9(W)),G;if(J.length===0)G=N.tuple([]);else G=N.tuple(J);if(Y.minItems!==void 0&&Y.minItems>J.length)G=!1;if(Y.maxItems!==void 0&&Y.maxItems<J.length)G=!1;Q.tuple=G,Q.array=!1}},OC6=class{apply(Q,X){let Y=X;if(Q.object===!1)return;if(Y.properties||Y.required||Y.additionalProperties!==void 0)Q.object=Q.object||N.object({}).passthrough()}},LC6=class{apply(Q,X){let Y=X;if(X.type===void 0&&(Y.maxProperties!==void 0||Y.minProperties!==void 0)){if(Q.object===void 0)Q.object=N.object({}).passthrough()}}},wC6=class{apply(Q,X){let Y=X;if(Y.maxProperties===void 0)return;if(Q.object!==!1){let J=Q.object||N.object({}).passthrough();Q.object=J.refine((G)=>Object.keys(G).length<=Y.maxProperties,{message:`Object must have at most ${Y.maxProperties} properties`})}}},MC6=class{apply(Q,X){let Y=X;if(Y.minProperties===void 0)return;if(Q.object!==!1){let J=Q.object||N.object({}).passthrough();Q.object=J.refine((G)=>Object.keys(G).length>=Y.minProperties,{message:`Object must have at least ${Y.minProperties} properties`})}}},TC6=class{apply(Q,X){if(!X.not)return Q;let Y=q9(X.not);return Q.refine((J)=>!Jy(Y,J),{message:"Value must not match the 'not' schema"})}},AC6=class{apply(Q,X){if(X.uniqueItems!==!0)return Q;return Q.refine(PC6(),{message:"Array items must be unique"})}},EC6=class{apply(Q,X){if(!X.allOf||X.allOf.length===0)return Q;return X.allOf.map((J)=>q9(J)).reduce((J,G)=>N.intersection(J,G),Q)}},jC6=class{apply(Q,X){if(!X.anyOf||X.anyOf.length===0)return Q;let Y=X.anyOf.length===1?q9(X.anyOf[0]):N.union([q9(X.anyOf[0]),q9(X.anyOf[1]),...X.anyOf.slice(2).map((J)=>q9(J))]);return N.intersection(Q,Y)}},CC6=class{apply(Q,X){if(!X.oneOf||X.oneOf.length===0)return Q;let Y=X.oneOf.map((J)=>q9(J));return Q.refine((J)=>{let G=0;for(let W of Y)if(W.safeParse(J).success){if(G++,G>1)return!1}return G===1},{message:"Value must match exactly one of the oneOf schemas"})}},IC6=class{apply(Q,X){let Y=X;if(Y.prefixItems&&Array.isArray(Y.prefixItems)){let G=Y.prefixItems.map((W)=>q9(W));return Q.refine((W)=>{if(!Array.isArray(W))return!0;for(let Z=0;Z<Math.min(W.length,G.length);Z++)if(!Jy(G[Z],W[Z]))return!1;if(W.length>G.length){if(typeof Y.items==="boolean"&&Y.items===!1)return!1;else if(Y.items&&typeof Y.items==="object"&&!Array.isArray(Y.items)){let Z=q9(Y.items);for(let $=G.length;$<W.length;$++)if(!Jy(Z,W[$]))return!1}}return!0},{message:"Array does not match prefixItems schema"})}return Q}},RC6=class{apply(Q,X){let Y=X;if(!Y.properties&&!Y.required&&Y.additionalProperties!==!1)return Q;if(Q instanceof N.ZodObject||Q instanceof N.ZodRecord){let J={};if(Y.properties){for(let[G,W]of Object.entries(Y.properties))if(W!==void 0)J[G]=q9(W)}if(Y.required&&Array.isArray(Y.required)){let G=new Set(Y.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(Y.additionalProperties===!1)return N.object(J);else return N.object(J).passthrough()}return Q.refine((J)=>{if(typeof J!=="object"||J===null||Array.isArray(J))return!0;if(Y.properties){for(let[G,W]of Object.entries(Y.properties))if(W!==void 0){if(Object.getOwnPropertyDescriptor(J,G)!==void 0){if(!q9(W).safeParse(J[G]).success)return!1}}}if(Y.required&&Array.isArray(Y.required)){for(let G of Y.required)if(Object.getOwnPropertyDescriptor(J,G)===void 0)return!1}if(Y.additionalProperties===!1&&Y.properties){let G=new Set(Object.keys(Y.properties));for(let W in J)if(!G.has(W))return!1}return!0},{message:"Object constraints validation failed"})}},SC6=class{apply(Q,X){if(!X.enum||X.enum.length===0)return Q;let Y=X.enum.filter((J)=>Array.isArray(J)||typeof J==="object"&&J!==null);if(Y.length===0)return Q;return Q.refine((J)=>{if(typeof J!=="object"||J===null)return!0;return Y.some((G)=>vM(J,G))},{message:"Value must match one of the enum values"})}},kC6=class{apply(Q,X){if(X.const===void 0)return Q;let Y=X.const;if(typeof Y!=="object"||Y===null)return Q;return Q.refine((J)=>vM(J,Y),{message:"Value must equal the const value"})}},vC6=class{apply(Q,X){if(X.description)Q=Q.describe(X.description);return Q}},_C6=class{apply(Q,X){var Y;let J=X;if(!((Y=J.required)==null?void 0:Y.includes("__proto__"))||X.type!==void 0)return Q;return N.any().refine((G)=>this.validateRequired(G,J.required),{message:"Missing required properties"})}validateRequired(Q,X){if(typeof Q!=="object"||Q===null||Array.isArray(Q))return!0;return X.every((Y)=>Object.prototype.hasOwnProperty.call(Q,Y))}},yC6=class{apply(Q,X){var Y;let J=X;if(J.contains===void 0)return Q;let G=q9(J.contains),W=(Y=J.minContains)!=null?Y:1,Z=J.maxContains;return Q.refine(($)=>{if(!Array.isArray($))return!0;let K=0;for(let H of $)if(Jy(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"})}},bC6=class{apply(Q,X){let{default:Y}=X;if(Y===void 0)return Q;if(!Q.safeParse(Y).success)return Q;return Q.default(Y)}},fC6,hC6;var _Q1=o(()=>{r6();r6();r6();r6();r6();r6();r6();r6();r6();r6();r6();r6();r6();r6();fC6=[new XC6,new YC6,new QC6,new JC6,new GC6,new zC6,new LC6,new WC6,new ZC6,new $C6,new KC6,new HC6,new FC6,new VC6,new qC6,new NC6,new UC6,new BC6,new DC6,new wC6,new MC6,new OC6],hC6=[new _C6,new SC6,new kC6,new EC6,new jC6,new CC6,new IC6,new RC6,new yC6,new TC6,new AC6,new bC6,new vC6]});function xC6(Q){let X=globalThis.DOMException;return typeof X=="function"?new X(Q,"SyntaxError"):SyntaxError(Q)}function R60(Q){return Q instanceof Error?"errors"in Q&&Array.isArray(Q.errors)?Q.errors.map(R60).join(", "):("cause"in Q)&&Q.cause instanceof Error?`${Q}: ${R60(Q.cause)}`:Q.message:`${Q}`}function yQ1(Q){return{type:Q.type,message:Q.message,code:Q.code,defaultPrevented:Q.defaultPrevented,cancelable:Q.cancelable,timeStamp:Q.timeStamp}}function gC6(){let Q="document"in globalThis?globalThis.document:void 0;return Q&&typeof Q=="object"&&"baseURI"in Q&&typeof Q.baseURI=="string"?Q.baseURI:void 0}var I60,fQ1=(Q)=>{throw TypeError(Q)},h60=(Q,X,Y)=>X.has(Q)||fQ1("Cannot "+Y),I6=(Q,X,Y)=>(h60(Q,X,"read from private field"),Y?Y.call(Q):X.get(Q)),BQ=(Q,X,Y)=>X.has(Q)?fQ1("Cannot add the same private member more than once"):X instanceof WeakSet?X.add(Q):X.set(Q,Y),P8=(Q,X,Y,J)=>(h60(Q,X,"write to private field"),X.set(Q,Y),Y),R7=(Q,X,Y)=>(h60(Q,X,"access private method"),Y),YY,n3,BU,Gy,Wy,bM,OU,fM,l$,DU,LU,NU,_M,C5,S60,k60,v60,bQ1,_60,y60,yM,b60,f60,wU;var hQ1=o(()=>{U60();I60=class I60 extends Event{constructor(Q,X){var Y,J;super(Q),this.code=(Y=X==null?void 0:X.code)!=null?Y:void 0,this.message=(J=X==null?void 0:X.message)!=null?J:void 0}[Symbol.for("nodejs.util.inspect.custom")](Q,X,Y){return Y(yQ1(this),X)}[Symbol.for("Deno.customInspect")](Q,X){return Q(yQ1(this),X)}};wU=class wU extends EventTarget{constructor(Q,X){var Y,J;super(),BQ(this,C5),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,BQ(this,YY),BQ(this,n3),BQ(this,BU),BQ(this,Gy),BQ(this,Wy),BQ(this,bM),BQ(this,OU),BQ(this,fM,null),BQ(this,l$),BQ(this,DU),BQ(this,LU,null),BQ(this,NU,null),BQ(this,_M,null),BQ(this,k60,async(G)=>{var W;I6(this,DU).reset();let{body:Z,redirected:$,status:K,headers:H}=G;if(K===204){R7(this,C5,yM).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if($?P8(this,BU,new URL(G.url)):P8(this,BU,void 0),K!==200){R7(this,C5,yM).call(this,`Non-200 status code (${K})`,K);return}if(!(H.get("content-type")||"").startsWith("text/event-stream")){R7(this,C5,yM).call(this,'Invalid content type, expected "text/event-stream"',K);return}if(I6(this,YY)===this.CLOSED)return;P8(this,YY,this.OPEN);let F=new Event("open");if((W=I6(this,_M))==null||W.call(this,F),this.dispatchEvent(F),typeof Z!="object"||!Z||!("getReader"in Z)){R7(this,C5,yM).call(this,"Invalid response body, expected a web ReadableStream",K),this.close();return}let V=new TextDecoder,q=Z.getReader(),U=!0;do{let{done:D,value:B}=await q.read();B&&I6(this,DU).feed(V.decode(B,{stream:!D})),D&&(U=!1,I6(this,DU).reset(),R7(this,C5,b60).call(this))}while(U)}),BQ(this,v60,(G)=>{P8(this,l$,void 0),!(G.name==="AbortError"||G.type==="aborted")&&R7(this,C5,b60).call(this,R60(G))}),BQ(this,_60,(G)=>{typeof G.id=="string"&&P8(this,fM,G.id);let W=new MessageEvent(G.event||"message",{data:G.data,origin:I6(this,BU)?I6(this,BU).origin:I6(this,n3).origin,lastEventId:G.id||""});I6(this,NU)&&(!G.event||G.event==="message")&&I6(this,NU).call(this,W),this.dispatchEvent(W)}),BQ(this,y60,(G)=>{P8(this,bM,G)}),BQ(this,f60,()=>{P8(this,OU,void 0),I6(this,YY)===this.CONNECTING&&R7(this,C5,S60).call(this)});try{if(Q instanceof URL)P8(this,n3,Q);else if(typeof Q=="string")P8(this,n3,new URL(Q,gC6()));else throw Error("Invalid URL")}catch{throw xC6("An invalid or illegal string was specified")}P8(this,DU,t_({onEvent:I6(this,_60),onRetry:I6(this,y60)})),P8(this,YY,this.CONNECTING),P8(this,bM,3000),P8(this,Wy,(Y=X==null?void 0:X.fetch)!=null?Y:globalThis.fetch),P8(this,Gy,(J=X==null?void 0:X.withCredentials)!=null?J:!1),R7(this,C5,S60).call(this)}get readyState(){return I6(this,YY)}get url(){return I6(this,n3).href}get withCredentials(){return I6(this,Gy)}get onerror(){return I6(this,LU)}set onerror(Q){P8(this,LU,Q)}get onmessage(){return I6(this,NU)}set onmessage(Q){P8(this,NU,Q)}get onopen(){return I6(this,_M)}set onopen(Q){P8(this,_M,Q)}addEventListener(Q,X,Y){let J=X;super.addEventListener(Q,J,Y)}removeEventListener(Q,X,Y){let J=X;super.removeEventListener(Q,J,Y)}close(){I6(this,OU)&&clearTimeout(I6(this,OU)),I6(this,YY)!==this.CLOSED&&(I6(this,l$)&&I6(this,l$).abort(),P8(this,YY,this.CLOSED),P8(this,l$,void 0))}};YY=new WeakMap,n3=new WeakMap,BU=new WeakMap,Gy=new WeakMap,Wy=new WeakMap,bM=new WeakMap,OU=new WeakMap,fM=new WeakMap,l$=new WeakMap,DU=new WeakMap,LU=new WeakMap,NU=new WeakMap,_M=new WeakMap,C5=new WeakSet,S60=function(){P8(this,YY,this.CONNECTING),P8(this,l$,new AbortController),I6(this,Wy)(I6(this,n3),R7(this,C5,bQ1).call(this)).then(I6(this,k60)).catch(I6(this,v60))},k60=new WeakMap,v60=new WeakMap,bQ1=function(){var Q;let X={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...I6(this,fM)?{"Last-Event-ID":I6(this,fM)}:void 0},cache:"no-store",signal:(Q=I6(this,l$))==null?void 0:Q.signal};return"window"in globalThis&&(X.credentials=this.withCredentials?"include":"same-origin"),X},_60=new WeakMap,y60=new WeakMap,yM=function(Q,X){var Y;I6(this,YY)!==this.CLOSED&&P8(this,YY,this.CLOSED);let J=new I60("error",{code:X,message:Q});(Y=I6(this,LU))==null||Y.call(this,J),this.dispatchEvent(J)},b60=function(Q,X){var Y;if(I6(this,YY)===this.CLOSED)return;P8(this,YY,this.CONNECTING);let J=new I60("error",{code:X,message:Q});(Y=I6(this,LU))==null||Y.call(this,J),this.dispatchEvent(J),P8(this,OU,setTimeout(I6(this,f60),I6(this,bM)))},f60=new WeakMap,wU.CONNECTING=0,wU.OPEN=1,wU.CLOSED=2});class x60{constructor(Q,X){this._url=Q,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=X?.eventSourceInit,this._requestInit=X?.requestInit,this._authProvider=X?.authProvider,this._fetch=X?.fetch,this._fetchWithInit=g_(X?.fetch,X?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new XY("No auth provider");let Q;try{Q=await C7(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(X){throw this.onerror?.(X),X}if(Q!=="AUTHORIZED")throw new XY;return await this._startOrAuth()}async _commonHeaders(){let Q={};if(this._authProvider){let Y=await this._authProvider.tokens();if(Y)Q.Authorization=`Bearer ${Y.access_token}`}if(this._protocolVersion)Q["mcp-protocol-version"]=this._protocolVersion;let X=$U(this._requestInit?.headers);return new Headers({...Q,...X})}_startOrAuth(){let Q=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((X,Y)=>{this._eventSource=new wU(this._url.href,{...this._eventSourceInit,fetch:async(J,G)=>{let W=await this._commonHeaders();W.set("Accept","text/event-stream");let Z=await Q(J,{...G,headers:W});if(Z.status===401&&Z.headers.has("www-authenticate")){let{resourceMetadataUrl:$,scope:K}=qU(Z);this._resourceMetadataUrl=$,this._scope=K}return Z}}),this._abortController=new AbortController,this._eventSource.onerror=(J)=>{if(J.code===401&&this._authProvider){this._authThenStart().then(X,Y);return}let G=new xQ1(J.code,J.message,J);Y(G),this.onerror?.(G)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",(J)=>{let G=J;try{if(this._endpoint=new URL(G.data,this._url),this._endpoint.origin!==this._url.origin)throw Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(W){Y(W),this.onerror?.(W),this.close();return}X()}),this._eventSource.onmessage=(J)=>{let G=J,W;try{W=vY.parse(JSON.parse(G.data))}catch(Z){this.onerror?.(Z);return}this.onmessage?.(W)}})}async start(){if(this._eventSource)throw Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(Q){if(!this._authProvider)throw new XY("No auth provider");if(await C7(this._authProvider,{serverUrl:this._url,authorizationCode:Q,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new XY("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(Q){if(!this._endpoint)throw Error("Not connected");try{let X=await this._commonHeaders();X.set("content-type","application/json");let Y={...this._requestInit,method:"POST",headers:X,body:JSON.stringify(Q),signal:this._abortController?.signal},J=await(this._fetch??fetch)(this._endpoint,Y);if(!J.ok){let G=await J.text().catch(()=>null);if(J.status===401&&this._authProvider){let{resourceMetadataUrl:W,scope:Z}=qU(J);if(this._resourceMetadataUrl=W,this._scope=Z,await C7(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new XY;return this.send(Q)}throw Error(`Error POSTing to endpoint (HTTP ${J.status}): ${G}`)}await J.body?.cancel()}catch(X){throw this.onerror?.(X),X}}setProtocolVersion(Q){this._protocolVersion=Q}}var xQ1;var gQ1=o(()=>{hQ1();_9();V60();xQ1=class xQ1 extends Error{constructor(Q,X,Y){super(`SSE error: ${X}`);this.code=Q,this.event=Y}}});class g60{constructor(Q){this._url=Q}start(){if(this._socket)throw Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((Q,X)=>{this._socket=new WebSocket(this._url,uC6),this._socket.onerror=(Y)=>{let J="error"in Y?Y.error:Error(`WebSocket error: ${JSON.stringify(Y)}`);X(J),this.onerror?.(J)},this._socket.onopen=()=>{Q()},this._socket.onclose=()=>{this.onclose?.()},this._socket.onmessage=(Y)=>{let J;try{J=vY.parse(JSON.parse(Y.data))}catch(G){this.onerror?.(G);return}this.onmessage?.(J)}})}async close(){this._socket?.close()}send(Q){return new Promise((X,Y)=>{if(!this._socket){Y(Error("Not connected"));return}this._socket?.send(JSON.stringify(Q)),X()})}}var uC6="mcp";var uQ1=o(()=>{_9()});function mC6(Q){let X=Q;if(!X||typeof X!=="object"||!("method"in X))return null;switch(X.method){case"initialize":{let Y=X?.params?.protocolVersion;if(!Y)return null;return{type:"emit",message:{result:{protocolVersion:Y,capabilities:{tools:{}},serverInfo:{name:"deco-chat-server",version:"1.0.0"}},jsonrpc:X.jsonrpc??"2.0",id:X.id}}}case"notifications/roots/list_changed":case"notifications/initialized":case"notifications/cancelled":case"notifications/progress":return{type:"suppress"};default:return null}}var u60;var mQ1=o(()=>{RM();u60=class u60 extends I7{constructor(Q,X){super(Q,X)}send(Q,X){let Y=mC6(Q);if(Y?.type==="emit")return this.onmessage?.(Y.message),Promise.resolve();if(Y?.type==="suppress")return Promise.resolve();return super.send(Q,X)}}});var lQ1,dQ1=async(Q,X,Y)=>{let J=lC6(Q.connection,X,Y);if(!J)throw Error("Unknown MCP connection type");let G=new lQ1({name:Q?.name??"MCP Client",version:"1.0.0"});return await G.connect(J),{client:G,callStreamableTool:(W,Z)=>{if(Q.connection.type!=="HTTP")throw Error("HTTP connection required");let $=new Headers(Y);if(!$.has("Authorization"))$.set("Authorization",`Bearer ${Q.connection.token}`);for(let[F,V]of Object.entries(Q.connection.headers??{}))$.set(F,V);let K=new URL(Q.connection.url),H=K.pathname.replace(/\/+$/,"")||"/";return K.pathname=`${H}/call-tool/${encodeURIComponent(W)}`,fetch(K.href,{method:"POST",redirect:"manual",body:JSON.stringify(Z),headers:$})}}},lC6=(Q,X,Y)=>{if(Q.type==="Websocket")return new g60(new URL(Q.url));if(Q.type!=="SSE"&&Q.type!=="HTTP")return null;let G={...Q.token?{authorization:`Bearer ${Q.token}`}:{},...Y??{},..."headers"in Q?Q.headers||{}:{}};if(Q.type==="SSE"){let W={requestInit:{headers:G,signal:X}};if(Q.token)W.eventSourceInit={fetch:(Z,$)=>{return fetch(Z,{...$,headers:{...G,Accept:"text/event-stream"},signal:X})}};return new x60(new URL(Q.url),W)}return new u60(new URL(Q.url),{requestInit:{headers:G,signal:X,credentials:"include"}})};var pQ1=o(()=>{GU();gQ1();uQ1();_9();mQ1();lQ1=class lQ1 extends _J{constructor(Q,X){super(Q,X)}async listTools(Q,X){return await this.request({method:"tools/list",params:Q},tw,X)}}});function nQ1(Q){let X=(Y)=>{if("connection"in Q)return dQ1({connection:Q.connection},void 0,Y);return Q.client};return new Proxy({},{get(Y,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=Q?.debugId?.(),V=F?{"x-trace-debug-id":F}:void 0,{client:q,callStreamableTool:U}=await X(V);if(Q?.streamable?.[String(H)])return U(String(H),K);let{structuredContent:D,isError:B,content:L}=await q.callTool({name:String(H),arguments:K});if(B){let M=L?.[0]?.text,C=typeof M==="string"?dC6(M):null,E=C?.code&&typeof Q?.getErrorByStatusCode==="function"?Q.getErrorByStatusCode(C.code,C.message,C.traceId):null;if(E)throw E;throw Error(`Tool ${String(H)} returned an error: ${JSON.stringify(D??L)}`)}return D}async function W(){let{client:K}=await X(),{tools:H}=await K.listTools();return H}async function Z(){if(!("connection"in Q))return W();let K=Q.connection,H=JSON.stringify(K);try{if(!Zy.has(H))Zy.set(H,W());return await Zy.get(H)}catch(F){console.error("Failed to list tools",F),Zy.delete(H);return}}async function $(){return(await Z()??[]).map((H)=>cQ1(H,G))}return G.asTool=async()=>{let H=(await Z()??[]).find((F)=>F.name===J);if(!H)throw Error(`Tool ${J} not found`);return cQ1(H,G)},G}})}var dC6=(Q)=>{try{return JSON.parse(Q)}catch{return Q}},Zy,cQ1=(Q,X)=>{return{...Q,id:Q.name,inputSchema:Q.inputSchema?q9(Q.inputSchema):void 0,outputSchema:Q.outputSchema?q9(Q.outputSchema):void 0,execute:(Y)=>{return X(Y.context,Q.name)}}};var iQ1=o(()=>{_Q1();pQ1();Zy=new Map});function $y(Q){return nQ1(Q)}var Uv4;var aQ1=o(()=>{iQ1();Uv4=new Proxy({},{get(Q,X){if(X==="toJSON")return null;if(X==="forConnection")return(Y)=>$y({connection:Y});return global[X]}})});function Ky(Q){return{isImplementedBy:(X)=>{for(let Y of Q){let J=typeof Y.name==="string"?new RegExp(`^${Y.name}$`):Y.name,G=X.find((W)=>J.test(W.name));if(!G&&Y.opt)continue;if(!G)return!1}return!0}}}var MU=(Q)=>{return{...Ky(Q),forClient:(X)=>{return $y({client:X,streamable:Q.reduce((Y,J)=>{return Y[J.name]=J.streamable===!0,Y},{})})},forConnection:(X)=>{return $y({connection:X,streamable:Q.reduce((Y,J)=>{return Y[J.name]=J.streamable===!0,Y},{})})}}};var hM=o(()=>{aQ1()});function gM(Q){return N.object({items:N.array(Q).describe("Array of collection items"),totalCount:N.number().int().min(0).optional().describe("Total number of matching items (if available)"),hasMore:N.boolean().optional().describe("Whether there are more items available")})}function l60(Q){return N.object({item:Q.nullable().describe("The retrieved item, or null if not found")})}function nC6(Q){return N.object({data:Q.partial().describe("Data for the new entity (id may be auto-generated)")})}function iC6(Q){return N.object({item:Q.describe("The created entity with generated id")})}function aC6(Q){return N.object({id:N.string().describe("ID of the entity to update"),data:Q.partial().describe("Partial entity data to update")})}function rC6(Q){return N.object({item:Q.describe("The updated entity")})}function p60(Q){return N.object({item:Q.describe("The deleted entity")})}function TU(Q,X,Y){let J=Q.toUpperCase(),G=Y?.readOnly??!1,W=[{name:`COLLECTION_${J}_LIST`,inputSchema:xM,outputSchema:gM(X)},{name:`COLLECTION_${J}_GET`,inputSchema:m60,outputSchema:l60(X)}];if(!G)W.push({name:`COLLECTION_${J}_CREATE`,inputSchema:nC6(X),outputSchema:iC6(X),opt:!0},{name:`COLLECTION_${J}_UPDATE`,inputSchema:aC6(X),outputSchema:rC6(X),opt:!0},{name:`COLLECTION_${J}_DELETE`,inputSchema:d60,outputSchema:p60(X),opt:!0});return W}var PU,pC6,rQ1,cC6,xM,m60,d60;var d$=o(()=>{W1();PU=N.object({id:N.string().describe("Unique identifier for the entity"),title:N.string().describe("Human-readable title for the entity"),description:N.string().nullish().describe("Description of the entity"),created_at:N.string().datetime(),updated_at:N.string().datetime(),created_by:N.string().optional(),updated_by:N.string().optional()}),pC6=N.object({field:N.array(N.string()),operator:N.enum(["eq","gt","gte","lt","lte","in","like","contains"]),value:N.unknown()}),rQ1=N.lazy(()=>N.union([pC6,N.object({operator:N.enum(["and","or","not"]),conditions:N.array(rQ1)})])),cC6=N.object({field:N.array(N.string()),direction:N.enum(["asc","desc"]),nulls:N.enum(["first","last"]).optional()}),xM=N.object({where:rQ1.optional().describe("Filter expression"),orderBy:N.array(cC6).optional().describe("Sort expressions"),limit:N.number().int().min(1).max(1000).optional().describe("Maximum number of items to return"),offset:N.number().int().min(0).optional().describe("Number of items to skip")});m60=N.object({id:N.string().describe("ID of the entity to retrieve")});d60=N.object({id:N.string().describe("ID of the entity to delete")})});var oC6,oQ1,Tv4;var sQ1=o(()=>{W1();d$();oC6=N.object({id:N.string(),name:N.string(),description:N.string().optional(),inputSchema:N.record(N.string(),N.unknown()),outputSchema:N.record(N.string(),N.unknown()).optional()}),oQ1=PU.extend({_meta:N.object({"io.decocms":N.object({id:N.string(),verified:N.boolean(),scopeName:N.string(),appName:N.string(),friendlyName:N.string().nullable().optional(),metadata:N.record(N.string(),N.unknown()).nullable().optional(),publishedAt:N.string().datetime().optional(),updatedAt:N.string().datetime().optional(),tools:N.array(oC6).nullable().optional().describe("Available tools exposed by this app")}).optional()}).optional(),server:N.object({$schema:N.string().optional(),_meta:N.record(N.string(),N.unknown()).optional(),name:N.string().describe("The server name (scope/app)"),title:N.string().optional().describe("User-friendly title"),description:N.string().optional().describe("Server description"),icons:N.array(N.object({src:N.string(),mimeType:N.string().optional(),sizes:N.array(N.string()).optional(),theme:N.enum(["light","dark"]).optional()})).optional(),remotes:N.array(N.object({type:N.enum(["http","stdio","sse"]),url:N.string().optional(),headers:N.array(N.unknown()).optional()})).optional(),packages:N.array(N.unknown()).optional(),repository:N.object({url:N.string(),source:N.string().optional(),subfolder:N.string().optional()}).optional(),version:N.string().optional(),websiteUrl:N.string().optional()})}),Tv4=TU("registry_app",oQ1,{readOnly:!0})});var tQ1,eQ1,Q91,X91,Y91,c60;var J91=o(()=>{W1();hM();tQ1=N.object({specversion:N.literal("1.0").describe("CloudEvents specification version"),id:N.string().describe("Unique identifier for this event (UUID recommended)"),source:N.string().describe("Connection ID of the event publisher"),type:N.string().describe("Event type (e.g., 'order.created', 'user.signup')"),time:N.string().datetime().optional().describe("Timestamp of when the event occurred (ISO 8601)"),subject:N.string().optional().describe("Subject/resource identifier (e.g., order ID, user ID)"),datacontenttype:N.string().optional().default("application/json").describe("Content type of the data attribute"),dataschema:N.string().url().optional().describe("URI to the schema for the data attribute"),data:N.unknown().optional().describe("Event payload (any JSON value)")}),eQ1=N.object({events:N.array(tQ1).min(1).describe("Batch of CloudEvents to process")}),Q91=N.object({success:N.boolean().optional().describe("Whether this event was processed successfully"),error:N.string().optional().describe("Error message for this event"),retryAfter:N.number().int().positive().optional().describe("Re-deliver this event after this many ms")}),X91=N.object({success:N.boolean().optional().describe("Batch success - applies to events not in results"),error:N.string().optional().describe("Batch error message - applies to events not in results"),processedCount:N.number().int().min(0).optional().describe("Number of events successfully processed"),retryAfter:N.number().int().positive().optional().describe("Batch retryAfter - applies to events not in results"),results:N.record(N.string(),Q91).optional().describe("Per-event results keyed by event ID")}),Y91=[{name:"ON_EVENTS",inputSchema:eQ1,outputSchema:X91}],c60=MU(Y91)});var uM,mM,lM,dM,G91,W91,pM,cM,nM,iM,aM,rM,oM,sM,Z91,sC6;var $91=o(()=>{W1();hM();uM=N.object({type:N.string().min(1).max(255).describe("Event type identifier"),subject:N.string().max(255).optional().describe("Subject/resource identifier (e.g., order ID)"),data:N.unknown().optional().describe("Event payload"),deliverAt:N.string().datetime().optional().describe("Scheduled delivery time (ISO 8601). Omit for immediate delivery."),cron:N.string().max(100).optional().describe("Cron expression for recurring delivery. Use EVENT_CANCEL to stop.")}),mM=N.object({id:N.string().describe("Unique event ID"),type:N.string().describe("Event type"),source:N.string().describe("Source connection ID"),time:N.string().describe("Event timestamp")}),lM=N.object({eventType:N.string().min(1).max(255).describe("Event type to subscribe to"),publisher:N.string().optional().describe("Filter events by publisher connection ID"),filter:N.string().max(1000).optional().describe("JSONPath filter expression on event data")}),dM=N.object({subscription:N.object({id:N.string().describe("Subscription ID"),connectionId:N.string().describe("Subscriber connection ID"),eventType:N.string().describe("Event type pattern"),publisher:N.string().nullable().describe("Publisher connection filter"),filter:N.string().nullable().describe("JSONPath filter expression"),enabled:N.boolean().describe("Whether subscription is enabled"),createdAt:N.union([N.string(),N.date()]).describe("Created timestamp"),updatedAt:N.union([N.string(),N.date()]).describe("Updated timestamp")})}),G91=N.object({eventType:N.string().min(1).max(255).describe("Event type to subscribe to"),publisher:N.string().optional().describe("Filter events by publisher connection ID"),filter:N.string().max(1000).optional().describe("JSONPath filter expression on event data")}),W91=N.object({id:N.string().describe("Subscription ID"),connectionId:N.string().describe("Subscriber connection ID"),eventType:N.string().describe("Event type pattern"),publisher:N.string().nullable().describe("Publisher connection filter"),filter:N.string().nullable().describe("JSONPath filter expression"),enabled:N.boolean().describe("Whether subscription is enabled"),createdAt:N.union([N.string(),N.date()]).describe("Created timestamp"),updatedAt:N.union([N.string(),N.date()]).describe("Updated timestamp")}),pM=N.object({subscriptions:N.array(G91).describe("Desired subscriptions - system will create/update/delete to match")}),cM=N.object({created:N.number().int().min(0).describe("Number of subscriptions created"),updated:N.number().int().min(0).describe("Number of subscriptions with filter updated"),deleted:N.number().int().min(0).describe("Number of subscriptions removed"),unchanged:N.number().int().min(0).describe("Number of subscriptions unchanged"),subscriptions:N.array(W91).describe("Current subscriptions after sync")}),nM=N.object({subscriptionId:N.string().describe("Subscription ID to remove")}),iM=N.object({success:N.boolean().describe("Whether unsubscribe was successful"),subscriptionId:N.string().describe("Subscription ID that was removed")}),aM=N.object({eventId:N.string().describe("Event ID to cancel")}),rM=N.object({success:N.boolean().describe("Whether cancellation was successful"),eventId:N.string().describe("Event ID that was cancelled")}),oM=N.object({eventId:N.string().describe("Event ID to acknowledge")}),sM=N.object({success:N.boolean().describe("Whether ACK was successful"),eventId:N.string().describe("Event ID that was acknowledged")}),Z91=[{name:"EVENT_PUBLISH",inputSchema:uM,outputSchema:mM},{name:"EVENT_SUBSCRIBE",inputSchema:lM,outputSchema:dM},{name:"EVENT_UNSUBSCRIBE",inputSchema:nM,outputSchema:iM},{name:"EVENT_CANCEL",inputSchema:aM,outputSchema:rM},{name:"EVENT_ACK",inputSchema:oM,outputSchema:sM},{name:"EVENT_SYNC_SUBSCRIPTIONS",inputSchema:pM,outputSchema:cM}],sC6=MU(Z91)});var Hy=o(()=>{hM();sQ1();J91();$91()});var tC6,eC6,K91;var H91=o(()=>{W1();d$();tC6=PU.extend({avatar:N.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:N.string().describe("System prompt that defines the assistant's behavior"),gateway_id:N.string().describe("Gateway ID to use for this assistant"),model:N.object({id:N.string().describe("Model ID"),connectionId:N.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),eC6=TU("assistant",tC6),K91=[...eC6]});var tM,S7,V91,QI6,XI6,q91,YI6,JI6,GI6,WI6,ZI6,$I6,z91,KI6,HI6,FI6,VI6,qI6,zI6,UI6,BI6,DI6,NI6,dv4,OI6,pv4,F91,LI6,wI6,n60,U91;var i60=o(()=>{W1();hM();d$();tM=N.lazy(()=>N.union([N.null(),N.string(),N.number(),N.boolean(),N.record(N.string(),tM),N.array(tM)])),S7=N.record(N.string(),N.record(N.string(),tM)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),V91=N.object({type:N.literal("text"),text:N.string().describe("The text content"),providerOptions:S7}),QI6=N.object({type:N.literal("text"),text:N.string().describe("The text content"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),XI6=N.string().describe("File data as URL string"),q91=N.object({type:N.literal("file"),filename:N.string().optional().describe("Optional filename of the file"),data:XI6,mediaType:N.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:S7}),YI6=N.object({type:N.literal("file"),mediaType:N.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),data:N.string().describe("Generated file data as base64 encoded string")}),JI6=N.object({type:N.literal("reasoning"),text:N.string().describe("The reasoning text"),providerOptions:S7}),GI6=N.object({type:N.literal("reasoning"),text:N.string().describe("The reasoning text"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),WI6=N.object({type:N.literal("tool-call"),toolCallId:N.string().describe("ID of the tool call, used to match with tool result"),toolName:N.string().describe("Name of the tool being called"),input:N.string().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:N.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:S7}),ZI6=N.object({type:N.literal("tool-call"),toolCallId:N.string().describe("ID of the tool call"),toolName:N.string().describe("Name of the tool being called"),input:N.string().describe("Stringified JSON object with the tool call arguments"),providerExecuted:N.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),$I6=N.union([N.object({type:N.literal("text"),value:N.string()}),N.object({type:N.literal("json"),value:tM}),N.object({type:N.literal("error-text"),value:N.string()}),N.object({type:N.literal("error-json"),value:tM}),N.object({type:N.literal("content"),value:N.array(N.union([N.object({type:N.literal("text"),text:N.string().describe("Text content")}),N.object({type:N.literal("media"),data:N.string().describe("Base-64 encoded media data"),mediaType:N.string().describe("IANA media type")})]))})]),z91=N.object({type:N.literal("tool-result"),toolCallId:N.string().describe("ID of the tool call that this result is associated with"),toolName:N.string().describe("Name of the tool that generated this result"),output:$I6.describe("Result of the tool call"),result:N.unknown().describe("Unknown result of the tool call"),providerOptions:S7}),KI6=N.object({type:N.literal("tool-result"),toolCallId:N.string().describe("ID of the tool call that this result is associated with"),toolName:N.string().describe("Name of the tool that generated this result"),result:N.any().describe("Result of the tool call (JSON-serializable)"),isError:N.boolean().optional().describe("Whether the result is an error or error message"),providerExecuted:N.boolean().optional().describe("Whether the tool result was generated by the provider"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),HI6=N.union([N.object({type:N.literal("source"),sourceType:N.literal("url"),id:N.string().describe("The ID of the source"),url:N.string().describe("The URL of the source"),title:N.string().optional().describe("The title of the source"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),N.object({type:N.literal("source"),sourceType:N.literal("document"),id:N.string().describe("The ID of the source"),mediaType:N.string().describe("IANA media type of the document (e.g., application/pdf)"),title:N.string().describe("The title of the document"),filename:N.string().optional().describe("Optional filename of the document"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")})]),FI6=N.object({role:N.literal("system"),content:N.string().describe("System message content"),providerOptions:S7}),VI6=N.object({role:N.literal("user"),content:N.array(N.union([V91,q91])).describe("User message content parts (text or file)"),providerOptions:S7}),qI6=N.object({role:N.literal("assistant"),content:N.array(N.union([V91,q91,JI6,WI6,z91])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:S7}),zI6=N.object({role:N.literal("tool"),content:N.array(z91).describe("Tool message content (tool results)"),providerOptions:S7}),UI6=N.union([FI6,VI6,qI6,zI6]),BI6=N.array(UI6).describe("A list of messages forming the prompt"),DI6=N.object({prompt:BI6.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:N.number().optional().describe("Maximum number of tokens to generate"),temperature:N.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:N.number().optional().describe("Nucleus sampling parameter"),topK:N.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:N.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:N.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:N.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:N.array(N.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:N.union([N.object({type:N.literal("text")}),N.object({type:N.literal("json"),schema:N.any().optional().describe("JSON schema that the generated output should conform to"),name:N.string().optional().describe("Name of output that should be generated"),description:N.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:N.array(N.any()).optional().describe("The tools that are available for the model"),toolChoice:N.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:N.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:N.any().optional().describe("Abort signal for cancelling the operation"),providerOptions:N.any().optional().describe("Additional provider-specific options")}),NI6=N.object({content:N.array(N.union([QI6,YI6,GI6,ZI6,KI6,HI6])).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:N.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:N.looseObject({inputTokens:N.number().optional(),outputTokens:N.number().optional(),totalTokens:N.number().optional(),reasoningTokens:N.number().optional()}).describe("Usage information for the language model call"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata"),request:N.object({body:N.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:N.object({id:N.string().optional().describe("ID for the generated response"),timestamp:N.iso.datetime().optional().describe("Timestamp for the start of the generated response"),modelId:N.string().optional().describe("The ID of the response model that was used"),headers:N.record(N.string(),N.string()).optional().describe("Response headers"),body:N.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:N.array(N.any()).describe("Warnings for the call, e.g. unsupported settings")}),dv4=N.object({stream:N.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:N.object({body:N.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:N.object({headers:N.record(N.string(),N.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),OI6=N.object({supportedUrls:N.record(N.string(),N.array(N.string())).describe("Supported URL patterns by media type for the provider")}),pv4=N.object({modelId:N.string().describe("The ID of the model"),logo:N.string().nullable(),description:N.string().nullable(),capabilities:N.array(N.string()),limits:N.object({contextWindow:N.number(),maxOutputTokens:N.number()}).nullable(),costs:N.object({input:N.number(),output:N.number()}).nullable(),provider:N.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),F91=N.object({modelId:N.string().describe("The ID of the model"),callOptions:DI6}),LI6=PU.extend({logo:N.string().nullable(),description:N.string().nullable(),capabilities:N.array(N.string()),limits:N.object({contextWindow:N.number(),maxOutputTokens:N.number()}).nullable(),costs:N.object({input:N.number(),output:N.number()}).nullable(),provider:N.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),wI6=TU("llm",LI6,{readOnly:!0}),n60=[{name:"LLM_METADATA",inputSchema:N.object({modelId:N.string().describe("The ID of the model")}),outputSchema:OI6},{name:"LLM_DO_STREAM",inputSchema:F91,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:F91,outputSchema:NI6},...wI6],U91=MU(n60)});function PI6(Q){let X=[],Y=0;while(Y<Q.length){let J=Q[Y];if(J==="%")X.push(".*");else if(J==="_")X.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))X.push("\\"+J);else X.push(J);Y++}return X.join("")}function p$(Q){return typeof Q==="string"||typeof Q==="number"}function Fy(Q,X){if("conditions"in X){let{operator:$,conditions:K}=X;switch($){case"and":return K.every((H)=>Fy(Q,H));case"or":return K.some((H)=>Fy(Q,H));case"not":return!K.every((H)=>Fy(Q,H));default:return!0}}let{field:Y,operator:J,value:G}=X,W=Y.join("."),Z=a60(Q,W);switch(J){case"eq":return Z===G;case"gt":return p$(Z)&&p$(G)&&Z>G;case"gte":return p$(Z)&&p$(G)&&Z>=G;case"lt":return p$(Z)&&p$(G)&&Z<G;case"lte":return p$(Z)&&p$(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 $=PI6(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 a60(Q,X){let Y=X.split("."),J=Q;for(let G of Y){if(J==null||typeof J!=="object")return;J=J[G]}return J}function TI6(Q,X){return[...Q].sort((Y,J)=>{for(let G of X){let W=G.field.join("."),Z=a60(Y,W),$=a60(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 MI6,AI6,EI6,r60;var B91=o(()=>{Hy();H91();d$();i60();W1();P6();U7();MI6={LLM:n60,ASSISTANTS:K91};AI6=xM.extend({binding:N.union([N.object({}).passthrough(),N.string()]).optional()}),EI6=gM(CJ),r60=N1({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",inputSchema:AI6,outputSchema:EI6,handler:async(Q,X)=>{await X.access.check();let Y=O6(X),J=Q.binding?typeof Q.binding==="string"?(()=>{let q=MI6[Q.binding.toUpperCase()];if(!q)throw Error(`Unknown binding: ${Q.binding}`);return q})():Q.binding:void 0,G=J?Ky(J):void 0,W=await X.storage.connections.list(Y.id),Z=G?await Promise.all(W.map(async(q)=>{if(!q.tools||q.tools.length===0)return null;return G.isImplementedBy(q.tools.map((D)=>({name:D.name,inputSchema:D.inputSchema,outputSchema:D.outputSchema})))?q:null})).then((q)=>q.filter((U)=>U!==null)):W;if(Q.where)Z=Z.filter((q)=>Fy(q,Q.where));if(Q.orderBy&&Q.orderBy.length>0)Z=TI6(Z,Q.orderBy);let $=Z.length,K=Q.offset??0,H=Q.limit??100,F=Z.slice(K,K+H),V=K+H<$;return{items:F,totalCount:$,hasMore:V}}})});var jI6,o60;var D91=o(()=>{d$();P6();U7();jI6=l60(CJ),o60=N1({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",inputSchema:m60,outputSchema:jI6,handler:async(Q,X)=>{let Y=O6(X);await X.access.check();let J=await X.storage.connections.findById(Q.id);if(!J||J.organization_id!==Y.id)return{item:null};return{item:J}}})});var Vy=(Q,X)=>{if(X===null||X===void 0)return;let Y=Q.replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),J=X;for(let G of Y){if(J===null||J===void 0||typeof J!=="object")return;J=J[G]}return J};function N91(Q){let X=Q.split("::");if(X.length!==2||!X[0]||!X[1])throw Error(`Invalid scope format: ${Q}. Expected format: "KEY::SCOPE"`);return X}function CI6(Q){let X=Q.split("::");if(X.length!==2||!X[0]||!X[1])return null;return X}function II6(Q){if(typeof Q==="object"&&Q!==null&&"value"in Q){let X=Q.value;if(typeof X==="string")return X}return null}function s60(Q,X){let Y={};if(!Q||!X)return Y;for(let J of X){if(J==="*"){Y["*"]=["*"];continue}let G=CI6(J);if(!G)continue;let[W,Z]=G,$=Vy(W,Q),K=II6($);if(K){if(!Y[K])Y[K]=[];Y[K].push(Z)}}return Y}function O91(Q,X){let Y=s60(Q,X);return new Set(Object.keys(Y).filter((J)=>J!=="*"))}var t60=()=>{};async function kI6(Q,X,Y,J){for(let W of X){if(W==="*")continue;let[Z]=N91(W),$=Vy(Z,Q);if($===void 0||$===null)throw Error(`Scope references key "${Z}" but it's not present in state`)}let G=O91(Q,X);for(let W of G){if(W===D5.SELF)continue;let Z=await J.storage.connections.findById(W);if(!Z||Z.organization_id!==Y)throw Error(`Referenced connection not found: ${W}`);try{await J.access.check(W)}catch($){throw Error(`Access denied to referenced connection: ${W}. ${$.message}`)}}}var RI6,SI6,e60;var L91=o(()=>{t60();R3();W1();P6();e_();U7();RI6=N.object({id:N.string().describe("ID of the connection to update"),data:es0.describe("Partial connection data to update")}),SI6=N.object({item:CJ.describe("The updated connection entity")});e60=N1({name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update an existing MCP connection in the organization",inputSchema:RI6,outputSchema:SI6,handler:async(Q,X)=>{S1(X);let Y=O6(X);await X.access.check();let{id:J,data:G}=Q,W=await X.storage.connections.findById(J);if(!W||W.organization_id!==Y.id)throw Error("Connection not found in organization");let Z=G.configuration_state??W.configuration_state,$=G.configuration_scopes??W.configuration_scopes??[];if(G.configuration_state!==void 0||G.configuration_scopes!==void 0){if(G.configuration_state!==void 0)Z=G.configuration_state;else if(Z===null)Z={};if(G.configuration_scopes!==void 0)$=G.configuration_scopes??[];if($.length>0&&Z)await kI6(Z,$,Y.id,X)}let K=await zU({id:W.id,title:G.title??W.title,connection_type:G.connection_type??W.connection_type,connection_url:G.connection_url??W.connection_url,connection_token:G.connection_token??W.connection_token,connection_headers:G.connection_headers??W.connection_headers}).catch(()=>null),H=K?.length?K:null,F={...G,tools:H,configuration_state:Z,configuration_scopes:$},V=await X.storage.connections.update(J,F);if((G.configuration_state!==void 0||G.configuration_scopes!==void 0)&&Z&&$.length>0)try{await(await X.createMCPProxy(J)).client.callTool({name:"ON_MCP_CONFIGURATION",arguments:{state:Z,scopes:$}})}catch(q){console.error("Failed to invoke ON_MCP_CONFIGURATION callback",q)}return{item:V}}})});var Q40;var w91=o(()=>{d$();P6();U7();Q40=N1({name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete a connection",inputSchema:d60,outputSchema:p60(CJ),handler:async(Q,X)=>{S1(X);let Y=O6(X);await X.access.check();let J=await X.storage.connections.findById(Q.id);if(!J)throw Error(`Connection not found: ${Q.id}`);if(J.organization_id!==Y.id)throw Error("Connection not found in organization");return await X.storage.connections.delete(Q.id),{item:J}}})});var X40;var M91=o(()=>{W1();P6();X40=N1({name:"CONNECTION_TEST",description:"Test connection health and latency",inputSchema:N.object({id:N.string()}),outputSchema:N.object({id:N.string(),healthy:N.boolean(),latencyMs:N.number()}),handler:async(Q,X)=>{let Y=O6(X);await X.access.check();let J=await X.storage.connections.findById(Q.id);if(!J||J.organization_id!==Y.id)throw Error("Connection not found");let G=await X.storage.connections.testConnection(Q.id);return{id:Q.id,...G}}})});var P91=o(()=>{vQ1();B91();D91();L91();w91();M91()});import{sql as t6}from"kysely";function T91(Q){if(Q===null||Q===void 0)return"NULL";if(typeof Q==="number")return String(Q);if(typeof Q==="boolean")return Q?"TRUE":"FALSE";if(typeof Q==="string")return`'${Q.replace(/'/g,"''")}'`;if(Q instanceof Date)return`'${Q.toISOString()}'`;return`'${JSON.stringify(Q).replace(/'/g,"''")}'`}function yI6(Q,X){let Y=Q;for(let G=X.length;G>=1;G--){let W=`$${G}`;if(Y.includes(W))Y=Y.replaceAll(W,T91(X[G-1]))}let J=[];for(let G=0;G<Y.length;G++)if(Y[G]==="?")J.push(G);for(let G=Math.min(J.length,X.length)-1;G>=0;G--){let W=J[G],Z=T91(X[G]);Y=Y.slice(0,W)+Z+Y.slice(W+1)}return Y}function A91(Q){return Q.replace(/-/g,"_")}function fI6(Q){return`app_${A91(Q)}`}function hI6(Q){return`app_role_${A91(Q)}`}function xI6(Q){if(Q instanceof Error){let X=Q.message.toLowerCase(),Y=Q.code;return Y==="3F000"||Y==="42704"||X.includes("schema")&&X.includes("does not exist")||X.includes("role")&&X.includes("does not exist")}return!1}async function gI6(Q,X,Y){if(await t6`CREATE SCHEMA IF NOT EXISTS ${t6.id(X)}`.execute(Q),!(await t6`
254
254
  SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${Y}) as exists
255
- `.execute(Q)).rows[0]?.exists)await t6`CREATE ROLE ${t6.id(Y)} NOLOGIN`.execute(Q);await t6`GRANT ${t6.id(Y)} TO CURRENT_USER`.execute(Q),await t6`GRANT USAGE, CREATE ON SCHEMA ${t6.id(X)} TO ${t6.id(Y)}`.execute(Q),await t6`GRANT ALL ON ALL TABLES IN SCHEMA ${t6.id(X)} TO ${t6.id(Y)}`.execute(Q),await t6`GRANT ALL ON ALL SEQUENCES IN SCHEMA ${t6.id(X)} TO ${t6.id(Y)}`.execute(Q),await t6`ALTER DEFAULT PRIVILEGES IN SCHEMA ${t6.id(X)} GRANT ALL ON TABLES TO ${t6.id(Y)}`.execute(Q),await t6`ALTER DEFAULT PRIVILEGES IN SCHEMA ${t6.id(X)} GRANT ALL ON SEQUENCES TO ${t6.id(Y)}`.execute(Q),await t6`REVOKE ALL ON SCHEMA public FROM ${t6.id(Y)}`.execute(Q)}async function uI6(Q,X,Y,J){try{return await Q.transaction().execute(async(G)=>{return await t6`SET LOCAL ROLE ${t6.id(Y)}`.execute(G),await t6`SET LOCAL search_path TO ${t6.id(X)}`.execute(G),await t6.raw(J).execute(G)})}catch(G){if(xI6(G))return await gI6(Q,X,Y),await Q.transaction().execute(async(W)=>{return await t6`SET LOCAL ROLE ${t6.id(Y)}`.execute(W),await t6`SET LOCAL search_path TO ${t6.id(X)}`.execute(W),await t6.raw(J).execute(W)});throw G}}var _I6,bI6,E91;var j91=o(()=>{W1();P6();_I6=N.object({results:N.array(N.unknown()).optional(),success:N.boolean().optional()});bI6=N.object({sql:N.string().describe("The SQL query to run"),params:N.array(N.any()).describe("The parameters to pass to the SQL query").optional()});E91=N1({name:"DATABASES_RUN_SQL",description:"Run a SQL query against the database",inputSchema:bI6,outputSchema:N.object({result:N.array(_I6)}),handler:async(Q,X)=>{S1(X),await X.access.check();let Y=yI6(Q.sql,Q.params||[]);if(!X.connectionId)throw Error("Connection context required for database access");let J=fI6(X.connectionId),G=hI6(X.connectionId);return{result:[{results:(await uI6(X.db,J,G,Y)).rows,success:!0}]}}})});var C91,lI6,I91;var k7=o(()=>{W1();Hy();C91=N.object({connectionId:N.string().optional().describe("Filter subscriptions by connection ID (optional)")}),lI6=N.object({id:N.string().describe("Subscription ID"),connectionId:N.string().describe("Subscriber connection ID"),eventType:N.string().describe("Event type pattern"),publisher:N.string().nullable().describe("Publisher connection filter (null = all publishers)"),filter:N.string().nullable().describe("JSONPath filter expression"),enabled:N.boolean().describe("Whether subscription is enabled"),createdAt:N.union([N.string(),N.date()]).describe("Created timestamp"),updatedAt:N.union([N.string(),N.date()]).describe("Updated timestamp")}),I91=N.object({subscriptions:N.array(lI6).describe("List of subscriptions")})});var Y40;var R91=o(()=>{P6();k7();Y40=N1({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:uM,outputSchema:mM,handler:async(Q,X)=>{S1(X);let Y=O6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to publish events. Use a connection-scoped token.");let G=await X.eventBus.publish(Y.id,J,{type:Q.type,subject:Q.subject,data:Q.data,deliverAt:Q.deliverAt,cron:Q.cron});return{id:G.id,type:G.type,source:G.source,time:G.time}}})});var J40;var S91=o(()=>{P6();k7();J40=N1({name:"EVENT_SUBSCRIBE",description:"Subscribe to events of a specific type. The subscriber is automatically set to the caller's connection.",inputSchema:lM,outputSchema:dM,handler:async(Q,X)=>{S1(X);let Y=O6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to subscribe. Use a connection-scoped token.");let G=await X.eventBus.subscribe(Y.id,{connectionId:J,eventType:Q.eventType,publisher:Q.publisher,filter:Q.filter});return{subscription:{id:G.id,connectionId:G.connectionId,eventType:G.eventType,publisher:G.publisher,filter:G.filter,enabled:G.enabled,createdAt:G.createdAt,updatedAt:G.updatedAt}}}})});var G40;var k91=o(()=>{P6();k7();G40=N1({name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events by removing a subscription.",inputSchema:nM,outputSchema:iM,handler:async(Q,X)=>{S1(X);let Y=O6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to unsubscribe. Use a connection-scoped token.");let G=await X.eventBus.getSubscription(Y.id,Q.subscriptionId);if(!G)throw Error(`Subscription not found: ${Q.subscriptionId}`);if(G.connectionId!==J)throw Error("Cannot unsubscribe from a subscription owned by another connection");return{success:(await X.eventBus.unsubscribe(Y.id,Q.subscriptionId)).success,subscriptionId:Q.subscriptionId}}})});var W40;var v91=o(()=>{P6();k7();W40=N1({name:"EVENT_CANCEL",description:"Cancel a recurring event to stop future deliveries. Only the publisher can cancel their own events.",inputSchema:aM,outputSchema:rM,handler:async(Q,X)=>{S1(X);let Y=O6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to cancel events. Use a connection-scoped token.");if(!await X.eventBus.getEvent(Y.id,Q.eventId))throw Error(`Event not found: ${Q.eventId}`);if(!(await X.eventBus.cancelEvent(Y.id,Q.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:Q.eventId}}})});var Z40;var _91=o(()=>{P6();k7();Z40=N1({name:"EVENT_ACK",description:"Acknowledge delivery of an event. Call after successfully processing an event received via ON_EVENTS with retryAfter.",inputSchema:oM,outputSchema:sM,handler:async(Q,X)=>{S1(X);let Y=O6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to acknowledge events. Use a connection-scoped token.");if(!(await X.eventBus.ackEvent(Y.id,Q.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:Q.eventId}}})});var $40;var y91=o(()=>{P6();k7();$40=N1({name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions, optionally filtered by connection ID.",inputSchema:C91,outputSchema:I91,handler:async(Q,X)=>{S1(X);let Y=O6(X);return await X.access.check(),{subscriptions:(await X.eventBus.listSubscriptions(Y.id,Q.connectionId)).map((G)=>({id:G.id,connectionId:G.connectionId,eventType:G.eventType,publisher:G.publisher,filter:G.filter,enabled:G.enabled,createdAt:G.createdAt,updatedAt:G.updatedAt}))}}})});var K40;var b91=o(()=>{P6();k7();K40=N1({name:"EVENT_SYNC_SUBSCRIPTIONS",description:"Sync subscriptions to desired state. Creates new, deletes removed, updates changed filters. Subscriptions are identified by (eventType, publisher).",inputSchema:pM,outputSchema:cM,handler:async(Q,X)=>{S1(X);let Y=O6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to sync subscriptions. Use a connection-scoped token.");let G=await X.eventBus.syncSubscriptions(Y.id,{connectionId:J,subscriptions:Q.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,updatedAt:W.updatedAt}))}}})});var f91=o(()=>{R91();S91();k91();v91();_91();y91();b91();k7()});var H40,F40,pI6,eG,h91,x91;var AU=o(()=>{W1();H40=N.enum(["inclusion","exclusion"]).describe("Tool selection mode: 'inclusion' = include selected (default), 'exclusion' = exclude selected"),F40=N.enum(["passthrough","smart_tool_selection","code_execution"]).describe("Gateway tool selection strategy: 'passthrough' (default), 'smart_tool_selection', or 'code_execution'"),pI6=N.object({connection_id:N.string().describe("Connection ID"),selected_tools:N.array(N.string()).nullable().describe("Selected tool names. With 'inclusion' mode: null = all tools included. With 'exclusion' mode: null = entire connection excluded"),selected_resources:N.array(N.string()).nullable().describe("Selected resource URIs or patterns. Supports * and ** wildcards for pattern matching. With 'inclusion' mode: null = all resources included."),selected_prompts:N.array(N.string()).nullable().describe("Selected prompt names. With 'inclusion' mode: null = all prompts included. With 'exclusion' mode: null = entire connection excluded.")}),eG=N.object({id:N.string().describe("Unique identifier for the gateway"),title:N.string().describe("Human-readable name for the gateway"),description:N.string().nullable().describe("Description of the gateway"),icon:N.string().nullable().optional().describe("Icon URL for the gateway"),created_at:N.string().describe("When the gateway was created"),updated_at:N.string().describe("When the gateway was last updated"),created_by:N.string().describe("User ID who created the gateway"),updated_by:N.string().optional().describe("User ID who last updated the gateway"),organization_id:N.string().describe("Organization ID this gateway belongs to"),tool_selection_strategy:F40.describe("Gateway behavior strategy (metadata for now): 'passthrough', 'smart_tool_selection', or 'code_execution'"),tool_selection_mode:H40.describe("Tool selection mode: 'inclusion' = include selected, 'exclusion' = exclude selected"),status:N.enum(["active","inactive"]).describe("Current status"),is_default:N.boolean().describe("Whether this is the default gateway for the organization"),connections:N.array(pI6).describe("Connections with their selected tools (behavior depends on tool_selection_mode)")}),h91=N.object({title:N.string().min(1).max(255).describe("Name for the gateway"),description:N.string().nullable().optional().describe("Optional description"),tool_selection_strategy:F40.optional().default("passthrough").describe("Gateway behavior strategy (defaults to 'passthrough')"),tool_selection_mode:H40.optional().default("inclusion").describe("Tool selection mode (defaults to 'inclusion')"),icon:N.string().nullable().optional().describe("Optional icon URL"),status:N.enum(["active","inactive"]).optional().default("active").describe("Initial status"),is_default:N.boolean().optional().default(!1).describe("Whether this is the default gateway for the organization"),connections:N.array(N.object({connection_id:N.string().describe("Connection ID"),selected_tools:N.array(N.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools or full exclusion)"),selected_resources:N.array(N.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources)"),selected_prompts:N.array(N.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)")}),x91=N.object({title:N.string().min(1).max(255).optional().describe("New name"),description:N.string().nullable().optional().describe("New description (null to clear)"),tool_selection_strategy:F40.optional().describe("New gateway behavior strategy"),tool_selection_mode:H40.optional().describe("New tool selection mode"),icon:N.string().nullable().optional().describe("New icon URL (null to clear)"),status:N.enum(["active","inactive"]).optional().describe("New status"),is_default:N.boolean().optional().describe("Set as default gateway for the organization"),connections:N.array(N.object({connection_id:N.string().describe("Connection ID"),selected_tools:N.array(N.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools or full exclusion)"),selected_resources:N.array(N.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources)"),selected_prompts:N.array(N.string()).nullable().optional().describe("Selected prompt names (null/undefined = all prompts or full exclusion)")})).optional().describe("New connections (replaces existing)")})});var cI6,nI6,V40;var g91=o(()=>{W1();P6();AU();cI6=N.object({data:h91.describe("Data for the new gateway")}),nI6=N.object({item:eG.describe("The created gateway entity")}),V40=N1({name:"COLLECTION_GATEWAY_CREATE",description:"Create a new MCP gateway in the organization",inputSchema:cI6,outputSchema:nI6,handler:async(Q,X)=>{S1(X);let Y=O6(X);await X.access.check();let J=b9(X);if(!J)throw Error("User ID required to create gateway");let G={title:Q.data.title,description:Q.data.description??null,toolSelectionStrategy:Q.data.tool_selection_strategy??"passthrough",toolSelectionMode:Q.data.tool_selection_mode??"inclusion",icon:Q.data.icon??null,status:Q.data.status,isDefault:Q.data.is_default??!1,connections:Q.data.connections.map((Z)=>({connectionId:Z.connection_id,selectedTools:Z.selected_tools??null,selectedResources:Z.selected_resources??null,selectedPrompts:Z.selected_prompts??null}))},W=await X.storage.gateways.create(Y.id,J,G);return{item:{id:W.id,title:W.title,description:W.description,icon:W.icon,organization_id:W.organizationId,tool_selection_strategy:W.toolSelectionStrategy,tool_selection_mode:W.toolSelectionMode,status:W.status,is_default:W.isDefault,connections:W.connections.map((Z)=>({connection_id:Z.connectionId,selected_tools:Z.selectedTools,selected_resources:Z.selectedResources,selected_prompts:Z.selectedPrompts})),created_at:W.createdAt,updated_at:W.updatedAt,created_by:W.createdBy,updated_by:W.updatedBy??void 0}}}})});function iI6(Q){let X=[],Y=0;while(Y<Q.length){let J=Q[Y];if(J==="%")X.push(".*");else if(J==="_")X.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))X.push("\\"+J);else X.push(J);Y++}return X.join("")}function c$(Q){return typeof Q==="string"||typeof Q==="number"}function q40(Q,X){let Y=X.split("."),J=Q;for(let G of Y){if(J==null||typeof J!=="object")return;J=J[G]}return J}function aI6(Q,X){return Q.connections.some((Y)=>Y.connection_id===X)}function qy(Q,X){if("conditions"in X){let{operator:$,conditions:K}=X;switch($){case"and":return K.every((H)=>qy(Q,H));case"or":return K.some((H)=>qy(Q,H));case"not":return!K.every((H)=>qy(Q,H));default:return!0}}let{field:Y,operator:J,value:G}=X,W=Y.join(".");if(W==="connection_id"){if(J!=="eq"||typeof G!=="string")return!1;return aI6(Q,G)}let Z=q40(Q,W);switch(J){case"eq":return Z===G;case"gt":return c$(Z)&&c$(G)&&Z>G;case"gte":return c$(Z)&&c$(G)&&Z>=G;case"lt":return c$(Z)&&c$(G)&&Z<G;case"lte":return c$(Z)&&c$(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 $=iI6(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 rI6(Q,X){return[...Q].sort((Y,J)=>{for(let G of X){let W=G.field.join("."),Z=q40(Y,W),$=q40(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 oI6,sI6,z40;var u91=o(()=>{d$();P6();AU();oI6=xM,sI6=gM(eG),z40=N1({name:"COLLECTION_GATEWAY_LIST",description:"List all MCP gateways in the organization",inputSchema:oI6,outputSchema:sI6,handler:async(Q,X)=>{await X.access.check();let Y=O6(X),J=Q.where&&!("conditions"in Q.where)&&Q.where.field.join(".")==="connection_id"&&Q.where.operator==="eq"&&typeof Q.where.value==="string"?Q.where.value:void 0,W=(J?await X.storage.gateways.listByConnectionId(Y.id,J):await X.storage.gateways.list(Y.id)).map((V)=>({id:V.id,title:V.title,description:V.description,icon:V.icon,is_default:V.isDefault,organization_id:V.organizationId,tool_selection_strategy:V.toolSelectionStrategy,tool_selection_mode:V.toolSelectionMode,status:V.status,connections:V.connections.map((q)=>({connection_id:q.connectionId,selected_tools:q.selectedTools,selected_resources:q.selectedResources,selected_prompts:q.selectedPrompts})),created_at:V.createdAt,updated_at:V.updatedAt,created_by:V.createdBy,updated_by:V.updatedBy??void 0}));if(Q.where)W=W.filter((V)=>qy(V,Q.where));if(Q.orderBy&&Q.orderBy.length>0)W=rI6(W,Q.orderBy);let Z=W.length,$=Q.offset??0,K=Q.limit??100,H=W.slice($,$+K),F=$+K<Z;return{items:H,totalCount:Z,hasMore:F}}})});var tI6,eI6,U40;var m91=o(()=>{W1();P6();AU();tI6=N.object({id:N.string().describe("ID of the gateway to retrieve")}),eI6=N.object({item:eG.nullable().describe("The retrieved gateway, or null if not found")}),U40=N1({name:"COLLECTION_GATEWAY_GET",description:"Get an MCP gateway by ID",inputSchema:tI6,outputSchema:eI6,handler:async(Q,X)=>{S1(X);let Y=O6(X);await X.access.check();let J=await X.storage.gateways.findById(Q.id);if(J&&J.organizationId!==Y.id)return{item:null};if(!J)return{item:null};return{item:{id:J.id,title:J.title,description:J.description,icon:J.icon,organization_id:J.organizationId,tool_selection_strategy:J.toolSelectionStrategy,tool_selection_mode:J.toolSelectionMode,status:J.status,is_default:J.isDefault,connections:J.connections.map((G)=>({connection_id:G.connectionId,selected_tools:G.selectedTools,selected_resources:G.selectedResources,selected_prompts:G.selectedPrompts})),created_at:J.createdAt,updated_at:J.updatedAt,created_by:J.createdBy,updated_by:J.updatedBy??void 0}}}})});var QR6,XR6,B40;var l91=o(()=>{W1();P6();AU();QR6=N.object({id:N.string().describe("ID of the gateway to update"),data:x91.describe("Partial gateway data to update")}),XR6=N.object({item:eG.describe("The updated gateway entity")}),B40=N1({name:"COLLECTION_GATEWAY_UPDATE",description:"Update an MCP gateway",inputSchema:QR6,outputSchema:XR6,handler:async(Q,X)=>{S1(X);let Y=O6(X);await X.access.check();let J=b9(X);if(!J)throw Error("User ID required to update gateway");let G=await X.storage.gateways.findById(Q.id);if(!G)throw Error(`Gateway not found: ${Q.id}`);if(G.organizationId!==Y.id)throw Error(`Gateway not found: ${Q.id}`);let W={};if(Q.data.title!==void 0)W.title=Q.data.title;if(Q.data.description!==void 0)W.description=Q.data.description;if(Q.data.tool_selection_strategy!==void 0)W.toolSelectionStrategy=Q.data.tool_selection_strategy;if(Q.data.tool_selection_mode!==void 0)W.toolSelectionMode=Q.data.tool_selection_mode;if(Q.data.icon!==void 0)W.icon=Q.data.icon;if(Q.data.status!==void 0)W.status=Q.data.status;if(Q.data.is_default!==void 0)W.isDefault=Q.data.is_default;if(Q.data.connections!==void 0)W.connections=Q.data.connections.map(($)=>({connectionId:$.connection_id,selectedTools:$.selected_tools??null,selectedResources:$.selected_resources??null,selectedPrompts:$.selected_prompts??null}));let Z=await X.storage.gateways.update(Q.id,J,W);return{item:{id:Z.id,title:Z.title,description:Z.description,icon:Z.icon,organization_id:Z.organizationId,tool_selection_strategy:Z.toolSelectionStrategy,tool_selection_mode:Z.toolSelectionMode,status:Z.status,is_default:Z.isDefault,connections:Z.connections.map(($)=>({connection_id:$.connectionId,selected_tools:$.selectedTools,selected_resources:$.selectedResources,selected_prompts:$.selectedPrompts})),created_at:Z.createdAt,updated_at:Z.updatedAt,created_by:Z.createdBy,updated_by:Z.updatedBy??void 0}}}})});var YR6,JR6,D40;var d91=o(()=>{W1();P6();AU();YR6=N.object({id:N.string().describe("ID of the gateway to delete")}),JR6=N.object({item:eG.describe("The deleted gateway entity")}),D40=N1({name:"COLLECTION_GATEWAY_DELETE",description:"Delete an MCP gateway",inputSchema:YR6,outputSchema:JR6,handler:async(Q,X)=>{S1(X);let Y=O6(X);await X.access.check();let J=await X.storage.gateways.findById(Q.id);if(!J)throw Error(`Gateway not found: ${Q.id}`);if(J.organizationId!==Y.id)throw Error(`Gateway not found: ${Q.id}`);if(J.isDefault)throw Error("Cannot delete the default gateway. Set another gateway as default first.");return await X.storage.gateways.delete(Q.id),{item:{id:J.id,title:J.title,description:J.description,icon:J.icon,organization_id:J.organizationId,tool_selection_strategy:J.toolSelectionStrategy,tool_selection_mode:J.toolSelectionMode,status:J.status,is_default:J.isDefault,connections:J.connections.map((G)=>({connection_id:G.connectionId,selected_tools:G.selectedTools,selected_resources:G.selectedResources,selected_prompts:G.selectedPrompts})),created_at:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt,updated_at:J.updatedAt instanceof Date?J.updatedAt.toISOString():J.updatedAt,created_by:J.createdBy,updated_by:J.updatedBy??void 0}}}})});var p91=o(()=>{g91();u91();m91();l91();d91()});var WR6,N40;var c91=o(()=>{P6();W1();WR6=N.object({id:N.string().optional().describe("Unique log identifier"),organizationId:N.string().describe("Organization ID"),connectionId:N.string().describe("Connection ID"),connectionTitle:N.string().describe("Connection display name"),toolName:N.string().describe("Name of the tool that was called"),input:N.record(N.string(),N.unknown()).describe("Redacted tool input"),output:N.record(N.string(),N.unknown()).describe("Redacted tool output"),isError:N.boolean().describe("Whether the call resulted in an error"),errorMessage:N.string().nullish().describe("Error message if applicable"),durationMs:N.number().describe("Call duration in milliseconds"),timestamp:N.string().describe("ISO 8601 timestamp of the call"),userId:N.string().nullish().describe("User who triggered the call"),requestId:N.string().describe("Unique request identifier"),userAgent:N.string().nullish().describe("Client identifier (x-mesh-client header)"),gatewayId:N.string().nullish().describe("Gateway ID if routed through a gateway"),properties:N.record(N.string(),N.string()).nullish().describe("Custom key-value metadata attached to the log")}),N40=N1({name:"MONITORING_LOGS_LIST",description:"List monitoring logs for tool calls in the organization",inputSchema:N.object({connectionId:N.string().optional().describe("Filter by connection ID"),gatewayId:N.string().optional().describe("Filter by gateway ID"),toolName:N.string().optional().describe("Filter by tool name"),isError:N.boolean().optional().describe("Filter by error status"),startDate:N.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:N.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)"),limit:N.number().default(100).describe("Maximum number of results"),offset:N.number().default(0).describe("Offset for pagination"),properties:N.record(N.string(),N.string()).optional().describe("Filter by exact property key=value matches"),propertyKeys:N.array(N.string()).optional().describe("Filter by logs that have these property keys"),propertyPatterns:N.record(N.string(),N.string()).optional().describe("Filter by property value patterns (SQL LIKE, use % as wildcard)")}),outputSchema:N.object({logs:N.array(WR6).describe("Array of monitoring logs"),total:N.number().describe("Total number of logs matching filters"),offset:N.number().describe("Current offset for pagination"),limit:N.number().describe("Current limit for pagination")}),handler:async(Q,X)=>{let Y=O6(X),G=Q.properties||Q.propertyKeys||Q.propertyPatterns?{properties:Q.properties,propertyKeys:Q.propertyKeys,propertyPatterns:Q.propertyPatterns}:void 0,W={organizationId:Y.id,connectionId:Q.connectionId,gatewayId:Q.gatewayId,toolName:Q.toolName,isError:Q.isError,startDate:Q.startDate?new Date(Q.startDate):void 0,endDate:Q.endDate?new Date(Q.endDate):void 0,limit:Q.limit,offset:Q.offset,propertyFilters:G},Z=await X.storage.monitoring.query(W);return{logs:Z.logs.map(($)=>({...$,timestamp:$.timestamp instanceof Date?$.timestamp.toISOString():$.timestamp})),total:Z.total,offset:Q.offset,limit:Q.limit}}})});var O40;var n91=o(()=>{P6();W1();O40=N1({name:"MONITORING_STATS",description:"Get aggregated statistics for tool call monitoring",inputSchema:N.object({startDate:N.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:N.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)")}),outputSchema:N.object({totalCalls:N.number().describe("Total number of tool calls"),errorRate:N.number().describe("Error rate as a decimal (0 to 1)"),avgDurationMs:N.number().describe("Average call duration in milliseconds"),errorRatePercent:N.string().describe("Error rate as a percentage string")}),handler:async(Q,X)=>{let J={organizationId:O6(X).id,startDate:Q.startDate?new Date(Q.startDate):void 0,endDate:Q.endDate?new Date(Q.endDate):void 0},G=await X.storage.monitoring.getStats(J);return{...G,errorRatePercent:(G.errorRate*100).toFixed(2)}}})});var i91=o(()=>{c91();n91()});var L40;var a91=o(()=>{W1();P6();L40=N1({name:"ORGANIZATION_CREATE",description:"Create a new organization",inputSchema:N.object({slug:N.string().min(1).max(50).regex(/^[a-z0-9-]+$/,"Slug must be lowercase alphanumeric with hyphens"),name:N.string().min(1).max(255),description:N.string().optional()}),outputSchema:N.object({id:N.string(),name:N.string(),slug:N.string(),logo:N.string().nullable().optional(),metadata:N.any().optional(),createdAt:N.union([N.date(),N.string()]),members:N.array(N.any()).optional()}),handler:async(Q,X)=>{S1(X),await X.access.check();let Y=b9(X);if(!Y)throw Error("User ID required to create organization");let J=await X.boundAuth.organization.create({name:Q.name,slug:Q.slug,metadata:Q.description?{description:Q.description}:void 0,userId:Y});if(!J)throw Error("Failed to create organization");return J}})});var w40;var r91=o(()=>{W1();P6();w40=N1({name:"ORGANIZATION_LIST",description:"List all organizations user has access to",inputSchema:N.object({userId:N.string().optional()}),outputSchema:N.object({organizations:N.array(N.object({id:N.string(),name:N.string(),slug:N.string(),logo:N.string().nullable().optional(),metadata:N.any().optional(),createdAt:N.union([N.date(),N.string()])}))}),handler:async(Q,X)=>{S1(X),await X.access.check();let Y=b9(X),J=Q.userId||Y;if(!J)throw Error("User ID required to list organizations");return{organizations:await X.boundAuth.organization.list(J)}}})});var M40;var o91=o(()=>{W1();P6();M40=N1({name:"ORGANIZATION_GET",description:"Get organization details by slug or ID",inputSchema:N.object({}),outputSchema:N.object({id:N.string(),name:N.string(),slug:N.string(),logo:N.string().nullable().optional(),metadata:N.any().optional(),createdAt:N.union([N.date(),N.string()]),members:N.array(N.any()).optional(),invitations:N.array(N.any()).optional()}),handler:async(Q,X)=>{S1(X),await X.access.check();let Y=await X.boundAuth.organization.get();if(!Y)throw Error("No active organization found");return Y}})});var P40;var s91=o(()=>{W1();P6();P40=N1({name:"ORGANIZATION_UPDATE",description:"Update an existing organization",inputSchema:N.object({id:N.string(),slug:N.string().min(1).max(50).regex(/^[a-z0-9-]+$/).optional(),name:N.string().min(1).max(255).optional(),description:N.string().optional()}),outputSchema:N.object({id:N.string(),name:N.string(),slug:N.string(),logo:N.string().nullable().optional(),metadata:N.any().optional(),createdAt:N.union([N.date(),N.string()])}),handler:async(Q,X)=>{S1(X),await X.access.check();let Y={};if(Q.name)Y.name=Q.name;if(Q.slug)Y.slug=Q.slug;if(Q.description)Y.metadata={description:Q.description};let J=await X.boundAuth.organization.update({organizationId:Q.id,data:Y});if(!J)throw Error("Failed to update organization");return J}})});var T40;var t91=o(()=>{W1();P6();T40=N1({name:"ORGANIZATION_DELETE",description:"Delete an organization",inputSchema:N.object({id:N.string()}),outputSchema:N.object({success:N.boolean(),id:N.string()}),handler:async(Q,X)=>{return S1(X),await X.access.check(),await X.boundAuth.organization.delete(Q.id),{success:!0,id:Q.id}}})});var eM;var A40=o(()=>{W1();eM=N.object({title:N.string(),url:N.string(),icon:N.string()})});var E40;var e91=o(()=>{W1();P6();A40();E40=N1({name:"ORGANIZATION_SETTINGS_GET",description:"Get organization-level settings",inputSchema:N.object({}),outputSchema:N.object({organizationId:N.string(),sidebar_items:N.array(eM).nullable().optional(),createdAt:N.union([N.date(),N.string()]).optional(),updatedAt:N.union([N.date(),N.string()]).optional()}),handler:async(Q,X)=>{S1(X),await X.access.check();let Y=X.organization?.id;if(!Y)throw Error("Organization ID required (no active organization in context)");let J=await X.storage.organizationSettings.get(Y);if(!J)return{organizationId:Y};return J}})});var j40;var QX1=o(()=>{W1();P6();A40();j40=N1({name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization-level settings",inputSchema:N.object({organizationId:N.string(),sidebar_items:N.array(eM).optional()}),outputSchema:N.object({organizationId:N.string(),sidebar_items:N.array(eM).nullable().optional(),createdAt:N.union([N.date(),N.string()]),updatedAt:N.union([N.date(),N.string()])}),handler:async(Q,X)=>{if(S1(X),await X.access.check(),X.organization&&X.organization.id!==Q.organizationId)throw Error("Cannot update settings for a different organization");return await X.storage.organizationSettings.upsert(Q.organizationId,{sidebar_items:Q.sidebar_items})}})});var C40;var XX1=o(()=>{W1();P6();C40=N1({name:"ORGANIZATION_MEMBER_ADD",description:"Add a member to an organization",inputSchema:N.object({organizationId:N.string().optional(),userId:N.string(),role:N.array(N.string())}),outputSchema:N.object({id:N.string(),organizationId:N.string(),userId:N.string(),role:N.union([N.string(),N.array(N.string())]),createdAt:N.union([N.date(),N.string()])}),handler:async(Q,X)=>{S1(X),await X.access.check();let Y=Q.organizationId||X.organization?.id;if(!Y)throw Error("Organization ID required (no active organization in context)");let J=await X.boundAuth.organization.addMember({organizationId:Y,userId:Q.userId,role:Q.role});if(!J)throw Error("Failed to add member");return J}})});var I40;var YX1=o(()=>{W1();P6();I40=N1({name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove a member from an organization",inputSchema:N.object({organizationId:N.string().optional(),memberIdOrEmail:N.string()}),outputSchema:N.object({success:N.boolean(),memberIdOrEmail:N.string()}),handler:async(Q,X)=>{S1(X),await X.access.check();let Y=Q.organizationId||X.organization?.id;if(!Y)throw Error("Organization ID required (no active organization in context)");return await X.boundAuth.organization.removeMember({organizationId:Y,memberIdOrEmail:Q.memberIdOrEmail}),{success:!0,memberIdOrEmail:Q.memberIdOrEmail}}})});var R40;var JX1=o(()=>{W1();P6();R40=N1({name:"ORGANIZATION_MEMBER_LIST",description:"List all members in an organization",inputSchema:N.object({limit:N.number().optional(),offset:N.number().optional()}),outputSchema:N.object({members:N.array(N.object({id:N.string(),organizationId:N.string(),userId:N.string(),role:N.string(),createdAt:N.union([N.date(),N.string()]),user:N.object({id:N.string(),name:N.string(),email:N.string(),image:N.string().optional()}).optional()}))}),handler:async(Q,X)=>{S1(X),await X.access.check();let Y=X.organization?.id;if(!Y)throw Error("Organization ID required (no active organization in context)");let J=await X.boundAuth.organization.listMembers({organizationId:Y,limit:Q.limit,offset:Q.offset});return{members:Array.isArray(J)?J:[]}}})});var S40;var GX1=o(()=>{W1();P6();S40=N1({name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Update a member's role in an organization",inputSchema:N.object({organizationId:N.string().optional(),memberId:N.string(),role:N.array(N.string())}),outputSchema:N.object({id:N.string(),organizationId:N.string(),userId:N.string(),role:N.union([N.literal("admin"),N.literal("member"),N.literal("owner")]),createdAt:N.union([N.date(),N.string()]),user:N.object({email:N.string(),name:N.string(),image:N.string().optional()})}),handler:async(Q,X)=>{S1(X),await X.access.check();let Y=Q.organizationId||X.organization?.id;if(!Y)throw Error("Organization ID required (no active organization in context)");let J=await X.boundAuth.organization.updateMemberRole({organizationId:Y,memberId:Q.memberId,role:Q.role});if(!J)throw Error("Failed to update member role");return J}})});var WX1=o(()=>{a91();r91();o91();s91();t91();e91();QX1();XX1();YX1();JX1();GX1()});var KR6,HR6,k40;var ZX1=o(()=>{W1();P6();KR6=N.object({id:N.string().min(1)}),HR6=N.object({user:N.object({id:N.string(),name:N.string(),email:N.string(),image:N.string().nullable()}).nullable()}),k40=N1({name:"USER_GET",description:"Get a user by id (restricted to shared organizations)",inputSchema:KR6,outputSchema:HR6,handler:async(Q,X)=>{await X.access.check(),S1(X);let Y=b9(X);if(!Y)throw Error("Authentication required");let J=await X.storage.users.findById(Q.id,Y);if(!J)return{user:null};return{user:{id:J.id,name:J.name,email:J.email,image:J.image??null}}}})});var $X1=o(()=>{ZX1()});var HX1={};K8(HX1,{managementMCP:()=>v40,ALL_TOOLS:()=>KX1});var KX1,v40=(Q)=>{let X=KX1.map((J)=>({name:J.name,description:J.description,inputSchema:J.inputSchema,outputSchema:J.outputSchema,handler:async(G)=>{return Q.access.setToolName(J.name),await J.execute(G,Q)}}));return DQ1({name:"mcp-mesh-management",version:"1.0.0"}).withTools(X).build()};var _40=o(()=>{NQ1();kQ1();P91();j91();f91();p91();i91();WX1();$X1();KX1=[L40,w40,M40,P40,T40,E40,j40,C40,I40,R40,S40,C60,r60,o60,e60,Q40,X40,V40,z40,U40,B40,D40,E91,N40,O40,T60,E60,j60,A60,Y40,J40,G40,W40,Z40,$40,K40,k40]});var a3,i40,Py,r3,$P;var Ty=o(()=>{a3={JS_EVAL_TYPE_GLOBAL:0,JS_EVAL_TYPE_MODULE:1,JS_EVAL_TYPE_DIRECT:2,JS_EVAL_TYPE_INDIRECT:3,JS_EVAL_TYPE_MASK:3,JS_EVAL_FLAG_STRICT:8,JS_EVAL_FLAG_STRIP:16,JS_EVAL_FLAG_COMPILE_ONLY:32,JS_EVAL_FLAG_BACKTRACE_BARRIER:64},i40={BaseObjects:1,Date:2,Eval:4,StringNormalize:8,RegExp:16,RegExpCompiler:32,JSON:64,Proxy:128,MapSet:256,TypedArrays:512,Promise:1024,BigInt:2048,BigFloat:4096,BigDecimal:8192,OperatorOverloading:16384,BignumExt:32768},Py={Pending:0,Fulfilled:1,Rejected:2},r3={JS_GPN_STRING_MASK:1,JS_GPN_SYMBOL_MASK:2,JS_GPN_PRIVATE_MASK:4,JS_GPN_ENUM_ONLY:16,JS_GPN_SET_ENUM:32,QTS_GPN_NUMBER_MASK:64,QTS_STANDARD_COMPLIANT_NUMBER:128},$P={IsStrictlyEqual:0,IsSameValue:1,IsSameValueZero:2}});function CU(...Q){e40&&console.log("quickjs-emscripten:",...Q)}function*DY1(Q){return yield Q}function eR6(Q){return DY1(X80(Q))}function GY1(Q,X){return(...Y)=>{let J=X.call(Q,Q80,...Y);return X80(J)}}function QS6(Q,X){let Y=X.call(Q,Q80);return X80(Y)}function X80(Q){function X(Y){return Y.done?Y.value:Y.value instanceof Promise?Y.value.then((J)=>X(Q.next(J)),(J)=>X(Q.throw(J))):X(Q.next(Y.value))}return X(Q.next())}function a40(Q,X){let Y;try{Q.dispose()}catch(J){Y=J}if(X&&Y)throw Object.assign(X,{message:`${X.message}
255
+ `.execute(Q)).rows[0]?.exists)await t6`CREATE ROLE ${t6.id(Y)} NOLOGIN`.execute(Q);await t6`GRANT ${t6.id(Y)} TO CURRENT_USER`.execute(Q),await t6`GRANT USAGE, CREATE ON SCHEMA ${t6.id(X)} TO ${t6.id(Y)}`.execute(Q),await t6`GRANT ALL ON ALL TABLES IN SCHEMA ${t6.id(X)} TO ${t6.id(Y)}`.execute(Q),await t6`GRANT ALL ON ALL SEQUENCES IN SCHEMA ${t6.id(X)} TO ${t6.id(Y)}`.execute(Q),await t6`ALTER DEFAULT PRIVILEGES IN SCHEMA ${t6.id(X)} GRANT ALL ON TABLES TO ${t6.id(Y)}`.execute(Q),await t6`ALTER DEFAULT PRIVILEGES IN SCHEMA ${t6.id(X)} GRANT ALL ON SEQUENCES TO ${t6.id(Y)}`.execute(Q),await t6`REVOKE ALL ON SCHEMA public FROM ${t6.id(Y)}`.execute(Q)}async function uI6(Q,X,Y,J){try{return await Q.transaction().execute(async(G)=>{return await t6`SET LOCAL ROLE ${t6.id(Y)}`.execute(G),await t6`SET LOCAL search_path TO ${t6.id(X)}`.execute(G),await t6.raw(J).execute(G)})}catch(G){if(xI6(G))return await gI6(Q,X,Y),await Q.transaction().execute(async(W)=>{return await t6`SET LOCAL ROLE ${t6.id(Y)}`.execute(W),await t6`SET LOCAL search_path TO ${t6.id(X)}`.execute(W),await t6.raw(J).execute(W)});throw G}}var _I6,bI6,E91;var j91=o(()=>{W1();P6();_I6=N.object({results:N.array(N.unknown()).optional(),success:N.boolean().optional()});bI6=N.object({sql:N.string().describe("The SQL query to run"),params:N.array(N.any()).describe("The parameters to pass to the SQL query").optional()});E91=N1({name:"DATABASES_RUN_SQL",description:"Run a SQL query against the database",inputSchema:bI6,outputSchema:N.object({result:N.array(_I6)}),handler:async(Q,X)=>{S1(X),await X.access.check();let Y=yI6(Q.sql,Q.params||[]);if(!X.connectionId)throw Error("Connection context required for database access");let J=fI6(X.connectionId),G=hI6(X.connectionId);return{result:[{results:(await uI6(X.db,J,G,Y)).rows,success:!0}]}}})});var C91,lI6,I91;var k7=o(()=>{W1();Hy();C91=N.object({connectionId:N.string().optional().describe("Filter subscriptions by connection ID (optional)")}),lI6=N.object({id:N.string().describe("Subscription ID"),connectionId:N.string().describe("Subscriber connection ID"),eventType:N.string().describe("Event type pattern"),publisher:N.string().nullable().describe("Publisher connection filter (null = all publishers)"),filter:N.string().nullable().describe("JSONPath filter expression"),enabled:N.boolean().describe("Whether subscription is enabled"),createdAt:N.union([N.string(),N.date()]).describe("Created timestamp"),updatedAt:N.union([N.string(),N.date()]).describe("Updated timestamp")}),I91=N.object({subscriptions:N.array(lI6).describe("List of subscriptions")})});var Y40;var R91=o(()=>{P6();k7();Y40=N1({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:uM,outputSchema:mM,handler:async(Q,X)=>{S1(X);let Y=O6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to publish events. Use a connection-scoped token.");let G=await X.eventBus.publish(Y.id,J,{type:Q.type,subject:Q.subject,data:Q.data,deliverAt:Q.deliverAt,cron:Q.cron});return{id:G.id,type:G.type,source:G.source,time:G.time}}})});var J40;var S91=o(()=>{P6();k7();J40=N1({name:"EVENT_SUBSCRIBE",description:"Subscribe to events of a specific type. The subscriber is automatically set to the caller's connection.",inputSchema:lM,outputSchema:dM,handler:async(Q,X)=>{S1(X);let Y=O6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to subscribe. Use a connection-scoped token.");let G=await X.eventBus.subscribe(Y.id,{connectionId:J,eventType:Q.eventType,publisher:Q.publisher,filter:Q.filter});return{subscription:{id:G.id,connectionId:G.connectionId,eventType:G.eventType,publisher:G.publisher,filter:G.filter,enabled:G.enabled,createdAt:G.createdAt,updatedAt:G.updatedAt}}}})});var G40;var k91=o(()=>{P6();k7();G40=N1({name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events by removing a subscription.",inputSchema:nM,outputSchema:iM,handler:async(Q,X)=>{S1(X);let Y=O6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to unsubscribe. Use a connection-scoped token.");let G=await X.eventBus.getSubscription(Y.id,Q.subscriptionId);if(!G)throw Error(`Subscription not found: ${Q.subscriptionId}`);if(G.connectionId!==J)throw Error("Cannot unsubscribe from a subscription owned by another connection");return{success:(await X.eventBus.unsubscribe(Y.id,Q.subscriptionId)).success,subscriptionId:Q.subscriptionId}}})});var W40;var v91=o(()=>{P6();k7();W40=N1({name:"EVENT_CANCEL",description:"Cancel a recurring event to stop future deliveries. Only the publisher can cancel their own events.",inputSchema:aM,outputSchema:rM,handler:async(Q,X)=>{S1(X);let Y=O6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to cancel events. Use a connection-scoped token.");if(!await X.eventBus.getEvent(Y.id,Q.eventId))throw Error(`Event not found: ${Q.eventId}`);if(!(await X.eventBus.cancelEvent(Y.id,Q.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:Q.eventId}}})});var Z40;var _91=o(()=>{P6();k7();Z40=N1({name:"EVENT_ACK",description:"Acknowledge delivery of an event. Call after successfully processing an event received via ON_EVENTS with retryAfter.",inputSchema:oM,outputSchema:sM,handler:async(Q,X)=>{S1(X);let Y=O6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to acknowledge events. Use a connection-scoped token.");if(!(await X.eventBus.ackEvent(Y.id,Q.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:Q.eventId}}})});var $40;var y91=o(()=>{P6();k7();$40=N1({name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions, optionally filtered by connection ID.",inputSchema:C91,outputSchema:I91,handler:async(Q,X)=>{S1(X);let Y=O6(X);return await X.access.check(),{subscriptions:(await X.eventBus.listSubscriptions(Y.id,Q.connectionId)).map((G)=>({id:G.id,connectionId:G.connectionId,eventType:G.eventType,publisher:G.publisher,filter:G.filter,enabled:G.enabled,createdAt:G.createdAt,updatedAt:G.updatedAt}))}}})});var K40;var b91=o(()=>{P6();k7();K40=N1({name:"EVENT_SYNC_SUBSCRIPTIONS",description:"Sync subscriptions to desired state. Creates new, deletes removed, updates changed filters. Subscriptions are identified by (eventType, publisher).",inputSchema:pM,outputSchema:cM,handler:async(Q,X)=>{S1(X);let Y=O6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to sync subscriptions. Use a connection-scoped token.");let G=await X.eventBus.syncSubscriptions(Y.id,{connectionId:J,subscriptions:Q.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,updatedAt:W.updatedAt}))}}})});var f91=o(()=>{R91();S91();k91();v91();_91();y91();b91();k7()});var H40,F40,pI6,eG,h91,x91;var AU=o(()=>{W1();H40=N.enum(["inclusion","exclusion"]).describe("Tool selection mode: 'inclusion' = include selected (default), 'exclusion' = exclude selected"),F40=N.enum(["passthrough","smart_tool_selection","code_execution"]).describe("Gateway tool selection strategy: 'passthrough' (default), 'smart_tool_selection', or 'code_execution'"),pI6=N.object({connection_id:N.string().describe("Connection ID"),selected_tools:N.array(N.string()).nullable().describe("Selected tool names. With 'inclusion' mode: null = all tools included. With 'exclusion' mode: null = entire connection excluded"),selected_resources:N.array(N.string()).nullable().describe("Selected resource URIs or patterns. Supports * and ** wildcards for pattern matching. With 'inclusion' mode: null = all resources included."),selected_prompts:N.array(N.string()).nullable().describe("Selected prompt names. With 'inclusion' mode: null = all prompts included. With 'exclusion' mode: null = entire connection excluded.")}),eG=N.object({id:N.string().describe("Unique identifier for the gateway"),title:N.string().describe("Human-readable name for the gateway"),description:N.string().nullable().describe("Description of the gateway"),icon:N.string().nullable().optional().describe("Icon URL for the gateway"),created_at:N.string().describe("When the gateway was created"),updated_at:N.string().describe("When the gateway was last updated"),created_by:N.string().describe("User ID who created the gateway"),updated_by:N.string().optional().describe("User ID who last updated the gateway"),organization_id:N.string().describe("Organization ID this gateway belongs to"),tool_selection_strategy:F40.describe("Gateway behavior strategy (metadata for now): 'passthrough', 'smart_tool_selection', or 'code_execution'"),tool_selection_mode:H40.describe("Tool selection mode: 'inclusion' = include selected, 'exclusion' = exclude selected"),status:N.enum(["active","inactive"]).describe("Current status"),is_default:N.boolean().describe("Whether this is the default Hub for the organization"),connections:N.array(pI6).describe("Connections with their selected tools (behavior depends on tool_selection_mode)")}),h91=N.object({title:N.string().min(1).max(255).describe("Name for the gateway"),description:N.string().nullable().optional().describe("Optional description"),tool_selection_strategy:F40.optional().default("passthrough").describe("Gateway behavior strategy (defaults to 'passthrough')"),tool_selection_mode:H40.optional().default("inclusion").describe("Tool selection mode (defaults to 'inclusion')"),icon:N.string().nullable().optional().describe("Optional icon URL"),status:N.enum(["active","inactive"]).optional().default("active").describe("Initial status"),is_default:N.boolean().optional().default(!1).describe("Whether this is the default Hub for the organization"),connections:N.array(N.object({connection_id:N.string().describe("Connection ID"),selected_tools:N.array(N.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools or full exclusion)"),selected_resources:N.array(N.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources)"),selected_prompts:N.array(N.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)")}),x91=N.object({title:N.string().min(1).max(255).optional().describe("New name"),description:N.string().nullable().optional().describe("New description (null to clear)"),tool_selection_strategy:F40.optional().describe("New gateway behavior strategy"),tool_selection_mode:H40.optional().describe("New tool selection mode"),icon:N.string().nullable().optional().describe("New icon URL (null to clear)"),status:N.enum(["active","inactive"]).optional().describe("New status"),is_default:N.boolean().optional().describe("Set as default Hub for the organization"),connections:N.array(N.object({connection_id:N.string().describe("Connection ID"),selected_tools:N.array(N.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools or full exclusion)"),selected_resources:N.array(N.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources)"),selected_prompts:N.array(N.string()).nullable().optional().describe("Selected prompt names (null/undefined = all prompts or full exclusion)")})).optional().describe("New connections (replaces existing)")})});var cI6,nI6,V40;var g91=o(()=>{W1();P6();AU();cI6=N.object({data:h91.describe("Data for the new gateway")}),nI6=N.object({item:eG.describe("The created gateway entity")}),V40=N1({name:"COLLECTION_GATEWAY_CREATE",description:"Create a new MCP gateway in the organization",inputSchema:cI6,outputSchema:nI6,handler:async(Q,X)=>{S1(X);let Y=O6(X);await X.access.check();let J=b9(X);if(!J)throw Error("User ID required to create gateway");let G={title:Q.data.title,description:Q.data.description??null,toolSelectionStrategy:Q.data.tool_selection_strategy??"passthrough",toolSelectionMode:Q.data.tool_selection_mode??"inclusion",icon:Q.data.icon??null,status:Q.data.status,isDefault:Q.data.is_default??!1,connections:Q.data.connections.map((Z)=>({connectionId:Z.connection_id,selectedTools:Z.selected_tools??null,selectedResources:Z.selected_resources??null,selectedPrompts:Z.selected_prompts??null}))},W=await X.storage.gateways.create(Y.id,J,G);return{item:{id:W.id,title:W.title,description:W.description,icon:W.icon,organization_id:W.organizationId,tool_selection_strategy:W.toolSelectionStrategy,tool_selection_mode:W.toolSelectionMode,status:W.status,is_default:W.isDefault,connections:W.connections.map((Z)=>({connection_id:Z.connectionId,selected_tools:Z.selectedTools,selected_resources:Z.selectedResources,selected_prompts:Z.selectedPrompts})),created_at:W.createdAt,updated_at:W.updatedAt,created_by:W.createdBy,updated_by:W.updatedBy??void 0}}}})});function iI6(Q){let X=[],Y=0;while(Y<Q.length){let J=Q[Y];if(J==="%")X.push(".*");else if(J==="_")X.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))X.push("\\"+J);else X.push(J);Y++}return X.join("")}function c$(Q){return typeof Q==="string"||typeof Q==="number"}function q40(Q,X){let Y=X.split("."),J=Q;for(let G of Y){if(J==null||typeof J!=="object")return;J=J[G]}return J}function aI6(Q,X){return Q.connections.some((Y)=>Y.connection_id===X)}function qy(Q,X){if("conditions"in X){let{operator:$,conditions:K}=X;switch($){case"and":return K.every((H)=>qy(Q,H));case"or":return K.some((H)=>qy(Q,H));case"not":return!K.every((H)=>qy(Q,H));default:return!0}}let{field:Y,operator:J,value:G}=X,W=Y.join(".");if(W==="connection_id"){if(J!=="eq"||typeof G!=="string")return!1;return aI6(Q,G)}let Z=q40(Q,W);switch(J){case"eq":return Z===G;case"gt":return c$(Z)&&c$(G)&&Z>G;case"gte":return c$(Z)&&c$(G)&&Z>=G;case"lt":return c$(Z)&&c$(G)&&Z<G;case"lte":return c$(Z)&&c$(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 $=iI6(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 rI6(Q,X){return[...Q].sort((Y,J)=>{for(let G of X){let W=G.field.join("."),Z=q40(Y,W),$=q40(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 oI6,sI6,z40;var u91=o(()=>{d$();P6();AU();oI6=xM,sI6=gM(eG),z40=N1({name:"COLLECTION_GATEWAY_LIST",description:"List all MCP gateways in the organization",inputSchema:oI6,outputSchema:sI6,handler:async(Q,X)=>{await X.access.check();let Y=O6(X),J=Q.where&&!("conditions"in Q.where)&&Q.where.field.join(".")==="connection_id"&&Q.where.operator==="eq"&&typeof Q.where.value==="string"?Q.where.value:void 0,W=(J?await X.storage.gateways.listByConnectionId(Y.id,J):await X.storage.gateways.list(Y.id)).map((V)=>({id:V.id,title:V.title,description:V.description,icon:V.icon,is_default:V.isDefault,organization_id:V.organizationId,tool_selection_strategy:V.toolSelectionStrategy,tool_selection_mode:V.toolSelectionMode,status:V.status,connections:V.connections.map((q)=>({connection_id:q.connectionId,selected_tools:q.selectedTools,selected_resources:q.selectedResources,selected_prompts:q.selectedPrompts})),created_at:V.createdAt,updated_at:V.updatedAt,created_by:V.createdBy,updated_by:V.updatedBy??void 0}));if(Q.where)W=W.filter((V)=>qy(V,Q.where));if(Q.orderBy&&Q.orderBy.length>0)W=rI6(W,Q.orderBy);let Z=W.length,$=Q.offset??0,K=Q.limit??100,H=W.slice($,$+K),F=$+K<Z;return{items:H,totalCount:Z,hasMore:F}}})});var tI6,eI6,U40;var m91=o(()=>{W1();P6();AU();tI6=N.object({id:N.string().describe("ID of the gateway to retrieve")}),eI6=N.object({item:eG.nullable().describe("The retrieved gateway, or null if not found")}),U40=N1({name:"COLLECTION_GATEWAY_GET",description:"Get an MCP gateway by ID",inputSchema:tI6,outputSchema:eI6,handler:async(Q,X)=>{S1(X);let Y=O6(X);await X.access.check();let J=await X.storage.gateways.findById(Q.id);if(J&&J.organizationId!==Y.id)return{item:null};if(!J)return{item:null};return{item:{id:J.id,title:J.title,description:J.description,icon:J.icon,organization_id:J.organizationId,tool_selection_strategy:J.toolSelectionStrategy,tool_selection_mode:J.toolSelectionMode,status:J.status,is_default:J.isDefault,connections:J.connections.map((G)=>({connection_id:G.connectionId,selected_tools:G.selectedTools,selected_resources:G.selectedResources,selected_prompts:G.selectedPrompts})),created_at:J.createdAt,updated_at:J.updatedAt,created_by:J.createdBy,updated_by:J.updatedBy??void 0}}}})});var QR6,XR6,B40;var l91=o(()=>{W1();P6();AU();QR6=N.object({id:N.string().describe("ID of the gateway to update"),data:x91.describe("Partial gateway data to update")}),XR6=N.object({item:eG.describe("The updated gateway entity")}),B40=N1({name:"COLLECTION_GATEWAY_UPDATE",description:"Update an MCP gateway",inputSchema:QR6,outputSchema:XR6,handler:async(Q,X)=>{S1(X);let Y=O6(X);await X.access.check();let J=b9(X);if(!J)throw Error("User ID required to update gateway");let G=await X.storage.gateways.findById(Q.id);if(!G)throw Error(`Gateway not found: ${Q.id}`);if(G.organizationId!==Y.id)throw Error(`Gateway not found: ${Q.id}`);let W={};if(Q.data.title!==void 0)W.title=Q.data.title;if(Q.data.description!==void 0)W.description=Q.data.description;if(Q.data.tool_selection_strategy!==void 0)W.toolSelectionStrategy=Q.data.tool_selection_strategy;if(Q.data.tool_selection_mode!==void 0)W.toolSelectionMode=Q.data.tool_selection_mode;if(Q.data.icon!==void 0)W.icon=Q.data.icon;if(Q.data.status!==void 0)W.status=Q.data.status;if(Q.data.is_default!==void 0)W.isDefault=Q.data.is_default;if(Q.data.connections!==void 0)W.connections=Q.data.connections.map(($)=>({connectionId:$.connection_id,selectedTools:$.selected_tools??null,selectedResources:$.selected_resources??null,selectedPrompts:$.selected_prompts??null}));let Z=await X.storage.gateways.update(Q.id,J,W);return{item:{id:Z.id,title:Z.title,description:Z.description,icon:Z.icon,organization_id:Z.organizationId,tool_selection_strategy:Z.toolSelectionStrategy,tool_selection_mode:Z.toolSelectionMode,status:Z.status,is_default:Z.isDefault,connections:Z.connections.map(($)=>({connection_id:$.connectionId,selected_tools:$.selectedTools,selected_resources:$.selectedResources,selected_prompts:$.selectedPrompts})),created_at:Z.createdAt,updated_at:Z.updatedAt,created_by:Z.createdBy,updated_by:Z.updatedBy??void 0}}}})});var YR6,JR6,D40;var d91=o(()=>{W1();P6();AU();YR6=N.object({id:N.string().describe("ID of the gateway to delete")}),JR6=N.object({item:eG.describe("The deleted gateway entity")}),D40=N1({name:"COLLECTION_GATEWAY_DELETE",description:"Delete an MCP gateway",inputSchema:YR6,outputSchema:JR6,handler:async(Q,X)=>{S1(X);let Y=O6(X);await X.access.check();let J=await X.storage.gateways.findById(Q.id);if(!J)throw Error(`Gateway not found: ${Q.id}`);if(J.organizationId!==Y.id)throw Error(`Gateway not found: ${Q.id}`);if(J.isDefault)throw Error("Cannot delete the default Hub. Set another Hub as default first.");return await X.storage.gateways.delete(Q.id),{item:{id:J.id,title:J.title,description:J.description,icon:J.icon,organization_id:J.organizationId,tool_selection_strategy:J.toolSelectionStrategy,tool_selection_mode:J.toolSelectionMode,status:J.status,is_default:J.isDefault,connections:J.connections.map((G)=>({connection_id:G.connectionId,selected_tools:G.selectedTools,selected_resources:G.selectedResources,selected_prompts:G.selectedPrompts})),created_at:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt,updated_at:J.updatedAt instanceof Date?J.updatedAt.toISOString():J.updatedAt,created_by:J.createdBy,updated_by:J.updatedBy??void 0}}}})});var p91=o(()=>{g91();u91();m91();l91();d91()});var WR6,N40;var c91=o(()=>{P6();W1();WR6=N.object({id:N.string().optional().describe("Unique log identifier"),organizationId:N.string().describe("Organization ID"),connectionId:N.string().describe("Connection ID"),connectionTitle:N.string().describe("Connection display name"),toolName:N.string().describe("Name of the tool that was called"),input:N.record(N.string(),N.unknown()).describe("Redacted tool input"),output:N.record(N.string(),N.unknown()).describe("Redacted tool output"),isError:N.boolean().describe("Whether the call resulted in an error"),errorMessage:N.string().nullish().describe("Error message if applicable"),durationMs:N.number().describe("Call duration in milliseconds"),timestamp:N.string().describe("ISO 8601 timestamp of the call"),userId:N.string().nullish().describe("User who triggered the call"),requestId:N.string().describe("Unique request identifier"),userAgent:N.string().nullish().describe("Client identifier (x-mesh-client header)"),gatewayId:N.string().nullish().describe("Gateway ID if routed through a gateway"),properties:N.record(N.string(),N.string()).nullish().describe("Custom key-value metadata attached to the log")}),N40=N1({name:"MONITORING_LOGS_LIST",description:"List monitoring logs for tool calls in the organization",inputSchema:N.object({connectionId:N.string().optional().describe("Filter by connection ID"),gatewayId:N.string().optional().describe("Filter by gateway ID"),toolName:N.string().optional().describe("Filter by tool name"),isError:N.boolean().optional().describe("Filter by error status"),startDate:N.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:N.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)"),limit:N.number().default(100).describe("Maximum number of results"),offset:N.number().default(0).describe("Offset for pagination"),properties:N.record(N.string(),N.string()).optional().describe("Filter by exact property key=value matches"),propertyKeys:N.array(N.string()).optional().describe("Filter by logs that have these property keys"),propertyPatterns:N.record(N.string(),N.string()).optional().describe("Filter by property value patterns (SQL LIKE, use % as wildcard)")}),outputSchema:N.object({logs:N.array(WR6).describe("Array of monitoring logs"),total:N.number().describe("Total number of logs matching filters"),offset:N.number().describe("Current offset for pagination"),limit:N.number().describe("Current limit for pagination")}),handler:async(Q,X)=>{let Y=O6(X),G=Q.properties||Q.propertyKeys||Q.propertyPatterns?{properties:Q.properties,propertyKeys:Q.propertyKeys,propertyPatterns:Q.propertyPatterns}:void 0,W={organizationId:Y.id,connectionId:Q.connectionId,gatewayId:Q.gatewayId,toolName:Q.toolName,isError:Q.isError,startDate:Q.startDate?new Date(Q.startDate):void 0,endDate:Q.endDate?new Date(Q.endDate):void 0,limit:Q.limit,offset:Q.offset,propertyFilters:G},Z=await X.storage.monitoring.query(W);return{logs:Z.logs.map(($)=>({...$,timestamp:$.timestamp instanceof Date?$.timestamp.toISOString():$.timestamp})),total:Z.total,offset:Q.offset,limit:Q.limit}}})});var O40;var n91=o(()=>{P6();W1();O40=N1({name:"MONITORING_STATS",description:"Get aggregated statistics for tool call monitoring",inputSchema:N.object({startDate:N.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:N.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)")}),outputSchema:N.object({totalCalls:N.number().describe("Total number of tool calls"),errorRate:N.number().describe("Error rate as a decimal (0 to 1)"),avgDurationMs:N.number().describe("Average call duration in milliseconds"),errorRatePercent:N.string().describe("Error rate as a percentage string")}),handler:async(Q,X)=>{let J={organizationId:O6(X).id,startDate:Q.startDate?new Date(Q.startDate):void 0,endDate:Q.endDate?new Date(Q.endDate):void 0},G=await X.storage.monitoring.getStats(J);return{...G,errorRatePercent:(G.errorRate*100).toFixed(2)}}})});var i91=o(()=>{c91();n91()});var L40;var a91=o(()=>{W1();P6();L40=N1({name:"ORGANIZATION_CREATE",description:"Create a new organization",inputSchema:N.object({slug:N.string().min(1).max(50).regex(/^[a-z0-9-]+$/,"Slug must be lowercase alphanumeric with hyphens"),name:N.string().min(1).max(255),description:N.string().optional()}),outputSchema:N.object({id:N.string(),name:N.string(),slug:N.string(),logo:N.string().nullable().optional(),metadata:N.any().optional(),createdAt:N.union([N.date(),N.string()]),members:N.array(N.any()).optional()}),handler:async(Q,X)=>{S1(X),await X.access.check();let Y=b9(X);if(!Y)throw Error("User ID required to create organization");let J=await X.boundAuth.organization.create({name:Q.name,slug:Q.slug,metadata:Q.description?{description:Q.description}:void 0,userId:Y});if(!J)throw Error("Failed to create organization");return J}})});var w40;var r91=o(()=>{W1();P6();w40=N1({name:"ORGANIZATION_LIST",description:"List all organizations user has access to",inputSchema:N.object({userId:N.string().optional()}),outputSchema:N.object({organizations:N.array(N.object({id:N.string(),name:N.string(),slug:N.string(),logo:N.string().nullable().optional(),metadata:N.any().optional(),createdAt:N.union([N.date(),N.string()])}))}),handler:async(Q,X)=>{S1(X),await X.access.check();let Y=b9(X),J=Q.userId||Y;if(!J)throw Error("User ID required to list organizations");return{organizations:await X.boundAuth.organization.list(J)}}})});var M40;var o91=o(()=>{W1();P6();M40=N1({name:"ORGANIZATION_GET",description:"Get organization details by slug or ID",inputSchema:N.object({}),outputSchema:N.object({id:N.string(),name:N.string(),slug:N.string(),logo:N.string().nullable().optional(),metadata:N.any().optional(),createdAt:N.union([N.date(),N.string()]),members:N.array(N.any()).optional(),invitations:N.array(N.any()).optional()}),handler:async(Q,X)=>{S1(X),await X.access.check();let Y=await X.boundAuth.organization.get();if(!Y)throw Error("No active organization found");return Y}})});var P40;var s91=o(()=>{W1();P6();P40=N1({name:"ORGANIZATION_UPDATE",description:"Update an existing organization",inputSchema:N.object({id:N.string(),slug:N.string().min(1).max(50).regex(/^[a-z0-9-]+$/).optional(),name:N.string().min(1).max(255).optional(),description:N.string().optional()}),outputSchema:N.object({id:N.string(),name:N.string(),slug:N.string(),logo:N.string().nullable().optional(),metadata:N.any().optional(),createdAt:N.union([N.date(),N.string()])}),handler:async(Q,X)=>{S1(X),await X.access.check();let Y={};if(Q.name)Y.name=Q.name;if(Q.slug)Y.slug=Q.slug;if(Q.description)Y.metadata={description:Q.description};let J=await X.boundAuth.organization.update({organizationId:Q.id,data:Y});if(!J)throw Error("Failed to update organization");return J}})});var T40;var t91=o(()=>{W1();P6();T40=N1({name:"ORGANIZATION_DELETE",description:"Delete an organization",inputSchema:N.object({id:N.string()}),outputSchema:N.object({success:N.boolean(),id:N.string()}),handler:async(Q,X)=>{return S1(X),await X.access.check(),await X.boundAuth.organization.delete(Q.id),{success:!0,id:Q.id}}})});var eM;var A40=o(()=>{W1();eM=N.object({title:N.string(),url:N.string(),icon:N.string()})});var E40;var e91=o(()=>{W1();P6();A40();E40=N1({name:"ORGANIZATION_SETTINGS_GET",description:"Get organization-level settings",inputSchema:N.object({}),outputSchema:N.object({organizationId:N.string(),sidebar_items:N.array(eM).nullable().optional(),createdAt:N.union([N.date(),N.string()]).optional(),updatedAt:N.union([N.date(),N.string()]).optional()}),handler:async(Q,X)=>{S1(X),await X.access.check();let Y=X.organization?.id;if(!Y)throw Error("Organization ID required (no active organization in context)");let J=await X.storage.organizationSettings.get(Y);if(!J)return{organizationId:Y};return J}})});var j40;var QX1=o(()=>{W1();P6();A40();j40=N1({name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization-level settings",inputSchema:N.object({organizationId:N.string(),sidebar_items:N.array(eM).optional()}),outputSchema:N.object({organizationId:N.string(),sidebar_items:N.array(eM).nullable().optional(),createdAt:N.union([N.date(),N.string()]),updatedAt:N.union([N.date(),N.string()])}),handler:async(Q,X)=>{if(S1(X),await X.access.check(),X.organization&&X.organization.id!==Q.organizationId)throw Error("Cannot update settings for a different organization");return await X.storage.organizationSettings.upsert(Q.organizationId,{sidebar_items:Q.sidebar_items})}})});var C40;var XX1=o(()=>{W1();P6();C40=N1({name:"ORGANIZATION_MEMBER_ADD",description:"Add a member to an organization",inputSchema:N.object({organizationId:N.string().optional(),userId:N.string(),role:N.array(N.string())}),outputSchema:N.object({id:N.string(),organizationId:N.string(),userId:N.string(),role:N.union([N.string(),N.array(N.string())]),createdAt:N.union([N.date(),N.string()])}),handler:async(Q,X)=>{S1(X),await X.access.check();let Y=Q.organizationId||X.organization?.id;if(!Y)throw Error("Organization ID required (no active organization in context)");let J=await X.boundAuth.organization.addMember({organizationId:Y,userId:Q.userId,role:Q.role});if(!J)throw Error("Failed to add member");return J}})});var I40;var YX1=o(()=>{W1();P6();I40=N1({name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove a member from an organization",inputSchema:N.object({organizationId:N.string().optional(),memberIdOrEmail:N.string()}),outputSchema:N.object({success:N.boolean(),memberIdOrEmail:N.string()}),handler:async(Q,X)=>{S1(X),await X.access.check();let Y=Q.organizationId||X.organization?.id;if(!Y)throw Error("Organization ID required (no active organization in context)");return await X.boundAuth.organization.removeMember({organizationId:Y,memberIdOrEmail:Q.memberIdOrEmail}),{success:!0,memberIdOrEmail:Q.memberIdOrEmail}}})});var R40;var JX1=o(()=>{W1();P6();R40=N1({name:"ORGANIZATION_MEMBER_LIST",description:"List all members in an organization",inputSchema:N.object({limit:N.number().optional(),offset:N.number().optional()}),outputSchema:N.object({members:N.array(N.object({id:N.string(),organizationId:N.string(),userId:N.string(),role:N.string(),createdAt:N.union([N.date(),N.string()]),user:N.object({id:N.string(),name:N.string(),email:N.string(),image:N.string().optional()}).optional()}))}),handler:async(Q,X)=>{S1(X),await X.access.check();let Y=X.organization?.id;if(!Y)throw Error("Organization ID required (no active organization in context)");let J=await X.boundAuth.organization.listMembers({organizationId:Y,limit:Q.limit,offset:Q.offset});return{members:Array.isArray(J)?J:[]}}})});var S40;var GX1=o(()=>{W1();P6();S40=N1({name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Update a member's role in an organization",inputSchema:N.object({organizationId:N.string().optional(),memberId:N.string(),role:N.array(N.string())}),outputSchema:N.object({id:N.string(),organizationId:N.string(),userId:N.string(),role:N.union([N.literal("admin"),N.literal("member"),N.literal("owner")]),createdAt:N.union([N.date(),N.string()]),user:N.object({email:N.string(),name:N.string(),image:N.string().optional()})}),handler:async(Q,X)=>{S1(X),await X.access.check();let Y=Q.organizationId||X.organization?.id;if(!Y)throw Error("Organization ID required (no active organization in context)");let J=await X.boundAuth.organization.updateMemberRole({organizationId:Y,memberId:Q.memberId,role:Q.role});if(!J)throw Error("Failed to update member role");return J}})});var WX1=o(()=>{a91();r91();o91();s91();t91();e91();QX1();XX1();YX1();JX1();GX1()});var KR6,HR6,k40;var ZX1=o(()=>{W1();P6();KR6=N.object({id:N.string().min(1)}),HR6=N.object({user:N.object({id:N.string(),name:N.string(),email:N.string(),image:N.string().nullable()}).nullable()}),k40=N1({name:"USER_GET",description:"Get a user by id (restricted to shared organizations)",inputSchema:KR6,outputSchema:HR6,handler:async(Q,X)=>{await X.access.check(),S1(X);let Y=b9(X);if(!Y)throw Error("Authentication required");let J=await X.storage.users.findById(Q.id,Y);if(!J)return{user:null};return{user:{id:J.id,name:J.name,email:J.email,image:J.image??null}}}})});var $X1=o(()=>{ZX1()});var HX1={};K8(HX1,{managementMCP:()=>v40,ALL_TOOLS:()=>KX1});var KX1,v40=(Q)=>{let X=KX1.map((J)=>({name:J.name,description:J.description,inputSchema:J.inputSchema,outputSchema:J.outputSchema,handler:async(G)=>{return Q.access.setToolName(J.name),await J.execute(G,Q)}}));return DQ1({name:"mcp-mesh-management",version:"1.0.0"}).withTools(X).build()};var _40=o(()=>{NQ1();kQ1();P91();j91();f91();p91();i91();WX1();$X1();KX1=[L40,w40,M40,P40,T40,E40,j40,C40,I40,R40,S40,C60,r60,o60,e60,Q40,X40,V40,z40,U40,B40,D40,E91,N40,O40,T60,E60,j60,A60,Y40,J40,G40,W40,Z40,$40,K40,k40]});var a3,i40,Py,r3,$P;var Ty=o(()=>{a3={JS_EVAL_TYPE_GLOBAL:0,JS_EVAL_TYPE_MODULE:1,JS_EVAL_TYPE_DIRECT:2,JS_EVAL_TYPE_INDIRECT:3,JS_EVAL_TYPE_MASK:3,JS_EVAL_FLAG_STRICT:8,JS_EVAL_FLAG_STRIP:16,JS_EVAL_FLAG_COMPILE_ONLY:32,JS_EVAL_FLAG_BACKTRACE_BARRIER:64},i40={BaseObjects:1,Date:2,Eval:4,StringNormalize:8,RegExp:16,RegExpCompiler:32,JSON:64,Proxy:128,MapSet:256,TypedArrays:512,Promise:1024,BigInt:2048,BigFloat:4096,BigDecimal:8192,OperatorOverloading:16384,BignumExt:32768},Py={Pending:0,Fulfilled:1,Rejected:2},r3={JS_GPN_STRING_MASK:1,JS_GPN_SYMBOL_MASK:2,JS_GPN_PRIVATE_MASK:4,JS_GPN_ENUM_ONLY:16,JS_GPN_SET_ENUM:32,QTS_GPN_NUMBER_MASK:64,QTS_STANDARD_COMPLIANT_NUMBER:128},$P={IsStrictlyEqual:0,IsSameValue:1,IsSameValueZero:2}});function CU(...Q){e40&&console.log("quickjs-emscripten:",...Q)}function*DY1(Q){return yield Q}function eR6(Q){return DY1(X80(Q))}function GY1(Q,X){return(...Y)=>{let J=X.call(Q,Q80,...Y);return X80(J)}}function QS6(Q,X){let Y=X.call(Q,Q80);return X80(Y)}function X80(Q){function X(Y){return Y.done?Y.value:Y.value instanceof Promise?Y.value.then((J)=>X(Q.next(J)),(J)=>X(Q.throw(J))):X(Q.next(Y.value))}return X(Q.next())}function a40(Q,X){let Y;try{Q.dispose()}catch(J){Y=J}if(X&&Y)throw Object.assign(X,{message:`${X.message}
256
256
  Then, failed to dispose scope: ${Y.message}`,disposeError:Y}),X;if(X||Y)throw X||Y}function NY1(Q){let X=Q?Array.from(Q):[];function Y(){return X.forEach((G)=>G.alive?G.dispose():void 0)}function J(){return X.some((G)=>G.alive)}return Object.defineProperty(X,s40,{configurable:!0,enumerable:!1,value:Y}),Object.defineProperty(X,"dispose",{configurable:!0,enumerable:!1,value:Y}),Object.defineProperty(X,"alive",{configurable:!0,enumerable:!1,get:J}),X}function Ay(Q){return!!(Q&&(typeof Q=="object"||typeof Q=="function")&&("alive"in Q)&&typeof Q.alive=="boolean"&&("dispose"in Q)&&typeof Q.dispose=="function")}function XS6(Q){if(!Q)return 0;let X=0;for(let[Y,J]of Object.entries(Q)){if(!(Y in i40))throw new zY1(Y);J&&(X|=i40[Y])}return X}function YS6(Q){if(typeof Q=="number")return Q;if(Q===void 0)return 0;let{type:X,strict:Y,strip:J,compileOnly:G,backtraceBarrier:W}=Q,Z=0;return X==="global"&&(Z|=a3.JS_EVAL_TYPE_GLOBAL),X==="module"&&(Z|=a3.JS_EVAL_TYPE_MODULE),Y&&(Z|=a3.JS_EVAL_FLAG_STRICT),J&&(Z|=a3.JS_EVAL_FLAG_STRIP),G&&(Z|=a3.JS_EVAL_FLAG_COMPILE_ONLY),W&&(Z|=a3.JS_EVAL_FLAG_BACKTRACE_BARRIER),Z}function JS6(Q){if(typeof Q=="number")return Q;if(Q===void 0)return 0;let{strings:X,symbols:Y,quickjsPrivate:J,onlyEnumerable:G,numbers:W,numbersAsStrings:Z}=Q,$=0;return X&&($|=r3.JS_GPN_STRING_MASK),Y&&($|=r3.JS_GPN_SYMBOL_MASK),J&&($|=r3.JS_GPN_PRIVATE_MASK),G&&($|=r3.JS_GPN_ENUM_ONLY),W&&($|=r3.QTS_GPN_NUMBER_MASK),Z&&($|=r3.QTS_STANDARD_COMPLIANT_NUMBER),$}function GS6(...Q){let X=[];for(let Y of Q)Y!==void 0&&(X=X.concat(Y));return X}function W80(Q,X){X.interruptHandler&&Q.setInterruptHandler(X.interruptHandler),X.maxStackSizeBytes!==void 0&&Q.setMaxStackSize(X.maxStackSizeBytes),X.memoryLimitBytes!==void 0&&Q.setMemoryLimit(X.memoryLimitBytes)}function Z80(Q,X){X.moduleLoader&&Q.setModuleLoader(X.moduleLoader),X.shouldInterrupt&&Q.setInterruptHandler(X.shouldInterrupt),X.memoryLimitBytes!==void 0&&Q.setMemoryLimit(X.memoryLimitBytes),X.maxStackSizeBytes!==void 0&&Q.setMaxStackSize(X.maxStackSizeBytes)}var sR6,tR6=(Q,X)=>{for(var Y in X)sR6(Q,Y,{get:X[Y],enumerable:!0})},e40=!1,ZY1,r40,$Y1,o40,KY1,HY1,FY1,VY1,qY1,zY1,UY1,BY1,Q80,y7,s40,WY1,h9,i$,t40,I5,Y80,OY1,LY1,o3,wY1,MY1=class{constructor(Q){this.module=Q}toPointerArray(Q){let X=new Int32Array(Q.map((G)=>G.value)),Y=X.length*X.BYTES_PER_ELEMENT,J=this.module._malloc(Y);return new Uint8Array(this.module.HEAPU8.buffer,J,Y).set(new Uint8Array(X.buffer)),new h9(J,void 0,(G)=>this.module._free(G))}newTypedArray(Q,X){let Y=new Q(Array(X).fill(0)),J=Y.length*Y.BYTES_PER_ELEMENT,G=this.module._malloc(J),W=new Q(this.module.HEAPU8.buffer,G,X);return W.set(Y),new h9({typedArray:W,ptr:G},void 0,(Z)=>this.module._free(Z.ptr))}newMutablePointerArray(Q){return this.newTypedArray(Int32Array,Q)}newHeapCharPointer(Q){let X=this.module.lengthBytesUTF8(Q),Y=X+1,J=this.module._malloc(Y);return this.module.stringToUTF8(Q,J,Y),new h9({ptr:J,strlen:X},void 0,(G)=>this.module._free(G.ptr))}newHeapBufferPointer(Q){let X=Q.byteLength,Y=this.module._malloc(X);return this.module.HEAPU8.set(Q,Y),new h9({pointer:Y,numBytes:X},void 0,(J)=>this.module._free(J.pointer))}consumeHeapCharPointer(Q){let X=this.module.UTF8ToString(Q);return this.module._free(Q),X}},_x4,J80,WS6,ZS6,PY1,TY1,$S6=class{constructor(Q){this.callFunction=Q.callFunction,this.shouldInterrupt=Q.shouldInterrupt,this.loadModuleSource=Q.loadModuleSource,this.normalizeModule=Q.normalizeModule}},G80=class{constructor(Q){this.contextCallbacks=new Map,this.runtimeCallbacks=new Map,this.suspendedCount=0,this.cToHostCallbacks=new $S6({callFunction:(X,Y,J,G,W,Z)=>this.handleAsyncify(X,()=>{try{let $=this.contextCallbacks.get(Y);if(!$)throw Error(`QuickJSContext(ctx = ${Y}) not found for C function call "${Z}"`);return $.callFunction(Y,J,G,W,Z)}catch($){return console.error("[C to host error: returning null]",$),0}}),shouldInterrupt:(X,Y)=>this.handleAsyncify(X,()=>{try{let J=this.runtimeCallbacks.get(Y);if(!J)throw Error(`QuickJSRuntime(rt = ${Y}) not found for C interrupt`);return J.shouldInterrupt(Y)}catch(J){return console.error("[C to host interrupt: returning error]",J),1}}),loadModuleSource:(X,Y,J,G)=>this.handleAsyncify(X,()=>{try{let W=this.runtimeCallbacks.get(Y);if(!W)throw Error(`QuickJSRuntime(rt = ${Y}) not found for C module loader`);let Z=W.loadModuleSource;if(!Z)throw Error(`QuickJSRuntime(rt = ${Y}) does not support module loading`);return Z(Y,J,G)}catch(W){return console.error("[C to host module loader error: returning null]",W),0}}),normalizeModule:(X,Y,J,G,W)=>this.handleAsyncify(X,()=>{try{let Z=this.runtimeCallbacks.get(Y);if(!Z)throw Error(`QuickJSRuntime(rt = ${Y}) not found for C module loader`);let $=Z.normalizeModule;if(!$)throw Error(`QuickJSRuntime(rt = ${Y}) does not support module loading`);return $(Y,J,G,W)}catch(Z){return console.error("[C to host module loader error: returning null]",Z),0}})}),this.module=Q,this.module.callbacks=this.cToHostCallbacks}setRuntimeCallbacks(Q,X){this.runtimeCallbacks.set(Q,X)}deleteRuntime(Q){this.runtimeCallbacks.delete(Q)}setContextCallbacks(Q,X){this.contextCallbacks.set(Q,X)}deleteContext(Q){this.contextCallbacks.delete(Q)}handleAsyncify(Q,X){if(Q)return Q.handleSleep((J)=>{try{let G=X();if(!(G instanceof Promise)){CU("asyncify.handleSleep: not suspending:",G),J(G);return}if(this.suspended)throw new HY1(`Already suspended at: ${this.suspended.stack}
257
257
  Attempted to suspend at:`);this.suspended=new FY1(`(${this.suspendedCount++})`),CU("asyncify.handleSleep: suspending:",this.suspended),G.then((W)=>{this.suspended=void 0,CU("asyncify.handleSleep: resolved:",W),J(W)},(W)=>{CU("asyncify.handleSleep: rejected:",W),console.error("QuickJS: cannot handle error in suspended function",W),this.suspended=void 0})}catch(G){throw CU("asyncify.handleSleep: error:",G),this.suspended=void 0,G}});let Y=X();if(Y instanceof Promise)throw Error("Promise return value not supported in non-asyncify context.");return Y}},$80=class{constructor(Q,X){this.module=Q,this.ffi=X,this.callbacks=new G80(Q)}newRuntime(Q={}){let X=new h9(this.ffi.QTS_NewRuntime(),void 0,(J)=>{this.callbacks.deleteRuntime(J),this.ffi.QTS_FreeRuntime(J)}),Y=new TY1({module:this.module,callbacks:this.callbacks,ffi:this.ffi,rt:X});return W80(Y,Q),Q.moduleLoader&&Y.setModuleLoader(Q.moduleLoader),Y}newContext(Q={}){let X=this.newRuntime(),Y=X.newContext({...Q,ownedLifetimes:GS6(X,Q.ownedLifetimes)});return X.context=Y,Y}evalCode(Q,X={}){return I5.withScope((Y)=>{let J=Y.manage(this.newContext());Z80(J.runtime,X);let G=J.evalCode(Q,"eval.js");if(X.memoryLimitBytes!==void 0&&J.runtime.setMemoryLimit(-1),G.error)throw J.dump(Y.manage(G.error));return J.dump(Y.manage(G.value))})}getWasmMemory(){let Q=this.module.quickjsEmscriptenInit?.(()=>{})?.getWasmMemory?.();if(!Q)throw Error("Variant does not support getting WebAssembly.Memory");return Q}getFFI(){return this.ffi}};var K80=o(()=>{Ty();Ty();sR6=Object.defineProperty;ZY1={};tR6(ZY1,{QuickJSAsyncifyError:()=>HY1,QuickJSAsyncifySuspended:()=>FY1,QuickJSEmptyGetOwnPropertyNames:()=>BY1,QuickJSEmscriptenModuleError:()=>qY1,QuickJSMemoryLeakDetected:()=>VY1,QuickJSNotImplemented:()=>KY1,QuickJSPromisePending:()=>UY1,QuickJSUnknownIntrinsic:()=>zY1,QuickJSUnwrapError:()=>r40,QuickJSUseAfterFree:()=>o40,QuickJSWrongOwner:()=>$Y1});r40=class extends Error{constructor(Q,X){let Y=typeof Q=="object"&&Q&&"message"in Q?String(Q.message):String(Q);super(Y);this.cause=Q,this.context=X,this.name="QuickJSUnwrapError"}},$Y1=class extends Error{constructor(){super(...arguments);this.name="QuickJSWrongOwner"}},o40=class extends Error{constructor(){super(...arguments);this.name="QuickJSUseAfterFree"}},KY1=class extends Error{constructor(){super(...arguments);this.name="QuickJSNotImplemented"}},HY1=class extends Error{constructor(){super(...arguments);this.name="QuickJSAsyncifyError"}},FY1=class extends Error{constructor(){super(...arguments);this.name="QuickJSAsyncifySuspended"}},VY1=class extends Error{constructor(){super(...arguments);this.name="QuickJSMemoryLeakDetected"}},qY1=class extends Error{constructor(){super(...arguments);this.name="QuickJSEmscriptenModuleError"}},zY1=class extends TypeError{constructor(){super(...arguments);this.name="QuickJSUnknownIntrinsic"}},UY1=class extends Error{constructor(){super(...arguments);this.name="QuickJSPromisePending"}},BY1=class extends Error{constructor(){super(...arguments);this.name="QuickJSEmptyGetOwnPropertyNames"}};Q80=DY1;Q80.of=eR6;y7=class{[Symbol.dispose](){return this.dispose()}},s40=Symbol.dispose??Symbol.for("Symbol.dispose"),WY1=y7.prototype;WY1[s40]||(WY1[s40]=function(){return this.dispose()});h9=class Q extends y7{constructor(X,Y,J,G){super();this._value=X,this.copier=Y,this.disposer=J,this._owner=G,this._alive=!0,this._constructorStack=e40?Error("Lifetime constructed").stack:void 0}get alive(){return this._alive}get value(){return this.assertAlive(),this._value}get owner(){return this._owner}get dupable(){return!!this.copier}dup(){if(this.assertAlive(),!this.copier)throw Error("Non-dupable lifetime");return new Q(this.copier(this._value),this.copier,this.disposer,this._owner)}consume(X){this.assertAlive();let Y=X(this);return this.dispose(),Y}map(X){return this.assertAlive(),X(this)}tap(X){return X(this),this}dispose(){this.assertAlive(),this.disposer&&this.disposer(this._value),this._alive=!1}assertAlive(){if(!this.alive)throw this._constructorStack?new o40(`Lifetime not alive
258
258
  ${this._constructorStack}
@@ -1032,7 +1032,7 @@ Please refer to the documentation here: https://better-auth.com/docs/plugins/org
1032
1032
  </script>
1033
1033
  <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference" ${J}></script>
1034
1034
  </body>
1035
- </html>`},gt=(Q)=>{let X=Q?.path??"/reference";return{id:"open-api",endpoints:{generateOpenAPISchema:y0("/open-api/generate-schema",{method:"GET"},async(Y)=>{let J=await $r0(Y.context,Y.context.options);return Y.json(J)}),openAPIReference:y0(X,{method:"GET",metadata:{isAction:!1}},async(Y)=>{if(Q?.disableDefaultReference)throw new n("NOT_FOUND");let J=await $r0(Y.context,Y.context.options);return new Response(qq6(J,Q?.theme,Q?.nonce),{headers:{"Content-Type":"text/html"}})})}}};KX();CG();d8();fQ();W1();var BL4=a6(async()=>{return{}}),DL4=a6({use:[Y8]},async(Q)=>{return{session:Q.context.session}}),NL4=P4({YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION:"You are not allowed to create a new organization",YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS:"You have reached the maximum number of organizations",ORGANIZATION_ALREADY_EXISTS:"Organization already exists",ORGANIZATION_SLUG_ALREADY_TAKEN:"Organization slug already taken",ORGANIZATION_NOT_FOUND:"Organization not found",USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION:"User is not a member of the organization",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION:"You are not allowed to update this organization",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION:"You are not allowed to delete this organization",NO_ACTIVE_ORGANIZATION:"No active organization",USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION:"User is already a member of this organization",MEMBER_NOT_FOUND:"Member not found",ROLE_NOT_FOUND:"Role not found",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM:"You are not allowed to create a new team",TEAM_ALREADY_EXISTS:"Team already exists",TEAM_NOT_FOUND:"Team not found",YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER:"You cannot leave the organization as the only owner",YOU_CANNOT_LEAVE_THE_ORGANIZATION_WITHOUT_AN_OWNER:"You cannot leave the organization without an owner",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER:"You are not allowed to delete this member",YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION:"You are not allowed to invite users to this organization",USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION:"User is already invited to this organization",INVITATION_NOT_FOUND:"Invitation not found",YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION:"You are not the recipient of the invitation",EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION:"Email verification required before accepting or rejecting invitation",YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION:"You are not allowed to cancel this invitation",INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION:"Inviter is no longer a member of the organization",YOU_ARE_NOT_ALLOWED_TO_INVITE_USER_WITH_THIS_ROLE:"You are not allowed to invite a user with this role",FAILED_TO_RETRIEVE_INVITATION:"Failed to retrieve invitation",YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_TEAMS:"You have reached the maximum number of teams",UNABLE_TO_REMOVE_LAST_TEAM:"Unable to remove last team",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER:"You are not allowed to update this member",ORGANIZATION_MEMBERSHIP_LIMIT_REACHED:"Organization membership limit reached",YOU_ARE_NOT_ALLOWED_TO_CREATE_TEAMS_IN_THIS_ORGANIZATION:"You are not allowed to create teams in this organization",YOU_ARE_NOT_ALLOWED_TO_DELETE_TEAMS_IN_THIS_ORGANIZATION:"You are not allowed to delete teams in this organization",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM:"You are not allowed to update this team",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_TEAM:"You are not allowed to delete this team",INVITATION_LIMIT_REACHED:"Invitation limit reached",TEAM_MEMBER_LIMIT_REACHED:"Team member limit reached",USER_IS_NOT_A_MEMBER_OF_THE_TEAM:"User is not a member of the team",YOU_CAN_NOT_ACCESS_THE_MEMBERS_OF_THIS_TEAM:"You are not allowed to list the members of this team",YOU_DO_NOT_HAVE_AN_ACTIVE_TEAM:"You do not have an active team",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM_MEMBER:"You are not allowed to create a new member",YOU_ARE_NOT_ALLOWED_TO_REMOVE_A_TEAM_MEMBER:"You are not allowed to remove a team member",YOU_ARE_NOT_ALLOWED_TO_ACCESS_THIS_ORGANIZATION:"You are not allowed to access this organization as an owner",YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION:"You are not a member of this organization",MISSING_AC_INSTANCE:"Dynamic Access Control requires a pre-defined ac instance on the server auth plugin. Read server logs for more information",YOU_MUST_BE_IN_AN_ORGANIZATION_TO_CREATE_A_ROLE:"You must be in an organization to create a role",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_ROLE:"You are not allowed to create a role",YOU_ARE_NOT_ALLOWED_TO_UPDATE_A_ROLE:"You are not allowed to update a role",YOU_ARE_NOT_ALLOWED_TO_DELETE_A_ROLE:"You are not allowed to delete a role",YOU_ARE_NOT_ALLOWED_TO_READ_A_ROLE:"You are not allowed to read a role",YOU_ARE_NOT_ALLOWED_TO_LIST_A_ROLE:"You are not allowed to list a role",YOU_ARE_NOT_ALLOWED_TO_GET_A_ROLE:"You are not allowed to get a role",TOO_MANY_ROLES:"This organization has too many roles",INVALID_RESOURCE:"The provided permission includes an invalid resource",ROLE_NAME_IS_ALREADY_TAKEN:"That role name is already taken",CANNOT_DELETE_A_PRE_DEFINED_ROLE:"Cannot delete a pre-defined role"});var OL4=Number.POSITIVE_INFINITY;var Hr0=P(),Uq6=q1(["pending","accepted","rejected","canceled"]).default("pending"),LL4=d({id:P().default(XQ),name:P(),slug:P(),logo:P().nullish().optional(),metadata:a0(P(),G4()).or(P().transform((Q)=>JSON.parse(Q))).optional(),createdAt:n1()}),wL4=d({id:P().default(XQ),organizationId:P(),userId:_1.string(),role:Hr0,createdAt:n1().default(()=>new Date)}),ML4=d({id:P().default(XQ),organizationId:P(),email:P(),role:Hr0,status:Uq6,teamId:P().nullish(),inviterId:P(),expiresAt:n1(),createdAt:n1().default(()=>new Date)}),PL4=d({id:P().default(XQ),name:P().min(1),organizationId:P(),createdAt:n1(),updatedAt:n1().optional()}),TL4=d({id:P().default(XQ),teamId:P(),userId:P(),createdAt:n1().default(()=>new Date)}),AL4=d({id:P().default(XQ),organizationId:P(),role:P(),permission:a0(P(),w0(P())),createdAt:n1().default(()=>new Date),updatedAt:n1().optional()}),Kr0=["admin","member","owner"],EL4=r1([q1(Kr0),w0(q1(Kr0))]);z8();d8();fQ();var bL4=P4({INVALID_PHONE_NUMBER:"Invalid phone number",PHONE_NUMBER_EXIST:"Phone number already exists",PHONE_NUMBER_NOT_EXIST:"phone number isn't registered",INVALID_PHONE_NUMBER_OR_PASSWORD:"Invalid phone number or password",UNEXPECTED_ERROR:"Unexpected error",OTP_NOT_FOUND:"OTP not found",OTP_EXPIRED:"OTP expired",INVALID_OTP:"Invalid OTP",PHONE_NUMBER_NOT_VERIFIED:"Phone number not verified",PHONE_NUMBER_CANNOT_BE_UPDATED:"Phone number cannot be updated",SEND_OTP_NOT_IMPLEMENTED:"sendOTP not implemented",TOO_MANY_ATTEMPTS:"Too many attempts"});z8();HX();d8();fQ();SQ();n4();var Bq6=P4({OTP_NOT_ENABLED:"OTP not enabled",OTP_HAS_EXPIRED:"OTP has expired",TOTP_NOT_ENABLED:"TOTP not enabled",TWO_FACTOR_NOT_ENABLED:"Two factor isn't enabled",BACKUP_CODES_NOT_ENABLED:"Backup codes aren't enabled",INVALID_BACKUP_CODE:"Invalid backup code",INVALID_CODE:"Invalid code",TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE:"Too many attempts. Please request a new code.",INVALID_TWO_FACTOR_COOKIE:"Invalid two factor cookie"});d8();fQ();var Dq6=P4({INVALID_USERNAME_OR_PASSWORD:"Invalid username or password",EMAIL_NOT_VERIFIED:"Email not verified",UNEXPECTED_ERROR:"Unexpected error",USERNAME_IS_ALREADY_TAKEN:"Username is already taken. Please try another.",USERNAME_TOO_SHORT:"Username is too short",USERNAME_TOO_LONG:"Username is too long",INVALID_USERNAME:"Username is invalid",INVALID_DISPLAY_USERNAME:"Display username is invalid"});var j3={enabled:!0,batchSize:250,flushIntervalMs:300,maxQueueSize:1e4,redactor:"regex"};import{existsSync as Fr0,readFileSync as Vr0}from"fs";var rk={emailAndPassword:{enabled:!0}},qr0=process.env.CONFIG_PATH||"./config.json",zr0=process.env.AUTH_CONFIG_PATH||"./auth-config.json";function Nq6(){if(Fr0(qr0))try{let Q=Vr0(qr0,"utf-8"),X=JSON.parse(Q);return{auth:rk,monitoring:j3,...X}}catch{return{auth:rk,monitoring:j3}}if(Fr0(zr0))try{let Q=Vr0(zr0,"utf-8");return{auth:JSON.parse(Q),monitoring:j3}}catch{return{auth:rk,monitoring:j3}}return{auth:rk,monitoring:j3}}var ok=Nq6();function Ur0(){return{...j3,...ok.monitoring}}import{existsSync as KD6,mkdirSync as HD6}from"fs";import{Kysely as bs0,PostgresDialect as fs0,sql as ys0}from"kysely";import{BunWorkerDialect as hs0}from"kysely-bun-worker";import*as xs0 from"path";var jJ=m6(De(),1),vP4=jJ.default.Client,we=jJ.default.Pool,_P4=jJ.default.Connection,yP4=jJ.default.types,bP4=jJ.default.Query,fP4=jJ.default.DatabaseError,hP4=jJ.default.escapeIdentifier,xP4=jJ.default.escapeLiteral,gP4=jJ.default.Result,uP4=jJ.default.TypeOverrides,mP4=jJ.default.defaults;function FD6(Q){let X=new we({connectionString:Q.connectionString,max:Q.options?.maxConnections||10,ssl:process.env.DATABASE_PG_SSL==="true"?!0:!1}),Y=new fs0({pool:X});return{type:"postgres",db:new bs0({dialect:Y}),pool:X}}function gs0(Q){if(Q===":memory:")return":memory:";if(Q.includes("://"))return new URL(Q).pathname;return Q}function us0(Q){if(Q!==":memory:"&&Q!=="/"&&Q){let X=Q.substring(0,Q.lastIndexOf("/"));if(X&&X!=="/"&&!KD6(X))try{HD6(X,{recursive:!0})}catch{return console.warn(`Failed to create directory ${X}, using in-memory database`),":memory:"}}return Q}function VD6(Q){let X=gs0(Q.connectionString);X=us0(X);let Y=new hs0({url:X||":memory:"}),J=new bs0({dialect:Y});if(X!==":memory:"&&Q.options?.enableWAL!==!1)ys0`PRAGMA journal_mode = WAL;`.execute(J).catch(()=>{});if(X!==":memory:"){let G=Q.options?.busyTimeout||5000;ys0`PRAGMA busy_timeout = ${G};`.execute(J).catch(()=>{})}return{type:"sqlite",db:J}}function ms0(Q){let X=Q||"file:./data/mesh.db";if(X===":memory:")return{type:"sqlite",connectionString:":memory:"};X=X.startsWith("/")?`file://${X}`:X;let Y=URL.canParse(X)?new URL(X):null,J=Y?.protocol.replace(":","")??X.split("://")[0];switch(J){case"postgres":case"postgresql":return{type:"postgres",connectionString:X};case"sqlite":case"file":if(!Y?.pathname)throw Error("Invalid database URL: "+X);return{type:"sqlite",connectionString:Y.pathname};default:throw Error(`Unsupported database protocol: ${J}. Supported protocols: postgres://, postgresql://, sqlite://, file://`)}}function Pe(){return process.env.DATABASE_URL||`file:${xs0.join(process.cwd(),"data/mesh.db")}`}function ls0(Q){let X=ms0(Q);if(X.type==="postgres")return new fs0({pool:new we({connectionString:X.connectionString,max:X.options?.maxConnections||10,ssl:process.env.DATABASE_PG_SSL==="true"?!0:!1})});let Y=gs0(X.connectionString);return Y=us0(Y),new hs0({url:Y||":memory:"})}function qD6(Q){let X=ms0(Q);if(X.type==="postgres")return FD6(X);return VD6(X)}var Me=null;function Kv(){if(!Me)Me=qD6(Pe());return Me}class Te{apiKey;constructor(Q){this.apiKey=Q}async sendEmail({to:Q,from:X,subject:Y,html:J}){let G=await fetch("https://api.resend.com/emails",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({to:Q,from:X,subject:Y,html:J})});if(!G.ok)throw Error(`Failed to send email: ${G.statusText}`)}}class Ae{apiKey;constructor(Q){this.apiKey=Q}async sendEmail({to:Q,from:X,subject:Y,html:J}){let G=await fetch("https://api.sendgrid.com/v3/mail/send",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({personalizations:[{to:[{email:Q}]}],from:{email:X},subject:Y,content:[{type:"text/html",value:J}]})});if(!G.ok){let W=await G.text();throw Error(`Failed to send email via SendGrid: ${G.statusText} - ${W}`)}}}var zD6=(Q)=>{let X=new Te(Q.config.apiKey);return async({to:Y,subject:J,html:G})=>{await X.sendEmail({to:Y,from:Q.config.fromEmail,subject:J,html:G})}},UD6=(Q)=>{let X=new Ae(Q.config.apiKey);return async({to:Y,subject:J,html:G})=>{await X.sendEmail({to:Y,from:Q.config.fromEmail,subject:J,html:G})}},BD6={resend:zD6,sendgrid:UD6};function Hv(Q){let X=BD6[Q.provider];if(!X)throw Error(`Unknown email provider: ${Q.provider}`);return X(Q)}function Fv(Q,X){return Q.find((Y)=>Y.id===X)}var ds0=(Q,X)=>{let Y=Fv(X,Q.emailProviderId);if(!Y)throw Error(`Email provider with id '${Q.emailProviderId}' not found`);let J=Hv(Y);return{sendMagicLink:async({email:G,url:W})=>{await J({to:G,subject:"Magic Link",html:`<p>Click <a href="${W}">here</a> to login</p>`})}}};R3();import{createCipheriv as DD6,createDecipheriv as ND6,randomBytes as as0}from"crypto";var rs0="aes-256-gcm",jw=16,os0=16,ss0=32;class Cw{key;constructor(Q){if(Buffer.from(Q,"base64").length===ss0)this.key=Buffer.from(Q,"base64");else{let X=D0("crypto");this.key=X.createHash("sha256").update(Q).digest()}}async encrypt(Q){let X=as0(jw),Y=DD6(rs0,this.key,X),J=Y.update(Q,"utf8");J=Buffer.concat([J,Y.final()]);let G=Y.getAuthTag();return Buffer.concat([X,G,J]).toString("base64")}async decrypt(Q){let X=Buffer.from(Q,"base64"),Y=X.subarray(0,jw),J=X.subarray(jw,jw+os0),G=X.subarray(jw+os0),W=ND6(rs0,this.key,Y);W.setAuthTag(J);let Z=W.update(G);return Z=Buffer.concat([Z,W.final()]),Z.toString("utf8")}static generateKey(){return as0(ss0).toString("base64")}}U7();import{webcrypto as Xt0}from"crypto";var Qt0="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var PD6=128,k3,yz;function TD6(Q){if(!k3||k3.length<Q)k3=Buffer.allocUnsafe(Q*PD6),Xt0.getRandomValues(k3),yz=0;else if(yz+Q>k3.length)Xt0.getRandomValues(k3),yz=0;yz+=Q}function Yt0(Q=21){TD6(Q|=0);let X="";for(let Y=yz-Q;Y<yz;Y++)X+=Qt0[k3[Y]&63];return X}function lG(Q){return`${Q}_${Yt0()}`}var AD6=["connection_headers","oauth_config","configuration_scopes","metadata","tools","bindings"];class Iw{db;vault;constructor(Q,X){this.db=Q;this.vault=X}async create(Q){let X=Q.id??lG("conn"),Y=new Date().toISOString(),J=await this.findById(X);if(J){if(J.organization_id!==Q.organization_id)throw Error("Connection ID already exists");return this.update(X,Q)}let G=await this.serializeConnection({...Q,id:Q.id??X,status:"active",created_at:Y,updated_at:Y});await this.db.insertInto("connections").values(G).execute();let W=await this.findById(X);if(!W)throw Error(`Failed to create connection with id: ${X}`);return W}async findById(Q,X){let Y=this.db.selectFrom("connections").selectAll().where("id","=",Q);if(X)Y=Y.where("organization_id","=",X);let J=await Y.executeTakeFirst();return J?this.deserializeConnection(J):null}async list(Q){let X=await this.db.selectFrom("connections").selectAll().where("organization_id","=",Q).execute();return Promise.all(X.map((Y)=>this.deserializeConnection(Y)))}async update(Q,X){if(Object.keys(X).length===0){let G=await this.findById(Q);if(!G)throw Error("Connection not found");return G}let Y=await this.serializeConnection({...X,updated_at:new Date().toISOString()});await this.db.updateTable("connections").set(Y).where("id","=",Q).execute();let J=await this.findById(Q);if(!J)throw Error("Connection not found after update");return J}async delete(Q){await this.db.deleteFrom("connections").where("id","=",Q).execute()}async testConnection(Q,X){let Y=await this.findById(Q);if(!Y)throw Error("Connection not found");let J=Date.now();if(Y.connection_type==="STDIO")return{healthy:!0,latencyMs:Date.now()-J};if(!Y.connection_url)return{healthy:!1,latencyMs:Date.now()-J};try{let G=Y.connection_headers,W=await fetch(Y.connection_url,{method:"POST",headers:{"Content-Type":"application/json",...Y.connection_token&&{Authorization:`Bearer ${Y.connection_token}`},...G?.headers,...X},body:JSON.stringify({jsonrpc:"2.0",method:"ping",id:1})});return{healthy:W.ok||W.status===404,latencyMs:Date.now()-J}}catch{return{healthy:!1,latencyMs:Date.now()-J}}}async serializeConnection(Q){let X={};for(let[Y,J]of Object.entries(Q)){if(J===void 0)continue;if(Y==="connection_token"&&J)X[Y]=await this.vault.encrypt(J);else if(Y==="configuration_state"&&J){let G=JSON.stringify(J);X[Y]=await this.vault.encrypt(G)}else if(Y==="connection_headers"&&J){let G=J;if(S3(G)&&G.envVars){let W={};for(let[Z,$]of Object.entries(G.envVars))W[Z]=await this.vault.encrypt($);X[Y]=JSON.stringify({...G,envVars:W})}else X[Y]=JSON.stringify(G)}else if(AD6.includes(Y))X[Y]=J?JSON.stringify(J):null;else X[Y]=J}return X}async deserializeConnection(Q){let X=null;if(Q.connection_token)try{X=await this.vault.decrypt(Q.connection_token)}catch(W){console.error("Failed to decrypt connection token:",W)}let Y=null;if(Q.configuration_state)try{let W=await this.vault.decrypt(Q.configuration_state);Y=JSON.parse(W)}catch(W){console.error("Failed to decrypt configuration state:",W)}let J=null;if(Q.connection_headers)try{let W=JSON.parse(Q.connection_headers);if(S3(W)&&W.envVars){let Z={};for(let[$,K]of Object.entries(W.envVars))try{Z[$]=await this.vault.decrypt(K)}catch{Z[$]=K}J={...W,envVars:Z}}else J=W}catch(W){console.error("Failed to parse connection_headers:",W)}let G=(W)=>{if(W===null)return null;if(typeof W==="string")try{return JSON.parse(W)}catch{return null}return W};return{id:Q.id,organization_id:Q.organization_id,created_by:Q.created_by,title:Q.title,description:Q.description,icon:Q.icon,app_name:Q.app_name,app_id:Q.app_id,connection_type:Q.connection_type,connection_url:Q.connection_url,connection_token:X,connection_headers:J,oauth_config:G(Q.oauth_config),configuration_state:Y,configuration_scopes:G(Q.configuration_scopes),metadata:G(Q.metadata),tools:G(Q.tools),bindings:G(Q.bindings),status:Q.status,created_at:Q.created_at,updated_at:Q.updated_at}}}class Rw{db;constructor(Q){this.db=Q}async create(Q,X,Y){let J=lG("gw"),G=new Date().toISOString();if(Y.isDefault)return await this.db.transaction().execute(async(Z)=>{if(await Z.updateTable("gateways").set({is_default:0,updated_at:G,updated_by:X}).where("organization_id","=",Q).where("is_default","=",1).execute(),await Z.insertInto("gateways").values({id:J,organization_id:Q,title:Y.title,description:Y.description??null,tool_selection_strategy:Y.toolSelectionStrategy??"passthrough",tool_selection_mode:Y.toolSelectionMode??"inclusion",icon:Y.icon??null,status:Y.status??"active",is_default:1,created_at:G,updated_at:G,created_by:X,updated_by:null}).execute(),Y.connections.length>0)await Z.insertInto("gateway_connections").values(Y.connections.map((K)=>({id:lG("gwc"),gateway_id:J,connection_id:K.connectionId,selected_tools:K.selectedTools?JSON.stringify(K.selectedTools):null,selected_resources:K.selectedResources?JSON.stringify(K.selectedResources):null,selected_prompts:K.selectedPrompts?JSON.stringify(K.selectedPrompts):null,created_at:G}))).execute();let $=await this.findByIdInternal(Z,J);if(!$)throw Error(`Failed to create gateway with id: ${J}`);return $});if(await this.db.insertInto("gateways").values({id:J,organization_id:Q,title:Y.title,description:Y.description??null,tool_selection_strategy:Y.toolSelectionStrategy??"passthrough",tool_selection_mode:Y.toolSelectionMode??"inclusion",icon:Y.icon??null,status:Y.status??"active",is_default:0,created_at:G,updated_at:G,created_by:X,updated_by:null}).execute(),Y.connections.length>0)await this.db.insertInto("gateway_connections").values(Y.connections.map((Z)=>({id:lG("gwc"),gateway_id:J,connection_id:Z.connectionId,selected_tools:Z.selectedTools?JSON.stringify(Z.selectedTools):null,selected_resources:Z.selectedResources?JSON.stringify(Z.selectedResources):null,selected_prompts:Z.selectedPrompts?JSON.stringify(Z.selectedPrompts):null,created_at:G}))).execute();let W=await this.findById(J);if(!W)throw Error(`Failed to create gateway with id: ${J}`);return W}async findById(Q){return this.findByIdInternal(this.db,Q)}async findByIdInternal(Q,X){let Y=await Q.selectFrom("gateways").selectAll().where("id","=",X).executeTakeFirst();if(!Y)return null;let J=await Q.selectFrom("gateway_connections").selectAll().where("gateway_id","=",X).execute();return this.deserializeGatewayWithConnections(Y,J)}async list(Q){let X=await this.db.selectFrom("gateways").selectAll().where("organization_id","=",Q).execute(),Y=X.map((W)=>W.id);if(Y.length===0)return[];let J=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","in",Y).execute(),G=new Map;for(let W of J){let Z=G.get(W.gateway_id)??[];Z.push(W),G.set(W.gateway_id,Z)}return X.map((W)=>this.deserializeGatewayWithConnections(W,G.get(W.id)??[]))}async listByConnectionId(Q,X){let J=(await this.db.selectFrom("gateway_connections").select("gateway_id").where("connection_id","=",X).execute()).map((K)=>K.gateway_id);if(J.length===0)return[];let G=await this.db.selectFrom("gateways").selectAll().where("id","in",J).where("organization_id","=",Q).execute();if(G.length===0)return[];let W=G.map((K)=>K.id),Z=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","in",W).execute(),$=new Map;for(let K of Z){let H=$.get(K.gateway_id)??[];H.push(K),$.set(K.gateway_id,H)}return G.map((K)=>this.deserializeGatewayWithConnections(K,$.get(K.id)??[]))}async update(Q,X,Y){let J=new Date().toISOString(),G={updated_at:J,updated_by:X};if(Y.title!==void 0)G.title=Y.title;if(Y.description!==void 0)G.description=Y.description;if(Y.toolSelectionStrategy!==void 0)G.tool_selection_strategy=Y.toolSelectionStrategy;if(Y.toolSelectionMode!==void 0)G.tool_selection_mode=Y.toolSelectionMode;if(Y.icon!==void 0)G.icon=Y.icon;if(Y.status!==void 0)G.status=Y.status;if(Y.isDefault===!1)G.is_default=0;if(Y.isDefault===!0)G.is_default=1;if(Y.isDefault===!0){let Z=await this.findById(Q);if(!Z)throw Error(`Gateway not found: ${Q}`);await this.db.transaction().execute(async($)=>{if(await $.updateTable("gateways").set({is_default:0,updated_at:J,updated_by:X}).where("organization_id","=",Z.organizationId).where("is_default","=",1).execute(),await $.updateTable("gateways").set(G).where("id","=",Q).execute(),Y.connections!==void 0){if(await $.deleteFrom("gateway_connections").where("gateway_id","=",Q).execute(),Y.connections.length>0)await $.insertInto("gateway_connections").values(Y.connections.map((K)=>({id:lG("gwc"),gateway_id:Q,connection_id:K.connectionId,selected_tools:K.selectedTools?JSON.stringify(K.selectedTools):null,selected_resources:K.selectedResources?JSON.stringify(K.selectedResources):null,selected_prompts:K.selectedPrompts?JSON.stringify(K.selectedPrompts):null,created_at:J}))).execute()}})}else if(await this.db.updateTable("gateways").set(G).where("id","=",Q).execute(),Y.connections!==void 0){if(await this.db.deleteFrom("gateway_connections").where("gateway_id","=",Q).execute(),Y.connections.length>0)await this.db.insertInto("gateway_connections").values(Y.connections.map((Z)=>({id:lG("gwc"),gateway_id:Q,connection_id:Z.connectionId,selected_tools:Z.selectedTools?JSON.stringify(Z.selectedTools):null,selected_resources:Z.selectedResources?JSON.stringify(Z.selectedResources):null,selected_prompts:Z.selectedPrompts?JSON.stringify(Z.selectedPrompts):null,created_at:J}))).execute()}let W=await this.findById(Q);if(!W)throw Error("Gateway not found after update");return W}async delete(Q){await this.db.deleteFrom("gateways").where("id","=",Q).execute()}async getDefaultByOrgId(Q){let X=await this.db.selectFrom("gateways").selectAll().where("organization_id","=",Q).where("is_default","=",1).executeTakeFirst();if(!X)return null;let Y=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","=",X.id).execute();return this.deserializeGatewayWithConnections(X,Y)}async getDefaultByOrgSlug(Q){let X=await this.db.selectFrom("organization").select("id").where("slug","=",Q).executeTakeFirst();if(!X)return null;return this.getDefaultByOrgId(X.id)}async setDefault(Q,X){let Y=await this.findById(Q);if(!Y)throw Error(`Gateway not found: ${Q}`);let J=new Date().toISOString();await this.db.transaction().execute(async(W)=>{await W.updateTable("gateways").set({is_default:0,updated_at:J,updated_by:X}).where("organization_id","=",Y.organizationId).where("is_default","=",1).execute(),await W.updateTable("gateways").set({is_default:1,updated_at:J,updated_by:X}).where("id","=",Q).execute()});let G=await this.findById(Q);if(!G)throw Error("Gateway not found after setting default");return G}deserializeGatewayWithConnections(Q,X){return{...this.deserializeGateway(Q),connections:X.map((J)=>({connectionId:J.connection_id,selectedTools:this.parseJson(J.selected_tools),selectedResources:this.parseJson(J.selected_resources),selectedPrompts:this.parseJson(J.selected_prompts)}))}}deserializeGateway(Q){return{id:Q.id,organizationId:Q.organization_id,title:Q.title,description:Q.description,toolSelectionStrategy:this.parseToolSelectionStrategy(Q.tool_selection_strategy),toolSelectionMode:this.parseToolSelectionMode(Q.tool_selection_mode),icon:Q.icon,status:Q.status,isDefault:Q.is_default===1,createdAt:Q.created_at,updatedAt:Q.updated_at,createdBy:Q.created_by,updatedBy:Q.updated_by}}parseToolSelectionStrategy(Q){if(Q==="smart_tool_selection")return"smart_tool_selection";if(Q==="code_execution")return"code_execution";return"passthrough"}parseToolSelectionMode(Q){if(Q==="exclusion")return"exclusion";return"inclusion"}parseJson(Q){if(Q===null)return null;if(typeof Q==="string")try{return JSON.parse(Q)}catch{return null}return Q}}e_();W1();function VR6(){return[{permissions:{self:["*"]},getTools:async()=>{let{ALL_TOOLS:Q}=await Promise.resolve().then(() => (_40(),HX1));return Q.map((X)=>{return{name:X.name,inputSchema:N.toJSONSchema(X.inputSchema,{unrepresentable:"any"}),outputSchema:X.outputSchema?N.toJSONSchema(X.outputSchema,{unrepresentable:"any"}):void 0,description:X.description}})},data:is0(process.env.BASE_URL||"http://localhost:3000")},{data:ns0()}]}async function FX1(Q,X){try{let Y=Kv(),J=new Cw(process.env.ENCRYPTION_KEY||""),G=new Iw(Y.db,J),W=new Rw(Y.db),Z=VR6(),$=[];await Promise.all(Z.map(async(K)=>{let H=null;if(K.permissions)H=(await v7.api.createApiKey({body:{name:`${K.data.app_name??crypto.randomUUID()}-mcp`,userId:X,permissions:K.permissions,rateLimitEnabled:!1,metadata:{organization:{id:Q},purpose:"default-org-connections"}}}))?.key;let F=await K.getTools?.()??await zU({id:"pending",title:K.data.title,connection_type:K.data.connection_type,connection_url:K.data.connection_url,connection_token:K.data.connection_token,connection_headers:K.data.connection_headers}).catch(()=>null),V=K.data.id?`${Q}_${K.data.id}`:void 0,q=await G.create({...K.data,id:V,tools:F,organization_id:Q,created_by:X,connection_token:K.data.connection_token??H});$.push(q.id)})),await W.create(Q,X,{title:"Default Gateway",description:"Auto-created gateway for organization",toolSelectionStrategy:"passthrough",toolSelectionMode:"exclusion",status:"active",isDefault:!0,connections:$.map((K)=>({connectionId:K}))})}catch(Y){console.error("Error creating default MCP connections:",Y)}}var y40=["owner","admin","user"],VX1=["owner","admin"];var qR6=(Q)=>{return{defaultSSO:[{domain:Q.domain,providerId:Q.providerId,oidcConfig:{issuer:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/v2.0`,pkce:!0,clientId:Q.MS_CLIENT_ID,clientSecret:Q.MS_CLIENT_SECRET,discoveryEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/v2.0/.well-known/openid-configuration`,authorizationEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/oauth2/v2.0/authorize`,tokenEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/oauth2/v2.0/token`,jwksEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/discovery/v2.0/keys`,userInfoEndpoint:"https://graph.microsoft.com/oidc/userinfo",tokenEndpointAuthentication:"client_secret_post",scopes:Q.scopes,mapping:{id:"sub",email:"email",emailVerified:"email_verified",name:"name",image:"picture",extraFields:{emailVerified:"email_verified"}}}}]}},qX1=(Q)=>{if(Q.providerId==="microsoft")return qR6(Q);throw Error(`Unsupported provider: ${Q.providerId}`)};function zR6(Q){return Q.toLowerCase().trim().replace(/[^a-z0-9\s_-]+/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var zX1=["labs","hub","studio","workspace","systems","core","cloud","works"],UX1=["capybara","guarana","deco","samba","feijoada","capoeira","carnival"];function UR6(){let Q=Math.floor(Math.random()*UX1.length),X=Math.floor(Math.random()*zX1.length),Y=UX1[Q]??"deco",J=zX1[X]??"studio";return`${Y}-${J}`}var BR6=Object.values(vD()).map((Q)=>Q.map((X)=>X.name)).flat(),DR6={...bk,self:["*",...BR6]},zy=mG(DR6),NR6=zy.newRole({self:["*"],...$w.statements}),OR6=zy.newRole({self:["*"],...$w.statements}),LR6=zy.newRole({self:["*"],...$w.statements}),BX1=Object.values(vD()).map((Q)=>Q.map((X)=>`self:${X.name}`)).flat(),a8=ok.auth,DX1=void 0;if(a8.inviteEmailProviderId&&a8.emailProviders&&a8.emailProviders.length>0){let Q=Fv(a8.emailProviders,a8.inviteEmailProviderId);if(Q){let X=Hv(Q);DX1=async(Y)=>{let J=Y.inviter.user?.name||Y.inviter.user?.email,G=`${process.env.BASE_URL||"http://localhost:3000"}/auth/accept-invitation?invitationId=${Y.invitation.id}`;await X({to:Y.email,subject:`Invitation to join ${Y.organization.name}`,html:`
1035
+ </html>`},gt=(Q)=>{let X=Q?.path??"/reference";return{id:"open-api",endpoints:{generateOpenAPISchema:y0("/open-api/generate-schema",{method:"GET"},async(Y)=>{let J=await $r0(Y.context,Y.context.options);return Y.json(J)}),openAPIReference:y0(X,{method:"GET",metadata:{isAction:!1}},async(Y)=>{if(Q?.disableDefaultReference)throw new n("NOT_FOUND");let J=await $r0(Y.context,Y.context.options);return new Response(qq6(J,Q?.theme,Q?.nonce),{headers:{"Content-Type":"text/html"}})})}}};KX();CG();d8();fQ();W1();var BL4=a6(async()=>{return{}}),DL4=a6({use:[Y8]},async(Q)=>{return{session:Q.context.session}}),NL4=P4({YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION:"You are not allowed to create a new organization",YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS:"You have reached the maximum number of organizations",ORGANIZATION_ALREADY_EXISTS:"Organization already exists",ORGANIZATION_SLUG_ALREADY_TAKEN:"Organization slug already taken",ORGANIZATION_NOT_FOUND:"Organization not found",USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION:"User is not a member of the organization",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION:"You are not allowed to update this organization",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION:"You are not allowed to delete this organization",NO_ACTIVE_ORGANIZATION:"No active organization",USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION:"User is already a member of this organization",MEMBER_NOT_FOUND:"Member not found",ROLE_NOT_FOUND:"Role not found",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM:"You are not allowed to create a new team",TEAM_ALREADY_EXISTS:"Team already exists",TEAM_NOT_FOUND:"Team not found",YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER:"You cannot leave the organization as the only owner",YOU_CANNOT_LEAVE_THE_ORGANIZATION_WITHOUT_AN_OWNER:"You cannot leave the organization without an owner",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER:"You are not allowed to delete this member",YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION:"You are not allowed to invite users to this organization",USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION:"User is already invited to this organization",INVITATION_NOT_FOUND:"Invitation not found",YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION:"You are not the recipient of the invitation",EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION:"Email verification required before accepting or rejecting invitation",YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION:"You are not allowed to cancel this invitation",INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION:"Inviter is no longer a member of the organization",YOU_ARE_NOT_ALLOWED_TO_INVITE_USER_WITH_THIS_ROLE:"You are not allowed to invite a user with this role",FAILED_TO_RETRIEVE_INVITATION:"Failed to retrieve invitation",YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_TEAMS:"You have reached the maximum number of teams",UNABLE_TO_REMOVE_LAST_TEAM:"Unable to remove last team",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER:"You are not allowed to update this member",ORGANIZATION_MEMBERSHIP_LIMIT_REACHED:"Organization membership limit reached",YOU_ARE_NOT_ALLOWED_TO_CREATE_TEAMS_IN_THIS_ORGANIZATION:"You are not allowed to create teams in this organization",YOU_ARE_NOT_ALLOWED_TO_DELETE_TEAMS_IN_THIS_ORGANIZATION:"You are not allowed to delete teams in this organization",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM:"You are not allowed to update this team",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_TEAM:"You are not allowed to delete this team",INVITATION_LIMIT_REACHED:"Invitation limit reached",TEAM_MEMBER_LIMIT_REACHED:"Team member limit reached",USER_IS_NOT_A_MEMBER_OF_THE_TEAM:"User is not a member of the team",YOU_CAN_NOT_ACCESS_THE_MEMBERS_OF_THIS_TEAM:"You are not allowed to list the members of this team",YOU_DO_NOT_HAVE_AN_ACTIVE_TEAM:"You do not have an active team",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM_MEMBER:"You are not allowed to create a new member",YOU_ARE_NOT_ALLOWED_TO_REMOVE_A_TEAM_MEMBER:"You are not allowed to remove a team member",YOU_ARE_NOT_ALLOWED_TO_ACCESS_THIS_ORGANIZATION:"You are not allowed to access this organization as an owner",YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION:"You are not a member of this organization",MISSING_AC_INSTANCE:"Dynamic Access Control requires a pre-defined ac instance on the server auth plugin. Read server logs for more information",YOU_MUST_BE_IN_AN_ORGANIZATION_TO_CREATE_A_ROLE:"You must be in an organization to create a role",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_ROLE:"You are not allowed to create a role",YOU_ARE_NOT_ALLOWED_TO_UPDATE_A_ROLE:"You are not allowed to update a role",YOU_ARE_NOT_ALLOWED_TO_DELETE_A_ROLE:"You are not allowed to delete a role",YOU_ARE_NOT_ALLOWED_TO_READ_A_ROLE:"You are not allowed to read a role",YOU_ARE_NOT_ALLOWED_TO_LIST_A_ROLE:"You are not allowed to list a role",YOU_ARE_NOT_ALLOWED_TO_GET_A_ROLE:"You are not allowed to get a role",TOO_MANY_ROLES:"This organization has too many roles",INVALID_RESOURCE:"The provided permission includes an invalid resource",ROLE_NAME_IS_ALREADY_TAKEN:"That role name is already taken",CANNOT_DELETE_A_PRE_DEFINED_ROLE:"Cannot delete a pre-defined role"});var OL4=Number.POSITIVE_INFINITY;var Hr0=P(),Uq6=q1(["pending","accepted","rejected","canceled"]).default("pending"),LL4=d({id:P().default(XQ),name:P(),slug:P(),logo:P().nullish().optional(),metadata:a0(P(),G4()).or(P().transform((Q)=>JSON.parse(Q))).optional(),createdAt:n1()}),wL4=d({id:P().default(XQ),organizationId:P(),userId:_1.string(),role:Hr0,createdAt:n1().default(()=>new Date)}),ML4=d({id:P().default(XQ),organizationId:P(),email:P(),role:Hr0,status:Uq6,teamId:P().nullish(),inviterId:P(),expiresAt:n1(),createdAt:n1().default(()=>new Date)}),PL4=d({id:P().default(XQ),name:P().min(1),organizationId:P(),createdAt:n1(),updatedAt:n1().optional()}),TL4=d({id:P().default(XQ),teamId:P(),userId:P(),createdAt:n1().default(()=>new Date)}),AL4=d({id:P().default(XQ),organizationId:P(),role:P(),permission:a0(P(),w0(P())),createdAt:n1().default(()=>new Date),updatedAt:n1().optional()}),Kr0=["admin","member","owner"],EL4=r1([q1(Kr0),w0(q1(Kr0))]);z8();d8();fQ();var bL4=P4({INVALID_PHONE_NUMBER:"Invalid phone number",PHONE_NUMBER_EXIST:"Phone number already exists",PHONE_NUMBER_NOT_EXIST:"phone number isn't registered",INVALID_PHONE_NUMBER_OR_PASSWORD:"Invalid phone number or password",UNEXPECTED_ERROR:"Unexpected error",OTP_NOT_FOUND:"OTP not found",OTP_EXPIRED:"OTP expired",INVALID_OTP:"Invalid OTP",PHONE_NUMBER_NOT_VERIFIED:"Phone number not verified",PHONE_NUMBER_CANNOT_BE_UPDATED:"Phone number cannot be updated",SEND_OTP_NOT_IMPLEMENTED:"sendOTP not implemented",TOO_MANY_ATTEMPTS:"Too many attempts"});z8();HX();d8();fQ();SQ();n4();var Bq6=P4({OTP_NOT_ENABLED:"OTP not enabled",OTP_HAS_EXPIRED:"OTP has expired",TOTP_NOT_ENABLED:"TOTP not enabled",TWO_FACTOR_NOT_ENABLED:"Two factor isn't enabled",BACKUP_CODES_NOT_ENABLED:"Backup codes aren't enabled",INVALID_BACKUP_CODE:"Invalid backup code",INVALID_CODE:"Invalid code",TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE:"Too many attempts. Please request a new code.",INVALID_TWO_FACTOR_COOKIE:"Invalid two factor cookie"});d8();fQ();var Dq6=P4({INVALID_USERNAME_OR_PASSWORD:"Invalid username or password",EMAIL_NOT_VERIFIED:"Email not verified",UNEXPECTED_ERROR:"Unexpected error",USERNAME_IS_ALREADY_TAKEN:"Username is already taken. Please try another.",USERNAME_TOO_SHORT:"Username is too short",USERNAME_TOO_LONG:"Username is too long",INVALID_USERNAME:"Username is invalid",INVALID_DISPLAY_USERNAME:"Display username is invalid"});var j3={enabled:!0,batchSize:250,flushIntervalMs:300,maxQueueSize:1e4,redactor:"regex"};import{existsSync as Fr0,readFileSync as Vr0}from"fs";var rk={emailAndPassword:{enabled:!0}},qr0=process.env.CONFIG_PATH||"./config.json",zr0=process.env.AUTH_CONFIG_PATH||"./auth-config.json";function Nq6(){if(Fr0(qr0))try{let Q=Vr0(qr0,"utf-8"),X=JSON.parse(Q);return{auth:rk,monitoring:j3,...X}}catch{return{auth:rk,monitoring:j3}}if(Fr0(zr0))try{let Q=Vr0(zr0,"utf-8");return{auth:JSON.parse(Q),monitoring:j3}}catch{return{auth:rk,monitoring:j3}}return{auth:rk,monitoring:j3}}var ok=Nq6();function Ur0(){return{...j3,...ok.monitoring}}import{existsSync as KD6,mkdirSync as HD6}from"fs";import{Kysely as bs0,PostgresDialect as fs0,sql as ys0}from"kysely";import{BunWorkerDialect as hs0}from"kysely-bun-worker";import*as xs0 from"path";var jJ=m6(De(),1),vP4=jJ.default.Client,we=jJ.default.Pool,_P4=jJ.default.Connection,yP4=jJ.default.types,bP4=jJ.default.Query,fP4=jJ.default.DatabaseError,hP4=jJ.default.escapeIdentifier,xP4=jJ.default.escapeLiteral,gP4=jJ.default.Result,uP4=jJ.default.TypeOverrides,mP4=jJ.default.defaults;function FD6(Q){let X=new we({connectionString:Q.connectionString,max:Q.options?.maxConnections||10,ssl:process.env.DATABASE_PG_SSL==="true"?!0:!1}),Y=new fs0({pool:X});return{type:"postgres",db:new bs0({dialect:Y}),pool:X}}function gs0(Q){if(Q===":memory:")return":memory:";if(Q.includes("://"))return new URL(Q).pathname;return Q}function us0(Q){if(Q!==":memory:"&&Q!=="/"&&Q){let X=Q.substring(0,Q.lastIndexOf("/"));if(X&&X!=="/"&&!KD6(X))try{HD6(X,{recursive:!0})}catch{return console.warn(`Failed to create directory ${X}, using in-memory database`),":memory:"}}return Q}function VD6(Q){let X=gs0(Q.connectionString);X=us0(X);let Y=new hs0({url:X||":memory:"}),J=new bs0({dialect:Y});if(X!==":memory:"&&Q.options?.enableWAL!==!1)ys0`PRAGMA journal_mode = WAL;`.execute(J).catch(()=>{});if(X!==":memory:"){let G=Q.options?.busyTimeout||5000;ys0`PRAGMA busy_timeout = ${G};`.execute(J).catch(()=>{})}return{type:"sqlite",db:J}}function ms0(Q){let X=Q||"file:./data/mesh.db";if(X===":memory:")return{type:"sqlite",connectionString:":memory:"};X=X.startsWith("/")?`file://${X}`:X;let Y=URL.canParse(X)?new URL(X):null,J=Y?.protocol.replace(":","")??X.split("://")[0];switch(J){case"postgres":case"postgresql":return{type:"postgres",connectionString:X};case"sqlite":case"file":if(!Y?.pathname)throw Error("Invalid database URL: "+X);return{type:"sqlite",connectionString:Y.pathname};default:throw Error(`Unsupported database protocol: ${J}. Supported protocols: postgres://, postgresql://, sqlite://, file://`)}}function Pe(){return process.env.DATABASE_URL||`file:${xs0.join(process.cwd(),"data/mesh.db")}`}function ls0(Q){let X=ms0(Q);if(X.type==="postgres")return new fs0({pool:new we({connectionString:X.connectionString,max:X.options?.maxConnections||10,ssl:process.env.DATABASE_PG_SSL==="true"?!0:!1})});let Y=gs0(X.connectionString);return Y=us0(Y),new hs0({url:Y||":memory:"})}function qD6(Q){let X=ms0(Q);if(X.type==="postgres")return FD6(X);return VD6(X)}var Me=null;function Kv(){if(!Me)Me=qD6(Pe());return Me}class Te{apiKey;constructor(Q){this.apiKey=Q}async sendEmail({to:Q,from:X,subject:Y,html:J}){let G=await fetch("https://api.resend.com/emails",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({to:Q,from:X,subject:Y,html:J})});if(!G.ok)throw Error(`Failed to send email: ${G.statusText}`)}}class Ae{apiKey;constructor(Q){this.apiKey=Q}async sendEmail({to:Q,from:X,subject:Y,html:J}){let G=await fetch("https://api.sendgrid.com/v3/mail/send",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({personalizations:[{to:[{email:Q}]}],from:{email:X},subject:Y,content:[{type:"text/html",value:J}]})});if(!G.ok){let W=await G.text();throw Error(`Failed to send email via SendGrid: ${G.statusText} - ${W}`)}}}var zD6=(Q)=>{let X=new Te(Q.config.apiKey);return async({to:Y,subject:J,html:G})=>{await X.sendEmail({to:Y,from:Q.config.fromEmail,subject:J,html:G})}},UD6=(Q)=>{let X=new Ae(Q.config.apiKey);return async({to:Y,subject:J,html:G})=>{await X.sendEmail({to:Y,from:Q.config.fromEmail,subject:J,html:G})}},BD6={resend:zD6,sendgrid:UD6};function Hv(Q){let X=BD6[Q.provider];if(!X)throw Error(`Unknown email provider: ${Q.provider}`);return X(Q)}function Fv(Q,X){return Q.find((Y)=>Y.id===X)}var ds0=(Q,X)=>{let Y=Fv(X,Q.emailProviderId);if(!Y)throw Error(`Email provider with id '${Q.emailProviderId}' not found`);let J=Hv(Y);return{sendMagicLink:async({email:G,url:W})=>{await J({to:G,subject:"Magic Link",html:`<p>Click <a href="${W}">here</a> to login</p>`})}}};R3();import{createCipheriv as DD6,createDecipheriv as ND6,randomBytes as as0}from"crypto";var rs0="aes-256-gcm",jw=16,os0=16,ss0=32;class Cw{key;constructor(Q){if(Buffer.from(Q,"base64").length===ss0)this.key=Buffer.from(Q,"base64");else{let X=D0("crypto");this.key=X.createHash("sha256").update(Q).digest()}}async encrypt(Q){let X=as0(jw),Y=DD6(rs0,this.key,X),J=Y.update(Q,"utf8");J=Buffer.concat([J,Y.final()]);let G=Y.getAuthTag();return Buffer.concat([X,G,J]).toString("base64")}async decrypt(Q){let X=Buffer.from(Q,"base64"),Y=X.subarray(0,jw),J=X.subarray(jw,jw+os0),G=X.subarray(jw+os0),W=ND6(rs0,this.key,Y);W.setAuthTag(J);let Z=W.update(G);return Z=Buffer.concat([Z,W.final()]),Z.toString("utf8")}static generateKey(){return as0(ss0).toString("base64")}}U7();import{webcrypto as Xt0}from"crypto";var Qt0="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var PD6=128,k3,yz;function TD6(Q){if(!k3||k3.length<Q)k3=Buffer.allocUnsafe(Q*PD6),Xt0.getRandomValues(k3),yz=0;else if(yz+Q>k3.length)Xt0.getRandomValues(k3),yz=0;yz+=Q}function Yt0(Q=21){TD6(Q|=0);let X="";for(let Y=yz-Q;Y<yz;Y++)X+=Qt0[k3[Y]&63];return X}function lG(Q){return`${Q}_${Yt0()}`}var AD6=["connection_headers","oauth_config","configuration_scopes","metadata","tools","bindings"];class Iw{db;vault;constructor(Q,X){this.db=Q;this.vault=X}async create(Q){let X=Q.id??lG("conn"),Y=new Date().toISOString(),J=await this.findById(X);if(J){if(J.organization_id!==Q.organization_id)throw Error("Connection ID already exists");return this.update(X,Q)}let G=await this.serializeConnection({...Q,id:Q.id??X,status:"active",created_at:Y,updated_at:Y});await this.db.insertInto("connections").values(G).execute();let W=await this.findById(X);if(!W)throw Error(`Failed to create connection with id: ${X}`);return W}async findById(Q,X){let Y=this.db.selectFrom("connections").selectAll().where("id","=",Q);if(X)Y=Y.where("organization_id","=",X);let J=await Y.executeTakeFirst();return J?this.deserializeConnection(J):null}async list(Q){let X=await this.db.selectFrom("connections").selectAll().where("organization_id","=",Q).execute();return Promise.all(X.map((Y)=>this.deserializeConnection(Y)))}async update(Q,X){if(Object.keys(X).length===0){let G=await this.findById(Q);if(!G)throw Error("Connection not found");return G}let Y=await this.serializeConnection({...X,updated_at:new Date().toISOString()});await this.db.updateTable("connections").set(Y).where("id","=",Q).execute();let J=await this.findById(Q);if(!J)throw Error("Connection not found after update");return J}async delete(Q){await this.db.deleteFrom("connections").where("id","=",Q).execute()}async testConnection(Q,X){let Y=await this.findById(Q);if(!Y)throw Error("Connection not found");let J=Date.now();if(Y.connection_type==="STDIO")return{healthy:!0,latencyMs:Date.now()-J};if(!Y.connection_url)return{healthy:!1,latencyMs:Date.now()-J};try{let G=Y.connection_headers,W=await fetch(Y.connection_url,{method:"POST",headers:{"Content-Type":"application/json",...Y.connection_token&&{Authorization:`Bearer ${Y.connection_token}`},...G?.headers,...X},body:JSON.stringify({jsonrpc:"2.0",method:"ping",id:1})});return{healthy:W.ok||W.status===404,latencyMs:Date.now()-J}}catch{return{healthy:!1,latencyMs:Date.now()-J}}}async serializeConnection(Q){let X={};for(let[Y,J]of Object.entries(Q)){if(J===void 0)continue;if(Y==="connection_token"&&J)X[Y]=await this.vault.encrypt(J);else if(Y==="configuration_state"&&J){let G=JSON.stringify(J);X[Y]=await this.vault.encrypt(G)}else if(Y==="connection_headers"&&J){let G=J;if(S3(G)&&G.envVars){let W={};for(let[Z,$]of Object.entries(G.envVars))W[Z]=await this.vault.encrypt($);X[Y]=JSON.stringify({...G,envVars:W})}else X[Y]=JSON.stringify(G)}else if(AD6.includes(Y))X[Y]=J?JSON.stringify(J):null;else X[Y]=J}return X}async deserializeConnection(Q){let X=null;if(Q.connection_token)try{X=await this.vault.decrypt(Q.connection_token)}catch(W){console.error("Failed to decrypt connection token:",W)}let Y=null;if(Q.configuration_state)try{let W=await this.vault.decrypt(Q.configuration_state);Y=JSON.parse(W)}catch(W){console.error("Failed to decrypt configuration state:",W)}let J=null;if(Q.connection_headers)try{let W=JSON.parse(Q.connection_headers);if(S3(W)&&W.envVars){let Z={};for(let[$,K]of Object.entries(W.envVars))try{Z[$]=await this.vault.decrypt(K)}catch{Z[$]=K}J={...W,envVars:Z}}else J=W}catch(W){console.error("Failed to parse connection_headers:",W)}let G=(W)=>{if(W===null)return null;if(typeof W==="string")try{return JSON.parse(W)}catch{return null}return W};return{id:Q.id,organization_id:Q.organization_id,created_by:Q.created_by,title:Q.title,description:Q.description,icon:Q.icon,app_name:Q.app_name,app_id:Q.app_id,connection_type:Q.connection_type,connection_url:Q.connection_url,connection_token:X,connection_headers:J,oauth_config:G(Q.oauth_config),configuration_state:Y,configuration_scopes:G(Q.configuration_scopes),metadata:G(Q.metadata),tools:G(Q.tools),bindings:G(Q.bindings),status:Q.status,created_at:Q.created_at,updated_at:Q.updated_at}}}class Rw{db;constructor(Q){this.db=Q}async create(Q,X,Y){let J=lG("gw"),G=new Date().toISOString();if(Y.isDefault)return await this.db.transaction().execute(async(Z)=>{if(await Z.updateTable("gateways").set({is_default:0,updated_at:G,updated_by:X}).where("organization_id","=",Q).where("is_default","=",1).execute(),await Z.insertInto("gateways").values({id:J,organization_id:Q,title:Y.title,description:Y.description??null,tool_selection_strategy:Y.toolSelectionStrategy??"passthrough",tool_selection_mode:Y.toolSelectionMode??"inclusion",icon:Y.icon??null,status:Y.status??"active",is_default:1,created_at:G,updated_at:G,created_by:X,updated_by:null}).execute(),Y.connections.length>0)await Z.insertInto("gateway_connections").values(Y.connections.map((K)=>({id:lG("gwc"),gateway_id:J,connection_id:K.connectionId,selected_tools:K.selectedTools?JSON.stringify(K.selectedTools):null,selected_resources:K.selectedResources?JSON.stringify(K.selectedResources):null,selected_prompts:K.selectedPrompts?JSON.stringify(K.selectedPrompts):null,created_at:G}))).execute();let $=await this.findByIdInternal(Z,J);if(!$)throw Error(`Failed to create gateway with id: ${J}`);return $});if(await this.db.insertInto("gateways").values({id:J,organization_id:Q,title:Y.title,description:Y.description??null,tool_selection_strategy:Y.toolSelectionStrategy??"passthrough",tool_selection_mode:Y.toolSelectionMode??"inclusion",icon:Y.icon??null,status:Y.status??"active",is_default:0,created_at:G,updated_at:G,created_by:X,updated_by:null}).execute(),Y.connections.length>0)await this.db.insertInto("gateway_connections").values(Y.connections.map((Z)=>({id:lG("gwc"),gateway_id:J,connection_id:Z.connectionId,selected_tools:Z.selectedTools?JSON.stringify(Z.selectedTools):null,selected_resources:Z.selectedResources?JSON.stringify(Z.selectedResources):null,selected_prompts:Z.selectedPrompts?JSON.stringify(Z.selectedPrompts):null,created_at:G}))).execute();let W=await this.findById(J);if(!W)throw Error(`Failed to create gateway with id: ${J}`);return W}async findById(Q){return this.findByIdInternal(this.db,Q)}async findByIdInternal(Q,X){let Y=await Q.selectFrom("gateways").selectAll().where("id","=",X).executeTakeFirst();if(!Y)return null;let J=await Q.selectFrom("gateway_connections").selectAll().where("gateway_id","=",X).execute();return this.deserializeGatewayWithConnections(Y,J)}async list(Q){let X=await this.db.selectFrom("gateways").selectAll().where("organization_id","=",Q).execute(),Y=X.map((W)=>W.id);if(Y.length===0)return[];let J=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","in",Y).execute(),G=new Map;for(let W of J){let Z=G.get(W.gateway_id)??[];Z.push(W),G.set(W.gateway_id,Z)}return X.map((W)=>this.deserializeGatewayWithConnections(W,G.get(W.id)??[]))}async listByConnectionId(Q,X){let J=(await this.db.selectFrom("gateway_connections").select("gateway_id").where("connection_id","=",X).execute()).map((K)=>K.gateway_id);if(J.length===0)return[];let G=await this.db.selectFrom("gateways").selectAll().where("id","in",J).where("organization_id","=",Q).execute();if(G.length===0)return[];let W=G.map((K)=>K.id),Z=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","in",W).execute(),$=new Map;for(let K of Z){let H=$.get(K.gateway_id)??[];H.push(K),$.set(K.gateway_id,H)}return G.map((K)=>this.deserializeGatewayWithConnections(K,$.get(K.id)??[]))}async update(Q,X,Y){let J=new Date().toISOString(),G={updated_at:J,updated_by:X};if(Y.title!==void 0)G.title=Y.title;if(Y.description!==void 0)G.description=Y.description;if(Y.toolSelectionStrategy!==void 0)G.tool_selection_strategy=Y.toolSelectionStrategy;if(Y.toolSelectionMode!==void 0)G.tool_selection_mode=Y.toolSelectionMode;if(Y.icon!==void 0)G.icon=Y.icon;if(Y.status!==void 0)G.status=Y.status;if(Y.isDefault===!1)G.is_default=0;if(Y.isDefault===!0)G.is_default=1;if(Y.isDefault===!0){let Z=await this.findById(Q);if(!Z)throw Error(`Gateway not found: ${Q}`);await this.db.transaction().execute(async($)=>{if(await $.updateTable("gateways").set({is_default:0,updated_at:J,updated_by:X}).where("organization_id","=",Z.organizationId).where("is_default","=",1).execute(),await $.updateTable("gateways").set(G).where("id","=",Q).execute(),Y.connections!==void 0){if(await $.deleteFrom("gateway_connections").where("gateway_id","=",Q).execute(),Y.connections.length>0)await $.insertInto("gateway_connections").values(Y.connections.map((K)=>({id:lG("gwc"),gateway_id:Q,connection_id:K.connectionId,selected_tools:K.selectedTools?JSON.stringify(K.selectedTools):null,selected_resources:K.selectedResources?JSON.stringify(K.selectedResources):null,selected_prompts:K.selectedPrompts?JSON.stringify(K.selectedPrompts):null,created_at:J}))).execute()}})}else if(await this.db.updateTable("gateways").set(G).where("id","=",Q).execute(),Y.connections!==void 0){if(await this.db.deleteFrom("gateway_connections").where("gateway_id","=",Q).execute(),Y.connections.length>0)await this.db.insertInto("gateway_connections").values(Y.connections.map((Z)=>({id:lG("gwc"),gateway_id:Q,connection_id:Z.connectionId,selected_tools:Z.selectedTools?JSON.stringify(Z.selectedTools):null,selected_resources:Z.selectedResources?JSON.stringify(Z.selectedResources):null,selected_prompts:Z.selectedPrompts?JSON.stringify(Z.selectedPrompts):null,created_at:J}))).execute()}let W=await this.findById(Q);if(!W)throw Error("Gateway not found after update");return W}async delete(Q){await this.db.deleteFrom("gateways").where("id","=",Q).execute()}async getDefaultByOrgId(Q){let X=await this.db.selectFrom("gateways").selectAll().where("organization_id","=",Q).where("is_default","=",1).executeTakeFirst();if(!X)return null;let Y=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","=",X.id).execute();return this.deserializeGatewayWithConnections(X,Y)}async getDefaultByOrgSlug(Q){let X=await this.db.selectFrom("organization").select("id").where("slug","=",Q).executeTakeFirst();if(!X)return null;return this.getDefaultByOrgId(X.id)}async setDefault(Q,X){let Y=await this.findById(Q);if(!Y)throw Error(`Gateway not found: ${Q}`);let J=new Date().toISOString();await this.db.transaction().execute(async(W)=>{await W.updateTable("gateways").set({is_default:0,updated_at:J,updated_by:X}).where("organization_id","=",Y.organizationId).where("is_default","=",1).execute(),await W.updateTable("gateways").set({is_default:1,updated_at:J,updated_by:X}).where("id","=",Q).execute()});let G=await this.findById(Q);if(!G)throw Error("Gateway not found after setting default");return G}deserializeGatewayWithConnections(Q,X){return{...this.deserializeGateway(Q),connections:X.map((J)=>({connectionId:J.connection_id,selectedTools:this.parseJson(J.selected_tools),selectedResources:this.parseJson(J.selected_resources),selectedPrompts:this.parseJson(J.selected_prompts)}))}}deserializeGateway(Q){return{id:Q.id,organizationId:Q.organization_id,title:Q.title,description:Q.description,toolSelectionStrategy:this.parseToolSelectionStrategy(Q.tool_selection_strategy),toolSelectionMode:this.parseToolSelectionMode(Q.tool_selection_mode),icon:Q.icon,status:Q.status,isDefault:Q.is_default===1,createdAt:Q.created_at,updatedAt:Q.updated_at,createdBy:Q.created_by,updatedBy:Q.updated_by}}parseToolSelectionStrategy(Q){if(Q==="smart_tool_selection")return"smart_tool_selection";if(Q==="code_execution")return"code_execution";return"passthrough"}parseToolSelectionMode(Q){if(Q==="exclusion")return"exclusion";return"inclusion"}parseJson(Q){if(Q===null)return null;if(typeof Q==="string")try{return JSON.parse(Q)}catch{return null}return Q}}e_();W1();function VR6(){return[{permissions:{self:["*"]},getTools:async()=>{let{ALL_TOOLS:Q}=await Promise.resolve().then(() => (_40(),HX1));return Q.map((X)=>{return{name:X.name,inputSchema:N.toJSONSchema(X.inputSchema,{unrepresentable:"any"}),outputSchema:X.outputSchema?N.toJSONSchema(X.outputSchema,{unrepresentable:"any"}):void 0,description:X.description}})},data:is0(process.env.BASE_URL||"http://localhost:3000")},{data:ns0()}]}async function FX1(Q,X){try{let Y=Kv(),J=new Cw(process.env.ENCRYPTION_KEY||""),G=new Iw(Y.db,J),W=new Rw(Y.db),Z=VR6(),$=[];await Promise.all(Z.map(async(K)=>{let H=null;if(K.permissions)H=(await v7.api.createApiKey({body:{name:`${K.data.app_name??crypto.randomUUID()}-mcp`,userId:X,permissions:K.permissions,rateLimitEnabled:!1,metadata:{organization:{id:Q},purpose:"default-org-connections"}}}))?.key;let F=await K.getTools?.()??await zU({id:"pending",title:K.data.title,connection_type:K.data.connection_type,connection_url:K.data.connection_url,connection_token:K.data.connection_token,connection_headers:K.data.connection_headers}).catch(()=>null),V=K.data.id?`${Q}_${K.data.id}`:void 0,q=await G.create({...K.data,id:V,tools:F,organization_id:Q,created_by:X,connection_token:K.data.connection_token??H});$.push(q.id)})),await W.create(Q,X,{title:"Default Hub",description:"Auto-created Hub for organization",toolSelectionStrategy:"passthrough",toolSelectionMode:"exclusion",status:"active",isDefault:!0,connections:$.map((K)=>({connectionId:K}))})}catch(Y){console.error("Error creating default MCP connections:",Y)}}var y40=["owner","admin","user"],VX1=["owner","admin"];var qR6=(Q)=>{return{defaultSSO:[{domain:Q.domain,providerId:Q.providerId,oidcConfig:{issuer:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/v2.0`,pkce:!0,clientId:Q.MS_CLIENT_ID,clientSecret:Q.MS_CLIENT_SECRET,discoveryEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/v2.0/.well-known/openid-configuration`,authorizationEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/oauth2/v2.0/authorize`,tokenEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/oauth2/v2.0/token`,jwksEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/discovery/v2.0/keys`,userInfoEndpoint:"https://graph.microsoft.com/oidc/userinfo",tokenEndpointAuthentication:"client_secret_post",scopes:Q.scopes,mapping:{id:"sub",email:"email",emailVerified:"email_verified",name:"name",image:"picture",extraFields:{emailVerified:"email_verified"}}}}]}},qX1=(Q)=>{if(Q.providerId==="microsoft")return qR6(Q);throw Error(`Unsupported provider: ${Q.providerId}`)};function zR6(Q){return Q.toLowerCase().trim().replace(/[^a-z0-9\s_-]+/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var zX1=["labs","hub","studio","workspace","systems","core","cloud","works"],UX1=["capybara","guarana","deco","samba","feijoada","capoeira","carnival"];function UR6(){let Q=Math.floor(Math.random()*UX1.length),X=Math.floor(Math.random()*zX1.length),Y=UX1[Q]??"deco",J=zX1[X]??"studio";return`${Y}-${J}`}var BR6=Object.values(vD()).map((Q)=>Q.map((X)=>X.name)).flat(),DR6={...bk,self:["*",...BR6]},zy=mG(DR6),NR6=zy.newRole({self:["*"],...$w.statements}),OR6=zy.newRole({self:["*"],...$w.statements}),LR6=zy.newRole({self:["*"],...$w.statements}),BX1=Object.values(vD()).map((Q)=>Q.map((X)=>`self:${X.name}`)).flat(),a8=ok.auth,DX1=void 0;if(a8.inviteEmailProviderId&&a8.emailProviders&&a8.emailProviders.length>0){let Q=Fv(a8.emailProviders,a8.inviteEmailProviderId);if(Q){let X=Hv(Q);DX1=async(Y)=>{let J=Y.inviter.user?.name||Y.inviter.user?.email,G=`${process.env.BASE_URL||"http://localhost:3000"}/auth/accept-invitation?invitationId=${Y.invitation.id}`;await X({to:Y.email,subject:`Invitation to join ${Y.organization.name}`,html:`
1036
1036
  <h2>You've been invited!</h2>
1037
1037
  <p>${J} has invited you to join <strong>${Y.organization.name}</strong>.</p>
1038
1038
  <p><a href="${G}">Click here to accept the invitation</a></p>
@@ -1041,7 +1041,7 @@ ${Q.stack}`;return X}if(typeof Q==="object"&&Q!==null){let X=Q,Y="";if(typeof X.
1041
1041
  ${X.stack}`;return Y}try{let G=JSON.stringify(X,null,2);if(G!=="{}"&&G.length<1000){if(typeof X.stack==="string"&&X.stack&&X.stack.length<2000)return`${G}
1042
1042
 
1043
1043
  Stack trace:
1044
- ${X.stack}`;return G}}catch{}if(typeof X.toString==="function")try{let G=X.toString();if(G!=="[object Object]")return G}catch{}let J=Object.keys(X);if(J.length>0)return`Object with keys: ${J.join(", ")}`;return"[object Object]"}if(typeof Q==="string")return Q;if(typeof Q==="number"||typeof Q==="boolean")return String(Q);if(typeof Q==="function")return`[Function: ${Q.name||"anon"}]`;if(typeof Q==="symbol")return Q.toString();if(typeof Q==="bigint")return Q.toString();try{return String(Q)}catch{return"Unknown value (could not convert to string)"}}function RU(Q,X){switch(typeof X){case"string":return Q.newString(X);case"number":return Q.newNumber(X);case"boolean":return X?Q.true:Q.false;case"undefined":return Q.undefined;case"object":{if(X===null)return Q.null;if(Array.isArray(X)){let J=Q.newArray();return X.forEach((G,W)=>{let Z=RU(Q,G);try{Q.setProp(J,String(W),Z)}finally{Z.dispose?.()}}),J}let Y=Q.newObject();for(let[J,G]of Object.entries(X)){let W=RU(Q,G);try{Q.setProp(Y,J,W)}finally{W.dispose?.()}}return Y}case"function":{let Y=`__hostFn_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return Q.newFunction(Y,(...G)=>{try{let W=G.map(($)=>Q.dump($)),Z=X(...W);if(Z&&typeof Z.then==="function"){let $=Q.newPromise();return Z.then((K)=>{try{let H=RU(Q,K);$.resolve(H),H.dispose(),Q.runtime.executePendingJobs()}catch(H){let F=IU(H),V=Q.newString(`Promise resolution error: ${F}`);$.reject(V),V.dispose(),Q.runtime.executePendingJobs()}}).catch((K)=>{let H=IU(K),F=Q.newString(`Promise rejection: ${H}`);$.reject(F),F.dispose(),Q.runtime.executePendingJobs()}),$.handle}return RU(Q,Z)}catch(W){let Z=IU(W);return Q.newString(`HostFunctionError: ${Z}`)}finally{G.forEach((W)=>W.dispose())}})}case"bigint":return Q.newString(X.toString());case"symbol":return Q.newString(X.toString());default:try{return Q.newString(String(X))}catch{return Q.undefined}}}var qS6=(Q)=>new Promise((X)=>setTimeout(X,Q));function fY1(Q){let X=Q.runtime.executePendingJobs(100);try{if("unwrap"in X&&typeof X.unwrap==="function")X.unwrap()}finally{if("dispose"in X&&typeof X.dispose==="function")X.dispose()}}async function bY1(Q,X,Y){let J=Date.now(),G=Q.resolvePromise(X);while(!0){fY1(Q);let W=await Promise.race([G,qS6(0).then(()=>null)]);if(W!==null)return W;if(Date.now()-J>Y)throw Error(`Timed out after ${Y}ms while awaiting a QuickJS promise`)}}async function F80({tools:Q,code:X,timeoutMs:Y}){let Z=[];try{let J=await yY1({memoryLimitBytes:33554432,stackSizeBytes:524288});const G=ny(Z,J.newContext({interruptAfterMs:Y}),0);const W=ny(Z,JY1(G),0);try{let F=G.evalCode(X,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult(F),q=RU(G,Q);G.setProp(G.global,"tools",q);let U=G.runtime.hasPendingJob()?G.unwrapResult(await bY1(G,V,Y)):V;if(U!==V)V.dispose();let D=G.getProp(U,"default"),B=G.typeof(D);if(B!=="function")return{error:`Code must export default a function (tools). Got ${B}. Example: export default async (tools) => { /* ... */ }`,consoleLogs:W.logs};let L=G.callFunction(D,G.undefined,q),M=G.unwrapResult(L),C=await bY1(G,M,Y),E=G.unwrapResult(C);if(G.runtime.hasPendingJob())fY1(G);return{returnValue:G.dump(E),consoleLogs:W.logs}}catch(F){return console.log(F),{error:IU(F),consoleLogs:W.logs}}}catch($){var K=$,H=1}finally{r80(Z,K,H)}}function zS6(Q){return Q.toLowerCase().split(/[\s_\-./]+/).filter((X)=>X.length>=2)}function US6(Q,X){let Y=0,J=X.name.toLowerCase(),G=(X.description??"").toLowerCase(),W=X._meta.connectionTitle.toLowerCase();for(let Z of Q){if(J===Z)Y+=10;else if(J.includes(Z))Y+=3;if(G.includes(Z))Y+=2;if(W.includes(Z))Y+=1}return Y}function BS6(Q,X,Y){let J=zS6(Q);if(J.length===0)return X.slice(0,Y);return X.map((G)=>({tool:G,score:US6(J,G)})).filter((G)=>G.score>0).sort((G,W)=>W.score-G.score).slice(0,Y).map((G)=>G.tool)}function V80(Q){return{content:[{type:"text",text:JSON.stringify(Q,null,2)}]}}function KP(Q){return{content:[{type:"text",text:JSON.stringify(Q,null,2)}],isError:!0}}function hY1(Q){let X=N.object({query:N.string().describe("Natural language search query (e.g., 'send email', 'create order')"),limit:N.number().default(10).describe("Maximum results to return (default: 10)")});return{tool:{name:"GATEWAY_SEARCH_TOOLS",description:`Search for available tools by name or description. Returns tool names and brief descriptions without full schemas.${Q.categories.length>0?` Available categories: ${Q.categories.join(", ")}.`:""} Total tools: ${Q.tools.length}.`,inputSchema:N.toJSONSchema(X)},handler:async(J)=>{let G=X.safeParse(J);if(!G.success)return KP({error:G.error.flatten()});let W=BS6(G.data.query,Q.tools,G.data.limit);return V80({query:G.data.query,results:W.map((Z)=>({name:Z.name,description:Z.description,connection:Z._meta.connectionTitle})),totalAvailable:Q.tools.length})}}}function xY1(Q){let X=N.object({tools:N.array(N.string()).min(1).describe("Array of tool names to get detailed schemas for")});return{tool:{name:"GATEWAY_DESCRIBE_TOOLS",description:"Get detailed schemas for specific tools. Call after searching to get full input/output schemas.",inputSchema:N.toJSONSchema(X)},handler:async(Y)=>{let J=X.safeParse(Y);if(!J.success)return KP({error:J.error.flatten()});let G=new Map(Q.tools.map((Z)=>[Z.name,Z])),W=J.data.tools.map((Z)=>G.get(Z)).filter((Z)=>Z!==void 0);return V80({tools:W.map((Z)=>({name:Z.name,description:Z.description,connection:Z._meta.connectionTitle,inputSchema:Z.inputSchema,outputSchema:Z.outputSchema})),notFound:J.data.tools.filter((Z)=>!G.has(Z))})}}}function DS6(Q){let X=Q.tools.map((G)=>G.name),Y=new Map(Q.tools.map((G)=>[G.name,G])),J=N.object({name:N.enum(X).describe("The name of the tool to execute"),arguments:N.record(N.string(),N.unknown()).default({}).describe("Arguments to pass to the tool")});return{tool:{name:"GATEWAY_CALL_TOOL",description:"Execute a tool by name. Use GATEWAY_DESCRIBE_TOOLS first to understand the input schema.",inputSchema:N.toJSONSchema(J)},handler:async(G)=>{let W=J.safeParse(G);if(!W.success)return KP({error:W.error.flatten()});let{name:Z,arguments:$}=W.data;if(!Y.has(Z))return{content:[{type:"text",text:`Tool not found: ${Z}. Use GATEWAY_SEARCH_TOOLS to find available tools.`}],isError:!0};return Q.callTool(Z,$)}}}function NS6(Q){let X=N.object({code:N.string().min(1).describe("JavaScript code to execute. It runs as an async function body; you can use top-level `return` and `await`."),timeoutMs:N.number().default(3000).describe("Max execution time in milliseconds (default: 3000).")});return{tool:{name:"GATEWAY_RUN_CODE",description:'Run JavaScript code in a sandbox. Code must be an ES module that `export default`s an async function that receives (tools) as its first parameter. Use GATEWAY_DESCRIBE_TOOLS to understand the input/output schemas for a tool before calling it. Use `await tools.toolName(args)` or `await tools["tool-name"](args)` to call tools.',inputSchema:N.toJSONSchema(X)},handler:async(Y)=>{let J=X.safeParse(Y);if(!J.success)return KP({error:J.error.flatten()});let G=Object.fromEntries(Q.tools.map((Z)=>[Z.name,async($)=>Q.callTool(Z.name,$??{})])),W=await F80({...J.data,tools:G});if(W.error)return KP(W);return V80(W)}}}function gY1(Q){let X=new Map(Q.map((J)=>[J.tool.name,J.handler])),Y=Q.map((J)=>J.tool.name);return{tools:Q.map((J)=>J.tool),callTool:async(J,G)=>{let W=X.get(J);if(!W)return{content:[{type:"text",text:`Unknown meta-tool: ${J}. Available: ${Y.join(", ")}`}],isError:!0};return W(G)}}}var OS6=(Q)=>({tools:Q.tools,callTool:(X,Y)=>Q.callTool(X,Y)}),LS6=(Q)=>gY1([hY1(Q),xY1(Q),NS6(Q)]),wS6=(Q)=>gY1([hY1(Q),xY1(Q),DS6(Q)]);function uY1(Q){switch(Q){case"smart_tool_selection":return wS6;case"code_execution":return LS6;case"passthrough":default:return OS6}}class Ey{proxies;options;cache;constructor(Q,X){this.proxies=Q;this.options=X;this.cache=QW(()=>this.loadTools())}async loadTools(){let Q=await this.proxies.mapSettled(async(K,H)=>{try{let V=(await K.proxy.client.listTools()).tools;if(this.options.selectionMode==="exclusion"){if(K.selectedTools&&K.selectedTools.length>0){let q=new Set(K.selectedTools);V=V.filter((U)=>!q.has(U.name))}}else if(K.selectedTools&&K.selectedTools.length>0){let q=new Set(K.selectedTools);V=V.filter((U)=>q.has(U.name))}return{connectionId:H,connectionTitle:K.connection.title,tools:V}}catch(F){return console.error(`[gateway] Failed to list tools for connection ${H}:`,F),null}}),X=new Set,Y=[],J=new Map,G=new Set;for(let K of Q){if(K.status!=="fulfilled"||!K.value)continue;let{connectionId:H,connectionTitle:F,tools:V}=K.value;G.add(F);for(let q of V){if(X.has(q.name))continue;X.add(q.name),Y.push({...q,_meta:{connectionId:H,connectionTitle:F}}),J.set(q.name,{connectionId:H,originalName:q.name})}}let W=async(K,H)=>{let F=J.get(K);if(!F)return{content:[{type:"text",text:`Tool not found: ${K}`}],isError:!0};let V=this.proxies.get(F.connectionId);if(!V)return{content:[{type:"text",text:`Connection not found for tool: ${K}`}],isError:!0};return await V.proxy.client.callTool({name:F.originalName,arguments:H})},$=uY1(this.options.strategy)({tools:Y,callTool:W,categories:Array.from(G).sort()});return{tools:Y,mappings:J,strategyResult:$}}async list(){return{tools:(await this.cache).strategyResult.tools}}async call(Q){return(await this.cache).strategyResult.callTool(Q.name,Q.arguments??{})}async callStreamable(Q,X){let Y=await this.cache,J=Y.mappings.get(Q);if(J){let W=this.proxies.get(J.connectionId);if(W)return W.proxy.callStreamableTool(J.originalName,X)}let G=await Y.strategyResult.callTool(Q,X);return new Response(JSON.stringify(G),{headers:{"Content-Type":"application/json"}})}}function MS6(Q,X){if(Q===X)return!0;if(!X.includes("*"))return!1;let Y=X.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"<<<DOUBLE_STAR>>>").replace(/\*/g,"[^/]*").replace(/<<<DOUBLE_STAR>>>/g,".*");Y=`^${Y}$`;try{return new RegExp(Y).test(Q)}catch{return!1}}function mY1(Q,X){return X.some((Y)=>MS6(Q,Y))}class jy{proxies;options;cache;constructor(Q,X){this.proxies=Q;this.options=X;this.cache=QW(()=>this.loadResources())}async loadResources(){let Q=await this.proxies.mapSettled(async(G,W)=>{try{let $=(await G.proxy.client.listResources()).resources;if(this.options.selectionMode==="exclusion"){if(G.selectedResources&&G.selectedResources.length>0)$=$.filter((K)=>!mY1(K.uri,G.selectedResources))}else if(!G.selectedResources||G.selectedResources.length===0)$=[];else $=$.filter((K)=>mY1(K.uri,G.selectedResources));return{connectionId:W,resources:$}}catch(Z){return console.error(`[gateway] Failed to list resources for connection ${W}:`,Z),{connectionId:W,resources:[]}}}),X=new Set,Y=[],J=new Map;for(let G of Q){if(G.status!=="fulfilled")continue;let{connectionId:W,resources:Z}=G.value;for(let $ of Z){if(X.has($.uri))continue;X.add($.uri),Y.push($),J.set($.uri,W)}}return{resources:Y,mappings:J}}async list(){return{resources:(await this.cache).resources}}async read(Q){let Y=(await this.cache).mappings.get(Q.uri);if(!Y)throw Error(`Resource not found: ${Q.uri}`);let J=this.proxies.get(Y);if(!J)throw Error(`Connection not found for resource: ${Q.uri}`);return await J.proxy.client.readResource(Q)}}class Cy{proxies;cache;constructor(Q){this.proxies=Q;this.cache=QW(()=>this.loadResourceTemplates())}async loadResourceTemplates(){let Q=await this.proxies.mapSettled(async(Y,J)=>{try{let G=await Y.proxy.client.listResourceTemplates();return{connectionId:J,templates:G.resourceTemplates}}catch(G){return console.error(`[gateway] Failed to list resource templates for connection ${J}:`,G),{connectionId:J,templates:[]}}}),X=[];for(let Y of Q){if(Y.status!=="fulfilled")continue;let{templates:J}=Y.value;for(let G of J)X.push(G)}return{templates:X}}async list(){return{resourceTemplates:(await this.cache).templates}}}class Iy{proxies;options;cache;constructor(Q,X){this.proxies=Q;this.options=X;this.cache=QW(()=>this.loadPrompts())}async loadPrompts(){let Q=await this.proxies.mapSettled(async(G,W)=>{try{let $=(await G.proxy.client.listPrompts()).prompts;if(this.options.selectionMode==="exclusion"){if(G.selectedPrompts&&G.selectedPrompts.length>0){let K=new Set(G.selectedPrompts);$=$.filter((H)=>!K.has(H.name))}}else if(!G.selectedPrompts||G.selectedPrompts.length===0)$=[];else{let K=new Set(G.selectedPrompts);$=$.filter((H)=>K.has(H.name))}return{connectionId:W,prompts:$}}catch(Z){return console.error(`[PromptGateway] Failed to list prompts for connection ${W}:`,Z),{connectionId:W,prompts:[]}}}),X=new Set,Y=[],J=new Map;for(let G of Q){if(G.status!=="fulfilled")continue;let{connectionId:W,prompts:Z}=G.value;for(let $ of Z){if(X.has($.name))continue;X.add($.name),Y.push($),J.set($.name,W)}}return{prompts:Y,mappings:J}}async list(){return{prompts:(await this.cache).prompts}}async get(Q){let Y=(await this.cache).mappings.get(Q.name);if(!Y)throw Error(`Prompt not found: ${Q.name}`);let J=this.proxies.get(Y);if(!J)throw Error(`Connection not found for prompt: ${Q.name}`);return await J.proxy.client.getPrompt(Q)}}var lY1=new d9;async function PS6(Q,X){let Y=await ZP.create(Q.connections,X),J=new Ey(Y,{selectionMode:Q.toolSelectionMode,strategy:Q.toolSelectionStrategy}),G=new jy(Y,{selectionMode:Q.toolSelectionMode}),W=new Cy(Y),Z=new Iy(Y,{selectionMode:Q.toolSelectionMode});return{client:{listTools:J.list.bind(J),callTool:J.call.bind(J),listResources:G.list.bind(G),readResource:G.read.bind(G),listResourceTemplates:W.list.bind(W),listPrompts:Z.list.bind(Z),getPrompt:Z.get.bind(Z)},callStreamableTool:J.callStreamable.bind(J)}}async function TS6(Q,X){let Y;if(Q.toolSelectionMode==="exclusion"){let W=(await X.storage.connections.list(Q.organizationId)).filter(($)=>$.status==="active"),Z=new Map;for(let $ of Q.connections)Z.set($.connectionId,{selectedTools:$.selectedTools,selectedResources:$.selectedResources,selectedPrompts:$.selectedPrompts});Y=[];for(let $ of W){let K=Z.get($.id);if(K===void 0)Y.push({connection:$,selectedTools:null,selectedResources:null,selectedPrompts:null});else if((K.selectedTools===null||K.selectedTools.length===0)&&(K.selectedResources===null||K.selectedResources.length===0)&&(K.selectedPrompts===null||K.selectedPrompts.length===0));else Y.push({connection:$,selectedTools:K.selectedTools,selectedResources:K.selectedResources,selectedPrompts:K.selectedPrompts})}}else{let G=Q.connections.map((Z)=>Z.connectionId),W=[];for(let Z of G){let $=await X.storage.connections.findById(Z);if($&&$.status==="active")W.push($)}Y=W.map((Z)=>{let $=Q.connections.find((K)=>K.connectionId===Z.id);return{connection:Z,selectedTools:$?.selectedTools??null,selectedResources:$?.selectedResources??null,selectedPrompts:$?.selectedPrompts??null}})}let J={connections:Y,toolSelectionMode:Q.toolSelectionMode,toolSelectionStrategy:Q.toolSelectionStrategy};return PS6(J,X)}lY1.all("/gateway/:gatewayId?",async(Q)=>{let X=Q.req.param("gatewayId"),Y=Q.get("meshContext");try{let J=null;if(X)J=await Y.storage.gateways.findById(X);else{let K=Q.req.header("x-org-id"),H=Q.req.header("x-org-slug");if(K)J=await Y.storage.gateways.getDefaultByOrgId(K);else if(H)J=await Y.storage.gateways.getDefaultByOrgSlug(H);else return Q.json({error:"Gateway ID required, or provide x-org-id or x-org-slug header for default gateway"},400)}if(!J){if(X)return Q.json({error:`Gateway not found: ${X}`},404);return Q.json({error:"No default gateway configured for this organization"},404)}if(Y.gatewayId=J.id,J.status!=="active")return Q.json({error:`Gateway is inactive: ${J.id}`},503);let G=await Y.db.selectFrom("organization").select(["id","slug","name"]).where("id","=",J.organizationId).executeTakeFirst();if(G)Y.organization={id:G.id,slug:G.slug,name:G.name};let W=await TS6(J,Y),Z=new p3({name:`mcp-gateway-${J.title}`,version:"1.0.0"},{capabilities:{tools:{},resources:{},prompts:{}}}),$=new c3({enableJsonResponse:Q.req.header("Accept")?.includes("application/json")??!1});return await Z.connect($),Z.server.setRequestHandler(k$,async(K)=>{return W.client.listTools()}),Z.server.setRequestHandler(rG,async(K)=>{return await W.client.callTool(K.params)}),Z.server.setRequestHandler(j$,async()=>{return W.client.listResources()}),Z.server.setRequestHandler(I$,async(K)=>{return W.client.readResource(K.params)}),Z.server.setRequestHandler(C$,async()=>{return W.client.listResourceTemplates()}),Z.server.setRequestHandler(R$,async()=>{return W.client.listPrompts()}),Z.server.setRequestHandler(S$,async(K)=>{return W.client.getPrompt(K.params)}),await $.handleRequest(Q.req.raw)}catch(J){let G=J;return console.error("[gateway] Error handling gateway request:",G),Q.json({error:"Internal server error",message:G.message},500)}});var dY1=lY1;_40();var pY1=new d9;pY1.all("/",async(Q)=>{return v40(Q.get("meshContext")).fetch(Q.req.raw)});var cY1=pY1;i60();GU();RM();_9();var wJ1="vercel.ai.error",AS6=Symbol.for(wJ1),nY1,iY1,P1=class Q extends(iY1=Error,nY1=AS6,iY1){constructor({name:X,message:Y,cause:J}){super(Y);this[nY1]=!0,this.name=X,this.cause=J}static isInstance(X){return Q.hasMarker(X,wJ1)}static hasMarker(X,Y){let J=Symbol.for(Y);return X!=null&&typeof X==="object"&&J in X&&typeof X[J]==="boolean"&&X[J]===!0}},MJ1="AI_APICallError",PJ1=`vercel.ai.error.${MJ1}`,ES6=Symbol.for(PJ1),aY1,rY1,r8=class extends(rY1=P1,aY1=ES6,rY1){constructor({message:Q,url:X,requestBodyValues:Y,statusCode:J,responseHeaders:G,responseBody:W,cause:Z,isRetryable:$=J!=null&&(J===408||J===409||J===429||J>=500),data:K}){super({name:MJ1,message:Q,cause:Z});this[aY1]=!0,this.url=X,this.requestBodyValues=Y,this.statusCode=J,this.responseHeaders=G,this.responseBody=W,this.isRetryable=$,this.data=K}static isInstance(Q){return P1.hasMarker(Q,PJ1)}},TJ1="AI_EmptyResponseBodyError",AJ1=`vercel.ai.error.${TJ1}`,jS6=Symbol.for(AJ1),oY1,sY1,EJ1=class extends(sY1=P1,oY1=jS6,sY1){constructor({message:Q="Empty response body"}={}){super({name:TJ1,message:Q});this[oY1]=!0}static isInstance(Q){return P1.hasMarker(Q,AJ1)}};function R5(Q){if(Q==null)return"unknown error";if(typeof Q==="string")return Q;if(Q instanceof Error)return Q.message;return JSON.stringify(Q)}var jJ1="AI_InvalidArgumentError",CJ1=`vercel.ai.error.${jJ1}`,CS6=Symbol.for(CJ1),tY1,eY1,IJ1=class extends(eY1=P1,tY1=CS6,eY1){constructor({message:Q,cause:X,argument:Y}){super({name:jJ1,message:Q,cause:X});this[tY1]=!0,this.argument=Y}static isInstance(Q){return P1.hasMarker(Q,CJ1)}},RJ1="AI_InvalidPromptError",SJ1=`vercel.ai.error.${RJ1}`,IS6=Symbol.for(SJ1),QJ1,XJ1,s3=class extends(XJ1=P1,QJ1=IS6,XJ1){constructor({prompt:Q,message:X,cause:Y}){super({name:RJ1,message:`Invalid prompt: ${X}`,cause:Y});this[QJ1]=!0,this.prompt=Q}static isInstance(Q){return P1.hasMarker(Q,SJ1)}},kJ1="AI_InvalidResponseDataError",vJ1=`vercel.ai.error.${kJ1}`,RS6=Symbol.for(vJ1),YJ1,JJ1,Ju4=class extends(JJ1=P1,YJ1=RS6,JJ1){constructor({data:Q,message:X=`Invalid response data: ${JSON.stringify(Q)}.`}){super({name:kJ1,message:X});this[YJ1]=!0,this.data=Q}static isInstance(Q){return P1.hasMarker(Q,vJ1)}},_J1="AI_JSONParseError",yJ1=`vercel.ai.error.${_J1}`,SS6=Symbol.for(yJ1),GJ1,WJ1,HP=class extends(WJ1=P1,GJ1=SS6,WJ1){constructor({text:Q,cause:X}){super({name:_J1,message:`JSON parsing failed: Text: ${Q}.
1044
+ ${X.stack}`;return G}}catch{}if(typeof X.toString==="function")try{let G=X.toString();if(G!=="[object Object]")return G}catch{}let J=Object.keys(X);if(J.length>0)return`Object with keys: ${J.join(", ")}`;return"[object Object]"}if(typeof Q==="string")return Q;if(typeof Q==="number"||typeof Q==="boolean")return String(Q);if(typeof Q==="function")return`[Function: ${Q.name||"anon"}]`;if(typeof Q==="symbol")return Q.toString();if(typeof Q==="bigint")return Q.toString();try{return String(Q)}catch{return"Unknown value (could not convert to string)"}}function RU(Q,X){switch(typeof X){case"string":return Q.newString(X);case"number":return Q.newNumber(X);case"boolean":return X?Q.true:Q.false;case"undefined":return Q.undefined;case"object":{if(X===null)return Q.null;if(Array.isArray(X)){let J=Q.newArray();return X.forEach((G,W)=>{let Z=RU(Q,G);try{Q.setProp(J,String(W),Z)}finally{Z.dispose?.()}}),J}let Y=Q.newObject();for(let[J,G]of Object.entries(X)){let W=RU(Q,G);try{Q.setProp(Y,J,W)}finally{W.dispose?.()}}return Y}case"function":{let Y=`__hostFn_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return Q.newFunction(Y,(...G)=>{try{let W=G.map(($)=>Q.dump($)),Z=X(...W);if(Z&&typeof Z.then==="function"){let $=Q.newPromise();return Z.then((K)=>{try{let H=RU(Q,K);$.resolve(H),H.dispose(),Q.runtime.executePendingJobs()}catch(H){let F=IU(H),V=Q.newString(`Promise resolution error: ${F}`);$.reject(V),V.dispose(),Q.runtime.executePendingJobs()}}).catch((K)=>{let H=IU(K),F=Q.newString(`Promise rejection: ${H}`);$.reject(F),F.dispose(),Q.runtime.executePendingJobs()}),$.handle}return RU(Q,Z)}catch(W){let Z=IU(W);return Q.newString(`HostFunctionError: ${Z}`)}finally{G.forEach((W)=>W.dispose())}})}case"bigint":return Q.newString(X.toString());case"symbol":return Q.newString(X.toString());default:try{return Q.newString(String(X))}catch{return Q.undefined}}}var qS6=(Q)=>new Promise((X)=>setTimeout(X,Q));function fY1(Q){let X=Q.runtime.executePendingJobs(100);try{if("unwrap"in X&&typeof X.unwrap==="function")X.unwrap()}finally{if("dispose"in X&&typeof X.dispose==="function")X.dispose()}}async function bY1(Q,X,Y){let J=Date.now(),G=Q.resolvePromise(X);while(!0){fY1(Q);let W=await Promise.race([G,qS6(0).then(()=>null)]);if(W!==null)return W;if(Date.now()-J>Y)throw Error(`Timed out after ${Y}ms while awaiting a QuickJS promise`)}}async function F80({tools:Q,code:X,timeoutMs:Y}){let Z=[];try{let J=await yY1({memoryLimitBytes:33554432,stackSizeBytes:524288});const G=ny(Z,J.newContext({interruptAfterMs:Y}),0);const W=ny(Z,JY1(G),0);try{let F=G.evalCode(X,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult(F),q=RU(G,Q);G.setProp(G.global,"tools",q);let U=G.runtime.hasPendingJob()?G.unwrapResult(await bY1(G,V,Y)):V;if(U!==V)V.dispose();let D=G.getProp(U,"default"),B=G.typeof(D);if(B!=="function")return{error:`Code must export default a function (tools). Got ${B}. Example: export default async (tools) => { /* ... */ }`,consoleLogs:W.logs};let L=G.callFunction(D,G.undefined,q),M=G.unwrapResult(L),C=await bY1(G,M,Y),E=G.unwrapResult(C);if(G.runtime.hasPendingJob())fY1(G);return{returnValue:G.dump(E),consoleLogs:W.logs}}catch(F){return console.log(F),{error:IU(F),consoleLogs:W.logs}}}catch($){var K=$,H=1}finally{r80(Z,K,H)}}function zS6(Q){return Q.toLowerCase().split(/[\s_\-./]+/).filter((X)=>X.length>=2)}function US6(Q,X){let Y=0,J=X.name.toLowerCase(),G=(X.description??"").toLowerCase(),W=X._meta.connectionTitle.toLowerCase();for(let Z of Q){if(J===Z)Y+=10;else if(J.includes(Z))Y+=3;if(G.includes(Z))Y+=2;if(W.includes(Z))Y+=1}return Y}function BS6(Q,X,Y){let J=zS6(Q);if(J.length===0)return X.slice(0,Y);return X.map((G)=>({tool:G,score:US6(J,G)})).filter((G)=>G.score>0).sort((G,W)=>W.score-G.score).slice(0,Y).map((G)=>G.tool)}function V80(Q){return{content:[{type:"text",text:JSON.stringify(Q,null,2)}]}}function KP(Q){return{content:[{type:"text",text:JSON.stringify(Q,null,2)}],isError:!0}}function hY1(Q){let X=N.object({query:N.string().describe("Natural language search query (e.g., 'send email', 'create order')"),limit:N.number().default(10).describe("Maximum results to return (default: 10)")});return{tool:{name:"GATEWAY_SEARCH_TOOLS",description:`Search for available tools by name or description. Returns tool names and brief descriptions without full schemas.${Q.categories.length>0?` Available categories: ${Q.categories.join(", ")}.`:""} Total tools: ${Q.tools.length}.`,inputSchema:N.toJSONSchema(X)},handler:async(J)=>{let G=X.safeParse(J);if(!G.success)return KP({error:G.error.flatten()});let W=BS6(G.data.query,Q.tools,G.data.limit);return V80({query:G.data.query,results:W.map((Z)=>({name:Z.name,description:Z.description,connection:Z._meta.connectionTitle})),totalAvailable:Q.tools.length})}}}function xY1(Q){let X=N.object({tools:N.array(N.string()).min(1).describe("Array of tool names to get detailed schemas for")});return{tool:{name:"GATEWAY_DESCRIBE_TOOLS",description:"Get detailed schemas for specific tools. Call after searching to get full input/output schemas.",inputSchema:N.toJSONSchema(X)},handler:async(Y)=>{let J=X.safeParse(Y);if(!J.success)return KP({error:J.error.flatten()});let G=new Map(Q.tools.map((Z)=>[Z.name,Z])),W=J.data.tools.map((Z)=>G.get(Z)).filter((Z)=>Z!==void 0);return V80({tools:W.map((Z)=>({name:Z.name,description:Z.description,connection:Z._meta.connectionTitle,inputSchema:Z.inputSchema,outputSchema:Z.outputSchema})),notFound:J.data.tools.filter((Z)=>!G.has(Z))})}}}function DS6(Q){let X=Q.tools.map((G)=>G.name),Y=new Map(Q.tools.map((G)=>[G.name,G])),J=N.object({name:N.enum(X).describe("The name of the tool to execute"),arguments:N.record(N.string(),N.unknown()).default({}).describe("Arguments to pass to the tool")});return{tool:{name:"GATEWAY_CALL_TOOL",description:"Execute a tool by name. Use GATEWAY_DESCRIBE_TOOLS first to understand the input schema.",inputSchema:N.toJSONSchema(J)},handler:async(G)=>{let W=J.safeParse(G);if(!W.success)return KP({error:W.error.flatten()});let{name:Z,arguments:$}=W.data;if(!Y.has(Z))return{content:[{type:"text",text:`Tool not found: ${Z}. Use GATEWAY_SEARCH_TOOLS to find available tools.`}],isError:!0};return Q.callTool(Z,$)}}}function NS6(Q){let X=N.object({code:N.string().min(1).describe("JavaScript code to execute. It runs as an async function body; you can use top-level `return` and `await`."),timeoutMs:N.number().default(3000).describe("Max execution time in milliseconds (default: 3000).")});return{tool:{name:"GATEWAY_RUN_CODE",description:'Run JavaScript code in a sandbox. Code must be an ES module that `export default`s an async function that receives (tools) as its first parameter. Use GATEWAY_DESCRIBE_TOOLS to understand the input/output schemas for a tool before calling it. Use `await tools.toolName(args)` or `await tools["tool-name"](args)` to call tools.',inputSchema:N.toJSONSchema(X)},handler:async(Y)=>{let J=X.safeParse(Y);if(!J.success)return KP({error:J.error.flatten()});let G=Object.fromEntries(Q.tools.map((Z)=>[Z.name,async($)=>Q.callTool(Z.name,$??{})])),W=await F80({...J.data,tools:G});if(W.error)return KP(W);return V80(W)}}}function gY1(Q){let X=new Map(Q.map((J)=>[J.tool.name,J.handler])),Y=Q.map((J)=>J.tool.name);return{tools:Q.map((J)=>J.tool),callTool:async(J,G)=>{let W=X.get(J);if(!W)return{content:[{type:"text",text:`Unknown meta-tool: ${J}. Available: ${Y.join(", ")}`}],isError:!0};return W(G)}}}var OS6=(Q)=>({tools:Q.tools,callTool:(X,Y)=>Q.callTool(X,Y)}),LS6=(Q)=>gY1([hY1(Q),xY1(Q),NS6(Q)]),wS6=(Q)=>gY1([hY1(Q),xY1(Q),DS6(Q)]);function uY1(Q){switch(Q){case"smart_tool_selection":return wS6;case"code_execution":return LS6;case"passthrough":default:return OS6}}class Ey{proxies;options;cache;constructor(Q,X){this.proxies=Q;this.options=X;this.cache=QW(()=>this.loadTools())}async loadTools(){let Q=await this.proxies.mapSettled(async(K,H)=>{try{let V=(await K.proxy.client.listTools()).tools;if(this.options.selectionMode==="exclusion"){if(K.selectedTools&&K.selectedTools.length>0){let q=new Set(K.selectedTools);V=V.filter((U)=>!q.has(U.name))}}else if(K.selectedTools&&K.selectedTools.length>0){let q=new Set(K.selectedTools);V=V.filter((U)=>q.has(U.name))}return{connectionId:H,connectionTitle:K.connection.title,tools:V}}catch(F){return console.error(`[gateway] Failed to list tools for connection ${H}:`,F),null}}),X=new Set,Y=[],J=new Map,G=new Set;for(let K of Q){if(K.status!=="fulfilled"||!K.value)continue;let{connectionId:H,connectionTitle:F,tools:V}=K.value;G.add(F);for(let q of V){if(X.has(q.name))continue;X.add(q.name),Y.push({...q,_meta:{connectionId:H,connectionTitle:F}}),J.set(q.name,{connectionId:H,originalName:q.name})}}let W=async(K,H)=>{let F=J.get(K);if(!F)return{content:[{type:"text",text:`Tool not found: ${K}`}],isError:!0};let V=this.proxies.get(F.connectionId);if(!V)return{content:[{type:"text",text:`Connection not found for tool: ${K}`}],isError:!0};return await V.proxy.client.callTool({name:F.originalName,arguments:H})},$=uY1(this.options.strategy)({tools:Y,callTool:W,categories:Array.from(G).sort()});return{tools:Y,mappings:J,strategyResult:$}}async list(){return{tools:(await this.cache).strategyResult.tools}}async call(Q){return(await this.cache).strategyResult.callTool(Q.name,Q.arguments??{})}async callStreamable(Q,X){let Y=await this.cache,J=Y.mappings.get(Q);if(J){let W=this.proxies.get(J.connectionId);if(W)return W.proxy.callStreamableTool(J.originalName,X)}let G=await Y.strategyResult.callTool(Q,X);return new Response(JSON.stringify(G),{headers:{"Content-Type":"application/json"}})}}function MS6(Q,X){if(Q===X)return!0;if(!X.includes("*"))return!1;let Y=X.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"<<<DOUBLE_STAR>>>").replace(/\*/g,"[^/]*").replace(/<<<DOUBLE_STAR>>>/g,".*");Y=`^${Y}$`;try{return new RegExp(Y).test(Q)}catch{return!1}}function mY1(Q,X){return X.some((Y)=>MS6(Q,Y))}class jy{proxies;options;cache;constructor(Q,X){this.proxies=Q;this.options=X;this.cache=QW(()=>this.loadResources())}async loadResources(){let Q=await this.proxies.mapSettled(async(G,W)=>{try{let $=(await G.proxy.client.listResources()).resources;if(this.options.selectionMode==="exclusion"){if(G.selectedResources&&G.selectedResources.length>0)$=$.filter((K)=>!mY1(K.uri,G.selectedResources))}else if(!G.selectedResources||G.selectedResources.length===0)$=[];else $=$.filter((K)=>mY1(K.uri,G.selectedResources));return{connectionId:W,resources:$}}catch(Z){return console.error(`[gateway] Failed to list resources for connection ${W}:`,Z),{connectionId:W,resources:[]}}}),X=new Set,Y=[],J=new Map;for(let G of Q){if(G.status!=="fulfilled")continue;let{connectionId:W,resources:Z}=G.value;for(let $ of Z){if(X.has($.uri))continue;X.add($.uri),Y.push($),J.set($.uri,W)}}return{resources:Y,mappings:J}}async list(){return{resources:(await this.cache).resources}}async read(Q){let Y=(await this.cache).mappings.get(Q.uri);if(!Y)throw Error(`Resource not found: ${Q.uri}`);let J=this.proxies.get(Y);if(!J)throw Error(`Connection not found for resource: ${Q.uri}`);return await J.proxy.client.readResource(Q)}}class Cy{proxies;cache;constructor(Q){this.proxies=Q;this.cache=QW(()=>this.loadResourceTemplates())}async loadResourceTemplates(){let Q=await this.proxies.mapSettled(async(Y,J)=>{try{let G=await Y.proxy.client.listResourceTemplates();return{connectionId:J,templates:G.resourceTemplates}}catch(G){return console.error(`[gateway] Failed to list resource templates for connection ${J}:`,G),{connectionId:J,templates:[]}}}),X=[];for(let Y of Q){if(Y.status!=="fulfilled")continue;let{templates:J}=Y.value;for(let G of J)X.push(G)}return{templates:X}}async list(){return{resourceTemplates:(await this.cache).templates}}}class Iy{proxies;options;cache;constructor(Q,X){this.proxies=Q;this.options=X;this.cache=QW(()=>this.loadPrompts())}async loadPrompts(){let Q=await this.proxies.mapSettled(async(G,W)=>{try{let $=(await G.proxy.client.listPrompts()).prompts;if(this.options.selectionMode==="exclusion"){if(G.selectedPrompts&&G.selectedPrompts.length>0){let K=new Set(G.selectedPrompts);$=$.filter((H)=>!K.has(H.name))}}else if(!G.selectedPrompts||G.selectedPrompts.length===0)$=[];else{let K=new Set(G.selectedPrompts);$=$.filter((H)=>K.has(H.name))}return{connectionId:W,prompts:$}}catch(Z){return console.error(`[PromptGateway] Failed to list prompts for connection ${W}:`,Z),{connectionId:W,prompts:[]}}}),X=new Set,Y=[],J=new Map;for(let G of Q){if(G.status!=="fulfilled")continue;let{connectionId:W,prompts:Z}=G.value;for(let $ of Z){if(X.has($.name))continue;X.add($.name),Y.push($),J.set($.name,W)}}return{prompts:Y,mappings:J}}async list(){return{prompts:(await this.cache).prompts}}async get(Q){let Y=(await this.cache).mappings.get(Q.name);if(!Y)throw Error(`Prompt not found: ${Q.name}`);let J=this.proxies.get(Y);if(!J)throw Error(`Connection not found for prompt: ${Q.name}`);return await J.proxy.client.getPrompt(Q)}}var lY1=new d9;async function PS6(Q,X){let Y=await ZP.create(Q.connections,X),J=new Ey(Y,{selectionMode:Q.toolSelectionMode,strategy:Q.toolSelectionStrategy}),G=new jy(Y,{selectionMode:Q.toolSelectionMode}),W=new Cy(Y),Z=new Iy(Y,{selectionMode:Q.toolSelectionMode});return{client:{listTools:J.list.bind(J),callTool:J.call.bind(J),listResources:G.list.bind(G),readResource:G.read.bind(G),listResourceTemplates:W.list.bind(W),listPrompts:Z.list.bind(Z),getPrompt:Z.get.bind(Z)},callStreamableTool:J.callStreamable.bind(J)}}async function TS6(Q,X){let Y;if(Q.toolSelectionMode==="exclusion"){let W=(await X.storage.connections.list(Q.organizationId)).filter(($)=>$.status==="active"),Z=new Map;for(let $ of Q.connections)Z.set($.connectionId,{selectedTools:$.selectedTools,selectedResources:$.selectedResources,selectedPrompts:$.selectedPrompts});Y=[];for(let $ of W){let K=Z.get($.id);if(K===void 0)Y.push({connection:$,selectedTools:null,selectedResources:null,selectedPrompts:null});else if((K.selectedTools===null||K.selectedTools.length===0)&&(K.selectedResources===null||K.selectedResources.length===0)&&(K.selectedPrompts===null||K.selectedPrompts.length===0));else Y.push({connection:$,selectedTools:K.selectedTools,selectedResources:K.selectedResources,selectedPrompts:K.selectedPrompts})}}else{let G=Q.connections.map((Z)=>Z.connectionId),W=[];for(let Z of G){let $=await X.storage.connections.findById(Z);if($&&$.status==="active")W.push($)}Y=W.map((Z)=>{let $=Q.connections.find((K)=>K.connectionId===Z.id);return{connection:Z,selectedTools:$?.selectedTools??null,selectedResources:$?.selectedResources??null,selectedPrompts:$?.selectedPrompts??null}})}let J={connections:Y,toolSelectionMode:Q.toolSelectionMode,toolSelectionStrategy:Q.toolSelectionStrategy};return PS6(J,X)}lY1.all("/gateway/:gatewayId?",async(Q)=>{let X=Q.req.param("gatewayId"),Y=Q.get("meshContext");try{let J=null;if(X)J=await Y.storage.gateways.findById(X);else{let K=Q.req.header("x-org-id"),H=Q.req.header("x-org-slug");if(K)J=await Y.storage.gateways.getDefaultByOrgId(K);else if(H)J=await Y.storage.gateways.getDefaultByOrgSlug(H);else return Q.json({error:"Gateway ID required, or provide x-org-id or x-org-slug header for default Hub"},400)}if(!J){if(X)return Q.json({error:`Gateway not found: ${X}`},404);return Q.json({error:"No default Hub configured for this organization"},404)}if(Y.gatewayId=J.id,J.status!=="active")return Q.json({error:`Gateway is inactive: ${J.id}`},503);let G=await Y.db.selectFrom("organization").select(["id","slug","name"]).where("id","=",J.organizationId).executeTakeFirst();if(G)Y.organization={id:G.id,slug:G.slug,name:G.name};let W=await TS6(J,Y),Z=new p3({name:`mcp-gateway-${J.title}`,version:"1.0.0"},{capabilities:{tools:{},resources:{},prompts:{}}}),$=new c3({enableJsonResponse:Q.req.header("Accept")?.includes("application/json")??!1});return await Z.connect($),Z.server.setRequestHandler(k$,async(K)=>{return W.client.listTools()}),Z.server.setRequestHandler(rG,async(K)=>{return await W.client.callTool(K.params)}),Z.server.setRequestHandler(j$,async()=>{return W.client.listResources()}),Z.server.setRequestHandler(I$,async(K)=>{return W.client.readResource(K.params)}),Z.server.setRequestHandler(C$,async()=>{return W.client.listResourceTemplates()}),Z.server.setRequestHandler(R$,async()=>{return W.client.listPrompts()}),Z.server.setRequestHandler(S$,async(K)=>{return W.client.getPrompt(K.params)}),await $.handleRequest(Q.req.raw)}catch(J){let G=J;return console.error("[gateway] Error handling gateway request:",G),Q.json({error:"Internal server error",message:G.message},500)}});var dY1=lY1;_40();var pY1=new d9;pY1.all("/",async(Q)=>{return v40(Q.get("meshContext")).fetch(Q.req.raw)});var cY1=pY1;i60();GU();RM();_9();var wJ1="vercel.ai.error",AS6=Symbol.for(wJ1),nY1,iY1,P1=class Q extends(iY1=Error,nY1=AS6,iY1){constructor({name:X,message:Y,cause:J}){super(Y);this[nY1]=!0,this.name=X,this.cause=J}static isInstance(X){return Q.hasMarker(X,wJ1)}static hasMarker(X,Y){let J=Symbol.for(Y);return X!=null&&typeof X==="object"&&J in X&&typeof X[J]==="boolean"&&X[J]===!0}},MJ1="AI_APICallError",PJ1=`vercel.ai.error.${MJ1}`,ES6=Symbol.for(PJ1),aY1,rY1,r8=class extends(rY1=P1,aY1=ES6,rY1){constructor({message:Q,url:X,requestBodyValues:Y,statusCode:J,responseHeaders:G,responseBody:W,cause:Z,isRetryable:$=J!=null&&(J===408||J===409||J===429||J>=500),data:K}){super({name:MJ1,message:Q,cause:Z});this[aY1]=!0,this.url=X,this.requestBodyValues=Y,this.statusCode=J,this.responseHeaders=G,this.responseBody=W,this.isRetryable=$,this.data=K}static isInstance(Q){return P1.hasMarker(Q,PJ1)}},TJ1="AI_EmptyResponseBodyError",AJ1=`vercel.ai.error.${TJ1}`,jS6=Symbol.for(AJ1),oY1,sY1,EJ1=class extends(sY1=P1,oY1=jS6,sY1){constructor({message:Q="Empty response body"}={}){super({name:TJ1,message:Q});this[oY1]=!0}static isInstance(Q){return P1.hasMarker(Q,AJ1)}};function R5(Q){if(Q==null)return"unknown error";if(typeof Q==="string")return Q;if(Q instanceof Error)return Q.message;return JSON.stringify(Q)}var jJ1="AI_InvalidArgumentError",CJ1=`vercel.ai.error.${jJ1}`,CS6=Symbol.for(CJ1),tY1,eY1,IJ1=class extends(eY1=P1,tY1=CS6,eY1){constructor({message:Q,cause:X,argument:Y}){super({name:jJ1,message:Q,cause:X});this[tY1]=!0,this.argument=Y}static isInstance(Q){return P1.hasMarker(Q,CJ1)}},RJ1="AI_InvalidPromptError",SJ1=`vercel.ai.error.${RJ1}`,IS6=Symbol.for(SJ1),QJ1,XJ1,s3=class extends(XJ1=P1,QJ1=IS6,XJ1){constructor({prompt:Q,message:X,cause:Y}){super({name:RJ1,message:`Invalid prompt: ${X}`,cause:Y});this[QJ1]=!0,this.prompt=Q}static isInstance(Q){return P1.hasMarker(Q,SJ1)}},kJ1="AI_InvalidResponseDataError",vJ1=`vercel.ai.error.${kJ1}`,RS6=Symbol.for(vJ1),YJ1,JJ1,Ju4=class extends(JJ1=P1,YJ1=RS6,JJ1){constructor({data:Q,message:X=`Invalid response data: ${JSON.stringify(Q)}.`}){super({name:kJ1,message:X});this[YJ1]=!0,this.data=Q}static isInstance(Q){return P1.hasMarker(Q,vJ1)}},_J1="AI_JSONParseError",yJ1=`vercel.ai.error.${_J1}`,SS6=Symbol.for(yJ1),GJ1,WJ1,HP=class extends(WJ1=P1,GJ1=SS6,WJ1){constructor({text:Q,cause:X}){super({name:_J1,message:`JSON parsing failed: Text: ${Q}.
1045
1045
  Error message: ${R5(X)}`,cause:X});this[GJ1]=!0,this.text=Q}static isInstance(Q){return P1.hasMarker(Q,yJ1)}},bJ1="AI_LoadAPIKeyError",fJ1=`vercel.ai.error.${bJ1}`,kS6=Symbol.for(fJ1),ZJ1,$J1,Gu4=class extends($J1=P1,ZJ1=kS6,$J1){constructor({message:Q}){super({name:bJ1,message:Q});this[ZJ1]=!0}static isInstance(Q){return P1.hasMarker(Q,fJ1)}},hJ1="AI_LoadSettingError",xJ1=`vercel.ai.error.${hJ1}`,vS6=Symbol.for(xJ1),KJ1,HJ1,Wu4=class extends(HJ1=P1,KJ1=vS6,HJ1){constructor({message:Q}){super({name:hJ1,message:Q});this[KJ1]=!0}static isInstance(Q){return P1.hasMarker(Q,xJ1)}},gJ1="AI_NoContentGeneratedError",uJ1=`vercel.ai.error.${gJ1}`,_S6=Symbol.for(uJ1),FJ1,VJ1,Zu4=class extends(VJ1=P1,FJ1=_S6,VJ1){constructor({message:Q="No content generated."}={}){super({name:gJ1,message:Q});this[FJ1]=!0}static isInstance(Q){return P1.hasMarker(Q,uJ1)}},mJ1="AI_NoSuchModelError",lJ1=`vercel.ai.error.${mJ1}`,yS6=Symbol.for(lJ1),qJ1,zJ1,$u4=class extends(zJ1=P1,qJ1=yS6,zJ1){constructor({errorName:Q=mJ1,modelId:X,modelType:Y,message:J=`No such ${Y}: ${X}`}){super({name:Q,message:J});this[qJ1]=!0,this.modelId=X,this.modelType=Y}static isInstance(Q){return P1.hasMarker(Q,lJ1)}},dJ1="AI_TooManyEmbeddingValuesForCallError",pJ1=`vercel.ai.error.${dJ1}`,bS6=Symbol.for(pJ1),UJ1,BJ1,Ku4=class extends(BJ1=P1,UJ1=bS6,BJ1){constructor(Q){super({name:dJ1,message:`Too many values for a single embedding call. The ${Q.provider} model "${Q.modelId}" can only embed up to ${Q.maxEmbeddingsPerCall} values per call, but ${Q.values.length} values were provided.`});this[UJ1]=!0,this.provider=Q.provider,this.modelId=Q.modelId,this.maxEmbeddingsPerCall=Q.maxEmbeddingsPerCall,this.values=Q.values}static isInstance(Q){return P1.hasMarker(Q,pJ1)}},cJ1="AI_TypeValidationError",nJ1=`vercel.ai.error.${cJ1}`,fS6=Symbol.for(nJ1),DJ1,NJ1,S5=class Q extends(NJ1=P1,DJ1=fS6,NJ1){constructor({value:X,cause:Y}){super({name:cJ1,message:`Type validation failed: Value: ${JSON.stringify(X)}.
1046
1046
  Error message: ${R5(Y)}`,cause:Y});this[DJ1]=!0,this.value=X}static isInstance(X){return P1.hasMarker(X,nJ1)}static wrap({value:X,cause:Y}){return Q.isInstance(Y)&&Y.value===X?Y:new Q({value:X,cause:Y})}},iJ1="AI_UnsupportedFunctionalityError",aJ1=`vercel.ai.error.${iJ1}`,hS6=Symbol.for(aJ1),OJ1,LJ1,Hu4=class extends(LJ1=P1,OJ1=hS6,LJ1){constructor({functionality:Q,message:X=`'${Q}' functionality not supported.`}){super({name:iJ1,message:X});this[OJ1]=!0,this.functionality=Q}static isInstance(Q){return P1.hasMarker(Q,aJ1)}};r6();T$();T$();T$();B60();function e3(...Q){return Q.reduce((X,Y)=>({...X,...Y!=null?Y:{}}),{})}async function X51(Q,X){if(Q==null)return Promise.resolve();let Y=X==null?void 0:X.abortSignal;return new Promise((J,G)=>{if(Y==null?void 0:Y.aborted){G(rJ1());return}let W=setTimeout(()=>{Z(),J()},Q),Z=()=>{clearTimeout(W),Y==null||Y.removeEventListener("abort",$)},$=()=>{Z(),G(rJ1())};Y==null||Y.addEventListener("abort",$)})}function rJ1(){return new DOMException("Delay was aborted","AbortError")}var QF=class{constructor(){this.status={type:"pending"},this._resolve=void 0,this._reject=void 0}get promise(){if(this._promise)return this._promise;return this._promise=new Promise((Q,X)=>{if(this.status.type==="resolved")Q(this.status.value);else if(this.status.type==="rejected")X(this.status.error);this._resolve=Q,this._reject=X}),this._promise}resolve(Q){var X;if(this.status={type:"resolved",value:Q},this._promise)(X=this._resolve)==null||X.call(this,Q)}reject(Q){var X;if(this.status={type:"rejected",error:Q},this._promise)(X=this._reject)==null||X.call(this,Q)}isResolved(){return this.status.type==="resolved"}isRejected(){return this.status.type==="rejected"}isPending(){return this.status.type==="pending"}};function FP(Q){return Object.fromEntries([...Q.headers])}var{btoa:xS6,atob:gS6}=globalThis;function SU(Q){let X=Q.replace(/-/g,"+").replace(/_/g,"/"),Y=gS6(X);return Uint8Array.from(Y,(J)=>J.codePointAt(0))}function XF(Q){let X="";for(let Y=0;Y<Q.length;Y++)X+=String.fromCodePoint(Q[Y]);return xS6(X)}var Y51="AI_DownloadError",J51=`vercel.ai.error.${Y51}`,uS6=Symbol.for(J51),oJ1,sJ1,Ry=class extends(sJ1=P1,oJ1=uS6,sJ1){constructor({url:Q,statusCode:X,statusText:Y,cause:J,message:G=J==null?`Failed to download ${Q}: ${X} ${Y}`:`Failed to download ${Q}: ${J}`}){super({name:Y51,message:G,cause:J});this[oJ1]=!0,this.url=Q,this.statusCode=X,this.statusText=Y}static isInstance(Q){return P1.hasMarker(Q,J51)}};var XW=({prefix:Q,size:X=16,alphabet:Y="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:J="-"}={})=>{let G=()=>{let W=Y.length,Z=Array(X);for(let $=0;$<X;$++)Z[$]=Y[Math.random()*W|0];return Z.join("")};if(Q==null)return G;if(Y.includes(J))throw new IJ1({argument:"separator",message:`The separator "${J}" must not be part of the alphabet "${Y}".`});return()=>`${Q}${J}${G()}`},mS6=XW();function VP(Q){if(Q==null)return"unknown error";if(typeof Q==="string")return Q;if(Q instanceof Error)return Q.message;return JSON.stringify(Q)}function b7(Q){return(Q instanceof Error||Q instanceof DOMException)&&(Q.name==="AbortError"||Q.name==="ResponseAborted"||Q.name==="TimeoutError")}var lS6=["fetch failed","failed to fetch"];function G51({error:Q,url:X,requestBodyValues:Y}){if(b7(Q))return Q;if(Q instanceof TypeError&&lS6.includes(Q.message.toLowerCase())){let J=Q.cause;if(J!=null)return new r8({message:`Cannot connect to API: ${J.message}`,cause:J,url:X,requestBodyValues:Y,isRetryable:!0})}return Q}function Sy(Q=globalThis){var X,Y,J;if(Q.window)return"runtime/browser";if((X=Q.navigator)==null?void 0:X.userAgent)return`runtime/${Q.navigator.userAgent.toLowerCase()}`;if((J=(Y=Q.process)==null?void 0:Y.versions)==null?void 0:J.node)return`runtime/node.js/${Q.process.version.substring(0)}`;if(Q.EdgeRuntime)return"runtime/vercel-edge";return"runtime/unknown"}function dS6(Q){if(Q==null)return{};let X={};if(Q instanceof Headers)Q.forEach((Y,J)=>{X[J.toLowerCase()]=Y});else{if(!Array.isArray(Q))Q=Object.entries(Q);for(let[Y,J]of Q)if(J!=null)X[Y.toLowerCase()]=J}return X}function a$(Q,...X){let Y=new Headers(dS6(Q)),J=Y.get("user-agent")||"";return Y.set("user-agent",[J,...X].filter(Boolean).join(" ")),Object.fromEntries(Y.entries())}var W51="4.0.4",pS6=()=>globalThis.fetch,D80=async({url:Q,headers:X={},successfulResponseHandler:Y,failedResponseHandler:J,abortSignal:G,fetch:W=pS6()})=>{try{let Z=await W(Q,{method:"GET",headers:a$(X,`ai-sdk/provider-utils/${W51}`,Sy()),signal:G}),$=FP(Z);if(!Z.ok){let K;try{K=await J({response:Z,url:Q,requestBodyValues:{}})}catch(H){if(b7(H)||r8.isInstance(H))throw H;throw new r8({message:"Failed to process error response",cause:H,statusCode:Z.status,url:Q,responseHeaders:$,requestBodyValues:{}})}throw K.value}try{return await Y({response:Z,url:Q,requestBodyValues:{}})}catch(K){if(K instanceof Error){if(b7(K)||r8.isInstance(K))throw K}throw new r8({message:"Failed to process successful response",cause:K,statusCode:Z.status,url:Q,responseHeaders:$,requestBodyValues:{}})}}catch(Z){throw G51({error:Z,url:Q,requestBodyValues:{}})}};function Z51(Q){return Q!=null}function $51({mediaType:Q,url:X,supportedUrls:Y}){return X=X.toLowerCase(),Q=Q.toLowerCase(),Object.entries(Y).map(([J,G])=>{let W=J.toLowerCase();return W==="*"||W==="*/*"?{mediaTypePrefix:"",regexes:G}:{mediaTypePrefix:W.replace(/\*/,""),regexes:G}}).filter(({mediaTypePrefix:J})=>Q.startsWith(J)).flatMap(({regexes:J})=>J).some((J)=>J.test(X))}function qP({settingValue:Q,environmentVariableName:X}){if(typeof Q==="string")return Q;if(Q!=null||typeof process>"u")return;if(Q=process.env[X],Q==null||typeof Q!=="string")return;return Q}var cS6=/"__proto__"\s*:/,nS6=/"constructor"\s*:/;function tJ1(Q){let X=JSON.parse(Q);if(X===null||typeof X!=="object")return X;if(cS6.test(Q)===!1&&nS6.test(Q)===!1)return X;return iS6(X)}function iS6(Q){let X=[Q];while(X.length){let Y=X;X=[];for(let J of Y){if(Object.prototype.hasOwnProperty.call(J,"__proto__"))throw SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(J,"constructor")&&Object.prototype.hasOwnProperty.call(J.constructor,"prototype"))throw SyntaxError("Object contains forbidden prototype property");for(let G in J){let W=J[G];if(W&&typeof W==="object")X.push(W)}}}return Q}function K51(Q){let{stackTraceLimit:X}=Error;try{Error.stackTraceLimit=0}catch(Y){return tJ1(Q)}try{return tJ1(Q)}finally{Error.stackTraceLimit=X}}function H51(Q){if(Q.type==="object"||Array.isArray(Q.type)&&Q.type.includes("object")){Q.additionalProperties=!1;let{properties:Y}=Q;if(Y!=null)for(let J of Object.keys(Y))Y[J]=t3(Y[J])}if(Q.items!=null)Q.items=Array.isArray(Q.items)?Q.items.map(t3):t3(Q.items);if(Q.anyOf!=null)Q.anyOf=Q.anyOf.map(t3);if(Q.allOf!=null)Q.allOf=Q.allOf.map(t3);if(Q.oneOf!=null)Q.oneOf=Q.oneOf.map(t3);let{definitions:X}=Q;if(X!=null)for(let Y of Object.keys(X))X[Y]=t3(X[Y]);return Q}function t3(Q){if(typeof Q==="boolean")return Q;return H51(Q)}var aS6=Symbol("Let zodToJsonSchema decide on which parser to use"),eJ1={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},rS6=(Q)=>typeof Q==="string"?{...eJ1,name:Q}:{...eJ1,...Q};function _Y(){return{}}function oS6(Q,X){var Y,J,G;let W={type:"array"};if(((Y=Q.type)==null?void 0:Y._def)&&((G=(J=Q.type)==null?void 0:J._def)==null?void 0:G.typeName)!==j0.ZodAny)W.items=f4(Q.type._def,{...X,currentPath:[...X.currentPath,"items"]});if(Q.minLength)W.minItems=Q.minLength.value;if(Q.maxLength)W.maxItems=Q.maxLength.value;if(Q.exactLength)W.minItems=Q.exactLength.value,W.maxItems=Q.exactLength.value;return W}function sS6(Q){let X={type:"integer",format:"int64"};if(!Q.checks)return X;for(let Y of Q.checks)switch(Y.kind){case"min":if(Y.inclusive)X.minimum=Y.value;else X.exclusiveMinimum=Y.value;break;case"max":if(Y.inclusive)X.maximum=Y.value;else X.exclusiveMaximum=Y.value;break;case"multipleOf":X.multipleOf=Y.value;break}return X}function tS6(){return{type:"boolean"}}function F51(Q,X){return f4(Q.type._def,X)}var eS6=(Q,X)=>{return f4(Q.innerType._def,X)};function V51(Q,X,Y){let J=Y!=null?Y:X.dateStrategy;if(Array.isArray(J))return{anyOf:J.map((G,W)=>V51(Q,X,G))};switch(J){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Qk6(Q)}}var Qk6=(Q)=>{let X={type:"integer",format:"unix-time"};for(let Y of Q.checks)switch(Y.kind){case"min":X.minimum=Y.value;break;case"max":X.maximum=Y.value;break}return X};function Xk6(Q,X){return{...f4(Q.innerType._def,X),default:Q.defaultValue()}}function Yk6(Q,X){return X.effectStrategy==="input"?f4(Q.schema._def,X):_Y()}function Jk6(Q){return{type:"string",enum:Array.from(Q.values)}}var Gk6=(Q)=>{if("type"in Q&&Q.type==="string")return!1;return"allOf"in Q};function Wk6(Q,X){let Y=[f4(Q.left._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),f4(Q.right._def,{...X,currentPath:[...X.currentPath,"allOf","1"]})].filter((G)=>!!G),J=[];return Y.forEach((G)=>{if(Gk6(G))J.push(...G.allOf);else{let W=G;if("additionalProperties"in G&&G.additionalProperties===!1){let{additionalProperties:Z,...$}=G;W=$}J.push(W)}}),J.length?{allOf:J}:void 0}function Zk6(Q){let X=typeof Q.value;if(X!=="bigint"&&X!=="number"&&X!=="boolean"&&X!=="string")return{type:Array.isArray(Q.value)?"array":"object"};return{type:X==="bigint"?"integer":X,const:Q.value}}var q80=void 0,k5={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>{if(q80===void 0)q80=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return q80},uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function q51(Q,X){let Y={type:"string"};if(Q.checks)for(let J of Q.checks)switch(J.kind){case"min":Y.minLength=typeof Y.minLength==="number"?Math.max(Y.minLength,J.value):J.value;break;case"max":Y.maxLength=typeof Y.maxLength==="number"?Math.min(Y.maxLength,J.value):J.value;break;case"email":switch(X.emailStrategy){case"format:email":v5(Y,"email",J.message,X);break;case"format:idn-email":v5(Y,"idn-email",J.message,X);break;case"pattern:zod":NX(Y,k5.email,J.message,X);break}break;case"url":v5(Y,"uri",J.message,X);break;case"uuid":v5(Y,"uuid",J.message,X);break;case"regex":NX(Y,J.regex,J.message,X);break;case"cuid":NX(Y,k5.cuid,J.message,X);break;case"cuid2":NX(Y,k5.cuid2,J.message,X);break;case"startsWith":NX(Y,RegExp(`^${z80(J.value,X)}`),J.message,X);break;case"endsWith":NX(Y,RegExp(`${z80(J.value,X)}$`),J.message,X);break;case"datetime":v5(Y,"date-time",J.message,X);break;case"date":v5(Y,"date",J.message,X);break;case"time":v5(Y,"time",J.message,X);break;case"duration":v5(Y,"duration",J.message,X);break;case"length":Y.minLength=typeof Y.minLength==="number"?Math.max(Y.minLength,J.value):J.value,Y.maxLength=typeof Y.maxLength==="number"?Math.min(Y.maxLength,J.value):J.value;break;case"includes":{NX(Y,RegExp(z80(J.value,X)),J.message,X);break}case"ip":{if(J.version!=="v6")v5(Y,"ipv4",J.message,X);if(J.version!=="v4")v5(Y,"ipv6",J.message,X);break}case"base64url":NX(Y,k5.base64url,J.message,X);break;case"jwt":NX(Y,k5.jwt,J.message,X);break;case"cidr":{if(J.version!=="v6")NX(Y,k5.ipv4Cidr,J.message,X);if(J.version!=="v4")NX(Y,k5.ipv6Cidr,J.message,X);break}case"emoji":NX(Y,k5.emoji(),J.message,X);break;case"ulid":{NX(Y,k5.ulid,J.message,X);break}case"base64":{switch(X.base64Strategy){case"format:binary":{v5(Y,"binary",J.message,X);break}case"contentEncoding:base64":{Y.contentEncoding="base64";break}case"pattern:zod":{NX(Y,k5.base64,J.message,X);break}}break}case"nanoid":NX(Y,k5.nanoid,J.message,X);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return Y}function z80(Q,X){return X.patternStrategy==="escape"?Kk6(Q):Q}var $k6=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Kk6(Q){let X="";for(let Y=0;Y<Q.length;Y++){if(!$k6.has(Q[Y]))X+="\\";X+=Q[Y]}return X}function v5(Q,X,Y,J){var G;if(Q.format||((G=Q.anyOf)==null?void 0:G.some((W)=>W.format))){if(!Q.anyOf)Q.anyOf=[];if(Q.format)Q.anyOf.push({format:Q.format}),delete Q.format;Q.anyOf.push({format:X,...Y&&J.errorMessages&&{errorMessage:{format:Y}}})}else Q.format=X}function NX(Q,X,Y,J){var G;if(Q.pattern||((G=Q.allOf)==null?void 0:G.some((W)=>W.pattern))){if(!Q.allOf)Q.allOf=[];if(Q.pattern)Q.allOf.push({pattern:Q.pattern}),delete Q.pattern;Q.allOf.push({pattern:Q51(X,J),...Y&&J.errorMessages&&{errorMessage:{pattern:Y}}})}else Q.pattern=Q51(X,J)}function Q51(Q,X){var Y;if(!X.applyRegexFlags||!Q.flags)return Q.source;let J={i:Q.flags.includes("i"),m:Q.flags.includes("m"),s:Q.flags.includes("s")},G=J.i?Q.source.toLowerCase():Q.source,W="",Z=!1,$=!1,K=!1;for(let H=0;H<G.length;H++){if(Z){W+=G[H],Z=!1;continue}if(J.i){if($){if(G[H].match(/[a-z]/)){if(K)W+=G[H],W+=`${G[H-2]}-${G[H]}`.toUpperCase(),K=!1;else if(G[H+1]==="-"&&((Y=G[H+2])==null?void 0:Y.match(/[a-z]/)))W+=G[H],K=!0;else W+=`${G[H]}${G[H].toUpperCase()}`;continue}}else if(G[H].match(/[a-z]/)){W+=`[${G[H]}${G[H].toUpperCase()}]`;continue}}if(J.m){if(G[H]==="^"){W+=`(^|(?<=[\r
1047
1047
  ]))`;continue}else if(G[H]==="$"){W+=`($|(?=[\r