@github/copilot 0.0.348-16 → 0.0.348-17

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/index.js CHANGED
@@ -1951,10 +1951,10 @@ Pay attention to the following when using it:
1951
1951
  `,n),a=-1;if(r!==-1&&I!==-1?a=Math.min(r,I):r!==-1?a=r:I!==-1&&(a=I),a===-1){l=t.slice(n);break}else{let s=t.slice(n,a);e.push(s),n=a+1,t[n-1]==="\r"&&t[n]===`
1952
1952
  `&&n++}}return[e,l]}var D1e=class extends Event{constructor(e,l){var n,r;super(e),this.code=(n=l?.code)!=null?n:void 0,this.message=(r=l?.message)!=null?r:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,l,n){return n(JTt(this),l)}[Symbol.for("Deno.customInspect")](e,l){return e(JTt(this),l)}};function l2n(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function YKe(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(YKe).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${YKe(t.cause)}`:t.message:`${t}`}function JTt(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var STt=t=>{throw TypeError(t)},HKe=(t,e,l)=>e.has(t)||STt("Cannot "+l),is=(t,e,l)=>(HKe(t,e,"read from private field"),l?l.call(t):e.get(t)),Yb=(t,e,l)=>e.has(t)?STt("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,l),Gd=(t,e,l,n)=>(HKe(t,e,"write to private field"),e.set(t,l),l),jv=(t,e,l)=>(HKe(t,e,"access private method"),l),eN,GO,g8,_1e,z1e,kde,y8,Lde,$k,N8,E8,W8,Hde,_2,VKe,wKe,QKe,xTt,FKe,CKe,Xde,vKe,fKe,pO=class extends EventTarget{constructor(e,l){var n,r;super(),Yb(this,_2),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Yb(this,eN),Yb(this,GO),Yb(this,g8),Yb(this,_1e),Yb(this,z1e),Yb(this,kde),Yb(this,y8),Yb(this,Lde,null),Yb(this,$k),Yb(this,N8),Yb(this,E8,null),Yb(this,W8,null),Yb(this,Hde,null),Yb(this,wKe,async I=>{var a;is(this,N8).reset();let{body:s,redirected:o,status:d,headers:u}=I;if(d===204){jv(this,_2,Xde).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(o?Gd(this,g8,new URL(I.url)):Gd(this,g8,void 0),d!==200){jv(this,_2,Xde).call(this,`Non-200 status code (${d})`,d);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){jv(this,_2,Xde).call(this,'Invalid content type, expected "text/event-stream"',d);return}if(is(this,eN)===this.CLOSED)return;Gd(this,eN,this.OPEN);let b=new Event("open");if((a=is(this,Hde))==null||a.call(this,b),this.dispatchEvent(b),typeof s!="object"||!s||!("getReader"in s)){jv(this,_2,Xde).call(this,"Invalid response body, expected a web ReadableStream",d),this.close();return}let p=new TextDecoder,h=s.getReader(),Z=!0;do{let{done:N,value:y}=await h.read();y&&is(this,N8).feed(p.decode(y,{stream:!N})),N&&(Z=!1,is(this,N8).reset(),jv(this,_2,vKe).call(this))}while(Z)}),Yb(this,QKe,I=>{Gd(this,$k,void 0),!(I.name==="AbortError"||I.type==="aborted")&&jv(this,_2,vKe).call(this,YKe(I))}),Yb(this,FKe,I=>{typeof I.id=="string"&&Gd(this,Lde,I.id);let a=new MessageEvent(I.event||"message",{data:I.data,origin:is(this,g8)?is(this,g8).origin:is(this,GO).origin,lastEventId:I.id||""});is(this,W8)&&(!I.event||I.event==="message")&&is(this,W8).call(this,a),this.dispatchEvent(a)}),Yb(this,CKe,I=>{Gd(this,kde,I)}),Yb(this,fKe,()=>{Gd(this,y8,void 0),is(this,eN)===this.CONNECTING&&jv(this,_2,VKe).call(this)});try{if(e instanceof URL)Gd(this,GO,e);else if(typeof e=="string")Gd(this,GO,new URL(e,n2n()));else throw new Error("Invalid URL")}catch{throw l2n("An invalid or illegal string was specified")}Gd(this,N8,M1e({onEvent:is(this,FKe),onRetry:is(this,CKe)})),Gd(this,eN,this.CONNECTING),Gd(this,kde,3e3),Gd(this,z1e,(n=l?.fetch)!=null?n:globalThis.fetch),Gd(this,_1e,(r=l?.withCredentials)!=null?r:!1),jv(this,_2,VKe).call(this)}get readyState(){return is(this,eN)}get url(){return is(this,GO).href}get withCredentials(){return is(this,_1e)}get onerror(){return is(this,E8)}set onerror(e){Gd(this,E8,e)}get onmessage(){return is(this,W8)}set onmessage(e){Gd(this,W8,e)}get onopen(){return is(this,Hde)}set onopen(e){Gd(this,Hde,e)}addEventListener(e,l,n){let r=l;super.addEventListener(e,r,n)}removeEventListener(e,l,n){let r=l;super.removeEventListener(e,r,n)}close(){is(this,y8)&&clearTimeout(is(this,y8)),is(this,eN)!==this.CLOSED&&(is(this,$k)&&is(this,$k).abort(),Gd(this,eN,this.CLOSED),Gd(this,$k,void 0))}};eN=new WeakMap,GO=new WeakMap,g8=new WeakMap,_1e=new WeakMap,z1e=new WeakMap,kde=new WeakMap,y8=new WeakMap,Lde=new WeakMap,$k=new WeakMap,N8=new WeakMap,E8=new WeakMap,W8=new WeakMap,Hde=new WeakMap,_2=new WeakSet,VKe=function(){Gd(this,eN,this.CONNECTING),Gd(this,$k,new AbortController),is(this,z1e)(is(this,GO),jv(this,_2,xTt).call(this)).then(is(this,wKe)).catch(is(this,QKe))},wKe=new WeakMap,QKe=new WeakMap,xTt=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...is(this,Lde)?{"Last-Event-ID":is(this,Lde)}:void 0},cache:"no-store",signal:(t=is(this,$k))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},FKe=new WeakMap,CKe=new WeakMap,Xde=function(t,e){var l;is(this,eN)!==this.CLOSED&&Gd(this,eN,this.CLOSED);let n=new D1e("error",{code:e,message:t});(l=is(this,E8))==null||l.call(this,n),this.dispatchEvent(n)},vKe=function(t,e){var l;if(is(this,eN)===this.CLOSED)return;Gd(this,eN,this.CONNECTING);let n=new D1e("error",{code:e,message:t});(l=is(this,E8))==null||l.call(this,n),this.dispatchEvent(n),Gd(this,y8,setTimeout(is(this,fKe),is(this,kde)))},fKe=new WeakMap,pO.CONNECTING=0,pO.OPEN=1,pO.CLOSED=2;function n2n(){let t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}c();c();var XKe;XKe=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(t=>t.webcrypto);async function r2n(t){return(await XKe).getRandomValues(new Uint8Array(t))}async function I2n(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",l="",n=await r2n(t);for(let r=0;r<t;r++){let I=n[r]%e.length;l+=e[I]}return l}async function a2n(t){return await I2n(t)}async function s2n(t){let e=await(await XKe).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function kKe(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;let e=await a2n(t),l=await s2n(e);return{code_verifier:e,code_challenge:l}}c();var CG=z.string().url().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:z.ZodIssueCode.custom,message:"URL must be parseable",fatal:!0}),z.NEVER}).refine(t=>{let e=new URL(t);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),BTt=z.object({resource:z.string().url(),authorization_servers:z.array(CG).optional(),jwks_uri:z.string().url().optional(),scopes_supported:z.array(z.string()).optional(),bearer_methods_supported:z.array(z.string()).optional(),resource_signing_alg_values_supported:z.array(z.string()).optional(),resource_name:z.string().optional(),resource_documentation:z.string().optional(),resource_policy_uri:z.string().url().optional(),resource_tos_uri:z.string().url().optional(),tls_client_certificate_bound_access_tokens:z.boolean().optional(),authorization_details_types_supported:z.array(z.string()).optional(),dpop_signing_alg_values_supported:z.array(z.string()).optional(),dpop_bound_access_tokens_required:z.boolean().optional()}).passthrough(),LKe=z.object({issuer:z.string(),authorization_endpoint:CG,token_endpoint:CG,registration_endpoint:CG.optional(),scopes_supported:z.array(z.string()).optional(),response_types_supported:z.array(z.string()),response_modes_supported:z.array(z.string()).optional(),grant_types_supported:z.array(z.string()).optional(),token_endpoint_auth_methods_supported:z.array(z.string()).optional(),token_endpoint_auth_signing_alg_values_supported:z.array(z.string()).optional(),service_documentation:CG.optional(),revocation_endpoint:CG.optional(),revocation_endpoint_auth_methods_supported:z.array(z.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:z.array(z.string()).optional(),introspection_endpoint:z.string().optional(),introspection_endpoint_auth_methods_supported:z.array(z.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:z.array(z.string()).optional(),code_challenge_methods_supported:z.array(z.string()).optional()}).passthrough(),o2n=z.object({issuer:z.string(),authorization_endpoint:CG,token_endpoint:CG,userinfo_endpoint:CG.optional(),jwks_uri:CG,registration_endpoint:CG.optional(),scopes_supported:z.array(z.string()).optional(),response_types_supported:z.array(z.string()),response_modes_supported:z.array(z.string()).optional(),grant_types_supported:z.array(z.string()).optional(),acr_values_supported:z.array(z.string()).optional(),subject_types_supported:z.array(z.string()),id_token_signing_alg_values_supported:z.array(z.string()),id_token_encryption_alg_values_supported:z.array(z.string()).optional(),id_token_encryption_enc_values_supported:z.array(z.string()).optional(),userinfo_signing_alg_values_supported:z.array(z.string()).optional(),userinfo_encryption_alg_values_supported:z.array(z.string()).optional(),userinfo_encryption_enc_values_supported:z.array(z.string()).optional(),request_object_signing_alg_values_supported:z.array(z.string()).optional(),request_object_encryption_alg_values_supported:z.array(z.string()).optional(),request_object_encryption_enc_values_supported:z.array(z.string()).optional(),token_endpoint_auth_methods_supported:z.array(z.string()).optional(),token_endpoint_auth_signing_alg_values_supported:z.array(z.string()).optional(),display_values_supported:z.array(z.string()).optional(),claim_types_supported:z.array(z.string()).optional(),claims_supported:z.array(z.string()).optional(),service_documentation:z.string().optional(),claims_locales_supported:z.array(z.string()).optional(),ui_locales_supported:z.array(z.string()).optional(),claims_parameter_supported:z.boolean().optional(),request_parameter_supported:z.boolean().optional(),request_uri_parameter_supported:z.boolean().optional(),require_request_uri_registration:z.boolean().optional(),op_policy_uri:CG.optional(),op_tos_uri:CG.optional()}).passthrough(),OTt=o2n.merge(LKe.pick({code_challenge_methods_supported:!0})),JKe=z.object({access_token:z.string(),id_token:z.string().optional(),token_type:z.string(),expires_in:z.number().optional(),scope:z.string().optional(),refresh_token:z.string().optional()}).strip(),TTt=z.object({error:z.string(),error_description:z.string().optional(),error_uri:z.string().optional()}),i2n=z.object({redirect_uris:z.array(CG),token_endpoint_auth_method:z.string().optional(),grant_types:z.array(z.string()).optional(),response_types:z.array(z.string()).optional(),client_name:z.string().optional(),client_uri:CG.optional(),logo_uri:CG.optional(),scope:z.string().optional(),contacts:z.array(z.string()).optional(),tos_uri:CG.optional(),policy_uri:z.string().optional(),jwks_uri:CG.optional(),jwks:z.any().optional(),software_id:z.string().optional(),software_version:z.string().optional(),software_statement:z.string().optional()}).strip(),c2n=z.object({client_id:z.string(),client_secret:z.string().optional(),client_id_issued_at:z.number().optional(),client_secret_expires_at:z.number().optional()}).strip(),UTt=i2n.merge(c2n),uNa=z.object({error:z.string(),error_description:z.string().optional()}).strip(),mNa=z.object({token:z.string(),token_type_hint:z.string().optional()}).strip();c();function MTt(t){let e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function _Tt({requestedResource:t,configuredResource:e}){let l=typeof t=="string"?new URL(t):new URL(t.href),n=typeof e=="string"?new URL(e):new URL(e.href);if(l.origin!==n.origin||l.pathname.length<n.pathname.length)return!1;let r=l.pathname.endsWith("/")?l.pathname:l.pathname+"/",I=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return r.startsWith(I)}c();var Mm=class extends Error{constructor(e,l){super(e),this.errorUri=l,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}},Jde=class extends Mm{};Jde.errorCode="invalid_request";var hO=class extends Mm{};hO.errorCode="invalid_client";var AO=class extends Mm{};AO.errorCode="invalid_grant";var ZO=class extends Mm{};ZO.errorCode="unauthorized_client";var xde=class extends Mm{};xde.errorCode="unsupported_grant_type";var Sde=class extends Mm{};Sde.errorCode="invalid_scope";var Bde=class extends Mm{};Bde.errorCode="access_denied";var Kv=class extends Mm{};Kv.errorCode="server_error";var Ode=class extends Mm{};Ode.errorCode="temporarily_unavailable";var Tde=class extends Mm{};Tde.errorCode="unsupported_response_type";var Ude=class extends Mm{};Ude.errorCode="unsupported_token_type";var Mde=class extends Mm{};Mde.errorCode="invalid_token";var _de=class extends Mm{};_de.errorCode="method_not_allowed";var Dde=class extends Mm{};Dde.errorCode="too_many_requests";var zde=class extends Mm{};zde.errorCode="invalid_client_metadata";var Pde=class extends Mm{};Pde.errorCode="insufficient_scope";var DTt={[Jde.errorCode]:Jde,[hO.errorCode]:hO,[AO.errorCode]:AO,[ZO.errorCode]:ZO,[xde.errorCode]:xde,[Sde.errorCode]:Sde,[Bde.errorCode]:Bde,[Kv.errorCode]:Kv,[Ode.errorCode]:Ode,[Tde.errorCode]:Tde,[Ude.errorCode]:Ude,[Mde.errorCode]:Mde,[_de.errorCode]:_de,[Dde.errorCode]:Dde,[zde.errorCode]:zde,[Pde.errorCode]:Pde};var tN=class extends Error{constructor(e){super(e??"Unauthorized")}};function PTt(t,e){let l=t.client_secret!==void 0;return e.length===0?l?"client_secret_post":"none":l&&e.includes("client_secret_basic")?"client_secret_basic":l&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":l?"client_secret_post":"none"}function jTt(t,e,l,n){let{client_id:r,client_secret:I}=e;switch(t){case"client_secret_basic":d2n(r,I,l);return;case"client_secret_post":u2n(r,I,n);return;case"none":m2n(r,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function d2n(t,e,l){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");let n=btoa(`${t}:${e}`);l.set("Authorization",`Basic ${n}`)}function u2n(t,e,l){l.set("client_id",t),e&&l.set("client_secret",e)}function m2n(t,e){e.set("client_id",t)}async function SKe(t){let e=t instanceof Response?t.status:void 0,l=t instanceof Response?await t.text():t;try{let n=TTt.parse(JSON.parse(l)),{error:r,error_description:I,error_uri:a}=n,s=DTt[r]||Kv;return new s(I||"",a)}catch(n){let r=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${l}`;return new Kv(r)}}async function eL(t,e){var l,n;try{return await xKe(t,e)}catch(r){if(r instanceof hO||r instanceof ZO)return await((l=t.invalidateCredentials)===null||l===void 0?void 0:l.call(t,"all")),await xKe(t,e);if(r instanceof AO)return await((n=t.invalidateCredentials)===null||n===void 0?void 0:n.call(t,"tokens")),await xKe(t,e);throw r}}async function xKe(t,{serverUrl:e,authorizationCode:l,scope:n,resourceMetadataUrl:r,fetchFn:I}){let a,s;try{a=await G2n(e,{resourceMetadataUrl:r},I),a.authorization_servers&&a.authorization_servers.length>0&&(s=a.authorization_servers[0])}catch{}s||(s=e);let o=await b2n(e,t,a),d=await g2n(s,{fetchFn:I}),u=await Promise.resolve(t.clientInformation());if(!u){if(l!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let N=await E2n(s,{metadata:d,clientMetadata:t.clientMetadata,fetchFn:I});await t.saveClientInformation(N),u=N}if(l!==void 0){let N=await t.codeVerifier(),y=await W2n(s,{metadata:d,clientInformation:u,authorizationCode:l,codeVerifier:N,redirectUri:t.redirectUrl,resource:o,addClientAuthentication:t.addClientAuthentication,fetchFn:I});return await t.saveTokens(y),"AUTHORIZED"}let b=await t.tokens();if(b?.refresh_token)try{let N=await y2n(s,{metadata:d,clientInformation:u,refreshToken:b.refresh_token,resource:o,addClientAuthentication:t.addClientAuthentication,fetchFn:I});return await t.saveTokens(N),"AUTHORIZED"}catch(N){if(!(!(N instanceof Mm)||N instanceof Kv))throw N}let p=t.state?await t.state():void 0,{authorizationUrl:h,codeVerifier:Z}=await N2n(s,{metadata:d,clientInformation:u,state:p,redirectUrl:t.redirectUrl,scope:n||t.clientMetadata.scope,resource:o});return await t.saveCodeVerifier(Z),await t.redirectToAuthorization(h),"REDIRECT"}async function b2n(t,e,l){let n=MTt(t);if(e.validateResourceURL)return await e.validateResourceURL(n,l?.resource);if(l){if(!_Tt({requestedResource:n,configuredResource:l.resource}))throw new Error(`Protected resource ${l.resource} does not match expected ${n} (or origin)`);return new URL(l.resource)}}function jde(t){let e=t.headers.get("WWW-Authenticate");if(!e)return;let[l,n]=e.split(" ");if(l.toLowerCase()!=="bearer"||!n)return;let I=/resource_metadata="([^"]*)"/.exec(e);if(I)try{return new URL(I[1])}catch{return}}async function G2n(t,e,l=fetch){let n=await A2n(t,"oauth-protected-resource",l,{protocolVersion:e?.protocolVersion,metadataUrl:e?.resourceMetadataUrl});if(!n||n.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return BTt.parse(await n.json())}async function BKe(t,e,l=fetch){try{return await l(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?BKe(t,void 0,l):void 0;throw n}}function p2n(t,e="",l={}){return e.endsWith("/")&&(e=e.slice(0,-1)),l.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function zTt(t,e,l=fetch){return await BKe(t,{"MCP-Protocol-Version":e},l)}function h2n(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function A2n(t,e,l,n){var r,I;let a=new URL(t),s=(r=n?.protocolVersion)!==null&&r!==void 0?r:I8,o;if(n?.metadataUrl)o=new URL(n.metadataUrl);else{let u=p2n(e,a.pathname);o=new URL(u,(I=n?.metadataServerUrl)!==null&&I!==void 0?I:a),o.search=a.search}let d=await zTt(o,s,l);if(!n?.metadataUrl&&h2n(d,a.pathname)){let u=new URL(`/.well-known/${e}`,a);d=await zTt(u,s,l)}return d}function Z2n(t){let e=typeof t=="string"?new URL(t):t,l=e.pathname!=="/",n=[];if(!l)return n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),n;let r=e.pathname;return r.endsWith("/")&&(r=r.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${r}`,e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${r}`,e.origin),type:"oidc"}),n.push({url:new URL(`${r}/.well-known/openid-configuration`,e.origin),type:"oidc"}),n}async function g2n(t,{fetchFn:e=fetch,protocolVersion:l=I8}={}){var n;let r={"MCP-Protocol-Version":l},I=Z2n(t);for(let{url:a,type:s}of I){let o=await BKe(a,r,e);if(o){if(!o.ok){if(o.status>=400&&o.status<500)continue;throw new Error(`HTTP ${o.status} trying to load ${s==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}if(s==="oauth")return LKe.parse(await o.json());{let d=OTt.parse(await o.json());if(!(!((n=d.code_challenge_methods_supported)===null||n===void 0)&&n.includes("S256")))throw new Error(`Incompatible OIDC provider at ${a}: does not support S256 code challenge method required by MCP specification`);return d}}}}async function N2n(t,{metadata:e,clientInformation:l,redirectUrl:n,scope:r,state:I,resource:a}){let s="code",o="S256",d;if(e){if(d=new URL(e.authorization_endpoint),!e.response_types_supported.includes(s))throw new Error(`Incompatible auth server: does not support response type ${s}`);if(!e.code_challenge_methods_supported||!e.code_challenge_methods_supported.includes(o))throw new Error(`Incompatible auth server: does not support code challenge method ${o}`)}else d=new URL("/authorize",t);let u=await kKe(),b=u.code_verifier,p=u.code_challenge;return d.searchParams.set("response_type",s),d.searchParams.set("client_id",l.client_id),d.searchParams.set("code_challenge",p),d.searchParams.set("code_challenge_method",o),d.searchParams.set("redirect_uri",String(n)),I&&d.searchParams.set("state",I),r&&d.searchParams.set("scope",r),r?.includes("offline_access")&&d.searchParams.append("prompt","consent"),a&&d.searchParams.set("resource",a.href),{authorizationUrl:d,codeVerifier:b}}async function W2n(t,{metadata:e,clientInformation:l,authorizationCode:n,codeVerifier:r,redirectUri:I,resource:a,addClientAuthentication:s,fetchFn:o}){var d;let u="authorization_code",b=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",t);if(e?.grant_types_supported&&!e.grant_types_supported.includes(u))throw new Error(`Incompatible auth server: does not support grant type ${u}`);let p=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),h=new URLSearchParams({grant_type:u,code:n,code_verifier:r,redirect_uri:String(I)});if(s)s(p,h,t,e);else{let N=(d=e?.token_endpoint_auth_methods_supported)!==null&&d!==void 0?d:[],y=PTt(l,N);jTt(y,l,p,h)}a&&h.set("resource",a.href);let Z=await(o??fetch)(b,{method:"POST",headers:p,body:h});if(!Z.ok)throw await SKe(Z);return JKe.parse(await Z.json())}async function y2n(t,{metadata:e,clientInformation:l,refreshToken:n,resource:r,addClientAuthentication:I,fetchFn:a}){var s;let o="refresh_token",d;if(e){if(d=new URL(e.token_endpoint),e.grant_types_supported&&!e.grant_types_supported.includes(o))throw new Error(`Incompatible auth server: does not support grant type ${o}`)}else d=new URL("/token",t);let u=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),b=new URLSearchParams({grant_type:o,refresh_token:n});if(I)I(u,b,t,e);else{let h=(s=e?.token_endpoint_auth_methods_supported)!==null&&s!==void 0?s:[],Z=PTt(l,h);jTt(Z,l,u,b)}r&&b.set("resource",r.href);let p=await(a??fetch)(d,{method:"POST",headers:u,body:b});if(!p.ok)throw await SKe(p);return JKe.parse({refresh_token:n,...await p.json()})}async function E2n(t,{metadata:e,clientMetadata:l,fetchFn:n}){let r;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");r=new URL(e.registration_endpoint)}else r=new URL("/register",t);let I=await(n??fetch)(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!I.ok)throw await SKe(I);return UTt.parse(await I.json())}var OKe=class extends Error{constructor(e,l,n){super(`SSE error: ${l}`),this.code=e,this.event=n}},P1e=class{constructor(e,l){this._url=e,this._resourceMetadataUrl=void 0,this._eventSourceInit=l?.eventSourceInit,this._requestInit=l?.requestInit,this._authProvider=l?.authProvider,this._fetch=l?.fetch}async _authThenStart(){var e;if(!this._authProvider)throw new tN("No auth provider");let l;try{l=await eL(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(l!=="AUTHORIZED")throw new tN;return await this._startOrAuth()}async _commonHeaders(){var e;let l={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(l.Authorization=`Bearer ${n.access_token}`)}return this._protocolVersion&&(l["mcp-protocol-version"]=this._protocolVersion),new Headers({...l,...(e=this._requestInit)===null||e===void 0?void 0:e.headers})}_startOrAuth(){var e,l,n;let r=(n=(l=(e=this===null||this===void 0?void 0:this._eventSourceInit)===null||e===void 0?void 0:e.fetch)!==null&&l!==void 0?l:this._fetch)!==null&&n!==void 0?n:fetch;return new Promise((I,a)=>{this._eventSource=new pO(this._url.href,{...this._eventSourceInit,fetch:async(s,o)=>{let d=await this._commonHeaders();d.set("Accept","text/event-stream");let u=await r(s,{...o,headers:d});return u.status===401&&u.headers.has("www-authenticate")&&(this._resourceMetadataUrl=jde(u)),u}}),this._abortController=new AbortController,this._eventSource.onerror=s=>{var o;if(s.code===401&&this._authProvider){this._authThenStart().then(I,a);return}let d=new OKe(s.code,s.message,s);a(d),(o=this.onerror)===null||o===void 0||o.call(this,d)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",s=>{var o;let d=s;try{if(this._endpoint=new URL(d.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(u){a(u),(o=this.onerror)===null||o===void 0||o.call(this,u),this.close();return}I()}),this._eventSource.onmessage=s=>{var o,d;let u=s,b;try{b=Mk.parse(JSON.parse(u.data))}catch(p){(o=this.onerror)===null||o===void 0||o.call(this,p);return}(d=this.onmessage)===null||d===void 0||d.call(this,b)}})}async start(){if(this._eventSource)throw new 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 tN("No auth provider");if(await eL(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new tN("Failed to authorize")}async close(){var e,l,n;(e=this._abortController)===null||e===void 0||e.abort(),(l=this._eventSource)===null||l===void 0||l.close(),(n=this.onclose)===null||n===void 0||n.call(this)}async send(e){var l,n,r;if(!this._endpoint)throw new Error("Not connected");try{let I=await this._commonHeaders();I.set("content-type","application/json");let a={...this._requestInit,method:"POST",headers:I,body:JSON.stringify(e),signal:(l=this._abortController)===null||l===void 0?void 0:l.signal},s=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._endpoint,a);if(!s.ok){if(s.status===401&&this._authProvider){if(this._resourceMetadataUrl=jde(s),await eL(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new tN;return this.send(e)}let o=await s.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${s.status}): ${o}`)}}catch(I){throw(r=this.onerror)===null||r===void 0||r.call(this,I),I}}setProtocolVersion(e){this._protocolVersion=e}};c();var SUt=nt(JUt(),1);import $1e from"node:process";import{PassThrough as q2n}from"node:stream";c();var K1e=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
1953
1953
  `);if(e===-1)return null;let l=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),K2n(l)}clear(){this._buffer=void 0}};function K2n(t){return Mk.parse(JSON.parse(t))}function xUt(t){return JSON.stringify(t)+`
1954
- `}var $2n=$1e.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function eYn(){let t={};for(let e of $2n){let l=$1e.env[e];l!==void 0&&(l.startsWith("()")||(t[e]=l))}return t}var q1e=class{constructor(e){this._abortController=new AbortController,this._readBuffer=new K1e,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new q2n)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,l)=>{var n,r,I,a,s;this._process=(0,SUt.default)(this._serverParams.command,(n=this._serverParams.args)!==null&&n!==void 0?n:[],{env:{...eYn(),...this._serverParams.env},stdio:["pipe","pipe",(r=this._serverParams.stderr)!==null&&r!==void 0?r:"inherit"],shell:!1,signal:this._abortController.signal,windowsHide:$1e.platform==="win32"&&tYn(),cwd:this._serverParams.cwd}),this._process.on("error",o=>{var d,u;if(o.name==="AbortError"){(d=this.onclose)===null||d===void 0||d.call(this);return}l(o),(u=this.onerror)===null||u===void 0||u.call(this,o)}),this._process.on("spawn",()=>{e()}),this._process.on("close",o=>{var d;this._process=void 0,(d=this.onclose)===null||d===void 0||d.call(this)}),(I=this._process.stdin)===null||I===void 0||I.on("error",o=>{var d;(d=this.onerror)===null||d===void 0||d.call(this,o)}),(a=this._process.stdout)===null||a===void 0||a.on("data",o=>{this._readBuffer.append(o),this.processReadBuffer()}),(s=this._process.stdout)===null||s===void 0||s.on("error",o=>{var d;(d=this.onerror)===null||d===void 0||d.call(this,o)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){var e,l;return this._stderrStream?this._stderrStream:(l=(e=this._process)===null||e===void 0?void 0:e.stderr)!==null&&l!==void 0?l:null}get pid(){var e,l;return(l=(e=this._process)===null||e===void 0?void 0:e.pid)!==null&&l!==void 0?l:null}processReadBuffer(){for(var e,l;;)try{let n=this._readBuffer.readMessage();if(n===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,n)}catch(n){(l=this.onerror)===null||l===void 0||l.call(this,n)}}async close(){this._abortController.abort(),this._process=void 0,this._readBuffer.clear()}send(e){return new Promise(l=>{var n;if(!(!((n=this._process)===null||n===void 0)&&n.stdin))throw new Error("Not connected");let r=xUt(e);this._process.stdin.write(r)?l():this._process.stdin.once("drain",l)})}};function tYn(){return"type"in $1e}c();c();var eVe=class extends TransformStream{constructor({onError:e,onRetry:l,onComment:n}={}){let r;super({start(I){r=M1e({onEvent:a=>{I.enqueue(a)},onError(a){e==="terminate"?I.error(a):typeof e=="function"&&e(a)},onRetry:l,onComment:n})},transform(I){r.feed(I)}})}};var lYn={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Kde=class extends Error{constructor(e,l){super(`Streamable HTTP error: ${l}`),this.code=e}},tVe=class{constructor(e,l){var n;this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=l?.requestInit,this._authProvider=l?.authProvider,this._fetch=l?.fetch,this._sessionId=l?.sessionId,this._reconnectionOptions=(n=l?.reconnectionOptions)!==null&&n!==void 0?n:lYn}async _authThenStart(){var e;if(!this._authProvider)throw new tN("No auth provider");let l;try{l=await eL(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(l!=="AUTHORIZED")throw new tN;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let l={};if(this._authProvider){let r=await this._authProvider.tokens();r&&(l.Authorization=`Bearer ${r.access_token}`)}this._sessionId&&(l["mcp-session-id"]=this._sessionId),this._protocolVersion&&(l["mcp-protocol-version"]=this._protocolVersion);let n=this._normalizeHeaders((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...l,...n})}async _startOrAuthSse(e){var l,n,r;let{resumptionToken:I}=e;try{let a=await this._commonHeaders();a.set("Accept","text/event-stream"),I&&a.set("last-event-id",I);let s=await((l=this._fetch)!==null&&l!==void 0?l:fetch)(this._url,{method:"GET",headers:a,signal:(n=this._abortController)===null||n===void 0?void 0:n.signal});if(!s.ok){if(s.status===401&&this._authProvider)return await this._authThenStart();if(s.status===405)return;throw new Kde(s.status,`Failed to open SSE stream: ${s.statusText}`)}this._handleSseStream(s.body,e,!0)}catch(a){throw(r=this.onerror)===null||r===void 0||r.call(this,a),a}}_getNextReconnectionDelay(e){let l=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,r=this._reconnectionOptions.maxReconnectionDelay;return Math.min(l*Math.pow(n,e),r)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,l=0){var n;let r=this._reconnectionOptions.maxRetries;if(r>0&&l>=r){(n=this.onerror)===null||n===void 0||n.call(this,new Error(`Maximum reconnection attempts (${r}) exceeded.`));return}let I=this._getNextReconnectionDelay(l);setTimeout(()=>{this._startOrAuthSse(e).catch(a=>{var s;(s=this.onerror)===null||s===void 0||s.call(this,new Error(`Failed to reconnect SSE stream: ${a instanceof Error?a.message:String(a)}`)),this._scheduleReconnection(e,l+1)})},I)}_handleSseStream(e,l,n){if(!e)return;let{onresumptiontoken:r,replayMessageId:I}=l,a;(async()=>{var o,d,u,b;try{let p=e.pipeThrough(new TextDecoderStream).pipeThrough(new eVe).getReader();for(;;){let{value:h,done:Z}=await p.read();if(Z)break;if(h.id&&(a=h.id,r?.(h.id)),!h.event||h.event==="message")try{let N=Mk.parse(JSON.parse(h.data));I!==void 0&&rde(N)&&(N.id=I),(o=this.onmessage)===null||o===void 0||o.call(this,N)}catch(N){(d=this.onerror)===null||d===void 0||d.call(this,N)}}}catch(p){if((u=this.onerror)===null||u===void 0||u.call(this,new Error(`SSE stream disconnected: ${p}`)),n&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:I},0)}catch(h){(b=this.onerror)===null||b===void 0||b.call(this,new Error(`Failed to reconnect: ${h instanceof Error?h.message:String(h)}`))}}})()}async start(){if(this._abortController)throw new 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 tN("No auth provider");if(await eL(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new tN("Failed to authorize")}async close(){var e,l;(e=this._abortController)===null||e===void 0||e.abort(),(l=this.onclose)===null||l===void 0||l.call(this)}async send(e,l){var n,r,I,a;try{let{resumptionToken:s,onresumptiontoken:o}=l||{};if(s){this._startOrAuthSse({resumptionToken:s,replayMessageId:$Ye(e)?e.id:void 0}).catch(y=>{var Y;return(Y=this.onerror)===null||Y===void 0?void 0:Y.call(this,y)});return}let d=await this._commonHeaders();d.set("content-type","application/json"),d.set("accept","application/json, text/event-stream");let u={...this._requestInit,method:"POST",headers:d,body:JSON.stringify(e),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},b=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,u),p=b.headers.get("mcp-session-id");if(p&&(this._sessionId=p),!b.ok){if(b.status===401&&this._authProvider){if(this._resourceMetadataUrl=jde(b),await eL(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new tN;return this.send(e)}let y=await b.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${b.status}): ${y}`)}if(b.status===202){jBt(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(y=>{var Y;return(Y=this.onerror)===null||Y===void 0?void 0:Y.call(this,y)});return}let Z=(Array.isArray(e)?e:[e]).filter(y=>"method"in y&&"id"in y&&y.id!==void 0).length>0,N=b.headers.get("content-type");if(Z)if(N?.includes("text/event-stream"))this._handleSseStream(b.body,{onresumptiontoken:o},!1);else if(N?.includes("application/json")){let y=await b.json(),Y=Array.isArray(y)?y.map(w=>Mk.parse(w)):[Mk.parse(y)];for(let w of Y)(I=this.onmessage)===null||I===void 0||I.call(this,w)}else throw new Kde(-1,`Unexpected content type: ${N}`)}catch(s){throw(a=this.onerror)===null||a===void 0||a.call(this,s),s}}get sessionId(){return this._sessionId}async terminateSession(){var e,l,n;if(this._sessionId)try{let r=await this._commonHeaders(),I={...this._requestInit,method:"DELETE",headers:r,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},a=await((l=this._fetch)!==null&&l!==void 0?l:fetch)(this._url,I);if(!a.ok&&a.status!==405)throw new Kde(a.status,`Failed to terminate session: ${a.statusText}`);this._sessionId=void 0}catch(r){throw(n=this.onerror)===null||n===void 0||n.call(this,r),r}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}};c();var lVe=class{constructor(e){this.server=e}onmessage;onerror;onclose;serverTransport;closed=!1;async start(){if(this.closed)throw new Error("Transport is closed");this.serverTransport=new qKe(this),await this.server.connect(this.serverTransport)}async send(e){if(this.closed)throw new Error("Transport is closed");setImmediate(()=>{try{this.serverTransport?.onmessage?.(e)}catch(l){this.onerror?.(l instanceof Error?l:new Error(String(l)))}})}receive(e){this.closed||this.onmessage?.(e)}async close(){this.closed||(this.closed=!0,await this.serverTransport?.close(),this.onclose?.())}},qKe=class{constructor(e){this.clientTransport=e}onmessage;onerror;onclose;closed=!1;async start(){}async send(e){if(this.closed)throw new Error("Transport is closed");setImmediate(()=>{try{this.clientTransport.receive(e)}catch(l){this.onerror?.(l instanceof Error?l:new Error(String(l)))}})}async close(){this.closed||(this.closed=!0,this.onclose?.())}};var nVe=class{createTransport(e){switch(e.type){case"stdio":{let l=new q1e({command:e.command,args:e.args,env:e.env,stderr:e.stderr?"pipe":void 0});return l.stderr?.pipe(e.stderr),l}case"http":return new tVe(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"sse":return new P1e(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"memory":return new lVe(e.server);default:throw new Error(`Unsupported transport type: ${e.type}`)}}};c();var gO="blackbird-mcp-server",V8="github-mcp-server",$Ke="playwright";function w8(t){return t.type===void 0||t.type.toLowerCase()==="local"||t.type.toLowerCase()==="stdio"}function Q8(t){return qde(t)||$de(t)}function qde(t){return t.type?.toLowerCase()==="http"}function $de(t){return t.type?.toLowerCase()==="sse"}function eue(t){return t.type?.toLowerCase()==="memory"}var e8e=class extends nYn{constructor(l,n){super({decodeStrings:!1});this.serverName=l;this.logger=n}_write(l,n,r){try{let I=l.toString();this.logger.log(`[mcp server ${this.serverName} stderr] ${I}`),r()}catch(I){r(I instanceof Error?I:new Error(String(I)))}}},rVe=class{constructor(e,l=new T1e,n=new nVe,r="indirect"){this.logger=e;this.clientFactory=l;this.transportFactory=n;this.envValueMode=r}clients={};transports={};async startLocalMcpClient(e,l,n,r){this.logger.log(`Starting MCP client for ${e} with command: ${n} and args: ${r}`);let I=new e8e(e,this.logger),a={type:"stdio",command:n,args:r,env:{...l,PATH:process.env.PATH},stderr:I},s=this.transportFactory.createTransport(a);await this.setupAndConnectClient(e,s)}async startHttpMcpClient(e,l){this.logger.log(`Starting remote MCP client for ${e} with url: ${l.url}`);let n={type:"http",url:l.url,headers:l.headers},r=this.transportFactory.createTransport(n);await this.setupAndConnectClient(e,r)}async startSseMcpClient(e,l){this.logger.log(`Starting remote MCP client for ${e} with url: ${l.url}`);let n={type:"sse",url:l.url,headers:l.headers},r=this.transportFactory.createTransport(n);await this.setupAndConnectClient(e,r)}async startInMemoryMcpClient(e,l){this.logger.log(`Starting in-memory MCP client for ${e}`);let n={type:"memory",server:l},r=this.transportFactory.createTransport(n);await this.setupAndConnectClient(e,r)}async setupAndConnectClient(e,l){this.transports[e]=l,l.onclose=()=>{this.logger.log(`MCP transport for ${e} closed`),delete this.transports[e]},this.logger.log(`Creating MCP client for ${e}...`);let n=this.clientFactory.createClient({name:"github-copilot-developer",version:"1.0.0"},{capabilities:{experimental:void 0,roots:void 0,sampling:void 0}}),r=Date.now();this.logger.log(`Connecting MCP client for ${e}...`),await n.connect(l),n.onclose=()=>{this.logger.log(`MCP client for ${e} closed`),delete this.clients[e]},n.onerror=I=>{this.logger.error(`MCP client for ${e} errored ${I}`)},this.logger.log(`MCP client for ${e} connected, took ${Date.now()-r}ms`),this.clients[e]=n}async getTools(e,l){let n={};for(let[r,I]of Object.entries(this.clients)){let a=[];try{this.logger.log(`Fetching tools from client: ${r}`);let s=await I.listTools(),o=e?.mcpServers[r].tools,d=e?.mcpServers[r].filterMapping;for(let b of s.tools){if(b.name==="get_copilot_space")continue;if(!(o?.includes("*")||o?.includes(b.name))){this.logger.log(`Tool ${b.name} is not in the allowed list for client: ${r}`);continue}let h=jye(r,b.name),Z=`${r}-${b.name}`,N;typeof d=="string"?N=bOe(d):N=bOe(d?.[b.name]??"hidden_characters"),n[`${r}/${b.name}`]={name:Z,namespacedName:`${r}/${b.name}`,title:b.title??b.annotations?.title??b.name,description:b.description??Z,input_schema:b.inputSchema,readOnly:b.annotations?.readOnlyHint,safeForTelemetry:{name:!!(e?.mcpServers[r].isDefaultServer||h),inputsNames:!!e?.mcpServers[r].isDefaultServer},filterMode:N},a.push(b.name),this.logger.log(`Tool ${b.name} added to tools list for client: ${r}`)}this.logger.log(`Successfully retrieved ${a.length} tools from client: ${r}`);let u=I.getServerVersion();await this.logServerSuccessWithTools(r,a,u,l)}catch(s){this.logger.error(`Failed to get tools from client: ${r} ${s}`)}}return this.logger.log(`All tools retrieved: ${JSON.stringify(n,null,2)}`),n}async logServerSuccessWithTools(e,l,n,r){if(e!=gO&&r)try{let I=l.map(o=>`- ${o}`).join(`
1954
+ `}var $2n=$1e.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function eYn(){let t={};for(let e of $2n){let l=$1e.env[e];l!==void 0&&(l.startsWith("()")||(t[e]=l))}return t}var q1e=class{constructor(e){this._abortController=new AbortController,this._readBuffer=new K1e,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new q2n)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,l)=>{var n,r,I,a,s;this._process=(0,SUt.default)(this._serverParams.command,(n=this._serverParams.args)!==null&&n!==void 0?n:[],{env:{...eYn(),...this._serverParams.env},stdio:["pipe","pipe",(r=this._serverParams.stderr)!==null&&r!==void 0?r:"inherit"],shell:!1,signal:this._abortController.signal,windowsHide:$1e.platform==="win32"&&tYn(),cwd:this._serverParams.cwd}),this._process.on("error",o=>{var d,u;if(o.name==="AbortError"){(d=this.onclose)===null||d===void 0||d.call(this);return}l(o),(u=this.onerror)===null||u===void 0||u.call(this,o)}),this._process.on("spawn",()=>{e()}),this._process.on("close",o=>{var d;this._process=void 0,(d=this.onclose)===null||d===void 0||d.call(this)}),(I=this._process.stdin)===null||I===void 0||I.on("error",o=>{var d;(d=this.onerror)===null||d===void 0||d.call(this,o)}),(a=this._process.stdout)===null||a===void 0||a.on("data",o=>{this._readBuffer.append(o),this.processReadBuffer()}),(s=this._process.stdout)===null||s===void 0||s.on("error",o=>{var d;(d=this.onerror)===null||d===void 0||d.call(this,o)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){var e,l;return this._stderrStream?this._stderrStream:(l=(e=this._process)===null||e===void 0?void 0:e.stderr)!==null&&l!==void 0?l:null}get pid(){var e,l;return(l=(e=this._process)===null||e===void 0?void 0:e.pid)!==null&&l!==void 0?l:null}processReadBuffer(){for(var e,l;;)try{let n=this._readBuffer.readMessage();if(n===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,n)}catch(n){(l=this.onerror)===null||l===void 0||l.call(this,n)}}async close(){this._abortController.abort(),this._process=void 0,this._readBuffer.clear()}send(e){return new Promise(l=>{var n;if(!(!((n=this._process)===null||n===void 0)&&n.stdin))throw new Error("Not connected");let r=xUt(e);this._process.stdin.write(r)?l():this._process.stdin.once("drain",l)})}};function tYn(){return"type"in $1e}c();c();var eVe=class extends TransformStream{constructor({onError:e,onRetry:l,onComment:n}={}){let r;super({start(I){r=M1e({onEvent:a=>{I.enqueue(a)},onError(a){e==="terminate"?I.error(a):typeof e=="function"&&e(a)},onRetry:l,onComment:n})},transform(I){r.feed(I)}})}};var lYn={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Kde=class extends Error{constructor(e,l){super(`Streamable HTTP error: ${l}`),this.code=e}},tVe=class{constructor(e,l){var n;this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=l?.requestInit,this._authProvider=l?.authProvider,this._fetch=l?.fetch,this._sessionId=l?.sessionId,this._reconnectionOptions=(n=l?.reconnectionOptions)!==null&&n!==void 0?n:lYn}async _authThenStart(){var e;if(!this._authProvider)throw new tN("No auth provider");let l;try{l=await eL(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(l!=="AUTHORIZED")throw new tN;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let l={};if(this._authProvider){let r=await this._authProvider.tokens();r&&(l.Authorization=`Bearer ${r.access_token}`)}this._sessionId&&(l["mcp-session-id"]=this._sessionId),this._protocolVersion&&(l["mcp-protocol-version"]=this._protocolVersion);let n=this._normalizeHeaders((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...l,...n})}async _startOrAuthSse(e){var l,n,r;let{resumptionToken:I}=e;try{let a=await this._commonHeaders();a.set("Accept","text/event-stream"),I&&a.set("last-event-id",I);let s=await((l=this._fetch)!==null&&l!==void 0?l:fetch)(this._url,{method:"GET",headers:a,signal:(n=this._abortController)===null||n===void 0?void 0:n.signal});if(!s.ok){if(s.status===401&&this._authProvider)return await this._authThenStart();if(s.status===405)return;throw new Kde(s.status,`Failed to open SSE stream: ${s.statusText}`)}this._handleSseStream(s.body,e,!0)}catch(a){throw(r=this.onerror)===null||r===void 0||r.call(this,a),a}}_getNextReconnectionDelay(e){let l=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,r=this._reconnectionOptions.maxReconnectionDelay;return Math.min(l*Math.pow(n,e),r)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,l=0){var n;let r=this._reconnectionOptions.maxRetries;if(r>0&&l>=r){(n=this.onerror)===null||n===void 0||n.call(this,new Error(`Maximum reconnection attempts (${r}) exceeded.`));return}let I=this._getNextReconnectionDelay(l);setTimeout(()=>{this._startOrAuthSse(e).catch(a=>{var s;(s=this.onerror)===null||s===void 0||s.call(this,new Error(`Failed to reconnect SSE stream: ${a instanceof Error?a.message:String(a)}`)),this._scheduleReconnection(e,l+1)})},I)}_handleSseStream(e,l,n){if(!e)return;let{onresumptiontoken:r,replayMessageId:I}=l,a;(async()=>{var o,d,u,b;try{let p=e.pipeThrough(new TextDecoderStream).pipeThrough(new eVe).getReader();for(;;){let{value:h,done:Z}=await p.read();if(Z)break;if(h.id&&(a=h.id,r?.(h.id)),!h.event||h.event==="message")try{let N=Mk.parse(JSON.parse(h.data));I!==void 0&&rde(N)&&(N.id=I),(o=this.onmessage)===null||o===void 0||o.call(this,N)}catch(N){(d=this.onerror)===null||d===void 0||d.call(this,N)}}}catch(p){if((u=this.onerror)===null||u===void 0||u.call(this,new Error(`SSE stream disconnected: ${p}`)),n&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:I},0)}catch(h){(b=this.onerror)===null||b===void 0||b.call(this,new Error(`Failed to reconnect: ${h instanceof Error?h.message:String(h)}`))}}})()}async start(){if(this._abortController)throw new 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 tN("No auth provider");if(await eL(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new tN("Failed to authorize")}async close(){var e,l;(e=this._abortController)===null||e===void 0||e.abort(),(l=this.onclose)===null||l===void 0||l.call(this)}async send(e,l){var n,r,I,a;try{let{resumptionToken:s,onresumptiontoken:o}=l||{};if(s){this._startOrAuthSse({resumptionToken:s,replayMessageId:$Ye(e)?e.id:void 0}).catch(y=>{var Y;return(Y=this.onerror)===null||Y===void 0?void 0:Y.call(this,y)});return}let d=await this._commonHeaders();d.set("content-type","application/json"),d.set("accept","application/json, text/event-stream");let u={...this._requestInit,method:"POST",headers:d,body:JSON.stringify(e),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},b=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,u),p=b.headers.get("mcp-session-id");if(p&&(this._sessionId=p),!b.ok){if(b.status===401&&this._authProvider){if(this._resourceMetadataUrl=jde(b),await eL(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new tN;return this.send(e)}let y=await b.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${b.status}): ${y}`)}if(b.status===202){jBt(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(y=>{var Y;return(Y=this.onerror)===null||Y===void 0?void 0:Y.call(this,y)});return}let Z=(Array.isArray(e)?e:[e]).filter(y=>"method"in y&&"id"in y&&y.id!==void 0).length>0,N=b.headers.get("content-type");if(Z)if(N?.includes("text/event-stream"))this._handleSseStream(b.body,{onresumptiontoken:o},!1);else if(N?.includes("application/json")){let y=await b.json(),Y=Array.isArray(y)?y.map(w=>Mk.parse(w)):[Mk.parse(y)];for(let w of Y)(I=this.onmessage)===null||I===void 0||I.call(this,w)}else throw new Kde(-1,`Unexpected content type: ${N}`)}catch(s){throw(a=this.onerror)===null||a===void 0||a.call(this,s),s}}get sessionId(){return this._sessionId}async terminateSession(){var e,l,n;if(this._sessionId)try{let r=await this._commonHeaders(),I={...this._requestInit,method:"DELETE",headers:r,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},a=await((l=this._fetch)!==null&&l!==void 0?l:fetch)(this._url,I);if(!a.ok&&a.status!==405)throw new Kde(a.status,`Failed to terminate session: ${a.statusText}`);this._sessionId=void 0}catch(r){throw(n=this.onerror)===null||n===void 0||n.call(this,r),r}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}};c();var lVe=class{constructor(e){this.server=e}onmessage;onerror;onclose;serverTransport;closed=!1;async start(){if(this.closed)throw new Error("Transport is closed");this.serverTransport=new qKe(this),await this.server.connect(this.serverTransport)}async send(e){if(this.closed)throw new Error("Transport is closed");setImmediate(()=>{try{this.serverTransport?.onmessage?.(e)}catch(l){this.onerror?.(l instanceof Error?l:new Error(String(l)))}})}receive(e){this.closed||this.onmessage?.(e)}async close(){this.closed||(this.closed=!0,await this.serverTransport?.close(),this.onclose?.())}},qKe=class{constructor(e){this.clientTransport=e}onmessage;onerror;onclose;closed=!1;async start(){}async send(e){if(this.closed)throw new Error("Transport is closed");setImmediate(()=>{try{this.clientTransport.receive(e)}catch(l){this.onerror?.(l instanceof Error?l:new Error(String(l)))}})}async close(){this.closed||(this.closed=!0,this.onclose?.())}};var nVe=class{createTransport(e){switch(e.type){case"stdio":{let l=new q1e({command:e.command,args:e.args,env:e.env,stderr:e.stderr?"pipe":void 0,cwd:e.cwd});return l.stderr?.pipe(e.stderr),l}case"http":return new tVe(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"sse":return new P1e(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"memory":return new lVe(e.server);default:throw new Error(`Unsupported transport type: ${e.type}`)}}};c();var gO="blackbird-mcp-server",V8="github-mcp-server",$Ke="playwright";function w8(t){return t.type===void 0||t.type.toLowerCase()==="local"||t.type.toLowerCase()==="stdio"}function Q8(t){return qde(t)||$de(t)}function qde(t){return t.type?.toLowerCase()==="http"}function $de(t){return t.type?.toLowerCase()==="sse"}function eue(t){return t.type?.toLowerCase()==="memory"}var e8e=class extends nYn{constructor(l,n){super({decodeStrings:!1});this.serverName=l;this.logger=n}_write(l,n,r){try{let I=l.toString();this.logger.log(`[mcp server ${this.serverName} stderr] ${I}`),r()}catch(I){r(I instanceof Error?I:new Error(String(I)))}}},rVe=class{constructor(e,l=new T1e,n=new nVe,r="indirect"){this.logger=e;this.clientFactory=l;this.transportFactory=n;this.envValueMode=r}clients={};transports={};async startLocalMcpClient(e,l,n,r,I){this.logger.log(`Starting MCP client for ${e} with command: ${n} and args: ${r}`);let a=new e8e(e,this.logger),s={type:"stdio",command:n,args:r,env:{...l,PATH:process.env.PATH},stderr:a,cwd:I},o=this.transportFactory.createTransport(s);await this.setupAndConnectClient(e,o)}async startHttpMcpClient(e,l){this.logger.log(`Starting remote MCP client for ${e} with url: ${l.url}`);let n={type:"http",url:l.url,headers:l.headers},r=this.transportFactory.createTransport(n);await this.setupAndConnectClient(e,r)}async startSseMcpClient(e,l){this.logger.log(`Starting remote MCP client for ${e} with url: ${l.url}`);let n={type:"sse",url:l.url,headers:l.headers},r=this.transportFactory.createTransport(n);await this.setupAndConnectClient(e,r)}async startInMemoryMcpClient(e,l){this.logger.log(`Starting in-memory MCP client for ${e}`);let n={type:"memory",server:l},r=this.transportFactory.createTransport(n);await this.setupAndConnectClient(e,r)}async setupAndConnectClient(e,l){this.transports[e]=l,l.onclose=()=>{this.logger.log(`MCP transport for ${e} closed`),delete this.transports[e]},this.logger.log(`Creating MCP client for ${e}...`);let n=this.clientFactory.createClient({name:"github-copilot-developer",version:"1.0.0"},{capabilities:{experimental:void 0,roots:void 0,sampling:void 0}}),r=Date.now();this.logger.log(`Connecting MCP client for ${e}...`),await n.connect(l),n.onclose=()=>{this.logger.log(`MCP client for ${e} closed`),delete this.clients[e]},n.onerror=I=>{this.logger.error(`MCP client for ${e} errored ${I}`)},this.logger.log(`MCP client for ${e} connected, took ${Date.now()-r}ms`),this.clients[e]=n}async getTools(e,l){let n={};for(let[r,I]of Object.entries(this.clients)){let a=[];try{this.logger.log(`Fetching tools from client: ${r}`);let s=await I.listTools(),o=e?.mcpServers[r].tools,d=e?.mcpServers[r].filterMapping;for(let b of s.tools){if(b.name==="get_copilot_space")continue;if(!(o?.includes("*")||o?.includes(b.name))){this.logger.log(`Tool ${b.name} is not in the allowed list for client: ${r}`);continue}let h=jye(r,b.name),Z=`${r}-${b.name}`,N;typeof d=="string"?N=bOe(d):N=bOe(d?.[b.name]??"hidden_characters"),n[`${r}/${b.name}`]={name:Z,namespacedName:`${r}/${b.name}`,title:b.title??b.annotations?.title??b.name,description:b.description??Z,input_schema:b.inputSchema,readOnly:b.annotations?.readOnlyHint,safeForTelemetry:{name:!!(e?.mcpServers[r].isDefaultServer||h),inputsNames:!!e?.mcpServers[r].isDefaultServer},filterMode:N},a.push(b.name),this.logger.log(`Tool ${b.name} added to tools list for client: ${r}`)}this.logger.log(`Successfully retrieved ${a.length} tools from client: ${r}`);let u=I.getServerVersion();await this.logServerSuccessWithTools(r,a,u,l)}catch(s){this.logger.error(`Failed to get tools from client: ${r} ${s}`)}}return this.logger.log(`All tools retrieved: ${JSON.stringify(n,null,2)}`),n}async logServerSuccessWithTools(e,l,n,r){if(e!=gO&&r)try{let I=l.map(o=>`- ${o}`).join(`
1955
1955
  `),s=`MCP server started successfully${n?` (version ${n.version})`:""} with ${l.length} ${l.length===1?"tool":"tools"} - for the full output, see the verbose logs
1956
1956
 
1957
- ${I}`;await r.logMCPSetup(e,s),this.logger.log(`Updated session log for ${e} with ${l.length} tools`)}catch(I){this.logger.error(`Failed to update session log for ${e}: ${I}`)}}};c();var t8e={mcpServers:{}},IVe=class{constructor(e,l,n){this.logger=e;this.registry=l;this.remoteEnabled=n?.remoteEnabled??!1,this.mcp3pEnabled=n?.mcp3pEnabled??!1,this.blackbirdMetisIndexEnabled=n?.blackbirdMetisIndexEnabled??!1,this.sessionClient=n?.sessionClient,this.mcpEnvConfig=void 0,this.envValueMode=n?.envValueMode??this.registry.envValueMode}remoteEnabled;mcp3pEnabled;blackbirdMetisIndexEnabled;mcpEnvConfig;sessionClient;envValueMode;ReadMcpConfigFromEnv(e){this.mcpEnvConfig=process.env.GITHUB_COPILOT_MCP_JSON,this.mcp3pEnabled=process.env.GITHUB_COPILOT_3P_MCP_ENABLED==="true",this.remoteEnabled=process.env.GITHUB_COPILOT_REMOTE_MCP_ENABLED==="true",this.blackbirdMetisIndexEnabled=process.env.BLACKBIRD_METIS_INDEX_ENABLED==="true";let l=this.validateEnvConfig();return process.env.GITHUB_COPILOT_CLI_MODE==="true"?this.logger.log("CLI mode detected - skipping default MCP servers"):(this.logger.log("Adding default MCP servers to configuration"),this.configureBlackbirdMcp(l,e),this.configureGitHubMcp(l,e),this.configurePlaywrightMcp(l)),l}validateEnvConfig(){if(!this.mcp3pEnabled)return this.logger.log("User-provided MCPs are disabled"),t8e;if(this.logger.log("User-provided MCPs are enabled, checking for environment variable"),!this.mcpEnvConfig)return this.logger.log("No user-provided MCP servers found"),t8e;try{let e=JSON.parse(this.mcpEnvConfig);if(!e.mcpServers)throw new Error("User-provided config had incorrect format. Missing 'mcpServers' property.");for(let l in e.mcpServers)e.mcpServers[l].isDefaultServer=!1;return e}catch(e){return this.logger.error(`Warning: User-provided MCP servers were defined but invalid: ${e}`),t8e}}configureGitHubMcp(e,l){this.remoteEnabled?this.configureRemoteGitHubMcp(e,l):this.configureLocalGitHubMcp(e)}configureRemoteGitHubMcp(e,l){this.logger.log("Using default remote GitHub MCP server configuration");let n="repos,issues,users,pull_requests,code_security,secret_protection,actions,web_search";process.env.COPILOT_MCP_COPILOT_SPACES_ENABLED==="true"&&(this.logger.log("Enabling Copilot Spaces in GitHub MCP server configuration"),n=n+",copilot_spaces");let r={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":n,"X-MCP-Host":"github-coding-agent","X-Initiator":"agent"};l&&l.api?.copilot?.integrationId&&(r["Copilot-Integration-Id"]=l.api.copilot.integrationId),process.env.GITHUB_COPILOT_INTERACTION_ID&&(r["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let I={type:"http",url:this.getCapiMcpUrl(),headers:r,tools:["*"],isDefaultServer:!0,filterMapping:{get_issue:"markdown",get_issue_comments:"markdown",get_pull_request:"markdown",get_pull_request_comments:"markdown",get_pull_request_reviews:"markdown"}};e.mcpServers[V8]=I}configureLocalGitHubMcp(e){if(e.mcpServers[V8]){this.logger.log("Using user-provided GitHub MCP server configuration");let l=e.mcpServers[V8]??{};w8(l)&&!l.command&&(e.mcpServers[V8]={...l,command:"./copilot-developer-action-main/github-mcp-server/github-mcp-server",isDefaultServer:!0},this.logger.log("Added default command to user-provided GitHub MCP server configuration"))}else{this.logger.log("Using default local GitHub MCP server configuration");let l={command:"./copilot-developer-action-main/github-mcp-server/github-mcp-server",args:["stdio","--read-only"],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",GITHUB_HOST:"GITHUB_SERVER_URL"},tools:["*"],isDefaultServer:!0};e.mcpServers[V8]=l}}configurePlaywrightMcp(e){if(!e.mcpServers[$Ke]){if((process.env.COPILOT_FEATURE_FLAGS??"").split(",").map(n=>n.trim()).includes("copilot_swe_agent_playwright_use_firewall")){this.logger.log("Playwright MCP server is configured to use the firewall, skipping launch.");return}this.logger.log("Enabling Playwright MCP server");let l={command:"npx",args:[...gTe,"--allowed-origins","localhost;localhost:*;127.0.0.1;127.0.0.1:*"],tools:["*"],isDefaultServer:!0};e.mcpServers[$Ke]=l}}configureBlackbirdMcp(e,l){this.remoteEnabled?this.configureRemoteBlackbirdMcp(e):this.blackbirdMetisIndexEnabled?this.configureLocalMetisBlackbirdMCP(e,l):this.configureLocalBlackbirdMcp(e)}configureLocalMetisBlackbirdMCP(e,l){this.logger.log("Using local Metis Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${l.blackbird?.mode}`);let n=process.env.AGENT_DIR||"/agent";this.logger.log(`Using agent directory: ${n}`);let r=[];l.blackbird?.mode==="tool"&&(r=["*"]),this.logger.log(`Using blackbird Metis server: ${l.blackbird?.mode}`);let I={command:`${n}/blackbird/mcp`,args:["serve","--index",`${n}/blackbird/metis`],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",COPILOT_API_HMAC_KEY:"CAPI_HMAC_KEY",MODEL_BASED_RETRIEVAL_TOKEN:"BLACKBIRD_AUTH_MODEL_BASED_RETRIEVAL_TOKEN",METIS_API_KEY:"BLACKBIRD_AUTH_METIS_API_KEY"},tools:r,isDefaultServer:!0};e.mcpServers[gO]=I}configureLocalBlackbirdMcp(e){this.logger.log("Using local Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let l=[];process.env.BLACKBIRD_MODE==="tool"&&(l=["*"]);let n={command:"./copilot-developer-action-main/blackbird-mcp-server/blackbird-mcp-server",args:["stdio"],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",CAPI_HOST:"COPILOT_API_URL"},tools:l,isDefaultServer:!0};e.mcpServers[gO]=n}configureRemoteBlackbirdMcp(e){this.logger.log("Using remote Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let l=[];process.env.BLACKBIRD_MODE==="tool"&&(l=["*"]);let n={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":"search_agent","X-MCP-Host":"github-coding-agent"};process.env.GITHUB_COPILOT_INTERACTION_ID&&(n["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let r={type:"http",url:this.getCapiMcpUrl(),headers:n,tools:l,isDefaultServer:!0};e.mcpServers[gO]=r}getCapiMcpUrl(){return process.env.COPILOT_API_URL?new URL("/mcp/readonly",process.env.COPILOT_API_URL).toString():"https://api.githubcopilot.com/mcp/readonly"}isValidServerType(e){return w8(e)||qde(e)||$de(e)||eue(e)}isValidLocalServerConfig(e){return e.command!==void 0&&e.command.trim()!==""&&Array.isArray(e.args)}isValidRemoteServerConfig(e){return e.url!==void 0&&e.url.trim()!==""}isValidInMemoryServerConfig(e){return e.serverInstance!==void 0&&typeof e.serverInstance=="object"}validateServerConfig(e,l){return this.remoteEnabled&&!this.isValidServerType(l)?(this.logger.error(`Unsupported server type "${l.type}" for server "${e}". Only "Local", "STDIO", "HTTP", "SSE", or "Memory" are supported.`),!1):!this.remoteEnabled&&!w8(l)&&!eue(l)?(this.logger.error(`Unsupported server type "${l.type}" for server "${e}". Only "Local", "STDIO", or "Memory" are supported.`),!1):l.tools?w8(l)&&!this.isValidLocalServerConfig(l)?(this.logger.error(`Invalid local server configuration for "${e}". Please ensure 'command' and 'args' are provided.`),!1):(qde(l)||$de(l))&&!this.isValidRemoteServerConfig(l)?(this.logger.error(`Invalid remote server configuration for "${e}". Please ensure 'url' is provided.`),!1):eue(l)&&!this.isValidInMemoryServerConfig(l)?(this.logger.error(`Invalid in-memory server configuration for "${e}". Please ensure 'serverInstance' is provided and is an instance of MCPServer.`),!1):!0:(this.logger.error(`No tools specified for server "${e}". Please provide a list of tools or "*" to include all tools.`),!1)}async processHttpServer(e,l){try{let n=this.resolveHeaders(l.headers,process.env),r={...l,headers:n};await this.registry.startHttpMcpClient(e,r),this.logger.log(`Started MCP client for remote server ${e}`)}catch(n){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${n}`),n}}async processSseServer(e,l){try{let n=this.resolveRemoteServerConfig(l);await this.registry.startSseMcpClient(e,n),this.logger.log(`Started MCP client for remote server ${e}`)}catch(n){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${n}`),n}}resolveRemoteServerConfig(e){return e.url=this.resolveString(e.url,process.env),e.headers=this.resolveHeaders(e.headers,process.env),{...e,url:e.url,headers:e.headers}}async processInMemoryServer(e,l){try{await this.registry.startInMemoryMcpClient(e,l.serverInstance),this.logger.log(`Started in-memory MCP client for ${e}`)}catch(n){throw this.logger.error(`Failed to start in-memory MCP client for ${e}: ${n}`),n}}async processLocalServer(e,l){let n={...l};if(l.command==="python")try{n=await this.convertPythonToPipx(n)}catch(a){this.logger.error(`Failed to handle Python module for ${e}: ${a}`)}let r=this.buildEnvironment(n),I=this.resolveLocalServerConfig(n,r);this.logger.log(`Starting MCP client for ${e} with command: ${I.command} and args: ${I.args}`);try{await this.registry.startLocalMcpClient(e,r,I.command,I.args),this.logger.log(`Started MCP client for ${e}`)}catch(a){throw this.logger.error(`Failed to start MCP client for ${e}: ${a}`),a}}convertPythonToPipx(e){if(!e||!e.args||e.args.length===0)return e;let l=e.args,n=l.indexOf("-m");if(n===-1||n===l.length-1)throw new Error("Python command with -m flag must specify a module");let r=l[n+1];this.logger.log(`Converting Python module: ${r} to pipx command`);let I=["run",r];for(let a=n+2;a<l.length;a++)I.push(l[a]);for(let a=0;a<n;a++)I.push(l[a]);return{...e,command:"pipx",args:I}}buildEnvironment(e){let l={};if(e.env)if(this.envValueMode==="direct")for(let[n,r]of Object.entries(e.env))l[n]=this.resolveString(r,process.env);else for(let[n,r]of Object.entries(e.env)){let I=r.trim(),a=I;if(I.includes("$")&&(a=this.resolveString(I,process.env)),a!==I){l[n]=a;continue}process.env[I]!==void 0&&(l[n]=process.env[I])}return l}resolveLocalServerConfig(e,l){let n=this.resolveString(e.command,l),r=this.resolveArray(e.args,l);return{...e,command:n,args:r}}resolveString(e,l){return l?e.replace(/\$(?:\{([A-Z0-9_]+)(?::-(.*?))?\}|([A-Z0-9_]+))/g,(n,r,I,a)=>{let o=l[r||a];return o!==void 0?o:I!==void 0?I:n}):e}resolveArray(e,l){return e?l?e.map(n=>this.resolveString(n,l)):e:[]}resolveHeaders(e,l){if(!e)return{};if(!l)return e;let n={};for(let[r,I]of Object.entries(e)){let a=this.resolveArray([I],l);n[r]=a[0]}return n}async processServers(e){if(!e)throw new Error("No servers to process");let l=Object.entries(e.mcpServers).map(([n,r])=>this.processServer(n,r));await Promise.all(l)}async processServer(e,l){if(!this.validateServerConfig(e,l)){this.logger.error(`Skipping server "${e}" due to invalid configuration.`);return}try{w8(l)?await this.processLocalServer(e,l):qde(l)&&this.remoteEnabled?await this.processHttpServer(e,l):$de(l)&&this.remoteEnabled?await this.processSseServer(e,l):eue(l)&&await this.processInMemoryServer(e,l)}catch(n){e!==gO&&await this.logServerFailure(e,n)}}async logServerFailure(e,l){if(this.sessionClient)try{await this.sessionClient.logMCPSetup(e,`<error>MCP server failed to start: ${l.message} - for the full output, see the verbose logs</error>`)}catch(n){this.logger.error(`Failed to log failure for MCP Server '${e}': '${n}'`)}}};var tue=class{constructor(e,l,n,r="indirect"){this.logger=e;let I;if(typeof l=="string"){if(I=JSON.parse(l),typeof I!="object")throw new Error("Invalid MCP configuration: must be an object");if(I===null||!("mcpServers"in I)||typeof I.mcpServers!="object")throw new Error("Invalid MCP configuration: missing or invalid mcpServers property");this.config=I}else this.config=l;this.disabledServers=new Set(n||[]),this.registry=new rVe(this.logger,void 0,void 0,r),this.processor=new IVe(this.logger,this.registry,{mcp3pEnabled:!0,remoteEnabled:!0})}registry;processor;config;startServersPromise=null;transport=null;disabledServers;async startServers(){return this.startServersPromise||(this.startServersPromise=this.processServersWithExtensions()),this.startServersPromise}async injectDefaultServers(e){}async processServersWithExtensions(){await this.injectDefaultServers(this.config);let e;if(this.disabledServers.size>0){let l={};for(let[n,r]of Object.entries(this.config.mcpServers))this.disabledServers.has(n)?this.logger.log(`Skipping disabled MCP server: ${n}`):l[n]=r;e={...this.config,mcpServers:l}}else e=this.config;return this.processor.processServers(e)}async stopServers(){for(let[e,l]of Object.entries(this.registry.transports))try{await l.close()}catch(n){this.logger.error(`Error closing transport for ${e}: ${n}`)}this.startServersPromise=null,this.transport=null}async getTools(e,l,n){await this.startServers(),this.transport=this.transport??new nse(e,l,!0);let r=[];for(let I of Object.keys(this.registry.clients)){let a=await this.transport.loadTools({mcpClient:this.registry.clients[I],clientName:I,tools:this.config.mcpServers[I]?.tools||["*"],filterMapping:this.config.mcpServers[I]?.filterMapping||"hidden_characters"},n);r.push(...a)}return r}getConfig(){return this.config}getClients(){return this.registry.clients}async startServer(e,l){await this.startServers(),this.config.mcpServers[e]=l,await this.processor.processServer(e,l),this.transport=null}async stopServer(e){let l=this.registry.transports[e];if(l)try{await l.close(),delete this.registry.transports[e]}catch(n){this.logger.error(`Error closing transport for ${e}: ${n}`)}this.registry.clients[e]&&delete this.registry.clients[e],this.transport=null}async restartServer(e,l){this.isServerRunning(e)&&await this.stopServer(e),delete this.config.mcpServers[e],await this.startServer(e,l)}isServerRunning(e){return e in this.registry.transports&&e in this.registry.clients}isServerDisabled(e){return this.disabledServers.has(e)}async disableServer(e){if(this.disabledServers.has(e)){this.logger.log(`Server ${e} is already disabled`);return}this.disabledServers.add(e),this.logger.log(`Disabled server ${e} for this session`),this.isServerRunning(e)&&await this.stopServer(e),this.transport=null}async enableServer(e){if(!this.disabledServers.has(e)){this.logger.log(`Server ${e} is not disabled`);return}this.disabledServers.delete(e),this.logger.log(`Enabled server ${e} for this session`);let l=this.getServerConfig(e);l?await this.startServer(e,l):await this.startBuiltInServer(e),this.transport=null}async startBuiltInServer(e){}getServerConfig(e){return this.config.mcpServers[e]}};c();var rYn="/login/device/code",IYn="/login/oauth/access_token",BUt="Ov23ctDVkRmgkPke0Mmm",lL="https://github.com",tL=class extends Error{constructor(l,n){super(n);this.status=l;this.message=n;this.name="GitHubApiError"}};function NO(t){let e=new URL(t);return e.hostname.startsWith("api.")||(e.hostname="api."+e.hostname),e.href}async function OUt(t){let e=new URL(rYn,t),l=await fetch(e.href,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({client_id:BUt,scope:"user:email,read:user,repo,workflow"})});if(!l.ok)throw new tL(l.status,`Failed to request device code: ${l.statusText}`);return await l.json()}async function TUt(t,e){let l=new URL(IYn,t),n=await fetch(l.href,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({client_id:BUt,device_code:e,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})});if(!n.ok)throw new tL(n.status,`Failed to authorize: ${n.statusText}`);let r=await n.json();if(typeof r.access_token=="string")return r.access_token;if(r.error!=="authorization_pending"&&r.error!=="slow_down")throw new Error(r.error_description||`Unexpected error: ${r.error}`)}async function F8(t,e){let l=new URL("/user",NO(t)),n=await fetch(l.href,{headers:{Authorization:`Bearer ${e}`,Accept:"application/json"}});if(!n.ok)throw new tL(n.status,`Failed to fetch user info: ${n.statusText}`);return(await n.json()).login}async function c0(t,e){let l=`
1957
+ ${I}`;await r.logMCPSetup(e,s),this.logger.log(`Updated session log for ${e} with ${l.length} tools`)}catch(I){this.logger.error(`Failed to update session log for ${e}: ${I}`)}}};c();var t8e={mcpServers:{}},IVe=class{constructor(e,l,n){this.logger=e;this.registry=l;this.remoteEnabled=n?.remoteEnabled??!1,this.mcp3pEnabled=n?.mcp3pEnabled??!1,this.blackbirdMetisIndexEnabled=n?.blackbirdMetisIndexEnabled??!1,this.sessionClient=n?.sessionClient,this.mcpEnvConfig=void 0,this.envValueMode=n?.envValueMode??this.registry.envValueMode}remoteEnabled;mcp3pEnabled;blackbirdMetisIndexEnabled;mcpEnvConfig;sessionClient;envValueMode;ReadMcpConfigFromEnv(e){this.mcpEnvConfig=process.env.GITHUB_COPILOT_MCP_JSON,this.mcp3pEnabled=process.env.GITHUB_COPILOT_3P_MCP_ENABLED==="true",this.remoteEnabled=process.env.GITHUB_COPILOT_REMOTE_MCP_ENABLED==="true",this.blackbirdMetisIndexEnabled=process.env.BLACKBIRD_METIS_INDEX_ENABLED==="true";let l=this.validateEnvConfig();return process.env.GITHUB_COPILOT_CLI_MODE==="true"?this.logger.log("CLI mode detected - skipping default MCP servers"):(this.logger.log("Adding default MCP servers to configuration"),this.configureBlackbirdMcp(l,e),this.configureGitHubMcp(l,e),this.configurePlaywrightMcp(l)),l}validateEnvConfig(){if(!this.mcp3pEnabled)return this.logger.log("User-provided MCPs are disabled"),t8e;if(this.logger.log("User-provided MCPs are enabled, checking for environment variable"),!this.mcpEnvConfig)return this.logger.log("No user-provided MCP servers found"),t8e;try{let e=JSON.parse(this.mcpEnvConfig);if(!e.mcpServers)throw new Error("User-provided config had incorrect format. Missing 'mcpServers' property.");for(let l in e.mcpServers)e.mcpServers[l].isDefaultServer=!1;return e}catch(e){return this.logger.error(`Warning: User-provided MCP servers were defined but invalid: ${e}`),t8e}}configureGitHubMcp(e,l){this.remoteEnabled?this.configureRemoteGitHubMcp(e,l):this.configureLocalGitHubMcp(e)}configureRemoteGitHubMcp(e,l){this.logger.log("Using default remote GitHub MCP server configuration");let n="repos,issues,users,pull_requests,code_security,secret_protection,actions,web_search";process.env.COPILOT_MCP_COPILOT_SPACES_ENABLED==="true"&&(this.logger.log("Enabling Copilot Spaces in GitHub MCP server configuration"),n=n+",copilot_spaces");let r={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":n,"X-MCP-Host":"github-coding-agent","X-Initiator":"agent"};l&&l.api?.copilot?.integrationId&&(r["Copilot-Integration-Id"]=l.api.copilot.integrationId),process.env.GITHUB_COPILOT_INTERACTION_ID&&(r["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let I={type:"http",url:this.getCapiMcpUrl(),headers:r,tools:["*"],isDefaultServer:!0,filterMapping:{get_issue:"markdown",get_issue_comments:"markdown",get_pull_request:"markdown",get_pull_request_comments:"markdown",get_pull_request_reviews:"markdown"}};e.mcpServers[V8]=I}configureLocalGitHubMcp(e){if(e.mcpServers[V8]){this.logger.log("Using user-provided GitHub MCP server configuration");let l=e.mcpServers[V8]??{};w8(l)&&!l.command&&(e.mcpServers[V8]={...l,command:"./copilot-developer-action-main/github-mcp-server/github-mcp-server",isDefaultServer:!0},this.logger.log("Added default command to user-provided GitHub MCP server configuration"))}else{this.logger.log("Using default local GitHub MCP server configuration");let l={command:"./copilot-developer-action-main/github-mcp-server/github-mcp-server",args:["stdio","--read-only"],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",GITHUB_HOST:"GITHUB_SERVER_URL"},tools:["*"],isDefaultServer:!0};e.mcpServers[V8]=l}}configurePlaywrightMcp(e){if(!e.mcpServers[$Ke]){if((process.env.COPILOT_FEATURE_FLAGS??"").split(",").map(n=>n.trim()).includes("copilot_swe_agent_playwright_use_firewall")){this.logger.log("Playwright MCP server is configured to use the firewall, skipping launch.");return}this.logger.log("Enabling Playwright MCP server");let l={command:"npx",args:[...gTe,"--allowed-origins","localhost;localhost:*;127.0.0.1;127.0.0.1:*"],tools:["*"],isDefaultServer:!0};e.mcpServers[$Ke]=l}}configureBlackbirdMcp(e,l){this.remoteEnabled?this.configureRemoteBlackbirdMcp(e):this.blackbirdMetisIndexEnabled?this.configureLocalMetisBlackbirdMCP(e,l):this.configureLocalBlackbirdMcp(e)}configureLocalMetisBlackbirdMCP(e,l){this.logger.log("Using local Metis Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${l.blackbird?.mode}`);let n=process.env.AGENT_DIR||"/agent";this.logger.log(`Using agent directory: ${n}`);let r=[];l.blackbird?.mode==="tool"&&(r=["*"]),this.logger.log(`Using blackbird Metis server: ${l.blackbird?.mode}`);let I={command:`${n}/blackbird/mcp`,args:["serve","--index",`${n}/blackbird/metis`],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",COPILOT_API_HMAC_KEY:"CAPI_HMAC_KEY",MODEL_BASED_RETRIEVAL_TOKEN:"BLACKBIRD_AUTH_MODEL_BASED_RETRIEVAL_TOKEN",METIS_API_KEY:"BLACKBIRD_AUTH_METIS_API_KEY"},tools:r,isDefaultServer:!0};e.mcpServers[gO]=I}configureLocalBlackbirdMcp(e){this.logger.log("Using local Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let l=[];process.env.BLACKBIRD_MODE==="tool"&&(l=["*"]);let n={command:"./copilot-developer-action-main/blackbird-mcp-server/blackbird-mcp-server",args:["stdio"],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",CAPI_HOST:"COPILOT_API_URL"},tools:l,isDefaultServer:!0};e.mcpServers[gO]=n}configureRemoteBlackbirdMcp(e){this.logger.log("Using remote Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let l=[];process.env.BLACKBIRD_MODE==="tool"&&(l=["*"]);let n={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":"search_agent","X-MCP-Host":"github-coding-agent"};process.env.GITHUB_COPILOT_INTERACTION_ID&&(n["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let r={type:"http",url:this.getCapiMcpUrl(),headers:n,tools:l,isDefaultServer:!0};e.mcpServers[gO]=r}getCapiMcpUrl(){return process.env.COPILOT_API_URL?new URL("/mcp/readonly",process.env.COPILOT_API_URL).toString():"https://api.githubcopilot.com/mcp/readonly"}isValidServerType(e){return w8(e)||qde(e)||$de(e)||eue(e)}isValidLocalServerConfig(e){return e.command!==void 0&&e.command.trim()!==""&&Array.isArray(e.args)}isValidRemoteServerConfig(e){return e.url!==void 0&&e.url.trim()!==""}isValidInMemoryServerConfig(e){return e.serverInstance!==void 0&&typeof e.serverInstance=="object"}validateServerConfig(e,l){return this.remoteEnabled&&!this.isValidServerType(l)?(this.logger.error(`Unsupported server type "${l.type}" for server "${e}". Only "Local", "STDIO", "HTTP", "SSE", or "Memory" are supported.`),!1):!this.remoteEnabled&&!w8(l)&&!eue(l)?(this.logger.error(`Unsupported server type "${l.type}" for server "${e}". Only "Local", "STDIO", or "Memory" are supported.`),!1):l.tools?w8(l)&&!this.isValidLocalServerConfig(l)?(this.logger.error(`Invalid local server configuration for "${e}". Please ensure 'command' and 'args' are provided.`),!1):(qde(l)||$de(l))&&!this.isValidRemoteServerConfig(l)?(this.logger.error(`Invalid remote server configuration for "${e}". Please ensure 'url' is provided.`),!1):eue(l)&&!this.isValidInMemoryServerConfig(l)?(this.logger.error(`Invalid in-memory server configuration for "${e}". Please ensure 'serverInstance' is provided and is an instance of MCPServer.`),!1):!0:(this.logger.error(`No tools specified for server "${e}". Please provide a list of tools or "*" to include all tools.`),!1)}async processHttpServer(e,l){try{let n=this.resolveHeaders(l.headers,process.env),r={...l,headers:n};await this.registry.startHttpMcpClient(e,r),this.logger.log(`Started MCP client for remote server ${e}`)}catch(n){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${n}`),n}}async processSseServer(e,l){try{let n=this.resolveRemoteServerConfig(l);await this.registry.startSseMcpClient(e,n),this.logger.log(`Started MCP client for remote server ${e}`)}catch(n){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${n}`),n}}resolveRemoteServerConfig(e){return e.url=this.resolveString(e.url,process.env),e.headers=this.resolveHeaders(e.headers,process.env),{...e,url:e.url,headers:e.headers}}async processInMemoryServer(e,l){try{await this.registry.startInMemoryMcpClient(e,l.serverInstance),this.logger.log(`Started in-memory MCP client for ${e}`)}catch(n){throw this.logger.error(`Failed to start in-memory MCP client for ${e}: ${n}`),n}}async processLocalServer(e,l){let n={...l};if(l.command==="python")try{n=await this.convertPythonToPipx(n)}catch(a){this.logger.error(`Failed to handle Python module for ${e}: ${a}`)}let r=this.buildEnvironment(n),I=this.resolveLocalServerConfig(n,r);this.logger.log(`Starting MCP client for ${e} with command: ${I.command} and args: ${I.args}`),I.cwd&&this.logger.log(`cwd: ${I.cwd}`);try{await this.registry.startLocalMcpClient(e,r,I.command,I.args,I.cwd),this.logger.log(`Started MCP client for ${e}`)}catch(a){throw this.logger.error(`Failed to start MCP client for ${e}: ${a}`),a}}convertPythonToPipx(e){if(!e||!e.args||e.args.length===0)return e;let l=e.args,n=l.indexOf("-m");if(n===-1||n===l.length-1)throw new Error("Python command with -m flag must specify a module");let r=l[n+1];this.logger.log(`Converting Python module: ${r} to pipx command`);let I=["run",r];for(let a=n+2;a<l.length;a++)I.push(l[a]);for(let a=0;a<n;a++)I.push(l[a]);return{...e,command:"pipx",args:I}}buildEnvironment(e){let l={};if(e.env)if(this.envValueMode==="direct")for(let[n,r]of Object.entries(e.env))l[n]=this.resolveString(r,process.env);else for(let[n,r]of Object.entries(e.env)){let I=r.trim(),a=I;if(I.includes("$")&&(a=this.resolveString(I,process.env)),a!==I){l[n]=a;continue}process.env[I]!==void 0&&(l[n]=process.env[I])}return l}resolveLocalServerConfig(e,l){let n=this.resolveString(e.command,l),r=this.resolveArray(e.args,l),I;return e.cwd&&(I=this.resolveString(e.cwd,l)),{...e,command:n,args:r,cwd:I}}resolveString(e,l){return l?e.replace(/\$(?:\{([A-Z0-9_]+)(?::-(.*?))?\}|([A-Z0-9_]+))/g,(n,r,I,a)=>{let o=l[r||a];return o!==void 0?o:I!==void 0?I:n}):e}resolveArray(e,l){return e?l?e.map(n=>this.resolveString(n,l)):e:[]}resolveHeaders(e,l){if(!e)return{};if(!l)return e;let n={};for(let[r,I]of Object.entries(e)){let a=this.resolveArray([I],l);n[r]=a[0]}return n}async processServers(e){if(!e)throw new Error("No servers to process");let l=Object.entries(e.mcpServers).map(([n,r])=>this.processServer(n,r));await Promise.all(l)}async processServer(e,l){if(!this.validateServerConfig(e,l)){this.logger.error(`Skipping server "${e}" due to invalid configuration.`);return}try{w8(l)?await this.processLocalServer(e,l):qde(l)&&this.remoteEnabled?await this.processHttpServer(e,l):$de(l)&&this.remoteEnabled?await this.processSseServer(e,l):eue(l)&&await this.processInMemoryServer(e,l)}catch(n){e!==gO&&await this.logServerFailure(e,n)}}async logServerFailure(e,l){if(this.sessionClient)try{await this.sessionClient.logMCPSetup(e,`<error>MCP server failed to start: ${l.message} - for the full output, see the verbose logs</error>`)}catch(n){this.logger.error(`Failed to log failure for MCP Server '${e}': '${n}'`)}}};var tue=class{constructor(e,l,n,r="indirect"){this.logger=e;let I;if(typeof l=="string"){if(I=JSON.parse(l),typeof I!="object")throw new Error("Invalid MCP configuration: must be an object");if(I===null||!("mcpServers"in I)||typeof I.mcpServers!="object")throw new Error("Invalid MCP configuration: missing or invalid mcpServers property");this.config=I}else this.config=l;this.disabledServers=new Set(n||[]),this.registry=new rVe(this.logger,void 0,void 0,r),this.processor=new IVe(this.logger,this.registry,{mcp3pEnabled:!0,remoteEnabled:!0})}registry;processor;config;startServersPromise=null;transport=null;disabledServers;async startServers(){return this.startServersPromise||(this.startServersPromise=this.processServersWithExtensions()),this.startServersPromise}async injectDefaultServers(e){}async processServersWithExtensions(){await this.injectDefaultServers(this.config);let e;if(this.disabledServers.size>0){let l={};for(let[n,r]of Object.entries(this.config.mcpServers))this.disabledServers.has(n)?this.logger.log(`Skipping disabled MCP server: ${n}`):l[n]=r;e={...this.config,mcpServers:l}}else e=this.config;return this.processor.processServers(e)}async stopServers(){for(let[e,l]of Object.entries(this.registry.transports))try{await l.close()}catch(n){this.logger.error(`Error closing transport for ${e}: ${n}`)}this.startServersPromise=null,this.transport=null}async getTools(e,l,n){await this.startServers(),this.transport=this.transport??new nse(e,l,!0);let r=[];for(let I of Object.keys(this.registry.clients)){let a=await this.transport.loadTools({mcpClient:this.registry.clients[I],clientName:I,tools:this.config.mcpServers[I]?.tools||["*"],filterMapping:this.config.mcpServers[I]?.filterMapping||"hidden_characters"},n);r.push(...a)}return r}getConfig(){return this.config}getClients(){return this.registry.clients}async startServer(e,l){await this.startServers(),this.config.mcpServers[e]=l,await this.processor.processServer(e,l),this.transport=null}async stopServer(e){let l=this.registry.transports[e];if(l)try{await l.close(),delete this.registry.transports[e]}catch(n){this.logger.error(`Error closing transport for ${e}: ${n}`)}this.registry.clients[e]&&delete this.registry.clients[e],this.transport=null}async restartServer(e,l){this.isServerRunning(e)&&await this.stopServer(e),delete this.config.mcpServers[e],await this.startServer(e,l)}isServerRunning(e){return e in this.registry.transports&&e in this.registry.clients}isServerDisabled(e){return this.disabledServers.has(e)}async disableServer(e){if(this.disabledServers.has(e)){this.logger.log(`Server ${e} is already disabled`);return}this.disabledServers.add(e),this.logger.log(`Disabled server ${e} for this session`),this.isServerRunning(e)&&await this.stopServer(e),this.transport=null}async enableServer(e){if(!this.disabledServers.has(e)){this.logger.log(`Server ${e} is not disabled`);return}this.disabledServers.delete(e),this.logger.log(`Enabled server ${e} for this session`);let l=this.getServerConfig(e);l?await this.startServer(e,l):await this.startBuiltInServer(e),this.transport=null}async startBuiltInServer(e){}getServerConfig(e){return this.config.mcpServers[e]}};c();var rYn="/login/device/code",IYn="/login/oauth/access_token",BUt="Ov23ctDVkRmgkPke0Mmm",lL="https://github.com",tL=class extends Error{constructor(l,n){super(n);this.status=l;this.message=n;this.name="GitHubApiError"}};function NO(t){let e=new URL(t);return e.hostname.startsWith("api.")||(e.hostname="api."+e.hostname),e.href}async function OUt(t){let e=new URL(rYn,t),l=await fetch(e.href,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({client_id:BUt,scope:"user:email,read:user,repo,workflow"})});if(!l.ok)throw new tL(l.status,`Failed to request device code: ${l.statusText}`);return await l.json()}async function TUt(t,e){let l=new URL(IYn,t),n=await fetch(l.href,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({client_id:BUt,device_code:e,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})});if(!n.ok)throw new tL(n.status,`Failed to authorize: ${n.statusText}`);let r=await n.json();if(typeof r.access_token=="string")return r.access_token;if(r.error!=="authorization_pending"&&r.error!=="slow_down")throw new Error(r.error_description||`Unexpected error: ${r.error}`)}async function F8(t,e){let l=new URL("/user",NO(t)),n=await fetch(l.href,{headers:{Authorization:`Bearer ${e}`,Accept:"application/json"}});if(!n.ok)throw new tL(n.status,`Failed to fetch user info: ${n.statusText}`);return(await n.json()).login}async function c0(t,e){let l=`
1958
1958
  {
1959
1959
  viewer {
1960
1960
  copilotEndpoints {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@github/copilot",
3
3
  "description": "GitHub Copilot CLI brings the power of Copilot coding agent directly to your terminal.",
4
- "version": "0.0.348-16",
4
+ "version": "0.0.348-17",
5
5
  "type": "module",
6
6
  "repository": {
7
7
  "type": "git",
@@ -35,7 +35,7 @@
35
35
  "worker/**/*"
36
36
  ],
37
37
  "buildMetadata": {
38
- "gitCommit": "990e257"
38
+ "gitCommit": "18dee97"
39
39
  },
40
40
  "dependencies": {
41
41
  "sharp": "^0.34.3"
package/sdk/index.d.ts CHANGED
@@ -673,6 +673,7 @@ declare interface MCPLocalServerConfig extends MCPServerConfigBase {
673
673
  * Empty means no env vars passed.
674
674
  */
675
675
  env?: Record<string, string>;
676
+ cwd?: string;
676
677
  }
677
678
 
678
679
  /**