@github/copilot 0.0.333 → 0.0.334-0

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
@@ -1541,7 +1541,7 @@ Answer:
1541
1541
  `}var NSl=tWe.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function WSl(){let t={};for(let e of NSl){let l=tWe.env[e];l!==void 0&&(l.startsWith("()")||(t[e]=l))}return t}var eWe=class{constructor(e){this._abortController=new AbortController,this._readBuffer=new $Ne,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new ZSl)}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 I,n,r,a,s;this._process=(0,rEt.default)(this._serverParams.command,(I=this._serverParams.args)!==null&&I!==void 0?I:[],{env:{...WSl(),...this._serverParams.env},stdio:["pipe","pipe",(n=this._serverParams.stderr)!==null&&n!==void 0?n:"inherit"],shell:!1,signal:this._abortController.signal,windowsHide:tWe.platform==="win32"&&gSl(),cwd:this._serverParams.cwd}),this._process.on("error",o=>{var d,G;if(o.name==="AbortError"){(d=this.onclose)===null||d===void 0||d.call(this);return}l(o),(G=this.onerror)===null||G===void 0||G.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 I=this._readBuffer.readMessage();if(I===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,I)}catch(I){(l=this.onerror)===null||l===void 0||l.call(this,I)}}async close(){this._abortController.abort(),this._process=void 0,this._readBuffer.clear()}send(e){return new Promise(l=>{var I;if(!(!((I=this._process)===null||I===void 0)&&I.stdin))throw new Error("Not connected");let n=nEt(e);this._process.stdin.write(n)?l():this._process.stdin.once("drain",l)})}};function gSl(){return"type"in tWe}c();c();var lWe=class extends TransformStream{constructor({onError:e,onRetry:l,onComment:I}={}){let n;super({start(r){n=MNe({onEvent:a=>{r.enqueue(a)},onError(a){e==="terminate"?r.error(a):typeof e=="function"&&e(a)},onRetry:l,onComment:I})},transform(r){n.feed(r)}})}};var ASl={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Xne=class extends Error{constructor(e,l){super(`Streamable HTTP error: ${l}`),this.code=e}},IWe=class{constructor(e,l){var I;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=(I=l?.reconnectionOptions)!==null&&I!==void 0?I:ASl}async _authThenStart(){var e;if(!this._authProvider)throw new NN("No auth provider");let l;try{l=await Lf(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(I){throw(e=this.onerror)===null||e===void 0||e.call(this,I),I}if(l!=="AUTHORIZED")throw new NN;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let l={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(l.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(l["mcp-session-id"]=this._sessionId),this._protocolVersion&&(l["mcp-protocol-version"]=this._protocolVersion);let I=this._normalizeHeaders((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...l,...I})}async _startOrAuthSse(e){var l,I,n;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:(I=this._abortController)===null||I===void 0?void 0:I.signal});if(!s.ok){if(s.status===401&&this._authProvider)return await this._authThenStart();if(s.status===405)return;throw new Xne(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 l=this._reconnectionOptions.initialReconnectionDelay,I=this._reconnectionOptions.reconnectionDelayGrowFactor,n=this._reconnectionOptions.maxReconnectionDelay;return Math.min(l*Math.pow(I,e),n)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,l=0){var I;let n=this._reconnectionOptions.maxRetries;if(n>0&&l>=n){(I=this.onerror)===null||I===void 0||I.call(this,new Error(`Maximum reconnection attempts (${n}) 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,I){if(!e)return;let{onresumptiontoken:n,replayMessageId:r}=l,a;(async()=>{var o,d,G,u;try{let h=e.pipeThrough(new TextDecoderStream).pipeThrough(new lWe).getReader();for(;;){let{value:W,done:y}=await h.read();if(y)break;if(W.id&&(a=W.id,n?.(W.id)),!W.event||W.event==="message")try{let R=Ff.parse(JSON.parse(W.data));r!==void 0&&BIe(R)&&(R.id=r),(o=this.onmessage)===null||o===void 0||o.call(this,R)}catch(R){(d=this.onerror)===null||d===void 0||d.call(this,R)}}}catch(h){if((G=this.onerror)===null||G===void 0||G.call(this,new Error(`SSE stream disconnected: ${h}`)),I&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:n,replayMessageId:r},0)}catch(W){(u=this.onerror)===null||u===void 0||u.call(this,new Error(`Failed to reconnect: ${W instanceof Error?W.message:String(W)}`))}}})()}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 NN("No auth provider");if(await Lf(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new NN("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 I,n,r,a;try{let{resumptionToken:s,onresumptiontoken:o}=l||{};if(s){this._startOrAuthSse({resumptionToken:s,replayMessageId:tNe(e)?e.id:void 0}).catch(V=>{var F;return(F=this.onerror)===null||F===void 0?void 0:F.call(this,V)});return}let d=await this._commonHeaders();d.set("content-type","application/json"),d.set("accept","application/json, text/event-stream");let G={...this._requestInit,method:"POST",headers:d,body:JSON.stringify(e),signal:(I=this._abortController)===null||I===void 0?void 0:I.signal},u=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._url,G),h=u.headers.get("mcp-session-id");if(h&&(this._sessionId=h),!u.ok){if(u.status===401&&this._authProvider){if(this._resourceMetadataUrl=Hne(u),await Lf(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new NN;return this.send(e)}let V=await u.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${u.status}): ${V}`)}if(u.status===202){uyt(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(V=>{var F;return(F=this.onerror)===null||F===void 0?void 0:F.call(this,V)});return}let y=(Array.isArray(e)?e:[e]).filter(V=>"method"in V&&"id"in V&&V.id!==void 0).length>0,R=u.headers.get("content-type");if(y)if(R?.includes("text/event-stream"))this._handleSseStream(u.body,{onresumptiontoken:o},!1);else if(R?.includes("application/json")){let V=await u.json(),F=Array.isArray(V)?V.map(f=>Ff.parse(f)):[Ff.parse(V)];for(let f of F)(r=this.onmessage)===null||r===void 0||r.call(this,f)}else throw new Xne(-1,`Unexpected content type: ${R}`)}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,I;if(this._sessionId)try{let n=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:n,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 Xne(a.status,`Failed to terminate session: ${a.statusText}`);this._sessionId=void 0}catch(n){throw(I=this.onerror)===null||I===void 0||I.call(this,n),n}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}};c();var nWe=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 dxe(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?.())}},dxe=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 rWe=class{createTransport(e){switch(e.type){case"stdio":{let l=new eWe({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 IWe(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"sse":return new KNe(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"memory":return new nWe(e.server);default:throw new Error(`Unsupported transport type: ${e.type}`)}}};c();var bx="blackbird-mcp-server",ID="github-mcp-server",mxe="playwright";function nD(t){return t.type===void 0||t.type.toLowerCase()==="local"||t.type.toLowerCase()==="stdio"}function rD(t){return fne(t)||Jne(t)}function fne(t){return t.type?.toLowerCase()==="http"}function Jne(t){return t.type?.toLowerCase()==="sse"}function kne(t){return t.type?.toLowerCase()==="memory"}var Gxe=class extends ySl{constructor(l,I){super({decodeStrings:!1});this.serverName=l;this.logger=I}_write(l,I,n){try{let r=l.toString();this.logger.log(`[mcp server ${this.serverName} stderr] ${r}`),n()}catch(r){n(r instanceof Error?r:new Error(String(r)))}}},aWe=class{constructor(e,l=new _Ne,I=new rWe){this.logger=e;this.clientFactory=l;this.transportFactory=I}clients={};transports={};async startLocalMcpClient(e,l,I,n){this.logger.log(`Starting MCP client for ${e} with command: ${I} and args: ${n}`);let r=new Gxe(e,this.logger),a={type:"stdio",command:I,args:n,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 I={type:"http",url:l.url,headers:l.headers},n=this.transportFactory.createTransport(I);await this.setupAndConnectClient(e,n)}async startSseMcpClient(e,l){this.logger.log(`Starting remote MCP client for ${e} with url: ${l.url}`);let I={type:"sse",url:l.url,headers:l.headers},n=this.transportFactory.createTransport(I);await this.setupAndConnectClient(e,n)}async startInMemoryMcpClient(e,l){this.logger.log(`Starting in-memory MCP client for ${e}`);let I={type:"memory",server:l},n=this.transportFactory.createTransport(I);await this.setupAndConnectClient(e,n)}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 I=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 I.connect(l),I.onclose=()=>{this.logger.log(`MCP client for ${e} closed`),delete this.clients[e]},I.onerror=r=>{this.logger.error(`MCP client for ${e} errored ${r}`)},this.logger.log(`MCP client for ${e} connected, took ${Date.now()-n}ms`),this.clients[e]=I}async getTools(e,l){let I={};for(let[n,r]of Object.entries(this.clients)){let a=[];try{this.logger.log(`Fetching tools from client: ${n}`);let s=await r.listTools(),o=e?.mcpServers[n].tools,d=e?.mcpServers[n].filterMapping;for(let u of s.tools){if(u.name==="get_copilot_space")continue;if(!(o?.includes("*")||o?.includes(u.name))){this.logger.log(`Tool ${u.name} is not in the allowed list for client: ${n}`);continue}let W=obe(n,u.name),y=`${n}-${u.name}`,R;typeof d=="string"?R=sCe(d):R=sCe(d?.[u.name]??"hidden_characters"),I[`${n}/${u.name}`]={name:y,title:u.title??u.annotations?.title??u.name,description:u.description??y,input_schema:u.inputSchema,readOnly:u.annotations?.readOnlyHint,safeForTelemetry:{name:!!(e?.mcpServers[n].isDefaultServer||W),inputsNames:!!e?.mcpServers[n].isDefaultServer},filterMode:R},a.push(u.name),this.logger.log(`Tool ${u.name} added to tools list for client: ${n}`)}this.logger.log(`Successfully retrieved ${a.length} tools from client: ${n}`);let G=r.getServerVersion();await this.logServerSuccessWithTools(n,a,G,l)}catch(s){this.logger.error(`Failed to get tools from client: ${n} ${s}`)}}return this.logger.log(`All tools retrieved: ${JSON.stringify(I,null,2)}`),I}async logServerSuccessWithTools(e,l,I,n){if(e!=bx&&n)try{let r=l.map(o=>`- ${o}`).join(`
1542
1542
  `),s=`MCP server started successfully${I?` (version ${I.version})`:""} with ${l.length} ${l.length===1?"tool":"tools"} - for the full output, see the verbose logs
1543
1543
 
1544
- ${r}`;await n.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 bxe={mcpServers:{}},sWe=class{constructor(e,l,I){this.logger=e;this.registry=l;this.remoteEnabled=I?.remoteEnabled??!1,this.mcp3pEnabled=I?.mcp3pEnabled??!1,this.blackbirdMetisIndexEnabled=I?.blackbirdMetisIndexEnabled??!1,this.sessionClient=I?.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"),bxe;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"),bxe;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}`),bxe}}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 I="repos,issues,users,pull_requests,code_security,secret_protection,actions";process.env.COPILOT_MCP_COPILOT_SPACES_ENABLED==="true"&&(this.logger.log("Enabling Copilot Spaces in GitHub MCP server configuration"),I=I+",copilot_spaces");let n={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":I,"X-MCP-Host":"github-coding-agent","X-Initiator":"agent"};l&&l.api?.copilot?.integrationId&&(n["Copilot-Integration-Id"]=l.api.copilot.integrationId),process.env.GITHUB_COPILOT_INTERACTION_ID&&(n["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let r={type:"http",url:this.getCapiMcpUrl(),headers:n,tools:["*"],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[ID]=r}configureLocalGitHubMcp(e){if(e.mcpServers[ID]){this.logger.log("Using user-provided GitHub MCP server configuration");let l=e.mcpServers[ID]??{};nD(l)&&!l.command&&(e.mcpServers[ID]={...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[ID]=l}}configurePlaywrightMcp(e){if(!e.mcpServers[mxe]){if((process.env.COPILOT_FEATURE_FLAGS??"").split(",").map(I=>I.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:[...TCe,"--allowed-origins","localhost;localhost:*;127.0.0.1;127.0.0.1:*"],tools:["*"],isDefaultServer:!0};e.mcpServers[mxe]=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 I=process.env.AGENT_DIR||"/agent";this.logger.log(`Using agent directory: ${I}`);let n=[];l.blackbird?.mode==="tool"&&(n=["*"]),this.logger.log(`Using blackbird Metis server: ${l.blackbird?.mode}`);let r={command:`${I}/blackbird/mcp`,args:["serve","--index",`${I}/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[bx]=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 I={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[bx]=I}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 I={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&&(I["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let n={type:"http",url:this.getCapiMcpUrl(),headers:I,tools:l,isDefaultServer:!0};e.mcpServers[bx]=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 nD(e)||fne(e)||Jne(e)||kne(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&&!nD(l)&&!kne(l)?(this.logger.error(`Unsupported server type "${l.type}" for server "${e}". Only "Local", "STDIO", or "Memory" are supported.`),!1):l.tools?nD(l)&&!this.isValidLocalServerConfig(l)?(this.logger.error(`Invalid local server configuration for "${e}". Please ensure 'command' and 'args' are provided.`),!1):(fne(l)||Jne(l))&&!this.isValidRemoteServerConfig(l)?(this.logger.error(`Invalid remote server configuration for "${e}". Please ensure 'url' is provided.`),!1):kne(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 I=this.resolveHeaders(l.headers,process.env),n={...l,headers:I};await this.registry.startHttpMcpClient(e,n),this.logger.log(`Started MCP client for remote server ${e}`)}catch(I){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${I}`),I}}async processSseServer(e,l){try{let I=this.resolveHeaders(l.headers,process.env),n={...l,headers:I};await this.registry.startSseMcpClient(e,n),this.logger.log(`Started MCP client for remote server ${e}`)}catch(I){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${I}`),I}}async processInMemoryServer(e,l){try{await this.registry.startInMemoryMcpClient(e,l.serverInstance),this.logger.log(`Started in-memory MCP client for ${e}`)}catch(I){throw this.logger.error(`Failed to start in-memory MCP client for ${e}: ${I}`),I}}async processLocalServer(e,l){let I={...l};if(l.command==="python")try{I=await this.convertPythonToPipx(I)}catch(a){this.logger.error(`Failed to handle Python module for ${e}: ${a}`)}let n=this.buildEnvironment(I),r=this.resolveArray(I.args,n);this.logger.log(`Starting MCP client for ${e} with command: ${I.command} and args: ${r}`);try{await this.registry.startLocalMcpClient(e,n,I.command,r),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,I=l.indexOf("-m");if(I===-1||I===l.length-1)throw new Error("Python command with -m flag must specify a module");let n=l[I+1];this.logger.log(`Converting Python module: ${n} to pipx command`);let r=["run",n];for(let a=I+2;a<l.length;a++)r.push(l[a]);for(let a=0;a<I;a++)r.push(l[a]);return{...e,command:"pipx",args:r}}buildEnvironment(e){let l={};if(e.env)for(let[I,n]of Object.entries(e.env)){let r=n.trim();process.env[r]!==void 0&&(l[I]=process.env[r])}return l}resolveArray(e,l){return e?l?e.map(I=>I.replace(/\$([A-Z0-9_]+)/g,(n,r)=>l[r]||n)):e:[]}resolveHeaders(e,l){if(!e)return{};if(!l)return e;let I={};for(let[n,r]of Object.entries(e)){let a=this.resolveArray([r],l);I[n]=a[0]}return I}async processServers(e){if(!e)throw new Error("No servers to process");for(let[l,I]of Object.entries(e.mcpServers))await this.processServer(l,I)}async processServer(e,l){if(!this.validateServerConfig(e,l)){this.logger.error(`Skipping server "${e}" due to invalid configuration.`);return}try{nD(l)?await this.processLocalServer(e,l):fne(l)&&this.remoteEnabled?await this.processHttpServer(e,l):Jne(l)&&this.remoteEnabled?await this.processSseServer(e,l):kne(l)&&await this.processInMemoryServer(e,l)}catch(I){e!==bx&&await this.logServerFailure(e,I)}}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(I){this.logger.error(`Failed to log failure for MCP Server '${e}': '${I}'`)}}};var oWe=class{constructor(e,l,I){this.logger=e;let n;if(typeof l=="string"){if(n=JSON.parse(l),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=l;this.disabledServers=new Set(I||[]),this.registry=new aWe(this.logger),this.processor=new sWe(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[I,n]of Object.entries(this.config.mcpServers))this.disabledServers.has(I)?this.logger.log(`Skipping disabled MCP server: ${I}`):l[I]=n;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(I){this.logger.error(`Error closing transport for ${e}: ${I}`)}this.startServersPromise=null,this.allTools=null}async getTools(e,l,I){if(!this.allTools){await this.startServers();let n=new _$(e,l,I),r=[];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"});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(I){this.logger.error(`Error closing transport for ${e}: ${I}`)}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 RSl="/login/device/code",ESl="/login/oauth/access_token",aEt="Ov23ctDVkRmgkPke0Mmm",v2="https://github.com",xf=class extends Error{constructor(l,I){super(I);this.status=l;this.message=I;this.name="GitHubApiError"}};function sEt(t){let e=new URL(t);return e.hostname.startsWith("api.")||(e.hostname="api."+e.hostname),e.href}async function oEt(t){let e=new URL(RSl,t),l=await fetch(e.href,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({client_id:aEt,scope:"user:email,read:user,repo,workflow"})});if(!l.ok)throw new xf(l.status,`Failed to request device code: ${l.statusText}`);return await l.json()}async function cEt(t,e){let l=new URL(ESl,t),I=await fetch(l.href,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({client_id:aEt,device_code:e,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})});if(!I.ok)throw new xf(I.status,`Failed to authorize: ${I.statusText}`);let n=await I.json();if(typeof n.access_token=="string")return n.access_token;if(n.error!=="authorization_pending"&&n.error!=="slow_down")throw new Error(n.error_description||`Unexpected error: ${n.error}`)}async function aD(t,e){let l=new URL("/user",sEt(t)),I=await fetch(l.href,{headers:{Authorization:`Bearer ${e}`,Accept:"application/json"}});if(!I.ok)throw new xf(I.status,`Failed to fetch user info: ${I.statusText}`);return(await I.json()).login}async function sD(t,e){let l=`
1544
+ ${r}`;await n.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 bxe={mcpServers:{}},sWe=class{constructor(e,l,I){this.logger=e;this.registry=l;this.remoteEnabled=I?.remoteEnabled??!1,this.mcp3pEnabled=I?.mcp3pEnabled??!1,this.blackbirdMetisIndexEnabled=I?.blackbirdMetisIndexEnabled??!1,this.sessionClient=I?.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"),bxe;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"),bxe;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}`),bxe}}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 I="repos,issues,users,pull_requests,code_security,secret_protection,actions";process.env.COPILOT_MCP_COPILOT_SPACES_ENABLED==="true"&&(this.logger.log("Enabling Copilot Spaces in GitHub MCP server configuration"),I=I+",copilot_spaces");let n={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":I,"X-MCP-Host":"github-coding-agent","X-Initiator":"agent"};l&&l.api?.copilot?.integrationId&&(n["Copilot-Integration-Id"]=l.api.copilot.integrationId),process.env.GITHUB_COPILOT_INTERACTION_ID&&(n["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let r={type:"http",url:this.getCapiMcpUrl(),headers:n,tools:["*"],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[ID]=r}configureLocalGitHubMcp(e){if(e.mcpServers[ID]){this.logger.log("Using user-provided GitHub MCP server configuration");let l=e.mcpServers[ID]??{};nD(l)&&!l.command&&(e.mcpServers[ID]={...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[ID]=l}}configurePlaywrightMcp(e){if(!e.mcpServers[mxe]){if((process.env.COPILOT_FEATURE_FLAGS??"").split(",").map(I=>I.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:[...TCe,"--allowed-origins","localhost;localhost:*;127.0.0.1;127.0.0.1:*"],tools:["*"],isDefaultServer:!0};e.mcpServers[mxe]=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 I=process.env.AGENT_DIR||"/agent";this.logger.log(`Using agent directory: ${I}`);let n=[];l.blackbird?.mode==="tool"&&(n=["*"]),this.logger.log(`Using blackbird Metis server: ${l.blackbird?.mode}`);let r={command:`${I}/blackbird/mcp`,args:["serve","--index",`${I}/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[bx]=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 I={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[bx]=I}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 I={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&&(I["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let n={type:"http",url:this.getCapiMcpUrl(),headers:I,tools:l,isDefaultServer:!0};e.mcpServers[bx]=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 nD(e)||fne(e)||Jne(e)||kne(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&&!nD(l)&&!kne(l)?(this.logger.error(`Unsupported server type "${l.type}" for server "${e}". Only "Local", "STDIO", or "Memory" are supported.`),!1):l.tools?nD(l)&&!this.isValidLocalServerConfig(l)?(this.logger.error(`Invalid local server configuration for "${e}". Please ensure 'command' and 'args' are provided.`),!1):(fne(l)||Jne(l))&&!this.isValidRemoteServerConfig(l)?(this.logger.error(`Invalid remote server configuration for "${e}". Please ensure 'url' is provided.`),!1):kne(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 I=this.resolveHeaders(l.headers,process.env),n={...l,headers:I};await this.registry.startHttpMcpClient(e,n),this.logger.log(`Started MCP client for remote server ${e}`)}catch(I){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${I}`),I}}async processSseServer(e,l){try{let I=this.resolveHeaders(l.headers,process.env),n={...l,headers:I};await this.registry.startSseMcpClient(e,n),this.logger.log(`Started MCP client for remote server ${e}`)}catch(I){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${I}`),I}}async processInMemoryServer(e,l){try{await this.registry.startInMemoryMcpClient(e,l.serverInstance),this.logger.log(`Started in-memory MCP client for ${e}`)}catch(I){throw this.logger.error(`Failed to start in-memory MCP client for ${e}: ${I}`),I}}async processLocalServer(e,l){let I={...l};if(l.command==="python")try{I=await this.convertPythonToPipx(I)}catch(a){this.logger.error(`Failed to handle Python module for ${e}: ${a}`)}let n=this.buildEnvironment(I),r=this.resolveArray(I.args,n);this.logger.log(`Starting MCP client for ${e} with command: ${I.command} and args: ${r}`);try{await this.registry.startLocalMcpClient(e,n,I.command,r),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,I=l.indexOf("-m");if(I===-1||I===l.length-1)throw new Error("Python command with -m flag must specify a module");let n=l[I+1];this.logger.log(`Converting Python module: ${n} to pipx command`);let r=["run",n];for(let a=I+2;a<l.length;a++)r.push(l[a]);for(let a=0;a<I;a++)r.push(l[a]);return{...e,command:"pipx",args:r}}buildEnvironment(e){let l={};if(e.env)for(let[I,n]of Object.entries(e.env)){let r=n.trim();process.env[r]!==void 0&&(l[I]=process.env[r])}return l}resolveArray(e,l){return e?l?e.map(I=>I.replace(/\$([A-Z0-9_]+)/g,(n,r)=>l[r]||n)):e:[]}resolveHeaders(e,l){if(!e)return{};if(!l)return e;let I={};for(let[n,r]of Object.entries(e)){let a=this.resolveArray([r],l);I[n]=a[0]}return I}async processServers(e){if(!e)throw new Error("No servers to process");let l=Object.entries(e.mcpServers).map(([I,n])=>this.processServer(I,n));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{nD(l)?await this.processLocalServer(e,l):fne(l)&&this.remoteEnabled?await this.processHttpServer(e,l):Jne(l)&&this.remoteEnabled?await this.processSseServer(e,l):kne(l)&&await this.processInMemoryServer(e,l)}catch(I){e!==bx&&await this.logServerFailure(e,I)}}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(I){this.logger.error(`Failed to log failure for MCP Server '${e}': '${I}'`)}}};var oWe=class{constructor(e,l,I){this.logger=e;let n;if(typeof l=="string"){if(n=JSON.parse(l),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=l;this.disabledServers=new Set(I||[]),this.registry=new aWe(this.logger),this.processor=new sWe(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[I,n]of Object.entries(this.config.mcpServers))this.disabledServers.has(I)?this.logger.log(`Skipping disabled MCP server: ${I}`):l[I]=n;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(I){this.logger.error(`Error closing transport for ${e}: ${I}`)}this.startServersPromise=null,this.allTools=null}async getTools(e,l,I){if(!this.allTools){await this.startServers();let n=new _$(e,l,I),r=[];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"});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(I){this.logger.error(`Error closing transport for ${e}: ${I}`)}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 RSl="/login/device/code",ESl="/login/oauth/access_token",aEt="Ov23ctDVkRmgkPke0Mmm",v2="https://github.com",xf=class extends Error{constructor(l,I){super(I);this.status=l;this.message=I;this.name="GitHubApiError"}};function sEt(t){let e=new URL(t);return e.hostname.startsWith("api.")||(e.hostname="api."+e.hostname),e.href}async function oEt(t){let e=new URL(RSl,t),l=await fetch(e.href,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({client_id:aEt,scope:"user:email,read:user,repo,workflow"})});if(!l.ok)throw new xf(l.status,`Failed to request device code: ${l.statusText}`);return await l.json()}async function cEt(t,e){let l=new URL(ESl,t),I=await fetch(l.href,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({client_id:aEt,device_code:e,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})});if(!I.ok)throw new xf(I.status,`Failed to authorize: ${I.statusText}`);let n=await I.json();if(typeof n.access_token=="string")return n.access_token;if(n.error!=="authorization_pending"&&n.error!=="slow_down")throw new Error(n.error_description||`Unexpected error: ${n.error}`)}async function aD(t,e){let l=new URL("/user",sEt(t)),I=await fetch(l.href,{headers:{Authorization:`Bearer ${e}`,Accept:"application/json"}});if(!I.ok)throw new xf(I.status,`Failed to fetch user info: ${I.statusText}`);return(await I.json()).login}async function sD(t,e){let l=`
1545
1545
  {
1546
1546
  viewer {
1547
1547
  copilotEndpoints {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@github/copilot",
3
3
  "description": "GitHub Copilot CLI brings the power of Copilot coding agent directly to your terminal.",
4
- "version": "0.0.333",
4
+ "version": "0.0.334-0",
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": "4cbf3da"
36
+ "gitCommit": "739eb8b"
37
37
  },
38
38
  "dependencies": {
39
39
  "node-pty": "npm:@devm33/node-pty@^1.0.8",
package/sdk/index.js CHANGED
@@ -1125,7 +1125,7 @@ Answer:
1125
1125
  `}var B3e=jK.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function z3e(){let t={};for(let I of B3e){let e=jK.env[I];e!==void 0&&(e.startsWith("()")||(t[I]=e))}return t}var TK=class{constructor(I){this._abortController=new AbortController,this._readBuffer=new MK,this._stderrStream=null,this._serverParams=I,(I.stderr==="pipe"||I.stderr==="overlapped")&&(this._stderrStream=new x3e)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((I,e)=>{var l,c,n,a,s;this._process=(0,_zI.default)(this._serverParams.command,(l=this._serverParams.args)!==null&&l!==void 0?l:[],{env:{...z3e(),...this._serverParams.env},stdio:["pipe","pipe",(c=this._serverParams.stderr)!==null&&c!==void 0?c:"inherit"],shell:!1,signal:this._abortController.signal,windowsHide:jK.platform==="win32"&&U3e(),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}e(r),(d=this.onerror)===null||d===void 0||d.call(this,r)}),this._process.on("spawn",()=>{I()}),this._process.on("close",r=>{var o;this._process=void 0,(o=this.onclose)===null||o===void 0||o.call(this)}),(n=this._process.stdin)===null||n===void 0||n.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 I,e;return this._stderrStream?this._stderrStream:(e=(I=this._process)===null||I===void 0?void 0:I.stderr)!==null&&e!==void 0?e:null}get pid(){var I,e;return(e=(I=this._process)===null||I===void 0?void 0:I.pid)!==null&&e!==void 0?e:null}processReadBuffer(){for(var I,e;;)try{let l=this._readBuffer.readMessage();if(l===null)break;(I=this.onmessage)===null||I===void 0||I.call(this,l)}catch(l){(e=this.onerror)===null||e===void 0||e.call(this,l)}}async close(){this._abortController.abort(),this._process=void 0,this._readBuffer.clear()}send(I){return new Promise(e=>{var l;if(!(!((l=this._process)===null||l===void 0)&&l.stdin))throw new Error("Not connected");let c=qzI(I);this._process.stdin.write(c)?e():this._process.stdin.once("drain",e)})}};function U3e(){return"type"in jK}G();G();var DK=class extends TransformStream{constructor({onError:I,onRetry:e,onComment:l}={}){let c;super({start(n){c=xK({onEvent:a=>{n.enqueue(a)},onError(a){I==="terminate"?n.error(a):typeof I=="function"&&I(a)},onRetry:e,onComment:l})},transform(n){c.feed(n)}})}};var S3e={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},P9=class extends Error{constructor(I,e){super(`Streamable HTTP error: ${e}`),this.code=I}},KK=class{constructor(I,e){var l;this._url=I,this._resourceMetadataUrl=void 0,this._requestInit=e?.requestInit,this._authProvider=e?.authProvider,this._fetch=e?.fetch,this._sessionId=e?.sessionId,this._reconnectionOptions=(l=e?.reconnectionOptions)!==null&&l!==void 0?l:S3e}async _authThenStart(){var I;if(!this._authProvider)throw new OG("No auth provider");let e;try{e=await MY(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(l){throw(I=this.onerror)===null||I===void 0||I.call(this,l),l}if(e!=="AUTHORIZED")throw new OG;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var I;let e={};if(this._authProvider){let c=await this._authProvider.tokens();c&&(e.Authorization=`Bearer ${c.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let l=this._normalizeHeaders((I=this._requestInit)===null||I===void 0?void 0:I.headers);return new Headers({...e,...l})}async _startOrAuthSse(I){var e,l,c;let{resumptionToken:n}=I;try{let a=await this._commonHeaders();a.set("Accept","text/event-stream"),n&&a.set("last-event-id",n);let s=await((e=this._fetch)!==null&&e!==void 0?e: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 P9(s.status,`Failed to open SSE stream: ${s.statusText}`)}this._handleSseStream(s.body,I,!0)}catch(a){throw(c=this.onerror)===null||c===void 0||c.call(this,a),a}}_getNextReconnectionDelay(I){let e=this._reconnectionOptions.initialReconnectionDelay,l=this._reconnectionOptions.reconnectionDelayGrowFactor,c=this._reconnectionOptions.maxReconnectionDelay;return Math.min(e*Math.pow(l,I),c)}_normalizeHeaders(I){return I?I instanceof Headers?Object.fromEntries(I.entries()):Array.isArray(I)?Object.fromEntries(I):{...I}:{}}_scheduleReconnection(I,e=0){var l;let c=this._reconnectionOptions.maxRetries;if(c>0&&e>=c){(l=this.onerror)===null||l===void 0||l.call(this,new Error(`Maximum reconnection attempts (${c}) exceeded.`));return}let n=this._getNextReconnectionDelay(e);setTimeout(()=>{this._startOrAuthSse(I).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(I,e+1)})},n)}_handleSseStream(I,e,l){if(!I)return;let{onresumptiontoken:c,replayMessageId:n}=e,a;(async()=>{var r,o,d,b;try{let h=I.pipeThrough(new TextDecoderStream).pipeThrough(new DK).getReader();for(;;){let{value:Z,done:p}=await h.read();if(p)break;if(Z.id&&(a=Z.id,c?.(Z.id)),!Z.event||Z.event==="message")try{let W=LY.parse(JSON.parse(Z.data));n!==void 0&&l9(W)&&(W.id=n),(r=this.onmessage)===null||r===void 0||r.call(this,W)}catch(W){(o=this.onerror)===null||o===void 0||o.call(this,W)}}}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:c,replayMessageId:n},0)}catch(Z){(b=this.onerror)===null||b===void 0||b.call(this,new Error(`Failed to reconnect: ${Z instanceof Error?Z.message:String(Z)}`))}}})()}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(I){if(!this._authProvider)throw new OG("No auth provider");if(await MY(this._authProvider,{serverUrl:this._url,authorizationCode:I,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new OG("Failed to authorize")}async close(){var I,e;(I=this._abortController)===null||I===void 0||I.abort(),(e=this.onclose)===null||e===void 0||e.call(this)}async send(I,e){var l,c,n,a;try{let{resumptionToken:s,onresumptiontoken:r}=e||{};if(s){this._startOrAuthSse({resumptionToken:s,replayMessageId:jD(I)?I.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(I),signal:(l=this._abortController)===null||l===void 0?void 0:l.signal},b=await((c=this._fetch)!==null&&c!==void 0?c:fetch)(this._url,d),h=b.headers.get("mcp-session-id");if(h&&(this._sessionId=h),!b.ok){if(b.status===401&&this._authProvider){if(this._resourceMetadataUrl=K9(b),await MY(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new OG;return this.send(I)}let N=await b.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${b.status}): ${N}`)}if(b.status===202){rfI(I)&&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 p=(Array.isArray(I)?I:[I]).filter(N=>"method"in N&&"id"in N&&N.id!==void 0).length>0,W=b.headers.get("content-type");if(p)if(W?.includes("text/event-stream"))this._handleSseStream(b.body,{onresumptiontoken:r},!1);else if(W?.includes("application/json")){let N=await b.json(),Y=Array.isArray(N)?N.map(F=>LY.parse(F)):[LY.parse(N)];for(let F of Y)(n=this.onmessage)===null||n===void 0||n.call(this,F)}else throw new P9(-1,`Unexpected content type: ${W}`)}catch(s){throw(a=this.onerror)===null||a===void 0||a.call(this,s),s}}get sessionId(){return this._sessionId}async terminateSession(){var I,e,l;if(this._sessionId)try{let c=await this._commonHeaders(),n={...this._requestInit,method:"DELETE",headers:c,signal:(I=this._abortController)===null||I===void 0?void 0:I.signal},a=await((e=this._fetch)!==null&&e!==void 0?e:fetch)(this._url,n);if(!a.ok&&a.status!==405)throw new P9(a.status,`Failed to terminate session: ${a.statusText}`);this._sessionId=void 0}catch(c){throw(l=this.onerror)===null||l===void 0||l.call(this,c),c}}setProtocolVersion(I){this._protocolVersion=I}get protocolVersion(){return this._protocolVersion}};G();var PK=class{constructor(I){this.server=I}onmessage;onerror;onclose;serverTransport;closed=!1;async start(){if(this.closed)throw new Error("Transport is closed");this.serverTransport=new gbI(this),await this.server.connect(this.serverTransport)}async send(I){if(this.closed)throw new Error("Transport is closed");setImmediate(()=>{try{this.serverTransport?.onmessage?.(I)}catch(e){this.onerror?.(e instanceof Error?e:new Error(String(e)))}})}receive(I){this.closed||this.onmessage?.(I)}async close(){this.closed||(this.closed=!0,await this.serverTransport?.close(),this.onclose?.())}},gbI=class{constructor(I){this.clientTransport=I}onmessage;onerror;onclose;closed=!1;async start(){}async send(I){if(this.closed)throw new Error("Transport is closed");setImmediate(()=>{try{this.clientTransport.receive(I)}catch(e){this.onerror?.(e instanceof Error?e:new Error(String(e)))}})}async close(){this.closed||(this.closed=!0,this.onclose?.())}};var qK=class{createTransport(I){switch(I.type){case"stdio":{let e=new TK({command:I.command,args:I.args,env:I.env,stderr:I.stderr?"pipe":void 0});return e.stderr?.pipe(I.stderr),e}case"http":return new KK(new URL(I.url),{requestInit:{headers:I.headers||{}}});case"sse":return new SK(new URL(I.url),{requestInit:{headers:I.headers||{}}});case"memory":return new PK(I.server);default:throw new Error(`Unsupported transport type: ${I.type}`)}}};G();var Ry="blackbird-mcp-server",_H="github-mcp-server",AbI="playwright";function $H(t){return t.type===void 0||t.type.toLowerCase()==="local"||t.type.toLowerCase()==="stdio"}function _K(t){return t.type?.toLowerCase()==="http"}function $K(t){return t.type?.toLowerCase()==="sse"}function q9(t){return t.type?.toLowerCase()==="memory"}var XbI=class extends O3e{constructor(e,l){super({decodeStrings:!1});this.serverName=e;this.logger=l}_write(e,l,c){try{let n=e.toString();this.logger.log(`[mcp server ${this.serverName} stderr] ${n}`),c()}catch(n){c(n instanceof Error?n:new Error(String(n)))}}},IP=class{constructor(I,e=new kK,l=new qK){this.logger=I;this.clientFactory=e;this.transportFactory=l}clients={};transports={};async startLocalMcpClient(I,e,l,c){this.logger.log(`Starting MCP client for ${I} with command: ${l} and args: ${c}`);let n=new XbI(I,this.logger),a={type:"stdio",command:l,args:c,env:{...e,PATH:process.env.PATH},stderr:n},s=this.transportFactory.createTransport(a);await this.setupAndConnectClient(I,s)}async startHttpMcpClient(I,e){this.logger.log(`Starting remote MCP client for ${I} with url: ${e.url}`);let l={type:"http",url:e.url,headers:e.headers},c=this.transportFactory.createTransport(l);await this.setupAndConnectClient(I,c)}async startSseMcpClient(I,e){this.logger.log(`Starting remote MCP client for ${I} with url: ${e.url}`);let l={type:"sse",url:e.url,headers:e.headers},c=this.transportFactory.createTransport(l);await this.setupAndConnectClient(I,c)}async startInMemoryMcpClient(I,e){this.logger.log(`Starting in-memory MCP client for ${I}`);let l={type:"memory",server:e},c=this.transportFactory.createTransport(l);await this.setupAndConnectClient(I,c)}async setupAndConnectClient(I,e){this.transports[I]=e,e.onclose=()=>{this.logger.log(`MCP transport for ${I} closed`),delete this.transports[I]},this.logger.log(`Creating MCP client for ${I}...`);let l=this.clientFactory.createClient({name:"github-copilot-developer",version:"1.0.0"},{capabilities:{experimental:void 0,roots:void 0,sampling:void 0}}),c=Date.now();this.logger.log(`Connecting MCP client for ${I}...`),await l.connect(e),l.onclose=()=>{this.logger.log(`MCP client for ${I} closed`),delete this.clients[I]},l.onerror=n=>{this.logger.error(`MCP client for ${I} errored ${n}`)},this.logger.log(`MCP client for ${I} connected, took ${Date.now()-c}ms`),this.clients[I]=l}async getTools(I,e){let l={};for(let[c,n]of Object.entries(this.clients)){let a=[];try{this.logger.log(`Fetching tools from client: ${c}`);let s=await n.listTools(),r=I?.mcpServers[c].tools,o=I?.mcpServers[c].filterMapping;for(let b of s.tools){if(b.name==="get_copilot_space")continue;if(!(r?.includes("*")||r?.includes(b.name))){this.logger.log(`Tool ${b.name} is not in the allowed list for client: ${c}`);continue}let Z=vD(c,b.name),p=`${c}-${b.name}`,W;typeof o=="string"?W=_rI(o):W=_rI(o?.[b.name]??"hidden_characters"),l[`${c}/${b.name}`]={name:p,title:b.title??b.annotations?.title??b.name,description:b.description??p,input_schema:b.inputSchema,readOnly:b.annotations?.readOnlyHint,safeForTelemetry:{name:!!(I?.mcpServers[c].isDefaultServer||Z),inputsNames:!!I?.mcpServers[c].isDefaultServer},filterMode:W},a.push(b.name),this.logger.log(`Tool ${b.name} added to tools list for client: ${c}`)}this.logger.log(`Successfully retrieved ${a.length} tools from client: ${c}`);let d=n.getServerVersion();await this.logServerSuccessWithTools(c,a,d,e)}catch(s){this.logger.error(`Failed to get tools from client: ${c} ${s}`)}}return this.logger.log(`All tools retrieved: ${JSON.stringify(l,null,2)}`),l}async logServerSuccessWithTools(I,e,l,c){if(I!=Ry&&c)try{let n=e.map(r=>`- ${r}`).join(`
1126
1126
  `),s=`MCP server started successfully${l?` (version ${l.version})`:""} with ${e.length} ${e.length===1?"tool":"tools"} - for the full output, see the verbose logs
1127
1127
 
1128
- ${n}`;await c.logMCPSetup(I,s),this.logger.log(`Updated session log for ${I} with ${e.length} tools`)}catch(n){this.logger.error(`Failed to update session log for ${I}: ${n}`)}}};G();var wbI={mcpServers:{}},eP=class{constructor(I,e,l){this.logger=I;this.registry=e;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(I){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 e=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(e,I),this.configureGitHubMcp(e,I),this.configurePlaywrightMcp(e)),e}validateEnvConfig(){if(!this.mcp3pEnabled)return this.logger.log("User-provided MCPs are disabled"),wbI;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"),wbI;try{let I=JSON.parse(this.mcpEnvConfig);if(!I.mcpServers)throw new Error("User-provided config had incorrect format. Missing 'mcpServers' property.");for(let e in I.mcpServers)I.mcpServers[e].isDefaultServer=!1;return I}catch(I){return this.logger.error(`Warning: User-provided MCP servers were defined but invalid: ${I}`),wbI}}configureGitHubMcp(I,e){this.remoteEnabled?this.configureRemoteGitHubMcp(I,e):this.configureLocalGitHubMcp(I)}configureRemoteGitHubMcp(I,e){this.logger.log("Using default remote GitHub MCP server configuration");let l="repos,issues,users,pull_requests,code_security,secret_protection,actions";process.env.COPILOT_MCP_COPILOT_SPACES_ENABLED==="true"&&(this.logger.log("Enabling Copilot Spaces in GitHub MCP server configuration"),l=l+",copilot_spaces");let c={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":l,"X-MCP-Host":"github-coding-agent","X-Initiator":"agent"};e&&e.api?.copilot?.integrationId&&(c["Copilot-Integration-Id"]=e.api.copilot.integrationId),process.env.GITHUB_COPILOT_INTERACTION_ID&&(c["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let n={type:"http",url:this.getCapiMcpUrl(),headers:c,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"}};I.mcpServers[_H]=n}configureLocalGitHubMcp(I){if(I.mcpServers[_H]){this.logger.log("Using user-provided GitHub MCP server configuration");let e=I.mcpServers[_H]??{};$H(e)&&!e.command&&(I.mcpServers[_H]={...e,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 e={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};I.mcpServers[_H]=e}}configurePlaywrightMcp(I){if(!I.mcpServers[AbI]){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 e={command:"npx",args:[...LGI,"--allowed-origins","localhost;localhost:*;127.0.0.1;127.0.0.1:*"],tools:["*"],isDefaultServer:!0};I.mcpServers[AbI]=e}}configureBlackbirdMcp(I,e){this.remoteEnabled?this.configureRemoteBlackbirdMcp(I):this.blackbirdMetisIndexEnabled?this.configureLocalMetisBlackbirdMCP(I,e):this.configureLocalBlackbirdMcp(I)}configureLocalMetisBlackbirdMCP(I,e){this.logger.log("Using local Metis Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${e.blackbird?.mode}`);let l=process.env.AGENT_DIR||"/agent";this.logger.log(`Using agent directory: ${l}`);let c=[];e.blackbird?.mode==="tool"&&(c=["*"]),this.logger.log(`Using blackbird Metis server: ${e.blackbird?.mode}`);let n={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:c,isDefaultServer:!0};I.mcpServers[Ry]=n}configureLocalBlackbirdMcp(I){this.logger.log("Using local Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let e=[];process.env.BLACKBIRD_MODE==="tool"&&(e=["*"]);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:e,isDefaultServer:!0};I.mcpServers[Ry]=l}configureRemoteBlackbirdMcp(I){this.logger.log("Using remote Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let e=[];process.env.BLACKBIRD_MODE==="tool"&&(e=["*"]);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 c={type:"http",url:this.getCapiMcpUrl(),headers:l,tools:e,isDefaultServer:!0};I.mcpServers[Ry]=c}getCapiMcpUrl(){return process.env.COPILOT_API_URL?new URL("/mcp/readonly",process.env.COPILOT_API_URL).toString():"https://api.githubcopilot.com/mcp/readonly"}isValidServerType(I){return $H(I)||_K(I)||$K(I)||q9(I)}isValidLocalServerConfig(I){return I.command!==void 0&&I.command.trim()!==""&&Array.isArray(I.args)}isValidRemoteServerConfig(I){return I.url!==void 0&&I.url.trim()!==""}isValidInMemoryServerConfig(I){return I.serverInstance!==void 0&&typeof I.serverInstance=="object"}validateServerConfig(I,e){return this.remoteEnabled&&!this.isValidServerType(e)?(this.logger.error(`Unsupported server type "${e.type}" for server "${I}". Only "Local", "STDIO", "HTTP", "SSE", or "Memory" are supported.`),!1):!this.remoteEnabled&&!$H(e)&&!q9(e)?(this.logger.error(`Unsupported server type "${e.type}" for server "${I}". Only "Local", "STDIO", or "Memory" are supported.`),!1):e.tools?$H(e)&&!this.isValidLocalServerConfig(e)?(this.logger.error(`Invalid local server configuration for "${I}". Please ensure 'command' and 'args' are provided.`),!1):(_K(e)||$K(e))&&!this.isValidRemoteServerConfig(e)?(this.logger.error(`Invalid remote server configuration for "${I}". Please ensure 'url' is provided.`),!1):q9(e)&&!this.isValidInMemoryServerConfig(e)?(this.logger.error(`Invalid in-memory server configuration for "${I}". Please ensure 'serverInstance' is provided and is an instance of MCPServer.`),!1):!0:(this.logger.error(`No tools specified for server "${I}". Please provide a list of tools or "*" to include all tools.`),!1)}async processHttpServer(I,e){try{let l=this.resolveHeaders(e.headers,process.env),c={...e,headers:l};await this.registry.startHttpMcpClient(I,c),this.logger.log(`Started MCP client for remote server ${I}`)}catch(l){throw this.logger.error(`Failed to start MCP client for remote server ${I}: ${l}`),l}}async processSseServer(I,e){try{let l=this.resolveHeaders(e.headers,process.env),c={...e,headers:l};await this.registry.startSseMcpClient(I,c),this.logger.log(`Started MCP client for remote server ${I}`)}catch(l){throw this.logger.error(`Failed to start MCP client for remote server ${I}: ${l}`),l}}async processInMemoryServer(I,e){try{await this.registry.startInMemoryMcpClient(I,e.serverInstance),this.logger.log(`Started in-memory MCP client for ${I}`)}catch(l){throw this.logger.error(`Failed to start in-memory MCP client for ${I}: ${l}`),l}}async processLocalServer(I,e){let l={...e};if(e.command==="python")try{l=await this.convertPythonToPipx(l)}catch(a){this.logger.error(`Failed to handle Python module for ${I}: ${a}`)}let c=this.buildEnvironment(l),n=this.resolveArray(l.args,c);this.logger.log(`Starting MCP client for ${I} with command: ${l.command} and args: ${n}`);try{await this.registry.startLocalMcpClient(I,c,l.command,n),this.logger.log(`Started MCP client for ${I}`)}catch(a){throw this.logger.error(`Failed to start MCP client for ${I}: ${a}`),a}}convertPythonToPipx(I){if(!I||!I.args||I.args.length===0)return I;let e=I.args,l=e.indexOf("-m");if(l===-1||l===e.length-1)throw new Error("Python command with -m flag must specify a module");let c=e[l+1];this.logger.log(`Converting Python module: ${c} to pipx command`);let n=["run",c];for(let a=l+2;a<e.length;a++)n.push(e[a]);for(let a=0;a<l;a++)n.push(e[a]);return{...I,command:"pipx",args:n}}buildEnvironment(I){let e={};if(I.env)for(let[l,c]of Object.entries(I.env)){let n=c.trim();process.env[n]!==void 0&&(e[l]=process.env[n])}return e}resolveArray(I,e){return I?e?I.map(l=>l.replace(/\$([A-Z0-9_]+)/g,(c,n)=>e[n]||c)):I:[]}resolveHeaders(I,e){if(!I)return{};if(!e)return I;let l={};for(let[c,n]of Object.entries(I)){let a=this.resolveArray([n],e);l[c]=a[0]}return l}async processServers(I){if(!I)throw new Error("No servers to process");for(let[e,l]of Object.entries(I.mcpServers))await this.processServer(e,l)}async processServer(I,e){if(!this.validateServerConfig(I,e)){this.logger.error(`Skipping server "${I}" due to invalid configuration.`);return}try{$H(e)?await this.processLocalServer(I,e):_K(e)&&this.remoteEnabled?await this.processHttpServer(I,e):$K(e)&&this.remoteEnabled?await this.processSseServer(I,e):q9(e)&&await this.processInMemoryServer(I,e)}catch(l){I!==Ry&&await this.logServerFailure(I,l)}}async logServerFailure(I,e){if(this.sessionClient)try{await this.sessionClient.logMCPSetup(I,`<error>MCP server failed to start: ${e.message} - for the full output, see the verbose logs</error>`)}catch(l){this.logger.error(`Failed to log failure for MCP Server '${I}': '${l}'`)}}};var tP=class{constructor(I,e,l){this.logger=I;let c;if(typeof e=="string"){if(c=JSON.parse(e),typeof c!="object")throw new Error("Invalid MCP configuration: must be an object");if(c===null||!("mcpServers"in c)||typeof c.mcpServers!="object")throw new Error("Invalid MCP configuration: missing or invalid mcpServers property");this.config=c}else this.config=e;this.disabledServers=new Set(l||[]),this.registry=new IP(this.logger),this.processor=new eP(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(I){}async processServersWithExtensions(){await this.injectDefaultServers(this.config);let I;if(this.disabledServers.size>0){let e={};for(let[l,c]of Object.entries(this.config.mcpServers))this.disabledServers.has(l)?this.logger.log(`Skipping disabled MCP server: ${l}`):e[l]=c;I={...this.config,mcpServers:e}}else I=this.config;return this.processor.processServers(I)}async stopServers(){for(let[I,e]of Object.entries(this.registry.transports))try{await e.close()}catch(l){this.logger.error(`Error closing transport for ${I}: ${l}`)}this.startServersPromise=null,this.allTools=null}async getTools(I,e,l){if(!this.allTools){await this.startServers();let c=new Pk(I,e,l),n=[];for(let a of Object.keys(this.registry.clients)){let s=await c.loadTools({mcpClient:this.registry.clients[a],clientName:a,tools:this.config.mcpServers[a]?.tools||["*"],filterMapping:this.config.mcpServers[a]?.filterMapping||"hidden_characters"});n.push(...s)}this.allTools=n}return this.allTools}getConfig(){return this.config}async startServer(I,e){await this.startServers(),this.config.mcpServers[I]=e,await this.processor.processServer(I,e),this.allTools=null}async stopServer(I){let e=this.registry.transports[I];if(e)try{await e.close(),delete this.registry.transports[I]}catch(l){this.logger.error(`Error closing transport for ${I}: ${l}`)}this.registry.clients[I]&&delete this.registry.clients[I],this.allTools=null}async restartServer(I,e){this.isServerRunning(I)&&await this.stopServer(I),delete this.config.mcpServers[I],await this.startServer(I,e)}isServerRunning(I){return I in this.registry.transports&&I in this.registry.clients}isServerDisabled(I){return this.disabledServers.has(I)}async disableServer(I){if(this.disabledServers.has(I)){this.logger.log(`Server ${I} is already disabled`);return}this.disabledServers.add(I),this.logger.log(`Disabled server ${I} for this session`),this.isServerRunning(I)&&await this.stopServer(I),this.allTools=null}async enableServer(I){if(!this.disabledServers.has(I)){this.logger.log(`Server ${I} is not disabled`);return}this.disabledServers.delete(I),this.logger.log(`Enabled server ${I} for this session`);let e=this.getServerConfig(I);e?await this.startServer(I,e):await this.startBuiltInServer(I),this.allTools=null}async startBuiltInServer(I){}getServerConfig(I){return this.config.mcpServers[I]}};G();var AUI=Qc(gUI(),1);async function k9e(t={}){let I=await EiI();return XiI((0,AUI.default)({},I,t))}async function XUI(t={}){if(Nf())throw new Error("Settings have already been initialized");return k9e(t)}G();async function TY(t,I,e){if(!t||t.length===0)return;let l=!1,c={};for(let n of t)try{let a=await n(I);a&&(l=!0,c={...c,...a})}catch(a){e.error(`Hook execution failed: ${a}`)}return l?c:void 0}G();G();G();var zbI=class{loggers;constructor(I){this.loggers=I}isDebug(){return this.loggers.some(I=>I.isDebug())}debug(I){this.loggers.forEach(e=>e.debug(I))}log(I){this.loggers.forEach(e=>e.log(I))}info(I){this.loggers.forEach(e=>e.info(I))}notice(I){this.loggers.forEach(e=>e.notice(I))}warning(I){this.loggers.forEach(e=>e.warning(I))}error(I){this.loggers.forEach(e=>e.error(I))}startGroup(I,e){this.loggers.forEach(l=>l.startGroup(I,e))}endGroup(I){this.loggers.forEach(e=>e.endGroup(I))}};G();import{appendFile as f9e,access as x9e,mkdir as B9e}from"fs/promises";import{constants as z9e}from"fs";import{dirname as U9e}from"path";var UbI=class extends Bh{constructor(e,l,c){super(l,c);this.filePath=e;this.writeQueue=S9e(U9e(this.filePath)).catch(()=>{})}writeQueue=Promise.resolve();log(e){this.write("LOG",e)}debug(e){super.shouldLog(8)&&this.write("DEBUG",this.filterSecrets(e).toString())}info(e){super.shouldLog(4)&&this.write("INFO",this.filterSecrets(e).toString())}notice(e){super.shouldLog(2)&&this.write("NOTICE",this.filterSecrets(e).toString())}warning(e){super.shouldLog(2)&&this.write("WARNING",this.filterSecrets(e).toString())}error(e){super.shouldLog(1)&&this.write("ERROR",this.filterSecrets(e).toString())}startGroup(e,l){super.shouldLog(l||4)&&this.write("START-GROUP",e)}endGroup(e){super.shouldLog(e||4)&&this.write("END-GROUP","")}write(e,l){let n=`${new Date().toISOString()} [${e}] ${l}
1128
+ ${n}`;await c.logMCPSetup(I,s),this.logger.log(`Updated session log for ${I} with ${e.length} tools`)}catch(n){this.logger.error(`Failed to update session log for ${I}: ${n}`)}}};G();var wbI={mcpServers:{}},eP=class{constructor(I,e,l){this.logger=I;this.registry=e;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(I){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 e=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(e,I),this.configureGitHubMcp(e,I),this.configurePlaywrightMcp(e)),e}validateEnvConfig(){if(!this.mcp3pEnabled)return this.logger.log("User-provided MCPs are disabled"),wbI;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"),wbI;try{let I=JSON.parse(this.mcpEnvConfig);if(!I.mcpServers)throw new Error("User-provided config had incorrect format. Missing 'mcpServers' property.");for(let e in I.mcpServers)I.mcpServers[e].isDefaultServer=!1;return I}catch(I){return this.logger.error(`Warning: User-provided MCP servers were defined but invalid: ${I}`),wbI}}configureGitHubMcp(I,e){this.remoteEnabled?this.configureRemoteGitHubMcp(I,e):this.configureLocalGitHubMcp(I)}configureRemoteGitHubMcp(I,e){this.logger.log("Using default remote GitHub MCP server configuration");let l="repos,issues,users,pull_requests,code_security,secret_protection,actions";process.env.COPILOT_MCP_COPILOT_SPACES_ENABLED==="true"&&(this.logger.log("Enabling Copilot Spaces in GitHub MCP server configuration"),l=l+",copilot_spaces");let c={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":l,"X-MCP-Host":"github-coding-agent","X-Initiator":"agent"};e&&e.api?.copilot?.integrationId&&(c["Copilot-Integration-Id"]=e.api.copilot.integrationId),process.env.GITHUB_COPILOT_INTERACTION_ID&&(c["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let n={type:"http",url:this.getCapiMcpUrl(),headers:c,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"}};I.mcpServers[_H]=n}configureLocalGitHubMcp(I){if(I.mcpServers[_H]){this.logger.log("Using user-provided GitHub MCP server configuration");let e=I.mcpServers[_H]??{};$H(e)&&!e.command&&(I.mcpServers[_H]={...e,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 e={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};I.mcpServers[_H]=e}}configurePlaywrightMcp(I){if(!I.mcpServers[AbI]){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 e={command:"npx",args:[...LGI,"--allowed-origins","localhost;localhost:*;127.0.0.1;127.0.0.1:*"],tools:["*"],isDefaultServer:!0};I.mcpServers[AbI]=e}}configureBlackbirdMcp(I,e){this.remoteEnabled?this.configureRemoteBlackbirdMcp(I):this.blackbirdMetisIndexEnabled?this.configureLocalMetisBlackbirdMCP(I,e):this.configureLocalBlackbirdMcp(I)}configureLocalMetisBlackbirdMCP(I,e){this.logger.log("Using local Metis Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${e.blackbird?.mode}`);let l=process.env.AGENT_DIR||"/agent";this.logger.log(`Using agent directory: ${l}`);let c=[];e.blackbird?.mode==="tool"&&(c=["*"]),this.logger.log(`Using blackbird Metis server: ${e.blackbird?.mode}`);let n={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:c,isDefaultServer:!0};I.mcpServers[Ry]=n}configureLocalBlackbirdMcp(I){this.logger.log("Using local Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let e=[];process.env.BLACKBIRD_MODE==="tool"&&(e=["*"]);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:e,isDefaultServer:!0};I.mcpServers[Ry]=l}configureRemoteBlackbirdMcp(I){this.logger.log("Using remote Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let e=[];process.env.BLACKBIRD_MODE==="tool"&&(e=["*"]);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 c={type:"http",url:this.getCapiMcpUrl(),headers:l,tools:e,isDefaultServer:!0};I.mcpServers[Ry]=c}getCapiMcpUrl(){return process.env.COPILOT_API_URL?new URL("/mcp/readonly",process.env.COPILOT_API_URL).toString():"https://api.githubcopilot.com/mcp/readonly"}isValidServerType(I){return $H(I)||_K(I)||$K(I)||q9(I)}isValidLocalServerConfig(I){return I.command!==void 0&&I.command.trim()!==""&&Array.isArray(I.args)}isValidRemoteServerConfig(I){return I.url!==void 0&&I.url.trim()!==""}isValidInMemoryServerConfig(I){return I.serverInstance!==void 0&&typeof I.serverInstance=="object"}validateServerConfig(I,e){return this.remoteEnabled&&!this.isValidServerType(e)?(this.logger.error(`Unsupported server type "${e.type}" for server "${I}". Only "Local", "STDIO", "HTTP", "SSE", or "Memory" are supported.`),!1):!this.remoteEnabled&&!$H(e)&&!q9(e)?(this.logger.error(`Unsupported server type "${e.type}" for server "${I}". Only "Local", "STDIO", or "Memory" are supported.`),!1):e.tools?$H(e)&&!this.isValidLocalServerConfig(e)?(this.logger.error(`Invalid local server configuration for "${I}". Please ensure 'command' and 'args' are provided.`),!1):(_K(e)||$K(e))&&!this.isValidRemoteServerConfig(e)?(this.logger.error(`Invalid remote server configuration for "${I}". Please ensure 'url' is provided.`),!1):q9(e)&&!this.isValidInMemoryServerConfig(e)?(this.logger.error(`Invalid in-memory server configuration for "${I}". Please ensure 'serverInstance' is provided and is an instance of MCPServer.`),!1):!0:(this.logger.error(`No tools specified for server "${I}". Please provide a list of tools or "*" to include all tools.`),!1)}async processHttpServer(I,e){try{let l=this.resolveHeaders(e.headers,process.env),c={...e,headers:l};await this.registry.startHttpMcpClient(I,c),this.logger.log(`Started MCP client for remote server ${I}`)}catch(l){throw this.logger.error(`Failed to start MCP client for remote server ${I}: ${l}`),l}}async processSseServer(I,e){try{let l=this.resolveHeaders(e.headers,process.env),c={...e,headers:l};await this.registry.startSseMcpClient(I,c),this.logger.log(`Started MCP client for remote server ${I}`)}catch(l){throw this.logger.error(`Failed to start MCP client for remote server ${I}: ${l}`),l}}async processInMemoryServer(I,e){try{await this.registry.startInMemoryMcpClient(I,e.serverInstance),this.logger.log(`Started in-memory MCP client for ${I}`)}catch(l){throw this.logger.error(`Failed to start in-memory MCP client for ${I}: ${l}`),l}}async processLocalServer(I,e){let l={...e};if(e.command==="python")try{l=await this.convertPythonToPipx(l)}catch(a){this.logger.error(`Failed to handle Python module for ${I}: ${a}`)}let c=this.buildEnvironment(l),n=this.resolveArray(l.args,c);this.logger.log(`Starting MCP client for ${I} with command: ${l.command} and args: ${n}`);try{await this.registry.startLocalMcpClient(I,c,l.command,n),this.logger.log(`Started MCP client for ${I}`)}catch(a){throw this.logger.error(`Failed to start MCP client for ${I}: ${a}`),a}}convertPythonToPipx(I){if(!I||!I.args||I.args.length===0)return I;let e=I.args,l=e.indexOf("-m");if(l===-1||l===e.length-1)throw new Error("Python command with -m flag must specify a module");let c=e[l+1];this.logger.log(`Converting Python module: ${c} to pipx command`);let n=["run",c];for(let a=l+2;a<e.length;a++)n.push(e[a]);for(let a=0;a<l;a++)n.push(e[a]);return{...I,command:"pipx",args:n}}buildEnvironment(I){let e={};if(I.env)for(let[l,c]of Object.entries(I.env)){let n=c.trim();process.env[n]!==void 0&&(e[l]=process.env[n])}return e}resolveArray(I,e){return I?e?I.map(l=>l.replace(/\$([A-Z0-9_]+)/g,(c,n)=>e[n]||c)):I:[]}resolveHeaders(I,e){if(!I)return{};if(!e)return I;let l={};for(let[c,n]of Object.entries(I)){let a=this.resolveArray([n],e);l[c]=a[0]}return l}async processServers(I){if(!I)throw new Error("No servers to process");let e=Object.entries(I.mcpServers).map(([l,c])=>this.processServer(l,c));await Promise.all(e)}async processServer(I,e){if(!this.validateServerConfig(I,e)){this.logger.error(`Skipping server "${I}" due to invalid configuration.`);return}try{$H(e)?await this.processLocalServer(I,e):_K(e)&&this.remoteEnabled?await this.processHttpServer(I,e):$K(e)&&this.remoteEnabled?await this.processSseServer(I,e):q9(e)&&await this.processInMemoryServer(I,e)}catch(l){I!==Ry&&await this.logServerFailure(I,l)}}async logServerFailure(I,e){if(this.sessionClient)try{await this.sessionClient.logMCPSetup(I,`<error>MCP server failed to start: ${e.message} - for the full output, see the verbose logs</error>`)}catch(l){this.logger.error(`Failed to log failure for MCP Server '${I}': '${l}'`)}}};var tP=class{constructor(I,e,l){this.logger=I;let c;if(typeof e=="string"){if(c=JSON.parse(e),typeof c!="object")throw new Error("Invalid MCP configuration: must be an object");if(c===null||!("mcpServers"in c)||typeof c.mcpServers!="object")throw new Error("Invalid MCP configuration: missing or invalid mcpServers property");this.config=c}else this.config=e;this.disabledServers=new Set(l||[]),this.registry=new IP(this.logger),this.processor=new eP(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(I){}async processServersWithExtensions(){await this.injectDefaultServers(this.config);let I;if(this.disabledServers.size>0){let e={};for(let[l,c]of Object.entries(this.config.mcpServers))this.disabledServers.has(l)?this.logger.log(`Skipping disabled MCP server: ${l}`):e[l]=c;I={...this.config,mcpServers:e}}else I=this.config;return this.processor.processServers(I)}async stopServers(){for(let[I,e]of Object.entries(this.registry.transports))try{await e.close()}catch(l){this.logger.error(`Error closing transport for ${I}: ${l}`)}this.startServersPromise=null,this.allTools=null}async getTools(I,e,l){if(!this.allTools){await this.startServers();let c=new Pk(I,e,l),n=[];for(let a of Object.keys(this.registry.clients)){let s=await c.loadTools({mcpClient:this.registry.clients[a],clientName:a,tools:this.config.mcpServers[a]?.tools||["*"],filterMapping:this.config.mcpServers[a]?.filterMapping||"hidden_characters"});n.push(...s)}this.allTools=n}return this.allTools}getConfig(){return this.config}async startServer(I,e){await this.startServers(),this.config.mcpServers[I]=e,await this.processor.processServer(I,e),this.allTools=null}async stopServer(I){let e=this.registry.transports[I];if(e)try{await e.close(),delete this.registry.transports[I]}catch(l){this.logger.error(`Error closing transport for ${I}: ${l}`)}this.registry.clients[I]&&delete this.registry.clients[I],this.allTools=null}async restartServer(I,e){this.isServerRunning(I)&&await this.stopServer(I),delete this.config.mcpServers[I],await this.startServer(I,e)}isServerRunning(I){return I in this.registry.transports&&I in this.registry.clients}isServerDisabled(I){return this.disabledServers.has(I)}async disableServer(I){if(this.disabledServers.has(I)){this.logger.log(`Server ${I} is already disabled`);return}this.disabledServers.add(I),this.logger.log(`Disabled server ${I} for this session`),this.isServerRunning(I)&&await this.stopServer(I),this.allTools=null}async enableServer(I){if(!this.disabledServers.has(I)){this.logger.log(`Server ${I} is not disabled`);return}this.disabledServers.delete(I),this.logger.log(`Enabled server ${I} for this session`);let e=this.getServerConfig(I);e?await this.startServer(I,e):await this.startBuiltInServer(I),this.allTools=null}async startBuiltInServer(I){}getServerConfig(I){return this.config.mcpServers[I]}};G();var AUI=Qc(gUI(),1);async function k9e(t={}){let I=await EiI();return XiI((0,AUI.default)({},I,t))}async function XUI(t={}){if(Nf())throw new Error("Settings have already been initialized");return k9e(t)}G();async function TY(t,I,e){if(!t||t.length===0)return;let l=!1,c={};for(let n of t)try{let a=await n(I);a&&(l=!0,c={...c,...a})}catch(a){e.error(`Hook execution failed: ${a}`)}return l?c:void 0}G();G();G();var zbI=class{loggers;constructor(I){this.loggers=I}isDebug(){return this.loggers.some(I=>I.isDebug())}debug(I){this.loggers.forEach(e=>e.debug(I))}log(I){this.loggers.forEach(e=>e.log(I))}info(I){this.loggers.forEach(e=>e.info(I))}notice(I){this.loggers.forEach(e=>e.notice(I))}warning(I){this.loggers.forEach(e=>e.warning(I))}error(I){this.loggers.forEach(e=>e.error(I))}startGroup(I,e){this.loggers.forEach(l=>l.startGroup(I,e))}endGroup(I){this.loggers.forEach(e=>e.endGroup(I))}};G();import{appendFile as f9e,access as x9e,mkdir as B9e}from"fs/promises";import{constants as z9e}from"fs";import{dirname as U9e}from"path";var UbI=class extends Bh{constructor(e,l,c){super(l,c);this.filePath=e;this.writeQueue=S9e(U9e(this.filePath)).catch(()=>{})}writeQueue=Promise.resolve();log(e){this.write("LOG",e)}debug(e){super.shouldLog(8)&&this.write("DEBUG",this.filterSecrets(e).toString())}info(e){super.shouldLog(4)&&this.write("INFO",this.filterSecrets(e).toString())}notice(e){super.shouldLog(2)&&this.write("NOTICE",this.filterSecrets(e).toString())}warning(e){super.shouldLog(2)&&this.write("WARNING",this.filterSecrets(e).toString())}error(e){super.shouldLog(1)&&this.write("ERROR",this.filterSecrets(e).toString())}startGroup(e,l){super.shouldLog(l||4)&&this.write("START-GROUP",e)}endGroup(e){super.shouldLog(e||4)&&this.write("END-GROUP","")}write(e,l){let n=`${new Date().toISOString()} [${e}] ${l}
1129
1129
  `;this.writeQueue=this.writeQueue.then(()=>this.performWrite(n)).catch(()=>{})}async performWrite(e){await f9e(this.filePath,e)}};async function S9e(t){try{await x9e(t,z9e.F_OK)}catch{await B9e(t,{recursive:!0})}}G();var lE=class{id;startTime;selectedModel;logger;constructor({id:I,startTime:e,selectedModel:l}={},c){this.id=I||Oo(),this.startTime=e||new Date,this.selectedModel=l,this.logger=c||new zr}};var lf=class extends lE{messages=[];constructor({chatMessages:I,...e}={},l){super(e,l),this.messages=I||[]}async getChatMessages(){return[...this.messages]}async addChatMessage(I){this.messages.push(I)}async onAbort(){}},wUI=class{sessions=new Map;logger;constructor(I){this.logger=I?.logger||new zr}async createSession(){let I=new lf({},this.logger);return this.sessions.set(I.id,I),this.logger.info(`Created new in-memory session with ID: ${I.id}`),I}async getLastSession(){let I=Array.from(this.sessions.values()).pop();if(!I)throw new Error("No sessions available");return I}async getSession(I){let e=this.sessions.get(I);if(!e)throw new Error(`Session with ID ${I} not found`);return e}async listSessions(){return Array.from(this.sessions.values()).map(I=>({id:I.id,startTime:I.startTime,selectedModel:I.selectedModel}))}async saveSession(I){this.logger.info(`Session with ID ${I.id} is in-memory and does not require saving.`)}enableAutoSave(){this.logger.info("Auto-save is not applicable for in-memory sessions.")}async deleteSession(I){this.sessions.delete(I.id)?this.logger.info(`Deleted session with ID: ${I.id}`):this.logger.warning(`Attempted to delete non-existent session with ID: ${I.id}`)}};var dP=class{static name="Copilot";static description="Base Copilot Agent";options;logger;workingDir;session;constructor(I){this.options=I,this.logger=I.logger||new zr,this.workingDir=I.workingDirectory||process.cwd(),this.session=I.session||new lf}async*query(I){let e=new Map,l;try{if(this.options.mcpServers&&Object.keys(this.options.mcpServers).length>0)try{l=new tP(this.logger,{mcpServers:this.options.mcpServers},this.options.disabledTools),await l.startServers()}catch(FI){this.logger.error(`Failed to initialize MCP host: ${FI}`)}let c={timestamp:Date.now(),cwd:this.workingDir,prompt:I},a=(await TY(this.options.hooks?.userPromptSubmitted,c,this.logger))?.modifiedPrompt??I;await this.session.addChatMessage({role:"user",content:a});let r=new ky().setProblemStatement(a).setAgentModel(this.buildAgentModelString()).setGithubRepoName("copilot-sdk-session").setGithubRepoCommit("copilot-sdk-commit").setGithubRepoReadWrite(!1).setCopilotIntegrationId(this.options.integrationId||"copilot-sdk-unknown").setCopilotHmacKey(this.options.hmacKey).setCopilotToken(this.options.copilotToken).build();wiI();let o=await XUI(r),d=o.service?.agent?.model,b=jGI(d),h=b.agent,Z=b.model?{model:b.model}:void 0,p=raI(o,this.logger,h,Z),W={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"?pb.powerShell:pb.bash},N=await x9I(W,this.logger),Y=[];if(l)try{Y=await l.getTools(o,this.logger,W.permissions)}catch(FI){this.logger.error(`Failed to get MCP tools: ${FI}`)}let F=[...N,...Y],A=this.applyToolFiltering(F,this.options.allowedTools,this.options.disabledTools),g=await lkI(this.workingDir),k={...(z9I()["sweagent-capi"]?.["claude-sonnet-4"]??B9I()).supports,reasoning:!0},z=await Y9I(g.found?g.gitRoot:"",uCI(),this.workingDir,{},k,W),rI=(await this.session.getChatMessages()).slice(0,-1),VI={role:"user",content:y9I(a,k)},UI=[...rI,VI],HI={timestamp:Date.now(),cwd:this.workingDir,source:"new",initialPrompt:I};await TY(this.options.hooks?.sessionStart,HI,this.logger);let hI=p.getCompletionWithTools(z,UI,A,{failIfInitialInputsTooLong:!1,processors:{preRequest:[new YH(this.logger)]},executeToolsInParallel:!1,abortSignal:this.options.abortController?.signal});for await(let FI of hI){if(this.options.abortController?.signal.aborted){yield{type:"error",error:new Error("Operation was cancelled")};return}let EI=await this.translateEvent(FI,e);for(let Pt of EI)Pt.type==="message"&&Pt.role==="assistant"&&await this.session.addChatMessage({role:"assistant",content:Pt.content}),yield Pt}yield{type:"complete"}}catch(c){let n={timestamp:Date.now(),cwd:this.workingDir,reason:"error",error:c instanceof Error?c:new Error(String(c))};await TY(this.options.hooks?.sessionEnd,n,this.logger),yield{type:"error",error:c instanceof Error?c:new Error(String(c))}}finally{let c={timestamp:Date.now(),cwd:this.workingDir,reason:"complete"};if(await TY(this.options.hooks?.sessionEnd,c,this.logger),l)try{await l.stopServers(),this.logger.log("MCP host stopped successfully")}catch(n){this.logger.error(`Error stopping MCP host: ${n}`)}}}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(I,e,l){let c=I;return e&&e.length>0&&(c=c.filter(n=>e.includes(n.name))),l&&l.length>0&&(c=c.filter(n=>!l.includes(n.name))),c}async translateEvent(I,e){switch(I.kind){case"message":{if(JD(I)&&I.message.content)return[{type:"message",content:typeof I.message.content=="string"?I.message.content:"",role:"assistant"}];if(v9I(I)){let l=[];for(let c of I.message.tool_calls){let n=Jg(c.function.arguments);e.set(c.id,c.function.name);let a={timestamp:Date.now(),cwd:this.workingDir,toolName:c.function.name,toolArgs:n},r=(await TY(this.options.hooks?.preToolUse,a,this.logger))?.modifiedArgs??n;l.push({type:"tool_use",toolName:c.function.name,args:r,toolCallId:c.id})}return l}return[]}case"response":return I.response.content&&typeof I.response.content=="string"?[{type:"message",content:I.response.content,role:"assistant"}]:[];case"model_call_failure":{let l=new Error(I.modelCall?.error||"Model call failed"),c={timestamp:Date.now(),cwd:this.workingDir,error:l,errorContext:"model_call",recoverable:!0};return await TY(this.options.hooks?.errorOccurred,c,this.logger),[{type:"error",error:l}]}case"tool_execution":{let l=e.get(I.toolCallId)||"unknown",c={timestamp:Date.now(),cwd:this.workingDir,toolName:l,toolArgs:{},toolResult:I.toolResult},a=(await TY(this.options.hooks?.postToolUse,c,this.logger))?.modifiedResult??I.toolResult;return[{type:"tool_result",toolName:l,result:a,toolCallId:I.toolCallId}]}default:return[]}}};G();G();G();G();var YSI=Qc(oSI(),1);G();import{existsSync as ciI}from"fs";import{mkdir as Lxe,readdir as kxe,readFile as fxe,stat as xxe,writeFile as Bxe}from"fs/promises";import{homedir as zxe}from"os";import{dirname as Uxe,join as sf}from"path";G();G();var Hxe=new Error("timeout while waiting for mutex to become available"),Czl=new Error("mutex already locked"),Exe=new Error("request for lock canceled"),vxe=function(t,I,e,l){function c(n){return n instanceof e?n:new e(function(a){a(n)})}return new(e||(e=Promise))(function(n,a){function s(d){try{o(l.next(d))}catch(b){a(b)}}function r(d){try{o(l.throw(d))}catch(b){a(b)}}function o(d){d.done?n(d.value):c(d.value).then(s,r)}o((l=l.apply(t,I||[])).next())})},liI=class{constructor(I,e=Exe){this._value=I,this._cancelError=e,this._queue=[],this._weightedWaiters=[]}acquire(I=1,e=0){if(I<=0)throw new Error(`invalid weight ${I}: must be positive`);return new Promise((l,c)=>{let n={resolve:l,reject:c,weight:I,priority:e},a=bSI(this._queue,s=>e<=s.priority);a===-1&&I<=this._value?this._dispatchItem(n):this._queue.splice(a+1,0,n)})}runExclusive(I){return vxe(this,arguments,void 0,function*(e,l=1,c=0){let[n,a]=yield this.acquire(l,c);try{return yield e(n)}finally{a()}})}waitForUnlock(I=1,e=0){if(I<=0)throw new Error(`invalid weight ${I}: must be positive`);return this._couldLockImmediately(I,e)?Promise.resolve():new Promise(l=>{this._weightedWaiters[I-1]||(this._weightedWaiters[I-1]=[]),Cxe(this._weightedWaiters[I-1],{resolve:l,priority:e})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(I){this._value=I,this._dispatchQueue()}release(I=1){if(I<=0)throw new Error(`invalid weight ${I}: must be positive`);this._value+=I,this._dispatchQueue()}cancel(){this._queue.forEach(I=>I.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(I){let e=this._value;this._value-=I.weight,I.resolve([e,this._newReleaser(I.weight)])}_newReleaser(I){let e=!1;return()=>{e||(e=!0,this.release(I))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let I=this._value;I>0;I--){let e=this._weightedWaiters[I-1];e&&(e.forEach(l=>l.resolve()),this._weightedWaiters[I-1]=[])}else{let I=this._queue[0].priority;for(let e=this._value;e>0;e--){let l=this._weightedWaiters[e-1];if(!l)continue;let c=l.findIndex(n=>n.priority<=I);(c===-1?l:l.splice(0,c)).forEach(n=>n.resolve())}}}_couldLockImmediately(I,e){return(this._queue.length===0||this._queue[0].priority<e)&&I<=this._value}};function Cxe(t,I){let e=bSI(t,l=>I.priority<=l.priority);t.splice(e+1,0,I)}function bSI(t,I){for(let e=t.length-1;e>=0;e--)if(I(t[e]))return e;return-1}var Jxe=function(t,I,e,l){function c(n){return n instanceof e?n:new e(function(a){a(n)})}return new(e||(e=Promise))(function(n,a){function s(d){try{o(l.next(d))}catch(b){a(b)}}function r(d){try{o(l.throw(d))}catch(b){a(b)}}function o(d){d.done?n(d.value):c(d.value).then(s,r)}o((l=l.apply(t,I||[])).next())})},AP=class{constructor(I){this._semaphore=new liI(1,I)}acquire(){return Jxe(this,arguments,void 0,function*(I=0){let[,e]=yield this._semaphore.acquire(1,I);return e})}runExclusive(I,e=0){return this._semaphore.runExclusive(()=>I(),1,e)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(I=0){return this._semaphore.waitForUnlock(1,I)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}},dSI=function(t,I,e,l){function c(n){return n instanceof e?n:new e(function(a){a(n)})}return new(e||(e=Promise))(function(n,a){function s(d){try{o(l.next(d))}catch(b){a(b)}}function r(d){try{o(l.throw(d))}catch(b){a(b)}}function o(d){d.done?n(d.value):c(d.value).then(s,r)}o((l=l.apply(t,I||[])).next())})};function iSI(t,I,e=Hxe){return{acquire:(l,c)=>{let n;if(gP(t)?n=l:(n=void 0,c=l),n!==void 0&&n<=0)throw new Error(`invalid weight ${n}: must be positive`);return new Promise((a,s)=>dSI(this,void 0,void 0,function*(){let r=!1,o=setTimeout(()=>{r=!0,s(e)},I);try{let d=yield gP(t)?t.acquire(n,c):t.acquire(c);r?(Array.isArray(d)?d[1]:d)():(clearTimeout(o),a(d))}catch(d){r||(clearTimeout(o),s(d))}}))},runExclusive(l,c,n){return dSI(this,void 0,void 0,function*(){let a=()=>{};try{let s=yield this.acquire(c,n);return Array.isArray(s)?(a=s[1],yield l(s[0])):(a=s,yield l())}finally{a()}})},release(l){t.release(l)},cancel(){return t.cancel()},waitForUnlock:(l,c)=>{let n;if(gP(t)?n=l:(n=void 0,c=l),n!==void 0&&n<=0)throw new Error(`invalid weight ${n}: must be positive`);return new Promise((a,s)=>{let r=setTimeout(()=>s(e),I);(gP(t)?t.waitForUnlock(n,c):t.waitForUnlock(c)).then(()=>{clearTimeout(r),a()})})},isLocked:()=>t.isLocked(),getValue:()=>t.getValue(),setValue:l=>t.setValue(l)}}function gP(t){return t.getValue!==void 0}var XP=class{mutexes=new Map;async runExclusive(I,e,l=5e3){let c=this.mutexes.get(I);c||(c=new AP,c.refCount=0,this.mutexes.set(I,c));let n=c;try{return n.refCount++,await iSI(c,l).runExclusive(e)}finally{--n.refCount===0&&this.mutexes.delete(I)}}};var niI=(e=>(e.DEFAULT="config",e.MCP="mcp",e))(niI||{});function mSI(t){return Object.values(niI).includes(t)}var hSI=".copilot",ZSI=new XP;async function Sxe(t){let I=Uxe(t);try{await Lxe(I,{recursive:!0,mode:448})}catch{}}async function Oxe(t,I){if(ciI(t))try{let e={},l=await ZSI.runExclusive(t,()=>fxe(t,"utf8"));return l.trim().startsWith("{")?e=JSON.parse(l):l.split(`
1130
1130
  `).forEach(c=>{let[n,a]=c.split("=").map(s=>s.trim());n&&a&&(e[n]=a)}),I(e)}catch(e){throw new Error(`Failed to read configuration from ${t}: ${e}`)}}async function Mxe(t,I){try{await Sxe(t);let e=JSON.stringify(I,null,2);await ZSI.runExclusive(t,()=>Bxe(t,e,{mode:384}))}catch(e){throw new Error(`Failed to write configuration to ${t}: ${e}`)}}var pSI=(t,I)=>{let e=()=>{let o=mSI(I)?process.env.XDG_CONFIG_HOME:process.env.XDG_STATE_HOME;return o?sf(o,hSI):sf(zxe(),hSI)},l=()=>{let o=mSI(I)?"-config":"-state";return`${I}${I=="config"?"":o}`},c=o=>{let d=".json",b=l()+(o?"":d),h=sf(e(),b,o?`${o}${d}`:"");return!ciI(h)&&ciI(h.replace(/\.json$/,""))&&(h=h.replace(/\.json$/,"")),h},n=async()=>{let o=sf(e(),l());try{let b=(await kxe(o)).filter(Z=>Z.endsWith(".json")),h=await Promise.all(b.map(async Z=>{let p=sf(o,Z);try{let W=await xxe(p);return{file:Z,mtime:W.mtime}}catch{return{file:Z,mtime:new Date}}}));return h.sort((Z,p)=>p.mtime.getTime()-Z.mtime.getTime()),h.map(Z=>Z.file)}catch{}return[]},a=async o=>await Oxe(c(o),t),s=async(o,d)=>{await Mxe(c(d),o)};return{load:a,write:s,writeKey:async(o,d,b)=>{let h=await a(b);if(d===void 0){h&&(delete h[o],await s(h,b));return}let Z={[o]:d},p;h?p={...h,...Z}:p=Z,await s(p,b)},path:c,directoryFiles:n}},uSI=(t,I)=>pSI(t,I),WSI=(t,I)=>pSI(t,I);var NSI=Ae({host:vI(),login:vI()}),Txe=Ae({banner:au(["always","once","never"]).optional(),beep:fa().optional(),last_logged_in_user:NSI.optional(),logged_in_users:Us(NSI).optional(),model:au(wP).optional(),render_markdown:fa().optional(),screen_reader:fa().optional(),theme:vI().optional(),trusted_folders:Us(vI()).optional(),capi_hmac_key:vI().optional(),copilot_hmac_key:vI().optional(),copilot_integration_id:vI().optional(),copilot_tokens:OD(vI(),vI()).optional(),copilot_url:vI().optional()}),jxe=OD(vI(),IoI()),Dxe=jxe.transform(t=>(0,YSI.default)(t,(I,e)=>{let l=e.toLowerCase();return l==="github_copilot_integration_id"?"copilot_integration_id":l})),Kxe=Dxe.pipe(Txe),Pxe=uSI(Kxe.parse,"config");var wP=["claude-sonnet-4.5","claude-sonnet-4","gpt-5"];G();var qxe=Ae({type:sl("copilot"),text:vI()}),_xe=Ae({type:sl("error"),text:vI()}),$xe=Ae({type:sl("info"),text:vI()}),IBe=Ae({displayText:vI(),fullPath:vI(),type:au(["file","directory","unresolved","image"]),startIndex:wh()}),eBe=Ae({type:sl("user"),text:vI(),expandedText:vI().optional(),mentions:Us(IBe).optional(),imageAttachments:Us(Ae({type:sl("image_url"),image_url:Ae({url:vI()})})).optional()}),tBe=Ae({command:vI(),description:vI(),timeout:wh().optional(),sessionId:vI().optional(),async:fa().optional()}),lBe=Ae({sessionId:vI(),input:vI(),delay:wh().optional()}),cBe=Ae({sessionId:vI(),delay:wh()}),nBe=Ae({sessionId:vI()}),aBe=Ss([tBe,lBe,cBe,nBe]),sBe=Ae({command:sl("view"),path:vI(),view_range:loI([wh(),wh()]).optional()}),rBe=Ae({command:sl("create"),path:vI(),file_text:vI()}),GBe=Ae({command:sl("str_replace"),path:vI(),new_str:vI().optional(),old_str:vI()}),oBe=Ae({command:sl("insert"),path:vI(),insert_line:wh(),new_str:vI()}),dBe=toI("command",[sBe,rBe,GBe,oBe]),VSI=Ss([aBe,dBe,eoI()]),bBe=Ae({type:sl("tool_call_requested"),callId:vI(),name:vI(),toolTitle:vI().optional(),intentionSummary:vI().nullable(),arguments:VSI,partialOutput:vI().optional(),isHidden:fa().optional(),isAlwaysExpanded:fa().optional(),showNoContent:fa().optional()}),iBe=Ae({type:sl("tool_call_completed"),callId:vI(),name:vI(),toolTitle:vI().optional(),intentionSummary:vI().nullable(),result:Ss([Ae({type:sl("success"),log:vI(),markdown:fa().optional()}),Ae({type:sl("failure"),log:vI(),markdown:fa().optional()}),Ae({type:sl("rejected"),markdown:fa().optional()}),Ae({type:sl("denied"),log:vI(),markdown:fa().optional()})]),arguments:VSI,isHidden:fa().optional(),isAlwaysExpanded:fa().optional(),showNoContent:fa().optional()}),mBe=Ss([qxe,_xe,$xe,eBe,bBe,iBe]),RSI=mBe.and(Ae({id:vI(),timestamp:e9.date()}));var rf=Ae({type:sl("text"),text:vI()}),hBe=Ae({type:sl("refusal"),refusal:vI()}),ZBe=Ae({type:sl("image_url"),image_url:Ae({url:vI(),detail:au(["auto","low","high"]).optional()})}),pBe=Ae({type:sl("input_audio"),input_audio:Ae({data:vI(),format:sl("wav").or(sl("mp3"))})}),uBe=Ae({type:sl("file"),file:Ae({file_date:vI().optional(),file_id:vI().optional(),filename:vI().optional()})}),WBe=Ss([rf,ZBe,pBe,uBe]),NBe=Ae({name:vI(),arguments:vI()}),YBe=Ae({name:vI(),input:vI()}),VBe=Ae({id:vI(),type:sl("function"),function:NBe}),RBe=Ae({id:vI(),type:sl("custom"),custom:YBe}),yBe=Ss([VBe,RBe]),FBe=Ae({name:vI(),arguments:vI()}),QBe=Ae({id:vI()}),gBe=Ae({content:Ss([vI(),Us(rf)]),role:sl("developer"),name:vI().optional()}),ABe=Ae({content:Ss([vI(),Us(rf)]),role:sl("system"),name:vI().optional()}),XBe=Ae({content:Ss([vI(),Us(WBe)]),role:sl("user"),name:vI().optional()}),wBe=Ae({content:Ss([vI(),Us(Ss([rf,hBe]))]).nullable().optional(),role:sl("assistant"),name:vI().optional(),refusal:vI().nullable().optional(),audio:QBe.nullable().optional(),function_call:FBe.nullable().optional(),tool_calls:Us(yBe).optional()}),HBe=Ae({content:Ss([vI(),Us(rf)]),role:sl("tool"),tool_call_id:vI()}),EBe=Ae({content:vI().nullable(),role:sl("function"),name:vI()}),vBe=Ss([gBe,ABe,XBe,wBe,HBe,EBe]),CBe=Ae({sessionId:vI(),startTime:e9.date(),chatMessages:Us(vBe),timeline:Us(RSI),selectedModel:au(wP).optional()}),Nu=WSI(CBe.parse,"history-session");G();function JBe(t){return`session_${t.sessionId}_${t.startTime.getTime()}`}function ySI(t){let I=/^session_(.+)_(\d+)\.json$/,e=t.match(I);if(!e)return null;let[,l,c]=e;return{sessionId:l,startTime:new Date(parseInt(c,10))}}var GE=class t{currentSession;onTimelineEntriesChangeCallback=null;debounceSave=null;logger;needsSessionPicker=!1;autoSaveEnabled=!1;usageMetrics={totalPremiumRequests:0,totalApiDurationMs:0,sessionStartTime:Date.now(),codeChanges:{linesAdded:0,linesRemoved:0,filesModified:new Set},modelMetrics:new Map};static async create(I){let e=new t;switch(I.kind){case"new":break;case"resume-last":await e.resumeLastSession();break;case"resume":await e.resumeSpecificSession(I.sessionId);break;case"resume-with-picker":e.needsSessionPicker=!0;break;default:{let l=I;throw new Error(`unexpected session kind: ${JSON.stringify(l)}`)}}return e}static async hasMultipleSessions(){try{return(await Nu.directoryFiles()).length>1}catch{return!1}}constructor(){this.currentSession=this.generateSession(),this.logger=new zr}setLogger(I){this.logger=I}getLogger(){return this.logger}isWaitingForSessionPicker(){return this.needsSessionPicker}async selectSession(I){this.needsSessionPicker=!1,await this.resumeSpecificSession(I)}setOnTimelineEntriesChangeCallback(I){this.onTimelineEntriesChangeCallback=I,this.notifyTimelineEntriesChange()}notifyTimelineEntriesChange(){this.onTimelineEntriesChangeCallback?.([...this.currentSession.timeline])}enableAutoSave(){this.autoSaveEnabled=!0}async forceSave(){await this.saveHistorySession(this.currentSession)}scheduleSave(){this.debounceSave&&clearTimeout(this.debounceSave);let I=this.currentSession;this.debounceSave=setTimeout(()=>{this.autoSaveEnabled&&this.saveHistorySession(I)},100)}getTimelineEntries(){return[...this.currentSession.timeline]}async loadHistorySession(I){try{let e=await Nu.load(I);if(!e)return;let l={...e,startTime:new Date(e.startTime)};this.currentSession=l;for(let c of this.currentSession.timeline)c.timestamp=new Date(c.timestamp);this.currentSession.chatMessages=this.completeOrphanedToolCalls(this.currentSession.chatMessages),this.enableAutoSave(),this.notifyTimelineEntriesChange()}catch(e){throw this.logger.error(`Error loading history session: ${e}`),e}}async saveHistorySession(I){let e=JBe(I);await Nu.write(I,e)}getCurrentSessionId(){return this.currentSession?.sessionId}getCurrentSessionStartTime(){return this.currentSession?.startTime}getSelectedModel(){return this.currentSession?.selectedModel}getCurrentModel(I){return I||this.currentSession?.selectedModel||this.usageMetrics.currentModel||""}setSelectedModel(I){this.currentSession.selectedModel=I,this.scheduleSave()}addTimelineEntry(I){try{this.currentSession.timeline.push({id:Oo(),timestamp:new Date,...I}),this.scheduleSave(),this.notifyTimelineEntriesChange()}catch(e){this.logger.error(`Error adding timeline entry: ${e}`)}}clearHistory(){this.currentSession.chatMessages=[],this.currentSession.timeline=[],this.scheduleSave(),this.notifyTimelineEntriesChange()}addChatMessage(I){this.currentSession.chatMessages.push(I),this.scheduleSave()}getChatContextMessages(){return this.currentSession.chatMessages.filter(I=>I.role!=="system")}handleAbortedOperation(){this.currentSession.chatMessages=this.completeOrphanedToolCalls(this.currentSession.chatMessages),this.scheduleSave()}completeOrphanedToolCalls(I){if(I.length===0)return I;let e=[];for(let n=I.length-1;n>=0;n--){let a=I[n];if(a.role==="assistant"&&"tool_calls"in a&&a.tool_calls&&a.tool_calls.length>0)for(let s of a.tool_calls)e.push(s.id);else break}if(e.length===0)return I;let l="The execution of this tool, or a previous tool was interrupted.";this.logger.info(`Completing ${e.length} orphaned tool calls.`);let c=e.map(n=>({role:"tool",tool_call_id:n,content:l}));for(let n of e)this.updateToolCallTimelineEntryResult({callId:n,resultType:"rejected",log:l});return[...I,...c]}updateToolCallTimelineEntryResult(I){let e=this.currentSession.timeline.findLastIndex(n=>n.type==="tool_call_requested"&&n.callId===I.callId);if(e===-1){this.logger.error(`Pending tool call with ID ${I.callId} not found`);return}let l=this.currentSession.timeline[e];if(l.type==="tool_call_requested"&&l.name==="str_replace_editor"&&I.log){let s=l.arguments?.path;this.updateCodeChangeMetrics(I.log,s)}let c=this.currentSession.timeline[e];this.currentSession.timeline[e]={type:"tool_call_completed",id:c.id,timestamp:c.timestamp,callId:c.callId,name:c.name,toolTitle:c.toolTitle,intentionSummary:c.intentionSummary,arguments:c.arguments,result:{type:I.resultType,log:I.log,markdown:I.markdown},isAlwaysExpanded:c.isAlwaysExpanded,showNoContent:c.showNoContent},this.scheduleSave(),this.notifyTimelineEntriesChange()}updateToolCallTimelineEntryPartialOutput(I,e){let l=this.currentSession.timeline.findLastIndex(n=>n.type==="tool_call_requested"&&n.callId===I);if(l===-1){this.logger.error(`Pending tool call with ID ${I} not found`);return}let c=this.currentSession.timeline[l];this.currentSession.timeline[l]={type:"tool_call_requested",id:c.id,timestamp:c.timestamp,callId:c.callId,name:c.name,toolTitle:c.toolTitle,intentionSummary:c.intentionSummary,arguments:c.arguments,partialOutput:e,isAlwaysExpanded:c.isAlwaysExpanded,showNoContent:c.showNoContent},this.notifyTimelineEntriesChange()}async resumeSpecificSession(I){let e=await Nu.directoryFiles();if(e.length===0)throw new Error(`Session not found: ${I}`);let l=null,c=[];for(let n of e){let a=ySI(n);if(a&&a.sessionId===I){l=n;break}}if(!l){for(let n of e){let a=ySI(n);a&&a.sessionId.startsWith(I)&&c.push({file:n,parsed:a})}c.length>0&&(c.sort((n,a)=>a.parsed.startTime.getTime()-n.parsed.startTime.getTime()),l=c[0].file)}if(!l)throw new Error(`Session not found: ${I}`);try{await this.loadHistorySession(l)}catch(n){throw new Error(`Failed to load session ${I}: ${n}`)}}async resumeLastSession(){let I=await Nu.directoryFiles();if(I.length===0)throw new Error("No sessions found");let e=I[0];try{await this.loadHistorySession(e)}catch(l){throw new Error(`Failed to resume last session: ${l}`)}}generateSession(){return this.resetUsageMetrics(),{sessionId:this.generateSessionId(),startTime:new Date,chatMessages:[],timeline:[]}}generateSessionId(){return Oo()}getUsageMetrics(){return this.usageMetrics}resetUsageMetrics(){this.usageMetrics={totalPremiumRequests:0,totalApiDurationMs:0,sessionStartTime:Date.now(),codeChanges:{linesAdded:0,linesRemoved:0,filesModified:new Set},modelMetrics:new Map}}getModelRequestMultiplier(I){return{"claude-sonnet-4":1,"gpt-5":1,"claude-sonnet-4.5":1}[I]??1}trackUserMessage(I){let e=I||"",c=1*this.getModelRequestMultiplier(e);this.usageMetrics.totalPremiumRequests+=c,this.usageMetrics.modelMetrics.has(e)||this.usageMetrics.modelMetrics.set(e,{requests:{count:0,cost:0},usage:{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0}});let n=this.usageMetrics.modelMetrics.get(e);n.requests.count+=1,n.requests.cost+=c,this.usageMetrics.currentModel=e}updateModelUsageMetrics(I,e,l){let c=I||"";if(this.usageMetrics.totalApiDurationMs+=e,l){this.usageMetrics.modelMetrics.has(c)||this.usageMetrics.modelMetrics.set(c,{requests:{count:0,cost:0},usage:{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0}});let n=this.usageMetrics.modelMetrics.get(c);if(n.usage.inputTokens+=l.prompt_tokens||0,n.usage.outputTokens+=l.completion_tokens||0,l.prompt_tokens_details?.cached_tokens){n.usage.cacheReadTokens+=l.prompt_tokens_details.cached_tokens;let a=(l.prompt_tokens||0)-l.prompt_tokens_details.cached_tokens;n.usage.cacheWriteTokens+=Math.max(0,a)}}}updateCodeChangeMetrics(I,e){if(!I||!I.includes("diff --git"))return;let l=I.split(`
1131
1131
  `),c=0,n=0;for(let a of l)a.startsWith("+")&&!a.startsWith("+++")?c++:a.startsWith("-")&&!a.startsWith("---")&&n++;this.usageMetrics.codeChanges.linesAdded+=c,this.usageMetrics.codeChanges.linesRemoved+=n,e&&this.usageMetrics.codeChanges.filesModified.add(e)}formatTokenCount(I){return I===0?"0":I<1e3?I.toString():I<1e6?`${(I/1e3).toFixed(1)}k`:`${(I/1e6).toFixed(1)}m`}formatDuration(I){let e=Math.floor(I/1e3),l=Math.floor(e/60),c=Math.floor(l/60);if(c>0){let n=l%60,a=I%6e4/1e3;return`${c}h ${n}m ${a.toFixed(1)}s`}else if(l>0){let n=I%6e4/1e3;return`${l}m ${n.toFixed(1)}s`}else return`${(I/1e3).toFixed(1)}s`}getFormattedUsageOutput(){let I=this.usageMetrics,e=this.formatDuration(Date.now()-I.sessionStartTime),l=this.formatDuration(I.totalApiDurationMs),c=Math.round(I.totalPremiumRequests),a=[`Total usage est: ${c} ${c===1?"Premium request":"Premium requests"}`,`Total duration (API): ${l}`,`Total duration (wall): ${e}`,`Total code changes: ${I.codeChanges.linesAdded} lines added, ${I.codeChanges.linesRemoved} lines removed`];if(I.modelMetrics.size>0){a.push("Usage by model:");for(let[s,r]of I.modelMetrics){let{requests:o,usage:d}=r,b=this.formatTokenCount(d.inputTokens),h=this.formatTokenCount(d.outputTokens),Z=this.formatTokenCount(d.cacheReadTokens),p=this.formatTokenCount(d.cacheWriteTokens),W=Math.round(o.cost),N=W===1?"Premium request":"Premium requests",F=(s||"(unknown)").padEnd(20);a.push(` ${F} ${b} input, ${h} output, ${Z} cache read, ${p} cache write (Est. ${W} ${N})`)}}return a.join(`