@github/copilot 0.0.349-11 → 0.0.349-12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.js +1 -1
- package/package.json +2 -2
- package/sdk/index.js +1 -1
- package/sdk/index.js.map +1 -1
package/index.js
CHANGED
|
@@ -1954,7 +1954,7 @@ Pay attention to the following when using it:
|
|
|
1954
1954
|
`}var nYn=tVe.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function rYn(){let t={};for(let e of nYn){let l=tVe.env[e];l!==void 0&&(l.startsWith("()")||(t[e]=l))}return t}var eVe=class{constructor(e){this._abortController=new AbortController,this._readBuffer=new $1e,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new lYn)}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,TUt.default)(this._serverParams.command,(n=this._serverParams.args)!==null&&n!==void 0?n:[],{env:{...rYn(),...this._serverParams.env},stdio:["pipe","pipe",(r=this._serverParams.stderr)!==null&&r!==void 0?r:"inherit"],shell:!1,signal:this._abortController.signal,windowsHide:tVe.platform==="win32"&&IYn(),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=OUt(e);this._process.stdin.write(r)?l():this._process.stdin.once("drain",l)})}};function IYn(){return"type"in tVe}c();c();var lVe=class extends TransformStream{constructor({onError:e,onRetry:l,onComment:n}={}){let r;super({start(I){r=D1e({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 aYn={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Kde=class extends Error{constructor(e,l){super(`Streamable HTTP error: ${l}`),this.code=e}},nVe=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:aYn}async _authThenStart(){var e;if(!this._authProvider)throw new tN("No auth provider");let l;try{l=await eL(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 tN;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 Kde(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 lVe).getReader();for(;;){let{value:h,done:Z}=await p.read();if(Z)break;if(h.id&&(a=h.id,r?.(h.id)),!h.event||h.event==="message")try{let N=Mk.parse(JSON.parse(h.data));I!==void 0&&rde(N)&&(N.id=I),(o=this.onmessage)===null||o===void 0||o.call(this,N)}catch(N){(d=this.onerror)===null||d===void 0||d.call(this,N)}}}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 tN("No auth provider");if(await eL(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new tN("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:t1e(e)?e.id:void 0}).catch(y=>{var Y;return(Y=this.onerror)===null||Y===void 0?void 0:Y.call(this,y)});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=jde(b),await eL(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new tN;return this.send(e)}let y=await b.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${b.status}): ${y}`)}if(b.status===202){$Bt(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(y=>{var Y;return(Y=this.onerror)===null||Y===void 0?void 0:Y.call(this,y)});return}let Z=(Array.isArray(e)?e:[e]).filter(y=>"method"in y&&"id"in y&&y.id!==void 0).length>0,N=b.headers.get("content-type");if(Z)if(N?.includes("text/event-stream"))this._handleSseStream(b.body,{onresumptiontoken:o},!1);else if(N?.includes("application/json")){let y=await b.json(),Y=Array.isArray(y)?y.map(w=>Mk.parse(w)):[Mk.parse(y)];for(let w of Y)(I=this.onmessage)===null||I===void 0||I.call(this,w)}else throw new Kde(-1,`Unexpected content type: ${N}`)}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 Kde(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 rVe=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 e8e(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?.())}},e8e=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 IVe=class{createTransport(e){switch(e.type){case"stdio":{let l=new eVe({command:e.command,args:e.args,env:e.env,stderr:e.stderr?"pipe":void 0,cwd:e.cwd});return l.stderr?.pipe(e.stderr),l}case"http":return new nVe(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"sse":return new K1e(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"memory":return new rVe(e.server);default:throw new Error(`Unsupported transport type: ${e.type}`)}}};c();var qde="blackbird-mcp-server",Y8="github-mcp-server",t8e="playwright",$de=[qde];function V8(t){return t.type===void 0||t.type.toLowerCase()==="local"||t.type.toLowerCase()==="stdio"}function w8(t){return eue(t)||tue(t)}function eue(t){return t.type?.toLowerCase()==="http"}function tue(t){return t.type?.toLowerCase()==="sse"}function lue(t){return t.type?.toLowerCase()==="memory"}var l8e=class extends sYn{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)))}}},aVe=class{constructor(e,l=new M1e,n=new IVe,r="indirect"){this.logger=e;this.clientFactory=l;this.transportFactory=n;this.envValueMode=r}clients={};transports={};async startLocalMcpClient(e,l,n,r,I){this.logger.log(`Starting MCP client for ${e} with command: ${n} and args: ${r}`);let a=new l8e(e,this.logger),s={type:"stdio",command:n,args:r,env:{...l,PATH:process.env.PATH},stderr:a,cwd:I},o=this.transportFactory.createTransport(s);await this.setupAndConnectClient(e,o)}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=qye(r,b.name),Z=`${r}-${b.name}`,N;typeof d=="string"?N=pOe(d):N=pOe(d?.[b.name]??"hidden_characters"),n[`${r}/${b.name}`]={name:Z,namespacedName:`${r}/${b.name}`,title:b.title??b.annotations?.title??b.name,description:b.description??Z,input_schema:b.inputSchema,readOnly:b.annotations?.readOnlyHint,safeForTelemetry:{name:!!(e?.mcpServers[r].isDefaultServer||h),inputsNames:!!e?.mcpServers[r].isDefaultServer},filterMode:N},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(!$de.includes(e)&&r)try{let I=l.map(o=>`- ${o}`).join(`
|
|
1955
1955
|
`),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
|
|
1956
1956
|
|
|
1957
|
-
${I}`;await r.createOrUpdateMCPStartupToolCall({serverName:e,content: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();c();var tL=class t{static resolveString(e,l){return!l||e.length>1e3?e:e.replace(/\$\{([A-Z0-9_]+)(?::-([^}]*))?\}|\$([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})}static resolveArray(e,l){return e?l?e.map(n=>t.resolveString(n,l)):e:[]}static resolveHeaders(e,l){if(!e)return{};if(!l)return e;let n={};for(let[r,I]of Object.entries(e)){let a=t.resolveArray([I],l);n[r]=a[0]}return n}static resolveLocalServerConfig(e,l){let n=t.resolveString(e.command,l),r=t.resolveArray(e.args,l),I;return e.cwd&&(I=t.resolveString(e.cwd,l)),{...e,command:n,args:r,cwd:I}}static resolveRemoteServerConfig(e,l=process.env){let n=t.resolveString(e.url,l),r=t.resolveHeaders(e.headers,l);return{...e,url:n,headers:r}}};var n8e={mcpServers:{}},sVe=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"),n8e;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"),n8e;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}`),n8e}}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[Y8]=I}configureLocalGitHubMcp(e){if(e.mcpServers[Y8]){this.logger.log("Using user-provided GitHub MCP server configuration");let l=e.mcpServers[Y8]??{};V8(l)&&!l.command&&(e.mcpServers[Y8]={...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[Y8]=l}}configurePlaywrightMcp(e){if(!e.mcpServers[t8e]){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:[...WTe,"--allowed-origins","localhost;localhost:*;127.0.0.1;127.0.0.1:*"],tools:["*"],isDefaultServer:!0};e.mcpServers[t8e]=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[qde]=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[qde]=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[qde]=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 V8(e)||eue(e)||tue(e)||lue(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&&!V8(l)&&!lue(l)?(this.logger.error(`Unsupported server type "${l.type}" for server "${e}". Only "Local", "STDIO", or "Memory" are supported.`),!1):l.tools?V8(l)&&!this.isValidLocalServerConfig(l)?(this.logger.error(`Invalid local server configuration for "${e}". Please ensure 'command' and 'args' are provided.`),!1):(eue(l)||tue(l))&&!this.isValidRemoteServerConfig(l)?(this.logger.error(`Invalid remote server configuration for "${e}". Please ensure 'url' is provided.`),!1):lue(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=tL.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=tL.resolveRemoteServerConfig(l,process.env);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}}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=tL.resolveLocalServerConfig(n,r);this.logger.log(`Starting MCP client for ${e} with command: ${I.command} and args: ${I.args}`),I.cwd&&this.logger.log(`cwd: ${I.cwd}`);try{await this.registry.startLocalMcpClient(e,r,I.command,I.args,I.cwd),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]=tL.resolveString(r,process.env);else for(let[n,r]of Object.entries(e.env)){let I=r.trim(),a=I;if(I.includes("$")&&(a=tL.resolveString(I,process.env)),a!==I){l[n]=a;continue}process.env[I]!==void 0&&(l[n]=process.env[I])}return l}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}$de.includes(e)||await this.sessionClient?.createOrUpdateMCPStartupToolCall({serverName:e});try{V8(l)?await this.processLocalServer(e,l):eue(l)&&this.remoteEnabled?await this.processHttpServer(e,l):tue(l)&&this.remoteEnabled?await this.processSseServer(e,l):lue(l)&&await this.processInMemoryServer(e,l)}catch(n){$de.includes(e)||await this.logServerFailure(e,n)}}async logServerFailure(e,l){if(this.sessionClient)try{await this.sessionClient.createOrUpdateMCPStartupToolCall({serverName:e,content:`<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 nue=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 aVe(this.logger,void 0,void 0,r),this.processor=new sVe(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 rse(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 oYn="/login/device/code",iYn="/login/oauth/access_token",UUt="Ov23ctDVkRmgkPke0Mmm",nL="https://github.com",lL=class extends Error{constructor(l,n){super(n);this.status=l;this.message=n;this.name="GitHubApiError"}};function gO(t){let e=new URL(t);return e.hostname.startsWith("api.")||(e.hostname="api."+e.hostname),e.href}async function MUt(t){let e=new URL(oYn,t),l=await fetch(e.href,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({client_id:UUt,scope:"user:email,read:user,repo,workflow"})});if(!l.ok)throw new lL(l.status,`Failed to request device code: ${l.statusText}`);return await l.json()}async function _Ut(t,e){let l=new URL(iYn,t),n=await fetch(l.href,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({client_id:UUt,device_code:e,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})});if(!n.ok)throw new lL(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 Q8(t,e){let l=new URL("/user",gO(t)),n=await fetch(l.href,{headers:{Authorization:`Bearer ${e}`,Accept:"application/json"}});if(!n.ok)throw new lL(n.status,`Failed to fetch user info: ${n.statusText}`);return(await n.json()).login}async function c0(t,e){let l=`
|
|
1957
|
+
${I}`;await r.createOrUpdateMCPStartupToolCall({serverName:e,content: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();c();var tL=class t{static resolveString(e,l){return!l||e.length>1e3?e:e.replace(/\$\{([A-Z0-9_]+)(?::-([^}]*))?\}|\$([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})}static resolveArray(e,l){return e?l?e.map(n=>t.resolveString(n,l)):e:[]}static resolveHeaders(e,l){if(!e)return{};if(!l)return e;let n={};for(let[r,I]of Object.entries(e)){let a=t.resolveArray([I],l);n[r]=a[0]}return n}static resolveLocalServerConfig(e,l){let n=t.resolveString(e.command,l),r=t.resolveArray(e.args,l),I;return e.cwd&&(I=t.resolveString(e.cwd,l)),{...e,command:n,args:r,cwd:I}}static resolveRemoteServerConfig(e,l=process.env){let n=t.resolveString(e.url,l),r=t.resolveHeaders(e.headers,l);return{...e,url:n,headers:r}}};var n8e={mcpServers:{}},sVe=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"),n8e;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"),n8e;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}`),n8e}}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[Y8]=I}configureLocalGitHubMcp(e){if(e.mcpServers[Y8]){this.logger.log("Using user-provided GitHub MCP server configuration");let l=e.mcpServers[Y8]??{};V8(l)&&!l.command&&(e.mcpServers[Y8]={...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[Y8]=l}}configurePlaywrightMcp(e){if(!e.mcpServers[t8e]){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:[...WTe,"--allowed-origins","localhost;localhost:*;127.0.0.1;127.0.0.1:*"],tools:["*"],isDefaultServer:!0};e.mcpServers[t8e]=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[qde]=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[qde]=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[qde]=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 V8(e)||eue(e)||tue(e)||lue(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&&!V8(l)&&!lue(l)?(this.logger.error(`Unsupported server type "${l.type}" for server "${e}". Only "Local", "STDIO", or "Memory" are supported.`),!1):l.tools?V8(l)&&!this.isValidLocalServerConfig(l)?(this.logger.error(`Invalid local server configuration for "${e}". Please ensure 'command' and 'args' are provided.`),!1):(eue(l)||tue(l))&&!this.isValidRemoteServerConfig(l)?(this.logger.error(`Invalid remote server configuration for "${e}". Please ensure 'url' is provided.`),!1):lue(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=tL.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=tL.resolveRemoteServerConfig(l,process.env);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}}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=tL.resolveLocalServerConfig(n,r);this.logger.log(`Starting MCP client for ${e} with command: ${I.command} and args: ${I.args}`),I.cwd&&this.logger.log(`cwd: ${I.cwd}`);try{await this.registry.startLocalMcpClient(e,r,I.command,I.args,I.cwd),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;if(l.length>1e3)throw new Error("Too many arguments provided to Python command");let 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]=tL.resolveString(r,process.env);else for(let[n,r]of Object.entries(e.env)){let I=r.trim(),a=I;if(I.includes("$")&&(a=tL.resolveString(I,process.env)),a!==I){l[n]=a;continue}process.env[I]!==void 0&&(l[n]=process.env[I])}return l}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}$de.includes(e)||await this.sessionClient?.createOrUpdateMCPStartupToolCall({serverName:e});try{V8(l)?await this.processLocalServer(e,l):eue(l)&&this.remoteEnabled?await this.processHttpServer(e,l):tue(l)&&this.remoteEnabled?await this.processSseServer(e,l):lue(l)&&await this.processInMemoryServer(e,l)}catch(n){$de.includes(e)||await this.logServerFailure(e,n)}}async logServerFailure(e,l){if(this.sessionClient)try{await this.sessionClient.createOrUpdateMCPStartupToolCall({serverName:e,content:`<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 nue=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 aVe(this.logger,void 0,void 0,r),this.processor=new sVe(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 rse(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 oYn="/login/device/code",iYn="/login/oauth/access_token",UUt="Ov23ctDVkRmgkPke0Mmm",nL="https://github.com",lL=class extends Error{constructor(l,n){super(n);this.status=l;this.message=n;this.name="GitHubApiError"}};function gO(t){let e=new URL(t);return e.hostname.startsWith("api.")||(e.hostname="api."+e.hostname),e.href}async function MUt(t){let e=new URL(oYn,t),l=await fetch(e.href,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({client_id:UUt,scope:"user:email,read:user,repo,workflow"})});if(!l.ok)throw new lL(l.status,`Failed to request device code: ${l.statusText}`);return await l.json()}async function _Ut(t,e){let l=new URL(iYn,t),n=await fetch(l.href,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({client_id:UUt,device_code:e,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})});if(!n.ok)throw new lL(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 Q8(t,e){let l=new URL("/user",gO(t)),n=await fetch(l.href,{headers:{Authorization:`Bearer ${e}`,Accept:"application/json"}});if(!n.ok)throw new lL(n.status,`Failed to fetch user info: ${n.statusText}`);return(await n.json()).login}async function c0(t,e){let l=`
|
|
1958
1958
|
{
|
|
1959
1959
|
viewer {
|
|
1960
1960
|
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.349-
|
|
4
|
+
"version": "0.0.349-12",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"repository": {
|
|
7
7
|
"type": "git",
|
|
@@ -35,7 +35,7 @@
|
|
|
35
35
|
"worker/**/*"
|
|
36
36
|
],
|
|
37
37
|
"buildMetadata": {
|
|
38
|
-
"gitCommit": "
|
|
38
|
+
"gitCommit": "ce581e0"
|
|
39
39
|
},
|
|
40
40
|
"dependencies": {
|
|
41
41
|
"sharp": "^0.34.3"
|
package/sdk/index.js
CHANGED
|
@@ -1410,7 +1410,7 @@ Pay attention to the following when using it:
|
|
|
1410
1410
|
`}var cIt=h7.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function rIt(){let t={};for(let e of cIt){let I=h7.env[e];I!==void 0&&(I.startsWith("()")||(t[e]=I))}return t}var m7=class{constructor(e){this._abortController=new AbortController,this._readBuffer=new b7,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new nIt)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,I)=>{var l,n,c,r,s;this._process=(0,O7e.default)(this._serverParams.command,(l=this._serverParams.args)!==null&&l!==void 0?l:[],{env:{...rIt(),...this._serverParams.env},stdio:["pipe","pipe",(n=this._serverParams.stderr)!==null&&n!==void 0?n:"inherit"],shell:!1,signal:this._abortController.signal,windowsHide:h7.platform==="win32"&&sIt(),cwd:this._serverParams.cwd}),this._process.on("error",a=>{var G,d;if(a.name==="AbortError"){(G=this.onclose)===null||G===void 0||G.call(this);return}I(a),(d=this.onerror)===null||d===void 0||d.call(this,a)}),this._process.on("spawn",()=>{e()}),this._process.on("close",a=>{var G;this._process=void 0,(G=this.onclose)===null||G===void 0||G.call(this)}),(c=this._process.stdin)===null||c===void 0||c.on("error",a=>{var G;(G=this.onerror)===null||G===void 0||G.call(this,a)}),(r=this._process.stdout)===null||r===void 0||r.on("data",a=>{this._readBuffer.append(a),this.processReadBuffer()}),(s=this._process.stdout)===null||s===void 0||s.on("error",a=>{var G;(G=this.onerror)===null||G===void 0||G.call(this,a)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){var e,I;return this._stderrStream?this._stderrStream:(I=(e=this._process)===null||e===void 0?void 0:e.stderr)!==null&&I!==void 0?I:null}get pid(){var e,I;return(I=(e=this._process)===null||e===void 0?void 0:e.pid)!==null&&I!==void 0?I:null}processReadBuffer(){for(var e,I;;)try{let l=this._readBuffer.readMessage();if(l===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,l)}catch(l){(I=this.onerror)===null||I===void 0||I.call(this,l)}}async close(){this._abortController.abort(),this._process=void 0,this._readBuffer.clear()}send(e){return new Promise(I=>{var l;if(!(!((l=this._process)===null||l===void 0)&&l.stdin))throw new Error("Not connected");let n=S7e(e);this._process.stdin.write(n)?I():this._process.stdin.once("drain",I)})}};function sIt(){return"type"in h7}o();o();var p7=class extends TransformStream{constructor({onError:e,onRetry:I,onComment:l}={}){let n;super({start(c){n=s7({onEvent:r=>{c.enqueue(r)},onError(r){e==="terminate"?c.error(r):typeof e=="function"&&e(r)},onRetry:I,onComment:l})},transform(c){n.feed(c)}})}};var aIt={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},_B=class extends Error{constructor(e,I){super(`Streamable HTTP error: ${I}`),this.code=e}},u7=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:aIt}async _authThenStart(){var e;if(!this._authProvider)throw new pG("No auth provider");let I;try{I=await qV(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(l){throw(e=this.onerror)===null||e===void 0||e.call(this,l),l}if(I!=="AUTHORIZED")throw new pG;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let I={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(I.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(I["mcp-session-id"]=this._sessionId),this._protocolVersion&&(I["mcp-protocol-version"]=this._protocolVersion);let l=this._normalizeHeaders((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...I,...l})}async _startOrAuthSse(e){var I,l,n;let{resumptionToken:c}=e;try{let r=await this._commonHeaders();r.set("Accept","text/event-stream"),c&&r.set("last-event-id",c);let s=await((I=this._fetch)!==null&&I!==void 0?I:fetch)(this._url,{method:"GET",headers:r,signal:(l=this._abortController)===null||l===void 0?void 0:l.signal});if(!s.ok){if(s.status===401&&this._authProvider)return await this._authThenStart();if(s.status===405)return;throw new _B(s.status,`Failed to open SSE stream: ${s.statusText}`)}this._handleSseStream(s.body,e,!0)}catch(r){throw(n=this.onerror)===null||n===void 0||n.call(this,r),r}}_getNextReconnectionDelay(e){let I=this._reconnectionOptions.initialReconnectionDelay,l=this._reconnectionOptions.reconnectionDelayGrowFactor,n=this._reconnectionOptions.maxReconnectionDelay;return Math.min(I*Math.pow(l,e),n)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,I=0){var l;let n=this._reconnectionOptions.maxRetries;if(n>0&&I>=n){(l=this.onerror)===null||l===void 0||l.call(this,new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let c=this._getNextReconnectionDelay(I);setTimeout(()=>{this._startOrAuthSse(e).catch(r=>{var s;(s=this.onerror)===null||s===void 0||s.call(this,new Error(`Failed to reconnect SSE stream: ${r instanceof Error?r.message:String(r)}`)),this._scheduleReconnection(e,I+1)})},c)}_handleSseStream(e,I,l){if(!e)return;let{onresumptiontoken:n,replayMessageId:c}=I,r;(async()=>{var a,G,d,i;try{let b=e.pipeThrough(new TextDecoderStream).pipeThrough(new p7).getReader();for(;;){let{value:m,done:h}=await b.read();if(h)break;if(m.id&&(r=m.id,n?.(m.id)),!m.event||m.event==="message")try{let p=UV.parse(JSON.parse(m.data));c!==void 0&&cB(p)&&(p.id=c),(a=this.onmessage)===null||a===void 0||a.call(this,p)}catch(p){(G=this.onerror)===null||G===void 0||G.call(this,p)}}}catch(b){if((d=this.onerror)===null||d===void 0||d.call(this,new Error(`SSE stream disconnected: ${b}`)),l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:r,onresumptiontoken:n,replayMessageId:c},0)}catch(m){(i=this.onerror)===null||i===void 0||i.call(this,new Error(`Failed to reconnect: ${m instanceof Error?m.message:String(m)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new pG("No auth provider");if(await qV(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new pG("Failed to authorize")}async close(){var e,I;(e=this._abortController)===null||e===void 0||e.abort(),(I=this.onclose)===null||I===void 0||I.call(this)}async send(e,I){var l,n,c,r;try{let{resumptionToken:s,onresumptiontoken:a}=I||{};if(s){this._startOrAuthSse({resumptionToken:s,replayMessageId:h8(e)?e.id:void 0}).catch(Z=>{var W;return(W=this.onerror)===null||W===void 0?void 0:W.call(this,Z)});return}let G=await this._commonHeaders();G.set("content-type","application/json"),G.set("accept","application/json, text/event-stream");let d={...this._requestInit,method:"POST",headers:G,body:JSON.stringify(e),signal:(l=this._abortController)===null||l===void 0?void 0:l.signal},i=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._url,d),b=i.headers.get("mcp-session-id");if(b&&(this._sessionId=b),!i.ok){if(i.status===401&&this._authProvider){if(this._resourceMetadataUrl=qB(i),await qV(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new pG;return this.send(e)}let Z=await i.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${i.status}): ${Z}`)}if(i.status===202){e6e(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(Z=>{var W;return(W=this.onerror)===null||W===void 0?void 0:W.call(this,Z)});return}let h=(Array.isArray(e)?e:[e]).filter(Z=>"method"in Z&&"id"in Z&&Z.id!==void 0).length>0,p=i.headers.get("content-type");if(h)if(p?.includes("text/event-stream"))this._handleSseStream(i.body,{onresumptiontoken:a},!1);else if(p?.includes("application/json")){let Z=await i.json(),W=Array.isArray(Z)?Z.map(Y=>UV.parse(Y)):[UV.parse(Z)];for(let Y of W)(c=this.onmessage)===null||c===void 0||c.call(this,Y)}else throw new _B(-1,`Unexpected content type: ${p}`)}catch(s){throw(r=this.onerror)===null||r===void 0||r.call(this,s),s}}get sessionId(){return this._sessionId}async terminateSession(){var e,I,l;if(this._sessionId)try{let n=await this._commonHeaders(),c={...this._requestInit,method:"DELETE",headers:n,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},r=await((I=this._fetch)!==null&&I!==void 0?I:fetch)(this._url,c);if(!r.ok&&r.status!==405)throw new _B(r.status,`Failed to terminate session: ${r.statusText}`);this._sessionId=void 0}catch(n){throw(l=this.onerror)===null||l===void 0||l.call(this,n),n}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}};o();var Z7=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 QWe(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?.())}},QWe=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 W7=class{createTransport(e){switch(e.type){case"stdio":{let I=new m7({command:e.command,args:e.args,env:e.env,stderr:e.stderr?"pipe":void 0,cwd:e.cwd});return I.stderr?.pipe(e.stderr),I}case"http":return new u7(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"sse":return new d7(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"memory":return new Z7(e.server);default:throw new Error(`Unsupported transport type: ${e.type}`)}}};o();var $B="blackbird-mcp-server",lv="github-mcp-server",wWe="playwright",ez=[$B];function nv(t){return t.type===void 0||t.type.toLowerCase()==="local"||t.type.toLowerCase()==="stdio"}function N7(t){return t.type?.toLowerCase()==="http"}function Y7(t){return t.type?.toLowerCase()==="sse"}function Iz(t){return t.type?.toLowerCase()==="memory"}var XWe=class extends oIt{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)))}}},V7=class{constructor(e,I=new c7,l=new W7,n="indirect"){this.logger=e;this.clientFactory=I;this.transportFactory=l;this.envValueMode=n}clients={};transports={};async startLocalMcpClient(e,I,l,n,c){this.logger.log(`Starting MCP client for ${e} with command: ${l} and args: ${n}`);let r=new XWe(e,this.logger),s={type:"stdio",command:l,args:n,env:{...I,PATH:process.env.PATH},stderr:r,cwd:c},a=this.transportFactory.createTransport(s);await this.setupAndConnectClient(e,a)}async startHttpMcpClient(e,I){this.logger.log(`Starting remote MCP client for ${e} with url: ${I.url}`);let l={type:"http",url:I.url,headers:I.headers},n=this.transportFactory.createTransport(l);await this.setupAndConnectClient(e,n)}async startSseMcpClient(e,I){this.logger.log(`Starting remote MCP client for ${e} with url: ${I.url}`);let l={type:"sse",url:I.url,headers:I.headers},n=this.transportFactory.createTransport(l);await this.setupAndConnectClient(e,n)}async startInMemoryMcpClient(e,I){this.logger.log(`Starting in-memory MCP client for ${e}`);let l={type:"memory",server:I},n=this.transportFactory.createTransport(l);await this.setupAndConnectClient(e,n)}async setupAndConnectClient(e,I){this.transports[e]=I,I.onclose=()=>{this.logger.log(`MCP transport for ${e} closed`),delete this.transports[e]},this.logger.log(`Creating MCP client for ${e}...`);let l=this.clientFactory.createClient({name:"github-copilot-developer",version:"1.0.0"},{capabilities:{experimental:void 0,roots:void 0,sampling:void 0}}),n=Date.now();this.logger.log(`Connecting MCP client for ${e}...`),await l.connect(I),l.onclose=()=>{this.logger.log(`MCP client for ${e} closed`),delete this.clients[e]},l.onerror=c=>{this.logger.error(`MCP client for ${e} errored ${c}`)},this.logger.log(`MCP client for ${e} connected, took ${Date.now()-n}ms`),this.clients[e]=l}async getTools(e,I){let l={};for(let[n,c]of Object.entries(this.clients)){let r=[];try{this.logger.log(`Fetching tools from client: ${n}`);let s=await c.listTools(),a=e?.mcpServers[n].tools,G=e?.mcpServers[n].filterMapping;for(let i of s.tools){if(i.name==="get_copilot_space")continue;if(!(a?.includes("*")||a?.includes(i.name))){this.logger.log(`Tool ${i.name} is not in the allowed list for client: ${n}`);continue}let m=$q(n,i.name),h=`${n}-${i.name}`,p;typeof G=="string"?p=khe(G):p=khe(G?.[i.name]??"hidden_characters"),l[`${n}/${i.name}`]={name:h,namespacedName:`${n}/${i.name}`,title:i.title??i.annotations?.title??i.name,description:i.description??h,input_schema:i.inputSchema,readOnly:i.annotations?.readOnlyHint,safeForTelemetry:{name:!!(e?.mcpServers[n].isDefaultServer||m),inputsNames:!!e?.mcpServers[n].isDefaultServer},filterMode:p},r.push(i.name),this.logger.log(`Tool ${i.name} added to tools list for client: ${n}`)}this.logger.log(`Successfully retrieved ${r.length} tools from client: ${n}`);let d=c.getServerVersion();await this.logServerSuccessWithTools(n,r,d,I)}catch(s){this.logger.error(`Failed to get tools from client: ${n} ${s}`)}}return this.logger.log(`All tools retrieved: ${JSON.stringify(l,null,2)}`),l}async logServerSuccessWithTools(e,I,l,n){if(!ez.includes(e)&&n)try{let c=I.map(a=>`- ${a}`).join(`
|
|
1411
1411
|
`),s=`MCP server started successfully${l?` (version ${l.version})`:""} with ${I.length} ${I.length===1?"tool":"tools"} - for the full output, see the verbose logs
|
|
1412
1412
|
|
|
1413
|
-
${c}`;await n.createOrUpdateMCPStartupToolCall({serverName:e,content:s}),this.logger.log(`Updated session log for ${e} with ${I.length} tools`)}catch(c){this.logger.error(`Failed to update session log for ${e}: ${c}`)}}};o();o();var _V=class t{static resolveString(e,I){return!I||e.length>1e3?e:e.replace(/\$\{([A-Z0-9_]+)(?::-([^}]*))?\}|\$([A-Z0-9_]+)(?![A-Z0-9_])/g,(l,n,c,r)=>{let a=I[n||r];return a!==void 0?a:c!==void 0?c:l})}static resolveArray(e,I){return e?I?e.map(l=>t.resolveString(l,I)):e:[]}static resolveHeaders(e,I){if(!e)return{};if(!I)return e;let l={};for(let[n,c]of Object.entries(e)){let r=t.resolveArray([c],I);l[n]=r[0]}return l}static resolveLocalServerConfig(e,I){let l=t.resolveString(e.command,I),n=t.resolveArray(e.args,I),c;return e.cwd&&(c=t.resolveString(e.cwd,I)),{...e,command:l,args:n,cwd:c}}static resolveRemoteServerConfig(e,I=process.env){let l=t.resolveString(e.url,I),n=t.resolveHeaders(e.headers,I);return{...e,url:l,headers:n}}};var EWe={mcpServers:{}},R7=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"),EWe;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"),EWe;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}`),EWe}}configureGitHubMcp(e,I){this.remoteEnabled?this.configureRemoteGitHubMcp(e,I):this.configureLocalGitHubMcp(e)}configureRemoteGitHubMcp(e,I){this.logger.log("Using default remote GitHub MCP server configuration");let l="repos,issues,users,pull_requests,code_security,secret_protection,actions,web_search";process.env.COPILOT_MCP_COPILOT_SPACES_ENABLED==="true"&&(this.logger.log("Enabling Copilot Spaces in GitHub MCP server configuration"),l=l+",copilot_spaces");let n={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":l,"X-MCP-Host":"github-coding-agent","X-Initiator":"agent"};I&&I.api?.copilot?.integrationId&&(n["Copilot-Integration-Id"]=I.api.copilot.integrationId),process.env.GITHUB_COPILOT_INTERACTION_ID&&(n["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let c={type:"http",url:this.getCapiMcpUrl(),headers:n,tools:["*"],isDefaultServer:!0,filterMapping:{get_issue:"markdown",get_issue_comments:"markdown",get_pull_request:"markdown",get_pull_request_comments:"markdown",get_pull_request_reviews:"markdown"}};e.mcpServers[lv]=c}configureLocalGitHubMcp(e){if(e.mcpServers[lv]){this.logger.log("Using user-provided GitHub MCP server configuration");let I=e.mcpServers[lv]??{};nv(I)&&!I.command&&(e.mcpServers[lv]={...I,command:"./copilot-developer-action-main/github-mcp-server/github-mcp-server",isDefaultServer:!0},this.logger.log("Added default command to user-provided GitHub MCP server configuration"))}else{this.logger.log("Using default local GitHub MCP server configuration");let I={command:"./copilot-developer-action-main/github-mcp-server/github-mcp-server",args:["stdio","--read-only"],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",GITHUB_HOST:"GITHUB_SERVER_URL"},tools:["*"],isDefaultServer:!0};e.mcpServers[lv]=I}}configurePlaywrightMcp(e){if(!e.mcpServers[wWe]){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:[...Spe,"--allowed-origins","localhost;localhost:*;127.0.0.1;127.0.0.1:*"],tools:["*"],isDefaultServer:!0};e.mcpServers[wWe]=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[$B]=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[$B]=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[$B]=n}getCapiMcpUrl(){return process.env.COPILOT_API_URL?new URL("/mcp/readonly",process.env.COPILOT_API_URL).toString():"https://api.githubcopilot.com/mcp/readonly"}isValidServerType(e){return nv(e)||N7(e)||Y7(e)||Iz(e)}isValidLocalServerConfig(e){return e.command!==void 0&&e.command.trim()!==""&&Array.isArray(e.args)}isValidRemoteServerConfig(e){return e.url!==void 0&&e.url.trim()!==""}isValidInMemoryServerConfig(e){return e.serverInstance!==void 0&&typeof e.serverInstance=="object"}validateServerConfig(e,I){return this.remoteEnabled&&!this.isValidServerType(I)?(this.logger.error(`Unsupported server type "${I.type}" for server "${e}". Only "Local", "STDIO", "HTTP", "SSE", or "Memory" are supported.`),!1):!this.remoteEnabled&&!nv(I)&&!Iz(I)?(this.logger.error(`Unsupported server type "${I.type}" for server "${e}". Only "Local", "STDIO", or "Memory" are supported.`),!1):I.tools?nv(I)&&!this.isValidLocalServerConfig(I)?(this.logger.error(`Invalid local server configuration for "${e}". Please ensure 'command' and 'args' are provided.`),!1):(N7(I)||Y7(I))&&!this.isValidRemoteServerConfig(I)?(this.logger.error(`Invalid remote server configuration for "${e}". Please ensure 'url' is provided.`),!1):Iz(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=_V.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=_V.resolveRemoteServerConfig(I,process.env);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}}async processInMemoryServer(e,I){try{await this.registry.startInMemoryMcpClient(e,I.serverInstance),this.logger.log(`Started in-memory MCP client for ${e}`)}catch(l){throw this.logger.error(`Failed to start in-memory MCP client for ${e}: ${l}`),l}}async processLocalServer(e,I){let l={...I};if(I.command==="python")try{l=await this.convertPythonToPipx(l)}catch(r){this.logger.error(`Failed to handle Python module for ${e}: ${r}`)}let n=this.buildEnvironment(l),c=_V.resolveLocalServerConfig(l,n);this.logger.log(`Starting MCP client for ${e} with command: ${c.command} and args: ${c.args}`),c.cwd&&this.logger.log(`cwd: ${c.cwd}`);try{await this.registry.startLocalMcpClient(e,n,c.command,c.args,c.cwd),this.logger.log(`Started MCP client for ${e}`)}catch(r){throw this.logger.error(`Failed to start MCP client for ${e}: ${r}`),r}}convertPythonToPipx(e){if(!e||!e.args||e.args.length===0)return e;let I=e.args,l=I.indexOf("-m");if(l===-1||l===I.length-1)throw new Error("Python command with -m flag must specify a module");let n=I[l+1];this.logger.log(`Converting Python module: ${n} to pipx command`);let c=["run",n];for(let r=l+2;r<I.length;r++)c.push(I[r]);for(let r=0;r<l;r++)c.push(I[r]);return{...e,command:"pipx",args:c}}buildEnvironment(e){let I={};if(e.env)if(this.envValueMode==="direct")for(let[l,n]of Object.entries(e.env))I[l]=_V.resolveString(n,process.env);else for(let[l,n]of Object.entries(e.env)){let c=n.trim(),r=c;if(c.includes("$")&&(r=_V.resolveString(c,process.env)),r!==c){I[l]=r;continue}process.env[c]!==void 0&&(I[l]=process.env[c])}return I}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}ez.includes(e)||await this.sessionClient?.createOrUpdateMCPStartupToolCall({serverName:e});try{nv(I)?await this.processLocalServer(e,I):N7(I)&&this.remoteEnabled?await this.processHttpServer(e,I):Y7(I)&&this.remoteEnabled?await this.processSseServer(e,I):Iz(I)&&await this.processInMemoryServer(e,I)}catch(l){ez.includes(e)||await this.logServerFailure(e,l)}}async logServerFailure(e,I){if(this.sessionClient)try{await this.sessionClient.createOrUpdateMCPStartupToolCall({serverName:e,content:`<error>MCP server failed to start: ${I.message} - for the full output, see the verbose logs</error>`})}catch(l){this.logger.error(`Failed to log failure for MCP Server '${e}': '${l}'`)}}};var y7=class{constructor(e,I,l,n="indirect"){this.logger=e;let c;if(typeof I=="string"){if(c=JSON.parse(I),typeof c!="object")throw new Error("Invalid MCP configuration: must be an object");if(c===null||!("mcpServers"in c)||typeof c.mcpServers!="object")throw new Error("Invalid MCP configuration: missing or invalid mcpServers property");this.config=c}else this.config=I;this.disabledServers=new Set(l||[]),this.registry=new V7(this.logger,void 0,void 0,n),this.processor=new R7(this.logger,this.registry,{mcp3pEnabled:!0,remoteEnabled:!0})}registry;processor;config;startServersPromise=null;transport=null;disabledServers;async startServers(){return this.startServersPromise||(this.startServersPromise=this.processServersWithExtensions()),this.startServersPromise}async injectDefaultServers(e){}async processServersWithExtensions(){await this.injectDefaultServers(this.config);let e;if(this.disabledServers.size>0){let I={};for(let[l,n]of Object.entries(this.config.mcpServers))this.disabledServers.has(l)?this.logger.log(`Skipping disabled MCP server: ${l}`):I[l]=n;e={...this.config,mcpServers:I}}else e=this.config;return this.processor.processServers(e)}async stopServers(){for(let[e,I]of Object.entries(this.registry.transports))try{await I.close()}catch(l){this.logger.error(`Error closing transport for ${e}: ${l}`)}this.startServersPromise=null,this.transport=null}async getTools(e,I,l){await this.startServers(),this.transport=this.transport??new Kx(e,I,!0);let n=[];for(let c of Object.keys(this.registry.clients)){let r=await this.transport.loadTools({mcpClient:this.registry.clients[c],clientName:c,tools:this.config.mcpServers[c]?.tools||["*"],filterMapping:this.config.mcpServers[c]?.filterMapping||"hidden_characters"},l);n.push(...r)}return n}getConfig(){return this.config}getClients(){return this.registry.clients}async startServer(e,I){await this.startServers(),this.config.mcpServers[e]=I,await this.processor.processServer(e,I),this.transport=null}async stopServer(e){let I=this.registry.transports[e];if(I)try{await I.close(),delete this.registry.transports[e]}catch(l){this.logger.error(`Error closing transport for ${e}: ${l}`)}this.registry.clients[e]&&delete this.registry.clients[e],this.transport=null}async restartServer(e,I){this.isServerRunning(e)&&await this.stopServer(e),delete this.config.mcpServers[e],await this.startServer(e,I)}isServerRunning(e){return e in this.registry.transports&&e in this.registry.clients}isServerDisabled(e){return this.disabledServers.has(e)}async disableServer(e){if(this.disabledServers.has(e)){this.logger.log(`Server ${e} is already disabled`);return}this.disabledServers.add(e),this.logger.log(`Disabled server ${e} for this session`),this.isServerRunning(e)&&await this.stopServer(e),this.transport=null}async enableServer(e){if(!this.disabledServers.has(e)){this.logger.log(`Server ${e} is not disabled`);return}this.disabledServers.delete(e),this.logger.log(`Enabled server ${e} for this session`);let I=this.getServerConfig(e);I?await this.startServer(e,I):await this.startBuiltInServer(e),this.transport=null}async startBuiltInServer(e){}getServerConfig(e){return this.config.mcpServers[e]}};o();var N_e=Ll(W_e(),1);async function tlt(t={}){let e=await LNe();return vNe((0,N_e.default)({},e,t))}async function Y_e(t={}){if(Vz())throw new Error("Settings have already been initialized");return tlt(t)}o();async function $V(t,e,I){if(!t||t.length===0)return;let l=!1,n={};for(let c of t)try{let r=await c(e);r&&(l=!0,n={...n,...r})}catch(r){I.error(`Hook execution failed: ${r}`)}return l?n:void 0}o();o();import{promises as llt}from"fs";import V_e from"path";var nlt=3*1024*1024;function R_e(t){let e=V_e.extname(t).toLowerCase();return[".png",".jpg",".jpeg",".gif",".webp"].includes(e)}function clt(t){switch(V_e.extname(t).toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";default:return null}}async function rlt(t,e){e.debug(`Processing local image file: ${t}`);let I=await llt.readFile(t),l=clt(t);if(!l)throw new Error(`Unsupported image format: ${t}`);let n=new Dx,c=await qq(e,n,nlt,Mx,l,I);if(!c)throw new Error(`Image too large or couldn't be processed: ${t}`);let r=c.toString("base64");return`data:${l};base64,${r}`}async function slt(t,e){let I=es();try{let l=await Jce({command:"view",path:t,view_range:void 0},{properties:{command:"view",resolvedPathAgainstCwd:"false",options:"{}",inputs:"[]"},metrics:{responseTokenLimit:void 0,resultLength:0,resultForLlmLength:0},restrictedProperties:{}},e);return{id:I,name:"view",arguments:{path:t},result:l.textResultForLlm||""}}catch(l){return{id:I,name:"view",arguments:{path:t},result:`Error reading ${t}: ${l}`}}}async function y_e(t,e){let I=[],l=t.filter(c=>!R_e(c.path));if(l.length===0)return I;let n=[];for(let c of l)try{let r=await slt(c.path,e);n.push(r)}catch{}if(n.length>0){let c=n.map(r=>({id:r.id,type:"function",function:{name:r.name,arguments:JSON.stringify(r.arguments)}}));I.push({role:"assistant",content:"I need to read the content of those paths to answer this request.",tool_calls:c}),I.push(...n.map(r=>({role:"tool",tool_call_id:r.id,content:r.result})))}return I}async function g_e(t,e){let I=t.filter(n=>R_e(n.path));return(await Promise.all(I.map(async n=>{try{return{type:"image_url",image_url:{url:await rlt(n.path,e)}}}catch(c){e.error(`Failed to process image ${n.path}: ${c instanceof Error?c.message:String(c)}`);return}}))).filter(n=>n!==void 0)}var gp=class{sessionId;startTime;modifiedTime;events=[];_chatMessages=[];_selectedModel;logger;eventCallbacks=[];eventProcessingQueue=Promise.resolve();constructor({sessionId:e,startTime:I,modifiedTime:l,logger:n}={}){this.sessionId=e||es(),this.startTime=I||new Date,this.modifiedTime=l||this.startTime,this.logger=n||new Ri}get messageCount(){let e=this.events.find(l=>l.type==="session.import_legacy"),I=0;return e&&(I=(e.data.legacySession?.chatMessages||[]).filter(c=>c.role==="user"||c.role==="assistant").length),this.logger.debug(`Imported message count: ${I}`),this.events.filter(l=>l.type==="user.message"||l.type==="assistant.message").length+I}get summary(){let e=this.events.find(c=>c.type==="session.import_legacy"||c.type==="user.message"),I;if(e?.type==="session.import_legacy"){let c=e.data.legacySession.chatMessages.find(r=>r.role==="user");c?.content&&(typeof c.content=="string"?I=c.content:I=c.content.find(r=>r.type==="text")?.text)}else e?.type==="user.message"&&(I=e.data.content);if(!I)return;let l=I.lastIndexOf("<reminder>");l!==-1&&(I=I.substring(0,l).trim());let n=I.replace(/\s+/g," ").trim();return n.length>75&&(n=n.substring(0,55).trim()+"..."),n=n.split("").filter(c=>{let r=c.charCodeAt(0);return r>=32&&r!==127}).join(""),n}static async fromEvents({events:e,logger:I}){if(e.length===0)throw new Error("Cannot create session from empty events array");let l=e[0];if(l.type!=="session.start")throw new Error("First event must be session.start");let n=new this({sessionId:l.data.sessionId,startTime:new Date(l.data.startTime),logger:I||new Ri});n._selectedModel=l.data.selectedModel,n.events.push(l);for(let c=1;c<e.length;c++){let r=e[c];n.events.push(r),await n.processEventForState(r)}return n}addEvent(e){let I=e.id||es(),l=e.timestamp||new Date().toISOString(),n=e.parentId!==void 0?e.parentId:this.getLastEventId(),c={...e,id:I,timestamp:l,parentId:n};return this.events.push(c),this.enqueueEventProcessing(()=>this.processEventForState(c).catch(r=>{this.logger.error(`Error processing event ${c.type} (${c.id}): ${r instanceof Error?r.message:String(r)}`)})).catch(r=>{this.logger.error(`Error processing event queue ${r instanceof Error?r.message:String(r)}`)}),this.notifyEventCallbacks(c),c}getEvents(){return this.events}onEvent(e){return this.eventCallbacks.push(e),()=>{let I=this.eventCallbacks.indexOf(e);I>-1&&this.eventCallbacks.splice(I,1)}}async getChatMessages(){return this.enqueueEventProcessing(()=>this._chatMessages)}async getChatContextMessages(){return(await this.getChatMessages()).filter(I=>I.role!=="system")}async getSystemContextMessages(){return(await this.getChatMessages()).filter(I=>I.role==="system")}async getSelectedModel(){return this.enqueueEventProcessing(()=>this._selectedModel)}setSelectedModel(e){let I=this._selectedModel;this._selectedModel=e,this.addEvent({type:"session.model_change",data:{previousModel:I,newModel:e}})}getLastEventId(){return this.events.length===0?null:this.events[this.events.length-1].id}enqueueEventProcessing(e){let I=this.eventProcessingQueue.then(()=>e());return this.eventProcessingQueue=I,I}async processEventForState(e){switch(e.type){case"session.start":e.data.selectedModel&&(this._selectedModel=e.data.selectedModel);break;case"session.model_change":this._selectedModel=e.data.newModel;break;case"user.message":{let I=[],l=[];if(e.data.attachments&&e.data.attachments.length>0){let n=await g_e(e.data.attachments,this.logger);I.push(...n);let c=await y_e(e.data.attachments,this.logger);l.push(...c)}I.length>0?this._chatMessages.push({role:"user",content:[{type:"text",text:e.data.content},...I]}):this._chatMessages.push({role:"user",content:e.data.content}),l.length>0&&this._chatMessages.push(...l);break}case"assistant.message":{if(e.ephemeral)break;let I={role:"assistant",content:e.data.content||null};e.data.toolRequests&&e.data.toolRequests.length>0&&(I.tool_calls=e.data.toolRequests.map(l=>({id:l.toolCallId,type:"function",function:{name:l.name,arguments:typeof l.arguments=="string"?l.arguments:JSON.stringify(l.arguments)}}))),this._chatMessages.push(I);break}case"tool.execution_complete":{e.data.isUserRequested||this._chatMessages.push({role:"tool",tool_call_id:e.data.toolCallId,content:e.data.success?e.data.result?.content||"":e.data.error?.message||"Tool execution failed"});break}case"system.message":this._chatMessages.push({role:e.data.role,content:e.data.content,...e.data.name&&{name:e.data.name}});break;case"session.import_legacy":this._chatMessages=[...e.data.legacySession.chatMessages],e.data.legacySession.selectedModel&&(this._selectedModel=e.data.legacySession.selectedModel);break;case"abort":case"session.resume":this._chatMessages=alt(this._chatMessages,this.logger);break;case"session.error":case"session.info":case"assistant.turn_start":case"assistant.turn_end":case"assistant.usage":case"tool.user_requested":case"tool.execution_start":case"tool.execution_partial_result":case"hook.start":case"hook.end":break;default:{let I=e;this.logger.error(`Unknown event type: ${I.type}`);break}}}notifyEventCallbacks(e){for(let I of this.eventCallbacks)try{I(e)}catch(l){this.logger.error(`Error in event callback: ${l instanceof Error?l.message:String(l)}`)}}};function alt(t,e){if(t.length===0)return t;let I=[],l=new Set,n=!1;for(let s=t.length-1;s>=0;s--){let a=t[s];if(a.role==="assistant"&&(n=!0),a.role==="assistant"&&"tool_calls"in a&&a.tool_calls&&a.tool_calls.length>0)for(let G of a.tool_calls)l.has(G.id)||I.push(G.id);else{if(n)break;a.role==="tool"&&a.tool_call_id&&l.add(a.tool_call_id)}}if(I.length===0)return t;let c="The execution of this tool, or a previous tool was interrupted.";e.info(`Completing ${I.length} orphaned tool calls.`);let r=I.map(s=>({role:"tool",tool_call_id:s,content:c}));return[...t,...r]}var v7=class{static name="Copilot";static description="Base Copilot Agent";options;logger;workingDir;session;constructor(e){this.options=e,this.logger=e.logger||new Ri,this.workingDir=e.workingDirectory||process.cwd(),this.session=e.session||new gp,Iue(this.workingDir).then(I=>{if(I.found)return DDe(I.gitRoot,!0,this.workingDir)}).catch(I=>{this.logger.debug(`Failed to initialize custom instructions cache: ${I}`)})}async*query(e,I=[]){let l=new Map,n=new Map,c;try{if(this.options.mcpServers&&Object.keys(this.options.mcpServers).length>0)try{c=new y7(this.logger,{mcpServers:this.options.mcpServers},this.options.disabledTools),await c.startServers()}catch(He){this.logger.error(`Failed to initialize MCP host: ${He}`)}let s=(await $V(this.options.hooks?.userPromptSubmitted,{timestamp:Date.now(),cwd:this.workingDir,prompt:e},this.logger))?.modifiedPrompt??e;this.session.addEvent({type:"user.message",data:{content:zpe({problemStatement:s,capabilities:{}}),attachments:I}});let G=new iF().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();CNe();let d=await Y_e(G),i=d.service?.agent?.model,b=I8(i),m=b.agent,h=b.model?{model:b.model}:void 0,p=Jie(d,this.logger,m,h),Z={location:this.workingDir,timeout:3e4,requireReasoning:!0,toolPartialResultCallback:(He,Re)=>{this.session.addEvent({type:"tool.execution_partial_result",ephemeral:!0,data:{toolCallId:He,partialOutput:Re}})},permissions:this.options.requestPermission?{requestRequired:!0,request:this.options.requestPermission}:{requestRequired:!1},shellConfig:(process.platform==="win32"?_i.powerShell:_i.bash).withScriptSafetyAssessor(async function(He){return{result:"completed",commands:[{identifier:He,readOnly:!1}],possiblePaths:[],hasWriteFileRedirection:!1,canOfferSessionApproval:!1}})},W=await EPe(Z,this.logger),Y=[];if(c)try{Y=await c.getTools(d,this.logger,Z.permissions)}catch(He){this.logger.error(`Failed to get MCP tools: ${He}`)}let F=[...W,...Y].filter(He=>this.options.allowedTools?this.options.allowedTools.includes(He.name):this.options.disabledTools?!this.options.disabledTools.includes(He.name):!0),g=await Iue(this.workingDir),w={...(vPe()["sweagent-capi"]?.["claude-sonnet-4"]??HPe()).supports,reasoning:!0},H=await pPe(g.found?g.gitRoot:"",YBe(),this.workingDir,{},w,Z,F,void 0);this.session.addEvent({type:"system.message",data:{content:H,role:"system"}});let $=(await this.session.getChatMessages()).slice(0,-1),ge={role:"user",content:zpe({customAgentPrompt:void 0,problemStatement:s,capabilities:w})},ye=[...$,ge];await $V(this.options.hooks?.sessionStart,{timestamp:Date.now(),cwd:this.workingDir,source:"new",initialPrompt:e},this.logger);let ve=new g1(ge,this.logger),Qe=p.getCompletionWithTools(H,ye,F,{failIfInitialInputsTooLong:!1,processors:{preRequest:[ve,new Px(this.logger)],onRequestError:[ve]},executeToolsInParallel:!1,abortSignal:this.options.abortController?.signal}),Ne=es();yield this.session.addEvent({type:"assistant.turn_start",data:{turnId:Ne}});for await(let He of Qe){if(this.options.abortController?.signal.aborted){yield this.session.addEvent({type:"abort",data:{reason:"user initiated"}});break}switch(He.kind){case"message":{if(t8(He)){let Re=gPe(He)?await Promise.all(He.message.tool_calls.map(async Fe=>{let At=fw(Fe.function.arguments);l.set(Fe.id,Fe.function.name),n.set(Fe.id,At);let wI=await $V(this.options.hooks?.preToolUse,{timestamp:Date.now(),cwd:this.workingDir,toolName:Fe.function.name,toolArgs:At},this.logger);return{toolCallId:Fe.id,name:Fe.function.name,arguments:wI?.modifiedArgs??At}})):[];yield this.session.addEvent({type:"assistant.message",data:{messageId:es(),content:typeof He.message.content=="string"?He.message.content:"",toolRequests:Re}});for(let Fe of Re)yield this.session.addEvent({type:"tool.execution_start",data:{toolCallId:Fe.toolCallId,toolName:Fe.name,arguments:Fe.arguments}})}else(He.message.role==="system"||He.message.role==="developer")&&(yield this.session.addEvent({type:"system.message",data:{role:He.message.role,content:typeof He.message.content=="string"?He.message.content:JSON.stringify(He.message.content),name:"name"in He.message?He.message.name:void 0}}));break}case"model_call_failure":{let Re=new Error(He.modelCall?.error||"Model call failed");await $V(this.options.hooks?.errorOccurred,{timestamp:Date.now(),cwd:this.workingDir,error:Re,errorContext:"model_call",recoverable:!0},this.logger),yield this.session.addEvent({type:"session.error",data:{errorType:"model_call",message:Re.message,stack:Re.stack}});break}case"tool_execution":{let Fe=(await $V(this.options.hooks?.postToolUse,{timestamp:Date.now(),cwd:this.workingDir,toolName:l.get(He.toolCallId)||"unknown",toolArgs:n.get(He.toolCallId)||{},toolResult:He.toolResult},this.logger))?.modifiedResult??He.toolResult,At=(Fe.resultType==="failure"?Fe.error:void 0)||Fe.sessionLog||Fe.textResultForLlm;yield this.session.addEvent({type:"tool.execution_complete",data:{toolCallId:He.toolCallId,success:Fe.resultType==="success",result:Fe.resultType==="success"?{content:At}:void 0,error:Fe.resultType!=="success"?{message:At,code:Fe.resultType}:void 0}});break}case"response":case"images_removed":case"image_processing":case"history_truncated":case"turn_started":case"turn_ended":case"turn_failed":case"turn_retry":case"model_call_success":this.logger.debug(`Ignoring event of kind: ${He.kind}`);break;default:Xp(He,"Unhandled event type")}}yield this.session.addEvent({type:"assistant.turn_end",data:{turnId:Ne}})}catch(r){await $V(this.options.hooks?.sessionEnd,{timestamp:Date.now(),cwd:this.workingDir,reason:"error",error:r instanceof Error?r:new Error(String(r))},this.logger),yield this.session.addEvent({type:"session.error",data:{errorType:"query",message:r instanceof Error?r.message:String(r),stack:r instanceof Error?r.stack:void 0}})}finally{if(await $V(this.options.hooks?.sessionEnd,{timestamp:Date.now(),cwd:this.workingDir,reason:"complete"},this.logger),c)try{await c.stopServers(),this.logger.log("MCP host stopped successfully")}catch(r){this.logger.error(`Error stopping MCP host: ${r}`)}}}buildAgentModelString(){switch(this.options.modelProvider.type){case"openai":return`openai:${this.options.modelProvider.model}`;case"anthropic":return`anthropic:${this.options.modelProvider.model}`;case"copilot":return`capi:${this.options.modelProvider.model}`;default:throw new Error(`Unsupported provider: ${this.options.modelProvider.type}`)}}applyToolFiltering(e,I,l){let n=e;return I&&I.length>0&&(n=n.filter(c=>I.includes(c.name))),l&&l.length>0&&(n=n.filter(c=>!l.includes(c.name))),n}};var y$e={};Jc(y$e,{CLISessionManager:()=>cNe});o();o();import{unlink as R$e}from"fs/promises";import{join as hrt}from"path";o();var C7=class{sessions;logger;lastAccessedSessionId;constructor({logger:e}={}){this.sessions=new Map,this.logger=e||new Ri}async createSession(){let e=new gp({logger:this.logger});return this.sessions.set(e.sessionId,e),this.lastAccessedSessionId=e.sessionId,e}async getSession(e){let I=this.sessions.get(e);return I&&(this.lastAccessedSessionId=e),I}async getLastSession(){if(this.lastAccessedSessionId){let l=this.sessions.get(this.lastAccessedSessionId);if(l)return l}let e=Array.from(this.sessions.values());if(e.length===0)return;e.sort((l,n)=>n.startTime.getTime()-l.startTime.getTime());let I=e[0];return this.lastAccessedSessionId=I.sessionId,I}async listSessions(){return Array.from(this.sessions.values()).map(e=>({sessionId:e.sessionId,startTime:e.startTime,modifiedTime:e.modifiedTime}))}async saveSession(e){}async deleteSession(e){this.sessions.delete(e.sessionId),this.lastAccessedSessionId===e.sessionId&&(this.lastAccessedSessionId=void 0)}};o();o();o();var Z$e=Ll(c$e(),1);o();import{existsSync as $7}from"fs";import{appendFile as Ict,mkdir as tct,readdir as e_,readFile as G$e,stat as I_,writeFile as lct}from"fs/promises";import{homedir as d$e}from"os";import{dirname as nct,join as uG}from"path";o();o();var Pnt=new Error("timeout while waiting for mutex to become available"),Qmn=new Error("mutex already locked"),qnt=new Error("request for lock canceled"),_nt=function(t,e,I,l){function n(c){return c instanceof I?c:new I(function(r){r(c)})}return new(I||(I=Promise))(function(c,r){function s(d){try{G(l.next(d))}catch(i){r(i)}}function a(d){try{G(l.throw(d))}catch(i){r(i)}}function G(d){d.done?c(d.value):n(d.value).then(s,a)}G((l=l.apply(t,e||[])).next())})},tNe=class{constructor(e,I=qnt){this._value=e,this._cancelError=I,this._queue=[],this._weightedWaiters=[]}acquire(e=1,I=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((l,n)=>{let c={resolve:l,reject:n,weight:e,priority:I},r=s$e(this._queue,s=>I<=s.priority);r===-1&&e<=this._value?this._dispatchItem(c):this._queue.splice(r+1,0,c)})}runExclusive(e){return _nt(this,arguments,void 0,function*(I,l=1,n=0){let[c,r]=yield this.acquire(l,n);try{return yield I(c)}finally{r()}})}waitForUnlock(e=1,I=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,I)?Promise.resolve():new Promise(l=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),$nt(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 $nt(t,e){let I=s$e(t,l=>e.priority<=l.priority);t.splice(I+1,0,e)}function s$e(t,e){for(let I=t.length-1;I>=0;I--)if(e(t[I]))return I;return-1}var ect=function(t,e,I,l){function n(c){return c instanceof I?c:new I(function(r){r(c)})}return new(I||(I=Promise))(function(c,r){function s(d){try{G(l.next(d))}catch(i){r(i)}}function a(d){try{G(l.throw(d))}catch(i){r(i)}}function G(d){d.done?c(d.value):n(d.value).then(s,a)}G((l=l.apply(t,e||[])).next())})},q7=class{constructor(e){this._semaphore=new tNe(1,e)}acquire(){return ect(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()}},r$e=function(t,e,I,l){function n(c){return c instanceof I?c:new I(function(r){r(c)})}return new(I||(I=Promise))(function(c,r){function s(d){try{G(l.next(d))}catch(i){r(i)}}function a(d){try{G(l.throw(d))}catch(i){r(i)}}function G(d){d.done?c(d.value):n(d.value).then(s,a)}G((l=l.apply(t,e||[])).next())})};function a$e(t,e,I=Pnt){return{acquire:(l,n)=>{let c;if(P7(t)?c=l:(c=void 0,n=l),c!==void 0&&c<=0)throw new Error(`invalid weight ${c}: must be positive`);return new Promise((r,s)=>r$e(this,void 0,void 0,function*(){let a=!1,G=setTimeout(()=>{a=!0,s(I)},e);try{let d=yield P7(t)?t.acquire(c,n):t.acquire(n);a?(Array.isArray(d)?d[1]:d)():(clearTimeout(G),r(d))}catch(d){a||(clearTimeout(G),s(d))}}))},runExclusive(l,n,c){return r$e(this,void 0,void 0,function*(){let r=()=>{};try{let s=yield this.acquire(n,c);return Array.isArray(s)?(r=s[1],yield l(s[0])):(r=s,yield l())}finally{r()}})},release(l){t.release(l)},cancel(){return t.cancel()},waitForUnlock:(l,n)=>{let c;if(P7(t)?c=l:(c=void 0,n=l),c!==void 0&&c<=0)throw new Error(`invalid weight ${c}: must be positive`);return new Promise((r,s)=>{let a=setTimeout(()=>s(I),e);(P7(t)?t.waitForUnlock(c,n):t.waitForUnlock(n)).then(()=>{clearTimeout(a),r()})})},isLocked:()=>t.isLocked(),getValue:()=>t.getValue(),setValue:l=>t.setValue(l)}}function P7(t){return t.getValue!==void 0}var _7=class{mutexes=new Map;async runExclusive(e,I,l=5e3){let n=this.mutexes.get(e);n||(n=new q7,n.refCount=0,this.mutexes.set(e,n));let c=n;try{return c.refCount++,await a$e(n,l).runExclusive(I)}finally{--c.refCount===0&&this.mutexes.delete(e)}}};var lNe=(I=>(I.DEFAULT="config",I.MCP="mcp",I))(lNe||{});function o$e(t){return Object.values(lNe).includes(t)}var t_=".copilot",l_=new _7;async function i$e(t){let e=nct(t);try{await tct(e,{recursive:!0,mode:448})}catch{}}async function cct(t,e){if($7(t))try{let I={},l=await l_.runExclusive(t,()=>G$e(t,"utf8"));return l.trim().startsWith("{")?I=JSON.parse(l):l.split(`
|
|
1413
|
+
${c}`;await n.createOrUpdateMCPStartupToolCall({serverName:e,content:s}),this.logger.log(`Updated session log for ${e} with ${I.length} tools`)}catch(c){this.logger.error(`Failed to update session log for ${e}: ${c}`)}}};o();o();var _V=class t{static resolveString(e,I){return!I||e.length>1e3?e:e.replace(/\$\{([A-Z0-9_]+)(?::-([^}]*))?\}|\$([A-Z0-9_]+)(?![A-Z0-9_])/g,(l,n,c,r)=>{let a=I[n||r];return a!==void 0?a:c!==void 0?c:l})}static resolveArray(e,I){return e?I?e.map(l=>t.resolveString(l,I)):e:[]}static resolveHeaders(e,I){if(!e)return{};if(!I)return e;let l={};for(let[n,c]of Object.entries(e)){let r=t.resolveArray([c],I);l[n]=r[0]}return l}static resolveLocalServerConfig(e,I){let l=t.resolveString(e.command,I),n=t.resolveArray(e.args,I),c;return e.cwd&&(c=t.resolveString(e.cwd,I)),{...e,command:l,args:n,cwd:c}}static resolveRemoteServerConfig(e,I=process.env){let l=t.resolveString(e.url,I),n=t.resolveHeaders(e.headers,I);return{...e,url:l,headers:n}}};var EWe={mcpServers:{}},R7=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"),EWe;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"),EWe;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}`),EWe}}configureGitHubMcp(e,I){this.remoteEnabled?this.configureRemoteGitHubMcp(e,I):this.configureLocalGitHubMcp(e)}configureRemoteGitHubMcp(e,I){this.logger.log("Using default remote GitHub MCP server configuration");let l="repos,issues,users,pull_requests,code_security,secret_protection,actions,web_search";process.env.COPILOT_MCP_COPILOT_SPACES_ENABLED==="true"&&(this.logger.log("Enabling Copilot Spaces in GitHub MCP server configuration"),l=l+",copilot_spaces");let n={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":l,"X-MCP-Host":"github-coding-agent","X-Initiator":"agent"};I&&I.api?.copilot?.integrationId&&(n["Copilot-Integration-Id"]=I.api.copilot.integrationId),process.env.GITHUB_COPILOT_INTERACTION_ID&&(n["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let c={type:"http",url:this.getCapiMcpUrl(),headers:n,tools:["*"],isDefaultServer:!0,filterMapping:{get_issue:"markdown",get_issue_comments:"markdown",get_pull_request:"markdown",get_pull_request_comments:"markdown",get_pull_request_reviews:"markdown"}};e.mcpServers[lv]=c}configureLocalGitHubMcp(e){if(e.mcpServers[lv]){this.logger.log("Using user-provided GitHub MCP server configuration");let I=e.mcpServers[lv]??{};nv(I)&&!I.command&&(e.mcpServers[lv]={...I,command:"./copilot-developer-action-main/github-mcp-server/github-mcp-server",isDefaultServer:!0},this.logger.log("Added default command to user-provided GitHub MCP server configuration"))}else{this.logger.log("Using default local GitHub MCP server configuration");let I={command:"./copilot-developer-action-main/github-mcp-server/github-mcp-server",args:["stdio","--read-only"],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",GITHUB_HOST:"GITHUB_SERVER_URL"},tools:["*"],isDefaultServer:!0};e.mcpServers[lv]=I}}configurePlaywrightMcp(e){if(!e.mcpServers[wWe]){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:[...Spe,"--allowed-origins","localhost;localhost:*;127.0.0.1;127.0.0.1:*"],tools:["*"],isDefaultServer:!0};e.mcpServers[wWe]=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[$B]=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[$B]=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[$B]=n}getCapiMcpUrl(){return process.env.COPILOT_API_URL?new URL("/mcp/readonly",process.env.COPILOT_API_URL).toString():"https://api.githubcopilot.com/mcp/readonly"}isValidServerType(e){return nv(e)||N7(e)||Y7(e)||Iz(e)}isValidLocalServerConfig(e){return e.command!==void 0&&e.command.trim()!==""&&Array.isArray(e.args)}isValidRemoteServerConfig(e){return e.url!==void 0&&e.url.trim()!==""}isValidInMemoryServerConfig(e){return e.serverInstance!==void 0&&typeof e.serverInstance=="object"}validateServerConfig(e,I){return this.remoteEnabled&&!this.isValidServerType(I)?(this.logger.error(`Unsupported server type "${I.type}" for server "${e}". Only "Local", "STDIO", "HTTP", "SSE", or "Memory" are supported.`),!1):!this.remoteEnabled&&!nv(I)&&!Iz(I)?(this.logger.error(`Unsupported server type "${I.type}" for server "${e}". Only "Local", "STDIO", or "Memory" are supported.`),!1):I.tools?nv(I)&&!this.isValidLocalServerConfig(I)?(this.logger.error(`Invalid local server configuration for "${e}". Please ensure 'command' and 'args' are provided.`),!1):(N7(I)||Y7(I))&&!this.isValidRemoteServerConfig(I)?(this.logger.error(`Invalid remote server configuration for "${e}". Please ensure 'url' is provided.`),!1):Iz(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=_V.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=_V.resolveRemoteServerConfig(I,process.env);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}}async processInMemoryServer(e,I){try{await this.registry.startInMemoryMcpClient(e,I.serverInstance),this.logger.log(`Started in-memory MCP client for ${e}`)}catch(l){throw this.logger.error(`Failed to start in-memory MCP client for ${e}: ${l}`),l}}async processLocalServer(e,I){let l={...I};if(I.command==="python")try{l=await this.convertPythonToPipx(l)}catch(r){this.logger.error(`Failed to handle Python module for ${e}: ${r}`)}let n=this.buildEnvironment(l),c=_V.resolveLocalServerConfig(l,n);this.logger.log(`Starting MCP client for ${e} with command: ${c.command} and args: ${c.args}`),c.cwd&&this.logger.log(`cwd: ${c.cwd}`);try{await this.registry.startLocalMcpClient(e,n,c.command,c.args,c.cwd),this.logger.log(`Started MCP client for ${e}`)}catch(r){throw this.logger.error(`Failed to start MCP client for ${e}: ${r}`),r}}convertPythonToPipx(e){if(!e||!e.args||e.args.length===0)return e;let I=e.args;if(I.length>1e3)throw new Error("Too many arguments provided to Python command");let l=I.indexOf("-m");if(l===-1||l===I.length-1)throw new Error("Python command with -m flag must specify a module");let n=I[l+1];this.logger.log(`Converting Python module: ${n} to pipx command`);let c=["run",n];for(let r=l+2;r<I.length;r++)c.push(I[r]);for(let r=0;r<l;r++)c.push(I[r]);return{...e,command:"pipx",args:c}}buildEnvironment(e){let I={};if(e.env)if(this.envValueMode==="direct")for(let[l,n]of Object.entries(e.env))I[l]=_V.resolveString(n,process.env);else for(let[l,n]of Object.entries(e.env)){let c=n.trim(),r=c;if(c.includes("$")&&(r=_V.resolveString(c,process.env)),r!==c){I[l]=r;continue}process.env[c]!==void 0&&(I[l]=process.env[c])}return I}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}ez.includes(e)||await this.sessionClient?.createOrUpdateMCPStartupToolCall({serverName:e});try{nv(I)?await this.processLocalServer(e,I):N7(I)&&this.remoteEnabled?await this.processHttpServer(e,I):Y7(I)&&this.remoteEnabled?await this.processSseServer(e,I):Iz(I)&&await this.processInMemoryServer(e,I)}catch(l){ez.includes(e)||await this.logServerFailure(e,l)}}async logServerFailure(e,I){if(this.sessionClient)try{await this.sessionClient.createOrUpdateMCPStartupToolCall({serverName:e,content:`<error>MCP server failed to start: ${I.message} - for the full output, see the verbose logs</error>`})}catch(l){this.logger.error(`Failed to log failure for MCP Server '${e}': '${l}'`)}}};var y7=class{constructor(e,I,l,n="indirect"){this.logger=e;let c;if(typeof I=="string"){if(c=JSON.parse(I),typeof c!="object")throw new Error("Invalid MCP configuration: must be an object");if(c===null||!("mcpServers"in c)||typeof c.mcpServers!="object")throw new Error("Invalid MCP configuration: missing or invalid mcpServers property");this.config=c}else this.config=I;this.disabledServers=new Set(l||[]),this.registry=new V7(this.logger,void 0,void 0,n),this.processor=new R7(this.logger,this.registry,{mcp3pEnabled:!0,remoteEnabled:!0})}registry;processor;config;startServersPromise=null;transport=null;disabledServers;async startServers(){return this.startServersPromise||(this.startServersPromise=this.processServersWithExtensions()),this.startServersPromise}async injectDefaultServers(e){}async processServersWithExtensions(){await this.injectDefaultServers(this.config);let e;if(this.disabledServers.size>0){let I={};for(let[l,n]of Object.entries(this.config.mcpServers))this.disabledServers.has(l)?this.logger.log(`Skipping disabled MCP server: ${l}`):I[l]=n;e={...this.config,mcpServers:I}}else e=this.config;return this.processor.processServers(e)}async stopServers(){for(let[e,I]of Object.entries(this.registry.transports))try{await I.close()}catch(l){this.logger.error(`Error closing transport for ${e}: ${l}`)}this.startServersPromise=null,this.transport=null}async getTools(e,I,l){await this.startServers(),this.transport=this.transport??new Kx(e,I,!0);let n=[];for(let c of Object.keys(this.registry.clients)){let r=await this.transport.loadTools({mcpClient:this.registry.clients[c],clientName:c,tools:this.config.mcpServers[c]?.tools||["*"],filterMapping:this.config.mcpServers[c]?.filterMapping||"hidden_characters"},l);n.push(...r)}return n}getConfig(){return this.config}getClients(){return this.registry.clients}async startServer(e,I){await this.startServers(),this.config.mcpServers[e]=I,await this.processor.processServer(e,I),this.transport=null}async stopServer(e){let I=this.registry.transports[e];if(I)try{await I.close(),delete this.registry.transports[e]}catch(l){this.logger.error(`Error closing transport for ${e}: ${l}`)}this.registry.clients[e]&&delete this.registry.clients[e],this.transport=null}async restartServer(e,I){this.isServerRunning(e)&&await this.stopServer(e),delete this.config.mcpServers[e],await this.startServer(e,I)}isServerRunning(e){return e in this.registry.transports&&e in this.registry.clients}isServerDisabled(e){return this.disabledServers.has(e)}async disableServer(e){if(this.disabledServers.has(e)){this.logger.log(`Server ${e} is already disabled`);return}this.disabledServers.add(e),this.logger.log(`Disabled server ${e} for this session`),this.isServerRunning(e)&&await this.stopServer(e),this.transport=null}async enableServer(e){if(!this.disabledServers.has(e)){this.logger.log(`Server ${e} is not disabled`);return}this.disabledServers.delete(e),this.logger.log(`Enabled server ${e} for this session`);let I=this.getServerConfig(e);I?await this.startServer(e,I):await this.startBuiltInServer(e),this.transport=null}async startBuiltInServer(e){}getServerConfig(e){return this.config.mcpServers[e]}};o();var N_e=Ll(W_e(),1);async function tlt(t={}){let e=await LNe();return vNe((0,N_e.default)({},e,t))}async function Y_e(t={}){if(Vz())throw new Error("Settings have already been initialized");return tlt(t)}o();async function $V(t,e,I){if(!t||t.length===0)return;let l=!1,n={};for(let c of t)try{let r=await c(e);r&&(l=!0,n={...n,...r})}catch(r){I.error(`Hook execution failed: ${r}`)}return l?n:void 0}o();o();import{promises as llt}from"fs";import V_e from"path";var nlt=3*1024*1024;function R_e(t){let e=V_e.extname(t).toLowerCase();return[".png",".jpg",".jpeg",".gif",".webp"].includes(e)}function clt(t){switch(V_e.extname(t).toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";default:return null}}async function rlt(t,e){e.debug(`Processing local image file: ${t}`);let I=await llt.readFile(t),l=clt(t);if(!l)throw new Error(`Unsupported image format: ${t}`);let n=new Dx,c=await qq(e,n,nlt,Mx,l,I);if(!c)throw new Error(`Image too large or couldn't be processed: ${t}`);let r=c.toString("base64");return`data:${l};base64,${r}`}async function slt(t,e){let I=es();try{let l=await Jce({command:"view",path:t,view_range:void 0},{properties:{command:"view",resolvedPathAgainstCwd:"false",options:"{}",inputs:"[]"},metrics:{responseTokenLimit:void 0,resultLength:0,resultForLlmLength:0},restrictedProperties:{}},e);return{id:I,name:"view",arguments:{path:t},result:l.textResultForLlm||""}}catch(l){return{id:I,name:"view",arguments:{path:t},result:`Error reading ${t}: ${l}`}}}async function y_e(t,e){let I=[],l=t.filter(c=>!R_e(c.path));if(l.length===0)return I;let n=[];for(let c of l)try{let r=await slt(c.path,e);n.push(r)}catch{}if(n.length>0){let c=n.map(r=>({id:r.id,type:"function",function:{name:r.name,arguments:JSON.stringify(r.arguments)}}));I.push({role:"assistant",content:"I need to read the content of those paths to answer this request.",tool_calls:c}),I.push(...n.map(r=>({role:"tool",tool_call_id:r.id,content:r.result})))}return I}async function g_e(t,e){let I=t.filter(n=>R_e(n.path));return(await Promise.all(I.map(async n=>{try{return{type:"image_url",image_url:{url:await rlt(n.path,e)}}}catch(c){e.error(`Failed to process image ${n.path}: ${c instanceof Error?c.message:String(c)}`);return}}))).filter(n=>n!==void 0)}var gp=class{sessionId;startTime;modifiedTime;events=[];_chatMessages=[];_selectedModel;logger;eventCallbacks=[];eventProcessingQueue=Promise.resolve();constructor({sessionId:e,startTime:I,modifiedTime:l,logger:n}={}){this.sessionId=e||es(),this.startTime=I||new Date,this.modifiedTime=l||this.startTime,this.logger=n||new Ri}get messageCount(){let e=this.events.find(l=>l.type==="session.import_legacy"),I=0;return e&&(I=(e.data.legacySession?.chatMessages||[]).filter(c=>c.role==="user"||c.role==="assistant").length),this.logger.debug(`Imported message count: ${I}`),this.events.filter(l=>l.type==="user.message"||l.type==="assistant.message").length+I}get summary(){let e=this.events.find(c=>c.type==="session.import_legacy"||c.type==="user.message"),I;if(e?.type==="session.import_legacy"){let c=e.data.legacySession.chatMessages.find(r=>r.role==="user");c?.content&&(typeof c.content=="string"?I=c.content:I=c.content.find(r=>r.type==="text")?.text)}else e?.type==="user.message"&&(I=e.data.content);if(!I)return;let l=I.lastIndexOf("<reminder>");l!==-1&&(I=I.substring(0,l).trim());let n=I.replace(/\s+/g," ").trim();return n.length>75&&(n=n.substring(0,55).trim()+"..."),n=n.split("").filter(c=>{let r=c.charCodeAt(0);return r>=32&&r!==127}).join(""),n}static async fromEvents({events:e,logger:I}){if(e.length===0)throw new Error("Cannot create session from empty events array");let l=e[0];if(l.type!=="session.start")throw new Error("First event must be session.start");let n=new this({sessionId:l.data.sessionId,startTime:new Date(l.data.startTime),logger:I||new Ri});n._selectedModel=l.data.selectedModel,n.events.push(l);for(let c=1;c<e.length;c++){let r=e[c];n.events.push(r),await n.processEventForState(r)}return n}addEvent(e){let I=e.id||es(),l=e.timestamp||new Date().toISOString(),n=e.parentId!==void 0?e.parentId:this.getLastEventId(),c={...e,id:I,timestamp:l,parentId:n};return this.events.push(c),this.enqueueEventProcessing(()=>this.processEventForState(c).catch(r=>{this.logger.error(`Error processing event ${c.type} (${c.id}): ${r instanceof Error?r.message:String(r)}`)})).catch(r=>{this.logger.error(`Error processing event queue ${r instanceof Error?r.message:String(r)}`)}),this.notifyEventCallbacks(c),c}getEvents(){return this.events}onEvent(e){return this.eventCallbacks.push(e),()=>{let I=this.eventCallbacks.indexOf(e);I>-1&&this.eventCallbacks.splice(I,1)}}async getChatMessages(){return this.enqueueEventProcessing(()=>this._chatMessages)}async getChatContextMessages(){return(await this.getChatMessages()).filter(I=>I.role!=="system")}async getSystemContextMessages(){return(await this.getChatMessages()).filter(I=>I.role==="system")}async getSelectedModel(){return this.enqueueEventProcessing(()=>this._selectedModel)}setSelectedModel(e){let I=this._selectedModel;this._selectedModel=e,this.addEvent({type:"session.model_change",data:{previousModel:I,newModel:e}})}getLastEventId(){return this.events.length===0?null:this.events[this.events.length-1].id}enqueueEventProcessing(e){let I=this.eventProcessingQueue.then(()=>e());return this.eventProcessingQueue=I,I}async processEventForState(e){switch(e.type){case"session.start":e.data.selectedModel&&(this._selectedModel=e.data.selectedModel);break;case"session.model_change":this._selectedModel=e.data.newModel;break;case"user.message":{let I=[],l=[];if(e.data.attachments&&e.data.attachments.length>0){let n=await g_e(e.data.attachments,this.logger);I.push(...n);let c=await y_e(e.data.attachments,this.logger);l.push(...c)}I.length>0?this._chatMessages.push({role:"user",content:[{type:"text",text:e.data.content},...I]}):this._chatMessages.push({role:"user",content:e.data.content}),l.length>0&&this._chatMessages.push(...l);break}case"assistant.message":{if(e.ephemeral)break;let I={role:"assistant",content:e.data.content||null};e.data.toolRequests&&e.data.toolRequests.length>0&&(I.tool_calls=e.data.toolRequests.map(l=>({id:l.toolCallId,type:"function",function:{name:l.name,arguments:typeof l.arguments=="string"?l.arguments:JSON.stringify(l.arguments)}}))),this._chatMessages.push(I);break}case"tool.execution_complete":{e.data.isUserRequested||this._chatMessages.push({role:"tool",tool_call_id:e.data.toolCallId,content:e.data.success?e.data.result?.content||"":e.data.error?.message||"Tool execution failed"});break}case"system.message":this._chatMessages.push({role:e.data.role,content:e.data.content,...e.data.name&&{name:e.data.name}});break;case"session.import_legacy":this._chatMessages=[...e.data.legacySession.chatMessages],e.data.legacySession.selectedModel&&(this._selectedModel=e.data.legacySession.selectedModel);break;case"abort":case"session.resume":this._chatMessages=alt(this._chatMessages,this.logger);break;case"session.error":case"session.info":case"assistant.turn_start":case"assistant.turn_end":case"assistant.usage":case"tool.user_requested":case"tool.execution_start":case"tool.execution_partial_result":case"hook.start":case"hook.end":break;default:{let I=e;this.logger.error(`Unknown event type: ${I.type}`);break}}}notifyEventCallbacks(e){for(let I of this.eventCallbacks)try{I(e)}catch(l){this.logger.error(`Error in event callback: ${l instanceof Error?l.message:String(l)}`)}}};function alt(t,e){if(t.length===0)return t;let I=[],l=new Set,n=!1;for(let s=t.length-1;s>=0;s--){let a=t[s];if(a.role==="assistant"&&(n=!0),a.role==="assistant"&&"tool_calls"in a&&a.tool_calls&&a.tool_calls.length>0)for(let G of a.tool_calls)l.has(G.id)||I.push(G.id);else{if(n)break;a.role==="tool"&&a.tool_call_id&&l.add(a.tool_call_id)}}if(I.length===0)return t;let c="The execution of this tool, or a previous tool was interrupted.";e.info(`Completing ${I.length} orphaned tool calls.`);let r=I.map(s=>({role:"tool",tool_call_id:s,content:c}));return[...t,...r]}var v7=class{static name="Copilot";static description="Base Copilot Agent";options;logger;workingDir;session;constructor(e){this.options=e,this.logger=e.logger||new Ri,this.workingDir=e.workingDirectory||process.cwd(),this.session=e.session||new gp,Iue(this.workingDir).then(I=>{if(I.found)return DDe(I.gitRoot,!0,this.workingDir)}).catch(I=>{this.logger.debug(`Failed to initialize custom instructions cache: ${I}`)})}async*query(e,I=[]){let l=new Map,n=new Map,c;try{if(this.options.mcpServers&&Object.keys(this.options.mcpServers).length>0)try{c=new y7(this.logger,{mcpServers:this.options.mcpServers},this.options.disabledTools),await c.startServers()}catch(He){this.logger.error(`Failed to initialize MCP host: ${He}`)}let s=(await $V(this.options.hooks?.userPromptSubmitted,{timestamp:Date.now(),cwd:this.workingDir,prompt:e},this.logger))?.modifiedPrompt??e;this.session.addEvent({type:"user.message",data:{content:zpe({problemStatement:s,capabilities:{}}),attachments:I}});let G=new iF().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();CNe();let d=await Y_e(G),i=d.service?.agent?.model,b=I8(i),m=b.agent,h=b.model?{model:b.model}:void 0,p=Jie(d,this.logger,m,h),Z={location:this.workingDir,timeout:3e4,requireReasoning:!0,toolPartialResultCallback:(He,Re)=>{this.session.addEvent({type:"tool.execution_partial_result",ephemeral:!0,data:{toolCallId:He,partialOutput:Re}})},permissions:this.options.requestPermission?{requestRequired:!0,request:this.options.requestPermission}:{requestRequired:!1},shellConfig:(process.platform==="win32"?_i.powerShell:_i.bash).withScriptSafetyAssessor(async function(He){return{result:"completed",commands:[{identifier:He,readOnly:!1}],possiblePaths:[],hasWriteFileRedirection:!1,canOfferSessionApproval:!1}})},W=await EPe(Z,this.logger),Y=[];if(c)try{Y=await c.getTools(d,this.logger,Z.permissions)}catch(He){this.logger.error(`Failed to get MCP tools: ${He}`)}let F=[...W,...Y].filter(He=>this.options.allowedTools?this.options.allowedTools.includes(He.name):this.options.disabledTools?!this.options.disabledTools.includes(He.name):!0),g=await Iue(this.workingDir),w={...(vPe()["sweagent-capi"]?.["claude-sonnet-4"]??HPe()).supports,reasoning:!0},H=await pPe(g.found?g.gitRoot:"",YBe(),this.workingDir,{},w,Z,F,void 0);this.session.addEvent({type:"system.message",data:{content:H,role:"system"}});let $=(await this.session.getChatMessages()).slice(0,-1),ge={role:"user",content:zpe({customAgentPrompt:void 0,problemStatement:s,capabilities:w})},ye=[...$,ge];await $V(this.options.hooks?.sessionStart,{timestamp:Date.now(),cwd:this.workingDir,source:"new",initialPrompt:e},this.logger);let ve=new g1(ge,this.logger),Qe=p.getCompletionWithTools(H,ye,F,{failIfInitialInputsTooLong:!1,processors:{preRequest:[ve,new Px(this.logger)],onRequestError:[ve]},executeToolsInParallel:!1,abortSignal:this.options.abortController?.signal}),Ne=es();yield this.session.addEvent({type:"assistant.turn_start",data:{turnId:Ne}});for await(let He of Qe){if(this.options.abortController?.signal.aborted){yield this.session.addEvent({type:"abort",data:{reason:"user initiated"}});break}switch(He.kind){case"message":{if(t8(He)){let Re=gPe(He)?await Promise.all(He.message.tool_calls.map(async Fe=>{let At=fw(Fe.function.arguments);l.set(Fe.id,Fe.function.name),n.set(Fe.id,At);let wI=await $V(this.options.hooks?.preToolUse,{timestamp:Date.now(),cwd:this.workingDir,toolName:Fe.function.name,toolArgs:At},this.logger);return{toolCallId:Fe.id,name:Fe.function.name,arguments:wI?.modifiedArgs??At}})):[];yield this.session.addEvent({type:"assistant.message",data:{messageId:es(),content:typeof He.message.content=="string"?He.message.content:"",toolRequests:Re}});for(let Fe of Re)yield this.session.addEvent({type:"tool.execution_start",data:{toolCallId:Fe.toolCallId,toolName:Fe.name,arguments:Fe.arguments}})}else(He.message.role==="system"||He.message.role==="developer")&&(yield this.session.addEvent({type:"system.message",data:{role:He.message.role,content:typeof He.message.content=="string"?He.message.content:JSON.stringify(He.message.content),name:"name"in He.message?He.message.name:void 0}}));break}case"model_call_failure":{let Re=new Error(He.modelCall?.error||"Model call failed");await $V(this.options.hooks?.errorOccurred,{timestamp:Date.now(),cwd:this.workingDir,error:Re,errorContext:"model_call",recoverable:!0},this.logger),yield this.session.addEvent({type:"session.error",data:{errorType:"model_call",message:Re.message,stack:Re.stack}});break}case"tool_execution":{let Fe=(await $V(this.options.hooks?.postToolUse,{timestamp:Date.now(),cwd:this.workingDir,toolName:l.get(He.toolCallId)||"unknown",toolArgs:n.get(He.toolCallId)||{},toolResult:He.toolResult},this.logger))?.modifiedResult??He.toolResult,At=(Fe.resultType==="failure"?Fe.error:void 0)||Fe.sessionLog||Fe.textResultForLlm;yield this.session.addEvent({type:"tool.execution_complete",data:{toolCallId:He.toolCallId,success:Fe.resultType==="success",result:Fe.resultType==="success"?{content:At}:void 0,error:Fe.resultType!=="success"?{message:At,code:Fe.resultType}:void 0}});break}case"response":case"images_removed":case"image_processing":case"history_truncated":case"turn_started":case"turn_ended":case"turn_failed":case"turn_retry":case"model_call_success":this.logger.debug(`Ignoring event of kind: ${He.kind}`);break;default:Xp(He,"Unhandled event type")}}yield this.session.addEvent({type:"assistant.turn_end",data:{turnId:Ne}})}catch(r){await $V(this.options.hooks?.sessionEnd,{timestamp:Date.now(),cwd:this.workingDir,reason:"error",error:r instanceof Error?r:new Error(String(r))},this.logger),yield this.session.addEvent({type:"session.error",data:{errorType:"query",message:r instanceof Error?r.message:String(r),stack:r instanceof Error?r.stack:void 0}})}finally{if(await $V(this.options.hooks?.sessionEnd,{timestamp:Date.now(),cwd:this.workingDir,reason:"complete"},this.logger),c)try{await c.stopServers(),this.logger.log("MCP host stopped successfully")}catch(r){this.logger.error(`Error stopping MCP host: ${r}`)}}}buildAgentModelString(){switch(this.options.modelProvider.type){case"openai":return`openai:${this.options.modelProvider.model}`;case"anthropic":return`anthropic:${this.options.modelProvider.model}`;case"copilot":return`capi:${this.options.modelProvider.model}`;default:throw new Error(`Unsupported provider: ${this.options.modelProvider.type}`)}}applyToolFiltering(e,I,l){let n=e;return I&&I.length>0&&(n=n.filter(c=>I.includes(c.name))),l&&l.length>0&&(n=n.filter(c=>!l.includes(c.name))),n}};var y$e={};Jc(y$e,{CLISessionManager:()=>cNe});o();o();import{unlink as R$e}from"fs/promises";import{join as hrt}from"path";o();var C7=class{sessions;logger;lastAccessedSessionId;constructor({logger:e}={}){this.sessions=new Map,this.logger=e||new Ri}async createSession(){let e=new gp({logger:this.logger});return this.sessions.set(e.sessionId,e),this.lastAccessedSessionId=e.sessionId,e}async getSession(e){let I=this.sessions.get(e);return I&&(this.lastAccessedSessionId=e),I}async getLastSession(){if(this.lastAccessedSessionId){let l=this.sessions.get(this.lastAccessedSessionId);if(l)return l}let e=Array.from(this.sessions.values());if(e.length===0)return;e.sort((l,n)=>n.startTime.getTime()-l.startTime.getTime());let I=e[0];return this.lastAccessedSessionId=I.sessionId,I}async listSessions(){return Array.from(this.sessions.values()).map(e=>({sessionId:e.sessionId,startTime:e.startTime,modifiedTime:e.modifiedTime}))}async saveSession(e){}async deleteSession(e){this.sessions.delete(e.sessionId),this.lastAccessedSessionId===e.sessionId&&(this.lastAccessedSessionId=void 0)}};o();o();o();var Z$e=Ll(c$e(),1);o();import{existsSync as $7}from"fs";import{appendFile as Ict,mkdir as tct,readdir as e_,readFile as G$e,stat as I_,writeFile as lct}from"fs/promises";import{homedir as d$e}from"os";import{dirname as nct,join as uG}from"path";o();o();var Pnt=new Error("timeout while waiting for mutex to become available"),Qmn=new Error("mutex already locked"),qnt=new Error("request for lock canceled"),_nt=function(t,e,I,l){function n(c){return c instanceof I?c:new I(function(r){r(c)})}return new(I||(I=Promise))(function(c,r){function s(d){try{G(l.next(d))}catch(i){r(i)}}function a(d){try{G(l.throw(d))}catch(i){r(i)}}function G(d){d.done?c(d.value):n(d.value).then(s,a)}G((l=l.apply(t,e||[])).next())})},tNe=class{constructor(e,I=qnt){this._value=e,this._cancelError=I,this._queue=[],this._weightedWaiters=[]}acquire(e=1,I=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((l,n)=>{let c={resolve:l,reject:n,weight:e,priority:I},r=s$e(this._queue,s=>I<=s.priority);r===-1&&e<=this._value?this._dispatchItem(c):this._queue.splice(r+1,0,c)})}runExclusive(e){return _nt(this,arguments,void 0,function*(I,l=1,n=0){let[c,r]=yield this.acquire(l,n);try{return yield I(c)}finally{r()}})}waitForUnlock(e=1,I=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,I)?Promise.resolve():new Promise(l=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),$nt(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 $nt(t,e){let I=s$e(t,l=>e.priority<=l.priority);t.splice(I+1,0,e)}function s$e(t,e){for(let I=t.length-1;I>=0;I--)if(e(t[I]))return I;return-1}var ect=function(t,e,I,l){function n(c){return c instanceof I?c:new I(function(r){r(c)})}return new(I||(I=Promise))(function(c,r){function s(d){try{G(l.next(d))}catch(i){r(i)}}function a(d){try{G(l.throw(d))}catch(i){r(i)}}function G(d){d.done?c(d.value):n(d.value).then(s,a)}G((l=l.apply(t,e||[])).next())})},q7=class{constructor(e){this._semaphore=new tNe(1,e)}acquire(){return ect(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()}},r$e=function(t,e,I,l){function n(c){return c instanceof I?c:new I(function(r){r(c)})}return new(I||(I=Promise))(function(c,r){function s(d){try{G(l.next(d))}catch(i){r(i)}}function a(d){try{G(l.throw(d))}catch(i){r(i)}}function G(d){d.done?c(d.value):n(d.value).then(s,a)}G((l=l.apply(t,e||[])).next())})};function a$e(t,e,I=Pnt){return{acquire:(l,n)=>{let c;if(P7(t)?c=l:(c=void 0,n=l),c!==void 0&&c<=0)throw new Error(`invalid weight ${c}: must be positive`);return new Promise((r,s)=>r$e(this,void 0,void 0,function*(){let a=!1,G=setTimeout(()=>{a=!0,s(I)},e);try{let d=yield P7(t)?t.acquire(c,n):t.acquire(n);a?(Array.isArray(d)?d[1]:d)():(clearTimeout(G),r(d))}catch(d){a||(clearTimeout(G),s(d))}}))},runExclusive(l,n,c){return r$e(this,void 0,void 0,function*(){let r=()=>{};try{let s=yield this.acquire(n,c);return Array.isArray(s)?(r=s[1],yield l(s[0])):(r=s,yield l())}finally{r()}})},release(l){t.release(l)},cancel(){return t.cancel()},waitForUnlock:(l,n)=>{let c;if(P7(t)?c=l:(c=void 0,n=l),c!==void 0&&c<=0)throw new Error(`invalid weight ${c}: must be positive`);return new Promise((r,s)=>{let a=setTimeout(()=>s(I),e);(P7(t)?t.waitForUnlock(c,n):t.waitForUnlock(n)).then(()=>{clearTimeout(a),r()})})},isLocked:()=>t.isLocked(),getValue:()=>t.getValue(),setValue:l=>t.setValue(l)}}function P7(t){return t.getValue!==void 0}var _7=class{mutexes=new Map;async runExclusive(e,I,l=5e3){let n=this.mutexes.get(e);n||(n=new q7,n.refCount=0,this.mutexes.set(e,n));let c=n;try{return c.refCount++,await a$e(n,l).runExclusive(I)}finally{--c.refCount===0&&this.mutexes.delete(e)}}};var lNe=(I=>(I.DEFAULT="config",I.MCP="mcp",I))(lNe||{});function o$e(t){return Object.values(lNe).includes(t)}var t_=".copilot",l_=new _7;async function i$e(t){let e=nct(t);try{await tct(e,{recursive:!0,mode:448})}catch{}}async function cct(t,e){if($7(t))try{let I={},l=await l_.runExclusive(t,()=>G$e(t,"utf8"));return l.trim().startsWith("{")?I=JSON.parse(l):l.split(`
|
|
1414
1414
|
`).forEach(n=>{let[c,r]=n.split("=").map(s=>s.trim());c&&r&&(I[c]=r)}),e(I)}catch(I){throw new Error(`Failed to read configuration from ${t}: ${I}`)}}async function rct(t,e){try{await i$e(t);let I=JSON.stringify(e,null,2);await l_.runExclusive(t,()=>lct(t,I,{mode:384}))}catch(I){throw new Error(`Failed to write configuration to ${t}: ${I}`)}}var b$e=(t,e,{shouldCache:I})=>{let l=new Map,n=()=>{let b=o$e(e)?process.env.XDG_CONFIG_HOME:process.env.XDG_STATE_HOME;return b?uG(b,t_):uG(d$e(),t_)},c=()=>{let b=o$e(e)?"-config":"-state";return`${e}${e=="config"?"":b}`},r=b=>{let m=".json",h=c()+(b?"":m),p=uG(n(),h,b?`${b}${m}`:"");return!$7(p)&&$7(p.replace(/\.json$/,""))&&(p=p.replace(/\.json$/,"")),p},s=async()=>{let b=uG(n(),c());try{let h=(await e_(b,{withFileTypes:!0})).filter(Z=>Z.isFile()&&Z.name.endsWith(".json")).map(Z=>Z.name),p=await Promise.all(h.map(async Z=>{let W=uG(b,Z);try{let Y=await I_(W);return{file:Z,mtime:Y.mtime}}catch{return{file:Z,mtime:new Date}}}));return p.sort((Z,W)=>W.mtime.getTime()-Z.mtime.getTime()),p.map(Z=>Z.file)}catch{}return[]},a=async()=>{let b=uG(n(),c());try{let h=(await e_(b,{withFileTypes:!0})).filter(Z=>Z.isFile()&&Z.name.endsWith(".json")).map(Z=>Z.name),p=await Promise.all(h.map(async Z=>{let W=uG(b,Z);try{let Y=await I_(W);return{file:Z,mtime:Y.mtime,ctime:Y.ctime}}catch{return{file:Z,mtime:new Date,ctime:new Date}}}));return p.sort((Z,W)=>W.mtime.getTime()-Z.mtime.getTime()),p}catch{}return[]},G=async(b="")=>{if(I&&l.has(b))return l.get(b);let m=await cct(r(b),t);return I&&m&&l.set(b,m),m},d=async(b,m="")=>{I&&l.set(m,b),await rct(r(m),b)};return{load:G,write:d,writeKey:async(b,m,h)=>{let p=await G(h);if(m===void 0){p&&(delete p[b],await d(p,h));return}let Z={[b]:m},W;p?W={...p,...Z}:W=Z,await d(W,h)},path:r,directoryFiles:s,directoryFilesWithMetadata:a}},m$e=(t,e)=>b$e(t,e,{shouldCache:!0}),h$e=(t,e)=>b$e(t,e,{shouldCache:!1}),p$e=(t,e)=>{let I=()=>{let G=process.env.XDG_STATE_HOME;return G?uG(G,t_):uG(d$e(),t_)},l=()=>`${e}-state`,n=G=>{let d=".jsonl",i=l()+(G?"":d);return uG(I(),i,G?`${G}${d}`:"")};return{load:async G=>{let d=n(G);if(!$7(d))return[];try{let b=(await l_.runExclusive(d,()=>G$e(d,"utf8"))).trim().split(`
|
|
1415
1415
|
`).filter(h=>h.trim()),m=[];for(let h=0;h<b.length;h++)try{let p=JSON.parse(b[h]),Z=t(p);m.push(Z)}catch(p){throw new Error(`Invalid event at line ${h+1} in ${d}: ${p}`)}return m}catch(i){throw new Error(`Failed to read JSONL from ${d}: ${i}`)}},append:async(G,d)=>{let i=n(d),b=Array.isArray(G)?G:[G];try{await i$e(i);let m=b.map(h=>JSON.stringify(h)).join(`
|
|
1416
1416
|
`)+`
|