@github/copilot 0.0.354-27 → 0.0.354-29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -2056,7 +2056,7 @@ cwd: ${a.cwd}`);try{let I={...a,env:r};await this.registry.startLocalMcpClient(e
2056
2056
  `)),s}}import{homedir as $jt}from"node:os";import S4n,{resolve as B4n}from"node:path";function sHn(t){return t.length>0&&/^[0-9a-zA-Z_-]+$/.test(t)}function QPt(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 wPt=h0(["none","markdown","hidden_characters"]),FPt=zl({tools:Od(Qt()),type:Qt().optional(),isDefaultServer:ro().optional(),filterMapping:rY(Qt(),wPt).or(wPt).optional(),timeout:Pm().positive().optional()}),oHn=FPt.extend({type:pr("local").optional(),command:Qt(),args:Od(Qt()),env:rY(Qt(),Qt()).optional()}),iHn=FPt.extend({type:pr("http").or(pr("sse")),url:Qt(),headers:rY(Qt(),Qt()).optional()}),I7e=zl({mcpServers:rY(Qt().min(1,"MCP server name cannot be empty").refine(sHn,{message:"MCP server name must only contain alphanumeric characters, underscores, and hyphens"}),oHn.or(iHn))}),uY=_we(I7e.parse,"mcp");function CPt(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 cHn(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 fPt=["#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 dHn(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 uHn(t){return t<0||t>=fPt.length?{r:0,g:0,b:0}:dHn(fPt[t])}function vPt(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:")?cHn(l):null}async function mHn(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(vPt(c));return}let o=l.match(/11;rgb:([0-9a-f/]+)(?:\x07|\x1b\\|\x9c)/i);if(o){r(),e(vPt(`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 bHn(){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:uHn(n)}async function HPt(){try{let t=await mHn();if(t)return CPt(t).l<.5;let e=bHn();return e?CPt(e).l<.5:!0}catch{return!0}}var XPt={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"},GHn={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 s7e(t){return t==="auto"||t==="dark"||t==="light"}function tQe(t){switch(t){case"dark":return XPt;case"light":return GHn;default:return XPt}}var lQe=await HPt();async function nQe(){let e=(await Sr.load())?.theme||"";return s7e(e)?e:"auto"}async function kPt(t){await Sr.writeKey("theme",t)}var LPt=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(`
2057
2057
  `).map(d=>d.startsWith(I)?d.slice(I.length):d).join(`
2058
2058
  `)),s.trimEnd()},listitem:r=>e(r.trimEnd()),reflowText:!0,showSectionPrefix:!1,unescape:!0,emoji:!0,tab:2,tableOptions:{style:{compact:!1}}}},pHn=LPt(!0),hHn=LPt(!1);function JPt(t){return t==="light"?hHn:pHn}import{exec as L4n}from"node:child_process";import*as L7e from"node:os";import{promisify as J4n}from"node:util";async function TL(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{existsSync as g4n}from"fs";import{unlink as w7e}from"fs/promises";import{join as Z4n}from"path";import{execFile as AHn}from"node:child_process";import{normalize as gHn}from"node:path";import{promisify as ZHn}from"node:util";var ome=ZHn(AHn);async function mY(t=process.cwd()){try{let l=(await ome("git",["rev-parse","--show-toplevel"],{cwd:t,encoding:"utf8",timeout:5e3,maxBuffer:1048576})).stdout.trim();if(l)return{gitRoot:gHn(l),found:!0}}catch{}return{gitRoot:t,found:!1}}async function xPt(t){let{stdout:e}=await ome("git",["-C",t,"remote","-v"],{encoding:"utf8",timeout:5e3,maxBuffer:1048576}),l=e.trim().split(`
2059
- `),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 SPt(t){try{let{stdout:e}=await ome("git",["status","--porcelain"],{cwd:t,encoding:"utf8",timeout:5e3,maxBuffer:1048576});return e.trim().length>0}catch{return!1}}async function BPt(t){try{let{stdout:e}=await ome("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:t,encoding:"utf8",timeout:5e3,maxBuffer:1048576}),l=e.trim();if(l==="HEAD"){let{stdout:n}=await ome("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 rQe=$e($t(),1);function TPt(t,e,l,n){let[r,a]=(0,rQe.useState)();return(0,rQe.useEffect)(()=>{async function I(){if(!l)return;let s=await ime(t,e,l,n);a(s)}I()},[l,e,n]),{models:r}}async function ime(t,e,l,n){if(BL())return{type:"success",list:[]};try{if(l.type==="hmac")return{type:"success",list:await QT.createWithHmac(t,Dte,n,l.hmac,e).listModels()};let r=await Qg(l);if(!r)return{type:"noauth"};let a=await dN(l.host,r,t);return{type:"success",list:await QT.createWithOAuthToken(t,a,n,r,e).listModels()}}catch(r){return{type:"error",error:r}}}var Ajt=$e(hjt(),1);async function m5n(t={}){let e=await tZt();return rZt((0,Ajt.default)({},e,t))}async function Gme(t={}){if(GD())throw new Error("Settings have already been initialized");return m5n(t)}import{promises as b5n}from"fs";import gjt from"path";var G5n=3*1024*1024;function Zjt(t){let e=gjt.extname(t).toLowerCase();return[".png",".jpg",".jpeg",".gif",".webp"].includes(e)}function p5n(t){switch(gjt.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 h5n(t,e){e.debug(`Processing local image file: ${t}`);let l=await b5n.readFile(t),n=p5n(t);if(!n)throw new Error(`Unsupported image format: ${t}`);let r=new Ioe,a=await h0e(e,r,G5n,noe,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 A5n(t,e,l){let n=km();try{let r=await YBe({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 Njt(t,e,l){let n=[],r=t.filter(I=>!Zjt(I.path));if(r.length===0)return n;let a=[];for(let I of r)try{let s=await A5n(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 Wjt(t,e){let l=t.filter(r=>Zjt(r.path));return(await Promise.all(l.map(async r=>{try{return{type:"image_url",image_url:{url:await h5n(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 yjt="copilot-developer-cli",g5n=nZe(dN),A7e=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"}},hO=class t{sessionId;startTime;modifiedTime;logger;events=[];_chatMessages=[];_selectedModel;eventProcessingQueue=Promise.resolve();eventHandlers={};wildcardEventHandlers=[];isProcessing=!1;messageQueue=[];immediatePromptProcessor;mcpHost;workingDir;abortController;allowedTools;disabledTools;requestPermission;mcpServers;hooks;authInfo;constructor(e={}){this.sessionId=e.sessionId||km(),this.startTime=e.startTime||new Date,this.modifiedTime=e.modifiedTime||this.startTime,this.logger=e.logger||new xd,this._selectedModel=e.model,this.allowedTools=e.allowedTools,this.disabledTools=e.disabledTools,this.requestPermission=e.requestPermission,this.mcpServers=e.mcpServers,this.hooks=e.hooks,this.authInfo=e.authInfo,this.workingDir=e.workingDirectory||process.cwd(),this.immediatePromptProcessor=new A7e(this.logger,this),mY(this.workingDir).then(l=>{if(l.found)return JEe(l.gitRoot,!0,this.workingDir)}).catch(l=>{this.logger.debug(`Failed to initialize custom instructions cache: ${l}`)})}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=km(),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 Wjt(e.data.attachments,this.logger);l.push(...r);let a=await Njt(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=Z5n(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){if(e.mode==="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 l=this.messageQueue.shift();this.abortController=l.abortController||new AbortController,await this.runAgenticLoop(l.prompt,l.attachments)}this.isProcessing=!1,this.emitEphemeral("session.idle",{})}}async abort(){this.abortController?.abort()}setAuthInfo(e){this.authInfo=e}async initializeMcpHost(){if(!this.mcpHost&&this.mcpServers&&Object.keys(this.mcpServers).length>0)try{this.mcpHost=new kL(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.authInfo)throw new Error("Session was not created with authentication info");let n=new Map,r=new Map;try{let I=(await TL(this.hooks?.userPromptSubmitted,{timestamp:Date.now(),cwd:this.workingDir,prompt:e},this.logger))?.modifiedPrompt??e;this.emit("user.message",{content:kB({problemStatement:I,capabilities:{}}),attachments:l});let s=await Qg(this.authInfo),o=this.authInfo.type!=="hmac"?await g5n(this.authInfo.host,s||"",this.logger):void 0,c=await ime(this.logger,this.sessionId,this.authInfo,yjt);if(c.type!=="success")throw new Error("Failed to list available models");let d=await Vv(this._selectedModel,this,c.list,this.logger);if(!d)throw new Error("No available models found. Please check your Copilot license and permissions.");let b=new zX().setProblemStatement(I).setAgentModel(`capi:${d}`).setGithubRepoName("copilot-sdk-session").setGithubRepoCommit("copilot-sdk-commit").setGithubRepoReadWrite(!1).setCopilotIntegrationId(yjt).setCopilotUrl(o).setGithubToken(s).build();Cx();let p=await Gme(b),A=p.service?.agent?.model,Z=SB(A),W=Z.agent,R=W??"sweagent-capi",V=Z.model?{model:Z.model}:void 0,f=Dde(p,this.logger,W,V),X={location:this.workingDir,timeout:3e4,requireReasoning:!0,toolPartialResultCallback:(Ge,me)=>{this.emitEphemeral("tool.execution_partial_result",{toolCallId:Ge,partialOutput:me})},permissions:this.requestPermission?{requestRequired:!0,request:this.requestPermission}:{requestRequired:!1},shellConfig:(process.platform==="win32"?bp.powerShell:bp.bash).withScriptSafetyAssessor(async function(Ge){return{result:"completed",commands:[{identifier:Ge,readOnly:!1}],possiblePaths:[],hasWriteFileRedirection:!1,canOfferSessionApproval:!1}})},S=await aVe(X,this.logger),U=[];if(this.mcpHost)try{U=await this.mcpHost.getTools(p,this.logger,X.permissions)}catch(Ge){this.logger.error(`Failed to get MCP tools: ${Ge}`)}let T=[...S,...U].filter(Ge=>this.allowedTools?this.allowedTools.includes(Ge.name):this.disabledTools?!this.disabledTools.includes(Ge.name):!0),j=await mY(this.workingDir),z={...(_8()[R]?.[f.model]??M8()).supports,reasoning:!0},ae=await g6({location:j.found?j.gitRoot:"",version:bL(),currentWorkingDirectory:this.workingDir,parts:{},capabilities:z,toolConfigOverrides:X,tools:T,organizationCustomInstructions:void 0}),he=await this.getChatMessages(),We=he.findLastIndex(Ge=>Ge.role==="user"),K=he.filter(Ge=>Ge.role==="user").at(-1);if(!K)throw new Error("No user message found in session messages after sending prompt");typeof K.content=="string"?K={...K,content:kB({customAgentPrompt:void 0,problemStatement:K.content,capabilities:z})}:K={...K,content:K.content.map(Ge=>Ge.type==="text"?{...Ge,text:kB({customAgentPrompt:void 0,problemStatement:Ge.text,capabilities:z})}:Ge)};let O=he.map((Ge,me)=>me===We?K:Ge);await TL(this.hooks?.sessionStart,{timestamp:Date.now(),cwd:this.workingDir,source:"new",initialPrompt:e},this.logger);let se=new q4(K,this.logger),Ie=f.getCompletionWithTools(ae,O,T,{failIfInitialInputsTooLong:!1,processors:{preRequest:[se,this.immediatePromptProcessor,new FT(this.logger)],onRequestError:[se]},executeToolsInParallel:!1,abortSignal:this.abortController?.signal});for await(let Ge of Ie){if(this.abortController?.signal.aborted){this.emit("abort",{reason:"user initiated"});break}switch(Ge.kind){case"message":{if(hL(Ge)){let me=U8(Ge)?await Promise.all(Ge.message.tool_calls.map(async Qe=>{let Re=lL(Qe.function.arguments);n.set(Qe.id,Qe.function.name),r.set(Qe.id,Re);let Ae=await TL(this.hooks?.preToolUse,{timestamp:Date.now(),cwd:this.workingDir,toolName:Qe.function.name,toolArgs:Re},this.logger);return{toolCallId:Qe.id,name:Qe.function.name,arguments:Ae?.modifiedArgs??Re}})):[];this.emit("assistant.message",{parentToolCallId:void 0,messageId:km(),content:typeof Ge.message.content=="string"?Ge.message.content:"",toolRequests:me});for(let Qe of me)this.emit("tool.execution_start",{toolCallId:Qe.toolCallId,toolName:Qe.name,arguments:Qe.arguments})}else(Ge.message.role==="system"||Ge.message.role==="developer")&&this.emit("system.message",{role:Ge.message.role,content:typeof Ge.message.content=="string"?Ge.message.content:JSON.stringify(Ge.message.content),name:"name"in Ge.message?Ge.message.name:void 0});break}case"model_call_failure":{let me=new Error(Ge.modelCall?.error||"Model call failed");await TL(this.hooks?.errorOccurred,{timestamp:Date.now(),cwd:this.workingDir,error:me,errorContext:"model_call",recoverable:!0},this.logger),this.emit("session.error",{errorType:"model_call",message:me.message,stack:me.stack});break}case"tool_execution":{let Qe=(await TL(this.hooks?.postToolUse,{timestamp:Date.now(),cwd:this.workingDir,toolName:n.get(Ge.toolCallId)||"unknown",toolArgs:r.get(Ge.toolCallId)||{},toolResult:Ge.toolResult},this.logger))?.modifiedResult??Ge.toolResult,Re=(Qe.resultType==="failure"?Qe.error:void 0)||Qe.sessionLog||Qe.textResultForLlm;this.emit("tool.execution_complete",{parentToolCallId:void 0,toolCallId:Ge.toolCallId,success:Qe.resultType==="success",result:Qe.resultType==="success"?{content:Re}:void 0,error:Qe.resultType!=="success"?{message:Re,code:Qe.resultType}:void 0});break}case"turn_started":{this.emit("assistant.turn_start",{turnId:`${Ge.turn}`});break}case"turn_ended":{this.emit("assistant.turn_end",{turnId:`${Ge.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: ${Ge.kind}`);break;default:wo(Ge,"Unhandled event type")}}}catch(a){await TL(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 TL(this.hooks?.sessionEnd,{timestamp:Date.now(),cwd:this.workingDir,reason:"complete"},this.logger)}}};function Z5n(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 Xq=zl({command:Qt(),description:Qt(),timeout:Pm().optional(),sessionId:Qt().optional(),async:ro().optional()}),g7e=zl({sessionId:Qt(),input:Qt(),delay:Pm().optional()}),Z7e=zl({sessionId:Qt(),delay:Pm()}),N7e=zl({sessionId:Qt()}),Ejt=Oh([Xq,g7e,Z7e,N7e]),N5n=zl({command:pr("view"),path:Qt(),view_range:dVe([Pm(),Pm()]).optional()}),W5n=zl({command:pr("create"),path:Qt(),file_text:Qt()}),y5n=zl({command:pr("str_replace"),path:Qt(),new_str:Qt().optional(),old_str:Qt()}),E5n=zl({command:pr("insert"),path:Qt(),insert_line:Pm(),new_str:Qt()}),W7e=$de("command",[N5n,W5n,y5n,E5n]),y7e=zl({path:Qt(),view_range:dVe([Pm(),Pm()]).optional()}),E7e=zl({path:Qt(),file_text:Qt()}),R7e=zl({path:Qt(),old_str:Qt(),new_str:Qt().optional()}),Y7e=Oh([Ejt,W7e,Bw()]),Rjt=(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 Yjt(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 AO=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 pme=zl({type:pr("text"),text:Qt()}),R5n=zl({type:pr("refusal"),refusal:Qt()}),Y5n=zl({type:pr("image_url"),image_url:zl({url:Qt(),detail:h0(["auto","low","high"]).optional()})}),V5n=zl({type:pr("input_audio"),input_audio:zl({data:Qt(),format:pr("wav").or(pr("mp3"))})}),w5n=zl({type:pr("file"),file:zl({file_date:Qt().optional(),file_id:Qt().optional(),filename:Qt().optional()})}),Q5n=Oh([pme,Y5n,V5n,w5n]),F5n=zl({name:Qt(),arguments:Qt()}),C5n=zl({name:Qt(),input:Qt()}),f5n=zl({id:Qt(),type:pr("function"),function:F5n}),v5n=zl({id:Qt(),type:pr("custom"),custom:C5n}),H5n=Oh([f5n,v5n]),X5n=zl({name:Qt(),arguments:Qt()}),k5n=zl({id:Qt()}),L5n=zl({content:Oh([Qt(),Od(pme)]),role:pr("developer"),name:Qt().optional()}),J5n=zl({content:Oh([Qt(),Od(pme)]),role:pr("system"),name:Qt().optional()}),x5n=zl({content:Oh([Qt(),Od(Q5n)]),role:pr("user"),name:Qt().optional()}),S5n=zl({content:Oh([Qt(),Od(Oh([pme,R5n]))]).nullable().optional(),role:pr("assistant"),name:Qt().optional(),refusal:Qt().nullable().optional(),audio:k5n.nullable().optional(),function_call:X5n.nullable().optional(),tool_calls:Od(H5n).optional()}),B5n=zl({content:Oh([Qt(),Od(pme)]),role:pr("tool"),tool_call_id:Qt()}),T5n=zl({content:Qt().nullable(),role:pr("function"),name:Qt()}),O5n=Oh([L5n,J5n,x5n,S5n,B5n,T5n]),U5n=zl({type:pr("copilot"),text:Qt(),isStreaming:ro().optional()}),M5n=zl({type:pr("error"),text:Qt()}),_5n=zl({type:pr("info"),text:Qt()}),D5n=zl({type:pr("user"),text:Qt()}),z5n=zl({type:pr("tool_call_requested"),callId:Qt(),name:Qt(),toolTitle:Qt().optional(),intentionSummary:Qt().nullable(),arguments:Y7e,partialOutput:Qt().optional(),isHidden:ro().optional(),isAlwaysExpanded:ro().optional(),showNoContent:ro().optional()}),P5n=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:Y7e,isHidden:ro().optional(),isAlwaysExpanded:ro().optional(),showNoContent:ro().optional()}),j5n=Oh([U5n,M5n,_5n,D5n,z5n,P5n]),K5n=j5n.and(zl({id:Qt(),timestamp:uVe.date()})),V7e=zl({sessionId:Qt(),startTime:uVe.date(),chatMessages:Od(O5n),timeline:Od(K5n),selectedModel:h0(Yv).optional()}),OL=Dwe(V7e.parse,"history-session");var Km=zl({id:Qt().uuid(),timestamp:Qt().datetime(),parentId:Qt().uuid().nullable(),ephemeral:ro().optional()}),Vjt=zl({parentToolCallId:Qt().optional()}),q5n=Km.extend({type:pr("session.start"),data:zl({sessionId:Qt(),version:Pm(),producer:Qt(),copilotVersion:Qt(),startTime:Qt().datetime(),selectedModel:Qt().optional()})}),$5n=Km.extend({type:pr("session.resume"),data:zl({resumeTime:Qt().datetime(),eventCount:Pm()})}),e4n=Km.extend({type:pr("session.error"),data:zl({errorType:Qt(),message:Qt(),stack:Qt().optional()})}),t4n=Km.extend({type:pr("session.info"),data:zl({infoType:Qt(),message:Qt()})}),l4n=Km.extend({type:pr("session.model_change"),data:zl({previousModel:Qt().optional(),newModel:Qt()})}),n4n=Km.extend({type:pr("session.import_legacy"),data:zl({legacySession:V7e,importTime:Qt().datetime(),sourceFile:Qt()})}),r4n=Km.extend({type:pr("session.idle"),ephemeral:pr(!0),data:zl({})}),a4n=zl({type:h0(["file","directory"]),path:Qt(),displayName:Qt()}),I4n=Km.extend({type:pr("user.message"),data:zl({content:Qt(),attachments:Od(a4n).optional()})}),s4n=Km.extend({type:pr("assistant.turn_start"),data:zl({turnId:Qt()})}),o4n=Km.extend({type:pr("assistant.message"),data:zl({messageId:Qt(),content:Qt(),toolRequests:Od(zl({toolCallId:Qt(),name:Qt(),arguments:Bw()})).optional()}).merge(Vjt)}),i4n=Km.extend({type:pr("assistant.turn_end"),data:zl({turnId:Qt()})}),c4n=Km.extend({type:pr("assistant.usage"),ephemeral:pr(!0),data:zl({model:Qt().optional(),inputTokens:Pm().optional(),outputTokens:Pm().optional(),cost:Pm().optional(),duration:Pm().optional(),initiator:Qt().optional()})}),d4n=Km.extend({type:pr("abort"),data:zl({reason:Qt()})}),u4n=Km.extend({type:pr("tool.user_requested"),data:zl({toolCallId:Qt(),toolName:Qt(),arguments:Bw()})}),m4n=Km.extend({type:pr("tool.execution_start"),data:zl({toolCallId:Qt(),toolName:Qt(),arguments:Bw()})}),b4n=Km.extend({type:pr("tool.execution_partial_result"),ephemeral:pr(!0),data:zl({toolCallId:Qt(),partialOutput:Qt()})}),G4n=Km.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(Vjt)}),p4n=Km.extend({type:pr("hook.start"),data:zl({hookInvocationId:Qt(),hookType:Qt(),input:Bw()})}),h4n=Km.extend({type:pr("hook.end"),data:zl({hookInvocationId:Qt(),hookType:Qt(),output:Bw(),success:ro(),error:zl({message:Qt(),stack:Qt().optional()}).optional()})}),A4n=Km.extend({type:pr("system.message"),data:zl({content:Qt(),role:h0(["system","developer"]),name:Qt().optional(),metadata:zl({promptVersion:Qt().optional(),variables:rY(Bw()).optional()}).optional()})}),wjt=$de("type",[q5n,$5n,e4n,r4n,t4n,l4n,n4n,I4n,s4n,o4n,i4n,c4n,d4n,u4n,m4n,b4n,G4n,p4n,h4n,A4n]);var UL=dPt(wjt.parse,"session");var mQe=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 UL.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 w7e(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())}}};function Qjt(t){if(t.role==="user")return typeof t.content=="string"?t.content:t.content.find(e=>e.type==="text")?.text}async function N4n(t){if(g4n(t))try{return await lNt(t,e=>{if(e.trim())try{let l=JSON.parse(e);if(l.type==="session.import_legacy"){let n=l.data.legacySession.chatMessages.find(r=>r.role==="user");if(n?.content){let r=Qjt(n);if(r)return Q7e(r)}}if(l.type==="user.message"){let n=l.data.content;if(n)return Q7e(n)}return}catch{return}})}catch{return}}function Q7e(t){let e=t.lastIndexOf("<reminder>");e!==-1&&(t=t.substring(0,e).trim());let l=t.replace(/\s+/g," ").trim();return l.length>75&&(l=l.substring(0,55).trim()+"..."),l=l.split("").filter(n=>{let r=n.charCodeAt(0);return r>=32&&r!==127}).join(""),l}var bQe=class{sessionWriters={};copilotVersion;flushDebounceMs;logger;constructor({version:e,flushDebounceMs:l,...n}){this.logger=n.logger||new xd,this.copilotVersion=e||"unknown",this.flushDebounceMs=l||100}async createSession(e){let l=new hO({...e,startTime:e?.startTime||new Date});return this.sessionWriters[l.sessionId]=new mQe(l,this.logger,this.flushDebounceMs),l.emit("session.start",{sessionId:l.sessionId,version:1,producer:"copilot-agent",copilotVersion:this.copilotVersion,startTime:l.startTime.toISOString(),selectedModel:e?.model}),l}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.sessionId]||(this.sessionWriters[e.sessionId]=new mQe(n,this.logger,this.flushDebounceMs,!0,r)),l&&n.emit("session.resume",{resumeTime:new Date().toISOString(),eventCount:n.getEvents().length}),n}async getLastSession(e={}){let l=await this.listSessions();if(l.length===0)return;l.sort((r,a)=>a.modifiedTime.getTime()-r.modifiedTime.getTime());let n=l[0].sessionId;return await this.getSession({...e,sessionId:n})}async saveSession(e){await this.sessionWriters[e.sessionId]?.flush()}async loadSession(e){let l=await UL.load(e.sessionId);return await hO.fromEvents(l,e)}async loadLegacySession(e){let n=(await OL.directoryFiles()).filter(o=>{let c=o.match(/^session_(.+)_(\d+)\.json$/);return c&&c[1]===e.sessionId});if(n.length===0)throw new Error(`Legacy session ${e.sessionId} not found`);let r=n[0];n.length>1&&this.logger.info(`Multiple legacy sessions found for ${e.sessionId}, using newest`);let a=await OL.load(r);if(!a)throw new Error(`Failed to load legacy session from ${r}`);let I=new Date(a.startTime),s=new hO({...e,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.sessionId} from ${r}`),{session:s,legacySourceFile:OL.path(r.replace(/\.json$/,""))}}async listSessions(){let e=await UL.directoryFilesWithMetadata(),l=await OL.directoryFilesWithMetadata(),n=await Promise.all(e.map(async I=>{let s=I.file.replace(".jsonl",""),o=UL.path(s),c=await N4n(o);return{sessionId:s,startTime:I.birthtime,modifiedTime:I.mtime,summary:c}})),r=(await Promise.all(l.map(async I=>{let s=I.file.match(/^session_(.+)_(\d+)\.json$/);if(!s)return null;let o=s[1],c;try{let d=await OL.load(I.file.replace(/\.json$/,""));if(d){let m=d.chatMessages?.find(b=>b.role==="user");if(m?.content){let b=Qjt(m);b&&(c=Q7e(b))}}}catch{}return{sessionId:o,startTime:I.birthtime,modifiedTime:I.mtime,summary:c}}))).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 deleteSession(e){await this.closeSession(e);let l=UL.path(e);try{await w7e(l),this.logger.info(`Deleted session file ${l}`);return}catch{let a=(await OL.directoryFiles()).filter(I=>{let s=I.match(/^session_(.+)_(\d+)\.json$/);return s&&s[1]===e});if(a.length===0)throw new Error(`Session file not found for ${e}`);for(let I of a){let s=OL.path(I.replace(/\.json$/,""));this.logger.info(`Deleting legacy session file ${s}`),await w7e(s)}}}async closeSession(e){this.logger.info(`Closing session ${e}`);let l=this.sessionWriters[e];l&&(await l.flush(),l.dispose(),delete this.sessionWriters[e])}getSessionsDirectory(){return Z4n(UL.home(),UL.directory())}setLogger(e){this.logger=e}};function _c(t){return t()}var hme;function y4n(t,e){return t.includes("\x1B[?")&&t.includes(e)}async function E4n(t){let e=process.stdin.isRaw;e||process.stdin.setRawMode(!0);try{return await t()}finally{e||process.stdin.setRawMode(!1)}}function Fjt(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(),y4n(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 R4n(){return!(!(process.stdin.isTTY&&process.stdout.isTTY)||!await Fjt("?u","u",200)||!await Fjt("c","c",1e3))}async function fjt(){hme===void 0&&(hme=await E4n(R4n),hme===!0&&(Y4n(),process.on("exit",Cjt),process.on("SIGTERM",Cjt)))}function Y4n(){process.stdout.write("\x1B[>1u")}function Cjt(){process.stdout.write("\x1B[<u"),hme=void 0}function GQe(){return hme===!0}function gme(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 b(f,X){let S=0,U=0;for(;S<f||!X;){let T=t.charCodeAt(n);if(T>=48&&T<=57)U=U*16+T-48;else if(T>=65&&T<=70)U=U*16+T-65+10;else if(T>=97&&T<=102)U=U*16+T-97+10;else break;n++,S++}return S<f&&(U=-1),U}function p(f){n=f,r="",a=0,I=16,m=0}function A(){let f=n;if(t.charCodeAt(n)===48)n++;else for(n++;n<t.length&&kq(t.charCodeAt(n));)n++;if(n<t.length&&t.charCodeAt(n)===46)if(n++,n<t.length&&kq(t.charCodeAt(n)))for(n++;n<t.length&&kq(t.charCodeAt(n));)n++;else return m=3,t.substring(f,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&&kq(t.charCodeAt(n))){for(n++;n<t.length&&kq(t.charCodeAt(n));)n++;X=n}else m=3;return t.substring(f,X)}function Z(){let f="",X=n;for(;;){if(n>=l){f+=t.substring(X,n),m=2;break}let S=t.charCodeAt(n);if(S===34){f+=t.substring(X,n),n++;break}if(S===92){if(f+=t.substring(X,n),n++,n>=l){m=2;break}switch(t.charCodeAt(n++)){case 34:f+='"';break;case 92:f+="\\";break;case 47:f+="/";break;case 98:f+="\b";break;case 102:f+="\f";break;case 110:f+=`
2059
+ `),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 SPt(t){try{let{stdout:e}=await ome("git",["status","--porcelain"],{cwd:t,encoding:"utf8",timeout:5e3,maxBuffer:1048576});return e.trim().length>0}catch{return!1}}async function BPt(t){try{let{stdout:e}=await ome("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:t,encoding:"utf8",timeout:5e3,maxBuffer:1048576}),l=e.trim();if(l==="HEAD"){let{stdout:n}=await ome("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 rQe=$e($t(),1);function TPt(t,e,l,n){let[r,a]=(0,rQe.useState)();return(0,rQe.useEffect)(()=>{async function I(){if(!l)return;let s=await ime(t,e,l,n);a(s)}I()},[l,e,n]),{models:r}}async function ime(t,e,l,n){if(BL())return{type:"success",list:[]};try{if(l.type==="hmac")return{type:"success",list:await QT.createWithHmac(t,Dte,n,l.hmac,e).listModels()};let r=await Qg(l);if(!r)return{type:"noauth"};let a=await dN(l.host,r,t);return{type:"success",list:await QT.createWithOAuthToken(t,a,n,r,e).listModels()}}catch(r){return{type:"error",error:r}}}var Ajt=$e(hjt(),1);async function m5n(t={}){let e=await tZt();return rZt((0,Ajt.default)({},e,t))}async function Gme(t={}){if(GD())throw new Error("Settings have already been initialized");return m5n(t)}import{promises as b5n}from"fs";import gjt from"path";var G5n=3*1024*1024;function Zjt(t){let e=gjt.extname(t).toLowerCase();return[".png",".jpg",".jpeg",".gif",".webp"].includes(e)}function p5n(t){switch(gjt.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 h5n(t,e){e.debug(`Processing local image file: ${t}`);let l=await b5n.readFile(t),n=p5n(t);if(!n)throw new Error(`Unsupported image format: ${t}`);let r=new Ioe,a=await h0e(e,r,G5n,noe,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 A5n(t,e,l){let n=km();try{let r=await YBe({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 Njt(t,e,l){let n=[],r=t.filter(I=>!Zjt(I.path));if(r.length===0)return n;let a=[];for(let I of r)try{let s=await A5n(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 Wjt(t,e){let l=t.filter(r=>Zjt(r.path));return(await Promise.all(l.map(async r=>{try{return{type:"image_url",image_url:{url:await h5n(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 yjt="copilot-developer-cli",g5n=nZe(dN),A7e=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"}},hO=class t{sessionId;startTime;modifiedTime;logger;events=[];_chatMessages=[];_selectedModel;eventProcessingQueue=Promise.resolve();eventHandlers={};wildcardEventHandlers=[];isProcessing=!1;messageQueue=[];immediatePromptProcessor;mcpHost;workingDir;abortController;allowedTools;disabledTools;requestPermission;mcpServers;hooks;authInfo;constructor(e={}){this.sessionId=e.sessionId||km(),this.startTime=e.startTime||new Date,this.modifiedTime=e.modifiedTime||this.startTime,this.logger=e.logger||new xd,this._selectedModel=e.model,this.allowedTools=e.allowedTools,this.disabledTools=e.disabledTools,this.requestPermission=e.requestPermission,this.mcpServers=e.mcpServers,this.hooks=e.hooks,this.authInfo=e.authInfo,this.workingDir=e.workingDirectory||process.cwd(),this.immediatePromptProcessor=new A7e(this.logger,this),mY(this.workingDir).then(l=>{if(l.found)return JEe(l.gitRoot,!0,this.workingDir)}).catch(l=>{this.logger.debug(`Failed to initialize custom instructions cache: ${l}`)})}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=km(),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 Wjt(e.data.attachments,this.logger);l.push(...r);let a=await Njt(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=Z5n(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){if(e.mode==="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 l=this.messageQueue.shift();this.abortController=l.abortController||new AbortController,await this.runAgenticLoop(l.prompt,l.attachments)}this.isProcessing=!1,this.emitEphemeral("session.idle",{})}}async abort(){this.abortController?.abort()}setAuthInfo(e){this.authInfo=e}async initializeMcpHost(){if(!this.mcpHost&&this.mcpServers&&Object.keys(this.mcpServers).length>0)try{this.mcpHost=new kL(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.authInfo)throw new Error("Session was not created with authentication info");let n=new Map,r=new Map;try{let I=(await TL(this.hooks?.userPromptSubmitted,{timestamp:Date.now(),cwd:this.workingDir,prompt:e},this.logger))?.modifiedPrompt??e;this.emit("user.message",{content:kB({problemStatement:I,capabilities:{}}),attachments:l});let s=await Qg(this.authInfo),o=this.authInfo.type!=="hmac"?await g5n(this.authInfo.host,s||"",this.logger):void 0,c=await ime(this.logger,this.sessionId,this.authInfo,yjt);if(c.type!=="success")throw new Error("Failed to list available models");let d=await Vv(this._selectedModel,this,c.list,this.logger);if(!d)throw new Error("No available models found. Please check your Copilot license and permissions.");let b=new zX().setProblemStatement(I).setAgentModel(`capi:${d}`).setGithubRepoName("copilot-sdk-session").setGithubRepoCommit("copilot-sdk-commit").setGithubRepoReadWrite(!1).setCopilotIntegrationId(yjt).setCopilotUrl(o).setGithubToken(s).setCopilotToken(s).build();Cx();let p=await Gme(b),A=p.service?.agent?.model,Z=SB(A),W=Z.agent,R=W??"sweagent-capi",V=Z.model?{model:Z.model}:void 0,f=Dde(p,this.logger,W,V),X={location:this.workingDir,timeout:3e4,requireReasoning:!0,toolPartialResultCallback:(Ge,me)=>{this.emitEphemeral("tool.execution_partial_result",{toolCallId:Ge,partialOutput:me})},permissions:this.requestPermission?{requestRequired:!0,request:this.requestPermission}:{requestRequired:!1},shellConfig:(process.platform==="win32"?bp.powerShell:bp.bash).withScriptSafetyAssessor(async function(Ge){return{result:"completed",commands:[{identifier:Ge,readOnly:!1}],possiblePaths:[],hasWriteFileRedirection:!1,canOfferSessionApproval:!1}})},S=await aVe(X,this.logger),U=[];if(this.mcpHost)try{U=await this.mcpHost.getTools(p,this.logger,X.permissions)}catch(Ge){this.logger.error(`Failed to get MCP tools: ${Ge}`)}let T=[...S,...U].filter(Ge=>this.allowedTools?this.allowedTools.includes(Ge.name):this.disabledTools?!this.disabledTools.includes(Ge.name):!0),j=await mY(this.workingDir),z={...(_8()[R]?.[f.model]??M8()).supports,reasoning:!0},ae=await g6({location:j.found?j.gitRoot:"",version:bL(),currentWorkingDirectory:this.workingDir,parts:{},capabilities:z,toolConfigOverrides:X,tools:T,organizationCustomInstructions:void 0}),he=await this.getChatMessages(),We=he.findLastIndex(Ge=>Ge.role==="user"),K=he.filter(Ge=>Ge.role==="user").at(-1);if(!K)throw new Error("No user message found in session messages after sending prompt");typeof K.content=="string"?K={...K,content:kB({customAgentPrompt:void 0,problemStatement:K.content,capabilities:z})}:K={...K,content:K.content.map(Ge=>Ge.type==="text"?{...Ge,text:kB({customAgentPrompt:void 0,problemStatement:Ge.text,capabilities:z})}:Ge)};let O=he.map((Ge,me)=>me===We?K:Ge);await TL(this.hooks?.sessionStart,{timestamp:Date.now(),cwd:this.workingDir,source:"new",initialPrompt:e},this.logger);let se=new q4(K,this.logger),Ie=f.getCompletionWithTools(ae,O,T,{failIfInitialInputsTooLong:!1,processors:{preRequest:[se,this.immediatePromptProcessor,new FT(this.logger)],onRequestError:[se]},executeToolsInParallel:!1,abortSignal:this.abortController?.signal});for await(let Ge of Ie){if(this.abortController?.signal.aborted){this.emit("abort",{reason:"user initiated"});break}switch(Ge.kind){case"message":{if(hL(Ge)){let me=U8(Ge)?await Promise.all(Ge.message.tool_calls.map(async Qe=>{let Re=lL(Qe.function.arguments);n.set(Qe.id,Qe.function.name),r.set(Qe.id,Re);let Ae=await TL(this.hooks?.preToolUse,{timestamp:Date.now(),cwd:this.workingDir,toolName:Qe.function.name,toolArgs:Re},this.logger);return{toolCallId:Qe.id,name:Qe.function.name,arguments:Ae?.modifiedArgs??Re}})):[];this.emit("assistant.message",{parentToolCallId:void 0,messageId:km(),content:typeof Ge.message.content=="string"?Ge.message.content:"",toolRequests:me});for(let Qe of me)this.emit("tool.execution_start",{toolCallId:Qe.toolCallId,toolName:Qe.name,arguments:Qe.arguments})}else(Ge.message.role==="system"||Ge.message.role==="developer")&&this.emit("system.message",{role:Ge.message.role,content:typeof Ge.message.content=="string"?Ge.message.content:JSON.stringify(Ge.message.content),name:"name"in Ge.message?Ge.message.name:void 0});break}case"model_call_failure":{let me=new Error(Ge.modelCall?.error||"Model call failed");await TL(this.hooks?.errorOccurred,{timestamp:Date.now(),cwd:this.workingDir,error:me,errorContext:"model_call",recoverable:!0},this.logger),this.emit("session.error",{errorType:"model_call",message:me.message,stack:me.stack});break}case"tool_execution":{let Qe=(await TL(this.hooks?.postToolUse,{timestamp:Date.now(),cwd:this.workingDir,toolName:n.get(Ge.toolCallId)||"unknown",toolArgs:r.get(Ge.toolCallId)||{},toolResult:Ge.toolResult},this.logger))?.modifiedResult??Ge.toolResult,Re=(Qe.resultType==="failure"?Qe.error:void 0)||Qe.sessionLog||Qe.textResultForLlm;this.emit("tool.execution_complete",{parentToolCallId:void 0,toolCallId:Ge.toolCallId,success:Qe.resultType==="success",result:Qe.resultType==="success"?{content:Re}:void 0,error:Qe.resultType!=="success"?{message:Re,code:Qe.resultType}:void 0});break}case"turn_started":{this.emit("assistant.turn_start",{turnId:`${Ge.turn}`});break}case"turn_ended":{this.emit("assistant.turn_end",{turnId:`${Ge.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: ${Ge.kind}`);break;default:wo(Ge,"Unhandled event type")}}}catch(a){await TL(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 TL(this.hooks?.sessionEnd,{timestamp:Date.now(),cwd:this.workingDir,reason:"complete"},this.logger)}}};function Z5n(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 Xq=zl({command:Qt(),description:Qt(),timeout:Pm().optional(),sessionId:Qt().optional(),async:ro().optional()}),g7e=zl({sessionId:Qt(),input:Qt(),delay:Pm().optional()}),Z7e=zl({sessionId:Qt(),delay:Pm()}),N7e=zl({sessionId:Qt()}),Ejt=Oh([Xq,g7e,Z7e,N7e]),N5n=zl({command:pr("view"),path:Qt(),view_range:dVe([Pm(),Pm()]).optional()}),W5n=zl({command:pr("create"),path:Qt(),file_text:Qt()}),y5n=zl({command:pr("str_replace"),path:Qt(),new_str:Qt().optional(),old_str:Qt()}),E5n=zl({command:pr("insert"),path:Qt(),insert_line:Pm(),new_str:Qt()}),W7e=$de("command",[N5n,W5n,y5n,E5n]),y7e=zl({path:Qt(),view_range:dVe([Pm(),Pm()]).optional()}),E7e=zl({path:Qt(),file_text:Qt()}),R7e=zl({path:Qt(),old_str:Qt(),new_str:Qt().optional()}),Y7e=Oh([Ejt,W7e,Bw()]),Rjt=(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 Yjt(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 AO=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 pme=zl({type:pr("text"),text:Qt()}),R5n=zl({type:pr("refusal"),refusal:Qt()}),Y5n=zl({type:pr("image_url"),image_url:zl({url:Qt(),detail:h0(["auto","low","high"]).optional()})}),V5n=zl({type:pr("input_audio"),input_audio:zl({data:Qt(),format:pr("wav").or(pr("mp3"))})}),w5n=zl({type:pr("file"),file:zl({file_date:Qt().optional(),file_id:Qt().optional(),filename:Qt().optional()})}),Q5n=Oh([pme,Y5n,V5n,w5n]),F5n=zl({name:Qt(),arguments:Qt()}),C5n=zl({name:Qt(),input:Qt()}),f5n=zl({id:Qt(),type:pr("function"),function:F5n}),v5n=zl({id:Qt(),type:pr("custom"),custom:C5n}),H5n=Oh([f5n,v5n]),X5n=zl({name:Qt(),arguments:Qt()}),k5n=zl({id:Qt()}),L5n=zl({content:Oh([Qt(),Od(pme)]),role:pr("developer"),name:Qt().optional()}),J5n=zl({content:Oh([Qt(),Od(pme)]),role:pr("system"),name:Qt().optional()}),x5n=zl({content:Oh([Qt(),Od(Q5n)]),role:pr("user"),name:Qt().optional()}),S5n=zl({content:Oh([Qt(),Od(Oh([pme,R5n]))]).nullable().optional(),role:pr("assistant"),name:Qt().optional(),refusal:Qt().nullable().optional(),audio:k5n.nullable().optional(),function_call:X5n.nullable().optional(),tool_calls:Od(H5n).optional()}),B5n=zl({content:Oh([Qt(),Od(pme)]),role:pr("tool"),tool_call_id:Qt()}),T5n=zl({content:Qt().nullable(),role:pr("function"),name:Qt()}),O5n=Oh([L5n,J5n,x5n,S5n,B5n,T5n]),U5n=zl({type:pr("copilot"),text:Qt(),isStreaming:ro().optional()}),M5n=zl({type:pr("error"),text:Qt()}),_5n=zl({type:pr("info"),text:Qt()}),D5n=zl({type:pr("user"),text:Qt()}),z5n=zl({type:pr("tool_call_requested"),callId:Qt(),name:Qt(),toolTitle:Qt().optional(),intentionSummary:Qt().nullable(),arguments:Y7e,partialOutput:Qt().optional(),isHidden:ro().optional(),isAlwaysExpanded:ro().optional(),showNoContent:ro().optional()}),P5n=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:Y7e,isHidden:ro().optional(),isAlwaysExpanded:ro().optional(),showNoContent:ro().optional()}),j5n=Oh([U5n,M5n,_5n,D5n,z5n,P5n]),K5n=j5n.and(zl({id:Qt(),timestamp:uVe.date()})),V7e=zl({sessionId:Qt(),startTime:uVe.date(),chatMessages:Od(O5n),timeline:Od(K5n),selectedModel:h0(Yv).optional()}),OL=Dwe(V7e.parse,"history-session");var Km=zl({id:Qt().uuid(),timestamp:Qt().datetime(),parentId:Qt().uuid().nullable(),ephemeral:ro().optional()}),Vjt=zl({parentToolCallId:Qt().optional()}),q5n=Km.extend({type:pr("session.start"),data:zl({sessionId:Qt(),version:Pm(),producer:Qt(),copilotVersion:Qt(),startTime:Qt().datetime(),selectedModel:Qt().optional()})}),$5n=Km.extend({type:pr("session.resume"),data:zl({resumeTime:Qt().datetime(),eventCount:Pm()})}),e4n=Km.extend({type:pr("session.error"),data:zl({errorType:Qt(),message:Qt(),stack:Qt().optional()})}),t4n=Km.extend({type:pr("session.info"),data:zl({infoType:Qt(),message:Qt()})}),l4n=Km.extend({type:pr("session.model_change"),data:zl({previousModel:Qt().optional(),newModel:Qt()})}),n4n=Km.extend({type:pr("session.import_legacy"),data:zl({legacySession:V7e,importTime:Qt().datetime(),sourceFile:Qt()})}),r4n=Km.extend({type:pr("session.idle"),ephemeral:pr(!0),data:zl({})}),a4n=zl({type:h0(["file","directory"]),path:Qt(),displayName:Qt()}),I4n=Km.extend({type:pr("user.message"),data:zl({content:Qt(),attachments:Od(a4n).optional()})}),s4n=Km.extend({type:pr("assistant.turn_start"),data:zl({turnId:Qt()})}),o4n=Km.extend({type:pr("assistant.message"),data:zl({messageId:Qt(),content:Qt(),toolRequests:Od(zl({toolCallId:Qt(),name:Qt(),arguments:Bw()})).optional()}).merge(Vjt)}),i4n=Km.extend({type:pr("assistant.turn_end"),data:zl({turnId:Qt()})}),c4n=Km.extend({type:pr("assistant.usage"),ephemeral:pr(!0),data:zl({model:Qt().optional(),inputTokens:Pm().optional(),outputTokens:Pm().optional(),cost:Pm().optional(),duration:Pm().optional(),initiator:Qt().optional()})}),d4n=Km.extend({type:pr("abort"),data:zl({reason:Qt()})}),u4n=Km.extend({type:pr("tool.user_requested"),data:zl({toolCallId:Qt(),toolName:Qt(),arguments:Bw()})}),m4n=Km.extend({type:pr("tool.execution_start"),data:zl({toolCallId:Qt(),toolName:Qt(),arguments:Bw()})}),b4n=Km.extend({type:pr("tool.execution_partial_result"),ephemeral:pr(!0),data:zl({toolCallId:Qt(),partialOutput:Qt()})}),G4n=Km.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(Vjt)}),p4n=Km.extend({type:pr("hook.start"),data:zl({hookInvocationId:Qt(),hookType:Qt(),input:Bw()})}),h4n=Km.extend({type:pr("hook.end"),data:zl({hookInvocationId:Qt(),hookType:Qt(),output:Bw(),success:ro(),error:zl({message:Qt(),stack:Qt().optional()}).optional()})}),A4n=Km.extend({type:pr("system.message"),data:zl({content:Qt(),role:h0(["system","developer"]),name:Qt().optional(),metadata:zl({promptVersion:Qt().optional(),variables:rY(Bw()).optional()}).optional()})}),wjt=$de("type",[q5n,$5n,e4n,r4n,t4n,l4n,n4n,I4n,s4n,o4n,i4n,c4n,d4n,u4n,m4n,b4n,G4n,p4n,h4n,A4n]);var UL=dPt(wjt.parse,"session");var mQe=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 UL.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 w7e(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())}}};function Qjt(t){if(t.role==="user")return typeof t.content=="string"?t.content:t.content.find(e=>e.type==="text")?.text}async function N4n(t){if(g4n(t))try{return await lNt(t,e=>{if(e.trim())try{let l=JSON.parse(e);if(l.type==="session.import_legacy"){let n=l.data.legacySession.chatMessages.find(r=>r.role==="user");if(n?.content){let r=Qjt(n);if(r)return Q7e(r)}}if(l.type==="user.message"){let n=l.data.content;if(n)return Q7e(n)}return}catch{return}})}catch{return}}function Q7e(t){let e=t.lastIndexOf("<reminder>");e!==-1&&(t=t.substring(0,e).trim());let l=t.replace(/\s+/g," ").trim();return l.length>75&&(l=l.substring(0,55).trim()+"..."),l=l.split("").filter(n=>{let r=n.charCodeAt(0);return r>=32&&r!==127}).join(""),l}var bQe=class{sessionWriters={};copilotVersion;flushDebounceMs;logger;constructor({version:e,flushDebounceMs:l,...n}){this.logger=n.logger||new xd,this.copilotVersion=e||"unknown",this.flushDebounceMs=l||100}async createSession(e){let l=new hO({...e,startTime:e?.startTime||new Date});return this.sessionWriters[l.sessionId]=new mQe(l,this.logger,this.flushDebounceMs),l.emit("session.start",{sessionId:l.sessionId,version:1,producer:"copilot-agent",copilotVersion:this.copilotVersion,startTime:l.startTime.toISOString(),selectedModel:e?.model}),l}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.sessionId]||(this.sessionWriters[e.sessionId]=new mQe(n,this.logger,this.flushDebounceMs,!0,r)),l&&n.emit("session.resume",{resumeTime:new Date().toISOString(),eventCount:n.getEvents().length}),n}async getLastSession(e={}){let l=await this.listSessions();if(l.length===0)return;l.sort((r,a)=>a.modifiedTime.getTime()-r.modifiedTime.getTime());let n=l[0].sessionId;return await this.getSession({...e,sessionId:n})}async saveSession(e){await this.sessionWriters[e.sessionId]?.flush()}async loadSession(e){let l=await UL.load(e.sessionId);return await hO.fromEvents(l,e)}async loadLegacySession(e){let n=(await OL.directoryFiles()).filter(o=>{let c=o.match(/^session_(.+)_(\d+)\.json$/);return c&&c[1]===e.sessionId});if(n.length===0)throw new Error(`Legacy session ${e.sessionId} not found`);let r=n[0];n.length>1&&this.logger.info(`Multiple legacy sessions found for ${e.sessionId}, using newest`);let a=await OL.load(r);if(!a)throw new Error(`Failed to load legacy session from ${r}`);let I=new Date(a.startTime),s=new hO({...e,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.sessionId} from ${r}`),{session:s,legacySourceFile:OL.path(r.replace(/\.json$/,""))}}async listSessions(){let e=await UL.directoryFilesWithMetadata(),l=await OL.directoryFilesWithMetadata(),n=await Promise.all(e.map(async I=>{let s=I.file.replace(".jsonl",""),o=UL.path(s),c=await N4n(o);return{sessionId:s,startTime:I.birthtime,modifiedTime:I.mtime,summary:c}})),r=(await Promise.all(l.map(async I=>{let s=I.file.match(/^session_(.+)_(\d+)\.json$/);if(!s)return null;let o=s[1],c;try{let d=await OL.load(I.file.replace(/\.json$/,""));if(d){let m=d.chatMessages?.find(b=>b.role==="user");if(m?.content){let b=Qjt(m);b&&(c=Q7e(b))}}}catch{}return{sessionId:o,startTime:I.birthtime,modifiedTime:I.mtime,summary:c}}))).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 deleteSession(e){await this.closeSession(e);let l=UL.path(e);try{await w7e(l),this.logger.info(`Deleted session file ${l}`);return}catch{let a=(await OL.directoryFiles()).filter(I=>{let s=I.match(/^session_(.+)_(\d+)\.json$/);return s&&s[1]===e});if(a.length===0)throw new Error(`Session file not found for ${e}`);for(let I of a){let s=OL.path(I.replace(/\.json$/,""));this.logger.info(`Deleting legacy session file ${s}`),await w7e(s)}}}async closeSession(e){this.logger.info(`Closing session ${e}`);let l=this.sessionWriters[e];l&&(await l.flush(),l.dispose(),delete this.sessionWriters[e])}getSessionsDirectory(){return Z4n(UL.home(),UL.directory())}setLogger(e){this.logger=e}};function _c(t){return t()}var hme;function y4n(t,e){return t.includes("\x1B[?")&&t.includes(e)}async function E4n(t){let e=process.stdin.isRaw;e||process.stdin.setRawMode(!0);try{return await t()}finally{e||process.stdin.setRawMode(!1)}}function Fjt(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(),y4n(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 R4n(){return!(!(process.stdin.isTTY&&process.stdout.isTTY)||!await Fjt("?u","u",200)||!await Fjt("c","c",1e3))}async function fjt(){hme===void 0&&(hme=await E4n(R4n),hme===!0&&(Y4n(),process.on("exit",Cjt),process.on("SIGTERM",Cjt)))}function Y4n(){process.stdout.write("\x1B[>1u")}function Cjt(){process.stdout.write("\x1B[<u"),hme=void 0}function GQe(){return hme===!0}function gme(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 b(f,X){let S=0,U=0;for(;S<f||!X;){let T=t.charCodeAt(n);if(T>=48&&T<=57)U=U*16+T-48;else if(T>=65&&T<=70)U=U*16+T-65+10;else if(T>=97&&T<=102)U=U*16+T-97+10;else break;n++,S++}return S<f&&(U=-1),U}function p(f){n=f,r="",a=0,I=16,m=0}function A(){let f=n;if(t.charCodeAt(n)===48)n++;else for(n++;n<t.length&&kq(t.charCodeAt(n));)n++;if(n<t.length&&t.charCodeAt(n)===46)if(n++,n<t.length&&kq(t.charCodeAt(n)))for(n++;n<t.length&&kq(t.charCodeAt(n));)n++;else return m=3,t.substring(f,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&&kq(t.charCodeAt(n))){for(n++;n<t.length&&kq(t.charCodeAt(n));)n++;X=n}else m=3;return t.substring(f,X)}function Z(){let f="",X=n;for(;;){if(n>=l){f+=t.substring(X,n),m=2;break}let S=t.charCodeAt(n);if(S===34){f+=t.substring(X,n),n++;break}if(S===92){if(f+=t.substring(X,n),n++,n>=l){m=2;break}switch(t.charCodeAt(n++)){case 34:f+='"';break;case 92:f+="\\";break;case 47:f+="/";break;case 98:f+="\b";break;case 102:f+="\f";break;case 110:f+=`
2060
2060
  `;break;case 114:f+="\r";break;case 116:f+=" ";break;case 117:let T=b(4,!0);T>=0?f+=String.fromCharCode(T):m=4;break;default:m=5}X=n;continue}if(S>=0&&S<=31)if(Ame(S)){f+=t.substring(X,n),m=2;break}else m=6;n++}return f}function W(){if(r="",m=0,a=n,o=s,d=c,n>=l)return a=l,I=17;let f=t.charCodeAt(n);if(F7e(f)){do n++,r+=String.fromCharCode(f),f=t.charCodeAt(n);while(F7e(f));return I=15}if(Ame(f))return n++,r+=String.fromCharCode(f),f===13&&t.charCodeAt(n)===10&&(n++,r+=`
2061
2061
  `),s++,c=n,I=14;switch(f){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&&!Ame(t.charCodeAt(n));)n++;return r=t.substring(X,n),I=12}if(t.charCodeAt(n+1)===42){n+=2;let S=l-1,U=!1;for(;n<S;){let T=t.charCodeAt(n);if(T===42&&t.charCodeAt(n+1)===47){n+=2,U=!0;break}n++,Ame(T)&&(T===13&&t.charCodeAt(n)===10&&n++,s++,c=n)}return U||(n++,m=1),r=t.substring(X,n),I=13}return r+=String.fromCharCode(f),n++,I=16;case 45:if(r+=String.fromCharCode(f),n++,n===l||!kq(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(f);)n++,f=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(f),n++,I=16}}function R(f){if(F7e(f)||Ame(f))return!1;switch(f){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}function V(){let f;do f=W();while(f>=12&&f<=15);return f}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 F7e(t){return t===32||t===9}function Ame(t){return t===10||t===13}function kq(t){return t>=48&&t<=57}var vjt;(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"})(vjt||(vjt={}));var iy=new Array(20).fill(0).map((t,e)=>" ".repeat(e)),Lq=200,C7e={" ":{"\n":new Array(Lq).fill(0).map((t,e)=>`
2062
2062
  `+" ".repeat(e)),"\r":new Array(Lq).fill(0).map((t,e)=>"\r"+" ".repeat(e)),"\r\n":new Array(Lq).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-27",
4
+ "version": "0.0.354-29",
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": "e5266c2"
40
+ "gitCommit": "7aa2054"
41
41
  }
42
42
  }
package/sdk/index.js CHANGED
@@ -1497,7 +1497,7 @@ Pay attention to the following when using it:
1497
1497
  ${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 eR=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 a2e={mcpServers:{}},B$=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"),a2e;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"),a2e;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}`),a2e}}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[$V]??void 0;if(r&&GlI(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[$V]=s}else this.logger.log("Using default remote GitHub MCP server configuration"),e.mcpServers[$V]=c}configureLocalGitHubMcp(e){if(e.mcpServers[$V]){this.logger.log("Using user-provided GitHub MCP server configuration");let I=e.mcpServers[$V]??{};gC(I)&&!I.command&&(e.mcpServers[$V]={...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[$V]=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[r2e]){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:[...XZe,"--allowed-origins","localhost;localhost:*;127.0.0.1;127.0.0.1:*"],tools:["*"],isDefaultServer:!0};e.mcpServers[r2e]=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[CU]=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[CU]=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[CU]=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 gC(e)||LU(e)||fU(e)||kU(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&&!gC(I)&&!kU(I)?(this.logger.error(`Unsupported server type "${I.type}" for server "${e}". Only "Local", "STDIO", or "Memory" are supported.`),!1):I.tools?gC(I)&&!this.isValidLocalServerConfig(I)?(this.logger.error(`Invalid local server configuration for "${e}". Please ensure 'command' and 'args' are provided.`),!1):(LU(I)||fU(I))&&!this.isValidRemoteServerConfig(I)?(this.logger.error(`Invalid remote server configuration for "${e}". Please ensure 'url' is provided.`),!1):kU(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=eR.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=eR.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,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=eR.resolveLocalServerConfig(l,n);process.env.GITHUB_WORKSPACE&&c.cwd===void 0&&(c.cwd=process.env.GITHUB_WORKSPACE),this.logger.log(`Starting MCP client for ${e} with
1498
1498
  command: ${c.command}
1499
1499
  args: ${c.args}
1500
- cwd: ${c.cwd}`);try{let r={...c,env:n};await this.registry.startLocalMcpClient(e,r),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]=eR.resolveString(n,process.env);else for(let[l,n]of Object.entries(e.env)){let c=n.trim(),r=c;if(c.includes("$")&&(r=eR.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}JU.includes(e)||await this.sessionClient?.createOrUpdateMCPStartupToolCall({serverName:e});try{gC(I)?await this.processLocalServer(e,I):LU(I)&&this.remoteEnabled?await this.processHttpServer(e,I):fU(I)&&this.remoteEnabled?await this.processSseServer(e,I):kU(I)&&await this.processInMemoryServer(e,I)}catch(l){JU.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 z$=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 x$(this.logger,void 0,void 0,n),this.registry.setToolsChangedCallback(r=>{this.handleToolsChanged(r)}),this.processor=new B$(this.logger,this.registry,{mcp3pEnabled:!0,remoteEnabled:!0})}registry;processor;config;startServersPromise=null;transport=null;disabledServers;async handleToolsChanged(e){if(this.logger.log(`Handling tools changed notification for ${e}`),this.transport){let I=this.registry.clients[e];I?await this.transport.refreshProvider({mcpClient:I,clientName:e,tools:this.config.mcpServers[e]?.tools||["*"],filterMapping:this.config.mcpServers[e]?.filterMapping||"hidden_characters"}):this.logger.log(`No client found for ${e}, cannot refresh`)}}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 Vz(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",timeout:this.config.mcpServers[c]?.timeout},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 BlI=vl(xlI(),1);async function zdt(t={}){let e=await _2e();return K2e((0,BlI.default)({},e,t))}async function zlI(t={}){if(qU())throw new Error("Settings have already been initialized");return zdt(t)}import{promises as Udt}from"fs";import UlI from"path";var Sdt=3*1024*1024;function SlI(t){let e=UlI.extname(t).toLowerCase();return[".png",".jpg",".jpeg",".gif",".webp"].includes(e)}function Odt(t){switch(UlI.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 Mdt(t,e){e.debug(`Processing local image file: ${t}`);let I=await Udt.readFile(t),l=Odt(t);if(!l)throw new Error(`Unsupported image format: ${t}`);let n=new Yz,c=await x7(e,n,Sdt,Zz,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 Tdt(t,e,I){let l=UG();try{let n=await Vse({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 OlI(t,e,I){let l=[],n=t.filter(r=>!SlI(r.path));if(n.length===0)return l;let c=[];for(let r of n)try{let s=await Tdt(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 MlI(t,e){let I=t.filter(n=>SlI(n.path));return(await Promise.all(I.map(async n=>{try{return{type:"image_url",image_url:{url:await Mdt(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 TlI="copilot-developer-cli",jdt=M2e(I_),W2e=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"}},IR=class t{sessionId;startTime;modifiedTime;logger;events=[];_chatMessages=[];_selectedModel;eventProcessingQueue=Promise.resolve();eventHandlers={};wildcardEventHandlers=[];isProcessing=!1;messageQueue=[];immediatePromptProcessor;mcpHost;workingDir;abortController;allowedTools;disabledTools;requestPermission;mcpServers;hooks;authInfo;constructor(e={}){this.sessionId=e.sessionId||UG(),this.startTime=e.startTime||new Date,this.modifiedTime=e.modifiedTime||this.startTime,this.logger=e.logger||new Vm,this._selectedModel=e.model,this.allowedTools=e.allowedTools,this.disabledTools=e.disabledTools,this.requestPermission=e.requestPermission,this.mcpServers=e.mcpServers,this.hooks=e.hooks,this.authInfo=e.authInfo,this.workingDir=e.workingDirectory||process.cwd(),this.immediatePromptProcessor=new W2e(this.logger,this),nWe(this.workingDir).then(I=>{if(I.found)return o6e(I.gitRoot,!0,this.workingDir)}).catch(I=>{this.logger.debug(`Failed to initialize custom instructions cache: ${I}`)})}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=UG(),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 MlI(e.data.attachments,this.logger);I.push(...n);let c=await OlI(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=Ddt(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){if(e.mode==="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 I=this.messageQueue.shift();this.abortController=I.abortController||new AbortController,await this.runAgenticLoop(I.prompt,I.attachments)}this.isProcessing=!1,this.emitEphemeral("session.idle",{})}}async abort(){this.abortController?.abort()}setAuthInfo(e){this.authInfo=e}async initializeMcpHost(){if(!this.mcpHost&&this.mcpServers&&Object.keys(this.mcpServers).length>0)try{this.mcpHost=new z$(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.authInfo)throw new Error("Session was not created with authentication info");let l=new Map,n=new Map;try{let r=(await rN(this.hooks?.userPromptSubmitted,{timestamp:Date.now(),cwd:this.workingDir,prompt:e},this.logger))?.modifiedPrompt??e;this.emit("user.message",{content:g7({problemStatement:r,capabilities:{}}),attachments:I});let s=await kz(this.authInfo),a=this.authInfo.type!=="hmac"?await jdt(this.authInfo.host,s||"",this.logger):void 0,o=await s$e(this.logger,this.sessionId,this.authInfo,TlI);if(o.type!=="success")throw new Error("Failed to list available models");let G=await f_e(this._selectedModel,this,o.list,this.logger);if(!G)throw new Error("No available models found. Please check your Copilot license and permissions.");let d=new mA().setProblemStatement(r).setAgentModel(`capi:${G}`).setGithubRepoName("copilot-sdk-session").setGithubRepoCommit("copilot-sdk-commit").setGithubRepoReadWrite(!1).setCopilotIntegrationId(TlI).setCopilotUrl(a).setGithubToken(s).build();P2e();let b=await zlI(d),m=b.service?.agent?.model,h=G3(m),u=h.agent,Z=u??"sweagent-capi",N=h.model?{model:h.model}:void 0,g=Rme(b,this.logger,u,N),y={location:this.workingDir,timeout:3e4,requireReasoning:!0,toolPartialResultCallback:(ne,oI)=>{this.emitEphemeral("tool.execution_partial_result",{toolCallId:ne,partialOutput:oI})},permissions:this.requestPermission?{requestRequired:!0,request:this.requestPermission}:{requestRequired:!1},shellConfig:(process.platform==="win32"?Fb.powerShell:Fb.bash).withScriptSafetyAssessor(async function(ne){return{result:"completed",commands:[{identifier:ne,readOnly:!1}],possiblePaths:[],hasWriteFileRedirection:!1,canOfferSessionApproval:!1}})},A=await w7e(y,this.logger),f=[];if(this.mcpHost)try{f=await this.mcpHost.getTools(b,this.logger,y.permissions)}catch(ne){this.logger.error(`Failed to get MCP tools: ${ne}`)}let J=[...A,...f].filter(ne=>this.allowedTools?this.allowedTools.includes(ne.name):this.disabledTools?!this.disabledTools.includes(ne.name):!0),X=await nWe(this.workingDir),x={...(E7e()[Z]?.[g.model]??X7e()).supports,reasoning:!0},S=await Eqe({location:X.found?X.gitRoot:"",version:LUe(),currentWorkingDirectory:this.workingDir,parts:{},capabilities:x,toolConfigOverrides:y,tools:J,organizationCustomInstructions:void 0}),le=await this.getChatMessages(),be=le.findLastIndex(ne=>ne.role==="user"),Ae=le.filter(ne=>ne.role==="user").at(-1);if(!Ae)throw new Error("No user message found in session messages after sending prompt");typeof Ae.content=="string"?Ae={...Ae,content:g7({customAgentPrompt:void 0,problemStatement:Ae.content,capabilities:x})}:Ae={...Ae,content:Ae.content.map(ne=>ne.type==="text"?{...ne,text:g7({customAgentPrompt:void 0,problemStatement:ne.text,capabilities:x})}:ne)};let we=le.map((ne,oI)=>oI===be?Ae:ne);await rN(this.hooks?.sessionStart,{timestamp:Date.now(),cwd:this.workingDir,source:"new",initialPrompt:e},this.logger);let Le=new fv(Ae,this.logger),Xe=g.getCompletionWithTools(S,we,J,{failIfInitialInputsTooLong:!1,processors:{preRequest:[Le,this.immediatePromptProcessor,new Rz(this.logger)],onRequestError:[Le]},executeToolsInParallel:!1,abortSignal:this.abortController?.signal});for await(let ne of Xe){if(this.abortController?.signal.aborted){this.emit("abort",{reason:"user initiated"});break}switch(ne.kind){case"message":{if(S7(ne)){let oI=R7e(ne)?await Promise.all(ne.message.tool_calls.map(async Ye=>{let ze=UX(Ye.function.arguments);l.set(Ye.id,Ye.function.name),n.set(Ye.id,ze);let nl=await rN(this.hooks?.preToolUse,{timestamp:Date.now(),cwd:this.workingDir,toolName:Ye.function.name,toolArgs:ze},this.logger);return{toolCallId:Ye.id,name:Ye.function.name,arguments:nl?.modifiedArgs??ze}})):[];this.emit("assistant.message",{parentToolCallId:void 0,messageId:UG(),content:typeof ne.message.content=="string"?ne.message.content:"",toolRequests:oI});for(let Ye of oI)this.emit("tool.execution_start",{toolCallId:Ye.toolCallId,toolName:Ye.name,arguments:Ye.arguments})}else(ne.message.role==="system"||ne.message.role==="developer")&&this.emit("system.message",{role:ne.message.role,content:typeof ne.message.content=="string"?ne.message.content:JSON.stringify(ne.message.content),name:"name"in ne.message?ne.message.name:void 0});break}case"model_call_failure":{let oI=new Error(ne.modelCall?.error||"Model call failed");await rN(this.hooks?.errorOccurred,{timestamp:Date.now(),cwd:this.workingDir,error:oI,errorContext:"model_call",recoverable:!0},this.logger),this.emit("session.error",{errorType:"model_call",message:oI.message,stack:oI.stack});break}case"tool_execution":{let Ye=(await rN(this.hooks?.postToolUse,{timestamp:Date.now(),cwd:this.workingDir,toolName:l.get(ne.toolCallId)||"unknown",toolArgs:n.get(ne.toolCallId)||{},toolResult:ne.toolResult},this.logger))?.modifiedResult??ne.toolResult,ze=(Ye.resultType==="failure"?Ye.error:void 0)||Ye.sessionLog||Ye.textResultForLlm;this.emit("tool.execution_complete",{parentToolCallId:void 0,toolCallId:ne.toolCallId,success:Ye.resultType==="success",result:Ye.resultType==="success"?{content:ze}:void 0,error:Ye.resultType!=="success"?{message:ze,code:Ye.resultType}:void 0});break}case"turn_started":{this.emit("assistant.turn_start",{turnId:`${ne.turn}`});break}case"turn_ended":{this.emit("assistant.turn_end",{turnId:`${ne.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: ${ne.kind}`);break;default:vm(ne,"Unhandled event type")}}}catch(c){await rN(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 rN(this.hooks?.sessionEnd,{timestamp:Date.now(),cwd:this.workingDir,reason:"complete"},this.logger)}}};function Ddt(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 Kdt=fe({command:oe(),description:oe(),timeout:Zs().optional(),sessionId:oe().optional(),async:kl().optional()}),Pdt=fe({sessionId:oe(),input:oe(),delay:Zs().optional()}),qdt=fe({sessionId:oe(),delay:Zs()}),_dt=fe({sessionId:oe()}),$dt=wa([Kdt,Pdt,qdt,_dt]),ebt=fe({command:gI("view"),path:oe(),view_range:_7([Zs(),Zs()]).optional()}),Ibt=fe({command:gI("create"),path:oe(),file_text:oe()}),tbt=fe({command:gI("str_replace"),path:oe(),new_str:oe().optional(),old_str:oe()}),lbt=fe({command:gI("insert"),path:oe(),insert_line:Zs(),new_str:oe()}),nbt=wz("command",[ebt,Ibt,tbt,lbt]),eKl=fe({path:oe(),view_range:_7([Zs(),Zs()]).optional()}),IKl=fe({path:oe(),file_text:oe()}),tKl=fe({path:oe(),old_str:oe(),new_str:oe().optional()}),N2e=wa([$dt,nbt,eu()]);var OU=fe({type:gI("text"),text:oe()}),rbt=fe({type:gI("refusal"),refusal:oe()}),sbt=fe({type:gI("image_url"),image_url:fe({url:oe(),detail:Iu(["auto","low","high"]).optional()})}),abt=fe({type:gI("input_audio"),input_audio:fe({data:oe(),format:gI("wav").or(gI("mp3"))})}),obt=fe({type:gI("file"),file:fe({file_date:oe().optional(),file_id:oe().optional(),filename:oe().optional()})}),Gbt=wa([OU,sbt,abt,obt]),ibt=fe({name:oe(),arguments:oe()}),dbt=fe({name:oe(),input:oe()}),bbt=fe({id:oe(),type:gI("function"),function:ibt}),mbt=fe({id:oe(),type:gI("custom"),custom:dbt}),hbt=wa([bbt,mbt]),pbt=fe({name:oe(),arguments:oe()}),ubt=fe({id:oe()}),Zbt=fe({content:wa([oe(),Ws(OU)]),role:gI("developer"),name:oe().optional()}),Wbt=fe({content:wa([oe(),Ws(OU)]),role:gI("system"),name:oe().optional()}),Nbt=fe({content:wa([oe(),Ws(Gbt)]),role:gI("user"),name:oe().optional()}),Ybt=fe({content:wa([oe(),Ws(wa([OU,rbt]))]).nullable().optional(),role:gI("assistant"),name:oe().optional(),refusal:oe().nullable().optional(),audio:ubt.nullable().optional(),function_call:pbt.nullable().optional(),tool_calls:Ws(hbt).optional()}),Vbt=fe({content:wa([oe(),Ws(OU)]),role:gI("tool"),tool_call_id:oe()}),Rbt=fe({content:oe().nullable(),role:gI("function"),name:oe()}),ybt=wa([Zbt,Wbt,Nbt,Ybt,Vbt,Rbt]),gbt=fe({type:gI("copilot"),text:oe(),isStreaming:kl().optional()}),Fbt=fe({type:gI("error"),text:oe()}),Abt=fe({type:gI("info"),text:oe()}),Qbt=fe({type:gI("user"),text:oe()}),wbt=fe({type:gI("tool_call_requested"),callId:oe(),name:oe(),toolTitle:oe().optional(),intentionSummary:oe().nullable(),arguments:N2e,partialOutput:oe().optional(),isHidden:kl().optional(),isAlwaysExpanded:kl().optional(),showNoContent:kl().optional()}),Xbt=fe({type:gI("tool_call_completed"),callId:oe(),name:oe(),toolTitle:oe().optional(),intentionSummary:oe().nullable(),result:wa([fe({type:gI("success"),log:oe(),markdown:kl().optional()}),fe({type:gI("failure"),log:oe(),markdown:kl().optional()}),fe({type:gI("rejected"),markdown:kl().optional()}),fe({type:gI("denied"),log:oe(),markdown:kl().optional()})]),arguments:N2e,isHidden:kl().optional(),isAlwaysExpanded:kl().optional(),showNoContent:kl().optional()}),Ebt=wa([gbt,Fbt,Abt,Qbt,wbt,Xbt]),Hbt=Ebt.and(fe({id:oe(),timestamp:$7.date()})),Y2e=fe({sessionId:oe(),startTime:$7.date(),chatMessages:Ws(ybt),timeline:Ws(Hbt),selectedModel:Iu(g_).optional()}),tR=E_e(Y2e.parse,"history-session");var Nr=fe({id:oe().uuid(),timestamp:oe().datetime(),parentId:oe().uuid().nullable(),ephemeral:kl().optional()}),jlI=fe({parentToolCallId:oe().optional()}),vbt=Nr.extend({type:gI("session.start"),data:fe({sessionId:oe(),version:Zs(),producer:oe(),copilotVersion:oe(),startTime:oe().datetime(),selectedModel:oe().optional()})}),Cbt=Nr.extend({type:gI("session.resume"),data:fe({resumeTime:oe().datetime(),eventCount:Zs()})}),Jbt=Nr.extend({type:gI("session.error"),data:fe({errorType:oe(),message:oe(),stack:oe().optional()})}),Lbt=Nr.extend({type:gI("session.info"),data:fe({infoType:oe(),message:oe()})}),fbt=Nr.extend({type:gI("session.model_change"),data:fe({previousModel:oe().optional(),newModel:oe()})}),kbt=Nr.extend({type:gI("session.import_legacy"),data:fe({legacySession:Y2e,importTime:oe().datetime(),sourceFile:oe()})}),xbt=Nr.extend({type:gI("session.idle"),ephemeral:gI(!0),data:fe({})}),Bbt=fe({type:Iu(["file","directory"]),path:oe(),displayName:oe()}),zbt=Nr.extend({type:gI("user.message"),data:fe({content:oe(),attachments:Ws(Bbt).optional()})}),Ubt=Nr.extend({type:gI("assistant.turn_start"),data:fe({turnId:oe()})}),Sbt=Nr.extend({type:gI("assistant.message"),data:fe({messageId:oe(),content:oe(),toolRequests:Ws(fe({toolCallId:oe(),name:oe(),arguments:eu()})).optional()}).merge(jlI)}),Obt=Nr.extend({type:gI("assistant.turn_end"),data:fe({turnId:oe()})}),Mbt=Nr.extend({type:gI("assistant.usage"),ephemeral:gI(!0),data:fe({model:oe().optional(),inputTokens:Zs().optional(),outputTokens:Zs().optional(),cost:Zs().optional(),duration:Zs().optional(),initiator:oe().optional()})}),Tbt=Nr.extend({type:gI("abort"),data:fe({reason:oe()})}),jbt=Nr.extend({type:gI("tool.user_requested"),data:fe({toolCallId:oe(),toolName:oe(),arguments:eu()})}),Dbt=Nr.extend({type:gI("tool.execution_start"),data:fe({toolCallId:oe(),toolName:oe(),arguments:eu()})}),Kbt=Nr.extend({type:gI("tool.execution_partial_result"),ephemeral:gI(!0),data:fe({toolCallId:oe(),partialOutput:oe()})}),Pbt=Nr.extend({type:gI("tool.execution_complete"),data:fe({toolCallId:oe(),success:kl(),isUserRequested:kl().optional(),result:fe({content:oe()}).optional(),error:fe({message:oe(),code:oe().optional()}).optional()}).merge(jlI)}),qbt=Nr.extend({type:gI("hook.start"),data:fe({hookInvocationId:oe(),hookType:oe(),input:eu()})}),_bt=Nr.extend({type:gI("hook.end"),data:fe({hookInvocationId:oe(),hookType:oe(),output:eu(),success:kl(),error:fe({message:oe(),stack:oe().optional()}).optional()})}),$bt=Nr.extend({type:gI("system.message"),data:fe({content:oe(),role:Iu(["system","developer"]),name:oe().optional(),metadata:fe({promptVersion:oe().optional(),variables:Tv(eu()).optional()}).optional()})}),DlI=wz("type",[vbt,Cbt,Jbt,xbt,Lbt,fbt,kbt,zbt,Ubt,Sbt,Obt,Mbt,Tbt,jbt,Dbt,Kbt,Pbt,qbt,_bt,$bt]);var lR=H_e(DlI.parse,"session");var P$=class{constructor(e,I,l,n=!1,c){this.session=e;this.logger=I;this.flushDebounceMs=l;this.shouldSaveSession=n;this.legacySourceFile=c;this.unsubscribe=this.session.on("*",r=>{r.ephemeral||(this.unflushedEvents.push(r),!this.shouldSaveSession&&r.type==="user.message"&&(this.shouldSaveSession=!0),r.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 lR.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 V2e(this.legacySourceFile)}catch(I){this.logger.error(`Failed to delete legacy session file ${this.legacySourceFile}: ${I}`)}this.migratedLegacy=!0}}catch(I){this.logger.error(`Failed to flush events for ${this.session.sessionId}: ${I instanceof Error?I.message:String(I)}`),this.unflushedEvents.unshift(...e)}finally{this.isFlushing=!1,this.needsFlushAfterCurrent&&(this.needsFlushAfterCurrent=!1,await this.flush())}}};function KlI(t){if(t.role==="user")return typeof t.content=="string"?t.content:t.content.find(e=>e.type==="text")?.text}async function tmt(t){if(emt(t))try{return await S2e(t,e=>{if(e.trim())try{let I=JSON.parse(e);if(I.type==="session.import_legacy"){let l=I.data.legacySession.chatMessages.find(n=>n.role==="user");if(l?.content){let n=KlI(l);if(n)return R2e(n)}}if(I.type==="user.message"){let l=I.data.content;if(l)return R2e(l)}return}catch{return}})}catch{return}}function R2e(t){let e=t.lastIndexOf("<reminder>");e!==-1&&(t=t.substring(0,e).trim());let I=t.replace(/\s+/g," ").trim();return I.length>75&&(I=I.substring(0,55).trim()+"..."),I=I.split("").filter(l=>{let n=l.charCodeAt(0);return n>=32&&n!==127}).join(""),I}var y2e=class{sessionWriters={};copilotVersion;flushDebounceMs;logger;constructor({version:e,flushDebounceMs:I,...l}){this.logger=l.logger||new Vm,this.copilotVersion=e||"unknown",this.flushDebounceMs=I||100}async createSession(e){let I=new IR({...e,startTime:e?.startTime||new Date});return this.sessionWriters[I.sessionId]=new P$(I,this.logger,this.flushDebounceMs),I.emit("session.start",{sessionId:I.sessionId,version:1,producer:"copilot-agent",copilotVersion:this.copilotVersion,startTime:I.startTime.toISOString(),selectedModel:e?.model}),I}async getSession(e,I=!0){let l,n;try{l=await this.loadSession(e)}catch{try{let c=await this.loadLegacySession(e);l=c.session,n=c.legacySourceFile}catch{return}}return this.sessionWriters[e.sessionId]||(this.sessionWriters[e.sessionId]=new P$(l,this.logger,this.flushDebounceMs,!0,n)),I&&l.emit("session.resume",{resumeTime:new Date().toISOString(),eventCount:l.getEvents().length}),l}async getLastSession(e={}){let I=await this.listSessions();if(I.length===0)return;I.sort((n,c)=>c.modifiedTime.getTime()-n.modifiedTime.getTime());let l=I[0].sessionId;return await this.getSession({...e,sessionId:l})}async saveSession(e){await this.sessionWriters[e.sessionId]?.flush()}async loadSession(e){let I=await lR.load(e.sessionId);return await IR.fromEvents(I,e)}async loadLegacySession(e){let l=(await tR.directoryFiles()).filter(a=>{let o=a.match(/^session_(.+)_(\d+)\.json$/);return o&&o[1]===e.sessionId});if(l.length===0)throw new Error(`Legacy session ${e.sessionId} not found`);let n=l[0];l.length>1&&this.logger.info(`Multiple legacy sessions found for ${e.sessionId}, using newest`);let c=await tR.load(n);if(!c)throw new Error(`Failed to load legacy session from ${n}`);let r=new Date(c.startTime),s=new IR({...e,sessionId:c.sessionId,startTime:r});return s.emit("session.start",{sessionId:c.sessionId,version:1,producer:"copilot-agent",copilotVersion:this.copilotVersion,startTime:r.toISOString(),selectedModel:c.selectedModel}),s.emit("session.import_legacy",{legacySession:{sessionId:c.sessionId,startTime:r,chatMessages:c.chatMessages,timeline:c.timeline,selectedModel:c.selectedModel},importTime:new Date().toISOString(),sourceFile:n}),this.logger.info(`Loaded legacy session ${e.sessionId} from ${n}`),{session:s,legacySourceFile:tR.path(n.replace(/\.json$/,""))}}async listSessions(){let e=await lR.directoryFilesWithMetadata(),I=await tR.directoryFilesWithMetadata(),l=await Promise.all(e.map(async r=>{let s=r.file.replace(".jsonl",""),a=lR.path(s),o=await tmt(a);return{sessionId:s,startTime:r.birthtime,modifiedTime:r.mtime,summary:o}})),n=(await Promise.all(I.map(async r=>{let s=r.file.match(/^session_(.+)_(\d+)\.json$/);if(!s)return null;let a=s[1],o;try{let G=await tR.load(r.file.replace(/\.json$/,""));if(G){let i=G.chatMessages?.find(d=>d.role==="user");if(i?.content){let d=KlI(i);d&&(o=R2e(d))}}}catch{}return{sessionId:a,startTime:r.birthtime,modifiedTime:r.mtime,summary:o}}))).filter(r=>r!==null);this.logger.debug(`Found ${l.length} JSONL sessions and ${n.length} legacy sessions`);let c=new Map;for(let r of n)c.set(r.sessionId,r);for(let r of l)c.set(r.sessionId,r);return Array.from(c.values()).sort((r,s)=>s.modifiedTime.getTime()-r.modifiedTime.getTime())}async deleteSession(e){await this.closeSession(e);let I=lR.path(e);try{await V2e(I),this.logger.info(`Deleted session file ${I}`);return}catch{let c=(await tR.directoryFiles()).filter(r=>{let s=r.match(/^session_(.+)_(\d+)\.json$/);return s&&s[1]===e});if(c.length===0)throw new Error(`Session file not found for ${e}`);for(let r of c){let s=tR.path(r.replace(/\.json$/,""));this.logger.info(`Deleting legacy session file ${s}`),await V2e(s)}}}async closeSession(e){this.logger.info(`Closing session ${e}`);let I=this.sessionWriters[e];I&&(await I.flush(),I.dispose(),delete this.sessionWriters[e])}getSessionsDirectory(){return Imt(lR.home(),lR.directory())}setLogger(e){this.logger=e}};var g2e=class{loggers;constructor(e){this.loggers=e}isDebug(){return this.loggers.some(e=>e.isDebug())}debug(e){this.loggers.forEach(I=>I.debug(e))}log(e){this.loggers.forEach(I=>I.log(e))}info(e){this.loggers.forEach(I=>I.info(e))}notice(e){this.loggers.forEach(I=>I.notice(e))}warning(e){this.loggers.forEach(I=>I.warning(e))}error(e){this.loggers.forEach(I=>I.error(e))}startGroup(e,I){this.loggers.forEach(l=>l.startGroup(e,I))}endGroup(e){this.loggers.forEach(I=>I.endGroup(e))}};import{appendFile as lmt,access as nmt,mkdir as cmt}from"fs/promises";import{constants as rmt}from"fs";import{dirname as smt}from"path";var F2e=class extends bu{constructor(I,l,n){super(l,n);this.filePath=I;this.writeQueue=amt(smt(this.filePath)).catch(()=>{})}writeQueue=Promise.resolve();log(I){this.write("LOG",I)}debug(I){super.shouldLog(8)&&this.write("DEBUG",this.filterSecrets(I).toString())}info(I){super.shouldLog(4)&&this.write("INFO",this.filterSecrets(I).toString())}notice(I){super.shouldLog(2)&&this.write("NOTICE",this.filterSecrets(I).toString())}warning(I){super.shouldLog(2)&&this.write("WARNING",this.filterSecrets(I).toString())}error(I){super.shouldLog(1)&&this.write("ERROR",this.filterSecrets(I).toString())}startGroup(I,l){super.shouldLog(l||4)&&this.write("START-GROUP",I)}endGroup(I){super.shouldLog(I||4)&&this.write("END-GROUP","")}write(I,l){let c=`${new Date().toISOString()} [${I}] ${l}
1500
+ cwd: ${c.cwd}`);try{let r={...c,env:n};await this.registry.startLocalMcpClient(e,r),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]=eR.resolveString(n,process.env);else for(let[l,n]of Object.entries(e.env)){let c=n.trim(),r=c;if(c.includes("$")&&(r=eR.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}JU.includes(e)||await this.sessionClient?.createOrUpdateMCPStartupToolCall({serverName:e});try{gC(I)?await this.processLocalServer(e,I):LU(I)&&this.remoteEnabled?await this.processHttpServer(e,I):fU(I)&&this.remoteEnabled?await this.processSseServer(e,I):kU(I)&&await this.processInMemoryServer(e,I)}catch(l){JU.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 z$=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 x$(this.logger,void 0,void 0,n),this.registry.setToolsChangedCallback(r=>{this.handleToolsChanged(r)}),this.processor=new B$(this.logger,this.registry,{mcp3pEnabled:!0,remoteEnabled:!0})}registry;processor;config;startServersPromise=null;transport=null;disabledServers;async handleToolsChanged(e){if(this.logger.log(`Handling tools changed notification for ${e}`),this.transport){let I=this.registry.clients[e];I?await this.transport.refreshProvider({mcpClient:I,clientName:e,tools:this.config.mcpServers[e]?.tools||["*"],filterMapping:this.config.mcpServers[e]?.filterMapping||"hidden_characters"}):this.logger.log(`No client found for ${e}, cannot refresh`)}}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 Vz(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",timeout:this.config.mcpServers[c]?.timeout},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 BlI=vl(xlI(),1);async function zdt(t={}){let e=await _2e();return K2e((0,BlI.default)({},e,t))}async function zlI(t={}){if(qU())throw new Error("Settings have already been initialized");return zdt(t)}import{promises as Udt}from"fs";import UlI from"path";var Sdt=3*1024*1024;function SlI(t){let e=UlI.extname(t).toLowerCase();return[".png",".jpg",".jpeg",".gif",".webp"].includes(e)}function Odt(t){switch(UlI.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 Mdt(t,e){e.debug(`Processing local image file: ${t}`);let I=await Udt.readFile(t),l=Odt(t);if(!l)throw new Error(`Unsupported image format: ${t}`);let n=new Yz,c=await x7(e,n,Sdt,Zz,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 Tdt(t,e,I){let l=UG();try{let n=await Vse({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 OlI(t,e,I){let l=[],n=t.filter(r=>!SlI(r.path));if(n.length===0)return l;let c=[];for(let r of n)try{let s=await Tdt(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 MlI(t,e){let I=t.filter(n=>SlI(n.path));return(await Promise.all(I.map(async n=>{try{return{type:"image_url",image_url:{url:await Mdt(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 TlI="copilot-developer-cli",jdt=M2e(I_),W2e=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"}},IR=class t{sessionId;startTime;modifiedTime;logger;events=[];_chatMessages=[];_selectedModel;eventProcessingQueue=Promise.resolve();eventHandlers={};wildcardEventHandlers=[];isProcessing=!1;messageQueue=[];immediatePromptProcessor;mcpHost;workingDir;abortController;allowedTools;disabledTools;requestPermission;mcpServers;hooks;authInfo;constructor(e={}){this.sessionId=e.sessionId||UG(),this.startTime=e.startTime||new Date,this.modifiedTime=e.modifiedTime||this.startTime,this.logger=e.logger||new Vm,this._selectedModel=e.model,this.allowedTools=e.allowedTools,this.disabledTools=e.disabledTools,this.requestPermission=e.requestPermission,this.mcpServers=e.mcpServers,this.hooks=e.hooks,this.authInfo=e.authInfo,this.workingDir=e.workingDirectory||process.cwd(),this.immediatePromptProcessor=new W2e(this.logger,this),nWe(this.workingDir).then(I=>{if(I.found)return o6e(I.gitRoot,!0,this.workingDir)}).catch(I=>{this.logger.debug(`Failed to initialize custom instructions cache: ${I}`)})}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=UG(),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 MlI(e.data.attachments,this.logger);I.push(...n);let c=await OlI(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=Ddt(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){if(e.mode==="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 I=this.messageQueue.shift();this.abortController=I.abortController||new AbortController,await this.runAgenticLoop(I.prompt,I.attachments)}this.isProcessing=!1,this.emitEphemeral("session.idle",{})}}async abort(){this.abortController?.abort()}setAuthInfo(e){this.authInfo=e}async initializeMcpHost(){if(!this.mcpHost&&this.mcpServers&&Object.keys(this.mcpServers).length>0)try{this.mcpHost=new z$(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.authInfo)throw new Error("Session was not created with authentication info");let l=new Map,n=new Map;try{let r=(await rN(this.hooks?.userPromptSubmitted,{timestamp:Date.now(),cwd:this.workingDir,prompt:e},this.logger))?.modifiedPrompt??e;this.emit("user.message",{content:g7({problemStatement:r,capabilities:{}}),attachments:I});let s=await kz(this.authInfo),a=this.authInfo.type!=="hmac"?await jdt(this.authInfo.host,s||"",this.logger):void 0,o=await s$e(this.logger,this.sessionId,this.authInfo,TlI);if(o.type!=="success")throw new Error("Failed to list available models");let G=await f_e(this._selectedModel,this,o.list,this.logger);if(!G)throw new Error("No available models found. Please check your Copilot license and permissions.");let d=new mA().setProblemStatement(r).setAgentModel(`capi:${G}`).setGithubRepoName("copilot-sdk-session").setGithubRepoCommit("copilot-sdk-commit").setGithubRepoReadWrite(!1).setCopilotIntegrationId(TlI).setCopilotUrl(a).setGithubToken(s).setCopilotToken(s).build();P2e();let b=await zlI(d),m=b.service?.agent?.model,h=G3(m),u=h.agent,Z=u??"sweagent-capi",N=h.model?{model:h.model}:void 0,g=Rme(b,this.logger,u,N),y={location:this.workingDir,timeout:3e4,requireReasoning:!0,toolPartialResultCallback:(ne,oI)=>{this.emitEphemeral("tool.execution_partial_result",{toolCallId:ne,partialOutput:oI})},permissions:this.requestPermission?{requestRequired:!0,request:this.requestPermission}:{requestRequired:!1},shellConfig:(process.platform==="win32"?Fb.powerShell:Fb.bash).withScriptSafetyAssessor(async function(ne){return{result:"completed",commands:[{identifier:ne,readOnly:!1}],possiblePaths:[],hasWriteFileRedirection:!1,canOfferSessionApproval:!1}})},A=await w7e(y,this.logger),f=[];if(this.mcpHost)try{f=await this.mcpHost.getTools(b,this.logger,y.permissions)}catch(ne){this.logger.error(`Failed to get MCP tools: ${ne}`)}let J=[...A,...f].filter(ne=>this.allowedTools?this.allowedTools.includes(ne.name):this.disabledTools?!this.disabledTools.includes(ne.name):!0),X=await nWe(this.workingDir),x={...(E7e()[Z]?.[g.model]??X7e()).supports,reasoning:!0},S=await Eqe({location:X.found?X.gitRoot:"",version:LUe(),currentWorkingDirectory:this.workingDir,parts:{},capabilities:x,toolConfigOverrides:y,tools:J,organizationCustomInstructions:void 0}),le=await this.getChatMessages(),be=le.findLastIndex(ne=>ne.role==="user"),Ae=le.filter(ne=>ne.role==="user").at(-1);if(!Ae)throw new Error("No user message found in session messages after sending prompt");typeof Ae.content=="string"?Ae={...Ae,content:g7({customAgentPrompt:void 0,problemStatement:Ae.content,capabilities:x})}:Ae={...Ae,content:Ae.content.map(ne=>ne.type==="text"?{...ne,text:g7({customAgentPrompt:void 0,problemStatement:ne.text,capabilities:x})}:ne)};let we=le.map((ne,oI)=>oI===be?Ae:ne);await rN(this.hooks?.sessionStart,{timestamp:Date.now(),cwd:this.workingDir,source:"new",initialPrompt:e},this.logger);let Le=new fv(Ae,this.logger),Xe=g.getCompletionWithTools(S,we,J,{failIfInitialInputsTooLong:!1,processors:{preRequest:[Le,this.immediatePromptProcessor,new Rz(this.logger)],onRequestError:[Le]},executeToolsInParallel:!1,abortSignal:this.abortController?.signal});for await(let ne of Xe){if(this.abortController?.signal.aborted){this.emit("abort",{reason:"user initiated"});break}switch(ne.kind){case"message":{if(S7(ne)){let oI=R7e(ne)?await Promise.all(ne.message.tool_calls.map(async Ye=>{let ze=UX(Ye.function.arguments);l.set(Ye.id,Ye.function.name),n.set(Ye.id,ze);let nl=await rN(this.hooks?.preToolUse,{timestamp:Date.now(),cwd:this.workingDir,toolName:Ye.function.name,toolArgs:ze},this.logger);return{toolCallId:Ye.id,name:Ye.function.name,arguments:nl?.modifiedArgs??ze}})):[];this.emit("assistant.message",{parentToolCallId:void 0,messageId:UG(),content:typeof ne.message.content=="string"?ne.message.content:"",toolRequests:oI});for(let Ye of oI)this.emit("tool.execution_start",{toolCallId:Ye.toolCallId,toolName:Ye.name,arguments:Ye.arguments})}else(ne.message.role==="system"||ne.message.role==="developer")&&this.emit("system.message",{role:ne.message.role,content:typeof ne.message.content=="string"?ne.message.content:JSON.stringify(ne.message.content),name:"name"in ne.message?ne.message.name:void 0});break}case"model_call_failure":{let oI=new Error(ne.modelCall?.error||"Model call failed");await rN(this.hooks?.errorOccurred,{timestamp:Date.now(),cwd:this.workingDir,error:oI,errorContext:"model_call",recoverable:!0},this.logger),this.emit("session.error",{errorType:"model_call",message:oI.message,stack:oI.stack});break}case"tool_execution":{let Ye=(await rN(this.hooks?.postToolUse,{timestamp:Date.now(),cwd:this.workingDir,toolName:l.get(ne.toolCallId)||"unknown",toolArgs:n.get(ne.toolCallId)||{},toolResult:ne.toolResult},this.logger))?.modifiedResult??ne.toolResult,ze=(Ye.resultType==="failure"?Ye.error:void 0)||Ye.sessionLog||Ye.textResultForLlm;this.emit("tool.execution_complete",{parentToolCallId:void 0,toolCallId:ne.toolCallId,success:Ye.resultType==="success",result:Ye.resultType==="success"?{content:ze}:void 0,error:Ye.resultType!=="success"?{message:ze,code:Ye.resultType}:void 0});break}case"turn_started":{this.emit("assistant.turn_start",{turnId:`${ne.turn}`});break}case"turn_ended":{this.emit("assistant.turn_end",{turnId:`${ne.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: ${ne.kind}`);break;default:vm(ne,"Unhandled event type")}}}catch(c){await rN(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 rN(this.hooks?.sessionEnd,{timestamp:Date.now(),cwd:this.workingDir,reason:"complete"},this.logger)}}};function Ddt(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 Kdt=fe({command:oe(),description:oe(),timeout:Zs().optional(),sessionId:oe().optional(),async:kl().optional()}),Pdt=fe({sessionId:oe(),input:oe(),delay:Zs().optional()}),qdt=fe({sessionId:oe(),delay:Zs()}),_dt=fe({sessionId:oe()}),$dt=wa([Kdt,Pdt,qdt,_dt]),ebt=fe({command:gI("view"),path:oe(),view_range:_7([Zs(),Zs()]).optional()}),Ibt=fe({command:gI("create"),path:oe(),file_text:oe()}),tbt=fe({command:gI("str_replace"),path:oe(),new_str:oe().optional(),old_str:oe()}),lbt=fe({command:gI("insert"),path:oe(),insert_line:Zs(),new_str:oe()}),nbt=wz("command",[ebt,Ibt,tbt,lbt]),eKl=fe({path:oe(),view_range:_7([Zs(),Zs()]).optional()}),IKl=fe({path:oe(),file_text:oe()}),tKl=fe({path:oe(),old_str:oe(),new_str:oe().optional()}),N2e=wa([$dt,nbt,eu()]);var OU=fe({type:gI("text"),text:oe()}),rbt=fe({type:gI("refusal"),refusal:oe()}),sbt=fe({type:gI("image_url"),image_url:fe({url:oe(),detail:Iu(["auto","low","high"]).optional()})}),abt=fe({type:gI("input_audio"),input_audio:fe({data:oe(),format:gI("wav").or(gI("mp3"))})}),obt=fe({type:gI("file"),file:fe({file_date:oe().optional(),file_id:oe().optional(),filename:oe().optional()})}),Gbt=wa([OU,sbt,abt,obt]),ibt=fe({name:oe(),arguments:oe()}),dbt=fe({name:oe(),input:oe()}),bbt=fe({id:oe(),type:gI("function"),function:ibt}),mbt=fe({id:oe(),type:gI("custom"),custom:dbt}),hbt=wa([bbt,mbt]),pbt=fe({name:oe(),arguments:oe()}),ubt=fe({id:oe()}),Zbt=fe({content:wa([oe(),Ws(OU)]),role:gI("developer"),name:oe().optional()}),Wbt=fe({content:wa([oe(),Ws(OU)]),role:gI("system"),name:oe().optional()}),Nbt=fe({content:wa([oe(),Ws(Gbt)]),role:gI("user"),name:oe().optional()}),Ybt=fe({content:wa([oe(),Ws(wa([OU,rbt]))]).nullable().optional(),role:gI("assistant"),name:oe().optional(),refusal:oe().nullable().optional(),audio:ubt.nullable().optional(),function_call:pbt.nullable().optional(),tool_calls:Ws(hbt).optional()}),Vbt=fe({content:wa([oe(),Ws(OU)]),role:gI("tool"),tool_call_id:oe()}),Rbt=fe({content:oe().nullable(),role:gI("function"),name:oe()}),ybt=wa([Zbt,Wbt,Nbt,Ybt,Vbt,Rbt]),gbt=fe({type:gI("copilot"),text:oe(),isStreaming:kl().optional()}),Fbt=fe({type:gI("error"),text:oe()}),Abt=fe({type:gI("info"),text:oe()}),Qbt=fe({type:gI("user"),text:oe()}),wbt=fe({type:gI("tool_call_requested"),callId:oe(),name:oe(),toolTitle:oe().optional(),intentionSummary:oe().nullable(),arguments:N2e,partialOutput:oe().optional(),isHidden:kl().optional(),isAlwaysExpanded:kl().optional(),showNoContent:kl().optional()}),Xbt=fe({type:gI("tool_call_completed"),callId:oe(),name:oe(),toolTitle:oe().optional(),intentionSummary:oe().nullable(),result:wa([fe({type:gI("success"),log:oe(),markdown:kl().optional()}),fe({type:gI("failure"),log:oe(),markdown:kl().optional()}),fe({type:gI("rejected"),markdown:kl().optional()}),fe({type:gI("denied"),log:oe(),markdown:kl().optional()})]),arguments:N2e,isHidden:kl().optional(),isAlwaysExpanded:kl().optional(),showNoContent:kl().optional()}),Ebt=wa([gbt,Fbt,Abt,Qbt,wbt,Xbt]),Hbt=Ebt.and(fe({id:oe(),timestamp:$7.date()})),Y2e=fe({sessionId:oe(),startTime:$7.date(),chatMessages:Ws(ybt),timeline:Ws(Hbt),selectedModel:Iu(g_).optional()}),tR=E_e(Y2e.parse,"history-session");var Nr=fe({id:oe().uuid(),timestamp:oe().datetime(),parentId:oe().uuid().nullable(),ephemeral:kl().optional()}),jlI=fe({parentToolCallId:oe().optional()}),vbt=Nr.extend({type:gI("session.start"),data:fe({sessionId:oe(),version:Zs(),producer:oe(),copilotVersion:oe(),startTime:oe().datetime(),selectedModel:oe().optional()})}),Cbt=Nr.extend({type:gI("session.resume"),data:fe({resumeTime:oe().datetime(),eventCount:Zs()})}),Jbt=Nr.extend({type:gI("session.error"),data:fe({errorType:oe(),message:oe(),stack:oe().optional()})}),Lbt=Nr.extend({type:gI("session.info"),data:fe({infoType:oe(),message:oe()})}),fbt=Nr.extend({type:gI("session.model_change"),data:fe({previousModel:oe().optional(),newModel:oe()})}),kbt=Nr.extend({type:gI("session.import_legacy"),data:fe({legacySession:Y2e,importTime:oe().datetime(),sourceFile:oe()})}),xbt=Nr.extend({type:gI("session.idle"),ephemeral:gI(!0),data:fe({})}),Bbt=fe({type:Iu(["file","directory"]),path:oe(),displayName:oe()}),zbt=Nr.extend({type:gI("user.message"),data:fe({content:oe(),attachments:Ws(Bbt).optional()})}),Ubt=Nr.extend({type:gI("assistant.turn_start"),data:fe({turnId:oe()})}),Sbt=Nr.extend({type:gI("assistant.message"),data:fe({messageId:oe(),content:oe(),toolRequests:Ws(fe({toolCallId:oe(),name:oe(),arguments:eu()})).optional()}).merge(jlI)}),Obt=Nr.extend({type:gI("assistant.turn_end"),data:fe({turnId:oe()})}),Mbt=Nr.extend({type:gI("assistant.usage"),ephemeral:gI(!0),data:fe({model:oe().optional(),inputTokens:Zs().optional(),outputTokens:Zs().optional(),cost:Zs().optional(),duration:Zs().optional(),initiator:oe().optional()})}),Tbt=Nr.extend({type:gI("abort"),data:fe({reason:oe()})}),jbt=Nr.extend({type:gI("tool.user_requested"),data:fe({toolCallId:oe(),toolName:oe(),arguments:eu()})}),Dbt=Nr.extend({type:gI("tool.execution_start"),data:fe({toolCallId:oe(),toolName:oe(),arguments:eu()})}),Kbt=Nr.extend({type:gI("tool.execution_partial_result"),ephemeral:gI(!0),data:fe({toolCallId:oe(),partialOutput:oe()})}),Pbt=Nr.extend({type:gI("tool.execution_complete"),data:fe({toolCallId:oe(),success:kl(),isUserRequested:kl().optional(),result:fe({content:oe()}).optional(),error:fe({message:oe(),code:oe().optional()}).optional()}).merge(jlI)}),qbt=Nr.extend({type:gI("hook.start"),data:fe({hookInvocationId:oe(),hookType:oe(),input:eu()})}),_bt=Nr.extend({type:gI("hook.end"),data:fe({hookInvocationId:oe(),hookType:oe(),output:eu(),success:kl(),error:fe({message:oe(),stack:oe().optional()}).optional()})}),$bt=Nr.extend({type:gI("system.message"),data:fe({content:oe(),role:Iu(["system","developer"]),name:oe().optional(),metadata:fe({promptVersion:oe().optional(),variables:Tv(eu()).optional()}).optional()})}),DlI=wz("type",[vbt,Cbt,Jbt,xbt,Lbt,fbt,kbt,zbt,Ubt,Sbt,Obt,Mbt,Tbt,jbt,Dbt,Kbt,Pbt,qbt,_bt,$bt]);var lR=H_e(DlI.parse,"session");var P$=class{constructor(e,I,l,n=!1,c){this.session=e;this.logger=I;this.flushDebounceMs=l;this.shouldSaveSession=n;this.legacySourceFile=c;this.unsubscribe=this.session.on("*",r=>{r.ephemeral||(this.unflushedEvents.push(r),!this.shouldSaveSession&&r.type==="user.message"&&(this.shouldSaveSession=!0),r.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 lR.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 V2e(this.legacySourceFile)}catch(I){this.logger.error(`Failed to delete legacy session file ${this.legacySourceFile}: ${I}`)}this.migratedLegacy=!0}}catch(I){this.logger.error(`Failed to flush events for ${this.session.sessionId}: ${I instanceof Error?I.message:String(I)}`),this.unflushedEvents.unshift(...e)}finally{this.isFlushing=!1,this.needsFlushAfterCurrent&&(this.needsFlushAfterCurrent=!1,await this.flush())}}};function KlI(t){if(t.role==="user")return typeof t.content=="string"?t.content:t.content.find(e=>e.type==="text")?.text}async function tmt(t){if(emt(t))try{return await S2e(t,e=>{if(e.trim())try{let I=JSON.parse(e);if(I.type==="session.import_legacy"){let l=I.data.legacySession.chatMessages.find(n=>n.role==="user");if(l?.content){let n=KlI(l);if(n)return R2e(n)}}if(I.type==="user.message"){let l=I.data.content;if(l)return R2e(l)}return}catch{return}})}catch{return}}function R2e(t){let e=t.lastIndexOf("<reminder>");e!==-1&&(t=t.substring(0,e).trim());let I=t.replace(/\s+/g," ").trim();return I.length>75&&(I=I.substring(0,55).trim()+"..."),I=I.split("").filter(l=>{let n=l.charCodeAt(0);return n>=32&&n!==127}).join(""),I}var y2e=class{sessionWriters={};copilotVersion;flushDebounceMs;logger;constructor({version:e,flushDebounceMs:I,...l}){this.logger=l.logger||new Vm,this.copilotVersion=e||"unknown",this.flushDebounceMs=I||100}async createSession(e){let I=new IR({...e,startTime:e?.startTime||new Date});return this.sessionWriters[I.sessionId]=new P$(I,this.logger,this.flushDebounceMs),I.emit("session.start",{sessionId:I.sessionId,version:1,producer:"copilot-agent",copilotVersion:this.copilotVersion,startTime:I.startTime.toISOString(),selectedModel:e?.model}),I}async getSession(e,I=!0){let l,n;try{l=await this.loadSession(e)}catch{try{let c=await this.loadLegacySession(e);l=c.session,n=c.legacySourceFile}catch{return}}return this.sessionWriters[e.sessionId]||(this.sessionWriters[e.sessionId]=new P$(l,this.logger,this.flushDebounceMs,!0,n)),I&&l.emit("session.resume",{resumeTime:new Date().toISOString(),eventCount:l.getEvents().length}),l}async getLastSession(e={}){let I=await this.listSessions();if(I.length===0)return;I.sort((n,c)=>c.modifiedTime.getTime()-n.modifiedTime.getTime());let l=I[0].sessionId;return await this.getSession({...e,sessionId:l})}async saveSession(e){await this.sessionWriters[e.sessionId]?.flush()}async loadSession(e){let I=await lR.load(e.sessionId);return await IR.fromEvents(I,e)}async loadLegacySession(e){let l=(await tR.directoryFiles()).filter(a=>{let o=a.match(/^session_(.+)_(\d+)\.json$/);return o&&o[1]===e.sessionId});if(l.length===0)throw new Error(`Legacy session ${e.sessionId} not found`);let n=l[0];l.length>1&&this.logger.info(`Multiple legacy sessions found for ${e.sessionId}, using newest`);let c=await tR.load(n);if(!c)throw new Error(`Failed to load legacy session from ${n}`);let r=new Date(c.startTime),s=new IR({...e,sessionId:c.sessionId,startTime:r});return s.emit("session.start",{sessionId:c.sessionId,version:1,producer:"copilot-agent",copilotVersion:this.copilotVersion,startTime:r.toISOString(),selectedModel:c.selectedModel}),s.emit("session.import_legacy",{legacySession:{sessionId:c.sessionId,startTime:r,chatMessages:c.chatMessages,timeline:c.timeline,selectedModel:c.selectedModel},importTime:new Date().toISOString(),sourceFile:n}),this.logger.info(`Loaded legacy session ${e.sessionId} from ${n}`),{session:s,legacySourceFile:tR.path(n.replace(/\.json$/,""))}}async listSessions(){let e=await lR.directoryFilesWithMetadata(),I=await tR.directoryFilesWithMetadata(),l=await Promise.all(e.map(async r=>{let s=r.file.replace(".jsonl",""),a=lR.path(s),o=await tmt(a);return{sessionId:s,startTime:r.birthtime,modifiedTime:r.mtime,summary:o}})),n=(await Promise.all(I.map(async r=>{let s=r.file.match(/^session_(.+)_(\d+)\.json$/);if(!s)return null;let a=s[1],o;try{let G=await tR.load(r.file.replace(/\.json$/,""));if(G){let i=G.chatMessages?.find(d=>d.role==="user");if(i?.content){let d=KlI(i);d&&(o=R2e(d))}}}catch{}return{sessionId:a,startTime:r.birthtime,modifiedTime:r.mtime,summary:o}}))).filter(r=>r!==null);this.logger.debug(`Found ${l.length} JSONL sessions and ${n.length} legacy sessions`);let c=new Map;for(let r of n)c.set(r.sessionId,r);for(let r of l)c.set(r.sessionId,r);return Array.from(c.values()).sort((r,s)=>s.modifiedTime.getTime()-r.modifiedTime.getTime())}async deleteSession(e){await this.closeSession(e);let I=lR.path(e);try{await V2e(I),this.logger.info(`Deleted session file ${I}`);return}catch{let c=(await tR.directoryFiles()).filter(r=>{let s=r.match(/^session_(.+)_(\d+)\.json$/);return s&&s[1]===e});if(c.length===0)throw new Error(`Session file not found for ${e}`);for(let r of c){let s=tR.path(r.replace(/\.json$/,""));this.logger.info(`Deleting legacy session file ${s}`),await V2e(s)}}}async closeSession(e){this.logger.info(`Closing session ${e}`);let I=this.sessionWriters[e];I&&(await I.flush(),I.dispose(),delete this.sessionWriters[e])}getSessionsDirectory(){return Imt(lR.home(),lR.directory())}setLogger(e){this.logger=e}};var g2e=class{loggers;constructor(e){this.loggers=e}isDebug(){return this.loggers.some(e=>e.isDebug())}debug(e){this.loggers.forEach(I=>I.debug(e))}log(e){this.loggers.forEach(I=>I.log(e))}info(e){this.loggers.forEach(I=>I.info(e))}notice(e){this.loggers.forEach(I=>I.notice(e))}warning(e){this.loggers.forEach(I=>I.warning(e))}error(e){this.loggers.forEach(I=>I.error(e))}startGroup(e,I){this.loggers.forEach(l=>l.startGroup(e,I))}endGroup(e){this.loggers.forEach(I=>I.endGroup(e))}};import{appendFile as lmt,access as nmt,mkdir as cmt}from"fs/promises";import{constants as rmt}from"fs";import{dirname as smt}from"path";var F2e=class extends bu{constructor(I,l,n){super(l,n);this.filePath=I;this.writeQueue=amt(smt(this.filePath)).catch(()=>{})}writeQueue=Promise.resolve();log(I){this.write("LOG",I)}debug(I){super.shouldLog(8)&&this.write("DEBUG",this.filterSecrets(I).toString())}info(I){super.shouldLog(4)&&this.write("INFO",this.filterSecrets(I).toString())}notice(I){super.shouldLog(2)&&this.write("NOTICE",this.filterSecrets(I).toString())}warning(I){super.shouldLog(2)&&this.write("WARNING",this.filterSecrets(I).toString())}error(I){super.shouldLog(1)&&this.write("ERROR",this.filterSecrets(I).toString())}startGroup(I,l){super.shouldLog(l||4)&&this.write("START-GROUP",I)}endGroup(I){super.shouldLog(I||4)&&this.write("END-GROUP","")}write(I,l){let c=`${new Date().toISOString()} [${I}] ${l}
1501
1501
  `;this.writeQueue=this.writeQueue.then(()=>this.performWrite(c)).catch(()=>{})}async performWrite(I){await lmt(this.filePath,I)}};async function amt(t){try{await nmt(t,rmt.F_OK)}catch{await cmt(t,{recursive:!0})}}async function zKl(){return L_e}async function*OKl(t){let{prompt:e,abortController:I,...l}=t,n=new IR(l),c=[],r=!1,s=n.on("*",o=>{c.push(o),o.type==="session.idle"&&(r=!0)}),a={prompt:e};for(I&&(a.abortController=I),n.send(a);!r||c.length>0;){let o=c.shift();o?yield o:await new Promise(G=>setTimeout(G,10))}s()}export{bu as BaseLogger,g2e as CompoundLogger,vR as ConsoleLogger,F2e as FileLogger,Vm as NoopLogger,IR as Session,DlI as SessionEventSchema,Ddt as completeOrphanedToolCalls,rN as executeHooks,zKl as getAvailableModels,PlI as internal,kC as isDebugEnvironment,OKl as query};
1502
1502
  /*! Bundled license information:
1503
1503