@github/copilot 0.0.354-3 → 0.0.354-5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.js +1 -1
- package/package.json +2 -2
- package/sdk/index.d.ts +11 -2
- package/sdk/index.js +1 -1
package/index.js
CHANGED
|
@@ -2043,7 +2043,7 @@ ${a}`;await r.createOrUpdateMCPStartupToolCall({serverName:e,content:o,toolNames
|
|
|
2043
2043
|
`)),s}}import{homedir as xjt}from"node:os";import R4n,{resolve as Y4n}from"node:path";function Pfn(t){return t.length>0&&/^[0-9a-zA-Z_-]+$/.test(t)}function hPt(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 pPt=G0(["none","markdown","hidden_characters"]),APt=zl({tools:Od(Qt()),type:Qt().optional(),isDefaultServer:ro().optional(),filterMapping:rY(Qt(),pPt).or(pPt).optional()}),jfn=APt.extend({type:pr("local").optional(),command:Qt(),args:Od(Qt()),env:rY(Qt(),Qt()).optional()}),Kfn=APt.extend({type:pr("http").or(pr("sse")),url:Qt(),headers:rY(Qt(),Qt()).optional()}),qqe=zl({mcpServers:rY(Qt().min(1,"MCP server name cannot be empty").refine(Pfn,{message:"MCP server name must only contain alphanumeric characters, underscores, and hyphens"}),jfn.or(Kfn))}),uY=Jwe(qqe.parse,"mcp");function gPt(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,c=(r+a)/2;if(I!==0){switch(o=c>.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:c}}function qfn(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=c=>c.length>=2?parseInt(c.substring(0,2),16):c.length===1?parseInt(c+c,16):0,I=a(l),s=a(n),o=a(r);return{r:I,g:s,b:o}}var ZPt=["#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 $fn(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 eHn(t){return t<0||t>=ZPt.length?{r:0,g:0,b:0}:$fn(ZPt[t])}function NPt(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:")?qfn(l):null}async function tHn(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 c=`11;${s[1]}`;e(NPt(c));return}let o=l.match(/11;rgb:([0-9a-f/]+)(?:\x07|\x1b\\|\x9c)/i);if(o){r(),e(NPt(`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 lHn(){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:eHn(n)}async function WPt(){try{let t=await tHn();if(t)return gPt(t).l<.5;let e=lHn();return e?gPt(e).l<.5:!0}catch{return!0}}var yPt={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"},nHn={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 $qe(t){return t==="auto"||t==="dark"||t==="light"}function _we(t){switch(t){case"dark":return yPt;case"light":return nHn;default:return yPt}}var Dwe=await WPt();async function zwe(){let e=(await Sr.load())?.theme||"";return $qe(e)?e:"auto"}async function EPt(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(`
|
|
2044
2044
|
`).map(d=>d.startsWith(I)?d.slice(I.length):d).join(`
|
|
2045
2045
|
`)),s.trimEnd()},listitem:r=>e(r.trimEnd()),reflowText:!0,showSectionPrefix:!1,unescape:!0,emoji:!0,tab:2,tableOptions:{style:{compact:!1}}}},rHn=RPt(!0),aHn=RPt(!1);function YPt(t){return t==="light"?aHn:rHn}import{exec as W4n}from"node:child_process";import*as V7e from"node:os";import{promisify as y4n}from"node:util";async function BL(t,e,l){if(!t||t.length===0)return;let n=!1,r={};for(let a of t)try{let I=await a(e);I&&(n=!0,r={...r,...I})}catch(I){l.error(`Hook execution failed: ${I}`)}return n?r:void 0}import{unlink as Gjt}from"fs/promises";import{join as I4n}from"path";import{execFile as IHn}from"node:child_process";import{normalize as sHn}from"node:path";import{promisify as oHn}from"node:util";var Ime=oHn(IHn);async function mY(t=process.cwd()){try{let l=(await Ime("git",["rev-parse","--show-toplevel"],{cwd:t,encoding:"utf8",timeout:5e3,maxBuffer:1048576})).stdout.trim();if(l)return{gitRoot:sHn(l),found:!0}}catch{}return{gitRoot:t,found:!1}}async function VPt(t){let{stdout:e}=await Ime("git",["-C",t,"remote","-v"],{encoding:"utf8",timeout:5e3,maxBuffer:1048576}),l=e.trim().split(`
|
|
2046
|
-
`),n={};for(let r of l){let a=r.split(/\s+/);if(a.length>=3){let I=a[0],s=a[1],o=a[2].replace(/[()]/g,"");n[I]||(n[I]={Name:I,FetchURL:"",PushURL:""}),o==="fetch"?n[I].FetchURL=s:o==="push"&&(n[I].PushURL=s)}}return Object.values(n)}async function wPt(t){try{let{stdout:e}=await Ime("git",["status","--porcelain"],{cwd:t,encoding:"utf8",timeout:5e3,maxBuffer:1048576});return e.trim().length>0}catch{return!1}}async function QPt(t){try{let{stdout:e}=await Ime("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:t,encoding:"utf8",timeout:5e3,maxBuffer:1048576}),l=e.trim();if(l==="HEAD"){let{stdout:n}=await Ime("git",["rev-parse","--short","HEAD"],{cwd:t,encoding:"utf8",timeout:5e3,maxBuffer:1048576}),r=n.trim();return r?`detached@${r}`:null}return l||null}catch{return null}}var ajt=$e(rjt(),1);async function t5n(t={}){let e=await _gt();return Pgt((0,ajt.default)({},e,t))}async function ume(t={}){if(uD())throw new Error("Settings have already been initialized");return t5n(t)}import{promises as l5n}from"fs";import Ijt from"path";var n5n=3*1024*1024;function sjt(t){let e=Ijt.extname(t).toLowerCase();return[".png",".jpg",".jpeg",".gif",".webp"].includes(e)}function r5n(t){switch(Ijt.extname(t).toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";default:return null}}async function a5n(t,e){e.debug(`Processing local image file: ${t}`);let l=await l5n.readFile(t),n=r5n(t);if(!n)throw new Error(`Unsupported image format: ${t}`);let r=new roe,a=await c0e(e,r,n5n,toe,n,l);if(!a)throw new Error(`Image too large or couldn't be processed: ${t}`);let I=a.toString("base64");return`data:${n};base64,${I}`}async function I5n(t,e,l){let n=cu();try{let r=await hBe({command:"view",path:t,view_range:void 0},{properties:{command:"view",resolvedPathAgainstCwd:"false",options:"{}",inputs:"[]"},metrics:{responseTokenLimit:void 0,resultLength:0,resultForLlmLength:0},restrictedProperties:{}},e,l);return{id:n,name:"view",arguments:{path:t},result:r.textResultForLlm||""}}catch(r){return{id:n,name:"view",arguments:{path:t},result:`Error reading ${t}: ${r}`}}}async function ojt(t,e,l){let n=[],r=t.filter(I=>!sjt(I.path));if(r.length===0)return n;let a=[];for(let I of r)try{let s=await I5n(I.path,e,l);a.push(s)}catch{}if(a.length>0){let I=a.map(s=>({id:s.id,type:"function",function:{name:s.name,arguments:JSON.stringify(s.arguments)}}));n.push({role:"assistant",content:"I need to read the content of those paths to answer this request.",tool_calls:I}),n.push(...a.map(s=>({role:"tool",tool_call_id:s.id,content:s.result})))}return n}async function ijt(t,e){let l=t.filter(r=>sjt(r.path));return(await Promise.all(l.map(async r=>{try{return{type:"image_url",image_url:{url:await a5n(r.path,e)}}}catch(a){e.error(`Failed to process image ${r.path}: ${a instanceof Error?a.message:String(a)}`);return}}))).filter(r=>r!==void 0)}var c7e=class{constructor(e,l){this.logger=e;this.session=l}messageQueue=[];async*preRequest(e){this.logger.debug("ImmediatePromptProcessor: Injecting immediate prompts");let n=(await this.session.getChatMessages()).length;for(;this.messageQueue.length>0;){let I=this.messageQueue.shift();this.session.emit("user.message",{content:I.prompt,attachments:I.attachments})}let a=(await this.session.getChatMessages()).slice(n);for(let I of a)e.messages.push(I),yield{kind:"message",message:I,turn:e.turn,source:"immediate-prompt"}}addMessage(e){this.messageQueue.push(e)}toJSON(){return"ImmediatePromptProcessor"}},Ff=class t{sessionId;startTime;modifiedTime;logger;events=[];_chatMessages=[];_selectedModel;eventProcessingQueue=Promise.resolve();eventHandlers={};wildcardEventHandlers=[];isProcessing=!1;messageQueue=[];immediatePromptProcessor;mcpHost;workingDir;abortController;modelProvider;allowedTools;disabledTools;requestPermission;mcpServers;hooks;hmacKey;copilotToken;constructor(e={},l={}){this.sessionId=l.sessionId||cu(),this.startTime=l.startTime||new Date,this.modifiedTime=l.modifiedTime||this.startTime,this.logger=e.logger||new xd,this.modelProvider=e.modelProvider,this.allowedTools=e.allowedTools,this.disabledTools=e.disabledTools,this.requestPermission=e.requestPermission,this.mcpServers=e.mcpServers,this.hooks=e.hooks,this.hmacKey=e.hmacKey,this.copilotToken=e.copilotToken,this.workingDir=e.workingDirectory||process.cwd(),this.immediatePromptProcessor=new c7e(this.logger,this),this.abortController=e.abortController||new AbortController,mY(this.workingDir).then(n=>{if(n.found)return vEe(n.gitRoot,!0,this.workingDir)}).catch(n=>{this.logger.debug(`Failed to initialize custom instructions cache: ${n}`)})}get messageCount(){let e=this.events.find(n=>n.type==="session.import_legacy"),l=0;return e&&(l=(e.data.legacySession?.chatMessages||[]).filter(a=>a.role==="user"||a.role==="assistant").length),this.logger.debug(`Imported message count: ${l}`),this.events.filter(n=>n.type==="user.message"||n.type==="assistant.message").length+l}get summary(){let e=this.events.find(a=>a.type==="session.import_legacy"||a.type==="user.message"),l;if(e?.type==="session.import_legacy"){let a=e.data.legacySession.chatMessages.find(I=>I.role==="user");a?.content&&(typeof a.content=="string"?l=a.content:l=a.content.find(I=>I.type==="text")?.text)}else e?.type==="user.message"&&(l=e.data.content);if(!l)return;let n=l.lastIndexOf("<reminder>");n!==-1&&(l=l.substring(0,n).trim());let r=l.replace(/\s+/g," ").trim();return r.length>75&&(r=r.substring(0,55).trim()+"..."),r=r.split("").filter(a=>{let I=a.charCodeAt(0);return I>=32&&I!==127}).join(""),r}static async fromEvents(e,l={}){if(e.length===0)throw new Error("Cannot create session from empty events array");let n=e[0];if(n.type!=="session.start")throw new Error("First event must be session.start");let r=new t(l,{sessionId:n.data.sessionId,startTime:new Date(n.data.startTime)});r._selectedModel=n.data.selectedModel,r.events.push(n);for(let a=1;a<e.length;a++){let I=e[a];r.events.push(I),await r.processEventForState(I)}return r}on(e,l){return e==="*"?(this.wildcardEventHandlers.push(l),()=>{let n=this.wildcardEventHandlers.indexOf(l);n!==-1&&this.wildcardEventHandlers.splice(n,1)}):(this.eventHandlers[e]||(this.eventHandlers[e]=[]),this.eventHandlers[e].push(l),()=>{let n=this.eventHandlers[e];if(n){let r=n.indexOf(l);r!==-1&&n.splice(r,1)}})}emit(e,l,n=!1){let r=cu(),a=new Date().toISOString(),I=this.getLastEventId(),s={type:e,data:l,id:r,timestamp:a,parentId:I,...n&&{ephemeral:n}};this.events.push(s),this.enqueueEventProcessing(()=>this.processEventForState(s)).catch(o=>{this.logger.error(`Error emitting event: ${o instanceof Error?o.message:String(o)}`)}).catch(o=>{this.logger.error(`Error emitting event ${o instanceof Error?o.message:String(o)}`)}),[...this.eventHandlers[s.type]||[],...this.wildcardEventHandlers].forEach(o=>{try{o(s)}catch(c){this.logger.error(`Error in event handler for event type ${s.type}: ${c instanceof Error?c.message:String(c)}`)}})}emitEphemeral(e,l){this.emit(e,l,!0)}getEvents(){return this.events}async getChatMessages(){return this.enqueueEventProcessing(()=>this._chatMessages)}async getChatContextMessages(){return(await this.getChatMessages()).filter(l=>l.role!=="system")}async getSystemContextMessages(){return(await this.getChatMessages()).filter(l=>l.role==="system")}async getSelectedModel(){return this.enqueueEventProcessing(()=>this._selectedModel)}async setSelectedModel(e){let l=await this.getSelectedModel();this.emit("session.model_change",{previousModel:l,newModel:e})}getLastEventId(){return this.events.length===0?null:this.events[this.events.length-1].id}enqueueEventProcessing(e){let l=this.eventProcessingQueue.then(()=>e());return this.eventProcessingQueue=l,l}async processEventForState(e){switch(e.type){case"session.start":e.data.selectedModel&&(this._selectedModel=e.data.selectedModel);break;case"session.model_change":this._selectedModel=e.data.newModel;break;case"user.message":{let l=[],n=[];if(e.data.attachments&&e.data.attachments.length>0){let r=await ijt(e.data.attachments,this.logger);l.push(...r);let a=await ojt(e.data.attachments,{requestRequired:!1},this.logger);n.push(...a)}l.length>0?this._chatMessages.push({role:"user",content:[{type:"text",text:e.data.content},...l]}):this._chatMessages.push({role:"user",content:e.data.content}),n.length>0&&this._chatMessages.push(...n);break}case"assistant.message":{if(e.ephemeral||e.data.parentToolCallId)break;let l={role:"assistant",content:e.data.content||null};e.data.toolRequests&&e.data.toolRequests.length>0&&(l.tool_calls=e.data.toolRequests.map(n=>({id:n.toolCallId,type:"function",function:{name:n.name,arguments:typeof n.arguments=="string"?n.arguments:JSON.stringify(n.arguments)}}))),this._chatMessages.push(l);break}case"tool.execution_complete":{if(e.data.parentToolCallId)break;e.data.isUserRequested||this._chatMessages.push({role:"tool",tool_call_id:e.data.toolCallId,content:e.data.success?e.data.result?.content||"":e.data.error?.message||"Tool execution failed"});break}case"system.message":this._chatMessages.push({role:e.data.role,content:e.data.content,...e.data.name&&{name:e.data.name}});break;case"session.import_legacy":this._chatMessages=[...e.data.legacySession.chatMessages],e.data.legacySession.selectedModel&&(this._selectedModel=e.data.legacySession.selectedModel);break;case"abort":case"session.resume":this._chatMessages=s5n(this._chatMessages,this.logger);break;case"session.idle":case"session.error":case"session.info":case"assistant.turn_start":case"assistant.turn_end":case"assistant.usage":case"tool.user_requested":case"tool.execution_start":case"tool.execution_partial_result":case"hook.start":case"hook.end":break;default:{let l=e;this.logger.error(`Unknown event type: ${l.type}`);break}}}async send(e,l={}){if((l.mode||"enqueue")==="immediate"&&this.isProcessing)this.immediatePromptProcessor.addMessage(e);else{if(this.messageQueue.push(e),this.isProcessing)return;for(this.isProcessing=!0,await this.initializeMcpHost();this.messageQueue.length>0;){let r=this.messageQueue.shift();await this.runAgenticLoop(r.prompt,r.attachments)}this.isProcessing=!1,this.emit("session.idle",{})}}async abort(){this.abortController.abort()}async initializeMcpHost(){if(!this.mcpHost&&this.mcpServers&&Object.keys(this.mcpServers).length>0)try{this.mcpHost=new XL(this.logger,{mcpServers:this.mcpServers},this.disabledTools),await this.mcpHost.startServers()}catch(e){this.logger.error(`Failed to initialize MCP host: ${e}`)}}async runAgenticLoop(e,l=[]){if(!this.modelProvider)throw new Error("Session must be created with modelProvider to use send/query methods");let n=new Map,r=new Map;try{let I=(await BL(this.hooks?.userPromptSubmitted,{timestamp:Date.now(),cwd:this.workingDir,prompt:e},this.logger))?.modifiedPrompt??e;this.emit("user.message",{content:Q6({problemStatement:I,capabilities:{}}),attachments:l});let o=new DX().setProblemStatement(I).setAgentModel(this.buildAgentModelString()).setGithubRepoName("copilot-sdk-session").setGithubRepoCommit("copilot-sdk-commit").setGithubRepoReadWrite(!1).setCopilotIntegrationId("copilot-developer-cli").setCopilotHmacKey(this.hmacKey).setCopilotToken(this.copilotToken).build();wx();let c=await ume(o),d=c.service?.agent?.model,m=kB(d),G=m.agent,p=G??"sweagent-capi",A=m.model?{model:m.model}:void 0,Z=Mde(c,this.logger,G,A),W={location:this.workingDir,timeout:3e4,requireReasoning:!0,toolPartialResultCallback:(re,se)=>{this.emitEphemeral("tool.execution_partial_result",{toolCallId:re,partialOutput:se})},permissions:this.requestPermission?{requestRequired:!0,request:this.requestPermission}:{requestRequired:!1},shellConfig:(process.platform==="win32"?bp.powerShell:bp.bash).withScriptSafetyAssessor(async function(re){return{result:"completed",commands:[{identifier:re,readOnly:!1}],possiblePaths:[],hasWriteFileRedirection:!1,canOfferSessionApproval:!1}})},R=await K1e(W,this.logger),V=[];if(this.mcpHost)try{V=await this.mcpHost.getTools(c,this.logger,W.permissions)}catch(re){this.logger.error(`Failed to get MCP tools: ${re}`)}let v=[...R,...V].filter(re=>this.allowedTools?this.allowedTools.includes(re.name):this.disabledTools?!this.disabledTools.includes(re.name):!0),X=await mY(this.workingDir),O={...(U8()[p]?.[Z.model]??O8()).supports,reasoning:!0},T=await w6({location:X.found?X.gitRoot:"",version:mL(),currentWorkingDirectory:this.workingDir,parts:{},capabilities:O,toolConfigOverrides:W,tools:v,organizationCustomInstructions:void 0}),D=(await this.getChatMessages()).slice(0,-1),Ge={role:"user",content:Q6({customAgentPrompt:void 0,problemStatement:I,capabilities:O})},ge=[...D,Ge];await BL(this.hooks?.sessionStart,{timestamp:Date.now(),cwd:this.workingDir,source:"new",initialPrompt:e},this.logger);let K=new K4(Ge,this.logger),U=Z.getCompletionWithTools(T,ge,v,{failIfInitialInputsTooLong:!1,processors:{preRequest:[K,this.immediatePromptProcessor,new YT(this.logger)],onRequestError:[K]},executeToolsInParallel:!1,abortSignal:this.abortController.signal});for await(let re of U){if(this.abortController.signal.aborted){this.emit("abort",{reason:"user initiated"});break}switch(re.kind){case"message":{if(pL(re)){let se=T8(re)?await Promise.all(re.message.tool_calls.map(async We=>{let me=tL(We.function.arguments);n.set(We.id,We.function.name),r.set(We.id,me);let ve=await BL(this.hooks?.preToolUse,{timestamp:Date.now(),cwd:this.workingDir,toolName:We.function.name,toolArgs:me},this.logger);return{toolCallId:We.id,name:We.function.name,arguments:ve?.modifiedArgs??me}})):[];this.emit("assistant.message",{parentToolCallId:void 0,messageId:cu(),content:typeof re.message.content=="string"?re.message.content:"",toolRequests:se});for(let We of se)this.emit("tool.execution_start",{toolCallId:We.toolCallId,toolName:We.name,arguments:We.arguments})}else(re.message.role==="system"||re.message.role==="developer")&&this.emit("system.message",{role:re.message.role,content:typeof re.message.content=="string"?re.message.content:JSON.stringify(re.message.content),name:"name"in re.message?re.message.name:void 0});break}case"model_call_failure":{let se=new Error(re.modelCall?.error||"Model call failed");await BL(this.hooks?.errorOccurred,{timestamp:Date.now(),cwd:this.workingDir,error:se,errorContext:"model_call",recoverable:!0},this.logger),this.emit("session.error",{errorType:"model_call",message:se.message,stack:se.stack});break}case"tool_execution":{let We=(await BL(this.hooks?.postToolUse,{timestamp:Date.now(),cwd:this.workingDir,toolName:n.get(re.toolCallId)||"unknown",toolArgs:r.get(re.toolCallId)||{},toolResult:re.toolResult},this.logger))?.modifiedResult??re.toolResult,me=(We.resultType==="failure"?We.error:void 0)||We.sessionLog||We.textResultForLlm;this.emit("tool.execution_complete",{parentToolCallId:void 0,toolCallId:re.toolCallId,success:We.resultType==="success",result:We.resultType==="success"?{content:me}:void 0,error:We.resultType!=="success"?{message:me,code:We.resultType}:void 0});break}case"turn_started":{this.emit("assistant.turn_start",{turnId:`${re.turn}`});break}case"turn_ended":{this.emit("assistant.turn_end",{turnId:`${re.turn}`});break}case"response":case"images_removed":case"image_processing":case"history_truncated":case"turn_failed":case"turn_retry":case"model_call_success":this.logger.debug(`Ignoring event of kind: ${re.kind}`);break;default:wo(re,"Unhandled event type")}}}catch(a){await BL(this.hooks?.sessionEnd,{timestamp:Date.now(),cwd:this.workingDir,reason:"error",error:a instanceof Error?a:new Error(String(a))},this.logger),this.emit("session.error",{errorType:"query",message:a instanceof Error?a.message:String(a),stack:a instanceof Error?a.stack:void 0})}finally{await BL(this.hooks?.sessionEnd,{timestamp:Date.now(),cwd:this.workingDir,reason:"complete"},this.logger)}}buildAgentModelString(){if(!this.modelProvider)throw new Error("Session must be created with modelProvider");switch(this.modelProvider.type){case"openai":return`openai:${this.modelProvider.model}`;case"anthropic":return`anthropic:${this.modelProvider.model}`;case"copilot":return`capi:${this.modelProvider.model}`;default:throw new Error(`Unsupported provider: ${this.modelProvider.type}`)}}};function s5n(t,e){if(t.length===0)return t;let l=[],n=new Set,r=!1;for(let s=t.length-1;s>=0;s--){let o=t[s];if(o.role==="assistant"&&(r=!0),o.role==="assistant"&&"tool_calls"in o&&o.tool_calls&&o.tool_calls.length>0)for(let c of o.tool_calls)n.has(c.id)||l.push(c.id);else{if(r)break;o.role==="tool"&&o.tool_call_id&&n.add(o.tool_call_id)}}if(l.length===0)return t;let a="The execution of this tool, or a previous tool was interrupted.";e.info(`Completing ${l.length} orphaned tool calls.`);let I=l.map(s=>({role:"tool",tool_call_id:s,content:a}));return[...t,...I]}var nQe=class{sessions;logger;options;lastAccessedSessionId;constructor(e){this.options=e,this.sessions=new Map,this.logger=e.logger||new xd}async createSession(){let e=new Ff(this.options);return this.sessions.set(e.sessionId,e),this.lastAccessedSessionId=e.sessionId,e}async getSession(e){let l=this.sessions.get(e);return l&&(this.lastAccessedSessionId=e),l}async getLastSession(){if(this.lastAccessedSessionId){let n=this.sessions.get(this.lastAccessedSessionId);if(n)return n}let e=Array.from(this.sessions.values());if(e.length===0)return;e.sort((n,r)=>r.startTime.getTime()-n.startTime.getTime());let l=e[0];return this.lastAccessedSessionId=l.sessionId,l}async listSessions(){return Array.from(this.sessions.values()).map(e=>({sessionId:e.sessionId,startTime:e.startTime,modifiedTime:e.modifiedTime}))}async saveSession(e){}async deleteSession(e){this.sessions.delete(e.sessionId),this.lastAccessedSessionId===e.sessionId&&(this.lastAccessedSessionId=void 0)}async closeSession(e){}};var fq=zl({command:Qt(),description:Qt(),timeout:LG().optional(),sessionId:Qt().optional(),async:ro().optional()}),d7e=zl({sessionId:Qt(),input:Qt(),delay:LG().optional()}),u7e=zl({sessionId:Qt(),delay:LG()}),m7e=zl({sessionId:Qt()}),cjt=Oh([fq,d7e,u7e,m7e]),o5n=zl({command:pr("view"),path:Qt(),view_range:nVe([LG(),LG()]).optional()}),i5n=zl({command:pr("create"),path:Qt(),file_text:Qt()}),c5n=zl({command:pr("str_replace"),path:Qt(),new_str:Qt().optional(),old_str:Qt()}),d5n=zl({command:pr("insert"),path:Qt(),insert_line:LG(),new_str:Qt()}),b7e=Kde("command",[o5n,i5n,c5n,d5n]),G7e=zl({path:Qt(),view_range:nVe([LG(),LG()]).optional()}),p7e=zl({path:Qt(),file_text:Qt()}),h7e=zl({path:Qt(),old_str:Qt(),new_str:Qt().optional()}),A7e=Oh([cjt,b7e,Sw()]),djt=(t,e)=>{switch(t.type){case"copilot":return e.onCopilot(t);case"tool_call_requested":return e.onToolCallRequested(t);case"tool_call_completed":return e.onToolCallCompleted(t);default:wo(t,"Unknown groupable timeline entry type")}};function ujt(t,e){switch(t.type){case"copilot":return e.onCopilot(t);case"error":return e.onError(t);case"group_tool_call_requested":return e.onGroupToolCallRequested(t);case"group_tool_call_completed":return e.onGroupToolCallCompleted(t);case"info":return e.onInfo(t);case"tool_call_requested":return e.onToolCallRequested(t);case"tool_call_completed":return e.onToolCallCompleted(t);case"user":return e.onUser(t);default:wo(t,"Unknown timeline entry type")}}var bO=class t extends Error{prUrl;timeoutContext;constructor(e,l,n){super(e),this.name="JobStatusTimeoutError",this.timeoutContext=l,this.prUrl=n,Error.captureStackTrace&&Error.captureStackTrace(this,t)}};var mme=zl({type:pr("text"),text:Qt()}),u5n=zl({type:pr("refusal"),refusal:Qt()}),m5n=zl({type:pr("image_url"),image_url:zl({url:Qt(),detail:G0(["auto","low","high"]).optional()})}),b5n=zl({type:pr("input_audio"),input_audio:zl({data:Qt(),format:pr("wav").or(pr("mp3"))})}),G5n=zl({type:pr("file"),file:zl({file_date:Qt().optional(),file_id:Qt().optional(),filename:Qt().optional()})}),p5n=Oh([mme,m5n,b5n,G5n]),h5n=zl({name:Qt(),arguments:Qt()}),A5n=zl({name:Qt(),input:Qt()}),g5n=zl({id:Qt(),type:pr("function"),function:h5n}),Z5n=zl({id:Qt(),type:pr("custom"),custom:A5n}),N5n=Oh([g5n,Z5n]),W5n=zl({name:Qt(),arguments:Qt()}),y5n=zl({id:Qt()}),E5n=zl({content:Oh([Qt(),Od(mme)]),role:pr("developer"),name:Qt().optional()}),R5n=zl({content:Oh([Qt(),Od(mme)]),role:pr("system"),name:Qt().optional()}),Y5n=zl({content:Oh([Qt(),Od(p5n)]),role:pr("user"),name:Qt().optional()}),V5n=zl({content:Oh([Qt(),Od(Oh([mme,u5n]))]).nullable().optional(),role:pr("assistant"),name:Qt().optional(),refusal:Qt().nullable().optional(),audio:y5n.nullable().optional(),function_call:W5n.nullable().optional(),tool_calls:Od(N5n).optional()}),w5n=zl({content:Oh([Qt(),Od(mme)]),role:pr("tool"),tool_call_id:Qt()}),Q5n=zl({content:Qt().nullable(),role:pr("function"),name:Qt()}),F5n=Oh([E5n,R5n,Y5n,V5n,w5n,Q5n]),C5n=zl({type:pr("copilot"),text:Qt(),isStreaming:ro().optional()}),v5n=zl({type:pr("error"),text:Qt()}),f5n=zl({type:pr("info"),text:Qt()}),H5n=zl({type:pr("user"),text:Qt()}),X5n=zl({type:pr("tool_call_requested"),callId:Qt(),name:Qt(),toolTitle:Qt().optional(),intentionSummary:Qt().nullable(),arguments:A7e,partialOutput:Qt().optional(),isHidden:ro().optional(),isAlwaysExpanded:ro().optional(),showNoContent:ro().optional()}),k5n=zl({type:pr("tool_call_completed"),callId:Qt(),name:Qt(),toolTitle:Qt().optional(),intentionSummary:Qt().nullable(),result:Oh([zl({type:pr("success"),log:Qt(),markdown:ro().optional()}),zl({type:pr("failure"),log:Qt(),markdown:ro().optional()}),zl({type:pr("rejected"),markdown:ro().optional()}),zl({type:pr("denied"),log:Qt(),markdown:ro().optional()})]),arguments:A7e,isHidden:ro().optional(),isAlwaysExpanded:ro().optional(),showNoContent:ro().optional()}),L5n=Oh([C5n,v5n,f5n,H5n,X5n,k5n]),J5n=L5n.and(zl({id:Qt(),timestamp:rVe.date()})),g7e=zl({sessionId:Qt(),startTime:rVe.date(),chatMessages:Od(F5n),timeline:Od(J5n),selectedModel:G0(Ef).optional()}),bme=xwe(g7e.parse,"history-session");var jm=zl({id:Qt().uuid(),timestamp:Qt().datetime(),parentId:Qt().uuid().nullable(),ephemeral:ro().optional()}),mjt=zl({parentToolCallId:Qt().optional()}),x5n=jm.extend({type:pr("session.start"),data:zl({sessionId:Qt(),version:LG(),producer:Qt(),copilotVersion:Qt(),startTime:Qt().datetime(),selectedModel:Qt().optional()})}),S5n=jm.extend({type:pr("session.resume"),data:zl({resumeTime:Qt().datetime(),eventCount:LG()})}),B5n=jm.extend({type:pr("session.error"),data:zl({errorType:Qt(),message:Qt(),stack:Qt().optional()})}),T5n=jm.extend({type:pr("session.info"),data:zl({infoType:Qt(),message:Qt()})}),O5n=jm.extend({type:pr("session.model_change"),data:zl({previousModel:Qt().optional(),newModel:Qt()})}),U5n=jm.extend({type:pr("session.import_legacy"),data:zl({legacySession:g7e,importTime:Qt().datetime(),sourceFile:Qt()})}),M5n=jm.extend({type:pr("session.idle"),ephemeral:pr(!0),data:zl({})}),_5n=zl({type:G0(["file","directory"]),path:Qt(),displayName:Qt()}),D5n=jm.extend({type:pr("user.message"),data:zl({content:Qt(),attachments:Od(_5n).optional()})}),z5n=jm.extend({type:pr("assistant.turn_start"),data:zl({turnId:Qt()})}),P5n=jm.extend({type:pr("assistant.message"),data:zl({messageId:Qt(),content:Qt(),toolRequests:Od(zl({toolCallId:Qt(),name:Qt(),arguments:Sw()})).optional()}).merge(mjt)}),j5n=jm.extend({type:pr("assistant.turn_end"),data:zl({turnId:Qt()})}),K5n=jm.extend({type:pr("assistant.usage"),ephemeral:pr(!0),data:zl({model:Qt().optional(),inputTokens:LG().optional(),outputTokens:LG().optional(),cost:LG().optional(),duration:LG().optional(),initiator:Qt().optional()})}),q5n=jm.extend({type:pr("abort"),data:zl({reason:Qt()})}),$5n=jm.extend({type:pr("tool.user_requested"),data:zl({toolCallId:Qt(),toolName:Qt(),arguments:Sw()})}),e4n=jm.extend({type:pr("tool.execution_start"),data:zl({toolCallId:Qt(),toolName:Qt(),arguments:Sw()})}),t4n=jm.extend({type:pr("tool.execution_partial_result"),ephemeral:pr(!0),data:zl({toolCallId:Qt(),partialOutput:Qt()})}),l4n=jm.extend({type:pr("tool.execution_complete"),data:zl({toolCallId:Qt(),success:ro(),isUserRequested:ro().optional(),result:zl({content:Qt()}).optional(),error:zl({message:Qt(),code:Qt().optional()}).optional()}).merge(mjt)}),n4n=jm.extend({type:pr("hook.start"),data:zl({hookInvocationId:Qt(),hookType:Qt(),input:Sw()})}),r4n=jm.extend({type:pr("hook.end"),data:zl({hookInvocationId:Qt(),hookType:Qt(),output:Sw(),success:ro(),error:zl({message:Qt(),stack:Qt().optional()}).optional()})}),a4n=jm.extend({type:pr("system.message"),data:zl({content:Qt(),role:G0(["system","developer"]),name:Qt().optional(),metadata:zl({promptVersion:Qt().optional(),variables:rY(Sw()).optional()}).optional()})}),bjt=Kde("type",[x5n,S5n,B5n,M5n,T5n,O5n,U5n,D5n,z5n,P5n,j5n,K5n,q5n,$5n,e4n,t4n,l4n,n4n,r4n,a4n]);var GO=$zt(bjt.parse,"session");var rQe=class{constructor(e,l,n,r=!1,a){this.session=e;this.logger=l;this.flushDebounceMs=n;this.shouldSaveSession=r;this.legacySourceFile=a;this.unsubscribe=this.session.on("*",I=>{I.ephemeral||(this.unflushedEvents.push(I),!this.shouldSaveSession&&I.type==="user.message"&&(this.shouldSaveSession=!0),I.type!=="session.resume"&&this.shouldSaveSession&&(this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=setTimeout(()=>{this.flush().catch(s=>{this.logger.error(`Error flushing session ${this.session.sessionId}: ${s instanceof Error?s.message:String(s)}`)})},this.flushDebounceMs)))})}flushTimer=null;unflushedEvents=[];migratedLegacy=!1;isFlushing=!1;needsFlushAfterCurrent=!1;unsubscribe;dispose(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.unsubscribe()}async flush(){if(!this.shouldSaveSession||this.unflushedEvents.length===0)return;if(this.isFlushing){this.needsFlushAfterCurrent=!0;return}this.isFlushing=!0,this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null);let e=this.unflushedEvents;this.unflushedEvents=[];try{if(await GO.append(e,this.session.sessionId),this.logger.debug(`Flushed ${e.length} events to session ${this.session.sessionId}`),this.legacySourceFile&&!this.migratedLegacy){this.logger.debug(`Migrated legacy session ${this.session.sessionId} from ${this.legacySourceFile}`);try{await Gjt(this.legacySourceFile)}catch(l){this.logger.error(`Failed to delete legacy session file ${this.legacySourceFile}: ${l}`)}this.migratedLegacy=!0}}catch(l){this.logger.error(`Failed to flush events for ${this.session.sessionId}: ${l instanceof Error?l.message:String(l)}`),this.unflushedEvents.unshift(...e)}finally{this.isFlushing=!1,this.needsFlushAfterCurrent&&(this.needsFlushAfterCurrent=!1,await this.flush())}}},aQe=class extends nQe{sessionWriters={};copilotVersion;flushDebounceMs;constructor({version:e,flushDebounceMs:l,...n}){super({...n}),this.copilotVersion=e||"unknown",this.flushDebounceMs=l||100}async createSession(e){let l=e?.sessionId??cu(),n=new Date,r=new Ff(this.options,{sessionId:l,startTime:n});return this.sessionWriters[l]=new rQe(r,this.logger,this.flushDebounceMs),r.emit("session.start",{sessionId:l,version:1,producer:"copilot-agent",copilotVersion:this.copilotVersion,startTime:n.toISOString(),selectedModel:e?.selectedModel}),r}async getSession(e,l=!0){let n,r;try{n=await this.loadSession(e)}catch{try{let a=await this.loadLegacySession(e);n=a.session,r=a.legacySourceFile}catch{return}}return this.sessionWriters[e]||(this.sessionWriters[e]=new rQe(n,this.logger,this.flushDebounceMs,!0,r)),l&&n.emit("session.resume",{resumeTime:new Date().toISOString(),eventCount:n.getEvents().length}),n}async saveSession(e){await this.sessionWriters[e.sessionId]?.flush()}async loadSession(e){let l=await GO.load(e);return await Ff.fromEvents(l,this.options)}async loadLegacySession(e){let n=(await bme.directoryFiles()).filter(o=>{let c=o.match(/^session_(.+)_(\d+)\.json$/);return c&&c[1]===e});if(n.length===0)throw new Error(`Legacy session ${e} not found`);let r=n[0];n.length>1&&this.logger.info(`Multiple legacy sessions found for ${e}, using newest`);let a=await bme.load(r);if(!a)throw new Error(`Failed to load legacy session from ${r}`);let I=new Date(a.startTime),s=new Ff(this.options,{sessionId:a.sessionId,startTime:I});return s.emit("session.start",{sessionId:a.sessionId,version:1,producer:"copilot-agent",copilotVersion:this.copilotVersion,startTime:I.toISOString(),selectedModel:a.selectedModel}),s.emit("session.import_legacy",{legacySession:{sessionId:a.sessionId,startTime:I,chatMessages:a.chatMessages,timeline:a.timeline,selectedModel:a.selectedModel},importTime:new Date().toISOString(),sourceFile:r}),this.logger.info(`Loaded legacy session ${e} from ${r}`),{session:s,legacySourceFile:bme.path(r.replace(/\.json$/,""))}}async listSessions(){let e=await GO.directoryFilesWithMetadata(),l=await bme.directoryFilesWithMetadata(),n=await Promise.all(e.map(async I=>({sessionId:I.file.replace(".jsonl",""),startTime:I.birthtime,modifiedTime:I.mtime}))),r=(await Promise.all(l.map(async I=>{let s=I.file.match(/^session_(.+)_(\d+)\.json$/);return s?{sessionId:s[1],startTime:I.birthtime,modifiedTime:I.mtime}:null}))).filter(I=>I!==null);this.logger.debug(`Found ${n.length} JSONL sessions and ${r.length} legacy sessions`);let a=new Map;for(let I of r)a.set(I.sessionId,I);for(let I of n)a.set(I.sessionId,I);return Array.from(a.values()).sort((I,s)=>s.modifiedTime.getTime()-I.modifiedTime.getTime())}async getLastSession(){let e=await this.listSessions();if(e.length===0)return;e.sort((n,r)=>r.modifiedTime.getTime()-n.modifiedTime.getTime());let l=e[0].sessionId;return await this.getSession(l)}async deleteSession(e){await this.closeSession(e);let l=GO.path(e.sessionId);this.logger.info(`Deleting session file ${l}`),await Gjt(l)}async closeSession(e){this.logger.info(`Closing session ${e.sessionId}`);let l=this.sessionWriters[e.sessionId];l&&(await l.flush(),l.dispose(),delete this.sessionWriters[e.sessionId])}getSessionsDirectory(){return I4n(GO.home(),GO.directory())}setLogger(e){this.logger=e}};function _c(t){return t()}var Gme;function o4n(t,e){return t.includes("\x1B[?")&&t.includes(e)}async function i4n(t){let e=process.stdin.isRaw;e||process.stdin.setRawMode(!0);try{return await t()}finally{e||process.stdin.setRawMode(!1)}}function pjt(t,e,l){return new Promise(n=>{let r="",a,I=()=>{a=void 0,process.stdin.removeListener("data",s),n(!1)},s=o=>{a!==void 0&&(r+=o.toString(),o4n(r,e)&&(process.stdin.removeListener("data",s),clearTimeout(a),a=void 0,n(!0)))};process.stdin.on("data",s),process.stdout.write("\x1B["+t),a=setTimeout(I,l)})}async function c4n(){return!(!(process.stdin.isTTY&&process.stdout.isTTY)||!await pjt("?u","u",200)||!await pjt("c","c",1e3))}async function Ajt(){Gme===void 0&&(Gme=await i4n(c4n),Gme===!0&&(d4n(),process.on("exit",hjt),process.on("SIGTERM",hjt)))}function d4n(){process.stdout.write("\x1B[>1u")}function hjt(){process.stdout.write("\x1B[<u"),Gme=void 0}function IQe(){return Gme===!0}function hme(t,e=!1){let l=t.length,n=0,r="",a=0,I=16,s=0,o=0,c=0,d=0,m=0;function G(v,X){let S=0,O=0;for(;S<v||!X;){let T=t.charCodeAt(n);if(T>=48&&T<=57)O=O*16+T-48;else if(T>=65&&T<=70)O=O*16+T-65+10;else if(T>=97&&T<=102)O=O*16+T-97+10;else break;n++,S++}return S<v&&(O=-1),O}function p(v){n=v,r="",a=0,I=16,m=0}function A(){let v=n;if(t.charCodeAt(n)===48)n++;else for(n++;n<t.length&&Hq(t.charCodeAt(n));)n++;if(n<t.length&&t.charCodeAt(n)===46)if(n++,n<t.length&&Hq(t.charCodeAt(n)))for(n++;n<t.length&&Hq(t.charCodeAt(n));)n++;else return m=3,t.substring(v,n);let X=n;if(n<t.length&&(t.charCodeAt(n)===69||t.charCodeAt(n)===101))if(n++,(n<t.length&&t.charCodeAt(n)===43||t.charCodeAt(n)===45)&&n++,n<t.length&&Hq(t.charCodeAt(n))){for(n++;n<t.length&&Hq(t.charCodeAt(n));)n++;X=n}else m=3;return t.substring(v,X)}function Z(){let v="",X=n;for(;;){if(n>=l){v+=t.substring(X,n),m=2;break}let S=t.charCodeAt(n);if(S===34){v+=t.substring(X,n),n++;break}if(S===92){if(v+=t.substring(X,n),n++,n>=l){m=2;break}switch(t.charCodeAt(n++)){case 34:v+='"';break;case 92:v+="\\";break;case 47:v+="/";break;case 98:v+="\b";break;case 102:v+="\f";break;case 110:v+=`
|
|
2046
|
+
`),n={};for(let r of l){let a=r.split(/\s+/);if(a.length>=3){let I=a[0],s=a[1],o=a[2].replace(/[()]/g,"");n[I]||(n[I]={Name:I,FetchURL:"",PushURL:""}),o==="fetch"?n[I].FetchURL=s:o==="push"&&(n[I].PushURL=s)}}return Object.values(n)}async function wPt(t){try{let{stdout:e}=await Ime("git",["status","--porcelain"],{cwd:t,encoding:"utf8",timeout:5e3,maxBuffer:1048576});return e.trim().length>0}catch{return!1}}async function QPt(t){try{let{stdout:e}=await Ime("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:t,encoding:"utf8",timeout:5e3,maxBuffer:1048576}),l=e.trim();if(l==="HEAD"){let{stdout:n}=await Ime("git",["rev-parse","--short","HEAD"],{cwd:t,encoding:"utf8",timeout:5e3,maxBuffer:1048576}),r=n.trim();return r?`detached@${r}`:null}return l||null}catch{return null}}var ajt=$e(rjt(),1);async function t5n(t={}){let e=await _gt();return Pgt((0,ajt.default)({},e,t))}async function ume(t={}){if(uD())throw new Error("Settings have already been initialized");return t5n(t)}import{promises as l5n}from"fs";import Ijt from"path";var n5n=3*1024*1024;function sjt(t){let e=Ijt.extname(t).toLowerCase();return[".png",".jpg",".jpeg",".gif",".webp"].includes(e)}function r5n(t){switch(Ijt.extname(t).toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";default:return null}}async function a5n(t,e){e.debug(`Processing local image file: ${t}`);let l=await l5n.readFile(t),n=r5n(t);if(!n)throw new Error(`Unsupported image format: ${t}`);let r=new roe,a=await c0e(e,r,n5n,toe,n,l);if(!a)throw new Error(`Image too large or couldn't be processed: ${t}`);let I=a.toString("base64");return`data:${n};base64,${I}`}async function I5n(t,e,l){let n=cu();try{let r=await hBe({command:"view",path:t,view_range:void 0},{properties:{command:"view",resolvedPathAgainstCwd:"false",options:"{}",inputs:"[]"},metrics:{responseTokenLimit:void 0,resultLength:0,resultForLlmLength:0},restrictedProperties:{}},e,l);return{id:n,name:"view",arguments:{path:t},result:r.textResultForLlm||""}}catch(r){return{id:n,name:"view",arguments:{path:t},result:`Error reading ${t}: ${r}`}}}async function ojt(t,e,l){let n=[],r=t.filter(I=>!sjt(I.path));if(r.length===0)return n;let a=[];for(let I of r)try{let s=await I5n(I.path,e,l);a.push(s)}catch{}if(a.length>0){let I=a.map(s=>({id:s.id,type:"function",function:{name:s.name,arguments:JSON.stringify(s.arguments)}}));n.push({role:"assistant",content:"I need to read the content of those paths to answer this request.",tool_calls:I}),n.push(...a.map(s=>({role:"tool",tool_call_id:s.id,content:s.result})))}return n}async function ijt(t,e){let l=t.filter(r=>sjt(r.path));return(await Promise.all(l.map(async r=>{try{return{type:"image_url",image_url:{url:await a5n(r.path,e)}}}catch(a){e.error(`Failed to process image ${r.path}: ${a instanceof Error?a.message:String(a)}`);return}}))).filter(r=>r!==void 0)}var c7e=class{constructor(e,l){this.logger=e;this.session=l}messageQueue=[];async*preRequest(e){this.logger.debug("ImmediatePromptProcessor: Injecting immediate prompts");let n=(await this.session.getChatMessages()).length;for(;this.messageQueue.length>0;){let I=this.messageQueue.shift();this.session.emit("user.message",{content:I.prompt,attachments:I.attachments})}let a=(await this.session.getChatMessages()).slice(n);for(let I of a)e.messages.push(I),yield{kind:"message",message:I,turn:e.turn,source:"immediate-prompt"}}addMessage(e){this.messageQueue.push(e)}toJSON(){return"ImmediatePromptProcessor"}},Ff=class t{sessionId;startTime;modifiedTime;logger;events=[];_chatMessages=[];_selectedModel;eventProcessingQueue=Promise.resolve();eventHandlers={};wildcardEventHandlers=[];isProcessing=!1;messageQueue=[];immediatePromptProcessor;mcpHost;workingDir;abortController;modelProvider;allowedTools;disabledTools;requestPermission;mcpServers;hooks;hmacKey;copilotToken;constructor(e={},l={}){this.sessionId=l.sessionId||cu(),this.startTime=l.startTime||new Date,this.modifiedTime=l.modifiedTime||this.startTime,this.logger=e.logger||new xd,this.modelProvider=e.modelProvider,this.allowedTools=e.allowedTools,this.disabledTools=e.disabledTools,this.requestPermission=e.requestPermission,this.mcpServers=e.mcpServers,this.hooks=e.hooks,this.hmacKey=e.hmacKey,this.copilotToken=e.copilotToken,this.workingDir=e.workingDirectory||process.cwd(),this.immediatePromptProcessor=new c7e(this.logger,this),this.abortController=e.abortController||new AbortController,mY(this.workingDir).then(n=>{if(n.found)return vEe(n.gitRoot,!0,this.workingDir)}).catch(n=>{this.logger.debug(`Failed to initialize custom instructions cache: ${n}`)})}get messageCount(){let e=this.events.find(n=>n.type==="session.import_legacy"),l=0;return e&&(l=(e.data.legacySession?.chatMessages||[]).filter(a=>a.role==="user"||a.role==="assistant").length),this.logger.debug(`Imported message count: ${l}`),this.events.filter(n=>n.type==="user.message"||n.type==="assistant.message").length+l}get summary(){let e=this.events.find(a=>a.type==="session.import_legacy"||a.type==="user.message"),l;if(e?.type==="session.import_legacy"){let a=e.data.legacySession.chatMessages.find(I=>I.role==="user");a?.content&&(typeof a.content=="string"?l=a.content:l=a.content.find(I=>I.type==="text")?.text)}else e?.type==="user.message"&&(l=e.data.content);if(!l)return;let n=l.lastIndexOf("<reminder>");n!==-1&&(l=l.substring(0,n).trim());let r=l.replace(/\s+/g," ").trim();return r.length>75&&(r=r.substring(0,55).trim()+"..."),r=r.split("").filter(a=>{let I=a.charCodeAt(0);return I>=32&&I!==127}).join(""),r}static async fromEvents(e,l={}){if(e.length===0)throw new Error("Cannot create session from empty events array");let n=e[0];if(n.type!=="session.start")throw new Error("First event must be session.start");let r=new t(l,{sessionId:n.data.sessionId,startTime:new Date(n.data.startTime)});r._selectedModel=n.data.selectedModel,r.events.push(n);for(let a=1;a<e.length;a++){let I=e[a];r.events.push(I),await r.processEventForState(I)}return r}on(e,l){return e==="*"?(this.wildcardEventHandlers.push(l),()=>{let n=this.wildcardEventHandlers.indexOf(l);n!==-1&&this.wildcardEventHandlers.splice(n,1)}):(this.eventHandlers[e]||(this.eventHandlers[e]=[]),this.eventHandlers[e].push(l),()=>{let n=this.eventHandlers[e];if(n){let r=n.indexOf(l);r!==-1&&n.splice(r,1)}})}emitInternal(e,l,n=!1){let r=cu(),a=new Date().toISOString(),I=this.getLastEventId(),s={type:e,data:l,id:r,timestamp:a,parentId:I,...n&&{ephemeral:n}};this.events.push(s),this.enqueueEventProcessing(()=>this.processEventForState(s)).catch(o=>{this.logger.error(`Error emitting event: ${o instanceof Error?o.message:String(o)}`)}).catch(o=>{this.logger.error(`Error emitting event ${o instanceof Error?o.message:String(o)}`)}),[...this.eventHandlers[s.type]||[],...this.wildcardEventHandlers].forEach(o=>{try{o(s)}catch(c){this.logger.error(`Error in event handler for event type ${s.type}: ${c instanceof Error?c.message:String(c)}`)}})}emit(e,l){this.emitInternal(e,l)}emitEphemeral(e,l){this.emitInternal(e,l,!0)}getEvents(){return this.events}async getChatMessages(){return this.enqueueEventProcessing(()=>this._chatMessages)}async getChatContextMessages(){return(await this.getChatMessages()).filter(l=>l.role!=="system")}async getSystemContextMessages(){return(await this.getChatMessages()).filter(l=>l.role==="system")}async getSelectedModel(){return this.enqueueEventProcessing(()=>this._selectedModel)}async setSelectedModel(e){let l=await this.getSelectedModel();this.emit("session.model_change",{previousModel:l,newModel:e})}getLastEventId(){return this.events.length===0?null:this.events[this.events.length-1].id}enqueueEventProcessing(e){let l=this.eventProcessingQueue.then(()=>e());return this.eventProcessingQueue=l,l}async processEventForState(e){switch(e.type){case"session.start":e.data.selectedModel&&(this._selectedModel=e.data.selectedModel);break;case"session.model_change":this._selectedModel=e.data.newModel;break;case"user.message":{let l=[],n=[];if(e.data.attachments&&e.data.attachments.length>0){let r=await ijt(e.data.attachments,this.logger);l.push(...r);let a=await ojt(e.data.attachments,{requestRequired:!1},this.logger);n.push(...a)}l.length>0?this._chatMessages.push({role:"user",content:[{type:"text",text:e.data.content},...l]}):this._chatMessages.push({role:"user",content:e.data.content}),n.length>0&&this._chatMessages.push(...n);break}case"assistant.message":{if(e.ephemeral||e.data.parentToolCallId)break;let l={role:"assistant",content:e.data.content||null};e.data.toolRequests&&e.data.toolRequests.length>0&&(l.tool_calls=e.data.toolRequests.map(n=>({id:n.toolCallId,type:"function",function:{name:n.name,arguments:typeof n.arguments=="string"?n.arguments:JSON.stringify(n.arguments)}}))),this._chatMessages.push(l);break}case"tool.execution_complete":{if(e.data.parentToolCallId)break;e.data.isUserRequested||this._chatMessages.push({role:"tool",tool_call_id:e.data.toolCallId,content:e.data.success?e.data.result?.content||"":e.data.error?.message||"Tool execution failed"});break}case"system.message":this._chatMessages.push({role:e.data.role,content:e.data.content,...e.data.name&&{name:e.data.name}});break;case"session.import_legacy":this._chatMessages=[...e.data.legacySession.chatMessages],e.data.legacySession.selectedModel&&(this._selectedModel=e.data.legacySession.selectedModel);break;case"abort":case"session.resume":this._chatMessages=s5n(this._chatMessages,this.logger);break;case"session.idle":case"session.error":case"session.info":case"assistant.turn_start":case"assistant.turn_end":case"assistant.usage":case"tool.user_requested":case"tool.execution_start":case"tool.execution_partial_result":case"hook.start":case"hook.end":break;default:{let l=e;this.logger.error(`Unknown event type: ${l.type}`);break}}}async send(e,l={}){if((l.mode||"enqueue")==="immediate"&&this.isProcessing)this.immediatePromptProcessor.addMessage(e);else{if(this.messageQueue.push(e),this.isProcessing)return;for(this.isProcessing=!0,await this.initializeMcpHost();this.messageQueue.length>0;){let r=this.messageQueue.shift();await this.runAgenticLoop(r.prompt,r.attachments)}this.isProcessing=!1,this.emitEphemeral("session.idle",{})}}async abort(){this.abortController.abort()}async initializeMcpHost(){if(!this.mcpHost&&this.mcpServers&&Object.keys(this.mcpServers).length>0)try{this.mcpHost=new XL(this.logger,{mcpServers:this.mcpServers},this.disabledTools),await this.mcpHost.startServers()}catch(e){this.logger.error(`Failed to initialize MCP host: ${e}`)}}async runAgenticLoop(e,l=[]){if(!this.modelProvider)throw new Error("Session must be created with modelProvider to use send/query methods");let n=new Map,r=new Map;try{let I=(await BL(this.hooks?.userPromptSubmitted,{timestamp:Date.now(),cwd:this.workingDir,prompt:e},this.logger))?.modifiedPrompt??e;this.emit("user.message",{content:Q6({problemStatement:I,capabilities:{}}),attachments:l});let o=new DX().setProblemStatement(I).setAgentModel(this.buildAgentModelString()).setGithubRepoName("copilot-sdk-session").setGithubRepoCommit("copilot-sdk-commit").setGithubRepoReadWrite(!1).setCopilotIntegrationId("copilot-developer-cli").setCopilotHmacKey(this.hmacKey).setCopilotToken(this.copilotToken).build();wx();let c=await ume(o),d=c.service?.agent?.model,m=kB(d),G=m.agent,p=G??"sweagent-capi",A=m.model?{model:m.model}:void 0,Z=Mde(c,this.logger,G,A),W={location:this.workingDir,timeout:3e4,requireReasoning:!0,toolPartialResultCallback:(re,se)=>{this.emitEphemeral("tool.execution_partial_result",{toolCallId:re,partialOutput:se})},permissions:this.requestPermission?{requestRequired:!0,request:this.requestPermission}:{requestRequired:!1},shellConfig:(process.platform==="win32"?bp.powerShell:bp.bash).withScriptSafetyAssessor(async function(re){return{result:"completed",commands:[{identifier:re,readOnly:!1}],possiblePaths:[],hasWriteFileRedirection:!1,canOfferSessionApproval:!1}})},R=await K1e(W,this.logger),V=[];if(this.mcpHost)try{V=await this.mcpHost.getTools(c,this.logger,W.permissions)}catch(re){this.logger.error(`Failed to get MCP tools: ${re}`)}let v=[...R,...V].filter(re=>this.allowedTools?this.allowedTools.includes(re.name):this.disabledTools?!this.disabledTools.includes(re.name):!0),X=await mY(this.workingDir),O={...(U8()[p]?.[Z.model]??O8()).supports,reasoning:!0},T=await w6({location:X.found?X.gitRoot:"",version:mL(),currentWorkingDirectory:this.workingDir,parts:{},capabilities:O,toolConfigOverrides:W,tools:v,organizationCustomInstructions:void 0}),D=(await this.getChatMessages()).slice(0,-1),Ge={role:"user",content:Q6({customAgentPrompt:void 0,problemStatement:I,capabilities:O})},ge=[...D,Ge];await BL(this.hooks?.sessionStart,{timestamp:Date.now(),cwd:this.workingDir,source:"new",initialPrompt:e},this.logger);let K=new K4(Ge,this.logger),U=Z.getCompletionWithTools(T,ge,v,{failIfInitialInputsTooLong:!1,processors:{preRequest:[K,this.immediatePromptProcessor,new YT(this.logger)],onRequestError:[K]},executeToolsInParallel:!1,abortSignal:this.abortController.signal});for await(let re of U){if(this.abortController.signal.aborted){this.emit("abort",{reason:"user initiated"});break}switch(re.kind){case"message":{if(pL(re)){let se=T8(re)?await Promise.all(re.message.tool_calls.map(async We=>{let me=tL(We.function.arguments);n.set(We.id,We.function.name),r.set(We.id,me);let ve=await BL(this.hooks?.preToolUse,{timestamp:Date.now(),cwd:this.workingDir,toolName:We.function.name,toolArgs:me},this.logger);return{toolCallId:We.id,name:We.function.name,arguments:ve?.modifiedArgs??me}})):[];this.emit("assistant.message",{parentToolCallId:void 0,messageId:cu(),content:typeof re.message.content=="string"?re.message.content:"",toolRequests:se});for(let We of se)this.emit("tool.execution_start",{toolCallId:We.toolCallId,toolName:We.name,arguments:We.arguments})}else(re.message.role==="system"||re.message.role==="developer")&&this.emit("system.message",{role:re.message.role,content:typeof re.message.content=="string"?re.message.content:JSON.stringify(re.message.content),name:"name"in re.message?re.message.name:void 0});break}case"model_call_failure":{let se=new Error(re.modelCall?.error||"Model call failed");await BL(this.hooks?.errorOccurred,{timestamp:Date.now(),cwd:this.workingDir,error:se,errorContext:"model_call",recoverable:!0},this.logger),this.emit("session.error",{errorType:"model_call",message:se.message,stack:se.stack});break}case"tool_execution":{let We=(await BL(this.hooks?.postToolUse,{timestamp:Date.now(),cwd:this.workingDir,toolName:n.get(re.toolCallId)||"unknown",toolArgs:r.get(re.toolCallId)||{},toolResult:re.toolResult},this.logger))?.modifiedResult??re.toolResult,me=(We.resultType==="failure"?We.error:void 0)||We.sessionLog||We.textResultForLlm;this.emit("tool.execution_complete",{parentToolCallId:void 0,toolCallId:re.toolCallId,success:We.resultType==="success",result:We.resultType==="success"?{content:me}:void 0,error:We.resultType!=="success"?{message:me,code:We.resultType}:void 0});break}case"turn_started":{this.emit("assistant.turn_start",{turnId:`${re.turn}`});break}case"turn_ended":{this.emit("assistant.turn_end",{turnId:`${re.turn}`});break}case"response":case"images_removed":case"image_processing":case"history_truncated":case"turn_failed":case"turn_retry":case"model_call_success":this.logger.debug(`Ignoring event of kind: ${re.kind}`);break;default:wo(re,"Unhandled event type")}}}catch(a){await BL(this.hooks?.sessionEnd,{timestamp:Date.now(),cwd:this.workingDir,reason:"error",error:a instanceof Error?a:new Error(String(a))},this.logger),this.emit("session.error",{errorType:"query",message:a instanceof Error?a.message:String(a),stack:a instanceof Error?a.stack:void 0})}finally{await BL(this.hooks?.sessionEnd,{timestamp:Date.now(),cwd:this.workingDir,reason:"complete"},this.logger)}}buildAgentModelString(){if(!this.modelProvider)throw new Error("Session must be created with modelProvider");switch(this.modelProvider.type){case"openai":return`openai:${this.modelProvider.model}`;case"anthropic":return`anthropic:${this.modelProvider.model}`;case"copilot":return`capi:${this.modelProvider.model}`;default:throw new Error(`Unsupported provider: ${this.modelProvider.type}`)}}};function s5n(t,e){if(t.length===0)return t;let l=[],n=new Set,r=!1;for(let s=t.length-1;s>=0;s--){let o=t[s];if(o.role==="assistant"&&(r=!0),o.role==="assistant"&&"tool_calls"in o&&o.tool_calls&&o.tool_calls.length>0)for(let c of o.tool_calls)n.has(c.id)||l.push(c.id);else{if(r)break;o.role==="tool"&&o.tool_call_id&&n.add(o.tool_call_id)}}if(l.length===0)return t;let a="The execution of this tool, or a previous tool was interrupted.";e.info(`Completing ${l.length} orphaned tool calls.`);let I=l.map(s=>({role:"tool",tool_call_id:s,content:a}));return[...t,...I]}var nQe=class{sessions;logger;options;lastAccessedSessionId;constructor(e){this.options=e,this.sessions=new Map,this.logger=e.logger||new xd}async createSession(){let e=new Ff(this.options);return this.sessions.set(e.sessionId,e),this.lastAccessedSessionId=e.sessionId,e}async getSession(e){let l=this.sessions.get(e);return l&&(this.lastAccessedSessionId=e),l}async getLastSession(){if(this.lastAccessedSessionId){let n=this.sessions.get(this.lastAccessedSessionId);if(n)return n}let e=Array.from(this.sessions.values());if(e.length===0)return;e.sort((n,r)=>r.startTime.getTime()-n.startTime.getTime());let l=e[0];return this.lastAccessedSessionId=l.sessionId,l}async listSessions(){return Array.from(this.sessions.values()).map(e=>({sessionId:e.sessionId,startTime:e.startTime,modifiedTime:e.modifiedTime}))}async saveSession(e){}async deleteSession(e){this.sessions.delete(e.sessionId),this.lastAccessedSessionId===e.sessionId&&(this.lastAccessedSessionId=void 0)}async closeSession(e){}};var fq=zl({command:Qt(),description:Qt(),timeout:LG().optional(),sessionId:Qt().optional(),async:ro().optional()}),d7e=zl({sessionId:Qt(),input:Qt(),delay:LG().optional()}),u7e=zl({sessionId:Qt(),delay:LG()}),m7e=zl({sessionId:Qt()}),cjt=Oh([fq,d7e,u7e,m7e]),o5n=zl({command:pr("view"),path:Qt(),view_range:nVe([LG(),LG()]).optional()}),i5n=zl({command:pr("create"),path:Qt(),file_text:Qt()}),c5n=zl({command:pr("str_replace"),path:Qt(),new_str:Qt().optional(),old_str:Qt()}),d5n=zl({command:pr("insert"),path:Qt(),insert_line:LG(),new_str:Qt()}),b7e=Kde("command",[o5n,i5n,c5n,d5n]),G7e=zl({path:Qt(),view_range:nVe([LG(),LG()]).optional()}),p7e=zl({path:Qt(),file_text:Qt()}),h7e=zl({path:Qt(),old_str:Qt(),new_str:Qt().optional()}),A7e=Oh([cjt,b7e,Sw()]),djt=(t,e)=>{switch(t.type){case"copilot":return e.onCopilot(t);case"tool_call_requested":return e.onToolCallRequested(t);case"tool_call_completed":return e.onToolCallCompleted(t);default:wo(t,"Unknown groupable timeline entry type")}};function ujt(t,e){switch(t.type){case"copilot":return e.onCopilot(t);case"error":return e.onError(t);case"group_tool_call_requested":return e.onGroupToolCallRequested(t);case"group_tool_call_completed":return e.onGroupToolCallCompleted(t);case"info":return e.onInfo(t);case"tool_call_requested":return e.onToolCallRequested(t);case"tool_call_completed":return e.onToolCallCompleted(t);case"user":return e.onUser(t);default:wo(t,"Unknown timeline entry type")}}var bO=class t extends Error{prUrl;timeoutContext;constructor(e,l,n){super(e),this.name="JobStatusTimeoutError",this.timeoutContext=l,this.prUrl=n,Error.captureStackTrace&&Error.captureStackTrace(this,t)}};var mme=zl({type:pr("text"),text:Qt()}),u5n=zl({type:pr("refusal"),refusal:Qt()}),m5n=zl({type:pr("image_url"),image_url:zl({url:Qt(),detail:G0(["auto","low","high"]).optional()})}),b5n=zl({type:pr("input_audio"),input_audio:zl({data:Qt(),format:pr("wav").or(pr("mp3"))})}),G5n=zl({type:pr("file"),file:zl({file_date:Qt().optional(),file_id:Qt().optional(),filename:Qt().optional()})}),p5n=Oh([mme,m5n,b5n,G5n]),h5n=zl({name:Qt(),arguments:Qt()}),A5n=zl({name:Qt(),input:Qt()}),g5n=zl({id:Qt(),type:pr("function"),function:h5n}),Z5n=zl({id:Qt(),type:pr("custom"),custom:A5n}),N5n=Oh([g5n,Z5n]),W5n=zl({name:Qt(),arguments:Qt()}),y5n=zl({id:Qt()}),E5n=zl({content:Oh([Qt(),Od(mme)]),role:pr("developer"),name:Qt().optional()}),R5n=zl({content:Oh([Qt(),Od(mme)]),role:pr("system"),name:Qt().optional()}),Y5n=zl({content:Oh([Qt(),Od(p5n)]),role:pr("user"),name:Qt().optional()}),V5n=zl({content:Oh([Qt(),Od(Oh([mme,u5n]))]).nullable().optional(),role:pr("assistant"),name:Qt().optional(),refusal:Qt().nullable().optional(),audio:y5n.nullable().optional(),function_call:W5n.nullable().optional(),tool_calls:Od(N5n).optional()}),w5n=zl({content:Oh([Qt(),Od(mme)]),role:pr("tool"),tool_call_id:Qt()}),Q5n=zl({content:Qt().nullable(),role:pr("function"),name:Qt()}),F5n=Oh([E5n,R5n,Y5n,V5n,w5n,Q5n]),C5n=zl({type:pr("copilot"),text:Qt(),isStreaming:ro().optional()}),v5n=zl({type:pr("error"),text:Qt()}),f5n=zl({type:pr("info"),text:Qt()}),H5n=zl({type:pr("user"),text:Qt()}),X5n=zl({type:pr("tool_call_requested"),callId:Qt(),name:Qt(),toolTitle:Qt().optional(),intentionSummary:Qt().nullable(),arguments:A7e,partialOutput:Qt().optional(),isHidden:ro().optional(),isAlwaysExpanded:ro().optional(),showNoContent:ro().optional()}),k5n=zl({type:pr("tool_call_completed"),callId:Qt(),name:Qt(),toolTitle:Qt().optional(),intentionSummary:Qt().nullable(),result:Oh([zl({type:pr("success"),log:Qt(),markdown:ro().optional()}),zl({type:pr("failure"),log:Qt(),markdown:ro().optional()}),zl({type:pr("rejected"),markdown:ro().optional()}),zl({type:pr("denied"),log:Qt(),markdown:ro().optional()})]),arguments:A7e,isHidden:ro().optional(),isAlwaysExpanded:ro().optional(),showNoContent:ro().optional()}),L5n=Oh([C5n,v5n,f5n,H5n,X5n,k5n]),J5n=L5n.and(zl({id:Qt(),timestamp:rVe.date()})),g7e=zl({sessionId:Qt(),startTime:rVe.date(),chatMessages:Od(F5n),timeline:Od(J5n),selectedModel:G0(Ef).optional()}),bme=xwe(g7e.parse,"history-session");var jm=zl({id:Qt().uuid(),timestamp:Qt().datetime(),parentId:Qt().uuid().nullable(),ephemeral:ro().optional()}),mjt=zl({parentToolCallId:Qt().optional()}),x5n=jm.extend({type:pr("session.start"),data:zl({sessionId:Qt(),version:LG(),producer:Qt(),copilotVersion:Qt(),startTime:Qt().datetime(),selectedModel:Qt().optional()})}),S5n=jm.extend({type:pr("session.resume"),data:zl({resumeTime:Qt().datetime(),eventCount:LG()})}),B5n=jm.extend({type:pr("session.error"),data:zl({errorType:Qt(),message:Qt(),stack:Qt().optional()})}),T5n=jm.extend({type:pr("session.info"),data:zl({infoType:Qt(),message:Qt()})}),O5n=jm.extend({type:pr("session.model_change"),data:zl({previousModel:Qt().optional(),newModel:Qt()})}),U5n=jm.extend({type:pr("session.import_legacy"),data:zl({legacySession:g7e,importTime:Qt().datetime(),sourceFile:Qt()})}),M5n=jm.extend({type:pr("session.idle"),ephemeral:pr(!0),data:zl({})}),_5n=zl({type:G0(["file","directory"]),path:Qt(),displayName:Qt()}),D5n=jm.extend({type:pr("user.message"),data:zl({content:Qt(),attachments:Od(_5n).optional()})}),z5n=jm.extend({type:pr("assistant.turn_start"),data:zl({turnId:Qt()})}),P5n=jm.extend({type:pr("assistant.message"),data:zl({messageId:Qt(),content:Qt(),toolRequests:Od(zl({toolCallId:Qt(),name:Qt(),arguments:Sw()})).optional()}).merge(mjt)}),j5n=jm.extend({type:pr("assistant.turn_end"),data:zl({turnId:Qt()})}),K5n=jm.extend({type:pr("assistant.usage"),ephemeral:pr(!0),data:zl({model:Qt().optional(),inputTokens:LG().optional(),outputTokens:LG().optional(),cost:LG().optional(),duration:LG().optional(),initiator:Qt().optional()})}),q5n=jm.extend({type:pr("abort"),data:zl({reason:Qt()})}),$5n=jm.extend({type:pr("tool.user_requested"),data:zl({toolCallId:Qt(),toolName:Qt(),arguments:Sw()})}),e4n=jm.extend({type:pr("tool.execution_start"),data:zl({toolCallId:Qt(),toolName:Qt(),arguments:Sw()})}),t4n=jm.extend({type:pr("tool.execution_partial_result"),ephemeral:pr(!0),data:zl({toolCallId:Qt(),partialOutput:Qt()})}),l4n=jm.extend({type:pr("tool.execution_complete"),data:zl({toolCallId:Qt(),success:ro(),isUserRequested:ro().optional(),result:zl({content:Qt()}).optional(),error:zl({message:Qt(),code:Qt().optional()}).optional()}).merge(mjt)}),n4n=jm.extend({type:pr("hook.start"),data:zl({hookInvocationId:Qt(),hookType:Qt(),input:Sw()})}),r4n=jm.extend({type:pr("hook.end"),data:zl({hookInvocationId:Qt(),hookType:Qt(),output:Sw(),success:ro(),error:zl({message:Qt(),stack:Qt().optional()}).optional()})}),a4n=jm.extend({type:pr("system.message"),data:zl({content:Qt(),role:G0(["system","developer"]),name:Qt().optional(),metadata:zl({promptVersion:Qt().optional(),variables:rY(Sw()).optional()}).optional()})}),bjt=Kde("type",[x5n,S5n,B5n,M5n,T5n,O5n,U5n,D5n,z5n,P5n,j5n,K5n,q5n,$5n,e4n,t4n,l4n,n4n,r4n,a4n]);var GO=$zt(bjt.parse,"session");var rQe=class{constructor(e,l,n,r=!1,a){this.session=e;this.logger=l;this.flushDebounceMs=n;this.shouldSaveSession=r;this.legacySourceFile=a;this.unsubscribe=this.session.on("*",I=>{I.ephemeral||(this.unflushedEvents.push(I),!this.shouldSaveSession&&I.type==="user.message"&&(this.shouldSaveSession=!0),I.type!=="session.resume"&&this.shouldSaveSession&&(this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=setTimeout(()=>{this.flush().catch(s=>{this.logger.error(`Error flushing session ${this.session.sessionId}: ${s instanceof Error?s.message:String(s)}`)})},this.flushDebounceMs)))})}flushTimer=null;unflushedEvents=[];migratedLegacy=!1;isFlushing=!1;needsFlushAfterCurrent=!1;unsubscribe;dispose(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.unsubscribe()}async flush(){if(!this.shouldSaveSession||this.unflushedEvents.length===0)return;if(this.isFlushing){this.needsFlushAfterCurrent=!0;return}this.isFlushing=!0,this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null);let e=this.unflushedEvents;this.unflushedEvents=[];try{if(await GO.append(e,this.session.sessionId),this.logger.debug(`Flushed ${e.length} events to session ${this.session.sessionId}`),this.legacySourceFile&&!this.migratedLegacy){this.logger.debug(`Migrated legacy session ${this.session.sessionId} from ${this.legacySourceFile}`);try{await Gjt(this.legacySourceFile)}catch(l){this.logger.error(`Failed to delete legacy session file ${this.legacySourceFile}: ${l}`)}this.migratedLegacy=!0}}catch(l){this.logger.error(`Failed to flush events for ${this.session.sessionId}: ${l instanceof Error?l.message:String(l)}`),this.unflushedEvents.unshift(...e)}finally{this.isFlushing=!1,this.needsFlushAfterCurrent&&(this.needsFlushAfterCurrent=!1,await this.flush())}}},aQe=class extends nQe{sessionWriters={};copilotVersion;flushDebounceMs;constructor({version:e,flushDebounceMs:l,...n}){super({...n}),this.copilotVersion=e||"unknown",this.flushDebounceMs=l||100}async createSession(e){let l=e?.sessionId??cu(),n=new Date,r=new Ff(this.options,{sessionId:l,startTime:n});return this.sessionWriters[l]=new rQe(r,this.logger,this.flushDebounceMs),r.emit("session.start",{sessionId:l,version:1,producer:"copilot-agent",copilotVersion:this.copilotVersion,startTime:n.toISOString(),selectedModel:e?.selectedModel}),r}async getSession(e,l=!0){let n,r;try{n=await this.loadSession(e)}catch{try{let a=await this.loadLegacySession(e);n=a.session,r=a.legacySourceFile}catch{return}}return this.sessionWriters[e]||(this.sessionWriters[e]=new rQe(n,this.logger,this.flushDebounceMs,!0,r)),l&&n.emit("session.resume",{resumeTime:new Date().toISOString(),eventCount:n.getEvents().length}),n}async saveSession(e){await this.sessionWriters[e.sessionId]?.flush()}async loadSession(e){let l=await GO.load(e);return await Ff.fromEvents(l,this.options)}async loadLegacySession(e){let n=(await bme.directoryFiles()).filter(o=>{let c=o.match(/^session_(.+)_(\d+)\.json$/);return c&&c[1]===e});if(n.length===0)throw new Error(`Legacy session ${e} not found`);let r=n[0];n.length>1&&this.logger.info(`Multiple legacy sessions found for ${e}, using newest`);let a=await bme.load(r);if(!a)throw new Error(`Failed to load legacy session from ${r}`);let I=new Date(a.startTime),s=new Ff(this.options,{sessionId:a.sessionId,startTime:I});return s.emit("session.start",{sessionId:a.sessionId,version:1,producer:"copilot-agent",copilotVersion:this.copilotVersion,startTime:I.toISOString(),selectedModel:a.selectedModel}),s.emit("session.import_legacy",{legacySession:{sessionId:a.sessionId,startTime:I,chatMessages:a.chatMessages,timeline:a.timeline,selectedModel:a.selectedModel},importTime:new Date().toISOString(),sourceFile:r}),this.logger.info(`Loaded legacy session ${e} from ${r}`),{session:s,legacySourceFile:bme.path(r.replace(/\.json$/,""))}}async listSessions(){let e=await GO.directoryFilesWithMetadata(),l=await bme.directoryFilesWithMetadata(),n=await Promise.all(e.map(async I=>({sessionId:I.file.replace(".jsonl",""),startTime:I.birthtime,modifiedTime:I.mtime}))),r=(await Promise.all(l.map(async I=>{let s=I.file.match(/^session_(.+)_(\d+)\.json$/);return s?{sessionId:s[1],startTime:I.birthtime,modifiedTime:I.mtime}:null}))).filter(I=>I!==null);this.logger.debug(`Found ${n.length} JSONL sessions and ${r.length} legacy sessions`);let a=new Map;for(let I of r)a.set(I.sessionId,I);for(let I of n)a.set(I.sessionId,I);return Array.from(a.values()).sort((I,s)=>s.modifiedTime.getTime()-I.modifiedTime.getTime())}async getLastSession(){let e=await this.listSessions();if(e.length===0)return;e.sort((n,r)=>r.modifiedTime.getTime()-n.modifiedTime.getTime());let l=e[0].sessionId;return await this.getSession(l)}async deleteSession(e){await this.closeSession(e);let l=GO.path(e.sessionId);this.logger.info(`Deleting session file ${l}`),await Gjt(l)}async closeSession(e){this.logger.info(`Closing session ${e.sessionId}`);let l=this.sessionWriters[e.sessionId];l&&(await l.flush(),l.dispose(),delete this.sessionWriters[e.sessionId])}getSessionsDirectory(){return I4n(GO.home(),GO.directory())}setLogger(e){this.logger=e}};function _c(t){return t()}var Gme;function o4n(t,e){return t.includes("\x1B[?")&&t.includes(e)}async function i4n(t){let e=process.stdin.isRaw;e||process.stdin.setRawMode(!0);try{return await t()}finally{e||process.stdin.setRawMode(!1)}}function pjt(t,e,l){return new Promise(n=>{let r="",a,I=()=>{a=void 0,process.stdin.removeListener("data",s),n(!1)},s=o=>{a!==void 0&&(r+=o.toString(),o4n(r,e)&&(process.stdin.removeListener("data",s),clearTimeout(a),a=void 0,n(!0)))};process.stdin.on("data",s),process.stdout.write("\x1B["+t),a=setTimeout(I,l)})}async function c4n(){return!(!(process.stdin.isTTY&&process.stdout.isTTY)||!await pjt("?u","u",200)||!await pjt("c","c",1e3))}async function Ajt(){Gme===void 0&&(Gme=await i4n(c4n),Gme===!0&&(d4n(),process.on("exit",hjt),process.on("SIGTERM",hjt)))}function d4n(){process.stdout.write("\x1B[>1u")}function hjt(){process.stdout.write("\x1B[<u"),Gme=void 0}function IQe(){return Gme===!0}function hme(t,e=!1){let l=t.length,n=0,r="",a=0,I=16,s=0,o=0,c=0,d=0,m=0;function G(v,X){let S=0,O=0;for(;S<v||!X;){let T=t.charCodeAt(n);if(T>=48&&T<=57)O=O*16+T-48;else if(T>=65&&T<=70)O=O*16+T-65+10;else if(T>=97&&T<=102)O=O*16+T-97+10;else break;n++,S++}return S<v&&(O=-1),O}function p(v){n=v,r="",a=0,I=16,m=0}function A(){let v=n;if(t.charCodeAt(n)===48)n++;else for(n++;n<t.length&&Hq(t.charCodeAt(n));)n++;if(n<t.length&&t.charCodeAt(n)===46)if(n++,n<t.length&&Hq(t.charCodeAt(n)))for(n++;n<t.length&&Hq(t.charCodeAt(n));)n++;else return m=3,t.substring(v,n);let X=n;if(n<t.length&&(t.charCodeAt(n)===69||t.charCodeAt(n)===101))if(n++,(n<t.length&&t.charCodeAt(n)===43||t.charCodeAt(n)===45)&&n++,n<t.length&&Hq(t.charCodeAt(n))){for(n++;n<t.length&&Hq(t.charCodeAt(n));)n++;X=n}else m=3;return t.substring(v,X)}function Z(){let v="",X=n;for(;;){if(n>=l){v+=t.substring(X,n),m=2;break}let S=t.charCodeAt(n);if(S===34){v+=t.substring(X,n),n++;break}if(S===92){if(v+=t.substring(X,n),n++,n>=l){m=2;break}switch(t.charCodeAt(n++)){case 34:v+='"';break;case 92:v+="\\";break;case 47:v+="/";break;case 98:v+="\b";break;case 102:v+="\f";break;case 110:v+=`
|
|
2047
2047
|
`;break;case 114:v+="\r";break;case 116:v+=" ";break;case 117:let T=G(4,!0);T>=0?v+=String.fromCharCode(T):m=4;break;default:m=5}X=n;continue}if(S>=0&&S<=31)if(pme(S)){v+=t.substring(X,n),m=2;break}else m=6;n++}return v}function W(){if(r="",m=0,a=n,o=s,d=c,n>=l)return a=l,I=17;let v=t.charCodeAt(n);if(Z7e(v)){do n++,r+=String.fromCharCode(v),v=t.charCodeAt(n);while(Z7e(v));return I=15}if(pme(v))return n++,r+=String.fromCharCode(v),v===13&&t.charCodeAt(n)===10&&(n++,r+=`
|
|
2048
2048
|
`),s++,c=n,I=14;switch(v){case 123:return n++,I=1;case 125:return n++,I=2;case 91:return n++,I=3;case 93:return n++,I=4;case 58:return n++,I=6;case 44:return n++,I=5;case 34:return n++,r=Z(),I=10;case 47:let X=n-1;if(t.charCodeAt(n+1)===47){for(n+=2;n<l&&!pme(t.charCodeAt(n));)n++;return r=t.substring(X,n),I=12}if(t.charCodeAt(n+1)===42){n+=2;let S=l-1,O=!1;for(;n<S;){let T=t.charCodeAt(n);if(T===42&&t.charCodeAt(n+1)===47){n+=2,O=!0;break}n++,pme(T)&&(T===13&&t.charCodeAt(n)===10&&n++,s++,c=n)}return O||(n++,m=1),r=t.substring(X,n),I=13}return r+=String.fromCharCode(v),n++,I=16;case 45:if(r+=String.fromCharCode(v),n++,n===l||!Hq(t.charCodeAt(n)))return I=16;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return r+=A(),I=11;default:for(;n<l&&R(v);)n++,v=t.charCodeAt(n);if(a!==n){switch(r=t.substring(a,n),r){case"true":return I=8;case"false":return I=9;case"null":return I=7}return I=16}return r+=String.fromCharCode(v),n++,I=16}}function R(v){if(Z7e(v)||pme(v))return!1;switch(v){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}function V(){let v;do v=W();while(v>=12&&v<=15);return v}return{setPosition:p,getPosition:()=>n,scan:e?V:W,getToken:()=>I,getTokenValue:()=>r,getTokenOffset:()=>a,getTokenLength:()=>n-a,getTokenStartLine:()=>o,getTokenStartCharacter:()=>a-d,getTokenError:()=>m}}function Z7e(t){return t===32||t===9}function pme(t){return t===10||t===13}function Hq(t){return t>=48&&t<=57}var gjt;(function(t){t[t.lineFeed=10]="lineFeed",t[t.carriageReturn=13]="carriageReturn",t[t.space=32]="space",t[t._0=48]="_0",t[t._1=49]="_1",t[t._2=50]="_2",t[t._3=51]="_3",t[t._4=52]="_4",t[t._5=53]="_5",t[t._6=54]="_6",t[t._7=55]="_7",t[t._8=56]="_8",t[t._9=57]="_9",t[t.a=97]="a",t[t.b=98]="b",t[t.c=99]="c",t[t.d=100]="d",t[t.e=101]="e",t[t.f=102]="f",t[t.g=103]="g",t[t.h=104]="h",t[t.i=105]="i",t[t.j=106]="j",t[t.k=107]="k",t[t.l=108]="l",t[t.m=109]="m",t[t.n=110]="n",t[t.o=111]="o",t[t.p=112]="p",t[t.q=113]="q",t[t.r=114]="r",t[t.s=115]="s",t[t.t=116]="t",t[t.u=117]="u",t[t.v=118]="v",t[t.w=119]="w",t[t.x=120]="x",t[t.y=121]="y",t[t.z=122]="z",t[t.A=65]="A",t[t.B=66]="B",t[t.C=67]="C",t[t.D=68]="D",t[t.E=69]="E",t[t.F=70]="F",t[t.G=71]="G",t[t.H=72]="H",t[t.I=73]="I",t[t.J=74]="J",t[t.K=75]="K",t[t.L=76]="L",t[t.M=77]="M",t[t.N=78]="N",t[t.O=79]="O",t[t.P=80]="P",t[t.Q=81]="Q",t[t.R=82]="R",t[t.S=83]="S",t[t.T=84]="T",t[t.U=85]="U",t[t.V=86]="V",t[t.W=87]="W",t[t.X=88]="X",t[t.Y=89]="Y",t[t.Z=90]="Z",t[t.asterisk=42]="asterisk",t[t.backslash=92]="backslash",t[t.closeBrace=125]="closeBrace",t[t.closeBracket=93]="closeBracket",t[t.colon=58]="colon",t[t.comma=44]="comma",t[t.dot=46]="dot",t[t.doubleQuote=34]="doubleQuote",t[t.minus=45]="minus",t[t.openBrace=123]="openBrace",t[t.openBracket=91]="openBracket",t[t.plus=43]="plus",t[t.slash=47]="slash",t[t.formFeed=12]="formFeed",t[t.tab=9]="tab"})(gjt||(gjt={}));var sy=new Array(20).fill(0).map((t,e)=>" ".repeat(e)),Xq=200,N7e={" ":{"\n":new Array(Xq).fill(0).map((t,e)=>`
|
|
2049
2049
|
`+" ".repeat(e)),"\r":new Array(Xq).fill(0).map((t,e)=>"\r"+" ".repeat(e)),"\r\n":new Array(Xq).fill(0).map((t,e)=>`\r
|
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.354-
|
|
4
|
+
"version": "0.0.354-5",
|
|
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": "4615d06"
|
|
41
41
|
}
|
|
42
42
|
}
|
package/sdk/index.d.ts
CHANGED
|
@@ -998,7 +998,16 @@ export declare class Session implements SessionMetadata {
|
|
|
998
998
|
* @param data - The event data payload
|
|
999
999
|
* @param ephemeral - Whether this event should be persisted (default: false)
|
|
1000
1000
|
*/
|
|
1001
|
-
|
|
1001
|
+
private emitInternal;
|
|
1002
|
+
/**
|
|
1003
|
+
* Emits an event to all registered handlers.
|
|
1004
|
+
* Automatically generates event fields (id, timestamp, parentId) and adds the event to the session history.
|
|
1005
|
+
* Triggers both legacy callbacks and new-style event handlers. Does not allow emitting ephemeral events.
|
|
1006
|
+
*
|
|
1007
|
+
* @param eventType - The type of event to emit
|
|
1008
|
+
* @param data - The event data payload
|
|
1009
|
+
*/
|
|
1010
|
+
emit<K extends EventType>(eventType: EventPayload<K>["ephemeral"] extends true ? never : K, data: EventData<K>): void;
|
|
1002
1011
|
/**
|
|
1003
1012
|
* Emits an ephemeral event (not persisted to disk).
|
|
1004
1013
|
* Convenience method that calls emit() with ephemeral = true.
|
|
@@ -1006,7 +1015,7 @@ export declare class Session implements SessionMetadata {
|
|
|
1006
1015
|
* @param eventType - The type of event to emit
|
|
1007
1016
|
* @param data - The event data payload
|
|
1008
1017
|
*/
|
|
1009
|
-
emitEphemeral<K extends EventType>(eventType: K, data: EventData<K>): void;
|
|
1018
|
+
emitEphemeral<K extends EventType>(eventType: EventPayload<K>["ephemeral"] extends false ? never : K, data: EventData<K>): void;
|
|
1010
1019
|
/**
|
|
1011
1020
|
* Returns all events that have occurred in the session.
|
|
1012
1021
|
* Events are returned in chronological order and include all session lifecycle, user messages,
|
package/sdk/index.js
CHANGED
|
@@ -1459,7 +1459,7 @@ Pay attention to the following when using it:
|
|
|
1459
1459
|
`}var $rt=m_.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function est(){let t={};for(let e of $rt){let I=m_.env[e];I!==void 0&&(I.startsWith("()")||(t[e]=I))}return t}var b_=class{constructor(e){this._abortController=new AbortController,this._readBuffer=new d_,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new _rt)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,I)=>{var l,n,c,r,s;this._process=(0,UeI.default)(this._serverParams.command,(l=this._serverParams.args)!==null&&l!==void 0?l:[],{env:{...est(),...this._serverParams.env},stdio:["pipe","pipe",(n=this._serverParams.stderr)!==null&&n!==void 0?n:"inherit"],shell:!1,signal:this._abortController.signal,windowsHide:m_.platform==="win32"&&Ist(),cwd:this._serverParams.cwd}),this._process.on("error",a=>{var o,G;if(a.name==="AbortError"){(o=this.onclose)===null||o===void 0||o.call(this);return}I(a),(G=this.onerror)===null||G===void 0||G.call(this,a)}),this._process.on("spawn",()=>{e()}),this._process.on("close",a=>{var o;this._process=void 0,(o=this.onclose)===null||o===void 0||o.call(this)}),(c=this._process.stdin)===null||c===void 0||c.on("error",a=>{var o;(o=this.onerror)===null||o===void 0||o.call(this,a)}),(r=this._process.stdout)===null||r===void 0||r.on("data",a=>{this._readBuffer.append(a),this.processReadBuffer()}),(s=this._process.stdout)===null||s===void 0||s.on("error",a=>{var o;(o=this.onerror)===null||o===void 0||o.call(this,a)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){var e,I;return this._stderrStream?this._stderrStream:(I=(e=this._process)===null||e===void 0?void 0:e.stderr)!==null&&I!==void 0?I:null}get pid(){var e,I;return(I=(e=this._process)===null||e===void 0?void 0:e.pid)!==null&&I!==void 0?I:null}processReadBuffer(){for(var e,I;;)try{let l=this._readBuffer.readMessage();if(l===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,l)}catch(l){(I=this.onerror)===null||I===void 0||I.call(this,l)}}async close(){this._abortController.abort(),this._process=void 0,this._readBuffer.clear()}send(e){return new Promise(I=>{var l;if(!(!((l=this._process)===null||l===void 0)&&l.stdin))throw new Error("Not connected");let n=zeI(e);this._process.stdin.write(n)?I():this._process.stdin.once("drain",I)})}};function Ist(){return"type"in m_}var h_=class extends TransformStream{constructor({onError:e,onRetry:I,onComment:l}={}){let n;super({start(c){n=r_({onEvent:r=>{c.enqueue(r)},onError(r){e==="terminate"?c.error(r):typeof e=="function"&&e(r)},onRetry:I,onComment:l})},transform(c){n.feed(c)}})}};var tst={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},kz=class extends Error{constructor(e,I){super(`Streamable HTTP error: ${I}`),this.code=e}},p_=class{constructor(e,I){var l;this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=I?.requestInit,this._authProvider=I?.authProvider,this._fetch=I?.fetch,this._sessionId=I?.sessionId,this._reconnectionOptions=(l=I?.reconnectionOptions)!==null&&l!==void 0?l:tst}async _authThenStart(){var e;if(!this._authProvider)throw new gG("No auth provider");let I;try{I=await YV(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(l){throw(e=this.onerror)===null||e===void 0||e.call(this,l),l}if(I!=="AUTHORIZED")throw new gG;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let I={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(I.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(I["mcp-session-id"]=this._sessionId),this._protocolVersion&&(I["mcp-protocol-version"]=this._protocolVersion);let l=this._normalizeHeaders((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...I,...l})}async _startOrAuthSse(e){var I,l,n;let{resumptionToken:c}=e;try{let r=await this._commonHeaders();r.set("Accept","text/event-stream"),c&&r.set("last-event-id",c);let s=await((I=this._fetch)!==null&&I!==void 0?I:fetch)(this._url,{method:"GET",headers:r,signal:(l=this._abortController)===null||l===void 0?void 0:l.signal});if(!s.ok){if(s.status===401&&this._authProvider)return await this._authThenStart();if(s.status===405)return;throw new kz(s.status,`Failed to open SSE stream: ${s.statusText}`)}this._handleSseStream(s.body,e,!0)}catch(r){throw(n=this.onerror)===null||n===void 0||n.call(this,r),r}}_getNextReconnectionDelay(e){let I=this._reconnectionOptions.initialReconnectionDelay,l=this._reconnectionOptions.reconnectionDelayGrowFactor,n=this._reconnectionOptions.maxReconnectionDelay;return Math.min(I*Math.pow(l,e),n)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,I=0){var l;let n=this._reconnectionOptions.maxRetries;if(n>0&&I>=n){(l=this.onerror)===null||l===void 0||l.call(this,new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let c=this._getNextReconnectionDelay(I);setTimeout(()=>{this._startOrAuthSse(e).catch(r=>{var s;(s=this.onerror)===null||s===void 0||s.call(this,new Error(`Failed to reconnect SSE stream: ${r instanceof Error?r.message:String(r)}`)),this._scheduleReconnection(e,I+1)})},c)}_handleSseStream(e,I,l){if(!e)return;let{onresumptiontoken:n,replayMessageId:c}=I,r;(async()=>{var a,o,G,i;try{let d=e.pipeThrough(new TextDecoderStream).pipeThrough(new h_).getReader();for(;;){let{value:b,done:m}=await d.read();if(m)break;if(b.id&&(r=b.id,n?.(b.id)),!b.event||b.event==="message")try{let h=dV.parse(JSON.parse(b.data));c!==void 0&&MB(h)&&(h.id=c),(a=this.onmessage)===null||a===void 0||a.call(this,h)}catch(h){(o=this.onerror)===null||o===void 0||o.call(this,h)}}}catch(d){if((G=this.onerror)===null||G===void 0||G.call(this,new Error(`SSE stream disconnected: ${d}`)),l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:r,onresumptiontoken:n,replayMessageId:c},0)}catch(b){(i=this.onerror)===null||i===void 0||i.call(this,new Error(`Failed to reconnect: ${b instanceof Error?b.message:String(b)}`))}}})()}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 gG("No auth provider");if(await YV(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new gG("Failed to authorize")}async close(){var e,I;(e=this._abortController)===null||e===void 0||e.abort(),(I=this.onclose)===null||I===void 0||I.call(this)}async send(e,I){var l,n,c,r;try{let{resumptionToken:s,onresumptiontoken:a}=I||{};if(s){this._startOrAuthSse({resumptionToken:s,replayMessageId:m7(e)?e.id:void 0}).catch(u=>{var Z;return(Z=this.onerror)===null||Z===void 0?void 0:Z.call(this,u)});return}let o=await this._commonHeaders();o.set("content-type","application/json"),o.set("accept","application/json, text/event-stream");let G={...this._requestInit,method:"POST",headers:o,body:JSON.stringify(e),signal:(l=this._abortController)===null||l===void 0?void 0:l.signal},i=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._url,G),d=i.headers.get("mcp-session-id");if(d&&(this._sessionId=d),!i.ok){if(i.status===401&&this._authProvider){if(this._resourceMetadataUrl=fz(i),await YV(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new gG;return this.send(e)}let u=await i.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${i.status}): ${u}`)}if(i.status===202){_8e(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(u=>{var Z;return(Z=this.onerror)===null||Z===void 0?void 0:Z.call(this,u)});return}let m=(Array.isArray(e)?e:[e]).filter(u=>"method"in u&&"id"in u&&u.id!==void 0).length>0,h=i.headers.get("content-type");if(m)if(h?.includes("text/event-stream"))this._handleSseStream(i.body,{onresumptiontoken:a},!1);else if(h?.includes("application/json")){let u=await i.json(),Z=Array.isArray(u)?u.map(N=>dV.parse(N)):[dV.parse(u)];for(let N of Z)(c=this.onmessage)===null||c===void 0||c.call(this,N)}else throw new kz(-1,`Unexpected content type: ${h}`)}catch(s){throw(r=this.onerror)===null||r===void 0||r.call(this,s),s}}get sessionId(){return this._sessionId}async terminateSession(){var e,I,l;if(this._sessionId)try{let n=await this._commonHeaders(),c={...this._requestInit,method:"DELETE",headers:n,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},r=await((I=this._fetch)!==null&&I!==void 0?I:fetch)(this._url,c);if(!r.ok&&r.status!==405)throw new kz(r.status,`Failed to terminate session: ${r.statusText}`);this._sessionId=void 0}catch(n){throw(l=this.onerror)===null||l===void 0||l.call(this,n),n}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}};var u_=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 UNe(this),await this.server.connect(this.serverTransport)}async send(e){if(this.closed)throw new Error("Transport is closed");setImmediate(()=>{try{this.serverTransport?.onmessage?.(e)}catch(I){this.onerror?.(I instanceof Error?I:new Error(String(I)))}})}receive(e){this.closed||this.onmessage?.(e)}async close(){this.closed||(this.closed=!0,await this.serverTransport?.close(),this.onclose?.())}},UNe=class{constructor(e){this.clientTransport=e}onmessage;onerror;onclose;closed=!1;async start(){}async send(e){if(this.closed)throw new Error("Transport is closed");setImmediate(()=>{try{this.clientTransport.receive(e)}catch(I){this.onerror?.(I instanceof Error?I:new Error(String(I)))}})}async close(){this.closed||(this.closed=!0,this.onclose?.())}};var Z_=class{createTransport(e){switch(e.type){case"stdio":{let I=new b_({command:e.command,args:e.args,env:e.env,stderr:e.stderr?"pipe":void 0,cwd:e.cwd});return I.stderr?.pipe(e.stderr),I}case"http":return new p_(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"sse":return new G_(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"memory":return new u_(e.server);default:throw new Error(`Unsupported transport type: ${e.type}`)}}};var xz="blackbird-mcp-server",VV="github-mcp-server",SNe="playwright",Bz=[xz];function Bv(t){return t.type===void 0||t.type.toLowerCase()==="local"||t.type.toLowerCase()==="stdio"}function SeI(t){return zz(t)||Uz(t)}function zz(t){return t.type?.toLowerCase()==="http"}function Uz(t){return t.type?.toLowerCase()==="sse"}function Sz(t){return t.type?.toLowerCase()==="memory"}var ONe=class extends lst{constructor(I,l){super({decodeStrings:!1});this.serverName=I;this.logger=l}_write(I,l,n){try{let c=I.toString();this.logger.log(`[mcp server ${this.serverName} stderr] ${c}`),n()}catch(c){n(c instanceof Error?c:new Error(String(c)))}}},W_=class{constructor(e,I=new n_,l=new Z_,n="indirect"){this.logger=e;this.clientFactory=I;this.transportFactory=l;this.envValueMode=n}clients={};transports={};async startLocalMcpClient(e,I,l,n,c){this.logger.log(`Starting MCP client for ${e} with command: ${l} and args: ${n}`);let r=new ONe(e,this.logger),s={type:"stdio",command:l,args:n,env:{...I,PATH:process.env.PATH},stderr:r,cwd:c},a=this.transportFactory.createTransport(s);await this.setupAndConnectClient(e,a)}async startHttpMcpClient(e,I){this.logger.log(`Starting remote MCP client for ${e} with url: ${I.url}`);let l={type:"http",url:I.url,headers:I.headers},n=this.transportFactory.createTransport(l);await this.setupAndConnectClient(e,n)}async startSseMcpClient(e,I){this.logger.log(`Starting remote MCP client for ${e} with url: ${I.url}`);let l={type:"sse",url:I.url,headers:I.headers},n=this.transportFactory.createTransport(l);await this.setupAndConnectClient(e,n)}async startInMemoryMcpClient(e,I){this.logger.log(`Starting in-memory MCP client for ${e}`);let l={type:"memory",server:I},n=this.transportFactory.createTransport(l);await this.setupAndConnectClient(e,n)}async setupAndConnectClient(e,I){this.transports[e]=I,I.onclose=()=>{this.logger.log(`MCP transport for ${e} closed`),delete this.transports[e]},this.logger.log(`Creating MCP client for ${e}...`);let l=this.clientFactory.createClient({name:"github-copilot-developer",version:"1.0.0"},{capabilities:{experimental:void 0,roots:void 0,sampling:void 0}}),n=Date.now();this.logger.log(`Connecting MCP client for ${e}...`),await l.connect(I),l.onclose=()=>{this.logger.log(`MCP client for ${e} closed`),delete this.clients[e]},l.onerror=c=>{this.logger.error(`MCP client for ${e} errored ${c}`)},this.logger.log(`MCP client for ${e} connected, took ${Date.now()-n}ms`),this.clients[e]=l}async getTools(e,I){let l={};for(let[n,c]of Object.entries(this.clients))(await this.getServerTools(n,c,e,I)).forEach(s=>{l[s.namespacedName]=s});return this.logger.log(`All tools retrieved: ${JSON.stringify(l,null,2)}`),l}async getServerTools(e,I,l,n){let c=[];try{this.logger.log(`Fetching tools from client: ${e}`);let r=await I.listTools(),s=l?.mcpServers[e].tools,a=l?.mcpServers[e].filterMapping;for(let G of r.tools){if(G.name==="get_copilot_space")continue;if(!(s?.includes("*")||s?.includes(G.name))){this.logger.log(`Tool ${G.name} is not in the allowed list for client: ${e}`);continue}let d=q8(e,G.name),b=`${e}-${G.name}`,m;typeof a=="string"?m=Cpe(a):m=Cpe(a?.[G.name]??"hidden_characters");let h=`${e}/${G.name}`,u={name:b,namespacedName:h,title:G.title||G.annotations?.title||h||G.name,description:G.description??b,input_schema:G.inputSchema,readOnly:G.annotations?.readOnlyHint,safeForTelemetry:{name:!!(l?.mcpServers[e].isDefaultServer||d),inputsNames:!!l?.mcpServers[e].isDefaultServer},filterMode:m};c.push(u),this.logger.log(`Tool ${G.name} added to tools list for client: ${e}`)}this.logger.log(`Successfully retrieved ${c.length} tools from client: ${e}`);let o=I.getServerVersion();await this.logServerSuccessWithTools(e,c,o,n)}catch(r){this.logger.error(`Failed to get tools from client: ${e} ${r}`)}return c}async logServerSuccessWithTools(e,I,l,n){if(!Bz.includes(e)&&n)try{let c=I.map(o=>`- ${o.namespacedName}`).join(`
|
|
1460
1460
|
`),r=I.reduce((o,G)=>(o[G.name]=G.title||G.namespacedName,o),{}),a=`MCP server started successfully${l?` (version ${l.version})`:""} with ${I.length} ${I.length===1?"tool":"tools"} - for the full output, see the verbose logs
|
|
1461
1461
|
|
|
1462
|
-
${c}`;await n.createOrUpdateMCPStartupToolCall({serverName:e,content:a,toolNamesToDisplayNames:r}),this.logger.log(`Updated session log for ${e} with ${I.length} tools`)}catch(c){this.logger.error(`Failed to update session log for ${e}: ${c}`)}}};var RV=class t{static resolveString(e,I){return!I||e.length>1e3?e:e.replace(/\$\{([A-Z0-9_]+)(?::-([^}]*))?\}|\$([A-Z0-9_]+)(?![A-Z0-9_])/g,(l,n,c,r)=>{let a=I[n||r];return a!==void 0?a:c!==void 0?c:l})}static resolveArray(e,I){return e?I?e.map(l=>t.resolveString(l,I)):e:[]}static resolveHeaders(e,I){if(!e)return{};if(!I)return e;let l={};for(let[n,c]of Object.entries(e)){let r=t.resolveArray([c],I);l[n]=r[0]}return l}static resolveLocalServerConfig(e,I){let l=t.resolveString(e.command,I),n=t.resolveArray(e.args,I),c;return e.cwd&&(c=t.resolveString(e.cwd,I)),{...e,command:l,args:n,cwd:c}}static resolveRemoteServerConfig(e,I=process.env){let l=t.resolveString(e.url,I),n=t.resolveHeaders(e.headers,I);return{...e,url:l,headers:n}}};var MNe={mcpServers:{}},N_=class{constructor(e,I,l){this.logger=e;this.registry=I;this.remoteEnabled=l?.remoteEnabled??!1,this.mcp3pEnabled=l?.mcp3pEnabled??!1,this.blackbirdMetisIndexEnabled=l?.blackbirdMetisIndexEnabled??!1,this.sessionClient=l?.sessionClient,this.mcpEnvConfig=void 0,this.envValueMode=l?.envValueMode??this.registry.envValueMode}remoteEnabled;mcp3pEnabled;blackbirdMetisIndexEnabled;mcpEnvConfig;sessionClient;envValueMode;ReadMcpConfigFromEnv(e){this.mcpEnvConfig=process.env.GITHUB_COPILOT_MCP_JSON,this.mcp3pEnabled=process.env.GITHUB_COPILOT_3P_MCP_ENABLED==="true",this.remoteEnabled=process.env.GITHUB_COPILOT_REMOTE_MCP_ENABLED==="true",this.blackbirdMetisIndexEnabled=process.env.BLACKBIRD_METIS_INDEX_ENABLED==="true";let I=this.validateEnvConfig();return process.env.GITHUB_COPILOT_CLI_MODE==="true"?this.logger.log("CLI mode detected - skipping default MCP servers"):(this.logger.log("Adding default MCP servers to configuration"),this.configureBlackbirdMcp(I,e),this.configureGitHubMcp(I,e),this.configurePlaywrightMcp(I)),I}validateEnvConfig(){if(!this.mcp3pEnabled)return this.logger.log("User-provided MCPs are disabled"),MNe;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"),MNe;try{let e=JSON.parse(this.mcpEnvConfig);if(!e.mcpServers)throw new Error("User-provided config had incorrect format. Missing 'mcpServers' property.");for(let I in e.mcpServers){if(I.indexOf("/")===-1)continue;let l=I.replace(/\//g,"__");e.mcpServers[l]=e.mcpServers[I],delete e.mcpServers[I]}for(let I in e.mcpServers)e.mcpServers[I].isDefaultServer=!1;return e}catch(e){return this.logger.error(`Warning: User-provided MCP servers were defined but invalid: ${e}`),MNe}}configureGitHubMcp(e,I){this.remoteEnabled?this.configureRemoteGitHubMcp(e,I):this.configureLocalGitHubMcp(e)}configureRemoteGitHubMcp(e,I){let l="repos,issues,users,pull_requests,code_security,secret_protection,actions,web_search";process.env.COPILOT_MCP_COPILOT_SPACES_ENABLED==="true"&&(this.logger.log("Enabling Copilot Spaces in GitHub MCP server configuration"),l=l+",copilot_spaces");let n={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":l,"X-MCP-Host":"github-coding-agent","X-Initiator":"agent"};I&&I.api?.copilot?.integrationId&&(n["Copilot-Integration-Id"]=I.api.copilot.integrationId),process.env.GITHUB_COPILOT_INTERACTION_ID&&(n["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let c={type:"http",url:this.getCapiMcpUrl(),headers:n,tools:["*"],isDefaultServer:!0};this.setDefaultGitHubFilterMapping(c);let r=e.mcpServers[VV]??void 0;if(r&&SeI(r)){let s=structuredClone(r);this.logger.log("GitHub MCP server configuration already provided by user, skipping default remote configuration"),r.headers===void 0&&(r.headers={}),s.headers={...n,...r.headers},s.isDefaultServer=!0,this.setDefaultGitHubFilterMapping(s),e.mcpServers[VV]=s}else this.logger.log("Using default remote GitHub MCP server configuration"),e.mcpServers[VV]=c}configureLocalGitHubMcp(e){if(e.mcpServers[VV]){this.logger.log("Using user-provided GitHub MCP server configuration");let I=e.mcpServers[VV]??{};Bv(I)&&!I.command&&(e.mcpServers[VV]={...I,command:"./copilot-developer-action-main/github-mcp-server/github-mcp-server",isDefaultServer:!0},this.logger.log("Added default command to user-provided GitHub MCP server configuration"))}else{this.logger.log("Using default local GitHub MCP server configuration");let I={command:"./copilot-developer-action-main/github-mcp-server/github-mcp-server",args:["stdio","--read-only"],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",GITHUB_HOST:"GITHUB_SERVER_URL"},tools:["*"],isDefaultServer:!0};e.mcpServers[VV]=I}}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[SNe]){if((process.env.COPILOT_FEATURE_FLAGS??"").split(",").map(l=>l.trim()).includes("copilot_swe_agent_playwright_use_firewall")){this.logger.log("Playwright MCP server is configured to use the firewall, skipping launch.");return}this.logger.log("Enabling Playwright MCP server");let I={command:"npx",args:[...tZe,"--allowed-origins","localhost;localhost:*;127.0.0.1;127.0.0.1:*"],tools:["*"],isDefaultServer:!0};e.mcpServers[SNe]=I}}configureBlackbirdMcp(e,I){this.remoteEnabled?this.configureRemoteBlackbirdMcp(e):this.blackbirdMetisIndexEnabled?this.configureLocalMetisBlackbirdMCP(e,I):this.configureLocalBlackbirdMcp(e)}configureLocalMetisBlackbirdMCP(e,I){this.logger.log("Using local Metis Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${I.blackbird?.mode}`);let l=process.env.AGENT_DIR||"/agent";this.logger.log(`Using agent directory: ${l}`);let n=[];I.blackbird?.mode==="tool"&&(n=["*"]),this.logger.log(`Using blackbird Metis server: ${I.blackbird?.mode}`);let c={command:`${l}/blackbird/mcp`,args:["serve","--index",`${l}/blackbird/metis`],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",COPILOT_API_HMAC_KEY:"CAPI_HMAC_KEY",MODEL_BASED_RETRIEVAL_TOKEN:"BLACKBIRD_AUTH_MODEL_BASED_RETRIEVAL_TOKEN",METIS_API_KEY:"BLACKBIRD_AUTH_METIS_API_KEY"},tools:n,isDefaultServer:!0};e.mcpServers[xz]=c}configureLocalBlackbirdMcp(e){this.logger.log("Using local Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let I=[];process.env.BLACKBIRD_MODE==="tool"&&(I=["*"]);let l={command:"./copilot-developer-action-main/blackbird-mcp-server/blackbird-mcp-server",args:["stdio"],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",CAPI_HOST:"COPILOT_API_URL"},tools:I,isDefaultServer:!0};e.mcpServers[xz]=l}configureRemoteBlackbirdMcp(e){this.logger.log("Using remote Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let I=[];process.env.BLACKBIRD_MODE==="tool"&&(I=["*"]);let l={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":"search_agent","X-MCP-Host":"github-coding-agent"};process.env.GITHUB_COPILOT_INTERACTION_ID&&(l["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let n={type:"http",url:this.getCapiMcpUrl(),headers:l,tools:I,isDefaultServer:!0};e.mcpServers[xz]=n}getCapiMcpUrl(){return process.env.COPILOT_API_URL?new URL("/mcp/readonly",process.env.COPILOT_API_URL).toString():"https://api.githubcopilot.com/mcp/readonly"}isValidServerType(e){return Bv(e)||zz(e)||Uz(e)||Sz(e)}isValidLocalServerConfig(e){return e.command!==void 0&&e.command.trim()!==""&&Array.isArray(e.args)}isValidRemoteServerConfig(e){return e.url!==void 0&&e.url.trim()!==""}isValidInMemoryServerConfig(e){return e.serverInstance!==void 0&&typeof e.serverInstance=="object"}validateServerConfig(e,I){return this.remoteEnabled&&!this.isValidServerType(I)?(this.logger.error(`Unsupported server type "${I.type}" for server "${e}". Only "Local", "STDIO", "HTTP", "SSE", or "Memory" are supported.`),!1):!this.remoteEnabled&&!Bv(I)&&!Sz(I)?(this.logger.error(`Unsupported server type "${I.type}" for server "${e}". Only "Local", "STDIO", or "Memory" are supported.`),!1):I.tools?Bv(I)&&!this.isValidLocalServerConfig(I)?(this.logger.error(`Invalid local server configuration for "${e}". Please ensure 'command' and 'args' are provided.`),!1):(zz(I)||Uz(I))&&!this.isValidRemoteServerConfig(I)?(this.logger.error(`Invalid remote server configuration for "${e}". Please ensure 'url' is provided.`),!1):Sz(I)&&!this.isValidInMemoryServerConfig(I)?(this.logger.error(`Invalid in-memory server configuration for "${e}". Please ensure 'serverInstance' is provided and is an instance of MCPServer.`),!1):!0:(this.logger.error(`No tools specified for server "${e}". Please provide a list of tools or "*" to include all tools.`),!1)}async processHttpServer(e,I){try{let l=RV.resolveHeaders(I.headers,process.env),n={...I,headers:l};await this.registry.startHttpMcpClient(e,n),this.logger.log(`Started MCP client for remote server ${e}`)}catch(l){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${l}`),l}}async processSseServer(e,I){try{let l=RV.resolveRemoteServerConfig(I,process.env);await this.registry.startSseMcpClient(e,l),this.logger.log(`Started MCP client for remote server ${e}`)}catch(l){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${l}`),l}}async processInMemoryServer(e,I){try{await this.registry.startInMemoryMcpClient(e,I.serverInstance),this.logger.log(`Started in-memory MCP client for ${e}`)}catch(l){throw this.logger.error(`Failed to start in-memory MCP client for ${e}: ${l}`),l}}async processLocalServer(e,I){let l={...I};if(I.command==="python")try{l=await this.convertPythonToPipx(l)}catch(r){this.logger.error(`Failed to handle Python module for ${e}: ${r}`)}let n=this.buildEnvironment(l),c=RV.resolveLocalServerConfig(l,n);this.logger.log(`Starting MCP client for ${e} with command: ${c.command} and args: ${c.args}`),c.cwd&&this.logger.log(`cwd: ${c.cwd}`);try{await this.registry.startLocalMcpClient(e,n,c.command,c.args,c.cwd),this.logger.log(`Started MCP client for ${e}`)}catch(r){throw this.logger.error(`Failed to start MCP client for ${e}: ${r}`),r}}convertPythonToPipx(e){if(!e||!e.args||e.args.length===0)return e;let I=e.args;if(I.length>1e3)throw new Error("Too many arguments provided to Python command");let l=I.indexOf("-m");if(l===-1||l===I.length-1)throw new Error("Python command with -m flag must specify a module");let n=I[l+1];this.logger.log(`Converting Python module: ${n} to pipx command`);let c=["run",n];for(let r=l+2;r<I.length;r++)c.push(I[r]);for(let r=0;r<l;r++)c.push(I[r]);return{...e,command:"pipx",args:c}}buildEnvironment(e){let I={};if(e.env)if(this.envValueMode==="direct")for(let[l,n]of Object.entries(e.env))I[l]=RV.resolveString(n,process.env);else for(let[l,n]of Object.entries(e.env)){let c=n.trim(),r=c;if(c.includes("$")&&(r=RV.resolveString(c,process.env)),r!==c){I[l]=r;continue}process.env[c]!==void 0&&(I[l]=process.env[c])}return I}async processServers(e){if(!e)throw new Error("No servers to process");let I=Object.entries(e.mcpServers).map(([l,n])=>this.processServer(l,n));await Promise.all(I)}async processServer(e,I){if(e=e.replace(/\//g,"__"),!this.validateServerConfig(e,I)){this.logger.error(`Skipping server "${e}" due to invalid configuration.`);return}Bz.includes(e)||await this.sessionClient?.createOrUpdateMCPStartupToolCall({serverName:e});try{Bv(I)?await this.processLocalServer(e,I):zz(I)&&this.remoteEnabled?await this.processHttpServer(e,I):Uz(I)&&this.remoteEnabled?await this.processSseServer(e,I):Sz(I)&&await this.processInMemoryServer(e,I)}catch(l){Bz.includes(e)||await this.logServerFailure(e,l)}}async logServerFailure(e,I){if(this.sessionClient)try{await this.sessionClient.createOrUpdateMCPStartupToolCall({serverName:e,content:`<error>MCP server failed to start: ${I.message} - for the full output, see the verbose logs</error>`})}catch(l){this.logger.error(`Failed to log failure for MCP Server '${e}': '${l}'`)}}};var Y_=class{constructor(e,I,l,n="indirect"){this.logger=e;let c;if(typeof I=="string"){if(c=JSON.parse(I),typeof c!="object")throw new Error("Invalid MCP configuration: must be an object");if(c===null||!("mcpServers"in c)||typeof c.mcpServers!="object")throw new Error("Invalid MCP configuration: missing or invalid mcpServers property");this.config=c}else this.config=I;this.disabledServers=new Set(l||[]),this.registry=new W_(this.logger,void 0,void 0,n),this.processor=new N_(this.logger,this.registry,{mcp3pEnabled:!0,remoteEnabled:!0})}registry;processor;config;startServersPromise=null;transport=null;disabledServers;async startServers(){return this.startServersPromise||(this.startServersPromise=this.processServersWithExtensions()),this.startServersPromise}async injectDefaultServers(e){}async processServersWithExtensions(){await this.injectDefaultServers(this.config);let e;if(this.disabledServers.size>0){let I={};for(let[l,n]of Object.entries(this.config.mcpServers))this.disabledServers.has(l)?this.logger.log(`Skipping disabled MCP server: ${l}`):I[l]=n;e={...this.config,mcpServers:I}}else e=this.config;return this.processor.processServers(e)}async stopServers(){for(let[e,I]of Object.entries(this.registry.transports))try{await I.close()}catch(l){this.logger.error(`Error closing transport for ${e}: ${l}`)}this.startServersPromise=null,this.transport=null}async getTools(e,I,l){await this.startServers(),this.transport=this.transport??new LB(e,I,!0);let n=[];for(let c of Object.keys(this.registry.clients)){let r=await this.transport.loadTools({mcpClient:this.registry.clients[c],clientName:c,tools:this.config.mcpServers[c]?.tools||["*"],filterMapping:this.config.mcpServers[c]?.filterMapping||"hidden_characters"},l);n.push(...r)}return n}getConfig(){return this.config}getClients(){return this.registry.clients}async startServer(e,I){await this.startServers(),this.config.mcpServers[e]=I,await this.processor.processServer(e,I),this.transport=null}async stopServer(e){let I=this.registry.transports[e];if(I)try{await I.close(),delete this.registry.transports[e]}catch(l){this.logger.error(`Error closing transport for ${e}: ${l}`)}this.registry.clients[e]&&delete this.registry.clients[e],this.transport=null}async restartServer(e,I){this.isServerRunning(e)&&await this.stopServer(e),delete this.config.mcpServers[e],await this.startServer(e,I)}isServerRunning(e){return e in this.registry.transports&&e in this.registry.clients}isServerDisabled(e){return this.disabledServers.has(e)}async disableServer(e){if(this.disabledServers.has(e)){this.logger.log(`Server ${e} is already disabled`);return}this.disabledServers.add(e),this.logger.log(`Disabled server ${e} for this session`),this.isServerRunning(e)&&await this.stopServer(e),this.transport=null}async enableServer(e){if(!this.disabledServers.has(e)){this.logger.log(`Server ${e} is not disabled`);return}this.disabledServers.delete(e),this.logger.log(`Enabled server ${e} for this session`);let I=this.getServerConfig(e);I?await this.startServer(e,I):await this.startBuiltInServer(e),this.transport=null}async startBuiltInServer(e){}getServerConfig(e){return this.config.mcpServers[e]}};var WII=Ll(ZII(),1);async function Pat(t={}){let e=await _Ye();return KYe((0,WII.default)({},e,t))}async function NII(t={}){if(GU())throw new Error("Settings have already been initialized");return Pat(t)}import{promises as qat}from"fs";import YII from"path";var _at=3*1024*1024;function VII(t){let e=YII.extname(t).toLowerCase();return[".png",".jpg",".jpeg",".gif",".webp"].includes(e)}function $at(t){switch(YII.extname(t).toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";default:return null}}async function eot(t,e){e.debug(`Processing local image file: ${t}`);let I=await qat.readFile(t),l=$at(t);if(!l)throw new Error(`Unsupported image format: ${t}`);let n=new JB,c=await K8(e,n,_at,HB,l,I);if(!c)throw new Error(`Image too large or couldn't be processed: ${t}`);let r=c.toString("base64");return`data:${l};base64,${r}`}async function Iot(t,e,I){let l=Za();try{let n=await Ere({command:"view",path:t,view_range:void 0},{properties:{command:"view",resolvedPathAgainstCwd:"false",options:"{}",inputs:"[]"},metrics:{responseTokenLimit:void 0,resultLength:0,resultForLlmLength:0},restrictedProperties:{}},e,I);return{id:l,name:"view",arguments:{path:t},result:n.textResultForLlm||""}}catch(n){return{id:l,name:"view",arguments:{path:t},result:`Error reading ${t}: ${n}`}}}async function RII(t,e,I){let l=[],n=t.filter(r=>!VII(r.path));if(n.length===0)return l;let c=[];for(let r of n)try{let s=await Iot(r.path,e,I);c.push(s)}catch{}if(c.length>0){let r=c.map(s=>({id:s.id,type:"function",function:{name:s.name,arguments:JSON.stringify(s.arguments)}}));l.push({role:"assistant",content:"I need to read the content of those paths to answer this request.",tool_calls:r}),l.push(...c.map(s=>({role:"tool",tool_call_id:s.id,content:s.result})))}return l}async function yII(t,e){let I=t.filter(n=>VII(n.path));return(await Promise.all(I.map(async n=>{try{return{type:"image_url",image_url:{url:await eot(n.path,e)}}}catch(c){e.error(`Failed to process image ${n.path}: ${c instanceof Error?c.message:String(c)}`);return}}))).filter(n=>n!==void 0)}var tYe=class{constructor(e,I){this.logger=e;this.session=I}messageQueue=[];async*preRequest(e){this.logger.debug("ImmediatePromptProcessor: Injecting immediate prompts");let l=(await this.session.getChatMessages()).length;for(;this.messageQueue.length>0;){let r=this.messageQueue.shift();this.session.emit("user.message",{content:r.prompt,attachments:r.attachments})}let c=(await this.session.getChatMessages()).slice(l);for(let r of c)e.messages.push(r),yield{kind:"message",message:r,turn:e.turn,source:"immediate-prompt"}}addMessage(e){this.messageQueue.push(e)}toJSON(){return"ImmediatePromptProcessor"}},zp=class t{sessionId;startTime;modifiedTime;logger;events=[];_chatMessages=[];_selectedModel;eventProcessingQueue=Promise.resolve();eventHandlers={};wildcardEventHandlers=[];isProcessing=!1;messageQueue=[];immediatePromptProcessor;mcpHost;workingDir;abortController;modelProvider;allowedTools;disabledTools;requestPermission;mcpServers;hooks;hmacKey;copilotToken;constructor(e={},I={}){this.sessionId=I.sessionId||Za(),this.startTime=I.startTime||new Date,this.modifiedTime=I.modifiedTime||this.startTime,this.logger=e.logger||new dW,this.modelProvider=e.modelProvider,this.allowedTools=e.allowedTools,this.disabledTools=e.disabledTools,this.requestPermission=e.requestPermission,this.mcpServers=e.mcpServers,this.hooks=e.hooks,this.hmacKey=e.hmacKey,this.copilotToken=e.copilotToken,this.workingDir=e.workingDirectory||process.cwd(),this.immediatePromptProcessor=new tYe(this.logger,this),this.abortController=e.abortController||new AbortController,hZe(this.workingDir).then(l=>{if(l.found)return GPe(l.gitRoot,!0,this.workingDir)}).catch(l=>{this.logger.debug(`Failed to initialize custom instructions cache: ${l}`)})}get messageCount(){let e=this.events.find(l=>l.type==="session.import_legacy"),I=0;return e&&(I=(e.data.legacySession?.chatMessages||[]).filter(c=>c.role==="user"||c.role==="assistant").length),this.logger.debug(`Imported message count: ${I}`),this.events.filter(l=>l.type==="user.message"||l.type==="assistant.message").length+I}get summary(){let e=this.events.find(c=>c.type==="session.import_legacy"||c.type==="user.message"),I;if(e?.type==="session.import_legacy"){let c=e.data.legacySession.chatMessages.find(r=>r.role==="user");c?.content&&(typeof c.content=="string"?I=c.content:I=c.content.find(r=>r.type==="text")?.text)}else e?.type==="user.message"&&(I=e.data.content);if(!I)return;let l=I.lastIndexOf("<reminder>");l!==-1&&(I=I.substring(0,l).trim());let n=I.replace(/\s+/g," ").trim();return n.length>75&&(n=n.substring(0,55).trim()+"..."),n=n.split("").filter(c=>{let r=c.charCodeAt(0);return r>=32&&r!==127}).join(""),n}static async fromEvents(e,I={}){if(e.length===0)throw new Error("Cannot create session from empty events array");let l=e[0];if(l.type!=="session.start")throw new Error("First event must be session.start");let n=new t(I,{sessionId:l.data.sessionId,startTime:new Date(l.data.startTime)});n._selectedModel=l.data.selectedModel,n.events.push(l);for(let c=1;c<e.length;c++){let r=e[c];n.events.push(r),await n.processEventForState(r)}return n}on(e,I){return e==="*"?(this.wildcardEventHandlers.push(I),()=>{let l=this.wildcardEventHandlers.indexOf(I);l!==-1&&this.wildcardEventHandlers.splice(l,1)}):(this.eventHandlers[e]||(this.eventHandlers[e]=[]),this.eventHandlers[e].push(I),()=>{let l=this.eventHandlers[e];if(l){let n=l.indexOf(I);n!==-1&&l.splice(n,1)}})}emit(e,I,l=!1){let n=Za(),c=new Date().toISOString(),r=this.getLastEventId(),s={type:e,data:I,id:n,timestamp:c,parentId:r,...l&&{ephemeral:l}};this.events.push(s),this.enqueueEventProcessing(()=>this.processEventForState(s)).catch(a=>{this.logger.error(`Error emitting event: ${a instanceof Error?a.message:String(a)}`)}).catch(a=>{this.logger.error(`Error emitting event ${a instanceof Error?a.message:String(a)}`)}),[...this.eventHandlers[s.type]||[],...this.wildcardEventHandlers].forEach(a=>{try{a(s)}catch(o){this.logger.error(`Error in event handler for event type ${s.type}: ${o instanceof Error?o.message:String(o)}`)}})}emitEphemeral(e,I){this.emit(e,I,!0)}getEvents(){return this.events}async getChatMessages(){return this.enqueueEventProcessing(()=>this._chatMessages)}async getChatContextMessages(){return(await this.getChatMessages()).filter(I=>I.role!=="system")}async getSystemContextMessages(){return(await this.getChatMessages()).filter(I=>I.role==="system")}async getSelectedModel(){return this.enqueueEventProcessing(()=>this._selectedModel)}async setSelectedModel(e){let I=await this.getSelectedModel();this.emit("session.model_change",{previousModel:I,newModel:e})}getLastEventId(){return this.events.length===0?null:this.events[this.events.length-1].id}enqueueEventProcessing(e){let I=this.eventProcessingQueue.then(()=>e());return this.eventProcessingQueue=I,I}async processEventForState(e){switch(e.type){case"session.start":e.data.selectedModel&&(this._selectedModel=e.data.selectedModel);break;case"session.model_change":this._selectedModel=e.data.newModel;break;case"user.message":{let I=[],l=[];if(e.data.attachments&&e.data.attachments.length>0){let n=await yII(e.data.attachments,this.logger);I.push(...n);let c=await RII(e.data.attachments,{requestRequired:!1},this.logger);l.push(...c)}I.length>0?this._chatMessages.push({role:"user",content:[{type:"text",text:e.data.content},...I]}):this._chatMessages.push({role:"user",content:e.data.content}),l.length>0&&this._chatMessages.push(...l);break}case"assistant.message":{if(e.ephemeral||e.data.parentToolCallId)break;let I={role:"assistant",content:e.data.content||null};e.data.toolRequests&&e.data.toolRequests.length>0&&(I.tool_calls=e.data.toolRequests.map(l=>({id:l.toolCallId,type:"function",function:{name:l.name,arguments:typeof l.arguments=="string"?l.arguments:JSON.stringify(l.arguments)}}))),this._chatMessages.push(I);break}case"tool.execution_complete":{if(e.data.parentToolCallId)break;e.data.isUserRequested||this._chatMessages.push({role:"tool",tool_call_id:e.data.toolCallId,content:e.data.success?e.data.result?.content||"":e.data.error?.message||"Tool execution failed"});break}case"system.message":this._chatMessages.push({role:e.data.role,content:e.data.content,...e.data.name&&{name:e.data.name}});break;case"session.import_legacy":this._chatMessages=[...e.data.legacySession.chatMessages],e.data.legacySession.selectedModel&&(this._selectedModel=e.data.legacySession.selectedModel);break;case"abort":case"session.resume":this._chatMessages=tot(this._chatMessages,this.logger);break;case"session.idle":case"session.error":case"session.info":case"assistant.turn_start":case"assistant.turn_end":case"assistant.usage":case"tool.user_requested":case"tool.execution_start":case"tool.execution_partial_result":case"hook.start":case"hook.end":break;default:{let I=e;this.logger.error(`Unknown event type: ${I.type}`);break}}}async send(e,I={}){if((I.mode||"enqueue")==="immediate"&&this.isProcessing)this.immediatePromptProcessor.addMessage(e);else{if(this.messageQueue.push(e),this.isProcessing)return;for(this.isProcessing=!0,await this.initializeMcpHost();this.messageQueue.length>0;){let n=this.messageQueue.shift();await this.runAgenticLoop(n.prompt,n.attachments)}this.isProcessing=!1,this.emit("session.idle",{})}}async abort(){this.abortController.abort()}async initializeMcpHost(){if(!this.mcpHost&&this.mcpServers&&Object.keys(this.mcpServers).length>0)try{this.mcpHost=new Y_(this.logger,{mcpServers:this.mcpServers},this.disabledTools),await this.mcpHost.startServers()}catch(e){this.logger.error(`Failed to initialize MCP host: ${e}`)}}async runAgenticLoop(e,I=[]){if(!this.modelProvider)throw new Error("Session must be created with modelProvider to use send/query methods");let l=new Map,n=new Map;try{let r=(await XW(this.hooks?.userPromptSubmitted,{timestamp:Date.now(),cwd:this.workingDir,prompt:e},this.logger))?.modifiedPrompt??e;this.emit("user.message",{content:eZe({problemStatement:r,capabilities:{}}),attachments:I});let a=new kF().setProblemStatement(r).setAgentModel(this.buildAgentModelString()).setGithubRepoName("copilot-sdk-session").setGithubRepoCommit("copilot-sdk-commit").setGithubRepoReadWrite(!1).setCopilotIntegrationId("copilot-developer-cli").setCopilotHmacKey(this.hmacKey).setCopilotToken(this.copilotToken).build();PYe();let o=await NII(a),G=o.service?.agent?.model,i=$8(G),d=i.agent,b=d??"sweagent-capi",m=i.model?{model:i.model}:void 0,h=Hbe(o,this.logger,d,m),u={location:this.workingDir,timeout:3e4,requireReasoning:!0,toolPartialResultCallback:(pe,Fe)=>{this.emitEphemeral("tool.execution_partial_result",{toolCallId:pe,partialOutput:Fe})},permissions:this.requestPermission?{requestRequired:!0,request:this.requestPermission}:{requestRequired:!1},shellConfig:(process.platform==="win32"?ab.powerShell:ab.bash).withScriptSafetyAssessor(async function(pe){return{result:"completed",commands:[{identifier:pe,readOnly:!1}],possiblePaths:[],hasWriteFileRedirection:!1,canOfferSessionApproval:!1}})},Z=await w8e(u,this.logger),N=[];if(this.mcpHost)try{N=await this.mcpHost.getTools(o,this.logger,u.permissions)}catch(pe){this.logger.error(`Failed to get MCP tools: ${pe}`)}let g=[...Z,...N].filter(pe=>this.allowedTools?this.allowedTools.includes(pe.name):this.disabledTools?!this.disabledTools.includes(pe.name):!0),y=await hZe(this.workingDir),f={...(E8e()[b]?.[h.model]??X8e()).supports,reasoning:!0},v=await h8e({location:y.found?y.gitRoot:"",version:fze(),currentWorkingDirectory:this.workingDir,parts:{},capabilities:f,toolConfigOverrides:u,tools:g,organizationCustomInstructions:void 0}),L=(await this.getChatMessages()).slice(0,-1),Ie={role:"user",content:eZe({customAgentPrompt:void 0,problemStatement:r,capabilities:f})},Ge=[...L,Ie];await XW(this.hooks?.sessionStart,{timestamp:Date.now(),cwd:this.workingDir,source:"new",initialPrompt:e},this.logger);let Qe=new av(Ie,this.logger),Ae=h.getCompletionWithTools(v,Ge,g,{failIfInitialInputsTooLong:!1,processors:{preRequest:[Qe,this.immediatePromptProcessor,new fB(this.logger)],onRequestError:[Qe]},executeToolsInParallel:!1,abortSignal:this.abortController.signal});for await(let pe of Ae){if(this.abortController.signal.aborted){this.emit("abort",{reason:"user initiated"});break}switch(pe.kind){case"message":{if(e7(pe)){let Fe=R8e(pe)?await Promise.all(pe.message.tool_calls.map(async me=>{let uI=bX(me.function.arguments);l.set(me.id,me.function.name),n.set(me.id,uI);let ve=await XW(this.hooks?.preToolUse,{timestamp:Date.now(),cwd:this.workingDir,toolName:me.function.name,toolArgs:uI},this.logger);return{toolCallId:me.id,name:me.function.name,arguments:ve?.modifiedArgs??uI}})):[];this.emit("assistant.message",{parentToolCallId:void 0,messageId:Za(),content:typeof pe.message.content=="string"?pe.message.content:"",toolRequests:Fe});for(let me of Fe)this.emit("tool.execution_start",{toolCallId:me.toolCallId,toolName:me.name,arguments:me.arguments})}else(pe.message.role==="system"||pe.message.role==="developer")&&this.emit("system.message",{role:pe.message.role,content:typeof pe.message.content=="string"?pe.message.content:JSON.stringify(pe.message.content),name:"name"in pe.message?pe.message.name:void 0});break}case"model_call_failure":{let Fe=new Error(pe.modelCall?.error||"Model call failed");await XW(this.hooks?.errorOccurred,{timestamp:Date.now(),cwd:this.workingDir,error:Fe,errorContext:"model_call",recoverable:!0},this.logger),this.emit("session.error",{errorType:"model_call",message:Fe.message,stack:Fe.stack});break}case"tool_execution":{let me=(await XW(this.hooks?.postToolUse,{timestamp:Date.now(),cwd:this.workingDir,toolName:l.get(pe.toolCallId)||"unknown",toolArgs:n.get(pe.toolCallId)||{},toolResult:pe.toolResult},this.logger))?.modifiedResult??pe.toolResult,uI=(me.resultType==="failure"?me.error:void 0)||me.sessionLog||me.textResultForLlm;this.emit("tool.execution_complete",{parentToolCallId:void 0,toolCallId:pe.toolCallId,success:me.resultType==="success",result:me.resultType==="success"?{content:uI}:void 0,error:me.resultType!=="success"?{message:uI,code:me.resultType}:void 0});break}case"turn_started":{this.emit("assistant.turn_start",{turnId:`${pe.turn}`});break}case"turn_ended":{this.emit("assistant.turn_end",{turnId:`${pe.turn}`});break}case"response":case"images_removed":case"image_processing":case"history_truncated":case"turn_failed":case"turn_retry":case"model_call_success":this.logger.debug(`Ignoring event of kind: ${pe.kind}`);break;default:bm(pe,"Unhandled event type")}}}catch(c){await XW(this.hooks?.sessionEnd,{timestamp:Date.now(),cwd:this.workingDir,reason:"error",error:c instanceof Error?c:new Error(String(c))},this.logger),this.emit("session.error",{errorType:"query",message:c instanceof Error?c.message:String(c),stack:c instanceof Error?c.stack:void 0})}finally{await XW(this.hooks?.sessionEnd,{timestamp:Date.now(),cwd:this.workingDir,reason:"complete"},this.logger)}}buildAgentModelString(){if(!this.modelProvider)throw new Error("Session must be created with modelProvider");switch(this.modelProvider.type){case"openai":return`openai:${this.modelProvider.model}`;case"anthropic":return`anthropic:${this.modelProvider.model}`;case"copilot":return`capi:${this.modelProvider.model}`;default:throw new Error(`Unsupported provider: ${this.modelProvider.type}`)}}};function tot(t,e){if(t.length===0)return t;let I=[],l=new Set,n=!1;for(let s=t.length-1;s>=0;s--){let a=t[s];if(a.role==="assistant"&&(n=!0),a.role==="assistant"&&"tool_calls"in a&&a.tool_calls&&a.tool_calls.length>0)for(let o of a.tool_calls)l.has(o.id)||I.push(o.id);else{if(n)break;a.role==="tool"&&a.tool_call_id&&l.add(a.tool_call_id)}}if(I.length===0)return t;let c="The execution of this tool, or a previous tool was interrupted.";e.info(`Completing ${I.length} orphaned tool calls.`);let r=I.map(s=>({role:"tool",tool_call_id:s,content:c}));return[...t,...r]}var X_=class{sessions;logger;options;lastAccessedSessionId;constructor(e){this.options=e,this.sessions=new Map,this.logger=e.logger||new dW}async createSession(){let e=new zp(this.options);return this.sessions.set(e.sessionId,e),this.lastAccessedSessionId=e.sessionId,e}async getSession(e){let I=this.sessions.get(e);return I&&(this.lastAccessedSessionId=e),I}async getLastSession(){if(this.lastAccessedSessionId){let l=this.sessions.get(this.lastAccessedSessionId);if(l)return l}let e=Array.from(this.sessions.values());if(e.length===0)return;e.sort((l,n)=>n.startTime.getTime()-l.startTime.getTime());let I=e[0];return this.lastAccessedSessionId=I.sessionId,I}async listSessions(){return Array.from(this.sessions.values()).map(e=>({sessionId:e.sessionId,startTime:e.startTime,modifiedTime:e.modifiedTime}))}async saveSession(e){}async deleteSession(e){this.sessions.delete(e.sessionId),this.lastAccessedSessionId===e.sessionId&&(this.lastAccessedSessionId=void 0)}async closeSession(e){}};var utI=Ll(ntI(),1);import{existsSync as K_}from"fs";import{appendFile as KGt,mkdir as PGt,readdir as P_,readFile as otI,stat as q_,writeFile as qGt}from"fs/promises";import{homedir as GtI}from"os";import{dirname as _Gt,join as FG}from"path";var OGt=new Error("timeout while waiting for mutex to become available"),eTl=new Error("mutex already locked"),MGt=new Error("request for lock canceled"),TGt=function(t,e,I,l){function n(c){return c instanceof I?c:new I(function(r){r(c)})}return new(I||(I=Promise))(function(c,r){function s(G){try{o(l.next(G))}catch(i){r(i)}}function a(G){try{o(l.throw(G))}catch(i){r(i)}}function o(G){G.done?c(G.value):n(G.value).then(s,a)}o((l=l.apply(t,e||[])).next())})},uYe=class{constructor(e,I=MGt){this._value=e,this._cancelError=I,this._queue=[],this._weightedWaiters=[]}acquire(e=1,I=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((l,n)=>{let c={resolve:l,reject:n,weight:e,priority:I},r=rtI(this._queue,s=>I<=s.priority);r===-1&&e<=this._value?this._dispatchItem(c):this._queue.splice(r+1,0,c)})}runExclusive(e){return TGt(this,arguments,void 0,function*(I,l=1,n=0){let[c,r]=yield this.acquire(l,n);try{return yield I(c)}finally{r()}})}waitForUnlock(e=1,I=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,I)?Promise.resolve():new Promise(l=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),jGt(this._weightedWaiters[e-1],{resolve:l,priority:I})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){let I=this._value;this._value-=e.weight,e.resolve([I,this._newReleaser(e.weight)])}_newReleaser(e){let I=!1;return()=>{I||(I=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){let I=this._weightedWaiters[e-1];I&&(I.forEach(l=>l.resolve()),this._weightedWaiters[e-1]=[])}else{let e=this._queue[0].priority;for(let I=this._value;I>0;I--){let l=this._weightedWaiters[I-1];if(!l)continue;let n=l.findIndex(c=>c.priority<=e);(n===-1?l:l.splice(0,n)).forEach(c=>c.resolve())}}}_couldLockImmediately(e,I){return(this._queue.length===0||this._queue[0].priority<I)&&e<=this._value}};function jGt(t,e){let I=rtI(t,l=>e.priority<=l.priority);t.splice(I+1,0,e)}function rtI(t,e){for(let I=t.length-1;I>=0;I--)if(e(t[I]))return I;return-1}var DGt=function(t,e,I,l){function n(c){return c instanceof I?c:new I(function(r){r(c)})}return new(I||(I=Promise))(function(c,r){function s(G){try{o(l.next(G))}catch(i){r(i)}}function a(G){try{o(l.throw(G))}catch(i){r(i)}}function o(G){G.done?c(G.value):n(G.value).then(s,a)}o((l=l.apply(t,e||[])).next())})},j_=class{constructor(e){this._semaphore=new uYe(1,e)}acquire(){return DGt(this,arguments,void 0,function*(e=0){let[,I]=yield this._semaphore.acquire(1,e);return I})}runExclusive(e,I=0){return this._semaphore.runExclusive(()=>e(),1,I)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}},ctI=function(t,e,I,l){function n(c){return c instanceof I?c:new I(function(r){r(c)})}return new(I||(I=Promise))(function(c,r){function s(G){try{o(l.next(G))}catch(i){r(i)}}function a(G){try{o(l.throw(G))}catch(i){r(i)}}function o(G){G.done?c(G.value):n(G.value).then(s,a)}o((l=l.apply(t,e||[])).next())})};function stI(t,e,I=OGt){return{acquire:(l,n)=>{let c;if(T_(t)?c=l:(c=void 0,n=l),c!==void 0&&c<=0)throw new Error(`invalid weight ${c}: must be positive`);return new Promise((r,s)=>ctI(this,void 0,void 0,function*(){let a=!1,o=setTimeout(()=>{a=!0,s(I)},e);try{let G=yield T_(t)?t.acquire(c,n):t.acquire(n);a?(Array.isArray(G)?G[1]:G)():(clearTimeout(o),r(G))}catch(G){a||(clearTimeout(o),s(G))}}))},runExclusive(l,n,c){return ctI(this,void 0,void 0,function*(){let r=()=>{};try{let s=yield this.acquire(n,c);return Array.isArray(s)?(r=s[1],yield l(s[0])):(r=s,yield l())}finally{r()}})},release(l){t.release(l)},cancel(){return t.cancel()},waitForUnlock:(l,n)=>{let c;if(T_(t)?c=l:(c=void 0,n=l),c!==void 0&&c<=0)throw new Error(`invalid weight ${c}: must be positive`);return new Promise((r,s)=>{let a=setTimeout(()=>s(I),e);(T_(t)?t.waitForUnlock(c,n):t.waitForUnlock(n)).then(()=>{clearTimeout(a),r()})})},isLocked:()=>t.isLocked(),getValue:()=>t.getValue(),setValue:l=>t.setValue(l)}}function T_(t){return t.getValue!==void 0}var D_=class{mutexes=new Map;async runExclusive(e,I,l=5e3){let n=this.mutexes.get(e);n||(n=new j_,n.refCount=0,this.mutexes.set(e,n));let c=n;try{return c.refCount++,await stI(n,l).runExclusive(I)}finally{--c.refCount===0&&this.mutexes.delete(e)}}};var ZYe=(I=>(I.DEFAULT="config",I.MCP="mcp",I))(ZYe||{});function atI(t){return Object.values(ZYe).includes(t)}var __=".copilot",$_=new D_;async function itI(t){let e=_Gt(t);try{await PGt(e,{recursive:!0,mode:448})}catch{}}async function $Gt(t,e){if(K_(t))try{let I={},l=await $_.runExclusive(t,()=>otI(t,"utf8"));return l.trim().startsWith("{")?I=JSON.parse(l):l.split(`
|
|
1462
|
+
${c}`;await n.createOrUpdateMCPStartupToolCall({serverName:e,content:a,toolNamesToDisplayNames:r}),this.logger.log(`Updated session log for ${e} with ${I.length} tools`)}catch(c){this.logger.error(`Failed to update session log for ${e}: ${c}`)}}};var RV=class t{static resolveString(e,I){return!I||e.length>1e3?e:e.replace(/\$\{([A-Z0-9_]+)(?::-([^}]*))?\}|\$([A-Z0-9_]+)(?![A-Z0-9_])/g,(l,n,c,r)=>{let a=I[n||r];return a!==void 0?a:c!==void 0?c:l})}static resolveArray(e,I){return e?I?e.map(l=>t.resolveString(l,I)):e:[]}static resolveHeaders(e,I){if(!e)return{};if(!I)return e;let l={};for(let[n,c]of Object.entries(e)){let r=t.resolveArray([c],I);l[n]=r[0]}return l}static resolveLocalServerConfig(e,I){let l=t.resolveString(e.command,I),n=t.resolveArray(e.args,I),c;return e.cwd&&(c=t.resolveString(e.cwd,I)),{...e,command:l,args:n,cwd:c}}static resolveRemoteServerConfig(e,I=process.env){let l=t.resolveString(e.url,I),n=t.resolveHeaders(e.headers,I);return{...e,url:l,headers:n}}};var MNe={mcpServers:{}},N_=class{constructor(e,I,l){this.logger=e;this.registry=I;this.remoteEnabled=l?.remoteEnabled??!1,this.mcp3pEnabled=l?.mcp3pEnabled??!1,this.blackbirdMetisIndexEnabled=l?.blackbirdMetisIndexEnabled??!1,this.sessionClient=l?.sessionClient,this.mcpEnvConfig=void 0,this.envValueMode=l?.envValueMode??this.registry.envValueMode}remoteEnabled;mcp3pEnabled;blackbirdMetisIndexEnabled;mcpEnvConfig;sessionClient;envValueMode;ReadMcpConfigFromEnv(e){this.mcpEnvConfig=process.env.GITHUB_COPILOT_MCP_JSON,this.mcp3pEnabled=process.env.GITHUB_COPILOT_3P_MCP_ENABLED==="true",this.remoteEnabled=process.env.GITHUB_COPILOT_REMOTE_MCP_ENABLED==="true",this.blackbirdMetisIndexEnabled=process.env.BLACKBIRD_METIS_INDEX_ENABLED==="true";let I=this.validateEnvConfig();return process.env.GITHUB_COPILOT_CLI_MODE==="true"?this.logger.log("CLI mode detected - skipping default MCP servers"):(this.logger.log("Adding default MCP servers to configuration"),this.configureBlackbirdMcp(I,e),this.configureGitHubMcp(I,e),this.configurePlaywrightMcp(I)),I}validateEnvConfig(){if(!this.mcp3pEnabled)return this.logger.log("User-provided MCPs are disabled"),MNe;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"),MNe;try{let e=JSON.parse(this.mcpEnvConfig);if(!e.mcpServers)throw new Error("User-provided config had incorrect format. Missing 'mcpServers' property.");for(let I in e.mcpServers){if(I.indexOf("/")===-1)continue;let l=I.replace(/\//g,"__");e.mcpServers[l]=e.mcpServers[I],delete e.mcpServers[I]}for(let I in e.mcpServers)e.mcpServers[I].isDefaultServer=!1;return e}catch(e){return this.logger.error(`Warning: User-provided MCP servers were defined but invalid: ${e}`),MNe}}configureGitHubMcp(e,I){this.remoteEnabled?this.configureRemoteGitHubMcp(e,I):this.configureLocalGitHubMcp(e)}configureRemoteGitHubMcp(e,I){let l="repos,issues,users,pull_requests,code_security,secret_protection,actions,web_search";process.env.COPILOT_MCP_COPILOT_SPACES_ENABLED==="true"&&(this.logger.log("Enabling Copilot Spaces in GitHub MCP server configuration"),l=l+",copilot_spaces");let n={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":l,"X-MCP-Host":"github-coding-agent","X-Initiator":"agent"};I&&I.api?.copilot?.integrationId&&(n["Copilot-Integration-Id"]=I.api.copilot.integrationId),process.env.GITHUB_COPILOT_INTERACTION_ID&&(n["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let c={type:"http",url:this.getCapiMcpUrl(),headers:n,tools:["*"],isDefaultServer:!0};this.setDefaultGitHubFilterMapping(c);let r=e.mcpServers[VV]??void 0;if(r&&SeI(r)){let s=structuredClone(r);this.logger.log("GitHub MCP server configuration already provided by user, skipping default remote configuration"),r.headers===void 0&&(r.headers={}),s.headers={...n,...r.headers},s.isDefaultServer=!0,this.setDefaultGitHubFilterMapping(s),e.mcpServers[VV]=s}else this.logger.log("Using default remote GitHub MCP server configuration"),e.mcpServers[VV]=c}configureLocalGitHubMcp(e){if(e.mcpServers[VV]){this.logger.log("Using user-provided GitHub MCP server configuration");let I=e.mcpServers[VV]??{};Bv(I)&&!I.command&&(e.mcpServers[VV]={...I,command:"./copilot-developer-action-main/github-mcp-server/github-mcp-server",isDefaultServer:!0},this.logger.log("Added default command to user-provided GitHub MCP server configuration"))}else{this.logger.log("Using default local GitHub MCP server configuration");let I={command:"./copilot-developer-action-main/github-mcp-server/github-mcp-server",args:["stdio","--read-only"],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",GITHUB_HOST:"GITHUB_SERVER_URL"},tools:["*"],isDefaultServer:!0};e.mcpServers[VV]=I}}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[SNe]){if((process.env.COPILOT_FEATURE_FLAGS??"").split(",").map(l=>l.trim()).includes("copilot_swe_agent_playwright_use_firewall")){this.logger.log("Playwright MCP server is configured to use the firewall, skipping launch.");return}this.logger.log("Enabling Playwright MCP server");let I={command:"npx",args:[...tZe,"--allowed-origins","localhost;localhost:*;127.0.0.1;127.0.0.1:*"],tools:["*"],isDefaultServer:!0};e.mcpServers[SNe]=I}}configureBlackbirdMcp(e,I){this.remoteEnabled?this.configureRemoteBlackbirdMcp(e):this.blackbirdMetisIndexEnabled?this.configureLocalMetisBlackbirdMCP(e,I):this.configureLocalBlackbirdMcp(e)}configureLocalMetisBlackbirdMCP(e,I){this.logger.log("Using local Metis Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${I.blackbird?.mode}`);let l=process.env.AGENT_DIR||"/agent";this.logger.log(`Using agent directory: ${l}`);let n=[];I.blackbird?.mode==="tool"&&(n=["*"]),this.logger.log(`Using blackbird Metis server: ${I.blackbird?.mode}`);let c={command:`${l}/blackbird/mcp`,args:["serve","--index",`${l}/blackbird/metis`],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",COPILOT_API_HMAC_KEY:"CAPI_HMAC_KEY",MODEL_BASED_RETRIEVAL_TOKEN:"BLACKBIRD_AUTH_MODEL_BASED_RETRIEVAL_TOKEN",METIS_API_KEY:"BLACKBIRD_AUTH_METIS_API_KEY"},tools:n,isDefaultServer:!0};e.mcpServers[xz]=c}configureLocalBlackbirdMcp(e){this.logger.log("Using local Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let I=[];process.env.BLACKBIRD_MODE==="tool"&&(I=["*"]);let l={command:"./copilot-developer-action-main/blackbird-mcp-server/blackbird-mcp-server",args:["stdio"],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",CAPI_HOST:"COPILOT_API_URL"},tools:I,isDefaultServer:!0};e.mcpServers[xz]=l}configureRemoteBlackbirdMcp(e){this.logger.log("Using remote Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let I=[];process.env.BLACKBIRD_MODE==="tool"&&(I=["*"]);let l={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":"search_agent","X-MCP-Host":"github-coding-agent"};process.env.GITHUB_COPILOT_INTERACTION_ID&&(l["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let n={type:"http",url:this.getCapiMcpUrl(),headers:l,tools:I,isDefaultServer:!0};e.mcpServers[xz]=n}getCapiMcpUrl(){return process.env.COPILOT_API_URL?new URL("/mcp/readonly",process.env.COPILOT_API_URL).toString():"https://api.githubcopilot.com/mcp/readonly"}isValidServerType(e){return Bv(e)||zz(e)||Uz(e)||Sz(e)}isValidLocalServerConfig(e){return e.command!==void 0&&e.command.trim()!==""&&Array.isArray(e.args)}isValidRemoteServerConfig(e){return e.url!==void 0&&e.url.trim()!==""}isValidInMemoryServerConfig(e){return e.serverInstance!==void 0&&typeof e.serverInstance=="object"}validateServerConfig(e,I){return this.remoteEnabled&&!this.isValidServerType(I)?(this.logger.error(`Unsupported server type "${I.type}" for server "${e}". Only "Local", "STDIO", "HTTP", "SSE", or "Memory" are supported.`),!1):!this.remoteEnabled&&!Bv(I)&&!Sz(I)?(this.logger.error(`Unsupported server type "${I.type}" for server "${e}". Only "Local", "STDIO", or "Memory" are supported.`),!1):I.tools?Bv(I)&&!this.isValidLocalServerConfig(I)?(this.logger.error(`Invalid local server configuration for "${e}". Please ensure 'command' and 'args' are provided.`),!1):(zz(I)||Uz(I))&&!this.isValidRemoteServerConfig(I)?(this.logger.error(`Invalid remote server configuration for "${e}". Please ensure 'url' is provided.`),!1):Sz(I)&&!this.isValidInMemoryServerConfig(I)?(this.logger.error(`Invalid in-memory server configuration for "${e}". Please ensure 'serverInstance' is provided and is an instance of MCPServer.`),!1):!0:(this.logger.error(`No tools specified for server "${e}". Please provide a list of tools or "*" to include all tools.`),!1)}async processHttpServer(e,I){try{let l=RV.resolveHeaders(I.headers,process.env),n={...I,headers:l};await this.registry.startHttpMcpClient(e,n),this.logger.log(`Started MCP client for remote server ${e}`)}catch(l){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${l}`),l}}async processSseServer(e,I){try{let l=RV.resolveRemoteServerConfig(I,process.env);await this.registry.startSseMcpClient(e,l),this.logger.log(`Started MCP client for remote server ${e}`)}catch(l){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${l}`),l}}async processInMemoryServer(e,I){try{await this.registry.startInMemoryMcpClient(e,I.serverInstance),this.logger.log(`Started in-memory MCP client for ${e}`)}catch(l){throw this.logger.error(`Failed to start in-memory MCP client for ${e}: ${l}`),l}}async processLocalServer(e,I){let l={...I};if(I.command==="python")try{l=await this.convertPythonToPipx(l)}catch(r){this.logger.error(`Failed to handle Python module for ${e}: ${r}`)}let n=this.buildEnvironment(l),c=RV.resolveLocalServerConfig(l,n);this.logger.log(`Starting MCP client for ${e} with command: ${c.command} and args: ${c.args}`),c.cwd&&this.logger.log(`cwd: ${c.cwd}`);try{await this.registry.startLocalMcpClient(e,n,c.command,c.args,c.cwd),this.logger.log(`Started MCP client for ${e}`)}catch(r){throw this.logger.error(`Failed to start MCP client for ${e}: ${r}`),r}}convertPythonToPipx(e){if(!e||!e.args||e.args.length===0)return e;let I=e.args;if(I.length>1e3)throw new Error("Too many arguments provided to Python command");let l=I.indexOf("-m");if(l===-1||l===I.length-1)throw new Error("Python command with -m flag must specify a module");let n=I[l+1];this.logger.log(`Converting Python module: ${n} to pipx command`);let c=["run",n];for(let r=l+2;r<I.length;r++)c.push(I[r]);for(let r=0;r<l;r++)c.push(I[r]);return{...e,command:"pipx",args:c}}buildEnvironment(e){let I={};if(e.env)if(this.envValueMode==="direct")for(let[l,n]of Object.entries(e.env))I[l]=RV.resolveString(n,process.env);else for(let[l,n]of Object.entries(e.env)){let c=n.trim(),r=c;if(c.includes("$")&&(r=RV.resolveString(c,process.env)),r!==c){I[l]=r;continue}process.env[c]!==void 0&&(I[l]=process.env[c])}return I}async processServers(e){if(!e)throw new Error("No servers to process");let I=Object.entries(e.mcpServers).map(([l,n])=>this.processServer(l,n));await Promise.all(I)}async processServer(e,I){if(e=e.replace(/\//g,"__"),!this.validateServerConfig(e,I)){this.logger.error(`Skipping server "${e}" due to invalid configuration.`);return}Bz.includes(e)||await this.sessionClient?.createOrUpdateMCPStartupToolCall({serverName:e});try{Bv(I)?await this.processLocalServer(e,I):zz(I)&&this.remoteEnabled?await this.processHttpServer(e,I):Uz(I)&&this.remoteEnabled?await this.processSseServer(e,I):Sz(I)&&await this.processInMemoryServer(e,I)}catch(l){Bz.includes(e)||await this.logServerFailure(e,l)}}async logServerFailure(e,I){if(this.sessionClient)try{await this.sessionClient.createOrUpdateMCPStartupToolCall({serverName:e,content:`<error>MCP server failed to start: ${I.message} - for the full output, see the verbose logs</error>`})}catch(l){this.logger.error(`Failed to log failure for MCP Server '${e}': '${l}'`)}}};var Y_=class{constructor(e,I,l,n="indirect"){this.logger=e;let c;if(typeof I=="string"){if(c=JSON.parse(I),typeof c!="object")throw new Error("Invalid MCP configuration: must be an object");if(c===null||!("mcpServers"in c)||typeof c.mcpServers!="object")throw new Error("Invalid MCP configuration: missing or invalid mcpServers property");this.config=c}else this.config=I;this.disabledServers=new Set(l||[]),this.registry=new W_(this.logger,void 0,void 0,n),this.processor=new N_(this.logger,this.registry,{mcp3pEnabled:!0,remoteEnabled:!0})}registry;processor;config;startServersPromise=null;transport=null;disabledServers;async startServers(){return this.startServersPromise||(this.startServersPromise=this.processServersWithExtensions()),this.startServersPromise}async injectDefaultServers(e){}async processServersWithExtensions(){await this.injectDefaultServers(this.config);let e;if(this.disabledServers.size>0){let I={};for(let[l,n]of Object.entries(this.config.mcpServers))this.disabledServers.has(l)?this.logger.log(`Skipping disabled MCP server: ${l}`):I[l]=n;e={...this.config,mcpServers:I}}else e=this.config;return this.processor.processServers(e)}async stopServers(){for(let[e,I]of Object.entries(this.registry.transports))try{await I.close()}catch(l){this.logger.error(`Error closing transport for ${e}: ${l}`)}this.startServersPromise=null,this.transport=null}async getTools(e,I,l){await this.startServers(),this.transport=this.transport??new LB(e,I,!0);let n=[];for(let c of Object.keys(this.registry.clients)){let r=await this.transport.loadTools({mcpClient:this.registry.clients[c],clientName:c,tools:this.config.mcpServers[c]?.tools||["*"],filterMapping:this.config.mcpServers[c]?.filterMapping||"hidden_characters"},l);n.push(...r)}return n}getConfig(){return this.config}getClients(){return this.registry.clients}async startServer(e,I){await this.startServers(),this.config.mcpServers[e]=I,await this.processor.processServer(e,I),this.transport=null}async stopServer(e){let I=this.registry.transports[e];if(I)try{await I.close(),delete this.registry.transports[e]}catch(l){this.logger.error(`Error closing transport for ${e}: ${l}`)}this.registry.clients[e]&&delete this.registry.clients[e],this.transport=null}async restartServer(e,I){this.isServerRunning(e)&&await this.stopServer(e),delete this.config.mcpServers[e],await this.startServer(e,I)}isServerRunning(e){return e in this.registry.transports&&e in this.registry.clients}isServerDisabled(e){return this.disabledServers.has(e)}async disableServer(e){if(this.disabledServers.has(e)){this.logger.log(`Server ${e} is already disabled`);return}this.disabledServers.add(e),this.logger.log(`Disabled server ${e} for this session`),this.isServerRunning(e)&&await this.stopServer(e),this.transport=null}async enableServer(e){if(!this.disabledServers.has(e)){this.logger.log(`Server ${e} is not disabled`);return}this.disabledServers.delete(e),this.logger.log(`Enabled server ${e} for this session`);let I=this.getServerConfig(e);I?await this.startServer(e,I):await this.startBuiltInServer(e),this.transport=null}async startBuiltInServer(e){}getServerConfig(e){return this.config.mcpServers[e]}};var WII=Ll(ZII(),1);async function Pat(t={}){let e=await _Ye();return KYe((0,WII.default)({},e,t))}async function NII(t={}){if(GU())throw new Error("Settings have already been initialized");return Pat(t)}import{promises as qat}from"fs";import YII from"path";var _at=3*1024*1024;function VII(t){let e=YII.extname(t).toLowerCase();return[".png",".jpg",".jpeg",".gif",".webp"].includes(e)}function $at(t){switch(YII.extname(t).toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";default:return null}}async function eot(t,e){e.debug(`Processing local image file: ${t}`);let I=await qat.readFile(t),l=$at(t);if(!l)throw new Error(`Unsupported image format: ${t}`);let n=new JB,c=await K8(e,n,_at,HB,l,I);if(!c)throw new Error(`Image too large or couldn't be processed: ${t}`);let r=c.toString("base64");return`data:${l};base64,${r}`}async function Iot(t,e,I){let l=Za();try{let n=await Ere({command:"view",path:t,view_range:void 0},{properties:{command:"view",resolvedPathAgainstCwd:"false",options:"{}",inputs:"[]"},metrics:{responseTokenLimit:void 0,resultLength:0,resultForLlmLength:0},restrictedProperties:{}},e,I);return{id:l,name:"view",arguments:{path:t},result:n.textResultForLlm||""}}catch(n){return{id:l,name:"view",arguments:{path:t},result:`Error reading ${t}: ${n}`}}}async function RII(t,e,I){let l=[],n=t.filter(r=>!VII(r.path));if(n.length===0)return l;let c=[];for(let r of n)try{let s=await Iot(r.path,e,I);c.push(s)}catch{}if(c.length>0){let r=c.map(s=>({id:s.id,type:"function",function:{name:s.name,arguments:JSON.stringify(s.arguments)}}));l.push({role:"assistant",content:"I need to read the content of those paths to answer this request.",tool_calls:r}),l.push(...c.map(s=>({role:"tool",tool_call_id:s.id,content:s.result})))}return l}async function yII(t,e){let I=t.filter(n=>VII(n.path));return(await Promise.all(I.map(async n=>{try{return{type:"image_url",image_url:{url:await eot(n.path,e)}}}catch(c){e.error(`Failed to process image ${n.path}: ${c instanceof Error?c.message:String(c)}`);return}}))).filter(n=>n!==void 0)}var tYe=class{constructor(e,I){this.logger=e;this.session=I}messageQueue=[];async*preRequest(e){this.logger.debug("ImmediatePromptProcessor: Injecting immediate prompts");let l=(await this.session.getChatMessages()).length;for(;this.messageQueue.length>0;){let r=this.messageQueue.shift();this.session.emit("user.message",{content:r.prompt,attachments:r.attachments})}let c=(await this.session.getChatMessages()).slice(l);for(let r of c)e.messages.push(r),yield{kind:"message",message:r,turn:e.turn,source:"immediate-prompt"}}addMessage(e){this.messageQueue.push(e)}toJSON(){return"ImmediatePromptProcessor"}},zp=class t{sessionId;startTime;modifiedTime;logger;events=[];_chatMessages=[];_selectedModel;eventProcessingQueue=Promise.resolve();eventHandlers={};wildcardEventHandlers=[];isProcessing=!1;messageQueue=[];immediatePromptProcessor;mcpHost;workingDir;abortController;modelProvider;allowedTools;disabledTools;requestPermission;mcpServers;hooks;hmacKey;copilotToken;constructor(e={},I={}){this.sessionId=I.sessionId||Za(),this.startTime=I.startTime||new Date,this.modifiedTime=I.modifiedTime||this.startTime,this.logger=e.logger||new dW,this.modelProvider=e.modelProvider,this.allowedTools=e.allowedTools,this.disabledTools=e.disabledTools,this.requestPermission=e.requestPermission,this.mcpServers=e.mcpServers,this.hooks=e.hooks,this.hmacKey=e.hmacKey,this.copilotToken=e.copilotToken,this.workingDir=e.workingDirectory||process.cwd(),this.immediatePromptProcessor=new tYe(this.logger,this),this.abortController=e.abortController||new AbortController,hZe(this.workingDir).then(l=>{if(l.found)return GPe(l.gitRoot,!0,this.workingDir)}).catch(l=>{this.logger.debug(`Failed to initialize custom instructions cache: ${l}`)})}get messageCount(){let e=this.events.find(l=>l.type==="session.import_legacy"),I=0;return e&&(I=(e.data.legacySession?.chatMessages||[]).filter(c=>c.role==="user"||c.role==="assistant").length),this.logger.debug(`Imported message count: ${I}`),this.events.filter(l=>l.type==="user.message"||l.type==="assistant.message").length+I}get summary(){let e=this.events.find(c=>c.type==="session.import_legacy"||c.type==="user.message"),I;if(e?.type==="session.import_legacy"){let c=e.data.legacySession.chatMessages.find(r=>r.role==="user");c?.content&&(typeof c.content=="string"?I=c.content:I=c.content.find(r=>r.type==="text")?.text)}else e?.type==="user.message"&&(I=e.data.content);if(!I)return;let l=I.lastIndexOf("<reminder>");l!==-1&&(I=I.substring(0,l).trim());let n=I.replace(/\s+/g," ").trim();return n.length>75&&(n=n.substring(0,55).trim()+"..."),n=n.split("").filter(c=>{let r=c.charCodeAt(0);return r>=32&&r!==127}).join(""),n}static async fromEvents(e,I={}){if(e.length===0)throw new Error("Cannot create session from empty events array");let l=e[0];if(l.type!=="session.start")throw new Error("First event must be session.start");let n=new t(I,{sessionId:l.data.sessionId,startTime:new Date(l.data.startTime)});n._selectedModel=l.data.selectedModel,n.events.push(l);for(let c=1;c<e.length;c++){let r=e[c];n.events.push(r),await n.processEventForState(r)}return n}on(e,I){return e==="*"?(this.wildcardEventHandlers.push(I),()=>{let l=this.wildcardEventHandlers.indexOf(I);l!==-1&&this.wildcardEventHandlers.splice(l,1)}):(this.eventHandlers[e]||(this.eventHandlers[e]=[]),this.eventHandlers[e].push(I),()=>{let l=this.eventHandlers[e];if(l){let n=l.indexOf(I);n!==-1&&l.splice(n,1)}})}emitInternal(e,I,l=!1){let n=Za(),c=new Date().toISOString(),r=this.getLastEventId(),s={type:e,data:I,id:n,timestamp:c,parentId:r,...l&&{ephemeral:l}};this.events.push(s),this.enqueueEventProcessing(()=>this.processEventForState(s)).catch(a=>{this.logger.error(`Error emitting event: ${a instanceof Error?a.message:String(a)}`)}).catch(a=>{this.logger.error(`Error emitting event ${a instanceof Error?a.message:String(a)}`)}),[...this.eventHandlers[s.type]||[],...this.wildcardEventHandlers].forEach(a=>{try{a(s)}catch(o){this.logger.error(`Error in event handler for event type ${s.type}: ${o instanceof Error?o.message:String(o)}`)}})}emit(e,I){this.emitInternal(e,I)}emitEphemeral(e,I){this.emitInternal(e,I,!0)}getEvents(){return this.events}async getChatMessages(){return this.enqueueEventProcessing(()=>this._chatMessages)}async getChatContextMessages(){return(await this.getChatMessages()).filter(I=>I.role!=="system")}async getSystemContextMessages(){return(await this.getChatMessages()).filter(I=>I.role==="system")}async getSelectedModel(){return this.enqueueEventProcessing(()=>this._selectedModel)}async setSelectedModel(e){let I=await this.getSelectedModel();this.emit("session.model_change",{previousModel:I,newModel:e})}getLastEventId(){return this.events.length===0?null:this.events[this.events.length-1].id}enqueueEventProcessing(e){let I=this.eventProcessingQueue.then(()=>e());return this.eventProcessingQueue=I,I}async processEventForState(e){switch(e.type){case"session.start":e.data.selectedModel&&(this._selectedModel=e.data.selectedModel);break;case"session.model_change":this._selectedModel=e.data.newModel;break;case"user.message":{let I=[],l=[];if(e.data.attachments&&e.data.attachments.length>0){let n=await yII(e.data.attachments,this.logger);I.push(...n);let c=await RII(e.data.attachments,{requestRequired:!1},this.logger);l.push(...c)}I.length>0?this._chatMessages.push({role:"user",content:[{type:"text",text:e.data.content},...I]}):this._chatMessages.push({role:"user",content:e.data.content}),l.length>0&&this._chatMessages.push(...l);break}case"assistant.message":{if(e.ephemeral||e.data.parentToolCallId)break;let I={role:"assistant",content:e.data.content||null};e.data.toolRequests&&e.data.toolRequests.length>0&&(I.tool_calls=e.data.toolRequests.map(l=>({id:l.toolCallId,type:"function",function:{name:l.name,arguments:typeof l.arguments=="string"?l.arguments:JSON.stringify(l.arguments)}}))),this._chatMessages.push(I);break}case"tool.execution_complete":{if(e.data.parentToolCallId)break;e.data.isUserRequested||this._chatMessages.push({role:"tool",tool_call_id:e.data.toolCallId,content:e.data.success?e.data.result?.content||"":e.data.error?.message||"Tool execution failed"});break}case"system.message":this._chatMessages.push({role:e.data.role,content:e.data.content,...e.data.name&&{name:e.data.name}});break;case"session.import_legacy":this._chatMessages=[...e.data.legacySession.chatMessages],e.data.legacySession.selectedModel&&(this._selectedModel=e.data.legacySession.selectedModel);break;case"abort":case"session.resume":this._chatMessages=tot(this._chatMessages,this.logger);break;case"session.idle":case"session.error":case"session.info":case"assistant.turn_start":case"assistant.turn_end":case"assistant.usage":case"tool.user_requested":case"tool.execution_start":case"tool.execution_partial_result":case"hook.start":case"hook.end":break;default:{let I=e;this.logger.error(`Unknown event type: ${I.type}`);break}}}async send(e,I={}){if((I.mode||"enqueue")==="immediate"&&this.isProcessing)this.immediatePromptProcessor.addMessage(e);else{if(this.messageQueue.push(e),this.isProcessing)return;for(this.isProcessing=!0,await this.initializeMcpHost();this.messageQueue.length>0;){let n=this.messageQueue.shift();await this.runAgenticLoop(n.prompt,n.attachments)}this.isProcessing=!1,this.emitEphemeral("session.idle",{})}}async abort(){this.abortController.abort()}async initializeMcpHost(){if(!this.mcpHost&&this.mcpServers&&Object.keys(this.mcpServers).length>0)try{this.mcpHost=new Y_(this.logger,{mcpServers:this.mcpServers},this.disabledTools),await this.mcpHost.startServers()}catch(e){this.logger.error(`Failed to initialize MCP host: ${e}`)}}async runAgenticLoop(e,I=[]){if(!this.modelProvider)throw new Error("Session must be created with modelProvider to use send/query methods");let l=new Map,n=new Map;try{let r=(await XW(this.hooks?.userPromptSubmitted,{timestamp:Date.now(),cwd:this.workingDir,prompt:e},this.logger))?.modifiedPrompt??e;this.emit("user.message",{content:eZe({problemStatement:r,capabilities:{}}),attachments:I});let a=new kF().setProblemStatement(r).setAgentModel(this.buildAgentModelString()).setGithubRepoName("copilot-sdk-session").setGithubRepoCommit("copilot-sdk-commit").setGithubRepoReadWrite(!1).setCopilotIntegrationId("copilot-developer-cli").setCopilotHmacKey(this.hmacKey).setCopilotToken(this.copilotToken).build();PYe();let o=await NII(a),G=o.service?.agent?.model,i=$8(G),d=i.agent,b=d??"sweagent-capi",m=i.model?{model:i.model}:void 0,h=Hbe(o,this.logger,d,m),u={location:this.workingDir,timeout:3e4,requireReasoning:!0,toolPartialResultCallback:(pe,Fe)=>{this.emitEphemeral("tool.execution_partial_result",{toolCallId:pe,partialOutput:Fe})},permissions:this.requestPermission?{requestRequired:!0,request:this.requestPermission}:{requestRequired:!1},shellConfig:(process.platform==="win32"?ab.powerShell:ab.bash).withScriptSafetyAssessor(async function(pe){return{result:"completed",commands:[{identifier:pe,readOnly:!1}],possiblePaths:[],hasWriteFileRedirection:!1,canOfferSessionApproval:!1}})},Z=await w8e(u,this.logger),N=[];if(this.mcpHost)try{N=await this.mcpHost.getTools(o,this.logger,u.permissions)}catch(pe){this.logger.error(`Failed to get MCP tools: ${pe}`)}let g=[...Z,...N].filter(pe=>this.allowedTools?this.allowedTools.includes(pe.name):this.disabledTools?!this.disabledTools.includes(pe.name):!0),y=await hZe(this.workingDir),f={...(E8e()[b]?.[h.model]??X8e()).supports,reasoning:!0},v=await h8e({location:y.found?y.gitRoot:"",version:fze(),currentWorkingDirectory:this.workingDir,parts:{},capabilities:f,toolConfigOverrides:u,tools:g,organizationCustomInstructions:void 0}),L=(await this.getChatMessages()).slice(0,-1),Ie={role:"user",content:eZe({customAgentPrompt:void 0,problemStatement:r,capabilities:f})},Ge=[...L,Ie];await XW(this.hooks?.sessionStart,{timestamp:Date.now(),cwd:this.workingDir,source:"new",initialPrompt:e},this.logger);let Qe=new av(Ie,this.logger),Ae=h.getCompletionWithTools(v,Ge,g,{failIfInitialInputsTooLong:!1,processors:{preRequest:[Qe,this.immediatePromptProcessor,new fB(this.logger)],onRequestError:[Qe]},executeToolsInParallel:!1,abortSignal:this.abortController.signal});for await(let pe of Ae){if(this.abortController.signal.aborted){this.emit("abort",{reason:"user initiated"});break}switch(pe.kind){case"message":{if(e7(pe)){let Fe=R8e(pe)?await Promise.all(pe.message.tool_calls.map(async me=>{let uI=bX(me.function.arguments);l.set(me.id,me.function.name),n.set(me.id,uI);let ve=await XW(this.hooks?.preToolUse,{timestamp:Date.now(),cwd:this.workingDir,toolName:me.function.name,toolArgs:uI},this.logger);return{toolCallId:me.id,name:me.function.name,arguments:ve?.modifiedArgs??uI}})):[];this.emit("assistant.message",{parentToolCallId:void 0,messageId:Za(),content:typeof pe.message.content=="string"?pe.message.content:"",toolRequests:Fe});for(let me of Fe)this.emit("tool.execution_start",{toolCallId:me.toolCallId,toolName:me.name,arguments:me.arguments})}else(pe.message.role==="system"||pe.message.role==="developer")&&this.emit("system.message",{role:pe.message.role,content:typeof pe.message.content=="string"?pe.message.content:JSON.stringify(pe.message.content),name:"name"in pe.message?pe.message.name:void 0});break}case"model_call_failure":{let Fe=new Error(pe.modelCall?.error||"Model call failed");await XW(this.hooks?.errorOccurred,{timestamp:Date.now(),cwd:this.workingDir,error:Fe,errorContext:"model_call",recoverable:!0},this.logger),this.emit("session.error",{errorType:"model_call",message:Fe.message,stack:Fe.stack});break}case"tool_execution":{let me=(await XW(this.hooks?.postToolUse,{timestamp:Date.now(),cwd:this.workingDir,toolName:l.get(pe.toolCallId)||"unknown",toolArgs:n.get(pe.toolCallId)||{},toolResult:pe.toolResult},this.logger))?.modifiedResult??pe.toolResult,uI=(me.resultType==="failure"?me.error:void 0)||me.sessionLog||me.textResultForLlm;this.emit("tool.execution_complete",{parentToolCallId:void 0,toolCallId:pe.toolCallId,success:me.resultType==="success",result:me.resultType==="success"?{content:uI}:void 0,error:me.resultType!=="success"?{message:uI,code:me.resultType}:void 0});break}case"turn_started":{this.emit("assistant.turn_start",{turnId:`${pe.turn}`});break}case"turn_ended":{this.emit("assistant.turn_end",{turnId:`${pe.turn}`});break}case"response":case"images_removed":case"image_processing":case"history_truncated":case"turn_failed":case"turn_retry":case"model_call_success":this.logger.debug(`Ignoring event of kind: ${pe.kind}`);break;default:bm(pe,"Unhandled event type")}}}catch(c){await XW(this.hooks?.sessionEnd,{timestamp:Date.now(),cwd:this.workingDir,reason:"error",error:c instanceof Error?c:new Error(String(c))},this.logger),this.emit("session.error",{errorType:"query",message:c instanceof Error?c.message:String(c),stack:c instanceof Error?c.stack:void 0})}finally{await XW(this.hooks?.sessionEnd,{timestamp:Date.now(),cwd:this.workingDir,reason:"complete"},this.logger)}}buildAgentModelString(){if(!this.modelProvider)throw new Error("Session must be created with modelProvider");switch(this.modelProvider.type){case"openai":return`openai:${this.modelProvider.model}`;case"anthropic":return`anthropic:${this.modelProvider.model}`;case"copilot":return`capi:${this.modelProvider.model}`;default:throw new Error(`Unsupported provider: ${this.modelProvider.type}`)}}};function tot(t,e){if(t.length===0)return t;let I=[],l=new Set,n=!1;for(let s=t.length-1;s>=0;s--){let a=t[s];if(a.role==="assistant"&&(n=!0),a.role==="assistant"&&"tool_calls"in a&&a.tool_calls&&a.tool_calls.length>0)for(let o of a.tool_calls)l.has(o.id)||I.push(o.id);else{if(n)break;a.role==="tool"&&a.tool_call_id&&l.add(a.tool_call_id)}}if(I.length===0)return t;let c="The execution of this tool, or a previous tool was interrupted.";e.info(`Completing ${I.length} orphaned tool calls.`);let r=I.map(s=>({role:"tool",tool_call_id:s,content:c}));return[...t,...r]}var X_=class{sessions;logger;options;lastAccessedSessionId;constructor(e){this.options=e,this.sessions=new Map,this.logger=e.logger||new dW}async createSession(){let e=new zp(this.options);return this.sessions.set(e.sessionId,e),this.lastAccessedSessionId=e.sessionId,e}async getSession(e){let I=this.sessions.get(e);return I&&(this.lastAccessedSessionId=e),I}async getLastSession(){if(this.lastAccessedSessionId){let l=this.sessions.get(this.lastAccessedSessionId);if(l)return l}let e=Array.from(this.sessions.values());if(e.length===0)return;e.sort((l,n)=>n.startTime.getTime()-l.startTime.getTime());let I=e[0];return this.lastAccessedSessionId=I.sessionId,I}async listSessions(){return Array.from(this.sessions.values()).map(e=>({sessionId:e.sessionId,startTime:e.startTime,modifiedTime:e.modifiedTime}))}async saveSession(e){}async deleteSession(e){this.sessions.delete(e.sessionId),this.lastAccessedSessionId===e.sessionId&&(this.lastAccessedSessionId=void 0)}async closeSession(e){}};var utI=Ll(ntI(),1);import{existsSync as K_}from"fs";import{appendFile as KGt,mkdir as PGt,readdir as P_,readFile as otI,stat as q_,writeFile as qGt}from"fs/promises";import{homedir as GtI}from"os";import{dirname as _Gt,join as FG}from"path";var OGt=new Error("timeout while waiting for mutex to become available"),eTl=new Error("mutex already locked"),MGt=new Error("request for lock canceled"),TGt=function(t,e,I,l){function n(c){return c instanceof I?c:new I(function(r){r(c)})}return new(I||(I=Promise))(function(c,r){function s(G){try{o(l.next(G))}catch(i){r(i)}}function a(G){try{o(l.throw(G))}catch(i){r(i)}}function o(G){G.done?c(G.value):n(G.value).then(s,a)}o((l=l.apply(t,e||[])).next())})},uYe=class{constructor(e,I=MGt){this._value=e,this._cancelError=I,this._queue=[],this._weightedWaiters=[]}acquire(e=1,I=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((l,n)=>{let c={resolve:l,reject:n,weight:e,priority:I},r=rtI(this._queue,s=>I<=s.priority);r===-1&&e<=this._value?this._dispatchItem(c):this._queue.splice(r+1,0,c)})}runExclusive(e){return TGt(this,arguments,void 0,function*(I,l=1,n=0){let[c,r]=yield this.acquire(l,n);try{return yield I(c)}finally{r()}})}waitForUnlock(e=1,I=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,I)?Promise.resolve():new Promise(l=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),jGt(this._weightedWaiters[e-1],{resolve:l,priority:I})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){let I=this._value;this._value-=e.weight,e.resolve([I,this._newReleaser(e.weight)])}_newReleaser(e){let I=!1;return()=>{I||(I=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){let I=this._weightedWaiters[e-1];I&&(I.forEach(l=>l.resolve()),this._weightedWaiters[e-1]=[])}else{let e=this._queue[0].priority;for(let I=this._value;I>0;I--){let l=this._weightedWaiters[I-1];if(!l)continue;let n=l.findIndex(c=>c.priority<=e);(n===-1?l:l.splice(0,n)).forEach(c=>c.resolve())}}}_couldLockImmediately(e,I){return(this._queue.length===0||this._queue[0].priority<I)&&e<=this._value}};function jGt(t,e){let I=rtI(t,l=>e.priority<=l.priority);t.splice(I+1,0,e)}function rtI(t,e){for(let I=t.length-1;I>=0;I--)if(e(t[I]))return I;return-1}var DGt=function(t,e,I,l){function n(c){return c instanceof I?c:new I(function(r){r(c)})}return new(I||(I=Promise))(function(c,r){function s(G){try{o(l.next(G))}catch(i){r(i)}}function a(G){try{o(l.throw(G))}catch(i){r(i)}}function o(G){G.done?c(G.value):n(G.value).then(s,a)}o((l=l.apply(t,e||[])).next())})},j_=class{constructor(e){this._semaphore=new uYe(1,e)}acquire(){return DGt(this,arguments,void 0,function*(e=0){let[,I]=yield this._semaphore.acquire(1,e);return I})}runExclusive(e,I=0){return this._semaphore.runExclusive(()=>e(),1,I)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}},ctI=function(t,e,I,l){function n(c){return c instanceof I?c:new I(function(r){r(c)})}return new(I||(I=Promise))(function(c,r){function s(G){try{o(l.next(G))}catch(i){r(i)}}function a(G){try{o(l.throw(G))}catch(i){r(i)}}function o(G){G.done?c(G.value):n(G.value).then(s,a)}o((l=l.apply(t,e||[])).next())})};function stI(t,e,I=OGt){return{acquire:(l,n)=>{let c;if(T_(t)?c=l:(c=void 0,n=l),c!==void 0&&c<=0)throw new Error(`invalid weight ${c}: must be positive`);return new Promise((r,s)=>ctI(this,void 0,void 0,function*(){let a=!1,o=setTimeout(()=>{a=!0,s(I)},e);try{let G=yield T_(t)?t.acquire(c,n):t.acquire(n);a?(Array.isArray(G)?G[1]:G)():(clearTimeout(o),r(G))}catch(G){a||(clearTimeout(o),s(G))}}))},runExclusive(l,n,c){return ctI(this,void 0,void 0,function*(){let r=()=>{};try{let s=yield this.acquire(n,c);return Array.isArray(s)?(r=s[1],yield l(s[0])):(r=s,yield l())}finally{r()}})},release(l){t.release(l)},cancel(){return t.cancel()},waitForUnlock:(l,n)=>{let c;if(T_(t)?c=l:(c=void 0,n=l),c!==void 0&&c<=0)throw new Error(`invalid weight ${c}: must be positive`);return new Promise((r,s)=>{let a=setTimeout(()=>s(I),e);(T_(t)?t.waitForUnlock(c,n):t.waitForUnlock(n)).then(()=>{clearTimeout(a),r()})})},isLocked:()=>t.isLocked(),getValue:()=>t.getValue(),setValue:l=>t.setValue(l)}}function T_(t){return t.getValue!==void 0}var D_=class{mutexes=new Map;async runExclusive(e,I,l=5e3){let n=this.mutexes.get(e);n||(n=new j_,n.refCount=0,this.mutexes.set(e,n));let c=n;try{return c.refCount++,await stI(n,l).runExclusive(I)}finally{--c.refCount===0&&this.mutexes.delete(e)}}};var ZYe=(I=>(I.DEFAULT="config",I.MCP="mcp",I))(ZYe||{});function atI(t){return Object.values(ZYe).includes(t)}var __=".copilot",$_=new D_;async function itI(t){let e=_Gt(t);try{await PGt(e,{recursive:!0,mode:448})}catch{}}async function $Gt(t,e){if(K_(t))try{let I={},l=await $_.runExclusive(t,()=>otI(t,"utf8"));return l.trim().startsWith("{")?I=JSON.parse(l):l.split(`
|
|
1463
1463
|
`).forEach(n=>{let[c,r]=n.split("=").map(s=>s.trim());c&&r&&(I[c]=r)}),e(I)}catch(I){throw new Error(`Failed to read configuration from ${t}: ${I}`)}}async function eit(t,e){try{await itI(t);let I=JSON.stringify(e,null,2);await $_.runExclusive(t,()=>qGt(t,I,{mode:384}))}catch(I){throw new Error(`Failed to write configuration to ${t}: ${I}`)}}var dtI=(t,e,{shouldCache:I})=>{let l=new Map,n=()=>{let d=atI(e)?process.env.XDG_CONFIG_HOME:process.env.XDG_STATE_HOME;return d?FG(d,__):FG(GtI(),__)},c=()=>{let d=atI(e)?"-config":"-state";return`${e}${e=="config"?"":d}`},r=d=>{let b=".json",m=c()+(d?"":b),h=FG(n(),m,d?`${d}${b}`:"");return!K_(h)&&K_(h.replace(/\.json$/,""))&&(h=h.replace(/\.json$/,"")),h},s=async()=>{let d=FG(n(),c());try{let m=(await P_(d,{withFileTypes:!0})).filter(u=>u.isFile()&&u.name.endsWith(".json")).map(u=>u.name),h=await Promise.all(m.map(async u=>{let Z=FG(d,u);try{let N=await q_(Z);return{file:u,mtime:N.mtime}}catch{return{file:u,mtime:new Date}}}));return h.sort((u,Z)=>Z.mtime.getTime()-u.mtime.getTime()),h.map(u=>u.file)}catch{}return[]},a=async()=>{let d=FG(n(),c());try{let m=(await P_(d,{withFileTypes:!0})).filter(u=>u.isFile()&&u.name.endsWith(".json")).map(u=>u.name),h=await Promise.all(m.map(async u=>{let Z=FG(d,u);try{let N=await q_(Z);return{file:u,mtime:N.mtime,birthtime:N.birthtime}}catch{return{file:u,mtime:new Date,birthtime:new Date}}}));return h.sort((u,Z)=>Z.mtime.getTime()-u.mtime.getTime()),h}catch{}return[]},o=async(d="")=>{if(I&&l.has(d))return l.get(d);let b=await $Gt(r(d),t);return I&&b&&l.set(d,b),b},G=async(d,b="")=>{I&&l.set(b,d),await eit(r(b),d)};return{load:o,write:G,writeKey:async(d,b,m)=>{let h=await o(m);if(b===void 0){h&&(delete h[d],await G(h,m));return}let u={[d]:b},Z;h?Z={...h,...u}:Z=u,await G(Z,m)},path:r,directoryFiles:s,directoryFilesWithMetadata:a}},btI=(t,e)=>dtI(t,e,{shouldCache:!0}),mtI=(t,e)=>dtI(t,e,{shouldCache:!1}),htI=(t,e)=>{let I=()=>{let o=process.env.XDG_STATE_HOME;return o?FG(o,__):FG(GtI(),__)},l=()=>`${e}-state`,n=o=>{let G=".jsonl",i=l()+(o?"":G);return FG(I(),i,o?`${o}${G}`:"")};return{load:async o=>{let G=n(o);if(!K_(G))return[];try{let d=(await $_.runExclusive(G,()=>otI(G,"utf8"))).trim().split(`
|
|
1464
1464
|
`).filter(m=>m.trim()),b=[];for(let m=0;m<d.length;m++)try{let h=JSON.parse(d[m]),u=t(h);b.push(u)}catch(h){throw new Error(`Invalid event at line ${m+1} in ${G}: ${h}`)}return b}catch(i){throw new Error(`Failed to read JSONL from ${G}: ${i}`)}},append:async(o,G)=>{let i=n(G),d=Array.isArray(o)?o:[o];try{await itI(i);let b=d.map(m=>JSON.stringify(m)).join(`
|
|
1465
1465
|
`)+`
|