@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.
Files changed (117) hide show
  1. package/dist/client/assets/{AlertCircle-DiqlNboz.js → AlertCircle-laxSE0PX.js} +1 -1
  2. package/dist/client/assets/{ArrowLeft-C4VtVMs2.js → ArrowLeft-Dd7BK5dX.js} +1 -1
  3. package/dist/client/assets/{ChevronDown-CcUg3X_Y.js → ChevronDown-CvWv-usR.js} +1 -1
  4. package/dist/client/assets/{ChevronRight-DoX6pxYj.js → ChevronRight-Fe_n2oGa.js} +1 -1
  5. package/dist/client/assets/{Copy01-BJql3T8w.js → Copy01-C6NIIZuG.js} +1 -1
  6. package/dist/client/assets/{DotsHorizontal-wWvFFsxa.js → DotsHorizontal-Cw17Pnyf.js} +1 -1
  7. package/dist/client/assets/{DotsVertical-C_psDJy3.js → DotsVertical-CH2fNSbY.js} +1 -1
  8. package/dist/client/assets/{File06-CfmzgkCD.js → File06-BFg45elm.js} +1 -1
  9. package/dist/client/assets/{FilterLines-MNaVyood.js → FilterLines-BjvAuET2.js} +1 -1
  10. package/dist/client/assets/{FlipBackward-qa1GrgeQ.js → FlipBackward-BCF9hA9D.js} +1 -1
  11. package/dist/client/assets/{GitBranch01-Cy-aTD__.js → GitBranch01-5UP5g_4t.js} +1 -1
  12. package/dist/client/assets/{Grid01-400pwqps.js → Grid01-Soc1w0HN.js} +1 -1
  13. package/dist/client/assets/{Inbox01-DQ40if0u.js → Inbox01-D8CnGo7i.js} +1 -1
  14. package/dist/client/assets/{InfoCircle-DbgHopMm.js → InfoCircle-CJE1rYNL.js} +1 -1
  15. package/dist/client/assets/{Key01-CXPRpQE9.js → Key01-D6Y52TVu.js} +1 -1
  16. package/dist/client/assets/{LinkExternal01-BJZvPGF2.js → LinkExternal01-DbeN7vxS.js} +1 -1
  17. package/dist/client/assets/{Loading01-DSWhKp36.js → Loading01-B8IKnW3x.js} +1 -1
  18. package/dist/client/assets/{Lock01-Cw5Gl3NV.js → Lock01-DGGIBBCl.js} +1 -1
  19. package/dist/client/assets/{Play-18tBEZWZ.js → Play-D2jnwQAI.js} +1 -1
  20. package/dist/client/assets/{Plus-SMn8MQ-H.js → Plus-3Cnjm1UT.js} +1 -1
  21. package/dist/client/assets/{Terminal-yR92omIF.js → Terminal-vZCLGbvo.js} +1 -1
  22. package/dist/client/assets/{Trash01-DaFJSHZu.js → Trash01-D0jDlYQJ.js} +1 -1
  23. package/dist/client/assets/{X-q_t7ZUi-.js → X-CrCcl1sv.js} +1 -1
  24. package/dist/client/assets/{XClose-2lFeEEkz.js → XClose-DZ7ckVTf.js} +1 -1
  25. package/dist/client/assets/{alert-dialog-BOjS3GrS.js → alert-dialog-BHM4cw4Q.js} +2 -2
  26. package/dist/client/assets/{auth-BvEfLR40.js → auth-BfhoYwZo.js} +1 -1
  27. package/dist/client/assets/{auth-catchall-qnrnPCT6.js → auth-catchall-BQuGaWdj.js} +1 -1
  28. package/dist/client/assets/{avatar-D8KYLrun.js → avatar-CBETgvTo.js} +1 -1
  29. package/dist/client/assets/{badge-DHFuTJNA.js → badge-BoEIasGQ.js} +1 -1
  30. package/dist/client/assets/{card-CSWNwOPv.js → card-TBEiO_pf.js} +1 -1
  31. package/dist/client/assets/{checkbox-D6eJScSi.js → checkbox-CFS6LZcp.js} +1 -1
  32. package/dist/client/assets/{collection-detail-cLR1iiCF.js → collection-detail-BnDPq9AR.js} +18 -18
  33. package/dist/client/assets/{collection-display-button-DWBgVnY5.js → collection-display-button-KvR7sWeM.js} +1 -1
  34. package/dist/client/assets/{collection-header-BYkZ9Trb.js → collection-header-f1ffdO7f.js} +1 -1
  35. package/dist/client/assets/{collection-page-BjyL0NfT.js → collection-page-WZgTp5Lv.js} +1 -1
  36. package/dist/client/assets/{collection-search-BhTsTIQF.js → collection-search-3XPe6V_T.js} +1 -1
  37. package/dist/client/assets/{collection-tab-ByD_c7B5.js → collection-tab-CNcWbqd2.js} +1 -1
  38. package/dist/client/assets/{collection-table-wrapper-G4nlfvjF.js → collection-table-wrapper-B34CJdmN.js} +1 -1
  39. package/dist/client/assets/{connection-card-BRub-GLZ.js → connection-card-AILFqLN1.js} +1 -1
  40. package/dist/client/assets/connection-detail-Dkmb8FZw.js +1 -0
  41. package/dist/client/assets/{connections-BEv7u43V.js → connections-Ce1zfRUl.js} +1 -1
  42. package/dist/client/assets/constants-D2EL4NMa.js +1 -0
  43. package/dist/client/assets/{create-organization-dialog-CahJq4TL.js → create-organization-dialog-6aGfA3nN.js} +1 -1
  44. package/dist/client/assets/{dialog-Ay6PD9W0.js → dialog-By5cpA-o.js} +1 -1
  45. package/dist/client/assets/{dropdown-menu-CX0_ej-t.js → dropdown-menu-CxU4B3XS.js} +1 -1
  46. package/dist/client/assets/{empty-state-DOXYCllo.js → empty-state-DDZV3qxG.js} +1 -1
  47. package/dist/client/assets/{env-vars-editor-DB_yBian.js → env-vars-editor-CLtT_Pn2.js} +1 -1
  48. package/dist/client/assets/{error-boundary-BITgBYMF.js → error-boundary-DFjr3eHD.js} +1 -1
  49. package/dist/client/assets/{extract-connection-data-CaZ0wil0.js → extract-connection-data-CNLQVqLl.js} +1 -1
  50. package/dist/client/assets/{form-CTm5F5lc.js → form-BAnmUhVa.js} +1 -1
  51. package/dist/client/assets/gateway-detail-CD1SXTO4.js +1 -0
  52. package/dist/client/assets/gateway-selector-BC3bwpkS.js +1 -0
  53. package/dist/client/assets/gateways-BPDYdmPL.js +1 -0
  54. package/dist/client/assets/{home-BCE1FamF.js → home-CxQ-oPDQ.js} +1 -1
  55. package/dist/client/assets/index-BQaN6CW7.js +25 -0
  56. package/dist/client/assets/{index-DU53zBhA.css → index-BV_tzcZC.css} +1 -1
  57. package/dist/client/assets/{index-Tg8Sdg8t.js → index-CIDbVI0o.js} +2 -2
  58. package/dist/client/assets/{index-DskbBe5h.js → index-DxSQLqqY.js} +1 -1
  59. package/dist/client/assets/{input-DZxsngZP.js → input-BYLamBFT.js} +1 -1
  60. package/dist/client/assets/{layout-Brqmaefj.js → layout-CPjqBR8a.js} +1 -1
  61. package/dist/client/assets/{lazy-highlighter-CiDPKksG.js → lazy-highlighter-L5Lo_GWJ.js} +1 -1
  62. package/dist/client/assets/localstorage-keys-BcKYfcRC.js +1 -0
  63. package/dist/client/assets/{login-DTvg0d0e.js → login-CWasMrLi.js} +1 -1
  64. package/dist/client/assets/{mcp-oauth-SMi_MNm0.js → mcp-oauth-BbYG4wEg.js} +1 -1
  65. package/dist/client/assets/{mcp-server-detail-Dp4c82jn.js → mcp-server-detail-DL1XSpPt.js} +1 -1
  66. package/dist/client/assets/{members-Antj9sp8.js → members-Cm7y0IGn.js} +1 -1
  67. package/dist/client/assets/{monaco-editor-DzF_l7qF.js → monaco-editor-BANuhZc7.js} +1 -1
  68. package/dist/client/assets/{monitoring-CFWL1rLz.js → monitoring-CypFTCwZ.js} +3 -3
  69. package/dist/client/assets/{oauth-callback-CG8hLD-b.js → oauth-callback-BljFGwn2.js} +1 -1
  70. package/dist/client/assets/page-B3Vk0n7G.js +35 -0
  71. package/dist/client/assets/{page-BvT1wvbD.js → page-DPBKFn7H.js} +1 -1
  72. package/dist/client/assets/{pin-to-sidebar-button-fGogNndB.js → pin-to-sidebar-button-GermWsTp.js} +1 -1
  73. package/dist/client/assets/{popover-D8pPVQL_.js → popover-BXzChz3h.js} +1 -1
  74. package/dist/client/assets/{project-context-provider-DzGl09z5.js → project-context-provider-rr2ZgefD.js} +1 -1
  75. package/dist/client/assets/{resizable-RYzDqksM.js → resizable-DKOKD5be.js} +1 -1
  76. package/dist/client/assets/{resource-tabs-Dx00akPb.js → resource-tabs-UF1uUrPS.js} +1 -1
  77. package/dist/client/assets/{select-DXarH3zI.js → select-8RE8G2EV.js} +1 -1
  78. package/dist/client/assets/{settings-CppuOJKP.js → settings-WmaC0ugB.js} +1 -1
  79. package/dist/client/assets/shell-layout-DLeQwwOP.js +1 -0
  80. package/dist/client/assets/{spinner-BlgPNYJ_.js → spinner-CeWqo2ib.js} +1 -1
  81. package/dist/client/assets/{switch-D8JX4qkY.js → switch-CxhRshQs.js} +1 -1
  82. package/dist/client/assets/{textarea-B4gwvsMJ.js → textarea-DbQy5F3n.js} +1 -1
  83. package/dist/client/assets/{thread-history-popover-BGdJj9Uf.js → thread-history-popover-Dh1623de.js} +82 -45
  84. package/dist/client/assets/{tools-list-PNSOJy0p.js → tools-list-Bf2FOeAk.js} +1 -1
  85. package/dist/client/assets/{use-binding-BrFwEM85.js → use-binding-B-kSZTGy.js} +1 -1
  86. package/dist/client/assets/{use-connection-C0rtvbAv.js → use-connection-DFkAC4Is.js} +1 -1
  87. package/dist/client/assets/use-connection-resources-BYLrv2O6.js +1 -0
  88. package/dist/client/assets/{use-gateway-XK2Ec2c7.js → use-gateway-QZNjV_Br.js} +1 -1
  89. package/dist/client/assets/use-gateway-system-prompt-DowqNUnD.js +1 -0
  90. package/dist/client/assets/{use-list-state-CaOiitHv.js → use-list-state-oVkbwyL1.js} +1 -1
  91. package/dist/client/assets/{use-mcp-DP2e7Pak.js → use-mcp-B38V1Eo_.js} +1 -1
  92. package/dist/client/assets/{use-members-BZIlp51_.js → use-members-B5ZPlWxC.js} +1 -1
  93. package/dist/client/assets/{use-mobile-C9ZrGbF1.js → use-mobile-DKb1FXwT.js} +1 -1
  94. package/dist/client/assets/{use-organization-settings-CpuYghUf.js → use-organization-settings-DDkza1UL.js} +1 -1
  95. package/dist/client/assets/{use-tool-call-BLCuCQA5.js → use-tool-call-CkogDXv4.js} +1 -1
  96. package/dist/client/assets/useQueries-D02scwU5.js +1 -0
  97. package/dist/client/assets/useQuery-Cu8VEtZR.js +1 -0
  98. package/dist/client/assets/{value-C6pOmVvH.js → value-0Lc1LEd3.js} +1 -1
  99. package/dist/client/assets/{view-mode-toggle-BegVAMeC.js → view-mode-toggle-C8FGoH5Z.js} +1 -1
  100. package/dist/client/assets/{workflow-ChKb4zdL.js → workflow-C4jHNR-h.js} +1 -1
  101. package/dist/client/index.html +2 -2
  102. package/dist/server/cli.js +2 -2
  103. package/dist/server/migrate.js +2 -2
  104. package/dist/server/server.js +3 -3
  105. package/package.json +1 -1
  106. package/dist/client/assets/connection-detail-DgCsw2FN.js +0 -1
  107. package/dist/client/assets/constants-CxNag89_.js +0 -1
  108. package/dist/client/assets/formatDistanceToNow-Da1WFNC1.js +0 -1
  109. package/dist/client/assets/gateway-detail-ZvOmrysO.js +0 -1
  110. package/dist/client/assets/gateway-selector-zAzGBjF_.js +0 -1
  111. package/dist/client/assets/gateways-JihiLKrE.js +0 -1
  112. package/dist/client/assets/index-DOV_cVSz.js +0 -25
  113. package/dist/client/assets/localstorage-keys-Bmzia9Ql.js +0 -1
  114. package/dist/client/assets/page-CBEZJuHw.js +0 -35
  115. package/dist/client/assets/shell-layout-9hZXlinq.js +0 -19
  116. package/dist/client/assets/use-connection-resources-85AsmF-4.js +0 -1
  117. package/dist/client/assets/useQuery-CDC7rIFj.js +0 -1
@@ -986,7 +986,7 @@ data:
986
986
 
987
987
  `,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)=>iY.parse(L));else Z=[iY.parse(W)]}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}let $=Z.some(va);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(QW)){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)=>va(L)),V=F?F.params.protocolVersion:Q.headers.get("mcp-protocol-version")??nL0;if(this._enableJsonResponse)return new Promise((L)=>{this._streamMapping.set(H,{resolveJson:L,cleanup:()=>{this._streamMapping.delete(H)}});for(let M of Z)if(QW(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(QW(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(QW(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&&!O3.includes(X))return this.createJsonErrorResponse(400,-32000,`Bad Request: Unsupported protocol version: ${X} (supported versions: ${O3.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(E5(Q)||wz(Q))Y=Q.id;if(Y===void 0){if(E5(Q)||wz(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(E5(Q)||wz(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 av=y(()=>{s9()});var yw=(...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 gj0{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?yw(...this.callToolMiddlewares):null,X=()=>{let Y=new j3({name:this.config.name,version:this.config.version},{capabilities:this.config.capabilities});for(let J of this.tools){let G=async(K)=>{try{let H=await J.handler(K);return{content:[{type:"text",text:JSON.stringify(H)}],structuredContent:H}}catch(H){return{content:[{type:"text",text:`Error: ${H.message}`}],isError:!0}}},W=Q?async(K)=>{let H={method:"tools/call",params:{name:J.name,arguments:K}};return await Q(H,()=>G(K))}:G,Z="shape"in J.inputSchema?J.inputSchema.shape:N.object({}).shape,$=J.outputSchema&&"shape"in J.outputSchema?J.outputSchema.shape:N.object({}).shape;Y.registerTool(J.name,{annotations:J.annotations,description:J.description??"",inputSchema:Z,outputSchema:$},W)}return Y};return{callStreamableTool:async(Y,J)=>{let G=this.tools.find((Z)=>Z.name===Y);if(!G)throw Error(`Tool ${Y} not found`);let W=await G.handler(J);if(!(W instanceof Response))throw Error(`Tool ${Y} returned a non-response`);return W},client:{listTools:async()=>{return{tools:this.tools.map((Y)=>({name:Y.name,description:Y.description??"",inputSchema:N.toJSONSchema(Y.inputSchema),outputSchema:Y.outputSchema?N.toJSONSchema(Y.outputSchema):void 0}))}},callTool:async(Y)=>{let J=this.tools.find((G)=>G.name===Y.name);if(!J)return{content:[{type:"text",text:"Tool not found"}]};try{let G=await J?.handler(Y.arguments??{});return{content:[{type:"text",text:JSON.stringify(G)}],structuredContent:G}}catch(G){return{content:[{type:"text",text:`Error: ${G.message}`}]}}}},fetch:async(Y)=>{let J=new C3({enableJsonResponse:Y.headers.get("Accept")?.includes("application/json")??!1});return await X().connect(J),await J.handleRequest(Y)}}}}function uj0(Q){return new gj0(Q)}var mj0=y(()=>{iv();av();W6()});var pj0=I((lj0)=>{Object.defineProperty(lj0,"__esModule",{value:!0});lj0._globalThis=void 0;lj0._globalThis=typeof globalThis==="object"?globalThis:global});var cj0=I((I3)=>{var At6=I3&&I3.__createBinding||(Object.create?function(Q,X,Y,J){if(J===void 0)J=Y;Object.defineProperty(Q,J,{enumerable:!0,get:function(){return X[Y]}})}:function(Q,X,Y,J){if(J===void 0)J=Y;Q[J]=X[Y]}),Et6=I3&&I3.__exportStar||function(Q,X){for(var Y in Q)if(Y!=="default"&&!Object.prototype.hasOwnProperty.call(X,Y))At6(X,Q,Y)};Object.defineProperty(I3,"__esModule",{value:!0});Et6(pj0(),I3)});var nj0=I((R3)=>{var jt6=R3&&R3.__createBinding||(Object.create?function(Q,X,Y,J){if(J===void 0)J=Y;Object.defineProperty(Q,J,{enumerable:!0,get:function(){return X[Y]}})}:function(Q,X,Y,J){if(J===void 0)J=Y;Q[J]=X[Y]}),Ct6=R3&&R3.__exportStar||function(Q,X){for(var Y in Q)if(Y!=="default"&&!Object.prototype.hasOwnProperty.call(X,Y))jt6(X,Q,Y)};Object.defineProperty(R3,"__esModule",{value:!0});Ct6(cj0(),R3)});var Bs=I((ij0)=>{Object.defineProperty(ij0,"__esModule",{value:!0});ij0.VERSION=void 0;ij0.VERSION="1.9.0"});var ej0=I((sj0)=>{Object.defineProperty(sj0,"__esModule",{value:!0});sj0.isCompatible=sj0._makeCompatibilityCheck=void 0;var It6=Bs(),rj0=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function oj0(Q){let X=new Set([Q]),Y=new Set,J=Q.match(rj0);if(!J)return()=>!1;let G={major:+J[1],minor:+J[2],patch:+J[3],prerelease:J[4]};if(G.prerelease!=null)return function(K){return K===Q};function W($){return Y.add($),!1}function Z($){return X.add($),!0}return function(K){if(X.has(K))return!0;if(Y.has(K))return!1;let H=K.match(rj0);if(!H)return W(K);let F={major:+H[1],minor:+H[2],patch:+H[3],prerelease:H[4]};if(F.prerelease!=null)return W(K);if(G.major!==F.major)return W(K);if(G.major===0){if(G.minor===F.minor&&G.patch<=F.patch)return Z(K);return W(K)}if(G.minor<=F.minor)return Z(K);return W(K)}}sj0._makeCompatibilityCheck=oj0;sj0.isCompatible=oj0(It6.VERSION)});var S3=I((Q20)=>{Object.defineProperty(Q20,"__esModule",{value:!0});Q20.unregisterGlobal=Q20.getGlobal=Q20.registerGlobal=void 0;var St6=nj0(),pz=Bs(),vt6=ej0(),kt6=pz.VERSION.split(".")[0],bw=Symbol.for(`opentelemetry.js.api.${kt6}`),fw=St6._globalThis;function _t6(Q,X,Y,J=!1){var G;let W=fw[bw]=(G=fw[bw])!==null&&G!==void 0?G:{version:pz.VERSION};if(!J&&W[Q]){let Z=Error(`@opentelemetry/api: Attempted duplicate registration of API: ${Q}`);return Y.error(Z.stack||Z.message),!1}if(W.version!==pz.VERSION){let Z=Error(`@opentelemetry/api: Registration of version v${W.version} for ${Q} does not match previously registered API v${pz.VERSION}`);return Y.error(Z.stack||Z.message),!1}return W[Q]=X,Y.debug(`@opentelemetry/api: Registered a global for ${Q} v${pz.VERSION}.`),!0}Q20.registerGlobal=_t6;function yt6(Q){var X,Y;let J=(X=fw[bw])===null||X===void 0?void 0:X.version;if(!J||!(0,vt6.isCompatible)(J))return;return(Y=fw[bw])===null||Y===void 0?void 0:Y[Q]}Q20.getGlobal=yt6;function bt6(Q,X){X.debug(`@opentelemetry/api: Unregistering a global for ${Q} v${pz.VERSION}.`);let Y=fw[bw];if(Y)delete Y[Q]}Q20.unregisterGlobal=bt6});var W20=I((J20)=>{Object.defineProperty(J20,"__esModule",{value:!0});J20.DiagComponentLogger=void 0;var xt6=S3();class Y20{constructor(Q){this._namespace=Q.namespace||"DiagComponentLogger"}debug(...Q){return hw("debug",this._namespace,Q)}error(...Q){return hw("error",this._namespace,Q)}info(...Q){return hw("info",this._namespace,Q)}warn(...Q){return hw("warn",this._namespace,Q)}verbose(...Q){return hw("verbose",this._namespace,Q)}}J20.DiagComponentLogger=Y20;function hw(Q,X,Y){let J=(0,xt6.getGlobal)("diag");if(!J)return;return Y.unshift(X),J[Q](...Y)}});var rv=I((Z20)=>{Object.defineProperty(Z20,"__esModule",{value:!0});Z20.DiagLogLevel=void 0;var gt6;(function(Q){Q[Q.NONE=0]="NONE",Q[Q.ERROR=30]="ERROR",Q[Q.WARN=50]="WARN",Q[Q.INFO=60]="INFO",Q[Q.DEBUG=70]="DEBUG",Q[Q.VERBOSE=80]="VERBOSE",Q[Q.ALL=9999]="ALL"})(gt6=Z20.DiagLogLevel||(Z20.DiagLogLevel={}))});var H20=I(($20)=>{Object.defineProperty($20,"__esModule",{value:!0});$20.createLogLevelDiagLogger=void 0;var x7=rv();function ut6(Q,X){if(Q<x7.DiagLogLevel.NONE)Q=x7.DiagLogLevel.NONE;else if(Q>x7.DiagLogLevel.ALL)Q=x7.DiagLogLevel.ALL;X=X||{};function Y(J,G){let W=X[J];if(typeof W==="function"&&Q>=G)return W.bind(X);return function(){}}return{error:Y("error",x7.DiagLogLevel.ERROR),warn:Y("warn",x7.DiagLogLevel.WARN),info:Y("info",x7.DiagLogLevel.INFO),debug:Y("debug",x7.DiagLogLevel.DEBUG),verbose:Y("verbose",x7.DiagLogLevel.VERBOSE)}}$20.createLogLevelDiagLogger=ut6});var v3=I((V20)=>{Object.defineProperty(V20,"__esModule",{value:!0});V20.DiagAPI=void 0;var mt6=W20(),lt6=H20(),F20=rv(),ov=S3(),dt6="diag";class Ns{constructor(){function Q(J){return function(...G){let W=(0,ov.getGlobal)("diag");if(!W)return;return W[J](...G)}}let X=this,Y=(J,G={logLevel:F20.DiagLogLevel.INFO})=>{var W,Z,$;if(J===X){let F=Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return X.error((W=F.stack)!==null&&W!==void 0?W:F.message),!1}if(typeof G==="number")G={logLevel:G};let K=(0,ov.getGlobal)("diag"),H=(0,lt6.createLogLevelDiagLogger)((Z=G.logLevel)!==null&&Z!==void 0?Z:F20.DiagLogLevel.INFO,J);if(K&&!G.suppressOverrideMessage){let F=($=Error().stack)!==null&&$!==void 0?$:"<failed to generate stacktrace>";K.warn(`Current logger will be overwritten from ${F}`),H.warn(`Current logger will overwrite one already registered from ${F}`)}return(0,ov.registerGlobal)("diag",H,X,!0)};X.setLogger=Y,X.disable=()=>{(0,ov.unregisterGlobal)(dt6,X)},X.createComponentLogger=(J)=>{return new mt6.DiagComponentLogger(J)},X.verbose=Q("verbose"),X.debug=Q("debug"),X.info=Q("info"),X.warn=Q("warn"),X.error=Q("error")}static instance(){if(!this._instance)this._instance=new Ns;return this._instance}}V20.DiagAPI=Ns});var B20=I((z20)=>{Object.defineProperty(z20,"__esModule",{value:!0});z20.BaggageImpl=void 0;class cz{constructor(Q){this._entries=Q?new Map(Q):new Map}getEntry(Q){let X=this._entries.get(Q);if(!X)return;return Object.assign({},X)}getAllEntries(){return Array.from(this._entries.entries()).map(([Q,X])=>[Q,X])}setEntry(Q,X){let Y=new cz(this._entries);return Y._entries.set(Q,X),Y}removeEntry(Q){let X=new cz(this._entries);return X._entries.delete(Q),X}removeEntries(...Q){let X=new cz(this._entries);for(let Y of Q)X._entries.delete(Y);return X}clear(){return new cz}}z20.BaggageImpl=cz});var O20=I((D20)=>{Object.defineProperty(D20,"__esModule",{value:!0});D20.baggageEntryMetadataSymbol=void 0;D20.baggageEntryMetadataSymbol=Symbol("BaggageEntryMetadata")});var Os=I((L20)=>{Object.defineProperty(L20,"__esModule",{value:!0});L20.baggageEntryMetadataFromString=L20.createBaggage=void 0;var pt6=v3(),ct6=B20(),nt6=O20(),it6=pt6.DiagAPI.instance();function at6(Q={}){return new ct6.BaggageImpl(new Map(Object.entries(Q)))}L20.createBaggage=at6;function rt6(Q){if(typeof Q!=="string")it6.error(`Cannot create baggage metadata from unknown type: ${typeof Q}`),Q="";return{__TYPE__:nt6.baggageEntryMetadataSymbol,toString(){return Q}}}L20.baggageEntryMetadataFromString=rt6});var xw=I((M20)=>{Object.defineProperty(M20,"__esModule",{value:!0});M20.ROOT_CONTEXT=M20.createContextKey=void 0;function st6(Q){return Symbol.for(Q)}M20.createContextKey=st6;class sv{constructor(Q){let X=this;X._currentContext=Q?new Map(Q):new Map,X.getValue=(Y)=>X._currentContext.get(Y),X.setValue=(Y,J)=>{let G=new sv(X._currentContext);return G._currentContext.set(Y,J),G},X.deleteValue=(Y)=>{let J=new sv(X._currentContext);return J._currentContext.delete(Y),J}}}M20.ROOT_CONTEXT=new sv});var j20=I((A20)=>{Object.defineProperty(A20,"__esModule",{value:!0});A20.DiagConsoleLogger=void 0;var Ls=[{n:"error",c:"error"},{n:"warn",c:"warn"},{n:"info",c:"info"},{n:"debug",c:"debug"},{n:"verbose",c:"trace"}];class T20{constructor(){function Q(X){return function(...Y){if(console){let J=console[X];if(typeof J!=="function")J=console.log;if(typeof J==="function")return J.apply(console,Y)}}}for(let X=0;X<Ls.length;X++)this[Ls[X].n]=Q(Ls[X].c)}}A20.DiagConsoleLogger=T20});var Is=I((C20)=>{Object.defineProperty(C20,"__esModule",{value:!0});C20.createNoopMeter=C20.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC=C20.NOOP_OBSERVABLE_GAUGE_METRIC=C20.NOOP_OBSERVABLE_COUNTER_METRIC=C20.NOOP_UP_DOWN_COUNTER_METRIC=C20.NOOP_HISTOGRAM_METRIC=C20.NOOP_GAUGE_METRIC=C20.NOOP_COUNTER_METRIC=C20.NOOP_METER=C20.NoopObservableUpDownCounterMetric=C20.NoopObservableGaugeMetric=C20.NoopObservableCounterMetric=C20.NoopObservableMetric=C20.NoopHistogramMetric=C20.NoopGaugeMetric=C20.NoopUpDownCounterMetric=C20.NoopCounterMetric=C20.NoopMetric=C20.NoopMeter=void 0;class ws{constructor(){}createGauge(Q,X){return C20.NOOP_GAUGE_METRIC}createHistogram(Q,X){return C20.NOOP_HISTOGRAM_METRIC}createCounter(Q,X){return C20.NOOP_COUNTER_METRIC}createUpDownCounter(Q,X){return C20.NOOP_UP_DOWN_COUNTER_METRIC}createObservableGauge(Q,X){return C20.NOOP_OBSERVABLE_GAUGE_METRIC}createObservableCounter(Q,X){return C20.NOOP_OBSERVABLE_COUNTER_METRIC}createObservableUpDownCounter(Q,X){return C20.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC}addBatchObservableCallback(Q,X){}removeBatchObservableCallback(Q){}}C20.NoopMeter=ws;class nz{}C20.NoopMetric=nz;class Ms extends nz{add(Q,X){}}C20.NoopCounterMetric=Ms;class Ps extends nz{add(Q,X){}}C20.NoopUpDownCounterMetric=Ps;class Ts extends nz{record(Q,X){}}C20.NoopGaugeMetric=Ts;class As extends nz{record(Q,X){}}C20.NoopHistogramMetric=As;class gw{addCallback(Q){}removeCallback(Q){}}C20.NoopObservableMetric=gw;class Es extends gw{}C20.NoopObservableCounterMetric=Es;class js extends gw{}C20.NoopObservableGaugeMetric=js;class Cs extends gw{}C20.NoopObservableUpDownCounterMetric=Cs;C20.NOOP_METER=new ws;C20.NOOP_COUNTER_METRIC=new Ms;C20.NOOP_GAUGE_METRIC=new Ts;C20.NOOP_HISTOGRAM_METRIC=new As;C20.NOOP_UP_DOWN_COUNTER_METRIC=new Ps;C20.NOOP_OBSERVABLE_COUNTER_METRIC=new Es;C20.NOOP_OBSERVABLE_GAUGE_METRIC=new js;C20.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC=new Cs;function et6(){return C20.NOOP_METER}C20.createNoopMeter=et6});var x20=I((h20)=>{Object.defineProperty(h20,"__esModule",{value:!0});h20.ValueType=void 0;var Fe6;(function(Q){Q[Q.INT=0]="INT",Q[Q.DOUBLE=1]="DOUBLE"})(Fe6=h20.ValueType||(h20.ValueType={}))});var Ss=I((g20)=>{Object.defineProperty(g20,"__esModule",{value:!0});g20.defaultTextMapSetter=g20.defaultTextMapGetter=void 0;g20.defaultTextMapGetter={get(Q,X){if(Q==null)return;return Q[X]},keys(Q){if(Q==null)return[];return Object.keys(Q)}};g20.defaultTextMapSetter={set(Q,X,Y){if(Q==null)return;Q[X]=Y}}});var p20=I((l20)=>{Object.defineProperty(l20,"__esModule",{value:!0});l20.NoopContextManager=void 0;var qe6=xw();class m20{active(){return qe6.ROOT_CONTEXT}with(Q,X,Y,...J){return X.call(Y,...J)}bind(Q,X){return X}enable(){return this}disable(){return this}}l20.NoopContextManager=m20});var uw=I((n20)=>{Object.defineProperty(n20,"__esModule",{value:!0});n20.ContextAPI=void 0;var ze6=p20(),vs=S3(),c20=v3(),ks="context",Ue6=new ze6.NoopContextManager;class _s{constructor(){}static getInstance(){if(!this._instance)this._instance=new _s;return this._instance}setGlobalContextManager(Q){return(0,vs.registerGlobal)(ks,Q,c20.DiagAPI.instance())}active(){return this._getContextManager().active()}with(Q,X,Y,...J){return this._getContextManager().with(Q,X,Y,...J)}bind(Q,X){return this._getContextManager().bind(Q,X)}_getContextManager(){return(0,vs.getGlobal)(ks)||Ue6}disable(){this._getContextManager().disable(),(0,vs.unregisterGlobal)(ks,c20.DiagAPI.instance())}}n20.ContextAPI=_s});var bs=I((a20)=>{Object.defineProperty(a20,"__esModule",{value:!0});a20.TraceFlags=void 0;var Be6;(function(Q){Q[Q.NONE=0]="NONE",Q[Q.SAMPLED=1]="SAMPLED"})(Be6=a20.TraceFlags||(a20.TraceFlags={}))});var tv=I((r20)=>{Object.defineProperty(r20,"__esModule",{value:!0});r20.INVALID_SPAN_CONTEXT=r20.INVALID_TRACEID=r20.INVALID_SPANID=void 0;var De6=bs();r20.INVALID_SPANID="0000000000000000";r20.INVALID_TRACEID="00000000000000000000000000000000";r20.INVALID_SPAN_CONTEXT={traceId:r20.INVALID_TRACEID,spanId:r20.INVALID_SPANID,traceFlags:De6.TraceFlags.NONE}});var ev=I((QC0)=>{Object.defineProperty(QC0,"__esModule",{value:!0});QC0.NonRecordingSpan=void 0;var Ne6=tv();class e20{constructor(Q=Ne6.INVALID_SPAN_CONTEXT){this._spanContext=Q}spanContext(){return this._spanContext}setAttribute(Q,X){return this}setAttributes(Q){return this}addEvent(Q,X){return this}addLink(Q){return this}addLinks(Q){return this}setStatus(Q){return this}updateName(Q){return this}end(Q){}isRecording(){return!1}recordException(Q,X){}}QC0.NonRecordingSpan=e20});var xs=I((JC0)=>{Object.defineProperty(JC0,"__esModule",{value:!0});JC0.getSpanContext=JC0.setSpanContext=JC0.deleteSpan=JC0.setSpan=JC0.getActiveSpan=JC0.getSpan=void 0;var Oe6=xw(),Le6=ev(),we6=uw(),fs=(0,Oe6.createContextKey)("OpenTelemetry Context Key SPAN");function hs(Q){return Q.getValue(fs)||void 0}JC0.getSpan=hs;function Me6(){return hs(we6.ContextAPI.getInstance().active())}JC0.getActiveSpan=Me6;function YC0(Q,X){return Q.setValue(fs,X)}JC0.setSpan=YC0;function Pe6(Q){return Q.deleteValue(fs)}JC0.deleteSpan=Pe6;function Te6(Q,X){return YC0(Q,new Le6.NonRecordingSpan(X))}JC0.setSpanContext=Te6;function Ae6(Q){var X;return(X=hs(Q))===null||X===void 0?void 0:X.spanContext()}JC0.getSpanContext=Ae6});var Qk=I((KC0)=>{Object.defineProperty(KC0,"__esModule",{value:!0});KC0.wrapSpanContext=KC0.isSpanContextValid=KC0.isValidSpanId=KC0.isValidTraceId=void 0;var WC0=tv(),Se6=ev(),ve6=/^([0-9a-f]{32})$/i,ke6=/^[0-9a-f]{16}$/i;function ZC0(Q){return ve6.test(Q)&&Q!==WC0.INVALID_TRACEID}KC0.isValidTraceId=ZC0;function $C0(Q){return ke6.test(Q)&&Q!==WC0.INVALID_SPANID}KC0.isValidSpanId=$C0;function _e6(Q){return ZC0(Q.traceId)&&$C0(Q.spanId)}KC0.isSpanContextValid=_e6;function ye6(Q){return new Se6.NonRecordingSpan(Q)}KC0.wrapSpanContext=ye6});var ms=I((qC0)=>{Object.defineProperty(qC0,"__esModule",{value:!0});qC0.NoopTracer=void 0;var xe6=uw(),FC0=xs(),gs=ev(),ge6=Qk(),us=xe6.ContextAPI.getInstance();class VC0{startSpan(Q,X,Y=us.active()){if(Boolean(X===null||X===void 0?void 0:X.root))return new gs.NonRecordingSpan;let G=Y&&(0,FC0.getSpanContext)(Y);if(ue6(G)&&(0,ge6.isSpanContextValid)(G))return new gs.NonRecordingSpan(G);else return new gs.NonRecordingSpan}startActiveSpan(Q,X,Y,J){let G,W,Z;if(arguments.length<2)return;else if(arguments.length===2)Z=X;else if(arguments.length===3)G=X,Z=Y;else G=X,W=Y,Z=J;let $=W!==null&&W!==void 0?W:us.active(),K=this.startSpan(Q,G,$),H=(0,FC0.setSpan)($,K);return us.with(H,Z,void 0,K)}}qC0.NoopTracer=VC0;function ue6(Q){return typeof Q==="object"&&typeof Q.spanId==="string"&&typeof Q.traceId==="string"&&typeof Q.traceFlags==="number"}});var ls=I((BC0)=>{Object.defineProperty(BC0,"__esModule",{value:!0});BC0.ProxyTracer=void 0;var me6=ms(),le6=new me6.NoopTracer;class UC0{constructor(Q,X,Y,J){this._provider=Q,this.name=X,this.version=Y,this.options=J}startSpan(Q,X,Y){return this._getTracer().startSpan(Q,X,Y)}startActiveSpan(Q,X,Y,J){let G=this._getTracer();return Reflect.apply(G.startActiveSpan,G,arguments)}_getTracer(){if(this._delegate)return this._delegate;let Q=this._provider.getDelegateTracer(this.name,this.version,this.options);if(!Q)return le6;return this._delegate=Q,this._delegate}}BC0.ProxyTracer=UC0});var wC0=I((OC0)=>{Object.defineProperty(OC0,"__esModule",{value:!0});OC0.NoopTracerProvider=void 0;var de6=ms();class NC0{getTracer(Q,X,Y){return new de6.NoopTracer}}OC0.NoopTracerProvider=NC0});var ds=I((PC0)=>{Object.defineProperty(PC0,"__esModule",{value:!0});PC0.ProxyTracerProvider=void 0;var pe6=ls(),ce6=wC0(),ne6=new ce6.NoopTracerProvider;class MC0{getTracer(Q,X,Y){var J;return(J=this.getDelegateTracer(Q,X,Y))!==null&&J!==void 0?J:new pe6.ProxyTracer(this,Q,X,Y)}getDelegate(){var Q;return(Q=this._delegate)!==null&&Q!==void 0?Q:ne6}setDelegate(Q){this._delegate=Q}getDelegateTracer(Q,X,Y){var J;return(J=this._delegate)===null||J===void 0?void 0:J.getTracer(Q,X,Y)}}PC0.ProxyTracerProvider=MC0});var EC0=I((AC0)=>{Object.defineProperty(AC0,"__esModule",{value:!0});AC0.SamplingDecision=void 0;var ie6;(function(Q){Q[Q.NOT_RECORD=0]="NOT_RECORD",Q[Q.RECORD=1]="RECORD",Q[Q.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED"})(ie6=AC0.SamplingDecision||(AC0.SamplingDecision={}))});var CC0=I((jC0)=>{Object.defineProperty(jC0,"__esModule",{value:!0});jC0.SpanKind=void 0;var ae6;(function(Q){Q[Q.INTERNAL=0]="INTERNAL",Q[Q.SERVER=1]="SERVER",Q[Q.CLIENT=2]="CLIENT",Q[Q.PRODUCER=3]="PRODUCER",Q[Q.CONSUMER=4]="CONSUMER"})(ae6=jC0.SpanKind||(jC0.SpanKind={}))});var RC0=I((IC0)=>{Object.defineProperty(IC0,"__esModule",{value:!0});IC0.SpanStatusCode=void 0;var re6;(function(Q){Q[Q.UNSET=0]="UNSET",Q[Q.OK=1]="OK",Q[Q.ERROR=2]="ERROR"})(re6=IC0.SpanStatusCode||(IC0.SpanStatusCode={}))});var kC0=I((SC0)=>{Object.defineProperty(SC0,"__esModule",{value:!0});SC0.validateValue=SC0.validateKey=void 0;var is="[_0-9a-z-*/]",oe6=`[a-z]${is}{0,255}`,se6=`[a-z0-9]${is}{0,240}@[a-z]${is}{0,13}`,te6=new RegExp(`^(?:${oe6}|${se6})$`),ee6=/^[ -~]{0,255}[!-~]$/,Q01=/,|=/;function X01(Q){return te6.test(Q)}SC0.validateKey=X01;function Y01(Q){return ee6.test(Q)&&!Q01.test(Q)}SC0.validateValue=Y01});var gC0=I((hC0)=>{Object.defineProperty(hC0,"__esModule",{value:!0});hC0.TraceStateImpl=void 0;var _C0=kC0(),yC0=32,G01=512,bC0=",",fC0="=";class as{constructor(Q){if(this._internalState=new Map,Q)this._parse(Q)}set(Q,X){let Y=this._clone();if(Y._internalState.has(Q))Y._internalState.delete(Q);return Y._internalState.set(Q,X),Y}unset(Q){let X=this._clone();return X._internalState.delete(Q),X}get(Q){return this._internalState.get(Q)}serialize(){return this._keys().reduce((Q,X)=>{return Q.push(X+fC0+this.get(X)),Q},[]).join(bC0)}_parse(Q){if(Q.length>G01)return;if(this._internalState=Q.split(bC0).reverse().reduce((X,Y)=>{let J=Y.trim(),G=J.indexOf(fC0);if(G!==-1){let W=J.slice(0,G),Z=J.slice(G+1,Y.length);if((0,_C0.validateKey)(W)&&(0,_C0.validateValue)(Z))X.set(W,Z)}return X},new Map),this._internalState.size>yC0)this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,yC0))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let Q=new as;return Q._internalState=new Map(this._internalState),Q}}hC0.TraceStateImpl=as});var lC0=I((uC0)=>{Object.defineProperty(uC0,"__esModule",{value:!0});uC0.createTraceState=void 0;var W01=gC0();function Z01(Q){return new W01.TraceStateImpl(Q)}uC0.createTraceState=Z01});var cC0=I((dC0)=>{Object.defineProperty(dC0,"__esModule",{value:!0});dC0.context=void 0;var $01=uw();dC0.context=$01.ContextAPI.getInstance()});var aC0=I((nC0)=>{Object.defineProperty(nC0,"__esModule",{value:!0});nC0.diag=void 0;var K01=v3();nC0.diag=K01.DiagAPI.instance()});var sC0=I((rC0)=>{Object.defineProperty(rC0,"__esModule",{value:!0});rC0.NOOP_METER_PROVIDER=rC0.NoopMeterProvider=void 0;var H01=Is();class rs{getMeter(Q,X,Y){return H01.NOOP_METER}}rC0.NoopMeterProvider=rs;rC0.NOOP_METER_PROVIDER=new rs});var XI0=I((eC0)=>{Object.defineProperty(eC0,"__esModule",{value:!0});eC0.MetricsAPI=void 0;var V01=sC0(),os=S3(),tC0=v3(),ss="metrics";class ts{constructor(){}static getInstance(){if(!this._instance)this._instance=new ts;return this._instance}setGlobalMeterProvider(Q){return(0,os.registerGlobal)(ss,Q,tC0.DiagAPI.instance())}getMeterProvider(){return(0,os.getGlobal)(ss)||V01.NOOP_METER_PROVIDER}getMeter(Q,X,Y){return this.getMeterProvider().getMeter(Q,X,Y)}disable(){(0,os.unregisterGlobal)(ss,tC0.DiagAPI.instance())}}eC0.MetricsAPI=ts});var GI0=I((YI0)=>{Object.defineProperty(YI0,"__esModule",{value:!0});YI0.metrics=void 0;var q01=XI0();YI0.metrics=q01.MetricsAPI.getInstance()});var KI0=I((ZI0)=>{Object.defineProperty(ZI0,"__esModule",{value:!0});ZI0.NoopTextMapPropagator=void 0;class WI0{inject(Q,X){}extract(Q,X){return Q}fields(){return[]}}ZI0.NoopTextMapPropagator=WI0});var qI0=I((FI0)=>{Object.defineProperty(FI0,"__esModule",{value:!0});FI0.deleteBaggage=FI0.setBaggage=FI0.getActiveBaggage=FI0.getBaggage=void 0;var z01=uw(),U01=xw(),es=(0,U01.createContextKey)("OpenTelemetry Baggage Key");function HI0(Q){return Q.getValue(es)||void 0}FI0.getBaggage=HI0;function B01(){return HI0(z01.ContextAPI.getInstance().active())}FI0.getActiveBaggage=B01;function D01(Q,X){return Q.setValue(es,X)}FI0.setBaggage=D01;function N01(Q){return Q.deleteValue(es)}FI0.deleteBaggage=N01});var NI0=I((BI0)=>{Object.defineProperty(BI0,"__esModule",{value:!0});BI0.PropagationAPI=void 0;var Qt=S3(),M01=KI0(),zI0=Ss(),Xk=qI0(),P01=Os(),UI0=v3(),Xt="propagation",T01=new M01.NoopTextMapPropagator;class Yt{constructor(){this.createBaggage=P01.createBaggage,this.getBaggage=Xk.getBaggage,this.getActiveBaggage=Xk.getActiveBaggage,this.setBaggage=Xk.setBaggage,this.deleteBaggage=Xk.deleteBaggage}static getInstance(){if(!this._instance)this._instance=new Yt;return this._instance}setGlobalPropagator(Q){return(0,Qt.registerGlobal)(Xt,Q,UI0.DiagAPI.instance())}inject(Q,X,Y=zI0.defaultTextMapSetter){return this._getGlobalPropagator().inject(Q,X,Y)}extract(Q,X,Y=zI0.defaultTextMapGetter){return this._getGlobalPropagator().extract(Q,X,Y)}fields(){return this._getGlobalPropagator().fields()}disable(){(0,Qt.unregisterGlobal)(Xt,UI0.DiagAPI.instance())}_getGlobalPropagator(){return(0,Qt.getGlobal)(Xt)||T01}}BI0.PropagationAPI=Yt});var wI0=I((OI0)=>{Object.defineProperty(OI0,"__esModule",{value:!0});OI0.propagation=void 0;var A01=NI0();OI0.propagation=A01.PropagationAPI.getInstance()});var jI0=I((AI0)=>{Object.defineProperty(AI0,"__esModule",{value:!0});AI0.TraceAPI=void 0;var Jt=S3(),MI0=ds(),PI0=Qk(),iz=xs(),TI0=v3(),Gt="trace";class Wt{constructor(){this._proxyTracerProvider=new MI0.ProxyTracerProvider,this.wrapSpanContext=PI0.wrapSpanContext,this.isSpanContextValid=PI0.isSpanContextValid,this.deleteSpan=iz.deleteSpan,this.getSpan=iz.getSpan,this.getActiveSpan=iz.getActiveSpan,this.getSpanContext=iz.getSpanContext,this.setSpan=iz.setSpan,this.setSpanContext=iz.setSpanContext}static getInstance(){if(!this._instance)this._instance=new Wt;return this._instance}setGlobalTracerProvider(Q){let X=(0,Jt.registerGlobal)(Gt,this._proxyTracerProvider,TI0.DiagAPI.instance());if(X)this._proxyTracerProvider.setDelegate(Q);return X}getTracerProvider(){return(0,Jt.getGlobal)(Gt)||this._proxyTracerProvider}getTracer(Q,X){return this.getTracerProvider().getTracer(Q,X)}disable(){(0,Jt.unregisterGlobal)(Gt,TI0.DiagAPI.instance()),this._proxyTracerProvider=new MI0.ProxyTracerProvider}}AI0.TraceAPI=Wt});var RI0=I((CI0)=>{Object.defineProperty(CI0,"__esModule",{value:!0});CI0.trace=void 0;var E01=jI0();CI0.trace=E01.TraceAPI.getInstance()});var $6=I((f4)=>{Object.defineProperty(f4,"__esModule",{value:!0});f4.trace=f4.propagation=f4.metrics=f4.diag=f4.context=f4.INVALID_SPAN_CONTEXT=f4.INVALID_TRACEID=f4.INVALID_SPANID=f4.isValidSpanId=f4.isValidTraceId=f4.isSpanContextValid=f4.createTraceState=f4.TraceFlags=f4.SpanStatusCode=f4.SpanKind=f4.SamplingDecision=f4.ProxyTracerProvider=f4.ProxyTracer=f4.defaultTextMapSetter=f4.defaultTextMapGetter=f4.ValueType=f4.createNoopMeter=f4.DiagLogLevel=f4.DiagConsoleLogger=f4.ROOT_CONTEXT=f4.createContextKey=f4.baggageEntryMetadataFromString=void 0;var j01=Os();Object.defineProperty(f4,"baggageEntryMetadataFromString",{enumerable:!0,get:function(){return j01.baggageEntryMetadataFromString}});var SI0=xw();Object.defineProperty(f4,"createContextKey",{enumerable:!0,get:function(){return SI0.createContextKey}});Object.defineProperty(f4,"ROOT_CONTEXT",{enumerable:!0,get:function(){return SI0.ROOT_CONTEXT}});var C01=j20();Object.defineProperty(f4,"DiagConsoleLogger",{enumerable:!0,get:function(){return C01.DiagConsoleLogger}});var I01=rv();Object.defineProperty(f4,"DiagLogLevel",{enumerable:!0,get:function(){return I01.DiagLogLevel}});var R01=Is();Object.defineProperty(f4,"createNoopMeter",{enumerable:!0,get:function(){return R01.createNoopMeter}});var S01=x20();Object.defineProperty(f4,"ValueType",{enumerable:!0,get:function(){return S01.ValueType}});var vI0=Ss();Object.defineProperty(f4,"defaultTextMapGetter",{enumerable:!0,get:function(){return vI0.defaultTextMapGetter}});Object.defineProperty(f4,"defaultTextMapSetter",{enumerable:!0,get:function(){return vI0.defaultTextMapSetter}});var v01=ls();Object.defineProperty(f4,"ProxyTracer",{enumerable:!0,get:function(){return v01.ProxyTracer}});var k01=ds();Object.defineProperty(f4,"ProxyTracerProvider",{enumerable:!0,get:function(){return k01.ProxyTracerProvider}});var _01=EC0();Object.defineProperty(f4,"SamplingDecision",{enumerable:!0,get:function(){return _01.SamplingDecision}});var y01=CC0();Object.defineProperty(f4,"SpanKind",{enumerable:!0,get:function(){return y01.SpanKind}});var b01=RC0();Object.defineProperty(f4,"SpanStatusCode",{enumerable:!0,get:function(){return b01.SpanStatusCode}});var f01=bs();Object.defineProperty(f4,"TraceFlags",{enumerable:!0,get:function(){return f01.TraceFlags}});var h01=lC0();Object.defineProperty(f4,"createTraceState",{enumerable:!0,get:function(){return h01.createTraceState}});var Zt=Qk();Object.defineProperty(f4,"isSpanContextValid",{enumerable:!0,get:function(){return Zt.isSpanContextValid}});Object.defineProperty(f4,"isValidTraceId",{enumerable:!0,get:function(){return Zt.isValidTraceId}});Object.defineProperty(f4,"isValidSpanId",{enumerable:!0,get:function(){return Zt.isValidSpanId}});var $t=tv();Object.defineProperty(f4,"INVALID_SPANID",{enumerable:!0,get:function(){return $t.INVALID_SPANID}});Object.defineProperty(f4,"INVALID_TRACEID",{enumerable:!0,get:function(){return $t.INVALID_TRACEID}});Object.defineProperty(f4,"INVALID_SPAN_CONTEXT",{enumerable:!0,get:function(){return $t.INVALID_SPAN_CONTEXT}});var kI0=cC0();Object.defineProperty(f4,"context",{enumerable:!0,get:function(){return kI0.context}});var _I0=aC0();Object.defineProperty(f4,"diag",{enumerable:!0,get:function(){return _I0.diag}});var yI0=GI0();Object.defineProperty(f4,"metrics",{enumerable:!0,get:function(){return yI0.metrics}});var bI0=wI0();Object.defineProperty(f4,"propagation",{enumerable:!0,get:function(){return bI0.propagation}});var fI0=RI0();Object.defineProperty(f4,"trace",{enumerable:!0,get:function(){return fI0.trace}});f4.default={context:kI0.context,diag:_I0.diag,metrics:yI0.metrics,propagation:bI0.propagation,trace:fI0.trace}});function D6(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:Kt.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:Kt.SpanStatusCode.ERROR,message:W.message}),G.recordException(W),W}finally{G.end()}})}}}var Kt;var j1=y(()=>{Kt=k1($6(),1)});function L1(Q){if(!Q.organization)throw Error("This operation requires organization scope");return Q.organization}function iQ(Q){return Q.auth.user?.id??Q.auth.apiKey?.userId}function u01(Q){return!!(Q.auth.user||Q.auth.apiKey)}function I6(Q){if(!u01(Q))throw Error("Authentication required")}var Yk,hI0,xI0,gI0,uI0,mI0,lI0,dI0,pI0,cI0;var az=y(()=>{W6();Yk=N.record(N.string(),N.array(N.string())),hI0=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:Yk.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")}),xI0=N.object({name:N.string().min(1).max(64).describe("Human-readable name for the API key"),permissions:Yk.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")}),gI0=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:Yk.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")}),uI0=N.object({}),mI0=N.object({items:N.array(hI0).describe("List of API keys (without key values)")}),lI0=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:Yk.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.")}),dI0=N.object({item:hI0.describe("The updated API key (without key value)")}),pI0=N.object({keyId:N.string().describe("ID of the API key to delete")}),cI0=N.object({success:N.boolean().describe("Whether the deletion was successful"),keyId:N.string().describe("ID of the deleted API key")})});var Ht;var nI0=y(()=>{j1();az();Ht=D6({name:"API_KEY_CREATE",description:"Create a new API key with specified permissions. The key value is only returned once - store it securely!",inputSchema:xI0,outputSchema:gI0,handler:async(Q,X)=>{I6(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 Ft;var iI0=y(()=>{j1();az();Ft=D6({name:"API_KEY_DELETE",description:"Delete an API key. This instantly revokes the key - it can no longer be used for authentication.",inputSchema:pI0,outputSchema:cI0,handler:async(Q,X)=>{if(I6(X),await X.access.check(),!iQ(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 Vt;var aI0=y(()=>{j1();az();Vt=D6({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:uI0,outputSchema:mI0,handler:async(Q,X)=>{I6(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 qt;var rI0=y(()=>{j1();az();qt=D6({name:"API_KEY_UPDATE",description:"Update an existing API key's name, permissions, or metadata. Note: Key value cannot be changed or retrieved.",inputSchema:lI0,outputSchema:dI0,handler:async(Q,X)=>{if(I6(X),await X.access.check(),!iQ(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 oI0=y(()=>{nI0();iI0();aI0();rI0();az()});var l01,d01,zt;var sI0=y(()=>{V3();W6();j1();nv();T7();l01=N.object({data:ML0.describe("Data for the new connection (id is auto-generated if not provided)")}),d01=N.object({item:fJ.describe("The created connection entity")}),zt=D6({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",inputSchema:l01,outputSchema:d01,handler:async(Q,X)=>{I6(X);let Y=L1(X);await X.access.check();let J=iQ(X);if(!J)throw Error("User ID required to create connection");let G={...Q.data,organization_id:Y.id,created_by:J},W=await dz({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,Hz.SELF(Y.id),{type:"connection.created",data:$}),{item:$}}})});function mw(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)=>mw(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)&&mw(Q[G],X[G]))}return!1}function q61(){return(Q)=>{if(!Array.isArray(Q))return!0;let X=[];return Q.every((Y)=>{if(X.some((G)=>mw(Y,G)))return!1;return X.push(Y),!0})}}function Jk(Q,X){return Q.safeParse(X).success}function A9(Q){if(typeof Q==="boolean")return Q?N.any():N.never();let X={};for(let G of j61)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 C61)J=G.apply(J,Q);return J}var p01=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()}}},c01=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}},n01=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}},i01=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}}},a01=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()}}},r01=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`})}}},o01=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`})}}},s01=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)}}}},t01=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)}}},e01=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)}}},Q61=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}}},X61=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}}},Y61=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}`})}}},J61=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())}}},G61=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)}},W61=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)}},Z61=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=A9(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())}},$61=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)=>A9(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}},K61=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()}},H61=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()}}},F61=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`})}}},V61=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`})}}},z61=class{apply(Q,X){if(!X.not)return Q;let Y=A9(X.not);return Q.refine((J)=>!Jk(Y,J),{message:"Value must not match the 'not' schema"})}},U61=class{apply(Q,X){if(X.uniqueItems!==!0)return Q;return Q.refine(q61(),{message:"Array items must be unique"})}},B61=class{apply(Q,X){if(!X.allOf||X.allOf.length===0)return Q;return X.allOf.map((J)=>A9(J)).reduce((J,G)=>N.intersection(J,G),Q)}},D61=class{apply(Q,X){if(!X.anyOf||X.anyOf.length===0)return Q;let Y=X.anyOf.length===1?A9(X.anyOf[0]):N.union([A9(X.anyOf[0]),A9(X.anyOf[1]),...X.anyOf.slice(2).map((J)=>A9(J))]);return N.intersection(Q,Y)}},N61=class{apply(Q,X){if(!X.oneOf||X.oneOf.length===0)return Q;let Y=X.oneOf.map((J)=>A9(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"})}},O61=class{apply(Q,X){let Y=X;if(Y.prefixItems&&Array.isArray(Y.prefixItems)){let G=Y.prefixItems.map((W)=>A9(W));return Q.refine((W)=>{if(!Array.isArray(W))return!0;for(let Z=0;Z<Math.min(W.length,G.length);Z++)if(!Jk(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=A9(Y.items);for(let $=G.length;$<W.length;$++)if(!Jk(Z,W[$]))return!1}}return!0},{message:"Array does not match prefixItems schema"})}return Q}},L61=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]=A9(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(!A9(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"})}},w61=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)=>mw(J,G))},{message:"Value must match one of the enum values"})}},M61=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)=>mw(J,Y),{message:"Value must equal the const value"})}},P61=class{apply(Q,X){if(X.description)Q=Q.describe(X.description);return Q}},T61=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))}},A61=class{apply(Q,X){var Y;let J=X;if(J.contains===void 0)return Q;let G=A9(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(Jk(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"})}},E61=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)}},j61,C61;var tI0=y(()=>{a1();a1();a1();a1();a1();a1();a1();a1();a1();a1();a1();a1();a1();a1();j61=[new c01,new n01,new p01,new i01,new a01,new J61,new H61,new r01,new o01,new s01,new t01,new e01,new Q61,new X61,new Y61,new $61,new G61,new W61,new Z61,new F61,new V61,new K61],C61=[new T61,new w61,new M61,new B61,new D61,new N61,new O61,new L61,new A61,new z61,new U61,new E61,new P61]});function I61(Q){let X=globalThis.DOMException;return typeof X=="function"?new X(Q,"SyntaxError"):SyntaxError(Q)}function Bt(Q){return Q instanceof Error?"errors"in Q&&Array.isArray(Q.errors)?Q.errors.map(Bt).join(", "):("cause"in Q)&&Q.cause instanceof Error?`${Q}: ${Bt(Q.cause)}`:Q.message:`${Q}`}function eI0(Q){return{type:Q.type,message:Q.message,code:Q.code,defaultPrevented:Q.defaultPrevented,cancelable:Q.cancelable,timeStamp:Q.timeStamp}}function R61(){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 Ut,XR0=(Q)=>{throw TypeError(Q)},Tt=(Q,X,Y)=>X.has(Q)||XR0("Cannot "+Y),S1=(Q,X,Y)=>(Tt(Q,X,"read from private field"),Y?Y.call(Q):X.get(Q)),PQ=(Q,X,Y)=>X.has(Q)?XR0("Cannot add the same private member more than once"):X instanceof WeakSet?X.add(Q):X.set(Q,Y),j8=(Q,X,Y,J)=>(Tt(Q,X,"write to private field"),X.set(Q,Y),Y),g7=(Q,X,Y)=>(Tt(Q,X,"access private method"),Y),VY,k3,rz,Gk,Wk,pw,tz,cw,r$,oz,ez,sz,lw,y5,Dt,Nt,Ot,QR0,Lt,wt,dw,Mt,Pt,QU;var YR0=y(()=>{$s();Ut=class Ut 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(eI0(this),X)}[Symbol.for("Deno.customInspect")](Q,X){return Q(eI0(this),X)}};QU=class QU extends EventTarget{constructor(Q,X){var Y,J;super(),PQ(this,y5),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,PQ(this,VY),PQ(this,k3),PQ(this,rz),PQ(this,Gk),PQ(this,Wk),PQ(this,pw),PQ(this,tz),PQ(this,cw,null),PQ(this,r$),PQ(this,oz),PQ(this,ez,null),PQ(this,sz,null),PQ(this,lw,null),PQ(this,Nt,async(G)=>{var W;S1(this,oz).reset();let{body:Z,redirected:$,status:K,headers:H}=G;if(K===204){g7(this,y5,dw).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if($?j8(this,rz,new URL(G.url)):j8(this,rz,void 0),K!==200){g7(this,y5,dw).call(this,`Non-200 status code (${K})`,K);return}if(!(H.get("content-type")||"").startsWith("text/event-stream")){g7(this,y5,dw).call(this,'Invalid content type, expected "text/event-stream"',K);return}if(S1(this,VY)===this.CLOSED)return;j8(this,VY,this.OPEN);let F=new Event("open");if((W=S1(this,lw))==null||W.call(this,F),this.dispatchEvent(F),typeof Z!="object"||!Z||!("getReader"in Z)){g7(this,y5,dw).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&&S1(this,oz).feed(V.decode(D,{stream:!B})),B&&(z=!1,S1(this,oz).reset(),g7(this,y5,Mt).call(this))}while(z)}),PQ(this,Ot,(G)=>{j8(this,r$,void 0),!(G.name==="AbortError"||G.type==="aborted")&&g7(this,y5,Mt).call(this,Bt(G))}),PQ(this,Lt,(G)=>{typeof G.id=="string"&&j8(this,cw,G.id);let W=new MessageEvent(G.event||"message",{data:G.data,origin:S1(this,rz)?S1(this,rz).origin:S1(this,k3).origin,lastEventId:G.id||""});S1(this,sz)&&(!G.event||G.event==="message")&&S1(this,sz).call(this,W),this.dispatchEvent(W)}),PQ(this,wt,(G)=>{j8(this,pw,G)}),PQ(this,Pt,()=>{j8(this,tz,void 0),S1(this,VY)===this.CONNECTING&&g7(this,y5,Dt).call(this)});try{if(Q instanceof URL)j8(this,k3,Q);else if(typeof Q=="string")j8(this,k3,new URL(Q,R61()));else throw Error("Invalid URL")}catch{throw I61("An invalid or illegal string was specified")}j8(this,oz,cv({onEvent:S1(this,Lt),onRetry:S1(this,wt)})),j8(this,VY,this.CONNECTING),j8(this,pw,3000),j8(this,Wk,(Y=X==null?void 0:X.fetch)!=null?Y:globalThis.fetch),j8(this,Gk,(J=X==null?void 0:X.withCredentials)!=null?J:!1),g7(this,y5,Dt).call(this)}get readyState(){return S1(this,VY)}get url(){return S1(this,k3).href}get withCredentials(){return S1(this,Gk)}get onerror(){return S1(this,ez)}set onerror(Q){j8(this,ez,Q)}get onmessage(){return S1(this,sz)}set onmessage(Q){j8(this,sz,Q)}get onopen(){return S1(this,lw)}set onopen(Q){j8(this,lw,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(){S1(this,tz)&&clearTimeout(S1(this,tz)),S1(this,VY)!==this.CLOSED&&(S1(this,r$)&&S1(this,r$).abort(),j8(this,VY,this.CLOSED),j8(this,r$,void 0))}};VY=new WeakMap,k3=new WeakMap,rz=new WeakMap,Gk=new WeakMap,Wk=new WeakMap,pw=new WeakMap,tz=new WeakMap,cw=new WeakMap,r$=new WeakMap,oz=new WeakMap,ez=new WeakMap,sz=new WeakMap,lw=new WeakMap,y5=new WeakSet,Dt=function(){j8(this,VY,this.CONNECTING),j8(this,r$,new AbortController),S1(this,Wk)(S1(this,k3),g7(this,y5,QR0).call(this)).then(S1(this,Nt)).catch(S1(this,Ot))},Nt=new WeakMap,Ot=new WeakMap,QR0=function(){var Q;let X={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...S1(this,cw)?{"Last-Event-ID":S1(this,cw)}:void 0},cache:"no-store",signal:(Q=S1(this,r$))==null?void 0:Q.signal};return"window"in globalThis&&(X.credentials=this.withCredentials?"include":"same-origin"),X},Lt=new WeakMap,wt=new WeakMap,dw=function(Q,X){var Y;S1(this,VY)!==this.CLOSED&&j8(this,VY,this.CLOSED);let J=new Ut("error",{code:X,message:Q});(Y=S1(this,ez))==null||Y.call(this,J),this.dispatchEvent(J)},Mt=function(Q,X){var Y;if(S1(this,VY)===this.CLOSED)return;j8(this,VY,this.CONNECTING);let J=new Ut("error",{code:X,message:Q});(Y=S1(this,ez))==null||Y.call(this,J),this.dispatchEvent(J),j8(this,tz,setTimeout(S1(this,Pt),S1(this,pw)))},Pt=new WeakMap,QU.CONNECTING=0,QU.OPEN=1,QU.CLOSED=2});class At{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=kv(X?.fetch,X?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new FY("No auth provider");let Q;try{Q=await f7(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 FY;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=hz(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 QU(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}=lz(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 JR0(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=iY.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 FY("No auth provider");if(await f7(this._authProvider,{serverUrl:this._url,authorizationCode:Q,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new FY("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}=lz(J);if(this._resourceMetadataUrl=W,this._scope=Z,await f7(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new FY;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 JR0;var GR0=y(()=>{YR0();s9();Gs();JR0=class JR0 extends Error{constructor(Q,X,Y){super(`SSE error: ${X}`);this.code=Q,this.event=Y}}});class Et{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,S61),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=iY.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 S61="mcp";var WR0=y(()=>{s9()});function v61(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 jt;var ZR0=y(()=>{kw();jt=class jt extends h7{constructor(Q,X){super(Q,X)}send(Q,X){let Y=v61(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 $R0,KR0=async(Q,X,Y)=>{let J=k61(Q.connection,X,Y);if(!J)throw Error("Unknown MCP connection type");let G=new $R0({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:$})}}},k61=(Q,X,Y)=>{if(Q.type==="Websocket")return new Et(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 At(new URL(Q.url),W)}return new jt(new URL(Q.url),{requestInit:{headers:G,signal:X,credentials:"include"}})};var HR0=y(()=>{yz();GR0();WR0();s9();ZR0();$R0=class $R0 extends dJ{constructor(Q,X){super(Q,X)}async listTools(Q,X){return await this.request({method:"tools/list",params:Q},Xw,X)}}});function VR0(Q){let X=(Y)=>{if("connection"in Q)return KR0({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"?_61(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(!Zk.has(H))Zk.set(H,W());return await Zk.get(H)}catch(F){console.error("Failed to list tools",F),Zk.delete(H);return}}async function $(){return(await Z()??[]).map((H)=>FR0(H,G))}return G.asTool=async()=>{let H=(await Z()??[]).find((F)=>F.name===J);if(!H)throw Error(`Tool ${J} not found`);return FR0(H,G)},G}})}var _61=(Q)=>{try{return JSON.parse(Q)}catch{return Q}},Zk,FR0=(Q,X)=>{return{...Q,id:Q.name,inputSchema:Q.inputSchema?A9(Q.inputSchema):void 0,outputSchema:Q.outputSchema?A9(Q.outputSchema):void 0,execute:(Y)=>{return X(Y.context,Q.name)}}};var qR0=y(()=>{tI0();HR0();Zk=new Map});function $k(Q){return VR0(Q)}var qj4;var zR0=y(()=>{qR0();qj4=new Proxy({},{get(Q,X){if(X==="toJSON")return null;if(X==="forConnection")return(Y)=>$k({connection:Y});return global[X]}})});function Kk(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 XU=(Q)=>{return{...Kk(Q),forClient:(X)=>{return $k({client:X,streamable:Q.reduce((Y,J)=>{return Y[J.name]=J.streamable===!0,Y},{})})},forConnection:(X)=>{return $k({connection:X,streamable:Q.reduce((Y,J)=>{return Y[J.name]=J.streamable===!0,Y},{})})}}};var nw=y(()=>{zR0()});function aw(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 It(Q){return N.object({item:Q.nullable().describe("The retrieved item, or null if not found")})}function f61(Q){return N.object({data:Q.partial().describe("Data for the new entity (id may be auto-generated)")})}function h61(Q){return N.object({item:Q.describe("The created entity with generated id")})}function x61(Q){return N.object({id:N.string().describe("ID of the entity to update"),data:Q.partial().describe("Partial entity data to update")})}function g61(Q){return N.object({item:Q.describe("The updated entity")})}function St(Q){return N.object({item:Q.describe("The deleted entity")})}function JU(Q,X,Y){let J=Q.toUpperCase(),G=Y?.readOnly??!1,W=[{name:`COLLECTION_${J}_LIST`,inputSchema:iw,outputSchema:aw(X)},{name:`COLLECTION_${J}_GET`,inputSchema:Ct,outputSchema:It(X)}];if(!G)W.push({name:`COLLECTION_${J}_CREATE`,inputSchema:f61(X),outputSchema:h61(X),opt:!0},{name:`COLLECTION_${J}_UPDATE`,inputSchema:x61(X),outputSchema:g61(X),opt:!0},{name:`COLLECTION_${J}_DELETE`,inputSchema:Rt,outputSchema:St(X),opt:!0});return W}var YU,y61,UR0,b61,iw,Ct,Rt;var o$=y(()=>{W6();YU=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()}),y61=N.object({field:N.array(N.string()),operator:N.enum(["eq","gt","gte","lt","lte","in","like","contains"]),value:N.unknown()}),UR0=N.lazy(()=>N.union([y61,N.object({operator:N.enum(["and","or","not"]),conditions:N.array(UR0)})])),b61=N.object({field:N.array(N.string()),direction:N.enum(["asc","desc"]),nulls:N.enum(["first","last"]).optional()}),iw=N.object({where:UR0.optional().describe("Filter expression"),orderBy:N.array(b61).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")});Ct=N.object({id:N.string().describe("ID of the entity to retrieve")});Rt=N.object({id:N.string().describe("ID of the entity to delete")})});var u61,BR0,Mj4;var DR0=y(()=>{W6();o$();u61=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()}),BR0=YU.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(u61).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()})}),Mj4=JU("registry_app",BR0,{readOnly:!0})});var NR0,OR0,LR0,wR0,MR0,vt;var PR0=y(()=>{W6();nw();NR0=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)")}),OR0=N.object({events:N.array(NR0).min(1).describe("Batch of CloudEvents to process")}),LR0=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")}),wR0=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(),LR0).optional().describe("Per-event results keyed by event ID")}),MR0=[{name:"ON_EVENTS",inputSchema:OR0,outputSchema:wR0}],vt=XU(MR0)});var rw,ow,sw,tw,TR0,AR0,ew,QM,XM,YM,JM,GM,WM,ZM,ER0,m61;var jR0=y(()=>{W6();nw();rw=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.")}),ow=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")}),sw=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")}),tw=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")})}),TR0=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")}),AR0=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")}),ew=N.object({subscriptions:N.array(TR0).describe("Desired subscriptions - system will create/update/delete to match")}),QM=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(AR0).describe("Current subscriptions after sync")}),XM=N.object({subscriptionId:N.string().describe("Subscription ID to remove")}),YM=N.object({success:N.boolean().describe("Whether unsubscribe was successful"),subscriptionId:N.string().describe("Subscription ID that was removed")}),JM=N.object({eventId:N.string().describe("Event ID to cancel")}),GM=N.object({success:N.boolean().describe("Whether cancellation was successful"),eventId:N.string().describe("Event ID that was cancelled")}),WM=N.object({eventId:N.string().describe("Event ID to acknowledge")}),ZM=N.object({success:N.boolean().describe("Whether ACK was successful"),eventId:N.string().describe("Event ID that was acknowledged")}),ER0=[{name:"EVENT_PUBLISH",inputSchema:rw,outputSchema:ow},{name:"EVENT_SUBSCRIBE",inputSchema:sw,outputSchema:tw},{name:"EVENT_UNSUBSCRIBE",inputSchema:XM,outputSchema:YM},{name:"EVENT_CANCEL",inputSchema:JM,outputSchema:GM},{name:"EVENT_ACK",inputSchema:WM,outputSchema:ZM},{name:"EVENT_SYNC_SUBSCRIPTIONS",inputSchema:ew,outputSchema:QM}],m61=XU(ER0)});var Hk=y(()=>{nw();DR0();PR0();jR0()});var l61,d61,CR0;var IR0=y(()=>{W6();o$();l61=YU.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")}),d61=JU("assistant",l61),CR0=[...d61]});var $M,u7,SR0,p61,c61,vR0,n61,i61,a61,r61,o61,s61,kR0,t61,e61,Q11,X11,Y11,J11,G11,W11,Z11,$11,mj4,K11,lj4,RR0,H11,F11,kt,_R0;var _t=y(()=>{W6();nw();o$();$M=N.lazy(()=>N.union([N.null(),N.string(),N.number(),N.boolean(),N.record(N.string(),$M),N.array($M)])),u7=N.record(N.string(),N.record(N.string(),$M)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),SR0=N.object({type:N.literal("text"),text:N.string().describe("The text content"),providerOptions:u7}),p61=N.object({type:N.literal("text"),text:N.string().describe("The text content"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),c61=N.string().describe("File data as URL string"),vR0=N.object({type:N.literal("file"),filename:N.string().optional().describe("Optional filename of the file"),data:c61,mediaType:N.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:u7}),n61=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")}),i61=N.object({type:N.literal("reasoning"),text:N.string().describe("The reasoning text"),providerOptions:u7}),a61=N.object({type:N.literal("reasoning"),text:N.string().describe("The reasoning text"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),r61=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:u7}),o61=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")}),s61=N.union([N.object({type:N.literal("text"),value:N.string()}),N.object({type:N.literal("json"),value:$M}),N.object({type:N.literal("error-text"),value:N.string()}),N.object({type:N.literal("error-json"),value:$M}),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")})]))})]),kR0=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:s61.describe("Result of the tool call"),result:N.unknown().describe("Unknown result of the tool call"),providerOptions:u7}),t61=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")}),e61=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")})]),Q11=N.object({role:N.literal("system"),content:N.string().describe("System message content"),providerOptions:u7}),X11=N.object({role:N.literal("user"),content:N.array(N.union([SR0,vR0])).describe("User message content parts (text or file)"),providerOptions:u7}),Y11=N.object({role:N.literal("assistant"),content:N.array(N.union([SR0,vR0,i61,r61,kR0])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:u7}),J11=N.object({role:N.literal("tool"),content:N.array(kR0).describe("Tool message content (tool results)"),providerOptions:u7}),G11=N.union([Q11,X11,Y11,J11]),W11=N.array(G11).describe("A list of messages forming the prompt"),Z11=N.object({prompt:W11.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")}),$11=N.object({content:N.array(N.union([p61,n61,a61,o61,t61,e61])).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")}),mj4=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")}),K11=N.object({supportedUrls:N.record(N.string(),N.array(N.string())).describe("Supported URL patterns by media type for the provider")}),lj4=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()}),RR0=N.object({modelId:N.string().describe("The ID of the model"),callOptions:Z11}),H11=YU.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()}),F11=JU("llm",H11,{readOnly:!0}),kt=[{name:"LLM_METADATA",inputSchema:N.object({modelId:N.string().describe("The ID of the model")}),outputSchema:K11},{name:"LLM_DO_STREAM",inputSchema:RR0,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:RR0,outputSchema:$11},...F11],_R0=XU(kt)});function q11(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 s$(Q){return typeof Q==="string"||typeof Q==="number"}function Fk(Q,X){if("conditions"in X){let{operator:$,conditions:K}=X;switch($){case"and":return K.every((H)=>Fk(Q,H));case"or":return K.some((H)=>Fk(Q,H));case"not":return!K.every((H)=>Fk(Q,H));default:return!0}}let{field:Y,operator:J,value:G}=X,W=Y.join("."),Z=yt(Q,W);switch(J){case"eq":return Z===G;case"gt":return s$(Z)&&s$(G)&&Z>G;case"gte":return s$(Z)&&s$(G)&&Z>=G;case"lt":return s$(Z)&&s$(G)&&Z<G;case"lte":return s$(Z)&&s$(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 $=q11(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 yt(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 z11(Q,X){return[...Q].sort((Y,J)=>{for(let G of X){let W=G.field.join("."),Z=yt(Y,W),$=yt(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 V11,U11,B11,bt;var yR0=y(()=>{Hk();IR0();o$();_t();W6();j1();T7();V11={LLM:kt,ASSISTANTS:CR0};U11=iw.extend({binding:N.union([N.object({}).passthrough(),N.string()]).optional()}),B11=aw(fJ),bt=D6({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",inputSchema:U11,outputSchema:B11,handler:async(Q,X)=>{await X.access.check();let Y=L1(X),J=Q.binding?typeof Q.binding==="string"?(()=>{let q=V11[Q.binding.toUpperCase()];if(!q)throw Error(`Unknown binding: ${Q.binding}`);return q})():Q.binding:void 0,G=J?Kk(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)=>Fk(q,Q.where));if(Q.orderBy&&Q.orderBy.length>0)Z=z11(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 D11,ft;var bR0=y(()=>{o$();j1();T7();D11=It(fJ),ft=D6({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",inputSchema:Ct,outputSchema:D11,handler:async(Q,X)=>{let Y=L1(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 Vk=(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 fR0(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 N11(Q){let X=Q.split("::");if(X.length!==2||!X[0]||!X[1])return null;return X}function O11(Q){if(typeof Q==="object"&&Q!==null&&"value"in Q){let X=Q.value;if(typeof X==="string")return X}return null}function ht(Q,X){let Y={};if(!Q||!X)return Y;for(let J of X){if(J==="*"){Y["*"]=["*"];continue}let G=N11(J);if(!G)continue;let[W,Z]=G,$=Vk(W,Q),K=O11($);if(K){if(!Y[K])Y[K]=[];Y[K].push(Z)}}return Y}function hR0(Q,X){let Y=ht(Q,X);return new Set(Object.keys(Y).filter((J)=>J!=="*"))}var xt=()=>{};class m7{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=hJ("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 qk=y(()=>{SL()});async function M11(Q,X,Y,J){for(let W of X){if(W==="*")continue;let[Z]=fR0(W),$=Vk(Z,Q);if($===void 0||$===null)throw Error(`Scope references key "${Z}" but it's not present in state`)}let G=hR0(Q,X);for(let W of G){if(W===T5.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 L11,w11,gt;var xR0=y(()=>{xt();V3();qk();W6();j1();nv();T7();L11=N.object({id:N.string().describe("ID of the connection to update"),data:PL0.describe("Partial connection data to update")}),w11=N.object({item:fJ.describe("The updated connection entity")});gt=D6({name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update an existing MCP connection in the organization",inputSchema:L11,outputSchema:w11,handler:async(Q,X)=>{I6(X);let Y=L1(X);await X.access.check();let J=iQ(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 M11($,K,Y.id,X)}let H=W.connection_token??Z.connection_token;if(!H)try{let D=await new m7(X.db,X.vault).get(G,J);if(D?.accessToken)H=D.accessToken}catch{}let F=await dz({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 ut;var gR0=y(()=>{o$();j1();T7();ut=D6({name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete a connection",inputSchema:Rt,outputSchema:St(fJ),handler:async(Q,X)=>{I6(X);let Y=L1(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 mt;var uR0=y(()=>{W6();j1();mt=D6({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=L1(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 mR0=y(()=>{sI0();yR0();bR0();xR0();gR0();uR0()});import{sql as s1}from"kysely";function lR0(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 A11(Q,X){let Y=Q;for(let G=X.length;G>=1;G--){let W=`$${G}`;if(Y.includes(W))Y=Y.replaceAll(W,lR0(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=lR0(X[G]);Y=Y.slice(0,W)+Z+Y.slice(W+1)}return Y}function dR0(Q){return Q.replace(/-/g,"_")}function j11(Q){return`app_${dR0(Q)}`}function C11(Q){return`app_role_${dR0(Q)}`}function I11(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 R11(Q,X,Y){if(await s1`CREATE SCHEMA IF NOT EXISTS ${s1.id(X)}`.execute(Q),!(await s1`
988
988
  SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${Y}) as exists
989
- `.execute(Q)).rows[0]?.exists)await s1`CREATE ROLE ${s1.id(Y)} NOLOGIN`.execute(Q);await s1`GRANT ${s1.id(Y)} TO CURRENT_USER`.execute(Q),await s1`GRANT USAGE, CREATE ON SCHEMA ${s1.id(X)} TO ${s1.id(Y)}`.execute(Q),await s1`GRANT ALL ON ALL TABLES IN SCHEMA ${s1.id(X)} TO ${s1.id(Y)}`.execute(Q),await s1`GRANT ALL ON ALL SEQUENCES IN SCHEMA ${s1.id(X)} TO ${s1.id(Y)}`.execute(Q),await s1`ALTER DEFAULT PRIVILEGES IN SCHEMA ${s1.id(X)} GRANT ALL ON TABLES TO ${s1.id(Y)}`.execute(Q),await s1`ALTER DEFAULT PRIVILEGES IN SCHEMA ${s1.id(X)} GRANT ALL ON SEQUENCES TO ${s1.id(Y)}`.execute(Q),await s1`REVOKE ALL ON SCHEMA public FROM ${s1.id(Y)}`.execute(Q)}async function S11(Q,X,Y,J){try{return await Q.transaction().execute(async(G)=>{return await s1`SET LOCAL ROLE ${s1.id(Y)}`.execute(G),await s1`SET LOCAL search_path TO ${s1.id(X)}`.execute(G),await s1.raw(J).execute(G)})}catch(G){if(I11(G))return await R11(Q,X,Y),await Q.transaction().execute(async(W)=>{return await s1`SET LOCAL ROLE ${s1.id(Y)}`.execute(W),await s1`SET LOCAL search_path TO ${s1.id(X)}`.execute(W),await s1.raw(J).execute(W)});throw G}}var T11,E11,pR0;var cR0=y(()=>{W6();j1();T11=N.object({results:N.array(N.unknown()).optional(),success:N.boolean().optional()});E11=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()});pR0=D6({name:"DATABASES_RUN_SQL",description:"Run a SQL query against the database",inputSchema:E11,outputSchema:N.object({result:N.array(T11)}),handler:async(Q,X)=>{I6(X),await X.access.check();let Y=A11(Q.sql,Q.params||[]);if(!X.connectionId)throw Error("Connection context required for database access");let J=j11(X.connectionId),G=C11(X.connectionId);return{result:[{results:(await S11(X.db,J,G,Y)).rows,success:!0}]}}})});var nR0,k11,iR0;var l7=y(()=>{W6();Hk();nR0=N.object({connectionId:N.string().optional().describe("Filter subscriptions by connection ID (optional)")}),k11=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")}),iR0=N.object({subscriptions:N.array(k11).describe("List of subscriptions")})});var lt;var aR0=y(()=>{j1();l7();lt=D6({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:rw,outputSchema:ow,handler:async(Q,X)=>{I6(X);let Y=L1(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 dt;var rR0=y(()=>{j1();l7();dt=D6({name:"EVENT_SUBSCRIBE",description:"Subscribe to events of a specific type. The subscriber is automatically set to the caller's connection.",inputSchema:sw,outputSchema:tw,handler:async(Q,X)=>{I6(X);let Y=L1(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 pt;var oR0=y(()=>{j1();l7();pt=D6({name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events by removing a subscription.",inputSchema:XM,outputSchema:YM,handler:async(Q,X)=>{I6(X);let Y=L1(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 ct;var sR0=y(()=>{j1();l7();ct=D6({name:"EVENT_CANCEL",description:"Cancel a recurring event to stop future deliveries. Only the publisher can cancel their own events.",inputSchema:JM,outputSchema:GM,handler:async(Q,X)=>{I6(X);let Y=L1(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 nt;var tR0=y(()=>{j1();l7();nt=D6({name:"EVENT_ACK",description:"Acknowledge delivery of an event. Call after successfully processing an event received via ON_EVENTS with retryAfter.",inputSchema:WM,outputSchema:ZM,handler:async(Q,X)=>{I6(X);let Y=L1(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 it;var eR0=y(()=>{j1();l7();it=D6({name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions, optionally filtered by connection ID.",inputSchema:nR0,outputSchema:iR0,handler:async(Q,X)=>{I6(X);let Y=L1(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 at;var QS0=y(()=>{j1();l7();at=D6({name:"EVENT_SYNC_SUBSCRIPTIONS",description:"Sync subscriptions to desired state. Creates new, deletes removed, updates changed filters. Subscriptions are identified by (eventType, publisher).",inputSchema:ew,outputSchema:QM,handler:async(Q,X)=>{I6(X);let Y=L1(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 XS0=y(()=>{aR0();rR0();oR0();sR0();tR0();eR0();QS0();l7()});var rt,ot,y11,ZW,YS0,JS0;var GU=y(()=>{W6();rt=N.enum(["inclusion","exclusion"]).describe("Tool selection mode: 'inclusion' = include selected (default), 'exclusion' = exclude selected"),ot=N.enum(["passthrough","smart_tool_selection","code_execution"]).describe("Gateway tool selection strategy: 'passthrough' (default), 'smart_tool_selection', or 'code_execution'"),y11=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.")}),ZW=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:ot.describe("Gateway behavior strategy (metadata for now): 'passthrough', 'smart_tool_selection', or 'code_execution'"),tool_selection_mode:rt.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(y11).describe("Connections with their selected tools (behavior depends on tool_selection_mode)")}),YS0=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:ot.optional().default("passthrough").describe("Gateway behavior strategy (defaults to 'passthrough')"),tool_selection_mode:rt.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)")}),JS0=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:ot.optional().describe("New gateway behavior strategy"),tool_selection_mode:rt.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 b11,f11,st;var GS0=y(()=>{W6();j1();GU();b11=N.object({data:YS0.describe("Data for the new gateway")}),f11=N.object({item:ZW.describe("The created gateway entity")}),st=D6({name:"COLLECTION_GATEWAY_CREATE",description:"Create a new MCP gateway in the organization",inputSchema:b11,outputSchema:f11,handler:async(Q,X)=>{I6(X);let Y=L1(X);await X.access.check();let J=iQ(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 h11(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 t$(Q){return typeof Q==="string"||typeof Q==="number"}function tt(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 x11(Q,X){return Q.connections.some((Y)=>Y.connection_id===X)}function zk(Q,X){if("conditions"in X){let{operator:$,conditions:K}=X;switch($){case"and":return K.every((H)=>zk(Q,H));case"or":return K.some((H)=>zk(Q,H));case"not":return!K.every((H)=>zk(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 x11(Q,G)}let Z=tt(Q,W);switch(J){case"eq":return Z===G;case"gt":return t$(Z)&&t$(G)&&Z>G;case"gte":return t$(Z)&&t$(G)&&Z>=G;case"lt":return t$(Z)&&t$(G)&&Z<G;case"lte":return t$(Z)&&t$(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 $=h11(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 g11(Q,X){return[...Q].sort((Y,J)=>{for(let G of X){let W=G.field.join("."),Z=tt(Y,W),$=tt(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 u11,m11,et;var WS0=y(()=>{o$();j1();GU();u11=iw,m11=aw(ZW),et=D6({name:"COLLECTION_GATEWAY_LIST",description:"List all MCP gateways in the organization",inputSchema:u11,outputSchema:m11,handler:async(Q,X)=>{await X.access.check();let Y=L1(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)=>zk(V,Q.where));if(Q.orderBy&&Q.orderBy.length>0)W=g11(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 l11,d11,Qe;var ZS0=y(()=>{W6();j1();GU();l11=N.object({id:N.string().describe("ID of the gateway to retrieve")}),d11=N.object({item:ZW.nullable().describe("The retrieved gateway, or null if not found")}),Qe=D6({name:"COLLECTION_GATEWAY_GET",description:"Get an MCP gateway by ID",inputSchema:l11,outputSchema:d11,handler:async(Q,X)=>{I6(X);let Y=L1(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 p11,c11,Xe;var $S0=y(()=>{W6();j1();GU();p11=N.object({id:N.string().describe("ID of the gateway to update"),data:JS0.describe("Partial gateway data to update")}),c11=N.object({item:ZW.describe("The updated gateway entity")}),Xe=D6({name:"COLLECTION_GATEWAY_UPDATE",description:"Update an MCP gateway",inputSchema:p11,outputSchema:c11,handler:async(Q,X)=>{I6(X);let Y=L1(X);await X.access.check();let J=iQ(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 n11,i11,Ye;var KS0=y(()=>{W6();j1();GU();n11=N.object({id:N.string().describe("ID of the gateway to delete")}),i11=N.object({item:ZW.describe("The deleted gateway entity")}),Ye=D6({name:"COLLECTION_GATEWAY_DELETE",description:"Delete an MCP gateway",inputSchema:n11,outputSchema:i11,handler:async(Q,X)=>{I6(X);let Y=L1(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 HS0=y(()=>{GS0();WS0();ZS0();$S0();KS0()});var r11,Je;var FS0=y(()=>{j1();W6();r11=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")}),Je=D6({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(r11).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=L1(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 Ge;var VS0=y(()=>{j1();W6();Ge=D6({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:L1(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 qS0=y(()=>{FS0();VS0()});var We;var zS0=y(()=>{W6();j1();We=D6({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)=>{I6(X),await X.access.check();let Y=iQ(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 Ze;var US0=y(()=>{W6();j1();Ze=D6({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)=>{I6(X),await X.access.check();let Y=iQ(X),J=Q.userId||Y;if(!J)throw Error("User ID required to list organizations");return{organizations:await X.boundAuth.organization.list(J)}}})});var $e;var BS0=y(()=>{W6();j1();$e=D6({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)=>{I6(X),await X.access.check();let Y=await X.boundAuth.organization.get();if(!Y)throw Error("No active organization found");return Y}})});var Ke;var DS0=y(()=>{W6();j1();Ke=D6({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)=>{I6(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 He;var NS0=y(()=>{W6();j1();He=D6({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 I6(X),await X.access.check(),await X.boundAuth.organization.delete(Q.id),{success:!0,id:Q.id}}})});var KM;var Fe=y(()=>{W6();KM=N.object({title:N.string(),url:N.string(),icon:N.string()})});var Ve;var OS0=y(()=>{W6();j1();Fe();Ve=D6({name:"ORGANIZATION_SETTINGS_GET",description:"Get organization-level settings",inputSchema:N.object({}),outputSchema:N.object({organizationId:N.string(),sidebar_items:N.array(KM).nullable().optional(),createdAt:N.union([N.date(),N.string()]).optional(),updatedAt:N.union([N.date(),N.string()]).optional()}),handler:async(Q,X)=>{I6(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 qe;var LS0=y(()=>{W6();j1();Fe();qe=D6({name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization-level settings",inputSchema:N.object({organizationId:N.string(),sidebar_items:N.array(KM).optional()}),outputSchema:N.object({organizationId:N.string(),sidebar_items:N.array(KM).nullable().optional(),createdAt:N.union([N.date(),N.string()]),updatedAt:N.union([N.date(),N.string()])}),handler:async(Q,X)=>{if(I6(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 ze;var wS0=y(()=>{W6();j1();ze=D6({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)=>{I6(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 Ue;var MS0=y(()=>{W6();j1();Ue=D6({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)=>{I6(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 Be;var PS0=y(()=>{W6();j1();Be=D6({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)=>{I6(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 De;var TS0=y(()=>{W6();j1();De=D6({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)=>{I6(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 AS0=y(()=>{zS0();US0();BS0();DS0();NS0();OS0();LS0();wS0();MS0();PS0();TS0()});var t11,e11,Ne;var ES0=y(()=>{W6();j1();t11=N.object({id:N.string().min(1)}),e11=N.object({user:N.object({id:N.string(),name:N.string(),email:N.string(),image:N.string().nullable()}).nullable()}),Ne=D6({name:"USER_GET",description:"Get a user by id (restricted to shared organizations)",inputSchema:t11,outputSchema:e11,handler:async(Q,X)=>{await X.access.check(),I6(X);let Y=iQ(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 jS0=y(()=>{ES0()});var IS0={};q1(IS0,{managementMCP:()=>Oe,ALL_TOOLS:()=>CS0});var CS0,Oe=(Q)=>{let X=CS0.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 uj0({name:"mcp-mesh-management",version:"1.0.0"}).withTools(X).build()};var Le=y(()=>{mj0();oI0();mR0();cR0();XS0();HS0();qS0();AS0();jS0();CS0=[We,Ze,$e,Ke,He,Ve,qe,ze,Ue,Be,De,zt,bt,ft,gt,ut,mt,st,et,Qe,Xe,Ye,pR0,Je,Ge,Ht,Vt,qt,Ft,lt,dt,pt,ct,nt,it,at,Ne]});function X41(Q){return[{permissions:{self:["*"]},getTools:async()=>{let{ALL_TOOLS:X}=await Promise.resolve().then(() => (Le(),IS0));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:DL0(process.env.BASE_URL||"http://localhost:3000")},{data:BL0()},{data:UL0(Q)}]}async function RS0(Q,X){try{let Y=F3(),J=new RL(process.env.ENCRYPTION_KEY||""),G=new vL(Y.db,J),W=new kL(Y.db),Z=X41(Q),$=[];await Promise.all(Z.map(async(K)=>{let H=null;if(K.permissions)H=(await b5.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 dz({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 SS0=y(()=>{V3();CL();Ua();Ba();Da();nv();W6();WU()});var we,vS0;var Me=y(()=>{we=["owner","admin","user"],vS0=["owner","admin"]});var Y41=(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"}}}}]}},kS0=(Q)=>{if(Q.providerId==="microsoft")return Y41(Q);throw Error(`Unsupported provider: ${Q.providerId}`)};function J41(Q){return Q.toLowerCase().trim().replace(/[^a-z0-9\s_-]+/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function G41(){let Q=Math.floor(Math.random()*yS0.length),X=Math.floor(Math.random()*_S0.length),Y=yS0[Q]??"deco",J=_S0[X]??"studio";return`${Y}-${J}`}var _S0,yS0,W41,Z41,Uk,$41,K41,H41,bS0,o8,fS0=void 0,F41,V41,q41,b5;var WU=y(()=>{Ul();iz0();_B0();Xn();ji();ED0();Ci();kD0();CL();za();VL0();SS0();Me();_S0=["labs","hub","studio","workspace","systems","core","cloud","works"],yS0=["capybara","guarana","deco","samba","feijoada","capoeira","carnival"];W41=Object.values(SN()).map((Q)=>Q.map((X)=>X.name)).flat(),Z41={...IR,self:["*",...W41]},Uk=rG(Z41),$41=Uk.newRole({self:["*"],...KL.statements}),K41=Uk.newRole({self:["*"],...KL.statements}),H41=Uk.newRole({self:["*"],...KL.statements}),bS0=Object.values(SN()).map((Q)=>Q.map((X)=>`self:${X.name}`)).flat(),o8=pR.auth;if(o8.inviteEmailProviderId&&o8.emailProviders&&o8.emailProviders.length>0){let Q=JS(o8.emailProviders,o8.inviteEmailProviderId);if(Q){let X=YS(Q);fS0=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:`
989
+ `.execute(Q)).rows[0]?.exists)await s1`CREATE ROLE ${s1.id(Y)} NOLOGIN`.execute(Q);await s1`GRANT ${s1.id(Y)} TO CURRENT_USER`.execute(Q),await s1`GRANT USAGE, CREATE ON SCHEMA ${s1.id(X)} TO ${s1.id(Y)}`.execute(Q),await s1`GRANT ALL ON ALL TABLES IN SCHEMA ${s1.id(X)} TO ${s1.id(Y)}`.execute(Q),await s1`GRANT ALL ON ALL SEQUENCES IN SCHEMA ${s1.id(X)} TO ${s1.id(Y)}`.execute(Q),await s1`ALTER DEFAULT PRIVILEGES IN SCHEMA ${s1.id(X)} GRANT ALL ON TABLES TO ${s1.id(Y)}`.execute(Q),await s1`ALTER DEFAULT PRIVILEGES IN SCHEMA ${s1.id(X)} GRANT ALL ON SEQUENCES TO ${s1.id(Y)}`.execute(Q),await s1`REVOKE ALL ON SCHEMA public FROM ${s1.id(Y)}`.execute(Q)}async function S11(Q,X,Y,J){try{return await Q.transaction().execute(async(G)=>{return await s1`SET LOCAL ROLE ${s1.id(Y)}`.execute(G),await s1`SET LOCAL search_path TO ${s1.id(X)}`.execute(G),await s1.raw(J).execute(G)})}catch(G){if(I11(G))return await R11(Q,X,Y),await Q.transaction().execute(async(W)=>{return await s1`SET LOCAL ROLE ${s1.id(Y)}`.execute(W),await s1`SET LOCAL search_path TO ${s1.id(X)}`.execute(W),await s1.raw(J).execute(W)});throw G}}var T11,E11,pR0;var cR0=y(()=>{W6();j1();T11=N.object({results:N.array(N.unknown()).optional(),success:N.boolean().optional()});E11=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()});pR0=D6({name:"DATABASES_RUN_SQL",description:"Run a SQL query against the database",inputSchema:E11,outputSchema:N.object({result:N.array(T11)}),handler:async(Q,X)=>{I6(X),await X.access.check();let Y=A11(Q.sql,Q.params||[]);if(!X.connectionId)throw Error("Connection context required for database access");let J=j11(X.connectionId),G=C11(X.connectionId);return{result:[{results:(await S11(X.db,J,G,Y)).rows,success:!0}]}}})});var nR0,k11,iR0;var l7=y(()=>{W6();Hk();nR0=N.object({connectionId:N.string().optional().describe("Filter subscriptions by connection ID (optional)")}),k11=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")}),iR0=N.object({subscriptions:N.array(k11).describe("List of subscriptions")})});var lt;var aR0=y(()=>{j1();l7();lt=D6({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:rw,outputSchema:ow,handler:async(Q,X)=>{I6(X);let Y=L1(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 dt;var rR0=y(()=>{j1();l7();dt=D6({name:"EVENT_SUBSCRIBE",description:"Subscribe to events of a specific type. The subscriber is automatically set to the caller's connection.",inputSchema:sw,outputSchema:tw,handler:async(Q,X)=>{I6(X);let Y=L1(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 pt;var oR0=y(()=>{j1();l7();pt=D6({name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events by removing a subscription.",inputSchema:XM,outputSchema:YM,handler:async(Q,X)=>{I6(X);let Y=L1(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 ct;var sR0=y(()=>{j1();l7();ct=D6({name:"EVENT_CANCEL",description:"Cancel a recurring event to stop future deliveries. Only the publisher can cancel their own events.",inputSchema:JM,outputSchema:GM,handler:async(Q,X)=>{I6(X);let Y=L1(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 nt;var tR0=y(()=>{j1();l7();nt=D6({name:"EVENT_ACK",description:"Acknowledge delivery of an event. Call after successfully processing an event received via ON_EVENTS with retryAfter.",inputSchema:WM,outputSchema:ZM,handler:async(Q,X)=>{I6(X);let Y=L1(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 it;var eR0=y(()=>{j1();l7();it=D6({name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions, optionally filtered by connection ID.",inputSchema:nR0,outputSchema:iR0,handler:async(Q,X)=>{I6(X);let Y=L1(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 at;var QS0=y(()=>{j1();l7();at=D6({name:"EVENT_SYNC_SUBSCRIPTIONS",description:"Sync subscriptions to desired state. Creates new, deletes removed, updates changed filters. Subscriptions are identified by (eventType, publisher).",inputSchema:ew,outputSchema:QM,handler:async(Q,X)=>{I6(X);let Y=L1(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 XS0=y(()=>{aR0();rR0();oR0();sR0();tR0();eR0();QS0();l7()});var rt,ot,y11,ZW,YS0,JS0;var GU=y(()=>{W6();rt=N.enum(["inclusion","exclusion"]).describe("Tool selection mode: 'inclusion' = include selected (default), 'exclusion' = exclude selected"),ot=N.enum(["passthrough","smart_tool_selection","code_execution"]).describe("Gateway tool selection strategy: 'passthrough' (default), 'smart_tool_selection', or 'code_execution'"),y11=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.")}),ZW=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:ot.describe("Gateway behavior strategy (metadata for now): 'passthrough', 'smart_tool_selection', or 'code_execution'"),tool_selection_mode:rt.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(y11).describe("Connections with their selected tools (behavior depends on tool_selection_mode)")}),YS0=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:ot.optional().default("passthrough").describe("Gateway behavior strategy (defaults to 'passthrough')"),tool_selection_mode:rt.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)")}),JS0=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:ot.optional().describe("New gateway behavior strategy"),tool_selection_mode:rt.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 b11,f11,st;var GS0=y(()=>{W6();j1();GU();b11=N.object({data:YS0.describe("Data for the new gateway")}),f11=N.object({item:ZW.describe("The created gateway entity")}),st=D6({name:"COLLECTION_GATEWAY_CREATE",description:"Create a new MCP gateway in the organization",inputSchema:b11,outputSchema:f11,handler:async(Q,X)=>{I6(X);let Y=L1(X);await X.access.check();let J=iQ(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 h11(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 t$(Q){return typeof Q==="string"||typeof Q==="number"}function tt(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 x11(Q,X){return Q.connections.some((Y)=>Y.connection_id===X)}function zk(Q,X){if("conditions"in X){let{operator:$,conditions:K}=X;switch($){case"and":return K.every((H)=>zk(Q,H));case"or":return K.some((H)=>zk(Q,H));case"not":return!K.every((H)=>zk(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 x11(Q,G)}let Z=tt(Q,W);switch(J){case"eq":return Z===G;case"gt":return t$(Z)&&t$(G)&&Z>G;case"gte":return t$(Z)&&t$(G)&&Z>=G;case"lt":return t$(Z)&&t$(G)&&Z<G;case"lte":return t$(Z)&&t$(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 $=h11(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 g11(Q,X){return[...Q].sort((Y,J)=>{for(let G of X){let W=G.field.join("."),Z=tt(Y,W),$=tt(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 u11,m11,et;var WS0=y(()=>{o$();j1();GU();u11=iw,m11=aw(ZW),et=D6({name:"COLLECTION_GATEWAY_LIST",description:"List all MCP gateways in the organization",inputSchema:u11,outputSchema:m11,handler:async(Q,X)=>{await X.access.check();let Y=L1(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)=>zk(V,Q.where));if(Q.orderBy&&Q.orderBy.length>0)W=g11(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 l11,d11,Qe;var ZS0=y(()=>{W6();j1();GU();l11=N.object({id:N.string().describe("ID of the gateway to retrieve")}),d11=N.object({item:ZW.nullable().describe("The retrieved gateway, or null if not found")}),Qe=D6({name:"COLLECTION_GATEWAY_GET",description:"Get an MCP gateway by ID",inputSchema:l11,outputSchema:d11,handler:async(Q,X)=>{I6(X);let Y=L1(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 p11,c11,Xe;var $S0=y(()=>{W6();j1();GU();p11=N.object({id:N.string().describe("ID of the gateway to update"),data:JS0.describe("Partial gateway data to update")}),c11=N.object({item:ZW.describe("The updated gateway entity")}),Xe=D6({name:"COLLECTION_GATEWAY_UPDATE",description:"Update an MCP gateway",inputSchema:p11,outputSchema:c11,handler:async(Q,X)=>{I6(X);let Y=L1(X);await X.access.check();let J=iQ(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 n11,i11,Ye;var KS0=y(()=>{W6();j1();GU();n11=N.object({id:N.string().describe("ID of the gateway to delete")}),i11=N.object({item:ZW.describe("The deleted gateway entity")}),Ye=D6({name:"COLLECTION_GATEWAY_DELETE",description:"Delete an MCP gateway",inputSchema:n11,outputSchema:i11,handler:async(Q,X)=>{I6(X);let Y=L1(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 HS0=y(()=>{GS0();WS0();ZS0();$S0();KS0()});var r11,Je;var FS0=y(()=>{j1();W6();r11=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")}),Je=D6({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(r11).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=L1(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 Ge;var VS0=y(()=>{j1();W6();Ge=D6({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:L1(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 qS0=y(()=>{FS0();VS0()});var We;var zS0=y(()=>{W6();j1();We=D6({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)=>{I6(X),await X.access.check();let Y=iQ(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 Ze;var US0=y(()=>{W6();j1();Ze=D6({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)=>{I6(X),await X.access.check();let Y=iQ(X),J=Q.userId||Y;if(!J)throw Error("User ID required to list organizations");return{organizations:await X.boundAuth.organization.list(J)}}})});var $e;var BS0=y(()=>{W6();j1();$e=D6({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)=>{I6(X),await X.access.check();let Y=await X.boundAuth.organization.get();if(!Y)throw Error("No active organization found");return Y}})});var Ke;var DS0=y(()=>{W6();j1();Ke=D6({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)=>{I6(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 He;var NS0=y(()=>{W6();j1();He=D6({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 I6(X),await X.access.check(),await X.boundAuth.organization.delete(Q.id),{success:!0,id:Q.id}}})});var KM;var Fe=y(()=>{W6();KM=N.object({title:N.string(),url:N.string(),icon:N.string()})});var Ve;var OS0=y(()=>{W6();j1();Fe();Ve=D6({name:"ORGANIZATION_SETTINGS_GET",description:"Get organization-level settings",inputSchema:N.object({}),outputSchema:N.object({organizationId:N.string(),sidebar_items:N.array(KM).nullable().optional(),createdAt:N.union([N.date(),N.string()]).optional(),updatedAt:N.union([N.date(),N.string()]).optional()}),handler:async(Q,X)=>{I6(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 qe;var LS0=y(()=>{W6();j1();Fe();qe=D6({name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization-level settings",inputSchema:N.object({organizationId:N.string(),sidebar_items:N.array(KM).optional()}),outputSchema:N.object({organizationId:N.string(),sidebar_items:N.array(KM).nullable().optional(),createdAt:N.union([N.date(),N.string()]),updatedAt:N.union([N.date(),N.string()])}),handler:async(Q,X)=>{if(I6(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 ze;var wS0=y(()=>{W6();j1();ze=D6({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)=>{I6(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 Ue;var MS0=y(()=>{W6();j1();Ue=D6({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)=>{I6(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 Be;var PS0=y(()=>{W6();j1();Be=D6({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)=>{I6(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 De;var TS0=y(()=>{W6();j1();De=D6({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)=>{I6(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 AS0=y(()=>{zS0();US0();BS0();DS0();NS0();OS0();LS0();wS0();MS0();PS0();TS0()});var t11,e11,Ne;var ES0=y(()=>{W6();j1();t11=N.object({id:N.string().min(1)}),e11=N.object({user:N.object({id:N.string(),name:N.string(),email:N.string(),image:N.string().nullable()}).nullable()}),Ne=D6({name:"USER_GET",description:"Get a user by id (restricted to shared organizations)",inputSchema:t11,outputSchema:e11,handler:async(Q,X)=>{await X.access.check(),I6(X);let Y=iQ(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 jS0=y(()=>{ES0()});var IS0={};q1(IS0,{managementMCP:()=>Oe,ALL_TOOLS:()=>CS0});var CS0,Oe=(Q)=>{let X=CS0.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 uj0({name:"mcp-mesh-management",version:"1.0.0"}).withTools(X).build()};var Le=y(()=>{mj0();oI0();mR0();cR0();XS0();HS0();qS0();AS0();jS0();CS0=[We,Ze,$e,Ke,He,Ve,qe,ze,Ue,Be,De,zt,bt,ft,gt,ut,mt,st,et,Qe,Xe,Ye,pR0,Je,Ge,Ht,Vt,qt,Ft,lt,dt,pt,ct,nt,it,at,Ne]});function X41(Q){return[{permissions:{self:["*"]},getTools:async()=>{let{ALL_TOOLS:X}=await Promise.resolve().then(() => (Le(),IS0));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:DL0(process.env.BASE_URL||"http://localhost:3000")},{data:BL0()},{data:UL0(Q)}]}async function RS0(Q,X){try{let Y=F3(),J=new RL(process.env.ENCRYPTION_KEY||""),G=new vL(Y.db,J),W=new kL(Y.db),Z=X41(Q),$=[];await Promise.all(Z.map(async(K)=>{let H=null;if(K.permissions)H=(await b5.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 dz({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 SS0=y(()=>{V3();CL();Ua();Ba();Da();nv();W6();WU()});var we,vS0;var Me=y(()=>{we=["owner","admin","user"],vS0=["owner","admin"]});var Y41=(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"}}}}]}},kS0=(Q)=>{if(Q.providerId==="microsoft")return Y41(Q);throw Error(`Unsupported provider: ${Q.providerId}`)};function J41(Q){return Q.toLowerCase().trim().replace(/[^a-z0-9\s_-]+/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function G41(){let Q=Math.floor(Math.random()*yS0.length),X=Math.floor(Math.random()*_S0.length),Y=yS0[Q]??"deco",J=_S0[X]??"studio";return`${Y}-${J}`}var _S0,yS0,W41,Z41,Uk,$41,K41,H41,bS0,o8,fS0=void 0,F41,V41,q41,b5;var WU=y(()=>{Ul();iz0();_B0();Xn();ji();ED0();Ci();kD0();CL();za();VL0();SS0();Me();_S0=["labs","agent","studio","workspace","systems","core","cloud","works"],yS0=["capybara","guarana","deco","samba","feijoada","capoeira","carnival"];W41=Object.values(SN()).map((Q)=>Q.map((X)=>X.name)).flat(),Z41={...IR,self:["*",...W41]},Uk=rG(Z41),$41=Uk.newRole({self:["*"],...KL.statements}),K41=Uk.newRole({self:["*"],...KL.statements}),H41=Uk.newRole({self:["*"],...KL.statements}),bS0=Object.values(SN()).map((Q)=>Q.map((X)=>`self:${X.name}`)).flat(),o8=pR.auth;if(o8.inviteEmailProviderId&&o8.emailProviders&&o8.emailProviders.length>0){let Q=JS(o8.emailProviders,o8.inviteEmailProviderId);if(Q){let X=YS(Q);fS0=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:`
990
990
  <h2>You've been invited!</h2>
991
991
  <p>${J} has invited you to join <strong>${Y.organization.name}</strong>.</p>
992
992
  <p><a href="${G}">Click here to accept the invitation</a></p>
@@ -1053,7 +1053,7 @@ ${Q.stack}`;return X}if(typeof Q==="object"&&Q!==null){let X=Q,Y="";if(typeof X.
1053
1053
  ${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}
1054
1054
 
1055
1055
  Stack trace:
1056
- ${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 DB(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=DB(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=DB(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=DB(Q,K);$.resolve(H),H.dispose(),Q.runtime.executePendingJobs()}catch(H){let F=BB(H),V=Q.newString(`Promise resolution error: ${F}`);$.reject(V),V.dispose(),Q.runtime.executePendingJobs()}}).catch((K)=>{let H=BB(K),F=Q.newString(`Promise rejection: ${H}`);$.reject(F),F.dispose(),Q.runtime.executePendingJobs()}),$.handle}return DB(Q,Z)}catch(W){let Z=BB(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 y76=()=>{};function f76(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 b76(Q,X,Y){let J=Date.now(),G=Q.resolvePromise(X);while(!0){f76(Q);let W=await Promise.race([G,Vf1(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 _90({tools:Q,code:X,timeoutMs:Y}){let Z=[];try{let J=await k76({memoryLimitBytes:33554432,stackSizeBytes:524288});const G=Vf(Z,J.newContext({interruptAfterMs:Y}),0);const W=Vf(Z,eW6(G),0);try{let F=G.evalCode(X,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult(F),q=DB(G,Q);G.setProp(G.global,"tools",q);let z=G.runtime.hasPendingJob()?G.unwrapResult(await b76(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 b76(G,M,Y),A=G.unwrapResult(C);if(G.runtime.hasPendingJob())f76(G);return{returnValue:G.dump(A),consoleLogs:W.logs}}catch(F){return console.log(F),{error:BB(F),consoleLogs:W.logs}}}catch($){var K=$,H=1}finally{EX0(Z,K,H)}}var Vf1=(Q)=>new Promise((X)=>setTimeout(X,Q));var h76=y(()=>{_76();y76()});var x76=y(()=>{h76()});function qf1(Q){return Q.toLowerCase().split(/[\s_\-./]+/).filter((X)=>X.length>=2)}function zf1(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 Uf1(Q,X,Y){let J=qf1(Q);if(J.length===0)return X.slice(0,Y);return X.map((G)=>({tool:G,score:zf1(J,G)})).filter((G)=>G.score>0).sort((G,W)=>W.score-G.score).slice(0,Y).map((G)=>G.tool)}function y90(Q){return{content:[{type:"text",text:JSON.stringify(Q,null,2)}]}}function $T(Q){return{content:[{type:"text",text:JSON.stringify(Q,null,2)}],isError:!0}}function g76(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 $T({error:G.error.flatten()});let W=Uf1(G.data.query,Q.tools,G.data.limit);return y90({query:G.data.query,results:W.map((Z)=>({name:Z.name,description:Z.description,connection:Z._meta.connectionTitle})),totalAvailable:Q.tools.length})}}}function u76(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 $T({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 y90({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 Bf1(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 $T({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 Df1(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 $T({error:J.error.flatten()});let G=Object.fromEntries(Q.tools.map((Z)=>[Z.name,async($)=>Q.callTool(Z.name,$??{})])),W=await _90({...J.data,tools:G});if(W.error)return $T(W);return y90(W)}}}function m76(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)}}}function l76(Q){switch(Q){case"smart_tool_selection":return Lf1;case"code_execution":return Of1;case"passthrough":default:return Nf1}}var Nf1=(Q)=>({tools:Q.tools,callTool:(X,Y)=>Q.callTool(X,Y)}),Of1=(Q)=>m76([g76(Q),u76(Q),Df1(Q)]),Lf1=(Q)=>m76([g76(Q),u76(Q),Bf1(Q)]);var d76=y(()=>{W6();x76()});class lb{proxies;options;cache;constructor(Q,X){this.proxies=Q;this.options=X;this.cache=IW(()=>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})},$=l76(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"}})}}var p76=y(()=>{d76()});function wf1(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 c76(Q,X){return X.some((Y)=>wf1(Q,Y))}class db{proxies;options;cache;constructor(Q,X){this.proxies=Q;this.options=X;this.cache=IW(()=>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)=>!c76(K.uri,G.selectedResources))}else if(!G.selectedResources||G.selectedResources.length===0)$=[];else $=$.filter((K)=>c76(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)}}var n76=()=>{};class pb{proxies;cache;constructor(Q){this.proxies=Q;this.cache=IW(()=>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}}}var i76=()=>{};class cb{proxies;options;cache;constructor(Q,X){this.proxies=Q;this.options=X;this.cache=IW(()=>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 a76=()=>{};var r76=y(()=>{p76();n76();i76();a76()});async function Mf1(Q,X){let Y=await WT.create(Q.connections,X),J=new lb(Y,{selectionMode:Q.toolSelectionMode,strategy:Q.toolSelectionStrategy}),G=new db(Y,{selectionMode:Q.toolSelectionMode}),W=new pb(Y),Z=new cb(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 Pf1(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 Mf1(J,X)}var o76,s76;var t76=y(()=>{iv();av();s9();HZ();r76();o76=new I9;o76.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 Pf1(J,Y),Z=new j3({name:`mcp-gateway-${J.title}`,version:"1.0.0"},{capabilities:{tools:{},resources:{},prompts:{}}}),$=new C3({enableJsonResponse:Q.req.header("Accept")?.includes("application/json")??!1});return await Z.connect($),Z.server.setRequestHandler(x$,async(K)=>{return W.client.listTools()}),Z.server.setRequestHandler(YW,async(K)=>{return await W.client.callTool(K.params)}),Z.server.setRequestHandler(_$,async()=>{return W.client.listResources()}),Z.server.setRequestHandler(b$,async(K)=>{return W.client.readResource(K.params)}),Z.server.setRequestHandler(y$,async()=>{return W.client.listResourceTemplates()}),Z.server.setRequestHandler(f$,async()=>{return W.client.listPrompts()}),Z.server.setRequestHandler(h$,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)}});s76=o76});var e76,QZ6;var XZ6=y(()=>{HZ();Le();e76=new I9;e76.all("/",async(Q)=>{return Oe(Q.get("meshContext")).fetch(Q.req.raw)});QZ6=e76});function e5(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 SZ6="vercel.ai.error",Tf1,YZ6,JZ6,w6,vZ6="AI_APICallError",kZ6,Af1,GZ6,WZ6,YQ,_Z6="AI_EmptyResponseBodyError",yZ6,Ef1,ZZ6,$Z6,bZ6,fZ6="AI_InvalidArgumentError",hZ6,jf1,KZ6,HZ6,xZ6,gZ6="AI_InvalidPromptError",uZ6,Cf1,FZ6,VZ6,vF,mZ6="AI_InvalidResponseDataError",lZ6,If1,qZ6,zZ6,Fi4,dZ6="AI_JSONParseError",pZ6,Rf1,UZ6,BZ6,KT,cZ6="AI_LoadAPIKeyError",nZ6,Sf1,DZ6,NZ6,Vi4,iZ6="AI_LoadSettingError",aZ6,vf1,OZ6,LZ6,qi4,rZ6="AI_NoContentGeneratedError",oZ6,kf1,wZ6,MZ6,zi4,sZ6="AI_NoSuchModelError",tZ6,_f1,PZ6,TZ6,Ui4,eZ6="AI_TooManyEmbeddingValuesForCallError",Q$6,yf1,AZ6,EZ6,Bi4,X$6="AI_TypeValidationError",Y$6,bf1,jZ6,CZ6,QG,J$6="AI_UnsupportedFunctionalityError",G$6,ff1,IZ6,RZ6,Di4;var v4=y(()=>{Tf1=Symbol.for(SZ6),w6=class Q extends(JZ6=Error,YZ6=Tf1,JZ6){constructor({name:X,message:Y,cause:J}){super(Y);this[YZ6]=!0,this.name=X,this.cause=J}static isInstance(X){return Q.hasMarker(X,SZ6)}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}},kZ6=`vercel.ai.error.${vZ6}`,Af1=Symbol.for(kZ6),YQ=class extends(WZ6=w6,GZ6=Af1,WZ6){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:vZ6,message:Q,cause:Z});this[GZ6]=!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 w6.hasMarker(Q,kZ6)}},yZ6=`vercel.ai.error.${_Z6}`,Ef1=Symbol.for(yZ6),bZ6=class extends($Z6=w6,ZZ6=Ef1,$Z6){constructor({message:Q="Empty response body"}={}){super({name:_Z6,message:Q});this[ZZ6]=!0}static isInstance(Q){return w6.hasMarker(Q,yZ6)}};hZ6=`vercel.ai.error.${fZ6}`,jf1=Symbol.for(hZ6),xZ6=class extends(HZ6=w6,KZ6=jf1,HZ6){constructor({message:Q,cause:X,argument:Y}){super({name:fZ6,message:Q,cause:X});this[KZ6]=!0,this.argument=Y}static isInstance(Q){return w6.hasMarker(Q,hZ6)}},uZ6=`vercel.ai.error.${gZ6}`,Cf1=Symbol.for(uZ6),vF=class extends(VZ6=w6,FZ6=Cf1,VZ6){constructor({prompt:Q,message:X,cause:Y}){super({name:gZ6,message:`Invalid prompt: ${X}`,cause:Y});this[FZ6]=!0,this.prompt=Q}static isInstance(Q){return w6.hasMarker(Q,uZ6)}},lZ6=`vercel.ai.error.${mZ6}`,If1=Symbol.for(lZ6),Fi4=class extends(zZ6=w6,qZ6=If1,zZ6){constructor({data:Q,message:X=`Invalid response data: ${JSON.stringify(Q)}.`}){super({name:mZ6,message:X});this[qZ6]=!0,this.data=Q}static isInstance(Q){return w6.hasMarker(Q,lZ6)}},pZ6=`vercel.ai.error.${dZ6}`,Rf1=Symbol.for(pZ6),KT=class extends(BZ6=w6,UZ6=Rf1,BZ6){constructor({text:Q,cause:X}){super({name:dZ6,message:`JSON parsing failed: Text: ${Q}.
1056
+ ${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 DB(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=DB(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=DB(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=DB(Q,K);$.resolve(H),H.dispose(),Q.runtime.executePendingJobs()}catch(H){let F=BB(H),V=Q.newString(`Promise resolution error: ${F}`);$.reject(V),V.dispose(),Q.runtime.executePendingJobs()}}).catch((K)=>{let H=BB(K),F=Q.newString(`Promise rejection: ${H}`);$.reject(F),F.dispose(),Q.runtime.executePendingJobs()}),$.handle}return DB(Q,Z)}catch(W){let Z=BB(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 y76=()=>{};function f76(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 b76(Q,X,Y){let J=Date.now(),G=Q.resolvePromise(X);while(!0){f76(Q);let W=await Promise.race([G,Vf1(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 _90({tools:Q,code:X,timeoutMs:Y}){let Z=[];try{let J=await k76({memoryLimitBytes:33554432,stackSizeBytes:524288});const G=Vf(Z,J.newContext({interruptAfterMs:Y}),0);const W=Vf(Z,eW6(G),0);try{let F=G.evalCode(X,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult(F),q=DB(G,Q);G.setProp(G.global,"tools",q);let z=G.runtime.hasPendingJob()?G.unwrapResult(await b76(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 b76(G,M,Y),A=G.unwrapResult(C);if(G.runtime.hasPendingJob())f76(G);return{returnValue:G.dump(A),consoleLogs:W.logs}}catch(F){return console.log(F),{error:BB(F),consoleLogs:W.logs}}}catch($){var K=$,H=1}finally{EX0(Z,K,H)}}var Vf1=(Q)=>new Promise((X)=>setTimeout(X,Q));var h76=y(()=>{_76();y76()});var x76=y(()=>{h76()});function qf1(Q){return Q.toLowerCase().split(/[\s_\-./]+/).filter((X)=>X.length>=2)}function zf1(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 Uf1(Q,X,Y){let J=qf1(Q);if(J.length===0)return X.slice(0,Y);return X.map((G)=>({tool:G,score:zf1(J,G)})).filter((G)=>G.score>0).sort((G,W)=>W.score-G.score).slice(0,Y).map((G)=>G.tool)}function y90(Q){return{content:[{type:"text",text:JSON.stringify(Q,null,2)}]}}function $T(Q){return{content:[{type:"text",text:JSON.stringify(Q,null,2)}],isError:!0}}function g76(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 $T({error:G.error.flatten()});let W=Uf1(G.data.query,Q.tools,G.data.limit);return y90({query:G.data.query,results:W.map((Z)=>({name:Z.name,description:Z.description,connection:Z._meta.connectionTitle})),totalAvailable:Q.tools.length})}}}function u76(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 $T({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 y90({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 Bf1(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 $T({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 Df1(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 $T({error:J.error.flatten()});let G=Object.fromEntries(Q.tools.map((Z)=>[Z.name,async($)=>Q.callTool(Z.name,$??{})])),W=await _90({...J.data,tools:G});if(W.error)return $T(W);return y90(W)}}}function m76(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)}}}function l76(Q){switch(Q){case"smart_tool_selection":return Lf1;case"code_execution":return Of1;case"passthrough":default:return Nf1}}var Nf1=(Q)=>({tools:Q.tools,callTool:(X,Y)=>Q.callTool(X,Y)}),Of1=(Q)=>m76([g76(Q),u76(Q),Df1(Q)]),Lf1=(Q)=>m76([g76(Q),u76(Q),Bf1(Q)]);var d76=y(()=>{W6();x76()});class lb{proxies;options;cache;constructor(Q,X){this.proxies=Q;this.options=X;this.cache=IW(()=>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})},$=l76(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"}})}}var p76=y(()=>{d76()});function wf1(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 c76(Q,X){return X.some((Y)=>wf1(Q,Y))}class db{proxies;options;cache;constructor(Q,X){this.proxies=Q;this.options=X;this.cache=IW(()=>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)=>!c76(K.uri,G.selectedResources))}else if(!G.selectedResources||G.selectedResources.length===0)$=[];else $=$.filter((K)=>c76(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)}}var n76=()=>{};class pb{proxies;cache;constructor(Q){this.proxies=Q;this.cache=IW(()=>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}}}var i76=()=>{};class cb{proxies;options;cache;constructor(Q,X){this.proxies=Q;this.options=X;this.cache=IW(()=>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 a76=()=>{};var r76=y(()=>{p76();n76();i76();a76()});async function Mf1(Q,X){let Y=await WT.create(Q.connections,X),J=new lb(Y,{selectionMode:Q.toolSelectionMode,strategy:Q.toolSelectionStrategy}),G=new db(Y,{selectionMode:Q.toolSelectionMode}),W=new pb(Y),Z=new cb(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 Pf1(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 Mf1(J,X)}var o76,s76;var t76=y(()=>{iv();av();s9();HZ();r76();o76=new I9;o76.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 Pf1(J,Y),Z=new j3({name:`mcp-gateway-${J.title}`,version:"1.0.0"},{capabilities:{tools:{},resources:{},prompts:{}}}),$=new C3({enableJsonResponse:Q.req.header("Accept")?.includes("application/json")??!1});return await Z.connect($),Z.server.setRequestHandler(x$,async(K)=>{return W.client.listTools()}),Z.server.setRequestHandler(YW,async(K)=>{return await W.client.callTool(K.params)}),Z.server.setRequestHandler(_$,async()=>{return W.client.listResources()}),Z.server.setRequestHandler(b$,async(K)=>{return W.client.readResource(K.params)}),Z.server.setRequestHandler(y$,async()=>{return W.client.listResourceTemplates()}),Z.server.setRequestHandler(f$,async()=>{return W.client.listPrompts()}),Z.server.setRequestHandler(h$,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)}});s76=o76});var e76,QZ6;var XZ6=y(()=>{HZ();Le();e76=new I9;e76.all("/",async(Q)=>{return Oe(Q.get("meshContext")).fetch(Q.req.raw)});QZ6=e76});function e5(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 SZ6="vercel.ai.error",Tf1,YZ6,JZ6,w6,vZ6="AI_APICallError",kZ6,Af1,GZ6,WZ6,YQ,_Z6="AI_EmptyResponseBodyError",yZ6,Ef1,ZZ6,$Z6,bZ6,fZ6="AI_InvalidArgumentError",hZ6,jf1,KZ6,HZ6,xZ6,gZ6="AI_InvalidPromptError",uZ6,Cf1,FZ6,VZ6,vF,mZ6="AI_InvalidResponseDataError",lZ6,If1,qZ6,zZ6,Fi4,dZ6="AI_JSONParseError",pZ6,Rf1,UZ6,BZ6,KT,cZ6="AI_LoadAPIKeyError",nZ6,Sf1,DZ6,NZ6,Vi4,iZ6="AI_LoadSettingError",aZ6,vf1,OZ6,LZ6,qi4,rZ6="AI_NoContentGeneratedError",oZ6,kf1,wZ6,MZ6,zi4,sZ6="AI_NoSuchModelError",tZ6,_f1,PZ6,TZ6,Ui4,eZ6="AI_TooManyEmbeddingValuesForCallError",Q$6,yf1,AZ6,EZ6,Bi4,X$6="AI_TypeValidationError",Y$6,bf1,jZ6,CZ6,QG,J$6="AI_UnsupportedFunctionalityError",G$6,ff1,IZ6,RZ6,Di4;var v4=y(()=>{Tf1=Symbol.for(SZ6),w6=class Q extends(JZ6=Error,YZ6=Tf1,JZ6){constructor({name:X,message:Y,cause:J}){super(Y);this[YZ6]=!0,this.name=X,this.cause=J}static isInstance(X){return Q.hasMarker(X,SZ6)}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}},kZ6=`vercel.ai.error.${vZ6}`,Af1=Symbol.for(kZ6),YQ=class extends(WZ6=w6,GZ6=Af1,WZ6){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:vZ6,message:Q,cause:Z});this[GZ6]=!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 w6.hasMarker(Q,kZ6)}},yZ6=`vercel.ai.error.${_Z6}`,Ef1=Symbol.for(yZ6),bZ6=class extends($Z6=w6,ZZ6=Ef1,$Z6){constructor({message:Q="Empty response body"}={}){super({name:_Z6,message:Q});this[ZZ6]=!0}static isInstance(Q){return w6.hasMarker(Q,yZ6)}};hZ6=`vercel.ai.error.${fZ6}`,jf1=Symbol.for(hZ6),xZ6=class extends(HZ6=w6,KZ6=jf1,HZ6){constructor({message:Q,cause:X,argument:Y}){super({name:fZ6,message:Q,cause:X});this[KZ6]=!0,this.argument=Y}static isInstance(Q){return w6.hasMarker(Q,hZ6)}},uZ6=`vercel.ai.error.${gZ6}`,Cf1=Symbol.for(uZ6),vF=class extends(VZ6=w6,FZ6=Cf1,VZ6){constructor({prompt:Q,message:X,cause:Y}){super({name:gZ6,message:`Invalid prompt: ${X}`,cause:Y});this[FZ6]=!0,this.prompt=Q}static isInstance(Q){return w6.hasMarker(Q,uZ6)}},lZ6=`vercel.ai.error.${mZ6}`,If1=Symbol.for(lZ6),Fi4=class extends(zZ6=w6,qZ6=If1,zZ6){constructor({data:Q,message:X=`Invalid response data: ${JSON.stringify(Q)}.`}){super({name:mZ6,message:X});this[qZ6]=!0,this.data=Q}static isInstance(Q){return w6.hasMarker(Q,lZ6)}},pZ6=`vercel.ai.error.${dZ6}`,Rf1=Symbol.for(pZ6),KT=class extends(BZ6=w6,UZ6=Rf1,BZ6){constructor({text:Q,cause:X}){super({name:dZ6,message:`JSON parsing failed: Text: ${Q}.
1057
1057
  Error message: ${e5(X)}`,cause:X});this[UZ6]=!0,this.text=Q}static isInstance(Q){return w6.hasMarker(Q,pZ6)}},nZ6=`vercel.ai.error.${cZ6}`,Sf1=Symbol.for(nZ6),Vi4=class extends(NZ6=w6,DZ6=Sf1,NZ6){constructor({message:Q}){super({name:cZ6,message:Q});this[DZ6]=!0}static isInstance(Q){return w6.hasMarker(Q,nZ6)}},aZ6=`vercel.ai.error.${iZ6}`,vf1=Symbol.for(aZ6),qi4=class extends(LZ6=w6,OZ6=vf1,LZ6){constructor({message:Q}){super({name:iZ6,message:Q});this[OZ6]=!0}static isInstance(Q){return w6.hasMarker(Q,aZ6)}},oZ6=`vercel.ai.error.${rZ6}`,kf1=Symbol.for(oZ6),zi4=class extends(MZ6=w6,wZ6=kf1,MZ6){constructor({message:Q="No content generated."}={}){super({name:rZ6,message:Q});this[wZ6]=!0}static isInstance(Q){return w6.hasMarker(Q,oZ6)}},tZ6=`vercel.ai.error.${sZ6}`,_f1=Symbol.for(tZ6),Ui4=class extends(TZ6=w6,PZ6=_f1,TZ6){constructor({errorName:Q=sZ6,modelId:X,modelType:Y,message:J=`No such ${Y}: ${X}`}){super({name:Q,message:J});this[PZ6]=!0,this.modelId=X,this.modelType=Y}static isInstance(Q){return w6.hasMarker(Q,tZ6)}},Q$6=`vercel.ai.error.${eZ6}`,yf1=Symbol.for(Q$6),Bi4=class extends(EZ6=w6,AZ6=yf1,EZ6){constructor(Q){super({name:eZ6,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[AZ6]=!0,this.provider=Q.provider,this.modelId=Q.modelId,this.maxEmbeddingsPerCall=Q.maxEmbeddingsPerCall,this.values=Q.values}static isInstance(Q){return w6.hasMarker(Q,Q$6)}},Y$6=`vercel.ai.error.${X$6}`,bf1=Symbol.for(Y$6),QG=class Q extends(CZ6=w6,jZ6=bf1,CZ6){constructor({value:X,cause:Y}){super({name:X$6,message:`Type validation failed: Value: ${JSON.stringify(X)}.
1058
1058
  Error message: ${e5(Y)}`,cause:Y});this[jZ6]=!0,this.value=X}static isInstance(X){return w6.hasMarker(X,Y$6)}static wrap({value:X,cause:Y}){return Q.isInstance(Y)&&Y.value===X?Y:new Q({value:X,cause:Y})}},G$6=`vercel.ai.error.${J$6}`,ff1=Symbol.for(G$6),Di4=class extends(RZ6=w6,IZ6=ff1,RZ6){constructor({functionality:Q,message:X=`'${Q}' functionality not supported.`}){super({name:J$6,message:X});this[IZ6]=!0,this.functionality=Q}static isInstance(Q){return w6.hasMarker(Q,G$6)}}});var W$6=()=>{};function _F(...Q){return Q.reduce((X,Y)=>({...X,...Y!=null?Y:{}}),{})}async function q$6(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(Z$6());return}let W=setTimeout(()=>{Z(),J()},Q),Z=()=>{clearTimeout(W),Y==null||Y.removeEventListener("abort",$)},$=()=>{Z(),G(Z$6())};Y==null||Y.addEventListener("abort",$)})}function Z$6(){return new DOMException("Delay was aborted","AbortError")}function HT(Q){return Object.fromEntries([...Q.headers])}function NB(Q){let X=Q.replace(/-/g,"+").replace(/_/g,"/"),Y=xf1(X);return Uint8Array.from(Y,(J)=>J.codePointAt(0))}function bF(Q){let X="";for(let Y=0;Y<Q.length;Y++)X+=String.fromCodePoint(Q[Y]);return hf1(X)}function FT(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 qZ(Q){return(Q instanceof Error||Q instanceof DOMException)&&(Q.name==="AbortError"||Q.name==="ResponseAborted"||Q.name==="TimeoutError")}function B$6({error:Q,url:X,requestBodyValues:Y}){if(qZ(Q))return Q;if(Q instanceof TypeError&&mf1.includes(Q.message.toLowerCase())){let J=Q.cause;if(J!=null)return new YQ({message:`Cannot connect to API: ${J.message}`,cause:J,url:X,requestBodyValues:Y,isRetryable:!0})}return Q}function ib(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 lf1(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 jK(Q,...X){let Y=new Headers(lf1(Q)),J=Y.get("user-agent")||"";return Y.set("user-agent",[J,...X].filter(Boolean).join(" ")),Object.fromEntries(Y.entries())}function N$6(Q){return Q!=null}function O$6({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 VT({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}function H$6(Q){let X=JSON.parse(Q);if(X===null||typeof X!=="object")return X;if(pf1.test(Q)===!1&&cf1.test(Q)===!1)return X;return nf1(X)}function nf1(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 L$6(Q){let{stackTraceLimit:X}=Error;try{Error.stackTraceLimit=0}catch(Y){return H$6(Q)}try{return H$6(Q)}finally{Error.stackTraceLimit=X}}function w$6(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]=kF(Y[J])}if(Q.items!=null)Q.items=Array.isArray(Q.items)?Q.items.map(kF):kF(Q.items);if(Q.anyOf!=null)Q.anyOf=Q.anyOf.map(kF);if(Q.allOf!=null)Q.allOf=Q.allOf.map(kF);if(Q.oneOf!=null)Q.oneOf=Q.oneOf.map(kF);let{definitions:X}=Q;if(X!=null)for(let Y of Object.keys(X))X[Y]=kF(X[Y]);return Q}function kF(Q){if(typeof Q==="boolean")return Q;return w$6(Q)}function QJ(){return{}}function rf1(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=x4(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 of1(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 sf1(){return{type:"boolean"}}function M$6(Q,X){return x4(Q.type._def,X)}function P$6(Q,X,Y){let J=Y!=null?Y:X.dateStrategy;if(Array.isArray(J))return{anyOf:J.map((G,W)=>P$6(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 ef1(Q)}}function Qh1(Q,X){return{...x4(Q.innerType._def,X),default:Q.defaultValue()}}function Xh1(Q,X){return X.effectStrategy==="input"?x4(Q.schema._def,X):QJ()}function Yh1(Q){return{type:"string",enum:Array.from(Q.values)}}function Gh1(Q,X){let Y=[x4(Q.left._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),x4(Q.right._def,{...X,currentPath:[...X.currentPath,"allOf","1"]})].filter((G)=>!!G),J=[];return Y.forEach((G)=>{if(Jh1(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 Wh1(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}}function T$6(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":YG(Y,"email",J.message,X);break;case"format:idn-email":YG(Y,"idn-email",J.message,X);break;case"pattern:zod":fX(Y,XG.email,J.message,X);break}break;case"url":YG(Y,"uri",J.message,X);break;case"uuid":YG(Y,"uuid",J.message,X);break;case"regex":fX(Y,J.regex,J.message,X);break;case"cuid":fX(Y,XG.cuid,J.message,X);break;case"cuid2":fX(Y,XG.cuid2,J.message,X);break;case"startsWith":fX(Y,RegExp(`^${f90(J.value,X)}`),J.message,X);break;case"endsWith":fX(Y,RegExp(`${f90(J.value,X)}$`),J.message,X);break;case"datetime":YG(Y,"date-time",J.message,X);break;case"date":YG(Y,"date",J.message,X);break;case"time":YG(Y,"time",J.message,X);break;case"duration":YG(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":{fX(Y,RegExp(f90(J.value,X)),J.message,X);break}case"ip":{if(J.version!=="v6")YG(Y,"ipv4",J.message,X);if(J.version!=="v4")YG(Y,"ipv6",J.message,X);break}case"base64url":fX(Y,XG.base64url,J.message,X);break;case"jwt":fX(Y,XG.jwt,J.message,X);break;case"cidr":{if(J.version!=="v6")fX(Y,XG.ipv4Cidr,J.message,X);if(J.version!=="v4")fX(Y,XG.ipv6Cidr,J.message,X);break}case"emoji":fX(Y,XG.emoji(),J.message,X);break;case"ulid":{fX(Y,XG.ulid,J.message,X);break}case"base64":{switch(X.base64Strategy){case"format:binary":{YG(Y,"binary",J.message,X);break}case"contentEncoding:base64":{Y.contentEncoding="base64";break}case"pattern:zod":{fX(Y,XG.base64,J.message,X);break}}break}case"nanoid":fX(Y,XG.nanoid,J.message,X);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return Y}function f90(Q,X){return X.patternStrategy==="escape"?$h1(Q):Q}function $h1(Q){let X="";for(let Y=0;Y<Q.length;Y++){if(!Zh1.has(Q[Y]))X+="\\";X+=Q[Y]}return X}function YG(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 fX(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:V$6(X,J),...Y&&J.errorMessages&&{errorMessage:{pattern:Y}}})}else Q.pattern=V$6(X,J)}function V$6(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
1059
1059
  ]))`;continue}else if(G[H]==="$"){W+=`($|(?=[\r