@github/copilot 0.0.327-1 → 0.0.328

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.
Files changed (2) hide show
  1. package/index.js +2 -1
  2. package/package.json +2 -2
package/index.js CHANGED
@@ -542,6 +542,7 @@ Note: ${G.warning}`);e.debug(`Code review completed: ${h}`);let W=u.map(y=>y.met
542
542
  `).reduce(Ibl,Object.create(null)),Ibl=(t,e)=>{let l=parseInt(e,10);if(l!==Buffer.byteLength(e)+1)return t;e=e.slice((l+" ").length);let I=e.split("="),n=I.shift();if(!n)return t;let r=n.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),a=I.join("=");return t[r]=/^([A-Z]+\.)?([mac]|birth|creation)time$/.test(r)?new Date(Number(a)*1e3):/^[0-9]+$/.test(a)?+a:a,t};c();c();var nbl=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,dr=nbl!=="win32"?t=>t:t=>t&&t.replace(/\\/g,"/");var aT=class extends RG{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=!1;ignore=!1;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=!1;absolute;unsupported=!1;constructor(e,l,I){switch(super({}),this.pause(),this.extended=l,this.globalExtended=I,this.header=e,this.remain=e.size??0,this.startBlockSize=512*Math.ceil(this.remain/512),this.blockRemain=this.startBlockSize,this.type=e.type,this.type){case"File":case"OldFile":case"Link":case"SymbolicLink":case"CharacterDevice":case"BlockDevice":case"Directory":case"FIFO":case"ContiguousFile":case"GNUDumpDir":break;case"NextFileHasLongLinkpath":case"NextFileHasLongPath":case"OldGnuLongPath":case"GlobalExtendedHeader":case"ExtendedHeader":case"OldExtendedHeader":this.meta=!0;break;default:this.ignore=!0}if(!e.path)throw new Error("no path provided for tar.ReadEntry");this.path=dr(e.path),this.mode=e.mode,this.mode&&(this.mode=this.mode&4095),this.uid=e.uid,this.gid=e.gid,this.uname=e.uname,this.gname=e.gname,this.size=this.remain,this.mtime=e.mtime,this.atime=e.atime,this.ctime=e.ctime,this.linkpath=e.linkpath?dr(e.linkpath):void 0,this.uname=e.uname,this.gname=e.gname,l&&this.#e(l),I&&this.#e(I,!0)}write(e){let l=e.length;if(l>this.blockRemain)throw new Error("writing more to entry than is appropriate");let I=this.remain,n=this.blockRemain;return this.remain=Math.max(0,I-l),this.blockRemain=Math.max(0,n-l),this.ignore?!0:I>=l?super.write(e):super.write(e.subarray(0,I))}#e(e,l=!1){e.path&&(e.path=dr(e.path)),e.linkpath&&(e.linkpath=dr(e.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(e).filter(([I,n])=>!(n==null||I==="path"&&l))))}};c();var Yk=(t,e,l,I={})=>{t.file&&(I.file=t.file),t.cwd&&(I.cwd=t.cwd),I.code=l instanceof Error&&l.code||e,I.tarCode=e,!t.strict&&I.recoverable!==!1?(l instanceof Error&&(I=Object.assign(l,I),l=l.message),t.emit("warn",e,l,I)):l instanceof Error?t.emit("error",Object.assign(l,I)):t.emit("error",Object.assign(new Error(`${e}: ${l}`),I))};var abl=1024*1024,_Fe=Buffer.from([31,139]),VA=Symbol("state"),Vk=Symbol("writeEntry"),Uw=Symbol("readEntry"),zFe=Symbol("nextEntry"),lnt=Symbol("processEntry"),HE=Symbol("extendedHeader"),G8=Symbol("globalExtendedHeader"),yH=Symbol("meta"),Int=Symbol("emitMeta"),Mc=Symbol("buffer"),_w=Symbol("queue"),RH=Symbol("ended"),MFe=Symbol("emittedEnd"),wk=Symbol("emit"),EG=Symbol("unzip"),pme=Symbol("consumeChunk"),hme=Symbol("consumeChunkSub"),DFe=Symbol("consumeBody"),nnt=Symbol("consumeMeta"),rnt=Symbol("consumeHeader"),b8=Symbol("consuming"),jFe=Symbol("bufferConcat"),Zme=Symbol("maybeEnd"),sT=Symbol("writing"),EH=Symbol("aborted"),Nme=Symbol("onDone"),Fk=Symbol("sawValidEntry"),Wme=Symbol("sawNullBlock"),gme=Symbol("sawEOF"),ant=Symbol("closeStream"),sbl=()=>!0,zw=class extends rbl{file;strict;maxMetaEntrySize;filter;brotli;writable=!0;readable=!1;[_w]=new nT;[Mc];[Uw];[Vk];[VA]="begin";[yH]="";[HE];[G8];[RH]=!1;[EG];[EH]=!1;[Fk];[Wme]=!1;[gme]=!1;[sT]=!1;[b8]=!1;[MFe]=!1;constructor(e={}){super(),this.file=e.file||"",this.on(Nme,()=>{(this[VA]==="begin"||this[Fk]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),e.ondone?this.on(Nme,e.ondone):this.on(Nme,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!e.strict,this.maxMetaEntrySize=e.maxMetaEntrySize||abl,this.filter=typeof e.filter=="function"?e.filter:sbl;let l=e.file&&(e.file.endsWith(".tar.br")||e.file.endsWith(".tbr"));this.brotli=!e.gzip&&e.brotli!==void 0?e.brotli:l?void 0:!1,this.on("end",()=>this[ant]()),typeof e.onwarn=="function"&&this.on("warn",e.onwarn),typeof e.onReadEntry=="function"&&this.on("entry",e.onReadEntry)}warn(e,l,I={}){Yk(this,e,l,I)}[rnt](e,l){this[Fk]===void 0&&(this[Fk]=!1);let I;try{I=new xW(e,l,this[HE],this[G8])}catch(n){return this.warn("TAR_ENTRY_INVALID",n)}if(I.nullBlock)this[Wme]?(this[gme]=!0,this[VA]==="begin"&&(this[VA]="header"),this[wk]("eof")):(this[Wme]=!0,this[wk]("nullBlock"));else if(this[Wme]=!1,!I.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:I});else if(!I.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:I});else{let n=I.type;if(/^(Symbolic)?Link$/.test(n)&&!I.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:I});else if(!/^(Symbolic)?Link$/.test(n)&&!/^(Global)?ExtendedHeader$/.test(n)&&I.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:I});else{let r=this[Vk]=new aT(I,this[HE],this[G8]);if(!this[Fk])if(r.remain){let a=()=>{r.invalid||(this[Fk]=!0)};r.on("end",a)}else this[Fk]=!0;r.meta?r.size>this.maxMetaEntrySize?(r.ignore=!0,this[wk]("ignoredEntry",r),this[VA]="ignore",r.resume()):r.size>0&&(this[yH]="",r.on("data",a=>this[yH]+=a),this[VA]="meta"):(this[HE]=void 0,r.ignore=r.ignore||!this.filter(r.path,r),r.ignore?(this[wk]("ignoredEntry",r),this[VA]=r.remain?"ignore":"header",r.resume()):(r.remain?this[VA]="body":(this[VA]="header",r.end()),this[Uw]?this[_w].push(r):(this[_w].push(r),this[zFe]())))}}}[ant](){queueMicrotask(()=>this.emit("close"))}[lnt](e){let l=!0;if(!e)this[Uw]=void 0,l=!1;else if(Array.isArray(e)){let[I,...n]=e;this.emit(I,...n)}else this[Uw]=e,this.emit("entry",e),e.emittedEnd||(e.on("end",()=>this[zFe]()),l=!1);return l}[zFe](){do;while(this[lnt](this[_w].shift()));if(!this[_w].length){let e=this[Uw];!e||e.flowing||e.size===e.remain?this[sT]||this.emit("drain"):e.once("drain",()=>this.emit("drain"))}}[DFe](e,l){let I=this[Vk];if(!I)throw new Error("attempt to consume body without entry??");let n=I.blockRemain??0,r=n>=e.length&&l===0?e:e.subarray(l,l+n);return I.write(r),I.blockRemain||(this[VA]="header",this[Vk]=void 0,I.end()),r.length}[nnt](e,l){let I=this[Vk],n=this[DFe](e,l);return!this[Vk]&&I&&this[Int](I),n}[wk](e,l,I){!this[_w].length&&!this[Uw]?this.emit(e,l,I):this[_w].push([e,l,I])}[Int](e){switch(this[wk]("meta",this[yH]),e.type){case"ExtendedHeader":case"OldExtendedHeader":this[HE]=AH.parse(this[yH],this[HE],!1);break;case"GlobalExtendedHeader":this[G8]=AH.parse(this[yH],this[G8],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let l=this[HE]??Object.create(null);this[HE]=l,l.path=this[yH].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let l=this[HE]||Object.create(null);this[HE]=l,l.linkpath=this[yH].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+e.type)}}abort(e){this[EH]=!0,this.emit("abort",e),this.warn("TAR_ABORT",e,{recoverable:!1})}write(e,l,I){if(typeof l=="function"&&(I=l,l=void 0),typeof e=="string"&&(e=Buffer.from(e,typeof l=="string"?l:"utf8")),this[EH])return I?.(),!1;if((this[EG]===void 0||this.brotli===void 0&&this[EG]===!1)&&e){if(this[Mc]&&(e=Buffer.concat([this[Mc],e]),this[Mc]=void 0),e.length<_Fe.length)return this[Mc]=e,I?.(),!0;for(let s=0;this[EG]===void 0&&s<_Fe.length;s++)e[s]!==_Fe[s]&&(this[EG]=!1);let a=this.brotli===void 0;if(this[EG]===!1&&a)if(e.length<512)if(this[RH])this.brotli=!0;else return this[Mc]=e,I?.(),!0;else try{new xW(e.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[EG]===void 0||this[EG]===!1&&this.brotli){let s=this[RH];this[RH]=!1,this[EG]=this[EG]===void 0?new ime({}):new Gme({}),this[EG].on("data",d=>this[pme](d)),this[EG].on("error",d=>this.abort(d)),this[EG].on("end",()=>{this[RH]=!0,this[pme]()}),this[sT]=!0;let o=!!this[EG][s?"end":"write"](e);return this[sT]=!1,I?.(),o}}this[sT]=!0,this[EG]?this[EG].write(e):this[pme](e),this[sT]=!1;let r=this[_w].length?!1:this[Uw]?this[Uw].flowing:!0;return!r&&!this[_w].length&&this[Uw]?.once("drain",()=>this.emit("drain")),I?.(),r}[jFe](e){e&&!this[EH]&&(this[Mc]=this[Mc]?Buffer.concat([this[Mc],e]):e)}[Zme](){if(this[RH]&&!this[MFe]&&!this[EH]&&!this[b8]){this[MFe]=!0;let e=this[Vk];if(e&&e.blockRemain){let l=this[Mc]?this[Mc].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${e.blockRemain} more bytes, only ${l} available)`,{entry:e}),this[Mc]&&e.write(this[Mc]),e.end()}this[wk](Nme)}}[pme](e){if(this[b8]&&e)this[jFe](e);else if(!e&&!this[Mc])this[Zme]();else if(e){if(this[b8]=!0,this[Mc]){this[jFe](e);let l=this[Mc];this[Mc]=void 0,this[hme](l)}else this[hme](e);for(;this[Mc]&&this[Mc]?.length>=512&&!this[EH]&&!this[gme];){let l=this[Mc];this[Mc]=void 0,this[hme](l)}this[b8]=!1}(!this[Mc]||this[RH])&&this[Zme]()}[hme](e){let l=0,I=e.length;for(;l+512<=I&&!this[EH]&&!this[gme];)switch(this[VA]){case"begin":case"header":this[rnt](e,l),l+=512;break;case"ignore":case"body":l+=this[DFe](e,l);break;case"meta":l+=this[nnt](e,l);break;default:throw new Error("invalid state: "+this[VA])}l<I&&(this[Mc]?this[Mc]=Buffer.concat([e.subarray(l),this[Mc]]):this[Mc]=e.subarray(l))}end(e,l,I){return typeof e=="function"&&(I=e,l=void 0,e=void 0),typeof l=="function"&&(I=l,l=void 0),typeof e=="string"&&(e=Buffer.from(e,l)),I&&this.once("finish",I),this[EH]||(this[EG]?(e&&this[EG].write(e),this[EG].end()):(this[RH]=!0,this.brotli===void 0&&(e=e||Buffer.alloc(0)),e&&this.write(e),this[Zme]())),this}};c();var XE=t=>{let e=t.length-1,l=-1;for(;e>-1&&t.charAt(e)==="/";)l=e,e--;return l===-1?t:t.slice(0,l)};var ibl=t=>{let e=t.onReadEntry;t.onReadEntry=e?l=>{e(l),l.resume()}:l=>l.resume()},PFe=(t,e)=>{let l=new Map(e.map(r=>[XE(r),!0])),I=t.filter,n=(r,a="")=>{let s=a||cbl(r).root||".",o;if(r===s)o=!1;else{let d=l.get(r);d!==void 0?o=d:o=n(obl(r),s)}return l.set(r,o),o};t.filter=I?(r,a)=>I(r,a)&&n(XE(r)):r=>n(XE(r))},dbl=t=>{let e=new zw(t),l=t.file,I;try{let n=oT.statSync(l),r=t.maxReadSize||16*1024*1024;if(n.size<r)e.end(oT.readFileSync(l));else{let a=0,s=Buffer.allocUnsafe(r);for(I=oT.openSync(l,"r");a<n.size;){let o=oT.readSync(I,s,0,r,a);a+=o,e.write(s.subarray(0,o))}e.end()}}finally{if(typeof I=="number")try{oT.closeSync(I)}catch{}}},mbl=(t,e)=>{let l=new zw(t),I=t.maxReadSize||16*1024*1024,n=t.file;return new Promise((a,s)=>{l.on("error",s),l.on("end",a),oT.stat(n,(o,d)=>{if(o)s(o);else{let G=new gk(n,{readSize:I,size:d.size});G.on("error",s),G.pipe(l)}})})},vk=CE(dbl,mbl,t=>new zw(t),t=>new zw(t),(t,e)=>{e?.length&&PFe(t,e),t.noResume||ibl(t)});c();import Hme from"fs";c();import fE from"fs";import int from"path";c();var KFe=(t,e,l)=>(t&=4095,l&&(t=(t|384)&-19),e&&(t&256&&(t|=64),t&32&&(t|=8),t&4&&(t|=1)),t);c();import{win32 as Gbl}from"node:path";var{isAbsolute:bbl,parse:snt}=Gbl,u8=t=>{let e="",l=snt(t);for(;bbl(t)||l.root;){let I=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":l.root;t=t.slice(I.length),e+=I,l=snt(t)}return[e,t]};c();var Ame=["|","<",">","?",":"],qFe=Ame.map(t=>String.fromCharCode(61440+t.charCodeAt(0))),ubl=new Map(Ame.map((t,e)=>[t,qFe[e]])),pbl=new Map(qFe.map((t,e)=>[t,Ame[e]])),$Fe=t=>Ame.reduce((e,l)=>e.split(l).join(ubl.get(l)),t),ont=t=>qFe.reduce((e,l)=>e.split(l).join(pbl.get(l)),t);var unt=(t,e)=>e?(t=dr(t).replace(/^\.(\/|$)/,""),XE(e)+"/"+t):dr(t),hbl=16*1024*1024,dnt=Symbol("process"),mnt=Symbol("file"),Gnt=Symbol("directory"),tve=Symbol("symlink"),bnt=Symbol("hardlink"),p8=Symbol("header"),yme=Symbol("read"),lve=Symbol("lstat"),Rme=Symbol("onlstat"),Ive=Symbol("onread"),nve=Symbol("onreadlink"),rve=Symbol("openfile"),ave=Symbol("onopenfile"),YH=Symbol("close"),Eme=Symbol("mode"),sve=Symbol("awaitDrain"),eve=Symbol("ondrain"),JE=Symbol("prefix"),h8=class extends RG{path;portable;myuid=process.getuid&&process.getuid()||0;myuser=process.env.USER||"";maxReadSize;linkCache;statCache;preservePaths;cwd;strict;mtime;noPax;noMtime;prefix;fd;blockLen=0;blockRemain=0;buf;pos=0;remain=0;length=0;offset=0;win32;absolute;header;type;linkpath;stat;onWriteEntry;#e=!1;constructor(e,l={}){let I=d8(l);super(),this.path=dr(e),this.portable=!!I.portable,this.maxReadSize=I.maxReadSize||hbl,this.linkCache=I.linkCache||new Map,this.statCache=I.statCache||new Map,this.preservePaths=!!I.preservePaths,this.cwd=dr(I.cwd||process.cwd()),this.strict=!!I.strict,this.noPax=!!I.noPax,this.noMtime=!!I.noMtime,this.mtime=I.mtime,this.prefix=I.prefix?dr(I.prefix):void 0,this.onWriteEntry=I.onWriteEntry,typeof I.onwarn=="function"&&this.on("warn",I.onwarn);let n=!1;if(!this.preservePaths){let[a,s]=u8(this.path);a&&typeof s=="string"&&(this.path=s,n=a)}this.win32=!!I.win32||process.platform==="win32",this.win32&&(this.path=ont(this.path.replace(/\\/g,"/")),e=e.replace(/\\/g,"/")),this.absolute=dr(I.absolute||int.resolve(this.cwd,e)),this.path===""&&(this.path="./"),n&&this.warn("TAR_ENTRY_INFO",`stripping ${n} from absolute path`,{entry:this,path:n+this.path});let r=this.statCache.get(this.absolute);r?this[Rme](r):this[lve]()}warn(e,l,I={}){return Yk(this,e,l,I)}emit(e,...l){return e==="error"&&(this.#e=!0),super.emit(e,...l)}[lve](){fE.lstat(this.absolute,(e,l)=>{if(e)return this.emit("error",e);this[Rme](l)})}[Rme](e){this.statCache.set(this.absolute,e),this.stat=e,e.isFile()||(e.size=0),this.type=Zbl(e),this.emit("stat",e),this[dnt]()}[dnt](){switch(this.type){case"File":return this[mnt]();case"Directory":return this[Gnt]();case"SymbolicLink":return this[tve]();default:return this.end()}}[Eme](e){return KFe(e,this.type==="Directory",this.portable)}[JE](e){return unt(e,this.prefix)}[p8](){if(!this.stat)throw new Error("cannot write header before stat");this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.onWriteEntry?.(this),this.header=new xW({path:this[JE](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[JE](this.linkpath):this.linkpath,mode:this[Eme](this.stat.mode),uid:this.portable?void 0:this.stat.uid,gid:this.portable?void 0:this.stat.gid,size:this.stat.size,mtime:this.noMtime?void 0:this.mtime||this.stat.mtime,type:this.type==="Unsupported"?void 0:this.type,uname:this.portable?void 0:this.stat.uid===this.myuid?this.myuser:"",atime:this.portable?void 0:this.stat.atime,ctime:this.portable?void 0:this.stat.ctime}),this.header.encode()&&!this.noPax&&super.write(new AH({atime:this.portable?void 0:this.header.atime,ctime:this.portable?void 0:this.header.ctime,gid:this.portable?void 0:this.header.gid,mtime:this.noMtime?void 0:this.mtime||this.header.mtime,path:this[JE](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[JE](this.linkpath):this.linkpath,size:this.header.size,uid:this.portable?void 0:this.header.uid,uname:this.portable?void 0:this.header.uname,dev:this.portable?void 0:this.stat.dev,ino:this.portable?void 0:this.stat.ino,nlink:this.portable?void 0:this.stat.nlink}).encode());let e=this.header?.block;if(!e)throw new Error("failed to encode header");super.write(e)}[Gnt](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[p8](),this.end()}[tve](){fE.readlink(this.absolute,(e,l)=>{if(e)return this.emit("error",e);this[nve](l)})}[nve](e){this.linkpath=dr(e),this[p8](),this.end()}[bnt](e){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=dr(int.relative(this.cwd,e)),this.stat.size=0,this[p8](),this.end()}[mnt](){if(!this.stat)throw new Error("cannot create file entry without stat");if(this.stat.nlink>1){let e=`${this.stat.dev}:${this.stat.ino}`,l=this.linkCache.get(e);if(l?.indexOf(this.cwd)===0)return this[bnt](l);this.linkCache.set(e,this.absolute)}if(this[p8](),this.stat.size===0)return this.end();this[rve]()}[rve](){fE.open(this.absolute,"r",(e,l)=>{if(e)return this.emit("error",e);this[ave](l)})}[ave](e){if(this.fd=e,this.#e)return this[YH]();if(!this.stat)throw new Error("should stat before calling onopenfile");this.blockLen=512*Math.ceil(this.stat.size/512),this.blockRemain=this.blockLen;let l=Math.min(this.blockLen,this.maxReadSize);this.buf=Buffer.allocUnsafe(l),this.offset=0,this.pos=0,this.remain=this.stat.size,this.length=this.buf.length,this[yme]()}[yme](){let{fd:e,buf:l,offset:I,length:n,pos:r}=this;if(e===void 0||l===void 0)throw new Error("cannot read file without first opening");fE.read(e,l,I,n,r,(a,s)=>{if(a)return this[YH](()=>this.emit("error",a));this[Ive](s)})}[YH](e=()=>{}){this.fd!==void 0&&fE.close(this.fd,e)}[Ive](e){if(e<=0&&this.remain>0){let n=Object.assign(new Error("encountered unexpected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[YH](()=>this.emit("error",n))}if(e>this.remain){let n=Object.assign(new Error("did not encounter expected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[YH](()=>this.emit("error",n))}if(!this.buf)throw new Error("should have created buffer prior to reading");if(e===this.remain)for(let n=e;n<this.length&&e<this.blockRemain;n++)this.buf[n+this.offset]=0,e++,this.remain++;let l=this.offset===0&&e===this.buf.length?this.buf:this.buf.subarray(this.offset,this.offset+e);this.write(l)?this[eve]():this[sve](()=>this[eve]())}[sve](e){this.once("drain",e)}write(e,l,I){if(typeof l=="function"&&(I=l,l=void 0),typeof e=="string"&&(e=Buffer.from(e,typeof l=="string"?l:"utf8")),this.blockRemain<e.length){let n=Object.assign(new Error("writing more data than expected"),{path:this.absolute});return this.emit("error",n)}return this.remain-=e.length,this.blockRemain-=e.length,this.pos+=e.length,this.offset+=e.length,super.write(e,null,I)}[eve](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[YH](e=>e?this.emit("error",e):this.end());if(!this.buf)throw new Error("buffer lost somehow in ONDRAIN");this.offset>=this.length&&(this.buf=Buffer.allocUnsafe(Math.min(this.blockRemain,this.buf.length)),this.offset=0),this.length=this.buf.length-this.offset,this[yme]()}},Yme=class extends h8{sync=!0;[lve](){this[Rme](fE.lstatSync(this.absolute))}[tve](){this[nve](fE.readlinkSync(this.absolute))}[rve](){this[ave](fE.openSync(this.absolute,"r"))}[yme](){let e=!0;try{let{fd:l,buf:I,offset:n,length:r,pos:a}=this;if(l===void 0||I===void 0)throw new Error("fd and buf must be set in READ method");let s=fE.readSync(l,I,n,r,a);this[Ive](s),e=!1}finally{if(e)try{this[YH](()=>{})}catch{}}}[sve](e){e()}[YH](e=()=>{}){this.fd!==void 0&&fE.closeSync(this.fd),e()}},Vme=class extends RG{blockLen=0;blockRemain=0;buf=0;pos=0;remain=0;length=0;preservePaths;portable;strict;noPax;noMtime;readEntry;type;prefix;path;mode;uid;gid;uname;gname;header;mtime;atime;ctime;linkpath;size;onWriteEntry;warn(e,l,I={}){return Yk(this,e,l,I)}constructor(e,l={}){let I=d8(l);super(),this.preservePaths=!!I.preservePaths,this.portable=!!I.portable,this.strict=!!I.strict,this.noPax=!!I.noPax,this.noMtime=!!I.noMtime,this.onWriteEntry=I.onWriteEntry,this.readEntry=e;let{type:n}=e;if(n==="Unsupported")throw new Error("writing entry that should be ignored");this.type=n,this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.prefix=I.prefix,this.path=dr(e.path),this.mode=e.mode!==void 0?this[Eme](e.mode):void 0,this.uid=this.portable?void 0:e.uid,this.gid=this.portable?void 0:e.gid,this.uname=this.portable?void 0:e.uname,this.gname=this.portable?void 0:e.gname,this.size=e.size,this.mtime=this.noMtime?void 0:I.mtime||e.mtime,this.atime=this.portable?void 0:e.atime,this.ctime=this.portable?void 0:e.ctime,this.linkpath=e.linkpath!==void 0?dr(e.linkpath):void 0,typeof I.onwarn=="function"&&this.on("warn",I.onwarn);let r=!1;if(!this.preservePaths){let[s,o]=u8(this.path);s&&typeof o=="string"&&(this.path=o,r=s)}this.remain=e.size,this.blockRemain=e.startBlockSize,this.onWriteEntry?.(this),this.header=new xW({path:this[JE](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[JE](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?void 0:this.uid,gid:this.portable?void 0:this.gid,size:this.size,mtime:this.noMtime?void 0:this.mtime,type:this.type,uname:this.portable?void 0:this.uname,atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime}),r&&this.warn("TAR_ENTRY_INFO",`stripping ${r} from absolute path`,{entry:this,path:r+this.path}),this.header.encode()&&!this.noPax&&super.write(new AH({atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime,gid:this.portable?void 0:this.gid,mtime:this.noMtime?void 0:this.mtime,path:this[JE](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[JE](this.linkpath):this.linkpath,size:this.size,uid:this.portable?void 0:this.uid,uname:this.portable?void 0:this.uname,dev:this.portable?void 0:this.readEntry.dev,ino:this.portable?void 0:this.readEntry.ino,nlink:this.portable?void 0:this.readEntry.nlink}).encode());let a=this.header?.block;if(!a)throw new Error("failed to encode header");super.write(a),e.pipe(this)}[JE](e){return unt(e,this.prefix)}[Eme](e){return KFe(e,this.type==="Directory",this.portable)}write(e,l,I){typeof l=="function"&&(I=l,l=void 0),typeof e=="string"&&(e=Buffer.from(e,typeof l=="string"?l:"utf8"));let n=e.length;if(n>this.blockRemain)throw new Error("writing more to entry than is appropriate");return this.blockRemain-=n,super.write(e,I)}end(e,l,I){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),typeof e=="function"&&(I=e,l=void 0,e=void 0),typeof l=="function"&&(I=l,l=void 0),typeof e=="string"&&(e=Buffer.from(e,l??"utf8")),I&&this.once("finish",I),e?super.end(e,I):super.end(I),this}},Zbl=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported";import Wnt from"path";var Xme=class{path;absolute;entry;stat;readdir;pending=!1;ignore=!1;piped=!1;constructor(e,l){this.path=e||"./",this.absolute=l}},pnt=Buffer.alloc(1024),wme=Symbol("onStat"),Z8=Symbol("ended"),t2=Symbol("queue"),cT=Symbol("current"),Qk=Symbol("process"),N8=Symbol("processing"),hnt=Symbol("processJob"),l2=Symbol("jobs"),ove=Symbol("jobDone"),Fme=Symbol("addFSEntry"),Znt=Symbol("addTarEntry"),dve=Symbol("stat"),mve=Symbol("readdir"),vme=Symbol("onreaddir"),Qme=Symbol("pipe"),Nnt=Symbol("entry"),cve=Symbol("entryOpt"),Cme=Symbol("writeEntryClass"),gnt=Symbol("write"),ive=Symbol("ondrain"),VH=class extends RG{opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[Cme];onWriteEntry;[t2];[l2]=0;[N8]=!1;[Z8]=!1;constructor(e={}){if(super(),this.opt=e,this.file=e.file||"",this.cwd=e.cwd||process.cwd(),this.maxReadSize=e.maxReadSize,this.preservePaths=!!e.preservePaths,this.strict=!!e.strict,this.noPax=!!e.noPax,this.prefix=dr(e.prefix||""),this.linkCache=e.linkCache||new Map,this.statCache=e.statCache||new Map,this.readdirCache=e.readdirCache||new Map,this.onWriteEntry=e.onWriteEntry,this[Cme]=h8,typeof e.onwarn=="function"&&this.on("warn",e.onwarn),this.portable=!!e.portable,e.gzip||e.brotli){if(e.gzip&&e.brotli)throw new TypeError("gzip and brotli are mutually exclusive");if(e.gzip&&(typeof e.gzip!="object"&&(e.gzip={}),this.portable&&(e.gzip.portable=!0),this.zip=new cme(e.gzip)),e.brotli&&(typeof e.brotli!="object"&&(e.brotli={}),this.zip=new mme(e.brotli)),!this.zip)throw new Error("impossible");let l=this.zip;l.on("data",I=>super.write(I)),l.on("end",()=>super.end()),l.on("drain",()=>this[ive]()),this.on("resume",()=>l.resume())}else this.on("drain",this[ive]);this.noDirRecurse=!!e.noDirRecurse,this.follow=!!e.follow,this.noMtime=!!e.noMtime,e.mtime&&(this.mtime=e.mtime),this.filter=typeof e.filter=="function"?e.filter:()=>!0,this[t2]=new nT,this[l2]=0,this.jobs=Number(e.jobs)||4,this[N8]=!1,this[Z8]=!1}[gnt](e){return super.write(e)}add(e){return this.write(e),this}end(e,l,I){return typeof e=="function"&&(I=e,e=void 0),typeof l=="function"&&(I=l,l=void 0),e&&this.add(e),this[Z8]=!0,this[Qk](),I&&I(),this}write(e){if(this[Z8])throw new Error("write after end");return e instanceof aT?this[Znt](e):this[Fme](e),this.flowing}[Znt](e){let l=dr(Wnt.resolve(this.cwd,e.path));if(!this.filter(e.path,e))e.resume();else{let I=new Xme(e.path,l);I.entry=new Vme(e,this[cve](I)),I.entry.on("end",()=>this[ove](I)),this[l2]+=1,this[t2].push(I)}this[Qk]()}[Fme](e){let l=dr(Wnt.resolve(this.cwd,e));this[t2].push(new Xme(e,l)),this[Qk]()}[dve](e){e.pending=!0,this[l2]+=1;let l=this.follow?"stat":"lstat";Hme[l](e.absolute,(I,n)=>{e.pending=!1,this[l2]-=1,I?this.emit("error",I):this[wme](e,n)})}[wme](e,l){this.statCache.set(e.absolute,l),e.stat=l,this.filter(e.path,l)||(e.ignore=!0),this[Qk]()}[mve](e){e.pending=!0,this[l2]+=1,Hme.readdir(e.absolute,(l,I)=>{if(e.pending=!1,this[l2]-=1,l)return this.emit("error",l);this[vme](e,I)})}[vme](e,l){this.readdirCache.set(e.absolute,l),e.readdir=l,this[Qk]()}[Qk](){if(!this[N8]){this[N8]=!0;for(let e=this[t2].head;e&&this[l2]<this.jobs;e=e.next)if(this[hnt](e.value),e.value.ignore){let l=e.next;this[t2].removeNode(e),e.next=l}this[N8]=!1,this[Z8]&&!this[t2].length&&this[l2]===0&&(this.zip?this.zip.end(pnt):(super.write(pnt),super.end()))}}get[cT](){return this[t2]&&this[t2].head&&this[t2].head.value}[ove](e){this[t2].shift(),this[l2]-=1,this[Qk]()}[hnt](e){if(!e.pending){if(e.entry){e===this[cT]&&!e.piped&&this[Qme](e);return}if(!e.stat){let l=this.statCache.get(e.absolute);l?this[wme](e,l):this[dve](e)}if(e.stat&&!e.ignore){if(!this.noDirRecurse&&e.stat.isDirectory()&&!e.readdir){let l=this.readdirCache.get(e.absolute);if(l?this[vme](e,l):this[mve](e),!e.readdir)return}if(e.entry=this[Nnt](e),!e.entry){e.ignore=!0;return}e===this[cT]&&!e.piped&&this[Qme](e)}}}[cve](e){return{onwarn:(l,I,n)=>this.warn(l,I,n),noPax:this.noPax,cwd:this.cwd,absolute:e.absolute,preservePaths:this.preservePaths,maxReadSize:this.maxReadSize,strict:this.strict,portable:this.portable,linkCache:this.linkCache,statCache:this.statCache,noMtime:this.noMtime,mtime:this.mtime,prefix:this.prefix,onWriteEntry:this.onWriteEntry}}[Nnt](e){this[l2]+=1;try{return new this[Cme](e.path,this[cve](e)).on("end",()=>this[ove](e)).on("error",I=>this.emit("error",I))}catch(l){this.emit("error",l)}}[ive](){this[cT]&&this[cT].entry&&this[cT].entry.resume()}[Qme](e){e.piped=!0,e.readdir&&e.readdir.forEach(n=>{let r=e.path,a=r==="./"?"":r.replace(/\/*$/,"/");this[Fme](a+n)});let l=e.entry,I=this.zip;if(!l)throw new Error("cannot pipe without source");I?l.on("data",n=>{I.write(n)||l.pause()}):l.on("data",n=>{super.write(n)||l.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}warn(e,l,I={}){Yk(this,e,l,I)}},Ck=class extends VH{sync=!0;constructor(e){super(e),this[Cme]=Yme}pause(){}resume(){}[dve](e){let l=this.follow?"statSync":"lstatSync";this[wme](e,Hme[l](e.absolute))}[mve](e){this[vme](e,Hme.readdirSync(e.absolute))}[Qme](e){let l=e.entry,I=this.zip;if(e.readdir&&e.readdir.forEach(n=>{let r=e.path,a=r==="./"?"":r.replace(/\/*$/,"/");this[Fme](a+n)}),!l)throw new Error("Cannot pipe without source");I?l.on("data",n=>{I.write(n)}):l.on("data",n=>{super[gnt](n)})}};var Nbl=(t,e)=>{let l=new Ck(t),I=new lT(t.file,{mode:t.mode||438});l.pipe(I),ynt(l,e)},Wbl=(t,e)=>{let l=new VH(t),I=new Ow(t.file,{mode:t.mode||438});l.pipe(I);let n=new Promise((r,a)=>{I.on("error",a),I.on("close",r),l.on("error",a)});return Rnt(l,e),n},ynt=(t,e)=>{e.forEach(l=>{l.charAt(0)==="@"?vk({file:Ant.resolve(t.cwd,l.slice(1)),sync:!0,noResume:!0,onReadEntry:I=>t.add(I)}):t.add(l)}),t.end()},Rnt=async(t,e)=>{for(let l=0;l<e.length;l++){let I=String(e[l]);I.charAt(0)==="@"?await vk({file:Ant.resolve(String(t.cwd),I.slice(1)),noResume:!0,onReadEntry:n=>{t.add(n)}}):t.add(I)}t.end()},gbl=(t,e)=>{let l=new Ck(t);return ynt(l,e),l},Abl=(t,e)=>{let l=new VH(t);return Rnt(l,e),l},Gve=CE(Nbl,Wbl,gbl,Abl,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")});c();import znt from"node:fs";c();import jbl from"node:assert";import{randomBytes as _nt}from"node:crypto";import Ds from"node:fs";import Dw from"node:path";c();import Ent from"fs";var ybl=process.env.__FAKE_PLATFORM__||process.platform,Rbl=ybl==="win32",{O_CREAT:Ebl,O_TRUNC:Ybl,O_WRONLY:Vbl}=Ent.constants,Ynt=Number(process.env.__FAKE_FS_O_FILENAME__)||Ent.constants.UV_FS_O_FILEMAP||0,wbl=Rbl&&!!Ynt,Fbl=512*1024,vbl=Ynt|Ybl|Ebl|Vbl,bve=wbl?t=>t<Fbl?vbl:"w":()=>"w";c();c();import Jme from"node:fs";import W8 from"node:path";var uve=(t,e,l)=>{try{return Jme.lchownSync(t,e,l)}catch(I){if(I?.code!=="ENOENT")throw I}},fme=(t,e,l,I)=>{Jme.lchown(t,e,l,n=>{I(n&&n?.code!=="ENOENT"?n:null)})},Qbl=(t,e,l,I,n)=>{if(e.isDirectory())pve(W8.resolve(t,e.name),l,I,r=>{if(r)return n(r);let a=W8.resolve(t,e.name);fme(a,l,I,n)});else{let r=W8.resolve(t,e.name);fme(r,l,I,n)}},pve=(t,e,l,I)=>{Jme.readdir(t,{withFileTypes:!0},(n,r)=>{if(n){if(n.code==="ENOENT")return I();if(n.code!=="ENOTDIR"&&n.code!=="ENOTSUP")return I(n)}if(n||!r.length)return fme(t,e,l,I);let a=r.length,s=null,o=d=>{if(!s){if(d)return I(s=d);if(--a===0)return fme(t,e,l,I)}};for(let d of r)Qbl(t,d,e,l,o)})},Cbl=(t,e,l,I)=>{e.isDirectory()&&hve(W8.resolve(t,e.name),l,I),uve(W8.resolve(t,e.name),l,I)},hve=(t,e,l)=>{let I;try{I=Jme.readdirSync(t,{withFileTypes:!0})}catch(n){let r=n;if(r?.code==="ENOENT")return;if(r?.code==="ENOTDIR"||r?.code==="ENOTSUP")return uve(t,e,l);throw r}for(let n of I)Cbl(t,n,e,l);return uve(t,e,l)};import FA from"fs";c();c();import{dirname as Vnt}from"path";c();import{mkdir as Hbl,mkdirSync as Xbl,stat as fbl,statSync as Jbl}from"fs";var wA=t=>{if(!t)t={mode:511};else if(typeof t=="object")t={mode:511,...t};else if(typeof t=="number")t={mode:t};else if(typeof t=="string")t={mode:parseInt(t,8)};else throw new TypeError("invalid options argument");let e=t,l=t.fs||{};return t.mkdir=t.mkdir||l.mkdir||Hbl,t.mkdirAsync=t.mkdirAsync?t.mkdirAsync:async(I,n)=>new Promise((r,a)=>e.mkdir(I,n,(s,o)=>s?a(s):r(o))),t.stat=t.stat||l.stat||fbl,t.statAsync=t.statAsync?t.statAsync:async I=>new Promise((n,r)=>e.stat(I,(a,s)=>a?r(a):n(s))),t.statSync=t.statSync||l.statSync||Jbl,t.mkdirSync=t.mkdirSync||l.mkdirSync||Xbl,e};var kE=(t,e,l)=>{let I=Vnt(t),n={...wA(e),recursive:!1};if(I===t)try{return n.mkdirSync(t,n)}catch(r){let a=r;if(a&&a.code!=="EISDIR")throw r;return}try{return n.mkdirSync(t,n),l||t}catch(r){let a=r;if(a&&a.code==="ENOENT")return kE(t,n,kE(I,n,l));if(a&&a.code!=="EEXIST"&&a&&a.code!=="EROFS")throw r;try{if(!n.statSync(t).isDirectory())throw r}catch{throw r}}},Mw=Object.assign(async(t,e,l)=>{let I=wA(e);I.recursive=!1;let n=Vnt(t);return n===t?I.mkdirAsync(t,I).catch(r=>{let a=r;if(a&&a.code!=="EISDIR")throw r}):I.mkdirAsync(t,I).then(()=>l||t,async r=>{let a=r;if(a&&a.code==="ENOENT")return Mw(n,I).then(s=>Mw(t,I,s));if(a&&a.code!=="EEXIST"&&a.code!=="EROFS")throw r;return I.statAsync(t).then(s=>{if(s.isDirectory())return l;throw r},()=>{throw r})})},{sync:kE});c();import{dirname as Fnt}from"path";c();import{dirname as wnt}from"path";var Zve=async(t,e,l)=>{if(l!==e)return t.statAsync(e).then(I=>I.isDirectory()?l:void 0,I=>{let n=I;return n&&n.code==="ENOENT"?Zve(t,wnt(e),e):void 0})},Nve=(t,e,l)=>{if(l!==e)try{return t.statSync(e).isDirectory()?l:void 0}catch(I){let n=I;return n&&n.code==="ENOENT"?Nve(t,wnt(e),e):void 0}};var iT=(t,e)=>{let l=wA(e);if(l.recursive=!0,Fnt(t)===t)return l.mkdirSync(t,l);let n=Nve(l,t);try{return l.mkdirSync(t,l),n}catch(r){let a=r;if(a&&a.code==="ENOENT")return kE(t,l);throw r}},g8=Object.assign(async(t,e)=>{let l={...wA(e),recursive:!0};return Fnt(t)===t?await l.mkdirAsync(t,l):Zve(l,t).then(n=>l.mkdirAsync(t,l).then(r=>n||r).catch(r=>{let a=r;if(a&&a.code==="ENOENT")return Mw(t,l);throw r}))},{sync:iT});c();import{parse as Lbl,resolve as xbl}from"path";var kbl=process.env.__TESTING_MKDIRP_PLATFORM__||process.platform,Wve=t=>{if(/\0/.test(t))throw Object.assign(new TypeError("path must be a string without null bytes"),{path:t,code:"ERR_INVALID_ARG_VALUE"});if(t=xbl(t),kbl==="win32"){let e=/[*|"<>?:]/,{root:l}=Lbl(t);if(e.test(t.substring(l.length)))throw Object.assign(new Error("Illegal characters in path."),{path:t,code:"EINVAL"})}return t};c();import{mkdir as Sbl,mkdirSync as Bbl}from"fs";var Obl=process.env.__TESTING_MKDIRP_NODE_VERSION__||process.version,gve=Obl.replace(/^v/,"").split("."),vnt=+gve[0]>10||+gve[0]==10&&+gve[1]>=12,A8=vnt?t=>wA(t).mkdirSync===Bbl:()=>!1,kme=Object.assign(vnt?t=>wA(t).mkdir===Sbl:()=>!1,{sync:A8});var Lme=(t,e)=>{t=Wve(t);let l=wA(e);return A8(l)?iT(t,l):kE(t,l)};var Qnt=Object.assign(async(t,e)=>{t=Wve(t);let l=wA(e);return kme(l)?g8(t,l):Mw(t,l)},{mkdirpSync:Lme,mkdirpNative:g8,mkdirpNativeSync:iT,mkdirpManual:Mw,mkdirpManualSync:kE,sync:Lme,native:g8,nativeSync:iT,manual:Mw,manualSync:kE,useNative:kme,useNativeSync:A8});import xme from"node:path";c();var y8=class extends Error{path;code;syscall="chdir";constructor(e,l){super(`${l}: Cannot cd into '${e}'`),this.path=e,this.code=l}get name(){return"CwdError"}};c();var R8=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(e,l){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=e,this.path=l}get name(){return"SymlinkError"}};var Sme=(t,e)=>t.get(dr(e)),E8=(t,e,l)=>t.set(dr(e),l),Tbl=(t,e)=>{FA.stat(t,(l,I)=>{(l||!I.isDirectory())&&(l=new y8(t,l?.code||"ENOTDIR")),e(l)})},Cnt=(t,e,l)=>{t=dr(t);let I=e.umask??18,n=e.mode|448,r=(n&I)!==0,a=e.uid,s=e.gid,o=typeof a=="number"&&typeof s=="number"&&(a!==e.processUid||s!==e.processGid),d=e.preserve,G=e.unlink,u=e.cache,h=dr(e.cwd),W=(w,v)=>{w?l(w):(E8(u,t,!0),v&&o?pve(v,a,s,f=>W(f)):r?FA.chmod(t,n,l):l())};if(u&&Sme(u,t)===!0)return W();if(t===h)return Tbl(t,W);if(d)return Qnt(t,{mode:n}).then(w=>W(null,w??void 0),W);let R=dr(xme.relative(h,t)).split("/");Bme(h,R,n,u,G,h,void 0,W)},Bme=(t,e,l,I,n,r,a,s)=>{if(!e.length)return s(null,a);let o=e.shift(),d=dr(xme.resolve(t+"/"+o));if(Sme(I,d))return Bme(d,e,l,I,n,r,a,s);FA.mkdir(d,l,Hnt(d,e,l,I,n,r,a,s))},Hnt=(t,e,l,I,n,r,a,s)=>o=>{o?FA.lstat(t,(d,G)=>{if(d)d.path=d.path&&dr(d.path),s(d);else if(G.isDirectory())Bme(t,e,l,I,n,r,a,s);else if(n)FA.unlink(t,u=>{if(u)return s(u);FA.mkdir(t,l,Hnt(t,e,l,I,n,r,a,s))});else{if(G.isSymbolicLink())return s(new R8(t,t+"/"+e.join("/")));s(o)}}):(a=a||t,Bme(t,e,l,I,n,r,a,s))},Ubl=t=>{let e=!1,l;try{e=FA.statSync(t).isDirectory()}catch(I){l=I?.code}finally{if(!e)throw new y8(t,l??"ENOTDIR")}},Xnt=(t,e)=>{t=dr(t);let l=e.umask??18,I=e.mode|448,n=(I&l)!==0,r=e.uid,a=e.gid,s=typeof r=="number"&&typeof a=="number"&&(r!==e.processUid||a!==e.processGid),o=e.preserve,d=e.unlink,G=e.cache,u=dr(e.cwd),h=w=>{E8(G,t,!0),w&&s&&hve(w,r,a),n&&FA.chmodSync(t,I)};if(G&&Sme(G,t)===!0)return h();if(t===u)return Ubl(u),h();if(o)return h(Lme(t,I)??void 0);let y=dr(xme.relative(u,t)).split("/"),R;for(let w=y.shift(),v=u;w&&(v+="/"+w);w=y.shift())if(v=dr(xme.resolve(v)),!Sme(G,v))try{FA.mkdirSync(v,I),R=R||v,E8(G,v,!0)}catch{let S=FA.lstatSync(v);if(S.isDirectory()){E8(G,v,!0);continue}else if(d){FA.unlinkSync(v),FA.mkdirSync(v,I),R=R||v,E8(G,v,!0);continue}else if(S.isSymbolicLink())return new R8(v,v+"/"+y.join("/"))}return h(R)};c();var Ave=Object.create(null),{hasOwnProperty:_bl}=Object.prototype,Ome=t=>(_bl.call(Ave,t)||(Ave[t]=t.normalize("NFD")),Ave[t]);c();import{join as fnt}from"node:path";var zbl=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Mbl=zbl==="win32",Dbl=t=>t.split("/").slice(0,-1).reduce((l,I)=>{let n=l[l.length-1];return n!==void 0&&(I=fnt(n,I)),l.push(I||"/"),l},[]),Tme=class{#e=new Map;#t=new Map;#l=new Set;reserve(e,l){e=Mbl?["win32 parallelization disabled"]:e.map(n=>XE(fnt(Ome(n))).toLowerCase());let I=new Set(e.map(n=>Dbl(n)).reduce((n,r)=>n.concat(r)));this.#t.set(l,{dirs:I,paths:e});for(let n of e){let r=this.#e.get(n);r?r.push(l):this.#e.set(n,[l])}for(let n of I){let r=this.#e.get(n);if(!r)this.#e.set(n,[new Set([l])]);else{let a=r[r.length-1];a instanceof Set?a.add(l):r.push(new Set([l]))}}return this.#n(l)}#I(e){let l=this.#t.get(e);if(!l)throw new Error("function does not have any path reservations");return{paths:l.paths.map(I=>this.#e.get(I)),dirs:[...l.dirs].map(I=>this.#e.get(I))}}check(e){let{paths:l,dirs:I}=this.#I(e);return l.every(n=>n&&n[0]===e)&&I.every(n=>n&&n[0]instanceof Set&&n[0].has(e))}#n(e){return this.#l.has(e)||!this.check(e)?!1:(this.#l.add(e),e(()=>this.#r(e)),!0)}#r(e){if(!this.#l.has(e))return!1;let l=this.#t.get(e);if(!l)throw new Error("invalid reservation");let{paths:I,dirs:n}=l,r=new Set;for(let a of I){let s=this.#e.get(a);if(!s||s?.[0]!==e)continue;let o=s[1];if(!o){this.#e.delete(a);continue}if(s.shift(),typeof o=="function")r.add(o);else for(let d of o)r.add(d)}for(let a of n){let s=this.#e.get(a),o=s?.[0];if(!(!s||!(o instanceof Set)))if(o.size===1&&s.length===1){this.#e.delete(a);continue}else if(o.size===1){s.shift();let d=s[0];typeof d=="function"&&r.add(d)}else o.delete(e)}return this.#l.delete(e),r.forEach(a=>this.#n(a)),!0}};var Jnt=Symbol("onEntry"),Eve=Symbol("checkFs"),knt=Symbol("checkFs2"),zme=Symbol("pruneCache"),Yve=Symbol("isReusable"),vA=Symbol("makeFs"),Vve=Symbol("file"),wve=Symbol("directory"),Mme=Symbol("link"),Lnt=Symbol("symlink"),xnt=Symbol("hardlink"),Snt=Symbol("unsupported"),Bnt=Symbol("checkPath"),wH=Symbol("mkdir"),rp=Symbol("onError"),Ume=Symbol("pending"),Ont=Symbol("pend"),dT=Symbol("unpend"),yve=Symbol("ended"),Rve=Symbol("maybeClose"),Fve=Symbol("skip"),Y8=Symbol("doChown"),V8=Symbol("uid"),w8=Symbol("gid"),F8=Symbol("checkedCwd"),Pbl=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,v8=Pbl==="win32",Kbl=1024,qbl=(t,e)=>{if(!v8)return Ds.unlink(t,e);let l=t+".DELETE."+_nt(16).toString("hex");Ds.rename(t,l,I=>{if(I)return e(I);Ds.unlink(l,e)})},$bl=t=>{if(!v8)return Ds.unlinkSync(t);let e=t+".DELETE."+_nt(16).toString("hex");Ds.renameSync(t,e),Ds.unlinkSync(e)},Tnt=(t,e,l)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:l,Unt=t=>XE(dr(Ome(t))).toLowerCase(),eul=(t,e)=>{e=Unt(e);for(let l of t.keys()){let I=Unt(l);(I===e||I.indexOf(e+"/")===0)&&t.delete(l)}},tul=t=>{for(let e of t.keys())t.delete(e)},mT=class extends zw{[yve]=!1;[F8]=!1;[Ume]=0;reservations=new Tme;transform;writable=!0;readable=!1;dirCache;uid;gid;setOwner;preserveOwner;processGid;processUid;maxDepth;forceChown;win32;newer;keep;noMtime;preservePaths;unlink;cwd;strip;processUmask;umask;dmode;fmode;chmod;constructor(e={}){if(e.ondone=()=>{this[yve]=!0,this[Rve]()},super(e),this.transform=e.transform,this.dirCache=e.dirCache||new Map,this.chmod=!!e.chmod,typeof e.uid=="number"||typeof e.gid=="number"){if(typeof e.uid!="number"||typeof e.gid!="number")throw new TypeError("cannot set owner without number uid and gid");if(e.preserveOwner)throw new TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=e.uid,this.gid=e.gid,this.setOwner=!0}else this.uid=void 0,this.gid=void 0,this.setOwner=!1;e.preserveOwner===void 0&&typeof e.uid!="number"?this.preserveOwner=!!(process.getuid&&process.getuid()===0):this.preserveOwner=!!e.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():void 0,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():void 0,this.maxDepth=typeof e.maxDepth=="number"?e.maxDepth:Kbl,this.forceChown=e.forceChown===!0,this.win32=!!e.win32||v8,this.newer=!!e.newer,this.keep=!!e.keep,this.noMtime=!!e.noMtime,this.preservePaths=!!e.preservePaths,this.unlink=!!e.unlink,this.cwd=dr(Dw.resolve(e.cwd||process.cwd())),this.strip=Number(e.strip)||0,this.processUmask=this.chmod?typeof e.processUmask=="number"?e.processUmask:process.umask():0,this.umask=typeof e.umask=="number"?e.umask:this.processUmask,this.dmode=e.dmode||511&~this.umask,this.fmode=e.fmode||438&~this.umask,this.on("entry",l=>this[Jnt](l))}warn(e,l,I={}){return(e==="TAR_BAD_ARCHIVE"||e==="TAR_ABORT")&&(I.recoverable=!1),super.warn(e,l,I)}[Rve](){this[yve]&&this[Ume]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[Bnt](e){let l=dr(e.path),I=l.split("/");if(this.strip){if(I.length<this.strip)return!1;if(e.type==="Link"){let n=dr(String(e.linkpath)).split("/");if(n.length>=this.strip)e.linkpath=n.slice(this.strip).join("/");else return!1}I.splice(0,this.strip),e.path=I.join("/")}if(isFinite(this.maxDepth)&&I.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:e,path:l,depth:I.length,maxDepth:this.maxDepth}),!1;if(!this.preservePaths){if(I.includes("..")||v8&&/^[a-z]:\.\.$/i.test(I[0]??""))return this.warn("TAR_ENTRY_ERROR","path contains '..'",{entry:e,path:l}),!1;let[n,r]=u8(l);n&&(e.path=String(r),this.warn("TAR_ENTRY_INFO",`stripping ${n} from absolute path`,{entry:e,path:l}))}if(Dw.isAbsolute(e.path)?e.absolute=dr(Dw.resolve(e.path)):e.absolute=dr(Dw.resolve(this.cwd,e.path)),!this.preservePaths&&typeof e.absolute=="string"&&e.absolute.indexOf(this.cwd+"/")!==0&&e.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:e,path:dr(e.path),resolvedPath:e.absolute,cwd:this.cwd}),!1;if(e.absolute===this.cwd&&e.type!=="Directory"&&e.type!=="GNUDumpDir")return!1;if(this.win32){let{root:n}=Dw.win32.parse(String(e.absolute));e.absolute=n+$Fe(String(e.absolute).slice(n.length));let{root:r}=Dw.win32.parse(e.path);e.path=r+$Fe(e.path.slice(r.length))}return!0}[Jnt](e){if(!this[Bnt](e))return e.resume();switch(jbl.equal(typeof e.absolute,"string"),e.type){case"Directory":case"GNUDumpDir":e.mode&&(e.mode=e.mode|448);case"File":case"OldFile":case"ContiguousFile":case"Link":case"SymbolicLink":return this[Eve](e);case"CharacterDevice":case"BlockDevice":case"FIFO":default:return this[Snt](e)}}[rp](e,l){e.name==="CwdError"?this.emit("error",e):(this.warn("TAR_ENTRY_ERROR",e,{entry:l}),this[dT](),l.resume())}[wH](e,l,I){Cnt(dr(e),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cache:this.dirCache,cwd:this.cwd,mode:l},I)}[Y8](e){return this.forceChown||this.preserveOwner&&(typeof e.uid=="number"&&e.uid!==this.processUid||typeof e.gid=="number"&&e.gid!==this.processGid)||typeof this.uid=="number"&&this.uid!==this.processUid||typeof this.gid=="number"&&this.gid!==this.processGid}[V8](e){return Tnt(this.uid,e.uid,this.processUid)}[w8](e){return Tnt(this.gid,e.gid,this.processGid)}[Vve](e,l){let I=typeof e.mode=="number"?e.mode&4095:this.fmode,n=new Ow(String(e.absolute),{flags:bve(e.size),mode:I,autoClose:!1});n.on("error",o=>{n.fd&&Ds.close(n.fd,()=>{}),n.write=()=>!0,this[rp](o,e),l()});let r=1,a=o=>{if(o){n.fd&&Ds.close(n.fd,()=>{}),this[rp](o,e),l();return}--r===0&&n.fd!==void 0&&Ds.close(n.fd,d=>{d?this[rp](d,e):this[dT](),l()})};n.on("finish",()=>{let o=String(e.absolute),d=n.fd;if(typeof d=="number"&&e.mtime&&!this.noMtime){r++;let G=e.atime||new Date,u=e.mtime;Ds.futimes(d,G,u,h=>h?Ds.utimes(o,G,u,W=>a(W&&h)):a())}if(typeof d=="number"&&this[Y8](e)){r++;let G=this[V8](e),u=this[w8](e);typeof G=="number"&&typeof u=="number"&&Ds.fchown(d,G,u,h=>h?Ds.chown(o,G,u,W=>a(W&&h)):a())}a()});let s=this.transform&&this.transform(e)||e;s!==e&&(s.on("error",o=>{this[rp](o,e),l()}),e.pipe(s)),s.pipe(n)}[wve](e,l){let I=typeof e.mode=="number"?e.mode&4095:this.dmode;this[wH](String(e.absolute),I,n=>{if(n){this[rp](n,e),l();return}let r=1,a=()=>{--r===0&&(l(),this[dT](),e.resume())};e.mtime&&!this.noMtime&&(r++,Ds.utimes(String(e.absolute),e.atime||new Date,e.mtime,a)),this[Y8](e)&&(r++,Ds.chown(String(e.absolute),Number(this[V8](e)),Number(this[w8](e)),a)),a()})}[Snt](e){e.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${e.type}`,{entry:e}),e.resume()}[Lnt](e,l){this[Mme](e,String(e.linkpath),"symlink",l)}[xnt](e,l){let I=dr(Dw.resolve(this.cwd,String(e.linkpath)));this[Mme](e,I,"link",l)}[Ont](){this[Ume]++}[dT](){this[Ume]--,this[Rve]()}[Fve](e){this[dT](),e.resume()}[Yve](e,l){return e.type==="File"&&!this.unlink&&l.isFile()&&l.nlink<=1&&!v8}[Eve](e){this[Ont]();let l=[e.path];e.linkpath&&l.push(e.linkpath),this.reservations.reserve(l,I=>this[knt](e,I))}[zme](e){e.type==="SymbolicLink"?tul(this.dirCache):e.type!=="Directory"&&eul(this.dirCache,String(e.absolute))}[knt](e,l){this[zme](e);let I=s=>{this[zme](e),l(s)},n=()=>{this[wH](this.cwd,this.dmode,s=>{if(s){this[rp](s,e),I();return}this[F8]=!0,r()})},r=()=>{if(e.absolute!==this.cwd){let s=dr(Dw.dirname(String(e.absolute)));if(s!==this.cwd)return this[wH](s,this.dmode,o=>{if(o){this[rp](o,e),I();return}a()})}a()},a=()=>{Ds.lstat(String(e.absolute),(s,o)=>{if(o&&(this.keep||this.newer&&o.mtime>(e.mtime??o.mtime))){this[Fve](e),I();return}if(s||this[Yve](e,o))return this[vA](null,e,I);if(o.isDirectory()){if(e.type==="Directory"){let d=this.chmod&&e.mode&&(o.mode&4095)!==e.mode,G=u=>this[vA](u??null,e,I);return d?Ds.chmod(String(e.absolute),Number(e.mode),G):G()}if(e.absolute!==this.cwd)return Ds.rmdir(String(e.absolute),d=>this[vA](d??null,e,I))}if(e.absolute===this.cwd)return this[vA](null,e,I);qbl(String(e.absolute),d=>this[vA](d??null,e,I))})};this[F8]?r():n()}[vA](e,l,I){if(e){this[rp](e,l),I();return}switch(l.type){case"File":case"OldFile":case"ContiguousFile":return this[Vve](l,I);case"Link":return this[xnt](l,I);case"SymbolicLink":return this[Lnt](l,I);case"Directory":case"GNUDumpDir":return this[wve](l,I)}}[Mme](e,l,I,n){Ds[I](l,String(e.absolute),r=>{r?this[rp](r,e):(this[dT](),e.resume()),n()})}},_me=t=>{try{return[null,t()]}catch(e){return[e,null]}},Q8=class extends mT{sync=!0;[vA](e,l){return super[vA](e,l,()=>{})}[Eve](e){if(this[zme](e),!this[F8]){let r=this[wH](this.cwd,this.dmode);if(r)return this[rp](r,e);this[F8]=!0}if(e.absolute!==this.cwd){let r=dr(Dw.dirname(String(e.absolute)));if(r!==this.cwd){let a=this[wH](r,this.dmode);if(a)return this[rp](a,e)}}let[l,I]=_me(()=>Ds.lstatSync(String(e.absolute)));if(I&&(this.keep||this.newer&&I.mtime>(e.mtime??I.mtime)))return this[Fve](e);if(l||this[Yve](e,I))return this[vA](null,e);if(I.isDirectory()){if(e.type==="Directory"){let a=this.chmod&&e.mode&&(I.mode&4095)!==e.mode,[s]=a?_me(()=>{Ds.chmodSync(String(e.absolute),Number(e.mode))}):[];return this[vA](s,e)}let[r]=_me(()=>Ds.rmdirSync(String(e.absolute)));this[vA](r,e)}let[n]=e.absolute===this.cwd?[]:_me(()=>$bl(String(e.absolute)));this[vA](n,e)}[Vve](e,l){let I=typeof e.mode=="number"?e.mode&4095:this.fmode,n=s=>{let o;try{Ds.closeSync(r)}catch(d){o=d}(s||o)&&this[rp](s||o,e),l()},r;try{r=Ds.openSync(String(e.absolute),bve(e.size),I)}catch(s){return n(s)}let a=this.transform&&this.transform(e)||e;a!==e&&(a.on("error",s=>this[rp](s,e)),e.pipe(a)),a.on("data",s=>{try{Ds.writeSync(r,s,0,s.length)}catch(o){n(o)}}),a.on("end",()=>{let s=null;if(e.mtime&&!this.noMtime){let o=e.atime||new Date,d=e.mtime;try{Ds.futimesSync(r,o,d)}catch(G){try{Ds.utimesSync(String(e.absolute),o,d)}catch{s=G}}}if(this[Y8](e)){let o=this[V8](e),d=this[w8](e);try{Ds.fchownSync(r,Number(o),Number(d))}catch(G){try{Ds.chownSync(String(e.absolute),Number(o),Number(d))}catch{s=s||G}}}n(s)})}[wve](e,l){let I=typeof e.mode=="number"?e.mode&4095:this.dmode,n=this[wH](String(e.absolute),I);if(n){this[rp](n,e),l();return}if(e.mtime&&!this.noMtime)try{Ds.utimesSync(String(e.absolute),e.atime||new Date,e.mtime)}catch{}if(this[Y8](e))try{Ds.chownSync(String(e.absolute),Number(this[V8](e)),Number(this[w8](e)))}catch{}l(),e.resume()}[wH](e,l){try{return Xnt(dr(e),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cache:this.dirCache,cwd:this.cwd,mode:l})}catch(I){return I}}[Mme](e,l,I,n){let r=`${I}Sync`;try{Ds[r](l,String(e.absolute)),n(),e.resume()}catch(a){return this[rp](a,e)}}};var lul=t=>{let e=new Q8(t),l=t.file,I=znt.statSync(l),n=t.maxReadSize||16*1024*1024;new ame(l,{readSize:n,size:I.size}).pipe(e)},Iul=(t,e)=>{let l=new mT(t),I=t.maxReadSize||16*1024*1024,n=t.file;return new Promise((a,s)=>{l.on("error",s),l.on("close",a),znt.stat(n,(o,d)=>{if(o)s(o);else{let G=new gk(n,{readSize:I,size:d.size});G.on("error",s),G.pipe(l)}})})},vve=CE(lul,Iul,t=>new Q8(t),t=>new mT(t),(t,e)=>{e?.length&&PFe(t,e)});c();import SW from"node:fs";import Mnt from"node:path";var nul=(t,e)=>{let l=new Ck(t),I=!0,n,r;try{try{n=SW.openSync(t.file,"r+")}catch(o){if(o?.code==="ENOENT")n=SW.openSync(t.file,"w+");else throw o}let a=SW.fstatSync(n),s=Buffer.alloc(512);e:for(r=0;r<a.size;r+=512){for(let G=0,u=0;G<512;G+=u){if(u=SW.readSync(n,s,G,s.length-G,r+G),r===0&&s[0]===31&&s[1]===139)throw new Error("cannot append to compressed archives");if(!u)break e}let o=new xW(s);if(!o.cksumValid)break;let d=512*Math.ceil((o.size||0)/512);if(r+d+512>a.size)break;r+=d,t.mtimeCache&&o.mtime&&t.mtimeCache.set(String(o.path),o.mtime)}I=!1,rul(t,l,r,n,e)}finally{if(I)try{SW.closeSync(n)}catch{}}},rul=(t,e,l,I,n)=>{let r=new lT(t.file,{fd:I,start:l});e.pipe(r),sul(e,n)},aul=(t,e)=>{e=Array.from(e);let l=new VH(t),I=(r,a,s)=>{let o=(W,y)=>{W?SW.close(r,R=>s(W)):s(null,y)},d=0;if(a===0)return o(null,0);let G=0,u=Buffer.alloc(512),h=(W,y)=>{if(W||typeof y>"u")return o(W);if(G+=y,G<512&&y)return SW.read(r,u,G,u.length-G,d+G,h);if(d===0&&u[0]===31&&u[1]===139)return o(new Error("cannot append to compressed archives"));if(G<512)return o(null,d);let R=new xW(u);if(!R.cksumValid)return o(null,d);let w=512*Math.ceil((R.size??0)/512);if(d+w+512>a||(d+=w+512,d>=a))return o(null,d);t.mtimeCache&&R.mtime&&t.mtimeCache.set(String(R.path),R.mtime),G=0,SW.read(r,u,0,512,d,h)};SW.read(r,u,0,512,d,h)};return new Promise((r,a)=>{l.on("error",a);let s="r+",o=(d,G)=>{if(d&&d.code==="ENOENT"&&s==="r+")return s="w+",SW.open(t.file,s,o);if(d||!G)return a(d);SW.fstat(G,(u,h)=>{if(u)return SW.close(G,()=>a(u));I(G,h.size,(W,y)=>{if(W)return a(W);let R=new Ow(t.file,{fd:G,start:y});l.pipe(R),R.on("error",a),R.on("close",r),oul(l,e)})})};SW.open(t.file,s,o)})},sul=(t,e)=>{e.forEach(l=>{l.charAt(0)==="@"?vk({file:Mnt.resolve(t.cwd,l.slice(1)),sync:!0,noResume:!0,onReadEntry:I=>t.add(I)}):t.add(l)}),t.end()},oul=async(t,e)=>{for(let l=0;l<e.length;l++){let I=String(e[l]);I.charAt(0)==="@"?await vk({file:Mnt.resolve(String(t.cwd),I.slice(1)),noResume:!0,onReadEntry:n=>t.add(n)}):t.add(I)}t.end()},Hk=CE(nul,aul,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!DIt(t))throw new TypeError("file is required");if(t.gzip||t.brotli||t.file.endsWith(".br")||t.file.endsWith(".tbr"))throw new TypeError("cannot append to compressed archives");if(!e?.length)throw new TypeError("no paths specified to add/replace")});c();var cul=CE(Hk.syncFile,Hk.asyncFile,Hk.syncNoFile,Hk.asyncNoFile,(t,e=[])=>{Hk.validate?.(t,e),iul(t)}),iul=t=>{let e=t.filter;t.mtimeCache||(t.mtimeCache=new Map),t.filter=e?(l,I)=>e(l,I)&&!((t.mtimeCache?.get(l)??I.mtime??0)>(I.mtime??0)):(l,I)=>!((t.mtimeCache?.get(l)??I.mtime??0)>(I.mtime??0))};var nGe=Gt(Grt(),1);c();import*as grt from"child_process";import*as Art from"fs";c();import*as hrt from"fs";c();import brt from"path";function urt(t,e){return[...(t.locations||[]).map(I=>I.physicalLocation),...(t.relatedLocations||[]).map(I=>I.physicalLocation)].some(I=>{let n=I?.artifactLocation?.uri,r=I?.region?.startLine;if(!n||r===void 0)return!1;let a=n.replaceAll(brt.sep,"/");return e.some(s=>s.path===a&&(s.startLine<=r&&s.endLine>=r||s.startLine===0&&s.endLine===0))})}function prt(t){let e=t.map(({path:l})=>l).filter(l=>!wpl(l)).map(l=>Vpl(l)).reduce((l,I)=>(I&&l.add(I),l),new Set);return Array.from(e)}function Vpl(t){switch(brt.extname(t)){case".js":case".jsx":case".ts":case".tsx":return"javascript";case".py":return"python";case".rb":case".erb":return"ruby";case".go":return"go";case".java":return"java";case".cs":return"csharp";case".cpp":case".cc":case".cxx":case".c":case".h":case".hpp":case".hh":case".hxx":return"cpp";case".rs":return"rust";case".swift":return"swift";default:return}}function wpl(t){return t.includes("node_modules/")||t.includes("dist/")||t.includes("target/")||t.includes("vendor/")}var _ve="<unknown>",tGe=class{constructor(e,l){this.sarifPath=e;this.logProgress=l}async summarize(e,l){let I=await hrt.promises.readFile(this.sarifPath,"utf-8"),n=JSON.parse(I);if(!n.runs||n.runs.length===0)return{language:e,alerts:[]};let r=n.runs.flatMap(a=>{if(a.results!==void 0)return a.results.filter(s=>urt(s,l)?!0:(this.logProgress(`CodeQL checker filtered out '${s.ruleId}' alert at the following location since it was outside the diff: ${JSON.stringify(s.locations)}`),!1)).map(s=>({ruleId:s.ruleId,message:s.message.text??_ve,description:Fpl(s.ruleId,n),locations:s.locations?.map(o=>({uri:o.physicalLocation?.artifactLocation?.uri??"",region:o.physicalLocation?.region}))??[]}))}).filter(a=>!!a);return{language:e,alerts:r}}};function Fpl(t,e){return t?e.runs?.flatMap(I=>I.tool?.driver?.rules).find(I=>I&&I.id===t)?.fullDescription?.text??_ve:_ve}c();import*as k8 from"os";import*as lGe from"fs";var vpl=.05,Zrt=1024*1024;function Nrt(t){let e=k8.platform(),l=Cpl(e,t)/(1024*1024),I=Qpl(l,e),n=Math.floor(l-I);return t(`Using ${n} MB for CodeQL, out of ${l} MB total.`,8),n}function Qpl(t,e){let l=1024*(e==="win32"?1.5:1),I=vpl*Math.max(t-8*1024,0);return l+I}function Cpl(t,e){let l=[k8.totalmem()];return t==="linux"&&l.push(...["/sys/fs/cgroup/memory/memory.limit_in_bytes","/sys/fs/cgroup/memory.max"].map(n=>Hpl(n,e)).filter(n=>n!==void 0).map(n=>n)),Math.min(...l)}function Hpl(t,e){if(!lGe.existsSync(t)){e(`While resolving RAM, did not find a cgroup memory limit at ${t}.`,8);return}let l=Number(lGe.readFileSync(t,"utf8"));if(!Number.isInteger(l)){e(`While resolving RAM, ignored the file ${t} that may contain a cgroup memory limit as this file did not contain an integer.`,8);return}let I=`${Math.floor(l/(1024*1024))} MiB`;if(l>k8.totalmem()){e(`While resolving RAM, ignored the file ${t} that may contain a cgroup memory limit as its contents ${I} were greater than the total amount of system memory.`,8);return}if(l<Zrt){e(`While resolving RAM, ignored a cgroup limit of ${I} in ${t} as it was below ${Zrt/(1024*1024)} MiB.`,8);return}return e(`While resolving RAM, found a cgroup limit of ${I} in ${t}.`,8),l}c();import*as pT from"fs";import*as IGe from"os";function Wrt(t){let e=[IGe.cpus().length];return IGe.platform()==="linux"&&(e.push(...["/sys/fs/cgroup/cpuset.cpus.effective","/sys/fs/cgroup/cpuset.cpus"].map(I=>fpl(I,t)).filter(I=>I!==void 0&&I>0).map(I=>I)),e.push(...["/sys/fs/cgroup/cpu.max"].map(I=>Xpl(I,t)).filter(I=>I!==void 0&&I>0).map(I=>I))),Math.min(...e)}function Xpl(t,e){if(!pT.existsSync(t)){e(`While resolving threads, did not find a cgroup CPU file at ${t}.`,8);return}let I=pT.readFileSync(t,"utf-8").split(" ");if(I.length!==2){e(`While resolving threads, did not use cgroup CPU file at ${t} because it contained ${I.length} value(s) rather than the two expected.`,8);return}let n=I[0];if(n==="max")return;let r=I[1],a=Math.floor(parseInt(n)/parseInt(r));return e(`While resolving threads, found a cgroup CPU file with ${a} CPUs in ${t}.`,8),a}function fpl(t,e){if(!pT.existsSync(t)){e(`While resolving threads, did not find a cgroup CPUs file at ${t}.`,8);return}let l=0,I=pT.readFileSync(t,"utf-8").trim();if(I.length!==0){for(let n of I.split(","))if(!n.includes("-"))++l;else{let r=parseInt(n.split("-")[0]),a=parseInt(n.split("-")[1]);l+=a-r+1}return e(`While resolving threads, found a cgroup CPUs file with ${l} CPUs in ${t}.`,8),l}}var hT=class t{constructor(e,l,I){this.executablePath=e;this.databaseDir=l;this.progressLogger=I;this.ram=this.resolveRam(),this.threads=this.resolveThreads()}ram;threads;async createDatabase(e,l){let I=`${this.databaseDir}/${e}`,n=this.getBuildMode(e);return await this.execCommand(`database create ${this.ram} ${this.threads} --no-sublanguage-file-coverage --no-calculate-baseline --overwrite --language ${e} --build-mode ${n} --source-root ${l} ${I}`),I}static AUTOBUILD_ONLY_LANGUAGES=["cpp","go","swift"];getBuildMode(e){return t.AUTOBUILD_ONLY_LANGUAGES.includes(e)?"autobuild":"none"}async analyzeDatabase(e,l){let I=`${this.databaseDir}/${e}`,n=`${I}/results-${e}.json`;return await Art.promises.rm(n,{force:!0}),this.progressLogger(`Analyzing database at ${I} for language ${e}`),await this.execCommand(`database analyze ${this.ram} ${this.threads} --format sarifv2.1.0 --output ${n} ${I} codeql/${e}-queries`),new tGe(n,this.progressLogger.bind(this)).summarize(e,l)}async version(){let e=await this.execCommand("version --format json");try{return JSON.parse(e).version}catch{throw new Error(`Failed to parse CodeQL version output: ${e}`)}}async execCommand(e){return this.progressLogger(`Executing CodeQL command: ${e}`),new Promise((l,I)=>{grt.exec(`${this.executablePath} ${e}`,(n,r,a)=>{let s=n?1:4;this.progressLogger(a,s,"CodeQL Output"),n?I("Error executing command."):l(r)})})}resolveRam(){try{return`--ram ${Nrt(this.progressLogger)}`}catch(e){return this.progressLogger(`Failed to resolve RAM, not passing --ram flag to CodeQL: ${e}`,2),""}}resolveThreads(){try{return`--threads ${Wrt(this.progressLogger)}`}catch(e){return this.progressLogger(`Failed to resolve threads, not passing --threads flag to CodeQL: ${e}`,2),""}}};var Rrt="codeql-bundle-linux64.tar.gz",Lpl=new TO;async function xpl(t,e){let n=(await new jO({auth:t}).rest.repos.getLatestRelease({owner:"github",repo:"codeql-action"})).data.assets.find(r=>r.name===Rrt);if(n)return e(`CodeQL asset ID: ${n.id}`),n.id;throw new Error("CodeQL asset not found")}async function Spl(t,e,l,I){let n=await fetch(`https://api.github.com/repos/github/codeql-action/releases/assets/${t}`,{headers:{Authorization:`token ${l}`,Accept:"application/octet-stream"},redirect:"follow"});if(!n.ok||!n.body)throw new Error(`Failed to download asset: ${n.statusText}`);let r=ZT.join(e,Rrt),a=xE.createWriteStream(r,{flags:"wx"});return await Jpl(kpl.fromWeb(n.body).pipe(a)),I(`CodeQL downloaded to ${r}`),r}async function Bpl(t,e,l){await xE.promises.mkdir(e,{recursive:!0});try{return await vve({file:t,cwd:e}),l(`CodeQL unzipped to ${e}`),Vrt(e)}catch(I){throw Lpl.error(`Error unzipping CodeQL: ${String(I)}`),I}}async function Opl(t,e,l){let I=process.env.GITHUB_TOKEN||Cw(l),n=await xpl(I,e),r=Tpl(t);await xE.promises.mkdir(r,{recursive:!0});let a=await Spl(n,r,I,e);return await Bpl(a,t,e),await xE.promises.rm(a),Yrt(t)}async function Ert(t,e,l){let I=Upl(t);await xE.promises.mkdir(I,{recursive:!0});let n=await _pl(l);if(n)return new hT(n,I,l);let r=Yrt(t);if(await zve(r))return l(`CodeQL already exists at ${r}`),new hT(r,I,l);try{let a=await Opl(t,l,e);return new hT(a,I,l)}catch(a){throw l(`Error ensuring CodeQL: ${String(a)}`,1),a}}function Tpl(t){return ZT.join(t,"codeql-download")}function Yrt(t){return ZT.join(Vrt(t),"codeql")}function Vrt(t){return ZT.join(t,"codeql")}function Upl(t){return ZT.join(t,"dbs")}async function _pl(t){if(!process.env.RUNNER_TOOL_CACHE)return;let e=nGe.findAllVersions("CodeQL");if(!e.length)return;let l=e[0],I=nGe.find("CodeQL",l,yrt.arch());if(I){let n=ZT.join(I,"codeql","codeql");if(t(`CodeQL directory found in toolcache at '${I}'.`),!await zve(n)){let r;throw await zve(I)?r=xE.readdirSync(I):r=["path does not exist"],new Error(`CodeQL executable not found at '${n}'. Contents of toolcache: '${r.join(", ")}'.`)}return n}}async function zve(t){try{return await xE.promises.stat(t),!0}catch{return!1}}import wrt from"path";var zpl={cpp:["C++"],csharp:["C#"],go:["Go"],java:["Java"],javascript:["JavaScript","TypeScript","TSX","JSX"],python:["Python"],ruby:["Ruby"],rust:["Rust"],swift:["Swift"]},rGe=class t{constructor(e,l,I,n,r){this.config=e;this.git=l;this.baseCommit=I;this.settings=n;this.logger=r}static DEFAULT_MAX_REPO_SIZE_BYTES=1e7;static TOOL_NAME="codeql_checker";static CODEQL_CHECKER_ENABLED_FF="copilot_swe_agent_enable_security_tool";static CODEQL_CHECKER_DISABLED_FF="copilot_swe_agent_enable_security_tool_disabled";static isEnabled(e){return lc(e,t.CODEQL_CHECKER_ENABLED_FF)&&!lc(e,t.CODEQL_CHECKER_DISABLED_FF)}repoSizes;getCodeQLCheckerTool(){return{name:t.TOOL_NAME,description:`This is a security tool that discovers vulnerabilities in code using CodeQL. It must always be run when there are code changes.
543
543
  It is run after committing all changed code and before the final verification. Feedback from this tool must be incorporated into
544
544
  the change and then the tool must be re-run.`,input_schema:{type:"object",properties:{}},callback:this.callback.bind(this),safeForTelemetry:!0}}async callback(){let e={},l="unknown",I=Date.now();try{let n=await this.createCodeQLScratchDir(this.config.location),r=await Ert(n,this.settings,this.logProgress.bind(this));l=await r.version(),await this.git.stageChanges(this.config.location);let a=await this.git.getDiffRanges(this.config.location,this.baseCommit),s=prt(a);s.length>0?this.logProgress(`Found ${s.join(", ")} languages to analyze.`):this.logProgress("No languages found to analyze.");let o=[],d=!0;for(let u of s){if(!await this.shouldAnalyzeLanguage(u)){e[u]={databaseCreationError:`Did not build database for ${u} due to repo size.`,databaseCreationSuccess:!1,databaseCreationTimeMs:0};continue}let h=Date.now();try{await r.createDatabase(u,this.config.location),this.logProgress(`Created database for ${u}.`),e[u]={databaseCreationSuccess:!0,databaseCreationTimeMs:Date.now()-h}}catch(y){d=!1;let R=`Error creating database for ${u}: ${String(y)}`;this.logProgress(R,1),e[u]={databaseCreationError:R,databaseCreationSuccess:!1,databaseCreationTimeMs:Date.now()-h};continue}let W=Date.now();try{let y=await r.analyzeDatabase(u,a);o.push(y);let R=y.alerts.length;this.logProgress(`Completed analysis of ${u}. ${R} ${R===1?"alert":"alerts"} found.`),e[u]={...e[u],analysisSuccess:!0,analysisTimeMs:Date.now()-W,analysisRuleIds:y.alerts.flatMap(w=>w.ruleId?[w.ruleId]:[]),querySuite:`${u}-code-scanning`}}catch(y){d=!1;let R=`Error analyzing database for ${u}: ${String(y)}`;this.logProgress(R,1),e[u]={...e[u],analysisError:R,analysisSuccess:!1,analysisTimeMs:Date.now()-W,analysisRuleIds:[]}}}let G=o.filter(u=>u.alerts.length>0).reduce((u,h)=>u+h.alerts.length,0);return{resultType:d?"success":"failure",textResultForLlm:`Analysis Result for '${s}'. Found ${G} alert(s): ${JSON.stringify(o,null,2)}`,sessionLog:`<info>Analysis completed successfully for '${s}'.</info>`,toolTelemetry:{properties:{"codeql.version":l},metrics:{"codeql.languages.count":s.length,"codeql.total.alerts":G,"codeql.total.duration.ms":Date.now()-I}}}}catch(n){let r=`Error in CodeQL Checker: '${String(n)}'`;return this.logProgress(r,1),{resultType:"failure",textResultForLlm:r,sessionLog:`<error>${r}</error>`,toolTelemetry:{properties:{"codeql.version":l},metrics:{"codeql.languages.count":0,"codeql.total.alerts":0,"codeql.checker.duration.ms":Date.now()-I}}}}finally{let n=this.createTelemetryByLanguage(e,l);for(let r of n)this.config.callback?.progress({kind:"telemetry",telemetry:r})}}async logProgress(e,l=4,I){switch(I&&this.logger.startGroup(I),l){case 8:this.logger.debug(e);break;case 4:this.logger.info(e);break;case 2:this.logger.warning(e);break;case 1:this.logger.error(e);break;default:this.logger.log(e);break}I&&this.logger.endGroup(),this.config.callback&&await this.config.callback?.progress({kind:"log",message:e})}async createCodeQLScratchDir(e){let l=wrt.normalize(wrt.join(e,"..",".codeql-scratch"));return await Frt.promises.mkdir(l,{recursive:!0}),l}createTelemetryByLanguage(e,l){let I=[];for(let[n,r]of Object.entries(e))I.push({event:"codeql-checker-completion",properties:{"codeql.language":n,"codeql.databaseCreationSuccess":String(r.databaseCreationSuccess),"codeql.analysisSuccess":NT(r)?String(r.analysisSuccess):void 0,"codeql.analysisRuleIds":NT(r)?r.analysisRuleIds.join(","):"","codeql.version":l,"codeql.querySuite":NT(r)?r.querySuite:void 0},metrics:{"codeql.databaseCreationTimeMs":r.databaseCreationTimeMs,"codeql.analysisTimeMs":NT(r)?r.analysisTimeMs:void 0,"codeql.alertCount":NT(r)?r.analysisRuleIds.length:0},restrictedProperties:{"codeql.language":n,"codeql.databaseCreationError":r.databaseCreationError??void 0,"codeql.analysisError":NT(r)?r.analysisError??void 0:void 0}});return I}async shouldAnalyzeLanguage(e){if(this.repoSizes||(this.repoSizes=await this.requestSize()),!this.repoSizes)return!0;let l=zpl[e];if(!l||l.length===0)return!0;let I=l.map(r=>this.repoSizes?this.repoSizes[r]??0:0).reduce((r,a)=>r+a,0),n=I<t.DEFAULT_MAX_REPO_SIZE_BYTES;return n||this.logProgress(`Skipping analysis for ${e} because the repository size is ${I} bytes, which exceeds the limit of ${t.DEFAULT_MAX_REPO_SIZE_BYTES} bytes.`,2),n}async requestSize(){try{let e=new jO({userAgent:t.TOOL_NAME,auth:Cw(this.settings)}),l=this.settings.github?.repo,I=this.settings.github?.owner;if(!l?.name||!I?.name)throw new Error("GitHub repository name and owner are required to check repository size.");let n=await e.request("GET /repos/{owner}/{repo}/languages",{owner:I.name,repo:l.name,headers:{"X-GitHub-Api-Version":"2022-11-28"}});if(n.status!==200)throw new Error(`Failed to get repository languages: ${n.status} ${n.data}`);return n.data}catch(e){this.logProgress(`Failed to get repository size: ${String(e)}`,2)}}};function NT(t){return"analysisSuccess"in t}c();var Mpl="gh-advisory-database",Qrt="copilot_swe_agent_validation_agent_dependencies",Dpl="security agent",Crt={name:Mpl,description:"Security tool that checks the GitHub advisory DB and informs you about reported vulnerabilities in dependencies. Run this tool ALWAYS before you add new dependencies, to check if they contain vulnerabilities. This is NOT optional. If you don't know the version number you are going to install, retrieve that first. Feedback from this tool MUST be incorporated. Re-run the tool as appropriate.",input_schema:{type:"object",properties:{dependencies:{type:"array",items:{type:"object",properties:{version:{type:"string",description:"The version of the dependency in semver format. Examples: '1.0.0', '2.1.0'."},name:{type:"string",description:"The name of the dependency. Examples: 'express', 'lodash'."}},required:["name","version"]}}},required:["dependencies"]},callback:jpl,safeForTelemetry:{name:!0,inputsNames:!1}};async function jpl({dependencies:t},e){if(!t||t.length===0)return{textResultForLlm:"No dependencies provided for checking.",resultType:"success",sessionLog:"No dependencies provided for checking.",toolTelemetry:{}};let l=[];for(let I of t){let n=qpl(I);if(n)return Promise.resolve(n);try{let r=e?Cw(e.settings):process.env.GH_TOKEN;if(!r){let s="GitHub token is required to use the dependency checker tool. Please set it in the settings or as the GH_TOKEN environment variable.";return{textResultForLlm:s,resultType:"failure",sessionLog:s,toolTelemetry:{properties:{error:s}}}}let a=new jO({userAgent:Dpl,auth:r});l.push(...await Ppl(a,I))}catch(r){let a=`Error checking dependency ${I.name}: ${String(r)}`,s=r instanceof Error?r.stack:void 0;return{textResultForLlm:a,resultType:"failure",sessionLog:a,toolTelemetry:{restrictedProperties:{dep:`${I.name}@${I.version}`,error:a,stackTrace:s}}}}}if(l.length===0)return{textResultForLlm:"No vulnerabilities found in the provided dependencies.",resultType:"success",sessionLog:"No vulnerabilities found in the provided dependencies.",toolTelemetry:{}};{let I=Kpl(l);return{textResultForLlm:I,resultType:"success",sessionLog:I,toolTelemetry:{restrictedProperties:{vulnerableDeps:l.map(n=>`${n.name}@${n.version}`).join(", ")},metrics:{vulnerableDependencies:l.length}}}}}async function Ppl(t,e){let l=await t.securityAdvisories.listGlobalAdvisories({affects:`${e.name}@${e.version}`,severity:"high"}),I=await t.securityAdvisories.listGlobalAdvisories({affects:`${e.name}@${e.version}`,severity:"critical"}),n=await t.securityAdvisories.listGlobalAdvisories({affects:`${e.name}@${e.version}`,type:"malware"}),r=[...l.data,...I.data,...n.data];return r.length===0?[]:r.flatMap(a=>a.vulnerabilities?.map(s=>({name:e.name,version:e.version,summary:a.summary,ecosystem:s.package.ecosystem,affectedVersions:s.vulnerable_version_range??"",patchedVersion:s.first_patched_version??"not available",severity:a.severity,type:a.type}))??[])}function Kpl(t){return t.map(e=>{let l=e.type==="malware"?"is malware":"has a vulnerability";return`Dependency ${e.name} version ${e.version} in ecosystem ${e.ecosystem} ${l}: ${e.summary}. Affected versions: ${e.affectedVersions}. Patched version: ${e.patchedVersion}.`}).join(`
545
+
545
546
  `)}function vrt(t){if(typeof t!="string"||t.trim()==="")return"parameter must be a non-empty string."}function qpl(t){let e=[],l=vrt(t.name);l&&e.push(`name: ${l}`);let I=vrt(t.version);if(I&&e.push(`version: ${I}`),e.length>0){let n=`Invalid parameters found for dependency ${t.name}: ${e.join(", ")}`;return{textResultForLlm:n,resultType:"failure",sessionLog:n,toolTelemetry:{}}}}c();var Hrt="reply_to_comment",Xrt=(t,e)=>({name:Hrt,description:`Reply to new comments. Use when you've completed a meaningful unit of work that specifically addresses the request, question, or feedback in the comment.
546
547
  * Use this tool no more than once per <comment_id>, and only after you have completed meaningful work that specifically addresses the text in the comment.
547
548
  * Ignore comments with no comment_id. Do not make up comment_ids.
@@ -1429,7 +1430,7 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
1429
1430
  Body doesn't contain an array property with name: ${e}`);return l??[]}function SOl(t,e){if(!e.includes(t.status))throw Yp(`Pagination failed with unexpected statusCode ${t.status}`,t)}c();function UD(t,e,l){return(e??l==="+")||l==="#"?OEt(t):TEt(t)}function OEt(t){return t.split(/(%[0-9A-Fa-f]{2})/g).map(e=>/%[0-9A-Fa-f]/.test(e)?e:encodeURI(e)).join("")}function TEt(t){return encodeURIComponent(t).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function zne(t){return t!=null}function H3e(t){return[!!t&&[";","?","&"].includes(t),t&&["?","&"].includes(t)?"=":""]}function nWe(t,e=!1){return e?!t||t==="+"?"":t:!t||t==="+"||t==="#"?",":t==="?"?"&":t}function BOl(t){let e=t.isFirst,{op:l,varName:I,varValue:n,reserved:r}=t,a=[],[s,o]=H3e(l);if(Array.isArray(n))for(let d of n.filter(zne))a.push(`${nWe(l,e)}`),s&&I&&(a.push(`${encodeURIComponent(I)}`),d===""?a.push(o):a.push("=")),a.push(UD(d,r,l)),e=!1;else if(typeof n=="object")for(let d of Object.keys(n)){let G=n[d];zne(G)&&(a.push(`${nWe(l,e)}`),d&&(a.push(`${encodeURIComponent(d)}`),s&&G===""?a.push(o):a.push("=")),a.push(UD(G,r,l)),e=!1)}return a.join("")}function OOl(t){let{op:e,varName:l,varValue:I,isFirst:n,reserved:r}=t,a=[],s=nWe(e,n),[o,d]=H3e(e);if(o&&l){if(a.push(UD(l,r,e)),I==="")return d||a.push(d),a.join("")?`${s}${a.join("")}`:void 0;a.push("=")}let G=[];if(Array.isArray(I))for(let u of I.filter(zne))G.push(UD(u,r,e));else if(typeof I=="object")for(let u of Object.keys(I))zne(I[u])&&(G.push(TEt(u)),G.push(UD(I[u],r,e)));return a.push(G.join(",")),a.join(",")?`${s}${a.join("")}`:void 0}function TOl(t){let{op:e,varName:l,modifier:I,isFirst:n,reserved:r,varValue:a}=t;if(zne(a))if(["string","number","boolean"].includes(typeof a)){let s=a.toString(),[o,d]=H3e(e),G=[nWe(e,n)];return o&&l&&(G.push(l),s===""?G.push(d):G.push("=")),I&&I!=="*"&&(s=s.substring(0,parseInt(I,10))),G.push(UD(s,r,e)),G.join("")}else return I==="*"?BOl(t):OOl(t);else return}function Vg(t,e,l){return t.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g,(I,n,r)=>{if(!n)return OEt(r);let a;["+","#",".","/",";","?","&"].includes(n[0])&&(a=n[0],n=n.slice(1));let s=n.split(/,/g),o=[];for(let d of s){let G=/([^:\*]*)(?::(\d+)|(\*))?/.exec(d);if(!G||!G[1])continue;let u=TOl({isFirst:o.length===0,op:a,varValue:e[G[1]],varName:G[1],modifier:G[2]||G[3],reserved:l?.allowReserved});u&&o.push(u)}return o.join("")})}function UOl(t,e,l={requestOptions:{}}){var I,n;let r=Vg("/secrets/restore{?api%2Dversion}",{"api%2Dversion":t.apiVersion},{allowReserved:(I=l?.requestOptions)===null||I===void 0?void 0:I.skipUrlEncoding});return t.path(r).post(Object.assign(Object.assign({},VN(l)),{contentType:"application/json",headers:Object.assign({accept:"application/json"},(n=l.requestOptions)===null||n===void 0?void 0:n.headers),body:BEt(e)}))}async function _Ol(t){if(!["200"].includes(t.status)){let l=Yp(t);throw l.details=Yg(t.body),l}return TD(t.body)}async function X3e(t,e,l={requestOptions:{}}){let I=await UOl(t,e,l);return _Ol(I)}function zOl(t,e,l={requestOptions:{}}){var I,n;let r=Vg("/secrets/{secret-name}/backup{?api%2Dversion}",{"secret-name":e,"api%2Dversion":t.apiVersion},{allowReserved:(I=l?.requestOptions)===null||I===void 0?void 0:I.skipUrlEncoding});return t.path(r).post(Object.assign(Object.assign({},VN(l)),{headers:Object.assign({accept:"application/json"},(n=l.requestOptions)===null||n===void 0?void 0:n.headers)}))}async function MOl(t){if(!["200"].includes(t.status)){let l=Yp(t);throw l.details=Yg(t.body),l}return SEt(t.body)}async function f3e(t,e,l={requestOptions:{}}){let I=await zOl(t,e,l);return MOl(I)}function DOl(t,e,l={requestOptions:{}}){var I,n;let r=Vg("/deletedsecrets/{secret-name}/recover{?api%2Dversion}",{"secret-name":e,"api%2Dversion":t.apiVersion},{allowReserved:(I=l?.requestOptions)===null||I===void 0?void 0:I.skipUrlEncoding});return t.path(r).post(Object.assign(Object.assign({},VN(l)),{headers:Object.assign({accept:"application/json"},(n=l.requestOptions)===null||n===void 0?void 0:n.headers)}))}async function jOl(t){if(!["200"].includes(t.status)){let l=Yp(t);throw l.details=Yg(t.body),l}return TD(t.body)}async function J3e(t,e,l={requestOptions:{}}){let I=await DOl(t,e,l);return jOl(I)}function POl(t,e,l={requestOptions:{}}){var I,n;let r=Vg("/deletedsecrets/{secret-name}{?api%2Dversion}",{"secret-name":e,"api%2Dversion":t.apiVersion},{allowReserved:(I=l?.requestOptions)===null||I===void 0?void 0:I.skipUrlEncoding});return t.path(r).delete(Object.assign(Object.assign({},VN(l)),{headers:Object.assign({accept:"application/json"},(n=l.requestOptions)===null||n===void 0?void 0:n.headers)}))}async function KOl(t){if(!["204"].includes(t.status)){let l=Yp(t);throw l.details=Yg(t.body),l}}async function k3e(t,e,l={requestOptions:{}}){let I=await POl(t,e,l);return KOl(I)}function qOl(t,e,l={requestOptions:{}}){var I,n;let r=Vg("/deletedsecrets/{secret-name}{?api%2Dversion}",{"secret-name":e,"api%2Dversion":t.apiVersion},{allowReserved:(I=l?.requestOptions)===null||I===void 0?void 0:I.skipUrlEncoding});return t.path(r).get(Object.assign(Object.assign({},VN(l)),{headers:Object.assign({accept:"application/json"},(n=l.requestOptions)===null||n===void 0?void 0:n.headers)}))}async function $Ol(t){if(!["200"].includes(t.status)){let l=Yp(t);throw l.details=Yg(t.body),l}return v3e(t.body)}async function L3e(t,e,l={requestOptions:{}}){let I=await qOl(t,e,l);return $Ol(I)}function eTl(t,e={requestOptions:{}}){var l,I;let n=Vg("/deletedsecrets{?api%2Dversion,maxresults}",{"api%2Dversion":t.apiVersion,maxresults:e?.maxresults},{allowReserved:(l=e?.requestOptions)===null||l===void 0?void 0:l.skipUrlEncoding});return t.path(n).get(Object.assign(Object.assign({},VN(e)),{headers:Object.assign({accept:"application/json"},(I=e.requestOptions)===null||I===void 0?void 0:I.headers)}))}async function tTl(t){if(!["200"].includes(t.status)){let l=Yp(t);throw l.details=Yg(t.body),l}return xEt(t.body)}function x3e(t,e={requestOptions:{}}){return IWe(t,()=>eTl(t,e),tTl,["200"],{itemName:"value",nextLinkName:"nextLink"})}function lTl(t,e,l={requestOptions:{}}){var I,n;let r=Vg("/secrets/{secret-name}/versions{?api%2Dversion,maxresults}",{"secret-name":e,"api%2Dversion":t.apiVersion,maxresults:l?.maxresults},{allowReserved:(I=l?.requestOptions)===null||I===void 0?void 0:I.skipUrlEncoding});return t.path(r).get(Object.assign(Object.assign({},VN(l)),{headers:Object.assign({accept:"application/json"},(n=l.requestOptions)===null||n===void 0?void 0:n.headers)}))}async function ITl(t){if(!["200"].includes(t.status)){let l=Yp(t);throw l.details=Yg(t.body),l}return Q3e(t.body)}function S3e(t,e,l={requestOptions:{}}){return IWe(t,()=>lTl(t,e,l),ITl,["200"],{itemName:"value",nextLinkName:"nextLink"})}function nTl(t,e={requestOptions:{}}){var l,I;let n=Vg("/secrets{?api%2Dversion,maxresults}",{"api%2Dversion":t.apiVersion,maxresults:e?.maxresults},{allowReserved:(l=e?.requestOptions)===null||l===void 0?void 0:l.skipUrlEncoding});return t.path(n).get(Object.assign(Object.assign({},VN(e)),{headers:Object.assign({accept:"application/json"},(I=e.requestOptions)===null||I===void 0?void 0:I.headers)}))}async function rTl(t){if(!["200"].includes(t.status)){let l=Yp(t);throw l.details=Yg(t.body),l}return Q3e(t.body)}function B3e(t,e={requestOptions:{}}){return IWe(t,()=>nTl(t,e),rTl,["200"],{itemName:"value",nextLinkName:"nextLink"})}function aTl(t,e,l,I={requestOptions:{}}){var n,r;let a=Vg("/secrets/{secret-name}/{secret-version}{?api%2Dversion}",{"secret-name":e,"secret-version":l,"api%2Dversion":t.apiVersion},{allowReserved:(n=I?.requestOptions)===null||n===void 0?void 0:n.skipUrlEncoding});return t.path(a).get(Object.assign(Object.assign({},VN(I)),{headers:Object.assign({accept:"application/json"},(r=I.requestOptions)===null||r===void 0?void 0:r.headers)}))}async function sTl(t){if(!["200"].includes(t.status)){let l=Yp(t);throw l.details=Yg(t.body),l}return TD(t.body)}async function O3e(t,e,l,I={requestOptions:{}}){let n=await aTl(t,e,l,I);return sTl(n)}function oTl(t,e,l,I,n={requestOptions:{}}){var r,a;let s=Vg("/secrets/{secret-name}/{secret-version}{?api%2Dversion}",{"secret-name":e,"secret-version":l,"api%2Dversion":t.apiVersion},{allowReserved:(r=n?.requestOptions)===null||r===void 0?void 0:r.skipUrlEncoding});return t.path(s).patch(Object.assign(Object.assign({},VN(n)),{contentType:"application/json",headers:Object.assign({accept:"application/json"},(a=n.requestOptions)===null||a===void 0?void 0:a.headers),body:LEt(I)}))}async function cTl(t){if(!["200"].includes(t.status)){let l=Yp(t);throw l.details=Yg(t.body),l}return TD(t.body)}async function T3e(t,e,l,I,n={requestOptions:{}}){let r=await oTl(t,e,l,I,n);return cTl(r)}function iTl(t,e,l={requestOptions:{}}){var I,n;let r=Vg("/secrets/{secret-name}{?api%2Dversion}",{"secret-name":e,"api%2Dversion":t.apiVersion},{allowReserved:(I=l?.requestOptions)===null||I===void 0?void 0:I.skipUrlEncoding});return t.path(r).delete(Object.assign(Object.assign({},VN(l)),{headers:Object.assign({accept:"application/json"},(n=l.requestOptions)===null||n===void 0?void 0:n.headers)}))}async function dTl(t){if(!["200"].includes(t.status)){let l=Yp(t);throw l.details=Yg(t.body),l}return v3e(t.body)}async function U3e(t,e,l={requestOptions:{}}){let I=await iTl(t,e,l);return dTl(I)}function mTl(t,e,l,I={requestOptions:{}}){var n,r;let a=Vg("/secrets/{secret-name}{?api%2Dversion}",{"secret-name":e,"api%2Dversion":t.apiVersion},{allowReserved:(n=I?.requestOptions)===null||n===void 0?void 0:n.skipUrlEncoding});return t.path(a).put(Object.assign(Object.assign({},VN(I)),{contentType:"application/json",headers:Object.assign({accept:"application/json"},(r=I.requestOptions)===null||r===void 0?void 0:r.headers),body:fEt(l)}))}async function GTl(t){if(!["200"].includes(t.status)){let l=Yp(t);throw l.details=Yg(t.body),l}return TD(t.body)}async function _3e(t,e,l,I={requestOptions:{}}){let n=await mTl(t,e,l,I);return GTl(n)}var Mne=class{constructor(e,l,I={}){var n;let r=(n=I?.userAgentOptions)===null||n===void 0?void 0:n.userAgentPrefix,a=r?`${r} azsdk-js-client`:"azsdk-js-client";this._client=F3e(e,l,Object.assign(Object.assign({},I),{userAgentOptions:{userAgentPrefix:a}})),this.pipeline=this._client.pipeline}restoreSecret(e,l={requestOptions:{}}){return X3e(this._client,e,l)}backupSecret(e,l={requestOptions:{}}){return f3e(this._client,e,l)}recoverDeletedSecret(e,l={requestOptions:{}}){return J3e(this._client,e,l)}purgeDeletedSecret(e,l={requestOptions:{}}){return k3e(this._client,e,l)}getDeletedSecret(e,l={requestOptions:{}}){return L3e(this._client,e,l)}getDeletedSecrets(e={requestOptions:{}}){return x3e(this._client,e)}getSecretVersions(e,l={requestOptions:{}}){return S3e(this._client,e,l)}getSecrets(e={requestOptions:{}}){return B3e(this._client,e)}getSecret(e,l,I={requestOptions:{}}){return O3e(this._client,e,l,I)}updateSecret(e,l,I,n={requestOptions:{}}){return T3e(this._client,e,l,I,n)}deleteSecret(e,l={requestOptions:{}}){return U3e(this._client,e,l)}setSecret(e,l,I={requestOptions:{}}){return _3e(this._client,e,l,I)}};c();c();c();var bTl=["authorization","authorization_url","resource","scope","tenantId","claims","error"];function z3e(t){let e=/,? +/,l=t.split(e).reduce((I,n)=>{if(n.match(/\w="/)){let[r,...a]=n.split("=");if(bTl.includes(r))return Object.assign(Object.assign({},I),{[r]:a.join("=").slice(1,-1)})}return I},{});if(l.authorization)try{let I=new URL(l.authorization).pathname.substring(1);I&&(l.tenantId=I)}catch{throw new Error(`The challenge authorization URI '${l.authorization}' is invalid.`)}return l}c();var uTl={forcedRefreshWindowInMs:1e3,retryIntervalInMs:3e3,refreshWindowInMs:1e3*60*2};async function pTl(t,e,l){async function I(){if(Date.now()<l)try{return await t()}catch{return null}else{let r=await t();if(r===null)throw new Error("Failed to refresh access token.");return r}}let n=await I();for(;n===null;)await sf(e),n=await I();return n}function UEt(t,e){let l=null,I=null,n,r=Object.assign(Object.assign({},uTl),e),a={get isRefreshing(){return l!==null},get shouldRefresh(){var o;return a.isRefreshing?!1:I?.refreshAfterTimestamp&&I.refreshAfterTimestamp<Date.now()?!0:((o=I?.expiresOnTimestamp)!==null&&o!==void 0?o:0)-r.refreshWindowInMs<Date.now()},get mustRefresh(){return I===null||I.expiresOnTimestamp-r.forcedRefreshWindowInMs<Date.now()}};function s(o,d){var G;return a.isRefreshing||(l=pTl(()=>t.getToken(o,d),r.retryIntervalInMs,(G=I?.expiresOnTimestamp)!==null&&G!==void 0?G:Date.now()).then(h=>(l=null,I=h,n=d.tenantId,I)).catch(h=>{throw l=null,I=null,n=void 0,h})),l}return async(o,d)=>{let G=!!d.claims,u=n!==d.tenantId;return G&&(I=null),u||G||a.mustRefresh?s(o,d):(a.shouldRefresh&&s(o,d),I)}}c();var _Et=hp("keyvault-common");function hTl(t,e){let l;try{l=new URL(t)}catch{throw new Error(`The challenge contains invalid scope '${t}'`)}if(!new URL(e.url).hostname.endsWith(`.${l.hostname}`))throw new Error(`The challenge resource '${l.hostname}' does not match the requested domain. Set disableChallengeResourceVerification to true in your client options to disable. See https://aka.ms/azsdk/blog/vault-uri for more information.`)}var ZTl="keyVaultAuthenticationPolicy";function zEt(t,e={}){let{disableChallengeResourceVerification:l}=e,I={status:"none"},n=UEt(t);function r(G){return{abortSignal:G.abortSignal,requestOptions:{timeout:G.timeout>0?G.timeout:void 0},tracingOptions:G.tracingOptions}}async function a(G){let u=r(G);switch(I.status){case"none":I={status:"started",originalBody:G.body},G.body=null;break;case"started":break;case"complete":{let h=await n(I.scopes,Object.assign(Object.assign({},u),{enableCae:!0,tenantId:I.tenantId}));h&&G.headers.set("authorization",`Bearer ${h.token}`);break}}}async function s(G,u,h){if(u.status!==401)return u;G.body===null&&I.status==="started"&&(G.body=I.originalBody);let W=r(G),y=u.headers.get("WWW-Authenticate");if(!y)return _Et.warning("keyVaultAuthentication policy encountered a 401 response without a corresponding WWW-Authenticate header. This is unexpected. Not handling the 401 response."),u;let R=z3e(y),w=R.resource?R.resource+"/.default":R.scope;if(!w)return u;l||hTl(w,G);let v=await n([w],Object.assign(Object.assign({},W),{enableCae:!0,tenantId:R.tenantId}));return v?(G.headers.set("Authorization",`Bearer ${v.token}`),I={status:"complete",scopes:[w],tenantId:R.tenantId},h(G)):u}async function o(G,u,h){if(I.status!=="complete"||u.status!==401)return u;let W=r(G),y=u.headers.get("WWW-Authenticate");if(!y)return u;let{claims:R,error:w}=z3e(y);if(w!=="insufficient_claims"||R===void 0)return u;let v=atob(R),f=await n(I.scopes,Object.assign(Object.assign({},W),{enableCae:!0,tenantId:I.tenantId,claims:v}));return G.headers.set("Authorization",`Bearer ${f.token}`),h(G)}async function d(G,u){await a(G);let h=await u(G);return h=await s(G,h,u),h=await o(G,h,u),h}return{name:ZTl,sendRequest:d}}c();function MEt(t,e){if(typeof t!="string"||!(t=t.trim()))throw new Error("Invalid collection argument");if(typeof e!="string"||!(e=e.trim()))throw new Error("Invalid identifier argument");let l;try{l=new URL(e)}catch{throw new Error(`Invalid ${t} identifier: ${e}. Not a valid URI`)}let I=(l.pathname||"").split("/");if(I.length!==3&&I.length!==4)throw new Error(`Invalid ${t} identifier: ${e}. Bad number of segments: ${I.length}`);if(t!==I[1])throw new Error(`Invalid ${t} identifier: ${e}. segment [1] should be "${t}", found "${I[1]}"`);let n=`${l.protocol}//${l.host}`,r=I[2],a=I.length===4?I[3]:void 0;return{vaultUrl:n,name:r,version:a}}c();c();c();c();function M3e(t){let l=t.split("/")[3];return Object.assign({sourceId:t},MEt(l,t))}c();function qh(t){let e=t,l=t,I=M3e(e.id),n=e.attributes;delete e.attributes;let r={value:e.value,name:I.name,properties:{expiresOn:n?.expires,createdOn:n?.created,updatedOn:n?.updated,enabled:n?.enabled,notBefore:n?.notBefore,recoverableDays:n?.recoverableDays,recoveryLevel:n?.recoveryLevel,id:e.id,contentType:e.contentType,tags:e.tags,managed:e.managed,vaultUrl:I.vaultUrl,version:I.version,name:I.name,certificateKeyId:e.kid}};return l.recoveryId&&(r.properties.recoveryId=l.recoveryId,r.properties.scheduledPurgeDate=l.scheduledPurgeDate,r.properties.deletedOn=l.deletedDate,r.recoveryId=l.recoveryId,r.scheduledPurgeDate=l.scheduledPurgeDate,r.deletedOn=l.deletedDate),n&&(n.vaultUrl&&delete r.properties.vaultUrl,n.expires&&delete r.properties.expires,n.created&&delete r.properties.created,n.updated&&delete r.properties.updated),r}function rWe(t,e,l){let I;return{async next(){I??(I=t(Object.assign(Object.assign({},e),{maxresults:void 0})));let n=await I.next();return Object.assign(Object.assign({},n),{value:n.value&&l(n.value)})},[Symbol.asyncIterator](){return this},byPage(n){return nf(this,arguments,function*(){var a,s,o,d;let G=t(Object.assign(Object.assign({},e),{maxresults:n?.maxPageSize})).byPage(n);try{for(var u=!0,h=$L(G),W;W=yield Ni(h.next()),a=W.done,!a;u=!0)d=W.value,u=!1,yield yield Ni(d.map(l))}catch(y){s={error:y}}finally{try{!u&&!a&&(o=h.return)&&(yield Ni(o.call(h)))}finally{if(s)throw s.error}}})}}}c();c();var aWe="4.10.0";var wN=t3({namespace:"Microsoft.KeyVault",packageName:"@azure/keyvault-secrets",packageVersion:aWe});c();c();c();c();c();c();c();c();var D3e=hp("core-lro");c();c();c();c();c();c();var j3e=class t extends Error{constructor(e){super(e),this.name="PollerStoppedError",Object.setPrototypeOf(this,t.prototype)}},P3e=class t extends Error{constructor(e){super(e),this.name="PollerCancelledError",Object.setPrototypeOf(this,t.prototype)}},Dne=class{constructor(e){this.resolveOnUnsuccessful=!1,this.stopped=!0,this.pollProgressCallbacks=[],this.operation=e,this.promise=new Promise((l,I)=>{this.resolve=l,this.reject=I}),this.promise.catch(()=>{})}async startPolling(e={}){for(this.stopped&&(this.stopped=!1);!this.isStopped()&&!this.isDone();)await this.poll(e),await this.delay()}async pollOnce(e={}){this.isDone()||(this.operation=await this.operation.update({abortSignal:e.abortSignal,fireProgress:this.fireProgress.bind(this)})),this.processUpdatedState()}fireProgress(e){for(let l of this.pollProgressCallbacks)l(e)}async cancelOnce(e={}){this.operation=await this.operation.cancel(e)}poll(e={}){if(!this.pollOncePromise){this.pollOncePromise=this.pollOnce(e);let l=()=>{this.pollOncePromise=void 0};this.pollOncePromise.then(l,l).catch(this.reject)}return this.pollOncePromise}processUpdatedState(){if(this.operation.state.error&&(this.stopped=!0,!this.resolveOnUnsuccessful))throw this.reject(this.operation.state.error),this.operation.state.error;if(this.operation.state.isCancelled&&(this.stopped=!0,!this.resolveOnUnsuccessful)){let e=new P3e("Operation was canceled");throw this.reject(e),e}this.isDone()&&this.resolve&&this.resolve(this.getResult())}async pollUntilDone(e={}){return this.stopped&&this.startPolling(e).catch(this.reject),this.processUpdatedState(),this.promise}onProgress(e){return this.pollProgressCallbacks.push(e),()=>{this.pollProgressCallbacks=this.pollProgressCallbacks.filter(l=>l!==e)}}isDone(){let e=this.operation.state;return!!(e.isCompleted||e.isCancelled||e.error)}stopPolling(){this.stopped||(this.stopped=!0,this.reject&&this.reject(new j3e("This poller is already stopped")))}isStopped(){return this.stopped}cancelOperation(e={}){if(!this.cancelPromise)this.cancelPromise=this.cancelOnce(e);else if(e.abortSignal)throw new Error("A cancel request is currently pending");return this.cancelPromise}getOperationState(){return this.operation.state}getResult(){return this.operation.state.result}toString(){return this.operation.toString()}};c();var _D=class extends Dne{constructor(){super(...arguments),this.intervalInMs=2e3}async delay(){return sf(this.intervalInMs)}},zD=class{constructor(e,l={}){this.state=e,this.cancelMessage="",l.cancelMessage&&(this.cancelMessage=l.cancelMessage)}async update(){throw new Error("Operation not supported.")}async cancel(){throw new Error(this.cancelMessage)}toString(){return JSON.stringify({state:this.state})}};var sWe=class extends zD{constructor(e,l,I={}){super(e,{cancelMessage:"Canceling the deletion of a secret is not supported."}),this.state=e,this.client=l,this.operationOptions=I}deleteSecret(e,l={}){return wN.withSpan("DeleteSecretPoller.deleteSecret",l,async I=>{let n=await this.client.deleteSecret(e,I);return qh(n)})}getDeletedSecret(e,l={}){return wN.withSpan("DeleteSecretPoller.getDeletedSecret",l,async I=>{let n=await this.client.getDeletedSecret(e,I);return qh(n)})}async update(e={}){let l=this.state,{name:I}=l;if(e.abortSignal&&(this.operationOptions.abortSignal=e.abortSignal),!l.isStarted){let n=await this.deleteSecret(I,this.operationOptions);l.isStarted=!0,l.result=n,n.properties.recoveryId||(l.isCompleted=!0)}if(!l.isCompleted)try{l.result=await this.getDeletedSecret(I,this.operationOptions),l.isCompleted=!0}catch(n){if(n.statusCode===403)l.isCompleted=!0;else if(n.statusCode!==404)throw l.error=n,l.isCompleted=!0,n}return this}};var oWe=class extends _D{constructor(e){let{client:l,name:I,operationOptions:n,intervalInMs:r=2e3,resumeFrom:a}=e,s;a&&(s=JSON.parse(a).state);let o=new sWe(Object.assign(Object.assign({},s),{name:I}),l,n);super(o),this.intervalInMs=r}};c();c();var cWe=class extends zD{constructor(e,l,I={}){super(e,{cancelMessage:"Canceling the recovery of a deleted secret is not supported."}),this.state=e,this.client=l,this.options=I}getSecret(e,l={}){return wN.withSpan("RecoverDeletedSecretPoller.getSecret",l,async I=>{let n=await this.client.getSecret(e,l&&l.version?l.version:"",I);return qh(n)})}recoverDeletedSecret(e,l={}){return wN.withSpan("RecoverDeletedSecretPoller.recoverDeletedSecret",l,async I=>{let n=await this.client.recoverDeletedSecret(e,I);return qh(n)})}async update(e={}){let l=this.state,{name:I}=l;if(e.abortSignal&&(this.options.abortSignal=e.abortSignal),!l.isStarted){try{l.result=(await this.getSecret(I,this.options)).properties,l.isCompleted=!0}catch{}l.isCompleted||(l.result=(await this.recoverDeletedSecret(I,this.options)).properties,l.isStarted=!0)}if(!l.isCompleted)try{l.result=(await this.getSecret(I,this.options)).properties,l.isCompleted=!0}catch(n){if(n.statusCode===403)l.isCompleted=!0;else if(n.statusCode!==404)throw l.error=n,l.isCompleted=!0,n}return this}};var iWe=class extends _D{constructor(e){let{client:l,name:I,operationOptions:n,intervalInMs:r=2e3,resumeFrom:a}=e,s;a&&(s=JSON.parse(a).state);let o=new cWe(Object.assign(Object.assign({},s),{name:I}),l,n);super(o),this.intervalInMs=r}};var dWe=class{constructor(e,l,I={}){var n,r;this.vaultUrl=e;let a=Object.assign(Object.assign({},I),{userAgentOptions:{userAgentPrefix:`${(r=(n=I.userAgentOptions)===null||n===void 0?void 0:n.userAgentPrefix)!==null&&r!==void 0?r:""} azsdk-js-keyvault-secrets/${aWe}`},apiVersion:I.serviceVersion||"7.6",loggingOptions:{logger:wEt.info,additionalAllowedHeaderNames:["x-ms-keyvault-region","x-ms-keyvault-network-info","x-ms-keyvault-service-version"]}});this.client=new Mne(this.vaultUrl,l,a),this.client.pipeline.removePolicy({name:hpe}),this.client.pipeline.addPolicy(zEt(l,I),{}),this.client.pipeline.addPolicy({name:"ContentTypePolicy",sendRequest(s,o){var d;return((d=s.headers.get("Content-Type"))!==null&&d!==void 0?d:"").startsWith("application/json")&&s.headers.set("Content-Type","application/json"),o(s)}})}setSecret(e,l,I={}){let{enabled:n,notBefore:r,expiresOn:a,tags:s}=I,o=kte(I,["enabled","notBefore","expiresOn","tags"]);return wN.withSpan("SecretClient.setSecret",o,async d=>{let G=await this.client.setSecret(e,{value:l,secretAttributes:{enabled:n,notBefore:r,expires:a},tags:s},d);return qh(G)})}async beginDeleteSecret(e,l={}){let I=new oWe(Object.assign(Object.assign({name:e,client:this.client},l),{operationOptions:l}));return await I.poll(),I}async updateSecretProperties(e,l,I={}){let{enabled:n,notBefore:r,expiresOn:a,tags:s}=I,o=kte(I,["enabled","notBefore","expiresOn","tags"]);return wN.withSpan("SecretClient.updateSecretProperties",o,async d=>{let G=await this.client.updateSecret(e,l,{secretAttributes:{enabled:n,notBefore:r,expires:a},tags:s},d);return qh(G).properties})}getSecret(e,l={}){return wN.withSpan("SecretClient.getSecret",l,async I=>{let n=await this.client.getSecret(e,l&&l.version?l.version:"",I);return qh(n)})}getDeletedSecret(e,l={}){return wN.withSpan("SecretClient.getDeletedSecret",l,async I=>{let n=await this.client.getDeletedSecret(e,I);return qh(n)})}purgeDeletedSecret(e,l={}){return wN.withSpan("SecretClient.purgeDeletedSecret",l,async I=>{await this.client.purgeDeletedSecret(e,I)})}async beginRecoverDeletedSecret(e,l={}){let I=new iWe(Object.assign(Object.assign({name:e,client:this.client},l),{operationOptions:l}));return await I.poll(),I}backupSecret(e,l={}){return wN.withSpan("SecretClient.backupSecret",l,async I=>(await this.client.backupSecret(e,I)).value)}restoreSecretBackup(e,l={}){return wN.withSpan("SecretClient.restoreSecretBackup",l,async I=>{let n=await this.client.restoreSecret({secretBundleBackup:e},I);return qh(n).properties})}listPropertiesOfSecretVersions(e,l={}){return rWe(I=>this.client.getSecretVersions(e,I),l,I=>qh(I).properties)}listPropertiesOfSecrets(e={}){return rWe(this.client.getSecrets.bind(this.client),e,l=>qh(l).properties)}listDeletedSecrets(e={}){return rWe(this.client.getDeletedSecrets.bind(this.client),e,qh)}};var K3e=class{client;logger;constructor(e,l){if(this.logger=l,e){this.logger.debug(`Using Azure Key Vault at ${e}`);let I=new t1;this.client=new dWe(e,I)}else this.logger.debug("No Azure Key Vault URI provided, secret provider disabled")}async getSecret(e){if(this.client)try{return(await this.client.getSecret(e)).value}catch(l){if(this.logger.warning(`Error fetching secret ${e}: ${l}`),l?.code==="SecretNotFound")return;throw l}}};function q3e(t,e){let l=t.api?.copilot?.azureKeyVaultUri;return $3e(l,e)}function $3e(t,e){return new K3e(t,e)}c();import{createHmac as RTl}from"crypto";var mWe=class t{static encode(e){let l=t.hmacGetBytes(e),a=(Math.floor(Date.now()/1e3)+30).toString(),s=Buffer.from(a,"ascii"),G=RTl("sha256",l).update(s).digest().toString("hex").toUpperCase();return`${a}.${G}`}static hmacGetBytes(e){return Buffer.from(e,"ascii")}};var ETl="X-GitHub-Api-Version",YTl="2025-05-01",GWe=class t extends $Ne{constructor(l,I,n,r){super({baseURL:l,apiKey:""});this.headers=I;this.logger=n;this.hmacKey=r}static baseHeaders={"Content-Type":"application/json",Accept:"application/json","X-Interaction-Type":"conversation-agent","Openai-Intent":"conversation-agent","X-Initiator":"user",[ETl]:YTl};hmacKey;static createWithOAuthToken(l,I,n,r,a,s){let o={...this.defaultHeaders(n,a),Authorization:`Bearer ${r}`,...s??{}};return l.debug(`Creating copilot-client for integration ID ${n} with token authentication. User-agent: ${o["User-Agent"]}`),new t(I,o,l)}static createWithHmac(l,I,n,r,a,s,o){let d={...this.defaultHeaders(n,a),Authorization:"",...o??{}};return s&&(d["X-GitHub-User"]=s),l.debug(`Creating copilot-client for integration ID ${n} with key authentication. User-agent: ${d["User-Agent"]}`),new t(I,d,l,r)}static defaultHeaders(l,I){let n=YN();return{...t.baseHeaders,"Copilot-Integration-Id":l,"User-Agent":`${n.nameNoScope}/${n.version} (${process.platform} ${process.version}) OpenAI/${vv}`,"X-Interaction-Id":I}}async prepareOptions(l){this.hmacKey&&(this.headers["Request-HMAC"]=mWe.encode(this.hmacKey)),l.headers={...this.headers,...l.headers},await super.prepareOptions(l)}setInitiatorHeader(l){this.headers["X-Initiator"]=l}async listModels(){let l={method:"get",path:""};await this.prepareOptions(l);let I={};if(l.headers)for(let[s,o]of Object.entries(l.headers))typeof o=="string"&&(I[s]=o);let n=`${this.baseURL}/models`,r=await fetch(n,{method:l.method,headers:I});if(!r.ok)return this.logger.error(`Failed to list models: ${r.statusText}`),[];let a=await r.json();return this.logger.debug(`Successfully listed ${a.data.length} models`),a.data}async prepareRequest(l,{url:I,options:n}){try{n.body.messages.some(s=>Array.isArray(s.content)?s.content.some(o=>o.type==="image_url"):!1)&&(l.headers={...n.headers,"Copilot-Vision-Request":"true"})}catch{this.logger.error("Error while preparing request headers for Copilot-Vision-Request")}await super.prepareRequest(l,{url:I,options:n})}},bWe=class{async createClient(e,l,I){l.startGroup("configured settings:",8),l.debug(JSON.stringify(e,null,2)),l.endGroup(8);let n=e.api?.copilot?.token,r=e.api?.copilot?.hmacKey,a=!!(r||n);if(!a){l.debug("No Copilot HMAC key or GitHub OAuth token provided, trying secret provider");let u=q3e(e,l);try{r=await u.getSecret("capi-hmac-key")}catch(h){l.debug(`Failed to get Copilot HMAC key from secret provider:
1430
1431
  ${h}`)}try{n=await u.getSecret("capi-token")}catch(h){l.debug(`Failed to get Copilot GitHub OAuth token from secret provider:
1431
1432
  ${h}`)}a=!!(r||n)}let s,o=zwe(e),d=OO(e),G=e.api?.copilot?.sessionId??Gk(e);if(l.debug(`Using Copilot API at ${o} with integration ID ${d}`),n&&(l.debug("Using GitHub OAuth token for Copilot API"),s=GWe.createWithOAuthToken(l,o,d,n,G,I?.requestHeaders)),r){l.debug("Using Copilot HMAC key for Copilot API");let u=process.env.GITHUB_USER_ID;u?l.debug(`Using user ID ${u} for Copilot HMAC key`):l.debug("No user ID provided for Copilot HMAC key"),s=GWe.createWithHmac(l,o,d,r,G,u,I?.requestHeaders)}if(s===void 0)throw new Error("No GitHub OAuth token or Copilot HMAC key provided");return s}},Bx=class t extends Nd{constructor(e){super(e.status,e.error,e.message,e.headers),this.name="CAPIError",this.ghRequestId=e.headers?.["x-github-request-id"]||this.request_id}ghRequestId;static fromAPIError(e){if(!(!e||!(e instanceof Nd)))return new t(e)}};c();var exe="x-quota-snapshot-";function DEt(t){if(t)try{let e=new URLSearchParams(t),l=parseInt(e.get("ent")||"0",10),I=parseFloat(e.get("ov")||"0.0"),n=e.get("ovPerm")==="true",r=parseFloat(e.get("rem")||"0.0"),a=e.get("rst"),s;a?s=new Date(a):(s=new Date,s.setMonth(s.getMonth()+1));let o=Math.round(Math.max(0,l*(1-r/100)));return isNaN(l)||isNaN(I)||isNaN(r)?void 0:{isUnlimitedEntitlement:l===-1,entitlementRequests:l,usedRequests:o,usageAllowedWithExhaustedQuota:n,overage:I,overageAllowedWithExhaustedQuota:n,remainingPercentage:r,resetDate:s}}catch{return}}var txe={type:"ephemeral"},MD=class t{constructor(e,l,I,n){this.settings=l;this.logger=I;this.clientOptions=t.initDefaultOptions(n),I.info(" "),I.debug(`Using model: ${this.model}`),this.clientPromise=e.createClient(l,I,n),this.modelPromise=this.clientPromise.then(async()=>{let r=await this.getModel();return I.debug(`Got model info: ${JSON.stringify(r,null,2)}`),r})}clientOptions;clientPromise;modelPromise;agent="sweagent-capi";get model(){return this.clientOptions.model}static initDefaultOptions(e){return{model:e?.model||ufe.model,toolTokenBudgetProportion:e?.toolTokenBudgetProportion??.25,retryPolicy:{maxRetries:e?.retryPolicy?.maxRetries??5,errorCodesToRetry:e?.retryPolicy?.errorCodesToRetry??[],rateLimitRetryPolicy:{defaultRetryAfterSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.defaultRetryAfterSeconds??5,initialRetryBackoffExtraSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.initialRetryBackoffExtraSeconds??1,retryBackoffExtraGrowth:e?.retryPolicy?.rateLimitRetryPolicy?.retryBackoffExtraGrowth??2,maxRetryAfterSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.maxRetryAfterSeconds??180}},thinkingMode:e?.thinkingMode??!1,requestHeaders:e?.requestHeaders??{}}}getCompletionOptions(e,l){let I={snippy:{enabled:!1}};return{temperature:0,top_p:.95,frequency_penalty:0,presence_penalty:0,tool_choice:l?.toolChoice,...I}}makeRequest(e,l,I,n,r,a,s){return e.chat.completions.create({model:l,messages:[...I],...n,tools:r},{maxRetries:a,headers:s?.requestHeaders,signal:s?.abortSignal}).withResponse()}async*getCompletionWithTools(e,l,I,n){let r=this.model,a=await this.clientPromise,s=await this.modelPromise,o=CH(I),d=[{role:"system",content:e,copilot_cache_control:txe},...l.map(R=>Ite(R))],G=I.map((R,w)=>({type:"function",function:{name:R.name,description:R.description,parameters:R.input_schema},copilot_cache_control:w===I.length-1?txe:void 0}));this.logger.startGroup("Completion request configuration: ",8),this.logger.debug("Client options: "),this.logger.debug(JSON.stringify(this.clientOptions,null,2)),this.logger.debug("Request options: "),this.logger.debug(JSON.stringify(n??{},null,2)),this.logger.debug("Tools: "),this.logger.debug(JSON.stringify(G,null,2)),this.logger.endGroup(8);let u=this.getCompletionOptions(I,n),h=n?.initialTurnCount!==void 0?n.initialTurnCount+1:0,W=!1,y=!1;for(;!W&&!y;){let R=Date.now();yield{kind:"turn_started",model:r,modelInfo:s,turn:h,timestampMs:R};let w=0,v=0,f=0,S=[429,503,500,400],B=this.clientOptions.retryPolicy.maxRetries,T=this.clientOptions.retryPolicy.rateLimitRetryPolicy.initialRetryBackoffExtraSeconds,q=0,te=this.clientOptions.retryPolicy.rateLimitRetryPolicy.maxRetryAfterSeconds,ae=s.capabilities.limits.max_prompt_tokens||s.capabilities.limits.max_context_window_tokens,U=1,ee=.5,ge=()=>ae*U,he,Re;try{if(h===0){let be=klt(d,r),se=Llt(G,r);if(be+se>ae){if(n?.failIfInitialInputsTooLong)throw new Error(`Initial inputs exceed the model's token limit of ${ae} tokens.`);this.logger.warning(`Initial inputs exceed the model's token limit of ${ae} tokens. The model may not be able to process the inputs correctly.`)}}let ne=[],D;do{f>0&&(yield{kind:"turn_retry",model:r,modelInfo:s,turn:h,timestampMs:Date.now()});try{for(let Fe of n?.processors?.preRequest||[]){let me=Fe.preRequest({turn:h,messages:d,toolDefinitions:G,modelInfo:s,tokenLimit:ge()});for await(let mt of me)yield mt}if(this.logger.startGroup("Sending request to the AI model",8),lc(this.settings,"copilot_swe_agent_request_logging")){let Fe=JSON.stringify(d,null,2),me=JSON.stringify(u,null,2);this.logger.debug(`Request messages: ${Fe}`),this.logger.debug(`Request options: ${me}`)}ne=d.map((Fe,me)=>me===d.length-1?{...Fe,copilot_cache_control:txe}:Fe),w=Date.now();let be=await this.makeRequest(a,r,ne,u,G,B,n);v=Date.now()-w,he=be.data,D={model:he.model,api_id:he.id,request_id:be.response.headers.get("x-github-request-id")||void 0};let se={};be.response.headers.forEach((Fe,me)=>{if(me.toLowerCase().startsWith(exe)){let mt=DEt(Fe);mt&&(se[me.replace(exe,"")]=mt)}}),yield{kind:"model_call_success",turn:h,modelCallDurationMs:v,modelCall:D,responseChunk:zmt(he),responseUsage:he.usage,requestMessages:JSON.stringify(ne),quotaSnapshots:se},this.logger.debug(`response (Request-ID ${be.request_id}):`),this.logger.debug("data:"),this.logger.debug(JSON.stringify(be.data,null,2))}catch(be){v=Date.now()-w;let se=Bx.fromAPIError(be),Fe=se?.error;if(se){yield{kind:"model_call_failure",turn:h,modelCallDurationMs:v,requestMessages:JSON.stringify(ne),modelCall:{model:r,status:se.status,error:JSON.stringify(se?.error||se?.message||"unknown error"),api_id:se.request_id||void 0,request_id:se.headers?.["x-github-request-id"]||""}},Re=se;let mt=se.ghRequestId||se.headers?.["x-github-request-id"]||se.request_id;this.logger.error(`error (Request-ID ${mt})`),this.logger.error(JSON.stringify(se,null,2)),this.logger.debug(`Failed to get response from the AI model: ${se}`),Fe&&this.logger.debug(`Inner error: ${JSON.stringify(Fe,null,2)}`);for(let Qe of n?.processors?.onRequestError||[])await Qe.onRequestError(Fe);let fe=se.status,Ye=fe?this.clientOptions.retryPolicy.errorCodesToRetry.some(Qe=>Array.isArray(Qe)?fe>=Qe[0]&&(Qe[1]===void 0||fe<=Qe[1]):fe===Qe):!1,re,je=typeof Fe?.message=="string"?Fe.message.match(/prompt token count of (\d+) exceeds the limit of (\d+)/):void 0;if(se.status!==402){if(se.status===400&&je){re=1;let Qe=parseInt(je[2],10);Qe<ae?(ae=Qe,U=1):U=Math.max(U-ee/B,ee),this.logger.debug(`Adjusted model token limit to ${ae}, token limit retry buffer to ${U}`)}else if(se.status===413){this.logger.debug("Request is too large, trying to remove images from the request");let Qe=0;for(let Jt=d.length-1;Jt>=0;Jt--)pz(d[Jt])&&(d.splice(Jt,1),Qe++,yield{kind:"images_removed",turn:h,imagesRemoved:1,largeImagesRemoved:1});Qe>0?(this.logger.info(`Images have been removed from the request due to size constraints. Please resize images to be smaller than ${SE(s.capabilities.limits.vision?.max_prompt_image_size||0)}.`),this.logger.debug(`Removed ${Qe} image messages from the request`),re=1):this.logger.debug("No image messages found in the request - unsure why the request is too large - will fail")}else if((typeof se.status=="number"&&S.includes(se.status)||Ye)&&(re=parseInt(se.headers?.["retry-after"]||`${this.clientOptions.retryPolicy.rateLimitRetryPolicy.defaultRetryAfterSeconds}`,10)+T,T*=this.clientOptions.retryPolicy.rateLimitRetryPolicy.retryBackoffExtraGrowth,f==B-1))for(let Qe=d.length-1;Qe>=0;Qe--)pz(d[Qe])&&(this.logger.debug(`Removing image message at index ${Qe} to avoid failure`),d.splice(Qe,1),yield{kind:"images_removed",turn:h,imagesRemoved:1})}if(re!==void 0&&re<=te){let Qe=.8+Math.random()*.4,Jt=re*Qe;this.logger.debug(`Retrying after ${Jt} seconds...`),await new Promise(gl=>setTimeout(gl,Jt*1e3)),q+=Jt,this.logger.debug(`Retrying after ${re} seconds... Will try again now!`);continue}else re?this.logger.error(`Retry after ${re} seconds is too long. Giving up.`):this.logger.error("Retry after is not set. Giving up.")}let me=se||be;for(let mt of n?.processors?.onRequestError||[])await mt.preErrorThrow(be);throw this.logger.error("error"),this.logger.error(JSON.stringify(me,null,2)),me}finally{this.logger.endGroup(8)}}while(!he&&f++<B);if(!he){this.logger.debug("Recent messages prior to failure:");for(let se=Math.max(0,d.length-6);se<d.length;se++)this.logger.debug(`${se}: ${JSON.stringify(d[se],null,2)}`);let be=new Error(`Failed to get response from the AI model; retried ${f-1} times (total retry wait time: ${q} seconds)`,{cause:Re});throw this.isRateLimitExceededError(be)&&(this.logger.info(`Rate limit exceeded after ${f-1} retries, will fail job but skip Sentry reporting`),be.skipReport=!0),be}for(let be of he.choices.map(se=>se.message))VTl(be.tool_calls||[]),d.push(be),yield{kind:"message",modelCall:D,message:Ite(uz(be)),turn:h};if(this.isToolCallResponse(he)){let be=ge()*this.clientOptions.toolTokenBudgetProportion,se=Prt(r,be,this,this.settings),me=he.choices.filter(re=>re.message.tool_calls!==void 0).flatMap(re=>re.message.tool_calls||[]),mt=new Map;for(let re of n?.processors?.preToolsExecution||[]){let je=await re.preToolsExecution({turn:h,toolCalls:me,modelInfo:s});if(je)for(let[Qe,Jt]of je)mt.set(Qe,Jt)}let fe=me.filter(re=>!mt.has(re.id)),Ye=this.mergeToolResults(mt,me,fe,o,se,n?.executeToolsInParallel);for await(let re of Ye){re.toolResult.resultType==="rejected"&&(y=!0);let je={role:"tool",tool_call_id:re.originalCall.id,content:re.toolResult.textResultForLlm};d.push(je),yield{kind:"message",modelCall:D,message:Ite(je),turn:h},yield{kind:"tool_execution",turn:h,toolCallId:re.originalCall.id,toolResult:re.toolResult,durationMs:re.durationMs};for(let Qe of n?.processors?.postToolExecution||[])await Qe.postToolExecution({toolCall:re.originalCall,toolResult:re.toolResult,turn:h,modelInfo:s})}}else for(let be of he.choices.map(se=>se.message))yield{kind:"response",modelCall:{model:he.model,api_id:he.id},response:Ite(uz(be)),turn:h},W=!0;a.setInitiatorHeader("agent")}catch(ne){let D;throw ne instanceof Error&&ne.cause&&ne.cause instanceof Bx?D=`${ne} (Cause: ${ne.cause})`:D=`${ne}`,yield{kind:"turn_failed",model:r,modelInfo:s,turn:h,error:D,timestampMs:Date.now()},ne}finally{let ne=Date.now();yield{kind:"turn_ended",model:r,modelInfo:s,turn:h,timestampMs:ne},h++}}}async*mergeToolResults(e,l,I,n,r,a=!1){for(let[s,o]of e){let d=l.find(G=>G.id===s);d&&(yield{durationMs:0,originalCall:d,toolResult:o})}I.length>0&&(yield*this.callTools(I,n,r,a))}async*callTools(e,l,I,n=!1){if(e.length===0)throw new Error("Tool call is missing");if(this.logger.debug(`Tool calls count: ${e.length}`),n)this.logger.debug("Running tool calls in parallel"),yield*_rt(e.map(r=>()=>this.callTool(r,l,I)));else{this.logger.debug("Running tool calls sequentially");for(let r of e)yield await this.callTool(r,l,I)}}async callTool(e,l,I){let n=0,r=e?.function.name;if(!r)throw new Error("Tool name is missing");let a=e?.function.arguments;if(!a)throw new Error("Tool call arguments are missing");let s=e?.id;if(!s)throw new Error("Tool call id is missing");let o,d=l[r];try{let G=KM(a);if(!d||!d.callback)o={textResultForLlm:`Tool '${r}' does not exist. Available tools that can be called are ${Object.keys(l).join(", ")}.`,resultType:"failure",error:`Tool '${r}' does not exist.`,sessionLog:`<error>Tool '${r}' does not exist.</error>`,toolTelemetry:{}};else{let u=d.callback,h=Date.now(),W={...I,toolCallId:s,toolOptions:this.settings.service?.tools?.[r]},y=await u({...G},W);n=Date.now()-h,o=typeof y=="string"?{textResultForLlm:y,resultType:"success",toolTelemetry:{}}:y}}catch(G){G instanceof SyntaxError?(o={textResultForLlm:`The arguments for the tool call '${r}' were not valid JSON. The arguments have been cleared. Arguments: ${a}. JSON parse error: ${G.message}`,resultType:"failure",error:`${G.message}`,sessionLog:`<error>Failed to execute \`${r}\` tool with arguments: ${a} due to syntax error: ${G.message}</error>`,toolTelemetry:{properties:{wasSyntaxError:"true"}}},e.function.arguments="{}"):o={textResultForLlm:`Failed to execute \`${r}\` tool with arguments: ${a} due to error: ${G}`,resultType:"failure",error:G instanceof Error?G.message:`${G}`,sessionLog:`<error>Failed to execute \`${r}\` tool with arguments: ${a}</error>`,toolTelemetry:{}}}return{durationMs:n,originalCall:e,toolResult:o}}isToolCallResponse(e){return e.choices.find(l=>l.message.tool_calls!==void 0)!==void 0}isRateLimitExceededError(e){if(e instanceof Error){if(e.message?.includes("exceeded maximum number of retries")&&e.message?.includes("rate-limited requests"))return!0;if(e.message?.includes("Failed to get response from the AI model")&&e.cause instanceof Bx)return e.cause.status===429}return!1}async getModel(){let e=this.clientOptions.model,l={id:e,name:e,capabilities:{supports:{vision:!1},limits:{max_prompt_tokens:9e4,max_context_window_tokens:128e3,vision:{max_prompt_image_size:3145728,max_prompt_images:1,supported_media_types:["image/jpeg","image/png","image/webp"]}}}};return(await(await this.clientPromise).listModels()).filter(a=>a.id===e).at(0)||l}};function VTl(t){for(let e of t)e.function.name=e.function.name.replace(/[^a-zA-Z0-9_-]+/g,"_")}var jne=class extends MD{constructor(e,l,I){let n=new bWe;super(n,e,l,I)}};c();var uWe=class extends MD{constructor(e,l,I,n){super(e,l,I,n)}getCompletionOptions(e,l){return{...this.model.startsWith("gpt-4")?{temperature:0,top_p:.95,frequency_penalty:0,presence_penalty:0,parallel_tool_calls:e?!1:void 0}:{},tool_choice:l?.toolChoice}}async*getCompletionWithTools(e,l,I,n){let r=await super.getCompletionWithTools(e,l,I,n);for await(let a of r)a.kind==="message"?yield{...a,message:uz({...a.message,reasoning_text:a.message?.cot_summary})}:yield a}};c();c();var pWe=class t{constructor(e,l,I,n){this.settings=l;this.logger=I;this.clientOptions=t.initDefaultOptions(n),this.logger.info(`Using responses with model: ${this.model}`),this.clientPromise=e.createClient(l,I,this.clientOptions)}clientOptions;clientPromise;get model(){return this.clientOptions.model}static initDefaultOptions(e){return{model:e?.model||"o4-mini",toolTokenBudgetProportion:e?.toolTokenBudgetProportion??.25,retryPolicy:{maxRetries:e?.retryPolicy?.maxRetries??5,errorCodesToRetry:e?.retryPolicy?.errorCodesToRetry??[],rateLimitRetryPolicy:{defaultRetryAfterSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.defaultRetryAfterSeconds??5,initialRetryBackoffExtraSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.initialRetryBackoffExtraSeconds??1,retryBackoffExtraGrowth:e?.retryPolicy?.rateLimitRetryPolicy?.retryBackoffExtraGrowth??2,maxRetryAfterSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.maxRetryAfterSeconds??60}},thinkingMode:e?.thinkingMode??!0,requestHeaders:e?.requestHeaders??{}}}async*getCompletionWithTools(e,l,I,n){let r=await this.clientPromise,a=CH(I),s=I.map(w=>({name:w.name,description:w.description,parameters:w.input_schema,strict:!1,type:"function"})),o=0,d=this.clientOptions.retryPolicy.maxRetries,G=this.clientOptions.retryPolicy.rateLimitRetryPolicy.initialRetryBackoffExtraSeconds,u=0,h=this.clientOptions.retryPolicy.rateLimitRetryPolicy.maxRetryAfterSeconds,W=l.flatMap(wTl),y,R=!1;for(;!R;){let w;do{w=void 0;try{let v=await r.responses.create({model:this.model,previous_response_id:y?.id,instructions:e,input:W,parallel_tool_calls:s.length>0?!0:void 0,tools:s,reasoning:{summary:"auto",effort:"medium"}},{maxRetries:d}).withResponse();y=v.data,this.logger.debug(`response (Request-ID ${v.request_id}):`),this.logger.debug("data:"),this.logger.debug(JSON.stringify(v.data,null,2))}catch(v){let f=v,S=f.error;if(f){w=f,this.logger.error(`error (Request-ID ${f.request_id})`),this.logger.error(JSON.stringify(f,null,2)),this.logger.debug(`Failed to get response from the AI model: ${f}`),S&&this.logger.debug(`Inner error: ${JSON.stringify(S,null,2)}`);let B=f.status,T=B?this.clientOptions.retryPolicy.errorCodesToRetry.some(te=>Array.isArray(te)?B>=te[0]&&(te[1]===void 0||B<=te[1]):B===te):!1,q;if((f.status===429||T)&&(q=parseInt(f.headers?.["retry-after"]||`${this.clientOptions.retryPolicy.rateLimitRetryPolicy.defaultRetryAfterSeconds}`,10)+G,G*=this.clientOptions.retryPolicy.rateLimitRetryPolicy.retryBackoffExtraGrowth),q!==void 0&&q<=h){this.logger.debug(`Retrying after ${q} seconds...`),await new Promise(te=>setTimeout(te,q*1e3)),u+=q,this.logger.debug(`Retrying after ${q} seconds... Will try again now!`);continue}else q?this.logger.error(`Retry after ${q} seconds is too long. Giving up.`):this.logger.error("Retry after is not set. Giving up.")}throw this.logger.error("error"),this.logger.error(JSON.stringify(v,null,2)),v}finally{this.logger.endGroup(8)}}while(w&&o++<d);if(!y||w){this.logger.debug("Recent messages prior to failure:");for(let v=Math.max(0,W.length-6);v<W.length;v++)this.logger.debug(`${v}: ${JSON.stringify(W[v],null,2)}`);throw new Error(`Failed to get response from the AI model; retried ${o-1} times (total retry wait time: ${u} seconds)`,{cause:w})}if(this.requiresToolOutput(y)){for(let f of y.output)yield{kind:"message",message:lxe(f)};W=(await this.runTool(y,a)).map(f=>({type:"function_call_output",call_id:f.toolCallId,output:f.textResultForLlm}));for(let f of W)yield{kind:"message",message:lxe(f)}}else{for(let v of y.output)yield{kind:"message",message:lxe(v)};yield{kind:"response",response:{content:y.output_text,refusal:null,role:"assistant"}},R=!0}}}async runTool(e,l,I){let n=e.output.filter(a=>a.type==="function_call");if(!n||n.length===0)throw new Error("Tool calls in response are missing");let r=[];for(let a of n){let s=a.name;if(!s)throw new Error("Tool name is missing");let o=a.arguments;if(!o)throw new Error("Tool call arguments are missing");let d=a.call_id;if(!d)throw new Error("Tool call id is missing");let G,u=l[s];try{let h=KM(o);if(!u||!u.callback)G={textResultForLlm:`Tool '${s}' does not exist. Available tools that can be called are ${Object.keys(l).join(", ")}.`,resultType:"failure",error:`Tool '${s}' does not exist.`,sessionLog:`<error>Tool '${s}' does not exist.</error>`,toolTelemetry:{}};else{let W=u.callback,y={...I,toolOptions:this.settings.service?.tools?.[s],settings:this.settings},R=await W({...h},y);G=typeof R=="string"?{textResultForLlm:R,resultType:"success",toolTelemetry:{}}:R}}catch(h){G={textResultForLlm:`Failed to execute \`${s}\` tool with arguments: ${o} due to error: ${h}`,resultType:"failure",error:h instanceof Error?h.message:`${h}`,sessionLog:`<error>Failed to execute \`${s}\` tool with arguments: ${o}</error>`,toolTelemetry:{properties:{wasSyntaxError:h instanceof SyntaxError?"true":"false"}}}}r.push({toolCallId:d,textResultForLlm:G.textResultForLlm,sessionLog:G.resultType=="success"?G.sessionLog:G.error?`<error>${G.error}</error>`:void 0})}return r}requiresToolOutput(e){return e.output.filter(l=>l.type==="function_call").length>0}};function wTl(t){if(t.role==="function")throw new Error("Function role is not supported");let e=[];if(t.reasoning_opaque&&e.push({id:t.reasoning_opaque,type:"reasoning",summary:t.reasoning_text?[{text:t.reasoning_text,type:"summary_text"}]:[]}),t.role==="assistant"&&t.tool_calls&&t.tool_calls.length>0){let l=t.tool_calls[0];return[...e,{type:"function_call",id:t.id,name:l.function.name,arguments:l.function.arguments,call_id:l.id}]}return t.role==="tool"?[...e,{type:"function_call_output",call_id:t.tool_call_id,output:typeof t.content=="string"?t.content:t.content?.map(l=>l.type==="text"?l:{type:"text",text:""}).join(" ")??""}]:t.content?t.role==="assistant"?[...e,{type:"message",id:t.id,role:t.role,content:[{annotations:[],type:"output_text",text:typeof t.content=="string"?t.content:t.content?.map(l=>l.type==="text"?l.text:"").join(" ")??""}]}]:[...e,{role:t.role,content:typeof t.content=="string"?t.content:t.content?.map(l=>l.type==="text"?l.text:"").join(" ")??"",type:"message"}]:e}function lxe(t){if(t.type==="reasoning")return{role:"assistant",reasoning_opaque:t.id,reasoning_text:t.summary?t.summary.map(e=>e.text).join(" "):void 0,content:""};if(t.type==="function_call")return{role:"assistant",id:t.id,tool_calls:[{id:t.call_id,type:"function",function:{name:t.name,arguments:t.arguments}}],content:""};if(t.type==="function_call_output")return{role:"tool",content:t.output,tool_call_id:t.call_id};if(t.type==="message")return{id:"id"in t?t.id:void 0,role:t.role,content:typeof t.content=="string"?t.content:t.content?.map(e=>e.type==="input_text"||e.type==="output_text"?e.text:"").join(" ")??""};throw new Error(`Unknown item type: ${t.type}`)}var hWe=class extends pWe{constructor(e,l,I,n){super(e,l,I,n)}};c();var Ixe=class extends qNe{constructor(e){super(e)}setInitiatorHeader(e){}listModels(){return Promise.resolve([])}},ZWe=class{async createClient(e,l,I){l.startGroup("configured settings:",8),l.debug(JSON.stringify(e,null,2)),l.endGroup(8);let n=e.api?.openai?.apiKey,r=e.api?.openai?.azureKeyVaultUri,a=e.api?.openai?.azureSecretName;if(!n&&r){l.debug("No API_KEY provided, trying secret provider");let G=$3e(r,l);try{n=await G.getSecret(a||"azure-openai-api-key")}catch(u){l.debug(`Failed to get API Key from secret provider:
1432
- ${u}`)}}let s=Zlt(e);l.debug(`Using Azure Open API at ${s}`);let d={baseURL:`${new URL(s).origin}/openai`,apiVersion:e.api?.openai?.azure?.apiVersion||"2024-10-21",deployment:I?.model,defaultHeaders:I?.requestHeaders};if(n)d={...d,apiKey:n},l.debug("Using Azure OpenAI API Key");else{let G=new t1,h=lke(G,"https://cognitiveservices.azure.com/.default");d={...d,azureADTokenProvider:h},l.debug("Using Azure Managed Identity")}return new Ixe(d)}};c();var nxe=class extends $Ne{constructor(e){super(e)}setInitiatorHeader(e){}listModels(){return Promise.resolve([])}},NWe=class{async createClient(e,l,I){l.startGroup("configured settings:",8),l.debug(JSON.stringify(e,null,2)),l.endGroup(8);let n=hlt(e),r=e.api?.openai?.baseUrl,a=I?.requestHeaders;return new nxe({baseURL:r,apiKey:n,defaultHeaders:a})}};function rxe(t,e,l,I){switch(I?.thinkingMode===void 0&&lc(t,"copilot_swe_agent_thinking_mode")&&(I={...I,thinkingMode:!0}),l){case"sweagent-aip":return new lZe(t,e,I);case"sweagent-anthropic":return new ANe(t,e,I);case"sweagent-capi":return new jne(t,e,I);case"sweagent-openai":return I?.thinkingMode?new hWe(jEt(t),t,e,I):new uWe(jEt(t),t,e,I);default:return new jne(t,e,I)}}function jEt(t){return t.api?.openai?.azure?.url?new ZWe:new NWe}c();c();function DD(t){return t.kind==="message"&&t.message.role==="assistant"}function PEt(t){return t.kind==="message"&&t.message.role==="user"}function WWe(t){return t.kind==="message"&&t.message.role==="assistant"&&!!t.message.tool_calls}function gWe(t){return t.kind==="message"&&t.message.role==="tool"}function FTl(t,e){return t.toolCalls.find(l=>l.toolCallId===e)}function vTl(t,e){let l=e.function.name;try{let I=JSON.parse(e.function.arguments||"{}"),r=t.find(a=>a.name===l)?.safeForTelemetry||{name:!1,inputsNames:!1};return{toolCallId:e.id,toolName:l,arguments:e.function.arguments,safeForTelemetryToolName:r===!0||r.name?l:Jk(l),safeForTelemetryArguments:r===!0||r.inputsNames?CRt(I):""}}catch{return{toolCallId:e.id,toolName:l,arguments:e.function.arguments,safeForTelemetryToolName:Jk(l),safeForTelemetryArguments:""}}}var AWe=class{forAgent;turnDataCache;emittedTurns=new Set;callback;settings;toolsInUse;constructor(e,l,I,n){this.forAgent=e,this.turnDataCache=new Map,this.emittedTurns=new Set,this.callback=l,this.settings=I,this.toolsInUse=n}getTurnData(){return this.turnDataCache}async ingestEvent(e){let l,I;if("turn"in e&&typeof e.turn=="number"){if(l=e.turn+1,this.emittedTurns.has(l))return;this.turnDataCache.has(l)||this.turnDataCache.set(l,{featureFlagsAsString:Owe(this.settings),toolCalls:[],toolCallExecutions:[],turn:l}),I=this.turnDataCache.get(l)}else return;e.kind==="tool_execution"?await this.ingestToolExecutionEventAndEmitToolCallExecutedTelemetry(I,e):e.kind==="turn_started"||e.kind==="turn_failed"||e.kind==="turn_retry"||e.kind==="turn_ended"?(I={...I,model:e.model,modelInfo:JSON.stringify(e.modelInfo)},e.kind==="turn_started"?I={...I,startTimeMs:e.timestampMs}:e.kind==="turn_retry"?I={...I,endTimeMs:e.timestampMs,retriesUsed:(I.retriesUsed??0)+1}:e.kind==="turn_failed"?I={...I,endTimeMs:e.timestampMs,error:e.error}:e.kind==="turn_ended"&&(I={...I,endTimeMs:e.timestampMs})):e.kind==="history_truncated"?I={...I,truncateEvent:e}:e.kind==="image_processing"?I={...I,imageProcessingMetrics:e.imageProcessingMetrics}:e.kind==="images_removed"?I={...I,largeImagesRemoved:(I.largeImagesRemoved??0)+(e.largeImagesRemoved?1:0),imagesRemoved:(I.imagesRemoved??0)+(e.imagesRemoved?1:0)}:e.kind==="model_call_success"||e.kind==="model_call_failure"?(I={...I,modelCallDurationMs:e.modelCallDurationMs,api_call_id:e.modelCall.api_id,provider_call_id:e.modelCall.request_id,conversationStructureSummary:_mt(e.requestMessages)},e.kind==="model_call_success"&&(I={...I,responsePromptTokens:e.responseUsage?.prompt_tokens,responseCompletionTokens:e.responseUsage?.completion_tokens,responseTotalTokens:e.responseUsage?.total_tokens})):PEt(e)&&e.source==="jit-instruction"?I={...I,jitInstructionsAdded:(I?.jitInstructionsAdded??0)+1}:DD(e)&&e.message.tool_calls?I={...I,toolCalls:I.toolCalls.concat(e.message.tool_calls.map(n=>({...vTl(this.toolsInUse,n)})))}:gWe(e)&&(I={...I,toolCallExecutions:I.toolCallExecutions.concat([e.message.tool_call_id])}),this.turnDataCache.set(l,I),e.kind==="turn_ended"&&(await this.emitTurnTelemetry(l),this.emittedTurns.add(l),this.turnDataCache.delete(l))}async emitTurnTelemetry(e){let l=this.turnDataCache.get(e);if(l){let I={kind:"telemetry",telemetry:{event:"get_completion_with_tools_turn",properties:{model:l.model||"default",modelInfo:l.modelInfo||"{}",api_call_id:l.api_call_id,provider_call_id:l.provider_call_id,agent:this.forAgent,toolCalls:JSON.stringify(l.toolCalls.map(n=>({toolCallId:n.toolCallId,toolName:n.safeForTelemetryToolName}))),toolCallExecutions:JSON.stringify(l.toolCallExecutions),error:l.error,featureFlags:Owe(this.settings),conversationStructureSummary:l.conversationStructureSummary,truncationPerformedBy:l.truncateEvent?.performedBy},metrics:{turn:e,turnDurationMs:l.endTimeMs!==void 0&&l.startTimeMs!==void 0?l.endTimeMs-l.startTimeMs:0,modelCallDurationMs:l.modelCallDurationMs,retriesUsed:l.retriesUsed??0,numToolCalls:l.toolCalls.length,numToolExecutions:l.toolCallExecutions.length,largeImagesRemoved:l.largeImagesRemoved,imagesRemoved:l.imagesRemoved,responsePromptTokens:l.responsePromptTokens,responseCompletionTokens:l.responseCompletionTokens,responseTotalTokens:l.responseTotalTokens,jitInstructionsAdded:l.jitInstructionsAdded,...l.truncateEvent?.truncateResult,...l.imageProcessingMetrics},restrictedProperties:{}}};await this.callback.progress(I)}}async ingestToolExecutionEventAndEmitToolCallExecutedTelemetry(e,l){let I=l.toolCallId,n=FTl(e,I);if(n){let r=l.toolResult,a={kind:"telemetry",telemetry:{event:"tool_call_executed",properties:{...r.toolTelemetry.properties,resultType:r.resultType,toolCallId:I,arguments:n.safeForTelemetryArguments,toolName:n.safeForTelemetryToolName,api_call_id:e.api_call_id},restrictedProperties:{...r.toolTelemetry.restrictedProperties,arguments:n.arguments,toolName:n.toolName,error:r.error},metrics:{...r.toolTelemetry.metrics,durationMs:l.durationMs}}};await this.callback.progress(a)}}};c();var Pne=class{async*preRequest(e){yield*[]}handleCallbackResponse(e){}getUserMessages(){return[]}clearUserMessages(){}canProcessUserMessages(){return!1}toJSON(){return JSON.stringify({type:"NoopUserMessageProcessor"})}};var yWe=class{constructor(e,l){this.runtimeContext=e;this.subAgentName=l;this.gitHandlers={silent:new UZ(new Bh,this.runtimeContext.exec),logging:new UZ(this.runtimeContext.logger,this.runtimeContext.exec)}}gitHandlers;async agent(e,l,I,n,r,a,s=new Pne,o){let d=async(W,y,R)=>{let w={role:"user",content:W};return await this.runtimeContext.callback?.progress({kind:"message",message:w,turn:0}),await this.runCompletionWithTools(e,l,[...y??[],w],a,r,{executeToolsInParallel:lc(this.runtimeContext.settings,"copilot_swe_agent_parallel_tool_execution"),initialTurnCount:R},o,s)},G=n,u=I??[],h;for(;G;){let W=await d(G,u,h);h=W.finalTurnCount,u=W.messages,G=await o?.onResult(W.postCompletionWithToolsCommitHash)}for(let W of a)if(W.shutdown){let y=await W.shutdown();y&&await this.runtimeContext.callback?.progress(y)}return{finalTurnCount:h||0,messages:u}}async runCompletionWithTools(e,l,I,n,r,a,s,o=new Pne){let d=this.runtimeContext.callback?new AWe("sweagent-capi",this.runtimeContext.callback,this.runtimeContext.settings,n):void 0,G=this.gitHandlers.logging,u=await G.getCurrentCommitHash(e),h=I.filter(S=>S.role==="user").at(-1),W=this.createCompletionWithToolsProcessors(e,u,n,o,r,s,h),y=this.runtimeContext.client.getCompletionWithTools(l,I,n,{...a,processors:W}),R=0,w=[...I],v=[];for await(let S of y){if(lc(this.runtimeContext.settings,"copilot_swe_agent_progress_commands")){let B=await this.runtimeContext.callback?.progress(S,{accepts_user_messages:o.canProcessUserMessages()});o.handleCallbackResponse(B)}else S.kind==="response"?await this.runtimeContext.callback?.progress({...S,subAgentName:this.subAgentName}):await this.runtimeContext.callback?.progress(S);d&&await d.ingestEvent(S),(S.kind==="message"||S.kind==="response")&&(S.kind==="message"&&w.push(S.message),S.kind==="response"&&v.push(S.response),R=Math.max(R,S.turn??0))}let f=await G.getCurrentCommitHash(e);return{finalTurnCount:R,messages:w,resultMessages:v,preCompletionWithToolsCommitHash:u,postCompletionWithToolsCommitHash:f}}createCompletionWithToolsProcessors(e,l,I,n,r,a,s){let o=new Jue(this.runtimeContext.logger,this.runtimeContext.settings,I.find(W=>W.name==="github-mcp-server-get_file_contents")),d=new Lue(this.runtimeContext.settings,this.runtimeContext.logger,this.gitHandlers.silent,e,l,r),G=new Vz(this.runtimeContext.logger),u=s?new wz(s,this.runtimeContext.logger):void 0,h=[d,o,G,u];return lc(this.runtimeContext.settings,"copilot_swe_agent_progress_commands")&&h.push(n),{preRequest:h.filter(W=>W!==void 0),preToolsExecution:[a].filter(W=>W!==void 0),postToolExecution:[o,a].filter(W=>W!==void 0),onRequestError:[o,u].filter(W=>W!==void 0)}}};c();async function axe(t,e,l,I,n){try{return(await I.invokeTool("blackbird-mcp-server/search_repository_with_agent",{task:t,depth:2,owner:e,repo:l,numSnippets:10},"hidden_characters")).textResultForLlm}catch(r){return n.error(`Error during Blackbird search: ${r}`),""}}var qEt=t=>lc(t,"copilot_swe_agent_search")||llt(t,"SearchAgentExperiment")==="enabled",KEt="search";function sxe(t){return t!==null&&typeof t=="object"&&"question"in t&&"reason"in t&&"searchCommand"in t}var QTl=(t,e,l)=>`
1433
+ ${u}`)}}let s=Zlt(e);l.debug(`Using Azure Open API at ${s}`);let d={baseURL:`${new URL(s).origin}/openai`,apiVersion:e.api?.openai?.azure?.apiVersion||"2024-10-21",deployment:I?.model,defaultHeaders:I?.requestHeaders};if(n)d={...d,apiKey:n},l.debug("Using Azure OpenAI API Key");else{let G=new t1,h=lke(G,"https://cognitiveservices.azure.com/.default");d={...d,azureADTokenProvider:h},l.debug("Using Azure Managed Identity")}return new Ixe(d)}};c();var nxe=class extends $Ne{constructor(e){super(e)}setInitiatorHeader(e){}listModels(){return Promise.resolve([])}},NWe=class{async createClient(e,l,I){l.startGroup("configured settings:",8),l.debug(JSON.stringify(e,null,2)),l.endGroup(8);let n=hlt(e),r=e.api?.openai?.baseUrl,a=I?.requestHeaders;return new nxe({baseURL:r,apiKey:n,defaultHeaders:a})}};function rxe(t,e,l,I){switch(I?.thinkingMode===void 0&&lc(t,"copilot_swe_agent_thinking_mode")&&(I={...I,thinkingMode:!0}),l){case"sweagent-aip":return new lZe(t,e,I);case"sweagent-anthropic":return new ANe(t,e,I);case"sweagent-capi":return new jne(t,e,I);case"sweagent-openai":return I?.thinkingMode?new hWe(jEt(t),t,e,I):new uWe(jEt(t),t,e,I);default:return new jne(t,e,I)}}function jEt(t){return t.api?.openai?.azure?.url?new ZWe:new NWe}c();c();function DD(t){return t.kind==="message"&&t.message.role==="assistant"}function PEt(t){return t.kind==="message"&&t.message.role==="user"}function WWe(t){return t.kind==="message"&&t.message.role==="assistant"&&!!t.message.tool_calls}function gWe(t){return t.kind==="message"&&t.message.role==="tool"}function FTl(t,e){return t.toolCalls.find(l=>l.toolCallId===e)}function vTl(t,e){let l=e.function.name;try{let I=JSON.parse(e.function.arguments||"{}"),r=t.find(a=>a.name===l)?.safeForTelemetry||{name:!1,inputsNames:!1};return{toolCallId:e.id,toolName:l,arguments:e.function.arguments,safeForTelemetryToolName:r===!0||r.name?l:Jk(l),safeForTelemetryArguments:r===!0||r.inputsNames?CRt(I):""}}catch{return{toolCallId:e.id,toolName:l,arguments:e.function.arguments,safeForTelemetryToolName:Jk(l),safeForTelemetryArguments:""}}}var AWe=class{forAgent;turnDataCache;emittedTurns=new Set;callback;settings;toolsInUse;constructor(e,l,I,n){this.forAgent=e,this.turnDataCache=new Map,this.emittedTurns=new Set,this.callback=l,this.settings=I,this.toolsInUse=n}getTurnData(){return this.turnDataCache}async ingestEvent(e){let l,I;if("turn"in e&&typeof e.turn=="number"){if(l=e.turn+1,this.emittedTurns.has(l))return;this.turnDataCache.has(l)||this.turnDataCache.set(l,{featureFlagsAsString:Owe(this.settings),toolCalls:[],toolCallExecutions:[],turn:l}),I=this.turnDataCache.get(l)}else return;e.kind==="tool_execution"?await this.ingestToolExecutionEventAndEmitToolCallExecutedTelemetry(I,e):e.kind==="turn_started"||e.kind==="turn_failed"||e.kind==="turn_retry"||e.kind==="turn_ended"?(I={...I,model:e.model,modelInfo:JSON.stringify(e.modelInfo)},e.kind==="turn_started"?I={...I,startTimeMs:e.timestampMs}:e.kind==="turn_retry"?I={...I,endTimeMs:e.timestampMs,retriesUsed:(I.retriesUsed??0)+1}:e.kind==="turn_failed"?I={...I,endTimeMs:e.timestampMs,error:e.error}:e.kind==="turn_ended"&&(I={...I,endTimeMs:e.timestampMs})):e.kind==="history_truncated"?I={...I,truncateEvent:e}:e.kind==="image_processing"?I={...I,imageProcessingMetrics:e.imageProcessingMetrics}:e.kind==="images_removed"?I={...I,largeImagesRemoved:(I.largeImagesRemoved??0)+(e.largeImagesRemoved?1:0),imagesRemoved:(I.imagesRemoved??0)+(e.imagesRemoved?1:0)}:e.kind==="model_call_success"||e.kind==="model_call_failure"?(I={...I,modelCallDurationMs:e.modelCallDurationMs,api_call_id:e.modelCall.api_id,provider_call_id:e.modelCall.request_id,conversationStructureSummary:_mt(e.requestMessages)},e.kind==="model_call_success"&&(I={...I,responsePromptTokens:e.responseUsage?.prompt_tokens,responseCompletionTokens:e.responseUsage?.completion_tokens,responseTotalTokens:e.responseUsage?.total_tokens})):PEt(e)&&e.source==="jit-instruction"?I={...I,jitInstructionsAdded:(I?.jitInstructionsAdded??0)+1}:DD(e)&&e.message.tool_calls?I={...I,toolCalls:I.toolCalls.concat(e.message.tool_calls.map(n=>({...vTl(this.toolsInUse,n)})))}:gWe(e)&&(I={...I,toolCallExecutions:I.toolCallExecutions.concat([e.message.tool_call_id])}),this.turnDataCache.set(l,I),e.kind==="turn_ended"&&(await this.emitTurnTelemetry(l),this.emittedTurns.add(l),this.turnDataCache.delete(l))}async emitTurnTelemetry(e){let l=this.turnDataCache.get(e);if(l){let I={kind:"telemetry",telemetry:{event:"get_completion_with_tools_turn",properties:{model:l.model||"default",modelInfo:l.modelInfo||"{}",api_call_id:l.api_call_id,provider_call_id:l.provider_call_id,agent:this.forAgent,toolCalls:JSON.stringify(l.toolCalls.map(n=>({toolCallId:n.toolCallId,toolName:n.safeForTelemetryToolName}))),toolCallExecutions:JSON.stringify(l.toolCallExecutions),error:l.error,featureFlags:Owe(this.settings),conversationStructureSummary:l.conversationStructureSummary,truncationPerformedBy:l.truncateEvent?.performedBy},metrics:{turn:e,turnDurationMs:l.endTimeMs!==void 0&&l.startTimeMs!==void 0?l.endTimeMs-l.startTimeMs:0,modelCallDurationMs:l.modelCallDurationMs,retriesUsed:l.retriesUsed??0,numToolCalls:l.toolCalls.length,numToolExecutions:l.toolCallExecutions.length,largeImagesRemoved:l.largeImagesRemoved,imagesRemoved:l.imagesRemoved,responsePromptTokens:l.responsePromptTokens,responseCompletionTokens:l.responseCompletionTokens,responseTotalTokens:l.responseTotalTokens,jitInstructionsAdded:l.jitInstructionsAdded,...l.truncateEvent?.truncateResult,...l.imageProcessingMetrics},restrictedProperties:{}}};await this.callback.progress(I)}}async ingestToolExecutionEventAndEmitToolCallExecutedTelemetry(e,l){let I=l.toolCallId,n=FTl(e,I);if(n){let r=l.toolResult,a={kind:"telemetry",telemetry:{event:"tool_call_executed",properties:{...r.toolTelemetry.properties,resultType:r.resultType,toolCallId:I,arguments:n.safeForTelemetryArguments,toolName:n.safeForTelemetryToolName,api_call_id:e.api_call_id},restrictedProperties:{...r.toolTelemetry.restrictedProperties,arguments:n.arguments,toolName:n.toolName,error:r.error},metrics:{...r.toolTelemetry.metrics,durationMs:l.durationMs}}};await this.callback.progress(a)}}};c();var Pne=class{async*preRequest(e){yield*[]}handleCallbackResponse(e){}getUserMessages(){return[]}clearUserMessages(){}canProcessUserMessages(){return!1}toJSON(){return JSON.stringify({type:"NoopUserMessageProcessor"})}};var yWe=class{constructor(e,l){this.runtimeContext=e;this.customAgentName=l;this.gitHandlers={silent:new UZ(new Bh,this.runtimeContext.exec),logging:new UZ(this.runtimeContext.logger,this.runtimeContext.exec)}}gitHandlers;async agent(e,l,I,n,r,a,s=new Pne,o){let d=async(W,y,R)=>{let w={role:"user",content:W};return await this.runtimeContext.callback?.progress({kind:"message",message:w,turn:0}),await this.runCompletionWithTools(e,l,[...y??[],w],a,r,{executeToolsInParallel:lc(this.runtimeContext.settings,"copilot_swe_agent_parallel_tool_execution"),initialTurnCount:R},o,s)},G=n,u=I??[],h;for(;G;){let W=await d(G,u,h);h=W.finalTurnCount,u=W.messages,G=await o?.onResult(W.postCompletionWithToolsCommitHash)}for(let W of a)if(W.shutdown){let y=await W.shutdown();y&&await this.runtimeContext.callback?.progress(y)}return{finalTurnCount:h||0,messages:u}}async runCompletionWithTools(e,l,I,n,r,a,s,o=new Pne){let d=this.runtimeContext.callback?new AWe("sweagent-capi",this.runtimeContext.callback,this.runtimeContext.settings,n):void 0,G=this.gitHandlers.logging,u=await G.getCurrentCommitHash(e),h=I.filter(S=>S.role==="user").at(-1),W=this.createCompletionWithToolsProcessors(e,u,n,o,r,s,h),y=this.runtimeContext.client.getCompletionWithTools(l,I,n,{...a,processors:W}),R=0,w=[...I],v=[];for await(let S of y){if(lc(this.runtimeContext.settings,"copilot_swe_agent_progress_commands")){let B=await this.runtimeContext.callback?.progress(S,{accepts_user_messages:o.canProcessUserMessages()});o.handleCallbackResponse(B)}else S.kind==="response"?await this.runtimeContext.callback?.progress({...S,customAgentName:this.customAgentName}):await this.runtimeContext.callback?.progress(S);d&&await d.ingestEvent(S),(S.kind==="message"||S.kind==="response")&&(S.kind==="message"&&w.push(S.message),S.kind==="response"&&v.push(S.response),R=Math.max(R,S.turn??0))}let f=await G.getCurrentCommitHash(e);return{finalTurnCount:R,messages:w,resultMessages:v,preCompletionWithToolsCommitHash:u,postCompletionWithToolsCommitHash:f}}createCompletionWithToolsProcessors(e,l,I,n,r,a,s){let o=new Jue(this.runtimeContext.logger,this.runtimeContext.settings,I.find(W=>W.name==="github-mcp-server-get_file_contents")),d=new Lue(this.runtimeContext.settings,this.runtimeContext.logger,this.gitHandlers.silent,e,l,r),G=new Vz(this.runtimeContext.logger),u=s?new wz(s,this.runtimeContext.logger):void 0,h=[d,o,G,u];return lc(this.runtimeContext.settings,"copilot_swe_agent_progress_commands")&&h.push(n),{preRequest:h.filter(W=>W!==void 0),preToolsExecution:[a].filter(W=>W!==void 0),postToolExecution:[o,a].filter(W=>W!==void 0),onRequestError:[o,u].filter(W=>W!==void 0)}}};c();async function axe(t,e,l,I,n){try{return(await I.invokeTool("blackbird-mcp-server/search_repository_with_agent",{task:t,depth:2,owner:e,repo:l,numSnippets:10},"hidden_characters")).textResultForLlm}catch(r){return n.error(`Error during Blackbird search: ${r}`),""}}var qEt=t=>lc(t,"copilot_swe_agent_search")||llt(t,"SearchAgentExperiment")==="enabled",KEt="search";function sxe(t){return t!==null&&typeof t=="object"&&"question"in t&&"reason"in t&&"searchCommand"in t}var QTl=(t,e,l)=>`
1433
1434
  You are a question answering agent that is a component of GitHub Copilot coding agent. Your task is to take the given question
1434
1435
  and answer it using the given facts.
1435
1436
 
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.327-1",
4
+ "version": "0.0.328",
5
5
  "type": "module",
6
6
  "repository": {
7
7
  "type": "git",
@@ -26,7 +26,7 @@
26
26
  "tree-sitter-powershell.wasm"
27
27
  ],
28
28
  "buildMetadata": {
29
- "gitCommit": "837833d"
29
+ "gitCommit": "3755a93"
30
30
  },
31
31
  "dependencies": {
32
32
  "node-pty": "npm:@devm33/node-pty@^1.0.8",