@superinterface/server 1.5.0-beta.0 → 1.5.0-beta.2
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/.next/BUILD_ID +1 -1
- package/.next/build-manifest.json +2 -2
- package/.next/cache/.tsbuildinfo +1 -1
- package/.next/cache/eslint/.cache_btwyo7 +1 -1
- package/.next/fallback-build-manifest.json +2 -2
- package/.next/server/app/_not-found.html +1 -1
- package/.next/server/app/_not-found.rsc +1 -1
- package/.next/server/app/index.html +1 -1
- package/.next/server/app/index.rsc +1 -1
- package/.next/server/chunks/c4f00_next_dist_esm_build_templates_app-route_f952d9ab.js +1 -1
- package/.next/server/chunks/c4f00_next_dist_esm_build_templates_app-route_f952d9ab.js.map +1 -1
- package/.next/server/chunks/supercorp_superinterface_bebd2c96._.js +1 -1
- package/.next/server/chunks/supercorp_superinterface_bebd2c96._.js.map +1 -1
- package/.next/server/pages/404.html +1 -1
- package/.next/server/pages/500.html +1 -1
- package/.next/trace +1 -1
- package/dist/app/api/messages/buildRoute.js +1 -1
- package/dist/lib/tools/tools/index.d.ts.map +1 -1
- package/dist/lib/tools/tools/index.js +9 -1
- package/package.json +1 -1
- /package/.next/static/{ZR7Sh-LZF3xBJ-5AhtC88 → AgkqDoZ0OpW8jWkwEy55l}/_buildManifest.js +0 -0
- /package/.next/static/{ZR7Sh-LZF3xBJ-5AhtC88 → AgkqDoZ0OpW8jWkwEy55l}/_clientMiddlewareManifest.json +0 -0
- /package/.next/static/{ZR7Sh-LZF3xBJ-5AhtC88 → AgkqDoZ0OpW8jWkwEy55l}/_ssgManifest.js +0 -0
|
@@ -2,6 +2,6 @@ module.exports=[58325,(e,r,t)=>{e.e,function(e){"use strict";function r(){for(va
|
|
|
2
2
|
`)?l.slice(0,-1):l}),n=void 0,l="",c="");if(e.startsWith(":")){o&&o(e.slice(e.startsWith(": ")?2:1));return}let t=e.indexOf(":");if(-1!==t){let r=e.slice(0,t),a=" "===e[t+1]?2:1;h(r,e.slice(t+a),e);return}h(e,"",e)}function h(e,r,o){switch(e){case"event":c=r;break;case"data":l=`${l}${r}
|
|
3
3
|
`;break;case"id":n=r.includes("\0")?void 0:r;break;case"retry":/^\d+$/.test(r)?a(parseInt(r,10)):t(new m(`Invalid \`retry\` value: "${r}"`,{type:"invalid-retry",value:r,line:o}));break;default:t(new m(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:"unknown-field",field:e,value:r,line:o}))}}return{feed:function(e){let r=i?e.replace(/^\xEF\xBB\xBF/,""):e,[t,a]=function(e){let r=[],t="",a=0;for(;a<e.length;){let o=e.indexOf("\r",a),s=e.indexOf(`
|
|
4
4
|
`,a),i=-1;if(-1!==o&&-1!==s?i=Math.min(o,s):-1!==o?i=o===e.length-1?-1:o:-1!==s&&(i=s),-1===i){t=e.slice(a);break}{let t=e.slice(a,i);r.push(t),"\r"===e[(a=i+1)-1]&&e[a]===`
|
|
5
|
-
`&&a++}}return[r,t]}(`${s}${r}`);for(let e of t)u(e);s=a,i=!1},reset:function(e={}){s&&e.consume&&u(s),i=!0,n=void 0,l="",c="",s=""}}}class g extends Event{constructor(e,r){var t,a;super(e),this.code=null!=(t=null==r?void 0:r.code)?t:void 0,this.message=null!=(a=null==r?void 0:r.message)?a:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,t){return t(y(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(y(this),r)}}function y(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var _,E,P,b,w,z,S,R,T,C,O,x,I,A,j,D,$,F,k,U,L,N,M,q=e=>{throw TypeError(e)},H=(e,r,t)=>r.has(e)||q("Cannot "+t),V=(e,r,t)=>(H(e,r,"read from private field"),t?t.call(e):r.get(e)),Q=(e,r,t)=>r.has(e)?q("Cannot add the same private member more than once"):r instanceof WeakSet?r.add(e):r.set(e,t),G=(e,r,t,a)=>(H(e,r,"write to private field"),r.set(e,t),t),B=(e,r,t)=>(H(e,r,"access private method"),t);class K extends EventTarget{constructor(e,r){var t,a;super(),Q(this,A),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Q(this,_),Q(this,E),Q(this,P),Q(this,b),Q(this,w),Q(this,z),Q(this,S),Q(this,R,null),Q(this,T),Q(this,C),Q(this,O,null),Q(this,x,null),Q(this,I,null),Q(this,D,async e=>{var r;V(this,C).reset();let{body:t,redirected:a,status:o,headers:s}=e;if(204===o){B(this,A,L).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(a?G(this,P,new URL(e.url)):G(this,P,void 0),200!==o)return void B(this,A,L).call(this,`Non-200 status code (${o})`,o);if(!(s.get("content-type")||"").startsWith("text/event-stream"))return void B(this,A,L).call(this,'Invalid content type, expected "text/event-stream"',o);if(V(this,_)===this.CLOSED)return;G(this,_,this.OPEN);let i=new Event("open");if(null==(r=V(this,I))||r.call(this,i),this.dispatchEvent(i),"object"!=typeof t||!t||!("getReader"in t)){B(this,A,L).call(this,"Invalid response body, expected a web ReadableStream",o),this.close();return}let n=new TextDecoder,l=t.getReader(),c=!0;do{let{done:e,value:r}=await l.read();r&&V(this,C).feed(n.decode(r,{stream:!e})),e&&(c=!1,V(this,C).reset(),B(this,A,N).call(this))}while(c)}),Q(this,$,e=>{G(this,T,void 0),"AbortError"!==e.name&&"aborted"!==e.type&&B(this,A,N).call(this,function e(r){return r instanceof Error?"errors"in r&&Array.isArray(r.errors)?r.errors.map(e).join(", "):"cause"in r&&r.cause instanceof Error?`${r}: ${e(r.cause)}`:r.message:`${r}`}(e))}),Q(this,k,e=>{"string"==typeof e.id&&G(this,R,e.id);let r=new MessageEvent(e.event||"message",{data:e.data,origin:V(this,P)?V(this,P).origin:V(this,E).origin,lastEventId:e.id||""});V(this,x)&&(!e.event||"message"===e.event)&&V(this,x).call(this,r),this.dispatchEvent(r)}),Q(this,U,e=>{G(this,z,e)}),Q(this,M,()=>{G(this,S,void 0),V(this,_)===this.CONNECTING&&B(this,A,j).call(this)});try{if(e instanceof URL)G(this,E,e);else if("string"==typeof e)G(this,E,new URL(e,function(){let e="document"in globalThis?globalThis.document:void 0;return e&&"object"==typeof e&&"baseURI"in e&&"string"==typeof e.baseURI?e.baseURI:void 0}()));else throw Error("Invalid URL")}catch{throw function(e){let r=globalThis.DOMException;return"function"==typeof r?new r(e,"SyntaxError"):SyntaxError(e)}("An invalid or illegal string was specified")}G(this,C,v({onEvent:V(this,k),onRetry:V(this,U)})),G(this,_,this.CONNECTING),G(this,z,3e3),G(this,w,null!=(t=null==r?void 0:r.fetch)?t:globalThis.fetch),G(this,b,null!=(a=null==r?void 0:r.withCredentials)&&a),B(this,A,j).call(this)}get readyState(){return V(this,_)}get url(){return V(this,E).href}get withCredentials(){return V(this,b)}get onerror(){return V(this,O)}set onerror(e){G(this,O,e)}get onmessage(){return V(this,x)}set onmessage(e){G(this,x,e)}get onopen(){return V(this,I)}set onopen(e){G(this,I,e)}addEventListener(e,r,t){super.addEventListener(e,r,t)}removeEventListener(e,r,t){super.removeEventListener(e,r,t)}close(){V(this,S)&&clearTimeout(V(this,S)),V(this,_)!==this.CLOSED&&(V(this,T)&&V(this,T).abort(),G(this,_,this.CLOSED),G(this,T,void 0))}}_=new WeakMap,E=new WeakMap,P=new WeakMap,b=new WeakMap,w=new WeakMap,z=new WeakMap,S=new WeakMap,R=new WeakMap,T=new WeakMap,C=new WeakMap,O=new WeakMap,x=new WeakMap,I=new WeakMap,A=new WeakSet,j=function(){G(this,_,this.CONNECTING),G(this,T,new AbortController),V(this,w)(V(this,E),B(this,A,F).call(this)).then(V(this,D)).catch(V(this,$))},D=new WeakMap,$=new WeakMap,F=function(){var e;let r={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...V(this,R)?{"Last-Event-ID":V(this,R)}:void 0},cache:"no-store",signal:null==(e=V(this,T))?void 0:e.signal};return"window"in globalThis&&(r.credentials=this.withCredentials?"include":"same-origin"),r},k=new WeakMap,U=new WeakMap,L=function(e,r){var t;V(this,_)!==this.CLOSED&&G(this,_,this.CLOSED);let a=new g("error",{code:r,message:e});null==(t=V(this,O))||t.call(this,a),this.dispatchEvent(a)},N=function(e,r){var t;if(V(this,_)===this.CLOSED)return;G(this,_,this.CONNECTING);let a=new g("error",{code:r,message:e});null==(t=V(this,O))||t.call(this,a),this.dispatchEvent(a),G(this,S,setTimeout(V(this,M),V(this,z)))},M=new WeakMap,K.CONNECTING=0,K.OPEN=1,K.CLOSED=2,e.s(["CallToolResultSchema",()=>ra,"CancelledNotificationSchema",()=>eg,"CompleteResultSchema",()=>rz,"EmptyResultSchema",()=>ev,"ErrorCode",()=>t,"GetPromptResultSchema",()=>e6,"InitializeResultSchema",()=>eS,"JSONRPCMessageSchema",()=>ef,"LATEST_PROTOCOL_VERSION",()=>J,"ListPromptsResultSchema",()=>eY,"ListResourceTemplatesResultSchema",()=>eq,"ListResourcesResultSchema",()=>eN,"ListToolsResultSchema",()=>rt,"McpError",()=>rO,"PingRequestSchema",()=>eC,"ProgressNotificationSchema",()=>ex,"ReadResourceResultSchema",()=>eV,"SUPPORTED_PROTOCOL_VERSIONS",()=>Z,"isInitializedNotification",()=>eT,"isJSONRPCError",()=>em,"isJSONRPCNotification",()=>eu,"isJSONRPCRequest",()=>el,"isJSONRPCResponse",()=>ep],76862);var W=e.i(13669);let J="2025-06-18",Z=[J,"2025-03-26","2024-11-05","2024-10-07"],Y=W.z.union([W.z.string(),W.z.number().int()]),X=W.z.string(),ee=W.z.object({progressToken:W.z.optional(Y)}).passthrough(),er=W.z.object({_meta:W.z.optional(ee)}).passthrough(),et=W.z.object({method:W.z.string(),params:W.z.optional(er)}),ea=W.z.object({_meta:W.z.optional(W.z.object({}).passthrough())}).passthrough(),eo=W.z.object({method:W.z.string(),params:W.z.optional(ea)}),es=W.z.object({_meta:W.z.optional(W.z.object({}).passthrough())}).passthrough(),ei=W.z.union([W.z.string(),W.z.number().int()]),en=W.z.object({jsonrpc:W.z.literal("2.0"),id:ei}).merge(et).strict(),el=e=>en.safeParse(e).success,ec=W.z.object({jsonrpc:W.z.literal("2.0")}).merge(eo).strict(),eu=e=>ec.safeParse(e).success,eh=W.z.object({jsonrpc:W.z.literal("2.0"),id:ei,result:es}).strict(),ep=e=>eh.safeParse(e).success;!function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError"}(t||(t={}));let ed=W.z.object({jsonrpc:W.z.literal("2.0"),id:ei,error:W.z.object({code:W.z.number().int(),message:W.z.string(),data:W.z.optional(W.z.unknown())})}).strict(),em=e=>ed.safeParse(e).success,ef=W.z.union([en,ec,eh,ed]),ev=es.strict(),eg=eo.extend({method:W.z.literal("notifications/cancelled"),params:ea.extend({requestId:ei,reason:W.z.string().optional()})}),ey=W.z.object({src:W.z.string(),mimeType:W.z.optional(W.z.string()),sizes:W.z.optional(W.z.array(W.z.string()))}).passthrough(),e_=W.z.object({icons:W.z.array(ey).optional()}).passthrough(),eE=W.z.object({name:W.z.string(),title:W.z.optional(W.z.string())}).passthrough(),eP=eE.extend({version:W.z.string(),websiteUrl:W.z.optional(W.z.string())}).merge(e_),eb=W.z.object({experimental:W.z.optional(W.z.object({}).passthrough()),sampling:W.z.optional(W.z.object({}).passthrough()),elicitation:W.z.optional(W.z.object({}).passthrough()),roots:W.z.optional(W.z.object({listChanged:W.z.optional(W.z.boolean())}).passthrough())}).passthrough(),ew=et.extend({method:W.z.literal("initialize"),params:er.extend({protocolVersion:W.z.string(),capabilities:eb,clientInfo:eP})}),ez=W.z.object({experimental:W.z.optional(W.z.object({}).passthrough()),logging:W.z.optional(W.z.object({}).passthrough()),completions:W.z.optional(W.z.object({}).passthrough()),prompts:W.z.optional(W.z.object({listChanged:W.z.optional(W.z.boolean())}).passthrough()),resources:W.z.optional(W.z.object({subscribe:W.z.optional(W.z.boolean()),listChanged:W.z.optional(W.z.boolean())}).passthrough()),tools:W.z.optional(W.z.object({listChanged:W.z.optional(W.z.boolean())}).passthrough())}).passthrough(),eS=es.extend({protocolVersion:W.z.string(),capabilities:ez,serverInfo:eP,instructions:W.z.optional(W.z.string())}),eR=eo.extend({method:W.z.literal("notifications/initialized")}),eT=e=>eR.safeParse(e).success,eC=et.extend({method:W.z.literal("ping")}),eO=W.z.object({progress:W.z.number(),total:W.z.optional(W.z.number()),message:W.z.optional(W.z.string())}).passthrough(),ex=eo.extend({method:W.z.literal("notifications/progress"),params:ea.merge(eO).extend({progressToken:Y})}),eI=et.extend({params:er.extend({cursor:W.z.optional(X)}).optional()}),eA=es.extend({nextCursor:W.z.optional(X)}),ej=W.z.object({uri:W.z.string(),mimeType:W.z.optional(W.z.string()),_meta:W.z.optional(W.z.object({}).passthrough())}).passthrough(),eD=ej.extend({text:W.z.string()}),e$=W.z.string().refine(e=>{try{return atob(e),!0}catch(e){return!1}},{message:"Invalid Base64 string"}),eF=ej.extend({blob:e$}),ek=eE.extend({uri:W.z.string(),description:W.z.optional(W.z.string()),mimeType:W.z.optional(W.z.string()),_meta:W.z.optional(W.z.object({}).passthrough())}).merge(e_),eU=eE.extend({uriTemplate:W.z.string(),description:W.z.optional(W.z.string()),mimeType:W.z.optional(W.z.string()),_meta:W.z.optional(W.z.object({}).passthrough())}).merge(e_),eL=eI.extend({method:W.z.literal("resources/list")}),eN=eA.extend({resources:W.z.array(ek)}),eM=eI.extend({method:W.z.literal("resources/templates/list")}),eq=eA.extend({resourceTemplates:W.z.array(eU)}),eH=et.extend({method:W.z.literal("resources/read"),params:er.extend({uri:W.z.string()})}),eV=es.extend({contents:W.z.array(W.z.union([eD,eF]))}),eQ=eo.extend({method:W.z.literal("notifications/resources/list_changed")}),eG=et.extend({method:W.z.literal("resources/subscribe"),params:er.extend({uri:W.z.string()})}),eB=et.extend({method:W.z.literal("resources/unsubscribe"),params:er.extend({uri:W.z.string()})}),eK=eo.extend({method:W.z.literal("notifications/resources/updated"),params:ea.extend({uri:W.z.string()})}),eW=W.z.object({name:W.z.string(),description:W.z.optional(W.z.string()),required:W.z.optional(W.z.boolean())}).passthrough(),eJ=eE.extend({description:W.z.optional(W.z.string()),arguments:W.z.optional(W.z.array(eW)),_meta:W.z.optional(W.z.object({}).passthrough())}).merge(e_),eZ=eI.extend({method:W.z.literal("prompts/list")}),eY=eA.extend({prompts:W.z.array(eJ)}),eX=et.extend({method:W.z.literal("prompts/get"),params:er.extend({name:W.z.string(),arguments:W.z.optional(W.z.record(W.z.string()))})}),e0=W.z.object({type:W.z.literal("text"),text:W.z.string(),_meta:W.z.optional(W.z.object({}).passthrough())}).passthrough(),e1=W.z.object({type:W.z.literal("image"),data:e$,mimeType:W.z.string(),_meta:W.z.optional(W.z.object({}).passthrough())}).passthrough(),e2=W.z.object({type:W.z.literal("audio"),data:e$,mimeType:W.z.string(),_meta:W.z.optional(W.z.object({}).passthrough())}).passthrough(),e9=W.z.object({type:W.z.literal("resource"),resource:W.z.union([eD,eF]),_meta:W.z.optional(W.z.object({}).passthrough())}).passthrough(),e4=ek.extend({type:W.z.literal("resource_link")}),e3=W.z.union([e0,e1,e2,e4,e9]),e5=W.z.object({role:W.z.enum(["user","assistant"]),content:e3}).passthrough(),e6=es.extend({description:W.z.optional(W.z.string()),messages:W.z.array(e5)}),e7=eo.extend({method:W.z.literal("notifications/prompts/list_changed")}),e8=W.z.object({title:W.z.optional(W.z.string()),readOnlyHint:W.z.optional(W.z.boolean()),destructiveHint:W.z.optional(W.z.boolean()),idempotentHint:W.z.optional(W.z.boolean()),openWorldHint:W.z.optional(W.z.boolean())}).passthrough(),re=eE.extend({description:W.z.optional(W.z.string()),inputSchema:W.z.object({type:W.z.literal("object"),properties:W.z.optional(W.z.object({}).passthrough()),required:W.z.optional(W.z.array(W.z.string()))}).passthrough(),outputSchema:W.z.optional(W.z.object({type:W.z.literal("object"),properties:W.z.optional(W.z.object({}).passthrough()),required:W.z.optional(W.z.array(W.z.string()))}).passthrough()),annotations:W.z.optional(e8),_meta:W.z.optional(W.z.object({}).passthrough())}).merge(e_),rr=eI.extend({method:W.z.literal("tools/list")}),rt=eA.extend({tools:W.z.array(re)}),ra=es.extend({content:W.z.array(e3).default([]),structuredContent:W.z.object({}).passthrough().optional(),isError:W.z.optional(W.z.boolean())});ra.or(es.extend({toolResult:W.z.unknown()}));let ro=et.extend({method:W.z.literal("tools/call"),params:er.extend({name:W.z.string(),arguments:W.z.optional(W.z.record(W.z.unknown()))})}),rs=eo.extend({method:W.z.literal("notifications/tools/list_changed")}),ri=W.z.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),rn=et.extend({method:W.z.literal("logging/setLevel"),params:er.extend({level:ri})}),rl=eo.extend({method:W.z.literal("notifications/message"),params:ea.extend({level:ri,logger:W.z.optional(W.z.string()),data:W.z.unknown()})}),rc=W.z.object({name:W.z.string().optional()}).passthrough(),ru=W.z.object({hints:W.z.optional(W.z.array(rc)),costPriority:W.z.optional(W.z.number().min(0).max(1)),speedPriority:W.z.optional(W.z.number().min(0).max(1)),intelligencePriority:W.z.optional(W.z.number().min(0).max(1))}).passthrough(),rh=W.z.object({role:W.z.enum(["user","assistant"]),content:W.z.union([e0,e1,e2])}).passthrough(),rp=et.extend({method:W.z.literal("sampling/createMessage"),params:er.extend({messages:W.z.array(rh),systemPrompt:W.z.optional(W.z.string()),includeContext:W.z.optional(W.z.enum(["none","thisServer","allServers"])),temperature:W.z.optional(W.z.number()),maxTokens:W.z.number().int(),stopSequences:W.z.optional(W.z.array(W.z.string())),metadata:W.z.optional(W.z.object({}).passthrough()),modelPreferences:W.z.optional(ru)})}),rd=es.extend({model:W.z.string(),stopReason:W.z.optional(W.z.enum(["endTurn","stopSequence","maxTokens"]).or(W.z.string())),role:W.z.enum(["user","assistant"]),content:W.z.discriminatedUnion("type",[e0,e1,e2])}),rm=W.z.object({type:W.z.literal("boolean"),title:W.z.optional(W.z.string()),description:W.z.optional(W.z.string()),default:W.z.optional(W.z.boolean())}).passthrough(),rf=W.z.object({type:W.z.literal("string"),title:W.z.optional(W.z.string()),description:W.z.optional(W.z.string()),minLength:W.z.optional(W.z.number()),maxLength:W.z.optional(W.z.number()),format:W.z.optional(W.z.enum(["email","uri","date","date-time"]))}).passthrough(),rv=W.z.object({type:W.z.enum(["number","integer"]),title:W.z.optional(W.z.string()),description:W.z.optional(W.z.string()),minimum:W.z.optional(W.z.number()),maximum:W.z.optional(W.z.number())}).passthrough(),rg=W.z.object({type:W.z.literal("string"),title:W.z.optional(W.z.string()),description:W.z.optional(W.z.string()),enum:W.z.array(W.z.string()),enumNames:W.z.optional(W.z.array(W.z.string()))}).passthrough(),ry=W.z.union([rm,rf,rv,rg]),r_=et.extend({method:W.z.literal("elicitation/create"),params:er.extend({message:W.z.string(),requestedSchema:W.z.object({type:W.z.literal("object"),properties:W.z.record(W.z.string(),ry),required:W.z.optional(W.z.array(W.z.string()))}).passthrough()})}),rE=es.extend({action:W.z.enum(["accept","decline","cancel"]),content:W.z.optional(W.z.record(W.z.string(),W.z.unknown()))}),rP=W.z.object({type:W.z.literal("ref/resource"),uri:W.z.string()}).passthrough(),rb=W.z.object({type:W.z.literal("ref/prompt"),name:W.z.string()}).passthrough(),rw=et.extend({method:W.z.literal("completion/complete"),params:er.extend({ref:W.z.union([rb,rP]),argument:W.z.object({name:W.z.string(),value:W.z.string()}).passthrough(),context:W.z.optional(W.z.object({arguments:W.z.optional(W.z.record(W.z.string(),W.z.string()))}))})}),rz=es.extend({completion:W.z.object({values:W.z.array(W.z.string()).max(100),total:W.z.optional(W.z.number().int()),hasMore:W.z.optional(W.z.boolean())}).passthrough()}),rS=W.z.object({uri:W.z.string().startsWith("file://"),name:W.z.optional(W.z.string()),_meta:W.z.optional(W.z.object({}).passthrough())}).passthrough(),rR=et.extend({method:W.z.literal("roots/list")}),rT=es.extend({roots:W.z.array(rS)}),rC=eo.extend({method:W.z.literal("notifications/roots/list_changed")});W.z.union([eC,ew,rw,rn,eX,eZ,eL,eM,eH,eG,eB,ro,rr]),W.z.union([eg,ex,eR,rC]),W.z.union([ev,rd,rE,rT]),W.z.union([eC,rp,r_,rR]),W.z.union([eg,ex,rl,eK,eQ,rs,e7]),W.z.union([ev,eS,rz,e6,eY,eN,eq,eV,ra,rt]);class rO extends Error{constructor(e,r,t){super(`MCP error ${e}: ${r}`),this.code=e,this.data=t,this.name="McpError"}}class rx{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this.setNotificationHandler(eg,e=>{let r=this._requestHandlerAbortControllers.get(e.params.requestId);null==r||r.abort(e.params.reason)}),this.setNotificationHandler(ex,e=>{this._onprogress(e)}),this.setRequestHandler(eC,e=>({}))}_setupTimeout(e,r,t,a,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(a,r),startTime:Date.now(),timeout:r,maxTotalTimeout:t,resetTimeoutOnProgress:o,onTimeout:a})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let a=Date.now()-r.startTime;if(r.maxTotalTimeout&&a>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),new rO(t.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:a});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var r,t,a;this._transport=e;let o=null==(r=this.transport)?void 0:r.onclose;this._transport.onclose=()=>{null==o||o(),this._onclose()};let s=null==(t=this.transport)?void 0:t.onerror;this._transport.onerror=e=>{null==s||s(e),this._onerror(e)};let i=null==(a=this._transport)?void 0:a.onmessage;this._transport.onmessage=(e,r)=>{null==i||i(e,r),ep(e)||em(e)?this._onresponse(e):el(e)?this._onrequest(e,r):eu(e)?this._onnotification(e):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){var e;let r=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,null==(e=this.onclose)||e.call(this);let a=new rO(t.ConnectionClosed,"Connection closed");for(let e of r.values())e(a)}_onerror(e){var r;null==(r=this.onerror)||r.call(this,e)}_onnotification(e){var r;let t=null!=(r=this._notificationHandlers.get(e.method))?r:this.fallbackNotificationHandler;void 0!==t&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,r){var a,o;let s=null!=(a=this._requestHandlers.get(e.method))?a:this.fallbackRequestHandler,i=this._transport;if(void 0===s){null==i||i.send({jsonrpc:"2.0",id:e.id,error:{code:t.MethodNotFound,message:"Method not found"}}).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)));return}let n=new AbortController;this._requestHandlerAbortControllers.set(e.id,n);let l={signal:n.signal,sessionId:null==i?void 0:i.sessionId,_meta:null==(o=e.params)?void 0:o._meta,sendNotification:r=>this.notification(r,{relatedRequestId:e.id}),sendRequest:(r,t,a)=>this.request(r,t,{...a,relatedRequestId:e.id}),authInfo:null==r?void 0:r.authInfo,requestId:e.id,requestInfo:null==r?void 0:r.requestInfo};Promise.resolve().then(()=>s(e,l)).then(r=>{if(!n.signal.aborted)return null==i?void 0:i.send({result:r,jsonrpc:"2.0",id:e.id})},r=>{var a;if(!n.signal.aborted)return null==i?void 0:i.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(r.code)?r.code:t.InternalError,message:null!=(a=r.message)?a:"Internal error"}})}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...t}=e.params,a=Number(r),o=this._progressHandlers.get(a);if(!o)return void this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));let s=this._responseHandlers.get(a),i=this._timeoutInfo.get(a);if(i&&s&&i.resetTimeoutOnProgress)try{this._resetTimeout(a)}catch(e){s(e);return}o(t)}_onresponse(e){let r=Number(e.id),t=this._responseHandlers.get(r);if(void 0===t)return void this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),t(ep(e)?e:new rO(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){var e;await (null==(e=this._transport)?void 0:e.close())}request(e,r,a){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}=null!=a?a:{};return new Promise((n,l)=>{var c,u,h,p,d,m;if(!this._transport)return void l(Error("Not connected"));(null==(c=this._options)?void 0:c.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),null==(u=null==a?void 0:a.signal)||u.throwIfAborted();let f=this._requestMessageId++,v={...e,jsonrpc:"2.0",id:f};(null==a?void 0:a.onprogress)&&(this._progressHandlers.set(f,a.onprogress),v.params={...e.params,_meta:{...(null==(h=e.params)?void 0:h._meta)||{},progressToken:f}});let g=e=>{var r;this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),null==(r=this._transport)||r.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(e)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))),l(e)};this._responseHandlers.set(f,e=>{var t;if(null==(t=null==a?void 0:a.signal)||!t.aborted){if(e instanceof Error)return l(e);try{let t=r.parse(e.result);n(t)}catch(e){l(e)}}}),null==(p=null==a?void 0:a.signal)||p.addEventListener("abort",()=>{var e;g(null==(e=null==a?void 0:a.signal)?void 0:e.reason)});let y=null!=(d=null==a?void 0:a.timeout)?d:6e4;this._setupTimeout(f,y,null==a?void 0:a.maxTotalTimeout,()=>g(new rO(t.RequestTimeout,"Request timed out",{timeout:y})),null!=(m=null==a?void 0:a.resetTimeoutOnProgress)&&m),this._transport.send(v,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(e=>{this._cleanupTimeout(f),l(e)})})}async notification(e,r){var t,a;if(!this._transport)throw Error("Not connected");if(this.assertNotificationCapability(e.method),(null!=(a=null==(t=this._options)?void 0:t.debouncedNotificationMethods)?a:[]).includes(e.method)&&!e.params&&!(null==r?void 0:r.relatedRequestId)){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{var t;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};null==(t=this._transport)||t.send(a,r).catch(e=>this._onerror(e))});return}let o={...e,jsonrpc:"2.0"};await this._transport.send(o,r)}setRequestHandler(e,r){let t=e.shape.method.value;this.assertRequestHandlerCapability(t),this._requestHandlers.set(t,(t,a)=>Promise.resolve(r(e.parse(t),a)))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){this._notificationHandlers.set(e.shape.method.value,t=>Promise.resolve(r(e.parse(t))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}}var rI=e.i(14510);class rA extends rx{constructor(e,r){var t;super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._capabilities=null!=(t=null==r?void 0:r.capabilities)?t:{},this._ajv=new rI.default}registerCapabilities(e){var r;if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=(r=this._capabilities,Object.entries(e).reduce((e,[r,t])=>(t&&"object"==typeof t?e[r]=e[r]?{...e[r],...t}:t:e[r]=t,e),{...r}))}assertCapability(e,r){var t;if(!(null==(t=this._serverCapabilities)?void 0:t[e]))throw Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),void 0===e.sessionId)try{let t=await this.request({method:"initialize",params:{protocolVersion:J,capabilities:this._capabilities,clientInfo:this._clientInfo}},eS,r);if(void 0===t)throw Error(`Server sent invalid initialize result: ${t}`);if(!Z.includes(t.protocolVersion))throw Error(`Server's protocol version is not supported: ${t.protocolVersion}`);this._serverCapabilities=t.capabilities,this._serverVersion=t.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(t.protocolVersion),this._instructions=t.instructions,await this.notification({method:"notifications/initialized"})}catch(e){throw this.close(),e}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){var r,t,a,o,s;switch(e){case"logging/setLevel":if(!(null==(r=this._serverCapabilities)?void 0:r.logging))throw Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!(null==(t=this._serverCapabilities)?void 0:t.prompts))throw Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!(null==(a=this._serverCapabilities)?void 0:a.resources))throw Error(`Server does not support resources (required for ${e})`);if("resources/subscribe"===e&&!this._serverCapabilities.resources.subscribe)throw Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!(null==(o=this._serverCapabilities)?void 0:o.tools))throw Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!(null==(s=this._serverCapabilities)?void 0:s.completions))throw Error(`Server does not support completions (required for ${e})`)}}assertNotificationCapability(e){var r;if("notifications/roots/list_changed"===e&&!(null==(r=this._capabilities.roots)?void 0:r.listChanged))throw Error(`Client does not support roots list changed notifications (required for ${e})`)}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw Error(`Client does not support roots capability (required for ${e})`)}}async ping(e){return this.request({method:"ping"},ev,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},rz,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},ev,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},e6,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},eY,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},eN,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},eq,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},eV,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},ev,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},ev,r)}async callTool(e,r=ra,a){let o=await this.request({method:"tools/call",params:e},r,a),s=this.getToolOutputValidator(e.name);if(s){if(!o.structuredContent&&!o.isError)throw new rO(t.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(o.structuredContent)try{if(!s(o.structuredContent))throw new rO(t.InvalidParams,`Structured content does not match the tool's output schema: ${this._ajv.errorsText(s.errors)}`)}catch(e){if(e instanceof rO)throw e;throw new rO(t.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)}}return o}cacheToolOutputSchemas(e){for(let r of(this._cachedToolOutputValidators.clear(),e))if(r.outputSchema)try{let e=this._ajv.compile(r.outputSchema);this._cachedToolOutputValidators.set(r.name,e)}catch(e){}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){let t=await this.request({method:"tools/list",params:e},rt,r);return this.cacheToolOutputSchemas(t.tools),t}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}async function rj(e){return(await r).getRandomValues(new Uint8Array(e))}async function rD(e){let r="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",t="",a=await rj(e);for(let o=0;o<e;o++){let e=a[o]%r.length;t+=r[e]}return t}async function r$(e){return await rD(e)}async function rF(e){return btoa(String.fromCharCode(...new Uint8Array(await (await r).subtle.digest("SHA-256",new TextEncoder().encode(e))))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function rk(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let r=await r$(e),t=await rF(r);return{code_verifier:r,code_challenge:t}}r=globalThis.crypto?.webcrypto??globalThis.crypto??e.A(70729).then(e=>e.webcrypto);let rU=W.z.string().url().superRefine((e,r)=>{if(!URL.canParse(e))return r.addIssue({code:W.z.ZodIssueCode.custom,message:"URL must be parseable",fatal:!0}),W.z.NEVER}).refine(e=>{let r=new URL(e);return"javascript:"!==r.protocol&&"data:"!==r.protocol&&"vbscript:"!==r.protocol},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),rL=W.z.object({resource:W.z.string().url(),authorization_servers:W.z.array(rU).optional(),jwks_uri:W.z.string().url().optional(),scopes_supported:W.z.array(W.z.string()).optional(),bearer_methods_supported:W.z.array(W.z.string()).optional(),resource_signing_alg_values_supported:W.z.array(W.z.string()).optional(),resource_name:W.z.string().optional(),resource_documentation:W.z.string().optional(),resource_policy_uri:W.z.string().url().optional(),resource_tos_uri:W.z.string().url().optional(),tls_client_certificate_bound_access_tokens:W.z.boolean().optional(),authorization_details_types_supported:W.z.array(W.z.string()).optional(),dpop_signing_alg_values_supported:W.z.array(W.z.string()).optional(),dpop_bound_access_tokens_required:W.z.boolean().optional()}).passthrough(),rN=W.z.object({issuer:W.z.string(),authorization_endpoint:rU,token_endpoint:rU,registration_endpoint:rU.optional(),scopes_supported:W.z.array(W.z.string()).optional(),response_types_supported:W.z.array(W.z.string()),response_modes_supported:W.z.array(W.z.string()).optional(),grant_types_supported:W.z.array(W.z.string()).optional(),token_endpoint_auth_methods_supported:W.z.array(W.z.string()).optional(),token_endpoint_auth_signing_alg_values_supported:W.z.array(W.z.string()).optional(),service_documentation:rU.optional(),revocation_endpoint:rU.optional(),revocation_endpoint_auth_methods_supported:W.z.array(W.z.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:W.z.array(W.z.string()).optional(),introspection_endpoint:W.z.string().optional(),introspection_endpoint_auth_methods_supported:W.z.array(W.z.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:W.z.array(W.z.string()).optional(),code_challenge_methods_supported:W.z.array(W.z.string()).optional()}).passthrough(),rM=W.z.object({issuer:W.z.string(),authorization_endpoint:rU,token_endpoint:rU,userinfo_endpoint:rU.optional(),jwks_uri:rU,registration_endpoint:rU.optional(),scopes_supported:W.z.array(W.z.string()).optional(),response_types_supported:W.z.array(W.z.string()),response_modes_supported:W.z.array(W.z.string()).optional(),grant_types_supported:W.z.array(W.z.string()).optional(),acr_values_supported:W.z.array(W.z.string()).optional(),subject_types_supported:W.z.array(W.z.string()),id_token_signing_alg_values_supported:W.z.array(W.z.string()),id_token_encryption_alg_values_supported:W.z.array(W.z.string()).optional(),id_token_encryption_enc_values_supported:W.z.array(W.z.string()).optional(),userinfo_signing_alg_values_supported:W.z.array(W.z.string()).optional(),userinfo_encryption_alg_values_supported:W.z.array(W.z.string()).optional(),userinfo_encryption_enc_values_supported:W.z.array(W.z.string()).optional(),request_object_signing_alg_values_supported:W.z.array(W.z.string()).optional(),request_object_encryption_alg_values_supported:W.z.array(W.z.string()).optional(),request_object_encryption_enc_values_supported:W.z.array(W.z.string()).optional(),token_endpoint_auth_methods_supported:W.z.array(W.z.string()).optional(),token_endpoint_auth_signing_alg_values_supported:W.z.array(W.z.string()).optional(),display_values_supported:W.z.array(W.z.string()).optional(),claim_types_supported:W.z.array(W.z.string()).optional(),claims_supported:W.z.array(W.z.string()).optional(),service_documentation:W.z.string().optional(),claims_locales_supported:W.z.array(W.z.string()).optional(),ui_locales_supported:W.z.array(W.z.string()).optional(),claims_parameter_supported:W.z.boolean().optional(),request_parameter_supported:W.z.boolean().optional(),request_uri_parameter_supported:W.z.boolean().optional(),require_request_uri_registration:W.z.boolean().optional(),op_policy_uri:rU.optional(),op_tos_uri:rU.optional()}).passthrough().merge(rN.pick({code_challenge_methods_supported:!0})),rq=W.z.object({access_token:W.z.string(),id_token:W.z.string().optional(),token_type:W.z.string(),expires_in:W.z.number().optional(),scope:W.z.string().optional(),refresh_token:W.z.string().optional()}).strip(),rH=W.z.object({error:W.z.string(),error_description:W.z.string().optional(),error_uri:W.z.string().optional()}),rV=rU.optional().or(W.z.literal("").transform(()=>void 0)),rQ=W.z.object({redirect_uris:W.z.array(rU),token_endpoint_auth_method:W.z.string().optional(),grant_types:W.z.array(W.z.string()).optional(),response_types:W.z.array(W.z.string()).optional(),client_name:W.z.string().optional(),client_uri:rU.optional(),logo_uri:rV,scope:W.z.string().optional(),contacts:W.z.array(W.z.string()).optional(),tos_uri:rV,policy_uri:W.z.string().optional(),jwks_uri:rU.optional(),jwks:W.z.any().optional(),software_id:W.z.string().optional(),software_version:W.z.string().optional(),software_statement:W.z.string().optional()}).strip(),rG=W.z.object({client_id:W.z.string(),client_secret:W.z.string().optional(),client_id_issued_at:W.z.number().optional(),client_secret_expires_at:W.z.number().optional()}).strip(),rB=rQ.merge(rG);W.z.object({error:W.z.string(),error_description:W.z.string().optional()}).strip(),W.z.object({token:W.z.string(),token_type_hint:W.z.string().optional()}).strip();class rK extends Error{constructor(e,r){super(e),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}}class rW extends rK{}rW.errorCode="invalid_request";class rJ extends rK{}rJ.errorCode="invalid_client";class rZ extends rK{}rZ.errorCode="invalid_grant";class rY extends rK{}rY.errorCode="unauthorized_client";class rX extends rK{}rX.errorCode="unsupported_grant_type";class r0 extends rK{}r0.errorCode="invalid_scope";class r1 extends rK{}r1.errorCode="access_denied";class r2 extends rK{}r2.errorCode="server_error";class r9 extends rK{}r9.errorCode="temporarily_unavailable";class r4 extends rK{}r4.errorCode="unsupported_response_type";class r3 extends rK{}r3.errorCode="unsupported_token_type";class r5 extends rK{}r5.errorCode="invalid_token";class r6 extends rK{}r6.errorCode="method_not_allowed";class r7 extends rK{}r7.errorCode="too_many_requests";class r8 extends rK{}r8.errorCode="invalid_client_metadata";class te extends rK{}te.errorCode="insufficient_scope";let tr={[rW.errorCode]:rW,[rJ.errorCode]:rJ,[rZ.errorCode]:rZ,[rY.errorCode]:rY,[rX.errorCode]:rX,[r0.errorCode]:r0,[r1.errorCode]:r1,[r2.errorCode]:r2,[r9.errorCode]:r9,[r4.errorCode]:r4,[r3.errorCode]:r3,[r5.errorCode]:r5,[r6.errorCode]:r6,[r7.errorCode]:r7,[r8.errorCode]:r8,[te.errorCode]:te};class tt extends Error{constructor(e){super(null!=e?e:"Unauthorized")}}let ta="code",to="S256";function ts(e,r){let t=void 0!==e.client_secret;return 0===r.length?t?"client_secret_post":"none":t&&r.includes("client_secret_basic")?"client_secret_basic":t&&r.includes("client_secret_post")?"client_secret_post":r.includes("none")?"none":t?"client_secret_post":"none"}function ti(e,r,t,a){let{client_id:o,client_secret:s}=r;switch(e){case"client_secret_basic":var i,n,l,c,u=o,h=s,p=t;if(!h)throw Error("client_secret_basic authentication requires a client_secret");let d=btoa(`${u}:${h}`);p.set("Authorization",`Basic ${d}`);return;case"client_secret_post":i=o,n=s,(l=a).set("client_id",i),n&&l.set("client_secret",n);return;case"none":c=o,a.set("client_id",c);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}async function tn(e){let r=e instanceof Response?e.status:void 0,t=e instanceof Response?await e.text():e;try{let{error:e,error_description:r,error_uri:a}=rH.parse(JSON.parse(t));return new(tr[e]||r2)(r||"",a)}catch(e){return new r2(`${r?`HTTP ${r}: `:""}Invalid OAuth error response: ${e}. Raw body: ${t}`)}}async function tl(e,r){var t,a;try{return await tc(e,r)}catch(o){if(o instanceof rJ||o instanceof rY)return await (null==(t=e.invalidateCredentials)?void 0:t.call(e,"all")),await tc(e,r);if(o instanceof rZ)return await (null==(a=e.invalidateCredentials)?void 0:a.call(e,"tokens")),await tc(e,r);throw o}}async function tc(e,{serverUrl:r,authorizationCode:t,scope:a,resourceMetadataUrl:o,fetchFn:s}){let i,n;try{(i=await tp(r,{resourceMetadataUrl:o},s)).authorization_servers&&i.authorization_servers.length>0&&(n=i.authorization_servers[0])}catch(e){}n||(n=r);let l=await tu(r,e,i),c=await tv(n,{fetchFn:s}),u=await Promise.resolve(e.clientInformation());if(!u){if(void 0!==t)throw Error("Existing OAuth client information is required when exchanging an authorization code");if(!e.saveClientInformation)throw Error("OAuth client information must be saveable for dynamic registration");let r=await tE(n,{metadata:c,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(r),u=r}if(void 0!==t){let r=await e.codeVerifier(),a=await ty(n,{metadata:c,clientInformation:u,authorizationCode:t,codeVerifier:r,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(a),"AUTHORIZED"}let h=await e.tokens();if(null==h?void 0:h.refresh_token)try{let r=await t_(n,{metadata:c,clientInformation:u,refreshToken:h.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(r),"AUTHORIZED"}catch(e){if(!(e instanceof rK)||e instanceof r2);else throw e}let p=e.state?await e.state():void 0,{authorizationUrl:d,codeVerifier:m}=await tg(n,{metadata:c,clientInformation:u,state:p,redirectUrl:e.redirectUrl,scope:a||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(m),await e.redirectToAuthorization(d),"REDIRECT"}async function tu(e,r,t){let a=function(e){let r=new URL("string"==typeof e?e:e.href);return r.hash="",r}(e);if(r.validateResourceURL)return await r.validateResourceURL(a,null==t?void 0:t.resource);if(t){if(!function({requestedResource:e,configuredResource:r}){let t=new URL("string"==typeof e?e:e.href),a=new URL("string"==typeof r?r:r.href);if(t.origin!==a.origin||t.pathname.length<a.pathname.length)return!1;let o=t.pathname.endsWith("/")?t.pathname:t.pathname+"/",s=a.pathname.endsWith("/")?a.pathname:a.pathname+"/";return o.startsWith(s)}({requestedResource:a,configuredResource:t.resource}))throw Error(`Protected resource ${t.resource} does not match expected ${a} (or origin)`);return new URL(t.resource)}}function th(e){let r=e.headers.get("WWW-Authenticate");if(!r)return;let[t,a]=r.split(" ");if("bearer"!==t.toLowerCase()||!a)return;let o=/resource_metadata="([^"]*)"/.exec(r);if(o)try{return new URL(o[1])}catch(e){return}}async function tp(e,r,t=fetch){let a=await tf(e,"oauth-protected-resource",t,{protocolVersion:null==r?void 0:r.protocolVersion,metadataUrl:null==r?void 0:r.resourceMetadataUrl});if(!a||404===a.status)throw Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!a.ok)throw Error(`HTTP ${a.status} trying to load well-known OAuth protected resource metadata.`);return rL.parse(await a.json())}async function td(e,r,t=fetch){try{return await t(e,{headers:r})}catch(a){if(a instanceof TypeError)if(r)return td(e,void 0,t);else return;throw a}}async function tm(e,r,t=fetch){return await td(e,{"MCP-Protocol-Version":r},t)}async function tf(e,r,t,a){var o,s,i,n;let l,c=new URL(e),u=null!=(o=null==a?void 0:a.protocolVersion)?o:J;(null==a?void 0:a.metadataUrl)?l=new URL(a.metadataUrl):(l=new URL(function(e,r="",t={}){return r.endsWith("/")&&(r=r.slice(0,-1)),t.prependPathname?`${r}/.well-known/${e}`:`/.well-known/${e}${r}`}(r,c.pathname),null!=(s=null==a?void 0:a.metadataServerUrl)?s:c)).search=c.search;let h=await tm(l,u,t);if(!(null==a?void 0:a.metadataUrl)&&(i=h,n=c.pathname,!i||i.status>=400&&i.status<500&&"/"!==n)){let e=new URL(`/.well-known/${r}`,c);h=await tm(e,u,t)}return h}async function tv(e,{fetchFn:r=fetch,protocolVersion:t=J}={}){let a={"MCP-Protocol-Version":t,Accept:"application/json"};for(let{url:t,type:o}of function(e){let r="string"==typeof e?new URL(e):e,t="/"!==r.pathname,a=[];if(!t)return a.push({url:new URL("/.well-known/oauth-authorization-server",r.origin),type:"oauth"}),a.push({url:new URL("/.well-known/openid-configuration",r.origin),type:"oidc"}),a;let o=r.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),a.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,r.origin),type:"oauth"}),a.push({url:new URL("/.well-known/oauth-authorization-server",r.origin),type:"oauth"}),a.push({url:new URL(`/.well-known/openid-configuration${o}`,r.origin),type:"oidc"}),a.push({url:new URL(`${o}/.well-known/openid-configuration`,r.origin),type:"oidc"}),a}(e)){let e=await td(t,a,r);if(e){if(!e.ok){if(e.status>=400&&e.status<500)continue;throw Error(`HTTP ${e.status} trying to load ${"oauth"===o?"OAuth":"OpenID provider"} metadata from ${t}`)}if("oauth"===o)return rN.parse(await e.json());return rM.parse(await e.json())}}}async function tg(e,{metadata:r,clientInformation:t,redirectUrl:a,scope:o,state:s,resource:i}){let n;if(r){if(n=new URL(r.authorization_endpoint),!r.response_types_supported.includes(ta))throw Error(`Incompatible auth server: does not support response type ${ta}`);if(r.code_challenge_methods_supported&&!r.code_challenge_methods_supported.includes(to))throw Error(`Incompatible auth server: does not support code challenge method ${to}`)}else n=new URL("/authorize",e);let l=await rk(),c=l.code_verifier,u=l.code_challenge;return n.searchParams.set("response_type",ta),n.searchParams.set("client_id",t.client_id),n.searchParams.set("code_challenge",u),n.searchParams.set("code_challenge_method",to),n.searchParams.set("redirect_uri",String(a)),s&&n.searchParams.set("state",s),o&&n.searchParams.set("scope",o),(null==o?void 0:o.includes("offline_access"))&&n.searchParams.append("prompt","consent"),i&&n.searchParams.set("resource",i.href),{authorizationUrl:n,codeVerifier:c}}async function ty(e,{metadata:r,clientInformation:t,authorizationCode:a,codeVerifier:o,redirectUri:s,resource:i,addClientAuthentication:n,fetchFn:l}){var c;let u="authorization_code",h=(null==r?void 0:r.token_endpoint)?new URL(r.token_endpoint):new URL("/token",e);if((null==r?void 0:r.grant_types_supported)&&!r.grant_types_supported.includes(u))throw Error(`Incompatible auth server: does not support grant type ${u}`);let p=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),d=new URLSearchParams({grant_type:u,code:a,code_verifier:o,redirect_uri:String(s)});n?n(p,d,e,r):ti(ts(t,null!=(c=null==r?void 0:r.token_endpoint_auth_methods_supported)?c:[]),t,p,d),i&&d.set("resource",i.href);let m=await (null!=l?l:fetch)(h,{method:"POST",headers:p,body:d});if(!m.ok)throw await tn(m);return rq.parse(await m.json())}async function t_(e,{metadata:r,clientInformation:t,refreshToken:a,resource:o,addClientAuthentication:s,fetchFn:i}){var n;let l,c="refresh_token";if(r){if(l=new URL(r.token_endpoint),r.grant_types_supported&&!r.grant_types_supported.includes(c))throw Error(`Incompatible auth server: does not support grant type ${c}`)}else l=new URL("/token",e);let u=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),h=new URLSearchParams({grant_type:c,refresh_token:a});s?s(u,h,e,r):ti(ts(t,null!=(n=null==r?void 0:r.token_endpoint_auth_methods_supported)?n:[]),t,u,h),o&&h.set("resource",o.href);let p=await (null!=i?i:fetch)(l,{method:"POST",headers:u,body:h});if(!p.ok)throw await tn(p);return rq.parse({refresh_token:a,...await p.json()})}async function tE(e,{metadata:r,clientMetadata:t,fetchFn:a}){let o;if(r){if(!r.registration_endpoint)throw Error("Incompatible auth server: does not support dynamic client registration");o=new URL(r.registration_endpoint)}else o=new URL("/register",e);let s=await (null!=a?a:fetch)(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok)throw await tn(s);return rB.parse(await s.json())}class tP extends Error{constructor(e,r,t){super(`SSE error: ${r}`),this.code=e,this.event=t}}class tb{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._eventSourceInit=null==r?void 0:r.eventSourceInit,this._requestInit=null==r?void 0:r.requestInit,this._authProvider=null==r?void 0:r.authProvider,this._fetch=null==r?void 0:r.fetch}async _authThenStart(){var e;let r;if(!this._authProvider)throw new tt("No auth provider");try{r=await tl(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(r){throw null==(e=this.onerror)||e.call(this,r),r}if("AUTHORIZED"!==r)throw new tt;return await this._startOrAuth()}async _commonHeaders(){var e;let r={};if(this._authProvider){let e=await this._authProvider.tokens();e&&(r.Authorization=`Bearer ${e.access_token}`)}return this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion),new Headers({...r,...null==(e=this._requestInit)?void 0:e.headers})}_startOrAuth(){var e,r,t;let a=null!=(t=null!=(r=null==(e=this===null||void 0===this?void 0:this._eventSourceInit)?void 0:e.fetch)?r:this._fetch)?t:fetch;return new Promise((e,r)=>{this._eventSource=new K(this._url.href,{...this._eventSourceInit,fetch:async(e,r)=>{let t=await this._commonHeaders();t.set("Accept","text/event-stream");let o=await a(e,{...r,headers:t});return 401===o.status&&o.headers.has("www-authenticate")&&(this._resourceMetadataUrl=th(o)),o}}),this._abortController=new AbortController,this._eventSource.onerror=t=>{var a;if(401===t.code&&this._authProvider)return void this._authThenStart().then(e,r);let o=new tP(t.code,t.message,t);r(o),null==(a=this.onerror)||a.call(this,o)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",t=>{var a;try{if(this._endpoint=new URL(t.data,this._url),this._endpoint.origin!==this._url.origin)throw Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(e){r(e),null==(a=this.onerror)||a.call(this,e),this.close();return}e()}),this._eventSource.onmessage=e=>{var r,t;let a;try{a=ef.parse(JSON.parse(e.data))}catch(e){null==(r=this.onerror)||r.call(this,e);return}null==(t=this.onmessage)||t.call(this,a)}})}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(e){if(!this._authProvider)throw new tt("No auth provider");if("AUTHORIZED"!==await tl(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch}))throw new tt("Failed to authorize")}async close(){var e,r,t;null==(e=this._abortController)||e.abort(),null==(r=this._eventSource)||r.close(),null==(t=this.onclose)||t.call(this)}async send(e){var r,t,a;if(!this._endpoint)throw Error("Not connected");try{let a=await this._commonHeaders();a.set("content-type","application/json");let o={...this._requestInit,method:"POST",headers:a,body:JSON.stringify(e),signal:null==(r=this._abortController)?void 0:r.signal},s=await (null!=(t=this._fetch)?t:fetch)(this._endpoint,o);if(!s.ok){if(401===s.status&&this._authProvider){this._resourceMetadataUrl=th(s);let r=await tl(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch});if("AUTHORIZED"!==r)throw new tt;return this.send(e)}let r=await s.text().catch(()=>null);throw Error(`Error POSTing to endpoint (HTTP ${s.status}): ${r}`)}}catch(e){throw null==(a=this.onerror)||a.call(this,e),e}}setProtocolVersion(e){this._protocolVersion=e}}class tw extends TransformStream{constructor({onError:e,onRetry:r,onComment:t}={}){let a;super({start(o){a=v({onEvent:e=>{o.enqueue(e)},onError(r){"terminate"===e?o.error(r):"function"==typeof e&&e(r)},onRetry:r,onComment:t})},transform(e){a.feed(e)}})}}let tz={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class tS extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}}class tR{constructor(e,r){var t;this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=null==r?void 0:r.requestInit,this._authProvider=null==r?void 0:r.authProvider,this._fetch=null==r?void 0:r.fetch,this._sessionId=null==r?void 0:r.sessionId,this._reconnectionOptions=null!=(t=null==r?void 0:r.reconnectionOptions)?t:tz}async _authThenStart(){var e;let r;if(!this._authProvider)throw new tt("No auth provider");try{r=await tl(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(r){throw null==(e=this.onerror)||e.call(this,r),r}if("AUTHORIZED"!==r)throw new tt;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let r={};if(this._authProvider){let e=await this._authProvider.tokens();e&&(r.Authorization=`Bearer ${e.access_token}`)}this._sessionId&&(r["mcp-session-id"]=this._sessionId),this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);let t=this._normalizeHeaders(null==(e=this._requestInit)?void 0:e.headers);return new Headers({...r,...t})}async _startOrAuthSse(e){var r,t,a;let{resumptionToken:o}=e;try{let a=await this._commonHeaders();a.set("Accept","text/event-stream"),o&&a.set("last-event-id",o);let s=await (null!=(r=this._fetch)?r:fetch)(this._url,{method:"GET",headers:a,signal:null==(t=this._abortController)?void 0:t.signal});if(!s.ok){if(401===s.status&&this._authProvider)return await this._authThenStart();if(405===s.status)return;throw new tS(s.status,`Failed to open SSE stream: ${s.statusText}`)}this._handleSseStream(s.body,e,!0)}catch(e){throw null==(a=this.onerror)||a.call(this,e),e}}_getNextReconnectionDelay(e){let r=this._reconnectionOptions.initialReconnectionDelay;return Math.min(r*Math.pow(this._reconnectionOptions.reconnectionDelayGrowFactor,e),this._reconnectionOptions.maxReconnectionDelay)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,r=0){var t;let a=this._reconnectionOptions.maxRetries;if(a>0&&r>=a){null==(t=this.onerror)||t.call(this,Error(`Maximum reconnection attempts (${a}) exceeded.`));return}setTimeout(()=>{this._startOrAuthSse(e).catch(t=>{var a;null==(a=this.onerror)||a.call(this,Error(`Failed to reconnect SSE stream: ${t instanceof Error?t.message:String(t)}`)),this._scheduleReconnection(e,r+1)})},this._getNextReconnectionDelay(r))}_handleSseStream(e,r,t){let a;if(!e)return;let{onresumptiontoken:o,replayMessageId:s}=r;(async()=>{var r,i,n,l;try{let t=e.pipeThrough(new TextDecoderStream).pipeThrough(new tw).getReader();for(;;){let{value:e,done:n}=await t.read();if(n)break;if(e.id&&(a=e.id,null==o||o(e.id)),!e.event||"message"===e.event)try{let t=ef.parse(JSON.parse(e.data));void 0!==s&&ep(t)&&(t.id=s),null==(r=this.onmessage)||r.call(this,t)}catch(e){null==(i=this.onerror)||i.call(this,e)}}}catch(e){if(null==(n=this.onerror)||n.call(this,Error(`SSE stream disconnected: ${e}`)),t&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:o,replayMessageId:s},0)}catch(e){null==(l=this.onerror)||l.call(this,Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`))}}})()}async start(){if(this._abortController)throw Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new tt("No auth provider");if("AUTHORIZED"!==await tl(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch}))throw new tt("Failed to authorize")}async close(){var e,r;null==(e=this._abortController)||e.abort(),null==(r=this.onclose)||r.call(this)}async send(e,r){var t,a,o,s;try{let{resumptionToken:s,onresumptiontoken:i}=r||{};if(s)return void this._startOrAuthSse({resumptionToken:s,replayMessageId:el(e)?e.id:void 0}).catch(e=>{var r;return null==(r=this.onerror)?void 0:r.call(this,e)});let n=await this._commonHeaders();n.set("content-type","application/json"),n.set("accept","application/json, text/event-stream");let l={...this._requestInit,method:"POST",headers:n,body:JSON.stringify(e),signal:null==(t=this._abortController)?void 0:t.signal},c=await (null!=(a=this._fetch)?a:fetch)(this._url,l),u=c.headers.get("mcp-session-id");if(u&&(this._sessionId=u),!c.ok){if(401===c.status&&this._authProvider){if(this._hasCompletedAuthFlow)throw new tS(401,"Server returned 401 after successful authentication");this._resourceMetadataUrl=th(c);let r=await tl(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch});if("AUTHORIZED"!==r)throw new tt;return this._hasCompletedAuthFlow=!0,this.send(e)}let r=await c.text().catch(()=>null);throw Error(`Error POSTing to endpoint (HTTP ${c.status}): ${r}`)}if(this._hasCompletedAuthFlow=!1,202===c.status){eT(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>{var r;return null==(r=this.onerror)?void 0:r.call(this,e)});return}let h=(Array.isArray(e)?e:[e]).filter(e=>"method"in e&&"id"in e&&void 0!==e.id).length>0,p=c.headers.get("content-type");if(h)if(null==p?void 0:p.includes("text/event-stream"))this._handleSseStream(c.body,{onresumptiontoken:i},!1);else if(null==p?void 0:p.includes("application/json")){let e=await c.json();for(let r of Array.isArray(e)?e.map(e=>ef.parse(e)):[ef.parse(e)])null==(o=this.onmessage)||o.call(this,r)}else throw new tS(-1,`Unexpected content type: ${p}`)}catch(e){throw null==(s=this.onerror)||s.call(this,e),e}}get sessionId(){return this._sessionId}async terminateSession(){var e,r,t;if(this._sessionId)try{let t=await this._commonHeaders(),a={...this._requestInit,method:"DELETE",headers:t,signal:null==(e=this._abortController)?void 0:e.signal},o=await (null!=(r=this._fetch)?r:fetch)(this._url,a);if(!o.ok&&405!==o.status)throw new tS(o.status,`Failed to terminate session: ${o.statusText}`);this._sessionId=void 0}catch(e){throw null==(t=this.onerror)||t.call(this,e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}}let tT=e=>{if(!e||0===e.length)return"";let r=e.toLowerCase();return r.substring(0,1).toUpperCase()+r.substring(1,r.length)};e.s(["interpolateFunctionValue",()=>tC],43488);let tC=({value:e,args:r,thread:t,assistant:a})=>{let o=[];return{value:(e||"").replace(/{{\s*([\w-]+)\s*}}/g,(e,s)=>r&&s in r?String(r[s]):s in(t.metadata||{})?String(t.metadata[s]):"threadId"===s?t.id:"assistantId"===s?a.id:(o.push(s),`{{${s}}}`)),missing:o}};e.s(["createLog",()=>tx],18527);var tO=e.i(45076);let tx=({log:e,prisma:r})=>(0,tO.waitUntil)(new Promise(async t=>{console.log("Logging error."),await r.log.create({data:e}),console.log("Successfully logged error."),t(!0)})),tI=({thread:e,mcpServer:r,assistant:t,prisma:o})=>{let{headers:s,missing:i}=(({mcpServer:e,thread:r,metadata:t,assistant:o})=>{let s={},i=[];for(let[n,l]of Object.entries((({mcpServer:e})=>e.transportType===a.TransportType.HTTP?e.httpTransport.headers:e.transportType===a.TransportType.SSE?e.sseTransport.headers:{})({mcpServer:e}))){let e=tC({value:l,args:t,thread:r,assistant:o});s[n]=e.value,i.push(...e.missing)}return{headers:s,missing:i}})({mcpServer:r,thread:e,metadata:e.metadata??{},assistant:t});if(i.length){let r=`Missing variables in MCP server: ${i.join(", ")}`;throw tx({log:{requestMethod:a.LogRequestMethod.POST,requestRoute:a.LogRequestRoute.MESSAGES,level:a.LogLevel.ERROR,status:400,message:r,workspaceId:t.workspaceId,assistantId:t.id,threadId:e.id},prisma:o}),Error(r)}return Object.fromEntries(Object.entries({...s,...e.metadata??{}}).map(([e,r])=>[(e=>{let r=e?.replace(/([A-Z])+/g,tT)?.split(/(?=[A-Z])|[\.\-\s_]/).map(e=>e.toLowerCase())??[];return 0===r.length?"":1===r.length?r[0]:r.reduce((e,r)=>`${e}-${r.toLowerCase()}`)})(e),r]))},tA=({thread:e,mcpServer:r,assistant:t,prisma:o})=>{let{url:s,missing:i}=(({mcpServer:e,thread:r,metadata:t,assistant:o})=>{let{value:s,missing:i}=tC({value:(({mcpServer:e})=>e.transportType===a.TransportType.HTTP?e.httpTransport.url:e.transportType===a.TransportType.SSE?e.sseTransport.url:"")({mcpServer:e}),args:t,thread:r,assistant:o});return{url:s,missing:i}})({mcpServer:r,thread:e,metadata:e.metadata??{},assistant:t});if(i.length){let r=`Missing variables in MCP server: ${i.join(", ")}`;throw tx({log:{requestMethod:a.LogRequestMethod.POST,requestRoute:a.LogRequestRoute.MESSAGES,level:a.LogLevel.ERROR,status:400,message:r,workspaceId:t.workspaceId,assistantId:t.id,threadId:e.id},prisma:o}),Error(r)}return s};e.g.EventSource=K;let tj=async({mcpServer:e,thread:r,assistant:t,prisma:o})=>{let s=new rA({name:"superinterface-mcp-client",version:"1.0.0"},{capabilities:{}}),i=(({mcpServer:e,thread:r,assistant:t,prisma:o})=>{if(e.transportType===a.TransportType.STDIO)throw Error("STDIO transport is not supported.");if(e.transportType===a.TransportType.HTTP){let a=tI({thread:r,mcpServer:e,assistant:t,prisma:o});return new tR(new URL(tA({thread:r,mcpServer:e,assistant:t,prisma:o})),{requestInit:{headers:a}})}if(e.transportType===a.TransportType.SSE){let a=tA({thread:r,mcpServer:e,assistant:t,prisma:o}),s=tI({thread:r,mcpServer:e,assistant:t,prisma:o});return new tb(new URL(a),{eventSourceInit:{fetch:(({headers:e})=>(r,t)=>{let a=new Headers({...t?.headers??{},...e});return fetch(r.toString(),{...t,headers:a})})({headers:s})},requestInit:{headers:s}})}throw Error(`Unknown transport type ${e.transportType}`)})({mcpServer:e,thread:r,assistant:t,prisma:o});return await s.connect(i),{mcpConnection:{client:s,transport:i}}};e.s(["closeMcpConnection",()=>tD],10273);let tD=async({mcpConnection:e})=>{await e.client.close(),await e.transport.close()};var t$=e.i(45027);let tF=async({assistant:e,thread:r,prisma:t})=>{let a=e.mcpServers.filter(e=>!e.computerUseTool);if((0,n.isResponsesStorageProvider)({storageProviderType:e.storageProviderType})&&!e.modelSlug.match("computer-use"))return a.map(a=>({type:"mcp",mcp:{server_label:(0,t$.getMcpServerLabel)({id:a.id,name:a.name}),...a.description?{server_description:a.description}:{},server_url:tA({thread:r,mcpServer:a,assistant:e,prisma:t}),headers:tI({thread:r,mcpServer:a,assistant:e,prisma:t}),require_approval:"never"}}));let o=await (({mcpServers:e,thread:r,assistant:t,prisma:a})=>Promise.all(e.map(async e=>{let{mcpConnection:o}=await tj({mcpServer:e,thread:r,assistant:t,prisma:a}),s=await o.client.listTools();return await tD({mcpConnection:o}),s.tools.map(e=>({type:"function",function:(({tool:e})=>({name:e.name,description:e.description,parameters:e.inputSchema}))({tool:e})}))})))({mcpServers:a,thread:r,assistant:e,prisma:t});return(0,p.flat)(o)},tk=async({assistant:e,thread:r,prisma:t})=>{let o=d.find(r=>r.type===e.modelProvider.type);return o&&o.isFunctionCallingAvailable?{tools:[...await tF({assistant:e,thread:r,prisma:t}),...e.functions.map(e=>({type:"function",function:e.openapiSpec})),...(({assistant:e})=>e.tools.map(r=>{if(r.type===a.ToolType.FILE_SEARCH){if(i({storageProviderType:e.storageProviderType})||c({storageProviderType:e.storageProviderType}))return{type:"file_search"};if((0,n.isResponsesStorageProvider)({storageProviderType:e.storageProviderType}))return{type:"file_search",file_search:{vector_store_ids:r.fileSearchTool.vectorStoreIds,max_num_results:r.fileSearchTool.maxNumResults}}}else if(r.type===a.ToolType.CODE_INTERPRETER){if(i({storageProviderType:e.storageProviderType})||c({storageProviderType:e.storageProviderType}))return{type:"code_interpreter"};if((0,n.isResponsesStorageProvider)({storageProviderType:e.storageProviderType}))return{type:"code_interpreter",code_interpreter:{container:{type:"auto"}}};if(e.modelProvider.type===a.ModelProviderType.ANTHROPIC)return{type:"code_execution_20250825",code_execution_20250825:{name:"code_execution"}}}else if(r.type===a.ToolType.IMAGE_GENERATION){if((0,n.isResponsesStorageProvider)({storageProviderType:e.storageProviderType}))return{type:"image_generation",image_generation:{model:r.imageGenerationTool.model,background:r.imageGenerationTool.background.toLowerCase(),quality:r.imageGenerationTool.quality.toLowerCase(),output_format:r.imageGenerationTool.outputFormat.toLowerCase(),size:(({tool:e})=>e.imageGenerationTool.size===a.ImageGenerationToolSize.AUTO?"auto":e.imageGenerationTool.size===a.ImageGenerationToolSize.SIZE_1024_1024?"1024x1024":e.imageGenerationTool.size===a.ImageGenerationToolSize.SIZE_1024_1536?"1024x1536":e.imageGenerationTool.size===a.ImageGenerationToolSize.SIZE_1536_1024?"1536x1024":void 0)({tool:r}),partial_images:r.imageGenerationTool.partialImages}}}else if(r.type===a.ToolType.WEB_SEARCH){if((0,n.isResponsesStorageProvider)({storageProviderType:e.storageProviderType}))return{type:"web_search"};if(e.modelProvider.type===a.ModelProviderType.ANTHROPIC)return{type:"web_search_20250305",web_search_20250305:{name:"web_search"}}}else if(r.type===a.ToolType.COMPUTER_USE){if(!r.computerUseTool.mcpServerId)return null;if((0,n.isResponsesStorageProvider)({storageProviderType:e.storageProviderType}))return{type:"computer_use_preview",computer_use_preview:{environment:r.computerUseTool.environment.toLowerCase(),display_width:r.computerUseTool.displayWidth,display_height:r.computerUseTool.displayHeight}};if(e.modelProvider.type===a.ModelProviderType.ANTHROPIC)return{type:"computer_20250124",computer_20250124:{name:"computer",display_width_px:r.computerUseTool.displayWidth,display_height_px:r.computerUseTool.displayHeight}}}return null}).filter(Boolean))({assistant:e})]}:{}};var tU=e.i(92859);let tL=({assistant:e,prisma:r,thread:t=null})=>(0,o.supercompat)({client:(0,u.clientAdapter)({modelProvider:e.modelProvider,storageProviderType:e.storageProviderType}),storage:(({assistant:e,prisma:r})=>{if(e.storageProviderType===a.StorageProviderType.SUPERINTERFACE_CLOUD)return(0,o.prismaStorageAdapter)({prisma:r});if(!i({storageProviderType:e.storageProviderType})){if(e.storageProviderType===a.StorageProviderType.AZURE_OPENAI_RESPONSES)return(0,o.azureResponsesStorageAdapter)();if((0,n.isResponsesStorageProvider)({storageProviderType:e.storageProviderType}))return(0,o.responsesStorageAdapter)();if(c({storageProviderType:e.storageProviderType})){let t=(0,tU.getAzureAiProjectClient)({modelProvider:e.modelProvider,storageProviderType:e.storageProviderType});return(0,o.azureAgentsStorageAdapter)({azureAiProject:t,prisma:r})}throw Error(`Invalid storage provider type: ${e.storageProviderType}`)}})({assistant:e,prisma:r}),runAdapter:(({assistant:e,thread:r,prisma:t})=>{if(e.storageProviderType===a.StorageProviderType.SUPERINTERFACE_CLOUD)return(0,o.completionsRunAdapter)();if(!i({storageProviderType:e.storageProviderType})){if((0,n.isResponsesStorageProvider)({storageProviderType:e.storageProviderType}))return(0,o.responsesRunAdapter)({getOpenaiAssistant:(({assistant:e,thread:r,prisma:t})=>async({select:{id:o=!1}={}}={})=>({id:o}).id?{id:e.id}:{id:e.id,object:"assistant",created_at:(0,h.default)().unix(),model:e.modelSlug,name:e.name,instructions:e.instructions,description:null,tools:r?(await tk({assistant:e,thread:r,prisma:t}))?.tools??[]:[],metadata:{},top_p:1,temperature:1,response_format:{type:"text"},truncation_strategy:(({assistant:e})=>e.truncationType===a.TruncationType.LAST_MESSAGES?{type:"last_messages",last_messages:e.truncationLastMessagesCount}:e.truncationType===a.TruncationType.DISABLED?{type:"disabled"}:{type:"auto"})({assistant:e})})({assistant:e,thread:r,prisma:t}),waitUntil:tO.waitUntil});if(c({storageProviderType:e.storageProviderType})){let r=(0,tU.getAzureAiProjectClient)({modelProvider:e.modelProvider,storageProviderType:e.storageProviderType});return(0,o.azureAgentsRunAdapter)({azureAiProject:r})}throw Error(`Invalid storage provider type: ${e.storageProviderType}`)}})({assistant:e,thread:t,prisma:r})})}];
|
|
5
|
+
`&&a++}}return[r,t]}(`${s}${r}`);for(let e of t)u(e);s=a,i=!1},reset:function(e={}){s&&e.consume&&u(s),i=!0,n=void 0,l="",c="",s=""}}}class g extends Event{constructor(e,r){var t,a;super(e),this.code=null!=(t=null==r?void 0:r.code)?t:void 0,this.message=null!=(a=null==r?void 0:r.message)?a:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,t){return t(y(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(y(this),r)}}function y(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var _,E,P,b,w,z,S,R,T,C,O,x,I,A,j,D,$,F,k,U,L,N,M,q=e=>{throw TypeError(e)},H=(e,r,t)=>r.has(e)||q("Cannot "+t),V=(e,r,t)=>(H(e,r,"read from private field"),t?t.call(e):r.get(e)),Q=(e,r,t)=>r.has(e)?q("Cannot add the same private member more than once"):r instanceof WeakSet?r.add(e):r.set(e,t),G=(e,r,t,a)=>(H(e,r,"write to private field"),r.set(e,t),t),B=(e,r,t)=>(H(e,r,"access private method"),t);class K extends EventTarget{constructor(e,r){var t,a;super(),Q(this,A),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Q(this,_),Q(this,E),Q(this,P),Q(this,b),Q(this,w),Q(this,z),Q(this,S),Q(this,R,null),Q(this,T),Q(this,C),Q(this,O,null),Q(this,x,null),Q(this,I,null),Q(this,D,async e=>{var r;V(this,C).reset();let{body:t,redirected:a,status:o,headers:s}=e;if(204===o){B(this,A,L).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(a?G(this,P,new URL(e.url)):G(this,P,void 0),200!==o)return void B(this,A,L).call(this,`Non-200 status code (${o})`,o);if(!(s.get("content-type")||"").startsWith("text/event-stream"))return void B(this,A,L).call(this,'Invalid content type, expected "text/event-stream"',o);if(V(this,_)===this.CLOSED)return;G(this,_,this.OPEN);let i=new Event("open");if(null==(r=V(this,I))||r.call(this,i),this.dispatchEvent(i),"object"!=typeof t||!t||!("getReader"in t)){B(this,A,L).call(this,"Invalid response body, expected a web ReadableStream",o),this.close();return}let n=new TextDecoder,l=t.getReader(),c=!0;do{let{done:e,value:r}=await l.read();r&&V(this,C).feed(n.decode(r,{stream:!e})),e&&(c=!1,V(this,C).reset(),B(this,A,N).call(this))}while(c)}),Q(this,$,e=>{G(this,T,void 0),"AbortError"!==e.name&&"aborted"!==e.type&&B(this,A,N).call(this,function e(r){return r instanceof Error?"errors"in r&&Array.isArray(r.errors)?r.errors.map(e).join(", "):"cause"in r&&r.cause instanceof Error?`${r}: ${e(r.cause)}`:r.message:`${r}`}(e))}),Q(this,k,e=>{"string"==typeof e.id&&G(this,R,e.id);let r=new MessageEvent(e.event||"message",{data:e.data,origin:V(this,P)?V(this,P).origin:V(this,E).origin,lastEventId:e.id||""});V(this,x)&&(!e.event||"message"===e.event)&&V(this,x).call(this,r),this.dispatchEvent(r)}),Q(this,U,e=>{G(this,z,e)}),Q(this,M,()=>{G(this,S,void 0),V(this,_)===this.CONNECTING&&B(this,A,j).call(this)});try{if(e instanceof URL)G(this,E,e);else if("string"==typeof e)G(this,E,new URL(e,function(){let e="document"in globalThis?globalThis.document:void 0;return e&&"object"==typeof e&&"baseURI"in e&&"string"==typeof e.baseURI?e.baseURI:void 0}()));else throw Error("Invalid URL")}catch{throw function(e){let r=globalThis.DOMException;return"function"==typeof r?new r(e,"SyntaxError"):SyntaxError(e)}("An invalid or illegal string was specified")}G(this,C,v({onEvent:V(this,k),onRetry:V(this,U)})),G(this,_,this.CONNECTING),G(this,z,3e3),G(this,w,null!=(t=null==r?void 0:r.fetch)?t:globalThis.fetch),G(this,b,null!=(a=null==r?void 0:r.withCredentials)&&a),B(this,A,j).call(this)}get readyState(){return V(this,_)}get url(){return V(this,E).href}get withCredentials(){return V(this,b)}get onerror(){return V(this,O)}set onerror(e){G(this,O,e)}get onmessage(){return V(this,x)}set onmessage(e){G(this,x,e)}get onopen(){return V(this,I)}set onopen(e){G(this,I,e)}addEventListener(e,r,t){super.addEventListener(e,r,t)}removeEventListener(e,r,t){super.removeEventListener(e,r,t)}close(){V(this,S)&&clearTimeout(V(this,S)),V(this,_)!==this.CLOSED&&(V(this,T)&&V(this,T).abort(),G(this,_,this.CLOSED),G(this,T,void 0))}}_=new WeakMap,E=new WeakMap,P=new WeakMap,b=new WeakMap,w=new WeakMap,z=new WeakMap,S=new WeakMap,R=new WeakMap,T=new WeakMap,C=new WeakMap,O=new WeakMap,x=new WeakMap,I=new WeakMap,A=new WeakSet,j=function(){G(this,_,this.CONNECTING),G(this,T,new AbortController),V(this,w)(V(this,E),B(this,A,F).call(this)).then(V(this,D)).catch(V(this,$))},D=new WeakMap,$=new WeakMap,F=function(){var e;let r={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...V(this,R)?{"Last-Event-ID":V(this,R)}:void 0},cache:"no-store",signal:null==(e=V(this,T))?void 0:e.signal};return"window"in globalThis&&(r.credentials=this.withCredentials?"include":"same-origin"),r},k=new WeakMap,U=new WeakMap,L=function(e,r){var t;V(this,_)!==this.CLOSED&&G(this,_,this.CLOSED);let a=new g("error",{code:r,message:e});null==(t=V(this,O))||t.call(this,a),this.dispatchEvent(a)},N=function(e,r){var t;if(V(this,_)===this.CLOSED)return;G(this,_,this.CONNECTING);let a=new g("error",{code:r,message:e});null==(t=V(this,O))||t.call(this,a),this.dispatchEvent(a),G(this,S,setTimeout(V(this,M),V(this,z)))},M=new WeakMap,K.CONNECTING=0,K.OPEN=1,K.CLOSED=2,e.s(["CallToolResultSchema",()=>ra,"CancelledNotificationSchema",()=>eg,"CompleteResultSchema",()=>rz,"EmptyResultSchema",()=>ev,"ErrorCode",()=>t,"GetPromptResultSchema",()=>e6,"InitializeResultSchema",()=>eS,"JSONRPCMessageSchema",()=>ef,"LATEST_PROTOCOL_VERSION",()=>J,"ListPromptsResultSchema",()=>eY,"ListResourceTemplatesResultSchema",()=>eq,"ListResourcesResultSchema",()=>eN,"ListToolsResultSchema",()=>rt,"McpError",()=>rO,"PingRequestSchema",()=>eC,"ProgressNotificationSchema",()=>ex,"ReadResourceResultSchema",()=>eV,"SUPPORTED_PROTOCOL_VERSIONS",()=>Z,"isInitializedNotification",()=>eT,"isJSONRPCError",()=>em,"isJSONRPCNotification",()=>eu,"isJSONRPCRequest",()=>el,"isJSONRPCResponse",()=>ep],76862);var W=e.i(13669);let J="2025-06-18",Z=[J,"2025-03-26","2024-11-05","2024-10-07"],Y=W.z.union([W.z.string(),W.z.number().int()]),X=W.z.string(),ee=W.z.object({progressToken:W.z.optional(Y)}).passthrough(),er=W.z.object({_meta:W.z.optional(ee)}).passthrough(),et=W.z.object({method:W.z.string(),params:W.z.optional(er)}),ea=W.z.object({_meta:W.z.optional(W.z.object({}).passthrough())}).passthrough(),eo=W.z.object({method:W.z.string(),params:W.z.optional(ea)}),es=W.z.object({_meta:W.z.optional(W.z.object({}).passthrough())}).passthrough(),ei=W.z.union([W.z.string(),W.z.number().int()]),en=W.z.object({jsonrpc:W.z.literal("2.0"),id:ei}).merge(et).strict(),el=e=>en.safeParse(e).success,ec=W.z.object({jsonrpc:W.z.literal("2.0")}).merge(eo).strict(),eu=e=>ec.safeParse(e).success,eh=W.z.object({jsonrpc:W.z.literal("2.0"),id:ei,result:es}).strict(),ep=e=>eh.safeParse(e).success;!function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError"}(t||(t={}));let ed=W.z.object({jsonrpc:W.z.literal("2.0"),id:ei,error:W.z.object({code:W.z.number().int(),message:W.z.string(),data:W.z.optional(W.z.unknown())})}).strict(),em=e=>ed.safeParse(e).success,ef=W.z.union([en,ec,eh,ed]),ev=es.strict(),eg=eo.extend({method:W.z.literal("notifications/cancelled"),params:ea.extend({requestId:ei,reason:W.z.string().optional()})}),ey=W.z.object({src:W.z.string(),mimeType:W.z.optional(W.z.string()),sizes:W.z.optional(W.z.array(W.z.string()))}).passthrough(),e_=W.z.object({icons:W.z.array(ey).optional()}).passthrough(),eE=W.z.object({name:W.z.string(),title:W.z.optional(W.z.string())}).passthrough(),eP=eE.extend({version:W.z.string(),websiteUrl:W.z.optional(W.z.string())}).merge(e_),eb=W.z.object({experimental:W.z.optional(W.z.object({}).passthrough()),sampling:W.z.optional(W.z.object({}).passthrough()),elicitation:W.z.optional(W.z.object({}).passthrough()),roots:W.z.optional(W.z.object({listChanged:W.z.optional(W.z.boolean())}).passthrough())}).passthrough(),ew=et.extend({method:W.z.literal("initialize"),params:er.extend({protocolVersion:W.z.string(),capabilities:eb,clientInfo:eP})}),ez=W.z.object({experimental:W.z.optional(W.z.object({}).passthrough()),logging:W.z.optional(W.z.object({}).passthrough()),completions:W.z.optional(W.z.object({}).passthrough()),prompts:W.z.optional(W.z.object({listChanged:W.z.optional(W.z.boolean())}).passthrough()),resources:W.z.optional(W.z.object({subscribe:W.z.optional(W.z.boolean()),listChanged:W.z.optional(W.z.boolean())}).passthrough()),tools:W.z.optional(W.z.object({listChanged:W.z.optional(W.z.boolean())}).passthrough())}).passthrough(),eS=es.extend({protocolVersion:W.z.string(),capabilities:ez,serverInfo:eP,instructions:W.z.optional(W.z.string())}),eR=eo.extend({method:W.z.literal("notifications/initialized")}),eT=e=>eR.safeParse(e).success,eC=et.extend({method:W.z.literal("ping")}),eO=W.z.object({progress:W.z.number(),total:W.z.optional(W.z.number()),message:W.z.optional(W.z.string())}).passthrough(),ex=eo.extend({method:W.z.literal("notifications/progress"),params:ea.merge(eO).extend({progressToken:Y})}),eI=et.extend({params:er.extend({cursor:W.z.optional(X)}).optional()}),eA=es.extend({nextCursor:W.z.optional(X)}),ej=W.z.object({uri:W.z.string(),mimeType:W.z.optional(W.z.string()),_meta:W.z.optional(W.z.object({}).passthrough())}).passthrough(),eD=ej.extend({text:W.z.string()}),e$=W.z.string().refine(e=>{try{return atob(e),!0}catch(e){return!1}},{message:"Invalid Base64 string"}),eF=ej.extend({blob:e$}),ek=eE.extend({uri:W.z.string(),description:W.z.optional(W.z.string()),mimeType:W.z.optional(W.z.string()),_meta:W.z.optional(W.z.object({}).passthrough())}).merge(e_),eU=eE.extend({uriTemplate:W.z.string(),description:W.z.optional(W.z.string()),mimeType:W.z.optional(W.z.string()),_meta:W.z.optional(W.z.object({}).passthrough())}).merge(e_),eL=eI.extend({method:W.z.literal("resources/list")}),eN=eA.extend({resources:W.z.array(ek)}),eM=eI.extend({method:W.z.literal("resources/templates/list")}),eq=eA.extend({resourceTemplates:W.z.array(eU)}),eH=et.extend({method:W.z.literal("resources/read"),params:er.extend({uri:W.z.string()})}),eV=es.extend({contents:W.z.array(W.z.union([eD,eF]))}),eQ=eo.extend({method:W.z.literal("notifications/resources/list_changed")}),eG=et.extend({method:W.z.literal("resources/subscribe"),params:er.extend({uri:W.z.string()})}),eB=et.extend({method:W.z.literal("resources/unsubscribe"),params:er.extend({uri:W.z.string()})}),eK=eo.extend({method:W.z.literal("notifications/resources/updated"),params:ea.extend({uri:W.z.string()})}),eW=W.z.object({name:W.z.string(),description:W.z.optional(W.z.string()),required:W.z.optional(W.z.boolean())}).passthrough(),eJ=eE.extend({description:W.z.optional(W.z.string()),arguments:W.z.optional(W.z.array(eW)),_meta:W.z.optional(W.z.object({}).passthrough())}).merge(e_),eZ=eI.extend({method:W.z.literal("prompts/list")}),eY=eA.extend({prompts:W.z.array(eJ)}),eX=et.extend({method:W.z.literal("prompts/get"),params:er.extend({name:W.z.string(),arguments:W.z.optional(W.z.record(W.z.string()))})}),e0=W.z.object({type:W.z.literal("text"),text:W.z.string(),_meta:W.z.optional(W.z.object({}).passthrough())}).passthrough(),e1=W.z.object({type:W.z.literal("image"),data:e$,mimeType:W.z.string(),_meta:W.z.optional(W.z.object({}).passthrough())}).passthrough(),e2=W.z.object({type:W.z.literal("audio"),data:e$,mimeType:W.z.string(),_meta:W.z.optional(W.z.object({}).passthrough())}).passthrough(),e9=W.z.object({type:W.z.literal("resource"),resource:W.z.union([eD,eF]),_meta:W.z.optional(W.z.object({}).passthrough())}).passthrough(),e4=ek.extend({type:W.z.literal("resource_link")}),e3=W.z.union([e0,e1,e2,e4,e9]),e5=W.z.object({role:W.z.enum(["user","assistant"]),content:e3}).passthrough(),e6=es.extend({description:W.z.optional(W.z.string()),messages:W.z.array(e5)}),e7=eo.extend({method:W.z.literal("notifications/prompts/list_changed")}),e8=W.z.object({title:W.z.optional(W.z.string()),readOnlyHint:W.z.optional(W.z.boolean()),destructiveHint:W.z.optional(W.z.boolean()),idempotentHint:W.z.optional(W.z.boolean()),openWorldHint:W.z.optional(W.z.boolean())}).passthrough(),re=eE.extend({description:W.z.optional(W.z.string()),inputSchema:W.z.object({type:W.z.literal("object"),properties:W.z.optional(W.z.object({}).passthrough()),required:W.z.optional(W.z.array(W.z.string()))}).passthrough(),outputSchema:W.z.optional(W.z.object({type:W.z.literal("object"),properties:W.z.optional(W.z.object({}).passthrough()),required:W.z.optional(W.z.array(W.z.string()))}).passthrough()),annotations:W.z.optional(e8),_meta:W.z.optional(W.z.object({}).passthrough())}).merge(e_),rr=eI.extend({method:W.z.literal("tools/list")}),rt=eA.extend({tools:W.z.array(re)}),ra=es.extend({content:W.z.array(e3).default([]),structuredContent:W.z.object({}).passthrough().optional(),isError:W.z.optional(W.z.boolean())});ra.or(es.extend({toolResult:W.z.unknown()}));let ro=et.extend({method:W.z.literal("tools/call"),params:er.extend({name:W.z.string(),arguments:W.z.optional(W.z.record(W.z.unknown()))})}),rs=eo.extend({method:W.z.literal("notifications/tools/list_changed")}),ri=W.z.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),rn=et.extend({method:W.z.literal("logging/setLevel"),params:er.extend({level:ri})}),rl=eo.extend({method:W.z.literal("notifications/message"),params:ea.extend({level:ri,logger:W.z.optional(W.z.string()),data:W.z.unknown()})}),rc=W.z.object({name:W.z.string().optional()}).passthrough(),ru=W.z.object({hints:W.z.optional(W.z.array(rc)),costPriority:W.z.optional(W.z.number().min(0).max(1)),speedPriority:W.z.optional(W.z.number().min(0).max(1)),intelligencePriority:W.z.optional(W.z.number().min(0).max(1))}).passthrough(),rh=W.z.object({role:W.z.enum(["user","assistant"]),content:W.z.union([e0,e1,e2])}).passthrough(),rp=et.extend({method:W.z.literal("sampling/createMessage"),params:er.extend({messages:W.z.array(rh),systemPrompt:W.z.optional(W.z.string()),includeContext:W.z.optional(W.z.enum(["none","thisServer","allServers"])),temperature:W.z.optional(W.z.number()),maxTokens:W.z.number().int(),stopSequences:W.z.optional(W.z.array(W.z.string())),metadata:W.z.optional(W.z.object({}).passthrough()),modelPreferences:W.z.optional(ru)})}),rd=es.extend({model:W.z.string(),stopReason:W.z.optional(W.z.enum(["endTurn","stopSequence","maxTokens"]).or(W.z.string())),role:W.z.enum(["user","assistant"]),content:W.z.discriminatedUnion("type",[e0,e1,e2])}),rm=W.z.object({type:W.z.literal("boolean"),title:W.z.optional(W.z.string()),description:W.z.optional(W.z.string()),default:W.z.optional(W.z.boolean())}).passthrough(),rf=W.z.object({type:W.z.literal("string"),title:W.z.optional(W.z.string()),description:W.z.optional(W.z.string()),minLength:W.z.optional(W.z.number()),maxLength:W.z.optional(W.z.number()),format:W.z.optional(W.z.enum(["email","uri","date","date-time"]))}).passthrough(),rv=W.z.object({type:W.z.enum(["number","integer"]),title:W.z.optional(W.z.string()),description:W.z.optional(W.z.string()),minimum:W.z.optional(W.z.number()),maximum:W.z.optional(W.z.number())}).passthrough(),rg=W.z.object({type:W.z.literal("string"),title:W.z.optional(W.z.string()),description:W.z.optional(W.z.string()),enum:W.z.array(W.z.string()),enumNames:W.z.optional(W.z.array(W.z.string()))}).passthrough(),ry=W.z.union([rm,rf,rv,rg]),r_=et.extend({method:W.z.literal("elicitation/create"),params:er.extend({message:W.z.string(),requestedSchema:W.z.object({type:W.z.literal("object"),properties:W.z.record(W.z.string(),ry),required:W.z.optional(W.z.array(W.z.string()))}).passthrough()})}),rE=es.extend({action:W.z.enum(["accept","decline","cancel"]),content:W.z.optional(W.z.record(W.z.string(),W.z.unknown()))}),rP=W.z.object({type:W.z.literal("ref/resource"),uri:W.z.string()}).passthrough(),rb=W.z.object({type:W.z.literal("ref/prompt"),name:W.z.string()}).passthrough(),rw=et.extend({method:W.z.literal("completion/complete"),params:er.extend({ref:W.z.union([rb,rP]),argument:W.z.object({name:W.z.string(),value:W.z.string()}).passthrough(),context:W.z.optional(W.z.object({arguments:W.z.optional(W.z.record(W.z.string(),W.z.string()))}))})}),rz=es.extend({completion:W.z.object({values:W.z.array(W.z.string()).max(100),total:W.z.optional(W.z.number().int()),hasMore:W.z.optional(W.z.boolean())}).passthrough()}),rS=W.z.object({uri:W.z.string().startsWith("file://"),name:W.z.optional(W.z.string()),_meta:W.z.optional(W.z.object({}).passthrough())}).passthrough(),rR=et.extend({method:W.z.literal("roots/list")}),rT=es.extend({roots:W.z.array(rS)}),rC=eo.extend({method:W.z.literal("notifications/roots/list_changed")});W.z.union([eC,ew,rw,rn,eX,eZ,eL,eM,eH,eG,eB,ro,rr]),W.z.union([eg,ex,eR,rC]),W.z.union([ev,rd,rE,rT]),W.z.union([eC,rp,r_,rR]),W.z.union([eg,ex,rl,eK,eQ,rs,e7]),W.z.union([ev,eS,rz,e6,eY,eN,eq,eV,ra,rt]);class rO extends Error{constructor(e,r,t){super(`MCP error ${e}: ${r}`),this.code=e,this.data=t,this.name="McpError"}}class rx{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this.setNotificationHandler(eg,e=>{let r=this._requestHandlerAbortControllers.get(e.params.requestId);null==r||r.abort(e.params.reason)}),this.setNotificationHandler(ex,e=>{this._onprogress(e)}),this.setRequestHandler(eC,e=>({}))}_setupTimeout(e,r,t,a,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(a,r),startTime:Date.now(),timeout:r,maxTotalTimeout:t,resetTimeoutOnProgress:o,onTimeout:a})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let a=Date.now()-r.startTime;if(r.maxTotalTimeout&&a>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),new rO(t.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:a});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var r,t,a;this._transport=e;let o=null==(r=this.transport)?void 0:r.onclose;this._transport.onclose=()=>{null==o||o(),this._onclose()};let s=null==(t=this.transport)?void 0:t.onerror;this._transport.onerror=e=>{null==s||s(e),this._onerror(e)};let i=null==(a=this._transport)?void 0:a.onmessage;this._transport.onmessage=(e,r)=>{null==i||i(e,r),ep(e)||em(e)?this._onresponse(e):el(e)?this._onrequest(e,r):eu(e)?this._onnotification(e):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){var e;let r=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,null==(e=this.onclose)||e.call(this);let a=new rO(t.ConnectionClosed,"Connection closed");for(let e of r.values())e(a)}_onerror(e){var r;null==(r=this.onerror)||r.call(this,e)}_onnotification(e){var r;let t=null!=(r=this._notificationHandlers.get(e.method))?r:this.fallbackNotificationHandler;void 0!==t&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,r){var a,o;let s=null!=(a=this._requestHandlers.get(e.method))?a:this.fallbackRequestHandler,i=this._transport;if(void 0===s){null==i||i.send({jsonrpc:"2.0",id:e.id,error:{code:t.MethodNotFound,message:"Method not found"}}).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)));return}let n=new AbortController;this._requestHandlerAbortControllers.set(e.id,n);let l={signal:n.signal,sessionId:null==i?void 0:i.sessionId,_meta:null==(o=e.params)?void 0:o._meta,sendNotification:r=>this.notification(r,{relatedRequestId:e.id}),sendRequest:(r,t,a)=>this.request(r,t,{...a,relatedRequestId:e.id}),authInfo:null==r?void 0:r.authInfo,requestId:e.id,requestInfo:null==r?void 0:r.requestInfo};Promise.resolve().then(()=>s(e,l)).then(r=>{if(!n.signal.aborted)return null==i?void 0:i.send({result:r,jsonrpc:"2.0",id:e.id})},r=>{var a;if(!n.signal.aborted)return null==i?void 0:i.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(r.code)?r.code:t.InternalError,message:null!=(a=r.message)?a:"Internal error"}})}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...t}=e.params,a=Number(r),o=this._progressHandlers.get(a);if(!o)return void this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));let s=this._responseHandlers.get(a),i=this._timeoutInfo.get(a);if(i&&s&&i.resetTimeoutOnProgress)try{this._resetTimeout(a)}catch(e){s(e);return}o(t)}_onresponse(e){let r=Number(e.id),t=this._responseHandlers.get(r);if(void 0===t)return void this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),t(ep(e)?e:new rO(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){var e;await (null==(e=this._transport)?void 0:e.close())}request(e,r,a){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}=null!=a?a:{};return new Promise((n,l)=>{var c,u,h,p,d,m;if(!this._transport)return void l(Error("Not connected"));(null==(c=this._options)?void 0:c.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),null==(u=null==a?void 0:a.signal)||u.throwIfAborted();let f=this._requestMessageId++,v={...e,jsonrpc:"2.0",id:f};(null==a?void 0:a.onprogress)&&(this._progressHandlers.set(f,a.onprogress),v.params={...e.params,_meta:{...(null==(h=e.params)?void 0:h._meta)||{},progressToken:f}});let g=e=>{var r;this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),null==(r=this._transport)||r.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(e)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))),l(e)};this._responseHandlers.set(f,e=>{var t;if(null==(t=null==a?void 0:a.signal)||!t.aborted){if(e instanceof Error)return l(e);try{let t=r.parse(e.result);n(t)}catch(e){l(e)}}}),null==(p=null==a?void 0:a.signal)||p.addEventListener("abort",()=>{var e;g(null==(e=null==a?void 0:a.signal)?void 0:e.reason)});let y=null!=(d=null==a?void 0:a.timeout)?d:6e4;this._setupTimeout(f,y,null==a?void 0:a.maxTotalTimeout,()=>g(new rO(t.RequestTimeout,"Request timed out",{timeout:y})),null!=(m=null==a?void 0:a.resetTimeoutOnProgress)&&m),this._transport.send(v,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(e=>{this._cleanupTimeout(f),l(e)})})}async notification(e,r){var t,a;if(!this._transport)throw Error("Not connected");if(this.assertNotificationCapability(e.method),(null!=(a=null==(t=this._options)?void 0:t.debouncedNotificationMethods)?a:[]).includes(e.method)&&!e.params&&!(null==r?void 0:r.relatedRequestId)){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{var t;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};null==(t=this._transport)||t.send(a,r).catch(e=>this._onerror(e))});return}let o={...e,jsonrpc:"2.0"};await this._transport.send(o,r)}setRequestHandler(e,r){let t=e.shape.method.value;this.assertRequestHandlerCapability(t),this._requestHandlers.set(t,(t,a)=>Promise.resolve(r(e.parse(t),a)))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){this._notificationHandlers.set(e.shape.method.value,t=>Promise.resolve(r(e.parse(t))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}}var rI=e.i(14510);class rA extends rx{constructor(e,r){var t;super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._capabilities=null!=(t=null==r?void 0:r.capabilities)?t:{},this._ajv=new rI.default}registerCapabilities(e){var r;if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=(r=this._capabilities,Object.entries(e).reduce((e,[r,t])=>(t&&"object"==typeof t?e[r]=e[r]?{...e[r],...t}:t:e[r]=t,e),{...r}))}assertCapability(e,r){var t;if(!(null==(t=this._serverCapabilities)?void 0:t[e]))throw Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),void 0===e.sessionId)try{let t=await this.request({method:"initialize",params:{protocolVersion:J,capabilities:this._capabilities,clientInfo:this._clientInfo}},eS,r);if(void 0===t)throw Error(`Server sent invalid initialize result: ${t}`);if(!Z.includes(t.protocolVersion))throw Error(`Server's protocol version is not supported: ${t.protocolVersion}`);this._serverCapabilities=t.capabilities,this._serverVersion=t.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(t.protocolVersion),this._instructions=t.instructions,await this.notification({method:"notifications/initialized"})}catch(e){throw this.close(),e}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){var r,t,a,o,s;switch(e){case"logging/setLevel":if(!(null==(r=this._serverCapabilities)?void 0:r.logging))throw Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!(null==(t=this._serverCapabilities)?void 0:t.prompts))throw Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!(null==(a=this._serverCapabilities)?void 0:a.resources))throw Error(`Server does not support resources (required for ${e})`);if("resources/subscribe"===e&&!this._serverCapabilities.resources.subscribe)throw Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!(null==(o=this._serverCapabilities)?void 0:o.tools))throw Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!(null==(s=this._serverCapabilities)?void 0:s.completions))throw Error(`Server does not support completions (required for ${e})`)}}assertNotificationCapability(e){var r;if("notifications/roots/list_changed"===e&&!(null==(r=this._capabilities.roots)?void 0:r.listChanged))throw Error(`Client does not support roots list changed notifications (required for ${e})`)}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw Error(`Client does not support roots capability (required for ${e})`)}}async ping(e){return this.request({method:"ping"},ev,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},rz,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},ev,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},e6,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},eY,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},eN,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},eq,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},eV,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},ev,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},ev,r)}async callTool(e,r=ra,a){let o=await this.request({method:"tools/call",params:e},r,a),s=this.getToolOutputValidator(e.name);if(s){if(!o.structuredContent&&!o.isError)throw new rO(t.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(o.structuredContent)try{if(!s(o.structuredContent))throw new rO(t.InvalidParams,`Structured content does not match the tool's output schema: ${this._ajv.errorsText(s.errors)}`)}catch(e){if(e instanceof rO)throw e;throw new rO(t.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)}}return o}cacheToolOutputSchemas(e){for(let r of(this._cachedToolOutputValidators.clear(),e))if(r.outputSchema)try{let e=this._ajv.compile(r.outputSchema);this._cachedToolOutputValidators.set(r.name,e)}catch(e){}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){let t=await this.request({method:"tools/list",params:e},rt,r);return this.cacheToolOutputSchemas(t.tools),t}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}async function rj(e){return(await r).getRandomValues(new Uint8Array(e))}async function rD(e){let r="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",t="",a=await rj(e);for(let o=0;o<e;o++){let e=a[o]%r.length;t+=r[e]}return t}async function r$(e){return await rD(e)}async function rF(e){return btoa(String.fromCharCode(...new Uint8Array(await (await r).subtle.digest("SHA-256",new TextEncoder().encode(e))))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function rk(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let r=await r$(e),t=await rF(r);return{code_verifier:r,code_challenge:t}}r=globalThis.crypto?.webcrypto??globalThis.crypto??e.A(70729).then(e=>e.webcrypto);let rU=W.z.string().url().superRefine((e,r)=>{if(!URL.canParse(e))return r.addIssue({code:W.z.ZodIssueCode.custom,message:"URL must be parseable",fatal:!0}),W.z.NEVER}).refine(e=>{let r=new URL(e);return"javascript:"!==r.protocol&&"data:"!==r.protocol&&"vbscript:"!==r.protocol},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),rL=W.z.object({resource:W.z.string().url(),authorization_servers:W.z.array(rU).optional(),jwks_uri:W.z.string().url().optional(),scopes_supported:W.z.array(W.z.string()).optional(),bearer_methods_supported:W.z.array(W.z.string()).optional(),resource_signing_alg_values_supported:W.z.array(W.z.string()).optional(),resource_name:W.z.string().optional(),resource_documentation:W.z.string().optional(),resource_policy_uri:W.z.string().url().optional(),resource_tos_uri:W.z.string().url().optional(),tls_client_certificate_bound_access_tokens:W.z.boolean().optional(),authorization_details_types_supported:W.z.array(W.z.string()).optional(),dpop_signing_alg_values_supported:W.z.array(W.z.string()).optional(),dpop_bound_access_tokens_required:W.z.boolean().optional()}).passthrough(),rN=W.z.object({issuer:W.z.string(),authorization_endpoint:rU,token_endpoint:rU,registration_endpoint:rU.optional(),scopes_supported:W.z.array(W.z.string()).optional(),response_types_supported:W.z.array(W.z.string()),response_modes_supported:W.z.array(W.z.string()).optional(),grant_types_supported:W.z.array(W.z.string()).optional(),token_endpoint_auth_methods_supported:W.z.array(W.z.string()).optional(),token_endpoint_auth_signing_alg_values_supported:W.z.array(W.z.string()).optional(),service_documentation:rU.optional(),revocation_endpoint:rU.optional(),revocation_endpoint_auth_methods_supported:W.z.array(W.z.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:W.z.array(W.z.string()).optional(),introspection_endpoint:W.z.string().optional(),introspection_endpoint_auth_methods_supported:W.z.array(W.z.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:W.z.array(W.z.string()).optional(),code_challenge_methods_supported:W.z.array(W.z.string()).optional()}).passthrough(),rM=W.z.object({issuer:W.z.string(),authorization_endpoint:rU,token_endpoint:rU,userinfo_endpoint:rU.optional(),jwks_uri:rU,registration_endpoint:rU.optional(),scopes_supported:W.z.array(W.z.string()).optional(),response_types_supported:W.z.array(W.z.string()),response_modes_supported:W.z.array(W.z.string()).optional(),grant_types_supported:W.z.array(W.z.string()).optional(),acr_values_supported:W.z.array(W.z.string()).optional(),subject_types_supported:W.z.array(W.z.string()),id_token_signing_alg_values_supported:W.z.array(W.z.string()),id_token_encryption_alg_values_supported:W.z.array(W.z.string()).optional(),id_token_encryption_enc_values_supported:W.z.array(W.z.string()).optional(),userinfo_signing_alg_values_supported:W.z.array(W.z.string()).optional(),userinfo_encryption_alg_values_supported:W.z.array(W.z.string()).optional(),userinfo_encryption_enc_values_supported:W.z.array(W.z.string()).optional(),request_object_signing_alg_values_supported:W.z.array(W.z.string()).optional(),request_object_encryption_alg_values_supported:W.z.array(W.z.string()).optional(),request_object_encryption_enc_values_supported:W.z.array(W.z.string()).optional(),token_endpoint_auth_methods_supported:W.z.array(W.z.string()).optional(),token_endpoint_auth_signing_alg_values_supported:W.z.array(W.z.string()).optional(),display_values_supported:W.z.array(W.z.string()).optional(),claim_types_supported:W.z.array(W.z.string()).optional(),claims_supported:W.z.array(W.z.string()).optional(),service_documentation:W.z.string().optional(),claims_locales_supported:W.z.array(W.z.string()).optional(),ui_locales_supported:W.z.array(W.z.string()).optional(),claims_parameter_supported:W.z.boolean().optional(),request_parameter_supported:W.z.boolean().optional(),request_uri_parameter_supported:W.z.boolean().optional(),require_request_uri_registration:W.z.boolean().optional(),op_policy_uri:rU.optional(),op_tos_uri:rU.optional()}).passthrough().merge(rN.pick({code_challenge_methods_supported:!0})),rq=W.z.object({access_token:W.z.string(),id_token:W.z.string().optional(),token_type:W.z.string(),expires_in:W.z.number().optional(),scope:W.z.string().optional(),refresh_token:W.z.string().optional()}).strip(),rH=W.z.object({error:W.z.string(),error_description:W.z.string().optional(),error_uri:W.z.string().optional()}),rV=rU.optional().or(W.z.literal("").transform(()=>void 0)),rQ=W.z.object({redirect_uris:W.z.array(rU),token_endpoint_auth_method:W.z.string().optional(),grant_types:W.z.array(W.z.string()).optional(),response_types:W.z.array(W.z.string()).optional(),client_name:W.z.string().optional(),client_uri:rU.optional(),logo_uri:rV,scope:W.z.string().optional(),contacts:W.z.array(W.z.string()).optional(),tos_uri:rV,policy_uri:W.z.string().optional(),jwks_uri:rU.optional(),jwks:W.z.any().optional(),software_id:W.z.string().optional(),software_version:W.z.string().optional(),software_statement:W.z.string().optional()}).strip(),rG=W.z.object({client_id:W.z.string(),client_secret:W.z.string().optional(),client_id_issued_at:W.z.number().optional(),client_secret_expires_at:W.z.number().optional()}).strip(),rB=rQ.merge(rG);W.z.object({error:W.z.string(),error_description:W.z.string().optional()}).strip(),W.z.object({token:W.z.string(),token_type_hint:W.z.string().optional()}).strip();class rK extends Error{constructor(e,r){super(e),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}}class rW extends rK{}rW.errorCode="invalid_request";class rJ extends rK{}rJ.errorCode="invalid_client";class rZ extends rK{}rZ.errorCode="invalid_grant";class rY extends rK{}rY.errorCode="unauthorized_client";class rX extends rK{}rX.errorCode="unsupported_grant_type";class r0 extends rK{}r0.errorCode="invalid_scope";class r1 extends rK{}r1.errorCode="access_denied";class r2 extends rK{}r2.errorCode="server_error";class r9 extends rK{}r9.errorCode="temporarily_unavailable";class r4 extends rK{}r4.errorCode="unsupported_response_type";class r3 extends rK{}r3.errorCode="unsupported_token_type";class r5 extends rK{}r5.errorCode="invalid_token";class r6 extends rK{}r6.errorCode="method_not_allowed";class r7 extends rK{}r7.errorCode="too_many_requests";class r8 extends rK{}r8.errorCode="invalid_client_metadata";class te extends rK{}te.errorCode="insufficient_scope";let tr={[rW.errorCode]:rW,[rJ.errorCode]:rJ,[rZ.errorCode]:rZ,[rY.errorCode]:rY,[rX.errorCode]:rX,[r0.errorCode]:r0,[r1.errorCode]:r1,[r2.errorCode]:r2,[r9.errorCode]:r9,[r4.errorCode]:r4,[r3.errorCode]:r3,[r5.errorCode]:r5,[r6.errorCode]:r6,[r7.errorCode]:r7,[r8.errorCode]:r8,[te.errorCode]:te};class tt extends Error{constructor(e){super(null!=e?e:"Unauthorized")}}let ta="code",to="S256";function ts(e,r){let t=void 0!==e.client_secret;return 0===r.length?t?"client_secret_post":"none":t&&r.includes("client_secret_basic")?"client_secret_basic":t&&r.includes("client_secret_post")?"client_secret_post":r.includes("none")?"none":t?"client_secret_post":"none"}function ti(e,r,t,a){let{client_id:o,client_secret:s}=r;switch(e){case"client_secret_basic":var i,n,l,c,u=o,h=s,p=t;if(!h)throw Error("client_secret_basic authentication requires a client_secret");let d=btoa(`${u}:${h}`);p.set("Authorization",`Basic ${d}`);return;case"client_secret_post":i=o,n=s,(l=a).set("client_id",i),n&&l.set("client_secret",n);return;case"none":c=o,a.set("client_id",c);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}async function tn(e){let r=e instanceof Response?e.status:void 0,t=e instanceof Response?await e.text():e;try{let{error:e,error_description:r,error_uri:a}=rH.parse(JSON.parse(t));return new(tr[e]||r2)(r||"",a)}catch(e){return new r2(`${r?`HTTP ${r}: `:""}Invalid OAuth error response: ${e}. Raw body: ${t}`)}}async function tl(e,r){var t,a;try{return await tc(e,r)}catch(o){if(o instanceof rJ||o instanceof rY)return await (null==(t=e.invalidateCredentials)?void 0:t.call(e,"all")),await tc(e,r);if(o instanceof rZ)return await (null==(a=e.invalidateCredentials)?void 0:a.call(e,"tokens")),await tc(e,r);throw o}}async function tc(e,{serverUrl:r,authorizationCode:t,scope:a,resourceMetadataUrl:o,fetchFn:s}){let i,n;try{(i=await tp(r,{resourceMetadataUrl:o},s)).authorization_servers&&i.authorization_servers.length>0&&(n=i.authorization_servers[0])}catch(e){}n||(n=r);let l=await tu(r,e,i),c=await tv(n,{fetchFn:s}),u=await Promise.resolve(e.clientInformation());if(!u){if(void 0!==t)throw Error("Existing OAuth client information is required when exchanging an authorization code");if(!e.saveClientInformation)throw Error("OAuth client information must be saveable for dynamic registration");let r=await tE(n,{metadata:c,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(r),u=r}if(void 0!==t){let r=await e.codeVerifier(),a=await ty(n,{metadata:c,clientInformation:u,authorizationCode:t,codeVerifier:r,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(a),"AUTHORIZED"}let h=await e.tokens();if(null==h?void 0:h.refresh_token)try{let r=await t_(n,{metadata:c,clientInformation:u,refreshToken:h.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(r),"AUTHORIZED"}catch(e){if(!(e instanceof rK)||e instanceof r2);else throw e}let p=e.state?await e.state():void 0,{authorizationUrl:d,codeVerifier:m}=await tg(n,{metadata:c,clientInformation:u,state:p,redirectUrl:e.redirectUrl,scope:a||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(m),await e.redirectToAuthorization(d),"REDIRECT"}async function tu(e,r,t){let a=function(e){let r=new URL("string"==typeof e?e:e.href);return r.hash="",r}(e);if(r.validateResourceURL)return await r.validateResourceURL(a,null==t?void 0:t.resource);if(t){if(!function({requestedResource:e,configuredResource:r}){let t=new URL("string"==typeof e?e:e.href),a=new URL("string"==typeof r?r:r.href);if(t.origin!==a.origin||t.pathname.length<a.pathname.length)return!1;let o=t.pathname.endsWith("/")?t.pathname:t.pathname+"/",s=a.pathname.endsWith("/")?a.pathname:a.pathname+"/";return o.startsWith(s)}({requestedResource:a,configuredResource:t.resource}))throw Error(`Protected resource ${t.resource} does not match expected ${a} (or origin)`);return new URL(t.resource)}}function th(e){let r=e.headers.get("WWW-Authenticate");if(!r)return;let[t,a]=r.split(" ");if("bearer"!==t.toLowerCase()||!a)return;let o=/resource_metadata="([^"]*)"/.exec(r);if(o)try{return new URL(o[1])}catch(e){return}}async function tp(e,r,t=fetch){let a=await tf(e,"oauth-protected-resource",t,{protocolVersion:null==r?void 0:r.protocolVersion,metadataUrl:null==r?void 0:r.resourceMetadataUrl});if(!a||404===a.status)throw Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!a.ok)throw Error(`HTTP ${a.status} trying to load well-known OAuth protected resource metadata.`);return rL.parse(await a.json())}async function td(e,r,t=fetch){try{return await t(e,{headers:r})}catch(a){if(a instanceof TypeError)if(r)return td(e,void 0,t);else return;throw a}}async function tm(e,r,t=fetch){return await td(e,{"MCP-Protocol-Version":r},t)}async function tf(e,r,t,a){var o,s,i,n;let l,c=new URL(e),u=null!=(o=null==a?void 0:a.protocolVersion)?o:J;(null==a?void 0:a.metadataUrl)?l=new URL(a.metadataUrl):(l=new URL(function(e,r="",t={}){return r.endsWith("/")&&(r=r.slice(0,-1)),t.prependPathname?`${r}/.well-known/${e}`:`/.well-known/${e}${r}`}(r,c.pathname),null!=(s=null==a?void 0:a.metadataServerUrl)?s:c)).search=c.search;let h=await tm(l,u,t);if(!(null==a?void 0:a.metadataUrl)&&(i=h,n=c.pathname,!i||i.status>=400&&i.status<500&&"/"!==n)){let e=new URL(`/.well-known/${r}`,c);h=await tm(e,u,t)}return h}async function tv(e,{fetchFn:r=fetch,protocolVersion:t=J}={}){let a={"MCP-Protocol-Version":t,Accept:"application/json"};for(let{url:t,type:o}of function(e){let r="string"==typeof e?new URL(e):e,t="/"!==r.pathname,a=[];if(!t)return a.push({url:new URL("/.well-known/oauth-authorization-server",r.origin),type:"oauth"}),a.push({url:new URL("/.well-known/openid-configuration",r.origin),type:"oidc"}),a;let o=r.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),a.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,r.origin),type:"oauth"}),a.push({url:new URL("/.well-known/oauth-authorization-server",r.origin),type:"oauth"}),a.push({url:new URL(`/.well-known/openid-configuration${o}`,r.origin),type:"oidc"}),a.push({url:new URL(`${o}/.well-known/openid-configuration`,r.origin),type:"oidc"}),a}(e)){let e=await td(t,a,r);if(e){if(!e.ok){if(e.status>=400&&e.status<500)continue;throw Error(`HTTP ${e.status} trying to load ${"oauth"===o?"OAuth":"OpenID provider"} metadata from ${t}`)}if("oauth"===o)return rN.parse(await e.json());return rM.parse(await e.json())}}}async function tg(e,{metadata:r,clientInformation:t,redirectUrl:a,scope:o,state:s,resource:i}){let n;if(r){if(n=new URL(r.authorization_endpoint),!r.response_types_supported.includes(ta))throw Error(`Incompatible auth server: does not support response type ${ta}`);if(r.code_challenge_methods_supported&&!r.code_challenge_methods_supported.includes(to))throw Error(`Incompatible auth server: does not support code challenge method ${to}`)}else n=new URL("/authorize",e);let l=await rk(),c=l.code_verifier,u=l.code_challenge;return n.searchParams.set("response_type",ta),n.searchParams.set("client_id",t.client_id),n.searchParams.set("code_challenge",u),n.searchParams.set("code_challenge_method",to),n.searchParams.set("redirect_uri",String(a)),s&&n.searchParams.set("state",s),o&&n.searchParams.set("scope",o),(null==o?void 0:o.includes("offline_access"))&&n.searchParams.append("prompt","consent"),i&&n.searchParams.set("resource",i.href),{authorizationUrl:n,codeVerifier:c}}async function ty(e,{metadata:r,clientInformation:t,authorizationCode:a,codeVerifier:o,redirectUri:s,resource:i,addClientAuthentication:n,fetchFn:l}){var c;let u="authorization_code",h=(null==r?void 0:r.token_endpoint)?new URL(r.token_endpoint):new URL("/token",e);if((null==r?void 0:r.grant_types_supported)&&!r.grant_types_supported.includes(u))throw Error(`Incompatible auth server: does not support grant type ${u}`);let p=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),d=new URLSearchParams({grant_type:u,code:a,code_verifier:o,redirect_uri:String(s)});n?n(p,d,e,r):ti(ts(t,null!=(c=null==r?void 0:r.token_endpoint_auth_methods_supported)?c:[]),t,p,d),i&&d.set("resource",i.href);let m=await (null!=l?l:fetch)(h,{method:"POST",headers:p,body:d});if(!m.ok)throw await tn(m);return rq.parse(await m.json())}async function t_(e,{metadata:r,clientInformation:t,refreshToken:a,resource:o,addClientAuthentication:s,fetchFn:i}){var n;let l,c="refresh_token";if(r){if(l=new URL(r.token_endpoint),r.grant_types_supported&&!r.grant_types_supported.includes(c))throw Error(`Incompatible auth server: does not support grant type ${c}`)}else l=new URL("/token",e);let u=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),h=new URLSearchParams({grant_type:c,refresh_token:a});s?s(u,h,e,r):ti(ts(t,null!=(n=null==r?void 0:r.token_endpoint_auth_methods_supported)?n:[]),t,u,h),o&&h.set("resource",o.href);let p=await (null!=i?i:fetch)(l,{method:"POST",headers:u,body:h});if(!p.ok)throw await tn(p);return rq.parse({refresh_token:a,...await p.json()})}async function tE(e,{metadata:r,clientMetadata:t,fetchFn:a}){let o;if(r){if(!r.registration_endpoint)throw Error("Incompatible auth server: does not support dynamic client registration");o=new URL(r.registration_endpoint)}else o=new URL("/register",e);let s=await (null!=a?a:fetch)(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok)throw await tn(s);return rB.parse(await s.json())}class tP extends Error{constructor(e,r,t){super(`SSE error: ${r}`),this.code=e,this.event=t}}class tb{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._eventSourceInit=null==r?void 0:r.eventSourceInit,this._requestInit=null==r?void 0:r.requestInit,this._authProvider=null==r?void 0:r.authProvider,this._fetch=null==r?void 0:r.fetch}async _authThenStart(){var e;let r;if(!this._authProvider)throw new tt("No auth provider");try{r=await tl(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(r){throw null==(e=this.onerror)||e.call(this,r),r}if("AUTHORIZED"!==r)throw new tt;return await this._startOrAuth()}async _commonHeaders(){var e;let r={};if(this._authProvider){let e=await this._authProvider.tokens();e&&(r.Authorization=`Bearer ${e.access_token}`)}return this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion),new Headers({...r,...null==(e=this._requestInit)?void 0:e.headers})}_startOrAuth(){var e,r,t;let a=null!=(t=null!=(r=null==(e=this===null||void 0===this?void 0:this._eventSourceInit)?void 0:e.fetch)?r:this._fetch)?t:fetch;return new Promise((e,r)=>{this._eventSource=new K(this._url.href,{...this._eventSourceInit,fetch:async(e,r)=>{let t=await this._commonHeaders();t.set("Accept","text/event-stream");let o=await a(e,{...r,headers:t});return 401===o.status&&o.headers.has("www-authenticate")&&(this._resourceMetadataUrl=th(o)),o}}),this._abortController=new AbortController,this._eventSource.onerror=t=>{var a;if(401===t.code&&this._authProvider)return void this._authThenStart().then(e,r);let o=new tP(t.code,t.message,t);r(o),null==(a=this.onerror)||a.call(this,o)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",t=>{var a;try{if(this._endpoint=new URL(t.data,this._url),this._endpoint.origin!==this._url.origin)throw Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(e){r(e),null==(a=this.onerror)||a.call(this,e),this.close();return}e()}),this._eventSource.onmessage=e=>{var r,t;let a;try{a=ef.parse(JSON.parse(e.data))}catch(e){null==(r=this.onerror)||r.call(this,e);return}null==(t=this.onmessage)||t.call(this,a)}})}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(e){if(!this._authProvider)throw new tt("No auth provider");if("AUTHORIZED"!==await tl(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch}))throw new tt("Failed to authorize")}async close(){var e,r,t;null==(e=this._abortController)||e.abort(),null==(r=this._eventSource)||r.close(),null==(t=this.onclose)||t.call(this)}async send(e){var r,t,a;if(!this._endpoint)throw Error("Not connected");try{let a=await this._commonHeaders();a.set("content-type","application/json");let o={...this._requestInit,method:"POST",headers:a,body:JSON.stringify(e),signal:null==(r=this._abortController)?void 0:r.signal},s=await (null!=(t=this._fetch)?t:fetch)(this._endpoint,o);if(!s.ok){if(401===s.status&&this._authProvider){this._resourceMetadataUrl=th(s);let r=await tl(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch});if("AUTHORIZED"!==r)throw new tt;return this.send(e)}let r=await s.text().catch(()=>null);throw Error(`Error POSTing to endpoint (HTTP ${s.status}): ${r}`)}}catch(e){throw null==(a=this.onerror)||a.call(this,e),e}}setProtocolVersion(e){this._protocolVersion=e}}class tw extends TransformStream{constructor({onError:e,onRetry:r,onComment:t}={}){let a;super({start(o){a=v({onEvent:e=>{o.enqueue(e)},onError(r){"terminate"===e?o.error(r):"function"==typeof e&&e(r)},onRetry:r,onComment:t})},transform(e){a.feed(e)}})}}let tz={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class tS extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}}class tR{constructor(e,r){var t;this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=null==r?void 0:r.requestInit,this._authProvider=null==r?void 0:r.authProvider,this._fetch=null==r?void 0:r.fetch,this._sessionId=null==r?void 0:r.sessionId,this._reconnectionOptions=null!=(t=null==r?void 0:r.reconnectionOptions)?t:tz}async _authThenStart(){var e;let r;if(!this._authProvider)throw new tt("No auth provider");try{r=await tl(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(r){throw null==(e=this.onerror)||e.call(this,r),r}if("AUTHORIZED"!==r)throw new tt;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let r={};if(this._authProvider){let e=await this._authProvider.tokens();e&&(r.Authorization=`Bearer ${e.access_token}`)}this._sessionId&&(r["mcp-session-id"]=this._sessionId),this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);let t=this._normalizeHeaders(null==(e=this._requestInit)?void 0:e.headers);return new Headers({...r,...t})}async _startOrAuthSse(e){var r,t,a;let{resumptionToken:o}=e;try{let a=await this._commonHeaders();a.set("Accept","text/event-stream"),o&&a.set("last-event-id",o);let s=await (null!=(r=this._fetch)?r:fetch)(this._url,{method:"GET",headers:a,signal:null==(t=this._abortController)?void 0:t.signal});if(!s.ok){if(401===s.status&&this._authProvider)return await this._authThenStart();if(405===s.status)return;throw new tS(s.status,`Failed to open SSE stream: ${s.statusText}`)}this._handleSseStream(s.body,e,!0)}catch(e){throw null==(a=this.onerror)||a.call(this,e),e}}_getNextReconnectionDelay(e){let r=this._reconnectionOptions.initialReconnectionDelay;return Math.min(r*Math.pow(this._reconnectionOptions.reconnectionDelayGrowFactor,e),this._reconnectionOptions.maxReconnectionDelay)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,r=0){var t;let a=this._reconnectionOptions.maxRetries;if(a>0&&r>=a){null==(t=this.onerror)||t.call(this,Error(`Maximum reconnection attempts (${a}) exceeded.`));return}setTimeout(()=>{this._startOrAuthSse(e).catch(t=>{var a;null==(a=this.onerror)||a.call(this,Error(`Failed to reconnect SSE stream: ${t instanceof Error?t.message:String(t)}`)),this._scheduleReconnection(e,r+1)})},this._getNextReconnectionDelay(r))}_handleSseStream(e,r,t){let a;if(!e)return;let{onresumptiontoken:o,replayMessageId:s}=r;(async()=>{var r,i,n,l;try{let t=e.pipeThrough(new TextDecoderStream).pipeThrough(new tw).getReader();for(;;){let{value:e,done:n}=await t.read();if(n)break;if(e.id&&(a=e.id,null==o||o(e.id)),!e.event||"message"===e.event)try{let t=ef.parse(JSON.parse(e.data));void 0!==s&&ep(t)&&(t.id=s),null==(r=this.onmessage)||r.call(this,t)}catch(e){null==(i=this.onerror)||i.call(this,e)}}}catch(e){if(null==(n=this.onerror)||n.call(this,Error(`SSE stream disconnected: ${e}`)),t&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:o,replayMessageId:s},0)}catch(e){null==(l=this.onerror)||l.call(this,Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`))}}})()}async start(){if(this._abortController)throw Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new tt("No auth provider");if("AUTHORIZED"!==await tl(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch}))throw new tt("Failed to authorize")}async close(){var e,r;null==(e=this._abortController)||e.abort(),null==(r=this.onclose)||r.call(this)}async send(e,r){var t,a,o,s;try{let{resumptionToken:s,onresumptiontoken:i}=r||{};if(s)return void this._startOrAuthSse({resumptionToken:s,replayMessageId:el(e)?e.id:void 0}).catch(e=>{var r;return null==(r=this.onerror)?void 0:r.call(this,e)});let n=await this._commonHeaders();n.set("content-type","application/json"),n.set("accept","application/json, text/event-stream");let l={...this._requestInit,method:"POST",headers:n,body:JSON.stringify(e),signal:null==(t=this._abortController)?void 0:t.signal},c=await (null!=(a=this._fetch)?a:fetch)(this._url,l),u=c.headers.get("mcp-session-id");if(u&&(this._sessionId=u),!c.ok){if(401===c.status&&this._authProvider){if(this._hasCompletedAuthFlow)throw new tS(401,"Server returned 401 after successful authentication");this._resourceMetadataUrl=th(c);let r=await tl(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch});if("AUTHORIZED"!==r)throw new tt;return this._hasCompletedAuthFlow=!0,this.send(e)}let r=await c.text().catch(()=>null);throw Error(`Error POSTing to endpoint (HTTP ${c.status}): ${r}`)}if(this._hasCompletedAuthFlow=!1,202===c.status){eT(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>{var r;return null==(r=this.onerror)?void 0:r.call(this,e)});return}let h=(Array.isArray(e)?e:[e]).filter(e=>"method"in e&&"id"in e&&void 0!==e.id).length>0,p=c.headers.get("content-type");if(h)if(null==p?void 0:p.includes("text/event-stream"))this._handleSseStream(c.body,{onresumptiontoken:i},!1);else if(null==p?void 0:p.includes("application/json")){let e=await c.json();for(let r of Array.isArray(e)?e.map(e=>ef.parse(e)):[ef.parse(e)])null==(o=this.onmessage)||o.call(this,r)}else throw new tS(-1,`Unexpected content type: ${p}`)}catch(e){throw null==(s=this.onerror)||s.call(this,e),e}}get sessionId(){return this._sessionId}async terminateSession(){var e,r,t;if(this._sessionId)try{let t=await this._commonHeaders(),a={...this._requestInit,method:"DELETE",headers:t,signal:null==(e=this._abortController)?void 0:e.signal},o=await (null!=(r=this._fetch)?r:fetch)(this._url,a);if(!o.ok&&405!==o.status)throw new tS(o.status,`Failed to terminate session: ${o.statusText}`);this._sessionId=void 0}catch(e){throw null==(t=this.onerror)||t.call(this,e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}}let tT=e=>{if(!e||0===e.length)return"";let r=e.toLowerCase();return r.substring(0,1).toUpperCase()+r.substring(1,r.length)};e.s(["interpolateFunctionValue",()=>tC],43488);let tC=({value:e,args:r,thread:t,assistant:a})=>{let o=[];return{value:(e||"").replace(/{{\s*([\w-]+)\s*}}/g,(e,s)=>r&&s in r?String(r[s]):s in(t.metadata||{})?String(t.metadata[s]):"threadId"===s?t.id:"assistantId"===s?a.id:(o.push(s),`{{${s}}}`)),missing:o}};e.s(["createLog",()=>tx],18527);var tO=e.i(45076);let tx=({log:e,prisma:r})=>(0,tO.waitUntil)(new Promise(async t=>{console.log("Logging error."),await r.log.create({data:e}),console.log("Successfully logged error."),t(!0)})),tI=({thread:e,mcpServer:r,assistant:t,prisma:o})=>{let{headers:s,missing:i}=(({mcpServer:e,thread:r,metadata:t,assistant:o})=>{let s={},i=[];for(let[n,l]of Object.entries((({mcpServer:e})=>e.transportType===a.TransportType.HTTP?e.httpTransport.headers:e.transportType===a.TransportType.SSE?e.sseTransport.headers:{})({mcpServer:e}))){let e=tC({value:l,args:t,thread:r,assistant:o});s[n]=e.value,i.push(...e.missing)}return{headers:s,missing:i}})({mcpServer:r,thread:e,metadata:e.metadata??{},assistant:t});if(i.length){let r=`Missing variables in MCP server: ${i.join(", ")}`;throw tx({log:{requestMethod:a.LogRequestMethod.POST,requestRoute:a.LogRequestRoute.MESSAGES,level:a.LogLevel.ERROR,status:400,message:r,workspaceId:t.workspaceId,assistantId:t.id,threadId:e.id},prisma:o}),Error(r)}return Object.fromEntries(Object.entries({...s,...e.metadata??{}}).map(([e,r])=>[(e=>{let r=e?.replace(/([A-Z])+/g,tT)?.split(/(?=[A-Z])|[\.\-\s_]/).map(e=>e.toLowerCase())??[];return 0===r.length?"":1===r.length?r[0]:r.reduce((e,r)=>`${e}-${r.toLowerCase()}`)})(e),r]))},tA=({thread:e,mcpServer:r,assistant:t,prisma:o})=>{let{url:s,missing:i}=(({mcpServer:e,thread:r,metadata:t,assistant:o})=>{let{value:s,missing:i}=tC({value:(({mcpServer:e})=>e.transportType===a.TransportType.HTTP?e.httpTransport.url:e.transportType===a.TransportType.SSE?e.sseTransport.url:"")({mcpServer:e}),args:t,thread:r,assistant:o});return{url:s,missing:i}})({mcpServer:r,thread:e,metadata:e.metadata??{},assistant:t});if(i.length){let r=`Missing variables in MCP server: ${i.join(", ")}`;throw tx({log:{requestMethod:a.LogRequestMethod.POST,requestRoute:a.LogRequestRoute.MESSAGES,level:a.LogLevel.ERROR,status:400,message:r,workspaceId:t.workspaceId,assistantId:t.id,threadId:e.id},prisma:o}),Error(r)}return s};e.g.EventSource=K;let tj=async({mcpServer:e,thread:r,assistant:t,prisma:o})=>{let s=new rA({name:"superinterface-mcp-client",version:"1.0.0"},{capabilities:{}}),i=(({mcpServer:e,thread:r,assistant:t,prisma:o})=>{if(e.transportType===a.TransportType.STDIO)throw Error("STDIO transport is not supported.");if(e.transportType===a.TransportType.HTTP){let a=tI({thread:r,mcpServer:e,assistant:t,prisma:o});return new tR(new URL(tA({thread:r,mcpServer:e,assistant:t,prisma:o})),{requestInit:{headers:a}})}if(e.transportType===a.TransportType.SSE){let a=tA({thread:r,mcpServer:e,assistant:t,prisma:o}),s=tI({thread:r,mcpServer:e,assistant:t,prisma:o});return new tb(new URL(a),{eventSourceInit:{fetch:(({headers:e})=>(r,t)=>{let a=new Headers({...t?.headers??{},...e});return fetch(r.toString(),{...t,headers:a})})({headers:s})},requestInit:{headers:s}})}throw Error(`Unknown transport type ${e.transportType}`)})({mcpServer:e,thread:r,assistant:t,prisma:o});return await s.connect(i),{mcpConnection:{client:s,transport:i}}};e.s(["closeMcpConnection",()=>tD],10273);let tD=async({mcpConnection:e})=>{await e.client.close(),await e.transport.close()};var t$=e.i(45027);let tF=async({assistant:e,thread:r,prisma:t})=>{let a=e.mcpServers.filter(e=>!e.computerUseTool);if((0,n.isResponsesStorageProvider)({storageProviderType:e.storageProviderType})&&!e.modelSlug.match("computer-use"))return a.map(a=>({type:"mcp",mcp:{server_label:(0,t$.getMcpServerLabel)({id:a.id,name:a.name}),...a.description?{server_description:a.description}:{},server_url:tA({thread:r,mcpServer:a,assistant:e,prisma:t}),headers:tI({thread:r,mcpServer:a,assistant:e,prisma:t}),require_approval:"never"}}));let o=await (({mcpServers:e,thread:r,assistant:t,prisma:a})=>Promise.all(e.map(async e=>{let{mcpConnection:o}=await tj({mcpServer:e,thread:r,assistant:t,prisma:a}),s=await o.client.listTools();return await tD({mcpConnection:o}),s.tools.map(e=>({type:"function",function:(({tool:e})=>({name:e.name,description:e.description,parameters:e.inputSchema}))({tool:e})}))})))({mcpServers:a,thread:r,assistant:e,prisma:t});return(0,p.flat)(o)},tk=async({assistant:e,thread:r,prisma:t})=>{let o=d.find(r=>r.type===e.modelProvider.type);return o&&o.isFunctionCallingAvailable?{tools:[...await tF({assistant:e,thread:r,prisma:t}),...e.functions.map(e=>({type:"function",function:e.openapiSpec})),...(({assistant:e})=>e.tools.map(r=>{if(r.type===a.ToolType.FILE_SEARCH){if(i({storageProviderType:e.storageProviderType})||c({storageProviderType:e.storageProviderType}))return{type:"file_search"};if((0,n.isResponsesStorageProvider)({storageProviderType:e.storageProviderType})){let e=r.fileSearchTool.vectorStoreIds;return 0===e.length?{type:"file_search"}:{type:"file_search",file_search:{vector_store_ids:e,max_num_results:r.fileSearchTool.maxNumResults}}}}else if(r.type===a.ToolType.CODE_INTERPRETER){if(i({storageProviderType:e.storageProviderType})||c({storageProviderType:e.storageProviderType}))return{type:"code_interpreter"};if((0,n.isResponsesStorageProvider)({storageProviderType:e.storageProviderType}))return{type:"code_interpreter",code_interpreter:{container:{type:"auto"}}};if(e.modelProvider.type===a.ModelProviderType.ANTHROPIC)return{type:"code_execution_20250825",code_execution_20250825:{name:"code_execution"}}}else if(r.type===a.ToolType.IMAGE_GENERATION){if((0,n.isResponsesStorageProvider)({storageProviderType:e.storageProviderType}))return{type:"image_generation",image_generation:{model:r.imageGenerationTool.model,background:r.imageGenerationTool.background.toLowerCase(),quality:r.imageGenerationTool.quality.toLowerCase(),output_format:r.imageGenerationTool.outputFormat.toLowerCase(),size:(({tool:e})=>e.imageGenerationTool.size===a.ImageGenerationToolSize.AUTO?"auto":e.imageGenerationTool.size===a.ImageGenerationToolSize.SIZE_1024_1024?"1024x1024":e.imageGenerationTool.size===a.ImageGenerationToolSize.SIZE_1024_1536?"1024x1536":e.imageGenerationTool.size===a.ImageGenerationToolSize.SIZE_1536_1024?"1536x1024":void 0)({tool:r}),partial_images:r.imageGenerationTool.partialImages}}}else if(r.type===a.ToolType.WEB_SEARCH){if((0,n.isResponsesStorageProvider)({storageProviderType:e.storageProviderType}))return{type:"web_search"};if(e.modelProvider.type===a.ModelProviderType.ANTHROPIC)return{type:"web_search_20250305",web_search_20250305:{name:"web_search"}}}else if(r.type===a.ToolType.COMPUTER_USE){if(!r.computerUseTool.mcpServerId)return null;if((0,n.isResponsesStorageProvider)({storageProviderType:e.storageProviderType}))return{type:"computer_use_preview",computer_use_preview:{environment:r.computerUseTool.environment.toLowerCase(),display_width:r.computerUseTool.displayWidth,display_height:r.computerUseTool.displayHeight}};if(e.modelProvider.type===a.ModelProviderType.ANTHROPIC)return{type:"computer_20250124",computer_20250124:{name:"computer",display_width_px:r.computerUseTool.displayWidth,display_height_px:r.computerUseTool.displayHeight}}}return null}).filter(Boolean))({assistant:e})]}:{}};var tU=e.i(92859);let tL=({assistant:e,prisma:r,thread:t=null})=>(0,o.supercompat)({client:(0,u.clientAdapter)({modelProvider:e.modelProvider,storageProviderType:e.storageProviderType}),storage:(({assistant:e,prisma:r})=>{if(e.storageProviderType===a.StorageProviderType.SUPERINTERFACE_CLOUD)return(0,o.prismaStorageAdapter)({prisma:r});if(!i({storageProviderType:e.storageProviderType})){if(e.storageProviderType===a.StorageProviderType.AZURE_OPENAI_RESPONSES)return(0,o.azureResponsesStorageAdapter)();if((0,n.isResponsesStorageProvider)({storageProviderType:e.storageProviderType}))return(0,o.responsesStorageAdapter)();if(c({storageProviderType:e.storageProviderType})){let t=(0,tU.getAzureAiProjectClient)({modelProvider:e.modelProvider,storageProviderType:e.storageProviderType});return(0,o.azureAgentsStorageAdapter)({azureAiProject:t,prisma:r})}throw Error(`Invalid storage provider type: ${e.storageProviderType}`)}})({assistant:e,prisma:r}),runAdapter:(({assistant:e,thread:r,prisma:t})=>{if(e.storageProviderType===a.StorageProviderType.SUPERINTERFACE_CLOUD)return(0,o.completionsRunAdapter)();if(!i({storageProviderType:e.storageProviderType})){if((0,n.isResponsesStorageProvider)({storageProviderType:e.storageProviderType}))return(0,o.responsesRunAdapter)({getOpenaiAssistant:(({assistant:e,thread:r,prisma:t})=>async({select:{id:o=!1}={}}={})=>({id:o}).id?{id:e.id}:{id:e.id,object:"assistant",created_at:(0,h.default)().unix(),model:e.modelSlug,name:e.name,instructions:e.instructions,description:null,tools:r?(await tk({assistant:e,thread:r,prisma:t}))?.tools??[]:[],metadata:{},top_p:1,temperature:1,response_format:{type:"text"},truncation_strategy:(({assistant:e})=>e.truncationType===a.TruncationType.LAST_MESSAGES?{type:"last_messages",last_messages:e.truncationLastMessagesCount}:e.truncationType===a.TruncationType.DISABLED?{type:"disabled"}:{type:"auto"})({assistant:e})})({assistant:e,thread:r,prisma:t}),waitUntil:tO.waitUntil});if(c({storageProviderType:e.storageProviderType})){let r=(0,tU.getAzureAiProjectClient)({modelProvider:e.modelProvider,storageProviderType:e.storageProviderType});return(0,o.azureAgentsRunAdapter)({azureAiProject:r})}throw Error(`Invalid storage provider type: ${e.storageProviderType}`)}})({assistant:e,thread:t,prisma:r})})}];
|
|
6
6
|
|
|
7
7
|
//# sourceMappingURL=supercorp_superinterface_bebd2c96._.js.map
|