@github/copilot 0.0.339-2 → 0.0.339-3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -1891,7 +1891,7 @@ Pay attention to the following when using it:
1891
1891
  `}var qbn=f2e.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function $bn(){let t={};for(let e of qbn){let l=f2e.env[e];l!==void 0&&(l.startsWith("()")||(t[e]=l))}return t}var v2e=class{constructor(e){this._abortController=new AbortController,this._readBuffer=new C2e,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new Kbn)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,l)=>{var n,I,r,a,s;this._process=(0,HBt.default)(this._serverParams.command,(n=this._serverParams.args)!==null&&n!==void 0?n:[],{env:{...$bn(),...this._serverParams.env},stdio:["pipe","pipe",(I=this._serverParams.stderr)!==null&&I!==void 0?I:"inherit"],shell:!1,signal:this._abortController.signal,windowsHide:f2e.platform==="win32"&&epn(),cwd:this._serverParams.cwd}),this._process.on("error",o=>{var d,u;if(o.name==="AbortError"){(d=this.onclose)===null||d===void 0||d.call(this);return}l(o),(u=this.onerror)===null||u===void 0||u.call(this,o)}),this._process.on("spawn",()=>{e()}),this._process.on("close",o=>{var d;this._process=void 0,(d=this.onclose)===null||d===void 0||d.call(this)}),(r=this._process.stdin)===null||r===void 0||r.on("error",o=>{var d;(d=this.onerror)===null||d===void 0||d.call(this,o)}),(a=this._process.stdout)===null||a===void 0||a.on("data",o=>{this._readBuffer.append(o),this.processReadBuffer()}),(s=this._process.stdout)===null||s===void 0||s.on("error",o=>{var d;(d=this.onerror)===null||d===void 0||d.call(this,o)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){var e,l;return this._stderrStream?this._stderrStream:(l=(e=this._process)===null||e===void 0?void 0:e.stderr)!==null&&l!==void 0?l:null}get pid(){var e,l;return(l=(e=this._process)===null||e===void 0?void 0:e.pid)!==null&&l!==void 0?l:null}processReadBuffer(){for(var e,l;;)try{let n=this._readBuffer.readMessage();if(n===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,n)}catch(n){(l=this.onerror)===null||l===void 0||l.call(this,n)}}async close(){this._abortController.abort(),this._process=void 0,this._readBuffer.clear()}send(e){return new Promise(l=>{var n;if(!(!((n=this._process)===null||n===void 0)&&n.stdin))throw new Error("Not connected");let I=fBt(e);this._process.stdin.write(I)?l():this._process.stdin.once("drain",l)})}};function epn(){return"type"in f2e}c();c();var H2e=class extends TransformStream{constructor({onError:e,onRetry:l,onComment:n}={}){let I;super({start(r){I=R2e({onEvent:a=>{r.enqueue(a)},onError(a){e==="terminate"?r.error(a):typeof e=="function"&&e(a)},onRetry:l,onComment:n})},transform(r){I.feed(r)}})}};var tpn={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},sce=class extends Error{constructor(e,l){super(`Streamable HTTP error: ${l}`),this.code=e}},X2e=class{constructor(e,l){var n;this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=l?.requestInit,this._authProvider=l?.authProvider,this._fetch=l?.fetch,this._sessionId=l?.sessionId,this._reconnectionOptions=(n=l?.reconnectionOptions)!==null&&n!==void 0?n:tpn}async _authThenStart(){var e;if(!this._authProvider)throw new Xg("No auth provider");let l;try{l=await hk(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(l!=="AUTHORIZED")throw new Xg;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let l={};if(this._authProvider){let I=await this._authProvider.tokens();I&&(l.Authorization=`Bearer ${I.access_token}`)}this._sessionId&&(l["mcp-session-id"]=this._sessionId),this._protocolVersion&&(l["mcp-protocol-version"]=this._protocolVersion);let n=this._normalizeHeaders((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...l,...n})}async _startOrAuthSse(e){var l,n,I;let{resumptionToken:r}=e;try{let a=await this._commonHeaders();a.set("Accept","text/event-stream"),r&&a.set("last-event-id",r);let s=await((l=this._fetch)!==null&&l!==void 0?l:fetch)(this._url,{method:"GET",headers:a,signal:(n=this._abortController)===null||n===void 0?void 0:n.signal});if(!s.ok){if(s.status===401&&this._authProvider)return await this._authThenStart();if(s.status===405)return;throw new sce(s.status,`Failed to open SSE stream: ${s.statusText}`)}this._handleSseStream(s.body,e,!0)}catch(a){throw(I=this.onerror)===null||I===void 0||I.call(this,a),a}}_getNextReconnectionDelay(e){let l=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,I=this._reconnectionOptions.maxReconnectionDelay;return Math.min(l*Math.pow(n,e),I)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,l=0){var n;let I=this._reconnectionOptions.maxRetries;if(I>0&&l>=I){(n=this.onerror)===null||n===void 0||n.call(this,new Error(`Maximum reconnection attempts (${I}) exceeded.`));return}let r=this._getNextReconnectionDelay(l);setTimeout(()=>{this._startOrAuthSse(e).catch(a=>{var s;(s=this.onerror)===null||s===void 0||s.call(this,new Error(`Failed to reconnect SSE stream: ${a instanceof Error?a.message:String(a)}`)),this._scheduleReconnection(e,l+1)})},r)}_handleSseStream(e,l,n){if(!e)return;let{onresumptiontoken:I,replayMessageId:r}=l,a;(async()=>{var o,d,u,G;try{let p=e.pipeThrough(new TextDecoderStream).pipeThrough(new H2e).getReader();for(;;){let{value:h,done:W}=await p.read();if(W)break;if(h.id&&(a=h.id,I?.(h.id)),!h.event||h.event==="message")try{let y=ok.parse(JSON.parse(h.data));r!==void 0&&Gie(y)&&(y.id=r),(o=this.onmessage)===null||o===void 0||o.call(this,y)}catch(y){(d=this.onerror)===null||d===void 0||d.call(this,y)}}}catch(p){if((u=this.onerror)===null||u===void 0||u.call(this,new Error(`SSE stream disconnected: ${p}`)),n&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:I,replayMessageId:r},0)}catch(h){(G=this.onerror)===null||G===void 0||G.call(this,new Error(`Failed to reconnect: ${h instanceof Error?h.message:String(h)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Xg("No auth provider");if(await hk(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new Xg("Failed to authorize")}async close(){var e,l;(e=this._abortController)===null||e===void 0||e.abort(),(l=this.onclose)===null||l===void 0||l.call(this)}async send(e,l){var n,I,r,a;try{let{resumptionToken:s,onresumptiontoken:o}=l||{};if(s){this._startOrAuthSse({resumptionToken:s,replayMessageId:fRe(e)?e.id:void 0}).catch(R=>{var w;return(w=this.onerror)===null||w===void 0?void 0:w.call(this,R)});return}let d=await this._commonHeaders();d.set("content-type","application/json"),d.set("accept","application/json, text/event-stream");let u={...this._requestInit,method:"POST",headers:d,body:JSON.stringify(e),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},G=await((I=this._fetch)!==null&&I!==void 0?I:fetch)(this._url,u),p=G.headers.get("mcp-session-id");if(p&&(this._sessionId=p),!G.ok){if(G.status===401&&this._authProvider){if(this._resourceMetadataUrl=ace(G),await hk(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new Xg;return this.send(e)}let R=await G.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${G.status}): ${R}`)}if(G.status===202){Ukt(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(R=>{var w;return(w=this.onerror)===null||w===void 0?void 0:w.call(this,R)});return}let W=(Array.isArray(e)?e:[e]).filter(R=>"method"in R&&"id"in R&&R.id!==void 0).length>0,y=G.headers.get("content-type");if(W)if(y?.includes("text/event-stream"))this._handleSseStream(G.body,{onresumptiontoken:o},!1);else if(y?.includes("application/json")){let R=await G.json(),w=Array.isArray(R)?R.map(C=>ok.parse(C)):[ok.parse(R)];for(let C of w)(r=this.onmessage)===null||r===void 0||r.call(this,C)}else throw new sce(-1,`Unexpected content type: ${y}`)}catch(s){throw(a=this.onerror)===null||a===void 0||a.call(this,s),s}}get sessionId(){return this._sessionId}async terminateSession(){var e,l,n;if(this._sessionId)try{let I=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:I,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},a=await((l=this._fetch)!==null&&l!==void 0?l:fetch)(this._url,r);if(!a.ok&&a.status!==405)throw new sce(a.status,`Failed to terminate session: ${a.statusText}`);this._sessionId=void 0}catch(I){throw(n=this.onerror)===null||n===void 0||n.call(this,I),I}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}};c();var k2e=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 UPe(this),await this.server.connect(this.serverTransport)}async send(e){if(this.closed)throw new Error("Transport is closed");setImmediate(()=>{try{this.serverTransport?.onmessage?.(e)}catch(l){this.onerror?.(l instanceof Error?l:new Error(String(l)))}})}receive(e){this.closed||this.onmessage?.(e)}async close(){this.closed||(this.closed=!0,await this.serverTransport?.close(),this.onclose?.())}},UPe=class{constructor(e){this.clientTransport=e}onmessage;onerror;onclose;closed=!1;async start(){}async send(e){if(this.closed)throw new Error("Transport is closed");setImmediate(()=>{try{this.clientTransport.receive(e)}catch(l){this.onerror?.(l instanceof Error?l:new Error(String(l)))}})}async close(){this.closed||(this.closed=!0,this.onclose?.())}};var L2e=class{createTransport(e){switch(e.type){case"stdio":{let l=new v2e({command:e.command,args:e.args,env:e.env,stderr:e.stderr?"pipe":void 0});return l.stderr?.pipe(e.stderr),l}case"http":return new X2e(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"sse":return new w2e(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"memory":return new k2e(e.server);default:throw new Error(`Unsupported transport type: ${e.type}`)}}};c();var y9="blackbird-mcp-server",cK="github-mcp-server",MPe="playwright";function dK(t){return t.type===void 0||t.type.toLowerCase()==="local"||t.type.toLowerCase()==="stdio"}function uK(t){return oce(t)||ice(t)}function oce(t){return t.type?.toLowerCase()==="http"}function ice(t){return t.type?.toLowerCase()==="sse"}function cce(t){return t.type?.toLowerCase()==="memory"}var _Pe=class extends lpn{constructor(l,n){super({decodeStrings:!1});this.serverName=l;this.logger=n}_write(l,n,I){try{let r=l.toString();this.logger.log(`[mcp server ${this.serverName} stderr] ${r}`),I()}catch(r){I(r instanceof Error?r:new Error(String(r)))}}},J2e=class{constructor(e,l=new y2e,n=new L2e){this.logger=e;this.clientFactory=l;this.transportFactory=n}clients={};transports={};async startLocalMcpClient(e,l,n,I){this.logger.log(`Starting MCP client for ${e} with command: ${n} and args: ${I}`);let r=new _Pe(e,this.logger),a={type:"stdio",command:n,args:I,env:{...l,PATH:process.env.PATH},stderr:r},s=this.transportFactory.createTransport(a);await this.setupAndConnectClient(e,s)}async startHttpMcpClient(e,l){this.logger.log(`Starting remote MCP client for ${e} with url: ${l.url}`);let n={type:"http",url:l.url,headers:l.headers},I=this.transportFactory.createTransport(n);await this.setupAndConnectClient(e,I)}async startSseMcpClient(e,l){this.logger.log(`Starting remote MCP client for ${e} with url: ${l.url}`);let n={type:"sse",url:l.url,headers:l.headers},I=this.transportFactory.createTransport(n);await this.setupAndConnectClient(e,I)}async startInMemoryMcpClient(e,l){this.logger.log(`Starting in-memory MCP client for ${e}`);let n={type:"memory",server:l},I=this.transportFactory.createTransport(n);await this.setupAndConnectClient(e,I)}async setupAndConnectClient(e,l){this.transports[e]=l,l.onclose=()=>{this.logger.log(`MCP transport for ${e} closed`),delete this.transports[e]},this.logger.log(`Creating MCP client for ${e}...`);let n=this.clientFactory.createClient({name:"github-copilot-developer",version:"1.0.0"},{capabilities:{experimental:void 0,roots:void 0,sampling:void 0}}),I=Date.now();this.logger.log(`Connecting MCP client for ${e}...`),await n.connect(l),n.onclose=()=>{this.logger.log(`MCP client for ${e} closed`),delete this.clients[e]},n.onerror=r=>{this.logger.error(`MCP client for ${e} errored ${r}`)},this.logger.log(`MCP client for ${e} connected, took ${Date.now()-I}ms`),this.clients[e]=n}async getTools(e,l){let n={};for(let[I,r]of Object.entries(this.clients)){let a=[];try{this.logger.log(`Fetching tools from client: ${I}`);let s=await r.listTools(),o=e?.mcpServers[I].tools,d=e?.mcpServers[I].filterMapping;for(let G of s.tools){if(G.name==="get_copilot_space")continue;if(!(o?.includes("*")||o?.includes(G.name))){this.logger.log(`Tool ${G.name} is not in the allowed list for client: ${I}`);continue}let h=HNe(I,G.name),W=`${I}-${G.name}`,y;typeof d=="string"?y=wxe(d):y=wxe(d?.[G.name]??"hidden_characters"),n[`${I}/${G.name}`]={name:W,title:G.title??G.annotations?.title??G.name,description:G.description??W,input_schema:G.inputSchema,readOnly:G.annotations?.readOnlyHint,safeForTelemetry:{name:!!(e?.mcpServers[I].isDefaultServer||h),inputsNames:!!e?.mcpServers[I].isDefaultServer},filterMode:y},a.push(G.name),this.logger.log(`Tool ${G.name} added to tools list for client: ${I}`)}this.logger.log(`Successfully retrieved ${a.length} tools from client: ${I}`);let u=r.getServerVersion();await this.logServerSuccessWithTools(I,a,u,l)}catch(s){this.logger.error(`Failed to get tools from client: ${I} ${s}`)}}return this.logger.log(`All tools retrieved: ${JSON.stringify(n,null,2)}`),n}async logServerSuccessWithTools(e,l,n,I){if(e!=y9&&I)try{let r=l.map(o=>`- ${o}`).join(`
1892
1892
  `),s=`MCP server started successfully${n?` (version ${n.version})`:""} with ${l.length} ${l.length===1?"tool":"tools"} - for the full output, see the verbose logs
1893
1893
 
1894
- ${r}`;await I.logMCPSetup(e,s),this.logger.log(`Updated session log for ${e} with ${l.length} tools`)}catch(r){this.logger.error(`Failed to update session log for ${e}: ${r}`)}}};c();var DPe={mcpServers:{}},B2e=class{constructor(e,l,n){this.logger=e;this.registry=l;this.remoteEnabled=n?.remoteEnabled??!1,this.mcp3pEnabled=n?.mcp3pEnabled??!1,this.blackbirdMetisIndexEnabled=n?.blackbirdMetisIndexEnabled??!1,this.sessionClient=n?.sessionClient,this.mcpEnvConfig=void 0}remoteEnabled;mcp3pEnabled;blackbirdMetisIndexEnabled;mcpEnvConfig;sessionClient;ReadMcpConfigFromEnv(e){this.mcpEnvConfig=process.env.GITHUB_COPILOT_MCP_JSON,this.mcp3pEnabled=process.env.GITHUB_COPILOT_3P_MCP_ENABLED==="true",this.remoteEnabled=process.env.GITHUB_COPILOT_REMOTE_MCP_ENABLED==="true",this.blackbirdMetisIndexEnabled=process.env.BLACKBIRD_METIS_INDEX_ENABLED==="true";let l=this.validateEnvConfig();return process.env.GITHUB_COPILOT_CLI_MODE==="true"?this.logger.log("CLI mode detected - skipping default MCP servers"):(this.logger.log("Adding default MCP servers to configuration"),this.configureBlackbirdMcp(l,e),this.configureGitHubMcp(l,e),this.configurePlaywrightMcp(l)),l}validateEnvConfig(){if(!this.mcp3pEnabled)return this.logger.log("User-provided MCPs are disabled"),DPe;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"),DPe;try{let e=JSON.parse(this.mcpEnvConfig);if(!e.mcpServers)throw new Error("User-provided config had incorrect format. Missing 'mcpServers' property.");for(let l in e.mcpServers)e.mcpServers[l].isDefaultServer=!1;return e}catch(e){return this.logger.error(`Warning: User-provided MCP servers were defined but invalid: ${e}`),DPe}}configureGitHubMcp(e,l){this.remoteEnabled?this.configureRemoteGitHubMcp(e,l):this.configureLocalGitHubMcp(e)}configureRemoteGitHubMcp(e,l){this.logger.log("Using default remote GitHub MCP server configuration");let n="repos,issues,users,pull_requests,code_security,secret_protection,actions,bing_search";process.env.COPILOT_MCP_COPILOT_SPACES_ENABLED==="true"&&(this.logger.log("Enabling Copilot Spaces in GitHub MCP server configuration"),n=n+",copilot_spaces");let I={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":n,"X-MCP-Host":"github-coding-agent","X-Initiator":"agent"};l&&l.api?.copilot?.integrationId&&(I["Copilot-Integration-Id"]=l.api.copilot.integrationId),process.env.GITHUB_COPILOT_INTERACTION_ID&&(I["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let r={type:"http",url:this.getCapiMcpUrl(),headers:I,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[cK]=r}configureLocalGitHubMcp(e){if(e.mcpServers[cK]){this.logger.log("Using user-provided GitHub MCP server configuration");let l=e.mcpServers[cK]??{};dK(l)&&!l.command&&(e.mcpServers[cK]={...l,command:"./copilot-developer-action-main/github-mcp-server/github-mcp-server",isDefaultServer:!0},this.logger.log("Added default command to user-provided GitHub MCP server configuration"))}else{this.logger.log("Using default local GitHub MCP server configuration");let l={command:"./copilot-developer-action-main/github-mcp-server/github-mcp-server",args:["stdio","--read-only"],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",GITHUB_HOST:"GITHUB_SERVER_URL"},tools:["*"],isDefaultServer:!0};e.mcpServers[cK]=l}}configurePlaywrightMcp(e){if(!e.mcpServers[MPe]){if((process.env.COPILOT_FEATURE_FLAGS??"").split(",").map(n=>n.trim()).includes("copilot_swe_agent_playwright_use_firewall")){this.logger.log("Playwright MCP server is configured to use the firewall, skipping launch.");return}this.logger.log("Enabling Playwright MCP server");let l={command:"npx",args:[...ASe,"--allowed-origins","localhost;localhost:*;127.0.0.1;127.0.0.1:*"],tools:["*"],isDefaultServer:!0};e.mcpServers[MPe]=l}}configureBlackbirdMcp(e,l){this.remoteEnabled?this.configureRemoteBlackbirdMcp(e):this.blackbirdMetisIndexEnabled?this.configureLocalMetisBlackbirdMCP(e,l):this.configureLocalBlackbirdMcp(e)}configureLocalMetisBlackbirdMCP(e,l){this.logger.log("Using local Metis Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${l.blackbird?.mode}`);let n=process.env.AGENT_DIR||"/agent";this.logger.log(`Using agent directory: ${n}`);let I=[];l.blackbird?.mode==="tool"&&(I=["*"]),this.logger.log(`Using blackbird Metis server: ${l.blackbird?.mode}`);let r={command:`${n}/blackbird/mcp`,args:["serve","--index",`${n}/blackbird/metis`],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",COPILOT_API_HMAC_KEY:"CAPI_HMAC_KEY",MODEL_BASED_RETRIEVAL_TOKEN:"BLACKBIRD_AUTH_MODEL_BASED_RETRIEVAL_TOKEN",METIS_API_KEY:"BLACKBIRD_AUTH_METIS_API_KEY"},tools:I,isDefaultServer:!0};e.mcpServers[y9]=r}configureLocalBlackbirdMcp(e){this.logger.log("Using local Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let l=[];process.env.BLACKBIRD_MODE==="tool"&&(l=["*"]);let n={command:"./copilot-developer-action-main/blackbird-mcp-server/blackbird-mcp-server",args:["stdio"],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",CAPI_HOST:"COPILOT_API_URL"},tools:l,isDefaultServer:!0};e.mcpServers[y9]=n}configureRemoteBlackbirdMcp(e){this.logger.log("Using remote Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let l=[];process.env.BLACKBIRD_MODE==="tool"&&(l=["*"]);let n={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":"search_agent","X-MCP-Host":"github-coding-agent"};process.env.GITHUB_COPILOT_INTERACTION_ID&&(n["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let I={type:"http",url:this.getCapiMcpUrl(),headers:n,tools:l,isDefaultServer:!0};e.mcpServers[y9]=I}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 dK(e)||oce(e)||ice(e)||cce(e)}isValidLocalServerConfig(e){return e.command!==void 0&&e.command.trim()!==""&&Array.isArray(e.args)}isValidRemoteServerConfig(e){return e.url!==void 0&&e.url.trim()!==""}isValidInMemoryServerConfig(e){return e.serverInstance!==void 0&&typeof e.serverInstance=="object"}validateServerConfig(e,l){return this.remoteEnabled&&!this.isValidServerType(l)?(this.logger.error(`Unsupported server type "${l.type}" for server "${e}". Only "Local", "STDIO", "HTTP", "SSE", or "Memory" are supported.`),!1):!this.remoteEnabled&&!dK(l)&&!cce(l)?(this.logger.error(`Unsupported server type "${l.type}" for server "${e}". Only "Local", "STDIO", or "Memory" are supported.`),!1):l.tools?dK(l)&&!this.isValidLocalServerConfig(l)?(this.logger.error(`Invalid local server configuration for "${e}". Please ensure 'command' and 'args' are provided.`),!1):(oce(l)||ice(l))&&!this.isValidRemoteServerConfig(l)?(this.logger.error(`Invalid remote server configuration for "${e}". Please ensure 'url' is provided.`),!1):cce(l)&&!this.isValidInMemoryServerConfig(l)?(this.logger.error(`Invalid in-memory server configuration for "${e}". Please ensure 'serverInstance' is provided and is an instance of MCPServer.`),!1):!0:(this.logger.error(`No tools specified for server "${e}". Please provide a list of tools or "*" to include all tools.`),!1)}async processHttpServer(e,l){try{let n=this.resolveHeaders(l.headers,process.env),I={...l,headers:n};await this.registry.startHttpMcpClient(e,I),this.logger.log(`Started MCP client for remote server ${e}`)}catch(n){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${n}`),n}}async processSseServer(e,l){try{let n=this.resolveRemoteServerConfig(l);await this.registry.startSseMcpClient(e,n),this.logger.log(`Started MCP client for remote server ${e}`)}catch(n){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${n}`),n}}resolveRemoteServerConfig(e){return e.url=this.resolveString(e.url,process.env),e.headers=this.resolveHeaders(e.headers,process.env),{...e,url:e.url,headers:e.headers}}async processInMemoryServer(e,l){try{await this.registry.startInMemoryMcpClient(e,l.serverInstance),this.logger.log(`Started in-memory MCP client for ${e}`)}catch(n){throw this.logger.error(`Failed to start in-memory MCP client for ${e}: ${n}`),n}}async processLocalServer(e,l){let n={...l};if(l.command==="python")try{n=await this.convertPythonToPipx(n)}catch(a){this.logger.error(`Failed to handle Python module for ${e}: ${a}`)}let I=this.buildEnvironment(n),r=this.resolveLocalServerConfig(n,I);this.logger.log(`Starting MCP client for ${e} with command: ${r.command} and args: ${r.args}`);try{await this.registry.startLocalMcpClient(e,I,r.command,r.args),this.logger.log(`Started MCP client for ${e}`)}catch(a){throw this.logger.error(`Failed to start MCP client for ${e}: ${a}`),a}}convertPythonToPipx(e){if(!e||!e.args||e.args.length===0)return e;let l=e.args,n=l.indexOf("-m");if(n===-1||n===l.length-1)throw new Error("Python command with -m flag must specify a module");let I=l[n+1];this.logger.log(`Converting Python module: ${I} to pipx command`);let r=["run",I];for(let a=n+2;a<l.length;a++)r.push(l[a]);for(let a=0;a<n;a++)r.push(l[a]);return{...e,command:"pipx",args:r}}buildEnvironment(e){let l={};if(e.env)for(let[n,I]of Object.entries(e.env)){let r=I.trim();process.env[r]!==void 0&&(l[n]=process.env[r])}return l}resolveLocalServerConfig(e,l){let n=this.resolveString(e.command,l),I=this.resolveArray(e.args,l);return{...e,command:n,args:I}}resolveString(e,l){return l?e.replace(/\$(?:\{([A-Z0-9_]+)(?::-(.*?))?\}|([A-Z0-9_]+))/g,(n,I,r,a)=>{let o=l[I||a];return o!==void 0?o:r!==void 0?r:n}):e}resolveArray(e,l){return e?l?e.map(n=>this.resolveString(n,l)):e:[]}resolveHeaders(e,l){if(!e)return{};if(!l)return e;let n={};for(let[I,r]of Object.entries(e)){let a=this.resolveArray([r],l);n[I]=a[0]}return n}async processServers(e){if(!e)throw new Error("No servers to process");let l=Object.entries(e.mcpServers).map(([n,I])=>this.processServer(n,I));await Promise.all(l)}async processServer(e,l){if(!this.validateServerConfig(e,l)){this.logger.error(`Skipping server "${e}" due to invalid configuration.`);return}try{dK(l)?await this.processLocalServer(e,l):oce(l)&&this.remoteEnabled?await this.processHttpServer(e,l):ice(l)&&this.remoteEnabled?await this.processSseServer(e,l):cce(l)&&await this.processInMemoryServer(e,l)}catch(n){e!==y9&&await this.logServerFailure(e,n)}}async logServerFailure(e,l){if(this.sessionClient)try{await this.sessionClient.logMCPSetup(e,`<error>MCP server failed to start: ${l.message} - for the full output, see the verbose logs</error>`)}catch(n){this.logger.error(`Failed to log failure for MCP Server '${e}': '${n}'`)}}};var x2e=class{constructor(e,l,n){this.logger=e;let I;if(typeof l=="string"){if(I=JSON.parse(l),typeof I!="object")throw new Error("Invalid MCP configuration: must be an object");if(I===null||!("mcpServers"in I)||typeof I.mcpServers!="object")throw new Error("Invalid MCP configuration: missing or invalid mcpServers property");this.config=I}else this.config=l;this.disabledServers=new Set(n||[]),this.registry=new J2e(this.logger),this.processor=new B2e(this.logger,this.registry,{mcp3pEnabled:!0,remoteEnabled:!0})}registry;processor;config;startServersPromise=null;allTools=null;disabledServers;async startServers(){return this.startServersPromise||(this.startServersPromise=this.processServersWithExtensions()),this.startServersPromise}async injectDefaultServers(e){}async processServersWithExtensions(){await this.injectDefaultServers(this.config);let e;if(this.disabledServers.size>0){let l={};for(let[n,I]of Object.entries(this.config.mcpServers))this.disabledServers.has(n)?this.logger.log(`Skipping disabled MCP server: ${n}`):l[n]=I;e={...this.config,mcpServers:l}}else e=this.config;return this.processor.processServers(e)}async stopServers(){for(let[e,l]of Object.entries(this.registry.transports))try{await l.close()}catch(n){this.logger.error(`Error closing transport for ${e}: ${n}`)}this.startServersPromise=null,this.allTools=null}async getTools(e,l,n){if(!this.allTools){await this.startServers();let I=new hre(e,l,n),r=[];for(let a of Object.keys(this.registry.clients)){let s=await I.loadTools({mcpClient:this.registry.clients[a],clientName:a,tools:this.config.mcpServers[a]?.tools||["*"],filterMapping:this.config.mcpServers[a]?.filterMapping||"hidden_characters"});r.push(...s)}this.allTools=r}return this.allTools}getConfig(){return this.config}async startServer(e,l){await this.startServers(),this.config.mcpServers[e]=l,await this.processor.processServer(e,l),this.allTools=null}async stopServer(e){let l=this.registry.transports[e];if(l)try{await l.close(),delete this.registry.transports[e]}catch(n){this.logger.error(`Error closing transport for ${e}: ${n}`)}this.registry.clients[e]&&delete this.registry.clients[e],this.allTools=null}async restartServer(e,l){this.isServerRunning(e)&&await this.stopServer(e),delete this.config.mcpServers[e],await this.startServer(e,l)}isServerRunning(e){return e in this.registry.transports&&e in this.registry.clients}isServerDisabled(e){return this.disabledServers.has(e)}async disableServer(e){if(this.disabledServers.has(e)){this.logger.log(`Server ${e} is already disabled`);return}this.disabledServers.add(e),this.logger.log(`Disabled server ${e} for this session`),this.isServerRunning(e)&&await this.stopServer(e),this.allTools=null}async enableServer(e){if(!this.disabledServers.has(e)){this.logger.log(`Server ${e} is not disabled`);return}this.disabledServers.delete(e),this.logger.log(`Enabled server ${e} for this session`);let l=this.getServerConfig(e);l?await this.startServer(e,l):await this.startBuiltInServer(e),this.allTools=null}async startBuiltInServer(e){}getServerConfig(e){return this.config.mcpServers[e]}};c();var npn="/login/device/code",Ipn="/login/oauth/access_token",XBt="Ov23ctDVkRmgkPke0Mmm",N2="https://github.com",Ak=class extends Error{constructor(l,n){super(n);this.status=l;this.message=n;this.name="GitHubApiError"}};function kBt(t){let e=new URL(t);return e.hostname.startsWith("api.")||(e.hostname="api."+e.hostname),e.href}async function LBt(t){let e=new URL(npn,t),l=await fetch(e.href,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({client_id:XBt,scope:"user:email,read:user,repo,workflow"})});if(!l.ok)throw new Ak(l.status,`Failed to request device code: ${l.statusText}`);return await l.json()}async function JBt(t,e){let l=new URL(Ipn,t),n=await fetch(l.href,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({client_id:XBt,device_code:e,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})});if(!n.ok)throw new Ak(n.status,`Failed to authorize: ${n.statusText}`);let I=await n.json();if(typeof I.access_token=="string")return I.access_token;if(I.error!=="authorization_pending"&&I.error!=="slow_down")throw new Error(I.error_description||`Unexpected error: ${I.error}`)}async function mK(t,e){let l=new URL("/user",kBt(t)),n=await fetch(l.href,{headers:{Authorization:`Bearer ${e}`,Accept:"application/json"}});if(!n.ok)throw new Ak(n.status,`Failed to fetch user info: ${n.statusText}`);return(await n.json()).login}async function GK(t,e){let l=`
1894
+ ${r}`;await I.logMCPSetup(e,s),this.logger.log(`Updated session log for ${e} with ${l.length} tools`)}catch(r){this.logger.error(`Failed to update session log for ${e}: ${r}`)}}};c();var DPe={mcpServers:{}},B2e=class{constructor(e,l,n){this.logger=e;this.registry=l;this.remoteEnabled=n?.remoteEnabled??!1,this.mcp3pEnabled=n?.mcp3pEnabled??!1,this.blackbirdMetisIndexEnabled=n?.blackbirdMetisIndexEnabled??!1,this.sessionClient=n?.sessionClient,this.mcpEnvConfig=void 0}remoteEnabled;mcp3pEnabled;blackbirdMetisIndexEnabled;mcpEnvConfig;sessionClient;ReadMcpConfigFromEnv(e){this.mcpEnvConfig=process.env.GITHUB_COPILOT_MCP_JSON,this.mcp3pEnabled=process.env.GITHUB_COPILOT_3P_MCP_ENABLED==="true",this.remoteEnabled=process.env.GITHUB_COPILOT_REMOTE_MCP_ENABLED==="true",this.blackbirdMetisIndexEnabled=process.env.BLACKBIRD_METIS_INDEX_ENABLED==="true";let l=this.validateEnvConfig();return process.env.GITHUB_COPILOT_CLI_MODE==="true"?this.logger.log("CLI mode detected - skipping default MCP servers"):(this.logger.log("Adding default MCP servers to configuration"),this.configureBlackbirdMcp(l,e),this.configureGitHubMcp(l,e),this.configurePlaywrightMcp(l)),l}validateEnvConfig(){if(!this.mcp3pEnabled)return this.logger.log("User-provided MCPs are disabled"),DPe;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"),DPe;try{let e=JSON.parse(this.mcpEnvConfig);if(!e.mcpServers)throw new Error("User-provided config had incorrect format. Missing 'mcpServers' property.");for(let l in e.mcpServers)e.mcpServers[l].isDefaultServer=!1;return e}catch(e){return this.logger.error(`Warning: User-provided MCP servers were defined but invalid: ${e}`),DPe}}configureGitHubMcp(e,l){this.remoteEnabled?this.configureRemoteGitHubMcp(e,l):this.configureLocalGitHubMcp(e)}configureRemoteGitHubMcp(e,l){this.logger.log("Using default remote GitHub MCP server configuration");let n="repos,issues,users,pull_requests,code_security,secret_protection,actions,web_search";process.env.COPILOT_MCP_COPILOT_SPACES_ENABLED==="true"&&(this.logger.log("Enabling Copilot Spaces in GitHub MCP server configuration"),n=n+",copilot_spaces");let I={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":n,"X-MCP-Host":"github-coding-agent","X-Initiator":"agent"};l&&l.api?.copilot?.integrationId&&(I["Copilot-Integration-Id"]=l.api.copilot.integrationId),process.env.GITHUB_COPILOT_INTERACTION_ID&&(I["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let r={type:"http",url:this.getCapiMcpUrl(),headers:I,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[cK]=r}configureLocalGitHubMcp(e){if(e.mcpServers[cK]){this.logger.log("Using user-provided GitHub MCP server configuration");let l=e.mcpServers[cK]??{};dK(l)&&!l.command&&(e.mcpServers[cK]={...l,command:"./copilot-developer-action-main/github-mcp-server/github-mcp-server",isDefaultServer:!0},this.logger.log("Added default command to user-provided GitHub MCP server configuration"))}else{this.logger.log("Using default local GitHub MCP server configuration");let l={command:"./copilot-developer-action-main/github-mcp-server/github-mcp-server",args:["stdio","--read-only"],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",GITHUB_HOST:"GITHUB_SERVER_URL"},tools:["*"],isDefaultServer:!0};e.mcpServers[cK]=l}}configurePlaywrightMcp(e){if(!e.mcpServers[MPe]){if((process.env.COPILOT_FEATURE_FLAGS??"").split(",").map(n=>n.trim()).includes("copilot_swe_agent_playwright_use_firewall")){this.logger.log("Playwright MCP server is configured to use the firewall, skipping launch.");return}this.logger.log("Enabling Playwright MCP server");let l={command:"npx",args:[...ASe,"--allowed-origins","localhost;localhost:*;127.0.0.1;127.0.0.1:*"],tools:["*"],isDefaultServer:!0};e.mcpServers[MPe]=l}}configureBlackbirdMcp(e,l){this.remoteEnabled?this.configureRemoteBlackbirdMcp(e):this.blackbirdMetisIndexEnabled?this.configureLocalMetisBlackbirdMCP(e,l):this.configureLocalBlackbirdMcp(e)}configureLocalMetisBlackbirdMCP(e,l){this.logger.log("Using local Metis Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${l.blackbird?.mode}`);let n=process.env.AGENT_DIR||"/agent";this.logger.log(`Using agent directory: ${n}`);let I=[];l.blackbird?.mode==="tool"&&(I=["*"]),this.logger.log(`Using blackbird Metis server: ${l.blackbird?.mode}`);let r={command:`${n}/blackbird/mcp`,args:["serve","--index",`${n}/blackbird/metis`],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",COPILOT_API_HMAC_KEY:"CAPI_HMAC_KEY",MODEL_BASED_RETRIEVAL_TOKEN:"BLACKBIRD_AUTH_MODEL_BASED_RETRIEVAL_TOKEN",METIS_API_KEY:"BLACKBIRD_AUTH_METIS_API_KEY"},tools:I,isDefaultServer:!0};e.mcpServers[y9]=r}configureLocalBlackbirdMcp(e){this.logger.log("Using local Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let l=[];process.env.BLACKBIRD_MODE==="tool"&&(l=["*"]);let n={command:"./copilot-developer-action-main/blackbird-mcp-server/blackbird-mcp-server",args:["stdio"],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",CAPI_HOST:"COPILOT_API_URL"},tools:l,isDefaultServer:!0};e.mcpServers[y9]=n}configureRemoteBlackbirdMcp(e){this.logger.log("Using remote Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let l=[];process.env.BLACKBIRD_MODE==="tool"&&(l=["*"]);let n={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":"search_agent","X-MCP-Host":"github-coding-agent"};process.env.GITHUB_COPILOT_INTERACTION_ID&&(n["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let I={type:"http",url:this.getCapiMcpUrl(),headers:n,tools:l,isDefaultServer:!0};e.mcpServers[y9]=I}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 dK(e)||oce(e)||ice(e)||cce(e)}isValidLocalServerConfig(e){return e.command!==void 0&&e.command.trim()!==""&&Array.isArray(e.args)}isValidRemoteServerConfig(e){return e.url!==void 0&&e.url.trim()!==""}isValidInMemoryServerConfig(e){return e.serverInstance!==void 0&&typeof e.serverInstance=="object"}validateServerConfig(e,l){return this.remoteEnabled&&!this.isValidServerType(l)?(this.logger.error(`Unsupported server type "${l.type}" for server "${e}". Only "Local", "STDIO", "HTTP", "SSE", or "Memory" are supported.`),!1):!this.remoteEnabled&&!dK(l)&&!cce(l)?(this.logger.error(`Unsupported server type "${l.type}" for server "${e}". Only "Local", "STDIO", or "Memory" are supported.`),!1):l.tools?dK(l)&&!this.isValidLocalServerConfig(l)?(this.logger.error(`Invalid local server configuration for "${e}". Please ensure 'command' and 'args' are provided.`),!1):(oce(l)||ice(l))&&!this.isValidRemoteServerConfig(l)?(this.logger.error(`Invalid remote server configuration for "${e}". Please ensure 'url' is provided.`),!1):cce(l)&&!this.isValidInMemoryServerConfig(l)?(this.logger.error(`Invalid in-memory server configuration for "${e}". Please ensure 'serverInstance' is provided and is an instance of MCPServer.`),!1):!0:(this.logger.error(`No tools specified for server "${e}". Please provide a list of tools or "*" to include all tools.`),!1)}async processHttpServer(e,l){try{let n=this.resolveHeaders(l.headers,process.env),I={...l,headers:n};await this.registry.startHttpMcpClient(e,I),this.logger.log(`Started MCP client for remote server ${e}`)}catch(n){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${n}`),n}}async processSseServer(e,l){try{let n=this.resolveRemoteServerConfig(l);await this.registry.startSseMcpClient(e,n),this.logger.log(`Started MCP client for remote server ${e}`)}catch(n){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${n}`),n}}resolveRemoteServerConfig(e){return e.url=this.resolveString(e.url,process.env),e.headers=this.resolveHeaders(e.headers,process.env),{...e,url:e.url,headers:e.headers}}async processInMemoryServer(e,l){try{await this.registry.startInMemoryMcpClient(e,l.serverInstance),this.logger.log(`Started in-memory MCP client for ${e}`)}catch(n){throw this.logger.error(`Failed to start in-memory MCP client for ${e}: ${n}`),n}}async processLocalServer(e,l){let n={...l};if(l.command==="python")try{n=await this.convertPythonToPipx(n)}catch(a){this.logger.error(`Failed to handle Python module for ${e}: ${a}`)}let I=this.buildEnvironment(n),r=this.resolveLocalServerConfig(n,I);this.logger.log(`Starting MCP client for ${e} with command: ${r.command} and args: ${r.args}`);try{await this.registry.startLocalMcpClient(e,I,r.command,r.args),this.logger.log(`Started MCP client for ${e}`)}catch(a){throw this.logger.error(`Failed to start MCP client for ${e}: ${a}`),a}}convertPythonToPipx(e){if(!e||!e.args||e.args.length===0)return e;let l=e.args,n=l.indexOf("-m");if(n===-1||n===l.length-1)throw new Error("Python command with -m flag must specify a module");let I=l[n+1];this.logger.log(`Converting Python module: ${I} to pipx command`);let r=["run",I];for(let a=n+2;a<l.length;a++)r.push(l[a]);for(let a=0;a<n;a++)r.push(l[a]);return{...e,command:"pipx",args:r}}buildEnvironment(e){let l={};if(e.env)for(let[n,I]of Object.entries(e.env)){let r=I.trim();process.env[r]!==void 0&&(l[n]=process.env[r])}return l}resolveLocalServerConfig(e,l){let n=this.resolveString(e.command,l),I=this.resolveArray(e.args,l);return{...e,command:n,args:I}}resolveString(e,l){return l?e.replace(/\$(?:\{([A-Z0-9_]+)(?::-(.*?))?\}|([A-Z0-9_]+))/g,(n,I,r,a)=>{let o=l[I||a];return o!==void 0?o:r!==void 0?r:n}):e}resolveArray(e,l){return e?l?e.map(n=>this.resolveString(n,l)):e:[]}resolveHeaders(e,l){if(!e)return{};if(!l)return e;let n={};for(let[I,r]of Object.entries(e)){let a=this.resolveArray([r],l);n[I]=a[0]}return n}async processServers(e){if(!e)throw new Error("No servers to process");let l=Object.entries(e.mcpServers).map(([n,I])=>this.processServer(n,I));await Promise.all(l)}async processServer(e,l){if(!this.validateServerConfig(e,l)){this.logger.error(`Skipping server "${e}" due to invalid configuration.`);return}try{dK(l)?await this.processLocalServer(e,l):oce(l)&&this.remoteEnabled?await this.processHttpServer(e,l):ice(l)&&this.remoteEnabled?await this.processSseServer(e,l):cce(l)&&await this.processInMemoryServer(e,l)}catch(n){e!==y9&&await this.logServerFailure(e,n)}}async logServerFailure(e,l){if(this.sessionClient)try{await this.sessionClient.logMCPSetup(e,`<error>MCP server failed to start: ${l.message} - for the full output, see the verbose logs</error>`)}catch(n){this.logger.error(`Failed to log failure for MCP Server '${e}': '${n}'`)}}};var x2e=class{constructor(e,l,n){this.logger=e;let I;if(typeof l=="string"){if(I=JSON.parse(l),typeof I!="object")throw new Error("Invalid MCP configuration: must be an object");if(I===null||!("mcpServers"in I)||typeof I.mcpServers!="object")throw new Error("Invalid MCP configuration: missing or invalid mcpServers property");this.config=I}else this.config=l;this.disabledServers=new Set(n||[]),this.registry=new J2e(this.logger),this.processor=new B2e(this.logger,this.registry,{mcp3pEnabled:!0,remoteEnabled:!0})}registry;processor;config;startServersPromise=null;allTools=null;disabledServers;async startServers(){return this.startServersPromise||(this.startServersPromise=this.processServersWithExtensions()),this.startServersPromise}async injectDefaultServers(e){}async processServersWithExtensions(){await this.injectDefaultServers(this.config);let e;if(this.disabledServers.size>0){let l={};for(let[n,I]of Object.entries(this.config.mcpServers))this.disabledServers.has(n)?this.logger.log(`Skipping disabled MCP server: ${n}`):l[n]=I;e={...this.config,mcpServers:l}}else e=this.config;return this.processor.processServers(e)}async stopServers(){for(let[e,l]of Object.entries(this.registry.transports))try{await l.close()}catch(n){this.logger.error(`Error closing transport for ${e}: ${n}`)}this.startServersPromise=null,this.allTools=null}async getTools(e,l,n){if(!this.allTools){await this.startServers();let I=new hre(e,l,n),r=[];for(let a of Object.keys(this.registry.clients)){let s=await I.loadTools({mcpClient:this.registry.clients[a],clientName:a,tools:this.config.mcpServers[a]?.tools||["*"],filterMapping:this.config.mcpServers[a]?.filterMapping||"hidden_characters"});r.push(...s)}this.allTools=r}return this.allTools}getConfig(){return this.config}async startServer(e,l){await this.startServers(),this.config.mcpServers[e]=l,await this.processor.processServer(e,l),this.allTools=null}async stopServer(e){let l=this.registry.transports[e];if(l)try{await l.close(),delete this.registry.transports[e]}catch(n){this.logger.error(`Error closing transport for ${e}: ${n}`)}this.registry.clients[e]&&delete this.registry.clients[e],this.allTools=null}async restartServer(e,l){this.isServerRunning(e)&&await this.stopServer(e),delete this.config.mcpServers[e],await this.startServer(e,l)}isServerRunning(e){return e in this.registry.transports&&e in this.registry.clients}isServerDisabled(e){return this.disabledServers.has(e)}async disableServer(e){if(this.disabledServers.has(e)){this.logger.log(`Server ${e} is already disabled`);return}this.disabledServers.add(e),this.logger.log(`Disabled server ${e} for this session`),this.isServerRunning(e)&&await this.stopServer(e),this.allTools=null}async enableServer(e){if(!this.disabledServers.has(e)){this.logger.log(`Server ${e} is not disabled`);return}this.disabledServers.delete(e),this.logger.log(`Enabled server ${e} for this session`);let l=this.getServerConfig(e);l?await this.startServer(e,l):await this.startBuiltInServer(e),this.allTools=null}async startBuiltInServer(e){}getServerConfig(e){return this.config.mcpServers[e]}};c();var npn="/login/device/code",Ipn="/login/oauth/access_token",XBt="Ov23ctDVkRmgkPke0Mmm",N2="https://github.com",Ak=class extends Error{constructor(l,n){super(n);this.status=l;this.message=n;this.name="GitHubApiError"}};function kBt(t){let e=new URL(t);return e.hostname.startsWith("api.")||(e.hostname="api."+e.hostname),e.href}async function LBt(t){let e=new URL(npn,t),l=await fetch(e.href,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({client_id:XBt,scope:"user:email,read:user,repo,workflow"})});if(!l.ok)throw new Ak(l.status,`Failed to request device code: ${l.statusText}`);return await l.json()}async function JBt(t,e){let l=new URL(Ipn,t),n=await fetch(l.href,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({client_id:XBt,device_code:e,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})});if(!n.ok)throw new Ak(n.status,`Failed to authorize: ${n.statusText}`);let I=await n.json();if(typeof I.access_token=="string")return I.access_token;if(I.error!=="authorization_pending"&&I.error!=="slow_down")throw new Error(I.error_description||`Unexpected error: ${I.error}`)}async function mK(t,e){let l=new URL("/user",kBt(t)),n=await fetch(l.href,{headers:{Authorization:`Bearer ${e}`,Accept:"application/json"}});if(!n.ok)throw new Ak(n.status,`Failed to fetch user info: ${n.statusText}`);return(await n.json()).login}async function GK(t,e){let l=`
1895
1895
  {
1896
1896
  viewer {
1897
1897
  copilotEndpoints {
@@ -1900,7 +1900,7 @@ ${r}`;await I.logMCPSetup(e,s),this.logger.log(`Updated session log for ${e} wit
1900
1900
  }
1901
1901
  }
1902
1902
  `,n=new URL("/graphql",kBt(t)),I=await fetch(n.href,{method:"POST",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},body:JSON.stringify({query:l})});if(!I.ok)throw new Error(`Failed to fetch Copilot info: ${I.statusText}`);let r=await I.json(),{viewer:a}=r.data;return a.copilotEndpoints.api}c();c();var Qxt=dt(Axt(),1);c();function V9(){return process.env.COPILOT_ENABLE_ALT_PROVIDERS==="true"}var Nk=["claude-sonnet-4.5","claude-sonnet-4","gpt-5"];function oje(t){return Nk.includes(t)||V9()}function ije(t,e){if(!e)return!0;let l=e.find(n=>n.id===t);return l?l.policy?l.policy.state!=="disabled":!0:!1}function lYe(t){let e=Nk.find(l=>ije(l,t));if(!e)throw new Error("No supported model available");return e}async function Q9(t,e,l){if(V9()&&process.env.COPILOT_AGENT_MODEL){let{model:n}=bP(process.env.COPILOT_AGENT_MODEL);if(n)return n}if(t)return t;if(e){let n=e.getSelectedModel();if(n)return n}if(process.env.COPILOT_MODEL&&oje(process.env.COPILOT_MODEL))return process.env.COPILOT_MODEL;try{let I=(await xr.load()||{}).model;if(I&&oje(I))return I}catch{}return lYe(l)}function Zxt(t,e,l){if(V9()&&process.env.COPILOT_AGENT_MODEL){let{model:n}=bP(process.env.COPILOT_AGENT_MODEL);if(n)return n}if(t)return t;if(e){let n=e.getSelectedModel();if(n)return n}return process.env.COPILOT_MODEL&&oje(process.env.COPILOT_MODEL)?process.env.COPILOT_MODEL:lYe(l)}c();import{existsSync as dje}from"fs";import{appendFile as Uaa,mkdir as Khn,readdir as qhn,readFile as $hn,stat as eAn,writeFile as tAn}from"fs/promises";import{homedir as lAn}from"os";import{dirname as nAn,join as Gce}from"path";c();c();var _hn=new Error("timeout while waiting for mutex to become available"),kaa=new Error("mutex already locked"),Dhn=new Error("request for lock canceled"),zhn=function(t,e,l,n){function I(r){return r instanceof l?r:new l(function(a){a(r)})}return new(l||(l=Promise))(function(r,a){function s(u){try{d(n.next(u))}catch(G){a(G)}}function o(u){try{d(n.throw(u))}catch(G){a(G)}}function d(u){u.done?r(u.value):I(u.value).then(s,o)}d((n=n.apply(t,e||[])).next())})},cje=class{constructor(e,l=Dhn){this._value=e,this._cancelError=l,this._queue=[],this._weightedWaiters=[]}acquire(e=1,l=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((n,I)=>{let r={resolve:n,reject:I,weight:e,priority:l},a=Nxt(this._queue,s=>l<=s.priority);a===-1&&e<=this._value?this._dispatchItem(r):this._queue.splice(a+1,0,r)})}runExclusive(e){return zhn(this,arguments,void 0,function*(l,n=1,I=0){let[r,a]=yield this.acquire(n,I);try{return yield l(r)}finally{a()}})}waitForUnlock(e=1,l=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,l)?Promise.resolve():new Promise(n=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),Phn(this._weightedWaiters[e-1],{resolve:n,priority:l})})}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 l=this._value;this._value-=e.weight,e.resolve([l,this._newReleaser(e.weight)])}_newReleaser(e){let l=!1;return()=>{l||(l=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){let l=this._weightedWaiters[e-1];l&&(l.forEach(n=>n.resolve()),this._weightedWaiters[e-1]=[])}else{let e=this._queue[0].priority;for(let l=this._value;l>0;l--){let n=this._weightedWaiters[l-1];if(!n)continue;let I=n.findIndex(r=>r.priority<=e);(I===-1?n:n.splice(0,I)).forEach(r=>r.resolve())}}}_couldLockImmediately(e,l){return(this._queue.length===0||this._queue[0].priority<l)&&e<=this._value}};function Phn(t,e){let l=Nxt(t,n=>e.priority<=n.priority);t.splice(l+1,0,e)}function Nxt(t,e){for(let l=t.length-1;l>=0;l--)if(e(t[l]))return l;return-1}var jhn=function(t,e,l,n){function I(r){return r instanceof l?r:new l(function(a){a(r)})}return new(l||(l=Promise))(function(r,a){function s(u){try{d(n.next(u))}catch(G){a(G)}}function o(u){try{d(n.throw(u))}catch(G){a(G)}}function d(u){u.done?r(u.value):I(u.value).then(s,o)}d((n=n.apply(t,e||[])).next())})},IYe=class{constructor(e){this._semaphore=new cje(1,e)}acquire(){return jhn(this,arguments,void 0,function*(e=0){let[,l]=yield this._semaphore.acquire(1,e);return l})}runExclusive(e,l=0){return this._semaphore.runExclusive(()=>e(),1,l)}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()}},gxt=function(t,e,l,n){function I(r){return r instanceof l?r:new l(function(a){a(r)})}return new(l||(l=Promise))(function(r,a){function s(u){try{d(n.next(u))}catch(G){a(G)}}function o(u){try{d(n.throw(u))}catch(G){a(G)}}function d(u){u.done?r(u.value):I(u.value).then(s,o)}d((n=n.apply(t,e||[])).next())})};function Wxt(t,e,l=_hn){return{acquire:(n,I)=>{let r;if(nYe(t)?r=n:(r=void 0,I=n),r!==void 0&&r<=0)throw new Error(`invalid weight ${r}: must be positive`);return new Promise((a,s)=>gxt(this,void 0,void 0,function*(){let o=!1,d=setTimeout(()=>{o=!0,s(l)},e);try{let u=yield nYe(t)?t.acquire(r,I):t.acquire(I);o?(Array.isArray(u)?u[1]:u)():(clearTimeout(d),a(u))}catch(u){o||(clearTimeout(d),s(u))}}))},runExclusive(n,I,r){return gxt(this,void 0,void 0,function*(){let a=()=>{};try{let s=yield this.acquire(I,r);return Array.isArray(s)?(a=s[1],yield n(s[0])):(a=s,yield n())}finally{a()}})},release(n){t.release(n)},cancel(){return t.cancel()},waitForUnlock:(n,I)=>{let r;if(nYe(t)?r=n:(r=void 0,I=n),r!==void 0&&r<=0)throw new Error(`invalid weight ${r}: must be positive`);return new Promise((a,s)=>{let o=setTimeout(()=>s(l),e);(nYe(t)?t.waitForUnlock(r,I):t.waitForUnlock(I)).then(()=>{clearTimeout(o),a()})})},isLocked:()=>t.isLocked(),getValue:()=>t.getValue(),setValue:n=>t.setValue(n)}}function nYe(t){return t.getValue!==void 0}var rYe=class{mutexes=new Map;async runExclusive(e,l,n=5e3){let I=this.mutexes.get(e);I||(I=new IYe,I.refCount=0,this.mutexes.set(e,I));let r=I;try{return r.refCount++,await Wxt(I,n).runExclusive(l)}finally{--r.refCount===0&&this.mutexes.delete(e)}}};var aYe=(l=>(l.DEFAULT="config",l.MCP="mcp",l))(aYe||{});function yxt(t){return Object.values(aYe).includes(t)}var Ext=".copilot",Rxt=new rYe;async function IAn(t){let e=nAn(t);try{await Khn(e,{recursive:!0,mode:448})}catch{}}async function rAn(t,e){if(dje(t))try{let l={},n=await Rxt.runExclusive(t,()=>$hn(t,"utf8"));return n.trim().startsWith("{")?l=JSON.parse(n):n.split(`
1903
- `).forEach(I=>{let[r,a]=I.split("=").map(s=>s.trim());r&&a&&(l[r]=a)}),e(l)}catch(l){throw new Error(`Failed to read configuration from ${t}: ${l}`)}}async function aAn(t,e){try{await IAn(t);let l=JSON.stringify(e,null,2);await Rxt.runExclusive(t,()=>tAn(t,l,{mode:384}))}catch(l){throw new Error(`Failed to write configuration to ${t}: ${l}`)}}var Yxt=(t,e,{shouldCache:l})=>{let n=new Map,I=()=>{let G=yxt(e)?process.env.XDG_CONFIG_HOME:process.env.XDG_STATE_HOME;return G?Gce(G,Ext):Gce(lAn(),Ext)},r=()=>{let G=yxt(e)?"-config":"-state";return`${e}${e=="config"?"":G}`},a=G=>{let p=".json",h=r()+(G?"":p),W=Gce(I(),h,G?`${G}${p}`:"");return!dje(W)&&dje(W.replace(/\.json$/,""))&&(W=W.replace(/\.json$/,"")),W},s=async()=>{let G=Gce(I(),r());try{let h=(await qhn(G)).filter(y=>y.endsWith(".json")),W=await Promise.all(h.map(async y=>{let R=Gce(G,y);try{let w=await eAn(R);return{file:y,mtime:w.mtime}}catch{return{file:y,mtime:new Date}}}));return W.sort((y,R)=>R.mtime.getTime()-y.mtime.getTime()),W.map(y=>y.file)}catch{}return[]},o=async(G="")=>{if(l&&n.has(G))return n.get(G);let p=await rAn(a(G),t);return l&&p&&n.set(G,p),p},d=async(G,p="")=>{l&&n.set(p,G),await aAn(a(p),G)};return{load:o,write:d,writeKey:async(G,p,h)=>{let W=await o(h);if(p===void 0){W&&(delete W[G],await d(W,h));return}let y={[G]:p},R;W?R={...W,...y}:R=y,await d(R,h)},path:a,directoryFiles:s}},sYe=(t,e)=>Yxt(t,e,{shouldCache:!0}),oYe=(t,e)=>Yxt(t,e,{shouldCache:!1});var Vxt=JI({host:kl(),login:kl()}),sAn=JI({banner:b2(["always","once","never"]).optional(),beep:Gu().optional(),last_logged_in_user:Vxt.optional(),logged_in_users:Wb(Vxt).optional(),model:b2(Nk).optional(),render_markdown:Gu().optional(),screen_reader:Gu().optional(),theme:kl().optional(),trusted_folders:Wb(kl()).optional(),store_token_plaintext:Gu().optional(),capi_hmac_key:kl().optional(),copilot_hmac_key:kl().optional(),copilot_integration_id:kl().optional(),copilot_tokens:Gv(kl(),kl()).optional(),copilot_url:kl().optional()}),oAn=Gv(kl(),ADe()),iAn=oAn.transform(t=>(0,Qxt.default)(t,(e,l)=>{let n=l.toLowerCase();return n==="github_copilot_integration_id"?"copilot_integration_id":n})),cAn=iAn.pipe(sAn),xr=sYe(cAn.parse,"config");c();function iYe(t){return Yv(t,{onHMACAuthInfo:()=>"Logged in with HMAC",onEnvAuthInfo:e=>`Logged in with ${e.envVar} as user: ${e.login}`,onUserAuthInfo:e=>`Logged in as user: ${bce(e)}`,onGhCliAuthInfo:e=>`Logged in with gh as user: ${bce(e)}`,onApiKeyAuthInfo:e=>`Logged in with API key to ${e.host}`})}function pce(t){return Yv(t,{onHMACAuthInfo:()=>"Unknown (via HMAC)",onEnvAuthInfo:e=>`${e.login} (via ${e.envVar})`,onUserAuthInfo:e=>bce(e),onGhCliAuthInfo:e=>`${e.login} (via gh)`,onApiKeyAuthInfo:e=>`${e.host} (via API key)`})}function uje(t,e){return Yv(t,{onHMACAuthInfo:l=>e.type==="hmac"&&l.hmac===e.hmac,onEnvAuthInfo:l=>e.type==="env"&&l.envVar===e.envVar&&l.login===e.login,onUserAuthInfo:l=>e.type==="user"&&w9(l,e),onGhCliAuthInfo:l=>e.type==="gh-cli"&&w9(l,e),onApiKeyAuthInfo:l=>e.type==="api-key"&&l.host===e.host&&l.apiKey===e.apiKey})}async function wxt(t,e){let l=await t.getAllAuthAvailable(),n=">",I="-";return l.map(r=>`${e&&uje(r.authInfo,e)?n:I} ${pce(r.authInfo)}`)}function bce(t){return t.host!==N2?`${t.login} (${t.host})`:t.login}async function Fxt(){let t=await xr.load()||{};return t?.last_logged_in_user??t.logged_in_users?.[0]??void 0}async function mje(t){await xr.writeKey("last_logged_in_user",t)}async function cYe(){return(await xr.load()||{}).logged_in_users||[]}async function Cxt(t,e){await xr.writeKey("last_logged_in_user",t),await xr.writeKey("logged_in_users",e)}async function vxt(t){let e=await cYe();return e.some(n=>w9(n,t))?(e=e.filter(n=>!w9(n,t)),await Cxt(void 0,e),e.length>0):!1}async function fxt(t){let e=await cYe();e.some(n=>w9(n,t))||(e.push(t),await Cxt(t,e))}function w9(t,e){return t.login===e.login&&t.host===e.host}c();async function Hxt(t,e){try{let l=await e.execReturn("gh",["auth","token","--hostname","github.com"],{silent:!0,ignoreReturnCode:!0});if(l.exitCode!==0||!l.stdout.trim()){let I=`Failed to retrieve GitHub token from CLI (exit code: ${l.exitCode})`,r=l.stderr?.trim();return r?t.debug(`${I}: ${r}`):t.debug(I),null}let n=l.stdout.trim();return n.startsWith("ghp_")?(t.debug("GitHub token is a classic PAT"),null):(t.debug("GitHub CLI authenticated with valid token"),n)}catch(l){let n=`Error checking GitHub CLI: ${l}`;return l&&typeof l=="object"&&"stderr"in l&&typeof l.stderr=="string"&&(n+=` (stderr: ${l.stderr.trim()})`),t.debug(n),null}}c();import{existsSync as Xxt}from"fs";var dYe="copilot-cli",uYe;async function mYe(){if(uYe)return uYe;let t=await import("keytar-forked-forked");return uYe=t.default||t,uYe}var hce=(t,e)=>{if(!(!t||!e))return`${t}:${e}`},dAn=()=>{let t=new Map,e=async(o,d)=>{let u=hce(o,d);if(u)if(Xxt(xr.path()))try{let h=(await xr.load())?.copilot_tokens?.[u];t.set(u,h&&h.trim()!==""?h:void 0)}catch{t.set(u,void 0)}else t.set(u,void 0)},l=async()=>{if(Xxt(xr.path()))try{let d=(await xr.load())?.copilot_tokens;if(d){let u=Object.values(d).filter(G=>G&&G.trim()!=="");if(u.length>0)return u[0]}}catch{return}},n=async(o,d)=>{let u=hce(o,d);if(!u)return;if(t.has(u))return t.get(u);if((await xr.load())?.store_token_plaintext)return await e(o,d),t.get(u);try{let h=await(await mYe()).getPassword(dYe,u);h?t.set(u,h):await e(o,d)}catch{await e(o,d)}return t.get(u)},I=async()=>{if(t.size>0)return t.values().next().value;if((await xr.load())?.store_token_plaintext)return await l();let d;try{d=await(await mYe()).findPassword(dYe)}catch{}return d||(d=await l()),d},r=async(o,d)=>{let u=hce(o,d);if(u){t.delete(u);try{return(await mYe()).deletePassword(dYe,u)}catch{let h=(await xr.load())?.copilot_tokens??{};return delete h[u],await xr.writeKey("copilot_tokens",h),Promise.resolve(!0)}}},a=async(o,d,u)=>{if(!o)throw new Error("No token provided to store");let G=hce(d,u);if(!G)return;if(t.set(G,o),(await xr.load())?.store_token_plaintext)return await s(d,u),!0;try{return await(await mYe()).setPassword(dYe,G,o),!0}catch{return!1}},s=async(o,d)=>{let u=hce(o,d);if(!u)return;let G=t.get(u);if(!G)return;let h=(await xr.load())?.copilot_tokens??{};h[u]=G,await xr.writeKey("copilot_tokens",h)};return{getToken:n,getAnyToken:I,removeToken:r,storeToken:a,storeCurrentTokenInConfig:s}},Vv=dAn();function Yv(t,e){switch(t.type){case"hmac":return e.onHMACAuthInfo(t);case"env":return e.onEnvAuthInfo(t);case"user":return e.onUserAuthInfo(t);case"gh-cli":return e.onGhCliAuthInfo(t);case"api-key":return e.onApiKeyAuthInfo(t);default:{let l=t;throw new Error(`unexpected auth info type: ${JSON.stringify(t)}`)}}}async function gK(t){return await Yv(t,{onHMACAuthInfo:async()=>{},onEnvAuthInfo:async e=>e.token,onUserAuthInfo:async e=>await Vv.getToken(e.host,e.login)||void 0,onGhCliAuthInfo:async e=>e.token,onApiKeyAuthInfo:async()=>{}})}var Gje=class{currentAuthInfo=null;logger=new XA;authCallbacks=[];setLogger(e){this.logger=e}onAuthChange(e){this.authCallbacks.push(e)}removeAuthCallback(e){let l=this.authCallbacks.indexOf(e);l>-1&&this.authCallbacks.splice(l,1)}async notifyAuthChange(e,l){this.currentAuthInfo=e;for(let n of this.authCallbacks)try{await n(e,l)}catch(I){this.logger.error(`Error in auth change callback: ${I}`)}}async tryHMACLogin(){let e=await xr.load()||{},l=e.copilot_hmac_key||e.capi_hmac_key||process.env.CAPI_HMAC_KEY||process.env.COPILOT_HMAC_KEY;return l?[{authInfo:{type:"hmac",hmac:l}}]:[]}async tryGitHubTokenLogin(){let e=process.env.GH_TOKEN||process.env.GITHUB_TOKEN;if(!e)return[];if(e.startsWith("ghp_"))return this.logger.error("Classic PATs are not supported. Please use fine-grained PATs or other supported token types."),[];if(!e.startsWith("gho_")&&!e.startsWith("ghu_")&&!e.startsWith("github_pat_"))return this.logger.error("Unsupported token type, ignoring."),[];try{let l=await mK(N2,e);return[{authInfo:{type:"env",host:N2,login:l,token:e,envVar:process.env.GH_TOKEN?"GH_TOKEN":"GITHUB_TOKEN"},token:e}]}catch(l){l instanceof Ak?this.logger.error(`Failed to fetch PAT user login (${l.status}): ${l.message}`):this.logger.error("Failed to fetch PAT user login")}return[]}async tryGhCliTokenLogin(){let e=new aR(this.logger),l=await Hxt(this.logger,e);if(!l)return[];try{let n=await mK(N2,l);return[{authInfo:{type:"gh-cli",host:N2,login:n,token:l},token:l}]}catch(n){n instanceof Ak?this.logger.error(`Failed to fetch GitHub CLI user login (${n.status}): ${n.message}`):this.logger.error("Failed to fetch GitHub CLI user login")}return[]}async tryApiKeyLogin(){if(!V9())return[];let e=process.env.ANTHROPIC_API_KEY||process.env.AZURE_OPENAI_API_KEY,l=process.env.ANTHROPIC_API_KEY?"https://api.anthropic.com":process.env.AZURE_OPENAI_API_KEY?process.env.AZURE_OPENAI_API_ENDPOINT||process.env.OPENAI_BASE_URL||"https://api.openai.com":void 0;return!e||!l?[]:[{authInfo:{type:"api-key",apiKey:e,host:l}}]}async tryLoginToken(){let e=await Fxt(),l;if(e){if(l=await Vv.getToken(e.host,e.login),!l||l.trim()==="")return[]}else{if(l=await Vv.getAnyToken(),!l||l.trim()==="")return[];e={host:N2,login:await mK(N2,l)}}return[{authInfo:{type:"user",host:e.host,login:e.login},token:l}]}async getAllGitHubLoginTokens(){let l=(await this.tryGitHubTokenLogin()).at(0),n=await cYe(),I=[];for(let r of n){if(l?.authInfo.type==="user"&&w9(r,l.authInfo))continue;let a=await Vv.getToken(r.host,r.login);a&&I.push({authInfo:{type:"user",host:r.host,login:r.login},token:a})}return I}async getAllAuthAvailable(){let e=[],l=this.getPrioritizedAuthMethods(!0);for(let n of l){let I=await n();e.push(...I)}return e}getPrioritizedAuthMethods(e){return[this.tryHMACLogin.bind(this),this.tryApiKeyLogin.bind(this),this.tryGitHubTokenLogin.bind(this),e?this.getAllGitHubLoginTokens.bind(this):this.tryLoginToken.bind(this),this.tryGhCliTokenLogin.bind(this)]}async loadAuthInfo(){let e=this.currentAuthInfo!==null;this.currentAuthInfo=null;let l=this.getPrioritizedAuthMethods(!1);for(let n of l){let I=await n();if(I.length>0){let{authInfo:r,token:a}=I[0];r.type==="user"&&mje({host:r.host,login:r.login}),this.currentAuthInfo=r,e||await this.notifyAuthChange(r,a);return}}}async getCurrentAuthInfo(){return this.currentAuthInfo||await this.loadAuthInfo(),this.currentAuthInfo}async loginUser(e,l){let n={host:e,login:l},I={type:"user",...n};await fxt(n);let r=await gK(I);await this.notifyAuthChange(I,r)}async switchToAuth(e){this.currentAuthInfo=e.authInfo,e.authInfo.type==="user"&&await mje({host:e.authInfo.host,login:e.authInfo.login}),await this.notifyAuthChange(e.authInfo,e.token)}async logout(){if(!this.currentAuthInfo)return!1;let e=await Yv(this.currentAuthInfo,{onHMACAuthInfo:async()=>!1,onEnvAuthInfo:async()=>!1,onUserAuthInfo:async l=>(await Vv.removeToken(l.host,l.login),await vxt(l)),onGhCliAuthInfo:async()=>!1,onApiKeyAuthInfo:async()=>!1});return await this.notifyAuthChange(null),e}},uAn=new Gje,GYe=uAn;var NK=class t extends x2e{constructor(l,n,I,r){super(l,n,r);this.exec=I}static GITHUB_SERVER_NAME="github-mcp-server";hasUserConfiguredGitHubServer=!1;lastGitHubAuthInfo=null;lastGitHubToken=null;githubMcpToken;async configureGitHubAuth(l,n){if(this.lastGitHubAuthInfo=l,this.lastGitHubToken=n,this.isServerDisabled(t.GITHUB_SERVER_NAME))return this.logger.debug("GitHub MCP server is disabled, skipping auto-configuration"),!1;if(this.hasUserConfiguredGitHubServer)return this.logger.debug("User has explicitly configured github-mcp-server, ignoring auth changes"),!1;if(await this.shouldHandleGitHubAuth(l)&&n){if(n===this.githubMcpToken)return!1;this.githubMcpToken=n;let r=await this.createGitHubServerConfig(n,l);try{return await this.restartServer(t.GITHUB_SERVER_NAME,r),this.logger.log("GitHub MCP server configured after authentication"),!0}catch(a){return this.logger.error(`Failed to configure GitHub MCP server after auth: ${a}`),!1}}return!1}async removeGitHubAuth(){if(this.hasUserConfiguredGitHubServer)return this.logger.debug("User has explicitly configured github-mcp-server, ignoring auth changes"),!1;this.githubMcpToken=void 0;try{return this.isServerRunning(t.GITHUB_SERVER_NAME)?(await this.stopServer(t.GITHUB_SERVER_NAME),this.logger.debug("Removed GitHub MCP server"),!0):!1}catch(l){return this.logger.error(`Failed to remove GitHub server: ${l}`),!1}}async shouldHandleGitHubAuth(l){return await Yv(l,{onHMACAuthInfo:async()=>!1,onEnvAuthInfo:async()=>!0,onUserAuthInfo:async()=>!0,onGhCliAuthInfo:async()=>!0,onApiKeyAuthInfo:async()=>!1})}async createGitHubServerConfig(l,n){let I="https://api.githubcopilot.com/mcp/readonly";try{let r=await Yv(n,{onHMACAuthInfo:async()=>"https://github.com",onEnvAuthInfo:async s=>s.host,onUserAuthInfo:async s=>s.host,onGhCliAuthInfo:async s=>s.host,onApiKeyAuthInfo:async s=>s.host}),a=await GK(r,l);I=new URL("/mcp/readonly",a).toString(),this.logger.log(`Using Copilot API endpoint: ${I}`)}catch(r){this.logger.error(`Failed to fetch Copilot URL, using default: ${r}`)}return{type:"http",url:I,headers:{Authorization:"Bearer "+l,"X-MCP-Toolsets":"repos,issues,users,pull_requests,code_security,secret_protection,actions,bing_search","X-MCP-Host":"copilot-cli"},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"}}}async injectDefaultServers(l){if(l.mcpServers[t.GITHUB_SERVER_NAME]){this.hasUserConfiguredGitHubServer=!0,this.logger.debug("User has already configured github-mcp-server, skipping auto-configuration");return}}async startBuiltInServer(l){l===t.GITHUB_SERVER_NAME&&!this.hasUserConfiguredGitHubServer?this.lastGitHubAuthInfo&&this.lastGitHubToken?(this.logger.log("Attempting to configure GitHub MCP server using stored authentication"),await this.configureGitHubAuth(this.lastGitHubAuthInfo,this.lastGitHubToken)?this.logger.log("GitHub MCP server configured successfully after enabling"):this.logger.log("GitHub MCP server enabled but could not be configured - authentication may be invalid or insufficient")):this.logger.log("GitHub MCP server enabled - will be configured automatically when authentication becomes available"):await super.startBuiltInServer(l)}};c();c();var GAn=JI({commandHistory:Wb(kl())}),bje=oYe(GAn.parse,"command-history");var bAn=50,pje=class{commandHistory=[];historyIndex=-1;isNavigatingHistory=!1;unSubmittedCommand=null;async initialize(){try{let e=await bje.load();this.commandHistory=e?.commandHistory||[],this.resetNavigation()}catch{this.commandHistory=[]}}async addCommand(e){this.commandHistory=this.commandHistory.filter(l=>l!==e),this.commandHistory.unshift(e),this.commandHistory=this.commandHistory.slice(0,bAn),this.resetNavigation(),this.unSubmittedCommand=null,await this.saveHistory()}async updateCurrentCommand(e){this.historyIndex!==-1?(this.commandHistory[this.historyIndex]=e,await this.saveHistory()):this.unSubmittedCommand=e}navigateUp(e){if(this.commandHistory.length===0)return;let l=this.historyIndex+1;if(l<this.commandHistory.length){this.historyIndex=l,this.isNavigatingHistory=!0;let n=this.getCurrentHistoryItem();n&&e.setText(n)}}navigateDown(e){if(this.historyIndex===-1)return;if(this.historyIndex===0)this.resetNavigation();else{let n=this.historyIndex-1;this.historyIndex=n,this.isNavigatingHistory=!0}let l=this.getCurrentHistoryItem();l?(e.setText(l),e.setCursorPosition(0)):e.clear()}resetNavigation(){this.historyIndex=-1,this.isNavigatingHistory=!1}getHistoryIndex(){return this.historyIndex}getHistory(){return this.commandHistory}getCurrentHistoryItem(){return this.historyIndex===-1?this.unSubmittedCommand?this.unSubmittedCommand:void 0:this.commandHistory[this.historyIndex]}isNavigating(){return this.isNavigatingHistory}setNavigating(e){this.isNavigatingHistory=e}async saveHistory(){try{await bje.write({commandHistory:this.commandHistory})}catch{}}},W2=new pje;c();c();function kxt(t,e){var l=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(I){return Object.getOwnPropertyDescriptor(t,I).enumerable})),l.push.apply(l,n)}return l}function Lxt(t){for(var e=1;e<arguments.length;e++){var l=arguments[e]!=null?arguments[e]:{};e%2?kxt(Object(l),!0).forEach(function(n){pAn(t,n,l[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(l)):kxt(Object(l)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(l,n))})}return t}function pAn(t,e,l){return e=hAn(e),e in t?Object.defineProperty(t,e,{value:l,enumerable:!0,configurable:!0,writable:!0}):t[e]=l,t}function hAn(t){var e=AAn(t,"string");return typeof e=="symbol"?e:String(e)}function AAn(t,e){if(typeof t!="object"||t===null)return t;var l=t[Symbol.toPrimitive];if(l!==void 0){var n=l.call(t,e||"default");if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var ZAn=Bxt({}),Jxt=ZAn;function Bxt(t){return e.withOptions=l=>Bxt(Lxt(Lxt({},t),l)),e;function e(l,...n){let I=typeof l=="string"?[l]:l.raw,{escapeSpecialCharacters:r=Array.isArray(l),trimWhitespace:a=!0}=t,s="";for(let u=0;u<I.length;u++){let G=I[u];r&&(G=G.replace(/\\\n[ \t]*/g,"").replace(/\\`/g,"`").replace(/\\\$/g,"$").replace(/\\\{/g,"{")),s+=G,u<n.length&&(s+=n[u])}let o=s.split(`
1903
+ `).forEach(I=>{let[r,a]=I.split("=").map(s=>s.trim());r&&a&&(l[r]=a)}),e(l)}catch(l){throw new Error(`Failed to read configuration from ${t}: ${l}`)}}async function aAn(t,e){try{await IAn(t);let l=JSON.stringify(e,null,2);await Rxt.runExclusive(t,()=>tAn(t,l,{mode:384}))}catch(l){throw new Error(`Failed to write configuration to ${t}: ${l}`)}}var Yxt=(t,e,{shouldCache:l})=>{let n=new Map,I=()=>{let G=yxt(e)?process.env.XDG_CONFIG_HOME:process.env.XDG_STATE_HOME;return G?Gce(G,Ext):Gce(lAn(),Ext)},r=()=>{let G=yxt(e)?"-config":"-state";return`${e}${e=="config"?"":G}`},a=G=>{let p=".json",h=r()+(G?"":p),W=Gce(I(),h,G?`${G}${p}`:"");return!dje(W)&&dje(W.replace(/\.json$/,""))&&(W=W.replace(/\.json$/,"")),W},s=async()=>{let G=Gce(I(),r());try{let h=(await qhn(G)).filter(y=>y.endsWith(".json")),W=await Promise.all(h.map(async y=>{let R=Gce(G,y);try{let w=await eAn(R);return{file:y,mtime:w.mtime}}catch{return{file:y,mtime:new Date}}}));return W.sort((y,R)=>R.mtime.getTime()-y.mtime.getTime()),W.map(y=>y.file)}catch{}return[]},o=async(G="")=>{if(l&&n.has(G))return n.get(G);let p=await rAn(a(G),t);return l&&p&&n.set(G,p),p},d=async(G,p="")=>{l&&n.set(p,G),await aAn(a(p),G)};return{load:o,write:d,writeKey:async(G,p,h)=>{let W=await o(h);if(p===void 0){W&&(delete W[G],await d(W,h));return}let y={[G]:p},R;W?R={...W,...y}:R=y,await d(R,h)},path:a,directoryFiles:s}},sYe=(t,e)=>Yxt(t,e,{shouldCache:!0}),oYe=(t,e)=>Yxt(t,e,{shouldCache:!1});var Vxt=JI({host:kl(),login:kl()}),sAn=JI({banner:b2(["always","once","never"]).optional(),beep:Gu().optional(),last_logged_in_user:Vxt.optional(),logged_in_users:Wb(Vxt).optional(),model:b2(Nk).optional(),render_markdown:Gu().optional(),screen_reader:Gu().optional(),theme:kl().optional(),trusted_folders:Wb(kl()).optional(),store_token_plaintext:Gu().optional(),capi_hmac_key:kl().optional(),copilot_hmac_key:kl().optional(),copilot_integration_id:kl().optional(),copilot_tokens:Gv(kl(),kl()).optional(),copilot_url:kl().optional()}),oAn=Gv(kl(),ADe()),iAn=oAn.transform(t=>(0,Qxt.default)(t,(e,l)=>{let n=l.toLowerCase();return n==="github_copilot_integration_id"?"copilot_integration_id":n})),cAn=iAn.pipe(sAn),xr=sYe(cAn.parse,"config");c();function iYe(t){return Yv(t,{onHMACAuthInfo:()=>"Logged in with HMAC",onEnvAuthInfo:e=>`Logged in with ${e.envVar} as user: ${e.login}`,onUserAuthInfo:e=>`Logged in as user: ${bce(e)}`,onGhCliAuthInfo:e=>`Logged in with gh as user: ${bce(e)}`,onApiKeyAuthInfo:e=>`Logged in with API key to ${e.host}`})}function pce(t){return Yv(t,{onHMACAuthInfo:()=>"Unknown (via HMAC)",onEnvAuthInfo:e=>`${e.login} (via ${e.envVar})`,onUserAuthInfo:e=>bce(e),onGhCliAuthInfo:e=>`${e.login} (via gh)`,onApiKeyAuthInfo:e=>`${e.host} (via API key)`})}function uje(t,e){return Yv(t,{onHMACAuthInfo:l=>e.type==="hmac"&&l.hmac===e.hmac,onEnvAuthInfo:l=>e.type==="env"&&l.envVar===e.envVar&&l.login===e.login,onUserAuthInfo:l=>e.type==="user"&&w9(l,e),onGhCliAuthInfo:l=>e.type==="gh-cli"&&w9(l,e),onApiKeyAuthInfo:l=>e.type==="api-key"&&l.host===e.host&&l.apiKey===e.apiKey})}async function wxt(t,e){let l=await t.getAllAuthAvailable(),n=">",I="-";return l.map(r=>`${e&&uje(r.authInfo,e)?n:I} ${pce(r.authInfo)}`)}function bce(t){return t.host!==N2?`${t.login} (${t.host})`:t.login}async function Fxt(){let t=await xr.load()||{};return t?.last_logged_in_user??t.logged_in_users?.[0]??void 0}async function mje(t){await xr.writeKey("last_logged_in_user",t)}async function cYe(){return(await xr.load()||{}).logged_in_users||[]}async function Cxt(t,e){await xr.writeKey("last_logged_in_user",t),await xr.writeKey("logged_in_users",e)}async function vxt(t){let e=await cYe();return e.some(n=>w9(n,t))?(e=e.filter(n=>!w9(n,t)),await Cxt(void 0,e),e.length>0):!1}async function fxt(t){let e=await cYe();e.some(n=>w9(n,t))||(e.push(t),await Cxt(t,e))}function w9(t,e){return t.login===e.login&&t.host===e.host}c();async function Hxt(t,e){try{let l=await e.execReturn("gh",["auth","token","--hostname","github.com"],{silent:!0,ignoreReturnCode:!0});if(l.exitCode!==0||!l.stdout.trim()){let I=`Failed to retrieve GitHub token from CLI (exit code: ${l.exitCode})`,r=l.stderr?.trim();return r?t.debug(`${I}: ${r}`):t.debug(I),null}let n=l.stdout.trim();return n.startsWith("ghp_")?(t.debug("GitHub token is a classic PAT"),null):(t.debug("GitHub CLI authenticated with valid token"),n)}catch(l){let n=`Error checking GitHub CLI: ${l}`;return l&&typeof l=="object"&&"stderr"in l&&typeof l.stderr=="string"&&(n+=` (stderr: ${l.stderr.trim()})`),t.debug(n),null}}c();import{existsSync as Xxt}from"fs";var dYe="copilot-cli",uYe;async function mYe(){if(uYe)return uYe;let t=await import("keytar-forked-forked");return uYe=t.default||t,uYe}var hce=(t,e)=>{if(!(!t||!e))return`${t}:${e}`},dAn=()=>{let t=new Map,e=async(o,d)=>{let u=hce(o,d);if(u)if(Xxt(xr.path()))try{let h=(await xr.load())?.copilot_tokens?.[u];t.set(u,h&&h.trim()!==""?h:void 0)}catch{t.set(u,void 0)}else t.set(u,void 0)},l=async()=>{if(Xxt(xr.path()))try{let d=(await xr.load())?.copilot_tokens;if(d){let u=Object.values(d).filter(G=>G&&G.trim()!=="");if(u.length>0)return u[0]}}catch{return}},n=async(o,d)=>{let u=hce(o,d);if(!u)return;if(t.has(u))return t.get(u);if((await xr.load())?.store_token_plaintext)return await e(o,d),t.get(u);try{let h=await(await mYe()).getPassword(dYe,u);h?t.set(u,h):await e(o,d)}catch{await e(o,d)}return t.get(u)},I=async()=>{if(t.size>0)return t.values().next().value;if((await xr.load())?.store_token_plaintext)return await l();let d;try{d=await(await mYe()).findPassword(dYe)}catch{}return d||(d=await l()),d},r=async(o,d)=>{let u=hce(o,d);if(u){t.delete(u);try{return(await mYe()).deletePassword(dYe,u)}catch{let h=(await xr.load())?.copilot_tokens??{};return delete h[u],await xr.writeKey("copilot_tokens",h),Promise.resolve(!0)}}},a=async(o,d,u)=>{if(!o)throw new Error("No token provided to store");let G=hce(d,u);if(!G)return;if(t.set(G,o),(await xr.load())?.store_token_plaintext)return await s(d,u),!0;try{return await(await mYe()).setPassword(dYe,G,o),!0}catch{return!1}},s=async(o,d)=>{let u=hce(o,d);if(!u)return;let G=t.get(u);if(!G)return;let h=(await xr.load())?.copilot_tokens??{};h[u]=G,await xr.writeKey("copilot_tokens",h)};return{getToken:n,getAnyToken:I,removeToken:r,storeToken:a,storeCurrentTokenInConfig:s}},Vv=dAn();function Yv(t,e){switch(t.type){case"hmac":return e.onHMACAuthInfo(t);case"env":return e.onEnvAuthInfo(t);case"user":return e.onUserAuthInfo(t);case"gh-cli":return e.onGhCliAuthInfo(t);case"api-key":return e.onApiKeyAuthInfo(t);default:{let l=t;throw new Error(`unexpected auth info type: ${JSON.stringify(t)}`)}}}async function gK(t){return await Yv(t,{onHMACAuthInfo:async()=>{},onEnvAuthInfo:async e=>e.token,onUserAuthInfo:async e=>await Vv.getToken(e.host,e.login)||void 0,onGhCliAuthInfo:async e=>e.token,onApiKeyAuthInfo:async()=>{}})}var Gje=class{currentAuthInfo=null;logger=new XA;authCallbacks=[];setLogger(e){this.logger=e}onAuthChange(e){this.authCallbacks.push(e)}removeAuthCallback(e){let l=this.authCallbacks.indexOf(e);l>-1&&this.authCallbacks.splice(l,1)}async notifyAuthChange(e,l){this.currentAuthInfo=e;for(let n of this.authCallbacks)try{await n(e,l)}catch(I){this.logger.error(`Error in auth change callback: ${I}`)}}async tryHMACLogin(){let e=await xr.load()||{},l=e.copilot_hmac_key||e.capi_hmac_key||process.env.CAPI_HMAC_KEY||process.env.COPILOT_HMAC_KEY;return l?[{authInfo:{type:"hmac",hmac:l}}]:[]}async tryGitHubTokenLogin(){let e=process.env.GH_TOKEN||process.env.GITHUB_TOKEN;if(!e)return[];if(e.startsWith("ghp_"))return this.logger.error("Classic PATs are not supported. Please use fine-grained PATs or other supported token types."),[];if(!e.startsWith("gho_")&&!e.startsWith("ghu_")&&!e.startsWith("github_pat_"))return this.logger.error("Unsupported token type, ignoring."),[];try{let l=await mK(N2,e);return[{authInfo:{type:"env",host:N2,login:l,token:e,envVar:process.env.GH_TOKEN?"GH_TOKEN":"GITHUB_TOKEN"},token:e}]}catch(l){l instanceof Ak?this.logger.error(`Failed to fetch PAT user login (${l.status}): ${l.message}`):this.logger.error("Failed to fetch PAT user login")}return[]}async tryGhCliTokenLogin(){let e=new aR(this.logger),l=await Hxt(this.logger,e);if(!l)return[];try{let n=await mK(N2,l);return[{authInfo:{type:"gh-cli",host:N2,login:n,token:l},token:l}]}catch(n){n instanceof Ak?this.logger.error(`Failed to fetch GitHub CLI user login (${n.status}): ${n.message}`):this.logger.error("Failed to fetch GitHub CLI user login")}return[]}async tryApiKeyLogin(){if(!V9())return[];let e=process.env.ANTHROPIC_API_KEY||process.env.AZURE_OPENAI_API_KEY,l=process.env.ANTHROPIC_API_KEY?"https://api.anthropic.com":process.env.AZURE_OPENAI_API_KEY?process.env.AZURE_OPENAI_API_ENDPOINT||process.env.OPENAI_BASE_URL||"https://api.openai.com":void 0;return!e||!l?[]:[{authInfo:{type:"api-key",apiKey:e,host:l}}]}async tryLoginToken(){let e=await Fxt(),l;if(e){if(l=await Vv.getToken(e.host,e.login),!l||l.trim()==="")return[]}else{if(l=await Vv.getAnyToken(),!l||l.trim()==="")return[];e={host:N2,login:await mK(N2,l)}}return[{authInfo:{type:"user",host:e.host,login:e.login},token:l}]}async getAllGitHubLoginTokens(){let l=(await this.tryGitHubTokenLogin()).at(0),n=await cYe(),I=[];for(let r of n){if(l?.authInfo.type==="user"&&w9(r,l.authInfo))continue;let a=await Vv.getToken(r.host,r.login);a&&I.push({authInfo:{type:"user",host:r.host,login:r.login},token:a})}return I}async getAllAuthAvailable(){let e=[],l=this.getPrioritizedAuthMethods(!0);for(let n of l){let I=await n();e.push(...I)}return e}getPrioritizedAuthMethods(e){return[this.tryHMACLogin.bind(this),this.tryApiKeyLogin.bind(this),this.tryGitHubTokenLogin.bind(this),e?this.getAllGitHubLoginTokens.bind(this):this.tryLoginToken.bind(this),this.tryGhCliTokenLogin.bind(this)]}async loadAuthInfo(){let e=this.currentAuthInfo!==null;this.currentAuthInfo=null;let l=this.getPrioritizedAuthMethods(!1);for(let n of l){let I=await n();if(I.length>0){let{authInfo:r,token:a}=I[0];r.type==="user"&&mje({host:r.host,login:r.login}),this.currentAuthInfo=r,e||await this.notifyAuthChange(r,a);return}}}async getCurrentAuthInfo(){return this.currentAuthInfo||await this.loadAuthInfo(),this.currentAuthInfo}async loginUser(e,l){let n={host:e,login:l},I={type:"user",...n};await fxt(n);let r=await gK(I);await this.notifyAuthChange(I,r)}async switchToAuth(e){this.currentAuthInfo=e.authInfo,e.authInfo.type==="user"&&await mje({host:e.authInfo.host,login:e.authInfo.login}),await this.notifyAuthChange(e.authInfo,e.token)}async logout(){if(!this.currentAuthInfo)return!1;let e=await Yv(this.currentAuthInfo,{onHMACAuthInfo:async()=>!1,onEnvAuthInfo:async()=>!1,onUserAuthInfo:async l=>(await Vv.removeToken(l.host,l.login),await vxt(l)),onGhCliAuthInfo:async()=>!1,onApiKeyAuthInfo:async()=>!1});return await this.notifyAuthChange(null),e}},uAn=new Gje,GYe=uAn;var NK=class t extends x2e{constructor(l,n,I,r){super(l,n,r);this.exec=I}static GITHUB_SERVER_NAME="github-mcp-server";hasUserConfiguredGitHubServer=!1;lastGitHubAuthInfo=null;lastGitHubToken=null;githubMcpToken;async configureGitHubAuth(l,n){if(this.lastGitHubAuthInfo=l,this.lastGitHubToken=n,this.isServerDisabled(t.GITHUB_SERVER_NAME))return this.logger.debug("GitHub MCP server is disabled, skipping auto-configuration"),!1;if(this.hasUserConfiguredGitHubServer)return this.logger.debug("User has explicitly configured github-mcp-server, ignoring auth changes"),!1;if(await this.shouldHandleGitHubAuth(l)&&n){if(n===this.githubMcpToken)return!1;this.githubMcpToken=n;let r=await this.createGitHubServerConfig(n,l);try{return await this.restartServer(t.GITHUB_SERVER_NAME,r),this.logger.log("GitHub MCP server configured after authentication"),!0}catch(a){return this.logger.error(`Failed to configure GitHub MCP server after auth: ${a}`),!1}}return!1}async removeGitHubAuth(){if(this.hasUserConfiguredGitHubServer)return this.logger.debug("User has explicitly configured github-mcp-server, ignoring auth changes"),!1;this.githubMcpToken=void 0;try{return this.isServerRunning(t.GITHUB_SERVER_NAME)?(await this.stopServer(t.GITHUB_SERVER_NAME),this.logger.debug("Removed GitHub MCP server"),!0):!1}catch(l){return this.logger.error(`Failed to remove GitHub server: ${l}`),!1}}async shouldHandleGitHubAuth(l){return await Yv(l,{onHMACAuthInfo:async()=>!1,onEnvAuthInfo:async()=>!0,onUserAuthInfo:async()=>!0,onGhCliAuthInfo:async()=>!0,onApiKeyAuthInfo:async()=>!1})}async createGitHubServerConfig(l,n){let I="https://api.githubcopilot.com/mcp/readonly";try{let r=await Yv(n,{onHMACAuthInfo:async()=>"https://github.com",onEnvAuthInfo:async s=>s.host,onUserAuthInfo:async s=>s.host,onGhCliAuthInfo:async s=>s.host,onApiKeyAuthInfo:async s=>s.host}),a=await GK(r,l);I=new URL("/mcp/readonly",a).toString(),this.logger.log(`Using Copilot API endpoint: ${I}`)}catch(r){this.logger.error(`Failed to fetch Copilot URL, using default: ${r}`)}return{type:"http",url:I,headers:{Authorization:"Bearer "+l,"X-MCP-Toolsets":"repos,issues,users,pull_requests,code_security,secret_protection,actions,web_search","X-MCP-Host":"copilot-cli"},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"}}}async injectDefaultServers(l){if(l.mcpServers[t.GITHUB_SERVER_NAME]){this.hasUserConfiguredGitHubServer=!0,this.logger.debug("User has already configured github-mcp-server, skipping auto-configuration");return}}async startBuiltInServer(l){l===t.GITHUB_SERVER_NAME&&!this.hasUserConfiguredGitHubServer?this.lastGitHubAuthInfo&&this.lastGitHubToken?(this.logger.log("Attempting to configure GitHub MCP server using stored authentication"),await this.configureGitHubAuth(this.lastGitHubAuthInfo,this.lastGitHubToken)?this.logger.log("GitHub MCP server configured successfully after enabling"):this.logger.log("GitHub MCP server enabled but could not be configured - authentication may be invalid or insufficient")):this.logger.log("GitHub MCP server enabled - will be configured automatically when authentication becomes available"):await super.startBuiltInServer(l)}};c();c();var GAn=JI({commandHistory:Wb(kl())}),bje=oYe(GAn.parse,"command-history");var bAn=50,pje=class{commandHistory=[];historyIndex=-1;isNavigatingHistory=!1;unSubmittedCommand=null;async initialize(){try{let e=await bje.load();this.commandHistory=e?.commandHistory||[],this.resetNavigation()}catch{this.commandHistory=[]}}async addCommand(e){this.commandHistory=this.commandHistory.filter(l=>l!==e),this.commandHistory.unshift(e),this.commandHistory=this.commandHistory.slice(0,bAn),this.resetNavigation(),this.unSubmittedCommand=null,await this.saveHistory()}async updateCurrentCommand(e){this.historyIndex!==-1?(this.commandHistory[this.historyIndex]=e,await this.saveHistory()):this.unSubmittedCommand=e}navigateUp(e){if(this.commandHistory.length===0)return;let l=this.historyIndex+1;if(l<this.commandHistory.length){this.historyIndex=l,this.isNavigatingHistory=!0;let n=this.getCurrentHistoryItem();n&&e.setText(n)}}navigateDown(e){if(this.historyIndex===-1)return;if(this.historyIndex===0)this.resetNavigation();else{let n=this.historyIndex-1;this.historyIndex=n,this.isNavigatingHistory=!0}let l=this.getCurrentHistoryItem();l?(e.setText(l),e.setCursorPosition(0)):e.clear()}resetNavigation(){this.historyIndex=-1,this.isNavigatingHistory=!1}getHistoryIndex(){return this.historyIndex}getHistory(){return this.commandHistory}getCurrentHistoryItem(){return this.historyIndex===-1?this.unSubmittedCommand?this.unSubmittedCommand:void 0:this.commandHistory[this.historyIndex]}isNavigating(){return this.isNavigatingHistory}setNavigating(e){this.isNavigatingHistory=e}async saveHistory(){try{await bje.write({commandHistory:this.commandHistory})}catch{}}},W2=new pje;c();c();function kxt(t,e){var l=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(I){return Object.getOwnPropertyDescriptor(t,I).enumerable})),l.push.apply(l,n)}return l}function Lxt(t){for(var e=1;e<arguments.length;e++){var l=arguments[e]!=null?arguments[e]:{};e%2?kxt(Object(l),!0).forEach(function(n){pAn(t,n,l[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(l)):kxt(Object(l)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(l,n))})}return t}function pAn(t,e,l){return e=hAn(e),e in t?Object.defineProperty(t,e,{value:l,enumerable:!0,configurable:!0,writable:!0}):t[e]=l,t}function hAn(t){var e=AAn(t,"string");return typeof e=="symbol"?e:String(e)}function AAn(t,e){if(typeof t!="object"||t===null)return t;var l=t[Symbol.toPrimitive];if(l!==void 0){var n=l.call(t,e||"default");if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var ZAn=Bxt({}),Jxt=ZAn;function Bxt(t){return e.withOptions=l=>Bxt(Lxt(Lxt({},t),l)),e;function e(l,...n){let I=typeof l=="string"?[l]:l.raw,{escapeSpecialCharacters:r=Array.isArray(l),trimWhitespace:a=!0}=t,s="";for(let u=0;u<I.length;u++){let G=I[u];r&&(G=G.replace(/\\\n[ \t]*/g,"").replace(/\\`/g,"`").replace(/\\\$/g,"$").replace(/\\\{/g,"{")),s+=G,u<n.length&&(s+=n[u])}let o=s.split(`
1904
1904
  `),d=null;for(let u of o){let G=u.match(/^(\s+)\S+/);if(G){let p=G[1].length;d?d=Math.min(d,p):d=p}}if(d!==null){let u=d;s=o.map(G=>G[0]===" "||G[0]===" "?G.slice(u):G).join(`
1905
1905
  `)}return a&&(s=s.trim()),r&&(s=s.replace(/\\n/g,`
1906
1906
  `)),s}}import{homedir as Kxt}from"node:os";import vAn,{resolve as fAn}from"node:path";c();function gAn(t){return t.length>0&&/^[0-9a-zA-Z_-]+$/.test(t)}function Sxt(t){return!t||t.length===0?{valid:!1,error:"MCP server name cannot be empty"}:/^[0-9a-zA-Z_-]+$/.test(t)?{valid:!0}:{valid:!1,error:"MCP server name must only contain alphanumeric characters, underscores, and hyphens"}}var xxt=b2(["none","markdown","hidden_characters"]),Oxt=JI({tools:Wb(kl()),type:kl().optional(),isDefaultServer:Gu().optional(),filterMapping:Gv(kl(),xxt).or(xxt).optional()}),NAn=Oxt.extend({type:ms("local").optional(),command:kl(),args:Wb(kl()),env:Gv(kl(),kl()).optional()}),WAn=Oxt.extend({type:ms("http").or(ms("sse")),url:kl(),headers:Gv(kl(),kl()).optional()}),yAn=JI({mcpServers:Gv(kl().min(1,"MCP server name cannot be empty").refine(gAn,{message:"MCP server name must only contain alphanumeric characters, underscores, and hyphens"}),NAn.or(WAn))}),y2=sYe(yAn.parse,"mcp");c();c();function Txt(t){let e=t.r/255,l=t.g/255,n=t.b/255,I=Math.max(e,l,n),r=Math.min(e,l,n),a=I-r,s=0,o=0,d=(I+r)/2;if(a!==0){switch(o=d>.5?a/(2-I-r):a/(I+r),I){case e:s=(l-n)/a+(l<n?6:0);break;case l:s=(n-e)/a+2;break;case n:s=(e-l)/a+4;break}s/=6}return{h:s*360,s:o,l:d}}function EAn(t){if(t.length<12||t.length>18)return null;let e=t.match(/rgb:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i);if(!e)return null;let[,l,n,I]=e,r=d=>d.length>=2?parseInt(d.substring(0,2),16):d.length===1?parseInt(d+d,16):0,a=r(l),s=r(n),o=r(I);return{r:a,g:s,b:o}}var Uxt=["#000000","#800000","#008000","#808000","#000080","#800080","#008080","#c0c0c0","#808080","#ff0000","#00ff00","#ffff00","#0000ff","#ff00ff","#00ffff","#ffffff","#000000","#00005f","#000087","#0000af","#0000d7","#0000ff","#005f00","#005f5f","#005f87","#005faf","#005fd7","#005fff","#008700","#00875f","#008787","#0087af","#0087d7","#0087ff","#00af00","#00af5f","#00af87","#00afaf","#00afd7","#00afff","#00d700","#00d75f","#00d787","#00d7af","#00d7d7","#00d7ff","#00ff00","#00ff5f","#00ff87","#00ffaf","#00ffd7","#00ffff","#5f0000","#5f005f","#5f0087","#5f00af","#5f00d7","#5f00ff","#5f5f00","#5f5f5f","#5f5f87","#5f5faf","#5f5fd7","#5f5fff","#5f8700","#5f875f","#5f8787","#5f87af","#5f87d7","#5f87ff","#5faf00","#5faf5f","#5faf87","#5fafaf","#5fafd7","#5fafff","#5fd700","#5fd75f","#5fd787","#5fd7af","#5fd7d7","#5fd7ff","#5fff00","#5fff5f","#5fff87","#5fffaf","#5fffd7","#5fffff","#870000","#87005f","#870087","#8700af","#8700d7","#8700ff","#875f00","#875f5f","#875f87","#875faf","#875fd7","#875fff","#878700","#87875f","#878787","#8787af","#8787d7","#8787ff","#87af00","#87af5f","#87af87","#87afaf","#87afd7","#87afff","#87d700","#87d75f","#87d787","#87d7af","#87d7d7","#87d7ff","#87ff00","#87ff5f","#87ff87","#87ffaf","#87ffd7","#87ffff","#af0000","#af005f","#af0087","#af00af","#af00d7","#af00ff","#af5f00","#af5f5f","#af5f87","#af5faf","#af5fd7","#af5fff","#af8700","#af875f","#af8787","#af87af","#af87d7","#af87ff","#afaf00","#afaf5f","#afaf87","#afafaf","#afafd7","#afafff","#afd700","#afd75f","#afd787","#afd7af","#afd7d7","#afd7ff","#afff00","#afff5f","#afff87","#afffaf","#afffd7","#afffff","#d70000","#d7005f","#d70087","#d700af","#d700d7","#d700ff","#d75f00","#d75f5f","#d75f87","#d75faf","#d75fd7","#d75fff","#d78700","#d7875f","#d78787","#d787af","#d787d7","#d787ff","#d7af00","#d7af5f","#d7af87","#d7afaf","#d7afd7","#d7afff","#d7d700","#d7d75f","#d7d787","#d7d7af","#d7d7d7","#d7d7ff","#d7ff00","#d7ff5f","#d7ff87","#d7ffaf","#d7ffd7","#d7ffff","#ff0000","#ff005f","#ff0087","#ff00af","#ff00d7","#ff00ff","#ff5f00","#ff5f5f","#ff5f87","#ff5faf","#ff5fd7","#ff5fff","#ff8700","#ff875f","#ff8787","#ff87af","#ff87d7","#ff87ff","#ffaf00","#ffaf5f","#ffaf87","#ffafaf","#ffafd7","#ffafff","#ffd700","#ffd75f","#ffd787","#ffd7af","#ffd7d7","#ffd7ff","#ffff00","#ffff5f","#ffff87","#ffffaf","#ffffd7","#ffffff","#080808","#121212","#1c1c1c","#262626","#303030","#3a3a3a","#444444","#4e4e4e","#585858","#626262","#6c6c6c","#767676","#808080","#8a8a8a","#949494","#9e9e9e","#a8a8a8","#b2b2b2","#bcbcbc","#c6c6c6","#d0d0d0","#dadada","#e4e4e4","#eeeeee"];function RAn(t){let e=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return e?{r:parseInt(e[1],16),g:parseInt(e[2],16),b:parseInt(e[3],16)}:{r:0,g:0,b:0}}function YAn(t){return t<0||t>=Uxt.length?{r:0,g:0,b:0}:RAn(Uxt[t])}function Mxt(t){if(t.length<15||t.length>30)return null;let e=t;e.endsWith("\x07")?e=e.slice(0,-1):e.endsWith("\x1B\\")?e=e.slice(0,-2):e.endsWith("\x9C")&&(e=e.slice(0,-1));let l=e;return l.startsWith("11;")&&(l=l.substring(3)),l.startsWith("rgb:")?EAn(l):null}async function VAn(t=100){return new Promise(e=>{if(!process.stdout.isTTY||!process.stdin.isTTY){e(null);return}let l="",n=null,I=()=>{process.stdin.removeListener("data",r),process.stdin.setRawMode(!1),n&&clearTimeout(n)},r=a=>{l+=a.toString();let s=l.match(/\x1b\]11;([^\x07\x1b\x9c]*?)(?:\x07|\x1b\\|\x9c)/);if(s){I();let d=`11;${s[1]}`;e(Mxt(d));return}let o=l.match(/11;rgb:([0-9a-f/]+)(?:\x07|\x1b\\|\x9c)/i);if(o){I(),e(Mxt(`11;rgb:${o[1]}`));return}};n=setTimeout(()=>{I(),e(null)},t);try{process.stdin.setRawMode(!0),process.stdin.on("data",r),process.stdout.write("\x1B]11;?\x1B\\")}catch{I(),e(null)}})}function QAn(){let t=process.env.COLORFGBG;if(!t||!t.includes(";"))return null;let e=t.split(";"),l=e[e.length-1],n=parseInt(l,10);return isNaN(n)?null:YAn(n)}async function _xt(){try{let t=await VAn();if(t)return Txt(t).l<.5;let e=QAn();return e?Txt(e).l<.5:!0}catch{return!0}}var Dxt={FG:"whiteBright",ACCENT:"blue",SUCCESS:"green",DIFF_ADDED_HIGHLIGHT_FG:"black",DIFF_REMOVED_HIGHLIGHT_FG:"white",ERROR:"red",WARNING:"yellow",COPILOT:"magenta",MUTED:"white",SELECTED:"cyan",BORDER:"blackBright"},wAn={FG:"black",ACCENT:"blue",SUCCESS:"green",DIFF_ADDED_HIGHLIGHT_FG:"black",DIFF_REMOVED_HIGHLIGHT_FG:"white",ERROR:"red",WARNING:"yellow",COPILOT:"magenta",MUTED:"blackBright",SELECTED:"cyan",BORDER:"blackBright"};function hje(t){return t==="auto"||t==="dark"||t==="light"}function bYe(t){switch(t){case"dark":return Dxt;case"light":return wAn;default:return Dxt}}var pYe=await _xt();async function hYe(){let e=(await xr.load())?.theme||"";return hje(e)?e:"auto"}async function zxt(t){await xr.writeKey("theme",t)}var Pxt=t=>{let e=t?Bl.whiteBright:Bl.black,l=t?Bl.cyanBright:Bl.blueBright,n=t?Bl.magentaBright:Bl.magenta;return{text:e,paragraph:e,html:e,table:e,blockquote:e,heading:Bl.bold,firstHeading:Bl.whiteBright.bold,strong:Bl.bold,em:Bl.italic,del:Bl.strikethrough,hr:Bl.white,link:l,href:l,image:(I,r,a)=>n(a?`Image: ${a} \u2192 ${I}`:`Image: ${I}`),codespan:Bl.cyan,code:Bl.cyan,list:(I,r,a)=>{let s=I.replace(/^(\s*)\* /gm,"$1- ");return a&&(s=s.split(`
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@github/copilot",
3
3
  "description": "GitHub Copilot CLI brings the power of Copilot coding agent directly to your terminal.",
4
- "version": "0.0.339-2",
4
+ "version": "0.0.339-3",
5
5
  "type": "module",
6
6
  "repository": {
7
7
  "type": "git",
@@ -33,7 +33,7 @@
33
33
  "sdk/**/*"
34
34
  ],
35
35
  "buildMetadata": {
36
- "gitCommit": "82c2a96"
36
+ "gitCommit": "4188608"
37
37
  },
38
38
  "dependencies": {
39
39
  "node-pty": "npm:@devm33/node-pty@^1.0.8",
package/sdk/index.js CHANGED
@@ -1347,7 +1347,7 @@ Pay attention to the following when using it:
1347
1347
  `}var cjI=pq.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function ajI(){let t={};for(let e of cjI){let I=pq.env[e];I!==void 0&&(I.startsWith("()")||(t[e]=I))}return t}var hq=class{constructor(e){this._abortController=new AbortController,this._readBuffer=new mq,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new njI)}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,a,s;this._process=(0,jDe.default)(this._serverParams.command,(l=this._serverParams.args)!==null&&l!==void 0?l:[],{env:{...ajI(),...this._serverParams.env},stdio:["pipe","pipe",(n=this._serverParams.stderr)!==null&&n!==void 0?n:"inherit"],shell:!1,signal:this._abortController.signal,windowsHide:pq.platform==="win32"&&sjI(),cwd:this._serverParams.cwd}),this._process.on("error",r=>{var o,d;if(r.name==="AbortError"){(o=this.onclose)===null||o===void 0||o.call(this);return}I(r),(d=this.onerror)===null||d===void 0||d.call(this,r)}),this._process.on("spawn",()=>{e()}),this._process.on("close",r=>{var o;this._process=void 0,(o=this.onclose)===null||o===void 0||o.call(this)}),(c=this._process.stdin)===null||c===void 0||c.on("error",r=>{var o;(o=this.onerror)===null||o===void 0||o.call(this,r)}),(a=this._process.stdout)===null||a===void 0||a.on("data",r=>{this._readBuffer.append(r),this.processReadBuffer()}),(s=this._process.stdout)===null||s===void 0||s.on("error",r=>{var o;(o=this.onerror)===null||o===void 0||o.call(this,r)}),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=TDe(e);this._process.stdin.write(n)?I():this._process.stdin.once("drain",I)})}};function sjI(){return"type"in pq}G();G();var Zq=class extends TransformStream{constructor({onError:e,onRetry:I,onComment:l}={}){let n;super({start(c){n=rq({onEvent:a=>{c.enqueue(a)},onError(a){e==="terminate"?c.error(a):typeof e=="function"&&e(a)},onRetry:I,onComment:l})},transform(c){n.feed(c)}})}};var rjI={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},yx=class extends Error{constructor(e,I){super(`Streamable HTTP error: ${I}`),this.code=e}},uq=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:rjI}async _authThenStart(){var e;if(!this._authProvider)throw new eo("No auth provider");let I;try{I=await WV(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 eo;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 a=await this._commonHeaders();a.set("Accept","text/event-stream"),c&&a.set("last-event-id",c);let s=await((I=this._fetch)!==null&&I!==void 0?I:fetch)(this._url,{method:"GET",headers:a,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 yx(s.status,`Failed to open SSE stream: ${s.statusText}`)}this._handleSseStream(s.body,e,!0)}catch(a){throw(n=this.onerror)===null||n===void 0||n.call(this,a),a}}_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(a=>{var s;(s=this.onerror)===null||s===void 0||s.call(this,new Error(`Failed to reconnect SSE stream: ${a instanceof Error?a.message:String(a)}`)),this._scheduleReconnection(e,I+1)})},c)}_handleSseStream(e,I,l){if(!e)return;let{onresumptiontoken:n,replayMessageId:c}=I,a;(async()=>{var r,o,d,i;try{let h=e.pipeThrough(new TextDecoderStream).pipeThrough(new Zq).getReader();for(;;){let{value:p,done:Z}=await h.read();if(Z)break;if(p.id&&(a=p.id,n?.(p.id)),!p.event||p.event==="message")try{let u=oV.parse(JSON.parse(p.data));c!==void 0&&H9(u)&&(u.id=c),(r=this.onmessage)===null||r===void 0||r.call(this,u)}catch(u){(o=this.onerror)===null||o===void 0||o.call(this,u)}}}catch(h){if((d=this.onerror)===null||d===void 0||d.call(this,new Error(`SSE stream disconnected: ${h}`)),l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:n,replayMessageId:c},0)}catch(p){(i=this.onerror)===null||i===void 0||i.call(this,new Error(`Failed to reconnect: ${p instanceof Error?p.message:String(p)}`))}}})()}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 eo("No auth provider");if(await WV(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new eo("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,a;try{let{resumptionToken:s,onresumptiontoken:r}=I||{};if(s){this._startOrAuthSse({resumptionToken:s,replayMessageId:p6(e)?e.id:void 0}).catch(N=>{var Y;return(Y=this.onerror)===null||Y===void 0?void 0:Y.call(this,N)});return}let o=await this._commonHeaders();o.set("content-type","application/json"),o.set("accept","application/json, text/event-stream");let d={...this._requestInit,method:"POST",headers:o,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),h=i.headers.get("mcp-session-id");if(h&&(this._sessionId=h),!i.ok){if(i.status===401&&this._authProvider){if(this._resourceMetadataUrl=Rx(i),await WV(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new eo;return this.send(e)}let N=await i.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${i.status}): ${N}`)}if(i.status===202){lMe(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(N=>{var Y;return(Y=this.onerror)===null||Y===void 0?void 0:Y.call(this,N)});return}let Z=(Array.isArray(e)?e:[e]).filter(N=>"method"in N&&"id"in N&&N.id!==void 0).length>0,u=i.headers.get("content-type");if(Z)if(u?.includes("text/event-stream"))this._handleSseStream(i.body,{onresumptiontoken:r},!1);else if(u?.includes("application/json")){let N=await i.json(),Y=Array.isArray(N)?N.map(y=>oV.parse(y)):[oV.parse(N)];for(let y of Y)(c=this.onmessage)===null||c===void 0||c.call(this,y)}else throw new yx(-1,`Unexpected content type: ${u}`)}catch(s){throw(a=this.onerror)===null||a===void 0||a.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},a=await((I=this._fetch)!==null&&I!==void 0?I:fetch)(this._url,c);if(!a.ok&&a.status!==405)throw new yx(a.status,`Failed to terminate session: ${a.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}};G();var Wq=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 Xpe(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?.())}},Xpe=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 Nq=class{createTransport(e){switch(e.type){case"stdio":{let I=new hq({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 uq(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"sse":return new iq(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"memory":return new Wq(e.server);default:throw new Error(`Unsupported transport type: ${e.type}`)}}};G();var rF="blackbird-mcp-server",qE="github-mcp-server",Hpe="playwright";function _E(t){return t.type===void 0||t.type.toLowerCase()==="local"||t.type.toLowerCase()==="stdio"}function Yq(t){return t.type?.toLowerCase()==="http"}function Vq(t){return t.type?.toLowerCase()==="sse"}function Fx(t){return t.type?.toLowerCase()==="memory"}var Epe=class extends GjI{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)))}}},Rq=class{constructor(e,I=new aq,l=new Nq){this.logger=e;this.clientFactory=I;this.transportFactory=l}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 Epe(e,this.logger),a={type:"stdio",command:l,args:n,env:{...I,PATH:process.env.PATH},stderr:c},s=this.transportFactory.createTransport(a);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 a=[];try{this.logger.log(`Fetching tools from client: ${n}`);let s=await c.listTools(),r=e?.mcpServers[n].tools,o=e?.mcpServers[n].filterMapping;for(let i of s.tools){if(i.name==="get_copilot_space")continue;if(!(r?.includes("*")||r?.includes(i.name))){this.logger.log(`Tool ${i.name} is not in the allowed list for client: ${n}`);continue}let p=l6(n,i.name),Z=`${n}-${i.name}`,u;typeof o=="string"?u=ebe(o):u=ebe(o?.[i.name]??"hidden_characters"),l[`${n}/${i.name}`]={name:Z,title:i.title??i.annotations?.title??i.name,description:i.description??Z,input_schema:i.inputSchema,readOnly:i.annotations?.readOnlyHint,safeForTelemetry:{name:!!(e?.mcpServers[n].isDefaultServer||p),inputsNames:!!e?.mcpServers[n].isDefaultServer},filterMode:u},a.push(i.name),this.logger.log(`Tool ${i.name} added to tools list for client: ${n}`)}this.logger.log(`Successfully retrieved ${a.length} tools from client: ${n}`);let d=c.getServerVersion();await this.logServerSuccessWithTools(n,a,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!=rF&&n)try{let c=I.map(r=>`- ${r}`).join(`
1348
1348
  `),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
1349
1349
 
1350
- ${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}`)}}};G();var vpe={mcpServers:{}},yq=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}remoteEnabled;mcp3pEnabled;blackbirdMetisIndexEnabled;mcpEnvConfig;sessionClient;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"),vpe;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"),vpe;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}`),vpe}}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,bing_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[qE]=c}configureLocalGitHubMcp(e){if(e.mcpServers[qE]){this.logger.log("Using user-provided GitHub MCP server configuration");let I=e.mcpServers[qE]??{};_E(I)&&!I.command&&(e.mcpServers[qE]={...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[qE]=I}}configurePlaywrightMcp(e){if(!e.mcpServers[Hpe]){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:[...Obe,"--allowed-origins","localhost;localhost:*;127.0.0.1;127.0.0.1:*"],tools:["*"],isDefaultServer:!0};e.mcpServers[Hpe]=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[rF]=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[rF]=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[rF]=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 _E(e)||Yq(e)||Vq(e)||Fx(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&&!_E(I)&&!Fx(I)?(this.logger.error(`Unsupported server type "${I.type}" for server "${e}". Only "Local", "STDIO", or "Memory" are supported.`),!1):I.tools?_E(I)&&!this.isValidLocalServerConfig(I)?(this.logger.error(`Invalid local server configuration for "${e}". Please ensure 'command' and 'args' are provided.`),!1):(Yq(I)||Vq(I))&&!this.isValidRemoteServerConfig(I)?(this.logger.error(`Invalid remote server configuration for "${e}". Please ensure 'url' is provided.`),!1):Fx(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(a){this.logger.error(`Failed to handle Python module for ${e}: ${a}`)}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(a){throw this.logger.error(`Failed to start MCP client for ${e}: ${a}`),a}}convertPythonToPipx(e){if(!e||!e.args||e.args.length===0)return e;let 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 a=l+2;a<I.length;a++)c.push(I[a]);for(let a=0;a<l;a++)c.push(I[a]);return{...e,command:"pipx",args:c}}buildEnvironment(e){let I={};if(e.env)for(let[l,n]of Object.entries(e.env)){let c=n.trim();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,a)=>{let r=I[n||a];return r!==void 0?r: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 a=this.resolveArray([c],I);l[n]=a[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{_E(I)?await this.processLocalServer(e,I):Yq(I)&&this.remoteEnabled?await this.processHttpServer(e,I):Vq(I)&&this.remoteEnabled?await this.processSseServer(e,I):Fx(I)&&await this.processInMemoryServer(e,I)}catch(l){e!==rF&&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 Fq=class{constructor(e,I,l){this.logger=e;let n;if(typeof I=="string"){if(n=JSON.parse(I),typeof n!="object")throw new Error("Invalid MCP configuration: must be an object");if(n===null||!("mcpServers"in n)||typeof n.mcpServers!="object")throw new Error("Invalid MCP configuration: missing or invalid mcpServers property");this.config=n}else this.config=I;this.disabledServers=new Set(l||[]),this.registry=new Rq(this.logger),this.processor=new yq(this.logger,this.registry,{mcp3pEnabled:!0,remoteEnabled:!0})}registry;processor;config;startServersPromise=null;allTools=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.allTools=null}async getTools(e,I,l){if(!this.allTools){await this.startServers();let n=new F9(e,I,l),c=[];for(let a of Object.keys(this.registry.clients)){let s=await n.loadTools({mcpClient:this.registry.clients[a],clientName:a,tools:this.config.mcpServers[a]?.tools||["*"],filterMapping:this.config.mcpServers[a]?.filterMapping||"hidden_characters"});c.push(...s)}this.allTools=c}return this.allTools}getConfig(){return this.config}async startServer(e,I){await this.startServers(),this.config.mcpServers[e]=I,await this.processor.processServer(e,I),this.allTools=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.allTools=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.allTools=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.allTools=null}async startBuiltInServer(e){}getServerConfig(e){return this.config.mcpServers[e]}};G();var RKe=rn(VKe(),1);async function tKI(t={}){let e=await uZe();return hZe((0,RKe.default)({},e,t))}async function yKe(t={}){if(Bx())throw new Error("Settings have already been initialized");return tKI(t)}G();async function NV(t,e,I){if(!t||t.length===0)return;let l=!1,n={};for(let c of t)try{let a=await c(e);a&&(l=!0,n={...n,...a})}catch(a){I.error(`Hook execution failed: ${a}`)}return l?n:void 0}G();var t1=class{sessionId;startTime;events=[];_chatMessages=[];_selectedModel;logger;eventCallbacks=[];constructor({sessionId:e,startTime:I,logger:l}={}){this.sessionId=e||kb(),this.startTime=I||new Date,this.logger=l||new ai}static 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 ai});n._selectedModel=l.data.selectedModel,n.events.push(l);for(let c=1;c<e.length;c++){let a=e[c];n.events.push(a),n.processEventForState(a)}return n}addEvent(e){let I=e.id||kb(),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.processEventForState(c),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)}}get chatMessages(){return this._chatMessages}get selectedModel(){return this._selectedModel}setSelectedModel(e){let I=this._selectedModel;this._selectedModel=e,this.addEvent({type:"session.model_change",data:{previousModel:I,newModel:e}})}getChatContextMessages(){return this._chatMessages.filter(e=>e.role!=="system")}getSystemContextMessages(){return this._chatMessages.filter(e=>e.role==="system")}getLastEventId(){return this.events.length===0?null:this.events[this.events.length-1].id}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":this._chatMessages.push({role:"user",content:e.data.content});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":{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.resume":case"session.error":case"session.info":case"session.import_legacy":case"assistant.turn_start":case"assistant.turn_end":case"assistant.usage":case"abort":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)}`)}}};var Cq=class{static name="Copilot";static description="Base Copilot Agent";options;logger;workingDir;session;constructor(e){this.options=e,this.logger=e.logger||new ai,this.workingDir=e.workingDirectory||process.cwd(),this.session=e.session||new t1,ybe(this.workingDir).then(I=>{if(I.found)return MUe(I.gitRoot,!0,this.workingDir)}).catch(I=>{this.logger.debug(`Failed to initialize custom instructions cache: ${I}`)})}async*query(e){let I=new Map,l;try{if(this.options.mcpServers&&Object.keys(this.options.mcpServers).length>0)try{l=new Fq(this.logger,{mcpServers:this.options.mcpServers},this.options.disabledTools),await l.startServers()}catch(Ze){this.logger.error(`Failed to initialize MCP host: ${Ze}`)}let n={timestamp:Date.now(),cwd:this.workingDir,prompt:e},a=(await NV(this.options.hooks?.userPromptSubmitted,n,this.logger))?.modifiedPrompt??e;this.session.addEvent({type:"user.message",data:{content:a}});let r=new WF().setProblemStatement(a).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();pZe();let o=await yKe(r),d=o.service?.agent?.model,i=Ime(d),h=i.agent,p=i.model?{model:i.model}:void 0,Z=coe(o,this.logger,h,p),u={location:this.workingDir,timeout:3e4,requireReasoning:!0,toolPartialResultCallback:void 0,permissions:this.options.requestPermission?{requestRequired:!0,request:this.options.requestPermission}:{requestRequired:!1},shellConfig:process.platform==="win32"?Ci.powerShell:Ci.bash},N=await HOe(u,this.logger),Y=[];if(l)try{Y=await l.getTools(o,this.logger,u.permissions)}catch(Ze){this.logger.error(`Failed to get MCP tools: ${Ze}`)}let y=[...N,...Y],Q=this.applyToolFiltering(y,this.options.allowedTools,this.options.disabledTools),A=await ybe(this.workingDir),H={...(vOe()["sweagent-capi"]?.["claude-sonnet-4"]??EOe()).supports,reasoning:!0},v=await iOe(A.found?A.gitRoot:"",qke(),this.workingDir,{},H,u,Q,void 0),ce=this.session.chatMessages.slice(0,-1),Re={role:"user",content:hOe(a,H)},Xe=[...ce,Re],He={timestamp:Date.now(),cwd:this.workingDir,source:"new",initialPrompt:e};await NV(this.options.hooks?.sessionStart,He,this.logger);let ie=Z.getCompletionWithTools(v,Xe,Q,{failIfInitialInputsTooLong:!1,processors:{preRequest:[new NE(Re,this.logger)]},executeToolsInParallel:!1,abortSignal:this.options.abortController?.signal});for await(let Ze of ie){if(this.options.abortController?.signal.aborted){yield{type:"error",error:new Error("Operation was cancelled")};return}let II=await this.translateEvent(Ze,I);for(let Je of II)Je.type==="message"&&Je.role==="assistant"&&this.session.addEvent({type:"assistant.message",data:{messageId:`msg-${Date.now()}`,content:Je.content}}),yield Je}yield{type:"complete"}}catch(n){let c={timestamp:Date.now(),cwd:this.workingDir,reason:"error",error:n instanceof Error?n:new Error(String(n))};await NV(this.options.hooks?.sessionEnd,c,this.logger),yield{type:"error",error:n instanceof Error?n:new Error(String(n))}}finally{let n={timestamp:Date.now(),cwd:this.workingDir,reason:"complete"};if(await NV(this.options.hooks?.sessionEnd,n,this.logger),l)try{await l.stopServers(),this.logger.log("MCP host stopped successfully")}catch(c){this.logger.error(`Error stopping MCP host: ${c}`)}}}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}async translateEvent(e,I){switch(e.kind){case"message":{if(c6(e)&&e.message.content)return[{type:"message",content:typeof e.message.content=="string"?e.message.content:"",role:"assistant"}];if(FOe(e)){let l=[];for(let n of e.message.tool_calls){let c=TA(n.function.arguments);I.set(n.id,n.function.name);let a={timestamp:Date.now(),cwd:this.workingDir,toolName:n.function.name,toolArgs:c},r=(await NV(this.options.hooks?.preToolUse,a,this.logger))?.modifiedArgs??c;l.push({type:"tool_use",toolName:n.function.name,args:r,toolCallId:n.id})}return l}return[]}case"response":return[];case"model_call_failure":{let l=new Error(e.modelCall?.error||"Model call failed"),n={timestamp:Date.now(),cwd:this.workingDir,error:l,errorContext:"model_call",recoverable:!0};return await NV(this.options.hooks?.errorOccurred,n,this.logger),[{type:"error",error:l}]}case"tool_execution":{let l=I.get(e.toolCallId)||"unknown",n={timestamp:Date.now(),cwd:this.workingDir,toolName:l,toolArgs:{},toolResult:e.toolResult},a=(await NV(this.options.hooks?.postToolUse,n,this.logger))?.modifiedResult??e.toolResult;return[{type:"tool_result",toolName:l,result:a,toolCallId:e.toolCallId}]}default:return[]}}};G();G();var Ope=class{loggers;constructor(e){this.loggers=e}isDebug(){return this.loggers.some(e=>e.isDebug())}debug(e){this.loggers.forEach(I=>I.debug(e))}log(e){this.loggers.forEach(I=>I.log(e))}info(e){this.loggers.forEach(I=>I.info(e))}notice(e){this.loggers.forEach(I=>I.notice(e))}warning(e){this.loggers.forEach(I=>I.warning(e))}error(e){this.loggers.forEach(I=>I.error(e))}startGroup(e,I){this.loggers.forEach(l=>l.startGroup(e,I))}endGroup(e){this.loggers.forEach(I=>I.endGroup(e))}};G();import{appendFile as lKI,access as nKI,mkdir as cKI}from"fs/promises";import{constants as aKI}from"fs";import{dirname as sKI}from"path";var Mpe=class extends Gp{constructor(I,l,n){super(l,n);this.filePath=I;this.writeQueue=rKI(sKI(this.filePath)).catch(()=>{})}writeQueue=Promise.resolve();log(I){this.write("LOG",I)}debug(I){super.shouldLog(8)&&this.write("DEBUG",this.filterSecrets(I).toString())}info(I){super.shouldLog(4)&&this.write("INFO",this.filterSecrets(I).toString())}notice(I){super.shouldLog(2)&&this.write("NOTICE",this.filterSecrets(I).toString())}warning(I){super.shouldLog(2)&&this.write("WARNING",this.filterSecrets(I).toString())}error(I){super.shouldLog(1)&&this.write("ERROR",this.filterSecrets(I).toString())}startGroup(I,l){super.shouldLog(l||4)&&this.write("START-GROUP",I)}endGroup(I){super.shouldLog(I||4)&&this.write("END-GROUP","")}write(I,l){let c=`${new Date().toISOString()} [${I}] ${l}
1350
+ ${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}`)}}};G();var vpe={mcpServers:{}},yq=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}remoteEnabled;mcp3pEnabled;blackbirdMetisIndexEnabled;mcpEnvConfig;sessionClient;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"),vpe;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"),vpe;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}`),vpe}}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[qE]=c}configureLocalGitHubMcp(e){if(e.mcpServers[qE]){this.logger.log("Using user-provided GitHub MCP server configuration");let I=e.mcpServers[qE]??{};_E(I)&&!I.command&&(e.mcpServers[qE]={...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[qE]=I}}configurePlaywrightMcp(e){if(!e.mcpServers[Hpe]){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:[...Obe,"--allowed-origins","localhost;localhost:*;127.0.0.1;127.0.0.1:*"],tools:["*"],isDefaultServer:!0};e.mcpServers[Hpe]=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[rF]=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[rF]=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[rF]=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 _E(e)||Yq(e)||Vq(e)||Fx(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&&!_E(I)&&!Fx(I)?(this.logger.error(`Unsupported server type "${I.type}" for server "${e}". Only "Local", "STDIO", or "Memory" are supported.`),!1):I.tools?_E(I)&&!this.isValidLocalServerConfig(I)?(this.logger.error(`Invalid local server configuration for "${e}". Please ensure 'command' and 'args' are provided.`),!1):(Yq(I)||Vq(I))&&!this.isValidRemoteServerConfig(I)?(this.logger.error(`Invalid remote server configuration for "${e}". Please ensure 'url' is provided.`),!1):Fx(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(a){this.logger.error(`Failed to handle Python module for ${e}: ${a}`)}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(a){throw this.logger.error(`Failed to start MCP client for ${e}: ${a}`),a}}convertPythonToPipx(e){if(!e||!e.args||e.args.length===0)return e;let 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 a=l+2;a<I.length;a++)c.push(I[a]);for(let a=0;a<l;a++)c.push(I[a]);return{...e,command:"pipx",args:c}}buildEnvironment(e){let I={};if(e.env)for(let[l,n]of Object.entries(e.env)){let c=n.trim();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,a)=>{let r=I[n||a];return r!==void 0?r: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 a=this.resolveArray([c],I);l[n]=a[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{_E(I)?await this.processLocalServer(e,I):Yq(I)&&this.remoteEnabled?await this.processHttpServer(e,I):Vq(I)&&this.remoteEnabled?await this.processSseServer(e,I):Fx(I)&&await this.processInMemoryServer(e,I)}catch(l){e!==rF&&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 Fq=class{constructor(e,I,l){this.logger=e;let n;if(typeof I=="string"){if(n=JSON.parse(I),typeof n!="object")throw new Error("Invalid MCP configuration: must be an object");if(n===null||!("mcpServers"in n)||typeof n.mcpServers!="object")throw new Error("Invalid MCP configuration: missing or invalid mcpServers property");this.config=n}else this.config=I;this.disabledServers=new Set(l||[]),this.registry=new Rq(this.logger),this.processor=new yq(this.logger,this.registry,{mcp3pEnabled:!0,remoteEnabled:!0})}registry;processor;config;startServersPromise=null;allTools=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.allTools=null}async getTools(e,I,l){if(!this.allTools){await this.startServers();let n=new F9(e,I,l),c=[];for(let a of Object.keys(this.registry.clients)){let s=await n.loadTools({mcpClient:this.registry.clients[a],clientName:a,tools:this.config.mcpServers[a]?.tools||["*"],filterMapping:this.config.mcpServers[a]?.filterMapping||"hidden_characters"});c.push(...s)}this.allTools=c}return this.allTools}getConfig(){return this.config}async startServer(e,I){await this.startServers(),this.config.mcpServers[e]=I,await this.processor.processServer(e,I),this.allTools=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.allTools=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.allTools=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.allTools=null}async startBuiltInServer(e){}getServerConfig(e){return this.config.mcpServers[e]}};G();var RKe=rn(VKe(),1);async function tKI(t={}){let e=await uZe();return hZe((0,RKe.default)({},e,t))}async function yKe(t={}){if(Bx())throw new Error("Settings have already been initialized");return tKI(t)}G();async function NV(t,e,I){if(!t||t.length===0)return;let l=!1,n={};for(let c of t)try{let a=await c(e);a&&(l=!0,n={...n,...a})}catch(a){I.error(`Hook execution failed: ${a}`)}return l?n:void 0}G();var t1=class{sessionId;startTime;events=[];_chatMessages=[];_selectedModel;logger;eventCallbacks=[];constructor({sessionId:e,startTime:I,logger:l}={}){this.sessionId=e||kb(),this.startTime=I||new Date,this.logger=l||new ai}static 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 ai});n._selectedModel=l.data.selectedModel,n.events.push(l);for(let c=1;c<e.length;c++){let a=e[c];n.events.push(a),n.processEventForState(a)}return n}addEvent(e){let I=e.id||kb(),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.processEventForState(c),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)}}get chatMessages(){return this._chatMessages}get selectedModel(){return this._selectedModel}setSelectedModel(e){let I=this._selectedModel;this._selectedModel=e,this.addEvent({type:"session.model_change",data:{previousModel:I,newModel:e}})}getChatContextMessages(){return this._chatMessages.filter(e=>e.role!=="system")}getSystemContextMessages(){return this._chatMessages.filter(e=>e.role==="system")}getLastEventId(){return this.events.length===0?null:this.events[this.events.length-1].id}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":this._chatMessages.push({role:"user",content:e.data.content});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":{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.resume":case"session.error":case"session.info":case"session.import_legacy":case"assistant.turn_start":case"assistant.turn_end":case"assistant.usage":case"abort":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)}`)}}};var Cq=class{static name="Copilot";static description="Base Copilot Agent";options;logger;workingDir;session;constructor(e){this.options=e,this.logger=e.logger||new ai,this.workingDir=e.workingDirectory||process.cwd(),this.session=e.session||new t1,ybe(this.workingDir).then(I=>{if(I.found)return MUe(I.gitRoot,!0,this.workingDir)}).catch(I=>{this.logger.debug(`Failed to initialize custom instructions cache: ${I}`)})}async*query(e){let I=new Map,l;try{if(this.options.mcpServers&&Object.keys(this.options.mcpServers).length>0)try{l=new Fq(this.logger,{mcpServers:this.options.mcpServers},this.options.disabledTools),await l.startServers()}catch(Ze){this.logger.error(`Failed to initialize MCP host: ${Ze}`)}let n={timestamp:Date.now(),cwd:this.workingDir,prompt:e},a=(await NV(this.options.hooks?.userPromptSubmitted,n,this.logger))?.modifiedPrompt??e;this.session.addEvent({type:"user.message",data:{content:a}});let r=new WF().setProblemStatement(a).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();pZe();let o=await yKe(r),d=o.service?.agent?.model,i=Ime(d),h=i.agent,p=i.model?{model:i.model}:void 0,Z=coe(o,this.logger,h,p),u={location:this.workingDir,timeout:3e4,requireReasoning:!0,toolPartialResultCallback:void 0,permissions:this.options.requestPermission?{requestRequired:!0,request:this.options.requestPermission}:{requestRequired:!1},shellConfig:process.platform==="win32"?Ci.powerShell:Ci.bash},N=await HOe(u,this.logger),Y=[];if(l)try{Y=await l.getTools(o,this.logger,u.permissions)}catch(Ze){this.logger.error(`Failed to get MCP tools: ${Ze}`)}let y=[...N,...Y],Q=this.applyToolFiltering(y,this.options.allowedTools,this.options.disabledTools),A=await ybe(this.workingDir),H={...(vOe()["sweagent-capi"]?.["claude-sonnet-4"]??EOe()).supports,reasoning:!0},v=await iOe(A.found?A.gitRoot:"",qke(),this.workingDir,{},H,u,Q,void 0),ce=this.session.chatMessages.slice(0,-1),Re={role:"user",content:hOe(a,H)},Xe=[...ce,Re],He={timestamp:Date.now(),cwd:this.workingDir,source:"new",initialPrompt:e};await NV(this.options.hooks?.sessionStart,He,this.logger);let ie=Z.getCompletionWithTools(v,Xe,Q,{failIfInitialInputsTooLong:!1,processors:{preRequest:[new NE(Re,this.logger)]},executeToolsInParallel:!1,abortSignal:this.options.abortController?.signal});for await(let Ze of ie){if(this.options.abortController?.signal.aborted){yield{type:"error",error:new Error("Operation was cancelled")};return}let II=await this.translateEvent(Ze,I);for(let Je of II)Je.type==="message"&&Je.role==="assistant"&&this.session.addEvent({type:"assistant.message",data:{messageId:`msg-${Date.now()}`,content:Je.content}}),yield Je}yield{type:"complete"}}catch(n){let c={timestamp:Date.now(),cwd:this.workingDir,reason:"error",error:n instanceof Error?n:new Error(String(n))};await NV(this.options.hooks?.sessionEnd,c,this.logger),yield{type:"error",error:n instanceof Error?n:new Error(String(n))}}finally{let n={timestamp:Date.now(),cwd:this.workingDir,reason:"complete"};if(await NV(this.options.hooks?.sessionEnd,n,this.logger),l)try{await l.stopServers(),this.logger.log("MCP host stopped successfully")}catch(c){this.logger.error(`Error stopping MCP host: ${c}`)}}}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}async translateEvent(e,I){switch(e.kind){case"message":{if(c6(e)&&e.message.content)return[{type:"message",content:typeof e.message.content=="string"?e.message.content:"",role:"assistant"}];if(FOe(e)){let l=[];for(let n of e.message.tool_calls){let c=TA(n.function.arguments);I.set(n.id,n.function.name);let a={timestamp:Date.now(),cwd:this.workingDir,toolName:n.function.name,toolArgs:c},r=(await NV(this.options.hooks?.preToolUse,a,this.logger))?.modifiedArgs??c;l.push({type:"tool_use",toolName:n.function.name,args:r,toolCallId:n.id})}return l}return[]}case"response":return[];case"model_call_failure":{let l=new Error(e.modelCall?.error||"Model call failed"),n={timestamp:Date.now(),cwd:this.workingDir,error:l,errorContext:"model_call",recoverable:!0};return await NV(this.options.hooks?.errorOccurred,n,this.logger),[{type:"error",error:l}]}case"tool_execution":{let l=I.get(e.toolCallId)||"unknown",n={timestamp:Date.now(),cwd:this.workingDir,toolName:l,toolArgs:{},toolResult:e.toolResult},a=(await NV(this.options.hooks?.postToolUse,n,this.logger))?.modifiedResult??e.toolResult;return[{type:"tool_result",toolName:l,result:a,toolCallId:e.toolCallId}]}default:return[]}}};G();G();var Ope=class{loggers;constructor(e){this.loggers=e}isDebug(){return this.loggers.some(e=>e.isDebug())}debug(e){this.loggers.forEach(I=>I.debug(e))}log(e){this.loggers.forEach(I=>I.log(e))}info(e){this.loggers.forEach(I=>I.info(e))}notice(e){this.loggers.forEach(I=>I.notice(e))}warning(e){this.loggers.forEach(I=>I.warning(e))}error(e){this.loggers.forEach(I=>I.error(e))}startGroup(e,I){this.loggers.forEach(l=>l.startGroup(e,I))}endGroup(e){this.loggers.forEach(I=>I.endGroup(e))}};G();import{appendFile as lKI,access as nKI,mkdir as cKI}from"fs/promises";import{constants as aKI}from"fs";import{dirname as sKI}from"path";var Mpe=class extends Gp{constructor(I,l,n){super(l,n);this.filePath=I;this.writeQueue=rKI(sKI(this.filePath)).catch(()=>{})}writeQueue=Promise.resolve();log(I){this.write("LOG",I)}debug(I){super.shouldLog(8)&&this.write("DEBUG",this.filterSecrets(I).toString())}info(I){super.shouldLog(4)&&this.write("INFO",this.filterSecrets(I).toString())}notice(I){super.shouldLog(2)&&this.write("NOTICE",this.filterSecrets(I).toString())}warning(I){super.shouldLog(2)&&this.write("WARNING",this.filterSecrets(I).toString())}error(I){super.shouldLog(1)&&this.write("ERROR",this.filterSecrets(I).toString())}startGroup(I,l){super.shouldLog(l||4)&&this.write("START-GROUP",I)}endGroup(I){super.shouldLog(I||4)&&this.write("END-GROUP","")}write(I,l){let c=`${new Date().toISOString()} [${I}] ${l}
1351
1351
  `;this.writeQueue=this.writeQueue.then(()=>this.performWrite(c)).catch(()=>{})}async performWrite(I){await lKI(this.filePath,I)}};async function rKI(t){try{await nKI(t,aKI.F_OK)}catch{await cKI(t,{recursive:!0})}}G();async function*k7l(t){let{prompt:e,...I}=t;yield*new Cq(I).query(e)}G();var FKe=class{sessions;logger;lastAccessedSessionId;constructor({logger:e}={}){this.sessions=new Map,this.logger=e||new ai}async createSession(){let e=new t1({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}))}async saveSession(e){}async deleteSession(e){this.sessions.delete(e.sessionId),this.lastAccessedSessionId===e.sessionId&&(this.lastAccessedSessionId=void 0)}};export{Cq as Agent,Gp as BaseLogger,Ope as CompoundLogger,qV as ConsoleLogger,Mpe as FileLogger,ai as NoopLogger,t1 as Session,FKe as SessionManager,NV as executeHooks,a1 as isDebugEnvironment,k7l as query};
1352
1352
  /*! Bundled license information:
1353
1353