@github/copilot 0.0.339-11 → 0.0.339-12

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
@@ -1894,7 +1894,7 @@ Pay attention to the following when using it:
1894
1894
  `}var mpn=X2e.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function Gpn(){let t={};for(let e of mpn){let l=X2e.env[e];l!==void 0&&(l.startsWith("()")||(t[e]=l))}return t}var H2e=class{constructor(e){this._abortController=new AbortController,this._readBuffer=new f2e,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new upn)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,l)=>{var n,I,r,a,s;this._process=(0,BBt.default)(this._serverParams.command,(n=this._serverParams.args)!==null&&n!==void 0?n:[],{env:{...Gpn(),...this._serverParams.env},stdio:["pipe","pipe",(I=this._serverParams.stderr)!==null&&I!==void 0?I:"inherit"],shell:!1,signal:this._abortController.signal,windowsHide:X2e.platform==="win32"&&bpn(),cwd:this._serverParams.cwd}),this._process.on("error",o=>{var d,u;if(o.name==="AbortError"){(d=this.onclose)===null||d===void 0||d.call(this);return}l(o),(u=this.onerror)===null||u===void 0||u.call(this,o)}),this._process.on("spawn",()=>{e()}),this._process.on("close",o=>{var d;this._process=void 0,(d=this.onclose)===null||d===void 0||d.call(this)}),(r=this._process.stdin)===null||r===void 0||r.on("error",o=>{var d;(d=this.onerror)===null||d===void 0||d.call(this,o)}),(a=this._process.stdout)===null||a===void 0||a.on("data",o=>{this._readBuffer.append(o),this.processReadBuffer()}),(s=this._process.stdout)===null||s===void 0||s.on("error",o=>{var d;(d=this.onerror)===null||d===void 0||d.call(this,o)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){var e,l;return this._stderrStream?this._stderrStream:(l=(e=this._process)===null||e===void 0?void 0:e.stderr)!==null&&l!==void 0?l:null}get pid(){var e,l;return(l=(e=this._process)===null||e===void 0?void 0:e.pid)!==null&&l!==void 0?l:null}processReadBuffer(){for(var e,l;;)try{let n=this._readBuffer.readMessage();if(n===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,n)}catch(n){(l=this.onerror)===null||l===void 0||l.call(this,n)}}async close(){this._abortController.abort(),this._process=void 0,this._readBuffer.clear()}send(e){return new Promise(l=>{var n;if(!(!((n=this._process)===null||n===void 0)&&n.stdin))throw new Error("Not connected");let I=JBt(e);this._process.stdin.write(I)?l():this._process.stdin.once("drain",l)})}};function bpn(){return"type"in X2e}c();c();var k2e=class extends TransformStream{constructor({onError:e,onRetry:l,onComment:n}={}){let I;super({start(r){I=V2e({onEvent:a=>{r.enqueue(a)},onError(a){e==="terminate"?r.error(a):typeof e=="function"&&e(a)},onRetry:l,onComment:n})},transform(r){I.feed(r)}})}};var ppn={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},oce=class extends Error{constructor(e,l){super(`Streamable HTTP error: ${l}`),this.code=e}},L2e=class{constructor(e,l){var n;this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=l?.requestInit,this._authProvider=l?.authProvider,this._fetch=l?.fetch,this._sessionId=l?.sessionId,this._reconnectionOptions=(n=l?.reconnectionOptions)!==null&&n!==void 0?n:ppn}async _authThenStart(){var e;if(!this._authProvider)throw new Sg("No auth provider");let l;try{l=await Ak(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(l!=="AUTHORIZED")throw new Sg;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let l={};if(this._authProvider){let I=await this._authProvider.tokens();I&&(l.Authorization=`Bearer ${I.access_token}`)}this._sessionId&&(l["mcp-session-id"]=this._sessionId),this._protocolVersion&&(l["mcp-protocol-version"]=this._protocolVersion);let n=this._normalizeHeaders((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...l,...n})}async _startOrAuthSse(e){var l,n,I;let{resumptionToken:r}=e;try{let a=await this._commonHeaders();a.set("Accept","text/event-stream"),r&&a.set("last-event-id",r);let s=await((l=this._fetch)!==null&&l!==void 0?l:fetch)(this._url,{method:"GET",headers:a,signal:(n=this._abortController)===null||n===void 0?void 0:n.signal});if(!s.ok){if(s.status===401&&this._authProvider)return await this._authThenStart();if(s.status===405)return;throw new oce(s.status,`Failed to open SSE stream: ${s.statusText}`)}this._handleSseStream(s.body,e,!0)}catch(a){throw(I=this.onerror)===null||I===void 0||I.call(this,a),a}}_getNextReconnectionDelay(e){let l=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,I=this._reconnectionOptions.maxReconnectionDelay;return Math.min(l*Math.pow(n,e),I)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,l=0){var n;let I=this._reconnectionOptions.maxRetries;if(I>0&&l>=I){(n=this.onerror)===null||n===void 0||n.call(this,new Error(`Maximum reconnection attempts (${I}) exceeded.`));return}let r=this._getNextReconnectionDelay(l);setTimeout(()=>{this._startOrAuthSse(e).catch(a=>{var s;(s=this.onerror)===null||s===void 0||s.call(this,new Error(`Failed to reconnect SSE stream: ${a instanceof Error?a.message:String(a)}`)),this._scheduleReconnection(e,l+1)})},r)}_handleSseStream(e,l,n){if(!e)return;let{onresumptiontoken:I,replayMessageId:r}=l,a;(async()=>{var o,d,u,G;try{let p=e.pipeThrough(new TextDecoderStream).pipeThrough(new k2e).getReader();for(;;){let{value:h,done:W}=await p.read();if(W)break;if(h.id&&(a=h.id,I?.(h.id)),!h.event||h.event==="message")try{let E=ik.parse(JSON.parse(h.data));r!==void 0&&bie(E)&&(E.id=r),(o=this.onmessage)===null||o===void 0||o.call(this,E)}catch(E){(d=this.onerror)===null||d===void 0||d.call(this,E)}}}catch(p){if((u=this.onerror)===null||u===void 0||u.call(this,new Error(`SSE stream disconnected: ${p}`)),n&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:I,replayMessageId:r},0)}catch(h){(G=this.onerror)===null||G===void 0||G.call(this,new Error(`Failed to reconnect: ${h instanceof Error?h.message:String(h)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Sg("No auth provider");if(await Ak(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new Sg("Failed to authorize")}async close(){var e,l;(e=this._abortController)===null||e===void 0||e.abort(),(l=this.onclose)===null||l===void 0||l.call(this)}async send(e,l){var n,I,r,a;try{let{resumptionToken:s,onresumptiontoken:o}=l||{};if(s){this._startOrAuthSse({resumptionToken:s,replayMessageId:XRe(e)?e.id:void 0}).catch(R=>{var w;return(w=this.onerror)===null||w===void 0?void 0:w.call(this,R)});return}let d=await this._commonHeaders();d.set("content-type","application/json"),d.set("accept","application/json, text/event-stream");let u={...this._requestInit,method:"POST",headers:d,body:JSON.stringify(e),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},G=await((I=this._fetch)!==null&&I!==void 0?I:fetch)(this._url,u),p=G.headers.get("mcp-session-id");if(p&&(this._sessionId=p),!G.ok){if(G.status===401&&this._authProvider){if(this._resourceMetadataUrl=sce(G),await Ak(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new Sg;return this.send(e)}let R=await G.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${G.status}): ${R}`)}if(G.status===202){Pkt(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(R=>{var w;return(w=this.onerror)===null||w===void 0?void 0:w.call(this,R)});return}let W=(Array.isArray(e)?e:[e]).filter(R=>"method"in R&&"id"in R&&R.id!==void 0).length>0,E=G.headers.get("content-type");if(W)if(E?.includes("text/event-stream"))this._handleSseStream(G.body,{onresumptiontoken:o},!1);else if(E?.includes("application/json")){let R=await G.json(),w=Array.isArray(R)?R.map(C=>ik.parse(C)):[ik.parse(R)];for(let C of w)(r=this.onmessage)===null||r===void 0||r.call(this,C)}else throw new oce(-1,`Unexpected content type: ${E}`)}catch(s){throw(a=this.onerror)===null||a===void 0||a.call(this,s),s}}get sessionId(){return this._sessionId}async terminateSession(){var e,l,n;if(this._sessionId)try{let I=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:I,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},a=await((l=this._fetch)!==null&&l!==void 0?l:fetch)(this._url,r);if(!a.ok&&a.status!==405)throw new oce(a.status,`Failed to terminate session: ${a.statusText}`);this._sessionId=void 0}catch(I){throw(n=this.onerror)===null||n===void 0||n.call(this,I),I}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}};c();var J2e=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 DPe(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?.())}},DPe=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 B2e=class{createTransport(e){switch(e.type){case"stdio":{let l=new H2e({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 L2e(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"sse":return new C2e(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"memory":return new J2e(e.server);default:throw new Error(`Unsupported transport type: ${e.type}`)}}};c();var y9="blackbird-mcp-server",iK="github-mcp-server",zPe="playwright";function cK(t){return t.type===void 0||t.type.toLowerCase()==="local"||t.type.toLowerCase()==="stdio"}function dK(t){return ice(t)||cce(t)}function ice(t){return t.type?.toLowerCase()==="http"}function cce(t){return t.type?.toLowerCase()==="sse"}function dce(t){return t.type?.toLowerCase()==="memory"}var PPe=class extends hpn{constructor(l,n){super({decodeStrings:!1});this.serverName=l;this.logger=n}_write(l,n,I){try{let r=l.toString();this.logger.log(`[mcp server ${this.serverName} stderr] ${r}`),I()}catch(r){I(r instanceof Error?r:new Error(String(r)))}}},x2e=class{constructor(e,l=new R2e,n=new B2e){this.logger=e;this.clientFactory=l;this.transportFactory=n}clients={};transports={};async startLocalMcpClient(e,l,n,I){this.logger.log(`Starting MCP client for ${e} with command: ${n} and args: ${I}`);let r=new PPe(e,this.logger),a={type:"stdio",command:n,args:I,env:{...l,PATH:process.env.PATH},stderr:r},s=this.transportFactory.createTransport(a);await this.setupAndConnectClient(e,s)}async startHttpMcpClient(e,l){this.logger.log(`Starting remote MCP client for ${e} with url: ${l.url}`);let n={type:"http",url:l.url,headers:l.headers},I=this.transportFactory.createTransport(n);await this.setupAndConnectClient(e,I)}async startSseMcpClient(e,l){this.logger.log(`Starting remote MCP client for ${e} with url: ${l.url}`);let n={type:"sse",url:l.url,headers:l.headers},I=this.transportFactory.createTransport(n);await this.setupAndConnectClient(e,I)}async startInMemoryMcpClient(e,l){this.logger.log(`Starting in-memory MCP client for ${e}`);let n={type:"memory",server:l},I=this.transportFactory.createTransport(n);await this.setupAndConnectClient(e,I)}async setupAndConnectClient(e,l){this.transports[e]=l,l.onclose=()=>{this.logger.log(`MCP transport for ${e} closed`),delete this.transports[e]},this.logger.log(`Creating MCP client for ${e}...`);let n=this.clientFactory.createClient({name:"github-copilot-developer",version:"1.0.0"},{capabilities:{experimental:void 0,roots:void 0,sampling:void 0}}),I=Date.now();this.logger.log(`Connecting MCP client for ${e}...`),await n.connect(l),n.onclose=()=>{this.logger.log(`MCP client for ${e} closed`),delete this.clients[e]},n.onerror=r=>{this.logger.error(`MCP client for ${e} errored ${r}`)},this.logger.log(`MCP client for ${e} connected, took ${Date.now()-I}ms`),this.clients[e]=n}async getTools(e,l){let n={};for(let[I,r]of Object.entries(this.clients)){let a=[];try{this.logger.log(`Fetching tools from client: ${I}`);let s=await r.listTools(),o=e?.mcpServers[I].tools,d=e?.mcpServers[I].filterMapping;for(let G of s.tools){if(G.name==="get_copilot_space")continue;if(!(o?.includes("*")||o?.includes(G.name))){this.logger.log(`Tool ${G.name} is not in the allowed list for client: ${I}`);continue}let h=kNe(I,G.name),W=`${I}-${G.name}`,E;typeof d=="string"?E=vxe(d):E=vxe(d?.[G.name]??"hidden_characters"),n[`${I}/${G.name}`]={name:W,title:G.title??G.annotations?.title??G.name,description:G.description??W,input_schema:G.inputSchema,readOnly:G.annotations?.readOnlyHint,safeForTelemetry:{name:!!(e?.mcpServers[I].isDefaultServer||h),inputsNames:!!e?.mcpServers[I].isDefaultServer},filterMode:E},a.push(G.name),this.logger.log(`Tool ${G.name} added to tools list for client: ${I}`)}this.logger.log(`Successfully retrieved ${a.length} tools from client: ${I}`);let u=r.getServerVersion();await this.logServerSuccessWithTools(I,a,u,l)}catch(s){this.logger.error(`Failed to get tools from client: ${I} ${s}`)}}return this.logger.log(`All tools retrieved: ${JSON.stringify(n,null,2)}`),n}async logServerSuccessWithTools(e,l,n,I){if(e!=y9&&I)try{let r=l.map(o=>`- ${o}`).join(`
1895
1895
  `),s=`MCP server started successfully${n?` (version ${n.version})`:""} with ${l.length} ${l.length===1?"tool":"tools"} - for the full output, see the verbose logs
1896
1896
 
1897
- ${r}`;await I.logMCPSetup(e,s),this.logger.log(`Updated session log for ${e} with ${l.length} tools`)}catch(r){this.logger.error(`Failed to update session log for ${e}: ${r}`)}}};c();var jPe={mcpServers:{}},S2e=class{constructor(e,l,n){this.logger=e;this.registry=l;this.remoteEnabled=n?.remoteEnabled??!1,this.mcp3pEnabled=n?.mcp3pEnabled??!1,this.blackbirdMetisIndexEnabled=n?.blackbirdMetisIndexEnabled??!1,this.sessionClient=n?.sessionClient,this.mcpEnvConfig=void 0}remoteEnabled;mcp3pEnabled;blackbirdMetisIndexEnabled;mcpEnvConfig;sessionClient;ReadMcpConfigFromEnv(e){this.mcpEnvConfig=process.env.GITHUB_COPILOT_MCP_JSON,this.mcp3pEnabled=process.env.GITHUB_COPILOT_3P_MCP_ENABLED==="true",this.remoteEnabled=process.env.GITHUB_COPILOT_REMOTE_MCP_ENABLED==="true",this.blackbirdMetisIndexEnabled=process.env.BLACKBIRD_METIS_INDEX_ENABLED==="true";let l=this.validateEnvConfig();return process.env.GITHUB_COPILOT_CLI_MODE==="true"?this.logger.log("CLI mode detected - skipping default MCP servers"):(this.logger.log("Adding default MCP servers to configuration"),this.configureBlackbirdMcp(l,e),this.configureGitHubMcp(l,e),this.configurePlaywrightMcp(l)),l}validateEnvConfig(){if(!this.mcp3pEnabled)return this.logger.log("User-provided MCPs are disabled"),jPe;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"),jPe;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}`),jPe}}configureGitHubMcp(e,l){this.remoteEnabled?this.configureRemoteGitHubMcp(e,l):this.configureLocalGitHubMcp(e)}configureRemoteGitHubMcp(e,l){this.logger.log("Using default remote GitHub MCP server configuration");let n="repos,issues,users,pull_requests,code_security,secret_protection,actions,web_search";process.env.COPILOT_MCP_COPILOT_SPACES_ENABLED==="true"&&(this.logger.log("Enabling Copilot Spaces in GitHub MCP server configuration"),n=n+",copilot_spaces");let I={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":n,"X-MCP-Host":"github-coding-agent","X-Initiator":"agent"};l&&l.api?.copilot?.integrationId&&(I["Copilot-Integration-Id"]=l.api.copilot.integrationId),process.env.GITHUB_COPILOT_INTERACTION_ID&&(I["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let r={type:"http",url:this.getCapiMcpUrl(),headers:I,tools:["*"],isDefaultServer:!0,filterMapping:{get_issue:"markdown",get_issue_comments:"markdown",get_pull_request:"markdown",get_pull_request_comments:"markdown",get_pull_request_reviews:"markdown"}};e.mcpServers[iK]=r}configureLocalGitHubMcp(e){if(e.mcpServers[iK]){this.logger.log("Using user-provided GitHub MCP server configuration");let l=e.mcpServers[iK]??{};cK(l)&&!l.command&&(e.mcpServers[iK]={...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[iK]=l}}configurePlaywrightMcp(e){if(!e.mcpServers[zPe]){if((process.env.COPILOT_FEATURE_FLAGS??"").split(",").map(n=>n.trim()).includes("copilot_swe_agent_playwright_use_firewall")){this.logger.log("Playwright MCP server is configured to use the firewall, skipping launch.");return}this.logger.log("Enabling Playwright MCP server");let l={command:"npx",args:[...NSe,"--allowed-origins","localhost;localhost:*;127.0.0.1;127.0.0.1:*"],tools:["*"],isDefaultServer:!0};e.mcpServers[zPe]=l}}configureBlackbirdMcp(e,l){this.remoteEnabled?this.configureRemoteBlackbirdMcp(e):this.blackbirdMetisIndexEnabled?this.configureLocalMetisBlackbirdMCP(e,l):this.configureLocalBlackbirdMcp(e)}configureLocalMetisBlackbirdMCP(e,l){this.logger.log("Using local Metis Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${l.blackbird?.mode}`);let n=process.env.AGENT_DIR||"/agent";this.logger.log(`Using agent directory: ${n}`);let I=[];l.blackbird?.mode==="tool"&&(I=["*"]),this.logger.log(`Using blackbird Metis server: ${l.blackbird?.mode}`);let r={command:`${n}/blackbird/mcp`,args:["serve","--index",`${n}/blackbird/metis`],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",COPILOT_API_HMAC_KEY:"CAPI_HMAC_KEY",MODEL_BASED_RETRIEVAL_TOKEN:"BLACKBIRD_AUTH_MODEL_BASED_RETRIEVAL_TOKEN",METIS_API_KEY:"BLACKBIRD_AUTH_METIS_API_KEY"},tools:I,isDefaultServer:!0};e.mcpServers[y9]=r}configureLocalBlackbirdMcp(e){this.logger.log("Using local Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let l=[];process.env.BLACKBIRD_MODE==="tool"&&(l=["*"]);let n={command:"./copilot-developer-action-main/blackbird-mcp-server/blackbird-mcp-server",args:["stdio"],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",CAPI_HOST:"COPILOT_API_URL"},tools:l,isDefaultServer:!0};e.mcpServers[y9]=n}configureRemoteBlackbirdMcp(e){this.logger.log("Using remote Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let l=[];process.env.BLACKBIRD_MODE==="tool"&&(l=["*"]);let n={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":"search_agent","X-MCP-Host":"github-coding-agent"};process.env.GITHUB_COPILOT_INTERACTION_ID&&(n["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let I={type:"http",url:this.getCapiMcpUrl(),headers:n,tools:l,isDefaultServer:!0};e.mcpServers[y9]=I}getCapiMcpUrl(){return process.env.COPILOT_API_URL?new URL("/mcp/readonly",process.env.COPILOT_API_URL).toString():"https://api.githubcopilot.com/mcp/readonly"}isValidServerType(e){return cK(e)||ice(e)||cce(e)||dce(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&&!cK(l)&&!dce(l)?(this.logger.error(`Unsupported server type "${l.type}" for server "${e}". Only "Local", "STDIO", or "Memory" are supported.`),!1):l.tools?cK(l)&&!this.isValidLocalServerConfig(l)?(this.logger.error(`Invalid local server configuration for "${e}". Please ensure 'command' and 'args' are provided.`),!1):(ice(l)||cce(l))&&!this.isValidRemoteServerConfig(l)?(this.logger.error(`Invalid remote server configuration for "${e}". Please ensure 'url' is provided.`),!1):dce(l)&&!this.isValidInMemoryServerConfig(l)?(this.logger.error(`Invalid in-memory server configuration for "${e}". Please ensure 'serverInstance' is provided and is an instance of MCPServer.`),!1):!0:(this.logger.error(`No tools specified for server "${e}". Please provide a list of tools or "*" to include all tools.`),!1)}async processHttpServer(e,l){try{let n=this.resolveHeaders(l.headers,process.env),I={...l,headers:n};await this.registry.startHttpMcpClient(e,I),this.logger.log(`Started MCP client for remote server ${e}`)}catch(n){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${n}`),n}}async processSseServer(e,l){try{let n=this.resolveRemoteServerConfig(l);await this.registry.startSseMcpClient(e,n),this.logger.log(`Started MCP client for remote server ${e}`)}catch(n){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${n}`),n}}resolveRemoteServerConfig(e){return e.url=this.resolveString(e.url,process.env),e.headers=this.resolveHeaders(e.headers,process.env),{...e,url:e.url,headers:e.headers}}async processInMemoryServer(e,l){try{await this.registry.startInMemoryMcpClient(e,l.serverInstance),this.logger.log(`Started in-memory MCP client for ${e}`)}catch(n){throw this.logger.error(`Failed to start in-memory MCP client for ${e}: ${n}`),n}}async processLocalServer(e,l){let n={...l};if(l.command==="python")try{n=await this.convertPythonToPipx(n)}catch(a){this.logger.error(`Failed to handle Python module for ${e}: ${a}`)}let I=this.buildEnvironment(n),r=this.resolveLocalServerConfig(n,I);this.logger.log(`Starting MCP client for ${e} with command: ${r.command} and args: ${r.args}`);try{await this.registry.startLocalMcpClient(e,I,r.command,r.args),this.logger.log(`Started MCP client for ${e}`)}catch(a){throw this.logger.error(`Failed to start MCP client for ${e}: ${a}`),a}}convertPythonToPipx(e){if(!e||!e.args||e.args.length===0)return e;let l=e.args,n=l.indexOf("-m");if(n===-1||n===l.length-1)throw new Error("Python command with -m flag must specify a module");let I=l[n+1];this.logger.log(`Converting Python module: ${I} to pipx command`);let r=["run",I];for(let a=n+2;a<l.length;a++)r.push(l[a]);for(let a=0;a<n;a++)r.push(l[a]);return{...e,command:"pipx",args:r}}buildEnvironment(e){let l={};if(e.env)for(let[n,I]of Object.entries(e.env)){let r=I.trim();process.env[r]!==void 0&&(l[n]=process.env[r])}return l}resolveLocalServerConfig(e,l){let n=this.resolveString(e.command,l),I=this.resolveArray(e.args,l);return{...e,command:n,args:I}}resolveString(e,l){return l?e.replace(/\$(?:\{([A-Z0-9_]+)(?::-(.*?))?\}|([A-Z0-9_]+))/g,(n,I,r,a)=>{let o=l[I||a];return o!==void 0?o:r!==void 0?r:n}):e}resolveArray(e,l){return e?l?e.map(n=>this.resolveString(n,l)):e:[]}resolveHeaders(e,l){if(!e)return{};if(!l)return e;let n={};for(let[I,r]of Object.entries(e)){let a=this.resolveArray([r],l);n[I]=a[0]}return n}async processServers(e){if(!e)throw new Error("No servers to process");let l=Object.entries(e.mcpServers).map(([n,I])=>this.processServer(n,I));await Promise.all(l)}async processServer(e,l){if(!this.validateServerConfig(e,l)){this.logger.error(`Skipping server "${e}" due to invalid configuration.`);return}try{cK(l)?await this.processLocalServer(e,l):ice(l)&&this.remoteEnabled?await this.processHttpServer(e,l):cce(l)&&this.remoteEnabled?await this.processSseServer(e,l):dce(l)&&await this.processInMemoryServer(e,l)}catch(n){e!==y9&&await this.logServerFailure(e,n)}}async logServerFailure(e,l){if(this.sessionClient)try{await this.sessionClient.logMCPSetup(e,`<error>MCP server failed to start: ${l.message} - for the full output, see the verbose logs</error>`)}catch(n){this.logger.error(`Failed to log failure for MCP Server '${e}': '${n}'`)}}};var O2e=class{constructor(e,l,n){this.logger=e;let I;if(typeof l=="string"){if(I=JSON.parse(l),typeof I!="object")throw new Error("Invalid MCP configuration: must be an object");if(I===null||!("mcpServers"in I)||typeof I.mcpServers!="object")throw new Error("Invalid MCP configuration: missing or invalid mcpServers property");this.config=I}else this.config=l;this.disabledServers=new Set(n||[]),this.registry=new x2e(this.logger),this.processor=new S2e(this.logger,this.registry,{mcp3pEnabled:!0,remoteEnabled:!0})}registry;processor;config;startServersPromise=null;allTools=null;disabledServers;async startServers(){return this.startServersPromise||(this.startServersPromise=this.processServersWithExtensions()),this.startServersPromise}async injectDefaultServers(e){}async processServersWithExtensions(){await this.injectDefaultServers(this.config);let e;if(this.disabledServers.size>0){let l={};for(let[n,I]of Object.entries(this.config.mcpServers))this.disabledServers.has(n)?this.logger.log(`Skipping disabled MCP server: ${n}`):l[n]=I;e={...this.config,mcpServers:l}}else e=this.config;return this.processor.processServers(e)}async stopServers(){for(let[e,l]of Object.entries(this.registry.transports))try{await l.close()}catch(n){this.logger.error(`Error closing transport for ${e}: ${n}`)}this.startServersPromise=null,this.allTools=null}async getTools(e,l,n){if(!this.allTools){await this.startServers();let I=new hre(e,l,n),r=[];for(let a of Object.keys(this.registry.clients)){let s=await I.loadTools({mcpClient:this.registry.clients[a],clientName:a,tools:this.config.mcpServers[a]?.tools||["*"],filterMapping:this.config.mcpServers[a]?.filterMapping||"hidden_characters"});r.push(...s)}this.allTools=r}return this.allTools}getConfig(){return this.config}async startServer(e,l){await this.startServers(),this.config.mcpServers[e]=l,await this.processor.processServer(e,l),this.allTools=null}async stopServer(e){let l=this.registry.transports[e];if(l)try{await l.close(),delete this.registry.transports[e]}catch(n){this.logger.error(`Error closing transport for ${e}: ${n}`)}this.registry.clients[e]&&delete this.registry.clients[e],this.allTools=null}async restartServer(e,l){this.isServerRunning(e)&&await this.stopServer(e),delete this.config.mcpServers[e],await this.startServer(e,l)}isServerRunning(e){return e in this.registry.transports&&e in this.registry.clients}isServerDisabled(e){return this.disabledServers.has(e)}async disableServer(e){if(this.disabledServers.has(e)){this.logger.log(`Server ${e} is already disabled`);return}this.disabledServers.add(e),this.logger.log(`Disabled server ${e} for this session`),this.isServerRunning(e)&&await this.stopServer(e),this.allTools=null}async enableServer(e){if(!this.disabledServers.has(e)){this.logger.log(`Server ${e} is not disabled`);return}this.disabledServers.delete(e),this.logger.log(`Enabled server ${e} for this session`);let l=this.getServerConfig(e);l?await this.startServer(e,l):await this.startBuiltInServer(e),this.allTools=null}async startBuiltInServer(e){}getServerConfig(e){return this.config.mcpServers[e]}};c();var Apn="/login/device/code",Zpn="/login/oauth/access_token",xBt="Ov23ctDVkRmgkPke0Mmm",g2="https://github.com",Zk=class extends Error{constructor(l,n){super(n);this.status=l;this.message=n;this.name="GitHubApiError"}};function SBt(t){let e=new URL(t);return e.hostname.startsWith("api.")||(e.hostname="api."+e.hostname),e.href}async function OBt(t){let e=new URL(Apn,t),l=await fetch(e.href,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({client_id:xBt,scope:"user:email,read:user,repo,workflow"})});if(!l.ok)throw new Zk(l.status,`Failed to request device code: ${l.statusText}`);return await l.json()}async function TBt(t,e){let l=new URL(Zpn,t),n=await fetch(l.href,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({client_id:xBt,device_code:e,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})});if(!n.ok)throw new Zk(n.status,`Failed to authorize: ${n.statusText}`);let I=await n.json();if(typeof I.access_token=="string")return I.access_token;if(I.error!=="authorization_pending"&&I.error!=="slow_down")throw new Error(I.error_description||`Unexpected error: ${I.error}`)}async function uK(t,e){let l=new URL("/user",SBt(t)),n=await fetch(l.href,{headers:{Authorization:`Bearer ${e}`,Accept:"application/json"}});if(!n.ok)throw new Zk(n.status,`Failed to fetch user info: ${n.statusText}`);return(await n.json()).login}async function mK(t,e){let l=`
1897
+ ${r}`;await I.logMCPSetup(e,s),this.logger.log(`Updated session log for ${e} with ${l.length} tools`)}catch(r){this.logger.error(`Failed to update session log for ${e}: ${r}`)}}};c();var jPe={mcpServers:{}},S2e=class{constructor(e,l,n){this.logger=e;this.registry=l;this.remoteEnabled=n?.remoteEnabled??!1,this.mcp3pEnabled=n?.mcp3pEnabled??!1,this.blackbirdMetisIndexEnabled=n?.blackbirdMetisIndexEnabled??!1,this.sessionClient=n?.sessionClient,this.mcpEnvConfig=void 0}remoteEnabled;mcp3pEnabled;blackbirdMetisIndexEnabled;mcpEnvConfig;sessionClient;ReadMcpConfigFromEnv(e){this.mcpEnvConfig=process.env.GITHUB_COPILOT_MCP_JSON,this.mcp3pEnabled=process.env.GITHUB_COPILOT_3P_MCP_ENABLED==="true",this.remoteEnabled=process.env.GITHUB_COPILOT_REMOTE_MCP_ENABLED==="true",this.blackbirdMetisIndexEnabled=process.env.BLACKBIRD_METIS_INDEX_ENABLED==="true";let l=this.validateEnvConfig();return process.env.GITHUB_COPILOT_CLI_MODE==="true"?this.logger.log("CLI mode detected - skipping default MCP servers"):(this.logger.log("Adding default MCP servers to configuration"),this.configureBlackbirdMcp(l,e),this.configureGitHubMcp(l,e),this.configurePlaywrightMcp(l)),l}validateEnvConfig(){if(!this.mcp3pEnabled)return this.logger.log("User-provided MCPs are disabled"),jPe;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"),jPe;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}`),jPe}}configureGitHubMcp(e,l){this.remoteEnabled?this.configureRemoteGitHubMcp(e,l):this.configureLocalGitHubMcp(e)}configureRemoteGitHubMcp(e,l){this.logger.log("Using default remote GitHub MCP server configuration");let n="repos,issues,users,pull_requests,code_security,secret_protection,actions,web_search";process.env.COPILOT_MCP_COPILOT_SPACES_ENABLED==="true"&&(this.logger.log("Enabling Copilot Spaces in GitHub MCP server configuration"),n=n+",copilot_spaces");let I={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":n,"X-MCP-Host":"github-coding-agent","X-Initiator":"agent"};l&&l.api?.copilot?.integrationId&&(I["Copilot-Integration-Id"]=l.api.copilot.integrationId),process.env.GITHUB_COPILOT_INTERACTION_ID&&(I["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let r={type:"http",url:this.getCapiMcpUrl(),headers:I,tools:["*"],isDefaultServer:!0,filterMapping:{get_issue:"markdown",get_issue_comments:"markdown",get_pull_request:"markdown",get_pull_request_comments:"markdown",get_pull_request_reviews:"markdown"}};e.mcpServers[iK]=r}configureLocalGitHubMcp(e){if(e.mcpServers[iK]){this.logger.log("Using user-provided GitHub MCP server configuration");let l=e.mcpServers[iK]??{};cK(l)&&!l.command&&(e.mcpServers[iK]={...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[iK]=l}}configurePlaywrightMcp(e){if(!e.mcpServers[zPe]){if((process.env.COPILOT_FEATURE_FLAGS??"").split(",").map(n=>n.trim()).includes("copilot_swe_agent_playwright_use_firewall")){this.logger.log("Playwright MCP server is configured to use the firewall, skipping launch.");return}this.logger.log("Enabling Playwright MCP server");let l={command:"npx",args:[...NSe,"--allowed-origins","localhost;localhost:*;127.0.0.1;127.0.0.1:*"],tools:["*"],isDefaultServer:!0};e.mcpServers[zPe]=l}}configureBlackbirdMcp(e,l){this.remoteEnabled?this.configureRemoteBlackbirdMcp(e):this.blackbirdMetisIndexEnabled?this.configureLocalMetisBlackbirdMCP(e,l):this.configureLocalBlackbirdMcp(e)}configureLocalMetisBlackbirdMCP(e,l){this.logger.log("Using local Metis Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${l.blackbird?.mode}`);let n=process.env.AGENT_DIR||"/agent";this.logger.log(`Using agent directory: ${n}`);let I=[];l.blackbird?.mode==="tool"&&(I=["*"]),this.logger.log(`Using blackbird Metis server: ${l.blackbird?.mode}`);let r={command:`${n}/blackbird/mcp`,args:["serve","--index",`${n}/blackbird/metis`],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",COPILOT_API_HMAC_KEY:"CAPI_HMAC_KEY",MODEL_BASED_RETRIEVAL_TOKEN:"BLACKBIRD_AUTH_MODEL_BASED_RETRIEVAL_TOKEN",METIS_API_KEY:"BLACKBIRD_AUTH_METIS_API_KEY"},tools:I,isDefaultServer:!0};e.mcpServers[y9]=r}configureLocalBlackbirdMcp(e){this.logger.log("Using local Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let l=[];process.env.BLACKBIRD_MODE==="tool"&&(l=["*"]);let n={command:"./copilot-developer-action-main/blackbird-mcp-server/blackbird-mcp-server",args:["stdio"],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",CAPI_HOST:"COPILOT_API_URL"},tools:l,isDefaultServer:!0};e.mcpServers[y9]=n}configureRemoteBlackbirdMcp(e){this.logger.log("Using remote Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let l=[];process.env.BLACKBIRD_MODE==="tool"&&(l=["*"]);let n={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":"search_agent","X-MCP-Host":"github-coding-agent"};process.env.GITHUB_COPILOT_INTERACTION_ID&&(n["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let I={type:"http",url:this.getCapiMcpUrl(),headers:n,tools:l,isDefaultServer:!0};e.mcpServers[y9]=I}getCapiMcpUrl(){return process.env.COPILOT_API_URL?new URL("/mcp/readonly",process.env.COPILOT_API_URL).toString():"https://api.githubcopilot.com/mcp/readonly"}isValidServerType(e){return cK(e)||ice(e)||cce(e)||dce(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&&!cK(l)&&!dce(l)?(this.logger.error(`Unsupported server type "${l.type}" for server "${e}". Only "Local", "STDIO", or "Memory" are supported.`),!1):l.tools?cK(l)&&!this.isValidLocalServerConfig(l)?(this.logger.error(`Invalid local server configuration for "${e}". Please ensure 'command' and 'args' are provided.`),!1):(ice(l)||cce(l))&&!this.isValidRemoteServerConfig(l)?(this.logger.error(`Invalid remote server configuration for "${e}". Please ensure 'url' is provided.`),!1):dce(l)&&!this.isValidInMemoryServerConfig(l)?(this.logger.error(`Invalid in-memory server configuration for "${e}". Please ensure 'serverInstance' is provided and is an instance of MCPServer.`),!1):!0:(this.logger.error(`No tools specified for server "${e}". Please provide a list of tools or "*" to include all tools.`),!1)}async processHttpServer(e,l){try{let n=this.resolveHeaders(l.headers,process.env),I={...l,headers:n};await this.registry.startHttpMcpClient(e,I),this.logger.log(`Started MCP client for remote server ${e}`)}catch(n){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${n}`),n}}async processSseServer(e,l){try{let n=this.resolveRemoteServerConfig(l);await this.registry.startSseMcpClient(e,n),this.logger.log(`Started MCP client for remote server ${e}`)}catch(n){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${n}`),n}}resolveRemoteServerConfig(e){return e.url=this.resolveString(e.url,process.env),e.headers=this.resolveHeaders(e.headers,process.env),{...e,url:e.url,headers:e.headers}}async processInMemoryServer(e,l){try{await this.registry.startInMemoryMcpClient(e,l.serverInstance),this.logger.log(`Started in-memory MCP client for ${e}`)}catch(n){throw this.logger.error(`Failed to start in-memory MCP client for ${e}: ${n}`),n}}async processLocalServer(e,l){let n={...l};if(l.command==="python")try{n=await this.convertPythonToPipx(n)}catch(a){this.logger.error(`Failed to handle Python module for ${e}: ${a}`)}let I=this.buildEnvironment(n),r=this.resolveLocalServerConfig(n,I);this.logger.log(`Starting MCP client for ${e} with command: ${r.command} and args: ${r.args}`);try{await this.registry.startLocalMcpClient(e,I,r.command,r.args),this.logger.log(`Started MCP client for ${e}`)}catch(a){throw this.logger.error(`Failed to start MCP client for ${e}: ${a}`),a}}convertPythonToPipx(e){if(!e||!e.args||e.args.length===0)return e;let l=e.args,n=l.indexOf("-m");if(n===-1||n===l.length-1)throw new Error("Python command with -m flag must specify a module");let I=l[n+1];this.logger.log(`Converting Python module: ${I} to pipx command`);let r=["run",I];for(let a=n+2;a<l.length;a++)r.push(l[a]);for(let a=0;a<n;a++)r.push(l[a]);return{...e,command:"pipx",args:r}}buildEnvironment(e){let l={};if(e.env)for(let[n,I]of Object.entries(e.env)){let r=I.trim(),a=r;if(r.includes("$")&&(a=this.resolveString(r,process.env)),a!==r){l[n]=a;continue}process.env[r]!==void 0&&(l[n]=process.env[r])}return l}resolveLocalServerConfig(e,l){let n=this.resolveString(e.command,l),I=this.resolveArray(e.args,l);return{...e,command:n,args:I}}resolveString(e,l){return l?e.replace(/\$(?:\{([A-Z0-9_]+)(?::-(.*?))?\}|([A-Z0-9_]+))/g,(n,I,r,a)=>{let o=l[I||a];return o!==void 0?o:r!==void 0?r:n}):e}resolveArray(e,l){return e?l?e.map(n=>this.resolveString(n,l)):e:[]}resolveHeaders(e,l){if(!e)return{};if(!l)return e;let n={};for(let[I,r]of Object.entries(e)){let a=this.resolveArray([r],l);n[I]=a[0]}return n}async processServers(e){if(!e)throw new Error("No servers to process");let l=Object.entries(e.mcpServers).map(([n,I])=>this.processServer(n,I));await Promise.all(l)}async processServer(e,l){if(!this.validateServerConfig(e,l)){this.logger.error(`Skipping server "${e}" due to invalid configuration.`);return}try{cK(l)?await this.processLocalServer(e,l):ice(l)&&this.remoteEnabled?await this.processHttpServer(e,l):cce(l)&&this.remoteEnabled?await this.processSseServer(e,l):dce(l)&&await this.processInMemoryServer(e,l)}catch(n){e!==y9&&await this.logServerFailure(e,n)}}async logServerFailure(e,l){if(this.sessionClient)try{await this.sessionClient.logMCPSetup(e,`<error>MCP server failed to start: ${l.message} - for the full output, see the verbose logs</error>`)}catch(n){this.logger.error(`Failed to log failure for MCP Server '${e}': '${n}'`)}}};var O2e=class{constructor(e,l,n){this.logger=e;let I;if(typeof l=="string"){if(I=JSON.parse(l),typeof I!="object")throw new Error("Invalid MCP configuration: must be an object");if(I===null||!("mcpServers"in I)||typeof I.mcpServers!="object")throw new Error("Invalid MCP configuration: missing or invalid mcpServers property");this.config=I}else this.config=l;this.disabledServers=new Set(n||[]),this.registry=new x2e(this.logger),this.processor=new S2e(this.logger,this.registry,{mcp3pEnabled:!0,remoteEnabled:!0})}registry;processor;config;startServersPromise=null;allTools=null;disabledServers;async startServers(){return this.startServersPromise||(this.startServersPromise=this.processServersWithExtensions()),this.startServersPromise}async injectDefaultServers(e){}async processServersWithExtensions(){await this.injectDefaultServers(this.config);let e;if(this.disabledServers.size>0){let l={};for(let[n,I]of Object.entries(this.config.mcpServers))this.disabledServers.has(n)?this.logger.log(`Skipping disabled MCP server: ${n}`):l[n]=I;e={...this.config,mcpServers:l}}else e=this.config;return this.processor.processServers(e)}async stopServers(){for(let[e,l]of Object.entries(this.registry.transports))try{await l.close()}catch(n){this.logger.error(`Error closing transport for ${e}: ${n}`)}this.startServersPromise=null,this.allTools=null}async getTools(e,l,n){if(!this.allTools){await this.startServers();let I=new hre(e,l,n),r=[];for(let a of Object.keys(this.registry.clients)){let s=await I.loadTools({mcpClient:this.registry.clients[a],clientName:a,tools:this.config.mcpServers[a]?.tools||["*"],filterMapping:this.config.mcpServers[a]?.filterMapping||"hidden_characters"});r.push(...s)}this.allTools=r}return this.allTools}getConfig(){return this.config}async startServer(e,l){await this.startServers(),this.config.mcpServers[e]=l,await this.processor.processServer(e,l),this.allTools=null}async stopServer(e){let l=this.registry.transports[e];if(l)try{await l.close(),delete this.registry.transports[e]}catch(n){this.logger.error(`Error closing transport for ${e}: ${n}`)}this.registry.clients[e]&&delete this.registry.clients[e],this.allTools=null}async restartServer(e,l){this.isServerRunning(e)&&await this.stopServer(e),delete this.config.mcpServers[e],await this.startServer(e,l)}isServerRunning(e){return e in this.registry.transports&&e in this.registry.clients}isServerDisabled(e){return this.disabledServers.has(e)}async disableServer(e){if(this.disabledServers.has(e)){this.logger.log(`Server ${e} is already disabled`);return}this.disabledServers.add(e),this.logger.log(`Disabled server ${e} for this session`),this.isServerRunning(e)&&await this.stopServer(e),this.allTools=null}async enableServer(e){if(!this.disabledServers.has(e)){this.logger.log(`Server ${e} is not disabled`);return}this.disabledServers.delete(e),this.logger.log(`Enabled server ${e} for this session`);let l=this.getServerConfig(e);l?await this.startServer(e,l):await this.startBuiltInServer(e),this.allTools=null}async startBuiltInServer(e){}getServerConfig(e){return this.config.mcpServers[e]}};c();var Apn="/login/device/code",Zpn="/login/oauth/access_token",xBt="Ov23ctDVkRmgkPke0Mmm",g2="https://github.com",Zk=class extends Error{constructor(l,n){super(n);this.status=l;this.message=n;this.name="GitHubApiError"}};function SBt(t){let e=new URL(t);return e.hostname.startsWith("api.")||(e.hostname="api."+e.hostname),e.href}async function OBt(t){let e=new URL(Apn,t),l=await fetch(e.href,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({client_id:xBt,scope:"user:email,read:user,repo,workflow"})});if(!l.ok)throw new Zk(l.status,`Failed to request device code: ${l.statusText}`);return await l.json()}async function TBt(t,e){let l=new URL(Zpn,t),n=await fetch(l.href,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({client_id:xBt,device_code:e,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})});if(!n.ok)throw new Zk(n.status,`Failed to authorize: ${n.statusText}`);let I=await n.json();if(typeof I.access_token=="string")return I.access_token;if(I.error!=="authorization_pending"&&I.error!=="slow_down")throw new Error(I.error_description||`Unexpected error: ${I.error}`)}async function uK(t,e){let l=new URL("/user",SBt(t)),n=await fetch(l.href,{headers:{Authorization:`Bearer ${e}`,Accept:"application/json"}});if(!n.ok)throw new Zk(n.status,`Failed to fetch user info: ${n.statusText}`);return(await n.json()).login}async function mK(t,e){let l=`
1898
1898
  {
1899
1899
  viewer {
1900
1900
  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.339-11",
4
+ "version": "0.0.339-12",
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": "3794e65"
36
+ "gitCommit": "6812c15"
37
37
  },
38
38
  "dependencies": {
39
39
  "node-pty": "npm:@devm33/node-pty@^1.0.8",
package/sdk/index.js CHANGED
@@ -1350,7 +1350,7 @@ Pay attention to the following when using it:
1350
1350
  `}var ijI=Zq.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function bjI(){let t={};for(let e of ijI){let I=Zq.env[e];I!==void 0&&(I.startsWith("()")||(t[e]=I))}return t}var pq=class{constructor(e){this._abortController=new AbortController,this._readBuffer=new hq,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new djI)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,I)=>{var l,n,c,a,s;this._process=(0,qDe.default)(this._serverParams.command,(l=this._serverParams.args)!==null&&l!==void 0?l:[],{env:{...bjI(),...this._serverParams.env},stdio:["pipe","pipe",(n=this._serverParams.stderr)!==null&&n!==void 0?n:"inherit"],shell:!1,signal:this._abortController.signal,windowsHide:Zq.platform==="win32"&&mjI(),cwd:this._serverParams.cwd}),this._process.on("error",r=>{var o,d;if(r.name==="AbortError"){(o=this.onclose)===null||o===void 0||o.call(this);return}I(r),(d=this.onerror)===null||d===void 0||d.call(this,r)}),this._process.on("spawn",()=>{e()}),this._process.on("close",r=>{var o;this._process=void 0,(o=this.onclose)===null||o===void 0||o.call(this)}),(c=this._process.stdin)===null||c===void 0||c.on("error",r=>{var o;(o=this.onerror)===null||o===void 0||o.call(this,r)}),(a=this._process.stdout)===null||a===void 0||a.on("data",r=>{this._readBuffer.append(r),this.processReadBuffer()}),(s=this._process.stdout)===null||s===void 0||s.on("error",r=>{var o;(o=this.onerror)===null||o===void 0||o.call(this,r)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){var e,I;return this._stderrStream?this._stderrStream:(I=(e=this._process)===null||e===void 0?void 0:e.stderr)!==null&&I!==void 0?I:null}get pid(){var e,I;return(I=(e=this._process)===null||e===void 0?void 0:e.pid)!==null&&I!==void 0?I:null}processReadBuffer(){for(var e,I;;)try{let l=this._readBuffer.readMessage();if(l===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,l)}catch(l){(I=this.onerror)===null||I===void 0||I.call(this,l)}}async close(){this._abortController.abort(),this._process=void 0,this._readBuffer.clear()}send(e){return new Promise(I=>{var l;if(!(!((l=this._process)===null||l===void 0)&&l.stdin))throw new Error("Not connected");let n=PDe(e);this._process.stdin.write(n)?I():this._process.stdin.once("drain",I)})}};function mjI(){return"type"in Zq}G();G();var uq=class extends TransformStream{constructor({onError:e,onRetry:I,onComment:l}={}){let n;super({start(c){n=Gq({onEvent:a=>{c.enqueue(a)},onError(a){e==="terminate"?c.error(a):typeof e=="function"&&e(a)},onRetry:I,onComment:l})},transform(c){n.feed(c)}})}};var hjI={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Fx=class extends Error{constructor(e,I){super(`Streamable HTTP error: ${I}`),this.code=e}},Wq=class{constructor(e,I){var l;this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=I?.requestInit,this._authProvider=I?.authProvider,this._fetch=I?.fetch,this._sessionId=I?.sessionId,this._reconnectionOptions=(l=I?.reconnectionOptions)!==null&&l!==void 0?l:hjI}async _authThenStart(){var e;if(!this._authProvider)throw new eo("No auth provider");let I;try{I=await NV(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(l){throw(e=this.onerror)===null||e===void 0||e.call(this,l),l}if(I!=="AUTHORIZED")throw new eo;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let I={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(I.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(I["mcp-session-id"]=this._sessionId),this._protocolVersion&&(I["mcp-protocol-version"]=this._protocolVersion);let l=this._normalizeHeaders((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...I,...l})}async _startOrAuthSse(e){var I,l,n;let{resumptionToken:c}=e;try{let a=await this._commonHeaders();a.set("Accept","text/event-stream"),c&&a.set("last-event-id",c);let s=await((I=this._fetch)!==null&&I!==void 0?I:fetch)(this._url,{method:"GET",headers:a,signal:(l=this._abortController)===null||l===void 0?void 0:l.signal});if(!s.ok){if(s.status===401&&this._authProvider)return await this._authThenStart();if(s.status===405)return;throw new Fx(s.status,`Failed to open SSE stream: ${s.statusText}`)}this._handleSseStream(s.body,e,!0)}catch(a){throw(n=this.onerror)===null||n===void 0||n.call(this,a),a}}_getNextReconnectionDelay(e){let I=this._reconnectionOptions.initialReconnectionDelay,l=this._reconnectionOptions.reconnectionDelayGrowFactor,n=this._reconnectionOptions.maxReconnectionDelay;return Math.min(I*Math.pow(l,e),n)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,I=0){var l;let n=this._reconnectionOptions.maxRetries;if(n>0&&I>=n){(l=this.onerror)===null||l===void 0||l.call(this,new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let c=this._getNextReconnectionDelay(I);setTimeout(()=>{this._startOrAuthSse(e).catch(a=>{var s;(s=this.onerror)===null||s===void 0||s.call(this,new Error(`Failed to reconnect SSE stream: ${a instanceof Error?a.message:String(a)}`)),this._scheduleReconnection(e,I+1)})},c)}_handleSseStream(e,I,l){if(!e)return;let{onresumptiontoken:n,replayMessageId:c}=I,a;(async()=>{var r,o,d,i;try{let h=e.pipeThrough(new TextDecoderStream).pipeThrough(new uq).getReader();for(;;){let{value:p,done:Z}=await h.read();if(Z)break;if(p.id&&(a=p.id,n?.(p.id)),!p.event||p.event==="message")try{let u=dV.parse(JSON.parse(p.data));c!==void 0&&E9(u)&&(u.id=c),(r=this.onmessage)===null||r===void 0||r.call(this,u)}catch(u){(o=this.onerror)===null||o===void 0||o.call(this,u)}}}catch(h){if((d=this.onerror)===null||d===void 0||d.call(this,new Error(`SSE stream disconnected: ${h}`)),l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:n,replayMessageId:c},0)}catch(p){(i=this.onerror)===null||i===void 0||i.call(this,new Error(`Failed to reconnect: ${p instanceof Error?p.message:String(p)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new eo("No auth provider");if(await NV(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new eo("Failed to authorize")}async close(){var e,I;(e=this._abortController)===null||e===void 0||e.abort(),(I=this.onclose)===null||I===void 0||I.call(this)}async send(e,I){var l,n,c,a;try{let{resumptionToken:s,onresumptiontoken:r}=I||{};if(s){this._startOrAuthSse({resumptionToken:s,replayMessageId:Z6(e)?e.id:void 0}).catch(N=>{var Y;return(Y=this.onerror)===null||Y===void 0?void 0:Y.call(this,N)});return}let o=await this._commonHeaders();o.set("content-type","application/json"),o.set("accept","application/json, text/event-stream");let d={...this._requestInit,method:"POST",headers:o,body:JSON.stringify(e),signal:(l=this._abortController)===null||l===void 0?void 0:l.signal},i=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._url,d),h=i.headers.get("mcp-session-id");if(h&&(this._sessionId=h),!i.ok){if(i.status===401&&this._authProvider){if(this._resourceMetadataUrl=yx(i),await NV(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new eo;return this.send(e)}let N=await i.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${i.status}): ${N}`)}if(i.status===202){sMe(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(N=>{var Y;return(Y=this.onerror)===null||Y===void 0?void 0:Y.call(this,N)});return}let Z=(Array.isArray(e)?e:[e]).filter(N=>"method"in N&&"id"in N&&N.id!==void 0).length>0,u=i.headers.get("content-type");if(Z)if(u?.includes("text/event-stream"))this._handleSseStream(i.body,{onresumptiontoken:r},!1);else if(u?.includes("application/json")){let N=await i.json(),Y=Array.isArray(N)?N.map(y=>dV.parse(y)):[dV.parse(N)];for(let y of Y)(c=this.onmessage)===null||c===void 0||c.call(this,y)}else throw new Fx(-1,`Unexpected content type: ${u}`)}catch(s){throw(a=this.onerror)===null||a===void 0||a.call(this,s),s}}get sessionId(){return this._sessionId}async terminateSession(){var e,I,l;if(this._sessionId)try{let n=await this._commonHeaders(),c={...this._requestInit,method:"DELETE",headers:n,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},a=await((I=this._fetch)!==null&&I!==void 0?I:fetch)(this._url,c);if(!a.ok&&a.status!==405)throw new Fx(a.status,`Failed to terminate session: ${a.statusText}`);this._sessionId=void 0}catch(n){throw(l=this.onerror)===null||l===void 0||l.call(this,n),n}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}};G();var Nq=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 Epe(this),await this.server.connect(this.serverTransport)}async send(e){if(this.closed)throw new Error("Transport is closed");setImmediate(()=>{try{this.serverTransport?.onmessage?.(e)}catch(I){this.onerror?.(I instanceof Error?I:new Error(String(I)))}})}receive(e){this.closed||this.onmessage?.(e)}async close(){this.closed||(this.closed=!0,await this.serverTransport?.close(),this.onclose?.())}},Epe=class{constructor(e){this.clientTransport=e}onmessage;onerror;onclose;closed=!1;async start(){}async send(e){if(this.closed)throw new Error("Transport is closed");setImmediate(()=>{try{this.clientTransport.receive(e)}catch(I){this.onerror?.(I instanceof Error?I:new Error(String(I)))}})}async close(){this.closed||(this.closed=!0,this.onclose?.())}};var Yq=class{createTransport(e){switch(e.type){case"stdio":{let I=new pq({command:e.command,args:e.args,env:e.env,stderr:e.stderr?"pipe":void 0});return I.stderr?.pipe(e.stderr),I}case"http":return new Wq(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"sse":return new bq(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"memory":return new Nq(e.server);default:throw new Error(`Unsupported transport type: ${e.type}`)}}};G();var rF="blackbird-mcp-server",_E="github-mcp-server",vpe="playwright";function $E(t){return t.type===void 0||t.type.toLowerCase()==="local"||t.type.toLowerCase()==="stdio"}function Vq(t){return t.type?.toLowerCase()==="http"}function Rq(t){return t.type?.toLowerCase()==="sse"}function gx(t){return t.type?.toLowerCase()==="memory"}var Cpe=class extends pjI{constructor(I,l){super({decodeStrings:!1});this.serverName=I;this.logger=l}_write(I,l,n){try{let c=I.toString();this.logger.log(`[mcp server ${this.serverName} stderr] ${c}`),n()}catch(c){n(c instanceof Error?c:new Error(String(c)))}}},yq=class{constructor(e,I=new sq,l=new Yq){this.logger=e;this.clientFactory=I;this.transportFactory=l}clients={};transports={};async startLocalMcpClient(e,I,l,n){this.logger.log(`Starting MCP client for ${e} with command: ${l} and args: ${n}`);let c=new Cpe(e,this.logger),a={type:"stdio",command:l,args:n,env:{...I,PATH:process.env.PATH},stderr:c},s=this.transportFactory.createTransport(a);await this.setupAndConnectClient(e,s)}async startHttpMcpClient(e,I){this.logger.log(`Starting remote MCP client for ${e} with url: ${I.url}`);let l={type:"http",url:I.url,headers:I.headers},n=this.transportFactory.createTransport(l);await this.setupAndConnectClient(e,n)}async startSseMcpClient(e,I){this.logger.log(`Starting remote MCP client for ${e} with url: ${I.url}`);let l={type:"sse",url:I.url,headers:I.headers},n=this.transportFactory.createTransport(l);await this.setupAndConnectClient(e,n)}async startInMemoryMcpClient(e,I){this.logger.log(`Starting in-memory MCP client for ${e}`);let l={type:"memory",server:I},n=this.transportFactory.createTransport(l);await this.setupAndConnectClient(e,n)}async setupAndConnectClient(e,I){this.transports[e]=I,I.onclose=()=>{this.logger.log(`MCP transport for ${e} closed`),delete this.transports[e]},this.logger.log(`Creating MCP client for ${e}...`);let l=this.clientFactory.createClient({name:"github-copilot-developer",version:"1.0.0"},{capabilities:{experimental:void 0,roots:void 0,sampling:void 0}}),n=Date.now();this.logger.log(`Connecting MCP client for ${e}...`),await l.connect(I),l.onclose=()=>{this.logger.log(`MCP client for ${e} closed`),delete this.clients[e]},l.onerror=c=>{this.logger.error(`MCP client for ${e} errored ${c}`)},this.logger.log(`MCP client for ${e} connected, took ${Date.now()-n}ms`),this.clients[e]=l}async getTools(e,I){let l={};for(let[n,c]of Object.entries(this.clients)){let a=[];try{this.logger.log(`Fetching tools from client: ${n}`);let s=await c.listTools(),r=e?.mcpServers[n].tools,o=e?.mcpServers[n].filterMapping;for(let i of s.tools){if(i.name==="get_copilot_space")continue;if(!(r?.includes("*")||r?.includes(i.name))){this.logger.log(`Tool ${i.name} is not in the allowed list for client: ${n}`);continue}let p=n6(n,i.name),Z=`${n}-${i.name}`,u;typeof o=="string"?u=tbe(o):u=tbe(o?.[i.name]??"hidden_characters"),l[`${n}/${i.name}`]={name:Z,title:i.title??i.annotations?.title??i.name,description:i.description??Z,input_schema:i.inputSchema,readOnly:i.annotations?.readOnlyHint,safeForTelemetry:{name:!!(e?.mcpServers[n].isDefaultServer||p),inputsNames:!!e?.mcpServers[n].isDefaultServer},filterMode:u},a.push(i.name),this.logger.log(`Tool ${i.name} added to tools list for client: ${n}`)}this.logger.log(`Successfully retrieved ${a.length} tools from client: ${n}`);let d=c.getServerVersion();await this.logServerSuccessWithTools(n,a,d,I)}catch(s){this.logger.error(`Failed to get tools from client: ${n} ${s}`)}}return this.logger.log(`All tools retrieved: ${JSON.stringify(l,null,2)}`),l}async logServerSuccessWithTools(e,I,l,n){if(e!=rF&&n)try{let c=I.map(r=>`- ${r}`).join(`
1351
1351
  `),s=`MCP server started successfully${l?` (version ${l.version})`:""} with ${I.length} ${I.length===1?"tool":"tools"} - for the full output, see the verbose logs
1352
1352
 
1353
- ${c}`;await n.logMCPSetup(e,s),this.logger.log(`Updated session log for ${e} with ${I.length} tools`)}catch(c){this.logger.error(`Failed to update session log for ${e}: ${c}`)}}};G();var Jpe={mcpServers:{}},Fq=class{constructor(e,I,l){this.logger=e;this.registry=I;this.remoteEnabled=l?.remoteEnabled??!1,this.mcp3pEnabled=l?.mcp3pEnabled??!1,this.blackbirdMetisIndexEnabled=l?.blackbirdMetisIndexEnabled??!1,this.sessionClient=l?.sessionClient,this.mcpEnvConfig=void 0}remoteEnabled;mcp3pEnabled;blackbirdMetisIndexEnabled;mcpEnvConfig;sessionClient;ReadMcpConfigFromEnv(e){this.mcpEnvConfig=process.env.GITHUB_COPILOT_MCP_JSON,this.mcp3pEnabled=process.env.GITHUB_COPILOT_3P_MCP_ENABLED==="true",this.remoteEnabled=process.env.GITHUB_COPILOT_REMOTE_MCP_ENABLED==="true",this.blackbirdMetisIndexEnabled=process.env.BLACKBIRD_METIS_INDEX_ENABLED==="true";let I=this.validateEnvConfig();return process.env.GITHUB_COPILOT_CLI_MODE==="true"?this.logger.log("CLI mode detected - skipping default MCP servers"):(this.logger.log("Adding default MCP servers to configuration"),this.configureBlackbirdMcp(I,e),this.configureGitHubMcp(I,e),this.configurePlaywrightMcp(I)),I}validateEnvConfig(){if(!this.mcp3pEnabled)return this.logger.log("User-provided MCPs are disabled"),Jpe;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"),Jpe;try{let e=JSON.parse(this.mcpEnvConfig);if(!e.mcpServers)throw new Error("User-provided config had incorrect format. Missing 'mcpServers' property.");for(let I in e.mcpServers)e.mcpServers[I].isDefaultServer=!1;return e}catch(e){return this.logger.error(`Warning: User-provided MCP servers were defined but invalid: ${e}`),Jpe}}configureGitHubMcp(e,I){this.remoteEnabled?this.configureRemoteGitHubMcp(e,I):this.configureLocalGitHubMcp(e)}configureRemoteGitHubMcp(e,I){this.logger.log("Using default remote GitHub MCP server configuration");let l="repos,issues,users,pull_requests,code_security,secret_protection,actions,web_search";process.env.COPILOT_MCP_COPILOT_SPACES_ENABLED==="true"&&(this.logger.log("Enabling Copilot Spaces in GitHub MCP server configuration"),l=l+",copilot_spaces");let n={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":l,"X-MCP-Host":"github-coding-agent","X-Initiator":"agent"};I&&I.api?.copilot?.integrationId&&(n["Copilot-Integration-Id"]=I.api.copilot.integrationId),process.env.GITHUB_COPILOT_INTERACTION_ID&&(n["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let c={type:"http",url:this.getCapiMcpUrl(),headers:n,tools:["*"],isDefaultServer:!0,filterMapping:{get_issue:"markdown",get_issue_comments:"markdown",get_pull_request:"markdown",get_pull_request_comments:"markdown",get_pull_request_reviews:"markdown"}};e.mcpServers[_E]=c}configureLocalGitHubMcp(e){if(e.mcpServers[_E]){this.logger.log("Using user-provided GitHub MCP server configuration");let I=e.mcpServers[_E]??{};$E(I)&&!I.command&&(e.mcpServers[_E]={...I,command:"./copilot-developer-action-main/github-mcp-server/github-mcp-server",isDefaultServer:!0},this.logger.log("Added default command to user-provided GitHub MCP server configuration"))}else{this.logger.log("Using default local GitHub MCP server configuration");let I={command:"./copilot-developer-action-main/github-mcp-server/github-mcp-server",args:["stdio","--read-only"],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",GITHUB_HOST:"GITHUB_SERVER_URL"},tools:["*"],isDefaultServer:!0};e.mcpServers[_E]=I}}configurePlaywrightMcp(e){if(!e.mcpServers[vpe]){if((process.env.COPILOT_FEATURE_FLAGS??"").split(",").map(l=>l.trim()).includes("copilot_swe_agent_playwright_use_firewall")){this.logger.log("Playwright MCP server is configured to use the firewall, skipping launch.");return}this.logger.log("Enabling Playwright MCP server");let I={command:"npx",args:[...Tbe,"--allowed-origins","localhost;localhost:*;127.0.0.1;127.0.0.1:*"],tools:["*"],isDefaultServer:!0};e.mcpServers[vpe]=I}}configureBlackbirdMcp(e,I){this.remoteEnabled?this.configureRemoteBlackbirdMcp(e):this.blackbirdMetisIndexEnabled?this.configureLocalMetisBlackbirdMCP(e,I):this.configureLocalBlackbirdMcp(e)}configureLocalMetisBlackbirdMCP(e,I){this.logger.log("Using local Metis Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${I.blackbird?.mode}`);let l=process.env.AGENT_DIR||"/agent";this.logger.log(`Using agent directory: ${l}`);let n=[];I.blackbird?.mode==="tool"&&(n=["*"]),this.logger.log(`Using blackbird Metis server: ${I.blackbird?.mode}`);let c={command:`${l}/blackbird/mcp`,args:["serve","--index",`${l}/blackbird/metis`],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",COPILOT_API_HMAC_KEY:"CAPI_HMAC_KEY",MODEL_BASED_RETRIEVAL_TOKEN:"BLACKBIRD_AUTH_MODEL_BASED_RETRIEVAL_TOKEN",METIS_API_KEY:"BLACKBIRD_AUTH_METIS_API_KEY"},tools:n,isDefaultServer:!0};e.mcpServers[rF]=c}configureLocalBlackbirdMcp(e){this.logger.log("Using local Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let I=[];process.env.BLACKBIRD_MODE==="tool"&&(I=["*"]);let l={command:"./copilot-developer-action-main/blackbird-mcp-server/blackbird-mcp-server",args:["stdio"],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",CAPI_HOST:"COPILOT_API_URL"},tools:I,isDefaultServer:!0};e.mcpServers[rF]=l}configureRemoteBlackbirdMcp(e){this.logger.log("Using remote Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let I=[];process.env.BLACKBIRD_MODE==="tool"&&(I=["*"]);let l={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":"search_agent","X-MCP-Host":"github-coding-agent"};process.env.GITHUB_COPILOT_INTERACTION_ID&&(l["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let n={type:"http",url:this.getCapiMcpUrl(),headers:l,tools:I,isDefaultServer:!0};e.mcpServers[rF]=n}getCapiMcpUrl(){return process.env.COPILOT_API_URL?new URL("/mcp/readonly",process.env.COPILOT_API_URL).toString():"https://api.githubcopilot.com/mcp/readonly"}isValidServerType(e){return $E(e)||Vq(e)||Rq(e)||gx(e)}isValidLocalServerConfig(e){return e.command!==void 0&&e.command.trim()!==""&&Array.isArray(e.args)}isValidRemoteServerConfig(e){return e.url!==void 0&&e.url.trim()!==""}isValidInMemoryServerConfig(e){return e.serverInstance!==void 0&&typeof e.serverInstance=="object"}validateServerConfig(e,I){return this.remoteEnabled&&!this.isValidServerType(I)?(this.logger.error(`Unsupported server type "${I.type}" for server "${e}". Only "Local", "STDIO", "HTTP", "SSE", or "Memory" are supported.`),!1):!this.remoteEnabled&&!$E(I)&&!gx(I)?(this.logger.error(`Unsupported server type "${I.type}" for server "${e}". Only "Local", "STDIO", or "Memory" are supported.`),!1):I.tools?$E(I)&&!this.isValidLocalServerConfig(I)?(this.logger.error(`Invalid local server configuration for "${e}". Please ensure 'command' and 'args' are provided.`),!1):(Vq(I)||Rq(I))&&!this.isValidRemoteServerConfig(I)?(this.logger.error(`Invalid remote server configuration for "${e}". Please ensure 'url' is provided.`),!1):gx(I)&&!this.isValidInMemoryServerConfig(I)?(this.logger.error(`Invalid in-memory server configuration for "${e}". Please ensure 'serverInstance' is provided and is an instance of MCPServer.`),!1):!0:(this.logger.error(`No tools specified for server "${e}". Please provide a list of tools or "*" to include all tools.`),!1)}async processHttpServer(e,I){try{let l=this.resolveHeaders(I.headers,process.env),n={...I,headers:l};await this.registry.startHttpMcpClient(e,n),this.logger.log(`Started MCP client for remote server ${e}`)}catch(l){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${l}`),l}}async processSseServer(e,I){try{let l=this.resolveRemoteServerConfig(I);await this.registry.startSseMcpClient(e,l),this.logger.log(`Started MCP client for remote server ${e}`)}catch(l){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${l}`),l}}resolveRemoteServerConfig(e){return e.url=this.resolveString(e.url,process.env),e.headers=this.resolveHeaders(e.headers,process.env),{...e,url:e.url,headers:e.headers}}async processInMemoryServer(e,I){try{await this.registry.startInMemoryMcpClient(e,I.serverInstance),this.logger.log(`Started in-memory MCP client for ${e}`)}catch(l){throw this.logger.error(`Failed to start in-memory MCP client for ${e}: ${l}`),l}}async processLocalServer(e,I){let l={...I};if(I.command==="python")try{l=await this.convertPythonToPipx(l)}catch(a){this.logger.error(`Failed to handle Python module for ${e}: ${a}`)}let n=this.buildEnvironment(l),c=this.resolveLocalServerConfig(l,n);this.logger.log(`Starting MCP client for ${e} with command: ${c.command} and args: ${c.args}`);try{await this.registry.startLocalMcpClient(e,n,c.command,c.args),this.logger.log(`Started MCP client for ${e}`)}catch(a){throw this.logger.error(`Failed to start MCP client for ${e}: ${a}`),a}}convertPythonToPipx(e){if(!e||!e.args||e.args.length===0)return e;let I=e.args,l=I.indexOf("-m");if(l===-1||l===I.length-1)throw new Error("Python command with -m flag must specify a module");let n=I[l+1];this.logger.log(`Converting Python module: ${n} to pipx command`);let c=["run",n];for(let a=l+2;a<I.length;a++)c.push(I[a]);for(let a=0;a<l;a++)c.push(I[a]);return{...e,command:"pipx",args:c}}buildEnvironment(e){let I={};if(e.env)for(let[l,n]of Object.entries(e.env)){let c=n.trim();process.env[c]!==void 0&&(I[l]=process.env[c])}return I}resolveLocalServerConfig(e,I){let l=this.resolveString(e.command,I),n=this.resolveArray(e.args,I);return{...e,command:l,args:n}}resolveString(e,I){return I?e.replace(/\$(?:\{([A-Z0-9_]+)(?::-(.*?))?\}|([A-Z0-9_]+))/g,(l,n,c,a)=>{let r=I[n||a];return r!==void 0?r:c!==void 0?c:l}):e}resolveArray(e,I){return e?I?e.map(l=>this.resolveString(l,I)):e:[]}resolveHeaders(e,I){if(!e)return{};if(!I)return e;let l={};for(let[n,c]of Object.entries(e)){let a=this.resolveArray([c],I);l[n]=a[0]}return l}async processServers(e){if(!e)throw new Error("No servers to process");let I=Object.entries(e.mcpServers).map(([l,n])=>this.processServer(l,n));await Promise.all(I)}async processServer(e,I){if(!this.validateServerConfig(e,I)){this.logger.error(`Skipping server "${e}" due to invalid configuration.`);return}try{$E(I)?await this.processLocalServer(e,I):Vq(I)&&this.remoteEnabled?await this.processHttpServer(e,I):Rq(I)&&this.remoteEnabled?await this.processSseServer(e,I):gx(I)&&await this.processInMemoryServer(e,I)}catch(l){e!==rF&&await this.logServerFailure(e,l)}}async logServerFailure(e,I){if(this.sessionClient)try{await this.sessionClient.logMCPSetup(e,`<error>MCP server failed to start: ${I.message} - for the full output, see the verbose logs</error>`)}catch(l){this.logger.error(`Failed to log failure for MCP Server '${e}': '${l}'`)}}};var gq=class{constructor(e,I,l){this.logger=e;let n;if(typeof I=="string"){if(n=JSON.parse(I),typeof n!="object")throw new Error("Invalid MCP configuration: must be an object");if(n===null||!("mcpServers"in n)||typeof n.mcpServers!="object")throw new Error("Invalid MCP configuration: missing or invalid mcpServers property");this.config=n}else this.config=I;this.disabledServers=new Set(l||[]),this.registry=new yq(this.logger),this.processor=new Fq(this.logger,this.registry,{mcp3pEnabled:!0,remoteEnabled:!0})}registry;processor;config;startServersPromise=null;allTools=null;disabledServers;async startServers(){return this.startServersPromise||(this.startServersPromise=this.processServersWithExtensions()),this.startServersPromise}async injectDefaultServers(e){}async processServersWithExtensions(){await this.injectDefaultServers(this.config);let e;if(this.disabledServers.size>0){let I={};for(let[l,n]of Object.entries(this.config.mcpServers))this.disabledServers.has(l)?this.logger.log(`Skipping disabled MCP server: ${l}`):I[l]=n;e={...this.config,mcpServers:I}}else e=this.config;return this.processor.processServers(e)}async stopServers(){for(let[e,I]of Object.entries(this.registry.transports))try{await I.close()}catch(l){this.logger.error(`Error closing transport for ${e}: ${l}`)}this.startServersPromise=null,this.allTools=null}async getTools(e,I,l){if(!this.allTools){await this.startServers();let n=new g9(e,I,l),c=[];for(let a of Object.keys(this.registry.clients)){let s=await n.loadTools({mcpClient:this.registry.clients[a],clientName:a,tools:this.config.mcpServers[a]?.tools||["*"],filterMapping:this.config.mcpServers[a]?.filterMapping||"hidden_characters"});c.push(...s)}this.allTools=c}return this.allTools}getConfig(){return this.config}async startServer(e,I){await this.startServers(),this.config.mcpServers[e]=I,await this.processor.processServer(e,I),this.allTools=null}async stopServer(e){let I=this.registry.transports[e];if(I)try{await I.close(),delete this.registry.transports[e]}catch(l){this.logger.error(`Error closing transport for ${e}: ${l}`)}this.registry.clients[e]&&delete this.registry.clients[e],this.allTools=null}async restartServer(e,I){this.isServerRunning(e)&&await this.stopServer(e),delete this.config.mcpServers[e],await this.startServer(e,I)}isServerRunning(e){return e in this.registry.transports&&e in this.registry.clients}isServerDisabled(e){return this.disabledServers.has(e)}async disableServer(e){if(this.disabledServers.has(e)){this.logger.log(`Server ${e} is already disabled`);return}this.disabledServers.add(e),this.logger.log(`Disabled server ${e} for this session`),this.isServerRunning(e)&&await this.stopServer(e),this.allTools=null}async enableServer(e){if(!this.disabledServers.has(e)){this.logger.log(`Server ${e} is not disabled`);return}this.disabledServers.delete(e),this.logger.log(`Enabled server ${e} for this session`);let I=this.getServerConfig(e);I?await this.startServer(e,I):await this.startBuiltInServer(e),this.allTools=null}async startBuiltInServer(e){}getServerConfig(e){return this.config.mcpServers[e]}};G();var QKe=rn(gKe(),1);async function GKI(t={}){let e=await NZe();return ZZe((0,QKe.default)({},e,t))}async function AKe(t={}){if(zx())throw new Error("Settings have already been initialized");return GKI(t)}G();async function YV(t,e,I){if(!t||t.length===0)return;let l=!1,n={};for(let c of t)try{let a=await c(e);a&&(l=!0,n={...n,...a})}catch(a){I.error(`Hook execution failed: ${a}`)}return l?n:void 0}G();var l1=class{sessionId;startTime;events=[];_chatMessages=[];_selectedModel;logger;eventCallbacks=[];constructor({sessionId:e,startTime:I,logger:l}={}){this.sessionId=e||kb(),this.startTime=I||new Date,this.logger=l||new ai}static fromEvents({events:e,logger:I}){if(e.length===0)throw new Error("Cannot create session from empty events array");let l=e[0];if(l.type!=="session.start")throw new Error("First event must be session.start");let n=new this({sessionId:l.data.sessionId,startTime:new Date(l.data.startTime),logger:I||new ai});n._selectedModel=l.data.selectedModel,n.events.push(l);for(let c=1;c<e.length;c++){let a=e[c];n.events.push(a),n.processEventForState(a)}return n}addEvent(e){let I=e.id||kb(),l=e.timestamp||new Date().toISOString(),n=e.parentId!==void 0?e.parentId:this.getLastEventId(),c={...e,id:I,timestamp:l,parentId:n};return this.events.push(c),this.processEventForState(c),this.notifyEventCallbacks(c),c}getEvents(){return this.events}onEvent(e){return this.eventCallbacks.push(e),()=>{let I=this.eventCallbacks.indexOf(e);I>-1&&this.eventCallbacks.splice(I,1)}}get chatMessages(){return this._chatMessages}get selectedModel(){return this._selectedModel}setSelectedModel(e){let I=this._selectedModel;this._selectedModel=e,this.addEvent({type:"session.model_change",data:{previousModel:I,newModel:e}})}getChatContextMessages(){return this._chatMessages.filter(e=>e.role!=="system")}getSystemContextMessages(){return this._chatMessages.filter(e=>e.role==="system")}getLastEventId(){return this.events.length===0?null:this.events[this.events.length-1].id}processEventForState(e){switch(e.type){case"session.start":e.data.selectedModel&&(this._selectedModel=e.data.selectedModel);break;case"session.model_change":this._selectedModel=e.data.newModel;break;case"user.message":this._chatMessages.push({role:"user",content:e.data.content});break;case"assistant.message":{let I={role:"assistant",content:e.data.content||null};e.data.toolRequests&&e.data.toolRequests.length>0&&(I.tool_calls=e.data.toolRequests.map(l=>({id:l.toolCallId,type:"function",function:{name:l.name,arguments:typeof l.arguments=="string"?l.arguments:JSON.stringify(l.arguments)}}))),this._chatMessages.push(I);break}case"tool.execution_complete":{this._chatMessages.push({role:"tool",tool_call_id:e.data.toolCallId,content:e.data.success?e.data.result?.content||"":e.data.error?.message||"Tool execution failed"});break}case"system.message":this._chatMessages.push({role:e.data.role,content:e.data.content,...e.data.name&&{name:e.data.name}});break;case"session.resume":case"session.error":case"session.info":case"session.import_legacy":case"assistant.turn_start":case"assistant.turn_end":case"assistant.usage":case"abort":case"tool.execution_start":case"tool.execution_partial_result":case"hook.start":case"hook.end":break;default:{let I=e;this.logger.error(`Unknown event type: ${I.type}`);break}}}notifyEventCallbacks(e){for(let I of this.eventCallbacks)try{I(e)}catch(l){this.logger.error(`Error in event callback: ${l instanceof Error?l.message:String(l)}`)}}};var Jq=class{static name="Copilot";static description="Base Copilot Agent";options;logger;workingDir;session;constructor(e){this.options=e,this.logger=e.logger||new ai,this.workingDir=e.workingDirectory||process.cwd(),this.session=e.session||new l1,gbe(this.workingDir).then(I=>{if(I.found)return KUe(I.gitRoot,!0,this.workingDir)}).catch(I=>{this.logger.debug(`Failed to initialize custom instructions cache: ${I}`)})}async*query(e){let I=new Map,l;try{if(this.options.mcpServers&&Object.keys(this.options.mcpServers).length>0)try{l=new gq(this.logger,{mcpServers:this.options.mcpServers},this.options.disabledTools),await l.startServers()}catch(Ze){this.logger.error(`Failed to initialize MCP host: ${Ze}`)}let n={timestamp:Date.now(),cwd:this.workingDir,prompt:e},a=(await YV(this.options.hooks?.userPromptSubmitted,n,this.logger))?.modifiedPrompt??e;this.session.addEvent({type:"user.message",data:{content:a}});let r=new WF().setProblemStatement(a).setAgentModel(this.buildAgentModelString()).setGithubRepoName("copilot-sdk-session").setGithubRepoCommit("copilot-sdk-commit").setGithubRepoReadWrite(!1).setCopilotIntegrationId(this.options.integrationId||"copilot-developer-cli").setCopilotHmacKey(this.options.hmacKey).setCopilotToken(this.options.copilotToken).build();uZe();let o=await AKe(r),d=o.service?.agent?.model,i=lme(d),h=i.agent,p=i.model?{model:i.model}:void 0,Z=soe(o,this.logger,h,p),u={location:this.workingDir,timeout:3e4,requireReasoning:!0,toolPartialResultCallback:void 0,permissions:this.options.requestPermission?{requestRequired:!0,request:this.options.requestPermission}:{requestRequired:!1},shellConfig:process.platform==="win32"?Ci.powerShell:Ci.bash},N=await JOe(u,this.logger),Y=[];if(l)try{Y=await l.getTools(o,this.logger,u.permissions)}catch(Ze){this.logger.error(`Failed to get MCP tools: ${Ze}`)}let y=[...N,...Y],Q=this.applyToolFiltering(y,this.options.allowedTools,this.options.disabledTools),A=await gbe(this.workingDir),E={...(kOe()["sweagent-capi"]?.["claude-sonnet-4"]??LOe()).supports,reasoning:!0},C=await pOe(A.found?A.gitRoot:"",Ife(),this.workingDir,{},E,u,Q,void 0),ce=this.session.chatMessages.slice(0,-1),ye={role:"user",content:WOe(a,E)},Xe=[...ce,ye],He={timestamp:Date.now(),cwd:this.workingDir,source:"new",initialPrompt:e};await YV(this.options.hooks?.sessionStart,He,this.logger);let ie=Z.getCompletionWithTools(C,Xe,Q,{failIfInitialInputsTooLong:!1,processors:{preRequest:[new YE(ye,this.logger)]},executeToolsInParallel:!1,abortSignal:this.options.abortController?.signal});for await(let Ze of ie){if(this.options.abortController?.signal.aborted){yield{type:"error",error:new Error("Operation was cancelled")};return}let II=await this.translateEvent(Ze,I);for(let Je of II)Je.type==="message"&&Je.role==="assistant"&&this.session.addEvent({type:"assistant.message",data:{messageId:`msg-${Date.now()}`,content:Je.content}}),yield Je}yield{type:"complete"}}catch(n){let c={timestamp:Date.now(),cwd:this.workingDir,reason:"error",error:n instanceof Error?n:new Error(String(n))};await YV(this.options.hooks?.sessionEnd,c,this.logger),yield{type:"error",error:n instanceof Error?n:new Error(String(n))}}finally{let n={timestamp:Date.now(),cwd:this.workingDir,reason:"complete"};if(await YV(this.options.hooks?.sessionEnd,n,this.logger),l)try{await l.stopServers(),this.logger.log("MCP host stopped successfully")}catch(c){this.logger.error(`Error stopping MCP host: ${c}`)}}}buildAgentModelString(){switch(this.options.modelProvider.type){case"openai":return`openai:${this.options.modelProvider.model}`;case"anthropic":return`anthropic:${this.options.modelProvider.model}`;case"copilot":return`capi:${this.options.modelProvider.model}`;default:throw new Error(`Unsupported provider: ${this.options.modelProvider.type}`)}}applyToolFiltering(e,I,l){let n=e;return I&&I.length>0&&(n=n.filter(c=>I.includes(c.name))),l&&l.length>0&&(n=n.filter(c=>!l.includes(c.name))),n}async translateEvent(e,I){switch(e.kind){case"message":{if(a6(e)&&e.message.content)return[{type:"message",content:typeof e.message.content=="string"?e.message.content:"",role:"assistant"}];if(wOe(e)){let l=[];for(let n of e.message.tool_calls){let c=jA(n.function.arguments);I.set(n.id,n.function.name);let a={timestamp:Date.now(),cwd:this.workingDir,toolName:n.function.name,toolArgs:c},r=(await YV(this.options.hooks?.preToolUse,a,this.logger))?.modifiedArgs??c;l.push({type:"tool_use",toolName:n.function.name,args:r,toolCallId:n.id})}return l}return[]}case"response":return[];case"model_call_failure":{let l=new Error(e.modelCall?.error||"Model call failed"),n={timestamp:Date.now(),cwd:this.workingDir,error:l,errorContext:"model_call",recoverable:!0};return await YV(this.options.hooks?.errorOccurred,n,this.logger),[{type:"error",error:l}]}case"tool_execution":{let l=I.get(e.toolCallId)||"unknown",n={timestamp:Date.now(),cwd:this.workingDir,toolName:l,toolArgs:{},toolResult:e.toolResult},a=(await YV(this.options.hooks?.postToolUse,n,this.logger))?.modifiedResult??e.toolResult;return[{type:"tool_result",toolName:l,result:a,toolCallId:e.toolCallId}]}default:return[]}}};G();G();var Tpe=class{loggers;constructor(e){this.loggers=e}isDebug(){return this.loggers.some(e=>e.isDebug())}debug(e){this.loggers.forEach(I=>I.debug(e))}log(e){this.loggers.forEach(I=>I.log(e))}info(e){this.loggers.forEach(I=>I.info(e))}notice(e){this.loggers.forEach(I=>I.notice(e))}warning(e){this.loggers.forEach(I=>I.warning(e))}error(e){this.loggers.forEach(I=>I.error(e))}startGroup(e,I){this.loggers.forEach(l=>l.startGroup(e,I))}endGroup(e){this.loggers.forEach(I=>I.endGroup(e))}};G();import{appendFile as oKI,access as dKI,mkdir as iKI}from"fs/promises";import{constants as bKI}from"fs";import{dirname as mKI}from"path";var jpe=class extends Gp{constructor(I,l,n){super(l,n);this.filePath=I;this.writeQueue=hKI(mKI(this.filePath)).catch(()=>{})}writeQueue=Promise.resolve();log(I){this.write("LOG",I)}debug(I){super.shouldLog(8)&&this.write("DEBUG",this.filterSecrets(I).toString())}info(I){super.shouldLog(4)&&this.write("INFO",this.filterSecrets(I).toString())}notice(I){super.shouldLog(2)&&this.write("NOTICE",this.filterSecrets(I).toString())}warning(I){super.shouldLog(2)&&this.write("WARNING",this.filterSecrets(I).toString())}error(I){super.shouldLog(1)&&this.write("ERROR",this.filterSecrets(I).toString())}startGroup(I,l){super.shouldLog(l||4)&&this.write("START-GROUP",I)}endGroup(I){super.shouldLog(I||4)&&this.write("END-GROUP","")}write(I,l){let c=`${new Date().toISOString()} [${I}] ${l}
1353
+ ${c}`;await n.logMCPSetup(e,s),this.logger.log(`Updated session log for ${e} with ${I.length} tools`)}catch(c){this.logger.error(`Failed to update session log for ${e}: ${c}`)}}};G();var Jpe={mcpServers:{}},Fq=class{constructor(e,I,l){this.logger=e;this.registry=I;this.remoteEnabled=l?.remoteEnabled??!1,this.mcp3pEnabled=l?.mcp3pEnabled??!1,this.blackbirdMetisIndexEnabled=l?.blackbirdMetisIndexEnabled??!1,this.sessionClient=l?.sessionClient,this.mcpEnvConfig=void 0}remoteEnabled;mcp3pEnabled;blackbirdMetisIndexEnabled;mcpEnvConfig;sessionClient;ReadMcpConfigFromEnv(e){this.mcpEnvConfig=process.env.GITHUB_COPILOT_MCP_JSON,this.mcp3pEnabled=process.env.GITHUB_COPILOT_3P_MCP_ENABLED==="true",this.remoteEnabled=process.env.GITHUB_COPILOT_REMOTE_MCP_ENABLED==="true",this.blackbirdMetisIndexEnabled=process.env.BLACKBIRD_METIS_INDEX_ENABLED==="true";let I=this.validateEnvConfig();return process.env.GITHUB_COPILOT_CLI_MODE==="true"?this.logger.log("CLI mode detected - skipping default MCP servers"):(this.logger.log("Adding default MCP servers to configuration"),this.configureBlackbirdMcp(I,e),this.configureGitHubMcp(I,e),this.configurePlaywrightMcp(I)),I}validateEnvConfig(){if(!this.mcp3pEnabled)return this.logger.log("User-provided MCPs are disabled"),Jpe;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"),Jpe;try{let e=JSON.parse(this.mcpEnvConfig);if(!e.mcpServers)throw new Error("User-provided config had incorrect format. Missing 'mcpServers' property.");for(let I in e.mcpServers)e.mcpServers[I].isDefaultServer=!1;return e}catch(e){return this.logger.error(`Warning: User-provided MCP servers were defined but invalid: ${e}`),Jpe}}configureGitHubMcp(e,I){this.remoteEnabled?this.configureRemoteGitHubMcp(e,I):this.configureLocalGitHubMcp(e)}configureRemoteGitHubMcp(e,I){this.logger.log("Using default remote GitHub MCP server configuration");let l="repos,issues,users,pull_requests,code_security,secret_protection,actions,web_search";process.env.COPILOT_MCP_COPILOT_SPACES_ENABLED==="true"&&(this.logger.log("Enabling Copilot Spaces in GitHub MCP server configuration"),l=l+",copilot_spaces");let n={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":l,"X-MCP-Host":"github-coding-agent","X-Initiator":"agent"};I&&I.api?.copilot?.integrationId&&(n["Copilot-Integration-Id"]=I.api.copilot.integrationId),process.env.GITHUB_COPILOT_INTERACTION_ID&&(n["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let c={type:"http",url:this.getCapiMcpUrl(),headers:n,tools:["*"],isDefaultServer:!0,filterMapping:{get_issue:"markdown",get_issue_comments:"markdown",get_pull_request:"markdown",get_pull_request_comments:"markdown",get_pull_request_reviews:"markdown"}};e.mcpServers[_E]=c}configureLocalGitHubMcp(e){if(e.mcpServers[_E]){this.logger.log("Using user-provided GitHub MCP server configuration");let I=e.mcpServers[_E]??{};$E(I)&&!I.command&&(e.mcpServers[_E]={...I,command:"./copilot-developer-action-main/github-mcp-server/github-mcp-server",isDefaultServer:!0},this.logger.log("Added default command to user-provided GitHub MCP server configuration"))}else{this.logger.log("Using default local GitHub MCP server configuration");let I={command:"./copilot-developer-action-main/github-mcp-server/github-mcp-server",args:["stdio","--read-only"],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",GITHUB_HOST:"GITHUB_SERVER_URL"},tools:["*"],isDefaultServer:!0};e.mcpServers[_E]=I}}configurePlaywrightMcp(e){if(!e.mcpServers[vpe]){if((process.env.COPILOT_FEATURE_FLAGS??"").split(",").map(l=>l.trim()).includes("copilot_swe_agent_playwright_use_firewall")){this.logger.log("Playwright MCP server is configured to use the firewall, skipping launch.");return}this.logger.log("Enabling Playwright MCP server");let I={command:"npx",args:[...Tbe,"--allowed-origins","localhost;localhost:*;127.0.0.1;127.0.0.1:*"],tools:["*"],isDefaultServer:!0};e.mcpServers[vpe]=I}}configureBlackbirdMcp(e,I){this.remoteEnabled?this.configureRemoteBlackbirdMcp(e):this.blackbirdMetisIndexEnabled?this.configureLocalMetisBlackbirdMCP(e,I):this.configureLocalBlackbirdMcp(e)}configureLocalMetisBlackbirdMCP(e,I){this.logger.log("Using local Metis Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${I.blackbird?.mode}`);let l=process.env.AGENT_DIR||"/agent";this.logger.log(`Using agent directory: ${l}`);let n=[];I.blackbird?.mode==="tool"&&(n=["*"]),this.logger.log(`Using blackbird Metis server: ${I.blackbird?.mode}`);let c={command:`${l}/blackbird/mcp`,args:["serve","--index",`${l}/blackbird/metis`],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",COPILOT_API_HMAC_KEY:"CAPI_HMAC_KEY",MODEL_BASED_RETRIEVAL_TOKEN:"BLACKBIRD_AUTH_MODEL_BASED_RETRIEVAL_TOKEN",METIS_API_KEY:"BLACKBIRD_AUTH_METIS_API_KEY"},tools:n,isDefaultServer:!0};e.mcpServers[rF]=c}configureLocalBlackbirdMcp(e){this.logger.log("Using local Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let I=[];process.env.BLACKBIRD_MODE==="tool"&&(I=["*"]);let l={command:"./copilot-developer-action-main/blackbird-mcp-server/blackbird-mcp-server",args:["stdio"],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",CAPI_HOST:"COPILOT_API_URL"},tools:I,isDefaultServer:!0};e.mcpServers[rF]=l}configureRemoteBlackbirdMcp(e){this.logger.log("Using remote Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let I=[];process.env.BLACKBIRD_MODE==="tool"&&(I=["*"]);let l={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":"search_agent","X-MCP-Host":"github-coding-agent"};process.env.GITHUB_COPILOT_INTERACTION_ID&&(l["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let n={type:"http",url:this.getCapiMcpUrl(),headers:l,tools:I,isDefaultServer:!0};e.mcpServers[rF]=n}getCapiMcpUrl(){return process.env.COPILOT_API_URL?new URL("/mcp/readonly",process.env.COPILOT_API_URL).toString():"https://api.githubcopilot.com/mcp/readonly"}isValidServerType(e){return $E(e)||Vq(e)||Rq(e)||gx(e)}isValidLocalServerConfig(e){return e.command!==void 0&&e.command.trim()!==""&&Array.isArray(e.args)}isValidRemoteServerConfig(e){return e.url!==void 0&&e.url.trim()!==""}isValidInMemoryServerConfig(e){return e.serverInstance!==void 0&&typeof e.serverInstance=="object"}validateServerConfig(e,I){return this.remoteEnabled&&!this.isValidServerType(I)?(this.logger.error(`Unsupported server type "${I.type}" for server "${e}". Only "Local", "STDIO", "HTTP", "SSE", or "Memory" are supported.`),!1):!this.remoteEnabled&&!$E(I)&&!gx(I)?(this.logger.error(`Unsupported server type "${I.type}" for server "${e}". Only "Local", "STDIO", or "Memory" are supported.`),!1):I.tools?$E(I)&&!this.isValidLocalServerConfig(I)?(this.logger.error(`Invalid local server configuration for "${e}". Please ensure 'command' and 'args' are provided.`),!1):(Vq(I)||Rq(I))&&!this.isValidRemoteServerConfig(I)?(this.logger.error(`Invalid remote server configuration for "${e}". Please ensure 'url' is provided.`),!1):gx(I)&&!this.isValidInMemoryServerConfig(I)?(this.logger.error(`Invalid in-memory server configuration for "${e}". Please ensure 'serverInstance' is provided and is an instance of MCPServer.`),!1):!0:(this.logger.error(`No tools specified for server "${e}". Please provide a list of tools or "*" to include all tools.`),!1)}async processHttpServer(e,I){try{let l=this.resolveHeaders(I.headers,process.env),n={...I,headers:l};await this.registry.startHttpMcpClient(e,n),this.logger.log(`Started MCP client for remote server ${e}`)}catch(l){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${l}`),l}}async processSseServer(e,I){try{let l=this.resolveRemoteServerConfig(I);await this.registry.startSseMcpClient(e,l),this.logger.log(`Started MCP client for remote server ${e}`)}catch(l){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${l}`),l}}resolveRemoteServerConfig(e){return e.url=this.resolveString(e.url,process.env),e.headers=this.resolveHeaders(e.headers,process.env),{...e,url:e.url,headers:e.headers}}async processInMemoryServer(e,I){try{await this.registry.startInMemoryMcpClient(e,I.serverInstance),this.logger.log(`Started in-memory MCP client for ${e}`)}catch(l){throw this.logger.error(`Failed to start in-memory MCP client for ${e}: ${l}`),l}}async processLocalServer(e,I){let l={...I};if(I.command==="python")try{l=await this.convertPythonToPipx(l)}catch(a){this.logger.error(`Failed to handle Python module for ${e}: ${a}`)}let n=this.buildEnvironment(l),c=this.resolveLocalServerConfig(l,n);this.logger.log(`Starting MCP client for ${e} with command: ${c.command} and args: ${c.args}`);try{await this.registry.startLocalMcpClient(e,n,c.command,c.args),this.logger.log(`Started MCP client for ${e}`)}catch(a){throw this.logger.error(`Failed to start MCP client for ${e}: ${a}`),a}}convertPythonToPipx(e){if(!e||!e.args||e.args.length===0)return e;let I=e.args,l=I.indexOf("-m");if(l===-1||l===I.length-1)throw new Error("Python command with -m flag must specify a module");let n=I[l+1];this.logger.log(`Converting Python module: ${n} to pipx command`);let c=["run",n];for(let a=l+2;a<I.length;a++)c.push(I[a]);for(let a=0;a<l;a++)c.push(I[a]);return{...e,command:"pipx",args:c}}buildEnvironment(e){let I={};if(e.env)for(let[l,n]of Object.entries(e.env)){let c=n.trim(),a=c;if(c.includes("$")&&(a=this.resolveString(c,process.env)),a!==c){I[l]=a;continue}process.env[c]!==void 0&&(I[l]=process.env[c])}return I}resolveLocalServerConfig(e,I){let l=this.resolveString(e.command,I),n=this.resolveArray(e.args,I);return{...e,command:l,args:n}}resolveString(e,I){return I?e.replace(/\$(?:\{([A-Z0-9_]+)(?::-(.*?))?\}|([A-Z0-9_]+))/g,(l,n,c,a)=>{let r=I[n||a];return r!==void 0?r:c!==void 0?c:l}):e}resolveArray(e,I){return e?I?e.map(l=>this.resolveString(l,I)):e:[]}resolveHeaders(e,I){if(!e)return{};if(!I)return e;let l={};for(let[n,c]of Object.entries(e)){let a=this.resolveArray([c],I);l[n]=a[0]}return l}async processServers(e){if(!e)throw new Error("No servers to process");let I=Object.entries(e.mcpServers).map(([l,n])=>this.processServer(l,n));await Promise.all(I)}async processServer(e,I){if(!this.validateServerConfig(e,I)){this.logger.error(`Skipping server "${e}" due to invalid configuration.`);return}try{$E(I)?await this.processLocalServer(e,I):Vq(I)&&this.remoteEnabled?await this.processHttpServer(e,I):Rq(I)&&this.remoteEnabled?await this.processSseServer(e,I):gx(I)&&await this.processInMemoryServer(e,I)}catch(l){e!==rF&&await this.logServerFailure(e,l)}}async logServerFailure(e,I){if(this.sessionClient)try{await this.sessionClient.logMCPSetup(e,`<error>MCP server failed to start: ${I.message} - for the full output, see the verbose logs</error>`)}catch(l){this.logger.error(`Failed to log failure for MCP Server '${e}': '${l}'`)}}};var gq=class{constructor(e,I,l){this.logger=e;let n;if(typeof I=="string"){if(n=JSON.parse(I),typeof n!="object")throw new Error("Invalid MCP configuration: must be an object");if(n===null||!("mcpServers"in n)||typeof n.mcpServers!="object")throw new Error("Invalid MCP configuration: missing or invalid mcpServers property");this.config=n}else this.config=I;this.disabledServers=new Set(l||[]),this.registry=new yq(this.logger),this.processor=new Fq(this.logger,this.registry,{mcp3pEnabled:!0,remoteEnabled:!0})}registry;processor;config;startServersPromise=null;allTools=null;disabledServers;async startServers(){return this.startServersPromise||(this.startServersPromise=this.processServersWithExtensions()),this.startServersPromise}async injectDefaultServers(e){}async processServersWithExtensions(){await this.injectDefaultServers(this.config);let e;if(this.disabledServers.size>0){let I={};for(let[l,n]of Object.entries(this.config.mcpServers))this.disabledServers.has(l)?this.logger.log(`Skipping disabled MCP server: ${l}`):I[l]=n;e={...this.config,mcpServers:I}}else e=this.config;return this.processor.processServers(e)}async stopServers(){for(let[e,I]of Object.entries(this.registry.transports))try{await I.close()}catch(l){this.logger.error(`Error closing transport for ${e}: ${l}`)}this.startServersPromise=null,this.allTools=null}async getTools(e,I,l){if(!this.allTools){await this.startServers();let n=new g9(e,I,l),c=[];for(let a of Object.keys(this.registry.clients)){let s=await n.loadTools({mcpClient:this.registry.clients[a],clientName:a,tools:this.config.mcpServers[a]?.tools||["*"],filterMapping:this.config.mcpServers[a]?.filterMapping||"hidden_characters"});c.push(...s)}this.allTools=c}return this.allTools}getConfig(){return this.config}async startServer(e,I){await this.startServers(),this.config.mcpServers[e]=I,await this.processor.processServer(e,I),this.allTools=null}async stopServer(e){let I=this.registry.transports[e];if(I)try{await I.close(),delete this.registry.transports[e]}catch(l){this.logger.error(`Error closing transport for ${e}: ${l}`)}this.registry.clients[e]&&delete this.registry.clients[e],this.allTools=null}async restartServer(e,I){this.isServerRunning(e)&&await this.stopServer(e),delete this.config.mcpServers[e],await this.startServer(e,I)}isServerRunning(e){return e in this.registry.transports&&e in this.registry.clients}isServerDisabled(e){return this.disabledServers.has(e)}async disableServer(e){if(this.disabledServers.has(e)){this.logger.log(`Server ${e} is already disabled`);return}this.disabledServers.add(e),this.logger.log(`Disabled server ${e} for this session`),this.isServerRunning(e)&&await this.stopServer(e),this.allTools=null}async enableServer(e){if(!this.disabledServers.has(e)){this.logger.log(`Server ${e} is not disabled`);return}this.disabledServers.delete(e),this.logger.log(`Enabled server ${e} for this session`);let I=this.getServerConfig(e);I?await this.startServer(e,I):await this.startBuiltInServer(e),this.allTools=null}async startBuiltInServer(e){}getServerConfig(e){return this.config.mcpServers[e]}};G();var QKe=rn(gKe(),1);async function GKI(t={}){let e=await NZe();return ZZe((0,QKe.default)({},e,t))}async function AKe(t={}){if(zx())throw new Error("Settings have already been initialized");return GKI(t)}G();async function YV(t,e,I){if(!t||t.length===0)return;let l=!1,n={};for(let c of t)try{let a=await c(e);a&&(l=!0,n={...n,...a})}catch(a){I.error(`Hook execution failed: ${a}`)}return l?n:void 0}G();var l1=class{sessionId;startTime;events=[];_chatMessages=[];_selectedModel;logger;eventCallbacks=[];constructor({sessionId:e,startTime:I,logger:l}={}){this.sessionId=e||kb(),this.startTime=I||new Date,this.logger=l||new ai}static fromEvents({events:e,logger:I}){if(e.length===0)throw new Error("Cannot create session from empty events array");let l=e[0];if(l.type!=="session.start")throw new Error("First event must be session.start");let n=new this({sessionId:l.data.sessionId,startTime:new Date(l.data.startTime),logger:I||new ai});n._selectedModel=l.data.selectedModel,n.events.push(l);for(let c=1;c<e.length;c++){let a=e[c];n.events.push(a),n.processEventForState(a)}return n}addEvent(e){let I=e.id||kb(),l=e.timestamp||new Date().toISOString(),n=e.parentId!==void 0?e.parentId:this.getLastEventId(),c={...e,id:I,timestamp:l,parentId:n};return this.events.push(c),this.processEventForState(c),this.notifyEventCallbacks(c),c}getEvents(){return this.events}onEvent(e){return this.eventCallbacks.push(e),()=>{let I=this.eventCallbacks.indexOf(e);I>-1&&this.eventCallbacks.splice(I,1)}}get chatMessages(){return this._chatMessages}get selectedModel(){return this._selectedModel}setSelectedModel(e){let I=this._selectedModel;this._selectedModel=e,this.addEvent({type:"session.model_change",data:{previousModel:I,newModel:e}})}getChatContextMessages(){return this._chatMessages.filter(e=>e.role!=="system")}getSystemContextMessages(){return this._chatMessages.filter(e=>e.role==="system")}getLastEventId(){return this.events.length===0?null:this.events[this.events.length-1].id}processEventForState(e){switch(e.type){case"session.start":e.data.selectedModel&&(this._selectedModel=e.data.selectedModel);break;case"session.model_change":this._selectedModel=e.data.newModel;break;case"user.message":this._chatMessages.push({role:"user",content:e.data.content});break;case"assistant.message":{let I={role:"assistant",content:e.data.content||null};e.data.toolRequests&&e.data.toolRequests.length>0&&(I.tool_calls=e.data.toolRequests.map(l=>({id:l.toolCallId,type:"function",function:{name:l.name,arguments:typeof l.arguments=="string"?l.arguments:JSON.stringify(l.arguments)}}))),this._chatMessages.push(I);break}case"tool.execution_complete":{this._chatMessages.push({role:"tool",tool_call_id:e.data.toolCallId,content:e.data.success?e.data.result?.content||"":e.data.error?.message||"Tool execution failed"});break}case"system.message":this._chatMessages.push({role:e.data.role,content:e.data.content,...e.data.name&&{name:e.data.name}});break;case"session.resume":case"session.error":case"session.info":case"session.import_legacy":case"assistant.turn_start":case"assistant.turn_end":case"assistant.usage":case"abort":case"tool.execution_start":case"tool.execution_partial_result":case"hook.start":case"hook.end":break;default:{let I=e;this.logger.error(`Unknown event type: ${I.type}`);break}}}notifyEventCallbacks(e){for(let I of this.eventCallbacks)try{I(e)}catch(l){this.logger.error(`Error in event callback: ${l instanceof Error?l.message:String(l)}`)}}};var Jq=class{static name="Copilot";static description="Base Copilot Agent";options;logger;workingDir;session;constructor(e){this.options=e,this.logger=e.logger||new ai,this.workingDir=e.workingDirectory||process.cwd(),this.session=e.session||new l1,gbe(this.workingDir).then(I=>{if(I.found)return KUe(I.gitRoot,!0,this.workingDir)}).catch(I=>{this.logger.debug(`Failed to initialize custom instructions cache: ${I}`)})}async*query(e){let I=new Map,l;try{if(this.options.mcpServers&&Object.keys(this.options.mcpServers).length>0)try{l=new gq(this.logger,{mcpServers:this.options.mcpServers},this.options.disabledTools),await l.startServers()}catch(Ze){this.logger.error(`Failed to initialize MCP host: ${Ze}`)}let n={timestamp:Date.now(),cwd:this.workingDir,prompt:e},a=(await YV(this.options.hooks?.userPromptSubmitted,n,this.logger))?.modifiedPrompt??e;this.session.addEvent({type:"user.message",data:{content:a}});let r=new WF().setProblemStatement(a).setAgentModel(this.buildAgentModelString()).setGithubRepoName("copilot-sdk-session").setGithubRepoCommit("copilot-sdk-commit").setGithubRepoReadWrite(!1).setCopilotIntegrationId(this.options.integrationId||"copilot-developer-cli").setCopilotHmacKey(this.options.hmacKey).setCopilotToken(this.options.copilotToken).build();uZe();let o=await AKe(r),d=o.service?.agent?.model,i=lme(d),h=i.agent,p=i.model?{model:i.model}:void 0,Z=soe(o,this.logger,h,p),u={location:this.workingDir,timeout:3e4,requireReasoning:!0,toolPartialResultCallback:void 0,permissions:this.options.requestPermission?{requestRequired:!0,request:this.options.requestPermission}:{requestRequired:!1},shellConfig:process.platform==="win32"?Ci.powerShell:Ci.bash},N=await JOe(u,this.logger),Y=[];if(l)try{Y=await l.getTools(o,this.logger,u.permissions)}catch(Ze){this.logger.error(`Failed to get MCP tools: ${Ze}`)}let y=[...N,...Y],Q=this.applyToolFiltering(y,this.options.allowedTools,this.options.disabledTools),A=await gbe(this.workingDir),E={...(kOe()["sweagent-capi"]?.["claude-sonnet-4"]??LOe()).supports,reasoning:!0},C=await pOe(A.found?A.gitRoot:"",Ife(),this.workingDir,{},E,u,Q,void 0),ce=this.session.chatMessages.slice(0,-1),ye={role:"user",content:WOe(a,E)},Xe=[...ce,ye],He={timestamp:Date.now(),cwd:this.workingDir,source:"new",initialPrompt:e};await YV(this.options.hooks?.sessionStart,He,this.logger);let ie=Z.getCompletionWithTools(C,Xe,Q,{failIfInitialInputsTooLong:!1,processors:{preRequest:[new YE(ye,this.logger)]},executeToolsInParallel:!1,abortSignal:this.options.abortController?.signal});for await(let Ze of ie){if(this.options.abortController?.signal.aborted){yield{type:"error",error:new Error("Operation was cancelled")};return}let II=await this.translateEvent(Ze,I);for(let Je of II)Je.type==="message"&&Je.role==="assistant"&&this.session.addEvent({type:"assistant.message",data:{messageId:`msg-${Date.now()}`,content:Je.content}}),yield Je}yield{type:"complete"}}catch(n){let c={timestamp:Date.now(),cwd:this.workingDir,reason:"error",error:n instanceof Error?n:new Error(String(n))};await YV(this.options.hooks?.sessionEnd,c,this.logger),yield{type:"error",error:n instanceof Error?n:new Error(String(n))}}finally{let n={timestamp:Date.now(),cwd:this.workingDir,reason:"complete"};if(await YV(this.options.hooks?.sessionEnd,n,this.logger),l)try{await l.stopServers(),this.logger.log("MCP host stopped successfully")}catch(c){this.logger.error(`Error stopping MCP host: ${c}`)}}}buildAgentModelString(){switch(this.options.modelProvider.type){case"openai":return`openai:${this.options.modelProvider.model}`;case"anthropic":return`anthropic:${this.options.modelProvider.model}`;case"copilot":return`capi:${this.options.modelProvider.model}`;default:throw new Error(`Unsupported provider: ${this.options.modelProvider.type}`)}}applyToolFiltering(e,I,l){let n=e;return I&&I.length>0&&(n=n.filter(c=>I.includes(c.name))),l&&l.length>0&&(n=n.filter(c=>!l.includes(c.name))),n}async translateEvent(e,I){switch(e.kind){case"message":{if(a6(e)&&e.message.content)return[{type:"message",content:typeof e.message.content=="string"?e.message.content:"",role:"assistant"}];if(wOe(e)){let l=[];for(let n of e.message.tool_calls){let c=jA(n.function.arguments);I.set(n.id,n.function.name);let a={timestamp:Date.now(),cwd:this.workingDir,toolName:n.function.name,toolArgs:c},r=(await YV(this.options.hooks?.preToolUse,a,this.logger))?.modifiedArgs??c;l.push({type:"tool_use",toolName:n.function.name,args:r,toolCallId:n.id})}return l}return[]}case"response":return[];case"model_call_failure":{let l=new Error(e.modelCall?.error||"Model call failed"),n={timestamp:Date.now(),cwd:this.workingDir,error:l,errorContext:"model_call",recoverable:!0};return await YV(this.options.hooks?.errorOccurred,n,this.logger),[{type:"error",error:l}]}case"tool_execution":{let l=I.get(e.toolCallId)||"unknown",n={timestamp:Date.now(),cwd:this.workingDir,toolName:l,toolArgs:{},toolResult:e.toolResult},a=(await YV(this.options.hooks?.postToolUse,n,this.logger))?.modifiedResult??e.toolResult;return[{type:"tool_result",toolName:l,result:a,toolCallId:e.toolCallId}]}default:return[]}}};G();G();var Tpe=class{loggers;constructor(e){this.loggers=e}isDebug(){return this.loggers.some(e=>e.isDebug())}debug(e){this.loggers.forEach(I=>I.debug(e))}log(e){this.loggers.forEach(I=>I.log(e))}info(e){this.loggers.forEach(I=>I.info(e))}notice(e){this.loggers.forEach(I=>I.notice(e))}warning(e){this.loggers.forEach(I=>I.warning(e))}error(e){this.loggers.forEach(I=>I.error(e))}startGroup(e,I){this.loggers.forEach(l=>l.startGroup(e,I))}endGroup(e){this.loggers.forEach(I=>I.endGroup(e))}};G();import{appendFile as oKI,access as dKI,mkdir as iKI}from"fs/promises";import{constants as bKI}from"fs";import{dirname as mKI}from"path";var jpe=class extends Gp{constructor(I,l,n){super(l,n);this.filePath=I;this.writeQueue=hKI(mKI(this.filePath)).catch(()=>{})}writeQueue=Promise.resolve();log(I){this.write("LOG",I)}debug(I){super.shouldLog(8)&&this.write("DEBUG",this.filterSecrets(I).toString())}info(I){super.shouldLog(4)&&this.write("INFO",this.filterSecrets(I).toString())}notice(I){super.shouldLog(2)&&this.write("NOTICE",this.filterSecrets(I).toString())}warning(I){super.shouldLog(2)&&this.write("WARNING",this.filterSecrets(I).toString())}error(I){super.shouldLog(1)&&this.write("ERROR",this.filterSecrets(I).toString())}startGroup(I,l){super.shouldLog(l||4)&&this.write("START-GROUP",I)}endGroup(I){super.shouldLog(I||4)&&this.write("END-GROUP","")}write(I,l){let c=`${new Date().toISOString()} [${I}] ${l}
1354
1354
  `;this.writeQueue=this.writeQueue.then(()=>this.performWrite(c)).catch(()=>{})}async performWrite(I){await oKI(this.filePath,I)}};async function hKI(t){try{await dKI(t,bKI.F_OK)}catch{await iKI(t,{recursive:!0})}}G();async function*D7l(t){let{prompt:e,...I}=t;yield*new Jq(I).query(e)}G();var wKe=class{sessions;logger;lastAccessedSessionId;constructor({logger:e}={}){this.sessions=new Map,this.logger=e||new ai}async createSession(){let e=new l1({logger:this.logger});return this.sessions.set(e.sessionId,e),this.lastAccessedSessionId=e.sessionId,e}async getSession(e){let I=this.sessions.get(e);return I&&(this.lastAccessedSessionId=e),I}async getLastSession(){if(this.lastAccessedSessionId){let l=this.sessions.get(this.lastAccessedSessionId);if(l)return l}let e=Array.from(this.sessions.values());if(e.length===0)return;e.sort((l,n)=>n.startTime.getTime()-l.startTime.getTime());let I=e[0];return this.lastAccessedSessionId=I.sessionId,I}async listSessions(){return Array.from(this.sessions.values()).map(e=>({sessionId:e.sessionId,startTime:e.startTime}))}async saveSession(e){}async deleteSession(e){this.sessions.delete(e.sessionId),this.lastAccessedSessionId===e.sessionId&&(this.lastAccessedSessionId=void 0)}};export{Jq as Agent,Gp as BaseLogger,Tpe as CompoundLogger,qV as ConsoleLogger,jpe as FileLogger,ai as NoopLogger,l1 as Session,wKe as SessionManager,YV as executeHooks,s1 as isDebugEnvironment,D7l as query};
1355
1355
  /*! Bundled license information:
1356
1356