@decocms/mesh 1.0.0-alpha.36 → 1.0.0-alpha.37

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 (144) hide show
  1. package/dist/client/assets/{AlertCircle-BTyO1bIr.js → AlertCircle-FgA4OE_Y.js} +1 -1
  2. package/dist/client/assets/{ArrowLeft-7k17XFQG.js → ArrowLeft-DZ8Qhlyz.js} +1 -1
  3. package/dist/client/assets/{CheckCircle-C4Oiadwm.js → CheckCircle-D9-mPjW-.js} +1 -1
  4. package/dist/client/assets/{ChevronDown-BS79qwaj.js → ChevronDown-CRpCA4eQ.js} +1 -1
  5. package/dist/client/assets/{Clock-BOH6uFau.js → Clock-9Ud3hYi_.js} +1 -1
  6. package/dist/client/assets/{Copy01-CxnoIdIZ.js → Copy01-DGZy8_Wa.js} +1 -1
  7. package/dist/client/assets/{CpuChip02-D3wiCoBz.js → CpuChip02-9xkDTOQm.js} +1 -1
  8. package/dist/client/assets/{DotsVertical-CwJThHEX.js → DotsVertical-7BehxNIr.js} +1 -1
  9. package/dist/client/assets/{File06-BRYCQPQQ.js → File06-JZRzMAbM.js} +1 -1
  10. package/dist/client/assets/Grid01-CKvZ5Bgj.js +1 -0
  11. package/dist/client/assets/{Inbox01-BNVw88kh.js → Inbox01-Q7OGuD8_.js} +1 -1
  12. package/dist/client/assets/{InfoCircle-BE7jSjao.js → InfoCircle-ZmqIswrk.js} +1 -1
  13. package/dist/client/assets/{Key01-CV-PJgLz.js → Key01-Cc974JWF.js} +1 -1
  14. package/dist/client/assets/{LinkExternal01-Cw55I4YI.js → LinkExternal01-0ybSN01c.js} +1 -1
  15. package/dist/client/assets/{Loading01-BhFuCyVl.js → Loading01-BpGj_YCN.js} +1 -1
  16. package/dist/client/assets/{Plus-jUkR_Ter.js → Plus-BS5hPXY3.js} +1 -1
  17. package/dist/client/assets/{SearchMd-Cl2YCw8E.js → SearchMd-BbbPnMSd.js} +1 -1
  18. package/dist/client/assets/{Trash01-BWLyg5Oe.js → Trash01-DtIQgapG.js} +1 -1
  19. package/dist/client/assets/{Upload01-CS5lQvA-.js → Upload01-Zx3GirGx.js} +1 -1
  20. package/dist/client/assets/{X-CUPD619d.js → X-CYjj99XI.js} +1 -1
  21. package/dist/client/assets/{ChevronRight-CUy2lZv_.js → XClose-BDRe0Ozk.js} +1 -1
  22. package/dist/client/assets/{alert-dialog-BAf5ctm5.js → alert-dialog-Bj94Mg43.js} +3 -3
  23. package/dist/client/assets/auth-CbkV4JhC.js +1 -0
  24. package/dist/client/assets/{auth-catchall-wKD825hs.js → auth-catchall-pG3jhayZ.js} +1 -1
  25. package/dist/client/assets/avatar-DQuAu06W.js +1 -0
  26. package/dist/client/assets/badge-B6NR5xty.js +1 -0
  27. package/dist/client/assets/button-WA21TIge.js +1 -0
  28. package/dist/client/assets/{card-sfFKqZf-.js → card-fnco2BKy.js} +1 -1
  29. package/dist/client/assets/{checkbox-DgXbQ8Ox.js → checkbox-Bq4Db1eq.js} +1 -1
  30. package/dist/client/assets/collection-detail-C45JavW1.js +1 -0
  31. package/dist/client/assets/collection-display-button-CJgVNUjG.js +1 -0
  32. package/dist/client/assets/{collection-header-CHbECWq3.js → collection-header-COdYt0yo.js} +1 -1
  33. package/dist/client/assets/{collection-page-CDAnXQTM.js → collection-page-IZEjeZDJ.js} +1 -1
  34. package/dist/client/assets/collection-search-Dh2zcE6Z.js +1 -0
  35. package/dist/client/assets/collection-table-wrapper-DOiiwQBc.js +1 -0
  36. package/dist/client/assets/{connection-card-DDubRXhM.js → connection-card-P2DYTKtD.js} +1 -1
  37. package/dist/client/assets/connection-detail-2kY4jzvr.js +1 -0
  38. package/dist/client/assets/connections-CfReLX9R.js +1 -0
  39. package/dist/client/assets/{core-BQb1IbZ1.js → core-Bsa-CClQ.js} +1 -1
  40. package/dist/client/assets/create-organization-dialog-DjEf_yPL.js +1 -0
  41. package/dist/client/assets/deco-chat-skeleton-YKru_-uq.js +124 -0
  42. package/dist/client/assets/dialog-CzRcLMrO.js +1 -0
  43. package/dist/client/assets/dropdown-menu-lNp795nL.js +1 -0
  44. package/dist/client/assets/{error-boundary-CzZS2hu3.js → error-boundary-D10vdRO6.js} +1 -1
  45. package/dist/client/assets/{extract-connection-data-DG29RoY7.js → extract-connection-data-CnaW3oDd.js} +1 -1
  46. package/dist/client/assets/form-BUVsmabM.js +1 -0
  47. package/dist/client/assets/gateway-detail-DxVWCOGY.js +1 -0
  48. package/dist/client/assets/gateways-BDUTpLoJ.js +1 -0
  49. package/dist/client/assets/home-DcAStJkG.js +1 -0
  50. package/dist/client/assets/{index-Q4i_xzP8.js → index-B3MiP_oE.js} +1 -1
  51. package/dist/client/assets/{index-aPgTBlHu.js → index-BWMTgSpJ.js} +21 -21
  52. package/dist/client/assets/index-DXIf5jrv.js +1 -0
  53. package/dist/client/assets/index-DiIfEFEx.js +1 -0
  54. package/dist/client/assets/index-LtFisB9d.css +1 -0
  55. package/dist/client/assets/{input-DwDBCg8s.js → input-C8ckt9pD.js} +1 -1
  56. package/dist/client/assets/json-DgiEbznW.js +1 -0
  57. package/dist/client/assets/json-syntax-highlighter-DqTOcqS4.js +2 -0
  58. package/dist/client/assets/{layout-C05bVaci.js → layout-Ddw5vi1_.js} +1 -1
  59. package/dist/client/assets/{lazy-highlighter-nxpk4TOI.js → lazy-highlighter-D0ldRF_z.js} +1 -1
  60. package/dist/client/assets/localstorage-keys-C__QKrnP.js +1 -0
  61. package/dist/client/assets/{login-ilKhlZxM.js → login-Bfuntl4G.js} +1 -1
  62. package/dist/client/assets/{mcp-oauth-afk0hDd7.js → mcp-oauth-BeGFsv5e.js} +1 -1
  63. package/dist/client/assets/members-DsJnPzlW.js +3 -0
  64. package/dist/client/assets/monitoring-C4ZUhICh.js +1 -0
  65. package/dist/client/assets/{oauth-callback-CfhyzjS-.js → oauth-callback-rQDuS0Y4.js} +1 -1
  66. package/dist/client/assets/{page-CxqajJt6.js → page-CEwSU962.js} +1 -1
  67. package/dist/client/assets/popover-BSAaObMv.js +1 -0
  68. package/dist/client/assets/prism-light-BGWrXuVI.js +1 -0
  69. package/dist/client/assets/resource-tabs-TaJMxN6_.js +1 -0
  70. package/dist/client/assets/schema-B3tkq8IT.js +1 -0
  71. package/dist/client/assets/select-DQatPXKJ.js +1 -0
  72. package/dist/client/assets/settings-DIHeOoHX.js +1 -0
  73. package/dist/client/assets/shell-layout-D1irgz1e.js +1 -0
  74. package/dist/client/assets/spinner-DD8NRDSP.js +1 -0
  75. package/dist/client/assets/store-BlitdGFv.js +1 -0
  76. package/dist/client/assets/store-app-detail-C3gtVQGX.js +1 -0
  77. package/dist/client/assets/switch-BLTM21B0.js +1 -0
  78. package/dist/client/assets/{textarea-BmlKbSgg.js → textarea-OUcFAiZD.js} +1 -1
  79. package/dist/client/assets/tooltip-Dy-DsVOX.js +1 -0
  80. package/dist/client/assets/types-Be8keXIM.js +44 -0
  81. package/dist/client/assets/use-binding-pAqGO8UI.js +5 -0
  82. package/dist/client/assets/{use-connection-dLBcN4uO.js → use-connection-Lp9rwnx7.js} +2 -2
  83. package/dist/client/assets/use-gateway-C0GNG4JP.js +1 -0
  84. package/dist/client/assets/{use-list-state-O_LscsV3.js → use-list-state-BxKaK11n.js} +1 -1
  85. package/dist/client/assets/use-mcp-ClY7_5dz.js +1 -0
  86. package/dist/client/assets/use-members-4V3USNhz.js +1 -0
  87. package/dist/client/assets/{use-mobile-BdgLaCND.js → use-mobile-k1X2THZ9.js} +1 -1
  88. package/dist/client/assets/use-organization-settings-CMytLZst.js +1 -0
  89. package/dist/client/assets/use-tool-call-z8Rn6Gss.js +1 -0
  90. package/dist/client/assets/useQuery-CdGzN_Sp.js +1 -0
  91. package/dist/client/assets/utils-CvrJmBA1.js +1 -0
  92. package/dist/client/assets/{well-known-mcp-FQpRYY-w.js → well-known-mcp-CjKrCZkD.js} +1 -1
  93. package/dist/client/index.html +2 -2
  94. package/dist/server/cli.js +2 -2
  95. package/dist/server/migrate.js +72 -72
  96. package/dist/server/server.js +2 -2
  97. package/package.json +1 -1
  98. package/dist/client/assets/Play-DGLj3ZQ4.js +0 -1
  99. package/dist/client/assets/auth-D6xZlTbm.js +0 -1
  100. package/dist/client/assets/avatar-DPsLS6yn.js +0 -1
  101. package/dist/client/assets/badge-CpQrddlN.js +0 -1
  102. package/dist/client/assets/button-BIb1hBlM.js +0 -1
  103. package/dist/client/assets/collection-detail-kKrf7EiH.js +0 -1
  104. package/dist/client/assets/collection-display-button-BND5mm33.js +0 -1
  105. package/dist/client/assets/collection-search-Cvpn1oo5.js +0 -1
  106. package/dist/client/assets/collection-table-wrapper-LOaVebVl.js +0 -1
  107. package/dist/client/assets/connection-detail-BLnHf05r.js +0 -1
  108. package/dist/client/assets/connections-Dl3T9MjG.js +0 -1
  109. package/dist/client/assets/create-organization-dialog-DdWxBHuT.js +0 -1
  110. package/dist/client/assets/dialog-BUaIGJyb.js +0 -1
  111. package/dist/client/assets/dropdown-menu-0UYvqG1t.js +0 -1
  112. package/dist/client/assets/form-Cn0qh3yi.js +0 -1
  113. package/dist/client/assets/gateway-detail-ChvGwEiM.js +0 -1
  114. package/dist/client/assets/gateways-Dkkzx42w.js +0 -1
  115. package/dist/client/assets/home-u-36hLa3.js +0 -1
  116. package/dist/client/assets/index-BW5Ye25a.js +0 -1
  117. package/dist/client/assets/index-DJi6eJya.css +0 -1
  118. package/dist/client/assets/index-DekEYGbc.js +0 -1
  119. package/dist/client/assets/json-DwH08lZ1.js +0 -1
  120. package/dist/client/assets/localstorage-keys-BB92Mxjt.js +0 -1
  121. package/dist/client/assets/members-BLdNGmNL.js +0 -3
  122. package/dist/client/assets/monitoring-VVux_71k.js +0 -1
  123. package/dist/client/assets/popover-DG5g1uWj.js +0 -1
  124. package/dist/client/assets/prism-light-whovo9oO.js +0 -1
  125. package/dist/client/assets/resource-tabs-B2DkuD02.js +0 -1
  126. package/dist/client/assets/schema-DHyBqRM4.js +0 -1
  127. package/dist/client/assets/select-s-ULrx4h.js +0 -1
  128. package/dist/client/assets/settings-CBEAfPMj.js +0 -1
  129. package/dist/client/assets/shell-layout-Bcr5PqYt.js +0 -124
  130. package/dist/client/assets/spinner-ce6h3T1x.js +0 -1
  131. package/dist/client/assets/store-app-detail-B4MOAxlk.js +0 -1
  132. package/dist/client/assets/store-l32Dpsd2.js +0 -1
  133. package/dist/client/assets/switch-CoEnErLB.js +0 -1
  134. package/dist/client/assets/tool-set-selector-CCCV8X5h.js +0 -1
  135. package/dist/client/assets/tooltip-dlGCJiom.js +0 -1
  136. package/dist/client/assets/types-BA0RpCas.js +0 -45
  137. package/dist/client/assets/use-binding-DvLo4NgS.js +0 -5
  138. package/dist/client/assets/use-gateway-IzLpYPB0.js +0 -1
  139. package/dist/client/assets/use-mcp-DGdnUGyN.js +0 -1
  140. package/dist/client/assets/use-members-109akJr-.js +0 -1
  141. package/dist/client/assets/use-organization-settings-Bi59aqvp.js +0 -1
  142. package/dist/client/assets/use-tool-call-Bi8tuPr0.js +0 -1
  143. package/dist/client/assets/useQuery-DnWeHrBn.js +0 -1
  144. package/dist/client/assets/utils-BDGz_y2o.js +0 -1
@@ -286,7 +286,7 @@ return fn.apply(this, arguments)
286
286
  `;for(let Y of Object.keys(Q))if(Y!=="link")X+=Y+": "+Q[Y]+`\r
287
287
  `;X+=`\r
288
288
  `,this._writeRaw(X,"ascii",J)}_implicitHeader(){this.writeHead(this.statusCode)}writeHead(Q,J,X){if(this._header)throw new RW("write");let G=Q;if(Q|=0,Q<100||Q>999)throw new J80(G);if(typeof J==="string")this.statusMessage=J;else this.statusMessage||=WX1[Q]||"unknown",X??=J;this.statusCode=Q;let Y;if(this[M8]){let K;if(Array.isArray(X)){if(X.length%2!==0)throw new oK("headers",X);for(let Z=0;Z<X.length;Z+=2)K=X[Z+0],this.removeHeader(String(K));for(let Z=0;Z<X.length;Z+=2)if(K=X[Z],K)this.appendHeader(String(K),X[Z+1])}else if(X){let Z=Object.keys(X);for(let H=0;H<Z.length;H++)if(K=Z[H],K)this.setHeader(K,X[K])}Y=this[M8]}else Y=X;if(HI4(this.statusMessage))throw new KF("statusMessage");let W=`HTTP/1.1 ${Q} ${this.statusMessage}\r
289
- `;if(Q===204||Q===304||Q>=100&&Q<=199)this._hasBody=!1;if(this._expect_continue&&!this._sent100)this.shouldKeepAlive=!1;let $=Y&&!Array.isArray(Y)?Y:Y;return this._storeHeader(W,$??null),this}writeHeader=this.writeHead;fetchResponse;_toFetchResponse(Q,J,X,G,Y){let W=new Headers;for(let[Z,H]of X)W.append(Z,H);let $=this,K=this._hasBody?new ReadableStream({start(Z){for(let H of G)Z.enqueue(H);if(Y)Z.close();else $.on("finish",()=>{Y=!0,Z.close()}),$.on("_dataWritten",(H)=>{if(Y)return;let F=$.dataFromDataWrittenEvent(H);Z.enqueue(F)})}}):null;if(K!=null&&typeof FixedLengthStream<"u"){let Z=parseInt(W.get("content-length")??"",10);if(Z>=0)K=K.pipeThrough(new FixedLengthStream(Z))}return new Response(K,{status:Q,statusText:J,headers:W})}}});var KX1=s(()=>{Z80();B80();$X1()});var VF;var O_=s(()=>{nJ1();KX1();VF=class VF extends s60{constructor(Q){super({...Q,sessionIdGenerator:Q?.sessionIdGenerator})}async handleMessage(Q){let{req:J,res:X}=O80(Q);return super.handleRequest(J,X,await Q.json().catch(()=>null)),D80(X)}}});var TP=(...Q)=>{return function(X,G){let Y=(W)=>{let $=Q[W];if(!$)return G();return $(X,()=>Y(W+1))};return Y(0)}};class ZX1{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?TP(...this.callToolMiddlewares):null,J=()=>{let X=new YF({name:this.config.name,version:this.config.version},{capabilities:this.config.capabilities});for(let G of this.tools){let Y=async(Z)=>{try{let H=await G.handler(Z);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(Z)=>{let H={method:"tools/call",params:{name:G.name,arguments:Z}};return await Q(H,()=>Y(Z))}:Y,$="shape"in G.inputSchema?G.inputSchema.shape:y10.object({}).shape,K=G.outputSchema&&"shape"in G.outputSchema?G.outputSchema.shape:y10.object({}).shape;X.registerTool(G.name,{annotations:G.annotations,description:G.description??"",inputSchema:$,outputSchema:K},W)}return X};return{callStreamableTool:async(X,G)=>{let Y=this.tools.find(($)=>$.name===X);if(!Y)throw Error(`Tool ${X} not found`);let W=await Y.handler(G);if(!(W instanceof Response))throw Error(`Tool ${X} returned a non-response`);return W},client:{listTools:async()=>{return{tools:this.tools.map((X)=>({name:X.name,description:X.description??"",inputSchema:bY(X.inputSchema),outputSchema:X.outputSchema?bY(X.outputSchema):void 0}))}},callTool:async(X)=>{let G=this.tools.find((Y)=>Y.name===X.name);if(!G)return{content:[{type:"text",text:"Tool not found"}]};try{let Y=await G?.handler(X.arguments??{});return{content:[{type:"text",text:JSON.stringify(Y)}],structuredContent:Y}}catch(Y){return{content:[{type:"text",text:`Error: ${Y.message}`}]}}}},fetch:async(X)=>{let G=new VF({enableJsonResponse:X.headers.get("Accept")?.includes("application/json")??!1});return await J().connect(G),await G.handleMessage(X)}}}}function HX1(Q){return new ZX1(Q)}var FX1=s(()=>{nk();w4();zP();O_()});function j1(Q){return{...Q,execute:async(J,X)=>{let G=Date.now();return await X.tracer.startActiveSpan(`tool.${Q.name}`,{attributes:{"tool.name":Q.name,"organization.id":X.organization?.id??"system","user.id":X.auth.user?.id??X.auth.apiKey?.userId??"anonymous"}},async(Y)=>{try{X.toolName=Q.name,X.access.setToolName?.(Q.name);let W=await Q.handler(J,X),$=Date.now()-G;return X.meter.createHistogram("tool.execution.duration",{description:"Duration of tool executions in milliseconds",unit:"ms"}).record($,{"tool.name":Q.name,"organization.id":X.organization?.id??"system",status:"success"}),X.meter.createCounter("tool.execution.count",{description:"Number of tool executions"}).add(1,{"tool.name":Q.name,status:"success"}),Y.setStatus({code:L80.SpanStatusCode.OK}),W}catch(W){throw X.meter.createCounter("tool.execution.errors",{description:"Number of tool execution errors"}).add(1,{"tool.name":Q.name,"error.type":W.constructor.name}),Y.setStatus({code:L80.SpanStatusCode.ERROR,message:W.message}),Y.recordException(W),W}finally{Y.end()}})}}}var L80;var x4=s(()=>{L80=p4(V1(),1)});function j4(Q){if(!Q.organization)throw Error("This operation requires organization scope");return Q.organization}function QJ(Q){return Q.auth.user?.id??Q.auth.apiKey?.userId}function FI4(Q){return!!(Q.auth.user||Q.auth.apiKey)}function u1(Q){if(!FI4(Q))throw Error("Authentication required")}var D_,qX1,VX1,zX1,UX1,NX1,BX1,OX1,DX1,LX1;var _U=s(()=>{w4();D_=L.record(L.array(L.string())),qX1=L.object({id:L.string().describe("Unique identifier for the API key"),name:L.string().describe("Human-readable name for the API key"),userId:L.string().describe("ID of the user who owns this API key"),permissions:D_.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:L.union([L.string(),L.date()]).nullable().optional().describe("Expiration date of the API key"),createdAt:L.union([L.string(),L.date()]).describe("When the API key was created")}),VX1=L.object({name:L.string().min(1).max(64).describe("Human-readable name for the API key"),permissions:D_.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:L.number().positive().optional().describe("Expiration time in seconds. If not provided, key never expires."),metadata:L.record(L.unknown()).optional().describe("Additional metadata to store with the API key")}),zX1=L.object({id:L.string().describe("Unique identifier for the API key"),name:L.string().describe("Human-readable name for the API key"),key:L.string().describe("The actual API key value. STORE THIS SECURELY - it will not be shown again!"),permissions:D_.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:L.union([L.string(),L.date()]).nullable().optional().describe("Expiration date of the API key"),createdAt:L.union([L.string(),L.date()]).describe("When the API key was created")}),UX1=L.object({}),NX1=L.object({items:L.array(qX1).describe("List of API keys (without key values)")}),BX1=L.object({keyId:L.string().describe("ID of the API key to update"),name:L.string().min(1).max(64).optional().describe("New name for the API key"),permissions:D_.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:L.record(L.unknown()).optional().describe("New metadata. Replaces existing metadata.")}),OX1=L.object({item:qX1.describe("The updated API key (without key value)")}),DX1=L.object({keyId:L.string().describe("ID of the API key to delete")}),LX1=L.object({success:L.boolean().describe("Whether the deletion was successful"),keyId:L.string().describe("ID of the deleted API key")})});var w80;var wX1=s(()=>{x4();_U();w80=j1({name:"API_KEY_CREATE",description:"Create a new API key with specified permissions. The key value is only returned once - store it securely!",inputSchema:VX1,outputSchema:zX1,handler:async(Q,J)=>{u1(J),await J.access.check();let X=await J.boundAuth.apiKey.create({name:Q.name,permissions:Q.permissions,expiresIn:Q.expiresIn,metadata:{...Q.metadata,organization:J.organization}});return{id:X.id,name:X.name??Q.name,key:X.key,permissions:X.permissions??{},expiresAt:X.expiresAt??null,createdAt:X.createdAt}}})});var P80;var PX1=s(()=>{x4();_U();P80=j1({name:"API_KEY_DELETE",description:"Delete an API key. This instantly revokes the key - it can no longer be used for authentication.",inputSchema:DX1,outputSchema:LX1,handler:async(Q,J)=>{if(u1(J),await J.access.check(),!QJ(J))throw Error("User ID required to delete API key");let Y=(await J.boundAuth.apiKey.list())?.find((Z)=>Z.id===Q.keyId);if(!Y)throw Error("API key not found");let $=Y.metadata?.organization?.id,K=J.organization?.id;if($!==K)throw Error("Cannot delete API key from another organization");return await J.boundAuth.apiKey.delete(Q.keyId),{success:!0,keyId:Q.keyId}}})});var M80;var MX1=s(()=>{x4();_U();M80=j1({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:UX1,outputSchema:NX1,handler:async(Q,J)=>{u1(J),await J.access.check();let X=await J.boundAuth.apiKey.list(),G=J.organization?.id;return{items:(X??[]).filter((W)=>{return W.metadata?.organization?.id===G}).map((W)=>({id:W.id,name:W.name??"Unnamed Key",userId:W.userId,permissions:W.permissions??{},expiresAt:W.expiresAt??null,createdAt:W.createdAt}))}}})});var T80;var TX1=s(()=>{x4();_U();T80=j1({name:"API_KEY_UPDATE",description:"Update an existing API key's name, permissions, or metadata. Note: Key value cannot be changed or retrieved.",inputSchema:BX1,outputSchema:OX1,handler:async(Q,J)=>{if(u1(J),await J.access.check(),!QJ(J))throw Error("User ID required to update API key");let Y=(await J.boundAuth.apiKey.list())?.find((H)=>H.id===Q.keyId);if(!Y)throw Error(`API key not found: ${Q.keyId}`);let $=Y.metadata?.organization?.id,K=J.organization?.id;if($!==K)throw Error("Cannot update API key from another organization");let Z=await J.boundAuth.apiKey.update({keyId:Q.keyId,name:Q.name,permissions:Q.permissions,metadata:{...Q.metadata,organization:J.organization}});if(!Z)throw Error(`Failed to update API key: ${Q.keyId}`);return{item:{id:Z.id,name:Z.name??Q.name??"Unnamed Key",userId:Z.userId,permissions:Z.permissions??{},expiresAt:Z.expiresAt??null,createdAt:Z.createdAt}}}})});var AX1=s(()=>{wX1();PX1();MX1();TX1();_U()});var VI4,zI4,mX,EX1,jX1;var yU=s(()=>{w4();VI4=L.object({authorizationEndpoint:L.string().url(),tokenEndpoint:L.string().url(),introspectionEndpoint:L.string().url().optional(),clientId:L.string(),clientSecret:L.string().optional(),scopes:L.array(L.string()),grantType:L.enum(["authorization_code","client_credentials"])}),zI4=L.object({name:L.string(),description:L.string().optional(),inputSchema:L.record(L.unknown()),outputSchema:L.record(L.unknown()).optional()}),mX=L.object({id:L.string().describe("Unique identifier for the connection"),title:L.string().describe("Human-readable name for the connection"),created_at:L.string().describe("When the connection was created"),updated_at:L.string().describe("When the connection was last updated"),created_by:L.string().describe("User ID who created the connection"),updated_by:L.string().optional().describe("User ID who last updated the connection"),organization_id:L.string().describe("Organization ID this connection belongs to"),description:L.string().nullable().describe("Description of the connection"),icon:L.string().nullable().describe("Icon URL for the connection"),app_name:L.string().nullable().describe("Associated app name"),app_id:L.string().nullable().describe("Associated app ID"),connection_type:L.enum(["HTTP","SSE","Websocket"]).describe("Type of connection"),connection_url:L.string().describe("URL for the connection"),connection_token:L.string().nullable().describe("Authentication token"),connection_headers:L.record(L.string(),L.string()).nullable().describe("Custom headers"),oauth_config:VI4.nullable().describe("OAuth configuration"),configuration_state:L.record(L.unknown()).nullable().describe("Configuration state (decrypted)"),configuration_scopes:L.array(L.string()).nullable().optional().describe("Configuration scopes"),metadata:L.record(L.unknown()).nullable().describe("Additional metadata (includes repository info)"),tools:L.array(zI4).nullable().describe("Discovered tools from MCP"),bindings:L.array(L.string()).nullable().describe("Detected bindings"),status:L.enum(["active","inactive","error"]).describe("Current status")}),EX1=mX.omit({created_at:!0,updated_at:!0,created_by:!0,updated_by:!0,organization_id:!0,tools:!0,bindings:!0,status:!0}).partial({id:!0,description:!0,icon:!0,app_name:!0,app_id:!0,connection_token:!0,connection_headers:!0,oauth_config:!0,configuration_state:!0,configuration_scopes:!0,metadata:!0}),jX1=mX.partial()});var UI4,NI4,A80;var IX1=s(()=>{pH();w4();x4();hk();yU();UI4=L.object({data:EX1.describe("Data for the new connection (id is auto-generated if not provided)")}),NI4=L.object({item:mX.describe("The created connection entity")}),A80=j1({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",inputSchema:UI4,outputSchema:NI4,handler:async(Q,J)=>{u1(J);let X=j4(J);await J.access.check();let G=QJ(J);if(!G)throw Error("User ID required to create connection");let Y={...Q.data,organization_id:X.id,created_by:G},W=await TU({id:"pending",title:Y.title,connection_url:Y.connection_url,connection_token:Y.connection_token,connection_headers:Y.connection_headers}).catch(()=>null),$=W?.length?W:null,K=await J.storage.connections.create({...Y,tools:$});return await J.eventBus.publish(X.id,XU.SELF(X.id),{type:"connection.created",data:K}),{item:K}}})});function JZ(Q){function J(X,G){if(G.description)X=X.describe(G.description);return X}if(Q.const!==void 0){if(typeof Q.const==="string")return J(L.literal(Q.const),Q);else if(typeof Q.const==="number")return J(L.literal(Q.const),Q);else if(typeof Q.const==="boolean")return J(L.literal(Q.const),Q);else if(Q.const===null)return J(L.null(),Q);return J(L.literal(Q.const),Q)}if(Q.type)switch(Q.type){case"string":{if(Q.enum){if(Q.enum.length===0)return J(L.string(),Q);return J(L.enum(Q.enum),Q)}let X=L.string();if(Q.minLength!==void 0)X=X.min(Q.minLength);if(Q.maxLength!==void 0)X=X.max(Q.maxLength);if(Q.pattern!==void 0){let G=new RegExp(Q.pattern);X=X.regex(G)}return J(X,Q)}case"number":case"integer":{if(Q.enum){if(Q.enum.length===0)return J(L.number(),Q);let G=Q.enum.map((Y)=>L.literal(Y));if(G.length===1)return J(G[0],Q);if(G.length>=2){let Y=L.union([G[0],G[1],...G.slice(2)]);return J(Y,Q)}}let X=Q.type==="integer"?L.number().int():L.number();if(Q.minimum!==void 0)X=X.min(Q.minimum);if(Q.maximum!==void 0)X=X.max(Q.maximum);if(Q.exclusiveMinimum!==void 0)X=X.gt(Q.exclusiveMinimum);if(Q.exclusiveMaximum!==void 0)X=X.lt(Q.exclusiveMaximum);if(Q.multipleOf!==void 0)X=X.multipleOf(Q.multipleOf);return J(X,Q)}case"boolean":if(Q.enum){if(Q.enum.length===0)return J(L.boolean(),Q);let X=Q.enum.map((G)=>L.literal(G));if(X.length===1)return J(X[0],Q);if(X.length>=2){let G=L.union([X[0],X[1],...X.slice(2)]);return J(G,Q)}}return J(L.boolean(),Q);case"null":return J(L.null(),Q);case"object":if(Q.properties){let X={};for(let[Y,W]of Object.entries(Q.properties))X[Y]=JZ(W);if(Q.required&&Array.isArray(Q.required)){let Y=new Set(Q.required);for(let W of Object.keys(X))if(!Y.has(W))X[W]=X[W].optional()}else for(let Y of Object.keys(X))X[Y]=X[Y].optional();let G;if(Q.additionalProperties!==!1)G=L.object(X).passthrough();else G=L.object(X);return J(G,Q)}return J(L.object({}),Q);case"array":{let X;if(Q.items)X=L.array(JZ(Q.items));else X=L.array(L.any());if(Q.minItems!==void 0)X=X.min(Q.minItems);if(Q.maxItems!==void 0)X=X.max(Q.maxItems);if(Q.uniqueItems===!0)X=X.refine((G)=>{let Y=new Set;return G.every((W)=>{if(typeof W==="string"||typeof W==="number"||typeof W==="boolean"){if(Y.has(W))return!1;return Y.add(W),!0}let $=JSON.stringify(W);if(Y.has($))return!1;return Y.add($),!0})},{message:"Array items must be unique"});return J(X,Q)}}if(Q.enum){if(Q.enum.length===0)return J(L.never(),Q);if(Q.enum.every((G)=>typeof G==="string"))return J(L.enum(Q.enum),Q);else{let G=Q.enum.map((Y)=>L.literal(Y));if(G.length===1)return J(G[0],Q);if(G.length>=2){let Y=L.union([G[0],G[1],...G.slice(2)]);return J(Y,Q)}}}if(Q.anyOf&&Q.anyOf.length>=2){let X=Q.anyOf.map(JZ);return J(L.union([X[0],X[1],...X.slice(2)]),Q)}if(Q.allOf)return J(Q.allOf.reduce((X,G)=>L.intersection(X,JZ(G)),L.object({})),Q);if(Q.oneOf&&Q.oneOf.length>=2){let X=Q.oneOf.map(JZ);return J(L.union([X[0],X[1],...X.slice(2)]),Q)}return J(L.any(),Q)}var CX1=s(()=>{w4()});function BI4(Q){let J=globalThis.DOMException;return typeof J=="function"?new J(Q,"SyntaxError"):SyntaxError(Q)}function j80(Q){return Q instanceof Error?"errors"in Q&&Array.isArray(Q.errors)?Q.errors.map(j80).join(", "):("cause"in Q)&&Q.cause instanceof Error?`${Q}: ${j80(Q.cause)}`:Q.message:`${Q}`}function RX1(Q){return{type:Q.type,message:Q.message,code:Q.code,defaultPrevented:Q.defaultPrevented,cancelable:Q.cancelable,timeStamp:Q.timeStamp}}function OI4(){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 E80,vX1=(Q)=>{throw TypeError(Q)},y80=(Q,J,X)=>J.has(Q)||vX1("Cannot "+X),g4=(Q,J,X)=>(y80(Q,J,"read from private field"),X?X.call(Q):J.get(Q)),I9=(Q,J,X)=>J.has(Q)?vX1("Cannot add the same private member more than once"):J instanceof WeakSet?J.add(Q):J.set(Q,X),b8=(Q,J,X,G)=>(y80(Q,J,"write to private field"),J.set(Q,X),X),SW=(Q,J,X)=>(y80(Q,J,"access private method"),X),JJ,zF,hU,L_,w_,jP,xU,IP,XZ,fU,gU,bU,AP,gY,I80,C80,R80,SX1,S80,v80,EP,k80,_80,uU;var kX1=s(()=>{h40();E80=class E80 extends Event{constructor(Q,J){var X,G;super(Q),this.code=(X=J==null?void 0:J.code)!=null?X:void 0,this.message=(G=J==null?void 0:J.message)!=null?G:void 0}[Symbol.for("nodejs.util.inspect.custom")](Q,J,X){return X(RX1(this),J)}[Symbol.for("Deno.customInspect")](Q,J){return Q(RX1(this),J)}};uU=class uU extends EventTarget{constructor(Q,J){var X,G;super(),I9(this,gY),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,I9(this,JJ),I9(this,zF),I9(this,hU),I9(this,L_),I9(this,w_),I9(this,jP),I9(this,xU),I9(this,IP,null),I9(this,XZ),I9(this,fU),I9(this,gU,null),I9(this,bU,null),I9(this,AP,null),I9(this,C80,async(Y)=>{var W;g4(this,fU).reset();let{body:$,redirected:K,status:Z,headers:H}=Y;if(Z===204){SW(this,gY,EP).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(K?b8(this,hU,new URL(Y.url)):b8(this,hU,void 0),Z!==200){SW(this,gY,EP).call(this,`Non-200 status code (${Z})`,Z);return}if(!(H.get("content-type")||"").startsWith("text/event-stream")){SW(this,gY,EP).call(this,'Invalid content type, expected "text/event-stream"',Z);return}if(g4(this,JJ)===this.CLOSED)return;b8(this,JJ,this.OPEN);let F=new Event("open");if((W=g4(this,AP))==null||W.call(this,F),this.dispatchEvent(F),typeof $!="object"||!$||!("getReader"in $)){SW(this,gY,EP).call(this,"Invalid response body, expected a web ReadableStream",Z),this.close();return}let q=new TextDecoder,V=$.getReader(),z=!0;do{let{done:U,value:N}=await V.read();N&&g4(this,fU).feed(q.decode(N,{stream:!U})),U&&(z=!1,g4(this,fU).reset(),SW(this,gY,k80).call(this))}while(z)}),I9(this,R80,(Y)=>{b8(this,XZ,void 0),!(Y.name==="AbortError"||Y.type==="aborted")&&SW(this,gY,k80).call(this,j80(Y))}),I9(this,S80,(Y)=>{typeof Y.id=="string"&&b8(this,IP,Y.id);let W=new MessageEvent(Y.event||"message",{data:Y.data,origin:g4(this,hU)?g4(this,hU).origin:g4(this,zF).origin,lastEventId:Y.id||""});g4(this,bU)&&(!Y.event||Y.event==="message")&&g4(this,bU).call(this,W),this.dispatchEvent(W)}),I9(this,v80,(Y)=>{b8(this,jP,Y)}),I9(this,_80,()=>{b8(this,xU,void 0),g4(this,JJ)===this.CONNECTING&&SW(this,gY,I80).call(this)});try{if(Q instanceof URL)b8(this,zF,Q);else if(typeof Q=="string")b8(this,zF,new URL(Q,OI4()));else throw Error("Invalid URL")}catch{throw BI4("An invalid or illegal string was specified")}b8(this,fU,_k({onEvent:g4(this,S80),onRetry:g4(this,v80)})),b8(this,JJ,this.CONNECTING),b8(this,jP,3000),b8(this,w_,(X=J==null?void 0:J.fetch)!=null?X:globalThis.fetch),b8(this,L_,(G=J==null?void 0:J.withCredentials)!=null?G:!1),SW(this,gY,I80).call(this)}get readyState(){return g4(this,JJ)}get url(){return g4(this,zF).href}get withCredentials(){return g4(this,L_)}get onerror(){return g4(this,gU)}set onerror(Q){b8(this,gU,Q)}get onmessage(){return g4(this,bU)}set onmessage(Q){b8(this,bU,Q)}get onopen(){return g4(this,AP)}set onopen(Q){b8(this,AP,Q)}addEventListener(Q,J,X){let G=J;super.addEventListener(Q,G,X)}removeEventListener(Q,J,X){let G=J;super.removeEventListener(Q,G,X)}close(){g4(this,xU)&&clearTimeout(g4(this,xU)),g4(this,JJ)!==this.CLOSED&&(g4(this,XZ)&&g4(this,XZ).abort(),b8(this,JJ,this.CLOSED),b8(this,XZ,void 0))}};JJ=new WeakMap,zF=new WeakMap,hU=new WeakMap,L_=new WeakMap,w_=new WeakMap,jP=new WeakMap,xU=new WeakMap,IP=new WeakMap,XZ=new WeakMap,fU=new WeakMap,gU=new WeakMap,bU=new WeakMap,AP=new WeakMap,gY=new WeakSet,I80=function(){b8(this,JJ,this.CONNECTING),b8(this,XZ,new AbortController),g4(this,w_)(g4(this,zF),SW(this,gY,SX1).call(this)).then(g4(this,C80)).catch(g4(this,R80))},C80=new WeakMap,R80=new WeakMap,SX1=function(){var Q;let J={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...g4(this,IP)?{"Last-Event-ID":g4(this,IP)}:void 0},cache:"no-store",signal:(Q=g4(this,XZ))==null?void 0:Q.signal};return"window"in globalThis&&(J.credentials=this.withCredentials?"include":"same-origin"),J},S80=new WeakMap,v80=new WeakMap,EP=function(Q,J){var X;g4(this,JJ)!==this.CLOSED&&b8(this,JJ,this.CLOSED);let G=new E80("error",{code:J,message:Q});(X=g4(this,gU))==null||X.call(this,G),this.dispatchEvent(G)},k80=function(Q,J){var X;if(g4(this,JJ)===this.CLOSED)return;b8(this,JJ,this.CONNECTING);let G=new E80("error",{code:J,message:Q});(X=g4(this,gU))==null||X.call(this,G),this.dispatchEvent(G),b8(this,xU,setTimeout(g4(this,_80),g4(this,jP)))},_80=new WeakMap,uU.CONNECTING=0,uU.OPEN=1,uU.CLOSED=2});class h80{constructor(Q,J){this._url=Q,this._resourceMetadataUrl=void 0,this._eventSourceInit=J===null||J===void 0?void 0:J.eventSourceInit,this._requestInit=J===null||J===void 0?void 0:J.requestInit,this._authProvider=J===null||J===void 0?void 0:J.authProvider,this._fetch=J===null||J===void 0?void 0:J.fetch}async _authThenStart(){var Q;if(!this._authProvider)throw new bJ("No auth provider");let J;try{J=await rK(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(X){throw(Q=this.onerror)===null||Q===void 0||Q.call(this,X),X}if(J!=="AUTHORIZED")throw new bJ;return await this._startOrAuth()}async _commonHeaders(){var Q;let J={};if(this._authProvider){let X=await this._authProvider.tokens();if(X)J.Authorization=`Bearer ${X.access_token}`}if(this._protocolVersion)J["mcp-protocol-version"]=this._protocolVersion;return new Headers({...J,...(Q=this._requestInit)===null||Q===void 0?void 0:Q.headers})}_startOrAuth(){var Q,J,X;let G=(X=(J=(Q=this===null||this===void 0?void 0:this._eventSourceInit)===null||Q===void 0?void 0:Q.fetch)!==null&&J!==void 0?J:this._fetch)!==null&&X!==void 0?X:fetch;return new Promise((Y,W)=>{this._eventSource=new uU(this._url.href,{...this._eventSourceInit,fetch:async($,K)=>{let Z=await this._commonHeaders();Z.set("Accept","text/event-stream");let H=await G($,{...K,headers:Z});if(H.status===401&&H.headers.has("www-authenticate"))this._resourceMetadataUrl=ZP(H);return H}}),this._abortController=new AbortController,this._eventSource.onerror=($)=>{var K;if($.code===401&&this._authProvider){this._authThenStart().then(Y,W);return}let Z=new _X1($.code,$.message,$);W(Z),(K=this.onerror)===null||K===void 0||K.call(this,Z)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",($)=>{var K;let Z=$;try{if(this._endpoint=new URL(Z.data,this._url),this._endpoint.origin!==this._url.origin)throw Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(H){W(H),(K=this.onerror)===null||K===void 0||K.call(this,H),this.close();return}Y()}),this._eventSource.onmessage=($)=>{var K,Z;let H=$,F;try{F=_Y.parse(JSON.parse(H.data))}catch(q){(K=this.onerror)===null||K===void 0||K.call(this,q);return}(Z=this.onmessage)===null||Z===void 0||Z.call(this,F)}})}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 bJ("No auth provider");if(await rK(this._authProvider,{serverUrl:this._url,authorizationCode:Q,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new bJ("Failed to authorize")}async close(){var Q,J,X;(Q=this._abortController)===null||Q===void 0||Q.abort(),(J=this._eventSource)===null||J===void 0||J.close(),(X=this.onclose)===null||X===void 0||X.call(this)}async send(Q){var J,X,G;if(!this._endpoint)throw Error("Not connected");try{let Y=await this._commonHeaders();Y.set("content-type","application/json");let W={...this._requestInit,method:"POST",headers:Y,body:JSON.stringify(Q),signal:(J=this._abortController)===null||J===void 0?void 0:J.signal},$=await((X=this._fetch)!==null&&X!==void 0?X:fetch)(this._endpoint,W);if(!$.ok){if($.status===401&&this._authProvider){if(this._resourceMetadataUrl=ZP($),await rK(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new bJ;return this.send(Q)}let K=await $.text().catch(()=>null);throw Error(`Error POSTing to endpoint (HTTP ${$.status}): ${K}`)}}catch(Y){throw(G=this.onerror)===null||G===void 0||G.call(this,Y),Y}}setProtocolVersion(Q){this._protocolVersion=Q}}var _X1;var yX1=s(()=>{kX1();fJ();k40();_X1=class _X1 extends Error{constructor(Q,J,X){super(`SSE error: ${J}`);this.code=Q,this.event=X}}});class f80{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,J)=>{this._socket=new WebSocket(this._url,DI4),this._socket.onerror=(X)=>{var G;let Y="error"in X?X.error:Error(`WebSocket error: ${JSON.stringify(X)}`);J(Y),(G=this.onerror)===null||G===void 0||G.call(this,Y)},this._socket.onopen=()=>{Q()},this._socket.onclose=()=>{var X;(X=this.onclose)===null||X===void 0||X.call(this)},this._socket.onmessage=(X)=>{var G,Y;let W;try{W=_Y.parse(JSON.parse(X.data))}catch($){(G=this.onerror)===null||G===void 0||G.call(this,$);return}(Y=this.onmessage)===null||Y===void 0||Y.call(this,W)}})}async close(){var Q;(Q=this._socket)===null||Q===void 0||Q.close()}send(Q){return new Promise((J,X)=>{var G;if(!this._socket){X(Error("Not connected"));return}(G=this._socket)===null||G===void 0||G.send(JSON.stringify(Q)),J()})}}var DI4="mcp";var hX1=s(()=>{fJ()});function LI4(Q){let J=Q;if(!J||typeof J!=="object"||!("method"in J))return null;switch(J.method){case"initialize":{let X=J?.params?.protocolVersion;if(!X)return null;return{type:"emit",message:{result:{protocolVersion:X,capabilities:{tools:{}},serverInfo:{name:"deco-chat-server",version:"1.0.0"}},jsonrpc:J.jsonrpc??"2.0",id:J.id}}}case"notifications/roots/list_changed":case"notifications/initialized":case"notifications/cancelled":case"notifications/progress":return{type:"suppress"};default:return null}}var b80;var fX1=s(()=>{FP();b80=class b80 extends jW{constructor(Q,J){super(Q,J)}send(Q,J){let X=LI4(Q);if(X?.type==="emit")return this.onmessage?.(X.message),Promise.resolve();if(X?.type==="suppress")return Promise.resolve();return super.send(Q,J)}}});var bX1,xX1=async(Q,J,X)=>{let G=wI4(Q.connection,J,X);if(!G)throw Error("Unknown MCP connection type");let Y=new bX1({name:Q?.name??"MCP Client",version:"1.0.0"});return await Y.connect(G),{client:Y,callStreamableTool:(W,$)=>{if(Q.connection.type!=="HTTP")throw Error("HTTP connection required");let K=new Headers(X);if(!K.has("Authorization"))K.set("Authorization",`Bearer ${Q.connection.token}`);for(let[F,q]of Object.entries(Q.connection.headers??{}))K.set(F,q);let Z=new URL(Q.connection.url),H=Z.pathname.replace(/\/+$/,"")||"/";return Z.pathname=`${H}/call-tool/${encodeURIComponent(W)}`,fetch(Z.href,{method:"POST",redirect:"manual",body:JSON.stringify($),headers:K})}}},wI4=(Q,J,X)=>{if(Q.type==="Websocket")return new f80(new URL(Q.url));if(Q.type!=="SSE"&&Q.type!=="HTTP")return null;let Y={...Q.token?{authorization:`Bearer ${Q.token}`}:{},...X??{},..."headers"in Q?Q.headers||{}:{}};if(Q.type==="SSE"){let W={requestInit:{headers:Y,signal:J}};if(Q.token)W.eventSourceInit={fetch:($,K)=>{return fetch($,{...K,headers:{...Y,Accept:"text/event-stream"},signal:J})}};return new h80(new URL(Q.url),W)}return new b80(new URL(Q.url),{requestInit:{headers:Y,signal:J,credentials:"include"}})};var gX1=s(()=>{wk();yX1();hX1();fJ();fX1();bX1=class bX1 extends JF{constructor(Q,J){super(Q,J)}async listTools(Q,J){return await this.request({method:"tools/list",params:Q},YP,J)}}});function mX1(Q){let J=(X)=>{if("connection"in Q)return xX1({connection:Q.connection},void 0,X);return Q.client};return new Proxy({},{get(X,G){if(G==="toJSON")return null;if(typeof G!=="string")throw Error("Name must be a string");if(G==="listTools")return K;async function Y(Z,H=G){let F=Q?.debugId?.(),q=F?{"x-trace-debug-id":F}:void 0,{client:V,callStreamableTool:z}=await J(q);if(Q?.streamable?.[String(H)])return z(String(H),Z);let{structuredContent:U,isError:N,content:D}=await V.callTool({name:String(H),arguments:Z});if(N){let w=D?.[0]?.text,E=typeof w==="string"?PI4(w):null,M=E?.code&&typeof Q?.getErrorByStatusCode==="function"?Q.getErrorByStatusCode(E.code,E.message,E.traceId):null;if(M)throw M;throw Error(`Tool ${String(H)} returned an error: ${JSON.stringify(U??D)}`)}return U}async function W(){let{client:Z}=await J(),{tools:H}=await Z.listTools();return H}async function $(){if(!("connection"in Q))return W();let Z=Q.connection,H=JSON.stringify(Z);try{if(!P_.has(H))P_.set(H,W());return await P_.get(H)}catch(F){console.error("Failed to list tools",F),P_.delete(H);return}}async function K(){return(await $()??[]).map((H)=>uX1(H,Y))}return Y.asTool=async()=>{let H=(await $()??[]).find((F)=>F.name===G);if(!H)throw Error(`Tool ${G} not found`);return uX1(H,Y)},Y}})}var PI4=(Q)=>{try{return JSON.parse(Q)}catch{return Q}},P_,uX1=(Q,J)=>{return{...Q,id:Q.name,inputSchema:Q.inputSchema?JZ(Q.inputSchema):void 0,outputSchema:Q.outputSchema?JZ(Q.outputSchema):void 0,execute:(X)=>{return J(X.context,Q.name)}}};var lX1=s(()=>{CX1();gX1();P_=new Map});function M_(Q){return mX1(Q)}var uk6;var dX1=s(()=>{lX1();uk6=new Proxy({},{get(Q,J){if(J==="toJSON")return null;if(J==="forConnection")return(X)=>M_({connection:X});return global[J]}})});function T_(Q){return{isImplementedBy:(J)=>{for(let X of Q){let G=typeof X.name==="string"?new RegExp(`^${X.name}$`):X.name,Y=J.find((W)=>G.test(W.name));if(!Y&&X.opt)continue;if(!Y)return!1}return!0}}}var mU=(Q)=>{return{...T_(Q),forClient:(J)=>{return M_({client:J,streamable:Q.reduce((X,G)=>{return X[G.name]=G.streamable===!0,X},{})})},forConnection:(J)=>{return M_({connection:J,streamable:Q.reduce((X,G)=>{return X[G.name]=G.streamable===!0,X},{})})}}};var CP=s(()=>{dX1()});function SP(Q){return L.object({items:L.array(Q).describe("Array of collection items"),totalCount:L.number().int().min(0).optional().describe("Total number of matching items (if available)"),hasMore:L.boolean().optional().describe("Whether there are more items available")})}function g80(Q){return L.object({item:Q.nullable().describe("The retrieved item, or null if not found")})}function AI4(Q){return L.object({data:Q.partial().describe("Data for the new entity (id may be auto-generated)")})}function EI4(Q){return L.object({item:Q.describe("The created entity with generated id")})}function jI4(Q){return L.object({id:L.string().describe("ID of the entity to update"),data:Q.partial().describe("Partial entity data to update")})}function II4(Q){return L.object({item:Q.describe("The updated entity")})}function m80(Q){return L.object({item:Q.describe("The deleted entity")})}function dU(Q,J,X){let G=Q.toUpperCase(),Y=X?.readOnly??!1,W=[{name:`COLLECTION_${G}_LIST`,inputSchema:RP,outputSchema:SP(J)},{name:`COLLECTION_${G}_GET`,inputSchema:x80,outputSchema:g80(J)}];if(!Y)W.push({name:`COLLECTION_${G}_CREATE`,inputSchema:AI4(J),outputSchema:EI4(J),opt:!0},{name:`COLLECTION_${G}_UPDATE`,inputSchema:jI4(J),outputSchema:II4(J),opt:!0},{name:`COLLECTION_${G}_DELETE`,inputSchema:u80,outputSchema:m80(J),opt:!0});return W}var lU,MI4,pX1,TI4,RP,x80,u80;var YZ=s(()=>{w4();lU=L.object({id:L.string().describe("Unique identifier for the entity"),title:L.string().describe("Human-readable title for the entity"),description:L.string().nullish().describe("Description of the entity"),created_at:L.string().datetime(),updated_at:L.string().datetime(),created_by:L.string().optional(),updated_by:L.string().optional()}),MI4=L.object({field:L.array(L.string()),operator:L.enum(["eq","gt","gte","lt","lte","in","like","contains"]),value:L.unknown()}),pX1=L.lazy(()=>L.union([MI4,L.object({operator:L.enum(["and","or","not"]),conditions:L.array(pX1)})])),TI4=L.object({field:L.array(L.string()),direction:L.enum(["asc","desc"]),nulls:L.enum(["first","last"]).optional()}),RP=L.object({where:pX1.optional().describe("Filter expression"),orderBy:L.array(TI4).optional().describe("Sort expressions"),limit:L.number().int().min(1).max(1000).optional().describe("Maximum number of items to return"),offset:L.number().int().min(0).optional().describe("Number of items to skip")});x80=L.object({id:L.string().describe("ID of the entity to retrieve")});u80=L.object({id:L.string().describe("ID of the entity to delete")})});var CI4,cX1,ak6;var nX1=s(()=>{w4();YZ();CI4=L.object({id:L.string(),name:L.string(),description:L.string().optional(),inputSchema:L.record(L.unknown()),outputSchema:L.record(L.unknown()).optional()}),cX1=lU.extend({_meta:L.object({"io.decocms":L.object({id:L.string(),verified:L.boolean(),scopeName:L.string(),appName:L.string(),friendlyName:L.string().nullable().optional(),metadata:L.record(L.unknown()).nullable().optional(),publishedAt:L.string().datetime().optional(),updatedAt:L.string().datetime().optional(),tools:L.array(CI4).nullable().optional().describe("Available tools exposed by this app")}).optional()}).optional(),server:L.object({$schema:L.string().optional(),_meta:L.record(L.unknown()).optional(),name:L.string().describe("The server name (scope/app)"),title:L.string().optional().describe("User-friendly title"),description:L.string().optional().describe("Server description"),icons:L.array(L.object({src:L.string(),mimeType:L.string().optional(),sizes:L.array(L.string()).optional(),theme:L.enum(["light","dark"]).optional()})).optional(),remotes:L.array(L.object({type:L.enum(["http","stdio","sse"]),url:L.string().optional(),headers:L.array(L.unknown()).optional()})).optional(),packages:L.array(L.unknown()).optional(),repository:L.object({url:L.string(),source:L.string().optional(),subfolder:L.string().optional()}).optional(),version:L.string().optional(),websiteUrl:L.string().optional()})}),ak6=dU("registry_app",cX1,{readOnly:!0})});var iX1,rX1,aX1,oX1,sX1,l80;var tX1=s(()=>{w4();CP();iX1=L.object({specversion:L.literal("1.0").describe("CloudEvents specification version"),id:L.string().describe("Unique identifier for this event (UUID recommended)"),source:L.string().describe("Connection ID of the event publisher"),type:L.string().describe("Event type (e.g., 'order.created', 'user.signup')"),time:L.string().datetime().optional().describe("Timestamp of when the event occurred (ISO 8601)"),subject:L.string().optional().describe("Subject/resource identifier (e.g., order ID, user ID)"),datacontenttype:L.string().optional().default("application/json").describe("Content type of the data attribute"),dataschema:L.string().url().optional().describe("URI to the schema for the data attribute"),data:L.unknown().optional().describe("Event payload (any JSON value)")}),rX1=L.object({events:L.array(iX1).min(1).describe("Batch of CloudEvents to process")}),aX1=L.object({success:L.boolean().optional().describe("Whether this event was processed successfully"),error:L.string().optional().describe("Error message for this event"),retryAfter:L.number().int().positive().optional().describe("Re-deliver this event after this many ms")}),oX1=L.object({success:L.boolean().optional().describe("Batch success - applies to events not in results"),error:L.string().optional().describe("Batch error message - applies to events not in results"),processedCount:L.number().int().min(0).optional().describe("Number of events successfully processed"),retryAfter:L.number().int().positive().optional().describe("Batch retryAfter - applies to events not in results"),results:L.record(L.string(),aX1).optional().describe("Per-event results keyed by event ID")}),sX1=[{name:"ON_EVENTS",inputSchema:rX1,outputSchema:oX1}],l80=mU(sX1)});var vP,kP,_P,yP,eX1,QY1,hP,fP,bP,xP,gP,uP,mP,lP,JY1,RI4;var XY1=s(()=>{w4();CP();vP=L.object({type:L.string().min(1).max(255).describe("Event type identifier"),subject:L.string().max(255).optional().describe("Subject/resource identifier (e.g., order ID)"),data:L.unknown().optional().describe("Event payload"),deliverAt:L.string().datetime().optional().describe("Scheduled delivery time (ISO 8601). Omit for immediate delivery."),cron:L.string().max(100).optional().describe("Cron expression for recurring delivery. Use EVENT_CANCEL to stop.")}),kP=L.object({id:L.string().describe("Unique event ID"),type:L.string().describe("Event type"),source:L.string().describe("Source connection ID"),time:L.string().describe("Event timestamp")}),_P=L.object({eventType:L.string().min(1).max(255).describe("Event type to subscribe to"),publisher:L.string().optional().describe("Filter events by publisher connection ID"),filter:L.string().max(1000).optional().describe("JSONPath filter expression on event data")}),yP=L.object({subscription:L.object({id:L.string().describe("Subscription ID"),connectionId:L.string().describe("Subscriber connection ID"),eventType:L.string().describe("Event type pattern"),publisher:L.string().nullable().describe("Publisher connection filter"),filter:L.string().nullable().describe("JSONPath filter expression"),enabled:L.boolean().describe("Whether subscription is enabled"),createdAt:L.union([L.string(),L.date()]).describe("Created timestamp"),updatedAt:L.union([L.string(),L.date()]).describe("Updated timestamp")})}),eX1=L.object({eventType:L.string().min(1).max(255).describe("Event type to subscribe to"),publisher:L.string().optional().describe("Filter events by publisher connection ID"),filter:L.string().max(1000).optional().describe("JSONPath filter expression on event data")}),QY1=L.object({id:L.string().describe("Subscription ID"),connectionId:L.string().describe("Subscriber connection ID"),eventType:L.string().describe("Event type pattern"),publisher:L.string().nullable().describe("Publisher connection filter"),filter:L.string().nullable().describe("JSONPath filter expression"),enabled:L.boolean().describe("Whether subscription is enabled"),createdAt:L.union([L.string(),L.date()]).describe("Created timestamp"),updatedAt:L.union([L.string(),L.date()]).describe("Updated timestamp")}),hP=L.object({subscriptions:L.array(eX1).describe("Desired subscriptions - system will create/update/delete to match")}),fP=L.object({created:L.number().int().min(0).describe("Number of subscriptions created"),updated:L.number().int().min(0).describe("Number of subscriptions with filter updated"),deleted:L.number().int().min(0).describe("Number of subscriptions removed"),unchanged:L.number().int().min(0).describe("Number of subscriptions unchanged"),subscriptions:L.array(QY1).describe("Current subscriptions after sync")}),bP=L.object({subscriptionId:L.string().describe("Subscription ID to remove")}),xP=L.object({success:L.boolean().describe("Whether unsubscribe was successful"),subscriptionId:L.string().describe("Subscription ID that was removed")}),gP=L.object({eventId:L.string().describe("Event ID to cancel")}),uP=L.object({success:L.boolean().describe("Whether cancellation was successful"),eventId:L.string().describe("Event ID that was cancelled")}),mP=L.object({eventId:L.string().describe("Event ID to acknowledge")}),lP=L.object({success:L.boolean().describe("Whether ACK was successful"),eventId:L.string().describe("Event ID that was acknowledged")}),JY1=[{name:"EVENT_PUBLISH",inputSchema:vP,outputSchema:kP},{name:"EVENT_SUBSCRIBE",inputSchema:_P,outputSchema:yP},{name:"EVENT_UNSUBSCRIBE",inputSchema:bP,outputSchema:xP},{name:"EVENT_CANCEL",inputSchema:gP,outputSchema:uP},{name:"EVENT_ACK",inputSchema:mP,outputSchema:lP},{name:"EVENT_SYNC_SUBSCRIPTIONS",inputSchema:hP,outputSchema:fP}],RI4=mU(JY1)});var A_=s(()=>{CP();nX1();tX1();XY1()});var SI4,vI4,YY1;var GY1=s(()=>{w4();YZ();SI4=lU.extend({description:L.string().describe("Brief description of the agent's purpose"),instructions:L.string().describe("System instructions that define the agent's behavior"),tool_set:L.record(L.string(),L.array(L.string())).describe("Map of connection IDs to arrays of allowed tool names for this agent"),avatar:L.string().url().describe("URL to the agent's avatar image")}),vI4=dU("agent",SI4),YY1=[...vI4]});var dP,vW,$Y1,kI4,KY1,_I4,yI4,hI4,ZY1,fI4,bI4,xI4,gI4,uI4,mI4,lI4,dI4,N_6,pI4,B_6,WY1,cI4,nI4,d80,HY1;var p80=s(()=>{w4();CP();YZ();dP=L.lazy(()=>L.union([L.null(),L.string(),L.number(),L.boolean(),L.record(L.string(),dP),L.array(dP)])),vW=L.record(L.string(),L.record(L.string(),dP)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),$Y1=L.object({type:L.literal("text"),text:L.string().describe("The text content"),providerOptions:vW}),kI4=L.union([L.string(),L.instanceof(Uint8Array)]).describe("File data as base64 encoded string, URL string, or Uint8Array"),KY1=L.object({type:L.literal("file"),filename:L.string().optional().describe("Optional filename of the file"),data:kI4,mediaType:L.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:vW}),_I4=L.object({type:L.literal("reasoning"),text:L.string().describe("The reasoning text"),providerOptions:vW}),yI4=L.object({type:L.literal("tool-call"),toolCallId:L.string().describe("ID of the tool call, used to match with tool result"),toolName:L.string().describe("Name of the tool being called"),input:L.unknown().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:L.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:vW}),hI4=L.union([L.object({type:L.literal("text"),value:L.string()}),L.object({type:L.literal("json"),value:dP}),L.object({type:L.literal("error-text"),value:L.string()}),L.object({type:L.literal("error-json"),value:dP}),L.object({type:L.literal("content"),value:L.array(L.union([L.object({type:L.literal("text"),text:L.string().describe("Text content")}),L.object({type:L.literal("media"),data:L.string().describe("Base-64 encoded media data"),mediaType:L.string().describe("IANA media type")})]))})]),ZY1=L.object({type:L.literal("tool-result"),toolCallId:L.string().describe("ID of the tool call that this result is associated with"),toolName:L.string().describe("Name of the tool that generated this result"),output:hI4.describe("Result of the tool call"),providerOptions:vW}),fI4=L.object({role:L.literal("system"),content:L.string().describe("System message content"),providerOptions:vW}),bI4=L.object({role:L.literal("user"),content:L.array(L.union([$Y1,KY1])).describe("User message content parts (text or file)"),providerOptions:vW}),xI4=L.object({role:L.literal("assistant"),content:L.array(L.union([$Y1,KY1,_I4,yI4,ZY1])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:vW}),gI4=L.object({role:L.literal("tool"),content:L.array(ZY1).describe("Tool message content (tool results)"),providerOptions:vW}),uI4=L.union([fI4,bI4,xI4,gI4]),mI4=L.array(uI4).describe("A list of messages forming the prompt"),lI4=L.object({prompt:mI4.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:L.number().optional().describe("Maximum number of tokens to generate"),temperature:L.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:L.number().optional().describe("Nucleus sampling parameter"),topK:L.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:L.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:L.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:L.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:L.array(L.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:L.union([L.object({type:L.literal("text")}),L.object({type:L.literal("json"),schema:L.any().optional().describe("JSON schema that the generated output should conform to"),name:L.string().optional().describe("Name of output that should be generated"),description:L.string().optional().describe("Description of the output that should be generated")})]).optional().describe("Response format. The output can either be text or JSON. Default is text"),tools:L.array(L.any()).optional().describe("The tools that are available for the model"),toolChoice:L.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:L.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:L.any().optional().describe("Abort signal for cancelling the operation"),headers:L.record(L.string(),L.union([L.string(),L.undefined()])).optional().describe("Additional HTTP headers to be sent with the request"),providerOptions:L.any().optional().describe("Additional provider-specific options")}),dI4=L.object({content:L.array(L.any()).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:L.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:L.object({inputTokens:L.number().optional(),outputTokens:L.number().optional(),totalTokens:L.number().optional(),reasoningTokens:L.number().optional()}).passthrough().transform((Q)=>({inputTokens:Q.inputTokens,outputTokens:Q.outputTokens,totalTokens:Q.totalTokens,reasoningTokens:Q.reasoningTokens,...Q})).describe("Usage information for the language model call"),providerMetadata:L.any().optional().describe("Additional provider-specific metadata"),request:L.object({body:L.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:L.object({id:L.string().optional().describe("ID for the generated response"),timestamp:L.date().optional().describe("Timestamp for the start of the generated response"),modelId:L.string().optional().describe("The ID of the response model that was used"),headers:L.record(L.string(),L.string()).optional().describe("Response headers"),body:L.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:L.array(L.any()).describe("Warnings for the call, e.g. unsupported settings")}),N_6=L.object({stream:L.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:L.object({body:L.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:L.object({headers:L.record(L.string(),L.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),pI4=L.object({supportedUrls:L.record(L.string(),L.array(L.string())).describe("Supported URL patterns by media type for the provider")}),B_6=L.object({modelId:L.string().describe("The ID of the model"),logo:L.string().nullable(),description:L.string().nullable(),capabilities:L.array(L.string()),limits:L.object({contextWindow:L.number(),maxOutputTokens:L.number()}).nullable(),costs:L.object({input:L.number(),output:L.number()}).nullable(),provider:L.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),WY1=L.object({modelId:L.string().describe("The ID of the model"),callOptions:lI4}),cI4=lU.extend({logo:L.string().nullable(),description:L.string().nullable(),capabilities:L.array(L.string()),limits:L.object({contextWindow:L.number(),maxOutputTokens:L.number()}).nullable(),costs:L.object({input:L.number(),output:L.number()}).nullable(),provider:L.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),nI4=dU("llm",cI4,{readOnly:!0}),d80=[{name:"LLM_METADATA",inputSchema:L.object({modelId:L.string().describe("The ID of the model")}),outputSchema:pI4},{name:"LLM_DO_STREAM",inputSchema:WY1,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:WY1,outputSchema:dI4},...nI4],HY1=mU(d80)});function rI4(Q){let J=[],X=0;while(X<Q.length){let G=Q[X];if(G==="%")J.push(".*");else if(G==="_")J.push(".");else if(/[.*+?^${}()|[\]\\]/.test(G))J.push("\\"+G);else J.push(G);X++}return J.join("")}function GZ(Q){return typeof Q==="string"||typeof Q==="number"}function E_(Q,J){if("conditions"in J){let{operator:K,conditions:Z}=J;switch(K){case"and":return Z.every((H)=>E_(Q,H));case"or":return Z.some((H)=>E_(Q,H));case"not":return!Z.every((H)=>E_(Q,H));default:return!0}}let{field:X,operator:G,value:Y}=J,W=X.join("."),$=c80(Q,W);switch(G){case"eq":return $===Y;case"gt":return GZ($)&&GZ(Y)&&$>Y;case"gte":return GZ($)&&GZ(Y)&&$>=Y;case"lt":return GZ($)&&GZ(Y)&&$<Y;case"lte":return GZ($)&&GZ(Y)&&$<=Y;case"in":return Array.isArray(Y)&&Y.includes($);case"like":if(typeof $!=="string"||typeof Y!=="string")return!1;if(Y.length>100)return!1;let K=rI4(Y);return new RegExp(`^${K}$`,"i").test($);case"contains":if(typeof $!=="string"||typeof Y!=="string")return!1;return $.toLowerCase().includes(Y.toLowerCase());default:return!0}}function c80(Q,J){let X=J.split("."),G=Q;for(let Y of X){if(G==null||typeof G!=="object")return;G=G[Y]}return G}function aI4(Q,J){return[...Q].sort((X,G)=>{for(let Y of J){let W=Y.field.join("."),$=c80(X,W),K=c80(G,W),Z=0;if($==null&&K==null)continue;if($==null)Z=Y.nulls==="first"?-1:1;else if(K==null)Z=Y.nulls==="first"?1:-1;else if(typeof $==="string"&&typeof K==="string")Z=$.localeCompare(K);else if(typeof $==="number"&&typeof K==="number")Z=$-K;else Z=String($).localeCompare(String(K));if(Z!==0)return Y.direction==="desc"?-Z:Z}return 0})}var iI4,oI4,sI4,n80;var FY1=s(()=>{A_();GY1();YZ();p80();w4();x4();yU();iI4={LLM:d80,AGENTS:YY1};oI4=RP.extend({binding:L.union([L.object({}).passthrough(),L.string()]).optional()}),sI4=SP(mX),n80=j1({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",inputSchema:oI4,outputSchema:sI4,handler:async(Q,J)=>{await J.access.check();let X=j4(J),G=Q.binding?typeof Q.binding==="string"?(()=>{let V=iI4[Q.binding.toUpperCase()];if(!V)throw Error(`Unknown binding: ${Q.binding}`);return V})():Q.binding:void 0,Y=G?T_(G):void 0,W=await J.storage.connections.list(X.id),$=Y?await Promise.all(W.map(async(V)=>{if(!V.tools||V.tools.length===0)return null;return Y.isImplementedBy(V.tools.map((U)=>({name:U.name,inputSchema:U.inputSchema,outputSchema:U.outputSchema})))?V:null})).then((V)=>V.filter((z)=>z!==null)):W;if(Q.where)$=$.filter((V)=>E_(V,Q.where));if(Q.orderBy&&Q.orderBy.length>0)$=aI4($,Q.orderBy);let K=$.length,Z=Q.offset??0,H=Q.limit??100,F=$.slice(Z,Z+H),q=Z+H<K;return{items:F,totalCount:K,hasMore:q}}})});var tI4,i80;var qY1=s(()=>{YZ();x4();yU();tI4=g80(mX),i80=j1({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",inputSchema:x80,outputSchema:tI4,handler:async(Q,J)=>{let X=j4(J);await J.access.check();let G=await J.storage.connections.findById(Q.id);if(!G||G.organization_id!==X.id)return{item:null};return{item:G}}})});var j_=(Q,J)=>{if(J===null||J===void 0)return;let X=Q.replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),G=J;for(let Y of X){if(G===null||G===void 0||typeof G!=="object")return;G=G[Y]}return G};function VY1(Q){let J=Q.split("::");if(J.length!==2||!J[0]||!J[1])throw Error(`Invalid scope format: ${Q}. Expected format: "KEY::SCOPE"`);return J}function eI4(Q){let J=Q.split("::");if(J.length!==2||!J[0]||!J[1])return null;return J}function QC4(Q){if(typeof Q==="object"&&Q!==null&&"value"in Q){let J=Q.value;if(typeof J==="string")return J}return null}function r80(Q,J){let X={};if(!Q||!J)return X;for(let G of J){let Y=eI4(G);if(!Y)continue;let[W,$]=Y,K=j_(W,Q),Z=QC4(K);if(Z){if(!X[Z])X[Z]=[];X[Z].push($)}}return X}function zY1(Q,J){let X=r80(Q,J);return new Set(Object.keys(X))}var a80=()=>{};async function YC4(Q,J,X,G){for(let W of J){let[$]=VY1(W),K=j_($,Q);if(K===void 0||K===null)throw Error(`Scope references key "${$}" but it's not present in state`)}let Y=zY1(Q,J);for(let W of Y){if(W===IY.SELF)continue;let $=await G.storage.connections.findById(W);if(!$||$.organization_id!==X)throw Error(`Referenced connection not found: ${W}`);try{await G.access.check(W)}catch(K){throw Error(`Access denied to referenced connection: ${W}. ${K.message}`)}}}var JC4,XC4,o80;var UY1=s(()=>{a80();pH();w4();x4();hk();yU();JC4=L.object({id:L.string().describe("ID of the connection to update"),data:jX1.describe("Partial connection data to update")}),XC4=L.object({item:mX.describe("The updated connection entity")});o80=j1({name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update an existing MCP connection in the organization",inputSchema:JC4,outputSchema:XC4,handler:async(Q,J)=>{u1(J);let X=j4(J);await J.access.check();let{id:G,data:Y}=Q,W=await J.storage.connections.findById(G);if(!W||W.organization_id!==X.id)throw Error("Connection not found in organization");let $=Y.configuration_state??W.configuration_state,K=Y.configuration_scopes??W.configuration_scopes??[];if(Y.configuration_state!==void 0||Y.configuration_scopes!==void 0){if(Y.configuration_state!==void 0)$=Y.configuration_state;else if($===null)$={};if(Y.configuration_scopes!==void 0)K=Y.configuration_scopes??[];if(K.length>0&&$)await YC4($,K,X.id,J)}let Z=await TU({id:W.id,title:Y.title??W.title,connection_url:Y.connection_url??W.connection_url,connection_token:Y.connection_token??W.connection_token,connection_headers:Y.connection_headers??W.connection_headers}).catch(()=>null),H=Z?.length?Z:null,F={...Y,tools:H,configuration_state:$,configuration_scopes:K},q=await J.storage.connections.update(G,F);if((Y.configuration_state!==void 0||Y.configuration_scopes!==void 0)&&$&&K.length>0)try{await(await J.createMCPProxy(G)).client.callTool({name:"ON_MCP_CONFIGURATION",arguments:{state:$,scopes:K}})}catch(V){console.error("Failed to invoke ON_MCP_CONFIGURATION callback",V)}return{item:q}}})});var s80;var NY1=s(()=>{YZ();x4();yU();s80=j1({name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete a connection",inputSchema:u80,outputSchema:m80(mX),handler:async(Q,J)=>{u1(J);let X=j4(J);await J.access.check();let G=await J.storage.connections.findById(Q.id);if(!G)throw Error(`Connection not found: ${Q.id}`);if(G.organization_id!==X.id)throw Error("Connection not found in organization");return await J.storage.connections.delete(Q.id),{item:G}}})});var t80;var BY1=s(()=>{w4();x4();t80=j1({name:"CONNECTION_TEST",description:"Test connection health and latency",inputSchema:L.object({id:L.string()}),outputSchema:L.object({id:L.string(),healthy:L.boolean(),latencyMs:L.number()}),handler:async(Q,J)=>{let X=j4(J);await J.access.check();let G=await J.storage.connections.findById(Q.id);if(!G||G.organization_id!==X.id)throw Error("Connection not found");let Y=await J.storage.connections.testConnection(Q.id);return{id:Q.id,...Y}}})});var OY1=s(()=>{IX1();FY1();qY1();UY1();NY1();BY1()});import{sql as D6}from"kysely";function DY1(Q){return Q.replace(/-/g,"_")}function KC4(Q){return`app_${DY1(Q)}`}function ZC4(Q){return`app_role_${DY1(Q)}`}function HC4(Q){if(Q instanceof Error){let J=Q.message.toLowerCase(),X=Q.code;return X==="3F000"||X==="42704"||J.includes("schema")&&J.includes("does not exist")||J.includes("role")&&J.includes("does not exist")}return!1}async function FC4(Q,J,X){if(await D6`CREATE SCHEMA IF NOT EXISTS ${D6.id(J)}`.execute(Q),!(await D6`
289
+ `;if(Q===204||Q===304||Q>=100&&Q<=199)this._hasBody=!1;if(this._expect_continue&&!this._sent100)this.shouldKeepAlive=!1;let $=Y&&!Array.isArray(Y)?Y:Y;return this._storeHeader(W,$??null),this}writeHeader=this.writeHead;fetchResponse;_toFetchResponse(Q,J,X,G,Y){let W=new Headers;for(let[Z,H]of X)W.append(Z,H);let $=this,K=this._hasBody?new ReadableStream({start(Z){for(let H of G)Z.enqueue(H);if(Y)Z.close();else $.on("finish",()=>{Y=!0,Z.close()}),$.on("_dataWritten",(H)=>{if(Y)return;let F=$.dataFromDataWrittenEvent(H);Z.enqueue(F)})}}):null;if(K!=null&&typeof FixedLengthStream<"u"){let Z=parseInt(W.get("content-length")??"",10);if(Z>=0)K=K.pipeThrough(new FixedLengthStream(Z))}return new Response(K,{status:Q,statusText:J,headers:W})}}});var KX1=s(()=>{Z80();B80();$X1()});var VF;var O_=s(()=>{nJ1();KX1();VF=class VF extends s60{constructor(Q){super({...Q,sessionIdGenerator:Q?.sessionIdGenerator})}async handleMessage(Q){let{req:J,res:X}=O80(Q);return super.handleRequest(J,X,await Q.json().catch(()=>null)),D80(X)}}});var TP=(...Q)=>{return function(X,G){let Y=(W)=>{let $=Q[W];if(!$)return G();return $(X,()=>Y(W+1))};return Y(0)}};class ZX1{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?TP(...this.callToolMiddlewares):null,J=()=>{let X=new YF({name:this.config.name,version:this.config.version},{capabilities:this.config.capabilities});for(let G of this.tools){let Y=async(Z)=>{try{let H=await G.handler(Z);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(Z)=>{let H={method:"tools/call",params:{name:G.name,arguments:Z}};return await Q(H,()=>Y(Z))}:Y,$="shape"in G.inputSchema?G.inputSchema.shape:y10.object({}).shape,K=G.outputSchema&&"shape"in G.outputSchema?G.outputSchema.shape:y10.object({}).shape;X.registerTool(G.name,{annotations:G.annotations,description:G.description??"",inputSchema:$,outputSchema:K},W)}return X};return{callStreamableTool:async(X,G)=>{let Y=this.tools.find(($)=>$.name===X);if(!Y)throw Error(`Tool ${X} not found`);let W=await Y.handler(G);if(!(W instanceof Response))throw Error(`Tool ${X} returned a non-response`);return W},client:{listTools:async()=>{return{tools:this.tools.map((X)=>({name:X.name,description:X.description??"",inputSchema:bY(X.inputSchema),outputSchema:X.outputSchema?bY(X.outputSchema):void 0}))}},callTool:async(X)=>{let G=this.tools.find((Y)=>Y.name===X.name);if(!G)return{content:[{type:"text",text:"Tool not found"}]};try{let Y=await G?.handler(X.arguments??{});return{content:[{type:"text",text:JSON.stringify(Y)}],structuredContent:Y}}catch(Y){return{content:[{type:"text",text:`Error: ${Y.message}`}]}}}},fetch:async(X)=>{let G=new VF({enableJsonResponse:X.headers.get("Accept")?.includes("application/json")??!1});return await J().connect(G),await G.handleMessage(X)}}}}function HX1(Q){return new ZX1(Q)}var FX1=s(()=>{nk();w4();zP();O_()});function j1(Q){return{...Q,execute:async(J,X)=>{let G=Date.now();return await X.tracer.startActiveSpan(`tool.${Q.name}`,{attributes:{"tool.name":Q.name,"organization.id":X.organization?.id??"system","user.id":X.auth.user?.id??X.auth.apiKey?.userId??"anonymous"}},async(Y)=>{try{X.toolName=Q.name,X.access.setToolName?.(Q.name);let W=await Q.handler(J,X),$=Date.now()-G;return X.meter.createHistogram("tool.execution.duration",{description:"Duration of tool executions in milliseconds",unit:"ms"}).record($,{"tool.name":Q.name,"organization.id":X.organization?.id??"system",status:"success"}),X.meter.createCounter("tool.execution.count",{description:"Number of tool executions"}).add(1,{"tool.name":Q.name,status:"success"}),Y.setStatus({code:L80.SpanStatusCode.OK}),W}catch(W){throw X.meter.createCounter("tool.execution.errors",{description:"Number of tool execution errors"}).add(1,{"tool.name":Q.name,"error.type":W.constructor.name}),Y.setStatus({code:L80.SpanStatusCode.ERROR,message:W.message}),Y.recordException(W),W}finally{Y.end()}})}}}var L80;var x4=s(()=>{L80=p4(V1(),1)});function j4(Q){if(!Q.organization)throw Error("This operation requires organization scope");return Q.organization}function QJ(Q){return Q.auth.user?.id??Q.auth.apiKey?.userId}function FI4(Q){return!!(Q.auth.user||Q.auth.apiKey)}function u1(Q){if(!FI4(Q))throw Error("Authentication required")}var D_,qX1,VX1,zX1,UX1,NX1,BX1,OX1,DX1,LX1;var _U=s(()=>{w4();D_=L.record(L.array(L.string())),qX1=L.object({id:L.string().describe("Unique identifier for the API key"),name:L.string().describe("Human-readable name for the API key"),userId:L.string().describe("ID of the user who owns this API key"),permissions:D_.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:L.union([L.string(),L.date()]).nullable().optional().describe("Expiration date of the API key"),createdAt:L.union([L.string(),L.date()]).describe("When the API key was created")}),VX1=L.object({name:L.string().min(1).max(64).describe("Human-readable name for the API key"),permissions:D_.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:L.number().positive().optional().describe("Expiration time in seconds. If not provided, key never expires."),metadata:L.record(L.unknown()).optional().describe("Additional metadata to store with the API key")}),zX1=L.object({id:L.string().describe("Unique identifier for the API key"),name:L.string().describe("Human-readable name for the API key"),key:L.string().describe("The actual API key value. STORE THIS SECURELY - it will not be shown again!"),permissions:D_.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:L.union([L.string(),L.date()]).nullable().optional().describe("Expiration date of the API key"),createdAt:L.union([L.string(),L.date()]).describe("When the API key was created")}),UX1=L.object({}),NX1=L.object({items:L.array(qX1).describe("List of API keys (without key values)")}),BX1=L.object({keyId:L.string().describe("ID of the API key to update"),name:L.string().min(1).max(64).optional().describe("New name for the API key"),permissions:D_.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:L.record(L.unknown()).optional().describe("New metadata. Replaces existing metadata.")}),OX1=L.object({item:qX1.describe("The updated API key (without key value)")}),DX1=L.object({keyId:L.string().describe("ID of the API key to delete")}),LX1=L.object({success:L.boolean().describe("Whether the deletion was successful"),keyId:L.string().describe("ID of the deleted API key")})});var w80;var wX1=s(()=>{x4();_U();w80=j1({name:"API_KEY_CREATE",description:"Create a new API key with specified permissions. The key value is only returned once - store it securely!",inputSchema:VX1,outputSchema:zX1,handler:async(Q,J)=>{u1(J),await J.access.check();let X=await J.boundAuth.apiKey.create({name:Q.name,permissions:Q.permissions,expiresIn:Q.expiresIn,metadata:{...Q.metadata,organization:J.organization}});return{id:X.id,name:X.name??Q.name,key:X.key,permissions:X.permissions??{},expiresAt:X.expiresAt??null,createdAt:X.createdAt}}})});var P80;var PX1=s(()=>{x4();_U();P80=j1({name:"API_KEY_DELETE",description:"Delete an API key. This instantly revokes the key - it can no longer be used for authentication.",inputSchema:DX1,outputSchema:LX1,handler:async(Q,J)=>{if(u1(J),await J.access.check(),!QJ(J))throw Error("User ID required to delete API key");let Y=(await J.boundAuth.apiKey.list())?.find((Z)=>Z.id===Q.keyId);if(!Y)throw Error("API key not found");let $=Y.metadata?.organization?.id,K=J.organization?.id;if($!==K)throw Error("Cannot delete API key from another organization");return await J.boundAuth.apiKey.delete(Q.keyId),{success:!0,keyId:Q.keyId}}})});var M80;var MX1=s(()=>{x4();_U();M80=j1({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:UX1,outputSchema:NX1,handler:async(Q,J)=>{u1(J),await J.access.check();let X=await J.boundAuth.apiKey.list(),G=J.organization?.id;return{items:(X??[]).filter((W)=>{return W.metadata?.organization?.id===G}).map((W)=>({id:W.id,name:W.name??"Unnamed Key",userId:W.userId,permissions:W.permissions??{},expiresAt:W.expiresAt??null,createdAt:W.createdAt}))}}})});var T80;var TX1=s(()=>{x4();_U();T80=j1({name:"API_KEY_UPDATE",description:"Update an existing API key's name, permissions, or metadata. Note: Key value cannot be changed or retrieved.",inputSchema:BX1,outputSchema:OX1,handler:async(Q,J)=>{if(u1(J),await J.access.check(),!QJ(J))throw Error("User ID required to update API key");let Y=(await J.boundAuth.apiKey.list())?.find((H)=>H.id===Q.keyId);if(!Y)throw Error(`API key not found: ${Q.keyId}`);let $=Y.metadata?.organization?.id,K=J.organization?.id;if($!==K)throw Error("Cannot update API key from another organization");let Z=await J.boundAuth.apiKey.update({keyId:Q.keyId,name:Q.name,permissions:Q.permissions,metadata:{...Q.metadata,organization:J.organization}});if(!Z)throw Error(`Failed to update API key: ${Q.keyId}`);return{item:{id:Z.id,name:Z.name??Q.name??"Unnamed Key",userId:Z.userId,permissions:Z.permissions??{},expiresAt:Z.expiresAt??null,createdAt:Z.createdAt}}}})});var AX1=s(()=>{wX1();PX1();MX1();TX1();_U()});var VI4,zI4,mX,EX1,jX1;var yU=s(()=>{w4();VI4=L.object({authorizationEndpoint:L.string().url(),tokenEndpoint:L.string().url(),introspectionEndpoint:L.string().url().optional(),clientId:L.string(),clientSecret:L.string().optional(),scopes:L.array(L.string()),grantType:L.enum(["authorization_code","client_credentials"])}),zI4=L.object({name:L.string(),description:L.string().optional(),inputSchema:L.record(L.unknown()),outputSchema:L.record(L.unknown()).optional()}),mX=L.object({id:L.string().describe("Unique identifier for the connection"),title:L.string().describe("Human-readable name for the connection"),created_at:L.string().describe("When the connection was created"),updated_at:L.string().describe("When the connection was last updated"),created_by:L.string().describe("User ID who created the connection"),updated_by:L.string().optional().describe("User ID who last updated the connection"),organization_id:L.string().describe("Organization ID this connection belongs to"),description:L.string().nullable().describe("Description of the connection"),icon:L.string().nullable().describe("Icon URL for the connection"),app_name:L.string().nullable().describe("Associated app name"),app_id:L.string().nullable().describe("Associated app ID"),connection_type:L.enum(["HTTP","SSE","Websocket"]).describe("Type of connection"),connection_url:L.string().describe("URL for the connection"),connection_token:L.string().nullable().describe("Authentication token"),connection_headers:L.record(L.string(),L.string()).nullable().describe("Custom headers"),oauth_config:VI4.nullable().describe("OAuth configuration"),configuration_state:L.record(L.unknown()).nullable().describe("Configuration state (decrypted)"),configuration_scopes:L.array(L.string()).nullable().optional().describe("Configuration scopes"),metadata:L.record(L.unknown()).nullable().describe("Additional metadata (includes repository info)"),tools:L.array(zI4).nullable().describe("Discovered tools from MCP"),bindings:L.array(L.string()).nullable().describe("Detected bindings"),status:L.enum(["active","inactive","error"]).describe("Current status")}),EX1=mX.omit({created_at:!0,updated_at:!0,created_by:!0,updated_by:!0,organization_id:!0,tools:!0,bindings:!0,status:!0}).partial({id:!0,description:!0,icon:!0,app_name:!0,app_id:!0,connection_token:!0,connection_headers:!0,oauth_config:!0,configuration_state:!0,configuration_scopes:!0,metadata:!0}),jX1=mX.partial()});var UI4,NI4,A80;var IX1=s(()=>{pH();w4();x4();hk();yU();UI4=L.object({data:EX1.describe("Data for the new connection (id is auto-generated if not provided)")}),NI4=L.object({item:mX.describe("The created connection entity")}),A80=j1({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",inputSchema:UI4,outputSchema:NI4,handler:async(Q,J)=>{u1(J);let X=j4(J);await J.access.check();let G=QJ(J);if(!G)throw Error("User ID required to create connection");let Y={...Q.data,organization_id:X.id,created_by:G},W=await TU({id:"pending",title:Y.title,connection_url:Y.connection_url,connection_token:Y.connection_token,connection_headers:Y.connection_headers}).catch(()=>null),$=W?.length?W:null,K=await J.storage.connections.create({...Y,tools:$});return await J.eventBus.publish(X.id,XU.SELF(X.id),{type:"connection.created",data:K}),{item:K}}})});function JZ(Q){function J(X,G){if(G.description)X=X.describe(G.description);return X}if(Q.const!==void 0){if(typeof Q.const==="string")return J(L.literal(Q.const),Q);else if(typeof Q.const==="number")return J(L.literal(Q.const),Q);else if(typeof Q.const==="boolean")return J(L.literal(Q.const),Q);else if(Q.const===null)return J(L.null(),Q);return J(L.literal(Q.const),Q)}if(Q.type)switch(Q.type){case"string":{if(Q.enum){if(Q.enum.length===0)return J(L.string(),Q);return J(L.enum(Q.enum),Q)}let X=L.string();if(Q.minLength!==void 0)X=X.min(Q.minLength);if(Q.maxLength!==void 0)X=X.max(Q.maxLength);if(Q.pattern!==void 0){let G=new RegExp(Q.pattern);X=X.regex(G)}return J(X,Q)}case"number":case"integer":{if(Q.enum){if(Q.enum.length===0)return J(L.number(),Q);let G=Q.enum.map((Y)=>L.literal(Y));if(G.length===1)return J(G[0],Q);if(G.length>=2){let Y=L.union([G[0],G[1],...G.slice(2)]);return J(Y,Q)}}let X=Q.type==="integer"?L.number().int():L.number();if(Q.minimum!==void 0)X=X.min(Q.minimum);if(Q.maximum!==void 0)X=X.max(Q.maximum);if(Q.exclusiveMinimum!==void 0)X=X.gt(Q.exclusiveMinimum);if(Q.exclusiveMaximum!==void 0)X=X.lt(Q.exclusiveMaximum);if(Q.multipleOf!==void 0)X=X.multipleOf(Q.multipleOf);return J(X,Q)}case"boolean":if(Q.enum){if(Q.enum.length===0)return J(L.boolean(),Q);let X=Q.enum.map((G)=>L.literal(G));if(X.length===1)return J(X[0],Q);if(X.length>=2){let G=L.union([X[0],X[1],...X.slice(2)]);return J(G,Q)}}return J(L.boolean(),Q);case"null":return J(L.null(),Q);case"object":if(Q.properties){let X={};for(let[Y,W]of Object.entries(Q.properties))X[Y]=JZ(W);if(Q.required&&Array.isArray(Q.required)){let Y=new Set(Q.required);for(let W of Object.keys(X))if(!Y.has(W))X[W]=X[W].optional()}else for(let Y of Object.keys(X))X[Y]=X[Y].optional();let G;if(Q.additionalProperties!==!1)G=L.object(X).passthrough();else G=L.object(X);return J(G,Q)}return J(L.object({}),Q);case"array":{let X;if(Q.items)X=L.array(JZ(Q.items));else X=L.array(L.any());if(Q.minItems!==void 0)X=X.min(Q.minItems);if(Q.maxItems!==void 0)X=X.max(Q.maxItems);if(Q.uniqueItems===!0)X=X.refine((G)=>{let Y=new Set;return G.every((W)=>{if(typeof W==="string"||typeof W==="number"||typeof W==="boolean"){if(Y.has(W))return!1;return Y.add(W),!0}let $=JSON.stringify(W);if(Y.has($))return!1;return Y.add($),!0})},{message:"Array items must be unique"});return J(X,Q)}}if(Q.enum){if(Q.enum.length===0)return J(L.never(),Q);if(Q.enum.every((G)=>typeof G==="string"))return J(L.enum(Q.enum),Q);else{let G=Q.enum.map((Y)=>L.literal(Y));if(G.length===1)return J(G[0],Q);if(G.length>=2){let Y=L.union([G[0],G[1],...G.slice(2)]);return J(Y,Q)}}}if(Q.anyOf&&Q.anyOf.length>=2){let X=Q.anyOf.map(JZ);return J(L.union([X[0],X[1],...X.slice(2)]),Q)}if(Q.allOf)return J(Q.allOf.reduce((X,G)=>L.intersection(X,JZ(G)),L.object({})),Q);if(Q.oneOf&&Q.oneOf.length>=2){let X=Q.oneOf.map(JZ);return J(L.union([X[0],X[1],...X.slice(2)]),Q)}return J(L.any(),Q)}var CX1=s(()=>{w4()});function BI4(Q){let J=globalThis.DOMException;return typeof J=="function"?new J(Q,"SyntaxError"):SyntaxError(Q)}function j80(Q){return Q instanceof Error?"errors"in Q&&Array.isArray(Q.errors)?Q.errors.map(j80).join(", "):("cause"in Q)&&Q.cause instanceof Error?`${Q}: ${j80(Q.cause)}`:Q.message:`${Q}`}function RX1(Q){return{type:Q.type,message:Q.message,code:Q.code,defaultPrevented:Q.defaultPrevented,cancelable:Q.cancelable,timeStamp:Q.timeStamp}}function OI4(){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 E80,vX1=(Q)=>{throw TypeError(Q)},y80=(Q,J,X)=>J.has(Q)||vX1("Cannot "+X),g4=(Q,J,X)=>(y80(Q,J,"read from private field"),X?X.call(Q):J.get(Q)),I9=(Q,J,X)=>J.has(Q)?vX1("Cannot add the same private member more than once"):J instanceof WeakSet?J.add(Q):J.set(Q,X),b8=(Q,J,X,G)=>(y80(Q,J,"write to private field"),J.set(Q,X),X),SW=(Q,J,X)=>(y80(Q,J,"access private method"),X),JJ,zF,hU,L_,w_,jP,xU,IP,XZ,fU,gU,bU,AP,gY,I80,C80,R80,SX1,S80,v80,EP,k80,_80,uU;var kX1=s(()=>{h40();E80=class E80 extends Event{constructor(Q,J){var X,G;super(Q),this.code=(X=J==null?void 0:J.code)!=null?X:void 0,this.message=(G=J==null?void 0:J.message)!=null?G:void 0}[Symbol.for("nodejs.util.inspect.custom")](Q,J,X){return X(RX1(this),J)}[Symbol.for("Deno.customInspect")](Q,J){return Q(RX1(this),J)}};uU=class uU extends EventTarget{constructor(Q,J){var X,G;super(),I9(this,gY),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,I9(this,JJ),I9(this,zF),I9(this,hU),I9(this,L_),I9(this,w_),I9(this,jP),I9(this,xU),I9(this,IP,null),I9(this,XZ),I9(this,fU),I9(this,gU,null),I9(this,bU,null),I9(this,AP,null),I9(this,C80,async(Y)=>{var W;g4(this,fU).reset();let{body:$,redirected:K,status:Z,headers:H}=Y;if(Z===204){SW(this,gY,EP).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(K?b8(this,hU,new URL(Y.url)):b8(this,hU,void 0),Z!==200){SW(this,gY,EP).call(this,`Non-200 status code (${Z})`,Z);return}if(!(H.get("content-type")||"").startsWith("text/event-stream")){SW(this,gY,EP).call(this,'Invalid content type, expected "text/event-stream"',Z);return}if(g4(this,JJ)===this.CLOSED)return;b8(this,JJ,this.OPEN);let F=new Event("open");if((W=g4(this,AP))==null||W.call(this,F),this.dispatchEvent(F),typeof $!="object"||!$||!("getReader"in $)){SW(this,gY,EP).call(this,"Invalid response body, expected a web ReadableStream",Z),this.close();return}let q=new TextDecoder,V=$.getReader(),z=!0;do{let{done:U,value:N}=await V.read();N&&g4(this,fU).feed(q.decode(N,{stream:!U})),U&&(z=!1,g4(this,fU).reset(),SW(this,gY,k80).call(this))}while(z)}),I9(this,R80,(Y)=>{b8(this,XZ,void 0),!(Y.name==="AbortError"||Y.type==="aborted")&&SW(this,gY,k80).call(this,j80(Y))}),I9(this,S80,(Y)=>{typeof Y.id=="string"&&b8(this,IP,Y.id);let W=new MessageEvent(Y.event||"message",{data:Y.data,origin:g4(this,hU)?g4(this,hU).origin:g4(this,zF).origin,lastEventId:Y.id||""});g4(this,bU)&&(!Y.event||Y.event==="message")&&g4(this,bU).call(this,W),this.dispatchEvent(W)}),I9(this,v80,(Y)=>{b8(this,jP,Y)}),I9(this,_80,()=>{b8(this,xU,void 0),g4(this,JJ)===this.CONNECTING&&SW(this,gY,I80).call(this)});try{if(Q instanceof URL)b8(this,zF,Q);else if(typeof Q=="string")b8(this,zF,new URL(Q,OI4()));else throw Error("Invalid URL")}catch{throw BI4("An invalid or illegal string was specified")}b8(this,fU,_k({onEvent:g4(this,S80),onRetry:g4(this,v80)})),b8(this,JJ,this.CONNECTING),b8(this,jP,3000),b8(this,w_,(X=J==null?void 0:J.fetch)!=null?X:globalThis.fetch),b8(this,L_,(G=J==null?void 0:J.withCredentials)!=null?G:!1),SW(this,gY,I80).call(this)}get readyState(){return g4(this,JJ)}get url(){return g4(this,zF).href}get withCredentials(){return g4(this,L_)}get onerror(){return g4(this,gU)}set onerror(Q){b8(this,gU,Q)}get onmessage(){return g4(this,bU)}set onmessage(Q){b8(this,bU,Q)}get onopen(){return g4(this,AP)}set onopen(Q){b8(this,AP,Q)}addEventListener(Q,J,X){let G=J;super.addEventListener(Q,G,X)}removeEventListener(Q,J,X){let G=J;super.removeEventListener(Q,G,X)}close(){g4(this,xU)&&clearTimeout(g4(this,xU)),g4(this,JJ)!==this.CLOSED&&(g4(this,XZ)&&g4(this,XZ).abort(),b8(this,JJ,this.CLOSED),b8(this,XZ,void 0))}};JJ=new WeakMap,zF=new WeakMap,hU=new WeakMap,L_=new WeakMap,w_=new WeakMap,jP=new WeakMap,xU=new WeakMap,IP=new WeakMap,XZ=new WeakMap,fU=new WeakMap,gU=new WeakMap,bU=new WeakMap,AP=new WeakMap,gY=new WeakSet,I80=function(){b8(this,JJ,this.CONNECTING),b8(this,XZ,new AbortController),g4(this,w_)(g4(this,zF),SW(this,gY,SX1).call(this)).then(g4(this,C80)).catch(g4(this,R80))},C80=new WeakMap,R80=new WeakMap,SX1=function(){var Q;let J={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...g4(this,IP)?{"Last-Event-ID":g4(this,IP)}:void 0},cache:"no-store",signal:(Q=g4(this,XZ))==null?void 0:Q.signal};return"window"in globalThis&&(J.credentials=this.withCredentials?"include":"same-origin"),J},S80=new WeakMap,v80=new WeakMap,EP=function(Q,J){var X;g4(this,JJ)!==this.CLOSED&&b8(this,JJ,this.CLOSED);let G=new E80("error",{code:J,message:Q});(X=g4(this,gU))==null||X.call(this,G),this.dispatchEvent(G)},k80=function(Q,J){var X;if(g4(this,JJ)===this.CLOSED)return;b8(this,JJ,this.CONNECTING);let G=new E80("error",{code:J,message:Q});(X=g4(this,gU))==null||X.call(this,G),this.dispatchEvent(G),b8(this,xU,setTimeout(g4(this,_80),g4(this,jP)))},_80=new WeakMap,uU.CONNECTING=0,uU.OPEN=1,uU.CLOSED=2});class h80{constructor(Q,J){this._url=Q,this._resourceMetadataUrl=void 0,this._eventSourceInit=J===null||J===void 0?void 0:J.eventSourceInit,this._requestInit=J===null||J===void 0?void 0:J.requestInit,this._authProvider=J===null||J===void 0?void 0:J.authProvider,this._fetch=J===null||J===void 0?void 0:J.fetch}async _authThenStart(){var Q;if(!this._authProvider)throw new bJ("No auth provider");let J;try{J=await rK(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(X){throw(Q=this.onerror)===null||Q===void 0||Q.call(this,X),X}if(J!=="AUTHORIZED")throw new bJ;return await this._startOrAuth()}async _commonHeaders(){var Q;let J={};if(this._authProvider){let X=await this._authProvider.tokens();if(X)J.Authorization=`Bearer ${X.access_token}`}if(this._protocolVersion)J["mcp-protocol-version"]=this._protocolVersion;return new Headers({...J,...(Q=this._requestInit)===null||Q===void 0?void 0:Q.headers})}_startOrAuth(){var Q,J,X;let G=(X=(J=(Q=this===null||this===void 0?void 0:this._eventSourceInit)===null||Q===void 0?void 0:Q.fetch)!==null&&J!==void 0?J:this._fetch)!==null&&X!==void 0?X:fetch;return new Promise((Y,W)=>{this._eventSource=new uU(this._url.href,{...this._eventSourceInit,fetch:async($,K)=>{let Z=await this._commonHeaders();Z.set("Accept","text/event-stream");let H=await G($,{...K,headers:Z});if(H.status===401&&H.headers.has("www-authenticate"))this._resourceMetadataUrl=ZP(H);return H}}),this._abortController=new AbortController,this._eventSource.onerror=($)=>{var K;if($.code===401&&this._authProvider){this._authThenStart().then(Y,W);return}let Z=new _X1($.code,$.message,$);W(Z),(K=this.onerror)===null||K===void 0||K.call(this,Z)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",($)=>{var K;let Z=$;try{if(this._endpoint=new URL(Z.data,this._url),this._endpoint.origin!==this._url.origin)throw Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(H){W(H),(K=this.onerror)===null||K===void 0||K.call(this,H),this.close();return}Y()}),this._eventSource.onmessage=($)=>{var K,Z;let H=$,F;try{F=_Y.parse(JSON.parse(H.data))}catch(q){(K=this.onerror)===null||K===void 0||K.call(this,q);return}(Z=this.onmessage)===null||Z===void 0||Z.call(this,F)}})}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 bJ("No auth provider");if(await rK(this._authProvider,{serverUrl:this._url,authorizationCode:Q,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new bJ("Failed to authorize")}async close(){var Q,J,X;(Q=this._abortController)===null||Q===void 0||Q.abort(),(J=this._eventSource)===null||J===void 0||J.close(),(X=this.onclose)===null||X===void 0||X.call(this)}async send(Q){var J,X,G;if(!this._endpoint)throw Error("Not connected");try{let Y=await this._commonHeaders();Y.set("content-type","application/json");let W={...this._requestInit,method:"POST",headers:Y,body:JSON.stringify(Q),signal:(J=this._abortController)===null||J===void 0?void 0:J.signal},$=await((X=this._fetch)!==null&&X!==void 0?X:fetch)(this._endpoint,W);if(!$.ok){if($.status===401&&this._authProvider){if(this._resourceMetadataUrl=ZP($),await rK(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new bJ;return this.send(Q)}let K=await $.text().catch(()=>null);throw Error(`Error POSTing to endpoint (HTTP ${$.status}): ${K}`)}}catch(Y){throw(G=this.onerror)===null||G===void 0||G.call(this,Y),Y}}setProtocolVersion(Q){this._protocolVersion=Q}}var _X1;var yX1=s(()=>{kX1();fJ();k40();_X1=class _X1 extends Error{constructor(Q,J,X){super(`SSE error: ${J}`);this.code=Q,this.event=X}}});class f80{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,J)=>{this._socket=new WebSocket(this._url,DI4),this._socket.onerror=(X)=>{var G;let Y="error"in X?X.error:Error(`WebSocket error: ${JSON.stringify(X)}`);J(Y),(G=this.onerror)===null||G===void 0||G.call(this,Y)},this._socket.onopen=()=>{Q()},this._socket.onclose=()=>{var X;(X=this.onclose)===null||X===void 0||X.call(this)},this._socket.onmessage=(X)=>{var G,Y;let W;try{W=_Y.parse(JSON.parse(X.data))}catch($){(G=this.onerror)===null||G===void 0||G.call(this,$);return}(Y=this.onmessage)===null||Y===void 0||Y.call(this,W)}})}async close(){var Q;(Q=this._socket)===null||Q===void 0||Q.close()}send(Q){return new Promise((J,X)=>{var G;if(!this._socket){X(Error("Not connected"));return}(G=this._socket)===null||G===void 0||G.send(JSON.stringify(Q)),J()})}}var DI4="mcp";var hX1=s(()=>{fJ()});function LI4(Q){let J=Q;if(!J||typeof J!=="object"||!("method"in J))return null;switch(J.method){case"initialize":{let X=J?.params?.protocolVersion;if(!X)return null;return{type:"emit",message:{result:{protocolVersion:X,capabilities:{tools:{}},serverInfo:{name:"deco-chat-server",version:"1.0.0"}},jsonrpc:J.jsonrpc??"2.0",id:J.id}}}case"notifications/roots/list_changed":case"notifications/initialized":case"notifications/cancelled":case"notifications/progress":return{type:"suppress"};default:return null}}var b80;var fX1=s(()=>{FP();b80=class b80 extends jW{constructor(Q,J){super(Q,J)}send(Q,J){let X=LI4(Q);if(X?.type==="emit")return this.onmessage?.(X.message),Promise.resolve();if(X?.type==="suppress")return Promise.resolve();return super.send(Q,J)}}});var bX1,xX1=async(Q,J,X)=>{let G=wI4(Q.connection,J,X);if(!G)throw Error("Unknown MCP connection type");let Y=new bX1({name:Q?.name??"MCP Client",version:"1.0.0"});return await Y.connect(G),{client:Y,callStreamableTool:(W,$)=>{if(Q.connection.type!=="HTTP")throw Error("HTTP connection required");let K=new Headers(X);if(!K.has("Authorization"))K.set("Authorization",`Bearer ${Q.connection.token}`);for(let[F,q]of Object.entries(Q.connection.headers??{}))K.set(F,q);let Z=new URL(Q.connection.url),H=Z.pathname.replace(/\/+$/,"")||"/";return Z.pathname=`${H}/call-tool/${encodeURIComponent(W)}`,fetch(Z.href,{method:"POST",redirect:"manual",body:JSON.stringify($),headers:K})}}},wI4=(Q,J,X)=>{if(Q.type==="Websocket")return new f80(new URL(Q.url));if(Q.type!=="SSE"&&Q.type!=="HTTP")return null;let Y={...Q.token?{authorization:`Bearer ${Q.token}`}:{},...X??{},..."headers"in Q?Q.headers||{}:{}};if(Q.type==="SSE"){let W={requestInit:{headers:Y,signal:J}};if(Q.token)W.eventSourceInit={fetch:($,K)=>{return fetch($,{...K,headers:{...Y,Accept:"text/event-stream"},signal:J})}};return new h80(new URL(Q.url),W)}return new b80(new URL(Q.url),{requestInit:{headers:Y,signal:J,credentials:"include"}})};var gX1=s(()=>{wk();yX1();hX1();fJ();fX1();bX1=class bX1 extends JF{constructor(Q,J){super(Q,J)}async listTools(Q,J){return await this.request({method:"tools/list",params:Q},YP,J)}}});function mX1(Q){let J=(X)=>{if("connection"in Q)return xX1({connection:Q.connection},void 0,X);return Q.client};return new Proxy({},{get(X,G){if(G==="toJSON")return null;if(typeof G!=="string")throw Error("Name must be a string");if(G==="listTools")return K;async function Y(Z,H=G){let F=Q?.debugId?.(),q=F?{"x-trace-debug-id":F}:void 0,{client:V,callStreamableTool:z}=await J(q);if(Q?.streamable?.[String(H)])return z(String(H),Z);let{structuredContent:U,isError:N,content:D}=await V.callTool({name:String(H),arguments:Z});if(N){let w=D?.[0]?.text,E=typeof w==="string"?PI4(w):null,M=E?.code&&typeof Q?.getErrorByStatusCode==="function"?Q.getErrorByStatusCode(E.code,E.message,E.traceId):null;if(M)throw M;throw Error(`Tool ${String(H)} returned an error: ${JSON.stringify(U??D)}`)}return U}async function W(){let{client:Z}=await J(),{tools:H}=await Z.listTools();return H}async function $(){if(!("connection"in Q))return W();let Z=Q.connection,H=JSON.stringify(Z);try{if(!P_.has(H))P_.set(H,W());return await P_.get(H)}catch(F){console.error("Failed to list tools",F),P_.delete(H);return}}async function K(){return(await $()??[]).map((H)=>uX1(H,Y))}return Y.asTool=async()=>{let H=(await $()??[]).find((F)=>F.name===G);if(!H)throw Error(`Tool ${G} not found`);return uX1(H,Y)},Y}})}var PI4=(Q)=>{try{return JSON.parse(Q)}catch{return Q}},P_,uX1=(Q,J)=>{return{...Q,id:Q.name,inputSchema:Q.inputSchema?JZ(Q.inputSchema):void 0,outputSchema:Q.outputSchema?JZ(Q.outputSchema):void 0,execute:(X)=>{return J(X.context,Q.name)}}};var lX1=s(()=>{CX1();gX1();P_=new Map});function M_(Q){return mX1(Q)}var uk6;var dX1=s(()=>{lX1();uk6=new Proxy({},{get(Q,J){if(J==="toJSON")return null;if(J==="forConnection")return(X)=>M_({connection:X});return global[J]}})});function T_(Q){return{isImplementedBy:(J)=>{for(let X of Q){let G=typeof X.name==="string"?new RegExp(`^${X.name}$`):X.name,Y=J.find((W)=>G.test(W.name));if(!Y&&X.opt)continue;if(!Y)return!1}return!0}}}var mU=(Q)=>{return{...T_(Q),forClient:(J)=>{return M_({client:J,streamable:Q.reduce((X,G)=>{return X[G.name]=G.streamable===!0,X},{})})},forConnection:(J)=>{return M_({connection:J,streamable:Q.reduce((X,G)=>{return X[G.name]=G.streamable===!0,X},{})})}}};var CP=s(()=>{dX1()});function SP(Q){return L.object({items:L.array(Q).describe("Array of collection items"),totalCount:L.number().int().min(0).optional().describe("Total number of matching items (if available)"),hasMore:L.boolean().optional().describe("Whether there are more items available")})}function g80(Q){return L.object({item:Q.nullable().describe("The retrieved item, or null if not found")})}function AI4(Q){return L.object({data:Q.partial().describe("Data for the new entity (id may be auto-generated)")})}function EI4(Q){return L.object({item:Q.describe("The created entity with generated id")})}function jI4(Q){return L.object({id:L.string().describe("ID of the entity to update"),data:Q.partial().describe("Partial entity data to update")})}function II4(Q){return L.object({item:Q.describe("The updated entity")})}function m80(Q){return L.object({item:Q.describe("The deleted entity")})}function dU(Q,J,X){let G=Q.toUpperCase(),Y=X?.readOnly??!1,W=[{name:`COLLECTION_${G}_LIST`,inputSchema:RP,outputSchema:SP(J)},{name:`COLLECTION_${G}_GET`,inputSchema:x80,outputSchema:g80(J)}];if(!Y)W.push({name:`COLLECTION_${G}_CREATE`,inputSchema:AI4(J),outputSchema:EI4(J),opt:!0},{name:`COLLECTION_${G}_UPDATE`,inputSchema:jI4(J),outputSchema:II4(J),opt:!0},{name:`COLLECTION_${G}_DELETE`,inputSchema:u80,outputSchema:m80(J),opt:!0});return W}var lU,MI4,pX1,TI4,RP,x80,u80;var YZ=s(()=>{w4();lU=L.object({id:L.string().describe("Unique identifier for the entity"),title:L.string().describe("Human-readable title for the entity"),description:L.string().nullish().describe("Description of the entity"),created_at:L.string().datetime(),updated_at:L.string().datetime(),created_by:L.string().optional(),updated_by:L.string().optional()}),MI4=L.object({field:L.array(L.string()),operator:L.enum(["eq","gt","gte","lt","lte","in","like","contains"]),value:L.unknown()}),pX1=L.lazy(()=>L.union([MI4,L.object({operator:L.enum(["and","or","not"]),conditions:L.array(pX1)})])),TI4=L.object({field:L.array(L.string()),direction:L.enum(["asc","desc"]),nulls:L.enum(["first","last"]).optional()}),RP=L.object({where:pX1.optional().describe("Filter expression"),orderBy:L.array(TI4).optional().describe("Sort expressions"),limit:L.number().int().min(1).max(1000).optional().describe("Maximum number of items to return"),offset:L.number().int().min(0).optional().describe("Number of items to skip")});x80=L.object({id:L.string().describe("ID of the entity to retrieve")});u80=L.object({id:L.string().describe("ID of the entity to delete")})});var CI4,cX1,ak6;var nX1=s(()=>{w4();YZ();CI4=L.object({id:L.string(),name:L.string(),description:L.string().optional(),inputSchema:L.record(L.unknown()),outputSchema:L.record(L.unknown()).optional()}),cX1=lU.extend({_meta:L.object({"io.decocms":L.object({id:L.string(),verified:L.boolean(),scopeName:L.string(),appName:L.string(),friendlyName:L.string().nullable().optional(),metadata:L.record(L.unknown()).nullable().optional(),publishedAt:L.string().datetime().optional(),updatedAt:L.string().datetime().optional(),tools:L.array(CI4).nullable().optional().describe("Available tools exposed by this app")}).optional()}).optional(),server:L.object({$schema:L.string().optional(),_meta:L.record(L.unknown()).optional(),name:L.string().describe("The server name (scope/app)"),title:L.string().optional().describe("User-friendly title"),description:L.string().optional().describe("Server description"),icons:L.array(L.object({src:L.string(),mimeType:L.string().optional(),sizes:L.array(L.string()).optional(),theme:L.enum(["light","dark"]).optional()})).optional(),remotes:L.array(L.object({type:L.enum(["http","stdio","sse"]),url:L.string().optional(),headers:L.array(L.unknown()).optional()})).optional(),packages:L.array(L.unknown()).optional(),repository:L.object({url:L.string(),source:L.string().optional(),subfolder:L.string().optional()}).optional(),version:L.string().optional(),websiteUrl:L.string().optional()})}),ak6=dU("registry_app",cX1,{readOnly:!0})});var iX1,rX1,aX1,oX1,sX1,l80;var tX1=s(()=>{w4();CP();iX1=L.object({specversion:L.literal("1.0").describe("CloudEvents specification version"),id:L.string().describe("Unique identifier for this event (UUID recommended)"),source:L.string().describe("Connection ID of the event publisher"),type:L.string().describe("Event type (e.g., 'order.created', 'user.signup')"),time:L.string().datetime().optional().describe("Timestamp of when the event occurred (ISO 8601)"),subject:L.string().optional().describe("Subject/resource identifier (e.g., order ID, user ID)"),datacontenttype:L.string().optional().default("application/json").describe("Content type of the data attribute"),dataschema:L.string().url().optional().describe("URI to the schema for the data attribute"),data:L.unknown().optional().describe("Event payload (any JSON value)")}),rX1=L.object({events:L.array(iX1).min(1).describe("Batch of CloudEvents to process")}),aX1=L.object({success:L.boolean().optional().describe("Whether this event was processed successfully"),error:L.string().optional().describe("Error message for this event"),retryAfter:L.number().int().positive().optional().describe("Re-deliver this event after this many ms")}),oX1=L.object({success:L.boolean().optional().describe("Batch success - applies to events not in results"),error:L.string().optional().describe("Batch error message - applies to events not in results"),processedCount:L.number().int().min(0).optional().describe("Number of events successfully processed"),retryAfter:L.number().int().positive().optional().describe("Batch retryAfter - applies to events not in results"),results:L.record(L.string(),aX1).optional().describe("Per-event results keyed by event ID")}),sX1=[{name:"ON_EVENTS",inputSchema:rX1,outputSchema:oX1}],l80=mU(sX1)});var vP,kP,_P,yP,eX1,QY1,hP,fP,bP,xP,gP,uP,mP,lP,JY1,RI4;var XY1=s(()=>{w4();CP();vP=L.object({type:L.string().min(1).max(255).describe("Event type identifier"),subject:L.string().max(255).optional().describe("Subject/resource identifier (e.g., order ID)"),data:L.unknown().optional().describe("Event payload"),deliverAt:L.string().datetime().optional().describe("Scheduled delivery time (ISO 8601). Omit for immediate delivery."),cron:L.string().max(100).optional().describe("Cron expression for recurring delivery. Use EVENT_CANCEL to stop.")}),kP=L.object({id:L.string().describe("Unique event ID"),type:L.string().describe("Event type"),source:L.string().describe("Source connection ID"),time:L.string().describe("Event timestamp")}),_P=L.object({eventType:L.string().min(1).max(255).describe("Event type to subscribe to"),publisher:L.string().optional().describe("Filter events by publisher connection ID"),filter:L.string().max(1000).optional().describe("JSONPath filter expression on event data")}),yP=L.object({subscription:L.object({id:L.string().describe("Subscription ID"),connectionId:L.string().describe("Subscriber connection ID"),eventType:L.string().describe("Event type pattern"),publisher:L.string().nullable().describe("Publisher connection filter"),filter:L.string().nullable().describe("JSONPath filter expression"),enabled:L.boolean().describe("Whether subscription is enabled"),createdAt:L.union([L.string(),L.date()]).describe("Created timestamp"),updatedAt:L.union([L.string(),L.date()]).describe("Updated timestamp")})}),eX1=L.object({eventType:L.string().min(1).max(255).describe("Event type to subscribe to"),publisher:L.string().optional().describe("Filter events by publisher connection ID"),filter:L.string().max(1000).optional().describe("JSONPath filter expression on event data")}),QY1=L.object({id:L.string().describe("Subscription ID"),connectionId:L.string().describe("Subscriber connection ID"),eventType:L.string().describe("Event type pattern"),publisher:L.string().nullable().describe("Publisher connection filter"),filter:L.string().nullable().describe("JSONPath filter expression"),enabled:L.boolean().describe("Whether subscription is enabled"),createdAt:L.union([L.string(),L.date()]).describe("Created timestamp"),updatedAt:L.union([L.string(),L.date()]).describe("Updated timestamp")}),hP=L.object({subscriptions:L.array(eX1).describe("Desired subscriptions - system will create/update/delete to match")}),fP=L.object({created:L.number().int().min(0).describe("Number of subscriptions created"),updated:L.number().int().min(0).describe("Number of subscriptions with filter updated"),deleted:L.number().int().min(0).describe("Number of subscriptions removed"),unchanged:L.number().int().min(0).describe("Number of subscriptions unchanged"),subscriptions:L.array(QY1).describe("Current subscriptions after sync")}),bP=L.object({subscriptionId:L.string().describe("Subscription ID to remove")}),xP=L.object({success:L.boolean().describe("Whether unsubscribe was successful"),subscriptionId:L.string().describe("Subscription ID that was removed")}),gP=L.object({eventId:L.string().describe("Event ID to cancel")}),uP=L.object({success:L.boolean().describe("Whether cancellation was successful"),eventId:L.string().describe("Event ID that was cancelled")}),mP=L.object({eventId:L.string().describe("Event ID to acknowledge")}),lP=L.object({success:L.boolean().describe("Whether ACK was successful"),eventId:L.string().describe("Event ID that was acknowledged")}),JY1=[{name:"EVENT_PUBLISH",inputSchema:vP,outputSchema:kP},{name:"EVENT_SUBSCRIBE",inputSchema:_P,outputSchema:yP},{name:"EVENT_UNSUBSCRIBE",inputSchema:bP,outputSchema:xP},{name:"EVENT_CANCEL",inputSchema:gP,outputSchema:uP},{name:"EVENT_ACK",inputSchema:mP,outputSchema:lP},{name:"EVENT_SYNC_SUBSCRIPTIONS",inputSchema:hP,outputSchema:fP}],RI4=mU(JY1)});var A_=s(()=>{CP();nX1();tX1();XY1()});var SI4,vI4,YY1;var GY1=s(()=>{w4();YZ();SI4=lU.extend({avatar:L.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:L.string().describe("System prompt that defines the assistant's behavior"),gateway_id:L.string().describe("Gateway ID to use for this assistant"),model:L.object({id:L.string().describe("Model ID"),connectionId:L.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),vI4=dU("assistant",SI4),YY1=[...vI4]});var dP,vW,$Y1,kI4,KY1,_I4,yI4,hI4,ZY1,fI4,bI4,xI4,gI4,uI4,mI4,lI4,dI4,N_6,pI4,B_6,WY1,cI4,nI4,d80,HY1;var p80=s(()=>{w4();CP();YZ();dP=L.lazy(()=>L.union([L.null(),L.string(),L.number(),L.boolean(),L.record(L.string(),dP),L.array(dP)])),vW=L.record(L.string(),L.record(L.string(),dP)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),$Y1=L.object({type:L.literal("text"),text:L.string().describe("The text content"),providerOptions:vW}),kI4=L.union([L.string(),L.instanceof(Uint8Array)]).describe("File data as base64 encoded string, URL string, or Uint8Array"),KY1=L.object({type:L.literal("file"),filename:L.string().optional().describe("Optional filename of the file"),data:kI4,mediaType:L.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:vW}),_I4=L.object({type:L.literal("reasoning"),text:L.string().describe("The reasoning text"),providerOptions:vW}),yI4=L.object({type:L.literal("tool-call"),toolCallId:L.string().describe("ID of the tool call, used to match with tool result"),toolName:L.string().describe("Name of the tool being called"),input:L.unknown().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:L.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:vW}),hI4=L.union([L.object({type:L.literal("text"),value:L.string()}),L.object({type:L.literal("json"),value:dP}),L.object({type:L.literal("error-text"),value:L.string()}),L.object({type:L.literal("error-json"),value:dP}),L.object({type:L.literal("content"),value:L.array(L.union([L.object({type:L.literal("text"),text:L.string().describe("Text content")}),L.object({type:L.literal("media"),data:L.string().describe("Base-64 encoded media data"),mediaType:L.string().describe("IANA media type")})]))})]),ZY1=L.object({type:L.literal("tool-result"),toolCallId:L.string().describe("ID of the tool call that this result is associated with"),toolName:L.string().describe("Name of the tool that generated this result"),output:hI4.describe("Result of the tool call"),providerOptions:vW}),fI4=L.object({role:L.literal("system"),content:L.string().describe("System message content"),providerOptions:vW}),bI4=L.object({role:L.literal("user"),content:L.array(L.union([$Y1,KY1])).describe("User message content parts (text or file)"),providerOptions:vW}),xI4=L.object({role:L.literal("assistant"),content:L.array(L.union([$Y1,KY1,_I4,yI4,ZY1])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:vW}),gI4=L.object({role:L.literal("tool"),content:L.array(ZY1).describe("Tool message content (tool results)"),providerOptions:vW}),uI4=L.union([fI4,bI4,xI4,gI4]),mI4=L.array(uI4).describe("A list of messages forming the prompt"),lI4=L.object({prompt:mI4.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:L.number().optional().describe("Maximum number of tokens to generate"),temperature:L.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:L.number().optional().describe("Nucleus sampling parameter"),topK:L.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:L.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:L.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:L.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:L.array(L.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:L.union([L.object({type:L.literal("text")}),L.object({type:L.literal("json"),schema:L.any().optional().describe("JSON schema that the generated output should conform to"),name:L.string().optional().describe("Name of output that should be generated"),description:L.string().optional().describe("Description of the output that should be generated")})]).optional().describe("Response format. The output can either be text or JSON. Default is text"),tools:L.array(L.any()).optional().describe("The tools that are available for the model"),toolChoice:L.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:L.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:L.any().optional().describe("Abort signal for cancelling the operation"),headers:L.record(L.string(),L.union([L.string(),L.undefined()])).optional().describe("Additional HTTP headers to be sent with the request"),providerOptions:L.any().optional().describe("Additional provider-specific options")}),dI4=L.object({content:L.array(L.any()).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:L.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:L.object({inputTokens:L.number().optional(),outputTokens:L.number().optional(),totalTokens:L.number().optional(),reasoningTokens:L.number().optional()}).passthrough().transform((Q)=>({inputTokens:Q.inputTokens,outputTokens:Q.outputTokens,totalTokens:Q.totalTokens,reasoningTokens:Q.reasoningTokens,...Q})).describe("Usage information for the language model call"),providerMetadata:L.any().optional().describe("Additional provider-specific metadata"),request:L.object({body:L.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:L.object({id:L.string().optional().describe("ID for the generated response"),timestamp:L.date().optional().describe("Timestamp for the start of the generated response"),modelId:L.string().optional().describe("The ID of the response model that was used"),headers:L.record(L.string(),L.string()).optional().describe("Response headers"),body:L.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:L.array(L.any()).describe("Warnings for the call, e.g. unsupported settings")}),N_6=L.object({stream:L.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:L.object({body:L.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:L.object({headers:L.record(L.string(),L.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),pI4=L.object({supportedUrls:L.record(L.string(),L.array(L.string())).describe("Supported URL patterns by media type for the provider")}),B_6=L.object({modelId:L.string().describe("The ID of the model"),logo:L.string().nullable(),description:L.string().nullable(),capabilities:L.array(L.string()),limits:L.object({contextWindow:L.number(),maxOutputTokens:L.number()}).nullable(),costs:L.object({input:L.number(),output:L.number()}).nullable(),provider:L.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),WY1=L.object({modelId:L.string().describe("The ID of the model"),callOptions:lI4}),cI4=lU.extend({logo:L.string().nullable(),description:L.string().nullable(),capabilities:L.array(L.string()),limits:L.object({contextWindow:L.number(),maxOutputTokens:L.number()}).nullable(),costs:L.object({input:L.number(),output:L.number()}).nullable(),provider:L.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),nI4=dU("llm",cI4,{readOnly:!0}),d80=[{name:"LLM_METADATA",inputSchema:L.object({modelId:L.string().describe("The ID of the model")}),outputSchema:pI4},{name:"LLM_DO_STREAM",inputSchema:WY1,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:WY1,outputSchema:dI4},...nI4],HY1=mU(d80)});function rI4(Q){let J=[],X=0;while(X<Q.length){let G=Q[X];if(G==="%")J.push(".*");else if(G==="_")J.push(".");else if(/[.*+?^${}()|[\]\\]/.test(G))J.push("\\"+G);else J.push(G);X++}return J.join("")}function GZ(Q){return typeof Q==="string"||typeof Q==="number"}function E_(Q,J){if("conditions"in J){let{operator:K,conditions:Z}=J;switch(K){case"and":return Z.every((H)=>E_(Q,H));case"or":return Z.some((H)=>E_(Q,H));case"not":return!Z.every((H)=>E_(Q,H));default:return!0}}let{field:X,operator:G,value:Y}=J,W=X.join("."),$=c80(Q,W);switch(G){case"eq":return $===Y;case"gt":return GZ($)&&GZ(Y)&&$>Y;case"gte":return GZ($)&&GZ(Y)&&$>=Y;case"lt":return GZ($)&&GZ(Y)&&$<Y;case"lte":return GZ($)&&GZ(Y)&&$<=Y;case"in":return Array.isArray(Y)&&Y.includes($);case"like":if(typeof $!=="string"||typeof Y!=="string")return!1;if(Y.length>100)return!1;let K=rI4(Y);return new RegExp(`^${K}$`,"i").test($);case"contains":if(typeof $!=="string"||typeof Y!=="string")return!1;return $.toLowerCase().includes(Y.toLowerCase());default:return!0}}function c80(Q,J){let X=J.split("."),G=Q;for(let Y of X){if(G==null||typeof G!=="object")return;G=G[Y]}return G}function aI4(Q,J){return[...Q].sort((X,G)=>{for(let Y of J){let W=Y.field.join("."),$=c80(X,W),K=c80(G,W),Z=0;if($==null&&K==null)continue;if($==null)Z=Y.nulls==="first"?-1:1;else if(K==null)Z=Y.nulls==="first"?1:-1;else if(typeof $==="string"&&typeof K==="string")Z=$.localeCompare(K);else if(typeof $==="number"&&typeof K==="number")Z=$-K;else Z=String($).localeCompare(String(K));if(Z!==0)return Y.direction==="desc"?-Z:Z}return 0})}var iI4,oI4,sI4,n80;var FY1=s(()=>{A_();GY1();YZ();p80();w4();x4();yU();iI4={LLM:d80,ASSISTANTS:YY1};oI4=RP.extend({binding:L.union([L.object({}).passthrough(),L.string()]).optional()}),sI4=SP(mX),n80=j1({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",inputSchema:oI4,outputSchema:sI4,handler:async(Q,J)=>{await J.access.check();let X=j4(J),G=Q.binding?typeof Q.binding==="string"?(()=>{let V=iI4[Q.binding.toUpperCase()];if(!V)throw Error(`Unknown binding: ${Q.binding}`);return V})():Q.binding:void 0,Y=G?T_(G):void 0,W=await J.storage.connections.list(X.id),$=Y?await Promise.all(W.map(async(V)=>{if(!V.tools||V.tools.length===0)return null;return Y.isImplementedBy(V.tools.map((U)=>({name:U.name,inputSchema:U.inputSchema,outputSchema:U.outputSchema})))?V:null})).then((V)=>V.filter((z)=>z!==null)):W;if(Q.where)$=$.filter((V)=>E_(V,Q.where));if(Q.orderBy&&Q.orderBy.length>0)$=aI4($,Q.orderBy);let K=$.length,Z=Q.offset??0,H=Q.limit??100,F=$.slice(Z,Z+H),q=Z+H<K;return{items:F,totalCount:K,hasMore:q}}})});var tI4,i80;var qY1=s(()=>{YZ();x4();yU();tI4=g80(mX),i80=j1({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",inputSchema:x80,outputSchema:tI4,handler:async(Q,J)=>{let X=j4(J);await J.access.check();let G=await J.storage.connections.findById(Q.id);if(!G||G.organization_id!==X.id)return{item:null};return{item:G}}})});var j_=(Q,J)=>{if(J===null||J===void 0)return;let X=Q.replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),G=J;for(let Y of X){if(G===null||G===void 0||typeof G!=="object")return;G=G[Y]}return G};function VY1(Q){let J=Q.split("::");if(J.length!==2||!J[0]||!J[1])throw Error(`Invalid scope format: ${Q}. Expected format: "KEY::SCOPE"`);return J}function eI4(Q){let J=Q.split("::");if(J.length!==2||!J[0]||!J[1])return null;return J}function QC4(Q){if(typeof Q==="object"&&Q!==null&&"value"in Q){let J=Q.value;if(typeof J==="string")return J}return null}function r80(Q,J){let X={};if(!Q||!J)return X;for(let G of J){let Y=eI4(G);if(!Y)continue;let[W,$]=Y,K=j_(W,Q),Z=QC4(K);if(Z){if(!X[Z])X[Z]=[];X[Z].push($)}}return X}function zY1(Q,J){let X=r80(Q,J);return new Set(Object.keys(X))}var a80=()=>{};async function YC4(Q,J,X,G){for(let W of J){let[$]=VY1(W),K=j_($,Q);if(K===void 0||K===null)throw Error(`Scope references key "${$}" but it's not present in state`)}let Y=zY1(Q,J);for(let W of Y){if(W===IY.SELF)continue;let $=await G.storage.connections.findById(W);if(!$||$.organization_id!==X)throw Error(`Referenced connection not found: ${W}`);try{await G.access.check(W)}catch(K){throw Error(`Access denied to referenced connection: ${W}. ${K.message}`)}}}var JC4,XC4,o80;var UY1=s(()=>{a80();pH();w4();x4();hk();yU();JC4=L.object({id:L.string().describe("ID of the connection to update"),data:jX1.describe("Partial connection data to update")}),XC4=L.object({item:mX.describe("The updated connection entity")});o80=j1({name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update an existing MCP connection in the organization",inputSchema:JC4,outputSchema:XC4,handler:async(Q,J)=>{u1(J);let X=j4(J);await J.access.check();let{id:G,data:Y}=Q,W=await J.storage.connections.findById(G);if(!W||W.organization_id!==X.id)throw Error("Connection not found in organization");let $=Y.configuration_state??W.configuration_state,K=Y.configuration_scopes??W.configuration_scopes??[];if(Y.configuration_state!==void 0||Y.configuration_scopes!==void 0){if(Y.configuration_state!==void 0)$=Y.configuration_state;else if($===null)$={};if(Y.configuration_scopes!==void 0)K=Y.configuration_scopes??[];if(K.length>0&&$)await YC4($,K,X.id,J)}let Z=await TU({id:W.id,title:Y.title??W.title,connection_url:Y.connection_url??W.connection_url,connection_token:Y.connection_token??W.connection_token,connection_headers:Y.connection_headers??W.connection_headers}).catch(()=>null),H=Z?.length?Z:null,F={...Y,tools:H,configuration_state:$,configuration_scopes:K},q=await J.storage.connections.update(G,F);if((Y.configuration_state!==void 0||Y.configuration_scopes!==void 0)&&$&&K.length>0)try{await(await J.createMCPProxy(G)).client.callTool({name:"ON_MCP_CONFIGURATION",arguments:{state:$,scopes:K}})}catch(V){console.error("Failed to invoke ON_MCP_CONFIGURATION callback",V)}return{item:q}}})});var s80;var NY1=s(()=>{YZ();x4();yU();s80=j1({name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete a connection",inputSchema:u80,outputSchema:m80(mX),handler:async(Q,J)=>{u1(J);let X=j4(J);await J.access.check();let G=await J.storage.connections.findById(Q.id);if(!G)throw Error(`Connection not found: ${Q.id}`);if(G.organization_id!==X.id)throw Error("Connection not found in organization");return await J.storage.connections.delete(Q.id),{item:G}}})});var t80;var BY1=s(()=>{w4();x4();t80=j1({name:"CONNECTION_TEST",description:"Test connection health and latency",inputSchema:L.object({id:L.string()}),outputSchema:L.object({id:L.string(),healthy:L.boolean(),latencyMs:L.number()}),handler:async(Q,J)=>{let X=j4(J);await J.access.check();let G=await J.storage.connections.findById(Q.id);if(!G||G.organization_id!==X.id)throw Error("Connection not found");let Y=await J.storage.connections.testConnection(Q.id);return{id:Q.id,...Y}}})});var OY1=s(()=>{IX1();FY1();qY1();UY1();NY1();BY1()});import{sql as D6}from"kysely";function DY1(Q){return Q.replace(/-/g,"_")}function KC4(Q){return`app_${DY1(Q)}`}function ZC4(Q){return`app_role_${DY1(Q)}`}function HC4(Q){if(Q instanceof Error){let J=Q.message.toLowerCase(),X=Q.code;return X==="3F000"||X==="42704"||J.includes("schema")&&J.includes("does not exist")||J.includes("role")&&J.includes("does not exist")}return!1}async function FC4(Q,J,X){if(await D6`CREATE SCHEMA IF NOT EXISTS ${D6.id(J)}`.execute(Q),!(await D6`
290
290
  SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${X}) as exists
291
291
  `.execute(Q)).rows[0]?.exists)await D6`CREATE ROLE ${D6.id(X)} NOLOGIN`.execute(Q);await D6`GRANT USAGE, CREATE ON SCHEMA ${D6.id(J)} TO ${D6.id(X)}`.execute(Q),await D6`GRANT ALL ON ALL TABLES IN SCHEMA ${D6.id(J)} TO ${D6.id(X)}`.execute(Q),await D6`GRANT ALL ON ALL SEQUENCES IN SCHEMA ${D6.id(J)} TO ${D6.id(X)}`.execute(Q),await D6`ALTER DEFAULT PRIVILEGES IN SCHEMA ${D6.id(J)} GRANT ALL ON TABLES TO ${D6.id(X)}`.execute(Q),await D6`ALTER DEFAULT PRIVILEGES IN SCHEMA ${D6.id(J)} GRANT ALL ON SEQUENCES TO ${D6.id(X)}`.execute(Q),await D6`REVOKE ALL ON SCHEMA public FROM ${D6.id(X)}`.execute(Q)}async function qC4(Q,J,X,G){try{return await Q.transaction().execute(async(Y)=>{return await D6`SET LOCAL ROLE ${D6.id(X)}`.execute(Y),await D6`SET LOCAL search_path TO ${D6.id(J)}`.execute(Y),await D6.raw(G).execute(Y)})}catch(Y){if(HC4(Y))return await FC4(Q,J,X),await Q.transaction().execute(async(W)=>{return await D6`SET LOCAL ROLE ${D6.id(X)}`.execute(W),await D6`SET LOCAL search_path TO ${D6.id(J)}`.execute(W),await D6.raw(G).execute(W)});throw Y}}var WC4,$C4,LY1;var wY1=s(()=>{w4();x4();WC4=L.object({results:L.array(L.unknown()).optional(),success:L.boolean().optional()}),$C4=L.object({sql:L.string().describe("The SQL query to run"),params:L.array(L.any()).describe("The parameters to pass to the SQL query").optional()});LY1=j1({name:"DATABASES_RUN_SQL",description:"Run a SQL query against the database",inputSchema:$C4,outputSchema:L.lazy(()=>L.object({result:L.array(WC4)})),handler:async(Q,J)=>{if(u1(J),await J.access.check(),!J.connectionId)throw Error("Connection context required for database access");let X=KC4(J.connectionId),G=ZC4(J.connectionId),Y=Q.sql;for(let $=0;$<(Q.params?.length??0);$++){let K=Q.params?.[$];Y=Y.replace("?",typeof K==="string"?`'${K}'`:`${K}`)}return{result:[{results:(await qC4(J.db,X,G,Y)).rows,success:!0}]}}})});var PY1,zC4,MY1;var kW=s(()=>{w4();A_();PY1=L.object({connectionId:L.string().optional().describe("Filter subscriptions by connection ID (optional)")}),zC4=L.object({id:L.string().describe("Subscription ID"),connectionId:L.string().describe("Subscriber connection ID"),eventType:L.string().describe("Event type pattern"),publisher:L.string().nullable().describe("Publisher connection filter (null = all publishers)"),filter:L.string().nullable().describe("JSONPath filter expression"),enabled:L.boolean().describe("Whether subscription is enabled"),createdAt:L.union([L.string(),L.date()]).describe("Created timestamp"),updatedAt:L.union([L.string(),L.date()]).describe("Updated timestamp")}),MY1=L.object({subscriptions:L.array(zC4).describe("List of subscriptions")})});var e80;var TY1=s(()=>{x4();kW();e80=j1({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:vP,outputSchema:kP,handler:async(Q,J)=>{u1(J);let X=j4(J);await J.access.check();let G=J.connectionId;if(!G)throw Error("Connection ID required to publish events. Use a connection-scoped token.");let Y=await J.eventBus.publish(X.id,G,{type:Q.type,subject:Q.subject,data:Q.data,deliverAt:Q.deliverAt,cron:Q.cron});return{id:Y.id,type:Y.type,source:Y.source,time:Y.time}}})});var Q90;var AY1=s(()=>{x4();kW();Q90=j1({name:"EVENT_SUBSCRIBE",description:"Subscribe to events of a specific type. The subscriber is automatically set to the caller's connection.",inputSchema:_P,outputSchema:yP,handler:async(Q,J)=>{u1(J);let X=j4(J);await J.access.check();let G=J.connectionId;if(!G)throw Error("Connection ID required to subscribe. Use a connection-scoped token.");let Y=await J.eventBus.subscribe(X.id,{connectionId:G,eventType:Q.eventType,publisher:Q.publisher,filter:Q.filter});return{subscription:{id:Y.id,connectionId:Y.connectionId,eventType:Y.eventType,publisher:Y.publisher,filter:Y.filter,enabled:Y.enabled,createdAt:Y.createdAt,updatedAt:Y.updatedAt}}}})});var J90;var EY1=s(()=>{x4();kW();J90=j1({name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events by removing a subscription.",inputSchema:bP,outputSchema:xP,handler:async(Q,J)=>{u1(J);let X=j4(J);await J.access.check();let G=J.connectionId;if(!G)throw Error("Connection ID required to unsubscribe. Use a connection-scoped token.");let Y=await J.eventBus.getSubscription(X.id,Q.subscriptionId);if(!Y)throw Error(`Subscription not found: ${Q.subscriptionId}`);if(Y.connectionId!==G)throw Error("Cannot unsubscribe from a subscription owned by another connection");return{success:(await J.eventBus.unsubscribe(X.id,Q.subscriptionId)).success,subscriptionId:Q.subscriptionId}}})});var X90;var jY1=s(()=>{x4();kW();X90=j1({name:"EVENT_CANCEL",description:"Cancel a recurring event to stop future deliveries. Only the publisher can cancel their own events.",inputSchema:gP,outputSchema:uP,handler:async(Q,J)=>{u1(J);let X=j4(J);await J.access.check();let G=J.connectionId;if(!G)throw Error("Connection ID required to cancel events. Use a connection-scoped token.");if(!await J.eventBus.getEvent(X.id,Q.eventId))throw Error(`Event not found: ${Q.eventId}`);if(!(await J.eventBus.cancelEvent(X.id,Q.eventId,G)).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 Y90;var IY1=s(()=>{x4();kW();Y90=j1({name:"EVENT_ACK",description:"Acknowledge delivery of an event. Call after successfully processing an event received via ON_EVENTS with retryAfter.",inputSchema:mP,outputSchema:lP,handler:async(Q,J)=>{u1(J);let X=j4(J);await J.access.check();let G=J.connectionId;if(!G)throw Error("Connection ID required to acknowledge events. Use a connection-scoped token.");if(!(await J.eventBus.ackEvent(X.id,Q.eventId,G)).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 G90;var CY1=s(()=>{x4();kW();G90=j1({name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions, optionally filtered by connection ID.",inputSchema:PY1,outputSchema:MY1,handler:async(Q,J)=>{u1(J);let X=j4(J);return await J.access.check(),{subscriptions:(await J.eventBus.listSubscriptions(X.id,Q.connectionId)).map((Y)=>({id:Y.id,connectionId:Y.connectionId,eventType:Y.eventType,publisher:Y.publisher,filter:Y.filter,enabled:Y.enabled,createdAt:Y.createdAt,updatedAt:Y.updatedAt}))}}})});var W90;var RY1=s(()=>{pH();x4();kW();W90=j1({name:"EVENT_SYNC_SUBSCRIPTIONS",description:"Sync subscriptions to desired state. Creates new, deletes removed, updates changed filters. Subscriptions are identified by (eventType, publisher).",inputSchema:hP,outputSchema:fP,handler:async(Q,J)=>{u1(J);let X=j4(J);await J.access.check();let G=J.connectionId;if(!G)throw Error("Connection ID required to sync subscriptions. Use a connection-scoped token.");let Y=await J.eventBus.syncSubscriptions(X.id,{connectionId:G,subscriptions:Q.subscriptions}),W=Y.subscriptions.filter(($)=>$.eventType?.startsWith("cron/")&&$.publisher===XU.SELF(X.id));return await Promise.all(W.map(async($)=>{let K=$.eventType.split("/")[1];K&&await J.eventBus.publish(X.id,XU.SELF(X.id),{type:$.eventType,cron:K,data:{}})})),{created:Y.created,updated:Y.updated,deleted:Y.deleted,unchanged:Y.unchanged,subscriptions:Y.subscriptions.map(($)=>({id:$.id,connectionId:$.connectionId,eventType:$.eventType,publisher:$.publisher,filter:$.filter,enabled:$.enabled,createdAt:$.createdAt,updatedAt:$.updatedAt}))}}})});var SY1=s(()=>{TY1();AY1();EY1();jY1();IY1();CY1();RY1();kW()});var $90,K90,NC4,WG,vY1,kY1;var pU=s(()=>{w4();$90=L.enum(["inclusion","exclusion"]).describe("Tool selection mode: 'inclusion' = include selected (default), 'exclusion' = exclude selected"),K90=L.enum(["passthrough","smart_tool_selection","code_execution"]).describe("Gateway tool selection strategy: 'passthrough' (default), 'smart_tool_selection', or 'code_execution'"),NC4=L.object({connection_id:L.string().describe("Connection ID"),selected_tools:L.array(L.string()).nullable().describe("Selected tool names. With 'inclusion' mode: null = all tools included. With 'exclusion' mode: null = entire connection excluded")}),WG=L.object({id:L.string().describe("Unique identifier for the gateway"),title:L.string().describe("Human-readable name for the gateway"),description:L.string().nullable().describe("Description of the gateway"),icon:L.string().nullable().optional().describe("Icon URL for the gateway"),created_at:L.string().describe("When the gateway was created"),updated_at:L.string().describe("When the gateway was last updated"),created_by:L.string().describe("User ID who created the gateway"),updated_by:L.string().optional().describe("User ID who last updated the gateway"),organization_id:L.string().describe("Organization ID this gateway belongs to"),tool_selection_strategy:K90.describe("Gateway behavior strategy (metadata for now): 'passthrough', 'smart_tool_selection', or 'code_execution'"),tool_selection_mode:$90.describe("Tool selection mode: 'inclusion' = include selected, 'exclusion' = exclude selected"),status:L.enum(["active","inactive"]).describe("Current status"),is_default:L.boolean().describe("Whether this is the default gateway for the organization"),connections:L.array(NC4).describe("Connections with their selected tools (behavior depends on tool_selection_mode)")}),vY1=L.object({title:L.string().min(1).max(255).describe("Name for the gateway"),description:L.string().nullable().optional().describe("Optional description"),tool_selection_strategy:K90.optional().default("passthrough").describe("Gateway behavior strategy (defaults to 'passthrough')"),tool_selection_mode:$90.optional().default("inclusion").describe("Tool selection mode (defaults to 'inclusion')"),icon:L.string().nullable().optional().describe("Optional icon URL"),status:L.enum(["active","inactive"]).optional().default("active").describe("Initial status"),is_default:L.boolean().optional().default(!1).describe("Whether this is the default gateway for the organization"),connections:L.array(L.object({connection_id:L.string().describe("Connection ID"),selected_tools:L.array(L.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools or full exclusion)")})).describe("Connections to include/exclude (can be empty for exclusion mode)")}),kY1=L.object({title:L.string().min(1).max(255).optional().describe("New name"),description:L.string().nullable().optional().describe("New description (null to clear)"),tool_selection_strategy:K90.optional().describe("New gateway behavior strategy"),tool_selection_mode:$90.optional().describe("New tool selection mode"),icon:L.string().nullable().optional().describe("New icon URL (null to clear)"),status:L.enum(["active","inactive"]).optional().describe("New status"),is_default:L.boolean().optional().describe("Set as default gateway for the organization"),connections:L.array(L.object({connection_id:L.string().describe("Connection ID"),selected_tools:L.array(L.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools or full exclusion)")})).optional().describe("New connections (replaces existing)")})});var BC4,OC4,Z90;var _Y1=s(()=>{w4();x4();pU();BC4=L.object({data:vY1.describe("Data for the new gateway")}),OC4=L.object({item:WG.describe("The created gateway entity")}),Z90=j1({name:"COLLECTION_GATEWAY_CREATE",description:"Create a new MCP gateway in the organization",inputSchema:BC4,outputSchema:OC4,handler:async(Q,J)=>{u1(J);let X=j4(J);await J.access.check();let G=QJ(J);if(!G)throw Error("User ID required to create gateway");let Y={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(($)=>({connectionId:$.connection_id,selectedTools:$.selected_tools??null}))},W=await J.storage.gateways.create(X.id,G,Y);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(($)=>({connection_id:$.connectionId,selected_tools:$.selectedTools})),created_at:W.createdAt,updated_at:W.updatedAt,created_by:W.createdBy,updated_by:W.updatedBy??void 0}}}})});function DC4(Q){let J=[],X=0;while(X<Q.length){let G=Q[X];if(G==="%")J.push(".*");else if(G==="_")J.push(".");else if(/[.*+?^${}()|[\]\\]/.test(G))J.push("\\"+G);else J.push(G);X++}return J.join("")}function WZ(Q){return typeof Q==="string"||typeof Q==="number"}function H90(Q,J){let X=J.split("."),G=Q;for(let Y of X){if(G==null||typeof G!=="object")return;G=G[Y]}return G}function LC4(Q,J){return Q.connections.some((X)=>X.connection_id===J)}function I_(Q,J){if("conditions"in J){let{operator:K,conditions:Z}=J;switch(K){case"and":return Z.every((H)=>I_(Q,H));case"or":return Z.some((H)=>I_(Q,H));case"not":return!Z.every((H)=>I_(Q,H));default:return!0}}let{field:X,operator:G,value:Y}=J,W=X.join(".");if(W==="connection_id"){if(G!=="eq"||typeof Y!=="string")return!1;return LC4(Q,Y)}let $=H90(Q,W);switch(G){case"eq":return $===Y;case"gt":return WZ($)&&WZ(Y)&&$>Y;case"gte":return WZ($)&&WZ(Y)&&$>=Y;case"lt":return WZ($)&&WZ(Y)&&$<Y;case"lte":return WZ($)&&WZ(Y)&&$<=Y;case"in":return Array.isArray(Y)&&Y.includes($);case"like":if(typeof $!=="string"||typeof Y!=="string")return!1;if(Y.length>100)return!1;let K=DC4(Y);return new RegExp(`^${K}$`,"i").test($);case"contains":if(typeof $!=="string"||typeof Y!=="string")return!1;return $.toLowerCase().includes(Y.toLowerCase());default:return!0}}function wC4(Q,J){return[...Q].sort((X,G)=>{for(let Y of J){let W=Y.field.join("."),$=H90(X,W),K=H90(G,W),Z=0;if($==null&&K==null)continue;if($==null)Z=Y.nulls==="first"?-1:1;else if(K==null)Z=Y.nulls==="first"?1:-1;else if(typeof $==="string"&&typeof K==="string")Z=$.localeCompare(K);else if(typeof $==="number"&&typeof K==="number")Z=$-K;else Z=String($).localeCompare(String(K));if(Z!==0)return Y.direction==="desc"?-Z:Z}return 0})}var PC4,MC4,F90;var yY1=s(()=>{YZ();x4();pU();PC4=RP,MC4=SP(WG),F90=j1({name:"COLLECTION_GATEWAY_LIST",description:"List all MCP gateways in the organization",inputSchema:PC4,outputSchema:MC4,handler:async(Q,J)=>{await J.access.check();let X=j4(J),G=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=(G?await J.storage.gateways.listByConnectionId(X.id,G):await J.storage.gateways.list(X.id)).map((q)=>({id:q.id,title:q.title,description:q.description,icon:q.icon,is_default:q.isDefault,organization_id:q.organizationId,tool_selection_strategy:q.toolSelectionStrategy,tool_selection_mode:q.toolSelectionMode,status:q.status,connections:q.connections.map((V)=>({connection_id:V.connectionId,selected_tools:V.selectedTools})),created_at:q.createdAt,updated_at:q.updatedAt,created_by:q.createdBy,updated_by:q.updatedBy??void 0}));if(Q.where)W=W.filter((q)=>I_(q,Q.where));if(Q.orderBy&&Q.orderBy.length>0)W=wC4(W,Q.orderBy);let $=W.length,K=Q.offset??0,Z=Q.limit??100,H=W.slice(K,K+Z),F=K+Z<$;return{items:H,totalCount:$,hasMore:F}}})});var TC4,AC4,q90;var hY1=s(()=>{w4();x4();pU();TC4=L.object({id:L.string().describe("ID of the gateway to retrieve")}),AC4=L.object({item:WG.nullable().describe("The retrieved gateway, or null if not found")}),q90=j1({name:"COLLECTION_GATEWAY_GET",description:"Get an MCP gateway by ID",inputSchema:TC4,outputSchema:AC4,handler:async(Q,J)=>{u1(J);let X=j4(J);await J.access.check();let G=await J.storage.gateways.findById(Q.id);if(G&&G.organizationId!==X.id)return{item:null};if(!G)return{item:null};return{item:{id:G.id,title:G.title,description:G.description,icon:G.icon,organization_id:G.organizationId,tool_selection_strategy:G.toolSelectionStrategy,tool_selection_mode:G.toolSelectionMode,status:G.status,is_default:G.isDefault,connections:G.connections.map((Y)=>({connection_id:Y.connectionId,selected_tools:Y.selectedTools})),created_at:G.createdAt,updated_at:G.updatedAt,created_by:G.createdBy,updated_by:G.updatedBy??void 0}}}})});var EC4,jC4,V90;var fY1=s(()=>{w4();x4();pU();EC4=L.object({id:L.string().describe("ID of the gateway to update"),data:kY1.describe("Partial gateway data to update")}),jC4=L.object({item:WG.describe("The updated gateway entity")}),V90=j1({name:"COLLECTION_GATEWAY_UPDATE",description:"Update an MCP gateway",inputSchema:EC4,outputSchema:jC4,handler:async(Q,J)=>{u1(J);let X=j4(J);await J.access.check();let G=QJ(J);if(!G)throw Error("User ID required to update gateway");let Y=await J.storage.gateways.findById(Q.id);if(!Y)throw Error(`Gateway not found: ${Q.id}`);if(Y.organizationId!==X.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((K)=>({connectionId:K.connection_id,selectedTools:K.selected_tools??null}));let $=await J.storage.gateways.update(Q.id,G,W);return{item:{id:$.id,title:$.title,description:$.description,icon:$.icon,organization_id:$.organizationId,tool_selection_strategy:$.toolSelectionStrategy,tool_selection_mode:$.toolSelectionMode,status:$.status,is_default:$.isDefault,connections:$.connections.map((K)=>({connection_id:K.connectionId,selected_tools:K.selectedTools})),created_at:$.createdAt,updated_at:$.updatedAt,created_by:$.createdBy,updated_by:$.updatedBy??void 0}}}})});var IC4,CC4,z90;var bY1=s(()=>{w4();x4();pU();IC4=L.object({id:L.string().describe("ID of the gateway to delete")}),CC4=L.object({item:WG.describe("The deleted gateway entity")}),z90=j1({name:"COLLECTION_GATEWAY_DELETE",description:"Delete an MCP gateway",inputSchema:IC4,outputSchema:CC4,handler:async(Q,J)=>{u1(J);let X=j4(J);await J.access.check();let G=await J.storage.gateways.findById(Q.id);if(!G)throw Error(`Gateway not found: ${Q.id}`);if(G.organizationId!==X.id)throw Error(`Gateway not found: ${Q.id}`);if(G.isDefault)throw Error("Cannot delete the default gateway. Set another gateway as default first.");return await J.storage.gateways.delete(Q.id),{item:{id:G.id,title:G.title,description:G.description,icon:G.icon,organization_id:G.organizationId,tool_selection_strategy:G.toolSelectionStrategy,tool_selection_mode:G.toolSelectionMode,status:G.status,is_default:G.isDefault,connections:G.connections.map((Y)=>({connection_id:Y.connectionId,selected_tools:Y.selectedTools})),created_at:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updated_at:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt,created_by:G.createdBy,updated_by:G.updatedBy??void 0}}}})});var xY1=s(()=>{_Y1();yY1();hY1();fY1();bY1()});var SC4,U90;var gY1=s(()=>{x4();w4();SC4=L.object({id:L.string().optional().describe("Unique log identifier"),organizationId:L.string().describe("Organization ID"),connectionId:L.string().describe("Connection ID"),connectionTitle:L.string().describe("Connection display name"),toolName:L.string().describe("Name of the tool that was called"),input:L.record(L.unknown()).describe("Redacted tool input"),output:L.record(L.unknown()).describe("Redacted tool output"),isError:L.boolean().describe("Whether the call resulted in an error"),errorMessage:L.string().nullish().describe("Error message if applicable"),durationMs:L.number().describe("Call duration in milliseconds"),timestamp:L.string().describe("ISO 8601 timestamp of the call"),userId:L.string().nullish().describe("User who triggered the call"),requestId:L.string().describe("Unique request identifier"),userAgent:L.string().nullish().describe("Client identifier (x-mesh-client header)"),gatewayId:L.string().nullish().describe("Gateway ID if routed through a gateway")}),U90=j1({name:"MONITORING_LOGS_LIST",description:"List monitoring logs for tool calls in the organization",inputSchema:L.object({connectionId:L.string().optional().describe("Filter by connection ID"),gatewayId:L.string().optional().describe("Filter by gateway ID"),toolName:L.string().optional().describe("Filter by tool name"),isError:L.boolean().optional().describe("Filter by error status"),startDate:L.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:L.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)"),limit:L.number().default(100).describe("Maximum number of results"),offset:L.number().default(0).describe("Offset for pagination")}),outputSchema:L.object({logs:L.array(SC4).describe("Array of monitoring logs"),total:L.number().describe("Total number of logs matching filters"),offset:L.number().describe("Current offset for pagination"),limit:L.number().describe("Current limit for pagination")}),handler:async(Q,J)=>{let G={organizationId:j4(J).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},Y=await J.storage.monitoring.query(G);return{logs:Y.logs.map((W)=>({...W,timestamp:W.timestamp instanceof Date?W.timestamp.toISOString():W.timestamp})),total:Y.total,offset:Q.offset,limit:Q.limit}}})});var N90;var uY1=s(()=>{x4();w4();N90=j1({name:"MONITORING_STATS",description:"Get aggregated statistics for tool call monitoring",inputSchema:L.object({startDate:L.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:L.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)")}),outputSchema:L.object({totalCalls:L.number().describe("Total number of tool calls"),errorRate:L.number().describe("Error rate as a decimal (0 to 1)"),avgDurationMs:L.number().describe("Average call duration in milliseconds"),errorRatePercent:L.string().describe("Error rate as a percentage string")}),handler:async(Q,J)=>{let G={organizationId:j4(J).id,startDate:Q.startDate?new Date(Q.startDate):void 0,endDate:Q.endDate?new Date(Q.endDate):void 0},Y=await J.storage.monitoring.getStats(G);return{...Y,errorRatePercent:(Y.errorRate*100).toFixed(2)}}})});var mY1=s(()=>{gY1();uY1()});var B90;var lY1=s(()=>{w4();x4();B90=j1({name:"ORGANIZATION_CREATE",description:"Create a new organization",inputSchema:L.object({slug:L.string().min(1).max(50).regex(/^[a-z0-9-]+$/,"Slug must be lowercase alphanumeric with hyphens"),name:L.string().min(1).max(255),description:L.string().optional()}),outputSchema:L.object({id:L.string(),name:L.string(),slug:L.string(),logo:L.string().nullable().optional(),metadata:L.any().optional(),createdAt:L.union([L.date(),L.string()]),members:L.array(L.any()).optional()}),handler:async(Q,J)=>{u1(J),await J.access.check();let X=QJ(J);if(!X)throw Error("User ID required to create organization");let G=await J.boundAuth.organization.create({name:Q.name,slug:Q.slug,metadata:Q.description?{description:Q.description}:void 0,userId:X});if(!G)throw Error("Failed to create organization");return G}})});var O90;var dY1=s(()=>{w4();x4();O90=j1({name:"ORGANIZATION_LIST",description:"List all organizations user has access to",inputSchema:L.object({userId:L.string().optional()}),outputSchema:L.object({organizations:L.array(L.object({id:L.string(),name:L.string(),slug:L.string(),logo:L.string().nullable().optional(),metadata:L.any().optional(),createdAt:L.union([L.date(),L.string()])}))}),handler:async(Q,J)=>{u1(J),await J.access.check();let X=QJ(J),G=Q.userId||X;if(!G)throw Error("User ID required to list organizations");return{organizations:await J.boundAuth.organization.list(G)}}})});var D90;var pY1=s(()=>{w4();x4();D90=j1({name:"ORGANIZATION_GET",description:"Get organization details by slug or ID",inputSchema:L.object({}),outputSchema:L.object({id:L.string(),name:L.string(),slug:L.string(),logo:L.string().nullable().optional(),metadata:L.any().optional(),createdAt:L.union([L.date(),L.string()]),members:L.array(L.any()).optional(),invitations:L.array(L.any()).optional()}),handler:async(Q,J)=>{u1(J),await J.access.check();let X=await J.boundAuth.organization.get();if(!X)throw Error("No active organization found");return X}})});var L90;var cY1=s(()=>{w4();x4();L90=j1({name:"ORGANIZATION_UPDATE",description:"Update an existing organization",inputSchema:L.object({id:L.string(),slug:L.string().min(1).max(50).regex(/^[a-z0-9-]+$/).optional(),name:L.string().min(1).max(255).optional(),description:L.string().optional()}),outputSchema:L.object({id:L.string(),name:L.string(),slug:L.string(),logo:L.string().nullable().optional(),metadata:L.any().optional(),createdAt:L.union([L.date(),L.string()])}),handler:async(Q,J)=>{u1(J),await J.access.check();let X={};if(Q.name)X.name=Q.name;if(Q.slug)X.slug=Q.slug;if(Q.description)X.metadata={description:Q.description};let G=await J.boundAuth.organization.update({organizationId:Q.id,data:X});if(!G)throw Error("Failed to update organization");return G}})});var w90;var nY1=s(()=>{w4();x4();w90=j1({name:"ORGANIZATION_DELETE",description:"Delete an organization",inputSchema:L.object({id:L.string()}),outputSchema:L.object({success:L.boolean(),id:L.string()}),handler:async(Q,J)=>{return u1(J),await J.access.check(),await J.boundAuth.organization.delete(Q.id),{success:!0,id:Q.id}}})});var pP;var P90=s(()=>{w4();pP=L.object({title:L.string(),url:L.string(),connectionId:L.string(),icon:L.string()})});var M90;var iY1=s(()=>{w4();x4();P90();M90=j1({name:"ORGANIZATION_SETTINGS_GET",description:"Get organization-level settings",inputSchema:L.object({}),outputSchema:L.object({organizationId:L.string(),sidebar_items:L.array(pP).nullable().optional(),createdAt:L.union([L.date(),L.string()]).optional(),updatedAt:L.union([L.date(),L.string()]).optional()}),handler:async(Q,J)=>{u1(J),await J.access.check();let X=J.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");let G=await J.storage.organizationSettings.get(X);if(!G)return{organizationId:X};return G}})});var T90;var rY1=s(()=>{w4();x4();P90();T90=j1({name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization-level settings",inputSchema:L.object({organizationId:L.string(),sidebar_items:L.array(pP).optional()}),outputSchema:L.object({organizationId:L.string(),sidebar_items:L.array(pP).nullable().optional(),createdAt:L.union([L.date(),L.string()]),updatedAt:L.union([L.date(),L.string()])}),handler:async(Q,J)=>{if(u1(J),await J.access.check(),J.organization&&J.organization.id!==Q.organizationId)throw Error("Cannot update settings for a different organization");return await J.storage.organizationSettings.upsert(Q.organizationId,{sidebar_items:Q.sidebar_items})}})});var A90;var aY1=s(()=>{w4();x4();A90=j1({name:"ORGANIZATION_MEMBER_ADD",description:"Add a member to an organization",inputSchema:L.object({organizationId:L.string().optional(),userId:L.string(),role:L.array(L.string())}),outputSchema:L.object({id:L.string(),organizationId:L.string(),userId:L.string(),role:L.union([L.string(),L.array(L.string())]),createdAt:L.union([L.date(),L.string()])}),handler:async(Q,J)=>{u1(J),await J.access.check();let X=Q.organizationId||J.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");let G=await J.boundAuth.organization.addMember({organizationId:X,userId:Q.userId,role:Q.role});if(!G)throw Error("Failed to add member");return G}})});var E90;var oY1=s(()=>{w4();x4();E90=j1({name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove a member from an organization",inputSchema:L.object({organizationId:L.string().optional(),memberIdOrEmail:L.string()}),outputSchema:L.object({success:L.boolean(),memberIdOrEmail:L.string()}),handler:async(Q,J)=>{u1(J),await J.access.check();let X=Q.organizationId||J.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");return await J.boundAuth.organization.removeMember({organizationId:X,memberIdOrEmail:Q.memberIdOrEmail}),{success:!0,memberIdOrEmail:Q.memberIdOrEmail}}})});var j90;var sY1=s(()=>{w4();x4();j90=j1({name:"ORGANIZATION_MEMBER_LIST",description:"List all members in an organization",inputSchema:L.object({limit:L.number().optional(),offset:L.number().optional()}),outputSchema:L.object({members:L.array(L.object({id:L.string(),organizationId:L.string(),userId:L.string(),role:L.string(),createdAt:L.union([L.date(),L.string()]),user:L.object({id:L.string(),name:L.string(),email:L.string(),image:L.string().optional()}).optional()}))}),handler:async(Q,J)=>{u1(J),await J.access.check();let X=J.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");let G=await J.boundAuth.organization.listMembers({organizationId:X,limit:Q.limit,offset:Q.offset});return{members:Array.isArray(G)?G:[]}}})});var I90;var tY1=s(()=>{w4();x4();I90=j1({name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Update a member's role in an organization",inputSchema:L.object({organizationId:L.string().optional(),memberId:L.string(),role:L.array(L.string())}),outputSchema:L.object({id:L.string(),organizationId:L.string(),userId:L.string(),role:L.union([L.literal("admin"),L.literal("member"),L.literal("owner")]),createdAt:L.union([L.date(),L.string()]),user:L.object({email:L.string(),name:L.string(),image:L.string().optional()})}),handler:async(Q,J)=>{u1(J),await J.access.check();let X=Q.organizationId||J.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");let G=await J.boundAuth.organization.updateMemberRole({organizationId:X,memberId:Q.memberId,role:Q.role});if(!G)throw Error("Failed to update member role");return G}})});var eY1=s(()=>{lY1();dY1();pY1();cY1();nY1();iY1();rY1();aY1();oY1();sY1();tY1()});var J71={};z6(J71,{managementMCP:()=>C90,ALL_TOOLS:()=>Q71});var Q71,C90=(Q)=>{let J=Q71.map((G)=>({name:G.name,description:G.description,inputSchema:G.inputSchema,outputSchema:G.outputSchema,handler:async(Y)=>{return Q.access.setToolName(G.name),await G.execute(Y,Q)}}));return HX1({name:"mcp-mesh-management",version:"1.0.0"}).withTools(J).build()};var R90=s(()=>{FX1();AX1();OY1();wY1();SY1();xY1();mY1();eY1();Q71=[B90,O90,D90,L90,w90,M90,T90,A90,E90,j90,I90,A80,n80,i80,o80,s80,t80,Z90,F90,q90,V90,z90,LY1,U90,N90,w80,M80,T80,P80,e80,Q90,J90,X90,Y90,G90,W90]});var UF,m90,f_,NF,tP;var b_=s(()=>{UF={JS_EVAL_TYPE_GLOBAL:0,JS_EVAL_TYPE_MODULE:1,JS_EVAL_TYPE_DIRECT:2,JS_EVAL_TYPE_INDIRECT:3,JS_EVAL_TYPE_MASK:3,JS_EVAL_FLAG_STRICT:8,JS_EVAL_FLAG_STRIP:16,JS_EVAL_FLAG_COMPILE_ONLY:32,JS_EVAL_FLAG_BACKTRACE_BARRIER:64},m90={BaseObjects:1,Date:2,Eval:4,StringNormalize:8,RegExp:16,RegExpCompiler:32,JSON:64,Proxy:128,MapSet:256,TypedArrays:512,Promise:1024,BigInt:2048,BigFloat:4096,BigDecimal:8192,OperatorOverloading:16384,BignumExt:32768},f_={Pending:0,Fulfilled:1,Rejected:2},NF={JS_GPN_STRING_MASK:1,JS_GPN_SYMBOL_MASK:2,JS_GPN_PRIVATE_MASK:4,JS_GPN_ENUM_ONLY:16,JS_GPN_SET_ENUM:32,QTS_GPN_NUMBER_MASK:64,QTS_STANDARD_COMPLIANT_NUMBER:128},tP={IsStrictlyEqual:0,IsSameValue:1,IsSameValueZero:2}});function iU(...Q){i90&&console.log("quickjs-emscripten:",...Q)}function*WG1(Q){return yield Q}function UR4(Q){return WG1(a90(Q))}function i71(Q,J){return(...X)=>{let G=J.call(Q,r90,...X);return a90(G)}}function NR4(Q,J){let X=J.call(Q,r90);return a90(X)}function a90(Q){function J(X){return X.done?X.value:X.value instanceof Promise?X.value.then((G)=>J(Q.next(G)),(G)=>J(Q.throw(G))):J(Q.next(X.value))}return J(Q.next())}function l90(Q,J){let X;try{Q.dispose()}catch(G){X=G}if(J&&X)throw Object.assign(J,{message:`${J.message}
292
292
  Then, failed to dispose scope: ${X.message}`,disposeError:X}),J;if(J||X)throw J||X}function $G1(Q){let J=Q?Array.from(Q):[];function X(){return J.forEach((Y)=>Y.alive?Y.dispose():void 0)}function G(){return J.some((Y)=>Y.alive)}return Object.defineProperty(J,c90,{configurable:!0,enumerable:!1,value:X}),Object.defineProperty(J,"dispose",{configurable:!0,enumerable:!1,value:X}),Object.defineProperty(J,"alive",{configurable:!0,enumerable:!1,get:G}),J}function x_(Q){return!!(Q&&(typeof Q=="object"||typeof Q=="function")&&("alive"in Q)&&typeof Q.alive=="boolean"&&("dispose"in Q)&&typeof Q.dispose=="function")}function BR4(Q){if(!Q)return 0;let J=0;for(let[X,G]of Object.entries(Q)){if(!(X in m90))throw new XG1(X);G&&(J|=m90[X])}return J}function OR4(Q){if(typeof Q=="number")return Q;if(Q===void 0)return 0;let{type:J,strict:X,strip:G,compileOnly:Y,backtraceBarrier:W}=Q,$=0;return J==="global"&&($|=UF.JS_EVAL_TYPE_GLOBAL),J==="module"&&($|=UF.JS_EVAL_TYPE_MODULE),X&&($|=UF.JS_EVAL_FLAG_STRICT),G&&($|=UF.JS_EVAL_FLAG_STRIP),Y&&($|=UF.JS_EVAL_FLAG_COMPILE_ONLY),W&&($|=UF.JS_EVAL_FLAG_BACKTRACE_BARRIER),$}function DR4(Q){if(typeof Q=="number")return Q;if(Q===void 0)return 0;let{strings:J,symbols:X,quickjsPrivate:G,onlyEnumerable:Y,numbers:W,numbersAsStrings:$}=Q,K=0;return J&&(K|=NF.JS_GPN_STRING_MASK),X&&(K|=NF.JS_GPN_SYMBOL_MASK),G&&(K|=NF.JS_GPN_PRIVATE_MASK),Y&&(K|=NF.JS_GPN_ENUM_ONLY),W&&(K|=NF.QTS_GPN_NUMBER_MASK),$&&(K|=NF.QTS_STANDARD_COMPLIANT_NUMBER),K}function LR4(...Q){let J=[];for(let X of Q)X!==void 0&&(J=J.concat(X));return J}function e90(Q,J){J.interruptHandler&&Q.setInterruptHandler(J.interruptHandler),J.maxStackSizeBytes!==void 0&&Q.setMaxStackSize(J.maxStackSizeBytes),J.memoryLimitBytes!==void 0&&Q.setMemoryLimit(J.memoryLimitBytes)}function Q50(Q,J){J.moduleLoader&&Q.setModuleLoader(J.moduleLoader),J.shouldInterrupt&&Q.setInterruptHandler(J.shouldInterrupt),J.memoryLimitBytes!==void 0&&Q.setMemoryLimit(J.memoryLimitBytes),J.maxStackSizeBytes!==void 0&&Q.setMaxStackSize(J.maxStackSizeBytes)}var VR4,zR4=(Q,J)=>{for(var X in J)VR4(Q,X,{get:J[X],enumerable:!0})},i90=!1,a71,d90,o71,p90,s71,t71,e71,QG1,JG1,XG1,YG1,GG1,r90,hW,c90,r71,l5,KZ,n90,uY,o90,KG1,ZG1,BF,HG1,FG1=class{constructor(Q){this.module=Q}toPointerArray(Q){let J=new Int32Array(Q.map((Y)=>Y.value)),X=J.length*J.BYTES_PER_ELEMENT,G=this.module._malloc(X);return new Uint8Array(this.module.HEAPU8.buffer,G,X).set(new Uint8Array(J.buffer)),new l5(G,void 0,(Y)=>this.module._free(Y))}newTypedArray(Q,J){let X=new Q(Array(J).fill(0)),G=X.length*X.BYTES_PER_ELEMENT,Y=this.module._malloc(G),W=new Q(this.module.HEAPU8.buffer,Y,J);return W.set(X),new l5({typedArray:W,ptr:Y},void 0,($)=>this.module._free($.ptr))}newMutablePointerArray(Q){return this.newTypedArray(Int32Array,Q)}newHeapCharPointer(Q){let J=this.module.lengthBytesUTF8(Q),X=J+1,G=this.module._malloc(X);return this.module.stringToUTF8(Q,G,X),new l5({ptr:G,strlen:J},void 0,(Y)=>this.module._free(Y.ptr))}newHeapBufferPointer(Q){let J=Q.byteLength,X=this.module._malloc(J);return this.module.HEAPU8.set(Q,X),new l5({pointer:X,numBytes:J},void 0,(G)=>this.module._free(G.pointer))}consumeHeapCharPointer(Q){let J=this.module.UTF8ToString(Q);return this.module._free(Q),J}},nx6,s90,wR4,PR4,qG1,VG1,MR4=class{constructor(Q){this.callFunction=Q.callFunction,this.shouldInterrupt=Q.shouldInterrupt,this.loadModuleSource=Q.loadModuleSource,this.normalizeModule=Q.normalizeModule}},t90=class{constructor(Q){this.contextCallbacks=new Map,this.runtimeCallbacks=new Map,this.suspendedCount=0,this.cToHostCallbacks=new MR4({callFunction:(J,X,G,Y,W,$)=>this.handleAsyncify(J,()=>{try{let K=this.contextCallbacks.get(X);if(!K)throw Error(`QuickJSContext(ctx = ${X}) not found for C function call "${$}"`);return K.callFunction(X,G,Y,W,$)}catch(K){return console.error("[C to host error: returning null]",K),0}}),shouldInterrupt:(J,X)=>this.handleAsyncify(J,()=>{try{let G=this.runtimeCallbacks.get(X);if(!G)throw Error(`QuickJSRuntime(rt = ${X}) not found for C interrupt`);return G.shouldInterrupt(X)}catch(G){return console.error("[C to host interrupt: returning error]",G),1}}),loadModuleSource:(J,X,G,Y)=>this.handleAsyncify(J,()=>{try{let W=this.runtimeCallbacks.get(X);if(!W)throw Error(`QuickJSRuntime(rt = ${X}) not found for C module loader`);let $=W.loadModuleSource;if(!$)throw Error(`QuickJSRuntime(rt = ${X}) does not support module loading`);return $(X,G,Y)}catch(W){return console.error("[C to host module loader error: returning null]",W),0}}),normalizeModule:(J,X,G,Y,W)=>this.handleAsyncify(J,()=>{try{let $=this.runtimeCallbacks.get(X);if(!$)throw Error(`QuickJSRuntime(rt = ${X}) not found for C module loader`);let K=$.normalizeModule;if(!K)throw Error(`QuickJSRuntime(rt = ${X}) does not support module loading`);return K(X,G,Y,W)}catch($){return console.error("[C to host module loader error: returning null]",$),0}})}),this.module=Q,this.module.callbacks=this.cToHostCallbacks}setRuntimeCallbacks(Q,J){this.runtimeCallbacks.set(Q,J)}deleteRuntime(Q){this.runtimeCallbacks.delete(Q)}setContextCallbacks(Q,J){this.contextCallbacks.set(Q,J)}deleteContext(Q){this.contextCallbacks.delete(Q)}handleAsyncify(Q,J){if(Q)return Q.handleSleep((G)=>{try{let Y=J();if(!(Y instanceof Promise)){iU("asyncify.handleSleep: not suspending:",Y),G(Y);return}if(this.suspended)throw new t71(`Already suspended at: ${this.suspended.stack}
@@ -1139,4 +1139,4 @@ Learn more: \x1B[34m${X}\x1B[0m
1139
1139
  `)},flush(Q){Q.enqueue(`data: [DONE]
1140
1140
 
1141
1141
  `)}})}},s31={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function Px4({status:Q,statusText:J,headers:X,stream:G,consumeSseStream:Y}){let W=G.pipeThrough(new o31);if(Y){let[$,K]=W.tee();W=$,Y({stream:K})}return new Response(W.pipeThrough(new TextEncoderStream),{status:Q,statusText:J,headers:$h(X,s31)})}function Mx4({originalMessages:Q,responseMessageId:J}){if(Q==null)return;let X=Q[Q.length-1];return(X==null?void 0:X.role)==="assistant"?X.id:typeof J==="function"?J():J}var qc6=TQ(()=>d5(I.union([I.strictObject({type:I.literal("text-start"),id:I.string(),providerMetadata:e1.optional()}),I.strictObject({type:I.literal("text-delta"),id:I.string(),delta:I.string(),providerMetadata:e1.optional()}),I.strictObject({type:I.literal("text-end"),id:I.string(),providerMetadata:e1.optional()}),I.strictObject({type:I.literal("error"),errorText:I.string()}),I.strictObject({type:I.literal("tool-input-start"),toolCallId:I.string(),toolName:I.string(),providerExecuted:I.boolean().optional(),dynamic:I.boolean().optional(),title:I.string().optional()}),I.strictObject({type:I.literal("tool-input-delta"),toolCallId:I.string(),inputTextDelta:I.string()}),I.strictObject({type:I.literal("tool-input-available"),toolCallId:I.string(),toolName:I.string(),input:I.unknown(),providerExecuted:I.boolean().optional(),providerMetadata:e1.optional(),dynamic:I.boolean().optional(),title:I.string().optional()}),I.strictObject({type:I.literal("tool-input-error"),toolCallId:I.string(),toolName:I.string(),input:I.unknown(),providerExecuted:I.boolean().optional(),providerMetadata:e1.optional(),dynamic:I.boolean().optional(),errorText:I.string(),title:I.string().optional()}),I.strictObject({type:I.literal("tool-approval-request"),approvalId:I.string(),toolCallId:I.string()}),I.strictObject({type:I.literal("tool-output-available"),toolCallId:I.string(),output:I.unknown(),providerExecuted:I.boolean().optional(),dynamic:I.boolean().optional(),preliminary:I.boolean().optional()}),I.strictObject({type:I.literal("tool-output-error"),toolCallId:I.string(),errorText:I.string(),providerExecuted:I.boolean().optional(),dynamic:I.boolean().optional()}),I.strictObject({type:I.literal("tool-output-denied"),toolCallId:I.string()}),I.strictObject({type:I.literal("reasoning-start"),id:I.string(),providerMetadata:e1.optional()}),I.strictObject({type:I.literal("reasoning-delta"),id:I.string(),delta:I.string(),providerMetadata:e1.optional()}),I.strictObject({type:I.literal("reasoning-end"),id:I.string(),providerMetadata:e1.optional()}),I.strictObject({type:I.literal("source-url"),sourceId:I.string(),url:I.string(),title:I.string().optional(),providerMetadata:e1.optional()}),I.strictObject({type:I.literal("source-document"),sourceId:I.string(),mediaType:I.string(),title:I.string(),filename:I.string().optional(),providerMetadata:e1.optional()}),I.strictObject({type:I.literal("file"),url:I.string(),mediaType:I.string(),providerMetadata:e1.optional()}),I.strictObject({type:I.custom((Q)=>typeof Q==="string"&&Q.startsWith("data-"),{message:'Type must start with "data-"'}),id:I.string().optional(),data:I.unknown(),transient:I.boolean().optional()}),I.strictObject({type:I.literal("start-step")}),I.strictObject({type:I.literal("finish-step")}),I.strictObject({type:I.literal("start"),messageId:I.string().optional(),messageMetadata:I.unknown().optional()}),I.strictObject({type:I.literal("finish"),finishReason:I.enum(["stop","length","content-filter","tool-calls","error","other"]).optional(),messageMetadata:I.unknown().optional()}),I.strictObject({type:I.literal("abort")}),I.strictObject({type:I.literal("message-metadata"),messageMetadata:I.unknown()})])));function Tx4(Q){return Q.type.startsWith("data-")}function Q70(Q){return Q.type.startsWith("data-")}function J70(Q){return Q.type==="text"}function X70(Q){return Q.type==="file"}function eZ1(Q){return Q.type==="reasoning"}function H70(Q){return Q.type.startsWith("tool-")}function t31(Q){return Q.type==="dynamic-tool"}function aM(Q){return H70(Q)||t31(Q)}function F70(Q){return Q.type.split("-").slice(1).join("-")}function Y70(Q){return t31(Q)?Q.toolName:F70(Q)}function Ax4({lastMessage:Q,messageId:J}){return{message:(Q==null?void 0:Q.role)==="assistant"?Q:{id:J,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function Ex4({stream:Q,messageMetadataSchema:J,dataPartSchemas:X,runUpdateMessageJob:G,onError:Y,onToolCall:W,onData:$}){return Q.pipeThrough(new TransformStream({async transform(K,Z){await G(async({state:H,write:F})=>{var q,V,z,U;function N(M){let A=H.message.parts.filter(aM).find((j)=>j.toolCallId===M);if(A==null)throw Error(`no tool invocation found for tool call ${M}`);return A}function D(M){var T;let A=H.message.parts.find((v)=>H70(v)&&v.toolCallId===M.toolCallId),j=M,R=A;if(A!=null){if(A.state=M.state,R.input=j.input,R.output=j.output,R.errorText=j.errorText,R.rawInput=j.rawInput,R.preliminary=j.preliminary,M.title!==void 0)R.title=M.title;if(R.providerExecuted=(T=j.providerExecuted)!=null?T:A.providerExecuted,j.providerMetadata!=null&&A.state==="input-available")A.callProviderMetadata=j.providerMetadata}else H.message.parts.push({type:`tool-${M.toolName}`,toolCallId:M.toolCallId,state:M.state,title:M.title,input:j.input,output:j.output,rawInput:j.rawInput,errorText:j.errorText,providerExecuted:j.providerExecuted,preliminary:j.preliminary,...j.providerMetadata!=null?{callProviderMetadata:j.providerMetadata}:{}})}function w(M){var T,A;let j=H.message.parts.find((_)=>_.type==="dynamic-tool"&&_.toolCallId===M.toolCallId),R=M,v=j;if(j!=null){if(j.state=M.state,v.toolName=M.toolName,v.input=R.input,v.output=R.output,v.errorText=R.errorText,v.rawInput=(T=R.rawInput)!=null?T:v.rawInput,v.preliminary=R.preliminary,M.title!==void 0)v.title=M.title;if(v.providerExecuted=(A=R.providerExecuted)!=null?A:j.providerExecuted,R.providerMetadata!=null&&j.state==="input-available")j.callProviderMetadata=R.providerMetadata}else H.message.parts.push({type:"dynamic-tool",toolName:M.toolName,toolCallId:M.toolCallId,state:M.state,input:R.input,output:R.output,errorText:R.errorText,preliminary:R.preliminary,providerExecuted:R.providerExecuted,title:M.title,...R.providerMetadata!=null?{callProviderMetadata:R.providerMetadata}:{}})}async function E(M){if(M!=null){let T=H.message.metadata!=null?V70(H.message.metadata,M):M;if(J!=null)await pM({value:T,schema:J});H.message.metadata=T}}switch(K.type){case"text-start":{let M={type:"text",text:"",providerMetadata:K.providerMetadata,state:"streaming"};H.activeTextParts[K.id]=M,H.message.parts.push(M),F();break}case"text-delta":{let M=H.activeTextParts[K.id];M.text+=K.delta,M.providerMetadata=(q=K.providerMetadata)!=null?q:M.providerMetadata,F();break}case"text-end":{let M=H.activeTextParts[K.id];M.state="done",M.providerMetadata=(V=K.providerMetadata)!=null?V:M.providerMetadata,delete H.activeTextParts[K.id],F();break}case"reasoning-start":{let M={type:"reasoning",text:"",providerMetadata:K.providerMetadata,state:"streaming"};H.activeReasoningParts[K.id]=M,H.message.parts.push(M),F();break}case"reasoning-delta":{let M=H.activeReasoningParts[K.id];M.text+=K.delta,M.providerMetadata=(z=K.providerMetadata)!=null?z:M.providerMetadata,F();break}case"reasoning-end":{let M=H.activeReasoningParts[K.id];M.providerMetadata=(U=K.providerMetadata)!=null?U:M.providerMetadata,M.state="done",delete H.activeReasoningParts[K.id],F();break}case"file":{H.message.parts.push({type:"file",mediaType:K.mediaType,url:K.url}),F();break}case"source-url":{H.message.parts.push({type:"source-url",sourceId:K.sourceId,url:K.url,title:K.title,providerMetadata:K.providerMetadata}),F();break}case"source-document":{H.message.parts.push({type:"source-document",sourceId:K.sourceId,mediaType:K.mediaType,title:K.title,filename:K.filename,providerMetadata:K.providerMetadata}),F();break}case"tool-input-start":{let M=H.message.parts.filter(H70);if(H.partialToolCalls[K.toolCallId]={text:"",toolName:K.toolName,index:M.length,dynamic:K.dynamic,title:K.title},K.dynamic)w({toolCallId:K.toolCallId,toolName:K.toolName,state:"input-streaming",input:void 0,providerExecuted:K.providerExecuted,title:K.title});else D({toolCallId:K.toolCallId,toolName:K.toolName,state:"input-streaming",input:void 0,providerExecuted:K.providerExecuted,title:K.title});F();break}case"tool-input-delta":{let M=H.partialToolCalls[K.toolCallId];M.text+=K.inputTextDelta;let{value:T}=await sM(M.text);if(M.dynamic)w({toolCallId:K.toolCallId,toolName:M.toolName,state:"input-streaming",input:T,title:M.title});else D({toolCallId:K.toolCallId,toolName:M.toolName,state:"input-streaming",input:T,title:M.title});F();break}case"tool-input-available":{if(K.dynamic)w({toolCallId:K.toolCallId,toolName:K.toolName,state:"input-available",input:K.input,providerExecuted:K.providerExecuted,providerMetadata:K.providerMetadata,title:K.title});else D({toolCallId:K.toolCallId,toolName:K.toolName,state:"input-available",input:K.input,providerExecuted:K.providerExecuted,providerMetadata:K.providerMetadata,title:K.title});if(F(),W&&!K.providerExecuted)await W({toolCall:K});break}case"tool-input-error":{if(K.dynamic)w({toolCallId:K.toolCallId,toolName:K.toolName,state:"output-error",input:K.input,errorText:K.errorText,providerExecuted:K.providerExecuted,providerMetadata:K.providerMetadata});else D({toolCallId:K.toolCallId,toolName:K.toolName,state:"output-error",input:void 0,rawInput:K.input,errorText:K.errorText,providerExecuted:K.providerExecuted,providerMetadata:K.providerMetadata});F();break}case"tool-approval-request":{let M=N(K.toolCallId);M.state="approval-requested",M.approval={id:K.approvalId},F();break}case"tool-output-denied":{let M=N(K.toolCallId);M.state="output-denied",F();break}case"tool-output-available":{let M=N(K.toolCallId);if(M.type==="dynamic-tool")w({toolCallId:K.toolCallId,toolName:M.toolName,state:"output-available",input:M.input,output:K.output,preliminary:K.preliminary,providerExecuted:K.providerExecuted,title:M.title});else D({toolCallId:K.toolCallId,toolName:F70(M),state:"output-available",input:M.input,output:K.output,providerExecuted:K.providerExecuted,preliminary:K.preliminary,title:M.title});F();break}case"tool-output-error":{let M=N(K.toolCallId);if(M.type==="dynamic-tool")w({toolCallId:K.toolCallId,toolName:M.toolName,state:"output-error",input:M.input,errorText:K.errorText,providerExecuted:K.providerExecuted,title:M.title});else D({toolCallId:K.toolCallId,toolName:F70(M),state:"output-error",input:M.input,rawInput:M.rawInput,errorText:K.errorText,providerExecuted:K.providerExecuted,title:M.title});F();break}case"start-step":{H.message.parts.push({type:"step-start"});break}case"finish-step":{H.activeTextParts={},H.activeReasoningParts={};break}case"start":{if(K.messageId!=null)H.message.id=K.messageId;if(await E(K.messageMetadata),K.messageId!=null||K.messageMetadata!=null)F();break}case"finish":{if(K.finishReason!=null)H.finishReason=K.finishReason;if(await E(K.messageMetadata),K.messageMetadata!=null)F();break}case"message-metadata":{if(await E(K.messageMetadata),K.messageMetadata!=null)F();break}case"error":{Y==null||Y(Error(K.errorText));break}default:if(Tx4(K)){if((X==null?void 0:X[K.type])!=null)await pM({value:K.data,schema:X[K.type]});let M=K;if(M.transient){$==null||$(M);break}let T=M.id!=null?H.message.parts.find((A)=>M.type===A.type&&M.id===A.id):void 0;if(T!=null)T.data=M.data;else H.message.parts.push(M);$==null||$(M),F()}}Z.enqueue(K)})}}))}function jx4({messageId:Q,originalMessages:J=[],onFinish:X,onError:G,stream:Y}){let W=J==null?void 0:J[J.length-1];if((W==null?void 0:W.role)!=="assistant")W=void 0;else Q=W.id;let $=!1,K=Y.pipeThrough(new TransformStream({transform(V,z){if(V.type==="start"){let U=V;if(U.messageId==null&&Q!=null)U.messageId=Q}if(V.type==="abort")$=!0;z.enqueue(V)}}));if(X==null)return K;let Z=Ax4({lastMessage:W?structuredClone(W):void 0,messageId:Q!=null?Q:""}),H=async(V)=>{await V({state:Z,write:()=>{}})},F=!1,q=async()=>{if(F||!X)return;F=!0;let V=Z.message.id===(W==null?void 0:W.id);await X({isAborted:$,isContinuation:V,responseMessage:Z.message,messages:[...V?J.slice(0,-1):J,Z.message],finishReason:Z.finishReason})};return Ex4({stream:K,runUpdateMessageJob:H,onError:G}).pipeThrough(new TransformStream({transform(V,z){z.enqueue(V)},async cancel(){await q()},async flush(){await q()}}))}function Ix4({response:Q,status:J,statusText:X,headers:G,stream:Y,consumeSseStream:W}){let $=Y.pipeThrough(new o31);if(W){let[K,Z]=$.tee();$=K,W({stream:Z})}a31({response:Q,status:J,statusText:X,headers:Object.fromEntries($h(G,s31).entries()),stream:$.pipeThrough(new TextEncoderStream)})}function Gh(Q){let J=Q.pipeThrough(new TransformStream);return J[Symbol.asyncIterator]=function(){let X=this.getReader(),G=!1;async function Y(W){var $;G=!0;try{if(W)await(($=X.cancel)==null?void 0:$.call(X))}finally{try{X.releaseLock()}catch(K){}}}return{async next(){if(G)return{done:!0,value:void 0};let{done:W,value:$}=await X.read();if(W)return await Y(!0),{done:!0,value:void 0};return{done:!1,value:$}},async return(){return await Y(!0),{done:!0,value:void 0}},async throw(W){throw await Y(!0),W}}},J}async function Cx4({stream:Q,onError:J}){let X=Q.getReader();try{while(!0){let{done:G}=await X.read();if(G)break}}catch(G){J==null||J(G)}finally{X.releaseLock()}}function Q31(){let Q,J;return{promise:new Promise((G,Y)=>{Q=G,J=Y}),resolve:Q,reject:J}}function Rx4(){let Q=[],J=null,X=!1,G=Q31(),Y=()=>{X=!0,G.resolve(),Q.forEach(($)=>$.cancel()),Q=[],J==null||J.close()},W=async()=>{if(X&&Q.length===0){J==null||J.close();return}if(Q.length===0)return G=Q31(),await G.promise,W();try{let{value:$,done:K}=await Q[0].read();if(K)if(Q.shift(),Q.length===0&&X)J==null||J.close();else await W();else J==null||J.enqueue($)}catch($){J==null||J.error($),Q.shift(),Y()}};return{stream:new ReadableStream({start($){J=$},pull:W,async cancel(){for(let $ of Q)await $.cancel();Q=[],X=!0}}),addStream:($)=>{if(X)throw Error("Cannot add inner stream: outer stream is closed");Q.push($.getReader()),G.resolve()},close:()=>{if(X=!0,G.resolve(),Q.length===0)J==null||J.close()},terminate:Y}}function Sx4(){var Q,J;return(J=(Q=globalThis==null?void 0:globalThis.performance)==null?void 0:Q.now())!=null?J:Date.now()}function vx4({tools:Q,generatorStream:J,tracer:X,telemetry:G,system:Y,messages:W,abortSignal:$,repairToolCall:K,experimental_context:Z,generateId:H}){let F=null,q=new ReadableStream({start(M){F=M}}),V=new Set,z=new Map,U=new Map,N=!1,D=void 0;function w(){if(N&&V.size===0){if(D!=null)F.enqueue(D);F.close()}}let E=new TransformStream({async transform(M,T){let A=M.type;switch(A){case"stream-start":case"text-start":case"text-delta":case"text-end":case"reasoning-start":case"reasoning-delta":case"reasoning-end":case"tool-input-start":case"tool-input-delta":case"tool-input-end":case"source":case"response-metadata":case"error":case"raw":{T.enqueue(M);break}case"file":{T.enqueue({type:"file",file:new Zx4({data:M.data,mediaType:M.mediaType})});break}case"finish":{D={type:"finish",finishReason:M.finishReason.unified,rawFinishReason:M.finishReason.raw,usage:Jx4(M.usage),providerMetadata:M.providerMetadata};break}case"tool-approval-request":{let j=U.get(M.toolCallId);if(j==null){F.enqueue({type:"error",error:new z31({toolCallId:M.toolCallId,approvalId:M.approvalId})});break}T.enqueue({type:"tool-approval-request",approvalId:M.approvalId,toolCall:j});break}case"tool-call":{try{let j=await Bx4({toolCall:M,tools:Q,repairToolCall:K,system:Y,messages:W});if(U.set(j.toolCallId,j),T.enqueue(j),j.invalid){F.enqueue({type:"tool-error",toolCallId:j.toolCallId,toolName:j.toolName,input:j.input,error:lM(j.error),dynamic:!0,title:j.title});break}let R=Q==null?void 0:Q[j.toolName];if(R==null)break;if(R.onInputAvailable!=null)await R.onInputAvailable({input:j.input,toolCallId:j.toolCallId,messages:W,abortSignal:$,experimental_context:Z});if(await Hx4({tool:R,toolCall:j,messages:W,experimental_context:Z})){F.enqueue({type:"tool-approval-request",approvalId:H(),toolCall:j});break}if(z.set(j.toolCallId,j.input),R.execute!=null&&j.providerExecuted!==!0){let v=H();V.add(v),i31({toolCall:j,tools:Q,tracer:X,telemetry:G,messages:W,abortSignal:$,experimental_context:Z,onPreliminaryToolResult:(_)=>{F.enqueue(_)}}).then((_)=>{F.enqueue(_),V.delete(v),w()})}}catch(j){F.enqueue({type:"error",error:j})}break}case"tool-result":{let j=M.toolName;if(M.isError)F.enqueue({type:"tool-error",toolCallId:M.toolCallId,toolName:j,input:z.get(M.toolCallId),providerExecuted:!0,error:M.result,dynamic:M.dynamic});else T.enqueue({type:"tool-result",toolCallId:M.toolCallId,toolName:j,input:z.get(M.toolCallId),output:M.result,providerExecuted:!0,dynamic:M.dynamic});break}default:throw Error(`Unhandled chunk type: ${A}`)}},flush(){N=!0,w()}});return new ReadableStream({async start(M){return Promise.all([J.pipeThrough(E).pipeTo(new WritableStream({write(T){M.enqueue(T)},close(){}})),q.pipeTo(new WritableStream({write(T){M.enqueue(T)},close(){M.close()}}))])}})}var kx4=pW({prefix:"aitxt",size:24});function e31({model:Q,tools:J,toolChoice:X,system:G,prompt:Y,messages:W,maxRetries:$,abortSignal:K,headers:Z,stopWhen:H=z70(1),experimental_output:F,output:q=F,experimental_telemetry:V,prepareStep:z,providerOptions:U,experimental_activeTools:N,activeTools:D=N,experimental_repairToolCall:w,experimental_transform:E,experimental_download:M,includeRawChunks:T=!1,onChunk:A,onError:j=({error:g})=>{console.error(g)},onFinish:R,onAbort:v,onStepFinish:_,experimental_context:y,_internal:{now:b=Sx4,generateId:m=kx4,currentDate:x=()=>new Date}={},...k}){return new yx4({model:x31(Q),telemetry:V,headers:Z,settings:k,maxRetries:$,abortSignal:K,system:G,prompt:Y,messages:W,tools:J,toolChoice:X,transforms:Wh(E),activeTools:D,repairToolCall:w,stopConditions:Wh(H),output:q,providerOptions:U,prepareStep:z,includeRawChunks:T,onChunk:A,onError:j,onFinish:R,onAbort:v,onStepFinish:_,now:b,currentDate:x,generateId:m,experimental_context:y,download:M})}function _x4(Q){let J=void 0,X="",G="",Y=void 0,W="";function $({controller:K,partialOutput:Z=void 0}){K.enqueue({part:{type:"text-delta",id:J,text:G,providerMetadata:Y},partialOutput:Z}),G=""}return new TransformStream({async transform(K,Z){var H;if(K.type==="finish-step"&&G.length>0)$({controller:Z});if(K.type!=="text-delta"&&K.type!=="text-start"&&K.type!=="text-end"){Z.enqueue({part:K,partialOutput:void 0});return}if(J==null)J=K.id;else if(K.id!==J){Z.enqueue({part:K,partialOutput:void 0});return}if(K.type==="text-start"){Z.enqueue({part:K,partialOutput:void 0});return}if(K.type==="text-end"){if(G.length>0)$({controller:Z});Z.enqueue({part:K,partialOutput:void 0});return}X+=K.text,G+=K.text,Y=(H=K.providerMetadata)!=null?H:Y;let F=await Q.parsePartialOutput({text:X});if(F!==void 0){let q=JSON.stringify(F.partial);if(q!==W)$({controller:Z,partialOutput:F.partial}),W=q}}})}var yx4=class{constructor({model:Q,telemetry:J,headers:X,settings:G,maxRetries:Y,abortSignal:W,system:$,prompt:K,messages:Z,tools:H,toolChoice:F,transforms:q,activeTools:V,repairToolCall:z,stopConditions:U,output:N,providerOptions:D,prepareStep:w,includeRawChunks:E,now:M,currentDate:T,generateId:A,onChunk:j,onError:R,onFinish:v,onAbort:_,onStepFinish:y,experimental_context:b,download:m}){this._totalUsage=new IF,this._finishReason=new IF,this._rawFinishReason=new IF,this._steps=new IF,this.outputSpecification=N,this.includeRawChunks=E,this.tools=H;let x,k=[],g=[],J0=void 0,i=void 0,W0=void 0,V0={},G0=[],N0=[],R0=new Map,u0,c0={},O0={},H0=new TransformStream({async transform(p0,v0){var f0,W1,k1,a1;v0.enqueue(p0);let{part:l0}=p0;if(l0.type==="text-delta"||l0.type==="reasoning-delta"||l0.type==="source"||l0.type==="tool-call"||l0.type==="tool-result"||l0.type==="tool-input-start"||l0.type==="tool-input-delta"||l0.type==="raw")await(j==null?void 0:j({chunk:l0}));if(l0.type==="error")await R({error:ab4(l0.error)});if(l0.type==="text-start")c0[l0.id]={type:"text",text:"",providerMetadata:l0.providerMetadata},k.push(c0[l0.id]);if(l0.type==="text-delta"){let n0=c0[l0.id];if(n0==null){v0.enqueue({part:{type:"error",error:`text part ${l0.id} not found`},partialOutput:void 0});return}n0.text+=l0.text,n0.providerMetadata=(f0=l0.providerMetadata)!=null?f0:n0.providerMetadata}if(l0.type==="text-end"){let n0=c0[l0.id];if(n0==null){v0.enqueue({part:{type:"error",error:`text part ${l0.id} not found`},partialOutput:void 0});return}n0.providerMetadata=(W1=l0.providerMetadata)!=null?W1:n0.providerMetadata,delete c0[l0.id]}if(l0.type==="reasoning-start")O0[l0.id]={type:"reasoning",text:"",providerMetadata:l0.providerMetadata},k.push(O0[l0.id]);if(l0.type==="reasoning-delta"){let n0=O0[l0.id];if(n0==null){v0.enqueue({part:{type:"error",error:`reasoning part ${l0.id} not found`},partialOutput:void 0});return}n0.text+=l0.text,n0.providerMetadata=(k1=l0.providerMetadata)!=null?k1:n0.providerMetadata}if(l0.type==="reasoning-end"){let n0=O0[l0.id];if(n0==null){v0.enqueue({part:{type:"error",error:`reasoning part ${l0.id} not found`},partialOutput:void 0});return}n0.providerMetadata=(a1=l0.providerMetadata)!=null?a1:n0.providerMetadata,delete O0[l0.id]}if(l0.type==="file")k.push({type:"file",file:l0.file});if(l0.type==="source")k.push(l0);if(l0.type==="tool-call")k.push(l0);if(l0.type==="tool-result"&&!l0.preliminary)k.push(l0);if(l0.type==="tool-approval-request")k.push(l0);if(l0.type==="tool-error")k.push(l0);if(l0.type==="start-step")k=[],O0={},c0={},V0=l0.request,G0=l0.warnings;if(l0.type==="finish-step"){let n0=await tZ1({content:k,tools:H}),k0=new Ox4({content:k,finishReason:l0.finishReason,rawFinishReason:l0.rawFinishReason,usage:l0.usage,warnings:G0,request:V0,response:{...l0.response,messages:[...g,...n0]},providerMetadata:l0.providerMetadata});await(y==null?void 0:y(k0)),h31({warnings:G0,provider:Q.provider,model:Q.modelId}),N0.push(k0),g.push(...n0),x.resolve()}if(l0.type==="finish")W0=l0.totalUsage,J0=l0.finishReason,i=l0.rawFinishReason},async flush(p0){try{if(N0.length===0){let k1=new Jb4({message:"No output generated. Check the stream for errors."});L0._finishReason.reject(k1),L0._rawFinishReason.reject(k1),L0._totalUsage.reject(k1),L0._steps.reject(k1);return}let v0=J0!=null?J0:"other",f0=W0!=null?W0:eY0();L0._finishReason.resolve(v0),L0._rawFinishReason.resolve(i),L0._totalUsage.resolve(f0),L0._steps.resolve(N0);let W1=N0[N0.length-1];await(v==null?void 0:v({finishReason:W1.finishReason,rawFinishReason:W1.rawFinishReason,totalUsage:f0,usage:W1.usage,content:W1.content,text:W1.text,reasoningText:W1.reasoningText,reasoning:W1.reasoning,files:W1.files,sources:W1.sources,toolCalls:W1.toolCalls,staticToolCalls:W1.staticToolCalls,dynamicToolCalls:W1.dynamicToolCalls,toolResults:W1.toolResults,staticToolResults:W1.staticToolResults,dynamicToolResults:W1.dynamicToolResults,request:W1.request,response:W1.response,warnings:W1.warnings,providerMetadata:W1.providerMetadata,steps:N0,experimental_context:b})),u0.setAttributes(await zN({telemetry:J,attributes:{"ai.response.finishReason":v0,"ai.response.text":{output:()=>W1.text},"ai.response.toolCalls":{output:()=>{var k1;return((k1=W1.toolCalls)==null?void 0:k1.length)?JSON.stringify(W1.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(W1.providerMetadata),"ai.usage.inputTokens":f0.inputTokens,"ai.usage.outputTokens":f0.outputTokens,"ai.usage.totalTokens":f0.totalTokens,"ai.usage.reasoningTokens":f0.reasoningTokens,"ai.usage.cachedInputTokens":f0.cachedInputTokens}}))}catch(v0){p0.error(v0)}finally{u0.end()}}}),_0=Rx4();this.addStream=_0.addStream,this.closeStream=_0.close;let b1=_0.stream.getReader(),S1=new ReadableStream({async start(p0){p0.enqueue({type:"start"})},async pull(p0){function v0(){_==null||_({steps:N0}),p0.enqueue({type:"abort"}),p0.close()}try{let{done:f0,value:W1}=await b1.read();if(f0){p0.close();return}if(W==null?void 0:W.aborted){v0();return}p0.enqueue(W1)}catch(f0){if(dW(f0)&&(W==null?void 0:W.aborted))v0();else p0.error(f0)}},cancel(p0){return _0.stream.cancel(p0)}});for(let p0 of q)S1=S1.pipeThrough(p0({tools:H,stopStream(){_0.terminate()}}));this.baseStream=S1.pipeThrough(_x4(N!=null?N:Z70())).pipeThrough(H0);let{maxRetries:x0,retry:D0}=Wx4({maxRetries:Y,abortSignal:W}),z0=eb4(J),j0=yb4(G),K0=ob4({model:Q,telemetry:J,headers:X,settings:{...j0,maxRetries:x0}}),L0=this;K70({name:"ai.streamText",attributes:zN({telemetry:J,attributes:{...W70({operationId:"ai.streamText",telemetry:J}),...K0,"ai.prompt":{input:()=>JSON.stringify({system:$,prompt:K,messages:Z})}}}),tracer:z0,endWhenDone:!1,fn:async(p0)=>{u0=p0;let v0=await rb4({system:$,prompt:K,messages:Z}),f0=v0.messages,W1=[],{approvedToolApprovals:k1,deniedToolApprovals:a1}=$x4({messages:f0});if(a1.length>0||k1.length>0){let n0=[...k1,...a1].filter((C1)=>C1.toolCall.providerExecuted),k0=k1.filter((C1)=>!C1.toolCall.providerExecuted),J1=a1.filter((C1)=>!C1.toolCall.providerExecuted),G6=a1.filter((C1)=>C1.toolCall.providerExecuted),$4,Z8=new ReadableStream({start(C1){$4=C1}});L0.addStream(Z8);try{for(let y0 of[...J1,...G6])$4==null||$4.enqueue({type:"tool-output-denied",toolCallId:y0.toolCall.toolCallId,toolName:y0.toolCall.toolName});let C1=[];if(await Promise.all(k0.map(async(y0)=>{let d4=await i31({toolCall:y0.toolCall,tools:H,tracer:z0,telemetry:J,messages:f0,abortSignal:W,experimental_context:b,onPreliminaryToolResult:(O)=>{$4==null||$4.enqueue(O)}});if(d4!=null)$4==null||$4.enqueue(d4),C1.push(d4)})),n0.length>0)W1.push({role:"tool",content:n0.map((y0)=>({type:"tool-approval-response",approvalId:y0.approvalResponse.approvalId,approved:y0.approvalResponse.approved,reason:y0.approvalResponse.reason,providerExecuted:!0}))});if(C1.length>0||J1.length>0){let y0=[];for(let d4 of C1)y0.push({type:"tool-result",toolCallId:d4.toolCallId,toolName:d4.toolName,output:await UN({toolCallId:d4.toolCallId,input:d4.input,tool:H==null?void 0:H[d4.toolName],output:d4.type==="tool-result"?d4.output:d4.error,errorMode:d4.type==="tool-error"?"json":"none"})});for(let d4 of J1)y0.push({type:"tool-result",toolCallId:d4.toolCall.toolCallId,toolName:d4.toolCall.toolName,output:{type:"execution-denied",reason:d4.approvalResponse.reason}});W1.push({role:"tool",content:y0})}}finally{$4==null||$4.close()}}g.push(...W1);async function l0({currentStep:n0,responseMessages:k0,usage:J1}){var G6,$4,Z8,C1,y0,d4;let O=L0.includeRawChunks;x=new IF;let f=[...f0,...k0],Q0=await(w==null?void 0:w({model:Q,steps:N0,stepNumber:N0.length,messages:f,experimental_context:b})),F0=x31((G6=Q0==null?void 0:Q0.model)!=null?G6:Q),B=await Sb4({prompt:{system:($4=Q0==null?void 0:Q0.system)!=null?$4:v0.system,messages:(Z8=Q0==null?void 0:Q0.messages)!=null?Z8:f},supportedUrls:await F0.supportedUrls,download:m}),{toolChoice:P,tools:h}=await fb4({tools:H,toolChoice:(C1=Q0==null?void 0:Q0.toolChoice)!=null?C1:F,activeTools:(y0=Q0==null?void 0:Q0.activeTools)!=null?y0:V});b=(d4=Q0==null?void 0:Q0.experimental_context)!=null?d4:b;let n=V70(D,Q0==null?void 0:Q0.providerOptions),{result:{stream:o,response:d,request:S0},doStreamSpan:s0,startTimestampMs:R1}=await D0(()=>K70({name:"ai.streamText.doStream",attributes:zN({telemetry:J,attributes:{...W70({operationId:"ai.streamText.doStream",telemetry:J}),...K0,"ai.model.provider":F0.provider,"ai.model.id":F0.modelId,"ai.prompt.messages":{input:()=>Qx4(B)},"ai.prompt.tools":{input:()=>h==null?void 0:h.map((C0)=>JSON.stringify(C0))},"ai.prompt.toolChoice":{input:()=>P!=null?JSON.stringify(P):void 0},"gen_ai.system":F0.provider,"gen_ai.request.model":F0.modelId,"gen_ai.request.frequency_penalty":j0.frequencyPenalty,"gen_ai.request.max_tokens":j0.maxOutputTokens,"gen_ai.request.presence_penalty":j0.presencePenalty,"gen_ai.request.stop_sequences":j0.stopSequences,"gen_ai.request.temperature":j0.temperature,"gen_ai.request.top_k":j0.topK,"gen_ai.request.top_p":j0.topP}}),tracer:z0,endWhenDone:!1,fn:async(C0)=>({startTimestampMs:M(),doStreamSpan:C0,result:await F0.doStream({...j0,tools:h,toolChoice:P,responseFormat:await(N==null?void 0:N.responseFormat),prompt:B,providerOptions:n,abortSignal:W,headers:X,includeRawChunks:O})})})),d0=vx4({tools:H,generatorStream:o,tracer:z0,telemetry:J,system:$,messages:f,repairToolCall:z,abortSignal:W,experimental_context:b,generateId:A}),L1=S0!=null?S0:{},T4=[],U8=[],v4,s9={},lJ="other",cX=void 0,t=eY0(),X0,q0=!0,E0={id:A(),timestamp:T(),modelId:Q.modelId},$0="";L0.addStream(d0.pipeThrough(new TransformStream({async transform(C0,w1){var W4,R4,N8,r1,I6;if(C0.type==="stream-start"){v4=C0.warnings;return}if(q0){let q4=M()-R1;q0=!1,s0.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":q4}),s0.setAttributes({"ai.response.msToFirstChunk":q4}),w1.enqueue({type:"start-step",request:L1,warnings:v4!=null?v4:[]})}let T8=C0.type;switch(T8){case"tool-approval-request":case"text-start":case"text-end":{w1.enqueue(C0);break}case"text-delta":{if(C0.delta.length>0)w1.enqueue({type:"text-delta",id:C0.id,text:C0.delta,providerMetadata:C0.providerMetadata}),$0+=C0.delta;break}case"reasoning-start":case"reasoning-end":{w1.enqueue(C0);break}case"reasoning-delta":{w1.enqueue({type:"reasoning-delta",id:C0.id,text:C0.delta,providerMetadata:C0.providerMetadata});break}case"tool-call":{w1.enqueue(C0),T4.push(C0);break}case"tool-result":{if(w1.enqueue(C0),!C0.preliminary)U8.push(C0);break}case"tool-error":{w1.enqueue(C0),U8.push(C0);break}case"response-metadata":{E0={id:(W4=C0.id)!=null?W4:E0.id,timestamp:(R4=C0.timestamp)!=null?R4:E0.timestamp,modelId:(N8=C0.modelId)!=null?N8:E0.modelId};break}case"finish":{t=C0.usage,lJ=C0.finishReason,cX=C0.rawFinishReason,X0=C0.providerMetadata;let q4=M()-R1;s0.addEvent("ai.stream.finish"),s0.setAttributes({"ai.response.msToFinish":q4,"ai.response.avgOutputTokensPerSecond":1000*((r1=t.outputTokens)!=null?r1:0)/q4});break}case"file":{w1.enqueue(C0);break}case"source":{w1.enqueue(C0);break}case"tool-input-start":{s9[C0.id]=C0.toolName;let q4=H==null?void 0:H[C0.toolName];if((q4==null?void 0:q4.onInputStart)!=null)await q4.onInputStart({toolCallId:C0.id,messages:f,abortSignal:W,experimental_context:b});w1.enqueue({...C0,dynamic:(I6=C0.dynamic)!=null?I6:(q4==null?void 0:q4.type)==="dynamic",title:q4==null?void 0:q4.title});break}case"tool-input-end":{delete s9[C0.id],w1.enqueue(C0);break}case"tool-input-delta":{let q4=s9[C0.id],u4=H==null?void 0:H[q4];if((u4==null?void 0:u4.onInputDelta)!=null)await u4.onInputDelta({inputTextDelta:C0.delta,toolCallId:C0.id,messages:f,abortSignal:W,experimental_context:b});w1.enqueue(C0);break}case"error":{w1.enqueue(C0),lJ="error";break}case"raw":{if(O)w1.enqueue(C0);break}default:throw Error(`Unknown chunk type: ${T8}`)}},async flush(C0){let w1=T4.length>0?JSON.stringify(T4):void 0;try{s0.setAttributes(await zN({telemetry:J,attributes:{"ai.response.finishReason":lJ,"ai.response.text":{output:()=>$0},"ai.response.toolCalls":{output:()=>w1},"ai.response.id":E0.id,"ai.response.model":E0.modelId,"ai.response.timestamp":E0.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(X0),"ai.usage.inputTokens":t.inputTokens,"ai.usage.outputTokens":t.outputTokens,"ai.usage.totalTokens":t.totalTokens,"ai.usage.reasoningTokens":t.reasoningTokens,"ai.usage.cachedInputTokens":t.cachedInputTokens,"gen_ai.response.finish_reasons":[lJ],"gen_ai.response.id":E0.id,"gen_ai.response.model":E0.modelId,"gen_ai.usage.input_tokens":t.inputTokens,"gen_ai.usage.output_tokens":t.outputTokens}}))}catch(r1){}finally{s0.end()}C0.enqueue({type:"finish-step",finishReason:lJ,rawFinishReason:cX,usage:t,providerMetadata:X0,response:{...E0,headers:d==null?void 0:d.headers}});let W4=Xx4(J1,t);await x.promise;let R4=T4.filter((r1)=>r1.providerExecuted!==!0),N8=U8.filter((r1)=>r1.providerExecuted!==!0);for(let r1 of T4){if(r1.providerExecuted!==!0)continue;let I6=H==null?void 0:H[r1.toolName];if((I6==null?void 0:I6.type)==="provider"&&I6.supportsDeferredResults){if(!U8.some((q4)=>q4.type==="tool-result"&&q4.toolCallId===r1.toolCallId))R0.set(r1.toolCallId,{toolName:r1.toolName})}}for(let r1 of U8)if(r1.type==="tool-result")R0.delete(r1.toolCallId);if((R4.length>0&&N8.length===R4.length||R0.size>0)&&!await Dx4({stopConditions:U,steps:N0})){k0.push(...await tZ1({content:N0[N0.length-1].content,tools:H}));try{await l0({currentStep:n0+1,responseMessages:k0,usage:W4})}catch(r1){C0.enqueue({type:"error",error:r1}),L0.closeStream()}}else C0.enqueue({type:"finish",finishReason:lJ,rawFinishReason:cX,totalUsage:W4}),L0.closeStream()}})))}await l0({currentStep:0,responseMessages:W1,usage:eY0()})}}).catch((p0)=>{L0.addStream(new ReadableStream({start(v0){v0.enqueue({type:"error",error:p0}),v0.close()}})),L0.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then((Q)=>Q[Q.length-1])}get content(){return this.finalStep.then((Q)=>Q.content)}get warnings(){return this.finalStep.then((Q)=>Q.warnings)}get providerMetadata(){return this.finalStep.then((Q)=>Q.providerMetadata)}get text(){return this.finalStep.then((Q)=>Q.text)}get reasoningText(){return this.finalStep.then((Q)=>Q.reasoningText)}get reasoning(){return this.finalStep.then((Q)=>Q.reasoning)}get sources(){return this.finalStep.then((Q)=>Q.sources)}get files(){return this.finalStep.then((Q)=>Q.files)}get toolCalls(){return this.finalStep.then((Q)=>Q.toolCalls)}get staticToolCalls(){return this.finalStep.then((Q)=>Q.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then((Q)=>Q.dynamicToolCalls)}get toolResults(){return this.finalStep.then((Q)=>Q.toolResults)}get staticToolResults(){return this.finalStep.then((Q)=>Q.staticToolResults)}get dynamicToolResults(){return this.finalStep.then((Q)=>Q.dynamicToolResults)}get usage(){return this.finalStep.then((Q)=>Q.usage)}get request(){return this.finalStep.then((Q)=>Q.request)}get response(){return this.finalStep.then((Q)=>Q.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}get rawFinishReason(){return this.consumeStream(),this._rawFinishReason.promise}teeStream(){let[Q,J]=this.baseStream.tee();return this.baseStream=J,Q}get textStream(){return Gh(this.teeStream().pipeThrough(new TransformStream({transform({part:Q},J){if(Q.type==="text-delta")J.enqueue(Q.text)}})))}get fullStream(){return Gh(this.teeStream().pipeThrough(new TransformStream({transform({part:Q},J){J.enqueue(Q)}})))}async consumeStream(Q){var J;try{await Cx4({stream:this.fullStream,onError:Q==null?void 0:Q.onError})}catch(X){(J=Q==null?void 0:Q.onError)==null||J.call(Q,X)}}get experimental_partialOutputStream(){return this.partialOutputStream}get partialOutputStream(){return Gh(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:Q},J){if(Q!=null)J.enqueue(Q)}})))}get output(){return this.finalStep.then((Q)=>{var J;return((J=this.outputSpecification)!=null?J:Z70()).parseCompleteOutput({text:Q.text},{response:Q.response,usage:Q.usage,finishReason:Q.finishReason})})}toUIMessageStream({originalMessages:Q,generateMessageId:J,onFinish:X,messageMetadata:G,sendReasoning:Y=!0,sendSources:W=!1,sendStart:$=!0,sendFinish:K=!0,onError:Z=KG}={}){let H=J!=null?Mx4({originalMessages:Q,responseMessageId:J}):void 0,F=(V)=>{var z;let U=(z=this.tools)==null?void 0:z[V.toolName];if(U==null)return V.dynamic;return(U==null?void 0:U.type)==="dynamic"?!0:void 0},q=this.fullStream.pipeThrough(new TransformStream({transform:async(V,z)=>{let U=G==null?void 0:G({part:V}),N=V.type;switch(N){case"text-start":{z.enqueue({type:"text-start",id:V.id,...V.providerMetadata!=null?{providerMetadata:V.providerMetadata}:{}});break}case"text-delta":{z.enqueue({type:"text-delta",id:V.id,delta:V.text,...V.providerMetadata!=null?{providerMetadata:V.providerMetadata}:{}});break}case"text-end":{z.enqueue({type:"text-end",id:V.id,...V.providerMetadata!=null?{providerMetadata:V.providerMetadata}:{}});break}case"reasoning-start":{z.enqueue({type:"reasoning-start",id:V.id,...V.providerMetadata!=null?{providerMetadata:V.providerMetadata}:{}});break}case"reasoning-delta":{if(Y)z.enqueue({type:"reasoning-delta",id:V.id,delta:V.text,...V.providerMetadata!=null?{providerMetadata:V.providerMetadata}:{}});break}case"reasoning-end":{z.enqueue({type:"reasoning-end",id:V.id,...V.providerMetadata!=null?{providerMetadata:V.providerMetadata}:{}});break}case"file":{z.enqueue({type:"file",mediaType:V.file.mediaType,url:`data:${V.file.mediaType};base64,${V.file.base64}`});break}case"source":{if(W&&V.sourceType==="url")z.enqueue({type:"source-url",sourceId:V.id,url:V.url,title:V.title,...V.providerMetadata!=null?{providerMetadata:V.providerMetadata}:{}});if(W&&V.sourceType==="document")z.enqueue({type:"source-document",sourceId:V.id,mediaType:V.mediaType,title:V.title,filename:V.filename,...V.providerMetadata!=null?{providerMetadata:V.providerMetadata}:{}});break}case"tool-input-start":{let D=F(V);z.enqueue({type:"tool-input-start",toolCallId:V.id,toolName:V.toolName,...V.providerExecuted!=null?{providerExecuted:V.providerExecuted}:{},...D!=null?{dynamic:D}:{},...V.title!=null?{title:V.title}:{}});break}case"tool-input-delta":{z.enqueue({type:"tool-input-delta",toolCallId:V.id,inputTextDelta:V.delta});break}case"tool-call":{let D=F(V);if(V.invalid)z.enqueue({type:"tool-input-error",toolCallId:V.toolCallId,toolName:V.toolName,input:V.input,...V.providerExecuted!=null?{providerExecuted:V.providerExecuted}:{},...V.providerMetadata!=null?{providerMetadata:V.providerMetadata}:{},...D!=null?{dynamic:D}:{},errorText:Z(V.error),...V.title!=null?{title:V.title}:{}});else z.enqueue({type:"tool-input-available",toolCallId:V.toolCallId,toolName:V.toolName,input:V.input,...V.providerExecuted!=null?{providerExecuted:V.providerExecuted}:{},...V.providerMetadata!=null?{providerMetadata:V.providerMetadata}:{},...D!=null?{dynamic:D}:{},...V.title!=null?{title:V.title}:{}});break}case"tool-approval-request":{z.enqueue({type:"tool-approval-request",approvalId:V.approvalId,toolCallId:V.toolCall.toolCallId});break}case"tool-result":{let D=F(V);z.enqueue({type:"tool-output-available",toolCallId:V.toolCallId,output:V.output,...V.providerExecuted!=null?{providerExecuted:V.providerExecuted}:{},...V.preliminary!=null?{preliminary:V.preliminary}:{},...D!=null?{dynamic:D}:{}});break}case"tool-error":{let D=F(V);z.enqueue({type:"tool-output-error",toolCallId:V.toolCallId,errorText:Z(V.error),...V.providerExecuted!=null?{providerExecuted:V.providerExecuted}:{},...D!=null?{dynamic:D}:{}});break}case"tool-output-denied":{z.enqueue({type:"tool-output-denied",toolCallId:V.toolCallId});break}case"error":{z.enqueue({type:"error",errorText:Z(V.error)});break}case"start-step":{z.enqueue({type:"start-step"});break}case"finish-step":{z.enqueue({type:"finish-step"});break}case"start":{if($)z.enqueue({type:"start",...U!=null?{messageMetadata:U}:{},...H!=null?{messageId:H}:{}});break}case"finish":{if(K)z.enqueue({type:"finish",finishReason:V.finishReason,...U!=null?{messageMetadata:U}:{}});break}case"abort":{z.enqueue(V);break}case"tool-input-end":break;case"raw":break;default:throw Error(`Unknown chunk type: ${N}`)}if(U!=null&&N!=="start"&&N!=="finish")z.enqueue({type:"message-metadata",messageMetadata:U})}}));return Gh(jx4({stream:q,messageId:H!=null?H:J==null?void 0:J(),originalMessages:Q,onFinish:X,onError:Z}))}pipeUIMessageStreamToResponse(Q,{originalMessages:J,generateMessageId:X,onFinish:G,messageMetadata:Y,sendReasoning:W,sendSources:$,sendFinish:K,sendStart:Z,onError:H,...F}={}){Ix4({response:Q,stream:this.toUIMessageStream({originalMessages:J,generateMessageId:X,onFinish:G,messageMetadata:Y,sendReasoning:W,sendSources:$,sendFinish:K,sendStart:Z,onError:H}),...F})}pipeTextStreamToResponse(Q,J){wx4({response:Q,textStream:this.textStream,...J})}toUIMessageStreamResponse({originalMessages:Q,generateMessageId:J,onFinish:X,messageMetadata:G,sendReasoning:Y,sendSources:W,sendFinish:$,sendStart:K,onError:Z,...H}={}){return Px4({stream:this.toUIMessageStream({originalMessages:Q,generateMessageId:J,onFinish:X,messageMetadata:G,sendReasoning:Y,sendSources:W,sendFinish:$,sendStart:K,onError:Z}),...H})}toTextStreamResponse(Q){return Lx4({textStream:this.textStream,...Q})}};async function QH1(Q,J){let X=[];if(J==null?void 0:J.ignoreIncompleteToolCalls)Q=Q.map((G)=>({...G,parts:G.parts.filter((Y)=>!aM(Y)||Y.state!=="input-streaming"&&Y.state!=="input-available")}));for(let G of Q)switch(G.role){case"system":{let Y=G.parts.filter(($)=>$.type==="text"),W=Y.reduce(($,K)=>{if(K.providerMetadata!=null)return{...$,...K.providerMetadata};return $},{});X.push({role:"system",content:Y.map(($)=>$.text).join(""),...Object.keys(W).length>0?{providerOptions:W}:{}});break}case"user":{X.push({role:"user",content:G.parts.map((Y)=>{var W;if(J70(Y))return{type:"text",text:Y.text,...Y.providerMetadata!=null?{providerOptions:Y.providerMetadata}:{}};if(X70(Y))return{type:"file",mediaType:Y.mediaType,filename:Y.filename,data:Y.url,...Y.providerMetadata!=null?{providerOptions:Y.providerMetadata}:{}};if(Q70(Y))return(W=J==null?void 0:J.convertDataPart)==null?void 0:W.call(J,Y)}).filter(HK1)});break}case"assistant":{if(G.parts!=null){let Y=[];async function W(){var $,K,Z,H,F,q;if(Y.length===0)return;let V=[];for(let U of Y)if(J70(U))V.push({type:"text",text:U.text,...U.providerMetadata!=null?{providerOptions:U.providerMetadata}:{}});else if(X70(U))V.push({type:"file",mediaType:U.mediaType,filename:U.filename,data:U.url});else if(eZ1(U))V.push({type:"reasoning",text:U.text,providerOptions:U.providerMetadata});else if(aM(U)){let N=Y70(U);if(U.state!=="input-streaming"){if(V.push({type:"tool-call",toolCallId:U.toolCallId,toolName:N,input:U.state==="output-error"?($=U.input)!=null?$:("rawInput"in U)?U.rawInput:void 0:U.input,providerExecuted:U.providerExecuted,...U.callProviderMetadata!=null?{providerOptions:U.callProviderMetadata}:{}}),U.approval!=null)V.push({type:"tool-approval-request",approvalId:U.approval.id,toolCallId:U.toolCallId});if(U.providerExecuted===!0&&U.state!=="approval-responded"&&(U.state==="output-available"||U.state==="output-error"))V.push({type:"tool-result",toolCallId:U.toolCallId,toolName:N,output:await UN({toolCallId:U.toolCallId,input:U.input,output:U.state==="output-error"?U.errorText:U.output,tool:(K=J==null?void 0:J.tools)==null?void 0:K[N],errorMode:U.state==="output-error"?"json":"none"}),...U.callProviderMetadata!=null?{providerOptions:U.callProviderMetadata}:{}})}}else if(Q70(U)){let N=(Z=J==null?void 0:J.convertDataPart)==null?void 0:Z.call(J,U);if(N!=null)V.push(N)}else throw Error(`Unsupported part: ${U}`);X.push({role:"assistant",content:V});let z=Y.filter((U)=>{var N;return aM(U)&&(U.providerExecuted!==!0||((N=U.approval)==null?void 0:N.approved)!=null)});if(z.length>0){let U=[];for(let N of z){if(((H=N.approval)==null?void 0:H.approved)!=null)U.push({type:"tool-approval-response",approvalId:N.approval.id,approved:N.approval.approved,reason:N.approval.reason,providerExecuted:N.providerExecuted});if(N.providerExecuted===!0)continue;switch(N.state){case"output-denied":{U.push({type:"tool-result",toolCallId:N.toolCallId,toolName:Y70(N),output:{type:"error-text",value:(F=N.approval.reason)!=null?F:"Tool execution denied."},...N.callProviderMetadata!=null?{providerOptions:N.callProviderMetadata}:{}});break}case"output-error":case"output-available":{let D=Y70(N);U.push({type:"tool-result",toolCallId:N.toolCallId,toolName:D,output:await UN({toolCallId:N.toolCallId,input:N.input,output:N.state==="output-error"?N.errorText:N.output,tool:(q=J==null?void 0:J.tools)==null?void 0:q[D],errorMode:N.state==="output-error"?"text":"none"}),...N.callProviderMetadata!=null?{providerOptions:N.callProviderMetadata}:{}});break}}}if(U.length>0)X.push({role:"tool",content:U})}Y=[]}for(let $ of G.parts)if(J70($)||eZ1($)||X70($)||aM($)||Q70($))Y.push($);else if($.type==="step-start")await W();await W();break}break}default:{let Y=G.role;throw new zb4({originalMessage:G,message:`Unsupported role: ${Y}`})}}return X}var Bc6=TQ(()=>d5(I.array(I.object({id:I.string(),role:I.enum(["system","user","assistant"]),metadata:I.unknown().optional(),parts:I.array(I.union([I.object({type:I.literal("text"),text:I.string(),state:I.enum(["streaming","done"]).optional(),providerMetadata:e1.optional()}),I.object({type:I.literal("reasoning"),text:I.string(),state:I.enum(["streaming","done"]).optional(),providerMetadata:e1.optional()}),I.object({type:I.literal("source-url"),sourceId:I.string(),url:I.string(),title:I.string().optional(),providerMetadata:e1.optional()}),I.object({type:I.literal("source-document"),sourceId:I.string(),mediaType:I.string(),title:I.string(),filename:I.string().optional(),providerMetadata:e1.optional()}),I.object({type:I.literal("file"),mediaType:I.string(),filename:I.string().optional(),url:I.string(),providerMetadata:e1.optional()}),I.object({type:I.literal("step-start")}),I.object({type:I.string().startsWith("data-"),id:I.string().optional(),data:I.unknown()}),I.object({type:I.literal("dynamic-tool"),toolName:I.string(),toolCallId:I.string(),state:I.literal("input-streaming"),input:I.unknown().optional(),providerExecuted:I.boolean().optional(),output:I.never().optional(),errorText:I.never().optional(),approval:I.never().optional()}),I.object({type:I.literal("dynamic-tool"),toolName:I.string(),toolCallId:I.string(),state:I.literal("input-available"),input:I.unknown(),providerExecuted:I.boolean().optional(),output:I.never().optional(),errorText:I.never().optional(),callProviderMetadata:e1.optional(),approval:I.never().optional()}),I.object({type:I.literal("dynamic-tool"),toolName:I.string(),toolCallId:I.string(),state:I.literal("approval-requested"),input:I.unknown(),providerExecuted:I.boolean().optional(),output:I.never().optional(),errorText:I.never().optional(),callProviderMetadata:e1.optional(),approval:I.object({id:I.string(),approved:I.never().optional(),reason:I.never().optional()})}),I.object({type:I.literal("dynamic-tool"),toolName:I.string(),toolCallId:I.string(),state:I.literal("approval-responded"),input:I.unknown(),providerExecuted:I.boolean().optional(),output:I.never().optional(),errorText:I.never().optional(),callProviderMetadata:e1.optional(),approval:I.object({id:I.string(),approved:I.boolean(),reason:I.string().optional()})}),I.object({type:I.literal("dynamic-tool"),toolName:I.string(),toolCallId:I.string(),state:I.literal("output-available"),input:I.unknown(),providerExecuted:I.boolean().optional(),output:I.unknown(),errorText:I.never().optional(),callProviderMetadata:e1.optional(),preliminary:I.boolean().optional(),approval:I.object({id:I.string(),approved:I.literal(!0),reason:I.string().optional()}).optional()}),I.object({type:I.literal("dynamic-tool"),toolName:I.string(),toolCallId:I.string(),state:I.literal("output-error"),input:I.unknown(),providerExecuted:I.boolean().optional(),output:I.never().optional(),errorText:I.string(),callProviderMetadata:e1.optional(),approval:I.object({id:I.string(),approved:I.literal(!0),reason:I.string().optional()}).optional()}),I.object({type:I.literal("dynamic-tool"),toolName:I.string(),toolCallId:I.string(),state:I.literal("output-denied"),input:I.unknown(),providerExecuted:I.boolean().optional(),output:I.never().optional(),errorText:I.never().optional(),callProviderMetadata:e1.optional(),approval:I.object({id:I.string(),approved:I.literal(!1),reason:I.string().optional()})}),I.object({type:I.string().startsWith("tool-"),toolCallId:I.string(),state:I.literal("input-streaming"),providerExecuted:I.boolean().optional(),input:I.unknown().optional(),output:I.never().optional(),errorText:I.never().optional(),approval:I.never().optional()}),I.object({type:I.string().startsWith("tool-"),toolCallId:I.string(),state:I.literal("input-available"),providerExecuted:I.boolean().optional(),input:I.unknown(),output:I.never().optional(),errorText:I.never().optional(),callProviderMetadata:e1.optional(),approval:I.never().optional()}),I.object({type:I.string().startsWith("tool-"),toolCallId:I.string(),state:I.literal("approval-requested"),input:I.unknown(),providerExecuted:I.boolean().optional(),output:I.never().optional(),errorText:I.never().optional(),callProviderMetadata:e1.optional(),approval:I.object({id:I.string(),approved:I.never().optional(),reason:I.never().optional()})}),I.object({type:I.string().startsWith("tool-"),toolCallId:I.string(),state:I.literal("approval-responded"),input:I.unknown(),providerExecuted:I.boolean().optional(),output:I.never().optional(),errorText:I.never().optional(),callProviderMetadata:e1.optional(),approval:I.object({id:I.string(),approved:I.boolean(),reason:I.string().optional()})}),I.object({type:I.string().startsWith("tool-"),toolCallId:I.string(),state:I.literal("output-available"),providerExecuted:I.boolean().optional(),input:I.unknown(),output:I.unknown(),errorText:I.never().optional(),callProviderMetadata:e1.optional(),preliminary:I.boolean().optional(),approval:I.object({id:I.string(),approved:I.literal(!0),reason:I.string().optional()}).optional()}),I.object({type:I.string().startsWith("tool-"),toolCallId:I.string(),state:I.literal("output-error"),providerExecuted:I.boolean().optional(),input:I.unknown(),output:I.never().optional(),errorText:I.string(),callProviderMetadata:e1.optional(),approval:I.object({id:I.string(),approved:I.literal(!0),reason:I.string().optional()}).optional()}),I.object({type:I.string().startsWith("tool-"),toolCallId:I.string(),state:I.literal("output-denied"),providerExecuted:I.boolean().optional(),input:I.unknown(),output:I.never().optional(),errorText:I.never().optional(),callProviderMetadata:e1.optional(),approval:I.object({id:I.string(),approved:I.literal(!1),reason:I.string().optional()})})])).nonempty("Message must contain at least one part")})).nonempty("Messages array must not be empty")));var Dc6=pW({prefix:"aiobj",size:24});var wc6=pW({prefix:"aiobj",size:24});function JH1({messages:Q,reasoning:J="none",toolCalls:X=[],emptyMessages:G="remove"}){if(J==="all"||J==="before-last-message")Q=Q.map((Y,W)=>{if(Y.role!=="assistant"||typeof Y.content==="string"||J==="before-last-message"&&W===Q.length-1)return Y;return{...Y,content:Y.content.filter(($)=>$.type!=="reasoning")}});if(X==="none")X=[];else if(X==="all")X=[{type:"all"}];else if(X==="before-last-message")X=[{type:"before-last-message"}];else if(typeof X==="string")X=[{type:X}];for(let Y of X){let W=Y.type==="all"?void 0:Y.type==="before-last-message"?1:Number(Y.type.slice(12).slice(0,-9)),$=new Set,K=new Set;if(W!=null){for(let Z of Q.slice(-W))if((Z.role==="assistant"||Z.role==="tool")&&typeof Z.content!=="string"){for(let H of Z.content)if(H.type==="tool-call"||H.type==="tool-result")$.add(H.toolCallId);else if(H.type==="tool-approval-request"||H.type==="tool-approval-response")K.add(H.approvalId)}}Q=Q.map((Z,H)=>{if(Z.role!=="assistant"&&Z.role!=="tool"||typeof Z.content==="string"||W&&H>=Q.length-W)return Z;let F={},q={};return{...Z,content:Z.content.filter((V)=>{if(V.type!=="tool-call"&&V.type!=="tool-result"&&V.type!=="tool-approval-request"&&V.type!=="tool-approval-response")return!0;if(V.type==="tool-call")F[V.toolCallId]=V.toolName;else if(V.type==="tool-approval-request")q[V.approvalId]=F[V.toolCallId];if((V.type==="tool-call"||V.type==="tool-result")&&$.has(V.toolCallId)||(V.type==="tool-approval-request"||V.type==="tool-approval-response")&&K.has(V.approvalId))return!0;return Y.tools!=null&&!Y.tools.includes(V.type==="tool-call"||V.type==="tool-result"?V.toolName:q[V.approvalId])})}})}if(G==="remove")Q=Q.filter((Y)=>Y.content.length>0);return Q}var hx4="AI_NoSuchProviderError",fx4=`vercel.ai.error.${hx4}`,bx4=Symbol.for(fx4),xx4;xx4=bx4;w4();function gx4(Q){if(!Q.body)throw Error("Response body is null");let J="";return Q.body.pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({transform(X,G){J+=X;let Y=J.split(`
1142
- `);J=Y.pop()??"";for(let W of Y)if(W.trim())try{let $=JSON.parse(W);G.enqueue($)}catch($){throw console.error("Failed to parse stream chunk:",$,X),$}},flush(X){if(J.trim())try{let G=JSON.parse(J);X.enqueue(G)}catch(G){throw console.error("Failed to parse final stream chunk:",G),G}}}))}var ux4=(Q)=>{return Object.fromEntries(Object.entries(Q).map(([J,X])=>[J,X.map((G)=>new RegExp(G))]))},XH1=(Q)=>{return{imageModel:()=>{throw Error("Image models are not supported by this provider")},textEmbeddingModel:()=>{throw Error("Text embedding models are not supported by this provider")},listModels:async()=>{return await Q.COLLECTION_LLM_LIST({})},languageModel:(J)=>{let X=$G(()=>Q.LLM_METADATA({modelId:J}).then((G)=>ux4(G.supportedUrls)));return{specificationVersion:"v2",provider:"llm-binding",modelId:J,supportedUrls:X,doGenerate:async(G)=>{let Y=await Q.LLM_DO_GENERATE({callOptions:G,modelId:J});return{...Y,usage:{inputTokens:Y.usage.inputTokens??void 0,outputTokens:Y.usage.outputTokens??void 0,totalTokens:Y.usage.totalTokens??void 0,reasoningTokens:Y.usage.reasoningTokens??void 0}}},doStream:async(G)=>{let Y=await Q.LLM_DO_STREAM({callOptions:G,modelId:J});return{stream:gx4(Y),response:{headers:Object.fromEntries(Y.headers?.entries()??[])}}}}}}};var mx4=32768,lx4=50,dx4=L.object({messages:L.any(),model:L.object({id:L.string(),connectionId:L.string(),provider:L.enum(["openai","anthropic","google","xai","deepseek","openrouter","openai-compatible"]).optional().nullable()}).passthrough().optional(),gateway:L.object({id:L.string()}).passthrough().optional(),stream:L.boolean().optional(),temperature:L.number().optional(),maxOutputTokens:L.number().optional(),maxWindowSize:L.number().optional(),thread_id:L.string().optional()}),YH1=new a5;function px4(Q,J){if(!Q.organization)throw Error("Organization context is required");if(Q.organization.slug!==J)throw Error("Organization slug mismatch");return Q.organization}async function cx4(Q,J,X){let G=await Q.storage.connections.findById(X);if(!G)return null;if(G.organization_id!==J)throw Error("Connection does not belong to organization");if(G.status!=="active")throw Error(`Connection is ${G.status.toUpperCase()}, not active`);return G}function nx4(Q,J){let X=v_(new URL(Q.url)),G=`${X.protocol}//${X.host}`,Y=new Headers,W=["cookie","authorization"];for(let $ of W)if(Q.headers.has($))Y.set($,Q.headers.get($));return new jW(new URL(`/mcp/gateway/${J}`,G),{requestInit:{headers:Y}})}YH1.post("/:org/models/stream",async(Q)=>{let J=Q.get("meshContext"),X=Q.req.param("org"),G=null;try{let Y=px4(J,X),W=await Q.req.json(),$=dx4.safeParse(W);if(!$.success)return Q.json({error:"Invalid request body",details:$.error.issues},400);let K=$.data;if(!K.model)return Q.json({error:"model is required"},400);let{model:Z,gateway:H,messages:F,temperature:q,maxOutputTokens:V=mx4,maxWindowSize:z=lx4,thread_id:U}=K;if(!H?.id)return Q.json({error:"gateway is required"},400);let N=nx4(Q.req.raw,H.id),[D,w,E]=await Promise.all([QH1(F,{ignoreIncompleteToolCalls:!0}),cx4(J,Y.id,Z.connectionId),lK1({transport:N})]);if(!w)return Q.json({error:`Model connection not found: ${Z.connectionId}`},404);G=E;let M=JH1({messages:D,reasoning:"before-last-message",emptyMessages:"remove",toolCalls:"none"}).slice(-z),[T,A]=await Promise.all([J.createMCPProxy(w),E.tools({schemas:"automatic"})]),j=HY1.forClient(T),R=XH1(j).languageModel(Z.id);return e31({model:R,messages:M,tools:A,temperature:q,maxOutputTokens:V,abortSignal:Q.req.raw.signal,stopWhen:z70(30),onError:async(_)=>{console.error("[models:stream] Error",_),await E.close().catch(console.error)},onFinish:async()=>{await E.close().catch(console.error)}}).toUIMessageStreamResponse({messageMetadata:({part:_})=>{if(_.type==="start")return{gateway:H,model:Z,created_at:new Date,thread_id:U};if(_.type==="finish-step")return{usage:{..._.usage,providerMetadata:_.providerMetadata}};return{}}})}catch(Y){let W=Y;if(await G?.close().catch(console.error),W.name==="AbortError")return console.warn("[models:stream] Aborted",JSON.stringify({org:X})),Q.json({error:"Request aborted"},400);return console.error("[models:stream] Failed",JSON.stringify({org:X,error:W.message,stack:W.stack})),Q.json({error:W.message},500)}});var GH1=YH1;var Kh=null,ix4=new WH1.PrometheusSerializer,rx4=()=>m00(_W),ax4=()=>u00(_W);function $H1(Q={}){let J=Q.database??yv();if(Kh&&Kh.isRunning())console.log("[EventBus] Stopping previous worker (HMR cleanup)"),Promise.resolve(Kh.stop()).catch(($)=>{console.error("[EventBus] Error stopping previous worker:",$)});let X;if(Q.eventBus)X=Q.eventBus;else X=l71(J);Kh=X;let G=new a5;G.use("/*",ix0({origin:($)=>{if($.includes("localhost")||$.includes("127.0.0.1"))return $;return $},credentials:!0,allowMethods:["GET","POST","PUT","DELETE","OPTIONS"],allowHeaders:["Content-Type","Authorization","mcp-protocol-version"]})),G.use("*",ox0()),G.get(iP.HEALTH,($)=>{return $.json({status:"ok",timestamp:new Date().toISOString(),version:"1.0.0"})}),G.get(iP.METRICS,async($)=>{try{let K=await Pl.collect(),Z=ix4.serialize(K.resourceMetrics);return $.text(Z,200,{"Content-Type":"text/plain; version=0.0.4; charset=utf-8"})}catch(K){return console.error("Failed to collect metrics:",K),$.text("# Error collecting metrics",500)}}),G.route("/api/auth/custom",c71),G.all("/api/auth/*",async($)=>{return await _W.handler($.req.raw)}),G.route("/",L71),G.all("/oauth-proxy/:connectionId/*",async($)=>{let K=$.req.param("connectionId"),Z=$.req.path.split("/").filter(Boolean),H=Z[Z.length-1],F=$.get("meshContext");if(!F)F=await $Z.create($.req.raw),$.set("meshContext",F);let q=await F.storage.connections.findById(K);if(!q?.connection_url)return $.json({error:"Connection not found"},404);let V=await S_(q.connection_url);if(!V.ok)return $.json({error:"Failed to get resource metadata"},502);let U=(await V.json()).authorization_servers?.[0];if(!U)return $.json({error:"No authorization server found"},404);let N=await h90(U);if(!N.ok)return $.json({error:"Failed to get auth server metadata"},502);let D=await N.json(),w;if(H==="authorize")w=D.authorization_endpoint;else if(H==="token")w=D.token_endpoint;else if(H==="register")w=D.registration_endpoint;if(!w)return $.json({error:`Unknown OAuth endpoint: ${H}`},404);let E=new URL(w),M=new URL($.req.url);if(E.search=M.search,H==="authorize")return $.redirect(E.toString(),302);let T={Accept:$.req.header("Accept")||"application/json"},A=$.req.header("Content-Type");if(A)T["Content-Type"]=A;let j=$.req.header("Authorization");if(j)T.Authorization=j;let R=await fetch(E.toString(),{method:$.req.method,headers:T,body:$.req.method!=="GET"&&$.req.method!=="HEAD"?$.req.raw.body:void 0,duplex:"half",redirect:"manual"}),v=new Headers,_=["connection","keep-alive","transfer-encoding","content-encoding","content-length"];for(let[y,b]of R.headers.entries())if(!_.includes(y.toLowerCase()))v.set(y,b);return new Response(R.body,{status:R.status,statusText:R.statusText,headers:v})}),G.get("/mcp/:gateway?/:connectionId/.well-known/oauth-protected-resource/*",async($)=>{let Z=await rx4()($.req.raw),H=await Z.json();return Response.json(H,Z)});let Y=async($)=>{let Z=await ax4()($.req.raw),H=await Z.json();return Response.json(H,Z)};G.get("/.well-known/oauth-authorization-server/*/:gateway?/:connectionId?",Y),$Z.set(R71({db:J.db,auth:_W,encryption:{key:process.env.ENCRYPTION_KEY||""},observability:{tracer:FO,meter:Ex0},eventBus:X})),Promise.resolve(X.start()).then(()=>{console.log("[EventBus] Worker started")}),G.use("*",async($,K)=>{if(k71($.req.path))return K();let Z=await $Z.create($.req.raw);return $.set("meshContext",Z),K()}),G.get("/api/tools/management",($)=>{return $.json({tools:kl,grouped:NO()})});let W=async($,K)=>{let Z=$.var.meshContext;if(!Z.auth.user?.id&&!Z.auth.apiKey?.id){let H=new URL($.req.url);return $.res=new Response(null,{status:401,headers:{"WWW-Authenticate":`Bearer realm="mcp",resource_metadata="${H.origin}${H.pathname}/.well-known/oauth-protected-resource"`}})}return await K()};return G.use("/mcp/:connectionId?",W),G.use("/mcp/gateway/:gatewayId?",W),G.route("/mcp",vG1),G.route("/mcp",_G1),G.route("/mcp",I71),G.route("/api",GH1),G.notFound(($)=>{return $.json({error:"Not Found",path:$.req.path},404)}),G.onError(($,K)=>{console.error("Server error :",$);let Z=$ instanceof Error?$.message:"Unknown error";return K.json({error:"Internal Server Error",message:Z},500)}),G}var KH1=["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"],ox4=/^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/,sx4=(Q,J)=>{if(!Q)return{};let X=new Headers(Q.headers);if(J){let G=X.get("connection");if(G){let Y=G.split(",").map(($)=>$.trim()),W=Y.filter(($)=>!ox4.test($));if(W.length>0)throw new Tl(400,{message:`Invalid Connection header value: ${W.join(", ")}`});Y.forEach(($)=>{X.delete($)})}}return KH1.forEach((G)=>{X.delete(G)}),{method:Q.method,body:Q.body,duplex:Q.body?"half":void 0,headers:X,signal:Q.signal}},tx4=(Q)=>{if(!Q.headers||Array.isArray(Q.headers)||Q.headers instanceof Headers)return Q;let J=new Headers;for(let[X,G]of Object.entries(Q.headers))if(G==null)J.delete(X);else J.set(X,G);return Q.headers=J,Q},ZH1=async(Q,J)=>{let{raw:X,customFetch:G,strictConnectionProcessing:Y=!1,...W}=J instanceof Request?{raw:J}:J??{},$=new Request(Q,{...sx4(X,Y),...tx4(W)});$.headers.delete("accept-encoding");let K=await(G||fetch)($),Z=new Headers(K.headers);if(KH1.forEach((H)=>{Z.delete(H)}),Z.has("content-encoding"))Z.delete("content-encoding"),Z.delete("content-length");return new Response(K.body,{status:K.status,statusText:K.statusText,headers:Z})};var HH1=(Q)=>(J)=>{let X=new URL(J.req.raw.url),G=new URL(Q);return G.pathname=X.pathname,G.search=X.search,ZH1(G,{raw:J.req.raw,headers:{...J.req.raw.headers}})};import{resolve as tM,dirname as ex4}from"path";var Qg4="http://localhost:4000",Jg4="./dist/client";function Xg4(Q,J){let X=tM(J),G=tM(Q);return G===X||G.startsWith(X+"/")}function Yg4({requestPath:Q,clientDir:J}){let X=Q.startsWith("/")?Q.slice(1):Q,G=tM(J,X);if(!Xg4(G,J))return null;return G}function FH1(Q,J="../client"){let X=new URL(Q),G=ex4(X.pathname);return tM(G,J)}function qH1(Q={}){let{env:J="production",devServerUrl:X=Qg4,clientDir:G=Jg4,isServerPath:Y=()=>!1}=Q;if(J==="development"){let W=HH1(X);return async function(K){let Z=new URL(K.url);if(Y(Z.pathname))return null;let H={req:{raw:K,url:K.url}};return W(H)}}return async function($){if($.method!=="GET")return null;let K=new URL($.url),Z;try{Z=decodeURIComponent(K.pathname)}catch{return null}if(Y(Z))return null;let H=Yg4({requestPath:Z,clientDir:G});if(!H)return null;let F=tM(G,"index.html");for(let q of[H,F])try{let V=Bun.file(q);if(await V.exists())return new Response(V)}catch{}return null}}var VH1=parseInt(process.env.PORT||"3000",10),Zh="\x1B[0m",Gg4="\x1B[1m",Wg4="\x1B[2m",$g4="\x1B[32m",Kg4="\x1B[36m",Zg4="\x1B[4m",Hg4=`http://localhost:${VH1}`,Fg4=qH1({clientDir:FH1(import.meta.url,"../client"),isServerPath:v71}),qg4=$H1();console.log("");console.log(`${$g4}\u2713${Zh} ${Gg4}Ready${Zh}`);console.log("");console.log(` ${Wg4}Open in browser:${Zh} ${Kg4}${Zg4}${Hg4}${Zh}`);console.log("");Bun.serve({idleTimeout:0,port:VH1,hostname:"0.0.0.0",fetch:async(Q)=>{return await Fg4(Q)??qg4.fetch(Q)},development:!1});
1142
+ `);J=Y.pop()??"";for(let W of Y)if(W.trim())try{let $=JSON.parse(W);G.enqueue($)}catch($){throw console.error("Failed to parse stream chunk:",$,X),$}},flush(X){if(J.trim())try{let G=JSON.parse(J);X.enqueue(G)}catch(G){throw console.error("Failed to parse final stream chunk:",G),G}}}))}var ux4=(Q)=>{return Object.fromEntries(Object.entries(Q).map(([J,X])=>[J,X.map((G)=>new RegExp(G))]))},XH1=(Q)=>{return{imageModel:()=>{throw Error("Image models are not supported by this provider")},textEmbeddingModel:()=>{throw Error("Text embedding models are not supported by this provider")},listModels:async()=>{return await Q.COLLECTION_LLM_LIST({})},languageModel:(J)=>{let X=$G(()=>Q.LLM_METADATA({modelId:J}).then((G)=>ux4(G.supportedUrls)));return{specificationVersion:"v2",provider:"llm-binding",modelId:J,supportedUrls:X,doGenerate:async(G)=>{let Y=await Q.LLM_DO_GENERATE({callOptions:G,modelId:J});return{...Y,usage:{inputTokens:Y.usage.inputTokens??void 0,outputTokens:Y.usage.outputTokens??void 0,totalTokens:Y.usage.totalTokens??void 0,reasoningTokens:Y.usage.reasoningTokens??void 0}}},doStream:async(G)=>{let Y=await Q.LLM_DO_STREAM({callOptions:G,modelId:J});return{stream:gx4(Y),response:{headers:Object.fromEntries(Y.headers?.entries()??[])}}}}}}};var mx4=32768,lx4=50,dx4=L.object({messages:L.any(),model:L.object({id:L.string(),connectionId:L.string(),provider:L.enum(["openai","anthropic","google","xai","deepseek","openrouter","openai-compatible"]).optional().nullable()}).passthrough().optional(),gateway:L.object({id:L.string()}).passthrough().optional(),stream:L.boolean().optional(),temperature:L.number().optional(),maxOutputTokens:L.number().optional(),maxWindowSize:L.number().optional(),thread_id:L.string().optional()}),YH1=new a5;function px4(Q,J){if(!Q.organization)throw Error("Organization context is required");if(Q.organization.slug!==J)throw Error("Organization slug mismatch");return Q.organization}async function cx4(Q,J,X){let G=await Q.storage.connections.findById(X);if(!G)return null;if(G.organization_id!==J)throw Error("Connection does not belong to organization");if(G.status!=="active")throw Error(`Connection is ${G.status.toUpperCase()}, not active`);return G}function nx4(Q,J){let X=v_(new URL(Q.url)),G=`${X.protocol}//${X.host}`,Y=new Headers,W=["cookie","authorization"];for(let $ of W)if(Q.headers.has($))Y.set($,Q.headers.get($));return new jW(new URL(`/mcp/gateway/${J}`,G),{requestInit:{headers:Y}})}YH1.post("/:org/models/stream",async(Q)=>{let J=Q.get("meshContext"),X=Q.req.param("org"),G=null;try{let Y=px4(J,X),W=await Q.req.json(),$=dx4.safeParse(W);if(!$.success)return Q.json({error:"Invalid request body",details:$.error.issues},400);let K=$.data;if(!K.model)return Q.json({error:"model is required"},400);let{model:Z,gateway:H,messages:F,temperature:q,maxOutputTokens:V=mx4,maxWindowSize:z=lx4,thread_id:U}=K;if(!H?.id)return Q.json({error:"gateway is required"},400);let N=nx4(Q.req.raw,H.id),[D,w,E]=await Promise.all([QH1(F,{ignoreIncompleteToolCalls:!0}),cx4(J,Y.id,Z.connectionId),lK1({transport:N})]);if(!w)return Q.json({error:`Model connection not found: ${Z.connectionId}`},404);G=E;let M=D.find((m)=>m.role==="system"),T=M?.role==="system"?M.content:void 0,A=D.filter((m)=>m.role!=="system"),j=JH1({messages:A,reasoning:"before-last-message",emptyMessages:"remove",toolCalls:"none"}).slice(-z),[R,v]=await Promise.all([J.createMCPProxy(w),E.tools({schemas:"automatic"})]),_=HY1.forClient(R),y=XH1(_).languageModel(Z.id);return e31({model:y,system:T,messages:j,tools:v,temperature:q,maxOutputTokens:V,abortSignal:Q.req.raw.signal,stopWhen:z70(30),onError:async(m)=>{console.error("[models:stream] Error",m),await E.close().catch(console.error)},onFinish:async()=>{await E.close().catch(console.error)}}).toUIMessageStreamResponse({messageMetadata:({part:m})=>{if(m.type==="start")return{gateway:H,model:Z,created_at:new Date,thread_id:U};if(m.type==="finish-step")return{usage:{...m.usage,providerMetadata:m.providerMetadata}};return{}}})}catch(Y){let W=Y;if(await G?.close().catch(console.error),W.name==="AbortError")return console.warn("[models:stream] Aborted",JSON.stringify({org:X})),Q.json({error:"Request aborted"},400);return console.error("[models:stream] Failed",JSON.stringify({org:X,error:W.message,stack:W.stack})),Q.json({error:W.message},500)}});var GH1=YH1;var Kh=null,ix4=new WH1.PrometheusSerializer,rx4=()=>m00(_W),ax4=()=>u00(_W);function $H1(Q={}){let J=Q.database??yv();if(Kh&&Kh.isRunning())console.log("[EventBus] Stopping previous worker (HMR cleanup)"),Promise.resolve(Kh.stop()).catch(($)=>{console.error("[EventBus] Error stopping previous worker:",$)});let X;if(Q.eventBus)X=Q.eventBus;else X=l71(J);Kh=X;let G=new a5;G.use("/*",ix0({origin:($)=>{if($.includes("localhost")||$.includes("127.0.0.1"))return $;return $},credentials:!0,allowMethods:["GET","POST","PUT","DELETE","OPTIONS"],allowHeaders:["Content-Type","Authorization","mcp-protocol-version"]})),G.use("*",ox0()),G.get(iP.HEALTH,($)=>{return $.json({status:"ok",timestamp:new Date().toISOString(),version:"1.0.0"})}),G.get(iP.METRICS,async($)=>{try{let K=await Pl.collect(),Z=ix4.serialize(K.resourceMetrics);return $.text(Z,200,{"Content-Type":"text/plain; version=0.0.4; charset=utf-8"})}catch(K){return console.error("Failed to collect metrics:",K),$.text("# Error collecting metrics",500)}}),G.route("/api/auth/custom",c71),G.all("/api/auth/*",async($)=>{return await _W.handler($.req.raw)}),G.route("/",L71),G.all("/oauth-proxy/:connectionId/*",async($)=>{let K=$.req.param("connectionId"),Z=$.req.path.split("/").filter(Boolean),H=Z[Z.length-1],F=$.get("meshContext");if(!F)F=await $Z.create($.req.raw),$.set("meshContext",F);let q=await F.storage.connections.findById(K);if(!q?.connection_url)return $.json({error:"Connection not found"},404);let V=await S_(q.connection_url);if(!V.ok)return $.json({error:"Failed to get resource metadata"},502);let U=(await V.json()).authorization_servers?.[0];if(!U)return $.json({error:"No authorization server found"},404);let N=await h90(U);if(!N.ok)return $.json({error:"Failed to get auth server metadata"},502);let D=await N.json(),w;if(H==="authorize")w=D.authorization_endpoint;else if(H==="token")w=D.token_endpoint;else if(H==="register")w=D.registration_endpoint;if(!w)return $.json({error:`Unknown OAuth endpoint: ${H}`},404);let E=new URL(w),M=new URL($.req.url);if(E.search=M.search,H==="authorize")return $.redirect(E.toString(),302);let T={Accept:$.req.header("Accept")||"application/json"},A=$.req.header("Content-Type");if(A)T["Content-Type"]=A;let j=$.req.header("Authorization");if(j)T.Authorization=j;let R=await fetch(E.toString(),{method:$.req.method,headers:T,body:$.req.method!=="GET"&&$.req.method!=="HEAD"?$.req.raw.body:void 0,duplex:"half",redirect:"manual"}),v=new Headers,_=["connection","keep-alive","transfer-encoding","content-encoding","content-length"];for(let[y,b]of R.headers.entries())if(!_.includes(y.toLowerCase()))v.set(y,b);return new Response(R.body,{status:R.status,statusText:R.statusText,headers:v})}),G.get("/mcp/:gateway?/:connectionId/.well-known/oauth-protected-resource/*",async($)=>{let Z=await rx4()($.req.raw),H=await Z.json();return Response.json(H,Z)});let Y=async($)=>{let Z=await ax4()($.req.raw),H=await Z.json();return Response.json(H,Z)};G.get("/.well-known/oauth-authorization-server/*/:gateway?/:connectionId?",Y),$Z.set(R71({db:J.db,auth:_W,encryption:{key:process.env.ENCRYPTION_KEY||""},observability:{tracer:FO,meter:Ex0},eventBus:X})),Promise.resolve(X.start()).then(()=>{console.log("[EventBus] Worker started")}),G.use("*",async($,K)=>{if(k71($.req.path))return K();let Z=await $Z.create($.req.raw);return $.set("meshContext",Z),K()}),G.get("/api/tools/management",($)=>{return $.json({tools:kl,grouped:NO()})});let W=async($,K)=>{let Z=$.var.meshContext;if(!Z.auth.user?.id&&!Z.auth.apiKey?.id){let H=new URL($.req.url);return $.res=new Response(null,{status:401,headers:{"WWW-Authenticate":`Bearer realm="mcp",resource_metadata="${H.origin}${H.pathname}/.well-known/oauth-protected-resource"`}})}return await K()};return G.use("/mcp/:connectionId?",W),G.use("/mcp/gateway/:gatewayId?",W),G.route("/mcp",vG1),G.route("/mcp",_G1),G.route("/mcp",I71),G.route("/api",GH1),G.notFound(($)=>{return $.json({error:"Not Found",path:$.req.path},404)}),G.onError(($,K)=>{console.error("Server error :",$);let Z=$ instanceof Error?$.message:"Unknown error";return K.json({error:"Internal Server Error",message:Z},500)}),G}var KH1=["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"],ox4=/^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/,sx4=(Q,J)=>{if(!Q)return{};let X=new Headers(Q.headers);if(J){let G=X.get("connection");if(G){let Y=G.split(",").map(($)=>$.trim()),W=Y.filter(($)=>!ox4.test($));if(W.length>0)throw new Tl(400,{message:`Invalid Connection header value: ${W.join(", ")}`});Y.forEach(($)=>{X.delete($)})}}return KH1.forEach((G)=>{X.delete(G)}),{method:Q.method,body:Q.body,duplex:Q.body?"half":void 0,headers:X,signal:Q.signal}},tx4=(Q)=>{if(!Q.headers||Array.isArray(Q.headers)||Q.headers instanceof Headers)return Q;let J=new Headers;for(let[X,G]of Object.entries(Q.headers))if(G==null)J.delete(X);else J.set(X,G);return Q.headers=J,Q},ZH1=async(Q,J)=>{let{raw:X,customFetch:G,strictConnectionProcessing:Y=!1,...W}=J instanceof Request?{raw:J}:J??{},$=new Request(Q,{...sx4(X,Y),...tx4(W)});$.headers.delete("accept-encoding");let K=await(G||fetch)($),Z=new Headers(K.headers);if(KH1.forEach((H)=>{Z.delete(H)}),Z.has("content-encoding"))Z.delete("content-encoding"),Z.delete("content-length");return new Response(K.body,{status:K.status,statusText:K.statusText,headers:Z})};var HH1=(Q)=>(J)=>{let X=new URL(J.req.raw.url),G=new URL(Q);return G.pathname=X.pathname,G.search=X.search,ZH1(G,{raw:J.req.raw,headers:{...J.req.raw.headers}})};import{resolve as tM,dirname as ex4}from"path";var Qg4="http://localhost:4000",Jg4="./dist/client";function Xg4(Q,J){let X=tM(J),G=tM(Q);return G===X||G.startsWith(X+"/")}function Yg4({requestPath:Q,clientDir:J}){let X=Q.startsWith("/")?Q.slice(1):Q,G=tM(J,X);if(!Xg4(G,J))return null;return G}function FH1(Q,J="../client"){let X=new URL(Q),G=ex4(X.pathname);return tM(G,J)}function qH1(Q={}){let{env:J="production",devServerUrl:X=Qg4,clientDir:G=Jg4,isServerPath:Y=()=>!1}=Q;if(J==="development"){let W=HH1(X);return async function(K){let Z=new URL(K.url);if(Y(Z.pathname))return null;let H={req:{raw:K,url:K.url}};return W(H)}}return async function($){if($.method!=="GET")return null;let K=new URL($.url),Z;try{Z=decodeURIComponent(K.pathname)}catch{return null}if(Y(Z))return null;let H=Yg4({requestPath:Z,clientDir:G});if(!H)return null;let F=tM(G,"index.html");for(let q of[H,F])try{let V=Bun.file(q);if(await V.exists())return new Response(V)}catch{}return null}}var VH1=parseInt(process.env.PORT||"3000",10),Zh="\x1B[0m",Gg4="\x1B[1m",Wg4="\x1B[2m",$g4="\x1B[32m",Kg4="\x1B[36m",Zg4="\x1B[4m",Hg4=`http://localhost:${VH1}`,Fg4=qH1({clientDir:FH1(import.meta.url,"../client"),isServerPath:v71}),qg4=$H1();console.log("");console.log(`${$g4}\u2713${Zh} ${Gg4}Ready${Zh}`);console.log("");console.log(` ${Wg4}Open in browser:${Zh} ${Kg4}${Zg4}${Hg4}${Zh}`);console.log("");Bun.serve({idleTimeout:0,port:VH1,hostname:"0.0.0.0",fetch:async(Q)=>{return await Fg4(Q)??qg4.fetch(Q)},development:!1});