@decocms/mesh 2.1.2 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/assets/{AlertCircle-DiqlNboz.js → AlertCircle-laxSE0PX.js} +1 -1
- package/dist/client/assets/{ArrowLeft-C4VtVMs2.js → ArrowLeft-Dd7BK5dX.js} +1 -1
- package/dist/client/assets/{ChevronDown-CcUg3X_Y.js → ChevronDown-CvWv-usR.js} +1 -1
- package/dist/client/assets/{ChevronRight-DoX6pxYj.js → ChevronRight-Fe_n2oGa.js} +1 -1
- package/dist/client/assets/{Copy01-BJql3T8w.js → Copy01-C6NIIZuG.js} +1 -1
- package/dist/client/assets/{DotsHorizontal-wWvFFsxa.js → DotsHorizontal-Cw17Pnyf.js} +1 -1
- package/dist/client/assets/{DotsVertical-C_psDJy3.js → DotsVertical-CH2fNSbY.js} +1 -1
- package/dist/client/assets/{File06-CfmzgkCD.js → File06-BFg45elm.js} +1 -1
- package/dist/client/assets/{FilterLines-MNaVyood.js → FilterLines-BjvAuET2.js} +1 -1
- package/dist/client/assets/{FlipBackward-qa1GrgeQ.js → FlipBackward-BCF9hA9D.js} +1 -1
- package/dist/client/assets/{GitBranch01-Cy-aTD__.js → GitBranch01-5UP5g_4t.js} +1 -1
- package/dist/client/assets/{Grid01-400pwqps.js → Grid01-Soc1w0HN.js} +1 -1
- package/dist/client/assets/{Inbox01-DQ40if0u.js → Inbox01-D8CnGo7i.js} +1 -1
- package/dist/client/assets/{InfoCircle-DbgHopMm.js → InfoCircle-CJE1rYNL.js} +1 -1
- package/dist/client/assets/{Key01-CXPRpQE9.js → Key01-D6Y52TVu.js} +1 -1
- package/dist/client/assets/{LinkExternal01-BJZvPGF2.js → LinkExternal01-DbeN7vxS.js} +1 -1
- package/dist/client/assets/{Loading01-DSWhKp36.js → Loading01-B8IKnW3x.js} +1 -1
- package/dist/client/assets/{Lock01-Cw5Gl3NV.js → Lock01-DGGIBBCl.js} +1 -1
- package/dist/client/assets/{Play-18tBEZWZ.js → Play-D2jnwQAI.js} +1 -1
- package/dist/client/assets/{Plus-SMn8MQ-H.js → Plus-3Cnjm1UT.js} +1 -1
- package/dist/client/assets/{Terminal-yR92omIF.js → Terminal-vZCLGbvo.js} +1 -1
- package/dist/client/assets/{Trash01-DaFJSHZu.js → Trash01-D0jDlYQJ.js} +1 -1
- package/dist/client/assets/{X-q_t7ZUi-.js → X-CrCcl1sv.js} +1 -1
- package/dist/client/assets/{XClose-2lFeEEkz.js → XClose-DZ7ckVTf.js} +1 -1
- package/dist/client/assets/{alert-dialog-BOjS3GrS.js → alert-dialog-BHM4cw4Q.js} +2 -2
- package/dist/client/assets/{auth-BvEfLR40.js → auth-BfhoYwZo.js} +1 -1
- package/dist/client/assets/{auth-catchall-qnrnPCT6.js → auth-catchall-BQuGaWdj.js} +1 -1
- package/dist/client/assets/{avatar-D8KYLrun.js → avatar-CBETgvTo.js} +1 -1
- package/dist/client/assets/{badge-DHFuTJNA.js → badge-BoEIasGQ.js} +1 -1
- package/dist/client/assets/{card-CSWNwOPv.js → card-TBEiO_pf.js} +1 -1
- package/dist/client/assets/{checkbox-D6eJScSi.js → checkbox-CFS6LZcp.js} +1 -1
- package/dist/client/assets/{collection-detail-cLR1iiCF.js → collection-detail-BnDPq9AR.js} +18 -18
- package/dist/client/assets/{collection-display-button-DWBgVnY5.js → collection-display-button-KvR7sWeM.js} +1 -1
- package/dist/client/assets/{collection-header-BYkZ9Trb.js → collection-header-f1ffdO7f.js} +1 -1
- package/dist/client/assets/{collection-page-BjyL0NfT.js → collection-page-WZgTp5Lv.js} +1 -1
- package/dist/client/assets/{collection-search-BhTsTIQF.js → collection-search-3XPe6V_T.js} +1 -1
- package/dist/client/assets/{collection-tab-ByD_c7B5.js → collection-tab-CNcWbqd2.js} +1 -1
- package/dist/client/assets/{collection-table-wrapper-G4nlfvjF.js → collection-table-wrapper-B34CJdmN.js} +1 -1
- package/dist/client/assets/{connection-card-BRub-GLZ.js → connection-card-AILFqLN1.js} +1 -1
- package/dist/client/assets/connection-detail-Dkmb8FZw.js +1 -0
- package/dist/client/assets/{connections-BEv7u43V.js → connections-Ce1zfRUl.js} +1 -1
- package/dist/client/assets/constants-D2EL4NMa.js +1 -0
- package/dist/client/assets/{create-organization-dialog-CahJq4TL.js → create-organization-dialog-6aGfA3nN.js} +1 -1
- package/dist/client/assets/{dialog-Ay6PD9W0.js → dialog-By5cpA-o.js} +1 -1
- package/dist/client/assets/{dropdown-menu-CX0_ej-t.js → dropdown-menu-CxU4B3XS.js} +1 -1
- package/dist/client/assets/{empty-state-DOXYCllo.js → empty-state-DDZV3qxG.js} +1 -1
- package/dist/client/assets/{env-vars-editor-DB_yBian.js → env-vars-editor-CLtT_Pn2.js} +1 -1
- package/dist/client/assets/{error-boundary-BITgBYMF.js → error-boundary-DFjr3eHD.js} +1 -1
- package/dist/client/assets/{extract-connection-data-CaZ0wil0.js → extract-connection-data-CNLQVqLl.js} +1 -1
- package/dist/client/assets/{form-CTm5F5lc.js → form-BAnmUhVa.js} +1 -1
- package/dist/client/assets/gateway-detail-CD1SXTO4.js +1 -0
- package/dist/client/assets/gateway-selector-BC3bwpkS.js +1 -0
- package/dist/client/assets/gateways-BPDYdmPL.js +1 -0
- package/dist/client/assets/{home-BCE1FamF.js → home-CxQ-oPDQ.js} +1 -1
- package/dist/client/assets/index-BQaN6CW7.js +25 -0
- package/dist/client/assets/{index-DU53zBhA.css → index-BV_tzcZC.css} +1 -1
- package/dist/client/assets/{index-Tg8Sdg8t.js → index-CIDbVI0o.js} +2 -2
- package/dist/client/assets/{index-DskbBe5h.js → index-DxSQLqqY.js} +1 -1
- package/dist/client/assets/{input-DZxsngZP.js → input-BYLamBFT.js} +1 -1
- package/dist/client/assets/{layout-Brqmaefj.js → layout-CPjqBR8a.js} +1 -1
- package/dist/client/assets/{lazy-highlighter-CiDPKksG.js → lazy-highlighter-L5Lo_GWJ.js} +1 -1
- package/dist/client/assets/localstorage-keys-BcKYfcRC.js +1 -0
- package/dist/client/assets/{login-DTvg0d0e.js → login-CWasMrLi.js} +1 -1
- package/dist/client/assets/{mcp-oauth-SMi_MNm0.js → mcp-oauth-BbYG4wEg.js} +1 -1
- package/dist/client/assets/{mcp-server-detail-Dp4c82jn.js → mcp-server-detail-DL1XSpPt.js} +1 -1
- package/dist/client/assets/{members-Antj9sp8.js → members-Cm7y0IGn.js} +1 -1
- package/dist/client/assets/{monaco-editor-DzF_l7qF.js → monaco-editor-BANuhZc7.js} +1 -1
- package/dist/client/assets/{monitoring-CFWL1rLz.js → monitoring-CypFTCwZ.js} +3 -3
- package/dist/client/assets/{oauth-callback-CG8hLD-b.js → oauth-callback-BljFGwn2.js} +1 -1
- package/dist/client/assets/page-B3Vk0n7G.js +35 -0
- package/dist/client/assets/{page-BvT1wvbD.js → page-DPBKFn7H.js} +1 -1
- package/dist/client/assets/{pin-to-sidebar-button-fGogNndB.js → pin-to-sidebar-button-GermWsTp.js} +1 -1
- package/dist/client/assets/{popover-D8pPVQL_.js → popover-BXzChz3h.js} +1 -1
- package/dist/client/assets/{project-context-provider-DzGl09z5.js → project-context-provider-rr2ZgefD.js} +1 -1
- package/dist/client/assets/{resizable-RYzDqksM.js → resizable-DKOKD5be.js} +1 -1
- package/dist/client/assets/{resource-tabs-Dx00akPb.js → resource-tabs-UF1uUrPS.js} +1 -1
- package/dist/client/assets/{select-DXarH3zI.js → select-8RE8G2EV.js} +1 -1
- package/dist/client/assets/{settings-CppuOJKP.js → settings-WmaC0ugB.js} +1 -1
- package/dist/client/assets/shell-layout-DLeQwwOP.js +1 -0
- package/dist/client/assets/{spinner-BlgPNYJ_.js → spinner-CeWqo2ib.js} +1 -1
- package/dist/client/assets/{switch-D8JX4qkY.js → switch-CxhRshQs.js} +1 -1
- package/dist/client/assets/{textarea-B4gwvsMJ.js → textarea-DbQy5F3n.js} +1 -1
- package/dist/client/assets/{thread-history-popover-BGdJj9Uf.js → thread-history-popover-Dh1623de.js} +82 -45
- package/dist/client/assets/{tools-list-PNSOJy0p.js → tools-list-Bf2FOeAk.js} +1 -1
- package/dist/client/assets/{use-binding-BrFwEM85.js → use-binding-B-kSZTGy.js} +1 -1
- package/dist/client/assets/{use-connection-C0rtvbAv.js → use-connection-DFkAC4Is.js} +1 -1
- package/dist/client/assets/use-connection-resources-BYLrv2O6.js +1 -0
- package/dist/client/assets/{use-gateway-XK2Ec2c7.js → use-gateway-QZNjV_Br.js} +1 -1
- package/dist/client/assets/use-gateway-system-prompt-DowqNUnD.js +1 -0
- package/dist/client/assets/{use-list-state-CaOiitHv.js → use-list-state-oVkbwyL1.js} +1 -1
- package/dist/client/assets/{use-mcp-DP2e7Pak.js → use-mcp-B38V1Eo_.js} +1 -1
- package/dist/client/assets/{use-members-BZIlp51_.js → use-members-B5ZPlWxC.js} +1 -1
- package/dist/client/assets/{use-mobile-C9ZrGbF1.js → use-mobile-DKb1FXwT.js} +1 -1
- package/dist/client/assets/{use-organization-settings-CpuYghUf.js → use-organization-settings-DDkza1UL.js} +1 -1
- package/dist/client/assets/{use-tool-call-BLCuCQA5.js → use-tool-call-CkogDXv4.js} +1 -1
- package/dist/client/assets/useQueries-D02scwU5.js +1 -0
- package/dist/client/assets/useQuery-Cu8VEtZR.js +1 -0
- package/dist/client/assets/{value-C6pOmVvH.js → value-0Lc1LEd3.js} +1 -1
- package/dist/client/assets/{view-mode-toggle-BegVAMeC.js → view-mode-toggle-C8FGoH5Z.js} +1 -1
- package/dist/client/assets/{workflow-ChKb4zdL.js → workflow-C4jHNR-h.js} +1 -1
- package/dist/client/index.html +2 -2
- package/dist/server/cli.js +2 -2
- package/dist/server/migrate.js +2 -2
- package/dist/server/server.js +3 -3
- package/package.json +1 -1
- package/dist/client/assets/connection-detail-DgCsw2FN.js +0 -1
- package/dist/client/assets/constants-CxNag89_.js +0 -1
- package/dist/client/assets/formatDistanceToNow-Da1WFNC1.js +0 -1
- package/dist/client/assets/gateway-detail-ZvOmrysO.js +0 -1
- package/dist/client/assets/gateway-selector-zAzGBjF_.js +0 -1
- package/dist/client/assets/gateways-JihiLKrE.js +0 -1
- package/dist/client/assets/index-DOV_cVSz.js +0 -25
- package/dist/client/assets/localstorage-keys-Bmzia9Ql.js +0 -1
- package/dist/client/assets/page-CBEZJuHw.js +0 -35
- package/dist/client/assets/shell-layout-9hZXlinq.js +0 -19
- package/dist/client/assets/use-connection-resources-85AsmF-4.js +0 -1
- package/dist/client/assets/useQuery-CDC7rIFj.js +0 -1
package/dist/server/server.js
CHANGED
|
@@ -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)=>yY.parse(L));else Z=[yY.parse(W)]}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}let $=Z.some(re);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(sG)){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)=>re(L)),V=F?F.params.protocolVersion:Q.headers.get("mcp-protocol-version")??ht0;if(this._enableJsonResponse)return new Promise((L)=>{this._streamMapping.set(H,{resolveJson:L,cleanup:()=>{this._streamMapping.delete(H)}});for(let M of Z)if(sG(M))this._requestToStreamMapping.set(M.id,H);for(let M of Z)this.onmessage?.(M,{authInfo:X?.authInfo,requestInfo:G})});let q=new TextEncoder,z,B=new ReadableStream({start:(L)=>{z=L},cancel:()=>{this._streamMapping.delete(H)}}),D={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};if(this.sessionId!==void 0)D["mcp-session-id"]=this.sessionId;for(let L of Z)if(sG(L))this._streamMapping.set(H,{controller:z,encoder:q,cleanup:()=>{this._streamMapping.delete(H);try{z.close()}catch{}}}),this._requestToStreamMapping.set(L.id,H);await this.writePrimingEvent(z,q,H,V);for(let L of Z){let M,C;if(sG(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(B,{status:200,headers:D})}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&&!u3.includes(X))return this.createJsonErrorResponse(400,-32000,`Bad Request: Unsupported protocol version: ${X} (supported versions: ${u3.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(P5(Q)||rz(Q))Y=Q.id;if(Y===void 0){if(P5(Q)||rz(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(P5(Q)||rz(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 Ky=o(()=>{f9()});var xM=(...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 SQ1{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?xM(...this.callToolMiddlewares):null,X=()=>{let Y=new a3({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 r3({enableJsonResponse:Y.headers.get("Accept")?.includes("application/json")??!1});return await X().connect(J),await J.handleRequest(Y)}}}}function vQ1(Q){return new SQ1(Q)}var kQ1=o(()=>{$y();Ky();G1()});function B1(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:k60.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:k60.SpanStatusCode.ERROR,message:W.message}),G.recordException(W),W}finally{G.end()}})}}}var k60;var E6=o(()=>{k60=m6(Z1(),1)});function L6(Q){if(!Q.organization)throw Error("This operation requires organization scope");return Q.organization}function uQ(Q){return Q.auth.user?.id??Q.auth.apiKey?.userId}function UC6(Q){return!!(Q.auth.user||Q.auth.apiKey)}function C1(Q){if(!UC6(Q))throw Error("Authentication required")}var Hy,_Q1,yQ1,bQ1,fQ1,hQ1,xQ1,gQ1,uQ1,mQ1;var LU=o(()=>{G1();Hy=N.record(N.string(),N.array(N.string())),_Q1=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:Hy.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")}),yQ1=N.object({name:N.string().min(1).max(64).describe("Human-readable name for the API key"),permissions:Hy.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")}),bQ1=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:Hy.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")}),fQ1=N.object({}),hQ1=N.object({items:N.array(_Q1).describe("List of API keys (without key values)")}),xQ1=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:Hy.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.")}),gQ1=N.object({item:_Q1.describe("The updated API key (without key value)")}),uQ1=N.object({keyId:N.string().describe("ID of the API key to delete")}),mQ1=N.object({success:N.boolean().describe("Whether the deletion was successful"),keyId:N.string().describe("ID of the deleted API key")})});var _60;var lQ1=o(()=>{E6();LU();_60=B1({name:"API_KEY_CREATE",description:"Create a new API key with specified permissions. The key value is only returned once - store it securely!",inputSchema:yQ1,outputSchema:bQ1,handler:async(Q,X)=>{C1(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 y60;var dQ1=o(()=>{E6();LU();y60=B1({name:"API_KEY_DELETE",description:"Delete an API key. This instantly revokes the key - it can no longer be used for authentication.",inputSchema:uQ1,outputSchema:mQ1,handler:async(Q,X)=>{if(C1(X),await X.access.check(),!uQ(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 b60;var pQ1=o(()=>{E6();LU();b60=B1({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:fQ1,outputSchema:hQ1,handler:async(Q,X)=>{C1(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 f60;var cQ1=o(()=>{E6();LU();f60=B1({name:"API_KEY_UPDATE",description:"Update an existing API key's name, permissions, or metadata. Note: Key value cannot be changed or retrieved.",inputSchema:xQ1,outputSchema:gQ1,handler:async(Q,X)=>{if(C1(X),await X.access.check(),!uQ(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 nQ1=o(()=>{lQ1();dQ1();pQ1();cQ1();LU()});var DC6,NC6,h60;var iQ1=o(()=>{_3();G1();E6();Zy();O7();DC6=N.object({data:qt0.describe("Data for the new connection (id is auto-generated if not provided)")}),NC6=N.object({item:SJ.describe("The created connection entity")}),h60=B1({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",inputSchema:DC6,outputSchema:NC6,handler:async(Q,X)=>{C1(X);let Y=L6(X);await X.access.check();let J=uQ(X);if(!J)throw Error("User ID required to create connection");let G={...Q.data,organization_id:Y.id,created_by:J},W=await OU({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,xz.SELF(Y.id),{type:"connection.created",data:$}),{item:$}}})});function gM(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)=>gM(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)&&gM(Q[G],X[G]))}return!1}function uC6(){return(Q)=>{if(!Array.isArray(Q))return!0;let X=[];return Q.every((Y)=>{if(X.some((G)=>gM(Y,G)))return!1;return X.push(Y),!0})}}function Fy(Q,X){return Q.safeParse(X).success}function U9(Q){if(typeof Q==="boolean")return Q?N.any():N.never();let X={};for(let G of QI6)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 XI6)J=G.apply(J,Q);return J}var OC6=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()}}},LC6=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}},wC6=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}},MC6=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}}},PC6=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()}}},TC6=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`})}}},AC6=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`})}}},EC6=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)}}}},jC6=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)}}},CC6=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)}}},IC6=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}}},RC6=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}}},SC6=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}`})}}},vC6=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())}}},kC6=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)}},_C6=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)}},yC6=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=U9(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())}},bC6=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)=>U9(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}},fC6=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()}},hC6=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()}}},xC6=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`})}}},gC6=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`})}}},mC6=class{apply(Q,X){if(!X.not)return Q;let Y=U9(X.not);return Q.refine((J)=>!Fy(Y,J),{message:"Value must not match the 'not' schema"})}},lC6=class{apply(Q,X){if(X.uniqueItems!==!0)return Q;return Q.refine(uC6(),{message:"Array items must be unique"})}},dC6=class{apply(Q,X){if(!X.allOf||X.allOf.length===0)return Q;return X.allOf.map((J)=>U9(J)).reduce((J,G)=>N.intersection(J,G),Q)}},pC6=class{apply(Q,X){if(!X.anyOf||X.anyOf.length===0)return Q;let Y=X.anyOf.length===1?U9(X.anyOf[0]):N.union([U9(X.anyOf[0]),U9(X.anyOf[1]),...X.anyOf.slice(2).map((J)=>U9(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)=>U9(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"})}},nC6=class{apply(Q,X){let Y=X;if(Y.prefixItems&&Array.isArray(Y.prefixItems)){let G=Y.prefixItems.map((W)=>U9(W));return Q.refine((W)=>{if(!Array.isArray(W))return!0;for(let Z=0;Z<Math.min(W.length,G.length);Z++)if(!Fy(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=U9(Y.items);for(let $=G.length;$<W.length;$++)if(!Fy(Z,W[$]))return!1}}return!0},{message:"Array does not match prefixItems schema"})}return Q}},iC6=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]=U9(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(!U9(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"})}},aC6=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)=>gM(J,G))},{message:"Value must match one of the enum values"})}},rC6=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)=>gM(J,Y),{message:"Value must equal the const value"})}},oC6=class{apply(Q,X){if(X.description)Q=Q.describe(X.description);return Q}},sC6=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))}},tC6=class{apply(Q,X){var Y;let J=X;if(J.contains===void 0)return Q;let G=U9(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(Fy(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"})}},eC6=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)}},QI6,XI6;var aQ1=o(()=>{r6();r6();r6();r6();r6();r6();r6();r6();r6();r6();r6();r6();r6();r6();QI6=[new LC6,new wC6,new OC6,new MC6,new PC6,new vC6,new hC6,new TC6,new AC6,new EC6,new jC6,new CC6,new IC6,new RC6,new SC6,new bC6,new kC6,new _C6,new yC6,new xC6,new gC6,new fC6],XI6=[new sC6,new aC6,new rC6,new dC6,new pC6,new cC6,new nC6,new iC6,new tC6,new mC6,new lC6,new eC6,new oC6]});function YI6(Q){let X=globalThis.DOMException;return typeof X=="function"?new X(Q,"SyntaxError"):SyntaxError(Q)}function g60(Q){return Q instanceof Error?"errors"in Q&&Array.isArray(Q.errors)?Q.errors.map(g60).join(", "):("cause"in Q)&&Q.cause instanceof Error?`${Q}: ${g60(Q.cause)}`:Q.message:`${Q}`}function rQ1(Q){return{type:Q.type,message:Q.message,code:Q.code,defaultPrevented:Q.defaultPrevented,cancelable:Q.cancelable,timeStamp:Q.timeStamp}}function JI6(){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 x60,sQ1=(Q)=>{throw TypeError(Q)},i60=(Q,X,Y)=>X.has(Q)||sQ1("Cannot "+Y),S6=(Q,X,Y)=>(i60(Q,X,"read from private field"),Y?Y.call(Q):X.get(Q)),zQ=(Q,X,Y)=>X.has(Q)?sQ1("Cannot add the same private member more than once"):X instanceof WeakSet?X.add(Q):X.set(Q,Y),M8=(Q,X,Y,J)=>(i60(Q,X,"write to private field"),X.set(Q,Y),Y),_7=(Q,X,Y)=>(i60(Q,X,"access private method"),Y),XY,o3,wU,Vy,qy,lM,TU,dM,n$,MU,AU,PU,uM,v5,u60,m60,l60,oQ1,d60,p60,mM,c60,n60,EU;var tQ1=o(()=>{A60();x60=class x60 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(rQ1(this),X)}[Symbol.for("Deno.customInspect")](Q,X){return Q(rQ1(this),X)}};EU=class EU extends EventTarget{constructor(Q,X){var Y,J;super(),zQ(this,v5),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,zQ(this,XY),zQ(this,o3),zQ(this,wU),zQ(this,Vy),zQ(this,qy),zQ(this,lM),zQ(this,TU),zQ(this,dM,null),zQ(this,n$),zQ(this,MU),zQ(this,AU,null),zQ(this,PU,null),zQ(this,uM,null),zQ(this,m60,async(G)=>{var W;S6(this,MU).reset();let{body:Z,redirected:$,status:K,headers:H}=G;if(K===204){_7(this,v5,mM).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if($?M8(this,wU,new URL(G.url)):M8(this,wU,void 0),K!==200){_7(this,v5,mM).call(this,`Non-200 status code (${K})`,K);return}if(!(H.get("content-type")||"").startsWith("text/event-stream")){_7(this,v5,mM).call(this,'Invalid content type, expected "text/event-stream"',K);return}if(S6(this,XY)===this.CLOSED)return;M8(this,XY,this.OPEN);let F=new Event("open");if((W=S6(this,uM))==null||W.call(this,F),this.dispatchEvent(F),typeof Z!="object"||!Z||!("getReader"in Z)){_7(this,v5,mM).call(this,"Invalid response body, expected a web ReadableStream",K),this.close();return}let V=new TextDecoder,q=Z.getReader(),z=!0;do{let{done:B,value:D}=await q.read();D&&S6(this,MU).feed(V.decode(D,{stream:!B})),B&&(z=!1,S6(this,MU).reset(),_7(this,v5,c60).call(this))}while(z)}),zQ(this,l60,(G)=>{M8(this,n$,void 0),!(G.name==="AbortError"||G.type==="aborted")&&_7(this,v5,c60).call(this,g60(G))}),zQ(this,d60,(G)=>{typeof G.id=="string"&&M8(this,dM,G.id);let W=new MessageEvent(G.event||"message",{data:G.data,origin:S6(this,wU)?S6(this,wU).origin:S6(this,o3).origin,lastEventId:G.id||""});S6(this,PU)&&(!G.event||G.event==="message")&&S6(this,PU).call(this,W),this.dispatchEvent(W)}),zQ(this,p60,(G)=>{M8(this,lM,G)}),zQ(this,n60,()=>{M8(this,TU,void 0),S6(this,XY)===this.CONNECTING&&_7(this,v5,u60).call(this)});try{if(Q instanceof URL)M8(this,o3,Q);else if(typeof Q=="string")M8(this,o3,new URL(Q,JI6()));else throw Error("Invalid URL")}catch{throw YI6("An invalid or illegal string was specified")}M8(this,MU,Wy({onEvent:S6(this,d60),onRetry:S6(this,p60)})),M8(this,XY,this.CONNECTING),M8(this,lM,3000),M8(this,qy,(Y=X==null?void 0:X.fetch)!=null?Y:globalThis.fetch),M8(this,Vy,(J=X==null?void 0:X.withCredentials)!=null?J:!1),_7(this,v5,u60).call(this)}get readyState(){return S6(this,XY)}get url(){return S6(this,o3).href}get withCredentials(){return S6(this,Vy)}get onerror(){return S6(this,AU)}set onerror(Q){M8(this,AU,Q)}get onmessage(){return S6(this,PU)}set onmessage(Q){M8(this,PU,Q)}get onopen(){return S6(this,uM)}set onopen(Q){M8(this,uM,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(){S6(this,TU)&&clearTimeout(S6(this,TU)),S6(this,XY)!==this.CLOSED&&(S6(this,n$)&&S6(this,n$).abort(),M8(this,XY,this.CLOSED),M8(this,n$,void 0))}};XY=new WeakMap,o3=new WeakMap,wU=new WeakMap,Vy=new WeakMap,qy=new WeakMap,lM=new WeakMap,TU=new WeakMap,dM=new WeakMap,n$=new WeakMap,MU=new WeakMap,AU=new WeakMap,PU=new WeakMap,uM=new WeakMap,v5=new WeakSet,u60=function(){M8(this,XY,this.CONNECTING),M8(this,n$,new AbortController),S6(this,qy)(S6(this,o3),_7(this,v5,oQ1).call(this)).then(S6(this,m60)).catch(S6(this,l60))},m60=new WeakMap,l60=new WeakMap,oQ1=function(){var Q;let X={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...S6(this,dM)?{"Last-Event-ID":S6(this,dM)}:void 0},cache:"no-store",signal:(Q=S6(this,n$))==null?void 0:Q.signal};return"window"in globalThis&&(X.credentials=this.withCredentials?"include":"same-origin"),X},d60=new WeakMap,p60=new WeakMap,mM=function(Q,X){var Y;S6(this,XY)!==this.CLOSED&&M8(this,XY,this.CLOSED);let J=new x60("error",{code:X,message:Q});(Y=S6(this,AU))==null||Y.call(this,J),this.dispatchEvent(J)},c60=function(Q,X){var Y;if(S6(this,XY)===this.CLOSED)return;M8(this,XY,this.CONNECTING);let J=new x60("error",{code:X,message:Q});(Y=S6(this,AU))==null||Y.call(this,J),this.dispatchEvent(J),M8(this,TU,setTimeout(S6(this,n60),S6(this,lM)))},n60=new WeakMap,EU.CONNECTING=0,EU.OPEN=1,EU.CLOSED=2});class a60{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=n_(X?.fetch,X?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new QY("No auth provider");let Q;try{Q=await v7(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 QY;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=qU(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 EU(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}=NU(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 eQ1(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=yY.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 QY("No auth provider");if(await v7(this._authProvider,{serverUrl:this._url,authorizationCode:Q,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new QY("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}=NU(J);if(this._resourceMetadataUrl=W,this._scope=Z,await v7(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new QY;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 eQ1;var Q91=o(()=>{tQ1();f9();M60();eQ1=class eQ1 extends Error{constructor(Q,X,Y){super(`SSE error: ${X}`);this.code=Q,this.event=Y}}});class r60{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,GI6),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=yY.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 GI6="mcp";var X91=o(()=>{f9()});function WI6(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 o60;var Y91=o(()=>{fM();o60=class o60 extends k7{constructor(Q,X){super(Q,X)}send(Q,X){let Y=WI6(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 J91,G91=async(Q,X,Y)=>{let J=ZI6(Q.connection,X,Y);if(!J)throw Error("Unknown MCP connection type");let G=new J91({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:$})}}},ZI6=(Q,X,Y)=>{if(Q.type==="Websocket")return new r60(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 a60(new URL(Q.url),W)}return new o60(new URL(Q.url),{requestInit:{headers:G,signal:X,credentials:"include"}})};var W91=o(()=>{HU();Q91();X91();f9();Y91();J91=class J91 extends hJ{constructor(Q,X){super(Q,X)}async listTools(Q,X){return await this.request({method:"tools/list",params:Q},WM,X)}}});function $91(Q){let X=(Y)=>{if("connection"in Q)return G91({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:z}=await X(V);if(Q?.streamable?.[String(H)])return z(String(H),K);let{structuredContent:B,isError:D,content:L}=await q.callTool({name:String(H),arguments:K});if(D){let M=L?.[0]?.text,C=typeof M==="string"?$I6(M):null,A=C?.code&&typeof Q?.getErrorByStatusCode==="function"?Q.getErrorByStatusCode(C.code,C.message,C.traceId):null;if(A)throw A;throw Error(`Tool ${String(H)} returned an error: ${JSON.stringify(B??L)}`)}return B}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)=>Z91(H,G))}return G.asTool=async()=>{let H=(await Z()??[]).find((F)=>F.name===J);if(!H)throw Error(`Tool ${J} not found`);return Z91(H,G)},G}})}var $I6=(Q)=>{try{return JSON.parse(Q)}catch{return Q}},zy,Z91=(Q,X)=>{return{...Q,id:Q.name,inputSchema:Q.inputSchema?U9(Q.inputSchema):void 0,outputSchema:Q.outputSchema?U9(Q.outputSchema):void 0,execute:(Y)=>{return X(Y.context,Q.name)}}};var K91=o(()=>{aQ1();W91();zy=new Map});function Uy(Q){return $91(Q)}var yk4;var H91=o(()=>{K91();yk4=new Proxy({},{get(Q,X){if(X==="toJSON")return null;if(X==="forConnection")return(Y)=>Uy({connection:Y});return global[X]}})});function By(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 jU=(Q)=>{return{...By(Q),forClient:(X)=>{return Uy({client:X,streamable:Q.reduce((Y,J)=>{return Y[J.name]=J.streamable===!0,Y},{})})},forConnection:(X)=>{return Uy({connection:X,streamable:Q.reduce((Y,J)=>{return Y[J.name]=J.streamable===!0,Y},{})})}}};var pM=o(()=>{H91()});function nM(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 t60(Q){return N.object({item:Q.nullable().describe("The retrieved item, or null if not found")})}function FI6(Q){return N.object({data:Q.partial().describe("Data for the new entity (id may be auto-generated)")})}function VI6(Q){return N.object({item:Q.describe("The created entity with generated id")})}function qI6(Q){return N.object({id:N.string().describe("ID of the entity to update"),data:Q.partial().describe("Partial entity data to update")})}function zI6(Q){return N.object({item:Q.describe("The updated entity")})}function Q40(Q){return N.object({item:Q.describe("The deleted entity")})}function IU(Q,X,Y){let J=Q.toUpperCase(),G=Y?.readOnly??!1,W=[{name:`COLLECTION_${J}_LIST`,inputSchema:cM,outputSchema:nM(X)},{name:`COLLECTION_${J}_GET`,inputSchema:s60,outputSchema:t60(X)}];if(!G)W.push({name:`COLLECTION_${J}_CREATE`,inputSchema:FI6(X),outputSchema:VI6(X),opt:!0},{name:`COLLECTION_${J}_UPDATE`,inputSchema:qI6(X),outputSchema:zI6(X),opt:!0},{name:`COLLECTION_${J}_DELETE`,inputSchema:e60,outputSchema:Q40(X),opt:!0});return W}var CU,KI6,F91,HI6,cM,s60,e60;var i$=o(()=>{G1();CU=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()}),KI6=N.object({field:N.array(N.string()),operator:N.enum(["eq","gt","gte","lt","lte","in","like","contains"]),value:N.unknown()}),F91=N.lazy(()=>N.union([KI6,N.object({operator:N.enum(["and","or","not"]),conditions:N.array(F91)})])),HI6=N.object({field:N.array(N.string()),direction:N.enum(["asc","desc"]),nulls:N.enum(["first","last"]).optional()}),cM=N.object({where:F91.optional().describe("Filter expression"),orderBy:N.array(HI6).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")});s60=N.object({id:N.string().describe("ID of the entity to retrieve")});e60=N.object({id:N.string().describe("ID of the entity to delete")})});var UI6,V91,dk4;var q91=o(()=>{G1();i$();UI6=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()}),V91=CU.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(UI6).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()})}),dk4=IU("registry_app",V91,{readOnly:!0})});var z91,U91,B91,D91,N91,X40;var O91=o(()=>{G1();pM();z91=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)")}),U91=N.object({events:N.array(z91).min(1).describe("Batch of CloudEvents to process")}),B91=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")}),D91=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(),B91).optional().describe("Per-event results keyed by event ID")}),N91=[{name:"ON_EVENTS",inputSchema:U91,outputSchema:D91}],X40=jU(N91)});var iM,aM,rM,oM,L91,w91,sM,tM,eM,QP,XP,YP,JP,GP,M91,BI6;var P91=o(()=>{G1();pM();iM=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.")}),aM=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")}),rM=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")}),oM=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")})}),L91=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")}),sM=N.object({subscriptions:N.array(L91).describe("Desired subscriptions - system will create/update/delete to match")}),tM=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")}),eM=N.object({subscriptionId:N.string().describe("Subscription ID to remove")}),QP=N.object({success:N.boolean().describe("Whether unsubscribe was successful"),subscriptionId:N.string().describe("Subscription ID that was removed")}),XP=N.object({eventId:N.string().describe("Event ID to cancel")}),YP=N.object({success:N.boolean().describe("Whether cancellation was successful"),eventId:N.string().describe("Event ID that was cancelled")}),JP=N.object({eventId:N.string().describe("Event ID to acknowledge")}),GP=N.object({success:N.boolean().describe("Whether ACK was successful"),eventId:N.string().describe("Event ID that was acknowledged")}),M91=[{name:"EVENT_PUBLISH",inputSchema:iM,outputSchema:aM},{name:"EVENT_SUBSCRIBE",inputSchema:rM,outputSchema:oM},{name:"EVENT_UNSUBSCRIBE",inputSchema:eM,outputSchema:QP},{name:"EVENT_CANCEL",inputSchema:XP,outputSchema:YP},{name:"EVENT_ACK",inputSchema:JP,outputSchema:GP},{name:"EVENT_SYNC_SUBSCRIPTIONS",inputSchema:sM,outputSchema:tM}],BI6=jU(M91)});var Dy=o(()=>{pM();q91();O91();P91()});var DI6,NI6,T91;var A91=o(()=>{G1();i$();DI6=CU.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")}),NI6=IU("assistant",DI6),T91=[...NI6]});var WP,y7,j91,OI6,LI6,C91,wI6,MI6,PI6,TI6,AI6,EI6,I91,jI6,CI6,II6,RI6,SI6,vI6,kI6,_I6,yI6,bI6,H_4,fI6,F_4,E91,hI6,xI6,Y40,R91;var J40=o(()=>{G1();pM();i$();WP=N.lazy(()=>N.union([N.null(),N.string(),N.number(),N.boolean(),N.record(N.string(),WP),N.array(WP)])),y7=N.record(N.string(),N.record(N.string(),WP)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),j91=N.object({type:N.literal("text"),text:N.string().describe("The text content"),providerOptions:y7}),OI6=N.object({type:N.literal("text"),text:N.string().describe("The text content"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),LI6=N.string().describe("File data as URL string"),C91=N.object({type:N.literal("file"),filename:N.string().optional().describe("Optional filename of the file"),data:LI6,mediaType:N.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:y7}),wI6=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")}),MI6=N.object({type:N.literal("reasoning"),text:N.string().describe("The reasoning text"),providerOptions:y7}),PI6=N.object({type:N.literal("reasoning"),text:N.string().describe("The reasoning text"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),TI6=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:y7}),AI6=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")}),EI6=N.union([N.object({type:N.literal("text"),value:N.string()}),N.object({type:N.literal("json"),value:WP}),N.object({type:N.literal("error-text"),value:N.string()}),N.object({type:N.literal("error-json"),value:WP}),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")})]))})]),I91=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:EI6.describe("Result of the tool call"),result:N.unknown().describe("Unknown result of the tool call"),providerOptions:y7}),jI6=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")}),CI6=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")})]),II6=N.object({role:N.literal("system"),content:N.string().describe("System message content"),providerOptions:y7}),RI6=N.object({role:N.literal("user"),content:N.array(N.union([j91,C91])).describe("User message content parts (text or file)"),providerOptions:y7}),SI6=N.object({role:N.literal("assistant"),content:N.array(N.union([j91,C91,MI6,TI6,I91])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:y7}),vI6=N.object({role:N.literal("tool"),content:N.array(I91).describe("Tool message content (tool results)"),providerOptions:y7}),kI6=N.union([II6,RI6,SI6,vI6]),_I6=N.array(kI6).describe("A list of messages forming the prompt"),yI6=N.object({prompt:_I6.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")}),bI6=N.object({content:N.array(N.union([OI6,wI6,PI6,AI6,jI6,CI6])).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")}),H_4=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")}),fI6=N.object({supportedUrls:N.record(N.string(),N.array(N.string())).describe("Supported URL patterns by media type for the provider")}),F_4=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()}),E91=N.object({modelId:N.string().describe("The ID of the model"),callOptions:yI6}),hI6=CU.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()}),xI6=IU("llm",hI6,{readOnly:!0}),Y40=[{name:"LLM_METADATA",inputSchema:N.object({modelId:N.string().describe("The ID of the model")}),outputSchema:fI6},{name:"LLM_DO_STREAM",inputSchema:E91,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:E91,outputSchema:bI6},...xI6],R91=jU(Y40)});function uI6(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 a$(Q){return typeof Q==="string"||typeof Q==="number"}function Ny(Q,X){if("conditions"in X){let{operator:$,conditions:K}=X;switch($){case"and":return K.every((H)=>Ny(Q,H));case"or":return K.some((H)=>Ny(Q,H));case"not":return!K.every((H)=>Ny(Q,H));default:return!0}}let{field:Y,operator:J,value:G}=X,W=Y.join("."),Z=G40(Q,W);switch(J){case"eq":return Z===G;case"gt":return a$(Z)&&a$(G)&&Z>G;case"gte":return a$(Z)&&a$(G)&&Z>=G;case"lt":return a$(Z)&&a$(G)&&Z<G;case"lte":return a$(Z)&&a$(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 $=uI6(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 G40(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 mI6(Q,X){return[...Q].sort((Y,J)=>{for(let G of X){let W=G.field.join("."),Z=G40(Y,W),$=G40(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 gI6,lI6,dI6,W40;var S91=o(()=>{Dy();A91();i$();J40();G1();E6();O7();gI6={LLM:Y40,ASSISTANTS:T91};lI6=cM.extend({binding:N.union([N.object({}).passthrough(),N.string()]).optional()}),dI6=nM(SJ),W40=B1({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",inputSchema:lI6,outputSchema:dI6,handler:async(Q,X)=>{await X.access.check();let Y=L6(X),J=Q.binding?typeof Q.binding==="string"?(()=>{let q=gI6[Q.binding.toUpperCase()];if(!q)throw Error(`Unknown binding: ${Q.binding}`);return q})():Q.binding:void 0,G=J?By(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((B)=>({name:B.name,inputSchema:B.inputSchema,outputSchema:B.outputSchema})))?q:null})).then((q)=>q.filter((z)=>z!==null)):W;if(Q.where)Z=Z.filter((q)=>Ny(q,Q.where));if(Q.orderBy&&Q.orderBy.length>0)Z=mI6(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 pI6,Z40;var v91=o(()=>{i$();E6();O7();pI6=t60(SJ),Z40=B1({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",inputSchema:s60,outputSchema:pI6,handler:async(Q,X)=>{let Y=L6(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 Oy=(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 k91(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 nI6(Q){if(typeof Q==="object"&&Q!==null&&"value"in Q){let X=Q.value;if(typeof X==="string")return X}return null}function $40(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,$=Oy(W,Q),K=nI6($);if(K){if(!Y[K])Y[K]=[];Y[K].push(Z)}}return Y}function _91(Q,X){let Y=$40(Q,X);return new Set(Object.keys(Y).filter((J)=>J!=="*"))}var K40=()=>{};class b7{db;vault;constructor(Q,X){this.db=Q;this.vault=X}async get(Q,X){let Y=this.db.selectFrom("downstream_tokens").selectAll().where("connectionId","=",Q),J=await(X?Y.where("userId","=",X):Y.where("userId","is",null)).executeTakeFirst();if(!J)return null;return this.decryptToken(J)}async upsert(Q){let X=new Date().toISOString(),Y=await this.vault.encrypt(Q.accessToken),J=Q.refreshToken?await this.vault.encrypt(Q.refreshToken):null,G=Q.clientSecret?await this.vault.encrypt(Q.clientSecret):null;return await this.db.transaction().execute(async(W)=>{let Z=W.selectFrom("downstream_tokens").select(["id","createdAt"]).where("connectionId","=",Q.connectionId),$=await(Q.userId?Z.where("userId","=",Q.userId):Z.where("userId","is",null)).executeTakeFirst();if($)return await W.updateTable("downstream_tokens").set({accessToken:Y,refreshToken:J,scope:Q.scope,expiresAt:Q.expiresAt?.toISOString()??null,clientId:Q.clientId,clientSecret:G,tokenEndpoint:Q.tokenEndpoint,updatedAt:X}).where("id","=",$.id).execute(),{id:$.id,connectionId:Q.connectionId,userId:Q.userId,accessToken:Q.accessToken,refreshToken:Q.refreshToken,scope:Q.scope,expiresAt:Q.expiresAt,createdAt:$.createdAt,updatedAt:X,clientId:Q.clientId,clientSecret:Q.clientSecret,tokenEndpoint:Q.tokenEndpoint};let K=vJ("dtok");return await W.insertInto("downstream_tokens").values({id:K,connectionId:Q.connectionId,userId:Q.userId,accessToken:Y,refreshToken:J,scope:Q.scope,expiresAt:Q.expiresAt?.toISOString()??null,clientId:Q.clientId,clientSecret:G,tokenEndpoint:Q.tokenEndpoint,createdAt:X,updatedAt:X}).execute(),{id:K,connectionId:Q.connectionId,userId:Q.userId,accessToken:Q.accessToken,refreshToken:Q.refreshToken,scope:Q.scope,expiresAt:Q.expiresAt,createdAt:X,updatedAt:X,clientId:Q.clientId,clientSecret:Q.clientSecret,tokenEndpoint:Q.tokenEndpoint}})}async delete(Q,X){let Y=this.db.deleteFrom("downstream_tokens").where("connectionId","=",Q);await(X?Y.where("userId","=",X):Y.where("userId","is",null)).execute()}async deleteByConnection(Q){await this.db.deleteFrom("downstream_tokens").where("connectionId","=",Q).execute()}isExpired(Q,X=0){if(!Q.expiresAt)return!1;let J=(Q.expiresAt instanceof Date?Q.expiresAt:new Date(Q.expiresAt)).getTime();if(Number.isNaN(J))return!0;return J-X<Date.now()}async decryptToken(Q){let X=await this.vault.decrypt(Q.accessToken),Y=Q.refreshToken?await this.vault.decrypt(Q.refreshToken):null,J=Q.clientSecret?await this.vault.decrypt(Q.clientSecret):null;return{id:Q.id,connectionId:Q.connectionId,userId:Q.userId,accessToken:X,refreshToken:Y,scope:Q.scope,expiresAt:Q.expiresAt,createdAt:Q.createdAt,updatedAt:Q.updatedAt,clientId:Q.clientId,clientSecret:J,tokenEndpoint:Q.tokenEndpoint}}}var Ly=o(()=>{yw()});async function rI6(Q,X,Y,J){for(let W of X){if(W==="*")continue;let[Z]=k91(W),$=Oy(Z,Q);if($===void 0||$===null)throw Error(`Scope references key "${Z}" but it's not present in state`)}let G=_91(Q,X);for(let W of G){if(W===w5.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 iI6,aI6,H40;var y91=o(()=>{K40();_3();Ly();G1();E6();Zy();O7();iI6=N.object({id:N.string().describe("ID of the connection to update"),data:zt0.describe("Partial connection data to update")}),aI6=N.object({item:SJ.describe("The updated connection entity")});H40=B1({name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update an existing MCP connection in the organization",inputSchema:iI6,outputSchema:aI6,handler:async(Q,X)=>{C1(X);let Y=L6(X);await X.access.check();let J=uQ(X);if(!J)throw Error("User ID required to update connection");let{id:G,data:W}=Q,Z=await X.storage.connections.findById(G);if(!Z||Z.organization_id!==Y.id)throw Error("Connection not found in organization");let $=W.configuration_state??Z.configuration_state,K=W.configuration_scopes??Z.configuration_scopes??[];if(W.configuration_state!==void 0||W.configuration_scopes!==void 0){if(W.configuration_state!==void 0)$=W.configuration_state;else if($===null)$={};if(W.configuration_scopes!==void 0)K=W.configuration_scopes??[];if(K.length>0&&$)await rI6($,K,Y.id,X)}let H=W.connection_token??Z.connection_token;if(!H)try{let D=await new b7(X.db,X.vault).get(G,J);if(D?.accessToken)H=D.accessToken}catch{}let F=await OU({id:Z.id,title:W.title??Z.title,connection_type:W.connection_type??Z.connection_type,connection_url:W.connection_url??Z.connection_url,connection_token:H,connection_headers:W.connection_headers??Z.connection_headers}).catch(()=>null),V=F?.length?F:null,q={...W,tools:V,configuration_state:$,configuration_scopes:K},z=await X.storage.connections.update(G,q);if((W.configuration_state!==void 0||W.configuration_scopes!==void 0)&&$&&K.length>0)try{await(await X.createMCPProxy(G)).client.callTool({name:"ON_MCP_CONFIGURATION",arguments:{state:$,scopes:K}})}catch(B){console.error("Failed to invoke ON_MCP_CONFIGURATION callback",B)}return{item:z}}})});var F40;var b91=o(()=>{i$();E6();O7();F40=B1({name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete a connection",inputSchema:e60,outputSchema:Q40(SJ),handler:async(Q,X)=>{C1(X);let Y=L6(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 V40;var f91=o(()=>{G1();E6();V40=B1({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=L6(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 h91=o(()=>{iQ1();S91();v91();y91();b91();f91()});import{sql as t6}from"kysely";function x91(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 tI6(Q,X){let Y=Q;for(let G=X.length;G>=1;G--){let W=`$${G}`;if(Y.includes(W))Y=Y.replaceAll(W,x91(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=x91(X[G]);Y=Y.slice(0,W)+Z+Y.slice(W+1)}return Y}function g91(Q){return Q.replace(/-/g,"_")}function QR6(Q){return`app_${g91(Q)}`}function XR6(Q){return`app_role_${g91(Q)}`}function YR6(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 JR6(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 GR6(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(YR6(G))return await JR6(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 sI6,eI6,u91;var m91=o(()=>{G1();E6();sI6=N.object({results:N.array(N.unknown()).optional(),success:N.boolean().optional()});eI6=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()});u91=B1({name:"DATABASES_RUN_SQL",description:"Run a SQL query against the database",inputSchema:eI6,outputSchema:N.object({result:N.array(sI6)}),handler:async(Q,X)=>{C1(X),await X.access.check();let Y=tI6(Q.sql,Q.params||[]);if(!X.connectionId)throw Error("Connection context required for database access");let J=QR6(X.connectionId),G=XR6(X.connectionId);return{result:[{results:(await GR6(X.db,J,G,Y)).rows,success:!0}]}}})});var l91,ZR6,d91;var f7=o(()=>{G1();Dy();l91=N.object({connectionId:N.string().optional().describe("Filter subscriptions by connection ID (optional)")}),ZR6=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")}),d91=N.object({subscriptions:N.array(ZR6).describe("List of subscriptions")})});var q40;var p91=o(()=>{E6();f7();q40=B1({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:iM,outputSchema:aM,handler:async(Q,X)=>{C1(X);let Y=L6(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 z40;var c91=o(()=>{E6();f7();z40=B1({name:"EVENT_SUBSCRIBE",description:"Subscribe to events of a specific type. The subscriber is automatically set to the caller's connection.",inputSchema:rM,outputSchema:oM,handler:async(Q,X)=>{C1(X);let Y=L6(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 U40;var n91=o(()=>{E6();f7();U40=B1({name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events by removing a subscription.",inputSchema:eM,outputSchema:QP,handler:async(Q,X)=>{C1(X);let Y=L6(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 B40;var i91=o(()=>{E6();f7();B40=B1({name:"EVENT_CANCEL",description:"Cancel a recurring event to stop future deliveries. Only the publisher can cancel their own events.",inputSchema:XP,outputSchema:YP,handler:async(Q,X)=>{C1(X);let Y=L6(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 D40;var a91=o(()=>{E6();f7();D40=B1({name:"EVENT_ACK",description:"Acknowledge delivery of an event. Call after successfully processing an event received via ON_EVENTS with retryAfter.",inputSchema:JP,outputSchema:GP,handler:async(Q,X)=>{C1(X);let Y=L6(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 N40;var r91=o(()=>{E6();f7();N40=B1({name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions, optionally filtered by connection ID.",inputSchema:l91,outputSchema:d91,handler:async(Q,X)=>{C1(X);let Y=L6(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 O40;var o91=o(()=>{E6();f7();O40=B1({name:"EVENT_SYNC_SUBSCRIPTIONS",description:"Sync subscriptions to desired state. Creates new, deletes removed, updates changed filters. Subscriptions are identified by (eventType, publisher).",inputSchema:sM,outputSchema:tM,handler:async(Q,X)=>{C1(X);let Y=L6(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 s91=o(()=>{p91();c91();n91();i91();a91();r91();o91();f7()});var L40,w40,KR6,JW,t91,e91;var RU=o(()=>{G1();L40=N.enum(["inclusion","exclusion"]).describe("Tool selection mode: 'inclusion' = include selected (default), 'exclusion' = exclude selected"),w40=N.enum(["passthrough","smart_tool_selection","code_execution"]).describe("Gateway tool selection strategy: 'passthrough' (default), 'smart_tool_selection', or 'code_execution'"),KR6=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.")}),JW=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:w40.describe("Gateway behavior strategy (metadata for now): 'passthrough', 'smart_tool_selection', or 'code_execution'"),tool_selection_mode:L40.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(KR6).describe("Connections with their selected tools (behavior depends on tool_selection_mode)")}),t91=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:w40.optional().default("passthrough").describe("Gateway behavior strategy (defaults to 'passthrough')"),tool_selection_mode:L40.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)")}),e91=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:w40.optional().describe("New gateway behavior strategy"),tool_selection_mode:L40.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 HR6,FR6,M40;var QX1=o(()=>{G1();E6();RU();HR6=N.object({data:t91.describe("Data for the new gateway")}),FR6=N.object({item:JW.describe("The created gateway entity")}),M40=B1({name:"COLLECTION_GATEWAY_CREATE",description:"Create a new MCP gateway in the organization",inputSchema:HR6,outputSchema:FR6,handler:async(Q,X)=>{C1(X);let Y=L6(X);await X.access.check();let J=uQ(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 VR6(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 r$(Q){return typeof Q==="string"||typeof Q==="number"}function P40(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 qR6(Q,X){return Q.connections.some((Y)=>Y.connection_id===X)}function wy(Q,X){if("conditions"in X){let{operator:$,conditions:K}=X;switch($){case"and":return K.every((H)=>wy(Q,H));case"or":return K.some((H)=>wy(Q,H));case"not":return!K.every((H)=>wy(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 qR6(Q,G)}let Z=P40(Q,W);switch(J){case"eq":return Z===G;case"gt":return r$(Z)&&r$(G)&&Z>G;case"gte":return r$(Z)&&r$(G)&&Z>=G;case"lt":return r$(Z)&&r$(G)&&Z<G;case"lte":return r$(Z)&&r$(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 $=VR6(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 zR6(Q,X){return[...Q].sort((Y,J)=>{for(let G of X){let W=G.field.join("."),Z=P40(Y,W),$=P40(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 UR6,BR6,T40;var XX1=o(()=>{i$();E6();RU();UR6=cM,BR6=nM(JW),T40=B1({name:"COLLECTION_GATEWAY_LIST",description:"List all MCP gateways in the organization",inputSchema:UR6,outputSchema:BR6,handler:async(Q,X)=>{await X.access.check();let Y=L6(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)=>wy(V,Q.where));if(Q.orderBy&&Q.orderBy.length>0)W=zR6(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 DR6,NR6,A40;var YX1=o(()=>{G1();E6();RU();DR6=N.object({id:N.string().describe("ID of the gateway to retrieve")}),NR6=N.object({item:JW.nullable().describe("The retrieved gateway, or null if not found")}),A40=B1({name:"COLLECTION_GATEWAY_GET",description:"Get an MCP gateway by ID",inputSchema:DR6,outputSchema:NR6,handler:async(Q,X)=>{C1(X);let Y=L6(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 OR6,LR6,E40;var JX1=o(()=>{G1();E6();RU();OR6=N.object({id:N.string().describe("ID of the gateway to update"),data:e91.describe("Partial gateway data to update")}),LR6=N.object({item:JW.describe("The updated gateway entity")}),E40=B1({name:"COLLECTION_GATEWAY_UPDATE",description:"Update an MCP gateway",inputSchema:OR6,outputSchema:LR6,handler:async(Q,X)=>{C1(X);let Y=L6(X);await X.access.check();let J=uQ(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 wR6,MR6,j40;var GX1=o(()=>{G1();E6();RU();wR6=N.object({id:N.string().describe("ID of the gateway to delete")}),MR6=N.object({item:JW.describe("The deleted gateway entity")}),j40=B1({name:"COLLECTION_GATEWAY_DELETE",description:"Delete an MCP gateway",inputSchema:wR6,outputSchema:MR6,handler:async(Q,X)=>{C1(X);let Y=L6(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 WX1=o(()=>{QX1();XX1();YX1();JX1();GX1()});var TR6,C40;var ZX1=o(()=>{E6();G1();TR6=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")}),C40=B1({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(TR6).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=L6(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 I40;var $X1=o(()=>{E6();G1();I40=B1({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:L6(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 KX1=o(()=>{ZX1();$X1()});var R40;var HX1=o(()=>{G1();E6();R40=B1({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)=>{C1(X),await X.access.check();let Y=uQ(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 S40;var FX1=o(()=>{G1();E6();S40=B1({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)=>{C1(X),await X.access.check();let Y=uQ(X),J=Q.userId||Y;if(!J)throw Error("User ID required to list organizations");return{organizations:await X.boundAuth.organization.list(J)}}})});var v40;var VX1=o(()=>{G1();E6();v40=B1({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)=>{C1(X),await X.access.check();let Y=await X.boundAuth.organization.get();if(!Y)throw Error("No active organization found");return Y}})});var k40;var qX1=o(()=>{G1();E6();k40=B1({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)=>{C1(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 _40;var zX1=o(()=>{G1();E6();_40=B1({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 C1(X),await X.access.check(),await X.boundAuth.organization.delete(Q.id),{success:!0,id:Q.id}}})});var ZP;var y40=o(()=>{G1();ZP=N.object({title:N.string(),url:N.string(),icon:N.string()})});var b40;var UX1=o(()=>{G1();E6();y40();b40=B1({name:"ORGANIZATION_SETTINGS_GET",description:"Get organization-level settings",inputSchema:N.object({}),outputSchema:N.object({organizationId:N.string(),sidebar_items:N.array(ZP).nullable().optional(),createdAt:N.union([N.date(),N.string()]).optional(),updatedAt:N.union([N.date(),N.string()]).optional()}),handler:async(Q,X)=>{C1(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 f40;var BX1=o(()=>{G1();E6();y40();f40=B1({name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization-level settings",inputSchema:N.object({organizationId:N.string(),sidebar_items:N.array(ZP).optional()}),outputSchema:N.object({organizationId:N.string(),sidebar_items:N.array(ZP).nullable().optional(),createdAt:N.union([N.date(),N.string()]),updatedAt:N.union([N.date(),N.string()])}),handler:async(Q,X)=>{if(C1(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 h40;var DX1=o(()=>{G1();E6();h40=B1({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)=>{C1(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 x40;var NX1=o(()=>{G1();E6();x40=B1({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)=>{C1(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 g40;var OX1=o(()=>{G1();E6();g40=B1({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)=>{C1(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 u40;var LX1=o(()=>{G1();E6();u40=B1({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)=>{C1(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(()=>{HX1();FX1();VX1();qX1();zX1();UX1();BX1();DX1();NX1();OX1();LX1()});var jR6,CR6,m40;var MX1=o(()=>{G1();E6();jR6=N.object({id:N.string().min(1)}),CR6=N.object({user:N.object({id:N.string(),name:N.string(),email:N.string(),image:N.string().nullable()}).nullable()}),m40=B1({name:"USER_GET",description:"Get a user by id (restricted to shared organizations)",inputSchema:jR6,outputSchema:CR6,handler:async(Q,X)=>{await X.access.check(),C1(X);let Y=uQ(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 PX1=o(()=>{MX1()});var AX1={};$8(AX1,{managementMCP:()=>l40,ALL_TOOLS:()=>TX1});var TX1,l40=(Q)=>{let X=TX1.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 vQ1({name:"mcp-mesh-management",version:"1.0.0"}).withTools(X).build()};var d40=o(()=>{kQ1();nQ1();h91();m91();s91();WX1();KX1();wX1();PX1();TX1=[R40,S40,v40,k40,_40,b40,f40,h40,x40,g40,u40,h60,W40,Z40,H40,F40,V40,M40,T40,A40,E40,j40,u91,C40,I40,_60,b60,f60,y60,q40,z40,U40,B40,D40,N40,O40,m40]});var t3,J80,vy,e3,UP;var ky=o(()=>{t3={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},J80={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},vy={Pending:0,Fulfilled:1,Rejected:2},e3={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},UP={IsStrictlyEqual:0,IsSameValue:1,IsSameValueZero:2}});function kU(...Q){H80&&console.log("quickjs-emscripten:",...Q)}function*yY1(Q){return yield Q}function NS6(Q){return yY1(V80(Q))}function PY1(Q,X){return(...Y)=>{let J=X.call(Q,F80,...Y);return V80(J)}}function OS6(Q,X){let Y=X.call(Q,F80);return V80(Y)}function V80(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 G80(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 GR6(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(YR6(G))return await JR6(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 sI6,eI6,u91;var m91=o(()=>{G1();E6();sI6=N.object({results:N.array(N.unknown()).optional(),success:N.boolean().optional()});eI6=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()});u91=B1({name:"DATABASES_RUN_SQL",description:"Run a SQL query against the database",inputSchema:eI6,outputSchema:N.object({result:N.array(sI6)}),handler:async(Q,X)=>{C1(X),await X.access.check();let Y=tI6(Q.sql,Q.params||[]);if(!X.connectionId)throw Error("Connection context required for database access");let J=QR6(X.connectionId),G=XR6(X.connectionId);return{result:[{results:(await GR6(X.db,J,G,Y)).rows,success:!0}]}}})});var l91,ZR6,d91;var f7=o(()=>{G1();Dy();l91=N.object({connectionId:N.string().optional().describe("Filter subscriptions by connection ID (optional)")}),ZR6=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")}),d91=N.object({subscriptions:N.array(ZR6).describe("List of subscriptions")})});var q40;var p91=o(()=>{E6();f7();q40=B1({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:iM,outputSchema:aM,handler:async(Q,X)=>{C1(X);let Y=L6(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 z40;var c91=o(()=>{E6();f7();z40=B1({name:"EVENT_SUBSCRIBE",description:"Subscribe to events of a specific type. The subscriber is automatically set to the caller's connection.",inputSchema:rM,outputSchema:oM,handler:async(Q,X)=>{C1(X);let Y=L6(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 U40;var n91=o(()=>{E6();f7();U40=B1({name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events by removing a subscription.",inputSchema:eM,outputSchema:QP,handler:async(Q,X)=>{C1(X);let Y=L6(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 B40;var i91=o(()=>{E6();f7();B40=B1({name:"EVENT_CANCEL",description:"Cancel a recurring event to stop future deliveries. Only the publisher can cancel their own events.",inputSchema:XP,outputSchema:YP,handler:async(Q,X)=>{C1(X);let Y=L6(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 D40;var a91=o(()=>{E6();f7();D40=B1({name:"EVENT_ACK",description:"Acknowledge delivery of an event. Call after successfully processing an event received via ON_EVENTS with retryAfter.",inputSchema:JP,outputSchema:GP,handler:async(Q,X)=>{C1(X);let Y=L6(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 N40;var r91=o(()=>{E6();f7();N40=B1({name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions, optionally filtered by connection ID.",inputSchema:l91,outputSchema:d91,handler:async(Q,X)=>{C1(X);let Y=L6(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 O40;var o91=o(()=>{E6();f7();O40=B1({name:"EVENT_SYNC_SUBSCRIPTIONS",description:"Sync subscriptions to desired state. Creates new, deletes removed, updates changed filters. Subscriptions are identified by (eventType, publisher).",inputSchema:sM,outputSchema:tM,handler:async(Q,X)=>{C1(X);let Y=L6(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 s91=o(()=>{p91();c91();n91();i91();a91();r91();o91();f7()});var L40,w40,KR6,JW,t91,e91;var RU=o(()=>{G1();L40=N.enum(["inclusion","exclusion"]).describe("Tool selection mode: 'inclusion' = include selected (default), 'exclusion' = exclude selected"),w40=N.enum(["passthrough","smart_tool_selection","code_execution"]).describe("Gateway tool selection strategy: 'passthrough' (default), 'smart_tool_selection', or 'code_execution'"),KR6=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.")}),JW=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:w40.describe("Gateway behavior strategy (metadata for now): 'passthrough', 'smart_tool_selection', or 'code_execution'"),tool_selection_mode:L40.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 Organization Agent for the organization"),connections:N.array(KR6).describe("Connections with their selected tools (behavior depends on tool_selection_mode)")}),t91=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:w40.optional().default("passthrough").describe("Gateway behavior strategy (defaults to 'passthrough')"),tool_selection_mode:L40.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 Organization Agent 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)")}),e91=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:w40.optional().describe("New gateway behavior strategy"),tool_selection_mode:L40.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 Organization Agent 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 HR6,FR6,M40;var QX1=o(()=>{G1();E6();RU();HR6=N.object({data:t91.describe("Data for the new gateway")}),FR6=N.object({item:JW.describe("The created gateway entity")}),M40=B1({name:"COLLECTION_GATEWAY_CREATE",description:"Create a new MCP gateway in the organization",inputSchema:HR6,outputSchema:FR6,handler:async(Q,X)=>{C1(X);let Y=L6(X);await X.access.check();let J=uQ(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 VR6(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 r$(Q){return typeof Q==="string"||typeof Q==="number"}function P40(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 qR6(Q,X){return Q.connections.some((Y)=>Y.connection_id===X)}function wy(Q,X){if("conditions"in X){let{operator:$,conditions:K}=X;switch($){case"and":return K.every((H)=>wy(Q,H));case"or":return K.some((H)=>wy(Q,H));case"not":return!K.every((H)=>wy(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 qR6(Q,G)}let Z=P40(Q,W);switch(J){case"eq":return Z===G;case"gt":return r$(Z)&&r$(G)&&Z>G;case"gte":return r$(Z)&&r$(G)&&Z>=G;case"lt":return r$(Z)&&r$(G)&&Z<G;case"lte":return r$(Z)&&r$(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 $=VR6(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 zR6(Q,X){return[...Q].sort((Y,J)=>{for(let G of X){let W=G.field.join("."),Z=P40(Y,W),$=P40(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 UR6,BR6,T40;var XX1=o(()=>{i$();E6();RU();UR6=cM,BR6=nM(JW),T40=B1({name:"COLLECTION_GATEWAY_LIST",description:"List all MCP gateways in the organization",inputSchema:UR6,outputSchema:BR6,handler:async(Q,X)=>{await X.access.check();let Y=L6(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)=>wy(V,Q.where));if(Q.orderBy&&Q.orderBy.length>0)W=zR6(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 DR6,NR6,A40;var YX1=o(()=>{G1();E6();RU();DR6=N.object({id:N.string().describe("ID of the gateway to retrieve")}),NR6=N.object({item:JW.nullable().describe("The retrieved gateway, or null if not found")}),A40=B1({name:"COLLECTION_GATEWAY_GET",description:"Get an MCP gateway by ID",inputSchema:DR6,outputSchema:NR6,handler:async(Q,X)=>{C1(X);let Y=L6(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 OR6,LR6,E40;var JX1=o(()=>{G1();E6();RU();OR6=N.object({id:N.string().describe("ID of the gateway to update"),data:e91.describe("Partial gateway data to update")}),LR6=N.object({item:JW.describe("The updated gateway entity")}),E40=B1({name:"COLLECTION_GATEWAY_UPDATE",description:"Update an MCP gateway",inputSchema:OR6,outputSchema:LR6,handler:async(Q,X)=>{C1(X);let Y=L6(X);await X.access.check();let J=uQ(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 wR6,MR6,j40;var GX1=o(()=>{G1();E6();RU();wR6=N.object({id:N.string().describe("ID of the gateway to delete")}),MR6=N.object({item:JW.describe("The deleted gateway entity")}),j40=B1({name:"COLLECTION_GATEWAY_DELETE",description:"Delete an MCP gateway",inputSchema:wR6,outputSchema:MR6,handler:async(Q,X)=>{C1(X);let Y=L6(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 Organization Agent. Set another Agent as the Organization Agent 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 WX1=o(()=>{QX1();XX1();YX1();JX1();GX1()});var TR6,C40;var ZX1=o(()=>{E6();G1();TR6=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")}),C40=B1({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(TR6).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=L6(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 I40;var $X1=o(()=>{E6();G1();I40=B1({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:L6(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 KX1=o(()=>{ZX1();$X1()});var R40;var HX1=o(()=>{G1();E6();R40=B1({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)=>{C1(X),await X.access.check();let Y=uQ(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 S40;var FX1=o(()=>{G1();E6();S40=B1({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)=>{C1(X),await X.access.check();let Y=uQ(X),J=Q.userId||Y;if(!J)throw Error("User ID required to list organizations");return{organizations:await X.boundAuth.organization.list(J)}}})});var v40;var VX1=o(()=>{G1();E6();v40=B1({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)=>{C1(X),await X.access.check();let Y=await X.boundAuth.organization.get();if(!Y)throw Error("No active organization found");return Y}})});var k40;var qX1=o(()=>{G1();E6();k40=B1({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)=>{C1(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 _40;var zX1=o(()=>{G1();E6();_40=B1({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 C1(X),await X.access.check(),await X.boundAuth.organization.delete(Q.id),{success:!0,id:Q.id}}})});var ZP;var y40=o(()=>{G1();ZP=N.object({title:N.string(),url:N.string(),icon:N.string()})});var b40;var UX1=o(()=>{G1();E6();y40();b40=B1({name:"ORGANIZATION_SETTINGS_GET",description:"Get organization-level settings",inputSchema:N.object({}),outputSchema:N.object({organizationId:N.string(),sidebar_items:N.array(ZP).nullable().optional(),createdAt:N.union([N.date(),N.string()]).optional(),updatedAt:N.union([N.date(),N.string()]).optional()}),handler:async(Q,X)=>{C1(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 f40;var BX1=o(()=>{G1();E6();y40();f40=B1({name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization-level settings",inputSchema:N.object({organizationId:N.string(),sidebar_items:N.array(ZP).optional()}),outputSchema:N.object({organizationId:N.string(),sidebar_items:N.array(ZP).nullable().optional(),createdAt:N.union([N.date(),N.string()]),updatedAt:N.union([N.date(),N.string()])}),handler:async(Q,X)=>{if(C1(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 h40;var DX1=o(()=>{G1();E6();h40=B1({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)=>{C1(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 x40;var NX1=o(()=>{G1();E6();x40=B1({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)=>{C1(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 g40;var OX1=o(()=>{G1();E6();g40=B1({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)=>{C1(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 u40;var LX1=o(()=>{G1();E6();u40=B1({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)=>{C1(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(()=>{HX1();FX1();VX1();qX1();zX1();UX1();BX1();DX1();NX1();OX1();LX1()});var jR6,CR6,m40;var MX1=o(()=>{G1();E6();jR6=N.object({id:N.string().min(1)}),CR6=N.object({user:N.object({id:N.string(),name:N.string(),email:N.string(),image:N.string().nullable()}).nullable()}),m40=B1({name:"USER_GET",description:"Get a user by id (restricted to shared organizations)",inputSchema:jR6,outputSchema:CR6,handler:async(Q,X)=>{await X.access.check(),C1(X);let Y=uQ(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 PX1=o(()=>{MX1()});var AX1={};$8(AX1,{managementMCP:()=>l40,ALL_TOOLS:()=>TX1});var TX1,l40=(Q)=>{let X=TX1.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 vQ1({name:"mcp-mesh-management",version:"1.0.0"}).withTools(X).build()};var d40=o(()=>{kQ1();nQ1();h91();m91();s91();WX1();KX1();wX1();PX1();TX1=[R40,S40,v40,k40,_40,b40,f40,h40,x40,g40,u40,h60,W40,Z40,H40,F40,V40,M40,T40,A40,E40,j40,u91,C40,I40,_60,b60,f60,y60,q40,z40,U40,B40,D40,N40,O40,m40]});var t3,J80,vy,e3,UP;var ky=o(()=>{t3={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},J80={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},vy={Pending:0,Fulfilled:1,Rejected:2},e3={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},UP={IsStrictlyEqual:0,IsSameValue:1,IsSameValueZero:2}});function kU(...Q){H80&&console.log("quickjs-emscripten:",...Q)}function*yY1(Q){return yield Q}function NS6(Q){return yY1(V80(Q))}function PY1(Q,X){return(...Y)=>{let J=X.call(Q,F80,...Y);return V80(J)}}function OS6(Q,X){let Y=X.call(Q,F80);return V80(Y)}function V80(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 G80(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 bY1(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,$80,{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 _y(Q){return!!(Q&&(typeof Q=="object"||typeof Q=="function")&&("alive"in Q)&&typeof Q.alive=="boolean"&&("dispose"in Q)&&typeof Q.dispose=="function")}function LS6(Q){if(!Q)return 0;let X=0;for(let[Y,J]of Object.entries(Q)){if(!(Y in J80))throw new vY1(Y);J&&(X|=J80[Y])}return X}function wS6(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|=t3.JS_EVAL_TYPE_GLOBAL),X==="module"&&(Z|=t3.JS_EVAL_TYPE_MODULE),Y&&(Z|=t3.JS_EVAL_FLAG_STRICT),J&&(Z|=t3.JS_EVAL_FLAG_STRIP),G&&(Z|=t3.JS_EVAL_FLAG_COMPILE_ONLY),W&&(Z|=t3.JS_EVAL_FLAG_BACKTRACE_BARRIER),Z}function MS6(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&&($|=e3.JS_GPN_STRING_MASK),Y&&($|=e3.JS_GPN_SYMBOL_MASK),J&&($|=e3.JS_GPN_PRIVATE_MASK),G&&($|=e3.JS_GPN_ENUM_ONLY),W&&($|=e3.QTS_GPN_NUMBER_MASK),Z&&($|=e3.QTS_STANDARD_COMPLIANT_NUMBER),$}function PS6(...Q){let X=[];for(let Y of Q)Y!==void 0&&(X=X.concat(Y));return X}function B80(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 D80(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 BS6,DS6=(Q,X)=>{for(var Y in X)BS6(Q,Y,{get:X[Y],enumerable:!0})},H80=!1,AY1,W80,EY1,Z80,jY1,CY1,IY1,RY1,SY1,vY1,kY1,_Y1,F80,g7,$80,TY1,g9,s$,K80,k5,q80,fY1,hY1,QF,xY1,gY1=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 g9(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 g9({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 g9({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 g9({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}},Kg4,z80,TS6,AS6,uY1,mY1,ES6=class{constructor(Q){this.callFunction=Q.callFunction,this.shouldInterrupt=Q.shouldInterrupt,this.loadModuleSource=Q.loadModuleSource,this.normalizeModule=Q.normalizeModule}},U80=class{constructor(Q){this.contextCallbacks=new Map,this.runtimeCallbacks=new Map,this.suspendedCount=0,this.cToHostCallbacks=new ES6({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)){kU("asyncify.handleSleep: not suspending:",G),J(G);return}if(this.suspended)throw new CY1(`Already suspended at: ${this.suspended.stack}
|
|
257
257
|
Attempted to suspend at:`);this.suspended=new IY1(`(${this.suspendedCount++})`),kU("asyncify.handleSleep: suspending:",this.suspended),G.then((W)=>{this.suspended=void 0,kU("asyncify.handleSleep: resolved:",W),J(W)},(W)=>{kU("asyncify.handleSleep: rejected:",W),console.error("QuickJS: cannot handle error in suspended function",W),this.suspended=void 0})}catch(G){throw kU("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}},N80=class{constructor(Q,X){this.module=Q,this.ffi=X,this.callbacks=new U80(Q)}newRuntime(Q={}){let X=new g9(this.ffi.QTS_NewRuntime(),void 0,(J)=>{this.callbacks.deleteRuntime(J),this.ffi.QTS_FreeRuntime(J)}),Y=new mY1({module:this.module,callbacks:this.callbacks,ffi:this.ffi,rt:X});return B80(Y,Q),Q.moduleLoader&&Y.setModuleLoader(Q.moduleLoader),Y}newContext(Q={}){let X=this.newRuntime(),Y=X.newContext({...Q,ownedLifetimes:PS6(X,Q.ownedLifetimes)});return X.context=Y,Y}evalCode(Q,X={}){return k5.withScope((Y)=>{let J=Y.manage(this.newContext());D80(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 O80=o(()=>{ky();ky();BS6=Object.defineProperty;AY1={};DS6(AY1,{QuickJSAsyncifyError:()=>CY1,QuickJSAsyncifySuspended:()=>IY1,QuickJSEmptyGetOwnPropertyNames:()=>_Y1,QuickJSEmscriptenModuleError:()=>SY1,QuickJSMemoryLeakDetected:()=>RY1,QuickJSNotImplemented:()=>jY1,QuickJSPromisePending:()=>kY1,QuickJSUnknownIntrinsic:()=>vY1,QuickJSUnwrapError:()=>W80,QuickJSUseAfterFree:()=>Z80,QuickJSWrongOwner:()=>EY1});W80=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"}},EY1=class extends Error{constructor(){super(...arguments);this.name="QuickJSWrongOwner"}},Z80=class extends Error{constructor(){super(...arguments);this.name="QuickJSUseAfterFree"}},jY1=class extends Error{constructor(){super(...arguments);this.name="QuickJSNotImplemented"}},CY1=class extends Error{constructor(){super(...arguments);this.name="QuickJSAsyncifyError"}},IY1=class extends Error{constructor(){super(...arguments);this.name="QuickJSAsyncifySuspended"}},RY1=class extends Error{constructor(){super(...arguments);this.name="QuickJSMemoryLeakDetected"}},SY1=class extends Error{constructor(){super(...arguments);this.name="QuickJSEmscriptenModuleError"}},vY1=class extends TypeError{constructor(){super(...arguments);this.name="QuickJSUnknownIntrinsic"}},kY1=class extends Error{constructor(){super(...arguments);this.name="QuickJSPromisePending"}},_Y1=class extends Error{constructor(){super(...arguments);this.name="QuickJSEmptyGetOwnPropertyNames"}};F80=yY1;F80.of=NS6;g7=class{[Symbol.dispose](){return this.dispose()}},$80=Symbol.dispose??Symbol.for("Symbol.dispose"),TY1=g7.prototype;TY1[$80]||(TY1[$80]=function(){return this.dispose()});g9=class Q extends g7{constructor(X,Y,J,G){super();this._value=X,this.copier=Y,this.disposer=J,this._owner=G,this._alive=!0,this._constructorStack=H80?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 Z80(`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>`},rt=(Q)=>{let X=Q?.path??"/reference";return{id:"open-api",endpoints:{generateOpenAPISchema:f0("/open-api/generate-schema",{method:"GET"},async(Y)=>{let J=await Lr0(Y.context,Y.context.options);return Y.json(J)}),openAPIReference:f0(X,{method:"GET",metadata:{isAction:!1}},async(Y)=>{if(Q?.disableDefaultReference)throw new n("NOT_FOUND");let J=await Lr0(Y.context,Y.context.options);return new Response(Sq6(J,Q?.theme,Q?.nonce),{headers:{"Content-Type":"text/html"}})})}}};HX();kG();d8();bQ();G1();var bL4=a6(async()=>{return{}}),fL4=a6({use:[X8]},async(Q)=>{return{session:Q.context.session}}),hL4=T4({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 xL4=Number.POSITIVE_INFINITY;var Mr0=P(),kq6=F1(["pending","accepted","rejected","canceled"]).default("pending"),gL4=d({id:P().default(QQ),name:P(),slug:P(),logo:P().nullish().optional(),metadata:c0(P(),G4()).or(P().transform((Q)=>JSON.parse(Q))).optional(),createdAt:n1()}),uL4=d({id:P().default(QQ),organizationId:P(),userId:v1.string(),role:Mr0,createdAt:n1().default(()=>new Date)}),mL4=d({id:P().default(QQ),organizationId:P(),email:P(),role:Mr0,status:kq6,teamId:P().nullish(),inviterId:P(),expiresAt:n1(),createdAt:n1().default(()=>new Date)}),lL4=d({id:P().default(QQ),name:P().min(1),organizationId:P(),createdAt:n1(),updatedAt:n1().optional()}),dL4=d({id:P().default(QQ),teamId:P(),userId:P(),createdAt:n1().default(()=>new Date)}),pL4=d({id:P().default(QQ),organizationId:P(),role:P(),permission:c0(P(),M0(P())),createdAt:n1().default(()=>new Date),updatedAt:n1().optional()}),wr0=["admin","member","owner"],cL4=o1([F1(wr0),M0(F1(wr0))]);q8();d8();bQ();var Xw4=T4({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"});q8();FX();d8();bQ();RQ();c4();var _q6=T4({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();bQ();var yq6=T4({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 S3={enabled:!0,batchSize:250,flushIntervalMs:300,maxQueueSize:1e4,redactor:"regex"};import{existsSync as Pr0,readFileSync as Tr0}from"fs";var Yk={emailAndPassword:{enabled:!0}},Ar0=process.env.CONFIG_PATH||"./config.json",Er0=process.env.AUTH_CONFIG_PATH||"./auth-config.json";function bq6(){if(Pr0(Ar0))try{let Q=Tr0(Ar0,"utf-8"),X=JSON.parse(Q);return{auth:Yk,monitoring:S3,...X}}catch{return{auth:Yk,monitoring:S3}}if(Pr0(Er0))try{let Q=Tr0(Er0,"utf-8");return{auth:JSON.parse(Q),monitoring:S3}}catch{return{auth:Yk,monitoring:S3}}return{auth:Yk,monitoring:S3}}var Jk=bq6();function jr0(){return{...S3,...Jk.monitoring}}import{existsSync as jD6,mkdirSync as CD6}from"fs";import{Kysely as is0,PostgresDialect as as0,sql as ns0}from"kysely";import{BunWorkerDialect as rs0}from"kysely-bun-worker";import*as os0 from"path";var RJ=m6(je(),1),tP4=RJ.default.Client,Se=RJ.default.Pool,eP4=RJ.default.Connection,QT4=RJ.default.types,XT4=RJ.default.Query,YT4=RJ.default.DatabaseError,JT4=RJ.default.escapeIdentifier,GT4=RJ.default.escapeLiteral,WT4=RJ.default.Result,ZT4=RJ.default.TypeOverrides,$T4=RJ.default.defaults;var ss0={keepAlive:!0,keepAliveInitialDelayMillis:1e4,idleTimeoutMillis:300000,connectionTimeoutMillis:30000,allowExitOnIdle:!0};function ID6(Q){let X=new Se({connectionString:Q.connectionString,max:Q.options?.maxConnections||10,ssl:process.env.DATABASE_PG_SSL==="true"?!0:!1,...ss0}),Y=new as0({pool:X});return{type:"postgres",db:new is0({dialect:Y}),pool:X}}function ts0(Q){if(Q===":memory:")return":memory:";if(Q.includes("://"))return new URL(Q).pathname;return Q}function es0(Q){if(Q!==":memory:"&&Q!=="/"&&Q){let X=Q.substring(0,Q.lastIndexOf("/"));if(X&&X!=="/"&&!jD6(X))try{CD6(X,{recursive:!0})}catch{return console.warn(`Failed to create directory ${X}, using in-memory database`),":memory:"}}return Q}function RD6(Q){let X=ts0(Q.connectionString);X=es0(X);let Y=new rs0({url:X||":memory:"}),J=new is0({dialect:Y});if(X!==":memory:"&&Q.options?.enableWAL!==!1)ns0`PRAGMA journal_mode = WAL;`.execute(J).catch(()=>{});if(X!==":memory:"){let G=Q.options?.busyTimeout||5000;ns0`PRAGMA busy_timeout = ${G};`.execute(J).catch(()=>{})}return{type:"sqlite",db:J}}function Qt0(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 ke(){return process.env.DATABASE_URL||`file:${os0.join(process.cwd(),"data/mesh.db")}`}function Xt0(Q){let X=Qt0(Q);if(X.type==="postgres")return new as0({pool:new Se({connectionString:X.connectionString,max:X.options?.maxConnections||10,ssl:process.env.DATABASE_PG_SSL==="true"?!0:!1,...ss0})});let Y=ts0(X.connectionString);return Y=es0(Y),new rs0({url:Y||":memory:"})}function SD6(Q){let X=Qt0(Q);if(X.type==="postgres")return ID6(X);return RD6(X)}var ve=null;function Bk(){if(!ve)ve=SD6(ke());return ve}class _e{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 ye{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 vD6=(Q)=>{let X=new _e(Q.config.apiKey);return async({to:Y,subject:J,html:G})=>{await X.sendEmail({to:Y,from:Q.config.fromEmail,subject:J,html:G})}},kD6=(Q)=>{let X=new ye(Q.config.apiKey);return async({to:Y,subject:J,html:G})=>{await X.sendEmail({to:Y,from:Q.config.fromEmail,subject:J,html:G})}},_D6={resend:vD6,sendgrid:kD6};function Dk(Q){let X=_D6[Q.provider];if(!X)throw Error(`Unknown email provider: ${Q.provider}`);return X(Q)}function Nk(Q,X){return Q.find((Y)=>Y.id===X)}var Yt0=(Q,X)=>{let Y=Nk(X,Q.emailProviderId);if(!Y)throw Error(`Email provider with id '${Q.emailProviderId}' not found`);let J=Dk(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>`})}}};_3();import{createCipheriv as yD6,createDecipheriv as bD6,randomBytes as Kt0}from"crypto";var Ht0="aes-256-gcm",kw=16,Ft0=16,Vt0=32;class _w{key;constructor(Q){if(Buffer.from(Q,"base64").length===Vt0)this.key=Buffer.from(Q,"base64");else{let X=U0("crypto");this.key=X.createHash("sha256").update(Q).digest()}}async encrypt(Q){let X=Kt0(kw),Y=yD6(Ht0,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,kw),J=X.subarray(kw,kw+Ft0),G=X.subarray(kw+Ft0),W=bD6(Ht0,this.key,Y);W.setAuthTag(J);let Z=W.update(G);return Z=Buffer.concat([Z,W.final()]),Z.toString("utf8")}static generateKey(){return Kt0(Vt0).toString("base64")}}O7();yw();var lD6=["connection_headers","oauth_config","configuration_scopes","metadata","tools","bindings"];class bw{db;vault;constructor(Q,X){this.db=Q;this.vault=X}async create(Q){let X=Q.id??vJ("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(y3(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(lD6.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(y3(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}}}yw();class fw{db;constructor(Q){this.db=Q}async create(Q,X,Y){let J=vJ("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:vJ("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:vJ("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:vJ("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:vJ("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}}Zy();G1();function RR6(Q){return[{permissions:{self:["*"]},getTools:async()=>{let{ALL_TOOLS:X}=await Promise.resolve().then(() => (d40(),AX1));return X.map((Y)=>{return{name:Y.name,inputSchema:N.toJSONSchema(Y.inputSchema,{unrepresentable:"any"}),outputSchema:Y.outputSchema?N.toJSONSchema(Y.outputSchema,{unrepresentable:"any"}):void 0,description:Y.description}})},data:$t0(process.env.BASE_URL||"http://localhost:3000")},{data:Zt0()},{data:Wt0(Q)}]}async function EX1(Q,X){try{let Y=Bk(),J=new _w(process.env.ENCRYPTION_KEY||""),G=new bw(Y.db,J),W=new fw(Y.db),Z=RR6(Q),$=[];await Promise.all(Z.map(async(K)=>{let H=null;if(K.permissions)H=(await h7.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 OU({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?K.data.id.startsWith(`${Q}_`)?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 p40=["owner","admin","user"],jX1=["owner","admin"];var SR6=(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"}}}}]}},CX1=(Q)=>{if(Q.providerId==="microsoft")return SR6(Q);throw Error(`Unsupported provider: ${Q.providerId}`)};function vR6(Q){return Q.toLowerCase().trim().replace(/[^a-z0-9\s_-]+/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var IX1=["labs","hub","studio","workspace","systems","core","cloud","works"],RX1=["capybara","guarana","deco","samba","feijoada","capoeira","carnival"];function kR6(){let Q=Math.floor(Math.random()*RX1.length),X=Math.floor(Math.random()*IX1.length),Y=RX1[Q]??"deco",J=IX1[X]??"studio";return`${Y}-${J}`}var _R6=Object.values(gD()).map((Q)=>Q.map((X)=>X.name)).flat(),yR6={...lv,self:["*",..._R6]},My=nG(yR6),bR6=My.newRole({self:["*"],...Uw.statements}),fR6=My.newRole({self:["*"],...Uw.statements}),hR6=My.newRole({self:["*"],...Uw.statements}),SX1=Object.values(gD()).map((Q)=>Q.map((X)=>`self:${X.name}`)).flat(),a8=Jk.auth,vX1=void 0;if(a8.inviteEmailProviderId&&a8.emailProviders&&a8.emailProviders.length>0){let Q=Nk(a8.emailProviders,a8.inviteEmailProviderId);if(Q){let X=Dk(Q);vX1=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>`},rt=(Q)=>{let X=Q?.path??"/reference";return{id:"open-api",endpoints:{generateOpenAPISchema:f0("/open-api/generate-schema",{method:"GET"},async(Y)=>{let J=await Lr0(Y.context,Y.context.options);return Y.json(J)}),openAPIReference:f0(X,{method:"GET",metadata:{isAction:!1}},async(Y)=>{if(Q?.disableDefaultReference)throw new n("NOT_FOUND");let J=await Lr0(Y.context,Y.context.options);return new Response(Sq6(J,Q?.theme,Q?.nonce),{headers:{"Content-Type":"text/html"}})})}}};HX();kG();d8();bQ();G1();var bL4=a6(async()=>{return{}}),fL4=a6({use:[X8]},async(Q)=>{return{session:Q.context.session}}),hL4=T4({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 xL4=Number.POSITIVE_INFINITY;var Mr0=P(),kq6=F1(["pending","accepted","rejected","canceled"]).default("pending"),gL4=d({id:P().default(QQ),name:P(),slug:P(),logo:P().nullish().optional(),metadata:c0(P(),G4()).or(P().transform((Q)=>JSON.parse(Q))).optional(),createdAt:n1()}),uL4=d({id:P().default(QQ),organizationId:P(),userId:v1.string(),role:Mr0,createdAt:n1().default(()=>new Date)}),mL4=d({id:P().default(QQ),organizationId:P(),email:P(),role:Mr0,status:kq6,teamId:P().nullish(),inviterId:P(),expiresAt:n1(),createdAt:n1().default(()=>new Date)}),lL4=d({id:P().default(QQ),name:P().min(1),organizationId:P(),createdAt:n1(),updatedAt:n1().optional()}),dL4=d({id:P().default(QQ),teamId:P(),userId:P(),createdAt:n1().default(()=>new Date)}),pL4=d({id:P().default(QQ),organizationId:P(),role:P(),permission:c0(P(),M0(P())),createdAt:n1().default(()=>new Date),updatedAt:n1().optional()}),wr0=["admin","member","owner"],cL4=o1([F1(wr0),M0(F1(wr0))]);q8();d8();bQ();var Xw4=T4({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"});q8();FX();d8();bQ();RQ();c4();var _q6=T4({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();bQ();var yq6=T4({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 S3={enabled:!0,batchSize:250,flushIntervalMs:300,maxQueueSize:1e4,redactor:"regex"};import{existsSync as Pr0,readFileSync as Tr0}from"fs";var Yk={emailAndPassword:{enabled:!0}},Ar0=process.env.CONFIG_PATH||"./config.json",Er0=process.env.AUTH_CONFIG_PATH||"./auth-config.json";function bq6(){if(Pr0(Ar0))try{let Q=Tr0(Ar0,"utf-8"),X=JSON.parse(Q);return{auth:Yk,monitoring:S3,...X}}catch{return{auth:Yk,monitoring:S3}}if(Pr0(Er0))try{let Q=Tr0(Er0,"utf-8");return{auth:JSON.parse(Q),monitoring:S3}}catch{return{auth:Yk,monitoring:S3}}return{auth:Yk,monitoring:S3}}var Jk=bq6();function jr0(){return{...S3,...Jk.monitoring}}import{existsSync as jD6,mkdirSync as CD6}from"fs";import{Kysely as is0,PostgresDialect as as0,sql as ns0}from"kysely";import{BunWorkerDialect as rs0}from"kysely-bun-worker";import*as os0 from"path";var RJ=m6(je(),1),tP4=RJ.default.Client,Se=RJ.default.Pool,eP4=RJ.default.Connection,QT4=RJ.default.types,XT4=RJ.default.Query,YT4=RJ.default.DatabaseError,JT4=RJ.default.escapeIdentifier,GT4=RJ.default.escapeLiteral,WT4=RJ.default.Result,ZT4=RJ.default.TypeOverrides,$T4=RJ.default.defaults;var ss0={keepAlive:!0,keepAliveInitialDelayMillis:1e4,idleTimeoutMillis:300000,connectionTimeoutMillis:30000,allowExitOnIdle:!0};function ID6(Q){let X=new Se({connectionString:Q.connectionString,max:Q.options?.maxConnections||10,ssl:process.env.DATABASE_PG_SSL==="true"?!0:!1,...ss0}),Y=new as0({pool:X});return{type:"postgres",db:new is0({dialect:Y}),pool:X}}function ts0(Q){if(Q===":memory:")return":memory:";if(Q.includes("://"))return new URL(Q).pathname;return Q}function es0(Q){if(Q!==":memory:"&&Q!=="/"&&Q){let X=Q.substring(0,Q.lastIndexOf("/"));if(X&&X!=="/"&&!jD6(X))try{CD6(X,{recursive:!0})}catch{return console.warn(`Failed to create directory ${X}, using in-memory database`),":memory:"}}return Q}function RD6(Q){let X=ts0(Q.connectionString);X=es0(X);let Y=new rs0({url:X||":memory:"}),J=new is0({dialect:Y});if(X!==":memory:"&&Q.options?.enableWAL!==!1)ns0`PRAGMA journal_mode = WAL;`.execute(J).catch(()=>{});if(X!==":memory:"){let G=Q.options?.busyTimeout||5000;ns0`PRAGMA busy_timeout = ${G};`.execute(J).catch(()=>{})}return{type:"sqlite",db:J}}function Qt0(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 ke(){return process.env.DATABASE_URL||`file:${os0.join(process.cwd(),"data/mesh.db")}`}function Xt0(Q){let X=Qt0(Q);if(X.type==="postgres")return new as0({pool:new Se({connectionString:X.connectionString,max:X.options?.maxConnections||10,ssl:process.env.DATABASE_PG_SSL==="true"?!0:!1,...ss0})});let Y=ts0(X.connectionString);return Y=es0(Y),new rs0({url:Y||":memory:"})}function SD6(Q){let X=Qt0(Q);if(X.type==="postgres")return ID6(X);return RD6(X)}var ve=null;function Bk(){if(!ve)ve=SD6(ke());return ve}class _e{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 ye{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 vD6=(Q)=>{let X=new _e(Q.config.apiKey);return async({to:Y,subject:J,html:G})=>{await X.sendEmail({to:Y,from:Q.config.fromEmail,subject:J,html:G})}},kD6=(Q)=>{let X=new ye(Q.config.apiKey);return async({to:Y,subject:J,html:G})=>{await X.sendEmail({to:Y,from:Q.config.fromEmail,subject:J,html:G})}},_D6={resend:vD6,sendgrid:kD6};function Dk(Q){let X=_D6[Q.provider];if(!X)throw Error(`Unknown email provider: ${Q.provider}`);return X(Q)}function Nk(Q,X){return Q.find((Y)=>Y.id===X)}var Yt0=(Q,X)=>{let Y=Nk(X,Q.emailProviderId);if(!Y)throw Error(`Email provider with id '${Q.emailProviderId}' not found`);let J=Dk(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>`})}}};_3();import{createCipheriv as yD6,createDecipheriv as bD6,randomBytes as Kt0}from"crypto";var Ht0="aes-256-gcm",kw=16,Ft0=16,Vt0=32;class _w{key;constructor(Q){if(Buffer.from(Q,"base64").length===Vt0)this.key=Buffer.from(Q,"base64");else{let X=U0("crypto");this.key=X.createHash("sha256").update(Q).digest()}}async encrypt(Q){let X=Kt0(kw),Y=yD6(Ht0,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,kw),J=X.subarray(kw,kw+Ft0),G=X.subarray(kw+Ft0),W=bD6(Ht0,this.key,Y);W.setAuthTag(J);let Z=W.update(G);return Z=Buffer.concat([Z,W.final()]),Z.toString("utf8")}static generateKey(){return Kt0(Vt0).toString("base64")}}O7();yw();var lD6=["connection_headers","oauth_config","configuration_scopes","metadata","tools","bindings"];class bw{db;vault;constructor(Q,X){this.db=Q;this.vault=X}async create(Q){let X=Q.id??vJ("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(y3(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(lD6.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(y3(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}}}yw();class fw{db;constructor(Q){this.db=Q}async create(Q,X,Y){let J=vJ("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:vJ("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:vJ("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:vJ("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:vJ("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}}Zy();G1();function RR6(Q){return[{permissions:{self:["*"]},getTools:async()=>{let{ALL_TOOLS:X}=await Promise.resolve().then(() => (d40(),AX1));return X.map((Y)=>{return{name:Y.name,inputSchema:N.toJSONSchema(Y.inputSchema,{unrepresentable:"any"}),outputSchema:Y.outputSchema?N.toJSONSchema(Y.outputSchema,{unrepresentable:"any"}):void 0,description:Y.description}})},data:$t0(process.env.BASE_URL||"http://localhost:3000")},{data:Zt0()},{data:Wt0(Q)}]}async function EX1(Q,X){try{let Y=Bk(),J=new _w(process.env.ENCRYPTION_KEY||""),G=new bw(Y.db,J),W=new fw(Y.db),Z=RR6(Q),$=[];await Promise.all(Z.map(async(K)=>{let H=null;if(K.permissions)H=(await h7.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 OU({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?K.data.id.startsWith(`${Q}_`)?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:"Organization Agent",description:"Use all organization connections into a single agent",toolSelectionStrategy:"passthrough",toolSelectionMode:"exclusion",status:"active",isDefault:!0,connections:$.map((K)=>({connectionId:K}))})}catch(Y){console.error("Error creating default MCP connections:",Y)}}var p40=["owner","admin","user"],jX1=["owner","admin"];var SR6=(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"}}}}]}},CX1=(Q)=>{if(Q.providerId==="microsoft")return SR6(Q);throw Error(`Unsupported provider: ${Q.providerId}`)};function vR6(Q){return Q.toLowerCase().trim().replace(/[^a-z0-9\s_-]+/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var IX1=["labs","agent","studio","workspace","systems","core","cloud","works"],RX1=["capybara","guarana","deco","samba","feijoada","capoeira","carnival"];function kR6(){let Q=Math.floor(Math.random()*RX1.length),X=Math.floor(Math.random()*IX1.length),Y=RX1[Q]??"deco",J=IX1[X]??"studio";return`${Y}-${J}`}var _R6=Object.values(gD()).map((Q)=>Q.map((X)=>X.name)).flat(),yR6={...lv,self:["*",..._R6]},My=nG(yR6),bR6=My.newRole({self:["*"],...Uw.statements}),fR6=My.newRole({self:["*"],...Uw.statements}),hR6=My.newRole({self:["*"],...Uw.statements}),SX1=Object.values(gD()).map((Q)=>Q.map((X)=>`self:${X.name}`)).flat(),a8=Jk.auth,vX1=void 0;if(a8.inviteEmailProviderId&&a8.emailProviders&&a8.emailProviders.length>0){let Q=Nk(a8.emailProviders,a8.inviteEmailProviderId);if(Q){let X=Dk(Q);vX1=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 yU(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=yU(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=yU(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=yU(Q,K);$.resolve(H),H.dispose(),Q.runtime.executePendingJobs()}catch(H){let F=_U(H),V=Q.newString(`Promise resolution error: ${F}`);$.reject(V),V.dispose(),Q.runtime.executePendingJobs()}}).catch((K)=>{let H=_U(K),F=Q.newString(`Promise rejection: ${H}`);$.reject(F),F.dispose(),Q.runtime.executePendingJobs()}),$.handle}return yU(Q,Z)}catch(W){let Z=_U(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 SS6=(Q)=>new Promise((X)=>setTimeout(X,Q));function QJ1(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 eY1(Q,X,Y){let J=Date.now(),G=Q.resolvePromise(X);while(!0){QJ1(Q);let W=await Promise.race([G,SS6(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 w80({tools:Q,code:X,timeoutMs:Y}){let Z=[];try{let J=await tY1({memoryLimitBytes:33554432,stackSizeBytes:524288});const G=Yb(Z,J.newContext({interruptAfterMs:Y}),0);const W=Yb(Z,MY1(G),0);try{let F=G.evalCode(X,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult(F),q=yU(G,Q);G.setProp(G.global,"tools",q);let z=G.runtime.hasPendingJob()?G.unwrapResult(await eY1(G,V,Y)):V;if(z!==V)V.dispose();let B=G.getProp(z,"default"),D=G.typeof(B);if(D!=="function")return{error:`Code must export default a function (tools). Got ${D}. Example: export default async (tools) => { /* ... */ }`,consoleLogs:W.logs};let L=G.callFunction(B,G.undefined,q),M=G.unwrapResult(L),C=await eY1(G,M,Y),A=G.unwrapResult(C);if(G.runtime.hasPendingJob())QJ1(G);return{returnValue:G.dump(A),consoleLogs:W.logs}}catch(F){return console.log(F),{error:_U(F),consoleLogs:W.logs}}}catch($){var K=$,H=1}finally{$Q0(Z,K,H)}}function vS6(Q){return Q.toLowerCase().split(/[\s_\-./]+/).filter((X)=>X.length>=2)}function kS6(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 _S6(Q,X,Y){let J=vS6(Q);if(J.length===0)return X.slice(0,Y);return X.map((G)=>({tool:G,score:kS6(J,G)})).filter((G)=>G.score>0).sort((G,W)=>W.score-G.score).slice(0,Y).map((G)=>G.tool)}function M80(Q){return{content:[{type:"text",text:JSON.stringify(Q,null,2)}]}}function BP(Q){return{content:[{type:"text",text:JSON.stringify(Q,null,2)}],isError:!0}}function XJ1(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 BP({error:G.error.flatten()});let W=_S6(G.data.query,Q.tools,G.data.limit);return M80({query:G.data.query,results:W.map((Z)=>({name:Z.name,description:Z.description,connection:Z._meta.connectionTitle})),totalAvailable:Q.tools.length})}}}function YJ1(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 BP({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 M80({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 yS6(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 BP({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 bS6(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 BP({error:J.error.flatten()});let G=Object.fromEntries(Q.tools.map((Z)=>[Z.name,async($)=>Q.callTool(Z.name,$??{})])),W=await w80({...J.data,tools:G});if(W.error)return BP(W);return M80(W)}}}function JJ1(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 fS6=(Q)=>({tools:Q.tools,callTool:(X,Y)=>Q.callTool(X,Y)}),hS6=(Q)=>JJ1([XJ1(Q),YJ1(Q),bS6(Q)]),xS6=(Q)=>JJ1([XJ1(Q),YJ1(Q),yS6(Q)]);function GJ1(Q){switch(Q){case"smart_tool_selection":return xS6;case"code_execution":return hS6;case"passthrough":default:return fS6}}class yy{proxies;options;cache;constructor(Q,X){this.proxies=Q;this.options=X;this.cache=GW(()=>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((z)=>!q.has(z.name))}}else if(K.selectedTools&&K.selectedTools.length>0){let q=new Set(K.selectedTools);V=V.filter((z)=>q.has(z.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})},$=GJ1(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 gS6(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 WJ1(Q,X){return X.some((Y)=>gS6(Q,Y))}class by{proxies;options;cache;constructor(Q,X){this.proxies=Q;this.options=X;this.cache=GW(()=>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)=>!WJ1(K.uri,G.selectedResources))}else if(!G.selectedResources||G.selectedResources.length===0)$=[];else $=$.filter((K)=>WJ1(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 fy{proxies;cache;constructor(Q){this.proxies=Q;this.cache=GW(()=>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 hy{proxies;options;cache;constructor(Q,X){this.proxies=Q;this.options=X;this.cache=GW(()=>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 ZJ1=new cQ;async function uS6(Q,X){let Y=await zP.create(Q.connections,X),J=new yy(Y,{selectionMode:Q.toolSelectionMode,strategy:Q.toolSelectionStrategy}),G=new by(Y,{selectionMode:Q.toolSelectionMode}),W=new fy(Y),Z=new hy(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 mS6(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 uS6(J,X)}ZJ1.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 mS6(J,Y),Z=new a3({name:`mcp-gateway-${J.title}`,version:"1.0.0"},{capabilities:{tools:{},resources:{},prompts:{}}}),$=new r3({enableJsonResponse:Q.req.header("Accept")?.includes("application/json")??!1});return await Z.connect($),Z.server.setRequestHandler(b$,async(K)=>{return W.client.listTools()}),Z.server.setRequestHandler(eG,async(K)=>{return await W.client.callTool(K.params)}),Z.server.setRequestHandler(S$,async()=>{return W.client.listResources()}),Z.server.setRequestHandler(k$,async(K)=>{return W.client.readResource(K.params)}),Z.server.setRequestHandler(v$,async()=>{return W.client.listResourceTemplates()}),Z.server.setRequestHandler(_$,async()=>{return W.client.listPrompts()}),Z.server.setRequestHandler(y$,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 $J1=ZJ1;d40();var KJ1=new cQ;KJ1.all("/",async(Q)=>{return l40(Q.get("meshContext")).fetch(Q.req.raw)});var HJ1=KJ1;J40();HU();fM();f9();var xJ1="vercel.ai.error",lS6=Symbol.for(xJ1),FJ1,VJ1,L1=class Q extends(VJ1=Error,FJ1=lS6,VJ1){constructor({name:X,message:Y,cause:J}){super(Y);this[FJ1]=!0,this.name=X,this.cause=J}static isInstance(X){return Q.hasMarker(X,xJ1)}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}},gJ1="AI_APICallError",uJ1=`vercel.ai.error.${gJ1}`,dS6=Symbol.for(uJ1),qJ1,zJ1,r8=class extends(zJ1=L1,qJ1=dS6,zJ1){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:gJ1,message:Q,cause:Z});this[qJ1]=!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 L1.hasMarker(Q,uJ1)}},mJ1="AI_EmptyResponseBodyError",lJ1=`vercel.ai.error.${mJ1}`,pS6=Symbol.for(lJ1),UJ1,BJ1,dJ1=class extends(BJ1=L1,UJ1=pS6,BJ1){constructor({message:Q="Empty response body"}={}){super({name:mJ1,message:Q});this[UJ1]=!0}static isInstance(Q){return L1.hasMarker(Q,lJ1)}};function _5(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 pJ1="AI_InvalidArgumentError",cJ1=`vercel.ai.error.${pJ1}`,cS6=Symbol.for(cJ1),DJ1,NJ1,nJ1=class extends(NJ1=L1,DJ1=cS6,NJ1){constructor({message:Q,cause:X,argument:Y}){super({name:pJ1,message:Q,cause:X});this[DJ1]=!0,this.argument=Y}static isInstance(Q){return L1.hasMarker(Q,cJ1)}},iJ1="AI_InvalidPromptError",aJ1=`vercel.ai.error.${iJ1}`,nS6=Symbol.for(aJ1),OJ1,LJ1,XF=class extends(LJ1=L1,OJ1=nS6,LJ1){constructor({prompt:Q,message:X,cause:Y}){super({name:iJ1,message:`Invalid prompt: ${X}`,cause:Y});this[OJ1]=!0,this.prompt=Q}static isInstance(Q){return L1.hasMarker(Q,aJ1)}},rJ1="AI_InvalidResponseDataError",oJ1=`vercel.ai.error.${rJ1}`,iS6=Symbol.for(oJ1),wJ1,MJ1,ku4=class extends(MJ1=L1,wJ1=iS6,MJ1){constructor({data:Q,message:X=`Invalid response data: ${JSON.stringify(Q)}.`}){super({name:rJ1,message:X});this[wJ1]=!0,this.data=Q}static isInstance(Q){return L1.hasMarker(Q,oJ1)}},sJ1="AI_JSONParseError",tJ1=`vercel.ai.error.${sJ1}`,aS6=Symbol.for(tJ1),PJ1,TJ1,DP=class extends(TJ1=L1,PJ1=aS6,TJ1){constructor({text:Q,cause:X}){super({name:sJ1,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 yU(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=yU(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=yU(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=yU(Q,K);$.resolve(H),H.dispose(),Q.runtime.executePendingJobs()}catch(H){let F=_U(H),V=Q.newString(`Promise resolution error: ${F}`);$.reject(V),V.dispose(),Q.runtime.executePendingJobs()}}).catch((K)=>{let H=_U(K),F=Q.newString(`Promise rejection: ${H}`);$.reject(F),F.dispose(),Q.runtime.executePendingJobs()}),$.handle}return yU(Q,Z)}catch(W){let Z=_U(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 SS6=(Q)=>new Promise((X)=>setTimeout(X,Q));function QJ1(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 eY1(Q,X,Y){let J=Date.now(),G=Q.resolvePromise(X);while(!0){QJ1(Q);let W=await Promise.race([G,SS6(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 w80({tools:Q,code:X,timeoutMs:Y}){let Z=[];try{let J=await tY1({memoryLimitBytes:33554432,stackSizeBytes:524288});const G=Yb(Z,J.newContext({interruptAfterMs:Y}),0);const W=Yb(Z,MY1(G),0);try{let F=G.evalCode(X,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult(F),q=yU(G,Q);G.setProp(G.global,"tools",q);let z=G.runtime.hasPendingJob()?G.unwrapResult(await eY1(G,V,Y)):V;if(z!==V)V.dispose();let B=G.getProp(z,"default"),D=G.typeof(B);if(D!=="function")return{error:`Code must export default a function (tools). Got ${D}. Example: export default async (tools) => { /* ... */ }`,consoleLogs:W.logs};let L=G.callFunction(B,G.undefined,q),M=G.unwrapResult(L),C=await eY1(G,M,Y),A=G.unwrapResult(C);if(G.runtime.hasPendingJob())QJ1(G);return{returnValue:G.dump(A),consoleLogs:W.logs}}catch(F){return console.log(F),{error:_U(F),consoleLogs:W.logs}}}catch($){var K=$,H=1}finally{$Q0(Z,K,H)}}function vS6(Q){return Q.toLowerCase().split(/[\s_\-./]+/).filter((X)=>X.length>=2)}function kS6(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 _S6(Q,X,Y){let J=vS6(Q);if(J.length===0)return X.slice(0,Y);return X.map((G)=>({tool:G,score:kS6(J,G)})).filter((G)=>G.score>0).sort((G,W)=>W.score-G.score).slice(0,Y).map((G)=>G.tool)}function M80(Q){return{content:[{type:"text",text:JSON.stringify(Q,null,2)}]}}function BP(Q){return{content:[{type:"text",text:JSON.stringify(Q,null,2)}],isError:!0}}function XJ1(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 BP({error:G.error.flatten()});let W=_S6(G.data.query,Q.tools,G.data.limit);return M80({query:G.data.query,results:W.map((Z)=>({name:Z.name,description:Z.description,connection:Z._meta.connectionTitle})),totalAvailable:Q.tools.length})}}}function YJ1(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 BP({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 M80({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 yS6(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 BP({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 bS6(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 BP({error:J.error.flatten()});let G=Object.fromEntries(Q.tools.map((Z)=>[Z.name,async($)=>Q.callTool(Z.name,$??{})])),W=await w80({...J.data,tools:G});if(W.error)return BP(W);return M80(W)}}}function JJ1(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 fS6=(Q)=>({tools:Q.tools,callTool:(X,Y)=>Q.callTool(X,Y)}),hS6=(Q)=>JJ1([XJ1(Q),YJ1(Q),bS6(Q)]),xS6=(Q)=>JJ1([XJ1(Q),YJ1(Q),yS6(Q)]);function GJ1(Q){switch(Q){case"smart_tool_selection":return xS6;case"code_execution":return hS6;case"passthrough":default:return fS6}}class yy{proxies;options;cache;constructor(Q,X){this.proxies=Q;this.options=X;this.cache=GW(()=>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((z)=>!q.has(z.name))}}else if(K.selectedTools&&K.selectedTools.length>0){let q=new Set(K.selectedTools);V=V.filter((z)=>q.has(z.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})},$=GJ1(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 gS6(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 WJ1(Q,X){return X.some((Y)=>gS6(Q,Y))}class by{proxies;options;cache;constructor(Q,X){this.proxies=Q;this.options=X;this.cache=GW(()=>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)=>!WJ1(K.uri,G.selectedResources))}else if(!G.selectedResources||G.selectedResources.length===0)$=[];else $=$.filter((K)=>WJ1(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 fy{proxies;cache;constructor(Q){this.proxies=Q;this.cache=GW(()=>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 hy{proxies;options;cache;constructor(Q,X){this.proxies=Q;this.options=X;this.cache=GW(()=>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 ZJ1=new cQ;async function uS6(Q,X){let Y=await zP.create(Q.connections,X),J=new yy(Y,{selectionMode:Q.toolSelectionMode,strategy:Q.toolSelectionStrategy}),G=new by(Y,{selectionMode:Q.toolSelectionMode}),W=new fy(Y),Z=new hy(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 mS6(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 uS6(J,X)}ZJ1.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:"Agent ID required, or provide x-org-id or x-org-slug header for Organization Agent"},400)}if(!J){if(X)return Q.json({error:`Agent not found: ${X}`},404);return Q.json({error:"No Organization Agent configured for this organization"},404)}if(Y.gatewayId=J.id,J.status!=="active")return Q.json({error:`Agent 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 mS6(J,Y),Z=new a3({name:`mcp-gateway-${J.title}`,version:"1.0.0"},{capabilities:{tools:{},resources:{},prompts:{}}}),$=new r3({enableJsonResponse:Q.req.header("Accept")?.includes("application/json")??!1});return await Z.connect($),Z.server.setRequestHandler(b$,async(K)=>{return W.client.listTools()}),Z.server.setRequestHandler(eG,async(K)=>{return await W.client.callTool(K.params)}),Z.server.setRequestHandler(S$,async()=>{return W.client.listResources()}),Z.server.setRequestHandler(k$,async(K)=>{return W.client.readResource(K.params)}),Z.server.setRequestHandler(v$,async()=>{return W.client.listResourceTemplates()}),Z.server.setRequestHandler(_$,async()=>{return W.client.listPrompts()}),Z.server.setRequestHandler(y$,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 $J1=ZJ1;d40();var KJ1=new cQ;KJ1.all("/",async(Q)=>{return l40(Q.get("meshContext")).fetch(Q.req.raw)});var HJ1=KJ1;J40();HU();fM();f9();var xJ1="vercel.ai.error",lS6=Symbol.for(xJ1),FJ1,VJ1,L1=class Q extends(VJ1=Error,FJ1=lS6,VJ1){constructor({name:X,message:Y,cause:J}){super(Y);this[FJ1]=!0,this.name=X,this.cause=J}static isInstance(X){return Q.hasMarker(X,xJ1)}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}},gJ1="AI_APICallError",uJ1=`vercel.ai.error.${gJ1}`,dS6=Symbol.for(uJ1),qJ1,zJ1,r8=class extends(zJ1=L1,qJ1=dS6,zJ1){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:gJ1,message:Q,cause:Z});this[qJ1]=!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 L1.hasMarker(Q,uJ1)}},mJ1="AI_EmptyResponseBodyError",lJ1=`vercel.ai.error.${mJ1}`,pS6=Symbol.for(lJ1),UJ1,BJ1,dJ1=class extends(BJ1=L1,UJ1=pS6,BJ1){constructor({message:Q="Empty response body"}={}){super({name:mJ1,message:Q});this[UJ1]=!0}static isInstance(Q){return L1.hasMarker(Q,lJ1)}};function _5(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 pJ1="AI_InvalidArgumentError",cJ1=`vercel.ai.error.${pJ1}`,cS6=Symbol.for(cJ1),DJ1,NJ1,nJ1=class extends(NJ1=L1,DJ1=cS6,NJ1){constructor({message:Q,cause:X,argument:Y}){super({name:pJ1,message:Q,cause:X});this[DJ1]=!0,this.argument=Y}static isInstance(Q){return L1.hasMarker(Q,cJ1)}},iJ1="AI_InvalidPromptError",aJ1=`vercel.ai.error.${iJ1}`,nS6=Symbol.for(aJ1),OJ1,LJ1,XF=class extends(LJ1=L1,OJ1=nS6,LJ1){constructor({prompt:Q,message:X,cause:Y}){super({name:iJ1,message:`Invalid prompt: ${X}`,cause:Y});this[OJ1]=!0,this.prompt=Q}static isInstance(Q){return L1.hasMarker(Q,aJ1)}},rJ1="AI_InvalidResponseDataError",oJ1=`vercel.ai.error.${rJ1}`,iS6=Symbol.for(oJ1),wJ1,MJ1,ku4=class extends(MJ1=L1,wJ1=iS6,MJ1){constructor({data:Q,message:X=`Invalid response data: ${JSON.stringify(Q)}.`}){super({name:rJ1,message:X});this[wJ1]=!0,this.data=Q}static isInstance(Q){return L1.hasMarker(Q,oJ1)}},sJ1="AI_JSONParseError",tJ1=`vercel.ai.error.${sJ1}`,aS6=Symbol.for(tJ1),PJ1,TJ1,DP=class extends(TJ1=L1,PJ1=aS6,TJ1){constructor({text:Q,cause:X}){super({name:sJ1,message:`JSON parsing failed: Text: ${Q}.
|
|
1045
1045
|
Error message: ${_5(X)}`,cause:X});this[PJ1]=!0,this.text=Q}static isInstance(Q){return L1.hasMarker(Q,tJ1)}},eJ1="AI_LoadAPIKeyError",Q51=`vercel.ai.error.${eJ1}`,rS6=Symbol.for(Q51),AJ1,EJ1,_u4=class extends(EJ1=L1,AJ1=rS6,EJ1){constructor({message:Q}){super({name:eJ1,message:Q});this[AJ1]=!0}static isInstance(Q){return L1.hasMarker(Q,Q51)}},X51="AI_LoadSettingError",Y51=`vercel.ai.error.${X51}`,oS6=Symbol.for(Y51),jJ1,CJ1,yu4=class extends(CJ1=L1,jJ1=oS6,CJ1){constructor({message:Q}){super({name:X51,message:Q});this[jJ1]=!0}static isInstance(Q){return L1.hasMarker(Q,Y51)}},J51="AI_NoContentGeneratedError",G51=`vercel.ai.error.${J51}`,sS6=Symbol.for(G51),IJ1,RJ1,bu4=class extends(RJ1=L1,IJ1=sS6,RJ1){constructor({message:Q="No content generated."}={}){super({name:J51,message:Q});this[IJ1]=!0}static isInstance(Q){return L1.hasMarker(Q,G51)}},W51="AI_NoSuchModelError",Z51=`vercel.ai.error.${W51}`,tS6=Symbol.for(Z51),SJ1,vJ1,fu4=class extends(vJ1=L1,SJ1=tS6,vJ1){constructor({errorName:Q=W51,modelId:X,modelType:Y,message:J=`No such ${Y}: ${X}`}){super({name:Q,message:J});this[SJ1]=!0,this.modelId=X,this.modelType=Y}static isInstance(Q){return L1.hasMarker(Q,Z51)}},$51="AI_TooManyEmbeddingValuesForCallError",K51=`vercel.ai.error.${$51}`,eS6=Symbol.for(K51),kJ1,_J1,hu4=class extends(_J1=L1,kJ1=eS6,_J1){constructor(Q){super({name:$51,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[kJ1]=!0,this.provider=Q.provider,this.modelId=Q.modelId,this.maxEmbeddingsPerCall=Q.maxEmbeddingsPerCall,this.values=Q.values}static isInstance(Q){return L1.hasMarker(Q,K51)}},H51="AI_TypeValidationError",F51=`vercel.ai.error.${H51}`,Qv6=Symbol.for(F51),yJ1,bJ1,y5=class Q extends(bJ1=L1,yJ1=Qv6,bJ1){constructor({value:X,cause:Y}){super({name:H51,message:`Type validation failed: Value: ${JSON.stringify(X)}.
|
|
1046
1046
|
Error message: ${_5(Y)}`,cause:Y});this[yJ1]=!0,this.value=X}static isInstance(X){return L1.hasMarker(X,F51)}static wrap({value:X,cause:Y}){return Q.isInstance(Y)&&Y.value===X?Y:new Q({value:X,cause:Y})}},V51="AI_UnsupportedFunctionalityError",q51=`vercel.ai.error.${V51}`,Xv6=Symbol.for(q51),fJ1,hJ1,xu4=class extends(hJ1=L1,fJ1=Xv6,hJ1){constructor({functionality:Q,message:X=`'${Q}' functionality not supported.`}){super({name:V51,message:X});this[fJ1]=!0,this.functionality=Q}static isInstance(Q){return L1.hasMarker(Q,q51)}};r6();C$();C$();C$();E60();function JF(...Q){return Q.reduce((X,Y)=>({...X,...Y!=null?Y:{}}),{})}async function L51(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(z51());return}let W=setTimeout(()=>{Z(),J()},Q),Z=()=>{clearTimeout(W),Y==null||Y.removeEventListener("abort",$)},$=()=>{Z(),G(z51())};Y==null||Y.addEventListener("abort",$)})}function z51(){return new DOMException("Delay was aborted","AbortError")}var GF=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 NP(Q){return Object.fromEntries([...Q.headers])}var{btoa:Yv6,atob:Jv6}=globalThis;function bU(Q){let X=Q.replace(/-/g,"+").replace(/_/g,"/"),Y=Jv6(X);return Uint8Array.from(Y,(J)=>J.codePointAt(0))}function WF(Q){let X="";for(let Y=0;Y<Q.length;Y++)X+=String.fromCodePoint(Q[Y]);return Yv6(X)}var w51="AI_DownloadError",M51=`vercel.ai.error.${w51}`,Gv6=Symbol.for(M51),U51,B51,xy=class extends(B51=L1,U51=Gv6,B51){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:w51,message:G,cause:J});this[U51]=!0,this.url=Q,this.statusCode=X,this.statusText=Y}static isInstance(Q){return L1.hasMarker(Q,M51)}};var WW=({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 nJ1({argument:"separator",message:`The separator "${J}" must not be part of the alphabet "${Y}".`});return()=>`${Q}${J}${G()}`},Wv6=WW();function OP(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 u7(Q){return(Q instanceof Error||Q instanceof DOMException)&&(Q.name==="AbortError"||Q.name==="ResponseAborted"||Q.name==="TimeoutError")}var Zv6=["fetch failed","failed to fetch"];function P51({error:Q,url:X,requestBodyValues:Y}){if(u7(Q))return Q;if(Q instanceof TypeError&&Zv6.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 gy(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 $v6(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 t$(Q,...X){let Y=new Headers($v6(Q)),J=Y.get("user-agent")||"";return Y.set("user-agent",[J,...X].filter(Boolean).join(" ")),Object.fromEntries(Y.entries())}var T51="4.0.4",Kv6=()=>globalThis.fetch,j80=async({url:Q,headers:X={},successfulResponseHandler:Y,failedResponseHandler:J,abortSignal:G,fetch:W=Kv6()})=>{try{let Z=await W(Q,{method:"GET",headers:t$(X,`ai-sdk/provider-utils/${T51}`,gy()),signal:G}),$=NP(Z);if(!Z.ok){let K;try{K=await J({response:Z,url:Q,requestBodyValues:{}})}catch(H){if(u7(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(u7(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 P51({error:Z,url:Q,requestBodyValues:{}})}};function A51(Q){return Q!=null}function E51({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 LP({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 Hv6=/"__proto__"\s*:/,Fv6=/"constructor"\s*:/;function D51(Q){let X=JSON.parse(Q);if(X===null||typeof X!=="object")return X;if(Hv6.test(Q)===!1&&Fv6.test(Q)===!1)return X;return Vv6(X)}function Vv6(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 j51(Q){let{stackTraceLimit:X}=Error;try{Error.stackTraceLimit=0}catch(Y){return D51(Q)}try{return D51(Q)}finally{Error.stackTraceLimit=X}}function C51(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]=YF(Y[J])}if(Q.items!=null)Q.items=Array.isArray(Q.items)?Q.items.map(YF):YF(Q.items);if(Q.anyOf!=null)Q.anyOf=Q.anyOf.map(YF);if(Q.allOf!=null)Q.allOf=Q.allOf.map(YF);if(Q.oneOf!=null)Q.oneOf=Q.oneOf.map(YF);let{definitions:X}=Q;if(X!=null)for(let Y of Object.keys(X))X[Y]=YF(X[Y]);return Q}function YF(Q){if(typeof Q==="boolean")return Q;return C51(Q)}var qv6=Symbol("Let zodToJsonSchema decide on which parser to use"),N51={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"},zv6=(Q)=>typeof Q==="string"?{...N51,name:Q}:{...N51,...Q};function bY(){return{}}function Uv6(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)!==E0.ZodAny)W.items=b4(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 Bv6(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 Dv6(){return{type:"boolean"}}function I51(Q,X){return b4(Q.type._def,X)}var Nv6=(Q,X)=>{return b4(Q.innerType._def,X)};function R51(Q,X,Y){let J=Y!=null?Y:X.dateStrategy;if(Array.isArray(J))return{anyOf:J.map((G,W)=>R51(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 Ov6(Q)}}var Ov6=(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 Lv6(Q,X){return{...b4(Q.innerType._def,X),default:Q.defaultValue()}}function wv6(Q,X){return X.effectStrategy==="input"?b4(Q.schema._def,X):bY()}function Mv6(Q){return{type:"string",enum:Array.from(Q.values)}}var Pv6=(Q)=>{if("type"in Q&&Q.type==="string")return!1;return"allOf"in Q};function Tv6(Q,X){let Y=[b4(Q.left._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),b4(Q.right._def,{...X,currentPath:[...X.currentPath,"allOf","1"]})].filter((G)=>!!G),J=[];return Y.forEach((G)=>{if(Pv6(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 Av6(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 P80=void 0,b5={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(P80===void 0)P80=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return P80},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 S51(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":f5(Y,"email",J.message,X);break;case"format:idn-email":f5(Y,"idn-email",J.message,X);break;case"pattern:zod":OX(Y,b5.email,J.message,X);break}break;case"url":f5(Y,"uri",J.message,X);break;case"uuid":f5(Y,"uuid",J.message,X);break;case"regex":OX(Y,J.regex,J.message,X);break;case"cuid":OX(Y,b5.cuid,J.message,X);break;case"cuid2":OX(Y,b5.cuid2,J.message,X);break;case"startsWith":OX(Y,RegExp(`^${T80(J.value,X)}`),J.message,X);break;case"endsWith":OX(Y,RegExp(`${T80(J.value,X)}$`),J.message,X);break;case"datetime":f5(Y,"date-time",J.message,X);break;case"date":f5(Y,"date",J.message,X);break;case"time":f5(Y,"time",J.message,X);break;case"duration":f5(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":{OX(Y,RegExp(T80(J.value,X)),J.message,X);break}case"ip":{if(J.version!=="v6")f5(Y,"ipv4",J.message,X);if(J.version!=="v4")f5(Y,"ipv6",J.message,X);break}case"base64url":OX(Y,b5.base64url,J.message,X);break;case"jwt":OX(Y,b5.jwt,J.message,X);break;case"cidr":{if(J.version!=="v6")OX(Y,b5.ipv4Cidr,J.message,X);if(J.version!=="v4")OX(Y,b5.ipv6Cidr,J.message,X);break}case"emoji":OX(Y,b5.emoji(),J.message,X);break;case"ulid":{OX(Y,b5.ulid,J.message,X);break}case"base64":{switch(X.base64Strategy){case"format:binary":{f5(Y,"binary",J.message,X);break}case"contentEncoding:base64":{Y.contentEncoding="base64";break}case"pattern:zod":{OX(Y,b5.base64,J.message,X);break}}break}case"nanoid":OX(Y,b5.nanoid,J.message,X);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return Y}function T80(Q,X){return X.patternStrategy==="escape"?jv6(Q):Q}var Ev6=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function jv6(Q){let X="";for(let Y=0;Y<Q.length;Y++){if(!Ev6.has(Q[Y]))X+="\\";X+=Q[Y]}return X}function f5(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 OX(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:O51(X,J),...Y&&J.errorMessages&&{errorMessage:{pattern:Y}}})}else Q.pattern=O51(X,J)}function O51(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
|