@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/sdk/index.js CHANGED
@@ -1407,10 +1407,10 @@ Pay attention to the following when using it:
1407
1407
  `,l),r=-1;if(n!==-1&&c!==-1?r=Math.min(n,c):n!==-1?r=n:c!==-1&&(r=c),r===-1){I=t.slice(l);break}else{let s=t.slice(l,r);e.push(s),l=r+1,t[l-1]==="\r"&&t[l]===`
1408
1408
  `&&l++}}return[e,I]}var r7=class extends Event{constructor(e,I){var l,n;super(e),this.code=(l=I?.code)!=null?l:void 0,this.message=(n=I?.message)!=null?n:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,I,l){return l(x8e(this),I)}[Symbol.for("Deno.customInspect")](e,I){return e(x8e(this),I)}};function tet(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function $Ze(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map($Ze).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${$Ze(t.cause)}`:t.message:`${t}`}function x8e(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var z8e=t=>{throw TypeError(t)},sWe=(t,e,I)=>e.has(t)||z8e("Cannot "+I),St=(t,e,I)=>(sWe(t,e,"read from private field"),I?I.call(t):e.get(t)),pr=(t,e,I)=>e.has(t)?z8e("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,I),Bn=(t,e,I,l)=>(sWe(t,e,"write to private field"),e.set(t,I),I),nW=(t,e,I)=>(sWe(t,e,"access private method"),I),hG,jg,P1,c7,s7,LB,$1,kB,PV,q1,ev,_1,CB,$b,eWe,IWe,tWe,B8e,lWe,nWe,JB,cWe,rWe,Dg=class extends EventTarget{constructor(e,I){var l,n;super(),pr(this,$b),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,pr(this,hG),pr(this,jg),pr(this,P1),pr(this,c7),pr(this,s7),pr(this,LB),pr(this,$1),pr(this,kB,null),pr(this,PV),pr(this,q1),pr(this,ev,null),pr(this,_1,null),pr(this,CB,null),pr(this,IWe,async c=>{var r;St(this,q1).reset();let{body:s,redirected:a,status:G,headers:d}=c;if(G===204){nW(this,$b,JB).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(a?Bn(this,P1,new URL(c.url)):Bn(this,P1,void 0),G!==200){nW(this,$b,JB).call(this,`Non-200 status code (${G})`,G);return}if(!(d.get("content-type")||"").startsWith("text/event-stream")){nW(this,$b,JB).call(this,'Invalid content type, expected "text/event-stream"',G);return}if(St(this,hG)===this.CLOSED)return;Bn(this,hG,this.OPEN);let i=new Event("open");if((r=St(this,CB))==null||r.call(this,i),this.dispatchEvent(i),typeof s!="object"||!s||!("getReader"in s)){nW(this,$b,JB).call(this,"Invalid response body, expected a web ReadableStream",G),this.close();return}let b=new TextDecoder,m=s.getReader(),h=!0;do{let{done:p,value:Z}=await m.read();Z&&St(this,q1).feed(b.decode(Z,{stream:!p})),p&&(h=!1,St(this,q1).reset(),nW(this,$b,cWe).call(this))}while(h)}),pr(this,tWe,c=>{Bn(this,PV,void 0),!(c.name==="AbortError"||c.type==="aborted")&&nW(this,$b,cWe).call(this,$Ze(c))}),pr(this,lWe,c=>{typeof c.id=="string"&&Bn(this,kB,c.id);let r=new MessageEvent(c.event||"message",{data:c.data,origin:St(this,P1)?St(this,P1).origin:St(this,jg).origin,lastEventId:c.id||""});St(this,_1)&&(!c.event||c.event==="message")&&St(this,_1).call(this,r),this.dispatchEvent(r)}),pr(this,nWe,c=>{Bn(this,LB,c)}),pr(this,rWe,()=>{Bn(this,$1,void 0),St(this,hG)===this.CONNECTING&&nW(this,$b,eWe).call(this)});try{if(e instanceof URL)Bn(this,jg,e);else if(typeof e=="string")Bn(this,jg,new URL(e,net()));else throw new Error("Invalid URL")}catch{throw tet("An invalid or illegal string was specified")}Bn(this,q1,n7({onEvent:St(this,lWe),onRetry:St(this,nWe)})),Bn(this,hG,this.CONNECTING),Bn(this,LB,3e3),Bn(this,s7,(l=I?.fetch)!=null?l:globalThis.fetch),Bn(this,c7,(n=I?.withCredentials)!=null?n:!1),nW(this,$b,eWe).call(this)}get readyState(){return St(this,hG)}get url(){return St(this,jg).href}get withCredentials(){return St(this,c7)}get onerror(){return St(this,ev)}set onerror(e){Bn(this,ev,e)}get onmessage(){return St(this,_1)}set onmessage(e){Bn(this,_1,e)}get onopen(){return St(this,CB)}set onopen(e){Bn(this,CB,e)}addEventListener(e,I,l){let n=I;super.addEventListener(e,n,l)}removeEventListener(e,I,l){let n=I;super.removeEventListener(e,n,l)}close(){St(this,$1)&&clearTimeout(St(this,$1)),St(this,hG)!==this.CLOSED&&(St(this,PV)&&St(this,PV).abort(),Bn(this,hG,this.CLOSED),Bn(this,PV,void 0))}};hG=new WeakMap,jg=new WeakMap,P1=new WeakMap,c7=new WeakMap,s7=new WeakMap,LB=new WeakMap,$1=new WeakMap,kB=new WeakMap,PV=new WeakMap,q1=new WeakMap,ev=new WeakMap,_1=new WeakMap,CB=new WeakMap,$b=new WeakSet,eWe=function(){Bn(this,hG,this.CONNECTING),Bn(this,PV,new AbortController),St(this,s7)(St(this,jg),nW(this,$b,B8e).call(this)).then(St(this,IWe)).catch(St(this,tWe))},IWe=new WeakMap,tWe=new WeakMap,B8e=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...St(this,kB)?{"Last-Event-ID":St(this,kB)}:void 0},cache:"no-store",signal:(t=St(this,PV))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},lWe=new WeakMap,nWe=new WeakMap,JB=function(t,e){var I;St(this,hG)!==this.CLOSED&&Bn(this,hG,this.CLOSED);let l=new r7("error",{code:e,message:t});(I=St(this,ev))==null||I.call(this,l),this.dispatchEvent(l)},cWe=function(t,e){var I;if(St(this,hG)===this.CLOSED)return;Bn(this,hG,this.CONNECTING);let l=new r7("error",{code:e,message:t});(I=St(this,ev))==null||I.call(this,l),this.dispatchEvent(l),Bn(this,$1,setTimeout(St(this,rWe),St(this,LB)))},rWe=new WeakMap,Dg.CONNECTING=0,Dg.OPEN=1,Dg.CLOSED=2;function net(){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}o();o();var aWe;aWe=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(t=>t.webcrypto);async function cet(t){return(await aWe).getRandomValues(new Uint8Array(t))}async function ret(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",I="",l=await cet(t);for(let n=0;n<t;n++){let c=l[n]%e.length;I+=e[c]}return I}async function set(t){return await ret(t)}async function aet(t){let e=await(await aWe).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function oWe(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;let e=await set(t),I=await aet(e);return{code_verifier:e,code_challenge:I}}o();var qr=V.string().url().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:V.ZodIssueCode.custom,message:"URL must be parseable",fatal:!0}),V.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"}),U8e=V.object({resource:V.string().url(),authorization_servers:V.array(qr).optional(),jwks_uri:V.string().url().optional(),scopes_supported:V.array(V.string()).optional(),bearer_methods_supported:V.array(V.string()).optional(),resource_signing_alg_values_supported:V.array(V.string()).optional(),resource_name:V.string().optional(),resource_documentation:V.string().optional(),resource_policy_uri:V.string().url().optional(),resource_tos_uri:V.string().url().optional(),tls_client_certificate_bound_access_tokens:V.boolean().optional(),authorization_details_types_supported:V.array(V.string()).optional(),dpop_signing_alg_values_supported:V.array(V.string()).optional(),dpop_bound_access_tokens_required:V.boolean().optional()}).passthrough(),GWe=V.object({issuer:V.string(),authorization_endpoint:qr,token_endpoint:qr,registration_endpoint:qr.optional(),scopes_supported:V.array(V.string()).optional(),response_types_supported:V.array(V.string()),response_modes_supported:V.array(V.string()).optional(),grant_types_supported:V.array(V.string()).optional(),token_endpoint_auth_methods_supported:V.array(V.string()).optional(),token_endpoint_auth_signing_alg_values_supported:V.array(V.string()).optional(),service_documentation:qr.optional(),revocation_endpoint:qr.optional(),revocation_endpoint_auth_methods_supported:V.array(V.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:V.array(V.string()).optional(),introspection_endpoint:V.string().optional(),introspection_endpoint_auth_methods_supported:V.array(V.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:V.array(V.string()).optional(),code_challenge_methods_supported:V.array(V.string()).optional()}).passthrough(),oet=V.object({issuer:V.string(),authorization_endpoint:qr,token_endpoint:qr,userinfo_endpoint:qr.optional(),jwks_uri:qr,registration_endpoint:qr.optional(),scopes_supported:V.array(V.string()).optional(),response_types_supported:V.array(V.string()),response_modes_supported:V.array(V.string()).optional(),grant_types_supported:V.array(V.string()).optional(),acr_values_supported:V.array(V.string()).optional(),subject_types_supported:V.array(V.string()),id_token_signing_alg_values_supported:V.array(V.string()),id_token_encryption_alg_values_supported:V.array(V.string()).optional(),id_token_encryption_enc_values_supported:V.array(V.string()).optional(),userinfo_signing_alg_values_supported:V.array(V.string()).optional(),userinfo_encryption_alg_values_supported:V.array(V.string()).optional(),userinfo_encryption_enc_values_supported:V.array(V.string()).optional(),request_object_signing_alg_values_supported:V.array(V.string()).optional(),request_object_encryption_alg_values_supported:V.array(V.string()).optional(),request_object_encryption_enc_values_supported:V.array(V.string()).optional(),token_endpoint_auth_methods_supported:V.array(V.string()).optional(),token_endpoint_auth_signing_alg_values_supported:V.array(V.string()).optional(),display_values_supported:V.array(V.string()).optional(),claim_types_supported:V.array(V.string()).optional(),claims_supported:V.array(V.string()).optional(),service_documentation:V.string().optional(),claims_locales_supported:V.array(V.string()).optional(),ui_locales_supported:V.array(V.string()).optional(),claims_parameter_supported:V.boolean().optional(),request_parameter_supported:V.boolean().optional(),request_uri_parameter_supported:V.boolean().optional(),require_request_uri_registration:V.boolean().optional(),op_policy_uri:qr.optional(),op_tos_uri:qr.optional()}).passthrough(),S8e=oet.merge(GWe.pick({code_challenge_methods_supported:!0})),dWe=V.object({access_token:V.string(),id_token:V.string().optional(),token_type:V.string(),expires_in:V.number().optional(),scope:V.string().optional(),refresh_token:V.string().optional()}).strip(),O8e=V.object({error:V.string(),error_description:V.string().optional(),error_uri:V.string().optional()}),Get=V.object({redirect_uris:V.array(qr),token_endpoint_auth_method:V.string().optional(),grant_types:V.array(V.string()).optional(),response_types:V.array(V.string()).optional(),client_name:V.string().optional(),client_uri:qr.optional(),logo_uri:qr.optional(),scope:V.string().optional(),contacts:V.array(V.string()).optional(),tos_uri:qr.optional(),policy_uri:V.string().optional(),jwks_uri:qr.optional(),jwks:V.any().optional(),software_id:V.string().optional(),software_version:V.string().optional(),software_statement:V.string().optional()}).strip(),det=V.object({client_id:V.string(),client_secret:V.string().optional(),client_id_issued_at:V.number().optional(),client_secret_expires_at:V.number().optional()}).strip(),M8e=Get.merge(det),Fdn=V.object({error:V.string(),error_description:V.string().optional()}).strip(),Adn=V.object({token:V.string(),token_type_hint:V.string().optional()}).strip();o();function T8e(t){let e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function j8e({requestedResource:t,configuredResource:e}){let I=typeof t=="string"?new URL(t):new URL(t.href),l=typeof e=="string"?new URL(e):new URL(e.href);if(I.origin!==l.origin||I.pathname.length<l.pathname.length)return!1;let n=I.pathname.endsWith("/")?I.pathname:I.pathname+"/",c=l.pathname.endsWith("/")?l.pathname:l.pathname+"/";return n.startsWith(c)}o();var Pc=class extends Error{constructor(e,I){super(e),this.errorUri=I,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}},fB=class extends Pc{};fB.errorCode="invalid_request";var Kg=class extends Pc{};Kg.errorCode="invalid_client";var Pg=class extends Pc{};Pg.errorCode="invalid_grant";var qg=class extends Pc{};qg.errorCode="unauthorized_client";var xB=class extends Pc{};xB.errorCode="unsupported_grant_type";var BB=class extends Pc{};BB.errorCode="invalid_scope";var zB=class extends Pc{};zB.errorCode="access_denied";var cW=class extends Pc{};cW.errorCode="server_error";var UB=class extends Pc{};UB.errorCode="temporarily_unavailable";var SB=class extends Pc{};SB.errorCode="unsupported_response_type";var OB=class extends Pc{};OB.errorCode="unsupported_token_type";var MB=class extends Pc{};MB.errorCode="invalid_token";var TB=class extends Pc{};TB.errorCode="method_not_allowed";var jB=class extends Pc{};jB.errorCode="too_many_requests";var DB=class extends Pc{};DB.errorCode="invalid_client_metadata";var KB=class extends Pc{};KB.errorCode="insufficient_scope";var D8e={[fB.errorCode]:fB,[Kg.errorCode]:Kg,[Pg.errorCode]:Pg,[qg.errorCode]:qg,[xB.errorCode]:xB,[BB.errorCode]:BB,[zB.errorCode]:zB,[cW.errorCode]:cW,[UB.errorCode]:UB,[SB.errorCode]:SB,[OB.errorCode]:OB,[MB.errorCode]:MB,[TB.errorCode]:TB,[jB.errorCode]:jB,[DB.errorCode]:DB,[KB.errorCode]:KB};var pG=class extends Error{constructor(e){super(e??"Unauthorized")}};function P8e(t,e){let I=t.client_secret!==void 0;return e.length===0?I?"client_secret_post":"none":I&&e.includes("client_secret_basic")?"client_secret_basic":I&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":I?"client_secret_post":"none"}function q8e(t,e,I,l){let{client_id:n,client_secret:c}=e;switch(t){case"client_secret_basic":iet(n,c,I);return;case"client_secret_post":bet(n,c,l);return;case"none":met(n,l);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function iet(t,e,I){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");let l=btoa(`${t}:${e}`);I.set("Authorization",`Basic ${l}`)}function bet(t,e,I){I.set("client_id",t),e&&I.set("client_secret",e)}function met(t,e){e.set("client_id",t)}async function bWe(t){let e=t instanceof Response?t.status:void 0,I=t instanceof Response?await t.text():t;try{let l=O8e.parse(JSON.parse(I)),{error:n,error_description:c,error_uri:r}=l,s=D8e[n]||cW;return new s(c||"",r)}catch(l){let n=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${l}. Raw body: ${I}`;return new cW(n)}}async function qV(t,e){var I,l;try{return await iWe(t,e)}catch(n){if(n instanceof Kg||n instanceof qg)return await((I=t.invalidateCredentials)===null||I===void 0?void 0:I.call(t,"all")),await iWe(t,e);if(n instanceof Pg)return await((l=t.invalidateCredentials)===null||l===void 0?void 0:l.call(t,"tokens")),await iWe(t,e);throw n}}async function iWe(t,{serverUrl:e,authorizationCode:I,scope:l,resourceMetadataUrl:n,fetchFn:c}){let r,s;try{r=await pet(e,{resourceMetadataUrl:n},c),r.authorization_servers&&r.authorization_servers.length>0&&(s=r.authorization_servers[0])}catch{}s||(s=e);let a=await het(e,t,r),G=await Yet(s,{fetchFn:c}),d=await Promise.resolve(t.clientInformation());if(!d){if(I!==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 p=await get(s,{metadata:G,clientMetadata:t.clientMetadata,fetchFn:c});await t.saveClientInformation(p),d=p}if(I!==void 0){let p=await t.codeVerifier(),Z=await Ret(s,{metadata:G,clientInformation:d,authorizationCode:I,codeVerifier:p,redirectUri:t.redirectUrl,resource:a,addClientAuthentication:t.addClientAuthentication,fetchFn:c});return await t.saveTokens(Z),"AUTHORIZED"}let i=await t.tokens();if(i?.refresh_token)try{let p=await yet(s,{metadata:G,clientInformation:d,refreshToken:i.refresh_token,resource:a,addClientAuthentication:t.addClientAuthentication,fetchFn:c});return await t.saveTokens(p),"AUTHORIZED"}catch(p){if(!(!(p instanceof Pc)||p instanceof cW))throw p}let b=t.state?await t.state():void 0,{authorizationUrl:m,codeVerifier:h}=await Vet(s,{metadata:G,clientInformation:d,state:b,redirectUrl:t.redirectUrl,scope:l||t.clientMetadata.scope,resource:a});return await t.saveCodeVerifier(h),await t.redirectToAuthorization(m),"REDIRECT"}async function het(t,e,I){let l=T8e(t);if(e.validateResourceURL)return await e.validateResourceURL(l,I?.resource);if(I){if(!j8e({requestedResource:l,configuredResource:I.resource}))throw new Error(`Protected resource ${I.resource} does not match expected ${l} (or origin)`);return new URL(I.resource)}}function PB(t){let e=t.headers.get("WWW-Authenticate");if(!e)return;let[I,l]=e.split(" ");if(I.toLowerCase()!=="bearer"||!l)return;let c=/resource_metadata="([^"]*)"/.exec(e);if(c)try{return new URL(c[1])}catch{return}}async function pet(t,e,I=fetch){let l=await Wet(t,"oauth-protected-resource",I,{protocolVersion:e?.protocolVersion,metadataUrl:e?.resourceMetadataUrl});if(!l||l.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!l.ok)throw new Error(`HTTP ${l.status} trying to load well-known OAuth protected resource metadata.`);return U8e.parse(await l.json())}async function mWe(t,e,I=fetch){try{return await I(t,{headers:e})}catch(l){if(l instanceof TypeError)return e?mWe(t,void 0,I):void 0;throw l}}function uet(t,e="",I={}){return e.endsWith("/")&&(e=e.slice(0,-1)),I.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function K8e(t,e,I=fetch){return await mWe(t,{"MCP-Protocol-Version":e},I)}function Zet(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function Wet(t,e,I,l){var n,c;let r=new URL(t),s=(n=l?.protocolVersion)!==null&&n!==void 0?n:J1,a;if(l?.metadataUrl)a=new URL(l.metadataUrl);else{let d=uet(e,r.pathname);a=new URL(d,(c=l?.metadataServerUrl)!==null&&c!==void 0?c:r),a.search=r.search}let G=await K8e(a,s,I);if(!l?.metadataUrl&&Zet(G,r.pathname)){let d=new URL(`/.well-known/${e}`,r);G=await K8e(d,s,I)}return G}function Net(t){let e=typeof t=="string"?new URL(t):t,I=e.pathname!=="/",l=[];if(!I)return l.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),l.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),l;let n=e.pathname;return n.endsWith("/")&&(n=n.slice(0,-1)),l.push({url:new URL(`/.well-known/oauth-authorization-server${n}`,e.origin),type:"oauth"}),l.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),l.push({url:new URL(`/.well-known/openid-configuration${n}`,e.origin),type:"oidc"}),l.push({url:new URL(`${n}/.well-known/openid-configuration`,e.origin),type:"oidc"}),l}async function Yet(t,{fetchFn:e=fetch,protocolVersion:I=J1}={}){var l;let n={"MCP-Protocol-Version":I},c=Net(t);for(let{url:r,type:s}of c){let a=await mWe(r,n,e);if(a){if(!a.ok){if(a.status>=400&&a.status<500)continue;throw new Error(`HTTP ${a.status} trying to load ${s==="oauth"?"OAuth":"OpenID provider"} metadata from ${r}`)}if(s==="oauth")return GWe.parse(await a.json());{let G=S8e.parse(await a.json());if(!(!((l=G.code_challenge_methods_supported)===null||l===void 0)&&l.includes("S256")))throw new Error(`Incompatible OIDC provider at ${r}: does not support S256 code challenge method required by MCP specification`);return G}}}}async function Vet(t,{metadata:e,clientInformation:I,redirectUrl:l,scope:n,state:c,resource:r}){let s="code",a="S256",G;if(e){if(G=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(a))throw new Error(`Incompatible auth server: does not support code challenge method ${a}`)}else G=new URL("/authorize",t);let d=await oWe(),i=d.code_verifier,b=d.code_challenge;return G.searchParams.set("response_type",s),G.searchParams.set("client_id",I.client_id),G.searchParams.set("code_challenge",b),G.searchParams.set("code_challenge_method",a),G.searchParams.set("redirect_uri",String(l)),c&&G.searchParams.set("state",c),n&&G.searchParams.set("scope",n),n?.includes("offline_access")&&G.searchParams.append("prompt","consent"),r&&G.searchParams.set("resource",r.href),{authorizationUrl:G,codeVerifier:i}}async function Ret(t,{metadata:e,clientInformation:I,authorizationCode:l,codeVerifier:n,redirectUri:c,resource:r,addClientAuthentication:s,fetchFn:a}){var G;let d="authorization_code",i=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",t);if(e?.grant_types_supported&&!e.grant_types_supported.includes(d))throw new Error(`Incompatible auth server: does not support grant type ${d}`);let b=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),m=new URLSearchParams({grant_type:d,code:l,code_verifier:n,redirect_uri:String(c)});if(s)s(b,m,t,e);else{let p=(G=e?.token_endpoint_auth_methods_supported)!==null&&G!==void 0?G:[],Z=P8e(I,p);q8e(Z,I,b,m)}r&&m.set("resource",r.href);let h=await(a??fetch)(i,{method:"POST",headers:b,body:m});if(!h.ok)throw await bWe(h);return dWe.parse(await h.json())}async function yet(t,{metadata:e,clientInformation:I,refreshToken:l,resource:n,addClientAuthentication:c,fetchFn:r}){var s;let a="refresh_token",G;if(e){if(G=new URL(e.token_endpoint),e.grant_types_supported&&!e.grant_types_supported.includes(a))throw new Error(`Incompatible auth server: does not support grant type ${a}`)}else G=new URL("/token",t);let d=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),i=new URLSearchParams({grant_type:a,refresh_token:l});if(c)c(d,i,t,e);else{let m=(s=e?.token_endpoint_auth_methods_supported)!==null&&s!==void 0?s:[],h=P8e(I,m);q8e(h,I,d,i)}n&&i.set("resource",n.href);let b=await(r??fetch)(G,{method:"POST",headers:d,body:i});if(!b.ok)throw await bWe(b);return dWe.parse({refresh_token:l,...await b.json()})}async function get(t,{metadata:e,clientMetadata:I,fetchFn:l}){let n;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");n=new URL(e.registration_endpoint)}else n=new URL("/register",t);let c=await(l??fetch)(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(I)});if(!c.ok)throw await bWe(c);return M8e.parse(await c.json())}var hWe=class extends Error{constructor(e,I,l){super(`SSE error: ${I}`),this.code=e,this.event=l}},a7=class{constructor(e,I){this._url=e,this._resourceMetadataUrl=void 0,this._eventSourceInit=I?.eventSourceInit,this._requestInit=I?.requestInit,this._authProvider=I?.authProvider,this._fetch=I?.fetch}async _authThenStart(){var e;if(!this._authProvider)throw new pG("No auth provider");let I;try{I=await qV(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(l){throw(e=this.onerror)===null||e===void 0||e.call(this,l),l}if(I!=="AUTHORIZED")throw new pG;return await this._startOrAuth()}async _commonHeaders(){var e;let I={};if(this._authProvider){let l=await this._authProvider.tokens();l&&(I.Authorization=`Bearer ${l.access_token}`)}return this._protocolVersion&&(I["mcp-protocol-version"]=this._protocolVersion),new Headers({...I,...(e=this._requestInit)===null||e===void 0?void 0:e.headers})}_startOrAuth(){var e,I,l;let n=(l=(I=(e=this===null||this===void 0?void 0:this._eventSourceInit)===null||e===void 0?void 0:e.fetch)!==null&&I!==void 0?I:this._fetch)!==null&&l!==void 0?l:fetch;return new Promise((c,r)=>{this._eventSource=new Dg(this._url.href,{...this._eventSourceInit,fetch:async(s,a)=>{let G=await this._commonHeaders();G.set("Accept","text/event-stream");let d=await n(s,{...a,headers:G});return d.status===401&&d.headers.has("www-authenticate")&&(this._resourceMetadataUrl=PB(d)),d}}),this._abortController=new AbortController,this._eventSource.onerror=s=>{var a;if(s.code===401&&this._authProvider){this._authThenStart().then(c,r);return}let G=new hWe(s.code,s.message,s);r(G),(a=this.onerror)===null||a===void 0||a.call(this,G)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",s=>{var a;let G=s;try{if(this._endpoint=new URL(G.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(d){r(d),(a=this.onerror)===null||a===void 0||a.call(this,d),this.close();return}c()}),this._eventSource.onmessage=s=>{var a,G;let d=s,i;try{i=UV.parse(JSON.parse(d.data))}catch(b){(a=this.onerror)===null||a===void 0||a.call(this,b);return}(G=this.onmessage)===null||G===void 0||G.call(this,i)}})}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 pG("No auth provider");if(await qV(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new pG("Failed to authorize")}async close(){var e,I,l;(e=this._abortController)===null||e===void 0||e.abort(),(I=this._eventSource)===null||I===void 0||I.close(),(l=this.onclose)===null||l===void 0||l.call(this)}async send(e){var I,l,n;if(!this._endpoint)throw new Error("Not connected");try{let c=await this._commonHeaders();c.set("content-type","application/json");let r={...this._requestInit,method:"POST",headers:c,body:JSON.stringify(e),signal:(I=this._abortController)===null||I===void 0?void 0:I.signal},s=await((l=this._fetch)!==null&&l!==void 0?l:fetch)(this._endpoint,r);if(!s.ok){if(s.status===401&&this._authProvider){if(this._resourceMetadataUrl=PB(s),await qV(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new pG;return this.send(e)}let a=await s.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${s.status}): ${a}`)}}catch(c){throw(n=this.onerror)===null||n===void 0||n.call(this,c),c}}setProtocolVersion(e){this._protocolVersion=e}};o();var z7e=Ll(x7e(),1);import i7 from"node:process";import{PassThrough as eIt}from"node:stream";o();var G7=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
1409
1409
  `);if(e===-1)return null;let I=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),$et(I)}clear(){this._buffer=void 0}};function $et(t){return UV.parse(JSON.parse(t))}function B7e(t){return JSON.stringify(t)+`
1410
- `}var IIt=i7.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function tIt(){let t={};for(let e of IIt){let I=i7.env[e];I!==void 0&&(I.startsWith("()")||(t[e]=I))}return t}var d7=class{constructor(e){this._abortController=new AbortController,this._readBuffer=new G7,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new eIt)}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,I)=>{var l,n,c,r,s;this._process=(0,z7e.default)(this._serverParams.command,(l=this._serverParams.args)!==null&&l!==void 0?l:[],{env:{...tIt(),...this._serverParams.env},stdio:["pipe","pipe",(n=this._serverParams.stderr)!==null&&n!==void 0?n:"inherit"],shell:!1,signal:this._abortController.signal,windowsHide:i7.platform==="win32"&&lIt(),cwd:this._serverParams.cwd}),this._process.on("error",a=>{var G,d;if(a.name==="AbortError"){(G=this.onclose)===null||G===void 0||G.call(this);return}I(a),(d=this.onerror)===null||d===void 0||d.call(this,a)}),this._process.on("spawn",()=>{e()}),this._process.on("close",a=>{var G;this._process=void 0,(G=this.onclose)===null||G===void 0||G.call(this)}),(c=this._process.stdin)===null||c===void 0||c.on("error",a=>{var G;(G=this.onerror)===null||G===void 0||G.call(this,a)}),(r=this._process.stdout)===null||r===void 0||r.on("data",a=>{this._readBuffer.append(a),this.processReadBuffer()}),(s=this._process.stdout)===null||s===void 0||s.on("error",a=>{var G;(G=this.onerror)===null||G===void 0||G.call(this,a)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){var e,I;return this._stderrStream?this._stderrStream:(I=(e=this._process)===null||e===void 0?void 0:e.stderr)!==null&&I!==void 0?I:null}get pid(){var e,I;return(I=(e=this._process)===null||e===void 0?void 0:e.pid)!==null&&I!==void 0?I:null}processReadBuffer(){for(var e,I;;)try{let l=this._readBuffer.readMessage();if(l===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,l)}catch(l){(I=this.onerror)===null||I===void 0||I.call(this,l)}}async close(){this._abortController.abort(),this._process=void 0,this._readBuffer.clear()}send(e){return new Promise(I=>{var l;if(!(!((l=this._process)===null||l===void 0)&&l.stdin))throw new Error("Not connected");let n=B7e(e);this._process.stdin.write(n)?I():this._process.stdin.once("drain",I)})}};function lIt(){return"type"in i7}o();o();var b7=class extends TransformStream{constructor({onError:e,onRetry:I,onComment:l}={}){let n;super({start(c){n=n7({onEvent:r=>{c.enqueue(r)},onError(r){e==="terminate"?c.error(r):typeof e=="function"&&e(r)},onRetry:I,onComment:l})},transform(c){n.feed(c)}})}};var nIt={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},qB=class extends Error{constructor(e,I){super(`Streamable HTTP error: ${I}`),this.code=e}},m7=class{constructor(e,I){var l;this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=I?.requestInit,this._authProvider=I?.authProvider,this._fetch=I?.fetch,this._sessionId=I?.sessionId,this._reconnectionOptions=(l=I?.reconnectionOptions)!==null&&l!==void 0?l:nIt}async _authThenStart(){var e;if(!this._authProvider)throw new pG("No auth provider");let I;try{I=await qV(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(l){throw(e=this.onerror)===null||e===void 0||e.call(this,l),l}if(I!=="AUTHORIZED")throw new pG;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let I={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(I.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(I["mcp-session-id"]=this._sessionId),this._protocolVersion&&(I["mcp-protocol-version"]=this._protocolVersion);let l=this._normalizeHeaders((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...I,...l})}async _startOrAuthSse(e){var I,l,n;let{resumptionToken:c}=e;try{let r=await this._commonHeaders();r.set("Accept","text/event-stream"),c&&r.set("last-event-id",c);let s=await((I=this._fetch)!==null&&I!==void 0?I:fetch)(this._url,{method:"GET",headers:r,signal:(l=this._abortController)===null||l===void 0?void 0:l.signal});if(!s.ok){if(s.status===401&&this._authProvider)return await this._authThenStart();if(s.status===405)return;throw new qB(s.status,`Failed to open SSE stream: ${s.statusText}`)}this._handleSseStream(s.body,e,!0)}catch(r){throw(n=this.onerror)===null||n===void 0||n.call(this,r),r}}_getNextReconnectionDelay(e){let I=this._reconnectionOptions.initialReconnectionDelay,l=this._reconnectionOptions.reconnectionDelayGrowFactor,n=this._reconnectionOptions.maxReconnectionDelay;return Math.min(I*Math.pow(l,e),n)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,I=0){var l;let n=this._reconnectionOptions.maxRetries;if(n>0&&I>=n){(l=this.onerror)===null||l===void 0||l.call(this,new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let c=this._getNextReconnectionDelay(I);setTimeout(()=>{this._startOrAuthSse(e).catch(r=>{var s;(s=this.onerror)===null||s===void 0||s.call(this,new Error(`Failed to reconnect SSE stream: ${r instanceof Error?r.message:String(r)}`)),this._scheduleReconnection(e,I+1)})},c)}_handleSseStream(e,I,l){if(!e)return;let{onresumptiontoken:n,replayMessageId:c}=I,r;(async()=>{var a,G,d,i;try{let b=e.pipeThrough(new TextDecoderStream).pipeThrough(new b7).getReader();for(;;){let{value:m,done:h}=await b.read();if(h)break;if(m.id&&(r=m.id,n?.(m.id)),!m.event||m.event==="message")try{let p=UV.parse(JSON.parse(m.data));c!==void 0&&nB(p)&&(p.id=c),(a=this.onmessage)===null||a===void 0||a.call(this,p)}catch(p){(G=this.onerror)===null||G===void 0||G.call(this,p)}}}catch(b){if((d=this.onerror)===null||d===void 0||d.call(this,new Error(`SSE stream disconnected: ${b}`)),l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:r,onresumptiontoken:n,replayMessageId:c},0)}catch(m){(i=this.onerror)===null||i===void 0||i.call(this,new Error(`Failed to reconnect: ${m instanceof Error?m.message:String(m)}`))}}})()}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 pG("No auth provider");if(await qV(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new pG("Failed to authorize")}async close(){var e,I;(e=this._abortController)===null||e===void 0||e.abort(),(I=this.onclose)===null||I===void 0||I.call(this)}async send(e,I){var l,n,c,r;try{let{resumptionToken:s,onresumptiontoken:a}=I||{};if(s){this._startOrAuthSse({resumptionToken:s,replayMessageId:i8(e)?e.id:void 0}).catch(Z=>{var W;return(W=this.onerror)===null||W===void 0?void 0:W.call(this,Z)});return}let G=await this._commonHeaders();G.set("content-type","application/json"),G.set("accept","application/json, text/event-stream");let d={...this._requestInit,method:"POST",headers:G,body:JSON.stringify(e),signal:(l=this._abortController)===null||l===void 0?void 0:l.signal},i=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._url,d),b=i.headers.get("mcp-session-id");if(b&&(this._sessionId=b),!i.ok){if(i.status===401&&this._authProvider){if(this._resourceMetadataUrl=PB(i),await qV(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new pG;return this.send(e)}let Z=await i.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${i.status}): ${Z}`)}if(i.status===202){qPe(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(Z=>{var W;return(W=this.onerror)===null||W===void 0?void 0:W.call(this,Z)});return}let h=(Array.isArray(e)?e:[e]).filter(Z=>"method"in Z&&"id"in Z&&Z.id!==void 0).length>0,p=i.headers.get("content-type");if(h)if(p?.includes("text/event-stream"))this._handleSseStream(i.body,{onresumptiontoken:a},!1);else if(p?.includes("application/json")){let Z=await i.json(),W=Array.isArray(Z)?Z.map(Y=>UV.parse(Y)):[UV.parse(Z)];for(let Y of W)(c=this.onmessage)===null||c===void 0||c.call(this,Y)}else throw new qB(-1,`Unexpected content type: ${p}`)}catch(s){throw(r=this.onerror)===null||r===void 0||r.call(this,s),s}}get sessionId(){return this._sessionId}async terminateSession(){var e,I,l;if(this._sessionId)try{let n=await this._commonHeaders(),c={...this._requestInit,method:"DELETE",headers:n,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},r=await((I=this._fetch)!==null&&I!==void 0?I:fetch)(this._url,c);if(!r.ok&&r.status!==405)throw new qB(r.status,`Failed to terminate session: ${r.statusText}`);this._sessionId=void 0}catch(n){throw(l=this.onerror)===null||l===void 0||l.call(this,n),n}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}};o();var h7=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 gWe(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(I){this.onerror?.(I instanceof Error?I:new Error(String(I)))}})}receive(e){this.closed||this.onmessage?.(e)}async close(){this.closed||(this.closed=!0,await this.serverTransport?.close(),this.onclose?.())}},gWe=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(I){this.onerror?.(I instanceof Error?I:new Error(String(I)))}})}async close(){this.closed||(this.closed=!0,this.onclose?.())}};var p7=class{createTransport(e){switch(e.type){case"stdio":{let I=new d7({command:e.command,args:e.args,env:e.env,stderr:e.stderr?"pipe":void 0});return I.stderr?.pipe(e.stderr),I}case"http":return new m7(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"sse":return new a7(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"memory":return new h7(e.server);default:throw new Error(`Unsupported transport type: ${e.type}`)}}};o();var _g="blackbird-mcp-server",lv="github-mcp-server",FWe="playwright";function nv(t){return t.type===void 0||t.type.toLowerCase()==="local"||t.type.toLowerCase()==="stdio"}function u7(t){return t.type?.toLowerCase()==="http"}function Z7(t){return t.type?.toLowerCase()==="sse"}function _B(t){return t.type?.toLowerCase()==="memory"}var AWe=class extends cIt{constructor(I,l){super({decodeStrings:!1});this.serverName=I;this.logger=l}_write(I,l,n){try{let c=I.toString();this.logger.log(`[mcp server ${this.serverName} stderr] ${c}`),n()}catch(c){n(c instanceof Error?c:new Error(String(c)))}}},W7=class{constructor(e,I=new t7,l=new p7,n="indirect"){this.logger=e;this.clientFactory=I;this.transportFactory=l;this.envValueMode=n}clients={};transports={};async startLocalMcpClient(e,I,l,n){this.logger.log(`Starting MCP client for ${e} with command: ${l} and args: ${n}`);let c=new AWe(e,this.logger),r={type:"stdio",command:l,args:n,env:{...I,PATH:process.env.PATH},stderr:c},s=this.transportFactory.createTransport(r);await this.setupAndConnectClient(e,s)}async startHttpMcpClient(e,I){this.logger.log(`Starting remote MCP client for ${e} with url: ${I.url}`);let l={type:"http",url:I.url,headers:I.headers},n=this.transportFactory.createTransport(l);await this.setupAndConnectClient(e,n)}async startSseMcpClient(e,I){this.logger.log(`Starting remote MCP client for ${e} with url: ${I.url}`);let l={type:"sse",url:I.url,headers:I.headers},n=this.transportFactory.createTransport(l);await this.setupAndConnectClient(e,n)}async startInMemoryMcpClient(e,I){this.logger.log(`Starting in-memory MCP client for ${e}`);let l={type:"memory",server:I},n=this.transportFactory.createTransport(l);await this.setupAndConnectClient(e,n)}async setupAndConnectClient(e,I){this.transports[e]=I,I.onclose=()=>{this.logger.log(`MCP transport for ${e} closed`),delete this.transports[e]},this.logger.log(`Creating MCP client for ${e}...`);let l=this.clientFactory.createClient({name:"github-copilot-developer",version:"1.0.0"},{capabilities:{experimental:void 0,roots:void 0,sampling:void 0}}),n=Date.now();this.logger.log(`Connecting MCP client for ${e}...`),await l.connect(I),l.onclose=()=>{this.logger.log(`MCP client for ${e} closed`),delete this.clients[e]},l.onerror=c=>{this.logger.error(`MCP client for ${e} errored ${c}`)},this.logger.log(`MCP client for ${e} connected, took ${Date.now()-n}ms`),this.clients[e]=l}async getTools(e,I){let l={};for(let[n,c]of Object.entries(this.clients)){let r=[];try{this.logger.log(`Fetching tools from client: ${n}`);let s=await c.listTools(),a=e?.mcpServers[n].tools,G=e?.mcpServers[n].filterMapping;for(let i of s.tools){if(i.name==="get_copilot_space")continue;if(!(a?.includes("*")||a?.includes(i.name))){this.logger.log(`Tool ${i.name} is not in the allowed list for client: ${n}`);continue}let m=Pq(n,i.name),h=`${n}-${i.name}`,p;typeof G=="string"?p=Che(G):p=Che(G?.[i.name]??"hidden_characters"),l[`${n}/${i.name}`]={name:h,namespacedName:`${n}/${i.name}`,title:i.title??i.annotations?.title??i.name,description:i.description??h,input_schema:i.inputSchema,readOnly:i.annotations?.readOnlyHint,safeForTelemetry:{name:!!(e?.mcpServers[n].isDefaultServer||m),inputsNames:!!e?.mcpServers[n].isDefaultServer},filterMode:p},r.push(i.name),this.logger.log(`Tool ${i.name} added to tools list for client: ${n}`)}this.logger.log(`Successfully retrieved ${r.length} tools from client: ${n}`);let d=c.getServerVersion();await this.logServerSuccessWithTools(n,r,d,I)}catch(s){this.logger.error(`Failed to get tools from client: ${n} ${s}`)}}return this.logger.log(`All tools retrieved: ${JSON.stringify(l,null,2)}`),l}async logServerSuccessWithTools(e,I,l,n){if(e!=_g&&n)try{let c=I.map(a=>`- ${a}`).join(`
1410
+ `}var IIt=i7.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function tIt(){let t={};for(let e of IIt){let I=i7.env[e];I!==void 0&&(I.startsWith("()")||(t[e]=I))}return t}var d7=class{constructor(e){this._abortController=new AbortController,this._readBuffer=new G7,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new eIt)}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,I)=>{var l,n,c,r,s;this._process=(0,z7e.default)(this._serverParams.command,(l=this._serverParams.args)!==null&&l!==void 0?l:[],{env:{...tIt(),...this._serverParams.env},stdio:["pipe","pipe",(n=this._serverParams.stderr)!==null&&n!==void 0?n:"inherit"],shell:!1,signal:this._abortController.signal,windowsHide:i7.platform==="win32"&&lIt(),cwd:this._serverParams.cwd}),this._process.on("error",a=>{var G,d;if(a.name==="AbortError"){(G=this.onclose)===null||G===void 0||G.call(this);return}I(a),(d=this.onerror)===null||d===void 0||d.call(this,a)}),this._process.on("spawn",()=>{e()}),this._process.on("close",a=>{var G;this._process=void 0,(G=this.onclose)===null||G===void 0||G.call(this)}),(c=this._process.stdin)===null||c===void 0||c.on("error",a=>{var G;(G=this.onerror)===null||G===void 0||G.call(this,a)}),(r=this._process.stdout)===null||r===void 0||r.on("data",a=>{this._readBuffer.append(a),this.processReadBuffer()}),(s=this._process.stdout)===null||s===void 0||s.on("error",a=>{var G;(G=this.onerror)===null||G===void 0||G.call(this,a)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){var e,I;return this._stderrStream?this._stderrStream:(I=(e=this._process)===null||e===void 0?void 0:e.stderr)!==null&&I!==void 0?I:null}get pid(){var e,I;return(I=(e=this._process)===null||e===void 0?void 0:e.pid)!==null&&I!==void 0?I:null}processReadBuffer(){for(var e,I;;)try{let l=this._readBuffer.readMessage();if(l===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,l)}catch(l){(I=this.onerror)===null||I===void 0||I.call(this,l)}}async close(){this._abortController.abort(),this._process=void 0,this._readBuffer.clear()}send(e){return new Promise(I=>{var l;if(!(!((l=this._process)===null||l===void 0)&&l.stdin))throw new Error("Not connected");let n=B7e(e);this._process.stdin.write(n)?I():this._process.stdin.once("drain",I)})}};function lIt(){return"type"in i7}o();o();var b7=class extends TransformStream{constructor({onError:e,onRetry:I,onComment:l}={}){let n;super({start(c){n=n7({onEvent:r=>{c.enqueue(r)},onError(r){e==="terminate"?c.error(r):typeof e=="function"&&e(r)},onRetry:I,onComment:l})},transform(c){n.feed(c)}})}};var nIt={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},qB=class extends Error{constructor(e,I){super(`Streamable HTTP error: ${I}`),this.code=e}},m7=class{constructor(e,I){var l;this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=I?.requestInit,this._authProvider=I?.authProvider,this._fetch=I?.fetch,this._sessionId=I?.sessionId,this._reconnectionOptions=(l=I?.reconnectionOptions)!==null&&l!==void 0?l:nIt}async _authThenStart(){var e;if(!this._authProvider)throw new pG("No auth provider");let I;try{I=await qV(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(l){throw(e=this.onerror)===null||e===void 0||e.call(this,l),l}if(I!=="AUTHORIZED")throw new pG;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let I={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(I.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(I["mcp-session-id"]=this._sessionId),this._protocolVersion&&(I["mcp-protocol-version"]=this._protocolVersion);let l=this._normalizeHeaders((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...I,...l})}async _startOrAuthSse(e){var I,l,n;let{resumptionToken:c}=e;try{let r=await this._commonHeaders();r.set("Accept","text/event-stream"),c&&r.set("last-event-id",c);let s=await((I=this._fetch)!==null&&I!==void 0?I:fetch)(this._url,{method:"GET",headers:r,signal:(l=this._abortController)===null||l===void 0?void 0:l.signal});if(!s.ok){if(s.status===401&&this._authProvider)return await this._authThenStart();if(s.status===405)return;throw new qB(s.status,`Failed to open SSE stream: ${s.statusText}`)}this._handleSseStream(s.body,e,!0)}catch(r){throw(n=this.onerror)===null||n===void 0||n.call(this,r),r}}_getNextReconnectionDelay(e){let I=this._reconnectionOptions.initialReconnectionDelay,l=this._reconnectionOptions.reconnectionDelayGrowFactor,n=this._reconnectionOptions.maxReconnectionDelay;return Math.min(I*Math.pow(l,e),n)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,I=0){var l;let n=this._reconnectionOptions.maxRetries;if(n>0&&I>=n){(l=this.onerror)===null||l===void 0||l.call(this,new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let c=this._getNextReconnectionDelay(I);setTimeout(()=>{this._startOrAuthSse(e).catch(r=>{var s;(s=this.onerror)===null||s===void 0||s.call(this,new Error(`Failed to reconnect SSE stream: ${r instanceof Error?r.message:String(r)}`)),this._scheduleReconnection(e,I+1)})},c)}_handleSseStream(e,I,l){if(!e)return;let{onresumptiontoken:n,replayMessageId:c}=I,r;(async()=>{var a,G,d,i;try{let b=e.pipeThrough(new TextDecoderStream).pipeThrough(new b7).getReader();for(;;){let{value:m,done:h}=await b.read();if(h)break;if(m.id&&(r=m.id,n?.(m.id)),!m.event||m.event==="message")try{let p=UV.parse(JSON.parse(m.data));c!==void 0&&nB(p)&&(p.id=c),(a=this.onmessage)===null||a===void 0||a.call(this,p)}catch(p){(G=this.onerror)===null||G===void 0||G.call(this,p)}}}catch(b){if((d=this.onerror)===null||d===void 0||d.call(this,new Error(`SSE stream disconnected: ${b}`)),l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:r,onresumptiontoken:n,replayMessageId:c},0)}catch(m){(i=this.onerror)===null||i===void 0||i.call(this,new Error(`Failed to reconnect: ${m instanceof Error?m.message:String(m)}`))}}})()}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 pG("No auth provider");if(await qV(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new pG("Failed to authorize")}async close(){var e,I;(e=this._abortController)===null||e===void 0||e.abort(),(I=this.onclose)===null||I===void 0||I.call(this)}async send(e,I){var l,n,c,r;try{let{resumptionToken:s,onresumptiontoken:a}=I||{};if(s){this._startOrAuthSse({resumptionToken:s,replayMessageId:i8(e)?e.id:void 0}).catch(Z=>{var W;return(W=this.onerror)===null||W===void 0?void 0:W.call(this,Z)});return}let G=await this._commonHeaders();G.set("content-type","application/json"),G.set("accept","application/json, text/event-stream");let d={...this._requestInit,method:"POST",headers:G,body:JSON.stringify(e),signal:(l=this._abortController)===null||l===void 0?void 0:l.signal},i=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._url,d),b=i.headers.get("mcp-session-id");if(b&&(this._sessionId=b),!i.ok){if(i.status===401&&this._authProvider){if(this._resourceMetadataUrl=PB(i),await qV(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new pG;return this.send(e)}let Z=await i.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${i.status}): ${Z}`)}if(i.status===202){qPe(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(Z=>{var W;return(W=this.onerror)===null||W===void 0?void 0:W.call(this,Z)});return}let h=(Array.isArray(e)?e:[e]).filter(Z=>"method"in Z&&"id"in Z&&Z.id!==void 0).length>0,p=i.headers.get("content-type");if(h)if(p?.includes("text/event-stream"))this._handleSseStream(i.body,{onresumptiontoken:a},!1);else if(p?.includes("application/json")){let Z=await i.json(),W=Array.isArray(Z)?Z.map(Y=>UV.parse(Y)):[UV.parse(Z)];for(let Y of W)(c=this.onmessage)===null||c===void 0||c.call(this,Y)}else throw new qB(-1,`Unexpected content type: ${p}`)}catch(s){throw(r=this.onerror)===null||r===void 0||r.call(this,s),s}}get sessionId(){return this._sessionId}async terminateSession(){var e,I,l;if(this._sessionId)try{let n=await this._commonHeaders(),c={...this._requestInit,method:"DELETE",headers:n,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},r=await((I=this._fetch)!==null&&I!==void 0?I:fetch)(this._url,c);if(!r.ok&&r.status!==405)throw new qB(r.status,`Failed to terminate session: ${r.statusText}`);this._sessionId=void 0}catch(n){throw(l=this.onerror)===null||l===void 0||l.call(this,n),n}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}};o();var h7=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 gWe(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(I){this.onerror?.(I instanceof Error?I:new Error(String(I)))}})}receive(e){this.closed||this.onmessage?.(e)}async close(){this.closed||(this.closed=!0,await this.serverTransport?.close(),this.onclose?.())}},gWe=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(I){this.onerror?.(I instanceof Error?I:new Error(String(I)))}})}async close(){this.closed||(this.closed=!0,this.onclose?.())}};var p7=class{createTransport(e){switch(e.type){case"stdio":{let I=new d7({command:e.command,args:e.args,env:e.env,stderr:e.stderr?"pipe":void 0,cwd:e.cwd});return I.stderr?.pipe(e.stderr),I}case"http":return new m7(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"sse":return new a7(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"memory":return new h7(e.server);default:throw new Error(`Unsupported transport type: ${e.type}`)}}};o();var _g="blackbird-mcp-server",lv="github-mcp-server",FWe="playwright";function nv(t){return t.type===void 0||t.type.toLowerCase()==="local"||t.type.toLowerCase()==="stdio"}function u7(t){return t.type?.toLowerCase()==="http"}function Z7(t){return t.type?.toLowerCase()==="sse"}function _B(t){return t.type?.toLowerCase()==="memory"}var AWe=class extends cIt{constructor(I,l){super({decodeStrings:!1});this.serverName=I;this.logger=l}_write(I,l,n){try{let c=I.toString();this.logger.log(`[mcp server ${this.serverName} stderr] ${c}`),n()}catch(c){n(c instanceof Error?c:new Error(String(c)))}}},W7=class{constructor(e,I=new t7,l=new p7,n="indirect"){this.logger=e;this.clientFactory=I;this.transportFactory=l;this.envValueMode=n}clients={};transports={};async startLocalMcpClient(e,I,l,n,c){this.logger.log(`Starting MCP client for ${e} with command: ${l} and args: ${n}`);let r=new AWe(e,this.logger),s={type:"stdio",command:l,args:n,env:{...I,PATH:process.env.PATH},stderr:r,cwd:c},a=this.transportFactory.createTransport(s);await this.setupAndConnectClient(e,a)}async startHttpMcpClient(e,I){this.logger.log(`Starting remote MCP client for ${e} with url: ${I.url}`);let l={type:"http",url:I.url,headers:I.headers},n=this.transportFactory.createTransport(l);await this.setupAndConnectClient(e,n)}async startSseMcpClient(e,I){this.logger.log(`Starting remote MCP client for ${e} with url: ${I.url}`);let l={type:"sse",url:I.url,headers:I.headers},n=this.transportFactory.createTransport(l);await this.setupAndConnectClient(e,n)}async startInMemoryMcpClient(e,I){this.logger.log(`Starting in-memory MCP client for ${e}`);let l={type:"memory",server:I},n=this.transportFactory.createTransport(l);await this.setupAndConnectClient(e,n)}async setupAndConnectClient(e,I){this.transports[e]=I,I.onclose=()=>{this.logger.log(`MCP transport for ${e} closed`),delete this.transports[e]},this.logger.log(`Creating MCP client for ${e}...`);let l=this.clientFactory.createClient({name:"github-copilot-developer",version:"1.0.0"},{capabilities:{experimental:void 0,roots:void 0,sampling:void 0}}),n=Date.now();this.logger.log(`Connecting MCP client for ${e}...`),await l.connect(I),l.onclose=()=>{this.logger.log(`MCP client for ${e} closed`),delete this.clients[e]},l.onerror=c=>{this.logger.error(`MCP client for ${e} errored ${c}`)},this.logger.log(`MCP client for ${e} connected, took ${Date.now()-n}ms`),this.clients[e]=l}async getTools(e,I){let l={};for(let[n,c]of Object.entries(this.clients)){let r=[];try{this.logger.log(`Fetching tools from client: ${n}`);let s=await c.listTools(),a=e?.mcpServers[n].tools,G=e?.mcpServers[n].filterMapping;for(let i of s.tools){if(i.name==="get_copilot_space")continue;if(!(a?.includes("*")||a?.includes(i.name))){this.logger.log(`Tool ${i.name} is not in the allowed list for client: ${n}`);continue}let m=Pq(n,i.name),h=`${n}-${i.name}`,p;typeof G=="string"?p=Che(G):p=Che(G?.[i.name]??"hidden_characters"),l[`${n}/${i.name}`]={name:h,namespacedName:`${n}/${i.name}`,title:i.title??i.annotations?.title??i.name,description:i.description??h,input_schema:i.inputSchema,readOnly:i.annotations?.readOnlyHint,safeForTelemetry:{name:!!(e?.mcpServers[n].isDefaultServer||m),inputsNames:!!e?.mcpServers[n].isDefaultServer},filterMode:p},r.push(i.name),this.logger.log(`Tool ${i.name} added to tools list for client: ${n}`)}this.logger.log(`Successfully retrieved ${r.length} tools from client: ${n}`);let d=c.getServerVersion();await this.logServerSuccessWithTools(n,r,d,I)}catch(s){this.logger.error(`Failed to get tools from client: ${n} ${s}`)}}return this.logger.log(`All tools retrieved: ${JSON.stringify(l,null,2)}`),l}async logServerSuccessWithTools(e,I,l,n){if(e!=_g&&n)try{let c=I.map(a=>`- ${a}`).join(`
1411
1411
  `),s=`MCP server started successfully${l?` (version ${l.version})`:""} with ${I.length} ${I.length===1?"tool":"tools"} - for the full output, see the verbose logs
1412
1412
 
1413
- ${c}`;await n.logMCPSetup(e,s),this.logger.log(`Updated session log for ${e} with ${I.length} tools`)}catch(c){this.logger.error(`Failed to update session log for ${e}: ${c}`)}}};o();var QWe={mcpServers:{}},N7=class{constructor(e,I,l){this.logger=e;this.registry=I;this.remoteEnabled=l?.remoteEnabled??!1,this.mcp3pEnabled=l?.mcp3pEnabled??!1,this.blackbirdMetisIndexEnabled=l?.blackbirdMetisIndexEnabled??!1,this.sessionClient=l?.sessionClient,this.mcpEnvConfig=void 0,this.envValueMode=l?.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 I=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(I,e),this.configureGitHubMcp(I,e),this.configurePlaywrightMcp(I)),I}validateEnvConfig(){if(!this.mcp3pEnabled)return this.logger.log("User-provided MCPs are disabled"),QWe;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"),QWe;try{let e=JSON.parse(this.mcpEnvConfig);if(!e.mcpServers)throw new Error("User-provided config had incorrect format. Missing 'mcpServers' property.");for(let I in e.mcpServers)e.mcpServers[I].isDefaultServer=!1;return e}catch(e){return this.logger.error(`Warning: User-provided MCP servers were defined but invalid: ${e}`),QWe}}configureGitHubMcp(e,I){this.remoteEnabled?this.configureRemoteGitHubMcp(e,I):this.configureLocalGitHubMcp(e)}configureRemoteGitHubMcp(e,I){this.logger.log("Using default remote GitHub MCP server configuration");let l="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"),l=l+",copilot_spaces");let n={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":l,"X-MCP-Host":"github-coding-agent","X-Initiator":"agent"};I&&I.api?.copilot?.integrationId&&(n["Copilot-Integration-Id"]=I.api.copilot.integrationId),process.env.GITHUB_COPILOT_INTERACTION_ID&&(n["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let c={type:"http",url:this.getCapiMcpUrl(),headers:n,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[lv]=c}configureLocalGitHubMcp(e){if(e.mcpServers[lv]){this.logger.log("Using user-provided GitHub MCP server configuration");let I=e.mcpServers[lv]??{};nv(I)&&!I.command&&(e.mcpServers[lv]={...I,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 I={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[lv]=I}}configurePlaywrightMcp(e){if(!e.mcpServers[FWe]){if((process.env.COPILOT_FEATURE_FLAGS??"").split(",").map(l=>l.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 I={command:"npx",args:[...Bpe,"--allowed-origins","localhost;localhost:*;127.0.0.1;127.0.0.1:*"],tools:["*"],isDefaultServer:!0};e.mcpServers[FWe]=I}}configureBlackbirdMcp(e,I){this.remoteEnabled?this.configureRemoteBlackbirdMcp(e):this.blackbirdMetisIndexEnabled?this.configureLocalMetisBlackbirdMCP(e,I):this.configureLocalBlackbirdMcp(e)}configureLocalMetisBlackbirdMCP(e,I){this.logger.log("Using local Metis Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${I.blackbird?.mode}`);let l=process.env.AGENT_DIR||"/agent";this.logger.log(`Using agent directory: ${l}`);let n=[];I.blackbird?.mode==="tool"&&(n=["*"]),this.logger.log(`Using blackbird Metis server: ${I.blackbird?.mode}`);let c={command:`${l}/blackbird/mcp`,args:["serve","--index",`${l}/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:n,isDefaultServer:!0};e.mcpServers[_g]=c}configureLocalBlackbirdMcp(e){this.logger.log("Using local Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let I=[];process.env.BLACKBIRD_MODE==="tool"&&(I=["*"]);let l={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:I,isDefaultServer:!0};e.mcpServers[_g]=l}configureRemoteBlackbirdMcp(e){this.logger.log("Using remote Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let I=[];process.env.BLACKBIRD_MODE==="tool"&&(I=["*"]);let l={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&&(l["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let n={type:"http",url:this.getCapiMcpUrl(),headers:l,tools:I,isDefaultServer:!0};e.mcpServers[_g]=n}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 nv(e)||u7(e)||Z7(e)||_B(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,I){return this.remoteEnabled&&!this.isValidServerType(I)?(this.logger.error(`Unsupported server type "${I.type}" for server "${e}". Only "Local", "STDIO", "HTTP", "SSE", or "Memory" are supported.`),!1):!this.remoteEnabled&&!nv(I)&&!_B(I)?(this.logger.error(`Unsupported server type "${I.type}" for server "${e}". Only "Local", "STDIO", or "Memory" are supported.`),!1):I.tools?nv(I)&&!this.isValidLocalServerConfig(I)?(this.logger.error(`Invalid local server configuration for "${e}". Please ensure 'command' and 'args' are provided.`),!1):(u7(I)||Z7(I))&&!this.isValidRemoteServerConfig(I)?(this.logger.error(`Invalid remote server configuration for "${e}". Please ensure 'url' is provided.`),!1):_B(I)&&!this.isValidInMemoryServerConfig(I)?(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,I){try{let l=this.resolveHeaders(I.headers,process.env),n={...I,headers:l};await this.registry.startHttpMcpClient(e,n),this.logger.log(`Started MCP client for remote server ${e}`)}catch(l){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${l}`),l}}async processSseServer(e,I){try{let l=this.resolveRemoteServerConfig(I);await this.registry.startSseMcpClient(e,l),this.logger.log(`Started MCP client for remote server ${e}`)}catch(l){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${l}`),l}}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,I){try{await this.registry.startInMemoryMcpClient(e,I.serverInstance),this.logger.log(`Started in-memory MCP client for ${e}`)}catch(l){throw this.logger.error(`Failed to start in-memory MCP client for ${e}: ${l}`),l}}async processLocalServer(e,I){let l={...I};if(I.command==="python")try{l=await this.convertPythonToPipx(l)}catch(r){this.logger.error(`Failed to handle Python module for ${e}: ${r}`)}let n=this.buildEnvironment(l),c=this.resolveLocalServerConfig(l,n);this.logger.log(`Starting MCP client for ${e} with command: ${c.command} and args: ${c.args}`);try{await this.registry.startLocalMcpClient(e,n,c.command,c.args),this.logger.log(`Started MCP client for ${e}`)}catch(r){throw this.logger.error(`Failed to start MCP client for ${e}: ${r}`),r}}convertPythonToPipx(e){if(!e||!e.args||e.args.length===0)return e;let I=e.args,l=I.indexOf("-m");if(l===-1||l===I.length-1)throw new Error("Python command with -m flag must specify a module");let n=I[l+1];this.logger.log(`Converting Python module: ${n} to pipx command`);let c=["run",n];for(let r=l+2;r<I.length;r++)c.push(I[r]);for(let r=0;r<l;r++)c.push(I[r]);return{...e,command:"pipx",args:c}}buildEnvironment(e){let I={};if(e.env)if(this.envValueMode==="direct")for(let[l,n]of Object.entries(e.env))I[l]=this.resolveString(n,process.env);else for(let[l,n]of Object.entries(e.env)){let c=n.trim(),r=c;if(c.includes("$")&&(r=this.resolveString(c,process.env)),r!==c){I[l]=r;continue}process.env[c]!==void 0&&(I[l]=process.env[c])}return I}resolveLocalServerConfig(e,I){let l=this.resolveString(e.command,I),n=this.resolveArray(e.args,I);return{...e,command:l,args:n}}resolveString(e,I){return I?e.replace(/\$(?:\{([A-Z0-9_]+)(?::-(.*?))?\}|([A-Z0-9_]+))/g,(l,n,c,r)=>{let a=I[n||r];return a!==void 0?a:c!==void 0?c:l}):e}resolveArray(e,I){return e?I?e.map(l=>this.resolveString(l,I)):e:[]}resolveHeaders(e,I){if(!e)return{};if(!I)return e;let l={};for(let[n,c]of Object.entries(e)){let r=this.resolveArray([c],I);l[n]=r[0]}return l}async processServers(e){if(!e)throw new Error("No servers to process");let I=Object.entries(e.mcpServers).map(([l,n])=>this.processServer(l,n));await Promise.all(I)}async processServer(e,I){if(!this.validateServerConfig(e,I)){this.logger.error(`Skipping server "${e}" due to invalid configuration.`);return}try{nv(I)?await this.processLocalServer(e,I):u7(I)&&this.remoteEnabled?await this.processHttpServer(e,I):Z7(I)&&this.remoteEnabled?await this.processSseServer(e,I):_B(I)&&await this.processInMemoryServer(e,I)}catch(l){e!==_g&&await this.logServerFailure(e,l)}}async logServerFailure(e,I){if(this.sessionClient)try{await this.sessionClient.logMCPSetup(e,`<error>MCP server failed to start: ${I.message} - for the full output, see the verbose logs</error>`)}catch(l){this.logger.error(`Failed to log failure for MCP Server '${e}': '${l}'`)}}};var Y7=class{constructor(e,I,l,n="indirect"){this.logger=e;let c;if(typeof I=="string"){if(c=JSON.parse(I),typeof c!="object")throw new Error("Invalid MCP configuration: must be an object");if(c===null||!("mcpServers"in c)||typeof c.mcpServers!="object")throw new Error("Invalid MCP configuration: missing or invalid mcpServers property");this.config=c}else this.config=I;this.disabledServers=new Set(l||[]),this.registry=new W7(this.logger,void 0,void 0,n),this.processor=new N7(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 I={};for(let[l,n]of Object.entries(this.config.mcpServers))this.disabledServers.has(l)?this.logger.log(`Skipping disabled MCP server: ${l}`):I[l]=n;e={...this.config,mcpServers:I}}else e=this.config;return this.processor.processServers(e)}async stopServers(){for(let[e,I]of Object.entries(this.registry.transports))try{await I.close()}catch(l){this.logger.error(`Error closing transport for ${e}: ${l}`)}this.startServersPromise=null,this.transport=null}async getTools(e,I,l){await this.startServers(),this.transport=this.transport??new Kx(e,I,!0);let n=[];for(let c of Object.keys(this.registry.clients)){let r=await this.transport.loadTools({mcpClient:this.registry.clients[c],clientName:c,tools:this.config.mcpServers[c]?.tools||["*"],filterMapping:this.config.mcpServers[c]?.filterMapping||"hidden_characters"},l);n.push(...r)}return n}getConfig(){return this.config}getClients(){return this.registry.clients}async startServer(e,I){await this.startServers(),this.config.mcpServers[e]=I,await this.processor.processServer(e,I),this.transport=null}async stopServer(e){let I=this.registry.transports[e];if(I)try{await I.close(),delete this.registry.transports[e]}catch(l){this.logger.error(`Error closing transport for ${e}: ${l}`)}this.registry.clients[e]&&delete this.registry.clients[e],this.transport=null}async restartServer(e,I){this.isServerRunning(e)&&await this.stopServer(e),delete this.config.mcpServers[e],await this.startServer(e,I)}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 I=this.getServerConfig(e);I?await this.startServer(e,I):await this.startBuiltInServer(e),this.transport=null}async startBuiltInServer(e){}getServerConfig(e){return this.config.mcpServers[e]}};o();var u_e=Ll(p_e(),1);async function _tt(t={}){let e=await vNe();return XNe((0,u_e.default)({},e,t))}async function Z_e(t={}){if(Wz())throw new Error("Settings have already been initialized");return _tt(t)}o();async function _V(t,e,I){if(!t||t.length===0)return;let l=!1,n={};for(let c of t)try{let r=await c(e);r&&(l=!0,n={...n,...r})}catch(r){I.error(`Hook execution failed: ${r}`)}return l?n:void 0}o();o();import{promises as $tt}from"fs";import W_e from"path";var elt=3*1024*1024;function N_e(t){let e=W_e.extname(t).toLowerCase();return[".png",".jpg",".jpeg",".gif",".webp"].includes(e)}function Ilt(t){switch(W_e.extname(t).toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";default:return null}}async function tlt(t,e){e.debug(`Processing local image file: ${t}`);let I=await $tt.readFile(t),l=Ilt(t);if(!l)throw new Error(`Unsupported image format: ${t}`);let n=new Dx,c=await Dq(e,n,elt,Mx,l,I);if(!c)throw new Error(`Image too large or couldn't be processed: ${t}`);let r=c.toString("base64");return`data:${l};base64,${r}`}async function llt(t,e){let I=es();try{let l=await Hce({command:"view",path:t,view_range:void 0},{properties:{command:"view",resolvedPathAgainstCwd:"false",options:"{}",inputs:"[]"},metrics:{responseTokenLimit:void 0,resultLength:0,resultForLlmLength:0},restrictedProperties:{}},e);return{id:I,name:"view",arguments:{path:t},result:l.textResultForLlm||""}}catch(l){return{id:I,name:"view",arguments:{path:t},result:`Error reading ${t}: ${l}`}}}async function Y_e(t,e){let I=[],l=t.filter(c=>!N_e(c.path));if(l.length===0)return I;let n=[];for(let c of l)try{let r=await llt(c.path,e);n.push(r)}catch{}if(n.length>0){let c=n.map(r=>({id:r.id,type:"function",function:{name:r.name,arguments:JSON.stringify(r.arguments)}}));I.push({role:"assistant",content:"I need to read the content of those paths to answer this request.",tool_calls:c}),I.push(...n.map(r=>({role:"tool",tool_call_id:r.id,content:r.result})))}return I}async function V_e(t,e){let I=t.filter(n=>N_e(n.path));return(await Promise.all(I.map(async n=>{try{return{type:"image_url",image_url:{url:await tlt(n.path,e)}}}catch(c){e.error(`Failed to process image ${n.path}: ${c instanceof Error?c.message:String(c)}`);return}}))).filter(n=>n!==void 0)}var gp=class{sessionId;startTime;modifiedTime;events=[];_chatMessages=[];_selectedModel;logger;eventCallbacks=[];eventProcessingQueue=Promise.resolve();constructor({sessionId:e,startTime:I,modifiedTime:l,logger:n}={}){this.sessionId=e||es(),this.startTime=I||new Date,this.modifiedTime=l||this.startTime,this.logger=n||new Ri}get messageCount(){let e=this.events.find(l=>l.type==="session.import_legacy"),I=0;return e&&(I=(e.data.legacySession?.chatMessages||[]).filter(c=>c.role==="user"||c.role==="assistant").length),this.logger.debug(`Imported message count: ${I}`),this.events.filter(l=>l.type==="user.message"||l.type==="assistant.message").length+I}get summary(){let e=this.events.find(c=>c.type==="session.import_legacy"||c.type==="user.message"),I;if(e?.type==="session.import_legacy"){let c=e.data.legacySession.chatMessages.find(r=>r.role==="user");c?.content&&(typeof c.content=="string"?I=c.content:I=c.content.find(r=>r.type==="text")?.text)}else e?.type==="user.message"&&(I=e.data.content);if(!I)return;let l=I.lastIndexOf("<reminder>");l!==-1&&(I=I.substring(0,l).trim());let n=I.replace(/\s+/g," ").trim();return n.length>75&&(n=n.substring(0,55).trim()+"..."),n=n.split("").filter(c=>{let r=c.charCodeAt(0);return r>=32&&r!==127}).join(""),n}static async fromEvents({events:e,logger:I}){if(e.length===0)throw new Error("Cannot create session from empty events array");let l=e[0];if(l.type!=="session.start")throw new Error("First event must be session.start");let n=new this({sessionId:l.data.sessionId,startTime:new Date(l.data.startTime),logger:I||new Ri});n._selectedModel=l.data.selectedModel,n.events.push(l);for(let c=1;c<e.length;c++){let r=e[c];n.events.push(r),await n.processEventForState(r)}return n}addEvent(e){let I=e.id||es(),l=e.timestamp||new Date().toISOString(),n=e.parentId!==void 0?e.parentId:this.getLastEventId(),c={...e,id:I,timestamp:l,parentId:n};return this.events.push(c),this.enqueueEventProcessing(()=>this.processEventForState(c).catch(r=>{this.logger.error(`Error processing event ${c.type} (${c.id}): ${r instanceof Error?r.message:String(r)}`)})).catch(r=>{this.logger.error(`Error processing event queue ${r instanceof Error?r.message:String(r)}`)}),this.notifyEventCallbacks(c),c}getEvents(){return this.events}onEvent(e){return this.eventCallbacks.push(e),()=>{let I=this.eventCallbacks.indexOf(e);I>-1&&this.eventCallbacks.splice(I,1)}}async getChatMessages(){return this.enqueueEventProcessing(()=>this._chatMessages)}async getChatContextMessages(){return(await this.getChatMessages()).filter(I=>I.role!=="system")}async getSystemContextMessages(){return(await this.getChatMessages()).filter(I=>I.role==="system")}async getSelectedModel(){return this.enqueueEventProcessing(()=>this._selectedModel)}setSelectedModel(e){let I=this._selectedModel;this._selectedModel=e,this.addEvent({type:"session.model_change",data:{previousModel:I,newModel:e}})}getLastEventId(){return this.events.length===0?null:this.events[this.events.length-1].id}enqueueEventProcessing(e){let I=this.eventProcessingQueue.then(()=>e());return this.eventProcessingQueue=I,I}async processEventForState(e){switch(e.type){case"session.start":e.data.selectedModel&&(this._selectedModel=e.data.selectedModel);break;case"session.model_change":this._selectedModel=e.data.newModel;break;case"user.message":{let I=[],l=[];if(e.data.attachments&&e.data.attachments.length>0){let n=await V_e(e.data.attachments,this.logger);I.push(...n);let c=await Y_e(e.data.attachments,this.logger);l.push(...c)}I.length>0?this._chatMessages.push({role:"user",content:[{type:"text",text:e.data.content},...I]}):this._chatMessages.push({role:"user",content:e.data.content}),l.length>0&&this._chatMessages.push(...l);break}case"assistant.message":{let I={role:"assistant",content:e.data.content||null};e.data.toolRequests&&e.data.toolRequests.length>0&&(I.tool_calls=e.data.toolRequests.map(l=>({id:l.toolCallId,type:"function",function:{name:l.name,arguments:typeof l.arguments=="string"?l.arguments:JSON.stringify(l.arguments)}}))),this._chatMessages.push(I);break}case"tool.execution_complete":{e.data.isUserRequested||this._chatMessages.push({role:"tool",tool_call_id:e.data.toolCallId,content:e.data.success?e.data.result?.content||"":e.data.error?.message||"Tool execution failed"});break}case"system.message":this._chatMessages.push({role:e.data.role,content:e.data.content,...e.data.name&&{name:e.data.name}});break;case"session.import_legacy":this._chatMessages=[...e.data.legacySession.chatMessages],e.data.legacySession.selectedModel&&(this._selectedModel=e.data.legacySession.selectedModel);break;case"abort":case"session.resume":this._chatMessages=nlt(this._chatMessages,this.logger);break;case"session.error":case"session.info":case"assistant.turn_start":case"assistant.turn_end":case"assistant.usage":case"tool.user_requested":case"tool.execution_start":case"tool.execution_partial_result":case"hook.start":case"hook.end":break;default:{let I=e;this.logger.error(`Unknown event type: ${I.type}`);break}}}notifyEventCallbacks(e){for(let I of this.eventCallbacks)try{I(e)}catch(l){this.logger.error(`Error in event callback: ${l instanceof Error?l.message:String(l)}`)}}};function nlt(t,e){if(t.length===0)return t;let I=[],l=new Set,n=!1;for(let s=t.length-1;s>=0;s--){let a=t[s];if(a.role==="assistant"&&(n=!0),a.role==="assistant"&&"tool_calls"in a&&a.tool_calls&&a.tool_calls.length>0)for(let G of a.tool_calls)l.has(G.id)||I.push(G.id);else{if(n)break;a.role==="tool"&&a.tool_call_id&&l.add(a.tool_call_id)}}if(I.length===0)return t;let c="The execution of this tool, or a previous tool was interrupted.";e.info(`Completing ${I.length} orphaned tool calls.`);let r=I.map(s=>({role:"tool",tool_call_id:s,content:c}));return[...t,...r]}var X7=class{static name="Copilot";static description="Base Copilot Agent";options;logger;workingDir;session;constructor(e){this.options=e,this.logger=e.logger||new Ri,this.workingDir=e.workingDirectory||process.cwd(),this.session=e.session||new gp,_pe(this.workingDir).then(I=>{if(I.found)return MDe(I.gitRoot,!0,this.workingDir)}).catch(I=>{this.logger.debug(`Failed to initialize custom instructions cache: ${I}`)})}async*query(e,I=[]){let l=new Map,n=new Map,c;try{if(this.options.mcpServers&&Object.keys(this.options.mcpServers).length>0)try{c=new Y7(this.logger,{mcpServers:this.options.mcpServers},this.options.disabledTools),await c.startServers()}catch(He){this.logger.error(`Failed to initialize MCP host: ${He}`)}let s=(await _V(this.options.hooks?.userPromptSubmitted,{timestamp:Date.now(),cwd:this.workingDir,prompt:e},this.logger))?.modifiedPrompt??e;this.session.addEvent({type:"user.message",data:{content:fpe({problemStatement:s,capabilities:{}}),attachments:I}});let G=new bF().setProblemStatement(s).setAgentModel(this.buildAgentModelString()).setGithubRepoName("copilot-sdk-session").setGithubRepoCommit("copilot-sdk-commit").setGithubRepoReadWrite(!1).setCopilotIntegrationId(this.options.integrationId||"copilot-developer-cli").setCopilotHmacKey(this.options.hmacKey).setCopilotToken(this.options.copilotToken).build();ENe();let d=await Z_e(G),i=d.service?.agent?.model,b=_q(i),m=b.agent,h=b.model?{model:b.model}:void 0,p=Hie(d,this.logger,m,h),Z={location:this.workingDir,timeout:3e4,requireReasoning:!0,toolPartialResultCallback:(He,Re)=>{this.session.addEvent({type:"tool.execution_partial_result",ephemeral:!0,data:{toolCallId:He,partialOutput:Re}})},permissions:this.options.requestPermission?{requestRequired:!0,request:this.options.requestPermission}:{requestRequired:!1},shellConfig:(process.platform==="win32"?_i.powerShell:_i.bash).withScriptSafetyAssessor(async function(He){return{result:"completed",commands:[{identifier:He,readOnly:!1}],possiblePaths:[],hasWriteFileRedirection:!1,canOfferSessionApproval:!1}})},W=await QPe(Z,this.logger),Y=[];if(c)try{Y=await c.getTools(d,this.logger,Z.permissions)}catch(He){this.logger.error(`Failed to get MCP tools: ${He}`)}let F=[...W,...Y].filter(He=>this.options.allowedTools?this.options.allowedTools.includes(He.name):this.options.disabledTools?!this.options.disabledTools.includes(He.name):!0),g=await _pe(this.workingDir),w={...(XPe()["sweagent-capi"]?.["claude-sonnet-4"]??wPe()).supports,reasoning:!0},H=await bPe(g.found?g.gitRoot:"",ZBe(),this.workingDir,{},w,Z,F,void 0);this.session.addEvent({type:"system.message",data:{content:H,role:"system"}});let $=(await this.session.getChatMessages()).slice(0,-1),ge={role:"user",content:fpe({customAgentPrompt:void 0,problemStatement:s,capabilities:w})},ye=[...$,ge];await _V(this.options.hooks?.sessionStart,{timestamp:Date.now(),cwd:this.workingDir,source:"new",initialPrompt:e},this.logger);let ve=new Wg(ge,this.logger),Qe=p.getCompletionWithTools(H,ye,F,{failIfInitialInputsTooLong:!1,processors:{preRequest:[ve,new Wg(void 0,this.logger)],onRequestError:[ve]},executeToolsInParallel:!1,abortSignal:this.options.abortController?.signal}),Ne=es();yield this.session.addEvent({type:"assistant.turn_start",data:{turnId:Ne}});for await(let He of Qe){if(this.options.abortController?.signal.aborted){yield this.session.addEvent({type:"abort",data:{reason:"user initiated"}});break}switch(He.kind){case"message":{if($q(He)){let Re=VPe(He)?await Promise.all(He.message.tool_calls.map(async Fe=>{let At=xw(Fe.function.arguments);l.set(Fe.id,Fe.function.name),n.set(Fe.id,At);let wI=await _V(this.options.hooks?.preToolUse,{timestamp:Date.now(),cwd:this.workingDir,toolName:Fe.function.name,toolArgs:At},this.logger);return{toolCallId:Fe.id,name:Fe.function.name,arguments:wI?.modifiedArgs??At}})):[];yield this.session.addEvent({type:"assistant.message",data:{messageId:es(),content:typeof He.message.content=="string"?He.message.content:"",toolRequests:Re}});for(let Fe of Re)yield this.session.addEvent({type:"tool.execution_start",data:{toolCallId:Fe.toolCallId,toolName:Fe.name,arguments:Fe.arguments}})}else(He.message.role==="system"||He.message.role==="developer")&&(yield this.session.addEvent({type:"system.message",data:{role:He.message.role,content:typeof He.message.content=="string"?He.message.content:JSON.stringify(He.message.content),name:"name"in He.message?He.message.name:void 0}}));break}case"model_call_failure":{let Re=new Error(He.modelCall?.error||"Model call failed");await _V(this.options.hooks?.errorOccurred,{timestamp:Date.now(),cwd:this.workingDir,error:Re,errorContext:"model_call",recoverable:!0},this.logger),yield this.session.addEvent({type:"session.error",data:{errorType:"model_call",message:Re.message,stack:Re.stack}});break}case"tool_execution":{let Fe=(await _V(this.options.hooks?.postToolUse,{timestamp:Date.now(),cwd:this.workingDir,toolName:l.get(He.toolCallId)||"unknown",toolArgs:n.get(He.toolCallId)||{},toolResult:He.toolResult},this.logger))?.modifiedResult??He.toolResult,At=(Fe.resultType==="failure"?Fe.error:void 0)||Fe.sessionLog||Fe.textResultForLlm;yield this.session.addEvent({type:"tool.execution_complete",data:{toolCallId:He.toolCallId,success:Fe.resultType==="success",result:Fe.resultType==="success"?{content:At}:void 0,error:Fe.resultType!=="success"?{message:At,code:Fe.resultType}:void 0}});break}case"response":case"images_removed":case"image_processing":case"history_truncated":case"turn_started":case"turn_ended":case"turn_failed":case"turn_retry":case"model_call_success":this.logger.debug(`Ignoring event of kind: ${He.kind}`);break;default:Xp(He,"Unhandled event type")}}yield this.session.addEvent({type:"assistant.turn_end",data:{turnId:Ne}})}catch(r){await _V(this.options.hooks?.sessionEnd,{timestamp:Date.now(),cwd:this.workingDir,reason:"error",error:r instanceof Error?r:new Error(String(r))},this.logger),yield this.session.addEvent({type:"session.error",data:{errorType:"query",message:r instanceof Error?r.message:String(r),stack:r instanceof Error?r.stack:void 0}})}finally{if(await _V(this.options.hooks?.sessionEnd,{timestamp:Date.now(),cwd:this.workingDir,reason:"complete"},this.logger),c)try{await c.stopServers(),this.logger.log("MCP host stopped successfully")}catch(r){this.logger.error(`Error stopping MCP host: ${r}`)}}}buildAgentModelString(){switch(this.options.modelProvider.type){case"openai":return`openai:${this.options.modelProvider.model}`;case"anthropic":return`anthropic:${this.options.modelProvider.model}`;case"copilot":return`capi:${this.options.modelProvider.model}`;default:throw new Error(`Unsupported provider: ${this.options.modelProvider.type}`)}}applyToolFiltering(e,I,l){let n=e;return I&&I.length>0&&(n=n.filter(c=>I.includes(c.name))),l&&l.length>0&&(n=n.filter(c=>!l.includes(c.name))),n}};var Y$e={};Jc(Y$e,{CLISessionManager:()=>tNe});o();o();import{unlink as N$e}from"fs/promises";import{join as drt}from"path";o();var E7=class{sessions;logger;lastAccessedSessionId;constructor({logger:e}={}){this.sessions=new Map,this.logger=e||new Ri}async createSession(){let e=new gp({logger:this.logger});return this.sessions.set(e.sessionId,e),this.lastAccessedSessionId=e.sessionId,e}async getSession(e){let I=this.sessions.get(e);return I&&(this.lastAccessedSessionId=e),I}async getLastSession(){if(this.lastAccessedSessionId){let l=this.sessions.get(this.lastAccessedSessionId);if(l)return l}let e=Array.from(this.sessions.values());if(e.length===0)return;e.sort((l,n)=>n.startTime.getTime()-l.startTime.getTime());let I=e[0];return this.lastAccessedSessionId=I.sessionId,I}async listSessions(){return Array.from(this.sessions.values()).map(e=>({sessionId:e.sessionId,startTime:e.startTime,modifiedTime:e.modifiedTime}))}async saveSession(e){}async deleteSession(e){this.sessions.delete(e.sessionId),this.lastAccessedSessionId===e.sessionId&&(this.lastAccessedSessionId=void 0)}};o();o();o();var h$e=Ll(t$e(),1);o();import{existsSync as P7}from"fs";import{appendFile as qnt,mkdir as _nt,readdir as q7,readFile as s$e,stat as _7,writeFile as $nt}from"fs/promises";import{homedir as a$e}from"os";import{dirname as ect,join as uG}from"path";o();o();var Tnt=new Error("timeout while waiting for mutex to become available"),Ymn=new Error("mutex already locked"),jnt=new Error("request for lock canceled"),Dnt=function(t,e,I,l){function n(c){return c instanceof I?c:new I(function(r){r(c)})}return new(I||(I=Promise))(function(c,r){function s(d){try{G(l.next(d))}catch(i){r(i)}}function a(d){try{G(l.throw(d))}catch(i){r(i)}}function G(d){d.done?c(d.value):n(d.value).then(s,a)}G((l=l.apply(t,e||[])).next())})},$We=class{constructor(e,I=jnt){this._value=e,this._cancelError=I,this._queue=[],this._weightedWaiters=[]}acquire(e=1,I=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((l,n)=>{let c={resolve:l,reject:n,weight:e,priority:I},r=n$e(this._queue,s=>I<=s.priority);r===-1&&e<=this._value?this._dispatchItem(c):this._queue.splice(r+1,0,c)})}runExclusive(e){return Dnt(this,arguments,void 0,function*(I,l=1,n=0){let[c,r]=yield this.acquire(l,n);try{return yield I(c)}finally{r()}})}waitForUnlock(e=1,I=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,I)?Promise.resolve():new Promise(l=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),Knt(this._weightedWaiters[e-1],{resolve:l,priority:I})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){let I=this._value;this._value-=e.weight,e.resolve([I,this._newReleaser(e.weight)])}_newReleaser(e){let I=!1;return()=>{I||(I=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){let I=this._weightedWaiters[e-1];I&&(I.forEach(l=>l.resolve()),this._weightedWaiters[e-1]=[])}else{let e=this._queue[0].priority;for(let I=this._value;I>0;I--){let l=this._weightedWaiters[I-1];if(!l)continue;let n=l.findIndex(c=>c.priority<=e);(n===-1?l:l.splice(0,n)).forEach(c=>c.resolve())}}}_couldLockImmediately(e,I){return(this._queue.length===0||this._queue[0].priority<I)&&e<=this._value}};function Knt(t,e){let I=n$e(t,l=>e.priority<=l.priority);t.splice(I+1,0,e)}function n$e(t,e){for(let I=t.length-1;I>=0;I--)if(e(t[I]))return I;return-1}var Pnt=function(t,e,I,l){function n(c){return c instanceof I?c:new I(function(r){r(c)})}return new(I||(I=Promise))(function(c,r){function s(d){try{G(l.next(d))}catch(i){r(i)}}function a(d){try{G(l.throw(d))}catch(i){r(i)}}function G(d){d.done?c(d.value):n(d.value).then(s,a)}G((l=l.apply(t,e||[])).next())})},D7=class{constructor(e){this._semaphore=new $We(1,e)}acquire(){return Pnt(this,arguments,void 0,function*(e=0){let[,I]=yield this._semaphore.acquire(1,e);return I})}runExclusive(e,I=0){return this._semaphore.runExclusive(()=>e(),1,I)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}},l$e=function(t,e,I,l){function n(c){return c instanceof I?c:new I(function(r){r(c)})}return new(I||(I=Promise))(function(c,r){function s(d){try{G(l.next(d))}catch(i){r(i)}}function a(d){try{G(l.throw(d))}catch(i){r(i)}}function G(d){d.done?c(d.value):n(d.value).then(s,a)}G((l=l.apply(t,e||[])).next())})};function c$e(t,e,I=Tnt){return{acquire:(l,n)=>{let c;if(j7(t)?c=l:(c=void 0,n=l),c!==void 0&&c<=0)throw new Error(`invalid weight ${c}: must be positive`);return new Promise((r,s)=>l$e(this,void 0,void 0,function*(){let a=!1,G=setTimeout(()=>{a=!0,s(I)},e);try{let d=yield j7(t)?t.acquire(c,n):t.acquire(n);a?(Array.isArray(d)?d[1]:d)():(clearTimeout(G),r(d))}catch(d){a||(clearTimeout(G),s(d))}}))},runExclusive(l,n,c){return l$e(this,void 0,void 0,function*(){let r=()=>{};try{let s=yield this.acquire(n,c);return Array.isArray(s)?(r=s[1],yield l(s[0])):(r=s,yield l())}finally{r()}})},release(l){t.release(l)},cancel(){return t.cancel()},waitForUnlock:(l,n)=>{let c;if(j7(t)?c=l:(c=void 0,n=l),c!==void 0&&c<=0)throw new Error(`invalid weight ${c}: must be positive`);return new Promise((r,s)=>{let a=setTimeout(()=>s(I),e);(j7(t)?t.waitForUnlock(c,n):t.waitForUnlock(n)).then(()=>{clearTimeout(a),r()})})},isLocked:()=>t.isLocked(),getValue:()=>t.getValue(),setValue:l=>t.setValue(l)}}function j7(t){return t.getValue!==void 0}var K7=class{mutexes=new Map;async runExclusive(e,I,l=5e3){let n=this.mutexes.get(e);n||(n=new D7,n.refCount=0,this.mutexes.set(e,n));let c=n;try{return c.refCount++,await c$e(n,l).runExclusive(I)}finally{--c.refCount===0&&this.mutexes.delete(e)}}};var eNe=(I=>(I.DEFAULT="config",I.MCP="mcp",I))(eNe||{});function r$e(t){return Object.values(eNe).includes(t)}var $7=".copilot",e_=new K7;async function o$e(t){let e=ect(t);try{await _nt(e,{recursive:!0,mode:448})}catch{}}async function Ict(t,e){if(P7(t))try{let I={},l=await e_.runExclusive(t,()=>s$e(t,"utf8"));return l.trim().startsWith("{")?I=JSON.parse(l):l.split(`
1413
+ ${c}`;await n.logMCPSetup(e,s),this.logger.log(`Updated session log for ${e} with ${I.length} tools`)}catch(c){this.logger.error(`Failed to update session log for ${e}: ${c}`)}}};o();var QWe={mcpServers:{}},N7=class{constructor(e,I,l){this.logger=e;this.registry=I;this.remoteEnabled=l?.remoteEnabled??!1,this.mcp3pEnabled=l?.mcp3pEnabled??!1,this.blackbirdMetisIndexEnabled=l?.blackbirdMetisIndexEnabled??!1,this.sessionClient=l?.sessionClient,this.mcpEnvConfig=void 0,this.envValueMode=l?.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 I=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(I,e),this.configureGitHubMcp(I,e),this.configurePlaywrightMcp(I)),I}validateEnvConfig(){if(!this.mcp3pEnabled)return this.logger.log("User-provided MCPs are disabled"),QWe;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"),QWe;try{let e=JSON.parse(this.mcpEnvConfig);if(!e.mcpServers)throw new Error("User-provided config had incorrect format. Missing 'mcpServers' property.");for(let I in e.mcpServers)e.mcpServers[I].isDefaultServer=!1;return e}catch(e){return this.logger.error(`Warning: User-provided MCP servers were defined but invalid: ${e}`),QWe}}configureGitHubMcp(e,I){this.remoteEnabled?this.configureRemoteGitHubMcp(e,I):this.configureLocalGitHubMcp(e)}configureRemoteGitHubMcp(e,I){this.logger.log("Using default remote GitHub MCP server configuration");let l="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"),l=l+",copilot_spaces");let n={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":l,"X-MCP-Host":"github-coding-agent","X-Initiator":"agent"};I&&I.api?.copilot?.integrationId&&(n["Copilot-Integration-Id"]=I.api.copilot.integrationId),process.env.GITHUB_COPILOT_INTERACTION_ID&&(n["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let c={type:"http",url:this.getCapiMcpUrl(),headers:n,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[lv]=c}configureLocalGitHubMcp(e){if(e.mcpServers[lv]){this.logger.log("Using user-provided GitHub MCP server configuration");let I=e.mcpServers[lv]??{};nv(I)&&!I.command&&(e.mcpServers[lv]={...I,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 I={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[lv]=I}}configurePlaywrightMcp(e){if(!e.mcpServers[FWe]){if((process.env.COPILOT_FEATURE_FLAGS??"").split(",").map(l=>l.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 I={command:"npx",args:[...Bpe,"--allowed-origins","localhost;localhost:*;127.0.0.1;127.0.0.1:*"],tools:["*"],isDefaultServer:!0};e.mcpServers[FWe]=I}}configureBlackbirdMcp(e,I){this.remoteEnabled?this.configureRemoteBlackbirdMcp(e):this.blackbirdMetisIndexEnabled?this.configureLocalMetisBlackbirdMCP(e,I):this.configureLocalBlackbirdMcp(e)}configureLocalMetisBlackbirdMCP(e,I){this.logger.log("Using local Metis Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${I.blackbird?.mode}`);let l=process.env.AGENT_DIR||"/agent";this.logger.log(`Using agent directory: ${l}`);let n=[];I.blackbird?.mode==="tool"&&(n=["*"]),this.logger.log(`Using blackbird Metis server: ${I.blackbird?.mode}`);let c={command:`${l}/blackbird/mcp`,args:["serve","--index",`${l}/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:n,isDefaultServer:!0};e.mcpServers[_g]=c}configureLocalBlackbirdMcp(e){this.logger.log("Using local Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let I=[];process.env.BLACKBIRD_MODE==="tool"&&(I=["*"]);let l={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:I,isDefaultServer:!0};e.mcpServers[_g]=l}configureRemoteBlackbirdMcp(e){this.logger.log("Using remote Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let I=[];process.env.BLACKBIRD_MODE==="tool"&&(I=["*"]);let l={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&&(l["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let n={type:"http",url:this.getCapiMcpUrl(),headers:l,tools:I,isDefaultServer:!0};e.mcpServers[_g]=n}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 nv(e)||u7(e)||Z7(e)||_B(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,I){return this.remoteEnabled&&!this.isValidServerType(I)?(this.logger.error(`Unsupported server type "${I.type}" for server "${e}". Only "Local", "STDIO", "HTTP", "SSE", or "Memory" are supported.`),!1):!this.remoteEnabled&&!nv(I)&&!_B(I)?(this.logger.error(`Unsupported server type "${I.type}" for server "${e}". Only "Local", "STDIO", or "Memory" are supported.`),!1):I.tools?nv(I)&&!this.isValidLocalServerConfig(I)?(this.logger.error(`Invalid local server configuration for "${e}". Please ensure 'command' and 'args' are provided.`),!1):(u7(I)||Z7(I))&&!this.isValidRemoteServerConfig(I)?(this.logger.error(`Invalid remote server configuration for "${e}". Please ensure 'url' is provided.`),!1):_B(I)&&!this.isValidInMemoryServerConfig(I)?(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,I){try{let l=this.resolveHeaders(I.headers,process.env),n={...I,headers:l};await this.registry.startHttpMcpClient(e,n),this.logger.log(`Started MCP client for remote server ${e}`)}catch(l){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${l}`),l}}async processSseServer(e,I){try{let l=this.resolveRemoteServerConfig(I);await this.registry.startSseMcpClient(e,l),this.logger.log(`Started MCP client for remote server ${e}`)}catch(l){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${l}`),l}}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,I){try{await this.registry.startInMemoryMcpClient(e,I.serverInstance),this.logger.log(`Started in-memory MCP client for ${e}`)}catch(l){throw this.logger.error(`Failed to start in-memory MCP client for ${e}: ${l}`),l}}async processLocalServer(e,I){let l={...I};if(I.command==="python")try{l=await this.convertPythonToPipx(l)}catch(r){this.logger.error(`Failed to handle Python module for ${e}: ${r}`)}let n=this.buildEnvironment(l),c=this.resolveLocalServerConfig(l,n);this.logger.log(`Starting MCP client for ${e} with command: ${c.command} and args: ${c.args}`),c.cwd&&this.logger.log(`cwd: ${c.cwd}`);try{await this.registry.startLocalMcpClient(e,n,c.command,c.args,c.cwd),this.logger.log(`Started MCP client for ${e}`)}catch(r){throw this.logger.error(`Failed to start MCP client for ${e}: ${r}`),r}}convertPythonToPipx(e){if(!e||!e.args||e.args.length===0)return e;let I=e.args,l=I.indexOf("-m");if(l===-1||l===I.length-1)throw new Error("Python command with -m flag must specify a module");let n=I[l+1];this.logger.log(`Converting Python module: ${n} to pipx command`);let c=["run",n];for(let r=l+2;r<I.length;r++)c.push(I[r]);for(let r=0;r<l;r++)c.push(I[r]);return{...e,command:"pipx",args:c}}buildEnvironment(e){let I={};if(e.env)if(this.envValueMode==="direct")for(let[l,n]of Object.entries(e.env))I[l]=this.resolveString(n,process.env);else for(let[l,n]of Object.entries(e.env)){let c=n.trim(),r=c;if(c.includes("$")&&(r=this.resolveString(c,process.env)),r!==c){I[l]=r;continue}process.env[c]!==void 0&&(I[l]=process.env[c])}return I}resolveLocalServerConfig(e,I){let l=this.resolveString(e.command,I),n=this.resolveArray(e.args,I),c;return e.cwd&&(c=this.resolveString(e.cwd,I)),{...e,command:l,args:n,cwd:c}}resolveString(e,I){return I?e.replace(/\$(?:\{([A-Z0-9_]+)(?::-(.*?))?\}|([A-Z0-9_]+))/g,(l,n,c,r)=>{let a=I[n||r];return a!==void 0?a:c!==void 0?c:l}):e}resolveArray(e,I){return e?I?e.map(l=>this.resolveString(l,I)):e:[]}resolveHeaders(e,I){if(!e)return{};if(!I)return e;let l={};for(let[n,c]of Object.entries(e)){let r=this.resolveArray([c],I);l[n]=r[0]}return l}async processServers(e){if(!e)throw new Error("No servers to process");let I=Object.entries(e.mcpServers).map(([l,n])=>this.processServer(l,n));await Promise.all(I)}async processServer(e,I){if(!this.validateServerConfig(e,I)){this.logger.error(`Skipping server "${e}" due to invalid configuration.`);return}try{nv(I)?await this.processLocalServer(e,I):u7(I)&&this.remoteEnabled?await this.processHttpServer(e,I):Z7(I)&&this.remoteEnabled?await this.processSseServer(e,I):_B(I)&&await this.processInMemoryServer(e,I)}catch(l){e!==_g&&await this.logServerFailure(e,l)}}async logServerFailure(e,I){if(this.sessionClient)try{await this.sessionClient.logMCPSetup(e,`<error>MCP server failed to start: ${I.message} - for the full output, see the verbose logs</error>`)}catch(l){this.logger.error(`Failed to log failure for MCP Server '${e}': '${l}'`)}}};var Y7=class{constructor(e,I,l,n="indirect"){this.logger=e;let c;if(typeof I=="string"){if(c=JSON.parse(I),typeof c!="object")throw new Error("Invalid MCP configuration: must be an object");if(c===null||!("mcpServers"in c)||typeof c.mcpServers!="object")throw new Error("Invalid MCP configuration: missing or invalid mcpServers property");this.config=c}else this.config=I;this.disabledServers=new Set(l||[]),this.registry=new W7(this.logger,void 0,void 0,n),this.processor=new N7(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 I={};for(let[l,n]of Object.entries(this.config.mcpServers))this.disabledServers.has(l)?this.logger.log(`Skipping disabled MCP server: ${l}`):I[l]=n;e={...this.config,mcpServers:I}}else e=this.config;return this.processor.processServers(e)}async stopServers(){for(let[e,I]of Object.entries(this.registry.transports))try{await I.close()}catch(l){this.logger.error(`Error closing transport for ${e}: ${l}`)}this.startServersPromise=null,this.transport=null}async getTools(e,I,l){await this.startServers(),this.transport=this.transport??new Kx(e,I,!0);let n=[];for(let c of Object.keys(this.registry.clients)){let r=await this.transport.loadTools({mcpClient:this.registry.clients[c],clientName:c,tools:this.config.mcpServers[c]?.tools||["*"],filterMapping:this.config.mcpServers[c]?.filterMapping||"hidden_characters"},l);n.push(...r)}return n}getConfig(){return this.config}getClients(){return this.registry.clients}async startServer(e,I){await this.startServers(),this.config.mcpServers[e]=I,await this.processor.processServer(e,I),this.transport=null}async stopServer(e){let I=this.registry.transports[e];if(I)try{await I.close(),delete this.registry.transports[e]}catch(l){this.logger.error(`Error closing transport for ${e}: ${l}`)}this.registry.clients[e]&&delete this.registry.clients[e],this.transport=null}async restartServer(e,I){this.isServerRunning(e)&&await this.stopServer(e),delete this.config.mcpServers[e],await this.startServer(e,I)}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 I=this.getServerConfig(e);I?await this.startServer(e,I):await this.startBuiltInServer(e),this.transport=null}async startBuiltInServer(e){}getServerConfig(e){return this.config.mcpServers[e]}};o();var u_e=Ll(p_e(),1);async function _tt(t={}){let e=await vNe();return XNe((0,u_e.default)({},e,t))}async function Z_e(t={}){if(Wz())throw new Error("Settings have already been initialized");return _tt(t)}o();async function _V(t,e,I){if(!t||t.length===0)return;let l=!1,n={};for(let c of t)try{let r=await c(e);r&&(l=!0,n={...n,...r})}catch(r){I.error(`Hook execution failed: ${r}`)}return l?n:void 0}o();o();import{promises as $tt}from"fs";import W_e from"path";var elt=3*1024*1024;function N_e(t){let e=W_e.extname(t).toLowerCase();return[".png",".jpg",".jpeg",".gif",".webp"].includes(e)}function Ilt(t){switch(W_e.extname(t).toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";default:return null}}async function tlt(t,e){e.debug(`Processing local image file: ${t}`);let I=await $tt.readFile(t),l=Ilt(t);if(!l)throw new Error(`Unsupported image format: ${t}`);let n=new Dx,c=await Dq(e,n,elt,Mx,l,I);if(!c)throw new Error(`Image too large or couldn't be processed: ${t}`);let r=c.toString("base64");return`data:${l};base64,${r}`}async function llt(t,e){let I=es();try{let l=await Hce({command:"view",path:t,view_range:void 0},{properties:{command:"view",resolvedPathAgainstCwd:"false",options:"{}",inputs:"[]"},metrics:{responseTokenLimit:void 0,resultLength:0,resultForLlmLength:0},restrictedProperties:{}},e);return{id:I,name:"view",arguments:{path:t},result:l.textResultForLlm||""}}catch(l){return{id:I,name:"view",arguments:{path:t},result:`Error reading ${t}: ${l}`}}}async function Y_e(t,e){let I=[],l=t.filter(c=>!N_e(c.path));if(l.length===0)return I;let n=[];for(let c of l)try{let r=await llt(c.path,e);n.push(r)}catch{}if(n.length>0){let c=n.map(r=>({id:r.id,type:"function",function:{name:r.name,arguments:JSON.stringify(r.arguments)}}));I.push({role:"assistant",content:"I need to read the content of those paths to answer this request.",tool_calls:c}),I.push(...n.map(r=>({role:"tool",tool_call_id:r.id,content:r.result})))}return I}async function V_e(t,e){let I=t.filter(n=>N_e(n.path));return(await Promise.all(I.map(async n=>{try{return{type:"image_url",image_url:{url:await tlt(n.path,e)}}}catch(c){e.error(`Failed to process image ${n.path}: ${c instanceof Error?c.message:String(c)}`);return}}))).filter(n=>n!==void 0)}var gp=class{sessionId;startTime;modifiedTime;events=[];_chatMessages=[];_selectedModel;logger;eventCallbacks=[];eventProcessingQueue=Promise.resolve();constructor({sessionId:e,startTime:I,modifiedTime:l,logger:n}={}){this.sessionId=e||es(),this.startTime=I||new Date,this.modifiedTime=l||this.startTime,this.logger=n||new Ri}get messageCount(){let e=this.events.find(l=>l.type==="session.import_legacy"),I=0;return e&&(I=(e.data.legacySession?.chatMessages||[]).filter(c=>c.role==="user"||c.role==="assistant").length),this.logger.debug(`Imported message count: ${I}`),this.events.filter(l=>l.type==="user.message"||l.type==="assistant.message").length+I}get summary(){let e=this.events.find(c=>c.type==="session.import_legacy"||c.type==="user.message"),I;if(e?.type==="session.import_legacy"){let c=e.data.legacySession.chatMessages.find(r=>r.role==="user");c?.content&&(typeof c.content=="string"?I=c.content:I=c.content.find(r=>r.type==="text")?.text)}else e?.type==="user.message"&&(I=e.data.content);if(!I)return;let l=I.lastIndexOf("<reminder>");l!==-1&&(I=I.substring(0,l).trim());let n=I.replace(/\s+/g," ").trim();return n.length>75&&(n=n.substring(0,55).trim()+"..."),n=n.split("").filter(c=>{let r=c.charCodeAt(0);return r>=32&&r!==127}).join(""),n}static async fromEvents({events:e,logger:I}){if(e.length===0)throw new Error("Cannot create session from empty events array");let l=e[0];if(l.type!=="session.start")throw new Error("First event must be session.start");let n=new this({sessionId:l.data.sessionId,startTime:new Date(l.data.startTime),logger:I||new Ri});n._selectedModel=l.data.selectedModel,n.events.push(l);for(let c=1;c<e.length;c++){let r=e[c];n.events.push(r),await n.processEventForState(r)}return n}addEvent(e){let I=e.id||es(),l=e.timestamp||new Date().toISOString(),n=e.parentId!==void 0?e.parentId:this.getLastEventId(),c={...e,id:I,timestamp:l,parentId:n};return this.events.push(c),this.enqueueEventProcessing(()=>this.processEventForState(c).catch(r=>{this.logger.error(`Error processing event ${c.type} (${c.id}): ${r instanceof Error?r.message:String(r)}`)})).catch(r=>{this.logger.error(`Error processing event queue ${r instanceof Error?r.message:String(r)}`)}),this.notifyEventCallbacks(c),c}getEvents(){return this.events}onEvent(e){return this.eventCallbacks.push(e),()=>{let I=this.eventCallbacks.indexOf(e);I>-1&&this.eventCallbacks.splice(I,1)}}async getChatMessages(){return this.enqueueEventProcessing(()=>this._chatMessages)}async getChatContextMessages(){return(await this.getChatMessages()).filter(I=>I.role!=="system")}async getSystemContextMessages(){return(await this.getChatMessages()).filter(I=>I.role==="system")}async getSelectedModel(){return this.enqueueEventProcessing(()=>this._selectedModel)}setSelectedModel(e){let I=this._selectedModel;this._selectedModel=e,this.addEvent({type:"session.model_change",data:{previousModel:I,newModel:e}})}getLastEventId(){return this.events.length===0?null:this.events[this.events.length-1].id}enqueueEventProcessing(e){let I=this.eventProcessingQueue.then(()=>e());return this.eventProcessingQueue=I,I}async processEventForState(e){switch(e.type){case"session.start":e.data.selectedModel&&(this._selectedModel=e.data.selectedModel);break;case"session.model_change":this._selectedModel=e.data.newModel;break;case"user.message":{let I=[],l=[];if(e.data.attachments&&e.data.attachments.length>0){let n=await V_e(e.data.attachments,this.logger);I.push(...n);let c=await Y_e(e.data.attachments,this.logger);l.push(...c)}I.length>0?this._chatMessages.push({role:"user",content:[{type:"text",text:e.data.content},...I]}):this._chatMessages.push({role:"user",content:e.data.content}),l.length>0&&this._chatMessages.push(...l);break}case"assistant.message":{let I={role:"assistant",content:e.data.content||null};e.data.toolRequests&&e.data.toolRequests.length>0&&(I.tool_calls=e.data.toolRequests.map(l=>({id:l.toolCallId,type:"function",function:{name:l.name,arguments:typeof l.arguments=="string"?l.arguments:JSON.stringify(l.arguments)}}))),this._chatMessages.push(I);break}case"tool.execution_complete":{e.data.isUserRequested||this._chatMessages.push({role:"tool",tool_call_id:e.data.toolCallId,content:e.data.success?e.data.result?.content||"":e.data.error?.message||"Tool execution failed"});break}case"system.message":this._chatMessages.push({role:e.data.role,content:e.data.content,...e.data.name&&{name:e.data.name}});break;case"session.import_legacy":this._chatMessages=[...e.data.legacySession.chatMessages],e.data.legacySession.selectedModel&&(this._selectedModel=e.data.legacySession.selectedModel);break;case"abort":case"session.resume":this._chatMessages=nlt(this._chatMessages,this.logger);break;case"session.error":case"session.info":case"assistant.turn_start":case"assistant.turn_end":case"assistant.usage":case"tool.user_requested":case"tool.execution_start":case"tool.execution_partial_result":case"hook.start":case"hook.end":break;default:{let I=e;this.logger.error(`Unknown event type: ${I.type}`);break}}}notifyEventCallbacks(e){for(let I of this.eventCallbacks)try{I(e)}catch(l){this.logger.error(`Error in event callback: ${l instanceof Error?l.message:String(l)}`)}}};function nlt(t,e){if(t.length===0)return t;let I=[],l=new Set,n=!1;for(let s=t.length-1;s>=0;s--){let a=t[s];if(a.role==="assistant"&&(n=!0),a.role==="assistant"&&"tool_calls"in a&&a.tool_calls&&a.tool_calls.length>0)for(let G of a.tool_calls)l.has(G.id)||I.push(G.id);else{if(n)break;a.role==="tool"&&a.tool_call_id&&l.add(a.tool_call_id)}}if(I.length===0)return t;let c="The execution of this tool, or a previous tool was interrupted.";e.info(`Completing ${I.length} orphaned tool calls.`);let r=I.map(s=>({role:"tool",tool_call_id:s,content:c}));return[...t,...r]}var X7=class{static name="Copilot";static description="Base Copilot Agent";options;logger;workingDir;session;constructor(e){this.options=e,this.logger=e.logger||new Ri,this.workingDir=e.workingDirectory||process.cwd(),this.session=e.session||new gp,_pe(this.workingDir).then(I=>{if(I.found)return MDe(I.gitRoot,!0,this.workingDir)}).catch(I=>{this.logger.debug(`Failed to initialize custom instructions cache: ${I}`)})}async*query(e,I=[]){let l=new Map,n=new Map,c;try{if(this.options.mcpServers&&Object.keys(this.options.mcpServers).length>0)try{c=new Y7(this.logger,{mcpServers:this.options.mcpServers},this.options.disabledTools),await c.startServers()}catch(He){this.logger.error(`Failed to initialize MCP host: ${He}`)}let s=(await _V(this.options.hooks?.userPromptSubmitted,{timestamp:Date.now(),cwd:this.workingDir,prompt:e},this.logger))?.modifiedPrompt??e;this.session.addEvent({type:"user.message",data:{content:fpe({problemStatement:s,capabilities:{}}),attachments:I}});let G=new bF().setProblemStatement(s).setAgentModel(this.buildAgentModelString()).setGithubRepoName("copilot-sdk-session").setGithubRepoCommit("copilot-sdk-commit").setGithubRepoReadWrite(!1).setCopilotIntegrationId(this.options.integrationId||"copilot-developer-cli").setCopilotHmacKey(this.options.hmacKey).setCopilotToken(this.options.copilotToken).build();ENe();let d=await Z_e(G),i=d.service?.agent?.model,b=_q(i),m=b.agent,h=b.model?{model:b.model}:void 0,p=Hie(d,this.logger,m,h),Z={location:this.workingDir,timeout:3e4,requireReasoning:!0,toolPartialResultCallback:(He,Re)=>{this.session.addEvent({type:"tool.execution_partial_result",ephemeral:!0,data:{toolCallId:He,partialOutput:Re}})},permissions:this.options.requestPermission?{requestRequired:!0,request:this.options.requestPermission}:{requestRequired:!1},shellConfig:(process.platform==="win32"?_i.powerShell:_i.bash).withScriptSafetyAssessor(async function(He){return{result:"completed",commands:[{identifier:He,readOnly:!1}],possiblePaths:[],hasWriteFileRedirection:!1,canOfferSessionApproval:!1}})},W=await QPe(Z,this.logger),Y=[];if(c)try{Y=await c.getTools(d,this.logger,Z.permissions)}catch(He){this.logger.error(`Failed to get MCP tools: ${He}`)}let F=[...W,...Y].filter(He=>this.options.allowedTools?this.options.allowedTools.includes(He.name):this.options.disabledTools?!this.options.disabledTools.includes(He.name):!0),g=await _pe(this.workingDir),w={...(XPe()["sweagent-capi"]?.["claude-sonnet-4"]??wPe()).supports,reasoning:!0},H=await bPe(g.found?g.gitRoot:"",ZBe(),this.workingDir,{},w,Z,F,void 0);this.session.addEvent({type:"system.message",data:{content:H,role:"system"}});let $=(await this.session.getChatMessages()).slice(0,-1),ge={role:"user",content:fpe({customAgentPrompt:void 0,problemStatement:s,capabilities:w})},ye=[...$,ge];await _V(this.options.hooks?.sessionStart,{timestamp:Date.now(),cwd:this.workingDir,source:"new",initialPrompt:e},this.logger);let ve=new Wg(ge,this.logger),Qe=p.getCompletionWithTools(H,ye,F,{failIfInitialInputsTooLong:!1,processors:{preRequest:[ve,new Wg(void 0,this.logger)],onRequestError:[ve]},executeToolsInParallel:!1,abortSignal:this.options.abortController?.signal}),Ne=es();yield this.session.addEvent({type:"assistant.turn_start",data:{turnId:Ne}});for await(let He of Qe){if(this.options.abortController?.signal.aborted){yield this.session.addEvent({type:"abort",data:{reason:"user initiated"}});break}switch(He.kind){case"message":{if($q(He)){let Re=VPe(He)?await Promise.all(He.message.tool_calls.map(async Fe=>{let At=xw(Fe.function.arguments);l.set(Fe.id,Fe.function.name),n.set(Fe.id,At);let wI=await _V(this.options.hooks?.preToolUse,{timestamp:Date.now(),cwd:this.workingDir,toolName:Fe.function.name,toolArgs:At},this.logger);return{toolCallId:Fe.id,name:Fe.function.name,arguments:wI?.modifiedArgs??At}})):[];yield this.session.addEvent({type:"assistant.message",data:{messageId:es(),content:typeof He.message.content=="string"?He.message.content:"",toolRequests:Re}});for(let Fe of Re)yield this.session.addEvent({type:"tool.execution_start",data:{toolCallId:Fe.toolCallId,toolName:Fe.name,arguments:Fe.arguments}})}else(He.message.role==="system"||He.message.role==="developer")&&(yield this.session.addEvent({type:"system.message",data:{role:He.message.role,content:typeof He.message.content=="string"?He.message.content:JSON.stringify(He.message.content),name:"name"in He.message?He.message.name:void 0}}));break}case"model_call_failure":{let Re=new Error(He.modelCall?.error||"Model call failed");await _V(this.options.hooks?.errorOccurred,{timestamp:Date.now(),cwd:this.workingDir,error:Re,errorContext:"model_call",recoverable:!0},this.logger),yield this.session.addEvent({type:"session.error",data:{errorType:"model_call",message:Re.message,stack:Re.stack}});break}case"tool_execution":{let Fe=(await _V(this.options.hooks?.postToolUse,{timestamp:Date.now(),cwd:this.workingDir,toolName:l.get(He.toolCallId)||"unknown",toolArgs:n.get(He.toolCallId)||{},toolResult:He.toolResult},this.logger))?.modifiedResult??He.toolResult,At=(Fe.resultType==="failure"?Fe.error:void 0)||Fe.sessionLog||Fe.textResultForLlm;yield this.session.addEvent({type:"tool.execution_complete",data:{toolCallId:He.toolCallId,success:Fe.resultType==="success",result:Fe.resultType==="success"?{content:At}:void 0,error:Fe.resultType!=="success"?{message:At,code:Fe.resultType}:void 0}});break}case"response":case"images_removed":case"image_processing":case"history_truncated":case"turn_started":case"turn_ended":case"turn_failed":case"turn_retry":case"model_call_success":this.logger.debug(`Ignoring event of kind: ${He.kind}`);break;default:Xp(He,"Unhandled event type")}}yield this.session.addEvent({type:"assistant.turn_end",data:{turnId:Ne}})}catch(r){await _V(this.options.hooks?.sessionEnd,{timestamp:Date.now(),cwd:this.workingDir,reason:"error",error:r instanceof Error?r:new Error(String(r))},this.logger),yield this.session.addEvent({type:"session.error",data:{errorType:"query",message:r instanceof Error?r.message:String(r),stack:r instanceof Error?r.stack:void 0}})}finally{if(await _V(this.options.hooks?.sessionEnd,{timestamp:Date.now(),cwd:this.workingDir,reason:"complete"},this.logger),c)try{await c.stopServers(),this.logger.log("MCP host stopped successfully")}catch(r){this.logger.error(`Error stopping MCP host: ${r}`)}}}buildAgentModelString(){switch(this.options.modelProvider.type){case"openai":return`openai:${this.options.modelProvider.model}`;case"anthropic":return`anthropic:${this.options.modelProvider.model}`;case"copilot":return`capi:${this.options.modelProvider.model}`;default:throw new Error(`Unsupported provider: ${this.options.modelProvider.type}`)}}applyToolFiltering(e,I,l){let n=e;return I&&I.length>0&&(n=n.filter(c=>I.includes(c.name))),l&&l.length>0&&(n=n.filter(c=>!l.includes(c.name))),n}};var Y$e={};Jc(Y$e,{CLISessionManager:()=>tNe});o();o();import{unlink as N$e}from"fs/promises";import{join as drt}from"path";o();var E7=class{sessions;logger;lastAccessedSessionId;constructor({logger:e}={}){this.sessions=new Map,this.logger=e||new Ri}async createSession(){let e=new gp({logger:this.logger});return this.sessions.set(e.sessionId,e),this.lastAccessedSessionId=e.sessionId,e}async getSession(e){let I=this.sessions.get(e);return I&&(this.lastAccessedSessionId=e),I}async getLastSession(){if(this.lastAccessedSessionId){let l=this.sessions.get(this.lastAccessedSessionId);if(l)return l}let e=Array.from(this.sessions.values());if(e.length===0)return;e.sort((l,n)=>n.startTime.getTime()-l.startTime.getTime());let I=e[0];return this.lastAccessedSessionId=I.sessionId,I}async listSessions(){return Array.from(this.sessions.values()).map(e=>({sessionId:e.sessionId,startTime:e.startTime,modifiedTime:e.modifiedTime}))}async saveSession(e){}async deleteSession(e){this.sessions.delete(e.sessionId),this.lastAccessedSessionId===e.sessionId&&(this.lastAccessedSessionId=void 0)}};o();o();o();var h$e=Ll(t$e(),1);o();import{existsSync as P7}from"fs";import{appendFile as qnt,mkdir as _nt,readdir as q7,readFile as s$e,stat as _7,writeFile as $nt}from"fs/promises";import{homedir as a$e}from"os";import{dirname as ect,join as uG}from"path";o();o();var Tnt=new Error("timeout while waiting for mutex to become available"),Ymn=new Error("mutex already locked"),jnt=new Error("request for lock canceled"),Dnt=function(t,e,I,l){function n(c){return c instanceof I?c:new I(function(r){r(c)})}return new(I||(I=Promise))(function(c,r){function s(d){try{G(l.next(d))}catch(i){r(i)}}function a(d){try{G(l.throw(d))}catch(i){r(i)}}function G(d){d.done?c(d.value):n(d.value).then(s,a)}G((l=l.apply(t,e||[])).next())})},$We=class{constructor(e,I=jnt){this._value=e,this._cancelError=I,this._queue=[],this._weightedWaiters=[]}acquire(e=1,I=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((l,n)=>{let c={resolve:l,reject:n,weight:e,priority:I},r=n$e(this._queue,s=>I<=s.priority);r===-1&&e<=this._value?this._dispatchItem(c):this._queue.splice(r+1,0,c)})}runExclusive(e){return Dnt(this,arguments,void 0,function*(I,l=1,n=0){let[c,r]=yield this.acquire(l,n);try{return yield I(c)}finally{r()}})}waitForUnlock(e=1,I=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,I)?Promise.resolve():new Promise(l=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),Knt(this._weightedWaiters[e-1],{resolve:l,priority:I})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){let I=this._value;this._value-=e.weight,e.resolve([I,this._newReleaser(e.weight)])}_newReleaser(e){let I=!1;return()=>{I||(I=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){let I=this._weightedWaiters[e-1];I&&(I.forEach(l=>l.resolve()),this._weightedWaiters[e-1]=[])}else{let e=this._queue[0].priority;for(let I=this._value;I>0;I--){let l=this._weightedWaiters[I-1];if(!l)continue;let n=l.findIndex(c=>c.priority<=e);(n===-1?l:l.splice(0,n)).forEach(c=>c.resolve())}}}_couldLockImmediately(e,I){return(this._queue.length===0||this._queue[0].priority<I)&&e<=this._value}};function Knt(t,e){let I=n$e(t,l=>e.priority<=l.priority);t.splice(I+1,0,e)}function n$e(t,e){for(let I=t.length-1;I>=0;I--)if(e(t[I]))return I;return-1}var Pnt=function(t,e,I,l){function n(c){return c instanceof I?c:new I(function(r){r(c)})}return new(I||(I=Promise))(function(c,r){function s(d){try{G(l.next(d))}catch(i){r(i)}}function a(d){try{G(l.throw(d))}catch(i){r(i)}}function G(d){d.done?c(d.value):n(d.value).then(s,a)}G((l=l.apply(t,e||[])).next())})},D7=class{constructor(e){this._semaphore=new $We(1,e)}acquire(){return Pnt(this,arguments,void 0,function*(e=0){let[,I]=yield this._semaphore.acquire(1,e);return I})}runExclusive(e,I=0){return this._semaphore.runExclusive(()=>e(),1,I)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}},l$e=function(t,e,I,l){function n(c){return c instanceof I?c:new I(function(r){r(c)})}return new(I||(I=Promise))(function(c,r){function s(d){try{G(l.next(d))}catch(i){r(i)}}function a(d){try{G(l.throw(d))}catch(i){r(i)}}function G(d){d.done?c(d.value):n(d.value).then(s,a)}G((l=l.apply(t,e||[])).next())})};function c$e(t,e,I=Tnt){return{acquire:(l,n)=>{let c;if(j7(t)?c=l:(c=void 0,n=l),c!==void 0&&c<=0)throw new Error(`invalid weight ${c}: must be positive`);return new Promise((r,s)=>l$e(this,void 0,void 0,function*(){let a=!1,G=setTimeout(()=>{a=!0,s(I)},e);try{let d=yield j7(t)?t.acquire(c,n):t.acquire(n);a?(Array.isArray(d)?d[1]:d)():(clearTimeout(G),r(d))}catch(d){a||(clearTimeout(G),s(d))}}))},runExclusive(l,n,c){return l$e(this,void 0,void 0,function*(){let r=()=>{};try{let s=yield this.acquire(n,c);return Array.isArray(s)?(r=s[1],yield l(s[0])):(r=s,yield l())}finally{r()}})},release(l){t.release(l)},cancel(){return t.cancel()},waitForUnlock:(l,n)=>{let c;if(j7(t)?c=l:(c=void 0,n=l),c!==void 0&&c<=0)throw new Error(`invalid weight ${c}: must be positive`);return new Promise((r,s)=>{let a=setTimeout(()=>s(I),e);(j7(t)?t.waitForUnlock(c,n):t.waitForUnlock(n)).then(()=>{clearTimeout(a),r()})})},isLocked:()=>t.isLocked(),getValue:()=>t.getValue(),setValue:l=>t.setValue(l)}}function j7(t){return t.getValue!==void 0}var K7=class{mutexes=new Map;async runExclusive(e,I,l=5e3){let n=this.mutexes.get(e);n||(n=new D7,n.refCount=0,this.mutexes.set(e,n));let c=n;try{return c.refCount++,await c$e(n,l).runExclusive(I)}finally{--c.refCount===0&&this.mutexes.delete(e)}}};var eNe=(I=>(I.DEFAULT="config",I.MCP="mcp",I))(eNe||{});function r$e(t){return Object.values(eNe).includes(t)}var $7=".copilot",e_=new K7;async function o$e(t){let e=ect(t);try{await _nt(e,{recursive:!0,mode:448})}catch{}}async function Ict(t,e){if(P7(t))try{let I={},l=await e_.runExclusive(t,()=>s$e(t,"utf8"));return l.trim().startsWith("{")?I=JSON.parse(l):l.split(`
1414
1414
  `).forEach(n=>{let[c,r]=n.split("=").map(s=>s.trim());c&&r&&(I[c]=r)}),e(I)}catch(I){throw new Error(`Failed to read configuration from ${t}: ${I}`)}}async function tct(t,e){try{await o$e(t);let I=JSON.stringify(e,null,2);await e_.runExclusive(t,()=>$nt(t,I,{mode:384}))}catch(I){throw new Error(`Failed to write configuration to ${t}: ${I}`)}}var G$e=(t,e,{shouldCache:I})=>{let l=new Map,n=()=>{let b=r$e(e)?process.env.XDG_CONFIG_HOME:process.env.XDG_STATE_HOME;return b?uG(b,$7):uG(a$e(),$7)},c=()=>{let b=r$e(e)?"-config":"-state";return`${e}${e=="config"?"":b}`},r=b=>{let m=".json",h=c()+(b?"":m),p=uG(n(),h,b?`${b}${m}`:"");return!P7(p)&&P7(p.replace(/\.json$/,""))&&(p=p.replace(/\.json$/,"")),p},s=async()=>{let b=uG(n(),c());try{let h=(await q7(b,{withFileTypes:!0})).filter(Z=>Z.isFile()&&Z.name.endsWith(".json")).map(Z=>Z.name),p=await Promise.all(h.map(async Z=>{let W=uG(b,Z);try{let Y=await _7(W);return{file:Z,mtime:Y.mtime}}catch{return{file:Z,mtime:new Date}}}));return p.sort((Z,W)=>W.mtime.getTime()-Z.mtime.getTime()),p.map(Z=>Z.file)}catch{}return[]},a=async()=>{let b=uG(n(),c());try{let h=(await q7(b,{withFileTypes:!0})).filter(Z=>Z.isFile()&&Z.name.endsWith(".json")).map(Z=>Z.name),p=await Promise.all(h.map(async Z=>{let W=uG(b,Z);try{let Y=await _7(W);return{file:Z,mtime:Y.mtime,ctime:Y.ctime}}catch{return{file:Z,mtime:new Date,ctime:new Date}}}));return p.sort((Z,W)=>W.mtime.getTime()-Z.mtime.getTime()),p}catch{}return[]},G=async(b="")=>{if(I&&l.has(b))return l.get(b);let m=await Ict(r(b),t);return I&&m&&l.set(b,m),m},d=async(b,m="")=>{I&&l.set(m,b),await tct(r(m),b)};return{load:G,write:d,writeKey:async(b,m,h)=>{let p=await G(h);if(m===void 0){p&&(delete p[b],await d(p,h));return}let Z={[b]:m},W;p?W={...p,...Z}:W=Z,await d(W,h)},path:r,directoryFiles:s,directoryFilesWithMetadata:a}},d$e=(t,e)=>G$e(t,e,{shouldCache:!0}),i$e=(t,e)=>G$e(t,e,{shouldCache:!1}),b$e=(t,e)=>{let I=()=>{let G=process.env.XDG_STATE_HOME;return G?uG(G,$7):uG(a$e(),$7)},l=()=>`${e}-state`,n=G=>{let d=".jsonl",i=l()+(G?"":d);return uG(I(),i,G?`${G}${d}`:"")};return{load:async G=>{let d=n(G);if(!P7(d))return[];try{let b=(await e_.runExclusive(d,()=>s$e(d,"utf8"))).trim().split(`
1415
1415
  `).filter(h=>h.trim()),m=[];for(let h=0;h<b.length;h++)try{let p=JSON.parse(b[h]),Z=t(p);m.push(Z)}catch(p){throw new Error(`Invalid event at line ${h+1} in ${d}: ${p}`)}return m}catch(i){throw new Error(`Failed to read JSONL from ${d}: ${i}`)}},append:async(G,d)=>{let i=n(d),b=Array.isArray(G)?G:[G];try{await o$e(i);let m=b.map(h=>JSON.stringify(h)).join(`
1416
1416
  `)+`