@github/copilot 0.0.348-12 → 0.0.348-13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.js +1 -1
- package/package.json +2 -2
- package/sdk/index.js +1 -1
- package/sdk/index.js.map +2 -2
package/index.js
CHANGED
|
@@ -1972,7 +1972,7 @@ ${I}`;await r.logMCPSetup(e,s),this.logger.log(`Updated session log for ${e} wit
|
|
|
1972
1972
|
`)),s}}import{homedir as ADt}from"node:os";import _Fn,{resolve as DFn}from"node:path";c();function AVn(t){return t.length>0&&/^[0-9a-zA-Z_-]+$/.test(t)}function jMt(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 PMt=_g(["none","markdown","hidden_characters"]),KMt=Dl({tools:Jd(Rt()),type:Rt().optional(),isDefaultServer:Yo().optional(),filterMapping:S2(Rt(),PMt).or(PMt).optional()}),ZVn=KMt.extend({type:Zr("local").optional(),command:Rt(),args:Jd(Rt()),env:S2(Rt(),Rt()).optional()}),gVn=KMt.extend({type:Zr("http").or(Zr("sse")),url:Rt(),headers:S2(Rt(),Rt()).optional()}),y8e=Dl({mcpServers:S2(Rt().min(1,"MCP server name cannot be empty").refine(AVn,{message:"MCP server name must only contain alphanumeric characters, underscores, and hyphens"}),ZVn.or(gVn))}),z2=wVe(y8e.parse,"mcp");c();c();function qMt(t){let e=t.r/255,l=t.g/255,n=t.b/255,r=Math.max(e,l,n),I=Math.min(e,l,n),a=r-I,s=0,o=0,d=(r+I)/2;if(a!==0){switch(o=d>.5?a/(2-r-I):a/(r+I),r){case e:s=(l-n)/a+(l<n?6:0);break;case l:s=(n-e)/a+2;break;case n:s=(e-l)/a+4;break}s/=6}return{h:s*360,s:o,l:d}}function NVn(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,I=d=>d.length>=2?parseInt(d.substring(0,2),16):d.length===1?parseInt(d+d,16):0,a=I(l),s=I(n),o=I(r);return{r:a,g:s,b:o}}var $Mt=["#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 WVn(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 yVn(t){return t<0||t>=$Mt.length?{r:0,g:0,b:0}:WVn($Mt[t])}function e_t(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:")?NVn(l):null}async function EVn(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",I),process.stdin.setRawMode(!1),n&&clearTimeout(n)},I=a=>{l+=a.toString();let s=l.match(/\x1b\]11;([^\x07\x1b\x9c]*?)(?:\x07|\x1b\\|\x9c)/);if(s){r();let d=`11;${s[1]}`;e(e_t(d));return}let o=l.match(/11;rgb:([0-9a-f/]+)(?:\x07|\x1b\\|\x9c)/i);if(o){r(),e(e_t(`11;rgb:${o[1]}`));return}};n=setTimeout(()=>{r(),e(null)},t);try{process.stdin.setRawMode(!0),process.stdin.on("data",I),process.stdout.write("\x1B]11;?\x1B\\")}catch{r(),e(null)}})}function RVn(){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:yVn(n)}async function t_t(){try{let t=await EVn();if(t)return qMt(t).l<.5;let e=RVn();return e?qMt(e).l<.5:!0}catch{return!0}}var l_t={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"},YVn={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 E8e(t){return t==="auto"||t==="dark"||t==="light"}function kVe(t){switch(t){case"dark":return l_t;case"light":return YVn;default:return l_t}}var LVe=await t_t();async function JVe(){let e=(await kr.load())?.theme||"";return E8e(e)?e:"auto"}async function n_t(t){await kr.writeKey("theme",t)}var r_t=t=>{let e=t?xl.whiteBright:xl.black,l=t?xl.cyanBright:xl.blueBright,n=t?xl.magentaBright:xl.magenta;return{text:e,paragraph:e,html:e,table:e,blockquote:e,heading:xl.bold,firstHeading:xl.whiteBright.bold,strong:xl.bold,em:xl.italic,del:xl.strikethrough,hr:xl.white,link:l,href:l,image:(r,I,a)=>n(a?`Image: ${a} \u2192 ${r}`:`Image: ${r}`),codespan:xl.cyan,code:xl.cyan,list:(r,I,a)=>{let s=r.replace(/^(\s*)\* /gm,"$1- ");return a&&(s=s.split(`
|
|
1973
1973
|
`).map(u=>u.startsWith(a)?u.slice(a.length):u).join(`
|
|
1974
1974
|
`)),s.trimEnd()},listitem:r=>e(r.trimEnd()),reflowText:!0,showSectionPrefix:!1,unescape:!0,emoji:!0,tab:2,tableOptions:{style:{compact:!1}}}},VVn=r_t(!0),wVn=r_t(!1);function I_t(t){return t==="light"?wVn:VVn}c();import{exec as TFn}from"node:child_process";import*as j8e from"node:os";import{promisify as UFn}from"node:util";c();c();c();import{execFile as QVn}from"node:child_process";import{normalize as FVn}from"node:path";import{promisify as CVn}from"node:util";var iue=CVn(QVn);async function If(t=process.cwd()){try{let l=(await iue("git",["rev-parse","--show-toplevel"],{cwd:t,encoding:"utf8",timeout:5e3,maxBuffer:1048576})).stdout.trim();if(l)return{gitRoot:FVn(l),found:!0}}catch{}return{gitRoot:t,found:!1}}async function a_t(t){let{stdout:e}=await iue("git",["-C",t,"remote","-v"],{encoding:"utf8",timeout:5e3,maxBuffer:1048576}),l=e.trim().split(`
|
|
1975
|
-
`),n={};for(let r of l){let I=r.split(/\s+/);if(I.length>=3){let a=I[0],s=I[1],o=I[2].replace(/[()]/g,"");n[a]||(n[a]={Name:a,FetchURL:"",PushURL:""}),o==="fetch"?n[a].FetchURL=s:o==="push"&&(n[a].PushURL=s)}}return Object.values(n)}async function s_t(t){try{let{stdout:e}=await iue("git",["status","--porcelain"],{cwd:t,encoding:"utf8",timeout:5e3,maxBuffer:1048576});return e.trim().length>0}catch{return!1}}async function o_t(t){try{let{stdout:e}=await iue("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:t,encoding:"utf8",timeout:5e3,maxBuffer:1048576}),l=e.trim();if(l==="HEAD"){let{stdout:n}=await iue("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}}c();var J_t=lt(L_t(),1);async function EQn(t={}){let e=await dAt();return bAt((0,J_t.default)({},e,t))}async function DVe(t={}){if(C_())throw new Error("Settings have already been initialized");return EQn(t)}c();c();c();import{promises as RQn}from"fs";import x_t from"path";var YQn=3*1024*1024;function S_t(t){let e=x_t.extname(t).toLowerCase();return[".png",".jpg",".jpeg",".gif",".webp"].includes(e)}function VQn(t){switch(x_t.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 wQn(t,e){e.debug(`Processing local image file: ${t}`);let l=await RQn.readFile(t),n=VQn(t);if(!n)throw new Error(`Unsupported image format: ${t}`);let r=new tse,I=await _ye(e,r,YQn,qae,n,l);if(!I)throw new Error(`Image too large or couldn't be processed: ${t}`);let a=I.toString("base64");return`data:${n};base64,${a}`}async function QQn(t,e){let l=Uu();try{let n=await aSe({command:"view",path:t,view_range:void 0},{properties:{command:"view",resolvedPathAgainstCwd:"false",options:"{}",inputs:"[]"},metrics:{responseTokenLimit:void 0,resultLength:0,resultForLlmLength:0},restrictedProperties:{}},e);return{id: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 B_t(t,e){let l=[],n=t.filter(I=>!S_t(I.path));if(n.length===0)return l;let r=[];for(let I of n)try{let a=await QQn(I.path,e);r.push(a)}catch{}if(r.length>0){let I=r.map(a=>({id:a.id,type:"function",function:{name:a.name,arguments:JSON.stringify(a.arguments)}}));l.push({role:"assistant",content:"I need to read the content of those paths to answer this request.",tool_calls:I}),l.push(...r.map(a=>({role:"tool",tool_call_id:a.id,content:a.result})))}return l}async function O_t(t,e){let l=t.filter(r=>S_t(r.path));return(await Promise.all(l.map(async r=>{try{return{type:"image_url",image_url:{url:await wQn(r.path,e)}}}catch(I){e.error(`Failed to process image ${r.path}: ${I instanceof Error?I.message:String(I)}`);return}}))).filter(r=>r!==void 0)}var of=class{sessionId;startTime;modifiedTime;events=[];_chatMessages=[];_selectedModel;logger;eventCallbacks=[];eventProcessingQueue=Promise.resolve();constructor({sessionId:e,startTime:l,modifiedTime:n,logger:r}={}){this.sessionId=e||Uu(),this.startTime=l||new Date,this.modifiedTime=n||this.startTime,this.logger=r||new Hc}get messageCount(){let e=this.events.find(n=>n.type==="session.import_legacy"),l=0;return e&&(l=(e.data.legacySession?.chatMessages||[]).filter(I=>I.role==="user"||I.role==="assistant").length),this.logger.debug(`Imported message count: ${l}`),this.events.filter(n=>n.type==="user.message"||n.type==="assistant.message").length+l}get summary(){let e=this.events.find(I=>I.type==="session.import_legacy"||I.type==="user.message"),l;if(e?.type==="session.import_legacy"){let I=e.data.legacySession.chatMessages.find(a=>a.role==="user");I?.content&&(typeof I.content=="string"?l=I.content:l=I.content.find(a=>a.type==="text")?.text)}else e?.type==="user.message"&&(l=e.data.content);if(!l)return;let n=l.lastIndexOf("<reminder>");n!==-1&&(l=l.substring(0,n).trim());let r=l.replace(/\s+/g," ").trim();return r.length>75&&(r=r.substring(0,55).trim()+"..."),r=r.split("").filter(I=>{let a=I.charCodeAt(0);return a>=32&&a!==127}).join(""),r}static async fromEvents({events:e,logger: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 this({sessionId:n.data.sessionId,startTime:new Date(n.data.startTime),logger:l||new Hc});r._selectedModel=n.data.selectedModel,r.events.push(n);for(let I=1;I<e.length;I++){let a=e[I];r.events.push(a),await r.processEventForState(a)}return r}addEvent(e){let l=e.id||Uu(),n=e.timestamp||new Date().toISOString(),r=e.parentId!==void 0?e.parentId:this.getLastEventId(),I={...e,id:l,timestamp:n,parentId:r};return this.events.push(I),this.enqueueEventProcessing(()=>this.processEventForState(I).catch(a=>{this.logger.error(`Error processing event ${I.type} (${I.id}): ${a instanceof Error?a.message:String(a)}`)})).catch(a=>{this.logger.error(`Error processing event queue ${a instanceof Error?a.message:String(a)}`)}),this.notifyEventCallbacks(I),I}getEvents(){return this.events}onEvent(e){return this.eventCallbacks.push(e),()=>{let l=this.eventCallbacks.indexOf(e);l>-1&&this.eventCallbacks.splice(l,1)}}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)}setSelectedModel(e){let l=this._selectedModel;this._selectedModel=e,this.addEvent({type:"session.model_change",data:{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 O_t(e.data.attachments,this.logger);l.push(...r);let I=await B_t(e.data.attachments,this.logger);n.push(...I)}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":{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":{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=FQn(this._chatMessages,this.logger);break;case"session.error":case"session.info":case"assistant.turn_start":case"assistant.turn_end":case"assistant.usage":case"tool.user_requested":case"tool.execution_start":case"tool.execution_partial_result":case"hook.start":case"hook.end":break;default:{let l=e;this.logger.error(`Unknown event type: ${l.type}`);break}}}notifyEventCallbacks(e){for(let l of this.eventCallbacks)try{l(e)}catch(n){this.logger.error(`Error in event callback: ${n instanceof Error?n.message:String(n)}`)}}};function FQn(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 d of o.tool_calls)n.has(d.id)||l.push(d.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 I="The execution of this tool, or a previous tool was interrupted.";e.info(`Completing ${l.length} orphaned tool calls.`);let a=l.map(s=>({role:"tool",tool_call_id:s,content:I}));return[...t,...a]}c();c();import{unlink as z_t}from"fs/promises";import{join as VFn}from"path";c();var zVe=class{sessions;logger;lastAccessedSessionId;constructor({logger:e}={}){this.sessions=new Map,this.logger=e||new Hc}async createSession(){let e=new of({logger:this.logger});return this.sessions.set(e.sessionId,e),this.lastAccessedSessionId=e.sessionId,e}async getSession(e){let l=this.sessions.get(e);return l&&(this.lastAccessedSessionId=e),l}async getLastSession(){if(this.lastAccessedSessionId){let n=this.sessions.get(this.lastAccessedSessionId);if(n)return n}let e=Array.from(this.sessions.values());if(e.length===0)return;e.sort((n,r)=>r.startTime.getTime()-n.startTime.getTime());let l=e[0];return this.lastAccessedSessionId=l.sessionId,l}async listSessions(){return Array.from(this.sessions.values()).map(e=>({sessionId:e.sessionId,startTime:e.startTime,modifiedTime:e.modifiedTime}))}async saveSession(e){}async deleteSession(e){this.sessions.delete(e.sessionId),this.lastAccessedSessionId===e.sessionId&&(this.lastAccessedSessionId=void 0)}};c();c();var CQn=Dl({type:Zr("copilot"),text:Rt(),isStreaming:Yo().optional()}),vQn=Dl({type:Zr("error"),text:Rt()}),fQn=Dl({type:Zr("info"),text:Rt()}),w0a=Dl({displayText:Rt(),fullPath:Rt(),type:_g(["file","directory","unresolved","image"]),startIndex:CG()}),HQn=Dl({type:Zr("user"),text:Rt()}),B8=Dl({command:Rt(),description:Rt(),timeout:CG().optional(),sessionId:Rt().optional(),async:Yo().optional()}),X8e=Dl({sessionId:Rt(),input:Rt(),delay:CG().optional()}),k8e=Dl({sessionId:Rt(),delay:CG()}),L8e=Dl({sessionId:Rt()}),T_t=fh([B8,X8e,k8e,L8e]),XQn=Dl({command:Zr("view"),path:Rt(),view_range:zYe([CG(),CG()]).optional()}),kQn=Dl({command:Zr("create"),path:Rt(),file_text:Rt()}),LQn=Dl({command:Zr("str_replace"),path:Rt(),new_str:Rt().optional(),old_str:Rt()}),JQn=Dl({command:Zr("insert"),path:Rt(),insert_line:CG(),new_str:Rt()}),J8e=tde("command",[XQn,kQn,LQn,JQn]),x8e=Dl({path:Rt(),view_range:zYe([CG(),CG()]).optional()}),S8e=Dl({path:Rt(),file_text:Rt()}),B8e=Dl({path:Rt(),old_str:Rt(),new_str:Rt().optional()}),U_t=fh([T_t,J8e,gw()]),xQn=Dl({type:Zr("tool_call_requested"),callId:Rt(),name:Rt(),toolTitle:Rt().optional(),intentionSummary:Rt().nullable(),arguments:U_t,partialOutput:Rt().optional(),isHidden:Yo().optional(),isAlwaysExpanded:Yo().optional(),showNoContent:Yo().optional()}),SQn=Dl({type:Zr("tool_call_completed"),callId:Rt(),name:Rt(),toolTitle:Rt().optional(),intentionSummary:Rt().nullable(),result:fh([Dl({type:Zr("success"),log:Rt(),markdown:Yo().optional()}),Dl({type:Zr("failure"),log:Rt(),markdown:Yo().optional()}),Dl({type:Zr("rejected"),markdown:Yo().optional()}),Dl({type:Zr("denied"),log:Rt(),markdown:Yo().optional()})]),arguments:U_t,isHidden:Yo().optional(),isAlwaysExpanded:Yo().optional(),showNoContent:Yo().optional()}),BQn=fh([CQn,vQn,fQn,HQn,xQn,SQn]),M_t=BQn.and(Dl({id:Rt(),timestamp:lde.date()}));function __t(t,e){switch(t.type){case"copilot":return e.onCopilot(t);case"error":return e.onError(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:{let l=t;throw new Error(`Unexpected message type: ${JSON.stringify(t)}`)}}}var vO=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 Gue=Dl({type:Zr("text"),text:Rt()}),OQn=Dl({type:Zr("refusal"),refusal:Rt()}),TQn=Dl({type:Zr("image_url"),image_url:Dl({url:Rt(),detail:_g(["auto","low","high"]).optional()})}),UQn=Dl({type:Zr("input_audio"),input_audio:Dl({data:Rt(),format:Zr("wav").or(Zr("mp3"))})}),MQn=Dl({type:Zr("file"),file:Dl({file_date:Rt().optional(),file_id:Rt().optional(),filename:Rt().optional()})}),_Qn=fh([Gue,TQn,UQn,MQn]),DQn=Dl({name:Rt(),arguments:Rt()}),zQn=Dl({name:Rt(),input:Rt()}),PQn=Dl({id:Rt(),type:Zr("function"),function:DQn}),jQn=Dl({id:Rt(),type:Zr("custom"),custom:zQn}),KQn=fh([PQn,jQn]),qQn=Dl({name:Rt(),arguments:Rt()}),$Qn=Dl({id:Rt()}),eFn=Dl({content:fh([Rt(),Jd(Gue)]),role:Zr("developer"),name:Rt().optional()}),tFn=Dl({content:fh([Rt(),Jd(Gue)]),role:Zr("system"),name:Rt().optional()}),lFn=Dl({content:fh([Rt(),Jd(_Qn)]),role:Zr("user"),name:Rt().optional()}),nFn=Dl({content:fh([Rt(),Jd(fh([Gue,OQn]))]).nullable().optional(),role:Zr("assistant"),name:Rt().optional(),refusal:Rt().nullable().optional(),audio:$Qn.nullable().optional(),function_call:qQn.nullable().optional(),tool_calls:Jd(KQn).optional()}),rFn=Dl({content:fh([Rt(),Jd(Gue)]),role:Zr("tool"),tool_call_id:Rt()}),IFn=Dl({content:Rt().nullable(),role:Zr("function"),name:Rt()}),aFn=fh([eFn,tFn,lFn,nFn,rFn,IFn]),O8e=Dl({sessionId:Rt(),startTime:lde.date(),chatMessages:Jd(aFn),timeline:Jd(M_t),selectedModel:_g(YO).optional()}),pue=QVe(O8e.parse,"history-session");c();c();var wb=Dl({id:Rt().uuid(),timestamp:Rt().datetime(),parentId:Rt().uuid().nullable(),ephemeral:Yo().optional()}),sFn=wb.extend({type:Zr("session.start"),data:Dl({sessionId:Rt(),version:CG(),producer:Rt(),copilotVersion:Rt(),startTime:Rt().datetime(),selectedModel:Rt().optional()})}),oFn=wb.extend({type:Zr("session.resume"),data:Dl({resumeTime:Rt().datetime(),eventCount:CG()})}),iFn=wb.extend({type:Zr("session.error"),data:Dl({errorType:Rt(),message:Rt(),stack:Rt().optional()})}),cFn=wb.extend({type:Zr("session.info"),data:Dl({infoType:Rt(),message:Rt()})}),dFn=wb.extend({type:Zr("session.model_change"),data:Dl({previousModel:Rt().optional(),newModel:Rt()})}),uFn=wb.extend({type:Zr("session.import_legacy"),data:Dl({legacySession:O8e,importTime:Rt().datetime(),sourceFile:Rt()})}),mFn=Dl({type:_g(["file","directory"]),path:Rt(),displayName:Rt()}),bFn=wb.extend({type:Zr("user.message"),data:Dl({content:Rt(),attachments:Jd(mFn).optional()})}),GFn=wb.extend({type:Zr("assistant.turn_start"),data:Dl({turnId:Rt()})}),pFn=wb.extend({type:Zr("assistant.message"),data:Dl({messageId:Rt(),content:Rt(),toolRequests:Jd(Dl({toolCallId:Rt(),name:Rt(),arguments:gw()})).optional()})}),hFn=wb.extend({type:Zr("assistant.turn_end"),data:Dl({turnId:Rt()})}),AFn=wb.extend({type:Zr("assistant.usage"),ephemeral:Zr(!0),data:Dl({model:Rt().optional(),tokensUsed:CG().optional(),cost:CG().optional(),duration:CG().optional(),initiator:Rt().optional()})}),ZFn=wb.extend({type:Zr("abort"),data:Dl({reason:Rt()})}),gFn=wb.extend({type:Zr("tool.user_requested"),data:Dl({toolCallId:Rt(),toolName:Rt(),arguments:gw()})}),NFn=wb.extend({type:Zr("tool.execution_start"),data:Dl({toolCallId:Rt(),toolName:Rt(),arguments:gw()})}),WFn=wb.extend({type:Zr("tool.execution_partial_result"),ephemeral:Zr(!0),data:Dl({toolCallId:Rt(),partialOutput:Rt()})}),yFn=wb.extend({type:Zr("tool.execution_complete"),data:Dl({toolCallId:Rt(),success:Yo(),isUserRequested:Yo().optional(),result:Dl({content:Rt()}).optional(),error:Dl({message:Rt(),code:Rt().optional()}).optional()})}),EFn=wb.extend({type:Zr("hook.start"),data:Dl({hookInvocationId:Rt(),hookType:Rt(),input:gw()})}),RFn=wb.extend({type:Zr("hook.end"),data:Dl({hookInvocationId:Rt(),hookType:Rt(),output:gw(),success:Yo(),error:Dl({message:Rt(),stack:Rt().optional()}).optional()})}),YFn=wb.extend({type:Zr("system.message"),data:Dl({content:Rt(),role:_g(["system","developer"]),name:Rt().optional(),metadata:Dl({promptVersion:Rt().optional(),variables:S2(gw()).optional()}).optional()})}),D_t=tde("type",[sFn,oFn,iFn,cFn,dFn,uFn,bFn,GFn,pFn,hFn,AFn,ZFn,gFn,NFn,WFn,yFn,EFn,RFn,YFn]);var fO=CMt(D_t.parse,"session");var PVe=class{constructor(e,l,n,r=!1,I){this.session=e;this.logger=l;this.flushDebounceMs=n;this.shouldSaveSession=r;this.legacySourceFile=I;this.unsubscribe=this.session.onEvent(a=>{a.ephemeral||(this.unflushedEvents.push(a),this.isDirty=!0,!this.shouldSaveSession&&a.type==="user.message"&&(this.shouldSaveSession=!0),this.isDirty&&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;isDirty=!1;unflushedEvents=[];migratedLegacy=!1;unsubscribe;dispose(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.unsubscribe()}async flush(){if(!(!this.isDirty||!this.shouldSaveSession||this.unflushedEvents.length===0)){if(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),await fO.append(this.unflushedEvents,this.session.sessionId),this.logger.debug(`Flushed ${this.unflushedEvents.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 z_t(this.legacySourceFile)}catch(e){this.logger.error(`Failed to delete legacy session file ${this.legacySourceFile}: ${e}`)}this.migratedLegacy=!0}this.unflushedEvents=[],this.isDirty=!1}}},jVe=class extends zVe{sessionWriters={};copilotVersion;flushDebounceMs;constructor({logger:e,version:l,flushDebounceMs:n}){super({logger:e}),this.copilotVersion=l||"unknown",this.flushDebounceMs=n||100}async createSession(e){let l=e?.sessionId??Uu(),n=new Date,r=new of({sessionId:l,startTime:n,logger:this.logger});return this.sessionWriters[l]=new PVe(r,this.logger,this.flushDebounceMs),r.addEvent({type:"session.start",data:{sessionId:l,version:1,producer:"copilot-agent",copilotVersion:this.copilotVersion,startTime:n.toISOString(),selectedModel:e?.selectedModel}}),r}async getSession(e){let l,n;try{l=await this.loadSession(e)}catch{try{let r=await this.loadLegacySession(e);l=r.session,n=r.legacySourceFile}catch{return}}return this.sessionWriters[e]||(this.sessionWriters[e]=new PVe(l,this.logger,this.flushDebounceMs,!0,n)),l.addEvent({type:"session.resume",data:{resumeTime:new Date().toISOString(),eventCount:l.getEvents().length}}),l}async saveSession(e){await this.sessionWriters[e.sessionId]?.flush()}async loadSession(e){let l=await fO.load(e);if(l.length===0)throw new Error(`Session ${e} has no events`);if(l[0].type!=="session.start")throw new Error("First event must be a session.start event");return await of.fromEvents({events:l,logger:this.logger})}async loadLegacySession(e){let n=(await pue.directoryFiles()).filter(o=>{let d=o.match(/^session_(.+)_(\d+)\.json$/);return d&&d[1]===e});if(n.length===0)throw new Error(`Legacy session ${e} not found`);let r=n[0];n.length>1&&this.logger.info(`Multiple legacy sessions found for ${e}, using newest`);let I=await pue.load(r);if(!I)throw new Error(`Failed to load legacy session from ${r}`);let a=new Date(I.startTime),s=new of({sessionId:I.sessionId,startTime:a,logger:this.logger});return s.addEvent({type:"session.start",data:{sessionId:I.sessionId,version:1,producer:"copilot-agent",copilotVersion:this.copilotVersion,startTime:a.toISOString(),selectedModel:I.selectedModel}}),s.addEvent({type:"session.import_legacy",data:{legacySession:{sessionId:I.sessionId,startTime:a,chatMessages:I.chatMessages,timeline:I.timeline,selectedModel:I.selectedModel},importTime:new Date().toISOString(),sourceFile:r}}),this.logger.info(`Loaded legacy session ${e} from ${r}`),{session:s,legacySourceFile:pue.path(r.replace(/\.json$/,""))}}async listSessions(){let e=await fO.directoryFilesWithMetadata(),l=await pue.directoryFilesWithMetadata(),n=await Promise.all(e.map(async a=>({sessionId:a.file.replace(".jsonl",""),startTime:a.ctime,modifiedTime:a.mtime}))),r=(await Promise.all(l.map(async a=>{let s=a.file.match(/^session_(.+)_(\d+)\.json$/);return s?{sessionId:s[1],startTime:a.ctime,modifiedTime:a.mtime}:null}))).filter(a=>a!==null);this.logger.debug(`Found ${n.length} JSONL sessions and ${r.length} legacy sessions`);let I=new Map;for(let a of r)I.set(a.sessionId,a);for(let a of n)I.set(a.sessionId,a);return Array.from(I.values()).sort((a,s)=>s.modifiedTime.getTime()-a.modifiedTime.getTime())}async getLastSession(){let e=await this.listSessions();if(e.length===0)return;e.sort((n,r)=>r.modifiedTime.getTime()-n.modifiedTime.getTime());let l=e[0].sessionId;return await this.getSession(l)}async deleteSession(e){this.sessionWriters[e.sessionId]?.dispose(),delete this.sessionWriters[e.sessionId];let l=fO.path(e.sessionId);this.logger.info(`Deleting session file ${l}`),await z_t(l)}getSessionsDirectory(){return VFn(fO.home(),fO.directory())}setLogger(e){this.logger=e}};c();c();c();c();function xd(t){return t()}c();var hue;function QFn(t,e){return t.includes("\x1B[?")&&t.includes(e)}async function FFn(t){let e=process.stdin.isRaw;e||process.stdin.setRawMode(!0);try{return await t()}finally{e||process.stdin.setRawMode(!1)}}function P_t(t,e,l){return new Promise(n=>{let r="",I,a=()=>{I=void 0,process.stdin.removeListener("data",s),n(!1)},s=o=>{I!==void 0&&(r+=o.toString(),QFn(r,e)&&(process.stdin.removeListener("data",s),clearTimeout(I),I=void 0,n(!0)))};process.stdin.on("data",s),process.stdout.write("\x1B["+t),I=setTimeout(a,l)})}async function CFn(){return!(!(process.stdin.isTTY&&process.stdout.isTTY)||!await P_t("?u","u",200)||!await P_t("c","c",1e3))}async function K_t(){hue===void 0&&(hue=await FFn(CFn),hue===!0&&(vFn(),process.on("exit",j_t),process.on("SIGTERM",j_t)))}function vFn(){process.stdout.write("\x1B[>1u")}function j_t(){process.stdout.write("\x1B[<u"),hue=void 0}function KVe(){return hue===!0}c();c();c();c();function Zue(t,e=!1){let l=t.length,n=0,r="",I=0,a=16,s=0,o=0,d=0,u=0,b=0;function p(H,k){let S=0,U=0;for(;S<H||!k;){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<H&&(U=-1),U}function h(H){n=H,r="",I=0,a=16,b=0}function Z(){let H=n;if(t.charCodeAt(n)===48)n++;else for(n++;n<t.length&&O8(t.charCodeAt(n));)n++;if(n<t.length&&t.charCodeAt(n)===46)if(n++,n<t.length&&O8(t.charCodeAt(n)))for(n++;n<t.length&&O8(t.charCodeAt(n));)n++;else return b=3,t.substring(H,n);let k=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&&O8(t.charCodeAt(n))){for(n++;n<t.length&&O8(t.charCodeAt(n));)n++;k=n}else b=3;return t.substring(H,k)}function N(){let H="",k=n;for(;;){if(n>=l){H+=t.substring(k,n),b=2;break}let S=t.charCodeAt(n);if(S===34){H+=t.substring(k,n),n++;break}if(S===92){if(H+=t.substring(k,n),n++,n>=l){b=2;break}switch(t.charCodeAt(n++)){case 34:H+='"';break;case 92:H+="\\";break;case 47:H+="/";break;case 98:H+="\b";break;case 102:H+="\f";break;case 110:H+=`
|
|
1975
|
+
`),n={};for(let r of l){let I=r.split(/\s+/);if(I.length>=3){let a=I[0],s=I[1],o=I[2].replace(/[()]/g,"");n[a]||(n[a]={Name:a,FetchURL:"",PushURL:""}),o==="fetch"?n[a].FetchURL=s:o==="push"&&(n[a].PushURL=s)}}return Object.values(n)}async function s_t(t){try{let{stdout:e}=await iue("git",["status","--porcelain"],{cwd:t,encoding:"utf8",timeout:5e3,maxBuffer:1048576});return e.trim().length>0}catch{return!1}}async function o_t(t){try{let{stdout:e}=await iue("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:t,encoding:"utf8",timeout:5e3,maxBuffer:1048576}),l=e.trim();if(l==="HEAD"){let{stdout:n}=await iue("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}}c();var J_t=lt(L_t(),1);async function EQn(t={}){let e=await dAt();return bAt((0,J_t.default)({},e,t))}async function DVe(t={}){if(C_())throw new Error("Settings have already been initialized");return EQn(t)}c();c();c();import{promises as RQn}from"fs";import x_t from"path";var YQn=3*1024*1024;function S_t(t){let e=x_t.extname(t).toLowerCase();return[".png",".jpg",".jpeg",".gif",".webp"].includes(e)}function VQn(t){switch(x_t.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 wQn(t,e){e.debug(`Processing local image file: ${t}`);let l=await RQn.readFile(t),n=VQn(t);if(!n)throw new Error(`Unsupported image format: ${t}`);let r=new tse,I=await _ye(e,r,YQn,qae,n,l);if(!I)throw new Error(`Image too large or couldn't be processed: ${t}`);let a=I.toString("base64");return`data:${n};base64,${a}`}async function QQn(t,e){let l=Uu();try{let n=await aSe({command:"view",path:t,view_range:void 0},{properties:{command:"view",resolvedPathAgainstCwd:"false",options:"{}",inputs:"[]"},metrics:{responseTokenLimit:void 0,resultLength:0,resultForLlmLength:0},restrictedProperties:{}},e);return{id: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 B_t(t,e){let l=[],n=t.filter(I=>!S_t(I.path));if(n.length===0)return l;let r=[];for(let I of n)try{let a=await QQn(I.path,e);r.push(a)}catch{}if(r.length>0){let I=r.map(a=>({id:a.id,type:"function",function:{name:a.name,arguments:JSON.stringify(a.arguments)}}));l.push({role:"assistant",content:"I need to read the content of those paths to answer this request.",tool_calls:I}),l.push(...r.map(a=>({role:"tool",tool_call_id:a.id,content:a.result})))}return l}async function O_t(t,e){let l=t.filter(r=>S_t(r.path));return(await Promise.all(l.map(async r=>{try{return{type:"image_url",image_url:{url:await wQn(r.path,e)}}}catch(I){e.error(`Failed to process image ${r.path}: ${I instanceof Error?I.message:String(I)}`);return}}))).filter(r=>r!==void 0)}var of=class{sessionId;startTime;modifiedTime;events=[];_chatMessages=[];_selectedModel;logger;eventCallbacks=[];eventProcessingQueue=Promise.resolve();constructor({sessionId:e,startTime:l,modifiedTime:n,logger:r}={}){this.sessionId=e||Uu(),this.startTime=l||new Date,this.modifiedTime=n||this.startTime,this.logger=r||new Hc}get messageCount(){let e=this.events.find(n=>n.type==="session.import_legacy"),l=0;return e&&(l=(e.data.legacySession?.chatMessages||[]).filter(I=>I.role==="user"||I.role==="assistant").length),this.logger.debug(`Imported message count: ${l}`),this.events.filter(n=>n.type==="user.message"||n.type==="assistant.message").length+l}get summary(){let e=this.events.find(I=>I.type==="session.import_legacy"||I.type==="user.message"),l;if(e?.type==="session.import_legacy"){let I=e.data.legacySession.chatMessages.find(a=>a.role==="user");I?.content&&(typeof I.content=="string"?l=I.content:l=I.content.find(a=>a.type==="text")?.text)}else e?.type==="user.message"&&(l=e.data.content);if(!l)return;let n=l.lastIndexOf("<reminder>");n!==-1&&(l=l.substring(0,n).trim());let r=l.replace(/\s+/g," ").trim();return r.length>75&&(r=r.substring(0,55).trim()+"..."),r=r.split("").filter(I=>{let a=I.charCodeAt(0);return a>=32&&a!==127}).join(""),r}static async fromEvents({events:e,logger: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 this({sessionId:n.data.sessionId,startTime:new Date(n.data.startTime),logger:l||new Hc});r._selectedModel=n.data.selectedModel,r.events.push(n);for(let I=1;I<e.length;I++){let a=e[I];r.events.push(a),await r.processEventForState(a)}return r}addEvent(e){let l=e.id||Uu(),n=e.timestamp||new Date().toISOString(),r=e.parentId!==void 0?e.parentId:this.getLastEventId(),I={...e,id:l,timestamp:n,parentId:r};return this.events.push(I),this.enqueueEventProcessing(()=>this.processEventForState(I).catch(a=>{this.logger.error(`Error processing event ${I.type} (${I.id}): ${a instanceof Error?a.message:String(a)}`)})).catch(a=>{this.logger.error(`Error processing event queue ${a instanceof Error?a.message:String(a)}`)}),this.notifyEventCallbacks(I),I}getEvents(){return this.events}onEvent(e){return this.eventCallbacks.push(e),()=>{let l=this.eventCallbacks.indexOf(e);l>-1&&this.eventCallbacks.splice(l,1)}}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)}setSelectedModel(e){let l=this._selectedModel;this._selectedModel=e,this.addEvent({type:"session.model_change",data:{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 O_t(e.data.attachments,this.logger);l.push(...r);let I=await B_t(e.data.attachments,this.logger);n.push(...I)}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":{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":{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=FQn(this._chatMessages,this.logger);break;case"session.error":case"session.info":case"assistant.turn_start":case"assistant.turn_end":case"assistant.usage":case"tool.user_requested":case"tool.execution_start":case"tool.execution_partial_result":case"hook.start":case"hook.end":break;default:{let l=e;this.logger.error(`Unknown event type: ${l.type}`);break}}}notifyEventCallbacks(e){for(let l of this.eventCallbacks)try{l(e)}catch(n){this.logger.error(`Error in event callback: ${n instanceof Error?n.message:String(n)}`)}}};function FQn(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 d of o.tool_calls)n.has(d.id)||l.push(d.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 I="The execution of this tool, or a previous tool was interrupted.";e.info(`Completing ${l.length} orphaned tool calls.`);let a=l.map(s=>({role:"tool",tool_call_id:s,content:I}));return[...t,...a]}c();c();import{unlink as z_t}from"fs/promises";import{join as VFn}from"path";c();var zVe=class{sessions;logger;lastAccessedSessionId;constructor({logger:e}={}){this.sessions=new Map,this.logger=e||new Hc}async createSession(){let e=new of({logger:this.logger});return this.sessions.set(e.sessionId,e),this.lastAccessedSessionId=e.sessionId,e}async getSession(e){let l=this.sessions.get(e);return l&&(this.lastAccessedSessionId=e),l}async getLastSession(){if(this.lastAccessedSessionId){let n=this.sessions.get(this.lastAccessedSessionId);if(n)return n}let e=Array.from(this.sessions.values());if(e.length===0)return;e.sort((n,r)=>r.startTime.getTime()-n.startTime.getTime());let l=e[0];return this.lastAccessedSessionId=l.sessionId,l}async listSessions(){return Array.from(this.sessions.values()).map(e=>({sessionId:e.sessionId,startTime:e.startTime,modifiedTime:e.modifiedTime}))}async saveSession(e){}async deleteSession(e){this.sessions.delete(e.sessionId),this.lastAccessedSessionId===e.sessionId&&(this.lastAccessedSessionId=void 0)}};c();c();var CQn=Dl({type:Zr("copilot"),text:Rt(),isStreaming:Yo().optional()}),vQn=Dl({type:Zr("error"),text:Rt()}),fQn=Dl({type:Zr("info"),text:Rt()}),w0a=Dl({displayText:Rt(),fullPath:Rt(),type:_g(["file","directory","unresolved","image"]),startIndex:CG()}),HQn=Dl({type:Zr("user"),text:Rt()}),B8=Dl({command:Rt(),description:Rt(),timeout:CG().optional(),sessionId:Rt().optional(),async:Yo().optional()}),X8e=Dl({sessionId:Rt(),input:Rt(),delay:CG().optional()}),k8e=Dl({sessionId:Rt(),delay:CG()}),L8e=Dl({sessionId:Rt()}),T_t=fh([B8,X8e,k8e,L8e]),XQn=Dl({command:Zr("view"),path:Rt(),view_range:zYe([CG(),CG()]).optional()}),kQn=Dl({command:Zr("create"),path:Rt(),file_text:Rt()}),LQn=Dl({command:Zr("str_replace"),path:Rt(),new_str:Rt().optional(),old_str:Rt()}),JQn=Dl({command:Zr("insert"),path:Rt(),insert_line:CG(),new_str:Rt()}),J8e=tde("command",[XQn,kQn,LQn,JQn]),x8e=Dl({path:Rt(),view_range:zYe([CG(),CG()]).optional()}),S8e=Dl({path:Rt(),file_text:Rt()}),B8e=Dl({path:Rt(),old_str:Rt(),new_str:Rt().optional()}),U_t=fh([T_t,J8e,gw()]),xQn=Dl({type:Zr("tool_call_requested"),callId:Rt(),name:Rt(),toolTitle:Rt().optional(),intentionSummary:Rt().nullable(),arguments:U_t,partialOutput:Rt().optional(),isHidden:Yo().optional(),isAlwaysExpanded:Yo().optional(),showNoContent:Yo().optional()}),SQn=Dl({type:Zr("tool_call_completed"),callId:Rt(),name:Rt(),toolTitle:Rt().optional(),intentionSummary:Rt().nullable(),result:fh([Dl({type:Zr("success"),log:Rt(),markdown:Yo().optional()}),Dl({type:Zr("failure"),log:Rt(),markdown:Yo().optional()}),Dl({type:Zr("rejected"),markdown:Yo().optional()}),Dl({type:Zr("denied"),log:Rt(),markdown:Yo().optional()})]),arguments:U_t,isHidden:Yo().optional(),isAlwaysExpanded:Yo().optional(),showNoContent:Yo().optional()}),BQn=fh([CQn,vQn,fQn,HQn,xQn,SQn]),M_t=BQn.and(Dl({id:Rt(),timestamp:lde.date()}));function __t(t,e){switch(t.type){case"copilot":return e.onCopilot(t);case"error":return e.onError(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:{let l=t;throw new Error(`Unexpected message type: ${JSON.stringify(t)}`)}}}var vO=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 Gue=Dl({type:Zr("text"),text:Rt()}),OQn=Dl({type:Zr("refusal"),refusal:Rt()}),TQn=Dl({type:Zr("image_url"),image_url:Dl({url:Rt(),detail:_g(["auto","low","high"]).optional()})}),UQn=Dl({type:Zr("input_audio"),input_audio:Dl({data:Rt(),format:Zr("wav").or(Zr("mp3"))})}),MQn=Dl({type:Zr("file"),file:Dl({file_date:Rt().optional(),file_id:Rt().optional(),filename:Rt().optional()})}),_Qn=fh([Gue,TQn,UQn,MQn]),DQn=Dl({name:Rt(),arguments:Rt()}),zQn=Dl({name:Rt(),input:Rt()}),PQn=Dl({id:Rt(),type:Zr("function"),function:DQn}),jQn=Dl({id:Rt(),type:Zr("custom"),custom:zQn}),KQn=fh([PQn,jQn]),qQn=Dl({name:Rt(),arguments:Rt()}),$Qn=Dl({id:Rt()}),eFn=Dl({content:fh([Rt(),Jd(Gue)]),role:Zr("developer"),name:Rt().optional()}),tFn=Dl({content:fh([Rt(),Jd(Gue)]),role:Zr("system"),name:Rt().optional()}),lFn=Dl({content:fh([Rt(),Jd(_Qn)]),role:Zr("user"),name:Rt().optional()}),nFn=Dl({content:fh([Rt(),Jd(fh([Gue,OQn]))]).nullable().optional(),role:Zr("assistant"),name:Rt().optional(),refusal:Rt().nullable().optional(),audio:$Qn.nullable().optional(),function_call:qQn.nullable().optional(),tool_calls:Jd(KQn).optional()}),rFn=Dl({content:fh([Rt(),Jd(Gue)]),role:Zr("tool"),tool_call_id:Rt()}),IFn=Dl({content:Rt().nullable(),role:Zr("function"),name:Rt()}),aFn=fh([eFn,tFn,lFn,nFn,rFn,IFn]),O8e=Dl({sessionId:Rt(),startTime:lde.date(),chatMessages:Jd(aFn),timeline:Jd(M_t),selectedModel:_g(YO).optional()}),pue=QVe(O8e.parse,"history-session");c();c();var wb=Dl({id:Rt().uuid(),timestamp:Rt().datetime(),parentId:Rt().uuid().nullable(),ephemeral:Yo().optional()}),sFn=wb.extend({type:Zr("session.start"),data:Dl({sessionId:Rt(),version:CG(),producer:Rt(),copilotVersion:Rt(),startTime:Rt().datetime(),selectedModel:Rt().optional()})}),oFn=wb.extend({type:Zr("session.resume"),data:Dl({resumeTime:Rt().datetime(),eventCount:CG()})}),iFn=wb.extend({type:Zr("session.error"),data:Dl({errorType:Rt(),message:Rt(),stack:Rt().optional()})}),cFn=wb.extend({type:Zr("session.info"),data:Dl({infoType:Rt(),message:Rt()})}),dFn=wb.extend({type:Zr("session.model_change"),data:Dl({previousModel:Rt().optional(),newModel:Rt()})}),uFn=wb.extend({type:Zr("session.import_legacy"),data:Dl({legacySession:O8e,importTime:Rt().datetime(),sourceFile:Rt()})}),mFn=Dl({type:_g(["file","directory"]),path:Rt(),displayName:Rt()}),bFn=wb.extend({type:Zr("user.message"),data:Dl({content:Rt(),attachments:Jd(mFn).optional()})}),GFn=wb.extend({type:Zr("assistant.turn_start"),data:Dl({turnId:Rt()})}),pFn=wb.extend({type:Zr("assistant.message"),data:Dl({messageId:Rt(),content:Rt(),toolRequests:Jd(Dl({toolCallId:Rt(),name:Rt(),arguments:gw()})).optional()})}),hFn=wb.extend({type:Zr("assistant.turn_end"),data:Dl({turnId:Rt()})}),AFn=wb.extend({type:Zr("assistant.usage"),ephemeral:Zr(!0),data:Dl({model:Rt().optional(),tokensUsed:CG().optional(),cost:CG().optional(),duration:CG().optional(),initiator:Rt().optional()})}),ZFn=wb.extend({type:Zr("abort"),data:Dl({reason:Rt()})}),gFn=wb.extend({type:Zr("tool.user_requested"),data:Dl({toolCallId:Rt(),toolName:Rt(),arguments:gw()})}),NFn=wb.extend({type:Zr("tool.execution_start"),data:Dl({toolCallId:Rt(),toolName:Rt(),arguments:gw()})}),WFn=wb.extend({type:Zr("tool.execution_partial_result"),ephemeral:Zr(!0),data:Dl({toolCallId:Rt(),partialOutput:Rt()})}),yFn=wb.extend({type:Zr("tool.execution_complete"),data:Dl({toolCallId:Rt(),success:Yo(),isUserRequested:Yo().optional(),result:Dl({content:Rt()}).optional(),error:Dl({message:Rt(),code:Rt().optional()}).optional()})}),EFn=wb.extend({type:Zr("hook.start"),data:Dl({hookInvocationId:Rt(),hookType:Rt(),input:gw()})}),RFn=wb.extend({type:Zr("hook.end"),data:Dl({hookInvocationId:Rt(),hookType:Rt(),output:gw(),success:Yo(),error:Dl({message:Rt(),stack:Rt().optional()}).optional()})}),YFn=wb.extend({type:Zr("system.message"),data:Dl({content:Rt(),role:_g(["system","developer"]),name:Rt().optional(),metadata:Dl({promptVersion:Rt().optional(),variables:S2(gw()).optional()}).optional()})}),D_t=tde("type",[sFn,oFn,iFn,cFn,dFn,uFn,bFn,GFn,pFn,hFn,AFn,ZFn,gFn,NFn,WFn,yFn,EFn,RFn,YFn]);var fO=CMt(D_t.parse,"session");var PVe=class{constructor(e,l,n,r=!1,I){this.session=e;this.logger=l;this.flushDebounceMs=n;this.shouldSaveSession=r;this.legacySourceFile=I;this.unsubscribe=this.session.onEvent(a=>{a.ephemeral||(this.unflushedEvents.push(a),!this.shouldSaveSession&&a.type==="user.message"&&(this.shouldSaveSession=!0),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 fO.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 z_t(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())}}},jVe=class extends zVe{sessionWriters={};copilotVersion;flushDebounceMs;constructor({logger:e,version:l,flushDebounceMs:n}){super({logger:e}),this.copilotVersion=l||"unknown",this.flushDebounceMs=n||100}async createSession(e){let l=e?.sessionId??Uu(),n=new Date,r=new of({sessionId:l,startTime:n,logger:this.logger});return this.sessionWriters[l]=new PVe(r,this.logger,this.flushDebounceMs),r.addEvent({type:"session.start",data:{sessionId:l,version:1,producer:"copilot-agent",copilotVersion:this.copilotVersion,startTime:n.toISOString(),selectedModel:e?.selectedModel}}),r}async getSession(e){let l,n;try{l=await this.loadSession(e)}catch{try{let r=await this.loadLegacySession(e);l=r.session,n=r.legacySourceFile}catch{return}}return this.sessionWriters[e]||(this.sessionWriters[e]=new PVe(l,this.logger,this.flushDebounceMs,!0,n)),l.addEvent({type:"session.resume",data:{resumeTime:new Date().toISOString(),eventCount:l.getEvents().length}}),l}async saveSession(e){await this.sessionWriters[e.sessionId]?.flush()}async loadSession(e){let l=await fO.load(e);if(l.length===0)throw new Error(`Session ${e} has no events`);if(l[0].type!=="session.start")throw new Error("First event must be a session.start event");return await of.fromEvents({events:l,logger:this.logger})}async loadLegacySession(e){let n=(await pue.directoryFiles()).filter(o=>{let d=o.match(/^session_(.+)_(\d+)\.json$/);return d&&d[1]===e});if(n.length===0)throw new Error(`Legacy session ${e} not found`);let r=n[0];n.length>1&&this.logger.info(`Multiple legacy sessions found for ${e}, using newest`);let I=await pue.load(r);if(!I)throw new Error(`Failed to load legacy session from ${r}`);let a=new Date(I.startTime),s=new of({sessionId:I.sessionId,startTime:a,logger:this.logger});return s.addEvent({type:"session.start",data:{sessionId:I.sessionId,version:1,producer:"copilot-agent",copilotVersion:this.copilotVersion,startTime:a.toISOString(),selectedModel:I.selectedModel}}),s.addEvent({type:"session.import_legacy",data:{legacySession:{sessionId:I.sessionId,startTime:a,chatMessages:I.chatMessages,timeline:I.timeline,selectedModel:I.selectedModel},importTime:new Date().toISOString(),sourceFile:r}}),this.logger.info(`Loaded legacy session ${e} from ${r}`),{session:s,legacySourceFile:pue.path(r.replace(/\.json$/,""))}}async listSessions(){let e=await fO.directoryFilesWithMetadata(),l=await pue.directoryFilesWithMetadata(),n=await Promise.all(e.map(async a=>({sessionId:a.file.replace(".jsonl",""),startTime:a.ctime,modifiedTime:a.mtime}))),r=(await Promise.all(l.map(async a=>{let s=a.file.match(/^session_(.+)_(\d+)\.json$/);return s?{sessionId:s[1],startTime:a.ctime,modifiedTime:a.mtime}:null}))).filter(a=>a!==null);this.logger.debug(`Found ${n.length} JSONL sessions and ${r.length} legacy sessions`);let I=new Map;for(let a of r)I.set(a.sessionId,a);for(let a of n)I.set(a.sessionId,a);return Array.from(I.values()).sort((a,s)=>s.modifiedTime.getTime()-a.modifiedTime.getTime())}async getLastSession(){let e=await this.listSessions();if(e.length===0)return;e.sort((n,r)=>r.modifiedTime.getTime()-n.modifiedTime.getTime());let l=e[0].sessionId;return await this.getSession(l)}async deleteSession(e){this.sessionWriters[e.sessionId]?.dispose(),delete this.sessionWriters[e.sessionId];let l=fO.path(e.sessionId);this.logger.info(`Deleting session file ${l}`),await z_t(l)}getSessionsDirectory(){return VFn(fO.home(),fO.directory())}setLogger(e){this.logger=e}};c();c();c();c();function xd(t){return t()}c();var hue;function QFn(t,e){return t.includes("\x1B[?")&&t.includes(e)}async function FFn(t){let e=process.stdin.isRaw;e||process.stdin.setRawMode(!0);try{return await t()}finally{e||process.stdin.setRawMode(!1)}}function P_t(t,e,l){return new Promise(n=>{let r="",I,a=()=>{I=void 0,process.stdin.removeListener("data",s),n(!1)},s=o=>{I!==void 0&&(r+=o.toString(),QFn(r,e)&&(process.stdin.removeListener("data",s),clearTimeout(I),I=void 0,n(!0)))};process.stdin.on("data",s),process.stdout.write("\x1B["+t),I=setTimeout(a,l)})}async function CFn(){return!(!(process.stdin.isTTY&&process.stdout.isTTY)||!await P_t("?u","u",200)||!await P_t("c","c",1e3))}async function K_t(){hue===void 0&&(hue=await FFn(CFn),hue===!0&&(vFn(),process.on("exit",j_t),process.on("SIGTERM",j_t)))}function vFn(){process.stdout.write("\x1B[>1u")}function j_t(){process.stdout.write("\x1B[<u"),hue=void 0}function KVe(){return hue===!0}c();c();c();c();function Zue(t,e=!1){let l=t.length,n=0,r="",I=0,a=16,s=0,o=0,d=0,u=0,b=0;function p(H,k){let S=0,U=0;for(;S<H||!k;){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<H&&(U=-1),U}function h(H){n=H,r="",I=0,a=16,b=0}function Z(){let H=n;if(t.charCodeAt(n)===48)n++;else for(n++;n<t.length&&O8(t.charCodeAt(n));)n++;if(n<t.length&&t.charCodeAt(n)===46)if(n++,n<t.length&&O8(t.charCodeAt(n)))for(n++;n<t.length&&O8(t.charCodeAt(n));)n++;else return b=3,t.substring(H,n);let k=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&&O8(t.charCodeAt(n))){for(n++;n<t.length&&O8(t.charCodeAt(n));)n++;k=n}else b=3;return t.substring(H,k)}function N(){let H="",k=n;for(;;){if(n>=l){H+=t.substring(k,n),b=2;break}let S=t.charCodeAt(n);if(S===34){H+=t.substring(k,n),n++;break}if(S===92){if(H+=t.substring(k,n),n++,n>=l){b=2;break}switch(t.charCodeAt(n++)){case 34:H+='"';break;case 92:H+="\\";break;case 47:H+="/";break;case 98:H+="\b";break;case 102:H+="\f";break;case 110:H+=`
|
|
1976
1976
|
`;break;case 114:H+="\r";break;case 116:H+=" ";break;case 117:let T=p(4,!0);T>=0?H+=String.fromCharCode(T):b=4;break;default:b=5}k=n;continue}if(S>=0&&S<=31)if(Aue(S)){H+=t.substring(k,n),b=2;break}else b=6;n++}return H}function y(){if(r="",b=0,I=n,o=s,u=d,n>=l)return I=l,a=17;let H=t.charCodeAt(n);if(T8e(H)){do n++,r+=String.fromCharCode(H),H=t.charCodeAt(n);while(T8e(H));return a=15}if(Aue(H))return n++,r+=String.fromCharCode(H),H===13&&t.charCodeAt(n)===10&&(n++,r+=`
|
|
1977
1977
|
`),s++,d=n,a=14;switch(H){case 123:return n++,a=1;case 125:return n++,a=2;case 91:return n++,a=3;case 93:return n++,a=4;case 58:return n++,a=6;case 44:return n++,a=5;case 34:return n++,r=N(),a=10;case 47:let k=n-1;if(t.charCodeAt(n+1)===47){for(n+=2;n<l&&!Aue(t.charCodeAt(n));)n++;return r=t.substring(k,n),a=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++,Aue(T)&&(T===13&&t.charCodeAt(n)===10&&n++,s++,d=n)}return U||(n++,b=1),r=t.substring(k,n),a=13}return r+=String.fromCharCode(H),n++,a=16;case 45:if(r+=String.fromCharCode(H),n++,n===l||!O8(t.charCodeAt(n)))return a=16;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return r+=Z(),a=11;default:for(;n<l&&Y(H);)n++,H=t.charCodeAt(n);if(I!==n){switch(r=t.substring(I,n),r){case"true":return a=8;case"false":return a=9;case"null":return a=7}return a=16}return r+=String.fromCharCode(H),n++,a=16}}function Y(H){if(T8e(H)||Aue(H))return!1;switch(H){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}function w(){let H;do H=y();while(H>=12&&H<=15);return H}return{setPosition:h,getPosition:()=>n,scan:e?w:y,getToken:()=>a,getTokenValue:()=>r,getTokenOffset:()=>I,getTokenLength:()=>n-I,getTokenStartLine:()=>o,getTokenStartCharacter:()=>I-u,getTokenError:()=>b}}function T8e(t){return t===32||t===9}function Aue(t){return t===10||t===13}function O8(t){return t>=48&&t<=57}var q_t;(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"})(q_t||(q_t={}));c();var PW=new Array(20).fill(0).map((t,e)=>" ".repeat(e)),T8=200,U8e={" ":{"\n":new Array(T8).fill(0).map((t,e)=>`
|
|
1978
1978
|
`+" ".repeat(e)),"\r":new Array(T8).fill(0).map((t,e)=>"\r"+" ".repeat(e)),"\r\n":new Array(T8).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.348-
|
|
4
|
+
"version": "0.0.348-13",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"repository": {
|
|
7
7
|
"type": "git",
|
|
@@ -35,7 +35,7 @@
|
|
|
35
35
|
"worker/**/*"
|
|
36
36
|
],
|
|
37
37
|
"buildMetadata": {
|
|
38
|
-
"gitCommit": "
|
|
38
|
+
"gitCommit": "73cec3c"
|
|
39
39
|
},
|
|
40
40
|
"dependencies": {
|
|
41
41
|
"sharp": "^0.34.3"
|
package/sdk/index.js
CHANGED
|
@@ -1407,7 +1407,7 @@ ${c}`;await n.logMCPSetup(e,s),this.logger.log(`Updated session log for ${e} wit
|
|
|
1407
1407
|
`).forEach(n=>{let[c,r]=n.split("=").map(s=>s.trim());c&&r&&(I[c]=r)}),e(I)}catch(I){throw new Error(`Failed to read configuration from ${t}: ${I}`)}}async function Ict(t,e){try{await a$e(t);let I=JSON.stringify(e,null,2);await $7.runExclusive(t,()=>_nt(t,I,{mode:384}))}catch(I){throw new Error(`Failed to write configuration to ${t}: ${I}`)}}var o$e=(t,e,{shouldCache:I})=>{let l=new Map,n=()=>{let b=c$e(e)?process.env.XDG_CONFIG_HOME:process.env.XDG_STATE_HOME;return b?uG(b,_7):uG(s$e(),_7)},c=()=>{let b=c$e(e)?"-config":"-state";return`${e}${e=="config"?"":b}`},r=b=>{let m=".json",h=c()+(b?"":m),p=uG(n(),h,b?`${b}${m}`:"");return!K7(p)&&K7(p.replace(/\.json$/,""))&&(p=p.replace(/\.json$/,"")),p},s=async()=>{let b=uG(n(),c());try{let h=(await P7(b,{withFileTypes:!0})).filter(Z=>Z.isFile()&&Z.name.endsWith(".json")).map(Z=>Z.name),p=await Promise.all(h.map(async Z=>{let W=uG(b,Z);try{let Y=await q7(W);return{file:Z,mtime:Y.mtime}}catch{return{file:Z,mtime:new Date}}}));return p.sort((Z,W)=>W.mtime.getTime()-Z.mtime.getTime()),p.map(Z=>Z.file)}catch{}return[]},a=async()=>{let b=uG(n(),c());try{let h=(await P7(b,{withFileTypes:!0})).filter(Z=>Z.isFile()&&Z.name.endsWith(".json")).map(Z=>Z.name),p=await Promise.all(h.map(async Z=>{let W=uG(b,Z);try{let Y=await q7(W);return{file:Z,mtime:Y.mtime,ctime:Y.ctime}}catch{return{file:Z,mtime:new Date,ctime:new Date}}}));return p.sort((Z,W)=>W.mtime.getTime()-Z.mtime.getTime()),p}catch{}return[]},G=async(b="")=>{if(I&&l.has(b))return l.get(b);let m=await ect(r(b),t);return I&&m&&l.set(b,m),m},d=async(b,m="")=>{I&&l.set(m,b),await Ict(r(m),b)};return{load:G,write:d,writeKey:async(b,m,h)=>{let p=await G(h);if(m===void 0){p&&(delete p[b],await d(p,h));return}let Z={[b]:m},W;p?W={...p,...Z}:W=Z,await d(W,h)},path:r,directoryFiles:s,directoryFilesWithMetadata:a}},G$e=(t,e)=>o$e(t,e,{shouldCache:!0}),d$e=(t,e)=>o$e(t,e,{shouldCache:!1}),i$e=(t,e)=>{let I=()=>{let G=process.env.XDG_STATE_HOME;return G?uG(G,_7):uG(s$e(),_7)},l=()=>`${e}-state`,n=G=>{let d=".jsonl",i=l()+(G?"":d);return uG(I(),i,G?`${G}${d}`:"")};return{load:async G=>{let d=n(G);if(!K7(d))return[];try{let b=(await $7.runExclusive(d,()=>r$e(d,"utf8"))).trim().split(`
|
|
1408
1408
|
`).filter(h=>h.trim()),m=[];for(let h=0;h<b.length;h++)try{let p=JSON.parse(b[h]),Z=t(p);m.push(Z)}catch(p){throw new Error(`Invalid event at line ${h+1} in ${d}: ${p}`)}return m}catch(i){throw new Error(`Failed to read JSONL from ${d}: ${i}`)}},append:async(G,d)=>{let i=n(d),b=Array.isArray(G)?G:[G];try{await a$e(i);let m=b.map(h=>JSON.stringify(h)).join(`
|
|
1409
1409
|
`)+`
|
|
1410
|
-
`;await $7.runExclusive(i,()=>Pnt(i,m,{mode:384}))}catch(m){throw new Error(`Failed to append to JSONL file ${i}: ${m}`)}},path:n,directoryFiles:async()=>{let G=uG(I(),l());try{let i=(await P7(G,{withFileTypes:!0})).filter(m=>m.isFile()&&m.name.endsWith(".jsonl")).map(m=>m.name),b=await Promise.all(i.map(async m=>{let h=uG(G,m);try{let p=await q7(h);return{file:m,mtime:p.mtime}}catch{return{file:m,mtime:new Date}}}));return b.sort((m,h)=>h.mtime.getTime()-m.mtime.getTime()),b.map(m=>m.file)}catch{return[]}},directoryFilesWithMetadata:async()=>{let G=uG(I(),l());try{let i=(await P7(G,{withFileTypes:!0})).filter(m=>m.isFile()&&m.name.endsWith(".jsonl")).map(m=>m.name),b=await Promise.all(i.map(async m=>{let h=uG(G,m);try{let p=await q7(h);return{file:m,mtime:p.mtime,ctime:p.ctime}}catch{return{file:m,mtime:new Date,ctime:new Date}}}));return b.sort((m,h)=>h.mtime.getTime()-m.mtime.getTime()),b}catch{return[]}},home:I,directory:l}};var b$e=xe({host:ne(),login:ne()}),tct=xe({banner:Ai(["always","once","never"]).optional(),beep:en().optional(),last_logged_in_user:b$e.optional(),logged_in_users:Pr(b$e).optional(),model:ne().optional(),render_markdown:en().optional(),screen_reader:en().optional(),theme:ne().optional(),trusted_folders:Pr(ne()).optional(),store_token_plaintext:en().optional(),stream:en().optional(),feature_flags:xe({enabled:Pr(ne()).optional()}).optional(),asked_setup_terminals:Pr(ne()).optional(),capi_hmac_key:ne().optional(),copilot_hmac_key:ne().optional(),copilot_integration_id:ne().optional(),copilot_tokens:C1(ne(),ne()).optional(),copilot_url:ne().optional(),staff:en().optional(),log_level:Ai(["none","error","warning","info","debug","all","default"]).optional()}),lct=C1(ne(),Iue()),nct=lct.transform(t=>(0,m$e.default)(t,(e,I)=>{let l=I.toLowerCase();return l==="github_copilot_integration_id"?"copilot_integration_id":l})),cct=nct.pipe(tct),rct=G$e(cct.parse,"config");var h$e=["claude-sonnet-4.5","claude-sonnet-4","claude-haiku-4.5","gpt-5"];o();var sct=xe({type:ZI("copilot"),text:ne(),isStreaming:en().optional()}),act=xe({type:ZI("error"),text:ne()}),oct=xe({type:ZI("info"),text:ne()}),Lmn=xe({displayText:ne(),fullPath:ne(),type:Ai(["file","directory","unresolved","image"]),startIndex:Kr()}),Gct=xe({type:ZI("user"),text:ne()}),dct=xe({command:ne(),description:ne(),timeout:Kr().optional(),sessionId:ne().optional(),async:en().optional()}),ict=xe({sessionId:ne(),input:ne(),delay:Kr().optional()}),bct=xe({sessionId:ne(),delay:Kr()}),mct=xe({sessionId:ne()}),hct=sa([dct,ict,bct,mct]),pct=xe({command:ZI("view"),path:ne(),view_range:s8([Kr(),Kr()]).optional()}),uct=xe({command:ZI("create"),path:ne(),file_text:ne()}),Zct=xe({command:ZI("str_replace"),path:ne(),new_str:ne().optional(),old_str:ne()}),Wct=xe({command:ZI("insert"),path:ne(),insert_line:Kr(),new_str:ne()}),Nct=IB("command",[pct,uct,Zct,Wct]),kmn=xe({path:ne(),view_range:s8([Kr(),Kr()]).optional()}),fmn=xe({path:ne(),file_text:ne()}),xmn=xe({path:ne(),old_str:ne(),new_str:ne().optional()}),p$e=sa([hct,Nct,Wp()]),Yct=xe({type:ZI("tool_call_requested"),callId:ne(),name:ne(),toolTitle:ne().optional(),intentionSummary:ne().nullable(),arguments:p$e,partialOutput:ne().optional(),isHidden:en().optional(),isAlwaysExpanded:en().optional(),showNoContent:en().optional()}),Vct=xe({type:ZI("tool_call_completed"),callId:ne(),name:ne(),toolTitle:ne().optional(),intentionSummary:ne().nullable(),result:sa([xe({type:ZI("success"),log:ne(),markdown:en().optional()}),xe({type:ZI("failure"),log:ne(),markdown:en().optional()}),xe({type:ZI("rejected"),markdown:en().optional()}),xe({type:ZI("denied"),log:ne(),markdown:en().optional()})]),arguments:p$e,isHidden:en().optional(),isAlwaysExpanded:en().optional(),showNoContent:en().optional()}),Rct=sa([sct,act,oct,Gct,Yct,Vct]),u$e=Rct.and(xe({id:ne(),timestamp:tB.date()}));var sz=xe({type:ZI("text"),text:ne()}),gct=xe({type:ZI("refusal"),refusal:ne()}),Fct=xe({type:ZI("image_url"),image_url:xe({url:ne(),detail:Ai(["auto","low","high"]).optional()})}),Act=xe({type:ZI("input_audio"),input_audio:xe({data:ne(),format:ZI("wav").or(ZI("mp3"))})}),Qct=xe({type:ZI("file"),file:xe({file_date:ne().optional(),file_id:ne().optional(),filename:ne().optional()})}),wct=sa([sz,Fct,Act,Qct]),Xct=xe({name:ne(),arguments:ne()}),Ect=xe({name:ne(),input:ne()}),Hct=xe({id:ne(),type:ZI("function"),function:Xct}),vct=xe({id:ne(),type:ZI("custom"),custom:Ect}),Cct=sa([Hct,vct]),Jct=xe({name:ne(),arguments:ne()}),Lct=xe({id:ne()}),kct=xe({content:sa([ne(),Pr(sz)]),role:ZI("developer"),name:ne().optional()}),fct=xe({content:sa([ne(),Pr(sz)]),role:ZI("system"),name:ne().optional()}),xct=xe({content:sa([ne(),Pr(wct)]),role:ZI("user"),name:ne().optional()}),Bct=xe({content:sa([ne(),Pr(sa([sz,gct]))]).nullable().optional(),role:ZI("assistant"),name:ne().optional(),refusal:ne().nullable().optional(),audio:Lct.nullable().optional(),function_call:Jct.nullable().optional(),tool_calls:Pr(Cct).optional()}),zct=xe({content:sa([ne(),Pr(sz)]),role:ZI("tool"),tool_call_id:ne()}),Uct=xe({content:ne().nullable(),role:ZI("function"),name:ne()}),Sct=sa([kct,fct,xct,Bct,zct,Uct]),eNe=xe({sessionId:ne(),startTime:tB.date(),chatMessages:Pr(Sct),timeline:Pr(u$e),selectedModel:Ai(h$e).optional()}),az=d$e(eNe.parse,"history-session");o();o();var ur=xe({id:ne().uuid(),timestamp:ne().datetime(),parentId:ne().uuid().nullable(),ephemeral:en().optional()}),Oct=ur.extend({type:ZI("session.start"),data:xe({sessionId:ne(),version:Kr(),producer:ne(),copilotVersion:ne(),startTime:ne().datetime(),selectedModel:ne().optional()})}),Mct=ur.extend({type:ZI("session.resume"),data:xe({resumeTime:ne().datetime(),eventCount:Kr()})}),Tct=ur.extend({type:ZI("session.error"),data:xe({errorType:ne(),message:ne(),stack:ne().optional()})}),jct=ur.extend({type:ZI("session.info"),data:xe({infoType:ne(),message:ne()})}),Dct=ur.extend({type:ZI("session.model_change"),data:xe({previousModel:ne().optional(),newModel:ne()})}),Kct=ur.extend({type:ZI("session.import_legacy"),data:xe({legacySession:eNe,importTime:ne().datetime(),sourceFile:ne()})}),Pct=xe({type:Ai(["file","directory"]),path:ne(),displayName:ne()}),qct=ur.extend({type:ZI("user.message"),data:xe({content:ne(),attachments:Pr(Pct).optional()})}),_ct=ur.extend({type:ZI("assistant.turn_start"),data:xe({turnId:ne()})}),$ct=ur.extend({type:ZI("assistant.message"),data:xe({messageId:ne(),content:ne(),toolRequests:Pr(xe({toolCallId:ne(),name:ne(),arguments:Wp()})).optional()})}),ert=ur.extend({type:ZI("assistant.turn_end"),data:xe({turnId:ne()})}),Irt=ur.extend({type:ZI("assistant.usage"),ephemeral:ZI(!0),data:xe({model:ne().optional(),tokensUsed:Kr().optional(),cost:Kr().optional(),duration:Kr().optional(),initiator:ne().optional()})}),trt=ur.extend({type:ZI("abort"),data:xe({reason:ne()})}),lrt=ur.extend({type:ZI("tool.user_requested"),data:xe({toolCallId:ne(),toolName:ne(),arguments:Wp()})}),nrt=ur.extend({type:ZI("tool.execution_start"),data:xe({toolCallId:ne(),toolName:ne(),arguments:Wp()})}),crt=ur.extend({type:ZI("tool.execution_partial_result"),ephemeral:ZI(!0),data:xe({toolCallId:ne(),partialOutput:ne()})}),rrt=ur.extend({type:ZI("tool.execution_complete"),data:xe({toolCallId:ne(),success:en(),isUserRequested:en().optional(),result:xe({content:ne()}).optional(),error:xe({message:ne(),code:ne().optional()}).optional()})}),srt=ur.extend({type:ZI("hook.start"),data:xe({hookInvocationId:ne(),hookType:ne(),input:Wp()})}),art=ur.extend({type:ZI("hook.end"),data:xe({hookInvocationId:ne(),hookType:ne(),output:Wp(),success:en(),error:xe({message:ne(),stack:ne().optional()}).optional()})}),ort=ur.extend({type:ZI("system.message"),data:xe({content:ne(),role:Ai(["system","developer"]),name:ne().optional(),metadata:xe({promptVersion:ne().optional(),variables:C1(Wp()).optional()}).optional()})}),Z$e=IB("type",[Oct,Mct,Tct,jct,Dct,Kct,qct,_ct,$ct,ert,Irt,trt,lrt,nrt,crt,rrt,srt,art,ort]);var cF=i$e(Z$e.parse,"session");var e_=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.onEvent(r=>{r.ephemeral||(this.unflushedEvents.push(r),this.isDirty=!0,!this.shouldSaveSession&&r.type==="user.message"&&(this.shouldSaveSession=!0),this.isDirty&&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;isDirty=!1;unflushedEvents=[];migratedLegacy=!1;unsubscribe;dispose(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.unsubscribe()}async flush(){if(!(!this.isDirty||!this.shouldSaveSession||this.unflushedEvents.length===0)){if(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),await cF.append(this.unflushedEvents,this.session.sessionId),this.logger.debug(`Flushed ${this.unflushedEvents.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 W$e(this.legacySourceFile)}catch(e){this.logger.error(`Failed to delete legacy session file ${this.legacySourceFile}: ${e}`)}this.migratedLegacy=!0}this.unflushedEvents=[],this.isDirty=!1}}},INe=class extends X7{sessionWriters={};copilotVersion;flushDebounceMs;constructor({logger:e,version:I,flushDebounceMs:l}){super({logger:e}),this.copilotVersion=I||"unknown",this.flushDebounceMs=l||100}async createSession(e){let I=e?.sessionId??es(),l=new Date,n=new gp({sessionId:I,startTime:l,logger:this.logger});return this.sessionWriters[I]=new e_(n,this.logger,this.flushDebounceMs),n.addEvent({type:"session.start",data:{sessionId:I,version:1,producer:"copilot-agent",copilotVersion:this.copilotVersion,startTime:l.toISOString(),selectedModel:e?.selectedModel}}),n}async getSession(e){let I,l;try{I=await this.loadSession(e)}catch{try{let n=await this.loadLegacySession(e);I=n.session,l=n.legacySourceFile}catch{return}}return this.sessionWriters[e]||(this.sessionWriters[e]=new e_(I,this.logger,this.flushDebounceMs,!0,l)),I.addEvent({type:"session.resume",data:{resumeTime:new Date().toISOString(),eventCount:I.getEvents().length}}),I}async saveSession(e){await this.sessionWriters[e.sessionId]?.flush()}async loadSession(e){let I=await cF.load(e);if(I.length===0)throw new Error(`Session ${e} has no events`);if(I[0].type!=="session.start")throw new Error("First event must be a session.start event");return await gp.fromEvents({events:I,logger:this.logger})}async loadLegacySession(e){let l=(await az.directoryFiles()).filter(a=>{let G=a.match(/^session_(.+)_(\d+)\.json$/);return G&&G[1]===e});if(l.length===0)throw new Error(`Legacy session ${e} not found`);let n=l[0];l.length>1&&this.logger.info(`Multiple legacy sessions found for ${e}, using newest`);let c=await az.load(n);if(!c)throw new Error(`Failed to load legacy session from ${n}`);let r=new Date(c.startTime),s=new gp({sessionId:c.sessionId,startTime:r,logger:this.logger});return s.addEvent({type:"session.start",data:{sessionId:c.sessionId,version:1,producer:"copilot-agent",copilotVersion:this.copilotVersion,startTime:r.toISOString(),selectedModel:c.selectedModel}}),s.addEvent({type:"session.import_legacy",data:{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} from ${n}`),{session:s,legacySourceFile:az.path(n.replace(/\.json$/,""))}}async listSessions(){let e=await cF.directoryFilesWithMetadata(),I=await az.directoryFilesWithMetadata(),l=await Promise.all(e.map(async r=>({sessionId:r.file.replace(".jsonl",""),startTime:r.ctime,modifiedTime:r.mtime}))),n=(await Promise.all(I.map(async r=>{let s=r.file.match(/^session_(.+)_(\d+)\.json$/);return s?{sessionId:s[1],startTime:r.ctime,modifiedTime:r.mtime}:null}))).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 getLastSession(){let e=await this.listSessions();if(e.length===0)return;e.sort((l,n)=>n.modifiedTime.getTime()-l.modifiedTime.getTime());let I=e[0].sessionId;return await this.getSession(I)}async deleteSession(e){this.sessionWriters[e.sessionId]?.dispose(),delete this.sessionWriters[e.sessionId];let I=cF.path(e.sessionId);this.logger.info(`Deleting session file ${I}`),await W$e(I)}getSessionsDirectory(){return Grt(cF.home(),cF.directory())}setLogger(e){this.logger=e}};o();o();var tNe=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))}};o();import{appendFile as drt,access as irt,mkdir as brt}from"fs/promises";import{constants as mrt}from"fs";import{dirname as hrt}from"path";var lNe=class extends wp{constructor(I,l,n){super(l,n);this.filePath=I;this.writeQueue=prt(hrt(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}
|
|
1410
|
+
`;await $7.runExclusive(i,()=>Pnt(i,m,{mode:384}))}catch(m){throw new Error(`Failed to append to JSONL file ${i}: ${m}`)}},path:n,directoryFiles:async()=>{let G=uG(I(),l());try{let i=(await P7(G,{withFileTypes:!0})).filter(m=>m.isFile()&&m.name.endsWith(".jsonl")).map(m=>m.name),b=await Promise.all(i.map(async m=>{let h=uG(G,m);try{let p=await q7(h);return{file:m,mtime:p.mtime}}catch{return{file:m,mtime:new Date}}}));return b.sort((m,h)=>h.mtime.getTime()-m.mtime.getTime()),b.map(m=>m.file)}catch{return[]}},directoryFilesWithMetadata:async()=>{let G=uG(I(),l());try{let i=(await P7(G,{withFileTypes:!0})).filter(m=>m.isFile()&&m.name.endsWith(".jsonl")).map(m=>m.name),b=await Promise.all(i.map(async m=>{let h=uG(G,m);try{let p=await q7(h);return{file:m,mtime:p.mtime,ctime:p.ctime}}catch{return{file:m,mtime:new Date,ctime:new Date}}}));return b.sort((m,h)=>h.mtime.getTime()-m.mtime.getTime()),b}catch{return[]}},home:I,directory:l}};var b$e=xe({host:ne(),login:ne()}),tct=xe({banner:Ai(["always","once","never"]).optional(),beep:en().optional(),last_logged_in_user:b$e.optional(),logged_in_users:Pr(b$e).optional(),model:ne().optional(),render_markdown:en().optional(),screen_reader:en().optional(),theme:ne().optional(),trusted_folders:Pr(ne()).optional(),store_token_plaintext:en().optional(),stream:en().optional(),feature_flags:xe({enabled:Pr(ne()).optional()}).optional(),asked_setup_terminals:Pr(ne()).optional(),capi_hmac_key:ne().optional(),copilot_hmac_key:ne().optional(),copilot_integration_id:ne().optional(),copilot_tokens:C1(ne(),ne()).optional(),copilot_url:ne().optional(),staff:en().optional(),log_level:Ai(["none","error","warning","info","debug","all","default"]).optional()}),lct=C1(ne(),Iue()),nct=lct.transform(t=>(0,m$e.default)(t,(e,I)=>{let l=I.toLowerCase();return l==="github_copilot_integration_id"?"copilot_integration_id":l})),cct=nct.pipe(tct),rct=G$e(cct.parse,"config");var h$e=["claude-sonnet-4.5","claude-sonnet-4","claude-haiku-4.5","gpt-5"];o();var sct=xe({type:ZI("copilot"),text:ne(),isStreaming:en().optional()}),act=xe({type:ZI("error"),text:ne()}),oct=xe({type:ZI("info"),text:ne()}),Lmn=xe({displayText:ne(),fullPath:ne(),type:Ai(["file","directory","unresolved","image"]),startIndex:Kr()}),Gct=xe({type:ZI("user"),text:ne()}),dct=xe({command:ne(),description:ne(),timeout:Kr().optional(),sessionId:ne().optional(),async:en().optional()}),ict=xe({sessionId:ne(),input:ne(),delay:Kr().optional()}),bct=xe({sessionId:ne(),delay:Kr()}),mct=xe({sessionId:ne()}),hct=sa([dct,ict,bct,mct]),pct=xe({command:ZI("view"),path:ne(),view_range:s8([Kr(),Kr()]).optional()}),uct=xe({command:ZI("create"),path:ne(),file_text:ne()}),Zct=xe({command:ZI("str_replace"),path:ne(),new_str:ne().optional(),old_str:ne()}),Wct=xe({command:ZI("insert"),path:ne(),insert_line:Kr(),new_str:ne()}),Nct=IB("command",[pct,uct,Zct,Wct]),kmn=xe({path:ne(),view_range:s8([Kr(),Kr()]).optional()}),fmn=xe({path:ne(),file_text:ne()}),xmn=xe({path:ne(),old_str:ne(),new_str:ne().optional()}),p$e=sa([hct,Nct,Wp()]),Yct=xe({type:ZI("tool_call_requested"),callId:ne(),name:ne(),toolTitle:ne().optional(),intentionSummary:ne().nullable(),arguments:p$e,partialOutput:ne().optional(),isHidden:en().optional(),isAlwaysExpanded:en().optional(),showNoContent:en().optional()}),Vct=xe({type:ZI("tool_call_completed"),callId:ne(),name:ne(),toolTitle:ne().optional(),intentionSummary:ne().nullable(),result:sa([xe({type:ZI("success"),log:ne(),markdown:en().optional()}),xe({type:ZI("failure"),log:ne(),markdown:en().optional()}),xe({type:ZI("rejected"),markdown:en().optional()}),xe({type:ZI("denied"),log:ne(),markdown:en().optional()})]),arguments:p$e,isHidden:en().optional(),isAlwaysExpanded:en().optional(),showNoContent:en().optional()}),Rct=sa([sct,act,oct,Gct,Yct,Vct]),u$e=Rct.and(xe({id:ne(),timestamp:tB.date()}));var sz=xe({type:ZI("text"),text:ne()}),gct=xe({type:ZI("refusal"),refusal:ne()}),Fct=xe({type:ZI("image_url"),image_url:xe({url:ne(),detail:Ai(["auto","low","high"]).optional()})}),Act=xe({type:ZI("input_audio"),input_audio:xe({data:ne(),format:ZI("wav").or(ZI("mp3"))})}),Qct=xe({type:ZI("file"),file:xe({file_date:ne().optional(),file_id:ne().optional(),filename:ne().optional()})}),wct=sa([sz,Fct,Act,Qct]),Xct=xe({name:ne(),arguments:ne()}),Ect=xe({name:ne(),input:ne()}),Hct=xe({id:ne(),type:ZI("function"),function:Xct}),vct=xe({id:ne(),type:ZI("custom"),custom:Ect}),Cct=sa([Hct,vct]),Jct=xe({name:ne(),arguments:ne()}),Lct=xe({id:ne()}),kct=xe({content:sa([ne(),Pr(sz)]),role:ZI("developer"),name:ne().optional()}),fct=xe({content:sa([ne(),Pr(sz)]),role:ZI("system"),name:ne().optional()}),xct=xe({content:sa([ne(),Pr(wct)]),role:ZI("user"),name:ne().optional()}),Bct=xe({content:sa([ne(),Pr(sa([sz,gct]))]).nullable().optional(),role:ZI("assistant"),name:ne().optional(),refusal:ne().nullable().optional(),audio:Lct.nullable().optional(),function_call:Jct.nullable().optional(),tool_calls:Pr(Cct).optional()}),zct=xe({content:sa([ne(),Pr(sz)]),role:ZI("tool"),tool_call_id:ne()}),Uct=xe({content:ne().nullable(),role:ZI("function"),name:ne()}),Sct=sa([kct,fct,xct,Bct,zct,Uct]),eNe=xe({sessionId:ne(),startTime:tB.date(),chatMessages:Pr(Sct),timeline:Pr(u$e),selectedModel:Ai(h$e).optional()}),az=d$e(eNe.parse,"history-session");o();o();var ur=xe({id:ne().uuid(),timestamp:ne().datetime(),parentId:ne().uuid().nullable(),ephemeral:en().optional()}),Oct=ur.extend({type:ZI("session.start"),data:xe({sessionId:ne(),version:Kr(),producer:ne(),copilotVersion:ne(),startTime:ne().datetime(),selectedModel:ne().optional()})}),Mct=ur.extend({type:ZI("session.resume"),data:xe({resumeTime:ne().datetime(),eventCount:Kr()})}),Tct=ur.extend({type:ZI("session.error"),data:xe({errorType:ne(),message:ne(),stack:ne().optional()})}),jct=ur.extend({type:ZI("session.info"),data:xe({infoType:ne(),message:ne()})}),Dct=ur.extend({type:ZI("session.model_change"),data:xe({previousModel:ne().optional(),newModel:ne()})}),Kct=ur.extend({type:ZI("session.import_legacy"),data:xe({legacySession:eNe,importTime:ne().datetime(),sourceFile:ne()})}),Pct=xe({type:Ai(["file","directory"]),path:ne(),displayName:ne()}),qct=ur.extend({type:ZI("user.message"),data:xe({content:ne(),attachments:Pr(Pct).optional()})}),_ct=ur.extend({type:ZI("assistant.turn_start"),data:xe({turnId:ne()})}),$ct=ur.extend({type:ZI("assistant.message"),data:xe({messageId:ne(),content:ne(),toolRequests:Pr(xe({toolCallId:ne(),name:ne(),arguments:Wp()})).optional()})}),ert=ur.extend({type:ZI("assistant.turn_end"),data:xe({turnId:ne()})}),Irt=ur.extend({type:ZI("assistant.usage"),ephemeral:ZI(!0),data:xe({model:ne().optional(),tokensUsed:Kr().optional(),cost:Kr().optional(),duration:Kr().optional(),initiator:ne().optional()})}),trt=ur.extend({type:ZI("abort"),data:xe({reason:ne()})}),lrt=ur.extend({type:ZI("tool.user_requested"),data:xe({toolCallId:ne(),toolName:ne(),arguments:Wp()})}),nrt=ur.extend({type:ZI("tool.execution_start"),data:xe({toolCallId:ne(),toolName:ne(),arguments:Wp()})}),crt=ur.extend({type:ZI("tool.execution_partial_result"),ephemeral:ZI(!0),data:xe({toolCallId:ne(),partialOutput:ne()})}),rrt=ur.extend({type:ZI("tool.execution_complete"),data:xe({toolCallId:ne(),success:en(),isUserRequested:en().optional(),result:xe({content:ne()}).optional(),error:xe({message:ne(),code:ne().optional()}).optional()})}),srt=ur.extend({type:ZI("hook.start"),data:xe({hookInvocationId:ne(),hookType:ne(),input:Wp()})}),art=ur.extend({type:ZI("hook.end"),data:xe({hookInvocationId:ne(),hookType:ne(),output:Wp(),success:en(),error:xe({message:ne(),stack:ne().optional()}).optional()})}),ort=ur.extend({type:ZI("system.message"),data:xe({content:ne(),role:Ai(["system","developer"]),name:ne().optional(),metadata:xe({promptVersion:ne().optional(),variables:C1(Wp()).optional()}).optional()})}),Z$e=IB("type",[Oct,Mct,Tct,jct,Dct,Kct,qct,_ct,$ct,ert,Irt,trt,lrt,nrt,crt,rrt,srt,art,ort]);var cF=i$e(Z$e.parse,"session");var e_=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.onEvent(r=>{r.ephemeral||(this.unflushedEvents.push(r),!this.shouldSaveSession&&r.type==="user.message"&&(this.shouldSaveSession=!0),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 cF.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 W$e(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())}}},INe=class extends X7{sessionWriters={};copilotVersion;flushDebounceMs;constructor({logger:e,version:I,flushDebounceMs:l}){super({logger:e}),this.copilotVersion=I||"unknown",this.flushDebounceMs=l||100}async createSession(e){let I=e?.sessionId??es(),l=new Date,n=new gp({sessionId:I,startTime:l,logger:this.logger});return this.sessionWriters[I]=new e_(n,this.logger,this.flushDebounceMs),n.addEvent({type:"session.start",data:{sessionId:I,version:1,producer:"copilot-agent",copilotVersion:this.copilotVersion,startTime:l.toISOString(),selectedModel:e?.selectedModel}}),n}async getSession(e){let I,l;try{I=await this.loadSession(e)}catch{try{let n=await this.loadLegacySession(e);I=n.session,l=n.legacySourceFile}catch{return}}return this.sessionWriters[e]||(this.sessionWriters[e]=new e_(I,this.logger,this.flushDebounceMs,!0,l)),I.addEvent({type:"session.resume",data:{resumeTime:new Date().toISOString(),eventCount:I.getEvents().length}}),I}async saveSession(e){await this.sessionWriters[e.sessionId]?.flush()}async loadSession(e){let I=await cF.load(e);if(I.length===0)throw new Error(`Session ${e} has no events`);if(I[0].type!=="session.start")throw new Error("First event must be a session.start event");return await gp.fromEvents({events:I,logger:this.logger})}async loadLegacySession(e){let l=(await az.directoryFiles()).filter(a=>{let G=a.match(/^session_(.+)_(\d+)\.json$/);return G&&G[1]===e});if(l.length===0)throw new Error(`Legacy session ${e} not found`);let n=l[0];l.length>1&&this.logger.info(`Multiple legacy sessions found for ${e}, using newest`);let c=await az.load(n);if(!c)throw new Error(`Failed to load legacy session from ${n}`);let r=new Date(c.startTime),s=new gp({sessionId:c.sessionId,startTime:r,logger:this.logger});return s.addEvent({type:"session.start",data:{sessionId:c.sessionId,version:1,producer:"copilot-agent",copilotVersion:this.copilotVersion,startTime:r.toISOString(),selectedModel:c.selectedModel}}),s.addEvent({type:"session.import_legacy",data:{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} from ${n}`),{session:s,legacySourceFile:az.path(n.replace(/\.json$/,""))}}async listSessions(){let e=await cF.directoryFilesWithMetadata(),I=await az.directoryFilesWithMetadata(),l=await Promise.all(e.map(async r=>({sessionId:r.file.replace(".jsonl",""),startTime:r.ctime,modifiedTime:r.mtime}))),n=(await Promise.all(I.map(async r=>{let s=r.file.match(/^session_(.+)_(\d+)\.json$/);return s?{sessionId:s[1],startTime:r.ctime,modifiedTime:r.mtime}:null}))).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 getLastSession(){let e=await this.listSessions();if(e.length===0)return;e.sort((l,n)=>n.modifiedTime.getTime()-l.modifiedTime.getTime());let I=e[0].sessionId;return await this.getSession(I)}async deleteSession(e){this.sessionWriters[e.sessionId]?.dispose(),delete this.sessionWriters[e.sessionId];let I=cF.path(e.sessionId);this.logger.info(`Deleting session file ${I}`),await W$e(I)}getSessionsDirectory(){return Grt(cF.home(),cF.directory())}setLogger(e){this.logger=e}};o();o();var tNe=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))}};o();import{appendFile as drt,access as irt,mkdir as brt}from"fs/promises";import{constants as mrt}from"fs";import{dirname as hrt}from"path";var lNe=class extends wp{constructor(I,l,n){super(l,n);this.filePath=I;this.writeQueue=prt(hrt(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}
|
|
1411
1411
|
`;this.writeQueue=this.writeQueue.then(()=>this.performWrite(c)).catch(()=>{})}async performWrite(I){await drt(this.filePath,I)}};async function prt(t){try{await irt(t,mrt.F_OK)}catch{await brt(t,{recursive:!0})}}o();async function*whn(t){let{prompt:e,...I}=t;yield*new w7(I).query(e)}export{w7 as Agent,wp as BaseLogger,tNe as CompoundLogger,X2 as ConsoleLogger,lNe as FileLogger,Ri as NoopLogger,gp as Session,Z$e as SessionEventSchema,X7 as SessionManager,llt as completeOrphanedToolCalls,_V as executeHooks,N$e as internal,pv as isDebugEnvironment,whn as query};
|
|
1412
1412
|
/*! Bundled license information:
|
|
1413
1413
|
|