@decocms/mesh 1.0.0-alpha.42 → 1.0.0-alpha.43
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/assets/{AlertCircle-CP-aGRsA.js → AlertCircle-D8keEzKG.js} +1 -1
- package/dist/client/assets/{ArrowLeft-wElnUYJ0.js → ArrowLeft-ALWG7VDf.js} +1 -1
- package/dist/client/assets/{CheckCircle-B_WVChj1.js → CheckCircle-D36cNDna.js} +1 -1
- package/dist/client/assets/{ChevronDown-133w8HOk.js → ChevronDown-Cm9t42v8.js} +1 -1
- package/dist/client/assets/{Clock-DqQ41LIc.js → Clock-CmEgvKtS.js} +1 -1
- package/dist/client/assets/{Copy01-BJwDNoQC.js → Copy01-ByJnMw1O.js} +1 -1
- package/dist/client/assets/{CpuChip02-bWa1f3Y1.js → CpuChip02-CON88pJ9.js} +1 -1
- package/dist/client/assets/{DotsVertical-CYYr09mb.js → DotsVertical-Bl5bEEk5.js} +1 -1
- package/dist/client/assets/{File06-Dtn5wW91.js → File06-aktnYzlw.js} +1 -1
- package/dist/client/assets/{Grid01-DZvMiQMk.js → Grid01-CMcq9qMK.js} +1 -1
- package/dist/client/assets/{Inbox01-CSe7MExo.js → Inbox01-CDP4Xvq8.js} +1 -1
- package/dist/client/assets/{InfoCircle-D3bW5Omw.js → InfoCircle-Dj48FaPG.js} +1 -1
- package/dist/client/assets/{Key01-C1qHez6H.js → Key01-DUuXuIEi.js} +1 -1
- package/dist/client/assets/{LinkExternal01-BWIXuo1e.js → LinkExternal01-DD1V7jlt.js} +1 -1
- package/dist/client/assets/{Loading01-CAh3R9sn.js → Loading01-CHuzyTrw.js} +1 -1
- package/dist/client/assets/{Plus-CYOELvWT.js → Plus-DsLFvXGg.js} +1 -1
- package/dist/client/assets/{SearchMd-Bq2ogvbg.js → SearchMd-AkbTxzGe.js} +1 -1
- package/dist/client/assets/{Trash01-KvM_z2HW.js → Trash01-Dy-SjaGQ.js} +1 -1
- package/dist/client/assets/{Upload01-BP0jqpHq.js → Upload01-D6dc6enb.js} +1 -1
- package/dist/client/assets/{X-CafPP_Iv.js → X-C4DsqTZD.js} +1 -1
- package/dist/client/assets/{XClose-CqJrzETU.js → XClose-RibbcNd2.js} +1 -1
- package/dist/client/assets/{alert-dialog-BUlG7TA4.js → alert-dialog-Di6ShLn9.js} +3 -3
- package/dist/client/assets/{auth-CJSooDCA.js → auth-D5CL68LS.js} +1 -1
- package/dist/client/assets/{auth-catchall-BjCX5usv.js → auth-catchall-D9jFZcp2.js} +1 -1
- package/dist/client/assets/{avatar-Cq0eS4K8.js → avatar-DCq0OD4f.js} +1 -1
- package/dist/client/assets/{badge-DwRxIVxi.js → badge-Cxx1Sxkf.js} +1 -1
- package/dist/client/assets/{button-DylnVNOq.js → button-DyxbcOso.js} +1 -1
- package/dist/client/assets/{card-DxJ2CMrY.js → card-E0A-GI_K.js} +1 -1
- package/dist/client/assets/{checkbox-DEErbcc0.js → checkbox-D_hM8b8h.js} +1 -1
- package/dist/client/assets/{collection-detail-CrH6CPOn.js → collection-detail-BUkQA_DU.js} +1 -1
- package/dist/client/assets/{collection-display-button-CvZ8eTT6.js → collection-display-button-BweLYsfq.js} +1 -1
- package/dist/client/assets/{collection-header-BZWDRhRJ.js → collection-header-Bameh_eh.js} +1 -1
- package/dist/client/assets/{collection-page-Cy4Url61.js → collection-page-BHSRRg3H.js} +1 -1
- package/dist/client/assets/{collection-search-BEr5-om_.js → collection-search-gavQJPP4.js} +1 -1
- package/dist/client/assets/{collection-table-wrapper-CYIQZiF8.js → collection-table-wrapper-BpS-68hf.js} +1 -1
- package/dist/client/assets/{connection-card-Cjb0De9E.js → connection-card-BVk7kFmW.js} +1 -1
- package/dist/client/assets/{connection-detail-CtapWDy0.js → connection-detail-DddBMHPf.js} +1 -1
- package/dist/client/assets/connections-B1rZil2n.js +1 -0
- package/dist/client/assets/{core-CwMiM80c.js → core-ByNFtKK6.js} +1 -1
- package/dist/client/assets/{create-organization-dialog-CDHLiEAk.js → create-organization-dialog-2urgxKJd.js} +1 -1
- package/dist/client/assets/{deco-chat-skeleton-DpvJuUNp.js → deco-chat-skeleton-DPM9016H.js} +3 -3
- package/dist/client/assets/{dialog-DHu5nMEY.js → dialog-fscHVB6N.js} +1 -1
- package/dist/client/assets/{dropdown-menu-DiYpBa-u.js → dropdown-menu-PdTp4dEf.js} +1 -1
- package/dist/client/assets/{error-boundary-xo0wHpmi.js → error-boundary-B2cVFy_k.js} +1 -1
- package/dist/client/assets/{extract-connection-data-CuVedqWo.js → extract-connection-data-DYfXaCx-.js} +1 -1
- package/dist/client/assets/{form-DJrhF5P2.js → form-DzRrgnqZ.js} +1 -1
- package/dist/client/assets/{formatDistanceToNow-BbvSNUQF.js → formatDistanceToNow-BUS4qZ3y.js} +1 -1
- package/dist/client/assets/{gateway-detail-BOFhJRga.js → gateway-detail-CNtXr5hn.js} +1 -1
- package/dist/client/assets/{gateways-EOO6wJEW.js → gateways-B0oJ21bg.js} +1 -1
- package/dist/client/assets/{home-BFuz55uE.js → home-CbM5g6hK.js} +1 -1
- package/dist/client/assets/{index-dUwc3ttQ.js → index-BfBFtyJG.js} +1 -1
- package/dist/client/assets/{index-DrO6_oKQ.js → index-BoajXOR2.js} +3 -3
- package/dist/client/assets/{index-Dm4arKBM.js → index-CLk7USHu.js} +1 -1
- package/dist/client/assets/index-Dw2USDt7.js +32 -0
- package/dist/client/assets/{input-KnYDv1A5.js → input-ZwYzWYsd.js} +1 -1
- package/dist/client/assets/json-shDxh9VI.js +1 -0
- package/dist/client/assets/{json-syntax-highlighter-BHL3wK0f.js → json-syntax-highlighter-CBCsDrbN.js} +2 -2
- package/dist/client/assets/{layout-NjL7irXi.js → layout-qWjUAxmx.js} +1 -1
- package/dist/client/assets/{lazy-highlighter-DfXFtweD.js → lazy-highlighter-CeR79qlP.js} +1 -1
- package/dist/client/assets/{localstorage-keys-Bla3L5Kn.js → localstorage-keys-Cc5ak95E.js} +1 -1
- package/dist/client/assets/{login-DWfPFu6G.js → login-Dzk1B1b-.js} +1 -1
- package/dist/client/assets/{mcp-oauth-B3voaRxT.js → mcp-oauth-AZGWVH9g.js} +1 -1
- package/dist/client/assets/{members-zioM9DX4.js → members-CCwAaAHQ.js} +1 -1
- package/dist/client/assets/{monitoring-BWq8obqP.js → monitoring-D3prTzA_.js} +1 -1
- package/dist/client/assets/{oauth-callback-B4ueERM_.js → oauth-callback-C7HHguix.js} +1 -1
- package/dist/client/assets/{page-Clx7_tn2.js → page-R6pHknz0.js} +1 -1
- package/dist/client/assets/{popover-BUiNi8m6.js → popover-C2ZTLfkD.js} +1 -1
- package/dist/client/assets/prism-light-C5gubXs2.js +1 -0
- package/dist/client/assets/{resource-tabs-yB0ODQBX.js → resource-tabs-C4ib9Qer.js} +1 -1
- package/dist/client/assets/{schema-DS_MXXSd.js → schema-DBCaYNfa.js} +1 -1
- package/dist/client/assets/{select-D2oQHnH-.js → select-Drv0jNpx.js} +1 -1
- package/dist/client/assets/{settings-CPxuZwVp.js → settings-48kN1cjt.js} +1 -1
- package/dist/client/assets/{shell-layout-BX0g1F2C.js → shell-layout-Cltos3LX.js} +1 -1
- package/dist/client/assets/{spinner-B-LyDgpm.js → spinner-pWVeZvIu.js} +1 -1
- package/dist/client/assets/{store-DpIupuN4.js → store-CUS-2is6.js} +1 -1
- package/dist/client/assets/{store-app-detail-Dzqp2haZ.js → store-app-detail-BJWFOzEW.js} +1 -1
- package/dist/client/assets/{switch-ZVXF1B-B.js → switch-BhPZG_BR.js} +1 -1
- package/dist/client/assets/{textarea-BYzZCFR4.js → textarea-CBwsqq0a.js} +1 -1
- package/dist/client/assets/{tools-list-DX1uzNKs.js → tools-list-BMljmspA.js} +1 -1
- package/dist/client/assets/{tooltip-C9HJ0ESh.js → tooltip-CTZbNNnK.js} +1 -1
- package/dist/client/assets/{types-BzJYylI4.js → types-B0kyZijl.js} +1 -1
- package/dist/client/assets/{use-binding-zihfVeqz.js → use-binding-DsbURj3b.js} +2 -2
- package/dist/client/assets/{use-connection-PNwxddOO.js → use-connection-BaSQ_kK7.js} +1 -1
- package/dist/client/assets/{use-gateway-v9UrwqWL.js → use-gateway-BFmqlcff.js} +1 -1
- package/dist/client/assets/{use-list-state-lBd2usQq.js → use-list-state-DOX95Ml_.js} +1 -1
- package/dist/client/assets/{use-mcp-DnENzWav.js → use-mcp-BI87vr5V.js} +1 -1
- package/dist/client/assets/{use-members-BZ9F4tXm.js → use-members-D8yePFg4.js} +1 -1
- package/dist/client/assets/{use-mobile-BZVx-pSu.js → use-mobile-BKS-qB3Y.js} +1 -1
- package/dist/client/assets/{use-organization-settings-D8NOmgEj.js → use-organization-settings-CfuafopH.js} +1 -1
- package/dist/client/assets/{use-tool-call-CDsX2AuI.js → use-tool-call-CoSkJnqm.js} +1 -1
- package/dist/client/assets/useQuery-SxQZJ5cp.js +1 -0
- package/dist/client/assets/utils-Dvu_Dkg0.js +1 -0
- package/dist/client/assets/{well-known-mcp-0xOmKc1Z.js → well-known-mcp-D7YKD5ci.js} +1 -1
- package/dist/client/index.html +1 -1
- package/dist/server/cli.js +1 -1
- package/dist/server/migrate.js +1 -1
- package/dist/server/server.js +1 -1
- package/package.json +1 -1
- package/dist/client/assets/connections-ByAWgP1A.js +0 -1
- package/dist/client/assets/index-BwcY8s4g.js +0 -32
- package/dist/client/assets/json-D3Bs6F9t.js +0 -1
- package/dist/client/assets/prism-light-CzedzUri.js +0 -1
- package/dist/client/assets/useQuery-BeDo1OnH.js +0 -1
- package/dist/client/assets/utils-CzqUBWOD.js +0 -1
package/dist/server/server.js
CHANGED
|
@@ -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 CW("write");let G=Q;if(Q|=0,Q<100||Q>999)throw new g60(G);if(typeof J==="string")this.statusMessage=J;else this.statusMessage||=mJ1[Q]||"unknown",X??=J;this.statusCode=Q;let Y;if(this[P8]){let K;if(Array.isArray(X)){if(X.length%2!==0)throw new nK("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[P8]}else Y=X;if(Tj4(this.statusMessage))throw new YF("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 dJ1=s(()=>{n60();Q80();lJ1()});var ZF;var K_=s(()=>{CJ1();dJ1();ZF=class ZF extends h60{constructor(Q){super({...Q,sessionIdGenerator:Q?.sessionIdGenerator})}async handleMessage(Q){let{req:J,res:X}=J80(Q);return super.handleRequest(J,X,await Q.json().catch(()=>null)),X80(X)}}});var DP=(...Q)=>{return function(X,G){let Y=(W)=>{let $=Q[W];if(!$)return G();return $(X,()=>Y(W+1))};return Y(0)}};class pJ1{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?DP(...this.callToolMiddlewares):null,J=()=>{let X=new eH({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:O10.object({}).shape,K=G.outputSchema&&"shape"in G.outputSchema?G.outputSchema.shape:O10.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:_Y(X.inputSchema),outputSchema:X.outputSchema?_Y(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 ZF({enableJsonResponse:X.headers.get("Accept")?.includes("application/json")??!1});return await J().connect(G),await G.handleMessage(X)}}}}function cJ1(Q){return new pJ1(Q)}var nJ1=s(()=>{fk();w4();ZP();K_()});function E1(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:Y80.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:Y80.SpanStatusCode.ERROR,message:W.message}),Y.recordException(W),W}finally{Y.end()}})}}}var Y80;var x4=s(()=>{Y80=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 Aj4(Q){return!!(Q.auth.user||Q.auth.apiKey)}function u1(Q){if(!Aj4(Q))throw Error("Authentication required")}var Z_,iJ1,rJ1,aJ1,oJ1,sJ1,tJ1,eJ1,QX1,JX1;var SU=s(()=>{w4();Z_=L.record(L.array(L.string())),iJ1=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:Z_.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")}),rJ1=L.object({name:L.string().min(1).max(64).describe("Human-readable name for the API key"),permissions:Z_.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")}),aJ1=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:Z_.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")}),oJ1=L.object({}),sJ1=L.object({items:L.array(iJ1).describe("List of API keys (without key values)")}),tJ1=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:Z_.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.")}),eJ1=L.object({item:iJ1.describe("The updated API key (without key value)")}),QX1=L.object({keyId:L.string().describe("ID of the API key to delete")}),JX1=L.object({success:L.boolean().describe("Whether the deletion was successful"),keyId:L.string().describe("ID of the deleted API key")})});var G80;var XX1=s(()=>{x4();SU();G80=E1({name:"API_KEY_CREATE",description:"Create a new API key with specified permissions. The key value is only returned once - store it securely!",inputSchema:rJ1,outputSchema:aJ1,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 W80;var YX1=s(()=>{x4();SU();W80=E1({name:"API_KEY_DELETE",description:"Delete an API key. This instantly revokes the key - it can no longer be used for authentication.",inputSchema:QX1,outputSchema:JX1,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 $80;var GX1=s(()=>{x4();SU();$80=E1({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:oJ1,outputSchema:sJ1,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 K80;var WX1=s(()=>{x4();SU();K80=E1({name:"API_KEY_UPDATE",description:"Update an existing API key's name, permissions, or metadata. Note: Key value cannot be changed or retrieved.",inputSchema:tJ1,outputSchema:eJ1,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 $X1=s(()=>{XX1();YX1();GX1();WX1();SU()});var jj4,Ij4,gX,KX1,ZX1;var vU=s(()=>{w4();jj4=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"])}),Ij4=L.object({name:L.string(),description:L.string().optional(),inputSchema:L.record(L.unknown()),outputSchema:L.record(L.unknown()).optional()}),gX=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:jj4.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(Ij4).nullable().describe("Discovered tools from MCP"),bindings:L.array(L.string()).nullable().describe("Detected bindings"),status:L.enum(["active","inactive","error"]).describe("Current status")}),KX1=gX.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}),ZX1=gX.partial()});var Cj4,Rj4,Z80;var HX1=s(()=>{mH();w4();x4();Ek();vU();Cj4=L.object({data:KX1.describe("Data for the new connection (id is auto-generated if not provided)")}),Rj4=L.object({item:gX.describe("The created connection entity")}),Z80=E1({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",inputSchema:Cj4,outputSchema:Rj4,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 wU({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,tz.SELF(X.id),{type:"connection.created",data:K}),{item:K}}})});function sK(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]=sK(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(sK(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(sK);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,sK(G)),L.object({})),Q);if(Q.oneOf&&Q.oneOf.length>=2){let X=Q.oneOf.map(sK);return J(L.union([X[0],X[1],...X.slice(2)]),Q)}return J(L.any(),Q)}var FX1=s(()=>{w4()});function Sj4(Q){let J=globalThis.DOMException;return typeof J=="function"?new J(Q,"SyntaxError"):SyntaxError(Q)}function F80(Q){return Q instanceof Error?"errors"in Q&&Array.isArray(Q.errors)?Q.errors.map(F80).join(", "):("cause"in Q)&&Q.cause instanceof Error?`${Q}: ${F80(Q.cause)}`:Q.message:`${Q}`}function qX1(Q){return{type:Q.type,message:Q.message,code:Q.code,defaultPrevented:Q.defaultPrevented,cancelable:Q.cancelable,timeStamp:Q.timeStamp}}function vj4(){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 H80,zX1=(Q)=>{throw TypeError(Q)},D80=(Q,J,X)=>J.has(Q)||zX1("Cannot "+X),g4=(Q,J,X)=>(D80(Q,J,"read from private field"),X?X.call(Q):J.get(Q)),j9=(Q,J,X)=>J.has(Q)?zX1("Cannot add the same private member more than once"):J instanceof WeakSet?J.add(Q):J.set(Q,X),f8=(Q,J,X,G)=>(D80(Q,J,"write to private field"),J.set(Q,X),X),RW=(Q,J,X)=>(D80(Q,J,"access private method"),X),JJ,HF,kU,H_,F_,PP,hU,MP,tK,_U,fU,yU,LP,hY,q80,V80,z80,VX1,U80,N80,wP,B80,O80,bU;var UX1=s(()=>{D40();H80=class H80 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(qX1(this),J)}[Symbol.for("Deno.customInspect")](Q,J){return Q(qX1(this),J)}};bU=class bU extends EventTarget{constructor(Q,J){var X,G;super(),j9(this,hY),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,j9(this,JJ),j9(this,HF),j9(this,kU),j9(this,H_),j9(this,F_),j9(this,PP),j9(this,hU),j9(this,MP,null),j9(this,tK),j9(this,_U),j9(this,fU,null),j9(this,yU,null),j9(this,LP,null),j9(this,V80,async(Y)=>{var W;g4(this,_U).reset();let{body:$,redirected:K,status:Z,headers:H}=Y;if(Z===204){RW(this,hY,wP).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(K?f8(this,kU,new URL(Y.url)):f8(this,kU,void 0),Z!==200){RW(this,hY,wP).call(this,`Non-200 status code (${Z})`,Z);return}if(!(H.get("content-type")||"").startsWith("text/event-stream")){RW(this,hY,wP).call(this,'Invalid content type, expected "text/event-stream"',Z);return}if(g4(this,JJ)===this.CLOSED)return;f8(this,JJ,this.OPEN);let F=new Event("open");if((W=g4(this,LP))==null||W.call(this,F),this.dispatchEvent(F),typeof $!="object"||!$||!("getReader"in $)){RW(this,hY,wP).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,_U).feed(q.decode(N,{stream:!U})),U&&(z=!1,g4(this,_U).reset(),RW(this,hY,B80).call(this))}while(z)}),j9(this,z80,(Y)=>{f8(this,tK,void 0),!(Y.name==="AbortError"||Y.type==="aborted")&&RW(this,hY,B80).call(this,F80(Y))}),j9(this,U80,(Y)=>{typeof Y.id=="string"&&f8(this,MP,Y.id);let W=new MessageEvent(Y.event||"message",{data:Y.data,origin:g4(this,kU)?g4(this,kU).origin:g4(this,HF).origin,lastEventId:Y.id||""});g4(this,yU)&&(!Y.event||Y.event==="message")&&g4(this,yU).call(this,W),this.dispatchEvent(W)}),j9(this,N80,(Y)=>{f8(this,PP,Y)}),j9(this,O80,()=>{f8(this,hU,void 0),g4(this,JJ)===this.CONNECTING&&RW(this,hY,q80).call(this)});try{if(Q instanceof URL)f8(this,HF,Q);else if(typeof Q=="string")f8(this,HF,new URL(Q,vj4()));else throw Error("Invalid URL")}catch{throw Sj4("An invalid or illegal string was specified")}f8(this,_U,Ak({onEvent:g4(this,U80),onRetry:g4(this,N80)})),f8(this,JJ,this.CONNECTING),f8(this,PP,3000),f8(this,F_,(X=J==null?void 0:J.fetch)!=null?X:globalThis.fetch),f8(this,H_,(G=J==null?void 0:J.withCredentials)!=null?G:!1),RW(this,hY,q80).call(this)}get readyState(){return g4(this,JJ)}get url(){return g4(this,HF).href}get withCredentials(){return g4(this,H_)}get onerror(){return g4(this,fU)}set onerror(Q){f8(this,fU,Q)}get onmessage(){return g4(this,yU)}set onmessage(Q){f8(this,yU,Q)}get onopen(){return g4(this,LP)}set onopen(Q){f8(this,LP,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,hU)&&clearTimeout(g4(this,hU)),g4(this,JJ)!==this.CLOSED&&(g4(this,tK)&&g4(this,tK).abort(),f8(this,JJ,this.CLOSED),f8(this,tK,void 0))}};JJ=new WeakMap,HF=new WeakMap,kU=new WeakMap,H_=new WeakMap,F_=new WeakMap,PP=new WeakMap,hU=new WeakMap,MP=new WeakMap,tK=new WeakMap,_U=new WeakMap,fU=new WeakMap,yU=new WeakMap,LP=new WeakMap,hY=new WeakSet,q80=function(){f8(this,JJ,this.CONNECTING),f8(this,tK,new AbortController),g4(this,F_)(g4(this,HF),RW(this,hY,VX1).call(this)).then(g4(this,V80)).catch(g4(this,z80))},V80=new WeakMap,z80=new WeakMap,VX1=function(){var Q;let J={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...g4(this,MP)?{"Last-Event-ID":g4(this,MP)}:void 0},cache:"no-store",signal:(Q=g4(this,tK))==null?void 0:Q.signal};return"window"in globalThis&&(J.credentials=this.withCredentials?"include":"same-origin"),J},U80=new WeakMap,N80=new WeakMap,wP=function(Q,J){var X;g4(this,JJ)!==this.CLOSED&&f8(this,JJ,this.CLOSED);let G=new H80("error",{code:J,message:Q});(X=g4(this,fU))==null||X.call(this,G),this.dispatchEvent(G)},B80=function(Q,J){var X;if(g4(this,JJ)===this.CLOSED)return;f8(this,JJ,this.CONNECTING);let G=new H80("error",{code:J,message:Q});(X=g4(this,fU))==null||X.call(this,G),this.dispatchEvent(G),f8(this,hU,setTimeout(g4(this,O80),g4(this,PP)))},O80=new WeakMap,bU.CONNECTING=0,bU.OPEN=1,bU.CLOSED=2});class L80{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 hJ("No auth provider");let J;try{J=await pK(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 hJ;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 bU(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=XP(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 NX1($.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=SY.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 hJ("No auth provider");if(await pK(this._authProvider,{serverUrl:this._url,authorizationCode:Q,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new hJ("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=XP($),await pK(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new hJ;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 NX1;var BX1=s(()=>{UX1();eQ();N40();NX1=class NX1 extends Error{constructor(Q,J,X){super(`SSE error: ${J}`);this.code=Q,this.event=X}}});class w80{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,kj4),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=SY.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 kj4="mcp";var OX1=s(()=>{eQ()});function _j4(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 P80;var DX1=s(()=>{WP();P80=class P80 extends EW{constructor(Q,J){super(Q,J)}send(Q,J){let X=_j4(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 LX1,wX1=async(Q,J,X)=>{let G=yj4(Q.connection,J,X);if(!G)throw Error("Unknown MCP connection type");let Y=new LX1({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})}}},yj4=(Q,J,X)=>{if(Q.type==="Websocket")return new w80(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 L80(new URL(Q.url),W)}return new P80(new URL(Q.url),{requestInit:{headers:Y,signal:J,credentials:"include"}})};var PX1=s(()=>{JP();BX1();OX1();eQ();DX1();LX1=class LX1 extends AW{constructor(Q,J){super(Q,J)}async listTools(Q,J){return await this.request({method:"tools/list",params:Q},sw,J)}}});function TX1(Q){let J=(X)=>{if("connection"in Q)return wX1({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 P=D?.[0]?.text,j=typeof P==="string"?hj4(P):null,M=j?.code&&typeof Q?.getErrorByStatusCode==="function"?Q.getErrorByStatusCode(j.code,j.message,j.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(!q_.has(H))q_.set(H,W());return await q_.get(H)}catch(F){console.error("Failed to list tools",F),q_.delete(H);return}}async function K(){return(await $()??[]).map((H)=>MX1(H,Y))}return Y.asTool=async()=>{let H=(await $()??[]).find((F)=>F.name===G);if(!H)throw Error(`Tool ${G} not found`);return MX1(H,Y)},Y}})}var hj4=(Q)=>{try{return JSON.parse(Q)}catch{return Q}},q_,MX1=(Q,J)=>{return{...Q,id:Q.name,inputSchema:Q.inputSchema?sK(Q.inputSchema):void 0,outputSchema:Q.outputSchema?sK(Q.outputSchema):void 0,execute:(X)=>{return J(X.context,Q.name)}}};var AX1=s(()=>{FX1();PX1();q_=new Map});function V_(Q){return TX1(Q)}var tS6;var EX1=s(()=>{AX1();tS6=new Proxy({},{get(Q,J){if(J==="toJSON")return null;if(J==="forConnection")return(X)=>V_({connection:X});return global[J]}})});function z_(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 xU=(Q)=>{return{...z_(Q),forClient:(J)=>{return V_({client:J,streamable:Q.reduce((X,G)=>{return X[G.name]=G.streamable===!0,X},{})})},forConnection:(J)=>{return V_({connection:J,streamable:Q.reduce((X,G)=>{return X[G.name]=G.streamable===!0,X},{})})}}};var TP=s(()=>{EX1()});function EP(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 T80(Q){return L.object({item:Q.nullable().describe("The retrieved item, or null if not found")})}function xj4(Q){return L.object({data:Q.partial().describe("Data for the new entity (id may be auto-generated)")})}function gj4(Q){return L.object({item:Q.describe("The created entity with generated id")})}function uj4(Q){return L.object({id:L.string().describe("ID of the entity to update"),data:Q.partial().describe("Partial entity data to update")})}function mj4(Q){return L.object({item:Q.describe("The updated entity")})}function E80(Q){return L.object({item:Q.describe("The deleted entity")})}function uU(Q,J,X){let G=Q.toUpperCase(),Y=X?.readOnly??!1,W=[{name:`COLLECTION_${G}_LIST`,inputSchema:AP,outputSchema:EP(J)},{name:`COLLECTION_${G}_GET`,inputSchema:M80,outputSchema:T80(J)}];if(!Y)W.push({name:`COLLECTION_${G}_CREATE`,inputSchema:xj4(J),outputSchema:gj4(J),opt:!0},{name:`COLLECTION_${G}_UPDATE`,inputSchema:uj4(J),outputSchema:mj4(J),opt:!0},{name:`COLLECTION_${G}_DELETE`,inputSchema:A80,outputSchema:E80(J),opt:!0});return W}var gU,fj4,jX1,bj4,AP,M80,A80;var eK=s(()=>{w4();gU=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()}),fj4=L.object({field:L.array(L.string()),operator:L.enum(["eq","gt","gte","lt","lte","in","like","contains"]),value:L.unknown()}),jX1=L.lazy(()=>L.union([fj4,L.object({operator:L.enum(["and","or","not"]),conditions:L.array(jX1)})])),bj4=L.object({field:L.array(L.string()),direction:L.enum(["asc","desc"]),nulls:L.enum(["first","last"]).optional()}),AP=L.object({where:jX1.optional().describe("Filter expression"),orderBy:L.array(bj4).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")});M80=L.object({id:L.string().describe("ID of the entity to retrieve")});A80=L.object({id:L.string().describe("ID of the entity to delete")})});var lj4,IX1,Kv6;var CX1=s(()=>{w4();eK();lj4=L.object({id:L.string(),name:L.string(),description:L.string().optional(),inputSchema:L.record(L.unknown()),outputSchema:L.record(L.unknown()).optional()}),IX1=gU.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(lj4).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()})}),Kv6=uU("registry_app",IX1,{readOnly:!0})});var RX1,SX1,vX1,kX1,_X1,j80;var yX1=s(()=>{w4();TP();RX1=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)")}),SX1=L.object({events:L.array(RX1).min(1).describe("Batch of CloudEvents to process")}),vX1=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")}),kX1=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(),vX1).optional().describe("Per-event results keyed by event ID")}),_X1=[{name:"ON_EVENTS",inputSchema:SX1,outputSchema:kX1}],j80=xU(_X1)});var jP,IP,CP,RP,hX1,fX1,SP,vP,kP,_P,yP,hP,fP,bP,bX1,dj4;var xX1=s(()=>{w4();TP();jP=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.")}),IP=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")}),CP=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")}),RP=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")})}),hX1=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")}),fX1=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")}),SP=L.object({subscriptions:L.array(hX1).describe("Desired subscriptions - system will create/update/delete to match")}),vP=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(fX1).describe("Current subscriptions after sync")}),kP=L.object({subscriptionId:L.string().describe("Subscription ID to remove")}),_P=L.object({success:L.boolean().describe("Whether unsubscribe was successful"),subscriptionId:L.string().describe("Subscription ID that was removed")}),yP=L.object({eventId:L.string().describe("Event ID to cancel")}),hP=L.object({success:L.boolean().describe("Whether cancellation was successful"),eventId:L.string().describe("Event ID that was cancelled")}),fP=L.object({eventId:L.string().describe("Event ID to acknowledge")}),bP=L.object({success:L.boolean().describe("Whether ACK was successful"),eventId:L.string().describe("Event ID that was acknowledged")}),bX1=[{name:"EVENT_PUBLISH",inputSchema:jP,outputSchema:IP},{name:"EVENT_SUBSCRIBE",inputSchema:CP,outputSchema:RP},{name:"EVENT_UNSUBSCRIBE",inputSchema:kP,outputSchema:_P},{name:"EVENT_CANCEL",inputSchema:yP,outputSchema:hP},{name:"EVENT_ACK",inputSchema:fP,outputSchema:bP},{name:"EVENT_SYNC_SUBSCRIPTIONS",inputSchema:SP,outputSchema:vP}],dj4=xU(bX1)});var U_=s(()=>{TP();CX1();yX1();xX1()});var pj4,cj4,gX1;var uX1=s(()=>{w4();eK();pj4=gU.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")}),cj4=uU("assistant",pj4),gX1=[...cj4]});var xP,SW,lX1,nj4,dX1,ij4,rj4,aj4,pX1,oj4,sj4,tj4,ej4,QI4,JI4,XI4,YI4,Iv6,GI4,Cv6,mX1,WI4,$I4,I80,cX1;var C80=s(()=>{w4();TP();eK();xP=L.lazy(()=>L.union([L.null(),L.string(),L.number(),L.boolean(),L.record(L.string(),xP),L.array(xP)])),SW=L.record(L.string(),L.record(L.string(),xP)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),lX1=L.object({type:L.literal("text"),text:L.string().describe("The text content"),providerOptions:SW}),nj4=L.union([L.string(),L.instanceof(Uint8Array)]).describe("File data as base64 encoded string, URL string, or Uint8Array"),dX1=L.object({type:L.literal("file"),filename:L.string().optional().describe("Optional filename of the file"),data:nj4,mediaType:L.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:SW}),ij4=L.object({type:L.literal("reasoning"),text:L.string().describe("The reasoning text"),providerOptions:SW}),rj4=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:SW}),aj4=L.union([L.object({type:L.literal("text"),value:L.string()}),L.object({type:L.literal("json"),value:xP}),L.object({type:L.literal("error-text"),value:L.string()}),L.object({type:L.literal("error-json"),value:xP}),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")})]))})]),pX1=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:aj4.describe("Result of the tool call"),providerOptions:SW}),oj4=L.object({role:L.literal("system"),content:L.string().describe("System message content"),providerOptions:SW}),sj4=L.object({role:L.literal("user"),content:L.array(L.union([lX1,dX1])).describe("User message content parts (text or file)"),providerOptions:SW}),tj4=L.object({role:L.literal("assistant"),content:L.array(L.union([lX1,dX1,ij4,rj4,pX1])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:SW}),ej4=L.object({role:L.literal("tool"),content:L.array(pX1).describe("Tool message content (tool results)"),providerOptions:SW}),QI4=L.union([oj4,sj4,tj4,ej4]),JI4=L.array(QI4).describe("A list of messages forming the prompt"),XI4=L.object({prompt:JI4.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")}),YI4=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")}),Iv6=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")}),GI4=L.object({supportedUrls:L.record(L.string(),L.array(L.string())).describe("Supported URL patterns by media type for the provider")}),Cv6=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()}),mX1=L.object({modelId:L.string().describe("The ID of the model"),callOptions:XI4}),WI4=gU.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()}),$I4=uU("llm",WI4,{readOnly:!0}),I80=[{name:"LLM_METADATA",inputSchema:L.object({modelId:L.string().describe("The ID of the model")}),outputSchema:GI4},{name:"LLM_DO_STREAM",inputSchema:mX1,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:mX1,outputSchema:YI4},...$I4],cX1=xU(I80)});function ZI4(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 QZ(Q){return typeof Q==="string"||typeof Q==="number"}function N_(Q,J){if("conditions"in J){let{operator:K,conditions:Z}=J;switch(K){case"and":return Z.every((H)=>N_(Q,H));case"or":return Z.some((H)=>N_(Q,H));case"not":return!Z.every((H)=>N_(Q,H));default:return!0}}let{field:X,operator:G,value:Y}=J,W=X.join("."),$=R80(Q,W);switch(G){case"eq":return $===Y;case"gt":return QZ($)&&QZ(Y)&&$>Y;case"gte":return QZ($)&&QZ(Y)&&$>=Y;case"lt":return QZ($)&&QZ(Y)&&$<Y;case"lte":return QZ($)&&QZ(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=ZI4(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 R80(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 HI4(Q,J){return[...Q].sort((X,G)=>{for(let Y of J){let W=Y.field.join("."),$=R80(X,W),K=R80(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 KI4,FI4,qI4,S80;var nX1=s(()=>{U_();uX1();eK();C80();w4();x4();vU();KI4={LLM:I80,ASSISTANTS:gX1};FI4=AP.extend({binding:L.union([L.object({}).passthrough(),L.string()]).optional()}),qI4=EP(gX),S80=E1({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",inputSchema:FI4,outputSchema:qI4,handler:async(Q,J)=>{await J.access.check();let X=j4(J),G=Q.binding?typeof Q.binding==="string"?(()=>{let V=KI4[Q.binding.toUpperCase()];if(!V)throw Error(`Unknown binding: ${Q.binding}`);return V})():Q.binding:void 0,Y=G?z_(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)=>N_(V,Q.where));if(Q.orderBy&&Q.orderBy.length>0)$=HI4($,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 VI4,v80;var iX1=s(()=>{eK();x4();vU();VI4=T80(gX),v80=E1({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",inputSchema:M80,outputSchema:VI4,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 B_=(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 rX1(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 zI4(Q){let J=Q.split("::");if(J.length!==2||!J[0]||!J[1])return null;return J}function UI4(Q){if(typeof Q==="object"&&Q!==null&&"value"in Q){let J=Q.value;if(typeof J==="string")return J}return null}function k80(Q,J){let X={};if(!Q||!J)return X;for(let G of J){let Y=zI4(G);if(!Y)continue;let[W,$]=Y,K=B_(W,Q),Z=UI4(K);if(Z){if(!X[Z])X[Z]=[];X[Z].push($)}}return X}function aX1(Q,J){let X=k80(Q,J);return new Set(Object.keys(X))}var _80=()=>{};async function OI4(Q,J,X,G){for(let W of J){let[$]=rX1(W),K=B_($,Q);if(K===void 0||K===null)throw Error(`Scope references key "${$}" but it's not present in state`)}let Y=aX1(Q,J);for(let W of Y){if(W===AY.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 NI4,BI4,y80;var oX1=s(()=>{_80();mH();w4();x4();Ek();vU();NI4=L.object({id:L.string().describe("ID of the connection to update"),data:ZX1.describe("Partial connection data to update")}),BI4=L.object({item:gX.describe("The updated connection entity")});y80=E1({name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update an existing MCP connection in the organization",inputSchema:NI4,outputSchema:BI4,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 OI4($,K,X.id,J)}let Z=await wU({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 h80;var sX1=s(()=>{eK();x4();vU();h80=E1({name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete a connection",inputSchema:A80,outputSchema:E80(gX),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 f80;var tX1=s(()=>{w4();x4();f80=E1({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 eX1=s(()=>{HX1();nX1();iX1();oX1();sX1();tX1()});import{sql as D6}from"kysely";function QY1(Q){return Q.replace(/-/g,"_")}function PI4(Q){return`app_${QY1(Q)}`}function MI4(Q){return`app_role_${QY1(Q)}`}function TI4(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 AI4(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 dJ1=s(()=>{n60();Q80();lJ1()});var ZF;var K_=s(()=>{CJ1();dJ1();ZF=class ZF extends h60{constructor(Q){super({...Q,sessionIdGenerator:Q?.sessionIdGenerator})}async handleMessage(Q){let{req:J,res:X}=J80(Q);return super.handleRequest(J,X,await Q.json().catch(()=>null)),X80(X)}}});var DP=(...Q)=>{return function(X,G){let Y=(W)=>{let $=Q[W];if(!$)return G();return $(X,()=>Y(W+1))};return Y(0)}};class pJ1{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?DP(...this.callToolMiddlewares):null,J=()=>{let X=new eH({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:O10.object({}).shape,K=G.outputSchema&&"shape"in G.outputSchema?G.outputSchema.shape:O10.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:_Y(X.inputSchema),outputSchema:X.outputSchema?_Y(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 ZF({enableJsonResponse:X.headers.get("Accept")?.includes("application/json")??!1});return await J().connect(G),await G.handleMessage(X)}}}}function cJ1(Q){return new pJ1(Q)}var nJ1=s(()=>{fk();w4();ZP();K_()});function E1(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:Y80.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:Y80.SpanStatusCode.ERROR,message:W.message}),Y.recordException(W),W}finally{Y.end()}})}}}var Y80;var x4=s(()=>{Y80=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 Aj4(Q){return!!(Q.auth.user||Q.auth.apiKey)}function u1(Q){if(!Aj4(Q))throw Error("Authentication required")}var Z_,iJ1,rJ1,aJ1,oJ1,sJ1,tJ1,eJ1,QX1,JX1;var SU=s(()=>{w4();Z_=L.record(L.array(L.string())),iJ1=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:Z_.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")}),rJ1=L.object({name:L.string().min(1).max(64).describe("Human-readable name for the API key"),permissions:Z_.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")}),aJ1=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:Z_.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")}),oJ1=L.object({}),sJ1=L.object({items:L.array(iJ1).describe("List of API keys (without key values)")}),tJ1=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:Z_.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.")}),eJ1=L.object({item:iJ1.describe("The updated API key (without key value)")}),QX1=L.object({keyId:L.string().describe("ID of the API key to delete")}),JX1=L.object({success:L.boolean().describe("Whether the deletion was successful"),keyId:L.string().describe("ID of the deleted API key")})});var G80;var XX1=s(()=>{x4();SU();G80=E1({name:"API_KEY_CREATE",description:"Create a new API key with specified permissions. The key value is only returned once - store it securely!",inputSchema:rJ1,outputSchema:aJ1,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 W80;var YX1=s(()=>{x4();SU();W80=E1({name:"API_KEY_DELETE",description:"Delete an API key. This instantly revokes the key - it can no longer be used for authentication.",inputSchema:QX1,outputSchema:JX1,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 $80;var GX1=s(()=>{x4();SU();$80=E1({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:oJ1,outputSchema:sJ1,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 K80;var WX1=s(()=>{x4();SU();K80=E1({name:"API_KEY_UPDATE",description:"Update an existing API key's name, permissions, or metadata. Note: Key value cannot be changed or retrieved.",inputSchema:tJ1,outputSchema:eJ1,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 $X1=s(()=>{XX1();YX1();GX1();WX1();SU()});var jj4,Ij4,gX,KX1,ZX1;var vU=s(()=>{w4();jj4=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"])}),Ij4=L.object({name:L.string(),description:L.string().optional(),inputSchema:L.record(L.unknown()),outputSchema:L.record(L.unknown()).optional()}),gX=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:jj4.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(Ij4).nullable().describe("Discovered tools from MCP"),bindings:L.array(L.string()).nullable().describe("Detected bindings"),status:L.enum(["active","inactive","error"]).describe("Current status")}),KX1=gX.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}),ZX1=gX.partial()});var Cj4,Rj4,Z80;var HX1=s(()=>{mH();w4();x4();Ek();vU();Cj4=L.object({data:KX1.describe("Data for the new connection (id is auto-generated if not provided)")}),Rj4=L.object({item:gX.describe("The created connection entity")}),Z80=E1({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",inputSchema:Cj4,outputSchema:Rj4,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 wU({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,tz.SELF(X.id),{type:"connection.created",data:K}),{item:K}}})});function sK(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]=sK(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(sK(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(sK);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,sK(G)),L.object({})),Q);if(Q.oneOf&&Q.oneOf.length>=2){let X=Q.oneOf.map(sK);return J(L.union([X[0],X[1],...X.slice(2)]),Q)}return J(L.any(),Q)}var FX1=s(()=>{w4()});function Sj4(Q){let J=globalThis.DOMException;return typeof J=="function"?new J(Q,"SyntaxError"):SyntaxError(Q)}function F80(Q){return Q instanceof Error?"errors"in Q&&Array.isArray(Q.errors)?Q.errors.map(F80).join(", "):("cause"in Q)&&Q.cause instanceof Error?`${Q}: ${F80(Q.cause)}`:Q.message:`${Q}`}function qX1(Q){return{type:Q.type,message:Q.message,code:Q.code,defaultPrevented:Q.defaultPrevented,cancelable:Q.cancelable,timeStamp:Q.timeStamp}}function vj4(){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 H80,zX1=(Q)=>{throw TypeError(Q)},D80=(Q,J,X)=>J.has(Q)||zX1("Cannot "+X),g4=(Q,J,X)=>(D80(Q,J,"read from private field"),X?X.call(Q):J.get(Q)),j9=(Q,J,X)=>J.has(Q)?zX1("Cannot add the same private member more than once"):J instanceof WeakSet?J.add(Q):J.set(Q,X),f8=(Q,J,X,G)=>(D80(Q,J,"write to private field"),J.set(Q,X),X),RW=(Q,J,X)=>(D80(Q,J,"access private method"),X),JJ,HF,kU,H_,F_,PP,hU,MP,tK,_U,fU,yU,LP,hY,q80,V80,z80,VX1,U80,N80,wP,B80,O80,bU;var UX1=s(()=>{D40();H80=class H80 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(qX1(this),J)}[Symbol.for("Deno.customInspect")](Q,J){return Q(qX1(this),J)}};bU=class bU extends EventTarget{constructor(Q,J){var X,G;super(),j9(this,hY),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,j9(this,JJ),j9(this,HF),j9(this,kU),j9(this,H_),j9(this,F_),j9(this,PP),j9(this,hU),j9(this,MP,null),j9(this,tK),j9(this,_U),j9(this,fU,null),j9(this,yU,null),j9(this,LP,null),j9(this,V80,async(Y)=>{var W;g4(this,_U).reset();let{body:$,redirected:K,status:Z,headers:H}=Y;if(Z===204){RW(this,hY,wP).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(K?f8(this,kU,new URL(Y.url)):f8(this,kU,void 0),Z!==200){RW(this,hY,wP).call(this,`Non-200 status code (${Z})`,Z);return}if(!(H.get("content-type")||"").startsWith("text/event-stream")){RW(this,hY,wP).call(this,'Invalid content type, expected "text/event-stream"',Z);return}if(g4(this,JJ)===this.CLOSED)return;f8(this,JJ,this.OPEN);let F=new Event("open");if((W=g4(this,LP))==null||W.call(this,F),this.dispatchEvent(F),typeof $!="object"||!$||!("getReader"in $)){RW(this,hY,wP).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,_U).feed(q.decode(N,{stream:!U})),U&&(z=!1,g4(this,_U).reset(),RW(this,hY,B80).call(this))}while(z)}),j9(this,z80,(Y)=>{f8(this,tK,void 0),!(Y.name==="AbortError"||Y.type==="aborted")&&RW(this,hY,B80).call(this,F80(Y))}),j9(this,U80,(Y)=>{typeof Y.id=="string"&&f8(this,MP,Y.id);let W=new MessageEvent(Y.event||"message",{data:Y.data,origin:g4(this,kU)?g4(this,kU).origin:g4(this,HF).origin,lastEventId:Y.id||""});g4(this,yU)&&(!Y.event||Y.event==="message")&&g4(this,yU).call(this,W),this.dispatchEvent(W)}),j9(this,N80,(Y)=>{f8(this,PP,Y)}),j9(this,O80,()=>{f8(this,hU,void 0),g4(this,JJ)===this.CONNECTING&&RW(this,hY,q80).call(this)});try{if(Q instanceof URL)f8(this,HF,Q);else if(typeof Q=="string")f8(this,HF,new URL(Q,vj4()));else throw Error("Invalid URL")}catch{throw Sj4("An invalid or illegal string was specified")}f8(this,_U,Ak({onEvent:g4(this,U80),onRetry:g4(this,N80)})),f8(this,JJ,this.CONNECTING),f8(this,PP,3000),f8(this,F_,(X=J==null?void 0:J.fetch)!=null?X:globalThis.fetch),f8(this,H_,(G=J==null?void 0:J.withCredentials)!=null?G:!1),RW(this,hY,q80).call(this)}get readyState(){return g4(this,JJ)}get url(){return g4(this,HF).href}get withCredentials(){return g4(this,H_)}get onerror(){return g4(this,fU)}set onerror(Q){f8(this,fU,Q)}get onmessage(){return g4(this,yU)}set onmessage(Q){f8(this,yU,Q)}get onopen(){return g4(this,LP)}set onopen(Q){f8(this,LP,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,hU)&&clearTimeout(g4(this,hU)),g4(this,JJ)!==this.CLOSED&&(g4(this,tK)&&g4(this,tK).abort(),f8(this,JJ,this.CLOSED),f8(this,tK,void 0))}};JJ=new WeakMap,HF=new WeakMap,kU=new WeakMap,H_=new WeakMap,F_=new WeakMap,PP=new WeakMap,hU=new WeakMap,MP=new WeakMap,tK=new WeakMap,_U=new WeakMap,fU=new WeakMap,yU=new WeakMap,LP=new WeakMap,hY=new WeakSet,q80=function(){f8(this,JJ,this.CONNECTING),f8(this,tK,new AbortController),g4(this,F_)(g4(this,HF),RW(this,hY,VX1).call(this)).then(g4(this,V80)).catch(g4(this,z80))},V80=new WeakMap,z80=new WeakMap,VX1=function(){var Q;let J={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...g4(this,MP)?{"Last-Event-ID":g4(this,MP)}:void 0},cache:"no-store",signal:(Q=g4(this,tK))==null?void 0:Q.signal};return"window"in globalThis&&(J.credentials=this.withCredentials?"include":"same-origin"),J},U80=new WeakMap,N80=new WeakMap,wP=function(Q,J){var X;g4(this,JJ)!==this.CLOSED&&f8(this,JJ,this.CLOSED);let G=new H80("error",{code:J,message:Q});(X=g4(this,fU))==null||X.call(this,G),this.dispatchEvent(G)},B80=function(Q,J){var X;if(g4(this,JJ)===this.CLOSED)return;f8(this,JJ,this.CONNECTING);let G=new H80("error",{code:J,message:Q});(X=g4(this,fU))==null||X.call(this,G),this.dispatchEvent(G),f8(this,hU,setTimeout(g4(this,O80),g4(this,PP)))},O80=new WeakMap,bU.CONNECTING=0,bU.OPEN=1,bU.CLOSED=2});class L80{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 hJ("No auth provider");let J;try{J=await pK(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 hJ;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 bU(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=XP(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 NX1($.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=SY.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 hJ("No auth provider");if(await pK(this._authProvider,{serverUrl:this._url,authorizationCode:Q,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new hJ("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=XP($),await pK(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new hJ;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 NX1;var BX1=s(()=>{UX1();eQ();N40();NX1=class NX1 extends Error{constructor(Q,J,X){super(`SSE error: ${J}`);this.code=Q,this.event=X}}});class w80{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,kj4),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=SY.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 kj4="mcp";var OX1=s(()=>{eQ()});function _j4(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 P80;var DX1=s(()=>{WP();P80=class P80 extends EW{constructor(Q,J){super(Q,J)}send(Q,J){let X=_j4(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 LX1,wX1=async(Q,J,X)=>{let G=yj4(Q.connection,J,X);if(!G)throw Error("Unknown MCP connection type");let Y=new LX1({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})}}},yj4=(Q,J,X)=>{if(Q.type==="Websocket")return new w80(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 L80(new URL(Q.url),W)}return new P80(new URL(Q.url),{requestInit:{headers:Y,signal:J,credentials:"include"}})};var PX1=s(()=>{JP();BX1();OX1();eQ();DX1();LX1=class LX1 extends AW{constructor(Q,J){super(Q,J)}async listTools(Q,J){return await this.request({method:"tools/list",params:Q},sw,J)}}});function TX1(Q){let J=(X)=>{if("connection"in Q)return wX1({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 P=D?.[0]?.text,j=typeof P==="string"?hj4(P):null,M=j?.code&&typeof Q?.getErrorByStatusCode==="function"?Q.getErrorByStatusCode(j.code,j.message,j.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(!q_.has(H))q_.set(H,W());return await q_.get(H)}catch(F){console.error("Failed to list tools",F),q_.delete(H);return}}async function K(){return(await $()??[]).map((H)=>MX1(H,Y))}return Y.asTool=async()=>{let H=(await $()??[]).find((F)=>F.name===G);if(!H)throw Error(`Tool ${G} not found`);return MX1(H,Y)},Y}})}var hj4=(Q)=>{try{return JSON.parse(Q)}catch{return Q}},q_,MX1=(Q,J)=>{return{...Q,id:Q.name,inputSchema:Q.inputSchema?sK(Q.inputSchema):void 0,outputSchema:Q.outputSchema?sK(Q.outputSchema):void 0,execute:(X)=>{return J(X.context,Q.name)}}};var AX1=s(()=>{FX1();PX1();q_=new Map});function V_(Q){return TX1(Q)}var tS6;var EX1=s(()=>{AX1();tS6=new Proxy({},{get(Q,J){if(J==="toJSON")return null;if(J==="forConnection")return(X)=>V_({connection:X});return global[J]}})});function z_(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 xU=(Q)=>{return{...z_(Q),forClient:(J)=>{return V_({client:J,streamable:Q.reduce((X,G)=>{return X[G.name]=G.streamable===!0,X},{})})},forConnection:(J)=>{return V_({connection:J,streamable:Q.reduce((X,G)=>{return X[G.name]=G.streamable===!0,X},{})})}}};var TP=s(()=>{EX1()});function EP(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 T80(Q){return L.object({item:Q.nullable().describe("The retrieved item, or null if not found")})}function xj4(Q){return L.object({data:Q.partial().describe("Data for the new entity (id may be auto-generated)")})}function gj4(Q){return L.object({item:Q.describe("The created entity with generated id")})}function uj4(Q){return L.object({id:L.string().describe("ID of the entity to update"),data:Q.partial().describe("Partial entity data to update")})}function mj4(Q){return L.object({item:Q.describe("The updated entity")})}function E80(Q){return L.object({item:Q.describe("The deleted entity")})}function uU(Q,J,X){let G=Q.toUpperCase(),Y=X?.readOnly??!1,W=[{name:`COLLECTION_${G}_LIST`,inputSchema:AP,outputSchema:EP(J)},{name:`COLLECTION_${G}_GET`,inputSchema:M80,outputSchema:T80(J)}];if(!Y)W.push({name:`COLLECTION_${G}_CREATE`,inputSchema:xj4(J),outputSchema:gj4(J),opt:!0},{name:`COLLECTION_${G}_UPDATE`,inputSchema:uj4(J),outputSchema:mj4(J),opt:!0},{name:`COLLECTION_${G}_DELETE`,inputSchema:A80,outputSchema:E80(J),opt:!0});return W}var gU,fj4,jX1,bj4,AP,M80,A80;var eK=s(()=>{w4();gU=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()}),fj4=L.object({field:L.array(L.string()),operator:L.enum(["eq","gt","gte","lt","lte","in","like","contains"]),value:L.unknown()}),jX1=L.lazy(()=>L.union([fj4,L.object({operator:L.enum(["and","or","not"]),conditions:L.array(jX1)})])),bj4=L.object({field:L.array(L.string()),direction:L.enum(["asc","desc"]),nulls:L.enum(["first","last"]).optional()}),AP=L.object({where:jX1.optional().describe("Filter expression"),orderBy:L.array(bj4).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")});M80=L.object({id:L.string().describe("ID of the entity to retrieve")});A80=L.object({id:L.string().describe("ID of the entity to delete")})});var lj4,IX1,Kv6;var CX1=s(()=>{w4();eK();lj4=L.object({id:L.string(),name:L.string(),description:L.string().optional(),inputSchema:L.record(L.unknown()),outputSchema:L.record(L.unknown()).optional()}),IX1=gU.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(lj4).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()})}),Kv6=uU("registry_app",IX1,{readOnly:!0})});var RX1,SX1,vX1,kX1,_X1,j80;var yX1=s(()=>{w4();TP();RX1=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)")}),SX1=L.object({events:L.array(RX1).min(1).describe("Batch of CloudEvents to process")}),vX1=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")}),kX1=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(),vX1).optional().describe("Per-event results keyed by event ID")}),_X1=[{name:"ON_EVENTS",inputSchema:SX1,outputSchema:kX1}],j80=xU(_X1)});var jP,IP,CP,RP,hX1,fX1,SP,vP,kP,_P,yP,hP,fP,bP,bX1,dj4;var xX1=s(()=>{w4();TP();jP=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.")}),IP=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")}),CP=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")}),RP=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")})}),hX1=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")}),fX1=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")}),SP=L.object({subscriptions:L.array(hX1).describe("Desired subscriptions - system will create/update/delete to match")}),vP=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(fX1).describe("Current subscriptions after sync")}),kP=L.object({subscriptionId:L.string().describe("Subscription ID to remove")}),_P=L.object({success:L.boolean().describe("Whether unsubscribe was successful"),subscriptionId:L.string().describe("Subscription ID that was removed")}),yP=L.object({eventId:L.string().describe("Event ID to cancel")}),hP=L.object({success:L.boolean().describe("Whether cancellation was successful"),eventId:L.string().describe("Event ID that was cancelled")}),fP=L.object({eventId:L.string().describe("Event ID to acknowledge")}),bP=L.object({success:L.boolean().describe("Whether ACK was successful"),eventId:L.string().describe("Event ID that was acknowledged")}),bX1=[{name:"EVENT_PUBLISH",inputSchema:jP,outputSchema:IP},{name:"EVENT_SUBSCRIBE",inputSchema:CP,outputSchema:RP},{name:"EVENT_UNSUBSCRIBE",inputSchema:kP,outputSchema:_P},{name:"EVENT_CANCEL",inputSchema:yP,outputSchema:hP},{name:"EVENT_ACK",inputSchema:fP,outputSchema:bP},{name:"EVENT_SYNC_SUBSCRIPTIONS",inputSchema:SP,outputSchema:vP}],dj4=xU(bX1)});var U_=s(()=>{TP();CX1();yX1();xX1()});var pj4,cj4,gX1;var uX1=s(()=>{w4();eK();pj4=gU.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")}),cj4=uU("assistant",pj4),gX1=[...cj4]});var xP,SW,lX1,nj4,dX1,ij4,rj4,aj4,pX1,oj4,sj4,tj4,ej4,QI4,JI4,XI4,YI4,Iv6,GI4,Cv6,mX1,WI4,$I4,I80,cX1;var C80=s(()=>{w4();TP();eK();xP=L.lazy(()=>L.union([L.null(),L.string(),L.number(),L.boolean(),L.record(L.string(),xP),L.array(xP)])),SW=L.record(L.string(),L.record(L.string(),xP)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),lX1=L.object({type:L.literal("text"),text:L.string().describe("The text content"),providerOptions:SW}),nj4=L.union([L.string(),L.instanceof(Uint8Array)]).describe("File data as base64 encoded string, URL string, or Uint8Array"),dX1=L.object({type:L.literal("file"),filename:L.string().optional().describe("Optional filename of the file"),data:nj4,mediaType:L.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:SW}),ij4=L.object({type:L.literal("reasoning"),text:L.string().describe("The reasoning text"),providerOptions:SW}),rj4=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:SW}),aj4=L.union([L.object({type:L.literal("text"),value:L.string()}),L.object({type:L.literal("json"),value:xP}),L.object({type:L.literal("error-text"),value:L.string()}),L.object({type:L.literal("error-json"),value:xP}),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")})]))})]),pX1=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:aj4.describe("Result of the tool call"),providerOptions:SW}),oj4=L.object({role:L.literal("system"),content:L.string().describe("System message content"),providerOptions:SW}),sj4=L.object({role:L.literal("user"),content:L.array(L.union([lX1,dX1])).describe("User message content parts (text or file)"),providerOptions:SW}),tj4=L.object({role:L.literal("assistant"),content:L.array(L.union([lX1,dX1,ij4,rj4,pX1])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:SW}),ej4=L.object({role:L.literal("tool"),content:L.array(pX1).describe("Tool message content (tool results)"),providerOptions:SW}),QI4=L.union([oj4,sj4,tj4,ej4]),JI4=L.array(QI4).describe("A list of messages forming the prompt"),XI4=L.object({prompt:JI4.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")}),YI4=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")}),Iv6=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")}),GI4=L.object({supportedUrls:L.record(L.string(),L.array(L.string())).describe("Supported URL patterns by media type for the provider")}),Cv6=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()}),mX1=L.object({modelId:L.string().describe("The ID of the model"),callOptions:XI4}),WI4=gU.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()}),$I4=uU("llm",WI4,{readOnly:!0}),I80=[{name:"LLM_METADATA",inputSchema:L.object({modelId:L.string().describe("The ID of the model")}),outputSchema:GI4},{name:"LLM_DO_STREAM",inputSchema:mX1,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:mX1,outputSchema:YI4},...$I4],cX1=xU(I80)});function ZI4(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 QZ(Q){return typeof Q==="string"||typeof Q==="number"}function N_(Q,J){if("conditions"in J){let{operator:K,conditions:Z}=J;switch(K){case"and":return Z.every((H)=>N_(Q,H));case"or":return Z.some((H)=>N_(Q,H));case"not":return!Z.every((H)=>N_(Q,H));default:return!0}}let{field:X,operator:G,value:Y}=J,W=X.join("."),$=R80(Q,W);switch(G){case"eq":return $===Y;case"gt":return QZ($)&&QZ(Y)&&$>Y;case"gte":return QZ($)&&QZ(Y)&&$>=Y;case"lt":return QZ($)&&QZ(Y)&&$<Y;case"lte":return QZ($)&&QZ(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=ZI4(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 R80(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 HI4(Q,J){return[...Q].sort((X,G)=>{for(let Y of J){let W=Y.field.join("."),$=R80(X,W),K=R80(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 KI4,FI4,qI4,S80;var nX1=s(()=>{U_();uX1();eK();C80();w4();x4();vU();KI4={LLM:I80,ASSISTANTS:gX1};FI4=AP.extend({binding:L.union([L.object({}).passthrough(),L.string()]).optional()}),qI4=EP(gX),S80=E1({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",inputSchema:FI4,outputSchema:qI4,handler:async(Q,J)=>{await J.access.check();let X=j4(J),G=Q.binding?typeof Q.binding==="string"?(()=>{let V=KI4[Q.binding.toUpperCase()];if(!V)throw Error(`Unknown binding: ${Q.binding}`);return V})():Q.binding:void 0,Y=G?z_(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)=>N_(V,Q.where));if(Q.orderBy&&Q.orderBy.length>0)$=HI4($,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 VI4,v80;var iX1=s(()=>{eK();x4();vU();VI4=T80(gX),v80=E1({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",inputSchema:M80,outputSchema:VI4,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 B_=(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 rX1(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 zI4(Q){let J=Q.split("::");if(J.length!==2||!J[0]||!J[1])return null;return J}function UI4(Q){if(typeof Q==="object"&&Q!==null&&"value"in Q){let J=Q.value;if(typeof J==="string")return J}return null}function k80(Q,J){let X={};if(!Q||!J)return X;for(let G of J){let Y=zI4(G);if(!Y)continue;let[W,$]=Y,K=B_(W,Q),Z=UI4(K);if(Z){if(!X[Z])X[Z]=[];X[Z].push($)}}return X}function aX1(Q,J){let X=k80(Q,J);return new Set(Object.keys(X).filter((G)=>G!=="*"))}var _80=()=>{};async function OI4(Q,J,X,G){for(let W of J){let[$]=rX1(W),K=B_($,Q);if(K===void 0||K===null)throw Error(`Scope references key "${$}" but it's not present in state`)}let Y=aX1(Q,J);for(let W of Y){if(W===AY.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 NI4,BI4,y80;var oX1=s(()=>{_80();mH();w4();x4();Ek();vU();NI4=L.object({id:L.string().describe("ID of the connection to update"),data:ZX1.describe("Partial connection data to update")}),BI4=L.object({item:gX.describe("The updated connection entity")});y80=E1({name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update an existing MCP connection in the organization",inputSchema:NI4,outputSchema:BI4,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 OI4($,K,X.id,J)}let Z=await wU({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 h80;var sX1=s(()=>{eK();x4();vU();h80=E1({name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete a connection",inputSchema:A80,outputSchema:E80(gX),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 f80;var tX1=s(()=>{w4();x4();f80=E1({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 eX1=s(()=>{HX1();nX1();iX1();oX1();sX1();tX1()});import{sql as D6}from"kysely";function QY1(Q){return Q.replace(/-/g,"_")}function PI4(Q){return`app_${QY1(Q)}`}function MI4(Q){return`app_role_${QY1(Q)}`}function TI4(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 AI4(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 EI4(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(TI4(Y))return await AI4(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 LI4,wI4,JY1;var XY1=s(()=>{w4();x4();LI4=L.object({results:L.array(L.unknown()).optional(),success:L.boolean().optional()}),wI4=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()});JY1=E1({name:"DATABASES_RUN_SQL",description:"Run a SQL query against the database",inputSchema:wI4,outputSchema:L.lazy(()=>L.object({result:L.array(LI4)})),handler:async(Q,J)=>{if(u1(J),await J.access.check(),!J.connectionId)throw Error("Connection context required for database access");let X=PI4(J.connectionId),G=MI4(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 EI4(J.db,X,G,Y)).rows,success:!0}]}}})});var YY1,II4,GY1;var vW=s(()=>{w4();U_();YY1=L.object({connectionId:L.string().optional().describe("Filter subscriptions by connection ID (optional)")}),II4=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")}),GY1=L.object({subscriptions:L.array(II4).describe("List of subscriptions")})});var b80;var WY1=s(()=>{x4();vW();b80=E1({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:jP,outputSchema:IP,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 x80;var $Y1=s(()=>{x4();vW();x80=E1({name:"EVENT_SUBSCRIBE",description:"Subscribe to events of a specific type. The subscriber is automatically set to the caller's connection.",inputSchema:CP,outputSchema:RP,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 g80;var KY1=s(()=>{x4();vW();g80=E1({name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events by removing a subscription.",inputSchema:kP,outputSchema:_P,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 u80;var ZY1=s(()=>{x4();vW();u80=E1({name:"EVENT_CANCEL",description:"Cancel a recurring event to stop future deliveries. Only the publisher can cancel their own events.",inputSchema:yP,outputSchema:hP,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 m80;var HY1=s(()=>{x4();vW();m80=E1({name:"EVENT_ACK",description:"Acknowledge delivery of an event. Call after successfully processing an event received via ON_EVENTS with retryAfter.",inputSchema:fP,outputSchema:bP,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 l80;var FY1=s(()=>{x4();vW();l80=E1({name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions, optionally filtered by connection ID.",inputSchema:YY1,outputSchema:GY1,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 d80;var qY1=s(()=>{mH();x4();vW();d80=E1({name:"EVENT_SYNC_SUBSCRIPTIONS",description:"Sync subscriptions to desired state. Creates new, deletes removed, updates changed filters. Subscriptions are identified by (eventType, publisher).",inputSchema:SP,outputSchema:vP,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===tz.SELF(X.id));return await Promise.all(W.map(async($)=>{let K=$.eventType.split("/")[1];K&&await J.eventBus.publish(X.id,tz.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 VY1=s(()=>{WY1();$Y1();KY1();ZY1();HY1();FY1();qY1();vW()});var p80,c80,RI4,JG,zY1,UY1;var mU=s(()=>{w4();p80=L.enum(["inclusion","exclusion"]).describe("Tool selection mode: 'inclusion' = include selected (default), 'exclusion' = exclude selected"),c80=L.enum(["passthrough","smart_tool_selection","code_execution"]).describe("Gateway tool selection strategy: 'passthrough' (default), 'smart_tool_selection', or 'code_execution'"),RI4=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"),selected_resources:L.array(L.string()).nullable().describe("Selected resource URIs or patterns. Supports * and ** wildcards for pattern matching. With 'inclusion' mode: null = all resources included."),selected_prompts:L.array(L.string()).nullable().describe("Selected prompt names. With 'inclusion' mode: null = all prompts included. With 'exclusion' mode: null = entire connection excluded.")}),JG=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:c80.describe("Gateway behavior strategy (metadata for now): 'passthrough', 'smart_tool_selection', or 'code_execution'"),tool_selection_mode:p80.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(RI4).describe("Connections with their selected tools (behavior depends on tool_selection_mode)")}),zY1=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:c80.optional().default("passthrough").describe("Gateway behavior strategy (defaults to 'passthrough')"),tool_selection_mode:p80.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)"),selected_resources:L.array(L.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources)"),selected_prompts:L.array(L.string()).nullable().optional().describe("Selected prompt names (null/undefined = all prompts or full exclusion)")})).describe("Connections to include/exclude (can be empty for exclusion mode)")}),UY1=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:c80.optional().describe("New gateway behavior strategy"),tool_selection_mode:p80.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)"),selected_resources:L.array(L.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources)"),selected_prompts:L.array(L.string()).nullable().optional().describe("Selected prompt names (null/undefined = all prompts or full exclusion)")})).optional().describe("New connections (replaces existing)")})});var SI4,vI4,n80;var NY1=s(()=>{w4();x4();mU();SI4=L.object({data:zY1.describe("Data for the new gateway")}),vI4=L.object({item:JG.describe("The created gateway entity")}),n80=E1({name:"COLLECTION_GATEWAY_CREATE",description:"Create a new MCP gateway in the organization",inputSchema:SI4,outputSchema:vI4,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,selectedResources:$.selected_resources??null,selectedPrompts:$.selected_prompts??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,selected_resources:$.selectedResources,selected_prompts:$.selectedPrompts})),created_at:W.createdAt,updated_at:W.updatedAt,created_by:W.createdBy,updated_by:W.updatedBy??void 0}}}})});function kI4(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 JZ(Q){return typeof Q==="string"||typeof Q==="number"}function i80(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 _I4(Q,J){return Q.connections.some((X)=>X.connection_id===J)}function O_(Q,J){if("conditions"in J){let{operator:K,conditions:Z}=J;switch(K){case"and":return Z.every((H)=>O_(Q,H));case"or":return Z.some((H)=>O_(Q,H));case"not":return!Z.every((H)=>O_(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 _I4(Q,Y)}let $=i80(Q,W);switch(G){case"eq":return $===Y;case"gt":return JZ($)&&JZ(Y)&&$>Y;case"gte":return JZ($)&&JZ(Y)&&$>=Y;case"lt":return JZ($)&&JZ(Y)&&$<Y;case"lte":return JZ($)&&JZ(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=kI4(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 yI4(Q,J){return[...Q].sort((X,G)=>{for(let Y of J){let W=Y.field.join("."),$=i80(X,W),K=i80(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 hI4,fI4,r80;var BY1=s(()=>{eK();x4();mU();hI4=AP,fI4=EP(JG),r80=E1({name:"COLLECTION_GATEWAY_LIST",description:"List all MCP gateways in the organization",inputSchema:hI4,outputSchema:fI4,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,selected_resources:V.selectedResources,selected_prompts:V.selectedPrompts})),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)=>O_(q,Q.where));if(Q.orderBy&&Q.orderBy.length>0)W=yI4(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 bI4,xI4,a80;var OY1=s(()=>{w4();x4();mU();bI4=L.object({id:L.string().describe("ID of the gateway to retrieve")}),xI4=L.object({item:JG.nullable().describe("The retrieved gateway, or null if not found")}),a80=E1({name:"COLLECTION_GATEWAY_GET",description:"Get an MCP gateway by ID",inputSchema:bI4,outputSchema:xI4,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,selected_resources:Y.selectedResources,selected_prompts:Y.selectedPrompts})),created_at:G.createdAt,updated_at:G.updatedAt,created_by:G.createdBy,updated_by:G.updatedBy??void 0}}}})});var gI4,uI4,o80;var DY1=s(()=>{w4();x4();mU();gI4=L.object({id:L.string().describe("ID of the gateway to update"),data:UY1.describe("Partial gateway data to update")}),uI4=L.object({item:JG.describe("The updated gateway entity")}),o80=E1({name:"COLLECTION_GATEWAY_UPDATE",description:"Update an MCP gateway",inputSchema:gI4,outputSchema:uI4,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,selectedResources:K.selected_resources??null,selectedPrompts:K.selected_prompts??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,selected_resources:K.selectedResources,selected_prompts:K.selectedPrompts})),created_at:$.createdAt,updated_at:$.updatedAt,created_by:$.createdBy,updated_by:$.updatedBy??void 0}}}})});var mI4,lI4,s80;var LY1=s(()=>{w4();x4();mU();mI4=L.object({id:L.string().describe("ID of the gateway to delete")}),lI4=L.object({item:JG.describe("The deleted gateway entity")}),s80=E1({name:"COLLECTION_GATEWAY_DELETE",description:"Delete an MCP gateway",inputSchema:mI4,outputSchema:lI4,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,selected_resources:Y.selectedResources,selected_prompts:Y.selectedPrompts})),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 wY1=s(()=>{NY1();BY1();OY1();DY1();LY1()});var pI4,t80;var PY1=s(()=>{x4();w4();pI4=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")}),t80=E1({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(pI4).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 e80;var MY1=s(()=>{x4();w4();e80=E1({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 TY1=s(()=>{PY1();MY1()});var Q90;var AY1=s(()=>{w4();x4();Q90=E1({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 J90;var EY1=s(()=>{w4();x4();J90=E1({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 X90;var jY1=s(()=>{w4();x4();X90=E1({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 Y90;var IY1=s(()=>{w4();x4();Y90=E1({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 G90;var CY1=s(()=>{w4();x4();G90=E1({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 gP;var W90=s(()=>{w4();gP=L.object({title:L.string(),url:L.string(),connectionId:L.string(),icon:L.string()})});var $90;var RY1=s(()=>{w4();x4();W90();$90=E1({name:"ORGANIZATION_SETTINGS_GET",description:"Get organization-level settings",inputSchema:L.object({}),outputSchema:L.object({organizationId:L.string(),sidebar_items:L.array(gP).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 K90;var SY1=s(()=>{w4();x4();W90();K90=E1({name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization-level settings",inputSchema:L.object({organizationId:L.string(),sidebar_items:L.array(gP).optional()}),outputSchema:L.object({organizationId:L.string(),sidebar_items:L.array(gP).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 Z90;var vY1=s(()=>{w4();x4();Z90=E1({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 H90;var kY1=s(()=>{w4();x4();H90=E1({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 F90;var _Y1=s(()=>{w4();x4();F90=E1({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 q90;var yY1=s(()=>{w4();x4();q90=E1({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 hY1=s(()=>{AY1();EY1();jY1();IY1();CY1();RY1();SY1();vY1();kY1();_Y1();yY1()});var bY1={};z6(bY1,{managementMCP:()=>V90,ALL_TOOLS:()=>fY1});var fY1,V90=(Q)=>{let J=fY1.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 cJ1({name:"mcp-mesh-management",version:"1.0.0"}).withTools(J).build()};var z90=s(()=>{nJ1();$X1();eX1();XY1();VY1();wY1();TY1();hY1();fY1=[Q90,J90,X90,Y90,G90,$90,K90,Z90,H90,F90,q90,Z80,S80,v80,y80,h80,f80,n80,r80,a80,o80,s80,JY1,t80,e80,G80,$80,K80,W80,b80,x80,g80,u80,m80,l80,d80]});var FF,E90,j_,qF,iP;var I_=s(()=>{FF={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},E90={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},j_={Pending:0,Fulfilled:1,Rejected:2},qF={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},iP={IsStrictlyEqual:0,IsSameValue:1,IsSameValueZero:2}});function pU(...Q){v90&&console.log("quickjs-emscripten:",...Q)}function*m71(Q){return yield Q}function CC4(Q){return m71(_90(Q))}function R71(Q,J){return(...X)=>{let G=J.call(Q,k90,...X);return _90(G)}}function RC4(Q,J){let X=J.call(Q,k90);return _90(X)}function _90(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 j90(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 l71(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,R90,{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 C_(Q){return!!(Q&&(typeof Q=="object"||typeof Q=="function")&&("alive"in Q)&&typeof Q.alive=="boolean"&&("dispose"in Q)&&typeof Q.dispose=="function")}function SC4(Q){if(!Q)return 0;let J=0;for(let[X,G]of Object.entries(Q)){if(!(X in E90))throw new x71(X);G&&(J|=E90[X])}return J}function vC4(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"&&($|=FF.JS_EVAL_TYPE_GLOBAL),J==="module"&&($|=FF.JS_EVAL_TYPE_MODULE),X&&($|=FF.JS_EVAL_FLAG_STRICT),G&&($|=FF.JS_EVAL_FLAG_STRIP),Y&&($|=FF.JS_EVAL_FLAG_COMPILE_ONLY),W&&($|=FF.JS_EVAL_FLAG_BACKTRACE_BARRIER),$}function kC4(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|=qF.JS_GPN_STRING_MASK),X&&(K|=qF.JS_GPN_SYMBOL_MASK),G&&(K|=qF.JS_GPN_PRIVATE_MASK),Y&&(K|=qF.JS_GPN_ENUM_ONLY),W&&(K|=qF.QTS_GPN_NUMBER_MASK),$&&(K|=qF.QTS_STANDARD_COMPLIANT_NUMBER),K}function _C4(...Q){let J=[];for(let X of Q)X!==void 0&&(J=J.concat(X));return J}function b90(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 x90(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 jC4,IC4=(Q,J)=>{for(var X in J)jC4(Q,X,{get:J[X],enumerable:!0})},v90=!1,v71,I90,k71,C90,_71,y71,h71,f71,b71,x71,g71,u71,k90,yW,R90,S71,l5,YZ,S90,fY,y90,d71,p71,VF,c71,n71=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}},Gb6,h90,yC4,hC4,i71,r71,fC4=class{constructor(Q){this.callFunction=Q.callFunction,this.shouldInterrupt=Q.shouldInterrupt,this.loadModuleSource=Q.loadModuleSource,this.normalizeModule=Q.normalizeModule}},f90=class{constructor(Q){this.contextCallbacks=new Map,this.runtimeCallbacks=new Map,this.suspendedCount=0,this.cToHostCallbacks=new fC4({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)){pU("asyncify.handleSleep: not suspending:",Y),G(Y);return}if(this.suspended)throw new y71(`Already suspended at: ${this.suspended.stack}
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{c as Fe,j as t,r as Me,f as He,b as Oe,a as Re,x as Ve,y as Le}from"./index-DrO6_oKQ.js";import{C as Ue}from"./schema-DS_MXXSd.js";import{C as We}from"./collection-header-BZWDRhRJ.js";import{C as qe}from"./collection-page-Cy4Url61.js";import{C as Ge}from"./collection-search-BEr5-om_.js";import{C as Je}from"./collection-table-wrapper-CYIQZiF8.js";import{C as Qe}from"./connection-card-Cjb0De9E.js";import{E as ke}from"./SearchMd-Bq2ogvbg.js";import{E as Xe}from"./error-boundary-xo0wHpmi.js";import{a as Ye,u as Ze,n as Ke,I as et}from"./use-connection-PNwxddOO.js";import{u as tt,s as Pe}from"./use-list-state-lBd2usQq.js";import{u as nt}from"./tooltip-C9HJ0ESh.js";import{c as ot,b as st,d as it,A as rt,e as lt,g as ct,a as at,f as dt}from"./alert-dialog-BUlG7TA4.js";import{B as mt}from"./badge-DwRxIVxi.js";import{B as E}from"./button-DylnVNOq.js";import{a as ut,b as pt,D as ht,f as ft,c as gt,d as xt}from"./dialog-DHu5nMEY.js";import{b as Te,D as $e,a as Ae,c as he}from"./dropdown-menu-DiYpBa-u.js";import{F as K,a as jt,b as B,c as H,d as O,f as R}from"./form-DJrhF5P2.js";import{i as ze}from"./DotsVertical-CYYr09mb.js";import{i as Ct}from"./Loading01-CAh3R9sn.js";import{s as Ee}from"./Trash01-KvM_z2HW.js";import{I as Ie}from"./input-KnYDv1A5.js";import{S as _t,a as St,b as yt,c as vt,d as Ne}from"./select-D2oQHnH-.js";import{T as wt}from"./textarea-BYzZCFR4.js";import{g as bt}from"./generate-id-Dyweu44Y.js";import"./collection-display-button-CvZ8eTT6.js";import"./Grid01-DZvMiQMk.js";import"./utils-CzqUBWOD.js";import"./card-DxJ2CMrY.js";import"./use-mobile-BZVx-pSu.js";import"./X-CafPP_Iv.js";import"./ChevronDown-133w8HOk.js";const Dt=Ue.pick({title:!0,description:!0,connection_type:!0,connection_url:!0,connection_token:!0}).partial({description:!0,connection_token:!0});function kt(e,n){switch(n.type){case"edit":return{mode:"editing",connection:n.connection};case"delete":return{mode:"deleting",connection:n.connection};case"close":return{mode:"idle"}}}function Nt(){const e=Fe.c(126),{org:n}=nt(),r=He();let V;e[0]===Symbol.for("react.memo_cache_sentinel")?(V={strict:!1},e[0]=V):V=e[0];const Be=Oe(V),{data:fe}=Re.useSession();let L;e[1]!==n.slug?(L={namespace:n.slug,resource:"connections"},e[1]=n.slug,e[2]=L):L=e[2];const o=tt(L),d=Ye(),F=Ze(o);let U;e[3]===Symbol.for("react.memo_cache_sentinel")?(U={mode:"idle"},e[3]=U):U=e[3];const[c,m]=Me.useReducer(kt,U),W=Be.action==="create";let q;e[4]!==r||e[5]!==n.slug?(q=()=>{r({to:"/$org/mcps",params:{org:n.slug},search:{action:"create"}})},e[4]=r,e[5]=n.slug,e[6]=q):q=e[6];const ge=q;let G;e[7]!==r||e[8]!==n.slug?(G=()=>{r({to:"/$org/mcps",params:{org:n.slug},search:{}})},e[7]=r,e[8]=n.slug,e[9]=G):G=e[9];const u=G;let J;e[10]===Symbol.for("react.memo_cache_sentinel")?(J={resolver:Ve(Dt),defaultValues:{title:"",description:null,connection_type:"HTTP",connection_url:"",connection_token:null}},e[10]=J):J=e[10];const i=Le(J),l=c.mode==="editing"?c.connection:null;let Q,X;e[11]!==l||e[12]!==i?(Q=()=>{l?i.reset({title:l.title,description:l.description,connection_type:l.connection_type,connection_url:l.connection_url,connection_token:null}):i.reset({title:"",description:null,connection_type:"HTTP",connection_url:"",connection_token:null})},X=[l,i],e[11]=l,e[12]=i,e[13]=Q,e[14]=X):(Q=e[13],X=e[14]),Me.useEffect(Q,X);let Y;e[15]!==d||e[16]!==c.connection||e[17]!==c.mode?(Y=async()=>{if(c.mode!=="deleting")return;const s=c.connection.id;m({type:"close"});try{await d.delete.mutateAsync(s)}catch{}},e[15]=d,e[16]=c.connection,e[17]=c.mode,e[18]=Y):Y=e[18];const xe=Y;let Z;e[19]!==d||e[20]!==u||e[21]!==l||e[22]!==i||e[23]!==r||e[24]!==n.id||e[25]!==n.slug||e[26]!==fe?.user?.id?(Z=async s=>{if(l){await d.update.mutateAsync({id:l.id,data:{title:s.title,description:s.description||null,connection_type:s.connection_type,connection_url:s.connection_url,...s.connection_token&&{connection_token:s.connection_token}}}),m({type:"close"}),i.reset();return}const a=bt("conn");await d.create.mutateAsync({id:a,title:s.title,description:s.description||null,connection_type:s.connection_type,connection_url:s.connection_url,connection_token:s.connection_token||null,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),created_by:fe?.user?.id||"system",organization_id:n.id,icon:null,app_name:null,app_id:null,connection_headers:null,oauth_config:null,configuration_state:null,metadata:null,tools:null,bindings:null,status:"inactive"}),u(),i.reset(),r({to:"/$org/mcps/$connectionId",params:{org:n.slug,connectionId:a}})},e[19]=d,e[20]=u,e[21]=l,e[22]=i,e[23]=r,e[24]=n.id,e[25]=n.slug,e[26]=fe?.user?.id,e[27]=Z):Z=e[27];const je=Z;let ee;e[28]!==u||e[29]!==i||e[30]!==W?(ee=s=>{s||(W?u():m({type:"close"}),i.reset())},e[28]=u,e[29]=i,e[30]=W,e[31]=ee):ee=e[31];const p=ee;let te,ne,oe,se,ie,re;e[32]===Symbol.for("react.memo_cache_sentinel")?(te={id:"icon",header:"",render:Vt,cellClassName:"w-16 shrink-0",wrap:!0},ne={id:"title",header:"Name",render:Rt,cellClassName:"w-48 min-w-0 shrink-0",sortable:!0},oe={id:"description",header:"Description",render:Ot,cellClassName:"flex-1 min-w-0",wrap:!0,sortable:!0},se={id:"connection_type",header:"Type",accessor:Ht,cellClassName:"w-24 shrink-0",sortable:!0},ie={id:"connection_url",header:"URL",render:Bt,wrap:!0,cellClassName:"w-48 min-w-0 shrink-0"},re={id:"status",header:"Status",render:Kt,cellClassName:"w-24 shrink-0",sortable:!0},e[32]=te,e[33]=ne,e[34]=oe,e[35]=se,e[36]=ie,e[37]=re):(te=e[32],ne=e[33],oe=e[34],se=e[35],ie=e[36],re=e[37]);let le;e[38]!==r||e[39]!==n.slug?(le=[te,ne,oe,se,ie,re,{id:"actions",header:"",render:s=>t.jsxs(Te,{children:[t.jsx($e,{asChild:!0,children:t.jsx(E,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:Ft,children:t.jsx(ze,{size:20})})}),t.jsxs(Ae,{align:"end",onClick:Et,children:[t.jsxs(he,{onClick:a=>{a.stopPropagation(),r({to:"/$org/mcps/$connectionId",params:{org:n.slug,connectionId:s.id}})},children:[t.jsx(Pe,{size:16}),"Inspect"]}),t.jsxs(he,{variant:"destructive",onClick:a=>{a.stopPropagation(),m({type:"delete",connection:s})},children:[t.jsx(Ee,{size:16}),"Delete"]})]})]}),cellClassName:"w-12 shrink-0"}],e[38]=r,e[39]=n.slug,e[40]=le):le=e[40];const Ce=le;let h;e[41]!==r||e[42]!==n.slug?(h=t.jsx(E,{variant:"outline",onClick:()=>r({to:"/$org/store",params:{org:n.slug}}),size:"sm",className:"h-7 px-3 rounded-lg text-sm font-medium",children:"Browse Store"}),e[41]=r,e[42]=n.slug,e[43]=h):h=e[43];let f;e[44]!==ge?(f=t.jsx(E,{onClick:ge,size:"sm",className:"h-7 px-3 rounded-lg text-sm font-medium",children:"Connect MCP Server"}),e[44]=ge,e[45]=f):f=e[45];let ce;e[46]!==h||e[47]!==f?(ce=t.jsxs("div",{className:"flex items-center gap-2",children:[h,f]}),e[46]=h,e[47]=f,e[48]=ce):ce=e[48];const _e=ce,Se=W||c.mode==="editing",ye=l?"Edit Connection":"Create New Connection";let g;e[49]!==ye?(g=t.jsx(ut,{children:ye}),e[49]=ye,e[50]=g):g=e[50];const ve=l?"Update the connection details below.":"Add a new connection to your organization. Fill in the details below.";let x;e[51]!==ve?(x=t.jsx(pt,{children:ve}),e[51]=ve,e[52]=x):x=e[52];let j;e[53]!==g||e[54]!==x?(j=t.jsxs(ht,{children:[g,x]}),e[53]=g,e[54]=x,e[55]=j):j=e[55];let C;e[56]!==i||e[57]!==je?(C=i.handleSubmit(je),e[56]=i,e[57]=je,e[58]=C):C=e[58];let _;e[59]!==i.control?(_=t.jsxs("div",{className:"grid gap-4 py-4",children:[t.jsx(K,{control:i.control,name:"title",render:zt}),t.jsx(K,{control:i.control,name:"description",render:At}),t.jsx(K,{control:i.control,name:"connection_type",render:$t}),t.jsx(K,{control:i.control,name:"connection_url",render:Tt}),t.jsx(K,{control:i.control,name:"connection_token",render:Pt})]}),e[59]=i.control,e[60]=_):_=e[60];let S;e[61]!==p?(S=t.jsx(E,{type:"button",variant:"outline",onClick:()=>p(!1),children:"Cancel"}),e[61]=p,e[62]=S):S=e[62];const we=i.formState.isSubmitting?"Saving...":l?"Update Connection":"Create Connection";let y;e[63]!==i.formState.isSubmitting||e[64]!==we?(y=t.jsx(E,{type:"submit",disabled:i.formState.isSubmitting,className:"min-w-40",children:we}),e[63]=i.formState.isSubmitting,e[64]=we,e[65]=y):y=e[65];let v;e[66]!==S||e[67]!==y?(v=t.jsxs(ft,{children:[S,y]}),e[66]=S,e[67]=y,e[68]=v):v=e[68];let w;e[69]!==C||e[70]!==_||e[71]!==v?(w=t.jsxs("form",{onSubmit:C,children:[_,v]}),e[69]=C,e[70]=_,e[71]=v,e[72]=w):w=e[72];let b;e[73]!==i||e[74]!==w?(b=t.jsx(jt,{...i,children:w}),e[73]=i,e[74]=w,e[75]=b):b=e[75];let D;e[76]!==j||e[77]!==b?(D=t.jsxs(gt,{className:"sm:max-w-[525px]",children:[j,b]}),e[76]=j,e[77]=b,e[78]=D):D=e[78];let k;e[79]!==p||e[80]!==Se||e[81]!==D?(k=t.jsx(xt,{open:Se,onOpenChange:p,children:D}),e[79]=p,e[80]=Se,e[81]=D,e[82]=k):k=e[82];const be=c.mode==="deleting";let ae;e[83]===Symbol.for("react.memo_cache_sentinel")?(ae=s=>!s&&m({type:"close"}),e[83]=ae):ae=e[83];let de;e[84]===Symbol.for("react.memo_cache_sentinel")?(de=t.jsx(ot,{children:"Delete Connection?"}),e[84]=de):de=e[84];const De=c.mode==="deleting"&&c.connection.title;let N;e[85]!==De?(N=t.jsxs(st,{children:[de,t.jsxs(it,{children:["This action cannot be undone. This will permanently delete"," ",t.jsx("span",{className:"font-medium text-foreground",children:De}),"."]})]}),e[85]=De,e[86]=N):N=e[86];let me;e[87]===Symbol.for("react.memo_cache_sentinel")?(me=t.jsx(rt,{children:"Cancel"}),e[87]=me):me=e[87];let M;e[88]!==xe?(M=t.jsxs(lt,{children:[me,t.jsx(ct,{onClick:xe,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]}),e[88]=xe,e[89]=M):M=e[89];let I;e[90]!==N||e[91]!==M?(I=t.jsxs(at,{children:[N,M]}),e[90]=N,e[91]=M,e[92]=I):I=e[92];let P;e[93]!==be||e[94]!==I?(P=t.jsx(dt,{open:be,onOpenChange:ae,children:I}),e[93]=be,e[94]=I,e[95]=P):P=e[95];let ue;e[96]===Symbol.for("react.memo_cache_sentinel")?(ue=[{id:"title",label:"Name"},{id:"description",label:"Description"},{id:"connection_type",label:"Type"},{id:"status",label:"Status"}],e[96]=ue):ue=e[96];let T;e[97]!==_e||e[98]!==o.handleSort||e[99]!==o.setViewMode||e[100]!==o.sortDirection||e[101]!==o.sortKey||e[102]!==o.viewMode?(T=t.jsx(We,{title:"MCP Servers",viewMode:o.viewMode,onViewModeChange:o.setViewMode,sortKey:o.sortKey,sortDirection:o.sortDirection,onSort:o.handleSort,sortOptions:ue,ctaButton:_e}),e[97]=_e,e[98]=o.handleSort,e[99]=o.setViewMode,e[100]=o.sortDirection,e[101]=o.sortKey,e[102]=o.viewMode,e[103]=T):T=e[103];let $;e[104]!==o?($=s=>{s.key==="Escape"&&(o.setSearch(""),s.target.blur())},e[104]=o,e[105]=$):$=e[105];let A;e[106]!==o.search||e[107]!==o.setSearch||e[108]!==$?(A=t.jsx(Ge,{value:o.search,onChange:o.setSearch,placeholder:"Search for an MCP Server...",onKeyDown:$}),e[106]=o.search,e[107]=o.setSearch,e[108]=$,e[109]=A):A=e[109];let z;e[110]!==Ce||e[111]!==F||e[112]!==o.handleSort||e[113]!==o.search||e[114]!==o.sortDirection||e[115]!==o.sortKey||e[116]!==o.viewMode||e[117]!==r||e[118]!==n.slug?(z=o.viewMode==="cards"?t.jsx("div",{className:"flex-1 overflow-auto p-5",children:F.length===0?t.jsx(ke,{image:t.jsx("img",{src:"/emptystate-mcp.svg",alt:"",width:500,height:223,"aria-hidden":"true"}),title:(o.search,"No MCP Servers found"),description:o.search?`No MCP Servers match "${o.search}"`:"Create a connection to get started."}):t.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 gap-4",children:F.map(s=>t.jsx(Qe,{connection:s,fallbackIcon:t.jsx(Ke,{}),onClick:()=>r({to:"/$org/mcps/$connectionId",params:{org:n.slug,connectionId:s.id}}),headerActions:t.jsxs(Te,{children:[t.jsx($e,{asChild:!0,children:t.jsx(E,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:It,children:t.jsx(ze,{size:20})})}),t.jsxs(Ae,{align:"end",onClick:Mt,children:[t.jsxs(he,{onClick:a=>{a.stopPropagation(),r({to:"/$org/mcps/$connectionId",params:{org:n.slug,connectionId:s.id}})},children:[t.jsx(Pe,{size:16}),"Inspect"]}),t.jsxs(he,{variant:"destructive",onClick:a=>{a.stopPropagation(),m({type:"delete",connection:s})},children:[t.jsx(Ee,{size:16}),"Delete"]})]})]})},s.id))})}):t.jsx(Je,{columns:Ce,data:F,isLoading:!1,sortKey:o.sortKey,sortDirection:o.sortDirection,onSort:o.handleSort,onRowClick:s=>r({to:"/$org/mcps/$connectionId",params:{org:n.slug,connectionId:s.id}}),emptyState:o.search?t.jsx(ke,{image:t.jsx("img",{src:"/emptystate-mcp.svg",alt:"",width:500,height:223,"aria-hidden":"true"}),title:"No MCP Servers found",description:`No MCP Servers match "${o.search}"`}):t.jsx(ke,{image:t.jsx("img",{src:"/emptystate-mcp.svg",alt:"",width:500,height:223,"aria-hidden":"true"}),title:"No MCP Servers found",description:"Create a connection to get started."})}),e[110]=Ce,e[111]=F,e[112]=o.handleSort,e[113]=o.search,e[114]=o.sortDirection,e[115]=o.sortKey,e[116]=o.viewMode,e[117]=r,e[118]=n.slug,e[119]=z):z=e[119];let pe;return e[120]!==k||e[121]!==P||e[122]!==T||e[123]!==A||e[124]!==z?(pe=t.jsxs(qe,{children:[k,P,T,A,z]}),e[120]=k,e[121]=P,e[122]=T,e[123]=A,e[124]=z,e[125]=pe):pe=e[125],pe}function Mt(e){return e.stopPropagation()}function It(e){return e.stopPropagation()}function Pt(e){const{field:n}=e;return t.jsxs(B,{children:[t.jsx(H,{children:"Token (optional)"}),t.jsx(O,{children:t.jsx(Ie,{type:"password",placeholder:"Bearer token or API key",...n,value:n.value??""})}),t.jsx(R,{})]})}function Tt(e){const{field:n}=e;return t.jsxs(B,{children:[t.jsx(H,{children:"URL *"}),t.jsx(O,{children:t.jsx(Ie,{placeholder:"https://example.com/mcp",...n})}),t.jsx(R,{})]})}function $t(e){const{field:n}=e;return t.jsxs(B,{children:[t.jsx(H,{children:"Type *"}),t.jsxs(_t,{value:n.value,onValueChange:n.onChange,children:[t.jsx(O,{children:t.jsx(St,{children:t.jsx(yt,{})})}),t.jsxs(vt,{children:[t.jsx(Ne,{value:"HTTP",children:"HTTP"}),t.jsx(Ne,{value:"SSE",children:"SSE"}),t.jsx(Ne,{value:"Websocket",children:"Websocket"})]})]}),t.jsx(R,{})]})}function At(e){const{field:n}=e;return t.jsxs(B,{children:[t.jsx(H,{children:"Description"}),t.jsx(O,{children:t.jsx(wt,{placeholder:"A brief description of this connection",rows:3,...n,value:n.value??""})}),t.jsx(R,{})]})}function zt(e){const{field:n}=e;return t.jsxs(B,{children:[t.jsx(H,{children:"Name *"}),t.jsx(O,{children:t.jsx(Ie,{placeholder:"My Connection",...n})}),t.jsx(R,{})]})}function Et(e){return e.stopPropagation()}function Ft(e){return e.stopPropagation()}function Kt(e){return t.jsx(mt,{variant:e.status==="active"?"success":"outline",children:e.status})}function Bt(e){return t.jsx("span",{className:"text-sm text-muted-foreground block truncate",children:e.connection_url})}function Ht(e){return t.jsx("span",{className:"text-sm font-medium",children:e.connection_type})}function Ot(e){return t.jsx("span",{className:"text-sm text-foreground line-clamp-2",children:e.description||"—"})}function Rt(e){return t.jsx("span",{className:"text-sm font-medium text-foreground truncate",children:e.title})}function Vt(e){return t.jsx(et,{icon:e.icon,name:e.title,size:"sm",className:"shrink-0 shadow-sm",fallbackIcon:t.jsx(Ke,{})})}function vn(){const e=Fe.c(1);let n;return e[0]===Symbol.for("react.memo_cache_sentinel")?(n=t.jsx(Xe,{children:t.jsx(Me.Suspense,{fallback:t.jsx("div",{className:"flex h-full items-center justify-center",children:t.jsx(Ct,{size:32,className:"animate-spin text-muted-foreground"})}),children:t.jsx(Nt,{})})}),e[0]=n):n=e[0],n}export{vn as default};
|