@github/copilot 0.0.350-19 → 0.0.350-20
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 +6 -6
- package/package.json +2 -2
package/index.js
CHANGED
|
@@ -1996,7 +1996,7 @@ Pay attention to the following when using it:
|
|
|
1996
1996
|
`}var MFn=nwe.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function _Fn(){let t={};for(let e of MFn){let l=nwe.env[e];l!==void 0&&(l.startsWith("()")||(t[e]=l))}return t}var lwe=class{constructor(e){this._abortController=new AbortController,this._readBuffer=new twe,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new UFn)}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,a,I,s;this._process=(0,JDt.default)(this._serverParams.command,(n=this._serverParams.args)!==null&&n!==void 0?n:[],{env:{..._Fn(),...this._serverParams.env},stdio:["pipe","pipe",(r=this._serverParams.stderr)!==null&&r!==void 0?r:"inherit"],shell:!1,signal:this._abortController.signal,windowsHide:nwe.platform==="win32"&&DFn(),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)}),(a=this._process.stdin)===null||a===void 0||a.on("error",o=>{var d;(d=this.onerror)===null||d===void 0||d.call(this,o)}),(I=this._process.stdout)===null||I===void 0||I.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=LDt(e);this._process.stdin.write(r)?l():this._process.stdin.once("drain",l)})}};function DFn(){return"type"in nwe}c();c();var rwe=class extends TransformStream{constructor({onError:e,onRetry:l,onComment:n}={}){let r;super({start(a){r=PVe({onEvent:I=>{a.enqueue(I)},onError(I){e==="terminate"?a.error(I):typeof e=="function"&&e(I)},onRetry:l,onComment:n})},transform(a){r.feed(a)}})}};var zFn={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Bue=class extends Error{constructor(e,l){super(`Streamable HTTP error: ${l}`),this.code=e}},awe=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:zFn}async _authThenStart(){var e;if(!this._authProvider)throw new cN("No auth provider");let l;try{l=await wL(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 cN;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:a}=e;try{let I=await this._commonHeaders();I.set("Accept","text/event-stream"),a&&I.set("last-event-id",a);let s=await((l=this._fetch)!==null&&l!==void 0?l:fetch)(this._url,{method:"GET",headers:I,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 Bue(s.status,`Failed to open SSE stream: ${s.statusText}`)}this._handleSseStream(s.body,e,!0)}catch(I){throw(r=this.onerror)===null||r===void 0||r.call(this,I),I}}_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 a=this._getNextReconnectionDelay(l);setTimeout(()=>{this._startOrAuthSse(e).catch(I=>{var s;(s=this.onerror)===null||s===void 0||s.call(this,new Error(`Failed to reconnect SSE stream: ${I instanceof Error?I.message:String(I)}`)),this._scheduleReconnection(e,l+1)})},a)}_handleSseStream(e,l,n){if(!e)return;let{onresumptiontoken:r,replayMessageId:a}=l,I;(async()=>{var o,d,u,b;try{let p=e.pipeThrough(new TextDecoderStream).pipeThrough(new rwe).getReader();for(;;){let{value:h,done:g}=await p.read();if(g)break;if(h.id&&(I=h.id,r?.(h.id)),!h.event||h.event==="message")try{let N=gL.parse(JSON.parse(h.data));a!==void 0&&zde(N)&&(N.id=a),(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:I,onresumptiontoken:r,replayMessageId:a},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 cN("No auth provider");if(await wL(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new cN("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,a,I;try{let{resumptionToken:s,onresumptiontoken:o}=l||{};if(s){this._startOrAuthSse({resumptionToken:s,replayMessageId:nVe(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=Sue(b),await wL(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new cN;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){zTt(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 g=(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(g)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=>gL.parse(w)):[gL.parse(y)];for(let w of Y)(a=this.onmessage)===null||a===void 0||a.call(this,w)}else throw new Bue(-1,`Unexpected content type: ${N}`)}catch(s){throw(I=this.onerror)===null||I===void 0||I.call(this,s),s}}get sessionId(){return this._sessionId}async terminateSession(){var e,l,n;if(this._sessionId)try{let r=await this._commonHeaders(),a={...this._requestInit,method:"DELETE",headers:r,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},I=await((l=this._fetch)!==null&&l!==void 0?l:fetch)(this._url,a);if(!I.ok&&I.status!==405)throw new Bue(I.status,`Failed to terminate session: ${I.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 Iwe=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 Gqe(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?.())}},Gqe=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 swe=class{createTransport(e){switch(e.type){case"stdio":{let l=new lwe({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 awe(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"sse":return new $Ve(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"memory":return new Iwe(e.server);default:throw new Error(`Unsupported transport type: ${e.type}`)}}};c();var Oue="blackbird-mcp-server",QL="github-mcp-server",pqe="playwright",Tue=[Oue];function mq(t){return t.type===void 0||t.type.toLowerCase()==="local"||t.type.toLowerCase()==="stdio"}function FL(t){return Uue(t)||Mue(t)}function Uue(t){return t.type?.toLowerCase()==="http"}function Mue(t){return t.type?.toLowerCase()==="sse"}function _ue(t){return t.type?.toLowerCase()==="memory"}var hqe=class extends PFn{constructor(l,n){super({decodeStrings:!1});this.serverName=l;this.logger=n}_write(l,n,r){try{let a=l.toString();this.logger.log(`[mcp server ${this.serverName} stderr] ${a}`),r()}catch(a){r(a instanceof Error?a:new Error(String(a)))}}},owe=class{constructor(e,l=new DVe,n=new swe,r="indirect"){this.logger=e;this.clientFactory=l;this.transportFactory=n;this.envValueMode=r}clients={};transports={};async startLocalMcpClient(e,l,n,r,a){this.logger.log(`Starting MCP client for ${e} with command: ${n} and args: ${r}`);let I=new hqe(e,this.logger),s={type:"stdio",command:n,args:r,env:{...l,PATH:process.env.PATH},stderr:I,cwd:a},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=a=>{this.logger.error(`MCP client for ${e} errored ${a}`)},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,a]of Object.entries(this.clients)){let I=[];try{this.logger.log(`Fetching tools from client: ${r}`);let s=await a.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=i0e(r,b.name),g=`${r}-${b.name}`,N;typeof d=="string"?N=hTe(d):N=hTe(d?.[b.name]??"hidden_characters"),n[`${r}/${b.name}`]={name:g,namespacedName:`${r}/${b.name}`,title:b.title??b.annotations?.title??b.name,description:b.description??g,input_schema:b.inputSchema,readOnly:b.annotations?.readOnlyHint,safeForTelemetry:{name:!!(e?.mcpServers[r].isDefaultServer||h),inputsNames:!!e?.mcpServers[r].isDefaultServer},filterMode:N},I.push(b.name),this.logger.log(`Tool ${b.name} added to tools list for client: ${r}`)}this.logger.log(`Successfully retrieved ${I.length} tools from client: ${r}`);let u=a.getServerVersion();await this.logServerSuccessWithTools(r,I,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(!Tue.includes(e)&&r)try{let a=l.map(o=>`- ${o}`).join(`
|
|
1997
1997
|
`),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
|
|
1998
1998
|
|
|
1999
|
-
${a}`;await r.createOrUpdateMCPStartupToolCall({serverName:e,content:s}),this.logger.log(`Updated session log for ${e} with ${l.length} tools`)}catch(a){this.logger.error(`Failed to update session log for ${e}: ${a}`)}}};c();c();var CL=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,a,I)=>{let o=l[r||I];return o!==void 0?o:a!==void 0?a: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,a]of Object.entries(e)){let I=t.resolveArray([a],l);n[r]=I[0]}return n}static resolveLocalServerConfig(e,l){let n=t.resolveString(e.command,l),r=t.resolveArray(e.args,l),a;return e.cwd&&(a=t.resolveString(e.cwd,l)),{...e,command:n,args:r,cwd:a}}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 Aqe={mcpServers:{}},iwe=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"),Aqe;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"),Aqe;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}`),Aqe}}configureGitHubMcp(e,l){this.remoteEnabled?this.configureRemoteGitHubMcp(e,l):this.configureLocalGitHubMcp(e)}configureRemoteGitHubMcp(e,l){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 a={type:"http",url:this.getCapiMcpUrl(),headers:r,tools:["*"],isDefaultServer:!0};this.setDefaultGitHubFilterMapping(a);let I=e.mcpServers[QL]??void 0;if(I&&FL(I)){let s=structuredClone(I);this.logger.log("GitHub MCP server configuration already provided by user, skipping default remote configuration"),I.headers===void 0&&(I.headers={}),s.headers={...r,...I.headers},s.isDefaultServer=!0,this.setDefaultGitHubFilterMapping(s),e.mcpServers[QL]=s}else this.logger.log("Using default remote GitHub MCP server configuration"),e.mcpServers[QL]=a}configureLocalGitHubMcp(e){if(e.mcpServers[QL]){this.logger.log("Using user-provided GitHub MCP server configuration");let l=e.mcpServers[QL]??{};mq(l)&&!l.command&&(e.mcpServers[QL]={...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[QL]=l}}setDefaultGitHubFilterMapping(e){e.filterMapping??={get_issue:"markdown",get_issue_comments:"markdown",get_pull_request:"markdown",get_pull_request_comments:"markdown",get_pull_request_reviews:"markdown"}}configurePlaywrightMcp(e){if(!e.mcpServers[pqe]){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:[...qUe,"--allowed-origins","localhost;localhost:*;127.0.0.1;127.0.0.1:*"],tools:["*"],isDefaultServer:!0};e.mcpServers[pqe]=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 a={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[Oue]=a}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[Oue]=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[Oue]=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 mq(e)||Uue(e)||Mue(e)||_ue(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&&!mq(l)&&!_ue(l)?(this.logger.error(`Unsupported server type "${l.type}" for server "${e}". Only "Local", "STDIO", or "Memory" are supported.`),!1):l.tools?mq(l)&&!this.isValidLocalServerConfig(l)?(this.logger.error(`Invalid local server configuration for "${e}". Please ensure 'command' and 'args' are provided.`),!1):(Uue(l)||Mue(l))&&!this.isValidRemoteServerConfig(l)?(this.logger.error(`Invalid remote server configuration for "${e}". Please ensure 'url' is provided.`),!1):_ue(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=CL.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=CL.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(I){this.logger.error(`Failed to handle Python module for ${e}: ${I}`)}let r=this.buildEnvironment(n),a=CL.resolveLocalServerConfig(n,r);this.logger.log(`Starting MCP client for ${e} with command: ${a.command} and args: ${a.args}`),a.cwd&&this.logger.log(`cwd: ${a.cwd}`);try{await this.registry.startLocalMcpClient(e,r,a.command,a.args,a.cwd),this.logger.log(`Started MCP client for ${e}`)}catch(I){throw this.logger.error(`Failed to start MCP client for ${e}: ${I}`),I}}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 a=["run",r];for(let I=n+2;I<l.length;I++)a.push(l[I]);for(let I=0;I<n;I++)a.push(l[I]);return{...e,command:"pipx",args:a}}buildEnvironment(e){let l={};if(e.env)if(this.envValueMode==="direct")for(let[n,r]of Object.entries(e.env))l[n]=CL.resolveString(r,process.env);else for(let[n,r]of Object.entries(e.env)){let a=r.trim(),I=a;if(a.includes("$")&&(I=CL.resolveString(a,process.env)),I!==a){l[n]=I;continue}process.env[a]!==void 0&&(l[n]=process.env[a])}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}Tue.includes(e)||await this.sessionClient?.createOrUpdateMCPStartupToolCall({serverName:e});try{mq(l)?await this.processLocalServer(e,l):Uue(l)&&this.remoteEnabled?await this.processHttpServer(e,l):Mue(l)&&this.remoteEnabled?await this.processSseServer(e,l):_ue(l)&&await this.processInMemoryServer(e,l)}catch(n){Tue.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 bq=class{constructor(e,l,n,r="indirect"){this.logger=e;let a;if(typeof l=="string"){if(a=JSON.parse(l),typeof a!="object")throw new Error("Invalid MCP configuration: must be an object");if(a===null||!("mcpServers"in a)||typeof a.mcpServers!="object")throw new Error("Invalid MCP configuration: missing or invalid mcpServers property");this.config=a}else this.config=l;this.disabledServers=new Set(n||[]),this.registry=new owe(this.logger,void 0,void 0,r),this.processor=new iwe(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 eoe(e,l,!0);let r=[];for(let a of Object.keys(this.registry.clients)){let I=await this.transport.loadTools({mcpClient:this.registry.clients[a],clientName:a,tools:this.config.mcpServers[a]?.tools||["*"],filterMapping:this.config.mcpServers[a]?.filterMapping||"hidden_characters"},n);r.push(...I)}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 jFn="/login/device/code",KFn="/login/oauth/access_token",xDt="Ov23ctDVkRmgkPke0Mmm",fL="https://github.com",vL=class extends Error{constructor(l,n){super(n);this.status=l;this.message=n;this.name="GitHubApiError"}};function qO(t){let e=new URL(t);return e.hostname.startsWith("api.")||(e.hostname="api."+e.hostname),e.href}async function SDt(t){let e=new URL(jFn,t),l=await fetch(e.href,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({client_id:xDt,scope:"user:email,read:user,repo,workflow"})});if(!l.ok)throw new vL(l.status,`Failed to request device code: ${l.statusText}`);return await l.json()}async function BDt(t,e){let l=new URL(KFn,t),n=await fetch(l.href,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({client_id:xDt,device_code:e,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})});if(!n.ok)throw new vL(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 Gq(t,e){let l=new URL("/user",qO(t)),n=await fetch(l.href,{headers:{Authorization:`Bearer ${e}`,Accept:"application/json"}});if(!n.ok)throw new vL(n.status,`Failed to fetch user info: ${n.statusText}`);return(await n.json()).login}async function R0(t,e){let l=`
|
|
1999
|
+
${a}`;await r.createOrUpdateMCPStartupToolCall({serverName:e,content:s}),this.logger.log(`Updated session log for ${e} with ${l.length} tools`)}catch(a){this.logger.error(`Failed to update session log for ${e}: ${a}`)}}};c();c();var CL=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,a,I)=>{let o=l[r||I];return o!==void 0?o:a!==void 0?a: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,a]of Object.entries(e)){let I=t.resolveArray([a],l);n[r]=I[0]}return n}static resolveLocalServerConfig(e,l){let n=t.resolveString(e.command,l),r=t.resolveArray(e.args,l),a;return e.cwd&&(a=t.resolveString(e.cwd,l)),{...e,command:n,args:r,cwd:a}}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 Aqe={mcpServers:{}},iwe=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"),Aqe;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"),Aqe;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}`),Aqe}}configureGitHubMcp(e,l){this.remoteEnabled?this.configureRemoteGitHubMcp(e,l):this.configureLocalGitHubMcp(e)}configureRemoteGitHubMcp(e,l){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 a={type:"http",url:this.getCapiMcpUrl(),headers:r,tools:["*"],isDefaultServer:!0};this.setDefaultGitHubFilterMapping(a);let I=e.mcpServers[QL]??void 0;if(I&&FL(I)){let s=structuredClone(I);this.logger.log("GitHub MCP server configuration already provided by user, skipping default remote configuration"),I.headers===void 0&&(I.headers={}),s.headers={...r,...I.headers},s.isDefaultServer=!0,this.setDefaultGitHubFilterMapping(s),e.mcpServers[QL]=s}else this.logger.log("Using default remote GitHub MCP server configuration"),e.mcpServers[QL]=a}configureLocalGitHubMcp(e){if(e.mcpServers[QL]){this.logger.log("Using user-provided GitHub MCP server configuration");let l=e.mcpServers[QL]??{};mq(l)&&!l.command&&(e.mcpServers[QL]={...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[QL]=l}}setDefaultGitHubFilterMapping(e){e.filterMapping??={get_issue:"markdown",get_issue_comments:"markdown",get_pull_request:"markdown",get_pull_request_comments:"markdown",get_pull_request_reviews:"markdown"}}configurePlaywrightMcp(e){if(!e.mcpServers[pqe]){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:[...qUe,"--allowed-origins","localhost;localhost:*;127.0.0.1;127.0.0.1:*"],tools:["*"],isDefaultServer:!0};e.mcpServers[pqe]=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 a={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[Oue]=a}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[Oue]=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[Oue]=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 mq(e)||Uue(e)||Mue(e)||_ue(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&&!mq(l)&&!_ue(l)?(this.logger.error(`Unsupported server type "${l.type}" for server "${e}". Only "Local", "STDIO", or "Memory" are supported.`),!1):l.tools?mq(l)&&!this.isValidLocalServerConfig(l)?(this.logger.error(`Invalid local server configuration for "${e}". Please ensure 'command' and 'args' are provided.`),!1):(Uue(l)||Mue(l))&&!this.isValidRemoteServerConfig(l)?(this.logger.error(`Invalid remote server configuration for "${e}". Please ensure 'url' is provided.`),!1):_ue(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=CL.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=CL.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(I){this.logger.error(`Failed to handle Python module for ${e}: ${I}`)}let r=this.buildEnvironment(n),a=CL.resolveLocalServerConfig(n,r);this.logger.log(`Starting MCP client for ${e} with command: ${a.command} and args: ${a.args}`),a.cwd&&this.logger.log(`cwd: ${a.cwd}`);try{await this.registry.startLocalMcpClient(e,r,a.command,a.args,a.cwd),this.logger.log(`Started MCP client for ${e}`)}catch(I){throw this.logger.error(`Failed to start MCP client for ${e}: ${I}`),I}}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 a=["run",r];for(let I=n+2;I<l.length;I++)a.push(l[I]);for(let I=0;I<n;I++)a.push(l[I]);return{...e,command:"pipx",args:a}}buildEnvironment(e){let l={};if(e.env)if(this.envValueMode==="direct")for(let[n,r]of Object.entries(e.env))l[n]=CL.resolveString(r,process.env);else for(let[n,r]of Object.entries(e.env)){let a=r.trim(),I=a;if(a.includes("$")&&(I=CL.resolveString(a,process.env)),I!==a){l[n]=I;continue}process.env[a]!==void 0&&(l[n]=process.env[a])}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}Tue.includes(e)||await this.sessionClient?.createOrUpdateMCPStartupToolCall({serverName:e});try{mq(l)?await this.processLocalServer(e,l):Uue(l)&&this.remoteEnabled?await this.processHttpServer(e,l):Mue(l)&&this.remoteEnabled?await this.processSseServer(e,l):_ue(l)&&await this.processInMemoryServer(e,l)}catch(n){Tue.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 bq=class{constructor(e,l,n,r="indirect"){this.logger=e;let a;if(typeof l=="string"){if(a=JSON.parse(l),typeof a!="object")throw new Error("Invalid MCP configuration: must be an object");if(a===null||!("mcpServers"in a)||typeof a.mcpServers!="object")throw new Error("Invalid MCP configuration: missing or invalid mcpServers property");this.config=a}else this.config=l;this.disabledServers=new Set(n||[]),this.registry=new owe(this.logger,void 0,void 0,r),this.processor=new iwe(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 eoe(e,l,!0);let r=[];for(let a of Object.keys(this.registry.clients)){let I=await this.transport.loadTools({mcpClient:this.registry.clients[a],clientName:a,tools:this.config.mcpServers[a]?.tools||["*"],filterMapping:this.config.mcpServers[a]?.filterMapping||"hidden_characters"},n);r.push(...I)}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 jFn="/login/device/code",KFn="/login/oauth/access_token",xDt="Ov23ctDVkRmgkPke0Mmm",fL="https://github.com",vL=class extends Error{constructor(l,n){super(n);this.status=l;this.message=n;this.name="GitHubApiError"}};function qO(t){let e=new URL(t);return e.hostname.startsWith("api.")||(e.hostname="api."+e.hostname),e.href}async function SDt(t){let e=new URL(jFn,t),l=await fetch(e.href,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({client_id:xDt,scope:"user:email,read:user,repo,workflow"})});if(!l.ok)throw new vL(l.status,`Failed to request device code: ${l.statusText}`);return await l.json()}async function BDt(t,e){let l=new URL(KFn,t),n=await fetch(l.href,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({client_id:xDt,device_code:e,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})});if(!n.ok)throw new vL(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 Gq(t,e){let l=new URL("/user",qO(t)),n=await fetch(l.href,{headers:{Authorization:`Bearer ${e}`,Accept:"application/json"}});if(!n.ok)throw new vL(n.status,`Failed to fetch user info: ${n.statusText}`);return(await n.json()).login}async function R0(t,e,l){let n=`
|
|
2000
2000
|
{
|
|
2001
2001
|
viewer {
|
|
2002
2002
|
copilotEndpoints {
|
|
@@ -2004,7 +2004,7 @@ ${a}`;await r.createOrUpdateMCPStartupToolCall({serverName:e,content:s}),this.lo
|
|
|
2004
2004
|
}
|
|
2005
2005
|
}
|
|
2006
2006
|
}
|
|
2007
|
-
`,
|
|
2007
|
+
`,r=new URL("/graphql",qO(t)),a=await fetch(r.href,{method:"POST",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},body:JSON.stringify({query:n})});if(!a.ok)throw new Error(`Failed to fetch Copilot info: ${a.status} ${a.statusText}`);let I=await a.json(),{viewer:s}=I.data;return l.debug(`Fetched Copilot URL: ${a.status} ${s.copilotEndpoints.api}`),s.copilotEndpoints.api}var qFn=zl({data:zl({viewer:zl({isEmployee:go()})})});async function ODt(t,e){let l=`
|
|
2008
2008
|
{
|
|
2009
2009
|
viewer {
|
|
2010
2010
|
isEmployee
|
|
@@ -2015,7 +2015,7 @@ ${a}`;await r.createOrUpdateMCPStartupToolCall({serverName:e,content:s}),this.lo
|
|
|
2015
2015
|
`).filter(g=>g.trim()),h=[];for(let g=0;g<p.length;g++)try{let N=JSON.parse(p[g]),y=t(N);h.push(y)}catch(N){throw new Error(`Invalid event at line ${g+1} in ${u}: ${N}`)}return h}catch(b){throw new Error(`Failed to read JSONL from ${u}: ${b}`)}},append:async(d,u)=>{let b=r(u),p=Array.isArray(d)?d:[d];try{await Qzt(b);let h=p.map(g=>JSON.stringify(g)).join(`
|
|
2016
2016
|
`)+`
|
|
2017
2017
|
`;await vwe.runExclusive(b,()=>Mvn(b,h,{mode:384}))}catch(h){throw new Error(`Failed to append to JSONL file ${b}: ${h}`)}},path:r,directoryFiles:async()=>{let d=dN(l(),n());try{let b=(await Qwe(d,{withFileTypes:!0})).filter(h=>h.isFile()&&h.name.endsWith(".jsonl")).map(h=>h.name),p=await Promise.all(b.map(async h=>{let g=dN(d,h);try{let N=await Fwe(g);return{file:h,mtime:N.mtime}}catch{return{file:h,mtime:new Date}}}));return p.sort((h,g)=>g.mtime.getTime()-h.mtime.getTime()),p.map(h=>h.file)}catch{return[]}},directoryFilesWithMetadata:async()=>{let d=dN(l(),n());try{let b=(await Qwe(d,{withFileTypes:!0})).filter(h=>h.isFile()&&h.name.endsWith(".jsonl")).map(h=>h.name),p=await Promise.all(b.map(async h=>{let g=dN(d,h);try{let N=await Fwe(g);return{file:h,mtime:N.mtime,ctime:N.ctime}}catch{return{file:h,mtime:new Date,ctime:new Date}}}));return p.sort((h,g)=>g.mtime.getTime()-h.mtime.getTime()),p}catch{return[]}},home:l,directory:n}};var vzt=zl({host:Yt(),login:Yt()}),Kvn=zl({banner:nN(["always","once","never"]).optional(),beep:go().optional(),last_logged_in_user:vzt.optional(),logged_in_users:Td(vzt).optional(),model:Yt().optional(),render_markdown:go().optional(),screen_reader:go().optional(),theme:Yt().optional(),trusted_folders:Td(Yt()).optional(),store_token_plaintext:go().optional(),stream:go().optional(),parallel_tool_execution:go().optional(),feature_flags:zl({enabled:Td(Yt()).optional()}).optional(),asked_setup_terminals:Td(Yt()).optional(),capi_hmac_key:Yt().optional(),copilot_hmac_key:Yt().optional(),copilot_integration_id:Yt().optional(),copilot_tokens:aY(Yt(),Yt()).optional(),copilot_url:Yt().optional(),staff:go().optional(),log_level:nN(["none","error","warning","info","debug","all","default"]).optional()}),qvn=aY(Yt(),_6e()),$vn=qvn.transform(t=>(0,fzt.default)(t,(e,l)=>{let n=l.toLowerCase();return n==="github_copilot_integration_id"?"copilot_integration_id":n})),efn=$vn.pipe(Kvn),Sr=Hwe(efn.parse,"config");c();function kL(){return process.env.COPILOT_ENABLE_ALT_PROVIDERS==="true"}var nT=["claude-sonnet-4.5","claude-sonnet-4","claude-haiku-4.5","gpt-5"];function Hzt(t,e){let l=" ".repeat(e);return t.map(n=>`${l}- "${n}"`).join(`
|
|
2018
|
-
`)}function Nq(t){return nT.includes(t)||kL()}function lT(t,e){if(!e)return!0;let l=e.find(n=>n.id===t);return l?l.policy?l.policy.state!=="disabled":!0:!1}function Hqe(t){return nT.find(e=>lT(e,t))}function Wq(t,e){if(e&&e.length>0){let n=e.find(r=>r.id===t);if(n?.billing?.multiplier!==void 0)return n.billing.multiplier}return{"claude-sonnet-4":1,"gpt-5":1,"claude-sonnet-4.5":1,"claude-haiku-4.5":.33}[t]??1}async function rT(t,e,l,n){if(kL()&&process.env.COPILOT_AGENT_MODEL){let{model:I}=QB(process.env.COPILOT_AGENT_MODEL);if(I)return I}if(t){if(lT(t,l))return t;n?.warning(`Model '${t}' from CLI argument is not available. Falling back to next option.`)}if(e){let I=await e?.getSelectedModel?.();if(I){if(lT(I,l))return I;n?.warning(`Model '${I}' from session is not available. Falling back to next option.`)}}let r=process.env.COPILOT_MODEL;if(r&&Nq(r)){if(lT(r,l))return r;n?.warning(`Model '${r}' from COPILOT_MODEL environment variable is not available. Falling back to next option.`)}try{let s=(await Sr.load()||{}).model;if(typeof s=="string"&&s&&Nq(s)){if(lT(s,l))return s;n?.warning(`Model '${s}' from config file is not available. Falling back to default.`)}}catch{}let a=Hqe(l);return a&&n?.info(`Using default model: ${a}`),a}c();function zw(t){return"host"in t?t.host:"https://github.com"}function Kue(t){return dY(t,{onHMACAuthInfo:()=>"Logged in with HMAC",onEnvAuthInfo:e=>`Logged in with ${e.envVar} as user: ${e.login}`,onUserAuthInfo:e=>`Logged in as user: ${jue(e)}`,onGhCliAuthInfo:e=>`Logged in with gh as user: ${jue(e)}`,onApiKeyAuthInfo:e=>`Logged in with API key to ${e.host}`})}function que(t){return dY(t,{onHMACAuthInfo:()=>"Unknown (via HMAC)",onEnvAuthInfo:e=>`${e.login} (via ${e.envVar})`,onUserAuthInfo:e=>jue(e),onGhCliAuthInfo:e=>`${e.login} (via gh)`,onApiKeyAuthInfo:e=>`${e.host} (via API key)`})}function Xqe(t,e){return dY(t,{onHMACAuthInfo:l=>e.type==="hmac"&&l.hmac===e.hmac,onEnvAuthInfo:l=>e.type==="env"&&l.envVar===e.envVar&&l.login===e.login,onUserAuthInfo:l=>e.type==="user"&&aT(l,e),onGhCliAuthInfo:l=>e.type==="gh-cli"&&aT(l,e),onApiKeyAuthInfo:l=>e.type==="api-key"&&l.host===e.host&&l.apiKey===e.apiKey})}async function Xzt(t,e){let l=await t.getAllAuthAvailable(),n=">",r="-";return l.map(a=>`${e&&Xqe(a.authInfo,e)?n:r} ${que(a.authInfo)}`)}function jue(t){return t.host!==fL?`${t.login} (${t.host})`:t.login}async function kzt(){let t=await Sr.load()||{};return t?.last_logged_in_user??t.logged_in_users?.[0]??void 0}async function kqe(t){await Sr.writeKey("last_logged_in_user",t)}async function kwe(){return(await Sr.load()||{}).logged_in_users||[]}async function Lzt(t,e){await Sr.writeKey("last_logged_in_user",t),await Sr.writeKey("logged_in_users",e)}async function Jzt(t){let e=await kwe();return e.some(n=>aT(n,t))?(e=e.filter(n=>!aT(n,t)),await Lzt(void 0,e),e.length>0):!1}async function xzt(t){let e=await kwe();e.some(n=>aT(n,t))||(e.push(t),await Lzt(t,e))}function aT(t,e){return t.login===e.login&&t.host===e.host}c();async function Szt(t,e){try{let l=tfn(),n=await e.execReturn("gh",["auth","token","--hostname",l],{silent:!0,ignoreReturnCode:!0});if(n.exitCode!==0||!n.stdout.trim()){let a=`Failed to retrieve GitHub token from CLI (exit code: ${n.exitCode})`,I=n.stderr?.trim();return I?t.debug(`${a}: ${I}`):t.debug(a),null}let r=n.stdout.trim();return r.startsWith("ghp_")?(t.debug("GitHub token is a classic PAT"),null):(t.debug("GitHub CLI authenticated with valid token"),{token:r,host:l})}catch(l){let n=`Error checking GitHub CLI: ${l}`;return l&&typeof l=="object"&&"stderr"in l&&typeof l.stderr=="string"&&(n+=` (stderr: ${l.stderr.trim()})`),t.debug(n),null}}function tfn(){return process.env.GH_HOST||"github.com"}function Lqe(){let t=process.env.GH_HOST;return t?t.startsWith("https://")?t:`https://${t}`:fL}c();import{existsSync as Tzt}from"fs";var Lwe="copilot-cli",Jwe;async function xwe(){if(Jwe)return Jwe;let t=await Promise.resolve().then(()=>nt(Ozt(),1));return Jwe=t.default||t,Jwe}var eme=(t,e)=>{if(!(!t||!e))return`${t}:${e}`},rfn=()=>{let t=new Map,e=async(o,d)=>{let u=eme(o,d);if(u)if(Tzt(Sr.path()))try{let h=(await Sr.load())?.copilot_tokens?.[u];t.set(u,h&&h.trim()!==""?h:void 0)}catch{t.set(u,void 0)}else t.set(u,void 0)},l=async()=>{if(Tzt(Sr.path()))try{let d=(await Sr.load())?.copilot_tokens;if(d){let u=Object.values(d).filter(b=>b&&b.trim()!=="");if(u.length>0)return u[0]}}catch{return}},n=async(o,d)=>{let u=eme(o,d);if(!u)return;if(t.has(u))return t.get(u);if((await Sr.load())?.store_token_plaintext)return await e(o,d),t.get(u);try{let h=await(await xwe()).getPassword(Lwe,u);h?t.set(u,h):await e(o,d)}catch{await e(o,d)}return t.get(u)},r=async()=>{if(t.size>0)return t.values().next().value;if((await Sr.load())?.store_token_plaintext)return await l();let d;try{d=await(await xwe()).findPassword(Lwe)}catch{}return d||(d=await l()),d},a=async(o,d)=>{let u=eme(o,d);if(u){t.delete(u);try{return(await xwe()).deletePassword(Lwe,u)}catch{let h=(await Sr.load())?.copilot_tokens??{};return delete h[u],await Sr.writeKey("copilot_tokens",h),Promise.resolve(!0)}}},I=async(o,d,u)=>{if(!o)throw new Error("No token provided to store");let b=eme(d,u);if(!b)return;if(t.set(b,o),(await Sr.load())?.store_token_plaintext)return await s(d,u),!0;try{return await(await xwe()).setPassword(Lwe,b,o),!0}catch{return!1}},s=async(o,d)=>{let u=eme(o,d);if(!u)return;let b=t.get(u);if(!b)return;let h=(await Sr.load())?.copilot_tokens??{};h[u]=b,await Sr.writeKey("copilot_tokens",h)};return{getToken:n,getAnyToken:r,removeToken:a,storeToken:I,storeCurrentTokenInConfig:s}},Rf=rfn();function dY(t,e){switch(t.type){case"hmac":return e.onHMACAuthInfo(t);case"env":return e.onEnvAuthInfo(t);case"user":return e.onUserAuthInfo(t);case"gh-cli":return e.onGhCliAuthInfo(t);case"api-key":return e.onApiKeyAuthInfo(t);default:{let l=t;throw new Error(`unexpected auth info type: ${JSON.stringify(t)}`)}}}async function ry(t){return await dY(t,{onHMACAuthInfo:async()=>process.env.GITHUB_MCP_SERVER_TOKEN,onEnvAuthInfo:async e=>e.token,onUserAuthInfo:async e=>await Rf.getToken(e.host,e.login)||void 0,onGhCliAuthInfo:async e=>e.token,onApiKeyAuthInfo:async()=>{}})}var Jqe=class{currentAuthInfo=null;logger=new xd;authCallbacks=[];setLogger(e){this.logger=e}onAuthChange(e){this.authCallbacks.push(e)}removeAuthCallback(e){let l=this.authCallbacks.indexOf(e);l>-1&&this.authCallbacks.splice(l,1)}async notifyAuthChange(e,l){this.currentAuthInfo=e;for(let n of this.authCallbacks)try{await n(e,l)}catch(r){this.logger.error(`Error in auth change callback: ${r}`)}}async tryHMACLogin(){let e=await Sr.load()||{},l=e.copilot_hmac_key||e.capi_hmac_key||process.env.CAPI_HMAC_KEY||process.env.COPILOT_HMAC_KEY;return l?[{authInfo:{type:"hmac",hmac:l}}]:[]}async tryGitHubTokenLogin(){let e=process.env.GH_TOKEN||process.env.GITHUB_TOKEN;if(!e)return[];if(e.startsWith("ghp_"))return this.logger.error("Classic PATs are not supported. Please use fine-grained PATs or other supported token types."),[];if(!e.startsWith("gho_")&&!e.startsWith("ghu_")&&!e.startsWith("github_pat_"))return this.logger.error("Unsupported token type, ignoring."),[];let l=Lqe();try{let n=await Gq(l,e);return[{authInfo:{type:"env",host:l,login:n,token:e,envVar:process.env.GH_TOKEN?"GH_TOKEN":"GITHUB_TOKEN"},token:e}]}catch(n){n instanceof vL?this.logger.error(`Failed to fetch PAT user login (${n.status}): ${n.message}`):this.logger.error("Failed to fetch PAT user login")}return[]}async tryGhCliTokenLogin(){let e=new uW(this.logger),l=await Szt(this.logger,e);if(!l)return[];let{token:n,host:r}=l;try{let a=r.startsWith("https://")?r:`https://${r}`,I=await Gq(a,n);return[{authInfo:{type:"gh-cli",host:a,login:I,token:n},token:n}]}catch(a){a instanceof vL?this.logger.error(`Failed to fetch GitHub CLI user login (${a.status}): ${a.message}`):this.logger.error("Failed to fetch GitHub CLI user login")}return[]}async tryApiKeyLogin(){if(!kL())return[];let e=process.env.ANTHROPIC_API_KEY||process.env.AZURE_OPENAI_API_KEY,l=process.env.ANTHROPIC_API_KEY?"https://api.anthropic.com":process.env.AZURE_OPENAI_API_KEY?process.env.AZURE_OPENAI_API_ENDPOINT||process.env.OPENAI_BASE_URL||"https://api.openai.com":void 0;return!e||!l?[]:[{authInfo:{type:"api-key",apiKey:e,host:l}}]}async tryLoginToken(){let e=await kzt(),l;if(e){if(l=await Rf.getToken(e.host,e.login),!l||l.trim()==="")return[]}else{if(l=await Rf.getAnyToken(),!l||l.trim()==="")return[];let n=Lqe();e={host:n,login:await Gq(n,l)}}return[{authInfo:{type:"user",host:e.host,login:e.login},token:l}]}async getAllGitHubLoginTokens(){let l=(await this.tryGitHubTokenLogin()).at(0),n=await kwe(),r=[];for(let a of n){if(l?.authInfo.type==="user"&&aT(a,l.authInfo))continue;let I=await Rf.getToken(a.host,a.login);I&&r.push({authInfo:{type:"user",host:a.host,login:a.login},token:I})}return r}async getAllAuthAvailable(){let e=[],l=this.getPrioritizedAuthMethods(!0);for(let n of l){let r=await n();e.push(...r)}return e}getPrioritizedAuthMethods(e){return[this.tryHMACLogin.bind(this),this.tryApiKeyLogin.bind(this),this.tryGitHubTokenLogin.bind(this),e?this.getAllGitHubLoginTokens.bind(this):this.tryLoginToken.bind(this),this.tryGhCliTokenLogin.bind(this)]}async loadAuthInfo(){let e=this.currentAuthInfo!==null;this.currentAuthInfo=null;let l=this.getPrioritizedAuthMethods(!1);for(let n of l){let r=await n();if(r.length>0){let{authInfo:a,token:I}=r[0];a.type==="user"&&kqe({host:a.host,login:a.login}),this.currentAuthInfo=a,e||await this.notifyAuthChange(a,I);return}}}async getCurrentAuthInfo(){return this.currentAuthInfo||await this.loadAuthInfo(),this.currentAuthInfo}async loginUser(e,l){let n={host:e,login:l},r={type:"user",...n};await xzt(n);let a=await ry(r);await this.notifyAuthChange(r,a)}async switchToAuth(e){this.currentAuthInfo=e.authInfo,e.authInfo.type==="user"&&await kqe({host:e.authInfo.host,login:e.authInfo.login}),await this.notifyAuthChange(e.authInfo,e.token)}async logout(){if(!this.currentAuthInfo)return!1;let e=await dY(this.currentAuthInfo,{onHMACAuthInfo:async()=>!1,onEnvAuthInfo:async()=>!1,onUserAuthInfo:async l=>(await Rf.removeToken(l.host,l.login),await Jzt(l)),onGhCliAuthInfo:async()=>!1,onApiKeyAuthInfo:async()=>!1});return await this.notifyAuthChange(null),e}},afn=new Jqe,Swe=afn;var Yf=class t extends bq{constructor(l,n,r,a,I){super(l,n,a,"direct");this.exec=r;this.enableAllGithubMcpTools=I??!1}static GITHUB_SERVER_NAME="github-mcp-server";static CLI_DEFAULT_GITHUB_MCP_TOOLS=["get_file_contents","search_code","search_repositories","list_branches","list_commits","get_commit","get_issue","list_issues","get_issue_comments","search_issues","pull_request_read","list_pull_requests","search_pull_requests","list_workflow_runs","get_job_logs","get_workflow_run","list_workflows","get_workflow_run_logs","web_search","search_users"];static BUILTIN_SERVERS=[t.GITHUB_SERVER_NAME];static getBuiltInServerNames(){return[...t.BUILTIN_SERVERS]}hasUserConfiguredGitHubServer=!1;lastGitHubAuthInfo=null;githubMcpToken;enableAllGithubMcpTools;async configureGitHubAuth(l){if(this.isServerDisabled(t.GITHUB_SERVER_NAME))return this.logger.debug("GitHub MCP server is disabled, skipping auto-configuration"),!1;if(this.hasUserConfiguredGitHubServer)return this.logger.debug("User has explicitly configured github-mcp-server, ignoring auth changes"),!1;if(await this.shouldHandleGitHubAuth(l)){let r=await ry(l);if(!r)return this.logger.debug("No token available for GitHub authentication"),!1;if(this.lastGitHubAuthInfo=l,r===this.githubMcpToken)return!1;this.githubMcpToken=r;let a=await this.createGitHubServerConfig(r,l);try{return await this.restartServer(t.GITHUB_SERVER_NAME,a),this.logger.log("GitHub MCP server configured after authentication"),!0}catch(I){return this.logger.error(`Failed to configure GitHub MCP server after auth: ${I}`),!1}}return!1}async removeGitHubAuth(){if(this.hasUserConfiguredGitHubServer)return this.logger.debug("User has explicitly configured github-mcp-server, ignoring auth changes"),!1;this.githubMcpToken=void 0;try{return this.isServerRunning(t.GITHUB_SERVER_NAME)?(await this.stopServer(t.GITHUB_SERVER_NAME),this.logger.debug("Removed GitHub MCP server"),!0):!1}catch(l){return this.logger.error(`Failed to remove GitHub server: ${l}`),!1}}async shouldHandleGitHubAuth(l){return await dY(l,{onHMACAuthInfo:async()=>!!process.env.GITHUB_MCP_SERVER_TOKEN,onEnvAuthInfo:async()=>!0,onUserAuthInfo:async()=>!0,onGhCliAuthInfo:async()=>!0,onApiKeyAuthInfo:async()=>!1})}async createGitHubServerConfig(l,n){let r="https://api.githubcopilot.com/mcp/readonly";try{let a=await dY(n,{onHMACAuthInfo:async()=>"https://github.com",onEnvAuthInfo:async s=>s.host,onUserAuthInfo:async s=>s.host,onGhCliAuthInfo:async s=>s.host,onApiKeyAuthInfo:async s=>s.host}),I=await R0(a,l);r=new URL("/mcp/readonly",I).toString(),this.logger.log(`Using Copilot API endpoint: ${r}`)}catch(a){this.logger.error(`Failed to fetch Copilot URL, using default: ${a}`)}return{type:"http",url:r,headers:{Authorization:"Bearer "+l,"X-MCP-Toolsets":"repos,issues,users,pull_requests,code_security,secret_protection,actions,web_search","X-MCP-Host":"copilot-cli"},tools:this.enableAllGithubMcpTools?["*"]:t.CLI_DEFAULT_GITHUB_MCP_TOOLS,isDefaultServer:!0,filterMapping:{get_issue:"markdown",get_issue_comments:"markdown",get_pull_request:"markdown",get_pull_request_comments:"markdown",get_pull_request_reviews:"markdown"}}}async injectDefaultServers(l){if(l.mcpServers[t.GITHUB_SERVER_NAME]){this.hasUserConfiguredGitHubServer=!0,this.logger.debug("User has already configured github-mcp-server, skipping auto-configuration");return}}async startBuiltInServer(l){l===t.GITHUB_SERVER_NAME&&!this.hasUserConfiguredGitHubServer?this.lastGitHubAuthInfo?(this.logger.log("Attempting to configure GitHub MCP server using stored authentication"),await this.configureGitHubAuth(this.lastGitHubAuthInfo)?this.logger.log("GitHub MCP server configured successfully after enabling"):this.logger.log("GitHub MCP server enabled but could not be configured - authentication may be invalid or insufficient")):this.logger.log("GitHub MCP server enabled - will be configured automatically when authentication becomes available"):await super.startBuiltInServer(l)}};c();c();var Ifn=zl({commandHistory:Td(Yt())}),xqe=Xwe(Ifn.parse,"command-history");var sfn=50,Sqe=class{commandHistory=[];historyIndex=-1;isNavigatingHistory=!1;unSubmittedCommand=null;async initialize(){try{let e=await xqe.load();this.commandHistory=e?.commandHistory||[],this.resetNavigation()}catch{this.commandHistory=[]}}async addCommand(e){this.commandHistory=this.commandHistory.filter(l=>l!==e),this.commandHistory.unshift(e),this.commandHistory=this.commandHistory.slice(0,sfn),this.resetNavigation(),this.unSubmittedCommand=null,await this.saveHistory()}async updateCurrentCommand(e){this.historyIndex!==-1?(this.commandHistory[this.historyIndex]=e,await this.saveHistory()):this.unSubmittedCommand=e}navigateUp(e){if(this.commandHistory.length===0)return;let l=this.historyIndex+1;if(l<this.commandHistory.length){this.historyIndex=l,this.isNavigatingHistory=!0;let n=this.getCurrentHistoryItem();n&&e.setText(n)}}navigateDown(e){if(this.historyIndex===-1)return;if(this.historyIndex===0)this.resetNavigation();else{let n=this.historyIndex-1;this.historyIndex=n,this.isNavigatingHistory=!0}let l=this.getCurrentHistoryItem();l?(e.setText(l),e.setCursorPosition(0)):e.clear()}resetNavigation(){this.historyIndex=-1,this.isNavigatingHistory=!1}getHistoryIndex(){return this.historyIndex}getHistory(){return this.commandHistory}getCurrentHistoryItem(){return this.historyIndex===-1?this.unSubmittedCommand?this.unSubmittedCommand:void 0:this.commandHistory[this.historyIndex]}isNavigating(){return this.isNavigatingHistory}setNavigating(e){this.isNavigatingHistory=e}async saveHistory(){try{await xqe.write({commandHistory:this.commandHistory})}catch{}}},uY=new Sqe;c();c();function Mzt(t,e){var l=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),l.push.apply(l,n)}return l}function _zt(t){for(var e=1;e<arguments.length;e++){var l=arguments[e]!=null?arguments[e]:{};e%2?Mzt(Object(l),!0).forEach(function(n){ofn(t,n,l[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(l)):Mzt(Object(l)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(l,n))})}return t}function ofn(t,e,l){return e=ifn(e),e in t?Object.defineProperty(t,e,{value:l,enumerable:!0,configurable:!0,writable:!0}):t[e]=l,t}function ifn(t){var e=cfn(t,"string");return typeof e=="symbol"?e:String(e)}function cfn(t,e){if(typeof t!="object"||t===null)return t;var l=t[Symbol.toPrimitive];if(l!==void 0){var n=l.call(t,e||"default");if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var dfn=zzt({}),Dzt=dfn;function zzt(t){return e.withOptions=l=>zzt(_zt(_zt({},t),l)),e;function e(l,...n){let r=typeof l=="string"?[l]:l.raw,{escapeSpecialCharacters:a=Array.isArray(l),trimWhitespace:I=!0}=t,s="";for(let u=0;u<r.length;u++){let b=r[u];a&&(b=b.replace(/\\\n[ \t]*/g,"").replace(/\\`/g,"`").replace(/\\\$/g,"$").replace(/\\\{/g,"{")),s+=b,u<n.length&&(s+=n[u])}let o=s.split(`
|
|
2018
|
+
`)}function Nq(t){return nT.includes(t)||kL()}function lT(t,e){if(!e)return!0;let l=e.find(n=>n.id===t);return l?l.policy?l.policy.state!=="disabled":!0:!1}function Hqe(t){return nT.find(e=>lT(e,t))}function Wq(t,e){if(e&&e.length>0){let n=e.find(r=>r.id===t);if(n?.billing?.multiplier!==void 0)return n.billing.multiplier}return{"claude-sonnet-4":1,"gpt-5":1,"claude-sonnet-4.5":1,"claude-haiku-4.5":.33}[t]??1}async function rT(t,e,l,n){if(kL()&&process.env.COPILOT_AGENT_MODEL){let{model:I}=QB(process.env.COPILOT_AGENT_MODEL);if(I)return I}if(t){if(lT(t,l))return t;n?.warning(`Model '${t}' from CLI argument is not available. Falling back to next option.`)}if(e){let I=await e?.getSelectedModel?.();if(I){if(lT(I,l))return I;n?.warning(`Model '${I}' from session is not available. Falling back to next option.`)}}let r=process.env.COPILOT_MODEL;if(r&&Nq(r)){if(lT(r,l))return r;n?.warning(`Model '${r}' from COPILOT_MODEL environment variable is not available. Falling back to next option.`)}try{let s=(await Sr.load()||{}).model;if(typeof s=="string"&&s&&Nq(s)){if(lT(s,l))return s;n?.warning(`Model '${s}' from config file is not available. Falling back to default.`)}}catch{}let a=Hqe(l);return a&&n?.info(`Using default model: ${a}`),a}c();function zw(t){return"host"in t?t.host:"https://github.com"}function Kue(t){return dY(t,{onHMACAuthInfo:()=>"Logged in with HMAC",onEnvAuthInfo:e=>`Logged in with ${e.envVar} as user: ${e.login}`,onUserAuthInfo:e=>`Logged in as user: ${jue(e)}`,onGhCliAuthInfo:e=>`Logged in with gh as user: ${jue(e)}`,onApiKeyAuthInfo:e=>`Logged in with API key to ${e.host}`})}function que(t){return dY(t,{onHMACAuthInfo:()=>"Unknown (via HMAC)",onEnvAuthInfo:e=>`${e.login} (via ${e.envVar})`,onUserAuthInfo:e=>jue(e),onGhCliAuthInfo:e=>`${e.login} (via gh)`,onApiKeyAuthInfo:e=>`${e.host} (via API key)`})}function Xqe(t,e){return dY(t,{onHMACAuthInfo:l=>e.type==="hmac"&&l.hmac===e.hmac,onEnvAuthInfo:l=>e.type==="env"&&l.envVar===e.envVar&&l.login===e.login,onUserAuthInfo:l=>e.type==="user"&&aT(l,e),onGhCliAuthInfo:l=>e.type==="gh-cli"&&aT(l,e),onApiKeyAuthInfo:l=>e.type==="api-key"&&l.host===e.host&&l.apiKey===e.apiKey})}async function Xzt(t,e){let l=await t.getAllAuthAvailable(),n=">",r="-";return l.map(a=>`${e&&Xqe(a.authInfo,e)?n:r} ${que(a.authInfo)}`)}function jue(t){return t.host!==fL?`${t.login} (${t.host})`:t.login}async function kzt(){let t=await Sr.load()||{};return t?.last_logged_in_user??t.logged_in_users?.[0]??void 0}async function kqe(t){await Sr.writeKey("last_logged_in_user",t)}async function kwe(){return(await Sr.load()||{}).logged_in_users||[]}async function Lzt(t,e){await Sr.writeKey("last_logged_in_user",t),await Sr.writeKey("logged_in_users",e)}async function Jzt(t){let e=await kwe();return e.some(n=>aT(n,t))?(e=e.filter(n=>!aT(n,t)),await Lzt(void 0,e),e.length>0):!1}async function xzt(t){let e=await kwe();e.some(n=>aT(n,t))||(e.push(t),await Lzt(t,e))}function aT(t,e){return t.login===e.login&&t.host===e.host}c();async function Szt(t,e){try{let l=tfn(),n=await e.execReturn("gh",["auth","token","--hostname",l],{silent:!0,ignoreReturnCode:!0});if(n.exitCode!==0||!n.stdout.trim()){let a=`Failed to retrieve GitHub token from CLI (exit code: ${n.exitCode})`,I=n.stderr?.trim();return I?t.debug(`${a}: ${I}`):t.debug(a),null}let r=n.stdout.trim();return r.startsWith("ghp_")?(t.debug("GitHub token is a classic PAT"),null):(t.debug("GitHub CLI authenticated with valid token"),{token:r,host:l})}catch(l){let n=`Error checking GitHub CLI: ${l}`;return l&&typeof l=="object"&&"stderr"in l&&typeof l.stderr=="string"&&(n+=` (stderr: ${l.stderr.trim()})`),t.debug(n),null}}function tfn(){return process.env.GH_HOST||"github.com"}function Lqe(){let t=process.env.GH_HOST;return t?t.startsWith("https://")?t:`https://${t}`:fL}c();import{existsSync as Tzt}from"fs";var Lwe="copilot-cli",Jwe;async function xwe(){if(Jwe)return Jwe;let t=await Promise.resolve().then(()=>nt(Ozt(),1));return Jwe=t.default||t,Jwe}var eme=(t,e)=>{if(!(!t||!e))return`${t}:${e}`},rfn=()=>{let t=new Map,e=async(o,d)=>{let u=eme(o,d);if(u)if(Tzt(Sr.path()))try{let h=(await Sr.load())?.copilot_tokens?.[u];t.set(u,h&&h.trim()!==""?h:void 0)}catch{t.set(u,void 0)}else t.set(u,void 0)},l=async()=>{if(Tzt(Sr.path()))try{let d=(await Sr.load())?.copilot_tokens;if(d){let u=Object.values(d).filter(b=>b&&b.trim()!=="");if(u.length>0)return u[0]}}catch{return}},n=async(o,d)=>{let u=eme(o,d);if(!u)return;if(t.has(u))return t.get(u);if((await Sr.load())?.store_token_plaintext)return await e(o,d),t.get(u);try{let h=await(await xwe()).getPassword(Lwe,u);h?t.set(u,h):await e(o,d)}catch{await e(o,d)}return t.get(u)},r=async()=>{if(t.size>0)return t.values().next().value;if((await Sr.load())?.store_token_plaintext)return await l();let d;try{d=await(await xwe()).findPassword(Lwe)}catch{}return d||(d=await l()),d},a=async(o,d)=>{let u=eme(o,d);if(u){t.delete(u);try{return(await xwe()).deletePassword(Lwe,u)}catch{let h=(await Sr.load())?.copilot_tokens??{};return delete h[u],await Sr.writeKey("copilot_tokens",h),Promise.resolve(!0)}}},I=async(o,d,u)=>{if(!o)throw new Error("No token provided to store");let b=eme(d,u);if(!b)return;if(t.set(b,o),(await Sr.load())?.store_token_plaintext)return await s(d,u),!0;try{return await(await xwe()).setPassword(Lwe,b,o),!0}catch{return!1}},s=async(o,d)=>{let u=eme(o,d);if(!u)return;let b=t.get(u);if(!b)return;let h=(await Sr.load())?.copilot_tokens??{};h[u]=b,await Sr.writeKey("copilot_tokens",h)};return{getToken:n,getAnyToken:r,removeToken:a,storeToken:I,storeCurrentTokenInConfig:s}},Rf=rfn();function dY(t,e){switch(t.type){case"hmac":return e.onHMACAuthInfo(t);case"env":return e.onEnvAuthInfo(t);case"user":return e.onUserAuthInfo(t);case"gh-cli":return e.onGhCliAuthInfo(t);case"api-key":return e.onApiKeyAuthInfo(t);default:{let l=t;throw new Error(`unexpected auth info type: ${JSON.stringify(t)}`)}}}async function ry(t){return await dY(t,{onHMACAuthInfo:async()=>process.env.GITHUB_MCP_SERVER_TOKEN,onEnvAuthInfo:async e=>e.token,onUserAuthInfo:async e=>await Rf.getToken(e.host,e.login)||void 0,onGhCliAuthInfo:async e=>e.token,onApiKeyAuthInfo:async()=>{}})}var Jqe=class{currentAuthInfo=null;logger=new xd;authCallbacks=[];setLogger(e){this.logger=e}onAuthChange(e){this.authCallbacks.push(e)}removeAuthCallback(e){let l=this.authCallbacks.indexOf(e);l>-1&&this.authCallbacks.splice(l,1)}async notifyAuthChange(e,l){this.currentAuthInfo=e;for(let n of this.authCallbacks)try{await n(e,l)}catch(r){this.logger.error(`Error in auth change callback: ${r}`)}}async tryHMACLogin(){let e=await Sr.load()||{},l=e.copilot_hmac_key||e.capi_hmac_key||process.env.CAPI_HMAC_KEY||process.env.COPILOT_HMAC_KEY;return l?[{authInfo:{type:"hmac",hmac:l}}]:[]}async tryGitHubTokenLogin(){let e=process.env.GH_TOKEN||process.env.GITHUB_TOKEN;if(!e)return[];if(e.startsWith("ghp_"))return this.logger.error("Classic PATs are not supported. Please use fine-grained PATs or other supported token types."),[];if(!e.startsWith("gho_")&&!e.startsWith("ghu_")&&!e.startsWith("github_pat_"))return this.logger.error("Unsupported token type, ignoring."),[];let l=Lqe();try{let n=await Gq(l,e);return[{authInfo:{type:"env",host:l,login:n,token:e,envVar:process.env.GH_TOKEN?"GH_TOKEN":"GITHUB_TOKEN"},token:e}]}catch(n){n instanceof vL?this.logger.error(`Failed to fetch PAT user login (${n.status}): ${n.message}`):this.logger.error("Failed to fetch PAT user login")}return[]}async tryGhCliTokenLogin(){let e=new uW(this.logger),l=await Szt(this.logger,e);if(!l)return[];let{token:n,host:r}=l;try{let a=r.startsWith("https://")?r:`https://${r}`,I=await Gq(a,n);return[{authInfo:{type:"gh-cli",host:a,login:I,token:n},token:n}]}catch(a){a instanceof vL?this.logger.error(`Failed to fetch GitHub CLI user login (${a.status}): ${a.message}`):this.logger.error("Failed to fetch GitHub CLI user login")}return[]}async tryApiKeyLogin(){if(!kL())return[];let e=process.env.ANTHROPIC_API_KEY||process.env.AZURE_OPENAI_API_KEY,l=process.env.ANTHROPIC_API_KEY?"https://api.anthropic.com":process.env.AZURE_OPENAI_API_KEY?process.env.AZURE_OPENAI_API_ENDPOINT||process.env.OPENAI_BASE_URL||"https://api.openai.com":void 0;return!e||!l?[]:[{authInfo:{type:"api-key",apiKey:e,host:l}}]}async tryLoginToken(){let e=await kzt(),l;if(e){if(l=await Rf.getToken(e.host,e.login),!l||l.trim()==="")return[]}else{if(l=await Rf.getAnyToken(),!l||l.trim()==="")return[];let n=Lqe();e={host:n,login:await Gq(n,l)}}return[{authInfo:{type:"user",host:e.host,login:e.login},token:l}]}async getAllGitHubLoginTokens(){let l=(await this.tryGitHubTokenLogin()).at(0),n=await kwe(),r=[];for(let a of n){if(l?.authInfo.type==="user"&&aT(a,l.authInfo))continue;let I=await Rf.getToken(a.host,a.login);I&&r.push({authInfo:{type:"user",host:a.host,login:a.login},token:I})}return r}async getAllAuthAvailable(){let e=[],l=this.getPrioritizedAuthMethods(!0);for(let n of l){let r=await n();e.push(...r)}return e}getPrioritizedAuthMethods(e){return[this.tryHMACLogin.bind(this),this.tryApiKeyLogin.bind(this),this.tryGitHubTokenLogin.bind(this),e?this.getAllGitHubLoginTokens.bind(this):this.tryLoginToken.bind(this),this.tryGhCliTokenLogin.bind(this)]}async loadAuthInfo(){let e=this.currentAuthInfo!==null;this.currentAuthInfo=null;let l=this.getPrioritizedAuthMethods(!1);for(let n of l){let r=await n();if(r.length>0){let{authInfo:a,token:I}=r[0];a.type==="user"&&kqe({host:a.host,login:a.login}),this.currentAuthInfo=a,e||await this.notifyAuthChange(a,I);return}}}async getCurrentAuthInfo(){return this.currentAuthInfo||await this.loadAuthInfo(),this.currentAuthInfo}async loginUser(e,l){let n={host:e,login:l},r={type:"user",...n};await xzt(n);let a=await ry(r);await this.notifyAuthChange(r,a)}async switchToAuth(e){this.currentAuthInfo=e.authInfo,e.authInfo.type==="user"&&await kqe({host:e.authInfo.host,login:e.authInfo.login}),await this.notifyAuthChange(e.authInfo,e.token)}async logout(){if(!this.currentAuthInfo)return!1;let e=await dY(this.currentAuthInfo,{onHMACAuthInfo:async()=>!1,onEnvAuthInfo:async()=>!1,onUserAuthInfo:async l=>(await Rf.removeToken(l.host,l.login),await Jzt(l)),onGhCliAuthInfo:async()=>!1,onApiKeyAuthInfo:async()=>!1});return await this.notifyAuthChange(null),e}},afn=new Jqe,Swe=afn;var Yf=class t extends bq{constructor(l,n,r,a,I){super(l,n,a,"direct");this.exec=r;this.enableAllGithubMcpTools=I??!1}static GITHUB_SERVER_NAME="github-mcp-server";static CLI_DEFAULT_GITHUB_MCP_TOOLS=["get_file_contents","search_code","search_repositories","list_branches","list_commits","get_commit","get_issue","list_issues","get_issue_comments","search_issues","pull_request_read","list_pull_requests","search_pull_requests","list_workflow_runs","get_job_logs","get_workflow_run","list_workflows","get_workflow_run_logs","web_search","search_users"];static BUILTIN_SERVERS=[t.GITHUB_SERVER_NAME];static getBuiltInServerNames(){return[...t.BUILTIN_SERVERS]}hasUserConfiguredGitHubServer=!1;lastGitHubAuthInfo=null;githubMcpToken;enableAllGithubMcpTools;async configureGitHubAuth(l){if(this.isServerDisabled(t.GITHUB_SERVER_NAME))return this.logger.debug("GitHub MCP server is disabled, skipping auto-configuration"),!1;if(this.hasUserConfiguredGitHubServer)return this.logger.debug("User has explicitly configured github-mcp-server, ignoring auth changes"),!1;if(await this.shouldHandleGitHubAuth(l)){let r=await ry(l);if(!r)return this.logger.debug("No token available for GitHub authentication"),!1;if(this.lastGitHubAuthInfo=l,r===this.githubMcpToken)return!1;this.githubMcpToken=r;let a=await this.createGitHubServerConfig(r,l);try{return await this.restartServer(t.GITHUB_SERVER_NAME,a),this.logger.log("GitHub MCP server configured after authentication"),!0}catch(I){return this.logger.error(`Failed to configure GitHub MCP server after auth: ${I}`),!1}}return!1}async removeGitHubAuth(){if(this.hasUserConfiguredGitHubServer)return this.logger.debug("User has explicitly configured github-mcp-server, ignoring auth changes"),!1;this.githubMcpToken=void 0;try{return this.isServerRunning(t.GITHUB_SERVER_NAME)?(await this.stopServer(t.GITHUB_SERVER_NAME),this.logger.debug("Removed GitHub MCP server"),!0):!1}catch(l){return this.logger.error(`Failed to remove GitHub server: ${l}`),!1}}async shouldHandleGitHubAuth(l){return await dY(l,{onHMACAuthInfo:async()=>!!process.env.GITHUB_MCP_SERVER_TOKEN,onEnvAuthInfo:async()=>!0,onUserAuthInfo:async()=>!0,onGhCliAuthInfo:async()=>!0,onApiKeyAuthInfo:async()=>!1})}async createGitHubServerConfig(l,n){let r="https://api.githubcopilot.com/mcp/readonly";try{let a=await dY(n,{onHMACAuthInfo:async()=>"https://github.com",onEnvAuthInfo:async s=>s.host,onUserAuthInfo:async s=>s.host,onGhCliAuthInfo:async s=>s.host,onApiKeyAuthInfo:async s=>s.host}),I=await R0(a,l,this.logger);r=new URL("/mcp/readonly",I).toString()}catch(a){this.logger.error(`Failed to fetch Copilot URL, using default: ${a}`)}return{type:"http",url:r,headers:{Authorization:"Bearer "+l,"X-MCP-Toolsets":"repos,issues,users,pull_requests,code_security,secret_protection,actions,web_search","X-MCP-Host":"copilot-cli"},tools:this.enableAllGithubMcpTools?["*"]:t.CLI_DEFAULT_GITHUB_MCP_TOOLS,isDefaultServer:!0,filterMapping:{get_issue:"markdown",get_issue_comments:"markdown",get_pull_request:"markdown",get_pull_request_comments:"markdown",get_pull_request_reviews:"markdown"}}}async injectDefaultServers(l){if(l.mcpServers[t.GITHUB_SERVER_NAME]){this.hasUserConfiguredGitHubServer=!0,this.logger.debug("User has already configured github-mcp-server, skipping auto-configuration");return}}async startBuiltInServer(l){l===t.GITHUB_SERVER_NAME&&!this.hasUserConfiguredGitHubServer?this.lastGitHubAuthInfo?(this.logger.log("Attempting to configure GitHub MCP server using stored authentication"),await this.configureGitHubAuth(this.lastGitHubAuthInfo)?this.logger.log("GitHub MCP server configured successfully after enabling"):this.logger.log("GitHub MCP server enabled but could not be configured - authentication may be invalid or insufficient")):this.logger.log("GitHub MCP server enabled - will be configured automatically when authentication becomes available"):await super.startBuiltInServer(l)}};c();c();var Ifn=zl({commandHistory:Td(Yt())}),xqe=Xwe(Ifn.parse,"command-history");var sfn=50,Sqe=class{commandHistory=[];historyIndex=-1;isNavigatingHistory=!1;unSubmittedCommand=null;async initialize(){try{let e=await xqe.load();this.commandHistory=e?.commandHistory||[],this.resetNavigation()}catch{this.commandHistory=[]}}async addCommand(e){this.commandHistory=this.commandHistory.filter(l=>l!==e),this.commandHistory.unshift(e),this.commandHistory=this.commandHistory.slice(0,sfn),this.resetNavigation(),this.unSubmittedCommand=null,await this.saveHistory()}async updateCurrentCommand(e){this.historyIndex!==-1?(this.commandHistory[this.historyIndex]=e,await this.saveHistory()):this.unSubmittedCommand=e}navigateUp(e){if(this.commandHistory.length===0)return;let l=this.historyIndex+1;if(l<this.commandHistory.length){this.historyIndex=l,this.isNavigatingHistory=!0;let n=this.getCurrentHistoryItem();n&&e.setText(n)}}navigateDown(e){if(this.historyIndex===-1)return;if(this.historyIndex===0)this.resetNavigation();else{let n=this.historyIndex-1;this.historyIndex=n,this.isNavigatingHistory=!0}let l=this.getCurrentHistoryItem();l?(e.setText(l),e.setCursorPosition(0)):e.clear()}resetNavigation(){this.historyIndex=-1,this.isNavigatingHistory=!1}getHistoryIndex(){return this.historyIndex}getHistory(){return this.commandHistory}getCurrentHistoryItem(){return this.historyIndex===-1?this.unSubmittedCommand?this.unSubmittedCommand:void 0:this.commandHistory[this.historyIndex]}isNavigating(){return this.isNavigatingHistory}setNavigating(e){this.isNavigatingHistory=e}async saveHistory(){try{await xqe.write({commandHistory:this.commandHistory})}catch{}}},uY=new Sqe;c();c();function Mzt(t,e){var l=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),l.push.apply(l,n)}return l}function _zt(t){for(var e=1;e<arguments.length;e++){var l=arguments[e]!=null?arguments[e]:{};e%2?Mzt(Object(l),!0).forEach(function(n){ofn(t,n,l[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(l)):Mzt(Object(l)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(l,n))})}return t}function ofn(t,e,l){return e=ifn(e),e in t?Object.defineProperty(t,e,{value:l,enumerable:!0,configurable:!0,writable:!0}):t[e]=l,t}function ifn(t){var e=cfn(t,"string");return typeof e=="symbol"?e:String(e)}function cfn(t,e){if(typeof t!="object"||t===null)return t;var l=t[Symbol.toPrimitive];if(l!==void 0){var n=l.call(t,e||"default");if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var dfn=zzt({}),Dzt=dfn;function zzt(t){return e.withOptions=l=>zzt(_zt(_zt({},t),l)),e;function e(l,...n){let r=typeof l=="string"?[l]:l.raw,{escapeSpecialCharacters:a=Array.isArray(l),trimWhitespace:I=!0}=t,s="";for(let u=0;u<r.length;u++){let b=r[u];a&&(b=b.replace(/\\\n[ \t]*/g,"").replace(/\\`/g,"`").replace(/\\\$/g,"$").replace(/\\\{/g,"{")),s+=b,u<n.length&&(s+=n[u])}let o=s.split(`
|
|
2019
2019
|
`),d=null;for(let u of o){let b=u.match(/^(\s+)\S+/);if(b){let p=b[1].length;d?d=Math.min(d,p):d=p}}if(d!==null){let u=d;s=o.map(b=>b[0]===" "||b[0]===" "?b.slice(u):b).join(`
|
|
2020
2020
|
`)}return I&&(s=s.trim()),a&&(s=s.replace(/\\n/g,`
|
|
2021
2021
|
`)),s}}import{homedir as Ajt}from"node:os";import B5n,{resolve as O5n}from"node:path";c();function ufn(t){return t.length>0&&/^[0-9a-zA-Z_-]+$/.test(t)}function jzt(t){return!t||t.length===0?{valid:!1,error:"MCP server name cannot be empty"}:/^[0-9a-zA-Z_-]+$/.test(t)?{valid:!0}:{valid:!1,error:"MCP server name must only contain alphanumeric characters, underscores, and hyphens"}}var Pzt=nN(["none","markdown","hidden_characters"]),Kzt=zl({tools:Td(Yt()),type:Yt().optional(),isDefaultServer:go().optional(),filterMapping:aY(Yt(),Pzt).or(Pzt).optional()}),mfn=Kzt.extend({type:pr("local").optional(),command:Yt(),args:Td(Yt()),env:aY(Yt(),Yt()).optional()}),bfn=Kzt.extend({type:pr("http").or(pr("sse")),url:Yt(),headers:aY(Yt(),Yt()).optional()}),Bqe=zl({mcpServers:aY(Yt().min(1,"MCP server name cannot be empty").refine(ufn,{message:"MCP server name must only contain alphanumeric characters, underscores, and hyphens"}),mfn.or(bfn))}),mY=Hwe(Bqe.parse,"mcp");c();c();function qzt(t){let e=t.r/255,l=t.g/255,n=t.b/255,r=Math.max(e,l,n),a=Math.min(e,l,n),I=r-a,s=0,o=0,d=(r+a)/2;if(I!==0){switch(o=d>.5?I/(2-r-a):I/(r+a),r){case e:s=(l-n)/I+(l<n?6:0);break;case l:s=(n-e)/I+2;break;case n:s=(e-l)/I+4;break}s/=6}return{h:s*360,s:o,l:d}}function Gfn(t){if(t.length<12||t.length>18)return null;let e=t.match(/rgb:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i);if(!e)return null;let[,l,n,r]=e,a=d=>d.length>=2?parseInt(d.substring(0,2),16):d.length===1?parseInt(d+d,16):0,I=a(l),s=a(n),o=a(r);return{r:I,g:s,b:o}}var $zt=["#000000","#800000","#008000","#808000","#000080","#800080","#008080","#c0c0c0","#808080","#ff0000","#00ff00","#ffff00","#0000ff","#ff00ff","#00ffff","#ffffff","#000000","#00005f","#000087","#0000af","#0000d7","#0000ff","#005f00","#005f5f","#005f87","#005faf","#005fd7","#005fff","#008700","#00875f","#008787","#0087af","#0087d7","#0087ff","#00af00","#00af5f","#00af87","#00afaf","#00afd7","#00afff","#00d700","#00d75f","#00d787","#00d7af","#00d7d7","#00d7ff","#00ff00","#00ff5f","#00ff87","#00ffaf","#00ffd7","#00ffff","#5f0000","#5f005f","#5f0087","#5f00af","#5f00d7","#5f00ff","#5f5f00","#5f5f5f","#5f5f87","#5f5faf","#5f5fd7","#5f5fff","#5f8700","#5f875f","#5f8787","#5f87af","#5f87d7","#5f87ff","#5faf00","#5faf5f","#5faf87","#5fafaf","#5fafd7","#5fafff","#5fd700","#5fd75f","#5fd787","#5fd7af","#5fd7d7","#5fd7ff","#5fff00","#5fff5f","#5fff87","#5fffaf","#5fffd7","#5fffff","#870000","#87005f","#870087","#8700af","#8700d7","#8700ff","#875f00","#875f5f","#875f87","#875faf","#875fd7","#875fff","#878700","#87875f","#878787","#8787af","#8787d7","#8787ff","#87af00","#87af5f","#87af87","#87afaf","#87afd7","#87afff","#87d700","#87d75f","#87d787","#87d7af","#87d7d7","#87d7ff","#87ff00","#87ff5f","#87ff87","#87ffaf","#87ffd7","#87ffff","#af0000","#af005f","#af0087","#af00af","#af00d7","#af00ff","#af5f00","#af5f5f","#af5f87","#af5faf","#af5fd7","#af5fff","#af8700","#af875f","#af8787","#af87af","#af87d7","#af87ff","#afaf00","#afaf5f","#afaf87","#afafaf","#afafd7","#afafff","#afd700","#afd75f","#afd787","#afd7af","#afd7d7","#afd7ff","#afff00","#afff5f","#afff87","#afffaf","#afffd7","#afffff","#d70000","#d7005f","#d70087","#d700af","#d700d7","#d700ff","#d75f00","#d75f5f","#d75f87","#d75faf","#d75fd7","#d75fff","#d78700","#d7875f","#d78787","#d787af","#d787d7","#d787ff","#d7af00","#d7af5f","#d7af87","#d7afaf","#d7afd7","#d7afff","#d7d700","#d7d75f","#d7d787","#d7d7af","#d7d7d7","#d7d7ff","#d7ff00","#d7ff5f","#d7ff87","#d7ffaf","#d7ffd7","#d7ffff","#ff0000","#ff005f","#ff0087","#ff00af","#ff00d7","#ff00ff","#ff5f00","#ff5f5f","#ff5f87","#ff5faf","#ff5fd7","#ff5fff","#ff8700","#ff875f","#ff8787","#ff87af","#ff87d7","#ff87ff","#ffaf00","#ffaf5f","#ffaf87","#ffafaf","#ffafd7","#ffafff","#ffd700","#ffd75f","#ffd787","#ffd7af","#ffd7d7","#ffd7ff","#ffff00","#ffff5f","#ffff87","#ffffaf","#ffffd7","#ffffff","#080808","#121212","#1c1c1c","#262626","#303030","#3a3a3a","#444444","#4e4e4e","#585858","#626262","#6c6c6c","#767676","#808080","#8a8a8a","#949494","#9e9e9e","#a8a8a8","#b2b2b2","#bcbcbc","#c6c6c6","#d0d0d0","#dadada","#e4e4e4","#eeeeee"];function pfn(t){let e=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return e?{r:parseInt(e[1],16),g:parseInt(e[2],16),b:parseInt(e[3],16)}:{r:0,g:0,b:0}}function hfn(t){return t<0||t>=$zt.length?{r:0,g:0,b:0}:pfn($zt[t])}function ePt(t){if(t.length<15||t.length>30)return null;let e=t;e.endsWith("\x07")?e=e.slice(0,-1):e.endsWith("\x1B\\")?e=e.slice(0,-2):e.endsWith("\x9C")&&(e=e.slice(0,-1));let l=e;return l.startsWith("11;")&&(l=l.substring(3)),l.startsWith("rgb:")?Gfn(l):null}async function Afn(t=100){return new Promise(e=>{if(!process.stdout.isTTY||!process.stdin.isTTY){e(null);return}let l="",n=null,r=()=>{process.stdin.removeListener("data",a),process.stdin.setRawMode(!1),n&&clearTimeout(n)},a=I=>{l+=I.toString();let s=l.match(/\x1b\]11;([^\x07\x1b\x9c]*?)(?:\x07|\x1b\\|\x9c)/);if(s){r();let d=`11;${s[1]}`;e(ePt(d));return}let o=l.match(/11;rgb:([0-9a-f/]+)(?:\x07|\x1b\\|\x9c)/i);if(o){r(),e(ePt(`11;rgb:${o[1]}`));return}};n=setTimeout(()=>{r(),e(null)},t);try{process.stdin.setRawMode(!0),process.stdin.on("data",a),process.stdout.write("\x1B]11;?\x1B\\")}catch{r(),e(null)}})}function gfn(){let t=process.env.COLORFGBG;if(!t||!t.includes(";"))return null;let e=t.split(";"),l=e[e.length-1],n=parseInt(l,10);return isNaN(n)?null:hfn(n)}async function tPt(){try{let t=await Afn();if(t)return qzt(t).l<.5;let e=gfn();return e?qzt(e).l<.5:!0}catch{return!0}}var lPt={FG:"whiteBright",ACCENT:"blue",SUCCESS:"green",DIFF_ADDED_HIGHLIGHT_FG:"black",DIFF_REMOVED_HIGHLIGHT_FG:"whiteBright",ERROR:"red",WARNING:"yellow",COPILOT:"magenta",COPILOT_BRIGHT:"magentaBright",MUTED:"white",SELECTED:"cyan",BORDER:"blackBright"},Zfn={FG:"black",ACCENT:"blue",SUCCESS:"green",DIFF_ADDED_HIGHLIGHT_FG:"black",DIFF_REMOVED_HIGHLIGHT_FG:"whiteBright",ERROR:"red",WARNING:"yellow",COPILOT:"magenta",COPILOT_BRIGHT:"magentaBright",MUTED:"blackBright",SELECTED:"cyan",BORDER:"blackBright"};function Oqe(t){return t==="auto"||t==="dark"||t==="light"}function Bwe(t){switch(t){case"dark":return lPt;case"light":return Zfn;default:return lPt}}var Owe=await tPt();async function Twe(){let e=(await Sr.load())?.theme||"";return Oqe(e)?e:"auto"}async function nPt(t){await Sr.writeKey("theme",t)}var rPt=t=>{let e=t?Sl.whiteBright:Sl.black,l=t?Sl.cyanBright:Sl.blueBright,n=t?Sl.magentaBright:Sl.magenta;return{text:e,paragraph:e,html:e,table:e,blockquote:e,heading:Sl.bold,firstHeading:Sl.whiteBright.bold,strong:Sl.bold,em:Sl.italic,del:Sl.strikethrough,hr:Sl.white,link:l,href:l,image:(r,a,I)=>n(I?`Image: ${I} \u2192 ${r}`:`Image: ${r}`),codespan:Sl.cyan,code:Sl.cyan,list:(r,a,I)=>{let s=r.replace(/^(\s*)\* /gm,"$1- ");return I&&(s=s.split(`
|
|
@@ -2446,7 +2446,7 @@ Run `+Sl.cyan("{updateCommand}")+" to update",a=e.message||r;e.boxenOptions??={p
|
|
|
2446
2446
|
`).map(l=>l.trim()).filter(l=>l&&!l.startsWith("#")).map(l=>l.endsWith("/")?l.slice(0,-1)+"/**":l)}shouldIgnore(e){try{let l=M8n(this.rootPath,e);return l==="."||l.startsWith("..")?!1:this.ig.ignores(l)}catch{return!1}}getDirectoryFilter(){return e=>{if(!e||e===".")return!1;let l=e.startsWith("./")?e.slice(2):e;return!l||l==="."?!1:this.ig.ignores(l)}}getFileFilter(){return e=>{if(!e||e===".")return!1;let l=e.startsWith("./")?e.slice(2):e;return!l||l==="."?!1:this.ig.ignores(l)}}updateFingerprint(){this.fingerprint=JSON.stringify(this.patterns)}getFingerprint(){return this.fingerprint}getPatterns(){return[...this.patterns]}};var cbl=2e4,snt=class extends Error{constructor(e="Search aborted"){super(e),this.name="AbortError"}};async function dbl(t,e,l,n){let r=(0,mbl.default)(e,{dot:!0,contains:!0,nocase:!0}),a=[];for(let[I,s]of t.entries()){if(I%1e3===0&&(await new Promise(o=>setImmediate(o)),l?.aborted))throw new snt;if(r(s)&&a.push(s),a.length>=n)break}return a.sort((I,s)=>{let o=I.endsWith(PT),d=s.endsWith(PT);return o&&!d?-1:!o&&d?1:I<s?-1:I>s?1:0}),a}var qbe=class{rootPath;ignorePatterns;maxResults;cacheTimeout;indexFileStats;maxStatConcurrency;includeDirsInIndex;allFiles=[];visiblePaths=[];fileCache=[];fileByRelative=new Map;lastCacheUpdate=0;isIndexing=!1;indexingPromise=null;isIndexed=!1;strategy="v2";fzf;onIndexingStart;onIndexingComplete;logger;constructor(e={}){this.rootPath=e.rootPath||process.cwd(),this.ignorePatterns=new Kbe(this.rootPath),this.maxResults=e.maxResults||50,this.cacheTimeout=e.cacheTimeout??5*6e4,this.indexFileStats=e.indexFileStats??!1,this.maxStatConcurrency=e.maxStatConcurrency??64,this.includeDirsInIndex=e.includeDirsInIndex??!1,this.onIndexingStart=e.onIndexingStart,this.onIndexingComplete=e.onIndexingComplete,this.logger=e.logger||new xd}async search(e){if(await this.ensureFileIndex(),this.fileCache.length===0)return[];if(!e.trim()){let l=this.fileCache;return l.slice(0,this.maxResults).map((n,r)=>({path:n.path,score:1-r/Math.max(l.length,1),relativePath:n.relativePath}))}if(e.includes("*")){let l=await dbl(this.visiblePaths,e,void 0,this.maxResults),n=[],r=this.fileByRelative;for(let[a,I]of l.entries()){if(a%1e3===0&&await new Promise(o=>setImmediate(o)),n.length>=this.maxResults)break;if(I===".")continue;let s=r.get(I);if(s){let o=this.calculateScore(s.relativePath,e);n.push({path:s.path,score:o,relativePath:s.relativePath})}}return n.sort((a,I)=>I.score-a.score),n}else{this.fzf||(this.fzf=new sve(this.visiblePaths,{fuzzy:this.visiblePaths.length>cbl?"v1":"v2"}));let l=[];try{l=await this.fzf.find(e)}catch{l=(await dbl(this.visiblePaths,e,void 0,this.maxResults)).map(I=>({item:I,score:1,start:0,end:0,positions:new Set}))}let n=l.slice(0,this.maxResults).map((a,I)=>({rel:a.item,idx:I})),r=[];for(let{rel:a,idx:I}of n){if(a===".")continue;let s=this.fileByRelative.get(a);s&&r.push({file:s,idx:I,bucket:this.exactBucket(s.relativePath,e),score:this.calculateScore(s.relativePath,e)})}return r.sort((a,I)=>I.bucket-a.bucket||a.idx-I.idx),r.map(a=>({path:a.file.path,relativePath:a.file.relativePath,score:a.score}))}}exactBucket(e,l){let n=e.toLowerCase(),r=l.toLowerCase();if(n===r)return 3;let a=n.lastIndexOf(PT),I=a===-1?n:n.slice(a+1);return I===r?2:I.startsWith(r)?1:0}calculateScore(e,l){let n=e.toLowerCase(),r=l.toLowerCase();if(n===r)return 1;let a=e.lastIndexOf(PT),s=(a===-1?e:e.slice(a+1)).toLowerCase();if(s===r)return .95;if(s.startsWith(r))return .85;if(n.startsWith(r))return .75;let o=n.indexOf(r);return o===-1?.5:Math.max(.1,.7-o/n.length)}async refresh(){this.invalidateCache(),await this.ensureFileIndex()}invalidateCache(){this.lastCacheUpdate=0,this.isIndexed=!1,this.indexingPromise=null,this.fileCache=[],this.allFiles=[],this.fzf=void 0,this.visiblePaths=[],this.fileByRelative.clear()}getCacheInfo(){return{fileCount:this.fileCache.length,lastUpdated:this.lastCacheUpdate,isIndexing:this.isIndexing,strategy:this.strategy,isIndexed:this.isIndexed}}async ensureFileIndex(){let e=Date.now();if(!(this.isIndexed&&this.fileCache.length>0&&e-this.lastCacheUpdate<this.cacheTimeout))return this.indexingPromise?this.indexingPromise:(this.isIndexing=!0,this.indexingPromise=this.buildFileIndex().finally(()=>{this.isIndexing=!1,this.indexingPromise=null}),this.indexingPromise)}async buildFileIndex(){let e=Date.now();this.onIndexingStart?.();try{await this.ignorePatterns.loadPatterns(),this.allFiles=await this.performCrawl();let l=await this.filterFilesConcurrently(this.allFiles),n=l.map(a=>({path:D8n(this.rootPath,a),relativePath:a,lastModified:0}));this.indexFileStats&&n.length&&await this.fillStatsConcurrently(n,this.maxStatConcurrency),n.sort((a,I)=>a.relativePath.localeCompare(I.relativePath)),this.fileCache=n,this.visiblePaths=l,this.fileByRelative=new Map(n.map(a=>[a.relativePath,a])),this.lastCacheUpdate=Date.now(),this.isIndexed=!0,this.strategy=this.visiblePaths.length>cbl?"v1":"v2";let r=Date.now()-e;this.onIndexingComplete?.(this.fileCache.length,r)}catch(l){this.logger.error(`Error building file index: ${l}`),this.fileCache=[],this.allFiles=[],this.visiblePaths=[],this.fileByRelative.clear(),this.isIndexed=!1;let n=Date.now()-e;this.onIndexingComplete?.(0,n)}}async fillStatsConcurrently(e,l){let n=0,r=new Array(Math.min(l,e.length)).fill(0).map(async()=>{for(;;){let a=n++;if(a>=e.length)break;let I=e[a];try{let s=await _8n(I.path);I.lastModified=s.mtime.getTime()}catch{}a%2e3===0&&await new Promise(s=>setImmediate(s))}});await Promise.all(r)}async filterFilesConcurrently(e,l=50){let n=this.ignorePatterns.getFileFilter(),r=[];for(let a=0;a<e.length;a+=l){let I=e.slice(a,a+l),s=I.map(o=>!n(o));I.forEach((o,d)=>{s[d]&&r.push(o)}),await new Promise(o=>setImmediate(o))}return r}async performCrawl(){let e=this.ignorePatterns.getDirectoryFilter(),l=new ubl.fdir().withRelativePaths().withPathSeparator(PT).exclude((n,r)=>{let a=z8n(this.rootPath,r);if(a==="."||a==="")return!1;let I=a.endsWith(PT)?a:`${a}${PT}`;return e(I)});return this.includeDirsInIndex&&l.withDirs(),l.crawl(this.rootPath).withPromise()}getRootPath(){return this.rootPath}async setRootPath(e){this.rootPath=e,this.ignorePatterns=new Kbe(e),this.invalidateCache()}},Int=null;function bbl(){return Int||(Int=new qbe),Int}function Gbl(t,e,l){let[n,r]=(0,IJ.useState)([]),[a,I]=(0,IJ.useState)(0),[s,o]=(0,IJ.useState)(new Map),d=e||bbl(),u=(0,IJ.useMemo)(()=>{let{text:w,cursorPosition:H}=t,L=-1;for(let U=H-1;U>=0;U--){let O=w[U];if(O==="@"){if(U===0||w[U-1]===" "||w[U-1]===`
|
|
2447
2447
|
`||w[U-1]===" "){L=U;break}}else if(O===" "||O===`
|
|
2448
2448
|
`||O===" ")break}if(L===-1)return{isAtMention:!1,atPosition:-1,query:""};let S=w.slice(L+1,H);return S.includes(" ")||S.includes(`
|
|
2449
|
-
`)||S.includes(" ")?{isAtMention:!1,atPosition:-1,query:""}:{isAtMention:!0,atPosition:L,query:S}},[t.text,t.cursorPosition]);(0,IJ.useEffect)(()=>{if(!u.isAtMention){r([]),I(0);return}let w=!1,H=async()=>{try{let S=await d.search(u.query),U=[...S];u.query===""&&l&&(U=[...l.getDirectories().map(B=>({path:B,relativePath:`[DIR] ${B}`,score:1})),...S]),w||(r(U),I(0))}catch{w||(r([]),I(0))}},L=setTimeout(()=>{H()},200);return()=>{w=!0,clearTimeout(L)}},[u.query,u.isAtMention,d]);let b=()=>{n.length!==0&&I(w=>w>0?w-1:n.length-1)},p=()=>{n.length!==0&&I(w=>w<n.length-1?w+1:0)},h=()=>{if(!u.isAtMention||n.length===0)return null;let w=n[a];if(!w)return null;let H=`@${w.relativePath}`,L=`${H} `,{text:S,cursorPosition:U}=t,O=S.slice(0,u.atPosition),j=S.slice(U),B=O+L+j,z={displayText:H,fullPath:w.path,type:w.relativePath.startsWith("[DIR]")?"directory":"file",startIndex:u.atPosition};return o(oe=>{let he=new Map(oe);return he.set(z.startIndex,z),he}),t.setText(B),t.setCursorPosition(u.atPosition+L.length),w.relativePath},g=()=>{r([]),I(0)},N=()=>{o(new Map)};return[{isActive:u.isAtMention&&n.length>0,query:u.query,suggestions:n,selectedIndex:a,atPosition:u.atPosition,storedMentions:s},{navigateUp:b,navigateDown:p,complete:h,reset:g,clearStoredMentions:N}]}c();var cve=nt(nl(),1),xbl=nt(KSe(),1);import{readdir as Zqn,readFile as Nqn}from"node:fs/promises";import Wqn,{join as Jbl}from"node:path";c();function jT(t,e){if(e instanceof Error)return`${t}: ${e.message}`;if(typeof e=="object"&&e!==null)try{return`${t}: ${JSON.stringify(e)}`}catch{return`${t}: [object with circular reference]`}else return`${t}: ${String(e)}`}c();var ive=nt(nl(),1);c();var fbl=nt(vbl(),1);function cnt(t){try{let e=(0,fbl.default)(t.FetchURL);return e.source!=="github.com"||!e.owner||!e.name?null:{owner:e.owner,name:e.name,host:"github.com"}}catch{return null}}async function ove(t){let e=await IPt(t);if(e.length===0)return null;if(e.length===1)return cnt(e[0]);let l=e.find(n=>n.Name==="origin");return cnt(l||e[0])}function Hbl(t){let[e,l]=(0,ive.useState)(null);return(0,ive.useEffect)(()=>{(async()=>{let n=await dnt(t);l(r=>!r||r.kind!==n.kind||r.path!==n.path||n.kind==="git"&&r.kind==="git"&&(r.repo?.owner!==n.repo?.owner||r.repo?.name!==n.repo?.name)?n:r)})()},[t]),e}async function dnt(t){let e=await bY(t);if(!e.found)return{kind:"plain",path:t};try{let l=await ove(e.gitRoot);return{kind:"git",path:e.gitRoot,repo:l}}catch{return{kind:"git",path:e.gitRoot,repo:null}}}function Sbl(t,e,l,n,r,a){let[I,s]=(0,cve.useState)({selected:null,available:[],warnings:[]}),o=Hbl(a);return(0,cve.useEffect)(()=>{if(!t)return;(async()=>{let{agents:u,warnings:b}=await unt(e,l,n,Wqn.join(r,"agents"),o);s({selected:null,available:u,warnings:b})})()},[t,e,l,n,r,o]),{customAgents:I,selectCustomAgent:async d=>{if(!t)throw new Error("attempted to use disabled feature flagged feature");let u=I.available.find(p=>p.id===d);if(!u)throw new Error(`attempted to select unknown custom agent: ${d} from ${I.available.map(p=>p.id).join(", ")}`);let b=await u.prompt().then(p=>({kind:"success",prompt:p}),p=>({kind:"error",message:jT("loading custom agent prompt",p)}));return b.kind==="error"?{kind:"error",message:b.message}:(s(p=>({...p,selected:{id:u.id,displayName:u.displayName,prompt:b.prompt}})),{kind:"success"})}}}function Xbl(t){let e=new Set,l=[];for(let n of t)e.has(n.id)||(e.add(n.id),l.push(n));return l}async function unt(t,e,l,n,r){let a=await kbl(n);if(r===null)return{agents:a.agents,warnings:a.warnings};let I=await kbl(Jbl(r.path,".github","agents")),s=Xbl([...a.agents,...I.agents]),o=[...a.warnings,...I.warnings];if(r.kind!=="git")return{agents:s,warnings:o};if(!r.repo)return{agents:s,warnings:[...o,"could not load remote agents, no github.com remote found"]};if(!l)return{agents:s,warnings:[...o,L7(r.repo,"no authentication available")]};let d=await yqn(t,e,l,r.repo);return{agents:Xbl([...s,...d.agents]),warnings:[...o,...d.warnings]}}function L7(t,e){return`could not load remote agents for ${t.owner}/${t.name}: ${e}`}async function yqn(t,e,l,n){let r=dY(l,{onHMACAuthInfo:()=>xte,onEnvAuthInfo:g=>g.host,onGhCliAuthInfo:g=>g.host,onUserAuthInfo:g=>g.host,onApiKeyAuthInfo:g=>g.host}),{host:a}=new URL(r);if(a!=="github.com")return{agents:[],warnings:[L7(n,"auth info does not target github.com")]};let I=await ry(l);if(!I)return{agents:[],warnings:[L7(n,"no usable token for accessing repo contents found")]};let s=await Bbl(()=>R0(r,I),g=>jT("fetching copilot URL",g));if(s.kind==="error")return{agents:[],warnings:[L7(n,s.message)]};let o=`${s.value}/agents/swe/custom-agents/${n.owner}/${n.name}?exclude_invalid_config=true`,d={Authorization:`Bearer ${I}`},u=await NC(o,{method:"GET",headers:d},t);if(!u.ok)return t.warning(`Failed to load custom agents for ${n.owner}/${n.name}: ${await u.text()}`),{agents:[],warnings:[L7(n,`server returned ${u.status}: ${u.statusText}`)]};let b=await u.json(),h=SI.object({agents:SI.array(Obl)}).safeParse(b);return h.success?{agents:h.data.agents.map(g=>({id:g.name,displayName:g.display_name,prompt:async()=>{let N=await Qqn({logger:t,integrationId:e,sweAgentsEndpoint:`${s.value}/agents/swe`,token:I,repoOwner:g.repo_owner,repoName:g.repo_name,customAgentName:g.name});if(!N)throw new Error(`Failed to load prompt for agent ${g.name}`);return N.prompt}})),warnings:[]}:{agents:[],warnings:[L7(n,jT("parsing http response into schema",h.error))]}}async function kbl(t){let e=await Zqn(t,{withFileTypes:!0}).then(r=>({kind:"success",dirEntries:r})).catch(r=>r.code==="ENOENT"?{kind:"success",dirEntries:[]}:{kind:"error",message:jT(t,r)});if(e.kind==="error")return{agents:[],warnings:[]};let l=[],n=[];for(let r of e.dirEntries)if(r.isFile()&&r.name.endsWith(".md")){let a=Jbl(t,r.name),I=r.name.slice(0,-3),s=await Lbl(a);if(s.kind==="error"){n.push(s.message);continue}l.push({id:I,displayName:s.agent.name,prompt:async()=>{let o=await Lbl(a);if(o.kind==="error")throw new Error(o.message);return await o.agent.prompt()}})}return{agents:l,warnings:n}}async function Lbl(t){let e=await Bbl(()=>Nqn(t,"utf-8"),n=>jT(t,n));if(e.kind==="error")return{kind:"error",message:e.message};let l=Eqn(e.value);return l.kind==="error"?{kind:"error",message:`${t}: ${l.message}`}:{kind:"success",agent:l.agent}}var Eqn=t=>{let e=SI.object({name:SI.string(),description:SI.string(),tools:SI.array(SI.string()).optional()}).strict(),l=/^---\s*\n([\s\S]*?)\n---\s*\n?/,n=t.match(l);if(!n)return{kind:"error",message:"custom agent markdown frontmatter is malformed"};let r=n[1];try{let a=(0,xbl.parse)(r),I=e.safeParse(a);if(!I.success)return{kind:"error",message:Rqn(I.error)};let s=t.slice(n[0].length);return{kind:"success",agent:{name:I.data.name,description:I.data.description,tools:I.data.tools||["*"],prompt:()=>Promise.resolve(s)}}}catch(a){return{kind:"error",message:jT("failed to parse front matter",a)}}};function Rqn(t){return t.issues.map(e=>`${e.path.join(".")||"(root)"}: ${e.message}`).join(", ")}async function Bbl(t,e){try{return{kind:"success",value:await t()}}catch(l){return{kind:"error",message:e(l)}}}var Yqn=SI.object({command:SI.string(),args:SI.array(SI.string()),env:SI.record(SI.string(),SI.string()).optional(),tools:SI.array(SI.string()),type:SI.enum(["local","stdio"]).optional()}),Vqn=SI.object({url:SI.string(),headers:SI.record(SI.string(),SI.string()).optional(),tools:SI.array(SI.string()),type:SI.enum(["http","sse"])}),Obl=SI.object({name:SI.string(),repo_owner:SI.string(),repo_name:SI.string(),display_name:SI.string(),description:SI.string(),tools:SI.array(SI.string()),version:SI.string(),mcp_servers:SI.record(SI.string(),SI.union([Yqn,Vqn])).optional().nullable()}),wqn=Obl.extend({prompt:SI.string()});async function Qqn(t){t.logger.info(`Reading custom agent "${t.customAgentName}" from ${t.repoOwner}/${t.repoName}`);try{let e={"Copilot-Integration-Id":t.integrationId,Authorization:`Bearer ${t.token}`,"X-GitHub-Job-Nonce":t.jobNonce??""},l=await NC(`${t.sweAgentsEndpoint}/custom-agents/${t.repoOwner}/${t.repoName}/${t.customAgentName}`,{method:"GET",headers:e},t.logger,"get custom agent config");if(!l.ok){if(l.status===404)return null;throw new Error(`Failed to get custom agent config: ${l.status} ${l.statusText}`)}let n=await l.json();return wqn.parse(n)}catch(e){let l=e,n=l?.requestId||"unknown";throw t.logger.error(`Failed to get custom agent config (request ID: ${n}): ${l}`),l}}c();var cy=nt(nl(),1);function Tbl(t){let{cliModel:e,session:l,currentWorkingDirectory:n,customAgentName:r,stdoutColumns:a,models:I}=t,[s,o]=(0,cy.useState)({gitRoot:"",found:!1}),[d,u]=(0,cy.useState)(null);(0,cy.useEffect)(()=>{(async()=>{u(null);let w=await bY(n);o(w)})()},[n]);let b=(0,cy.useCallback)(async()=>{if(!s.found){u(null);return}let Y=await oPt(s.gitRoot);if(!Y){u(null);return}let w=await sPt(s.gitRoot);u(H=>H?.branch===Y&&H?.hasChanges===w?H:{branch:Y,hasChanges:w})},[s]),p=(0,cy.useMemo)(()=>YEe(n),[n]),[h,g]=(0,cy.useState)("");(0,cy.useEffect)(()=>{(async()=>{if(!I||I.type!=="success")return;let w=await rT(e,l,I.list);w&&g(H=>H===w?H:w)})()},[e,l,I]);let N=(0,cy.useMemo)(()=>{if(!d||!d.branch)return null;let Y=a||80,w=h.length,H=r?.length||0,L=p.length,S=d.hasChanges?6:5,O=w+L+S+4+H,B=Math.max(8,Y-O)-3;return`[\u2387 ${d.branch.length>B?d.branch.substring(0,B)+"...":d.branch}${d.hasChanges?"*":""}]`},[d,a,p,h]),y=(0,cy.useMemo)(()=>{if(!h)return h;let Y=I&&I.type==="success"?I.list:void 0,w=Wq(h,Y);return`${h} (${w}x)`},[h,I]);return{displayCwd:p,gitBranchInfo:N,selectedModel:h,selectedModelDisplay:y,setSelectedModel:g,updateGitStatus:b}}c();var Fg=nt(nl(),1),Fqn=3*1e3;function Ubl(){let[t,e]=(0,Fg.useState)("idle"),[l,n]=(0,Fg.useState)(0),[r,a]=(0,Fg.useState)(0),[I,s]=(0,Fg.useState)(!1),o=(0,Fg.useRef)(null);(0,Fg.useEffect)(()=>()=>{o.current&&clearTimeout(o.current)},[]);let d=(0,Fg.useCallback)(()=>{o.current&&(clearTimeout(o.current),o.current=null),e("indexing"),n(0),a(0),s(!0)},[]),u=(0,Fg.useCallback)((g,N)=>{e("completed"),n(g),a(N),s(!0),o.current=setTimeout(()=>{s(!1),o.current=null},Fqn)},[]),b=(0,Fg.useCallback)(()=>{o.current&&(clearTimeout(o.current),o.current=null),e("idle"),n(0),a(0),s(!1)},[]),p={state:t,fileCount:l,durationMs:r,isVisible:I},h=(0,Fg.useMemo)(()=>({startIndexing:d,completeIndexing:u,reset:b}),[d,u,b]);return[p,h]}c();var Mbl=nt(nl(),1);function _bl(t,e){(0,Mbl.useEffect)(()=>{if(t)return t.on("assistant.message",l=>{if(l.data.toolRequests){for(let n of l.data.toolRequests)if(n.name===EE.name){let r=n.arguments.intent;r&&e(r)}}})},[t,e])}c();var dve=nt(nl(),1);function Dbl(t,e,l,n){let[r,a]=(0,dve.useState)();return(0,dve.useEffect)(()=>{async function I(){if(!l)return;let s=await mnt(t,e,l,n);a(s)}I()},[l,e,n]),{models:r}}async function mnt(t,e,l,n){if(kL())return{type:"success",list:[]};try{if(l.type==="hmac")return{type:"success",list:await AO.createWithHmac(t,xte,n,l.hmac,e).listModels()};let r=await ry(l);if(!r)return{type:"noauth"};let a=await R0(l.host,r);return{type:"success",list:await AO.createWithOAuthToken(t,a,n,r,e).listModels()}}catch(r){return{type:"error",error:r}}}c();var mQ=nt(nl(),1);function zbl(t=3){let[e,l]=(0,mQ.useState)(!1),n=(0,mQ.useRef)(null),r=(0,mQ.useRef)(t*1e3);(0,mQ.useEffect)(()=>{r.current=t*1e3},[t]),(0,mQ.useEffect)(()=>()=>{n.current&&clearTimeout(n.current)},[]);let a=(0,mQ.useCallback)(I=>{n.current&&(clearTimeout(n.current),n.current=null),l(!0);let s=I!==void 0?I*1e3:r.current;n.current=setTimeout(()=>{l(!1),n.current=null},s)},[]);return[e,a]}c();var $be=nt(nl(),1);function Pbl({builtInSlashCommands:t,logger:e,currentWorkingDirectory:l,setCurrentWorkingDirectory:n,fileSearch:r,authManager:a,mcpHost:I,loginStatus:s,setLoginStatus:o,addEntryToSession:d,clearSessionHistory:u,getSessionUsageOutput:b,pathManager:p,resetSessionToolApprovals:h,clearTimeline:g,clearHeader:N,clearContextWindowMetrics:y,setThemePreference:Y,refreshStatic:w,hasAvailableCustomAgents:H,slashCommandResultActions:L}){let S=(0,$be.useMemo)(()=>({logger:e,slashCommands:t,hasAvailableCustomAgents:H,mcp:{host:I,config:async()=>await mY.load()||{mcpServers:{}},hasServer:async j=>(await S.mcp.config())?.mcpServers[j]!==void 0,deleteServer:async j=>{let B=await S.mcp.config();delete B.mcpServers[j],await mY.write(B)}},auth:{availableAuthMethods:()=>Xzt(a,s.authInfo),loginStatus:s,logout:async()=>{let j=await a.logout();return o({status:"NotLoggedIn"}),j}},session:{addTimelineEntry:d,clearHistory:u,usageOutput:b},permissions:{allowedDirs:p.getDirectories.bind(p),addAllowedDirectory:p.addDirectory.bind(p),resetSessionToolApprovals:h},process:{cwd:l,chdir:async j=>{process.chdir(j),await p.updatePrimaryDirectory(j),n(j),await r.setRootPath(j)}},ui:{getThemePreference:Twe,setThemePreference:Y,clear:()=>{g(),N(),y(),w()}}}),[t,e,l,n,r,a,I,s,o,d,u,b,p,h,N,y,Y,w,H]),U=(0,$be.useCallback)(async j=>{let B=Ud(()=>{let q=j.trim();return q==="?"?"/help":q});if(!B.startsWith("/"))return{handled:!1};let z=B.split(" ")[0],oe=t.find(q=>q.name===z||q.aliases?.includes(z));if(!oe)return{handled:!1};let he=B.substring(oe.name.length).trim().split(" ").filter(q=>q),Ge=await oe.execute(S,he);if(!Ge)return{handled:!0};switch(Ge.kind){case"exit":return L.exit(),{handled:!0};case"add-timeline-entry":return d(Ge.entry),{handled:!0};case"show-dialog":switch(Ge.dialog.kind){case"custom-agent-picker":L.showCustomAgentPickerDialog();break;case"feedback":L.showFeedbackDialog();break;case"login":L.showLoginDialog();break;case"mcp":L.showMCPDialog(Ge.dialog.mode,Ge.dialog.serverName);break;case"model-picker":L.showModelPickerDialog();break;case"session":L.showSessionDialog();break;case"user-switcher":L.showUserSwitcherDialog();break;default:xm(Ge.dialog,`Unknown dialog kind: ${Ge.dialog}`)}return{handled:!0};case"set-model":return await L.setModel(Ge.model),{handled:!0};case"noop":return{handled:!0};case"start-remote-delegate":return L.startRemoteDelegation(Ge.prompt),{handled:!0};default:xm(Ge,`Unknown slash command result kind: ${Ge}`)}},[t,d,L,S]),O=(0,$be.useCallback)(j=>Ame(t,j),[t]);return{slashCommands:t,handleSlashCommand:U,matchingSlashCommands:O}}c();var uve=nt(nl(),1);function jbl(t,e,l){let n=(0,uve.useMemo)(()=>new Map,[]);(0,uve.useEffect)(()=>{(async()=>{if(Object.keys(t).length===0||t.staff!==void 0||!e)return;let a=await ry(e),I=e.type==="hmac"?void 0:e.host;if(!a||I!==fL)return;let s=n.get(a)??ODt(I,a).catch(()=>!1);n.set(a,s),await s&&(await Sr.writeKey("staff",!0),await Sr.writeKey("log_level","all"),l({type:"info",text:"Staff mode activated! Restart the app to enable staff features \u2728"}))})()},[t,e,l])}c();var sJ=nt(nl(),1);function Kbl(t,e,l){let[n,r]=(0,sJ.useState)(null),a=(0,sJ.useRef)("");return(0,sJ.useEffect)(()=>{e.text!==a.current&&(n?.availableOptions.some(o=>e.text===o.name)||r(null),a.current=e.text)},[e.text,n]),{handleTabCompletion:(0,sJ.useCallback)(()=>{let s=o=>{let d=o.indexOf(" ");return d===-1?!1:o.slice(d+1).trim().length>0};if(n){if(s(e.text)){r(null);return}let o=(n.currentIndex+1)%n.availableOptions.length,d=n.availableOptions[o];e.setText(d.name),r({...n,currentIndex:o}),l.setSlashCommandPickerIndex(o)}else{if(s(e.text))return;let o=Ame(t,e.text);if(o.length===1){let d=o[0],u=d.name;for(let b=u.length-1;b>=2;b--){let p=u.slice(0,b),h=Ame(t,p);if(h.length>1){let g=h.findIndex(Y=>Y.name===d.name);r({originalInput:p,availableOptions:h,currentIndex:g>=0?g:0});let N=(g+1)%h.length,y=h[N];e.setText(y.name),r({originalInput:p,availableOptions:h,currentIndex:N}),l.setSlashCommandPickerIndex(N);return}}}o.length>1?(r({originalInput:e.text,availableOptions:o,currentIndex:0}),e.setText(o[0].name),l.setSlashCommandPickerIndex(0)):o.length===1&&e.setText(o[0].name)}},[n,e,l]),tabCyclingState:n}}c();var tH=nt(nl(),1);function qbl(){let[t,e]=(0,tH.useState)({columns:process.stdout.columns,rows:process.stdout.rows}),l=(0,tH.useRef)(()=>{}),n=(0,tH.useCallback)(a=>{l.current=a||(()=>{})},[]),r=(0,tH.useCallback)(()=>{let{columns:a,rows:I}=process.stdout;e({columns:a,rows:I}),l.current(a,I)},[]);return(0,tH.useEffect)(()=>(process.stdout.on("resize",r),()=>{process.stdout.off("resize",r)}),[]),{...t,setOnResize:n}}c();var x7=nt(nl(),1);var oJ=t=>/\s/.test(t);function Cqn(t,e){if(e>=t.length)return t.length;let l=e;for(;l<t.length&&oJ(t[l]);)l+=t[l].length;for(;l<t.length&&!oJ(t[l]);)l+=t[l].length;return l}function $bl(t,e){if(e===0)return 0;let l=e-1;for(;l>=0&&oJ(t[l]);)l-=t[l].length;if(l<0)return 0;for(;l>=0&&!oJ(t[l]);)l-=t[l].length;return l+1}function vqn(t,e){if(e>=t.length)return t.length;let l=e;for(;l<t.length&&!oJ(t[l]);)l+=t[l].length;for(;l<t.length&&oJ(t[l]);)l+=t[l].length;return l}function KT(t,e){if(e<=0)return[t];let l=t.split(`
|
|
2449
|
+
`)||S.includes(" ")?{isAtMention:!1,atPosition:-1,query:""}:{isAtMention:!0,atPosition:L,query:S}},[t.text,t.cursorPosition]);(0,IJ.useEffect)(()=>{if(!u.isAtMention){r([]),I(0);return}let w=!1,H=async()=>{try{let S=await d.search(u.query),U=[...S];u.query===""&&l&&(U=[...l.getDirectories().map(B=>({path:B,relativePath:`[DIR] ${B}`,score:1})),...S]),w||(r(U),I(0))}catch{w||(r([]),I(0))}},L=setTimeout(()=>{H()},200);return()=>{w=!0,clearTimeout(L)}},[u.query,u.isAtMention,d]);let b=()=>{n.length!==0&&I(w=>w>0?w-1:n.length-1)},p=()=>{n.length!==0&&I(w=>w<n.length-1?w+1:0)},h=()=>{if(!u.isAtMention||n.length===0)return null;let w=n[a];if(!w)return null;let H=`@${w.relativePath}`,L=`${H} `,{text:S,cursorPosition:U}=t,O=S.slice(0,u.atPosition),j=S.slice(U),B=O+L+j,z={displayText:H,fullPath:w.path,type:w.relativePath.startsWith("[DIR]")?"directory":"file",startIndex:u.atPosition};return o(oe=>{let he=new Map(oe);return he.set(z.startIndex,z),he}),t.setText(B),t.setCursorPosition(u.atPosition+L.length),w.relativePath},g=()=>{r([]),I(0)},N=()=>{o(new Map)};return[{isActive:u.isAtMention&&n.length>0,query:u.query,suggestions:n,selectedIndex:a,atPosition:u.atPosition,storedMentions:s},{navigateUp:b,navigateDown:p,complete:h,reset:g,clearStoredMentions:N}]}c();var cve=nt(nl(),1),xbl=nt(KSe(),1);import{readdir as Zqn,readFile as Nqn}from"node:fs/promises";import Wqn,{join as Jbl}from"node:path";c();function jT(t,e){if(e instanceof Error)return`${t}: ${e.message}`;if(typeof e=="object"&&e!==null)try{return`${t}: ${JSON.stringify(e)}`}catch{return`${t}: [object with circular reference]`}else return`${t}: ${String(e)}`}c();var ive=nt(nl(),1);c();var fbl=nt(vbl(),1);function cnt(t){try{let e=(0,fbl.default)(t.FetchURL);return e.source!=="github.com"||!e.owner||!e.name?null:{owner:e.owner,name:e.name,host:"github.com"}}catch{return null}}async function ove(t){let e=await IPt(t);if(e.length===0)return null;if(e.length===1)return cnt(e[0]);let l=e.find(n=>n.Name==="origin");return cnt(l||e[0])}function Hbl(t){let[e,l]=(0,ive.useState)(null);return(0,ive.useEffect)(()=>{(async()=>{let n=await dnt(t);l(r=>!r||r.kind!==n.kind||r.path!==n.path||n.kind==="git"&&r.kind==="git"&&(r.repo?.owner!==n.repo?.owner||r.repo?.name!==n.repo?.name)?n:r)})()},[t]),e}async function dnt(t){let e=await bY(t);if(!e.found)return{kind:"plain",path:t};try{let l=await ove(e.gitRoot);return{kind:"git",path:e.gitRoot,repo:l}}catch{return{kind:"git",path:e.gitRoot,repo:null}}}function Sbl(t,e,l,n,r,a){let[I,s]=(0,cve.useState)({selected:null,available:[],warnings:[]}),o=Hbl(a);return(0,cve.useEffect)(()=>{if(!t)return;(async()=>{let{agents:u,warnings:b}=await unt(e,l,n,Wqn.join(r,"agents"),o);s({selected:null,available:u,warnings:b})})()},[t,e,l,n,r,o]),{customAgents:I,selectCustomAgent:async d=>{if(!t)throw new Error("attempted to use disabled feature flagged feature");let u=I.available.find(p=>p.id===d);if(!u)throw new Error(`attempted to select unknown custom agent: ${d} from ${I.available.map(p=>p.id).join(", ")}`);let b=await u.prompt().then(p=>({kind:"success",prompt:p}),p=>({kind:"error",message:jT("loading custom agent prompt",p)}));return b.kind==="error"?{kind:"error",message:b.message}:(s(p=>({...p,selected:{id:u.id,displayName:u.displayName,prompt:b.prompt}})),{kind:"success"})}}}function Xbl(t){let e=new Set,l=[];for(let n of t)e.has(n.id)||(e.add(n.id),l.push(n));return l}async function unt(t,e,l,n,r){let a=await kbl(n);if(r===null)return{agents:a.agents,warnings:a.warnings};let I=await kbl(Jbl(r.path,".github","agents")),s=Xbl([...a.agents,...I.agents]),o=[...a.warnings,...I.warnings];if(r.kind!=="git")return{agents:s,warnings:o};if(!r.repo)return{agents:s,warnings:[...o,"could not load remote agents, no github.com remote found"]};if(!l)return{agents:s,warnings:[...o,L7(r.repo,"no authentication available")]};let d=await yqn(t,e,l,r.repo);return{agents:Xbl([...s,...d.agents]),warnings:[...o,...d.warnings]}}function L7(t,e){return`could not load remote agents for ${t.owner}/${t.name}: ${e}`}async function yqn(t,e,l,n){let r=dY(l,{onHMACAuthInfo:()=>xte,onEnvAuthInfo:g=>g.host,onGhCliAuthInfo:g=>g.host,onUserAuthInfo:g=>g.host,onApiKeyAuthInfo:g=>g.host}),{host:a}=new URL(r);if(a!=="github.com")return{agents:[],warnings:[L7(n,"auth info does not target github.com")]};let I=await ry(l);if(!I)return{agents:[],warnings:[L7(n,"no usable token for accessing repo contents found")]};let s=await Bbl(()=>R0(r,I,t),g=>jT("fetching copilot URL",g));if(s.kind==="error")return{agents:[],warnings:[L7(n,s.message)]};let o=`${s.value}/agents/swe/custom-agents/${n.owner}/${n.name}?exclude_invalid_config=true`,d={Authorization:`Bearer ${I}`},u=await NC(o,{method:"GET",headers:d},t);if(!u.ok)return t.warning(`Failed to load custom agents for ${n.owner}/${n.name}: ${await u.text()}`),{agents:[],warnings:[L7(n,`server returned ${u.status}: ${u.statusText}`)]};let b=await u.json(),h=SI.object({agents:SI.array(Obl)}).safeParse(b);return h.success?{agents:h.data.agents.map(g=>({id:g.name,displayName:g.display_name,prompt:async()=>{let N=await Qqn({logger:t,integrationId:e,sweAgentsEndpoint:`${s.value}/agents/swe`,token:I,repoOwner:g.repo_owner,repoName:g.repo_name,customAgentName:g.name});if(!N)throw new Error(`Failed to load prompt for agent ${g.name}`);return N.prompt}})),warnings:[]}:{agents:[],warnings:[L7(n,jT("parsing http response into schema",h.error))]}}async function kbl(t){let e=await Zqn(t,{withFileTypes:!0}).then(r=>({kind:"success",dirEntries:r})).catch(r=>r.code==="ENOENT"?{kind:"success",dirEntries:[]}:{kind:"error",message:jT(t,r)});if(e.kind==="error")return{agents:[],warnings:[]};let l=[],n=[];for(let r of e.dirEntries)if(r.isFile()&&r.name.endsWith(".md")){let a=Jbl(t,r.name),I=r.name.slice(0,-3),s=await Lbl(a);if(s.kind==="error"){n.push(s.message);continue}l.push({id:I,displayName:s.agent.name,prompt:async()=>{let o=await Lbl(a);if(o.kind==="error")throw new Error(o.message);return await o.agent.prompt()}})}return{agents:l,warnings:n}}async function Lbl(t){let e=await Bbl(()=>Nqn(t,"utf-8"),n=>jT(t,n));if(e.kind==="error")return{kind:"error",message:e.message};let l=Eqn(e.value);return l.kind==="error"?{kind:"error",message:`${t}: ${l.message}`}:{kind:"success",agent:l.agent}}var Eqn=t=>{let e=SI.object({name:SI.string(),description:SI.string(),tools:SI.array(SI.string()).optional()}).strict(),l=/^---\s*\n([\s\S]*?)\n---\s*\n?/,n=t.match(l);if(!n)return{kind:"error",message:"custom agent markdown frontmatter is malformed"};let r=n[1];try{let a=(0,xbl.parse)(r),I=e.safeParse(a);if(!I.success)return{kind:"error",message:Rqn(I.error)};let s=t.slice(n[0].length);return{kind:"success",agent:{name:I.data.name,description:I.data.description,tools:I.data.tools||["*"],prompt:()=>Promise.resolve(s)}}}catch(a){return{kind:"error",message:jT("failed to parse front matter",a)}}};function Rqn(t){return t.issues.map(e=>`${e.path.join(".")||"(root)"}: ${e.message}`).join(", ")}async function Bbl(t,e){try{return{kind:"success",value:await t()}}catch(l){return{kind:"error",message:e(l)}}}var Yqn=SI.object({command:SI.string(),args:SI.array(SI.string()),env:SI.record(SI.string(),SI.string()).optional(),tools:SI.array(SI.string()),type:SI.enum(["local","stdio"]).optional()}),Vqn=SI.object({url:SI.string(),headers:SI.record(SI.string(),SI.string()).optional(),tools:SI.array(SI.string()),type:SI.enum(["http","sse"])}),Obl=SI.object({name:SI.string(),repo_owner:SI.string(),repo_name:SI.string(),display_name:SI.string(),description:SI.string(),tools:SI.array(SI.string()),version:SI.string(),mcp_servers:SI.record(SI.string(),SI.union([Yqn,Vqn])).optional().nullable()}),wqn=Obl.extend({prompt:SI.string()});async function Qqn(t){t.logger.info(`Reading custom agent "${t.customAgentName}" from ${t.repoOwner}/${t.repoName}`);try{let e={"Copilot-Integration-Id":t.integrationId,Authorization:`Bearer ${t.token}`,"X-GitHub-Job-Nonce":t.jobNonce??""},l=await NC(`${t.sweAgentsEndpoint}/custom-agents/${t.repoOwner}/${t.repoName}/${t.customAgentName}`,{method:"GET",headers:e},t.logger,"get custom agent config");if(!l.ok){if(l.status===404)return null;throw new Error(`Failed to get custom agent config: ${l.status} ${l.statusText}`)}let n=await l.json();return wqn.parse(n)}catch(e){let l=e,n=l?.requestId||"unknown";throw t.logger.error(`Failed to get custom agent config (request ID: ${n}): ${l}`),l}}c();var cy=nt(nl(),1);function Tbl(t){let{cliModel:e,session:l,currentWorkingDirectory:n,customAgentName:r,stdoutColumns:a,models:I}=t,[s,o]=(0,cy.useState)({gitRoot:"",found:!1}),[d,u]=(0,cy.useState)(null);(0,cy.useEffect)(()=>{(async()=>{u(null);let w=await bY(n);o(w)})()},[n]);let b=(0,cy.useCallback)(async()=>{if(!s.found){u(null);return}let Y=await oPt(s.gitRoot);if(!Y){u(null);return}let w=await sPt(s.gitRoot);u(H=>H?.branch===Y&&H?.hasChanges===w?H:{branch:Y,hasChanges:w})},[s]),p=(0,cy.useMemo)(()=>YEe(n),[n]),[h,g]=(0,cy.useState)("");(0,cy.useEffect)(()=>{(async()=>{if(!I||I.type!=="success")return;let w=await rT(e,l,I.list);w&&g(H=>H===w?H:w)})()},[e,l,I]);let N=(0,cy.useMemo)(()=>{if(!d||!d.branch)return null;let Y=a||80,w=h.length,H=r?.length||0,L=p.length,S=d.hasChanges?6:5,O=w+L+S+4+H,B=Math.max(8,Y-O)-3;return`[\u2387 ${d.branch.length>B?d.branch.substring(0,B)+"...":d.branch}${d.hasChanges?"*":""}]`},[d,a,p,h]),y=(0,cy.useMemo)(()=>{if(!h)return h;let Y=I&&I.type==="success"?I.list:void 0,w=Wq(h,Y);return`${h} (${w}x)`},[h,I]);return{displayCwd:p,gitBranchInfo:N,selectedModel:h,selectedModelDisplay:y,setSelectedModel:g,updateGitStatus:b}}c();var Fg=nt(nl(),1),Fqn=3*1e3;function Ubl(){let[t,e]=(0,Fg.useState)("idle"),[l,n]=(0,Fg.useState)(0),[r,a]=(0,Fg.useState)(0),[I,s]=(0,Fg.useState)(!1),o=(0,Fg.useRef)(null);(0,Fg.useEffect)(()=>()=>{o.current&&clearTimeout(o.current)},[]);let d=(0,Fg.useCallback)(()=>{o.current&&(clearTimeout(o.current),o.current=null),e("indexing"),n(0),a(0),s(!0)},[]),u=(0,Fg.useCallback)((g,N)=>{e("completed"),n(g),a(N),s(!0),o.current=setTimeout(()=>{s(!1),o.current=null},Fqn)},[]),b=(0,Fg.useCallback)(()=>{o.current&&(clearTimeout(o.current),o.current=null),e("idle"),n(0),a(0),s(!1)},[]),p={state:t,fileCount:l,durationMs:r,isVisible:I},h=(0,Fg.useMemo)(()=>({startIndexing:d,completeIndexing:u,reset:b}),[d,u,b]);return[p,h]}c();var Mbl=nt(nl(),1);function _bl(t,e){(0,Mbl.useEffect)(()=>{if(t)return t.on("assistant.message",l=>{if(l.data.toolRequests){for(let n of l.data.toolRequests)if(n.name===EE.name){let r=n.arguments.intent;r&&e(r)}}})},[t,e])}c();var dve=nt(nl(),1);function Dbl(t,e,l,n){let[r,a]=(0,dve.useState)();return(0,dve.useEffect)(()=>{async function I(){if(!l)return;let s=await mnt(t,e,l,n);a(s)}I()},[l,e,n]),{models:r}}async function mnt(t,e,l,n){if(kL())return{type:"success",list:[]};try{if(l.type==="hmac")return{type:"success",list:await AO.createWithHmac(t,xte,n,l.hmac,e).listModels()};let r=await ry(l);if(!r)return{type:"noauth"};let a=await R0(l.host,r,t);return{type:"success",list:await AO.createWithOAuthToken(t,a,n,r,e).listModels()}}catch(r){return{type:"error",error:r}}}c();var mQ=nt(nl(),1);function zbl(t=3){let[e,l]=(0,mQ.useState)(!1),n=(0,mQ.useRef)(null),r=(0,mQ.useRef)(t*1e3);(0,mQ.useEffect)(()=>{r.current=t*1e3},[t]),(0,mQ.useEffect)(()=>()=>{n.current&&clearTimeout(n.current)},[]);let a=(0,mQ.useCallback)(I=>{n.current&&(clearTimeout(n.current),n.current=null),l(!0);let s=I!==void 0?I*1e3:r.current;n.current=setTimeout(()=>{l(!1),n.current=null},s)},[]);return[e,a]}c();var $be=nt(nl(),1);function Pbl({builtInSlashCommands:t,logger:e,currentWorkingDirectory:l,setCurrentWorkingDirectory:n,fileSearch:r,authManager:a,mcpHost:I,loginStatus:s,setLoginStatus:o,addEntryToSession:d,clearSessionHistory:u,getSessionUsageOutput:b,pathManager:p,resetSessionToolApprovals:h,clearTimeline:g,clearHeader:N,clearContextWindowMetrics:y,setThemePreference:Y,refreshStatic:w,hasAvailableCustomAgents:H,slashCommandResultActions:L}){let S=(0,$be.useMemo)(()=>({logger:e,slashCommands:t,hasAvailableCustomAgents:H,mcp:{host:I,config:async()=>await mY.load()||{mcpServers:{}},hasServer:async j=>(await S.mcp.config())?.mcpServers[j]!==void 0,deleteServer:async j=>{let B=await S.mcp.config();delete B.mcpServers[j],await mY.write(B)}},auth:{availableAuthMethods:()=>Xzt(a,s.authInfo),loginStatus:s,logout:async()=>{let j=await a.logout();return o({status:"NotLoggedIn"}),j}},session:{addTimelineEntry:d,clearHistory:u,usageOutput:b},permissions:{allowedDirs:p.getDirectories.bind(p),addAllowedDirectory:p.addDirectory.bind(p),resetSessionToolApprovals:h},process:{cwd:l,chdir:async j=>{process.chdir(j),await p.updatePrimaryDirectory(j),n(j),await r.setRootPath(j)}},ui:{getThemePreference:Twe,setThemePreference:Y,clear:()=>{g(),N(),y(),w()}}}),[t,e,l,n,r,a,I,s,o,d,u,b,p,h,N,y,Y,w,H]),U=(0,$be.useCallback)(async j=>{let B=Ud(()=>{let q=j.trim();return q==="?"?"/help":q});if(!B.startsWith("/"))return{handled:!1};let z=B.split(" ")[0],oe=t.find(q=>q.name===z||q.aliases?.includes(z));if(!oe)return{handled:!1};let he=B.substring(oe.name.length).trim().split(" ").filter(q=>q),Ge=await oe.execute(S,he);if(!Ge)return{handled:!0};switch(Ge.kind){case"exit":return L.exit(),{handled:!0};case"add-timeline-entry":return d(Ge.entry),{handled:!0};case"show-dialog":switch(Ge.dialog.kind){case"custom-agent-picker":L.showCustomAgentPickerDialog();break;case"feedback":L.showFeedbackDialog();break;case"login":L.showLoginDialog();break;case"mcp":L.showMCPDialog(Ge.dialog.mode,Ge.dialog.serverName);break;case"model-picker":L.showModelPickerDialog();break;case"session":L.showSessionDialog();break;case"user-switcher":L.showUserSwitcherDialog();break;default:xm(Ge.dialog,`Unknown dialog kind: ${Ge.dialog}`)}return{handled:!0};case"set-model":return await L.setModel(Ge.model),{handled:!0};case"noop":return{handled:!0};case"start-remote-delegate":return L.startRemoteDelegation(Ge.prompt),{handled:!0};default:xm(Ge,`Unknown slash command result kind: ${Ge}`)}},[t,d,L,S]),O=(0,$be.useCallback)(j=>Ame(t,j),[t]);return{slashCommands:t,handleSlashCommand:U,matchingSlashCommands:O}}c();var uve=nt(nl(),1);function jbl(t,e,l){let n=(0,uve.useMemo)(()=>new Map,[]);(0,uve.useEffect)(()=>{(async()=>{if(Object.keys(t).length===0||t.staff!==void 0||!e)return;let a=await ry(e),I=e.type==="hmac"?void 0:e.host;if(!a||I!==fL)return;let s=n.get(a)??ODt(I,a).catch(()=>!1);n.set(a,s),await s&&(await Sr.writeKey("staff",!0),await Sr.writeKey("log_level","all"),l({type:"info",text:"Staff mode activated! Restart the app to enable staff features \u2728"}))})()},[t,e,l])}c();var sJ=nt(nl(),1);function Kbl(t,e,l){let[n,r]=(0,sJ.useState)(null),a=(0,sJ.useRef)("");return(0,sJ.useEffect)(()=>{e.text!==a.current&&(n?.availableOptions.some(o=>e.text===o.name)||r(null),a.current=e.text)},[e.text,n]),{handleTabCompletion:(0,sJ.useCallback)(()=>{let s=o=>{let d=o.indexOf(" ");return d===-1?!1:o.slice(d+1).trim().length>0};if(n){if(s(e.text)){r(null);return}let o=(n.currentIndex+1)%n.availableOptions.length,d=n.availableOptions[o];e.setText(d.name),r({...n,currentIndex:o}),l.setSlashCommandPickerIndex(o)}else{if(s(e.text))return;let o=Ame(t,e.text);if(o.length===1){let d=o[0],u=d.name;for(let b=u.length-1;b>=2;b--){let p=u.slice(0,b),h=Ame(t,p);if(h.length>1){let g=h.findIndex(Y=>Y.name===d.name);r({originalInput:p,availableOptions:h,currentIndex:g>=0?g:0});let N=(g+1)%h.length,y=h[N];e.setText(y.name),r({originalInput:p,availableOptions:h,currentIndex:N}),l.setSlashCommandPickerIndex(N);return}}}o.length>1?(r({originalInput:e.text,availableOptions:o,currentIndex:0}),e.setText(o[0].name),l.setSlashCommandPickerIndex(0)):o.length===1&&e.setText(o[0].name)}},[n,e,l]),tabCyclingState:n}}c();var tH=nt(nl(),1);function qbl(){let[t,e]=(0,tH.useState)({columns:process.stdout.columns,rows:process.stdout.rows}),l=(0,tH.useRef)(()=>{}),n=(0,tH.useCallback)(a=>{l.current=a||(()=>{})},[]),r=(0,tH.useCallback)(()=>{let{columns:a,rows:I}=process.stdout;e({columns:a,rows:I}),l.current(a,I)},[]);return(0,tH.useEffect)(()=>(process.stdout.on("resize",r),()=>{process.stdout.off("resize",r)}),[]),{...t,setOnResize:n}}c();var x7=nt(nl(),1);var oJ=t=>/\s/.test(t);function Cqn(t,e){if(e>=t.length)return t.length;let l=e;for(;l<t.length&&oJ(t[l]);)l+=t[l].length;for(;l<t.length&&!oJ(t[l]);)l+=t[l].length;return l}function $bl(t,e){if(e===0)return 0;let l=e-1;for(;l>=0&&oJ(t[l]);)l-=t[l].length;if(l<0)return 0;for(;l>=0&&!oJ(t[l]);)l-=t[l].length;return l+1}function vqn(t,e){if(e>=t.length)return t.length;let l=e;for(;l<t.length&&!oJ(t[l]);)l+=t[l].length;for(;l<t.length&&oJ(t[l]);)l+=t[l].length;return l}function KT(t,e){if(e<=0)return[t];let l=t.split(`
|
|
2450
2450
|
`).map(r=>r+" "),n=[];for(let r of l){if(r.length<=e){n.push(r);continue}let a=r;for(;a.length>e;){let I=e;if(oJ(a.slice(0,e)))for(let o=e-1;o>=Math.max(0,e-20)&&!oJ(a[o]);o--)I=o;let s=a.slice(0,I);n.push(s),a=a.slice(I)}a.length>0&&n.push(a)}return n}function S7(t,e){if(e.length===0)return{line:0,column:0};let l=0;for(let r=0;r<e.length;r++){let a=e[r],I=l+a.length;if(t<I)return{line:r,column:t-l};l=I}let n=e.length-1;return{line:n,column:e[n].length}}function J7(t,e,l,n){if(t.length===0)return 0;let r=0;for(let a=0;a<Math.min(e,t.length);a++)r+=t[a].length;return e<t.length?r+=Math.min(l,t[e].length):r=n.length,Math.min(r,n.length)}function fqn(t,e){switch(e.type){case"set_text":return{text:e.payload,cursorPosition:e.payload.length,width:t.width};case"set_cursor_position":return{...t,cursorPosition:Math.max(0,Math.min(e.payload,t.text.length))};case"set_cursor_line_position":{let{line:l,column:n}=e.payload,r=KT(t.text,t.width),a=J7(r,l,n,t.text);return{...t,cursorPosition:a}}case"set_width":return t.width===e.payload?t:{...t,width:e.payload};case"insert_input":{let{text:l,cursorPosition:n}=t,{input:r,callback:a}=e.payload,I=r.replace(/\r\n/g,`
|
|
2451
2451
|
`).replace(/\r/g,`
|
|
2452
2452
|
`),s=l.slice(0,n),o=l.slice(n),d=s+I+o,u=n+I.length;return a?.(d),{text:d,cursorPosition:u,width:t.width}}case"backspace":return t.cursorPosition===0?t:{text:t.text.slice(0,t.cursorPosition-1)+t.text.slice(t.cursorPosition),cursorPosition:t.cursorPosition-1,width:t.width};case"forward_delete":{if(t.cursorPosition>=t.text.length)return t;let l=t.text.slice(0,t.cursorPosition)+t.text.slice(t.cursorPosition+1);return{...t,text:l}}case"backspace_word":{let{text:l,cursorPosition:n}=t;if(n===0)return t;let r=$bl(l,n);return{text:l.slice(0,r)+l.slice(n),cursorPosition:r,width:t.width}}case"forward_delete_word":{let{text:l,cursorPosition:n}=t;if(n>=l.length)return t;let r=Cqn(l,n),a=l.slice(0,n)+l.slice(r);return{...t,text:a}}case"move_word_left":{let{text:l,cursorPosition:n}=t;if(n===0)return t;let r=$bl(l,n);return{...t,cursorPosition:r}}case"move_word_right":{let{text:l,cursorPosition:n}=t;if(n>=l.length)return t;let r=vqn(l,n);return{...t,cursorPosition:r}}case"move_right":return t.cursorPosition===t.text.length?t:{...t,cursorPosition:t.cursorPosition+1};case"move_left":return t.cursorPosition===0?t:{...t,cursorPosition:t.cursorPosition-1};case"move_up":{let{text:l,cursorPosition:n,width:r}=t,a=KT(l,r),I=S7(n,a);if(I.line>0){let s=I.line-1,o=Math.min(I.column,a[s].length-1),d=J7(a,s,o,l);return{...t,cursorPosition:d}}return t}case"move_down":{let{text:l,cursorPosition:n,width:r}=t,a=KT(l,r),I=S7(n,a);if(I.line<a.length-1){let s=I.line+1,o=Math.min(I.column,a[s].length-1),d=J7(a,s,o,l);return{...t,cursorPosition:d}}return t}case"clear":return{text:"",cursorPosition:0,width:t.width};case"clear_before_cursor":{let{text:l,cursorPosition:n,width:r}=t,a=KT(l,r),I=S7(n,a),s=J7(a,I.line,0,l);return{text:l.slice(0,s)+l.slice(n),cursorPosition:s,width:r}}case"clear_after_cursor":{let{text:l,cursorPosition:n}=t,r=l.indexOf(`
|
|
@@ -2454,9 +2454,9 @@ Run `+Sl.cyan("{updateCommand}")+" to update",a=e.message||r;e.boxenOptions??={p
|
|
|
2454
2454
|
`),l=0,n=0,r;for(let a of e){if(a.startsWith("diff --git")&&!r){let I=a.match(/diff --git a\/(.+) b\//);I&&(r=I[1])}a.startsWith("+")&&!a.startsWith("+++")?l++:a.startsWith("-")&&!a.startsWith("---")&&n++}return{linesAdded:l,linesRemoved:n,filePath:r}}function bve(t){return t===0?"0":t<1e3?t.toString():t<1e6?`${(t/1e3).toFixed(1)}k`:`${(t/1e6).toFixed(1)}m`}function lGl(t){return t===0?"0":Number.isInteger(t)?t.toString():t.toFixed(2).replace(/\.?0+$/,"")}function nGl(t){let e=Math.floor(t/1e3),l=Math.floor(e/60),n=Math.floor(l/60);if(n>0){let r=l%60,a=t%6e4/1e3;return`${n}h ${r}m ${a.toFixed(1)}s`}else if(l>0){let r=t%6e4/1e3;return`${l}m ${r.toFixed(1)}s`}else return`${(t/1e3).toFixed(1)}s`}function pve(t){let e=nGl(Date.now()-t.sessionStartTime),l=nGl(t.totalApiDurationMs),n=lGl(t.totalPremiumRequests),r=t.totalPremiumRequests===1?"Premium request":"Premium requests",a=[`Total usage est: ${n} ${r}`,`Total duration (API): ${l}`,`Total duration (wall): ${e}`,`Total code changes: ${t.codeChanges.linesAdded} lines added, ${t.codeChanges.linesRemoved} lines removed`];if(t.modelMetrics.size>0){a.push("Usage by model:");for(let[I,s]of t.modelMetrics){let{requests:o,usage:d}=s,u=bve(d.inputTokens),b=bve(d.outputTokens),p=bve(d.cacheReadTokens),h=bve(d.cacheWriteTokens),g=lGl(o.cost),N=parseFloat(o.cost.toString())===1?"Premium request":"Premium requests",Y=(I||"(unknown)").padEnd(20);a.push(` ${Y} ${u} input, ${b} output, ${p} cache read, ${h} cache write (Est. ${g} ${N})`)}}return a.join(`
|
|
2455
2455
|
`)}c();import*as aGl from"fs";function tGe(t,e){return{mcpServers:{...t.mcpServers,...e.mcpServers}}}function Lqn(t){try{let e=JSON.parse(t);return Bqe.parse(e)}catch(e){if(e instanceof SyntaxError)throw new Error(`Invalid JSON in --additional-mcp-config: ${e.message}`);if(e instanceof Oh){let l=e.errors.map(n=>`${n.path.join(".")}: ${n.message}`).join("; ");throw new Error(`Invalid MCP server configuration in --additional-mcp-config: ${l}`)}throw e}}function IGl(t){let e;if(t.startsWith("@")){let l=t.slice(1);try{e=aGl.readFileSync(l,"utf-8")}catch(n){throw n instanceof Error?new Error(`Failed to read MCP config file "${l}": ${n.message}`):n}}else e=t;return Lqn(e)}c();import{realpathSync as hve}from"fs";import{tmpdir as Jqn}from"os";import{isAbsolute as lGe,normalize as xqn,relative as Sqn,sep as Bqn}from"path";var nGe=class{directories=[];primaryDirectory;constructor(e,l=[],n){if(this.primaryDirectory=this.resolveAndValidateDirectory(e),this.directories=[this.primaryDirectory],n?.includeTempDirectory??!0){let a=Jqn(),I=this.resolveAndValidateDirectory(a);this.directories.includes(I)||this.directories.push(I)}for(let a of l){let I=this.resolveAndValidateDirectory(a);this.directories.includes(I)||this.directories.push(I)}}getDirectories(){return[...this.directories]}getPrimaryDirectory(){return this.primaryDirectory}async updatePrimaryDirectory(e){let l=this.resolveAndValidateDirectory(e);if(!await gC(l))throw new Error(`Directory does not exist: ${e}`);this.directories=this.directories.filter(r=>r!==this.primaryDirectory),this.directories.unshift(l),this.primaryDirectory=l}async addDirectory(e){let l=this.resolveAndValidateDirectory(e);if(!await gC(l))throw new Error(`Directory does not exist: ${e}`);this.directories.includes(l)||this.directories.push(l)}isPathWithinAllowedDirectories(e){if(e==="/dev/null")return!0;try{let l=this.fullyResolvedPath(e);for(let n of this.directories)if(this.isPathWithinRoot(l,n))return!0;return!1}catch{return!1}}fullyResolvedPath(e){try{if(!lGe(e))throw new Error(`Path must be absolute: ${e}`);return hve(e)}catch{return xqn(e)}}isPathWithinRoot(e,l){let n=Sqn(l,e);return!n.startsWith(`..${Bqn}`)&&n!==".."&&!lGe(n)}resolveAndValidateDirectory(e){if(!e)throw new Error("Directory path cannot be empty");if(!lGe(e))throw new Error(`Directory path must be absolute: ${e}`);try{return hve(e)}catch{throw new Error(`Directory does not exist or cannot be accessed: ${e}`)}}},rGe=class{primaryDirectory;constructor(e){if(!e)throw new Error("Directory path cannot be empty");if(!lGe(e))throw new Error(`Directory path must be absolute: ${e}`);try{this.primaryDirectory=hve(e)}catch{throw new Error(`Directory does not exist or cannot be accessed: ${e}`)}}getDirectories(){return[this.primaryDirectory]}getPrimaryDirectory(){return this.primaryDirectory}async updatePrimaryDirectory(e){if(!lGe(e))throw new Error(`Directory path must be absolute: ${e}`);if(!await gC(e))throw new Error(`Directory does not exist: ${e}`);try{this.primaryDirectory=hve(e)}catch{throw new Error(`Directory does not exist or cannot be accessed: ${e}`)}}async addDirectory(e){}isPathWithinAllowedDirectories(e){return!0}};c();c();c();c();var sGl=t=>{t=1831565813+(t|=0)|0;let e=Math.imul(t^t>>>15,1|t);return e=e+Math.imul(e^e>>>7,61|e)^e,((e^e>>>14)>>>0)/4294967296},bnt=class{constructor(e){this.dictionaries=void 0,this.length=void 0,this.separator=void 0,this.style=void 0,this.seed=void 0;let{length:l,separator:n,dictionaries:r,style:a,seed:I}=e;this.dictionaries=r,this.separator=n,this.length=l,this.style=a,this.seed=I}generate(){if(!this.dictionaries)throw new Error('Cannot find any dictionary. Please provide at least one, or leave the "dictionary" field empty in the config object');if(this.length<=0)throw new Error("Invalid length provided");if(this.length>this.dictionaries.length)throw new Error(`The length cannot be bigger than the number of dictionaries.
|
|
2456
2456
|
Length provided: ${this.length}. Number of dictionaries provided: ${this.dictionaries.length}`);let e=this.seed;return this.dictionaries.slice(0,this.length).reduce((l,n)=>{let r;e?(r=(I=>{if(typeof I=="string"){let s=I.split("").map(d=>d.charCodeAt(0)).reduce((d,u)=>d+u,1),o=Math.floor(Number(s));return sGl(o)}return sGl(I)})(e),e=4294967296*r):r=Math.random();let a=n[Math.floor(r*n.length)]||"";if(this.style==="lowerCase")a=a.toLowerCase();else if(this.style==="capital"){let[I,...s]=a.split("");a=I.toUpperCase()+s.join("")}else this.style==="upperCase"&&(a=a.toUpperCase());return l?`${l}${this.separator}${a}`:`${a}`},"")}},oGl={separator:"_",dictionaries:[]},iGl=t=>{let e=[...t&&t.dictionaries||oGl.dictionaries],l={...oGl,...t,length:t&&t.length||e.length,dictionaries:e};if(!t||!t.dictionaries||!t.dictionaries.length)throw new Error('A "dictionaries" array must be provided. This is a breaking change introduced starting from Unique Name Generator v4. Read more about the breaking change here: https://github.com/andreasonny83/unique-names-generator#migration-guide');return new bnt(l).generate()},cGl=["able","above","absent","absolute","abstract","abundant","academic","acceptable","accepted","accessible","accurate","accused","active","actual","acute","added","additional","adequate","adjacent","administrative","adorable","advanced","adverse","advisory","aesthetic","afraid","aggregate","aggressive","agreeable","agreed","agricultural","alert","alive","alleged","allied","alone","alright","alternative","amateur","amazing","ambitious","amused","ancient","angry","annoyed","annual","anonymous","anxious","appalling","apparent","applicable","appropriate","arbitrary","architectural","armed","arrogant","artificial","artistic","ashamed","asleep","assistant","associated","atomic","attractive","automatic","autonomous","available","average","awake","aware","awful","awkward","back","bad","balanced","bare","basic","beautiful","beneficial","better","bewildered","big","binding","biological","bitter","bizarre","blank","blonde","blushing","boiling","bold","bored","boring","bottom","brainy","brave","breakable","breezy","brief","bright","brilliant","broad","broken","bumpy","burning","busy","calm","capable","careful","casual","causal","cautious","central","certain","changing","characteristic","charming","cheap","cheerful","chemical","chief","chilly","chosen","chronic","chubby","circular","civic","civil","classic","classical","clean","clear","clever","clinical","close","closed","cloudy","clumsy","coastal","cognitive","coherent","cold","collective","colorful","colossal","coloured","colourful","combined","comfortable","commercial","common","compact","comparable","comparative","compatible","competent","competitive","complete","complex","complicated","comprehensive","compulsory","conceptual","concerned","concrete","condemned","confident","confidential","confused","conscious","conservation","considerable","consistent","constant","constitutional","contemporary","content","continental","continued","continuing","continuous","controlled","controversial","convenient","conventional","convinced","convincing","cooing","cool","cooperative","corporate","correct","corresponding","costly","courageous","creative","creepy","criminal","critical","crooked","crowded","crucial","crude","cruel","cuddly","cultural","curious","curly","current","curved","cute","daily","damaged","damp","dangerous","dark","dead","deafening","dear","decent","decisive","deep","defeated","defensive","defiant","definite","deliberate","delicate","delicious","delighted","delightful","democratic","dependent","depressed","desirable","desperate","detailed","determined","developed","developing","devoted","different","difficult","digital","diplomatic","direct","dirty","disappointed","disastrous","disciplinary","disgusted","distant","distinct","distinctive","distinguished","disturbed","disturbing","diverse","divine","dizzy","domestic","dominant","double","doubtful","drab","dramatic","dreadful","driving","dry","dual","due","dull","dusty","dutch","dying","dynamic","eager","early","eastern","easy","economic","educational","eerie","effective","efficient","elaborate","elated","elderly","eldest","electoral","electric","electrical","electronic","elegant","eligible","embarrassed","embarrassing","emotional","empirical","empty","enchanting","encouraging","endless","energetic","enormous","enthusiastic","entire","entitled","envious","environmental","equal","equivalent","essential","established","estimated","ethical","eventual","everyday","evident","evil","evolutionary","exact","excellent","exceptional","excess","excessive","excited","exciting","exclusive","existing","exotic","expected","expensive","experienced","experimental","explicit","extended","extensive","external","extra","extraordinary","extreme","exuberant","faint","fair","faithful","familiar","famous","fancy","fantastic","far","fascinating","fashionable","fast","fatal","favourable","favourite","federal","fellow","few","fierce","final","financial","fine","firm","fiscal","fit","fixed","flaky","flat","flexible","fluffy","fluttering","flying","following","fond","foolish","foreign","formal","formidable","forthcoming","fortunate","forward","fragile","frail","frantic","free","frequent","fresh","friendly","frightened","front","frozen","full","fun","functional","fundamental","funny","furious","future","fuzzy","gastric","general","generous","genetic","gentle","genuine","geographical","giant","gigantic","given","glad","glamorous","gleaming","global","glorious","golden","good","gorgeous","gothic","governing","graceful","gradual","grand","grateful","greasy","great","grieving","grim","gross","grotesque","growing","grubby","grumpy","guilty","handsome","happy","hard","harsh","head","healthy","heavy","helpful","helpless","hidden","high","hilarious","hissing","historic","historical","hollow","holy","homely","hon","honest","horizontal","horrible","hostile","hot","huge","human","hungry","hurt","hushed","husky","icy","ideal","identical","ideological","ill","illegal","imaginative","immediate","immense","implicit","important","impossible","impressed","impressive","improved","inadequate","inc","inclined","increased","increasing","incredible","independent","indirect","individual","industrial","inevitable","influential","informal","inherent","initial","injured","inland","inner","innocent","innovative","inquisitive","instant","institutional","insufficient","intact","integral","integrated","intellectual","intelligent","intense","intensive","interested","interesting","interim","interior","intermediate","internal","international","invisible","involved","irrelevant","isolated","itchy","jealous","jittery","joint","jolly","joyous","judicial","juicy","junior","just","keen","key","kind","known","labour","large","late","latin","lazy","leading","left","legal","legislative","legitimate","lengthy","lesser","level","lexical","liable","light","like","likely","limited","linear","linguistic","liquid","literary","little","live","lively","living","local","logical","lonely","long","loose","lost","loud","lovely","low","loyal","ltd","lucky","mad","magic","magnetic","magnificent","main","major","mammoth","managerial","managing","manual","many","marginal","marine","marked","married","marvellous","mass","massive","mathematical","mature","maximum","mean","meaningful","mechanical","medical","medieval","melodic","melted","mental","mere","metropolitan","mid","middle","mighty","mild","military","miniature","minimal","minimum","ministerial","minor","miserable","misleading","missing","misty","mixed","moaning","mobile","moderate","modern","modest","molecular","monetary","monthly","moral","motionless","muddy","multiple","mushy","musical","mutual","mysterious","naked","narrow","nasty","national","natural","naughty","naval","near","nearby","neat","necessary","negative","neighbouring","nervous","net","neutral","new","nice","noble","noisy","normal","northern","nosy","notable","novel","nuclear","numerous","nursing","nutritious","nutty","obedient","objective","obliged","obnoxious","obvious","occasional","occupational","odd","official","ok","okay","old","only","open","operational","opposite","optimistic","ordinary","organic","organisational","original","orthodox","other","outdoor","outer","outrageous","outside","outstanding","overall","overseas","overwhelming","painful","pale","panicky","parallel","parental","parliamentary","partial","particular","passing","passive","past","patient","payable","peaceful","peculiar","perfect","permanent","persistent","personal","petite","philosophical","physical","plain","planned","plastic","pleasant","pleased","poised","polite","poor","popular","positive","possible","potential","powerful","practical","precious","precise","preferred","pregnant","preliminary","premier","prepared","present","presidential","pretty","previous","prickly","primary","prime","principal","printed","prior","private","probable","productive","professional","profitable","profound","progressive","prominent","promising","proper","proposed","prospective","protective","proud","provincial","psychiatric","psychological","public","puny","pure","purring","puzzled","quaint","qualified","quarrelsome","querulous","quick","quickest","quiet","quintessential","quixotic","racial","radical","rainy","random","rapid","rare","raspy","rational","ratty","raw","ready","real","realistic","rear","reasonable","recent","reduced","redundant","regional","registered","regular","regulatory","related","relative","relaxed","relevant","reliable","relieved","religious","reluctant","remaining","remarkable","remote","renewed","representative","repulsive","required","resident","residential","resonant","respectable","respective","responsible","resulting","retail","retired","revolutionary","rich","ridiculous","right","rigid","ripe","rising","rival","roasted","robust","rolling","romantic","rotten","rough","round","royal","rubber","rude","ruling","running","rural","sacred","sad","safe","salty","satisfactory","satisfied","scared","scary","scattered","scientific","scornful","scrawny","screeching","secondary","secret","secure","select","selected","selective","selfish","semantic","senior","sensible","sensitive","separate","serious","severe","shaggy","shaky","shallow","shared","sharp","sheer","shiny","shivering","shocked","short","shrill","shy","sick","significant","silent","silky","silly","similar","simple","single","skilled","skinny","sleepy","slight","slim","slimy","slippery","slow","small","smart","smiling","smoggy","smooth","social","soft","solar","sole","solid","sophisticated","sore","sorry","sound","sour","southern","spare","sparkling","spatial","special","specific","specified","spectacular","spicy","spiritual","splendid","spontaneous","sporting","spotless","spotty","square","squealing","stable","stale","standard","static","statistical","statutory","steady","steep","sticky","stiff","still","stingy","stormy","straight","straightforward","strange","strategic","strict","striking","striped","strong","structural","stuck","subjective","subsequent","substantial","subtle","successful","successive","sudden","sufficient","suitable","sunny","super","superb","superior","supporting","supposed","supreme","sure","surprised","surprising","surrounding","surviving","suspicious","sweet","swift","symbolic","sympathetic","systematic","tall","tame","tart","tasteless","tasty","technical","technological","teenage","temporary","tender","tense","terrible","territorial","testy","then","theoretical","thick","thin","thorough","thoughtful","thoughtless","thundering","tight","tiny","tired","top","total","tough","toxic","traditional","tragic","tremendous","tricky","tropical","troubled","typical","ugliest","ugly","ultimate","unable","unacceptable","unaware","uncertain","unchanged","uncomfortable","unconscious","underground","underlying","unemployed","uneven","unexpected","unfair","unfortunate","unhappy","uniform","uninterested","unique","united","universal","unknown","unlikely","unnecessary","unpleasant","unsightly","unusual","unwilling","upper","upset","uptight","urban","urgent","used","useful","useless","usual","vague","valid","valuable","variable","varied","various","varying","vast","verbal","vertical","very","vicarious","vicious","victorious","violent","visible","visiting","visual","vital","vitreous","vivacious","vivid","vocal","vocational","voiceless","voluminous","voluntary","vulnerable","wandering","warm","wasteful","watery","weak","wealthy","weary","wee","weekly","weird","welcome","well","western","wet","whispering","whole","wicked","wide","widespread","wild","wilful","willing","willowy","wily","wise","wispy","wittering","witty","wonderful","wooden","working","worldwide","worried","worrying","worthwhile","worthy","written","wrong","xenacious","xenial","xenogeneic","xeric","xerothermic","yabbering","yammering","yappiest","yappy","yawning","yearling","yearning","yeasty","yelling","yelping","yielding","yodelling","young","youngest","youthful","ytterbic","yucky","yummy","zany","zealous","zeroth","zestful","zesty","zippy","zonal","zoophagous","zygomorphic","zygotic"],dGl=["aardvark","aardwolf","albatross","alligator","alpaca","amphibian","anaconda","angelfish","anglerfish","ant","anteater","antelope","antlion","ape","aphid","armadillo","asp","baboon","badger","bandicoot","barnacle","barracuda","basilisk","bass","bat","bear","beaver","bedbug","bee","beetle","bird","bison","blackbird","boa","boar","bobcat","bobolink","bonobo","bovid","bug","butterfly","buzzard","camel","canid","canidae","capybara","cardinal","caribou","carp","cat","caterpillar","catfish","catshark","cattle","centipede","cephalopod","chameleon","cheetah","chickadee","chicken","chimpanzee","chinchilla","chipmunk","cicada","clam","clownfish","cobra","cockroach","cod","condor","constrictor","coral","cougar","cow","coyote","crab","crane","crawdad","crayfish","cricket","crocodile","crow","cuckoo","damselfly","deer","dingo","dinosaur","dog","dolphin","donkey","dormouse","dove","dragon","dragonfly","duck","eagle","earthworm","earwig","echidna","eel","egret","elephant","elk","emu","ermine","falcon","felidae","ferret","finch","firefly","fish","flamingo","flea","fly","flyingfish","fowl","fox","frog","galliform","gamefowl","gayal","gazelle","gecko","gerbil","gibbon","giraffe","goat","goldfish","goose","gopher","gorilla","grasshopper","grouse","guan","guanaco","guineafowl","gull","guppy","haddock","halibut","hamster","hare","harrier","hawk","hedgehog","heron","herring","hippopotamus","hookworm","hornet","horse","hoverfly","hummingbird","hyena","iguana","impala","jackal","jaguar","jay","jellyfish","junglefowl","kangaroo","kingfisher","kite","kiwi","koala","koi","krill","ladybug","lamprey","landfowl","lark","leech","lemming","lemur","leopard","leopon","limpet","lion","lizard","llama","lobster","locust","loon","louse","lungfish","lynx","macaw","mackerel","magpie","mammal","manatee","mandrill","marlin","marmoset","marmot","marsupial","marten","mastodon","meadowlark","meerkat","mink","minnow","mite","mockingbird","mole","mollusk","mongoose","monkey","moose","mosquito","moth","mouse","mule","muskox","narwhal","newt","nightingale","ocelot","octopus","opossum","orangutan","orca","ostrich","otter","owl","ox","panda","panther","parakeet","parrot","parrotfish","partridge","peacock","peafowl","pelican","penguin","perch","pheasant","pig","pigeon","pike","pinniped","piranha","planarian","platypus","pony","porcupine","porpoise","possum","prawn","primate","ptarmigan","puffin","puma","python","quail","quelea","quokka","rabbit","raccoon","rat","rattlesnake","raven","reindeer","reptile","rhinoceros","roadrunner","rodent","rook","rooster","roundworm","sailfish","salamander","salmon","sawfish","scallop","scorpion","seahorse","shark","sheep","shrew","shrimp","silkworm","silverfish","skink","skunk","sloth","slug","smelt","snail","snake","snipe","sole","sparrow","spider","spoonbill","squid","squirrel","starfish","stingray","stoat","stork","sturgeon","swallow","swan","swift","swordfish","swordtail","tahr","takin","tapir","tarantula","tarsier","termite","tern","thrush","tick","tiger","tiglon","toad","tortoise","toucan","trout","tuna","turkey","turtle","tyrannosaurus","unicorn","urial","vicuna","viper","vole","vulture","wallaby","walrus","warbler","wasp","weasel","whale","whippet","whitefish","wildcat","wildebeest","wildfowl","wolf","wolverine","wombat","woodpecker","worm","wren","xerinae","yak","zebra"];import{execFile as Oqn}from"node:child_process";import{promisify as Tqn}from"node:util";function O7(t){let[e,l]=t.split("/");if(!e||!l)throw new Error(`Invalid repository format: ${t}. Expected format: owner/repo`);return{owner:e,repo:l}}var NN=Tqn(Oqn);async function uGl(t){try{let{stdout:e}=await NN("git",["status","--porcelain"],{cwd:t,encoding:"utf8",timeout:5e3,maxBuffer:1048576}),l=e.split(`
|
|
2457
|
-
`).filter(I=>I.length>0),n=0,r=0,a=0;for(let I of l){if(I.length<2)continue;let s=I[0],o=I[1];s==="?"&&o==="?"?a++:(s!==" "&&s!=="?"&&n++,o!==" "&&o!=="?"&&r++)}return{staged:n,unstaged:r,untracked:a,hasChanges:l.length>0}}catch{return{staged:0,unstaged:0,untracked:0,hasChanges:!1}}}async function mGl(){return"Checkpoint from Copilot CLI for coding agent session"}async function bGl(t){let{stdout:e}=await NN("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:t,encoding:"utf8",timeout:5e3});return e.trim()}async function GGl(t){try{return await bGl(t)==="HEAD"}catch{return!1}}async function Uqn(t){try{let{stdout:e}=await NN("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:t,encoding:"utf8",timeout:5e3}),l=e.trim();if(!l||l==="HEAD")return"origin";let{stdout:n}=await NN("git",["config",`branch.${l}.remote`],{cwd:t,encoding:"utf8",timeout:5e3});return n.trim()||"origin"}catch{return"origin"}}async function Mqn(t){let e=await Uqn(t);try{let{stdout:l}=await NN("git",["symbolic-ref",`refs/remotes/${e}/HEAD`],{cwd:t,encoding:"utf8",timeout:5e3}),n=l.match(new RegExp(`refs/remotes/${e}/(.+)`));if(n)return n[1].trim()}catch{}try{return await NN("git",["rev-parse","--verify",`refs/remotes/${e}/main`],{cwd:t,encoding:"utf8",timeout:5e3}),"main"}catch{}try{return await NN("git",["rev-parse","--verify",`refs/remotes/${e}/master`],{cwd:t,encoding:"utf8",timeout:5e3}),"master"}catch{return"main"}}async function _qn(t,e){try{return await NN("git",["rev-parse","--verify",`refs/heads/${e}`],{cwd:t,encoding:"utf8",timeout:5e3}),!0}catch{return!1}}async function Dqn(t,e){let n=["adjectives","animals"],a=[];for(let I of n)I.toLowerCase()==="adjectives"&&a.push(cGl),I.toLowerCase()==="animals"&&a.push(dGl);if(a.length===0)return`${e}/session${Date.now()}`;for(let I=0;I<5;I++){let s=`${e}/${iGl({dictionaries:a,length:a.length,separator:"-"})}`;if(!await _qn(t,s))return s}return`${e}/session${Date.now()}`}async function zqn(t){return Dqn(t,"copilot")}async function Gnt(t){try{let[e,l,n,r]=await Promise.all([bGl(t),ove(t),Mqn(t),zqn(t)]);if(!l)throw new Error("Could not determine GitHub repository from git remotes");return{repository:`${l.owner}/${l.name}`,baseBranch:n,headBranch:e,asyncBranch:r}}catch(e){throw new Error(`Failed to get repository info: ${e instanceof Error?e.message:String(e)}`)}}async function pGl(t,e){try{await NN("git",["add","--all"],{cwd:t,encoding:"utf8",timeout:1e4,maxBuffer:10*1024*1024});let{stdout:l}=await NN("git",["commit","-m",e],{cwd:t,encoding:"utf8",timeout:1e4,maxBuffer:10*1024*1024}),n,r=l.match(/\[[\w/-]+ ([a-f0-9]+)\]/);if(!r||!r[1]){let{stdout:a}=await NN("git",["rev-parse","--short","HEAD"],{cwd:t,encoding:"utf8",timeout:5e3});n=a.trim()}else n=r[1];return{commitHash:n,commitMessage:e}}catch(l){let n=l instanceof Error?l.message:String(l);throw n.includes("pre-commit")?new Error(`Pre-commit hook prevented the commit: ${n}`):n.includes("commit-msg")?new Error(`Commit-msg hook rejected the commit: ${n}`):n.includes("nothing to commit")||n.includes("no changes added")?new Error(`No changes to commit (possibly filtered by hooks): ${n}`):new Error(`Failed to commit changes: ${n}`)}}async function hGl(t,e=process.cwd()){try{await NN("git",["checkout",t],{cwd:e,encoding:"utf8",timeout:5e3,maxBuffer:10*1024*1024})}catch(l){let n=l instanceof Error?l.message:String(l);throw new Error(`Failed to switch to branch '${t}': ${n}`)}}async function AGl(t){let{cwd:e,asyncBranch:l}=t;try{await NN("git",["checkout","-b",l],{cwd:e,encoding:"utf8",timeout:1e4,maxBuffer:10*1024*1024}),await NN("git",["push","-u","origin",l],{cwd:e,encoding:"utf8",timeout:3e4,maxBuffer:10*1024*1024})}catch(n){let r=n instanceof Error?n.message:String(n);throw r.includes("branch")&&r.includes("already exists")?new Error(`Branch '${l}' already exists: ${r}`):r.includes("Could not read from remote repository")?new Error(`Failed to push branch - repository access issue: ${r}`):r.includes("Permission denied")||r.includes("403")?new Error(`Failed to push branch - permission denied: ${r}`):r.includes("remote rejected")?new Error(`Remote rejected the git push: ${r}`):new Error(`Failed to create and push branch '${l}': ${r}`)}}c();var T7=class extends Error{constructor(l,n,r){super(n);this.status=l;this.message=n;this.responseBody=r;this.name="HttpApiError"}};async function aGe(t){let e=await ry(t);if(!e)throw new Error("Failed to get authentication token");return e}async function Pqn(t){let e=t.statusText||`HTTP ${t.status}`,l;try{l=await t.json(),typeof l=="object"&&l&&"message"in l&&(e=l.message)}catch{try{let n=await t.text();n&&(l=n)}catch{}}return{message:e,body:l}}async function qT(t,e,l){let{message:n,body:r}=await Pqn(t),a;switch(t.status){case 400:a=`Bad request: ${n}`;break;case 401:a=`Unauthorized: ${n}`;break;case 402:a=e==="job"?"No remaining quota for premium requests":`Payment required: ${n}`;break;case 403:e==="job"||e==="agent"?a=`Coding Agent not enabled: ${n}`:a=`Forbidden: ${n}`;break;case 404:e==="job"&&l?.jobId?a=`Job not found: ${l.jobId}`:e==="session"&&l?.sessionId?a=`Session not found: ${l.sessionId}`:e==="repository"&&l?.repository?a=`Repository not found: ${l.repository}`:e==="pr"&&l?.prNumber?a=`Pull request not found: #${l.prNumber}`:a=`Not found: ${n}`;break;case 409:e==="pr"||e==="job"?a="PR already exists for these branches":a=`Conflict: ${n}`;break;case 422:e==="job"||e==="pr"?a="Branch protection or other rule prevents operation":a=`Unprocessable entity: ${n}`;break;case 500:a=`Internal server error: ${n}`;break;case 502:a=`Bad gateway: ${n}`;break;case 503:a=`Service unavailable: ${n}`;break;default:a=e?`Failed to ${e.replace(/_/g," ")}: ${n}`:n}throw new T7(t.status,a,r)}async function iJ(t,e,l,n,r="API"){let a=await aGe(e),I=Q8(),s={Authorization:`Bearer ${a}`,Accept:"application/json","User-Agent":`copilot-cli/${I}`};return n?.headers&&Object.assign(s,n.headers),NC(t,{...n,headers:s},l,r)}async function gGl(t,e,l){let{owner:n,repo:r}=O7(t),a=zw(e),I=qO(a),s=new URL(`/repos/${n}/${r}`,I),o=await iJ(s,e,l,{method:"GET",headers:{Accept:"application/vnd.github.v3+json"}},"GitHub Repository API");return o.ok||await qT(o,"repository",{repository:t}),!0}async function ZGl(t,e){return!0}c();async function NGl(t,e,l,n,r,a){let{owner:I,repo:s}=O7(t),{problemStatement:o}=Kol(e,n),d=await aGe(r),u=zw(r),b=await R0(u,d),p=new URL(`/agents/swe/v1/jobs/${I}/${s}`,b),g=await iJ(p,r,a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({problem_statement:o,pull_request:{head_ref:l,body_suffix:"Created from Copilot CLI via the copilot delegate command."},event_type:"cli_delegate_command"})},"Copilot Job API");g.ok||await qT(g,"job",{repository:t});let N=await g.json();return{jobId:N.job_id,sessionId:N.session_id,actor:{id:N.actor.id,login:N.actor.login},createdAt:new Date(N.created_at),updatedAt:new Date(N.updated_at)}}async function WGl(t){let{repository:e,jobId:l,authInfo:n,logger:r}=t,{owner:a,repo:I}=O7(e),s=await aGe(n),o=zw(n),d=await R0(o,s),u=new URL(`/agents/swe/v1/jobs/${a}/${I}/${l}`,d),b=await iJ(u,n,r,{method:"GET"},"Copilot Job Status API");b.ok||await qT(b,"job",{jobId:l});let p=await b.json(),h;return p.pull_request?.number&&(h=`${o}/${e}/pull/${p.pull_request.number}`),{jobId:p.job_id,sessionId:p.session_id,problemStatement:p.problem_statement,status:p.status,result:p.result,actor:{id:p.actor.id,login:p.actor.login},createdAt:new Date(p.created_at),updatedAt:new Date(p.updated_at),pullRequest:p.pull_request?{id:p.pull_request.id,number:p.pull_request.number,url:h}:void 0,workflowRun:p.workflow_run?{id:p.workflow_run.id}:void 0,error:p.error?{message:p.error.message,responseStatusCode:p.error.response_status_code,service:p.error.service}:void 0}}async function pnt(t){let{sessionId:e,authInfo:l,logger:n,integrationId:r}=t,a=await aGe(l),I=zw(l),s=await R0(I,a),o=new URL(`/agents/sessions/${e}`,s),d=await iJ(o,l,n,{method:"GET",headers:{"Copilot-Integration-Id":r}},"Copilot Session API");d.ok||await qT(d,"session",{sessionId:e});let u=await d.json(),b=u.state;return{sessionId:u.id,state:b,createdAt:u.created_at?new Date(u.created_at):new Date,updatedAt:u.last_updated_at?new Date(u.last_updated_at):new Date,resourceGlobalId:u.resource_global_id}}async function Ave(t){let{repository:e,prNumber:l,authInfo:n,logger:r,includeFiles:a=!1,maxFiles:I=100}=t,{owner:s,repo:o}=O7(e),d=zw(n),u=qO(d),b=new URL(`/repos/${s}/${o}/pulls/${l}`,u),p=await iJ(b,n,r,{method:"GET",headers:{Accept:"application/vnd.github.v3+json"}},"GitHub PR API");p.ok||await qT(p,"pr",{prNumber:l.toString()});let h=await p.json(),g={title:h.title,draft:h.draft,createdAt:new Date(h.created_at),changedFiles:h.changed_files,totalAdditions:h.additions,totalDeletions:h.deletions};if(a){let N=new URL(`/repos/${s}/${o}/pulls/${l}/files`,u);N.searchParams.set("per_page",Math.min(I,100).toString()),N.searchParams.set("page","1");let y=await iJ(N,n,r,{method:"GET",headers:{Accept:"application/vnd.github.v3+json"}},"GitHub PR Files API");if(y.ok){let Y=await y.json();g.files=Y.slice(0,I).map(w=>({filename:w.filename,status:w.status,additions:w.additions,deletions:w.deletions}))}}return g}var gve=class{state=null;onStateChangeCallback=null;onSessionCompleteCallback=null;timeoutId=null;pollingIntervalId=null;initialAuthInfo;authInfo;logger;integrationId;constructor(e,l,n){this.initialAuthInfo=e,this.logger=l,this.integrationId=n}startDelegation(e,l,n=""){if(!this.initialAuthInfo)throw new Error("Not authenticated. Please login first.");this.authInfo=this.initialAuthInfo,this.logger.startGroup("Remote Delegation Started"),this.logger.info(`Prompt: "${e.substring(0,100)}${e.length>100?"...":""}"`),this.logger.info(`CLI Session ID: ${l}`),n&&this.logger.info(`Problem Context: "${n.substring(0,100)}${n.length>100?"...":""}"`),this.logger.endGroup(),this.state={stage:"uncommitted_changes_check",prompt:e,problemContext:n,cliSessionId:l,isLoading:!0},this.notifyStateChange(),this.checkUncommittedChanges()}advanceStage(){if(!this.state)return;let e=this.state.stage;switch(this.state.stage){case"uncommitted_changes_check":this.logger.info(`--- Stage transition: ${e} \u2192 Confirm ---`),this.state={...this.state,stage:"confirm",isLoading:!0},this.notifyStateChange(),this.loadDelegationConfirmationData();break;case"confirm":this.logger.info(`--- Stage transition: ${e} \u2192 Processing ---`),this.state={...this.state,stage:"processing",processingStartTime:new Date},this.notifyStateChange(),this.executeDelegationOperations();break;case"processing":this.logger.info(`--- Stage transition: ${e} \u2192 Tracking ---`),this.state={...this.state,stage:"tracking"},this.notifyStateChange(),this.startJobTracking();break;case"tracking":this.logger.info(`--- Stage transition: ${e} \u2192 Complete ---`),this.completeDelegationOperation();break}}cancelDelegation(){let e=this.state?.stage;this.logger.info(`Remote delegation cancelled${e?` (was in stage: ${e})`:""}`),this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.clearPollingInterval(),this.state=null,this.notifyStateChange()}setOnStateChangeCallback(e){this.onStateChangeCallback=e,this.notifyStateChange()}onSessionComplete(e){this.onSessionCompleteCallback=e}getCurrentState(){return this.state}isActive(){return this.state!==null}async checkUncommittedChanges(){if(!this.state)return;let e=Date.now();this.logger.info("STAGE 1: UncommittedChangesCheck - Starting validation checks");try{let l=await bY(process.cwd());if(!l.found)throw new Error("Not a git repository");let n=await Gnt(process.cwd());this.logger.info(`Repository: ${n.repository}`),this.logger.info(`Base branch: ${n.baseBranch}, Head branch: ${n.headBranch}`),this.logger.info(`Async branch: ${n.asyncBranch}`),this.logger.info("Running parallel validation checks (detached HEAD, repo access, Copilot enabled)...");let[r,a,I]=await Promise.allSettled([GGl(process.cwd()),gGl(n.repository,this.authInfo,this.logger),ZGl(n.repository,this.authInfo)]),s=[];if(r.status==="fulfilled"&&r.value===!0?s.push("Repository is in detached HEAD state. Please checkout a branch before pushing."):r.status==="rejected"&&s.push(`Failed to check HEAD state: ${r.reason}`),a.status==="fulfilled"&&a.value===!1?s.push(`Repository not found or you don't have access: ${n.repository}`):a.status==="rejected"&&s.push(a.reason?.message||"Failed to check repository access"),I.status==="rejected"&&s.push(I.reason?.message||"Failed to check Copilot status"),s.length>0){let b=s.length===1?s[0]:`Multiple errors:
|
|
2457
|
+
`).filter(I=>I.length>0),n=0,r=0,a=0;for(let I of l){if(I.length<2)continue;let s=I[0],o=I[1];s==="?"&&o==="?"?a++:(s!==" "&&s!=="?"&&n++,o!==" "&&o!=="?"&&r++)}return{staged:n,unstaged:r,untracked:a,hasChanges:l.length>0}}catch{return{staged:0,unstaged:0,untracked:0,hasChanges:!1}}}async function mGl(){return"Checkpoint from Copilot CLI for coding agent session"}async function bGl(t){let{stdout:e}=await NN("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:t,encoding:"utf8",timeout:5e3});return e.trim()}async function GGl(t){try{return await bGl(t)==="HEAD"}catch{return!1}}async function Uqn(t){try{let{stdout:e}=await NN("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:t,encoding:"utf8",timeout:5e3}),l=e.trim();if(!l||l==="HEAD")return"origin";let{stdout:n}=await NN("git",["config",`branch.${l}.remote`],{cwd:t,encoding:"utf8",timeout:5e3});return n.trim()||"origin"}catch{return"origin"}}async function Mqn(t){let e=await Uqn(t);try{let{stdout:l}=await NN("git",["symbolic-ref",`refs/remotes/${e}/HEAD`],{cwd:t,encoding:"utf8",timeout:5e3}),n=l.match(new RegExp(`refs/remotes/${e}/(.+)`));if(n)return n[1].trim()}catch{}try{return await NN("git",["rev-parse","--verify",`refs/remotes/${e}/main`],{cwd:t,encoding:"utf8",timeout:5e3}),"main"}catch{}try{return await NN("git",["rev-parse","--verify",`refs/remotes/${e}/master`],{cwd:t,encoding:"utf8",timeout:5e3}),"master"}catch{return"main"}}async function _qn(t,e){try{return await NN("git",["rev-parse","--verify",`refs/heads/${e}`],{cwd:t,encoding:"utf8",timeout:5e3}),!0}catch{return!1}}async function Dqn(t,e){let n=["adjectives","animals"],a=[];for(let I of n)I.toLowerCase()==="adjectives"&&a.push(cGl),I.toLowerCase()==="animals"&&a.push(dGl);if(a.length===0)return`${e}/session${Date.now()}`;for(let I=0;I<5;I++){let s=`${e}/${iGl({dictionaries:a,length:a.length,separator:"-"})}`;if(!await _qn(t,s))return s}return`${e}/session${Date.now()}`}async function zqn(t){return Dqn(t,"copilot")}async function Gnt(t){try{let[e,l,n,r]=await Promise.all([bGl(t),ove(t),Mqn(t),zqn(t)]);if(!l)throw new Error("Could not determine GitHub repository from git remotes");return{repository:`${l.owner}/${l.name}`,baseBranch:n,headBranch:e,asyncBranch:r}}catch(e){throw new Error(`Failed to get repository info: ${e instanceof Error?e.message:String(e)}`)}}async function pGl(t,e){try{await NN("git",["add","--all"],{cwd:t,encoding:"utf8",timeout:1e4,maxBuffer:10*1024*1024});let{stdout:l}=await NN("git",["commit","-m",e],{cwd:t,encoding:"utf8",timeout:1e4,maxBuffer:10*1024*1024}),n,r=l.match(/\[[\w/-]+ ([a-f0-9]+)\]/);if(!r||!r[1]){let{stdout:a}=await NN("git",["rev-parse","--short","HEAD"],{cwd:t,encoding:"utf8",timeout:5e3});n=a.trim()}else n=r[1];return{commitHash:n,commitMessage:e}}catch(l){let n=l instanceof Error?l.message:String(l);throw n.includes("pre-commit")?new Error(`Pre-commit hook prevented the commit: ${n}`):n.includes("commit-msg")?new Error(`Commit-msg hook rejected the commit: ${n}`):n.includes("nothing to commit")||n.includes("no changes added")?new Error(`No changes to commit (possibly filtered by hooks): ${n}`):new Error(`Failed to commit changes: ${n}`)}}async function hGl(t,e=process.cwd()){try{await NN("git",["checkout",t],{cwd:e,encoding:"utf8",timeout:5e3,maxBuffer:10*1024*1024})}catch(l){let n=l instanceof Error?l.message:String(l);throw new Error(`Failed to switch to branch '${t}': ${n}`)}}async function AGl(t){let{cwd:e,asyncBranch:l}=t;try{await NN("git",["checkout","-b",l],{cwd:e,encoding:"utf8",timeout:1e4,maxBuffer:10*1024*1024}),await NN("git",["push","-u","origin",l],{cwd:e,encoding:"utf8",timeout:3e4,maxBuffer:10*1024*1024})}catch(n){let r=n instanceof Error?n.message:String(n);throw r.includes("branch")&&r.includes("already exists")?new Error(`Branch '${l}' already exists: ${r}`):r.includes("Could not read from remote repository")?new Error(`Failed to push branch - repository access issue: ${r}`):r.includes("Permission denied")||r.includes("403")?new Error(`Failed to push branch - permission denied: ${r}`):r.includes("remote rejected")?new Error(`Remote rejected the git push: ${r}`):new Error(`Failed to create and push branch '${l}': ${r}`)}}c();var T7=class extends Error{constructor(l,n,r){super(n);this.status=l;this.message=n;this.responseBody=r;this.name="HttpApiError"}};async function aGe(t){let e=await ry(t);if(!e)throw new Error("Failed to get authentication token");return e}async function Pqn(t){let e=t.statusText||`HTTP ${t.status}`,l;try{l=await t.json(),typeof l=="object"&&l&&"message"in l&&(e=l.message)}catch{try{let n=await t.text();n&&(l=n)}catch{}}return{message:e,body:l}}async function qT(t,e,l){let{message:n,body:r}=await Pqn(t),a;switch(t.status){case 400:a=`Bad request: ${n}`;break;case 401:a=`Unauthorized: ${n}`;break;case 402:a=e==="job"?"No remaining quota for premium requests":`Payment required: ${n}`;break;case 403:e==="job"||e==="agent"?a=`Coding Agent not enabled: ${n}`:a=`Forbidden: ${n}`;break;case 404:e==="job"&&l?.jobId?a=`Job not found: ${l.jobId}`:e==="session"&&l?.sessionId?a=`Session not found: ${l.sessionId}`:e==="repository"&&l?.repository?a=`Repository not found: ${l.repository}`:e==="pr"&&l?.prNumber?a=`Pull request not found: #${l.prNumber}`:a=`Not found: ${n}`;break;case 409:e==="pr"||e==="job"?a="PR already exists for these branches":a=`Conflict: ${n}`;break;case 422:e==="job"||e==="pr"?a="Branch protection or other rule prevents operation":a=`Unprocessable entity: ${n}`;break;case 500:a=`Internal server error: ${n}`;break;case 502:a=`Bad gateway: ${n}`;break;case 503:a=`Service unavailable: ${n}`;break;default:a=e?`Failed to ${e.replace(/_/g," ")}: ${n}`:n}throw new T7(t.status,a,r)}async function iJ(t,e,l,n,r="API"){let a=await aGe(e),I=Q8(),s={Authorization:`Bearer ${a}`,Accept:"application/json","User-Agent":`copilot-cli/${I}`};return n?.headers&&Object.assign(s,n.headers),NC(t,{...n,headers:s},l,r)}async function gGl(t,e,l){let{owner:n,repo:r}=O7(t),a=zw(e),I=qO(a),s=new URL(`/repos/${n}/${r}`,I),o=await iJ(s,e,l,{method:"GET",headers:{Accept:"application/vnd.github.v3+json"}},"GitHub Repository API");return o.ok||await qT(o,"repository",{repository:t}),!0}async function ZGl(t,e){return!0}c();async function NGl(t,e,l,n,r,a){let{owner:I,repo:s}=O7(t),{problemStatement:o}=Kol(e,n),d=await aGe(r),u=zw(r),b=await R0(u,d,a),p=new URL(`/agents/swe/v1/jobs/${I}/${s}`,b),g=await iJ(p,r,a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({problem_statement:o,pull_request:{head_ref:l,body_suffix:"Created from Copilot CLI via the copilot delegate command."},event_type:"cli_delegate_command"})},"Copilot Job API");g.ok||await qT(g,"job",{repository:t});let N=await g.json();return{jobId:N.job_id,sessionId:N.session_id,actor:{id:N.actor.id,login:N.actor.login},createdAt:new Date(N.created_at),updatedAt:new Date(N.updated_at)}}async function WGl(t){let{repository:e,jobId:l,authInfo:n,logger:r}=t,{owner:a,repo:I}=O7(e),s=await aGe(n),o=zw(n),d=await R0(o,s,r),u=new URL(`/agents/swe/v1/jobs/${a}/${I}/${l}`,d),b=await iJ(u,n,r,{method:"GET"},"Copilot Job Status API");b.ok||await qT(b,"job",{jobId:l});let p=await b.json(),h;return p.pull_request?.number&&(h=`${o}/${e}/pull/${p.pull_request.number}`),{jobId:p.job_id,sessionId:p.session_id,problemStatement:p.problem_statement,status:p.status,result:p.result,actor:{id:p.actor.id,login:p.actor.login},createdAt:new Date(p.created_at),updatedAt:new Date(p.updated_at),pullRequest:p.pull_request?{id:p.pull_request.id,number:p.pull_request.number,url:h}:void 0,workflowRun:p.workflow_run?{id:p.workflow_run.id}:void 0,error:p.error?{message:p.error.message,responseStatusCode:p.error.response_status_code,service:p.error.service}:void 0}}async function pnt(t){let{sessionId:e,authInfo:l,logger:n,integrationId:r}=t,a=await aGe(l),I=zw(l),s=await R0(I,a,n),o=new URL(`/agents/sessions/${e}`,s),d=await iJ(o,l,n,{method:"GET",headers:{"Copilot-Integration-Id":r}},"Copilot Session API");d.ok||await qT(d,"session",{sessionId:e});let u=await d.json(),b=u.state;return{sessionId:u.id,state:b,createdAt:u.created_at?new Date(u.created_at):new Date,updatedAt:u.last_updated_at?new Date(u.last_updated_at):new Date,resourceGlobalId:u.resource_global_id}}async function Ave(t){let{repository:e,prNumber:l,authInfo:n,logger:r,includeFiles:a=!1,maxFiles:I=100}=t,{owner:s,repo:o}=O7(e),d=zw(n),u=qO(d),b=new URL(`/repos/${s}/${o}/pulls/${l}`,u),p=await iJ(b,n,r,{method:"GET",headers:{Accept:"application/vnd.github.v3+json"}},"GitHub PR API");p.ok||await qT(p,"pr",{prNumber:l.toString()});let h=await p.json(),g={title:h.title,draft:h.draft,createdAt:new Date(h.created_at),changedFiles:h.changed_files,totalAdditions:h.additions,totalDeletions:h.deletions};if(a){let N=new URL(`/repos/${s}/${o}/pulls/${l}/files`,u);N.searchParams.set("per_page",Math.min(I,100).toString()),N.searchParams.set("page","1");let y=await iJ(N,n,r,{method:"GET",headers:{Accept:"application/vnd.github.v3+json"}},"GitHub PR Files API");if(y.ok){let Y=await y.json();g.files=Y.slice(0,I).map(w=>({filename:w.filename,status:w.status,additions:w.additions,deletions:w.deletions}))}}return g}var gve=class{state=null;onStateChangeCallback=null;onSessionCompleteCallback=null;timeoutId=null;pollingIntervalId=null;initialAuthInfo;authInfo;logger;integrationId;constructor(e,l,n){this.initialAuthInfo=e,this.logger=l,this.integrationId=n}startDelegation(e,l,n=""){if(!this.initialAuthInfo)throw new Error("Not authenticated. Please login first.");this.authInfo=this.initialAuthInfo,this.logger.startGroup("Remote Delegation Started"),this.logger.info(`Prompt: "${e.substring(0,100)}${e.length>100?"...":""}"`),this.logger.info(`CLI Session ID: ${l}`),n&&this.logger.info(`Problem Context: "${n.substring(0,100)}${n.length>100?"...":""}"`),this.logger.endGroup(),this.state={stage:"uncommitted_changes_check",prompt:e,problemContext:n,cliSessionId:l,isLoading:!0},this.notifyStateChange(),this.checkUncommittedChanges()}advanceStage(){if(!this.state)return;let e=this.state.stage;switch(this.state.stage){case"uncommitted_changes_check":this.logger.info(`--- Stage transition: ${e} \u2192 Confirm ---`),this.state={...this.state,stage:"confirm",isLoading:!0},this.notifyStateChange(),this.loadDelegationConfirmationData();break;case"confirm":this.logger.info(`--- Stage transition: ${e} \u2192 Processing ---`),this.state={...this.state,stage:"processing",processingStartTime:new Date},this.notifyStateChange(),this.executeDelegationOperations();break;case"processing":this.logger.info(`--- Stage transition: ${e} \u2192 Tracking ---`),this.state={...this.state,stage:"tracking"},this.notifyStateChange(),this.startJobTracking();break;case"tracking":this.logger.info(`--- Stage transition: ${e} \u2192 Complete ---`),this.completeDelegationOperation();break}}cancelDelegation(){let e=this.state?.stage;this.logger.info(`Remote delegation cancelled${e?` (was in stage: ${e})`:""}`),this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.clearPollingInterval(),this.state=null,this.notifyStateChange()}setOnStateChangeCallback(e){this.onStateChangeCallback=e,this.notifyStateChange()}onSessionComplete(e){this.onSessionCompleteCallback=e}getCurrentState(){return this.state}isActive(){return this.state!==null}async checkUncommittedChanges(){if(!this.state)return;let e=Date.now();this.logger.info("STAGE 1: UncommittedChangesCheck - Starting validation checks");try{let l=await bY(process.cwd());if(!l.found)throw new Error("Not a git repository");let n=await Gnt(process.cwd());this.logger.info(`Repository: ${n.repository}`),this.logger.info(`Base branch: ${n.baseBranch}, Head branch: ${n.headBranch}`),this.logger.info(`Async branch: ${n.asyncBranch}`),this.logger.info("Running parallel validation checks (detached HEAD, repo access, Copilot enabled)...");let[r,a,I]=await Promise.allSettled([GGl(process.cwd()),gGl(n.repository,this.authInfo,this.logger),ZGl(n.repository,this.authInfo)]),s=[];if(r.status==="fulfilled"&&r.value===!0?s.push("Repository is in detached HEAD state. Please checkout a branch before pushing."):r.status==="rejected"&&s.push(`Failed to check HEAD state: ${r.reason}`),a.status==="fulfilled"&&a.value===!1?s.push(`Repository not found or you don't have access: ${n.repository}`):a.status==="rejected"&&s.push(a.reason?.message||"Failed to check repository access"),I.status==="rejected"&&s.push(I.reason?.message||"Failed to check Copilot status"),s.length>0){let b=s.length===1?s[0]:`Multiple errors:
|
|
2458
2458
|
\u2022 ${s.join(`
|
|
2459
|
-
\u2022 `)}`;throw new Error(b)}let o=await uGl(process.cwd());o.hasChanges?this.logger.info(`Uncommitted changes detected: ${o.staged} staged, ${o.unstaged} unstaged, ${o.untracked} untracked`):this.logger.info("No uncommitted changes detected");let d=o.hasChanges?await mGl():void 0;d&&this.logger.info(`Generated checkpoint commit message: "${d}"`),this.state={...this.state,isLoading:!1,isGitRepository:l.found,hasUncommittedChanges:o.hasChanges,fileCount:o.hasChanges?{staged:o.staged,unstaged:o.unstaged,untracked:o.untracked}:void 0,commitMessage:d,repository:n.repository,baseBranch:n.baseBranch,headBranch:n.headBranch,asyncBranch:n.asyncBranch},this.notifyStateChange();let u=Date.now()-e;this.logger.info(`STAGE 1: UncommittedChangesCheck completed in ${u}ms`),o.hasChanges||(this.logger.info("Auto-advancing to Confirm stage (no uncommitted changes)"),this.state={...this.state,stage:"confirm",isLoading:!1,isGitRepository:l.found,hasUncommittedChanges:!1},this.notifyStateChange(),await this.loadDelegationConfirmationData())}catch(l){this.setError(l,"Failed during uncommitted changes check")}}async loadDelegationConfirmationData(){if(!this.state)return;let e=Date.now();this.logger.info("STAGE 2: Confirm - Loading delegation confirmation data");try{if(this.state.repository)this.logger.info("Repository info already available from previous stage"),this.state={...this.state,isLoading:!1};else{this.logger.info("Repository info not found, fetching...");let n=await Gnt(process.cwd());this.state={...this.state,isLoading:!1,repository:n.repository,baseBranch:n.baseBranch,headBranch:n.headBranch,asyncBranch:n.asyncBranch},this.logger.info(`Loaded repository info: ${n.repository}`)}this.notifyStateChange();let l=Date.now()-e;this.logger.info(`STAGE 2: Confirm completed in ${l}ms - Waiting for user confirmation`)}catch(l){this.setError(l,"Failed to load delegation confirmation data")}}async executeDelegationOperations(){if(!this.state)return;let e=Date.now();this.logger.info("STAGE 3: Processing - Executing delegation operations");try{let l=this.buildOperationsList();this.state={...this.state,operations:l},this.notifyStateChange(),this.logger.info(`Operations to execute: ${l.map(n=>n.id).join(" \u2192 ")}`);for(let n of l){if(!this.state)break;let r=Date.now();this.logger.info(`Operation [${n.id}] - Starting...`),this.updateOperationStatus(n.id,"running");try{switch(n.id){case"commit":{let I=await pGl(process.cwd(),this.state.commitMessage);this.state={...this.state,commitHash:I.commitHash},this.logger.info(`Operation [${n.id}] - Commit created: ${I.commitHash}`);break}case"create-branch":{this.logger.info(`Operation [${n.id}] - Creating branch: ${this.state.asyncBranch}`),await AGl({cwd:process.cwd(),repository:this.state.repository,headBranch:this.state.headBranch,baseBranch:this.state.baseBranch,asyncBranch:this.state.asyncBranch}),this.logger.info(`Operation [${n.id}] - Branch created and pushed: ${this.state.asyncBranch}`),await hGl(this.state.headBranch),this.logger.info(`Operation [${n.id}] - Switched back to: ${this.state.headBranch}`);break}case"start-job":{this.logger.info(`Operation [${n.id}] - Creating job for repository: ${this.state.repository}`);let I=await NGl(this.state.repository,this.state.prompt,this.state.asyncBranch,this.state.problemContext||"",this.authInfo,this.logger);if(!I.jobId||!I.sessionId)throw new Error(`Job creation returned incomplete data: jobId=${I.jobId}, sessionId=${I.sessionId}`);this.state={...this.state,jobId:I.jobId,sessionId:I.sessionId,jobCreatedBy:I.actor.login,jobCreatedAt:I.createdAt},this.logger.info(`Operation [${n.id}] - Job created: ID=${I.jobId}, Session=${I.sessionId}, CreatedBy=${I.actor.login}`);break}case"check-job":{if(!this.state.jobId)throw new Error("No job ID available to check status");let I=1e3,s=9e4,o=Date.now(),d=!1,u=0;for(this.logger.info(`Operation [${n.id}] - Polling for PR details (max ${s}ms)...`);!d&&Date.now()-o<s;){u++;let b=await WGl({repository:this.state.repository,jobId:this.state.jobId,authInfo:this.authInfo,logger:this.logger});this.state={...this.state,jobStatus:b.status,jobResult:b.result,prNumber:b.pullRequest?.number,prUrl:b.pullRequest?.url},b.pullRequest?.number?(this.logger.info(`Operation [${n.id}] - PR details received: #${b.pullRequest.number} (after ${u} polls, ${Date.now()-o}ms)`),d=!0):await new Promise(p=>setTimeout(p,I))}if(!d)throw new iT(`Timed out waiting for pull request information after ${s}ms`,"check-job",this.state.prUrl);break}case"wait-for-session":{if(!this.state.sessionId)throw new Error("No session ID available to check status");let I=1e3,s=9e4,o=Date.now(),d=!1,u=!1,b=!1,p=0;for(this.logger.info(`Operation [${n.id}] - Waiting for session to start (max ${s}ms)...`);!d&&Date.now()-o<s;){p++;let h=await pnt({sessionId:this.state.sessionId,authInfo:this.authInfo,logger:this.logger,integrationId:this.integrationId});if(h.resourceGlobalId&&!this.state.jobUrl){let g=zw(this.authInfo);this.state={...this.state,jobUrl:`${g}/copilot/tasks/pull/${h.resourceGlobalId}?session_id=${this.state.sessionId}`},b=!0,this.logger.info(`Operation [${n.id}] - Job URL constructed: ${this.state.jobUrl}`)}if(this.state.prNumber&&!u){let g=await Ave({repository:this.state.repository,prNumber:this.state.prNumber,authInfo:this.authInfo,logger:this.logger,includeFiles:!1});this.state={...this.state,prTitle:g.title,prDraft:g.draft,prCreatedAt:g.createdAt},u=!0,this.logger.info(`Operation [${n.id}] - PR details fetched: "${g.title}"`)}h.state==="in_progress"?(this.logger.info(`Operation [${n.id}] - Session transitioned to in_progress (after ${p} polls, ${Date.now()-o}ms)`),d=!0):h.state==="completed"||h.state==="failed"||h.state==="cancelled"||h.state==="timed_out"?(this.logger.info(`Operation [${n.id}] - Session ended with state: ${h.state} (after ${p} polls, ${Date.now()-o}ms)`),d=!0):(h.state==="waiting_for_user"||h.state==="idle")&&(this.logger.info(`Operation [${n.id}] - Session in intermediate state: ${h.state} (after ${p} polls, ${Date.now()-o}ms)`),d=!0),(!d||!u||!b)&&await new Promise(g=>setTimeout(g,I))}if(!d||!u||!b){let h=[];throw d||h.push("session transition"),u||h.push("PR details"),b||h.push("job URL"),new iT(`Timed out after ${s}ms waiting for: ${h.join(", ")}`,"wait-for-session",this.state.prUrl)}break}}this.updateOperationStatus(n.id,"done");let a=Date.now()-r;this.logger.info(`Operation [${n.id}] - Completed in ${a}ms`)}catch(a){this.updateOperationStatus(n.id,"error",a.message);let I=Date.now()-r;this.logger.error(`Operation [${n.id}] - Failed after ${I}ms: ${a.message}`),await new Promise(s=>setTimeout(s,3e3)),this.setError(a,`Operation '${n.id}' failed`);return}}if(this.allOperationsComplete()){let n=Date.now()-e;this.logger.info(`STAGE 3: Processing completed in ${n}ms - All operations successful`),setTimeout(()=>this.advanceStage(),2e3)}}catch(l){this.setError(l,"Failed to execute delegation operations")}}async startJobTracking(){if(!this.state||!this.state.sessionId){this.logger.error("Cannot start job tracking: missing state or sessionId"),this.cancelDelegation();return}this.logger.info("STAGE 4: Tracking - Starting job tracking"),this.logger.info(`Tracking session: ${this.state.sessionId}`),this.state.prNumber&&this.logger.info(`Tracking PR: #${this.state.prNumber}`);let e=1e3,l=null,n=async()=>{if(!this.state||!this.state.sessionId){this.clearPollingInterval();return}try{let r=await pnt({sessionId:this.state.sessionId,authInfo:this.authInfo,logger:this.logger,integrationId:this.integrationId}),a=this.state.sessionState;if(this.state={...this.state,sessionState:r.state},a!==r.state&&this.logger.info(`Session state changed: ${a||"unknown"} \u2192 ${r.state}`),!this.state.jobUrl&&r.resourceGlobalId){let s=zw(this.authInfo);this.state.jobUrl=`${s}/copilot/tasks/pull/${r.resourceGlobalId}?session_id=${this.state.sessionId}`,this.logger.info(`Constructed job URL from polling: ${this.state.jobUrl}`)}if(this.state.prNumber)try{let s=await Ave({repository:this.state.repository,prNumber:this.state.prNumber,authInfo:this.authInfo,logger:this.logger,includeFiles:!1}),o=s.changedFiles!==this.state.prChangedFiles||s.totalAdditions!==this.state.prTotalAdditions||s.totalDeletions!==this.state.prTotalDeletions;if(this.state={...this.state,prTitle:s.title,prDraft:s.draft,prCreatedAt:s.createdAt,prChangedFiles:s.changedFiles,prTotalAdditions:s.totalAdditions,prTotalDeletions:s.totalDeletions},o||!this.state.prFiles){let d=await Ave({repository:this.state.repository,prNumber:this.state.prNumber,authInfo:this.authInfo,logger:this.logger,includeFiles:!0,maxFiles:10});this.state={...this.state,prFiles:d.files},this.logger.info(`PR files updated: ${s.changedFiles} files${s.changedFiles>10?" (showing first 10)":""}, +${s.totalAdditions} -${s.totalDeletions}`)}}catch(s){this.logError("Failed to fetch PR details",s,"warning")}if(this.notifyStateChange(),r.state==="completed"||r.state==="failed"||r.state==="cancelled"||r.state==="timed_out"){this.logger.info(`STAGE 4: Tracking - Session ended with terminal state: ${r.state}`),this.clearPollingInterval(),setTimeout(()=>this.completeDelegationOperation(),3e3);return}let I=1e3;if(r.state==="waiting_for_user"||r.state==="idle"){l===null&&(l=Date.now());let s=Date.now()-l,o=300*1e3,d=Math.floor(s/o);I=Math.min(5e3+d*5e3,3e4)}else l=null;if(I!==e){let s=e;e=I,this.clearPollingInterval(),this.pollingIntervalId=setInterval(()=>void n(),e),this.logger.info(`Polling interval adjusted: ${s}ms \u2192 ${e}ms (state: ${r.state})`)}}catch(r){this.clearPollingInterval(),this.setError(r,"Error polling session status")}};this.pollingIntervalId=setInterval(()=>void n(),e),n()}completeDelegationOperation(){this.clearPollingInterval(),this.logger.info("STAGE 5: Complete - Delegation operation completed"),this.state&&(this.logger.startGroup("Delegation Operation Summary"),this.state.jobId&&this.logger.info(`Job ID: ${this.state.jobId}`),this.state.sessionId&&this.logger.info(`Session ID: ${this.state.sessionId}`),this.state.prNumber&&this.logger.info(`PR #${this.state.prNumber}: ${this.state.prUrl||"N/A"}`),this.state.commitHash&&this.logger.info(`Commit: ${this.state.commitHash}`),this.state.asyncBranch&&this.logger.info(`Branch: ${this.state.asyncBranch}`),this.state.sessionState&&this.logger.info(`Final session state: ${this.state.sessionState}`),this.logger.endGroup()),this.timeoutId&&clearTimeout(this.timeoutId),this.timeoutId=setTimeout(()=>{this.timeoutId=null,this.logger.info("Remote delegation workflow finished - Cleaning up"),this.onSessionCompleteCallback?this.onSessionCompleteCallback():(this.state=null,this.notifyStateChange())},3e3)}buildOperationsList(){if(!this.state)return[];let e=[];return this.state.hasUncommittedChanges&&e.push({id:"commit",status:"pending"}),e.push({id:"create-branch",status:"pending"},{id:"start-job",status:"pending"},{id:"check-job",status:"pending"},{id:"wait-for-session",status:"pending"}),e}updateOperationStatus(e,l,n){if(!this.state||!this.state.operations)return;let r=this.state.operations.map(a=>a.id===e?{...a,status:l,...n?{error:n}:{}}:a);this.state={...this.state,operations:r},this.notifyStateChange()}allOperationsComplete(){return!this.state||!this.state.operations?!0:this.state.operations.every(e=>e.status==="done"||e.status==="error")}setError(e,l){this.state&&(this.logError(l||"Operation failed",e,"error"),this.state={...this.state,error:e,isLoading:!1},this.notifyStateChange())}notifyStateChange(){this.onStateChangeCallback?.(this.state)}clearPollingInterval(){this.pollingIntervalId&&(clearInterval(this.pollingIntervalId),this.pollingIntervalId=null)}logError(e,l,n="error"){if(l instanceof T7){let r=l.responseBody?` | Response: ${JSON.stringify(l.responseBody)}`:"",a=`${e} - API error - Status: ${l.status} | Message: ${l.message}${r}`;n==="error"?this.logger.error(a):this.logger.warning(a)}else{let r=`${e}: ${l instanceof Error?l.message:String(l)}`;n==="error"?this.logger.error(r):this.logger.warning(r)}}};c();var U7=class{turnStartTimes=new Map;turnModelCallTimes=new Map;turnToolExecutionTimes=new Map;turnToolCallCounts=new Map;startTurn(e,l){this.turnStartTimes.set(e,l),this.turnModelCallTimes.set(e,{}),this.turnToolExecutionTimes.set(e,0),this.turnToolCallCounts.set(e,0)}recordModelCall(e,l){let n=this.turnModelCallTimes.get(e)||{};n.duration=l,this.turnModelCallTimes.set(e,n)}recordToolExecution(e,l){let n=this.turnToolExecutionTimes.get(e)||0;this.turnToolExecutionTimes.set(e,n+l);let r=this.turnToolCallCounts.get(e)||0;this.turnToolCallCounts.set(e,r+1)}finishTurn(e,l){let n=this.turnStartTimes.get(e);if(n===void 0)return this.cleanup(e),null;let r=l-n,a=this.turnModelCallTimes.get(e)||{},I=this.turnToolExecutionTimes.get(e)||0,s=this.turnToolCallCounts.get(e)||0,o=a.duration||0,d={totalDurationMs:r,llmDurationMs:o,toolExecutionMs:I,toolCallCount:s,totalDurationSeconds:(r/1e3).toFixed(2),llmDurationSeconds:(o/1e3).toFixed(2),toolExecutionSeconds:(I/1e3).toFixed(2)};return this.cleanup(e),d}cleanup(e){this.turnStartTimes.delete(e),this.turnModelCallTimes.delete(e),this.turnToolExecutionTimes.delete(e),this.turnToolCallCounts.delete(e)}static formatTimingBreakdown(e){return`LLM: ${e.llmDurationSeconds}s | Tools: ${e.toolExecutionSeconds}s (${e.toolCallCount} calls) | Total: ${e.totalDurationSeconds}s`}};c();var jqn="You are not licensed to use Copilot.",Kqn="You are not authorized to use this Copilot feature, it requires an enterprise or organization policy to be enabled.",qqn="The provided personal access token (PAT) does not have Copilot Requests permission. Please generate a new Fine-Grained Access Token with Copilot Requests permission (not a Classic token), or log in using /login";function hnt(t){return t.includes("not licensed to use Copilot")?{kind:"not-licensed",message:jqn}:t.includes("not authorized to use this Copilot feature")?{kind:"not-authorized",message:Kqn}:t.includes("Personal Access Token does not have Copilot Requests")?{kind:"not-authorized",message:qqn}:null}c();import{promises as $qn}from"fs";import Ant from"path";function e7n(t){let e=[],l=/(?<![a-zA-Z0-9])(@[^\s@]+)/g,n;for(;(n=l.exec(t))!==null;)e.push({displayText:n[1],startIndex:n.index,endIndex:n.index+n[0].length});return e}async function t7n(t){try{let e=await $qn.stat(t);return e.isDirectory()?"directory":e.isFile()?$se(Ant.basename(t))?"image":"file":null}catch{return null}}async function l7n(t,e=new Map,l=process.cwd()){let n=e7n(t),r=[];for(let a of n){let I=e.get(a.startIndex);if(I?.startIndex===a.startIndex)r.push(I);else{let s=a.displayText.slice(1).replace(/[.,;:!?]+$/,""),o=Ant.isAbsolute(s)?s:Ant.resolve(l,s),d=await t7n(o);if(d===null)continue;r.push({displayText:a.displayText,fullPath:o,type:d,startIndex:a.startIndex})}}return r}async function yGl(t,e=new Map,l=process.cwd(),n){let r=await l7n(t,e,l);return n.debug(`Detected mentions: ${r.map(a=>`${a.displayText} (${a.type})`).join(", ")}`),r.map(a=>({type:a.type==="image"?"file":a.type,path:a.fullPath,displayName:a.displayText,mentionIndex:a.startIndex}))}c();var Zve=nt(nl(),1);c();import{EventEmitter as Wnt}from"node:events";var gnt=class extends Wnt{get columns(){return 100}frames=[];_lastFrame;write=e=>{this.frames.push(e),this._lastFrame=e};lastFrame=()=>this._lastFrame},Znt=class extends Wnt{frames=[];_lastFrame;write=e=>{this.frames.push(e),this._lastFrame=e};lastFrame=()=>this._lastFrame},Nnt=class extends Wnt{isTTY=!0;data=null;constructor(e={}){super(),this.isTTY=e.isTTY??!0}write=e=>{this.data=e,this.emit("readable"),this.emit("data",e)};setEncoding(){}setRawMode(){}resume(){}pause(){}ref(){}unref(){}read=()=>{let{data:e}=this;return this.data=null,e}},n7n=[],EGl=t=>{let e=new gnt,l=new Znt,n=new Nnt,r=Pee(t,{stdout:e,stderr:l,stdin:n,debug:!0,exitOnCtrlC:!1,patchConsole:!1});return n7n.push(r),{rerender:r.rerender,unmount:r.unmount,cleanup:r.cleanup,stdout:e,stderr:l,stdin:n,frames:e.frames,lastFrame:e.lastFrame}};function RGl(t,e=!1){let l=Zve.default.createElement(yFe,{logger:new xd,children:Zve.default.createElement(VFe,{mode:"non-interactive",children:Zve.default.createElement(pbe,{entry:t,expand:e})})}),{lastFrame:n}=EGl(l),r=n();return r?r.trim():""}var YGl=1,ynt=!1;function I7n(t){ynt=t}var bQ=!1,Nve=[],qh=null,$T=!1;async function VGl(){if(bQ||Nve.length===0)return;bQ=!0;let{integrationId:t,messageContent:e,permissionService:l,authInfo:n,resolve:r,reject:a,completePendingToolCall:I,setQuotaSnapshots:s,setContextWindowMetrics:o,setStreamingResponseSize:d,setCurrentIntent:u,session:b,logger:p,pathManager:h,cliModel:g,enableStreaming:N,trajectoryOutputFile:y,mcpHost:Y,showLlmTiming:w,timingTracker:H,noCustomInstructions:L,setAvailableTools:S,customAgentPrompt:U,modelList:O,disableParallelToolsExecution:j}=Nve.shift();try{let B=await o7n(t,e,l,n,I,s,o,d,u,b,p,h,g,N,y,Y,w,H,L,S,U,O,j);r(B)}catch(B){B&&typeof B=="object"&&"name"in B&&B.name==="AbortError"||B&&typeof B=="object"&&"message"in B&&typeof B.message=="string"&&B.message.includes("Operation was cancelled")?r("Operation cancelled"):a(B)}finally{bQ=!1,Nve.length>0&&setTimeout(()=>void VGl(),100)}}var s7n=rZt(R0);async function o7n(t,e,l,n,r,a,I,s,o,d,u,b,p,h,g,N,y,Y,w,H,L,S,U){qh=new AbortController,a7n(0,qh.signal),s(0),o(null);try{let O=await Sr.load()||{},j=await ry(n),B=O.copilot_url;!B&&j&&n.type!=="hmac"&&(B=await s7n(n.host,j)),ls.env.GITHUB_COPILOT_CLI_MODE="true";let z={problemStatement:e,logger:u,saveTrajectoryOutput:g||void 0,apiCopilotIntegrationId:t,apiCopilotHmacKey:n.type==="hmac"?n.hmac:void 0,apiCopilotUrl:B,apiCopilotToken:j,serviceInstanceId:d.sessionId,mcpHost:N,saveEventLogs:ls.env.COPILOT_EVENTS_LOG_DIRECTORY},oe=kL()&&ls.env.COPILOT_AGENT_MODEL?ls.env.COPILOT_AGENT_MODEL:`sweagent-capi:${p}`,he={...z,pathManager:b,serviceAgentModel:oe,requestPermission:l.request,onToolPartialOutput:(Ge,q)=>{d.emitEphemeral("tool.execution_partial_result",{toolCallId:Ge,partialOutput:q})},showEvents:!0,showSessionLog:!1,useSessionLogOnly:!1,abortSignal:qh.signal,executeToolsInParallel:!U};try{let Ge=await cCe.createFromOptions(he);H&&H(Ge.getAvailableTools());let q=await bY(ls.cwd());q.found&&!w&&await VEe(q.gitRoot,!0,ls.cwd());let M=Ge.getAgentKind(),Ie=Ge.getModel(),se=z1e()[M]?.[Ie]??D1e(),Ee=Ge.getToolConfig?.call(Ge)??{},me=se.supports||{};me.reportIntent=!0;let ve=await r0e(q.found?q.gitRoot:"",Q8(),ls.cwd(),{},me,Ee,Ge.getAvailableTools(),void 0,w),Ye=new uCe(d,s,ynt,u),ye=await d.getChatContextMessages(),ne=ye.findLastIndex(Bt=>Bt.role==="user"),Oe=ye[ne];typeof Oe.content=="string"?Oe={...Oe,content:W6({customAgentPrompt:L,problemStatement:Oe.content,capabilities:me})}:Oe={...Oe,content:Oe.content.map(Bt=>Bt.type==="text"?{...Bt,text:W6({customAgentPrompt:L,problemStatement:Bt.text,capabilities:me})}:Bt)};let xe=new j4(Oe,u),ll=new gO(u),Yl=new mCe(o),Ft=Ge.getCompletionWithTools(ve,ye.map((Bt,Be)=>Be===ne?Oe:Bt),{stream:h,failIfInitialInputsTooLong:!1,processors:{preRequest:[xe,new o0e,ll],onRequestError:[xe],onStreamingChunk:[Ye,Yl]},executeToolsInParallel:!U,abortSignal:qh.signal});for await(let Bt of Ft){if(qh?.signal.aborted){let Be=new Error("Operation was cancelled");throw Be.name="AbortError",Be}await wTt(Bt,{onImageProcessingEvent:Be=>{},onImageRemovalEvent:Be=>{},onMessage:Be=>{if(mL(Be)){let Xt=Ye.endCurrentStreamingMessage(),$t=typeof Be.message.content=="string"?Be.message.content:null,Fn=k8(Be)?Be.message.tool_calls.map(rl=>({toolCallId:rl.id,name:rl.function.name,arguments:$k(rl.function.arguments)})):[];d.emit("assistant.message",{messageId:Xt??mu(),content:$t||"",toolRequests:Fn});for(let rl of Fn)d.emit("tool.execution_start",{toolCallId:rl.toolCallId,toolName:rl.name,arguments:rl.arguments})}else(Be.message.role==="system"||Be.message.role==="developer")&&d.emit("system.message",{role:Be.message.role,content:typeof Be.message.content=="string"?Be.message.content:JSON.stringify(Be.message.content),name:"name"in Be.message?Be.message.name:void 0})},onResponse:Be=>{},onModelCallFailure:Be=>{if(hnt(Be.modelCall?.error||""))return;let $t=Be.modelCall?.error||"Unknown error occurred";Be.modelCall.request_id&&($t+=` (Request ID: ${Be.modelCall.request_id})`),d.emit("session.error",{errorType:"model_call",message:`Model call failed: ${$t}`})},onModelCallSuccess:async Be=>{a(Be.quotaSnapshots||{});let Xt=Be.responseChunk.model||await d.getSelectedModel(),$t=Be.modelCallDurationMs||0,Fn=Be.responseUsage,rl=Xt?Wq(Xt,S):1;d.emitEphemeral("assistant.usage",{model:Xt||"unknown",inputTokens:Fn?.prompt_tokens||0,outputTokens:Fn?.completion_tokens||0,cost:rl,duration:$t,initiator:Be.modelCall?.initiator}),y&&Y&&Y.recordModelCall(Be.turn,Be.modelCallDurationMs)},onToolExecution:Be=>{r({callId:Be.toolCallId,resultType:Be.toolResult.resultType,log:(Be.toolResult.resultType==="failure"?Be.toolResult.error:void 0)||Be.toolResult.sessionLog||Be.toolResult.textResultForLlm}),y&&Y&&Y.recordToolExecution(Be.turn,Be.durationMs)},onTruncationEvent:Be=>{I(Xt=>{let $t=Math.max(Xt.totalTokens,Be.truncateResult.preTruncationTokensInMessages);return{...Xt,totalTokens:$t,postTruncationTokens:Be.truncateResult.postTruncationTokensInMessages,tokenLimit:Be.truncateResult.tokenLimit,messagesRemoved:Be.truncateResult.messagesRemovedDuringTruncation,tokensRemoved:Be.truncateResult.tokensRemovedDuringTruncation}})},onTurnEvent:Be=>{if(Be.kind==="turn_started")y&&Y&&Y.startTurn(Be.turn,Be.timestampMs);else if(Be.kind==="turn_ended"&&y&&Y){let Xt=Y.finishTurn(Be.turn,Be.timestampMs);if(Xt){let $t=U7.formatTimingBreakdown(Xt);ynt?ls.stdout.write(`
|
|
2459
|
+
\u2022 `)}`;throw new Error(b)}let o=await uGl(process.cwd());o.hasChanges?this.logger.info(`Uncommitted changes detected: ${o.staged} staged, ${o.unstaged} unstaged, ${o.untracked} untracked`):this.logger.info("No uncommitted changes detected");let d=o.hasChanges?await mGl():void 0;d&&this.logger.info(`Generated checkpoint commit message: "${d}"`),this.state={...this.state,isLoading:!1,isGitRepository:l.found,hasUncommittedChanges:o.hasChanges,fileCount:o.hasChanges?{staged:o.staged,unstaged:o.unstaged,untracked:o.untracked}:void 0,commitMessage:d,repository:n.repository,baseBranch:n.baseBranch,headBranch:n.headBranch,asyncBranch:n.asyncBranch},this.notifyStateChange();let u=Date.now()-e;this.logger.info(`STAGE 1: UncommittedChangesCheck completed in ${u}ms`),o.hasChanges||(this.logger.info("Auto-advancing to Confirm stage (no uncommitted changes)"),this.state={...this.state,stage:"confirm",isLoading:!1,isGitRepository:l.found,hasUncommittedChanges:!1},this.notifyStateChange(),await this.loadDelegationConfirmationData())}catch(l){this.setError(l,"Failed during uncommitted changes check")}}async loadDelegationConfirmationData(){if(!this.state)return;let e=Date.now();this.logger.info("STAGE 2: Confirm - Loading delegation confirmation data");try{if(this.state.repository)this.logger.info("Repository info already available from previous stage"),this.state={...this.state,isLoading:!1};else{this.logger.info("Repository info not found, fetching...");let n=await Gnt(process.cwd());this.state={...this.state,isLoading:!1,repository:n.repository,baseBranch:n.baseBranch,headBranch:n.headBranch,asyncBranch:n.asyncBranch},this.logger.info(`Loaded repository info: ${n.repository}`)}this.notifyStateChange();let l=Date.now()-e;this.logger.info(`STAGE 2: Confirm completed in ${l}ms - Waiting for user confirmation`)}catch(l){this.setError(l,"Failed to load delegation confirmation data")}}async executeDelegationOperations(){if(!this.state)return;let e=Date.now();this.logger.info("STAGE 3: Processing - Executing delegation operations");try{let l=this.buildOperationsList();this.state={...this.state,operations:l},this.notifyStateChange(),this.logger.info(`Operations to execute: ${l.map(n=>n.id).join(" \u2192 ")}`);for(let n of l){if(!this.state)break;let r=Date.now();this.logger.info(`Operation [${n.id}] - Starting...`),this.updateOperationStatus(n.id,"running");try{switch(n.id){case"commit":{let I=await pGl(process.cwd(),this.state.commitMessage);this.state={...this.state,commitHash:I.commitHash},this.logger.info(`Operation [${n.id}] - Commit created: ${I.commitHash}`);break}case"create-branch":{this.logger.info(`Operation [${n.id}] - Creating branch: ${this.state.asyncBranch}`),await AGl({cwd:process.cwd(),repository:this.state.repository,headBranch:this.state.headBranch,baseBranch:this.state.baseBranch,asyncBranch:this.state.asyncBranch}),this.logger.info(`Operation [${n.id}] - Branch created and pushed: ${this.state.asyncBranch}`),await hGl(this.state.headBranch),this.logger.info(`Operation [${n.id}] - Switched back to: ${this.state.headBranch}`);break}case"start-job":{this.logger.info(`Operation [${n.id}] - Creating job for repository: ${this.state.repository}`);let I=await NGl(this.state.repository,this.state.prompt,this.state.asyncBranch,this.state.problemContext||"",this.authInfo,this.logger);if(!I.jobId||!I.sessionId)throw new Error(`Job creation returned incomplete data: jobId=${I.jobId}, sessionId=${I.sessionId}`);this.state={...this.state,jobId:I.jobId,sessionId:I.sessionId,jobCreatedBy:I.actor.login,jobCreatedAt:I.createdAt},this.logger.info(`Operation [${n.id}] - Job created: ID=${I.jobId}, Session=${I.sessionId}, CreatedBy=${I.actor.login}`);break}case"check-job":{if(!this.state.jobId)throw new Error("No job ID available to check status");let I=1e3,s=9e4,o=Date.now(),d=!1,u=0;for(this.logger.info(`Operation [${n.id}] - Polling for PR details (max ${s}ms)...`);!d&&Date.now()-o<s;){u++;let b=await WGl({repository:this.state.repository,jobId:this.state.jobId,authInfo:this.authInfo,logger:this.logger});this.state={...this.state,jobStatus:b.status,jobResult:b.result,prNumber:b.pullRequest?.number,prUrl:b.pullRequest?.url},b.pullRequest?.number?(this.logger.info(`Operation [${n.id}] - PR details received: #${b.pullRequest.number} (after ${u} polls, ${Date.now()-o}ms)`),d=!0):await new Promise(p=>setTimeout(p,I))}if(!d)throw new iT(`Timed out waiting for pull request information after ${s}ms`,"check-job",this.state.prUrl);break}case"wait-for-session":{if(!this.state.sessionId)throw new Error("No session ID available to check status");let I=1e3,s=9e4,o=Date.now(),d=!1,u=!1,b=!1,p=0;for(this.logger.info(`Operation [${n.id}] - Waiting for session to start (max ${s}ms)...`);!d&&Date.now()-o<s;){p++;let h=await pnt({sessionId:this.state.sessionId,authInfo:this.authInfo,logger:this.logger,integrationId:this.integrationId});if(h.resourceGlobalId&&!this.state.jobUrl){let g=zw(this.authInfo);this.state={...this.state,jobUrl:`${g}/copilot/tasks/pull/${h.resourceGlobalId}?session_id=${this.state.sessionId}`},b=!0,this.logger.info(`Operation [${n.id}] - Job URL constructed: ${this.state.jobUrl}`)}if(this.state.prNumber&&!u){let g=await Ave({repository:this.state.repository,prNumber:this.state.prNumber,authInfo:this.authInfo,logger:this.logger,includeFiles:!1});this.state={...this.state,prTitle:g.title,prDraft:g.draft,prCreatedAt:g.createdAt},u=!0,this.logger.info(`Operation [${n.id}] - PR details fetched: "${g.title}"`)}h.state==="in_progress"?(this.logger.info(`Operation [${n.id}] - Session transitioned to in_progress (after ${p} polls, ${Date.now()-o}ms)`),d=!0):h.state==="completed"||h.state==="failed"||h.state==="cancelled"||h.state==="timed_out"?(this.logger.info(`Operation [${n.id}] - Session ended with state: ${h.state} (after ${p} polls, ${Date.now()-o}ms)`),d=!0):(h.state==="waiting_for_user"||h.state==="idle")&&(this.logger.info(`Operation [${n.id}] - Session in intermediate state: ${h.state} (after ${p} polls, ${Date.now()-o}ms)`),d=!0),(!d||!u||!b)&&await new Promise(g=>setTimeout(g,I))}if(!d||!u||!b){let h=[];throw d||h.push("session transition"),u||h.push("PR details"),b||h.push("job URL"),new iT(`Timed out after ${s}ms waiting for: ${h.join(", ")}`,"wait-for-session",this.state.prUrl)}break}}this.updateOperationStatus(n.id,"done");let a=Date.now()-r;this.logger.info(`Operation [${n.id}] - Completed in ${a}ms`)}catch(a){this.updateOperationStatus(n.id,"error",a.message);let I=Date.now()-r;this.logger.error(`Operation [${n.id}] - Failed after ${I}ms: ${a.message}`),await new Promise(s=>setTimeout(s,3e3)),this.setError(a,`Operation '${n.id}' failed`);return}}if(this.allOperationsComplete()){let n=Date.now()-e;this.logger.info(`STAGE 3: Processing completed in ${n}ms - All operations successful`),setTimeout(()=>this.advanceStage(),2e3)}}catch(l){this.setError(l,"Failed to execute delegation operations")}}async startJobTracking(){if(!this.state||!this.state.sessionId){this.logger.error("Cannot start job tracking: missing state or sessionId"),this.cancelDelegation();return}this.logger.info("STAGE 4: Tracking - Starting job tracking"),this.logger.info(`Tracking session: ${this.state.sessionId}`),this.state.prNumber&&this.logger.info(`Tracking PR: #${this.state.prNumber}`);let e=1e3,l=null,n=async()=>{if(!this.state||!this.state.sessionId){this.clearPollingInterval();return}try{let r=await pnt({sessionId:this.state.sessionId,authInfo:this.authInfo,logger:this.logger,integrationId:this.integrationId}),a=this.state.sessionState;if(this.state={...this.state,sessionState:r.state},a!==r.state&&this.logger.info(`Session state changed: ${a||"unknown"} \u2192 ${r.state}`),!this.state.jobUrl&&r.resourceGlobalId){let s=zw(this.authInfo);this.state.jobUrl=`${s}/copilot/tasks/pull/${r.resourceGlobalId}?session_id=${this.state.sessionId}`,this.logger.info(`Constructed job URL from polling: ${this.state.jobUrl}`)}if(this.state.prNumber)try{let s=await Ave({repository:this.state.repository,prNumber:this.state.prNumber,authInfo:this.authInfo,logger:this.logger,includeFiles:!1}),o=s.changedFiles!==this.state.prChangedFiles||s.totalAdditions!==this.state.prTotalAdditions||s.totalDeletions!==this.state.prTotalDeletions;if(this.state={...this.state,prTitle:s.title,prDraft:s.draft,prCreatedAt:s.createdAt,prChangedFiles:s.changedFiles,prTotalAdditions:s.totalAdditions,prTotalDeletions:s.totalDeletions},o||!this.state.prFiles){let d=await Ave({repository:this.state.repository,prNumber:this.state.prNumber,authInfo:this.authInfo,logger:this.logger,includeFiles:!0,maxFiles:10});this.state={...this.state,prFiles:d.files},this.logger.info(`PR files updated: ${s.changedFiles} files${s.changedFiles>10?" (showing first 10)":""}, +${s.totalAdditions} -${s.totalDeletions}`)}}catch(s){this.logError("Failed to fetch PR details",s,"warning")}if(this.notifyStateChange(),r.state==="completed"||r.state==="failed"||r.state==="cancelled"||r.state==="timed_out"){this.logger.info(`STAGE 4: Tracking - Session ended with terminal state: ${r.state}`),this.clearPollingInterval(),setTimeout(()=>this.completeDelegationOperation(),3e3);return}let I=1e3;if(r.state==="waiting_for_user"||r.state==="idle"){l===null&&(l=Date.now());let s=Date.now()-l,o=300*1e3,d=Math.floor(s/o);I=Math.min(5e3+d*5e3,3e4)}else l=null;if(I!==e){let s=e;e=I,this.clearPollingInterval(),this.pollingIntervalId=setInterval(()=>void n(),e),this.logger.info(`Polling interval adjusted: ${s}ms \u2192 ${e}ms (state: ${r.state})`)}}catch(r){this.clearPollingInterval(),this.setError(r,"Error polling session status")}};this.pollingIntervalId=setInterval(()=>void n(),e),n()}completeDelegationOperation(){this.clearPollingInterval(),this.logger.info("STAGE 5: Complete - Delegation operation completed"),this.state&&(this.logger.startGroup("Delegation Operation Summary"),this.state.jobId&&this.logger.info(`Job ID: ${this.state.jobId}`),this.state.sessionId&&this.logger.info(`Session ID: ${this.state.sessionId}`),this.state.prNumber&&this.logger.info(`PR #${this.state.prNumber}: ${this.state.prUrl||"N/A"}`),this.state.commitHash&&this.logger.info(`Commit: ${this.state.commitHash}`),this.state.asyncBranch&&this.logger.info(`Branch: ${this.state.asyncBranch}`),this.state.sessionState&&this.logger.info(`Final session state: ${this.state.sessionState}`),this.logger.endGroup()),this.timeoutId&&clearTimeout(this.timeoutId),this.timeoutId=setTimeout(()=>{this.timeoutId=null,this.logger.info("Remote delegation workflow finished - Cleaning up"),this.onSessionCompleteCallback?this.onSessionCompleteCallback():(this.state=null,this.notifyStateChange())},3e3)}buildOperationsList(){if(!this.state)return[];let e=[];return this.state.hasUncommittedChanges&&e.push({id:"commit",status:"pending"}),e.push({id:"create-branch",status:"pending"},{id:"start-job",status:"pending"},{id:"check-job",status:"pending"},{id:"wait-for-session",status:"pending"}),e}updateOperationStatus(e,l,n){if(!this.state||!this.state.operations)return;let r=this.state.operations.map(a=>a.id===e?{...a,status:l,...n?{error:n}:{}}:a);this.state={...this.state,operations:r},this.notifyStateChange()}allOperationsComplete(){return!this.state||!this.state.operations?!0:this.state.operations.every(e=>e.status==="done"||e.status==="error")}setError(e,l){this.state&&(this.logError(l||"Operation failed",e,"error"),this.state={...this.state,error:e,isLoading:!1},this.notifyStateChange())}notifyStateChange(){this.onStateChangeCallback?.(this.state)}clearPollingInterval(){this.pollingIntervalId&&(clearInterval(this.pollingIntervalId),this.pollingIntervalId=null)}logError(e,l,n="error"){if(l instanceof T7){let r=l.responseBody?` | Response: ${JSON.stringify(l.responseBody)}`:"",a=`${e} - API error - Status: ${l.status} | Message: ${l.message}${r}`;n==="error"?this.logger.error(a):this.logger.warning(a)}else{let r=`${e}: ${l instanceof Error?l.message:String(l)}`;n==="error"?this.logger.error(r):this.logger.warning(r)}}};c();var U7=class{turnStartTimes=new Map;turnModelCallTimes=new Map;turnToolExecutionTimes=new Map;turnToolCallCounts=new Map;startTurn(e,l){this.turnStartTimes.set(e,l),this.turnModelCallTimes.set(e,{}),this.turnToolExecutionTimes.set(e,0),this.turnToolCallCounts.set(e,0)}recordModelCall(e,l){let n=this.turnModelCallTimes.get(e)||{};n.duration=l,this.turnModelCallTimes.set(e,n)}recordToolExecution(e,l){let n=this.turnToolExecutionTimes.get(e)||0;this.turnToolExecutionTimes.set(e,n+l);let r=this.turnToolCallCounts.get(e)||0;this.turnToolCallCounts.set(e,r+1)}finishTurn(e,l){let n=this.turnStartTimes.get(e);if(n===void 0)return this.cleanup(e),null;let r=l-n,a=this.turnModelCallTimes.get(e)||{},I=this.turnToolExecutionTimes.get(e)||0,s=this.turnToolCallCounts.get(e)||0,o=a.duration||0,d={totalDurationMs:r,llmDurationMs:o,toolExecutionMs:I,toolCallCount:s,totalDurationSeconds:(r/1e3).toFixed(2),llmDurationSeconds:(o/1e3).toFixed(2),toolExecutionSeconds:(I/1e3).toFixed(2)};return this.cleanup(e),d}cleanup(e){this.turnStartTimes.delete(e),this.turnModelCallTimes.delete(e),this.turnToolExecutionTimes.delete(e),this.turnToolCallCounts.delete(e)}static formatTimingBreakdown(e){return`LLM: ${e.llmDurationSeconds}s | Tools: ${e.toolExecutionSeconds}s (${e.toolCallCount} calls) | Total: ${e.totalDurationSeconds}s`}};c();var jqn="You are not licensed to use Copilot.",Kqn="You are not authorized to use this Copilot feature, it requires an enterprise or organization policy to be enabled.",qqn="The provided personal access token (PAT) does not have Copilot Requests permission. Please generate a new Fine-Grained Access Token with Copilot Requests permission (not a Classic token), or log in using /login";function hnt(t){return t.includes("not licensed to use Copilot")?{kind:"not-licensed",message:jqn}:t.includes("not authorized to use this Copilot feature")?{kind:"not-authorized",message:Kqn}:t.includes("Personal Access Token does not have Copilot Requests")?{kind:"not-authorized",message:qqn}:null}c();import{promises as $qn}from"fs";import Ant from"path";function e7n(t){let e=[],l=/(?<![a-zA-Z0-9])(@[^\s@]+)/g,n;for(;(n=l.exec(t))!==null;)e.push({displayText:n[1],startIndex:n.index,endIndex:n.index+n[0].length});return e}async function t7n(t){try{let e=await $qn.stat(t);return e.isDirectory()?"directory":e.isFile()?$se(Ant.basename(t))?"image":"file":null}catch{return null}}async function l7n(t,e=new Map,l=process.cwd()){let n=e7n(t),r=[];for(let a of n){let I=e.get(a.startIndex);if(I?.startIndex===a.startIndex)r.push(I);else{let s=a.displayText.slice(1).replace(/[.,;:!?]+$/,""),o=Ant.isAbsolute(s)?s:Ant.resolve(l,s),d=await t7n(o);if(d===null)continue;r.push({displayText:a.displayText,fullPath:o,type:d,startIndex:a.startIndex})}}return r}async function yGl(t,e=new Map,l=process.cwd(),n){let r=await l7n(t,e,l);return n.debug(`Detected mentions: ${r.map(a=>`${a.displayText} (${a.type})`).join(", ")}`),r.map(a=>({type:a.type==="image"?"file":a.type,path:a.fullPath,displayName:a.displayText,mentionIndex:a.startIndex}))}c();var Zve=nt(nl(),1);c();import{EventEmitter as Wnt}from"node:events";var gnt=class extends Wnt{get columns(){return 100}frames=[];_lastFrame;write=e=>{this.frames.push(e),this._lastFrame=e};lastFrame=()=>this._lastFrame},Znt=class extends Wnt{frames=[];_lastFrame;write=e=>{this.frames.push(e),this._lastFrame=e};lastFrame=()=>this._lastFrame},Nnt=class extends Wnt{isTTY=!0;data=null;constructor(e={}){super(),this.isTTY=e.isTTY??!0}write=e=>{this.data=e,this.emit("readable"),this.emit("data",e)};setEncoding(){}setRawMode(){}resume(){}pause(){}ref(){}unref(){}read=()=>{let{data:e}=this;return this.data=null,e}},n7n=[],EGl=t=>{let e=new gnt,l=new Znt,n=new Nnt,r=Pee(t,{stdout:e,stderr:l,stdin:n,debug:!0,exitOnCtrlC:!1,patchConsole:!1});return n7n.push(r),{rerender:r.rerender,unmount:r.unmount,cleanup:r.cleanup,stdout:e,stderr:l,stdin:n,frames:e.frames,lastFrame:e.lastFrame}};function RGl(t,e=!1){let l=Zve.default.createElement(yFe,{logger:new xd,children:Zve.default.createElement(VFe,{mode:"non-interactive",children:Zve.default.createElement(pbe,{entry:t,expand:e})})}),{lastFrame:n}=EGl(l),r=n();return r?r.trim():""}var YGl=1,ynt=!1;function I7n(t){ynt=t}var bQ=!1,Nve=[],qh=null,$T=!1;async function VGl(){if(bQ||Nve.length===0)return;bQ=!0;let{integrationId:t,messageContent:e,permissionService:l,authInfo:n,resolve:r,reject:a,completePendingToolCall:I,setQuotaSnapshots:s,setContextWindowMetrics:o,setStreamingResponseSize:d,setCurrentIntent:u,session:b,logger:p,pathManager:h,cliModel:g,enableStreaming:N,trajectoryOutputFile:y,mcpHost:Y,showLlmTiming:w,timingTracker:H,noCustomInstructions:L,setAvailableTools:S,customAgentPrompt:U,modelList:O,disableParallelToolsExecution:j}=Nve.shift();try{let B=await o7n(t,e,l,n,I,s,o,d,u,b,p,h,g,N,y,Y,w,H,L,S,U,O,j);r(B)}catch(B){B&&typeof B=="object"&&"name"in B&&B.name==="AbortError"||B&&typeof B=="object"&&"message"in B&&typeof B.message=="string"&&B.message.includes("Operation was cancelled")?r("Operation cancelled"):a(B)}finally{bQ=!1,Nve.length>0&&setTimeout(()=>void VGl(),100)}}var s7n=rZt(R0);async function o7n(t,e,l,n,r,a,I,s,o,d,u,b,p,h,g,N,y,Y,w,H,L,S,U){qh=new AbortController,a7n(0,qh.signal),s(0),o(null);try{let O=await Sr.load()||{},j=await ry(n),B=O.copilot_url;!B&&j&&n.type!=="hmac"&&(B=await s7n(n.host,j,u)),ls.env.GITHUB_COPILOT_CLI_MODE="true";let z={problemStatement:e,logger:u,saveTrajectoryOutput:g||void 0,apiCopilotIntegrationId:t,apiCopilotHmacKey:n.type==="hmac"?n.hmac:void 0,apiCopilotUrl:B,apiCopilotToken:j,serviceInstanceId:d.sessionId,mcpHost:N,saveEventLogs:ls.env.COPILOT_EVENTS_LOG_DIRECTORY},oe=kL()&&ls.env.COPILOT_AGENT_MODEL?ls.env.COPILOT_AGENT_MODEL:`sweagent-capi:${p}`,he={...z,pathManager:b,serviceAgentModel:oe,requestPermission:l.request,onToolPartialOutput:(Ge,q)=>{d.emitEphemeral("tool.execution_partial_result",{toolCallId:Ge,partialOutput:q})},showEvents:!0,showSessionLog:!1,useSessionLogOnly:!1,abortSignal:qh.signal,executeToolsInParallel:!U};try{let Ge=await cCe.createFromOptions(he);H&&H(Ge.getAvailableTools());let q=await bY(ls.cwd());q.found&&!w&&await VEe(q.gitRoot,!0,ls.cwd());let M=Ge.getAgentKind(),Ie=Ge.getModel(),se=z1e()[M]?.[Ie]??D1e(),Ee=Ge.getToolConfig?.call(Ge)??{},me=se.supports||{};me.reportIntent=!0;let ve=await r0e(q.found?q.gitRoot:"",Q8(),ls.cwd(),{},me,Ee,Ge.getAvailableTools(),void 0,w),Ye=new uCe(d,s,ynt,u),ye=await d.getChatContextMessages(),ne=ye.findLastIndex(Bt=>Bt.role==="user"),Oe=ye[ne];typeof Oe.content=="string"?Oe={...Oe,content:W6({customAgentPrompt:L,problemStatement:Oe.content,capabilities:me})}:Oe={...Oe,content:Oe.content.map(Bt=>Bt.type==="text"?{...Bt,text:W6({customAgentPrompt:L,problemStatement:Bt.text,capabilities:me})}:Bt)};let xe=new j4(Oe,u),ll=new gO(u),Yl=new mCe(o),Ft=Ge.getCompletionWithTools(ve,ye.map((Bt,Be)=>Be===ne?Oe:Bt),{stream:h,failIfInitialInputsTooLong:!1,processors:{preRequest:[xe,new o0e,ll],onRequestError:[xe],onStreamingChunk:[Ye,Yl]},executeToolsInParallel:!U,abortSignal:qh.signal});for await(let Bt of Ft){if(qh?.signal.aborted){let Be=new Error("Operation was cancelled");throw Be.name="AbortError",Be}await wTt(Bt,{onImageProcessingEvent:Be=>{},onImageRemovalEvent:Be=>{},onMessage:Be=>{if(mL(Be)){let Xt=Ye.endCurrentStreamingMessage(),$t=typeof Be.message.content=="string"?Be.message.content:null,Fn=k8(Be)?Be.message.tool_calls.map(rl=>({toolCallId:rl.id,name:rl.function.name,arguments:$k(rl.function.arguments)})):[];d.emit("assistant.message",{messageId:Xt??mu(),content:$t||"",toolRequests:Fn});for(let rl of Fn)d.emit("tool.execution_start",{toolCallId:rl.toolCallId,toolName:rl.name,arguments:rl.arguments})}else(Be.message.role==="system"||Be.message.role==="developer")&&d.emit("system.message",{role:Be.message.role,content:typeof Be.message.content=="string"?Be.message.content:JSON.stringify(Be.message.content),name:"name"in Be.message?Be.message.name:void 0})},onResponse:Be=>{},onModelCallFailure:Be=>{if(hnt(Be.modelCall?.error||""))return;let $t=Be.modelCall?.error||"Unknown error occurred";Be.modelCall.request_id&&($t+=` (Request ID: ${Be.modelCall.request_id})`),d.emit("session.error",{errorType:"model_call",message:`Model call failed: ${$t}`})},onModelCallSuccess:async Be=>{a(Be.quotaSnapshots||{});let Xt=Be.responseChunk.model||await d.getSelectedModel(),$t=Be.modelCallDurationMs||0,Fn=Be.responseUsage,rl=Xt?Wq(Xt,S):1;d.emitEphemeral("assistant.usage",{model:Xt||"unknown",inputTokens:Fn?.prompt_tokens||0,outputTokens:Fn?.completion_tokens||0,cost:rl,duration:$t,initiator:Be.modelCall?.initiator}),y&&Y&&Y.recordModelCall(Be.turn,Be.modelCallDurationMs)},onToolExecution:Be=>{r({callId:Be.toolCallId,resultType:Be.toolResult.resultType,log:(Be.toolResult.resultType==="failure"?Be.toolResult.error:void 0)||Be.toolResult.sessionLog||Be.toolResult.textResultForLlm}),y&&Y&&Y.recordToolExecution(Be.turn,Be.durationMs)},onTruncationEvent:Be=>{I(Xt=>{let $t=Math.max(Xt.totalTokens,Be.truncateResult.preTruncationTokensInMessages);return{...Xt,totalTokens:$t,postTruncationTokens:Be.truncateResult.postTruncationTokensInMessages,tokenLimit:Be.truncateResult.tokenLimit,messagesRemoved:Be.truncateResult.messagesRemovedDuringTruncation,tokensRemoved:Be.truncateResult.tokensRemovedDuringTruncation}})},onTurnEvent:Be=>{if(Be.kind==="turn_started")y&&Y&&Y.startTurn(Be.turn,Be.timestampMs);else if(Be.kind==="turn_ended"&&y&&Y){let Xt=Y.finishTurn(Be.turn,Be.timestampMs);if(Xt){let $t=U7.formatTimingBreakdown(Xt);ynt?ls.stdout.write(`
|
|
2460
2460
|
\u{1F552} ${$t}
|
|
2461
2461
|
|
|
2462
2462
|
`):d.emitEphemeral("session.info",{infoType:"timing",message:$t})}}}})}return await Ge.shutdown(),"Command completed successfully"}catch(Ge){let q=Ge&&typeof Ge=="object"&&"name"in Ge&&Ge.name==="AbortError",M=Ge&&typeof Ge=="object"&&"message"in Ge&&typeof Ge.message=="string"&&Ge.message.includes("Operation was cancelled");throw!q&&!M&&(Ge instanceof Error?u.debug(`Command threw error: ${Ge.message}
|
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.350-
|
|
4
|
+
"version": "0.0.350-20",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE.md",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"repository": {
|
|
@@ -37,6 +37,6 @@
|
|
|
37
37
|
"worker/**/*"
|
|
38
38
|
],
|
|
39
39
|
"buildMetadata": {
|
|
40
|
-
"gitCommit": "
|
|
40
|
+
"gitCommit": "0165ac2"
|
|
41
41
|
}
|
|
42
42
|
}
|