billion-context 0.1.210 → 0.1.211

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.
@@ -126,7 +126,7 @@ ${captureLines}`:capture2.stack}module.exports.fetch=function fetch2(init,option
126
126
  `,n=Buffer.byteLength(r),o=Math.floor(Math.log(n)/Math.log(10))+1;return n+o>=Math.pow(10,o)&&(o+=1),o+n+r}static parse(t,e,i=false){return new s(On(Tn(t),e),i)}};On=(s3,t)=>t?Object.assign({},t,s3):s3;Tn=s3=>s3.replace(/\n$/,"").split(`
127
127
  `).reduce(xn,Object.create(null));xn=(s3,t)=>{let e=parseInt(t,10);if(e!==Buffer.byteLength(t)+1)return s3;t=t.slice((e+" ").length);let i=t.split("="),r=i.shift();if(!r)return s3;let n=r.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),o=i.join("=").replace(/\0.*/,"");switch(n){case"path":case"linkpath":case"type":case"charset":case"comment":case"gname":case"uname":s3[n]=o;break;case"ctime":case"atime":case"mtime":s3[n]=new Date(Number(o)*1e3);break;case"size":let h=+o;h>=0&&(s3[n]=h);break;case"gid":case"uid":case"dev":case"ino":case"nlink":case"mode":s3[n]=+o;break}return s3};Ln=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform;f=Ln!=="win32"?s3=>String(s3):s3=>String(s3).replaceAll(/\\/g,"/");$e=class extends A{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=false;ignore=false;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=false;absolute;unsupported=false;constructor(t,e,i){switch(super({}),this.pause(),this.extended=e,this.globalExtended=i,this.header=t,this.remain=t.size??0,this.startBlockSize=512*Math.ceil(this.remain/512),this.blockRemain=this.startBlockSize,this.type=t.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=true;break;default:this.ignore=true}if(!t.path)throw new Error("no path provided for tar.ReadEntry");this.path=f(t.path),this.mode=t.mode,this.mode&&(this.mode=this.mode&4095),this.uid=t.uid,this.gid=t.gid,this.uname=t.uname,this.gname=t.gname,this.size=this.remain,this.mtime=t.mtime,this.atime=t.atime,this.ctime=t.ctime,this.linkpath=t.linkpath?f(t.linkpath):void 0,this.uname=t.uname,this.gname=t.gname,e&&this.#t(e),i&&this.#t(i,true)}write(t){let e=t.length;if(e>this.blockRemain)throw new Error("writing more to entry than is appropriate");let i=this.remain,r=this.blockRemain;return this.remain=Math.max(0,i-e),this.blockRemain=Math.max(0,r-e),this.ignore?true:i>=e?super.write(t):super.write(t.subarray(0,i))}#t(t,e=false){t.path&&(t.path=f(t.path)),t.linkpath&&(t.linkpath=f(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([i,r])=>!(r==null||i==="path"&&e))))}};Dt=(s3,t,e,i={})=>{s3.file&&(i.file=s3.file),s3.cwd&&(i.cwd=s3.cwd),i.code=e instanceof Error&&e.code||t,i.tarCode=t,!s3.strict&&i.recoverable!==false?(e instanceof Error&&(i=Object.assign(e,i),e=e.message),s3.emit("warn",t,e,i)):e instanceof Error?s3.emit("error",Object.assign(e,i)):s3.emit("error",Object.assign(new Error(`${t}: ${e}`),i))};Nn=1024*1024;Xi=Buffer.from([31,139]);qi=Buffer.from([40,181,47,253]);An=Math.max(Xi.length,qi.length);B=Symbol("state");Nt=Symbol("writeEntry");it=Symbol("readEntry");Zi=Symbol("nextEntry");Zs=Symbol("processEntry");V=Symbol("extendedHeader");he=Symbol("globalExtendedHeader");dt=Symbol("meta");Ys=Symbol("emitMeta");p=Symbol("buffer");st=Symbol("queue");ut=Symbol("ended");Yi=Symbol("emittedEnd");At=Symbol("emit");w=Symbol("unzip");Xe=Symbol("consumeChunk");qe=Symbol("consumeChunkSub");Ki=Symbol("consumeBody");Ks=Symbol("consumeMeta");Vs=Symbol("consumeHeader");ae=Symbol("consuming");Vi=Symbol("bufferConcat");Qe=Symbol("maybeEnd");Yt=Symbol("writing");$=Symbol("aborted");Je=Symbol("onDone");It=Symbol("sawValidEntry");je=Symbol("sawNullBlock");ti=Symbol("sawEOF");$s=Symbol("closeStream");In=1e3;le=Symbol("compressedBytesRead");$i=Symbol("decompressedBytesRead");Xs=Symbol("checkDecompressionRatio");Cn=()=>true;rt=class extends Dn{file;strict;maxMetaEntrySize;filter;brotli;zstd;maxDecompressionRatio;writable=true;readable=false;[st]=[];[p];[it];[Nt];[B]="begin";[dt]="";[V];[he];[ut]=false;[w];[$]=false;[It];[je]=false;[ti]=false;[Yt]=false;[ae]=false;[Yi]=false;[le]=0;[$i]=0;constructor(t={}){super(),this.file=t.file||"",this.on(Je,()=>{(this[B]==="begin"||this[It]===false)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(Je,t.ondone):this.on(Je,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxDecompressionRatio=typeof t.maxDecompressionRatio=="number"?t.maxDecompressionRatio:In,this.maxMetaEntrySize=t.maxMetaEntrySize||Nn,this.filter=typeof t.filter=="function"?t.filter:Cn;let e=t.file&&(t.file.endsWith(".tar.br")||t.file.endsWith(".tbr"));this.brotli=!(t.gzip||t.zstd)&&t.brotli!==void 0?t.brotli:e?void 0:false;let i=t.file&&(t.file.endsWith(".tar.zst")||t.file.endsWith(".tzst"));this.zstd=!(t.gzip||t.brotli)&&t.zstd!==void 0?t.zstd:i?true:void 0,this.on("end",()=>this[$s]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,i={}){Dt(this,t,e,i)}[Vs](t,e){this[It]===void 0&&(this[It]=false);let i;try{i=new F(t,e,this[V],this[he])}catch(r){return this.warn("TAR_ENTRY_INVALID",r)}if(i.nullBlock)this[je]?(this[ti]=true,this[B]==="begin"&&(this[B]="header"),this[At]("eof")):(this[je]=true,this[At]("nullBlock"));else if(this[je]=false,!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 r=i.type;if(/^(Symbolic)?Link$/.test(r)&&!i.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:i});else if(!/^(Symbolic)?Link$/.test(r)&&!/^(Global)?ExtendedHeader$/.test(r)&&i.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:i});else{let n=this[Nt]=new $e(i,this[V],this[he]);if(!this[It])if(n.remain){let o=()=>{n.invalid||(this[It]=true)};n.on("end",o)}else this[It]=true;n.meta?n.size>this.maxMetaEntrySize?(n.ignore=true,this[At]("ignoredEntry",n),this[B]="ignore",n.resume()):n.size>0&&(this[dt]="",n.on("data",o=>this[dt]+=o),this[B]="meta"):(this[V]=void 0,n.ignore=n.ignore||!this.filter(n.path,n),n.ignore?(this[At]("ignoredEntry",n),this[B]=n.remain?"ignore":"header",n.resume()):(n.remain?this[B]="body":(this[B]="header",n.end()),this[it]?this[st].push(n):(this[st].push(n),this[Zi]())))}}}[$s](){queueMicrotask(()=>this.emit("close"))}[Zs](t){let e=true;if(!t)this[it]=void 0,e=false;else if(Array.isArray(t)){let[i,...r]=t;this.emit(i,...r)}else this[it]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[Zi]()),e=false);return e}[Zi](){do;while(this[Zs](this[st].shift()));if(this[st].length===0){let t=this[it];!t||t.flowing||t.size===t.remain?this[Yt]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[Ki](t,e){let i=this[Nt];if(!i)throw new Error("attempt to consume body without entry??");let r=i.blockRemain??0,n=r>=t.length&&e===0?t:t.subarray(e,e+r);return i.write(n),i.blockRemain||(this[B]="header",this[Nt]=void 0,i.end()),n.length}[Ks](t,e){let i=this[Nt],r=this[Ki](t,e);return!this[Nt]&&i&&this[Ys](i),r}[At](t,e,i){this[st].length===0&&!this[it]?this.emit(t,e,i):this[st].push([t,e,i])}[Ys](t){switch(this[At]("meta",this[dt]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[V]=ft.parse(this[dt],this[V],false);break;case"GlobalExtendedHeader":this[he]=ft.parse(this[dt],this[he],true);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[V]??Object.create(null);this[V]=e,e.path=this[dt].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[V]||Object.create(null);this[V]=e,e.linkpath=this[dt].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){if(!this[$]){if(this[w]){let e=this[w];e.write=()=>true,e.end=()=>e,e.emit=()=>false,e.destroy?.()}this[$]=true,this.emit("abort",t),this.warn("TAR_ABORT",t,{recoverable:false})}}[Xs](t){this[$i]+=t.length;let e=this[$i]/this[le];return e>this.maxDecompressionRatio?(this.abort(new Error(`max decompression ratio exceeded: ${e.toFixed(2)} > ${this.maxDecompressionRatio}`)),false):true}write(t,e,i){if(typeof e=="function"&&(i=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this[$])return i?.(),false;if((this[w]===void 0||this.brotli===void 0&&this[w]===false)&&t){if(this[p]&&(t=Buffer.concat([this[p],t]),this[p]=void 0),t.length<An)return this[p]=t,i?.(),true;for(let a=0;this[w]===void 0&&a<Xi.length;a++)t[a]!==Xi[a]&&(this[w]=false);let o=false;if(this[w]===false&&this.zstd!==false){o=true;for(let a=0;a<qi.length;a++)if(t[a]!==qi[a]){o=false;break}}let h=this.brotli===void 0&&!o;if(this[w]===false&&h)if(t.length<512)if(this[ut])this.brotli=true;else return this[p]=t,i?.(),true;else try{new F(t.subarray(0,512)),this.brotli=false}catch{this.brotli=true}if(this[w]===void 0||this[w]===false&&(this.brotli||o)){let a=this[ut];this[ut]=false,this[w]=this[w]===void 0?new Ue({}):o?new Ke({}):new Ge({}),this[w].on("data",c=>{this[Xs](c)&&this[Xe](c)}),this[w].on("error",c=>{this[$]||this.abort(c)}),this[w].on("end",()=>{this[ut]=true,this[Xe]()}),this[Yt]=true,this[le]+=t.length;let l4=!!this[w][a?"end":"write"](t);return this[Yt]=false,i?.(),l4}}this[Yt]=true,this[w]?(this[le]+=t.length,this[w].write(t)):this[Xe](t),this[Yt]=false;let n=this[st].length>0?false:this[it]?this[it].flowing:true;return!n&&this[st].length===0&&this[it]?.once("drain",()=>this.emit("drain")),i?.(),n}[Vi](t){t&&!this[$]&&(this[p]=this[p]?Buffer.concat([this[p],t]):t)}[Qe](){if(this[ut]&&!this[Yi]&&!this[$]&&!this[ae]){this[Yi]=true;let t=this[Nt];if(t?.blockRemain){let e=this[p]?this[p].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[p]&&t.write(this[p]),t.end()}this[At](Je)}}[Xe](t){if(this[ae]&&t)this[Vi](t);else if(!t&&!this[p])this[Qe]();else if(t){if(this[ae]=true,this[p]){this[Vi](t);let e=this[p];this[p]=void 0,this[qe](e)}else this[qe](t);for(;this[p]&&this[p]?.length>=512&&!this[$]&&!this[ti];){let e=this[p];this[p]=void 0,this[qe](e)}this[ae]=false}(!this[p]||this[ut])&&this[Qe]()}[qe](t){let e=0,i=t.length;for(;e+512<=i&&!this[$]&&!this[ti];)switch(this[B]){case"begin":case"header":this[Vs](t,e),e+=512;break;case"ignore":case"body":e+=this[Ki](t,e);break;case"meta":e+=this[Ks](t,e);break;default:throw new Error("invalid state: "+this[B])}e<i&&(this[p]=this[p]?Buffer.concat([t.subarray(e),this[p]]):t.subarray(e))}end(t,e,i){return typeof t=="function"&&(i=t,e=void 0,t=void 0),typeof e=="function"&&(i=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e)),i&&this.once("finish",i),this[$]||(this[w]?(t&&(this[le]+=t.length,this[w].write(t)),this[w].end()):(this[ut]=true,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[Qe]())),this}};mt=s3=>{let t=s3.length-1,e=-1;for(;t>-1&&s3.charAt(t)==="/";)e=t,t--;return e===-1?s3:s3.slice(0,e)};vn=s3=>{let t=s3.onReadEntry;s3.onReadEntry=t?e=>{t(e),e.resume()}:e=>e.resume()};Qi=(s3,t)=>{let e=new Map(t.map(o=>[mt(o),true])),i=s3.filter,r=100,n=(o,h="",a=0)=>{if(a>=r)return e.set(o,false),false;let l4=h||kn(o).root||".",c;if(o===l4)c=false;else{let d3=e.get(o);c=d3!==void 0?d3:n(Fn(o),l4,a+1)}return e.set(o,c),c};s3.filter=i?(o,h)=>i(o,h)&&n(mt(o)):o=>n(mt(o))};Mn=s3=>{let t=new rt(s3),e=s3.file,i;try{i=Kt.openSync(e,"r");let r=Kt.fstatSync(i),n=s3.maxReadSize||16*1024*1024;if(r.size<n){let o=Buffer.allocUnsafe(r.size),h=Kt.readSync(i,o,0,r.size,0);t.end(h===o.byteLength?o:o.subarray(0,h))}else{let o=0,h=Buffer.allocUnsafe(n);for(;o<r.size;){let a=Kt.readSync(i,h,0,n,o);if(a===0)break;o+=a,t.write(h.subarray(0,a))}t.end()}}finally{if(typeof i=="number")try{Kt.closeSync(i)}catch{}}};Bn=(s3,t)=>{let e=new rt(s3),i=s3.maxReadSize||16*1024*1024,r=s3.file;return new Promise((o,h)=>{e.on("error",h),e.on("end",o),Kt.stat(r,(a,l4)=>{if(a)h(a);else{let c=new _t(r,{readSize:i,size:l4.size});c.on("error",h),c.pipe(e)}})})};Ct=K(Mn,Bn,s3=>new rt(s3),s3=>new rt(s3),(s3,t)=>{t?.length&&Qi(s3,t),s3.noResume||vn(s3)});Ji=(s3,t,e)=>(s3&=4095,e&&(s3=(s3|384)&-19),t&&(s3&256&&(s3|=64),s3&32&&(s3|=8),s3&4&&(s3|=1)),s3);({isAbsolute:zn,parse:qs}=Pn);ce=s3=>{let t="",e=qs(s3);for(;zn(s3)||e.root;){let i=s3.charAt(0)==="/"&&s3.slice(0,4)!=="//?/"?"/":e.root;s3=s3.slice(i.length),t+=i,e=qs(s3)}return[t,s3]};ei=["|","<",">","?",":"];ji=ei.map(s3=>String.fromCodePoint(61440+Number(s3.codePointAt(0))));Un=new Map(ei.map((s3,t)=>[s3,ji[t]]));Hn=new Map(ji.map((s3,t)=>[s3,ei[t]]));ts=s3=>ei.reduce((t,e)=>t.split(e).join(Un.get(e)),s3);Qs=s3=>ji.reduce((t,e)=>t.split(e).join(Hn.get(e)),s3);rr=(s3,t)=>t?(s3=f(s3).replace(/^\.(\/|$)/,""),mt(t)+"/"+s3):f(s3);Wn=16*1024*1024;tr=Symbol("process");er=Symbol("file");ir=Symbol("directory");is=Symbol("symlink");sr=Symbol("hardlink");fe=Symbol("header");ii=Symbol("read");ss=Symbol("lstat");si=Symbol("onlstat");rs=Symbol("onread");ns=Symbol("onreadlink");os6=Symbol("openfile");hs=Symbol("onopenfile");pt=Symbol("close");ri=Symbol("mode");as=Symbol("awaitDrain");es=Symbol("ondrain");q=Symbol("prefix");de=class extends A{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;#t=false;constructor(t,e={}){let i=se(e);super(),this.path=f(t),this.portable=!!i.portable,this.maxReadSize=i.maxReadSize||Wn,this.linkCache=i.linkCache||new Map,this.statCache=i.statCache||new Map,this.preservePaths=!!i.preservePaths,this.cwd=f(i.cwd||process.cwd()),this.strict=!!i.strict,this.noPax=!!i.noPax,this.noMtime=!!i.noMtime,this.mtime=i.mtime,this.prefix=i.prefix?f(i.prefix):void 0,this.onWriteEntry=i.onWriteEntry,typeof i.onwarn=="function"&&this.on("warn",i.onwarn);let r=false;if(!this.preservePaths){let[o,h]=ce(this.path);o&&typeof h=="string"&&(this.path=h,r=o)}this.win32=!!i.win32||process.platform==="win32",this.win32&&(this.path=Qs(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=f(i.absolute||js.resolve(this.cwd,t)),this.path===""&&(this.path="./"),r&&this.warn("TAR_ENTRY_INFO",`stripping ${r} from absolute path`,{entry:this,path:r+this.path});let n=this.statCache.get(this.absolute);n?this[si](n):this[ss]()}warn(t,e,i={}){return Dt(this,t,e,i)}emit(t,...e){return t==="error"&&(this.#t=true),super.emit(t,...e)}[ss](){X.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[si](e)})}[si](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=Gn(t),this.emit("stat",t),this[tr]()}[tr](){switch(this.type){case"File":return this[er]();case"Directory":return this[ir]();case"SymbolicLink":return this[is]();default:return this.end()}}[ri](t){return Ji(t,this.type==="Directory",this.portable)}[q](t){return rr(t,this.prefix)}[fe](){if(!this.stat)throw new Error("cannot write header before stat");this.type==="Directory"&&this.portable&&(this.noMtime=true),this.onWriteEntry?.(this),this.header=new F({path:this[q](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[q](this.linkpath):this.linkpath,mode:this[ri](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 ft({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[q](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[q](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 t=this.header?.block;if(!t)throw new Error("failed to encode header");super.write(t)}[ir](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[fe](),this.end()}[is](){X.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[ns](e)})}[ns](t){this.linkpath=f(t),this[fe](),this.end()}[sr](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=f(js.relative(this.cwd,t)),this.stat.size=0,this[fe](),this.end()}[er](){if(!this.stat)throw new Error("cannot create file entry without stat");if(this.stat.nlink>1){let t=`${this.stat.dev}:${this.stat.ino}`,e=this.linkCache.get(t);if(e?.indexOf(this.cwd)===0)return this[sr](e);this.linkCache.set(t,this.absolute)}if(this[fe](),this.stat.size===0)return this.end();this[os6]()}[os6](){X.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[hs](e)})}[hs](t){if(this.fd=t,this.#t)return this[pt]();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 e=Math.min(this.blockLen,this.maxReadSize);this.buf=Buffer.allocUnsafe(e),this.offset=0,this.pos=0,this.remain=this.stat.size,this.length=this.buf.length,this[ii]()}[ii](){let{fd:t,buf:e,offset:i,length:r,pos:n}=this;if(t===void 0||e===void 0)throw new Error("cannot read file without first opening");X.read(t,e,i,r,n,(o,h)=>{if(o)return this[pt](()=>this.emit("error",o));this[rs](h)})}[pt](t=()=>{}){this.fd!==void 0&&X.close(this.fd,t)}[rs](t){if(t<=0&&this.remain>0){let r=Object.assign(new Error("encountered unexpected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[pt](()=>this.emit("error",r))}if(t>this.remain){let r=Object.assign(new Error("did not encounter expected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[pt](()=>this.emit("error",r))}if(!this.buf)throw new Error("should have created buffer prior to reading");if(t===this.remain)for(let r=t;r<this.length&&t<this.blockRemain;r++)this.buf[r+this.offset]=0,t++,this.remain++;let e=this.offset===0&&t===this.buf.length?this.buf:this.buf.subarray(this.offset,this.offset+t);this.write(e)?this[es]():this[as](()=>this[es]())}[as](t){this.once("drain",t)}write(t,e,i){if(typeof e=="function"&&(i=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this.blockRemain<t.length){let r=Object.assign(new Error("writing more data than expected"),{path:this.absolute});return this.emit("error",r)}return this.remain-=t.length,this.blockRemain-=t.length,this.pos+=t.length,this.offset+=t.length,super.write(t,null,i)}[es](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[pt](t=>t?this.emit("error",t):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[ii]()}};ni=class extends de{sync=true;[ss](){this[si](X.lstatSync(this.absolute))}[is](){this[ns](X.readlinkSync(this.absolute))}[os6](){this[hs](X.openSync(this.absolute,"r"))}[ii](){let t=true;try{let{fd:e,buf:i,offset:r,length:n,pos:o}=this;if(e===void 0||i===void 0)throw new Error("fd and buf must be set in READ method");let h=X.readSync(e,i,r,n,o);this[rs](h),t=false}finally{if(t)try{this[pt](()=>{})}catch{}}}[as](t){t()}[pt](t=()=>{}){this.fd!==void 0&&X.closeSync(this.fd),t()}};oi=class extends A{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(t,e,i={}){return Dt(this,t,e,i)}constructor(t,e={}){let i=se(e);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=t;let{type:r}=t;if(r==="Unsupported")throw new Error("writing entry that should be ignored");this.type=r,this.type==="Directory"&&this.portable&&(this.noMtime=true),this.prefix=i.prefix,this.path=f(t.path),this.mode=t.mode!==void 0?this[ri](t.mode):void 0,this.uid=this.portable?void 0:t.uid,this.gid=this.portable?void 0:t.gid,this.uname=this.portable?void 0:t.uname,this.gname=this.portable?void 0:t.gname,this.size=t.size,this.mtime=this.noMtime?void 0:i.mtime||t.mtime,this.atime=this.portable?void 0:t.atime,this.ctime=this.portable?void 0:t.ctime,this.linkpath=t.linkpath!==void 0?f(t.linkpath):void 0,typeof i.onwarn=="function"&&this.on("warn",i.onwarn);let n=false;if(!this.preservePaths){let[h,a]=ce(this.path);h&&typeof a=="string"&&(this.path=a,n=h)}this.remain=t.size,this.blockRemain=t.startBlockSize,this.onWriteEntry?.(this),this.header=new F({path:this[q](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[q](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}),n&&this.warn("TAR_ENTRY_INFO",`stripping ${n} from absolute path`,{entry:this,path:n+this.path}),this.header.encode()&&!this.noPax&&super.write(new ft({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[q](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[q](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 o=this.header?.block;if(!o)throw new Error("failed to encode header");super.write(o),t.pipe(this)}[q](t){return rr(t,this.prefix)}[ri](t){return Ji(t,this.type==="Directory",this.portable)}write(t,e,i){typeof e=="function"&&(i=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8"));let r=t.length;if(r>this.blockRemain)throw new Error("writing more to entry than is appropriate");return this.blockRemain-=r,super.write(t,i)}end(t,e,i){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),typeof t=="function"&&(i=t,e=void 0,t=void 0),typeof e=="function"&&(i=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e??"utf8")),i&&this.once("finish",i),t?super.end(t,i):super.end(i),this}};Gn=s3=>s3.isFile()?"File":s3.isDirectory()?"Directory":s3.isSymbolicLink()?"SymbolicLink":"Unsupported";hi=class s2{tail;head;length=0;static create(t=[]){return new s2(t)}constructor(t=[]){for(let e of t)this.push(e)}*[Symbol.iterator](){for(let t=this.head;t;t=t.next)yield t.value}removeNode(t){if(t.list!==this)throw new Error("removing node which does not belong to this list");let e=t.next,i=t.prev;return e&&(e.prev=i),i&&(i.next=e),t===this.head&&(this.head=e),t===this.tail&&(this.tail=i),this.length--,t.next=void 0,t.prev=void 0,t.list=void 0,e}unshiftNode(t){if(t===this.head)return;t.list&&t.list.removeNode(t);let e=this.head;t.list=this,t.next=e,e&&(e.prev=t),this.head=t,this.tail||(this.tail=t),this.length++}pushNode(t){if(t===this.tail)return;t.list&&t.list.removeNode(t);let e=this.tail;t.list=this,t.prev=e,e&&(e.next=t),this.tail=t,this.head||(this.head=t),this.length++}push(...t){for(let e=0,i=t.length;e<i;e++)Yn(this,t[e]);return this.length}unshift(...t){for(var e=0,i=t.length;e<i;e++)Kn(this,t[e]);return this.length}pop(){if(!this.tail)return;let t=this.tail.value,e=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,e.list=void 0,this.length--,t}shift(){if(!this.head)return;let t=this.head.value,e=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,e.list=void 0,this.length--,t}forEach(t,e){e=e||this;for(let i=this.head,r=0;i;r++)t.call(e,i.value,r,this),i=i.next}forEachReverse(t,e){e=e||this;for(let i=this.tail,r=this.length-1;i;r--)t.call(e,i.value,r,this),i=i.prev}get(t){let e=0,i=this.head;for(;i&&e<t;e++)i=i.next;if(e===t&&i)return i.value}getReverse(t){let e=0,i=this.tail;for(;i&&e<t;e++)i=i.prev;if(e===t&&i)return i.value}map(t,e){e=e||this;let i=new s2;for(let r=this.head;r;)i.push(t.call(e,r.value,this)),r=r.next;return i}mapReverse(t,e){e=e||this;var i=new s2;for(let r=this.tail;r;)i.push(t.call(e,r.value,this)),r=r.prev;return i}reduce(t,e){let i,r=this.head;if(arguments.length>1)i=e;else if(this.head)r=this.head.next,i=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var n=0;r;n++)i=t(i,r.value,n),r=r.next;return i}reduceReverse(t,e){let i,r=this.tail;if(arguments.length>1)i=e;else if(this.tail)r=this.tail.prev,i=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(let n=this.length-1;r;n--)i=t(i,r.value,n),r=r.prev;return i}toArray(){let t=new Array(this.length);for(let e=0,i=this.head;i;e++)t[e]=i.value,i=i.next;return t}toArrayReverse(){let t=new Array(this.length);for(let e=0,i=this.tail;i;e++)t[e]=i.value,i=i.prev;return t}slice(t=0,e=this.length){e<0&&(e+=this.length),t<0&&(t+=this.length);let i=new s2;if(e<t||e<0)return i;t<0&&(t=0),e>this.length&&(e=this.length);let r=this.head,n=0;for(n=0;r&&n<t;n++)r=r.next;for(;r&&n<e;n++,r=r.next)i.push(r.value);return i}sliceReverse(t=0,e=this.length){e<0&&(e+=this.length),t<0&&(t+=this.length);let i=new s2;if(e<t||e<0)return i;t<0&&(t=0),e>this.length&&(e=this.length);let r=this.length,n=this.tail;for(;n&&r>e;r--)n=n.prev;for(;n&&r>t;r--,n=n.prev)i.push(n.value);return i}splice(t,e=0,...i){t>this.length&&(t=this.length-1),t<0&&(t=this.length+t);let r=this.head;for(let o=0;r&&o<t;o++)r=r.next;let n=[];for(let o=0;r&&o<e;o++)n.push(r.value),r=this.removeNode(r);r?r!==this.tail&&(r=r.prev):r=this.tail;for(let o of i)r=Zn(this,r,o);return n}reverse(){let t=this.head,e=this.tail;for(let i=t;i;i=i.prev){let r=i.prev;i.prev=i.next,i.next=r}return this.head=e,this.tail=t,this}};ue=class{list;next;prev;value;constructor(t,e,i,r){this.list=r,this.value=t,e?(e.next=this,this.prev=e):this.prev=void 0,i?(i.prev=this,this.next=i):this.next=void 0}};pi=class{path;absolute;entry;stat;readdir;pending=false;pendingLink=false;ignore=false;piped=false;constructor(t,e){this.path=t||"./",this.absolute=e}};nr=Buffer.alloc(1024);li=Symbol("onStat");me=Symbol("ended");W=Symbol("queue");pe=Symbol("pendingLinks");Et=Symbol("current");Ft=Symbol("process");Ee=Symbol("processing");ai=Symbol("processJob");G=Symbol("jobs");ls=Symbol("jobDone");ci=Symbol("addFSEntry");or=Symbol("addTarEntry");ds=Symbol("stat");us=Symbol("readdir");fi=Symbol("onreaddir");di=Symbol("pipe");hr=Symbol("entry");cs=Symbol("entryOpt");ui=Symbol("writeEntryClass");lr=Symbol("write");fs7=Symbol("ondrain");wt=class extends A{sync=false;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[ui];onWriteEntry;[W];[pe]=new Map;[G]=0;[Ee]=false;[me]=false;constructor(t={}){if(super(),this.opt=t,this.file=t.file||"",this.cwd=t.cwd||process.cwd(),this.maxReadSize=t.maxReadSize,this.preservePaths=!!t.preservePaths,this.strict=!!t.strict,this.noPax=!!t.noPax,this.prefix=f(t.prefix||""),this.linkCache=t.linkCache||new Map,this.statCache=t.statCache||new Map,this.readdirCache=t.readdirCache||new Map,this.onWriteEntry=t.onWriteEntry,this[ui]=de,typeof t.onwarn=="function"&&this.on("warn",t.onwarn),this.portable=!!t.portable,t.gzip||t.brotli||t.zstd){if((t.gzip?1:0)+(t.brotli?1:0)+(t.zstd?1:0)>1)throw new TypeError("gzip, brotli, zstd are mutually exclusive");if(t.gzip&&(typeof t.gzip!="object"&&(t.gzip={}),this.portable&&(t.gzip.portable=true),this.zip=new ze(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new We(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new Ye(t.zstd)),!this.zip)throw new Error("impossible");let e=this.zip;e.on("data",i=>super.write(i)),e.on("end",()=>super.end()),e.on("drain",()=>this[fs7]()),this.on("resume",()=>e.resume())}else this.on("drain",this[fs7]);this.noDirRecurse=!!t.noDirRecurse,this.follow=!!t.follow,this.noMtime=!!t.noMtime,t.mtime&&(this.mtime=t.mtime),this.filter=typeof t.filter=="function"?t.filter:()=>true,this[W]=new hi,this[G]=0,this.jobs=Number(t.jobs)||4,this[Ee]=false,this[me]=false}[lr](t){return super.write(t)}add(t){return this.write(t),this}end(t,e,i){return typeof t=="function"&&(i=t,t=void 0),typeof e=="function"&&(i=e,e=void 0),t&&this.add(t),this[me]=true,this[Ft](),i&&i(),this}write(t){if(this[me])throw new Error("write after end");return typeof t=="string"?this[ci](t):this[or](t),this.flowing}[or](t){let e=f(ar.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let i=new pi(t.path,e);i.entry=new oi(t,this[cs](i)),i.entry.on("end",()=>this[ls](i)),this[G]+=1,this[W].push(i)}this[Ft]()}[ci](t){let e=f(ar.resolve(this.cwd,t));this[W].push(new pi(t,e)),this[Ft]()}[ds](t){t.pending=true,this[G]+=1;let e=this.follow?"stat":"lstat";mi[e](t.absolute,(i,r)=>{t.pending=false,this[G]-=1,i?this.emit("error",i):this[li](t,r)})}[li](t,e){if(this.statCache.set(t.absolute,e),t.stat=e,!this.filter(t.path,e))t.ignore=true;else if(e.isFile()&&e.nlink>1&&!this.linkCache.get(`${e.dev}:${e.ino}`)&&!this.sync)if(t===this[Et])this[ai](t);else{let i=`${e.dev}:${e.ino}`,r=this[pe].get(i);r?r.push(t):this[pe].set(i,[t]),t.pendingLink=true,t.pending=true}this[Ft]()}[us](t){t.pending=true,this[G]+=1,mi.readdir(t.absolute,(e,i)=>{if(t.pending=false,this[G]-=1,e)return this.emit("error",e);this[fi](t,i)})}[fi](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[Ft]()}[Ft](){if(!this[Ee]){this[Ee]=true;for(let t=this[W].head;t&&this[G]<this.jobs;t=t.next)if(this[ai](t.value),t.value.ignore){let e=t.next;this[W].removeNode(t),t.next=e}this[Ee]=false,this[me]&&this[W].length===0&&this[G]===0&&(this.zip?this.zip.end(nr):(super.write(nr),super.end()))}}get[Et](){return this[W]&&this[W].head&&this[W].head.value}[ls](t){this[W].shift(),this[G]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let i=`${e.dev}:${e.ino}`,r=this[pe].get(i);if(r){this[pe].delete(i);for(let n of r)n.pending=false,this[ai](n)}}this[Ft]()}[ai](t){if(t.pending&&t.pendingLink&&t===this[Et]&&(t.pending=false,t.pendingLink=false),!t.pending){if(t.entry){t===this[Et]&&!t.piped&&this[di](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[li](t,e):this[ds](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[fi](t,e):this[us](t),!t.readdir)return}if(t.entry=this[hr](t),!t.entry){t.ignore=true;return}t===this[Et]&&!t.piped&&this[di](t)}}}[cs](t){return{onwarn:(e,i,r)=>this.warn(e,i,r),noPax:this.noPax,cwd:this.cwd,absolute:t.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}}[hr](t){this[G]+=1;try{return new this[ui](t.path,this[cs](t)).on("end",()=>this[ls](t)).on("error",i=>this.emit("error",i))}catch(e){this.emit("error",e)}}[fs7](){this[Et]&&this[Et].entry&&this[Et].entry.resume()}[di](t){t.piped=true,t.readdir&&t.readdir.forEach(r=>{let n=t.path,o=n==="./"?"":n.replace(/\/*$/,"/");this[ci](o+r)});let e=t.entry,i=this.zip;if(!e)throw new Error("cannot pipe without source");i?e.on("data",r=>{i.write(r)||e.pause()}):e.on("data",r=>{super.write(r)||e.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}warn(t,e,i={}){Dt(this,t,e,i)}};kt=class extends wt{sync=true;constructor(t){super(t),this[ui]=ni}pause(){}resume(){}[ds](t){let e=this.follow?"statSync":"lstatSync";this[li](t,mi[e](t.absolute))}[us](t){this[fi](t,mi.readdirSync(t.absolute))}[di](t){let e=t.entry,i=this.zip;if(t.readdir&&t.readdir.forEach(r=>{let n=t.path,o=n==="./"?"":n.replace(/\/*$/,"/");this[ci](o+r)}),!e)throw new Error("Cannot pipe without source");i?e.on("data",r=>{i.write(r)}):e.on("data",r=>{super[lr](r)})}};Vn=(s3,t)=>{let e=new kt(s3),i=new Wt(s3.file,{mode:s3.mode||438});e.pipe(i),fr(e,t)};$n=(s3,t)=>{let e=new wt(s3),i=new et(s3.file,{mode:s3.mode||438});e.pipe(i);let r=new Promise((n,o)=>{i.on("error",o),i.on("close",n),e.on("error",o)});return dr(e,t).catch(n=>e.emit("error",n)),r};fr=(s3,t)=>{t.forEach(e=>{e.charAt(0)==="@"?Ct({file:cr.resolve(s3.cwd,e.slice(1)),sync:true,noResume:true,onReadEntry:i=>s3.add(i)}):s3.add(e)}),s3.end()};dr=async(s3,t)=>{for(let e of t)e.charAt(0)==="@"?await Ct({file:cr.resolve(String(s3.cwd),e.slice(1)),noResume:true,onReadEntry:i=>{s3.add(i)}}):s3.add(e);s3.end()};Xn=(s3,t)=>{let e=new kt(s3);return fr(e,t),e};qn=(s3,t)=>{let e=new wt(s3);return dr(e,t).catch(i=>e.emit("error",i)),e};Qn=K(Vn,$n,Xn,qn,(s3,t)=>{if(!t?.length)throw new TypeError("no paths specified to add to archive")});Jn=process.env.__FAKE_PLATFORM__||process.platform;Er=Jn==="win32";({O_CREAT:wr,O_NOFOLLOW:ur,O_TRUNC:Sr,O_WRONLY:yr}=pr.constants);Rr=Number(process.env.__FAKE_FS_O_FILENAME__)||pr.constants.UV_FS_O_FILEMAP||0;jn=Er&&!!Rr;to=512*1024;eo=Rr|Sr|wr|yr;mr=!Er&&typeof ur=="number"?ur|Sr|wr|yr:null;ms=mr!==null?()=>mr:jn?s3=>s3<to?eo:"w":()=>"w";ps=(s3,t,e)=>{try{return wi.lchownSync(s3,t,e)}catch(i){if(i?.code!=="ENOENT")throw i}};Ei=(s3,t,e,i)=>{wi.lchown(s3,t,e,r=>{i(r&&r?.code!=="ENOENT"?r:null)})};io=(s3,t,e,i,r)=>{if(t.isDirectory())Es(we.resolve(s3,t.name),e,i,n=>{if(n)return r(n);let o=we.resolve(s3,t.name);Ei(o,e,i,r)});else{let n=we.resolve(s3,t.name);Ei(n,e,i,r)}};Es=(s3,t,e,i)=>{wi.readdir(s3,{withFileTypes:true},(r,n)=>{if(r){if(r.code==="ENOENT")return i();if(r.code!=="ENOTDIR"&&r.code!=="ENOTSUP")return i(r)}if(r||!n.length)return Ei(s3,t,e,i);let o=n.length,h=null,a=l4=>{if(!h){if(l4)return i(h=l4);if(--o===0)return Ei(s3,t,e,i)}};for(let l4 of n)io(s3,l4,t,e,a)})};so=(s3,t,e,i)=>{t.isDirectory()&&ws(we.resolve(s3,t.name),e,i),ps(we.resolve(s3,t.name),e,i)};ws=(s3,t,e)=>{let i;try{i=wi.readdirSync(s3,{withFileTypes:true})}catch(r){let n=r;if(n?.code==="ENOENT")return;if(n?.code==="ENOTDIR"||n?.code==="ENOTSUP")return ps(s3,t,e);throw n}for(let r of i)so(s3,r,t,e);return ps(s3,t,e)};Se=class extends Error{path;code;syscall="chdir";constructor(t,e){super(`${e}: Cannot cd into '${t}'`),this.path=t,this.code=e}get name(){return"CwdError"}};St=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(t,e){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=t,this.path=e}get name(){return"SymlinkError"}};no=(s3,t)=>{k.stat(s3,(e,i)=>{(e||!i.isDirectory())&&(e=new Se(s3,e?.code||"ENOTDIR")),t(e)})};gr=(s3,t,e)=>{s3=f(s3);let i=t.umask??18,r=t.mode|448,n=(r&i)!==0,o=t.uid,h=t.gid,a=typeof o=="number"&&typeof h=="number"&&(o!==t.processUid||h!==t.processGid),l4=t.preserve,c=t.unlink,d3=f(t.cwd),y3=(E3,x3)=>{E3?e(E3):x3&&a?Es(x3,o,h,Le3=>y3(Le3)):n?k.chmod(s3,r,e):e()};if(s3===d3)return no(s3,y3);if(l4)return ro.mkdir(s3,{mode:r,recursive:true}).then(E3=>y3(null,E3??void 0),y3);let D3=f(Si.relative(d3,s3)).split("/");Ss(d3,D3,r,c,d3,void 0,y3)};Ss=(s3,t,e,i,r,n,o)=>{if(t.length===0)return o(null,n);let h=t.shift(),a=f(Si.resolve(s3+"/"+h));k.mkdir(a,e,br(a,t,e,i,r,n,o))};br=(s3,t,e,i,r,n,o)=>h=>{h?k.lstat(s3,(a,l4)=>{if(a)a.path=a.path&&f(a.path),o(a);else if(l4.isDirectory())Ss(s3,t,e,i,r,n,o);else if(i)k.unlink(s3,c=>{if(c)return o(c);k.mkdir(s3,e,br(s3,t,e,i,r,n,o))});else{if(l4.isSymbolicLink())return o(new St(s3,s3+"/"+t.join("/")));o(h)}}):(n=n||s3,Ss(s3,t,e,i,r,n,o))};oo=s3=>{let t=false,e;try{t=k.statSync(s3).isDirectory()}catch(i){e=i?.code}finally{if(!t)throw new Se(s3,e??"ENOTDIR")}};_r=(s3,t)=>{s3=f(s3);let e=t.umask??18,i=t.mode|448,r=(i&e)!==0,n=t.uid,o=t.gid,h=typeof n=="number"&&typeof o=="number"&&(n!==t.processUid||o!==t.processGid),a=t.preserve,l4=t.unlink,c=f(t.cwd),d3=E3=>{E3&&h&&ws(E3,n,o),r&&k.chmodSync(s3,i)};if(s3===c)return oo(c),d3();if(a)return d3(k.mkdirSync(s3,{mode:i,recursive:true})??void 0);let T3=f(Si.relative(c,s3)).split("/"),D3;for(let E3=T3.shift(),x3=c;E3&&(x3+="/"+E3);E3=T3.shift()){x3=f(Si.resolve(x3));try{k.mkdirSync(x3,i),D3=D3||x3}catch{let Le3=k.lstatSync(x3);if(Le3.isDirectory())continue;if(l4){k.unlinkSync(x3),k.mkdirSync(x3,i),D3=D3||x3;continue}else if(Le3.isSymbolicLink())return new St(x3,x3+"/"+T3.join("/"))}}return d3(D3)};ys=Object.create(null);Or=1e4;Vt=new Set;Tr=s3=>{Vt.has(s3)?Vt.delete(s3):ys[s3]=s3.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),Vt.add(s3);let t=ys[s3],e=Vt.size-Or;if(e>Or/10){for(let i of Vt)if(Vt.delete(i),delete ys[i],--e<=0)break}return t};ho=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform;ao=ho==="win32";lo=s3=>s3.split("/").slice(0,-1).reduce((e,i)=>{let r=e.at(-1);return r!==void 0&&(i=xr(r,i)),e.push(i||"/"),e},[]);yi=class{#t=new Map;#i=new Map;#s=new Set;reserve(t,e){t=ao?["win32 parallelization disabled"]:t.map(r=>mt(xr(Tr(r))));let i=new Set(t.map(r=>lo(r)).reduce((r,n)=>r.concat(n)));this.#i.set(e,{dirs:i,paths:t});for(let r of t){let n=this.#t.get(r);n?n.push(e):this.#t.set(r,[e])}for(let r of i){let n=this.#t.get(r);if(!n)this.#t.set(r,[new Set([e])]);else{let o=n.at(-1);o instanceof Set?o.add(e):n.push(new Set([e]))}}return this.#r(e)}#n(t){let e=this.#i.get(t);if(!e)throw new Error("function does not have any path reservations");return{paths:e.paths.map(i=>this.#t.get(i)),dirs:[...e.dirs].map(i=>this.#t.get(i))}}check(t){let{paths:e,dirs:i}=this.#n(t);return e.every(r=>r&&r[0]===t)&&i.every(r=>r&&r[0]instanceof Set&&r[0].has(t))}#r(t){return this.#s.has(t)||!this.check(t)?false:(this.#s.add(t),t(()=>this.#e(t)),true)}#e(t){if(!this.#s.has(t))return false;let e=this.#i.get(t);if(!e)throw new Error("invalid reservation");let{paths:i,dirs:r}=e,n=new Set;for(let o of i){let h=this.#t.get(o);if(!h||h?.[0]!==t)continue;let a=h[1];if(!a){this.#t.delete(o);continue}if(h.shift(),typeof a=="function")n.add(a);else for(let l4 of a)n.add(l4)}for(let o of r){let h=this.#t.get(o),a=h?.[0];if(!(!h||!(a instanceof Set)))if(a.size===1&&h.length===1){this.#t.delete(o);continue}else if(a.size===1){h.shift();let l4=h[0];typeof l4=="function"&&n.add(l4)}else a.delete(t)}return this.#s.delete(t),n.forEach(o=>this.#r(o)),true}};Lr=()=>process.umask();Dr=Symbol("onEntry");_s=Symbol("checkFs");Nr=Symbol("checkFs2");Os=Symbol("isReusable");P=Symbol("makeFs");Ts=Symbol("file");xs=Symbol("directory");gi=Symbol("link");Ar=Symbol("symlink");Ir=Symbol("hardlink");Re=Symbol("ensureNoSymlink");Cr=Symbol("unsupported");Fr=Symbol("checkPath");Rs=Symbol("stripAbsolutePath");yt=Symbol("mkdir");O=Symbol("onError");Ri=Symbol("pending");kr=Symbol("pend");$t=Symbol("unpend");gs=Symbol("ended");bs=Symbol("maybeClose");Ls=Symbol("skip");ge=Symbol("doChown");be=Symbol("uid");_e=Symbol("gid");Oe=Symbol("checkedCwd");fo=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform;Te=fo==="win32";uo=1024;mo=(s3,t)=>{if(!Te)return u.unlink(s3,t);let e=s3+".DELETE."+Mr(16).toString("hex");u.rename(s3,e,i=>{if(i)return t(i);u.unlink(e,t)})};po=s3=>{if(!Te)return u.unlinkSync(s3);let t=s3+".DELETE."+Mr(16).toString("hex");u.renameSync(s3,t),u.unlinkSync(t)};vr=(s3,t,e)=>s3!==void 0&&s3===s3>>>0?s3:t!==void 0&&t===t>>>0?t:e;Xt=class extends rt{[gs]=false;[Oe]=false;[Ri]=0;reservations=new yi;transform;writable=true;readable=false;uid;gid;setOwner;preserveOwner;processGid;processUid;maxDepth;forceChown;win32;newer;keep;noMtime;preservePaths;unlink;cwd;strip;processUmask;umask;dmode;fmode;chmod;constructor(t={}){if(t.ondone=()=>{this[gs]=true,this[bs]()},super(t),this.transform=t.transform,this.chmod=!!t.chmod,typeof t.uid=="number"||typeof t.gid=="number"){if(typeof t.uid!="number"||typeof t.gid!="number")throw new TypeError("cannot set owner without number uid and gid");if(t.preserveOwner)throw new TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=t.uid,this.gid=t.gid,this.setOwner=true}else this.uid=void 0,this.gid=void 0,this.setOwner=false;this.preserveOwner=t.preserveOwner===void 0&&typeof t.uid!="number"?process.getuid?.()===0:!!t.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 t.maxDepth=="number"?t.maxDepth:uo,this.forceChown=t.forceChown===true,this.win32=!!t.win32||Te,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=f(R.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:Lr():0,this.umask=typeof t.umask=="number"?t.umask:this.processUmask,this.dmode=t.dmode||511&~this.umask,this.fmode=t.fmode||438&~this.umask,this.on("entry",e=>this[Dr](e))}warn(t,e,i={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(i.recoverable=false),super.warn(t,e,i)}[bs](){this[gs]&&this[Ri]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[Rs](t,e){let i=t[e],{type:r}=t;if(!i||this.preservePaths)return true;let[n,o]=ce(i),h=o.replaceAll(/\\/g,"/").split("/");if(h.includes("..")||Te&&/^[a-z]:\.\.$/i.test(h[0]??"")){if(e==="path"||r==="Link")return this.warn("TAR_ENTRY_ERROR",`${e} contains '..'`,{entry:t,[e]:i}),false;let a=R.posix.dirname(t.path),l4=R.posix.normalize(R.posix.join(a,h.join("/")));if(l4.startsWith("../")||l4==="..")return this.warn("TAR_ENTRY_ERROR",`${e} escapes extraction directory`,{entry:t,[e]:i}),false}return n&&(t[e]=String(o),this.warn("TAR_ENTRY_INFO",`stripping ${n} from absolute ${e}`,{entry:t,[e]:i})),true}[Fr](t){let e=f(t.path),i=e.split("/");if(this.strip){if(i.length<this.strip)return false;if(t.type==="Link"){let r=f(String(t.linkpath)).split("/");if(r.length>=this.strip)t.linkpath=r.slice(this.strip).join("/");else return false}i.splice(0,this.strip),t.path=i.join("/")}if(isFinite(this.maxDepth)&&i.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:t,path:e,depth:i.length,maxDepth:this.maxDepth}),false;if(!this[Rs](t,"path")||!this[Rs](t,"linkpath"))return false;if(t.absolute=R.isAbsolute(t.path)?f(R.resolve(t.path)):f(R.resolve(this.cwd,t.path)),!this.preservePaths&&typeof t.absolute=="string"&&t.absolute.indexOf(this.cwd+"/")!==0&&t.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:t,path:f(t.path),resolvedPath:t.absolute,cwd:this.cwd}),false;if(t.absolute===this.cwd&&t.type!=="Directory"&&t.type!=="GNUDumpDir")return false;if(this.win32){let{root:r}=R.win32.parse(String(t.absolute));t.absolute=r+ts(String(t.absolute).slice(r.length));let{root:n}=R.win32.parse(t.path);t.path=n+ts(t.path.slice(n.length))}return true}[Dr](t){if(!this[Fr](t))return t.resume();switch(co.equal(typeof t.absolute,"string"),t.type){case"Directory":case"GNUDumpDir":t.mode&&(t.mode=t.mode|448);case"File":case"OldFile":case"ContiguousFile":case"Link":case"SymbolicLink":return this[_s](t);default:return this[Cr](t)}}[O](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[$t](),e.resume())}[yt](t,e,i){gr(f(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e},i)}[ge](t){return this.forceChown||this.preserveOwner&&(typeof t.uid=="number"&&t.uid!==this.processUid||typeof t.gid=="number"&&t.gid!==this.processGid)||typeof this.uid=="number"&&this.uid!==this.processUid||typeof this.gid=="number"&&this.gid!==this.processGid}[be](t){return vr(this.uid,t.uid,this.processUid)}[_e](t){return vr(this.gid,t.gid,this.processGid)}[Ts](t,e){let i=typeof t.mode=="number"?t.mode&4095:this.fmode,r=new et(String(t.absolute),{flags:ms(t.size),mode:i,autoClose:false});r.on("error",a=>{r.fd&&u.close(r.fd,()=>{}),r.write=()=>true,this[O](a,t),e()});let n=1,o=a=>{if(a){r.fd&&u.close(r.fd,()=>{}),this[O](a,t),e();return}--n===0&&r.fd!==void 0&&u.close(r.fd,l4=>{l4?this[O](l4,t):this[$t](),e()})};r.on("finish",()=>{let a=String(t.absolute),l4=r.fd;if(typeof l4=="number"&&t.mtime&&!this.noMtime){n++;let c=t.atime||new Date,d3=t.mtime;u.futimes(l4,c,d3,y3=>y3?u.utimes(a,c,d3,T3=>o(T3&&y3)):o())}if(typeof l4=="number"&&this[ge](t)){n++;let c=this[be](t),d3=this[_e](t);typeof c=="number"&&typeof d3=="number"&&u.fchown(l4,c,d3,y3=>y3?u.chown(a,c,d3,T3=>o(T3&&y3)):o())}o()});let h=this.transform&&this.transform(t)||t;h!==t&&(h.on("error",a=>{this[O](a,t),e()}),t.pipe(h)),h.pipe(r)}[xs](t,e){let i=typeof t.mode=="number"?t.mode&4095:this.dmode;this[yt](String(t.absolute),i,r=>{if(r){this[O](r,t),e();return}let n=1,o=()=>{--n===0&&(e(),this[$t](),t.resume())};t.mtime&&!this.noMtime&&(n++,u.utimes(String(t.absolute),t.atime||new Date,t.mtime,o)),this[ge](t)&&(n++,u.chown(String(t.absolute),Number(this[be](t)),Number(this[_e](t)),o)),o()})}[Cr](t){t.unsupported=true,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[Ar](t,e){let i=f(R.relative(this.cwd,R.resolve(R.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Re](t,this.cwd,i,()=>this[gi](t,String(t.linkpath),"symlink",e),r=>{this[O](r,t),e()})}[Ir](t,e){let i=f(R.resolve(this.cwd,String(t.linkpath))),r=f(String(t.linkpath)).split("/");this[Re](t,this.cwd,r,()=>this[gi](t,i,"link",e),n=>{this[O](n,t),e()})}[Re](t,e,i,r,n){let o=i.shift();if(this.preservePaths||o===void 0)return r();let h=R.resolve(e,o);u.lstat(h,(a,l4)=>{if(a)return r();if(l4?.isSymbolicLink())return n(new St(h,R.resolve(h,i.join("/"))));this[Re](t,h,i,r,n)})}[kr](){this[Ri]++}[$t](){this[Ri]--,this[bs]()}[Ls](t){this[$t](),t.resume()}[Os](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Te}[_s](t){this[kr]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,i=>this[Nr](t,i))}[Nr](t,e){let i=h=>{e(h)},r=()=>{this[yt](this.cwd,this.dmode,h=>{if(h){this[O](h,t),i();return}this[Oe]=true,n()})},n=()=>{if(t.absolute!==this.cwd){let h=f(R.dirname(String(t.absolute)));if(h!==this.cwd)return this[yt](h,this.dmode,a=>{if(a){this[O](a,t),i();return}o()})}o()},o=()=>{u.lstat(String(t.absolute),(h,a)=>{if(a&&(this.keep||this.newer&&a.mtime>(t.mtime??a.mtime))){this[Ls](t),i();return}if(h||this[Os](t,a))return this[P](null,t,i);if(a.isDirectory()){if(t.type==="Directory"){let l4=this.chmod&&t.mode&&(a.mode&4095)!==t.mode,c=d3=>this[P](d3??null,t,i);return l4?u.chmod(String(t.absolute),Number(t.mode),c):c()}if(t.absolute!==this.cwd)return u.rmdir(String(t.absolute),l4=>this[P](l4??null,t,i))}if(t.absolute===this.cwd)return this[P](null,t,i);mo(String(t.absolute),l4=>this[P](l4??null,t,i))})};this[Oe]?n():r()}[P](t,e,i){if(t){this[O](t,e),i();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[Ts](e,i);case"Link":return this[Ir](e,i);case"SymbolicLink":return this[Ar](e,i);case"Directory":case"GNUDumpDir":return this[xs](e,i)}}[gi](t,e,i,r){u[i](e,String(t.absolute),n=>{n?this[O](n,t):(this[$t](),t.resume()),r()})}};ye=s3=>{try{return[null,s3()]}catch(t){return[t,null]}};xe=class extends Xt{sync=true;[P](t,e){return super[P](t,e,()=>{})}[_s](t){if(!this[Oe]){let n=this[yt](this.cwd,this.dmode);if(n)return this[O](n,t);this[Oe]=true}if(t.absolute!==this.cwd){let n=f(R.dirname(String(t.absolute)));if(n!==this.cwd){let o=this[yt](n,this.dmode);if(o)return this[O](o,t)}}let[e,i]=ye(()=>u.lstatSync(String(t.absolute)));if(i&&(this.keep||this.newer&&i.mtime>(t.mtime??i.mtime)))return this[Ls](t);if(e||this[Os](t,i))return this[P](null,t);if(i.isDirectory()){if(t.type==="Directory"){let o=this.chmod&&t.mode&&(i.mode&4095)!==t.mode,[h]=o?ye(()=>{u.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[P](h,t)}let[n]=ye(()=>u.rmdirSync(String(t.absolute)));this[P](n,t)}let[r]=t.absolute===this.cwd?[]:ye(()=>po(String(t.absolute)));this[P](r,t)}[Ts](t,e){let i=typeof t.mode=="number"?t.mode&4095:this.fmode,r=h=>{let a;try{u.closeSync(n)}catch(l4){a=l4}(h||a)&&this[O](h||a,t),e()},n;try{n=u.openSync(String(t.absolute),ms(t.size),i)}catch(h){return r(h)}let o=this.transform&&this.transform(t)||t;o!==t&&(o.on("error",h=>this[O](h,t)),t.pipe(o)),o.on("data",h=>{try{u.writeSync(n,h,0,h.length)}catch(a){r(a)}}),o.on("end",()=>{let h=null;if(t.mtime&&!this.noMtime){let a=t.atime||new Date,l4=t.mtime;try{u.futimesSync(n,a,l4)}catch(c){try{u.utimesSync(String(t.absolute),a,l4)}catch{h=c}}}if(this[ge](t)){let a=this[be](t),l4=this[_e](t);try{u.fchownSync(n,Number(a),Number(l4))}catch(c){try{u.chownSync(String(t.absolute),Number(a),Number(l4))}catch{h=h||c}}}r(h)})}[xs](t,e){let i=typeof t.mode=="number"?t.mode&4095:this.dmode,r=this[yt](String(t.absolute),i);if(r){this[O](r,t),e();return}if(t.mtime&&!this.noMtime)try{u.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[ge](t))try{u.chownSync(String(t.absolute),Number(this[be](t)),Number(this[_e](t)))}catch{}e(),t.resume()}[yt](t,e){try{return _r(f(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e})}catch(i){return i}}[Re](t,e,i,r,n){if(this.preservePaths||i.length===0)return r();let o=e;for(let h of i){o=R.resolve(o,h);let[a,l4]=ye(()=>u.lstatSync(o));if(a)return r();if(l4.isSymbolicLink())return n(new St(o,R.resolve(e,i.join("/"))))}r()}[gi](t,e,i,r){let n=`${i}Sync`;try{u[n](e,String(t.absolute)),r(),t.resume()}catch(o){return this[O](o,t)}}};Eo=s3=>{let t=new xe(s3),e=s3.file,i=Br.statSync(e),r=s3.maxReadSize||16*1024*1024;new Be(e,{readSize:r,size:i.size}).pipe(t)};wo=(s3,t)=>{let e=new Xt(s3),i=s3.maxReadSize||16*1024*1024,r=s3.file;return new Promise((o,h)=>{e.on("error",h),e.on("close",o),Br.stat(r,(a,l4)=>{if(a)h(a);else{let c=new _t(r,{readSize:i,size:l4.size});c.on("error",h),c.pipe(e)}})})};So=K(Eo,wo,s3=>new xe(s3),s3=>new Xt(s3),(s3,t)=>{t?.length&&Qi(s3,t)});yo=(s3,t)=>{let e=new kt(s3),i=true,r,n;try{try{r=v.openSync(s3.file,"r+")}catch(a){if(a?.code==="ENOENT")r=v.openSync(s3.file,"w+");else throw a}let o=v.fstatSync(r),h=Buffer.alloc(512);t:for(n=0;n<o.size;n+=512){for(let c=0,d3=0;c<512;c+=d3){if(d3=v.readSync(r,h,c,h.length-c,n+c),n===0&&h[0]===31&&h[1]===139)throw new Error("cannot append to compressed archives");if(!d3)break t}let a=new F(h);if(!a.cksumValid)break;let l4=512*Math.ceil((a.size||0)/512);if(n+l4+512>o.size)break;n+=l4,s3.mtimeCache&&a.mtime&&s3.mtimeCache.set(String(a.path),a.mtime)}i=false,Ro(s3,e,n,r,t)}finally{if(i)try{v.closeSync(r)}catch{}}};Ro=(s3,t,e,i,r)=>{let n=new Wt(s3.file,{fd:i,start:e});t.pipe(n),bo(t,r)};go=(s3,t)=>{t=Array.from(t);let e=new wt(s3),i=(n,o,h)=>{let a=(T3,D3)=>{T3?v.close(n,E3=>h(T3)):h(null,D3)},l4=0;if(o===0)return a(null,0);let c=0,d3=Buffer.alloc(512),y3=(T3,D3)=>{if(T3||D3===void 0)return a(T3);if(c+=D3,c<512&&D3)return v.read(n,d3,c,d3.length-c,l4+c,y3);if(l4===0&&d3[0]===31&&d3[1]===139)return a(new Error("cannot append to compressed archives"));if(c<512)return a(null,l4);let E3=new F(d3);if(!E3.cksumValid)return a(null,l4);let x3=512*Math.ceil((E3.size??0)/512);if(l4+x3+512>o||(l4+=x3+512,l4>=o))return a(null,l4);s3.mtimeCache&&E3.mtime&&s3.mtimeCache.set(String(E3.path),E3.mtime),c=0,v.read(n,d3,0,512,l4,y3)};v.read(n,d3,0,512,l4,y3)};return new Promise((n,o)=>{e.on("error",o);let h="r+",a=(l4,c)=>{if(l4&&l4.code==="ENOENT"&&h==="r+")return h="w+",v.open(s3.file,h,a);if(l4||!c)return o(l4);v.fstat(c,(d3,y3)=>{if(d3)return v.close(c,()=>o(d3));i(c,y3.size,(T3,D3)=>{if(T3)return o(T3);let E3=new et(s3.file,{fd:c,start:D3});e.pipe(E3),E3.on("error",o),E3.on("close",n),_o(e,t)})})};v.open(s3.file,h,a)})};bo=(s3,t)=>{t.forEach(e=>{e.charAt(0)==="@"?Ct({file:Pr.resolve(s3.cwd,e.slice(1)),sync:true,noResume:true,onReadEntry:i=>s3.add(i)}):s3.add(e)}),s3.end()};_o=async(s3,t)=>{for(let e of t)e.charAt(0)==="@"?await Ct({file:Pr.resolve(String(s3.cwd),e.slice(1)),noResume:true,onReadEntry:i=>s3.add(i)}):s3.add(e);s3.end()};vt=K(yo,go,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(s3,t)=>{if(!Bs(s3))throw new TypeError("file is required");if(s3.gzip||s3.brotli||s3.zstd||s3.file.endsWith(".br")||s3.file.endsWith(".tbr"))throw new TypeError("cannot append to compressed archives");if(!t?.length)throw new TypeError("no paths specified to add/replace")});Oo=K(vt.syncFile,vt.asyncFile,vt.syncNoFile,vt.asyncNoFile,(s3,t=[])=>{vt.validate?.(s3,t),To(s3)});To=s3=>{let t=s3.filter;s3.mtimeCache||(s3.mtimeCache=new Map),s3.filter=t?(e,i)=>t(e,i)&&!((s3.mtimeCache?.get(e)??i.mtime??0)>(i.mtime??0)):(e,i)=>!((s3.mtimeCache?.get(e)??i.mtime??0)>(i.mtime??0))}}});var init_text_safe=__esm({"src/text-safe.ts"(){"use strict"}});import fs8 from"fs";import path12 from"path";var PKG_ESCAPED,PKG_ENTRY_RE;var init_dsh_ledger=__esm({"src/dsh-ledger.ts"(){"use strict";init_dsh_channel();PKG_ESCAPED=DSH_PACKAGE.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");PKG_ENTRY_RE=new RegExp(`^([ \\t]+)${PKG_ESCAPED}:([ \\t]*(\\S+))?[ \\t]*$`)}});import{readFile as readFile2,writeFile as writeFile2,mkdir as mkdir2,rename,unlink}from"fs/promises";import path13 from"path";var STAGGER_MIN_DELAY_DEFAULT_MS,STAGGER_MAX_DELAY_DEFAULT_MS,POLICY_STALE_CAP_MS,DELAY_SANITY_CAP_MS,PUBLISHED_VERSIONS_TTL_MS,STAGGER_PRUNE_MS;var init_update_policy=__esm({"src/update-policy.ts"(){"use strict";init_paths();init_logger();init_upstream_proxy();init_duration();STAGGER_MIN_DELAY_DEFAULT_MS=15*6e4;STAGGER_MAX_DELAY_DEFAULT_MS=48*36e5;POLICY_STALE_CAP_MS=30*864e5;DELAY_SANITY_CAP_MS=366*864e5;PUBLISHED_VERSIONS_TTL_MS=10*6e4;STAGGER_PRUNE_MS=7*864e5}});import{readFile as readFile3,writeFile as writeFile3,mkdir as mkdir3,access,constants,rm,cp,unlink as unlink2,lstat,stat,rename as rename2,mkdtemp,readdir}from"fs/promises";import{execFile as execFile3,spawn}from"child_process";import{realpathSync}from"fs";import crypto2 from"crypto";import path14 from"path";import os7 from"os";import{fileURLToPath as fileURLToPath2}from"url";function normalizeRegistryBase(raw){const v4=raw?.trim();if(!v4)return"https://registry.npmjs.org";return v4.replace(/\/+$/,"")}function isVersionNewer(latest,current){const next=parseSemVer(latest);const prev=parseSemVer(current);if(!next||!prev)return false;for(let i=0;i<3;i++){const a=next.parts[i]??0;const b4=prev.parts[i]??0;if(a!==b4)return a>b4}if(!next.pre.length&&prev.pre.length)return true;if(next.pre.length&&!prev.pre.length)return false;for(let i=0;i<Math.max(next.pre.length,prev.pre.length);i++){const a=next.pre[i];const b4=prev.pre[i];if(a===void 0)return false;if(b4===void 0)return true;if(a===b4)continue;const aNumber=/^\d+$/.test(a)?Number(a):void 0;const bNumber=/^\d+$/.test(b4)?Number(b4):void 0;if(aNumber!==void 0&&bNumber!==void 0)return aNumber>bNumber;if(aNumber!==void 0)return false;if(bNumber!==void 0)return true;return a>b4}return false}function parseSemVer(version){const match=version.match(/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.+)?$/);if(!match)return void 0;return{parts:[Number(match[1]),Number(match[2]),Number(match[3])],pre:match[4]?.split(".")??[]}}var REGISTRY_BASE,CHECK_INTERVAL_MS,THROTTLE_FILE,OWNER_THROTTLE_FILE,LOCK_FILE,OWNER_LANE_CHECK_BASE_MS,OWNER_LANE_CHECK_JITTER_MS,LOCK_MAX_AGE_MS,UPDATE_TMP_MAX_AGE_MS,BACKOFF_BASE_MS,BACKOFF_CAP_MS,BACKOFF_STATE_FILE,BACKOFF_PRUNE_MS,LAST_INSTALL_FILE,PI_LANE_HINT;var init_update=__esm({"src/update.ts"(){"use strict";init_index_min();init_text_safe();init_paths();init_logger();init_dsh_channel();init_dsh_ledger();init_pi_channel();init_client_config();init_upstream_proxy();init_knobs();init_update_policy();REGISTRY_BASE=normalizeRegistryBase(updateRegistryBase());CHECK_INTERVAL_MS=updateCheckIntervalMs();THROTTLE_FILE=path14.join(cacheDir(),".update-check");OWNER_THROTTLE_FILE=path14.join(cacheDir(),".owner-update-check");LOCK_FILE=path14.join(cacheDir(),".update-lock");OWNER_LANE_CHECK_BASE_MS=10*60*1e3;OWNER_LANE_CHECK_JITTER_MS=5*60*1e3;LOCK_MAX_AGE_MS=30*60*1e3;UPDATE_TMP_MAX_AGE_MS=60*60*1e3;BACKOFF_BASE_MS=5*60*1e3;BACKOFF_CAP_MS=6*60*60*1e3;BACKOFF_STATE_FILE=path14.join(cacheDir(),".install-backoff.json");BACKOFF_PRUNE_MS=7*24*60*60*1e3;LAST_INSTALL_FILE=path14.join(cacheDir(),".last-install.json");PI_LANE_HINT=`run \`pi update --extension ${PI_NPM_SPEC}\` from a shell where \`pi\` resolves (or point BILI_PI_BIN at pi's executable)`}});import{createRequire}from"module";var require2;var init_driver=__esm({"src/storage/driver.ts"(){"use strict";require2=createRequire(import.meta.url)}});import{createHash as createHash6,randomBytes}from"crypto";import{existsSync as existsSync3,readFileSync as readFileSync4}from"fs";import{promises as fsp}from"fs";import{createRequire as createRequire2}from"module";import path21 from"path";import{gunzipSync}from"zlib";var ENGINE_SPECS,COOLDOWN_MS,PINNED_DIR_PREFIXES;var init_engine_bootstrap=__esm({"src/storage/engine-bootstrap.ts"(){"use strict";init_logger();init_paths();init_driver();init_knobs();init_update();init_upstream_proxy();ENGINE_SPECS=Object.freeze([{version:"13.0.3",sha512Base64:"RbOBxmLBG8uvFUc15X9+9SFemKcQ0WBuISBVkpuiaUB2qblC8UWlHEjdVVoZ8AdhSwmoEgsiXKfopX0CQxaACQ==",minNodeMajor:22,minNapiVersion:10},{version:"12.9.0",sha512Base64:"wqUv4Gm3toFpHDQmaKD4QhZm3g1DjUBI0yzS4UBl6lElUmXFYdTQmmEDpAFa5o8FiFiymURypEnfVHzILKaxqQ==",minNodeMajor:20,prebuild:{sha512Base64ByAbi:Object.freeze({"115":Object.freeze({"linux-x64":"fNMKurhPKb0ki9mnZJK9PVazCiRugcdmauo5qGjqQjUGIrdaVWrb4nlLwU7IiyppcfLu8n/qUsQ5CEZ36uoGaw==","linux-arm64":"7q7wZe0+5LLQt2YUkocGb41B9TvEMLKIaNI+CiQUQQ2DFBO1RPr3ixj/Gtb+0noMYHjJrqtqKUMO1xMQXnE0iw==","linuxmusl-x64":"GCriICDKw7K5dNjAVo8xFpSJXcYXXBAK9RDoeuSUv6rB5IVRP96IwxeynTy4Xc21l1507Efz+I2yy6FW5gKQ/w==","linuxmusl-arm64":"2OWfVP1nklnuR8ZfCwozJcLB0ZpOTRHqAkDpsLonEF5uHZMBnOAzGtd5d+nuPU+KaS5czciU0tXZFhsCUw7dbg==","darwin-x64":"tW2Vb19+Bh+PLfcGVnrERhc9Mk50Vi8HciIc0nwIJXlPm21xzKL6uEQHMoyKIAxF+vNXxDsUoJyNRg/TgCXjkA==","darwin-arm64":"H6jehr7s1D/RSTRplCL++hneLTgpqVzgzjrX/NJCsf0OMBSKNGCd9kMYAZJjMlp0IetS39sG5PTG7AcLCTQKeg==","win32-x64":"r+BAeN980mQEdIwDcrNU3iJqzAryuOyfeICFfYHuHVclonTr2L0IlzsaGp2D50KNWUeLQrIhBCFuNoT2+iBDTw==","win32-arm64":"jMSa36VrAiLsWFtnwWX+FEs4JWIjHeduVITY44ZcHsqn7BzPcMljL8LdJ0tVVGssV8x9PuqgIqMD5gFmzcYh9w=="}),"127":Object.freeze({"linux-x64":"jpVKlRCjwmKDIfohRK4Zf/potrKjl2CuvKiWm2SOL1eY7pTRQrGBc1DSEr4OBulYHE6PTl59w7hoAlzNOefG3g==","linux-arm64":"ei++r3DQbhwXsP97PHYENHnNd3jrai5dy11SCDZqzmqEm6mjloT1qwrpglVJmW4TLliYBJ8U9bMG/6Y8nbDBCQ==","linuxmusl-x64":"eFglLYVSmdQo7ehLh30dOF4H9csX92XIn1oKB3TdtTZ+7TTh7cfViO7TQIC4NPt6Ufbl3cos9y6/pU8FNL1dQg==","linuxmusl-arm64":"e72bURjJ4SYseIMY7uW1IkubTqzuKzD6NIVP0InsD8+DJBnRwi8+yIEEcODIK4xsFKSO6tE8TLuvPmetXEk8aA==","darwin-x64":"GxXg+WENfyP9DGnvOSMnPge+kDkEZmU8cF7EFOoFSzAFhEwYOBvFB4VTTqhZ6G4y54I7ufkjgkOxZmafdSOXOw==","darwin-arm64":"V1mPpKKnv3AvfZb/++CSOx49tmUi4fba4vORsD8GTaJVwvKmveJ/uPqXaEVhYQgDkao5VLiWL6gN2wk9rQXfPw==","win32-x64":"7chlb4LP9ETESK6djkGxDq4aDTTByiG1VoUwadJk7JZFhfn2u7vblPCulZaM2C3Ju3jHowc8LBKKQZiH52Uc5g==","win32-arm64":"0mD1nLGHG066cUFdIgMTEJfhbIeOgD52+dE0r8LAALarhU5JD0uyKPvpQH/V3rBjvwTOtaQtYqeEFgRj5NUL/g=="})})}}]);COOLDOWN_MS=6*60*60*1e3;PINNED_DIR_PREFIXES=ENGINE_SPECS.map(s3=>`better-sqlite3-${s3.version}`)}});import{existsSync as existsSync4,readFileSync as readFileSync5,statSync as statSync4,writeFileSync as writeFileSync2}from"fs";import{Worker as Worker2}from"worker_threads";var INTEGRITY_SYNC_THRESHOLD_BYTES;var init_integrity_check=__esm({"src/storage/integrity-check.ts"(){"use strict";init_logger();init_runtime_status();init_schema();INTEGRITY_SYNC_THRESHOLD_BYTES=512*1024*1024}});var init_sqlite_errors=__esm({"src/storage/sqlite-errors.ts"(){"use strict"}});import{createHash as createHash7}from"crypto";import{mkdirSync as mkdirSync4,writeFileSync as writeFileSync3,appendFileSync as appendFileSync2,readFileSync as readFileSync6,existsSync as existsSync5,unlinkSync as unlinkSync2,statSync as statSync5}from"fs";import{dirname as dirname2,join}from"path";var EXT_VALUE_MAX_BYTES;var init_store=__esm({"src/storage/store.ts"(){"use strict";init_logger();init_driver();init_schema();init_identity();init_runtime_status();init_integrity_check();init_sqlite_errors();init_instance();EXT_VALUE_MAX_BYTES=4*1024*1024}});function createInitialState(){return{blocks:[],messageRefs:{byRaw:{},byRef:{}},tokenSnapshot:{},nudge:{lastPerMessageNudgeTokens:0,lastNudgeShownTokens:0,baselineTokens:0,anchors:{},lastShownByTier:{}},stats:{tokensCompressed:0,compressionCount:0,absorbedTokens:0,storedCount:0,retrievalCount:0},absorbed:[],rules:[],nextRuleId:1,nextBlockId:1,nextRunId:1}}var init_state=__esm({"kernel/src/state.ts"(){"use strict"}});function isResponsesTurnSeparatorId(id){return id.startsWith(RESPONSES_TURN_SEPARATOR_ID_PREFIX)}function scrubTurnSeparatorIds(blocks){let removed=0;for(const block of blocks){for(const key of["directMessageIds","effectiveMessageIds"]){const ids=block[key];if(!ids)continue;const kept=ids.filter(id=>!isResponsesTurnSeparatorId(id));if(kept.length!==ids.length){removed+=ids.length-kept.length;block[key]=kept}}}return removed}var RESPONSES_TURN_SEPARATOR_ID_PREFIX;var init_turn_separator=__esm({"src/turn-separator.ts"(){"use strict";RESPONSES_TURN_SEPARATOR_ID_PREFIX="acp_turn_sep_"}});function mergeState(parsed){const fresh=createInitialState();return{blocks:(()=>{const blocks=parsed.blocks??fresh.blocks;scrubTurnSeparatorIds(blocks);return blocks})(),messageRefs:parsed.messageRefs??fresh.messageRefs,nudge:{...fresh.nudge,...parsed.nudge??{}},stats:{...fresh.stats,...parsed.stats??{}},nextBlockId:parsed.nextBlockId??fresh.nextBlockId,nextRunId:parsed.nextRunId??fresh.nextRunId,tokenSnapshot:parsed.tokenSnapshot??fresh.tokenSnapshot,lastPassIds:parsed.lastPassIds??fresh.lastPassIds,hiddenOrphanRefs:parsed.hiddenOrphanRefs??fresh.hiddenOrphanRefs,deadRefs:parsed.deadRefs??fresh.deadRefs,refLedgerAligned:parsed.refLedgerAligned??fresh.refLedgerAligned,terminalStreak:parsed.terminalStreak??fresh.terminalStreak,nextRuleId:parsed.nextRuleId??fresh.nextRuleId,absorbed:parsed.absorbed??fresh.absorbed,rules:parsed.rules??fresh.rules,sweptOrphanCallIds:parsed.sweptOrphanCallIds??fresh.sweptOrphanCallIds,pendingOrphanSweepMinRef:parsed.pendingOrphanSweepMinRef??fresh.pendingOrphanSweepMinRef,emergencyTruncateLatch:parsed.emergencyTruncateLatch??fresh.emergencyTruncateLatch,renderDeferredRefs:parsed.renderDeferredRefs??fresh.renderDeferredRefs,viewLatches:parsed.viewLatches??fresh.viewLatches,tsStamps:parsed.tsStamps??fresh.tsStamps,viewLatchConfigDigest:parsed.viewLatchConfigDigest??fresh.viewLatchConfigDigest}}var COMPRESSION_STATE_FIELDS;var init_state_hydration=__esm({"src/state-hydration.ts"(){"use strict";init_state();init_turn_separator();COMPRESSION_STATE_FIELDS=Object.keys(mergeState(createInitialState()))}});var init_ingest=__esm({"src/storage/ingest.ts"(){"use strict";init_store();init_identity();init_state_hydration()}});var init_backend=__esm({"src/storage/backend.ts"(){"use strict";init_store()}});import{createHash as createHash8}from"crypto";var init_canonical=__esm({"src/storage/canonical.ts"(){"use strict"}});import path22 from"path";var init_shadow=__esm({"src/storage/shadow.ts"(){"use strict";init_logger();init_ingest();init_knobs();init_store();init_backend();init_canonical();init_runtime_status();init_knobs()}});function freshState(){return{requested:null,encryptionBlocked:false,persistDisabled:false,sidecar:null,sidecarOpenError:null,bootstrap:null,integrity:null,secondProcess:null,splitBrain:null,splitBrainAcks:new Map,backup:null}}var state;var init_runtime_status=__esm({"src/storage/runtime-status.ts"(){"use strict";init_engine_bootstrap();init_knobs();init_logger();init_text_safe();init_driver();init_shadow();state=freshState()}});import{createHash as createHash14,randomUUID as randomUUID6}from"crypto";import fs14 from"fs";import net3 from"net";import os9 from"os";import path26 from"path";import{createRequire as createRequire3}from"module";import{Worker as Worker3}from"worker_threads";import{pathToFileURL as pathToFileURL2}from"url";import{execFileSync as execFileSync5,spawn as spawn2,spawnSync as spawnSync3}from"child_process";import tls4 from"tls";var import_node_forge=__toESM(require_lib(),1);init_paths();init_logger();import crypto from"crypto";import{execFileSync as execFileSync2}from"child_process";import fs from"fs";import os2 from"os";import path4 from"path";import tls from"tls";var COMBINED_MAX_AGE_MS=24*60*60*1e3;var PLATFORM_CA_CANDIDATES=process.platform==="darwin"?["/etc/ssl/cert.pem","/private/etc/ssl/cert.pem"]:process.platform==="win32"?[]:["/etc/ssl/certs/ca-certificates.crt","/etc/pki/tls/certs/ca-bundle.crt","/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem","/etc/ssl/ca-bundle.pem","/etc/ssl/cert.pem"];init_upstream_proxy();init_client_config();init_vertex();import fs3 from"fs";import os4 from"os";import path8 from"path";init_util();init_log_mask();init_knobs();init_mitm_domains();init_private_host();init_upstream_fail();init_instance();var TWIN_ADOPT_EXIT_CODE=3;import net2 from"net";var CONNECT_PROBE_TIMEOUT_MS=2e3;function originHostPort(origin){try{const u2=new URL(origin);if(u2.protocol!=="http:"&&u2.protocol!=="https:")return void 0;const host=u2.hostname.replace(/^\[|\]$/g,"");if(host==="")return void 0;const port=u2.port!==""?Number(u2.port):u2.protocol==="https:"?443:80;return Number.isInteger(port)&&port>0?{host,port}:void 0}catch{return void 0}}function attemptConnect(host,port,timeoutMs){return new Promise(resolve=>{let settled=false;const settle=outcome=>{if(settled)return;settled=true;socket.destroy();resolve(outcome)};const socket=net2.connect({host,port});socket.setTimeout(timeoutMs);socket.once("connect",()=>settle({ok:true}));socket.once("timeout",()=>settle({ok:false,detail:`connect timeout after ${timeoutMs}ms`}));socket.once("error",err=>settle({ok:false,detail:typeof err.code==="string"&&err.code.length>0?err.code:String(err.message??err)}))})}async function tcpConnectable(origin,timeoutMs=CONNECT_PROBE_TIMEOUT_MS){const hp=originHostPort(origin);if(hp===void 0)return false;const outcome=await attemptConnect(hp.host,hp.port,timeoutMs);return outcome.ok}init_main();init_client_config();init_vertex();init_config();init_instance();init_dsh_channel();init_pi_channel();init_update();import fs12 from"fs";import path19 from"path";import os8 from"os";import crypto4 from"crypto";import{execFileSync as execFileSync4,spawnSync as spawnSync2}from"child_process";import{fileURLToPath as fileURLToPath4}from"url";import fs9 from"fs";import path16 from"path";init_client_config();init_instance();import path15 from"path";import{fileURLToPath as fileURLToPath3}from"url";function nativeProxyScriptPath(fromUrl=import.meta.url){return path15.resolve(path15.dirname(fileURLToPath3(fromUrl)),"..","index.js")}function nativeBootstrapGate(env,optOutKey){if(env.BILLION_CONTEXT_PLUGIN==="0")return false;if(env[optOutKey]==="0")return false;if(env.BILLION_CONTEXT_PROXY!==void 0&&env.BILLION_CONTEXT_PROXY.trim().length>0)return false;if(env.BILI_PROVIDER_REWRITES!==void 0)return false;return true}function proxyEnvOrigin(env){const raw=env.BILLION_CONTEXT_PROXY;if(raw===void 0)return void 0;const url=raw.trim();if(url.length===0||!/^https?:\/\//i.test(url))return void 0;try{new URL(url)}catch{return void 0}return url.replace(/\/+$/,"")}function nativeAttachOrigin(env){const raw=env.BILLION_CONTEXT_ATTACH;if(raw===void 0)return void 0;const url=raw.trim();if(url.length===0||!/^https?:\/\//i.test(url))return void 0;try{new URL(url)}catch{return void 0}return url.replace(/\/+$/,"")}function envMillis(env,name,fallback){const raw=env[name];if(raw===void 0)return fallback;const n=Number(raw);return Number.isFinite(n)&&n>0?Math.floor(n):fallback}var OMP_FIRST_EVENT_TIMEOUT_ENV="PI_OPENAI_STREAM_FIRST_EVENT_TIMEOUT_MS";var OMP_FIRST_EVENT_TIMEOUT_DEFAULT_MS=18e5;function ompFirstEventTimeoutValue(env){const raw=env[OMP_FIRST_EVENT_TIMEOUT_ENV];if(raw!==void 0&&raw.trim().length>0)return void 0;return String(OMP_FIRST_EVENT_TIMEOUT_DEFAULT_MS)}function applyOmpFirstEventTimeout(env){const value=ompFirstEventTimeoutValue(env);if(value!==void 0)env[OMP_FIRST_EVENT_TIMEOUT_ENV]=value}function markNativeHost(env,host){if(env.BILLION_CONTEXT_NATIVE===void 0||env.BILLION_CONTEXT_NATIVE.length===0){env.BILLION_CONTEXT_NATIVE=host}}function singleFlight(fn){let inFlight;return()=>{if(inFlight===void 0){inFlight=fn().finally(()=>{inFlight=void 0})}return inFlight}}var originWaiter;function setNativeOriginWaiter(waiter){originWaiter=waiter}async function awaitNativeProxyOrigin(){return originWaiter===void 0?void 0:originWaiter.wait()}function parseToolOutcome(value){return value==="applied"||value==="partial"||value==="refused"||value==="success"||value==="failure"?value:void 0}function parseBlocksCreated(value){return typeof value==="number"&&Number.isInteger(value)&&value>=0?value:void 0}function partialOutcomeNote(blocksCreated){const created=blocksCreated!==void 0?`${blocksCreated} block(s) created; `:"";return`[acp-result: PARTIAL \u2014 ${created}some requested range(s) were NOT folded. Retry ONLY the failed range(s) listed above; do not re-fold the ranges that were applied.]`}var MANIFEST_TIMEOUT_MS=5e3;var TOOL_TIMEOUT_MS=6e4;var TOOL_TIMEOUT_OVERHEAD_MARGIN_MS=3e4;var STATUS_TIMEOUT_MS=5e3;var ATTACH_HEALTH_DEADLINE_MS=15e3;var ATTACH_HEALTH_POLL_MS=250;function asciiHeaderValue(value){return/^[\x21-\x7e]{1,256}$/.test(value)?value:void 0}function proxyBaseFromUrl(baseUrl){if(!baseUrl)return void 0;try{const url=new URL(baseUrl);if(url.protocol!=="http:"&&url.protocol!=="https:")return void 0;const segments=url.pathname.split("/").filter(s3=>s3.length>0);if(segments[0]!=="bili")return void 0;const rest=url.pathname.slice(url.pathname.indexOf("bili")+"bili".length);if(!/^\/(?:responses\/)?https?:\/\//.test(rest))return void 0;return`${url.protocol}//${url.host}`}catch{return void 0}}function proxyBaseFromEnv(){const raw=process.env.BILLION_CONTEXT_PROXY?.trim();if(!raw)return void 0;try{const url=new URL(raw);return url.protocol==="http:"||url.protocol==="https:"?`${url.protocol}//${url.host}`:void 0}catch{return void 0}}function detectProxyBase(baseUrl){if(process.env.BILLION_CONTEXT_PLUGIN==="0")return void 0;return proxyBaseFromUrl(baseUrl)??proxyBaseFromEnv()}function mitmHostsFromEnv(env=process.env){const out=new Set;for(const raw of env.BILI_MITM_HOSTS?.split(",")??[]){const host=raw.trim().toLowerCase();if(host.length>0)out.add(host)}return out}function nonHttpProvidersFromEnv(env=process.env){const out=new Set;for(const raw of env.BILI_NON_HTTP_PROVIDERS?.split(",")??[]){const id=raw.trim();if(id.length>0)out.add(id)}return out}function destinationRoutedThroughProxy(baseUrl){if(!baseUrl)return false;const viaBiliPath=proxyBaseFromUrl(baseUrl)!==void 0;if(viaBiliPath)return true;let origin;let host;try{const url=new URL(baseUrl);if(url.protocol!=="http:"&&url.protocol!=="https:")return false;origin=`${url.protocol}//${url.host}`;host=url.hostname.toLowerCase()}catch{return false}if(origin===proxyBaseFromEnv())return true;const mitmHosts=mitmHostsFromEnv();if(mitmHosts.size===0)return false;for(const d3 of mitmHosts){if(host===d3||host.endsWith(`.${d3}`))return true}return false}async function fetchJson(url,init,timeoutMs,externalSignal){const ac=new AbortController;if(externalSignal?.aborted)ac.abort();const timer2=setTimeout(()=>ac.abort(),timeoutMs);const onExternalAbort=()=>ac.abort();externalSignal?.addEventListener("abort",onExternalAbort,{once:true});try{let res;try{res=await fetch(url,{...init,signal:ac.signal})}catch(err){if(ac.signal.aborted&&!externalSignal?.aborted)throw new Error(`timeout after ${timeoutMs}ms: ${url}`);throw err}const text=await res.text();let json=void 0;try{json=JSON.parse(text)}catch{json=void 0}return{ok:res.ok,status:res.status,json}}finally{clearTimeout(timer2);externalSignal?.removeEventListener("abort",onExternalAbort)}}var manifestToolDurations=new Map;function recordManifestToolDuration(proxyBase,json){const caps=json?.capabilities?.externalSummary;const value=caps?.maxToolDurationMs;if(typeof value==="number"&&Number.isFinite(value)&&value>0)manifestToolDurations.set(proxyBase,value)}function effectiveToolTimeoutMs(proxyBase,tool){if(tool!=="compress")return TOOL_TIMEOUT_MS;const advertised=manifestToolDurations.get(proxyBase);if(advertised===void 0)return TOOL_TIMEOUT_MS;return Math.max(TOOL_TIMEOUT_MS,advertised+TOOL_TIMEOUT_OVERHEAD_MARGIN_MS)}async function fetchManifest(proxyBase,format2="anthropic"){const{ok,status,json}=await fetchJson(`${proxyBase}/__bili/plugin/manifest`,void 0,MANIFEST_TIMEOUT_MS);if(!ok||!json||typeof json!=="object")throw new Error(`manifest fetch failed: ${status}`);recordManifestToolDuration(proxyBase,json);if(format2==="openai"){const data2=json;const tools2=[];for(const t of data2.tools?.openai??[]){const name=t.name??t.function?.name;if(typeof name!=="string"||name.length===0)continue;tools2.push({name,description:t.description??t.function?.description,inputSchema:t.parameters??t.function?.parameters??{type:"object",properties:{}}})}if(tools2.length===0)throw new Error("manifest served no openai tools");return tools2}const data=json;const tools=(data.tools?.anthropic??[]).filter(t=>typeof t.name==="string");if(tools.length===0)throw new Error("manifest served no anthropic tools");return tools.map(t=>({name:t.name,description:t.description,inputSchema:t.input_schema??{type:"object",properties:{}}}))}var COMPACT_TIMEOUT_MS=5e3;async function postIdentityRegister(proxyBase,conversationId,agent,parentConversationId){const res=await fetch(`${proxyBase}/__bili/plugin/register`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({conversationId,agent,identity:true,...parentConversationId?{parentConversationId}:{}}),signal:AbortSignal.timeout(COMPACT_TIMEOUT_MS)});if(!res.ok)throw new Error(`register HTTP ${res.status}`)}async function reportRuntimeInfo(proxyBase,info){const{ok,status}=await fetchJson(`${proxyBase}/__bili/plugin/runtime-info`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(info)},STATUS_TIMEOUT_MS);if(!ok)throw new Error(`runtime-info report failed (${status})`)}var lastRuntimeReport=new Map;function runtimeReportFingerprint(proxyBase,info){return[proxyBase,info.agent,info.conversationId??"",info.model,String(info.contextWindow??""),String(info.maxOutput??""),info.baseURL??""].join("\0")}async function reportRuntimeInfoOnChange(proxyBase,info){if(proxyBase===void 0||proxyBase.length===0)return;const key=`${info.agent}\0${info.conversationId??""}`;const fingerprint=runtimeReportFingerprint(proxyBase,info);if(lastRuntimeReport.get(key)===fingerprint)return;lastRuntimeReport.set(key,fingerprint);try{await reportRuntimeInfo(proxyBase,info)}catch{lastRuntimeReport.delete(key)}}async function forwardTool(proxyBase,conversationId,tool,args,signal,nativeCaller=false,toolCallId){const body={conversationId,tool,args:args??{}};if(toolCallId!==void 0)body.toolCallId=toolCallId;if(nativeCaller&&conversationId)body.nativeCaller=true;const{ok,status,json}=await fetchJson(`${proxyBase}/__bili/plugin/tool`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(body)},effectiveToolTimeoutMs(proxyBase,tool),signal);const data=json;if(!ok||!data?.ok){throw new Error(`bili proxy tool ${tool} failed (${status}): ${data?.error??"unknown error"}`)}const outcome=parseToolOutcome(data.outcome);const blocksCreated=parseBlocksCreated(data.blocksCreated);let text=data.result??"";if(outcome==="partial")text+=`
128
128
  ${partialOutcomeNote(blocksCreated)}`;const out={text,failed:outcome==="failure"||outcome==="refused"};if(outcome!==void 0)out.outcome=outcome;if(blocksCreated!==void 0)out.blocksCreated=blocksCreated;return out}async function fetchStatus(proxyBase,conversationId){const{ok,json}=await fetchJson(`${proxyBase}/__bili/plugin/status?conversationId=${encodeURIComponent(conversationId)}`,void 0,STATUS_TIMEOUT_MS);if(!ok||!json||typeof json!=="object")return void 0;return json}async function fetchProxyVersion(proxyBase,init){const{ok,json}=await fetchJson(`${proxyBase}/__bili/plugin/manifest`,init,STATUS_TIMEOUT_MS);if(!ok||!json||typeof json!=="object")return void 0;const m4=json;const version=m4.version;if(typeof version!=="string"||version.length===0)return void 0;const commit=m4.commit;if(typeof commit==="string"&&commit.length>0)return`${version} (${commit})`;return version}async function waitForProxyVersion(proxyBase){const limit=envMillis(process.env,"BILI_ATTACH_HEALTH_DEADLINE_MS",ATTACH_HEALTH_DEADLINE_MS);const startedAt=Date.now();for(;;){const version=await fetchProxyVersion(proxyBase).catch(()=>void 0);if(version!==void 0)return proxyBase;const elapsed=Date.now()-startedAt;if(elapsed>=limit)return void 0;await new Promise(r=>setTimeout(r,Math.min(ATTACH_HEALTH_POLL_MS,limit-elapsed)))}}function armedIdleNotice(version,base){return`billion-context@${version} \u2014 proxy connected${base?` via ${base}`:""}, compression armed. No model request yet; send one, then run /acp again.`}function noSessionWarning(){return"bili: no ACP session yet (send a model request first, then run /acp)"}init_client_config();import fs10 from"fs";import path17 from"path";import crypto3 from"crypto";import fs11 from"fs";import path18 from"path";init_instance();init_config();init_log_mask();init_logger();init_paths();init_version();import{appendFileSync,mkdirSync as mkdirSync3}from"fs";import path20 from"path";function logHostEvent(level,origin,msg){try{const file=defaultLogFile();mkdirSync3(path20.dirname(file),{recursive:true});const safe=maskUrlsForDiagnostics(maskIpsInText(redactSecretsInText(msg)));appendFileSync(file,`${logTimestamp()} [${level}] [v=${VERSION}] ${origin?`${origin} `:""}${safe}
129
- `)}catch{}}init_logger();init_version();import http from"http";var PERMISSION_DENIED_SIGNATURE=/\b(?:EPERM|EACCES|EROFS|EBUSY)\b|operation not permitted|permission denied|read-only file system|readonly database/i;var BILI_DATA_PATH_SIGNATURE=/billion-context|combined-ca\.pem|index\.db|\.local[\\/](?:share|state)[\\/]/i;function classifyStartupFailure(sample){if(!PERMISSION_DENIED_SIGNATURE.test(sample)||!BILI_DATA_PATH_SIGNATURE.test(sample))return"";return"possible cause: the proxy could not write its own data files (EPERM/EACCES/read-only on the bili data dir) \u2014 most often antivirus (e.g. Windows Defender Controlled Folder Access) blocking the node runtime, a read-only flag or ACL on the directory, or another process holding the files; add the bili data dir and the node runtime to AV exclusions (see #367) or fix the directory permissions, then retry"}var MAX_HOLD_MS=10*6e4;init_update();init_win_cmd();init_client_config();init_config();init_registry();init_config();init_logger();function parseLauncherModelWindows(raw){if(!raw)return{};try{const parsed=JSON.parse(raw);if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))return{};const out={};for(const[id,v4]of Object.entries(parsed)){if(typeof v4==="number"&&Number.isFinite(v4)&&v4>0)out[id]=Math.floor(v4)}return out}catch{return{}}}var LAUNCHER_MODEL_WINDOWS=parseLauncherModelWindows(process.env.BILI_LAUNCHER_MODEL_WINDOWS);function parseLauncherModelMaxOutputs(raw){if(!raw)return{};try{const parsed=JSON.parse(raw);if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))return{};const out={};for(const[id,v4]of Object.entries(parsed)){if(typeof v4==="number"&&Number.isFinite(v4)&&v4>0)out[id]=Math.floor(v4)}return out}catch{return{}}}var LAUNCHER_MODEL_MAX_OUTPUTS=parseLauncherModelMaxOutputs(process.env.BILI_LAUNCHER_MODEL_MAX_OUTPUTS);init_vertex();init_client_config();init_logger();import{createHash as createHash13}from"crypto";import{createHash as createHash12,randomUUID as randomUUID4}from"crypto";import{closeSync,existsSync as existsSync6,fsyncSync,mkdirSync as mkdirSync6,openSync,readdirSync,readFileSync as readFileSync7,renameSync as renameSync2,rmSync,statSync as statSync6,writeFileSync as writeFileSync5}from"fs";import{readdir as readdir2,readFile as readFile4,rm as rm2}from"fs/promises";import*as path23 from"path";init_paths();init_knobs();init_logger();init_runtime_status();init_version();import{createCipheriv,createDecipheriv,randomBytes as randomBytes2}from"crypto";import*as zlib from"zlib";var ENCRYPT_MAGIC=Buffer.from("BILIENC1","utf8");var ZSTD_MAGIC=Buffer.from("BILIZSTD1","utf8");var NONCE_LEN=12;var TAG_LEN=16;var ENCRYPT_HEADER_LEN=ENCRYPT_MAGIC.length+2+NONCE_LEN;var MIN_ENCRYPTED_LEN=ENCRYPT_HEADER_LEN+TAG_LEN;var PLAIN_HEADER_LEN=ZSTD_MAGIC.length+2;init_logger();init_billing();init_state_hydration();init_shadow();init_backend();init_ingest();init_store();init_logger();init_paths();import{randomUUID as randomUUID2}from"crypto";import{mkdirSync as mkdirSync5,writeFileSync as writeFileSync4}from"fs";import{dirname as dirname3,join as join2}from"path";init_knobs();import{createHash as createHash11,randomUUID as randomUUID3}from"crypto";import{AsyncLocalStorage as AsyncLocalStorage3}from"async_hooks";init_logger();import{createHash as createHash10}from"crypto";import{createHash as createHash9}from"crypto";init_logger();init_logger();init_billing();init_util();var BOOT_ID=randomUUID3();var SEAM_BODY_CAP=512*1024;var BODY_FULL_CAP=8*1024*1024;var captures=new AsyncLocalStorage3;var LEARNED_IMAGE_COST_TTL_MS=24*60*60*1e3;var{join:join4}=path23;init_version();init_knobs();init_config();init_config();init_paths();init_logger();init_external_summary_settings();import*as path24 from"path";init_turn_separator();init_turn_separator();var ABORT_REANCHOR_MAX_AGE_MS=30*60*1e3;var MAX_SESSIONS=maxSessions();var MAX_RESIDENT_BYTES=sessionResidentMaxBytes();var SPLIT_CANARY_FRESH_MS=10*60*1e3;import{randomUUID as randomUUID5}from"crypto";init_knobs();var CODEX_FORGED_HANDOFF_HEADER="[bili] context summary after compaction:";var FORGED_SUMMARY_HEADER="[Compressed conversation section]";init_client_config();import fs13 from"fs";import path25 from"path";init_dsh_channel();var SCAN_CACHE_TTL_MS=5*60*1e3;var CONFLICT_ACTIVE_WINDOW_MS=7*24*60*60*1e3;var LAUNCHER_DEFAULT_HOST="127.0.0.1";var HEALTH_PATH="/__bili/health";var HEALTH_POLL_INTERVAL_MS=200;var SPAWN_WAIT_MS=envMillis(process.env,"BILI_SPAWN_WAIT_MS",2e4);var SLOW_START_GRACE_MS=envMillis(process.env,"BILI_SLOW_START_GRACE_MS",4e4);var SPAWN_BUDGET_MS=SPAWN_WAIT_MS+SLOW_START_GRACE_MS;var PROBE_TIMEOUT_MS=1500;var STARTING_MARKER_TTL_MS=SPAWN_BUDGET_MS+3e4;var POST_EXIT_REDISCOVERY_MS=3e3;var DEFAULT_MITM_DOMAIN_SET=new Set(DEFAULT_MITM_DOMAINS.map(d3=>d3.toLowerCase()));function proxyOrigin(host,port){return`http://${host}:${port}`}function healthUrl(origin){return origin+HEALTH_PATH}async function defaultFetch(url){const ctrl=new AbortController;const t=setTimeout(()=>ctrl.abort(),PROBE_TIMEOUT_MS);try{const res=await fetch(url,{signal:ctrl.signal});return{ok:res.ok}}catch{return{ok:false}}finally{clearTimeout(t)}}async function probeHealth(origin,fetchImpl){try{const{ok}=await fetchImpl(healthUrl(origin));return ok}catch{return false}}function describeProbeFailure(err){const e=err;const code=e?.cause?.code??e?.code;if(typeof code==="string"&&code.length>0)return code;if(e?.name==="TimeoutError"||e?.name==="AbortError")return`timeout after ${PROBE_TIMEOUT_MS}ms`;if(typeof e?.message==="string"&&e.message.length>0)return e.message.slice(0,160);return String(err)}async function defaultFetchDetail(url){const ctrl=new AbortController;const t=setTimeout(()=>ctrl.abort(),PROBE_TIMEOUT_MS);try{const res=await fetch(url,{signal:ctrl.signal});return res.ok?{ok:true}:{ok:false,detail:`HTTP ${res.status}`}}catch(err){return{ok:false,detail:describeProbeFailure(err)}}finally{clearTimeout(t)}}async function fetchHealthInfoDefault(origin,opts){try{const res=await fetch(healthUrl(origin),{signal:AbortSignal.timeout(PROBE_TIMEOUT_MS),...opts?.noKeepAlive?{headers:{connection:"close"}}:{}});if(!res.ok)return void 0;const data=await res.json();const info={ok:Boolean(data.ok),instanceId:typeof data.instanceId==="string"?data.instanceId:void 0};if(typeof data.version==="string")info.version=data.version;if(typeof data.pid==="number")info.pid=data.pid;if(typeof data.auxProxy==="string"&&data.auxProxy.length>0)info.auxProxy=data.auxProxy;if(typeof data.auxProxySource==="string"&&data.auxProxySource.length>0)info.auxProxySource=data.auxProxySource;if(data.watchdog&&typeof data.watchdog==="object"&&typeof data.watchdog.armed==="boolean"){const wd=data.watchdog;const watchers=Array.isArray(wd.watchers)?wd.watchers.filter(w4=>typeof w4==="number"):void 0;info.watchdog={armed:wd.armed,watchers}}return info}catch{return void 0}}async function registerWatcherDefault(origin,pid){try{const res=await fetch(`${origin}/__bili/watcher`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({pid}),signal:AbortSignal.timeout(2e3)});if(!res.ok){if(res.status===409)return"refused";console.error(`bili: watcher registration returned HTTP ${res.status} \u2014 the shared proxy may exit when its first owner does`);return"failed"}return"ok"}catch(err){console.error(`bili: watcher registration failed \u2014 the shared proxy may exit when its first owner does (${err instanceof Error?err.message:String(err)})`);return"failed"}}function isStartingMarkerActive(marker,nowMs){return isPidAlive(marker.pid)&&nowMs-marker.startedAt<STARTING_MARKER_TTL_MS}function recordedModelMap(passed,ambientRaw,parse3){return parse3(passed&&Object.keys(passed).length>0?JSON.stringify(passed):ambientRaw)}function instanceShapeMismatch(inst,opts,foreignLanes=[]){if(opts.lane!==void 0&&inst.lane!==void 0&&inst.lane!==opts.lane&&!foreignLanes.includes(inst.lane))return"lane-mismatch";if(inst.host!==opts.host||inst.passthrough!==resolveRecordedPassthrough(opts.passthrough))return"host-or-passthrough-mismatch";const wantDomains=resolveRecordedMitmDomains(opts.mitmDomains);if(inst.mitmDomains.length!==wantDomains.length||inst.mitmDomains.some((d3,i)=>d3!==wantDomains[i]))return"mitm-domains-mismatch";const wantWindows=recordedModelMap(opts.modelWindows,process.env.BILI_LAUNCHER_MODEL_WINDOWS,parseLauncherModelWindows);if(Object.keys(inst.modelWindows).length!==Object.keys(wantWindows).length)return"model-windows-mismatch";if(!Object.keys(wantWindows).every(k2=>inst.modelWindows[k2]===wantWindows[k2]))return"model-windows-mismatch";const wantMax=recordedModelMap(opts.modelMaxOutputs,process.env.BILI_LAUNCHER_MODEL_MAX_OUTPUTS,parseLauncherModelMaxOutputs);if(Object.keys(inst.modelMaxOutputs??{}).length!==Object.keys(wantMax).length)return"model-max-outputs-mismatch";return Object.keys(wantMax).every(k2=>(inst.modelMaxOutputs??{})[k2]===wantMax[k2])?void 0:"model-max-outputs-mismatch"}function isNewerSameLaneHolder(inst,optsLane,healthVersion,ownVersion,userZone){if(userZone||optsLane===void 0||healthVersion===void 0)return false;return inst.lane===optsLane&&isVersionNewer(healthVersion,ownVersion)}function instanceCompatible(inst,opts,codeFingerprint,foreignLanes=[]){if(inst.codeFingerprint===void 0||inst.codeFingerprint!==codeFingerprint)return"code-fingerprint-mismatch";return instanceShapeMismatch(inst,opts,foreignLanes)}async function probeLiveInstances(readInstance,fetchHealthInfo,diag,isConnectable=tcpConnectable){const seen=new Map;const inst=readInstance();if(isProxyInstanceFile(inst))seen.set(inst.instanceId||inst.origin,inst);for(const live of discoverLiveInstances())seen.set(live.instanceId||live.origin,live);const checked=await Promise.all([...seen.values()].map(async c=>{if(!isPidAlive(c.pid)){diag?.(`native-attach: drop ${c.origin} (pid ${c.pid}): owner process gone`);return void 0}const health=await fetchHealthInfo(c.origin);if(!health||!health.ok){if(health===void 0&&await isConnectable(c.origin)){diag?.(`native-attach: keep ${c.origin} (pid ${c.pid}): health probe failed but TCP connect succeeded \u2014 instance is BUSY (event loop saturated), not dead (#3654/#4811)`);return{inst:c,health:void 0}}diag?.(health===void 0?`native-attach: drop ${c.origin} (pid ${c.pid}): health probe failed`:`native-attach: drop ${c.origin} (pid ${c.pid}): health probe answered but reports not-ok`);return void 0}if(health.instanceId!==void 0&&health.instanceId!==c.instanceId){diag?.(`native-attach: drop ${c.origin} (pid ${c.pid}): instance id mismatch (${c.instanceId} vs ${health.instanceId})`);return void 0}return{inst:c,health}}));return checked.filter(c=>c!==void 0)}function attachGateAllows(health,attachExternal){if(attachExternal)return true;return health?.watchdog?.armed===true}function isUserZoneInstance(inst){return inst.lane===void 0&&inst.launchToken===void 0}function gateRefusalMessage(inst,health){const reason=health.watchdog&&health.watchdog.armed===false?"it reports NO session-lifecycle watchdog (started without BILI_PARENT_PID, e.g. manual `bili start`)":"it does not report watchdog state (older bili build) \u2014 its lifecycle is unverifiable";return`bili: refusing to attach to ${inst.origin} (pid ${inst.pid}) \u2014 ${reason}. It would outlive this session and ignore config edits until killed (#1322/#1335). Starting a session-owned proxy instead; set native.attachExternal=true or BILI_NATIVE_ATTACH_EXTERNAL=1 to attach anyway.`}function attachClass(inst,lane,foreignLanes){if(lane===void 0)return 1;if(inst.lane===lane)return 0;if(inst.lane!==void 0)return 1+foreignLanes.indexOf(inst.lane);return foreignLanes.length+1}function normalizeOrigin(o){return o.trim().replace(/\/+$/,"").toLowerCase()}function pickAttachable(candidates,opts,codeFingerprint,attachExternal,attachPolicy,attachUrl,refusedLog,diag,foreignLanes=[]){let best;let bestClass=Number.MAX_SAFE_INTEGER;let bestStartedAt=Number.NEGATIVE_INFINITY;for(const c of candidates){if(attachUrl&&normalizeOrigin(c.inst.origin)!==normalizeOrigin(attachUrl)){diag?.(`native-attach: skip ${c.inst.origin} (pid ${c.inst.pid}): not the explicit attachUrl target`);continue}let incompatible=instanceCompatible(c.inst,opts,codeFingerprint,foreignLanes);if(incompatible==="code-fingerprint-mismatch"&&c.health?.version!==void 0&&isNewerSameLaneHolder(c.inst,opts.lane,c.health.version,VERSION,isUserZoneInstance(c.inst))){const adoptedShape=instanceShapeMismatch(c.inst,opts,foreignLanes);if(adoptedShape===void 0){diag?.(`native-attach: adopt ${c.inst.origin} (pid ${c.inst.pid}): foreign bytes but self-reported v${c.health.version} is strictly NEWER than this lane's v${VERSION} \u2014 riding the newer build instead of deadlocking behind it (#4125)`);incompatible=void 0}else{diag?.(`native-attach: skip ${c.inst.origin} (pid ${c.inst.pid}): reports v${c.health.version} (newer) but its config shape differs (${adoptedShape}) \u2014 shape guards survive upward adoption (#4125)`);incompatible=adoptedShape}}if(incompatible!==void 0){diag?.(`native-attach: skip ${c.inst.origin} (pid ${c.inst.pid}): incompatible (${incompatible})`);continue}if(opts.strictPort&&c.inst.port!==opts.port){diag?.(`native-attach: skip ${c.inst.origin} (pid ${c.inst.pid}): port mismatch`);continue}const sameLane=opts.lane!==void 0&&c.inst.lane===opts.lane;if(!attachUrl&&!attachExternal&&attachPolicy==="own-lane"&&opts.lane!==void 0&&!sameLane&&c.health?.watchdog?.armed!==true){diag?.(`native-attach: skip ${c.inst.origin} (pid ${c.inst.pid}): not own lane and not an armed shared daemon (attachPolicy=own-lane)`);continue}if(c.health===void 0){if(!sameLane&&!attachExternal&&!isUserZoneInstance(c.inst)){if(!refusedLog.has(c.inst.origin)){refusedLog.add(c.inst.origin);const msg=`bili: refusing to attach to ${c.inst.origin} (pid ${c.inst.pid}) \u2014 health probe silent but TCP alive (BUSY, event loop saturated #3654) and its lifecycle is unverifiable from this lane. Starting a session-owned proxy instead; set native.attachExternal=true or BILI_NATIVE_ATTACH_EXTERNAL=1 to attach anyway.`;console.error(msg);diag?.(msg)}continue}}else if(!attachGateAllows(c.health,attachExternal)&&!isUserZoneInstance(c.inst)){if(!refusedLog.has(c.inst.origin)){refusedLog.add(c.inst.origin);console.error(gateRefusalMessage(c.inst,c.health));diag?.(gateRefusalMessage(c.inst,c.health))}continue}const cls=attachClass(c.inst,opts.lane,foreignLanes);if(cls<bestClass||cls===bestClass&&c.inst.startedAt>bestStartedAt){best=c.inst;bestClass=cls;bestStartedAt=c.inst.startedAt}}return best}async function waitForStarterInstance(readInstance,fetchHealthInfo,now,sleepImpl,opts,codeFingerprint,attachExternal,attachPolicy,attachUrl,refusedLog,diag,foreignLanes=[],isConnectable=tcpConnectable){const deadline=now()+SPAWN_BUDGET_MS;const probe=async()=>pickAttachable(await probeLiveInstances(readInstance,fetchHealthInfo,diag,isConnectable),opts,codeFingerprint,attachExternal,attachPolicy,attachUrl,refusedLog,diag,foreignLanes);let inst;while(now()<deadline){await sleepImpl(HEALTH_POLL_INTERVAL_MS);inst=await probe();if(inst)break;const still=readStartingMarker();if(!still||!isStartingMarkerActive(still,now()))break}return inst??await probe()}function defaultAttachDiag(debug2){return msg=>{logHostEvent("info","",msg);if(debug2)process.stderr.write(`${logTimestamp()} [info] [v=${VERSION}] ${msg}
129
+ `)}catch{}}init_logger();init_version();import http from"http";var PERMISSION_DENIED_SIGNATURE=/\b(?:EPERM|EACCES|EROFS|EBUSY)\b|operation not permitted|permission denied|read-only file system|readonly database/i;var BILI_DATA_PATH_SIGNATURE=/billion-context|combined-ca\.pem|index\.db|\.local[\\/](?:share|state)[\\/]/i;function classifyStartupFailure(sample){if(!PERMISSION_DENIED_SIGNATURE.test(sample)||!BILI_DATA_PATH_SIGNATURE.test(sample))return"";return"possible cause: the proxy could not write its own data files (EPERM/EACCES/read-only on the bili data dir) \u2014 most often antivirus (e.g. Windows Defender Controlled Folder Access) blocking the node runtime, a read-only flag or ACL on the directory, or another process holding the files; add the bili data dir and the node runtime to AV exclusions (see #367) or fix the directory permissions, then retry"}var MAX_HOLD_MS=10*6e4;init_update();init_win_cmd();init_client_config();init_config();init_registry();init_config();init_logger();function parseLauncherModelWindows(raw){if(!raw)return{};try{const parsed=JSON.parse(raw);if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))return{};const out={};for(const[id,v4]of Object.entries(parsed)){if(typeof v4==="number"&&Number.isFinite(v4)&&v4>0)out[id]=Math.floor(v4)}return out}catch{return{}}}var LAUNCHER_MODEL_WINDOWS=parseLauncherModelWindows(process.env.BILI_LAUNCHER_MODEL_WINDOWS);function parseLauncherModelMaxOutputs(raw){if(!raw)return{};try{const parsed=JSON.parse(raw);if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))return{};const out={};for(const[id,v4]of Object.entries(parsed)){if(typeof v4==="number"&&Number.isFinite(v4)&&v4>0)out[id]=Math.floor(v4)}return out}catch{return{}}}var LAUNCHER_MODEL_MAX_OUTPUTS=parseLauncherModelMaxOutputs(process.env.BILI_LAUNCHER_MODEL_MAX_OUTPUTS);init_vertex();init_client_config();init_logger();import{createHash as createHash13}from"crypto";import{createHash as createHash12,randomUUID as randomUUID4}from"crypto";import{closeSync,existsSync as existsSync6,fsyncSync,mkdirSync as mkdirSync6,openSync,readdirSync,readFileSync as readFileSync7,renameSync as renameSync2,rmSync,statSync as statSync6,writeFileSync as writeFileSync5}from"fs";import{readdir as readdir2,readFile as readFile4,rm as rm2}from"fs/promises";import*as path23 from"path";init_paths();init_knobs();init_logger();init_runtime_status();init_version();import{createCipheriv,createDecipheriv,randomBytes as randomBytes2}from"crypto";import*as zlib from"zlib";var ENCRYPT_MAGIC=Buffer.from("BILIENC1","utf8");var ZSTD_MAGIC=Buffer.from("BILIZSTD1","utf8");var NONCE_LEN=12;var TAG_LEN=16;var ENCRYPT_HEADER_LEN=ENCRYPT_MAGIC.length+2+NONCE_LEN;var MIN_ENCRYPTED_LEN=ENCRYPT_HEADER_LEN+TAG_LEN;var PLAIN_HEADER_LEN=ZSTD_MAGIC.length+2;init_logger();init_billing();init_state_hydration();init_shadow();init_logger();var HOT_ATTACH_WINDOW_MS=10*6e4;var ATTACH_SILENCE_MS=5*6e4;init_backend();init_ingest();init_store();init_logger();init_paths();import{randomUUID as randomUUID2}from"crypto";import{mkdirSync as mkdirSync5,writeFileSync as writeFileSync4}from"fs";import{dirname as dirname3,join as join2}from"path";init_knobs();import{createHash as createHash11,randomUUID as randomUUID3}from"crypto";import{AsyncLocalStorage as AsyncLocalStorage3}from"async_hooks";init_logger();import{createHash as createHash10}from"crypto";import{createHash as createHash9}from"crypto";init_logger();init_logger();init_billing();init_util();var BOOT_ID=randomUUID3();var SEAM_BODY_CAP=512*1024;var BODY_FULL_CAP=8*1024*1024;var captures=new AsyncLocalStorage3;var LEARNED_IMAGE_COST_TTL_MS=24*60*60*1e3;var{join:join4}=path23;var FROZEN_SKIP_NOTICE_COOLDOWN_MS=10*6e4;init_version();init_knobs();init_config();init_config();init_paths();init_logger();init_external_summary_settings();import*as path24 from"path";init_turn_separator();init_turn_separator();var ABORT_REANCHOR_MAX_AGE_MS=30*60*1e3;var MAX_SESSIONS=maxSessions();var MAX_RESIDENT_BYTES=sessionResidentMaxBytes();var SPLIT_CANARY_FRESH_MS=10*60*1e3;import{randomUUID as randomUUID5}from"crypto";init_knobs();var CODEX_FORGED_HANDOFF_HEADER="[bili] context summary after compaction:";var FORGED_SUMMARY_HEADER="[Compressed conversation section]";init_client_config();import fs13 from"fs";import path25 from"path";init_dsh_channel();var SCAN_CACHE_TTL_MS=5*60*1e3;var CONFLICT_ACTIVE_WINDOW_MS=7*24*60*60*1e3;var LAUNCHER_DEFAULT_HOST="127.0.0.1";var HEALTH_PATH="/__bili/health";var HEALTH_POLL_INTERVAL_MS=200;var SPAWN_WAIT_MS=envMillis(process.env,"BILI_SPAWN_WAIT_MS",2e4);var SLOW_START_GRACE_MS=envMillis(process.env,"BILI_SLOW_START_GRACE_MS",4e4);var SPAWN_BUDGET_MS=SPAWN_WAIT_MS+SLOW_START_GRACE_MS;var PROBE_TIMEOUT_MS=1500;var STARTING_MARKER_TTL_MS=SPAWN_BUDGET_MS+3e4;var POST_EXIT_REDISCOVERY_MS=3e3;var DEFAULT_MITM_DOMAIN_SET=new Set(DEFAULT_MITM_DOMAINS.map(d3=>d3.toLowerCase()));function proxyOrigin(host,port){return`http://${host}:${port}`}function healthUrl(origin){return origin+HEALTH_PATH}async function defaultFetch(url){const ctrl=new AbortController;const t=setTimeout(()=>ctrl.abort(),PROBE_TIMEOUT_MS);try{const res=await fetch(url,{signal:ctrl.signal});return{ok:res.ok}}catch{return{ok:false}}finally{clearTimeout(t)}}async function probeHealth(origin,fetchImpl){try{const{ok}=await fetchImpl(healthUrl(origin));return ok}catch{return false}}function describeProbeFailure(err){const e=err;const code=e?.cause?.code??e?.code;if(typeof code==="string"&&code.length>0)return code;if(e?.name==="TimeoutError"||e?.name==="AbortError")return`timeout after ${PROBE_TIMEOUT_MS}ms`;if(typeof e?.message==="string"&&e.message.length>0)return e.message.slice(0,160);return String(err)}async function defaultFetchDetail(url){const ctrl=new AbortController;const t=setTimeout(()=>ctrl.abort(),PROBE_TIMEOUT_MS);try{const res=await fetch(url,{signal:ctrl.signal});return res.ok?{ok:true}:{ok:false,detail:`HTTP ${res.status}`}}catch(err){return{ok:false,detail:describeProbeFailure(err)}}finally{clearTimeout(t)}}async function fetchHealthInfoDefault(origin,opts){try{const res=await fetch(healthUrl(origin),{signal:AbortSignal.timeout(PROBE_TIMEOUT_MS),...opts?.noKeepAlive?{headers:{connection:"close"}}:{}});if(!res.ok)return void 0;const data=await res.json();const info={ok:Boolean(data.ok),instanceId:typeof data.instanceId==="string"?data.instanceId:void 0};if(typeof data.version==="string")info.version=data.version;if(typeof data.pid==="number")info.pid=data.pid;if(typeof data.auxProxy==="string"&&data.auxProxy.length>0)info.auxProxy=data.auxProxy;if(typeof data.auxProxySource==="string"&&data.auxProxySource.length>0)info.auxProxySource=data.auxProxySource;if(data.watchdog&&typeof data.watchdog==="object"&&typeof data.watchdog.armed==="boolean"){const wd=data.watchdog;const watchers=Array.isArray(wd.watchers)?wd.watchers.filter(w4=>typeof w4==="number"):void 0;info.watchdog={armed:wd.armed,watchers}}return info}catch{return void 0}}async function registerWatcherDefault(origin,pid){try{const res=await fetch(`${origin}/__bili/watcher`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({pid}),signal:AbortSignal.timeout(2e3)});if(!res.ok){if(res.status===409)return"refused";console.error(`bili: watcher registration returned HTTP ${res.status} \u2014 the shared proxy may exit when its first owner does`);return"failed"}return"ok"}catch(err){console.error(`bili: watcher registration failed \u2014 the shared proxy may exit when its first owner does (${err instanceof Error?err.message:String(err)})`);return"failed"}}function isStartingMarkerActive(marker,nowMs){return isPidAlive(marker.pid)&&nowMs-marker.startedAt<STARTING_MARKER_TTL_MS}function recordedModelMap(passed,ambientRaw,parse3){return parse3(passed&&Object.keys(passed).length>0?JSON.stringify(passed):ambientRaw)}function instanceShapeMismatch(inst,opts,foreignLanes=[]){if(opts.lane!==void 0&&inst.lane!==void 0&&inst.lane!==opts.lane&&!foreignLanes.includes(inst.lane))return"lane-mismatch";if(inst.host!==opts.host||inst.passthrough!==resolveRecordedPassthrough(opts.passthrough))return"host-or-passthrough-mismatch";const wantDomains=resolveRecordedMitmDomains(opts.mitmDomains);if(inst.mitmDomains.length!==wantDomains.length||inst.mitmDomains.some((d3,i)=>d3!==wantDomains[i]))return"mitm-domains-mismatch";const wantWindows=recordedModelMap(opts.modelWindows,process.env.BILI_LAUNCHER_MODEL_WINDOWS,parseLauncherModelWindows);if(Object.keys(inst.modelWindows).length!==Object.keys(wantWindows).length)return"model-windows-mismatch";if(!Object.keys(wantWindows).every(k2=>inst.modelWindows[k2]===wantWindows[k2]))return"model-windows-mismatch";const wantMax=recordedModelMap(opts.modelMaxOutputs,process.env.BILI_LAUNCHER_MODEL_MAX_OUTPUTS,parseLauncherModelMaxOutputs);if(Object.keys(inst.modelMaxOutputs??{}).length!==Object.keys(wantMax).length)return"model-max-outputs-mismatch";return Object.keys(wantMax).every(k2=>(inst.modelMaxOutputs??{})[k2]===wantMax[k2])?void 0:"model-max-outputs-mismatch"}function isNewerSameLaneHolder(inst,optsLane,healthVersion,ownVersion,userZone){if(userZone||optsLane===void 0||healthVersion===void 0)return false;return inst.lane===optsLane&&isVersionNewer(healthVersion,ownVersion)}function instanceCompatible(inst,opts,codeFingerprint,foreignLanes=[]){if(inst.codeFingerprint===void 0||inst.codeFingerprint!==codeFingerprint)return"code-fingerprint-mismatch";return instanceShapeMismatch(inst,opts,foreignLanes)}async function probeLiveInstances(readInstance,fetchHealthInfo,diag,isConnectable=tcpConnectable){const seen=new Map;const inst=readInstance();if(isProxyInstanceFile(inst))seen.set(inst.instanceId||inst.origin,inst);for(const live of discoverLiveInstances())seen.set(live.instanceId||live.origin,live);const checked=await Promise.all([...seen.values()].map(async c=>{if(!isPidAlive(c.pid)){diag?.(`native-attach: drop ${c.origin} (pid ${c.pid}): owner process gone`);return void 0}const health=await fetchHealthInfo(c.origin);if(!health||!health.ok){if(health===void 0&&await isConnectable(c.origin)){diag?.(`native-attach: keep ${c.origin} (pid ${c.pid}): health probe failed but TCP connect succeeded \u2014 instance is BUSY (event loop saturated), not dead (#3654/#4811)`);return{inst:c,health:void 0}}diag?.(health===void 0?`native-attach: drop ${c.origin} (pid ${c.pid}): health probe failed`:`native-attach: drop ${c.origin} (pid ${c.pid}): health probe answered but reports not-ok`);return void 0}if(health.instanceId!==void 0&&health.instanceId!==c.instanceId){diag?.(`native-attach: drop ${c.origin} (pid ${c.pid}): instance id mismatch (${c.instanceId} vs ${health.instanceId})`);return void 0}return{inst:c,health}}));return checked.filter(c=>c!==void 0)}function attachGateAllows(health,attachExternal){if(attachExternal)return true;return health?.watchdog?.armed===true}function isUserZoneInstance(inst){return inst.lane===void 0&&inst.launchToken===void 0}function gateRefusalMessage(inst,health){const reason=health.watchdog&&health.watchdog.armed===false?"it reports NO session-lifecycle watchdog (started without BILI_PARENT_PID, e.g. manual `bili start`)":"it does not report watchdog state (older bili build) \u2014 its lifecycle is unverifiable";return`bili: refusing to attach to ${inst.origin} (pid ${inst.pid}) \u2014 ${reason}. It would outlive this session and ignore config edits until killed (#1322/#1335). Starting a session-owned proxy instead; set native.attachExternal=true or BILI_NATIVE_ATTACH_EXTERNAL=1 to attach anyway.`}function attachClass(inst,lane,foreignLanes){if(lane===void 0)return 1;if(inst.lane===lane)return 0;if(inst.lane!==void 0)return 1+foreignLanes.indexOf(inst.lane);return foreignLanes.length+1}function normalizeOrigin(o){return o.trim().replace(/\/+$/,"").toLowerCase()}function pickAttachable(candidates,opts,codeFingerprint,attachExternal,attachPolicy,attachUrl,refusedLog,diag,foreignLanes=[]){let best;let bestClass=Number.MAX_SAFE_INTEGER;let bestStartedAt=Number.NEGATIVE_INFINITY;for(const c of candidates){if(attachUrl&&normalizeOrigin(c.inst.origin)!==normalizeOrigin(attachUrl)){diag?.(`native-attach: skip ${c.inst.origin} (pid ${c.inst.pid}): not the explicit attachUrl target`);continue}let incompatible=instanceCompatible(c.inst,opts,codeFingerprint,foreignLanes);if(incompatible==="code-fingerprint-mismatch"&&c.health?.version!==void 0&&isNewerSameLaneHolder(c.inst,opts.lane,c.health.version,VERSION,isUserZoneInstance(c.inst))){const adoptedShape=instanceShapeMismatch(c.inst,opts,foreignLanes);if(adoptedShape===void 0){diag?.(`native-attach: adopt ${c.inst.origin} (pid ${c.inst.pid}): foreign bytes but self-reported v${c.health.version} is strictly NEWER than this lane's v${VERSION} \u2014 riding the newer build instead of deadlocking behind it (#4125)`);incompatible=void 0}else{diag?.(`native-attach: skip ${c.inst.origin} (pid ${c.inst.pid}): reports v${c.health.version} (newer) but its config shape differs (${adoptedShape}) \u2014 shape guards survive upward adoption (#4125)`);incompatible=adoptedShape}}if(incompatible!==void 0){diag?.(`native-attach: skip ${c.inst.origin} (pid ${c.inst.pid}): incompatible (${incompatible})`);continue}if(opts.strictPort&&c.inst.port!==opts.port){diag?.(`native-attach: skip ${c.inst.origin} (pid ${c.inst.pid}): port mismatch`);continue}const sameLane=opts.lane!==void 0&&c.inst.lane===opts.lane;if(!attachUrl&&!attachExternal&&attachPolicy==="own-lane"&&opts.lane!==void 0&&!sameLane&&c.health?.watchdog?.armed!==true){diag?.(`native-attach: skip ${c.inst.origin} (pid ${c.inst.pid}): not own lane and not an armed shared daemon (attachPolicy=own-lane)`);continue}if(c.health===void 0){if(!sameLane&&!attachExternal&&!isUserZoneInstance(c.inst)){if(!refusedLog.has(c.inst.origin)){refusedLog.add(c.inst.origin);const msg=`bili: refusing to attach to ${c.inst.origin} (pid ${c.inst.pid}) \u2014 health probe silent but TCP alive (BUSY, event loop saturated #3654) and its lifecycle is unverifiable from this lane. Starting a session-owned proxy instead; set native.attachExternal=true or BILI_NATIVE_ATTACH_EXTERNAL=1 to attach anyway.`;console.error(msg);diag?.(msg)}continue}}else if(!attachGateAllows(c.health,attachExternal)&&!isUserZoneInstance(c.inst)){if(!refusedLog.has(c.inst.origin)){refusedLog.add(c.inst.origin);console.error(gateRefusalMessage(c.inst,c.health));diag?.(gateRefusalMessage(c.inst,c.health))}continue}const cls=attachClass(c.inst,opts.lane,foreignLanes);if(cls<bestClass||cls===bestClass&&c.inst.startedAt>bestStartedAt){best=c.inst;bestClass=cls;bestStartedAt=c.inst.startedAt}}return best}async function waitForStarterInstance(readInstance,fetchHealthInfo,now,sleepImpl,opts,codeFingerprint,attachExternal,attachPolicy,attachUrl,refusedLog,diag,foreignLanes=[],isConnectable=tcpConnectable){const deadline=now()+SPAWN_BUDGET_MS;const probe=async()=>pickAttachable(await probeLiveInstances(readInstance,fetchHealthInfo,diag,isConnectable),opts,codeFingerprint,attachExternal,attachPolicy,attachUrl,refusedLog,diag,foreignLanes);let inst;while(now()<deadline){await sleepImpl(HEALTH_POLL_INTERVAL_MS);inst=await probe();if(inst)break;const still=readStartingMarker();if(!still||!isStartingMarkerActive(still,now()))break}return inst??await probe()}function defaultAttachDiag(debug2){return msg=>{logHostEvent("info","",msg);if(debug2)process.stderr.write(`${logTimestamp()} [info] [v=${VERSION}] ${msg}
130
130
  `)}}function pickEphemeralPort(host=LAUNCHER_DEFAULT_HOST){return new Promise((resolve,reject)=>{const srv=net3.createServer();srv.once("error",reject);srv.listen(0,host,()=>{const addr=srv.address();srv.close(()=>{if(addr&&typeof addr==="object")resolve(addr.port);else reject(new Error("could not allocate a free port"))})})})}var INHERITED_PROXY_VARS=["http_proxy","https_proxy","all_proxy","HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","no_proxy","NO_PROXY"];var INTERNAL_LAUNCHER_CHANNEL_VARS=["BILI_LAUNCHER_LANE","BILI_LAUNCHER_MODEL_WINDOWS","BILI_LAUNCHER_MODEL_MAX_OUTPUTS","BILI_STRICT_PORT"];function stripInternalLauncherChannels(env){const cleaned={...env};for(const key of INTERNAL_LAUNCHER_CHANNEL_VARS)delete cleaned[key];return cleaned}function stripInheritedProxy(env){const cleaned={...env};for(const key of INHERITED_PROXY_VARS)delete cleaned[key];return stripInternalLauncherChannels(cleaned)}var INHERITED_LAUNCHER_CHANNELS=["BILI_LAUNCHER_LANE","BILI_LAUNCHER_MODEL_WINDOWS","BILI_LAUNCHER_MODEL_MAX_OUTPUTS","BILI_STRICT_PORT",SPAWN_FINGERPRINT_ENV];function stripInheritedLauncherChannels(env){const cleaned={...env};for(const key of INHERITED_LAUNCHER_CHANNELS)delete cleaned[key];return cleaned}function captureInheritedProxyEnv(env){const captured={};const pairs=[["BILI_INHERITED_HTTP_PROXY",env.HTTP_PROXY,env.http_proxy],["BILI_INHERITED_HTTPS_PROXY",env.HTTPS_PROXY,env.https_proxy],["BILI_INHERITED_ALL_PROXY",env.ALL_PROXY,env.all_proxy],["BILI_INHERITED_NO_PROXY",env.NO_PROXY,env.no_proxy]];for(const[name,upper,lower]of pairs){const value=(upper??lower??"").trim();if(value)captured[name]=value}return captured}function proxyStartArgs(opts){const args=["start","--host",opts.host,"--port",String(opts.port)];if(opts.passthrough)args.push("--passthrough");if(opts.debug)args.push("--debug");return args}function probeNodeWrapperTarget(candidate,env){try{const out=execFileSync5(candidate,["-p","process.execPath"],{windowsHide:true,timeout:5e3,encoding:"utf8",stdio:["ignore","pipe","pipe"],env});const p2=out.trim();return p2.length>0?p2:void 0}catch{return void 0}}function probeNodeMajor(candidate,env){try{const out=execFileSync5(candidate,["--version"],{windowsHide:true,timeout:5e3,encoding:"utf8",stdio:["ignore","pipe","pipe"],env});const m4=/^v(\d+)\.\d+\.\d+/.exec(out.trim());return m4?Number(m4[1]):void 0}catch{return void 0}}var MIN_PROXY_NODE_MAJOR=20;function looksLikeNodeExecutable(p2,platform){if(platform==="win32"){if(!/^[a-zA-Z]:[\\/]/.test(p2))return false}else if(!p2.startsWith("/")){return false}const base=p2.split(/[\\/]/).pop()?.toLowerCase()??"";return base==="node"||base==="node.exe"}function resolveNodeRuntime(execPath=process.execPath,env=process.env,platform=process.platform,existsImpl=fs14.existsSync,electronVersion=typeof process.versions.electron==="string"?process.versions.electron:void 0,probeWrapper=probeNodeWrapperTarget,probeNode=probeNodeMajor){const base=path26.basename(execPath).toLowerCase();if(base==="node"||base==="node.exe")return execPath;const override=typeof env.BILLION_CONTEXT_NODE==="string"?env.BILLION_CONTEXT_NODE.trim():"";if(override.length>0&&existsImpl(override))return override;const resolveDiscovered=candidate=>{let subject=candidate;if(platform==="win32"){const probed=probeWrapper(candidate,env);const target=probed?.trim();if(target&&target.length>0&&looksLikeNodeExecutable(target,platform)&&existsImpl(target)){if(target.toLowerCase()!==candidate.toLowerCase()){log("info",`bili: ${candidate} is a Windows node wrapper resolving to ${target} \u2014 spawning the real Node directly (#1887)`);subject=target}}}const major=probeNode(subject,env);if(major===void 0||major<MIN_PROXY_NODE_MAJOR)return void 0;return subject};const sep=platform==="win32"?";":":";const names=platform==="win32"?["node.exe"]:["node"];const home=platform==="win32"?env.USERPROFILE??"":env.HOME??"";const voltaHome=platform==="win32"?env.VOLTA_HOME??(home?home+"/Tools/volta":""):home?home+"/.volta":"";const extraDirs=platform==="win32"?["C:/Program Files/nodejs",env.LOCALAPPDATA?env.LOCALAPPDATA+"/Programs/nodejs":"",voltaHome?voltaHome+"/bin":""]:["/usr/local/bin","/opt/homebrew/bin","/opt/local/bin",voltaHome?voltaHome+"/bin":"",home?home+"/.local/bin":""];for(const dir of[...(env.PATH??"").split(sep),...extraDirs]){if(!dir)continue;for(const name of names){const candidate=dir.endsWith("/")||dir.endsWith("\\")?dir+name:dir+"/"+name;if(!existsImpl(candidate))continue;const resolved=resolveDiscovered(candidate);if(resolved!==void 0)return resolved;log("warn",`bili: skipping ${candidate} \u2014 not a usable Node runtime (--version did not report v${MIN_PROXY_NODE_MAJOR}+; set BILLION_CONTEXT_NODE if this is wrong, #3383)`)}}if(electronVersion&&electronVersion.length>0){log("warn",`bili: no usable Node runtime found on PATH or install dirs \u2014 falling back to the Electron host binary ${execPath} run as Node via ELECTRON_RUN_AS_NODE=1 (#1429/#3383)`);return execPath}throw new Error("bili: cannot find a Node runtime to spawn the proxy (this process is not Node) \u2014 set BILLION_CONTEXT_NODE")}var PORT_LOG_MAX_BYTES=5*1024*1024;function rotatePortLogIfNeeded(logPath2){try{if(fs14.statSync(logPath2).size<PORT_LOG_MAX_BYTES)return;try{fs14.unlinkSync(`${logPath2}.old`)}catch{}fs14.renameSync(logPath2,`${logPath2}.old`)}catch{}}var STALE_ROTATION_WAIT_MS=12e3;var SHUTDOWN_REQUEST_TIMEOUT_MS=3e3;var OWNER_HEARTBEAT_INTERVAL_MS=5e3;var OWNER_HEARTBEAT_POST_TIMEOUT_MS=2e3;async function requestInstanceShutdown(origin){try{const res=await fetch(`${origin}/__bili/shutdown`,{method:"POST",headers:{"content-type":"application/json",connection:"close"},body:"{}",signal:AbortSignal.timeout(SHUTDOWN_REQUEST_TIMEOUT_MS)});return res.ok}catch{return false}}async function rotateStalePredecessor(probed,resolveTargetPort,opts,attachUrl,foreignLanes,fetchHealthInfoNoReuse,now,sleep,requestShutdown){if(attachUrl!==void 0)return;const stale=probed.filter(c=>c.health!==void 0&&!isUserZoneInstance(c.inst)&&c.health.watchdog?.armed===true&&instanceShapeMismatch(c.inst,opts,foreignLanes)===void 0&&c.health.version!==void 0&&isVersionNewer(VERSION,c.health.version));if(stale.length===0)return;const targetPort=resolveTargetPort();if(targetPort===void 0)return;const candidate=stale.find(c=>c.inst.port===targetPort);if(!candidate)return;const running=candidate.health.version;if(running===void 0||!isVersionNewer(VERSION,running))return;console.error(`bili: rotating stale proxy ${candidate.inst.origin} (pid ${candidate.inst.pid}, running v${running}) \u2014 ours is v${VERSION}; requesting graceful shutdown before taking over port ${targetPort}`);const asked=await requestShutdown(candidate.inst.origin);if(!asked){console.error(`bili: stale rotation skipped \u2014 ${candidate.inst.origin} refused /__bili/shutdown (older build); falling back to the normal spawn ladder`);return}const deadline=now()+STALE_ROTATION_WAIT_MS;for(;;){const h=await fetchHealthInfoNoReuse(candidate.inst.origin);if(!h?.ok)break;if(now()>=deadline){console.error(`bili: stale rotation timed out after ${STALE_ROTATION_WAIT_MS}ms \u2014 ${candidate.inst.origin} still accepts fresh connections (listener open); falling back to the normal spawn ladder`);return}await sleep(HEALTH_POLL_INTERVAL_MS)}}function startOwnerHeartbeat(origin,pid,intervalMs=OWNER_HEARTBEAT_INTERVAL_MS,post){if(pid!==process.pid)return void 0;if(post!==void 0)return runOwnerHeartbeatLoop(post,pid,intervalMs);return runOwnerHeartbeatWorker(origin,pid,intervalMs)}var ownerHeartbeatWorkers=new Map;function runOwnerHeartbeatLoop(post,pid,intervalMs){let stopped=false;const beat=async()=>{while(!stopped){await new Promise(r=>{const t=setTimeout(r,intervalMs);t.unref?.()});if(stopped)return;try{await post(JSON.stringify({pid,hb:true}))}catch{}}};void beat();return()=>{stopped=true}}var OWNER_HEARTBEAT_WORKER_SOURCE=`
131
131
  const { parentPort, workerData } = require("node:worker_threads");
132
132
  const { origin, pid, intervalMs, timeoutMs } = workerData;