interscale 0.0.0-stage → 0.10.96

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.
@@ -0,0 +1,114 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __interscaleRequire } from "node:module"; const require = __interscaleRequire(import.meta.url);
3
+ var Zf=Object.create;var mi=Object.defineProperty;var Qf=Object.getOwnPropertyDescriptor;var em=Object.getOwnPropertyNames;var tm=Object.getPrototypeOf,rm=Object.prototype.hasOwnProperty;var a=(t,e)=>mi(t,"name",{value:e,configurable:!0}),U=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var C=(t,e,r)=>()=>{if(r)throw r[0];try{return t&&(e=t(t=0)),e}catch(n){throw r=[n],n}};var A=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},nm=(t,e)=>{for(var r in e)mi(t,r,{get:e[r],enumerable:!0})},im=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of em(e))!rm.call(t,i)&&i!==r&&mi(t,i,{get:()=>e[i],enumerable:!(n=Qf(e,i))||n.enumerable});return t};var ot=(t,e,r)=>(r=t!=null?Zf(tm(t)):{},im(e||!t||!t.__esModule?mi(r,"default",{value:t,enumerable:!0}):r,t));function _i(t){let e={};for(let r of["retryable","terminal"])typeof t?.[r]=="boolean"&&(e[r]=t[r]);for(let[r,n]of[["next_action",2e3],["request_id",200],["operation_id",200],["job_id",200],["transfer_id",200],["session_id",220],["idempotency_key",200],["question_id",200]]){let i=r==="transfer_id"?t?.transfer_id??t?.transferId:t?.[r];typeof i=="string"&&i.length&&(e[r]=i.slice(0,n))}return e}var M,R,le=C(()=>{a(_i,"publicErrorDetails");M=class extends Error{static{a(this,"InterscaleError")}constructor(e,r,n={}){super(r,n),this.name="InterscaleError",this.code=e,this.exitCode=n.exitCode??1}},R=class extends M{static{a(this,"ApiError")}constructor(e,r,n,i={}){super(r,n,i),this.name="ApiError",this.status=e}}});import cm from"events";import oe from"fs";import{EventEmitter as ta}from"node:events";import Ml from"node:stream";import{StringDecoder as lm}from"node:string_decoder";import Fl from"node:path";import Mr from"node:fs";import{dirname as Em,parse as Sm}from"path";import{EventEmitter as Nm}from"events";import Uo from"assert";import{Buffer as lr}from"buffer";import*as cl from"zlib";import Lm from"zlib";import{posix as Lr}from"node:path";import{basename as o_}from"node:path";import Wi from"fs";import Fe from"fs";import _l from"path";import{win32 as w_}from"node:path";import Sl from"path";import id from"node:fs";import U_ from"node:assert";import{randomBytes as sd}from"node:crypto";import N from"node:fs";import H from"node:path";import od from"fs";import Qi from"node:fs";import In from"node:path";import he from"node:fs";import z_ from"node:fs/promises";import Vi from"node:path";import{join as gd}from"node:path";import ue from"node:fs";import bd from"node:path";function I_(t,e,r){let n=e,i=e?e.next:t.head,s=new ca(r,n,i,t);return s.next===void 0&&(t.tail=s),s.prev===void 0&&(t.head=s),t.length++,s}function A_(t,e){t.tail=new ca(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function N_(t,e){t.head=new ca(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var om,am,il,dm,um,hm,at,ct,Ct,gi,un,yi,sl,wi,ol,xe,Nr,V,hn,Ur,J,te,Y,oo,bi,ee,z,ao,co,al,lo,je,uo,vi,pn,er,de,fn,pm,fm,mm,_m,$l,gm,ym,wm,hr,bm,Ft,Ie,mn,P,ho,ht,po,Po,Do,kn,Ei,qr,Fr,fo,Br,zt,Oe,Bt,Me,jr,mo,ut,_n,_o,Li,tr,Ci,cr,ra,vm,Ji,ql,Tm,xm,Rm,km,Om,Im,Am,na,Un,Cm,We,Pm,ll,Dm,go,dr,Si,yo,ia,zl,Um,Bm,Wl,jm,Mm,Hl,$m,qm,Fm,zm,Wm,Hm,Gm,Vm,Gl,Vl,Jm,Pi,Ym,Jl,Yi,sa,Km,ur,Xm,rr,wo,Zm,jt,Qm,e_,t_,Mt,r_,n_,i_,bo,s_,nr,zi,a_,c_,l_,d_,O,u_,Ki,h_,Bo,jo,p_,we,ir,lt,vo,dl,$e,gn,Pt,ul,j,dt,Dt,Eo,sr,q,Ti,xi,So,hl,pl,yn,To,Ri,Cr,qe,ki,or,Oi,Ii,fl,f_,wn,xo,ml,m_,Dn,On,__,Kl,g_,y_,zr,Xl,b_,gl,oa,Xi,aa,v_,E_,yl,S_,Zl,T_,wl,bl,vl,Mo,El,bn,Di,$o,Ui,qo,Fo,zo,Wo,$t,Hi,Ho,Ro,ze,Ql,x_,R_,k_,O_,ca,Tl,xl,Bi,vn,Re,En,Ut,ar,Sn,Ai,ke,ko,ji,Rl,Go,Vo,Mi,$i,kl,Oo,qi,ed,Io,Zi,la,L_,C_,td,rd,P_,D_,nd,B_,ad,cd,Ol,ld,dd,ud,j_,M_,$_,Il,hd,Jo,Gi,q_,pd,F_,fd,md,es,W_,H_,Yo,_d,G_,V_,Ao,Al,Pr,J_,Y_,K_,X_,Z_,Q_,Nl,Ko,Ll,Xo,be,Zo,Qo,Fi,Cl,Pl,Rn,Dl,Ul,No,qt,K,Ni,Bl,Dr,Lo,Co,ea,An,Nn,Ln,Cn,eg,Pn,tg,rg,ng,jl,da,Tn,yd,ig,sg,wd,og,ag,cg,lg,dg,xn,r1,ug,vd=C(()=>{om=Object.defineProperty,am=a((t,e)=>{for(var r in e)om(t,r,{get:e[r],enumerable:!0})},"Ur"),il=typeof process=="object"&&process?process:{stdout:null,stderr:null},dm=a(t=>!!t&&typeof t=="object"&&(t instanceof hr||t instanceof Ml||um(t)||hm(t)),"Wr"),um=a(t=>!!t&&typeof t=="object"&&t instanceof ta&&typeof t.pipe=="function"&&t.pipe!==Ml.Writable.prototype.pipe,"Gr"),hm=a(t=>!!t&&typeof t=="object"&&t instanceof ta&&typeof t.write=="function"&&typeof t.end=="function","Zr"),at=Symbol("EOF"),ct=Symbol("maybeEmitEnd"),Ct=Symbol("emittedEnd"),gi=Symbol("emittingEnd"),un=Symbol("emittedError"),yi=Symbol("closed"),sl=Symbol("read"),wi=Symbol("flush"),ol=Symbol("flushChunk"),xe=Symbol("encoding"),Nr=Symbol("decoder"),V=Symbol("flowing"),hn=Symbol("paused"),Ur=Symbol("resume"),J=Symbol("buffer"),te=Symbol("pipes"),Y=Symbol("bufferLength"),oo=Symbol("bufferPush"),bi=Symbol("bufferShift"),ee=Symbol("objectMode"),z=Symbol("destroyed"),ao=Symbol("error"),co=Symbol("emitData"),al=Symbol("emitEnd"),lo=Symbol("emitEnd2"),je=Symbol("async"),uo=Symbol("abort"),vi=Symbol("aborted"),pn=Symbol("signal"),er=Symbol("dataListeners"),de=Symbol("discarded"),fn=a(t=>Promise.resolve().then(t),"jt"),pm=a(t=>t(),"Yr"),fm=a(t=>t==="end"||t==="finish"||t==="prefinish","Kr"),mm=a(t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,"Vr"),_m=a(t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),"$r"),$l=class{static{a(this,"Fe")}src;dest;opts;ondrain;constructor(t,e,r){this.src=t,this.dest=e,this.opts=r,this.ondrain=()=>t[Ur](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},gm=class extends $l{static{a(this,"Li")}unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(t,e,r){super(t,e,r),this.proxyErrors=n=>this.dest.emit("error",n),t.on("error",this.proxyErrors)}},ym=a(t=>!!t.objectMode,"Xr"),wm=a(t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer","qr"),hr=class extends ta{static{a(this,"A")}[V]=!1;[hn]=!1;[te]=[];[J]=[];[ee];[xe];[je];[Nr];[at]=!1;[Ct]=!1;[gi]=!1;[yi]=!1;[un]=null;[Y]=0;[z]=!1;[pn];[vi]=!1;[er]=0;[de]=!1;writable=!0;readable=!0;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");ym(e)?(this[ee]=!0,this[xe]=null):wm(e)?(this[xe]=e.encoding,this[ee]=!1):(this[ee]=!1,this[xe]=null),this[je]=!!e.async,this[Nr]=this[xe]?new lm(this[xe]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:a(()=>this[J],"get")}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:a(()=>this[te],"get")});let{signal:r}=e;r&&(this[pn]=r,r.aborted?this[uo]():r.addEventListener("abort",()=>this[uo]()))}get bufferLength(){return this[Y]}get encoding(){return this[xe]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[ee]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[je]}set async(t){this[je]=this[je]||!!t}[uo](){this[vi]=!0,this.emit("abort",this[pn]?.reason),this.destroy(this[pn]?.reason)}get aborted(){return this[vi]}set aborted(t){}write(t,e,r){if(this[vi])return!1;if(this[at])throw new Error("write after end");if(this[z])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(r=e,e="utf8"),e||(e="utf8");let n=this[je]?fn:pm;if(!this[ee]&&!Buffer.isBuffer(t)){if(_m(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(mm(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[ee]?(this[V]&&this[Y]!==0&&this[wi](!0),this[V]?this.emit("data",t):this[oo](t),this[Y]!==0&&this.emit("readable"),r&&n(r),this[V]):t.length?(typeof t=="string"&&!(e===this[xe]&&!this[Nr]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[xe]&&(t=this[Nr].write(t)),this[V]&&this[Y]!==0&&this[wi](!0),this[V]?this.emit("data",t):this[oo](t),this[Y]!==0&&this.emit("readable"),r&&n(r),this[V]):(this[Y]!==0&&this.emit("readable"),r&&n(r),this[V])}read(t){if(this[z])return null;if(this[de]=!1,this[Y]===0||t===0||t&&t>this[Y])return this[ct](),null;this[ee]&&(t=null),this[J].length>1&&!this[ee]&&(this[J]=[this[xe]?this[J].join(""):Buffer.concat(this[J],this[Y])]);let e=this[sl](t||null,this[J][0]);return this[ct](),e}[sl](t,e){if(this[ee])this[bi]();else{let r=e;t===r.length||t===null?this[bi]():typeof r=="string"?(this[J][0]=r.slice(t),e=r.slice(0,t),this[Y]-=t):(this[J][0]=r.subarray(t),e=r.subarray(0,t),this[Y]-=t)}return this.emit("data",e),!this[J].length&&!this[at]&&this.emit("drain"),e}end(t,e,r){return typeof t=="function"&&(r=t,t=void 0),typeof e=="function"&&(r=e,e="utf8"),t!==void 0&&this.write(t,e),r&&this.once("end",r),this[at]=!0,this.writable=!1,(this[V]||!this[hn])&&this[ct](),this}[Ur](){this[z]||(!this[er]&&!this[te].length&&(this[de]=!0),this[hn]=!1,this[V]=!0,this.emit("resume"),this[J].length?this[wi]():this[at]?this[ct]():this.emit("drain"))}resume(){return this[Ur]()}pause(){this[V]=!1,this[hn]=!0,this[de]=!1}get destroyed(){return this[z]}get flowing(){return this[V]}get paused(){return this[hn]}[oo](t){this[ee]?this[Y]+=1:this[Y]+=t.length,this[J].push(t)}[bi](){return this[ee]?this[Y]-=1:this[Y]-=this[J][0].length,this[J].shift()}[wi](t=!1){do;while(this[ol](this[bi]())&&this[J].length);!t&&!this[J].length&&!this[at]&&this.emit("drain")}[ol](t){return this.emit("data",t),this[V]}pipe(t,e){if(this[z])return t;this[de]=!1;let r=this[Ct];return e=e||{},t===il.stdout||t===il.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,r?e.end&&t.end():(this[te].push(e.proxyErrors?new gm(this,t,e):new $l(this,t,e)),this[je]?fn(()=>this[Ur]()):this[Ur]()),t}unpipe(t){let e=this[te].find(r=>r.dest===t);e&&(this[te].length===1?(this[V]&&this[er]===0&&(this[V]=!1),this[te]=[]):this[te].splice(this[te].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let r=super.on(t,e);if(t==="data")this[de]=!1,this[er]++,!this[te].length&&!this[V]&&this[Ur]();else if(t==="readable"&&this[Y]!==0)super.emit("readable");else if(fm(t)&&this[Ct])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[un]){let n=e;this[je]?fn(()=>n.call(this,this[un])):n.call(this,this[un])}return r}removeListener(t,e){return this.off(t,e)}off(t,e){let r=super.off(t,e);return t==="data"&&(this[er]=this.listeners("data").length,this[er]===0&&!this[de]&&!this[te].length&&(this[V]=!1)),r}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[er]=0,!this[de]&&!this[te].length&&(this[V]=!1)),e}get emittedEnd(){return this[Ct]}[ct](){!this[gi]&&!this[Ct]&&!this[z]&&this[J].length===0&&this[at]&&(this[gi]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[yi]&&this.emit("close"),this[gi]=!1)}emit(t,...e){let r=e[0];if(t!=="error"&&t!=="close"&&t!==z&&this[z])return!1;if(t==="data")return!this[ee]&&!r?!1:this[je]?(fn(()=>this[co](r)),!0):this[co](r);if(t==="end")return this[al]();if(t==="close"){if(this[yi]=!0,!this[Ct]&&!this[z])return!1;let i=super.emit("close");return this.removeAllListeners("close"),i}else if(t==="error"){this[un]=r,super.emit(ao,r);let i=!this[pn]||this.listeners("error").length?super.emit("error",r):!1;return this[ct](),i}else if(t==="resume"){let i=super.emit("resume");return this[ct](),i}else if(t==="finish"||t==="prefinish"){let i=super.emit(t);return this.removeAllListeners(t),i}let n=super.emit(t,...e);return this[ct](),n}[co](t){for(let r of this[te])r.dest.write(t)===!1&&this.pause();let e=this[de]?!1:super.emit("data",t);return this[ct](),e}[al](){return this[Ct]?!1:(this[Ct]=!0,this.readable=!1,this[je]?(fn(()=>this[lo]()),!0):this[lo]())}[lo](){if(this[Nr]){let e=this[Nr].end();if(e){for(let r of this[te])r.dest.write(e);this[de]||super.emit("data",e)}}for(let e of this[te])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[ee]||(t.dataLength=0);let e=this.promise();return this.on("data",r=>{t.push(r),this[ee]||(t.dataLength+=r.length)}),await e,t}async concat(){if(this[ee])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[xe]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(z,()=>e(new Error("stream destroyed"))),this.on("error",r=>e(r)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[de]=!1;let t=!1,e=a(async()=>(this.pause(),t=!0,{value:void 0,done:!0}),"e");return{next:a(()=>{if(t)return e();let r=this.read();if(r!==null)return Promise.resolve({done:!1,value:r});if(this[at])return e();let n,i,s=a(d=>{this.off("data",o),this.off("end",c),this.off(z,l),e(),i(d)},"h"),o=a(d=>{this.off("error",s),this.off("end",c),this.off(z,l),this.pause(),n({value:d,done:!!this[at]})},"a"),c=a(()=>{this.off("error",s),this.off("data",o),this.off(z,l),e(),n({done:!0,value:void 0})},"l"),l=a(()=>s(new Error("stream destroyed")),"c");return new Promise((d,u)=>{i=u,n=d,this.once(z,l),this.once("error",s),this.once("end",c),this.once("data",o)})},"next"),throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[de]=!1;let t=!1,e=a(()=>(this.pause(),this.off(ao,e),this.off(z,e),this.off("end",e),t=!0,{done:!0,value:void 0}),"e"),r=a(()=>{if(t)return e();let n=this.read();return n===null?e():{done:!1,value:n}},"i");return this.once("end",e),this.once(ao,e),this.once(z,e),{next:r,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[z])return t?this.emit("error",t):this.emit(z),this;this[z]=!0,this[de]=!0,this[J].length=0,this[Y]=0;let e=this;return typeof e.close=="function"&&!this[yi]&&e.close(),t?this.emit("error",t):this.emit(z),this}static get isStream(){return dm}},bm=oe.writev,Ft=Symbol("_autoClose"),Ie=Symbol("_close"),mn=Symbol("_ended"),P=Symbol("_fd"),ho=Symbol("_finished"),ht=Symbol("_flags"),po=Symbol("_flush"),Po=Symbol("_handleChunk"),Do=Symbol("_makeBuf"),kn=Symbol("_mode"),Ei=Symbol("_needDrain"),qr=Symbol("_onerror"),Fr=Symbol("_onopen"),fo=Symbol("_onread"),Br=Symbol("_onwrite"),zt=Symbol("_open"),Oe=Symbol("_path"),Bt=Symbol("_pos"),Me=Symbol("_queue"),jr=Symbol("_read"),mo=Symbol("_readSize"),ut=Symbol("_reading"),_n=Symbol("_remain"),_o=Symbol("_size"),Li=Symbol("_write"),tr=Symbol("_writing"),Ci=Symbol("_defaultFlag"),cr=Symbol("_errored"),ra=class extends hr{static{a(this,"_t")}[cr]=!1;[P];[Oe];[mo];[ut]=!1;[_o];[_n];[Ft];constructor(t,e){if(e=e||{},super(e),this.readable=!0,this.writable=!1,typeof t!="string")throw new TypeError("path must be a string");this[cr]=!1,this[P]=typeof e.fd=="number"?e.fd:void 0,this[Oe]=t,this[mo]=e.readSize||16*1024*1024,this[ut]=!1,this[_o]=typeof e.size=="number"?e.size:1/0,this[_n]=this[_o],this[Ft]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[P]=="number"?this[jr]():this[zt]()}get fd(){return this[P]}get path(){return this[Oe]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[zt](){oe.open(this[Oe],"r",(t,e)=>this[Fr](t,e))}[Fr](t,e){t?this[qr](t):(this[P]=e,this.emit("open",e),this[jr]())}[Do](){return Buffer.allocUnsafe(Math.min(this[mo],this[_n]))}[jr](){if(!this[ut]){this[ut]=!0;let t=this[Do]();if(t.length===0)return process.nextTick(()=>this[fo](null,0,t));oe.read(this[P],t,0,t.length,null,(e,r,n)=>this[fo](e,r,n))}}[fo](t,e,r){this[ut]=!1,t?this[qr](t):this[Po](e,r)&&this[jr]()}[Ie](){if(this[Ft]&&typeof this[P]=="number"){let t=this[P];this[P]=void 0,oe.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[qr](t){this[ut]=!0,this[Ie](),this.emit("error",t)}[Po](t,e){let r=!1;return this[_n]-=t,t>0&&(r=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[_n]<=0)&&(r=!1,this[Ie](),super.end()),r}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[P]=="number"&&this[jr](),!1;case"error":return this[cr]?!1:(this[cr]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},vm=class extends ra{static{a(this,"Be")}[zt](){let t=!0;try{this[Fr](null,oe.openSync(this[Oe],"r")),t=!1}finally{t&&this[Ie]()}}[jr](){let t=!0;try{if(!this[ut]){this[ut]=!0;do{let e=this[Do](),r=e.length===0?0:oe.readSync(this[P],e,0,e.length,null);if(!this[Po](r,e))break}while(!0);this[ut]=!1}t=!1}finally{t&&this[Ie]()}}[Ie](){if(this[Ft]&&typeof this[P]=="number"){let t=this[P];this[P]=void 0,oe.closeSync(t),this.emit("close")}}},Ji=class extends cm{static{a(this,"et")}readable=!1;writable=!0;[cr]=!1;[tr]=!1;[mn]=!1;[Me]=[];[Ei]=!1;[Oe];[kn];[Ft];[P];[Ci];[ht];[ho]=!1;[Bt];constructor(t,e){e=e||{},super(e),this[Oe]=t,this[P]=typeof e.fd=="number"?e.fd:void 0,this[kn]=e.mode===void 0?438:e.mode,this[Bt]=typeof e.start=="number"?e.start:void 0,this[Ft]=typeof e.autoClose=="boolean"?e.autoClose:!0;let r=this[Bt]!==void 0?"r+":"w";this[Ci]=e.flags===void 0,this[ht]=e.flags===void 0?r:e.flags,this[P]===void 0&&this[zt]()}emit(t,...e){if(t==="error"){if(this[cr])return!1;this[cr]=!0}return super.emit(t,...e)}get fd(){return this[P]}get path(){return this[Oe]}[qr](t){this[Ie](),this[tr]=!0,this.emit("error",t)}[zt](){oe.open(this[Oe],this[ht],this[kn],(t,e)=>this[Fr](t,e))}[Fr](t,e){this[Ci]&&this[ht]==="r+"&&t&&t.code==="ENOENT"?(this[ht]="w",this[zt]()):t?this[qr](t):(this[P]=e,this.emit("open",e),this[tr]||this[po]())}end(t,e){return t&&this.write(t,e),this[mn]=!0,!this[tr]&&!this[Me].length&&typeof this[P]=="number"&&this[Br](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[mn]?(this.emit("error",new Error("write() after end()")),!1):this[P]===void 0||this[tr]||this[Me].length?(this[Me].push(t),this[Ei]=!0,!1):(this[tr]=!0,this[Li](t),!0)}[Li](t){oe.write(this[P],t,0,t.length,this[Bt],(e,r)=>this[Br](e,r))}[Br](t,e){t?this[qr](t):(this[Bt]!==void 0&&typeof e=="number"&&(this[Bt]+=e),this[Me].length?this[po]():(this[tr]=!1,this[mn]&&!this[ho]?(this[ho]=!0,this[Ie](),this.emit("finish")):this[Ei]&&(this[Ei]=!1,this.emit("drain"))))}[po](){if(this[Me].length===0)this[mn]&&this[Br](null,0);else if(this[Me].length===1)this[Li](this[Me].pop());else{let t=this[Me];this[Me]=[],bm(this[P],t,this[Bt],(e,r)=>this[Br](e,r))}}[Ie](){if(this[Ft]&&typeof this[P]=="number"){let t=this[P];this[P]=void 0,oe.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},ql=class extends Ji{static{a(this,"Wt")}[zt](){let t;if(this[Ci]&&this[ht]==="r+")try{t=oe.openSync(this[Oe],this[ht],this[kn])}catch(e){if(e?.code==="ENOENT")return this[ht]="w",this[zt]();throw e}else t=oe.openSync(this[Oe],this[ht],this[kn]);this[Fr](null,t)}[Ie](){if(this[Ft]&&typeof this[P]=="number"){let t=this[P];this[P]=void 0,oe.closeSync(t),this.emit("close")}}[Li](t){let e=!0;try{this[Br](null,oe.writeSync(this[P],t,0,t.length,this[Bt])),e=!1}finally{if(e)try{this[Ie]()}catch{}}}},Tm=new Map([["C","cwd"],["f","file"],["z","gzip"],["P","preservePaths"],["U","unlink"],["strip-components","strip"],["stripComponents","strip"],["keep-newer","newer"],["keepNewer","newer"],["keep-newer-files","newer"],["keepNewerFiles","newer"],["k","keep"],["keep-existing","keep"],["keepExisting","keep"],["m","noMtime"],["no-mtime","noMtime"],["p","preserveOwner"],["L","follow"],["h","follow"],["onentry","onReadEntry"]]),xm=a(t=>!!t.sync&&!!t.file,"Fs"),Rm=a(t=>!t.sync&&!!t.file,"ks"),km=a(t=>!!t.sync&&!t.file,"vs"),Om=a(t=>!t.sync&&!t.file,"Ms"),Im=a(t=>!!t.file,"Bs"),Am=a(t=>Tm.get(t)||t,"tn"),na=a((t={})=>{if(!t)return{};let e={};for(let[r,n]of Object.entries(t)){let i=Am(r);e[i]=n}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},"se"),Un=a((t,e,r,n,i)=>Object.assign((s=[],o,c)=>{Array.isArray(s)&&(o=s,s={}),typeof o=="function"&&(c=o,o=void 0),o=o?Array.from(o):[];let l=na(s);if(i?.(l,o),xm(l)){if(typeof c=="function")throw new TypeError("callback not supported for sync tar functions");return t(l,o)}else if(Rm(l)){let d=e(l,o);return c?d.then(()=>c(),c):d}else if(km(l)){if(typeof c=="function")throw new TypeError("callback not supported for sync tar functions");return r(l,o)}else if(Om(l)){if(typeof c=="function")throw new TypeError("callback only supported with file option");return n(l,o)}throw new Error("impossible options??")},{syncFile:t,asyncFile:e,syncNoFile:r,asyncNoFile:n,validate:i}),"K"),Cm=Lm.constants||{ZLIB_VERNUM:4736},We=Object.freeze(Object.assign(Object.create(null),{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:1/0,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1,BROTLI_OPERATION_PROCESS:0,BROTLI_OPERATION_FLUSH:1,BROTLI_OPERATION_FINISH:2,BROTLI_OPERATION_EMIT_METADATA:3,BROTLI_MODE_GENERIC:0,BROTLI_MODE_TEXT:1,BROTLI_MODE_FONT:2,BROTLI_DEFAULT_MODE:0,BROTLI_MIN_QUALITY:0,BROTLI_MAX_QUALITY:11,BROTLI_DEFAULT_QUALITY:11,BROTLI_MIN_WINDOW_BITS:10,BROTLI_MAX_WINDOW_BITS:24,BROTLI_LARGE_MAX_WINDOW_BITS:30,BROTLI_DEFAULT_WINDOW:22,BROTLI_MIN_INPUT_BLOCK_BITS:16,BROTLI_MAX_INPUT_BLOCK_BITS:24,BROTLI_PARAM_MODE:0,BROTLI_PARAM_QUALITY:1,BROTLI_PARAM_LGWIN:2,BROTLI_PARAM_LGBLOCK:3,BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING:4,BROTLI_PARAM_SIZE_HINT:5,BROTLI_PARAM_LARGE_WINDOW:6,BROTLI_PARAM_NPOSTFIX:7,BROTLI_PARAM_NDIRECT:8,BROTLI_DECODER_RESULT_ERROR:0,BROTLI_DECODER_RESULT_SUCCESS:1,BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:2,BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:0,BROTLI_DECODER_PARAM_LARGE_WINDOW:1,BROTLI_DECODER_NO_ERROR:0,BROTLI_DECODER_SUCCESS:1,BROTLI_DECODER_NEEDS_MORE_INPUT:2,BROTLI_DECODER_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:-1,BROTLI_DECODER_ERROR_FORMAT_RESERVED:-2,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:-3,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:-4,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:-5,BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:-6,BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:-7,BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:-8,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:-9,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:-10,BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:-11,BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:-12,BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:-13,BROTLI_DECODER_ERROR_FORMAT_PADDING_1:-14,BROTLI_DECODER_ERROR_FORMAT_PADDING_2:-15,BROTLI_DECODER_ERROR_FORMAT_DISTANCE:-16,BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:-19,BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:-20,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:-21,BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:-22,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:-25,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:-26,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:-27,BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:-30,BROTLI_DECODER_ERROR_UNREACHABLE:-31},Cm)),Pm=lr.concat,ll=Object.getOwnPropertyDescriptor(lr,"concat"),Dm=a(t=>t,"nn"),go=ll?.writable===!0||ll?.set!==void 0?t=>{lr.concat=t?Dm:Pm}:t=>{},dr=Symbol("_superWrite"),Si=class extends Error{static{a(this,"Gt")}code;errno;constructor(t,e){super("zlib: "+t.message,{cause:t}),this.code=t.code,this.errno=t.errno,this.code||(this.code="ZLIB_ERROR"),this.message="zlib: "+t.message,Error.captureStackTrace(this,e??this.constructor)}get name(){return"ZlibError"}},yo=Symbol("flushFlag"),ia=class extends hr{static{a(this,"re")}#e=!1;#r=!1;#n;#s;#i;#t;#o;get sawError(){return this.#e}get handle(){return this.#t}get flushFlag(){return this.#n}constructor(t,e){if(!t||typeof t!="object")throw new TypeError("invalid options for ZlibBase constructor");if(super(t),this.#n=t.flush??0,this.#s=t.finishFlush??0,this.#i=t.fullFlushFlag??0,typeof cl[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new cl[e](t)}catch(r){throw new Si(r,this.constructor)}this.#o=r=>{this.#e||(this.#e=!0,this.close(),this.emit("error",r))},this.#t?.on("error",r=>this.#o(new Si(r))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return Uo(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#i),this.write(Object.assign(lr.alloc(0),{[yo]:t})))}end(t,e,r){return typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),t&&(e?this.write(t,e):this.write(t)),this.flush(this.#s),this.#r=!0,super.end(r)}get ended(){return this.#r}[dr](t){return super.write(t)}write(t,e,r){if(typeof e=="function"&&(r=e,e="utf8"),typeof t=="string"&&(t=lr.from(t,e)),this.#e)return;Uo(this.#t,"zlib binding closed");let n=this.#t._handle,i=n.close;n.close=()=>{};let s=this.#t.close;this.#t.close=()=>{},go(!0);let o;try{let l=typeof t[yo]=="number"?t[yo]:this.#n;o=this.#t._processChunk(t,l),go(!1)}catch(l){go(!1),this.#o(new Si(l,this.write))}finally{this.#t&&(this.#t._handle=n,n.close=i,this.#t.close=s,this.#t.removeAllListeners("error"))}this.#t&&this.#t.on("error",l=>this.#o(new Si(l,this.write)));let c;if(o)if(Array.isArray(o)&&o.length>0){let l=o[0];c=this[dr](lr.from(l));for(let d=1;d<o.length;d++)c=this[dr](o[d])}else c=this[dr](lr.from(o));return r&&r(),c}},zl=class extends ia{static{a(this,"Pe")}#e;#r;constructor(t,e){t=t||{},t.flush=t.flush||We.Z_NO_FLUSH,t.finishFlush=t.finishFlush||We.Z_FINISH,t.fullFlushFlag=We.Z_FULL_FLUSH,super(t,e),this.#e=t.level,this.#r=t.strategy}params(t,e){if(!this.sawError){if(!this.handle)throw new Error("cannot switch params when binding is closed");if(!this.handle.params)throw new Error("not supported in this implementation");if(this.#e!==t||this.#r!==e){this.flush(We.Z_SYNC_FLUSH),Uo(this.handle,"zlib binding closed");let r=this.handle.flush;this.handle.flush=(n,i)=>{typeof n=="function"&&(i=n,n=this.flushFlag),this.flush(n),i?.()};try{this.handle.params(t,e)}finally{this.handle.flush=r}this.handle&&(this.#e=t,this.#r=e)}}}},Um=class extends zl{static{a(this,"ze")}#e;constructor(t){super(t,"Gzip"),this.#e=t&&!!t.portable}[dr](t){return this.#e?(this.#e=!1,t[9]=255,super[dr](t)):super[dr](t)}},Bm=class extends zl{static{a(this,"Ue")}constructor(t){super(t,"Unzip")}},Wl=class extends ia{static{a(this,"He")}constructor(t,e){t=t||{},t.flush=t.flush||We.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||We.BROTLI_OPERATION_FINISH,t.fullFlushFlag=We.BROTLI_OPERATION_FLUSH,super(t,e)}},jm=class extends Wl{static{a(this,"We")}constructor(t){super(t,"BrotliCompress")}},Mm=class extends Wl{static{a(this,"Ge")}constructor(t){super(t,"BrotliDecompress")}},Hl=class extends ia{static{a(this,"Ze")}constructor(t,e){t=t||{},t.flush=t.flush||We.ZSTD_e_continue,t.finishFlush=t.finishFlush||We.ZSTD_e_end,t.fullFlushFlag=We.ZSTD_e_flush,super(t,e)}},$m=class extends Hl{static{a(this,"Ye")}constructor(t){super(t,"ZstdCompress")}},qm=class extends Hl{static{a(this,"Ke")}constructor(t){super(t,"ZstdDecompress")}},Fm=a((t,e)=>{if(Number.isSafeInteger(t))t<0?Wm(t,e):zm(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},"Us"),zm=a((t,e)=>{e[0]=128;for(var r=e.length;r>1;r--)e[r-1]=t&255,t=Math.floor(t/256)},"hn"),Wm=a((t,e)=>{e[0]=255;var r=!1;t=t*-1;for(var n=e.length;n>1;n--){var i=t&255;t=Math.floor(t/256),r?e[n-1]=Gl(i):i===0?e[n-1]=0:(r=!0,e[n-1]=Vl(i))}},"an"),Hm=a(t=>{let e=t[0],r=e===128?Vm(t.subarray(1,t.length)):e===255?Gm(t):null;if(r===null)throw Error("invalid base256 encoding");if(!Number.isSafeInteger(r))throw Error("parsed number outside of javascript safe integer range");return r},"Hs"),Gm=a(t=>{for(var e=t.length,r=0,n=!1,i=e-1;i>-1;i--){var s=Number(t[i]),o;n?o=Gl(s):s===0?o=s:(n=!0,o=Vl(s)),o!==0&&(r-=o*Math.pow(256,e-i-1))}return r},"ln"),Vm=a(t=>{for(var e=t.length,r=0,n=e-1;n>-1;n--){var i=Number(t[n]);i!==0&&(r+=i*Math.pow(256,e-n-1))}return r},"cn"),Gl=a(t=>(255^t)&255,"Ws"),Vl=a(t=>(255^t)+1&255,"Gs"),Jm={};am(Jm,{code:a(()=>sa,"code"),isCode:a(()=>Pi,"isCode"),isName:a(()=>Ym,"isName"),name:a(()=>Yi,"name"),normalFsTypes:a(()=>Jl,"normalFsTypes")});Pi=a(t=>Yi.has(t),"ne"),Ym=a(t=>sa.has(t),"dn"),Jl=new Set(["0","","1","2","3","4","5","6","7","D"]),Yi=new Map([["0","File"],["","OldFile"],["1","Link"],["2","SymbolicLink"],["3","CharacterDevice"],["4","BlockDevice"],["5","Directory"],["6","FIFO"],["7","ContiguousFile"],["g","GlobalExtendedHeader"],["x","ExtendedHeader"],["A","SolarisACL"],["D","GNUDumpDir"],["I","Inode"],["K","NextFileHasLongLinkpath"],["L","NextFileHasLongPath"],["M","ContinuationFile"],["N","OldGnuLongPath"],["S","SparseFile"],["V","TapeVolumeHeader"],["X","OldExtendedHeader"]]),sa=new Map(Array.from(Yi).map(t=>[t[1],t[0]])),Km=a(t=>t===void 0||t<0?void 0:t,"un"),ur=class{static{a(this,"F")}cksumValid=!1;needPax=!1;nullBlock=!1;block;path;mode;uid;gid;size;cksum;#e="Unsupported";linkpath;uname;gname;devmaj=0;devmin=0;atime;ctime;mtime;charset;comment;constructor(t,e=0,r,n){Buffer.isBuffer(t)?this.decode(t,e||0,r,n):t&&this.#r(t)}decode(t,e,r,n){if(e||(e=0),!t||!(t.length>=e+512))throw new Error("need 512 bytes for header");let i=rr(t,e+156,1),s=Jl.has(i),o=s?r:void 0,c=s?n:void 0;if(this.path=o?.path??rr(t,e,100),this.mode=o?.mode??c?.mode??jt(t,e+100,8),this.uid=o?.uid??c?.uid??jt(t,e+108,8),this.gid=o?.gid??c?.gid??jt(t,e+116,8),this.size=Km(o?.size??c?.size??jt(t,e+124,12)),this.mtime=o?.mtime??c?.mtime??wo(t,e+136,12),this.cksum=jt(t,e+148,12),c&&this.#r(c,!0),o&&this.#r(o),Pi(i)&&(this.#e=i||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=rr(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=o?.uname??c?.uname??rr(t,e+265,32),this.gname=o?.gname??c?.gname??rr(t,e+297,32),this.devmaj=o?.devmaj??c?.devmaj??jt(t,e+329,8)??0,this.devmin=o?.devmin??c?.devmin??jt(t,e+337,8)??0,t[e+475]!==0){let d=rr(t,e+345,155);this.path=d+"/"+this.path}else{let d=rr(t,e+345,130);d&&(this.path=d+"/"+this.path),this.atime=r?.atime??n?.atime??wo(t,e+476,12),this.ctime=r?.ctime??n?.ctime??wo(t,e+488,12)}let l=256;for(let d=e;d<e+148;d++)l+=t[d];for(let d=e+156;d<e+512;d++)l+=t[d];this.cksumValid=l===this.cksum,this.cksum===void 0&&l===256&&(this.nullBlock=!0)}#r(t,e=!1){Object.assign(this,Object.fromEntries(Object.entries(t).filter(([r,n])=>!(n==null||r==="size"&&Number(n)<0||r==="path"&&e||r==="linkpath"&&e||r==="global"))))}encode(t,e=0){if(t||(t=this.block=Buffer.alloc(512)),this.#e==="Unsupported"&&(this.#e="0"),!(t.length>=e+512))throw new Error("need 512 bytes for header");let r=this.ctime||this.atime?130:155,n=Xm(this.path||"",r),i=n[0],s=n[1];this.needPax=!!n[2],this.needPax=nr(t,e,100,i)||this.needPax,this.needPax=Mt(t,e+100,8,this.mode)||this.needPax,this.needPax=Mt(t,e+108,8,this.uid)||this.needPax,this.needPax=Mt(t,e+116,8,this.gid)||this.needPax,this.needPax=Mt(t,e+124,12,this.size)||this.needPax,this.needPax=bo(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#e.codePointAt(0)),this.needPax=nr(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=nr(t,e+265,32,this.uname)||this.needPax,this.needPax=nr(t,e+297,32,this.gname)||this.needPax,this.needPax=Mt(t,e+329,8,this.devmaj)||this.needPax,this.needPax=Mt(t,e+337,8,this.devmin)||this.needPax,this.needPax=nr(t,e+345,r,s)||this.needPax,t[e+475]!==0?this.needPax=nr(t,e+345,155,s)||this.needPax:(this.needPax=nr(t,e+345,130,s)||this.needPax,this.needPax=bo(t,e+476,12,this.atime)||this.needPax,this.needPax=bo(t,e+488,12,this.ctime)||this.needPax);let o=256;for(let c=e;c<e+148;c++)o+=t[c];for(let c=e+156;c<e+512;c++)o+=t[c];return this.cksum=o,Mt(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:Yi.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(sa.get(t));if(Pi(e)||e==="Unsupported")this.#e=e;else if(Pi(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},Xm=a((t,e)=>{let r=t,n="",i,s=Lr.parse(t).root||".";if(Buffer.byteLength(r)<100)i=[r,n,!1];else{n=Lr.dirname(r),r=Lr.basename(r);do Buffer.byteLength(r)<=100&&Buffer.byteLength(n)<=e?i=[r,n,!1]:Buffer.byteLength(r)>100&&Buffer.byteLength(n)<=e?i=[r.slice(0,99),n,!0]:(r=Lr.join(Lr.basename(n),r),n=Lr.dirname(n));while(n!==s&&i===void 0);i||(i=[t.slice(0,99),"",!0])}return i},"mn"),rr=a((t,e,r)=>t.subarray(e,e+r).toString("utf8").replace(/\0.*/,""),"xt"),wo=a((t,e,r)=>Zm(jt(t,e,r)),"Wi"),Zm=a(t=>t===void 0?void 0:new Date(t*1e3),"pn"),jt=a((t,e,r)=>Number(t[e])&128?Hm(t.subarray(e,e+r)):e_(t,e,r),"lt"),Qm=a(t=>isNaN(t)?void 0:t,"En"),e_=a((t,e,r)=>Qm(parseInt(t.subarray(e,e+r).toString("utf8").replace(/\0.*$/,"").trim(),8)),"wn"),t_={12:8589934591,8:2097151},Mt=a((t,e,r,n)=>n===void 0?!1:n>t_[r]||n<0?(Fm(n,t.subarray(e,e+r)),!0):(r_(t,e,r,n),!1),"ct"),r_=a((t,e,r,n)=>t.write(n_(n,r),e,r,"ascii"),"yn"),n_=a((t,e)=>i_(Math.floor(t).toString(8),e),"Rn"),i_=a((t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0","gn"),bo=a((t,e,r,n)=>n===void 0?!1:Mt(t,e,r,n.getTime()/1e3),"Gi"),s_=new Array(156).join("\0"),nr=a((t,e,r,n)=>n===void 0?!1:(t.write(n+s_,e,r,"utf8"),n.length!==Buffer.byteLength(n)||n.length>r),"Lt"),zi=class Yl{static{a(this,"s")}atime;mtime;ctime;charset;comment;gid;uid;gname;uname;linkpath;dev;ino;nlink;path;size;mode;global;constructor(e,r=!1){this.atime=e.atime,this.charset=e.charset,this.comment=e.comment,this.ctime=e.ctime,this.dev=e.dev,this.gid=e.gid,this.global=r,this.gname=e.gname,this.ino=e.ino,this.linkpath=e.linkpath,this.mtime=e.mtime,this.nlink=e.nlink,this.path=e.path,this.size=e.size,this.uid=e.uid,this.uname=e.uname}encode(){let e=this.encodeBody();if(e==="")return Buffer.allocUnsafe(0);let r=Buffer.byteLength(e),n=512*Math.ceil(1+r/512),i=Buffer.allocUnsafe(n);for(let s=0;s<512;s++)i[s]=0;new ur({path:("PaxHeader/"+o_(this.path??"")).slice(0,99),mode:this.mode||420,uid:this.uid,gid:this.gid,size:r,mtime:this.mtime,type:this.global?"GlobalExtendedHeader":"ExtendedHeader",linkpath:"",uname:this.uname||"",gname:this.gname||"",devmaj:0,devmin:0,atime:this.atime,ctime:this.ctime}).encode(i),i.write(e,512,r,"utf8");for(let s=r+512;s<i.length;s++)i[s]=0;return i}encodeBody(){return this.encodeField("path")+this.encodeField("ctime")+this.encodeField("atime")+this.encodeField("dev")+this.encodeField("ino")+this.encodeField("nlink")+this.encodeField("charset")+this.encodeField("comment")+this.encodeField("gid")+this.encodeField("gname")+this.encodeField("linkpath")+this.encodeField("mtime")+this.encodeField("size")+this.encodeField("uid")+this.encodeField("uname")}encodeField(e){if(this[e]===void 0)return"";let r=this[e],n=r instanceof Date?r.getTime()/1e3:r,i=" "+(e==="dev"||e==="ino"||e==="nlink"?"SCHILY.":"")+e+"="+n+`
4
+ `,s=Buffer.byteLength(i),o=Math.floor(Math.log(s)/Math.log(10))+1;return s+o>=Math.pow(10,o)&&(o+=1),o+s+i}static parse(e,r,n=!1){return new Yl(a_(c_(e),r),n)}},a_=a((t,e)=>e?Object.assign({},e,t):t,"On"),c_=a(t=>t.replace(/\n$/,"").split(`
5
+ `).reduce(l_,Object.create(null)),"Tn"),l_=a((t,e)=>{let r=parseInt(e,10);if(r!==Buffer.byteLength(e)+1)return t;e=e.slice((r+" ").length);let n=e.split("="),i=n.shift();if(!i)return t;let s=i.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),o=n.join("=").replace(/\0.*/,"");switch(s){case"path":case"linkpath":case"type":case"charset":case"comment":case"gname":case"uname":t[s]=o;break;case"ctime":case"atime":case"mtime":t[s]=new Date(Number(o)*1e3);break;case"size":let c=+o;c>=0&&(t[s]=c);break;case"gid":case"uid":case"dev":case"ino":case"nlink":case"mode":t[s]=+o;break}return t},"xn"),d_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,O=d_!=="win32"?t=>String(t):t=>String(t).replaceAll(/\\/g,"/"),u_=class extends hr{static{a(this,"$e")}extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=!1;ignore=!1;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=!1;absolute;unsupported=!1;constructor(t,e,r){switch(super({}),this.pause(),this.extended=e,this.globalExtended=r,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=!0;break;default:this.ignore=!0}if(!t.path)throw new Error("no path provided for tar.ReadEntry");this.path=O(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?O(t.linkpath):void 0,this.uname=t.uname,this.gname=t.gname,e&&this.#e(e),r&&this.#e(r,!0)}write(t){let e=t.length;if(e>this.blockRemain)throw new Error("writing more to entry than is appropriate");let r=this.remain,n=this.blockRemain;return this.remain=Math.max(0,r-e),this.blockRemain=Math.max(0,n-e),this.ignore?!0:r>=e?super.write(t):super.write(t.subarray(0,r))}#e(t,e=!1){t.path&&(t.path=O(t.path)),t.linkpath&&(t.linkpath=O(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([r,n])=>!(n==null||r==="path"&&e))))}},Ki=a((t,e,r,n={})=>{t.file&&(n.file=t.file),t.cwd&&(n.cwd=t.cwd),n.code=r instanceof Error&&r.code||e,n.tarCode=e,!t.strict&&n.recoverable!==!1?(r instanceof Error&&(n=Object.assign(r,n),r=r.message),t.emit("warn",e,r,n)):r instanceof Error?t.emit("error",Object.assign(r,n)):t.emit("error",Object.assign(new Error(`${e}: ${r}`),n))},"Dt"),h_=1024*1024,Bo=Buffer.from([31,139]),jo=Buffer.from([40,181,47,253]),p_=Math.max(Bo.length,jo.length),we=Symbol("state"),ir=Symbol("writeEntry"),lt=Symbol("readEntry"),vo=Symbol("nextEntry"),dl=Symbol("processEntry"),$e=Symbol("extendedHeader"),gn=Symbol("globalExtendedHeader"),Pt=Symbol("meta"),ul=Symbol("emitMeta"),j=Symbol("buffer"),dt=Symbol("queue"),Dt=Symbol("ended"),Eo=Symbol("emittedEnd"),sr=Symbol("emit"),q=Symbol("unzip"),Ti=Symbol("consumeChunk"),xi=Symbol("consumeChunkSub"),So=Symbol("consumeBody"),hl=Symbol("consumeMeta"),pl=Symbol("consumeHeader"),yn=Symbol("consuming"),To=Symbol("bufferConcat"),Ri=Symbol("maybeEnd"),Cr=Symbol("writing"),qe=Symbol("aborted"),ki=Symbol("onDone"),or=Symbol("sawValidEntry"),Oi=Symbol("sawNullBlock"),Ii=Symbol("sawEOF"),fl=Symbol("closeStream"),f_=1e3,wn=Symbol("compressedBytesRead"),xo=Symbol("decompressedBytesRead"),ml=Symbol("checkDecompressionRatio"),m_=a(()=>!0,"Cn"),Dn=class extends Nm{static{a(this,"rt")}file;strict;maxMetaEntrySize;filter;brotli;zstd;maxDecompressionRatio;writable=!0;readable=!1;[dt]=[];[j];[lt];[ir];[we]="begin";[Pt]="";[$e];[gn];[Dt]=!1;[q];[qe]=!1;[or];[Oi]=!1;[Ii]=!1;[Cr]=!1;[yn]=!1;[Eo]=!1;[wn]=0;[xo]=0;constructor(t={}){super(),this.file=t.file||"",this.on(ki,()=>{(this[we]==="begin"||this[or]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(ki,t.ondone):this.on(ki,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxDecompressionRatio=typeof t.maxDecompressionRatio=="number"?t.maxDecompressionRatio:f_,this.maxMetaEntrySize=t.maxMetaEntrySize||h_,this.filter=typeof t.filter=="function"?t.filter:m_;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:!1;let r=t.file&&(t.file.endsWith(".tar.zst")||t.file.endsWith(".tzst"));this.zstd=!(t.gzip||t.brotli)&&t.zstd!==void 0?t.zstd:r?!0:void 0,this.on("end",()=>this[fl]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,r={}){Ki(this,t,e,r)}[pl](t,e){this[or]===void 0&&(this[or]=!1);let r;try{r=new ur(t,e,this[$e],this[gn])}catch(n){return this.warn("TAR_ENTRY_INVALID",n)}if(r.nullBlock)this[Oi]?(this[Ii]=!0,this[we]==="begin"&&(this[we]="header"),this[sr]("eof")):(this[Oi]=!0,this[sr]("nullBlock"));else if(this[Oi]=!1,!r.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:r});else if(!r.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:r});else{let n=r.type;if(/^(Symbolic)?Link$/.test(n)&&!r.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:r});else if(!/^(Symbolic)?Link$/.test(n)&&!/^(Global)?ExtendedHeader$/.test(n)&&r.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:r});else{let i=this[ir]=new u_(r,this[$e],this[gn]);if(!this[or])if(i.remain){let s=a(()=>{i.invalid||(this[or]=!0)},"o");i.on("end",s)}else this[or]=!0;i.meta?i.size>this.maxMetaEntrySize?(i.ignore=!0,this[sr]("ignoredEntry",i),this[we]="ignore",i.resume()):i.size>0&&(this[Pt]="",i.on("data",s=>this[Pt]+=s),this[we]="meta"):(this[$e]=void 0,i.ignore=i.ignore||!this.filter(i.path,i),i.ignore?(this[sr]("ignoredEntry",i),this[we]=i.remain?"ignore":"header",i.resume()):(i.remain?this[we]="body":(this[we]="header",i.end()),this[lt]?this[dt].push(i):(this[dt].push(i),this[vo]())))}}}[fl](){queueMicrotask(()=>this.emit("close"))}[dl](t){let e=!0;if(!t)this[lt]=void 0,e=!1;else if(Array.isArray(t)){let[r,...n]=t;this.emit(r,...n)}else this[lt]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[vo]()),e=!1);return e}[vo](){do;while(this[dl](this[dt].shift()));if(this[dt].length===0){let t=this[lt];!t||t.flowing||t.size===t.remain?this[Cr]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[So](t,e){let r=this[ir];if(!r)throw new Error("attempt to consume body without entry??");let n=r.blockRemain??0,i=n>=t.length&&e===0?t:t.subarray(e,e+n);return r.write(i),r.blockRemain||(this[we]="header",this[ir]=void 0,r.end()),i.length}[hl](t,e){let r=this[ir],n=this[So](t,e);return!this[ir]&&r&&this[ul](r),n}[sr](t,e,r){this[dt].length===0&&!this[lt]?this.emit(t,e,r):this[dt].push([t,e,r])}[ul](t){switch(this[sr]("meta",this[Pt]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[$e]=zi.parse(this[Pt],this[$e],!1);break;case"GlobalExtendedHeader":this[gn]=zi.parse(this[Pt],this[gn],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[$e]??Object.create(null);this[$e]=e,e.path=this[Pt].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[$e]||Object.create(null);this[$e]=e,e.linkpath=this[Pt].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){if(!this[qe]){if(this[q]){let e=this[q];e.write=()=>!0,e.end=()=>e,e.emit=()=>!1,e.destroy?.()}this[qe]=!0,this.emit("abort",t),this.warn("TAR_ABORT",t,{recoverable:!1})}}[ml](t){this[xo]+=t.length;let e=this[xo]/this[wn];return e>this.maxDecompressionRatio?(this.abort(new Error(`max decompression ratio exceeded: ${e.toFixed(2)} > ${this.maxDecompressionRatio}`)),!1):!0}write(t,e,r){if(typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this[qe])return r?.(),!1;if((this[q]===void 0||this.brotli===void 0&&this[q]===!1)&&t){if(this[j]&&(t=Buffer.concat([this[j],t]),this[j]=void 0),t.length<p_)return this[j]=t,r?.(),!0;for(let o=0;this[q]===void 0&&o<Bo.length;o++)t[o]!==Bo[o]&&(this[q]=!1);let i=!1;if(this[q]===!1&&this.zstd!==!1){i=!0;for(let o=0;o<jo.length;o++)if(t[o]!==jo[o]){i=!1;break}}let s=this.brotli===void 0&&!i;if(this[q]===!1&&s)if(t.length<512)if(this[Dt])this.brotli=!0;else return this[j]=t,r?.(),!0;else try{new ur(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[q]===void 0||this[q]===!1&&(this.brotli||i)){let o=this[Dt];this[Dt]=!1,this[q]=this[q]===void 0?new Bm({}):i?new qm({}):new Mm({}),this[q].on("data",l=>{this[ml](l)&&this[Ti](l)}),this[q].on("error",l=>{this[qe]||this.abort(l)}),this[q].on("end",()=>{this[Dt]=!0,this[Ti]()}),this[Cr]=!0,this[wn]+=t.length;let c=!!this[q][o?"end":"write"](t);return this[Cr]=!1,r?.(),c}}this[Cr]=!0,this[q]?(this[wn]+=t.length,this[q].write(t)):this[Ti](t),this[Cr]=!1;let n=this[dt].length>0?!1:this[lt]?this[lt].flowing:!0;return!n&&this[dt].length===0&&this[lt]?.once("drain",()=>this.emit("drain")),r?.(),n}[To](t){t&&!this[qe]&&(this[j]=this[j]?Buffer.concat([this[j],t]):t)}[Ri](){if(this[Dt]&&!this[Eo]&&!this[qe]&&!this[yn]){this[Eo]=!0;let t=this[ir];if(t?.blockRemain){let e=this[j]?this[j].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[j]&&t.write(this[j]),t.end()}this[sr](ki)}}[Ti](t){if(this[yn]&&t)this[To](t);else if(!t&&!this[j])this[Ri]();else if(t){if(this[yn]=!0,this[j]){this[To](t);let e=this[j];this[j]=void 0,this[xi](e)}else this[xi](t);for(;this[j]&&this[j]?.length>=512&&!this[qe]&&!this[Ii];){let e=this[j];this[j]=void 0,this[xi](e)}this[yn]=!1}(!this[j]||this[Dt])&&this[Ri]()}[xi](t){let e=0,r=t.length;for(;e+512<=r&&!this[qe]&&!this[Ii];)switch(this[we]){case"begin":case"header":this[pl](t,e),e+=512;break;case"ignore":case"body":e+=this[So](t,e);break;case"meta":e+=this[hl](t,e);break;default:throw new Error("invalid state: "+this[we])}e<r&&(this[j]=this[j]?Buffer.concat([t.subarray(e),this[j]]):t.subarray(e))}end(t,e,r){return typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e)),r&&this.once("finish",r),this[qe]||(this[q]?(t&&(this[wn]+=t.length,this[q].write(t)),this[q].end()):(this[Dt]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[Ri]())),this}},On=a(t=>{let e=t.length-1,r=-1;for(;e>-1&&t.charAt(e)==="/";)r=e,e--;return r===-1?t:t.slice(0,r)},"mt"),__=a(t=>{let e=t.onReadEntry;t.onReadEntry=e?r=>{e(r),r.resume()}:r=>r.resume()},"vn"),Kl=a((t,e)=>{let r=new Map(e.map(o=>[On(o),!0])),n=t.filter,i=100,s=a((o,c="",l=0)=>{if(l>=i)return r.set(o,!1),!1;let d=c||Sm(o).root||".",u;if(o===d)u=!1;else{let h=r.get(o);u=h!==void 0?h:s(Em(o),d,l+1)}return r.set(o,u),u},"n");t.filter=n?(o,c)=>n(o,c)&&s(On(o)):o=>s(On(o))},"Qi"),g_=a(t=>{let e=new Dn(t),r=t.file,n;try{n=Mr.openSync(r,"r");let i=Mr.fstatSync(n),s=t.maxReadSize||16*1024*1024;if(i.size<s){let o=Buffer.allocUnsafe(i.size),c=Mr.readSync(n,o,0,i.size,0);e.end(c===o.byteLength?o:o.subarray(0,c))}else{let o=0,c=Buffer.allocUnsafe(s);for(;o<i.size;){let l=Mr.readSync(n,c,0,s,o);if(l===0)break;o+=l,e.write(c.subarray(0,l))}e.end()}}finally{if(typeof n=="number")try{Mr.closeSync(n)}catch{}}},"Mn"),y_=a((t,e)=>{let r=new Dn(t),n=t.maxReadSize||16*1024*1024,i=t.file;return new Promise((s,o)=>{r.on("error",o),r.on("end",s),Mr.stat(i,(c,l)=>{if(c)o(c);else{let d=new ra(i,{readSize:n,size:l.size});d.on("error",o),d.pipe(r)}})})},"Bn"),zr=Un(g_,y_,t=>new Dn(t),t=>new Dn(t),(t,e)=>{e?.length&&Kl(t,e),t.noResume||__(t)}),Xl=a((t,e,r)=>(t&=4095,r&&(t=(t|384)&-19),e&&(t&256&&(t|=64),t&32&&(t|=8),t&4&&(t|=1)),t),"Ji"),{isAbsolute:b_,parse:gl}=w_,oa=a(t=>{let e="",r=gl(t);for(;b_(t)||r.root;){let n=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":r.root;t=t.slice(n.length),e+=n,r=gl(t)}return[e,t]},"ce"),Xi=["|","<",">","?",":"],aa=Xi.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),v_=new Map(Xi.map((t,e)=>[t,aa[e]])),E_=new Map(aa.map((t,e)=>[t,Xi[e]])),yl=a(t=>Xi.reduce((e,r)=>e.split(r).join(v_.get(r)),t),"ts"),S_=a(t=>aa.reduce((e,r)=>e.split(r).join(E_.get(r)),t),"Qs"),Zl=a((t,e)=>e?(t=O(t).replace(/^\.(\/|$)/,""),On(e)+"/"+t):O(t),"rr"),T_=16*1024*1024,wl=Symbol("process"),bl=Symbol("file"),vl=Symbol("directory"),Mo=Symbol("symlink"),El=Symbol("hardlink"),bn=Symbol("header"),Di=Symbol("read"),$o=Symbol("lstat"),Ui=Symbol("onlstat"),qo=Symbol("onread"),Fo=Symbol("onreadlink"),zo=Symbol("openfile"),Wo=Symbol("onopenfile"),$t=Symbol("close"),Hi=Symbol("mode"),Ho=Symbol("awaitDrain"),Ro=Symbol("ondrain"),ze=Symbol("prefix"),Ql=class extends hr{static{a(this,"de")}path;portable;myuid=process.getuid&&process.getuid()||0;myuser=process.env.USER||"";maxReadSize;linkCache;statCache;preservePaths;cwd;strict;mtime;noPax;noMtime;prefix;fd;blockLen=0;blockRemain=0;buf;pos=0;remain=0;length=0;offset=0;win32;absolute;header;type;linkpath;stat;onWriteEntry;#e=!1;constructor(t,e={}){let r=na(e);super(),this.path=O(t),this.portable=!!r.portable,this.maxReadSize=r.maxReadSize||T_,this.linkCache=r.linkCache||new Map,this.statCache=r.statCache||new Map,this.preservePaths=!!r.preservePaths,this.cwd=O(r.cwd||process.cwd()),this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.mtime=r.mtime,this.prefix=r.prefix?O(r.prefix):void 0,this.onWriteEntry=r.onWriteEntry,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let n=!1;if(!this.preservePaths){let[s,o]=oa(this.path);s&&typeof o=="string"&&(this.path=o,n=s)}this.win32=!!r.win32||process.platform==="win32",this.win32&&(this.path=S_(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=O(r.absolute||_l.resolve(this.cwd,t)),this.path===""&&(this.path="./"),n&&this.warn("TAR_ENTRY_INFO",`stripping ${n} from absolute path`,{entry:this,path:n+this.path});let i=this.statCache.get(this.absolute);i?this[Ui](i):this[$o]()}warn(t,e,r={}){return Ki(this,t,e,r)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[$o](){Fe.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Ui](e)})}[Ui](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=k_(t),this.emit("stat",t),this[wl]()}[wl](){switch(this.type){case"File":return this[bl]();case"Directory":return this[vl]();case"SymbolicLink":return this[Mo]();default:return this.end()}}[Hi](t){return Xl(t,this.type==="Directory",this.portable)}[ze](t){return Zl(t,this.prefix)}[bn](){if(!this.stat)throw new Error("cannot write header before stat");this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.onWriteEntry?.(this),this.header=new ur({path:this[ze](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[ze](this.linkpath):this.linkpath,mode:this[Hi](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 zi({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[ze](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[ze](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)}[vl](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[bn](),this.end()}[Mo](){Fe.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Fo](e)})}[Fo](t){this.linkpath=O(t),this[bn](),this.end()}[El](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=O(_l.relative(this.cwd,t)),this.stat.size=0,this[bn](),this.end()}[bl](){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[El](e);this.linkCache.set(t,this.absolute)}if(this[bn](),this.stat.size===0)return this.end();this[zo]()}[zo](){Fe.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[Wo](e)})}[Wo](t){if(this.fd=t,this.#e)return this[$t]();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[Di]()}[Di](){let{fd:t,buf:e,offset:r,length:n,pos:i}=this;if(t===void 0||e===void 0)throw new Error("cannot read file without first opening");Fe.read(t,e,r,n,i,(s,o)=>{if(s)return this[$t](()=>this.emit("error",s));this[qo](o)})}[$t](t=()=>{}){this.fd!==void 0&&Fe.close(this.fd,t)}[qo](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[$t](()=>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[$t](()=>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[Ro]():this[Ho](()=>this[Ro]())}[Ho](t){this.once("drain",t)}write(t,e,r){if(typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this.blockRemain<t.length){let n=Object.assign(new Error("writing more data than expected"),{path:this.absolute});return this.emit("error",n)}return this.remain-=t.length,this.blockRemain-=t.length,this.pos+=t.length,this.offset+=t.length,super.write(t,null,r)}[Ro](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[$t](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[Di]()}},x_=class extends Ql{static{a(this,"ni")}sync=!0;[$o](){this[Ui](Fe.lstatSync(this.absolute))}[Mo](){this[Fo](Fe.readlinkSync(this.absolute))}[zo](){this[Wo](Fe.openSync(this.absolute,"r"))}[Di](){let t=!0;try{let{fd:e,buf:r,offset:n,length:i,pos:s}=this;if(e===void 0||r===void 0)throw new Error("fd and buf must be set in READ method");let o=Fe.readSync(e,r,n,i,s);this[qo](o),t=!1}finally{if(t)try{this[$t](()=>{})}catch{}}}[Ho](t){t()}[$t](t=()=>{}){this.fd!==void 0&&Fe.closeSync(this.fd),t()}},R_=class extends hr{static{a(this,"oi")}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,r={}){return Ki(this,t,e,r)}constructor(t,e={}){let r=na(e);super(),this.preservePaths=!!r.preservePaths,this.portable=!!r.portable,this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.onWriteEntry=r.onWriteEntry,this.readEntry=t;let{type:n}=t;if(n==="Unsupported")throw new Error("writing entry that should be ignored");this.type=n,this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.prefix=r.prefix,this.path=O(t.path),this.mode=t.mode!==void 0?this[Hi](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:r.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?O(t.linkpath):void 0,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let i=!1;if(!this.preservePaths){let[o,c]=oa(this.path);o&&typeof c=="string"&&(this.path=c,i=o)}this.remain=t.size,this.blockRemain=t.startBlockSize,this.onWriteEntry?.(this),this.header=new ur({path:this[ze](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[ze](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}),i&&this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute path`,{entry:this,path:i+this.path}),this.header.encode()&&!this.noPax&&super.write(new zi({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[ze](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[ze](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 s=this.header?.block;if(!s)throw new Error("failed to encode header");super.write(s),t.pipe(this)}[ze](t){return Zl(t,this.prefix)}[Hi](t){return Xl(t,this.type==="Directory",this.portable)}write(t,e,r){typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8"));let n=t.length;if(n>this.blockRemain)throw new Error("writing more to entry than is appropriate");return this.blockRemain-=n,super.write(t,r)}end(t,e,r){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e??"utf8")),r&&this.once("finish",r),t?super.end(t,r):super.end(r),this}},k_=a(t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported","Gn"),O_=class $r{static{a(this,"s")}tail;head;length=0;static create(e=[]){return new $r(e)}constructor(e=[]){for(let r of e)this.push(r)}*[Symbol.iterator](){for(let e=this.head;e;e=e.next)yield e.value}removeNode(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");let r=e.next,n=e.prev;return r&&(r.prev=n),n&&(n.next=r),e===this.head&&(this.head=r),e===this.tail&&(this.tail=n),this.length--,e.next=void 0,e.prev=void 0,e.list=void 0,r}unshiftNode(e){if(e===this.head)return;e.list&&e.list.removeNode(e);let r=this.head;e.list=this,e.next=r,r&&(r.prev=e),this.head=e,this.tail||(this.tail=e),this.length++}pushNode(e){if(e===this.tail)return;e.list&&e.list.removeNode(e);let r=this.tail;e.list=this,e.prev=r,r&&(r.next=e),this.tail=e,this.head||(this.head=e),this.length++}push(...e){for(let r=0,n=e.length;r<n;r++)A_(this,e[r]);return this.length}unshift(...e){for(var r=0,n=e.length;r<n;r++)N_(this,e[r]);return this.length}pop(){if(!this.tail)return;let e=this.tail.value,r=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,r.list=void 0,this.length--,e}shift(){if(!this.head)return;let e=this.head.value,r=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,r.list=void 0,this.length--,e}forEach(e,r){r=r||this;for(let n=this.head,i=0;n;i++)e.call(r,n.value,i,this),n=n.next}forEachReverse(e,r){r=r||this;for(let n=this.tail,i=this.length-1;n;i--)e.call(r,n.value,i,this),n=n.prev}get(e){let r=0,n=this.head;for(;n&&r<e;r++)n=n.next;if(r===e&&n)return n.value}getReverse(e){let r=0,n=this.tail;for(;n&&r<e;r++)n=n.prev;if(r===e&&n)return n.value}map(e,r){r=r||this;let n=new $r;for(let i=this.head;i;)n.push(e.call(r,i.value,this)),i=i.next;return n}mapReverse(e,r){r=r||this;var n=new $r;for(let i=this.tail;i;)n.push(e.call(r,i.value,this)),i=i.prev;return n}reduce(e,r){let n,i=this.head;if(arguments.length>1)n=r;else if(this.head)i=this.head.next,n=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var s=0;i;s++)n=e(n,i.value,s),i=i.next;return n}reduceReverse(e,r){let n,i=this.tail;if(arguments.length>1)n=r;else if(this.tail)i=this.tail.prev,n=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(let s=this.length-1;i;s--)n=e(n,i.value,s),i=i.prev;return n}toArray(){let e=new Array(this.length);for(let r=0,n=this.head;n;r++)e[r]=n.value,n=n.next;return e}toArrayReverse(){let e=new Array(this.length);for(let r=0,n=this.tail;n;r++)e[r]=n.value,n=n.prev;return e}slice(e=0,r=this.length){r<0&&(r+=this.length),e<0&&(e+=this.length);let n=new $r;if(r<e||r<0)return n;e<0&&(e=0),r>this.length&&(r=this.length);let i=this.head,s=0;for(s=0;i&&s<e;s++)i=i.next;for(;i&&s<r;s++,i=i.next)n.push(i.value);return n}sliceReverse(e=0,r=this.length){r<0&&(r+=this.length),e<0&&(e+=this.length);let n=new $r;if(r<e||r<0)return n;e<0&&(e=0),r>this.length&&(r=this.length);let i=this.length,s=this.tail;for(;s&&i>r;i--)s=s.prev;for(;s&&i>e;i--,s=s.prev)n.push(s.value);return n}splice(e,r=0,...n){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);let i=this.head;for(let o=0;i&&o<e;o++)i=i.next;let s=[];for(let o=0;i&&o<r;o++)s.push(i.value),i=this.removeNode(i);i?i!==this.tail&&(i=i.prev):i=this.tail;for(let o of n)i=I_(this,i,o);return s}reverse(){let e=this.head,r=this.tail;for(let n=e;n;n=n.prev){let i=n.prev;n.prev=n.next,n.next=i}return this.head=r,this.tail=e,this}};a(I_,"Zn");a(A_,"Yn");a(N_,"Kn");ca=class{static{a(this,"ue")}list;next;prev;value;constructor(t,e,r,n){this.list=n,this.value=t,e?(e.next=this,this.prev=e):this.prev=void 0,r?(r.prev=this,this.next=r):this.next=void 0}},Tl=class{static{a(this,"pi")}path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},xl=Buffer.alloc(1024),Bi=Symbol("onStat"),vn=Symbol("ended"),Re=Symbol("queue"),En=Symbol("pendingLinks"),Ut=Symbol("current"),ar=Symbol("process"),Sn=Symbol("processing"),Ai=Symbol("processJob"),ke=Symbol("jobs"),ko=Symbol("jobDone"),ji=Symbol("addFSEntry"),Rl=Symbol("addTarEntry"),Go=Symbol("stat"),Vo=Symbol("readdir"),Mi=Symbol("onreaddir"),$i=Symbol("pipe"),kl=Symbol("entry"),Oo=Symbol("entryOpt"),qi=Symbol("writeEntryClass"),ed=Symbol("write"),Io=Symbol("ondrain"),Zi=class extends hr{static{a(this,"wt")}sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[qi];onWriteEntry;[Re];[En]=new Map;[ke]=0;[Sn]=!1;[vn]=!1;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=O(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[qi]=Ql,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=!0),this.zip=new Um(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new jm(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new $m(t.zstd)),!this.zip)throw new Error("impossible");let e=this.zip;e.on("data",r=>super.write(r)),e.on("end",()=>super.end()),e.on("drain",()=>this[Io]()),this.on("resume",()=>e.resume())}else this.on("drain",this[Io]);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:()=>!0,this[Re]=new O_,this[ke]=0,this.jobs=Number(t.jobs)||4,this[Sn]=!1,this[vn]=!1}[ed](t){return super.write(t)}add(t){return this.write(t),this}end(t,e,r){return typeof t=="function"&&(r=t,t=void 0),typeof e=="function"&&(r=e,e=void 0),t&&this.add(t),this[vn]=!0,this[ar](),r&&r(),this}write(t){if(this[vn])throw new Error("write after end");return typeof t=="string"?this[ji](t):this[Rl](t),this.flowing}[Rl](t){let e=O(Sl.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let r=new Tl(t.path,e);r.entry=new R_(t,this[Oo](r)),r.entry.on("end",()=>this[ko](r)),this[ke]+=1,this[Re].push(r)}this[ar]()}[ji](t){let e=O(Sl.resolve(this.cwd,t));this[Re].push(new Tl(t,e)),this[ar]()}[Go](t){t.pending=!0,this[ke]+=1;let e=this.follow?"stat":"lstat";Wi[e](t.absolute,(r,n)=>{t.pending=!1,this[ke]-=1,r?this.emit("error",r):this[Bi](t,n)})}[Bi](t,e){if(this.statCache.set(t.absolute,e),t.stat=e,!this.filter(t.path,e))t.ignore=!0;else if(e.isFile()&&e.nlink>1&&!this.linkCache.get(`${e.dev}:${e.ino}`)&&!this.sync)if(t===this[Ut])this[Ai](t);else{let r=`${e.dev}:${e.ino}`,n=this[En].get(r);n?n.push(t):this[En].set(r,[t]),t.pendingLink=!0,t.pending=!0}this[ar]()}[Vo](t){t.pending=!0,this[ke]+=1,Wi.readdir(t.absolute,(e,r)=>{if(t.pending=!1,this[ke]-=1,e)return this.emit("error",e);this[Mi](t,r)})}[Mi](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[ar]()}[ar](){if(!this[Sn]){this[Sn]=!0;for(let t=this[Re].head;t&&this[ke]<this.jobs;t=t.next)if(this[Ai](t.value),t.value.ignore){let e=t.next;this[Re].removeNode(t),t.next=e}this[Sn]=!1,this[vn]&&this[Re].length===0&&this[ke]===0&&(this.zip?this.zip.end(xl):(super.write(xl),super.end()))}}get[Ut](){return this[Re]&&this[Re].head&&this[Re].head.value}[ko](t){this[Re].shift(),this[ke]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let r=`${e.dev}:${e.ino}`,n=this[En].get(r);if(n){this[En].delete(r);for(let i of n)i.pending=!1,this[Ai](i)}}this[ar]()}[Ai](t){if(t.pending&&t.pendingLink&&t===this[Ut]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[Ut]&&!t.piped&&this[$i](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[Bi](t,e):this[Go](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[Mi](t,e):this[Vo](t),!t.readdir)return}if(t.entry=this[kl](t),!t.entry){t.ignore=!0;return}t===this[Ut]&&!t.piped&&this[$i](t)}}}[Oo](t){return{onwarn:a((e,r,n)=>this.warn(e,r,n),"onwarn"),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}}[kl](t){this[ke]+=1;try{return new this[qi](t.path,this[Oo](t)).on("end",()=>this[ko](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[Io](){this[Ut]&&this[Ut].entry&&this[Ut].entry.resume()}[$i](t){t.piped=!0,t.readdir&&t.readdir.forEach(n=>{let i=t.path,s=i==="./"?"":i.replace(/\/*$/,"/");this[ji](s+n)});let e=t.entry,r=this.zip;if(!e)throw new Error("cannot pipe without source");r?e.on("data",n=>{r.write(n)||e.pause()}):e.on("data",n=>{super.write(n)||e.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}warn(t,e,r={}){Ki(this,t,e,r)}},la=class extends Zi{static{a(this,"kt")}sync=!0;constructor(t){super(t),this[qi]=x_}pause(){}resume(){}[Go](t){let e=this.follow?"statSync":"lstatSync";this[Bi](t,Wi[e](t.absolute))}[Vo](t){this[Mi](t,Wi.readdirSync(t.absolute))}[$i](t){let e=t.entry,r=this.zip;if(t.readdir&&t.readdir.forEach(n=>{let i=t.path,s=i==="./"?"":i.replace(/\/*$/,"/");this[ji](s+n)}),!e)throw new Error("Cannot pipe without source");r?e.on("data",n=>{r.write(n)}):e.on("data",n=>{super[ed](n)})}},L_=a((t,e)=>{let r=new la(t),n=new ql(t.file,{mode:t.mode||438});r.pipe(n),td(r,e)},"Vn"),C_=a((t,e)=>{let r=new Zi(t),n=new Ji(t.file,{mode:t.mode||438});r.pipe(n);let i=new Promise((s,o)=>{n.on("error",o),n.on("close",s),r.on("error",o)});return rd(r,e).catch(s=>r.emit("error",s)),i},"$n"),td=a((t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?zr({file:Fl.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:a(n=>t.add(n),"onReadEntry")}):t.add(r)}),t.end()},"fr"),rd=a(async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await zr({file:Fl.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:a(n=>{t.add(n)},"onReadEntry")}):t.add(r);t.end()},"dr"),P_=a((t,e)=>{let r=new la(t);return td(r,e),r},"Xn"),D_=a((t,e)=>{let r=new Zi(t);return rd(r,e).catch(n=>r.emit("error",n)),r},"qn"),nd=Un(L_,C_,P_,D_,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),B_=process.env.__FAKE_PLATFORM__||process.platform,ad=B_==="win32",{O_CREAT:cd,O_NOFOLLOW:Ol,O_TRUNC:ld,O_WRONLY:dd}=od.constants,ud=Number(process.env.__FAKE_FS_O_FILENAME__)||od.constants.UV_FS_O_FILEMAP||0,j_=ad&&!!ud,M_=512*1024,$_=ud|ld|cd|dd,Il=!ad&&typeof Ol=="number"?Ol|ld|cd|dd:null,hd=Il!==null?()=>Il:j_?t=>t<M_?$_:"w":()=>"w",Jo=a((t,e,r)=>{try{return Qi.lchownSync(t,e,r)}catch(n){if(n?.code!=="ENOENT")throw n}},"ps"),Gi=a((t,e,r,n)=>{Qi.lchown(t,e,r,i=>{n(i&&i?.code!=="ENOENT"?i:null)})},"Ei"),q_=a((t,e,r,n,i)=>{if(e.isDirectory())pd(In.resolve(t,e.name),r,n,s=>{if(s)return i(s);let o=In.resolve(t,e.name);Gi(o,r,n,i)});else{let s=In.resolve(t,e.name);Gi(s,r,n,i)}},"io"),pd=a((t,e,r,n)=>{Qi.readdir(t,{withFileTypes:!0},(i,s)=>{if(i){if(i.code==="ENOENT")return n();if(i.code!=="ENOTDIR"&&i.code!=="ENOTSUP")return n(i)}if(i||!s.length)return Gi(t,e,r,n);let o=s.length,c=null,l=a(d=>{if(!c){if(d)return n(c=d);if(--o===0)return Gi(t,e,r,n)}},"a");for(let d of s)q_(t,d,e,r,l)})},"Es"),F_=a((t,e,r,n)=>{e.isDirectory()&&fd(In.resolve(t,e.name),r,n),Jo(In.resolve(t,e.name),r,n)},"so"),fd=a((t,e,r)=>{let n;try{n=Qi.readdirSync(t,{withFileTypes:!0})}catch(i){let s=i;if(s?.code==="ENOENT")return;if(s?.code==="ENOTDIR"||s?.code==="ENOTSUP")return Jo(t,e,r);throw s}for(let i of n)F_(t,i,e,r);return Jo(t,e,r)},"ws"),md=class extends Error{static{a(this,"Se")}path;code;syscall="chdir";constructor(t,e){super(`${e}: Cannot cd into '${t}'`),this.path=t,this.code=e}get name(){return"CwdError"}},es=class extends Error{static{a(this,"St")}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"}},W_=a((t,e)=>{he.stat(t,(r,n)=>{(r||!n.isDirectory())&&(r=new md(t,r?.code||"ENOTDIR")),e(r)})},"no"),H_=a((t,e,r)=>{t=O(t);let n=e.umask??18,i=e.mode|448,s=(i&n)!==0,o=e.uid,c=e.gid,l=typeof o=="number"&&typeof c=="number"&&(o!==e.processUid||c!==e.processGid),d=e.preserve,u=e.unlink,h=O(e.cwd),f=a((m,_)=>{m?r(m):_&&l?pd(_,o,c,g=>f(g)):s?he.chmod(t,i,r):r()},"y");if(t===h)return W_(t,f);if(d)return z_.mkdir(t,{mode:i,recursive:!0}).then(m=>f(null,m??void 0),f);let p=O(Vi.relative(h,t)).split("/");Yo(h,p,i,u,h,void 0,f)},"gr"),Yo=a((t,e,r,n,i,s,o)=>{if(e.length===0)return o(null,s);let c=e.shift(),l=O(Vi.resolve(t+"/"+c));he.mkdir(l,r,_d(l,e,r,n,i,s,o))},"Ss"),_d=a((t,e,r,n,i,s,o)=>c=>{c?he.lstat(t,(l,d)=>{if(l)l.path=l.path&&O(l.path),o(l);else if(d.isDirectory())Yo(t,e,r,n,i,s,o);else if(n)he.unlink(t,u=>{if(u)return o(u);he.mkdir(t,r,_d(t,e,r,n,i,s,o))});else{if(d.isSymbolicLink())return o(new es(t,t+"/"+e.join("/")));o(c)}}):(s=s||t,Yo(t,e,r,n,i,s,o))},"br"),G_=a(t=>{let e=!1,r;try{e=he.statSync(t).isDirectory()}catch(n){r=n?.code}finally{if(!e)throw new md(t,r??"ENOTDIR")}},"oo"),V_=a((t,e)=>{t=O(t);let r=e.umask??18,n=e.mode|448,i=(n&r)!==0,s=e.uid,o=e.gid,c=typeof s=="number"&&typeof o=="number"&&(s!==e.processUid||o!==e.processGid),l=e.preserve,d=e.unlink,u=O(e.cwd),h=a(m=>{m&&c&&fd(m,s,o),i&&he.chmodSync(t,n)},"d");if(t===u)return G_(u),h();if(l)return h(he.mkdirSync(t,{mode:n,recursive:!0})??void 0);let f=O(Vi.relative(u,t)).split("/"),p;for(let m=f.shift(),_=u;m&&(_+="/"+m);m=f.shift()){_=O(Vi.resolve(_));try{he.mkdirSync(_,n),p=p||_}catch{let g=he.lstatSync(_);if(g.isDirectory())continue;if(d){he.unlinkSync(_),he.mkdirSync(_,n),p=p||_;continue}else if(g.isSymbolicLink())return new es(_,_+"/"+f.join("/"))}}return h(p)},"_r"),Ao=Object.create(null),Al=1e4,Pr=new Set,J_=a(t=>{Pr.has(t)?Pr.delete(t):Ao[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),Pr.add(t);let e=Ao[t],r=Pr.size-Al;if(r>Al/10){for(let n of Pr)if(Pr.delete(n),delete Ao[n],--r<=0)break}return e},"Tr"),Y_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,K_=Y_==="win32",X_=a(t=>t.split("/").slice(0,-1).reduce((e,r)=>{let n=e.at(-1);return n!==void 0&&(r=gd(n,r)),e.push(r||"/"),e},[]),"lo"),Z_=class{static{a(this,"yi")}#e=new Map;#r=new Map;#n=new Set;reserve(t,e){t=K_?["win32 parallelization disabled"]:t.map(n=>On(gd(J_(n))));let r=new Set(t.map(n=>X_(n)).reduce((n,i)=>n.concat(i)));this.#r.set(e,{dirs:r,paths:t});for(let n of t){let i=this.#e.get(n);i?i.push(e):this.#e.set(n,[e])}for(let n of r){let i=this.#e.get(n);if(!i)this.#e.set(n,[new Set([e])]);else{let s=i.at(-1);s instanceof Set?s.add(e):i.push(new Set([e]))}}return this.#i(e)}#s(t){let e=this.#r.get(t);if(!e)throw new Error("function does not have any path reservations");return{paths:e.paths.map(r=>this.#e.get(r)),dirs:[...e.dirs].map(r=>this.#e.get(r))}}check(t){let{paths:e,dirs:r}=this.#s(t);return e.every(n=>n&&n[0]===t)&&r.every(n=>n&&n[0]instanceof Set&&n[0].has(t))}#i(t){return this.#n.has(t)||!this.check(t)?!1:(this.#n.add(t),t(()=>this.#t(t)),!0)}#t(t){if(!this.#n.has(t))return!1;let e=this.#r.get(t);if(!e)throw new Error("invalid reservation");let{paths:r,dirs:n}=e,i=new Set;for(let s of r){let o=this.#e.get(s);if(!o||o?.[0]!==t)continue;let c=o[1];if(!c){this.#e.delete(s);continue}if(o.shift(),typeof c=="function")i.add(c);else for(let l of c)i.add(l)}for(let s of n){let o=this.#e.get(s),c=o?.[0];if(!(!o||!(c instanceof Set)))if(c.size===1&&o.length===1){this.#e.delete(s);continue}else if(c.size===1){o.shift();let l=o[0];typeof l=="function"&&i.add(l)}else c.delete(t)}return this.#n.delete(t),i.forEach(s=>this.#i(s)),!0}},Q_=a(()=>process.umask(),"Lr"),Nl=Symbol("onEntry"),Ko=Symbol("checkFs"),Ll=Symbol("checkFs2"),Xo=Symbol("isReusable"),be=Symbol("makeFs"),Zo=Symbol("file"),Qo=Symbol("directory"),Fi=Symbol("link"),Cl=Symbol("symlink"),Pl=Symbol("hardlink"),Rn=Symbol("ensureNoSymlink"),Dl=Symbol("unsupported"),Ul=Symbol("checkPath"),No=Symbol("stripAbsolutePath"),qt=Symbol("mkdir"),K=Symbol("onError"),Ni=Symbol("pending"),Bl=Symbol("pend"),Dr=Symbol("unpend"),Lo=Symbol("ended"),Co=Symbol("maybeClose"),ea=Symbol("skip"),An=Symbol("doChown"),Nn=Symbol("uid"),Ln=Symbol("gid"),Cn=Symbol("checkedCwd"),eg=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Pn=eg==="win32",tg=1024,rg=a((t,e)=>{if(!Pn)return N.unlink(t,e);let r=t+".DELETE."+sd(16).toString("hex");N.rename(t,r,n=>{if(n)return e(n);N.unlink(r,e)})},"mo"),ng=a(t=>{if(!Pn)return N.unlinkSync(t);let e=t+".DELETE."+sd(16).toString("hex");N.renameSync(t,e),N.unlinkSync(e)},"po"),jl=a((t,e,r)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:r,"vr"),da=class extends Dn{static{a(this,"Xt")}[Lo]=!1;[Cn]=!1;[Ni]=0;reservations=new Z_;transform;writable=!0;readable=!1;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[Lo]=!0,this[Co]()},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=!0}else this.uid=void 0,this.gid=void 0,this.setOwner=!1;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:tg,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||Pn,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=O(H.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:Q_():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[Nl](e))}warn(t,e,r={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(r.recoverable=!1),super.warn(t,e,r)}[Co](){this[Lo]&&this[Ni]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[No](t,e){let r=t[e],{type:n}=t;if(!r||this.preservePaths)return!0;let[i,s]=oa(r),o=s.replaceAll(/\\/g,"/").split("/");if(o.includes("..")||Pn&&/^[a-z]:\.\.$/i.test(o[0]??"")){if(e==="path"||n==="Link")return this.warn("TAR_ENTRY_ERROR",`${e} contains '..'`,{entry:t,[e]:r}),!1;let c=H.posix.dirname(t.path),l=H.posix.normalize(H.posix.join(c,o.join("/")));if(l.startsWith("../")||l==="..")return this.warn("TAR_ENTRY_ERROR",`${e} escapes extraction directory`,{entry:t,[e]:r}),!1}return i&&(t[e]=String(s),this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute ${e}`,{entry:t,[e]:r})),!0}[Ul](t){let e=O(t.path),r=e.split("/");if(this.strip){if(r.length<this.strip)return!1;if(t.type==="Link"){let n=O(String(t.linkpath)).split("/");if(n.length>=this.strip)t.linkpath=n.slice(this.strip).join("/");else return!1}r.splice(0,this.strip),t.path=r.join("/")}if(isFinite(this.maxDepth)&&r.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:t,path:e,depth:r.length,maxDepth:this.maxDepth}),!1;if(!this[No](t,"path")||!this[No](t,"linkpath"))return!1;if(t.absolute=H.isAbsolute(t.path)?O(H.resolve(t.path)):O(H.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:O(t.path),resolvedPath:t.absolute,cwd:this.cwd}),!1;if(t.absolute===this.cwd&&t.type!=="Directory"&&t.type!=="GNUDumpDir")return!1;if(this.win32){let{root:n}=H.win32.parse(String(t.absolute));t.absolute=n+yl(String(t.absolute).slice(n.length));let{root:i}=H.win32.parse(t.path);t.path=i+yl(t.path.slice(i.length))}return!0}[Nl](t){if(!this[Ul](t))return t.resume();switch(U_.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[Ko](t);default:return this[Dl](t)}}[K](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[Dr](),e.resume())}[qt](t,e,r){H_(O(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},r)}[An](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}[Nn](t){return jl(this.uid,t.uid,this.processUid)}[Ln](t){return jl(this.gid,t.gid,this.processGid)}[Zo](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,n=new Ji(String(t.absolute),{flags:hd(t.size),mode:r,autoClose:!1});n.on("error",c=>{n.fd&&N.close(n.fd,()=>{}),n.write=()=>!0,this[K](c,t),e()});let i=1,s=a(c=>{if(c){n.fd&&N.close(n.fd,()=>{}),this[K](c,t),e();return}--i===0&&n.fd!==void 0&&N.close(n.fd,l=>{l?this[K](l,t):this[Dr](),e()})},"o");n.on("finish",()=>{let c=String(t.absolute),l=n.fd;if(typeof l=="number"&&t.mtime&&!this.noMtime){i++;let d=t.atime||new Date,u=t.mtime;N.futimes(l,d,u,h=>h?N.utimes(c,d,u,f=>s(f&&h)):s())}if(typeof l=="number"&&this[An](t)){i++;let d=this[Nn](t),u=this[Ln](t);typeof d=="number"&&typeof u=="number"&&N.fchown(l,d,u,h=>h?N.chown(c,d,u,f=>s(f&&h)):s())}s()});let o=this.transform&&this.transform(t)||t;o!==t&&(o.on("error",c=>{this[K](c,t),e()}),t.pipe(o)),o.pipe(n)}[Qo](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode;this[qt](String(t.absolute),r,n=>{if(n){this[K](n,t),e();return}let i=1,s=a(()=>{--i===0&&(e(),this[Dr](),t.resume())},"o");t.mtime&&!this.noMtime&&(i++,N.utimes(String(t.absolute),t.atime||new Date,t.mtime,s)),this[An](t)&&(i++,N.chown(String(t.absolute),Number(this[Nn](t)),Number(this[Ln](t)),s)),s()})}[Dl](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[Cl](t,e){let r=O(H.relative(this.cwd,H.resolve(H.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Rn](t,this.cwd,r,()=>this[Fi](t,String(t.linkpath),"symlink",e),n=>{this[K](n,t),e()})}[Pl](t,e){let r=O(H.resolve(this.cwd,String(t.linkpath))),n=O(String(t.linkpath)).split("/");this[Rn](t,this.cwd,n,()=>this[Fi](t,r,"link",e),i=>{this[K](i,t),e()})}[Rn](t,e,r,n,i){let s=r.shift();if(this.preservePaths||s===void 0)return n();let o=H.resolve(e,s);N.lstat(o,(c,l)=>{if(c)return n();if(l?.isSymbolicLink())return i(new es(o,H.resolve(o,r.join("/"))));this[Rn](t,o,r,n,i)})}[Bl](){this[Ni]++}[Dr](){this[Ni]--,this[Co]()}[ea](t){this[Dr](),t.resume()}[Xo](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Pn}[Ko](t){this[Bl]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,r=>this[Ll](t,r))}[Ll](t,e){let r=a(o=>{e(o)},"i"),n=a(()=>{this[qt](this.cwd,this.dmode,o=>{if(o){this[K](o,t),r();return}this[Cn]=!0,i()})},"r"),i=a(()=>{if(t.absolute!==this.cwd){let o=O(H.dirname(String(t.absolute)));if(o!==this.cwd)return this[qt](o,this.dmode,c=>{if(c){this[K](c,t),r();return}s()})}s()},"n"),s=a(()=>{N.lstat(String(t.absolute),(o,c)=>{if(c&&(this.keep||this.newer&&c.mtime>(t.mtime??c.mtime))){this[ea](t),r();return}if(o||this[Xo](t,c))return this[be](null,t,r);if(c.isDirectory()){if(t.type==="Directory"){let l=this.chmod&&t.mode&&(c.mode&4095)!==t.mode,d=a(u=>this[be](u??null,t,r),"c");return l?N.chmod(String(t.absolute),Number(t.mode),d):d()}if(t.absolute!==this.cwd)return N.rmdir(String(t.absolute),l=>this[be](l??null,t,r))}if(t.absolute===this.cwd)return this[be](null,t,r);rg(String(t.absolute),l=>this[be](l??null,t,r))})},"o");this[Cn]?i():n()}[be](t,e,r){if(t){this[K](t,e),r();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[Zo](e,r);case"Link":return this[Pl](e,r);case"SymbolicLink":return this[Cl](e,r);case"Directory":case"GNUDumpDir":return this[Qo](e,r)}}[Fi](t,e,r,n){N[r](e,String(t.absolute),i=>{i?this[K](i,t):(this[Dr](),t.resume()),n()})}},Tn=a(t=>{try{return[null,t()]}catch(e){return[e,null]}},"ye"),yd=class extends da{static{a(this,"xe")}sync=!0;[be](t,e){return super[be](t,e,()=>{})}[Ko](t){if(!this[Cn]){let i=this[qt](this.cwd,this.dmode);if(i)return this[K](i,t);this[Cn]=!0}if(t.absolute!==this.cwd){let i=O(H.dirname(String(t.absolute)));if(i!==this.cwd){let s=this[qt](i,this.dmode);if(s)return this[K](s,t)}}let[e,r]=Tn(()=>N.lstatSync(String(t.absolute)));if(r&&(this.keep||this.newer&&r.mtime>(t.mtime??r.mtime)))return this[ea](t);if(e||this[Xo](t,r))return this[be](null,t);if(r.isDirectory()){if(t.type==="Directory"){let s=this.chmod&&t.mode&&(r.mode&4095)!==t.mode,[o]=s?Tn(()=>{N.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[be](o,t)}let[i]=Tn(()=>N.rmdirSync(String(t.absolute)));this[be](i,t)}let[n]=t.absolute===this.cwd?[]:Tn(()=>ng(String(t.absolute)));this[be](n,t)}[Zo](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,n=a(o=>{let c;try{N.closeSync(i)}catch(l){c=l}(o||c)&&this[K](o||c,t),e()},"r"),i;try{i=N.openSync(String(t.absolute),hd(t.size),r)}catch(o){return n(o)}let s=this.transform&&this.transform(t)||t;s!==t&&(s.on("error",o=>this[K](o,t)),t.pipe(s)),s.on("data",o=>{try{N.writeSync(i,o,0,o.length)}catch(c){n(c)}}),s.on("end",()=>{let o=null;if(t.mtime&&!this.noMtime){let c=t.atime||new Date,l=t.mtime;try{N.futimesSync(i,c,l)}catch(d){try{N.utimesSync(String(t.absolute),c,l)}catch{o=d}}}if(this[An](t)){let c=this[Nn](t),l=this[Ln](t);try{N.fchownSync(i,Number(c),Number(l))}catch(d){try{N.chownSync(String(t.absolute),Number(c),Number(l))}catch{o=o||d}}}n(o)})}[Qo](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode,n=this[qt](String(t.absolute),r);if(n){this[K](n,t),e();return}if(t.mtime&&!this.noMtime)try{N.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[An](t))try{N.chownSync(String(t.absolute),Number(this[Nn](t)),Number(this[Ln](t)))}catch{}e(),t.resume()}[qt](t,e){try{return V_(O(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(r){return r}}[Rn](t,e,r,n,i){if(this.preservePaths||r.length===0)return n();let s=e;for(let o of r){s=H.resolve(s,o);let[c,l]=Tn(()=>N.lstatSync(s));if(c)return n();if(l.isSymbolicLink())return i(new es(s,H.resolve(e,r.join("/"))))}n()}[Fi](t,e,r,n){let i=`${r}Sync`;try{N[i](e,String(t.absolute)),n(),t.resume()}catch(s){return this[K](s,t)}}},ig=a(t=>{let e=new yd(t),r=t.file,n=id.statSync(r),i=t.maxReadSize||16*1024*1024;new vm(r,{readSize:i,size:n.size}).pipe(e)},"Eo"),sg=a((t,e)=>{let r=new da(t),n=t.maxReadSize||16*1024*1024,i=t.file;return new Promise((s,o)=>{r.on("error",o),r.on("close",s),id.stat(i,(c,l)=>{if(c)o(c);else{let d=new ra(i,{readSize:n,size:l.size});d.on("error",o),d.pipe(r)}})})},"wo"),wd=Un(ig,sg,t=>new yd(t),t=>new da(t),(t,e)=>{e?.length&&Kl(t,e)}),og=a((t,e)=>{let r=new la(t),n=!0,i,s;try{try{i=ue.openSync(t.file,"r+")}catch(l){if(l?.code==="ENOENT")i=ue.openSync(t.file,"w+");else throw l}let o=ue.fstatSync(i),c=Buffer.alloc(512);e:for(s=0;s<o.size;s+=512){for(let u=0,h=0;u<512;u+=h){if(h=ue.readSync(i,c,u,c.length-u,s+u),s===0&&c[0]===31&&c[1]===139)throw new Error("cannot append to compressed archives");if(!h)break e}let l=new ur(c);if(!l.cksumValid)break;let d=512*Math.ceil((l.size||0)/512);if(s+d+512>o.size)break;s+=d,t.mtimeCache&&l.mtime&&t.mtimeCache.set(String(l.path),l.mtime)}n=!1,ag(t,r,s,i,e)}finally{if(n)try{ue.closeSync(i)}catch{}}},"yo"),ag=a((t,e,r,n,i)=>{let s=new ql(t.file,{fd:n,start:r});e.pipe(s),lg(e,i)},"Ro"),cg=a((t,e)=>{e=Array.from(e);let r=new Zi(t),n=a((i,s,o)=>{let c=a((f,p)=>{f?ue.close(i,m=>o(f)):o(null,p)},"a"),l=0;if(s===0)return c(null,0);let d=0,u=Buffer.alloc(512),h=a((f,p)=>{if(f||p===void 0)return c(f);if(d+=p,d<512&&p)return ue.read(i,u,d,u.length-d,l+d,h);if(l===0&&u[0]===31&&u[1]===139)return c(new Error("cannot append to compressed archives"));if(d<512)return c(null,l);let m=new ur(u);if(!m.cksumValid)return c(null,l);let _=512*Math.ceil((m.size??0)/512);if(l+_+512>s||(l+=_+512,l>=s))return c(null,l);t.mtimeCache&&m.mtime&&t.mtimeCache.set(String(m.path),m.mtime),d=0,ue.read(i,u,0,512,l,h)},"y");ue.read(i,u,0,512,l,h)},"i");return new Promise((i,s)=>{r.on("error",s);let o="r+",c=a((l,d)=>{if(l&&l.code==="ENOENT"&&o==="r+")return o="w+",ue.open(t.file,o,c);if(l||!d)return s(l);ue.fstat(d,(u,h)=>{if(u)return ue.close(d,()=>s(u));n(d,h.size,(f,p)=>{if(f)return s(f);let m=new Ji(t.file,{fd:d,start:p});r.pipe(m),m.on("error",s),m.on("close",i),dg(r,e)})})},"a");ue.open(t.file,o,c)})},"go"),lg=a((t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?zr({file:bd.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:a(n=>t.add(n),"onReadEntry")}):t.add(r)}),t.end()},"bo"),dg=a(async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await zr({file:bd.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:a(n=>t.add(n),"onReadEntry")}):t.add(r);t.end()},"_o"),xn=Un(og,cg,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!Im(t))throw new TypeError("file is required");if(t.gzip||t.brotli||t.zstd||t.file.endsWith(".br")||t.file.endsWith(".tbr"))throw new TypeError("cannot append to compressed archives");if(!e?.length)throw new TypeError("no paths specified to add/replace")}),r1=Un(xn.syncFile,xn.asyncFile,xn.syncNoFile,xn.asyncNoFile,(t,e=[])=>{xn.validate?.(t,e),ug(t)}),ug=a(t=>{let e=t.filter;t.mtimeCache||(t.mtimeCache=new Map),t.filter=e?(r,n)=>e(r,n)&&!((t.mtimeCache?.get(r)??n.mtime??0)>(n.mtime??0)):(r,n)=>!((t.mtimeCache?.get(r)??n.mtime??0)>(n.mtime??0))},"To")});import{chmodSync as xd,mkdirSync as hg,renameSync as Rd,writeFileSync as kd,openSync as Ed,closeSync as Sd,fsyncSync as Td,rmSync as pg}from"node:fs";import{randomUUID as fg}from"node:crypto";import{dirname as Od}from"node:path";function pt(t){hg(t,{recursive:!0,mode:448});try{xd(t,448)}catch{}}function Bn(t,e,r=384){pt(Od(t));let n=`${t}.${process.pid}.tmp`;kd(n,`${JSON.stringify(e,null,2)}
6
+ `,{mode:r}),Rd(n,t);try{xd(t,r)}catch{}}function Ae(t,e){let r=Od(t);pt(r);let n=`${t}.${fg()}.tmp`;try{let i=Ed(n,"wx",384);try{kd(i,`${JSON.stringify(e,null,2)}
7
+ `),Td(i)}finally{Sd(i)}Rd(n,t);let s;try{s=Ed(r,"r"),Td(s)}catch(o){if(!["EINVAL","ENOTSUP"].includes(o.code)&&process.platform!=="win32")throw o}finally{s!==void 0&&Sd(s)}}finally{pg(n,{force:!0})}}var He=C(()=>{a(pt,"ensurePrivateDirectory");a(Bn,"writeJsonAtomic");a(Ae,"writeJsonDurableAtomic")});import{homedir as ua,platform as mg}from"node:os";import{join as Wt}from"node:path";function W(t=process.env,e=mg()){return t.INTERSCALE_HOME?t.INTERSCALE_HOME:e==="darwin"?Wt(ua(),"Library","Application Support","Interscale"):e==="win32"?Wt(t.LOCALAPPDATA||Wt(ua(),"AppData","Local"),"Interscale"):Wt(t.XDG_STATE_HOME||Wt(ua(),".local","state"),"interscale")}function jn(t=process.env){return t.INTERSCALE_TRANSFER_DB||Wt(W(t),"controller-transfers.sqlite3")}function Id(t=process.env){return t.INTERSCALE_DOWNLOAD_DB||Wt(W(t),"controller-downloads.sqlite3")}function Mn(t=process.env){return t.INTERSCALE_AGENT_CONFIG||Wt(W(t),"agent.json")}var Ne=C(()=>{a(W,"userDataDirectory");a(jn,"controllerTransferDatabasePath");a(Id,"controllerDownloadDatabasePath");a(Mn,"agentConfigPath")});import{execFile as _g}from"node:child_process";import{createHash as gg,randomUUID as Nd}from"node:crypto";import{existsSync as ha}from"node:fs";import{lstat as Ld,mkdir as yg,readdir as wg,rename as Ad,rm as pa,stat as Cd,open as bg}from"node:fs/promises";import{basename as Pd,dirname as $n,isAbsolute as Z1,join as qn,relative as Q1,resolve as Ht,sep as vg}from"node:path";async function Ud(t,e={}){let r=Ht(t);if(!(await Ld(r)).isDirectory())throw new Error(`Directory source expected: ${r}`);let i=await Rg(r,e.gitignore?await Tg(r):null),s=Ht(e.stagingDirectory||qn(W(),"staging"));pt(s);let o=Ht(e.output||qn(s,`directory-${Nd()}.tar`));return await nd({cwd:r,file:o,portable:!0,noMtime:!0,noDirRecurse:!0,follow:!1,gzip:!1,strict:!0},i.length>0?i:["."]),{path:o,kind:Eg,source_name:`${Pd(r)}.tar`,original_path:r,entries:i.length,size:(await Cd(o)).size,temporary:!0}}async function Bd(t,e,r={}){r.signal?.throwIfAborted();let n=Ht(t),i=Ht(e),s=await Cd(n);if(!s.isFile())throw new Error(`Directory archive is not a file: ${n}`);let o=Number(r.maximumBytes||s.size+1024*1024);if(await kg(n,o),r.signal?.throwIfAborted(),ha(i)&&!r.overwrite)throw new Error(`Destination already exists: ${i}`);let{stage:c,backup:l}=Sg(i,r.transferId||Nd());await pa(c,{recursive:!0,force:!0}),await yg(c,{recursive:!0,mode:448});let d=!1;try{if(await wd({cwd:c,file:n,preservePaths:!1,strict:!0,unlink:!0,filter:a((u,h)=>Dd.has(h.type),"filter")}),r.signal?.throwIfAborted(),await r.onStaged?.({destination:i,stage:c,backup:l}),d=!0,r.signal?.throwIfAborted(),ha(i)){if(!r.overwrite)throw Object.assign(new Error(`Destination already exists: ${i}`),{code:"destination_exists"});if(ha(l))throw Object.assign(new Error(`Directory backup already exists: ${l}`),{code:"directory_recovery_required"});await Ad(i,l),await fa($n(i)),await r.onBackedUp?.({destination:i,stage:c,backup:l})}await Ad(c,i),await fa($n(i)),await r.onPublished?.({destination:i,stage:c,backup:l}),await pa(l,{recursive:!0,force:!0}),await fa($n(i)),await r.onCleaned?.({destination:i,stage:c,backup:l})}catch(u){throw d||await pa(c,{recursive:!0,force:!0}),u}return i}function Sg(t,e){let r=Ht(t),n=gg("sha256").update(String(e)).digest("hex").slice(0,24),i=`.${Pd(r).slice(0,40)}.interscale-${n}`;return{destination:r,stage:qn($n(r),`${i}.stage`),backup:qn($n(r),`${i}.backup`)}}async function fa(t){if(process.platform==="win32")return;let e=await bg(t,"r");try{await e.sync()}catch(r){if(!["EINVAL","ENOTSUP"].includes(r.code))throw r}finally{await e.close()}}async function Tg(t,{run:e=xg}={}){let r=await e("git",["-C",t,"ls-files","-z","--cached","--others","--exclude-standard"]).catch(()=>null);if(r===null)return null;let n=new Set,i=new Set;for(let s of r.split("\0").filter(Boolean)){n.add(s);for(let o=s.indexOf("/");o>0;o=s.indexOf("/",o+1))i.add(s.slice(0,o))}return(s,o)=>o?i.has(s):n.has(s)}function xg(t,e){return new Promise((r,n)=>_g(t,e,{encoding:"utf8",maxBuffer:256*1024*1024,windowsHide:!0,timeout:6e4},(i,s)=>i?n(i):r(s)))}async function Rg(t,e=null){let r=[];return await n(""),r;async function n(i){let s=Ht(t,i),o=await wg(s,{withFileTypes:!0});o.sort((c,l)=>Ig(c.name,l.name));for(let c of o){let l=i?qn(i,c.name):c.name,d=l.split(vg).join("/");if(e&&!e(d,c.isDirectory()))continue;let u=await Ld(Ht(t,l));if(u.isSymbolicLink())throw new Error(`Symbolic links are not accepted in directory transfers: ${d}`);if(u.isDirectory())r.push(`${d}/`),await n(l);else if(u.isFile())r.push(d);else throw new Error(`Unsupported filesystem entry in directory transfer: ${d}`)}}a(n,"walk")}async function kg(t,e){let r=0,n=null,i=new Map;if(await zr({file:t,strict:!0,onReadEntry(s){if(!n)try{if(Og(s.path),!Dd.has(s.type))throw new Error(`Archive entry type is not allowed: ${s.type}`);let o=s.path.replace(/\\/g,"/").split("/").filter(c=>c&&c!==".").join("/").normalize("NFC").toLowerCase();if(o&&i.has(o))throw new Error(`Archive paths collide on case-insensitive file systems: ${i.get(o)} and ${s.path}`);if(o&&i.set(o,s.path),r+=Number(s.size||0),!Number.isSafeInteger(r)||r>e)throw new Error(`Archive expands beyond its declared limit of ${e} bytes`)}catch(o){n=o}}}),n)throw n}function Og(t){let e=String(t||"").replace(/\\/g,"/");if(!e||e.includes("\0")||e.startsWith("/")||/^[A-Za-z]:/.test(e))throw new Error(`Unsafe archive path: ${JSON.stringify(t)}`);if(e.split("/").some(r=>r===".."))throw new Error(`Archive path escapes destination: ${e}`)}function Ig(t,e){return Buffer.compare(Buffer.from(t,"utf8"),Buffer.from(e,"utf8"))}var Eg,Dd,ma=C(()=>{vd();He();Ne();Eg="directory-tar",Dd=new Set(["File","OldFile","Directory"]);a(Ud,"createDirectoryArchive");a(Bd,"extractDirectoryArchive");a(Sg,"directoryPublicationPaths");a(fa,"syncDirectory");a(Tg,"gitTrackedFilter");a(xg,"execFileText");a(Rg,"enumerateDirectory");a(kg,"validateDirectoryArchive");a(Og,"validateArchivePath");a(Ig,"compareNames")});import{createHash as Ag}from"node:crypto";import{lstat as Ng,open as Lg}from"node:fs/promises";function ts(t){return JSON.stringify([t.dev,t.ino,t.size,t.mtimeMs,t.ctimeMs,t.birthtimeMs])}function pr(t,e){if(!e.isFile()||e.isSymbolicLink()||ts(t)!==ts(e))throw Object.assign(new Error("Source changed while its content was being indexed; retry after writes finish"),{code:"source_changed"})}async function Wr(t,{expected:e,signal:r,io:n={lstat:Ng,open:Lg}}={}){r?.throwIfAborted();let i=e||await n.lstat(t);pr(i,i);let s=await n.open(t,"r");try{pr(i,await s.stat());let o=Ag("sha256"),c=Buffer.allocUnsafe(Math.min(1024*1024,Math.max(1,i.size))),l=0;for(;l<i.size;){r?.throwIfAborted();let u=Math.min(c.length,i.size-l),{bytesRead:h}=await s.read(c,0,u,l);if(!h)throw Object.assign(new Error("Source became shorter while indexing"),{code:"source_changed"});o.update(c.subarray(0,h)),l+=h}r?.throwIfAborted(),pr(i,await s.stat());let d;try{d=await n.lstat(t)}catch(u){throw u.code==="ENOENT"?Object.assign(new Error("Source disappeared while indexing"),{code:"source_changed",cause:u}):u}return pr(i,d),o.digest("hex")}finally{await s.close()}}var Fn=C(()=>{a(ts,"fileRevision");a(pr,"assertFileRevision");a(Wr,"hashStableFile")});import{constants as jd}from"node:fs";import{copyFile as Cg,chmod as Pg,lstat as Dg,mkdir as Ug,open as Bg,rm as jg,statfs as Mg}from"node:fs/promises";import{randomUUID as $g}from"node:crypto";import{basename as qg,join as Fg}from"node:path";async function Md(t,{stagingDirectory:e,reserve:r=1024**3,signal:n,hash:i=Wr,filesystem:s={copyFile:Cg,chmod:Pg,lstat:Dg,mkdir:Ug,open:Bg,rm:jg,statfs:Mg}}={}){n?.throwIfAborted();let o=await s.lstat(t);pr(o,o),await s.mkdir(e,{recursive:!0,mode:448});let c=await s.statfs(e,{bigint:!0});if(c.bavail*c.bsize<BigInt(o.size)+BigInt(r))throw Object.assign(new Error("Insufficient storage to retain a stable transfer source"),{code:"insufficient_space"});let l=Fg(e,`file-${$g()}.snapshot`);try{n?.throwIfAborted(),await s.copyFile(t,l,jd.COPYFILE_EXCL|jd.COPYFILE_FICLONE),n?.throwIfAborted(),await s.chmod(l,384),pr(o,await s.lstat(t));let d=await s.lstat(l);if(d.size!==o.size)throw Object.assign(new Error("Source size changed while copying"),{code:"source_changed"});let u=await i(l,{expected:d,signal:n}),h=await s.open(l,"r+");try{await h.sync()}finally{await h.close()}return n?.throwIfAborted(),{path:l,kind:"file",source_name:qg(t),size:d.size,temporary:!0,sha256:u}}catch(d){throw await s.rm(l,{force:!0}).catch(()=>{}),d}}var $d=C(()=>{Fn();a(Md,"createFileSnapshot")});import{Worker as zg}from"node:worker_threads";var Hr,_a=C(()=>{Fn();Hr=class{static{a(this,"FileHasher")}constructor({workerUrl:e=new URL("./file-hash-worker.mjs",import.meta.url),timeoutMs:r=30*6e4}={}){this.workerUrl=e,this.timeoutMs=r,this.sequence=0,this.terminations=new Set}hash(e,{expected:r,signal:n}={}){if(this.closed)return Promise.reject(new Error("File hasher closed"));if(this.pending)return Promise.reject(new Error("File hasher is busy"));if(n?.aborted)return Promise.reject(n.reason);let i=this.worker||this.start(),s=++this.sequence;return i.ref(),new Promise((o,c)=>{let l=a(()=>this.retire(i,n.reason),"abort"),d=setTimeout(()=>this.retire(i,Object.assign(new Error("File hashing exceeded its deadline"),{code:"file_hash_timeout"})),this.timeoutMs);this.pending={id:s,resolve:o,reject:c,cleanup:a(()=>{clearTimeout(d),n?.removeEventListener("abort",l)},"cleanup")},n?.addEventListener("abort",l,{once:!0});try{i.postMessage({id:s,path:e,revision:ts(r)})}catch(u){this.retire(i,u)}})}start(){let e=new zg(this.workerUrl);return this.worker=e,e.on("message",r=>{this.worker!==e||r?.id!==this.pending?.id||(r.error?this.settle(Object.assign(new Error(r.error.message),{code:r.error.code})):/^[a-f0-9]{64}$/.test(r.sha256||"")?this.settle(null,r.sha256):this.retire(e,new Error("Invalid hash worker response")))}),e.on("error",r=>this.retire(e,r)),e.on("exit",r=>{this.worker===e&&(this.worker=null,this.settle(new Error(`File hash worker exited before completion (${r})`)))}),e}settle(e,r){let n=this.pending;this.pending=null,this.worker?.unref(),n&&(n.cleanup(),e?n.reject(e):n.resolve(r))}retire(e,r){if(this.worker!==e)return;this.worker=null,this.settle(r);let n=e.terminate();this.terminations.add(n),n.then(()=>this.terminations.delete(n),()=>this.terminations.delete(n))}async close(){this.closed=!0,this.worker&&this.retire(this.worker,new Error("File hasher closed")),await Promise.allSettled([...this.terminations])}}});import{lstat as Wg}from"node:fs/promises";import{join as Hg}from"node:path";async function ga(t,e={}){e.signal?.throwIfAborted();let r=await Wg(t);if(r.isSymbolicLink())throw new Error(`Symbolic links are not accepted as transfer sources: ${t}`);if(r.isFile()){let n=new Hr;try{return await Md(t,{stagingDirectory:e.stagingDirectory||Hg(W(),"staging"),signal:e.signal,hash:a((i,s)=>n.hash(i,s),"hash")})}finally{await n.close()}}if(r.isDirectory()){e.json||process.stderr.write(`Packaging directory ${t}\u2026
8
+ `);let n=await Ud(t,{stagingDirectory:e.stagingDirectory,gitignore:e.gitignore===!0});return e.json||process.stderr.write(`Prepared deterministic archive (${n.size} bytes, ${n.entries} entries).
9
+ `),n}throw new Error(`Transfer source must be a regular file or directory: ${t}`)}var qd=C(()=>{ma();$d();Ne();_a();a(ga,"prepareTransferSource")});import{chmodSync as Gg,existsSync as Vg,mkdirSync as Wd}from"node:fs";import{dirname as Jg,join as Fd,resolve as rs}from"node:path";import{DatabaseSync as Yg}from"node:sqlite";import{randomUUID as Kg}from"node:crypto";import{isDeepStrictEqual as Hd}from"node:util";function Gd(t,e=jn()){if(!Vg(e))return null;let r=new zn(e);try{return r.database.prepare("SELECT token FROM transfers WHERE id = ?").get(t)?.token??null}finally{r.close()}}var ns,zd,zn,is,ya=C(()=>{Ne();ns=class{static{a(this,"ResumeStateStore")}constructor(e,r){this.kind=r,Wd(Jg(e),{recursive:!0,mode:448}),this.database=new Yg(e,{timeout:5e3});try{Gg(e,384)}catch{}this.database.exec(`
10
+ PRAGMA journal_mode = WAL;
11
+ CREATE TABLE IF NOT EXISTS ${r}_requests (
12
+ request_id TEXT PRIMARY KEY,
13
+ server_url TEXT NOT NULL,
14
+ input_json TEXT NOT NULL,
15
+ ${r==="download"?"output_path TEXT NOT NULL,":""}
16
+ ${r}_id TEXT,
17
+ created_at INTEGER NOT NULL
18
+ ) STRICT;
19
+ `)}prepareRequest({serverUrl:e,input:r,outputPath:n,requestId:i=Kg()}){if(typeof i!="string"||!i.trim()||i.length>200)throw new Error("Request ID must be a nonempty string of at most 200 characters");let s=this.kind==="download"?{output_path:rs(n)}:{},o=this.database.prepare(`SELECT * FROM ${this.kind}_requests WHERE request_id=?`).get(i);if(o){if(o.server_url!==e||!Hd(JSON.parse(o.input_json),r)||Object.entries(s).some(([l,d])=>o[l]!==d))throw new Error("Request ID was already used for a different hub, source, or destination");return i}let c={request_id:i,server_url:e,input_json:JSON.stringify(r),...s,created_at:Date.now()};return this.database.prepare(`INSERT INTO ${this.kind}_requests (${Object.keys(c).join(",")}) VALUES (${Object.keys(c).map(()=>"?").join(",")})`).run(...Object.values(c)),i}pendingRequests(){return this.database.prepare(`SELECT * FROM ${this.kind}_requests WHERE ${this.kind}_id IS NULL ORDER BY created_at LIMIT 1000`).all().map(({input_json:e,...r})=>({...r,input:JSON.parse(e)}))}requestRecord(e){let r=this.database.prepare(`SELECT * FROM ${this.kind}_requests WHERE request_id=?`).get(e);return r?{...r,input:JSON.parse(r.input_json)}:null}complete(e){this.database.prepare(`UPDATE ${this.kind}s SET state = 'completed', updated_at = ? WHERE id = ?`).run(Date.now(),e)}close(){this.database.close()}},zd=`
20
+ id TEXT PRIMARY KEY,
21
+ server_url TEXT NOT NULL,
22
+ token TEXT NOT NULL,
23
+ job_id TEXT,
24
+ relative_path TEXT NOT NULL,
25
+ source_path TEXT,
26
+ output_path TEXT NOT NULL,
27
+ part_path TEXT NOT NULL,
28
+ download_json TEXT NOT NULL,
29
+ manifest_json TEXT,
30
+ received_json TEXT NOT NULL DEFAULT '[]',
31
+ published INTEGER NOT NULL DEFAULT 0,
32
+ state TEXT NOT NULL,
33
+ created_at INTEGER NOT NULL,
34
+ updated_at INTEGER NOT NULL
35
+ `,zn=class extends ns{static{a(this,"TransferStateStore")}constructor(e=jn()){super(e,"transfer"),this.database.exec(`
36
+ CREATE TABLE IF NOT EXISTS transfers (
37
+ id TEXT PRIMARY KEY,
38
+ server_url TEXT NOT NULL,
39
+ token TEXT NOT NULL,
40
+ source_path TEXT NOT NULL,
41
+ target TEXT NOT NULL,
42
+ destination_path TEXT NOT NULL,
43
+ transfer_json TEXT NOT NULL,
44
+ temporary INTEGER NOT NULL DEFAULT 0,
45
+ state TEXT NOT NULL,
46
+ created_at INTEGER NOT NULL,
47
+ updated_at INTEGER NOT NULL
48
+ ) STRICT;
49
+ `),this.database.prepare("PRAGMA table_info(transfers)").all().some(n=>n.name==="temporary")||this.database.exec("ALTER TABLE transfers ADD COLUMN temporary INTEGER NOT NULL DEFAULT 0")}save({serverUrl:e,token:r,sourcePath:n,target:i,destinationPath:s,transfer:o,temporary:c=!1,requestId:l=null}){let d=Date.now();this.database.prepare(`
50
+ INSERT INTO transfers(
51
+ id, server_url, token, source_path, target, destination_path,
52
+ transfer_json, temporary, state, created_at, updated_at
53
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'active', ?, ?)
54
+ ON CONFLICT(id) DO UPDATE SET
55
+ token = excluded.token,
56
+ source_path = excluded.source_path,
57
+ transfer_json = excluded.transfer_json,
58
+ temporary = excluded.temporary,
59
+ state = 'active',
60
+ updated_at = excluded.updated_at
61
+ `).run(o.id,e,r,rs(n),i,s,JSON.stringify(o),c?1:0,d,d),l&&this.database.prepare("UPDATE transfer_requests SET transfer_id=? WHERE request_id=?").run(o.id,l)}get(e){let r=this.database.prepare("SELECT * FROM transfers WHERE id = ?").get(e);if(!r)throw new Error(`No local resumable transfer found: ${e}`);return{...r,temporary:!!r.temporary,transfer:JSON.parse(r.transfer_json)}}fail(e){this.database.prepare("UPDATE transfers SET state = 'failed', updated_at = ? WHERE id = ?").run(Date.now(),e)}active(){return this.database.prepare("SELECT id, source_path, target, destination_path, temporary, updated_at FROM transfers WHERE state = 'active' ORDER BY updated_at DESC").all().map(e=>({...e,temporary:!!e.temporary}))}};a(Gd,"storedTransferToken");is=class extends ns{static{a(this,"DownloadStateStore")}constructor(e=Id(),r={}){super(e,"download"),this.partRoot=rs(r.partRoot||Fd(W(),"downloads")),this.database.exec(`
62
+ CREATE TABLE IF NOT EXISTS downloads (${zd}) STRICT;
63
+ `),this.migrateForPulls(),this.database.exec(`CREATE TABLE IF NOT EXISTS download_chunk_hashes (
64
+ download_id TEXT NOT NULL, chunk_index INTEGER NOT NULL, sha256 TEXT NOT NULL,
65
+ PRIMARY KEY(download_id,chunk_index)
66
+ ) STRICT;`)}migrateForPulls(){let r=this.database.prepare("PRAGMA table_info(downloads)").all().find(n=>n.name==="job_id");!r||r.notnull===0||this.database.exec(`
67
+ CREATE TABLE downloads_migrated (${zd}) STRICT;
68
+ INSERT INTO downloads_migrated (
69
+ id, server_url, token, job_id, relative_path, output_path, part_path,
70
+ download_json, manifest_json, received_json, published, state, created_at, updated_at
71
+ )
72
+ SELECT id, server_url, token, job_id, relative_path, output_path, part_path,
73
+ download_json, manifest_json, received_json, published, state, created_at, updated_at
74
+ FROM downloads;
75
+ DROP TABLE downloads;
76
+ ALTER TABLE downloads_migrated RENAME TO downloads;
77
+ `)}request(e){let r=this.database.prepare("SELECT * FROM download_requests WHERE request_id=?").get(e);return r?{...r,input:JSON.parse(r.input_json)}:null}saveCreated({serverUrl:e,token:r,jobId:n=null,relativePath:i,sourcePath:s=null,outputPath:o,download:c,requestId:l=null}){let d=Date.now(),u=this.partRoot;Wd(u,{recursive:!0,mode:448});let h=Fd(u,`${c.id}.part`);return this.database.prepare(`
78
+ INSERT INTO downloads(
79
+ id, server_url, token, job_id, relative_path, source_path, output_path, part_path,
80
+ download_json, state, created_at, updated_at
81
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'active', ?, ?)
82
+ ON CONFLICT(id) DO UPDATE SET token = excluded.token, download_json = excluded.download_json,
83
+ state = 'active', updated_at = excluded.updated_at
84
+ `).run(c.id,e,r,n,i||".",s,rs(o),h,JSON.stringify(c),d,d),l&&this.database.prepare("UPDATE download_requests SET download_id=? WHERE request_id=?").run(c.id,l),this.get(c.id)}setManifest(e,r){let n=this.get(e).manifest,i=a(s=>[s.kind,s.size,s.sha256,s.chunk_size,s.total_chunks],"identity");if(n&&!Hd(i(n),i(r)))throw Object.assign(new Error("Download manifest changed; start a new download instead of reusing saved chunks"),{code:"source_changed",terminal:!0});this.database.prepare(`
85
+ UPDATE downloads SET manifest_json = ?, updated_at = ? WHERE id = ?
86
+ `).run(JSON.stringify(r),Date.now(),e)}markChunk(e,r,n=null){if(!Number.isSafeInteger(r)||r<0||n!==null&&!/^[a-f0-9]{64}$/.test(n))throw new Error("Invalid chunk receipt");let i=this.database.prepare("SELECT received_json FROM downloads WHERE id=?").get(e);if(!i)throw new Error(`No local resumable download found: ${e}`);let s=[...new Set([...JSON.parse(i.received_json),r])].sort((o,c)=>o-c);this.database.exec("BEGIN IMMEDIATE");try{n?this.database.prepare("INSERT OR REPLACE INTO download_chunk_hashes(download_id,chunk_index,sha256) VALUES (?,?,?)").run(e,r,n):this.database.prepare("DELETE FROM download_chunk_hashes WHERE download_id=? AND chunk_index=?").run(e,r),this.database.prepare("UPDATE downloads SET received_json = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(s),Date.now(),e),this.database.exec("COMMIT")}catch(o){throw this.database.exec("ROLLBACK"),o}return s}forgetChunk(e,r){let n=this.database.prepare("SELECT received_json FROM downloads WHERE id=?").get(e);if(!n)throw new Error(`No local resumable download found: ${e}`);let i=JSON.parse(n.received_json).filter(s=>s!==r);this.database.prepare("UPDATE downloads SET received_json=? WHERE id=?").run(JSON.stringify(i),e),this.database.prepare("DELETE FROM download_chunk_hashes WHERE download_id=? AND chunk_index=?").run(e,r)}markPublished(e){this.database.prepare("UPDATE downloads SET published = 1, updated_at = ? WHERE id = ?").run(Date.now(),e)}get(e){let r=this.database.prepare("SELECT * FROM downloads WHERE id = ?").get(e);if(!r)throw new Error(`No local resumable download found: ${e}`);return{...r,published:!!r.published,download:JSON.parse(r.download_json),manifest:r.manifest_json?JSON.parse(r.manifest_json):null,received:JSON.parse(r.received_json),chunk_hashes:Object.fromEntries(this.database.prepare("SELECT chunk_index,sha256 FROM download_chunk_hashes WHERE download_id=?").all(e).map(n=>[n.chunk_index,n.sha256]))}}active(){return this.database.prepare(`
87
+ SELECT id, job_id, relative_path, source_path, output_path, published, updated_at
88
+ FROM downloads WHERE state = 'active' ORDER BY updated_at DESC
89
+ `).all().map(e=>({...e,published:!!e.published}))}}});import{Agent as Xg,request as Zg}from"node:http";function Qg(t){let e=t||"",r=Vd.get(e);return r||(r=new Xg({keepAlive:!0,keepAliveMsecs:15e3,maxSockets:32,...t?{localAddress:t}:{}}),Vd.set(e,r)),r}async function ft(t,e={}){let{method:r="GET",headers:n={},body:i,signal:s,localAddress:o,maxResponseBytes:c=1024*1024}=e;if(!Number.isSafeInteger(c)||c<0)throw new Error("Invalid direct response limit");if(!o){let l=await fetch(t,{method:r,headers:n,body:i,signal:s}),d=[],u=0;if(Number(l.headers.get("content-length"))>c)throw await l.body?.cancel(),wa();for await(let h of l.body||[]){if(u+=h.length,u>c)throw wa();d.push(h)}return Jd(l.status,l.headers,Buffer.concat(d))}return new Promise((l,d)=>{let u=!1,h=a((g,y)=>{u||(u=!0,_(),g(y))},"finish"),f=new URL(t),p=Zg({protocol:f.protocol,hostname:f.hostname.replace(/^\[/,"").replace(/\]$/,""),port:f.port||80,path:`${f.pathname}${f.search}`,method:r,headers:n,agent:Qg(o)},g=>{let y=[],w=0,x=a(()=>{h(d,wa()),g.destroy(),p.destroy()},"tooLarge");if(g.on("data",v=>{if(w+=v.length,w>c){x();return}y.push(v)}),g.on("error",v=>h(d,v)),g.on("aborted",()=>h(d,new Error("Direct response ended prematurely"))),Number(g.headers["content-length"])>c){x();return}g.on("end",()=>{let v=Buffer.concat(y);h(l,Jd(g.statusCode,{get:a(k=>g.headers[String(k).toLowerCase()]??null,"get")},v))})}),m=a(()=>{p.destroy(),h(d,ey(s))},"onAbort"),_=a(()=>s?.removeEventListener?.("abort",m),"cleanup");if(s){if(s.aborted)return m();s.addEventListener("abort",m,{once:!0})}p.on("error",g=>h(d,g)),i==null?p.end():p.end(i)})}function Jd(t,e,r){return{ok:t>=200&&t<300,status:t,headers:e,text:a(async()=>r.toString("utf8"),"text"),json:a(async()=>JSON.parse(r.toString("utf8")),"json"),arrayBuffer:a(async()=>r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength),"arrayBuffer")}}function wa(){return Object.assign(new Error("Direct response exceeds its permitted size"),{code:"response_too_large"})}function ey(t){let e=t?.reason;if(e instanceof Error)return e;let r=new Error("The operation was aborted");return r.name="AbortError",r}var Vd,ss=C(()=>{Vd=new Map;a(Qg,"agentFor");a(ft,"directFetch");a(Jd,"bufferedResponse");a(wa,"responseLimitError");a(ey,"abortReason")});import{createCipheriv as ty,createDecipheriv as ry,createHash as ny,createHmac as iy,hkdfSync as Kd,randomBytes as sy,timingSafeEqual as oy}from"node:crypto";function Yd(t){return ny("sha256").update(t).digest()}function Xd(t,e){let r=Yd(Buffer.from(String(t))),n=Yd(Buffer.from(String(e)));return oy(r,n)}function Zd(t,e,r,n){let i=eu(t,e),s=sy(12),o=ty("aes-256-gcm",i,s);o.setAAD(Buffer.from(`${e}:${r}`,"utf8"));let c=[o.update(n),o.final()],l=o.getAuthTag(),d=Buffer.allocUnsafe(28+c[0].length+c[1].length);return s.copy(d,0),l.copy(d,12),c[0].copy(d,28),c[1].copy(d,28+c[0].length),d}function Qd(t,e,r,n){if(n.length<28)throw new Error("Encrypted transfer chunk is truncated");let i=eu(t,e),s=n.subarray(0,12),o=n.subarray(12,28),c=n.subarray(28),l=ry("aes-256-gcm",i,s);l.setAAD(Buffer.from(`${e}:${r}`,"utf8")),l.setAuthTag(o);let d=[l.update(c),l.final()],u=Buffer.allocUnsafe(d[0].length+d[1].length);return d[0].copy(u,0),d[1].copy(u,d[0].length),u}function fr(t,e,r,n){let i=Buffer.from(Kd("sha256",Buffer.from(t,"base64url"),Buffer.from(e,"utf8"),Buffer.from("interscale-transfer-auth-v1","utf8"),32));return iy("sha256",i).update(`${String(r).toUpperCase()}
90
+ ${n}`,"utf8").digest("base64url")}function eu(t,e){return Buffer.from(Kd("sha256",Buffer.from(t,"base64url"),Buffer.from(e,"utf8"),Buffer.from("interscale-transfer-v1","utf8"),32))}var Wn=C(()=>{a(Yd,"sha256");a(Xd,"constantTimeTextEqual");a(Zd,"encryptTransferChunk");a(Qd,"decryptTransferChunk");a(fr,"transferRequestProof");a(eu,"deriveTransferKey")});import{randomBytes as ay}from"node:crypto";import{networkInterfaces as cy}from"node:os";function ly(t,e,r,n){return fr(t,e,"ROUTE_RESPONSE",JSON.stringify([r,n]))}function os(t,e){mt.get(t)?.route===Ge(e)&&mt.delete(t)}async function as(t,{nodeId:e,id:r,token:n,kind:i="transfers",signal:s}={}){if(t.length===0||!e||!r||!n)return t;s?.throwIfAborted();let o=JSON.stringify(cy()),c=mt.get(e),l=[...t];c&&c.expires>Date.now()&&c.network===o?l.sort((L,ie)=>+(Ge(ie)===c.route)-+(Ge(L)===c.route)):mt.delete(e);let d=new AbortController,u=s?AbortSignal.any([s,d.signal]):d.signal,h=new Set,f=new Set,p=new Set,m=0,_=0,g=1,y=null,w,x=new Promise(L=>{w=L}),v=a(async L=>{let ie=ay(24).toString("base64url"),se=`/v1/${i}/${encodeURIComponent(r)}/probe/${ie}`,Qt=new AbortController,F=setTimeout(()=>Qt.abort(),750);try{let rl=await ft(`${L.url.replace(/\/$/,"")}${se}`,{headers:{authorization:`Interscale ${fr(n,r,"GET",se)}`},signal:AbortSignal.any([u,Qt.signal]),localAddress:L.localAddress,maxResponseBytes:4096});if(f.add(Ge(L)),!rl.ok)return;let so;try{so=await rl.json()}catch{h.add(Ge(L));return}if(so?.node_id!==e||!Xd(String(so.proof||""),ly(n,r,e,ie))){h.add(Ge(L));return}!y&&!u.aborted&&(y=L,w())}catch{u.aborted||h.add(Ge(L))}finally{clearTimeout(F)}},"probe"),k=a(()=>{for(;!u.aborted&&!y&&_<g&&m<l.length;){let L=l[m++];_++;let ie=v(L).finally(()=>{_--,p.delete(ie),k(),!_&&m===l.length&&w()});p.add(ie)}},"launch"),B=a(()=>w(),"abort");u.addEventListener("abort",B,{once:!0});let ce=setTimeout(()=>w(),2e3),ye=setTimeout(()=>{g=3,k()},150);try{k(),await x}finally{d.abort(),clearTimeout(ce),clearTimeout(ye),await Promise.allSettled([...p]),u.removeEventListener("abort",B)}return s?.throwIfAborted(),y?(mt.size>=256&&mt.delete(mt.keys().next().value),mt.set(e,{route:Ge(y),expires:Date.now()+3e5,network:o})):mt.delete(e),[...y?[y]:[],...l.filter(L=>L!==y&&!h.has(Ge(L))&&(y||f.has(Ge(L))))]}var mt,Ge,ba=C(()=>{ss();Wn();a(ly,"routeResponseProof");mt=new Map,Ge=a(t=>JSON.stringify([t.url,t.localAddress||""]),"routeKey");a(os,"invalidateRoute");a(as,"prioritizeDirectRoutes")});async function Hn(t,e,r,n){if(n?.throwIfAborted(),!Number.isFinite(e)||e<1)throw new RangeError("Transfer concurrency must be a positive finite number");let i=[...t],s=Math.max(1,Math.min(16,Math.floor(e))),o=new AbortController,c=n?AbortSignal.any([n,o.signal]):o.signal,l;if(await Promise.all(Array.from({length:Math.min(s,i.length)},async()=>{for(;!l&&i.length>0;)try{c.throwIfAborted(),await r(i.shift(),c)}catch(d){l||(l=d,o.abort(d))}})),l)throw l;n?.throwIfAborted()}var va=C(()=>{a(Hn,"parallelTransferMap")});import{constants as tu}from"node:fs";import{open as dy}from"node:fs/promises";function ru(t){return dy(t,tu.O_RDWR|tu.O_CREAT,384)}async function Gn(t,e,r=0){let n=0;for(;n<e.length;){let{bytesRead:i}=await t.read(e,n,e.length-n,r+n);if(!i)throw Object.assign(new Error("Source ended before the manifest's expected byte count"),{code:"source_changed"});n+=i}return e}async function nu(t,e,r=0){let n=0;for(;n<e.length;){let{bytesWritten:i}=await t.write(e,n,e.length-n,r+n);if(!i)throw Object.assign(new Error("File write made no progress"),{code:"write_stalled"});n+=i}}var Ea=C(()=>{a(ru,"openPartialFile");a(Gn,"readExactly");a(nu,"writeExactly")});import{readFileSync as uy}from"node:fs";var Vn,Gr,hy,tx,iu,cs,rx,su,nx,Jn,ou,ve=C(()=>{Vn=JSON.parse(uy(new URL("../package.json",import.meta.url),"utf8")).version,Gr="interscale/v1",hy=1024*1024,tx=48*1024,iu=32,cs=64*1024*1024,rx=4*1024*1024,su="claude",nx=576*60*60,Jn=new Set(["succeeded","failed","cancelled","rejected","expired","needs_review"]),ou={queued:new Set(["offered","cancelled","expired"]),offered:new Set(["accepted","cancel_requested","cancelled","rejected","expired"]),accepted:new Set(["running","cancel_requested","cancelled","failed","needs_review"]),running:new Set(["succeeded","cancel_requested","cancelled","failed","needs_review"]),cancel_requested:new Set(["cancelled","failed","needs_review"])}});function py(t){if(!Number.isSafeInteger(t)||t<1||t>cs)throw mr("Transfer chunk size must be between 1 byte and 64 MiB")}function Yn(t,{defaultKind:e}={}){if(!t||typeof t!="object"||Array.isArray(t))throw mr("Transfer manifest must be an object");let r=t.kind??e;if(!["file","directory-tar"].includes(r))throw mr("Transfer manifest has an unsupported kind");for(let n of["size","chunk_size","total_chunks"])if(!Number.isSafeInteger(t[n])||t[n]<(n==="size"?0:1))throw mr(`Transfer manifest has invalid ${n}`);if(py(t.chunk_size),t.total_chunks>au)throw mr(`Transfer exceeds ${au} chunks; use a larger chunk size or split the transfer`);if(t.total_chunks!==Math.max(1,Math.ceil(t.size/t.chunk_size)))throw mr("Transfer size and chunk count are inconsistent");if(typeof t.sha256!="string"||!/^[a-f0-9]{64}$/.test(t.sha256))throw mr("Transfer manifest has an invalid SHA-256");return{...t,kind:r}}var au,mr,Sa=C(()=>{ve();le();au=1e5,mr=a(t=>Object.assign(new R(400,"invalid_transfer_manifest",t),{terminal:!0}),"invalid");a(py,"validateTransferChunkSize");a(Yn,"validateTransferManifest")});import{createReadStream as fy}from"node:fs";import{mkdir as my}from"node:fs/promises";import{createHash as xa}from"node:crypto";import{dirname as _y}from"node:path";async function Ra(t,e,r,n={}){if(e=Yn(e),typeof n.fetchChunk!="function")throw new TypeError("A chunk transport is required");n.signal?.throwIfAborted(),r.setManifest(t.id,e);let i=r.get(t.id);await my(_y(i.part_path),{recursive:!0,mode:448});let s=await ru(i.part_path),o=new Set(i.received);try{await s.truncate(e.size);for(let d of o){Ta(n.signal);let u=i.chunk_hashes[d];(!Number.isSafeInteger(d)||d<0||d>=e.total_chunks||!u||await gy(s,d*e.chunk_size,cu(e,d),n.signal)!==u)&&(r.forgetChunk(i.id,d),o.delete(d))}let l=[];for(let d=0;d<e.total_chunks;d+=1)o.has(d)?n.onProgress?.({index:d,total:e.total_chunks,skipped:!0,route:n.route||"direct"}):l.push(d);await Hn(l,Number(n.concurrency||4),async(d,u)=>{u.throwIfAborted();let h=cu(e,d),f=await n.fetchChunk({index:d,expectedBytes:h+28,signal:u});if(!Buffer.isBuffer(f)||f.length!==h+28)throw new Error(`Encrypted result chunk ${d} does not match its manifest size`);let p=Qd(i.token,i.id,d,f);if(p.length!==h)throw new Error(`Result chunk ${d} has an invalid size`);u.throwIfAborted(),await nu(s,p,d*e.chunk_size),await s.sync(),r.markChunk(i.id,d,xa("sha256").update(p).digest("hex")),n.onProgress?.({index:d,total:e.total_chunks,bytes:p.length,skipped:!1,route:n.route||"direct"})},n.signal)}finally{await s.close()}Ta(n.signal);let c=await yy(i.part_path,n.signal);if(c!==e.sha256)throw new Error(`Downloaded result SHA-256 mismatch: expected ${e.sha256}, found ${c}`);return r.get(t.id)}async function gy(t,e,r,n){let i=xa("sha256"),s=Buffer.allocUnsafe(Math.min(1024*1024,Math.max(1,r)));for(let o=0;o<r;){Ta(n);let c=s.subarray(0,Math.min(s.length,r-o));await Gn(t,c,e+o),i.update(c),o+=c.length}return i.digest("hex")}function cu(t,e){return e===t.total_chunks-1?t.size-e*t.chunk_size:t.chunk_size}function yy(t,e){return new Promise((r,n)=>{let i=xa("sha256"),s=fy(t,{signal:e});s.on("error",n),s.on("data",o=>i.update(o)),s.on("end",()=>r(i.digest("hex")))})}function Ta(t){t?.throwIfAborted()}var lu=C(()=>{va();Wn();Ea();Sa();a(Ra,"receiveDownloadChunks");a(gy,"hashChunk");a(cu,"chunkLength");a(yy,"hashFile");a(Ta,"throwIfAborted")});var ls=A(ka=>{"use strict";Object.defineProperty(ka,"__esModule",{value:!0});ka.default=wy;var du=/[A-Z]/g;function uu(t){return t.toLowerCase()}a(uu,"toLowerCase");function wy(t,e){let r=t.replace(du,uu),n=e.replace(du,uu);return r===n}a(wy,"dnsEqual")});var Oa=A(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.DnsTxt=void 0;var ds=class{static{a(this,"DnsTxt")}constructor(e={}){this.binary=e?e.binary:!1}encode(e={}){return Object.entries(e).map(([r,n])=>{let i=`${r}=${n}`;return Buffer.from(i)})}decode(e){var r={};try{let i=e.toString().split(/=(.+)/),s=i[0],o=i[1];r[s]=o}catch{}return r}decodeAll(e){return e.filter(r=>r.length>1).map(r=>this.decode(r)).reduce((r,n)=>{var i=r;let[s]=Object.keys(n),[o]=Object.values(n);return i[s]=o,i},{})}};Kn.DnsTxt=ds;Kn.default=ds});var Ia=A(Vr=>{"use strict";Object.defineProperty(Vr,"__esModule",{value:!0});Vr.toType=Vr.toString=void 0;var hu=a(t=>"_"+t,"Prefix"),by=a(t=>["name","protocol","subtype"].includes(t),"AllowedProp"),vy=a(t=>{let e={name:t.name,protocol:t.protocol,subtype:t.subtype};return Object.entries(e).filter(([n,i])=>by(n)&&i!==void 0).reduce((n,[i,s])=>(typeof s==="object"?s.map(o=>n.push(hu(o))):n.push(hu(s)),n),[]).join(".")},"toString");Vr.toString=vy;var Ey=a(t=>{let e=t.split("."),r;for(let n in e)e[n][0]==="_"&&(e[n]=e[n].slice(1));return e.includes("sub")&&(r=e.shift(),e.shift()),{name:e.shift(),protocol:e.shift()||null,subtype:r}},"toType");Vr.toType=Ey});var Aa=A(_r=>{"use strict";var fu=_r&&_r.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(_r,"__esModule",{value:!0});_r.Service=void 0;var pu=fu(U("os")),Sy=fu(Oa()),Ty=U("events"),xy=Ia(),Jr=".local",us=class extends Ty.EventEmitter{static{a(this,"Service")}constructor(e,r,n){if(super(),this.start=r,this.stop=n,this.probe=!0,this.published=!1,this.activated=!1,this.destroyed=!1,this.txtService=new Sy.default,!e.name)throw new Error("ServiceConfig requires `name` property to be set");if(!e.type)throw new Error("ServiceConfig requires `type` property to be set");if(!e.port)throw new Error("ServiceConfig requires `port` property to be set");this.name=e.name.split(".").join("-"),this.protocol=e.protocol||"tcp",this.type=(0,xy.toString)({name:e.type,protocol:this.protocol}),this.port=e.port,this.host=e.host||pu.default.hostname(),this.fqdn=`${this.name}.${this.type}${Jr}`,this.txt=e.txt,this.subtypes=e.subtypes,this.disableIPv6=!!e.disableIPv6}records(){var e=[this.RecordPTR(this),this.RecordSRV(this),this.RecordTXT(this),this.RecordServicePTR(this)];for(let n of this.subtypes||[])e.push(this.RecordSubtypePTR(this,n));let r=Object.values(pu.default.networkInterfaces());for(let n of r){let i=n;for(let s of i)if(!(s.internal||s.mac==="00:00:00:00:00:00"))switch(s.family){case"IPv4":e.push(this.RecordA(this,s.address));break;case"IPv6":if(this.disableIPv6)break;e.push(this.RecordAAAA(this,s.address));break}}return e}RecordPTR(e){return{name:`${e.type}${Jr}`,type:"PTR",ttl:28800,data:e.fqdn}}RecordServicePTR(e){return{name:`_services._dns-sd._udp${Jr}`,type:"PTR",ttl:120,data:`${e.type}${Jr}`}}RecordSubtypePTR(e,r){return{name:`_${r}._sub.${e.type}${Jr}`,type:"PTR",ttl:28800,data:`${e.name}.${e.type}${Jr}`}}RecordSRV(e){return{name:e.fqdn,type:"SRV",ttl:120,data:{port:e.port,target:e.host}}}RecordTXT(e){return{name:e.fqdn,type:"TXT",ttl:4500,data:this.txtService.encode(e.txt)}}RecordA(e,r){return{name:e.host,type:"A",ttl:120,data:r}}RecordAAAA(e,r){return{name:e.host,type:"AAAA",ttl:120,data:r}}};_r.Service=us;_r.default=us});var _u=A(gr=>{"use strict";var mu=gr&&gr.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(gr,"__esModule",{value:!0});gr.Registry=void 0;var Ry=mu(ls()),Na=mu(Aa()),ky=3600*1e3,Oy=3,Iy=a(function(){},"noop"),hs=class{static{a(this,"Registry")}constructor(e){this.services=[],this.server=e}publish(e){let r=e.probe!==!1,n=new Na.default(e,i.bind(null,this),s.bind(null,this));function i(o,{probe:c=r}={}){n.activated||(n.activated=!0,o.services.push(n),n instanceof Na.default&&(c?o.probe(o.server.mdns,n,l=>{if(l){n.stop!==void 0&&n.stop(),console.log(new Error("Service name is already in use on the network"));return}o.announce(o.server,n)}):o.announce(o.server,n)))}a(i,"start");function s(o,c){if(c||(c=Iy),!n.activated||!(n instanceof Na.default))return process.nextTick(c);o.teardown(o.server,n,c);let l=o.services.indexOf(n);l!==-1&&o.services.splice(l,1)}return a(s,"stop"),n.start(),n}unpublishAll(e){this.teardown(this.server,this.services,e),this.services=[]}destroy(){this.services.map(e=>e.destroyed=!0)}probe(e,r,n){var i=!1,s=0,o;let c=a(()=>{!r.activated||r.destroyed||e.query(r.fqdn,"ANY",function(){i=!0,o=setTimeout(++s<3?c:u,250),o.unref()})},"send"),l=a(h=>{i&&(h.answers.some(d)||h.additionals.some(d))&&u(!0)},"onresponse"),d=a(h=>(0,Ry.default)(h.name,r.fqdn),"matchRR"),u=a(h=>{e.removeListener("response",l),clearTimeout(o),n(!!h)},"done");e.on("response",l),setTimeout(c,Math.random()*250)}announce(e,r){var n=1e3,i=r.records();e.register(i);let s=a(()=>{!r.activated||r.destroyed||e.mdns.respond(i,function(){r.published||(r.activated=!0,r.published=!0,r.emit("up")),n=n*Oy,n<ky&&!r.destroyed&&setTimeout(s,n).unref()})},"broadcast");s()}teardown(e,r,n){Array.isArray(r)||(r=[r]),r=r.filter(s=>s.activated);var i=r.flatMap(function(s){s.activated=!1;var o=s.records();return o.forEach(c=>{c.ttl=0}),o});if(i.length===0)return n&&process.nextTick(n);e.unregister(i),e.mdns.respond(i,function(){r.forEach(function(s){s.published=!1}),typeof n=="function"&&n.apply(null,arguments)})}};gr.Registry=hs;gr.default=hs});var gu=A(La=>{"use strict";La.toString=function(t){switch(t){case 1:return"A";case 10:return"NULL";case 28:return"AAAA";case 18:return"AFSDB";case 42:return"APL";case 257:return"CAA";case 60:return"CDNSKEY";case 59:return"CDS";case 37:return"CERT";case 5:return"CNAME";case 49:return"DHCID";case 32769:return"DLV";case 39:return"DNAME";case 48:return"DNSKEY";case 43:return"DS";case 55:return"HIP";case 13:return"HINFO";case 45:return"IPSECKEY";case 25:return"KEY";case 36:return"KX";case 29:return"LOC";case 15:return"MX";case 35:return"NAPTR";case 2:return"NS";case 47:return"NSEC";case 50:return"NSEC3";case 51:return"NSEC3PARAM";case 12:return"PTR";case 46:return"RRSIG";case 17:return"RP";case 24:return"SIG";case 6:return"SOA";case 99:return"SPF";case 33:return"SRV";case 44:return"SSHFP";case 32768:return"TA";case 249:return"TKEY";case 52:return"TLSA";case 250:return"TSIG";case 16:return"TXT";case 252:return"AXFR";case 251:return"IXFR";case 41:return"OPT";case 255:return"ANY"}return"UNKNOWN_"+t};La.toType=function(t){switch(t.toUpperCase()){case"A":return 1;case"NULL":return 10;case"AAAA":return 28;case"AFSDB":return 18;case"APL":return 42;case"CAA":return 257;case"CDNSKEY":return 60;case"CDS":return 59;case"CERT":return 37;case"CNAME":return 5;case"DHCID":return 49;case"DLV":return 32769;case"DNAME":return 39;case"DNSKEY":return 48;case"DS":return 43;case"HIP":return 55;case"HINFO":return 13;case"IPSECKEY":return 45;case"KEY":return 25;case"KX":return 36;case"LOC":return 29;case"MX":return 15;case"NAPTR":return 35;case"NS":return 2;case"NSEC":return 47;case"NSEC3":return 50;case"NSEC3PARAM":return 51;case"PTR":return 12;case"RRSIG":return 46;case"RP":return 17;case"SIG":return 24;case"SOA":return 6;case"SPF":return 99;case"SRV":return 33;case"SSHFP":return 44;case"TA":return 32768;case"TKEY":return 249;case"TLSA":return 52;case"TSIG":return 250;case"TXT":return 16;case"AXFR":return 252;case"IXFR":return 251;case"OPT":return 41;case"ANY":return 255;case"*":return 255}return t.toUpperCase().startsWith("UNKNOWN_")?parseInt(t.slice(8)):0}});var yu=A(Ca=>{"use strict";Ca.toString=function(t){switch(t){case 0:return"NOERROR";case 1:return"FORMERR";case 2:return"SERVFAIL";case 3:return"NXDOMAIN";case 4:return"NOTIMP";case 5:return"REFUSED";case 6:return"YXDOMAIN";case 7:return"YXRRSET";case 8:return"NXRRSET";case 9:return"NOTAUTH";case 10:return"NOTZONE";case 11:return"RCODE_11";case 12:return"RCODE_12";case 13:return"RCODE_13";case 14:return"RCODE_14";case 15:return"RCODE_15"}return"RCODE_"+t};Ca.toRcode=function(t){switch(t.toUpperCase()){case"NOERROR":return 0;case"FORMERR":return 1;case"SERVFAIL":return 2;case"NXDOMAIN":return 3;case"NOTIMP":return 4;case"REFUSED":return 5;case"YXDOMAIN":return 6;case"YXRRSET":return 7;case"NXRRSET":return 8;case"NOTAUTH":return 9;case"NOTZONE":return 10;case"RCODE_11":return 11;case"RCODE_12":return 12;case"RCODE_13":return 13;case"RCODE_14":return 14;case"RCODE_15":return 15}return 0}});var wu=A(Pa=>{"use strict";Pa.toString=function(t){switch(t){case 0:return"QUERY";case 1:return"IQUERY";case 2:return"STATUS";case 3:return"OPCODE_3";case 4:return"NOTIFY";case 5:return"UPDATE";case 6:return"OPCODE_6";case 7:return"OPCODE_7";case 8:return"OPCODE_8";case 9:return"OPCODE_9";case 10:return"OPCODE_10";case 11:return"OPCODE_11";case 12:return"OPCODE_12";case 13:return"OPCODE_13";case 14:return"OPCODE_14";case 15:return"OPCODE_15"}return"OPCODE_"+t};Pa.toOpcode=function(t){switch(t.toUpperCase()){case"QUERY":return 0;case"IQUERY":return 1;case"STATUS":return 2;case"OPCODE_3":return 3;case"NOTIFY":return 4;case"UPDATE":return 5;case"OPCODE_6":return 6;case"OPCODE_7":return 7;case"OPCODE_8":return 8;case"OPCODE_9":return 9;case"OPCODE_10":return 10;case"OPCODE_11":return 11;case"OPCODE_12":return 12;case"OPCODE_13":return 13;case"OPCODE_14":return 14;case"OPCODE_15":return 15}return 0}});var bu=A(Da=>{"use strict";Da.toString=function(t){switch(t){case 1:return"IN";case 2:return"CS";case 3:return"CH";case 4:return"HS";case 255:return"ANY"}return"UNKNOWN_"+t};Da.toClass=function(t){switch(t.toUpperCase()){case"IN":return 1;case"CS":return 2;case"CH":return 3;case"HS":return 4;case"ANY":return 255}return 0}});var vu=A(Ua=>{"use strict";Ua.toString=function(t){switch(t){case 1:return"LLQ";case 2:return"UL";case 3:return"NSID";case 5:return"DAU";case 6:return"DHU";case 7:return"N3U";case 8:return"CLIENT_SUBNET";case 9:return"EXPIRE";case 10:return"COOKIE";case 11:return"TCP_KEEPALIVE";case 12:return"PADDING";case 13:return"CHAIN";case 14:return"KEY_TAG";case 26946:return"DEVICEID"}return t<0?null:`OPTION_${t}`};Ua.toCode=function(t){if(typeof t=="number")return t;if(!t)return-1;switch(t.toUpperCase()){case"OPTION_0":return 0;case"LLQ":return 1;case"UL":return 2;case"NSID":return 3;case"OPTION_4":return 4;case"DAU":return 5;case"DHU":return 6;case"N3U":return 7;case"CLIENT_SUBNET":return 8;case"EXPIRE":return 9;case"COOKIE":return 10;case"TCP_KEEPALIVE":return 11;case"PADDING":return 12;case"CHAIN":return 13;case"KEY_TAG":return 14;case"DEVICEID":return 26946;case"OPTION_65535":return 65535}let e=t.match(/_(\d+)$/);return e?parseInt(e[1],10):-1}});var Tu=A((Su,Ba)=>{var Eu=(function(t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decode=h,t.encode=u,t.familyOf=d,t.name=void 0,t.sizeOf=l,t.v6=t.v4=void 0;let e=/^(\d{1,3}\.){3,3}\d{1,3}$/,r=4,n=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i,i=16,s={name:"v4",size:r,isFormat:a(f=>e.test(f),"isFormat"),encode(f,p,m){m=~~m,p=p||new Uint8Array(m+r);let _=f.length,g=0;for(let y=0;y<_;){let w=f.charCodeAt(y++);w===46?(p[m++]=g,g=0):g=g*10+(w-48)}return p[m]=g,p},decode(f,p){return p=~~p,`${f[p++]}.${f[p++]}.${f[p++]}.${f[p]}`}};t.v4=s;let o={name:"v6",size:i,isFormat:a(f=>f.length>0&&n.test(f),"isFormat"),encode(f,p,m){m=~~m;let _=m+i,g=-1,y=0,w=0,x=!0,v=!1;p=p||new Uint8Array(m+i);for(let k=0;k<f.length;k++){let B=f.charCodeAt(k);B===58?(x?g!==-1?(m<_&&(p[m]=0),m<_-1&&(p[m+1]=0),m+=2):m<_&&(g=m):(v===!0?(m<_&&(p[m]=w),m++):(m<_&&(p[m]=y>>8),m<_-1&&(p[m+1]=y&255),m+=2),y=0,w=0),x=!0,v=!1):B===46?(m<_&&(p[m]=w),m++,w=0,y=0,x=!1,v=!0):(x=!1,B>=97?B-=87:B>=65?B-=55:(B-=48,w=w*10+B),y=(y<<4)+B)}if(x===!1)v===!0?(m<_&&(p[m]=w),m++):(m<_&&(p[m]=y>>8),m<_-1&&(p[m+1]=y&255),m+=2);else if(g===0)m<_&&(p[m]=0),m<_-1&&(p[m+1]=0),m+=2;else if(g!==-1){m+=2;for(let k=Math.min(m-1,_-1);k>=g+2;k--)p[k]=p[k-2];p[g]=0,p[g+1]=0,g=m}if(g!==m&&g!==-1)for(m>_-2&&(m=_-2);_>g;)p[--_]=m<_&&m>g?p[--m]:0;else for(;m<_;)p[m++]=0;return p},decode(f,p){p=~~p;let m="";for(let _=0;_<i;_+=2)_!==0&&(m+=":"),m+=(f[p+_]<<8|f[p+_+1]).toString(16);return m.replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}};t.v6=o;let c="ip";t.name=c;function l(f){if(s.isFormat(f))return s.size;if(o.isFormat(f))return o.size;throw Error(`Invalid ip address: ${f}`)}a(l,"sizeOf");function d(f){return l(f)===s.size?1:2}a(d,"familyOf");function u(f,p,m){m=~~m;let _=l(f);return typeof p=="function"&&(p=p(m+_)),_===s.size?s.encode(f,p,m):o.encode(f,p,m)}a(u,"encode");function h(f,p,m){if(p=~~p,m=m||f.length-p,m===s.size)return s.decode(f,p,m);if(m===o.size)return o.decode(f,p,m);throw Error(`Invalid buffer size needs to be ${s.size} for v4 or ${o.size} for v6.`)}return a(h,"decode"),"default"in t?t.default:t})({});typeof define=="function"&&define.amd?define([],function(){return Eu}):typeof Ba=="object"&&typeof Su=="object"&&(Ba.exports=Eu)});var ku=A(E=>{"use strict";var S=U("buffer").Buffer,xt=gu(),Ay=yu(),Ny=wu(),fs=bu(),ja=vu(),yr=Tu(),Ly=0,xu=32768,Ma=32768,Cy=~Ma,Ru=32768,Py=~Ru,b=E.name={};b.encode=function(t,e,r,{mail:n=!1}={}){e||(e=S.alloc(b.encodingLength(t))),r||(r=0);let i=r,s=t.replace(/^\.|\.$/gm,"");if(s.length){let o=[];if(n){let c="";s.split(".").forEach(l=>{l.endsWith("\\")?c+=(c.length?".":"")+l.slice(0,-1):o.length===0&&c.length?o.push(c+"."+l):o.push(l)})}else o=s.split(".");for(let c=0;c<o.length;c++){let l=e.write(o[c],r+1);e[r]=l,r+=l+1}}return e[r++]=0,b.encode.bytes=r-i,e};b.encode.bytes=0;b.decode=function(t,e,{mail:r=!1}={}){e||(e=0);let n=[],i=e,s=0,o=0,c=!1;for(;;){if(e>=t.length)throw new Error("Cannot decode name (buffer overflow)");let l=t[e++];if(o+=c?0:1,l===0)break;if((l&192)===0){if(e+l>t.length)throw new Error("Cannot decode name (buffer overflow)");if(s+=l+1,s>254)throw new Error("Cannot decode name (name too long)");let d=t.toString("utf-8",e,e+l);r&&(d=d.replace(/\./g,"\\.")),n.push(d),e+=l,o+=c?0:l}else if((l&192)===192){if(e+1>t.length)throw new Error("Cannot decode name (buffer overflow)");let d=t.readUInt16BE(e-1)-49152;if(d>=i)throw new Error("Cannot decode name (bad pointer)");e=d,i=d,o+=c?0:1,c=!0}else throw new Error("Cannot decode name (bad label)")}return b.decode.bytes=o,n.length===0?".":n.join(".")};b.decode.bytes=0;b.encodingLength=function(t){return t==="."||t===".."?1:S.byteLength(t.replace(/^\.|\.$/gm,""))+2};var I={};I.encode=function(t,e,r){e||(e=S.alloc(I.encodingLength(t))),r||(r=0);let n=e.write(t,r+1);return e[r]=n,I.encode.bytes=n+1,e};I.encode.bytes=0;I.decode=function(t,e){e||(e=0);let r=t[e],n=t.toString("utf-8",e+1,e+1+r);return I.decode.bytes=r+1,n};I.decode.bytes=0;I.encodingLength=function(t){return S.byteLength(t)+1};var Pe={};Pe.encode=function(t,e,r){e||(e=Pe.encodingLength(t)),r||(r=0);let n=(t.flags||0)&32767,i=t.type==="response"?xu:Ly;return e.writeUInt16BE(t.id||0,r),e.writeUInt16BE(n|i,r+2),e.writeUInt16BE(t.questions.length,r+4),e.writeUInt16BE(t.answers.length,r+6),e.writeUInt16BE(t.authorities.length,r+8),e.writeUInt16BE(t.additionals.length,r+10),e};Pe.encode.bytes=12;Pe.decode=function(t,e){if(e||(e=0),t.length<12)throw new Error("Header must be 12 bytes");let r=t.readUInt16BE(e+2);return{id:t.readUInt16BE(e),type:r&xu?"response":"query",flags:r&32767,flag_qr:(r>>15&1)===1,opcode:Ny.toString(r>>11&15),flag_aa:(r>>10&1)===1,flag_tc:(r>>9&1)===1,flag_rd:(r>>8&1)===1,flag_ra:(r>>7&1)===1,flag_z:(r>>6&1)===1,flag_ad:(r>>5&1)===1,flag_cd:(r>>4&1)===1,rcode:Ay.toString(r&15),questions:new Array(t.readUInt16BE(e+4)),answers:new Array(t.readUInt16BE(e+6)),authorities:new Array(t.readUInt16BE(e+8)),additionals:new Array(t.readUInt16BE(e+10))}};Pe.decode.bytes=12;Pe.encodingLength=function(){return 12};var _t=E.unknown={};_t.encode=function(t,e,r){return e||(e=S.alloc(_t.encodingLength(t))),r||(r=0),e.writeUInt16BE(t.length,r),t.copy(e,r+2),_t.encode.bytes=t.length+2,e};_t.encode.bytes=0;_t.decode=function(t,e){e||(e=0);let r=t.readUInt16BE(e),n=t.slice(e+2,e+2+r);return _t.decode.bytes=r+2,n};_t.decode.bytes=0;_t.encodingLength=function(t){return t.length+2};var gt=E.ns={};gt.encode=function(t,e,r){return e||(e=S.alloc(gt.encodingLength(t))),r||(r=0),b.encode(t,e,r+2),e.writeUInt16BE(b.encode.bytes,r),gt.encode.bytes=b.encode.bytes+2,e};gt.encode.bytes=0;gt.decode=function(t,e){e||(e=0);let r=t.readUInt16BE(e),n=b.decode(t,e+2);return gt.decode.bytes=r+2,n};gt.decode.bytes=0;gt.encodingLength=function(t){return b.encodingLength(t)+2};var yt=E.soa={};yt.encode=function(t,e,r){e||(e=S.alloc(yt.encodingLength(t))),r||(r=0);let n=r;return r+=2,b.encode(t.mname,e,r),r+=b.encode.bytes,b.encode(t.rname,e,r,{mail:!0}),r+=b.encode.bytes,e.writeUInt32BE(t.serial||0,r),r+=4,e.writeUInt32BE(t.refresh||0,r),r+=4,e.writeUInt32BE(t.retry||0,r),r+=4,e.writeUInt32BE(t.expire||0,r),r+=4,e.writeUInt32BE(t.minimum||0,r),r+=4,e.writeUInt16BE(r-n-2,n),yt.encode.bytes=r-n,e};yt.encode.bytes=0;yt.decode=function(t,e){e||(e=0);let r=e,n={};return e+=2,n.mname=b.decode(t,e),e+=b.decode.bytes,n.rname=b.decode(t,e,{mail:!0}),e+=b.decode.bytes,n.serial=t.readUInt32BE(e),e+=4,n.refresh=t.readUInt32BE(e),e+=4,n.retry=t.readUInt32BE(e),e+=4,n.expire=t.readUInt32BE(e),e+=4,n.minimum=t.readUInt32BE(e),e+=4,yt.decode.bytes=e-r,n};yt.decode.bytes=0;yt.encodingLength=function(t){return 22+b.encodingLength(t.mname)+b.encodingLength(t.rname)};var wt=E.txt={};wt.encode=function(t,e,r){Array.isArray(t)||(t=[t]);for(let i=0;i<t.length;i++)if(typeof t[i]=="string"&&(t[i]=S.from(t[i])),!S.isBuffer(t[i]))throw new Error("Must be a Buffer");e||(e=S.alloc(wt.encodingLength(t))),r||(r=0);let n=r;return r+=2,t.forEach(function(i){e[r++]=i.length,i.copy(e,r,0,i.length),r+=i.length}),e.writeUInt16BE(r-n-2,n),wt.encode.bytes=r-n,e};wt.encode.bytes=0;wt.decode=function(t,e){e||(e=0);let r=e,n=t.readUInt16BE(e);e+=2;let i=[];for(;n>0;){let s=t[e++];if(--n,n<s)throw new Error("Buffer overflow");i.push(t.slice(e,e+s)),e+=s,n-=s}return wt.decode.bytes=e-r,i};wt.decode.bytes=0;wt.encodingLength=function(t){Array.isArray(t)||(t=[t]);let e=2;return t.forEach(function(r){typeof r=="string"?e+=S.byteLength(r)+1:e+=r.length+1}),e};var bt=E.null={};bt.encode=function(t,e,r){e||(e=S.alloc(bt.encodingLength(t))),r||(r=0),typeof t=="string"&&(t=S.from(t)),t||(t=S.alloc(0));let n=r;r+=2;let i=t.length;return t.copy(e,r,0,i),r+=i,e.writeUInt16BE(r-n-2,n),bt.encode.bytes=r-n,e};bt.encode.bytes=0;bt.decode=function(t,e){e||(e=0);let r=e,n=t.readUInt16BE(e);e+=2;let i=t.slice(e,e+n);return e+=n,bt.decode.bytes=e-r,i};bt.decode.bytes=0;bt.encodingLength=function(t){return t?(S.isBuffer(t)?t.length:S.byteLength(t))+2:2};var vt=E.hinfo={};vt.encode=function(t,e,r){e||(e=S.alloc(vt.encodingLength(t))),r||(r=0);let n=r;return r+=2,I.encode(t.cpu,e,r),r+=I.encode.bytes,I.encode(t.os,e,r),r+=I.encode.bytes,e.writeUInt16BE(r-n-2,n),vt.encode.bytes=r-n,e};vt.encode.bytes=0;vt.decode=function(t,e){e||(e=0);let r=e,n={};return e+=2,n.cpu=I.decode(t,e),e+=I.decode.bytes,n.os=I.decode(t,e),e+=I.decode.bytes,vt.decode.bytes=e-r,n};vt.decode.bytes=0;vt.encodingLength=function(t){return I.encodingLength(t.cpu)+I.encodingLength(t.os)+2};var Le=E.ptr={},Dy=E.cname=Le,Uy=E.dname=Le;Le.encode=function(t,e,r){return e||(e=S.alloc(Le.encodingLength(t))),r||(r=0),b.encode(t,e,r+2),e.writeUInt16BE(b.encode.bytes,r),Le.encode.bytes=b.encode.bytes+2,e};Le.encode.bytes=0;Le.decode=function(t,e){e||(e=0);let r=b.decode(t,e+2);return Le.decode.bytes=b.decode.bytes+2,r};Le.decode.bytes=0;Le.encodingLength=function(t){return b.encodingLength(t)+2};var Et=E.srv={};Et.encode=function(t,e,r){e||(e=S.alloc(Et.encodingLength(t))),r||(r=0),e.writeUInt16BE(t.priority||0,r+2),e.writeUInt16BE(t.weight||0,r+4),e.writeUInt16BE(t.port||0,r+6),b.encode(t.target,e,r+8);let n=b.encode.bytes+6;return e.writeUInt16BE(n,r),Et.encode.bytes=n+2,e};Et.encode.bytes=0;Et.decode=function(t,e){e||(e=0);let r=t.readUInt16BE(e),n={};return n.priority=t.readUInt16BE(e+2),n.weight=t.readUInt16BE(e+4),n.port=t.readUInt16BE(e+6),n.target=b.decode(t,e+8),Et.decode.bytes=r+2,n};Et.decode.bytes=0;Et.encodingLength=function(t){return 8+b.encodingLength(t.target)};var pe=E.caa={};pe.ISSUER_CRITICAL=128;pe.encode=function(t,e,r){let n=pe.encodingLength(t);return e||(e=S.alloc(pe.encodingLength(t))),r||(r=0),t.issuerCritical&&(t.flags=pe.ISSUER_CRITICAL),e.writeUInt16BE(n-2,r),r+=2,e.writeUInt8(t.flags||0,r),r+=1,I.encode(t.tag,e,r),r+=I.encode.bytes,e.write(t.value,r),r+=S.byteLength(t.value),pe.encode.bytes=n,e};pe.encode.bytes=0;pe.decode=function(t,e){e||(e=0);let r=t.readUInt16BE(e);e+=2;let n=e,i={};return i.flags=t.readUInt8(e),e+=1,i.tag=I.decode(t,e),e+=I.decode.bytes,i.value=t.toString("utf-8",e,n+r),i.issuerCritical=!!(i.flags&pe.ISSUER_CRITICAL),pe.decode.bytes=r+2,i};pe.decode.bytes=0;pe.encodingLength=function(t){return I.encodingLength(t.tag)+I.encodingLength(t.value)+2};var Gt=E.mx={};Gt.encode=function(t,e,r){e||(e=S.alloc(Gt.encodingLength(t))),r||(r=0);let n=r;return r+=2,e.writeUInt16BE(t.preference||0,r),r+=2,b.encode(t.exchange,e,r),r+=b.encode.bytes,e.writeUInt16BE(r-n-2,n),Gt.encode.bytes=r-n,e};Gt.encode.bytes=0;Gt.decode=function(t,e){e||(e=0);let r=e,n={};return e+=2,n.preference=t.readUInt16BE(e),e+=2,n.exchange=b.decode(t,e),e+=b.decode.bytes,Gt.decode.bytes=e-r,n};Gt.encodingLength=function(t){return 4+b.encodingLength(t.exchange)};var St=E.a={};St.encode=function(t,e,r){return e||(e=S.alloc(St.encodingLength(t))),r||(r=0),e.writeUInt16BE(4,r),r+=2,yr.v4.encode(t,e,r),St.encode.bytes=6,e};St.encode.bytes=0;St.decode=function(t,e){e||(e=0),e+=2;let r=yr.v4.decode(t,e);return St.decode.bytes=6,r};St.decode.bytes=0;St.encodingLength=function(){return 6};var Tt=E.aaaa={};Tt.encode=function(t,e,r){return e||(e=S.alloc(Tt.encodingLength(t))),r||(r=0),e.writeUInt16BE(16,r),r+=2,yr.v6.encode(t,e,r),Tt.encode.bytes=18,e};Tt.encode.bytes=0;Tt.decode=function(t,e){e||(e=0),e+=2;let r=yr.v6.decode(t,e);return Tt.decode.bytes=18,r};Tt.decode.bytes=0;Tt.encodingLength=function(){return 18};var ae=E.option={};ae.encode=function(t,e,r){e||(e=S.alloc(ae.encodingLength(t))),r||(r=0);let n=r,i=ja.toCode(t.code);if(e.writeUInt16BE(i,r),r+=2,t.data)e.writeUInt16BE(t.data.length,r),r+=2,t.data.copy(e,r),r+=t.data.length;else switch(i){case 8:let s=t.sourcePrefixLength||0,o=t.family||yr.familyOf(t.ip),c=yr.encode(t.ip,S.alloc),l=Math.ceil(s/8);e.writeUInt16BE(l+4,r),r+=2,e.writeUInt16BE(o,r),r+=2,e.writeUInt8(s,r++),e.writeUInt8(t.scopePrefixLength||0,r++),c.copy(e,r,0,l),r+=l;break;case 11:t.timeout?(e.writeUInt16BE(2,r),r+=2,e.writeUInt16BE(t.timeout,r),r+=2):(e.writeUInt16BE(0,r),r+=2);break;case 12:let d=t.length||0;e.writeUInt16BE(d,r),r+=2,e.fill(0,r,r+d),r+=d;break;case 14:let u=t.tags.length*2;e.writeUInt16BE(u,r),r+=2;for(let h of t.tags)e.writeUInt16BE(h,r),r+=2;break;default:throw new Error(`Unknown roption code: ${t.code}`)}return ae.encode.bytes=r-n,e};ae.encode.bytes=0;ae.decode=function(t,e){e||(e=0);let r={};r.code=t.readUInt16BE(e),r.type=ja.toString(r.code),e+=2;let n=t.readUInt16BE(e);switch(e+=2,r.data=t.slice(e,e+n),r.code){case 8:r.family=t.readUInt16BE(e),e+=2,r.sourcePrefixLength=t.readUInt8(e++),r.scopePrefixLength=t.readUInt8(e++);let i=S.alloc(r.family===1?4:16);t.copy(i,0,e,e+n-4),r.ip=yr.decode(i);break;case 11:n>0&&(r.timeout=t.readUInt16BE(e),e+=2);break;case 14:r.tags=[];for(let s=0;s<n;s+=2)r.tags.push(t.readUInt16BE(e)),e+=2}return ae.decode.bytes=n+4,r};ae.decode.bytes=0;ae.encodingLength=function(t){if(t.data)return t.data.length+4;switch(ja.toCode(t.code)){case 8:let r=t.sourcePrefixLength||0;return Math.ceil(r/8)+8;case 11:return typeof t.timeout=="number"?6:4;case 12:return t.length+4;case 14:return 4+t.tags.length*2}throw new Error(`Unknown roption code: ${t.code}`)};var me=E.opt={};me.encode=function(t,e,r){e||(e=S.alloc(me.encodingLength(t))),r||(r=0);let n=r,i=Yr(t,ae);return e.writeUInt16BE(i,r),r=Xn(t,ae,e,r+2),me.encode.bytes=r-n,e};me.encode.bytes=0;me.decode=function(t,e){e||(e=0);let r=e,n=[],i=t.readUInt16BE(e);e+=2;let s=0;for(;i>0;)n[s++]=ae.decode(t,e),e+=ae.decode.bytes,i-=ae.decode.bytes;return me.decode.bytes=e-r,n};me.decode.bytes=0;me.encodingLength=function(t){return 2+Yr(t||[],ae)};var re=E.dnskey={};re.PROTOCOL_DNSSEC=3;re.ZONE_KEY=128;re.SECURE_ENTRYPOINT=32768;re.encode=function(t,e,r){e||(e=S.alloc(re.encodingLength(t))),r||(r=0);let n=r,i=t.key;if(!S.isBuffer(i))throw new Error("Key must be a Buffer");return r+=2,e.writeUInt16BE(t.flags,r),r+=2,e.writeUInt8(re.PROTOCOL_DNSSEC,r),r+=1,e.writeUInt8(t.algorithm,r),r+=1,i.copy(e,r,0,i.length),r+=i.length,re.encode.bytes=r-n,e.writeUInt16BE(re.encode.bytes-2,n),e};re.encode.bytes=0;re.decode=function(t,e){e||(e=0);let r=e;var n={},i=t.readUInt16BE(e);if(e+=2,n.flags=t.readUInt16BE(e),e+=2,t.readUInt8(e)!==re.PROTOCOL_DNSSEC)throw new Error("Protocol must be 3");return e+=1,n.algorithm=t.readUInt8(e),e+=1,n.key=t.slice(e,r+i+2),e+=n.key.length,re.decode.bytes=e-r,n};re.decode.bytes=0;re.encodingLength=function(t){return 6+S.byteLength(t.key)};var Ve=E.rrsig={};Ve.encode=function(t,e,r){e||(e=S.alloc(Ve.encodingLength(t))),r||(r=0);let n=r,i=t.signature;if(!S.isBuffer(i))throw new Error("Signature must be a Buffer");return r+=2,e.writeUInt16BE(xt.toType(t.typeCovered),r),r+=2,e.writeUInt8(t.algorithm,r),r+=1,e.writeUInt8(t.labels,r),r+=1,e.writeUInt32BE(t.originalTTL,r),r+=4,e.writeUInt32BE(t.expiration,r),r+=4,e.writeUInt32BE(t.inception,r),r+=4,e.writeUInt16BE(t.keyTag,r),r+=2,b.encode(t.signersName,e,r),r+=b.encode.bytes,i.copy(e,r,0,i.length),r+=i.length,Ve.encode.bytes=r-n,e.writeUInt16BE(Ve.encode.bytes-2,n),e};Ve.encode.bytes=0;Ve.decode=function(t,e){e||(e=0);let r=e;var n={},i=t.readUInt16BE(e);return e+=2,n.typeCovered=xt.toString(t.readUInt16BE(e)),e+=2,n.algorithm=t.readUInt8(e),e+=1,n.labels=t.readUInt8(e),e+=1,n.originalTTL=t.readUInt32BE(e),e+=4,n.expiration=t.readUInt32BE(e),e+=4,n.inception=t.readUInt32BE(e),e+=4,n.keyTag=t.readUInt16BE(e),e+=2,n.signersName=b.decode(t,e),e+=b.decode.bytes,n.signature=t.slice(e,r+i+2),e+=n.signature.length,Ve.decode.bytes=e-r,n};Ve.decode.bytes=0;Ve.encodingLength=function(t){return 20+b.encodingLength(t.signersName)+S.byteLength(t.signature)};var Je=E.rp={};Je.encode=function(t,e,r){e||(e=S.alloc(Je.encodingLength(t))),r||(r=0);let n=r;return r+=2,b.encode(t.mbox||".",e,r,{mail:!0}),r+=b.encode.bytes,b.encode(t.txt||".",e,r),r+=b.encode.bytes,Je.encode.bytes=r-n,e.writeUInt16BE(Je.encode.bytes-2,n),e};Je.encode.bytes=0;Je.decode=function(t,e){e||(e=0);let r=e,n={};return e+=2,n.mbox=b.decode(t,e,{mail:!0})||".",e+=b.decode.bytes,n.txt=b.decode(t,e)||".",e+=b.decode.bytes,Je.decode.bytes=e-r,n};Je.decode.bytes=0;Je.encodingLength=function(t){return 2+b.encodingLength(t.mbox||".")+b.encodingLength(t.txt||".")};var X={};X.encode=function(t,e,r){e||(e=S.alloc(X.encodingLength(t))),r||(r=0);let n=r;for(var i=[],s=0;s<t.length;s++){var o=xt.toType(t[s]);i[o>>8]===void 0&&(i[o>>8]=[]),i[o>>8][o>>3&31]|=1<<7-(o&7)}for(s=0;s<i.length;s++)if(i[s]!==void 0){var c=S.from(i[s]);e.writeUInt8(s,r),r+=1,e.writeUInt8(c.length,r),r+=1,c.copy(e,r),r+=c.length}return X.encode.bytes=r-n,e};X.encode.bytes=0;X.decode=function(t,e,r){e||(e=0);let n=e;for(var i=[];e-n<r;){var s=t.readUInt8(e);e+=1;var o=t.readUInt8(e);e+=1;for(var c=0;c<o;c++)for(var l=t.readUInt8(e+c),d=0;d<8;d++)if(l&1<<7-d){var u=xt.toString(s<<8|c<<3|d);i.push(u)}e+=o}return X.decode.bytes=e-n,i};X.decode.bytes=0;X.encodingLength=function(t){for(var e=[],r=0;r<t.length;r++){var n=xt.toType(t[r]);e[n>>8]=Math.max(e[n>>8]||0,n&255)}var i=0;for(r=0;r<e.length;r++)e[r]!==void 0&&(i+=2+Math.ceil((e[r]+1)/8));return i};var Ye=E.nsec={};Ye.encode=function(t,e,r){e||(e=S.alloc(Ye.encodingLength(t))),r||(r=0);let n=r;return r+=2,b.encode(t.nextDomain,e,r),r+=b.encode.bytes,X.encode(t.rrtypes,e,r),r+=X.encode.bytes,Ye.encode.bytes=r-n,e.writeUInt16BE(Ye.encode.bytes-2,n),e};Ye.encode.bytes=0;Ye.decode=function(t,e){e||(e=0);let r=e;var n={},i=t.readUInt16BE(e);return e+=2,n.nextDomain=b.decode(t,e),e+=b.decode.bytes,n.rrtypes=X.decode(t,e,i-(e-r)),e+=X.decode.bytes,Ye.decode.bytes=e-r,n};Ye.decode.bytes=0;Ye.encodingLength=function(t){return 2+b.encodingLength(t.nextDomain)+X.encodingLength(t.rrtypes)};var Ke=E.nsec3={};Ke.encode=function(t,e,r){e||(e=S.alloc(Ke.encodingLength(t))),r||(r=0);let n=r,i=t.salt;if(!S.isBuffer(i))throw new Error("salt must be a Buffer");let s=t.nextDomain;if(!S.isBuffer(s))throw new Error("nextDomain must be a Buffer");return r+=2,e.writeUInt8(t.algorithm,r),r+=1,e.writeUInt8(t.flags,r),r+=1,e.writeUInt16BE(t.iterations,r),r+=2,e.writeUInt8(i.length,r),r+=1,i.copy(e,r,0,i.length),r+=i.length,e.writeUInt8(s.length,r),r+=1,s.copy(e,r,0,s.length),r+=s.length,X.encode(t.rrtypes,e,r),r+=X.encode.bytes,Ke.encode.bytes=r-n,e.writeUInt16BE(Ke.encode.bytes-2,n),e};Ke.encode.bytes=0;Ke.decode=function(t,e){e||(e=0);let r=e;var n={},i=t.readUInt16BE(e);e+=2,n.algorithm=t.readUInt8(e),e+=1,n.flags=t.readUInt8(e),e+=1,n.iterations=t.readUInt16BE(e),e+=2;let s=t.readUInt8(e);e+=1,n.salt=t.slice(e,e+s),e+=s;let o=t.readUInt8(e);return e+=1,n.nextDomain=t.slice(e,e+o),e+=o,n.rrtypes=X.decode(t,e,i-(e-r)),e+=X.decode.bytes,Ke.decode.bytes=e-r,n};Ke.decode.bytes=0;Ke.encodingLength=function(t){return 8+t.salt.length+t.nextDomain.length+X.encodingLength(t.rrtypes)};var Xe=E.ds={};Xe.encode=function(t,e,r){e||(e=S.alloc(Xe.encodingLength(t))),r||(r=0);let n=r,i=t.digest;if(!S.isBuffer(i))throw new Error("Digest must be a Buffer");return r+=2,e.writeUInt16BE(t.keyTag,r),r+=2,e.writeUInt8(t.algorithm,r),r+=1,e.writeUInt8(t.digestType,r),r+=1,i.copy(e,r,0,i.length),r+=i.length,Xe.encode.bytes=r-n,e.writeUInt16BE(Xe.encode.bytes-2,n),e};Xe.encode.bytes=0;Xe.decode=function(t,e){e||(e=0);let r=e;var n={},i=t.readUInt16BE(e);return e+=2,n.keyTag=t.readUInt16BE(e),e+=2,n.algorithm=t.readUInt8(e),e+=1,n.digestType=t.readUInt8(e),e+=1,n.digest=t.slice(e,r+i+2),e+=n.digest.length,Xe.decode.bytes=e-r,n};Xe.decode.bytes=0;Xe.encodingLength=function(t){return 6+S.byteLength(t.digest)};var fe=E.sshfp={};fe.getFingerprintLengthForHashType=a(function(e){switch(e){case 1:return 20;case 2:return 32}},"getFingerprintLengthForHashType");fe.encode=a(function(e,r,n){r||(r=S.alloc(fe.encodingLength(e))),n||(n=0);let i=n;n+=2,r[n]=e.algorithm,n+=1,r[n]=e.hash,n+=1;let s=S.from(e.fingerprint.toUpperCase(),"hex");if(s.length!==fe.getFingerprintLengthForHashType(e.hash))throw new Error("Invalid fingerprint length");return s.copy(r,n),n+=s.byteLength,fe.encode.bytes=n-i,r.writeUInt16BE(fe.encode.bytes-2,i),r},"encode");fe.encode.bytes=0;fe.decode=a(function(e,r){r||(r=0);let n=r,i={};r+=2,i.algorithm=e[r],r+=1,i.hash=e[r],r+=1;let s=fe.getFingerprintLengthForHashType(i.hash);return i.fingerprint=e.slice(r,r+s).toString("hex").toUpperCase(),r+=s,fe.decode.bytes=r-n,i},"decode");fe.decode.bytes=0;fe.encodingLength=function(t){return 4+S.from(t.fingerprint,"hex").byteLength};var Ze=E.naptr={};Ze.encode=function(t,e,r){e||(e=S.alloc(Ze.encodingLength(t))),r||(r=0);let n=r;return r+=2,e.writeUInt16BE(t.order||0,r),r+=2,e.writeUInt16BE(t.preference||0,r),r+=2,I.encode(t.flags,e,r),r+=I.encode.bytes,I.encode(t.services,e,r),r+=I.encode.bytes,I.encode(t.regexp,e,r),r+=I.encode.bytes,b.encode(t.replacement,e,r),r+=b.encode.bytes,Ze.encode.bytes=r-n,e.writeUInt16BE(Ze.encode.bytes-2,n),e};Ze.encode.bytes=0;Ze.decode=function(t,e){e||(e=0);let r=e,n={};return e+=2,n.order=t.readUInt16BE(e),e+=2,n.preference=t.readUInt16BE(e),e+=2,n.flags=I.decode(t,e),e+=I.decode.bytes,n.services=I.decode(t,e),e+=I.decode.bytes,n.regexp=I.decode(t,e),e+=I.decode.bytes,n.replacement=b.decode(t,e),e+=b.decode.bytes,Ze.decode.bytes=e-r,n};Ze.decode.bytes=0;Ze.encodingLength=function(t){return I.encodingLength(t.flags)+I.encodingLength(t.services)+I.encodingLength(t.regexp)+b.encodingLength(t.replacement)+6};var Qe=E.tlsa={};Qe.encode=function(t,e,r){e||(e=S.alloc(Qe.encodingLength(t))),r||(r=0);let n=r,i=t.certificate;if(!S.isBuffer(i))throw new Error("Certificate must be a Buffer");return r+=2,e.writeUInt8(t.usage,r),r+=1,e.writeUInt8(t.selector,r),r+=1,e.writeUInt8(t.matchingType,r),r+=1,i.copy(e,r,0,i.length),r+=i.length,Qe.encode.bytes=r-n,e.writeUInt16BE(Qe.encode.bytes-2,n),e};Qe.encode.bytes=0;Qe.decode=function(t,e){e||(e=0);let r=e,n={},i=t.readUInt16BE(e);return e+=2,n.usage=t.readUInt8(e),e+=1,n.selector=t.readUInt8(e),e+=1,n.matchingType=t.readUInt8(e),e+=1,n.certificate=t.slice(e,r+i+2),e+=n.certificate.length,Qe.decode.bytes=e-r,n};Qe.decode.bytes=0;Qe.encodingLength=function(t){return 5+S.byteLength(t.certificate)};var $a=E.record=function(t){switch(t.toUpperCase()){case"A":return St;case"PTR":return Le;case"CNAME":return Dy;case"DNAME":return Uy;case"TXT":return wt;case"NULL":return bt;case"AAAA":return Tt;case"SRV":return Et;case"HINFO":return vt;case"CAA":return pe;case"NS":return gt;case"SOA":return yt;case"MX":return Gt;case"OPT":return me;case"DNSKEY":return re;case"RRSIG":return Ve;case"RP":return Je;case"NSEC":return Ye;case"NSEC3":return Ke;case"SSHFP":return fe;case"DS":return Xe;case"NAPTR":return Ze;case"TLSA":return Qe}return _t},Q=E.answer={};Q.encode=function(t,e,r){e||(e=S.alloc(Q.encodingLength(t))),r||(r=0);let n=r;if(b.encode(t.name,e,r),r+=b.encode.bytes,e.writeUInt16BE(xt.toType(t.type),r),t.type.toUpperCase()==="OPT"){if(t.name!==".")throw new Error("OPT name must be root.");e.writeUInt16BE(t.udpPayloadSize||4096,r+2),e.writeUInt8(t.extendedRcode||0,r+4),e.writeUInt8(t.ednsVersion||0,r+5),e.writeUInt16BE(t.flags||0,r+6),r+=8,me.encode(t.options||[],e,r),r+=me.encode.bytes}else{let i=fs.toClass(t.class===void 0?"IN":t.class);t.flush&&(i|=Ma),e.writeUInt16BE(i,r+2),e.writeUInt32BE(t.ttl||0,r+4),r+=8;let s=$a(t.type);s.encode(t.data,e,r),r+=s.encode.bytes}return Q.encode.bytes=r-n,e};Q.encode.bytes=0;Q.decode=function(t,e){e||(e=0);let r={},n=e;if(r.name=b.decode(t,e),e+=b.decode.bytes,r.type=xt.toString(t.readUInt16BE(e)),r.type==="OPT")r.udpPayloadSize=t.readUInt16BE(e+2),r.extendedRcode=t.readUInt8(e+4),r.ednsVersion=t.readUInt8(e+5),r.flags=t.readUInt16BE(e+6),r.flag_do=(r.flags>>15&1)===1,r.options=me.decode(t,e+8),e+=8+me.decode.bytes;else{let i=t.readUInt16BE(e+2);r.ttl=t.readUInt32BE(e+4),r.class=fs.toString(i&Cy),r.flush=!!(i&Ma);let s=$a(r.type);r.data=s.decode(t,e+8),e+=8+s.decode.bytes}return Q.decode.bytes=e-n,r};Q.decode.bytes=0;Q.encodingLength=function(t){let e=t.data!==null&&t.data!==void 0?t.data:t.options;return b.encodingLength(t.name)+8+$a(t.type).encodingLength(e)};var Ce=E.question={};Ce.encode=function(t,e,r){e||(e=S.alloc(Ce.encodingLength(t))),r||(r=0);let n=r;return b.encode(t.name,e,r),r+=b.encode.bytes,e.writeUInt16BE(xt.toType(t.type),r),r+=2,e.writeUInt16BE(fs.toClass(t.class===void 0?"IN":t.class),r),r+=2,Ce.encode.bytes=r-n,t};Ce.encode.bytes=0;Ce.decode=function(t,e){e||(e=0);let r=e,n={};return n.name=b.decode(t,e),e+=b.decode.bytes,n.type=xt.toString(t.readUInt16BE(e)),e+=2,n.class=fs.toString(t.readUInt16BE(e)),e+=2,n.class&Ru&&(n.class&=Py),Ce.decode.bytes=e-r,n};Ce.decode.bytes=0;Ce.encodingLength=function(t){return b.encodingLength(t.name)+4};E.AUTHORITATIVE_ANSWER=1024;E.TRUNCATED_RESPONSE=512;E.RECURSION_DESIRED=256;E.RECURSION_AVAILABLE=128;E.AUTHENTIC_DATA=32;E.CHECKING_DISABLED=16;E.DNSSEC_OK=32768;E.encode=function(t,e,r){let n=!e;n&&(e=S.alloc(E.encodingLength(t))),r||(r=0);let i=r;return t.questions||(t.questions=[]),t.answers||(t.answers=[]),t.authorities||(t.authorities=[]),t.additionals||(t.additionals=[]),Pe.encode(t,e,r),r+=Pe.encode.bytes,r=Xn(t.questions,Ce,e,r),r=Xn(t.answers,Q,e,r),r=Xn(t.authorities,Q,e,r),r=Xn(t.additionals,Q,e,r),E.encode.bytes=r-i,n&&E.encode.bytes!==e.length?e.slice(0,E.encode.bytes):e};E.encode.bytes=0;E.decode=function(t,e){e||(e=0);let r=e,n=Pe.decode(t,e);return e+=Pe.decode.bytes,e=ps(n.questions,Ce,t,e),e=ps(n.answers,Q,t,e),e=ps(n.authorities,Q,t,e),e=ps(n.additionals,Q,t,e),E.decode.bytes=e-r,n};E.decode.bytes=0;E.encodingLength=function(t){return Pe.encodingLength(t)+Yr(t.questions||[],Ce)+Yr(t.answers||[],Q)+Yr(t.authorities||[],Q)+Yr(t.additionals||[],Q)};E.streamEncode=function(t){let e=E.encode(t),r=S.alloc(2);r.writeUInt16BE(e.byteLength);let n=S.concat([r,e]);return E.streamEncode.bytes=n.byteLength,n};E.streamEncode.bytes=0;E.streamDecode=function(t){let e=t.readUInt16BE(0);if(t.byteLength<e+2)return null;let r=E.decode(t.slice(2));return E.streamDecode.bytes=E.decode.bytes,r};E.streamDecode.bytes=0;function Yr(t,e){let r=0;for(let n=0;n<t.length;n++)r+=e.encodingLength(t[n]);return r}a(Yr,"encodingLengthList");function Xn(t,e,r,n){for(let i=0;i<t.length;i++)e.encode(t[i],r,n),n+=e.encode.bytes;return n}a(Xn,"encodeList");function ps(t,e,r,n){for(let i=0;i<t.length;i++)t[i]=e.decode(r,n),n+=e.decode.bytes;return n}a(ps,"decodeList")});var Au=A((Bx,Iu)=>{"use strict";var Ou=Fy;process.nextTick(qy,42);Iu.exports=By;function By(t){var e=n;return r;function r(i){e(i||My)}function n(i){var s=[i];e=o,t(c);function o(l){s.push(l)}a(o,"wait");function c(l){var d=arguments;for(e=jy(l)?n:u;s.length;)u(s.shift());function u(h){Ou($y,h,d)}a(u,"finished")}a(c,"done")}}a(By,"thunky");function jy(t){return Object.prototype.toString.call(t)==="[object Error]"}a(jy,"isError");function My(){}a(My,"noop");function $y(t,e){t.apply(null,e)}a($y,"apply");function qy(t){t===42&&(Ou=process.nextTick)}a(qy,"upgrade");function Fy(t,e,r){process.nextTick(function(){t(e,r)})}a(Fy,"nextTickArgs")});var Cu=A((Mx,Lu)=>{var qa=ku(),zy=U("dgram"),Wy=Au(),Hy=U("events"),za=U("os"),Fa=a(function(){},"noop");Lu.exports=function(t){t||(t={});var e=new Hy.EventEmitter,r=typeof t.port=="number"?t.port:5353,n=t.type||"udp4",i=t.ip||t.host||(n==="udp4"?"224.0.0.251":null),s={address:i,port:r},o={},c=!1,l=null;if(n==="udp6"&&(!i||!t.interface))throw new Error("For IPv6 multicast you must specify `ip` and `interface`");var d=t.socket||zy.createSocket({type:n,reuseAddr:t.reuseAddr!==!1,toString:a(function(){return n},"toString")});d.on("error",function(h){h.code==="EACCES"||h.code==="EADDRINUSE"?e.emit("error",h):e.emit("warning",h)}),d.on("message",function(h,f){try{h=qa.decode(h)}catch(p){e.emit("warning",p);return}e.emit("packet",h,f),h.type==="query"&&e.emit("query",h,f),h.type==="response"&&e.emit("response",h,f)}),d.on("listening",function(){r||(r=s.port=d.address().port),t.multicast!==!1&&(e.update(),l=setInterval(e.update,5e3),d.setMulticastTTL(t.ttl||255),d.setMulticastLoopback(t.loopback!==!1))});var u=Wy(function(h){if(!r||t.bind===!1)return h(null);d.once("error",h),d.bind(r,t.bind||t.interface,function(){d.removeListener("error",h),h(null)})});return u(function(h){if(h)return e.emit("error",h);e.emit("ready")}),e.send=function(h,f,p){if(typeof f=="function")return e.send(h,null,f);p||(p=Fa),f?!f.host&&!f.address&&(f.address=s.address):f=s,u(m);function m(_){if(c)return p();if(_)return p(_);var g=qa.encode(h);d.send(g,0,g.length,f.port,f.address||f.host,p)}a(m,"onbind")},e.response=e.respond=function(h,f,p){Array.isArray(h)&&(h={answers:h}),h.type="response",h.flags=(h.flags||0)|qa.AUTHORITATIVE_ANSWER,e.send(h,f,p)},e.query=function(h,f,p,m){if(typeof f=="function")return e.query(h,null,null,f);if(typeof f=="object"&&f&&f.port)return e.query(h,null,f,p);if(typeof p=="function")return e.query(h,f,null,p);m||(m=Fa),typeof h=="string"&&(h=[{name:h,type:f||"ANY"}]),Array.isArray(h)&&(h={type:"query",questions:h}),h.type="query",e.send(h,p,m)},e.destroy=function(h){if(h||(h=Fa),c)return process.nextTick(h);c=!0,clearInterval(l);for(var f in o)try{d.dropMembership(i,f)}catch{}o={},d.close(h)},e.update=function(){for(var h=t.interface?[].concat(t.interface):Vy(),f=!1,p=0;p<h.length;p++){var m=h[p];if(!o[m])try{d.addMembership(i,m),o[m]=!0,f=!0}catch(_){e.emit("warning",_)}}if(f){if(d.setMulticastInterface)try{d.setMulticastInterface(t.interface||Gy())}catch(_){e.emit("warning",_)}e.emit("networkInterface")}},e};function Gy(){for(var t=za.networkInterfaces(),e=Object.keys(t),r=0;r<e.length;r++)for(var n=t[e[r]],i=0;i<n.length;i++){var s=n[i];if(Nu(s.family)&&!s.internal)return za.platform()==="darwin"&&e[r]==="en0"?s.address:"0.0.0.0"}return"127.0.0.1"}a(Gy,"defaultInterface");function Vy(){for(var t=za.networkInterfaces(),e=Object.keys(t),r=[],n=0;n<e.length;n++)for(var i=t[e[n]],s=0;s<i.length;s++){var o=i[s];if(Nu(o.family)){r.push(o.address);break}}return r}a(Vy,"allInterfaces");function Nu(t){return t===4||t==="IPv4"}a(Nu,"isIPv4")});var Du=A((qx,Pu)=>{"use strict";Pu.exports=a(function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,i,s;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(i=n;i--!==0;)if(!t(e[i],r[i]))return!1;return!0}if(e instanceof Map&&r instanceof Map){if(e.size!==r.size)return!1;for(i of e.entries())if(!r.has(i[0]))return!1;for(i of e.entries())if(!t(i[1],r.get(i[0])))return!1;return!0}if(e instanceof Set&&r instanceof Set){if(e.size!==r.size)return!1;for(i of e.entries())if(!r.has(i[0]))return!1;return!0}if(ArrayBuffer.isView(e)&&ArrayBuffer.isView(r)){if(n=e.length,n!=r.length)return!1;for(i=n;i--!==0;)if(e[i]!==r[i])return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),n=s.length,n!==Object.keys(r).length)return!1;for(i=n;i--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[i]))return!1;for(i=n;i--!==0;){var o=s[i];if(!t(e[o],r[o]))return!1}return!0}return e!==e&&r!==r},"equal")});var Uu=A(wr=>{"use strict";var Wa=wr&&wr.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(wr,"__esModule",{value:!0});wr.Server=void 0;var Jy=Wa(Cu()),Yy=Wa(Du()),Ky=Wa(ls()),ms=class{static{a(this,"Server")}constructor(e,r){this.registry={},this.mdns=(0,Jy.default)(e),this.mdns.setMaxListeners(0),this.mdns.on("query",this.respondToQuery.bind(this)),this.errorCallback=r??function(n){throw n}}register(e){let r=a(n=>{var i=this.registry[n.type];if(!i)i=this.registry[n.type]=[];else if(i.some(this.isDuplicateRecord(n)))return;i.push(n)},"shouldRegister");Array.isArray(e)?e.forEach(r):r(e)}unregister(e){let r=a(n=>{let i=n.type;i in this.registry&&(this.registry[i]=this.registry[i].filter(s=>s.name!==n.name))},"shouldUnregister");Array.isArray(e)?e.forEach(r):r(e)}respondToQuery(e){let r=this;e.questions.forEach(n=>{var i=n.type,s=n.name,o=i==="ANY"?Object.keys(r.registry).map(r.recordsFor.bind(r,s)).flat(1):r.recordsFor(s,i);if(o.length!==0){var c=[];i!=="ANY"&&(o.forEach(l=>{l.type==="PTR"&&(c=c.concat(r.recordsFor(l.data,"SRV")).concat(r.recordsFor(l.data,"TXT")))}),c.filter(function(l){return l.type==="SRV"}).map(function(l){return l.data.target}).filter(this.unique()).forEach(function(l){c=c.concat(r.recordsFor(l,"A")).concat(r.recordsFor(l,"AAAA"))})),r.mdns.respond({answers:o,additionals:c},l=>{l&&this.errorCallback(l)})}})}recordsFor(e,r){return r in this.registry?this.registry[r].filter(n=>{var i=~e.indexOf(".")?n.name:n.name.split(".")[0];return(0,Ky.default)(i,e)}):[]}isDuplicateRecord(e){return r=>e.type===r.type&&e.name===r.name&&(0,Yy.default)(e.data,r.data)}unique(){var e=[];return r=>~e.indexOf(r)?!1:(e.push(r),!0)}};wr.Server=ms;wr.default=ms});var Bu=A(Ha=>{"use strict";Object.defineProperty(Ha,"__esModule",{value:!0});Ha.default=(t,e)=>{if(e===void 0)return!0;let r=t.txt,n=Object.entries(e).map(([i,s])=>{let o=r[i];return!(o===void 0||s!=o)});return n.length==0?!0:!n.includes(!1)}});var ju=A(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});Ga.default=t=>Object.keys(t).filter(e=>!e.includes("binary")).reduce((e,r)=>Object.assign(e,{[r]:t[r]}),{})});var Mu=A(Va=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});Va.default=Xy;function Xy(t,e){if(t===void 0||e===void 0)return!1;let r=Object.keys(t),n=Object.keys(e);if(r.length!=n.length)return!1;for(let i of r)if(t[i]!=e[i])return!1;return!0}a(Xy,"equalTxt")});var Fu=A(br=>{"use strict";var Zn=br&&br.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(br,"__esModule",{value:!0});br.Browser=void 0;var Zy=Zn(Oa()),Vt=Zn(ls()),Qy=U("events"),Ja=Ia(),$u=Zn(Bu()),ew=Zn(ju()),tw=Zn(Mu()),qu=".local",rw="_services._dns-sd._udp"+qu,_s=class t extends Qy.EventEmitter{static{a(this,"Browser")}constructor(e,r,n){if(super(),this.onresponse=void 0,this.serviceMap={},this.wildcard=!1,this._services=[],typeof r=="function")return new t(e,null,r);this.mdns=e,this.txt=new Zy.default(r!==null&&r.txt!=null?r.txt:void 0),r===null||r.type===void 0?(this.name=rw,this.wildcard=!0):(this.name=(0,Ja.toString)({name:r.type,protocol:r.protocol||"tcp"})+qu,r.name&&(this.name=r.name+"."+this.name),this.wildcard=!1),r!=null&&r.txt!==void 0&&(this.txtQuery=(0,ew.default)(r.txt)),n&&this.on("up",n),this.start()}start(){if(!(this.onresponse||this.name===void 0)){var e=this,r={};this.wildcard||(r[this.name]=!0),this.onresponse=(n,i)=>{e.wildcard&&n.answers.forEach(o=>{o.type!=="PTR"||o.name!==e.name||o.name in r||(r[o.data]=!0,e.mdns.query(o.data,"PTR"))});let s=Date.now();Object.keys(r).forEach(function(o){e.goodbyes(o,n).forEach(e.removeService.bind(e));var c=e.buildServicesFor(o,n,e.txt,i,s);c.length!==0&&c.forEach(l=>{let d=e._services.find(u=>(0,Vt.default)(u.fqdn,l.fqdn));if(d){e.updateServiceSrv(d,l),e.updateServiceTxt(d,l);return}e.addService(l)})})},this.mdns.on("response",this.onresponse),this.update()}}stop(){this.onresponse&&(this.mdns.removeListener("response",this.onresponse),this.onresponse=void 0)}update(){this.mdns.query(this.name,"PTR")}expire(){let e=Date.now();this._services=this._services.filter(r=>!r.ttl||r.lastSeen===void 0?!0:r.lastSeen+r.ttl*1e3<e?(this.emit("down",r),!1):!0)}get services(){return this._services}addService(e){(0,$u.default)(e,this.txtQuery)!==!1&&(this._services.push(e),this.serviceMap[e.fqdn]=!0,this.emit("up",e))}updateServiceSrv(e,r){(e.name!==r.name||e.host!==r.host||e.port!==r.port||e.type!==r.type||e.protocol!==r.protocol)&&(this.replaceService(r),this.emit("srv-update",r,e))}updateServiceTxt(e,r){if(!(0,tw.default)(r.txt,e?.txt||{})){if(!(0,$u.default)(r,this.txtQuery)){this.removeService(r.fqdn);return}this.replaceService(r),this.emit("txt-update",r,e)}}replaceService(e){this._services=this._services.map(r=>(0,Vt.default)(r.fqdn,e.fqdn)?e:r)}removeService(e){var r,n;this._services.some(function(i,s){if((0,Vt.default)(i.fqdn,e))return r=i,n=s,!0}),!(!r||n===void 0)&&(this._services.splice(n,1),delete this.serviceMap[e],this.emit("down",r))}goodbyes(e,r){return r.answers.concat(r.additionals).filter(n=>n.type==="PTR"&&n.ttl===0&&(0,Vt.default)(n.name,e)).map(n=>n.data)}buildServicesFor(e,r,n,i,s){var o=r.answers.concat(r.additionals).filter(c=>c.ttl>0);return o.filter(c=>c.type==="PTR"&&(0,Vt.default)(c.name,e)).map(c=>{let l={addresses:[],subtypes:[],ttl:c.ttl,lastSeen:s};if(o.filter(d=>d.type==="PTR"&&(0,Vt.default)(d.data,c.data)&&d.name.includes("._sub")).forEach(d=>{let u=(0,Ja.toType)(d.name);l.subtypes.push(u.subtype)}),o.filter(d=>(d.type==="SRV"||d.type==="TXT")&&(0,Vt.default)(d.name,c.data)).forEach(d=>{if(d.type==="SRV"){var u=d.name.split("."),h=u[0],f=(0,Ja.toType)(u.slice(1,-1).join("."));l.name=h,l.fqdn=d.name,l.host=d.data.target,l.referer=i,l.port=d.data.port,l.type=f.name,l.protocol=f.protocol}else d.type==="TXT"&&(l.rawTxt=d.data,l.txt=this.txt.decodeAll(d.data))}),!!l.name)return o.filter(d=>(d.type==="A"||d.type==="AAAA")&&(0,Vt.default)(d.name,l.host)).forEach(d=>l.addresses.push(d.data)),l}).filter(c=>!!c)}};br.Browser=_s;br.default=_s});var Xa=A(Rt=>{"use strict";var gs=Rt&&Rt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Rt,"__esModule",{value:!0});Rt.Browser=Rt.Service=void 0;var nw=gs(_u()),iw=gs(Uu()),Ya=gs(Fu());Rt.Browser=Ya.default;var sw=gs(Aa());Rt.Service=sw.default;var Ka=class{static{a(this,"Bonjour")}constructor(e={},r){this.server=new iw.default(e,r),this.registry=new nw.default(this.server)}publish(e){return this.registry.publish(e)}unpublishAll(e){return this.registry.unpublishAll(e)}find(e=null,r){return new Ya.default(this.server.mdns,e,r)}findOne(e=null,r=1e4,n){let i=new Ya.default(this.server.mdns,e);var s;return i.once("up",o=>{s!==void 0&&clearTimeout(s),i.stop(),n&&n(o)}),s=setTimeout(()=>{i.stop(),n&&n(null)},r),i}destroy(e){this.registry.destroy(),this.server.mdns.destroy(e)}};Rt.default=Ka});var zu=A((kt,Kr)=>{"use strict";var ow=kt&&kt.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:a(function(){return e[r]},"get")}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),aw=kt&&kt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),cw=kt&&kt.__importStar||(function(){var t=a(function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(n[n.length]=i);return n},t(e)},"ownKeys");return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),i=0;i<n.length;i++)n[i]!=="default"&&ow(r,e,n[i]);return aw(r,e),r}})(),lw=kt&&kt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}},dw=lw(Xa()),ys=cw(Xa()),et=class extends dw.default{static{a(this,"Bonjour")}},uw=et;(function(t){t.Bonjour=uw,t.Service=ys.Service,t.Browser=ys.Browser})(et||(et={}));Object.defineProperty(et,"default",{enumerable:!0,value:et});Kr.exports.Bonjour=et;Kr.exports.Service=ys.Service;Kr.exports.Browser=ys.Browser;Kr.exports.default=et;Kr.exports=et});import{isIP as Wu}from"node:net";function Za(t,{loopback:e=!0,linkLocal:r=!0}={}){let n=String(t||"").toLowerCase().split("%")[0];n.startsWith("::ffff:")&&Wu(n.slice(7))===4&&(n=n.slice(7));let i=Wu(n);if(i===4){let[s,o]=n.split(".").map(Number);return e&&s===127||s===10||s===172&&o>=16&&o<=31||s===192&&o===168||s===100&&o>=64&&o<=127||r&&s===169&&o===254}if(i===6){if(n==="::1")return e;let s=parseInt(n.split(":")[0]||"0",16);return(s&65024)===64512||r&&(s&65472)===65152}return!1}var Qa=C(()=>{a(Za,"isPrivateNetworkAddress")});import{isIP as hw}from"node:net";function ws(t,e={}){let r=Math.max(100,Math.min(5e3,Number(e.timeoutMs||2e3))),n=e.signal;return n?.aborted?Promise.reject(n.reason):new Promise((i,s)=>{let o=new Set,c=!1,l,d,u,h=a(()=>queueMicrotask(()=>f(n.reason instanceof Error?n.reason:new Error("Discovery cancelled"))),"abort");n?.addEventListener("abort",h,{once:!0});try{u=(e.createBonjour||(m=>new Hu.Bonjour(void 0,m)))(()=>queueMicrotask(()=>f())),l=u.find({type:pw,protocol:"tcp"}),l.on("up",m=>{if(!(c||fw(m.txt?.node_id)!==t||!mw(m.port)))for(let _ of m.addresses||[])Za(_)&&o.add(`http://${_w(_)}:${Number(m.port)}`)}),l.on("error",()=>f()),d=setTimeout(()=>f(),r),d.unref?.(),n?.aborted&&h()}catch(p){f(p)}function f(p){if(c)return;c=!0,clearTimeout(d),n?.removeEventListener("abort",h);let m=a(()=>{let _=p||(n?.aborted?n.reason||new Error("Discovery cancelled"):null);_?s(_):i([...o])},"complete");try{l?.stop()}catch(_){p||=_}try{u?u.destroy(m):m()}catch(_){p||=_,m()}}a(f,"finish")})}function fw(t){return Buffer.isBuffer(t)?t.toString("utf8"):typeof t=="string"?t:""}function mw(t){let e=Number(t);return Number.isInteger(e)&&e>=1&&e<=65535}function _w(t){return hw(t)===6?`[${t}]`:t}var Hu,pw,ec=C(()=>{Hu=ot(zu(),1);Qa();pw="interscale-data";a(ws,"discoverTransferCandidates");a(fw,"txtValue");a(mw,"validPort");a(_w,"formatHost")});import{networkInterfaces as Yu,platform as tc}from"node:os";import{execFileSync as Ku}from"node:child_process";import{readlinkSync as gw}from"node:fs";function ww({refresh:t=!1}={}){if(!t&&rc&&Date.now()-Vu<yw)return rc;let e;try{e=bw()}catch{e=new Map}return rc=e,Vu=Date.now(),e}function bw(){return tc()==="darwin"?vw():tc()==="linux"?Ew():tc()==="win32"?Sw():new Map}function vw(){let t=new Map,e=Ku("/usr/sbin/networksetup",["-listallhardwareports"],{encoding:"utf8",timeout:5e3}),r=null;for(let n of e.split(/\r?\n/)){let i=/^Hardware Port:\s*(.+?)\s*$/.exec(n);if(i){r=i[1];continue}let s=/^Device:\s*(.+?)\s*$/.exec(n);s&&r&&(t.set(s[1],Xu(r)),r=null)}return t}function Ew(){let t=new Map;for(let e of Object.keys(Yu())){if(/^(thunderbolt|tb)\d*$/i.test(e)){t.set(e,bs);continue}let r="";try{r=gw(`/sys/class/net/${e}`)}catch{r=""}/thunderbolt/i.test(r)?t.set(e,bs):/^(wl|wlan|wifi)/i.test(e)?t.set(e,sc):/^(en|eth|br|bond)/i.test(e)&&t.set(e,ic)}return t}function Sw(){let t=new Map,e=Ku("powershell.exe",["-NoProfile","-NonInteractive","-Command","Get-NetAdapter | Select-Object Name,InterfaceDescription | ConvertTo-Json -Compress"],{encoding:"utf8",timeout:1e4}),r=JSON.parse(e||"[]");for(let n of Array.isArray(r)?r:[r])n?.Name&&t.set(n.Name,Xu(`${n.Name} ${n.InterfaceDescription||""}`));return t}function Xu(t){return Tw.test(t)?oc:/thunderbolt/i.test(t)?bs:/wi-?fi|airport|wireless|wlan|802\.11/i.test(t)?sc:/ethernet|\blan\b|gigabit|bridge/i.test(t)?ic:Xr}function Rw({classes:t=ww()}={}){let e=[];for(let[r,n]of Object.entries(Yu()))for(let i of n||[])i.internal||e.push({name:r,kind:t.get(r)||(xw.test(r)?oc:Xr),family:kw(i.family),address:i.address,netmask:i.netmask,scopeid:i.scopeid});return e}function Ju(t){return Gu[t]??Gu[Xr]}function kw(t){return t===4||t===6?t:String(t).toLowerCase()==="ipv6"?6:4}function nc(t){let e=t.split(".");if(e.length!==4)return null;let r=0;for(let n of e){let i=Number(n);if(!Number.isInteger(i)||i<0||i>255)return null;r=r*256+i}return r}function Ow(t,e){let r=nc(t.address),n=nc(t.netmask||""),i=nc(e);return r===null||n===null||i===null?!1:(r&n)>>>0===(i&n)>>>0}function Iw(t,e,r){return r!==t.family?!1:r===4?Ow(t,e):e.toLowerCase().startsWith("fe80:")&&t.address.toLowerCase().startsWith("fe80:")}function Aw(t){try{return new URL(t).hostname.replace(/^\[/,"").replace(/\]$/,"")}catch{return null}}function Nw(t){return t?/^\d{1,3}(\.\d{1,3}){3}$/.test(t)?4:t.includes(":")?6:null:null}function vs(t,e=Rw()){let r=[],n=new Set;for(let i of t||[]){let s=Aw(i);if(!s)continue;let o=Nw(s),c=o?e.filter(d=>Iw(d,s,o)):[],l=c.length>0?c.map(d=>({url:i,localAddress:d.address,interface:d.name,kind:d.kind,rank:Ju(d.kind)})):[{url:i,localAddress:null,interface:null,kind:Xr,rank:Ju(Xr)+1}];for(let d of l){let u=`${d.url}|${d.localAddress||""}`;n.has(u)||(n.add(u),r.push(d))}}return r.map((i,s)=>({plan:i,index:s})).sort((i,s)=>i.plan.rank-s.plan.rank||i.index-s.index).map(i=>i.plan)}var bs,ic,sc,Xr,oc,Gu,yw,rc,Vu,Tw,xw,ac=C(()=>{Qa();bs="thunderbolt",ic="ethernet",sc="wifi",Xr="other",oc="virtual",Gu={[bs]:0,[ic]:1,[sc]:2,[Xr]:3,[oc]:4},yw=60*1e3,rc=null,Vu=0;a(ww,"interfaceClasses");a(bw,"detectInterfaceClasses");a(vw,"detectDarwin");a(Ew,"detectLinux");a(Sw,"detectWindows");Tw=/vEthernet|Hyper-V|\bWSL\b|Docker|VMware|VirtualBox|VBox|TAP-|\bTAP\b|Npcap|Parsec|Bluetooth|Default Switch/i,xw=/^(bridge1\d\d|vmnet\d+|vmenet\d+|feth\d+|docker\d*|br-[0-9a-f]+|veth\w*|virbr\d*|lxdbr\d*|cni\d*|flannel\S*|vboxnet\d+)$/;a(Xu,"kindFromPortName");a(Rw,"localLinks");a(Ju,"kindRank");a(kw,"normalizeFamily");a(nc,"ipv4ToInt");a(Ow,"sameIpv4Subnet");a(Iw,"reachesPeer");a(Aw,"hostFromUrl");a(Nw,"addressFamily");a(vs,"planDirectCandidates")});function Lw(t={}){let e={ENOENT:"source_missing",EACCES:"permission_denied",EPERM:"permission_denied",ENOSPC:"insufficient_space"}[t.code]||t.code||t.failure_code||"download_preparation_failed",r=String(t.message||t.failure_message||"The source agent could not prepare this download").slice(0,2e3),n=e==="source_missing"?"Check the source path and mounted volume, then start a new download":e==="source_changed"?"Wait for source writes to finish, then start a new download":e==="source_snapshot_unavailable"?"Start a new download; this download cannot safely resume without its prepared source":e==="permission_denied"?"Grant the agent account access to the source, then start a new download":e==="insufficient_space"?"Free space on the source staging volume, then start a new download":"Inspect the source path and agent error, then start a new download";return{code:String(e).slice(0,200),message:r,retryable:!1,next_action:n}}function vr(t){let e=Lw(t);return Object.assign(new Error(e.message),e,{terminal:!0})}function cc(t){let r={ENOSPC:["insufficient_space","Free space on the local staging and destination volumes, then resume"],EDQUOT:["insufficient_space","Increase the local storage quota or free space, then resume"],EACCES:["permission_denied","Grant the local account access to the staging and destination paths"],EPERM:["permission_denied","Check local file permissions and file locks before resuming"],EROFS:["read_only_destination","Choose a writable destination volume"],EEXIST:["destination_exists","Choose another destination or explicitly allow overwrite"],ENOTEMPTY:["destination_exists","Resolve the existing nonempty destination before resuming"],EFBIG:["local_file_too_large","Choose a filesystem that supports this file size"],ENOTDIR:["invalid_destination_path","Check that each parent in the local destination path is a directory"],EISDIR:["invalid_destination_path","Choose a file destination or resolve the existing directory conflict"],ENOENT:["local_path_missing","Check the local staging path and mounted destination volume before resuming"],EBUSY:["destination_busy","Close the application holding the local file, then resume"],EIO:["local_storage_error","Check the local drive and filesystem before resuming"],ERR_SQLITE_ERROR:["local_state_error","Check local resume-database storage and access before resuming"],publication_hash_mismatch:["publication_hash_mismatch","Check local storage integrity before retrying publication"],insufficient_space:["insufficient_space","Free space on the local staging and destination volumes, then resume"]}[t?.code];return r?Object.assign(new Error(t.message,{cause:t}),{code:r[0],next_action:r[1],terminal:!0,retryable:!1}):t}var Zu=C(()=>{a(Lw,"downloadFailure");a(vr,"failedDownloadError");a(cc,"localDownloadFailure")});import*as Qn from"node:path";import{stat as th,statfs as Cw,realpath as rh}from"node:fs/promises";async function Qu(t,e={stat:th,realpath:rh}){let r=Qn.resolve(t);for(;;)try{return{path:r,real:await e.realpath(r),metadata:await e.stat(r)}}catch(n){if(n.code!=="ENOENT")throw n;let i=Qn.dirname(r);if(i===r)throw n;r=i}}async function nh({stagingPath:t,destinationPath:e,size:r,reserve:n=1024**3,directory:i=!1,staged:s=!1,movable:o=!1},c={stat:th,realpath:rh,statfs:Cw}){if(!Number.isSafeInteger(r)||r<0||!Number.isSafeInteger(n)||n<0)throw eh("invalid_transfer_size","Transfer size and reserve must be nonnegative safe integers");let[l,d]=await Promise.all([Qu(t,c),Qu(Qn.dirname(e),c)]),u=new Map;for(let[h,f]of[[l,s?0n:BigInt(r)],[d,BigInt(r)*(i?2n:1n)]]){if(s&&h===l)continue;let p=String(h.metadata.dev),m=u.get(p);u.set(p,{path:h.path,required:(m?.required||BigInt(n))+(o&&m?0n:f)})}for(let h of u.values()){let f=await c.statfs(h.path,{bigint:!0}),p=BigInt(f.bavail)*BigInt(f.bsize);if(p<h.required)throw eh("insufficient_space",`Insufficient storage on ${h.path}: ${p} bytes available, ${h.required} required`)}}function eh(t,e){return Object.assign(new Error(e),{code:t})}var ih=C(()=>{a(Qu,"existingAncestor");a(nh,"checkTransferSpace");a(eh,"failure")});import{constants as sh,createReadStream as Pw}from"node:fs";import{copyFile as Dw,link as Uw,mkdir as Bw,open as lc,rename as Es,rm as dc,stat as ah}from"node:fs/promises";import{basename as jw,dirname as oh,join as Mw}from"node:path";import{createHash as $w,randomUUID as qw}from"node:crypto";async function ch(t,e,{overwrite:r=!1,move:n=!1,sha256:i,onStaged:s,onPublished:o,minimumFreeBytes:c=1024**3,signal:l}={}){l?.throwIfAborted();let d=oh(e),u=await ah(t),h=a(()=>nh({stagingPath:oh(t),destinationPath:e,size:u.size,reserve:c,staged:!0}),"checkSpace");n||await h(),await Bw(d,{recursive:!0,mode:448});let f=Mw(d,`.${jw(e).slice(0,60)}.interscale-${qw()}.part`),p=!1,m=!1;try{if(l?.throwIfAborted(),n)try{await Es(t,f),p=!0}catch(g){if(g.code!=="EXDEV")throw g;await h()}if(!p&&(await Dw(t,f,sh.COPYFILE_EXCL|sh.COPYFILE_FICLONE),l?.throwIfAborted(),i)){let g=$w("sha256");for await(let y of Pw(f,{signal:l}))g.update(y);if(g.digest("hex")!==i)throw Object.assign(new Error("Staged destination failed SHA-256 verification"),{code:"publication_hash_mismatch"})}let _=await lc(f,"r+");try{await _.sync()}finally{await _.close()}if(await s?.(f),l?.throwIfAborted(),r?await Es(f,e):await Fw(f,e),m=!0,process.platform!=="win32"){let g=await lc(d,"r");try{await g.sync()}catch(y){if(!["EINVAL","ENOTSUP"].includes(y.code))throw y}finally{await g.close()}}await o?.()}finally{p&&!m?await Es(f,t).catch(()=>dc(f,{force:!0})):await dc(f,{force:!0})}}async function Fw(t,e,{linkFile:r=Uw}={}){try{await r(t,e);return}catch(s){if(s.code==="EEXIST")throw s}let n=await lc(e,"wx"),i=await n.stat().finally(()=>n.close());try{await Es(t,e)}catch(s){let o=await ah(e).catch(()=>null);throw o&&o.ino===i.ino&&o.size===0&&await dc(e,{force:!0}),s}}var lh=C(()=>{ih();a(ch,"publishFile");a(Fw,"claimCreateOnly")});function Jt(t){return JSON.stringify(uc(t))}function uc(t){return Array.isArray(t)?t.map(uc):t&&typeof t=="object"?Object.fromEntries(Object.keys(t).sort().map(e=>[e,uc(t[e])])):t}var Ss=C(()=>{a(Jt,"canonicalJson");a(uc,"canonical")});import{rm as zw}from"node:fs/promises";import{setTimeout as hc}from"node:timers/promises";async function Ww(t,e,r,n={}){if(e.published)return Ts(t,e,r,null,n.signal,"r2");let i=n.relayTimeoutMs??1800*1e3;if(!Number.isSafeInteger(i)||i<1||i>2147483647)throw new RangeError("Invalid relay timeout");let s=new AbortController,o=setTimeout(()=>s.abort(),i),c=n.signal?AbortSignal.any([n.signal,s.signal]):s.signal,l=`/v1/downloads/${encodeURIComponent(e.id)}/relay`;try{c.throwIfAborted();let{relay:d}=await t.request(l,{method:"POST",json:{token:e.token},signal:c});for(;d.state!=="uploaded";){if(d.state==="failed"){let f=(await t.request(`/v1/downloads/${encodeURIComponent(e.id)}`,{signal:c})).download;throw vr(d.error||f)}if(d.source_relay_support==="upgrade_required")throw Object.assign(new M("download_relay_unsupported","Source agent has not advertised relay download support"),{retryable:!1,next_action:"Upgrade the source agent and wait for its next heartbeat, then resume this download."});if(["cancelled","completed"].includes(d.state))throw new M("download_stopped",`Relay download is ${d.state}; inspect its outcome`);await hc(500,void 0,{signal:c}),{relay:d}=await t.request(l,d.state==="expired"?{method:"POST",json:{token:e.token},signal:c}:{signal:c})}let u=Yn(d.manifest),h=await Ra(e,u,r,{...n,signal:c,route:"r2",concurrency:4,fetchChunk:a(async({index:f,expectedBytes:p,signal:m})=>{for(let _=0;_<2;_++){let g=await t.request(`${l}/read-plan`,{method:"POST",signal:m,json:{token:e.token,relay_id:d.relay_id,indices:[f]}}),y=g.chunks?.[0];if(g.download_id!==e.id||g.relay_id!==d.relay_id||Jt(g.manifest)!==Jt(d.manifest)||g.chunks?.length!==1||y?.index!==f||y.encrypted_size!==p||typeof y.url!="string")throw new M("invalid_relay_read_plan","Relay read plan does not match the retained download");let w=await ft(y.url,{signal:m,maxResponseBytes:p});if(!([401,403].includes(w.status)&&_===0)){if(!w.ok)throw new M("relay_chunk_unavailable",`Relay chunk ${f} returned HTTP ${w.status}`);return Buffer.from(await w.arrayBuffer())}}},"fetchChunk")});return await uh(h,u,{...n,signal:c}),r.markPublished(h.id),h=r.get(h.id),await Ts(t,h,r,null,c,"r2")}catch(d){throw s.signal.aborted&&!n.signal?.aborted?Object.assign(new M("relay_download_timeout","Relay download exceeded its deadline"),{retryable:!0,next_action:"Inspect or resume the existing download; its verified chunks and publication receipt are retained."}):cc(d)}finally{clearTimeout(o)}}async function dh(t,e,r,n,i={}){if(ei(i.signal),e.published)return Ts(t,e,n,null,i.signal);let s=new Set,o,c=a(async f=>{for(let p of await as(vs(f),{nodeId:e.download.target_node_id,id:e.id,token:e.token,kind:"downloads",signal:i.signal})){let m=p.url,_=`${m}|${p.localAddress||""}`;if(s.has(_))continue;s.add(_);let g={...i,localAddress:p.localAddress};try{i.onLinkAttempt?.(p);let y=await Hw(t,m,e.id,e.token,g);try{return await Gw(t,m,e,y,n,g)}catch(w){throw cc(w)}}catch(y){if(os(e.download.target_node_id,p),y.terminal||ph(y,i.signal))throw y;o=y}}return null},"tryCandidates"),l=await c(r);if(l)return l;let d=await ws(e.download.target_node_id,{timeoutMs:i.mdnsTimeoutMs,signal:i.signal}),u=await c(d);if(u)return{...u,discovered_by:"mdns"};let h=(await t.request(`/v1/downloads/${encodeURIComponent(e.id)}`,{signal:i.signal})).download;if(h?.state==="failed")throw vr(h);if(h?.r2_available??e.download.r2_available)return i.onFallback?.({route:"r2",reason:o?.message||"No direct route"}),Ww(t,e,n,i);throw s.size===0?new Error("Job machine is offline or has no direct LAN route"):new Error(`All direct result-download candidates failed: ${o?.message||"unknown error"}`)}async function Hw(t,e,r,n,i){let s=e.replace(/\/$/,""),o=`/v1/downloads/${encodeURIComponent(r)}/status`,c=Date.now()+Number(i.readyTimeoutMs||300*1e3),l=0,d=null;for(;Date.now()<c;){ei(i.signal);try{let u=await ft(`${s}${o}`,{headers:{authorization:hh(n,r,"GET",o)},signal:fh(i.signal,Number(i.connectTimeoutMs||2e3)),maxResponseBytes:65536,localAddress:i.localAddress});if(u.ok){let h=await u.json();if(h.state==="ready")return Yn(h);if(h.state==="failed")throw vr(h.error||h);d=null,l=0}else if(u.status===404){if(d===null){d=Date.now();let{download:h}=await t.request(`/v1/downloads/${encodeURIComponent(r)}`);if(h?.state==="failed")throw vr(h)}if(Date.now()-d>=Number(i.registrationTimeoutMs??2e3))throw Object.assign(new Error("Download is not registered on this route; reconnect the source agent or resume the download"),{code:"download_not_registered",routeFailed:!0})}else throw new Error(`Download status failed with HTTP ${u.status}`)}catch(u){if(u.terminal||u.routeFailed||ph(u,i.signal))throw u;if(l===0){let h=(await t.request(`/v1/downloads/${encodeURIComponent(r)}`,{signal:i.signal})).download;if(h?.state==="failed")throw vr(h)}if(l+=1,l>=3)throw u}await hc(250,void 0,{signal:i.signal})}throw new Error("Timed out while the agent prepared the job result")}async function Gw(t,e,r,n,i,s){let o=await Ra(r,n,i,{...s,concurrency:s.directConcurrency,fetchChunk:a(async({index:c,expectedBytes:l,signal:d})=>{let u=`/v1/downloads/${encodeURIComponent(r.id)}/chunks/${c}`,h=await ft(`${e.replace(/\/$/,"")}${u}`,{headers:{authorization:hh(r.token,r.id,"GET",u)},signal:fh(d,Number(s.chunkTimeoutMs||1800*1e3)),maxResponseBytes:l,localAddress:s.localAddress});if(!h.ok)throw new Error(`Result chunk ${c} failed with HTTP ${h.status}`);return Buffer.from(await h.arrayBuffer())},"fetchChunk")});return await uh(o,n,s),i.markPublished(o.id),o=i.get(o.id),Ts(t,o,i,e,s.signal)}async function uh(t,e,r){if(ei(r.signal),e.kind==="directory-tar"){await Bd(t.part_path,t.output_path,{overwrite:!!r.overwrite,transferId:t.id,maximumBytes:e.size+1024*1024});return}if(e.kind!=="file")throw new Error(`Unsupported result kind: ${e.kind}`);await ch(t.part_path,t.output_path,{overwrite:!!r.overwrite,sha256:e.sha256,signal:r.signal})}async function Ts(t,e,r,n=null,i,s="direct"){let o=Date.now()+1e4;for(;Date.now()<o;){ei(i);let l=(await t.request(`/v1/downloads/${encodeURIComponent(e.id)}`,{signal:i})).download;if(l.state==="ready"||l.state==="downloading"||l.state==="completed")break;if(l.state==="failed")throw vr(l);await hc(100,void 0,{signal:i})}ei(i);let c=await t.request(`/v1/downloads/${encodeURIComponent(e.id)}/complete`,{method:"POST",json:{},signal:i});return r.complete(e.id),await zw(e.part_path,{force:!0}),{download:c.download,route:s,candidate:n,output:e.output_path}}function hh(t,e,r,n){return`Interscale ${fr(t,e,r,n)}`}function ei(t){if(!t?.aborted)return;let e=t.reason instanceof Error?t.reason:new Error("Download interrupted");throw e.code||="download_interrupted",e}function ph(t,e){return!!e?.aborted||t?.code==="download_interrupted"||t?.name==="AbortError"}function fh(t,e){let r=AbortSignal.timeout(Math.max(1,e));return t?AbortSignal.any([t,r]):r}var mh=C(()=>{ba();lu();Wn();ma();ec();ac();ss();Zu();lh();Sa();Ss();le();a(Ww,"receiveRelayDownload");a(dh,"receiveDownload");a(Hw,"waitForManifest");a(Gw,"receiveFromCandidate");a(uh,"publishResult");a(Ts,"finishPublishedDownload");a(hh,"authorization");a(ei,"throwIfAborted");a(ph,"isInterrupted");a(fh,"combinedSignal")});function pc(t){if(t.outputs===void 0)return;let e=a(()=>{throw Object.assign(new Error("outputs must contain at most 100 distinct relative file paths or {path,required} records, without traversal, absolute paths or globs (64 KiB total)"),{code:"invalid_job_outputs"})},"invalid");(!["exec","shell","recipe"].includes(t.type)||!Array.isArray(t.outputs)||t.outputs.length>100)&&e();let r=new Set,n=0;for(let i of t.outputs){let s=typeof i=="string"?{path:i,required:!0}:i;(!s||typeof s!="object"||Array.isArray(s)||Object.keys(s).some(c=>!["path","required"].includes(c))||s.required!==void 0&&typeof s.required!="boolean"||typeof s.path!="string"||!s.path.length||s.path.length>3800||/[\0*?]/.test(s.path))&&e();let o=s.path.replace(/\\/g,"/");(o.startsWith("/")||/^[A-Za-z]:/.test(o)||o.split("/").some(c=>!c||c==="."||c==="..")||r.has(o))&&e(),r.add(o),n+=Buffer.byteLength(JSON.stringify(s))+1,n>64*1024&&e()}}function xs(t){return pc({type:"exec",outputs:t}),t.map(e=>typeof e=="string"?{path:e.replace(/\\/g,"/"),required:!0}:{path:e.path.replace(/\\/g,"/"),required:e.required!==!1})}var _h,Rs=C(()=>{_h={outputs:{type:"array",maxItems:100,items:{anyOf:[{type:"string",minLength:1,maxLength:3800},{type:"object",additionalProperties:!1,required:["path"],properties:{path:{type:"string",minLength:1,maxLength:3800},required:{type:"boolean"}}}]},description:"Files relative to cwd kept as verified artifacts (object entries may be optional); [] disables. No globs or directories."}};a(pc,"validateJobOutputs");a(xs,"normalizeJobOutputs")});function yh(t){if(t.inputs===void 0)return;let e=a(()=>{throw Object.assign(new Error("Job inputs must reference verified file transfers with distinct relative destinations"),{code:"invalid_job_inputs"})},"invalid");(!["exec","shell","recipe"].includes(t.type)||!Array.isArray(t.inputs)||t.inputs.length>100)&&e();let r;try{r=xs(t.inputs.map(n=>n?.path)).map(n=>n.path)}catch{e()}for(let[n,i]of t.inputs.entries())(!i||Object.keys(i).some(s=>!["transfer_id","path","sha256","kind","executable"].includes(s))||!/^transfer_[A-Za-z0-9-]{1,100}$/.test(i.transfer_id||"")||!/^[a-f0-9]{64}$/.test(i.sha256||"")||!["file","directory-tar"].includes(i.kind)||i.executable!==void 0&&typeof i.executable!="boolean")&&e(),r.some((s,o)=>n!==o&&s.startsWith(`${r[n]}/`))&&e()}var gh,wh=C(()=>{Rs();gh="jobs.inputs.v1";a(yh,"validateJobInputs")});import{existsSync as Vw,mkdirSync as Jw,readFileSync as fc,rmSync as bh,statSync as Yw,writeFileSync as Kw}from"node:fs";import{uptime as Xw}from"node:os";import{dirname as Zw}from"node:path";import{randomUUID as Qw}from"node:crypto";function _e(t){Jw(Zw(t),{recursive:!0,mode:448});let e=JSON.stringify({pid:process.pid,nonce:Qw()});for(let r=0;r<2;r++)try{Kw(t,e,{flag:"wx",mode:384});break}catch(n){if(n.code!=="EEXIST")throw n;let i=fc(t,"utf8"),s;try{s=JSON.parse(i).pid}catch{throw new Error("Invalid update lock; inspect the owning process before removing it")}if(!Number.isSafeInteger(s)||s<1)throw new Error("Invalid update lock owner");let o=!0;try{process.kill(s,0)}catch(c){c.code==="ESRCH"&&(o=!1)}if(o&&Yw(t).mtimeMs<Date.now()-Xw()*1e3-2e3&&(o=!1),o||r)throw Object.assign(new Error("Another updater is already running"),{code:"update_in_progress"});fc(t,"utf8")===i&&bh(t)}return()=>{Vw(t)&&fc(t,"utf8")===e&&bh(t)}}var ks=C(()=>{a(_e,"acquireProcessLock")});var Sh={};nm(Sh,{collectRunResults:()=>_c,prepareRunFiles:()=>s0});import{existsSync as e0}from"node:fs";import{createHash as t0}from"node:crypto";import{lstat as r0,rm as vh}from"node:fs/promises";import{dirname as n0,join as i0,resolve as Eh}from"node:path";async function s0(t,e,r,n){if(!Array.isArray(n.inputs)||n.inputs.length>100)throw Er("Provide at most 100 input files or directories");let i=n.inputs.map(u=>{if(!u||Object.keys(u).some(h=>!["source","path","include_ignored"].includes(h))||typeof u.source!="string"||!u.source.length||u.source.includes("\0")||u.include_ignored!==void 0&&typeof u.include_ignored!="boolean")throw Er("Each input needs a local source and relative destination path");return{source:Eh(u.source),path:u.path,...u.include_ignored?{include_ignored:!0}:{}}});for(let u of i)if(!e0(u.source))throw Object.assign(new Error(`Input ${u.source} does not exist on this machine (relative paths resolve from ${process.cwd()})`),{code:"input_not_found",retryable:!1,next_action:"Pass the absolute path of the local file or folder"});yh({type:"exec",inputs:i.map(u=>({path:u.path,transfer_id:"transfer_validation",sha256:"0".repeat(64),kind:"file"}))}),pc({type:"exec",outputs:n.outputs});let{node:s}=await t.node(e);if(!s.capabilities?.protocol_features?.includes(gh))throw Er("Upgrade the target agent before preparing job inputs");let o={idempotency_key:n.idempotencyKey,node:s.id,argv:r,inputs:i,outputs:n.outputs??null,workspace:n.workspace??null,workspaceRevision:n.workspaceRevision??null,cwdRelative:n.cwdRelative??null,cwdAlias:n.cwdAlias??null,environmentProfile:n.environmentProfile??null,timeoutSeconds:Number(n.timeoutSeconds)||0,gpu:Number(n.gpu||0),exclusive:!!n.exclusive},c;try{c=_e(i0(n0(n.transferStatePath||jn()),"run-locks",`${mc("prepare",t.serverUrl,n.idempotencyKey)}.lock`))}catch(u){throw u.code==="update_in_progress"?Object.assign(new Error("This run is already preparing its inputs; keep its idempotency key"),{code:"run_in_progress"}):u}let l,d=[];try{l=new zn(n.transferStatePath);for(let[u,h]of i.entries()){n.signal?.throwIfAborted();let f=mc("input",t.serverUrl,n.idempotencyKey,u),p=l.requestRecord(f),m,_=!1;try{let g=p?.input.executable??!!((await r0(h.source)).mode&73),y=h.include_ignored!==!0;p||(m=await ga(h.source,{json:!0,signal:n.signal,stagingDirectory:n.stagingDirectory,gitignore:y}));let w=p?.input.kind||m.kind;l.prepareRequest({serverUrl:t.serverUrl,requestId:f,input:{contract:o,kind:w,executable:g}});let x;if(p?.transfer_id){let k=l.get(p.transfer_id);x=await t.resumeCopy(k.source_path,k.id,k.token,{signal:n.signal})}else{m||=await ga(h.source,{json:!0,signal:n.signal,stagingDirectory:n.stagingDirectory,gitignore:y});let k=m.sha256||await Wr(m.path,{signal:n.signal}),B=`.run-inputs/${k}`;x=await t.copyFile(m.path,s.id,B,{kind:"file",sourceName:k,requestId:f,signal:n.signal,onCreated:a(({transfer:ce,token:ye})=>{l.save({serverUrl:t.serverUrl,requestId:f,transfer:ce,token:ye,sourcePath:m.path,target:s.id,destinationPath:B,temporary:!0}),_=!0},"onCreated")})}if(x.transfer.state!=="completed")throw Er("Input transfer has not completed");let v=l.get(x.transfer.id);d.push({transfer_id:v.id,path:h.path,kind:w,executable:g,sha256:v.transfer.sha256}),l.complete(v.id),await vh(v.source_path,{force:!0})}finally{m&&!_&&await vh(m.path,{force:!0})}}return d}finally{l?.close(),c()}}async function _c(t,e,r,n={}){if(e.state!=="succeeded")return[];if(typeof r!="string"||!r.length)throw Er("Provide a local result directory");if(!Array.isArray(e.payload.task.outputs))throw Er("Declare outputs before requesting local result collection");let i=xs(e.payload.task.outputs),s=new is(n.downloadStatePath,{partRoot:n.downloadPartRoot}),o=[];try{for(let c of i){n.signal?.throwIfAborted();let l=e.output_refs?.find(_=>/^\.outputs-[^/]+\/files\//.test(_.relative_path)&&_.relative_path.slice(_.relative_path.indexOf("/files/")+7)===c.path);if(!l){if(!c.required)continue;throw Er(`No verified output was registered for ${c.path}`)}let d=Eh(r,...c.path.split("/")),u=mc("output",t.serverUrl,e.id,l.artifact_id,d);s.prepareRequest({serverUrl:t.serverUrl,input:{artifact:l.artifact_id},outputPath:d,requestId:u});let h=s.requestRecord(u),f,p;if(h?.download_id)f=s.get(h.download_id),p=(await t.resumeDownload(f.id,f.token)).direct_candidates;else{let _=await t.createArtifactDownload(l.artifact_id,{requestId:u});f=s.saveCreated({serverUrl:t.serverUrl,token:_.token,jobId:e.id,relativePath:l.relative_path,outputPath:d,download:_.download,requestId:u}),p=_.direct_candidates}if(await dh(t,f,p,s,{signal:n.signal}),await Wr(d,{signal:n.signal}).catch(_=>{if(_.code==="ENOENT")return null;throw _})!==l.sha256)throw Object.assign(new Error(`Local result changed: ${d}`),{code:"result_file_changed",next_action:"Choose a new result directory to retrieve the verified output again; do not rerun the command."});o.push({path:d,artifact_id:l.artifact_id,sha256:l.sha256,download_id:f.id})}return o}catch(c){throw c.job_id=e.id,c.next_action||=`Resume result collection for job ${e.id}; the command has already completed and must not be resubmitted with a new key.`,c}finally{s.close()}}function mc(t,...e){return`run-${t}-${t0("sha256").update(JSON.stringify(e)).digest("hex")}`}function Er(t){return Object.assign(new Error(t),{code:"invalid_run_files"})}var gc=C(()=>{qd();ya();mh();Fn();Rs();wh();ks();Ne();a(s0,"prepareRunFiles");a(_c,"collectRunResults");a(mc,"requestKey");a(Er,"invalid")});var Ot=A((xO,tp)=>{"use strict";var Qh=["nodebuffer","arraybuffer","fragments"],ep=typeof Blob<"u";ep&&Qh.push("blob");tp.exports={BINARY_TYPES:Qh,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:ep,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:a(()=>{},"NOOP")}});var ti=A((kO,As)=>{"use strict";var{EMPTY_BUFFER:H0}=Ot(),vc=Buffer[Symbol.species];function G0(t,e){if(t.length===0)return H0;if(t.length===1)return t[0];let r=Buffer.allocUnsafe(e),n=0;for(let i=0;i<t.length;i++){let s=t[i];r.set(s,n),n+=s.length}return n<e?new vc(r.buffer,r.byteOffset,n):r}a(G0,"concat");function rp(t,e,r,n,i){for(let s=0;s<i;s++)r[n+s]=t[s]^e[s&3]}a(rp,"_mask");function np(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}a(np,"_unmask");function V0(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}a(V0,"toArrayBuffer");function Ec(t){if(Ec.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new vc(t):ArrayBuffer.isView(t)?e=new vc(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Ec.readOnly=!1),e}a(Ec,"toBuffer");As.exports={concat:G0,mask:rp,toArrayBuffer:V0,toBuffer:Ec,unmask:np};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=U("bufferutil");As.exports.mask=function(e,r,n,i,s){s<48?rp(e,r,n,i,s):t.mask(e,r,n,i,s)},As.exports.unmask=function(e,r){e.length<32?np(e,r):t.unmask(e,r)}}catch{}});var op=A((IO,sp)=>{"use strict";var ip=Symbol("kDone"),Sc=Symbol("kRun"),Tc=class{static{a(this,"Limiter")}constructor(e){this[ip]=()=>{this.pending--,this[Sc]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Sc]()}[Sc](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[ip])}}};sp.exports=Tc});var tn=A((NO,dp)=>{"use strict";var ri=U("zlib"),ap=ti(),J0=op(),{kStatusCode:cp}=Ot(),Y0=Buffer[Symbol.species],K0=Buffer.from([0,0,255,255]),Ls=Symbol("permessage-deflate"),It=Symbol("total-length"),Qr=Symbol("callback"),Kt=Symbol("buffers"),en=Symbol("error"),Ns,xc=class{static{a(this,"PerMessageDeflate")}constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Ns){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ns=new J0(r)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[Qr];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let r=this._options,n=e.find(i=>!(r.serverNoContextTakeover===!1&&i.server_no_context_takeover||i.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>i.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!i.client_max_window_bits));if(!n)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(n.server_no_context_takeover=!0),r.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(n.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?n.client_max_window_bits=r.clientMaxWindowBits:(n.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let r=e[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(e){return e.forEach(r=>{Object.keys(r).forEach(n=>{let i=r[n];if(i.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(i=i[0],n==="client_max_window_bits"){if(i!==!0){let s=+i;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${n}": ${i}`);i=s}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${i}`)}else if(n==="server_max_window_bits"){let s=+i;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${n}": ${i}`);i=s}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(i!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${i}`)}else throw new Error(`Unknown parameter "${n}"`);r[n]=i})}),e}decompress(e,r,n){Ns.add(i=>{this._decompress(e,r,(s,o)=>{i(),n(s,o)})})}compress(e,r,n){Ns.add(i=>{this._compress(e,r,(s,o)=>{i(),n(s,o)})})}_decompress(e,r,n){let i=this._isServer?"client":"server";if(!this._inflate){let s=`${i}_max_window_bits`,o=typeof this.params[s]!="number"?ri.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=ri.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Ls]=this,this._inflate[It]=0,this._inflate[Kt]=[],this._inflate.on("error",Z0),this._inflate.on("data",lp)}this._inflate[Qr]=n,this._inflate.write(e),r&&this._inflate.write(K0),this._inflate.flush(()=>{let s=this._inflate[en];if(s){this._inflate.close(),this._inflate=null,n(s);return}let o=ap.concat(this._inflate[Kt],this._inflate[It]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[It]=0,this._inflate[Kt]=[],r&&this.params[`${i}_no_context_takeover`]&&this._inflate.reset()),n(null,o)})}_compress(e,r,n){let i=this._isServer?"server":"client";if(!this._deflate){let s=`${i}_max_window_bits`,o=typeof this.params[s]!="number"?ri.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=ri.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[It]=0,this._deflate[Kt]=[],this._deflate.on("data",X0)}this._deflate[Qr]=n,this._deflate.write(e),this._deflate.flush(ri.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=ap.concat(this._deflate[Kt],this._deflate[It]);r&&(s=new Y0(s.buffer,s.byteOffset,s.length-4)),this._deflate[Qr]=null,this._deflate[It]=0,this._deflate[Kt]=[],r&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),n(null,s)})}};dp.exports=xc;function X0(t){this[Kt].push(t),this[It]+=t.length}a(X0,"deflateOnData");function lp(t){if(this[It]+=t.length,this[Ls]._maxPayload<1||this[It]<=this[Ls]._maxPayload){this[Kt].push(t);return}this[en]=new RangeError("Max payload size exceeded"),this[en].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[en][cp]=1009,this.removeListener("data",lp),this.reset()}a(lp,"inflateOnData");function Z0(t){if(this[Ls]._inflate=null,this[en]){this[Qr](this[en]);return}t[cp]=1007,this[Qr](t)}a(Z0,"inflateOnError")});var rn=A((CO,Cs)=>{"use strict";var{isUtf8:up}=U("buffer"),{hasBlob:Q0}=Ot(),eb=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function tb(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}a(tb,"isValidStatusCode");function Rc(t){let e=t.length,r=0;for(;r<e;)if((t[r]&128)===0)r++;else if((t[r]&224)===192){if(r+1===e||(t[r+1]&192)!==128||(t[r]&254)===192)return!1;r+=2}else if((t[r]&240)===224){if(r+2>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||t[r]===224&&(t[r+1]&224)===128||t[r]===237&&(t[r+1]&224)===160)return!1;r+=3}else if((t[r]&248)===240){if(r+3>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||(t[r+3]&192)!==128||t[r]===240&&(t[r+1]&240)===128||t[r]===244&&t[r+1]>143||t[r]>244)return!1;r+=4}else return!1;return!0}a(Rc,"_isValidUTF8");function rb(t){return Q0&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}a(rb,"isBlob");Cs.exports={isBlob:rb,isValidStatusCode:tb,isValidUTF8:Rc,tokenChars:eb};if(up)Cs.exports.isValidUTF8=function(t){return t.length<24?Rc(t):up(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=U("utf-8-validate");Cs.exports.isValidUTF8=function(e){return e.length<32?Rc(e):t(e)}}catch{}});var Nc=A((DO,yp)=>{"use strict";var{Writable:nb}=U("stream"),hp=tn(),{BINARY_TYPES:ib,EMPTY_BUFFER:pp,kStatusCode:sb,kWebSocket:ob}=Ot(),{concat:kc,toArrayBuffer:ab,unmask:cb}=ti(),{isValidStatusCode:lb,isValidUTF8:fp}=rn(),Ps=Buffer[Symbol.species],Ee=0,mp=1,_p=2,gp=3,Oc=4,Ic=5,Ds=6,Ac=class extends nb{static{a(this,"Receiver")}constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||ib[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[ob]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=Ee}_write(e,r,n){if(this._opcode===8&&this._state==Ee)return n();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){n(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new Ps(n.buffer,n.byteOffset+e,n.length-e),new Ps(n.buffer,n.byteOffset,e)}let r=Buffer.allocUnsafe(e);do{let n=this._buffers[0],i=r.length-e;e>=n.length?r.set(this._buffers.shift(),i):(r.set(new Uint8Array(n.buffer,n.byteOffset,e),i),this._buffers[0]=new Ps(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return r}startLoop(e){this._loop=!0;do switch(this._state){case Ee:this.getInfo(e);break;case mp:this.getPayloadLength16(e);break;case _p:this.getPayloadLength64(e);break;case gp:this.getMask();break;case Oc:this.getData(e);break;case Ic:case Ds:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if((r[0]&48)!==0){let i=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(i);return}let n=(r[0]&64)===64;if(n&&!this._extensions[hp.extensionName]){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(n){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(!this._fragmented){let i=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let i=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(i);return}if(n){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let i=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(i);return}}else{let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let i=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(i);return}}else if(this._masked){let i=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(i);return}this._payloadLength===126?this._state=mp:this._payloadLength===127?this._state=_p:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let r=this.consume(8),n=r.readUInt32BE(0);if(n>Math.pow(2,21)-1){let i=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(i);return}this._payloadLength=n*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(r);return}this._masked?this._state=gp:this._state=Oc}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Oc}getData(e){let r=pp;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}r=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&cb(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=Ic,this.decompress(r,e);return}if(r.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let n=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(n);return}this._messageLength=this._totalPayloadLength,this._fragments.push(r)}this.dataMessage(e)}decompress(e,r){this._extensions[hp.extensionName].decompress(e,this._fin,(i,s)=>{if(i)return r(i);if(s.length){if(this._messageLength+=s.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(o);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let o=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");r(o);return}this._fragments.push(s)}this.dataMessage(r),this._state===Ee&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=Ee;return}let r=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let i;this._binaryType==="nodebuffer"?i=kc(n,r):this._binaryType==="arraybuffer"?i=ab(kc(n,r)):this._binaryType==="blob"?i=new Blob(n):i=n,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=Ee):(this._state=Ds,setImmediate(()=>{this.emit("message",i,!0),this._state=Ee,this.startLoop(e)}))}else{let i=kc(n,r);if(!this._skipUTF8Validation&&!fp(i)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(s);return}this._state===Ic||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=Ee):(this._state=Ds,setImmediate(()=>{this.emit("message",i,!1),this._state=Ee,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,pp),this.end();else{let n=e.readUInt16BE(0);if(!lb(n)){let s=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(s);return}let i=new Ps(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!fp(i)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(s);return}this._loop=!1,this.emit("conclude",n,i),this.end()}this._state=Ee;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Ee):(this._state=Ds,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Ee,this.startLoop(r)}))}createError(e,r,n,i,s){this._loop=!1,this._errored=!0;let o=new e(n?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(o,this.createError),o.code=s,o[sb]=i,o}};yp.exports=Ac});var Pc=A((jO,vp)=>{"use strict";var{Duplex:BO}=U("stream"),{randomFillSync:db}=U("crypto"),{types:{isUint8Array:ub}}=U("util"),wp=tn(),{EMPTY_BUFFER:hb,kWebSocket:pb,NOOP:fb}=Ot(),{isBlob:nn,isValidStatusCode:mb}=rn(),{mask:bp,toBuffer:Sr}=ti(),Se=Symbol("kByteLength"),_b=Buffer.alloc(4),Us=8*1024,Tr,sn=Us,De=0,gb=1,yb=2,Lc=class t{static{a(this,"Sender")}constructor(e,r,n){this._extensions=r||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=De,this.onerror=fb,this[pb]=void 0}static frame(e,r){let n,i=!1,s=2,o=!1;r.mask&&(n=r.maskBuffer||_b,r.generateMask?r.generateMask(n):(sn===Us&&(Tr===void 0&&(Tr=Buffer.alloc(Us)),db(Tr,0,Us),sn=0),n[0]=Tr[sn++],n[1]=Tr[sn++],n[2]=Tr[sn++],n[3]=Tr[sn++]),o=(n[0]|n[1]|n[2]|n[3])===0,s=6);let c;typeof e=="string"?(!r.mask||o)&&r[Se]!==void 0?c=r[Se]:(e=Buffer.from(e),c=e.length):(c=e.length,i=r.mask&&r.readOnly&&!o);let l=c;c>=65536?(s+=8,l=127):c>125&&(s+=2,l=126);let d=Buffer.allocUnsafe(i?c+s:s);return d[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(d[0]|=64),d[1]=l,l===126?d.writeUInt16BE(c,2):l===127&&(d[2]=d[3]=0,d.writeUIntBE(c,4,6)),r.mask?(d[1]|=128,d[s-4]=n[0],d[s-3]=n[1],d[s-2]=n[2],d[s-1]=n[3],o?[d,e]:i?(bp(e,n,d,s,c),[d]):(bp(e,n,e,0,c),[d,e])):[d,e]}close(e,r,n,i){let s;if(e===void 0)s=hb;else{if(typeof e!="number"||!mb(e))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)s=Buffer.allocUnsafe(2),s.writeUInt16BE(e,0);else{let c=Buffer.byteLength(r);if(c>123)throw new RangeError("The message must not be greater than 123 bytes");if(s=Buffer.allocUnsafe(2+c),s.writeUInt16BE(e,0),typeof r=="string")s.write(r,2);else if(ub(r))s.set(r,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[Se]:s.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==De?this.enqueue([this.dispatch,s,!1,o,i]):this.sendFrame(t.frame(s,o),i)}ping(e,r,n){let i,s;if(typeof e=="string"?(i=Buffer.byteLength(e),s=!1):nn(e)?(i=e.size,s=!1):(e=Sr(e),i=e.length,s=Sr.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Se]:i,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};nn(e)?this._state!==De?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==De?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(t.frame(e,o),n)}pong(e,r,n){let i,s;if(typeof e=="string"?(i=Buffer.byteLength(e),s=!1):nn(e)?(i=e.size,s=!1):(e=Sr(e),i=e.length,s=Sr.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Se]:i,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};nn(e)?this._state!==De?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==De?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(t.frame(e,o),n)}send(e,r,n){let i=this._extensions[wp.extensionName],s=r.binary?2:1,o=r.compress,c,l;typeof e=="string"?(c=Buffer.byteLength(e),l=!1):nn(e)?(c=e.size,l=!1):(e=Sr(e),c=e.length,l=Sr.readOnly),this._firstFragment?(this._firstFragment=!1,o&&i&&i.params[i._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=c>=i._threshold),this._compress=o):(o=!1,s=0),r.fin&&(this._firstFragment=!0);let d={[Se]:c,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:l,rsv1:o};nn(e)?this._state!==De?this.enqueue([this.getBlobData,e,this._compress,d,n]):this.getBlobData(e,this._compress,d,n):this._state!==De?this.enqueue([this.dispatch,e,this._compress,d,n]):this.dispatch(e,this._compress,d,n)}getBlobData(e,r,n,i){this._bufferedBytes+=n[Se],this._state=yb,e.arrayBuffer().then(s=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(Cc,this,c,i);return}this._bufferedBytes-=n[Se];let o=Sr(s);r?this.dispatch(o,r,n,i):(this._state=De,this.sendFrame(t.frame(o,n),i),this.dequeue())}).catch(s=>{process.nextTick(wb,this,s,i)})}dispatch(e,r,n,i){if(!r){this.sendFrame(t.frame(e,n),i);return}let s=this._extensions[wp.extensionName];this._bufferedBytes+=n[Se],this._state=gb,s.compress(e,n.fin,(o,c)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");Cc(this,l,i);return}this._bufferedBytes-=n[Se],this._state=De,n.readOnly=!1,this.sendFrame(t.frame(c,n),i),this.dequeue()})}dequeue(){for(;this._state===De&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Se],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Se],this._queue.push(e)}sendFrame(e,r){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],r),this._socket.uncork()):this._socket.write(e[0],r)}};vp.exports=Lc;function Cc(t,e,r){typeof r=="function"&&r(e);for(let n=0;n<t._queue.length;n++){let i=t._queue[n],s=i[i.length-1];typeof s=="function"&&s(e)}}a(Cc,"callCallbacks");function wb(t,e,r){Cc(t,e,r),t.onerror(e)}a(wb,"onError")});var Ap=A(($O,Ip)=>{"use strict";var{kForOnEventAttribute:ni,kListener:Dc}=Ot(),Ep=Symbol("kCode"),Sp=Symbol("kData"),Tp=Symbol("kError"),xp=Symbol("kMessage"),Rp=Symbol("kReason"),on=Symbol("kTarget"),kp=Symbol("kType"),Op=Symbol("kWasClean"),At=class{static{a(this,"Event")}constructor(e){this[on]=null,this[kp]=e}get target(){return this[on]}get type(){return this[kp]}};Object.defineProperty(At.prototype,"target",{enumerable:!0});Object.defineProperty(At.prototype,"type",{enumerable:!0});var xr=class extends At{static{a(this,"CloseEvent")}constructor(e,r={}){super(e),this[Ep]=r.code===void 0?0:r.code,this[Rp]=r.reason===void 0?"":r.reason,this[Op]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[Ep]}get reason(){return this[Rp]}get wasClean(){return this[Op]}};Object.defineProperty(xr.prototype,"code",{enumerable:!0});Object.defineProperty(xr.prototype,"reason",{enumerable:!0});Object.defineProperty(xr.prototype,"wasClean",{enumerable:!0});var an=class extends At{static{a(this,"ErrorEvent")}constructor(e,r={}){super(e),this[Tp]=r.error===void 0?null:r.error,this[xp]=r.message===void 0?"":r.message}get error(){return this[Tp]}get message(){return this[xp]}};Object.defineProperty(an.prototype,"error",{enumerable:!0});Object.defineProperty(an.prototype,"message",{enumerable:!0});var ii=class extends At{static{a(this,"MessageEvent")}constructor(e,r={}){super(e),this[Sp]=r.data===void 0?null:r.data}get data(){return this[Sp]}};Object.defineProperty(ii.prototype,"data",{enumerable:!0});var bb={addEventListener(t,e,r={}){for(let i of this.listeners(t))if(!r[ni]&&i[Dc]===e&&!i[ni])return;let n;if(t==="message")n=a(function(s,o){let c=new ii("message",{data:o?s:s.toString()});c[on]=this,Bs(e,this,c)},"onMessage");else if(t==="close")n=a(function(s,o){let c=new xr("close",{code:s,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[on]=this,Bs(e,this,c)},"onClose");else if(t==="error")n=a(function(s){let o=new an("error",{error:s,message:s.message});o[on]=this,Bs(e,this,o)},"onError");else if(t==="open")n=a(function(){let s=new At("open");s[on]=this,Bs(e,this,s)},"onOpen");else return;n[ni]=!!r[ni],n[Dc]=e,r.once?this.once(t,n):this.on(t,n)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[Dc]===e&&!r[ni]){this.removeListener(t,r);break}}};Ip.exports={CloseEvent:xr,ErrorEvent:an,Event:At,EventTarget:bb,MessageEvent:ii};function Bs(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}a(Bs,"callListener")});var js=A((FO,Np)=>{"use strict";var{tokenChars:si}=rn();function tt(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}a(tt,"push");function vb(t){let e=Object.create(null),r=Object.create(null),n=!1,i=!1,s=!1,o,c,l=-1,d=-1,u=-1,h=0;for(;h<t.length;h++)if(d=t.charCodeAt(h),o===void 0)if(u===-1&&si[d]===1)l===-1&&(l=h);else if(h!==0&&(d===32||d===9))u===-1&&l!==-1&&(u=h);else if(d===59||d===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${h}`);u===-1&&(u=h);let p=t.slice(l,u);d===44?(tt(e,p,r),r=Object.create(null)):o=p,l=u=-1}else throw new SyntaxError(`Unexpected character at index ${h}`);else if(c===void 0)if(u===-1&&si[d]===1)l===-1&&(l=h);else if(d===32||d===9)u===-1&&l!==-1&&(u=h);else if(d===59||d===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${h}`);u===-1&&(u=h),tt(r,t.slice(l,u),!0),d===44&&(tt(e,o,r),r=Object.create(null),o=void 0),l=u=-1}else if(d===61&&l!==-1&&u===-1)c=t.slice(l,h),l=u=-1;else throw new SyntaxError(`Unexpected character at index ${h}`);else if(i){if(si[d]!==1)throw new SyntaxError(`Unexpected character at index ${h}`);l===-1?l=h:n||(n=!0),i=!1}else if(s)if(si[d]===1)l===-1&&(l=h);else if(d===34&&l!==-1)s=!1,u=h;else if(d===92)i=!0;else throw new SyntaxError(`Unexpected character at index ${h}`);else if(d===34&&t.charCodeAt(h-1)===61)s=!0;else if(u===-1&&si[d]===1)l===-1&&(l=h);else if(l!==-1&&(d===32||d===9))u===-1&&(u=h);else if(d===59||d===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${h}`);u===-1&&(u=h);let p=t.slice(l,u);n&&(p=p.replace(/\\/g,""),n=!1),tt(r,c,p),d===44&&(tt(e,o,r),r=Object.create(null),o=void 0),c=void 0,l=u=-1}else throw new SyntaxError(`Unexpected character at index ${h}`);if(l===-1||s||d===32||d===9)throw new SyntaxError("Unexpected end of input");u===-1&&(u=h);let f=t.slice(l,u);return o===void 0?tt(e,f,r):(c===void 0?tt(r,f,!0):n?tt(r,c,f.replace(/\\/g,"")):tt(r,c,f),tt(e,o,r)),e}a(vb,"parse");function Eb(t){return Object.keys(t).map(e=>{let r=t[e];return Array.isArray(r)||(r=[r]),r.map(n=>[e].concat(Object.keys(n).map(i=>{let s=n[i];return Array.isArray(s)||(s=[s]),s.map(o=>o===!0?i:`${i}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}a(Eb,"format");Np.exports={format:Eb,parse:vb}});var Fs=A((GO,zp)=>{"use strict";var Sb=U("events"),Tb=U("https"),xb=U("http"),Pp=U("net"),Rb=U("tls"),{randomBytes:kb,createHash:Ob}=U("crypto"),{Duplex:WO,Readable:HO}=U("stream"),{URL:Uc}=U("url"),Xt=tn(),Ib=Nc(),Ab=Pc(),{isBlob:Nb}=rn(),{BINARY_TYPES:Lp,CLOSE_TIMEOUT:Lb,EMPTY_BUFFER:Ms,GUID:Cb,kForOnEventAttribute:Bc,kListener:Pb,kStatusCode:Db,kWebSocket:Z,NOOP:Dp}=Ot(),{EventTarget:{addEventListener:Ub,removeEventListener:Bb}}=Ap(),{format:jb,parse:Mb}=js(),{toBuffer:$b}=ti(),Up=Symbol("kAborted"),jc=[8,13],Nt=["CONNECTING","OPEN","CLOSING","CLOSED"],qb=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,$=class t extends Sb{static{a(this,"WebSocket")}constructor(e,r,n){super(),this._binaryType=Lp[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Ms,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(n=r,r=[]):r=[r]),Bp(this,e,r,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Lp.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,r,n){let i=new Ib({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:n.maxBufferedChunks,maxFragments:n.maxFragments,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),s=new Ab(e,this._extensions,n.generateMask);this._receiver=i,this._sender=s,this._socket=e,i[Z]=this,s[Z]=this,e[Z]=this,i.on("conclude",Wb),i.on("drain",Hb),i.on("error",Gb),i.on("message",Vb),i.on("ping",Jb),i.on("pong",Yb),s.onerror=Kb,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",$p),e.on("data",qs),e.on("end",qp),e.on("error",Fp),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Xt.extensionName]&&this._extensions[Xt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,r){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ge(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,r,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Mp(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Mc(this,e,n);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||Ms,r,n)}pong(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Mc(this,e,n);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||Ms,r,n)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(n=r,r={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Mc(this,e,n);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[Xt.extensionName]||(i.compress=!1),this._sender.send(e||Ms,i,n)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ge(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty($,"CONNECTING",{enumerable:!0,value:Nt.indexOf("CONNECTING")});Object.defineProperty($.prototype,"CONNECTING",{enumerable:!0,value:Nt.indexOf("CONNECTING")});Object.defineProperty($,"OPEN",{enumerable:!0,value:Nt.indexOf("OPEN")});Object.defineProperty($.prototype,"OPEN",{enumerable:!0,value:Nt.indexOf("OPEN")});Object.defineProperty($,"CLOSING",{enumerable:!0,value:Nt.indexOf("CLOSING")});Object.defineProperty($.prototype,"CLOSING",{enumerable:!0,value:Nt.indexOf("CLOSING")});Object.defineProperty($,"CLOSED",{enumerable:!0,value:Nt.indexOf("CLOSED")});Object.defineProperty($.prototype,"CLOSED",{enumerable:!0,value:Nt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty($.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty($.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Bc])return e[Pb];return null},set(e){for(let r of this.listeners(t))if(r[Bc]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[Bc]:!0})}})});$.prototype.addEventListener=Ub;$.prototype.removeEventListener=Bb;zp.exports=$;function Bp(t,e,r,n){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Lb,protocolVersion:jc[1],maxBufferedChunks:1048576,maxFragments:131072,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=i.autoPong,t._closeTimeout=i.closeTimeout,!jc.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${jc.join(", ")})`);let s;if(e instanceof Uc)s=e;else try{s=new Uc(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}s.protocol==="http:"?s.protocol="ws:":s.protocol==="https:"&&(s.protocol="wss:"),t._url=s.href;let o=s.protocol==="wss:",c=s.protocol==="ws+unix:",l;if(s.protocol!=="ws:"&&!o&&!c?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:c&&!s.pathname?l="The URL's pathname is empty":s.hash&&(l="The URL contains a fragment identifier"),l){let _=new SyntaxError(l);if(t._redirects===0)throw _;$s(t,_);return}let d=o?443:80,u=kb(16).toString("base64"),h=o?Tb.request:xb.request,f=new Set,p;if(i.createConnection=i.createConnection||(o?zb:Fb),i.defaultPort=i.defaultPort||d,i.port=s.port||d,i.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},i.path=s.pathname+s.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(p=new Xt({...i.perMessageDeflate,isServer:!1,maxPayload:i.maxPayload}),i.headers["Sec-WebSocket-Extensions"]=jb({[Xt.extensionName]:p.offer()})),r.length){for(let _ of r){if(typeof _!="string"||!qb.test(_)||f.has(_))throw new SyntaxError("An invalid or duplicated subprotocol was specified");f.add(_)}i.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(s.username||s.password)&&(i.auth=`${s.username}:${s.password}`),c){let _=i.path.split(":");i.socketPath=_[0],i.path=_[1]}let m;if(i.followRedirects){if(t._redirects===0){t._originalIpc=c,t._originalSecure=o,t._originalHostOrSocketPath=c?i.socketPath:s.host;let _=n&&n.headers;if(n={...n,headers:{}},_)for(let[g,y]of Object.entries(_))n.headers[g.toLowerCase()]=y}else if(t.listenerCount("redirect")===0){let _=c?t._originalIpc?i.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:s.host===t._originalHostOrSocketPath;(!_||t._originalSecure&&!o)&&(delete i.headers.authorization,delete i.headers.cookie,_||delete i.headers.host,i.auth=void 0)}i.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),m=t._req=h(i),t._redirects&&t.emit("redirect",t.url,m)}else m=t._req=h(i);i.timeout&&m.on("timeout",()=>{ge(t,m,"Opening handshake has timed out")}),m.on("error",_=>{m===null||m[Up]||(m=t._req=null,$s(t,_))}),m.on("response",_=>{let g=_.headers.location,y=_.statusCode;if(g&&i.followRedirects&&y>=300&&y<400){if(++t._redirects>i.maxRedirects){ge(t,m,"Maximum redirects exceeded");return}m.abort();let w;try{w=new Uc(g,e)}catch{let v=new SyntaxError(`Invalid URL: ${g}`);$s(t,v);return}Bp(t,w,r,n)}else t.emit("unexpected-response",m,_)||ge(t,m,`Unexpected server response: ${_.statusCode}`)}),m.on("upgrade",(_,g,y)=>{if(t.emit("upgrade",_),t.readyState!==$.CONNECTING)return;m=t._req=null;let w=_.headers.upgrade;if(w===void 0||w.toLowerCase()!=="websocket"){ge(t,g,"Invalid Upgrade header");return}let x=Ob("sha1").update(u+Cb).digest("base64");if(_.headers["sec-websocket-accept"]!==x){ge(t,g,"Invalid Sec-WebSocket-Accept header");return}let v=_.headers["sec-websocket-protocol"],k;if(v!==void 0?f.size?f.has(v)||(k="Server sent an invalid subprotocol"):k="Server sent a subprotocol but none was requested":f.size&&(k="Server sent no subprotocol"),k){ge(t,g,k);return}v&&(t._protocol=v);let B=_.headers["sec-websocket-extensions"];if(B!==void 0){if(!p){ge(t,g,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let ce;try{ce=Mb(B)}catch{ge(t,g,"Invalid Sec-WebSocket-Extensions header");return}let ye=Object.keys(ce);if(ye.length!==1||ye[0]!==Xt.extensionName){ge(t,g,"Server indicated an extension that was not requested");return}try{p.accept(ce[Xt.extensionName])}catch{ge(t,g,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Xt.extensionName]=p}t.setSocket(g,y,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxBufferedChunks:i.maxBufferedChunks,maxFragments:i.maxFragments,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(m,t):m.end()}a(Bp,"initAsClient");function $s(t,e){t._readyState=$.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}a($s,"emitErrorAndClose");function Fb(t){return t.path=t.socketPath,Pp.connect(t)}a(Fb,"netConnect");function zb(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Pp.isIP(t.host)?"":t.host),Rb.connect(t)}a(zb,"tlsConnect");function ge(t,e,r){t._readyState=$.CLOSING;let n=new Error(r);Error.captureStackTrace(n,ge),e.setHeader?(e[Up]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick($s,t,n)):(e.destroy(n),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}a(ge,"abortHandshake");function Mc(t,e,r){if(e){let n=Nb(e)?e.size:$b(e).length;t._socket?t._sender._bufferedBytes+=n:t._bufferedAmount+=n}if(r){let n=new Error(`WebSocket is not open: readyState ${t.readyState} (${Nt[t.readyState]})`);process.nextTick(r,n)}}a(Mc,"sendAfterClose");function Wb(t,e){let r=this[Z];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[Z]!==void 0&&(r._socket.removeListener("data",qs),process.nextTick(jp,r._socket),t===1005?r.close():r.close(t,e))}a(Wb,"receiverOnConclude");function Hb(){let t=this[Z];t.isPaused||t._socket.resume()}a(Hb,"receiverOnDrain");function Gb(t){let e=this[Z];e._socket[Z]!==void 0&&(e._socket.removeListener("data",qs),process.nextTick(jp,e._socket),e.close(t[Db])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}a(Gb,"receiverOnError");function Cp(){this[Z].emitClose()}a(Cp,"receiverOnFinish");function Vb(t,e){this[Z].emit("message",t,e)}a(Vb,"receiverOnMessage");function Jb(t){let e=this[Z];e._autoPong&&e.pong(t,!this._isServer,Dp),e.emit("ping",t)}a(Jb,"receiverOnPing");function Yb(t){this[Z].emit("pong",t)}a(Yb,"receiverOnPong");function jp(t){t.resume()}a(jp,"resume");function Kb(t){let e=this[Z];e.readyState!==$.CLOSED&&(e.readyState===$.OPEN&&(e._readyState=$.CLOSING,Mp(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}a(Kb,"senderOnError");function Mp(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}a(Mp,"setCloseTimer");function $p(){let t=this[Z];if(this.removeListener("close",$p),this.removeListener("data",qs),this.removeListener("end",qp),t._readyState=$.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[Z]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Cp),t._receiver.on("finish",Cp))}a($p,"socketOnClose");function qs(t){this[Z]._receiver.write(t)||this.pause()}a(qs,"socketOnData");function qp(){let t=this[Z];t._readyState=$.CLOSING,t._receiver.end(),this.end()}a(qp,"socketOnEnd");function Fp(){let t=this[Z];this.removeListener("error",Fp),this.on("error",Dp),t&&(t._readyState=$.CLOSING,this.destroy())}a(Fp,"socketOnError")});var Vp=A((YO,Gp)=>{"use strict";var JO=Fs(),{Duplex:Xb}=U("stream");function Wp(t){t.emit("close")}a(Wp,"emitClose");function Zb(){!this.destroyed&&this._writableState.finished&&this.destroy()}a(Zb,"duplexOnEnd");function Hp(t){this.removeListener("error",Hp),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}a(Hp,"duplexOnError");function Qb(t,e){let r=!0,n=new Xb({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",a(function(s,o){let c=!o&&n._readableState.objectMode?s.toString():s;n.push(c)||t.pause()},"message")),t.once("error",a(function(s){n.destroyed||(r=!1,n.destroy(s))},"error")),t.once("close",a(function(){n.destroyed||n.push(null)},"close")),n._destroy=function(i,s){if(t.readyState===t.CLOSED){s(i),process.nextTick(Wp,n);return}let o=!1;t.once("error",a(function(l){o=!0,s(l)},"error")),t.once("close",a(function(){o||s(i),process.nextTick(Wp,n)},"close")),r&&t.terminate()},n._final=function(i){if(t.readyState===t.CONNECTING){t.once("open",a(function(){n._final(i)},"open"));return}t._socket!==null&&(t._socket._writableState.finished?(i(),n._readableState.endEmitted&&n.destroy()):(t._socket.once("finish",a(function(){i()},"finish")),t.close()))},n._read=function(){t.isPaused&&t.resume()},n._write=function(i,s,o){if(t.readyState===t.CONNECTING){t.once("open",a(function(){n._write(i,s,o)},"open"));return}t.send(i,o)},n.on("end",Zb),n.on("error",Hp),n}a(Qb,"createWebSocketStream");Gp.exports=Qb});var $c=A((XO,Jp)=>{"use strict";var{tokenChars:ev}=rn();function tv(t){let e=new Set,r=-1,n=-1,i=0;for(i;i<t.length;i++){let o=t.charCodeAt(i);if(n===-1&&ev[o]===1)r===-1&&(r=i);else if(i!==0&&(o===32||o===9))n===-1&&r!==-1&&(n=i);else if(o===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${i}`);n===-1&&(n=i);let c=t.slice(r,n);if(e.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);e.add(c),r=n=-1}else throw new SyntaxError(`Unexpected character at index ${i}`)}if(r===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let s=t.slice(r,i);if(e.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);return e.add(s),e}a(tv,"parse");Jp.exports={parse:tv}});var tf=A((eI,ef)=>{"use strict";var rv=U("events"),zs=U("http"),{Duplex:QO}=U("stream"),{createHash:nv}=U("crypto"),Yp=js(),Rr=tn(),iv=$c(),sv=Fs(),{CLOSE_TIMEOUT:ov,GUID:av,kWebSocket:cv}=Ot(),lv=/^[+/0-9A-Za-z]{22}==$/,Kp=0,Xp=1,Qp=2,qc=class extends rv{static{a(this,"WebSocketServer")}constructor(e,r){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:ov,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:sv,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=zs.createServer((n,i)=>{let s=zs.STATUS_CODES[426];i.writeHead(426,{"Content-Length":s.length,"Content-Type":"text/plain"}),i.end(s)}),this._server.listen(e.port,e.host,e.backlog,r)):e.server&&(this._server=e.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=dv(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:a((i,s,o)=>{this.handleUpgrade(i,s,o,n)},"upgrade")})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Kp}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Qp){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(oi,this);return}if(e&&this.once("close",e),this._state!==Xp)if(this._state=Xp,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(oi,this):process.nextTick(oi,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{oi(this)})}}shouldHandle(e){if(this.options.path){let r=e.url.indexOf("?");if((r!==-1?e.url.slice(0,r):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,r,n,i){r.on("error",Zp);let s=e.headers["sec-websocket-key"],o=e.headers.upgrade,c=+e.headers["sec-websocket-version"];if(e.method!=="GET"){kr(this,e,r,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){kr(this,e,r,400,"Invalid Upgrade header");return}if(s===void 0||!lv.test(s)){kr(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){kr(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){ai(r,400);return}let l=e.headers["sec-websocket-protocol"],d=new Set;if(l!==void 0)try{d=iv.parse(l)}catch{kr(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let u=e.headers["sec-websocket-extensions"],h={};if(this.options.perMessageDeflate&&u!==void 0){let f=new Rr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let p=Yp.parse(u);p[Rr.extensionName]&&(f.accept(p[Rr.extensionName]),h[Rr.extensionName]=f)}catch{kr(this,e,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let f={origin:e.headers[`${c===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(f,(p,m,_,g)=>{if(!p)return ai(r,m||401,_,g);this.completeUpgrade(h,s,d,e,r,n,i)});return}if(!this.options.verifyClient(f))return ai(r,401)}this.completeUpgrade(h,s,d,e,r,n,i)}completeUpgrade(e,r,n,i,s,o,c){if(!s.readable||!s.writable)return s.destroy();if(s[cv])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Kp)return ai(s,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${nv("sha1").update(r+av).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(n.size){let h=this.options.handleProtocols?this.options.handleProtocols(n,i):n.values().next().value;h&&(d.push(`Sec-WebSocket-Protocol: ${h}`),u._protocol=h)}if(e[Rr.extensionName]){let h=e[Rr.extensionName].params,f=Yp.format({[Rr.extensionName]:[h]});d.push(`Sec-WebSocket-Extensions: ${f}`),u._extensions=e}this.emit("headers",d,i),s.write(d.concat(`\r
91
+ `).join(`\r
92
+ `)),s.removeListener("error",Zp),u.setSocket(s,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(u),u.on("close",()=>{this.clients.delete(u),this._shouldEmitClose&&!this.clients.size&&process.nextTick(oi,this)})),c(u,i)}};ef.exports=qc;function dv(t,e){for(let r of Object.keys(e))t.on(r,e[r]);return a(function(){for(let n of Object.keys(e))t.removeListener(n,e[n])},"removeListeners")}a(dv,"addListeners");function oi(t){t._state=Qp,t.emit("close")}a(oi,"emitClose");function Zp(){this.destroy()}a(Zp,"socketOnError");function ai(t,e,r,n){r=r||zs.STATUS_CODES[e],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...n},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${zs.STATUS_CODES[e]}\r
93
+ `+Object.keys(n).map(i=>`${i}: ${n[i]}`).join(`\r
94
+ `)+`\r
95
+ \r
96
+ `+r)}a(ai,"abortHandshake");function kr(t,e,r,n,i,s){if(t.listenerCount("wsClientError")){let o=new Error(i);Error.captureStackTrace(o,kr),t.emit("wsClientError",o,r,e)}else ai(r,n,i,s)}a(kr,"abortHandshakeOrEmitwsClientError")});le();var sm=Object.freeze(["darwin","win32"]),bS=Object.freeze(["machine","server"]);function nl(t){return sm.includes(t)?"machine":"server"}a(nl,"nodeKind");gc();ve();import{createHash as o0}from"node:crypto";var a0=12e4;var Th=200,xh=/(^|\/)(node_modules|\.venv|venv|__pycache__|\.tox|target|\.gradle|Pods|\.next|\.nuxt|vendor\/bundle|dist|build|out|coverage|\.cache|\.pytest_cache|\.mypy_cache|\.ruff_cache)\/?$|(^|\/)(\.DS_Store|Thumbs\.db)$|\.(pyc|log)$/i;async function Os(t,e,r,{script:n=!1,idempotencyKey:i,signal:s,timeoutMs:o=a0}={}){let{job:c}=await t.run(e,n?void 0:r,{...n?{script:r}:{},ifOffline:"fail",idempotencyKey:i,signal:s,timeoutSeconds:Math.ceil(o/1e3)}),l=AbortSignal.timeout(o),d=await t.followJob(c.id,{signal:s?AbortSignal.any([s,l]):l}),u="",h="";return await t.eachJobPage(c.id,"logs",f=>{for(let p of f||[])p.stream==="stderr"?h+=p.text:u+=p.text},{signal:s}),{job_id:c.id,state:d.state,exit_code:d.result?.exit_code,stdout:u,stderr:h}}a(Os,"runToEnd");function Rh(t){return/^[A-Za-z]:[\\/]/.test(t)||t.includes("\\")&&!t.includes("/")}a(Rh,"looksWindows");function c0(t,e){let r=t.replace(/[\\/]+$/,"")||t,n=`rc-${o0("sha256").update(String(e)).digest("hex").slice(0,8)}`;return{base:r,name:n,branch:`interscale/${n}`,path:`${r}-worktrees${Rh(t)?"\\":"/"}${n}`}}a(c0,"worktreePlan");function yc(t,e){let r=(e.stderr||e.stdout).trim().slice(-500)||`job ${e.state}`;return Object.assign(new Error(`git worktree add failed on ${t}: ${r}`),{code:"worktree_failed",retryable:!1,next_action:"Check that cwd is in a git repository on that machine (git installed, no folder in the way), or start without worktree"})}a(yc,"worktreeError");async function kh(t,e,r,{requestId:n,signal:i}={}){let s=await Os(t,e,["git","-C",r,"rev-parse","--show-toplevel","--show-prefix"],{signal:i});if(s.state!=="succeeded")throw yc(e,s);let[o="",c=""]=s.stdout.split(/\r?\n/).map(_=>_.trim());if(!o)throw yc(e,s);let l=Rh(r),d=a(_=>l?_.replace(/\//g,"\\"):_,"native"),u=c0(d(o),n),h=d(c.replace(/\/+$/,"")),f={path:u.path,cwd:h?`${u.path}${l?"\\":"/"}${h}`:u.path,branch:u.branch,base:u.base},p=await Os(t,e,["git","-C",u.base,"worktree","add","-b",u.branch,u.path],{signal:i});if(p.state==="succeeded")return{...f,created:!0};let m=await Os(t,e,["git","-C",u.path,"rev-parse","--abbrev-ref","HEAD"],{signal:i});if(m.state==="succeeded"&&m.stdout.trim()===u.branch)return{...f,created:!1};throw yc(e,p)}a(kh,"prepareWorktree");function l0(t){let e="git ls-files --others --ignored --exclude-standard --directory";return[["toplevel","git rev-parse --show-toplevel"],["status","git status --porcelain=v1 --branch --untracked-files=normal"],["upstream","git rev-parse --abbrev-ref --symbolic-full-name '@{u}'"],["unpushed","git rev-list --count '@{u}..HEAD'"],["local_only","git rev-list --count --branches --tags --not --remotes"],["local_refs","git log --branches --tags --not --remotes --simplify-by-decoration --format=%D"],["stash","git stash list"],["worktrees","git worktree list --porcelain"],["submodules","git submodule status --recursive"],["lfs","git lfs ls-files --name-only"],["lfsattr","git grep -c filter=lfs HEAD .gitattributes"],["ignored",t?`${e} | Select-Object -First ${Th}`:`${e} | head -n ${Th}`],["ignored_count",t?`(${e} | Measure-Object -Line).Lines`:`${e} | wc -l`],["remotes","git remote -v"]]}a(l0,"preflightCommands");function d0(t,e){let r=e==="win32",n=a(s=>r?`'${s.replace(/'/g,"''")}'`:`'${s.replace(/'/g,"'\\''")}'`,"quote"),i=r?[`Set-Location -LiteralPath ${n(t)}`,"if (-not $?) { exit 3 }"]:[`cd ${n(t)} || exit 3`];for(let[s,o]of l0(r))i.push(`echo '@@${s}'`,o);return i.push("echo '@@end'"),`${i.join(`
97
+ `)}
98
+ `}a(d0,"preflightScript");function u0(t){let e={},r=null;for(let n of String(t).split(/\r?\n/)){let i=n.match(/^@@([a-z_]+)$/);if(i){r=i[1],e[r]=[];continue}r&&n.trim()&&e[r].push(n)}return e}a(u0,"parsePreflight");function h0(t,{node:e,path:r}){if(!t.end)throw Object.assign(new Error(`The preflight on ${e} stopped before its end`),{code:"preflight_incomplete"});let n=t.status||[];if(!n[0]?.startsWith("## "))throw Object.assign(new Error(`${r} on ${e} is not a git repository`),{code:"not_a_repository",next_action:"Give a folder inside the repository; a folder without git is copied as files with interscale_transfer_start"});let i=n[0].slice(3),s=/^HEAD \(no branch\)/.test(i)?null:i.replace(/^No commits yet on /,"").split("...")[0].trim(),o=n.slice(1),c=o.filter(F=>F.startsWith("?? ")).length,l=o.filter(F=>/^(DD|AU|UD|UA|DU|AA|UU) /.test(F)).length,d=o.length-c,u=t.upstream?.[0]?.trim()||null,h=u?Number(t.unpushed?.[0])||0:null,f=Number(t.local_only?.[0])||0,p=(t.local_refs||[]).map(F=>F.trim()).filter(Boolean),m=(t.stash||[]).length,_=a(F=>F.replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase(),"same"),g=t.toplevel?.[0]?.trim()||r,y=(t.worktrees||[]).filter(F=>F.startsWith("worktree ")).map(F=>F.slice(9)).filter(F=>_(F)!==_(g)),w=(t.submodules||[]).length,x=(t.lfs||[]).length,v=x>0||(t.lfsattr||[]).length>0,k=t.ignored||[],B=Math.max(k.length,Number(t.ignored_count?.[0])||0),ce=[...new Set((t.remotes||[]).map(F=>F.split(/\s+/)[0]))],ye=k.filter(F=>xh.test(F)),L=k.filter(F=>!xh.test(F)),ie=B-k.length,se=[];d&&se.push(`${d} uncommitted change(s)${l?`, ${l} in conflict`:""}`),c&&se.push(`${c} untracked path(s)`),ce.length?f&&se.push(`${f} commit(s) on no remote${p.length?` (${p.slice(0,5).join("; ")})`:""}`):se.push("no git remote: the history exists only on this machine"),m&&se.push(`${m} stash(es): a stash never leaves its machine`),y.length&&se.push(`${y.length} other worktree(s): ${y.slice(0,5).join(", ")}`),L.length&&se.push(`${L.length} ignored path(s) a clone will not bring: ${L.slice(0,10).join(", ")}${L.length>10?", ...":""}`),ie>0&&se.push(`${ie} more ignored path(s) not listed: check them before retiring this copy`);let Qt=[];return w&&Qt.push(`${w} submodule(s): clone with --recurse-submodules`),v&&Qt.push(`Git LFS in use${x?` (${x} files)`:""}: install git-lfs on the destination`),ye.length&&Qt.push(`rebuild or regenerate on the destination, for its OS: ${ye.slice(0,10).join(", ")}`),{node:e,path:r,top:g,branch:s,upstream:u,unpushed:h,local_only:f,uncommitted:d,conflicted:l,untracked:c,stashes:m,other_worktrees:y,submodules:w,lfs_files:x,remotes:ce,ignored_count:B,verdict:se.length?"copy_needed":"git_sync",carry:se,notes:Qt,next_action:se.length?"Commit and push what is listed in carry (or copy it with interscale_transfer_start), then clone on the destination":"Clone or pull on the destination: everything here is in git on a remote"}}a(h0,"preflightReport");async function Oh(t,e,r,{signal:n}={}){let i=(await t.node(e)).node.platform,s=await Os(t,e,d0(r,i),{script:!0,signal:n}),o=u0(s.stdout);if(!o.end)throw Object.assign(new Error(`The preflight on ${e} stopped early (${s.state}${s.exit_code===3?`: cannot open ${r}`:""})`),{code:"preflight_incomplete",job_id:s.job_id,next_action:"Check the path on that machine, then retry"});return{...h0(o,{node:e,path:r}),job_id:s.job_id}}a(Oh,"repoPreflight");ve();var Yt={limit:{type:"integer",minimum:1,maximum:1e3},cursor:{type:"string",maxLength:16e3}},p0=[...new Set([...Object.keys(ou),...Jn])],Ih={query:{type:"string",maxLength:1e3},node:{type:"string"},library:{type:"string",maxLength:4e3},relative_path:{type:"string",maxLength:4e3},...Yt},Ah={artifact:{type:"string",minLength:1,maxLength:1e3},...Yt},Nh={node:{type:"string"},kind:{type:"string",enum:["all","user","job"]},...Yt},Lh={node:{type:"string"},state:{type:"string",enum:p0},...Yt},Ch={node:{type:"string"},query:{type:"string",maxLength:200},...Yt};Rs();le();var f0=["hardware","gpus","runtimes","frameworks","tools","network","protocol_features"],Ph={section:{type:"string",enum:f0},limit:{type:"integer",minimum:1,maximum:1e3},cursor:{type:"string",maxLength:16e3}};var m0=/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/,Dh={environment_profile:{type:"string",minLength:1,maxLength:100,description:"Environment profile configured on the machine; its values stay there"}};function Uh(t){if(t===void 0)return;let e=a(i=>i&&typeof i=="object"&&!Array.isArray(i),"record"),r=a(()=>{throw new Error("Invalid environment profiles: use at most 100 named maps, 256 unique variable names per profile, 64 KiB per profile and 512 KiB total, without NUL characters")},"fail");(!e(t)||Object.keys(t).length>100)&&r();let n=0;for(let[i,s]of Object.entries(t)){(!m0.test(i)||!e(s)||Object.keys(s).length>256)&&r();let o=0,c=new Set;for(let[l,d]of Object.entries(s))(!/^[A-Za-z_][A-Za-z0-9_]{0,127}$/.test(l)||typeof d!="string"||d.includes("\0")||d.length>32768||c.has(l.toUpperCase()))&&r(),c.add(l.toUpperCase()),o+=Buffer.byteLength(l)+Buffer.byteLength(d)+2,o>64*1024&&r();n+=o+Buffer.byteLength(i),n>512*1024&&r()}}a(Uh,"validateEnvironmentProfiles");import{posix as Rk,win32 as kk,isAbsolute as _0}from"node:path";function Bh(t){if(t===void 0)return;let e=a(()=>{throw new Error("Invalid workspace aliases: use at most 1000 named absolute paths, without NUL characters, within 256 KiB")},"invalid");(!t||typeof t!="object"||Array.isArray(t)||Object.keys(t).length>1e3)&&e();let r=0;for(let[n,i]of Object.entries(t))(!n.length||n.length>200||n.includes("\0")||typeof i!="string"||i.length>32768||i.includes("\0")||!_0(i))&&e(),r+=Buffer.byteLength(JSON.stringify([n,i])),r>256*1024&&e()}a(Bh,"validateWorkspaceAliases");var jh={workspace:{type:"string",minLength:1,maxLength:200,description:"Configured workspace alias from node context"},workspace_revision:{type:"string",pattern:"^[a-f0-9]{64}$",description:"Context revision; a changed alias is refused before running"},cwd_relative:{type:"string",minLength:1,maxLength:4e3,description:"Existing subdirectory within the workspace; defaults to its root"}};var Mh={query:{type:"string",minLength:1,maxLength:200},source:{type:"string",enum:["index","live"],default:"index"},path:{type:"string",minLength:1,maxLength:32768},library:{type:"string",minLength:1,maxLength:200},limit:{type:"integer",minimum:1,maximum:1e3,default:100},cursor:{type:"string",maxLength:16e3}};import{existsSync as D0,readFileSync as U0}from"node:fs";import{dirname as B0,join as j0,resolve as Xh}from"node:path";import{fileURLToPath as M0}from"node:url";ve();le();import{setTimeout as g0}from"node:timers/promises";async function wc(t,e,r={}){let n=new URL(e,v0(t)),i=new Headers(r.headers||{});r.token&&i.set("authorization",`Bearer ${r.token}`);let s;r.json!==void 0&&(i.set("content-type","application/json"),s=JSON.stringify(r.json));let o=(r.method||(s?"POST":"GET")).toUpperCase(),c=o==="GET"||o==="HEAD",l=c?r.readRetries??2:0;if(!Number.isInteger(l)||l<0||l>2)throw new Error("readRetries must be between zero and two");let d=r.maxResponseBytes??8*1024*1024;if(!Number.isSafeInteger(d)||d<0||d>64*1024*1024)throw new Error("maxResponseBytes must be between zero and 64 MiB");let u=AbortSignal.timeout(r.timeoutMs??(c?1e4:2e4)),h=r.signal?AbortSignal.any([r.signal,u]):u;for(let p=0;;p+=1){let m,_;try{m=await fetch(n,{method:o,headers:i,body:s,signal:h}),_=await b0(m,d)}catch(y){if(y.code==="response_too_large"&&c)throw y;if(p<l&&!h.aborted&&y.code!=="response_too_large"){try{await $h(p,null,h,r)}catch(w){throw f(w)}continue}throw f(y)}let g={};if(_)try{g=JSON.parse(_)}catch{if(m.ok)throw new M("invalid_server_response",`Le serveur a r\xE9pondu avec un contenu invalide (${m.status}).`)}if(!m.ok){if(p<l&&[429,502,503,504].includes(m.status)&&g?.error?.retryable!==!1&&g?.error?.terminal!==!0){try{await $h(p,m,h,r)}catch(w){throw f(w)}continue}let y=new M(g?.error?.code||`http_${m.status}`,g?.error?.message||`HTTP ${m.status}`);throw y.status=m.status,Object.assign(y,_i(g?.error)),y}return g}function f(p){let m=w0(p);return new M(c?"network_error":"outcome_unknown",`R\xE9ponse incompl\xE8te de ${n.origin}: ${p.message}${m?` (${m})`:""}`,{cause:p})}a(f,"requestFailure")}a(wc,"apiRequest");var y0=[[/^(ENOTFOUND|EAI_AGAIN)$/,"cet ordinateur ne trouve pas l'adresse du hub : pas d'internet ou DNS bloqu\xE9"],[/^(ECONNREFUSED|ECONNRESET|ETIMEDOUT|EHOSTUNREACH|ENETUNREACH|UND_ERR_CONNECT_TIMEOUT|UND_ERR_SOCKET)$/,"connexion refus\xE9e ou coup\xE9e : pare-feu, proxy ou pas d'internet"],[/^(CERT_NOT_YET_VALID|CERT_HAS_EXPIRED)$/,"certificat du hub hors de ses dates : v\xE9rifiez l'horloge de cet ordinateur"],[/CERT|SELF_SIGNED|UNABLE_TO_(GET|VERIFY)/,"certificat non reconnu : un antivirus (analyse HTTPS) ou un proxy intercepte la connexion"]];function w0(t){let e=t?.cause?.code||t?.cause?.errors?.find(n=>n?.code)?.code;if(!e)return"";let r=y0.find(([n])=>n.test(e))?.[1];return r?`${e}: ${r}`:e}a(w0,"networkCause");async function b0(t,e){if(!t.body)return"";let r=a(()=>new M("response_too_large",`Control response exceeds ${e} bytes; narrow the query or request a smaller page`),"tooLarge");if(Number(t.headers.get("content-length"))>e)throw await t.body.cancel(),r();let n=[],i=0;for await(let s of t.body){if(i+=s.byteLength,i>e)throw r();n.push(s)}return Buffer.concat(n,i).toString("utf8")}a(b0,"readControlResponse");async function $h(t,e,r,n){let i=e?.headers.get("retry-after"),s=i?/^\d+(\.\d+)?$/.test(i)?Number(i)*1e3:Date.parse(i)-Date.now():0,o=Number(n.retryDelayMs??150)*2**t*(.75+Math.random()*.5);await g0(Math.min(2**31-1,Math.max(o,Number.isFinite(s)?s:0)),void 0,{signal:r})}a($h,"retryDelay");function v0(t){return t.endsWith("/")?t:`${t}/`}a(v0,"ensureTrailingSlash");function Zr(t,{allowHttpLocalhost:e=!0}={}){let r;try{r=new URL(t)}catch{throw new Error("L'URL du serveur est invalide.")}let n=["localhost","127.0.0.1","[::1]"].includes(r.hostname);if(r.protocol!=="https:"&&!(e&&n&&r.protocol==="http:"))throw new Error("Le serveur doit utiliser HTTPS (HTTP est permis uniquement sur localhost). ");if(!new Set(["","/"]).has(r.pathname)||r.search||r.hash||r.username||r.password)throw new Error("L'URL du serveur doit contenir uniquement le protocole, le domaine et \xE9ventuellement le port.");return r.pathname=r.pathname.replace(/\/$/,""),r.toString().replace(/\/$/,"")}a(Zr,"normalizeServerUrl");Ne();import{existsSync as L0,readFileSync as C0}from"node:fs";import{join as P0}from"node:path";He();Ne();import{existsSync as Hh,readFileSync as Gh,rmSync as Wk,writeFileSync as Hk}from"node:fs";import{platform as zh}from"node:os";import{join as bc}from"node:path";import{execFileSync as R0,spawnSync as k0}from"node:child_process";import{constants as qh,closeSync as E0,fstatSync as S0,openSync as T0,readFileSync as x0}from"node:fs";ve();Ne();He();function Fh(t,e){let r=T0(t,qh.O_RDONLY|(qh.O_NOFOLLOW||0));try{let n=S0(r);if(!n.isFile()||n.size>4096||process.platform!=="win32"&&(n.mode&63||process.getuid()!==0&&n.uid!==process.getuid()))throw new Error("Machine credential must be a private file owned by the service user");let i=JSON.parse(x0(r,"utf8"));if(i.schema!=="interscale.machine-credential/v1"||i.node_id!==e||typeof i.token!="string"||Buffer.from(i.token,"base64url").length!==iu)throw new Error("Machine credential does not match the enrolled node");return i.token}finally{E0(r)}}a(Fh,"readMachineCredential");var O0="com.interscale",Vh="Add-Type -AssemblyName System.Security",Zk=[Vh,"$plain=[Console]::In.ReadToEnd()","$bytes=[Text.Encoding]::UTF8.GetBytes($plain)","$encrypted=[Security.Cryptography.ProtectedData]::Protect($bytes,$null,[Security.Cryptography.DataProtectionScope]::CurrentUser)","[Convert]::ToBase64String($encrypted)"].join(";"),I0=[Vh,"$encoded=[Console]::In.ReadToEnd()","$encrypted=[Convert]::FromBase64String($encoded)","$bytes=[Security.Cryptography.ProtectedData]::Unprotect($encrypted,$null,[Security.Cryptography.DataProtectionScope]::CurrentUser)","[Console]::Out.Write([Text.Encoding]::UTF8.GetString($bytes))"].join(";");function Jh(t,e,r=process.env){if(t==="agent"&&r.INTERSCALE_MACHINE_CREDENTIAL)return Fh(r.INTERSCALE_MACHINE_CREDENTIAL,e);let n=r[`INTERSCALE_${t.toUpperCase()}_TOKEN`];return n||(r.INTERSCALE_TEST_SECRET_DIR?Wh(t,e,r.INTERSCALE_TEST_SECRET_DIR):zh()==="darwin"?A0(t,e):zh()==="win32"?N0(t,e,r):Wh(t,e,bc(W(r),"secrets")))}a(Jh,"getSecret");function A0(t,e){try{return R0("/usr/bin/security",["find-generic-password","-a",e,"-s",`${O0}.${t}`,"-w"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{throw new Error(`Secret ${t}/${e} not found in macOS Keychain`)}}a(A0,"getMacSecret");function N0(t,e,r){let n=Yh(bc(W(r),"secrets"),t,e);if(!Hh(n))throw new Error(`Secret ${t}/${e} not found`);let i=k0("powershell.exe",["-NoProfile","-NonInteractive","-Command",I0],{input:Gh(n,"utf8"),encoding:"utf8",windowsHide:!0});if(i.status!==0)throw new Error(`Windows DPAPI decryption failed: ${i.stderr}`);return i.stdout}a(N0,"getWindowsSecret");function Wh(t,e,r){let n=Yh(r,t,e);if(!Hh(n))throw new Error(`Secret ${t}/${e} not found at ${n}`);return Gh(n,"utf8")}a(Wh,"getFileSecret");function Yh(t,e,r){let n=`${e}-${r}`.replace(/[^a-zA-Z0-9_.-]/g,"_");return bc(t,`${n}.secret`)}a(Yh,"secretPath");He();function Kh(t=process.env){let e=P0(W(t),"connection.json");if(!L0(e))return null;let r=JSON.parse(C0(e,"utf8"));if(r.signed_out)throw Object.assign(new Error("Sign in to Interscale to continue"),{code:"signed_out"});if(r.version!==1||!/^ctok_[A-Za-z0-9-]{1,200}$/.test(r.token_id))throw new Error("Invalid installation identity");return{...r,server_url:Zr(r.server_url),token:Jh("controller",r.token_id,t)}}a(Kh,"loadConnection");var $0="interscale-fleet.private.json",q0=Xh(B0(M0(import.meta.url)),"..");function F0(t=process.env){return Xh(t.INTERSCALE_FLEET_PROFILE||j0(q0,$0))}a(F0,"fleetProfilePath");function Zh(t=process.env){let e=Kh(t);if(e)return{version:1,server_url:e.server_url,fleet_key:e.token,source:"installation",token_id:e.token_id,release_public_key:e.release_public_key};let r=F0(t);if(!D0(r))throw new Error("Sign in first: interscale login (or open the Interscale app on this computer)");let n;try{n=JSON.parse(U0(r,"utf8"))}catch{throw new Error(`Profil priv\xE9 Interscale illisible: ${r}`)}return z0(n)}a(Zh,"loadFleetProfile");function z0(t){if(!t||t.version!==1)throw new Error("Version du profil priv\xE9 Interscale invalide");return{version:1,server_url:Zr(t.server_url),fleet_key:W0(t.fleet_key)}}a(z0,"validateFleetProfile");function W0(t){if(typeof t!="string"||!/^[A-Za-z0-9_-]+$/.test(t))throw new Error("Cl\xE9 de flotte Interscale invalide");let e=Buffer.from(t,"base64url");if(e.length!==32||e.toString("base64url")!==t)throw new Error("La cl\xE9 de flotte Interscale doit contenir 256 bits");return t}a(W0,"validateFleetKey");ba();le();function Is(t){if(t.state==="completed")return null;let e,r,n;if(t.r2_deleted_at||t.r2_cleanup_started_at)e=t.r2_deleted_at?"transfer_reclaimed":"transfer_reclaiming",r=t.r2_deleted_at?"Relay storage was reclaimed":"Relay storage is being reclaimed",n="Inspect the destination for any published result. If delivery is incomplete, send the retained source with a new transfer; this transfer cannot resume.";else if(["cancel_requested","cancelled","needs_review"].includes(t.state))e="transfer_stopped",r=`Transfer is ${t.state}; inspect its cancellation outcome`,n="Inspect the transfer and destination outcome before starting replacement work.";else if(t.state==="failed")e=t.failure_code||"transfer_failed",r=t.failure_message||"Destination agent rejected the transfer",n="Inspect the transfer failure and correct its cause before retrying.";else return null;return Object.assign(new R(e==="transfer_reclaimed"?410:409,e,r),{terminal:!0,retryable:!1,transferId:t.id||null,next_action:n})}a(Is,"transferOutcomeError");va();import{randomUUID as Zt}from"node:crypto";import{open as cf,stat as rf,realpath as Ev}from"node:fs/promises";import{basename as Sv}from"node:path";import{setTimeout as Tv}from"node:timers/promises";le();ve();Wn();ve();ec();ac();ss();Ea();_a();var uv=ot(Vp(),1),hv=ot(js(),1),pv=ot(tn(),1),fv=ot(Nc(),1),mv=ot(Pc(),1),_v=ot($c(),1),cn=ot(Fs(),1),gv=ot(tf(),1);var Ws=class{static{a(this,"ControllerEventClient")}constructor(e,r,{connectTimeoutMs:n=1e4,heartbeatIntervalMs:i=15e3,heartbeatTimeoutMs:s=1e4}={}){if(!Number.isSafeInteger(n)||n<1||n>6e4)throw new Error("Invalid event connection timeout");for(let o of[i,s])if(!Number.isSafeInteger(o)||o<1||o>6e4)throw new Error("Invalid event heartbeat timing");this.connectTimeoutMs=n,this.heartbeatIntervalMs=i,this.heartbeatTimeoutMs=s,this.url=bv(e),this.token=r,this.socket=null,this.authenticated=!1,this.connecting=null,this.waiters=new Map,this.subscriptions=new Map,this.pending=new Map,this.pendingSizes=new Map,this.pendingBytes=0,this.connectionWaiters=0}async waitFor(e,r,n=0,i){if(i?.throwIfAborted(),!["job","operation","transfer","desktop_session","rc_session","fleet"].includes(e)||typeof r!="string"||!r.length||r.length>220||!Number.isSafeInteger(n)||n<0)throw Object.assign(new Error("Invalid controller subscription"),{code:"invalid_subscription"});await this.connect(i),i?.throwIfAborted();let s=`${e}:${r}`,o=this.pending.get(s);if(o?.type==="gap")throw this.dropPending(s),this.subscriptions.delete(s),Object.assign(new Error("Unconsumed controller updates were replaced; recover from the last consumed cursor"),{code:"event_gap"});if(o&&o.cursor>=n)return this.dropPending(s),o;let c=0;for(let l of this.waiters.values())c+=l.length;if(c>=256)throw Object.assign(new Error("Controller event waiter capacity is full"),{code:"event_client_busy"});if(!this.subscriptions.has(s)&&this.subscriptions.size>=256){let l=[...this.subscriptions.keys()].find(d=>!this.waiters.has(d));if(!l)throw Object.assign(new Error("Controller subscription capacity is full"),{code:"event_client_busy"});this.unsubscribeKey(l)}return new Promise((l,d)=>{let u={resolve:l,reject:d,signal:i,abort:null};i&&(u.abort=()=>{this.remove(s,u),this.waiters.has(s)||this.unsubscribeKey(s),d(i.reason instanceof Error?i.reason:new Error("Subscription cancelled"))},i.addEventListener("abort",u.abort,{once:!0}));let h=this.waiters.get(s)||[];h.push(u),this.waiters.set(s,h);let f=this.subscriptions.get(s);if(!f||f.cursor!==n||f.has_more){this.subscriptions.set(s,{kind:e,id:r,cursor:n,initializing:!0});try{this.socket.send(JSON.stringify({type:"subscribe",kind:e,id:r,cursor:n}))}catch(p){this.subscriptions.delete(s),this.remove(s,u),i?.removeEventListener("abort",u.abort),d(p)}}})}async connect(e){if(e?.throwIfAborted(),!(this.authenticated&&this.socket?.readyState===cn.default.OPEN)){if(this.connectionWaiters>=256)throw Object.assign(new Error("Controller connection waiter capacity is full"),{code:"event_client_busy"});this.connectionWaiters++;try{if(!this.connecting){let r;r=new Promise((n,i)=>{let s=new cn.default(this.url,{perMessageDeflate:!1,maxPayload:2097152});this.socket=s;let o,c,l=0,d=null,u=a(p=>{this.socket===s&&(clearTimeout(h),clearTimeout(o),clearTimeout(c),this.socket=null,this.authenticated=!1,this.connecting=null,this.stopConnection=null,this.subscriptions.clear(),this.clearPending(),i(p),this.fail(p),s.terminate())},"stop"),h=setTimeout(()=>u(Object.assign(new Error("Controller event connection/authentication timed out"),{code:"event_connect_timeout"})),this.connectTimeoutMs);this.stopConnection=u;let f=a(()=>{o=setTimeout(()=>{if(!(this.socket!==s||!this.authenticated)){d=`heartbeat-${++l}`,c=setTimeout(()=>u(Object.assign(new Error("Controller event stream heartbeat timed out; reconcile from the consumed cursor"),{code:"event_heartbeat_timeout"})),this.heartbeatTimeoutMs);try{s.send(JSON.stringify({type:"ping",request_id:d}))}catch(p){u(p)}}},this.heartbeatIntervalMs),o.unref()},"scheduleHeartbeat");s.once("open",()=>{if(this.socket===s)try{s.send(JSON.stringify({type:"authenticate",token:this.token}))}catch(p){u(p)}}),s.on("message",(p,m)=>{if(this.socket!==s)return;let _=a(()=>u(Object.assign(new Error("Controller event stream returned an invalid frame"),{code:"invalid_event_frame"})),"invalid");if(m)return _();let g;try{g=JSON.parse(p.toString("utf8"))}catch{return _()}if(!g||typeof g!="object"||Array.isArray(g))return _();if(g.type==="error")return u(Object.assign(new Error(g.message||"Controller stream rejected request"),{code:g.code||"event_stream_error"}));if(g.type==="authenticated"&&!this.authenticated){clearTimeout(h),this.authenticated=!0,f(),n();return}if(!this.authenticated)return _();if(g.type==="update")return this.resolve(`${g.kind}:${g.id}`,g);if(g.type==="gap")return u(Object.assign(new Error(g.reason||"Controller event cursor gap"),{code:"event_gap"}));if(g.type==="pong"){d!==null&&g.request_id===d&&(clearTimeout(c),d=null,f());return}return _()}),s.once("error",u),s.once("close",()=>u(Object.assign(new Error("Controller event stream closed"),{code:"event_stream_closed"})))}).finally(()=>{this.connecting===r&&(this.connecting=null)}),this.connecting=r}return await vv(this.connecting,e)}finally{this.connectionWaiters--}}}resolve(e,r){if(!this.subscriptions.has(e)&&!this.waiters.has(e)&&!this.pending.has(e))return;let n=this.subscriptions.get(e);n&&this.subscriptions.set(e,{...n,cursor:r.cursor,has_more:!!r.has_more,initializing:!1});let i=this.waiters.get(e)||[];if(i.length===0){let s=this.pending.get(e);if(s?.type==="gap")return;let o=s?yv(s,r):wv(r);o?this.storePending(e,o):(this.unsubscribeKey(e),this.storePending(e,{type:"gap"}));return}this.waiters.delete(e);for(let s of i)s.signal?.removeEventListener("abort",s.abort),s.resolve(r)}storePending(e,r){this.dropPending(e);let n=Buffer.byteLength(JSON.stringify(r));for(this.pending.set(e,r),this.pendingSizes.set(e,n),this.pendingBytes+=n;this.pending.size>256||this.pendingBytes>8*1024*1024;)this.unsubscribeKey(this.pending.keys().next().value)}dropPending(e){this.pendingBytes-=this.pendingSizes.get(e)||0,this.pendingSizes.delete(e),this.pending.delete(e)}clearPending(){this.pending.clear(),this.pendingSizes.clear(),this.pendingBytes=0}unsubscribeKey(e){let r=this.subscriptions.get(e);if(this.subscriptions.delete(e),this.dropPending(e),r&&this.socket?.readyState===cn.default.OPEN)try{this.socket.send(JSON.stringify({type:"unsubscribe",kind:r.kind,id:r.id}))}catch(n){this.stopConnection?.(n)}}remove(e,r){let n=(this.waiters.get(e)||[]).filter(i=>i!==r);n.length?this.waiters.set(e,n):this.waiters.delete(e)}fail(e){for(let r of this.waiters.values())for(let n of r)n.signal?.removeEventListener("abort",n.abort),n.reject(e);this.waiters.clear()}close(){if(this.stopConnection){this.stopConnection(Object.assign(new Error("Controller event client closed"),{code:"event_stream_closed"}));return}this.socket?.readyState<cn.default.CLOSING&&this.socket.close(1e3,"client closing"),this.socket=null,this.authenticated=!1,this.subscriptions.clear(),this.clearPending(),this.fail(Object.assign(new Error("Controller event client closed"),{code:"event_stream_closed"}))}};function yv(t,e){if(!Number.isSafeInteger(t.cursor)||!Number.isSafeInteger(e.cursor)||e.cursor<t.cursor)return null;let r=[],n=new Set;for(let s of[...t.events||[],...e.events||[]]){let o=s?.event_id||(s?.seq!=null?`seq:${s.seq}`:s?.cursor!=null?`cursor:${s.cursor}`:JSON.stringify(s));if(!n.has(o)&&(n.add(o),r.push(s),r.length>1e3))return null}let i={...t,...e,events:r,cursor:Math.max(t.cursor,e.cursor),has_more:!!(t.has_more||e.has_more)};return Buffer.byteLength(JSON.stringify(i))>2*1024*1024?null:i}a(yv,"mergeUpdates");function wv(t){return!Number.isSafeInteger(t?.cursor)||(t.events||[]).length>1e3||Buffer.byteLength(JSON.stringify(t))>2*1024*1024?null:t}a(wv,"boundedUpdate");function bv(t){let e=new URL(t);return e.protocol=e.protocol==="https:"?"wss:":"ws:",e.pathname=`${e.pathname.replace(/\/$/,"")}/v1/controller/connect`,e.search="",e.hash="",e.toString()}a(bv,"toWebSocketUrl");function vv(t,e){return e?(e.throwIfAborted(),new Promise((r,n)=>{let i=a(()=>n(e.reason instanceof Error?e.reason:new Error("Connection wait cancelled")),"abort");e.addEventListener("abort",i,{once:!0}),t.then(r,n).finally(()=>e.removeEventListener("abort",i))})):t}a(vv,"waitForConnection");var ci=class{static{a(this,"InterscaleClient")}constructor(e,r){this.serverUrl=e,this.token=r,this.eventClient=new Ws(e,r)}request(e,r={}){return wc(this.serverUrl,e,{...r,token:this.token})}nodes(e={}){let r=rt({view:e.view,limit:e.limit,cursor:e.cursor,kind:e.kind});return this.request(`/v1/nodes${r.size?`?${r}`:""}`)}fleetSummary(){return this.request("/v1/fleet/summary")}releases(){return this.request("/v1/releases")}async latestRelease(){return(await this.request("/v1/releases/latest")).release||null}publishRelease(e){return this.request("/v1/releases",{method:"POST",json:e})}listWorkspaces(e,r={}){let n=rt({limit:r.limit,cursor:r.cursor});return this.request(`/v1/nodes/${encodeURIComponent(e)}/workspaces?${n}`,{signal:r.signal})}nodeInventory(e,r={}){let n=rt({section:r.section,limit:r.limit,cursor:r.cursor});return this.request(`/v1/nodes/${encodeURIComponent(e)}/inventory?${n}`)}fileFind(e,r={}){let{signal:n,...i}=r;return this.request("/v1/files/find",{method:"POST",json:{...i,node:e},signal:n})}nodeContext(e,r={}){return this.request(`/v1/nodes/${encodeURIComponent(e)}/context`,{signal:r.signal})}fileStat(e,r,n={}){return this.request("/v1/files/stat",{method:"POST",json:{node:e,path:r},signal:n.signal})}fileList(e,r,n={}){return this.request("/v1/files/list",{method:"POST",json:{node:e,path:r,limit:n.limit,cursor:n.cursor},signal:n.signal})}whoami(){return this.request("/v1/whoami")}controllerTokens(){return this.request("/v1/controller-tokens")}createControllerToken(e){return this.request("/v1/controller-tokens",{method:"POST",json:{name:e}})}revokeControllerToken(e){return this.request(`/v1/controller-tokens/${encodeURIComponent(e)}/revoke`,{method:"POST",json:{}})}desktopDoctor(e){return this.request(`/v1/nodes/${encodeURIComponent(e)}/desktop/doctor`)}desktopSessions(e={}){let r=new URLSearchParams;return e.node&&r.set("node",e.node),e.limit!==void 0&&r.set("limit",String(e.limit)),this.request(`/v1/desktop-sessions${r.size?`?${r}`:""}`)}createDesktopSession(e,r={}){if(r.display!==void 0||r.quality!==void 0&&r.quality!=="latency")throw Object.assign(new Error("Interscale selects the active display and latency settings automatically"),{code:"invalid_desktop_request"});return this.request("/v1/desktop-sessions",{method:"POST",json:{node:e,request_id:r.requestId||`desktop-${Zt()}`,quality:"latency",...r.routeHost!==void 0?{route_host:r.routeHost}:{},...r.audio!==void 0?{audio:r.audio}:{},...r.input!==void 0?{input:r.input}:{},...r.localCursor===!0?{local_cursor:!0}:{}}})}desktopSession(e){return this.request(`/v1/desktop-sessions/${encodeURIComponent(e)}`)}desktopSessionEvents(e,r={}){let n=new URLSearchParams({since:String(r.since||0),limit:String(r.limit||100)});return this.request(`/v1/desktop-sessions/${encodeURIComponent(e)}/events?${n}`)}closeDesktopSession(e){return this.request(`/v1/desktop-sessions/${encodeURIComponent(e)}/close`,{method:"POST",json:{}})}retryDesktopSession(e,r,n){return this.request(`/v1/desktop-sessions/${encodeURIComponent(e)}/retry-route`,{method:"POST",json:{route_host:r,controller_fingerprint:n}})}reconcileDesktopSession(e){return this.request(`/v1/desktop-sessions/${encodeURIComponent(e)}/reconcile`,{method:"POST",json:{}})}heartbeatDesktopSession(e,r){return this.request(`/v1/desktop-sessions/${encodeURIComponent(e)}/heartbeat`,{method:"POST",json:{controller_fingerprint:r}})}issueDesktopTicket(e,r){return this.request(`/v1/desktop-sessions/${encodeURIComponent(e)}/ticket`,{method:"POST",json:{controller_fingerprint:r}})}consumeDesktopTicket(e,r,n){return this.request(`/v1/desktop-sessions/${encodeURIComponent(e)}/ticket/consume`,{method:"POST",json:{ticket:r,controller_fingerprint:n}})}trustDesktopController(e,r,n,i,s="Interscale Controller"){return this.request(`/v1/desktop-sessions/${encodeURIComponent(e)}/trust`,{method:"POST",json:{controller_fingerprint:r,pin:n,controller_address:i,controller_name:s}})}switchDesktopDisplay(e,r){return this.request(`/v1/desktop-sessions/${encodeURIComponent(e)}/switch-display`,{method:"POST",json:{controller_fingerprint:r}})}confirmDesktopController(e,r,n,i={}){return this.request(`/v1/desktop-sessions/${encodeURIComponent(e)}/controller-connected`,{method:"POST",json:{controller_fingerprint:r,route_class:n,stream_evidence:i.evidence,stream_startup_ms:i.startup_ms,stream_profile:i.stream_profile}})}markDesktopControllerDisconnected(e,r){return this.request(`/v1/desktop-sessions/${encodeURIComponent(e)}/controller-disconnected`,{method:"POST",json:{controller_fingerprint:r}})}async followDesktopSession(e,r=()=>{},n={}){let i=0,s=new Set(n.connectable?["connecting","active","reconnecting","ended","failed","cancelled","needs_review"]:["ended","failed","cancelled","needs_review"]);for(;;){n.signal?.throwIfAborted();let{session:o}=await this.desktopSession(e);if(r(o),s.has(o.state))return o;try{let c=await this.eventClient.waitFor("desktop_session",e,i,n.signal);if(i=Math.max(i,Number(c.cursor||0)),r(c.snapshot),s.has(c.snapshot.state))return c.snapshot}catch(c){if(n.signal?.aborted)throw c;await it(Number(n.legacyIntervalMs||1e3),n.signal)}}}operations({before:e=0,limit:r=100}={}){return this.request(`/v1/operations?before=${encodeURIComponent(e)}&limit=${encodeURIComponent(r)}`)}operation(e){return this.request(`/v1/operations/${encodeURIComponent(e)}`)}operationEvents(e,{since:r=0,limit:n=100}={}){return this.request(`/v1/operations/${encodeURIComponent(e)}/events?since=${encodeURIComponent(r)}&limit=${encodeURIComponent(n)}`)}close(){this.eventClient.close()}node(e){return this.request(`/v1/nodes/${encodeURIComponent(e)}`)}revokeNode(e){return this.request(`/v1/nodes/${encodeURIComponent(e)}/revoke`,{method:"POST",json:{}})}nodeArchiveCandidates(e={}){let r=new URLSearchParams;return e.staleDays!==void 0&&r.set("stale_days",String(e.staleDays)),e.limit!==void 0&&r.set("limit",String(e.limit)),this.request(`/v1/nodes/archive-candidates${r.size?`?${r}`:""}`)}archivedNodes(e={}){let r=new URLSearchParams;return e.limit!==void 0&&r.set("limit",String(e.limit)),this.request(`/v1/nodes/archived${r.size?`?${r}`:""}`)}archiveNode(e,r){if(!r||r.expectedLastSeen!==null&&(!Number.isSafeInteger(r.expectedLastSeen)||r.expectedLastSeen<0))throw new RangeError("expectedLastSeen must be null or a nonnegative integer timestamp");return this.request(`/v1/nodes/${encodeURIComponent(e)}/archive`,{method:"POST",json:{expected_last_seen:r.expectedLastSeen,stale_days:r.staleDays,reason:r.reason,confirm:r.confirm===!0}})}wakeNode(e,r={}){return this.request(`/v1/nodes/${encodeURIComponent(e)}/wake`,{method:"POST",json:{...r.requestId?{request_id:r.requestId}:{},...r.timeoutSeconds!==void 0?{timeout_seconds:r.timeoutSeconds}:{}}})}wakeStatus(e){return this.request(`/v1/wake/${encodeURIComponent(e)}`)}capabilities(e={}){let r=rt({limit:e.limit,cursor:e.cursor});return e.node&&r.set("node",e.node),e.query&&r.set("q",e.query),this.request(`/v1/capabilities${r.size?`?${r}`:""}`)}recipes(e=null){return this.request(`/v1/recipes${e?`?node=${encodeURIComponent(e)}`:""}`)}ensureCapability(e,r,n={}){return this.request(`/v1/capabilities/${encodeURIComponent(e)}/ensure`,{method:"POST",json:{target:r,...n.requestId?{request_id:n.requestId}:{}}})}ensureRecipe(e,r){return this.request(`/v1/recipes/${encodeURIComponent(e)}/ensure`,{method:"POST",json:{target:r}})}libraries(e=null,r={}){let n=rt({node:e||void 0,kind:r.kind,limit:r.limit,cursor:r.cursor});return this.request(`/v1/libraries?${n}`)}artifacts(e={}){let r=rt({q:e.query||void 0,node:e.node||void 0,limit:e.limit,cursor:e.cursor,library:e.library||void 0,relative_path:e.relativePath||void 0});return this.request(`/v1/artifacts${r.size?`?${r}`:""}`)}artifact(e,r={}){let n=rt({limit:r.limit,cursor:r.cursor});return this.request(`/v1/artifacts/${encodeURIComponent(e)}${n.size?`?${n}`:""}`)}stageArtifact(e,r){return this.request(`/v1/artifacts/${encodeURIComponent(e)}/stage`,{method:"POST",json:{target:r}})}diagnostics(e=null){return this.request(`/v1/diagnostics${e?`?node=${encodeURIComponent(e)}`:""}`)}activity(e={}){let r=new URLSearchParams;for(let n of["node","workspace","operation","parent","kind","status","limit","cursor"])e[n]!==void 0&&e[n]!==null&&r.set(n,String(e[n]));return this.request(`/v1/activity${r.size?`?${r}`:""}`)}createRcSession(e,r={}){return this.request("/v1/rc-sessions",{method:"POST",json:{node:e,provider:r.provider||su,cwd:r.cwd,...r.permissionProfile?{permission_profile:r.permissionProfile}:{},...r.model?{model:r.model}:{},...r.title?{title:r.title}:{},...r.turnTimeoutSeconds?{turn_timeout_seconds:Number(r.turnTimeoutSeconds)}:{},...r.maxBudgetUsd!=null?{max_budget_usd:Number(r.maxBudgetUsd)}:{},...r.requestId?{request_id:r.requestId}:{},...r.parentSessionId?{parent_session_id:r.parentSessionId}:{},...r.rootTaskId?{root_task_id:r.rootTaskId}:{}}})}rcSessions(e={}){let r=new URLSearchParams;return e.node&&r.set("node",e.node),e.parentSessionId&&r.set("parent_session_id",e.parentSessionId),e.rootTaskId&&r.set("root_task_id",e.rootTaskId),e.limit&&r.set("limit",String(e.limit)),this.request(`/v1/rc-sessions${r.size?`?${r}`:""}`)}rcSession(e,r={}){let n=r.view===void 0?"":`?view=${encodeURIComponent(r.view)}`;return this.request(`/v1/rc-sessions/${encodeURIComponent(e)}${n}`,{signal:r.signal})}rcTurns(e,r={}){let n=rt({limit:r.limit,cursor:r.cursor});return this.request(`/v1/rc-sessions/${encodeURIComponent(e)}/turns?${n}`,{signal:r.signal})}rcTurn(e,r,n={}){return this.request(`/v1/rc-sessions/${encodeURIComponent(e)}/turns/${encodeURIComponent(r)}`,{signal:n.signal})}messageRcSession(e,r,n={}){return this.request(`/v1/rc-sessions/${encodeURIComponent(e)}/messages`,{method:"POST",json:{message:r,...n.requestId?{request_id:n.requestId}:{}}})}rcSessionEvents(e,r=0,n=null,i={}){let s=new URLSearchParams;return r&&s.set("since_seq",String(r)),n&&s.set("limit",String(n)),this.request(`/v1/rc-sessions/${encodeURIComponent(e)}/events${s.size?`?${s}`:""}`,{signal:i.signal})}async waitRcSession(e,{sinceSeq:r=0,timeoutMs:n=45e3,signal:i,legacyIntervalMs:s=1e3,limit:o=100}={}){let c=AbortSignal.timeout(Math.max(1,n)),l=i?AbortSignal.any([i,c]):c,d=a(async(u,h)=>{let f=[],p=0;for(let _ of u.events){let g=kv(_);if(p+=JSON.stringify(g).length,f.length&&p>Rv)break;f.push(g)}let m=f.length<u.events.length;return{next_since_seq:m?f.at(-1).seq:u.next_since_seq,timed_out:h,has_more:m||!!u.has_more,session:(await this.rcSession(e,{view:"summary",signal:i})).session,events:f}},"finish");for(;;){i?.throwIfAborted();let u=await this.rcSessionEvents(e,r,o,{signal:i}),h=u.events.filter(f=>f.seq>r);if(h.length)return d({...u,events:h},!1);if(c.aborted)return d({events:[],next_since_seq:r,has_more:!1},!0);if(this.rcEventsUnsupported){await it(s,l).catch(()=>{});continue}try{await this.eventClient.waitFor("rc_session",e,r,l)}catch(f){if(i?.aborted)throw f;f?.code==="invalid_subscription"&&(this.rcEventsUnsupported=!0),c.aborted||await it(s,l).catch(()=>{})}}}registerMailbox(e={}){return this.request("/v1/mailbox/addresses",{method:"POST",json:{...e.title?{title:e.title}:{},...e.requestId?{request_id:e.requestId}:{}}})}sendMailboxMessage(e={}){return this.request("/v1/mailbox/messages",{method:"POST",signal:e.signal,json:{body:e.body,...e.from?{from:e.from}:{},...e.to?{to:e.to}:{},...e.kind?{kind:e.kind}:{},...e.replyTo?{reply_to:e.replyTo}:{},...e.requestId?{request_id:e.requestId}:{}}})}receiveMailbox(e,r={}){let n=Math.max(0,Math.min(25,Math.floor(Number(r.waitSeconds)||0)));return this.request(`/v1/mailbox/${encodeURIComponent(e)}/receive`,{method:"POST",signal:r.signal,timeoutMs:n*1e3+15e3,json:{since_seq:r.sinceSeq||0,wait_seconds:n,...r.replyTo?{reply_to:r.replyTo}:{},...r.limit?{limit:r.limit}:{}}})}async waitMailbox(e,{sinceSeq:r=0,timeoutMs:n=45e3,replyTo:i,signal:s}={}){let o=Date.now()+Math.max(0,n),c=r;for(;;){s?.throwIfAborted();let l=Math.max(0,Math.min(25,Math.floor((o-Date.now())/1e3))),d;try{d=await this.receiveMailbox(e,{sinceSeq:c,replyTo:i,waitSeconds:l,signal:s})}catch(u){if(!(["outcome_unknown","network_error"].includes(u?.code)||[429,502,503,504].includes(u?.status))||s?.aborted||Date.now()>=o)throw u;await it(1e3,s).catch(()=>{});continue}if(d.messages.length||Date.now()>=o-1e3)return{...d,timed_out:!d.messages.length};c=d.next_since_seq}}mailboxMessage(e,r={}){return this.request(`/v1/mailbox/messages/${encodeURIComponent(e)}`,{signal:r.signal})}ackMailboxMessage(e,r="handled"){return this.request(`/v1/mailbox/messages/${encodeURIComponent(e)}/ack`,{method:"POST",json:{state:r}})}cancelRcSession(e){return this.request(`/v1/rc-sessions/${encodeURIComponent(e)}/cancel`,{method:"POST",json:{}})}endRcSession(e){return this.request(`/v1/rc-sessions/${encodeURIComponent(e)}/end`,{method:"POST",json:{}})}async followRcSession(e,r={}){let n=Number(r.sinceSeq??0);if(!Number.isSafeInteger(n)||n<0)throw new M("invalid_cursor","RC event cursor must be a nonnegative safe integer");let i=new Set(["succeeded","failed","cancelled","needs_review"]);for(;;){r.signal?.throwIfAborted();let{session:s}=await this.rcSession(e,{signal:r.signal,view:"summary"});r.signal?.throwIfAborted();let{events:o}=await this.rcSessionEvents(e,n,100,r);if(r.signal?.throwIfAborted(),!Array.isArray(o)||o.length>100||o.some((c,l)=>!Number.isSafeInteger(c.seq)||c.seq<=(l?o[l-1].seq:n)))throw new M("invalid_rc_events","RC event page did not advance in sequence");for(let c of o)r.signal?.throwIfAborted(),n=c.seq,r.onEvent?.(c);if(r.signal?.throwIfAborted(),o.length!==100){if(i.has(s.state))return s;await it(1e3,r.signal)}}}async followRcTurn(e,r,n={}){let i=null;for(;;){n.signal?.throwIfAborted();let{turn:s}=await this.rcTurn(e,r,n);if(n.signal?.throwIfAborted(),s.state!==i&&(i=s.state,n.onState?.(s)),n.signal?.throwIfAborted(),new Set(["succeeded","failed","cancelled","needs_review"]).has(s.state))return s;await it(1e3,n.signal)}}jobs(e=100,r={}){let n=rt({limit:e,node:r.node,state:r.state,cursor:r.cursor});return this.request(`/v1/jobs?${n}`)}transfers(e={}){let r=rt({limit:e.limit,state:e.state||void 0,node:e.node||void 0});return this.request(`/v1/transfers${r.size?`?${r}`:""}`)}transfer(e){return this.request(`/v1/transfers/${encodeURIComponent(e)}`)}planTransfer(e,r,n={}){return this.request("/v1/transfers/plan",{method:"POST",json:{source:e,destination:r,overwrite:!!n.overwrite},signal:n.signal})}planUploadTransfer(e,r,n={}){return this.request("/v1/transfers/plan-upload",{method:"POST",json:{source:e,destination:r,overwrite:!!n.overwrite},signal:n.signal})}planDownloadTransfer(e,r={}){return this.request("/v1/transfers/plan-download",{method:"POST",json:{source:e},signal:r.signal})}startTransfer(e,r,n={}){return this.request("/v1/transfers/start",{method:"POST",json:{source:e,destination:r,overwrite:!!n.overwrite,request_id:n.requestId||Zt()},signal:n.signal})}transferEvents(e,{sinceSeq:r=0,limit:n=100,signal:i}={}){return this.request(`/v1/transfers/${encodeURIComponent(e)}/events?since_seq=${encodeURIComponent(r)}&limit=${encodeURIComponent(n)}`,{signal:i})}async followTransfer(e,r=()=>{},n={}){let i=n.intervalMs===void 0?1e3:Number(n.intervalMs);if(!Number.isSafeInteger(i)||i<100||i>6e4)throw new M("invalid_follow_interval","Transfer follow interval must be between 100 and 60000 milliseconds");let s=n.timeoutMs===void 0||n.timeoutMs===null?null:Number(n.timeoutMs);if(s!==null&&(!Number.isSafeInteger(s)||s<1||s>864e5))throw new M("invalid_follow_timeout","Transfer follow timeout must be between 1 millisecond and 24 hours");let o=s===null?null:Date.now()+s,c=new Set(["completed","failed","cancelled","needs_review"]),l=!0,d,u=a(h=>{let f=JSON.stringify(h);f!==d&&(d=f,r(h))},"emit");for(;;){if(n.signal?.throwIfAborted(),o!==null&&Date.now()>=o)throw af(e);let h=o===null?null:new AbortController,f=o===null?null:Math.max(1,o-Date.now()),p=h?setTimeout(()=>h.abort(af(e)),f):null;p?.unref?.();let m=h?n.signal?AbortSignal.any([n.signal,h.signal]):h.signal:n.signal,_;try{_=(await this.request(`/v1/transfers/${encodeURIComponent(e)}`,{signal:m})).transfer}catch(y){throw h?.signal.aborted&&!n.signal?.aborted?h.signal.reason:y}finally{p&&clearTimeout(p)}if(n.signal?.throwIfAborted(),u(_),n.signal?.throwIfAborted(),c.has(_.state))return _;let g=o===null?i:Math.min(i,Math.max(1,o-Date.now()));if(l){let y=new AbortController,w=setTimeout(()=>y.abort(),g);w.unref?.();let x=n.signal?AbortSignal.any([n.signal,y.signal]):y.signal;try{let v=await this.eventClient.waitFor("transfer",e,Number(_.event_cursor||0),x);if(n.signal?.throwIfAborted(),u(v.snapshot),n.signal?.throwIfAborted(),c.has(v.snapshot.state))return v.snapshot;continue}catch(v){if(n.signal?.aborted)throw n.signal.reason instanceof Error?n.signal.reason:v;if(y.signal.aborted)continue;l=!1}finally{clearTimeout(w)}}try{await it(g,n.signal)}catch(y){throw n.signal?.reason instanceof Error?n.signal.reason:y}}}cancelTransfer(e){return this.request(`/v1/transfers/${encodeURIComponent(e)}/cancel`,{method:"POST",json:{}})}pauseTransfer(e){return this.request(`/v1/transfers/${encodeURIComponent(e)}/pause`,{method:"POST",json:{}})}resumeTransfer(e,r={}){return this.request(`/v1/transfers/${encodeURIComponent(e)}/resume`,{method:"POST",json:r.token?{token:r.token}:{}})}async run(e,r,n={}){let i=n.idempotencyKey||`cli-${Zt()}`,s=!1;try{let o=n.script!==void 0?["<shell>",n.script]:r,c=n.inputs===void 0?n.inputRefs:await(await Promise.resolve().then(()=>(gc(),Sh))).prepareRunFiles(this,e,o,{...n,idempotencyKey:i});s=!0;let l={api_version:Gr,idempotency_key:i,target:{node:e,...n.ifOffline?{if_offline:n.ifOffline}:{}},task:{...n.script!==void 0?{type:"shell",script:n.script}:{type:"exec",argv:r},...c!==void 0?{inputs:c}:{},...Number(n.timeoutSeconds)>0?{timeout_seconds:Number(n.timeoutSeconds)}:{},...n.cwdAlias?{cwd_alias:n.cwdAlias}:{},...n.cwd?{cwd:n.cwd}:{},...n.env!==void 0?{env:n.env}:{},...n.outputs!==void 0?{outputs:n.outputs}:{},...n.environmentProfile!==void 0?{environment_profile:n.environmentProfile}:{},...n.workspaceRevision!==void 0?{workspace_revision:n.workspaceRevision}:{},...n.workspace!==void 0?{workspace:n.workspace}:{},...n.cwdRelative!==void 0?{cwd_relative:n.cwdRelative}:{}},resources:{gpu:Number(n.gpu||0),exclusive:!!n.exclusive}};try{return await this.request("/v1/jobs",{method:"POST",signal:n.signal,json:l})}catch(d){if(l.task.timeout_seconds!==void 0||d?.status!==400||!/timeout_seconds/.test(String(d?.message)))throw d;return await this.request("/v1/jobs",{method:"POST",signal:n.signal,json:{...l,task:{...l.task,timeout_seconds:10080*60}}})}}catch(o){throw o.idempotency_key=i,o.code==="outcome_unknown"&&(o.retryable=!1,o.next_action=s?"Reconcile the submitted job using this idempotency key; never retry the command with a new key.":"Resume input preparation using this idempotency key. This call did not submit the command."),o}}terminal(e,r,n={}){return this.request("/v1/jobs",{method:"POST",json:{api_version:Gr,idempotency_key:n.idempotencyKey||`term-${Zt()}`,target:{node:e},task:{type:"terminal",...r,timeout_seconds:Number(n.timeoutSeconds||60)},resources:{gpu:0,exclusive:!1}}})}async runTerminal(e,r,n={}){let i=await this.terminal(e,r,n),s=await this.followJob(i.job.id),o=[];await this.eachJobPage(s.id,"logs",d=>{o.push(...d)});let c=o.filter(d=>d.stream==="stdout").map(d=>d.text).join(""),l=null;try{l=JSON.parse(c.trim())}catch{l=null}if(l?.error){let d=new M(l.error.code,l.error.message);throw d.next_action=l.error.next_action,d}if(s.state!=="succeeded"){let d=o.filter(h=>h.stream==="stderr").map(h=>h.text).join("").trim(),u;throw await this.eachJobPage(s.id,"events",h=>{for(let f of h)f.type==="state"&&f.payload?.message&&(u=f.payload.message)}),new M("terminal_job_failed",d||u||`terminal job ${s.state}`)}if(!l)throw new M("terminal_output_unparsed","The terminal helper produced no parseable output");return{job:s,...l}}job(e,r={}){return this.request(`/v1/jobs/${encodeURIComponent(e)}`,{signal:r.signal})}events(e,r={}){let n=new URLSearchParams;return r.sinceSeq&&n.set("since_seq",String(r.sinceSeq)),r.limit&&n.set("limit",String(r.limit)),this.request(`/v1/jobs/${encodeURIComponent(e)}/events${n.size?`?${n}`:""}`,{signal:r.signal})}logs(e,r={}){let n=new URLSearchParams;return r.sinceSeq&&n.set("since_seq",String(r.sinceSeq)),r.limit&&n.set("limit",String(r.limit)),r.tail&&n.set("tail",String(r.tail)),this.request(`/v1/jobs/${encodeURIComponent(e)}/logs${n.size?`?${n}`:""}`,{signal:r.signal})}async eachJobPage(e,r,n,i={}){let s=0;for(;;){let o=await this[r](e,{sinceSeq:s,signal:i.signal});if(await n(o[r]),!o.has_more||!(o.next_since_seq>s))return;s=o.next_since_seq}}async logTail(e,r=64*1024,n={}){let i=await this.logs(e,{tail:r,signal:n.signal}),s=[],o=r,c=!!i.truncated;for(let l of[...i.logs].reverse()){if(o<=0){c=!0;break}let d=l.text.length>o?l.text.slice(-o):l.text;d!==l.text&&(c=!0),s.unshift({...l,text:d}),o-=d.length}return{logs:s,truncated:c,next_since_seq:i.next_since_seq}}cancel(e){return this.request(`/v1/jobs/${encodeURIComponent(e)}/cancel`,{method:"POST",json:{}})}createDownload(e,r=".",n={}){return this.request("/v1/downloads",{method:"POST",json:{job_id:e,request_id:n.requestId??Zt(),relative_path:r,...n.chunkSize?{chunk_size:Number(n.chunkSize)}:{}}})}createPull(e,r,n={}){return this.request("/v1/downloads",{method:"POST",json:{node:e,path:r,request_id:n.requestId??Zt(),...n.chunkSize?{chunk_size:Number(n.chunkSize)}:{}}})}createArtifactDownload(e,r={}){return this.request("/v1/downloads",{method:"POST",json:{artifact:e,request_id:r.requestId??Zt(),...r.chunkSize?{chunk_size:Number(r.chunkSize)}:{}}})}resumeDownload(e,r){return this.request(`/v1/downloads/${encodeURIComponent(e)}/resume`,{method:"POST",json:{token:r}})}async copyFile(e,r,n,i={}){nt(i.signal);let s=await rf(e);if(!s.isFile())throw new Error("Transfer source must be a regular file or a prepared directory archive");let o=await sf(e,s,i.signal);nt(i.signal);let c=Number(i.chunkSize||cs),l=await this.request("/v1/transfers",{method:"POST",signal:i.signal,json:{target:r,kind:i.kind||"file",source_name:i.sourceName||Sv(e),destination_path:n,size:s.size,sha256:o,chunk_size:c,overwrite:!!i.overwrite,request_id:i.requestId||Zt()}}),{transfer:d,token:u,direct_candidates:h}=l;return await i.onCreated?.({transfer:d,token:u,sourcePath:e,target:r,destinationPath:n}),this.continueCopy(e,d,u,h,l.r2_available,i)}async resumeCopy(e,r,n,i={}){nt(i.signal);let s=await this.request(`/v1/transfers/${encodeURIComponent(r)}/resume`,{method:"POST",json:{token:n},signal:i.signal}),{transfer:o,direct_candidates:c}=s;if(o.state==="completed")return{transfer:o,route:o.route||"direct",resumed:!0};let l=await rf(e);if(!l.isFile())throw new Error(`Resume source is not a regular file: ${e}`);if(l.size!==o.size)throw new Error(`Resume source size changed: expected ${o.size} bytes, found ${l.size}`);let d=await sf(e,l,i.signal);if(nt(i.signal),d!==o.sha256)throw new Error(`Resume source SHA-256 changed: expected ${o.sha256}, found ${d}`);return{...await this.continueCopy(e,o,n,c,s.r2_available,i),resumed:!0}}async continueCopy(e,r,n,i,s,o={}){nt(o.signal);let c,l=new Set,d=a(async()=>{try{nt(o.signal);let p=(await this.request(`/v1/transfers/${encodeURIComponent(r.id)}`,{signal:o.signal})).transfer;return Is(p)}catch(p){if(Fc(p,o.signal))throw p;return null}},"checkTransferFailure"),u=a(async p=>{for(let m of await as(vs(p),{nodeId:r.target_node_id,id:r.id,token:n,signal:o.signal})){let _=m.url,g=`${_}|${m.localAddress||""}`;if(l.has(g))continue;l.add(g);let y=!1;try{o.onLinkAttempt?.(m);let w=await xv(_,r,n,e,{...o,localAddress:m.localAddress,checkTransferFailure:d});return y=!0,nt(o.signal),await this.request(`/v1/transfers/${encodeURIComponent(r.id)}/complete`,{method:"POST",json:{},signal:o.signal}),{transfer:await this.waitForTransferCompletion(r.id,o),route:w.cacheHit?"cache":"direct",candidate:_,link:{kind:m.kind,interface:m.interface,local_address:m.localAddress}}}catch(w){if(os(r.target_node_id,m),y||Fc(w,o.signal)||w?.terminal)throw w;let x=await d();if(x)throw x;c=w}}return null},"tryCandidates"),h=await u(i);if(h)return h;if(r.route==="direct"&&o.mdns!==!1){let p=await ws(r.target_node_id,{signal:o.signal,timeoutMs:o.mdnsTimeoutMs}),m=await u(p);if(m)return{...m,discovered_by:"mdns"}}let f=await d();if(f)throw f;if(s)return o.onRouteChange?.({route:"r2",reason:c?.message||"no direct route"}),this.uploadR2(e,r,o);throw l.size===0?new Error("Destination is offline or has no direct LAN route, and R2 is not configured"):new Error(`All direct transfer candidates failed: ${c?.message||"unknown error"}`)}async uploadR2(e,r,n={}){nt(n.signal);let i=r;i.r2_upload_id||(i=(await this.request(`/v1/transfers/${encodeURIComponent(i.id)}/r2-start`,{method:"POST",json:{},signal:n.signal})).transfer);let s=await this.request(`/v1/transfers/${encodeURIComponent(i.id)}/r2-parts`,{method:"POST",json:{},signal:n.signal}),o=[...s.existing_parts],c=await cf(e,"r");try{await Hn(s.signed_parts,Number(n.r2Concurrency||4),async(l,d)=>{d.throwIfAborted();let u=l.part_number-1,h=u===i.total_chunks-1?i.size-u*i.chunk_size:i.chunk_size,f=Buffer.alloc(h);await Gn(c,f,u*i.chunk_size),d.throwIfAborted();let p=await fetch(l.url,{method:"PUT",headers:{"content-length":String(f.length)},body:f,signal:zc(d,Number(n.chunkTimeoutMs||1800*1e3))});if(!p.ok)throw new Error(`R2 part ${l.part_number} failed with HTTP ${p.status}`);let m=p.headers.get("etag");if(!m)throw new Error(`R2 part ${l.part_number} returned no ETag`);o.push({part_number:l.part_number,etag:m,size:f.length}),n.onProgress?.({index:u,total:i.total_chunks,bytes:h,skipped:!1,route:"r2"})},n.signal)}finally{await c.close()}return o.sort((l,d)=>l.part_number-d.part_number),nt(n.signal),await this.request(`/v1/transfers/${encodeURIComponent(i.id)}/r2-complete`,{method:"POST",json:{parts:o},signal:n.signal}),{transfer:await this.waitForTransferCompletion(i.id,n),route:"r2"}}async waitForTransferCompletion(e,r={}){let n=Number(r.completionTimeoutMs??864e5);if(!Number.isSafeInteger(n)||n<1||n>2147483647)throw new RangeError("completionTimeoutMs must be an integer between 1 and 2147483647");let i=new AbortController,s=setTimeout(()=>i.abort(),n),o=r.signal?AbortSignal.any([r.signal,i.signal]):i.signal;try{for(;;){o.throwIfAborted();let c=(await this.request(`/v1/transfers/${encodeURIComponent(e)}`,{signal:o})).transfer;if(o.throwIfAborted(),c.state==="completed")return c;let l=Is(c);if(l)throw l;await it(1e3,o)}}catch(c){throw i.signal.aborted&&!r.signal?.aborted?Object.assign(new M("transfer_completion_timeout","Timed out waiting for destination verification and publication"),{retryable:!0,transferId:e,next_action:"Check the transfer status or resume the existing transfer; destination work may still be running."}):c}finally{clearTimeout(s)}}async followJob(e,r={}){let n=0;for(;;){r.signal?.throwIfAborted();let{job:i}=await this.job(e,r);r.signal?.throwIfAborted();let s=n,o=await this.events(e,{sinceSeq:n,limit:100,signal:r.signal});r.signal?.throwIfAborted();for(let c of o.events)r.signal?.throwIfAborted(),!(c.seq<=n)&&(n=c.seq,r.onEvent?.(c));if(r.signal?.throwIfAborted(),!((o.has_more??o.events.length>=100)&&n>s)){if(Jn.has(i.state))return i;try{let c=await this.eventClient.waitFor("job",e,n,r.signal);r.signal?.throwIfAborted();for(let l of c.events||[])r.signal?.throwIfAborted(),!(l.seq<=n)&&(n=l.seq,r.onEvent?.(l));if(r.signal?.throwIfAborted(),Jn.has(c.snapshot.state))continue}catch(c){if(r.signal?.aborted)throw c;await it(Number(r.legacyIntervalMs||1e3),r.signal)}}}}};async function xv(t,e,r,n,i={}){let s=t.replace(/\/$/,""),o=`/v1/transfers/${encodeURIComponent(e.id)}/status`,c=`${s}${o}`,l,d=!1,u=0,h=Date.now()+Number(i.directReadyTimeoutMs||1e4),f=Date.now()+Number(i.cacheCheckTimeoutMs||1800*1e3);for(;Date.now()<(d?f:h);){nt(i.signal);try{let y=await ft(c,{headers:{authorization:nf(r,e.id,"GET",o)},signal:zc(i.signal,Number(i.connectTimeoutMs||2e3)),localAddress:i.localAddress});if(y.ok){let w=await y.json();if(d=w.state==="checking_cache",u=0,!d){l=w;break}}else{let w=await i.checkTransferFailure?.();if(w)throw w}}catch(y){if(Fc(y,i.signal)||y?.terminal)throw y;if(u+=1,!d&&u>=3)break}await it(250,i.signal)}if(!l){let y=await i.checkTransferFailure?.();throw y||new Error(`Direct endpoint did not become ready: ${t}`)}let p=Is(l);if(p){let y=await i.checkTransferFailure?.();throw y||p}let m=new Set(l.received_chunks||[]),_=l.state==="completed"&&m.size===e.total_chunks,g=await cf(n,"r");try{let y=[];for(let w=0;w<e.total_chunks;w+=1)m.has(w)?i.onProgress?.({index:w,total:e.total_chunks,skipped:!0,route:"direct"}):y.push(w);await Hn(y,Number(i.directConcurrency||4),async(w,x)=>{x.throwIfAborted();let v=w===e.total_chunks-1?e.size-w*e.chunk_size:e.chunk_size,k=i.transferBudget?await i.transferBudget.acquire(v*3+28,{priority:"foreground",signal:x,wireBytes:v+28}):()=>{};try{let B=Buffer.alloc(v);await Gn(g,B,w*e.chunk_size),x.throwIfAborted();let ce=Zd(r,e.id,w,B),ye=`/v1/transfers/${encodeURIComponent(e.id)}/chunks/${w}`,L=await ft(`${s}${ye}`,{method:"PUT",headers:{authorization:nf(r,e.id,"PUT",ye),"content-type":"application/octet-stream","content-length":String(ce.length)},body:ce,signal:zc(x,Number(i.chunkTimeoutMs||1800*1e3)),localAddress:i.localAddress});if(!L.ok){let ie=await L.text();throw new Error(`Chunk ${w} failed with HTTP ${L.status}: ${ie}`)}i.onProgress?.({index:w,total:e.total_chunks,bytes:v,skipped:!1,route:"direct"})}finally{k()}},i.signal)}finally{await g.close()}return{cacheHit:_}}a(xv,"uploadDirect");function nf(t,e,r,n){return`Interscale ${fr(t,e,r,n)}`}a(nf,"transferAuthorization");function nt(t){if(!t?.aborted)return;let e=t.reason instanceof Error?t.reason:new Error("Transfer interrupted");throw e.code||="transfer_interrupted",e}a(nt,"throwIfAborted");function Fc(t,e){return!!e?.aborted||t?.code==="transfer_interrupted"||t?.name==="AbortError"}a(Fc,"isTransferInterruption");function zc(t,e){let r=AbortSignal.timeout(Math.max(1,e));return t?AbortSignal.any([t,r]):r}a(zc,"combinedSignal");async function sf(t,e,r){let n=new Hr;try{let i=await Ev(t);return await n.hash(i,{expected:e,signal:r})}finally{await n.close()}}a(sf,"hashFile");var of=2e3,Rv=6e3;function kv(t){let e={};for(let[r,n]of Object.entries(t.payload||{}))typeof n=="string"&&n.length>of?(e[r]=n.slice(0,of),e[`${r}_truncated`]=!0):e[r]=n;return{...t,payload:e}}a(kv,"compactRcEvent");function it(t,e){return Tv(t,void 0,{signal:e})}a(it,"delay");function af(t){return Object.assign(new M("transfer_follow_timeout",`Timed out waiting for transfer ${t}`),{retryable:!0,transferId:t,next_action:`Run interscale transfer status ${t} --follow again or inspect the current status without --follow.`})}a(af,"transferFollowTimeout");function rt(t){return new URLSearchParams(Object.entries(t).filter(([,e])=>e!=null))}a(rt,"queryParameters");ya();ve();le();Ne();import{randomUUID as pi}from"node:crypto";import{readFile as Ff}from"node:fs/promises";import{arch as ZE,platform as QE}from"node:os";import{join as eS,resolve as eo}from"node:path";import{isIP as Ov}from"node:net";var lf=64,df=8,Iv=/^(?:[0-9a-f]{2}[:-]){5}[0-9a-f]{2}$/i;function uf(t){if(t==null)return{};if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Agent wake_targets must be an object");let e=Object.entries(t);if(e.length>lf)throw new Error(`Agent wake_targets cannot contain more than ${lf} machines`);let r={};for(let[n,i]of e){if(!Av(n)||!i||typeof i!="object"||Array.isArray(i))throw new Error(`Invalid Wake-on-LAN target: ${n}`);let s=Nv(i.mac),o=i.broadcast_addresses??i.broadcasts;if(!Array.isArray(o)||o.length<1||o.length>df)throw new Error(`Wake-on-LAN target ${n} needs 1-${df} broadcast_addresses`);let c=[...new Set(o.map(d=>Lv(d,n)))],l=i.port===void 0?9:Number(i.port);if(!Number.isInteger(l)||l<1||l>65535)throw new Error(`Invalid Wake-on-LAN port for ${n}`);r[n]={mac:s,broadcast_addresses:c,port:l}}return r}a(uf,"validateWakeTargets");function Av(t){return typeof t=="string"&&t.length>0&&t.length<=200&&!t.includes("\0")}a(Av,"validIdentity");function Nv(t){if(typeof t!="string"||!Iv.test(t))throw new Error("Wake-on-LAN MAC must contain six hexadecimal octets");return t.replaceAll("-",":").toLowerCase()}a(Nv,"normalizeMac");function Lv(t,e){if(typeof t!="string"||Ov(t)!==4)throw new Error(`Wake-on-LAN broadcast for ${e} must be an IPv4 address`);let r=Number(t.split(".")[0]);if(r===0||r===127||r>=224&&t!=="255.255.255.255")throw new Error(`Wake-on-LAN broadcast for ${e} is not a usable broadcast address`);return t}a(Lv,"validateBroadcast");le();Ne();He();import{existsSync as Wv,mkdirSync as GI,readFileSync as Hv,realpathSync as Gv}from"node:fs";import{basename as YI,dirname as KI,join as XI,resolve as Gc}from"node:path";Ss();ve();le();import{createHash as Cv,createPrivateKey as AI,createPublicKey as ff,sign as NI,verify as Pv}from"node:crypto";var hf="interscale.release/v1",pf="interscale.signed-release/v1",mf=new Set(["darwin","linux","win32"]),Dv=new Map([["darwin",new Set(["pkg"])],["linux",new Set(["deb","tar.gz"])],["win32",new Set(["zip"])]]),_f=new Set(["arm64","x64"]),Uv=100*1024**3;function Bv(t){if(!li(t)||t.schema!==hf)throw D("Release manifest schema is invalid");let e={schema:hf,release_id:Fv(t.release_id),version:yf(t.version),protocol_version:st(t.protocol_version,"protocol_version",80),protocol_features:Hs(t.protocol_features||[],"protocol_features",256),migration_compatibility:jv(t.migration_compatibility),created_at:zv(t.created_at,"created_at"),artifacts:$v(t.artifacts)};if(e.protocol_version!==Gr)throw D(`Release protocol must be ${Gr}`);return e}a(Bv,"validateReleaseManifest");function jv(t){if(t===void 0)return{hub_database_versions:[],agent_ledger_versions:[],previous_binary_versions:[],rollback_policy:"artifact_declared"};if(!li(t))throw D("Release migration compatibility is invalid");let e=st(t.rollback_policy,"rollback_policy",80);if(!["artifact_declared","retain_database_reconcile","no_binary_rollback"].includes(e))throw D("Release rollback policy is invalid");return{hub_database_versions:Hs(t.hub_database_versions,"hub_database_versions",32),agent_ledger_versions:Hs(t.agent_ledger_versions,"agent_ledger_versions",32),previous_binary_versions:Hs(t.previous_binary_versions,"previous_binary_versions",32),rollback_policy:e}}a(jv,"validateMigrationCompatibility");function Hs(t,e,r){if(!Array.isArray(t)||t.length>r)throw D(`${e} must be a bounded array`);let n=t.map(i=>st(i,e,200));if(new Set(n).size!==n.length)throw D(`${e} contains duplicate values`);return n}a(Hs,"validateTextList");function Mv(t,e){if(!li(t)||t.schema!==pf||typeof t.signature!="string"||!/^[A-Za-z0-9_-]{86}$/.test(t.signature))throw D("Signed release envelope is invalid");let r=Wc(e).key,n=gf(r);if(t.key_id!==n)throw D("Release signing key does not match the pinned verification key","release_key_mismatch");let i=Bv(t.manifest),s=Buffer.from(t.signature,"base64url");if(s.length!==64||!Pv(null,Buffer.from(Jt(i)),r,s))throw D("Release manifest signature is invalid","release_signature_invalid");return{schema:pf,key_id:n,manifest:i,signature:t.signature}}a(Mv,"verifySignedRelease");function Wc(t){if(typeof t!="string"||!t.length||Buffer.byteLength(t)>16*1024||/-----BEGIN (?:ENCRYPTED )?PRIVATE KEY-----/.test(t))throw D("Release public key is invalid");let e;try{e=ff(t)}catch{throw D("Release public key is invalid")}if(e.asymmetricKeyType!=="ed25519")throw D("Release verification key must be Ed25519");return{key:e,pem:e.export({type:"spki",format:"pem"}).toString(),key_id:gf(e)}}a(Wc,"releaseVerificationKey");function Hc(t,e,r={}){let n=Mv(t,e),i=r.platform||process.platform,s=r.arch||process.arch;if(!mf.has(i)||!_f.has(s))throw D("Update platform or architecture is unsupported","release_target_unsupported");let o=n.manifest.artifacts.filter(h=>h.platform===i&&h.arch===s);if(o.length!==1)throw D("Release has no unique artifact for this platform and architecture","release_artifact_missing");let c=o[0],l=Gs(r.configVersion??1,1,1e3,"config_version");if(!c.compatibility.agent_config_versions.includes(l))throw D("Release artifact is incompatible with the installed agent configuration","release_config_incompatible");let d=yf(r.currentVersion),u=qv(n.manifest.version,d);if(u<0&&r.allowDowngrade!==!0)throw D("Release is older than the installed version","release_downgrade_blocked");return{schema:"interscale.update-plan/v1",release_id:n.manifest.release_id,current_version:d,target_version:n.manifest.version,state:u===0?"no_change":"ready",artifact:c,key_id:n.key_id,gates:{signature:"verified",artifact_hash:"pending_download_verification",drain:u===0?"not_required":"required",checkpoint_policy:"wait_for_safe_boundary",retain_previous_binary:u!==0,rollback_compatible:c.compatibility.ledger_rollback_safe},preserved_local_state:["identity","credentials","aliases","environment_profiles","libraries","workspace_roots","concurrency"]}}a(Hc,"releaseUpdatePlan");function gf(t){let r=(t?.type==="public"?t:ff(t)).export({type:"spki",format:"der"});return`ed25519:${Cv("sha256").update(r).digest("base64url")}`}a(gf,"releaseKeyId");function $v(t){if(!Array.isArray(t)||t.length<1||t.length>12)throw D("Release must contain 1-12 artifacts");let e=new Set;return t.map(r=>{if(!li(r)||!li(r.compatibility))throw D("Release artifact is invalid");let n=st(r.platform,"platform",20),i=st(r.arch,"arch",20),s=st(r.package_format,"package_format",20);if(!mf.has(n)||!_f.has(i)||!Dv.get(n)?.has(s))throw D("Release artifact platform, architecture, or package format is unsupported");let o=`${n}:${i}`;if(e.has(o))throw D(`Duplicate release artifact target: ${o}`);e.add(o);let c=st(r.file_name,"file_name",255);if(c==="."||c===".."||/[\\/\0]/.test(c))throw D("Release artifact file_name must be a basename");let l;try{l=new URL(r.url)}catch{throw D("Release artifact URL is invalid")}if(l.protocol!=="https:"||l.username||l.password||l.search||l.hash)throw D("Release artifact URL must be credential-free HTTPS without a query or fragment");let d=st(r.sha256,"sha256",64);if(!/^[a-f0-9]{64}$/.test(d))throw D("Release artifact sha256 is invalid");let u=r.compatibility.agent_config_versions;if(!Array.isArray(u)||u.length<1||u.length>16)throw D("Release config compatibility is invalid");let h=[...new Set(u.map(f=>Gs(f,1,1e3,"agent_config_version")))].sort((f,p)=>f-p);if(typeof r.compatibility.ledger_rollback_safe!="boolean")throw D("Release rollback compatibility must be explicit");return{platform:n,arch:i,package_format:s,file_name:c,size:Gs(r.size,1,Uv,"size"),sha256:d,url:l.toString(),node_runtime_version:st(r.node_runtime_version,"node_runtime_version",80),compatibility:{agent_config_versions:h,ledger_rollback_safe:r.compatibility.ledger_rollback_safe}}})}a($v,"validateArtifacts");function qv(t,e){let r=t.split(".").map(Number),n=e.split(".").map(Number);for(let i=0;i<3;i+=1)if(r[i]!==n[i])return r[i]<n[i]?-1:1;return 0}a(qv,"compareVersions");function yf(t){if(typeof t!="string"||!/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/.test(t))throw D("Release version must be numeric major.minor.patch");return t}a(yf,"releaseVersion");function Fv(t){let e=st(t,"release_id",200);if(!/^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/.test(e))throw D("release_id must be safe for private staging");return e}a(Fv,"releaseId");function zv(t,e){return Gs(t,1,Number.MAX_SAFE_INTEGER,e)}a(zv,"timestamp");function Gs(t,e,r,n){let i=Number(t);if(!Number.isSafeInteger(i)||i<e||i>r)throw D(`${n} must be an integer from ${e} through ${r}`);return i}a(Gs,"integer");function st(t,e,r){if(typeof t!="string"||!t.length||t.length>r||t.includes("\0"))throw D(`${e} must be nonempty text of at most ${r} characters`);return t}a(st,"text");function li(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}a(li,"plainObject");function D(t,e="invalid_release_manifest"){return new R(400,e,t)}a(D,"invalid");ve();Fn();var wf=30,bf=100,jI=360*60*1e3;var Vv=new WeakMap;function Vs(t=Mn()){if(!Wv(t))throw new Error(`Agent configuration not found at ${t}. Run: interscale agent install`);let e=Gv(t),r=Hv(e,"utf8"),n=JSON.parse(r);return Jv(n),Vv.set(n,{path:e,requestedPath:Gc(t),text:r}),n}a(Vs,"loadAgentConfig");function Jv(t){if(!t||t.version!==1)throw new Error("Unsupported agent configuration version");if(Zr(t.server_url),!t.node_id||!t.node_name)throw new Error("Agent node identity is missing");if(t.graphical_worker!==void 0&&typeof t.graphical_worker!="boolean")throw new Error("Agent graphical_worker must be a boolean");let e=Number(t.data_port);if(!Number.isInteger(e)||e<0||e>65535)throw new Error("Agent data port is invalid");for(let n of["max_concurrent_jobs","max_concurrent_gpu_jobs"]){if(t[n]===void 0)continue;let i=Number(t[n]);if(!Number.isInteger(i)||i<1)throw new Error(`Agent ${n} must be a positive integer`)}if(t.max_transfer_bytes_per_second!==void 0){let n=Number(t.max_transfer_bytes_per_second);if(!Number.isSafeInteger(n)||n<1024||n>10*1024**3)throw new Error("Agent max_transfer_bytes_per_second must be an integer from 1024 through 10737418240");t.max_transfer_bytes_per_second=n}if(!t.receive_root||!t.work_root)throw new Error("Agent storage roots are missing");if(t.receive_retention_days??=wf,!Number.isInteger(Number(t.receive_retention_days))||Number(t.receive_retention_days)<0||Number(t.receive_retention_days)>3650)throw new Error("Agent receive_retention_days must be an integer from 0 through 3650");if(t.receive_retention_days=Number(t.receive_retention_days),t.receive_cleanup_max_entries_per_run??=bf,!Number.isInteger(Number(t.receive_cleanup_max_entries_per_run))||Number(t.receive_cleanup_max_entries_per_run)<1||Number(t.receive_cleanup_max_entries_per_run)>1e3)throw new Error("Agent receive_cleanup_max_entries_per_run must be an integer from 1 through 1000");t.receive_cleanup_max_entries_per_run=Number(t.receive_cleanup_max_entries_per_run);let r=Number(t.max_job_log_bytes??100*1024*1024);if(!Number.isSafeInteger(r)||r<1024)throw new Error("Agent max_job_log_bytes is invalid");if(t.max_job_log_bytes=r,t.tmux_socket!==void 0&&!/^[A-Za-z0-9_-]{1,64}$/.test(String(t.tmux_socket)))throw new Error("Agent tmux_socket must match [A-Za-z0-9_-]{1,64}");if(Uh(t.environment_profiles),Bh(t.path_aliases),t.wake_targets=uf(t.wake_targets),t.desktop_control=Yv(t.desktop_control),t.release_public_key!==void 0&&t.release_public_key!==null?t.release_public_key=Wc(t.release_public_key).pem:t.release_public_key=null,t.path_aliases||={},(!t.recipes||typeof t.recipes!="object")&&(t.recipes={}),(!t.libraries||typeof t.libraries!="object")&&(t.libraries={}),t.file_libraries!==void 0){if(!t.file_libraries||typeof t.file_libraries!="object"||Array.isArray(t.file_libraries))throw new Error("Invalid exact-file library configuration");for(let[n,i]of Object.entries(t.file_libraries)){if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(n)||typeof i!="string"||!i||t.libraries[n])throw new Error(`Invalid exact-file library: ${n}`);t.file_libraries[n]=Gc(i)}}for(let[n,i]of Object.entries(t.libraries)){if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(n)||typeof i!="string"||!i)throw new Error(`Invalid agent library: ${n}`);t.libraries[n]=Gc(i)}}a(Jv,"validateAgentConfig");function Yv(t){if(t==null&&(t={}),typeof t!="object"||Array.isArray(t))throw new Error("Agent desktop_control must be an object");let e={provider:"interscale",host_port:Number(t.host_port||47989),permission_state:t.permission_state||void 0,consent_mode:t.consent_mode||"per_session",audio:!0,max_fps:60,displays:[],encoders:[]};if(!Number.isInteger(e.host_port)||e.host_port<1||e.host_port>65535)throw new Error("Agent desktop_control.host_port is invalid");if(!Number.isInteger(e.max_fps)||e.max_fps<1||e.max_fps>240)throw new Error("Agent desktop_control.max_fps is invalid");if(e.permission_state!==void 0&&!["granted","prompt_required","denied","unavailable","not_required"].includes(e.permission_state))throw new Error("Agent desktop_control.permission_state is invalid");if(!["per_session","persistent","unattended","unsupported"].includes(e.consent_mode))throw new Error("Agent desktop_control.consent_mode is invalid");return t.keep_host_ready===!1&&(e.keep_host_ready=!1),e}a(Yv,"validateDesktopControlConfig");le();He();ve();import{closeSync as gE,existsSync as Be,openSync as yE,readFileSync as wE,realpathSync as Xc,renameSync as Of}from"node:fs";import{lstat as bE,mkdir as If,readdir as Zs,realpath as vE,rename as Cf,rm as Or}from"node:fs/promises";import{spawnSync as EE}from"node:child_process";import{createHash as SE}from"node:crypto";import{dirname as ui,isAbsolute as TE,join as T,relative as Pf,resolve as hi,win32 as xE}from"node:path";import{fileURLToPath as RE}from"node:url";import{spawnSync as vf}from"node:child_process";function Ef(t,e=process.platform){if(!Number.isSafeInteger(t)||t<=0)return null;let r=e==="win32"?vf("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter 'ProcessId=${t}').CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:15e3}):vf("ps",["-p",String(t),"-o","command="],{encoding:"utf8",timeout:5e3});return(r.status===0?String(r.stdout||"").trim():"")||null}a(Ef,"processCommandLine");He();ks();import{cp as dE,lstat as uE,mkdir as Vc,readdir as xf,readFile as Rf,rename as ln,rm as Ue}from"node:fs/promises";import{existsSync as Lt}from"node:fs";import{dirname as di,join as G,resolve as Jc}from"node:path";import{homedir as hE}from"node:os";import{randomUUID as pE}from"node:crypto";import{spawnSync as fE}from"node:child_process";Ne();He();import{createServer as dA,connect as Kv}from"node:net";import{existsSync as hA,lstatSync as Xv,mkdirSync as pA,unlinkSync as fA,chmodSync as mA,readFileSync as Zv}from"node:fs";import{createHash as Qv,createHmac as eE,randomBytes as tE,timingSafeEqual as rE}from"node:crypto";import{join as nE,posix as iE,win32 as sE}from"node:path";function oE(t=W(),e=process.platform){return e==="win32"?`\\\\.\\pipe\\interscale-application-update-${Qv("sha256").update(sE.resolve(t).toLowerCase()).digest("hex").slice(0,32)}`:iE.join(t,"application-update.sock")}a(oE,"applicationUpdateSocket");var aE=a(t=>nE(t,"application-update-key.json"),"keyPath");function Tf(t,{root:e=W(),timeoutMs:r=3e3,destination:n,platform:i=process.platform,socketPath:s=oE(e,i)}={}){return new Promise((o,c)=>{if(!["status","quit"].includes(t))return c(new Error("Invalid application update action"));let l=i==="win32",d={action:t,destination:n},u;if(l){try{u=cE(e)}catch{return c(new Error("Authenticated application update bridge is unavailable"))}d.nonce=tE(16).toString("hex"),d.at=Date.now(),d.mac=Sf(u,"request",d)}let h=Kv(s),f="",p=!1,m=a((_,g)=>{p||(p=!0,h.destroy(),_?c(_):o(g))},"finish");h.setTimeout(r,()=>m(new Error("Application update bridge timed out"))),h.once("connect",()=>h.write(JSON.stringify(d)+`
99
+ `)),h.on("data",_=>{if(f+=_,Buffer.byteLength(f)>2048)return m(new Error("Invalid application update response"));if(f.includes(`
100
+ `))try{let g=JSON.parse(f);if(!g||typeof g.idle!="boolean"||typeof g.version!="string"||l&&!lE(g.mac,Sf(u,"response",d,g)))throw new Error("Unauthenticated or invalid application update response");m(null,{idle:g.idle,version:g.version})}catch(g){m(g)}}),h.once("error",_=>m(_)),h.once("close",()=>m(new Error("Application update bridge disconnected")))})}a(Tf,"requestApplicationUpdate");function cE(t){let e=aE(t),r=Xv(e);if(!r.isFile()||r.size>1024)throw new Error("Invalid application update key");let n=JSON.parse(Zv(e,"utf8"));if(n.schema!=="interscale.application-update-key/v1"||!/^[a-f0-9]{64}$/.test(n.key||""))throw new Error("Invalid application update key");return n.key}a(cE,"readKey");function Sf(t,e,r,n){let i=[e,r.action,r.destination,r.nonce,r.at];return e==="response"&&i.push(n.idle,n.version),eE("sha256",Buffer.from(t,"hex")).update(JSON.stringify(i)).digest("hex")}a(Sf,"authenticate");function lE(t,e){return typeof t=="string"&&/^[a-f0-9]{64}$/.test(t)&&rE(Buffer.from(t,"hex"),Buffer.from(e,"hex"))}a(lE,"validMac");var Kc="com.interscale.desktop",Te=a((t,e)=>Object.assign(new Error(e),{code:t}),"fail"),Js=class{static{a(this,"MacApplicationInstaller")}constructor(e,r={}){this.root=Jc(e),this.destination=Jc(r.destination||"/Applications/Interscale.app"),this.searchRoots=r.searchRoots||[di(this.destination),G(hE(),"Applications")],this.inspect=r.inspect||kf,this.candidateIdentifier=r.candidateIdentifier||(this.inspect===kf?n=>JSON.parse(dn("/usr/bin/plutil",["-convert","json","-o","-",G(n,"Contents","Info.plist")]).stdout).CFBundleIdentifier:null),this.running=r.running||_E,this.run=r.run||dn,this.applicationRequest=r.applicationRequest||(n=>Tf(n,{destination:this.destination})),this.relaunch=r.relaunch||(()=>this.run("/usr/bin/open",["-a",this.destination])),this.statePath=G(this.root,"application-state.json")}async state(){try{return JSON.parse(await Rf(this.statePath,"utf8"))}catch(e){if(e.code==="ENOENT")return null;throw e}}async assertReady(e,r){let n=await this.inspect(e);if(ne(n,r),Lt(this.destination)){let i=await this.inspect(this.destination);if(ne(i,null,n.team_id),await this.running(this.destination)&&!(await this.applicationRequest("status").catch(()=>null))?.idle)throw Te("application_busy","InterScale has active sessions or cannot prepare its update yet")}}async apply(e,{version:r,health:n=a(async()=>!0,"health")}={}){let i=_e(G(this.root,"application.lock"));try{return await this.applyUnlocked(e,{version:r,health:n})}finally{i()}}async applyUnlocked(e,{version:r,health:n=a(async()=>!0,"health")}={}){await Vc(this.root,{recursive:!0,mode:448});let i=await this.state();if(i&&!["succeeded","rolled_back","failed"].includes(i.state))throw Te("application_update_unresolved","Reconcile the interrupted application update before replacing it");let s=await this.inspect(e);ne(s,r),await Yc(e);let o=Lt(this.destination)?await this.inspect(this.destination):null,c=!1;if(o){if(await Yc(this.destination),ne(o),o.team_id!==s.team_id)throw Te("application_publisher_mismatch","The new application must have the installed publisher identity");if(await this.running(this.destination)){if(!(await this.applicationRequest("quit").catch(()=>null))?.idle)throw Te("application_busy","InterScale has active sessions; its application update is deferred");let _=Date.now()+5e3;for(;await this.running(this.destination);){if(Date.now()>=_)throw Te("application_busy","InterScale has not finished closing; its update is deferred");await new Promise(g=>setTimeout(g,100))}c=!0}}let l=pE(),d=G(this.root,l);await Vc(d,{mode:448});let u=G(di(this.destination),`.interscale-stage-${l}`),h=G(di(this.destination),`.interscale-retired-${l}`),f=o?G(d,"previous.tar"):null,p={schema:"interscale.application-update/v1",id:l,destination:this.destination,stage:u,retired:h,backup:f,previous:o,target:s,relaunch:c,state:"preparing",created_at:Date.now()};this.write(p),Ae(G(d,"transaction.json"),p);try{if(await dE(e,u,{recursive:!0,verbatimSymlinks:!0,errorOnExist:!0,force:!1}),ne(await this.inspect(u),r,s.team_id),f&&this.run("/usr/bin/tar",["-cf",f,"-C",this.destination,"."]),this.write({...p,state:"activating"}),o&&await ln(this.destination,h),await ln(u,this.destination),ne(await this.inspect(this.destination),r,s.team_id),await n()!==!0)throw Te("application_health_failed","Application health check failed");let m={...p,state:"succeeded",completed_at:Date.now()};this.write(m),await Ue(h,{recursive:!0,force:!0}),i?.id&&/^[a-f0-9-]{36}$/.test(i.id)&&i.id!==l&&await Ue(G(this.root,i.id),{recursive:!0,force:!0}),await this.cleanRollbackHistory(m);let _=await this.cleanDuplicates(s);return this.write({...m,cleanup:_}),c&&this.relaunch(),{...m,cleanup:_}}catch(m){if((await this.state())?.state==="succeeded")return{...await this.state(),cleanup_pending:!0};if(await this.recoverUnlocked().catch(()=>{}),c&&Lt(this.destination))try{this.relaunch()}catch{}throw m}}async recover(){let e=_e(G(this.root,"application.lock"));try{return await this.recoverUnlocked()}finally{e()}}async recoverUnlocked(){let e=await this.state();if(!e||["succeeded","rolled_back","failed"].includes(e.state))return e;if(this.validateReceipt(e),e.state==="rolling_back"){!Lt(this.destination)&&Lt(e.stage)&&Lt(e.retired)&&(ne(await this.inspect(e.stage),e.previous.version,e.previous.team_id),await ln(e.stage,this.destination));let n=await this.inspect(this.destination);if(n.version===e.previous.version){ne(n,e.previous.version,e.previous.team_id);let s={...e,state:"rolled_back",rolled_back_at:Date.now()};return this.write(s),await Ue(e.retired,{recursive:!0,force:!0}),await Ue(e.stage,{recursive:!0,force:!0}),s}ne(n,e.target.version,e.target.team_id),await Ue(e.stage,{recursive:!0,force:!0});let i={...e,state:"succeeded"};return this.write(i),i}Lt(e.retired)?(ne(await this.inspect(e.retired),e.previous?.version,e.previous?.team_id),Lt(this.destination)&&(ne(await this.inspect(this.destination),e.target.version,e.target.team_id),await Ue(this.destination,{recursive:!0})),await ln(e.retired,this.destination)):!e.previous&&e.state==="activating"&&Lt(this.destination)&&(ne(await this.inspect(this.destination),e.target.version,e.target.team_id),await Ue(this.destination,{recursive:!0})),await Ue(e.stage,{recursive:!0,force:!0});let r={...e,state:"failed",recovered_at:Date.now()};return this.write(r),r}async rollback(){let e=_e(G(this.root,"application.lock"));try{return await this.rollbackUnlocked()}finally{e()}}async rollbackUnlocked(){let e=await this.recoverUnlocked();if(e?.state==="rolled_back")return e;if(!e?.backup||e.state!=="succeeded")throw Te("application_rollback_unavailable","No previous application is retained");if(this.validateReceipt(e),await this.running(this.destination))throw Te("application_busy","Close Interscale before restoring its previous application");let r=e.stage;await Vc(r,{mode:448}),this.run("/usr/bin/tar",["-xf",e.backup,"-C",r]),ne(await this.inspect(r),e.previous.version,e.previous.team_id),this.write({...e,state:"rolling_back"}),await ln(this.destination,e.retired);try{await ln(r,this.destination),ne(await this.inspect(this.destination),e.previous.version,e.previous.team_id);let n={...e,state:"rolled_back",rolled_back_at:Date.now()};return this.write(n),await Ue(e.retired,{recursive:!0,force:!0}),n}catch(n){throw await this.recoverUnlocked(),n}}async cleanDuplicates(e){let r=[],n=[];for(let i of new Set(this.searchRoots.map(s=>Jc(s)))){let s;try{s=await xf(i,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")continue;n.push({path:i,reason:"unreadable"});continue}for(let o of s){let c=G(i,o.name);if(!(c===this.destination||!o.isDirectory()||!o.name.endsWith(".app")))try{if(this.candidateIdentifier&&await this.candidateIdentifier(c)!==Kc)continue;let l=await this.inspect(c);if(l.identifier!==Kc||!l.signed||l.team_id!==e.team_id)continue;if(mE(l.version,e.version)>0){n.push({path:c,reason:"newer_version"});continue}if(await this.running(c)){n.push({path:c,reason:"running"});continue}await Yc(c),ne(await this.inspect(c),l.version,e.team_id),await Ue(c,{recursive:!0}),r.push(c)}catch{n.push({path:c,reason:"unverified_or_unwritable"})}}}return{removed:r,skipped:n}}async cleanRollbackHistory(e){for(let r of await xf(this.root,{withFileTypes:!0})){if(!r.isDirectory()||r.name===e.id||!/^[a-f0-9-]{36}$/.test(r.name))continue;let n=G(this.root,r.name);try{let i=JSON.parse(await Rf(G(n,"transaction.json"),"utf8"));if(this.validateReceipt(i),i.id!==r.name||i.schema!==e.schema||i.target?.team_id!==e.target.team_id)continue;await Ue(n,{recursive:!0})}catch{}}}validateReceipt(e){if(!/^[a-f0-9-]{36}$/.test(e.id)||e.destination!==this.destination||e.stage!==G(di(this.destination),`.interscale-stage-${e.id}`)||e.retired!==G(di(this.destination),`.interscale-retired-${e.id}`)||e.backup&&e.backup!==G(this.root,e.id,"previous.tar"))throw Te("application_receipt_invalid","Application transaction paths do not match this installation")}write(e){Ae(this.statePath,{...e,updated_at:Date.now()})}};async function kf(t){let e=JSON.parse(dn("/usr/bin/plutil",["-convert","json","-o","-",G(t,"Contents","Info.plist")]).stdout);dn("/usr/bin/codesign",["--verify","--deep","--strict",t]);let r=dn("/usr/bin/codesign",["-dv","--verbose=4",t]),n=r.stderr.match(/^TeamIdentifier=([A-Z0-9]+)$/m)?.[1];return{identifier:e.CFBundleIdentifier,version:e.CFBundleShortVersionString,team_id:n||null,cdhash:r.stderr.match(/^CDHash=([a-f0-9]+)$/m)?.[1]||null,signed:!!(n&&/^Authority=Developer ID Application:/m.test(r.stderr))}}a(kf,"inspectMacApplication");function ne(t,e,r){if(!t?.signed||t.identifier!==Kc||!t.team_id||!/^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/.test(t.version)||e&&t.version!==e||r&&t.team_id!==r)throw Te("application_identity_invalid","Expected a signed InterScale application with the release version and publisher")}a(ne,"assertIdentity");async function Yc(t){if(!(await uE(t)).isDirectory())throw Te("application_path_invalid","Application must be a real directory, not a symlink")}a(Yc,"assertDirectory");function mE(t,e){let r=t.split(/[.+-]/).slice(0,3).map(Number),n=e.split(/[.+-]/).slice(0,3).map(Number);if(r.some(i=>!Number.isFinite(i)))return 1;for(let i=0;i<3;i++)if(r[i]!==n[i])return r[i]-n[i];return t===e?0:1}a(mE,"compareVersions");function _E(t){return dn("/bin/ps",["-axo","command="]).stdout.split(`
101
+ `).some(e=>e.includes(`${t}/Contents/MacOS/`))}a(_E,"macApplicationRunning");function dn(t,e){let r=fE(t,e,{encoding:"utf8",timeout:12e4,maxBuffer:4194304});if(r.error||r.status!==0)throw Te("application_command_failed",`${t} failed while verifying or replacing InterScale`);return r}a(dn,"run");ks();var kE=new Set(["succeeded","failed","rolled_back"]),OE=10*6e4,Ks=class{static{a(this,"UpdateCoordinator")}constructor(e,r={}){this.root=hi(e),this.statePath=T(this.root,"update-state.json"),this.run=r.run||$E,this.installService=r.installService||((n,i)=>Nf(n,["agent","install","--config",i,"--json"],this.run)),this.serviceStatus=r.serviceStatus||(n=>Nf(n,["agent","status","--json"],this.run)),this.processCommand=r.processCommand||Ef,this.slots=r.slots??process.platform==="win32",this.slotInUse=r.slotInUse||LE,this.assertDrained=r.assertDrained||(async()=>{}),this.applicationInstaller=r.applicationInstaller===void 0?process.platform==="darwin"?new Js(T(this.root,"application")):null:r.applicationInstaller}serviceRuns(e,r){let n=ME(e),i=n?this.processCommand(n):null;if(!i||!r?.app_root)return!1;let s=a(o=>process.platform==="win32"?o.toLowerCase():o,"fold");return[r.app_root,Be(r.app_root)?Xc(r.app_root):null].some(o=>o&&s(i).includes(s(T(o,"bin","interscale-agent.mjs"))))}async apply(e,{configPath:r,signal:n,previousRuntimeRoot:i}={}){let s=_e(T(this.root,"operation.lock"));try{return await this.applyUnlocked(e,{configPath:r,signal:n,previousRuntimeRoot:i})}finally{s()}}async applyUnlocked(e,{configPath:r,signal:n,previousRuntimeRoot:i}={}){if(e?.schema!=="interscale.update-preflight/v1"||e.state!=="ready_for_drain"||e.apply_authorized!==!1||!e.stage?.artifact_path)throw new R(409,"update_preflight_required","Apply requires a fresh verified update preflight");n?.throwIfAborted(),await If(this.root,{recursive:!0,mode:448});let s=await this.read();if(s&&!kE.has(s.state))throw Object.assign(new R(409,"update_in_progress","An update has an unresolved activation outcome"),{retryable:!1,next_action:"Run interscale update status and reconcile the current update before another apply."});await this.assertDrained(n),n?.throwIfAborted();let o=i?jE(i,e.plan.current_version,this.run):Af(),c=this.slots?NE(this.root,o,{inUse:this.slotInUse}):null,l=c||T(this.root,"releases",Lf(e.plan.release_id)),d=T(l,"expanded");await Or(d,{recursive:!0,force:!0}),await If(d,{recursive:!0,mode:448});let u={schema:"interscale.update-state/v1",release_id:e.plan.release_id,target_version:e.plan.target_version,artifact_sha256:e.stage.sha256,artifact_path:e.stage.artifact_path,previous:o,state:"preparing",phase:"extract",created_at:Date.now(),updated_at:Date.now(),error:null};Ae(T(l,"release-receipt.json"),{schema:"interscale.runtime-retention/v1",release_id:u.release_id,sha256:u.artifact_sha256}),this.write(u);let h;try{if(await IE(e.plan.artifact.package_format,e.stage.artifact_path,d,this.run),h=await BE(d,e.plan.target_version),c&&(h=await UE(h,c)),Zc(h,this.run)!==e.plan.target_version)throw new R(409,"update_build_mismatch","Extracted runtime version does not match the signed manifest");this.applicationInstaller&&(h.desktop_bundle=await Df(d))}catch(p){throw this.write({...u,state:"failed",phase:"extract",updated_at:Date.now(),error:Ys(p,"update_extraction_failed")}),p}if(await this.assertDrained(n),n?.throwIfAborted(),h.desktop_bundle)try{await this.applicationInstaller.assertReady(h.desktop_bundle,h.version)}catch(p){throw this.write({...u,target:h,state:"failed",phase:"preflight",updated_at:Date.now(),error:Ys(p,"application_not_ready")}),p}let f={...u,target:h,state:"running",phase:"activation",activation_started_at:Date.now(),updated_at:Date.now()};this.write(f);try{let p=await this.installService(h,r),m=await this.serviceStatus(h);if(!this.serviceRuns(m,h))throw new R(503,"update_health_failed","Agent service is not running from the activated release");let _=h.desktop_bundle?await this.applicationInstaller.apply(h.desktop_bundle,{version:h.version}):null;return f={...f,state:"succeeded",phase:"health",service:p,health:m,observed_version:h.version,application:_,heartbeat_deadline:Date.now()+12e4,completed_at:Date.now(),updated_at:Date.now(),error:null},this.write(f),Ae(T(this.root,"active-runtime.json"),h),f}catch(p){throw f={...f,state:"needs_review",phase:"activation",updated_at:Date.now(),error:Ys(p,"update_activation_outcome_unknown"),next_action:"Run update status. If the target build is not healthy, run update rollback; do not automatically replay apply."},this.write(f),Object.assign(new R(409,"update_activation_outcome_unknown","Update activation may have changed the service and requires reconciliation"),{retryable:!1,next_action:f.next_action})}}async status(){let e;try{e=_e(T(this.root,"operation.lock"))}catch(r){if(r.code!=="update_in_progress")throw r;let n=await this.read();return{schema:"interscale.update-status/v1",state:n?.state||"idle",update:n,busy:!0}}try{return await this.statusUnlocked()}finally{e()}}async statusUnlocked(){let e=await this.read();if(!e)return{schema:"interscale.update-status/v1",state:"idle",update:null};if(["running","needs_review"].includes(e.state)&&e.phase==="activation"&&e.target)try{let r=await this.serviceStatus(e.target),n=e.target.desktop_bundle?await this.applicationInstaller?.state():null,i=!e.target.desktop_bundle||n?.state==="succeeded"&&n.target?.version===e.target_version;if(this.serviceRuns(r,e.target)&&i){let s={...e,state:"succeeded",phase:"health",observed_version:e.target_version,health:r,application:n,completed_at:e.completed_at||Date.now(),updated_at:Date.now(),error:null};return this.write(s),Ae(T(this.root,"active-runtime.json"),e.target),{schema:"interscale.update-status/v1",state:s.state,update:s}}}catch{}return{schema:"interscale.update-status/v1",state:e.state,update:e}}async rollback({configPath:e,signal:r}={}){let n=_e(T(this.root,"operation.lock"));try{return await this.rollbackUnlocked({configPath:e,signal:r})}finally{n()}}async rollbackUnlocked({configPath:e,signal:r}={}){let n=await this.read();if(!n?.previous||!["succeeded","needs_review","running"].includes(n.state))throw new R(409,"update_rollback_unavailable","No applied or uncertain update has a retained previous runtime");await this.assertDrained(r);let i=Zc(n.previous,this.run);if(i!==n.previous.version)throw new R(409,"rollback_build_mismatch","Retained previous runtime no longer matches its recorded version");let s={...n,state:"running",phase:"rollback",rollback_started_at:Date.now(),updated_at:Date.now()};this.write(s);try{if(n.target?.desktop_bundle&&this.applicationInstaller){let d=await this.applicationInstaller.recover();d?.state==="succeeded"&&d.target?.version===n.target_version?await this.applicationInstaller.rollback():await this.applicationInstaller.recover()}let o=await this.installService(n.previous,e),c=await this.serviceStatus(n.previous);if(!this.serviceRuns(c,n.previous))throw new Error("Previous agent service is not running from the retained runtime");let l={...s,state:"rolled_back",phase:"health",rollback_service:o,rollback_health:c,observed_version:i,rolled_back_at:Date.now(),updated_at:Date.now(),error:null};return this.write(l),Ae(T(this.root,"active-runtime.json"),n.previous),l}catch(o){let c={...s,state:"needs_review",updated_at:Date.now(),error:Ys(o,"rollback_outcome_unknown"),next_action:"Inspect the local agent service and retained runtimes; do not replay rollback until the active build is known."};throw this.write(c),Object.assign(new R(409,"rollback_outcome_unknown","Rollback outcome requires review"),{retryable:!1,next_action:c.next_action})}}async read(){if(!Be(this.statePath))return null;let e=await bE(this.statePath);if(!e.isFile()||e.size<2||e.size>256*1024)throw new R(409,"update_state_invalid","Update state receipt is invalid");let{readFile:r}=await import("node:fs/promises");try{return JSON.parse(await r(this.statePath,"utf8"))}catch{throw new R(409,"update_state_invalid","Update state receipt is invalid")}}async cleanup(){let e=_e(T(this.root,"operation.lock"));try{let r=await this.read();if(r?.state!=="succeeded"||!r.hub_health_verified_at)return{deferred:!0};let n=[r.target?.app_root,r.previous?.app_root,Af().app_root].filter(Boolean),i=T(this.root,"releases"),s=[];if(!Be(i))return{removed:s};for(let c of await Zs(i,{withFileTypes:!0})){if(!c.isDirectory())continue;let l=T(i,c.name);if(!n.some(d=>Ir(l,d)))try{let{readFile:d}=await import("node:fs/promises"),u=JSON.parse(await d(T(l,"release-receipt.json"),"utf8"));if(u.schema!=="interscale.runtime-retention/v1"||c.name!==Lf(u.release_id)||!/^[a-f0-9]{64}$/.test(u.sha256))continue;await Or(l,{recursive:!0}),s.push(l)}catch{}}let o=r.target?.desktop_bundle;return o&&Ir(i,o)&&!n.some(c=>Ir(c,o))&&await Or(o,{recursive:!0,force:!0}),{removed:s}}finally{e()}}async recoverPreparation(){let e=_e(T(this.root,"operation.lock"));try{let r=await this.read();r?.state==="preparing"&&this.write({...r,state:"failed",error:{code:"update_preparation_interrupted"},updated_at:Date.now()})}finally{e()}}async recordHubHealth(e){let r=_e(T(this.root,"operation.lock"));try{let n=await this.read();n?.state==="succeeded"&&n.release_id===e&&!n.hub_health_verified_at&&this.write({...n,hub_health_verified_at:Date.now()})}finally{r()}}write(e){Ae(this.statePath,e)}};async function Df(t,e=0){if(e>6)return null;for(let r of await Zs(t,{withFileTypes:!0})){if(!r.isDirectory())continue;let n=T(t,r.name);if(r.name==="Applications"&&Be(T(n,"Interscale.app","Contents","Info.plist")))return T(n,"Interscale.app");if(["app","node","node_modules"].includes(r.name)||r.name.endsWith(".app"))continue;let i=await Df(n,e+1);if(i)return i}return null}a(Df,"findDesktopBundle");async function IE(t,e,r,n){let i=AE(t,e,r);return i.removeDestination&&await Or(r,{recursive:!0,force:!0}),n(i.program,i.args)}a(IE,"extractPackage");function AE(t,e,r,{systemRoot:n=process.env.SystemRoot||"C:\\Windows"}={}){if(t==="pkg")return{program:"/usr/sbin/pkgutil",args:["--expand-full",e,r],removeDestination:!0};if(t==="deb")return{program:"dpkg-deb",args:["-x",e,r]};if(t==="tar.gz")return{program:"tar",args:["-xzf",e,"-C",r,"--no-same-owner","--no-same-permissions"]};if(t==="zip")return{program:xE.join(n,"System32","tar.exe"),args:["-xf",e,"-C",r]};throw new R(400,"release_target_unsupported",`Unsupported package format: ${t}`)}a(AE,"packageExtractionCommand");var Xs=["a","b","c"];function NE(t,e,{inUse:r=a(()=>!1,"inUse")}={}){let n=T(t,"slots"),i=DE(t,e);if(!r(i))return i;let s=Xs.find(c=>e?.app_root&&Ir(T(n,c),e.app_root));return Xs.map(c=>T(n,c)).find(c=>c!==i&&(!s||c!==T(n,s))&&!r(c))||i}a(NE,"inactiveSlot");function LE(t){if(process.platform!=="win32")return!1;let e=T(t,"runtime");if(!Be(e))return!1;if(Uf(e))return!0;let r=`${e}.in-use-check`;try{Of(e,r)}catch{return!0}try{Of(r,e)}catch{}return!1}a(LE,"slotInUse");function Uf(t){if(process.platform!=="win32")return!1;try{return gE(yE(T(t,"node","node.exe"),"r+")),!1}catch(e){return e.code!=="ENOENT"}}a(Uf,"nodeRunning");async function CE(t){let e=T(t,"runtime");Be(e)&&await Cf(e,T(t,`retired-${Date.now()}`)),await Or(`${e}.in-use-check`,{recursive:!0,force:!0})}a(CE,"retireSlotRuntime");async function PE(t){for(let e of Xs){let r=T(t,e);for(let n of Be(r)?await Zs(r):[])!n.startsWith("retired-")||Uf(T(r,n))||await Or(T(r,n),{recursive:!0,force:!0}).catch(()=>{})}}a(PE,"removeRetiredRuntimes");function DE(t,e){let r=T(t,"slots"),n=Xs.find(l=>e?.app_root&&Ir(T(r,l),e.app_root));if(n==="a"||n==="b")return T(r,n==="a"?"b":"a");let i=a(l=>{try{return JSON.parse(wE(T(r,l,"runtime","app","package.json"),"utf8")).version.split(".").map(Number)}catch{return null}},"version"),[s,o]=[i("a"),i("b")];if(!s||!o)return T(r,s?"b":"a");let c=s.findIndex((l,d)=>l!==o[d]);return T(r,c>=0&&s[c]>o[c]?"b":"a")}a(DE,"preferredSlot");async function UE(t,e){let r=T(e,"runtime");await CE(e),await Cf(ui(t.app_root),r),await Or(T(e,"expanded"),{recursive:!0,force:!0}),await PE(ui(e));let n=Pf(ui(t.app_root),t.node);return{...t,node:T(r,n),cli:T(r,"app","bin","interscale.mjs"),app_root:T(r,"app")}}a(UE,"settleSlotRuntime");async function BE(t,e){let r=[];if(await n(t,0),r.length!==1)throw new R(409,"update_runtime_ambiguous","Extracted package does not contain one exact Interscale runtime");return r[0];async function n(i,s){if(!(s>10||r.length>1))for(let o of await Zs(i,{withFileTypes:!0})){let c=T(i,o.name);if(o.isSymbolicLink()){let l=await vE(c);if(!Ir(t,l))throw new R(409,"update_archive_escape","Extracted package contains a symlink outside its private release root");continue}if(o.isDirectory()){if(o.name==="app"&&Be(T(c,"package.json"))&&Be(T(c,"bin","interscale.mjs"))){let l=ui(c),d=process.platform==="win32"?T(l,"node","node.exe"):T(l,"node","bin","node");if(Be(d)){let{readFile:u}=await import("node:fs/promises");JSON.parse(await u(T(c,"package.json"),"utf8")).version===e&&r.push({node:d,cli:T(c,"bin","interscale.mjs"),app_root:c,version:e})}}await n(c,s+1)}}}}a(BE,"locateRuntime");function Af(){let t=hi(ui(RE(import.meta.url)),"..");return{node:process.execPath,cli:T(t,"bin","interscale.mjs"),app_root:t,version:Vn}}a(Af,"currentRuntime");function jE(t,e,r){let n=Xc(hi(t)),i=T(n,"app"),s={node:process.platform==="win32"?T(n,"node","node.exe"):T(n,"node","bin","node"),cli:T(i,"bin","interscale.mjs"),app_root:i,version:e};for(let c of[s.node,s.cli,T(i,"package.json")])if(!Be(c)||!Ir(n,Xc(c)))throw new R(409,"rollback_runtime_invalid","The retained previous runtime is incomplete or escapes its retention root");if(Zc(s,r)!==e)throw new R(409,"rollback_build_mismatch","The retained previous runtime does not match the installed version being upgraded");return s}a(jE,"retainedRuntime");function Zc(t,e){return String(e(t.node,[t.cli,"version"]).stdout||"").trim()}a(Zc,"runtimeVersion");function ME(t){let e=t?.service||t||{},r=e.detail,n=Number(e.pid??r?.pid??(typeof r=="string"?r.match(/\bMainPID=(\d+)/)?.[1]:null));return Number.isSafeInteger(n)&&n>0?n:null}a(ME,"servicePid");function Nf(t,e,r){let n=r(t.node,[t.cli,...e]);try{return JSON.parse(n.stdout)}catch{return{loaded:n.status===0,output:n.stdout.trim()}}}a(Nf,"runRuntime");function $E(t,e){let r=EE(t,e,{encoding:"utf8",windowsHide:!0,timeout:OE,maxBuffer:4194304});if(r.error)throw r.error;if(r.status!==0)throw Object.assign(new Error(`${t} failed (${r.status}): ${(r.stderr||r.stdout).trim()}`),{code:"update_command_failed"});return{status:r.status,stdout:r.stdout||"",stderr:r.stderr||""}}a($E,"runCommand");function Ir(t,e){let r=Pf(hi(t),hi(e));return r===""||!r.startsWith("..")&&!TE(r)}a(Ir,"inside");function Lf(t,e=process.platform){let r=qE(t);return e==="win32"?`r-${SE("sha256").update(r).digest("hex").slice(0,24)}`:r}a(Lf,"updateReleaseDirectoryName");function qE(t){if(typeof t!="string"||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/.test(t))throw new R(400,"invalid_release_manifest","Unsafe release identity");return t}a(qE,"safeSegment");function Ys(t,e){return{code:String(t?.code||e).slice(0,200),message:String(t?.message||"Update failed").slice(0,2e3),retryable:t?.retryable===!0,next_action:t?.next_action||null}}a(Ys,"publicFailure");le();import{createHash as $f,randomUUID as FE}from"node:crypto";import{createReadStream as zE,existsSync as WE,rmSync as Bf}from"node:fs";import{link as HE,lstat as qf,open as GE,readFile as VE,unlink as JE}from"node:fs/promises";import{join as Ar,resolve as YE}from"node:path";He();Ss();var Qs=class{static{a(this,"UpdateStager")}constructor(e,r={}){this.root=YE(e),this.fetch=r.fetch||globalThis.fetch,pt(this.root)}async stage(e,r,n={}){let i=Hc(e,r,n);if(i.state==="no_change")return{schema:"interscale.update-stage/v1",state:"no_change",plan:i,receipt:null};let s=Ar(this.root,Mf(i.release_id));pt(s);let o=Ar(s,i.artifact.file_name),c=Ar(s,"stage-receipt.json");if(WE(o)){let d=await Qc(o,n.signal);if(d.size!==i.artifact.size||d.sha256!==i.artifact.sha256)throw new R(409,"release_staged_artifact_mismatch","Existing staged artifact does not match the signed release");let u=jf(i,o,c,!0);return Bn(c,u),{schema:"interscale.update-stage/v1",state:"verified",plan:i,receipt:u}}let l=Ar(s,`.${i.artifact.file_name}.${FE()}.partial`);try{let d=await this.fetch(i.artifact.url,{method:"GET",redirect:"error",headers:{"accept-encoding":"identity"},signal:n.signal});if(!d?.ok||!d.body)throw new R(502,"release_download_failed",`Release download failed with HTTP ${d?.status||"unknown"}`);let u=d.headers?.get?.("content-length");if(u!=null&&u!==""&&(!/^\d+$/.test(u)||!Number.isSafeInteger(Number(u))||Number(u)!==i.artifact.size))throw new R(409,"release_artifact_size_mismatch","Release Content-Length does not match the signed manifest");let h=await GE(l,"wx",384),f=$f("sha256"),p=0;try{for await(let y of d.body){n.signal?.throwIfAborted();let w=Buffer.from(y);if(p+=w.length,p>i.artifact.size)throw new R(409,"release_artifact_size_mismatch","Release download exceeds the signed byte size");f.update(w),await h.write(w)}await h.sync()}finally{await h.close()}let m=f.digest("hex");if(p!==i.artifact.size)throw new R(409,"release_artifact_size_mismatch","Release download is shorter than the signed byte size");if(m!==i.artifact.sha256)throw new R(409,"release_artifact_hash_mismatch","Release download does not match the signed SHA-256");let _=!1;try{await HE(l,o),await JE(l)}catch(y){if(y?.code!=="EEXIST")throw y;let w=await Qc(o,n.signal);if(w.size!==i.artifact.size||w.sha256!==i.artifact.sha256)throw new R(409,"release_staged_artifact_mismatch","Concurrent staged artifact does not match the signed release");_=!0,Bf(l,{force:!0})}let g=jf(i,o,c,_);return Bn(c,g),{schema:"interscale.update-stage/v1",state:"verified",plan:i,receipt:g}}catch(d){throw Bf(l,{force:!0}),d}}async preflight(e,r,n={}){let i=Hc(e,r,n);if(i.state==="no_change")return{schema:"interscale.update-preflight/v1",state:"no_change",plan:i,stage:null,apply_authorized:!1};let s=Ar(this.root,Mf(i.release_id)),o=Ar(s,i.artifact.file_name),c=Ar(s,"stage-receipt.json"),l=await KE(c);XE(l,i,o,c);let d;try{d=await Qc(o,n.signal)}catch(u){throw u?.code==="ENOENT"?new R(409,"release_staged_artifact_missing","The verified staged artifact is missing"):u}if(d.size!==i.artifact.size||d.sha256!==i.artifact.sha256)throw new R(409,"release_staged_artifact_mismatch","Staged artifact no longer matches the signed release");return{schema:"interscale.update-preflight/v1",state:"ready_for_drain",plan:{...i,gates:{...i.gates,artifact_hash:"verified"}},stage:{artifact_path:o,receipt_path:c,size:d.size,sha256:d.sha256,staged_at:l.verified_at,reverified_at:Date.now()},apply_authorized:!1,next_action:"Drain this node at a safe operation boundary before authorizing any package activation."}}};function jf(t,e,r,n){return{schema:"interscale.update-stage-receipt/v1",release_id:t.release_id,target_version:t.target_version,key_id:t.key_id,artifact:{platform:t.artifact.platform,arch:t.artifact.arch,package_format:t.artifact.package_format,file_name:t.artifact.file_name,size:t.artifact.size,sha256:t.artifact.sha256,node_runtime_version:t.artifact.node_runtime_version,compatibility:t.artifact.compatibility},artifact_path:e,receipt_path:r,reused:n,verified_at:Date.now(),apply_authorized:!1}}a(jf,"stageReceipt");async function Qc(t,e){let r=await qf(t);if(!r.isFile())throw new R(409,"release_staged_artifact_mismatch","Staged artifact is not a regular file");let n=$f("sha256");for await(let i of zE(t))e?.throwIfAborted(),n.update(i);return{size:r.size,sha256:n.digest("hex")}}a(Qc,"hashFile");async function KE(t){let e;try{e=await qf(t)}catch(r){throw r?.code==="ENOENT"?new R(409,"release_stage_receipt_missing","The signed release has no local staging receipt"):r}if(!e.isFile()||e.size<2||e.size>64*1024)throw new R(409,"release_stage_receipt_invalid","The local staging receipt is invalid");try{return JSON.parse(await VE(t,"utf8"))}catch{throw new R(409,"release_stage_receipt_invalid","The local staging receipt is invalid")}}a(KE,"readStageReceipt");function XE(t,e,r,n){let i={platform:e.artifact.platform,arch:e.artifact.arch,package_format:e.artifact.package_format,file_name:e.artifact.file_name,size:e.artifact.size,sha256:e.artifact.sha256,node_runtime_version:e.artifact.node_runtime_version,compatibility:e.artifact.compatibility};if(!t||t.schema!=="interscale.update-stage-receipt/v1"||t.release_id!==e.release_id||t.target_version!==e.target_version||t.key_id!==e.key_id||Jt(t.artifact)!==Jt(i)||t.artifact_path!==r||t.receipt_path!==n||t.apply_authorized!==!1||!Number.isSafeInteger(t.verified_at)||t.verified_at<1||typeof t.reused!="boolean")throw new R(409,"release_stage_receipt_invalid","The local staging receipt does not match the signed release plan")}a(XE,"validateStageReceipt");function Mf(t){if(typeof t!="string"||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/.test(t))throw new R(400,"invalid_release_manifest","release_id must be safe for private staging");return t}a(Mf,"safeSegment");async function Yf(t={}){let e=t.input||process.stdin,r=t.output||process.stdout,n=t.client||null;if(!n)try{let y=(t.loadProfile||Zh)();n=new ci(y.server_url,y.fleet_key)}catch(y){n=mS(y)}e.setEncoding("utf8");let i={client:n,env:t.env||process.env,mailbox:{},workerServerUrl:a(()=>t.workerServerUrl||Vs(Mn()).server_url,"workerServerUrl")},s=new Map,o={work:[],control:[]},c={work:0,control:0},l={work:8,control:4},d=new Set,u=!1,h=a(y=>{for(let w of s.values())w.abort.abort(y)},"abortPending"),f=a(y=>{u=!0,h(y),e.destroy?.(y)},"outputError");r.on?.("error",f);let p=a(y=>{y&&!u&&!r.destroyed&&!r.writableEnded&&r.write(`${JSON.stringify(y)}
102
+ `)},"write"),m=a(y=>{for(;c[y]<l[y]&&o[y].length;){let w=o[y].shift();c[y]+=1;let x=(async()=>{let v=w.request.params?._meta?.progressToken;try{w.abort.signal.throwIfAborted(),v!==void 0&&p({jsonrpc:"2.0",method:"notifications/progress",params:{progressToken:v,progress:0,total:1}}),p(await zf(w.request,{...i,signal:w.abort.signal})),v!==void 0&&p({jsonrpc:"2.0",method:"notifications/progress",params:{progressToken:v,progress:1,total:1}})}catch(k){p(to(w.request,k))}finally{s.delete(w.request.id),c[y]-=1,m(y)}})();d.add(x),x.then(()=>d.delete(x),()=>d.delete(x))}},"drain"),_=a(y=>{if(!y||Array.isArray(y)||y.jsonrpc!=="2.0"||typeof y.method!="string"){p({jsonrpc:"2.0",id:null,error:{code:-32600,message:"Invalid JSON-RPC request"}});return}if(y.method==="notifications/cancelled"){let v=s.get(y.params?.requestId);if(!v)return;let k=Object.assign(new Error("Request cancelled; reconcile any submitted operation before retrying"),{code:"request_cancelled"});v.abort.abort(k);let B=o[v.lane].indexOf(v);B!==-1&&(o[v.lane].splice(B,1),s.delete(v.request.id),p(to(v.request,k)));return}if(y.id===void 0||y.method.startsWith("notifications/"))return;if(!(typeof y.id=="string"||typeof y.id=="number"&&Number.isFinite(y.id))){p({jsonrpc:"2.0",id:null,error:{code:-32600,message:"Request ID must be a string or finite number"}});return}if(s.has(y.id)){p({jsonrpc:"2.0",id:y.id,error:{code:-32600,message:"Request ID already active"}});return}if(y.method!=="tools/call"){let v=zf(y,i).then(p).catch(k=>p(to(y,k)));d.add(v),v.then(()=>d.delete(v),()=>d.delete(v));return}let w=/_(status|cancel)$/.test(y.params?.name||"")?"control":"work";if(o[w].length>=64){p(to(y,new Error("MCP request queue is full; retry later")));return}let x={request:y,lane:w,abort:new AbortController};s.set(y.id,x),o[w].push(x),m(w)},"dispatch"),g="";try{for await(let y of e){for(g+=y;g.includes(`
103
+ `);){let w=g.indexOf(`
104
+ `),x=g.slice(0,w).trim();if(g=g.slice(w+1),!x)continue;let v;if(Buffer.byteLength(x)>1024*1024)throw new Error("MCP request exceeds 1 MiB");try{v=JSON.parse(x)}catch{p({jsonrpc:"2.0",id:null,error:{code:-32700,message:"Invalid JSON"}});continue}_(v)}if(Buffer.byteLength(g)>1024*1024)throw new Error("MCP request exceeds 1 MiB")}}finally{for(h(Object.assign(new Error("MCP input closed; reconcile submitted operations before retrying"),{code:"mcp_disconnected"}));d.size;)await Promise.allSettled([...d]);i.mailbox.workerClient?.close?.(),r.off?.("error",f)}}a(Yf,"runMcpServer");function to(t,e){return t.method!=="tools/call"?{jsonrpc:"2.0",id:t.id??null,error:{code:-32e3,message:e.message}}:fi(t.id,{isError:!0,content:[{type:"text",text:e.message}],structuredContent:{error:{code:e.code||"tool_failed",message:e.message,..._i(e)}}})}a(to,"toolError");async function zf(t,e){if(t.method==="notifications/initialized"||t.method?.startsWith("notifications/"))return null;if(t.method==="initialize")return fi(t.id,{protocolVersion:t.params?.protocolVersion||"2025-06-18",capabilities:{tools:{}},serverInfo:{name:"interscale",version:Vn},instructions:dS});if(t.method==="ping")return fi(t.id,{});if(t.method==="tools/list")return fi(t.id,{tools:tS().filter(r=>process.env.INTERSCALE_MCP_ALL_TOOLS==="1"||iS.has(r.function.name)||e.env?.INTERSCALE_RC_SESSION_ID&&sS.has(r.function.name)).map(r=>({name:r.function.name,description:r.function.description,inputSchema:r.function.parameters}))});if(t.method==="tools/call"){let r=t.params?.name,n=t.params?.arguments||{},i=Object.create(e.client);i.request=(o,c={})=>{e.signal?.throwIfAborted();let l=c.signal&&e.signal?AbortSignal.any([c.signal,e.signal]):c.signal||e.signal;return e.client.request(o,{...c,signal:l})};let s=await rS(i,r,n,e);return fi(t.id,{content:[{type:"text",text:JSON.stringify(s)}],structuredContent:s,...s?.[Kf]?{isError:!0}:{}})}return{jsonrpc:"2.0",id:t.id??null,error:{code:-32601,message:`Method not found: ${t.method}`}}}a(zf,"handleRequest");function tS(){let t=a((r={},n=[])=>({type:"object",properties:r,required:n,additionalProperties:!1}),"object"),e=a((r,n,i)=>({type:"function",function:{name:r,description:n,parameters:i}}),"tool");return[e("interscale_fleet_summary","Read a compact availability and load summary, without full machine inventories",t()),e("interscale_diagnostics","Read bounded hub and machine diagnostics for heartbeat, advertised routes, relay, file capabilities, and queues",t({node:{type:"string",maxLength:200}})),e("interscale_activity","Read one bounded, credential-free activity view across operations, transfers, jobs and desktop sessions; follow next_cursor with unchanged filters",t({node:{type:"string",maxLength:200},workspace:{type:"string",maxLength:200},operation:{type:"string",maxLength:200},kind:{type:"string",enum:["operation","transfer","job","desktop_session"]},status:{type:"string",enum:["open","terminal","all"]},limit:{type:"integer",minimum:1,maximum:200},cursor:{type:"string",maxLength:2048}})),e("interscale_desktop_doctor","Read bounded desktop host, permission and private-route readiness for one machine; this never starts capture or input",t({node:{type:"string",minLength:1,maxLength:200}},["node"])),e("interscale_desktop_status","Read one durable graphical desktop session and its terminal outcome; this never exposes media or input",t({session_id:{type:"string",minLength:1,maxLength:220}},["session_id"])),e("interscale_nodes","List computers (kind: machine=Mac/Windows, server=Linux); follow next_cursor. Details: capabilities and context",t({...Yt,kind:{type:"string",enum:["machine","server"]}})),e("interscale_node_archive_candidates","List offline stale machines and exact active-work blocker counts before any archival",t({stale_days:{type:"integer",minimum:7,maximum:3650},limit:{type:"integer",minimum:1,maximum:1e3}})),e("interscale_archived_nodes","List retained archived machine identities; archival preserves their operation history",t({limit:{type:"integer",minimum:1,maximum:1e3}})),e("interscale_node_archive","Archive one reviewed stale offline machine without deleting or merging history; requires fleet credentials and exact heartbeat compare-and-set",t({node:{type:"string",minLength:1,maxLength:200},expected_last_seen:{type:["integer","null"],minimum:0},stale_days:{type:"integer",minimum:7,maximum:3650},reason:{type:"string",minLength:1,maxLength:200},confirm:{type:"boolean",const:!0}},["node","expected_last_seen","reason","confirm"])),e("interscale_node_wake","Wake an offline machine through an opted-in LAN relay; a sent packet does not prove it woke",t({node:{type:"string",minLength:1,maxLength:200},request_id:{type:"string",minLength:1,maxLength:200},timeout_seconds:{type:"integer",minimum:15,maximum:600}},["node","request_id"])),e("interscale_wake_status","Read durable relay-send and target-heartbeat state for one Wake-on-LAN operation",t({operation_id:{type:"string",minLength:1,maxLength:200}},["operation_id"])),e("interscale_update_apply","Apply one signed release to the controller machine after exact artifact verification and a safe-boundary drain. Side-by-side activation retains the previous runtime; confirm must be true.",t({signed_release:{type:"string",minLength:1,maxLength:32768},public_key:{type:"string",minLength:1,maxLength:32768},config:{type:"string",minLength:1,maxLength:32768},staging_root:{type:"string",minLength:1,maxLength:32768},current_version:{type:"string",pattern:"^[0-9]+\\.[0-9]+\\.[0-9]+$"},allow_downgrade:{type:"boolean"},confirm:{type:"boolean",const:!0}},["signed_release","confirm"])),e("interscale_update_status","Read and reconcile the controller machine's durable side-by-side update state without replaying activation",t({staging_root:{type:"string",minLength:1,maxLength:32768}})),e("interscale_update_rollback","Rewire the controller machine to the retained previous runtime after a safe-boundary drain; confirm must be true",t({config:{type:"string",minLength:1,maxLength:32768},staging_root:{type:"string",minLength:1,maxLength:32768},confirm:{type:"boolean",const:!0}},["confirm"])),e("interscale_jobs","Browse job history newest first; follow next_cursor with the same node and state filters",t(Lh)),e("interscale_context","Inspect configured workspace aliases and machine locations without scanning or queuing a job",t({node:{type:"string"}},["node"])),e("interscale_workspaces","Page through every configured workspace; follow next_cursor and restart if workspace_list_changed",t({node:{type:"string"},...Yt},["node"])),e("interscale_inventory","Read one bounded stored inventory section; follow next_cursor, restarting if inventory_changed",t({node:{type:"string"},...Ph},["node","section"])),e("interscale_files_find","Search registered indexes (default); source live needs an explicit path and reports incomplete scans",t({node:{type:"string"},...Mh},["node","query"])),e("interscale_files_stat","Inspect an absolute path on a node without registering a library or queuing a job",t({node:{type:"string"},path:{type:"string"}},["node","path"])),e("interscale_files_list","List a directory without a job or index; follow next_cursor on the same path",t({node:{type:"string"},path:{type:"string"},limit:{type:"integer",minimum:1,maximum:1e3},cursor:{type:"string"}},["node","path"])),e("interscale_capabilities","Find hardware and software pages across machines; follow next_cursor with the same filters",t(Ch)),e("interscale_libraries","List a bounded library page; kind user excludes job outputs. Follow next_cursor with the same filters",t(Nh)),e("interscale_artifacts","Find registered files and locations; follow next_cursor using the same filters",t(Ih)),e("interscale_artifact","Inspect an artifact and its locations; follow next_locations_cursor with the same artifact",t(Ah,["artifact"])),e("interscale_transfers","List recent transfers with phase, route, queue reason, progress, verification and next action",t({node:{type:"string",maxLength:200},state:{type:"string",enum:["created","ready","receiving","uploading","uploaded","paused","completed","failed","cancel_requested","cancelled","needs_review"]},limit:{type:"integer",minimum:1,maximum:200}})),e("interscale_transfer_plan","Preflight a transfer between explicit paths on two nodes: route, reuse, capacity, bytes, recovery",t({source_node:{type:"string",minLength:1,maxLength:200},source_path:{type:"string",minLength:1,maxLength:32768},destination_node:{type:"string",minLength:1,maxLength:200},destination_path:{type:"string",minLength:1,maxLength:32768},overwrite:{type:"boolean"}},["source_node","source_path","destination_node","destination_path"])),e("interscale_transfer_start","Start one durable transfer between explicit paths on two nodes; reuse request_id to recover it",t({request_id:{type:"string",minLength:1,maxLength:200},source_node:{type:"string",minLength:1,maxLength:200},source_path:{type:"string",minLength:1,maxLength:32768},destination_node:{type:"string",minLength:1,maxLength:200},destination_path:{type:"string",minLength:1,maxLength:32768},overwrite:{type:"boolean"}},["request_id","source_node","source_path","destination_node","destination_path"])),e("interscale_transfer_status","Inspect one transfer's durable phase, destination progress, route wait and next action",t({transfer_id:{type:"string",minLength:1,maxLength:200}},["transfer_id"])),e("interscale_transfer_events","Read bounded durable transfer history after an event cursor",t({transfer_id:{type:"string",minLength:1,maxLength:200},since_seq:{type:"integer",minimum:0},limit:{type:"integer",minimum:1,maximum:1e3}},["transfer_id"])),e("interscale_transfer_pause","Pause a transfer after durable acknowledgement from both endpoints; verified partial chunks are retained",t({transfer_id:{type:"string",minLength:1,maxLength:200}},["transfer_id"])),e("interscale_transfer_resume","Resume a paused or interrupted transfer after both pause acknowledgements; controller uploads use the token interscale cp saved on this machine",t({transfer_id:{type:"string",minLength:1,maxLength:200}},["transfer_id"])),e("interscale_transfer_cancel","Request durable transfer cancellation; completion requires endpoint outcomes",t({transfer_id:{type:"string"}},["transfer_id"])),e("interscale_run","Run a command on a computer, waiting up to wait_seconds (default 45). command is a shell line (zsh -l on macOS, PowerShell on Windows); argv runs without a shell. Returns ok, state, exit_code, error and the last 8 KiB of output. Offline fails at once unless if_offline is queue. Reuse idempotency_key after an interruption",t({node:{type:"string",description:"Machine name, any case or a unique prefix"},command:{type:"string",minLength:1,maxLength:1048576},argv:{type:"array",items:{type:"string"},minItems:1},cwd:{type:"string",maxLength:4e3,description:"Absolute working directory on the machine"},env:{type:"object",additionalProperties:{type:"string"},description:"Extra environment variables for this job"},wait_seconds:{type:"integer",minimum:0,maximum:600},if_offline:{type:"string",enum:["fail","queue"]},inputs:{type:"array",maxItems:100,description:"Local files or folders copied into the job's directory first (no separate transfer). A git folder goes as git would commit it (no .git or ignored files) unless include_ignored",items:t({source:{type:"string",description:"Absolute local path"},path:{type:"string",description:"Relative destination in the job directory"},include_ignored:{type:"boolean"}},["source","path"])},result_directory:{type:"string",description:"Local directory for declared output files; requires outputs"},..._h,...Dh,...jh,timeout_seconds:{type:"integer",minimum:1,description:"Optional bound; by default none"},idempotency_key:{type:"string",minLength:1,maxLength:200},gpu:{type:"integer",minimum:0},exclusive:{type:"boolean"}},["node"])),e("interscale_job","Follow a job started by interscale_run: status, wait (up to wait_seconds, default 45), logs (from since_seq, up to 32 KiB) or cancel",t({job_id:{type:"string",minLength:1,maxLength:200},action:{type:"string",enum:["status","wait","logs","cancel"]},wait_seconds:{type:"integer",minimum:0,maximum:600},since_seq:{type:"integer",minimum:0}},["job_id"])),e("interscale_rc_start","Start a durable Claude Code or Codex session on a fleet machine, running there in cwd",t({node:{type:"string"},provider:{type:"string",enum:["claude","codex"],description:"Default: claude"},cwd:{type:"string"},permission_profile:{type:"string",enum:["full","workspace","read-only"]},model:{type:"string"},title:{type:"string"},parent_session_id:{type:"string",minLength:1,maxLength:200,description:"Default: your session or inbox"},root_task_id:{type:"string",minLength:1,maxLength:200},request_id:{type:"string",minLength:1,maxLength:200,description:"Reuse on retry: a repeat returns the original"},worktree:{type:"boolean",description:"Own git worktree and branch"}},["node","cwd"])),e("interscale_repo_preflight","Before copying or moving a git repository between machines: what git alone would not carry",t({node:{type:"string"},path:{type:"string"}},["node","path"])),e("interscale_rc_send","Send one turn to an rc session; returns the queued turn at once unless wait_seconds is set",t({session_id:{type:"string"},message:{type:"string"},wait_seconds:{type:"integer",minimum:1,maximum:600},request_id:{type:"string",minLength:1,maxLength:200,description:"Reuse on retry: a repeat returns the original"},reply_to:{type:"string",maxLength:200,description:"Question id to answer (no new turn)"}},["session_id","message"])),e("interscale_inbox","Wait for worker questions to you; answer with interscale_rc_send reply_to",t({address:{type:"string",maxLength:200},since_seq:{type:"integer",minimum:0},wait_seconds:{type:"integer",minimum:0,maximum:600}})),e("interscale_parent_ask","Ask the agent that started you a question and wait for its answer, mid-turn. Not answered yet: call again with the same request_id",t({question:{type:"string",minLength:1},wait_seconds:{type:"integer",minimum:1,maximum:600},request_id:{type:"string",minLength:1,maxLength:200}},["question"])),e("interscale_rc_wait","Wait for an rc session's next events (question, result, failure, state); returns on the first, else timed_out. Pass next_since_seq back as since_seq",t({session_id:{type:"string"},since_seq:{type:"integer",minimum:0},wait_seconds:{type:"integer",minimum:1,maximum:600}},["session_id"])),e("interscale_rc_history","Page through RC turn metadata and short message previews; fetch a selected turn for its full result",t({session_id:{type:"string"},limit:{type:"integer",minimum:1,maximum:1e3},cursor:{type:"string",maxLength:2048}},["session_id"])),e("interscale_rc_turn","Read one selected RC turn and its full result",t({session_id:{type:"string"},turn_id:{type:"string"}},["session_id","turn_id"])),e("interscale_rc_status","Read an rc session, its turns and their results",t({session_id:{type:"string"}},["session_id"])),e("interscale_rc_log","Read rc session events from a cursor (pass since_seq from the previous call)",t({session_id:{type:"string"},since_seq:{type:"integer",minimum:0}},["session_id"])),e("interscale_rc_cancel","Cancel an rc session's active and queued turns; the session stays usable",t({session_id:{type:"string"}},["session_id"])),e("interscale_term_list","List live terminals on a machine: tmux panes on macOS/Linux, named ConPTY sessions on Windows",t({node:{type:"string"}},["node"])),e("interscale_term_send","Type text or named keys (Enter, Escape, C-c) into a live terminal on a machine; target a tmux pane, or on Windows a session as name, name:0 or name:0.0",t({node:{type:"string"},target:{type:"string"},text:{type:"string"},keys:{type:"array",items:{type:"string"}},enter:{type:"boolean"}},["node","target"])),e("interscale_term_capture","Capture the screen text of a live tmux pane or Windows terminal session (kept in hub job logs)",t({node:{type:"string"},target:{type:"string"},lines:{type:"integer",minimum:1,maximum:1e4}},["node","target"]))]}a(tS,"controllerToolDefinitions");async function rS(t,e,r,n={}){if(e==="interscale_fleet_summary")return t.fleetSummary();if(e==="interscale_diagnostics")return t.diagnostics(r.node||null);if(e==="interscale_activity")return t.activity(r);if(e==="interscale_desktop_doctor")return t.desktopDoctor(r.node);if(e==="interscale_desktop_status")return t.desktopSession(r.session_id);if(e==="interscale_nodes"){let i=await t.nodes({view:"summary",limit:r.limit,cursor:r.cursor,kind:r.kind});return{...i,nodes:(i.nodes||[]).map(fS)}}if(e==="interscale_node_archive_candidates")return t.nodeArchiveCandidates({staleDays:r.stale_days,limit:r.limit});if(e==="interscale_archived_nodes")return t.archivedNodes({limit:r.limit});if(e==="interscale_node_archive")return t.archiveNode(r.node,{expectedLastSeen:r.expected_last_seen,staleDays:r.stale_days,reason:r.reason,confirm:r.confirm});if(e==="interscale_node_wake")return t.wakeNode(r.node,{requestId:r.request_id,timeoutSeconds:r.timeout_seconds});if(e==="interscale_wake_status")return t.wakeStatus(r.operation_id);if(["interscale_update_apply","interscale_update_status","interscale_update_rollback"].includes(e))return nS(t,e,r,n);if(e==="interscale_inventory")return t.nodeInventory(r.node,r);if(e==="interscale_workspaces")return t.listWorkspaces(r.node,r);if(e==="interscale_artifact")return t.artifact(r.artifact,{limit:r.limit,cursor:r.cursor});if(e==="interscale_context")return t.nodeContext(r.node);if(e==="interscale_files_find")return t.fileFind(r.node,r);if(e==="interscale_libraries")return t.libraries(r.node,r);if(e==="interscale_jobs")return t.jobs(r.limit,r);if(e==="interscale_files_stat")return t.fileStat(r.node,r.path);if(e==="interscale_files_list")return t.fileList(r.node,r.path,r);if(e==="interscale_capabilities")return t.capabilities(r);if(e==="interscale_artifacts")return t.artifacts({query:r.query,node:r.node,limit:r.limit,cursor:r.cursor,library:r.library,relativePath:r.relative_path});if(e==="interscale_transfers")return t.transfers(r);if(e==="interscale_transfer_plan")return t.planTransfer({node:r.source_node,path:r.source_path},{node:r.destination_node,path:r.destination_path},{overwrite:r.overwrite,signal:n.signal});if(e==="interscale_transfer_start")return t.startTransfer({node:r.source_node,path:r.source_path},{node:r.destination_node,path:r.destination_path},{requestId:r.request_id,overwrite:r.overwrite,signal:n.signal});if(e==="interscale_transfer_status")return t.transfer(r.transfer_id);if(e==="interscale_transfer_events")return t.transferEvents(r.transfer_id,{sinceSeq:r.since_seq,limit:r.limit});if(e==="interscale_transfer_pause")return t.pauseTransfer(r.transfer_id);if(e==="interscale_transfer_resume")return t.resumeTransfer(r.transfer_id,{token:Gd(r.transfer_id)});if(e==="interscale_transfer_cancel")return t.cancelTransfer(r.transfer_id);if(e==="interscale_run"){if(r.result_directory&&r.outputs===void 0)throw new Error("result_directory requires declared outputs");if(r.command===void 0==(r.argv===void 0))throw Object.assign(new Error("Give exactly one of command or argv"),{code:"invalid_run_request"});let i=await t.run(r.node,r.argv,{script:r.command,cwd:r.cwd,env:r.env,ifOffline:r.if_offline||"fail",inputs:r.inputs,signal:n.signal,timeoutSeconds:r.timeout_seconds,workspace:r.workspace,workspaceRevision:r.workspace_revision,cwdRelative:r.cwd_relative,environmentProfile:r.environment_profile,outputs:r.outputs,idempotencyKey:r.idempotency_key,gpu:r.gpu,exclusive:r.exclusive});try{let s=await Vf(t,i.job.id,r.wait_seconds??ro,n.signal),o=r.result_directory&&s.state==="succeeded"?await _c(t,s,r.result_directory,{signal:n.signal}):void 0;return{...await Jf(t,s,n.signal,r.node),...o?{results:o}:{}}}catch(s){throw n.signal?.aborted?Object.assign(new Error(`Stopped waiting; job ${i.job.id} keeps running. Follow it with interscale_job, or cancel it there`),{code:"wait_interrupted",job_id:i.job.id}):s}}if(e==="interscale_job"){let i=r.action||"status";if(i==="cancel"&&await t.cancel(r.job_id),i==="logs")return pS(t,r.job_id,r.since_seq||0,n.signal);let s=i==="wait"?await Vf(t,r.job_id,r.wait_seconds??ro,n.signal):(await t.job(r.job_id,{signal:n.signal})).job;return Jf(t,s,n.signal)}if(e==="interscale_rc_start"){let i=r.request_id||`mcp-${pi()}`,s=r.parent_session_id||n.env?.INTERSCALE_RC_SESSION_ID||await Hf(t,n)||void 0,o=r.worktree?await kh(t,r.node,r.cwd,{requestId:i,signal:n.signal}):null,c=await no(i,()=>t.createRcSession(r.node,{provider:r.provider,cwd:o?o.path:r.cwd,permissionProfile:r.permission_profile,model:r.model,title:r.title,parentSessionId:s,rootTaskId:r.root_task_id||(r.parent_session_id?void 0:n.env?.INTERSCALE_ROOT_TASK_ID)||void 0,requestId:i})),l=c?.session&&c.session.root_task_id===void 0;return{...c,request_id:i,...o?{worktree:o}:{},...l?{warning:"hub_without_lineage"}:{}}}if(e==="interscale_rc_send"&&r.reply_to){let i=r.request_id||`mcp-${pi()}`,s=el(t,n),o=s===t?Gf(n):void 0;return{...await no(i,()=>io(()=>s.sendMailboxMessage({to:r.session_id,replyTo:r.reply_to,kind:"reply",body:r.message,requestId:i,from:o,signal:n.signal}))),request_id:i}}if(e==="interscale_inbox"){let i=r.address||Gf(n)||await Hf(t,n,{required:!0}),s=Math.min(600,Math.max(0,Number(r.wait_seconds??ro)||0)),o=i===n.env?.INTERSCALE_RC_SESSION_ID?el(t,n):t,c=n.mailbox.cursors??={},l=r.since_seq===void 0?c[i]??0:Math.max(0,Number(r.since_seq)||0),d=Date.now()+s*1e3,u,h=[];do u=await io(()=>o.waitMailbox(i,{sinceSeq:l,timeoutMs:Math.max(0,d-Date.now()),signal:n.signal})),l=u.next_since_seq,h=u.messages.filter(p=>p.state!=="handled");while(!h.length&&u.messages.length&&Date.now()<d);c[i]=l;let f=h.map(hS);return{address:i,next_since_seq:l,timed_out:!f.length,has_more:!!u.has_more,messages:f,...f.some(p=>p.kind==="question")?{hint:"Answer: interscale_rc_send {session_id: <from>, reply_to: <id>, message}"}:{}}}if(e==="interscale_parent_ask"){let i=n.env?.INTERSCALE_RC_SESSION_ID;if(!i)throw Object.assign(new Error("interscale_parent_ask works inside a worker started by interscale_rc_start"),{code:"not_a_worker"});let s=r.request_id||`mcp-${pi()}`,o=el(t,n),{message:c}=await no(s,()=>io(()=>o.sendMailboxMessage({kind:"question",body:r.question,requestId:s,from:o===t?i:void 0,signal:n.signal}))),l=Math.min(600,Math.max(1,Number(r.wait_seconds)||oS)),d;try{d=await io(()=>o.waitMailbox(i,{sinceSeq:c.seq,replyTo:c.id,timeoutMs:l*1e3,signal:n.signal}))}catch(h){throw Object.assign(tl(h,s),{question_id:c.id,next_action:`Call interscale_parent_ask again with request_id ${s} to keep waiting; the question is not sent twice`})}let u=d.messages[0];return u?(await o.ackMailboxMessage(u.id,"handled").catch(()=>{}),{answered:!0,answer:u.body,from:u.from_address,question_id:c.id,request_id:s}):{answered:!1,question_id:c.id,request_id:s,...c.to_address?{}:{note:"You have no parent address: the question is in your session's event log for whoever follows it"},next_action:`Call interscale_parent_ask again with request_id ${s} to keep waiting; the question is not sent twice`}}if(e==="interscale_rc_send"){let i=r.request_id||`mcp-${pi()}`,s={...await no(i,()=>t.messageRcSession(r.session_id,r.message,{requestId:i})),request_id:i};if(!r.wait_seconds)return s;let o=new Set(["succeeded","failed","cancelled","needs_review"]),c=Date.now()+Math.min(600,r.wait_seconds)*1e3,l=s.turn;if(Number.isSafeInteger(l.event_seq)){let d=l.event_seq;for(;!o.has(l.state)&&Date.now()<c;){let u=await t.waitRcSession(r.session_id,{sinceSeq:d,timeoutMs:c-Date.now(),signal:n.signal});if(d=u.next_since_seq,u.timed_out||u.events.some(h=>h.type==="turn_state"&&h.payload?.turn_id===l.id&&o.has(h.payload.state)))break}}else for(;!o.has(l.state)&&Date.now()<c;)await new Promise(d=>setTimeout(d,1e3)),{turn:l}=await t.rcTurn(r.session_id,l.id);return{turn:l}=await t.rcTurn(r.session_id,l.id),{turn:l,complete:o.has(l.state),request_id:i}}if(e==="interscale_rc_wait"){let i=Math.min(600,Math.max(1,Number(r.wait_seconds)||ro));return t.waitRcSession(r.session_id,{sinceSeq:Math.max(0,Number(r.since_seq)||0),timeoutMs:i*1e3,signal:n.signal})}if(e==="interscale_repo_preflight")return Oh(t,r.node,r.path,{signal:n.signal});if(e==="interscale_rc_history")return t.rcTurns(r.session_id,r);if(e==="interscale_rc_turn")return t.rcTurn(r.session_id,r.turn_id);if(e==="interscale_rc_status")return t.rcSession(r.session_id);if(e==="interscale_rc_log")return t.rcSessionEvents(r.session_id,r.since_seq||0);if(e==="interscale_rc_cancel")return t.cancelRcSession(r.session_id);if(e==="interscale_term_list"){let{sessions:i}=await t.runTerminal(r.node,{op:"list"});return{sessions:i}}if(e==="interscale_term_send"){let i={op:"send",target:r.target};Array.isArray(r.keys)&&r.keys.length?i.keys=r.keys:(i.text=r.text,r.enter&&(i.enter=!0));let{sent:s}=await t.runTerminal(r.node,i);return{sent:s,target:r.target}}if(e==="interscale_term_capture"){let{text:i}=await t.runTerminal(r.node,{op:"capture",target:r.target,lines:r.lines});return{target:r.target,text:i}}throw new Error(`Unknown controller tool: ${e}`)}a(rS,"callControllerTool");async function nS(t,e,r,n){if(!r||typeof r!="object"||Array.isArray(r))throw Object.assign(new Error("Invalid update arguments"),{code:"invalid_update_request"});let i=e==="interscale_update_apply"?new Set(["signed_release","public_key","config","staging_root","current_version","allow_downgrade","confirm"]):e==="interscale_update_rollback"?new Set(["config","staging_root","confirm"]):new Set(["staging_root"]);if(Object.keys(r).some(m=>!i.has(m)))throw Object.assign(new Error("Update request contains unsupported fields"),{code:"invalid_update_request"});for(let m of["signed_release","public_key","config","staging_root"])if(r[m]!==void 0&&(typeof r[m]!="string"||!r[m].length||r[m].length>32768||r[m].includes("\0")))throw Object.assign(new Error(`Invalid ${m} path`),{code:"invalid_update_request"});let s=eo(r.staging_root||eS(W(),"updates")),o=eo(r.config||Mn()),c=new Ks(s,{assertDrained:a(async()=>{n.signal?.throwIfAborted();let m=Vs(o),_=await t.activity({node:m.node_id,status:"open",limit:10});if(_.summary.open>0)throw Object.assign(new Error(`Node has ${_.summary.open} open operation(s); update drain is not safe`),{code:"update_node_busy",retryable:!0,next_action:"Wait for active jobs, transfers and sessions to reach a safe boundary, then retry."})},"assertDrained")});if(e==="interscale_update_status")return c.status();if(r.confirm!==!0)throw Object.assign(new Error("Update mutation requires confirm=true"),{code:"update_confirmation_required"});if(e==="interscale_update_rollback")return c.rollback({configPath:o,signal:n.signal});let l=JSON.parse(await Ff(eo(r.signed_release),"utf8")),d=Vs(o),u=r.public_key?await Ff(eo(r.public_key),"utf8"):d.release_public_key;if(!u)throw Object.assign(new Error("No release verification key is pinned; provide public_key or pin one locally"),{code:"release_key_missing"});let h={currentVersion:r.current_version||Vn,configVersion:1,platform:QE(),arch:ZE(),allowDowngrade:r.allow_downgrade===!0,signal:n.signal},f=new Qs(s);await f.stage(l,u,h);let p=await f.preflight(l,u,h);return p.state==="no_change"?p:c.apply(p,{configPath:o,signal:n.signal})}a(nS,"localUpdateTool");function fi(t,e){return{jsonrpc:"2.0",id:t,result:e}}a(fi,"result");var iS=new Set(["interscale_fleet_summary","interscale_nodes","interscale_capabilities","interscale_context","interscale_run","interscale_job","interscale_jobs","interscale_files_list","interscale_files_stat","interscale_files_find","interscale_transfers","interscale_transfer_plan","interscale_transfer_start","interscale_transfer_status","interscale_transfer_cancel","interscale_node_wake","interscale_rc_start","interscale_rc_send","interscale_rc_wait","interscale_rc_status","interscale_rc_cancel","interscale_inbox","interscale_term_list","interscale_term_send","interscale_term_capture"]),sS=new Set(["interscale_parent_ask"]),Kf=Symbol("tool result failed"),ro=45,oS=300,Wf=2e3,aS=8*1024,cS=32*1024,lS=new Set(["succeeded","failed","cancelled","rejected","expired","needs_review"]),dS=`Interscale runs work on your own computers and computers explicitly shared with your account, some with NVIDIA GPUs. Macs and Windows PCs are machines; Linux hosts are servers.
105
+ - See the computers: interscale_nodes (kind, online, OS, GPUs; kind filters machines or servers) or interscale_fleet_summary.
106
+ - Run something: interscale_run {node, command}. command runs in the machine's login shell (zsh on macOS, PowerShell on Windows); pass cwd for an absolute working directory and env for extra variables. Computer names match in any case or by unique prefix.
107
+ - Local files or folders for the job: interscale_run {node, command, inputs: [{source: "/absolute/path/work", path: "work"}]} sends them into the job's directory first; no separate transfer is needed.
108
+ - Prefer these tools over the interscale command line: a sandboxed shell cannot read its credentials.
109
+ - interscale_run waits up to wait_seconds (default 45). Long jobs keep running: use interscale_job {job_id, action: "wait" | "status" | "logs" | "cancel"}.
110
+ - ok is false when the job failed; read exit_code, error.code, error.message and error.next_action before retrying.
111
+ - An offline computer fails at once with machine_offline; interscale_node_wake can wake one, or pass if_offline: "queue".
112
+ - Files: interscale_files_list / interscale_files_stat on a computer; interscale_transfer_start copies between computers.
113
+ - Claude Code or Codex on another computer: interscale_rc_start then interscale_rc_send; interscale_rc_wait waits for its next event instead of polling. A worker's questions arrive in interscale_inbox; answer with interscale_rc_send reply_to.
114
+ - interscale_nodes lists each computer's tools (Claude Code, Codex, Python, Git, FFmpeg...) and GPUs.`,uS=500;async function no(t,e){try{return await e()}catch(r){if(r?.code!=="outcome_unknown")throw tl(r,t);await new Promise(n=>setTimeout(n,uS));try{return await e()}catch(n){throw tl(n,t)}}}a(no,"withRequestRetry");async function Hf(t,e,{required:r=!1}={}){if(!e.env?.INTERSCALE_RC_SESSION_ID)try{return e.mailbox.requestId??=`mcp-inbox-${pi()}`,e.mailbox.pending??=t.registerMailbox({title:"main agent",requestId:e.mailbox.requestId}).then(({address:n})=>e.mailbox.address=n.id),await e.mailbox.pending}catch(n){if(e.mailbox.pending=void 0,!r)return;throw Xf(n)||n}}a(Hf,"ensureInbox");function Gf(t){return t.env?.INTERSCALE_RC_SESSION_ID||t.mailbox.address}a(Gf,"selfAddress");function el(t,e){let r=e.env?.INTERSCALE_RC_TOKEN;if(!r)return t;if(!e.mailbox.workerClient){let n=typeof e.client?.serverUrl=="string"?e.client.serverUrl:e.workerServerUrl();e.mailbox.workerClient=new ci(n,r)}return e.mailbox.workerClient}a(el,"mailboxClient");async function io(t){try{return await t()}catch(e){throw Xf(e)||e}}a(io,"withMailbox");function Xf(t){return t?.code!=="not_found"?null:Object.assign(new Error("This hub has no mailbox yet; deploy the hub from this release"),{code:"hub_without_mailbox",retryable:!1,next_action:"Until then, follow workers with interscale_rc_wait"})}a(Xf,"missingMailbox");function hS(t){let e=typeof t.body=="string"&&t.body.length>Wf;return{id:t.id,seq:t.seq,from:t.from_address,to:t.to_address,kind:t.kind,reply_to:t.reply_to,state:t.state,created_at:t.created_at,body:e?t.body.slice(0,Wf):t.body,...e?{body_truncated:!0}:{}}}a(hS,"compactMessage");function tl(t,e){return!t||typeof t!="object"||(t.request_id??=e,t.code==="outcome_unknown"&&(t.next_action??=`Retry with request_id ${e}: the hub returns what the first call created, never a duplicate`)),t}a(tl,"withRequestId");async function Vf(t,e,r,n){if(r>0){let i=AbortSignal.timeout(Math.min(600,r)*1e3);try{return await t.followJob(e,{signal:n?AbortSignal.any([n,i]):i})}catch(s){if(n?.aborted||!i.aborted)throw s}}return(await t.job(e,{signal:n})).job}a(Vf,"waitForJob");async function Jf(t,e,r,n){let i=lS.has(e.state),s=await t.logTail(e.id,aS,{signal:r}),o=e.result||{},c=e.state==="succeeded",l={ok:i?c:null,done:i,state:e.state,job_id:e.id,machine:n||e.target_node_id,...o.exit_code!==void 0?{exit_code:o.exit_code}:{},...o.signal?{signal:o.signal}:{},...i&&!c?{error:{code:o.code||(o.exit_code!==void 0?"exit_status":e.state),message:o.message||(o.exit_code!==void 0?`The command exited with status ${o.exit_code}`:`The job ended as ${e.state}`),...o.next_action?{next_action:o.next_action}:{}}}:{},output:s.logs.map(d=>d.text).join(""),output_truncated:s.truncated,next_since_seq:s.next_since_seq,...i?{}:{hint:`Still ${e.state}. Call interscale_job {job_id: "${e.id}", action: "wait"} to keep waiting.`}};return i&&!c&&(l[Kf]=!0),l}a(Jf,"jobSummary");async function pS(t,e,r,n){let i=await t.logs(e,{sinceSeq:r,limit:1e3,signal:n}),s="",o=r,c=!1;for(let l of i.logs||[]){if(Buffer.byteLength(s)+Buffer.byteLength(l.text)>cS){c=!0;break}s+=l.text,o=l.seq}return{job_id:e,output:s,next_since_seq:c?o:i.next_since_seq??o,more:c||!!i.has_more}}a(pS,"jobLogs");function fS(t){let e=t.capabilities||{},r=a(n=>Number.isFinite(n)?Math.round(n/1e9):null,"gigabytes");return{name:t.name,kind:t.kind||nl(t.platform),status:t.status,platform:t.platform,arch:e.arch||null,cpu:e.cpu_model?.trim()||null,cpu_threads:e.cpu_threads??null,memory_gb:r(e.memory_total_bytes),free_disk_gb:r(e.storage?.available_bytes),gpus:(e.gpus||[]).map(n=>[n.name,n.memory_bytes?`${r(n.memory_bytes)} GB`:null].filter(Boolean).join(" ")),tools:e.tools||[],active_jobs:e.active_job_count??null,agent_version:t.agent_version,last_seen:t.last_seen,id:t.id}}a(fS,"agentNodeView");function mS(t){let e=a(()=>Promise.reject(Object.assign(new Error(`This machine is not activated in Interscale: ${t.message}`),{code:"not_activated",retryable:!1,next_action:"Sign in to the Interscale app, or run: interscale login --server <hub> --email <email>"})),"fail");return new Proxy({},{get:a((r,n)=>n==="then"?void 0:e,"get")})}a(mS,"notActivated");Yf().catch(t=>{console.error(`interscale-mcp: ${t.message}`),process.exitCode=1});