@github/copilot 0.0.342-14 → 0.0.342-15

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
@@ -1923,7 +1923,7 @@ Pay attention to the following when using it:
1923
1923
  `}var cAn=mYe.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function dAn(){let t={};for(let e of cAn){let l=mYe.env[e];l!==void 0&&(l.startsWith("()")||(t[e]=l))}return t}var uYe=class{constructor(e){this._abortController=new AbortController,this._readBuffer=new dYe,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new iAn)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,l)=>{var n,r,I,a,s;this._process=(0,LSt.default)(this._serverParams.command,(n=this._serverParams.args)!==null&&n!==void 0?n:[],{env:{...dAn(),...this._serverParams.env},stdio:["pipe","pipe",(r=this._serverParams.stderr)!==null&&r!==void 0?r:"inherit"],shell:!1,signal:this._abortController.signal,windowsHide:mYe.platform==="win32"&&uAn(),cwd:this._serverParams.cwd}),this._process.on("error",o=>{var d,u;if(o.name==="AbortError"){(d=this.onclose)===null||d===void 0||d.call(this);return}l(o),(u=this.onerror)===null||u===void 0||u.call(this,o)}),this._process.on("spawn",()=>{e()}),this._process.on("close",o=>{var d;this._process=void 0,(d=this.onclose)===null||d===void 0||d.call(this)}),(I=this._process.stdin)===null||I===void 0||I.on("error",o=>{var d;(d=this.onerror)===null||d===void 0||d.call(this,o)}),(a=this._process.stdout)===null||a===void 0||a.on("data",o=>{this._readBuffer.append(o),this.processReadBuffer()}),(s=this._process.stdout)===null||s===void 0||s.on("error",o=>{var d;(d=this.onerror)===null||d===void 0||d.call(this,o)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){var e,l;return this._stderrStream?this._stderrStream:(l=(e=this._process)===null||e===void 0?void 0:e.stderr)!==null&&l!==void 0?l:null}get pid(){var e,l;return(l=(e=this._process)===null||e===void 0?void 0:e.pid)!==null&&l!==void 0?l:null}processReadBuffer(){for(var e,l;;)try{let n=this._readBuffer.readMessage();if(n===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,n)}catch(n){(l=this.onerror)===null||l===void 0||l.call(this,n)}}async close(){this._abortController.abort(),this._process=void 0,this._readBuffer.clear()}send(e){return new Promise(l=>{var n;if(!(!((n=this._process)===null||n===void 0)&&n.stdin))throw new Error("Not connected");let r=kSt(e);this._process.stdin.write(r)?l():this._process.stdin.once("drain",l)})}};function uAn(){return"type"in mYe}c();c();var bYe=class extends TransformStream{constructor({onError:e,onRetry:l,onComment:n}={}){let r;super({start(I){r=IYe({onEvent:a=>{I.enqueue(a)},onError(a){e==="terminate"?I.error(a):typeof e=="function"&&e(a)},onRetry:l,onComment:n})},transform(I){r.feed(I)}})}};var mAn={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Xce=class extends Error{constructor(e,l){super(`Streamable HTTP error: ${l}`),this.code=e}},GYe=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:mAn}async _authThenStart(){var e;if(!this._authProvider)throw new Pg("No auth provider");let l;try{l=await Hk(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(l!=="AUTHORIZED")throw new Pg;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let l={};if(this._authProvider){let r=await this._authProvider.tokens();r&&(l.Authorization=`Bearer ${r.access_token}`)}this._sessionId&&(l["mcp-session-id"]=this._sessionId),this._protocolVersion&&(l["mcp-protocol-version"]=this._protocolVersion);let n=this._normalizeHeaders((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...l,...n})}async _startOrAuthSse(e){var l,n,r;let{resumptionToken:I}=e;try{let a=await this._commonHeaders();a.set("Accept","text/event-stream"),I&&a.set("last-event-id",I);let s=await((l=this._fetch)!==null&&l!==void 0?l:fetch)(this._url,{method:"GET",headers:a,signal:(n=this._abortController)===null||n===void 0?void 0:n.signal});if(!s.ok){if(s.status===401&&this._authProvider)return await this._authThenStart();if(s.status===405)return;throw new Xce(s.status,`Failed to open SSE stream: ${s.statusText}`)}this._handleSseStream(s.body,e,!0)}catch(a){throw(r=this.onerror)===null||r===void 0||r.call(this,a),a}}_getNextReconnectionDelay(e){let l=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,r=this._reconnectionOptions.maxReconnectionDelay;return Math.min(l*Math.pow(n,e),r)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,l=0){var n;let r=this._reconnectionOptions.maxRetries;if(r>0&&l>=r){(n=this.onerror)===null||n===void 0||n.call(this,new Error(`Maximum reconnection attempts (${r}) exceeded.`));return}let I=this._getNextReconnectionDelay(l);setTimeout(()=>{this._startOrAuthSse(e).catch(a=>{var s;(s=this.onerror)===null||s===void 0||s.call(this,new Error(`Failed to reconnect SSE stream: ${a instanceof Error?a.message:String(a)}`)),this._scheduleReconnection(e,l+1)})},I)}_handleSseStream(e,l,n){if(!e)return;let{onresumptiontoken:r,replayMessageId:I}=l,a;(async()=>{var o,d,u,b;try{let p=e.pipeThrough(new TextDecoderStream).pipeThrough(new bYe).getReader();for(;;){let{value:h,done:W}=await p.read();if(W)break;if(h.id&&(a=h.id,r?.(h.id)),!h.event||h.event==="message")try{let y=Rk.parse(JSON.parse(h.data));I!==void 0&&Oie(y)&&(y.id=I),(o=this.onmessage)===null||o===void 0||o.call(this,y)}catch(y){(d=this.onerror)===null||d===void 0||d.call(this,y)}}}catch(p){if((u=this.onerror)===null||u===void 0||u.call(this,new Error(`SSE stream disconnected: ${p}`)),n&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:I},0)}catch(h){(b=this.onerror)===null||b===void 0||b.call(this,new Error(`Failed to reconnect: ${h instanceof Error?h.message:String(h)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Pg("No auth provider");if(await Hk(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new Pg("Failed to authorize")}async close(){var e,l;(e=this._abortController)===null||e===void 0||e.abort(),(l=this.onclose)===null||l===void 0||l.call(this)}async send(e,l){var n,r,I,a;try{let{resumptionToken:s,onresumptiontoken:o}=l||{};if(s){this._startOrAuthSse({resumptionToken:s,replayMessageId:m2e(e)?e.id:void 0}).catch(R=>{var Q;return(Q=this.onerror)===null||Q===void 0?void 0:Q.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},b=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,u),p=b.headers.get("mcp-session-id");if(p&&(this._sessionId=p),!b.ok){if(b.status===401&&this._authProvider){if(this._resourceMetadataUrl=Hce(b),await Hk(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new Pg;return this.send(e)}let R=await b.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${b.status}): ${R}`)}if(b.status===202){DLt(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(R=>{var Q;return(Q=this.onerror)===null||Q===void 0?void 0:Q.call(this,R)});return}let W=(Array.isArray(e)?e:[e]).filter(R=>"method"in R&&"id"in R&&R.id!==void 0).length>0,y=b.headers.get("content-type");if(W)if(y?.includes("text/event-stream"))this._handleSseStream(b.body,{onresumptiontoken:o},!1);else if(y?.includes("application/json")){let R=await b.json(),Q=Array.isArray(R)?R.map(C=>Rk.parse(C)):[Rk.parse(R)];for(let C of Q)(I=this.onmessage)===null||I===void 0||I.call(this,C)}else throw new Xce(-1,`Unexpected content type: ${y}`)}catch(s){throw(a=this.onerror)===null||a===void 0||a.call(this,s),s}}get sessionId(){return this._sessionId}async terminateSession(){var e,l,n;if(this._sessionId)try{let r=await this._commonHeaders(),I={...this._requestInit,method:"DELETE",headers:r,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},a=await((l=this._fetch)!==null&&l!==void 0?l:fetch)(this._url,I);if(!a.ok&&a.status!==405)throw new Xce(a.status,`Failed to terminate session: ${a.statusText}`);this._sessionId=void 0}catch(r){throw(n=this.onerror)===null||n===void 0||n.call(this,r),r}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}};c();var pYe=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 Cje(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?.())}},Cje=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 hYe=class{createTransport(e){switch(e.type){case"stdio":{let l=new uYe({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 GYe(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"sse":return new iYe(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"memory":return new pYe(e.server);default:throw new Error(`Unsupported transport type: ${e.type}`)}}};c();var O9="blackbird-mcp-server",vK="github-mcp-server",vje="playwright";function fK(t){return t.type===void 0||t.type.toLowerCase()==="local"||t.type.toLowerCase()==="stdio"}function HK(t){return kce(t)||Lce(t)}function kce(t){return t.type?.toLowerCase()==="http"}function Lce(t){return t.type?.toLowerCase()==="sse"}function Jce(t){return t.type?.toLowerCase()==="memory"}var fje=class extends bAn{constructor(l,n){super({decodeStrings:!1});this.serverName=l;this.logger=n}_write(l,n,r){try{let I=l.toString();this.logger.log(`[mcp server ${this.serverName} stderr] ${I}`),r()}catch(I){r(I instanceof Error?I:new Error(String(I)))}}},AYe=class{constructor(e,l=new nYe,n=new hYe,r="indirect"){this.logger=e;this.clientFactory=l;this.transportFactory=n;this.envValueMode=r}clients={};transports={};async startLocalMcpClient(e,l,n,r){this.logger.log(`Starting MCP client for ${e} with command: ${n} and args: ${r}`);let I=new fje(e,this.logger),a={type:"stdio",command:n,args:r,env:{...l,PATH:process.env.PATH},stderr:I},s=this.transportFactory.createTransport(a);await this.setupAndConnectClient(e,s)}async startHttpMcpClient(e,l){this.logger.log(`Starting remote MCP client for ${e} with url: ${l.url}`);let n={type:"http",url:l.url,headers:l.headers},r=this.transportFactory.createTransport(n);await this.setupAndConnectClient(e,r)}async startSseMcpClient(e,l){this.logger.log(`Starting remote MCP client for ${e} with url: ${l.url}`);let n={type:"sse",url:l.url,headers:l.headers},r=this.transportFactory.createTransport(n);await this.setupAndConnectClient(e,r)}async startInMemoryMcpClient(e,l){this.logger.log(`Starting in-memory MCP client for ${e}`);let n={type:"memory",server:l},r=this.transportFactory.createTransport(n);await this.setupAndConnectClient(e,r)}async setupAndConnectClient(e,l){this.transports[e]=l,l.onclose=()=>{this.logger.log(`MCP transport for ${e} closed`),delete this.transports[e]},this.logger.log(`Creating MCP client for ${e}...`);let n=this.clientFactory.createClient({name:"github-copilot-developer",version:"1.0.0"},{capabilities:{experimental:void 0,roots:void 0,sampling:void 0}}),r=Date.now();this.logger.log(`Connecting MCP client for ${e}...`),await n.connect(l),n.onclose=()=>{this.logger.log(`MCP client for ${e} closed`),delete this.clients[e]},n.onerror=I=>{this.logger.error(`MCP client for ${e} errored ${I}`)},this.logger.log(`MCP client for ${e} connected, took ${Date.now()-r}ms`),this.clients[e]=n}async getTools(e,l){let n={};for(let[r,I]of Object.entries(this.clients)){let a=[];try{this.logger.log(`Fetching tools from client: ${r}`);let s=await I.listTools(),o=e?.mcpServers[r].tools,d=e?.mcpServers[r].filterMapping;for(let b of s.tools){if(b.name==="get_copilot_space")continue;if(!(o?.includes("*")||o?.includes(b.name))){this.logger.log(`Tool ${b.name} is not in the allowed list for client: ${r}`);continue}let h=bWe(r,b.name),W=`${r}-${b.name}`,y;typeof d=="string"?y=hxe(d):y=hxe(d?.[b.name]??"hidden_characters"),n[`${r}/${b.name}`]={name:W,namespacedName:`${r}/${b.name}`,title:b.title??b.annotations?.title??b.name,description:b.description??W,input_schema:b.inputSchema,readOnly:b.annotations?.readOnlyHint,safeForTelemetry:{name:!!(e?.mcpServers[r].isDefaultServer||h),inputsNames:!!e?.mcpServers[r].isDefaultServer},filterMode:y},a.push(b.name),this.logger.log(`Tool ${b.name} added to tools list for client: ${r}`)}this.logger.log(`Successfully retrieved ${a.length} tools from client: ${r}`);let u=I.getServerVersion();await this.logServerSuccessWithTools(r,a,u,l)}catch(s){this.logger.error(`Failed to get tools from client: ${r} ${s}`)}}return this.logger.log(`All tools retrieved: ${JSON.stringify(n,null,2)}`),n}async logServerSuccessWithTools(e,l,n,r){if(e!=O9&&r)try{let I=l.map(o=>`- ${o}`).join(`
1924
1924
  `),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
1925
1925
 
1926
- ${I}`;await r.logMCPSetup(e,s),this.logger.log(`Updated session log for ${e} with ${l.length} tools`)}catch(I){this.logger.error(`Failed to update session log for ${e}: ${I}`)}}};c();var Hje={mcpServers:{}},ZYe=class{constructor(e,l,n){this.logger=e;this.registry=l;this.remoteEnabled=n?.remoteEnabled??!1,this.mcp3pEnabled=n?.mcp3pEnabled??!1,this.blackbirdMetisIndexEnabled=n?.blackbirdMetisIndexEnabled??!1,this.sessionClient=n?.sessionClient,this.mcpEnvConfig=void 0,this.envValueMode=n?.envValueMode??this.registry.envValueMode}remoteEnabled;mcp3pEnabled;blackbirdMetisIndexEnabled;mcpEnvConfig;sessionClient;envValueMode;ReadMcpConfigFromEnv(e){this.mcpEnvConfig=process.env.GITHUB_COPILOT_MCP_JSON,this.mcp3pEnabled=process.env.GITHUB_COPILOT_3P_MCP_ENABLED==="true",this.remoteEnabled=process.env.GITHUB_COPILOT_REMOTE_MCP_ENABLED==="true",this.blackbirdMetisIndexEnabled=process.env.BLACKBIRD_METIS_INDEX_ENABLED==="true";let l=this.validateEnvConfig();return process.env.GITHUB_COPILOT_CLI_MODE==="true"?this.logger.log("CLI mode detected - skipping default MCP servers"):(this.logger.log("Adding default MCP servers to configuration"),this.configureBlackbirdMcp(l,e),this.configureGitHubMcp(l,e),this.configurePlaywrightMcp(l)),l}validateEnvConfig(){if(!this.mcp3pEnabled)return this.logger.log("User-provided MCPs are disabled"),Hje;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"),Hje;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}`),Hje}}configureGitHubMcp(e,l){this.remoteEnabled?this.configureRemoteGitHubMcp(e,l):this.configureLocalGitHubMcp(e)}configureRemoteGitHubMcp(e,l){this.logger.log("Using default remote GitHub MCP server configuration");let n="repos,issues,users,pull_requests,code_security,secret_protection,actions,web_search";process.env.COPILOT_MCP_COPILOT_SPACES_ENABLED==="true"&&(this.logger.log("Enabling Copilot Spaces in GitHub MCP server configuration"),n=n+",copilot_spaces");let r={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":n,"X-MCP-Host":"github-coding-agent","X-Initiator":"agent"};l&&l.api?.copilot?.integrationId&&(r["Copilot-Integration-Id"]=l.api.copilot.integrationId),process.env.GITHUB_COPILOT_INTERACTION_ID&&(r["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let I={type:"http",url:this.getCapiMcpUrl(),headers:r,tools:["*"],isDefaultServer:!0,filterMapping:{get_issue:"markdown",get_issue_comments:"markdown",get_pull_request:"markdown",get_pull_request_comments:"markdown",get_pull_request_reviews:"markdown"}};e.mcpServers[vK]=I}configureLocalGitHubMcp(e){if(e.mcpServers[vK]){this.logger.log("Using user-provided GitHub MCP server configuration");let l=e.mcpServers[vK]??{};fK(l)&&!l.command&&(e.mcpServers[vK]={...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[vK]=l}}configurePlaywrightMcp(e){if(!e.mcpServers[vje]){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:[...I9e,"--allowed-origins","localhost;localhost:*;127.0.0.1;127.0.0.1:*"],tools:["*"],isDefaultServer:!0};e.mcpServers[vje]=l}}configureBlackbirdMcp(e,l){this.remoteEnabled?this.configureRemoteBlackbirdMcp(e):this.blackbirdMetisIndexEnabled?this.configureLocalMetisBlackbirdMCP(e,l):this.configureLocalBlackbirdMcp(e)}configureLocalMetisBlackbirdMCP(e,l){this.logger.log("Using local Metis Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${l.blackbird?.mode}`);let n=process.env.AGENT_DIR||"/agent";this.logger.log(`Using agent directory: ${n}`);let r=[];l.blackbird?.mode==="tool"&&(r=["*"]),this.logger.log(`Using blackbird Metis server: ${l.blackbird?.mode}`);let I={command:`${n}/blackbird/mcp`,args:["serve","--index",`${n}/blackbird/metis`],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",COPILOT_API_HMAC_KEY:"CAPI_HMAC_KEY",MODEL_BASED_RETRIEVAL_TOKEN:"BLACKBIRD_AUTH_MODEL_BASED_RETRIEVAL_TOKEN",METIS_API_KEY:"BLACKBIRD_AUTH_METIS_API_KEY"},tools:r,isDefaultServer:!0};e.mcpServers[O9]=I}configureLocalBlackbirdMcp(e){this.logger.log("Using local Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let l=[];process.env.BLACKBIRD_MODE==="tool"&&(l=["*"]);let n={command:"./copilot-developer-action-main/blackbird-mcp-server/blackbird-mcp-server",args:["stdio"],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",CAPI_HOST:"COPILOT_API_URL"},tools:l,isDefaultServer:!0};e.mcpServers[O9]=n}configureRemoteBlackbirdMcp(e){this.logger.log("Using remote Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let l=[];process.env.BLACKBIRD_MODE==="tool"&&(l=["*"]);let n={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":"search_agent","X-MCP-Host":"github-coding-agent"};process.env.GITHUB_COPILOT_INTERACTION_ID&&(n["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let r={type:"http",url:this.getCapiMcpUrl(),headers:n,tools:l,isDefaultServer:!0};e.mcpServers[O9]=r}getCapiMcpUrl(){return process.env.COPILOT_API_URL?new URL("/mcp/readonly",process.env.COPILOT_API_URL).toString():"https://api.githubcopilot.com/mcp/readonly"}isValidServerType(e){return fK(e)||kce(e)||Lce(e)||Jce(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&&!fK(l)&&!Jce(l)?(this.logger.error(`Unsupported server type "${l.type}" for server "${e}". Only "Local", "STDIO", or "Memory" are supported.`),!1):l.tools?fK(l)&&!this.isValidLocalServerConfig(l)?(this.logger.error(`Invalid local server configuration for "${e}". Please ensure 'command' and 'args' are provided.`),!1):(kce(l)||Lce(l))&&!this.isValidRemoteServerConfig(l)?(this.logger.error(`Invalid remote server configuration for "${e}". Please ensure 'url' is provided.`),!1):Jce(l)&&!this.isValidInMemoryServerConfig(l)?(this.logger.error(`Invalid in-memory server configuration for "${e}". Please ensure 'serverInstance' is provided and is an instance of MCPServer.`),!1):!0:(this.logger.error(`No tools specified for server "${e}". Please provide a list of tools or "*" to include all tools.`),!1)}async processHttpServer(e,l){try{let n=this.resolveHeaders(l.headers,process.env),r={...l,headers:n};await this.registry.startHttpMcpClient(e,r),this.logger.log(`Started MCP client for remote server ${e}`)}catch(n){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${n}`),n}}async processSseServer(e,l){try{let n=this.resolveRemoteServerConfig(l);await this.registry.startSseMcpClient(e,n),this.logger.log(`Started MCP client for remote server ${e}`)}catch(n){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${n}`),n}}resolveRemoteServerConfig(e){return e.url=this.resolveString(e.url,process.env),e.headers=this.resolveHeaders(e.headers,process.env),{...e,url:e.url,headers:e.headers}}async processInMemoryServer(e,l){try{await this.registry.startInMemoryMcpClient(e,l.serverInstance),this.logger.log(`Started in-memory MCP client for ${e}`)}catch(n){throw this.logger.error(`Failed to start in-memory MCP client for ${e}: ${n}`),n}}async processLocalServer(e,l){let n={...l};if(l.command==="python")try{n=await this.convertPythonToPipx(n)}catch(a){this.logger.error(`Failed to handle Python module for ${e}: ${a}`)}let r=this.buildEnvironment(n),I=this.resolveLocalServerConfig(n,r);this.logger.log(`Starting MCP client for ${e} with command: ${I.command} and args: ${I.args}`);try{await this.registry.startLocalMcpClient(e,r,I.command,I.args),this.logger.log(`Started MCP client for ${e}`)}catch(a){throw this.logger.error(`Failed to start MCP client for ${e}: ${a}`),a}}convertPythonToPipx(e){if(!e||!e.args||e.args.length===0)return e;let l=e.args,n=l.indexOf("-m");if(n===-1||n===l.length-1)throw new Error("Python command with -m flag must specify a module");let r=l[n+1];this.logger.log(`Converting Python module: ${r} to pipx command`);let I=["run",r];for(let a=n+2;a<l.length;a++)I.push(l[a]);for(let a=0;a<n;a++)I.push(l[a]);return{...e,command:"pipx",args:I}}buildEnvironment(e){let l={};if(e.env)if(this.envValueMode==="direct")for(let[n,r]of Object.entries(e.env))l[n]=this.resolveString(r,process.env);else for(let[n,r]of Object.entries(e.env)){let I=r.trim(),a=I;if(I.includes("$")&&(a=this.resolveString(I,process.env)),a!==I){l[n]=a;continue}process.env[I]!==void 0&&(l[n]=process.env[I])}return l}resolveLocalServerConfig(e,l){let n=this.resolveString(e.command,l),r=this.resolveArray(e.args,l);return{...e,command:n,args:r}}resolveString(e,l){return l?e.replace(/\$(?:\{([A-Z0-9_]+)(?::-(.*?))?\}|([A-Z0-9_]+))/g,(n,r,I,a)=>{let o=l[r||a];return o!==void 0?o:I!==void 0?I:n}):e}resolveArray(e,l){return e?l?e.map(n=>this.resolveString(n,l)):e:[]}resolveHeaders(e,l){if(!e)return{};if(!l)return e;let n={};for(let[r,I]of Object.entries(e)){let a=this.resolveArray([I],l);n[r]=a[0]}return n}async processServers(e){if(!e)throw new Error("No servers to process");let l=Object.entries(e.mcpServers).map(([n,r])=>this.processServer(n,r));await Promise.all(l)}async processServer(e,l){if(!this.validateServerConfig(e,l)){this.logger.error(`Skipping server "${e}" due to invalid configuration.`);return}try{fK(l)?await this.processLocalServer(e,l):kce(l)&&this.remoteEnabled?await this.processHttpServer(e,l):Lce(l)&&this.remoteEnabled?await this.processSseServer(e,l):Jce(l)&&await this.processInMemoryServer(e,l)}catch(n){e!==O9&&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 gYe=class{constructor(e,l,n,r="indirect"){this.logger=e;let I;if(typeof l=="string"){if(I=JSON.parse(l),typeof I!="object")throw new Error("Invalid MCP configuration: must be an object");if(I===null||!("mcpServers"in I)||typeof I.mcpServers!="object")throw new Error("Invalid MCP configuration: missing or invalid mcpServers property");this.config=I}else this.config=l;this.disabledServers=new Set(n||[]),this.registry=new AYe(this.logger,void 0,void 0,r),this.processor=new ZYe(this.logger,this.registry,{mcp3pEnabled:!0,remoteEnabled:!0})}registry;processor;config;startServersPromise=null;transport=null;disabledServers;async startServers(){return this.startServersPromise||(this.startServersPromise=this.processServersWithExtensions()),this.startServersPromise}async injectDefaultServers(e){}async processServersWithExtensions(){await this.injectDefaultServers(this.config);let e;if(this.disabledServers.size>0){let l={};for(let[n,r]of Object.entries(this.config.mcpServers))this.disabledServers.has(n)?this.logger.log(`Skipping disabled MCP server: ${n}`):l[n]=r;e={...this.config,mcpServers:l}}else e=this.config;return this.processor.processServers(e)}async stopServers(){for(let[e,l]of Object.entries(this.registry.transports))try{await l.close()}catch(n){this.logger.error(`Error closing transport for ${e}: ${n}`)}this.startServersPromise=null,this.transport=null}async getTools(e,l,n){await this.startServers(),this.transport=this.transport??new MIe(e,l,!0);let r=[];for(let I of Object.keys(this.registry.clients)){let a=await this.transport.loadTools({mcpClient:this.registry.clients[I],clientName:I,tools:this.config.mcpServers[I]?.tools||["*"],filterMapping:this.config.mcpServers[I]?.filterMapping||"hidden_characters"},n);r.push(...a)}return r}getConfig(){return this.config}async startServer(e,l){await this.startServers(),this.config.mcpServers[e]=l,await this.processor.processServer(e,l),this.transport=null}async stopServer(e){let l=this.registry.transports[e];if(l)try{await l.close(),delete this.registry.transports[e]}catch(n){this.logger.error(`Error closing transport for ${e}: ${n}`)}this.registry.clients[e]&&delete this.registry.clients[e],this.transport=null}async restartServer(e,l){this.isServerRunning(e)&&await this.stopServer(e),delete this.config.mcpServers[e],await this.startServer(e,l)}isServerRunning(e){return e in this.registry.transports&&e in this.registry.clients}isServerDisabled(e){return this.disabledServers.has(e)}async disableServer(e){if(this.disabledServers.has(e)){this.logger.log(`Server ${e} is already disabled`);return}this.disabledServers.add(e),this.logger.log(`Disabled server ${e} for this session`),this.isServerRunning(e)&&await this.stopServer(e),this.transport=null}async enableServer(e){if(!this.disabledServers.has(e)){this.logger.log(`Server ${e} is not disabled`);return}this.disabledServers.delete(e),this.logger.log(`Enabled server ${e} for this session`);let l=this.getServerConfig(e);l?await this.startServer(e,l):await this.startBuiltInServer(e),this.transport=null}async startBuiltInServer(e){}getServerConfig(e){return this.config.mcpServers[e]}};c();var GAn="/login/device/code",pAn="/login/oauth/access_token",JSt="Ov23ctDVkRmgkPke0Mmm",kk="https://github.com",Xk=class extends Error{constructor(l,n){super(n);this.status=l;this.message=n;this.name="GitHubApiError"}};function T9(t){let e=new URL(t);return e.hostname.startsWith("api.")||(e.hostname="api."+e.hostname),e.href}async function BSt(t){let e=new URL(GAn,t),l=await fetch(e.href,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({client_id:JSt,scope:"user:email,read:user,repo,workflow"})});if(!l.ok)throw new Xk(l.status,`Failed to request device code: ${l.statusText}`);return await l.json()}async function SSt(t,e){let l=new URL(pAn,t),n=await fetch(l.href,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({client_id:JSt,device_code:e,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})});if(!n.ok)throw new Xk(n.status,`Failed to authorize: ${n.statusText}`);let r=await n.json();if(typeof r.access_token=="string")return r.access_token;if(r.error!=="authorization_pending"&&r.error!=="slow_down")throw new Error(r.error_description||`Unexpected error: ${r.error}`)}async function XK(t,e){let l=new URL("/user",T9(t)),n=await fetch(l.href,{headers:{Authorization:`Bearer ${e}`,Accept:"application/json"}});if(!n.ok)throw new Xk(n.status,`Failed to fetch user info: ${n.statusText}`);return(await n.json()).login}async function qE(t,e){let l=`
1926
+ ${I}`;await r.logMCPSetup(e,s),this.logger.log(`Updated session log for ${e} with ${l.length} tools`)}catch(I){this.logger.error(`Failed to update session log for ${e}: ${I}`)}}};c();var Hje={mcpServers:{}},ZYe=class{constructor(e,l,n){this.logger=e;this.registry=l;this.remoteEnabled=n?.remoteEnabled??!1,this.mcp3pEnabled=n?.mcp3pEnabled??!1,this.blackbirdMetisIndexEnabled=n?.blackbirdMetisIndexEnabled??!1,this.sessionClient=n?.sessionClient,this.mcpEnvConfig=void 0,this.envValueMode=n?.envValueMode??this.registry.envValueMode}remoteEnabled;mcp3pEnabled;blackbirdMetisIndexEnabled;mcpEnvConfig;sessionClient;envValueMode;ReadMcpConfigFromEnv(e){this.mcpEnvConfig=process.env.GITHUB_COPILOT_MCP_JSON,this.mcp3pEnabled=process.env.GITHUB_COPILOT_3P_MCP_ENABLED==="true",this.remoteEnabled=process.env.GITHUB_COPILOT_REMOTE_MCP_ENABLED==="true",this.blackbirdMetisIndexEnabled=process.env.BLACKBIRD_METIS_INDEX_ENABLED==="true";let l=this.validateEnvConfig();return process.env.GITHUB_COPILOT_CLI_MODE==="true"?this.logger.log("CLI mode detected - skipping default MCP servers"):(this.logger.log("Adding default MCP servers to configuration"),this.configureBlackbirdMcp(l,e),this.configureGitHubMcp(l,e),this.configurePlaywrightMcp(l)),l}validateEnvConfig(){if(!this.mcp3pEnabled)return this.logger.log("User-provided MCPs are disabled"),Hje;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"),Hje;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}`),Hje}}configureGitHubMcp(e,l){this.remoteEnabled?this.configureRemoteGitHubMcp(e,l):this.configureLocalGitHubMcp(e)}configureRemoteGitHubMcp(e,l){this.logger.log("Using default remote GitHub MCP server configuration");let n="repos,issues,users,pull_requests,code_security,secret_protection,actions,web_search";process.env.COPILOT_MCP_COPILOT_SPACES_ENABLED==="true"&&(this.logger.log("Enabling Copilot Spaces in GitHub MCP server configuration"),n=n+",copilot_spaces");let r={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":n,"X-MCP-Host":"github-coding-agent","X-Initiator":"agent"};l&&l.api?.copilot?.integrationId&&(r["Copilot-Integration-Id"]=l.api.copilot.integrationId),process.env.GITHUB_COPILOT_INTERACTION_ID&&(r["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let I={type:"http",url:this.getCapiMcpUrl(),headers:r,tools:["*"],isDefaultServer:!0,filterMapping:{get_issue:"markdown",get_issue_comments:"markdown",get_pull_request:"markdown",get_pull_request_comments:"markdown",get_pull_request_reviews:"markdown"}};e.mcpServers[vK]=I}configureLocalGitHubMcp(e){if(e.mcpServers[vK]){this.logger.log("Using user-provided GitHub MCP server configuration");let l=e.mcpServers[vK]??{};fK(l)&&!l.command&&(e.mcpServers[vK]={...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[vK]=l}}configurePlaywrightMcp(e){if(!e.mcpServers[vje]){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:[...I9e,"--allowed-origins","localhost;localhost:*;127.0.0.1;127.0.0.1:*"],tools:["*"],isDefaultServer:!0};e.mcpServers[vje]=l}}configureBlackbirdMcp(e,l){this.remoteEnabled?this.configureRemoteBlackbirdMcp(e):this.blackbirdMetisIndexEnabled?this.configureLocalMetisBlackbirdMCP(e,l):this.configureLocalBlackbirdMcp(e)}configureLocalMetisBlackbirdMCP(e,l){this.logger.log("Using local Metis Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${l.blackbird?.mode}`);let n=process.env.AGENT_DIR||"/agent";this.logger.log(`Using agent directory: ${n}`);let r=[];l.blackbird?.mode==="tool"&&(r=["*"]),this.logger.log(`Using blackbird Metis server: ${l.blackbird?.mode}`);let I={command:`${n}/blackbird/mcp`,args:["serve","--index",`${n}/blackbird/metis`],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",COPILOT_API_HMAC_KEY:"CAPI_HMAC_KEY",MODEL_BASED_RETRIEVAL_TOKEN:"BLACKBIRD_AUTH_MODEL_BASED_RETRIEVAL_TOKEN",METIS_API_KEY:"BLACKBIRD_AUTH_METIS_API_KEY"},tools:r,isDefaultServer:!0};e.mcpServers[O9]=I}configureLocalBlackbirdMcp(e){this.logger.log("Using local Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let l=[];process.env.BLACKBIRD_MODE==="tool"&&(l=["*"]);let n={command:"./copilot-developer-action-main/blackbird-mcp-server/blackbird-mcp-server",args:["stdio"],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",CAPI_HOST:"COPILOT_API_URL"},tools:l,isDefaultServer:!0};e.mcpServers[O9]=n}configureRemoteBlackbirdMcp(e){this.logger.log("Using remote Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let l=[];process.env.BLACKBIRD_MODE==="tool"&&(l=["*"]);let n={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":"search_agent","X-MCP-Host":"github-coding-agent"};process.env.GITHUB_COPILOT_INTERACTION_ID&&(n["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let r={type:"http",url:this.getCapiMcpUrl(),headers:n,tools:l,isDefaultServer:!0};e.mcpServers[O9]=r}getCapiMcpUrl(){return process.env.COPILOT_API_URL?new URL("/mcp/readonly",process.env.COPILOT_API_URL).toString():"https://api.githubcopilot.com/mcp/readonly"}isValidServerType(e){return fK(e)||kce(e)||Lce(e)||Jce(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&&!fK(l)&&!Jce(l)?(this.logger.error(`Unsupported server type "${l.type}" for server "${e}". Only "Local", "STDIO", or "Memory" are supported.`),!1):l.tools?fK(l)&&!this.isValidLocalServerConfig(l)?(this.logger.error(`Invalid local server configuration for "${e}". Please ensure 'command' and 'args' are provided.`),!1):(kce(l)||Lce(l))&&!this.isValidRemoteServerConfig(l)?(this.logger.error(`Invalid remote server configuration for "${e}". Please ensure 'url' is provided.`),!1):Jce(l)&&!this.isValidInMemoryServerConfig(l)?(this.logger.error(`Invalid in-memory server configuration for "${e}". Please ensure 'serverInstance' is provided and is an instance of MCPServer.`),!1):!0:(this.logger.error(`No tools specified for server "${e}". Please provide a list of tools or "*" to include all tools.`),!1)}async processHttpServer(e,l){try{let n=this.resolveHeaders(l.headers,process.env),r={...l,headers:n};await this.registry.startHttpMcpClient(e,r),this.logger.log(`Started MCP client for remote server ${e}`)}catch(n){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${n}`),n}}async processSseServer(e,l){try{let n=this.resolveRemoteServerConfig(l);await this.registry.startSseMcpClient(e,n),this.logger.log(`Started MCP client for remote server ${e}`)}catch(n){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${n}`),n}}resolveRemoteServerConfig(e){return e.url=this.resolveString(e.url,process.env),e.headers=this.resolveHeaders(e.headers,process.env),{...e,url:e.url,headers:e.headers}}async processInMemoryServer(e,l){try{await this.registry.startInMemoryMcpClient(e,l.serverInstance),this.logger.log(`Started in-memory MCP client for ${e}`)}catch(n){throw this.logger.error(`Failed to start in-memory MCP client for ${e}: ${n}`),n}}async processLocalServer(e,l){let n={...l};if(l.command==="python")try{n=await this.convertPythonToPipx(n)}catch(a){this.logger.error(`Failed to handle Python module for ${e}: ${a}`)}let r=this.buildEnvironment(n),I=this.resolveLocalServerConfig(n,r);this.logger.log(`Starting MCP client for ${e} with command: ${I.command} and args: ${I.args}`);try{await this.registry.startLocalMcpClient(e,r,I.command,I.args),this.logger.log(`Started MCP client for ${e}`)}catch(a){throw this.logger.error(`Failed to start MCP client for ${e}: ${a}`),a}}convertPythonToPipx(e){if(!e||!e.args||e.args.length===0)return e;let l=e.args,n=l.indexOf("-m");if(n===-1||n===l.length-1)throw new Error("Python command with -m flag must specify a module");let r=l[n+1];this.logger.log(`Converting Python module: ${r} to pipx command`);let I=["run",r];for(let a=n+2;a<l.length;a++)I.push(l[a]);for(let a=0;a<n;a++)I.push(l[a]);return{...e,command:"pipx",args:I}}buildEnvironment(e){let l={};if(e.env)if(this.envValueMode==="direct")for(let[n,r]of Object.entries(e.env))l[n]=this.resolveString(r,process.env);else for(let[n,r]of Object.entries(e.env)){let I=r.trim(),a=I;if(I.includes("$")&&(a=this.resolveString(I,process.env)),a!==I){l[n]=a;continue}process.env[I]!==void 0&&(l[n]=process.env[I])}return l}resolveLocalServerConfig(e,l){let n=this.resolveString(e.command,l),r=this.resolveArray(e.args,l);return{...e,command:n,args:r}}resolveString(e,l){return l?e.replace(/\$(?:\{([A-Z0-9_]+)(?::-(.*?))?\}|([A-Z0-9_]+))/g,(n,r,I,a)=>{let o=l[r||a];return o!==void 0?o:I!==void 0?I:n}):e}resolveArray(e,l){return e?l?e.map(n=>this.resolveString(n,l)):e:[]}resolveHeaders(e,l){if(!e)return{};if(!l)return e;let n={};for(let[r,I]of Object.entries(e)){let a=this.resolveArray([I],l);n[r]=a[0]}return n}async processServers(e){if(!e)throw new Error("No servers to process");let l=Object.entries(e.mcpServers).map(([n,r])=>this.processServer(n,r));await Promise.all(l)}async processServer(e,l){if(!this.validateServerConfig(e,l)){this.logger.error(`Skipping server "${e}" due to invalid configuration.`);return}try{fK(l)?await this.processLocalServer(e,l):kce(l)&&this.remoteEnabled?await this.processHttpServer(e,l):Lce(l)&&this.remoteEnabled?await this.processSseServer(e,l):Jce(l)&&await this.processInMemoryServer(e,l)}catch(n){e!==O9&&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 gYe=class{constructor(e,l,n,r="indirect"){this.logger=e;let I;if(typeof l=="string"){if(I=JSON.parse(l),typeof I!="object")throw new Error("Invalid MCP configuration: must be an object");if(I===null||!("mcpServers"in I)||typeof I.mcpServers!="object")throw new Error("Invalid MCP configuration: missing or invalid mcpServers property");this.config=I}else this.config=l;this.disabledServers=new Set(n||[]),this.registry=new AYe(this.logger,void 0,void 0,r),this.processor=new ZYe(this.logger,this.registry,{mcp3pEnabled:!0,remoteEnabled:!0})}registry;processor;config;startServersPromise=null;transport=null;disabledServers;async startServers(){return this.startServersPromise||(this.startServersPromise=this.processServersWithExtensions()),this.startServersPromise}async injectDefaultServers(e){}async processServersWithExtensions(){await this.injectDefaultServers(this.config);let e;if(this.disabledServers.size>0){let l={};for(let[n,r]of Object.entries(this.config.mcpServers))this.disabledServers.has(n)?this.logger.log(`Skipping disabled MCP server: ${n}`):l[n]=r;e={...this.config,mcpServers:l}}else e=this.config;return this.processor.processServers(e)}async stopServers(){for(let[e,l]of Object.entries(this.registry.transports))try{await l.close()}catch(n){this.logger.error(`Error closing transport for ${e}: ${n}`)}this.startServersPromise=null,this.transport=null}async getTools(e,l,n){await this.startServers(),this.transport=this.transport??new MIe(e,l,!0);let r=[];for(let I of Object.keys(this.registry.clients)){let a=await this.transport.loadTools({mcpClient:this.registry.clients[I],clientName:I,tools:this.config.mcpServers[I]?.tools||["*"],filterMapping:this.config.mcpServers[I]?.filterMapping||"hidden_characters"},n);r.push(...a)}return r}getConfig(){return this.config}getClients(){return this.registry.clients}async startServer(e,l){await this.startServers(),this.config.mcpServers[e]=l,await this.processor.processServer(e,l),this.transport=null}async stopServer(e){let l=this.registry.transports[e];if(l)try{await l.close(),delete this.registry.transports[e]}catch(n){this.logger.error(`Error closing transport for ${e}: ${n}`)}this.registry.clients[e]&&delete this.registry.clients[e],this.transport=null}async restartServer(e,l){this.isServerRunning(e)&&await this.stopServer(e),delete this.config.mcpServers[e],await this.startServer(e,l)}isServerRunning(e){return e in this.registry.transports&&e in this.registry.clients}isServerDisabled(e){return this.disabledServers.has(e)}async disableServer(e){if(this.disabledServers.has(e)){this.logger.log(`Server ${e} is already disabled`);return}this.disabledServers.add(e),this.logger.log(`Disabled server ${e} for this session`),this.isServerRunning(e)&&await this.stopServer(e),this.transport=null}async enableServer(e){if(!this.disabledServers.has(e)){this.logger.log(`Server ${e} is not disabled`);return}this.disabledServers.delete(e),this.logger.log(`Enabled server ${e} for this session`);let l=this.getServerConfig(e);l?await this.startServer(e,l):await this.startBuiltInServer(e),this.transport=null}async startBuiltInServer(e){}getServerConfig(e){return this.config.mcpServers[e]}};c();var GAn="/login/device/code",pAn="/login/oauth/access_token",JSt="Ov23ctDVkRmgkPke0Mmm",kk="https://github.com",Xk=class extends Error{constructor(l,n){super(n);this.status=l;this.message=n;this.name="GitHubApiError"}};function T9(t){let e=new URL(t);return e.hostname.startsWith("api.")||(e.hostname="api."+e.hostname),e.href}async function BSt(t){let e=new URL(GAn,t),l=await fetch(e.href,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({client_id:JSt,scope:"user:email,read:user,repo,workflow"})});if(!l.ok)throw new Xk(l.status,`Failed to request device code: ${l.statusText}`);return await l.json()}async function SSt(t,e){let l=new URL(pAn,t),n=await fetch(l.href,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({client_id:JSt,device_code:e,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})});if(!n.ok)throw new Xk(n.status,`Failed to authorize: ${n.statusText}`);let r=await n.json();if(typeof r.access_token=="string")return r.access_token;if(r.error!=="authorization_pending"&&r.error!=="slow_down")throw new Error(r.error_description||`Unexpected error: ${r.error}`)}async function XK(t,e){let l=new URL("/user",T9(t)),n=await fetch(l.href,{headers:{Authorization:`Bearer ${e}`,Accept:"application/json"}});if(!n.ok)throw new Xk(n.status,`Failed to fetch user info: ${n.statusText}`);return(await n.json()).login}async function qE(t,e){let l=`
1927
1927
  {
1928
1928
  viewer {
1929
1929
  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.342-14",
4
+ "version": "0.0.342-15",
5
5
  "type": "module",
6
6
  "repository": {
7
7
  "type": "git",
@@ -34,7 +34,7 @@
34
34
  "sdk/**/*"
35
35
  ],
36
36
  "buildMetadata": {
37
- "gitCommit": "da88e16"
37
+ "gitCommit": "4b73aac"
38
38
  },
39
39
  "dependencies": {
40
40
  "node-pty": "npm:@devm33/node-pty@^1.0.8",
package/sdk/index.js CHANGED
@@ -1378,7 +1378,7 @@ Pay attention to the following when using it:
1378
1378
  `}var xjI=wq.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 xjI){let I=wq.env[e];I!==void 0&&(I.startsWith("()")||(t[e]=I))}return t}var Aq=class{constructor(e){this._abortController=new AbortController,this._readBuffer=new Qq,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new fjI)}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,s,a;this._process=(0,YKe.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:wq.platform==="win32"&&zjI(),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)}),(s=this._process.stdout)===null||s===void 0||s.on("data",r=>{this._readBuffer.append(r),this.processReadBuffer()}),(a=this._process.stdout)===null||a===void 0||a.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=NKe(e);this._process.stdin.write(n)?I():this._process.stdin.once("drain",I)})}};function zjI(){return"type"in wq}G();G();var Xq=class extends TransformStream{constructor({onError:e,onRetry:I,onComment:l}={}){let n;super({start(c){n=Yq({onEvent:s=>{c.enqueue(s)},onError(s){e==="terminate"?c.error(s):typeof e=="function"&&e(s)},onRetry:I,onComment:l})},transform(c){n.feed(c)}})}};var UjI={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},kx=class extends Error{constructor(e,I){super(`Streamable HTTP error: ${I}`),this.code=e}},Eq=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:UjI}async _authThenStart(){var e;if(!this._authProvider)throw new lo("No auth provider");let I;try{I=await gV(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 lo;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 s=await this._commonHeaders();s.set("Accept","text/event-stream"),c&&s.set("last-event-id",c);let a=await((I=this._fetch)!==null&&I!==void 0?I:fetch)(this._url,{method:"GET",headers:s,signal:(l=this._abortController)===null||l===void 0?void 0:l.signal});if(!a.ok){if(a.status===401&&this._authProvider)return await this._authThenStart();if(a.status===405)return;throw new kx(a.status,`Failed to open SSE stream: ${a.statusText}`)}this._handleSseStream(a.body,e,!0)}catch(s){throw(n=this.onerror)===null||n===void 0||n.call(this,s),s}}_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(s=>{var a;(a=this.onerror)===null||a===void 0||a.call(this,new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(e,I+1)})},c)}_handleSseStream(e,I,l){if(!e)return;let{onresumptiontoken:n,replayMessageId:c}=I,s;(async()=>{var r,o,d,i;try{let h=e.pipeThrough(new TextDecoderStream).pipeThrough(new Xq).getReader();for(;;){let{value:p,done:Z}=await h.read();if(Z)break;if(p.id&&(s=p.id,n?.(p.id)),!p.event||p.event==="message")try{let u=ZV.parse(JSON.parse(p.data));c!==void 0&&O9(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:s,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 lo("No auth provider");if(await gV(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new lo("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,s;try{let{resumptionToken:a,onresumptiontoken:r}=I||{};if(a){this._startOrAuthSse({resumptionToken:a,replayMessageId:w6(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=Lx(i),await gV(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new lo;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){EMe(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=>ZV.parse(y)):[ZV.parse(N)];for(let y of Y)(c=this.onmessage)===null||c===void 0||c.call(this,y)}else throw new kx(-1,`Unexpected content type: ${u}`)}catch(a){throw(s=this.onerror)===null||s===void 0||s.call(this,a),a}}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},s=await((I=this._fetch)!==null&&I!==void 0?I:fetch)(this._url,c);if(!s.ok&&s.status!==405)throw new kx(s.status,`Failed to terminate session: ${s.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 Hq=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(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?.())}},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(I){this.onerror?.(I instanceof Error?I:new Error(String(I)))}})}async close(){this.closed||(this.closed=!0,this.onclose?.())}};var vq=class{createTransport(e){switch(e.type){case"stdio":{let I=new Aq({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 Eq(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"sse":return new Fq(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"memory":return new Hq(e.server);default:throw new Error(`Unsupported transport type: ${e.type}`)}}};G();var uF="blackbird-mcp-server",o1="github-mcp-server",Kpe="playwright";function d1(t){return t.type===void 0||t.type.toLowerCase()==="local"||t.type.toLowerCase()==="stdio"}function Cq(t){return t.type?.toLowerCase()==="http"}function Jq(t){return t.type?.toLowerCase()==="sse"}function fx(t){return t.type?.toLowerCase()==="memory"}var Ppe=class extends SjI{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)))}}},Lq=class{constructor(e,I=new Wq,l=new vq,n="indirect"){this.logger=e;this.clientFactory=I;this.transportFactory=l;this.envValueMode=n}clients={};transports={};async startLocalMcpClient(e,I,l,n){this.logger.log(`Starting MCP client for ${e} with command: ${l} and args: ${n}`);let c=new Ppe(e,this.logger),s={type:"stdio",command:l,args:n,env:{...I,PATH:process.env.PATH},stderr:c},a=this.transportFactory.createTransport(s);await this.setupAndConnectClient(e,a)}async startHttpMcpClient(e,I){this.logger.log(`Starting remote MCP client for ${e} with url: ${I.url}`);let l={type:"http",url:I.url,headers:I.headers},n=this.transportFactory.createTransport(l);await this.setupAndConnectClient(e,n)}async startSseMcpClient(e,I){this.logger.log(`Starting remote MCP client for ${e} with url: ${I.url}`);let l={type:"sse",url:I.url,headers:I.headers},n=this.transportFactory.createTransport(l);await this.setupAndConnectClient(e,n)}async startInMemoryMcpClient(e,I){this.logger.log(`Starting in-memory MCP client for ${e}`);let l={type:"memory",server:I},n=this.transportFactory.createTransport(l);await this.setupAndConnectClient(e,n)}async setupAndConnectClient(e,I){this.transports[e]=I,I.onclose=()=>{this.logger.log(`MCP transport for ${e} closed`),delete this.transports[e]},this.logger.log(`Creating MCP client for ${e}...`);let l=this.clientFactory.createClient({name:"github-copilot-developer",version:"1.0.0"},{capabilities:{experimental:void 0,roots:void 0,sampling:void 0}}),n=Date.now();this.logger.log(`Connecting MCP client for ${e}...`),await l.connect(I),l.onclose=()=>{this.logger.log(`MCP client for ${e} closed`),delete this.clients[e]},l.onerror=c=>{this.logger.error(`MCP client for ${e} errored ${c}`)},this.logger.log(`MCP client for ${e} connected, took ${Date.now()-n}ms`),this.clients[e]=l}async getTools(e,I){let l={};for(let[n,c]of Object.entries(this.clients)){let s=[];try{this.logger.log(`Fetching tools from client: ${n}`);let a=await c.listTools(),r=e?.mcpServers[n].tools,o=e?.mcpServers[n].filterMapping;for(let i of a.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=m6(n,i.name),Z=`${n}-${i.name}`,u;typeof o=="string"?u=pbe(o):u=pbe(o?.[i.name]??"hidden_characters"),l[`${n}/${i.name}`]={name:Z,namespacedName:`${n}/${i.name}`,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},s.push(i.name),this.logger.log(`Tool ${i.name} added to tools list for client: ${n}`)}this.logger.log(`Successfully retrieved ${s.length} tools from client: ${n}`);let d=c.getServerVersion();await this.logServerSuccessWithTools(n,s,d,I)}catch(a){this.logger.error(`Failed to get tools from client: ${n} ${a}`)}}return this.logger.log(`All tools retrieved: ${JSON.stringify(l,null,2)}`),l}async logServerSuccessWithTools(e,I,l,n){if(e!=uF&&n)try{let c=I.map(r=>`- ${r}`).join(`
1379
1379
  `),a=`MCP server started successfully${l?` (version ${l.version})`:""} with ${I.length} ${I.length===1?"tool":"tools"} - for the full output, see the verbose logs
1380
1380
 
1381
- ${c}`;await n.logMCPSetup(e,a),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 qpe={mcpServers:{}},kq=class{constructor(e,I,l){this.logger=e;this.registry=I;this.remoteEnabled=l?.remoteEnabled??!1,this.mcp3pEnabled=l?.mcp3pEnabled??!1,this.blackbirdMetisIndexEnabled=l?.blackbirdMetisIndexEnabled??!1,this.sessionClient=l?.sessionClient,this.mcpEnvConfig=void 0,this.envValueMode=l?.envValueMode??this.registry.envValueMode}remoteEnabled;mcp3pEnabled;blackbirdMetisIndexEnabled;mcpEnvConfig;sessionClient;envValueMode;ReadMcpConfigFromEnv(e){this.mcpEnvConfig=process.env.GITHUB_COPILOT_MCP_JSON,this.mcp3pEnabled=process.env.GITHUB_COPILOT_3P_MCP_ENABLED==="true",this.remoteEnabled=process.env.GITHUB_COPILOT_REMOTE_MCP_ENABLED==="true",this.blackbirdMetisIndexEnabled=process.env.BLACKBIRD_METIS_INDEX_ENABLED==="true";let I=this.validateEnvConfig();return process.env.GITHUB_COPILOT_CLI_MODE==="true"?this.logger.log("CLI mode detected - skipping default MCP servers"):(this.logger.log("Adding default MCP servers to configuration"),this.configureBlackbirdMcp(I,e),this.configureGitHubMcp(I,e),this.configurePlaywrightMcp(I)),I}validateEnvConfig(){if(!this.mcp3pEnabled)return this.logger.log("User-provided MCPs are disabled"),qpe;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"),qpe;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}`),qpe}}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[o1]=c}configureLocalGitHubMcp(e){if(e.mcpServers[o1]){this.logger.log("Using user-provided GitHub MCP server configuration");let I=e.mcpServers[o1]??{};d1(I)&&!I.command&&(e.mcpServers[o1]={...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[o1]=I}}configurePlaywrightMcp(e){if(!e.mcpServers[Kpe]){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:[...cme,"--allowed-origins","localhost;localhost:*;127.0.0.1;127.0.0.1:*"],tools:["*"],isDefaultServer:!0};e.mcpServers[Kpe]=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[uF]=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[uF]=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[uF]=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 d1(e)||Cq(e)||Jq(e)||fx(e)}isValidLocalServerConfig(e){return e.command!==void 0&&e.command.trim()!==""&&Array.isArray(e.args)}isValidRemoteServerConfig(e){return e.url!==void 0&&e.url.trim()!==""}isValidInMemoryServerConfig(e){return e.serverInstance!==void 0&&typeof e.serverInstance=="object"}validateServerConfig(e,I){return this.remoteEnabled&&!this.isValidServerType(I)?(this.logger.error(`Unsupported server type "${I.type}" for server "${e}". Only "Local", "STDIO", "HTTP", "SSE", or "Memory" are supported.`),!1):!this.remoteEnabled&&!d1(I)&&!fx(I)?(this.logger.error(`Unsupported server type "${I.type}" for server "${e}". Only "Local", "STDIO", or "Memory" are supported.`),!1):I.tools?d1(I)&&!this.isValidLocalServerConfig(I)?(this.logger.error(`Invalid local server configuration for "${e}". Please ensure 'command' and 'args' are provided.`),!1):(Cq(I)||Jq(I))&&!this.isValidRemoteServerConfig(I)?(this.logger.error(`Invalid remote server configuration for "${e}". Please ensure 'url' is provided.`),!1):fx(I)&&!this.isValidInMemoryServerConfig(I)?(this.logger.error(`Invalid in-memory server configuration for "${e}". Please ensure 'serverInstance' is provided and is an instance of MCPServer.`),!1):!0:(this.logger.error(`No tools specified for server "${e}". Please provide a list of tools or "*" to include all tools.`),!1)}async processHttpServer(e,I){try{let l=this.resolveHeaders(I.headers,process.env),n={...I,headers:l};await this.registry.startHttpMcpClient(e,n),this.logger.log(`Started MCP client for remote server ${e}`)}catch(l){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${l}`),l}}async processSseServer(e,I){try{let l=this.resolveRemoteServerConfig(I);await this.registry.startSseMcpClient(e,l),this.logger.log(`Started MCP client for remote server ${e}`)}catch(l){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${l}`),l}}resolveRemoteServerConfig(e){return e.url=this.resolveString(e.url,process.env),e.headers=this.resolveHeaders(e.headers,process.env),{...e,url:e.url,headers:e.headers}}async processInMemoryServer(e,I){try{await this.registry.startInMemoryMcpClient(e,I.serverInstance),this.logger.log(`Started in-memory MCP client for ${e}`)}catch(l){throw this.logger.error(`Failed to start in-memory MCP client for ${e}: ${l}`),l}}async processLocalServer(e,I){let l={...I};if(I.command==="python")try{l=await this.convertPythonToPipx(l)}catch(s){this.logger.error(`Failed to handle Python module for ${e}: ${s}`)}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(s){throw this.logger.error(`Failed to start MCP client for ${e}: ${s}`),s}}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 s=l+2;s<I.length;s++)c.push(I[s]);for(let s=0;s<l;s++)c.push(I[s]);return{...e,command:"pipx",args:c}}buildEnvironment(e){let I={};if(e.env)if(this.envValueMode==="direct")for(let[l,n]of Object.entries(e.env))I[l]=this.resolveString(n,process.env);else for(let[l,n]of Object.entries(e.env)){let c=n.trim(),s=c;if(c.includes("$")&&(s=this.resolveString(c,process.env)),s!==c){I[l]=s;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,s)=>{let r=I[n||s];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 s=this.resolveArray([c],I);l[n]=s[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{d1(I)?await this.processLocalServer(e,I):Cq(I)&&this.remoteEnabled?await this.processHttpServer(e,I):Jq(I)&&this.remoteEnabled?await this.processSseServer(e,I):fx(I)&&await this.processInMemoryServer(e,I)}catch(l){e!==uF&&await this.logServerFailure(e,l)}}async logServerFailure(e,I){if(this.sessionClient)try{await this.sessionClient.logMCPSetup(e,`<error>MCP server failed to start: ${I.message} - for the full output, see the verbose logs</error>`)}catch(l){this.logger.error(`Failed to log failure for MCP Server '${e}': '${l}'`)}}};var fq=class{constructor(e,I,l,n="indirect"){this.logger=e;let c;if(typeof I=="string"){if(c=JSON.parse(I),typeof c!="object")throw new Error("Invalid MCP configuration: must be an object");if(c===null||!("mcpServers"in c)||typeof c.mcpServers!="object")throw new Error("Invalid MCP configuration: missing or invalid mcpServers property");this.config=c}else this.config=I;this.disabledServers=new Set(l||[]),this.registry=new Lq(this.logger,void 0,void 0,n),this.processor=new kq(this.logger,this.registry,{mcp3pEnabled:!0,remoteEnabled:!0})}registry;processor;config;startServersPromise=null;transport=null;disabledServers;async startServers(){return this.startServersPromise||(this.startServersPromise=this.processServersWithExtensions()),this.startServersPromise}async injectDefaultServers(e){}async processServersWithExtensions(){await this.injectDefaultServers(this.config);let e;if(this.disabledServers.size>0){let I={};for(let[l,n]of Object.entries(this.config.mcpServers))this.disabledServers.has(l)?this.logger.log(`Skipping disabled MCP server: ${l}`):I[l]=n;e={...this.config,mcpServers:I}}else e=this.config;return this.processor.processServers(e)}async stopServers(){for(let[e,I]of Object.entries(this.registry.transports))try{await I.close()}catch(l){this.logger.error(`Error closing transport for ${e}: ${l}`)}this.startServersPromise=null,this.transport=null}async getTools(e,I,l){await this.startServers(),this.transport=this.transport??new f9(e,I,!0);let n=[];for(let c of Object.keys(this.registry.clients)){let s=await this.transport.loadTools({mcpClient:this.registry.clients[c],clientName:c,tools:this.config.mcpServers[c]?.tools||["*"],filterMapping:this.config.mcpServers[c]?.filterMapping||"hidden_characters"},l);n.push(...s)}return n}getConfig(){return this.config}async startServer(e,I){await this.startServers(),this.config.mcpServers[e]=I,await this.processor.processServer(e,I),this.transport=null}async stopServer(e){let I=this.registry.transports[e];if(I)try{await I.close(),delete this.registry.transports[e]}catch(l){this.logger.error(`Error closing transport for ${e}: ${l}`)}this.registry.clients[e]&&delete this.registry.clients[e],this.transport=null}async restartServer(e,I){this.isServerRunning(e)&&await this.stopServer(e),delete this.config.mcpServers[e],await this.startServer(e,I)}isServerRunning(e){return e in this.registry.transports&&e in this.registry.clients}isServerDisabled(e){return this.disabledServers.has(e)}async disableServer(e){if(this.disabledServers.has(e)){this.logger.log(`Server ${e} is already disabled`);return}this.disabledServers.add(e),this.logger.log(`Disabled server ${e} for this session`),this.isServerRunning(e)&&await this.stopServer(e),this.transport=null}async enableServer(e){if(!this.disabledServers.has(e)){this.logger.log(`Server ${e} is not disabled`);return}this.disabledServers.delete(e),this.logger.log(`Enabled server ${e} for this session`);let I=this.getServerConfig(e);I?await this.startServer(e,I):await this.startBuiltInServer(e),this.transport=null}async startBuiltInServer(e){}getServerConfig(e){return this.config.mcpServers[e]}};G();var qKe=dn(PKe(),1);async function LKI(t={}){let e=await fZe();return JZe((0,qKe.default)({},e,t))}async function _Ke(t={}){if(eB())throw new Error("Settings have already been initialized");return LKI(t)}G();async function QV(t,e,I){if(!t||t.length===0)return;let l=!1,n={};for(let c of t)try{let s=await c(e);s&&(l=!0,n={...n,...s})}catch(s){I.error(`Hook execution failed: ${s}`)}return l?n:void 0}G();var AV=class{sessionId;startTime;events=[];_chatMessages=[];_selectedModel;logger;eventCallbacks=[];constructor({sessionId:e,startTime:I,logger:l}={}){this.sessionId=e||ld(),this.startTime=I||new Date,this.logger=l||new oi}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 oi});n._selectedModel=l.data.selectedModel,n.events.push(l);for(let c=1;c<e.length;c++){let s=e[c];n.events.push(s),n.processEventForState(s)}return n}addEvent(e){let I=e.id||ld(),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 oi,this.workingDir=e.workingDirectory||process.cwd(),this.session=e.session||new AV,Nme(this.workingDir).then(I=>{if(I.found)return NSe(I.gitRoot,!0,this.workingDir)}).catch(I=>{this.logger.debug(`Failed to initialize custom instructions cache: ${I}`)})}async*query(e){let I=new Map,l;try{if(this.options.mcpServers&&Object.keys(this.options.mcpServers).length>0)try{l=new fq(this.logger,{mcpServers:this.options.mcpServers},this.options.disabledTools),await l.startServers()}catch(Ne){this.logger.error(`Failed to initialize MCP host: ${Ne}`)}let n={timestamp:Date.now(),cwd:this.workingDir,prompt:e},s=(await QV(this.options.hooks?.userPromptSubmitted,n,this.logger))?.modifiedPrompt??e;this.session.addEvent({type:"user.message",data:{content:s}});let r=new wF().setProblemStatement(s).setAgentModel(this.buildAgentModelString()).setGithubRepoName("copilot-sdk-session").setGithubRepoCommit("copilot-sdk-commit").setGithubRepoReadWrite(!1).setCopilotIntegrationId(this.options.integrationId||"copilot-developer-cli").setCopilotHmacKey(this.options.hmacKey).setCopilotToken(this.options.copilotToken).build();LZe();let o=await _Ke(r),d=o.service?.agent?.model,i=pme(d),h=i.agent,p=i.model?{model:i.model}:void 0,Z=Yoe(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"?fi.powerShell:fi.bash},N=await rMe(u,this.logger),Y=[];if(l)try{Y=await l.getTools(o,this.logger,u.permissions)}catch(Ne){this.logger.error(`Failed to get MCP tools: ${Ne}`)}let y=[...N,...Y],Q=this.applyToolFiltering(y,this.options.allowedTools,this.options.disabledTools),A=await Nme(this.workingDir),E={...(oMe()["sweagent-capi"]?.["claude-sonnet-4"]??GMe()).supports,reasoning:!0},C=await OOe(A.found?A.gitRoot:"",Ffe(),this.workingDir,{},E,u,Q,void 0),te=this.session.chatMessages.slice(0,-1),Fe={role:"user",content:jOe({customAgentPrompt:void 0,problemStatement:s,capabilities:E})},ye=[...te,Fe],He={timestamp:Date.now(),cwd:this.workingDir,source:"new",initialPrompt:e};await QV(this.options.hooks?.sessionStart,He,this.logger);let Qe=Z.getCompletionWithTools(C,ye,Q,{failIfInitialInputsTooLong:!1,processors:{preRequest:[new EH(Fe,this.logger)]},executeToolsInParallel:!1,abortSignal:this.options.abortController?.signal});for await(let Ne of Qe){if(this.options.abortController?.signal.aborted){yield{type:"error",error:new Error("Operation was cancelled")};return}let WI=await this.translateEvent(Ne,I);for(let Ae of WI)Ae.type==="message"&&Ae.role==="assistant"&&this.session.addEvent({type:"assistant.message",data:{messageId:`msg-${Date.now()}`,content:Ae.content}}),yield Ae}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 QV(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 QV(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(p6(e)&&e.message.content)return[{type:"message",content:typeof e.message.content=="string"?e.message.content:"",role:"assistant"}];if(tMe(e)){let l=[];for(let n of e.message.tool_calls){let c=lw(n.function.arguments);I.set(n.id,n.function.name);let s={timestamp:Date.now(),cwd:this.workingDir,toolName:n.function.name,toolArgs:c},r=(await QV(this.options.hooks?.preToolUse,s,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 QV(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},s=(await QV(this.options.hooks?.postToolUse,n,this.logger))?.modifiedResult??e.toolResult;return[{type:"tool_result",toolName:l,result:s,toolCallId:e.toolCallId}]}default:return[]}}};var sPe={};jc(sPe,{CLISession:()=>h1,CLISessionManager:()=>GZe});G();G();G();G();var Os=Sl({id:ZI().uuid(),timestamp:ZI().datetime(),parentId:ZI().uuid().nullable(),ephemeral:BH().optional()}),kKI=Os.extend({type:ic("session.start"),data:Sl({sessionId:ZI(),version:pV(),producer:ZI(),copilotVersion:ZI(),startTime:ZI().datetime(),selectedModel:ZI().optional()})}),fKI=Os.extend({type:ic("session.resume"),data:Sl({resumeTime:ZI().datetime(),eventCount:pV()})}),xKI=Os.extend({type:ic("session.error"),data:Sl({errorType:ZI(),message:ZI(),stack:ZI().optional()})}),BKI=Os.extend({type:ic("session.info"),data:Sl({infoType:ZI(),message:ZI()})}),zKI=Os.extend({type:ic("session.model_change"),data:Sl({previousModel:ZI().optional(),newModel:ZI()})}),UKI=Os.extend({type:ic("session.import_legacy"),data:Sl({legacySession:Sl({sessionId:ZI(),startTime:ZI(),chatMessages:zH(F6()),timeline:zH(F6()),selectedModel:ZI().optional()}),importTime:ZI().datetime(),sourceFile:ZI()})}),SKI=Os.extend({type:ic("user.message"),data:Sl({content:ZI(),attachments:zH(Sl({type:g6(["file","directory"]),path:ZI(),displayName:ZI()})).optional()})}),OKI=Os.extend({type:ic("assistant.turn_start"),data:Sl({turnId:ZI()})}),MKI=Os.extend({type:ic("assistant.message"),data:Sl({messageId:ZI(),content:ZI(),toolRequests:zH(Sl({toolCallId:ZI(),name:ZI(),arguments:IF()})).optional()})}),TKI=Os.extend({type:ic("assistant.turn_end"),data:Sl({turnId:ZI()})}),jKI=Os.extend({type:ic("assistant.usage"),ephemeral:ic(!0),data:Sl({model:ZI().optional(),tokensUsed:pV().optional(),cost:pV().optional(),duration:pV().optional()})}),DKI=Os.extend({type:ic("abort"),data:Sl({reason:ZI()})}),KKI=Os.extend({type:ic("tool.execution_start"),data:Sl({toolCallId:ZI(),toolName:ZI(),arguments:IF()})}),PKI=Os.extend({type:ic("tool.execution_partial_result"),ephemeral:ic(!0),data:Sl({toolCallId:ZI(),toolName:ZI(),partialOutput:ZI()})}),qKI=Os.extend({type:ic("tool.execution_complete"),data:Sl({toolCallId:ZI(),toolName:ZI(),success:BH(),result:Sl({content:ZI()}).optional(),error:Sl({message:ZI(),code:ZI().optional()}).optional()})}),_KI=Os.extend({type:ic("hook.start"),data:Sl({hookInvocationId:ZI(),hookType:ZI(),input:IF()})}),$KI=Os.extend({type:ic("hook.end"),data:Sl({hookInvocationId:ZI(),hookType:ZI(),output:IF(),success:BH(),error:Sl({message:ZI(),stack:ZI().optional()}).optional()})}),ePI=Os.extend({type:ic("system.message"),data:Sl({content:ZI(),role:g6(["system","developer"]),name:ZI().optional(),metadata:Sl({promptVersion:ZI().optional(),variables:Fme(IF()).optional()}).optional()})}),$Ke=yme("type",[kKI,fKI,xKI,BKI,zKI,UKI,SKI,OKI,MKI,TKI,jKI,DKI,KKI,PKI,qKI,_KI,$KI,ePI]);G();import{existsSync as sPI}from"fs";import{appendFile as aPI,mkdir as rPI,readdir as GPI,readFile as oPI,stat as dPI,writeFile as t$l}from"fs/promises";import{homedir as iPI}from"os";import{dirname as bPI,join as Ox}from"path";G();G();var IPI=new Error("timeout while waiting for mutex to become available"),D_l=new Error("mutex already locked"),tPI=new Error("request for lock canceled"),lPI=function(t,e,I,l){function n(c){return c instanceof I?c:new I(function(s){s(c)})}return new(I||(I=Promise))(function(c,s){function a(d){try{o(l.next(d))}catch(i){s(i)}}function r(d){try{o(l.throw(d))}catch(i){s(i)}}function o(d){d.done?c(d.value):n(d.value).then(a,r)}o((l=l.apply(t,e||[])).next())})},rZe=class{constructor(e,I=tPI){this._value=e,this._cancelError=I,this._queue=[],this._weightedWaiters=[]}acquire(e=1,I=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((l,n)=>{let c={resolve:l,reject:n,weight:e,priority:I},s=IPe(this._queue,a=>I<=a.priority);s===-1&&e<=this._value?this._dispatchItem(c):this._queue.splice(s+1,0,c)})}runExclusive(e){return lPI(this,arguments,void 0,function*(I,l=1,n=0){let[c,s]=yield this.acquire(l,n);try{return yield I(c)}finally{s()}})}waitForUnlock(e=1,I=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,I)?Promise.resolve():new Promise(l=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),nPI(this._weightedWaiters[e-1],{resolve:l,priority:I})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){let I=this._value;this._value-=e.weight,e.resolve([I,this._newReleaser(e.weight)])}_newReleaser(e){let I=!1;return()=>{I||(I=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){let I=this._weightedWaiters[e-1];I&&(I.forEach(l=>l.resolve()),this._weightedWaiters[e-1]=[])}else{let e=this._queue[0].priority;for(let I=this._value;I>0;I--){let l=this._weightedWaiters[I-1];if(!l)continue;let n=l.findIndex(c=>c.priority<=e);(n===-1?l:l.splice(0,n)).forEach(c=>c.resolve())}}}_couldLockImmediately(e,I){return(this._queue.length===0||this._queue[0].priority<I)&&e<=this._value}};function nPI(t,e){let I=IPe(t,l=>e.priority<=l.priority);t.splice(I+1,0,e)}function IPe(t,e){for(let I=t.length-1;I>=0;I--)if(e(t[I]))return I;return-1}var cPI=function(t,e,I,l){function n(c){return c instanceof I?c:new I(function(s){s(c)})}return new(I||(I=Promise))(function(c,s){function a(d){try{o(l.next(d))}catch(i){s(i)}}function r(d){try{o(l.throw(d))}catch(i){s(i)}}function o(d){d.done?c(d.value):n(d.value).then(a,r)}o((l=l.apply(t,e||[])).next())})},Kq=class{constructor(e){this._semaphore=new rZe(1,e)}acquire(){return cPI(this,arguments,void 0,function*(e=0){let[,I]=yield this._semaphore.acquire(1,e);return I})}runExclusive(e,I=0){return this._semaphore.runExclusive(()=>e(),1,I)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}},ePe=function(t,e,I,l){function n(c){return c instanceof I?c:new I(function(s){s(c)})}return new(I||(I=Promise))(function(c,s){function a(d){try{o(l.next(d))}catch(i){s(i)}}function r(d){try{o(l.throw(d))}catch(i){s(i)}}function o(d){d.done?c(d.value):n(d.value).then(a,r)}o((l=l.apply(t,e||[])).next())})};function tPe(t,e,I=IPI){return{acquire:(l,n)=>{let c;if(Dq(t)?c=l:(c=void 0,n=l),c!==void 0&&c<=0)throw new Error(`invalid weight ${c}: must be positive`);return new Promise((s,a)=>ePe(this,void 0,void 0,function*(){let r=!1,o=setTimeout(()=>{r=!0,a(I)},e);try{let d=yield Dq(t)?t.acquire(c,n):t.acquire(n);r?(Array.isArray(d)?d[1]:d)():(clearTimeout(o),s(d))}catch(d){r||(clearTimeout(o),a(d))}}))},runExclusive(l,n,c){return ePe(this,void 0,void 0,function*(){let s=()=>{};try{let a=yield this.acquire(n,c);return Array.isArray(a)?(s=a[1],yield l(a[0])):(s=a,yield l())}finally{s()}})},release(l){t.release(l)},cancel(){return t.cancel()},waitForUnlock:(l,n)=>{let c;if(Dq(t)?c=l:(c=void 0,n=l),c!==void 0&&c<=0)throw new Error(`invalid weight ${c}: must be positive`);return new Promise((s,a)=>{let r=setTimeout(()=>a(I),e);(Dq(t)?t.waitForUnlock(c,n):t.waitForUnlock(n)).then(()=>{clearTimeout(r),s()})})},isLocked:()=>t.isLocked(),getValue:()=>t.getValue(),setValue:l=>t.setValue(l)}}function Dq(t){return t.getValue!==void 0}var Pq=class{mutexes=new Map;async runExclusive(e,I,l=5e3){let n=this.mutexes.get(e);n||(n=new Kq,n.refCount=0,this.mutexes.set(e,n));let c=n;try{return c.refCount++,await tPe(n,l).runExclusive(I)}finally{--c.refCount===0&&this.mutexes.delete(e)}}};var lPe=".copilot",nPe=new Pq;async function mPI(t){let e=bPI(t);try{await rPI(e,{recursive:!0,mode:448})}catch{}}var cPe=(t,e)=>{let I=()=>{let r=process.env.XDG_STATE_HOME;return r?Ox(r,lPe):Ox(iPI(),lPe)},l=()=>`${e}-state`,n=r=>{let o=".jsonl",d=l()+(r?"":o);return Ox(I(),d,r?`${r}${o}`:"")};return{load:async r=>{let o=n(r);if(!sPI(o))return[];try{let i=(await nPe.runExclusive(o,()=>oPI(o,"utf8"))).trim().split(`
1381
+ ${c}`;await n.logMCPSetup(e,a),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 qpe={mcpServers:{}},kq=class{constructor(e,I,l){this.logger=e;this.registry=I;this.remoteEnabled=l?.remoteEnabled??!1,this.mcp3pEnabled=l?.mcp3pEnabled??!1,this.blackbirdMetisIndexEnabled=l?.blackbirdMetisIndexEnabled??!1,this.sessionClient=l?.sessionClient,this.mcpEnvConfig=void 0,this.envValueMode=l?.envValueMode??this.registry.envValueMode}remoteEnabled;mcp3pEnabled;blackbirdMetisIndexEnabled;mcpEnvConfig;sessionClient;envValueMode;ReadMcpConfigFromEnv(e){this.mcpEnvConfig=process.env.GITHUB_COPILOT_MCP_JSON,this.mcp3pEnabled=process.env.GITHUB_COPILOT_3P_MCP_ENABLED==="true",this.remoteEnabled=process.env.GITHUB_COPILOT_REMOTE_MCP_ENABLED==="true",this.blackbirdMetisIndexEnabled=process.env.BLACKBIRD_METIS_INDEX_ENABLED==="true";let I=this.validateEnvConfig();return process.env.GITHUB_COPILOT_CLI_MODE==="true"?this.logger.log("CLI mode detected - skipping default MCP servers"):(this.logger.log("Adding default MCP servers to configuration"),this.configureBlackbirdMcp(I,e),this.configureGitHubMcp(I,e),this.configurePlaywrightMcp(I)),I}validateEnvConfig(){if(!this.mcp3pEnabled)return this.logger.log("User-provided MCPs are disabled"),qpe;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"),qpe;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}`),qpe}}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[o1]=c}configureLocalGitHubMcp(e){if(e.mcpServers[o1]){this.logger.log("Using user-provided GitHub MCP server configuration");let I=e.mcpServers[o1]??{};d1(I)&&!I.command&&(e.mcpServers[o1]={...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[o1]=I}}configurePlaywrightMcp(e){if(!e.mcpServers[Kpe]){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:[...cme,"--allowed-origins","localhost;localhost:*;127.0.0.1;127.0.0.1:*"],tools:["*"],isDefaultServer:!0};e.mcpServers[Kpe]=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[uF]=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[uF]=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[uF]=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 d1(e)||Cq(e)||Jq(e)||fx(e)}isValidLocalServerConfig(e){return e.command!==void 0&&e.command.trim()!==""&&Array.isArray(e.args)}isValidRemoteServerConfig(e){return e.url!==void 0&&e.url.trim()!==""}isValidInMemoryServerConfig(e){return e.serverInstance!==void 0&&typeof e.serverInstance=="object"}validateServerConfig(e,I){return this.remoteEnabled&&!this.isValidServerType(I)?(this.logger.error(`Unsupported server type "${I.type}" for server "${e}". Only "Local", "STDIO", "HTTP", "SSE", or "Memory" are supported.`),!1):!this.remoteEnabled&&!d1(I)&&!fx(I)?(this.logger.error(`Unsupported server type "${I.type}" for server "${e}". Only "Local", "STDIO", or "Memory" are supported.`),!1):I.tools?d1(I)&&!this.isValidLocalServerConfig(I)?(this.logger.error(`Invalid local server configuration for "${e}". Please ensure 'command' and 'args' are provided.`),!1):(Cq(I)||Jq(I))&&!this.isValidRemoteServerConfig(I)?(this.logger.error(`Invalid remote server configuration for "${e}". Please ensure 'url' is provided.`),!1):fx(I)&&!this.isValidInMemoryServerConfig(I)?(this.logger.error(`Invalid in-memory server configuration for "${e}". Please ensure 'serverInstance' is provided and is an instance of MCPServer.`),!1):!0:(this.logger.error(`No tools specified for server "${e}". Please provide a list of tools or "*" to include all tools.`),!1)}async processHttpServer(e,I){try{let l=this.resolveHeaders(I.headers,process.env),n={...I,headers:l};await this.registry.startHttpMcpClient(e,n),this.logger.log(`Started MCP client for remote server ${e}`)}catch(l){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${l}`),l}}async processSseServer(e,I){try{let l=this.resolveRemoteServerConfig(I);await this.registry.startSseMcpClient(e,l),this.logger.log(`Started MCP client for remote server ${e}`)}catch(l){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${l}`),l}}resolveRemoteServerConfig(e){return e.url=this.resolveString(e.url,process.env),e.headers=this.resolveHeaders(e.headers,process.env),{...e,url:e.url,headers:e.headers}}async processInMemoryServer(e,I){try{await this.registry.startInMemoryMcpClient(e,I.serverInstance),this.logger.log(`Started in-memory MCP client for ${e}`)}catch(l){throw this.logger.error(`Failed to start in-memory MCP client for ${e}: ${l}`),l}}async processLocalServer(e,I){let l={...I};if(I.command==="python")try{l=await this.convertPythonToPipx(l)}catch(s){this.logger.error(`Failed to handle Python module for ${e}: ${s}`)}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(s){throw this.logger.error(`Failed to start MCP client for ${e}: ${s}`),s}}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 s=l+2;s<I.length;s++)c.push(I[s]);for(let s=0;s<l;s++)c.push(I[s]);return{...e,command:"pipx",args:c}}buildEnvironment(e){let I={};if(e.env)if(this.envValueMode==="direct")for(let[l,n]of Object.entries(e.env))I[l]=this.resolveString(n,process.env);else for(let[l,n]of Object.entries(e.env)){let c=n.trim(),s=c;if(c.includes("$")&&(s=this.resolveString(c,process.env)),s!==c){I[l]=s;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,s)=>{let r=I[n||s];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 s=this.resolveArray([c],I);l[n]=s[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{d1(I)?await this.processLocalServer(e,I):Cq(I)&&this.remoteEnabled?await this.processHttpServer(e,I):Jq(I)&&this.remoteEnabled?await this.processSseServer(e,I):fx(I)&&await this.processInMemoryServer(e,I)}catch(l){e!==uF&&await this.logServerFailure(e,l)}}async logServerFailure(e,I){if(this.sessionClient)try{await this.sessionClient.logMCPSetup(e,`<error>MCP server failed to start: ${I.message} - for the full output, see the verbose logs</error>`)}catch(l){this.logger.error(`Failed to log failure for MCP Server '${e}': '${l}'`)}}};var fq=class{constructor(e,I,l,n="indirect"){this.logger=e;let c;if(typeof I=="string"){if(c=JSON.parse(I),typeof c!="object")throw new Error("Invalid MCP configuration: must be an object");if(c===null||!("mcpServers"in c)||typeof c.mcpServers!="object")throw new Error("Invalid MCP configuration: missing or invalid mcpServers property");this.config=c}else this.config=I;this.disabledServers=new Set(l||[]),this.registry=new Lq(this.logger,void 0,void 0,n),this.processor=new kq(this.logger,this.registry,{mcp3pEnabled:!0,remoteEnabled:!0})}registry;processor;config;startServersPromise=null;transport=null;disabledServers;async startServers(){return this.startServersPromise||(this.startServersPromise=this.processServersWithExtensions()),this.startServersPromise}async injectDefaultServers(e){}async processServersWithExtensions(){await this.injectDefaultServers(this.config);let e;if(this.disabledServers.size>0){let I={};for(let[l,n]of Object.entries(this.config.mcpServers))this.disabledServers.has(l)?this.logger.log(`Skipping disabled MCP server: ${l}`):I[l]=n;e={...this.config,mcpServers:I}}else e=this.config;return this.processor.processServers(e)}async stopServers(){for(let[e,I]of Object.entries(this.registry.transports))try{await I.close()}catch(l){this.logger.error(`Error closing transport for ${e}: ${l}`)}this.startServersPromise=null,this.transport=null}async getTools(e,I,l){await this.startServers(),this.transport=this.transport??new f9(e,I,!0);let n=[];for(let c of Object.keys(this.registry.clients)){let s=await this.transport.loadTools({mcpClient:this.registry.clients[c],clientName:c,tools:this.config.mcpServers[c]?.tools||["*"],filterMapping:this.config.mcpServers[c]?.filterMapping||"hidden_characters"},l);n.push(...s)}return n}getConfig(){return this.config}getClients(){return this.registry.clients}async startServer(e,I){await this.startServers(),this.config.mcpServers[e]=I,await this.processor.processServer(e,I),this.transport=null}async stopServer(e){let I=this.registry.transports[e];if(I)try{await I.close(),delete this.registry.transports[e]}catch(l){this.logger.error(`Error closing transport for ${e}: ${l}`)}this.registry.clients[e]&&delete this.registry.clients[e],this.transport=null}async restartServer(e,I){this.isServerRunning(e)&&await this.stopServer(e),delete this.config.mcpServers[e],await this.startServer(e,I)}isServerRunning(e){return e in this.registry.transports&&e in this.registry.clients}isServerDisabled(e){return this.disabledServers.has(e)}async disableServer(e){if(this.disabledServers.has(e)){this.logger.log(`Server ${e} is already disabled`);return}this.disabledServers.add(e),this.logger.log(`Disabled server ${e} for this session`),this.isServerRunning(e)&&await this.stopServer(e),this.transport=null}async enableServer(e){if(!this.disabledServers.has(e)){this.logger.log(`Server ${e} is not disabled`);return}this.disabledServers.delete(e),this.logger.log(`Enabled server ${e} for this session`);let I=this.getServerConfig(e);I?await this.startServer(e,I):await this.startBuiltInServer(e),this.transport=null}async startBuiltInServer(e){}getServerConfig(e){return this.config.mcpServers[e]}};G();var qKe=dn(PKe(),1);async function LKI(t={}){let e=await fZe();return JZe((0,qKe.default)({},e,t))}async function _Ke(t={}){if(eB())throw new Error("Settings have already been initialized");return LKI(t)}G();async function QV(t,e,I){if(!t||t.length===0)return;let l=!1,n={};for(let c of t)try{let s=await c(e);s&&(l=!0,n={...n,...s})}catch(s){I.error(`Hook execution failed: ${s}`)}return l?n:void 0}G();var AV=class{sessionId;startTime;events=[];_chatMessages=[];_selectedModel;logger;eventCallbacks=[];constructor({sessionId:e,startTime:I,logger:l}={}){this.sessionId=e||ld(),this.startTime=I||new Date,this.logger=l||new oi}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 oi});n._selectedModel=l.data.selectedModel,n.events.push(l);for(let c=1;c<e.length;c++){let s=e[c];n.events.push(s),n.processEventForState(s)}return n}addEvent(e){let I=e.id||ld(),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 oi,this.workingDir=e.workingDirectory||process.cwd(),this.session=e.session||new AV,Nme(this.workingDir).then(I=>{if(I.found)return NSe(I.gitRoot,!0,this.workingDir)}).catch(I=>{this.logger.debug(`Failed to initialize custom instructions cache: ${I}`)})}async*query(e){let I=new Map,l;try{if(this.options.mcpServers&&Object.keys(this.options.mcpServers).length>0)try{l=new fq(this.logger,{mcpServers:this.options.mcpServers},this.options.disabledTools),await l.startServers()}catch(Ne){this.logger.error(`Failed to initialize MCP host: ${Ne}`)}let n={timestamp:Date.now(),cwd:this.workingDir,prompt:e},s=(await QV(this.options.hooks?.userPromptSubmitted,n,this.logger))?.modifiedPrompt??e;this.session.addEvent({type:"user.message",data:{content:s}});let r=new wF().setProblemStatement(s).setAgentModel(this.buildAgentModelString()).setGithubRepoName("copilot-sdk-session").setGithubRepoCommit("copilot-sdk-commit").setGithubRepoReadWrite(!1).setCopilotIntegrationId(this.options.integrationId||"copilot-developer-cli").setCopilotHmacKey(this.options.hmacKey).setCopilotToken(this.options.copilotToken).build();LZe();let o=await _Ke(r),d=o.service?.agent?.model,i=pme(d),h=i.agent,p=i.model?{model:i.model}:void 0,Z=Yoe(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"?fi.powerShell:fi.bash},N=await rMe(u,this.logger),Y=[];if(l)try{Y=await l.getTools(o,this.logger,u.permissions)}catch(Ne){this.logger.error(`Failed to get MCP tools: ${Ne}`)}let y=[...N,...Y],Q=this.applyToolFiltering(y,this.options.allowedTools,this.options.disabledTools),A=await Nme(this.workingDir),E={...(oMe()["sweagent-capi"]?.["claude-sonnet-4"]??GMe()).supports,reasoning:!0},C=await OOe(A.found?A.gitRoot:"",Ffe(),this.workingDir,{},E,u,Q,void 0),te=this.session.chatMessages.slice(0,-1),Fe={role:"user",content:jOe({customAgentPrompt:void 0,problemStatement:s,capabilities:E})},ye=[...te,Fe],He={timestamp:Date.now(),cwd:this.workingDir,source:"new",initialPrompt:e};await QV(this.options.hooks?.sessionStart,He,this.logger);let Qe=Z.getCompletionWithTools(C,ye,Q,{failIfInitialInputsTooLong:!1,processors:{preRequest:[new EH(Fe,this.logger)]},executeToolsInParallel:!1,abortSignal:this.options.abortController?.signal});for await(let Ne of Qe){if(this.options.abortController?.signal.aborted){yield{type:"error",error:new Error("Operation was cancelled")};return}let WI=await this.translateEvent(Ne,I);for(let Ae of WI)Ae.type==="message"&&Ae.role==="assistant"&&this.session.addEvent({type:"assistant.message",data:{messageId:`msg-${Date.now()}`,content:Ae.content}}),yield Ae}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 QV(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 QV(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(p6(e)&&e.message.content)return[{type:"message",content:typeof e.message.content=="string"?e.message.content:"",role:"assistant"}];if(tMe(e)){let l=[];for(let n of e.message.tool_calls){let c=lw(n.function.arguments);I.set(n.id,n.function.name);let s={timestamp:Date.now(),cwd:this.workingDir,toolName:n.function.name,toolArgs:c},r=(await QV(this.options.hooks?.preToolUse,s,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 QV(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},s=(await QV(this.options.hooks?.postToolUse,n,this.logger))?.modifiedResult??e.toolResult;return[{type:"tool_result",toolName:l,result:s,toolCallId:e.toolCallId}]}default:return[]}}};var sPe={};jc(sPe,{CLISession:()=>h1,CLISessionManager:()=>GZe});G();G();G();G();var Os=Sl({id:ZI().uuid(),timestamp:ZI().datetime(),parentId:ZI().uuid().nullable(),ephemeral:BH().optional()}),kKI=Os.extend({type:ic("session.start"),data:Sl({sessionId:ZI(),version:pV(),producer:ZI(),copilotVersion:ZI(),startTime:ZI().datetime(),selectedModel:ZI().optional()})}),fKI=Os.extend({type:ic("session.resume"),data:Sl({resumeTime:ZI().datetime(),eventCount:pV()})}),xKI=Os.extend({type:ic("session.error"),data:Sl({errorType:ZI(),message:ZI(),stack:ZI().optional()})}),BKI=Os.extend({type:ic("session.info"),data:Sl({infoType:ZI(),message:ZI()})}),zKI=Os.extend({type:ic("session.model_change"),data:Sl({previousModel:ZI().optional(),newModel:ZI()})}),UKI=Os.extend({type:ic("session.import_legacy"),data:Sl({legacySession:Sl({sessionId:ZI(),startTime:ZI(),chatMessages:zH(F6()),timeline:zH(F6()),selectedModel:ZI().optional()}),importTime:ZI().datetime(),sourceFile:ZI()})}),SKI=Os.extend({type:ic("user.message"),data:Sl({content:ZI(),attachments:zH(Sl({type:g6(["file","directory"]),path:ZI(),displayName:ZI()})).optional()})}),OKI=Os.extend({type:ic("assistant.turn_start"),data:Sl({turnId:ZI()})}),MKI=Os.extend({type:ic("assistant.message"),data:Sl({messageId:ZI(),content:ZI(),toolRequests:zH(Sl({toolCallId:ZI(),name:ZI(),arguments:IF()})).optional()})}),TKI=Os.extend({type:ic("assistant.turn_end"),data:Sl({turnId:ZI()})}),jKI=Os.extend({type:ic("assistant.usage"),ephemeral:ic(!0),data:Sl({model:ZI().optional(),tokensUsed:pV().optional(),cost:pV().optional(),duration:pV().optional()})}),DKI=Os.extend({type:ic("abort"),data:Sl({reason:ZI()})}),KKI=Os.extend({type:ic("tool.execution_start"),data:Sl({toolCallId:ZI(),toolName:ZI(),arguments:IF()})}),PKI=Os.extend({type:ic("tool.execution_partial_result"),ephemeral:ic(!0),data:Sl({toolCallId:ZI(),toolName:ZI(),partialOutput:ZI()})}),qKI=Os.extend({type:ic("tool.execution_complete"),data:Sl({toolCallId:ZI(),toolName:ZI(),success:BH(),result:Sl({content:ZI()}).optional(),error:Sl({message:ZI(),code:ZI().optional()}).optional()})}),_KI=Os.extend({type:ic("hook.start"),data:Sl({hookInvocationId:ZI(),hookType:ZI(),input:IF()})}),$KI=Os.extend({type:ic("hook.end"),data:Sl({hookInvocationId:ZI(),hookType:ZI(),output:IF(),success:BH(),error:Sl({message:ZI(),stack:ZI().optional()}).optional()})}),ePI=Os.extend({type:ic("system.message"),data:Sl({content:ZI(),role:g6(["system","developer"]),name:ZI().optional(),metadata:Sl({promptVersion:ZI().optional(),variables:Fme(IF()).optional()}).optional()})}),$Ke=yme("type",[kKI,fKI,xKI,BKI,zKI,UKI,SKI,OKI,MKI,TKI,jKI,DKI,KKI,PKI,qKI,_KI,$KI,ePI]);G();import{existsSync as sPI}from"fs";import{appendFile as aPI,mkdir as rPI,readdir as GPI,readFile as oPI,stat as dPI,writeFile as t$l}from"fs/promises";import{homedir as iPI}from"os";import{dirname as bPI,join as Ox}from"path";G();G();var IPI=new Error("timeout while waiting for mutex to become available"),D_l=new Error("mutex already locked"),tPI=new Error("request for lock canceled"),lPI=function(t,e,I,l){function n(c){return c instanceof I?c:new I(function(s){s(c)})}return new(I||(I=Promise))(function(c,s){function a(d){try{o(l.next(d))}catch(i){s(i)}}function r(d){try{o(l.throw(d))}catch(i){s(i)}}function o(d){d.done?c(d.value):n(d.value).then(a,r)}o((l=l.apply(t,e||[])).next())})},rZe=class{constructor(e,I=tPI){this._value=e,this._cancelError=I,this._queue=[],this._weightedWaiters=[]}acquire(e=1,I=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((l,n)=>{let c={resolve:l,reject:n,weight:e,priority:I},s=IPe(this._queue,a=>I<=a.priority);s===-1&&e<=this._value?this._dispatchItem(c):this._queue.splice(s+1,0,c)})}runExclusive(e){return lPI(this,arguments,void 0,function*(I,l=1,n=0){let[c,s]=yield this.acquire(l,n);try{return yield I(c)}finally{s()}})}waitForUnlock(e=1,I=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,I)?Promise.resolve():new Promise(l=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),nPI(this._weightedWaiters[e-1],{resolve:l,priority:I})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){let I=this._value;this._value-=e.weight,e.resolve([I,this._newReleaser(e.weight)])}_newReleaser(e){let I=!1;return()=>{I||(I=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){let I=this._weightedWaiters[e-1];I&&(I.forEach(l=>l.resolve()),this._weightedWaiters[e-1]=[])}else{let e=this._queue[0].priority;for(let I=this._value;I>0;I--){let l=this._weightedWaiters[I-1];if(!l)continue;let n=l.findIndex(c=>c.priority<=e);(n===-1?l:l.splice(0,n)).forEach(c=>c.resolve())}}}_couldLockImmediately(e,I){return(this._queue.length===0||this._queue[0].priority<I)&&e<=this._value}};function nPI(t,e){let I=IPe(t,l=>e.priority<=l.priority);t.splice(I+1,0,e)}function IPe(t,e){for(let I=t.length-1;I>=0;I--)if(e(t[I]))return I;return-1}var cPI=function(t,e,I,l){function n(c){return c instanceof I?c:new I(function(s){s(c)})}return new(I||(I=Promise))(function(c,s){function a(d){try{o(l.next(d))}catch(i){s(i)}}function r(d){try{o(l.throw(d))}catch(i){s(i)}}function o(d){d.done?c(d.value):n(d.value).then(a,r)}o((l=l.apply(t,e||[])).next())})},Kq=class{constructor(e){this._semaphore=new rZe(1,e)}acquire(){return cPI(this,arguments,void 0,function*(e=0){let[,I]=yield this._semaphore.acquire(1,e);return I})}runExclusive(e,I=0){return this._semaphore.runExclusive(()=>e(),1,I)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}},ePe=function(t,e,I,l){function n(c){return c instanceof I?c:new I(function(s){s(c)})}return new(I||(I=Promise))(function(c,s){function a(d){try{o(l.next(d))}catch(i){s(i)}}function r(d){try{o(l.throw(d))}catch(i){s(i)}}function o(d){d.done?c(d.value):n(d.value).then(a,r)}o((l=l.apply(t,e||[])).next())})};function tPe(t,e,I=IPI){return{acquire:(l,n)=>{let c;if(Dq(t)?c=l:(c=void 0,n=l),c!==void 0&&c<=0)throw new Error(`invalid weight ${c}: must be positive`);return new Promise((s,a)=>ePe(this,void 0,void 0,function*(){let r=!1,o=setTimeout(()=>{r=!0,a(I)},e);try{let d=yield Dq(t)?t.acquire(c,n):t.acquire(n);r?(Array.isArray(d)?d[1]:d)():(clearTimeout(o),s(d))}catch(d){r||(clearTimeout(o),a(d))}}))},runExclusive(l,n,c){return ePe(this,void 0,void 0,function*(){let s=()=>{};try{let a=yield this.acquire(n,c);return Array.isArray(a)?(s=a[1],yield l(a[0])):(s=a,yield l())}finally{s()}})},release(l){t.release(l)},cancel(){return t.cancel()},waitForUnlock:(l,n)=>{let c;if(Dq(t)?c=l:(c=void 0,n=l),c!==void 0&&c<=0)throw new Error(`invalid weight ${c}: must be positive`);return new Promise((s,a)=>{let r=setTimeout(()=>a(I),e);(Dq(t)?t.waitForUnlock(c,n):t.waitForUnlock(n)).then(()=>{clearTimeout(r),s()})})},isLocked:()=>t.isLocked(),getValue:()=>t.getValue(),setValue:l=>t.setValue(l)}}function Dq(t){return t.getValue!==void 0}var Pq=class{mutexes=new Map;async runExclusive(e,I,l=5e3){let n=this.mutexes.get(e);n||(n=new Kq,n.refCount=0,this.mutexes.set(e,n));let c=n;try{return c.refCount++,await tPe(n,l).runExclusive(I)}finally{--c.refCount===0&&this.mutexes.delete(e)}}};var lPe=".copilot",nPe=new Pq;async function mPI(t){let e=bPI(t);try{await rPI(e,{recursive:!0,mode:448})}catch{}}var cPe=(t,e)=>{let I=()=>{let r=process.env.XDG_STATE_HOME;return r?Ox(r,lPe):Ox(iPI(),lPe)},l=()=>`${e}-state`,n=r=>{let o=".jsonl",d=l()+(r?"":o);return Ox(I(),d,r?`${r}${o}`:"")};return{load:async r=>{let o=n(r);if(!sPI(o))return[];try{let i=(await nPe.runExclusive(o,()=>oPI(o,"utf8"))).trim().split(`
1382
1382
  `).filter(p=>p.trim()),h=[];for(let p=0;p<i.length;p++)try{let Z=JSON.parse(i[p]),u=t(Z);h.push(u)}catch(Z){throw new Error(`Invalid event at line ${p+1} in ${o}: ${Z}`)}return h}catch(d){throw new Error(`Failed to read JSONL from ${o}: ${d}`)}},append:async(r,o)=>{let d=n(o),i=Array.isArray(r)?r:[r];try{await mPI(d);let h=i.map(p=>JSON.stringify(p)).join(`
1383
1383
  `)+`
1384
1384
  `;await nPe.runExclusive(d,()=>aPI(d,h,{mode:384}))}catch(h){throw new Error(`Failed to append to JSONL file ${d}: ${h}`)}},path:n,directoryFiles:async()=>{let r=Ox(I(),l());try{let d=(await GPI(r)).filter(h=>h.endsWith(".jsonl")),i=await Promise.all(d.map(async h=>{let p=Ox(r,h);try{let Z=await dPI(p);return{file:h,mtime:Z.mtime}}catch{return{file:h,mtime:new Date}}}));return i.sort((h,p)=>p.mtime.getTime()-h.mtime.getTime()),i.map(h=>h.file)}catch{return[]}},home:I,directory:l}};var Gp=cPe($Ke.parse,"session");var h1=class t extends AV{flushTimer=null;flushDebounceMs;isDirty=!1;unflushedEvents=[];constructor({sessionId:e,startTime:I,logger:l,options:n}){super({sessionId:e,startTime:I,logger:l}),this.flushDebounceMs=n?.flushDebounceMs??100}addEvent(e){let I=super.addEvent(e);return this.unflushedEvents.push(I),this.isDirty=!0,this.getEvents().length>1&&this.scheduleDebouncedFlush(),I}scheduleDebouncedFlush(){this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=setTimeout(()=>{this.flush().catch(e=>{this.logger.error(`Debounced flush failed: ${e}`)})},this.flushDebounceMs)}async flush(){if(!(!this.isDirty||this.unflushedEvents.length===0)){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null);try{let e=this.unflushedEvents.filter(I=>!I.ephemeral);await Gp.append(e,this.sessionId),this.unflushedEvents=[],this.isDirty=!1}catch(e){throw this.logger.error(`Failed to flush session ${this.sessionId}: ${e}`),e}}}getFilePath(){return Gp.path(this.sessionId)}static async load(e,I){let l=await Gp.load(e);if(l.length===0)throw new Error(`Session ${e} has no events`);if(l[0].type!=="session.start")throw new Error("First event must be a session.start event");let c=t.fromEvents({events:l,logger:I});return c.isDirty=!1,c.unflushedEvents=[],c}};G();import{unlink as hPI}from"fs/promises";import{join as pPI}from"path";G();var qq=class{sessions;logger;lastAccessedSessionId;constructor({logger:e}={}){this.sessions=new Map,this.logger=e||new oi}async createSession(){let e=new AV({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)}};var GZe=class extends qq{copilotVersion;constructor({logger:e,version:I}){super({logger:e}),this.copilotVersion=I||"unknown"}async createSession(e){let I=e?.sessionId??ld(),l=new Date,n=new h1({sessionId:I,startTime:l,logger:this.logger});return n.addEvent({type:"session.start",data:{sessionId:I,version:1,producer:"copilot-agent",copilotVersion:this.copilotVersion,startTime:l.toISOString(),selectedModel:e?.selectedModel}}),n}async getSession(e){try{return await h1.load(e,this.logger)}catch{return}}async listSessions(){let e=await Gp.directoryFiles();return(await Promise.all(e.map(async l=>{let n=l.replace(".jsonl","");try{let c=await Gp.load(n);if(c.length===0)return null;let s=c[0];return s.type!=="session.start"?null:{sessionId:s.data.sessionId,startTime:new Date(s.data.startTime)}}catch{return null}}))).filter(l=>l!==null)}async getLastSession(){let e=await this.listSessions();if(e.length===0)return;e.sort((l,n)=>n.startTime.getTime()-l.startTime.getTime());let I=e[0].sessionId;return await this.getSession(I)}async deleteSession(e){let I=Gp.path(e.sessionId);await hPI(I)}getSessionsDirectory(){return pPI(Gp.home(),Gp.directory())}};G();G();var oZe=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 ZPI,access as uPI,mkdir as WPI}from"fs/promises";import{constants as NPI}from"fs";import{dirname as YPI}from"path";var dZe=class extends bp{constructor(I,l,n){super(l,n);this.filePath=I;this.writeQueue=VPI(YPI(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}